@camstack/addon-admin-ui 1.2.471 → 1.2.472
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-D4joXvAw.js → AddonAssetIcon-BoV-s8vY.js} +1 -1
- package/dist/assets/Addons-DLTlJq7l.js +4 -0
- package/dist/assets/{AdminPage-92KQDOBy.js → AdminPage-DsAJhnoH.js} +1 -1
- package/dist/assets/{AdminSectionedPage-B-MH77Vx.js → AdminSectionedPage-DJx7aRbA.js} +1 -1
- package/dist/assets/AiProfiles-B8qFPcaJ.js +3 -0
- package/dist/assets/{BrokerForm-HjHrcv-P.js → BrokerForm-B3-e-xSz.js} +1 -1
- package/dist/assets/Build-LEBDM041.js +40 -0
- package/dist/assets/Calendars-BFKf7hvl.js +1 -0
- package/dist/assets/Cluster-CES248-c.js +1 -0
- package/dist/assets/CompositionCreateForm-CZcZeaFU.js +1 -0
- package/dist/assets/{CompositionEditorPage-CdJtfEi1.js → CompositionEditorPage-CBBOInEt.js} +1 -1
- package/dist/assets/Data-CGHht6N-.js +2 -0
- package/dist/assets/DeviceDetail-DYRNyiuG.js +2 -0
- package/dist/assets/{DeviceDoActionFields-B7UlBxQ0.js → DeviceDoActionFields-C9A5Vund.js} +1 -1
- package/dist/assets/{Devices-BAfbzc8b.js → Devices-BDcBpfdH.js} +1 -1
- package/dist/assets/{EmbedPlayerPage-CZM7W_SR.js → EmbedPlayerPage-kQQSKYcm.js} +1 -1
- package/dist/assets/History-DHqYgtT_.js +1 -0
- package/dist/assets/Identity-2aB-bcpG.js +1 -0
- package/dist/assets/IntegrationDetail-CHeCYf51.js +1 -0
- package/dist/assets/IntegrationHub-CDk7OQ80.js +1 -0
- package/dist/assets/Integrations-CLdAR_bC.js +1 -0
- package/dist/assets/Integrations-DtA-SgPz.js +1 -0
- package/dist/assets/{Library-X3g7Mvql.js → Library-jAJ1leN_.js} +1 -1
- package/dist/assets/Locations-D_Y_LS__.js +3 -0
- package/dist/assets/{Logs-C7Z3D9TY.js → Logs-CSouKCsq.js} +1 -1
- package/dist/assets/{MaskShapeCanvas-wRO0Yeyg.js → MaskShapeCanvas-DOTEtd0S.js} +1 -1
- package/dist/assets/{MotionZonesSettings-C8wTUqjQ.js → MotionZonesSettings-CvKLnfMs.js} +1 -1
- package/dist/assets/{MyAccess-Di7tv0VI.js → MyAccess-Dx2keRYZ.js} +1 -1
- package/dist/assets/{Network-3FZdyZoe.js → Network-DqeiKBG_.js} +1 -1
- package/dist/assets/{NodeAddonsSettingsPanel-ivhHs40k.js → NodeAddonsSettingsPanel-Bo6JkasG.js} +1 -1
- package/dist/assets/Notifications-BdRSwtaZ.js +1 -0
- package/dist/assets/Pipeline-B8BnTTB6.js +1 -0
- package/dist/assets/{PrivacyMaskSettings-DTetXxIV.js → PrivacyMaskSettings-B8RDIhLI.js} +1 -1
- package/dist/assets/Recordings-_9tze7ES.js +1 -0
- package/dist/assets/{ScanNetworkModal-DPHdPawS.js → ScanNetworkModal-D1789toC.js} +1 -1
- package/dist/assets/{SceneMonitorEditor-KPTdSp1h.js → SceneMonitorEditor-CidMFB_6.js} +1 -1
- package/dist/assets/SessionsList-BDFoAqB4.js +2 -0
- package/dist/assets/{Showroom-2gQYW-h2.js → Showroom-g9Vrk7ey.js} +1 -1
- package/dist/assets/{System-CDHw7Mcx.js → System-BFOcIYk6.js} +1 -1
- package/dist/assets/{Terminal-UXpMvEO1.js → Terminal-Dqvq98CQ.js} +5 -5
- package/dist/assets/{Viewer-ukAW_oJQ.js → Viewer-B6THeol3.js} +1 -1
- package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-KG1b6CPN.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-EdjPwsFV.js} +1 -1
- package/dist/assets/{addon-icons-context-gPkLZQ_G.js → addon-icons-context-BiqHN3N3.js} +1 -1
- package/dist/assets/{archive-CxbMF2yZ.js → archive-CnhS48Wh.js} +1 -1
- package/dist/assets/{assignment-candidates-CQGwwSSC.js → assignment-candidates-BuyOLzEY.js} +1 -1
- package/dist/assets/{authed-media-DpHGiSZS.js → authed-media-CIJCq1KJ.js} +1 -1
- package/dist/assets/{bell-off-CAN5HeZI.js → bell-off-7jyxJXpT.js} +1 -1
- package/dist/assets/{board-model-C6IplvmC.js → board-model-BtdRuNBI.js} +1 -1
- package/dist/assets/{boxes-BIYyTH0E.js → boxes-BA97gZyJ.js} +1 -1
- package/dist/assets/circle-slash-nVYwXt7M.js +1 -0
- package/dist/assets/client-DCH-eKE_.js +358 -0
- package/dist/assets/{cloud-upload-DvGDSWZB.js → cloud-upload-qezQXv3c.js} +1 -1
- package/dist/assets/crop-CFXeH_mC.js +1 -0
- package/dist/assets/{device-integration-icon-CRiv1vER.js → device-integration-icon-B4EZcZfv.js} +1 -1
- package/dist/assets/device-picker-model-C_qELDKl.js +1 -0
- package/dist/assets/{dist-BeSobRch.js → dist-BlRomFG_.js} +1 -1
- package/dist/assets/{eraser-CvXO1d9P.js → eraser-DLPQtKgN.js} +1 -1
- package/dist/assets/event-targets-DO8Gz77i.js +2 -0
- package/dist/assets/{format-Cz7vHmZ6.js → format-BYDOzxSv.js} +1 -1
- package/dist/assets/{hard-drive-download-xDn3u92n.js → hard-drive-download-g_5xAcFq.js} +1 -1
- package/dist/assets/{hostInit-Bcdd4neZ.js → hostInit-BDvZ4twh.js} +1 -1
- package/dist/assets/i18n-D3CF2V_j.js +1 -0
- package/dist/assets/{icons-Uf4a8HzM.js → icons-PobQxRhs.js} +1 -1
- package/dist/assets/index-BvsP28fN.css +2 -0
- package/dist/assets/index-Cv22-mxY.js +4 -0
- package/dist/assets/{key-D63R1Jty.js → key-C9NMIy5y.js} +1 -1
- package/dist/assets/{key-round-BH39VAkM.js → key-round-CaHb89Wi.js} +1 -1
- package/dist/assets/{layers-Cf6Xk9ts.js → layers-Avi8-PfM.js} +1 -1
- package/dist/assets/{linked-devices-model-DYRAb775.js → linked-devices-model-DgyEbI0V.js} +1 -1
- package/dist/assets/{list-ordered-9heb6Myu.js → list-ordered-6-NGRbR7.js} +1 -1
- package/dist/assets/{location-owned-usage-DPBYs4L0.js → location-owned-usage-BbuferaC.js} +1 -1
- package/dist/assets/{log-in-D6jMFDmP.js → log-in-D2R9cXBI.js} +1 -1
- package/dist/assets/{memory-stick-thjjQqgp.js → memory-stick-ev8VFA2q.js} +1 -1
- package/dist/assets/{message-square-plus-RcviJHk6.js → message-square-plus-C0P6xmPe.js} +1 -1
- package/dist/assets/{mf-entry-bootstrap-0-cbb0c272.js → mf-entry-bootstrap-0-3ff2e228.js} +2 -2
- package/dist/assets/{mic-off-DvjWBZuR.js → mic-off-BdFkx2wJ.js} +1 -1
- package/dist/assets/{monitor-off-DEBUzb17.js → monitor-off-DUZRNTFt.js} +1 -1
- package/dist/assets/{monitor-smartphone-rIimQM0r.js → monitor-smartphone-CsrrNdMJ.js} +1 -1
- package/dist/assets/mount-C_qELDKl.js +1 -0
- package/dist/assets/{player-overlays-DDFLUcm1.js → player-overlays-C6LCgH1T.js} +1 -1
- package/dist/assets/{recycle-CaQYaqJP.js → recycle-C3C83uwv.js} +1 -1
- package/dist/assets/remoteEntry-DY95P5t1.js +1 -0
- package/dist/assets/{scan-eye-BxF3-BiI.js → scan-eye-D2LQj-_4.js} +1 -1
- package/dist/assets/{scissors-DecmVZUv.js → scissors-DTz32yJa.js} +1 -1
- package/dist/assets/{search-x-CiS8b7vy.js → search-x-BQtbshQu.js} +1 -1
- package/dist/assets/{send-9ZOtM3uh.js → send-BfSwFs7e.js} +1 -1
- package/dist/assets/{settings-2-DVEGaYSK.js → settings-2-DJqkusF5.js} +1 -1
- package/dist/assets/{speaker-BLIN7g-W.js → speaker-D0AxWmRG.js} +1 -1
- package/dist/assets/src-V3rq3t7i.js +67 -0
- package/dist/assets/step-inspector-model-BwAjPOgf.js +1 -0
- package/dist/assets/{timer-reset-ESt9DRwd.js → timer-reset-DVs9TXU7.js} +1 -1
- package/dist/assets/{ungroup-uBZnvhmn.js → ungroup-vjygAxAO.js} +1 -1
- package/dist/assets/{unlink-BK0Zya0K.js → unlink-VhqcHI2O.js} +1 -1
- package/dist/assets/{usb--Z_ViOoE.js → usb-CTNmHXln.js} +1 -1
- package/dist/assets/{use-scenes-feed-Dpe5Lc_e.js → use-scenes-feed-DBEhAxap.js} +1 -1
- package/dist/assets/{use-stationary-objects-D9diuPzc.js → use-stationary-objects-BO1fOyUY.js} +1 -1
- package/dist/assets/useEventInvalidation-C_qELDKl.js +1 -0
- package/dist/assets/{useNodeUrlSelection-B-NA_JqT.js → useNodeUrlSelection-qvARJSiD.js} +1 -1
- package/dist/assets/user-round-CPpARWUk.js +1 -0
- package/dist/assets/{user-x-HmMRNIMy.js → user-x-BZF64XMi.js} +1 -1
- package/dist/assets/{video-BISLfAY2.js → video-BDVDsrHB.js} +1 -1
- package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-w3oA3S6D.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-XXht_Mtf.js} +2 -2
- package/dist/index.html +10 -10
- package/dist/server/addon.js +1 -1
- package/package.json +1 -1
- package/dist/assets/Addons-BNo3Y3g8.js +0 -4
- package/dist/assets/AiProfiles-CTHbBMUB.js +0 -3
- package/dist/assets/Build-Dlf7sJhk.js +0 -40
- package/dist/assets/Calendars-YnCFbUE7.js +0 -1
- package/dist/assets/Cluster-C4BsKola.js +0 -1
- package/dist/assets/CompositionCreateForm-D_Nmi2nG.js +0 -1
- package/dist/assets/Data-DkPbjXNV.js +0 -2
- package/dist/assets/DeviceDetail-BSWf6l6J.js +0 -2
- package/dist/assets/History-BfD8lMf9.js +0 -1
- package/dist/assets/Identity-6QdzCJrT.js +0 -1
- package/dist/assets/IntegrationDetail-B4X-8vcl.js +0 -1
- package/dist/assets/IntegrationHub-DCSIyXBI.js +0 -1
- package/dist/assets/Integrations-JcvhEroF.js +0 -1
- package/dist/assets/Integrations-XcsYTI2I.js +0 -1
- package/dist/assets/Locations-C--r0_cW.js +0 -3
- package/dist/assets/Notifications-D4LJlejx.js +0 -1
- package/dist/assets/Pipeline-BMhn1YbR.js +0 -1
- package/dist/assets/Recordings-Ct8JWW27.js +0 -1
- package/dist/assets/SessionsList-DrklEq9Z.js +0 -2
- package/dist/assets/circle-slash-BWtbQj2T.js +0 -1
- package/dist/assets/client-BnEPcD6s.js +0 -358
- package/dist/assets/crop-CDWciXWB.js +0 -1
- package/dist/assets/device-picker-model-DPfjZqVB.js +0 -1
- package/dist/assets/event-targets-CIffOoYs.js +0 -2
- package/dist/assets/i18n-DsGcRtAk.js +0 -1
- package/dist/assets/index-BMUVtgYi.css +0 -2
- package/dist/assets/index-CgxpaFwe.js +0 -4
- package/dist/assets/mount-DPfjZqVB.js +0 -1
- package/dist/assets/remoteEntry-DqDbkZhO.js +0 -1
- package/dist/assets/src-CWZRb0ia.js +0 -67
- package/dist/assets/step-inspector-model-B6Fs3NZo.js +0 -1
- package/dist/assets/useEventInvalidation-DPfjZqVB.js +0 -1
- package/dist/assets/user-round-D2ADHRLF.js +0 -1
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{$ as e,B as t,G as n,J as r,L as i,S as a,a as o,b as s,o as c,q as l,t as u,x as d}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEHpkaJP.js";import{Br as f,Cr as p,D as m,Di as h,En as g,G as _,Gn as v,It as y,J as b,Jn as x,Jr as S,K as C,Kn as w,Li as T,O as E,Ri as D,Si as O,St as k,T as A,V as j,W as ee,Xn as te,Xr as M,Z as ne,Zt as re,_t as N,bn as ie,dn as ae,dt as P,en as F,ht as oe,li as se,lr as I,or as L,ot as R,pi as z,pn as B,q as ce,r as le,sa as ue,t as de,ta as fe,vn as pe,xn as me,yn as V,z as H,zn as he,zr as ge}from"./player-overlays-DDFLUcm1.js";import{Di as U,Ei as _e,Fn as ve,Gt as W,In as ye,Jt as be,Kt as xe,Nn as Se,Oi as G,Pn as Ce,Pr as we,Qr as Te,Xt as Ee,Yt as De,ai as Oe,d as K,fi as ke,la as Ae,qt as je,ua as Me,wi as Ne}from"./client-BnEPcD6s.js";import{t as Pe}from"./archive-CxbMF2yZ.js";import{i as Fe,n as Ie,r as Le,t as Re}from"./scan-eye-BxF3-BiI.js";import{t as ze}from"./bell-off-CAN5HeZI.js";import{t as Be}from"./boxes-BIYyTH0E.js";import{n as Ve}from"./video-BISLfAY2.js";import{t as He}from"./circle-slash-BWtbQj2T.js";import{t as Ue}from"./layers-Cf6Xk9ts.js";import{$a as We,$c as Ge,$u as Ke,Aa as qe,Ac as Je,An as Ye,Ao as Xe,Bn as Ze,Br as Qe,Ci as $e,Cn as et,Co as tt,Cr as q,Da as nt,Dt as rt,Fr as it,Ft as at,Gn as ot,Gt as st,Hr as J,Ht as ct,Ic as lt,In as ut,It as dt,J as ft,Ja as pt,Ju as mt,Kn as ht,Kt as gt,L as _t,Ln as vt,Lo as yt,Ma as bt,Mc as xt,Mt as St,Na as Ct,No as wt,Nt as Tt,Oc as Et,On as Dt,Pa as Ot,Q as kt,Qc as At,Qr as jt,Qt as Mt,Qu as Nt,Rn as Pt,Rt as Ft,Sa as It,Tl as Lt,Tr as Rt,Ut as zt,Uu as Bt,Vc as Vt,Vn as Ht,Vt as Ut,Wa as Wt,Xt as Gt,Yr as Y,Yu as Kt,Z as qt,Zc as Jt,Zr as Yt,Zt as Xt,Zu as Zt,_a as Qt,_o as $t,_r as en,_t as tn,a as nn,as as rn,ba as an,bc as on,bn as sn,br as cn,bt as ln,c as un,cd as dn,co as fn,cr as pn,dr as mn,ds as hn,el as gn,eo as _n,et as vn,ga as yn,gn as bn,gr as xn,hr as Sn,i as Cn,ii as wn,io as Tn,jn as En,jt as Dn,ka as On,kc as kn,kn as An,kt as jn,l as Mn,ld as Nn,lr as Pn,ls as Fn,mo as In,mr as Ln,nt as Rn,o as zn,od as Bn,on as Vn,oo as Hn,pr as Un,q as Wn,qs as Gn,qt as Kn,r as qn,rc as Jn,ro as Yn,rt as Xn,so as Zn,tc as Qn,td as $n,tl as er,tt as tr,ul as nr,ur as rr,us as ir,xa as ar,xt as or,yr as sr,zi as cr,zn as lr,zt as ur}from"./src-CWZRb0ia.js";import{t as X}from"./i18n-DsGcRtAk.js";import{t as Z}from"./useTranslation-D3Is_4B6.js";import"./mount-DPfjZqVB.js";import{A as dr,D as fr,E as pr,M as mr,O as hr,ar as gr,cr as _r,dr as vr,er as yr,hr as br,j as xr,k as Sr,lr as Cr,mr as wr,nr as Tr,or as Er,p as Dr,pr as Or,rr as kr,sr as Ar,tr as jr,ur as Mr}from"./index-CgxpaFwe.js";import{A as Nr,C as Pr,D as Fr,E as Ir,M as Lr,N as Rr,O as zr,S as Br,_ as Vr,a as Hr,b as Ur,c as Wr,d as Gr,f as Kr,g as qr,h as Jr,i as Yr,j as Xr,k as Zr,l as Qr,m as $r,n as ei,o as ti,p as ni,r as ri,s as ii,t as ai,u as oi,v as si,w as ci,x as li,y as ui}from"./event-targets-CIffOoYs.js";import{r as di,t as fi}from"./assignment-candidates-CQGwwSSC.js";import{_ as pi,b as mi,i as hi,m as gi,o as _i,t as vi}from"./step-inspector-model-B6Fs3NZo.js";import"./useEventInvalidation-DPfjZqVB.js";import{t as yi}from"./use-stationary-objects-D9diuPzc.js";import{n as bi,t as xi}from"./format-Cz7vHmZ6.js";import{a as Si,i as Ci,n as wi,o as Ti,r as Ei,s as Di,t as Oi}from"./linked-devices-model-DYRAb775.js";import{t as ki}from"./authed-media-DpHGiSZS.js";e();function Ai(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 ji(e){if(typeof e!=`object`||!e)return null;let t=e.switches;if(!Array.isArray(t))return null;let n=t.map(Ai).filter(e=>e!==null);return n.length===0?null:n}var Mi=[[/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 Ni(e){for(let[t,n]of Mi)if(t.test(e))return n;return`generic`}function Pi(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(X.t(`helpers.cameraSwitchRows.off`,{list:r(t)})),n.length>0&&i.push(X.t(`helpers.cameraSwitchRows.unknown`,{list:r(n)})),{offIds:t,unknownIds:n,summary:i.length===0?X.t(`helpers.cameraSwitchRows.allOn`):i.join(` · `)}}var Fi={stream:me,detection:Re,privacy:ge,microphone:te,speaker:k,listening:Ie,archive:Pe,recording:Le,notifications:T,generic:F};function Ii({deviceId:e}){let{t}=Z(),n=c(),o=Number.isFinite(e),[s,l]=r(null),[u,f]=r(!1),p=xt({deviceId:e},{enabled:o});qn([`pipelineOrchestrator`,`getCameraSwitches`],[`capability.binding-changed`]);let m=ji(p.data),h=er({onError:(t,r)=>{console.error(`[CameraFunctionSwitches] switch write failed — reverting`,{tags:{deviceId:e},meta:{switchId:r.switchId,error:t instanceof Error?t.message:String(t)}}),n.invalidateQueries({queryKey:[[`pipelineOrchestrator`,`getCameraSwitches`]]}),l({id:r.switchId,message:t instanceof Error?t.message:String(t)})},onSuccess:()=>{l(null),n.invalidateQueries({queryKey:[[`pipelineOrchestrator`]]}),n.invalidateQueries({queryKey:[[`deviceManager`]]}),n.invalidateQueries({queryKey:[[`recording`]]})}}),g=i(t=>{!t.available||t.on===null||h.mutate({deviceId:e,switchId:t.id,enabled:!t.on})},[e,h]);if(m===null)return null;let _=Pi(m),v=e=>s?.id===e.id?s.message:null;return a(Zt,{open:u,onOpenChange:f,children:[a(Ke,{"aria-label":t(`device.cameraFunctionSwitches.cameraFunctions`,`Camera functions`),title:_.summary,className:`inline-flex items-center gap-1 rounded-lg border px-2 py-1.5 text-[11px] font-medium transition-colors ${s===null?_.offIds.length>0?`border-warning/40 text-warning hover:bg-warning/10`:`border-border text-foreground-subtle hover:text-foreground hover:bg-surface-hover`:`border-danger/50 text-danger bg-danger/5`}`,children:[d(F,{className:`h-3.5 w-3.5`}),d(`span`,{className:`hidden lg:inline`,children:t(`device.cameraFunctionSwitches.functions`,`Functions`)}),_.offIds.length>0&&d(`span`,{className:`rounded bg-warning/20 px-1 text-[9px] font-semibold uppercase tracking-wide`,children:t(`device.cameraFunctionSwitches.offCount`,{count:_.offIds.length})})]}),a(Nt,{align:`end`,className:`min-w-[240px] max-h-[60vh] overflow-y-auto p-1`,children:[d(`div`,{className:`px-2 py-1 text-[10px] uppercase tracking-wider text-foreground-subtle`,children:t(`device.cameraFunctionSwitches.cameraFunctions`,`Camera functions`)}),d(`ul`,{className:`space-y-0.5`,children:m.map(e=>d(`li`,{children:d(Li,{row:e,failure:v(e),onToggle:()=>g(e)})},e.id))})]})]})}function Li({row:e,failure:t,onToggle:n}){let{t:r}=Z(),i=Fi[Ni(e.label)],o=e.on===null,s=e.on===!1,c=t===null?o?e.unavailableReason??`The source that owns this did not answer.`:e.costWhenOff:`Write failed: ${t}`,l=t===null?o?e.unavailableReason??`unknown`:null:`write failed`;return a(`button`,{type:`button`,role:`switch`,"aria-label":e.label,"aria-checked":e.on===!0,disabled:!e.available,onClick:n,title:c,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:[d(i,{className:`h-3.5 w-3.5 shrink-0 ${t===null?o?`text-foreground-subtle/50`:s?`text-warning`:`text-success`:`text-danger`}`}),a(`span`,{className:`flex-1 min-w-0 truncate`,children:[e.label,l!==null&&a(`span`,{className:`ml-1 text-[10px] text-foreground-subtle`,children:[`· `,l]})]}),d(`span`,{className:`shrink-0 rounded px-1 py-0.5 text-[9px] font-semibold uppercase tracking-wide ${o?`bg-surface-hover text-foreground-subtle/60`:s?`bg-warning/20 text-warning`:`bg-success/20 text-success`}`,children:o?`—`:r(s?`common.off`:`common.on`)})]})}function Ri({deviceId:e}){let t=Ft(R().trpcClient,e);return t===null?null:a(`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:[d(f,{className:`h-3.5 w-3.5`}),d(`span`,{className:`hidden sm:inline`,children:t.label})]})}function zi({parentDeviceId:e}){let{t}=Z(),n=Or(),r=R(),{data:i,isLoading:o,isError:s}=kr(e),{data:c}=Yn({deviceId:e},{enabled:Number.isFinite(e)});if(o)return d(`div`,{className:`rounded-lg border border-border bg-surface p-3`,children:d(`p`,{className:`text-[10px] text-foreground-subtle`,children:t(`common.loading`,{defaultValue:`Loading…`})})});if(s)return d(`div`,{className:`rounded-lg border border-border bg-surface p-3`,children:d(`p`,{className:`text-[10px] text-warning`,children:t(`integrations.childrenLoadError`,{defaultValue:`Failed to load children`})})});let l=(i??[]).filter(e=>e.display?.hidden!==!0);if(l.length===0)return null;let u=Tt(c?.stableId??``,l,c?.childLayout),f=u.ungrouped,p=e=>n(`/devices/${String(e)}`),m=c?.name??``,h=(e,t)=>d(Dn,{trpc:r.trpcClient,device:{...t,name:ur(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?a(`div`,{className:`rounded-lg border border-border bg-surface p-3`,children:[d(`div`,{className:`text-[10px] font-semibold uppercase tracking-wide text-foreground-subtle mb-1.5`,children:v}),d(`div`,{className:`space-y-1`,children:f.map(e=>h(e.id,e))})]}):null,b=u.disabledSection===void 0?null:d(St,{title:t(`device.disabledSection`,{defaultValue:`Disabled`}),count:u.disabledSection.children.length,defaultOpen:!1,children:d(`div`,{className:`opacity-60 space-y-1`,children:u.disabledSection.children.map(e=>h(e.id,e))})},u.disabledSection.title);if(u.sections.length===0)return b===null?y:a(`div`,{className:`space-y-2`,children:[y,b]});let x=_&&!g;return a(`div`,{className:`space-y-2`,children:[x?y:null,u.sections.map(e=>d(St,{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 Bi({deviceId:e}){let t=R(),{data:n,isLoading:r}=Tr(e),{data:i,isLoading:a}=kr(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?d(`div`,{className:`h-full min-h-32 w-full animate-pulse rounded-lg bg-surface`,"aria-hidden":`true`}):d(`div`,{className:`flex h-full w-full flex-col`,children:d(Ut,{trpc:t.trpcClient,children:s,linkDeviceId:c,primaryChildEntityId:l})})}e();function Vi({dev:e,busy:t,setBusy:n}){let{t:i}=Z(),o=e?.motionTrigger,s=b(e?.state.motionTrigger),[c,l]=r(!1);if(!o)return null;let u=s?.enabled===!0,f=s!==void 0,p=async()=>{if(t||!f)return;let e=!u;n(!0),l(!0);try{await o.setMotionTrigger({enabled:e})}finally{n(!1),l(!1)}},m=c?u?`Disabling…`:`Enabling…`:f?u?`On motion: on`:`On motion: off`:`On motion: …`;return a(`button`,{type:`button`,onClick:()=>{p()},disabled:t||!f,title:f?u?i(`hero.motionTriggerToggle.disableTriggerOnMotion`,`Disable trigger on motion`):i(`hero.motionTriggerToggle.enableTriggerOnMotion`,`Enable trigger on motion`):i(`hero.motionTriggerToggle.awaitingState`,`Awaiting state…`),"aria-pressed":u,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 ${u?`border-primary/50 bg-primary/15 text-primary`:`border-border bg-surface text-foreground-subtle hover:text-foreground`}`,children:[d(fe,{className:`h-3 w-3`}),d(`span`,{children:m})]})}e();function Q({deviceId:e,deviceType:t,features:n}){let i=R(),o=st(t)?.HeroCard??gt,s=C(i.trpcClient,e),c=b(s?.state.deviceStatus),[l,u]=r(!1),f=c!==void 0&&c.online===!1,p=f?c.lastChangedAt:null;return a(`div`,{className:`flex h-full w-full flex-col items-stretch gap-3 p-3 sm:p-4`,children:[f?d(`div`,{className:`flex justify-center`,children:d(zt,{lastChangedAt:p})}):null,d(o,{trpc:i.trpcClient,deviceId:e,features:n}),d(`div`,{className:`flex justify-center`,children:d(Vi,{dev:s,busy:l,setBusy:u})})]})}function Hi({deviceId:e,features:t}){return d(`div`,{className:`flex h-full w-full flex-col items-stretch gap-3 p-3 sm:p-4`,children:d(Kn,{trpc:R().trpcClient,deviceId:e,features:t})})}function Ui({deviceId:e,features:t}){return d(`div`,{className:`flex h-full w-full flex-col items-stretch p-3 sm:p-4`,children:d(gt,{trpc:R().trpcClient,deviceId:e,features:t})})}function Wi(e){if(!e)return null;let t=e.channel;return typeof t!=`number`||!Number.isInteger(t)||t<0?null:t}function Gi(e){if(!e)return null;let t=Wi(e.data);return t===null?e.eventType:X.t(`helpers.eventEmitterFormat.buttonHeadline`,{channel:String(t),eventType:e.eventType})}var Ki=1e3,qi=60*Ki,Ji=60*qi,Yi=24*Ji;function Xi(e,t){if(e==null||e<=0)return`—`;let n=t-e;return n<Ki?X.t(`helpers.relativeTime.justNow`):n<qi?X.t(`helpers.relativeTime.secondsAgo`,{count:Math.floor(n/Ki)}):n<Ji?X.t(`helpers.relativeTime.minutesAgo`,{count:Math.floor(n/qi)}):n<Yi?X.t(`helpers.relativeTime.hoursAgo`,{count:Math.floor(n/Ji)}):X.t(`helpers.relativeTime.daysAgo`,{count:Math.floor(n/Yi)})}e();var Zi=1500,Qi=15e3,$i=1e3;function ea({deviceId:e}){let{t:n}=Z(),i=C(R().trpcClient,e)?.state.eventEmitter,o=b(i);t(()=>{if(!i)return;i.refresh();let e=setInterval(()=>{i.refresh()},Qi);return()=>{clearInterval(e)}},[i]);let s=o?.lastEvent??null,c=s?.seq??null,u=l(null),[f,m]=r(!1);t(()=>{if(c===null)return;let e=u.current;if(u.current=c,e===null||e===c)return;m(!0);let t=setTimeout(()=>{m(!1)},Zi);return()=>{clearTimeout(t)}},[c]);let[h,g]=r(()=>Date.now());t(()=>{let e=setInterval(()=>{g(Date.now())},$i);return()=>{clearInterval(e)}},[]);let _=Gi(s),y=o?.eventTypes??[],x=o?.eventCountSinceStart??0,S=o!==void 0,w=Wi(s?.data);return a(`div`,{className:`flex h-full w-full flex-col items-center justify-center gap-3 p-4`,children:[d(`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:_??n(`hero.eventEmitterHero.noPressRecorded`,`No press recorded`),children:d(f?v:p,{className:`h-10 w-10`})}),a(`div`,{className:`text-center`,children:[w!==null&&d(`div`,{className:`text-xs font-semibold uppercase tracking-wide text-primary`,children:n(`hero.eventEmitterHero.button`,`Button {{value1}}`,{value1:String(w)})}),d(`div`,{"data-testid":`event-emitter-headline`,className:`text-sm font-semibold ${_?`text-foreground`:`text-foreground-subtle`}`,children:_??(S?n(`hero.eventEmitterHero.noPressRecorded`,`No press recorded`):n(`hero.eventEmitterHero.awaitingState`,`Awaiting state…`))}),d(`div`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:s?Xi(s.timestamp,h):n(`hero.eventEmitterHero.waitingForTheFirstEvent`,`Waiting for the first event`)})]}),y.length>0&&d(`div`,{className:`flex max-w-full flex-wrap justify-center gap-1`,children:y.map(e=>d(`span`,{"data-testid":`event-emitter-chip`,className:`rounded-full border px-2 py-0.5 text-[10px] font-medium ${e===s?.eventType?`border-primary bg-primary/15 text-primary`:`border-border bg-surface text-foreground-subtle`}`,children:e},e))}),d(`div`,{className:`text-[10px] text-foreground-subtle`,children:n(`hero.eventEmitterHero.sinceStart`,{count:x})})]})}function ta({deviceName:e,deviceType:t,provider:n,isOnline:r,features:i}){let{t:o}=Z();return a(`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:[d(_r,{type:n,size:`lg`}),a(`div`,{children:[d(`div`,{className:`text-sm font-semibold text-foreground`,children:e}),d(`div`,{className:`text-[10px] text-foreground-subtle uppercase tracking-wider mt-0.5`,children:t})]}),a(`div`,{className:`flex items-center gap-2 flex-wrap justify-center`,children:[d(Xn,{status:r?`online`:`offline`}),i.length>0&&d(Cr,{capabilities:i})]}),d(`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.`)})]})}e();function na({deviceId:e}){let{t}=Z(),r=c(),i=On({deviceId:e},{refetchInterval:1e4,retry:!1}),o=qe({onSuccess:()=>{r.invalidateQueries({queryKey:[[`deviceDiscovery`,`listDiscovered`]]}),r.invalidateQueries({queryKey:[[`deviceDiscovery`,`getStatus`]]})}}),s=n(()=>ra(i.data??[]),[i.data]);return a(`div`,{className:`flex h-full w-full flex-col gap-3 p-3 sm:p-4`,children:[a(`div`,{className:`flex flex-wrap items-stretch gap-2 sm:gap-3`,children:[d(ia,{label:t(`hero.hubHero.discovered`,`Discovered`),value:s.total,icon:d(he,{className:`h-3.5 w-3.5`})}),d(ia,{label:t(`hero.hubHero.adopted`,`Adopted`),value:s.adopted,accent:`success`}),d(ia,{label:t(`hero.hubHero.available`,`Available`),value:s.available,accent:s.available>0?`primary`:void 0}),a(`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?d(L,{className:`h-3.5 w-3.5 animate-spin`}):d(ie,{className:`h-3.5 w-3.5`}),d(`span`,{className:`hidden sm:inline`,children:t(`hero.hubHero.discover`,`Discover`)})]})]}),a(`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:[d(aa,{icon:d(oe,{className:`h-3 w-3 text-emerald-500`}),label:t(`hero.hubHero.online`,`{{online}} online`,{online:s.online})}),d(aa,{icon:d(w,{className:`h-3 w-3 text-amber-500`}),label:t(`hero.hubHero.sleeping`,`{{sleeping}} sleeping`,{sleeping:s.sleeping})}),d(aa,{icon:d(N,{className:`h-3 w-3 text-destructive`}),label:t(`hero.hubHero.offline`,`{{offline}} offline`,{offline:s.offline})}),s.unknown>0?d(aa,{icon:d(se,{className:`h-3 w-3 text-foreground-subtle`}),label:t(`hero.hubHero.unknown`,`{{unknown}} unknown`,{unknown:s.unknown})}):null]})]})}function ra(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 ia({label:e,value:t,icon:n,accent:r}){return a(`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 ${r===`success`?`bg-emerald-500/10 border-emerald-500/30 text-emerald-500`:r===`primary`?`bg-primary/10 border-primary/30 text-primary`:`bg-surface-hover border-border text-foreground`}`,children:[a(`div`,{className:`flex items-center gap-1.5 text-[10px] uppercase tracking-wider opacity-70 truncate`,children:[n,d(`span`,{className:`truncate`,children:e})]}),d(`div`,{className:`text-xl sm:text-2xl font-semibold tabular-nums leading-none`,children:t})]})}function aa({icon:e,label:t}){return a(`span`,{className:`inline-flex items-center gap-1`,children:[e,d(`span`,{children:t})]})}var oa={[G.Switch]:Q,[G.Siren]:Q,[G.Light]:Q,[G.Sensor]:Q,[G.Button]:Q,[G.Hub]:na,[G.Cover]:Hi,[G.Valve]:Q,[G.Humidifier]:Q,[G.WaterHeater]:Q,[G.Container]:Bi,[G.Lock]:Q,[G.Fan]:Q,[G.Thermostat]:Q,[G.Climate]:Q,[G.MediaPlayer]:Q,[G.Control]:Q,[G.AlarmPanel]:Q,[G.EventEmitter]:ea,[G.Notifier]:Ui,[G.Script]:Q,[G.Automation]:Q,[G.Presence]:Q,[G.Update]:Q,[G.Vacuum]:Q,[G.LawnMower]:Q,[G.Weather]:Q,[G.Image]:Q,[G.PetFeeder]:Q,[G.Dishwasher]:Q};function sa(e){return oa[e]??ta}function ca({deviceId:e}){let t=ce(R().trpcClient,e,e=>e.runningState);return d(Ye,{running:t===void 0||t.running===null?null:t.running,since:t?.since??null,phase:t?.phase??null,className:`px-3 pt-2 sm:px-4`})}function la(e){let t=sa(e.deviceType);return a(s,{children:[d(ca,{deviceId:e.deviceId}),d(t,{...e})]})}function ua({deviceId:e,widgets:t}){return t.length===0?null:d(`div`,{className:`flex flex-col gap-3 px-3 pb-3 sm:px-4 sm:pb-4`,"data-testid":`device-hero-widgets`,children:t.map(t=>{let n=d(pn,{widgetId:t.widgetId,deviceId:t.deviceId});return d(`div`,{children:t.deviceId===e?n:d(it,{deviceId:t.deviceId,children:n})},t.widgetId)})})}function da(e){return e.sections.filter(e=>e.location===`hero`).flatMap(t=>t.fields.flatMap(n=>{if(typeof n!=`object`||!n)return[];let r=Reflect.get(n,`type`),i=Reflect.get(n,`widgetId`);return r!==`widget`||typeof i!=`string`||i.length===0?[]:[{widgetId:i,deviceId:e.deviceId,order:t.order??0}]}))}function fa(e){let t=da(e),n=new Set(t.map(e=>e.widgetId)),r=e.child===void 0?[]:da(e.child),i=[...t,...r.filter(e=>!n.has(e.widgetId))],a=new Set;return i.filter(e=>a.has(e.widgetId)?!1:(a.add(e.widgetId),!0)).sort((e,t)=>e.order-t.order)}function pa(e){return zn(R().trpcClient,e)}e();function ma(e){let[n,a]=r(`idle`),[o,s]=r(null),c=l(null),u=l(null),d=l(null),f=l(!0),p=ir(),m=Fn(),h=hn(),g=i(()=>{if(c.current){try{c.current.close()}catch{}c.current=null}if(u.current){for(let e of u.current.getTracks())try{e.stop()}catch{}u.current=null}d.current=null},[]),_=i(async()=>{if(n===`idle`)return;a(`stopping`);let t=d.current;if(t&&e!==null)try{await Promise.race([h.mutateAsync({deviceId:e,sessionId:t}),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&&(a(`idle`),s(null))},[n,e,h,g]),v=i(async()=>{if(e===null||n!==`idle`&&n!==`error`)return;s(null);let t=null,r=null,i=null;try{a(`requesting-mic`),t=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}),u.current=t,a(`starting`);let n=await p.mutateAsync({deviceId:e});i=n.sessionId,d.current=i,a(`connecting`),r=new RTCPeerConnection,c.current=r,r.oniceconnectionstatechange=()=>{if(!f.current)return;let e=r.iceConnectionState;e===`connected`||e===`completed`?a(`talking`):(e===`failed`||e===`closed`||e===`disconnected`)&&f.current&&(s(e===`failed`?`WebRTC connection failed`:null),_())};for(let e of t.getAudioTracks())r.addTrack(e,t);await r.setRemoteDescription({type:`offer`,sdp:n.sdpOffer});let o=await r.createAnswer();await r.setLocalDescription(o);let l=r.localDescription?.sdp??o.sdp??``;await m.mutateAsync({deviceId:e,sessionId:i,sdpAnswer:l})}catch(n){let o=n instanceof Error?n.message:String(n);if(console.warn(`[intercom] start failed`,n),r)try{r.close()}catch{}if(t)for(let e of t.getTracks())try{e.stop()}catch{}if(c.current=null,u.current=null,i!==null)try{await h.mutateAsync({deviceId:e,sessionId:i})}catch{}d.current=null,f.current&&(s(o),a(`error`))}},[e,n,p,m,h,_]);return t(()=>(f.current=!0,()=>{f.current=!1;let t=d.current;if(t!==null&&e!==null&&h.mutate({deviceId:e,sessionId:t}),c.current){try{c.current.close()}catch{}c.current=null}if(u.current){for(let e of u.current.getTracks())try{e.stop()}catch{}u.current=null}d.current=null}),[e]),{state:n,error:o,start:v,stop:_,isTalking:n===`talking`}}e();var ha=0;function $(){return++ha}function ga(e){switch(e.type){case`system`:return`system`;case`device`:return`#${e.deviceId}`;case`provider`:return e.providerId;case`addon`:return e.addonId}}function _a(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 ya(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 ba({scope:e,greeting:n,className:o}){let{t:s}=Z(),c=R(),[f,p]=r(()=>{let t=[];return n&&t.push({id:$(),kind:`info`,text:n}),t.push({id:$(),kind:`info`,text:`scope: ${ga(e)} — type help or context for available commands`}),t}),[m,h]=r(``),[g,_]=r([]),[v,y]=r(-1),b=l(null),x=l(null);t(()=>{let e=x.current;e&&(e.scrollTop=e.scrollHeight)},[f]);let S=i(()=>{b.current?.focus()},[]),C=u({mutationFn:t=>c.trpcClient.repl.execute.mutate({code:t,scope:e}),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(t){let n=t.trim();if(n){if(n===`clear`){p([{id:$(),kind:`info`,text:`scope: ${ga(e)}`}]),h(``);return}if(n===`help`){p(t=>[...t,{id:$(),kind:`input`,text:`> ${n}`},..._a(e).map(e=>({id:$(),kind:`info`,text:e}))]),h(``);return}if(n===`context`){p(t=>[...t,{id:$(),kind:`input`,text:`> ${n}`},...ya(e).map(e=>({id:$(),kind:`info`,text:e}))]),h(``);return}if(n===`examples`){p(t=>[...t,{id:$(),kind:`input`,text:`> ${n}`},...va(e).map(e=>({id:$(),kind:`info`,text:e}))]),h(``);return}_(e=>[...e,n]),y(-1),p(e=>[...e,{id:$(),kind:`input`,text:`> ${n}`}]),h(``),C.mutate(n)}}function T(t){if(t.key===`Enter`){t.preventDefault(),w(m);return}if(t.key===`ArrowUp`){if(t.preventDefault(),g.length===0)return;let e=v===-1?g.length-1:Math.max(0,v-1);y(e),h(g[e]??``);return}if(t.key===`ArrowDown`){if(t.preventDefault(),v===-1)return;let e=v+1;e>=g.length?(y(-1),h(``)):(y(e),h(g[e]??``));return}t.ctrlKey&&t.key===`l`&&(t.preventDefault(),p([{id:$(),kind:`info`,text:`scope: ${ga(e)}`}]))}let E={input:`text-zinc-300`,result:`text-emerald-300`,error:`text-red-300`,info:`text-zinc-400`};return a(`div`,{className:`flex flex-col bg-[#0c0a09] rounded-lg border border-border overflow-hidden font-mono text-xs ${o??``}`,onClick:S,children:[a(`div`,{ref:x,className:`flex-1 overflow-y-auto p-3 space-y-1 min-h-[120px]`,children:[f.map(e=>d(`pre`,{className:`whitespace-pre-wrap break-words leading-relaxed ${E[e.kind]}`,children:e.text},e.id)),C.isPending&&d(`span`,{className:`text-zinc-500 animate-pulse`,children:s(`shared.replTerminal.thinking`,`…thinking`)})]}),a(`div`,{className:`flex items-center gap-2 border-t border-zinc-800 px-3 py-2 bg-[#0c0a09]`,children:[d(`span`,{className:`text-emerald-400 flex-shrink-0 select-none font-bold`,children:s(`shared.replTerminal.text`,`>`)}),d(`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 xa(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}}}e();function Sa({deviceId:e,intercomAvailable:t=!1}){let r=R(),i=typeof window<`u`?ne():``,a=Number.isFinite(e),o=pa(a?e:null),c=yi(a?[e]:[]),l=n(()=>{if(!a)return;let e=[];for(let t of c.rows){let n=nn(t);n!==null&&e.push(n)}return e},[a,c.rows]),{streams:u,pipelineMetrics:f,createSession:p,sendAnswer:m,handleOffer:h,getIceServers:g,addIceCandidate:v,getIceCandidates:y,closeSession:b,getSessionState:x,applyDownlinkProbe:S}=bn(r.trpcClient,a?e:null),C=_(a?e:null,{width:Da}),w=ma(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=le(),k=cn(),A=typeof window<`u`?window.localStorage.getItem(`camstack_admin_token`):null,j=xa(k.request,A),ee=O.length>0?d(s,{children:O.map(e=>d(`div`,{className:`absolute inset-0`,children:e.node},e.id))}):null;return d(Wn,{serverUrl:i,createSession:p,sendAnswer:m,handleOffer:h,getIceServers:g,addIceCandidate:v,getIceCandidates:y,closeSession:b,getSessionState:x,applyDownlinkProbe:S,...j===null?{}:{...j,onExitPlayback:()=>k.clear()},streams:u,pipelineMetrics:f,phase:o.phase,detections:o,...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:ee,chromeless:!0,className:`h-full`})}function Ca({deviceId:e,containerDeviceId:t}){let{t:n}=Z();return Number.isFinite(e)?d(`div`,{className:`flex flex-col h-full`,children:d(Mt,{...t===void 0?{deviceId:e}:{containerDeviceId:t},limit:50,maxHeight:`max-h-full`,showScope:!1,showFilters:!1})}):d(`div`,{className:`flex items-center justify-center h-full text-[11px] text-foreground-subtle italic`,children:n(`device.panelContent.notLoaded`,{id:e})})}function wa({deviceId:e}){let{t}=Z();if(!Number.isFinite(e))return d(`div`,{className:`flex items-center justify-center h-full text-[11px] text-foreground-subtle italic`,children:t(`device.panelContent.notLoaded`,{id:e})});let n=[`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 d(ba,{scope:{type:`device`,deviceId:e},greeting:n,className:`h-full border-0 rounded-none`})}function Ta({deviceId:e}){let{t}=Z();return Number.isFinite(e)?d(`div`,{className:`flex flex-col h-full overflow-y-auto`,children:d(Xt,{deviceId:e,limit:50,maxHeight:`max-h-full`})}):d(`div`,{className:`flex items-center justify-center h-full text-[11px] text-foreground-subtle italic`,children:t(`device.panelContent.notLoaded`,{id:e})})}function Ea({deviceId:e}){let{t}=Z();return Number.isFinite(e)?d(`div`,{className:`flex flex-col h-full overflow-y-auto`,children:d(Gt,{deviceId:e,limit:50,maxHeight:`max-h-full`})}):d(`div`,{className:`flex items-center justify-center h-full text-[11px] text-foreground-subtle italic`,children:t(`device.panelContent.notLoaded`,{id:e})})}var Da=960;function Oa(e,t){let{hidden:n,...r}=e??{},i=t?{...r,hidden:!0}:r;return Object.keys(i).length===0?null:i}function ka(e){return typeof e.linkDeviceId==`number`}var Aa=new Set(Object.values(U));function ja(e){return Aa.has(e)}var Ma={[G.Switch]:[U.Siren,U.Floodlight,U.Spotlight,U.PirSensor,U.Chime,U.Autotrack,U.Nightvision,U.PrivacyMask,U.BinaryHelper],[G.Light]:[U.Floodlight,U.Spotlight,U.Nightvision],[G.Siren]:[U.Siren],[G.Button]:[U.Doorbell],[G.Sensor]:[U.MotionSensor,U.ContactSensor,U.LeakSensor,U.SmokeSensor,U.COSensor,U.GasSensor,U.TamperSensor,U.VibrationSensor,U.ConnectivitySensor,U.SoundSensor,U.BinarySensor,U.TemperatureSensor,U.HumiditySensor,U.AmbientLightSensor,U.PressureSensor,U.WindSensor,U.RainSensor,U.UvSensor,U.SolarRadiationSensor,U.SoilMoistureSensor,U.PowerSensor,U.EnergySensor,U.VoltageSensor,U.CurrentSensor,U.AirQualitySensor,U.BatterySensor,U.NumericSensor,U.EnumSensor,U.DateTimeSensor,U.GenericSensor],[G.Control]:[U.NumericControl,U.SelectControl,U.TextControl,U.DateTimeControl],[G.Notifier]:[U.MobilePushNotifier,U.MessagingNotifier,U.EmailNotifier,U.GenericNotifier]};function Na(e){for(let t of Object.values(G))if(t===e)return!0;return!1}function Pa(e){return Na(e)?Ma[e]??[]:[]}function Fa(e,t){let n=Pa(t);return e==null||e===``||n.includes(e)?n:[...n,e]}e();function Ia({device:e}){let{t}=Z(),n=ue(),i=c(),[o,s]=r(null),l=()=>s(null),u={onSuccess:()=>{l(),i.invalidateQueries({queryKey:[[`deviceManager`]]})},onError:e=>s(e.message)},f=Xe(),p=tt(),h=e.display?.hidden===!0;return a(`section`,{"aria-label":t(`customize.identity.title`),className:`${E} ${m}`,children:[a(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4`,children:[d(Er,{deviceId:e.id,initialName:e.name,label:t(`customize.identity.name`),layout:`stacked`,onError:s,onSaved:l,onCancel:l}),d(gr,{deviceId:e.id,initialLocation:e.location,label:t(`customize.identity.room`),layout:`stacked`,onError:s,onSaved:l,onCancel:l}),d(Ar,{label:t(`customize.identity.hidden`),layout:`stacked`,value:d(Ht,{"aria-label":t(`deviceDisplay.hideFromLists`),checked:h,disabled:p.isPending,onChange:t=>p.mutate({deviceId:e.id,display:Oa(e.display,t.target.checked)},u)})}),d(Ar,{label:t(`customize.identity.role`),layout:`stacked`,value:ka(e)?d(`span`,{children:La(e.role,t(`customize.identity.noRole`),n)}):d(Bt,{"aria-label":t(`customize.identity.role`),value:e.role??``,disabled:f.isPending,options:[{value:``,label:t(`customize.identity.noRole`)},...Fa(e.role,e.type).map(e=>({value:e,label:La(e,t(`customize.identity.noRole`),n)}))],onChange:t=>f.mutate({deviceId:e.id,role:t.target.value===``?null:t.target.value},u)})})]}),o!==null&&d(`p`,{role:`alert`,className:`mt-2 text-xs text-danger break-words`,children:o})]})}function La(e,t,n){return e==null||e===``?t:ja(e)?Bn(e,n).label:e}var Ra={binary:`binary`,switch:`switch`};function za(e){return Object.hasOwn(ye,e)}function Ba(e,t){if(!za(e))return null;let n=ye[e].targets.find(e=>e.id===t);return n===void 0||n.cardinality!==`event`?null:n}function Va(e,t){let n=Ba(e,t);if(n===null)return[];let r=[];for(let e of n.sources){let t=Ra[e.kind];t!==void 0&&r.push(t)}return r}function Ha(e,t){return t.some(t=>e.includes(t))}function Ua(e,t){let n=Ne[t]??null;if(n===null)return null;let r=e.caps.find(e=>e.cap===t);return r===void 0?null:r.fields.some(e=>e.path===n)?n:null}function Wa(e,t,n,r){let i=Ba(t,n);if(i===null)return null;let a=Gr(e,null).filter(e=>e.kind===`boolean`);for(let t of a){if(oi(i.sources,t)===null)continue;let n=Ua(e,t.cap);if(!(r===`pulse`&&n===null))return{cap:t.cap,fieldPath:t.path,changedAtField:n}}return null}function Ga(e,t,n,r){return e.filter(e=>e.id!==t).filter(e=>!Ha(n.get(e.id)??[],r)).map(e=>e.id)}function Ka(e,t){return e.filter(e=>e.id!==t).map(e=>({id:e.id,name:e.name,type:e.type,...e.location===null?{}:{location:e.location}}))}function qa(e){let t=Ce({draft:{kind:`pulse`,cap:e.cap,targetId:e.targetId,enabled:e.enabled,debounceMs:e.debounceMs,...e.edges===void 0?{}:{edges:[...e.edges]},sources:e.sources.map(e=>({addonId:e.addonId,stableId:e.stableId,cap:e.cap,fieldPath:e.fieldPath}))},device:e.device,changedAtFields:e.sources.map(e=>e.changedAtField)});return t.ok?t.value:null}function Ja(e){let t=ve({draft:{kind:`span`,cap:e.cap,targetId:e.targetId,timeoutMs:e.timeoutMs,...e.cooldownMs===void 0?{}:{cooldownMs:e.cooldownMs},sources:e.sources.map(e=>({addonId:e.addonId,stableId:e.stableId,cap:e.cap,fieldPath:e.fieldPath,mode:e.mode}))},device:e.device});return t.ok?t.value:null}function Ya(e,t){return{deviceId:e,config:t.config}}function Xa(e,t){return{deviceId:e,patch:{motionCooldownMs:t}}}async function Za(e,t,n,r){await n(Ya(e,t)),await r(Xa(e,t.timeoutMs))}e();function Qa(e){return e===`pending`?`pending`:e===`error`?`failed`:`answered`}function $a(e){let{t}=Z(),n=e.mode===`change`?t(`customize.scalar.changeTitle`,{title:e.title}):t(`customize.scalar.addTitle`,{title:e.title});return d(Pn,{open:e.open,onOpenChange:t=>!t&&e.onClose(),children:a(mn,{placement:`sheet-on-mobile`,scroll:`body`,"aria-label":n,children:[d(Ln,{children:d(Sn,{children:n})}),e.open?d(eo,{...e}):null]})})}function eo(e){let{t,i18n:i}=Z(),o=Zn({projection:`slim`}),c=o.status===`success`?ui(o.data):[],[l,u]=r(e.sources),[f,p]=r(null),[m,h]=r(e.edge),[g,_]=r(e.debounceMs/1e3),v=Hn({deviceId:f?.id??0}),y=yt({deviceId:f?.id??0}),b=v.status===`success`?v.data:{caps:[]},x=n(()=>Va(e.cap,e.targetId),[e.cap,e.targetId]),S=Xr(x,e.open),C=n(()=>S.kind===`known`?Ga(c,e.host.id,S.value,x):[],[S,c,e.host.id,x]),w=f===null?null:Wa(b,e.cap,e.targetId,`pulse`),T=no(f,w);to(T,u,p);let E=T===null?l:ro(l,T),D=E.length===0?null:qa({cap:e.cap,targetId:e.targetId,device:e.target,enabled:e.enabled,debounceMs:Math.round(g*1e3),edges:[m],sources:E}),O=typeof e.host.location==`string`&&e.host.location.length>0?e.host.location:null,k=co(y.data,E[0]??null),A=De(je,k,Math.round(g*1e3));return a(s,{children:[a(rr,{className:`flex flex-col gap-3 p-2 sm:p-4`,children:[d(`p`,{className:`text-[11px] text-foreground-muted`,children:t(`customize.event.pulseBody`)}),d(io,{edges:e.edges,edge:m,onChange:h}),d(ao,{fleet:c,rows:l,onChange:u}),d(oo,{devices:o,fleet:c,hostId:e.host.id,groupByLocation:O!==null,lockedIds:C,onPick:p}),f!==null&&w!==null&&d(`p`,{className:`text-xs text-foreground`,children:Fr(w.cap,w.fieldPath,i.language)}),f!==null&&w===null&&v.status===`success`&&d(`p`,{className:`text-xs text-foreground-subtle`,children:t(`customize.scalar.fit.kind`)}),a(`label`,{className:`flex flex-col gap-1 text-[11px] text-foreground`,children:[t(`customize.event.debounce`),d(mt,{type:`number`,"aria-label":t(`customize.event.debounce`),value:Number.isFinite(g)?g:0,onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&t>=0&&_(t)}})]}),d(`p`,{role:`status`,className:`text-[11px] text-foreground-subtle`,children:t(so(k,A.lastPressedAt))})]}),a(Un,{className:`flex flex-wrap gap-2`,children:[d(J,{variant:`ghost`,onClick:e.onClose,children:t(`customize.scalar.cancel`)}),d(J,{"data-testid":`event-save`,disabled:!e.canSave||D===null,onClick:()=>{D!==null&&e.onSave(D)},children:t(`customize.scalar.save`)})]})]})}function to(e,n,r){let i=e===null?null:`${e.addonId}/${e.stableId}/${e.fieldPath}`;t(()=>{e===null||i===null||(n(t=>ro(t,e)),r(null))},[i,e,r,n])}function no(e,t){return e===null||t===null||t.changedAtField===null?null:{addonId:e.addonId,stableId:e.stableId,cap:t.cap,fieldPath:t.fieldPath,changedAtField:t.changedAtField}}function ro(e,t){return e.some(e=>e.addonId===t.addonId&&e.stableId===t.stableId)?e:[...e,t]}function io({edges:e,edge:t,onChange:n}){let{t:r}=Z();return e.length===0?null:a(`label`,{className:`flex flex-col gap-1 text-[11px] text-foreground`,children:[r(`customize.event.edge`),d(Bt,{"aria-label":r(`customize.event.edge`),value:t,options:e.map(e=>({value:e,label:r(`customize.event.edgeValue.${e}`)})),onChange:t=>{let r=e.find(e=>e===t.target.value);r!==void 0&&n(r)}})]})}function ao({fleet:e,rows:t,onChange:n}){let{t:r}=Z();return t.length===0?null:d(`ul`,{className:`flex flex-col gap-1`,children:t.map(i=>a(`li`,{className:`flex items-center gap-2 text-xs`,children:[d(`span`,{className:`text-foreground`,children:e.find(e=>e.addonId===i.addonId&&e.stableId===i.stableId)?.name??i.stableId}),d(J,{variant:`ghost`,size:`sm`,onClick:()=>n(t.filter(e=>e.addonId!==i.addonId||e.stableId!==i.stableId)),children:r(`customize.event.clear`)})]},`${i.addonId}/${i.stableId}`))})}function oo({devices:e,fleet:t,hostId:n,groupByLocation:r,lockedIds:i,onPick:a}){let{t:o}=Z();return e.status===`error`?d(q,{title:o(`customize.picker.devicesFailed`),message:e.error?.message??``}):d(_t,{devices:Ka(t,n),listState:Qa(e.status),value:[],selection:`single`,...r?{groupBy:`location`}:{},lockedIds:i,lockedNote:o(`customize.scalar.fit.kind`),onChange:e=>{let n=e[0],r=n===void 0?void 0:t.find(e=>e.id===n);r!==void 0&&a(r)},noun:`device`,showAll:!0,testId:`event-pulse-picker`})}function so(e,t){return e.kind===`unread`?`customize.event.previewWaiting`:e.active&&t===null?`customize.event.previewAlreadyOn`:t===null?`customize.event.previewQuiet`:`customize.event.previewCounted`}function co(e,t){if(e===void 0||t===null)return{kind:`unread`};let n=e[t.cap],r=n===void 0?void 0:si(n,t.fieldPath),i=Ne[t.cap]??t.changedAtField,a=n===void 0?void 0:si(n,i);return typeof r==`boolean`?{kind:`level`,active:r,changedAt:typeof a==`number`&&Number.isFinite(a)?a:null}:{kind:`unread`}}function lo(e,t,n){if(e===`pending`)return{kind:`pending`,seconds:null};if(e===`unknown`||e==null)return{kind:`unknown`,seconds:null};if(!e)return{kind:`quiet`,seconds:null};let r=uo(t,n);return r===null?{kind:`unknown`,seconds:null}:{kind:`active`,seconds:r}}function uo(e,t){if(e==null||!Number.isFinite(e)||e<xi)return null;let n=Math.floor((t-e)/1e3);return n<0?0:n}function fo(e,t){if(e===`pending`)return{kind:`pending`,lastPressedAt:null,pressCount:null};if(e===`unknown`)return{kind:`unknown`,lastPressedAt:null,pressCount:null};let n=typeof e==`number`&&Number.isFinite(e)&&e>=xi?e:null,r=typeof t==`number`&&Number.isFinite(t)&&t>=0?t:null;return n===null?{kind:`none`,lastPressedAt:null,pressCount:r}:{kind:`ring`,lastPressedAt:n,pressCount:r}}e();function po({device:e,handle:t,availability:n,cap:i,title:o,view:c}){let{t:l,i18n:u}=Z(),f=Ur(),[p,m]=r(!1),[h,g]=r(null),_=zr(t.state),v=li(_,i),y=ho(t,v),b=y.kind===`known`&&y.value!==null?Se({feature:y.value,device:t.target,cap:i,targetId:c.id,timestampPath:c.timestampPath,counterPath:c.counterPath}):null,x=b!==null,S=Nr(x),C=b?.draft.sources[0]??null,w=C===null||S.kind!==`known`?null:S.value.find(e=>ke({addonId:e.addonId,stableId:e.stableId})===ke(C))??null,T=go(x,S.kind,w!==null),E=W({cap:i,targetId:c.id,device:t.target,timestampPath:c.timestampPath,counterPath:c.counterPath,apply:c.apply,stored:y,sourcePresence:T,sourceUnknownReason:S.kind===`unknown`?S.reason:null}),O=t.state.kind===`none`||t.state.kind===`present`;if(n.kind===`absent`||!c.deviceTypes.includes(e.type))return null;let k=async e=>{let n=await t.save(e);g(n.kind===`refused`?n.reason:null)},A=_o(b),j=b?.draft.edges?.[0],ee=j!==void 0&&c.edges.includes(j)?j:c.defaultEdge,te=C===null?``:Fr(C.cap,C.fieldPath,u.language),M=y.kind===`known`&&y.value===null,ne=!x&&y.kind===`known`&&y.value!==null;return a(s,{children:[d(Rr,{id:i,icon:D,title:o,testId:`event-card-${i}`,actions:a(s,{children:[v!==null&&a(`label`,{className:`flex items-center gap-1.5 text-[11px] text-foreground`,children:[d(Ht,{"aria-label":l(`customize.doorbell.active`),checked:v.enabled!==!1,disabled:!O||t.saving,onChange:e=>{k(Pr(_,t.target,{...v,enabled:e.target.checked}))}}),l(`customize.doorbell.active`)]}),d(Y,{children:l(ai(E.text,E.status.state))})]}),children:d(`div`,{className:`flex flex-col gap-2 px-3 py-2 sm:px-4`,children:n.kind===`pending`||n.kind===`present`&&!O?d(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:l(`customize.event.checking`)}):n.kind===`unknown`?d(q,{title:l(`customize.scalar.unreadable`),message:n.reason}):a(s,{children:[x&&C!==null&&d(`p`,{className:`text-xs text-foreground`,children:l(`customize.scalar.override`,{name:w?.name??C.stableId,field:te})}),x&&d(mo,{deviceId:e.id,cap:i,timestampPath:c.timestampPath,counterPath:c.counterPath,startedAt:t.state.kind===`present`?t.state.view.block.createdAt:null}),ne&&v!==null&&a(`p`,{className:`text-xs text-foreground flex flex-wrap items-center gap-1`,children:[l(`customize.doorbell.otherFormula`),d(Kr,{handle:t,cap:i,fieldPath:c.counterPath})]}),M&&d(`p`,{className:`text-xs text-foreground-subtle`,children:l(`customize.scalar.noOverride`)}),h!==null&&d(`p`,{role:`alert`,className:`text-xs text-danger break-words`,children:h}),a(`div`,{className:`flex flex-wrap gap-2`,children:[x&&d(J,{variant:`outline`,size:`sm`,disabled:t.saving,onClick:()=>m(!0),children:l(`customize.scalar.change`)}),x&&d(J,{variant:`ghost`,size:`sm`,disabled:t.saving,onClick:()=>{if(_===null)return;let t=ci(_,i);f(l(`customize.doorbell.removeWhat`,{name:w?.name??e.name}),t===null).then(e=>{e&&k(t)})},children:l(`customize.scalar.remove`)}),M&&d(J,{variant:`outline`,size:`sm`,"data-testid":`event-add-${i}`,disabled:t.saving,onClick:()=>m(!0),children:l(`customize.scalar.add`)})]})]})})}),d($a,{open:p,mode:x?`change`:`add`,title:o,cap:i,targetId:c.id,host:e,target:t.target,enabled:v?.enabled!==!1,debounceMs:b?.draft.debounceMs??c.debounceMs,edges:c.edges,edge:ee,sources:A,canSave:O&&!t.saving,onClose:()=>m(!1),onSave:e=>{m(!1),k(Pr(_,t.target,e))}})]})}function mo({deviceId:e,cap:t,timestampPath:n,counterPath:r,startedAt:i}){let{t:o}=Z(),s=Vr({deviceId:e,cap:t,path:n}),c=Vr({deviceId:e,cap:t,path:r}),l=fo(s.kind===`pending`?`pending`:s.kind!==`value`||typeof s.value!=`number`?`unknown`:s.value,c.kind===`value`&&typeof c.value==`number`?c.value:null);return l.kind===`pending`?d(`p`,{role:`status`,className:`text-[11px] text-foreground-subtle`,children:o(`customize.event.checking`)}):l.kind===`unknown`?d(`p`,{role:`status`,className:`text-[11px] text-foreground-subtle`,children:o(`customize.event.doorbellLast.unknown`)}):l.kind===`none`?a(`p`,{role:`status`,className:`text-[11px] text-foreground-subtle`,children:[o(`customize.event.doorbellLast.none`,{when:i===null?``:bi(i)}),l.pressCount===null?``:` · ${o(`customize.event.doorbellCount`,{count:l.pressCount})}`]}):a(`p`,{role:`status`,className:`text-[11px] text-foreground`,children:[o(`customize.event.doorbellLast.ring`,{when:bi(l.lastPressedAt)}),l.pressCount===null?``:` · ${o(`customize.event.doorbellCount`,{count:l.pressCount})}`]})}function ho(e,t){return e.state.kind===`pending`?{kind:`pending`}:e.state.kind===`unknown`||e.state.kind===`not-loaded`?{kind:`unknown`,reason:e.state.reason}:{kind:`known`,value:t}}function go(e,t,n){return e?t===`pending`?`pending`:t===`unknown`?`unknown`:n?`present`:`absent`:`present`}function _o(e){return e===null?[]:e.draft.sources.map((t,n)=>({addonId:t.addonId,stableId:t.stableId,cap:t.cap,fieldPath:t.fieldPath,changedAtField:e.changedAtFields[n]??``}))}e();function vo(e){return e===`pending`?`pending`:e===`error`?`failed`:`answered`}function yo(e){let{t}=Z(),n=e.mode===`change`?t(`customize.scalar.changeTitle`,{title:e.title}):t(`customize.scalar.addTitle`,{title:e.title});return d(Pn,{open:e.open,onOpenChange:t=>!t&&e.onClose(),children:a(mn,{placement:`sheet-on-mobile`,scroll:`body`,"aria-label":n,children:[d(Ln,{children:d(Sn,{children:n})}),e.open?d(bo,{...e}):null]})})}function bo(e){let{t,i18n:i}=Z(),o=Zn({projection:`slim`}),c=o.status===`success`?ui(o.data):[],[l,u]=r(e.sources),[f,p]=r(null),[m,h]=r(e.sourceModes[0]??`in-addition`),[g,_]=r(e.timeoutMs/1e3),[v,y]=r((e.cooldownMs??0)/1e3),b=f===null?null:c.find(e=>e.id===f)??null,x=Hn({deviceId:b?.id??0}),S=x.status===`success`?x.data:{caps:[]},C=n(()=>Va(e.cap,e.targetId),[e.cap,e.targetId]),w=Xr(C,e.open),T=n(()=>w.kind===`known`?Ga(c,e.host.id,w.value,C):[],[w,c,e.host.id,C]),E=b===null?null:Wa(S,e.cap,e.targetId,`span`),D=Ja({cap:e.cap,targetId:e.targetId,device:e.target,timeoutMs:Math.round(g*1e3),cooldownMs:e.cooldownMs===null?void 0:Math.round(v*1e3),sources:l}),O=typeof e.host.location==`string`&&e.host.location.length>0?e.host.location:null,k=()=>{if(b===null||E===null||b.addonId===e.host.addonId&&b.stableId===e.host.stableId)return;let t={addonId:b.addonId,stableId:b.stableId,cap:E.cap,fieldPath:E.fieldPath,mode:m,label:b.name};if(l.some(e=>e.addonId===t.addonId&&e.stableId===t.stableId)){p(null);return}u([...l,t]),p(null)};return a(s,{children:[a(rr,{className:`flex flex-col gap-3 p-2 sm:p-4`,children:[d(`p`,{className:`text-[11px] text-foreground-muted`,children:t(`customize.event.spanBody`)}),d(So,{mode:m,modes:e.sourceModes,name:t(`customize.motion.add`),onChange:h}),d(`ul`,{className:`flex flex-col gap-2`,children:l.map(n=>a(`li`,{className:`flex flex-col gap-1 text-xs`,children:[d(`span`,{className:`text-foreground`,children:n.label.length>0?n.label:Fr(n.cap,n.fieldPath,i.language)}),d(So,{mode:n.mode,modes:e.sourceModes,name:n.stableId,onChange:e=>u(l.map(t=>t.addonId===n.addonId&&t.stableId===n.stableId?{...t,mode:e}:t))}),d(J,{variant:`ghost`,size:`sm`,onClick:()=>u(l.filter(e=>e.addonId!==n.addonId||e.stableId!==n.stableId)),children:t(`customize.event.clear`)})]},`${n.addonId}/${n.stableId}`))}),o.status===`error`?d(q,{title:t(`customize.picker.devicesFailed`),message:o.error?.message??``}):d(_t,{devices:Ka(c,e.host.id),listState:vo(o.status),value:f===null?[]:[f],selection:`single`,...O===null?{}:{groupBy:`location`},lockedIds:T,lockedNote:t(`customize.scalar.fit.kind`),onChange:e=>p(e[0]??null),noun:`device`,showAll:!0,testId:`event-span-picker`}),E!==null&&d(`p`,{className:`text-[11px] text-foreground-subtle`,children:Fr(E.cap,E.fieldPath,i.language)}),d(J,{variant:`secondary`,size:`sm`,disabled:E===null,onClick:k,children:t(`customize.motion.add`)}),d(Co,{label:t(`customize.event.timeout`),value:g,onChange:_}),e.cooldownMs!==null&&d(Co,{label:t(`customize.event.cooldown`),value:v,onChange:y}),b!==null&&E!==null&&d(wo,{deviceId:b.id,cap:E.cap,fieldPath:E.fieldPath,timeoutMs:Math.round(g*1e3)})]}),a(Un,{className:`flex flex-wrap gap-2`,children:[d(J,{variant:`ghost`,onClick:e.onClose,children:t(`customize.scalar.cancel`)}),d(J,{"data-testid":`event-save`,disabled:!e.canSave||D===null,onClick:()=>{D!==null&&e.onSave(D)},children:t(`customize.scalar.save`)})]})]})}function xo(e,t){return t.find(t=>t===e)??null}function So({mode:e,modes:t,name:n,onChange:r}){let{t:i}=Z();return t.length===0?null:a(`div`,{className:`flex flex-col gap-1`,children:[d(Bt,{"aria-label":i(`customize.motion.modeFor`,{name:n}),value:e,options:t.map(e=>({value:e,label:i(`customize.motion.mode.${e}`)})),onChange:e=>{let n=xo(e.target.value,t);n!==null&&r(n)}}),d(`p`,{className:`text-[11px] text-foreground-muted`,children:i(`customize.motion.modeLine.${e}`)})]})}function Co({label:e,value:t,onChange:n}){return a(`label`,{className:`flex flex-col gap-1 text-[11px] text-foreground`,children:[e,d(mt,{type:`number`,"aria-label":e,value:Number.isFinite(t)?t:0,onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&t>=0&&n(t)}})]})}function wo({deviceId:e,cap:t,fieldPath:n,timeoutMs:r}){let{t:i}=Z(),a=Vr({deviceId:e,cap:t,path:n}),o=a.kind===`value`&&typeof a.value==`boolean`?{kind:`level`,active:a.value,changedAt:null}:{kind:`unread`};return d(`p`,{role:`status`,className:`text-[11px] text-foreground-subtle`,children:i(To(o,Ee(be,o,{timeoutMs:r,cooldownMs:0,nowMs:Date.now()}).open))})}function To(e,t){return e.kind===`unread`?`customize.event.previewWaiting`:t?`customize.event.previewMotionOn`:e.active?`customize.event.previewSensorOn`:`customize.event.previewMotionOff`}e();function Eo({device:e,availability:t,cap:n,title:i,view:o,sensors:c}){let{t:u}=Z(),f=At(),p=on(),m=wn({addonId:`pipeline-orchestrator`,deviceId:e.id,nodeId:`hub`}),[h,g]=r(!1),[_,v]=r(null),y=l(!1),[b,x]=r(!1),S=Oo(c),C=xe(o.id,S),w=Ao(pi(m.data).motionCooldownMs,o.timeoutMs);if(t.kind===`absent`||!o.deviceTypes.includes(e.type))return null;let T=b||f.isPending||p.isPending,E=C.writable&&!T&&t.kind===`present`,D=async t=>{if(!C.writable||y.current){v(u(`customize.saveInFlight`));return}y.current=!0,x(!0);try{await Za(e.id,t,async e=>{await f.mutateAsync({deviceId:e.deviceId,config:e.config===null?null:{sensors:e.config.sensors.map(e=>({addonId:e.addonId,stableId:e.stableId,mode:e.mode}))}})},async e=>{let t={motionCooldownMs:e.patch.motionCooldownMs};await p.mutateAsync({deviceId:e.deviceId,patch:t})}),v(null),await c.refetch()===`failed`&&v(u(`customize.motion.refetchFailed`))}catch(e){v(e instanceof Error?e.message:String(e))}finally{y.current=!1,x(!1)}},O=C.rows.map(e=>({addonId:e.addonId,stableId:e.stableId,cap:`binary`,fieldPath:`on`,mode:e.mode,label:e.name}));return a(s,{children:[d(Rr,{id:n,icon:fe,title:i,testId:`event-card-${n}`,actions:d(Y,{children:u(ai(C.text,C.status.state))}),children:d(`div`,{className:`flex flex-col gap-2 px-3 py-2 sm:px-4`,children:t.kind===`pending`||S.kind===`pending`?d(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:u(`customize.motion.reading`)}):t.kind===`unknown`||S.kind===`unknown`?d(q,{title:u(`customize.motion.unreadable`,{reason:ko(S)}),message:S.kind===`unknown`?S.reason??``:``}):a(s,{children:[d(Do,{deviceId:e.id}),C.rows.length===0?d(`p`,{className:`text-xs text-foreground-subtle`,children:u(`customize.scalar.noOverride`)}):d(`ul`,{className:`flex flex-col gap-1`,children:C.rows.map(e=>a(`li`,{className:`text-xs text-foreground`,children:[e.name,e.reason===null?``:` — ${u(`customize.motion.state.${e.state}`)}`]},e.key))}),d(`p`,{className:`text-[11px] text-foreground-subtle`,children:u(`customize.event.timeoutSeconds`,{seconds:w/1e3})}),_!==null&&d(`p`,{role:`alert`,className:`text-xs text-danger break-words`,children:_}),d(`div`,{className:`flex flex-wrap gap-2`,children:d(J,{variant:`outline`,size:`sm`,"data-testid":`event-add-${n}`,disabled:!E,onClick:()=>g(!0),children:C.rows.length===0?u(`customize.scalar.add`):u(`customize.scalar.change`)})})]})})}),d(yo,{open:h,mode:C.rows.length===0?`add`:`change`,title:i,cap:n,targetId:o.id,host:e,target:{addonId:e.addonId,stableId:e.stableId},timeoutMs:w,cooldownMs:o.cooldownMs,sourceModes:o.sourceModes,sources:O,canSave:E,onClose:()=>g(!1),onSave:e=>{g(!1),D(e)}})]})}function Do({deviceId:e}){let{t}=Z(),n=Vr({deviceId:e,cap:`motion`,path:`detected`}),r=Vr({deviceId:e,cap:`motion`,path:`lastDetectedAt`}),i=lo(n.kind===`pending`?`pending`:n.kind!==`value`||typeof n.value!=`boolean`?`unknown`:n.value,r.kind===`value`&&typeof r.value==`number`?r.value:null,Date.now());return d(`p`,{role:`status`,className:`text-xs text-foreground`,children:t(i.kind===`active`?`customize.event.motionNow.active`:`customize.event.motionNow.${i.kind}`,i.seconds===null?void 0:{seconds:i.seconds})})}function Oo(e){return e.presence===`pending`?{kind:`pending`}:e.status===null?{kind:`unknown`,reason:null}:{kind:`known`,value:e.status}}function ko(e){return e.kind===`unknown`?e.reason??``:e.kind===`known`&&e.value.state===`unreadable`?e.value.reason:``}function Ao(e,t){return e!==null&&Number.isFinite(e)?e:t}var jo=ye;function Mo(e,t){let n=jo[e];return n===void 0?null:n.targets.find(e=>e.id===t)??null}function No({device:e,handle:t,facts:n,sensors:r}){let{t:i}=Z();return d(s,{children:ei().map(a=>{let o=a.pulse??a.span;if(o===null||!o.deviceTypes.includes(e.type))return null;let s=Mo(a.cap,o.id);if(s===null)return null;let c=i(a.pulse===null?`customize.motion.title`:`customize.doorbell.title`),l=ni(Jr(a.cap,s),n);return a.pulse===null?a.span===null?null:d(Eo,{device:e,availability:l,cap:a.cap,title:c,view:a.span,sensors:r},a.cap):d(po,{device:e,handle:t,availability:l,cap:a.cap,title:c,view:a.pulse},a.cap)})})}function Po({id:e,icon:t,title:n,headerControl:r,addLabel:i,onAdd:o,addDisabled:c=!1,notices:l,suggestion:u,children:f}){let{t:p}=Z(),m=o!==void 0&&i!==void 0;return a(Rr,{id:e,icon:t,title:n,actions:a(s,{children:[r,m&&!c&&u!==void 0&&u.count>0&&a(J,{variant:`ghost`,size:`sm`,onClick:u.onOpen,children:[d(re,{className:`h-3.5 w-3.5`,"aria-hidden":!0}),p(`customize.suggest.hint`,{count:u.count,location:u.location})]}),m&&d(J,{variant:`outline`,size:`sm`,disabled:c,onClick:o,children:i})]}),children:[l!==void 0&&d(`div`,{className:`flex flex-col gap-1 px-3 pt-2 empty:hidden sm:px-4`,children:l}),d(`ul`,{className:`flex flex-col divide-y divide-border`,children:f})]})}function Fo(e,t){if(e.kind!==`known`||typeof t!=`string`||t.length===0)return null;let n=jt(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 Io(e,t,n){return Yt(e,t?.ids??new Set,n)}function Lo(e,t){return e?.containers.get(t)??null}function Ro(e,t,n){return e.kind===`known`?Io(e.value,t,n).suggested.length:0}function zo(e,t){let n=[t,e.detail].filter(e=>e!==null&&e!==``);return n.length===0?null:n.join(` · `)}function Bo({location:e,devices:t,action:n,onPick:r,onPickAll:i}){let{t:o}=Z();if(t.length===0)return null;let s=o(`customize.suggest.heading`,{location:e});return a(`section`,{"aria-label":s,className:`flex flex-col gap-1`,children:[a(`div`,{className:`flex min-h-7 items-center gap-2`,children:[d(`h3`,{className:`${j} min-w-0 flex-1`,children:s}),i!==void 0&&t.length>1&&d(J,{variant:`ghost`,size:`sm`,onClick:i,children:o(`customize.suggest.addAll`,{count:t.length})})]}),d(`ul`,{className:`flex flex-col divide-y divide-border rounded-md border border-border`,children:t.map(e=>{let t=zo(e,e.container===null||e.name.includes(e.container)?null:o(`customize.suggest.in`,{container:e.container}));return a(`li`,{className:`${A} flex items-center gap-3`,children:[a(`div`,{className:`min-w-0 flex-1`,children:[d(`div`,{className:`text-xs text-foreground break-words`,children:e.name}),t!==null&&d(`div`,{className:`text-[11px] text-foreground-subtle break-words`,children:t})]}),d(J,{variant:`outline`,size:`sm`,"aria-label":o(n===`add`?`customize.suggest.addNamed`:`customize.suggest.useNamed`,{name:e.name}),onClick:()=>r(e.id),children:o(n===`add`?`customize.suggest.add`:`customize.suggest.use`)})]},e.id)})})]})}e();function Vo(e){return e.kind===`pending`?`pending`:e.kind===`unknown`?`failed`:`answered`}function Ho(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 Uo({open:e,title:i,selection:o,candidates:s,filters:c,room:l=null,confirmLabel:u,onConfirm:f,onClose:p}){let{t:m}=Z(),[h,g]=r(null),[_,v]=r([]),y=c?.find(e=>e.id===h)??c?.[0]??null,b=s.kind===`known`?s.value:[],x=s.kind===`known`?di(s.value,``,y):[],S=Io(b,l,e=>e.deviceId).suggested,C=Io(x,l,e=>e.deviceId).others,w=n(()=>Ho(C),[C]),T=Vo(s),E=b.filter(e=>_.includes(e.deviceId));t(()=>{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 d(Pn,{open:e,onOpenChange:e=>e?void 0:D(),children:a(mn,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,"aria-label":i,children:[d(Ln,{children:d(Sn,{children:i})}),a(rr,{className:`flex flex-col gap-2 p-2 sm:p-4`,children:[c!==void 0&&c.length>0&&d(`div`,{className:`flex flex-wrap gap-1`,role:`tablist`,"aria-label":m(`customize.assign.filtersLabel`),children:c.map(e=>d(`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))}),l!==null&&d(Bo,{location:l.location,devices:S.map(e=>({id:e.deviceId,name:e.name,container:Lo(l,e.deviceId),detail:e.detail})),action:`add`,onPick:e=>O(S.filter(t=>t.deviceId===e)),...o===`multi`?{onPickAll:()=>O(S)}:{}}),s.kind===`unknown`?d(`p`,{role:`alert`,className:`text-xs text-warning`,children:m(`customize.assign.unknown`,{reason:s.reason})}):w.length===0&&S.length>0?null:d(_t,{devices:w,listState:T,value:_,onChange:e=>v(o===`single`?e.length>0?[e[e.length-1]]:[]:e),noun:`device`,emptyLabel:m(`customize.assign.none`),showAll:!0,testId:`customize-device-picker`})]}),a(Un,{children:[d(J,{variant:`ghost`,onClick:D,children:m(`customize.picker.cancel`)}),d(J,{disabled:E.length===0,onClick:k,children:u(E.length)})]})]})})}e();function Wo(e,t){let r=typeof e==`string`&&e.length>0,i=Nr(t&&r);return n(()=>t?Fo(i,e):null,[t,i,e])}e();function Go(e){return e==null?null:e.message}function Ko({device:e}){let t=ue(),{t:n}=Z(),i=c(),o=Ur(),l=we.includes(e.type),[u,f]=r(!1),[p,m]=r(!1),[h,g]=r(null),_=Ct({deviceId:e.id},{enabled:l}),v=Ei({status:_.status,data:_.data,error:Go(_.error)===null?null:{message:Go(_.error)??``}}),y=v.kind===`present`?v.slot.slotRef:``,b=v.kind===`present`?[...wi(v.slot,v.value).map(e=>e.deviceId),...Ci(v.slot,v.value)]:[],x=Ot(),S=Nr(l&&v.kind===`present`&&(u||b.length>0)),C=Wo(e.location,l&&v.kind===`present`),w=bt({deviceId:e.id,slotRef:y},{enabled:(u||C!==null)&&v.kind===`present`});if(!l||v.kind===`absent`)return null;if(v.kind!==`present`)return d(Po,{id:`linked`,icon:I,title:n(`customize.linked.title`),notices:v.kind===`pending`?d(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:n(`customize.assign.checking`)}):d(`p`,{role:`alert`,className:`text-xs text-warning break-words`,children:n(`customize.assign.unknown`,{reason:v.reason})}),children:null});let T=v.value,E=new Map(S.kind===`known`?S.value.map(e=>[e.id,e]):[]),D=T.trackedDeviceIds!==void 0,O=(e,t)=>{let n=E.get(e.deviceId);return{...e,name:e.name??n?.name??null,type:n?.type??null,detail:n===void 0?null:fi(n.integration,n.location),orphan:t}},k=[...wi(v.slot,T).map(e=>O(e,!1)),...Ci(v.slot,T).map(e=>O({deviceId:e,name:null,health:`ok`,implied:!1,tracked:!0},!0))],A=new Set(b),j=S.kind===`unknown`?S:w.status===`error`?{kind:`unknown`,reason:Go(w.error)??n(`helpers.customize.requestFailed`)}:S.kind===`pending`||w.status===`pending`||w.data===void 0?{kind:`pending`}:{kind:`known`,value:Oi(w.data.candidates,E,A)},ee=async t=>{if(p){g(n(`customize.saveInFlight`));return}m(!0),g(null);try{await x.mutateAsync({deviceId:e.id,slotRef:v.slot.slotRef,value:t}),await _.refetch(),await i.invalidateQueries({queryKey:[[`deviceManager`]]})}catch(e){g(e instanceof Error?e.message:String(e))}finally{m(!1)}},te=async e=>{await o(n(`customize.linked.removeWhat`,{name:e.name??`#${e.deviceId}`}),!1)&&await ee(Di(T,e.deviceId))},M=[{key:`device`,header:n(`customize.linked.device`),cell:e=>a(`div`,{className:`flex flex-col min-w-0`,children:[d(`span`,{className:`truncate text-xs text-foreground`,children:e.name??`#${e.deviceId}`}),e.detail!==null&&d(`span`,{className:`truncate text-[11px] text-foreground-subtle`,children:e.detail}),e.orphan&&d(`span`,{className:`text-[11px] text-foreground-subtle`,children:n(`customize.linked.notLinked`)}),e.health!==`ok`&&d(`span`,{role:`alert`,className:`text-[11px] text-warning`,children:n(`customize.linked.health.${e.health}`)})]})},{key:`type`,header:n(`customize.linked.type`),headerClassName:`hidden sm:table-cell`,cellClassName:`hidden sm:table-cell text-xs text-foreground-subtle`,cell:e=>e.type===null?`—`:dn(e.type,t).label},{key:`controls`,header:n(`customize.linked.controls`),headerClassName:`hidden md:table-cell`,cellClassName:`hidden md:table-cell text-xs text-foreground-subtle`,cell:e=>e.orphan?`—`:n(`customize.linked.yes`)},...D?[{key:`tracked`,header:n(`customize.linked.tracked`),cellClassName:`text-right`,headerClassName:`text-right`,cell:e=>d(Ze,{checked:e.tracked,disabled:p,"aria-label":n(`customize.linked.trackFor`,{name:e.name??e.deviceId}),onCheckedChange:t=>void ee(Ti(T,e.deviceId,t))})}]:[],{key:`remove`,header:``,cellClassName:`text-right w-10`,cell:e=>e.implied||e.orphan?null:d(Kt,{icon:P,variant:`ghost`,size:`sm`,"aria-label":n(`customize.assign.removeNamed`,{name:e.name??e.deviceId}),disabled:p,onClick:t=>{t.stopPropagation(),te(e)}})}];return a(s,{children:[d(Po,{id:`linked`,icon:I,title:n(`customize.linked.title`),addLabel:n(`customize.linked.add`),onAdd:p?void 0:()=>f(!0),...C===null?{}:{suggestion:{count:Ro(j,C,e=>e.deviceId),location:C.location,onOpen:()=>f(!0)}},notices:a(s,{children:[S.kind===`unknown`&&d(`p`,{role:`alert`,className:`text-xs text-warning break-words`,children:n(`customize.assign.devicesUnreadable`,{reason:S.reason})}),h!==null&&d(`p`,{role:`alert`,className:`text-xs text-danger break-words`,children:h})]}),children:a(`li`,{className:`list-none px-3 py-2 sm:px-4`,children:[k.length===0?d(`p`,{className:`text-[11px] text-foreground-subtle`,children:n(`customize.assign.none`)}):d(rt,{mode:`generic`,items:k,getKey:e=>String(e.deviceId),getSearchText:e=>[e.name??``,e.detail??``,e.type??``,String(e.deviceId)].join(` `),getFilterType:e=>e.type===null?null:dn(e.type,t).label,columns:M,searchPlaceholder:n(`customize.assign.search`),emptyLabel:n(`customize.assign.none`)}),k.some(e=>!e.orphan)&&d(`p`,{className:`mt-2 text-[10px] text-foreground-subtle`,children:n(`customize.linked.controlsAlways`)}),D&&d(`p`,{className:`mt-0.5 text-[10px] text-foreground-subtle`,children:n(`customize.linked.trackedHint`)})]})}),d(Uo,{open:u,title:n(`customize.linked.pickTitle`),selection:`multi`,candidates:j,room:C,confirmLabel:e=>n(`customize.assign.addCount`,{count:e}),onConfirm:e=>{f(!1),ee(Si(T,e.map(e=>e.deviceId)))},onClose:()=>f(!1)})]})}e();function qo(e){return e instanceof Error?e.message:String(e)}function Jo(e){let t=ar({addonId:e.addonId,stableId:e.stableId}),n=yn(),i=nt(),a=Qt(),o=Zr({status:t.status,data:t.data,error:t.error===null||t.error===void 0?null:{message:t.error.message}}),{t:s}=Z(),c=l(!1),[u,d]=r(!1),f=async e=>{let r=Br(o,e);try{switch(r.kind){case`refused`:return{kind:`refused`,reason:r.reason};case`noop`:return{kind:`saved`};case`create`:await n.mutateAsync({block:r.input});break;case`update`:await i.mutateAsync({blockId:r.blockId,expectedUpdatedAt:r.expectedUpdatedAt,block:{composition:r.composition}});break;case`delete`:await a.mutateAsync({blockId:r.blockId});break}return await t.refetch(),{kind:`saved`}}catch(e){return{kind:`refused`,reason:qo(e)}}};return{target:e,state:o,saving:u||n.isPending||i.isPending||a.isPending,save:async e=>{if(c.current)return{kind:`refused`,reason:s(`customize.saveInFlight`)};c.current=!0,d(!0);try{return await f(e)}finally{c.current=!1,d(!1)}}}}var Yo=`pipeline-orchestrator`;function Xo(e){return e.status===`pending`?`pending`:e.status===`error`?`unknown`:e.data===void 0?`pending`:e.data.cameraSensors===void 0?`absent`:`present`}function Zo(e,t){return e===`absent`?`absent`:Xo(t)}async function Qo(e){try{return(await e()).isError?`failed`:`answered`}catch{return`failed`}}function $o(e,t){let n=Rt(Yo),r=Je({deviceId:e},{enabled:t&&n!==`absent`}),i=()=>Qo(r.refetch);return t?{presence:Zo(n,{status:r.status,data:r.data}),status:r.data?.cameraSensors??null,refetch:i}:{presence:`absent`,status:null,refetch:i}}function es(e,t){let n=It({deviceType:e.type}),r=_n({deviceId:e.id}),i=Hn({deviceId:e.id}),a=Lr(n,e=>new Set(e.caps.map(e=>e.cap))),o=Lr(r,e=>$r(e.entries)),s=Lr(i,e=>e);return{deviceType:e.type,composable:a,nativeCaps:o,wireable:s,composed:new Set((t?.features??[]).map(e=>e.cap))}}function ts(e,t,n){let r=t.kind===`known`&&t.value.has(`consumables`),i=Vr(r?{deviceId:e,cap:Hr,path:ti}:null);return ii(t,n,r?i:null)}e();function ns({device:e}){let{t}=Z(),r=e.stableId.startsWith(`composed-`)?e.stableId.slice(Oe.length):null,i=an({blockId:r??``},{enabled:r!==null}),o=nt(),s=n(()=>{let e=new Set;for(let{cap:t}of Qr())e.add(t);for(let{cap:t}of Yr())e.add(t);for(let{cap:t}of ei())e.add(t);return e},[]);if(r===null)return d(`p`,{className:`text-xs text-foreground-subtle`,children:t(`customize.composed.missingBlock`)});if(i.status===`pending`)return d(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:t(`customize.loadingDevice`)});if(i.status===`error`)return d(q,{title:t(`customize.composed.loadFailed`),message:i.error.message,onRetry:()=>void i.refetch()});if(i.data.state===`not-loaded`)return d(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:t(`customize.status.notLoaded`,{reason:i.data.reason})});let c=i.data.view;if(c===null)return d(`p`,{className:`text-xs text-foreground-subtle`,children:t(`customize.composed.notFound`)});let l=Te(c.block);if(l===null)return d(`p`,{className:`text-xs text-foreground-subtle`,children:t(`compositionEditor.notComposition`)});let u={target:{addonId:e.addonId,stableId:e.stableId},state:{kind:`present`,view:c,composition:l},saving:o.isPending,save:async e=>{if(e===null)return{kind:`refused`,reason:t(`customize.composed.noDelete`)};try{return await o.mutateAsync({blockId:c.block.id,expectedUpdatedAt:c.block.updatedAt,block:{composition:e}}),await i.refetch(),{kind:`saved`}}catch(e){return{kind:`refused`,reason:e instanceof Error?e.message:String(e)}}}};return a(`div`,{className:`flex flex-col gap-3`,children:[d(Ia,{device:e}),Ir(l)===`incomplete`&&d(Y,{variant:`warning`,children:t(`customize.blockStatus.incomplete`)}),d(qr,{device:e,handle:u,skipCaps:s})]})}e();function rs({deviceId:e}){let{t}=Z(),n=Yn({deviceId:e}),r=n.data;return r==null?n.status===`error`?d(q,{title:t(`customize.deviceUnreadable`),message:n.error?.message??``,onRetry:()=>void n.refetch()}):r===null?d(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:t(`customize.noSuchDevice`,{deviceId:e})}):d(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:t(`customize.loadingDevice`)}):r.addonId===`composer`?d(ns,{device:r}):d(is,{device:r,target:{addonId:r.addonId,stableId:r.stableId}})}function is({device:e,target:t}){let r=Jo(t),i=Rt(`composer`),{t:o}=Z(),s=$o(e.id,e.type===G.Camera),c=es(e,zr(r.state)),l=ts(e.id,c.nativeCaps,c.wireable),u={deviceType:e.type,composable:c.composable,nativeCaps:c.nativeCaps,cameraSensors:s.presence},f=n(()=>{let e=new Set;for(let{cap:t}of Qr())e.add(t);for(let{cap:t}of Yr())e.add(t);for(let{cap:t}of ei())e.add(t);return e},[]);return a(`div`,{className:`flex flex-col gap-3`,children:[d(Ia,{device:e}),i===`absent`&&d(`p`,{role:`alert`,className:`text-xs text-warning`,children:o(`customize.composerAbsent`)}),r.state.kind!==`none`&&d(as,{state:r.state}),d(No,{device:e,handle:r,facts:u,sensors:s}),d(Wr,{device:e,handle:r,facts:u}),d(ri,{device:e,handle:r,facts:u,defaults:l}),d(qr,{device:e,handle:r,skipCaps:f}),d(Ko,{device:e})]})}function as({state:e}){let{t}=Z();switch(e.kind){case`pending`:return d(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:t(`customize.status.pending`)});case`unknown`:return d(q,{title:t(`customize.status.unknownTitle`),message:e.reason});case`not-loaded`:return d(`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 a(`div`,{className:`flex flex-wrap items-center gap-2`,children:[d(Y,{variant:n.status===`running`?`success`:n.status===`failed`?`danger`:`warning`,children:t(`customize.blockStatus.${n.status}`)}),!n.enabled&&d(Y,{variant:`default`,children:t(`customize.status.off`)}),n.lastError!==void 0&&d(`span`,{className:`text-[11px] text-foreground-muted break-words`,children:n.lastError}),e.view.state.kind===`unreachable`&&d(`span`,{className:`text-[11px] text-warning`,children:t(`customize.status.composerUnreachable`,{reason:e.view.state.error})})]})}}}var os=`overview`;function ss(e,t){return e.some(e=>e.id===t)?t:os}function cs({deviceId:e}){let{t}=Z(),n=c(),r=Number.isFinite(e),{data:i}=Yn({deviceId:e},{enabled:r}),o=typeof i?.type==`string`?i.type:`camera`;qn([`deviceManager`,`getBindings`],[`capability.binding-changed`]);let{data:s,isLoading:l,isError:u,error:f}=_n({deviceId:e},{enabled:r}),{data:p}=fn({deviceType:o},{enabled:!!o}),m=wt({onSuccess:()=>{n.invalidateQueries({queryKey:[[`deviceManager`,`getBindings`]]})}});if(l)return d(`div`,{className:`p-4`,children:d(`div`,{className:`h-20 rounded-lg border border-border bg-surface animate-pulse`})});if(u)return a(`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 s?.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 a(`div`,{className:`flex flex-col items-center justify-center gap-2 p-8 text-foreground-subtle`,children:[d(Be,{className:`h-8 w-8 opacity-40`}),d(`p`,{className:`text-xs`,children:t(`device.bindingsTab.noCapabilityProvidersApplicableTo`,`No capability providers applicable to this device yet.`)}),d(`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=>d(`span`,{className:`font-mono text-foreground`,children:e.capName})},{key:`kind`,header:t(`device.bindingsTab.kind`,`Kind`),render:e=>d(ls,{kind:e.kind})},{key:`provider`,header:t(`device.bindingsTab.activeProvider`,`Active Provider`),render:e=>d(`span`,{className:`font-mono text-foreground-subtle`,children:e.providerAddonId||d(`span`,{className:`opacity-40`,children:`—`})})},{key:`node`,header:t(`device.bindingsTab.node`,`Node`),render:e=>e.providerNodeId?d(us,{nodeId:e.providerNodeId}):d(`span`,{className:`text-[10px] opacity-40`,children:`—`})},{key:`native`,header:t(`device.bindingsTab.kindNative`,`Native`),render:e=>d(`span`,{className:`font-mono text-foreground-subtle`,children:e.nativeAddonId||d(`span`,{className:`opacity-40`,children:`—`})})},{key:`wrapper`,header:t(`device.bindingsTab.wrapper`,`Wrapper`),render:t=>{let n=t.kind===`wrapped`?t.providerAddonId:null;return d(ds,{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 a(`div`,{className:`flex flex-col gap-3 p-1`,children:[d(`div`,{className:`text-[11px] text-foreground-subtle`,children:d(Mr,{i18nKey:`device.bindingsTab.boundSummary`,count:_.length,values:{bound:v},components:{b:d(`span`,{className:`font-medium text-foreground`}),em:d(`em`,{})}})}),d(sn,{columns:y,rows:_,rowKey:e=>e.capName,minWidthPx:720})]})}function ls({kind:e}){let{t}=Z();return e===`native`?a(`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:[d(ae,{className:`h-3 w-3`}),t(`device.bindingsTab.kindNative`)]}):e===`wrapped`?a(`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:[d(Ue,{className:`h-3 w-3`}),t(`device.bindingsTab.wrapped`)]}):e===`linked`?a(`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:[d(I,{className:`h-3 w-3`}),t(`device.bindingsTab.linked`)]}):a(`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:[d(x,{className:`h-3 w-3`}),t(`common.unbound`)]})}function us({nodeId:e}){return d(`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 ds({wrappers:e,activeWrapperId:t,disabled:n,onPick:r}){let{t:i}=Z();return e.length===0?d(`span`,{className:`text-[10px] opacity-40`,children:i(`device.bindingsTab.noneAvailable`,`none available`)}):d(`div`,{className:`flex flex-wrap gap-1`,children:e.map(e=>{let o=e===t;return a(`button`,{disabled:n,onClick:()=>r(e),title:o?i(`device.bindingsTab.clickToDeactivateRevertTo`,`Click to deactivate (revert to native)`):i(`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:[d(o?O:V,{className:`h-3 w-3`}),e]},e)})})}function fs({deviceId:e,activeSubTab:t,onSubTabChange:n,deviceType:r,isAdmin:i}){return a(`div`,{className:`flex flex-col gap-3`,children:[Sr(r,i)&&d(en,{deviceId:e,readOnly:!0}),d(fr,{deviceId:e,activeSubTab:t,onSubTabChange:n})]})}e();var ps=[[`pipelineOrchestrator`,`getCameraDetectionSource`]];function ms(e){let t=c(),n=Et({deviceId:e},{refetchOnMount:`always`}),a=Jt(),[o,s]=r(null),[l,u]=r(null),d=i(async n=>{u(null),s(n);try{await a.mutateAsync({deviceId:e,source:n}),await t.invalidateQueries({queryKey:ps})}catch(e){u(e instanceof Error?e.message:`Could not change the root detector`),await t.invalidateQueries({queryKey:ps})}finally{s(null)}},[e,a,t]),f=n.data??null;return{view:f,isLoading:n.isLoading,source:o??f?.source??null,saving:o!==null,error:l,pick:d}}var hs=`object-detection`;function gs(e){return[e.addonId,...e.children.flatMap(gs)]}function _s(e,t){if(e===`pipeline`)return new Set;let n=vs(t,hs);return n===void 0?new Set:new Set(e===`onboard`?[n.addonId]:gs(n))}function vs(e,t){for(let n of e){if(n.addonId===t)return n;let e=vs(n.children,t);if(e!==void 0)return e}}function ys(e,t){return e===`onboard`?X.t(`helpers.detectionSourceModel.badgeCameraAi`):t===`object-detection`?X.t(`helpers.detectionSourceModel.badgeNoRoot`):X.t(`helpers.detectionSourceModel.badgeIdle`)}function bs(e){switch(e){case`pipeline`:return X.t(`helpers.detectionSourceModel.explainPipeline`);case`onboard`:return X.t(`helpers.detectionSourceModel.explainOnboard`);case`none`:return X.t(`helpers.detectionSourceModel.explainNone`)}}function xs(e){switch(e){case`boxed`:return``;case`while-streaming`:return X.t(`helpers.detectionSourceModel.geometryWhileStreaming`);case`flag-only`:return X.t(`helpers.detectionSourceModel.geometryFlagOnly`);case`unknown`:return X.t(`helpers.detectionSourceModel.geometryUnknown`)}}function Ss(e,t){return e===`onboard`?X.t(`helpers.detectionSourceModel.noticeOnboard`):t===`object-detection`?X.t(`helpers.detectionSourceModel.noticeNoRoot`):X.t(`helpers.detectionSourceModel.noticeIdle`)}var Cs=[`pl-2`,`pl-6`,`pl-10`,`pl-14`],ws={detector:`success`,cropper:`info`,classifier:`primary`,refiner:`warning`,"audio-classifier":`neutral`};function Ts(e){return Cs[Math.min(e,Cs.length-1)]??`pl-2`}function Es(e){return e.zoneDriven?{kind:`zone-driven`}:{kind:`gate`,effectiveOn:e.ownOn,defaultOn:e.defaultOn,explicit:e.choice!==`auto`}}function Ds(e,t,n){return e.kind===`parent`?n:ys(e.source,t)}function Os({inputs:e,outputs:t}){return e.length===0&&t.length===0?null:a(`span`,{className:`inline-flex flex-wrap items-center gap-1`,children:[e.map(e=>d(Y,{size:`sm`,variant:`info`,children:e},`in-${e}`)),e.length>0&&t.length>0&&d(`span`,{className:`text-[10px] text-foreground-subtle`,"aria-hidden":!0,children:`→`}),t.map(e=>d(Y,{size:`sm`,variant:`success`,children:e},`out-${e}`))]})}function ks({rows:e,label:t,selectedId:n,busy:r,onOpen:i,onSet:o}){let{t:s}=Z(),c=e=>{switch(e){case`detector`:return s(`device.cameraStepInspector.kindDetector`,`detector`);case`cropper`:return s(`device.cameraStepInspector.kindCropper`,`cropper`);case`classifier`:return s(`device.cameraStepInspector.kindClassifier`,`classifier`);case`refiner`:return s(`device.cameraStepInspector.kindRefiner`,`refiner`);case`audio-classifier`:return s(`device.cameraStepInspector.kindAudio`,`audio`)}},l=s(`device.cameraStepInspector.offBecauseParent`,`Off because its parent is off`);return d(`ul`,{"aria-label":t,className:`divide-y divide-border rounded-md border border-border`,children:e.map(e=>{let t=e.stepId===n,s=e.blocked===null?null:Ds(e.blocked,e.stepId,l);return a(`li`,{"data-step":e.stepId,"data-runs":e.runs?`yes`:`no`,className:`flex flex-wrap items-center gap-x-2 gap-y-1.5 py-2 pr-2 ${Ts(e.depth)} ${t?`bg-primary/10`:e.runs?``:`bg-muted/40`}`,children:[a(`button`,{type:`button`,"aria-expanded":t,onClick:()=>i(e.stepId),className:`flex min-w-0 flex-1 flex-wrap items-center gap-x-2 gap-y-1 text-left`,children:[d(`span`,{className:`text-sm font-medium ${e.runs?`text-foreground`:`text-foreground-muted`}`,children:e.name}),d(Y,{size:`sm`,variant:ws[e.kind],children:c(e.kind)}),d(Os,{inputs:e.inputs,outputs:e.outputs}),s!==null&&d(`span`,{className:`text-[11px] text-warning`,children:s})]}),d(Rn,{gate:Es(e),busy:r,onSet:t=>o(e.stepId,t)})]},e.stepId)})})}function As(e,t){let n=e?.[t];return n===void 0?`auto`:n?`on`:`off`}function js(e,t){return e===`auto`?t:e===`on`}function Ms(e,t,n){return e!==`onboard`&&e!==`none`||!n.has(t)?null:{kind:`source`,source:e}}function Ns(e,t,n,r,i){let a=e.zoneDrivenIds??new Set;return t.flatMap(t=>{let o=a.has(t.addonId),s=As(e.toggles,t.addonId),c=e.defaults[t.addonId]??!0,l=o||js(s,c),u=r===null?Ms(e.source,t.addonId,i):{kind:`parent`,ancestorId:r.stepId},d={stepId:t.addonId,name:t.addonName,kind:t.slot,depth:n,inputs:t.inputClasses,outputs:t.outputClasses,choice:s,defaultOn:c,ownOn:l,runs:u===null&&l,blocked:u,zoneDriven:o},f=l?r:{stepId:t.addonId};return[d,...Ns(e,t.children,n+1,f,i)]})}function Ps(e){let t=e.source===null?new Set:_s(e.source,e.tree);return Ns(e,e.tree,0,null,t)}function Fs({source:e,geometry:t,saving:n,error:r,onPick:i}){let{t:o}=Z(),s=t===`flag-only`,c=xs(t);return a(`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:[a(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-1.5`,children:[d(`h3`,{className:j,children:o(`device.detectionSourceControl.rootDetector`,`Root detector`)}),d(tr,{label:o(`device.detectionSourceControl.rootDetector`,`Root detector`),value:e,onChange:t=>{!n&&t!==e&&i(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&&d(`span`,{className:`text-[10px] text-foreground-subtle`,children:o(`device.detectionSourceControl.saving`,`Saving…`)})]}),a(`p`,{className:H,children:[bs(e),` `,o(`device.detectionSourceControl.oneRoot`)]}),c!==``&&d(`p`,{className:`text-[10px] text-foreground-subtle`,children:c}),r!==null&&d(`p`,{role:`alert`,className:`text-[11px] text-danger`,children:r})]})}e();var Is=new Set([`package-detection`]),Ls=`/system/pipeline?view=nodes`;function Rs(e){return Object.fromEntries(e.slots.flatMap(e=>e.addons.map(e=>[e.id,e.enabledByDefault??!0])))}function zs({deviceId:e}){let{t}=Z(),s=Qe(),u=$n(),f=c(),p=R().trpcClient,m=l(null),h=l(null),g=kn({deviceId:e},{refetchOnMount:`always`}),_=Vt(void 0,{refetchOnMount:`always`});qn([`nodes`,`topology`],[`agent.online`,`agent.offline`,`agent.unregistered`,`addon.installed`,`addon.uninstalled`]);let{nodes:v}=Nn(),y=n(()=>{let e=new Set((_.data??[]).map(e=>e.nodeId));return v.filter(t=>t.isOnline&&e.has(t.id)).map(e=>({id:e.id,name:e.name}))},[_.data,v]),b=y.map(e=>e.id).join(`,`),x=o({enabled:y.length>0,queryKey:[[`pipelineExecutor`,`getSchema`],`camera-step-schemas`,b],queryFn:async()=>{let e={};for(let t of y)try{e[t.id]=await p.pipelineExecutor.getSchema.query({nodeId:t.id})}catch{}return e}}),S=i(()=>{f.invalidateQueries({queryKey:[[`pipelineOrchestrator`,`getCameraSettings`]]})},[f]),C=gn({onSuccess:S}),w=Ge(),[T,E]=r(null),[D,O]=r(!1),[k,A]=r(null),j=ms(e),ee=x.data??{},te=g.data??null,M=y.map(e=>ee[e.id]).find(e=>e!==void 0)??null,ne=n(()=>M?ft(M):[],[M]),re=n(()=>M===null?[]:Ps({tree:ne,toggles:te?.stepToggles,defaults:Rs(M),source:j.source,zoneDrivenIds:Is}),[ne,M,te?.stepToggles,j.source]),{selection:N,open:ie,close:ae}=gi(n(()=>re.map(e=>e.stepId),[re]),[]),F=y[0]?.id,oe=i(async e=>{if(T!==null){if(!await s({title:t(`stepInspector.stepMatrixFrame.discardUnsavedChanges`,`Discard unsaved changes?`),message:t(`stepInspector.stepMatrixFrame.thisStepHasChangesThat`,`This step has changes that are not saved yet.`),confirmLabel:t(`stepInspector.stepMatrixFrame.discard`,`Discard`),variant:`danger`}))return;E(null)}e()},[s,T,t]),se=e=>{e!==N.stepId&&oe(()=>ie({stepId:e}))},I=()=>{oe(()=>ae())};if(_.isLoading||y.length>0&&x.isLoading)return d(`div`,{className:`animate-pulse p-4 text-xs text-foreground-subtle`,children:t(`device.cameraStepInspector.loadingPipeline`,`Loading pipeline…`)});if(y.length===0)return d(`div`,{className:`p-4 text-xs text-foreground-subtle`,children:t(`device.cameraStepInspector.noPipelineNodeIsOnline`,`No pipeline node is online.`)});if(M===null)return d(`div`,{className:`p-4 text-xs text-foreground-subtle`,children:t(`device.cameraStepInspector.catalogUnavailable`,`Catalog unavailable.`)});let L=e=>_.data?.find(e=>e.nodeId===F)?.settings.stepSettings?.[e]??{},z=re.find(e=>e.stepId===N.stepId)??null,B=z===null?null:hi(M,z.stepId),ce=u?d(kt,{onClick:I}):d(Kt,{icon:P,variant:`ghost`,size:`sm`,"aria-label":t(`common.close`,`Close`),onClick:I});return a(`div`,{ref:m,className:`space-y-2`,children:[j.view?.onboard.available===!0&&j.source!==null&&d(Fs,{source:j.source,geometry:j.view.onboard.geometry,saving:j.saving,error:j.error,onPick:e=>void j.pick(e)}),d(`p`,{className:H,children:d(Mr,{i18nKey:`device.cameraStepInspector.modelsChosenByAccelerators`,components:{nodes:d(vr,{to:Ls,className:`font-medium text-primary hover:underline`})}})}),N.staleStepId!==null&&d(`p`,{className:`rounded-md border border-warning/40 bg-warning/10 px-3 py-1.5 text-[11px] text-warning`,children:t(`stepInspector.stepMatrixFrame.staleStep`,{id:N.staleStepId})}),d(ks,{rows:re,label:t(`device.cameraStepInspector.detectionStepsOfThisCamera`,`Detection steps of this camera`),selectedId:N.stepId,busy:C.isPending,onOpen:se,onSet:(t,n)=>C.mutate({deviceId:e,addonId:t,enabled:n})}),d(vn,{open:z!==null&&B!==null,anchor:m,onClose:I,label:t(`stepInspector.stepMatrixFrame.stepSettings`,`Step settings`),children:z!==null&&B!==null&&d(Bs,{addon:B,nodeBag:L(z.stepId),storedCamera:te?.stepSettings?.[z.stepId],draft:T?.stepId===z.stepId?T:null,saving:D,status:k,notice:z.blocked?.kind===`source`?Ss(z.blocked.source,z.stepId):null,closeButton:ce,onEscape:I,headingRef:e=>{h.current=e},onDraft:e=>{A(null),E({stepId:z.stepId,camera:e})},onDiscard:()=>E(null),onSave:async n=>{O(!0);try{await w.mutateAsync({deviceId:e,addonId:z.stepId,settings:Object.keys(n).length>0?{...n}:null}),E(null),A({kind:`saved`})}catch(e){A({kind:`error`,error:e instanceof Error?e.message:t(`device.cameraStepInspector.saveFailed`)})}finally{O(!1),S()}}})})]})}function Bs({addon:e,nodeBag:t,storedCamera:n,draft:r,saving:i,status:o,notice:s,closeButton:c,onEscape:l,headingRef:u,onDraft:f,onDiscard:p,onSave:m}){let{t:h}=Z(),g=ot(e),_=vi(g),v=_i(g),y=r?.camera??n,b=r!==null&&!K(r.camera,n??{});return d(qt,{ref:u,title:h(`device.cameraStepInspector.thisCamera`,`{{name}} · this camera`,{name:e.name}),subtitle:e.slot,leading:c,onEscape:l,..._.length>0?{saveBar:{dirtyCount:+!!b,saving:i,status:o?.kind??null,...o?.error===void 0?{}:{error:o.error},onSave:()=>void m(r?.camera??n??{}),onDiscard:p,scope:d(`p`,{className:H,children:h(`device.cameraStepInspector.appliesToAllAcceleratorsOf`,`Applies to: all accelerators of this camera.`)})}}:{},children:a(`div`,{className:`space-y-3`,children:[s!==null&&d(`p`,{role:`note`,className:`rounded-md border border-warning/40 bg-warning/10 px-3 py-1.5 text-[11px] text-warning`,children:s}),_.length>0?d(Vs,{addon:e,fields:_,nodeBag:t,cameraBag:y,onChange:f}):d(`p`,{className:H,children:h(`device.cameraStepInspector.noCameraSettings`,`This step has no settings on this camera.`)}),v&&d(`p`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`accelerator-only-thresholds`,children:h(`device.cameraStepInspector.thresholdsAreTheAccelerators`,`Confidence thresholds belong to the model, so they are set on the accelerator that runs it (Pipeline → Nodes), not per camera.`)})]})})}function Vs({addon:e,fields:t,nodeBag:n,cameraBag:r,onChange:i}){let{t:a}=Z();return d(ht,{addon:e,fields:t,layers:{node:n,...r===void 0?{}:{camera:r}},target:`camera`,labels:{camera:a(`device.cameraStepInspector.layerCamera`,`This camera`),node:a(`device.cameraStepInspector.layerNode`,`Node`)},modelId:e.defaultModelId,onChangeLayer:i})}function Hs(e,t,n){return{id:e,get label(){return X.t(t)},icon:n}}var Us=[Hs(`object-detection`,`helpers.detectionSettingsGroups.objectDetection`,`scan-search`),Hs(`tracking`,`helpers.detectionSettingsGroups.tracking`,`route`),Hs(`motion`,`helpers.detectionSettingsGroups.motion`,`activity`),Hs(`stationary`,`helpers.detectionSettingsGroups.stationary`,`square-parking`),Hs(`zones`,`helpers.detectionSettingsGroups.zones`,`shapes`),Hs(`audio`,`helpers.detectionSettingsGroups.audio`,`volume-2`),Hs(`cluster`,`helpers.detectionSettingsGroups.cluster`,`server`)],Ws={"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 Gs(e){return Ws[e]??`object-detection`}e();var Ks=`steps`,qs=`settings`,Js=new Set([Ks,qs]);function Ys(e){return e.location===`top-tab`&&(e.tab===`detection-pipeline`||e.tab===`zones`)}function Xs({deviceId:e,activeSubTab:t,onSubTabChange:n}){let{t:r}=Z();return a(ut,{value:t&&Js.has(t)?t:Ks,onValueChange:i(e=>{n?.(e)},[n]),className:`flex flex-col`,children:[a(Pt,{className:`flex-shrink-0`,children:[d(lr,{value:Ks,children:r(`device.detectionPipelineTab.steps`,`Steps`)}),d(lr,{value:qs,children:r(`device.detectionPipelineTab.settings`,`Settings`)})]}),d(vt,{value:Ks,children:d(zs,{deviceId:e})}),d(vt,{value:qs,children:d(fr,{deviceId:e,sectionFilter:Ys,subTabGrouping:{groupOf:e=>Gs(e.id),tabs:Us}})})]})}var Zs=`Notifications`,Qs={i18nKey:`device.deviceNotificationMute.cameraCostWhenOff`,text:`This camera never notifies — no rule, no target, no alarm. Existing events, tracks and recordings are unaffected.`},$s={i18nKey:`device.deviceNotificationMute.deviceCostWhenOff`,text:`This device never notifies — no rule, no target, no alarm.`};function ec(e){let{mutedDeviceIds:t,deviceId:n}=e,r=t===null?null:!t.includes(n),i=e.pendingOn??null;return{label:Zs,on:r===null?null:i??r,available:r!==null,costWhenOff:e.isCamera?Qs:$s}}function tc(e,t){return!e.available||e.on===null?null:{deviceId:t,muted:e.on}}e();function nc(e){if(typeof e!=`object`||!e)return null;let t={...e}.mutedDeviceIds;return Array.isArray(t)?t.filter(e=>typeof e==`number`):null}function rc({deviceId:e,isCamera:t}){let{t:n}=Z(),o=c(),s=Number.isFinite(e),[l,u]=r(null),[f,p]=r(null),m=ec({mutedDeviceIds:nc(Qn({},{enabled:s}).data),deviceId:e,isCamera:t,pendingOn:f}),h=n(m.costWhenOff.i18nKey,m.costWhenOff.text),g=Jn({onError:t=>{console.error(`[DeviceNotificationMute] mute write failed — reverting`,{tags:{deviceId:e},meta:{error:t instanceof Error?t.message:String(t)}}),p(null),u(t instanceof Error?t.message:String(t)),o.invalidateQueries({queryKey:[[`notificationRules`,`listDeviceMutes`]]})},onSuccess:()=>{u(null),p(null),o.invalidateQueries({queryKey:[[`notificationRules`]]})}}),_=i(()=>{let t=tc(m,e);t!==null&&(p(!t.muted),g.mutate(t))},[e,g,m]),v=m.on===null,y=m.on===!1,b=y?ze:D;return a(`div`,{className:`rounded-lg border border-border bg-surface overflow-hidden`,children:[a(`div`,{className:`border-b border-border px-4 py-2 flex items-center justify-between gap-2`,children:[d(`h2`,{className:`text-xs font-semibold text-foreground uppercase tracking-wider`,children:n(`device.deviceNotificationMute.notifications`,`Notifications`)}),y&&d(`span`,{className:`rounded bg-warning/20 px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-wide text-warning`,children:n(`common.muted`)})]}),a(`div`,{className:`px-4 py-3 flex items-start gap-3`,children:[a(`button`,{type:`button`,role:`switch`,"aria-label":m.label,"aria-checked":m.on===!0,disabled:!m.available||g.isPending,onClick:_,title:v?n(`device.deviceNotificationMute.notificationMuteStateUnknownThe`,`Notification mute — state unknown; the notification centre did not answer.`):y?n(`device.deviceNotificationMute.muted`,`Muted. {{costWhenOff}}`,{costWhenOff:h}):n(`device.deviceNotificationMute.notifyingMutingIt`,`Notifying. Muting it: {{costWhenOff}}`,{costWhenOff:h}),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 ${l===null?v?`border-dashed border-border text-foreground-subtle/50`:y?`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:[d(b,{className:`h-3.5 w-3.5`}),d(`span`,{children:v?n(`device.deviceNotificationMute.unknown`,`Unknown`):y?n(`device.deviceNotificationMute.muted2`,`Muted`):n(`device.deviceNotificationMute.notifying`,`Notifying`)})]}),d(`p`,{className:`flex-1 text-[11px] leading-relaxed text-foreground-subtle`,children:l===null?v?n(`device.deviceNotificationMute.theNotificationCentreDidNot`,`The notification centre did not answer, so this device’s mute state is unknown.`):h:n(`device.deviceNotificationMute.writeFailed`,`Write failed: {{failure}}`,{failure:l})})]})]})}function ic(e,t){return{switchId:e,label:Ae[e].label,detail:t===void 0||t.length===0?null:t}}function ac(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 oc(e){let t=ac(e),n=new Set(e.sourceStillLive),r=e.sourceStillLive.map(e=>ic(e,t.get(e)?.detail)),i=[...t.values()].filter(e=>e.outcome===`not-offered`&&!n.has(e.switchId)).map(e=>ic(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}}e();function sc(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 cc({deviceId:e,deviceName:t}){let{t:i}=Z(),o=Qe(),[s,c]=r(null),l=Zn({isCamera:!0,projection:`slim`}),u=In(),f=l.data!==void 0,p=n(()=>l.data===void 0?[]:sc(l.data,e),[l.data,e]),m=p.find(e=>e.id===s)??null,h=u.data===void 0?null:oc(u.data),g=u.error===null?null:u.error.message,_=async()=>{m===null||m.id===e||await o({title:i(`deviceMigrate.confirmTitle`,`Replace “{{source}}” with “{{target}}”?`,{source:t,target:m.name}),message:i(`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:i(`deviceMigrate.confirmAction`,`Migrate`),variant:`danger`})&&u.mutate({sourceId:e,targetId:m.id})};return a(`div`,{className:`rounded-lg border border-border bg-surface px-4 py-3`,children:[a(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[a(`div`,{className:`min-w-0`,children:[d(`h2`,{className:`text-xs font-semibold uppercase tracking-wider text-foreground`,children:i(`deviceMigrate.title`,`Migrate to…`)}),d(`p`,{className:`mt-0.5 text-[11px] text-foreground-subtle`,children:i(`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})})]}),a(`div`,{className:`flex shrink-0 items-center gap-2`,children:[a(`select`,{"aria-label":i(`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||u.isPending,value:s===null?``:String(s),onChange:e=>{let t=e.target.value;c(t===``?null:Number(t))},children:[d(`option`,{value:``,children:f?i(`deviceMigrate.pickerPlaceholder`,`Select a camera…`):i(`deviceMigrate.pickerPending`,`Reading the fleet…`)}),p.map(e=>a(`option`,{value:String(e.id),children:[e.name,` (#`,e.id,`)`]},e.id))]}),a(`button`,{type:`button`,disabled:m===null||u.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:[d(Fe,{className:`h-3 w-3`}),u.isPending?i(`deviceMigrate.running`,`Migrating…`):i(`deviceMigrate.action`,`Migrate`)]})]})]}),f&&p.length===0&&d(`p`,{className:`mt-2 text-[11px] text-foreground-subtle`,children:i(`deviceMigrate.noTargets`,`No other camera is adopted, so there is nothing to migrate to.`)}),g!==null&&d(`p`,{className:`mt-2 text-[11px] text-danger`,children:i(`deviceMigrate.failed`,`Migration failed: {{error}}`,{error:g})}),h!==null&&d(lc,{report:h})]})}function lc({report:e}){let{t}=Z(),n=e.verdict===`quiet`;return a(`div`,{className:`mt-3 space-y-2 border-t border-border pt-3`,children:[d(`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?a(`div`,{className:`flex items-start gap-2 rounded-md border border-success/30 bg-success/5 px-3 py-2`,children:[d(z,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-success`}),d(`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.`)})]}):a(`div`,{className:`rounded-md border border-warning/40 bg-warning/5 px-3 py-2`,children:[a(`div`,{className:`flex items-start gap-2`,children:[d(me,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-warning`}),d(`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.`)})]}),d(`ul`,{className:`mt-2 space-y-1 pl-5`,children:e.stillLive.map(e=>a(`li`,{className:`text-[11px] text-foreground`,children:[d(`span`,{className:`font-medium`,children:e.label}),e.detail!==null&&a(`span`,{className:`text-foreground-subtle`,children:[` — `,e.detail]})]},e.switchId))})]}),e.neverOffered.length>0&&a(`div`,{className:`rounded-md border border-border px-3 py-2`,children:[a(`div`,{className:`flex items-start gap-2`,children:[d(He,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),d(`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.`)})]}),d(`ul`,{className:`mt-2 space-y-1 pl-5`,children:e.neverOffered.map(e=>d(`li`,{className:`text-[11px] text-foreground-subtle`,children:e.label},e.switchId))})]})]})}e();function uc({deviceId:e}){let{t}=Z(),[n,i]=r(null),o=Wt({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 a(`div`,{className:`rounded-lg border border-border bg-surface px-4 py-3`,children:[a(`div`,{className:`flex items-center justify-between gap-3`,children:[a(`div`,{children:[d(`h2`,{className:`text-xs font-semibold uppercase tracking-wider text-foreground`,children:t(`device.resyncButton.reSync`,`Re-sync`)}),d(`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.`)})]}),a(`button`,{type:`button`,disabled:o.isPending,onClick:()=>{i(null),o.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:[d(ie,{className:`h-3 w-3 ${o.isPending?`animate-spin`:``}`}),o.isPending?t(`device.resyncButton.reSyncing`,`Re-syncing…`):t(`device.resyncButton.reSync`,`Re-sync`)]})]}),n!==null&&d(`p`,{className:`mt-2 text-[11px] text-foreground-subtle`,children:n})]})}function dc(e){return e<1e3?`${e.toFixed(0)} kbps`:`${(e/1e3).toFixed(1)} Mbps`}function fc({device:e}){let{t}=Z(),n=Or(),r=typeof e.id==`number`?e.id:null,i=String(e.type??``),o=i===G.Camera,s=i===G.Hub,c=e.features??[],l=c.includes(_e.Resyncable),{data:u}=Gn({deviceId:r??0},{enabled:r!==null&&o,refetchInterval:5e3}),f=u?.streams??{},p=Object.entries(f),m=c.includes(_e.DoorbellButton),h=Cn(m?{deviceId:r??void 0,historyLimit:10}:void 0),g=h.latest?Date.now()-h.latest.timestamp<3e4:!1;return a(`div`,{className:`space-y-5`,children:[s&&r!==null&&d(or,{deviceId:r,onOpenChild:e=>n(`/devices/${e}`)}),l&&r!==null&&d(uc,{deviceId:r}),o&&r!==null&&d(cc,{deviceId:r,deviceName:String(e.name??``)}),r!==null&&d(rc,{deviceId:r,isCamera:o}),o&&r!==null&&d(pn,{widgetId:`pipeline-orchestrator/pipeline-quick-stats`,host:`device-tab`,deviceId:r}),m&&d(ln,{history:h.history,latestIsFresh:g}),o&&r!==null&&d(pn,{widgetId:`stream-broker/stream-broker-panel`,host:`device-tab`,deviceId:r}),o&&p.length>0&&a(`div`,{className:`@container rounded-lg border border-border bg-surface overflow-hidden`,style:{containerType:`inline-size`},children:[d(`div`,{className:`border-b border-border px-4 py-2`,children:d(`h2`,{className:`text-xs font-semibold text-foreground uppercase tracking-wider`,children:t(`device.overviewTab.streamNetwork`,`Stream Network`)})}),d(`div`,{className:`divide-y divide-border`,children:p.map(([e,n])=>a(`div`,{className:`px-4 py-2.5`,children:[a(`div`,{className:`flex items-center gap-2 mb-2`,children:[d(oe,{className:`h-3 w-3 text-foreground-subtle`}),d(`span`,{className:`text-[11px] font-medium text-foreground`,children:e})]}),a(`div`,{className:`grid grid-cols-2 @[640px]:grid-cols-4 gap-2`,children:[d(pc,{label:t(`device.overviewTab.nominal`,`Nominal`),value:dc(n.nominalBitrateKbps??0)}),d(pc,{label:t(`device.overviewTab.observed`,`Observed`),value:dc(n.observedBitrateKbps??0)}),d(pc,{label:t(`device.overviewTab.peak`,`Peak`),value:dc(n.peakBitrateKbps??0)}),d(pc,{label:t(`device.overviewTab.packetLoss`,`Packet Loss`),value:`${(n.packetLossPercent??0).toFixed(2)}%`,warning:(n.packetLossPercent??0)>1})]})]},e))})]}),d(jr,{}),r!==null&&d(pr,{deviceId:r})]})}function pc({label:e,value:t,warning:n}){return a(`div`,{children:[d(`p`,{className:`text-[10px] text-foreground-subtle`,children:e}),d(`p`,{className:`text-xs font-medium ${n?`text-warning`:`text-foreground`}`,children:t})]})}var mc=`history`,hc=[{id:`overview`,labelKey:`helpers.structuralTabs.overview`,cameraOnly:!1,adminOnly:!1},{id:`config`,labelKey:`helpers.structuralTabs.config`,cameraOnly:!1,adminOnly:!1},{id:Dr,labelKey:`helpers.structuralTabs.customize`,cameraOnly:!1,adminOnly:!0},{id:mc,labelKey:`helpers.structuralTabs.history`,cameraOnly:!1,adminOnly:!1},{id:`detection-pipeline`,labelKey:`helpers.structuralTabs.detectionPipeline`,cameraOnly:!0,adminOnly:!1},{id:`bindings`,labelKey:`helpers.structuralTabs.bindings`,cameraOnly:!0,adminOnly:!1}],gc=new Set([G.Hub,G.Container]);function _c(e,t){let n=e===G.Camera,r=e===void 0||!gc.has(e);return hc.filter(e=>(n||!e.cameraOnly)&&(t||!e.adminOnly)&&(r||e.id!==`history`)).map(({id:e,labelKey:t})=>({id:e,label:X.t(t)}))}function vc({provider:e,integrationId:t,name:n}){let r=Or(),i=t===null?`/integrations`:`/integrations/${t}`,a=n===null?`Open integrations`:`Open integration ${n}`;return d(`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:d(_r,{type:e,size:`lg`})})}e();var yc=[{id:`logs`,icon:B,labelKey:`common.logs`},{id:`repl`,icon:Ve,labelKey:`deviceDetail.repl`},{id:`events`,icon:T,labelKey:`common.events`},{id:`state`,icon:S,labelKey:`common.state`}];function bc(){let{t:e}=Z(),t=ue(),o=wr(),u=Number(o.deviceId),f=Number.isFinite(u),p=Or(),m=c(),_=Qe(),v=R(),{user:b}=yr(),x=b?.isAdmin===!0,[S,C]=br(),w=S.get(`tab`)??`overview`,T=S.get(`sub`),[E,D]=r(`logs`),O=`device-detail.left-col-width-px`,[k,A]=r(()=>{if(typeof window>`u`)return null;let e=window.localStorage.getItem(O),t=e?Number(e):NaN;return Number.isFinite(t)&&t>0?t:null}),j=l(k);j.current=k;function te(e){e.preventDefault();let t=e.clientX,n=e.currentTarget.previousElementSibling?.getBoundingClientRect().width??k??0,r=Math.max(330,Math.floor(window.innerWidth*.7)),i=e=>{A(Math.max(280,Math.min(r,n+(e.clientX-t))))},a=()=>{document.removeEventListener(`mousemove`,i),document.removeEventListener(`mouseup`,a);let e=j.current;if(e!==null)try{window.localStorage.setItem(O,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:M,isLoading:ne,isError:re}=Yn({deviceId:u},{enabled:f,refetchInterval:5e3,retry:1}),{data:N}=Tn({deviceId:u},{enabled:f}),ae=n(()=>{let e=N?.settings?.sections??[],t=N?.live?.sections??[],n=[...e,...t],r=new Set;for(let e of n)e.location===`top-tab`&&e.tab&&r.add(e.tab===`zones`?`detection-pipeline`:e.tab);return n.some(mr)&&r.add(dr),[...r].map(e=>e===`export`?{id:e,label:xr,isAddonContrib:!0}:{id:e,label:Me[e]?.label??e,isAddonContrib:!0})},[N]),P=M,F=String(P?.name??o.deviceId??`Device`),oe=P?.online===!0,se=oe?`online`:`offline`,I=String(P?.addonId??`rtsp`),L=P?.features??[],z=P?.type,B=z===G.Camera,{data:le}=kr(f?u:0),fe=z===G.Container,me=n(()=>(le??[]).map(e=>({id:e.id,stableId:e.stableId,type:e.type,...e.sourceInfo?{sourceInfo:{id:e.sourceInfo.id}}:{}})),[le]),V=n(()=>fe?ct(me,typeof P?.linkDeviceId==`number`?P.linkDeviceId:null,typeof P?.primaryChildEntityId==`string`?P.primaryChildEntityId:null)?.id??null:null,[fe,me,P?.linkDeviceId,P?.primaryChildEntityId]),{data:H}=Tn({deviceId:V??0},{enabled:V!==null}),he=n(()=>{if(V===null)return[];let e=H?.settings?.sections??[],t=H?.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:Me[e]?.label??e,isAddonContrib:!0,childDeviceId:V}))},[V,H]),ge=n(()=>fa({sections:[...N?.settings?.sections??[],...N?.live?.sections??[]],deviceId:u,...V===null?{}:{child:{sections:[...H?.settings?.sections??[],...H?.live?.sections??[]],deviceId:V}}}),[N,H,u,V]),U=typeof P?.parentDeviceId==`number`?P.parentDeviceId:null,{data:ve}=Yn({deviceId:U??0},{enabled:U!==null}),W=$n(),ye=P?.disabled!==!0,be=n(()=>{let e=N?.settings?.sections??[],t=N?.live?.sections??[];return hr([...e,...t],z,x,N!==void 0)},[N,z,x]),xe=n(()=>{let e=new Set,t=[];for(let n of[..._c(z,x),...ae,...he])n.id===`config`&&!be||e.has(n.id)||(e.add(n.id),t.push(n));return t},[z,x,ae,he,be]),Se=n(()=>ss(xe,w),[xe,w]),Ce=i(e=>{C(t=>{let n=new URLSearchParams(t);e===`overview`?n.delete(`tab`):n.set(`tab`,e),n.delete(`sub`);for(let e of mi)n.delete(e);return n},{replace:!0})},[C]),we=i(e=>{C(t=>{let n=new URLSearchParams(t);return n.set(`sub`,e),n},{replace:!0})},[C]),Te=(le??[]).length>0,Ee=n(()=>yc.filter(({featureGate:e})=>!e||L.includes(e)),[L]),{data:De}=rn(void 0),Oe=n(()=>P?jn(P,De):null,[P,De]),K=Oe?.kind===`resolved`?Oe.integration:null,ke=K===null?Oe?.kind===`unknown`?e(`deviceDetail.loadingIntegration`):Oe?.kind===`orphan`?e(`deviceDetail.missingIntegration`):e(`deviceDetail.noIntegration`):K.name,Ae=K!==null&&K.addonId===I?K.name:I,je=$t({onSuccess:()=>{m.invalidateQueries({queryKey:[[`deviceManager`]]}),p(K?.id?`/integrations/${K.id}`:`/integrations`)}}),Ne=We({onSuccess:()=>{m.invalidateQueries({queryKey:[[`deviceManager`]]})}}),Pe=pt({onSuccess:()=>{m.invalidateQueries({queryKey:[[`deviceManager`]]})}}),Fe=Lt(),Ie=$e({onSuccess:()=>{m.invalidateQueries({queryKey:[[`deviceManager`]]})}}),Le=L.includes(_e.Rebootable),Re=L.includes(_e.BatteryOperated),ze=dt(v.trpcClient,Re&&f?u:null),Be=at(v.trpcClient,f?u:null),Ve=ce(v.trpcClient,f?u:null,e=>e.runningState),He=Ve===void 0||Ve.running===null?null:Ve.running,Ue=dn(z??`unknown`,t).icon,[Ge,Ke]=r(!1),qe=async()=>{if(!Ge){Ke(!0);try{let e=F.replace(/[^a-zA-Z0-9_.-]+/g,`_`),t=new Date().toISOString().replace(/[:.]/g,`-`);await ki(`${ee}/${String(u)}.jpg?force=1`,`${e}-${t}.jpg`)}finally{Ke(!1)}}},Je=Ne.isPending||Pe.isPending,{data:Ye}=lt({deviceId:u},{enabled:f&&B,refetchInterval:1e4}),Xe=Ye?.agentNodeId??null,Ze=typeof Xe==`string`&&Xe.length>0&&!Xe.startsWith(`addon:`)?Xe:void 0,{data:tt}=nr({deviceId:u,...Ze?{nodeId:Ze}:{}},{enabled:f&&B,refetchInterval:3e3,retry:!1}),{data:q}=cr({deviceId:u},{enabled:f&&B,refetchInterval:3e3,retry:!1}),nt=q?.level?.dbfs??null;function rt(){if(!f)return null;switch(Se){case`overview`:return d(fc,{device:P??{}});case`config`:return d(fs,{deviceId:u,activeSubTab:T,onSubTabChange:we,deviceType:z,isAdmin:x});case`detection-pipeline`:return d(Xs,{deviceId:u,activeSubTab:T,onSubTabChange:we});case`bindings`:return d(cs,{deviceId:u});case mc:return d(Mn,{deviceId:u,onNavigate:e=>p(e)});case Dr:return d(rs,{deviceId:u});default:{let e=Se,t=ae.some(t=>t.id===e),n=he.find(t=>t.id===e);if(!t&&n===void 0)return null;let r=n?.childDeviceId??u;if(e===`export`)return d(fr,{deviceId:u,sectionFilter:mr,activeSubTab:T,onSubTabChange:we});let i=d(fr,{deviceId:r,sectionFilter:t=>t.location===`top-tab`&&(t.tab===e||e===`detection-pipeline`&&t.tab===`zones`),flattenSubTabs:e===`detection-pipeline`,activeSubTab:T,onSubTabChange:we});return n!==void 0&&r!==u?d(it,{deviceId:r,children:i}):i}}}return f?ne?a(`div`,{className:`flex flex-col h-full`,children:[a(`div`,{className:`border-b border-border bg-surface px-6 py-4`,children:[d(`div`,{className:`h-4 w-48 rounded bg-surface-hover animate-pulse mb-3`}),d(`div`,{className:`h-8 w-64 rounded bg-surface-hover animate-pulse`})]}),d(`div`,{className:`flex-1 p-6`,children:d(`div`,{className:`h-40 rounded-lg border border-border bg-surface animate-pulse`})})]}):re||!M?a(`div`,{className:`flex flex-col items-center justify-center h-full gap-3 text-foreground-subtle`,children:[d(`p`,{className:`text-lg font-semibold text-foreground`,children:e(`deviceDetail.deviceNotFound`,`Device not found`)}),d(`p`,{className:`text-xs`,children:d(Mr,{i18nKey:`deviceDetail.noDeviceWithId`,values:{id:u},components:{code:d(`code`,{className:`font-mono bg-surface px-1.5 py-0.5 rounded text-[11px]`})}})}),d(`button`,{onClick:()=>p(`/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:e(`deviceDetail.backToIntegrations`,`Back to Integrations`)})]}):a(`div`,{className:`absolute inset-0 flex flex-col overflow-clip`,children:[a(`div`,{className:`border-b border-border bg-surface px-6 py-3 flex-shrink-0`,children:[d(`div`,{className:`mb-2`,children:d(et,{items:[{label:e(`deviceDetail.integrations`,`Integrations`),onClick:()=>p(`/integrations`)},K===null?{label:ke}:{label:ke,onClick:()=>p(`/integrations/${K.id}`)},{label:F}]})}),a(`div`,{className:`flex items-center gap-2 sm:gap-3`,children:[K!==null&&d(vc,{provider:K.addonId,integrationId:K.id,name:K.name}),d(An,{running:He,children:d(Ue,{className:`h-5 w-5 text-foreground-subtle shrink-0`,"aria-hidden":!0})}),a(`div`,{className:`min-w-0 flex-1`,children:[a(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[d(`h1`,{className:`text-sm sm:text-base font-semibold text-foreground truncate`,children:F}),d(Xn,{status:se}),Re&&d(En,{status:ze,variant:`full`}),d(Dt,{status:Be})]}),U!==null&&ve&&a(`button`,{type:`button`,onClick:()=>p(`/devices/${U}`),className:`text-[10px] text-foreground-subtle hover:text-primary transition-colors mt-0.5 inline-flex items-center gap-1`,title:e(`deviceDetail.openParentDevice`,`Open parent device {{name}}`,{name:ve.name}),children:[d(`span`,{children:`↑`}),d(`span`,{className:`truncate`,children:String(ve.name??`Device #${U}`)})]}),d(`div`,{className:`hidden md:flex items-center gap-3 mt-0.5 text-[10px] text-foreground-subtle`,children:L.length>0&&d(Cr,{capabilities:L})})]}),tt&&d(`div`,{className:`hidden lg:flex`,children:d(xc,{metrics:tt,dbfs:nt})}),a(`div`,{className:`flex items-center gap-1 shrink-0`,children:[a(`button`,{onClick:async()=>{ye?await _({title:e(`deviceDetail.disable`,`Disable "{{name}}"?`,{name:F}),message:e(`deviceDetail.theDeviceWillStopProcessing`,`The device will stop processing streams and events. You can re-enable it later.`),confirmLabel:e(`common.disable`,`Disable`),variant:`danger`})&&Pe.mutate({deviceId:u}):Ne.mutate({deviceId:u})},disabled:Je,title:ye?e(`deviceDetail.disableDevice`,`Disable device`):e(`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 ${ye?`border-success/30 text-success hover:bg-success/10`:`border-border text-foreground-subtle/50 hover:text-foreground hover:bg-surface-hover`}`,children:[d(g,{className:`h-3.5 w-3.5`}),d(`span`,{className:`hidden sm:inline`,children:Je?e(`deviceDetail.updating`,`Updating…`):ye?e(`deviceDetail.enabled`,`Enabled`):e(`deviceDetail.disabled`,`Disabled`)})]}),d(`div`,{className:`hidden sm:block h-5 w-px bg-border mx-1`}),B&&a(s,{children:[d(Ii,{deviceId:u}),d(`div`,{className:`hidden sm:block h-5 w-px bg-border mx-1`})]}),d(Ri,{deviceId:u}),d(tn,{triggerClassName:`ml-1`,items:[{id:`snapshot`,label:e(`deviceDetail.takeSnapshot`,`Take snapshot`),description:e(`deviceDetail.fetchAFreshFrameAnd`,`Fetch a fresh frame and download it.`),icon:h,disabled:Ge,onClick:()=>{qe()}},{id:`reboot`,label:e(`deviceDetail.rebootDevice`,`Reboot device`),description:e(`deviceDetail.cameraGoesOfflineFor30`,`Camera goes offline for ~30 seconds.`),icon:pe,hidden:!Le,disabled:Fe.isPending,danger:!0,onClick:async()=>{await _({title:e(`deviceDetail.reboot`,`Reboot "{{name}}"?`,{name:F}),message:e(`deviceDetail.theCameraWillGoOffline`,`The camera will go offline for around 30 seconds while the firmware reboots.`),confirmLabel:e(`deviceDetail.reboot2`,`Reboot`),variant:`danger`})&&Fe.mutate({deviceId:u})}},{id:`restart-addon`,label:e(`deviceDetail.restartAddon`,`Restart addon`),description:e(`deviceDetail.bouncesEveryDeviceServedBy`,`Bounces every device served by {{servingAddonLabel}}.`,{servingAddonLabel:Ae}),icon:ie,disabled:Ie.isPending,danger:!0,onClick:async()=>{await _({title:e(`deviceDetail.restart`,`Restart "{{servingAddonLabel}}"?`,{servingAddonLabel:Ae}),message:e(`deviceDetail.restartingTheAddonWillBriefly`,`Restarting the addon will briefly disconnect every device served by it (not just "{{name}}"). Streams will reconnect automatically.`,{name:F}),confirmLabel:e(`deviceDetail.restart2`,`Restart`),variant:`danger`})&&Ie.mutate({addonId:I})}},{id:`delete`,label:e(`deviceDetail.deleteDevice`,`Delete device`),description:e(`deviceDetail.removeTheDeviceAndAll`,`Remove the device and all its settings.`),icon:y,separatorBefore:!0,disabled:je.isPending,danger:!0,onClick:async()=>{await _({title:e(`deviceDetail.delete`,`Delete "{{name}}"?`,{name:F}),message:e(`deviceDetail.thisWillRemoveTheDevice`,`This will remove the device and all its settings. This action cannot be undone.`),confirmLabel:e(`common.delete`,`Delete`),variant:`danger`})&&je.mutate({deviceId:u})}}]})]})]})]}),d(it,{deviceId:u,device:P??void 0,children:d(sr,{children:d(xn,{children:d(de,{children:d(un,{children:a(`main`,{className:W?`flex-1 overflow-y-auto flex flex-col`:`flex-1 min-h-0 overflow-hidden flex flex-row`,children:[a(`div`,{className:W?`flex flex-col bg-surface`:`${k===null?`w-1/2 lg:w-1/3`:``} flex-shrink-0 flex flex-col bg-surface min-h-0 overflow-y-auto`,style:!W&&k!==null?{width:`${String(k)}px`}:void 0,children:[d(`div`,{className:B?`flex-shrink-0 border-b border-border-subtle bg-black`:W?`flex-shrink-0 border-b border-border-subtle bg-surface`:`shrink-0 border-b border-border-subtle bg-surface`,children:B?d(Sa,{deviceId:u,intercomAvailable:L.includes(_e.TwoWayAudio)}):a(`div`,{children:[d(la,{deviceId:u,deviceName:F,deviceType:z??`unknown`,provider:I,isOnline:oe,features:L}),d(ua,{deviceId:u,widgets:ge})]})}),B&&ge.length>0&&d(`div`,{className:`flex-shrink-0 border-b border-border-subtle bg-surface pt-3 sm:pt-4`,children:d(ua,{deviceId:u,widgets:ge})}),a(`div`,{className:W?`flex flex-col border-b border-border`:`flex-1 min-h-64 flex flex-col overflow-hidden`,children:[d(`div`,{className:`flex-shrink-0 border-b border-border-subtle px-2 py-1.5`,children:d(`div`,{className:`flex gap-1 overflow-x-auto -mx-1 px-1 pb-0.5`,children:Ee.map(({id:t,labelKey:n,icon:r})=>{let i=E===t;return a(`button`,{onClick:()=>D(t),title:e(n),className:`flex items-center gap-1 rounded px-2 py-1 text-[10px] font-medium transition-colors flex-shrink-0 ${i?`bg-primary/15 text-primary`:`text-foreground-subtle hover:text-foreground hover:bg-surface-hover`}`,children:[d(r,{className:`h-3 w-3`}),e(n)]},t)})})}),a(`div`,{className:W?`h-72 overflow-hidden`:`flex-1 min-h-0 overflow-hidden`,children:[E===`logs`&&d(Ca,{deviceId:u,containerDeviceId:z===`container`?u:void 0}),E===`repl`&&d(wa,{deviceId:u}),E===`events`&&d(Ta,{deviceId:u}),E===`state`&&d(Ea,{deviceId:u})]})]})]}),!W&&d(`div`,{role:`separator`,"aria-orientation":`vertical`,title:e(`deviceDetail.dragToResize`,`Drag to resize`),onMouseDown:te,className:`flex-shrink-0 w-1 cursor-col-resize bg-border hover:bg-primary/40 transition-colors group relative z-10`,children:d(`span`,{className:`absolute inset-y-0 -left-1 -right-1`})}),a(`div`,{className:W?`flex flex-col`:`flex-1 min-w-0 min-h-0 flex flex-col overflow-hidden`,children:[d(`div`,{className:`flex-shrink-0 border-b border-border bg-surface px-4`,children:d(`div`,{className:`flex flex-nowrap overflow-x-auto md:flex-wrap md:overflow-x-visible items-center gap-0`,children:xe.map(e=>{let t=Se===e.id;return a(`button`,{onClick:()=>Ce(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&&d(`span`,{className:`absolute bottom-0 left-0 right-0 h-0.5 rounded-full bg-primary`})]},e.id)})})}),a(`div`,{className:W?`p-3 flex flex-col gap-3`:`flex-1 min-h-0 overflow-y-auto p-4 flex flex-col gap-3`,children:[Se===`overview`&&Te&&d(zi,{parentDeviceId:u}),rt()]})]})]})})})})})})]}):a(`div`,{className:`flex flex-col items-center justify-center h-full gap-3 text-foreground-subtle`,children:[d(`p`,{className:`text-lg font-semibold text-foreground`,children:e(`deviceDetail.invalidDeviceId`,`Invalid device id`)}),d(`p`,{className:`text-xs`,children:d(Mr,{i18nKey:`deviceDetail.invalidSegment`,values:{segment:o.deviceId},components:{code:d(`code`,{className:`font-mono bg-surface px-1.5 py-0.5 rounded text-[11px]`})}})}),d(`button`,{onClick:()=>p(`/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:e(`deviceDetail.backToIntegrations`,`Back to Integrations`)})]})}function xc({metrics:e,dbfs:t}){let n=ue(),{t:r}=Z(),i=Vn(e.phase??`idle`,n);return a(`div`,{className:`flex items-center gap-3 flex-shrink-0`,children:[a(`div`,{className:`flex items-center gap-1.5`,children:[d(`span`,{className:`h-1.5 w-1.5 rounded-full ${i.dotClass}`}),d(`span`,{className:`text-[10px] font-medium ${i.textColor}`,children:i.label})]}),d(`div`,{className:`h-3 w-px bg-border`}),a(`div`,{className:`flex items-center gap-1 text-[10px] text-foreground-subtle`,children:[d(fe,{className:`h-3 w-3`}),d(`span`,{className:`text-foreground tabular-nums`,children:(e.actualFps??0).toFixed(1)}),d(`span`,{children:r(`common.fpsWord`)})]}),a(`div`,{className:`flex items-center gap-1 text-[10px] text-foreground-subtle`,children:[d(M,{className:`h-3 w-3`}),d(`span`,{className:`text-foreground tabular-nums`,children:(e.avgInferenceTimeMs??0).toFixed(0)}),d(`span`,{children:`ms`})]}),a(`div`,{className:`flex items-center gap-1 text-[10px] text-foreground-subtle`,title:r(`deviceDetail.currentAudioLevelDbfs`,`Current audio level (dBFS)`),children:[d(k,{className:`h-3 w-3`}),d(`span`,{className:`text-foreground tabular-nums`,children:t==null?`—`:t.toFixed(0)}),d(`span`,{children:`dB`})]}),(e.queueDepth??0)>0&&a(`span`,{className:`text-[10px] text-warning tabular-nums`,children:[`q:`,e.queueDepth]})]})}export{bc as DeviceDetailPage};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{$ as e,G as t,J as n,S as r,b as i,i as a,x as o}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEHpkaJP.js";import{Ci as s,It as c,bn as l,dt as u,hn as d,or as f,ot as p,sa as m,yr as h}from"./player-overlays-DDFLUcm1.js";import{Oi as g,ar as _}from"./client-BnEPcD6s.js";import{A as v,Br as y,C as b,Cr as x,D as S,E as C,Er as w,Fa as T,Hl as E,Hr as D,Ia as O,M as k,N as A,O as j,P as M,S as ee,Tr as te,Vr as ne,Yr as N,_ as re,b as P,bn as F,d as ie,dn as ae,dr as oe,f as se,h as ce,hr as le,j as ue,k as de,ld as fe,lr as pe,m as me,mr as he,pr as ge,so as I,u as _e,un as ve,ur as ye,v as be,vn as L,w as xe,wr as R,x as z,xn as B,xr as Se}from"./src-CWZRb0ia.js";import{t as V}from"./useTranslation-D3Is_4B6.js";import{hr as Ce}from"./index-CgxpaFwe.js";import{t as we}from"./AdminPage-92KQDOBy.js";e();function H(e,t){return e.scope===``?e.displayName:`${e.displayName} · ${t?.(e)??e.scope}`}function Te(e,t,n){let r=[];for(let{device:t,series:i}of e)for(let e of i){let i={subject:{kind:`device`,deviceId:t.id},key:e.key,scope:e.scope};r.push({id:z(i),ref:i,info:e,subjectName:t.name,location:t.location??``,nodeId:``,metric:H(e,n)})}for(let{node:e,series:i}of t)for(let t of i){let i={subject:{kind:`node`,nodeId:e.id},key:t.key,scope:t.scope};r.push({id:z(i),ref:i,info:t,subjectName:e.name,location:``,nodeId:e.id,metric:H(t,n)})}return r}function Ee(e){return[e.subjectName,e.location,e.metric,e.info.key,e.info.unit??``,e.nodeId].join(` `)}var De=[`energy`,`temperatures`,`nodes`,`storage`],Oe=new Set([`cap:temperature-sensor.celsius`,`cap:climate-control.currentTemp`]),U=[`addon:metrics-native/node-cpu-percent`,`addon:metrics-native/node-memory-percent`],ke=`addon:storage-orchestrator/location-used-percent`;function Ae(e,t){let n=(e,n)=>{let r=t.filter(e);return P((n?[...r].sort(n):r).map(e=>e.ref))};switch(e){case`energy`:return n(e=>e.ref.subject.kind===`device`&&e.info.key===`derived:energy.kwh`);case`temperatures`:return n(e=>e.ref.subject.kind===`device`&&Oe.has(e.info.key)&&e.info.scope===``,(e,t)=>e.location.localeCompare(t.location)||e.subjectName.localeCompare(t.subjectName));case`nodes`:return n(e=>e.ref.subject.kind===`node`&&U.includes(e.info.key)&&e.info.scope===``,(e,t)=>U.indexOf(e.info.key)-U.indexOf(t.info.key)||e.subjectName.localeCompare(t.subjectName));case`storage`:return n(e=>e.ref.subject.kind===`node`&&e.info.key===ke)}}function je(e,t){let n=new Map(t.map(e=>[e.id,e])),r=[],i=[],a=[],o=[];for(let t of P(e)){let e=n.get(z(t));if(e===void 0){o.push(t);continue}e.info.key===`derived:energy.kwh`?a.push(e):e.info.kind===`boolean`||e.info.kind===`enum`?i.push(e):r.push(e)}return{lines:r,states:i,energy:a,missing:o}}function W(e){return e.subject.kind===`device`?{deviceId:e.subject.deviceId,key:e.key,scope:e.scope}:{forNodeId:e.subject.nodeId,key:e.key,scope:e.scope}}var G=`history-page`;function K(e){return`${e.subjectName} · ${e.metric}`}function Me({part:e,window:n}){let{t:i}=V(),a=m(),c=t(()=>[...e.lines,...e.states,...e.energy],[e]),l=me(t(()=>c.map(e=>W(e.ref)),[c]),n,!1),u=e=>l.status===`ok`?l.data.current.get(se(W(e.ref))):void 0,d=e=>{let t=u(e);return t?.ok?t.result:void 0};if(c.length===0)return o(R,{icon:s,title:i(`history.page.emptyTitle`,`Pick series to compare`),description:i(`history.page.emptyHint`,`Choose up to 24 series on the left, or start from a panel above.`)});if(l.status===`error`)return o(x,{title:i(`history.page.readFailed`,`History could not be read`),message:l.error});let f=l.status===`pending`,p=c.map(e=>({c:e,e:u(e)})).filter(e=>e.e?.ok===!1),h=e.lines.map((e,t)=>{let r=d(e),i=S(e.info,r,n.from);return{id:e.id,label:K(e),unit:e.info.unit,colorIndex:t,points:i.points,gapMs:i.gapMs,interpolation:i.held&&r?.resolution===`raw`?`step`:`linear`}}),g=e.states.map((e,t)=>{let r=j(e.info,d(e),n.from,n.to),i=xe(e.info.key,a);return{id:e.id,label:K(e),kind:e.info.kind===`boolean`?`boolean`:`enum`,colorIndex:e.info.kind===`boolean`?t:0,states:r.states,segments:r.segments,totals:r.totals,stateLabel:e.info.kind===`boolean`?e=>e===`true`?i.on:i.off:void 0}}),_=e.energy.map(e=>({c:e,...C(d(e))})),v=_[0]?.bucketMs??36e5,y=[...new Set(_.flatMap(e=>e.buckets.map(e=>e.t)))].sort((e,t)=>e-t).map(e=>({t:e,values:_.map(t=>t.buckets.find(t=>t.t===e)?.values[0]??null)}));return r(`div`,{className:`space-y-5 min-w-0`,children:[p.length>0&&o(x,{title:i(`history.page.someFailed`,`Some series could not be read`),message:p.map(e=>`${K(e.c)}: ${e.e.error}`).join(` · `)}),h.length>0&&o(M,{title:i(`history.page.lines`,`Measurements`),series:h,range:n,height:260,syncKey:G,pending:f}),_.length>0&&o(Se,{title:i(`history.page.energy`,`Energy`),layers:_.map((e,t)=>({id:e.c.id,label:e.c.subjectName,colorIndex:t})),buckets:y,bucketMs:v,range:n,unit:`kWh`,showTotal:!0,height:160,syncKey:G,pending:f}),g.length>0&&o(A,{title:g.length===1?g[0]?.label??``:i(`history.page.states`,`States`),rows:g,range:n,syncKey:G,pending:f})]})}function Ne(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}async function Pe(e,t){let n=[];for(let r of Ne(e,50))try{let{results:e}=await t(r),i=new Map(e.map(e=>[e.seriesId,e]));for(let e of r)n.push(i.get(e)??{seriesId:e,ok:!1,reason:`not-found`})}catch(e){let t=e instanceof Error?e.message:String(e);for(let e of r)n.push({seriesId:e,ok:!1,reason:`request-failed`,message:t})}return n}function q(e){return e.raw+e[`5m`]+e[`1h`]+e[`1d`]}function Fe(e){return e.reduce((e,t)=>t.ok?{...e,deleted:e.deleted+1,points:e.points+q(t.deleted)}:{...e,refused:e.refused+1},{deleted:0,refused:0,points:0})}function Ie(e,t){let n=new Map(e.map(e=>[e.seriesId,e]));return t.flatMap(e=>{let t=n.get(e.seriesId);return t===void 0?[]:[{series:t,outcome:e}]})}var J=e=>new Date(e).toLocaleDateString(void 0,{dateStyle:`short`});function Y(e,t,n){let r=t.get(e.deviceId);return r===void 0?e.reason===`device-gone`?n(`history.orphans.deviceRemoved`,`#{{id}} (removed)`,{id:e.deviceId}):n(`history.orphans.deviceId`,`#{{id}}`,{id:e.deviceId}):r}function X(e){let t=e.displayName??e.key;return e.scope===``?t:`${t} · ${e.scope}`}function Z(e,t,n){return{key:`series`,header:n(`history.orphans.colSeries`,`Series`),render:i=>{let a=e(i);return r(`div`,{className:`min-w-0 max-w-[16rem]`,children:[o(`div`,{className:`truncate text-foreground`,title:a.key,children:X(a)}),o(`div`,{className:`truncate text-[10px] text-foreground-subtle`,children:Y(a,t,n)})]})},sortValue:r=>`${Y(e(r),t,n)} ${X(e(r))}`}}var Le=[`raw`,`5m`,`1h`,`1d`];function Re(e,t){return e===`raw`?t(`history.orphans.colRaw`,`Raw points`):e===`5m`?t(`history.orphans.col5m`,`5 min`):e===`1h`?t(`history.orphans.col1h`,`1 h`):t(`history.orphans.col1d`,`1 day`)}function ze(e,t){return[Z(e=>e,e,t),{key:`reason`,header:t(`history.orphans.colReason`,`Reason`),render:e=>r(`div`,{className:`flex flex-col items-start gap-0.5`,children:[o(N,{variant:e.reason===`device-gone`?`warning`:`neutral`,className:`text-[10px]`,children:e.reason===`device-gone`?t(`history.orphans.deviceGone`,`Device removed`):t(`history.orphans.undeclared`,`No longer declared`)}),e.missingSince!==null&&o(`span`,{className:`text-[10px] text-foreground-subtle`,children:t(`history.orphans.since`,`since {{date}}`,{date:J(e.missingSince)})})]}),sortValue:e=>e.reason},{key:`span`,header:t(`history.orphans.colSpan`,`Recorded`),render:e=>r(`span`,{className:`tabular-nums text-foreground-muted`,children:[J(e.firstTs),` → `,J(e.lastTs)]}),sortValue:e=>e.lastTs},...Le.map(e=>({key:`rows-${e}`,header:Re(e,t),align:`right`,render:t=>o(`span`,{className:`tabular-nums text-foreground-muted`,children:t.rows[e].toLocaleString()}),sortValue:t=>t.rows[e]}))]}function Be(e,t){if(e.ok)return o(N,{variant:`success`,className:`text-[10px]`,children:t(`history.orphans.deleted`,{count:q(e.deleted),points:q(e.deleted).toLocaleString(),defaultValue_one:`Deleted · {{points}} point`,defaultValue_other:`Deleted · {{points}} points`})});let n=e.reason===`request-failed`?t(`history.orphans.requestFailed`,`Not sent: {{message}}`,{message:e.message}):e.reason===`not-orphan`?t(`history.orphans.refusedNotOrphan`,`Kept: no longer orphan`):e.reason===`not-found`?t(`history.orphans.refusedNotFound`,`Already gone`):t(`history.orphans.refusedFailed`,`The hub could not delete it`);return o(N,{variant:e.reason===`not-found`?`neutral`:`warning`,className:`text-[10px]`,children:n})}function Ve(e,t){return[Z(e=>e.series,e,t),{key:`result`,header:t(`history.orphans.colResult`,`Result`),render:e=>Be(e.outcome,t),sortValue:e=>+!e.outcome.ok}]}e();function He({open:e,onClose:i,list:a,deviceNames:s,onDelete:u,onRefresh:d,refreshing:p}){let{t:m}=V(),h=y(),[g,_]=n(new Set),[v,b]=n(!1),[x,S]=n([]),C=t(()=>ze(s,m),[s,m]),w=t(()=>Ve(s,m),[s,m]),T=t(()=>new Set(a.series.map(e=>String(e.seriesId))),[a.series]),E=[...g].filter(e=>T.has(e)).map(Number),O=Fe(x.map(e=>e.outcome)),k=async()=>{if(await h({title:m(`history.orphans.confirmTitle`,{count:E.length,defaultValue_one:`Delete {{count}} series`,defaultValue_other:`Delete {{count}} series`}),message:m(`history.orphans.confirmMessage`,`Every recorded point of these series is removed from the hub. This cannot be undone.`),confirmLabel:m(`history.orphans.confirmLabel`,`Delete`),variant:`danger`})){b(!0);try{let e=await Pe(E,u);S(Ie(a.series,e)),_(new Set)}finally{b(!1),d()}}};return o(pe,{open:e,onOpenChange:e=>!e&&i(),children:r(oe,{width:`xl`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`orphan-series-dialog`,children:[o(he,{children:o(le,{children:m(`history.orphans.title`,`Series no longer linked to a device`)})}),r(ye,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-muted`,children:m(`history.orphans.intro`,`Nothing records into these series any more: their device was removed, or no capability declares them now. Select the ones to delete.`)}),a.truncated&&r(`div`,{className:`flex flex-wrap items-center gap-2`,"data-testid":`orphan-truncated`,children:[o(`p`,{className:`text-xs text-warning`,children:m(`history.orphans.truncated`,`More series are unlinked than are listed here. Delete these, then load the rest.`)}),r(D,{size:`sm`,variant:`outline`,onClick:d,disabled:p,children:[o(l,{className:`h-3 w-3`,"aria-hidden":!0}),m(`history.orphans.loadAgain`,`Load again`)]})]}),x.length>0&&r(`div`,{className:`space-y-2`,"data-testid":`orphan-outcomes`,children:[o(`p`,{className:`text-xs text-foreground`,"aria-live":`polite`,children:m(`history.orphans.summary`,{count:O.deleted,refused:O.refused,points:O.points.toLocaleString(),defaultValue_one:`{{count}} series deleted ({{points}} points), {{refused}} kept.`,defaultValue_other:`{{count}} series deleted ({{points}} points), {{refused}} kept.`})}),o(F,{columns:w,rows:x,rowKey:e=>String(e.series.seriesId),minWidthPx:420,maxBodyHeight:`max-h-[60vh]`,emptyMessage:``})]}),o(F,{columns:C,rows:a.series,rowKey:e=>String(e.seriesId),minWidthPx:760,maxBodyHeight:B,defaultSort:{columnKey:`series`,dir:`asc`},emptyMessage:m(`history.orphans.empty`,`Every series is linked to a device.`),selection:{selected:g,onChange:_,rowLabel:e=>`${X(e)} — ${Y(e,s,m)}`,pageLabel:m(`history.orphans.selectAll`,`Select every listed series`)}})]}),r(ge,{children:[o(`span`,{className:`mr-auto text-[11px] tabular-nums text-foreground`,"aria-live":`polite`,children:m(`history.orphans.selected`,{count:E.length,defaultValue_one:`{{count}} selected`,defaultValue_other:`{{count}} selected`})}),o(D,{variant:`ghost`,size:`sm`,onClick:i,children:m(`history.orphans.close`,`Close`)}),r(D,{variant:`danger`,size:`sm`,disabled:E.length===0||v,onClick:()=>void k(),children:[v?o(f,{className:`h-3 w-3 animate-spin`,"aria-hidden":!0}):o(c,{className:`h-3 w-3`,"aria-hidden":!0}),m(`history.orphans.deleteSelected`,`Delete selected`)]})]})]})})}e();var Ue=5*6e4;function We({enabled:e}){let{t:a}=V(),[s,c]=n(!1),l=O({},{enabled:e,staleTime:Ue}),u=I({projection:`slim`},{enabled:e}),d=T(),f=t(()=>new Map((u.data??[]).map(e=>[e.id,e.name])),[u.data]),p=e=>d.mutateAsync({seriesIds:[...e]});if(!e||l.status===`pending`)return null;if(l.status===`error`)return o(x,{variant:`warning`,title:a(`history.orphans.checkFailedTitle`,`Could not check for unlinked series`),message:l.error.message,onRetry:()=>void l.refetch()});let m=l.data;if(m.series.length===0&&!s)return null;let h=m.series.length;return r(i,{children:[h>0&&o(x,{variant:`warning`,message:m.truncated?a(`history.orphans.noticeMore`,{count:h,defaultValue_one:`More than {{count}} series are no longer linked to a device.`,defaultValue_other:`More than {{count}} series are no longer linked to a device.`}):a(`history.orphans.notice`,{count:h,defaultValue_one:`{{count}} series is no longer linked to a device.`,defaultValue_other:`{{count}} series are no longer linked to a device.`}),action:o(D,{size:`sm`,variant:`outline`,onClick:()=>c(!0),children:a(`history.orphans.review`,`Review`)})}),o(He,{open:s,onClose:()=>c(!1),list:m,deviceNames:f,onDelete:p,onRefresh:()=>void l.refetch(),refreshing:l.isFetching})]})}e();var Q=`device`,Ge=`node`;function Ke({catalog:e,selected:n,onChange:i,loading:a}){let{t:s}=V(),c=ve(e,{searchText:e=>[Ee(e)],facetGroups:[{id:`subject`,value:e=>e.ref.subject.kind===`device`?Q:Ge},{id:`room`,value:e=>e.location},{id:`unit`,value:e=>e.info.unit??``}]}),l=t(()=>[{key:`metric`,header:s(`history.picker.series`,`Series`),render:e=>r(`div`,{className:`min-w-0`,children:[o(`div`,{className:`truncate text-foreground`,children:e.metric}),o(`div`,{className:`truncate text-[10px] text-foreground-subtle`,children:e.location===``?e.subjectName:`${e.subjectName} · ${e.location}`})]}),sortValue:e=>`${e.subjectName} ${e.metric}`},{key:`unit`,header:s(`history.picker.unit`,`Unit`),render:e=>o(`span`,{className:`text-foreground-muted`,children:e.info.unit??`—`}),sortValue:e=>e.info.unit??``}],[s]),u=n.size>=24;return r(`div`,{className:`space-y-2 min-w-0`,children:[o(ae,{state:c.state,facets:[],groups:[{...c.groups.find(e=>e.id===`subject`)??{id:`subject`,facets:[],selected:[]},label:s(`history.picker.subject`,`Source`),facetLabel:e=>e===Q?s(`history.picker.devices`,`Devices`):s(`history.picker.nodes`,`Nodes`)},{...c.groups.find(e=>e.id===`room`)??{id:`room`,facets:[],selected:[]},label:s(`history.picker.room`,`Room`),facetLabel:e=>e===``?s(`history.picker.noRoom`,`No room`):e},{...c.groups.find(e=>e.id===`unit`)??{id:`unit`,facets:[],selected:[]},label:s(`history.picker.metricType`,`Unit`),facetLabel:e=>e===``?s(`history.picker.noUnit`,`States & counts`):e}],labels:{searchPlaceholder:s(`history.picker.search`,`Search device, room, metric or node…`),searchLabel:s(`history.picker.searchLabel`,`Search series`),facetsLabel:s(`history.picker.facets`,`Filters`),clearLabel:s(`history.picker.clear`,`Clear`)},onSearch:c.setSearch,onToggleFacet:c.toggleFacet,onToggleGroupFacet:c.toggleGroupFacet,onClear:c.clear}),o(`p`,{className:`text-[10px] text-foreground-subtle`,"aria-live":`polite`,children:s(`history.picker.count`,`{{count}} of {{max}} selected`,{count:n.size,max:24})}),o(F,{columns:l,rows:c.rows,rowKey:e=>e.id,maxBodyHeight:B,pageSize:50,defaultSort:{columnKey:`metric`,dir:`asc`},emptyMessage:a?s(`history.picker.loading`,`Reading the series of every device…`):c.active?s(`history.picker.emptyFiltered`,`No series match these filters.`):s(`history.picker.empty`,`Nothing is recorded yet.`),selection:{selected:n,onChange:e=>{let t=[...e].filter(e=>n.has(e)),r=[...e].filter(e=>!n.has(e));i(new Set([...t,...r].slice(0,24)))},isSelectable:e=>n.has(e.id)||!u,rowLabel:e=>`${e.subjectName} · ${e.metric}`,pageLabel:s(`history.picker.selectPage`,`Select every series on this page`)}})]})}e();var qe=new Set([g.Hub,g.Container]),$=5*6e4;function Je(){let{t:e}=V(),n=te(`device-history`),[i,a]=Ce(),c=t(()=>P(i.getAll(`s`).flatMap(e=>{let t=re(e);return t===null?[]:[t]})),[i]),l=i.get(`window`),f=ue(l)?l:`7d`,p=de(i.get(`range`)),m=(e,t,n)=>{let r=new URLSearchParams;for(let t of P(e))r.append(`s`,be(t));t!==`7d`&&r.set(`window`,t);let o=n===void 0?i.get(`range`):n;t===`custom`&&o&&r.set(`range`,o),a(r,{replace:!0})},g=Ye(n===`present`),_=k(f,Date.now(),p),S=k(f,ie(Date.now(),_.to-_.from),p),C=t(()=>je(c,g.candidates),[c,g.candidates]),T=t(()=>new Set(c.map(z)),[c]),E=_e(),O=ne(),A=y(),j=async()=>{let t=await O({title:e(`history.page.saveTitle`,`Save as panel`),label:e(`history.page.saveName`,`Panel name`),confirmLabel:e(`history.page.save`,`Save`)});t===null||t.trim()===``||await E.update(e=>ee(e,{id:`panel-${Date.now().toString(36)}`,name:t.trim().slice(0,80),window:f,selection:[...c]}))},M=async(t,n)=>{await A({title:e(`history.page.deleteTitle`,`Delete panel`),message:e(`history.page.deleteMessage`,`The panel "{{name}}" is removed from your account.`,{name:n}),confirmLabel:e(`history.page.delete`,`Delete`),variant:`danger`})&&await E.update(e=>b(e,t))},N=t=>t===`energy`?e(`history.panels.energy`,`Total energy`):t===`temperatures`?e(`history.panels.temperatures`,`Temperatures by room`):t===`nodes`?e(`history.panels.nodes`,`Cluster nodes`):e(`history.panels.storage`,`Storage locations`);return o(we,{icon:s,title:e(`history.page.title`,`History`),subtitle:e(`history.page.subtitle`,`What devices, nodes and storage recorded over time, side by side.`),actions:n===`present`?r(D,{size:`sm`,variant:`outline`,onClick:()=>void j(),disabled:c.length===0||!E.writable,children:[o(d,{className:`h-3.5 w-3.5`,"aria-hidden":`true`}),e(`history.page.saveTitle`,`Save as panel`)]}):void 0,children:n===`pending`?o(w,{className:`h-64 w-full`}):n===`unknown`?o(x,{title:e(`history.page.presenceUnknownTitle`,`Could not reach the hub`),message:e(`history.page.presenceUnknown`,`The hub did not say whether device history is installed. Try again in a moment.`)}):n===`absent`?o(R,{icon:h,title:e(`history.page.absentTitle`,`Device history is not running on this hub`),description:e(`history.page.absent`,`Nothing is recorded until the device-history system addon is enabled.`)}):r(`div`,{className:`space-y-3 sm:space-y-4`,children:[o(We,{enabled:n===`present`}),r(`div`,{className:`flex flex-wrap items-center gap-2`,role:`group`,"aria-label":e(`history.page.panels`,`Panels`),children:[De.map(e=>o(D,{size:`sm`,variant:`outline`,disabled:g.status!==`ok`,onClick:()=>m(Ae(e,g.candidates),f),children:N(e)},e)),E.value.panels.map(t=>r(`span`,{className:`inline-flex items-center`,children:[o(D,{size:`sm`,variant:`secondary`,onClick:()=>m(t.selection,t.window,null),children:t.name}),o(D,{size:`sm`,variant:`ghost`,"aria-label":e(`history.page.deleteNamed`,`Delete panel {{name}}`,{name:t.name}),onClick:()=>void M(t.id,t.name),disabled:!E.writable,children:o(u,{className:`h-3.5 w-3.5`,"aria-hidden":`true`})})]},t.id))]}),r(`div`,{className:`grid grid-cols-1 gap-3 sm:gap-4 xl:grid-cols-5`,children:[o(`div`,{className:`min-w-0 xl:col-span-2`,children:o(L,{headingId:`history-picker`,title:e(`history.picker.title`,`Series`),children:o(`div`,{className:`p-2 sm:p-3`,children:g.status===`error`?o(x,{message:g.error}):o(Ke,{catalog:g.candidates,loading:g.status===`pending`,selected:T,onChange:e=>{let t=c.filter(t=>e.has(z(t))),n=g.candidates.filter(t=>e.has(t.id)&&!T.has(t.id)).map(e=>e.ref);m([...t,...n],f)}})})})}),o(`div`,{className:`min-w-0 xl:col-span-3`,children:o(L,{headingId:`history-overlay`,title:e(`history.page.overlay`,`Overlay`),actions:c.length>0?o(D,{size:`sm`,variant:`ghost`,onClick:()=>m([],f),children:e(`history.page.clear`,`Clear`)}):void 0,children:r(`div`,{className:`p-2 sm:p-3 space-y-3 min-w-0`,children:[o(ce,{value:f,onChange:e=>m(c,e),custom:p,onCustomChange:e=>m(c,`custom`,v(e))}),g.status===`pending`&&c.length>0?o(w,{className:`h-64 w-full`}):o(Me,{part:C,window:S}),C.missing.length>0&&g.status===`ok`&&o(`p`,{className:`text-[11px] text-foreground-subtle`,children:e(`history.page.missing`,{count:C.missing.length,defaultValue_one:`{{count}} selected series is no longer recorded.`,defaultValue_other:`{{count}} selected series are no longer recorded.`})})]})})})]})]})})}function Ye(e){let{t:n}=V(),r=n(`history.picker.wholeFrame`,`Whole frame`),i=p().trpcClient,o=I({projection:`slim`},{enabled:e}),{nodes:s}=fe(),c=t(()=>(o.data??[]).filter(e=>!qe.has(String(e.type))),[o.data]),l=a({queries:c.map(t=>({queryKey:[`device-history`,`listSeries`,t.id],queryFn:()=>i.deviceHistory.listSeries.query({deviceId:t.id}),enabled:e,staleTime:$}))}),u=a({queries:s.map(t=>({queryKey:[`device-history`,`listNodeSeries`,t.id],queryFn:()=>i.deviceHistory.listNodeSeries.query({forNodeId:t.id}),enabled:e,staleTime:$}))}),d=E({},{enabled:e,staleTime:$}),f=t(()=>new Map((d?.data??[]).map(e=>[e.id,e.displayName])),[d?.data]),m=l.map(e=>e.data),h=u.map(e=>e.data),g=t(()=>Te(c.flatMap((e,t)=>{let n=m[t];return n===void 0?[]:[{device:{id:e.id,name:e.name,location:e.location??null},series:n}]}),s.flatMap((e,t)=>{let n=h[t];return n===void 0?[]:[{node:{id:e.id,name:e.name},series:n}]}),e=>{if(e.key!==`addon:pipeline-analytics/occupancy`)return f.get(e.scope)??e.scope;let{zoneId:t,className:n}=_(e.scope),i=t===``?r:t;return n===void 0?i:`${i} · ${n}`}),[c,s,f,[...l,...u].map(e=>e.dataUpdatedAt).join(`,`),r]);return o.status===`error`?{status:`error`,error:o.error.message,candidates:[]}:{status:o.status===`pending`||l.some(e=>e.isPending)||u.some(e=>e.isPending)?`pending`:`ok`,error:``,candidates:g}}export{Je as HistoryPage};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{$ as e,B as t,G as n,J as r,L as i,S as a,a as o,b as s,o as c,q as l,t as u,x as d}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEHpkaJP.js";import{$t as f,D as p,Fn as m,Gi as h,It as g,Nt as _,Rr as v,Tt as y,Wr as b,an as x,bn as S,cn as C,dn as w,dt as T,kn as E,lr as D,mi as O,mr as k,or as A,ot as ee,pn as j,rr as M,sn as N}from"./player-overlays-DDFLUcm1.js";import{Ai as P,ga as F,ha as I,ki as L,ma as te,s as R}from"./client-BnEPcD6s.js";import{i as z,n as ne,r as re,t as ie}from"./key-D63R1Jty.js";import{d as ae,l as B,s as oe}from"./video-BISLfAY2.js";import{t as se}from"./key-round-BH39VAkM.js";import{t as ce}from"./monitor-smartphone-rIimQM0r.js";import{t as le}from"./unlink-BK0Zya0K.js";import{Au as ue,Bn as de,Br as V,Cr as H,Ds as fe,Du as pe,Er as me,Fs as U,Fu as he,Gu as ge,Hn as _e,Hr as W,In as ve,Is as ye,Iu as be,Ju as xe,Ku as Se,L as Ce,Lu as we,Ms as Te,Mu as Ee,Nu as De,Ou as Oe,Pu as ke,Rn as Ae,Ru as je,Uu as Me,Vn as Ne,Vr as Pe,Wu as Fe,Yr as G,_i as Ie,bn as Le,dr as Re,fn as ze,ft as Be,hr as Ve,ir as He,ju as Ue,ks as We,ku as Ge,lr as Ke,md as K,mr as qe,pn as Je,pr as Ye,qu as Xe,so as Ze,sr as Qe,tt as $e,ur as et,ut as tt,vi as nt,vn as rt,wr as it,xn as at,yn as q,yt as ot,zn as st}from"./src-CWZRb0ia.js";import{t as J}from"./i18n-DsGcRtAk.js";import{t as Y}from"./useTranslation-D3Is_4B6.js";import{a as ct,d as lt,dr as ut,er as dt,fr as ft,hr as pt,i as mt,l as ht,pr as gt,ur as _t,x as vt}from"./index-CgxpaFwe.js";import{t as yt}from"./AdminSectionedPage-B-MH77Vx.js";import{t as bt}from"./AdminPage-92KQDOBy.js";import{A as xt,C as St,D as Ct,E as wt,O as X,S as Tt,T as Et,a as Dt,b as Ot,c as kt,d as At,f as jt,g as Mt,h as Nt,i as Pt,k as Ft,l as It,m as Lt,n as Rt,o as zt,p as Bt,s as Vt,t as Ht,u as Ut,v as Wt,w as Gt,x as Kt,y as qt}from"./SessionsList-DrklEq9Z.js";import{i as Jt,n as Yt,r as Xt,t as Zt}from"./IntegrationHub-DCSIyXBI.js";import{n as Qt,t as $t}from"./addon-display-names-BkwMrExv.js";e();function en(){let{t:e}=Y(),t=V(),i=K.useUtils(),a=xt(),{data:o,isLoading:s}=De(),c=n(()=>o??[],[o]),l=K.useQueries(e=>c.map(t=>e.userManagement.listExternalIdentities({userId:t.id}))),u=K.auth.listLoginMethods.useQuery(),[f,p]=r(null),m=we({onSuccess:()=>void i.userManagement.listExternalIdentities.invalidate(),onError:e=>p(`Remove failed: ${e.message}`)}),h=n(()=>new Map((u.data??[]).flatMap(e=>e.kind===`redirect`?[[e.id,e.label]]:[])),[u.data]),g=c.flatMap((e,t)=>l[t]?.data??[]),_=g.map(e=>({...Tt(e,a),kind:h.get(e.provider)??e.provider})),v=async n=>{let r=g.find(e=>Kt(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 d(X,{notice:Ft(f),onDismissNotice:()=>{p(null)},id:`external-identities`,title:e(`access.externalIdentitiesSection.signInLinks`,`Sign-in links`),icon:ae,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:d(Et,{rows:_,label:`sign-in links`,isLoading:s||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:le,isAvailable:()=>!0,onRun:e=>void v(e),busyId:null,disabled:m.isPending}})})}e();var tn={key:`access.nouns.linkedApp`};function nn(e){if(e.type===`category`){let t=e.target??``;return t===`device`?J.t(`access.linkedAppsSection.allDevices`):J.t(`access.linkedAppsSection.allTarget`,{target:t})}if(e.type===`device`)return`device:[${(e.targets??[]).join(`,`)}]`;let t=e;return`${t.type}:${t.target??``}`}function rn(){let{t:e}=Y(),t=V(),i=c(),a=Ee(),[o,s]=r(null),l=()=>void i.invalidateQueries({queryKey:[[`userManagement`,`listOauthSessions`]]}),u=he({onSuccess:l,onError:e=>s(`Revoke failed: ${e.message}`)}),f=wt(tn,l),p=n(()=>(a.data??[]).map(e=>St(e,e.scopes.map(nn).join(`, `))),[a.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`})&&(s(null),u.mutate({id:n.id}))},h=u.isPending?u.variables?.id??null:null;return d(X,{notice:Ft(o,f.outcome),onDismissNotice:()=>{s(null),f.dismiss()},id:`linked-apps`,title:e(`access.linkedAppsSection.linkedApps`,`Linked apps`),icon:D,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:d(Et,{rows:p,label:e(`access.linkedAppsSection.linkedApps2`,`linked apps`),isLoading:a.isLoading,loadError:a.isError?a.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:g,isAvailable:e=>e.status===`active`||e.status===`revoked`,onRun:e=>void m(e),busyId:h,disabled:u.isPending||f.busy},bulk:{revoke:f,noun:tn,isSelectable:e=>e.status===`active`||e.status===`revoked`,quickSelect:[{label:e(`access.linkedAppsSection.selectRevoked`,`Select revoked`),match:e=>e.status===`revoked`}]}})})}e();var an={key:`access.nouns.session`};function on(){let{t:e}=Y(),t=V(),i=K.useUtils(),a=xt(),o=K.auth.listSessions.useQuery(),[s,c]=r(null),l=()=>void i.auth.listSessions.invalidate(),u=K.auth.revokeSessions.useMutation({onSuccess:l,onError:e=>c(`Sign out failed: ${e.message}`)}),f=wt(an,l),p=n(()=>(o.data??[]).map(e=>Gt(e,a,{client:e=>Wt(e).label,method:qt})),[o.data,a]),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`})&&(c(null),u.mutate({id:n.id}))};return d(X,{notice:Ft(s,f.outcome),onDismissNotice:()=>{c(null),f.dismiss()},id:`login-sessions`,title:e(`access.loginSessionsSection.loginSessions`,`Login sessions`),icon:ce,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:d(Et,{rows:p,label:e(`common.sessionsLabel`),isLoading:o.isLoading,loadError:o.isError?o.error?.message??`Request failed`:null,emptyText:`No active sessions.`,action:{label:e(`access.loginSessionsSection.signOut`,`Sign out`),icon:oe,isAvailable:e=>e.status===`active`,onRun:e=>void m(e),busyId:u.isPending&&u.variables!==void 0&&`id`in u.variables?u.variables.id:null,disabled:u.isPending||f.busy},bulk:{revoke:f,noun:an,isSelectable:e=>e.status===`active`}})})}var sn={"by-id":`helpers.authAuditWording.bulkNoun.credential`,"share-link":`helpers.authAuditWording.bulkNoun.shareLink`,"admin-token":`helpers.authAuditWording.bulkNoun.adminToken`,"login-session":`helpers.authAuditWording.bulkNoun.loginSession`};function Z(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:null}function cn(e,t){let n=Z(e,`tokenId`);return Z(e,`name`)??(n===null?void 0:t.get(n))??n??`?`}function Q(e){return e.filter(e=>e!==null)}function ln(e){let t=Z(e,`prefix`);return t===null?null:J.t(`helpers.authAuditWording.prefix`,{prefix:t})}function un(e,t){let n=e.detail??{};switch(e.action){case`admin-token-created`:{let e=n.expiresAt;return{title:J.t(`helpers.authAuditWording.tokenCreated`,{name:cn(n,t)}),details:Q([ln(n),typeof e==`number`?J.t(`helpers.authAuditWording.expires`,{at:Ot(e)}):null])}}case`admin-token-used`:{let e=Z(n,`path`);return{title:J.t(`helpers.authAuditWording.tokenUsed`,{name:cn(n,t)}),details:Q([ln(n),e===null?null:J.t(`helpers.authAuditWording.call`,{path:e})])}}case`token-minted`:{let e=n.expiresAt;return{title:J.t(`helpers.authAuditWording.tokenMinted`,{name:cn(n,t)}),details:Q([typeof e==`number`?J.t(`helpers.authAuditWording.expires`,{at:Ot(e)}):null])}}case`token-revoked`:return{title:J.t(`helpers.authAuditWording.anyTokenRevoked`,{name:cn(n,t)}),details:[]};case`admin-token-revoked`:return{title:J.t(`helpers.authAuditWording.tokenRevoked`,{name:cn(n,t)}),details:Q([ln(n)])};case`credentials-revoked`:{let e=Z(n,`kind`)??`credential`,t=n.revoked,r=n.skipped,i=sn[e],a=i===void 0?`${e}s`:J.t(i);return{title:J.t(`helpers.authAuditWording.bulkRevoked`,{n:typeof t==`number`?String(t):`?`,noun:a}),details:Q([typeof r==`number`&&r>0?J.t(`helpers.authAuditWording.skipped`,{count:r}):null,Z(n,`ids`)===null?null:J.t(`helpers.authAuditWording.ids`,{ids:Z(n,`ids`)??``})])}}case`second-factor-skipped`:{let e=Z(n,`method`),t=Z(n,`factors`);return{title:J.t(`helpers.authAuditWording.secondFactorSkipped`),details:Q([e===null?null:J.t(`helpers.authAuditWording.signedInWith`,{method:qt(e)}),t===null?null:J.t(`helpers.authAuditWording.skippedFactors`,{factors:t.split(`,`).join(`, `)})])}}default:return{title:e.action,details:Object.entries(n).map(([e,t])=>`${e}: ${String(t)}`)}}}e();var dn=100;function fn(){let{user:e}=dt();return e?.isAdmin?d(mn,{}):null}function pn(){let{data:e}=De(),{data:t}=K.auth.listTokens.useQuery(void 0);return n(()=>{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.label);return{userNameById:n,tokenNameById:r}},[e,t])}function mn(){let{t:e}=Y(),t=K.auth.listAuthAudit.useQuery({limit:dn}),{userNameById:n,tokenNameById:r}=pn(),i=t.data??[];return a(`div`,{"data-testid":`auth-audit`,className:`rounded-lg border border-border bg-surface overflow-hidden`,children:[a(`div`,{className:`px-4 py-2.5 border-b border-border flex items-center gap-2`,children:[d(j,{className:`h-3.5 w-3.5 text-foreground-subtle`}),d(`div`,{className:`text-xs font-semibold text-foreground`,children:e(`auth.authAuditSection.authenticationAudit`,`Authentication audit`)}),d(`span`,{className:`ml-auto text-[10px] text-foreground-subtle`,children:e(`auth.authAuditSection.latest`,{count:dn})})]}),d(`div`,{className:`p-4`,children:t.isLoading?a(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[d(A,{className:`h-3.5 w-3.5 animate-spin`}),e(`auth.authAuditSection.loadingAuditTrail`,`Loading audit trail…`)]}):t.isError?a(`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`)]}):i.length===0?a(`div`,{className:`rounded border border-dashed border-border px-3 py-4 text-xs text-foreground-subtle text-center space-y-1`,children:[d(`div`,{children:e(`auth.authAuditSection.noAuthenticationEventsRecordedYet`,`No authentication events recorded yet.`)}),d(`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.`)})]}):d(`ul`,{className:`divide-y divide-border rounded-md border border-border max-h-[420px] overflow-y-auto`,children:i.map(e=>d(hn,{record:e,userName:e.userId===void 0?null:n.get(e.userId)??e.userId,tokenNameById:r},e.id))})})]})}function hn({record:e,userName:t,tokenNameById:n}){let r=un(e,n);return a(`li`,{"data-testid":`auth-audit-row`,className:`px-3 py-2 text-xs space-y-0.5`,children:[a(`div`,{className:`flex flex-wrap items-baseline gap-x-2`,children:[d(`span`,{className:`font-medium text-foreground`,children:r.title}),d(`span`,{className:`ml-auto text-[10px] text-foreground-subtle`,children:Ot(e.at)})]}),a(`div`,{className:`flex flex-wrap gap-x-3 text-[11px] text-foreground-subtle`,children:[t!==null&&d(`span`,{className:`text-foreground`,children:t}),e.ip!==void 0&&d(`span`,{className:`font-mono`,children:e.ip}),r.details.map(e=>d(`span`,{className:`font-mono`,children:e},e))]})]})}e();var $={loginSessions:`login-sessions`,linkedApps:`linked-apps`,tokens:`tokens`,scopedTokens:`scoped-tokens`,adminTokens:`admin-tokens`,shareLinks:`share-links`,externalIdentities:`external-identities`,audit:`auth-audit`},gn={[$.scopedTokens]:$.tokens,[$.adminTokens]:$.tokens,[$.shareLinks]:$.tokens};function _n(){return[{id:$.loginSessions,label:J.t(`system.access.loginSessions`,`Login sessions`),icon:ce,render:()=>d(on,{})},{id:$.linkedApps,label:J.t(`system.access.linkedApps`,`Linked apps`),icon:D,render:()=>d(rn,{})},{id:$.tokens,label:J.t(`system.access.tokens`,`Tokens`),icon:se,render:({createRequested:e,onCreateConsumed:t})=>d(Nt,{headerOwnsCreate:!0,createRequested:e,onCreateConsumed:t})},{id:$.externalIdentities,label:J.t(`system.access.signInLinks`,`Sign-in links`),icon:ae,render:()=>d(en,{})},{id:$.audit,label:J.t(`system.access.audit`,`Audit`),icon:j,render:()=>d(fn,{})}]}function vn({createRequested:e=!1,onCreateConsumed:t}){let{t:r}=Y(),i=n(()=>_n(),[]),o=Jt({ids:n(()=>i.map(e=>e.id),[i]),answered:!0}),s=gt(),[c]=pt(),l=c.get(`integration`),u=l===null?void 0:gn[l];if(u!==void 0){let e=new URLSearchParams(c);return e.set(`integration`,u),d(ft,{to:`?${e.toString()}`,replace:!0})}let f=i.find(e=>e.id===o.selectedId)??i[0];return a(`div`,{className:`flex flex-col gap-3`,"data-testid":`access-page`,children:[d(ve,{appearance:`pills`,value:f?.id??$.loginSessions,onValueChange:e=>{s(`?${lt(c,e,null,null).toString()}`)},children:d(Ae,{"aria-label":r(`system.access.credentialKinds`,`Credential kinds`),children:i.map(e=>a(st,{value:e.id,"data-testid":`access-kind-${e.id}`,children:[d(e.icon,{className:`h-3.5 w-3.5 shrink-0`,"aria-hidden":!0}),e.label]},e.id))})}),f===void 0?null:d(`div`,{role:`region`,"aria-label":f.label,"data-testid":`access-kind-body`,children:f.render({createRequested:e&&f.id===$.tokens,onCreateConsumed:t??(()=>void 0)})},f.id)]})}function yn(e,t){if(e===$.tokens)return a(W,{size:`sm`,type:`button`,"data-testid":`access-new-token`,onClick:t,children:[d(se,{className:`h-3.5 w-3.5`,"aria-hidden":!0}),J.t(`system.access.newToken`,`New token`)]})}function bn(){let[e,t]=r(!1);return{createRequested:e,requestCreate:()=>t(!0),clearCreate:()=>t(!1)}}e();var xn=[`oidcConnections`,`listConnections`],Sn=[`oidcConnections`,`connectionFormSchema`],Cn={displayName:`OpenID Connect`,icon:`shield-check`,issuerUrl:``,clientId:``,clientSecret:``,redirectUri:``,scopes:`openid profile email`,usernameClaim:`preferred_username`},wn=/^[a-z0-9][a-z0-9-]{0,63}$/;function Tn(e){return e instanceof Error?e.message:String(e)}function En(e,t){if(t)return typeof e==`string`&&e.length>0?e:void 0;if(I(e))return te;if(typeof e==`string`&&e.length>0)return e;F(e)}function Dn(e){return typeof e!=`object`||!e?!1:Array.isArray(Reflect.get(e,`sections`))}function On({addonId:e}){let{t:f}=Y(),p=ee(),m=c(),h=V(),_=tt({editKey:`oidcEdit`,newKey:`oidcNew`}),[v,y]=r(!1),[b,x]=r(null),[S,C]=r(``),[w,T]=r({...Cn}),D=l(null),O=o({queryKey:[...xn,e],queryFn:async()=>p.trpcClient.oidcConnections.listConnections.query({})}),k=o({queryKey:Sn,queryFn:async()=>p.trpcClient.oidcConnections.connectionFormSchema.query({})}),A=O.data??[],j=Dn(k.data)?k.data:void 0,M=_.state,P=M.mode===`edit`?A.find(e=>e.id===M.id)??null:null;t(()=>{if(_.state.mode===`edit`&&P!==null){let e=`edit:${P.id}`;if(D.current===e)return;D.current=e,x(null),C(P.id),T(P.formValues===void 0?{...Cn}:{...P.formValues});return}if(_.state.mode===`new`){if(D.current===`new`)return;D.current=`new`,x(null),C(``),T({...Cn})}},[P,_.state]);let F=i(async()=>{await m.invalidateQueries({queryKey:xn})},[m]),I=u({mutationFn:async e=>p.trpcClient.oidcConnections.deleteConnection.mutate({id:e}),onSuccess:async()=>F()}),L=i(async e=>{await h({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 I.mutateAsync(e.id),_.state.mode===`edit`&&_.state.id===e.id&&(_.close(),D.current=null))},[h,I,_,f]),te=i(async()=>{let e=w.displayName,t=typeof e==`string`&&e.trim()!==``?e.trim():``;if(t===``){x(`Display name is required.`);return}let n=_.state.mode===`new`,r=n?S.trim():P?.id??``;if(n&&!wn.test(r)){x(`Instance id must be a lowercase slug (e.g. authentik, google).`);return}if(r===``){x(`That connection is no longer available.`);return}let i=En(w.clientSecret,n),a=w.icon,o=w.issuerUrl,s=w.clientId,c=w.redirectUri,l=w.scopes,u=w.usernameClaim,d=u===`email`||u===`sub`?u:`preferred_username`;y(!0),x(null);try{n&&await 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 F(),_.close(),D.current=null}catch(e){x(Tn(e))}finally{y(!1)}},[S,P?.id,_,w,F,p]),R=n(()=>[{key:`id`,header:f(`system.oidcSettingsConnections.id`,`Id`),sortValue:e=>e.id,render:e=>d(`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=>d(`span`,{className:`truncate font-medium text-foreground`,children:e.displayName})},{key:`issuer`,header:f(`system.oidcSettingsConnections.issuer`,`Issuer`),sortValue:e=>e.issuerUrl,render:e=>d(`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=>d(G,{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=>a(`div`,{className:`flex justify-end gap-1`,children:[d(W,{type:`button`,size:`sm`,variant:`secondary`,onClick:t=>{t.stopPropagation(),_.openEdit(e.id)},children:f(`common.edit`,`Edit`)}),d(W,{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(),L(e)},children:d(g,{className:`h-3.5 w-3.5 text-danger`})})]})}],[_,L,f]),z=_.state.mode===`new`,ne=z||P!==null,re=z?`new`:P===null?`closed`:`edit:${P.id}:${P.configured?`cfg`:`empty`}`,ie=`/addon/${e}/<id>/callback`;return a(`div`,{className:`flex min-h-0 flex-col gap-3`,"data-testid":`oidc-settings-connections`,children:[a(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[a(`p`,{className:`text-sm text-foreground-muted`,children:[f(`system.oidcSettingsConnections.eachRowIsOneIdp`,`Each row is one IdP. Redirect URI:`),` `,d(`span`,{className:`font-mono text-xs`,children:ie})]}),a(W,{type:`button`,size:`sm`,"data-testid":`oidc-connections-add`,onClick:()=>_.openNew(),children:[d(E,{className:`h-3.5 w-3.5`}),f(`system.oidcSettingsConnections.addConnection`,`Add connection`)]})]}),O.isError?d(`p`,{className:`text-sm text-danger`,children:f(`system.oidcSettingsConnections.couldNotLoadConnections`,`Could not load connections.`)}):null,O.isPending?d(me,{className:`h-32 w-full`}):d(Le,{columns:R,rows:A,rowKey:e=>e.id,pageSize:25,emptyMessage:f(`system.oidcSettingsConnections.noOidcConnectionsYetAdd`,`No OIDC connections yet. Add one to register an IdP.`),onRowClick:e=>_.openEdit(e.id),defaultSort:{columnKey:`name`,dir:`asc`}}),d(Be,{open:ne,onClose:()=>{_.close(),x(null),D.current=null},title:z?f(`system.oidcSettingsConnections.addOidcConnection`,`Add OIDC connection`):f(`system.oidcSettingsConnections.edit`,`Edit {{value1}}`,{value1:P?.displayName??`connection`}),icon:N,width:`xl`,testId:`oidc-connection-editor`,error:b,footer:d(W,{type:`button`,size:`sm`,disabled:v||z&&S.trim()===``,onClick:()=>void te(),children:v?f(`system.oidcSettingsConnections.saving`,`Saving…`):f(`common.save`,`Save`)}),children:ne?a(s,{children:[z?a(`div`,{children:[d(_e,{htmlFor:`oidc-connection-id`,children:f(`system.oidcSettingsConnections.instanceId`,`Instance id`)}),d(xe,{id:`oidc-connection-id`,value:S,onChange:e=>C(e.target.value),placeholder:`authentik`,autoComplete:`off`}),d(`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:e})})]}):a(`p`,{className:`text-sm text-foreground-muted`,children:[f(`system.oidcSettingsConnections.instanceId2`,`Instance id:`),` `,d(`span`,{className:`font-mono`,children:P?.id})]}),j===void 0?d(`p`,{className:`text-sm text-foreground-muted`,children:f(`system.oidcSettingsConnections.loadingForm`,`Loading form…`)}):d(He,{schema:j,values:w,onChange:T,bare:!0},re)]}):null})]})}e();var kn=3e4,An=[{capName:`auth-provider`,stageBadge:null},{capName:`user-passkeys`,stageBadge:`Second factor`}],jn={titleKey:`system.authentication.sectionTitle`,subtitleKey:`system.authentication.sectionSubtitle`,emptyTitleKey:`system.authentication.sectionEmptyTitle`,emptyDescriptionKey:`system.authentication.sectionEmptyDescription`,installLabelKey:`system.authentication.sectionInstall`};function Mn(e){return e===`local-auth`?{headline:`Username + password (local).`,icon:ne,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:B,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:B,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:f,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:f,bullets:[`Time-based codes from an authenticator app (RFC 6238).`,`Compatible with Google Authenticator, Aegis, 1Password, Bitwarden, etc.`]}:{headline:`Authentication provider.`,icon:N,bullets:[`Generic authentication provider. No additional hints registered.`]}}function Nn(){let{t:e}=Y(),t=nt({capName:An[0].capName},{refetchInterval:kn}),r=nt({capName:An[1].capName},{refetchInterval:kn}),i=Ie(void 0,{refetchInterval:kn}),a=n(()=>$t(i.data??[]),[i.data]),o=n(()=>{let e=[],n=[t.data??[],r.data??[]];for(let[t,r]of An.entries())for(let i of n[t]??[])e.push({addonId:i.addonId,displayName:a.get(i.addonId)??i.addonId,isActive:i.isActive,capName:r.capName,stageBadge:r.stageBadge});return e},[t.data,r.data,a]),s=[{id:`authentication`,label:e(`system.authentication.authenticationProviders`,`Authentication providers`),install:{capability:An[0].capName,label:e(jn.installLabelKey)},entries:o.map(t=>({id:t.addonId,name:t.displayName,fallbackIcon:N,...Qt(t.isActive),render:()=>d(Yt,{addonId:t.addonId,displayName:t.displayName,capName:t.capName,isActive:t.isActive,badges:t.stageBadge===null?null:d(G,{variant:`info`,className:Xt,children:t.stageBadge}),settingsContent:t.addonId.startsWith(`auth-oidc`)?d(On,{addonId:t.addonId}):void 0,panels:[{id:`about`,title:e(`system.authentication.about`,`About`),icon:Mn(t.addonId).icon,content:d(Pn,{addonId:t.addonId})}]})}))}];return d(Zt,{embedded:!0,icon:N,title:e(jn.titleKey),subtitle:e(jn.subtitleKey),groups:s,isLoading:t.isLoading||r.isLoading,emptyTitle:e(jn.emptyTitleKey),emptyDescription:e(jn.emptyDescriptionKey)})}function Pn({addonId:e}){let{t}=Y(),n=Mn(e),r=n.icon;return a(`div`,{className:`space-y-3 rounded-lg border border-border bg-surface p-2 sm:p-4`,children:[a(`div`,{className:`flex items-start gap-2.5`,children:[d(r,{className:`h-4 w-4 mt-0.5 text-primary shrink-0`}),d(`div`,{className:`text-xs text-foreground font-medium`,children:n.headline})]}),d(`ul`,{className:`text-xs text-foreground-subtle space-y-1.5 pl-6 list-disc`,children:n.bullets.map((e,t)=>d(`li`,{children:e},t))}),n.setupSteps&&n.setupSteps.length>0&&a(`div`,{className:`rounded-md border border-border bg-surface-hover/40 px-3 py-2.5 space-y-1.5`,children:[a(`div`,{className:`flex items-center gap-1.5 text-[10px] font-semibold text-foreground-subtle uppercase tracking-wide`,children:[d(z,{className:`h-3 w-3`}),t(`system.authentication.setupSteps`,`Setup steps`)]}),d(`ol`,{className:`text-xs text-foreground space-y-0.5 pl-4 list-decimal`,children:n.setupSteps.map((e,t)=>d(`li`,{children:e},t))})]}),e===`local-auth`&&a(`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:[d(k,{className:`h-3.5 w-3.5 mt-0.5 text-info shrink-0`}),d(`span`,{children:d(_t,{i18nKey:`system.authentication.totpNote`,components:{access:d(ut,{to:`/system/my-access?tab=sign-in`,className:`underline text-primary`}),users:d(ut,{to:`/system/identity?tab=users`,className:`underline text-primary`})}})})]})]})}function Fn({isPending:e,error:t,what:n,onRetry:r,children:i}){let{t:o}=Y();return e?a(`div`,{className:`flex items-center gap-2 py-3 text-xs text-foreground-subtle`,role:`status`,"data-testid":`query-pending`,children:[d(A,{className:`h-3.5 w-3.5 animate-spin`,"aria-hidden":!0}),o(`certificates.queryBody.reading`,{what:n})]}):t===null?i:d(H,{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:r})}function In(){let{t:e}=Y(),t=K.deviceCredentials.getDeviceCaStatus.useQuery({}),n=t.data;return d(X,{id:`device-ca`,title:e(`certificates.deviceCaCard.deviceCertificateAuthority`,`Device certificate authority`),icon:N,description:e(`certificates.deviceCaCard.signsTheCertificateEachPaired`,`Signs the certificate each paired device holds. It is created the first time a device is paired.`),children:d(Fn,{isPending:t.isPending,error:t.error,what:`the device CA`,onRetry:()=>void t.refetch(),children:n!==void 0&&a(`div`,{className:`space-y-1`,"data-testid":`device-ca-status`,children:[a(q,{label:e(`certificates.deviceCaCard.state`,`State`),children:[n.state===`ready`&&d(G,{variant:`success`,children:e(`certificates.deviceCaCard.ready`,`Ready`)}),n.state===`absent`&&d(G,{variant:`default`,children:e(`certificates.deviceCaCard.notCreatedYet`,`Not created yet`)}),n.state===`unavailable`&&d(G,{variant:`danger`,children:e(`certificates.deviceCaCard.unavailable`,`Unavailable`)})]}),n.state===`ready`&&a(s,{children:[d(q,{label:e(`certificates.deviceCaCard.subject`,`Subject`),valueClassName:`font-mono`,children:n.subject}),d(q,{label:e(`certificates.deviceCaCard.fingerprintSha256`,`Fingerprint (SHA-256)`),valueClassName:`font-mono`,children:n.fingerprintSha256}),d(q,{label:e(`certificates.deviceCaCard.validUntil`,`Valid until`),children:n.validTo})]}),n.state===`unavailable`&&d(q,{label:e(`certificates.deviceCaCard.reason`,`Reason`),children:d(`span`,{className:`text-danger`,children:n.reason})})]})})})}e();function Ln(){let{t:e}=Y(),t=K.useUtils(),n=K.deviceCredentials.getDeviceCertificateSettings.useQuery({}),[i,o]=r(null),s=K.deviceCredentials.setDeviceCertificateSettings.useMutation({onSuccess:()=>{o(null),t.deviceCredentials.getDeviceCertificateSettings.invalidate()},onError:e=>o(`Could not save: ${e.message}`)});return d(Fn,{isPending:n.isPending,error:n.error,what:`the enrollment setting`,onRetry:()=>void n.refetch(),children:n.data!==void 0&&a(q,{label:e(`certificates.deviceSettingsRow.usersCanEnrollTheirOwn`,`Users can enroll their own devices`),actions:d(de,{checked:n.data.selfEnrollment===`allowed`,disabled:s.isPending,"aria-label":e(`certificates.deviceSettingsRow.usersCanEnrollTheirOwn`,`Users can enroll their own devices`),onCheckedChange:e=>s.mutate({selfEnrollment:e?`allowed`:`disabled`})}),children:[d(`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&&d(`span`,{className:`block text-[11px] text-danger`,children:i})]})})}e();function Rn(e){let[n,i]=r(()=>Date.now());return t(()=>{let t=setInterval(()=>i(Date.now()),e);return()=>clearInterval(t)},[e]),n}e();var zn=80,Bn=208;function Vn({open:e,users:t,onClose:n,onPaired:i}){let{t:o}=Y(),s=K.deviceCredentials.startEnrollment.useMutation({onSuccess:i}),[c,l]=r(``),[u,p]=r(``),m=c===``?t[0]?.id??``:c,h=s.data,g=()=>{s.reset(),p(``),n()};return d(Be,{open:e,onClose:g,title:o(`certificates.pairDeviceDialog.pairADevice`,`Pair a device`),icon:f,width:`md`,testId:`pair-device-dialog`,error:s.isError?s.error.message:null,footer:h===void 0?a(W,{type:`button`,onClick:()=>{let e=u.trim();m===``||e===``||s.mutate({userId:m,deviceName:e})},disabled:s.isPending||m===``||u.trim()===``,children:[s.isPending&&d(A,{className:`h-3.5 w-3.5 animate-spin`,"aria-hidden":!0}),o(`certificates.pairDeviceDialog.createPairingCode`,`Create pairing code`)]}):d(W,{type:`button`,variant:`outline`,onClick:g,children:o(`certificates.pairDeviceDialog.done`,`Done`)}),children:h===void 0?a(`div`,{className:`space-y-3`,children:[d(`p`,{className:`text-[11px] text-foreground-subtle`,children:o(`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.`)}),d(ot,{label:o(`certificates.pairDeviceDialog.user`,`User`),required:!0,children:d(Me,{value:m,onChange:e=>l(e.target.value),options:t.map(e=>({value:e.id,label:e.username}))})}),d(ot,{label:o(`certificates.pairDeviceDialog.deviceName`,`Device name`),required:!0,description:o(`certificates.pairDeviceDialog.howThisPhoneIsListed`,`How this phone is listed, e.g. Anna's iPhone.`),children:d(xe,{value:u,maxLength:zn,onChange:e=>p(e.target.value),placeholder:o(`certificates.pairDeviceDialog.annaSIphone`,`Anna's iPhone`),autoFocus:!0})})]}):d(Hn,{enrollUrl:h.enrollUrl,expiresAt:h.expiresAt,hubKnown:h.hubOrigin!==null,onRestart:()=>s.reset()})})}function Hn({enrollUrl:e,expiresAt:t,hubKnown:n,onRestart:r}){let{t:i}=Y(),o=zt(t,Rn(1e3));return d(`div`,{className:`space-y-3`,"data-testid":`pair-issued`,children:a(`div`,{className:`flex flex-col items-center gap-3 sm:flex-row sm:items-start`,children:[d(`div`,{className:o.expired?`opacity-30`:void 0,children:d(Qe,{value:e,size:Bn,alt:i(`certificates.pairDeviceDialog.enrollmentQrCode`,`Enrollment QR code`)})}),a(`div`,{className:`min-w-0 flex-1 space-y-2`,children:[d(`p`,{className:`text-[11px] text-foreground-subtle`,children:i(`certificates.pairDeviceDialog.openTheCamstackAppOn`,`Open the CamStack app on the phone and scan this code. It works once.`)}),d(`div`,{className:`text-sm font-semibold tabular-nums text-foreground`,role:`timer`,"data-testid":`pair-countdown`,children:o.expired?i(`certificates.pairDeviceDialog.expiredCreateANewCode`,`Expired - create a new code`):i(`certificates.pairDeviceDialog.expiresIn`,`Expires in {{label}}`,{label:o.label})}),a(`div`,{className:`flex items-center gap-1 rounded-md border border-border bg-background px-2 py-1`,children:[d(`code`,{className:`min-w-0 flex-1 select-all break-all font-mono text-[11px] text-foreground`,children:e}),d(ze,{value:e,srLabel:`Enrollment link`})]}),!n&&a(`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:[d(_,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-warning`,"aria-hidden":!0}),d(`span`,{children:i(`certificates.pairDeviceDialog.theHubCouldNotName`,`The hub could not name an address for this link, so the app must already know it.`)})]}),o.expired&&d(W,{type:`button`,variant:`outline`,size:`sm`,onClick:r,children:i(`certificates.pairDeviceDialog.newCode`,`New code`)})]})]})})}e();var Un={key:`access.nouns.device`};function Wn({pairOpen:e,onPairClose:t}){let{t:i}=Y(),o=V(),s=Pe(),c=K.useUtils(),l=K.deviceCredentials.listDeviceCredentials.useQuery({includeRevoked:!0}),u=De(),[p,_]=r(null),[v,y]=r(null),b=()=>void c.deviceCredentials.listDeviceCredentials.invalidate(),x=e=>t=>{y(null),_(`${e} failed: ${t.message}`)},S=()=>{y(null),b()},C=K.deviceCredentials.revokeDeviceCredential.useMutation({onSuccess:S,onError:x(`Revoke`)}),w=K.deviceCredentials.deleteDeviceCredential.useMutation({onSuccess:e=>{e.result!==`deleted`&&_(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=Ct(Un,e=>C.mutateAsync({id:e}),b),D=E.busy||v!==null,O=n(()=>(l.data??[]).map(Rt),[l.data]),k=async e=>{await o({title:i(`certificates.devicesCard.revoke`,`Revoke "{{name}}"?`,{name:e.name}),message:i(`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:i(`certificates.devicesCard.revoke2`,`Revoke`),variant:`danger`})&&(_(null),y(e.id),C.mutate({id:e.id}))},A=async e=>{await o({title:i(`certificates.devicesCard.delete`,`Delete "{{name}}"?`,{name:e.name}),message:i(`certificates.devicesCard.isRemovedFromTheList`,`{{name}} is removed from the list. The audit trail keeps the revocation.`,{name:e.name}),confirmLabel:i(`common.delete`,`Delete`),variant:`danger`})&&(_(null),y(e.id),w.mutate({id:e.id}))},ee=async e=>{let t=(await s({title:i(`certificates.devicesCard.renameDevice`,`Rename device`),label:i(`certificates.devicesCard.deviceName`,`Device name`),defaultValue:e.name,confirmLabel:i(`certificates.devicesCard.rename`,`Rename`)}))?.trim()??``;t===``||t===e.name||(_(null),y(e.id),T.mutate({id:e.id,deviceName:t}))},j={label:i(`certificates.devicesCard.revoke2`,`Revoke`),icon:h,isAvailable:Dt,onRun:e=>void k(e),busyId:C.isPending?v:null,disabled:D},M=[{label:i(`certificates.devicesCard.rename`,`Rename`),icon:m,tone:`neutral`,isAvailable:()=>!0,onRun:e=>void ee(e),busyId:T.isPending?v:null,disabled:D},{label:i(`common.delete`,`Delete`),icon:g,isAvailable:Pt,onRun:e=>void A(e),busyId:w.isPending?v:null,disabled:D}];return a(X,{id:`devices`,title:i(`certificates.devicesCard.devices`,`Devices`),icon:f,description:i(`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:Ft(p,E.outcome),onDismissNotice:()=>{_(null),E.dismiss()},children:[d(Ln,{}),d(Et,{rows:O,label:i(`certificates.devicesCard.label`),isLoading:l.isPending,loadError:l.error===null?null:l.error.message||`Request failed`,emptyText:`No devices paired yet.`,expiresNone:`—`,action:j,extraActions:M,bulk:{revoke:E,noun:Un,isSelectable:Dt}}),d(Vn,{open:e,users:u.data??[],onClose:t,onPaired:b})]})}var Gn=/-----BEGIN CERTIFICATE-----[\s\S]+?-----END CERTIFICATE-----/,Kn=/-----BEGIN ((?:RSA |EC |ENCRYPTED )?PRIVATE KEY)-----[\s\S]+?-----END \1-----/,qn={certificate:`.pem,.crt,.cer`,privateKey:`.pem,.key`,ca:`.pem,.crt,.cer`};function Jn(e,t){if(t.trim()===``)return null;if(e===`privateKey`){let e=Kn.exec(t);return e===null?Gn.test(t)?J.t(`helpers.pemFile.isCert`):J.t(`helpers.pemFile.notKey`):e[1]===`ENCRYPTED PRIVATE KEY`?J.t(`helpers.pemFile.encrypted`):null}return Gn.test(t)?e===`certificate`&&Kn.test(t)?J.t(`helpers.pemFile.certHasKey`):null:Kn.test(t)?J.t(`helpers.pemFile.isKey`):J.t(`helpers.pemFile.notCert`)}function Yn(e){return e.text()}e();function Xn({kind:e,label:t,value:n,onChange:i,rows:o=6}){let{t:s}=Y(),c=l(null),[u,f]=r(null),[p,m]=r(null),h=p??Jn(e,n),g=`pem-${e}`,_=async e=>{let t=e.target.files?.[0];if(e.target.value=``,t!==void 0){f(t.name);try{let e=await Yn(t);m(null),i(e)}catch(e){m(`Could not read ${t.name}: ${e instanceof Error?e.message:String(e)}`)}}};return a(`div`,{className:`space-y-1`,children:[a(`div`,{className:`flex items-center justify-between gap-2`,children:[d(`label`,{htmlFor:g,className:`text-[11px] text-foreground-subtle`,children:t}),a(`div`,{className:`flex min-w-0 items-center gap-2`,children:[u!==null&&d(`span`,{className:`truncate font-mono text-[10px] text-foreground-subtle`,"data-testid":`${g}-file-name`,children:u}),d(`input`,{ref:c,type:`file`,accept:qn[e],onChange:e=>void _(e),className:`hidden`,"data-testid":`${g}-file`}),a(W,{size:`sm`,variant:`outline`,type:`button`,onClick:()=>c.current?.click(),children:[d(re,{className:`mr-1 h-3 w-3`}),s(`system.pemField.chooseFile`,`Choose file`)]})]})]}),d(`textarea`,{id:g,value:n,onChange:e=>{f(null),m(null),i(e.target.value)},rows:o,"aria-invalid":h!==null,className:`w-full rounded border border-border bg-surface px-2 py-1 font-mono text-[11px]`}),h!==null&&d(`p`,{className:`text-[11px] text-danger`,role:`alert`,children:h})]})}e();var Zn=30;function Qn(e){let t=Date.parse(e);return!Number.isNaN(t)&&Date.now()-t<Zn*864e5}function $n(e){if(e===null||e===``)return`—`;let t=e.replace(/:/g,``);return t.length<=16?e:`${t.slice(0,8)}…${t.slice(-8)}`}function er(){let{t:e}=Y(),t=c(),n=fe(void 0,{refetchInterval:15e3}),i=We({onSuccess:()=>void t.invalidateQueries({queryKey:[[`localNetwork`]]})}),o=Te({onSuccess:()=>void t.invalidateQueries({queryKey:[[`localNetwork`]]})}),s=ye({onSuccess:()=>void t.invalidateQueries({queryKey:[[`localNetwork`]]})}),l=U({onSuccess:()=>{m(!1),g(``),v(``),b(``),t.invalidateQueries({queryKey:[[`localNetwork`]]})}}),u=n.data,[f,m]=r(!1),[h,g]=r(``),[_,v]=r(``),[y,b]=r(``),S=()=>{if(!u?.caCertPem)return;let e=new Blob([u.caCertPem],{type:`application/x-pem-file`}),t=URL.createObjectURL(e),n=document.createElement(`a`);n.href=t,n.download=`camstack-ca.crt`,n.click(),URL.revokeObjectURL(t)},C=u?.mode===`uploaded`?`Uploaded`:u?.mode===`generated`?`Generated local CA`:`TLS disabled`;return d(rt,{headingId:`local-access-certificate`,title:e(`system.localAccess.certificate`,`Certificate`),icon:x,children:a(`div`,{className:`${p} space-y-3`,children:[n.isError&&d(`p`,{className:`text-xs text-danger`,children:e(`system.localAccess.couldNotReadTlsStatus`,`Could not read TLS status.`)}),u?.reissueError&&d(H,{variant:`warning`,title:e(`system.localAccess.certificateReissue`,`Certificate reissue`),message:u.reissueError}),u?.restartRequired&&d(H,{variant:`warning`,title:e(`system.localAccess.restartRequired`,`Restart required`),message:e(`system.localAccess.theHttpsListenerStillServes`,`The HTTPS listener still serves the previous certificate. Restart the hub to apply it.`)}),u?.caMissing===!0&&d(H,{variant:`warning`,title:e(`system.localAccess.caMissingTitle`,`CA missing - devices cannot trust this hub`),message:e(`system.localAccess.caMissingBody`,"The uploaded certificate was not issued by a public CA and no CA was stored with it, so Download CA has nothing to hand out. Upload the certificate again together with its CA (for mkcert, the rootCA.pem in the folder `mkcert -CAROOT` prints).")}),u?.caReplacedAt!=null&&Qn(u.caReplacedAt)&&d(H,{variant:`warning`,title:e(`system.localAccess.caReplacedTitle`,`The local CA was replaced - re-install it on your devices`),message:e(`system.localAccess.caReplacedBody`,`The previous local CA had no name constraints: if its key ever leaked it could vouch for any website. The hub now uses a CA limited to private addresses and local names. Download it again and trust it on every phone and computer that used the old one (replaced {{when}}).`,{when:new Date(u.caReplacedAt).toLocaleString()})}),a(`dl`,{className:`grid grid-cols-1 gap-2 text-xs sm:grid-cols-2`,children:[a(`div`,{children:[d(`dt`,{className:`text-foreground-subtle`,children:e(`system.localAccess.mode`,`Mode`)}),d(`dd`,{className:`font-medium`,children:C})]}),a(`div`,{children:[d(`dt`,{className:`text-foreground-subtle`,children:e(`system.localAccess.validTo`,`Valid to`)}),d(`dd`,{className:`font-mono`,children:u?.validTo?new Date(u.validTo).toLocaleString():`—`})]}),a(`div`,{children:[d(`dt`,{className:`text-foreground-subtle`,children:e(`system.localAccess.leafSha256`,`Leaf SHA-256`)}),d(`dd`,{className:`font-mono`,title:u?.leafFingerprintSha256??void 0,children:$n(u?.leafFingerprintSha256??null)})]}),u?.storedUpload!=null&&a(`div`,{children:[d(`dt`,{className:`text-foreground-subtle`,children:e(`system.localAccess.storedUpload`,`Stored upload`)}),d(`dd`,{className:`font-medium`,children:e(`system.localAccess.storedUploadValue`,`valid to {{validTo}}, {{ca}}`,{validTo:new Date(u.storedUpload.validTo).toLocaleDateString(),ca:u.storedUpload.hasCa?e(`system.localAccess.storedUploadWithCa`,`with its CA`):e(`system.localAccess.storedUploadNoCa`,`no CA`)})})]}),a(`div`,{children:[d(`dt`,{className:`text-foreground-subtle`,children:e(`system.localAccess.caSha256`,`CA SHA-256`)}),d(`dd`,{className:`font-mono`,title:u?.caFingerprintSha256??void 0,children:u?.mode===`uploaded`&&u.caFingerprintSha256===null?d(`span`,{className:`font-sans text-foreground-subtle`,children:e(`system.localAccess.issuerNotIncludedInThe`,`Issuer not included in the upload (not the local CA)`)}):$n(u?.caFingerprintSha256??null)})]})]}),u&&u.sans.length>0&&d(`div`,{className:`flex flex-wrap gap-1`,children:u.sans.map(e=>d(`span`,{className:`rounded border border-border bg-surface px-1.5 py-0.5 font-mono text-[10px] text-foreground-subtle`,children:e},e))}),a(`div`,{className:`flex flex-wrap gap-2`,children:[d(Je,{label:e(`system.localAccess.regenerate`,`Regenerate`),title:e(`system.localAccess.issueANewLeaf`,`Issue a new leaf?`),description:e(`system.localAccess.issuesANewLeafUnder`,`Issues a new leaf under the current local CA. Clients that trust the CA keep working. The HTTPS listener reloads.`),confirmLabel:e(`system.localAccess.regenerate`,`Regenerate`),disabled:u?.mode===`uploaded`||i.isPending,action:()=>i.mutateAsync({})}),d(W,{size:`sm`,variant:`outline`,onClick:()=>m(e=>!e),children:e(`system.localAccess.upload`,`Upload`)}),u?.caCertPem&&d(W,{size:`sm`,variant:`outline`,onClick:S,children:e(`system.localAccess.downloadCa`,`Download CA`)}),u?.mode===`uploaded`&&d(Je,{label:e(`system.localAccess.revertToGenerated`,`Revert to generated`),title:e(`system.localAccess.revertTitle`,`Switch back to the generated certificate?`),description:e(`system.localAccess.keepsTheUploadedPair`,`Returns to the generated local CA. The uploaded certificate and its CA stay stored here; you can select them again.`),confirmLabel:e(`system.localAccess.revert`,`Revert`),disabled:o.isPending,action:()=>o.mutateAsync({})}),u?.mode===`generated`&&u.storedUpload!=null&&d(Je,{label:e(`system.localAccess.useUploaded`,`Use uploaded certificate`),title:e(`system.localAccess.useUploadedTitle`,`Serve the stored upload again?`),description:e(`system.localAccess.useUploadedDescription`,`The stored uploaded certificate replaces the generated one on the HTTPS listener. The generated certificate stays stored.`),confirmLabel:e(`system.localAccess.useUploaded`,`Use uploaded certificate`),disabled:s.isPending,action:()=>s.mutateAsync(void 0)})]}),f&&a(`div`,{className:`space-y-2 border-t border-border pt-3`,children:[d(Xn,{kind:`certificate`,label:e(`system.localAccess.certificateOrFullChainPem`,`Certificate or full chain (PEM)`),value:h,onChange:g}),d(Xn,{kind:`privateKey`,label:e(`system.localAccess.privateKeyPem`,`Private key (PEM)`),value:_,onChange:v}),d(Xn,{kind:`ca`,label:e(`system.localAccess.caPemRequired`,`CA (PEM) - required unless the certificate comes from a public CA`),value:y,onChange:b,rows:4}),d(W,{size:`sm`,disabled:!h.trim()||!_.trim()||Jn(`certificate`,h)!==null||Jn(`privateKey`,_)!==null||Jn(`ca`,y)!==null||l.isPending,onClick:()=>l.mutate({certPem:h,keyPem:_,...y.trim()?{caPem:y}:{}}),children:e(`system.localAccess.saveCertificate`,`Save certificate`)}),l.isError&&d(`p`,{className:`text-xs text-danger`,children:l.error instanceof Error?l.error.message:e(`system.localAccess.uploadFailed`,`Upload failed`)})]})]})})}var tr={ok:`text-foreground-subtle`,soon:`text-warning`,expired:`text-danger`,unknown:`text-foreground-subtle`};function nr(e){let t=e.find(e=>e.isHub);return t?.https.kind===`served`?t.https.status.caFingerprintSha256:null}function rr({https:e,mesh:t,now:n}){let{t:r}=Y(),i=fe().data?.caCertPem??``,o=()=>{if(i===``)return;let e=URL.createObjectURL(new Blob([i],{type:`application/x-pem-file`})),t=document.createElement(`a`);t.href=e,t.download=`camstack-ca.crt`,t.click(),URL.revokeObjectURL(e)},s=t?.ca,c=s?.state===`ready`?Date.parse(s.validTo):null,l=t?.listener;return a(`div`,{className:`space-y-1`,"data-testid":`ca-strip`,children:[d(q,{label:r(`certificates.caStrip.localHttpsCaSha256`,`Local HTTPS CA (SHA-256)`),valueClassName:`font-mono`,children:a(`span`,{className:`flex flex-wrap items-center gap-2`,children:[nr(e)??`—`,i!==``&&a(W,{type:`button`,variant:`ghost`,size:`sm`,onClick:o,children:[d(b,{className:`h-3 w-3`,"aria-hidden":!0}),r(`certificates.caStrip.downloadCa`,`Download CA`)]})]})}),d(q,{label:r(`certificates.caStrip.clusterCaSha256`,`Cluster CA (SHA-256)`),valueClassName:`font-mono`,children:s===void 0?`—`:s.state===`ready`?s.fingerprintSha256:d(`span`,{className:`text-danger`,children:r(`certificates.caStrip.unavailable`,{reason:s.reason})})}),s?.state===`ready`&&a(q,{label:r(`certificates.caStrip.clusterCaValidUntil`,`Cluster CA valid until`),children:[s.validTo,c!==null&&!Number.isNaN(c)&&a(`span`,{className:`ml-2 text-[10px] ${tr[Ut(c,n)]}`,children:[`(`,kt(c,n),`)`]})]}),l!==void 0&&a(q,{label:r(`certificates.caStrip.nodeListener`,`Node listener`),children:[l.state===`open`&&d(G,{variant:`success`,children:r(`certificates.caStrip.open`,`Open`)}),l.state===`not-started`&&d(G,{variant:`default`,children:r(`certificates.caStrip.notStarted`,`Not started`)}),l.state===`closed`&&a(`span`,{className:`text-danger`,children:[r(`certificates.caStrip.closedSince`,{when:At(l.since)}),` `,l.reason]})]}),t!==void 0&&!t.registryAvailable&&a(`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:[d(_,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-warning`,"aria-hidden":!0}),d(`span`,{children:r(`certificates.caStrip.theCertificateRegistryIsNot`,`The certificate registry is not up, so the node list below is incomplete.`)})]})]})}function ir(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 ar(e){return e.isHub?J.t(`helpers.nodesModel.hubReissued`):e.mesh===null?J.t(`helpers.nodesModel.noCertRecorded`):e.online?null:J.t(`helpers.certificateModel.nodeOffline`)}function or(e){return e.isHub||e.mesh===null?ar(e):null}var sr={ok:`text-foreground-subtle`,soon:`text-warning`,expired:`text-danger`,unknown:`text-foreground-subtle`},cr={enroll:`Issued at enrollment`,renewal:`Issued by a renewal`,boot:`Issued at boot`,pairing:`Issued at pairing`,observed:`Observed on its connection`},lr={uploaded:`Uploaded`,generated:`Generated`,disabled:`Disabled`};function ur(e){let t=e.https?.https;return t?.kind===`served`?Vt(t.status.validTo):null}function dr({ms:e,now:t}){return e===null?d(`span`,{className:`text-foreground-subtle`,children:`—`}):a(`div`,{children:[d(`div`,{children:At(e)}),d(`div`,{className:`text-[10px] ${sr[Ut(e,t)]}`,children:kt(e,t)})]})}function fr({row:e}){let{t}=Y(),n=e.https?.https;return n===void 0?d(`span`,{className:`text-foreground-subtle`,children:`—`}):n.kind===`served`?a(`div`,{title:n.status.leafFingerprintSha256??``,children:[d(G,{variant:`success`,className:`text-[10px]`,children:t(`certificates.nodesColumns.served`,`Served`)}),d(`span`,{className:`ml-1.5 text-[10px] text-foreground-subtle`,children:lr[n.status.mode]}),d(`div`,{className:`mt-1 font-mono text-[10px] text-foreground-subtle`,children:Bt(n.status.leafFingerprintSha256)}),n.status.sans.length>0&&d(`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(`, `)})]}):a(`div`,{className:`max-w-[16rem]`,children:[d(G,{variant:n.kind===`unreadable`?`danger`:`warning`,className:`text-[10px]`,children:n.kind===`unreadable`?t(`certificates.nodesColumns.unreadable`,`Unreadable`):t(`certificates.nodesColumns.notServed`,`Not served`)}),d(`div`,{className:`mt-1 whitespace-normal text-[10px] text-foreground-subtle`,children:n.reason})]})}function pr({row:e}){let{t}=Y(),n=e.mesh?.current??null;if(n===null)return d(`span`,{className:`text-foreground-subtle`,children:t(`certificates.nodesColumns.noneRecorded`,`None recorded`)});let r=e.mesh?.history.length??0;return a(`div`,{children:[d(`div`,{className:`font-mono text-[11px]`,title:n.serial,children:Lt(n.serial)}),d(`div`,{className:`font-mono text-[10px] text-foreground-subtle`,title:n.fingerprintSha256,children:Bt(n.fingerprintSha256)}),a(`div`,{className:`text-[10px] text-foreground-subtle`,children:[cr[n.issuedVia],r>0?` · ${t(`certificates.nodesColumns.earlier`,{count:r})}`:``]})]})}function mr({row:e}){let{t}=Y(),n=e.mesh?.presentingCurrent??null;return n===null?d(`span`,{className:`text-foreground-subtle`,children:e.online?`—`:t(`certificates.nodesColumns.offline`,`Offline`)}):n?d(G,{variant:`success`,className:`text-[10px]`,children:t(`common.yes`,`Yes`)}):d(G,{variant:`warning`,className:`text-[10px]`,children:t(`certificates.nodesColumns.noPresentsAnother`,`No - presents another`)})}function hr(e){let t=e.icon;return a(W,{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?d(A,{className:`h-3 w-3 animate-spin`,"aria-hidden":!0}):d(t,{className:`h-3 w-3`,"aria-hidden":!0}),e.label]})}function gr({reasons:e}){let{t}=Y();return a(ge,{className:`inline-block`,children:[d(Xe,{children:d(`span`,{className:`cursor-help text-[11px] text-foreground-subtle`,"data-testid":`hub-managed-note`,children:t(`certificates.nodesColumns.managedByTheHub`,`Managed by the hub`)})}),d(Se,{children:d(`ul`,{className:`max-w-xs space-y-1 whitespace-normal text-left text-[11px]`,children:e.map(e=>d(`li`,{children:e},e))})})]})}function _r({row:e,o:t}){let{t:n}=Y(),r=e.https===null?`No HTTPS inventory for this node.`:jt(e.https).reason,i=ar(e),o=or(e),s=n=>t.running?.nodeId===e.nodeId&&t.running.action===n,c=t=>!e.isHub||t===null,l=[r,i,o].filter((e,t,n)=>e!==null&&n.indexOf(e)===t);return a(`div`,{className:`flex w-44 flex-col items-end gap-1`,children:[a(`div`,{className:`flex flex-col items-end gap-0.5`,children:[c(r)&&d(hr,{label:n(`certificates.nodesColumns.renewHttps`,`Renew HTTPS`),ariaLabel:n(`certificates.nodesColumns.renewTheCertificateOn`,`Renew the certificate on {{nodeId}}`,{nodeId:e.nodeId}),icon:S,reason:r,busy:t.busy,spinning:s(`renew-https`),danger:!1,onClick:()=>t.onRenewHttps(e)}),c(i)&&d(hr,{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:S,reason:i,busy:t.busy,spinning:s(`renew-identity`),danger:!1,onClick:()=>t.onRenewIdentity(e)}),c(o)&&d(hr,{label:n(`certificates.nodesColumns.revokeIdentity`,`Revoke identity`),ariaLabel:n(`certificates.nodesColumns.revokeTheClusterCertificateOf`,`Revoke the cluster certificate of {{nodeId}}`,{nodeId:e.nodeId}),icon:h,reason:o,busy:t.busy,spinning:s(`revoke-identity`),danger:!0,onClick:()=>t.onRevokeIdentity(e)})]}),e.isHub&&l.length>0&&d(gr,{reasons:l}),!e.isHub&&r!==null&&e.https!==null&&d(`div`,{className:`w-full whitespace-normal text-right text-[10px] text-foreground-subtle`,"data-testid":`renew-reason-${e.nodeId}`,children:r}),!e.isHub&&i!==null&&d(`div`,{className:`w-full whitespace-normal text-right text-[10px] text-foreground-subtle`,"data-testid":`mesh-reason-${e.nodeId}`,children:i})]})}function vr(e){return[{key:`node`,header:J.t(`certificates.nodesColumns.node`,`Node`),sortValue:e=>e.isHub?``:e.nodeId.toLowerCase(),render:e=>a(`div`,{className:`flex items-center gap-1.5`,children:[d(`span`,{className:`font-medium text-foreground`,children:e.nodeId}),e.nodeId===`hub`&&d(G,{variant:`info`,className:`text-[10px]`,children:J.t(`common.hubWord`)}),!e.online&&d(G,{variant:`default`,className:`text-[10px]`,children:J.t(`common.offline`)})]})},{key:`https-state`,header:`HTTPS`,notSortableReason:`A state with a reason has no single order.`,render:e=>d(fr,{row:e})},{key:`https-expires`,header:J.t(`certificates.nodesColumns.httpsExpires`,`HTTPS expires`),sortValue:e=>ur(e),render:t=>d(dr,{ms:ur(t),now:e.now})},{key:`identity`,header:J.t(`certificates.nodesColumns.identity`,`Identity`),sortValue:e=>e.mesh?.current?.serial??null,render:e=>d(pr,{row:e})},{key:`identity-expires`,header:J.t(`certificates.nodesColumns.identityExpires`,`Identity expires`),sortValue:e=>e.mesh?.current?.notAfter??null,render:t=>d(dr,{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=>d(mr,{row:e})},{key:`actions`,header:J.t(`certificates.nodesColumns.actions`,`Actions`),align:`right`,notSortableReason:`Actions have no order.`,render:t=>d(_r,{row:t,o:e})}]}e();function yr(){let{t:e}=Y(),t=V(),i=K.useUtils(),o=Rn(6e4),s=K.certificates.listHttpsCertificates.useQuery(),c=K.certificates.getMeshCertificates.useQuery(),[l,u]=r(null),[f,p]=r(null),[m,h]=r(null),g=()=>{h(null),i.certificates.listHttpsCertificates.invalidate(),i.certificates.getMeshCertificates.invalidate()},_=e=>(t,n)=>{h(null),u(`${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(It(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)=>{u(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}))},T=e=>{S(e.nodeId,`renew-identity`),y.mutate({nodeId:e.nodeId})},E=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}))},D=vr({now:o,busy:x,running:m,onRenewHttps:e=>void C(e),onRenewIdentity:T,onRevokeIdentity:e=>void E(e)}),O=n(()=>ir(s.data??[],c.data),[s.data,c.data]),k=c.data?.registryAvailable??!0;return d(X,{id:`nodes`,title:e(`certificates.nodesCard.nodes`,`Nodes`),icon:w,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:Ft(l,f),onDismissNotice:()=>{u(null),p(null)},children:d(Fn,{isPending:s.isPending||c.isPending,error:s.error??c.error,what:`node certificates`,onRetry:()=>{s.refetch(),c.refetch()},children:a(`div`,{className:`space-y-3`,children:[d(rr,{https:s.data??[],mesh:c.data,now:o}),d(Le,{columns:D,rows:O,rowKey:e=>e.nodeId,minWidthPx:960,maxBodyHeight:at,defaultSort:{columnKey:`node`,dir:`asc`},emptyMessage:k?e(`certificates.nodesCard.noNodesReported`,`No nodes reported.`):e(`certificates.nodesCard.theCertificateRegistryIsNot`,`The certificate registry is not available yet, so nodes cannot be listed.`)})]})})})}function br({pairOpen:e,onPairClose:t}){return a(`div`,{className:`space-y-4`,"data-testid":`certificates-page`,children:[d(Wn,{pairOpen:e,onPairClose:t}),d(In,{}),d(er,{}),d(yr,{})]})}function xr({userId:e,username:t,onClose:n}){let{t:r}=Y(),i=V(),o=K.useUtils(),s=Ue({userId:e}),c=K.auth.listLoginMethods.useQuery(),l=we({onSuccess:()=>void o.userManagement.listExternalIdentities.invalidate()}),u=new Map((c.data??[]).flatMap(e=>e.kind===`redirect`?[[e.id,e.label]]:[])),f=s.data??[],p=async(n,a)=>{await i({title:r(`users.externalIdentitiesModal.removeSignInLink`,`Remove sign-in link`),message:r(`users.externalIdentitiesModal.willNoLongerBeAble`,`"{{username}}" will no longer be able to sign in with this {{label}} account.`,{username:t,label:a}),confirmLabel:r(`common.remove`,`Remove`),variant:`danger`})&&l.mutate({userId:e,provider:n.provider,subject:n.subject})};return d(Ke,{open:!0,onOpenChange:e=>!e&&n(),children:a(Re,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`external-identities-modal`,children:[d(qe,{children:a(Ve,{className:`flex items-center gap-2`,children:[d(D,{className:`h-4 w-4 text-primary`}),a(`span`,{children:[r(`users.externalIdentitiesModal.linkedSignInAccounts`,`Linked sign-in accounts`),a(`span`,{className:`mt-0.5 block text-[11px] font-normal text-foreground-subtle`,children:[r(`users.externalIdentitiesModal.user`,`User:`),` `,d(`span`,{className:`font-mono`,children:t})]})]})]})}),d(et,{className:`space-y-3`,children:s.isLoading?a(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[d(A,{className:`h-3.5 w-3.5 animate-spin`}),r(`common.loading`,`Loading…`)]}):f.length===0?d(`p`,{className:`text-xs text-foreground-subtle`,children:r(`users.externalIdentitiesModal.noLinkedAccountsOnlyThe`,`No linked accounts. Only the user can link one, from their own profile page.`)}):d(`ul`,{className:`divide-y divide-border rounded-md border border-border`,children:f.map(e=>{let t=u.get(e.provider),n=t??e.provider;return a(`li`,{className:`flex items-center gap-3 px-3 py-2 text-xs`,children:[a(`div`,{className:`flex-1 min-w-0`,children:[a(`div`,{className:`font-medium text-foreground truncate`,children:[n,t===void 0&&d(`span`,{className:`ml-2 rounded bg-foreground-subtle/15 px-1.5 py-0.5 text-[10px] font-normal text-foreground-subtle`,children:r(`users.externalIdentitiesModal.providerUnavailable`,`provider unavailable`)})]}),a(`div`,{className:`text-[11px] text-foreground-subtle truncate`,children:[e.label??e.subject,` ·`,` `,new Date(e.linkedAt).toLocaleDateString()]})]}),a(`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:[d(le,{className:`h-3 w-3`}),r(`common.remove`,`Remove`)]})]},`${e.provider}|${e.subject}`)})})}),d(Ye,{children:d(W,{onClick:n,variant:`secondary`,children:r(`common.close`,`Close`)})})]})})}function Sr({userId:e,username:t,onClose:n}){let{t:r}=Y(),i=c(),o=V(),l=ue({userId:e}),u=l.data,p=()=>i.invalidateQueries({queryKey:[[`userManagement`,`getTotpStatus`]]}),m=Ge({onSuccess:()=>{p(),n()}}),h=l.isLoading?`loading`:u?.enabled?`enrolled`:`not_enrolled`;return d(Ke,{open:!0,onOpenChange:e=>!e&&n(),children:a(Re,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,children:[d(qe,{children:a(Ve,{className:`flex items-center gap-2`,children:[d(f,{className:`h-4 w-4 text-primary`}),a(`span`,{children:[r(`users.totpModal.twoFactorAuthentication`,`Two-factor authentication`),a(`span`,{className:`mt-0.5 block text-[11px] font-normal text-foreground-subtle`,children:[r(`users.totpModal.user`,`User:`),` `,d(`span`,{className:`font-mono`,children:t})]})]})]})}),a(et,{className:`space-y-4`,children:[h===`loading`&&a(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[d(A,{className:`h-3.5 w-3.5 animate-spin`}),r(`users.totpModal.checkingStatus`,`Checking status…`)]}),h===`not_enrolled`&&a(`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:[d(k,{className:`h-4 w-4 mt-0.5 shrink-0`}),a(`div`,{children:[d(`div`,{className:`font-medium text-foreground`,children:r(`users.totpModal.2faNotEnrolled`,`2FA not enrolled`)}),d(`p`,{className:`mt-0.5`,children:r(`users.totpModal.onlyTheUserThemselvesCan`,`Only the user themselves can enable 2FA, from their own profile page.`)})]})]}),h===`enrolled`&&u&&a(s,{children:[a(`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:[d(O,{className:`h-4 w-4 mt-0.5 text-emerald-500 shrink-0`}),a(`div`,{className:`text-xs text-foreground space-y-0.5`,children:[d(`div`,{className:`font-medium`,children:r(`users.totpModal.2faIsActive`,`2FA is active`)}),d(`div`,{className:`text-foreground-subtle`,children:r(`common.enrolledOn`,{when:u.confirmedAt?new Date(u.confirmedAt).toLocaleString():`—`})})]})]}),d(`div`,{className:`text-[11px] text-foreground-subtle`,children:r(`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.`)}),a(`div`,{className:`flex justify-end gap-2`,children:[d(W,{onClick:n,variant:`secondary`,children:r(`common.close`,`Close`)}),a(`button`,{onClick:async()=>{await o({title:r(`users.totpModal.remove2fa`,`Remove 2FA`),message:r(`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:r(`common.remove`,`Remove`),variant:`danger`})&&m.mutate({userId:e})},disabled:m.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:[m.isPending?d(A,{className:`h-3 w-3 animate-spin`}):d(T,{className:`h-3 w-3`}),r(`users.totpModal.remove2fa`,`Remove 2FA`)]})]})]})]})]})})}e();function Cr({userId:e,username:t,onClose:n}){let{t:i}=Y(),{user:o,logout:s}=dt(),c=o?.id===e,l=V(),u=K.useUtils(),f=K.auth.listSessions.useQuery({userId:e}),[p,m]=r(null),h=K.auth.revokeSessions.useMutation({onSuccess:(e,t)=>{if(c&&`userId`in t){s();return}u.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:Wt(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:c?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 d(Ke,{open:!0,onOpenChange:e=>!e&&n(),children:a(Re,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`user-sessions-modal`,children:[d(qe,{children:a(Ve,{className:`flex items-center gap-2`,children:[d(ce,{className:`h-4 w-4 text-primary`}),a(`span`,{children:[i(`users.userSessionsModal.activeSessions`,`Active sessions`),a(`span`,{className:`mt-0.5 block text-[11px] font-normal text-foreground-subtle`,children:[i(`users.userSessionsModal.user`,`User:`),` `,d(`span`,{className:`font-mono`,children:t})]})]})]})}),a(et,{className:`space-y-3`,children:[p!==null&&d(`div`,{className:`text-[11px] text-danger`,children:p}),d(Ht,{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})]}),a(Ye,{className:`justify-between`,children:[a(`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?d(A,{className:`h-3 w-3 animate-spin`}):d(oe,{className:`h-3 w-3`}),i(`users.userSessionsModal.signOutEverywhere`,`Sign out everywhere`)]}),d(W,{onClick:n,variant:`secondary`,children:i(`common.close`,`Close`)})]})]})})}function wr({scopes:e,invalidReason:t}){let{t:n}=Y(),r=ee(),i=o({queryKey:[`auth`,`previewScope`,e,!1],enabled:t===null,queryFn:()=>r.trpcClient.auth.previewScope.query({scopes:[...e],isAdmin:!1})}),{data:s}=Ze({projection:`slim`}),c=s?.length??null;if(t!==null)return a(`p`,{className:`flex items-center gap-1.5 text-[11px] text-warning`,"data-testid":`role-preview`,children:[d(C,{className:`h-3 w-3 shrink-0`}),t]});if(i.isLoading)return a(`p`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,"data-testid":`role-preview`,children:[d(A,{className:`h-3 w-3 shrink-0 animate-spin`}),n(`users.rolePreview.resolving`)]});if(i.isError||!i.data)return d(`p`,{className:`text-[11px] text-danger`,"data-testid":`role-preview`,children:n(`users.rolePreview.couldNotResolve`)});let l=i.data.viewableDeviceCount,u=i.data.device.view.all?n(`users.rolePreview.everyDevice`,{count:l}):c===null?n(`users.rolePreview.devicesVisible`,{count:l}):n(`users.rolePreview.devicesVisibleOf`,{count:l,total:c});return a(`p`,{className:`flex items-center gap-1.5 text-[11px] ${l===0?`text-warning`:`text-foreground`}`,"data-testid":`role-preview`,children:[l===0?d(C,{className:`h-3 w-3 shrink-0`}):d(v,{className:`h-3 w-3 shrink-0 text-foreground-subtle`}),l===0?n(`users.rolePreview.noDevice`):u]})}function Tr(e){let t=R(e.scopes??[]);if(t===null)return{role:e.isAdmin?`admin`:`viewer`,mode:`except`,pickedIds:[],viewer:L,unconfigured:!e.isAdmin};let n=Mr(t);return{role:e.isAdmin?`admin`:`viewer`,mode:n.mode,pickedIds:n.pickedIds,viewer:Nr(n.mode,n.pickedIds,t.features),unconfigured:!1}}function Er(e,t){return{...e,role:t}}function Dr(e,t){return{...e,mode:t,viewer:Nr(t,e.pickedIds,e.viewer.features)}}function Or(e,t){let n=Pr(t);return{...e,pickedIds:n,viewer:Nr(e.mode,n,e.viewer.features)}}function kr(e,t,n){let r=e.viewer.features.filter(e=>e!==t),i=n?[...r,t]:r;return{...e,viewer:Nr(e.mode,e.pickedIds,i)}}function Ar(e){return e.role===`viewer`&&e.mode===`only`&&e.pickedIds.length===0?`no-allowed-device`:null}function jr(e){return Ar(e)===null?e.role===`admin`?{isAdmin:!0,scopes:[]}:{isAdmin:!1,scopes:[e.viewer]}:null}function Mr(e){if(e.allow===`*`)return{mode:`except`,pickedIds:e.block};let t=new Set(e.block);return{mode:`only`,pickedIds:e.allow.filter(e=>!t.has(e))}}function Nr(e,t,n){let r=Pr(t);return e===`except`?{type:`viewer`,allow:`*`,block:r,features:[...n]}:{type:`viewer`,allow:r,block:[],features:[...n]}}function Pr(e){return[...new Set(e)]}e();var Fr=`text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle`;function Ir(e,t){return e?`failed`:t===void 0?`pending`:`answered`}function Lr(e){let t=[];for(let n of e)n.parentDeviceId===null&&t.push({id:n.id,name:n.name,type:String(n.type),...n.location===null?{}:{location:n.location}});return t}function Rr({user:e,isSelf:t,onClose:i,onSubmit:o,submitting:c,error:l}){let{t:u}=Y(),[f,p]=r(n(()=>Tr(e),[e])),m=Ze({projection:`slim`}),h=m.data,g=Ir(m.isError,h),_=n(()=>Lr(h??[]),[h]),v=n(()=>({state:g,devices:g===`answered`?(h??[]).map(e=>({id:e.id,name:e.name})):void 0}),[g,h]),y=Ar(f),b=jr(f),x=y===`no-allowed-device`?u(`users.userAccessModal.pickAllowedDevice`):null,S=e=>{p(Er(f,e))},C=[{value:`except`,label:u(`users.userAccessModal.modeExcept`)},{value:`only`,label:u(`users.userAccessModal.modeOnly`)}];return d(Ke,{open:!0,onOpenChange:e=>!e&&i(),children:a(Re,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,className:`md:max-w-2xl`,children:[d(qe,{children:d(Ve,{children:u(`users.userAccessModal.title`,{name:e.username})})}),a(et,{className:`space-y-4`,children:[f.unconfigured&&f.role===`viewer`&&d(H,{variant:`warning`,title:u(`users.userAccessModal.noAccessYet`),message:u(`users.userAccessModal.noAccessYetDetail`,{name:e.username})}),a(`section`,{className:`space-y-2`,children:[d(`h3`,{className:Fr,children:u(`users.userAccessModal.role`)}),a(`div`,{role:`radiogroup`,"aria-label":u(`users.userAccessModal.role`),className:`grid gap-1.5 sm:grid-cols-2`,children:[d(zr,{name:`admin`,checked:f.role===`admin`,label:u(`users.userAccessModal.admin`),description:u(`users.userAccessModal.adminDescription`),onPick:()=>S(`admin`)}),d(zr,{name:`viewer`,checked:f.role===`viewer`,disabled:t,label:u(`users.userAccessModal.viewer`),description:u(t?`users.userAccessModal.cannotDemoteSelf`:`users.userAccessModal.viewerDescription`),onPick:()=>S(`viewer`)})]})]}),f.role===`viewer`&&a(s,{children:[a(`section`,{className:`space-y-3`,children:[d(`h3`,{className:Fr,children:u(`users.userAccessModal.devices`)}),d($e,{label:u(`users.userAccessModal.whichDevices`),value:f.mode,options:C,onChange:e=>p(Dr(f,e))}),d(Ce,{devices:_,listState:g,fleet:v,value:[...f.pickedIds],onChange:e=>p(Or(f,e)),emptyMeansAll:f.mode===`except`,noun:`device`,testId:`viewer-device-picker`}),d(wr,{scopes:b?.scopes??[],invalidReason:x})]}),a(`section`,{className:`space-y-2`,children:[d(`h3`,{className:Fr,children:u(`users.userAccessModal.features`)}),d(`div`,{className:`space-y-1`,children:P.map(e=>a(`label`,{className:`flex cursor-pointer items-start gap-2 rounded-md p-1.5 hover:bg-surface-hover`,children:[d(Ne,{className:`mt-0.5`,checked:f.viewer.features.includes(e.id),onChange:t=>p(kr(f,e.id,t.target.checked))}),a(`span`,{className:`min-w-0`,children:[d(`span`,{className:`block text-[12px] font-medium text-foreground`,children:u(`users.viewerFeatures.${e.id}.label`,e.label)}),d(`span`,{className:`block text-[10px] text-foreground-subtle`,children:u(`users.viewerFeatures.${e.id}.description`,e.description)})]})]},e.id))})]})]}),l!==null&&d(H,{message:l})]}),a(Ye,{children:[d(W,{variant:`outline`,size:`sm`,onClick:i,children:u(`common.cancel`,`Cancel`)}),d(W,{size:`sm`,onClick:()=>b!==null&&o(b),disabled:c||b===null,children:c?d(A,{className:`h-3 w-3 animate-spin`}):u(`users.userAccessModal.saveAccess`)})]})]})})}function zr({name:e,checked:t,disabled:n=!1,label:r,description:i,onPick:o}){return a(`label`,{className:`flex items-start gap-2 rounded-lg border p-2.5 transition-colors ${t?`border-primary bg-primary/5`:`border-border hover:bg-surface-hover`} ${n?`cursor-not-allowed opacity-60`:`cursor-pointer`}`,children:[d(`input`,{type:`radio`,name:`user-role`,value:e,checked:t,disabled:n,onChange:o,className:`mt-0.5`}),a(`span`,{className:`min-w-0`,children:[d(`span`,{className:`block text-[12px] font-medium text-foreground`,children:r}),d(`span`,{className:`block text-[10px] text-foreground-subtle`,children:i})]})]})}e();var Br=8;function Vr(){return{username:``,password:``,isAdmin:!1}}function Hr(e){return{id:e.id,username:e.username,password:``,isAdmin:e.isAdmin}}function Ur(e){return e instanceof Error?e.message:J.t(`admin.system.users.genericError`)}function Wr(){let{t:e}=Y(),n=c(),{user:i}=dt(),{state:o,openNew:l,openEdit:u,close:p}=tt(),[h,_]=r(null),[v,b]=r(null),[x,S]=r(!1),{data:C,isLoading:w,isError:T,error:O,refetch:k}=De(),ee=V(),j=Pe(),M=()=>n.invalidateQueries({queryKey:[[`userManagement`,`listUsers`]]}),P=pe(),F=Oe({onSuccess:M}),I=je({onSuccess:M}),L=ke({onSuccess:M}),te=be(),[R,z]=r(null),[ne,re]=r(!1),[ae,B]=r(null),[oe,se]=r(null),[le,ue]=r(null),[de,fe]=r(null),me=C??[],U=o.mode===`edit`?me.find(e=>e.id===o.id)??null:null,he=()=>{_(null),b(null),S(!1),P.reset(),I.reset(),p()};t(()=>{if(o.mode===`closed`){_(null),b(null),S(!1);return}if(o.mode===`new`){_(e=>e!==null&&e.id===void 0?e:Vr());return}if(U===null){w||p();return}_(e=>e?.id===U.id?e:Hr(U))},[o,U,w,p]);let ge=o.mode===`new`&&h!==null&&h.id===void 0||o.mode===`edit`&&h!==null&&U!==null;async function _e(t){await ee({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`})&&(F.mutate({id:t.id}),o.mode===`edit`&&o.id===t.id&&he())}async function ve(t){let n=await j({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<Br?J.t(`admin.system.users.passwordTooShort`,{min:Br}):null});n===null||n.length===0||await ee({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`)})&&L.mutate({id:t.id,newPassword:n})}function ye(e){B(null),z(e)}async function Se(e,t){re(!0),B(null);try{t.isAdmin!==e.isAdmin&&await I.mutateAsync({id:e.id,isAdmin:t.isAdmin}),await te.mutateAsync({userId:e.id,scopes:[...t.scopes]}),z(null)}catch(e){B(Ur(e))}finally{re(!1),M()}}async function Ce(){if(h!==null){b(null);try{if(h.id===void 0){let e=h.username.trim();if(e===``||h.password.length<Br)return;await P.mutateAsync({username:e,password:h.password,isAdmin:h.isAdmin})}else await I.mutateAsync({id:h.id,isAdmin:h.isAdmin});M(),he()}catch(e){b(Ur(e))}}}function we(e){return e?new Date(typeof e==`number`?e:String(e)).toLocaleDateString(`en-GB`,{day:`2-digit`,month:`short`,year:`numeric`}):`—`}let Te=P.isPending||I.isPending,Ee=h!==null&&h.id===void 0&&h.username.trim()!==``&&h.password.length>=Br,Ae=h!==null&&h.id!==void 0,Me=Te||(h?.id===void 0?!Ee:!Ae),Ne=e=>F.isPending&&F.variables?.id===e.id||I.isPending&&I.variables?.id===e.id||L.isPending&&L.variables?.id===e.id,G=[{key:`username`,header:e(`admin.system.users.username`,`Username`),sortValue:e=>e.username,render:e=>d(`span`,{className:`font-medium text-foreground`,"data-testid":`user-open-${e.id}`,children:e.username})},{key:`scopes`,header:e(`admin.system.users.access`,`Access`),sortValue:e=>Gr(e),render:t=>d(`span`,{onClick:e=>e.stopPropagation(),children:a(W,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>ye(t),disabled:Ne(t),title:e(`admin.system.users.configureAccess`,`Configure access`),"data-testid":`user-access-${t.id}`,children:[d(N,{className:`h-3 w-3 shrink-0 text-foreground-subtle`}),d(Kr,{user:t})]})})},{key:`createdAt`,header:e(`admin.system.users.created`,`Created`),nowrap:!0,sortValue:e=>e.createdAt,render:e=>d(`span`,{className:`text-foreground-subtle`,children:we(e.createdAt)})},{key:`actions`,header:e(`admin.system.users.actions`,`Actions`),align:`right`,nowrap:!0,notSortableReason:`Row actions`,render:t=>{let n=Ne(t),r=t.id!==i?.id&&t.totpEnabled;return a(`div`,{className:`flex items-center justify-end gap-1`,onClick:e=>e.stopPropagation(),children:[a(W,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>u(t.id),disabled:n,title:e(`admin.system.users.editUser`,`Edit user`),children:[d(m,{className:`h-3 w-3`}),e(`common.edit`,`Edit`)]}),r&&a(W,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>se(t),disabled:n,title:e(`admin.system.users.removeTwoFactorAuthentication`,`Remove two-factor authentication`),children:[d(f,{className:`h-3 w-3`}),e(`admin.system.users.remove2fa`,`Remove 2FA`)]}),a(W,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>ue(t),disabled:n,title:e(`admin.system.users.linkedSignInAccounts`,`Linked sign-in accounts`),children:[d(D,{className:`h-3 w-3`}),e(`admin.system.users.signInLinks`,`Sign-in links`)]}),a(W,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>fe(t),disabled:n,title:e(`admin.system.users.activeSessions`,`Active sessions`),children:[d(ce,{className:`h-3 w-3`}),e(`admin.system.users.sessions`,`Sessions`)]}),a(W,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>void ve(t),disabled:n,title:e(`admin.system.users.resetPassword`,`Reset password`),children:[d(ie,{className:`h-3 w-3`}),e(`admin.system.users.resetPassword`,`Reset password`)]}),a(W,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>void _e(t),disabled:n,title:e(`admin.system.users.deleteUser`,`Delete user`),className:`text-danger hover:bg-danger/10`,children:[n?d(A,{className:`h-3 w-3 animate-spin`}):d(g,{className:`h-3 w-3`}),e(`common.delete`,`Delete`)]})]})}}];return a(bt,{embedded:!0,icon:y,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:a(W,{size:`sm`,type:`button`,onClick:()=>{b(null),l()},children:[d(E,{className:`h-3.5 w-3.5`}),e(`admin.system.users.createUser`,`Create User`)]}),children:[T&&d(H,{title:e(`admin.system.users.couldNotLoadUsers`,`Could not load users`),message:Ur(O),onRetry:()=>void k()}),w&&a(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[d(A,{className:`h-3.5 w-3.5 animate-spin`}),e(`common.loading`,`Loading…`)]}),!w&&!T&&me.length===0&&d(it,{icon:y,title:e(`admin.system.users.noUsersYet`,`No users yet`),description:e(`admin.system.users.createAUserToGrant`,`Create a user to grant hub access.`)}),!w&&!T&&me.length>0&&d(Le,{columns:G,rows:me,rowKey:e=>e.id,minWidthPx:560,maxBodyHeight:`max-h-[60vh]`,onRowClick:e=>u(e.id)}),d(Be,{open:ge,onClose:he,title:h?.id===void 0?e(`admin.system.users.createUser`,`Create User`):e(`admin.system.users.edit`,`Edit {{value1}}`,{value1:h.username||`user`}),icon:y,error:v,testId:`user-form-dialog`,footer:d(W,{size:`sm`,type:`button`,disabled:Me,onClick:()=>void Ce(),children:Te?a(s,{children:[d(A,{className:`h-3.5 w-3.5 animate-spin`}),e(`admin.system.users.saving`,`Saving…`)]}):h?.id===void 0?e(`admin.system.users.create`,`Create`):e(`common.save`,`Save`)}),children:h!==null&&a(`div`,{className:`space-y-3`,children:[d(ot,{label:e(`admin.system.users.username`,`Username`),required:h.id===void 0,children:d(xe,{value:h.username,onChange:e=>_({...h,username:e.target.value}),placeholder:`john`,autoFocus:h.id===void 0,disabled:h.id!==void 0,"data-testid":`user-form-username`})}),h.id===void 0&&d(ot,{label:e(`admin.system.users.password`,`Password`),required:!0,description:e(`admin.system.users.atLeastCharacters`,`At least {{value1}} characters.`,{value1:String(Br)}),children:d(Fe,{value:h.password,onValueChange:e=>_({...h,password:e}),shown:x,onToggleShown:()=>S(e=>!e),placeholder:`••••••••`,"data-testid":`user-form-password`})}),d(ot,{label:e(`admin.system.users.admin`,`Admin`),description:e(`admin.system.users.unrestrictedAccessToEveryCapability`,`Unrestricted access to every capability and device.`),children:a(`label`,{className:`inline-flex items-center gap-2 text-xs text-foreground cursor-pointer`,children:[d(`input`,{type:`checkbox`,checked:h.isAdmin,onChange:e=>_({...h,isAdmin:e.target.checked}),className:`rounded border-border focus:ring-primary`,"data-testid":`user-form-admin`}),d(`span`,{children:e(`admin.system.users.admin`,`Admin`)})]})}),h.id!==void 0&&d(`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.`)})]})}),oe&&d(Sr,{userId:oe.id,username:oe.username,onClose:()=>se(null)}),le&&d(xr,{userId:le.id,username:le.username,onClose:()=>ue(null)}),de&&d(Cr,{userId:de.id,username:de.username,onClose:()=>fe(null)}),R&&d(Rr,{user:R,isSelf:R.id===i?.id,onClose:()=>z(null),onSubmit:e=>void Se(R,e),submitting:ne,error:ae})]})}function Gr(e){let t=Tr(e);return t.role===`admin`?0:t.unconfigured?2:1}function Kr({user:e}){let{t}=Y(),n=Tr(e);if(n.role===`admin`)return d(`span`,{className:`font-medium text-foreground`,children:t(`users.accessSummary.admin`)});if(n.unconfigured)return d(`span`,{className:`font-medium text-warning`,children:t(`admin.system.users.noAccess`,`No access`)});let{allow:r,block:i,features:o}=n.viewer,c=r===`*`?t(`users.accessSummary.allDevices`):t(`users.accessSummary.devices`,{count:r.length});return a(`span`,{className:`text-foreground-subtle`,children:[d(`span`,{className:`font-medium text-foreground`,children:t(`users.accessSummary.viewer`)}),` ·`,` `,c,i.length>0&&a(s,{children:[` · `,t(`users.accessSummary.blocked`,{count:i.length})]}),o.length>0&&a(s,{children:[` · `,t(`users.accessSummary.features`,{count:o.length})]})]})}e();var qr={"api-keys":$.tokens,"linked-sessions":$.linkedApps},Jr=`certificates`;function Yr(e){return a(W,{size:`sm`,type:`button`,"data-testid":`certificates-pair-device`,onClick:e,children:[d(f,{className:`h-3.5 w-3.5`,"aria-hidden":!0}),J.t(`systemPage.identity.pairADevice`,`Pair a device`)]})}function Xr(){let{t:e}=Y(),[t]=pt(),n=bn(),[i,a]=r(!1),o=qr[t.get(`tab`)??``];if(o!==void 0)return d(ft,{to:ht(`access`,{integration:o}),replace:!0});let s=vt(`/system/identity`,{t:e,isAdmin:!0})??{icon:M,title:e(`system.identity`,`Identity & Access`)},c=t.get(`tab`)??`users`,l=t.get(`integration`),u=c===ct.access.tab?yn(l,n.requestCreate):c===`certificates`?Yr(()=>a(!0)):void 0;return d(yt,{icon:s.icon,title:s.title,defaultSection:`users`,sectionsLabel:`${s.title} sections`,actions:u,sections:[{id:`users`,label:e(`systemPage.identity.users`,`Users`),content:d(Wr,{})},{id:ct.access.tab,label:e(`systemPage.identity.tokensSessions`,`Tokens & sessions`),ownedParams:mt.concat([Mt.token,Mt.scoped,Mt.admin]),content:d(vn,{createRequested:n.createRequested,onCreateConsumed:n.clearCreate})},{id:Jr,label:e(`systemPage.identity.certificates`,`Certificates`),content:d(br,{pairOpen:i,onPairClose:()=>a(!1)})},{id:ct.authentication.tab,label:e(`systemPage.identity.authentication`,`Authentication`),content:d(Nn,{}),ownedParams:mt}]})}export{Xr as IdentityPage};
|