@camstack/addon-admin-ui 1.2.428 → 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.
- package/dist/assets/{AddonAssetIcon-Cs_blBpK.js → AddonAssetIcon-DR35yt0E.js} +1 -1
- package/dist/assets/Addons-gkGgGpTC.js +4 -0
- package/dist/assets/{AdminPage-DuuyDIsY.js → AdminPage-DAO24U0w.js} +1 -1
- package/dist/assets/AdminSectionedPage-B-qoE6ra.js +1 -0
- package/dist/assets/AiProfiles-BXcreqZP.js +3 -0
- package/dist/assets/BrokerForm-B3xs9aBj.js +1 -0
- package/dist/assets/Build-DeMAJfjN.js +40 -0
- package/dist/assets/Calendars-VPH-vy-o.js +1 -0
- package/dist/assets/Cluster-B-k0M79z.js +1 -0
- package/dist/assets/ClusterStepModel-DaAc_6nI.js +1 -0
- package/dist/assets/CompositionEditor-BrtLjoSu.js +1 -0
- package/dist/assets/{CompositionEditorPage-Acq7iapA.js → CompositionEditorPage-D51jS9td.js} +1 -1
- package/dist/assets/Data-IfJuKcwc.js +2 -0
- package/dist/assets/DeviceDetail-D1qU_p1k.js +2 -0
- package/dist/assets/DeviceDoActionFields-B62Nv4K7.js +1 -0
- package/dist/assets/Devices-Cf5Exjsk.js +1 -0
- package/dist/assets/{EmbedPlayerPage-RXOmf2F3.js → EmbedPlayerPage-CnEcSJ8D.js} +1 -1
- package/dist/assets/Identity-DNE80jdX.js +1 -0
- package/dist/assets/IntegrationDetail-LKbiJFU3.js +1 -0
- package/dist/assets/IntegrationHub-DdjWEObX.js +1 -0
- package/dist/assets/Integrations-CU7Ll9U_.js +1 -0
- package/dist/assets/Integrations-uZB2ozhn.js +1 -0
- package/dist/assets/Library-DSuCaXt6.js +1 -0
- package/dist/assets/Locations-BeaznsZS.js +3 -0
- package/dist/assets/{Logs-DIeXeCqI.js → Logs-cm-1R2Z4.js} +1 -1
- package/dist/assets/MaskShapeCanvas-CM9D4FOf.js +1 -0
- package/dist/assets/MotionZonesSettings-DqS8ndiK.js +1 -0
- package/dist/assets/MyAccess-Dxb11B6h.js +2 -0
- package/dist/assets/Network-BCDUHSB0.js +1 -0
- package/dist/assets/NodeAddonsSettingsPanel-BMat4ckt.js +1 -0
- package/dist/assets/Notifications-EPQiEZ1t.js +1 -0
- package/dist/assets/PrivacyMaskSettings-Bis0PO01.js +1 -0
- package/dist/assets/Recordings-BCeoXxL4.js +1 -0
- package/dist/assets/ScanNetworkModal-dHWFmbFe.js +1 -0
- package/dist/assets/SceneMonitorEditor-SFMMIopn.js +1 -0
- package/dist/assets/SessionsList-BRTwG3uv.js +2 -0
- package/dist/assets/{Showroom-W2yJvb8s.js → Showroom-Er-hes9K.js} +1 -1
- package/dist/assets/System-BDXxfgsq.js +1 -0
- package/dist/assets/{Terminal-CrFum1tE.js → Terminal-B70jnm8e.js} +4 -4
- package/dist/assets/{Viewer-YBzeS3RA.js → Viewer-BsGL5Dfa.js} +1 -1
- package/dist/assets/_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-C7iEnSHU.js +1 -0
- 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
- 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
- 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
- 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
- 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
- package/dist/assets/{addon-icons-context-D6glxUQF.js → addon-icons-context--6Hi3qRW.js} +1 -1
- package/dist/assets/{archive-kvflMCgL.js → archive-DtcjevJM.js} +1 -1
- package/dist/assets/{authed-media-CSlndmzS.js → authed-media-LCmlAEZ5.js} +1 -1
- package/dist/assets/{bell-off-BYnwGeiH.js → bell-off-eQBpwamg.js} +1 -1
- package/dist/assets/board-model-wzCmdEKJ.js +1 -0
- package/dist/assets/{boxes-Dx4USyB3.js → boxes-DikDfAoo.js} +1 -1
- package/dist/assets/circle-slash-YVgGJTpJ.js +1 -0
- package/dist/assets/client-DYbvGOid.js +358 -0
- package/dist/assets/{cloud-upload-82x5w5u8.js → cloud-upload-DI9XunFf.js} +1 -1
- package/dist/assets/crop-CxZbpOyK.js +1 -0
- package/dist/assets/{device-integration-icon-bTnWrYe0.js → device-integration-icon-D2lWVDM2.js} +1 -1
- package/dist/assets/device-picker-model-C4w1vbly.js +1 -0
- package/dist/assets/dist-CPO0KWoy.js +358 -0
- package/dist/assets/dist-ChQzskeX.js +1 -0
- package/dist/assets/{eraser-B8Awx5Sj.js → eraser-Dl5ROV0l.js} +1 -1
- package/dist/assets/{file-up-LqDVgVVa.js → file-up-WS3s_T9x.js} +1 -1
- package/dist/assets/{hard-drive-download-C24D80x2.js → hard-drive-download-B1ard6ym.js} +1 -1
- package/dist/assets/{history-DZsORyBG.js → history-BMhP0SFG.js} +1 -1
- package/dist/assets/{hostInit-D2EmEDvv.js → hostInit-FCvre9AW.js} +1 -1
- package/dist/assets/i18n-Vb3uBp7P.js +1 -0
- package/dist/assets/{icons-D5RaCH1q.js → icons-DocdgFuy.js} +1 -1
- package/dist/assets/index-DKqvG7BE.css +2 -0
- package/dist/assets/index-DvOECbab.js +4 -0
- package/dist/assets/{key-DLwSBrPM.js → key-B1M6i1mf.js} +1 -1
- package/dist/assets/{key-round-CYflkUyd.js → key-round-yCDTbIQb.js} +1 -1
- package/dist/assets/{layers-C1wzFfr1.js → layers-c960YTPf.js} +1 -1
- package/dist/assets/linked-devices-model-CB7qgVjI.js +1 -0
- package/dist/assets/{list-ordered-CFeS9o_w.js → list-ordered-C7hEwAd1.js} +1 -1
- package/dist/assets/location-owned-usage-D28vwYJT.js +1 -0
- package/dist/assets/{log-in-Be_RcxDr.js → log-in-DFfxcqYz.js} +1 -1
- package/dist/assets/{memory-stick-4BwYEagi.js → memory-stick-BBfIGrWx.js} +1 -1
- package/dist/assets/{message-square-plus-D7BNG3h7.js → message-square-plus-D8ZUT6rz.js} +1 -1
- package/dist/assets/{mf-entry-bootstrap-0-9df0d08c.js → mf-entry-bootstrap-0-3035e647.js} +2 -2
- package/dist/assets/{mic-off-e162Bcfu.js → mic-off-w2mFOBi3.js} +1 -1
- package/dist/assets/{monitor-off-CARYfHC4.js → monitor-off-DPi_gm_c.js} +1 -1
- package/dist/assets/{monitor-smartphone-lsNgnRRZ.js → monitor-smartphone-9Ife1Trw.js} +1 -1
- package/dist/assets/mount-C4w1vbly.js +1 -0
- package/dist/assets/notification-schedule-field-BuLfSYLZ.js +1 -0
- package/dist/assets/{octagon-alert-h80nyWRM.js → octagon-alert-C-jH7VH_.js} +1 -1
- package/dist/assets/player-overlays-D0U2dNvn.js +1 -0
- package/dist/assets/{recycle-0MLWppmT.js → recycle-Bbki65G2.js} +1 -1
- package/dist/assets/remoteEntry-DYVoozgD.js +1 -0
- package/dist/assets/{scan-eye-DVK8MF3K.js → scan-eye-AfIM_Dlr.js} +1 -1
- package/dist/assets/{scissors-Cz3GoeOd.js → scissors-CnL6g0BO.js} +1 -1
- package/dist/assets/{search-x-i_A-Upbe.js → search-x-eqJd3G8u.js} +1 -1
- package/dist/assets/{send-B5VKcNUH.js → send-B72RQ9UL.js} +1 -1
- package/dist/assets/{settings-2-ZQsYJ0Zb.js → settings-2-CXZ6DVRg.js} +1 -1
- package/dist/assets/{speaker-Cl8DZGk_.js → speaker-CcCWWecW.js} +1 -1
- package/dist/assets/src-CGxdJN_f.js +67 -0
- package/dist/assets/{timer-reset-A5ofAkBW.js → timer-reset-B9Lihcw9.js} +1 -1
- package/dist/assets/{ungroup-t0yDnzVf.js → ungroup-D753owNE.js} +1 -1
- package/dist/assets/{unlink-C1ZpCxl3.js → unlink-DzoLNfsq.js} +1 -1
- package/dist/assets/{usb-DmUPajSy.js → usb-CuSU-_EY.js} +1 -1
- package/dist/assets/{use-scenes-feed-BQlYhRMq.js → use-scenes-feed-CZjJNxfD.js} +1 -1
- package/dist/assets/{use-stationary-objects-BWM4vE0E.js → use-stationary-objects-BoGqWyLV.js} +1 -1
- package/dist/assets/useEventInvalidation-C4w1vbly.js +1 -0
- package/dist/assets/useNodeUrlSelection-BA6CgjTU.js +1 -0
- package/dist/assets/useTranslation-D3Is_4B6.js +1 -0
- package/dist/assets/user-round-CMg3Ndlt.js +1 -0
- package/dist/assets/{user-x-DRcPeM9C.js → user-x-PK8sSsso.js} +1 -1
- package/dist/assets/{video-tLHyNE3q.js → video-BBtESt54.js} +1 -1
- package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-DOOXjnRq.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-BKfTL-9e.js} +2 -2
- package/dist/index.html +12 -12
- package/dist/server/addon.js +174 -5
- package/package.json +1 -1
- package/dist/assets/Addons-2xWF73cR.js +0 -4
- package/dist/assets/AdminSectionedPage-C3VHg80L.js +0 -1
- package/dist/assets/AiProfiles-DmHcVlS2.js +0 -3
- package/dist/assets/BrokerForm-Dqhjsi3Y.js +0 -1
- package/dist/assets/Build-CBYP1fT5.js +0 -40
- package/dist/assets/Calendars-C926x7b_.js +0 -1
- package/dist/assets/Cluster-OZlA14uV.js +0 -1
- package/dist/assets/ClusterStepModel-DHbwIGAW.js +0 -1
- package/dist/assets/CompositionEditor-vP3JcV2R.js +0 -1
- package/dist/assets/Data-7BoejvKA.js +0 -1
- package/dist/assets/DeviceDetail-ByM0856T.js +0 -2
- package/dist/assets/DeviceDoActionFields-BDJsvRNX.js +0 -1
- package/dist/assets/Devices-PIrWjfhq.js +0 -1
- package/dist/assets/Identity-C-tztwfa.js +0 -1
- package/dist/assets/IntegrationDetail-DugB7cv6.js +0 -1
- package/dist/assets/IntegrationHub-BePMbmC5.js +0 -1
- package/dist/assets/Integrations-Dj3nT9ZT.js +0 -1
- package/dist/assets/Integrations-OH5z-t03.js +0 -1
- package/dist/assets/Library-DDNti2te.js +0 -1
- package/dist/assets/Locations-OL9_NoSi.js +0 -3
- package/dist/assets/MaskShapeCanvas-Dcpby34M.js +0 -1
- package/dist/assets/MotionZonesSettings-CfTOerul.js +0 -1
- package/dist/assets/MyAccess-iJP3JQIS.js +0 -2
- package/dist/assets/Network-DYssxNiN.js +0 -1
- package/dist/assets/NodeAddonsSettingsPanel-mmtEgDbu.js +0 -1
- package/dist/assets/Notifications-DEcxFWp3.js +0 -1
- package/dist/assets/PrivacyMaskSettings-CJUKFEIs.js +0 -1
- package/dist/assets/Recordings-lygSYEJj.js +0 -1
- package/dist/assets/ScanNetworkModal-C2oJlLfj.js +0 -1
- package/dist/assets/SceneMonitorEditor-D1S-D2V9.js +0 -1
- package/dist/assets/SessionsList-CIN4GdSm.js +0 -2
- package/dist/assets/System-ChWpOOqN.js +0 -1
- package/dist/assets/_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-CE2IIKhe.js +0 -1
- 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
- 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
- package/dist/assets/board-model-Bmts6hrg.js +0 -1
- package/dist/assets/circle-slash-D5mo-8G0.js +0 -1
- package/dist/assets/client-CMlUvfoK.js +0 -358
- package/dist/assets/crop-Dev61hIh.js +0 -1
- package/dist/assets/device-picker-model-DlnG_8P7.js +0 -1
- package/dist/assets/dist--5X8Gy0U.js +0 -1
- package/dist/assets/dist-Dod19ois.js +0 -358
- package/dist/assets/i18n-vggiB6gm.js +0 -1
- package/dist/assets/index-BgQGn3LX.js +0 -4
- package/dist/assets/index-BndCgmxf.css +0 -2
- package/dist/assets/linked-devices-model-CCTQ_gka.js +0 -1
- package/dist/assets/location-owned-usage-DSLiI6RY.js +0 -1
- package/dist/assets/mount-DlnG_8P7.js +0 -1
- package/dist/assets/notification-schedule-field-DWpT_5Vh.js +0 -1
- package/dist/assets/player-overlays-Cda8wso6.js +0 -1
- package/dist/assets/remoteEntry-V_83-NrI.js +0 -1
- package/dist/assets/src-eoSUZcV-.js +0 -67
- package/dist/assets/useEventInvalidation-DlnG_8P7.js +0 -1
- package/dist/assets/useNodeUrlSelection-CTxv9Em7.js +0 -1
- package/dist/assets/useTranslation-Bc5yH9V9.js +0 -1
- package/dist/assets/user-round-BTaID248.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 ee,W as N,Wn as P,Xt as F,Yn as I,Z as L,_n as te,_t as R,ar as ne,bi as z,bn as B,br as V,cr as re,di as ie,dt as ae,fn as oe,ht as H,m as U,ot as W,qn as se,r as ce,si as le,sr as G,t as ue,un as de,vn as fe,wi as pe,yn as me,z as he}from"./player-overlays-Cda8wso6.js";import{t as ge}from"./archive-kvflMCgL.js";import{i as _e,n as ve,r as ye,t as be}from"./scan-eye-DVK8MF3K.js";import{t as xe}from"./bell-off-BYnwGeiH.js";import{t as Se}from"./boxes-Dx4USyB3.js";import{n as K}from"./video-tLHyNE3q.js";import{t as Ce}from"./circle-slash-D5mo-8G0.js";import{t as we}from"./layers-C1wzFfr1.js";import{An as Te,Ar as Ee,Br as De,Dr as q,Er as Oe,Fn as ke,Mr as J,Nn as Ae,Pn as je,Vr as Me,Xn as Ne,_ as Pe,_i as Fe,_r as Ie,b as Le,en as Re,f as ze,fn as Be,g as Ve,gi as He,in as Ue,jr as Y,ln as We,lr as Ge,m as Ke,nn as qe,p as Je,pr as Ye,rn as Xe,tn as Ze,u as Qe,un as $e,wr as et,yr as tt}from"./client-CMlUvfoK.js";import{$s as nt,A as rt,Ai as it,An as at,Bi as ot,Bn as X,Ca as st,Ct as ct,Dn as lt,Ds as ut,Ei as dt,En as ft,Fn as pt,Ha as mt,Hi as ht,Ht as gt,Ia as _t,Ii as vt,In as yt,Is as bt,Jr as xt,K as St,Kl as Ct,Kn as wt,Kt as Tt,Ln as Et,M as Dt,Mn as Ot,Mr as kt,Ms as At,Mt as jt,Nn as Mt,Os as Nt,Qi as Pt,Ql 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,Yo as Xt,Zl as Zt,Zn as Qt,Zs as $t,Zt as en,_t as tn,_u as nn,a as rn,an,ar as on,as as sn,at as cn,ba as ln,bt as un,c as dn,cn as fn,co as pn,ct as mn,d as hn,da as gn,dn as _n,dt as vn,du as yn,ec as bn,en as xn,et as Sn,eu as Cn,fo as wn,ft as Tn,fu as En,gt as Dn,ha as On,hn as kn,ht as An,i as jn,in as Mn,it as Nn,iu as Pn,j as Fn,ji as In,jn as Ln,js as Rn,k as zn,ka as Bn,kn as Vn,ks as Hn,l as Un,ln as Wn,lt as Gn,lu as Kn,ma as qn,mo as Jn,mr as Yn,nc as Xn,nn as Zn,nt as Qn,nu as $n,o as er,oa as tr,or as nr,ot as rr,pa as ir,po as ar,q as or,r as sr,rn as cr,rs 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,w as xr,wn as Sr,wt as Cr,x as wr,xt as Tr,yt as Er,za as Dr,zi as Or,zt as kr}from"./src-eoSUZcV-.js";import{t as Z}from"./useTranslation-Bc5yH9V9.js";import"./mount-DlnG_8P7.js";import{A as Ar,B as jr,D as Mr,G as Nr,J as Pr,K as Fr,M as Ir,N as Lr,O as Rr,Q as zr,R as Br,U as Vr,V as Hr,W as Ur,X as Wr,Z as Gr,g as Kr,j as qr,k as Jr,q as Yr,v as Xr,y as Zr,z as Qr}from"./index-BgQGn3LX.js";import{C as $r,D as ei,E as ti,S as ni,_ as ri,a as ii,b as ai,c as oi,d as si,f as ci,g as li,h as ui,i as di,l as fi,m as pi,n as mi,o as hi,p as gi,r as _i,s as vi,t as yi,u as bi,v as xi,x as Si,y as Ci}from"./CompositionEditor-vP3JcV2R.js";import{_ as wi,a as Ti,c as Ei,d as Di,f as Oi,g as ki,h as Ai,i as ji,l as Mi,m as Ni,n as Pi,o as Fi,p as Ii,s as Li,t as Ri,u as zi,v as Bi,y as Vi}from"./ClusterStepModel-DHbwIGAW.js";import"./useEventInvalidation-DlnG_8P7.js";import{t as Hi}from"./use-stationary-objects-BWM4vE0E.js";import{a as Ui,c as Wi,d as Gi,f as Ki,i as qi,l as Ji,n as Yi,o as Xi,p as Zi,r as Qi,s as $i,t as ea,u as ta}from"./linked-devices-model-CCTQ_gka.js";import{t as na}from"./authed-media-CSlndmzS.js";n();function ra(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 ia(e){if(typeof e!=`object`||!e)return null;let t=e.switches;if(!Array.isArray(t))return null;let n=t.map(ra).filter(e=>e!==null);return n.length===0?null:n}var aa=[[/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 oa(e){for(let[t,n]of aa)if(t.test(e))return n;return`generic`}function sa(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 ca={stream:B,detection:be,privacy:C,microphone:I,speaker:A,listening:ve,archive:ge,recording:ye,notifications:T,generic:f};function la({deviceId:t}){let{t:n}=Z(),i=s(),a=Number.isFinite(t),[o,l]=c(null),[d,p]=c(!1),m=At({deviceId:t},{enabled:a});sr([`pipelineOrchestrator`,`getCameraSwitches`],[`capability.binding-changed`]);let h=ia(m.data),g=Xn({onError:(e,n)=>{console.error(`[CameraFunctionSwitches] switch write failed — reverting`,{tags:{deviceId:t},meta:{switchId:n.switchId,error:e instanceof Error?e.message:String(e)}}),i.invalidateQueries({queryKey:[[`pipelineOrchestrator`,`getCameraSwitches`]]}),l({id:n.switchId,message:e instanceof Error?e.message:String(e)})},onSuccess:()=>{l(null),i.invalidateQueries({queryKey:[[`pipelineOrchestrator`]]}),i.invalidateQueries({queryKey:[[`deviceManager`]]}),i.invalidateQueries({queryKey:[[`recording`]]})}}),_=e(e=>{!e.available||e.on===null||g.mutate({deviceId:t,switchId:e.id,enabled:!e.on})},[t,g]);if(h===null)return null;let v=sa(h),y=e=>o?.id===e.id?o.message:null;return r(Cn,{open:d,onOpenChange:p,children:[r($n,{"aria-label":n(`device.cameraFunctionSwitches.cameraFunctions`,`Camera functions`),title:v.summary,className:`inline-flex items-center gap-1 rounded-lg border px-2 py-1.5 text-[11px] font-medium transition-colors ${o===null?v.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:n(`device.cameraFunctionSwitches.functions`,`Functions`)}),v.offIds.length>0&&r(`span`,{className:`rounded bg-warning/20 px-1 text-[9px] font-semibold uppercase tracking-wide`,children:[v.offIds.length,` off`]})]}),r(_r,{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:n(`device.cameraFunctionSwitches.cameraFunctions`,`Camera functions`)}),u(`ul`,{className:`space-y-0.5`,children:h.map(e=>u(`li`,{children:u(ua,{row:e,failure:y(e),onToggle:()=>_(e)})},e.id))})]})]})}function ua({row:e,failure:t,onToggle:n}){let i=ca[oa(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 da({deviceId:e}){let t=vn(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 fa({parentDeviceId:e}){let{t}=Z(),n=Wr(),i=W(),{data:a,isLoading:o,isError:s}=Hr(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=rr(c?.stableId??``,l,c?.childLayout),f=d.ungrouped,p=e=>n(`/devices/${String(e)}`),m=c?.name??``,h=(e,t)=>u(Nn,{trpc:i.trpcClient,device:{...t,name:Tn(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 pa({deviceId:e}){let t=W(),{data:n,isLoading:r}=jr(e),{data:i,isLoading:a}=Hr(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(An,{trpc:t.trpcClient,children:s,linkDeviceId:c,primaryChildEntityId:l})})}n();function ma({dev:e,busy:t,setBusy:n}){let{t:i}=Z(),a=e?.motionTrigger,o=v(e?.state.motionTrigger),[s,l]=c(!1);if(!a)return null;let d=o?.enabled===!0,f=o!==void 0,p=async()=>{if(t||!f)return;let e=!d;n(!0),l(!0);try{await a.setMotionTrigger({enabled:e})}finally{n(!1),l(!1)}},m=s?d?`Disabling…`:`Enabling…`:f?d?`On motion: on`:`On motion: off`:`On motion: …`;return r(`button`,{type:`button`,onClick:()=>{p()},disabled:t||!f,title:f?d?i(`hero.motionTriggerToggle.disableTriggerOnMotion`,`Disable trigger on motion`):i(`hero.motionTriggerToggle.enableTriggerOnMotion`,`Enable trigger on motion`):i(`hero.motionTriggerToggle.awaitingState`,`Awaiting state…`),"aria-pressed":d,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 ${d?`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:m})]})}n();function Q({deviceId:e,deviceType:t,features:n}){let i=W(),a=Er(t)?.HeroCard??un,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(tn,{lastChangedAt:p})}):null,u(a,{trpc:i.trpcClient,deviceId:e,features:n}),u(`div`,{className:`flex justify-center`,children:u(ma,{dev:o,busy:l,setBusy:d})})]})}function ha({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(Tr,{trpc:W().trpcClient,deviceId:e,features:t})})}function ga({deviceId:e,features:t}){return u(`div`,{className:`flex h-full w-full flex-col items-stretch p-3 sm:p-4`,children:u(un,{trpc:W().trpcClient,deviceId:e,features:t})})}function _a(e){if(!e)return null;let t=e.channel;return typeof t!=`number`||!Number.isInteger(t)||t<0?null:t}function va(e){if(!e)return null;let t=_a(e.data);return t===null?e.eventType:`Button ${String(t)} · ${e.eventType}`}var ya=1e3,ba=60*ya,xa=60*ba,Sa=24*xa;function Ca(e,t){if(e==null||e<=0)return`—`;let n=t-e;return n<ya?`just now`:n<ba?`${String(Math.floor(n/ya))}s ago`:n<xa?`${String(Math.floor(n/ba))}m ago`:n<Sa?`${String(Math.floor(n/xa))}h ago`:`${String(Math.floor(n/Sa))}d ago`}n();var wa=1500,Ta=15e3,Ea=1e3;function Da({deviceId:e}){let{t:n}=Z(),i=b(W().trpcClient,e)?.state.eventEmitter,a=v(i);d(()=>{if(!i)return;i.refresh();let e=setInterval(()=>{i.refresh()},Ta);return()=>{clearInterval(e)}},[i]);let o=a?.lastEvent??null,s=o?.seq??null,l=t(null),[f,p]=c(!1);d(()=>{if(s===null)return;let e=l.current;if(l.current=s,e===null||e===s)return;p(!0);let t=setTimeout(()=>{p(!1)},wa);return()=>{clearTimeout(t)}},[s]);let[m,h]=c(()=>Date.now());d(()=>{let e=setInterval(()=>{h(Date.now())},Ea);return()=>{clearInterval(e)}},[]);let g=va(o),_=a?.eventTypes??[],y=a?.eventCountSinceStart??0,x=a!==void 0,S=_a(o?.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(f),className:`flex h-24 w-24 items-center justify-center rounded-full border-2 transition-all ${f?`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:g??n(`hero.eventEmitterHero.noPressRecorded`,`No press recorded`),children:u(f?P:V,{className:`h-10 w-10`})}),r(`div`,{className:`text-center`,children:[S!==null&&u(`div`,{className:`text-xs font-semibold uppercase tracking-wide text-primary`,children:n(`hero.eventEmitterHero.button`,`Button {{value1}}`,{value1:String(S)})}),u(`div`,{"data-testid":`event-emitter-headline`,className:`text-sm font-semibold ${g?`text-foreground`:`text-foreground-subtle`}`,children:g??(x?n(`hero.eventEmitterHero.noPressRecorded`,`No press recorded`):n(`hero.eventEmitterHero.awaitingState`,`Awaiting state…`))}),u(`div`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:o?Ca(o.timestamp,m):n(`hero.eventEmitterHero.waitingForTheFirstEvent`,`Waiting for the first event`)})]}),_.length>0&&u(`div`,{className:`flex max-w-full flex-wrap justify-center gap-1`,children:_.map(e=>u(`span`,{"data-testid":`event-emitter-chip`,className:`rounded-full border px-2 py-0.5 text-[10px] font-medium ${e===o?.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(y)} ${y===1?`event`:`events`} since start`})]})}function Oa({deviceName:e,deviceType:t,provider:n,isOnline:i,features:a}){let{t:o}=Z();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(Fr,{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(Dt,{status:i?`online`:`offline`}),a.length>0&&u(Yr,{capabilities:a})]}),u(`div`,{className:`text-[10px] text-foreground-subtle italic max-w-xs mt-1`,children:o(`hero.genericHero.noLiveViewForThis`,`No live view for this device type. Use the Config tab or the shortcut row to interact.`)})]})}n();function ka({deviceId:e}){let{t}=Z(),n=s(),a=Or({deviceId:e},{refetchInterval:1e4,retry:!1}),o=ot({onSuccess:()=>{n.invalidateQueries({queryKey:[[`deviceDiscovery`,`listDiscovered`]]}),n.invalidateQueries({queryKey:[[`deviceDiscovery`,`getStatus`]]})}}),c=i(()=>Aa(a.data??[]),[a.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(ja,{label:t(`hero.hubHero.discovered`,`Discovered`),value:c.total,icon:u(O,{className:`h-3.5 w-3.5`})}),u(ja,{label:t(`hero.hubHero.adopted`,`Adopted`),value:c.adopted,accent:`success`}),u(ja,{label:t(`hero.hubHero.available`,`Available`),value:c.available,accent:c.available>0?`primary`:void 0}),r(`button`,{type:`button`,onClick:()=>{o.mutateAsync({deviceId:e}).catch(()=>{})},disabled:o.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:[o.isPending?u(ne,{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:t(`hero.hubHero.discover`,`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(Ma,{icon:u(H,{className:`h-3 w-3 text-emerald-500`}),label:t(`hero.hubHero.online`,`{{online}} online`,{online:c.online})}),u(Ma,{icon:u(g,{className:`h-3 w-3 text-amber-500`}),label:t(`hero.hubHero.sleeping`,`{{sleeping}} sleeping`,{sleeping:c.sleeping})}),u(Ma,{icon:u(R,{className:`h-3 w-3 text-destructive`}),label:t(`hero.hubHero.offline`,`{{offline}} offline`,{offline:c.offline})}),c.unknown>0?u(Ma,{icon:u(le,{className:`h-3 w-3 text-foreground-subtle`}),label:t(`hero.hubHero.unknown`,`{{unknown}} unknown`,{unknown:c.unknown})}):null]})]})}function Aa(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 ja({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 Ma({icon:e,label:t}){return r(`span`,{className:`inline-flex items-center gap-1`,children:[e,u(`span`,{children:t})]})}var Na={[J.Switch]:Q,[J.Siren]:Q,[J.Light]:Q,[J.Sensor]:Q,[J.Button]:Q,[J.Hub]:ka,[J.Cover]:ha,[J.Valve]:Q,[J.Humidifier]:Q,[J.WaterHeater]:Q,[J.Container]:pa,[J.Lock]:Q,[J.Fan]:Q,[J.Thermostat]:Q,[J.Climate]:Q,[J.MediaPlayer]:Q,[J.Control]:Q,[J.AlarmPanel]:Q,[J.EventEmitter]:Da,[J.Notifier]:ga,[J.Script]:Q,[J.Automation]:Q,[J.Presence]:Q,[J.Update]:Q,[J.Vacuum]:Q,[J.LawnMower]:Q,[J.Weather]:Q,[J.Image]:Q,[J.PetFeeder]:Q};function Pa(e){return Na[e]??Oa}function Fa(e){return u(Pa(e.deviceType),{...e})}function Ia(e){return er(W().trpcClient,e)}n();function La(n){let[r,i]=c(`idle`),[a,o]=c(null),s=t(null),l=t(null),u=t(null),f=t(!0),p=ar(),m=wn(),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 Ra=0;function $(){return++Ra}function za(e){switch(e.type){case`system`:return`system`;case`device`:return`#${e.deviceId}`;case`provider`:return e.providerId;case`addon`:return e.addonId}}function Ba(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 Va(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 Ha(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 Ua({scope:n,greeting:i,className:a}){let{t:o}=Z(),s=W(),[f,p]=c(()=>{let e=[];return i&&e.push({id:$(),kind:`info`,text:i}),e.push({id:$(),kind:`info`,text:`scope: ${za(n)} — type help or context for available commands`}),e}),[m,h]=c(``),[g,_]=c([]),[v,y]=c(-1),b=t(null),x=t(null);d(()=>{let e=x.current;e&&(e.scrollTop=e.scrollHeight)},[f]);let S=e(()=>{b.current?.focus()},[]),C=l({mutationFn:e=>s.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`;p(e=>[...e,{id:$(),kind:r?`error`:`result`,text:n}])},onError:e=>{let t=e instanceof Error?e.message:String(e);p(e=>[...e,{id:$(),kind:`error`,text:t}])}});function w(e){let t=e.trim();if(t){if(t===`clear`){p([{id:$(),kind:`info`,text:`scope: ${za(n)}`}]),h(``);return}if(t===`help`){p(e=>[...e,{id:$(),kind:`input`,text:`> ${t}`},...Ba(n).map(e=>({id:$(),kind:`info`,text:e}))]),h(``);return}if(t===`context`){p(e=>[...e,{id:$(),kind:`input`,text:`> ${t}`},...Ha(n).map(e=>({id:$(),kind:`info`,text:e}))]),h(``);return}if(t===`examples`){p(e=>[...e,{id:$(),kind:`input`,text:`> ${t}`},...Va(n).map(e=>({id:$(),kind:`info`,text:e}))]),h(``);return}_(e=>[...e,t]),y(-1),p(e=>[...e,{id:$(),kind:`input`,text:`> ${t}`}]),h(``),C.mutate(t)}}function T(e){if(e.key===`Enter`){e.preventDefault(),w(m);return}if(e.key===`ArrowUp`){if(e.preventDefault(),g.length===0)return;let t=v===-1?g.length-1:Math.max(0,v-1);y(t),h(g[t]??``);return}if(e.key===`ArrowDown`){if(e.preventDefault(),v===-1)return;let t=v+1;t>=g.length?(y(-1),h(``)):(y(t),h(g[t]??``));return}e.ctrlKey&&e.key===`l`&&(e.preventDefault(),p([{id:$(),kind:`info`,text:`scope: ${za(n)}`}]))}let E={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:S,children:[r(`div`,{ref:x,className:`flex-1 overflow-y-auto p-3 space-y-1 min-h-[120px]`,children:[f.map(e=>u(`pre`,{className:`whitespace-pre-wrap break-words leading-relaxed ${E[e.kind]}`,children:e.text},e.id)),C.isPending&&u(`span`,{className:`text-zinc-500 animate-pulse`,children:o(`shared.replTerminal.thinking`,`…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:o(`shared.replTerminal.text`,`>`)}),u(`input`,{ref:b,value:m,onChange:e=>h(e.target.value),onKeyDown:T,disabled:C.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 Wa(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 Ga({deviceId:e,intercomAvailable:t=!1}){let n=W(),r=typeof window<`u`?L():``,a=Number.isFinite(e),s=Ia(a?e:null),c=Hi(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}=kr(n.trpcClient,a?e:null),C=h(a?e:null,{width:Xa}),w=La(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=yt(),A=typeof window<`u`?window.localStorage.getItem(`camstack_admin_token`):null,j=Wa(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(wr,{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 Ka({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 qa({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(Ua,{scope:{type:`device`,deviceId:e},greeting:t,className:`h-full border-0 rounded-none`})}function Ja({deviceId:e}){return Number.isFinite(e)?u(`div`,{className:`flex flex-col h-full overflow-y-auto`,children:u(Cr,{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 Ya({deviceId:e}){return Number.isFinite(e)?u(`div`,{className:`flex flex-col h-full overflow-y-auto`,children:u(ct,{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 Xa=960;function Za(e){return new Set(e.filter(e=>{let t=e.nativeAddonId?.trim()??``;return t!==``&&t!==`composer`}).map(e=>e.capName))}function Qa(e){return e.kind===`known`?null:e}function $a(e,t){return e.composable.kind===`known`?e.composable.value.has(t)?{kind:`present`,mode:`add`}:{kind:`absent`}:e.composable}function eo(e){if(e.deviceType!==J.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 to(e,t){if(e===`motion`)return eo(t);let n=Qa(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`}:$a(t,`doorbell`);case`battery`:return r.has(`battery`)?{kind:`present`,mode:`replace`}:$a(t,`battery`);case`consumables`:return r.has(`consumables`)?{kind:`absent`}:$a(t,`consumables`)}}function no({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 ro(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=Ye(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 io(e){return e.kind===`present`?e.composition:null}function ao(e,t){let{hidden:n,...r}=e??{},i=t?{...r,hidden:!0}:r;return Object.keys(i).length===0?null:i}function oo(e){return typeof e.linkDeviceId==`number`}var so=new Set(Object.values(Y));function co(e){return so.has(e)}var lo={[J.Switch]:[Y.Siren,Y.Floodlight,Y.Spotlight,Y.PirSensor,Y.Chime,Y.Autotrack,Y.Nightvision,Y.PrivacyMask,Y.BinaryHelper],[J.Light]:[Y.Floodlight,Y.Spotlight,Y.Nightvision],[J.Siren]:[Y.Siren],[J.Button]:[Y.Doorbell],[J.Sensor]:[Y.MotionSensor,Y.ContactSensor,Y.LeakSensor,Y.SmokeSensor,Y.COSensor,Y.GasSensor,Y.TamperSensor,Y.VibrationSensor,Y.ConnectivitySensor,Y.SoundSensor,Y.BinarySensor,Y.TemperatureSensor,Y.HumiditySensor,Y.AmbientLightSensor,Y.PressureSensor,Y.WindSensor,Y.RainSensor,Y.UvSensor,Y.SolarRadiationSensor,Y.SoilMoistureSensor,Y.PowerSensor,Y.EnergySensor,Y.VoltageSensor,Y.CurrentSensor,Y.AirQualitySensor,Y.BatterySensor,Y.NumericSensor,Y.EnumSensor,Y.DateTimeSensor,Y.GenericSensor],[J.Control]:[Y.NumericControl,Y.SelectControl,Y.TextControl,Y.DateTimeControl],[J.Notifier]:[Y.MobilePushNotifier,Y.MessagingNotifier,Y.EmailNotifier,Y.GenericNotifier]};function uo(e){for(let t of Object.values(J))if(t===e)return!0;return!1}function fo(e){return uo(e)?lo[e]??[]:[]}function po(e,t){let n=fo(t);return e==null||e===``||n.includes(e)?n:[...n,e]}n();function mo({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=_t(),f=Bn(),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(Vr,{deviceId:e.id,initialLocation:e.location,label:t(`customize.identity.room`),layout:`stacked`,onError:a,onSaved:o,onCancel:o}),u(Nr,{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:ao(e.display,t.target.checked)},l)})}),u(Nr,{label:t(`customize.identity.role`),layout:`stacked`,value:oo(e)?u(`span`,{children:ho(e.role,t(`customize.identity.noRole`))}):u(Ct,{"aria-label":t(`customize.identity.role`),value:e.role??``,disabled:d.isPending,options:[{value:``,label:t(`customize.identity.noRole`)},...po(e.role,e.type).map(e=>({value:e,label:ho(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 ho(e,t){return e==null||e===``?t:co(e)?Kn(e).label:e}n();function go(e){return e===`pending`?`pending`:e===`error`?`failed`:`answered`}function _o({excludeDeviceIds:e,onSelect:t}){let{t:n}=Z(),r=qn({projection:`slim`}),a=r.status===`success`?r.data:null,o=i(()=>{if(a===null)return[];let t=new Set(e);return oi(a).filter(e=>!t.has(e.id))},[a,e]),s=i(()=>new Map(o.map(e=>[e.id,e])),[o]),c=i(()=>o.map(e=>({id:e.id,name:e.name,type:e.type,...e.location===null?{}:{location:e.location}})),[o]);if(r.status===`error`)return u(Et,{title:n(`customize.picker.devicesFailed`),message:r.error?.message??``});let l=e=>{let n=s.get(e);n!==void 0&&t(n)};return u(hn,{devices:c,listState:go(r.status),value:[],onChange:e=>{let t=e.at(-1);t!==void 0&&l(t)},noun:`device`,emptyLabel:n(`customize.assign.none`),showAll:!0,testId:`customize-field-device-picker`})}function vo({open:e,title:t,targetKind:n,excludeDeviceIds:i,confirmLabel:a,extra:s,extraComplete:l=!0,onConfirm:d,onClose:f}){let{t:p}=Z(),[m,h]=c(null),[g,_]=c(null),v=()=>{h(null),_(null),f()};return u(Ht,{open:e,onOpenChange:e=>e?void 0:v(),children:r(lt,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,"aria-label":t,children:[u(at,{children:u(Ln,{children:t})}),u(ft,{className:`flex flex-col gap-3 p-2 sm:p-4`,children:e&&r(o,{children:[r(`section`,{"aria-label":p(`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:p(`customize.assign.stepDevice`)}),m===null?u(_o,{excludeDeviceIds:i,onSelect:h}):r(`p`,{className:`flex items-center gap-2 text-xs text-foreground`,children:[m.name,u(X,{variant:`ghost`,size:`sm`,onClick:()=>{h(null),_(null)},children:p(`customize.assign.change`)})]})]}),m!==null&&r(`section`,{"aria-label":p(`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:p(`customize.assign.stepField`)}),u(ii,{device:m,targetKind:n,selected:g===null?null:{cap:g.cap,path:g.path},onPick:_,onBack:()=>{h(null),_(null)}})]}),m!==null&&s!==void 0&&r(`section`,{"aria-label":p(`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:p(`customize.assign.stepDetails`)}),s]})]})}),r(Vn,{children:[u(X,{variant:`ghost`,onClick:v,children:p(`customize.assign.cancel`)}),u(X,{disabled:g===null||!l,onClick:()=>{g!==null&&(d(g),h(null),_(null))},children:a})]})]})})}function yo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function bo(e,t){let n=vi(e,t);return n===void 0?{kind:`absent`}:{kind:`value`,value:n}}function xo(e,t,n){return yo(t)?bo(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`}:bo(e.data,n)}function So(e,t,n){let r=e?`active`:`muted`;return t.cap===`contact`&&t.path===`entryOpen`?{text:e?n.open:n.closed,tone:r}:Me[t.cap]===t.path?{text:e?n.active:n.inactive,tone:r}:{text:String(e),tone:`normal`}}function Co(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`?So(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 wo=0;function To(e){let t=W(),n=mt({deviceId:e?.deviceId??wo,capName:e?.cap??``},{enabled:e!==null}),r=ur(t.trpcClient,e?.deviceId??null,e?.cap??``);return e===null?{kind:`absent`}:xo({status:n.status,data:n.data,error:n.error===null||n.error===void 0?null:{message:n.error.message}},r,e.path)}var Eo={muted:`text-foreground-subtle`,active:`text-success`,normal:`text-foreground`,warning:`text-warning`};function Do({target:e}){let{t}=Z(),n=To(e);return e===null?null:u(Oo,{display:Co(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 Oo({display:e}){return u(`span`,{className:`text-xs ${Eo[e.tone]}`,title:e.title,children:e.text})}function ko({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(Do,{target:i}):a!==null&&u(Oo,{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(Ft,{icon:ae,variant:`ghost`,size:`sm`,"aria-label":c,disabled:l,onClick:s})})]})}function Ao({id:e,...t}){return u(qt,{headingId:`customize-${e}`,...t})}function jo({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(Ao,{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(F,{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 Mo({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 No(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)}}function Po(e,t){let n=nn.useQueries(n=>e.map(e=>n.deviceManager.listDeviceIdsByCaps({capNames:[e]},{enabled:t})));return ta(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 Fo(e,t){let n=Qn(e,t);return n.kind===`resolved`?n.integration.name:null}function Io(e){let t=qn({projection:`slim`},{enabled:e}),{data:n}=pn(void 0,{enabled:e}),r=t.error===null||t.error===void 0?null:t.error.message;return i(()=>No({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:Fo(e,n),parentDeviceId:e.parentDeviceId,primaryChildEntityId:e.primaryChildEntityId??null,role:e.role??null}))),[t.status,t.data,r,n])}function Lo(e){let t=Io(e.enabled),n=Po(De,e.enabled);return t.kind===`unknown`?t:n.kind===`unknown`?n:t.kind===`pending`||n.kind===`pending`?{kind:`pending`}:{kind:`known`,value:Zi({devices:t.value,capIndex:n.value,hostId:e.hostId,excludeCameras:e.excludeCameras,assigned:e.assigned,preferredCap:e.preferredCap})}}function Ro(){let{t:e}=Z(),t=Qt();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 zo(e){return e===null?null:ui(e,`replace`)?`replace`:ui(e,`add`)?`add`:null}function Bo({device:e,handle:t,availability:n,onAdvanced:i}){let{t:a}=Z(),s=Ro(),[l,d]=c(!1),[f,p]=c(null),m=io(t.state),h=Ci(m,`battery`),g=zo(h),_=g===null?null:ri(h?.fields.percentage),v=Io(_!==null);if(n.kind===`absent`)return null;let y=n.kind===`present`?n.mode:null,b=t.state.kind===`none`||t.state.kind===`present`,x=_===null||v.kind!==`known`?null:v.value.find(e=>q({addonId:e.addonId,stableId:e.stableId})===q(_.source))??null,S=_===null?``:x?.name??q(_.source),C=async e=>{let n=await t.save(e);p(n.kind===`refused`?n.reason:null)},w=async()=>{if(m===null)return;let e=$r(m,`battery`);await s(a(`customize.battery.removeWhat`,{name:S}),e===null)&&await C(e)},T=y!==null&&b&&h===null&&!t.saving;return r(o,{children:[r(jo,{id:`battery`,icon:D,title:a(`customize.battery.title`),addLabel:a(y===`replace`?`customize.battery.replace`:`customize.battery.add`),onAdd:T?()=>d(!0):void 0,notices:r(o,{children:[u(Mo,{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:[y===`replace`&&b&&u(ko,{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&&y===`add`&&b&&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(ko,{name:S,detail:`${_.cap}.${_.fieldPath}`,meta:a(g===`replace`?`customize.assign.replaces`:`customize.assign.adds`),value:x===null?null:{deviceId:x.id,cap:_.cap,path:_.fieldPath},problem:x===null&&v.kind===`known`?a(`customize.assign.missingKept`):void 0,onRemove:b?()=>void w():void 0,removeLabel:a(`customize.assign.removeNamed`,{name:S}),busy:t.saving}),h!==null&&_===null&&u(ko,{name:a(`customize.battery.otherFormula`),detail:null,meta:u(no,{onAdvanced:i}),value:{deviceId:e.id,cap:`battery`,path:`percentage`},removeLabel:``})]}),u(vo,{open:l,title:a(y===`replace`?`customize.battery.replace`:`customize.battery.add`),targetKind:`number`,excludeDeviceIds:[e.id],confirmLabel:a(`customize.assign.add`),onConfirm:e=>{d(!1);let n=y===null?null:bi({percentage:{source:e.ref,cap:e.cap,fieldPath:e.path,kind:e.kind},mode:y});n===null?p(a(`customize.assign.pickUnusable`)):C(ni(m,t.target,n))},onClose:()=>d(!1)})]})}n();function Vo(e,t){let n=e.source;if(n===null||t.kind!==`known`)return null;let r=q(n.source);return t.value.find(e=>q({addonId:e.addonId,stableId:e.stableId})===r)??null}function Ho(e){let t=typeof e==`number`?e:typeof e==`string`?Number(e):NaN;return Number.isFinite(t)?t:null}function Uo({device:e,handle:t,availability:n,onAdvanced:i}){let{t:a}=Z(),s=Ro(),[l,d]=c(!1),[f,p]=c(``),[m,h]=c(`percent`),[g,_]=c(null),v=io(t.state),y=Ci(v,`consumables`),b=ci(y),x=Io(b.some(e=>e.source!==null));if(n.kind===`absent`)return null;let C=t.state.kind===`none`||t.state.kind===`present`,w=n.kind===`present`&&C&&!t.saving,T=li(f),E=b.find(e=>e.key===T)??null,D=E!==null,O=f.trim()!==``&&T===``,k=async e=>{let n=await t.save(e);_(n.kind===`refused`?n.reason:null)},A=()=>{d(!1),p(``),h(`percent`)},j=async e=>{if(y===null||v===null)return;let n=xi(y,e.key),r=n===null?$r(v,`consumables`):ni(v,t.target,n);await s(a(`customize.consumables.removeWhat`,{name:e.label}),r===null)&&await k(r)},M=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(Zt,{"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(Ct,{"aria-label":a(`customize.consumables.unit`),value:m,options:fi.map(e=>({value:e,label:a(`customize.consumables.units.${e}`)})),onChange:e=>{let t=fi.find(t=>t===e.target.value);t!==void 0&&h(t)}})]}),D&&u(`p`,{role:`alert`,className:`basis-full text-xs text-warning`,children:a(`customize.consumables.takenBy`,{name:E.label})}),O&&u(`p`,{role:`alert`,className:`basis-full text-xs text-warning`,children:a(`customize.consumables.keyless`)})]});return r(o,{children:[r(jo,{id:`consumables`,icon:S,title:a(`customize.consumables.title`),addLabel:a(`customize.consumables.add`),onAdd:w?()=>d(!0):void 0,notices:r(o,{children:[u(Mo,{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(ko,{name:e.label,detail:a(`customize.consumables.otherFormula`),meta:u(no,{onAdvanced:i}),value:null,removeLabel:``},e.key);let r=Vo(e,x),o=r?.name??q(n.source);return u(ko,{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:C?()=>void j(e):void 0,removeLabel:a(`customize.assign.removeNamed`,{name:e.label}),busy:t.saving},e.key)}),b.length===0&&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(vo,{open:l,title:a(`customize.consumables.pickTitle`),targetKind:`number`,excludeDeviceIds:[e.id],confirmLabel:a(`customize.assign.add`),extra:M,extraComplete:T!==``&&!D,onConfirm:e=>{let n=Ho(e.value);if(n!==null&&(n<0||m===`percent`&&n>100)){A(),_(a(`customize.consumables.outOfRange`,{value:n}));return}let r=si(y,{key:T,label:f,remaining:{source:e.ref,cap:e.cap,fieldPath:e.path,kind:e.kind},unit:m});A(),r===null?_(a(`customize.assign.pickUnusable`)):k(ni(v,t.target,r))},onClose:A})]})}function Wo(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 Go(e,t,n){return nr(e,t?.ids??new Set,n)}function Ko(e,t){return e?.containers.get(t)??null}function qo(e,t,n){return e.kind===`known`?Go(e.value,t,n).suggested.length:0}function Jo(e,t){let n=[t,e.detail].filter(e=>e!==null&&e!==``);return n.length===0?null:n.join(` · `)}function Yo({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:`${ee} 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=Jo(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 Xo(e){return e.kind===`pending`?`pending`:e.kind===`unknown`?`failed`:`answered`}function Zo(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 Qo({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`?Gi(a.value,``,y):[],S=Go(b,s,e=>e.deviceId).suggested,C=Go(x,s,e=>e.deviceId).others,w=i(()=>Zo(C),[C]),T=Xo(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(lt,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,"aria-label":t,children:[u(at,{children:u(Ln,{children:t})}),r(ft,{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(Yo,{location:s.location,devices:S.map(e=>({id:e.deviceId,name:e.name,container:Ko(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(hn,{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(Vn,{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 $o(e){if(e===null)return[];let t=pi(e);return gi(e).map(e=>{let n=q(e);return{key:n,ref:e,caps:t.filter(e=>q(e.source)===n).map(e=>e.cap)}})}function es(e,t){let n=pi(e);if(n.length===0)return!1;let{enabled:r,...i}=e,{enabled:a,...o}=Xe({camera:t,sources:n,enabled:!0});return Si(i,o)}function ts(e){return e?.enabled!==!1}function ns(e,t,n){let r=[...e===null?[]:pi(e),...n.flatMap(e=>Ue(e.ref,e.caps))];return r.length===0?null:Xe({camera:t,sources:r,enabled:ts(e)})}function rs(e,t,n){let r=pi(e).filter(e=>q(e.source)!==n);return r.length===0?null:Xe({camera:t,sources:r,enabled:ts(e)})}function is(e,t){return{...e,enabled:t}}n();function as({device:e,handle:t,availability:n,onAdvanced:i}){let{t:a}=Z(),s=Ro(),[l,d]=c(!1),[f,p]=c(null),h=io(t.state),g=Ci(h,`doorbell`),_=g===null||es(g,t.target),v=_?$o(g):[],y=Io(v.length>0),b=Lo({hostId:e.id,excludeCameras:!1,assigned:new Set(v.map(e=>e.key)),preferredCap:null,enabled:l});if(n.kind===`absent`)return null;let x=t.state.kind===`none`||t.state.kind===`present`,S=x&&!t.saving,C=n.kind===`present`&&S&&_,w=async e=>{let n=e===null?h===null?null:$r(h,`doorbell`):ni(h,t.target,e),r=await t.save(n);p(r.kind===`refused`?r.reason:null)},T=async(e,n)=>{if(g===null||h===null)return;let r=rs(g,t.target,e.key),i=r===null&&$r(h,`doorbell`)===null;await s(a(`customize.doorbell.removeWhat`,{name:n}),i)&&await w(r)},E=e=>y.kind===`known`?y.value.find(t=>q({addonId:t.addonId,stableId:t.stableId})===e.key)??null:null;return r(o,{children:[r(jo,{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:!S,onChange:e=>void w(is(g,e.target.checked))}),a(`customize.doorbell.active`)]}),addLabel:a(`customize.doorbell.add`),onAdd:C?()=>d(!0):void 0,notices:r(o,{children:[u(Mo,{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=E(e),r=n?.name??e.key,i=Ki(e.caps,null),o=i===null?void 0:Me[i];return u(ko,{name:r,detail:n===null?null:Ji(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:x?()=>void T(e,r):void 0,removeLabel:a(`customize.assign.removeNamed`,{name:r}),busy:t.saving},e.key)}),!_&&u(ko,{name:a(`customize.doorbell.otherFormula`),detail:null,meta:u(no,{onAdvanced:i}),value:null,removeLabel:``}),g===null&&n.kind===`present`&&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`)})]}),u(Qo,{open:l,title:a(`customize.doorbell.pickTitle`),selection:`multi`,candidates:b,confirmLabel:e=>a(`customize.assign.addCount`,{count:e}),onConfirm:e=>{d(!1),w(ns(g,t.target,e.map(e=>({ref:e.ref,caps:e.caps}))))},onClose:()=>d(!1)})]})}n();function os(e,t){let n=typeof e==`string`&&e.length>0,r=Io(t&&n);return i(()=>t?Wo(r,e):null,[t,r,e])}n();function ss(e){return e==null?null:e.message}function cs({device:e}){let{t}=Z(),n=s(),i=Ro(),a=Ne.includes(e.type),[l,d]=c(!1),[f,p]=c(!1),[m,h]=c(null),g=Wt({deviceId:e.id},{enabled:a}),_=Qi({status:g.status,data:g.data,error:ss(g.error)===null?null:{message:ss(g.error)??``}}),v=_.kind===`present`?_.slot.slotRef:``,y=_.kind===`present`?[...Yi(_.slot,_.value).map(e=>e.deviceId),...qi(_.slot,_.value)]:[],b=Yt(),x=Io(a&&_.kind===`present`&&(l||y.length>0)),S=os(e.location,a&&_.kind===`present`),C=ht({deviceId:e.id,slotRef:v},{enabled:(l||S!==null)&&_.kind===`present`});if(!a||_.kind===`absent`)return null;if(_.kind!==`present`)return u(jo,{id:`linked`,icon:re,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:Ji(n.integration,n.location),orphan:t}},O=[...Yi(_.slot,w).map(e=>D(e,!1)),...qi(_.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:ss(C.error)??`the request failed`}:x.kind===`pending`||C.status===`pending`||C.data===void 0?{kind:`pending`}:{kind:`known`,value:ea(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($i(w,e.deviceId))},ee=[{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?`—`:yn(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(Mn,{checked:e.tracked,disabled:f,"aria-label":t(`customize.linked.trackFor`,{name:e.name??e.deviceId}),onCheckedChange:t=>void j(Xi(w,e.deviceId,t))})}]:[],{key:`remove`,header:``,cellClassName:`text-right w-10`,cell:e=>e.implied||e.orphan?null:u(Ft,{icon:ae,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(jo,{id:`linked`,icon:re,title:t(`customize.linked.title`),addLabel:t(`customize.linked.add`),onAdd:f?void 0:()=>d(!0),...S===null?{}:{suggestion:{count:qo(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(Sn,{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:yn(e.type).label,columns:ee,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(Qo,{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(Ui(w,e.map(e=>e.deviceId)))},onClose:()=>d(!1)})]})}function ls(e){return e===null||e.state===`unreadable`?null:e.state===`configured`?e.sensors:[]}function us(e){return{addonId:e.addonId,stableId:e.stableId,mode:e.mode}}function ds(e){return e.length===0?null:{sensors:[...e]}}function fs(e,t){let n=new Set(e.map(ke));return ds([...e.map(us),...t.filter(e=>!n.has(ke(e))).map(e=>({...e,mode:je}))])}function ps(e,t,n){return ds(e.map(e=>ke(e)===t?{...us(e),mode:n}:us(e)))}function ms(e,t){return ds(e.filter(e=>ke(e)!==t).map(us))}function hs(e){return e?.state===`configured`&&e.cameraMotion!==void 0}function gs(e){return e===null||e.state===`unreadable`?null:e.state===`configured`?e.cameraMotion??`always`:`always`}function _s(e){return e===null||e.state===`unreadable`?!1:e.state===`not-configured`||hs(e)}function vs(e){return e?.state===`configured`&&(e.notForwarded!==void 0||e.notEnforced!==void 0)}function ys(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 bs=5e3;function xs(e){return e.state===`missing`||e.state===`unreadable`?e.stableId:e.name}function Ss({device:e,availability:n,sensors:i}){let{t:a}=Z(),s=Ro(),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()},bs);return()=>clearInterval(e)},[]);let C=ls(x);d(()=>{x!==null&&b(!1)},[x]);let w=i.presence===`present`&&_s(x)&&!y?C:null,T=Io(C!==null&&C.length>0),D=Lo({hostId:e.id,excludeCameras:!0,assigned:new Set((C??[]).map(ke)),preferredCap:`motion`,enabled:f});if(n.kind===`absent`)return null;let O=hs(x),k=vs(x)?`passes`:gs(x),A=ys(i.presence,x,y),j=A.kind===`none`?null:A.kind===`unknown`?{text:`?`,tone:`warning`,title:a(`customize.motion.cameraLevelUnknown`)}:{text:a(A.detected?`customize.assign.value.active`:`customize.assign.value.inactive`),tone:A.detected?`active`:`muted`,title:a(`customize.motion.cameraLevelOwn`,{at:new Date(A.atMs).toLocaleTimeString()})},M=_||l.isPending,ee=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)}},N=async e=>{w!==null&&await s(a(`customize.motion.removeWhat`,{name:xs(e)}),!1)&&await ee(ms(w,ke(e)))},P=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:Ji(t.integration,t.location)};return r(o,{children:[r(jo,{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:M,notices:r(o,{children:[u(Mo,{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`&&!_s(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(ko,{name:a(`customize.motion.camera`),detail:null,meta:k===null?a(`customize.assign.native`):`${a(`customize.motion.cameraState.${k}`)} · ${a(`customize.assign.native`)}`,value:null,shown:j,removeLabel:``}),(C??[]).map(e=>{let t=ke(e),n=xs(e),r=e.state===`ready`?Ki(e.caps,`motion`):null,i=r===null?void 0:Me[r];return u(ko,{name:n,detail:P(e),meta:O&&w!==null?u(Ct,{"aria-label":a(`customize.motion.modeFor`,{name:n}),value:e.mode,disabled:M,options:Ae.options.map(e=>({value:e,label:a(`customize.motion.mode.${e}`)})),onChange:e=>{let n=Ae.safeParse(e.target.value);n.success&&w!==null&&ee(ps(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 N(e),removeLabel:a(`customize.assign.removeNamed`,{name:n}),busy:M},t)})]}),u(Qo,{open:f,title:a(`customize.motion.pickTitle`),selection:`multi`,candidates:D,filters:Wi,confirmLabel:e=>a(`customize.assign.addCount`,{count:e}),onConfirm:e=>{if(p(!1),w===null)return;let t=fs(w,e.map(e=>e.ref));if(t!==null&&t.sensors.length>8){h(a(`customize.motion.tooMany`,{max:8}));return}ee(t)},onClose:()=>p(!1)})]})}var Cs={"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`}},ws=new Set([J.Camera]);function Ts(e){return e.unitField===null?[e.fieldPath]:[e.fieldPath,e.unitField]}function Es(e,t){if(ws.has(e))return{kind:`absent`};let n=null;for(let[e,r]of Object.entries(Cs))if(t.has(e)){n={cap:e,fieldPath:r.fieldPath,unitField:r.unitField};break}let r=null;for(let e of Re)if(t.has(e)){let t=Me[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 Ds(e){return $e(e.from,e.to)?Ze(e):null}function Os(e){return qe(e)}var ks=/^convert\(v,\s*"[^"]*",\s*"[^"]*"\)$/;function As(e){return e!==void 0&&ks.test(e.expr)}function js(e){return e===void 0||e.expr===`!v`||ks.test(e.expr)?!1:e.bindings.v!==void 0}function Ms(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=We({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 Ns(e,t,n){if(e===null)return null;let r=Ci(e,n.cap);if(r===null)return e;let i=new Set(Ts(n)),a=Object.fromEntries(Object.entries(r.fields).filter(([e])=>!i.has(e)));return Object.keys(a).length===0?$r(e,n.cap):ni(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 Ps(e){if(typeof e!=`object`||!e)return;let t=Reflect.get(e,`unit`);return typeof t==`string`?t:void 0}function Fs(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 Is(e,t){let n=Ci(e,t.cap);if(n===null)return;let r=n.fields[t.fieldPath];return r!==void 0&&r.kind===`expression`?r:void 0}function Ls(e,t){let n=Is(e,t);return n===void 0||!As(n)?null:/^convert\(v,\s*"[^"]*",\s*"([^"]*)"\)$/.exec(n.expr)?.[1]??null}function Rs(e,t){let n=Is(e,t);return n===void 0||!js(n)?null:n.expr}function zs(e,t,n){let r=Ci(e,t);if(r===null)return!1;let i=r.fields[n];return i!==void 0&&i.kind===`expression`&&i.expr===`!v`}function Bs(e){return typeof e==`number`||typeof e==`boolean`||typeof e==`string`?String(e):e===null?`null`:JSON.stringify(e)}function Vs({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:Es(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(Mo,{availability:{kind:`pending`}})});if(i.nativeCaps.kind===`unknown`)return u(`section`,{className:`${w} ${p}`,children:u(Mo,{availability:{kind:`unknown`,reason:i.nativeCaps.reason}})});if(_===null||_.kind===`absent`)return null;let b=io(n.state),x=_.convert,S=_.invert,C=x===null?void 0:Ps(y),T=C===void 0?void 0:Ge(C)??C,E=T===void 0?void 0:Be(T),D=x===null?null:Ls(b,x),O=x===null?null:Rs(b,x),k=m??O??``,A=S===null?!1:zs(b,S.cap,S.fieldPath),j=n.state.kind===`none`||n.state.kind===`present`,M=x===null?0:Fs(y,x.fieldPath)??0,ee=x!==null&&k.trim()!==``?{kind:`expression`,expr:k.trim(),bindings:{v:{kind:`from`,source:t,cap:x.cap,fieldPath:x.fieldPath}}}:null,N=ee===null||x===null?null:mi(ee,new Map([[Oe(t,x.cap),y===void 0?{kind:`pending`}:{kind:`value`,slice:y}]]),Date.now()),P=async e=>{let t=await n.save(e);l(t.kind===`refused`?t.reason:null)},F=async()=>{if(x===null||T===void 0||d===``)return;let e=Ds({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 P(ni(b,t,e))},I=async()=>{x!==null&&(await P(Ns(b,t,x)),f(``))},L=async()=>{if(x===null)return;let e=Ms({self:t,cap:x.cap,fieldPath:x.fieldPath,expr:k,probe:M});if(e.kind===`refused`){l(e.reason);return}f(``),await P(ni(b,t,e.feature))},te=async()=>{x!==null&&(await P(Ns(b,t,x)),h(``))},R=async()=>{if(S===null)return;let e=Os({self:t,cap:S.cap});if(e===null){l(a(`customize.numericTransforms.invertRefused`));return}await P(ni(b,t,e))},ne=async()=>{S===null||b===null||await P($r(b,S.cap))};return u(Ao,{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(Un,{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 F(),children:a(`customize.numericTransforms.applyConvert`)}),D!==null&&u(X,{size:`sm`,variant:`outline`,disabled:!j||n.saving,onClick:()=>void I(),children:a(`customize.numericTransforms.clearConvert`)})]})]}),x!==null&&r(`div`,{className:`flex flex-col gap-2`,"data-testid":`numeric-script`,children:[u(_i,{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`)}),N!==null&&u(`p`,{role:`status`,className:`text-[11px] font-mono text-foreground`,"data-testid":`numeric-script-preview`,children:N.kind===`value`?a(`customize.numericTransforms.preview`,{source:Bs(M),result:Bs(N.value)}):N.kind===`waiting`?a(`customize.numericTransforms.previewWaiting`):N.kind===`unavailable`?a(`customize.numericTransforms.previewError`,{reason:N.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 L(),children:a(`customize.numericTransforms.applyScript`)}),O!==null&&u(X,{size:`sm`,variant:`outline`,disabled:!j||n.saving,onClick:()=>void te(),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 ne(),children:a(`customize.numericTransforms.clearInvert`)}):u(X,{size:`sm`,disabled:!j||n.saving,onClick:()=>void R(),children:a(`customize.numericTransforms.applyInvert`)})})]})]})})}n();function Hs(e){return e instanceof Error?e.message:String(e)}function Us(e){let n=it({addonId:e.addonId,stableId:e.stableId}),r=Vt(),i=vt(),a=dt(),o=ro({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=ai(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:Hs(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 Ws=`pipeline-orchestrator`;function Gs(e){return e.status===`pending`?`pending`:e.status===`error`?`unknown`:e.data===void 0?`pending`:e.data.cameraSensors===void 0?`absent`:`present`}function Ks(e,t){return e===`absent`?`absent`:Gs(t)}async function qs(e){try{return(await e()).isError?`failed`:`answered`}catch{return`failed`}}function Js(e,t){let n=Gt(Ws),r=Hn({deviceId:e},{enabled:t&&n!==`absent`}),i=()=>qs(r.refetch);return t?{presence:Ks(n,{status:r.status,data:r.data}),status:r.data?.cameraSensors??null,refetch:i}:{presence:`absent`,status:null,refetch:i}}function Ys(e,t){let n=In({deviceType:e.type}),r=dr({deviceId:e.id}),i=ir({deviceId:e.id}),a=No(n,e=>new Set(e.caps.map(e=>e.cap))),o=No(r,e=>Za(e.entries)),s=No(i,e=>e);return{deviceType:e.type,composable:a,nativeCaps:o,wireable:s,composed:new Set((t?.features??[]).map(e=>e.cap))}}var Xs={kind:`unknown`,reason:`the composer reports no value for this field`};function Zs(e,t){let n=q(e);return t.get(n)??n}function Qs(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=gi(e).map(e=>Zs(e,n.sourceNames)).join(` + `),a=i.find(e=>e.field===`lastPressedAt`);return[{key:`doorbell`,label:`doorbell`,origin:{kind:r,from:t},value:a?.value??Xs}]}return e.cap===`consumables`?ci(e).map(e=>{let t=t=>et(tt,e.key,t),a=i.find(e=>e.field===t(`level`)||e.field===t(`remaining.value`)),o=e.source===null?``:Zs(e.source.source,n.sourceNames);return{key:`consumables.${e.key}`,label:`consumables · ${e.label}`,origin:{kind:r,from:o},value:a?.value??Xs}}):i.map(e=>({key:e.key,label:`${e.cap}.${e.field}`,origin:{kind:r,from:e.from},value:e.value}))}function $s(e){let t=di({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`?Qs(n,t,e):[])}function ec(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 tc=`${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)]`,nc=`font-mono text-[11px] text-foreground break-words`,rc=`text-[11px] text-foreground-subtle break-words`,ic=`text-[11px] break-words sm:text-right`;function ac({device:e,composition:t,state:n,nativeCaps:i,cameraSensors:a}){let{t:o}=Z(),s=t!==null&&n!==null,c=Io(s),l=new Map(c.kind===`known`?c.value.map(e=>[q({addonId:e.addonId,stableId:e.stableId}),e.name]):[]),d=s&&i.kind===`known`?$s({composition:t,nativeCaps:i.value,state:n,sourceNames:l}):[],f=s&&i.kind===`known`&&d.length===0&&t.features.length>0,p=ec(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(Ao,{id:`changes`,icon:G,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:tc,children:[u(`span`,{className:nc,children:e.label}),u(`span`,{className:rc,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:ic,children:u(oc,{value:e.value})})]},e.key)),p!==null&&r(`li`,{className:tc,children:[u(`span`,{className:nc,children:`motion`}),u(`span`,{className:rc,children:p}),u(`span`,{className:ic,children:u(Do,{target:{deviceId:e.id,cap:`motion`,path:`detected`}})})]})]})]})}function oc({value:e}){let{t}=Z();switch(e.kind){case`value`:return r(`span`,{children:[hi(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 sc({deviceId:e,activeSubTab:t,onSubTabChange:n}){let{t:r}=Z(),i=vr({deviceId:e}),a=i.data;return a==null?i.status===`error`?u(Et,{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(cc,{device:a}):u(lc,{device:a,target:{addonId:a.addonId,stableId:a.stableId},activeSubTab:t,onSubTabChange:n})}function cc({device:e}){let{t}=Z(),n=e.stableId.startsWith(`composed-`)?e.stableId.slice(Ie.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(Pr,{className:`text-[11px] text-primary hover:underline`,to:Zr(n),children:t(`customize.composed.edit`)})]})}function lc({device:e,target:t,activeSubTab:n,onSubTabChange:i}){let a=Us(t),o=Gt(`composer`),{t:s}=Z(),c=Js(e.id,e.type===J.Camera),l=Ys(e,io(a.state)),d={deviceType:e.type,composable:l.composable,nativeCaps:l.nativeCaps,cameraSensors:c.presence},f=()=>i(Kr),p=a.state.kind===`none`||a.state.kind===`present`;return n===`advanced`?r(`div`,{className:`flex flex-col gap-3`,children:[u(dc,{state:a.state}),p&&u(uc,{device:e,target:t,handle:a,facts:l,onDone:()=>i(`main`)})]}):r(`div`,{className:`flex flex-col gap-3`,children:[u(mo,{device:e}),o===`absent`&&u(`p`,{role:`alert`,className:`text-xs text-warning`,children:s(`customize.composerAbsent`)}),a.state.kind!==`none`&&u(dc,{state:a.state}),u(as,{device:e,handle:a,availability:to(`doorbell`,d),onAdvanced:f}),u(Ss,{device:e,handle:a,availability:to(`motion`,d),sensors:c}),u(Bo,{device:e,handle:a,availability:to(`battery`,d),onAdvanced:f}),u(Uo,{device:e,handle:a,availability:to(`consumables`,d),onAdvanced:f}),u(Vs,{device:e,target:t,handle:a,facts:l}),u(cs,{device:e}),u(ac,{device:e,composition:io(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(no,{onAdvanced:f}):u(`span`,{}),u(fc,{handle:a})]})]})}function uc({device:e,target:t,handle:n,facts:r,onDone:i}){let a=n.state.kind===`present`?n.state:null;return u(yi,{initial:a===null?ei(t):ti(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 dc({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(Et,{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 fc({handle:e}){let{t}=Z(),n=Qt(),[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 pc=`overview`;function mc(e,t){return e.some(e=>e.id===t)?t:pc}function hc({deviceId:e}){let{t}=Z(),n=s(),i=Number.isFinite(e),{data:a}=vr({deviceId:e},{enabled:i}),o=typeof a?.type==`string`?a.type:`camera`;sr([`deviceManager`,`getBindings`],[`capability.binding-changed`]);let{data:c,isLoading:l,isError:d,error:f}=dr({deviceId:e},{enabled:i}),{data:p}=On({deviceType:o},{enabled:!!o}),m=Dr({onSuccess:()=>{n.invalidateQueries({queryKey:[[`deviceManager`,`getBindings`]]})}});if(l)return u(`div`,{className:`p-4`,children:u(`div`,{className:`h-20 rounded-lg border border-border bg-surface animate-pulse`})});if(d)return r(`div`,{className:`p-4 text-xs text-red-400`,children:[t(`device.bindingsTab.failedToLoadBindings`,`Failed to load bindings:`),` `,f instanceof Error?f.message:String(f)]});let h=new Map,g={};for(let e of p??[])g[e.capName]=e.wrappers;for(let e of c?.entries??[])h.set(e.capName,{...e,wrappers:g[e.capName]??[]});for(let e of p??[])h.has(e.capName)||h.set(e.capName,{capName:e.capName,kind:`unbound`,providerAddonId:``,providerNodeId:``,nativeAddonId:``,wrappers:e.wrappers});let _=[...h.values()].toSorted((e,t)=>e.capName.localeCompare(t.capName));if(_.length===0)return r(`div`,{className:`flex flex-col items-center justify-center gap-2 p-8 text-foreground-subtle`,children:[u(Se,{className:`h-8 w-8 opacity-40`}),u(`p`,{className:`text-xs`,children:t(`device.bindingsTab.noCapabilityProvidersApplicableTo`,`No capability providers applicable to this device yet.`)}),u(`p`,{className:`text-[10px] opacity-60`,children:t(`device.bindingsTab.nativeProvidersShowUpHere`,`Native providers show up here as soon as the owning addon registers them.`)})]});let v=_.filter(e=>e.kind!==`unbound`).length,y=[{key:`capability`,header:t(`device.bindingsTab.capability`,`Capability`),render:e=>u(`span`,{className:`font-mono text-foreground`,children:e.capName})},{key:`kind`,header:t(`device.bindingsTab.kind`,`Kind`),render:e=>u(gc,{kind:e.kind})},{key:`provider`,header:t(`device.bindingsTab.activeProvider`,`Active Provider`),render:e=>u(`span`,{className:`font-mono text-foreground-subtle`,children:e.providerAddonId||u(`span`,{className:`opacity-40`,children:`—`})})},{key:`node`,header:t(`device.bindingsTab.node`,`Node`),render:e=>e.providerNodeId?u(_c,{nodeId:e.providerNodeId}):u(`span`,{className:`text-[10px] opacity-40`,children:`—`})},{key:`native`,header:t(`device.bindingsTab.native`,`Native`),render:e=>u(`span`,{className:`font-mono text-foreground-subtle`,children:e.nativeAddonId||u(`span`,{className:`opacity-40`,children:`—`})})},{key:`wrapper`,header:t(`device.bindingsTab.wrapper`,`Wrapper`),render:t=>{let n=t.kind===`wrapped`?t.providerAddonId:null;return u(vc,{wrappers:t.wrappers,activeWrapperId:n,disabled:m.isPending,onPick:r=>{let i=n===r;m.mutate({deviceId:e,capName:t.capName,wrapperAddonId:r,active:!i})}})}}];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:v}),` of `,_.length,` capabilit`,_.length===1?`y`:`ies`,` bound — rows marked `,u(`em`,{children:`unbound`}),` have a wrapper available you can activate.`]}),u(gt,{columns:y,rows:_,rowKey:e=>e.capName,minWidthPx:720})]})}function gc({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(re,{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 _c({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 vc({wrappers:e,activeWrapperId:t,disabled:n,onPick:i}){let{t:a}=Z();return e.length===0?u(`span`,{className:`text-[10px] opacity-40`,children:a(`device.bindingsTab.noneAvailable`,`none available`)}):u(`div`,{className:`flex flex-wrap gap-1`,children:e.map(e=>{let o=e===t;return r(`button`,{disabled:n,onClick:()=>i(e),title:o?a(`device.bindingsTab.clickToDeactivateRevertTo`,`Click to deactivate (revert to native)`):a(`device.bindingsTab.activateWrapper`,`Activate wrapper {{wrapperId}}`,{wrapperId: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 ${o?`border-primary/40 bg-primary/10 text-primary`:`border-border text-foreground-subtle hover:text-foreground hover:bg-surface-hover`}`,children:[u(o?z:fe,{className:`h-3 w-3`}),e]},e)})})}function yc({deviceId:e,activeSubTab:t,onSubTabChange:n,deviceType:i,isAdmin:a}){return r(`div`,{className:`flex flex-col gap-3`,children:[Ar(i,a)&&u(Mt,{deviceId:e,readOnly:!0}),u(Rr,{deviceId:e,activeSubTab:t,onSubTabChange:n})]})}n();var bc=[[`pipelineOrchestrator`,`getCameraDetectionSource`]];function xc(t){let n=s(),r=ut({deviceId:t},{refetchOnMount:`always`}),i=$t(),[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:bc})}catch(e){u(e instanceof Error?e.message:`Could not change the root detector`),await n.invalidateQueries({queryKey:bc})}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 Sc=`object-detection`;function Cc(e){return[e.addonId,...e.children.flatMap(Cc)]}function wc(e,t){if(e===`pipeline`)return new Set;let n=Tc(t,Sc);return n===void 0?new Set:new Set(e===`onboard`?[n.addonId]:Cc(n))}function Tc(e,t){for(let n of e){if(n.addonId===t)return n;let e=Tc(n.children,t);if(e!==void 0)return e}}function Ec(e,t){return e===`onboard`?`Camera AI`:t===`object-detection`?`No root`:`Idle`}function Dc(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 Oc(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 kc(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 Ac({source:e,geometry:t,saving:n,error:i,onPick:a}){let{t:o}=Z(),s=t===`flag-only`,c=Oc(t);return r(`section`,{"aria-label":o(`device.detectionSourceControl.rootDetector`,`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:ee,children:o(`device.detectionSourceControl.rootDetector`,`Root detector`)}),u(zn,{label:o(`device.detectionSourceControl.rootDetector`,`Root detector`),value:e,onChange:t=>{!n&&t!==e&&a(t)},options:[{value:`pipeline`,label:o(`device.detectionSourceControl.thisNode`,`This node`)},{value:`onboard`,label:o(`device.detectionSourceControl.cameraOnboardAi`,`Camera onboard AI`),disabled:s&&e!==`onboard`,reason:c},{value:`none`,label:o(`device.detectionSourceControl.none`,`None`)}]}),n&&u(`span`,{className:`text-[10px] text-foreground-subtle`,children:o(`device.detectionSourceControl.saving`,`Saving…`)})]}),r(`p`,{className:he,children:[Dc(e),` A camera runs one root detector at a time.`]}),c!==``&&u(`p`,{className:`text-[10px] text-foreground-subtle`,children:c}),i!==null&&u(`p`,{role:`alert`,className:`text-[11px] text-danger`,children:i})]})}n();var jc=new Set([`package-detection`]);function Mc(e){return e?.settings!==void 0&&Object.keys(e.settings).length>0?`accelerator`:`camera`}function Nc(e){return e===`camera`?`this camera`:e===`node`?`node pin`:`hardware default`}function Pc(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 Fc(e,t){return(e?.modelId??null)===(t?.modelId??null)&&Ke(e?.settings??{},t?.settings??{})}function Ic({deviceId:e}){let{t}=Z(),n=s(),l=W().trpcClient,d=Nt({deviceId:e},{refetchOnMount:`always`}),f=Rn({deviceId:e},{refetchOnMount:`always`}),p=Kt(void 0,{refetchOnMount:`always`}),m=Te(Yn({addonId:`pipeline-orchestrator`}).data??null);sr([`nodes`,`topology`],[`agent.online`,`agent.offline`,`agent.unregistered`,`addon.installed`,`addon.uninstalled`]);let{nodes:h}=En(),g=i(()=>{let e=new Set((p.data??[]).map(e=>e.nodeId));return h.filter(t=>t.isOnline&&e.has(t.id)).map(e=>({id:e.id,name:e.name}))},[p.data,h]),_=g.map(e=>e.id).join(`,`),v=a({enabled:g.length>0,queryKey:[[`pipelineExecutor`,`getSchema`],`camera-step-schemas`,_],queryFn:async()=>{let e={};for(let t of g)try{e[t.id]=await l.pipelineExecutor.getSchema.query({nodeId:t.id})}catch{}return e}}),y=a({enabled:g.length>0,queryKey:[[`pipelineOrchestrator`,`getNodeInferenceDevices`],`camera-step`,_],queryFn:async()=>{let e={};for(let t of g)try{e[t.id]=(await l.pipelineOrchestrator.getNodeInferenceDevices.query({nodeId:t.id})).devices}catch{e[t.id]=[]}return e}}),b=()=>{n.invalidateQueries({queryKey:[[`pipelineOrchestrator`,`getCameraSettings`]]}),n.invalidateQueries({queryKey:[[`pipelineOrchestrator`,`getCameraStepOverrides`]]})},x=hr({onSuccess:b}),S=nt(),C=bn(),[w,T]=c(null),[E,D]=c(null),[O,k]=c(null),[A,j]=c(!1),[M,N]=c(null),P=v.data??{},F=y.data??{},I=f.data??{},L=d.data??null,te=g.map(e=>P[e.id]).find(e=>e!==void 0)??null,R=i(()=>te?Rt(te):[],[te]),ne=i(()=>Mi(R),[R]),z=xc(e),B=i(()=>z.source===null?new Set:wc(z.source,R),[z.source,R]),[V,re]=c(!1),ie=i(()=>Fi(g,F,V),[g,F,V]),ae=i(()=>Fi(g,F,!0),[g,F]),oe=i(()=>Fi(g,F).length,[g,F]),H=(e,t)=>Ei(P[e.nodeId],t),U=(e,t)=>I[e.nodeId]?.[e.deviceKey]?.[t],se=(e,t)=>Bi(F[e.nodeId]??[],e.deviceKey,t)??{},ce=e=>{if(jc.has(e))return{kind:`zone-driven`};let t=Ei(te,e)?.enabledByDefault??!0,n=L?.stepToggles?.[e];return{kind:`gate`,effectiveOn:n??t,defaultOn:t,explicit:n!==void 0}},le=(e,t,n)=>{let r=n?.stepId===t?n:null;return{node:se(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},ue=(e,t)=>{if(B.has(e))return{kind:`disabled`};let n=H(t,e),r=ce(e),i=Pi(e),a=Di(P[t.nodeId],t,U(t,`object-detection`)?.modelId),o=le(t,e,null),s=Je(o.node,o.camera,o.accelerator);return Li({addon:n,acc:t,gatedOn:r.kind===`gate`?r.effectiveOn:!0,model:n?Ni(n,t,{nodePin:t.device.steps?.[e]?.modelId,cameraPin:U(t,e)?.modelId}):{modelId:void 0,source:`default`},...Ai(e,s,a)&&a?{rootName:a.name}:{},...i?{clusterModelId:m[e]??i.defaultModelId}:{}})},de=ne.map(({node:e})=>({addonId:e.addonId,name:e.addonName,fieldLabels:Ii(Ei(te,e.addonId))}));return p.isLoading||g.length>0&&(v.isLoading||y.isLoading)?u(`div`,{className:`animate-pulse p-4 text-xs text-foreground-subtle`,children:t(`device.cameraStepInspector.loadingPipeline`,`Loading pipeline…`)}):g.length===0?u(`div`,{className:`p-4 text-xs text-foreground-subtle`,children:t(`device.cameraStepInspector.noPipelineNodeIsOnline`,`No pipeline node is online.`)}):te===null?u(`div`,{className:`p-4 text-xs text-foreground-subtle`,children:t(`device.cameraStepInspector.catalogUnavailable`,`Catalog unavailable.`)}):r(`div`,{className:`space-y-2`,children:[z.view?.onboard.available===!0&&z.source!==null&&u(Ac,{source:z.source,geometry:z.view.onboard.geometry,saving:z.saving,error:z.error,onPick:e=>void z.pick(e)}),u(Ti,{tree:R,searchRows:de,accelerators:ie,cellState:ue,stepBadge:e=>B.has(e)&&z.source!==null?u(on,{variant:`warning`,title:kc(z.source,e),children:Ec(z.source,e)}):u(rt,{gate:ce(e)}),disabledCount:zi(Object.fromEntries(g.map(e=>[e.id,F[e.id]??[]]))),showDisabled:V,onShowDisabledChange:re,dirty:w!==null,onDiscard:()=>T(null),summary:r(`span`,{className:he,children:[`This camera is balanced across `,oe,` accelerator`,oe===1?``:`s`,` at every session start · ovr = this camera overrides the node`]}),label:t(`device.cameraStepInspector.detectionStepsOfThisCamera`,`Detection steps of this camera`),renderDetail:({stepId:n,accelerator:i,matchedField:a,closeButton:s,onEscape:c,headingRef:l})=>{let d=i??ie[0],f=d?H(d,n)??Ei(te,n):null;if(f===null||d===void 0)return u(`div`,{className:`p-4 text-xs text-foreground-subtle`,children:t(`device.cameraStepInspector.noStepSelected`,`No step selected.`)});let p=w?.stepId===n?w:null,m=Wn(f),h=Le(m),g=le(d,n,p),_=Je(g.node,g.camera,g.accelerator),v=Di(P[d.nodeId],d,U(d,`object-detection`)?.modelId),y=Ni(f,d,{nodePin:d.device.steps?.[n]?.modelId,cameraPin:G(d,n,p)}).modelId,F=Je(g.node,g.camera),I=ze(g.accelerator,F,h),R=Pi(n),ne=ce(n),V=m.find(e=>`label`in e&&e.label===a)?.key??null,re=i===null?null:`${n}|${i.id}`,oe=i===null?`camera`:E?.key===re?E.scope:Mc(U(i,n)),W=e=>{N(null),T(t=>e(t?.stepId===n?t:{stepId:n,perAccelerator:{}}))},ue=(e,t)=>W(n=>({...n,perAccelerator:{...n.perAccelerator,[e.id]:{...n.perAccelerator[e.id],...t}}})),de=e=>W(t=>{let r=g.accelerator??{},i=Ve(t.camera??L?.stepSettings?.[n],e,r,h),a={...t.perAccelerator};for(let r of ae){let i=t.perAccelerator[r.id]?.settings??U(r,n)?.settings;i!==void 0&&(a[r.id]={...a[r.id],settings:Pe(i,e,h)})}return{...t,camera:i,perAccelerator:a}}),fe=async()=>{if(p!==null){j(!0);try{let t=L?.stepSettings?.[n];p.camera!==void 0&&!Ke(p.camera,t??{})&&await C.mutateAsync({deviceId:e,addonId:n,settings:Object.keys(p.camera).length>0?{...p.camera}:null});let r=p.camera??t;for(let t of ae){let i=p.perAccelerator[t.id];if(i===void 0)continue;let a=U(t,n),o=Pc({stored:a,draft:i,below:Je(se(t,n),r),boundKeys:h});Fc(o,a)||await S.mutateAsync({deviceId:e,agentNodeId:t.nodeId,deviceKey:t.deviceKey,addonId:n,patch:o})}T(null),N({kind:`saved`})}catch(e){N({kind:`error`,error:e instanceof Error?e.message:`Save failed`})}finally{j(!1),b()}}},pe=p===null?0:+(p.camera!==void 0&&!Ke(p.camera,L?.stepSettings?.[n]??{}))+Object.values(p.perAccelerator).length,me=e=>{let t=H(e,n)??f,i=G(e,n,p),a=e.device.steps?.[n]?.modelId,s=Ni(t,e,{nodePin:a,cameraPin:i}),c=le(e,n,p),l=Di(P[e.nodeId],e,U(e,`object-detection`)?.modelId),d=Ai(n,Je(c.node,c.camera,c.accelerator),l),m=Oi(t,e)?d&&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:Nc(s.source),models:kn(t.models??[],e.device.format),defaultModelId:t.defaultModelIdByFormat?.[e.device.format]??t.defaultModelId,expanded:O===e.id,onToggle:()=>k(t=>t===e.id?null:e.id),onChangeModel:t=>ue(e,{modelId:t}),...i===void 0?{}:{onReset:()=>ue(e,{modelId:null}),resetLabel:a===void 0?`Reset to hardware default`:`Reset to node pin`},...m===void 0?{}:{note:m},changed:p?.perAccelerator[e.id]?.modelId!==void 0}},ge=R===null&&m.length>0?i===null?u(`p`,{className:he,children:t(`device.cameraStepInspector.appliesToAllAcceleratorsOf`,`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:t(`device.cameraStepInspector.appliesTo`,`Applies to`)}),u(zn,{label:t(`device.cameraStepInspector.settingsApplyTo`,`Settings apply to`),options:[{value:`accelerator`,label:t(`device.cameraStepInspector.thisAccelerator`,`This accelerator`)},{value:`camera`,label:t(`device.cameraStepInspector.allAcceleratorsOfThisCamera`,`All accelerators of this camera`)}],value:oe,onChange:e=>re!==null&&D({key:re,scope:e})})]}):void 0;return u(zt,{ref:l,title:i===null?t(`device.cameraStepInspector.thisCamera`,`{{name}} · this camera`,{name:f.name}):`${f.name} · ${i.label}`,subtitle:i===null?t(`device.cameraStepInspector.everyAcceleratorThisCameraRuns`,`{{slot}} · every accelerator this camera runs on`,{slot:f.slot}):`${f.slot} · ${i.device.format}`,leading:s,onEscape:c,headerActions:u(Fn,{gate:ne,busy:x.isPending,onSet:t=>x.mutate({deviceId:e,addonId:n,enabled:t})}),saveBar:{dirtyCount:pe,saving:A,status:M?.kind??null,...M?.error===void 0?{}:{error:M.error},onSave:()=>void fe(),onDiscard:()=>T(null),...ge===void 0?{}:{scope:ge}},children:r(`div`,{className:`space-y-3`,children:[B.has(n)&&z.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:kc(z.source,n)}),r(`section`,{className:`space-y-2`,"aria-label":t(`device.cameraStepInspector.model`,`Model`),children:[u(`h3`,{className:ee,children:t(`device.cameraStepInspector.model`,`Model`)}),R===null?i===null?u(ki,{rows:ie.map(e=>{let t=Ni(H(e,n)??f,e,{nodePin:e.device.steps?.[n]?.modelId,cameraPin:G(e,n,p)});return{id:e.id,label:e.label,modelId:t.modelId,sourceLabel:Nc(t.source)}})}):u(xr,{...me(i)},i.id):u(Ri,{step:R,engineFormat:d.device.format,runnableModelIds:kn(f.models??[],d.device.format).map(e=>e.id)})]}),R===null&&(m.length>0||v!==void 0)&&u(`section`,{"aria-label":t(`device.cameraStepInspector.settings`,`Settings`),className:`border-t border-border/60 pt-2`,children:u(Lc,{addon:f,fields:m,layers:g,scope:oe,viewed:i,modelId:fn(f,y,_,v),root:v,pinned:i===null?[]:I,highlightKey:V,onChangeCamera:e=>W(t=>({...t,camera:e})),onChangeAccelerator:e=>ue(d,{settings:e}),onApplyToAll:de,onFollowNode:()=>ue(d,{settings:I.reduce((e,t)=>Pe(e,t,h),{...g.accelerator})})})}),u(wi,{addonId:n,highlightLabel:a})]})})}})]})}function Lc({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}){let{t:h}=Z();ji(l===null?null:_n(l));let g=a!==null&&n.accelerator!==void 0;return u(br,{addon:e,fields:t,layers:{node:n.node,...n.camera===void 0?{}:{camera:n.camera},...g?{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:U,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:U,onClick:()=>p(e),children:h(`device.cameraStepInspector.applyToAllAccelerators`,`Apply to all accelerators`)}):null})}var Rc=[{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`}],zc={"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 Bc(e){return zc[e]??`object-detection`}n();var Vc=`steps`,Hc=`settings`,Uc=new Set([Vc,Hc]);function Wc(e){return e.location===`top-tab`&&(e.tab===`detection-pipeline`||e.tab===`zones`)}function Gc({deviceId:t,activeSubTab:n,onSubTabChange:i}){let{t:a}=Z();return r(xn,{value:n&&Uc.has(n)?n:Vc,onValueChange:e(e=>{i?.(e)},[i]),className:`flex flex-col`,children:[r(Zn,{className:`flex-shrink-0`,children:[u(cr,{value:Vc,children:a(`device.detectionPipelineTab.steps`,`Steps`)}),u(cr,{value:Hc,children:a(`device.detectionPipelineTab.settings`,`Settings`)})]}),u(gr,{value:Vc,children:u(Ic,{deviceId:t})}),u(gr,{value:Hc,children:u(Rr,{deviceId:t,sectionFilter:Wc,subTabGrouping:{groupOf:e=>Bc(e.id),tabs:Rc}})})]})}var Kc=`Notifications`,qc=`This camera never notifies — no rule, no target, no alarm. Existing events, tracks and recordings are unaffected.`;function Jc(e){let{mutedDeviceIds:t,deviceId:n}=e,r=t===null?null:!t.includes(n),i=e.pendingOn??null;return{label:Kc,on:r===null?null:i??r,available:r!==null,costWhenOff:qc}}function Yc(e,t){return!e.available||e.on===null?null:{deviceId:t,muted:e.on}}n();function Xc(e){if(typeof e!=`object`||!e)return null;let t={...e}.mutedDeviceIds;return Array.isArray(t)?t.filter(e=>typeof e==`number`):null}function Zc({deviceId:t}){let{t:n}=Z(),i=s(),a=Number.isFinite(t),[o,l]=c(null),[d,f]=c(null),p=Jc({mutedDeviceIds:Xc(lr({},{enabled:a}).data),deviceId:t,pendingOn:d}),h=sn({onError:e=>{console.error(`[DeviceNotificationMute] mute write failed — reverting`,{tags:{deviceId:t},meta:{error:e instanceof Error?e.message:String(e)}}),f(null),l(e instanceof Error?e.message:String(e)),i.invalidateQueries({queryKey:[[`notificationRules`,`listDeviceMutes`]]})},onSuccess:()=>{l(null),f(null),i.invalidateQueries({queryKey:[[`notificationRules`]]})}}),g=e(()=>{let e=Yc(p,t);e!==null&&(f(!e.muted),h.mutate(e))},[t,h,p]),_=p.on===null,v=p.on===!1,y=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:n(`device.deviceNotificationMute.notifications`,`Notifications`)}),v&&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":p.label,"aria-checked":p.on===!0,disabled:!p.available||h.isPending,onClick:g,title:_?n(`device.deviceNotificationMute.notificationMuteStateUnknownThe`,`Notification mute — state unknown; the notification centre did not answer.`):v?n(`device.deviceNotificationMute.muted`,`Muted. {{costWhenOff}}`,{costWhenOff:p.costWhenOff}):n(`device.deviceNotificationMute.notifyingMutingIt`,`Notifying. Muting it: {{costWhenOff}}`,{costWhenOff:p.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 ${o===null?_?`border-dashed border-border text-foreground-subtle/50`:v?`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(y,{className:`h-3.5 w-3.5`}),u(`span`,{children:_?n(`device.deviceNotificationMute.unknown`,`Unknown`):v?n(`device.deviceNotificationMute.muted2`,`Muted`):n(`device.deviceNotificationMute.notifying`,`Notifying`)})]}),u(`p`,{className:`flex-1 text-[11px] leading-relaxed text-foreground-subtle`,children:o===null?_?n(`device.deviceNotificationMute.theNotificationCentreDidNot`,`The notification centre did not answer, so this device’s mute state is unknown.`):p.costWhenOff:n(`device.deviceNotificationMute.writeFailed`,`Write failed: {{failure}}`,{failure:o})})]})]})}function Qc(e,t){return{switchId:e,label:He[e].label,detail:t===void 0||t.length===0?null:t}}function $c(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 el(e){let t=$c(e),n=new Set(e.sourceStillLive),r=e.sourceStillLive.map(e=>Qc(e,t.get(e)?.detail)),i=[...t.values()].filter(e=>e.outcome===`not-offered`&&!n.has(e.switchId)).map(e=>Qc(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 tl(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 nl({deviceId:e,deviceName:t}){let{t:n}=Z(),a=Qt(),[o,s]=c(null),l=qn({isCamera:!0,projection:`slim`}),d=ln(),f=l.data!==void 0,p=i(()=>l.data===void 0?[]:tl(l.data,e),[l.data,e]),m=p.find(e=>e.id===o)??null,h=d.data===void 0?null:el(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(rl,{report:h})]})}function rl({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(ie,{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(B,{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 il({deviceId:e}){let{t}=Z(),[n,i]=c(null),a=Pt({onSuccess:e=>{i(e.changed?`Re-aligned with source — ${e.rebuiltChildren} child${e.rebuiltChildren===1?``:`ren`} rebuilt.`:`Already up to date.`)},onError:e=>i(`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:t(`device.resyncButton.reSync`,`Re-sync`)}),u(`p`,{className:`mt-0.5 text-[11px] text-foreground-subtle`,children:t(`device.resyncButton.reAlignThisDeviceS`,`Re-align this device's type, role, capabilities and units with its source.`)})]}),r(`button`,{type:`button`,disabled:a.isPending,onClick:()=>{i(null),a.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 ${a.isPending?`animate-spin`:``}`}),a.isPending?t(`device.resyncButton.reSyncing`,`Re-syncing…`):t(`device.resyncButton.reSync`,`Re-sync`)]})]}),n!==null&&u(`p`,{className:`mt-2 text-[11px] text-foreground-subtle`,children:n})]})}function al(e){return e<1e3?`${e.toFixed(0)} kbps`:`${(e/1e3).toFixed(1)} Mbps`}function ol({device:e}){let{t}=Z(),n=Wr(),i=typeof e.id==`number`?e.id:null,a=String(e.type??``),o=a===J.Camera,s=a===J.Hub,c=e.features??[],l=c.includes(Ee.Resyncable),{data:d}=Xt({deviceId:i??0},{enabled:i!==null&&o,refetchInterval:5e3}),f=d?.streams??{},p=Object.entries(f),m=c.includes(Ee.DoorbellButton),h=jn(m?{deviceId:i??void 0,historyLimit:10}:void 0),g=h.latest?Date.now()-h.latest.timestamp<3e4:!1;return r(`div`,{className:`space-y-5`,children:[s&&i!==null&&u(or,{deviceId:i,onOpenChild:e=>n(`/devices/${e}`)}),l&&i!==null&&u(il,{deviceId:i}),o&&i!==null&&u(nl,{deviceId:i,deviceName:String(e.name??``)}),i!==null&&u(Zc,{deviceId:i}),o&&i!==null&&u(Sr,{widgetId:`pipeline-orchestrator/pipeline-quick-stats`,host:`device-tab`,deviceId:i}),m&&u(St,{history:h.history,latestIsFresh:g}),o&&i!==null&&u(Sr,{widgetId:`stream-broker/stream-broker-panel`,host:`device-tab`,deviceId:i}),o&&p.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:t(`device.overviewTab.streamNetwork`,`Stream Network`)})}),u(`div`,{className:`divide-y divide-border`,children:p.map(([e,n])=>r(`div`,{className:`px-4 py-2.5`,children:[r(`div`,{className:`flex items-center gap-2 mb-2`,children:[u(H,{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(sl,{label:t(`device.overviewTab.nominal`,`Nominal`),value:al(n.nominalBitrateKbps??0)}),u(sl,{label:t(`device.overviewTab.observed`,`Observed`),value:al(n.observedBitrateKbps??0)}),u(sl,{label:t(`device.overviewTab.peak`,`Peak`),value:al(n.peakBitrateKbps??0)}),u(sl,{label:t(`device.overviewTab.packetLoss`,`Packet Loss`),value:`${(n.packetLossPercent??0).toFixed(2)}%`,warning:(n.packetLossPercent??0)>1})]})]},e))})]}),u(Qr,{}),i!==null&&u(Mr,{deviceId:i})]})}function sl({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 cl=[{id:`overview`,label:`Overview`,cameraOnly:!1,adminOnly:!1},{id:`config`,label:`Config`,cameraOnly:!1,adminOnly:!1},{id:Xr,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 ll(e,t){let n=e===J.Camera;return cl.filter(e=>(n||!e.cameraOnly)&&(t||!e.adminOnly)).map(({id:e,label:t})=>({id:e,label:t}))}function ul({provider:e,integrationId:t,name:n}){let r=Wr(),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(Fr,{type:e,size:`lg`})})}n();var dl=[{id:`logs`,icon:oe,label:`Logs`},{id:`repl`,icon:K,label:`REPL`},{id:`events`,icon:T,label:`Events`},{id:`state`,icon:x,label:`State`}];function fl(){let{t:n}=Z(),a=Gr(),l=Number(a.deviceId),d=Number.isFinite(l),f=Wr(),p=s(),m=Qt(),h=W(),{user:g}=Br(),v=g?.isAdmin===!0,[y,b]=zr(),x=y.get(`tab`)??`overview`,S=y.get(`sub`),[C,w]=c(`logs`),T=`device-detail.left-col-width-px`,[E,D]=c(()=>{if(typeof window>`u`)return null;let e=window.localStorage.getItem(T),t=e?Number(e):NaN;return Number.isFinite(t)&&t>0?t:null}),O=t(E);O.current=E;function k(e){e.preventDefault();let t=e.clientX,n=e.currentTarget.previousElementSibling?.getBoundingClientRect().width??E??0,r=Math.max(330,Math.floor(window.innerWidth*.7)),i=e=>{D(Math.max(280,Math.min(r,n+(e.clientX-t))))},a=()=>{document.removeEventListener(`mousemove`,i),document.removeEventListener(`mouseup`,a);let e=O.current;if(e!==null)try{window.localStorage.setItem(T,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:A,isLoading:j,isError:ee}=vr({deviceId:l},{enabled:d,refetchInterval:5e3,retry:1}),{data:P}=gn({deviceId:l},{enabled:d}),F=i(()=>{let e=P?.settings?.sections??[],t=P?.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(Lr)&&r.add(qr),[...r].map(e=>e===`export`?{id:e,label:Ir,isAddonContrib:!0}:{id:e,label:Fe[e]?.label??e,isAddonContrib:!0})},[P]),I=A,L=String(I?.name??a.deviceId??`Device`),R=I?.online===!0,ne=R?`online`:`offline`,z=String(I?.addonId??`rtsp`),B=I?.features??[],V=I?.type,re=V===J.Camera,{data:ie}=Hr(d?l:0),ae=V===J.Container,oe=i(()=>(ie??[]).map(e=>({id:e.id,stableId:e.stableId,type:e.type,...e.sourceInfo?{sourceInfo:{id:e.sourceInfo.id}}:{}})),[ie]),H=i(()=>ae?Dn(oe,typeof I?.linkDeviceId==`number`?I.linkDeviceId:null,typeof I?.primaryChildEntityId==`string`?I.primaryChildEntityId:null)?.id??null:null,[ae,oe,I?.linkDeviceId,I?.primaryChildEntityId]),{data:U}=gn({deviceId:H??0},{enabled:H!==null}),se=i(()=>{if(H===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:Fe[e]?.label??e,isAddonContrib:!0,childDeviceId:H}))},[H,U]),ce=typeof I?.parentDeviceId==`number`?I.parentDeviceId:null,{data:le}=vr({deviceId:ce??0},{enabled:ce!==null}),G=Pn(),de=I?.disabled!==!0,fe=i(()=>{let e=P?.settings?.sections??[],t=P?.live?.sections??[];return Jr([...e,...t],V,v,P!==void 0)},[P,V,v]),he=i(()=>{let e=new Set,t=[];for(let n of[...ll(V,v),...F,...se])n.id===`config`&&!fe||e.has(n.id)||(e.add(n.id),t.push(n));return t},[V,v,F,se,fe]),ge=i(()=>mc(he,x),[he,x]),_e=e(e=>{b(t=>{let n=new URLSearchParams(t);e===`overview`?n.delete(`tab`):n.set(`tab`,e),n.delete(`sub`);for(let e of Vi)n.delete(e);return n},{replace:!0})},[b]),ve=e(e=>{b(t=>{let n=new URLSearchParams(t);return n.set(`sub`,e),n},{replace:!0})},[b]),ye=(ie??[]).length>0,be=i(()=>dl.filter(({featureGate:e})=>!e||B.includes(e)),[B]),{data:xe}=pn(void 0),Se=i(()=>I?Qn(I,xe):null,[I,xe]),K=Se?.kind===`resolved`?Se.integration:null,Ce=K===null?Se?.kind===`unknown`?`Loading integration…`:Se?.kind===`orphan`?`Missing integration`:`No integration`:K.name,we=K!==null&&K.addonId===z?K.name:z,Te=st({onSuccess:()=>{p.invalidateQueries({queryKey:[[`deviceManager`]]}),f(K?.id?`/integrations/${K.id}`:`/integrations`)}}),De=tr({onSuccess:()=>{p.invalidateQueries({queryKey:[[`deviceManager`]]})}}),q=mr({onSuccess:()=>{p.invalidateQueries({queryKey:[[`deviceManager`]]})}}),Oe=Bt(),ke=kt({onSuccess:()=>{p.invalidateQueries({queryKey:[[`deviceManager`]]})}}),Ae=B.includes(Ee.Rebootable),je=B.includes(Ee.BatteryOperated),Me=Gn(h.trpcClient,je&&d?l:null),Ne=mn(h.trpcClient,d?l:null),[Pe,Ie]=c(!1),Le=async()=>{if(!Pe){Ie(!0);try{let e=L.replace(/[^a-zA-Z0-9_.-]+/g,`_`),t=new Date().toISOString().replace(/[:.]/g,`-`);await na(`${N}/${String(l)}.jpg?force=1`,`${e}-${t}.jpg`)}finally{Ie(!1)}}},Re=De.isPending||q.isPending,{data:ze}=bt({deviceId:l},{enabled:d,refetchInterval:1e4}),Be=ze?.agentNodeId??null,Ve=typeof Be==`string`&&Be.length>0&&!Be.startsWith(`addon:`)?Be:void 0,{data:He}=yr({deviceId:l,...Ve?{nodeId:Ve}:{}},{enabled:d,refetchInterval:3e3,retry:!1}),{data:Ue}=xt({deviceId:l},{enabled:d,refetchInterval:3e3,retry:!1}),Y=Ue?.level?.dbfs??null;function We(){if(!d)return null;switch(ge){case`overview`:return u(ol,{device:I??{}});case`config`:return u(yc,{deviceId:l,activeSubTab:S,onSubTabChange:ve,deviceType:V,isAdmin:v});case`detection-pipeline`:return u(Gc,{deviceId:l,activeSubTab:S,onSubTabChange:ve});case`bindings`:return u(hc,{deviceId:l});case Xr:return u(sc,{deviceId:l,activeSubTab:S,onSubTabChange:ve});default:{let e=ge,t=F.some(t=>t.id===e),n=se.find(t=>t.id===e);if(!t&&n===void 0)return null;let r=n?.childDeviceId??l;if(e===`export`)return u(Rr,{deviceId:l,sectionFilter:Lr,activeSubTab:S,onSubTabChange:ve});let i=u(Rr,{deviceId:r,sectionFilter:t=>t.location===`top-tab`&&(t.tab===e||e===`detection-pipeline`&&t.tab===`zones`),flattenSubTabs:e===`detection-pipeline`,activeSubTab:S,onSubTabChange:ve});return n!==void 0&&r!==l?u(wt,{deviceId:r,children:i}):i}}}return d?j?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`})})]}):ee||!A?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:n(`deviceDetail.deviceNotFound`,`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:[`#`,l]})]}),u(`button`,{onClick:()=>f(`/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:n(`deviceDetail.backToIntegrations`,`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(Tt,{items:[{label:n(`deviceDetail.integrations`,`Integrations`),onClick:()=>f(`/integrations`)},K===null?{label:Ce}:{label:Ce,onClick:()=>f(`/integrations/${K.id}`)},{label:L}]})}),r(`div`,{className:`flex items-center gap-2 sm:gap-3`,children:[K!==null&&u(ul,{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(Dt,{status:ne}),je&&u(Lt,{status:Me,variant:`full`}),u(en,{status:Ne})]}),ce!==null&&le&&r(`button`,{type:`button`,onClick:()=>f(`/devices/${ce}`),className:`text-[10px] text-foreground-subtle hover:text-primary transition-colors mt-0.5 inline-flex items-center gap-1`,title:n(`deviceDetail.openParentDevice`,`Open parent device {{name}}`,{name:le.name}),children:[u(`span`,{children:`↑`}),u(`span`,{className:`truncate`,children:String(le.name??`Device #${ce}`)})]}),u(`div`,{className:`hidden md:flex items-center gap-3 mt-0.5 text-[10px] text-foreground-subtle`,children:B.length>0&&u(Yr,{capabilities:B})})]}),He&&u(`div`,{className:`hidden lg:flex`,children:u(pl,{metrics:He,dbfs:Y})}),r(`div`,{className:`flex items-center gap-1 shrink-0`,children:[r(`button`,{onClick:async()=>{de?await m({title:n(`deviceDetail.disable`,`Disable "{{name}}"?`,{name:L}),message:n(`deviceDetail.theDeviceWillStopProcessing`,`The device will stop processing streams and events. You can re-enable it later.`),confirmLabel:n(`common.disable`,`Disable`),variant:`danger`})&&q.mutate({deviceId:l}):De.mutate({deviceId:l})},disabled:Re,title:de?n(`deviceDetail.disableDevice`,`Disable device`):n(`deviceDetail.enableDevice`,`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 ${de?`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:Re?n(`deviceDetail.updating`,`Updating…`):de?n(`deviceDetail.enabled`,`Enabled`):n(`deviceDetail.disabled`,`Disabled`)})]}),u(`div`,{className:`hidden sm:block h-5 w-px bg-border mx-1`}),re&&r(o,{children:[u(la,{deviceId:l}),u(`div`,{className:`hidden sm:block h-5 w-px bg-border mx-1`})]}),u(da,{deviceId:l}),u(Jt,{triggerClassName:`ml-1`,items:[{id:`snapshot`,label:n(`deviceDetail.takeSnapshot`,`Take snapshot`),description:n(`deviceDetail.fetchAFreshFrameAnd`,`Fetch a fresh frame and download it.`),icon:pe,disabled:Pe,onClick:()=>{Le()}},{id:`reboot`,label:n(`deviceDetail.rebootDevice`,`Reboot device`),description:n(`deviceDetail.cameraGoesOfflineFor30`,`Camera goes offline for ~30 seconds.`),icon:te,hidden:!Ae,disabled:Oe.isPending,danger:!0,onClick:async()=>{await m({title:n(`deviceDetail.reboot`,`Reboot "{{name}}"?`,{name:L}),message:n(`deviceDetail.theCameraWillGoOffline`,`The camera will go offline for around 30 seconds while the firmware reboots.`),confirmLabel:n(`deviceDetail.reboot2`,`Reboot`),variant:`danger`})&&Oe.mutate({deviceId:l})}},{id:`restart-addon`,label:n(`deviceDetail.restartAddon`,`Restart addon`),description:n(`deviceDetail.bouncesEveryDeviceServedBy`,`Bounces every device served by {{servingAddonLabel}}.`,{servingAddonLabel:we}),icon:me,disabled:ke.isPending,danger:!0,onClick:async()=>{await m({title:n(`deviceDetail.restart`,`Restart "{{servingAddonLabel}}"?`,{servingAddonLabel:we}),message:n(`deviceDetail.restartingTheAddonWillBriefly`,`Restarting the addon will briefly disconnect every device served by it (not just "{{name}}"). Streams will reconnect automatically.`,{name:L}),confirmLabel:n(`deviceDetail.restart2`,`Restart`),variant:`danger`})&&ke.mutate({addonId:z})}},{id:`delete`,label:n(`deviceDetail.deleteDevice`,`Delete device`),description:n(`deviceDetail.removeTheDeviceAndAll`,`Remove the device and all its settings.`),icon:_,separatorBefore:!0,disabled:Te.isPending,danger:!0,onClick:async()=>{await m({title:n(`deviceDetail.delete`,`Delete "{{name}}"?`,{name:L}),message:n(`deviceDetail.thisWillRemoveTheDevice`,`This will remove the device and all its settings. This action cannot be undone.`),confirmLabel:n(`common.delete`,`Delete`),variant:`danger`})&&Te.mutate({deviceId:l})}}]})]})]})]}),u(wt,{deviceId:l,device:I??void 0,children:u(pt,{children:u(Ot,{children:u(ue,{children:u(dn,{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`:`${E===null?`w-1/2 lg:w-1/3`:``} flex-shrink-0 flex flex-col bg-surface min-h-0 overflow-hidden`,style:!G&&E!==null?{width:`${String(E)}px`}:void 0,children:[u(`div`,{className:re?`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:re?u(Ga,{deviceId:l,intercomAvailable:B.includes(Ee.TwoWayAudio)}):u(Fa,{deviceId:l,deviceName:L,deviceType:V??`unknown`,provider:z,isOnline:R,features:B})}),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:be.map(({id:e,label:t,icon:n})=>r(`button`,{onClick:()=>w(e),title:t,className:`flex items-center gap-1 rounded px-2 py-1 text-[10px] font-medium transition-colors flex-shrink-0 ${C===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:[C===`logs`&&u(Ka,{deviceId:l,containerDeviceId:V===`container`?l:void 0}),C===`repl`&&u(qa,{deviceId:l}),C===`events`&&u(Ja,{deviceId:l}),C===`state`&&u(Ya,{deviceId:l})]})]})]}),!G&&u(`div`,{role:`separator`,"aria-orientation":`vertical`,title:n(`deviceDetail.dragToResize`,`Drag to resize`),onMouseDown:k,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:he.map(e=>{let t=ge===e.id;return r(`button`,{onClick:()=>_e(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:[ge===`overview`&&ye&&u(fa,{parentDeviceId:l}),We()]})]})]})})})})})})]}):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:n(`deviceDetail.invalidDeviceId`,`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:a.deviceId}),` `,n(`deviceDetail.isNotANumber`,`is not a number.`)]}),u(`button`,{onClick:()=>f(`/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:n(`deviceDetail.backToIntegrations`,`Back to Integrations`)})]})}function pl({metrics:e,dbfs:t}){let{t:n}=Z(),i=jt(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 ${i.dotClass}`}),u(`span`,{className:`text-[10px] font-medium ${i.textColor}`,children:i.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:n(`deviceDetail.currentAudioLevelDbfs`,`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{fl 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-Cda8wso6.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-CMlUvfoK.js";import{d as m}from"./src-eoSUZcV-.js";import{t as h}from"./useTranslation-Bc5yH9V9.js";import"./notification-schedule-field-DWpT_5Vh.js";e();var g=6e4;function _(e){let t=a();return r({queryKey:[`device-do-action`,`bound-caps`,e],enabled:e>0,staleTime:g,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 v(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:g,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 y=`mt-1 w-full rounded border border-border bg-background px-2 py-1 text-xs`,b=`block text-[11px] font-medium text-foreground`,x=`deviceId`;function S(e,t){return t.length===0?0:t.length===1?t[0]:t.find(t=>!e.includes(t))??t[t.length-1]}function C(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 w(e){return e.length===0?0:e.length===1?e[0]:[...e]}function T(e){return typeof e==`number`?e>0?[e]:[]:Array.isArray(e)?e.filter(e=>e>0):[]}function E(e,t){return{deviceId:e,cap:t.cap,method:t.method,...t.args===void 0?{}:{args:{...t.args}}}}function D(e,t){return`Custom: ${e}.${t}`}function O({value:e,onChange:r,devices:a,listState:g,fleet:O,allowTriggerDevice:k=!1,allowMultiSameFamily:A=!1,testId:j=`device-do-action`}){let{t:M}=h(),N=typeof e.deviceId!=`number`&&!Array.isArray(e.deviceId),P=T(e.deviceId),F=n(()=>a.filter(e=>f(String(e.type??``))),[a]),I=n(()=>{let e=new Map;for(let t of F)t.type!==void 0&&t.type!==null&&e.set(t.id,String(t.type));return e},[F]),L=n(()=>{if(!A||P.length===0)return F;let e=I.get(P[0]);return e===void 0?F:F.filter(t=>{if(P.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)})},[A,P,F,I]),R=_(!A&&P.length===1?P[0]:0),z=v(A?P:[]),B=n(()=>N?c():P.length===0?[]:A?z.isLoading&&z.data===void 0?[]:d(P.map(e=>({boundCaps:z.data?.get(e),deviceType:I.get(e)}))):R.data===void 0&&R.isLoading?[]:o({boundCaps:R.data,deviceType:I.get(P[0])}),[N,P,A,z.data,z.isLoading,R.data,R.isLoading,I]),V=u(e.cap,e.method,e.args),H=s(e.cap,e.method,e.args),U=e.cap!==``&&e.method!==``&&H===null&&(N||P.length>0),W=A?z.isLoading:R.isLoading,G=A?z.isError:R.isError,K=t=>{if(t.startsWith(`custom:`))return;let n=p.find(e=>e.id===t);n!==void 0&&r(E(N?e.deviceId:P.length>0?w(P):F[0]?.id??0,n))};return t(`div`,{className:`flex min-w-0 flex-1 flex-col gap-2`,"data-testid":j,children:[k&&t(`div`,{className:`w-full max-w-xs`,children:[i(`label`,{className:b,children:M(`deviceDoAction.deviceDoActionFields.target`,`Target`)}),t(`select`,{className:y,"data-testid":`${j}-target`,value:N?`trigger`:`device`,onChange:e=>{if(e.target.value===`trigger`){r({deviceId:{$var:x},cap:``,method:``});return}r({deviceId:F[0]?.id??0,cap:``,method:``})},children:[i(`option`,{value:`device`,children:M(`deviceDoAction.deviceDoActionFields.specificDevice`,`Specific device`)}),i(`option`,{value:`trigger`,children:M(`deviceDoAction.deviceDoActionFields.theDeviceThatTriggeredThis`,`The device that triggered this run`)})]})]}),!N&&t(`div`,{"data-testid":`${j}-device`,children:[t(`label`,{className:b,children:[`Device`,A?`s`:``]}),i(m,{devices:L,listState:g,...O===void 0?{}:{fleet:O},value:[...P],onChange:e=>{r({deviceId:w(A?C(P,e,e=>I.get(e)):(()=>{let t=S(P,e);return t>0?[t]:[]})()),cap:``,method:``})},emptyLabel:A?`No devices selected`:`No device selected`,noun:`device`,testId:`${j}-device-picker`}),A&&P.length>1&&i(`p`,{className:`mt-1 text-[11px] text-foreground-subtle`,children:M(`deviceDoAction.deviceDoActionFields.sameFamilyOnlyTheAction`,`Same family only — the action runs on each selected device.`)})]}),t(`div`,{className:`w-full max-w-sm`,children:[i(`label`,{className:b,children:M(`deviceDoAction.deviceDoActionFields.action`,`Action`)}),t(`select`,{className:y,"data-testid":`${j}-action`,value:V===`custom:${e.cap}.${e.method}`?V:H?.id??``,disabled:!N&&(P.length===0||W),onChange:e=>K(e.target.value),children:[i(`option`,{value:``,children:!N&&P.length===0?M(`deviceDoAction.deviceDoActionFields.pickADeviceFirst`,`Pick a device first`):W?M(`deviceDoAction.deviceDoActionFields.loadingActions`,`Loading actions…`):B.length===0?M(`deviceDoAction.deviceDoActionFields.noActionsForThisDevice`,`No actions for this device`):M(`deviceDoAction.deviceDoActionFields.selectAnAction`,`Select an action…`)}),U&&i(`option`,{value:V,children:D(e.cap,e.method)}),B.map(e=>i(`option`,{value:e.id,children:e.label},e.id))]}),G&&i(`p`,{className:`mt-1 text-[11px] text-warning`,children:M(`deviceDoAction.deviceDoActionFields.couldNotReadThisDevice`,`Could not read this device’s capabilities.`)})]}),H?.openArgs!==void 0&&H.openArgs.length>0&&i(`div`,{className:`flex flex-col gap-2`,children:H.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:b,htmlFor:`${j}-${n.key}`,children:n.label}),i(`input`,{id:`${j}-${n.key}`,className:y,"data-testid":`${j}-${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{O 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-Cda8wso6.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-eoSUZcV-.js";import{t as _}from"./useTranslation-Bc5yH9V9.js";import{K as v,X as y}from"./index-BgQGn3LX.js";import{t as b}from"./AdminPage-DuuyDIsY.js";import"./useEventInvalidation-DlnG_8P7.js";import{t as x}from"./device-integration-icon-bTnWrYe0.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:t(`devices.orphanDevices`,`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:t(`devices.theseDevicesReferenceAnIntegration`,"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{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-Cda8wso6.js";import{n as I,r as L,t as ee}from"./key-DLwSBrPM.js";import{c as R,o as z,u as B}from"./video-tLHyNE3q.js";import{t as V}from"./history-DZsORyBG.js";import{t as H}from"./key-round-CYflkUyd.js";import{t as te}from"./monitor-smartphone-lsNgnRRZ.js";import{t as ne}from"./unlink-C1ZpCxl3.js";import{Si as re,a as ie,bi as ae,i as oe,o as se,s as ce,xi as le}from"./client-CMlUvfoK.js";import{Al as ue,An as de,Ao as fe,Bl as pe,Bn as U,Cn as me,Dl as he,Dn as ge,Dr as _e,El as ve,En as ye,Er as be,Fl as xe,Ft as Se,G as Ce,Ht as we,Il as Te,Jl as Ee,Kl as De,L as Oe,Ll as ke,Ln as Ae,Ml as je,N as Me,Nl as Ne,Ol as Pe,P as Fe,Pl as Ie,Qn as Le,Rl as Re,Rn as ze,Tn as Be,Ut as Ve,Vl as He,Wt as W,X as Ue,Xl as We,Yl as Ge,Z as Ke,Zl as qe,Zn as G,_u as K,ar as q,bn as Je,en as Ye,in as Xe,jl as Ze,jn as Qe,kl as $e,kn as et,ma as tt,nn as nt,on as rt,ql as it,rn as at,z as ot,zl as st,zn as ct}from"./src-eoSUZcV-.js";import{t as J}from"./i18n-vggiB6gm.js";import{t as Y}from"./useTranslation-Bc5yH9V9.js";import{C as lt,J as ut,Q as dt,R as ft,X as pt,Y as mt,c as ht,f as gt,m as _t,s as vt}from"./index-BgQGn3LX.js";import{t as yt}from"./AdminSectionedPage-C3VHg80L.js";import{t as bt}from"./AdminPage-DuuyDIsY.js";import{A as xt,C as St,D as Ct,E as wt,F as Tt,M as Et,N as X,O as Dt,P as Z,S as Ot,T as kt,_ as At,a as jt,b as Mt,c as Nt,d as Pt,f as Ft,h as It,i as Lt,j as Rt,k as zt,l as Bt,m as Vt,n as Ht,o as Ut,p as Wt,s as Gt,t as Kt,u as qt,v as Jt,w as Yt,x as Xt,y as Zt}from"./SessionsList-CIN4GdSm.js";import{i as Qt,n as $t,r as en,t as tn}from"./IntegrationHub-BePMbmC5.js";import{n as nn,t as rn}from"./addon-display-names-BkwMrExv.js";n();function an(){let{t:e}=Y(),t=G(),n=K.useUtils(),r=Tt(),{data:a,isLoading:o}=Ie(),s=i(()=>a??[],[a]),l=K.useQueries(e=>s.map(t=>e.userManagement.listExternalIdentities({userId:t.id}))),d=K.auth.listLoginMethods.useQuery(),[f,p]=c(null),m=pe({onSuccess:()=>void n.userManagement.listExternalIdentities.invalidate(),onError:e=>p(`Remove failed: ${e.message}`)}),h=i(()=>new Map((d.data??[]).flatMap(e=>e.kind===`redirect`?[[e.id,e.label]]:[])),[d.data]),g=s.flatMap((e,t)=>l[t]?.data??[]),_=g.map(e=>({...kt(e,r),kind:h.get(e.provider)??e.provider})),v=async n=>{let r=g.find(e=>Yt(e)===n.id);r!==void 0&&await t({title:e(`access.externalIdentitiesSection.removeSignInLink`,`Remove sign-in link`),message:e(`access.externalIdentitiesSection.willNoLongerBeAble`,`"{{ownerName}}" will no longer be able to sign in with this {{kind}} account.`,{ownerName:n.ownerName,kind:n.kind}),confirmLabel:e(`common.remove`,`Remove`),variant:`danger`})&&(p(null),m.mutate({userId:r.userId,provider:r.provider,subject:r.subject}))};return u(X,{notice:Z(f),onDismissNotice:()=>{p(null)},id:`external-identities`,title:e(`access.externalIdentitiesSection.signInLinks`,`Sign-in links`),icon:B,description:e(`access.externalIdentitiesSection.externalAccountsSingleSignOn`,`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(zt,{rows:_,label:`sign-in links`,isLoading:o||l.some(e=>e.isLoading),loadError:l.find(e=>e.isError)?.error?.message??null,emptyText:`No user has linked a sign-in account.`,expiresNone:`—`,action:{label:e(`common.remove`,`Remove`),icon:ne,isAvailable:()=>!0,onRun:e=>void v(e),busyId:null,disabled:m.isPending}})})}n();function on(){let{t:e}=Y(),t=G(),n=s(),r=Tt(),a=Ze(),[o,l]=c(null),d=Te({onSuccess:()=>void n.invalidateQueries({queryKey:[[`userManagement`,`listApiKeys`]]}),onError:e=>l(`Revoke failed: ${e.message}`)}),f=i(()=>(a.data??[]).map(e=>St(e,r)),[a.data,r]),p=async n=>{await t({title:e(`access.legacyApiKeysSection.revoke`,`Revoke "{{name}}"?`,{name:n.name}),message:e(`access.legacyApiKeysSection.anyClientUsingThisKey`,`Any client using this key loses access immediately. This cannot be undone.`),confirmLabel:e(`access.legacyApiKeysSection.revoke2`,`Revoke`),variant:`danger`})&&(l(null),d.mutate({id:n.id}))};return u(X,{notice:Z(o),onDismissNotice:()=>{l(null)},id:`legacy-api-keys`,title:e(`access.legacyApiKeysSection.legacyApiKeys`,`Legacy API keys`),icon:V,description:e(`access.legacyApiKeysSection.keysFromBeforeScopedTokens`,`Keys from before scoped tokens. Nothing creates them any more; revoke them and issue a scoped token instead.`),children:u(zt,{rows:f,label:e(`access.legacyApiKeysSection.legacyApiKeys2`,`legacy API keys`),isLoading:a.isLoading,loadError:a.isError?a.error?.message??`Request failed`:null,emptyText:`No legacy API keys.`,action:{label:e(`access.legacyApiKeysSection.revoke2`,`Revoke`),icon:h,isAvailable:()=>!0,onRun:e=>void p(e),busyId:d.isPending?d.variables?.id??null:null,disabled:d.isPending}})})}n();var sn={one:`linked app`,many:`linked apps`};function cn(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 ln(){let{t:e}=Y(),t=G(),n=s(),r=Ne(),[a,o]=c(null),l=()=>void n.invalidateQueries({queryKey:[[`userManagement`,`listOauthSessions`]]}),d=ke({onSuccess:l,onError:e=>o(`Revoke failed: ${e.message}`)}),f=xt(`oauth-session`,sn,l),p=i(()=>(r.data??[]).map(e=>wt(e,e.scopes.map(cn).join(`, `))),[r.data]),m=async n=>{await t({title:e(`access.linkedAppsSection.revokeTheLink`,`Revoke the "{{name}}" link?`,{name:n.name}),message:e(`access.linkedAppsSection.losesAccessForOnIts`,`{{name}} loses access for {{ownerName}} on its next call. Linking it again needs the account-link flow from the start.`,{name:n.name,ownerName:n.ownerName}),confirmLabel:e(`access.linkedAppsSection.revoke`,`Revoke`),variant:`danger`})&&(o(null),d.mutate({id:n.id}))},g=d.isPending?d.variables?.id??null:null;return u(X,{notice:Z(a,f.outcome),onDismissNotice:()=>{o(null),f.dismiss()},id:`linked-apps`,title:e(`access.linkedAppsSection.linkedApps`,`Linked apps`),icon:w,description:e(`access.linkedAppsSection.externalIntegrationsAlexaLinkedTo`,`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(zt,{rows:p,label:e(`access.linkedAppsSection.linkedApps2`,`linked apps`),isLoading:r.isLoading,loadError:r.isError?r.error?.message??`Request failed`:null,emptyText:`No linked apps — an integration appears here once it completes the account-link flow.`,expiresNone:`—`,action:{label:e(`access.linkedAppsSection.revoke`,`Revoke`),icon:h,isAvailable:e=>e.status===`active`||e.status===`revoked`,onRun:e=>void m(e),busyId:g,disabled:d.isPending||f.busy},bulk:{revoke:f,noun:sn,isSelectable:e=>e.status===`active`||e.status===`revoked`,quickSelect:[{label:e(`access.linkedAppsSection.selectRevoked`,`Select revoked`),match:e=>e.status===`revoked`}]}})})}n();var un={one:`session`,many:`sessions`};function dn(){let{t:e}=Y(),t=G(),n=K.useUtils(),r=Tt(),a=K.auth.listSessions.useQuery(),[o,s]=c(null),l=()=>void n.auth.listSessions.invalidate(),d=K.auth.revokeSessions.useMutation({onSuccess:l,onError:e=>s(`Sign out failed: ${e.message}`)}),f=xt(`login-session`,un,l),p=i(()=>(a.data??[]).map(e=>Ct(e,r,{client:e=>Jt(e).label,method:Zt})),[a.data,r]),m=async n=>{await t({title:e(`access.loginSessionsSection.signOutThisSession`,`Sign out this session`),message:e(`access.loginSessionsSection.onWillHaveToSign`,`{{ownerName}} on {{name}} will have to sign in again.`,{ownerName:n.ownerName,name:n.name}),confirmLabel:e(`access.loginSessionsSection.signOut`,`Sign out`),variant:`danger`})&&(s(null),d.mutate({id:n.id}))};return u(X,{notice:Z(o,f.outcome),onDismissNotice:()=>{s(null),f.dismiss()},id:`login-sessions`,title:e(`access.loginSessionsSection.loginSessions`,`Login sessions`),icon:te,description:e(`access.loginSessionsSection.everyBrowserAndAppSigned`,`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(zt,{rows:p,label:`sessions`,isLoading:a.isLoading,loadError:a.isError?a.error?.message??`Request failed`:null,emptyText:`No active sessions.`,action:{label:e(`access.loginSessionsSection.signOut`,`Sign out`),icon:z,isAvailable:e=>e.status===`active`,onRun:e=>void m(e),busyId:d.isPending&&d.variables!==void 0&&`id`in d.variables?d.variables.id:null,disabled:d.isPending||f.busy},bulk:{revoke:f,noun:un,isSelectable:e=>e.status===`active`}})})}function fn({token:e,label:t,onClose:n}){let{t:i}=Y();return u(Be,{open:!0,onOpenChange:e=>!e&&n(),children:r(ge,{width:`md`,scroll:`body`,children:[u(de,{children:u(Qe,{children:i(`auth.tokenModals.token`,`Token: {{label}}`,{label:t})})}),r(ye,{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:i(`auth.tokenModals.copyThisTokenNowOnce`,`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(et,{children:[u(Se,{value:e,label:i(`common.copy`,`Copy`),srLabel:`token`}),u(U,{type:`button`,variant:`primary`,size:`sm`,onClick:n,children:i(`auth.tokenModals.done`,`Done`)})]})]})})}var pn={token:`newToken`,scoped:`newScoped`,admin:`newAdmin`};n();var mn=7,hn=90,gn=80;function _n(e){let t=Number(e);return Number.isInteger(t)&&t>=1&&t<=hn?t:null}function vn({open:e,users:t,onClose:n,onSubmitScoped:i,onSubmitAdmin:a,submitting:s,formError:l,awaitingProof:f}){let{t:p}=Y(),{user:m}=ft(),h=m?.isAdmin===!0,g=h?null:m?.scopes??[],[_,v]=c(!1),[y,b]=c(t[0]?.id??``),[x,C]=c(``),[w,T]=c([{type:`capability`,target:``,access:[`view`,`create`]}]),[E,D]=c(``),[O,A]=c(String(mn));d(()=>{e||(v(!1),b(t[0]?.id??``),C(``),T([{type:`capability`,target:``,access:[`view`,`create`]}]),D(``),A(String(mn)))},[e,t]);let j=x.trim(),N=Fe(w),P=_n(O),F=!_&&y!==``&&j.length>0&&w.length>0&&N===null&&!s,I=_&&h&&j.length>0&&j.length<=gn&&P!==null&&!s&&!f,L=()=>{if(_){if(!I||P===null)return;a({name:j,expiresInDays:P});return}if(!F)return;let e=parseInt(E,10),t=Number.isFinite(e)&&e>0?Date.now()+e*864e5:void 0;i({userId:y,name:j,scopes:w,...t===void 0?{}:{expiresAt:t}})},ee=_,R=_?M:k;return u(ot,{open:e,onClose:n,title:_?p(`access.createTokenModal.createAdminToken`,`Create admin token`):p(`access.createTokenModal.createToken`,`Create token`),icon:_?M:H,error:l,width:`md`,testId:`create-token-dialog`,footer:r(U,{type:`button`,variant:ee?`danger`:`primary`,size:`sm`,onClick:L,disabled:_?!I:!F,children:[s||f?u(S,{className:`h-3.5 w-3.5 animate-spin`,"aria-hidden":!0}):u(R,{className:`h-3.5 w-3.5`,"aria-hidden":!0}),_?p(`access.createTokenModal.createAdminToken`,`Create admin token`):p(`access.createTokenModal.issueToken`,`Issue token`)]}),children:r(`div`,{className:`space-y-3`,children:[h?r(`label`,{className:`flex items-start gap-2 text-sm text-foreground`,children:[u(`input`,{type:`checkbox`,className:`mt-0.5`,checked:_,onChange:e=>v(e.target.checked),"data-testid":`token-as-admin`}),r(`span`,{children:[u(`span`,{className:`font-medium`,children:p(`access.createTokenModal.administrator`,`Administrator`)}),u(`span`,{className:`block text-[11px] text-foreground-subtle`,children:p(`access.createTokenModal.offScopedToASurface`,`Off = scoped to a surface. On = full admin for scripts (audited, max 90 days).`)})]})]}):null,_?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:p(`access.createTokenModal.fullAdministrator`,`full administrator`)}),`. Anyone holding it can do anything an admin can. Creating one asks you to confirm it is you.`]})}):null,_?null:r(`div`,{className:`space-y-1`,children:[u(rt,{htmlFor:`token-user`,children:p(`access.createTokenModal.onBehalfOfUser`,`On behalf of user`)}),u(De,{id:`token-user`,value:y,onChange:e=>b(e.target.value),options:t.map(e=>({value:e.id,label:e.username}))})]}),u(Ce,{label:p(`access.createTokenModal.name`,`Name`),required:!0,children:u(qe,{id:`token-name`,value:x,maxLength:gn,onChange:e=>C(e.target.value),placeholder:_?`nightly-backup`:`cloudflare-tunnel-route`,autoFocus:!0})}),_?r(`div`,{className:`space-y-1`,children:[u(rt,{htmlFor:`token-admin-days`,children:p(`access.createTokenModal.expiresInDays`,`Expires in (days)`)}),u(qe,{id:`token-admin-days`,type:`number`,min:1,max:hn,value:O,onChange:e=>A(e.target.value),state:P===null?`error`:`default`}),P===null?r(`p`,{className:`text-[11px] text-danger`,children:[`Expiry must be a whole number of days, 1 to `,hn,`.`]}):r(`p`,{className:`text-[11px] text-foreground-subtle`,children:[`Whole number of days, 1 to `,hn,`.`]})]}):r(o,{children:[r(`div`,{className:`space-y-1`,children:[u(rt,{children:p(`access.createTokenModal.scopes`,`Scopes`)}),u(Me,{value:w,onChange:T,clampToParent:g}),N&&u(`p`,{className:`text-[10px] text-danger`,children:N}),u(`p`,{className:`text-[10px] text-foreground-subtle`,children:p(`access.createTokenModal.eachScopePicksACap`,`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(rt,{htmlFor:`token-scoped-days`,children:p(`access.createTokenModal.expiresInDays`,`Expires in (days)`)}),u(qe,{id:`token-scoped-days`,type:`number`,min:1,value:E,onChange:e=>D(e.target.value),placeholder:`30`}),u(`p`,{className:`text-[10px] text-foreground-subtle`,children:p(`access.createTokenModal.leaveBlankForNonExpiring`,`Leave blank for non-expiring.`)})]})]})]})})}n();var yn={one:`token`,many:`tokens`};function bn(e){return e.type===`device`?`device:[${Ke(e.selector)}]`:`${e.type}:${e.target??``}`}function xn({createRequested:e=!1,onCreateConsumed:t}){let{t:n}=Y(),{user:a}=ft(),o=G(),l=s(),f=K.useUtils(),p=Tt(),{data:m,isLoading:g}=Ie(),_=i(()=>m??[],[m]),v=K.useQueries(e=>_.map(t=>e.userManagement.listScopedTokens({userId:t.id}))),y=K.auth.listAdminTokens.useQuery(void 0,{enabled:a?.isAdmin===!0}),{requestProof:b,dialog:x}=At(`Creating an admin token`),{state:S,openNew:C,close:w}=Oe({newKey:pn.token}),[T,E]=c(null),[D,O]=c(null),[k,A]=c(!1),[j,M]=c(null),[N,P]=c(null);d(()=>{e&&(C(),t?.())},[e,C,t]);let F=()=>{l.invalidateQueries({queryKey:[[`userManagement`,`listScopedTokens`]]}),f.auth.listAdminTokens.invalidate(),f.auth.listAuthAudit.invalidate()},I=ve({onSuccess:({token:e,record:t})=>{F(),w(),O(null),M({token:e,label:t.name})},onError:e=>{E(`Create failed: ${e.message}`),O(`Create failed: ${e.message}`)}}),L=K.auth.createAdminToken.useMutation({onSuccess:({token:e,record:t})=>{F(),w(),O(null),A(!1),M({token:e,label:t.name})},onError:e=>{E(`Create failed: ${e.message}`),O(`Create failed: ${e.message}`),A(!1)}}),ee=Re({onSuccess:()=>{P(null),F()},onError:e=>{P(null),E(`Revoke failed: ${e.message}`)}}),R=K.auth.revokeAdminToken.useMutation({onSuccess:()=>{P(null),F()},onError:e=>{P(null),E(`Revoke failed: ${e.message}`)}}),z=Et(yn,F),B=Date.now(),V=_.flatMap((e,t)=>(v[t]?.data??[]).map(t=>Dt(t,e.id,p,t.scopes.map(bn).join(`, `),B))),te=a?.isAdmin===!0?(y.data??[]).map(e=>Ot(e,p,B)):[],ne=[...V,...te],re=v.find(e=>e.isError)?.error?.message??(y.isError?y.error?.message??`Request failed`:null),ie=async e=>{let t=e.kind===Xt;await o({title:n(`access.tokensSection.revoke`,`Revoke "{{name}}"?`,{name:e.name}),message:t?n(`access.tokensSection.everyScriptUsingItLoses`,`Every script using it loses access immediately. This cannot be undone.`):n(`access.tokensSection.sScopedTokenStopsWorking`,`{{ownerName}}'s scoped token stops working on its next use. This cannot be undone.`,{ownerName:e.ownerName}),confirmLabel:n(`access.tokensSection.revoke2`,`Revoke`),variant:`danger`})&&(E(null),P(e.id),t?R.mutate({id:e.id}):ee.mutate({id:e.id}))},ae=I.isPending||L.isPending;return r(`div`,{"data-testid":`tokens`,children:[x,u(X,{notice:Z(T,z.outcome),onDismissNotice:()=>{E(null),z.dismiss()},id:`tokens`,title:n(`access.tokensSection.tokens`,`Tokens`),icon:H,description:n(`access.tokensSection.scopedTokensForANarrow`,`Scoped tokens for a narrow surface, and admin tokens for full-administrator scripts. Revoking one stops it on its next use.`),children:u(zt,{rows:ne,label:`tokens`,isLoading:g||v.some(e=>e.isLoading)||a?.isAdmin===!0&&y.isLoading,loadError:re,emptyText:`No tokens.`,action:{label:n(`access.tokensSection.revoke2`,`Revoke`),icon:h,isAvailable:e=>e.status===`active`,onRun:e=>void ie(e),busyId:N,disabled:z.busy||N!==null},bulk:{revoke:z,noun:yn,isSelectable:e=>e.status===`active`}})}),u(vn,{open:S.mode===`new`,users:_.map(e=>({id:e.id,username:e.username})),onClose:()=>{w(),O(null),A(!1)},submitting:ae,formError:D,awaitingProof:k,onSubmitScoped:e=>I.mutate({userId:e.userId,name:e.name,scopes:e.scopes,expiresAt:e.expiresAt}),onSubmitAdmin:e=>{(async()=>{E(null),O(null),A(!0);let t=await b();A(!1),t!==null&&L.mutate({...e,reauthToken:t})})()}}),j&&u(fn,{token:j.token,label:j.label,onClose:()=>M(null)})]})}var Sn={"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 Cn(e,t){let n=Q(e,`tokenId`);return Q(e,`name`)??(n===null?void 0:t.get(n))??n??`?`}function wn(e){return e.filter(e=>e!==null)}function Tn(e){let t=Q(e,`prefix`);return t===null?null:`Prefix ${t}…`}function En(e,t){let n=e.detail??{};switch(e.action){case`admin-token-created`:{let e=n.expiresAt;return{title:`Admin token "${Cn(n,t)}" created`,details:wn([Tn(n),typeof e==`number`?`Expires ${Mt(e)}`:null])}}case`admin-token-used`:{let e=Q(n,`path`);return{title:`Admin token "${Cn(n,t)}" used`,details:wn([Tn(n),e===null?null:`Call ${e}`])}}case`admin-token-revoked`:return{title:`Admin token "${Cn(n,t)}" revoked`,details:wn([Tn(n)])};case`credentials-revoked`:{let e=Q(n,`kind`)??`credential`,t=n.revoked,r=n.skipped,i=Sn[e]??`${e}s`;return{title:`${typeof t==`number`?String(t):`?`} ${i} revoked in bulk`,details:wn([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:wn([e===null?null:`Signed in with ${Zt(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 Dn=100;function On(){let{user:e}=ft();return e?.isAdmin?u(An,{}):null}function kn(){let{data:e}=Ie(),{data:t}=K.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 An(){let{t:e}=Y(),t=K.auth.listAuthAudit.useQuery({limit:Dn}),{userNameById:n,tokenNameById:i}=kn(),a=t.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:e(`auth.authAuditSection.authenticationAudit`,`Authentication audit`)}),r(`span`,{className:`ml-auto text-[10px] text-foreground-subtle`,children:[`Latest `,Dn,`, newest first`]})]}),u(`div`,{className:`p-4`,children:t.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`}),e(`auth.authAuditSection.loadingAuditTrail`,`Loading audit trail…`)]}):t.isError?r(`div`,{className:`text-[11px] text-danger`,children:[e(`auth.authAuditSection.couldNotLoadTheAudit`,`Could not load the audit trail:`),` `,t.error?.message??e(`auth.authAuditSection.requestFailed`,`Request failed`)]}):a.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:e(`auth.authAuditSection.noAuthenticationEventsRecordedYet`,`No authentication events recorded yet.`)}),u(`div`,{className:`text-[11px] text-foreground-subtle/90`,children:e(`auth.authAuditSection.thisTrailRecordsAdminToken`,`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:a.map(e=>u(jn,{record:e,userName:e.userId===void 0?null:n.get(e.userId)??e.userId,tokenNameById:i},e.id))})})]})}function jn({record:e,userName:t,tokenNameById:n}){let i=En(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:Mt(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`},Mn={[$.scopedTokens]:$.tokens,[$.adminTokens]:$.tokens};function Nn(e){return[{id:$.loginSessions,label:J.t(`system.access.loginSessions`,`Login sessions`),icon:te,render:()=>u(dn,{})},{id:$.linkedApps,label:J.t(`system.access.linkedApps`,`Linked apps`),icon:w,render:()=>u(ln,{})},{id:$.tokens,label:J.t(`system.access.tokens`,`Tokens`),icon:H,render:({createRequested:e,onCreateConsumed:t})=>u(xn,{headerOwnsCreate:!0,createRequested:e,onCreateConsumed:t})},{id:$.shareLinks,label:J.t(`system.access.shareLinks`,`Share links`),icon:C,render:()=>u(It,{})},...e?[{id:$.legacyApiKeys,label:J.t(`system.access.legacyApiKeys`,`Legacy API keys`),icon:V,render:()=>u(on,{})}]:[],{id:$.externalIdentities,label:J.t(`system.access.signInLinks`,`Sign-in links`),icon:B,render:()=>u(an,{})},{id:$.audit,label:J.t(`system.access.audit`,`Audit`),icon:D,render:()=>u(On,{})}]}function Pn({createRequested:e=!1,onCreateConsumed:t}){let{t:n}=Y(),a=Ze(),o=(a.data??[]).length>0,s=i(()=>Nn(o),[o]),c=Qt({ids:i(()=>s.map(e=>e.id),[s]),answered:!a.isLoading}),l=pt(),[d]=dt(),f=d.get(`integration`),p=f===null?void 0:Mn[f];if(p!==void 0){let e=new URLSearchParams(d);return e.set(`integration`,p),u(mt,{to:`?${e.toString()}`,replace:!0})}let m=s.find(e=>e.id===c.selectedId)??s[0],h=m?.id??$.loginSessions;return a.isLoading?u(`div`,{className:`text-sm text-foreground-subtle`,"data-testid":`access-page`,children:n(`common.loading`,`Loading…`)}):r(`div`,{className:`flex flex-col gap-3`,"data-testid":`access-page`,children:[u(Ye,{appearance:`pills`,value:h,onValueChange:e=>{l(`?${_t(d,e,null,null).toString()}`)},children:u(nt,{"aria-label":n(`system.access.credentialKinds`,`Credential kinds`),children:s.map(e=>r(at,{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))})}),m===void 0?null:u(`div`,{role:`region`,"aria-label":m.label,"data-testid":`access-kind-body`,children:m.render({createRequested:e&&m.id===$.tokens,onCreateConsumed:t??(()=>void 0)})},m.id)]})}function Fn(e,t){if(e===$.tokens)return r(U,{size:`sm`,type:`button`,"data-testid":`access-new-token`,onClick:t,children:[u(H,{className:`h-3.5 w-3.5`,"aria-hidden":!0}),J.t(`system.access.newToken`,`New token`)]})}function In(){let[e,t]=c(!1);return{createRequested:e,requestCreate:()=>t(!0),clearCreate:()=>t(!1)}}n();var Ln=[`oidcConnections`,`listConnections`],Rn=[`oidcConnections`,`connectionFormSchema`],zn={displayName:`OpenID Connect`,icon:`shield-check`,issuerUrl:``,clientId:``,clientSecret:``,redirectUri:``,scopes:`openid profile email`,usernameClaim:`preferred_username`},Bn=/^[a-z0-9][a-z0-9-]{0,63}$/;function Vn(e){return e instanceof Error?e.message:String(e)}function Hn(e,t){if(t)return typeof e==`string`&&e.length>0?e:void 0;if(le(e))return ae;if(typeof e==`string`&&e.length>0)return e;re(e)}function Un(e){return typeof e!=`object`||!e?!1:Array.isArray(Reflect.get(e,`sections`))}function Wn({addonId:n}){let{t:f}=Y(),p=A(),m=s(),g=G(),v=Oe({editKey:`oidcEdit`,newKey:`oidcNew`}),[y,b]=c(!1),[x,S]=c(null),[C,w]=c(``),[T,E]=c({...zn}),D=t(null),O=a({queryKey:[...Ln,n],queryFn:async()=>p.trpcClient.oidcConnections.listConnections.query({})}),j=a({queryKey:Rn,queryFn:async()=>p.trpcClient.oidcConnections.connectionFormSchema.query({})}),M=O.data??[],N=Un(j.data)?j.data:void 0,P=v.state,F=P.mode===`edit`?M.find(e=>e.id===P.id)??null:null;d(()=>{if(v.state.mode===`edit`&&F!==null){let e=`edit:${F.id}`;if(D.current===e)return;D.current=e,S(null),w(F.id),E(F.formValues===void 0?{...zn}:{...F.formValues});return}if(v.state.mode===`new`){if(D.current===`new`)return;D.current=`new`,S(null),w(``),E({...zn})}},[F,v.state]);let I=e(async()=>{await m.invalidateQueries({queryKey:Ln})},[m]),L=l({mutationFn:async e=>p.trpcClient.oidcConnections.deleteConnection.mutate({id:e}),onSuccess:async()=>I()}),ee=e(async e=>{await g({title:f(`system.oidcSettingsConnections.deleteOidcConnection`,`Delete OIDC connection?`),message:f(`system.oidcSettingsConnections.removeTheLoginButtonAnd`,`Remove “{{displayName}}” ({{id}}). The login button and IdP credentials for this id are dropped.`,{displayName:e.displayName,id:e.id}),confirmLabel:f(`common.delete`,`Delete`),cancelLabel:f(`common.cancel`,`Cancel`),variant:`danger`})&&(await L.mutateAsync(e.id),v.state.mode===`edit`&&v.state.id===e.id&&(v.close(),D.current=null))},[g,L,v,f]),R=e(async()=>{let e=T.displayName,t=typeof e==`string`&&e.trim()!==``?e.trim():``;if(t===``){S(`Display name is required.`);return}let n=v.state.mode===`new`,r=n?C.trim():F?.id??``;if(n&&!Bn.test(r)){S(`Instance id must be a lowercase slug (e.g. authentik, google).`);return}if(r===``){S(`That connection is no longer available.`);return}let i=Hn(T.clientSecret,n),a=T.icon,o=T.issuerUrl,s=T.clientId,c=T.redirectUri,l=T.scopes,u=T.usernameClaim,d=u===`email`||u===`sub`?u:`preferred_username`;b(!0),S(null);try{n&&await p.trpcClient.oidcConnections.createConnection.mutate({id:r,displayName:t}),await p.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 I(),v.close(),D.current=null}catch(e){S(Vn(e))}finally{b(!1)}},[C,F?.id,v,T,I,p]),z=i(()=>[{key:`id`,header:f(`system.oidcSettingsConnections.id`,`Id`),sortValue:e=>e.id,render:e=>u(`span`,{className:`font-mono text-xs text-foreground`,children:e.id})},{key:`name`,header:f(`system.oidcSettingsConnections.name`,`Name`),sortValue:e=>e.displayName,render:e=>u(`span`,{className:`truncate font-medium text-foreground`,children:e.displayName})},{key:`issuer`,header:f(`system.oidcSettingsConnections.issuer`,`Issuer`),sortValue:e=>e.issuerUrl,render:e=>u(`span`,{className:`truncate text-xs text-foreground-muted`,children:e.issuerUrl===``?`—`:e.issuerUrl})},{key:`status`,header:f(`system.oidcSettingsConnections.status`,`Status`),notSortableReason:`Badge`,render:e=>u(q,{variant:e.configured?`success`:`warning`,children:e.configured?f(`system.oidcSettingsConnections.configured`,`Configured`):f(`system.oidcSettingsConnections.notConfigured`,`Not configured`)})},{key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,nowrap:!0,render:e=>r(`div`,{className:`flex justify-end gap-1`,children:[u(U,{type:`button`,size:`sm`,variant:`secondary`,onClick:t=>{t.stopPropagation(),v.openEdit(e.id)},children:f(`common.edit`,`Edit`)}),u(U,{type:`button`,size:`sm`,variant:`ghost`,"aria-label":f(`system.oidcSettingsConnections.delete`,`Delete {{displayName}}`,{displayName:e.displayName}),title:f(`common.delete`,`Delete`),onClick:t=>{t.stopPropagation(),ee(e)},children:u(h,{className:`h-3.5 w-3.5 text-danger`})})]})}],[v,ee,f]),B=v.state.mode===`new`,V=B||F!==null,H=B?`new`:F===null?`closed`:`edit:${F.id}:${F.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:[f(`system.oidcSettingsConnections.eachRowIsOneIdp`,`Each row is one IdP. Redirect URI:`),` `,u(`span`,{className:`font-mono text-xs`,children:`/addon/${n}/<id>/callback`})]}),r(U,{type:`button`,size:`sm`,"data-testid":`oidc-connections-add`,onClick:()=>v.openNew(),children:[u(_,{className:`h-3.5 w-3.5`}),f(`system.oidcSettingsConnections.addConnection`,`Add connection`)]})]}),O.isError?u(`p`,{className:`text-sm text-danger`,children:f(`system.oidcSettingsConnections.couldNotLoadConnections`,`Could not load connections.`)}):null,O.isPending?u(ct,{className:`h-32 w-full`}):u(we,{columns:z,rows:M,rowKey:e=>e.id,pageSize:25,mobileMode:`scroll`,emptyMessage:f(`system.oidcSettingsConnections.noOidcConnectionsYetAdd`,`No OIDC connections yet. Add one to register an IdP.`),onRowClick:e=>v.openEdit(e.id),defaultSort:{columnKey:`name`,dir:`asc`}}),u(ot,{open:V,onClose:()=>{v.close(),S(null),D.current=null},title:B?f(`system.oidcSettingsConnections.addOidcConnection`,`Add OIDC connection`):f(`system.oidcSettingsConnections.edit`,`Edit {{value1}}`,{value1:F?.displayName??`connection`}),icon:k,width:`xl`,testId:`oidc-connection-editor`,error:x,footer:u(U,{type:`button`,size:`sm`,disabled:y||B&&C.trim()===``,onClick:()=>void R(),children:y?f(`system.oidcSettingsConnections.saving`,`Saving…`):f(`common.save`,`Save`)}),children:V?r(o,{children:[B?r(`div`,{children:[u(rt,{htmlFor:`oidc-connection-id`,children:f(`system.oidcSettingsConnections.instanceId`,`Instance id`)}),u(qe,{id:`oidc-connection-id`,value:C,onChange:e=>w(e.target.value),placeholder:`authentik`,autoComplete:`off`}),u(`p`,{className:`mt-1 text-xs text-foreground-muted`,children:f(`system.oidcSettingsConnections.urlSlugAppearsInAddon`,`URL slug — appears in /addon/{{addonId}}/<id>/callback. Stable; renaming is not supported after save.`,{addonId:n})})]}):r(`p`,{className:`text-sm text-foreground-muted`,children:[f(`system.oidcSettingsConnections.instanceId2`,`Instance id:`),` `,u(`span`,{className:`font-mono`,children:F?.id})]}),N===void 0?u(`p`,{className:`text-sm text-foreground-muted`,children:f(`system.oidcSettingsConnections.loadingForm`,`Loading form…`)}):u(Je,{schema:N,values:T,onChange:E,bare:!0},H)]}):null})]})}n();var Gn=3e4,Kn=[{capName:`auth-provider`,stageBadge:null},{capName:`user-passkeys`,stageBadge:`Second factor`}],qn={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 Jn(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 Yn(){let{t:e}=Y(),t=_e({capName:Kn[0].capName},{refetchInterval:Gn}),n=_e({capName:Kn[1].capName},{refetchInterval:Gn}),r=be(void 0,{refetchInterval:Gn}),a=i(()=>rn(r.data??[]),[r.data]),o=i(()=>{let e=[],r=[t.data??[],n.data??[]];for(let[t,n]of Kn.entries())for(let i of r[t]??[])e.push({addonId:i.addonId,displayName:a.get(i.addonId)??i.addonId,isActive:i.isActive,capName:n.capName,stageBadge:n.stageBadge});return e},[t.data,n.data,a]),s=[{id:`authentication`,label:e(`system.authentication.authenticationProviders`,`Authentication providers`),install:{capability:Kn[0].capName,label:qn.installLabel},entries:o.map(t=>({id:t.addonId,name:t.displayName,fallbackIcon:k,...nn(t.isActive),render:()=>u($t,{addonId:t.addonId,displayName:t.displayName,capName:t.capName,isActive:t.isActive,badges:t.stageBadge===null?null:u(q,{variant:`info`,className:en,children:t.stageBadge}),settingsContent:t.addonId.startsWith(`auth-oidc`)?u(Wn,{addonId:t.addonId}):void 0,panels:[{id:`about`,title:e(`system.authentication.about`,`About`),icon:Jn(t.addonId).icon,content:u(Xn,{addonId:t.addonId})}]})}))}];return u(tn,{embedded:!0,icon:k,title:qn.title,subtitle:qn.subtitle,groups:s,isLoading:t.isLoading||n.isLoading,emptyTitle:qn.emptyTitle,emptyDescription:qn.emptyDescription})}function Xn({addonId:e}){let{t}=Y(),n=Jn(e),i=n.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(i,{className:`h-4 w-4 mt-0.5 text-primary shrink-0`}),u(`div`,{className:`text-xs text-foreground font-medium`,children:n.headline})]}),u(`ul`,{className:`text-xs text-foreground-subtle space-y-1.5 pl-6 list-disc`,children:n.bullets.map((e,t)=>u(`li`,{children:e},t))}),n.setupSteps&&n.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`}),t(`system.authentication.setupSteps`,`Setup steps`)]}),u(`ol`,{className:`text-xs text-foreground space-y-0.5 pl-4 list-decimal`,children:n.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(ut,{to:`/system/my-access`,className:`underline text-primary`,children:t(`system.authentication.myAccess`,`My access`)}),` `,`→ “Two-factor authentication” → Enable 2FA. Admins can only remove a user’s active enrollment (lost device) from the`,` `,u(ut,{to:`/system/identity?tab=users`,className:`underline text-primary`,children:t(`system.authentication.users`,`Users`)}),` `,t(`system.authentication.pageViaActionsRemove2fa`,`page via Actions → “Remove 2FA”.`)]})]})]})}function Zn({isPending:e,error:t,what:n,onRetry:i,children:a}){let{t:o}=Y();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(Ae,{title:o(`certificates.queryBody.couldNotRead`,`Could not read {{what}}`,{what:n}),message:t.message.length>0?t.message:o(`certificates.queryBody.requestFailed`,`Request failed`),onRetry:i})}function Qn(){let{t:e}=Y(),t=K.deviceCredentials.getDeviceCaStatus.useQuery({}),n=t.data;return u(X,{id:`device-ca`,title:e(`certificates.deviceCaCard.deviceCertificateAuthority`,`Device certificate authority`),icon:k,description:e(`certificates.deviceCaCard.signsTheCertificateEachPaired`,`Signs the certificate each paired device holds. It is created the first time a device is paired.`),children:u(Zn,{isPending:t.isPending,error:t.error,what:`the device CA`,onRetry:()=>void t.refetch(),children:n!==void 0&&r(`div`,{className:`space-y-1`,"data-testid":`device-ca-status`,children:[r(W,{label:e(`certificates.deviceCaCard.state`,`State`),children:[n.state===`ready`&&u(q,{variant:`success`,children:e(`certificates.deviceCaCard.ready`,`Ready`)}),n.state===`absent`&&u(q,{variant:`default`,children:e(`certificates.deviceCaCard.notCreatedYet`,`Not created yet`)}),n.state===`unavailable`&&u(q,{variant:`danger`,children:e(`certificates.deviceCaCard.unavailable`,`Unavailable`)})]}),n.state===`ready`&&r(o,{children:[u(W,{label:e(`certificates.deviceCaCard.subject`,`Subject`),valueClassName:`font-mono`,children:n.subject}),u(W,{label:e(`certificates.deviceCaCard.fingerprintSha256`,`Fingerprint (SHA-256)`),valueClassName:`font-mono`,children:n.fingerprintSha256}),u(W,{label:e(`certificates.deviceCaCard.validUntil`,`Valid until`),children:n.validTo})]}),n.state===`unavailable`&&u(W,{label:e(`certificates.deviceCaCard.reason`,`Reason`),children:u(`span`,{className:`text-danger`,children:n.reason})})]})})})}n();function $n(){let{t:e}=Y(),t=K.useUtils(),n=K.deviceCredentials.getDeviceCertificateSettings.useQuery({}),[i,a]=c(null),o=K.deviceCredentials.setDeviceCertificateSettings.useMutation({onSuccess:()=>{a(null),t.deviceCredentials.getDeviceCertificateSettings.invalidate()},onError:e=>a(`Could not save: ${e.message}`)});return u(Zn,{isPending:n.isPending,error:n.error,what:`the enrollment setting`,onRetry:()=>void n.refetch(),children:n.data!==void 0&&r(W,{label:e(`certificates.deviceSettingsRow.usersCanEnrollTheirOwn`,`Users can enroll their own devices`),actions:u(Xe,{checked:n.data.selfEnrollment===`allowed`,disabled:o.isPending,"aria-label":e(`certificates.deviceSettingsRow.usersCanEnrollTheirOwn`,`Users can enroll their own devices`),onCheckedChange:e=>o.mutate({selfEnrollment:e?`allowed`:`disabled`})}),children:[u(`span`,{className:`text-[11px] text-foreground-subtle`,children:n.data.selfEnrollment===`allowed`?e(`certificates.deviceSettingsRow.allowedAUserSignedIn`,`Allowed - a user signed in on a phone can keep it signed in. Pairing by QR works either way.`):e(`certificates.deviceSettingsRow.disabledOnlyAnAdminCan`,`Disabled - only an admin can pair a device, with a QR code.`)}),i!==null&&u(`span`,{className:`block text-[11px] text-danger`,children:i})]})})}n();function er(e){let[t,n]=c(()=>Date.now());return d(()=>{let t=setInterval(()=>n(Date.now()),e);return()=>clearInterval(t)},[e]),t}n();var tr=80,nr=208;function rr({open:e,users:t,onClose:n,onPaired:i}){let{t:a}=Y(),o=K.deviceCredentials.startEnrollment.useMutation({onSuccess:i}),[s,l]=c(``),[d,f]=c(``),p=s===``?t[0]?.id??``:s,m=o.data,h=()=>{o.reset(),f(``),n()};return u(ot,{open:e,onClose:h,title:a(`certificates.pairDeviceDialog.pairADevice`,`Pair a device`),icon:y,width:`md`,testId:`pair-device-dialog`,error:o.isError?o.error.message:null,footer:m===void 0?r(U,{type:`button`,onClick:()=>{let e=d.trim();p===``||e===``||o.mutate({userId:p,deviceName:e})},disabled:o.isPending||p===``||d.trim()===``,children:[o.isPending&&u(S,{className:`h-3.5 w-3.5 animate-spin`,"aria-hidden":!0}),a(`certificates.pairDeviceDialog.createPairingCode`,`Create pairing code`)]}):u(U,{type:`button`,variant:`outline`,onClick:h,children:a(`certificates.pairDeviceDialog.done`,`Done`)}),children:m===void 0?r(`div`,{className:`space-y-3`,children:[u(`p`,{className:`text-[11px] text-foreground-subtle`,children:a(`certificates.pairDeviceDialog.createsAOneTimeCode`,`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(Ce,{label:a(`certificates.pairDeviceDialog.user`,`User`),required:!0,children:u(De,{value:p,onChange:e=>l(e.target.value),options:t.map(e=>({value:e.id,label:e.username}))})}),u(Ce,{label:a(`certificates.pairDeviceDialog.deviceName`,`Device name`),required:!0,description:a(`certificates.pairDeviceDialog.howThisPhoneIsListed`,`How this phone is listed, e.g. Anna's iPhone.`),children:u(qe,{value:d,maxLength:tr,onChange:e=>f(e.target.value),placeholder:a(`certificates.pairDeviceDialog.annaSIphone`,`Anna's iPhone`),autoFocus:!0})})]}):u(ir,{enrollUrl:m.enrollUrl,expiresAt:m.expiresAt,hubKnown:m.hubOrigin!==null,onRestart:()=>o.reset()})})}function ir({enrollUrl:e,expiresAt:t,hubKnown:n,onRestart:i}){let{t:a}=Y(),o=Ut(t,er(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:o.expired?`opacity-30`:void 0,children:u(me,{value:e,size:nr,alt:a(`certificates.pairDeviceDialog.enrollmentQrCode`,`Enrollment QR code`)})}),r(`div`,{className:`min-w-0 flex-1 space-y-2`,children:[u(`p`,{className:`text-[11px] text-foreground-subtle`,children:a(`certificates.pairDeviceDialog.openTheCamstackAppOn`,`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:o.expired?a(`certificates.pairDeviceDialog.expiredCreateANewCode`,`Expired - create a new code`):a(`certificates.pairDeviceDialog.expiresIn`,`Expires in {{label}}`,{label:o.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(Se,{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:a(`certificates.pairDeviceDialog.theHubCouldNotName`,`The hub could not name an address for this link, so the app must already know it.`)})]}),o.expired&&u(U,{type:`button`,variant:`outline`,size:`sm`,onClick:i,children:a(`certificates.pairDeviceDialog.newCode`,`New code`)})]})]})})}n();var ar={one:`device`,many:`devices`};function or({pairOpen:e,onPairClose:t}){let{t:n}=Y(),a=G(),o=Le(),s=K.useUtils(),l=K.deviceCredentials.listDeviceCredentials.useQuery({includeRevoked:!0}),d=Ie(),[p,m]=c(null),[g,_]=c(null),b=()=>void s.deviceCredentials.listDeviceCredentials.invalidate(),x=e=>t=>{_(null),m(`${e} failed: ${t.message}`)},S=()=>{_(null),b()},C=K.deviceCredentials.revokeDeviceCredential.useMutation({onSuccess:S,onError:x(`Revoke`)}),w=K.deviceCredentials.deleteDeviceCredential.useMutation({onSuccess:e=>{e.result!==`deleted`&&m(e.result===`live`?`Only a revoked device can be deleted: revoke it first.`:`That device no longer exists.`),S()},onError:x(`Delete`)}),T=K.deviceCredentials.renameDeviceCredential.useMutation({onSuccess:S,onError:x(`Rename`)}),E=Rt(ar,e=>C.mutateAsync({id:e}),b),D=E.busy||g!==null,O=i(()=>(l.data??[]).map(Ht),[l.data]),k=async e=>{await a({title:n(`certificates.devicesCard.revoke`,`Revoke "{{name}}"?`,{name:e.name}),message:n(`certificates.devicesCard.sDeviceStopsSigningIn`,`{{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.`,{ownerName:e.ownerName}),confirmLabel:n(`certificates.devicesCard.revoke2`,`Revoke`),variant:`danger`})&&(m(null),_(e.id),C.mutate({id:e.id}))},A=async e=>{await a({title:n(`certificates.devicesCard.delete`,`Delete "{{name}}"?`,{name:e.name}),message:n(`certificates.devicesCard.isRemovedFromTheList`,`{{name}} is removed from the list. The audit trail keeps the revocation.`,{name:e.name}),confirmLabel:n(`common.delete`,`Delete`),variant:`danger`})&&(m(null),_(e.id),w.mutate({id:e.id}))},j=async e=>{let t=(await o({title:n(`certificates.devicesCard.renameDevice`,`Rename device`),label:n(`certificates.devicesCard.deviceName`,`Device name`),defaultValue:e.name,confirmLabel:n(`certificates.devicesCard.rename`,`Rename`)}))?.trim()??``;t===``||t===e.name||(m(null),_(e.id),T.mutate({id:e.id,deviceName:t}))},M={label:n(`certificates.devicesCard.revoke2`,`Revoke`),icon:f,isAvailable:jt,onRun:e=>void k(e),busyId:C.isPending?g:null,disabled:D},N=[{label:n(`certificates.devicesCard.rename`,`Rename`),icon:v,tone:`neutral`,isAvailable:()=>!0,onRun:e=>void j(e),busyId:T.isPending?g:null,disabled:D},{label:n(`common.delete`,`Delete`),icon:h,isAvailable:Lt,onRun:e=>void A(e),busyId:w.isPending?g:null,disabled:D}];return r(X,{id:`devices`,title:n(`certificates.devicesCard.devices`,`Devices`),icon:y,description:n(`certificates.devicesCard.phonesThatStaySignedIn`,`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(p,E.outcome),onDismissNotice:()=>{m(null),E.dismiss()},children:[u($n,{}),u(zt,{rows:O,label:`devices`,isLoading:l.isPending,loadError:l.error===null?null:l.error.message||`Request failed`,emptyText:`No devices paired yet.`,expiresNone:`—`,action:M,extraActions:N,bulk:{revoke:E,noun:ar,isSelectable:jt}}),u(rr,{open:e,users:d.data??[],onClose:t,onPaired:b})]})}var sr={ok:`text-foreground-subtle`,soon:`text-warning`,expired:`text-danger`,unknown:`text-foreground-subtle`};function cr(e){let t=e.find(e=>e.isHub);return t?.https.kind===`served`?t.https.status.caFingerprintSha256:null}function lr({https:e,mesh:t,now:n}){let{t:i}=Y(),a=fe().data?.caCertPem??``,o=()=>{if(a===``)return;let e=URL.createObjectURL(new Blob([a],{type:`application/x-pem-file`})),t=document.createElement(`a`);t.href=e,t.download=`camstack-ca.crt`,t.click(),URL.revokeObjectURL(e)},s=t?.ca,c=s?.state===`ready`?Date.parse(s.validTo):null,l=t?.listener;return r(`div`,{className:`space-y-1`,"data-testid":`ca-strip`,children:[u(W,{label:i(`certificates.caStrip.localHttpsCaSha256`,`Local HTTPS CA (SHA-256)`),valueClassName:`font-mono`,children:r(`span`,{className:`flex flex-wrap items-center gap-2`,children:[cr(e)??`—`,a!==``&&r(U,{type:`button`,variant:`ghost`,size:`sm`,onClick:o,children:[u(p,{className:`h-3 w-3`,"aria-hidden":!0}),i(`certificates.caStrip.downloadCa`,`Download CA`)]})]})}),u(W,{label:i(`certificates.caStrip.clusterCaSha256`,`Cluster CA (SHA-256)`),valueClassName:`font-mono`,children:s===void 0?`—`:s.state===`ready`?s.fingerprintSha256:r(`span`,{className:`text-danger`,children:[`Unavailable - `,s.reason]})}),s?.state===`ready`&&r(W,{label:i(`certificates.caStrip.clusterCaValidUntil`,`Cluster CA valid until`),children:[s.validTo,c!==null&&!Number.isNaN(c)&&r(`span`,{className:`ml-2 text-[10px] ${sr[qt(c,n)]}`,children:[`(`,Nt(c,n),`)`]})]}),l!==void 0&&r(W,{label:i(`certificates.caStrip.nodeListener`,`Node listener`),children:[l.state===`open`&&u(q,{variant:`success`,children:i(`certificates.caStrip.open`,`Open`)}),l.state===`not-started`&&u(q,{variant:`default`,children:i(`certificates.caStrip.notStarted`,`Not started`)}),l.state===`closed`&&r(`span`,{className:`text-danger`,children:[`Closed since `,Pt(l.since),` - every node is refused.`,` `,l.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:i(`certificates.caStrip.theCertificateRegistryIsNot`,`The certificate registry is not up, so the node list below is incomplete.`)})]})]})}function ur(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 dr(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 fr(e){return e.isHub||e.mesh===null?dr(e):null}var pr={ok:`text-foreground-subtle`,soon:`text-warning`,expired:`text-danger`,unknown:`text-foreground-subtle`},mr={enroll:`Issued at enrollment`,renewal:`Issued by a renewal`,boot:`Issued at boot`,pairing:`Issued at pairing`,observed:`Observed on its connection`},hr={uploaded:`Uploaded`,generated:`Generated`,disabled:`Disabled`};function gr(e){let t=e.https?.https;return t?.kind===`served`?Gt(t.status.validTo):null}function _r({ms:e,now:t}){return e===null?u(`span`,{className:`text-foreground-subtle`,children:`—`}):r(`div`,{children:[u(`div`,{children:Pt(e)}),u(`div`,{className:`text-[10px] ${pr[qt(e,t)]}`,children:Nt(e,t)})]})}function vr({row:e}){let{t}=Y(),n=e.https?.https;return n===void 0?u(`span`,{className:`text-foreground-subtle`,children:`—`}):n.kind===`served`?r(`div`,{title:n.status.leafFingerprintSha256??``,children:[u(q,{variant:`success`,className:`text-[10px]`,children:t(`certificates.nodesColumns.served`,`Served`)}),u(`span`,{className:`ml-1.5 text-[10px] text-foreground-subtle`,children:hr[n.status.mode]}),u(`div`,{className:`mt-1 font-mono text-[10px] text-foreground-subtle`,children:Wt(n.status.leafFingerprintSha256)}),n.status.sans.length>0&&u(`div`,{className:`mt-0.5 max-w-[14rem] truncate font-mono text-[10px] text-foreground-subtle`,title:n.status.sans.join(`, `),children:n.status.sans.join(`, `)})]}):r(`div`,{className:`max-w-[16rem]`,children:[u(q,{variant:n.kind===`unreadable`?`danger`:`warning`,className:`text-[10px]`,children:n.kind===`unreadable`?t(`certificates.nodesColumns.unreadable`,`Unreadable`):t(`certificates.nodesColumns.notServed`,`Not served`)}),u(`div`,{className:`mt-1 whitespace-normal text-[10px] text-foreground-subtle`,children:n.reason})]})}function yr({row:e}){let{t}=Y(),n=e.mesh?.current??null;if(n===null)return u(`span`,{className:`text-foreground-subtle`,children:t(`certificates.nodesColumns.noneRecorded`,`None recorded`)});let i=e.mesh?.history.length??0;return r(`div`,{children:[u(`div`,{className:`font-mono text-[11px]`,title:n.serial,children:Vt(n.serial)}),u(`div`,{className:`font-mono text-[10px] text-foreground-subtle`,title:n.fingerprintSha256,children:Wt(n.fingerprintSha256)}),r(`div`,{className:`text-[10px] text-foreground-subtle`,children:[mr[n.issuedVia],i>0?` · ${String(i)} earlier`:``]})]})}function br({row:e}){let{t}=Y(),n=e.mesh?.presentingCurrent??null;return n===null?u(`span`,{className:`text-foreground-subtle`,children:e.online?`—`:t(`certificates.nodesColumns.offline`,`Offline`)}):n?u(q,{variant:`success`,className:`text-[10px]`,children:t(`common.yes`,`Yes`)}):u(q,{variant:`warning`,className:`text-[10px]`,children:t(`certificates.nodesColumns.noPresentsAnother`,`No - presents another`)})}function xr(e){let t=e.icon;return r(U,{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 Sr({reasons:e}){let{t}=Y();return r(Ee,{className:`inline-block`,children:[u(We,{children:u(`span`,{className:`cursor-help text-[11px] text-foreground-subtle`,"data-testid":`hub-managed-note`,children:t(`certificates.nodesColumns.managedByTheHub`,`Managed by the hub`)})}),u(Ge,{children:u(`ul`,{className:`max-w-xs space-y-1 whitespace-normal text-left text-[11px]`,children:e.map(e=>u(`li`,{children:e},e))})})]})}function Cr({row:e,o:t}){let{t:n}=Y(),i=e.https===null?`No HTTPS inventory for this node.`:Ft(e.https).reason,a=dr(e),o=fr(e),s=n=>t.running?.nodeId===e.nodeId&&t.running.action===n,c=t=>!e.isHub||t===null,l=[i,a,o].filter((e,t,n)=>e!==null&&n.indexOf(e)===t);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:[c(i)&&u(xr,{label:n(`certificates.nodesColumns.renewHttps`,`Renew HTTPS`),ariaLabel:n(`certificates.nodesColumns.renewTheCertificateOn`,`Renew the certificate on {{nodeId}}`,{nodeId:e.nodeId}),icon:F,reason:i,busy:t.busy,spinning:s(`renew-https`),danger:!1,onClick:()=>t.onRenewHttps(e)}),c(a)&&u(xr,{label:s(`renew-identity`)?n(`certificates.nodesColumns.renewing`,`Renewing…`):n(`certificates.nodesColumns.renewIdentity`,`Renew identity`),ariaLabel:n(`certificates.nodesColumns.renewTheClusterCertificateOf`,`Renew the cluster certificate of {{nodeId}}`,{nodeId:e.nodeId}),icon:F,reason:a,busy:t.busy,spinning:s(`renew-identity`),danger:!1,onClick:()=>t.onRenewIdentity(e)}),c(o)&&u(xr,{label:n(`certificates.nodesColumns.revokeIdentity`,`Revoke identity`),ariaLabel:n(`certificates.nodesColumns.revokeTheClusterCertificateOf`,`Revoke the cluster certificate of {{nodeId}}`,{nodeId:e.nodeId}),icon:f,reason:o,busy:t.busy,spinning:s(`revoke-identity`),danger:!0,onClick:()=>t.onRevokeIdentity(e)})]}),e.isHub&&l.length>0&&u(Sr,{reasons:l}),!e.isHub&&i!==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:i}),!e.isHub&&a!==null&&u(`div`,{className:`w-full whitespace-normal text-right text-[10px] text-foreground-subtle`,"data-testid":`mesh-reason-${e.nodeId}`,children:a})]})}function wr(e){return[{key:`node`,header:J.t(`certificates.nodesColumns.node`,`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(q,{variant:`info`,className:`text-[10px]`,children:`hub`}),!e.online&&u(q,{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(vr,{row:e})},{key:`https-expires`,header:J.t(`certificates.nodesColumns.httpsExpires`,`HTTPS expires`),sortValue:e=>gr(e),render:t=>u(_r,{ms:gr(t),now:e.now})},{key:`identity`,header:J.t(`certificates.nodesColumns.identity`,`Identity`),sortValue:e=>e.mesh?.current?.serial??null,render:e=>u(yr,{row:e})},{key:`identity-expires`,header:J.t(`certificates.nodesColumns.identityExpires`,`Identity expires`),sortValue:e=>e.mesh?.current?.notAfter??null,render:t=>u(_r,{ms:t.mesh?.current?.notAfter??null,now:e.now})},{key:`presenting`,header:J.t(`certificates.nodesColumns.inUse`,`In use`),notSortableReason:`Offline nodes have no answer to order by.`,render:e=>u(br,{row:e})},{key:`actions`,header:J.t(`certificates.nodesColumns.actions`,`Actions`),align:`right`,notSortableReason:`Actions have no order.`,render:t=>u(Cr,{row:t,o:e})}]}n();function Tr(){let{t:e}=Y(),t=G(),n=K.useUtils(),a=er(6e4),o=K.certificates.listHttpsCertificates.useQuery(),s=K.certificates.getMeshCertificates.useQuery(),[l,d]=c(null),[f,p]=c(null),[m,h]=c(null),g=()=>{h(null),n.certificates.listHttpsCertificates.invalidate(),n.certificates.getMeshCertificates.invalidate()},_=e=>(t,n)=>{h(null),d(`${n.nodeId}: ${e} - ${t.message}`)},v=K.certificates.renewHttpsOnNode.useMutation({onSuccess:(t,n)=>{p({tone:`success`,message:t.restartRequired?e(`certificates.nodesCard.newCertificateIssuedRestartThe`,`{{nodeId}}: new certificate issued. Restart the node to serve it.`,{nodeId:n.nodeId}):e(`certificates.nodesCard.newCertificateIssuedAndServed`,`{{nodeId}}: new certificate issued and served.`,{nodeId:n.nodeId})}),g()},onError:_(`renewal failed`)}),y=K.certificates.renewMeshOnNode.useMutation({onSuccess:e=>{p(Bt(e)),g()},onError:_(`renewal could not start`)}),b=K.certificates.revokeMeshOnNode.useMutation({onSuccess:e=>{p({tone:`success`,message:`${e.nodeId}: ${e.next}`}),g()},onError:_(`revoke failed`)}),x=v.isPending||y.isPending||b.isPending,S=(e,t)=>{d(null),p(null),h({nodeId:e,action:t})},C=async n=>{await t({title:e(`certificates.nodesCard.renewHttpsOn`,`Renew HTTPS on "{{nodeId}}"?`,{nodeId:n.nodeId}),message:n.isHub?e(`certificates.nodesCard.aNewCertificateIsIssued`,`A new certificate is issued from the local CA. Clients that trust the CA keep working.`):e(`certificates.nodesCard.theNodeMakesANew`,`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:e(`certificates.nodesCard.renew`,`Renew`)})&&(S(n.nodeId,`renew-https`),v.mutate({nodeId:n.nodeId}))},w=e=>{S(e.nodeId,`renew-identity`),y.mutate({nodeId:e.nodeId})},T=async n=>{await t({title:e(`certificates.nodesCard.revokeTheIdentityOf`,`Revoke the identity of "{{nodeId}}"?`,{nodeId:n.nodeId}),message:e(`certificates.nodesCard.isDisconnectedAtOnceAnd`,`{{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.`,{nodeId:n.nodeId}),confirmLabel:e(`certificates.nodesCard.revokeAndDisconnect`,`Revoke and disconnect`),variant:`danger`})&&(S(n.nodeId,`revoke-identity`),b.mutate({nodeId:n.nodeId}))},E=wr({now:a,busy:x,running:m,onRenewHttps:e=>void C(e),onRenewIdentity:w,onRevokeIdentity:e=>void T(e)}),D=i(()=>ur(o.data??[],s.data),[o.data,s.data]),O=s.data?.registryAvailable??!0;return u(X,{id:`nodes`,title:e(`certificates.nodesCard.nodes`,`Nodes`),icon:N,description:e(`certificates.nodesCard.eachNodeHoldsTwoCertificates`,`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(l,f),onDismissNotice:()=>{d(null),p(null)},children:u(Zn,{isPending:o.isPending||s.isPending,error:o.error??s.error,what:`node certificates`,onRetry:()=>{o.refetch(),s.refetch()},children:r(`div`,{className:`space-y-3`,children:[u(lr,{https:o.data??[],mesh:s.data,now:a}),u(we,{columns:E,rows:D,rowKey:e=>e.nodeId,minWidthPx:960,mobileMode:`cards`,maxBodyHeight:Ve,defaultSort:{columnKey:`node`,dir:`asc`},emptyMessage:O?e(`certificates.nodesCard.noNodesReported`,`No nodes reported.`):e(`certificates.nodesCard.theCertificateRegistryIsNot`,`The certificate registry is not available yet, so nodes cannot be listed.`)})]})})})}function Er({pairOpen:e,onPairClose:t}){return r(`div`,{className:`space-y-4`,"data-testid":`certificates-page`,children:[u(or,{pairOpen:e,onPairClose:t}),u(Qn,{}),u(Tr,{})]})}function Dr({userId:e,username:t,onClose:n}){let{t:i}=Y(),a=G(),o=K.useUtils(),s=je({userId:e}),c=K.auth.listLoginMethods.useQuery(),l=pe({onSuccess:()=>void o.userManagement.listExternalIdentities.invalidate()}),d=new Map((c.data??[]).flatMap(e=>e.kind===`redirect`?[[e.id,e.label]]:[])),f=s.data??[],p=async(n,r)=>{await a({title:i(`users.externalIdentitiesModal.removeSignInLink`,`Remove sign-in link`),message:i(`users.externalIdentitiesModal.willNoLongerBeAble`,`"{{username}}" will no longer be able to sign in with this {{label}} account.`,{username:t,label:r}),confirmLabel:i(`common.remove`,`Remove`),variant:`danger`})&&l.mutate({userId:e,provider:n.provider,subject:n.subject})};return u(Be,{open:!0,onOpenChange:e=>!e&&n(),children:r(ge,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`external-identities-modal`,children:[u(de,{children:r(Qe,{className:`flex items-center gap-2`,children:[u(w,{className:`h-4 w-4 text-primary`}),r(`span`,{children:[i(`users.externalIdentitiesModal.linkedSignInAccounts`,`Linked sign-in accounts`),r(`span`,{className:`mt-0.5 block text-[11px] font-normal text-foreground-subtle`,children:[i(`users.externalIdentitiesModal.user`,`User:`),` `,u(`span`,{className:`font-mono`,children:t})]})]})]})}),u(ye,{className:`space-y-3`,children:s.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`}),i(`common.loading`,`Loading…`)]}):f.length===0?u(`p`,{className:`text-xs text-foreground-subtle`,children:i(`users.externalIdentitiesModal.noLinkedAccountsOnlyThe`,`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:f.map(e=>{let t=d.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:i(`users.externalIdentitiesModal.providerUnavailable`,`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 p(e,n),disabled:l.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(ne,{className:`h-3 w-3`}),i(`common.remove`,`Remove`)]})]},`${e.provider}|${e.subject}`)})})}),u(et,{children:u(U,{onClick:n,variant:`secondary`,children:i(`common.close`,`Close`)})})]})})}function Or({userId:e,username:t,onClose:n}){let{t:i}=Y(),a=s(),c=G(),l=ue({userId:e}),d=l.data,f=()=>a.invalidateQueries({queryKey:[[`userManagement`,`getTotpStatus`]]}),p=$e({onSuccess:()=>{f(),n()}}),m=l.isLoading?`loading`:d?.enabled?`enrolled`:`not_enrolled`;return u(Be,{open:!0,onOpenChange:e=>!e&&n(),children:r(ge,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,children:[u(de,{children:r(Qe,{className:`flex items-center gap-2`,children:[u(y,{className:`h-4 w-4 text-primary`}),r(`span`,{children:[i(`users.totpModal.twoFactorAuthentication`,`Two-factor authentication`),r(`span`,{className:`mt-0.5 block text-[11px] font-normal text-foreground-subtle`,children:[i(`users.totpModal.user`,`User:`),` `,u(`span`,{className:`font-mono`,children:t})]})]})]})}),r(ye,{className:`space-y-4`,children:[m===`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`}),i(`users.totpModal.checkingStatus`,`Checking status…`)]}),m===`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:i(`users.totpModal.2faNotEnrolled`,`2FA not enrolled`)}),u(`p`,{className:`mt-0.5`,children:i(`users.totpModal.onlyTheUserThemselvesCan`,`Only the user themselves can enable 2FA, from their own profile page.`)})]})]}),m===`enrolled`&&d&&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:i(`users.totpModal.2faIsActive`,`2FA is active`)}),r(`div`,{className:`text-foreground-subtle`,children:[`Enrolled on`,` `,d.confirmedAt?new Date(d.confirmedAt).toLocaleString():`—`]})]})]}),u(`div`,{className:`text-[11px] text-foreground-subtle`,children:i(`users.totpModal.removingHereClearsTheServer`,`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(U,{onClick:n,variant:`secondary`,children:i(`common.close`,`Close`)}),r(`button`,{onClick:async()=>{await c({title:i(`users.totpModal.remove2fa`,`Remove 2FA`),message:i(`users.totpModal.removeTwoFactorAuthenticationFor`,`Remove two-factor authentication for "{{username}}"? They'll be able to log in with just their password until they re-enroll from their own profile page.`,{username:t}),confirmLabel:i(`common.remove`,`Remove`),variant:`danger`})&&p.mutate({userId:e})},disabled:p.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:[p.isPending?u(S,{className:`h-3 w-3 animate-spin`}):u(T,{className:`h-3 w-3`}),i(`users.totpModal.remove2fa`,`Remove 2FA`)]})]})]})]})]})})}n();function kr({userId:e,username:t,onClose:n}){let{t:i}=Y(),{user:a,logout:o}=ft(),s=a?.id===e,l=G(),d=K.useUtils(),f=K.auth.listSessions.useQuery({userId:e}),[p,m]=c(null),h=K.auth.revokeSessions.useMutation({onSuccess:(e,t)=>{if(s&&`userId`in t){o();return}d.auth.listSessions.invalidate()},onError:e=>m(`Sign out failed: ${e.message}`)}),g=async e=>{await l({title:i(`users.userSessionsModal.signOutThisSession`,`Sign out this session`),message:i(`users.userSessionsModal.onWillHaveToSign`,`"{{username}}" on {{label}} will have to sign in again.`,{username:t,label:Jt(e.client).label}),confirmLabel:i(`users.userSessionsModal.signOut`,`Sign out`),variant:`danger`})&&(m(null),h.mutate({id:e.id}))},_=async()=>{await l({title:i(`users.userSessionsModal.signOutEverywhere`,`Sign out everywhere`),message:s?i(`users.userSessionsModal.everySessionOfYourOwn`,`Every session of your own account ends, this browser included: you will be signed out here too.`):i(`users.userSessionsModal.everySessionOfEndsAt`,`Every session of "{{username}}" ends at once; each device has to sign in again.`,{username:t}),confirmLabel:i(`users.userSessionsModal.signOutEverywhere`,`Sign out everywhere`),variant:`danger`})&&(m(null),h.mutate({userId:e}))},v=h.isPending&&h.variables!==void 0&&`id`in h.variables?h.variables.id:null;return u(Be,{open:!0,onOpenChange:e=>!e&&n(),children:r(ge,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`user-sessions-modal`,children:[u(de,{children:r(Qe,{className:`flex items-center gap-2`,children:[u(te,{className:`h-4 w-4 text-primary`}),r(`span`,{children:[i(`users.userSessionsModal.activeSessions`,`Active sessions`),r(`span`,{className:`mt-0.5 block text-[11px] font-normal text-foreground-subtle`,children:[i(`users.userSessionsModal.user`,`User:`),` `,u(`span`,{className:`font-mono`,children:t})]})]})]})}),r(ye,{className:`space-y-3`,children:[p!==null&&u(`div`,{className:`text-[11px] text-danger`,children:p}),u(Kt,{sessions:f.data??[],isLoading:f.isLoading,loadError:f.isError?f.error?.message??`Request failed`:null,emptyText:`No active sessions.`,onRevoke:e=>void g(e),revokingId:v})]}),r(et,{className:`justify-between`,children:[r(`button`,{onClick:()=>void _(),disabled:h.isPending||(f.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:[h.isPending&&v===null?u(S,{className:`h-3 w-3 animate-spin`}):u(z,{className:`h-3 w-3`}),i(`users.userSessionsModal.signOutEverywhere`,`Sign out everywhere`)]}),u(U,{onClick:n,variant:`secondary`,children:i(`common.close`,`Close`)})]})]})})}function Ar({icon:e,label:t,count:n,all:i,total:a}){let{t:o}=Y();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?o(`users.scopePreview.all`,`all {{total}}`,{total:a}):o(`users.scopePreview.of`,`{{count}} of {{total}}`,{count:n,total:a})})]})}function jr({scopes:e,isAdmin:t,invalidReason:n}){let{t:i}=Y(),s=A(),c=a({queryKey:[`auth`,`previewScope`,e,t],enabled:n===null,queryFn:()=>s.trpcClient.auth.previewScope.query({scopes:[...e],isAdmin:t})}),{data:l}=tt({projection:`slim`}),d=l?.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(c.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`}),i(`users.scopePreview.resolving`,`Resolving…`)]});if(c.isError||!c.data)return u(`div`,{className:`rounded-lg border border-border bg-surface p-3`,children:u(`p`,{className:`text-[11px] text-danger`,children:i(`users.scopePreview.couldNotResolveThisGrant`,`Could not resolve this grant set. Saving is still allowed — the server enforces the same rules either way.`)})});let f=c.data;return u(`div`,{className:`space-y-2 rounded-lg border border-border bg-surface p-3`,children:f.isAdmin?r(`p`,{className:`text-[11px] text-foreground`,children:[u(`span`,{className:`font-medium`,children:i(`users.scopePreview.administrator`,`Administrator`)}),` `,`— unrestricted. Grants are ignored for an admin.`]}):r(o,{children:[u(Ar,{icon:m,label:i(`users.scopePreview.devicesTheyCanSee`,`Devices they can see`),count:f.device.view.deviceCount,all:f.device.view.all,total:d}),u(Ar,{icon:v,label:i(`users.scopePreview.devicesTheyCanOperate`,`Devices they can operate`),count:f.device.create.deviceCount,all:f.device.create.all,total:d}),u(Ar,{icon:h,label:i(`users.scopePreview.devicesTheyCanDelete`,`Devices they can delete`),count:f.device.delete.deviceCount,all:f.device.delete.all,total:d}),r(`div`,{className:`border-t border-border pt-2 text-[10px] text-foreground-subtle`,children:[i(`users.scopePreview.systemAccess`,`System access:`),` `,f.system.length===0?`none`:f.system.join(`, `),f.capabilities.length>0&&r(o,{children:[` `,i(`users.scopePreview.extraCapabilities`,`· Extra capabilities:`),` `,f.capabilities.map(e=>e.name).join(`, `)]}),f.addons.length>0&&r(o,{children:[` `,i(`users.scopePreview.addons`,`· Addons:`),` `,f.addons.map(e=>e.name).join(`, `)]})]}),f.device.view.deviceCount===0&&u(`p`,{className:`text-[10px] text-warning`,children:i(`users.scopePreview.thisUserWillNotBe`,`This user will not be able to see any device.`)})]})})}n();function Mr(e){let t=se(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 Nr(e){return e.mode===`advanced`?e.advancedScopes:e.roleId===null?[]:ie({roleId:e.roleId,selector:e.selector,includeLinked:e.includeLinked})}function Pr({user:e,onClose:t,onSubmit:n,submitting:a,callerScopes:s}){let{t:l}=Y(),d=i(()=>Mr(e.scopes??[]),[e.scopes]),[f,p]=c(d),[m,h]=c(d.mode===`advanced`),g=i(()=>Nr(f),[f]),_=!e.isAdmin&&f.mode===`role`&&f.roleId===null,v=i(()=>e.isAdmin?null:f.mode===`role`&&f.roleId===null?`Pick what this user can do to see the result.`:Fe(g),[e.isAdmin,f.mode,f.roleId,g]),y=e=>p({...f,...e});return u(Be,{open:!0,onOpenChange:e=>!e&&t(),children:r(ge,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,className:`md:max-w-2xl`,children:[r(de,{children:[r(Qe,{children:[`Access — `,e.username]}),u(`p`,{className:`text-[10px] text-foreground-subtle`,children:e.isAdmin?l(`users.userAccessModal.thisUserIsAnAdministrator`,`This user is an administrator — they can do everything, and the settings below are ignored.`):l(`users.userAccessModal.chooseWhatTheyCanDo`,`Choose what they can do, then which devices it applies to.`)})]}),r(ye,{className:`space-y-4`,children:[_&&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:l(`users.userAccessModal.noAccess`,`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:l(`users.userAccessModal.1WhatCanTheyDo`,`1 · What can they do`)}),u(`div`,{className:`space-y-1.5`,children:oe.map(e=>{let t=f.mode===`role`&&f.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:()=>y({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(!m){p({...f,mode:`advanced`,advancedScopes:g}),h(!0);return}h(!1),p(Mr(f.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(m?P:x,{className:`h-3 w-3`}),l(`users.userAccessModal.advancedEditRawGrants`,`Advanced — edit raw grants`)]}),m&&r(`div`,{className:`rounded-lg border border-border p-2`,children:[u(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:l(`users.userAccessModal.oneRowPerGrantAnything`,`One row per grant. Anything expressible here overrides the three roles above; close this section to go back to them.`)}),u(Me,{value:f.advancedScopes,onChange:e=>y({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.`]})})]})]}),f.mode===`role`&&r(`section`,{className:`space-y-2`,children:[u(`h3`,{className:`text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:l(`users.userAccessModal.2OnWhichDevices`,`2 · On which devices`)}),u(Ue,{value:f.selector,onChange:e=>y({selector:e}),includeLinked:f.includeLinked,onIncludeLinkedChange:e=>y({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:f.mode===`role`?l(`users.userAccessModal.3Result`,`3 · Result`):l(`users.userAccessModal.2Result`,`2 · Result`)}),u(jr,{scopes:g,isAdmin:e.isAdmin,invalidReason:v})]})]}),r(et,{children:[u(U,{variant:`outline`,size:`sm`,onClick:t,children:l(`common.cancel`,`Cancel`)}),u(U,{size:`sm`,onClick:()=>n([...g]),disabled:a||v!==null,children:a?u(S,{className:`h-3 w-3 animate-spin`}):l(`users.userAccessModal.saveAccess`,`Save access`)})]})]})})}n();var Fr=8;function Ir(){return{username:``,password:``,isAdmin:!1}}function Lr(e){return{id:e.id,username:e.username,password:``,isAdmin:e.isAdmin}}function Rr(e){return e instanceof Error?e.message:`Something went wrong`}function zr(){let{t:e}=Y(),t=s(),{user:n}=ft(),{state:i,openNew:a,openEdit:l,close:f}=Oe(),[p,m]=c(null),[g,x]=c(null),[C,T]=c(!1),{data:E,isLoading:D,isError:O,error:A,refetch:j}=Ie(),M=G(),N=Le(),P=()=>t.invalidateQueries({queryKey:[[`userManagement`,`listUsers`]]}),F=he(),I=Pe({onSuccess:P}),L=He({onSuccess:P}),R=xe({onSuccess:P}),z=st({onSuccess:()=>{P(),V(null)}}),[B,V]=c(null),[H,ne]=c(null),[re,ie]=c(null),[ae,oe]=c(null),se=E??[],ce=i.mode===`edit`?se.find(e=>e.id===i.id)??null:null,le=()=>{m(null),x(null),T(!1),F.reset(),L.reset(),f()};d(()=>{if(i.mode===`closed`){m(null),x(null),T(!1);return}if(i.mode===`new`){m(e=>e!==null&&e.id===void 0?e:Ir());return}if(ce===null){D||f();return}m(e=>e?.id===ce.id?e:Lr(ce))},[i,ce,D,f]);let ue=i.mode===`new`&&p!==null&&p.id===void 0||i.mode===`edit`&&p!==null&&ce!==null;async function de(t){await M({title:e(`admin.system.users.deleteUser`,`Delete user`),message:e(`admin.system.users.permanentlyDeleteUserThisCannot`,`Permanently delete user "{{username}}"? This cannot be undone — any active sessions will be revoked on next request.`,{username:t.username}),confirmLabel:e(`common.delete`,`Delete`),variant:`danger`})&&(I.mutate({id:t.id}),i.mode===`edit`&&i.id===t.id&&le())}async function fe(t){let n=await N({title:e(`admin.system.users.resetPassword`,`Reset password`),message:e(`admin.system.users.setANewPasswordFor`,`Set a new password for "{{username}}".`,{username:t.username}),label:e(`admin.system.users.newPassword`,`New password`),inputType:`password`,placeholder:e(`admin.system.users.atLeast8Characters`,`At least 8 characters`),confirmLabel:e(`admin.system.users.continue`,`Continue`),validate:e=>e.length<Fr?`Password must be at least ${String(Fr)} characters.`:null});n===null||n.length===0||await M({title:e(`admin.system.users.resetPassword`,`Reset password`),message:e(`admin.system.users.resetThePasswordForThey`,`Reset the password for "{{username}}"? They will need to use the new password on their next login.`,{username:t.username}),confirmLabel:e(`common.reset`,`Reset`)})&&R.mutate({id:t.id,newPassword:n})}function pe(e,t){t!==e.isAdmin&&L.mutate({id:e.id,isAdmin:t})}async function me(){if(p!==null){x(null);try{if(p.id===void 0){let e=p.username.trim();if(e===``||p.password.length<Fr)return;await F.mutateAsync({username:e,password:p.password,isAdmin:p.isAdmin})}else await L.mutateAsync({id:p.id,isAdmin:p.isAdmin});P(),le()}catch(e){x(Rr(e))}}}function ge(e){return e?new Date(typeof e==`number`?e:String(e)).toLocaleDateString(`en-GB`,{day:`2-digit`,month:`short`,year:`numeric`}):`—`}let _e=F.isPending||L.isPending,ve=p!==null&&p.id===void 0&&p.username.trim()!==``&&p.password.length>=Fr,ye=p!==null&&p.id!==void 0,be=_e||(p?.id===void 0?!ve:!ye),Se=e=>I.isPending&&I.variables?.id===e.id||L.isPending&&L.variables?.id===e.id||R.isPending&&R.variables?.id===e.id,Te=[{key:`username`,header:e(`admin.system.users.username`,`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:e(`admin.system.users.admin`,`Admin`),nowrap:!0,sortValue:e=>+!!e.isAdmin,render:t=>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:t.isAdmin,onChange:e=>pe(t,e.target.checked),disabled:Se(t),className:`rounded border-border focus:ring-primary disabled:opacity-50`}),u(`span`,{className:t.isAdmin?`text-primary font-medium`:`text-foreground-subtle`,children:t.isAdmin?e(`admin.system.users.admin`,`Admin`):e(`admin.system.users.regular`,`Regular`)})]})})},{key:`scopes`,header:e(`admin.system.users.access`,`Access`),render:t=>t.isAdmin?u(`span`,{className:`text-[10px] italic text-foreground-subtle`,children:e(`admin.system.users.everythingAdmin`,`everything (admin)`)}):u(`span`,{onClick:e=>e.stopPropagation(),children:r(U,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>V(t),title:e(`admin.system.users.configureAccess`,`Configure access`),children:[u(k,{className:`h-3 w-3 shrink-0 text-foreground-subtle`}),u(Br,{scopes:t.scopes??[]})]})})},{key:`createdAt`,header:e(`admin.system.users.created`,`Created`),nowrap:!0,sortValue:e=>e.createdAt,render:e=>u(`span`,{className:`text-foreground-subtle`,children:ge(e.createdAt)})},{key:`actions`,header:e(`admin.system.users.actions`,`Actions`),align:`right`,nowrap:!0,notSortableReason:`Row actions`,render:t=>{let i=Se(t),a=t.id!==n?.id&&t.totpEnabled;return r(`div`,{className:`flex items-center justify-end gap-1`,onClick:e=>e.stopPropagation(),children:[r(U,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>l(t.id),disabled:i,title:e(`admin.system.users.editUser`,`Edit user`),children:[u(v,{className:`h-3 w-3`}),e(`common.edit`,`Edit`)]}),a&&r(U,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>ne(t),disabled:i,title:e(`admin.system.users.removeTwoFactorAuthentication`,`Remove two-factor authentication`),children:[u(y,{className:`h-3 w-3`}),e(`admin.system.users.remove2fa`,`Remove 2FA`)]}),r(U,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>ie(t),disabled:i,title:e(`admin.system.users.linkedSignInAccounts`,`Linked sign-in accounts`),children:[u(w,{className:`h-3 w-3`}),e(`admin.system.users.signInLinks`,`Sign-in links`)]}),r(U,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>oe(t),disabled:i,title:e(`admin.system.users.activeSessions`,`Active sessions`),children:[u(te,{className:`h-3 w-3`}),e(`admin.system.users.sessions`,`Sessions`)]}),r(U,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>void fe(t),disabled:i,title:e(`admin.system.users.resetPassword`,`Reset password`),children:[u(ee,{className:`h-3 w-3`}),e(`admin.system.users.resetPassword`,`Reset password`)]}),r(U,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>void de(t),disabled:i,title:e(`admin.system.users.deleteUser`,`Delete user`),className:`text-danger hover:bg-danger/10`,children:[i?u(S,{className:`h-3 w-3 animate-spin`}):u(h,{className:`h-3 w-3`}),e(`common.delete`,`Delete`)]})]})}}];return r(bt,{embedded:!0,icon:b,title:e(`admin.system.users.users`,`Users`),subtitle:e(`admin.system.users.hubAccountsAdminFlagAccess`,`Hub accounts, admin flag, access scopes, sessions and sign-in links.`),actions:r(U,{size:`sm`,type:`button`,onClick:()=>{x(null),a()},children:[u(_,{className:`h-3.5 w-3.5`}),e(`admin.system.users.createUser`,`Create User`)]}),children:[O&&u(Ae,{title:e(`admin.system.users.couldNotLoadUsers`,`Could not load users`),message:Rr(A),onRetry:()=>void j()}),D&&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`}),e(`common.loading`,`Loading…`)]}),!D&&!O&&se.length===0&&u(ze,{icon:b,title:e(`admin.system.users.noUsersYet`,`No users yet`),description:e(`admin.system.users.createAUserToGrant`,`Create a user to grant hub access.`)}),!D&&!O&&se.length>0&&u(we,{columns:Te,rows:se,rowKey:e=>e.id,minWidthPx:560,maxBodyHeight:`max-h-[60vh]`,mobileMode:`scroll`,onRowClick:e=>l(e.id)}),u(ot,{open:ue,onClose:le,title:p?.id===void 0?e(`admin.system.users.createUser`,`Create User`):e(`admin.system.users.edit`,`Edit {{value1}}`,{value1:p.username||`user`}),icon:b,error:g,testId:`user-form-dialog`,footer:u(U,{size:`sm`,type:`button`,disabled:be,onClick:()=>void me(),children:_e?r(o,{children:[u(S,{className:`h-3.5 w-3.5 animate-spin`}),e(`admin.system.users.saving`,`Saving…`)]}):p?.id===void 0?e(`admin.system.users.create`,`Create`):e(`common.save`,`Save`)}),children:p!==null&&r(`div`,{className:`space-y-3`,children:[u(Ce,{label:e(`admin.system.users.username`,`Username`),required:p.id===void 0,children:u(qe,{value:p.username,onChange:e=>m({...p,username:e.target.value}),placeholder:`john`,autoFocus:p.id===void 0,disabled:p.id!==void 0,"data-testid":`user-form-username`})}),p.id===void 0&&u(Ce,{label:e(`admin.system.users.password`,`Password`),required:!0,description:e(`admin.system.users.atLeastCharacters`,`At least {{value1}} characters.`,{value1:String(Fr)}),children:u(it,{value:p.password,onValueChange:e=>m({...p,password:e}),shown:C,onToggleShown:()=>T(e=>!e),placeholder:`••••••••`,"data-testid":`user-form-password`})}),u(Ce,{label:e(`admin.system.users.admin`,`Admin`),description:e(`admin.system.users.unrestrictedAccessToEveryCapability`,`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:p.isAdmin,onChange:e=>m({...p,isAdmin:e.target.checked}),className:`rounded border-border focus:ring-primary`,"data-testid":`user-form-admin`}),u(`span`,{children:e(`admin.system.users.admin`,`Admin`)})]})}),p.id!==void 0&&u(`p`,{className:`text-[11px] text-foreground-subtle`,children:e(`admin.system.users.toChangeThePasswordUse`,`To change the password, use Reset password on the user's row. Access scopes are configured from the Access column.`)})]})}),H&&u(Or,{userId:H.id,username:H.username,onClose:()=>ne(null)}),re&&u(Dr,{userId:re.id,username:re.username,onClose:()=>ie(null)}),ae&&u(kr,{userId:ae.id,username:ae.username,onClose:()=>oe(null)}),B&&u(Vr,{user:B,onClose:()=>V(null),onSubmit:e=>z.mutate({userId:B.id,scopes:e}),submitting:z.isPending})]})}function Br({scopes:e}){let{t}=Y();if(e.length===0)return u(`span`,{className:`font-medium text-warning`,children:t(`admin.system.users.noAccess`,`No access`)});let n=se(e);return n===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:ce(n.roleId).label}),` ·`,` `,Ke(n.selector)]})}function Vr(e){let{user:t}=ft(),n=t?.isAdmin===!0;return u(Pr,{...e,callerScopes:n?null:t?.scopes??[]})}n();var Hr={"api-keys":$.tokens,"linked-sessions":$.linkedApps},Ur=`certificates`;function Wr(e){return r(U,{size:`sm`,type:`button`,"data-testid":`certificates-pair-device`,onClick:e,children:[u(y,{className:`h-3.5 w-3.5`,"aria-hidden":!0}),J.t(`systemPage.identity.pairADevice`,`Pair a device`)]})}function Gr(){let{t:e}=Y(),[t]=dt(),n=In(),[r,i]=c(!1),a=Hr[t.get(`tab`)??``];if(a!==void 0)return u(mt,{to:gt(`access`,{integration:a}),replace:!0});let o=lt(`/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===ht.access.tab?Fn(l,n.requestCreate):s===`certificates`?Wr(()=>i(!0)):void 0;return u(yt,{icon:o.icon,title:o.title,defaultSection:`users`,sectionsLabel:`${o.title} sections`,actions:d,sections:[{id:`users`,label:e(`systemPage.identity.users`,`Users`),content:u(zr,{})},{id:ht.access.tab,label:e(`systemPage.identity.tokensSessions`,`Tokens & sessions`),content:u(Pn,{createRequested:n.createRequested,onCreateConsumed:n.clearCreate}),ownedParams:vt.concat([pn.token,pn.scoped,pn.admin])},{id:Ur,label:e(`systemPage.identity.certificates`,`Certificates`),content:u(Er,{pairOpen:r,onPairClose:()=>i(!1)})},{id:ht.authentication.tab,label:e(`systemPage.identity.authentication`,`Authentication`),content:u(Yn,{}),ownedParams:vt}]})}export{Gr as IdentityPage};
|