@camstack/addon-admin-ui 1.2.378 → 1.2.379

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/dist/assets/{AddonAssetIcon-Ag9UiFD6.js → AddonAssetIcon-02uy1lo7.js} +1 -1
  2. package/dist/assets/{AddonIntegrationBody-PmjCQ2Ms.js → AddonIntegrationBody-oV8coptw.js} +1 -1
  3. package/dist/assets/Addons-BBMJbtIk.js +4 -0
  4. package/dist/assets/AdminPage-C1SqQSAP.js +1 -0
  5. package/dist/assets/{AdminTabs-CYT0Gfgp.js → AdminTabs-D_amP_Ho.js} +1 -1
  6. package/dist/assets/AiProfiles-C_MUiJTn.js +3 -0
  7. package/dist/assets/{BrokerForm-AegeAXg9.js → BrokerForm-DWNdijlI.js} +1 -1
  8. package/dist/assets/Build-BmR1cbDt.js +40 -0
  9. package/dist/assets/{Calendars-VvqcFPuG.js → Calendars-BRWb4l_h.js} +1 -1
  10. package/dist/assets/Cluster-DEbpxrVi.js +1 -0
  11. package/dist/assets/ClusterStepModel-D-XsmHIE.js +1 -0
  12. package/dist/assets/CompositionEditor-D2Mdanul.js +1 -0
  13. package/dist/assets/{CompositionEditorPage-vgyZiJfZ.js → CompositionEditorPage-ClvOpgEi.js} +1 -1
  14. package/dist/assets/Data-DzzC8p_q.js +1 -0
  15. package/dist/assets/DeviceDetail-CJduuTAv.js +2 -0
  16. package/dist/assets/{DeviceDoActionFields-9IITqtOQ.js → DeviceDoActionFields-CLSOxEiv.js} +1 -1
  17. package/dist/assets/{Devices-Cyh6Qlqo.js → Devices-D0yIu4CH.js} +1 -1
  18. package/dist/assets/{EmbedPlayerPage-CdCpi5P_.js → EmbedPlayerPage-D_h14JKk.js} +1 -1
  19. package/dist/assets/{HeaderPills-Bml4Qa81.js → HeaderPills-DvZSXIv5.js} +1 -1
  20. package/dist/assets/Identity-feKhsBbU.js +1 -0
  21. package/dist/assets/IntegrationDetail-CP2OcwRx.js +1 -0
  22. package/dist/assets/Integrations-BcNYo6tG.js +1 -0
  23. package/dist/assets/Integrations-iBbhRDLT.js +1 -0
  24. package/dist/assets/Library-BqAUXKdv.js +1 -0
  25. package/dist/assets/Locations-B9gGlGQS.js +3 -0
  26. package/dist/assets/{Logs-EXjQjLNI.js → Logs-BmTVkon0.js} +1 -1
  27. package/dist/assets/MotionZonesSettings-BbOnxwDN.js +1 -0
  28. package/dist/assets/MyAccess-DDYlOEbm.js +2 -0
  29. package/dist/assets/Network-BtT9FApe.js +1 -0
  30. package/dist/assets/{NodeAddonsSettingsPanel-DsaDhenp.js → NodeAddonsSettingsPanel-BH_xJge-.js} +1 -1
  31. package/dist/assets/Notifications-DxjFdLCC.js +1 -0
  32. package/dist/assets/{PrivacyMaskSettings-CeROKF6d.js → PrivacyMaskSettings-B8E2Jjy5.js} +1 -1
  33. package/dist/assets/Recordings-Cx8-bDgI.js +1 -0
  34. package/dist/assets/{ScanNetworkModal-LKDbSzGe.js → ScanNetworkModal-N-j2iMnZ.js} +1 -1
  35. package/dist/assets/{SceneMonitorEditor-Dq2eAkcS.js → SceneMonitorEditor-BFZ3oTIz.js} +1 -1
  36. package/dist/assets/SessionsList-542JIoxX.js +2 -0
  37. package/dist/assets/{Showroom-Cpy2XosF.js → Showroom-fId0hCWU.js} +1 -1
  38. package/dist/assets/System-rx1MvWgE.js +1 -0
  39. package/dist/assets/{Terminal-D0j2XTwz.js → Terminal-FY6VVyeT.js} +3 -3
  40. package/dist/assets/{Viewer-BBKHaGnS.js → Viewer-Db9V3y4R.js} +1 -1
  41. package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-Bl9asTFj.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-DgrbCMdK.js} +1 -1
  42. package/dist/assets/{archive-Ze9hhry4.js → archive-CJfmV07C.js} +1 -1
  43. package/dist/assets/{authed-media-BJ3V0Hsp.js → authed-media-CA36_TYL.js} +1 -1
  44. package/dist/assets/{boxes-EQnIjyQ5.js → boxes-X_rDWdou.js} +1 -1
  45. package/dist/assets/circle-slash-C9dO41QA.js +1 -0
  46. package/dist/assets/crop-o1ZnayCW.js +1 -0
  47. package/dist/assets/{device-integration-icon-CB229zfO.js → device-integration-icon-DcTMLxPi.js} +1 -1
  48. package/dist/assets/device-picker-model-BwPih3Va.js +1 -0
  49. package/dist/assets/{format-size-FKMC8cpk.js → format-size-B4KE3z8i.js} +1 -1
  50. package/dist/assets/{history-COLYUTit.js → history-BVPkDM04.js} +1 -1
  51. package/dist/assets/{hostInit-BdS3Gpsj.js → hostInit-CompbdN8.js} +1 -1
  52. package/dist/assets/index-BlUdDWLp.js +4 -0
  53. package/dist/assets/index-vq6byeQ3.css +2 -0
  54. package/dist/assets/{layers-cPcnAaGd.js → layers-Bg9_2Fck.js} +1 -1
  55. package/dist/assets/location-owned-usage-yNYTa3yG.js +1 -0
  56. package/dist/assets/{mf-entry-bootstrap-0-9976714b.js → mf-entry-bootstrap-0-e75731db.js} +2 -2
  57. package/dist/assets/{monitor-smartphone-Dpm4bhCz.js → monitor-smartphone-5lHVpcLH.js} +1 -1
  58. package/dist/assets/mount-BwPih3Va.js +1 -0
  59. package/dist/assets/notification-schedule-field-ql1Dzx_N.js +1 -0
  60. package/dist/assets/{octagon-alert-C31Yg2_w.js → octagon-alert-Bn06fTVi.js} +1 -1
  61. package/dist/assets/player-overlays-Sm-ivm_8.js +1 -0
  62. package/dist/assets/remoteEntry-CoqQRRUJ.js +1 -0
  63. package/dist/assets/{send-D7I4L3zS.js → send-TxnVMKnC.js} +1 -1
  64. package/dist/assets/{settings-2-ZWMbtxvo.js → settings-2-BAm45F1t.js} +1 -1
  65. package/dist/assets/src-CmnrQw1X.js +67 -0
  66. package/dist/assets/{use-scenes-feed-Dlji29sg.js → use-scenes-feed-CLHMDiWX.js} +1 -1
  67. package/dist/assets/{use-stationary-objects-wg1tYqCt.js → use-stationary-objects-Ba8qX5nf.js} +1 -1
  68. package/dist/assets/useEventInvalidation-BwPih3Va.js +1 -0
  69. package/dist/assets/{useNodeUrlSelection-CZ06zQfe.js → useNodeUrlSelection-CjzoYyR_.js} +1 -1
  70. package/dist/assets/user-round-BLTQwaog.js +1 -0
  71. package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-DwpWTSeK.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-DX2QtUlA.js} +2 -2
  72. package/dist/index.html +7 -7
  73. package/dist/server/addon.js +1 -1
  74. package/package.json +1 -1
  75. package/dist/assets/Addons-Ch8IGQYU.js +0 -4
  76. package/dist/assets/AdminPage-BSFohA3i.js +0 -1
  77. package/dist/assets/AiProfiles-CvGjy2UD.js +0 -3
  78. package/dist/assets/Build-K_E6WPuU.js +0 -40
  79. package/dist/assets/Cluster-Dys62hM2.js +0 -1
  80. package/dist/assets/ClusterStepModel-B6kJx6hO.js +0 -1
  81. package/dist/assets/CompositionEditor-Djb_m0Fq.js +0 -1
  82. package/dist/assets/Data-bZQZDfmh.js +0 -1
  83. package/dist/assets/DeviceDetail-CZm2UKkP.js +0 -2
  84. package/dist/assets/Identity-C3msiWzK.js +0 -1
  85. package/dist/assets/IntegrationDetail-DTa_Z_Y8.js +0 -1
  86. package/dist/assets/Integrations-BUs8sF9z.js +0 -1
  87. package/dist/assets/Integrations-Blra3sWt.js +0 -1
  88. package/dist/assets/Library-DtHrSPqN.js +0 -1
  89. package/dist/assets/Locations-DljHAtnI.js +0 -3
  90. package/dist/assets/MotionZonesSettings-DzJiBfBH.js +0 -1
  91. package/dist/assets/MyAccess-CYEHE4Vt.js +0 -2
  92. package/dist/assets/Network-Cymq4f9k.js +0 -1
  93. package/dist/assets/Notifications-Airu5OeS.js +0 -1
  94. package/dist/assets/Recordings-q5golvzT.js +0 -1
  95. package/dist/assets/SessionsList-C_zY2zSb.js +0 -2
  96. package/dist/assets/System-WwGShHpN.js +0 -1
  97. package/dist/assets/circle-slash-BiNjJGqu.js +0 -1
  98. package/dist/assets/crop-ByWrrroC.js +0 -1
  99. package/dist/assets/device-picker-model-DARErQpp.js +0 -1
  100. package/dist/assets/index-4-wf2dZY.css +0 -2
  101. package/dist/assets/index-L63cSV_9.js +0 -4
  102. package/dist/assets/location-owned-usage-Bv-8M-2g.js +0 -1
  103. package/dist/assets/mount-DARErQpp.js +0 -1
  104. package/dist/assets/notification-schedule-field-55LldawV.js +0 -1
  105. package/dist/assets/player-overlays-EDVR7CqJ.js +0 -1
  106. package/dist/assets/remoteEntry-BG8uep-b.js +0 -1
  107. package/dist/assets/src-BEsQ_4LU.js +0 -67
  108. package/dist/assets/useEventInvalidation-DARErQpp.js +0 -1
  109. package/dist/assets/user-round-WIoRKO7A.js +0 -1
@@ -1,2 +0,0 @@
1
- import{I as e,K as t,Q as n,S as r,W as i,a,b as o,o as s,q as c,t as l,x as u,z as d}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-DhP-Lgiq.js";import{B as f,D as p,E as m,G as h,R as g,T as _,U as v,W as y,X as b,_t as x,at as S,lt as C,m as w,mt as T,q as E,r as D,st as O,t as k,ut as A,vt as j}from"./player-overlays-EDVR7CqJ.js";import{$ as M,$t as N,A as P,An as F,Ar as I,B as ee,Bi as L,Ci as te,Cn as R,Dd as z,Di as ne,Dn as re,Ds as ie,Ea as B,Ef as V,Fn as H,Ft as ae,Gt as oe,Hd as se,Hu as U,Ia as ce,Ii as le,Jl as ue,Js as de,Jt as fe,Ko as W,Kr as pe,L as me,Ld as he,Li as ge,Ln as _e,Ls as ve,M as ye,Ms as be,Mt as xe,Na as Se,Ni as Ce,Nn as we,Nu as Te,Oi as Ee,On as De,Os as G,Pn as Oe,Pt as ke,Q as Ae,Qd as je,Qi as Me,Ql as Ne,Qt as Pe,Rn as K,S as Fe,Si as Ie,Sn as Le,T as Re,Tn as ze,Ts as Be,Tt as Ve,Ud as He,Ul as Ue,Vi as We,Wl as Ge,Wn as Ke,Wt as qe,Wu as Je,Xl as Ye,Xs as Xe,Xt as Ze,Xu as Qe,Y as $e,Yd as et,Yi as tt,Yn as nt,Ys as rt,Yt as it,Yu as at,Z as ot,Zs as st,Zt as ct,Zu as lt,_a as ut,_d as dt,_t as ft,a as pt,ac as mt,an as ht,ao as gt,ar as _t,at as vt,au as yt,b as bt,ba as xt,bc as St,c as Ct,ca as wt,cd as Tt,cn as Et,ct as Dt,cu as Ot,d as kt,da as At,dd as jt,df as Mt,do as Nt,ed as Pt,es as Ft,fa as It,ff as Lt,fr as Rt,ft as zt,fu as Bt,gt as Vt,hf as Ht,i as Ut,ia as Wt,ir as Gt,it as Kt,j as qt,jn as Jt,k as Yt,kn as Xt,ku as Zt,l as Qt,ld as $t,ln as en,lo as tn,lt as nn,lu as rn,mt as an,nn as on,ns as sn,nt as cn,o as ln,od as un,on as dn,pf as fn,pn,pt as mn,q as hn,qs as gn,qt as _n,r as vn,ra as yn,rf as bn,rn as xn,rr as Sn,ru as Cn,s as wn,sa as Tn,sd as En,sn as Dn,tn as On,tt as kn,ua as An,uo as jn,ut as Mn,vd as Nn,vt as Pn,w as Fn,wn as In,ws as Ln,x as Rn,y as zn,yd as Bn,z as Vn,za as Hn,zi as Un,zn as Wn,zt as Gn}from"./src-BEsQ_4LU.js";import{t as Kn}from"./archive-Ze9hhry4.js";import{t as qn}from"./boxes-EQnIjyQ5.js";import{t as Jn}from"./circle-slash-BiNjJGqu.js";import{_ as Yn,a as Xn,c as Zn,d as Qn,f as $n,g as er,h as tr,i as nr,l as rr,m as ir,n as ar,o as or,p as sr,s as cr,t as lr,u as ur,v as dr,y as fr}from"./ClusterStepModel-B6kJx6hO.js";import{t as pr}from"./layers-cPcnAaGd.js";import{An as mr,Er as q,Fn as hr,Fr as gr,Nn as _r,Pn as vr,Pr as yr,Tr as J,Yn as br,_ as xr,an as Sr,b as Cr,br as wr,di as Tr,dr as Er,f as Dr,fn as Or,g as kr,hn as Ar,in as jr,m as Mr,on as Nr,p as Pr,pn as Fr,pr as Ir,rn as Lr,rr as Rr,sn as zr,sr as Br,u as Vr,ui as Hr,vr as Ur,wr as Wr,xr as Y}from"./client-B2uiK_6q.js";import{t as X}from"./useTranslation-Bc5yH9V9.js";import"./mount-DARErQpp.js";import{$ as Gr,A as Kr,B as qr,D as Jr,E as Yr,G as Xr,J as Zr,K as Qr,M as $r,O as ei,Q as ti,R as ni,U as ri,V as ii,W as ai,Y as oi,Z as si,_ as ci,et as li,j as ui,k as di,x as fi,y as pi,z as mi}from"./index-L63cSV_9.js";import{C as hi,D as gi,E as _i,S as vi,_ as yi,a as bi,b as xi,c as Si,d as Ci,f as wi,g as Ti,h as Ei,i as Di,l as Oi,m as ki,n as Ai,o as ji,p as Mi,r as Ni,s as Pi,t as Fi,u as Ii,v as Li,x as Ri,y as zi}from"./CompositionEditor-Djb_m0Fq.js";import"./useEventInvalidation-DARErQpp.js";import{t as Bi}from"./use-stationary-objects-wg1tYqCt.js";import"./device-picker-model-DARErQpp.js";import{t as Vi}from"./authed-media-BJ3V0Hsp.js";var Hi=j(`arrow-left-right`,[[`path`,{d:`M8 3 4 7l4 4`,key:`9rb6wj`}],[`path`,{d:`M4 7h16`,key:`6tx8e3`}],[`path`,{d:`m16 21 4-4-4-4`,key:`siv7j2`}],[`path`,{d:`M20 17H4`,key:`h6l3hr`}]]),Ui=j(`disc`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`circle`,{cx:`12`,cy:`12`,r:`2`,key:`1c9p78`}]]),Wi=j(`ear`,[[`path`,{d:`M6 8.5a6.5 6.5 0 1 1 13 0c0 6-6 6-6 10a3.5 3.5 0 1 1-7 0`,key:`1dfaln`}],[`path`,{d:`M15 8.5a2.5 2.5 0 0 0-5 0v1a2 2 0 1 1 0 4`,key:`1qnva7`}]]),Gi=j(`scan-eye`,[[`path`,{d:`M3 7V5a2 2 0 0 1 2-2h2`,key:`aa7l1z`}],[`path`,{d:`M17 3h2a2 2 0 0 1 2 2v2`,key:`4qcy5o`}],[`path`,{d:`M21 17v2a2 2 0 0 1-2 2h-2`,key:`6vwrx8`}],[`path`,{d:`M7 21H5a2 2 0 0 1-2-2v-2`,key:`ioqczr`}],[`circle`,{cx:`12`,cy:`12`,r:`1`,key:`41hilf`}],[`path`,{d:`M18.944 12.33a1 1 0 0 0 0-.66 7.5 7.5 0 0 0-13.888 0 1 1 0 0 0 0 .66 7.5 7.5 0 0 0 13.888 0`,key:`11ak4c`}]]);n();function Ki(e){if(typeof e!=`object`||!e)return null;let t=e,n=t.id,r=t.label;if(typeof n!=`string`||typeof r!=`string`)return null;let i=t.available===!0,a=t.enabled,o=t.unavailableReason;return{id:n,label:r,costWhenOff:typeof t.costWhenOff==`string`?t.costWhenOff:``,on:i&&typeof a==`boolean`?a:null,available:i,unavailableReason:typeof o==`string`?o:null}}function qi(e){if(typeof e!=`object`||!e)return null;let t=e.switches;if(!Array.isArray(t))return null;let n=t.map(Ki).filter(e=>e!==null);return n.length===0?null:n}var Ji=[[/privacy|mask/i,`privacy`],[/microphone|mic\b/i,`microphone`],[/speaker|broker audio|stream audio/i,`speaker`],[/audio/i,`listening`],[/object|detect/i,`detection`],[/event/i,`archive`],[/record/i,`recording`],[/notif/i,`notifications`],[/stream|broker/i,`stream`]];function Yi(e){for(let[t,n]of Ji)if(t.test(e))return n;return`generic`}function Xi(e){let t=e.filter(e=>e.on===!1).map(e=>e.id),n=e.filter(e=>e.on===null).map(e=>e.id),r=t=>t.map(t=>e.find(e=>e.id===t)?.label??t).join(`, `),i=[];return t.length>0&&i.push(`Off: ${r(t)}`),n.length>0&&i.push(`Unknown: ${r(n)}`),{offIds:t,unknownIds:n,summary:i.length===0?`All camera functions on`:i.join(` · `)}}var Zi={stream:lt,detection:Gi,privacy:T,microphone:A,speaker:Bt,listening:Wi,archive:Kn,recording:Ui,notifications:Mt,generic:Te};function Qi({deviceId:t}){let n=s(),i=Number.isFinite(t),[a,o]=c(null),[l,d]=c(!1),f=G({deviceId:t},{enabled:i});vn([`pipelineOrchestrator`,`getCameraSwitches`],[`capability.binding-changed`]);let p=qi(f.data),m=st({onError:(e,r)=>{console.error(`[CameraFunctionSwitches] switch write failed — reverting`,{tags:{deviceId:t},meta:{switchId:r.switchId,error:e instanceof Error?e.message:String(e)}}),n.invalidateQueries({queryKey:[[`pipelineOrchestrator`,`getCameraSwitches`]]}),o({id:r.switchId,message:e instanceof Error?e.message:String(e)})},onSuccess:()=>{o(null),n.invalidateQueries({queryKey:[[`pipelineOrchestrator`]]}),n.invalidateQueries({queryKey:[[`deviceManager`]]}),n.invalidateQueries({queryKey:[[`recording`]]})}}),h=e(e=>{!e.available||e.on===null||m.mutate({deviceId:t,switchId:e.id,enabled:!e.on})},[t,m]);if(p===null)return null;let g=Xi(p),_=e=>a?.id===e.id?a.message:null;return r(ct,{open:l,onOpenChange:d,children:[r(N,{"aria-label":`Camera functions`,title:g.summary,className:`inline-flex items-center gap-1 rounded-lg border px-2 py-1.5 text-[11px] font-medium transition-colors ${a===null?g.offIds.length>0?`border-warning/40 text-warning hover:bg-warning/10`:`border-border text-foreground-subtle hover:text-foreground hover:bg-surface-hover`:`border-danger/50 text-danger bg-danger/5`}`,children:[u(Te,{className:`h-3.5 w-3.5`}),u(`span`,{className:`hidden lg:inline`,children:`Functions`}),g.offIds.length>0&&r(`span`,{className:`rounded bg-warning/20 px-1 text-[9px] font-semibold uppercase tracking-wide`,children:[g.offIds.length,` off`]})]}),r(Pe,{align:`end`,className:`min-w-[240px] max-h-[60vh] overflow-y-auto p-1`,children:[u(`div`,{className:`px-2 py-1 text-[10px] uppercase tracking-wider text-foreground-subtle`,children:`Camera functions`}),u(`ul`,{className:`space-y-0.5`,children:p.map(e=>u(`li`,{children:u($i,{row:e,failure:_(e),onToggle:()=>h(e)})},e.id))})]})]})}function $i({row:e,failure:t,onToggle:n}){let i=Zi[Yi(e.label)],a=e.on===null,o=e.on===!1,s=t===null?a?e.unavailableReason??`The source that owns this did not answer.`:e.costWhenOff:`Write failed: ${t}`,c=t===null?a?e.unavailableReason??`unknown`:null:`write failed`;return r(`button`,{type:`button`,role:`switch`,"aria-label":e.label,"aria-checked":e.on===!0,disabled:!e.available,onClick:n,title:s,className:`flex w-full items-center gap-2 rounded-md px-2 py-1 text-left text-[12px] text-foreground transition-colors hover:bg-surface-hover disabled:opacity-40 disabled:cursor-not-allowed`,children:[u(i,{className:`h-3.5 w-3.5 shrink-0 ${t===null?a?`text-foreground-subtle/50`:o?`text-warning`:`text-success`:`text-danger`}`}),r(`span`,{className:`flex-1 min-w-0 truncate`,children:[e.label,c!==null&&r(`span`,{className:`ml-1 text-[10px] text-foreground-subtle`,children:[`· `,c]})]}),u(`span`,{className:`shrink-0 rounded px-1 py-0.5 text-[9px] font-semibold uppercase tracking-wide ${a?`bg-surface-hover text-foreground-subtle/60`:o?`bg-warning/20 text-warning`:`bg-success/20 text-success`}`,children:a?`—`:o?`off`:`on`})]})}function ea({deviceId:e}){let t=Kt(S().trpcClient,e);return t===null?null:r(`a`,{href:t.url,target:`_blank`,rel:`noopener noreferrer`,title:`${t.label} — ${t.host}`,className:`inline-flex items-center gap-1.5 rounded-lg px-2 sm:px-2.5 py-1.5 text-[11px] font-medium border border-border text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,children:[u(he,{className:`h-3.5 w-3.5`}),u(`span`,{className:`hidden sm:inline`,children:t.label})]})}function ta({parentDeviceId:e}){let{t}=X(),n=si(),i=S(),{data:a,isLoading:o,isError:s}=ii(e),{data:c}=Tn({deviceId:e},{enabled:Number.isFinite(e)});if(o)return u(`div`,{className:`rounded-lg border border-border bg-surface p-3`,children:u(`p`,{className:`text-[10px] text-foreground-subtle`,children:t(`common.loading`,{defaultValue:`Loading…`})})});if(s)return u(`div`,{className:`rounded-lg border border-border bg-surface p-3`,children:u(`p`,{className:`text-[10px] text-warning`,children:t(`integrations.childrenLoadError`,{defaultValue:`Failed to load children`})})});let l=(a??[]).filter(e=>e.display?.hidden!==!0);if(l.length===0)return null;let d=M(c?.stableId??``,l,c?.childLayout),f=d.ungrouped,p=e=>n(`/devices/${String(e)}`),m=c?.name??``,h=(e,t)=>u(ot,{trpc:i.trpcClient,device:{...t,name:vt(t,m)},variant:`minimal`,onNavigate:p},e),g=f.some(e=>!!e.role),_=f.some(e=>!e.role),v=g&&!_?t(`device.accessories`,{defaultValue:`Accessories`}):!g&&_?t(`device.adoptedDevices`,{defaultValue:`Adopted devices`}):t(`device.children`,{defaultValue:`Children`}),y=f.length>0?r(`div`,{className:`rounded-lg border border-border bg-surface p-3`,children:[u(`div`,{className:`text-[10px] font-semibold uppercase tracking-wide text-foreground-subtle mb-1.5`,children:v}),u(`div`,{className:`space-y-1`,children:f.map(e=>h(e.id,e))})]}):null,b=d.disabledSection===void 0?null:u(Ae,{title:t(`device.disabledSection`,{defaultValue:`Disabled`}),count:d.disabledSection.children.length,defaultOpen:!1,children:u(`div`,{className:`opacity-60 space-y-1`,children:d.disabledSection.children.map(e=>h(e.id,e))})},d.disabledSection.title);if(d.sections.length===0)return b===null?y:r(`div`,{className:`space-y-2`,children:[y,b]});let x=_&&!g;return r(`div`,{className:`space-y-2`,children:[x?y:null,d.sections.map(e=>u(Ae,{title:e.title,count:e.children.length,defaultOpen:e.defaultOpen,children:e.children.map(e=>h(e.id,e))},e.title)),x?null:y,b]})}function na({deviceId:e}){let t=S(),{data:n,isLoading:r}=qr(e),{data:i,isLoading:a}=ii(e),o=r||a,s=(i??[]).map(e=>({id:e.id,stableId:e.stableId,type:e.type,name:e.name,features:e.features,...e.sourceInfo?{sourceInfo:{id:e.sourceInfo.id}}:{}})),c=typeof n?.linkDeviceId==`number`?n.linkDeviceId:null,l=typeof n?.primaryChildEntityId==`string`?n.primaryChildEntityId:null;return o?u(`div`,{className:`h-full min-h-32 w-full animate-pulse rounded-lg bg-surface`,"aria-hidden":`true`}):u(`div`,{className:`flex h-full w-full flex-col`,children:u(Dt,{trpc:t.trpcClient,children:s,linkDeviceId:c,primaryChildEntityId:l})})}n();function ra({dev:e,busy:t,setBusy:n}){let i=e?.motionTrigger,a=E(e?.state.motionTrigger),[o,s]=c(!1);if(!i)return null;let l=a?.enabled===!0,d=a!==void 0,f=async()=>{if(t||!d)return;let e=!l;n(!0),s(!0);try{await i.setMotionTrigger({enabled:e})}finally{n(!1),s(!1)}};return r(`button`,{type:`button`,onClick:()=>{f()},disabled:t||!d,title:d?l?`Disable trigger on motion`:`Enable trigger on motion`:`Awaiting state…`,"aria-pressed":l,className:`inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-[11px] font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${l?`border-primary/50 bg-primary/15 text-primary`:`border-border bg-surface text-foreground-subtle hover:text-foreground`}`,children:[u(V,{className:`h-3 w-3`}),u(`span`,{children:o?l?`Disabling…`:`Enabling…`:d?l?`On motion: on`:`On motion: off`:`On motion: …`})]})}n();function Z({deviceId:e,deviceType:t,features:n}){let i=S(),a=zt(t)?.HeroCard??mn,o=h(i.trpcClient,e),s=E(o?.state.deviceStatus),[l,d]=c(!1),f=s!==void 0&&s.online===!1,p=f?s.lastChangedAt:null;return r(`div`,{className:`flex h-full w-full flex-col items-stretch gap-3 p-3 sm:p-4`,children:[f?u(`div`,{className:`flex justify-center`,children:u(Mn,{lastChangedAt:p})}):null,u(a,{trpc:i.trpcClient,deviceId:e,features:n}),u(`div`,{className:`flex justify-center`,children:u(ra,{dev:o,busy:l,setBusy:d})})]})}function ia({deviceId:e,features:t}){return u(`div`,{className:`flex h-full w-full flex-col items-stretch gap-3 p-3 sm:p-4`,children:u(an,{trpc:S().trpcClient,deviceId:e,features:t})})}function aa({deviceId:e,features:t}){return u(`div`,{className:`flex h-full w-full flex-col items-stretch p-3 sm:p-4`,children:u(mn,{trpc:S().trpcClient,deviceId:e,features:t})})}function oa(e){if(!e)return null;let t=e.channel;return typeof t!=`number`||!Number.isInteger(t)||t<0?null:t}function sa(e){if(!e)return null;let t=oa(e.data);return t===null?e.eventType:`Button ${String(t)} · ${e.eventType}`}var ca=1e3,la=60*ca,ua=60*la,da=24*ua;function fa(e,t){if(e==null||e<=0)return`—`;let n=t-e;return n<ca?`just now`:n<la?`${String(Math.floor(n/ca))}s ago`:n<ua?`${String(Math.floor(n/la))}m ago`:n<da?`${String(Math.floor(n/ua))}h ago`:`${String(Math.floor(n/da))}d ago`}n();var pa=1500,ma=15e3,ha=1e3;function ga({deviceId:e}){let n=h(S().trpcClient,e)?.state.eventEmitter,i=E(n);d(()=>{if(!n)return;n.refresh();let e=setInterval(()=>{n.refresh()},ma);return()=>{clearInterval(e)}},[n]);let a=i?.lastEvent??null,o=a?.seq??null,s=t(null),[l,f]=c(!1);d(()=>{if(o===null)return;let e=s.current;if(s.current=o,e===null||e===o)return;f(!0);let t=setTimeout(()=>{f(!1)},pa);return()=>{clearTimeout(t)}},[o]);let[p,m]=c(()=>Date.now());d(()=>{let e=setInterval(()=>{m(Date.now())},ha);return()=>{clearInterval(e)}},[]);let g=sa(a),_=i?.eventTypes??[],v=i?.eventCountSinceStart??0,y=i!==void 0,b=oa(a?.data);return r(`div`,{className:`flex h-full w-full flex-col items-center justify-center gap-3 p-4`,children:[u(`div`,{"data-testid":`event-emitter-indicator`,"data-flashing":String(l),className:`flex h-24 w-24 items-center justify-center rounded-full border-2 transition-all ${l?`border-primary bg-primary/20 text-primary shadow-lg shadow-primary/30 scale-105`:`border-border bg-surface text-foreground-subtle`}`,"aria-live":`polite`,title:g??`No press recorded`,children:u(l?Tt:z,{className:`h-10 w-10`})}),r(`div`,{className:`text-center`,children:[b!==null&&u(`div`,{className:`text-xs font-semibold uppercase tracking-wide text-primary`,children:`Button ${String(b)}`}),u(`div`,{"data-testid":`event-emitter-headline`,className:`text-sm font-semibold ${g?`text-foreground`:`text-foreground-subtle`}`,children:g??(y?`No press recorded`:`Awaiting state…`)}),u(`div`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:a?fa(a.timestamp,p):`Waiting for the first event`})]}),_.length>0&&u(`div`,{className:`flex max-w-full flex-wrap justify-center gap-1`,children:_.map(e=>u(`span`,{"data-testid":`event-emitter-chip`,className:`rounded-full border px-2 py-0.5 text-[10px] font-medium ${e===a?.eventType?`border-primary bg-primary/15 text-primary`:`border-border bg-surface text-foreground-subtle`}`,children:e},e))}),u(`div`,{className:`text-[10px] text-foreground-subtle`,children:`${String(v)} ${v===1?`event`:`events`} since start`})]})}function _a({deviceName:e,deviceType:t,provider:n,isOnline:i,features:a}){return r(`div`,{className:`flex h-full w-full flex-col items-center justify-center gap-3 rounded-lg border border-dashed border-border bg-surface p-6 text-center`,children:[u(Qr,{type:n,size:`lg`}),r(`div`,{children:[u(`div`,{className:`text-sm font-semibold text-foreground`,children:e}),u(`div`,{className:`text-[10px] text-foreground-subtle uppercase tracking-wider mt-0.5`,children:t})]}),r(`div`,{className:`flex items-center gap-2 flex-wrap justify-center`,children:[u(ye,{status:i?`online`:`offline`}),a.length>0&&u(Zr,{capabilities:a})]}),u(`div`,{className:`text-[10px] text-foreground-subtle italic max-w-xs mt-1`,children:`No live view for this device type. Use the Config tab or the shortcut row to interact.`})]})}n();function va({deviceId:e}){let t=s(),n=le({deviceId:e},{refetchInterval:1e4,retry:!1}),a=ge({onSuccess:()=>{t.invalidateQueries({queryKey:[[`deviceDiscovery`,`listDiscovered`]]}),t.invalidateQueries({queryKey:[[`deviceDiscovery`,`getStatus`]]})}}),o=i(()=>ya(n.data??[]),[n.data]);return r(`div`,{className:`flex h-full w-full flex-col gap-3 p-3 sm:p-4`,children:[r(`div`,{className:`flex flex-wrap items-stretch gap-2 sm:gap-3`,children:[u(ba,{label:`Discovered`,value:o.total,icon:u(En,{className:`h-3.5 w-3.5`})}),u(ba,{label:`Adopted`,value:o.adopted,accent:`success`}),u(ba,{label:`Available`,value:o.available,accent:o.available>0?`primary`:void 0}),r(`button`,{type:`button`,onClick:()=>{a.mutateAsync({deviceId:e}).catch(()=>{})},disabled:a.isPending,className:`inline-flex items-center justify-center gap-1.5 rounded-lg border border-border px-3 py-2 text-xs font-medium text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors disabled:opacity-50 self-stretch shrink-0`,children:[a.isPending?u(dt,{className:`h-3.5 w-3.5 animate-spin`}):u(Qe,{className:`h-3.5 w-3.5`}),u(`span`,{className:`hidden sm:inline`,children:`Discover`})]})]}),r(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px] text-foreground-subtle border-t border-border-subtle pt-2`,children:[u(xa,{icon:u(Ot,{className:`h-3 w-3 text-emerald-500`}),label:`${o.online} online`}),u(xa,{icon:u($t,{className:`h-3 w-3 text-amber-500`}),label:`${o.sleeping} sleeping`}),u(xa,{icon:u(rn,{className:`h-3 w-3 text-destructive`}),label:`${o.offline} offline`}),o.unknown>0?u(xa,{icon:u(et,{className:`h-3 w-3 text-foreground-subtle`}),label:`${o.unknown} unknown`}):null]})]})}function ya(e){let t={total:e.length,adopted:0,available:0,online:0,sleeping:0,offline:0,unknown:0};for(let n of e)n.alreadyAdopted?t.adopted+=1:t.available+=1,t[n.status]+=1;return t}function ba({label:e,value:t,icon:n,accent:i}){return r(`div`,{className:`flex flex-1 basis-[140px] min-w-0 flex-col gap-1 rounded-lg border px-2 py-1.5 sm:px-3 sm:py-2 ${i===`success`?`bg-emerald-500/10 border-emerald-500/30 text-emerald-500`:i===`primary`?`bg-primary/10 border-primary/30 text-primary`:`bg-surface-hover border-border text-foreground`}`,children:[r(`div`,{className:`flex items-center gap-1.5 text-[10px] uppercase tracking-wider opacity-70 truncate`,children:[n,u(`span`,{className:`truncate`,children:e})]}),u(`div`,{className:`text-xl sm:text-2xl font-semibold tabular-nums leading-none`,children:t})]})}function xa({icon:e,label:t}){return r(`span`,{className:`inline-flex items-center gap-1`,children:[e,u(`span`,{children:t})]})}var Sa={[q.Switch]:Z,[q.Siren]:Z,[q.Light]:Z,[q.Sensor]:Z,[q.Button]:Z,[q.Hub]:va,[q.Cover]:ia,[q.Valve]:Z,[q.Humidifier]:Z,[q.WaterHeater]:Z,[q.Container]:na,[q.Lock]:Z,[q.Fan]:Z,[q.Thermostat]:Z,[q.Climate]:Z,[q.MediaPlayer]:Z,[q.Control]:Z,[q.AlarmPanel]:Z,[q.EventEmitter]:ga,[q.Notifier]:aa,[q.Script]:Z,[q.Automation]:Z,[q.Presence]:Z,[q.Update]:Z,[q.Vacuum]:Z,[q.LawnMower]:Z,[q.Weather]:Z,[q.Image]:Z,[q.PetFeeder]:Z};function Ca(e){return Sa[e]??_a}function wa(e){return u(Ca(e.deviceType),{...e})}function Ta(e){return ln(S().trpcClient,e)}n();function Ea(n){let[r,i]=c(`idle`),[a,o]=c(null),s=t(null),l=t(null),u=t(null),f=t(!0),p=jn(),m=tn(),h=Nt(),g=e(()=>{if(s.current){try{s.current.close()}catch{}s.current=null}if(l.current){for(let e of l.current.getTracks())try{e.stop()}catch{}l.current=null}u.current=null},[]),_=e(async()=>{if(r===`idle`)return;i(`stopping`);let e=u.current;if(e&&n!==null)try{await Promise.race([h.mutateAsync({deviceId:n,sessionId:e}),new Promise((e,t)=>setTimeout(()=>t(Error(`server stopSession timeout`)),2e3))])}catch(e){console.warn(`[intercom] server stopSession failed (continuing teardown)`,e)}g(),f.current&&(i(`idle`),o(null))},[r,n,h,g]),v=e(async()=>{if(n===null||r!==`idle`&&r!==`error`)return;o(null);let e=null,t=null,a=null;try{i(`requesting-mic`),e=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}),l.current=e,i(`starting`);let r=await p.mutateAsync({deviceId:n});a=r.sessionId,u.current=a,i(`connecting`),t=new RTCPeerConnection,s.current=t,t.oniceconnectionstatechange=()=>{if(!f.current)return;let e=t.iceConnectionState;e===`connected`||e===`completed`?i(`talking`):(e===`failed`||e===`closed`||e===`disconnected`)&&f.current&&(o(e===`failed`?`WebRTC connection failed`:null),_())};for(let n of e.getAudioTracks())t.addTrack(n,e);await t.setRemoteDescription({type:`offer`,sdp:r.sdpOffer});let c=await t.createAnswer();await t.setLocalDescription(c);let d=t.localDescription?.sdp??c.sdp??``;await m.mutateAsync({deviceId:n,sessionId:a,sdpAnswer:d})}catch(r){let c=r instanceof Error?r.message:String(r);if(console.warn(`[intercom] start failed`,r),t)try{t.close()}catch{}if(e)for(let t of e.getTracks())try{t.stop()}catch{}if(s.current=null,l.current=null,a!==null)try{await h.mutateAsync({deviceId:n,sessionId:a})}catch{}u.current=null,f.current&&(o(c),i(`error`))}},[n,r,p,m,h,_]);return d(()=>(f.current=!0,()=>{f.current=!1;let e=u.current;if(e!==null&&n!==null&&h.mutate({deviceId:n,sessionId:e}),s.current){try{s.current.close()}catch{}s.current=null}if(l.current){for(let e of l.current.getTracks())try{e.stop()}catch{}l.current=null}u.current=null}),[n]),{state:r,error:a,start:v,stop:_,isTalking:r===`talking`}}n();var Da=0;function Q(){return++Da}function Oa(e){switch(e.type){case`system`:return`system`;case`device`:return`#${e.deviceId}`;case`provider`:return e.providerId;case`addon`:return e.addonId}}function ka(e){return[``,`Commands`,` help Show this help`,` examples Show usage examples for the current scope`,` context Show every available variable + full API surface`,` clear Clear terminal (also Ctrl+L)`,``,`Shortcuts`,` Enter Execute expression`,` Arrow Up/Down Navigate command history`,` Ctrl+L Clear terminal`,``,`Try: ${{system:` sm.summary() // fleet overview`,device:` device.state.battery.value?.sleeping // sync read`,provider:` devices.map(d => d.name)`,addon:` manifest.version`}[e.type]}`,``,`Top-level objects: sm (SystemMirror), DeviceType, Math, JSON, Date, …`]}function Aa(e){switch(e.type){case`device`:return[``,`── State (sync, zero round-trip) ─────────────────────────`,` device.state.battery.value`,` device.state.battery.value?.percentage`,` device.state.motion.value?.detected`,``,`── Actions (async, through wrapper chain) ────────────────`,` await device.snapshot.getSnapshot({})`,` await device.ptz.move({ direction: 'left', steps: 1 })`,` await device.switch.setState({ on: true })`,``,`── Wait for condition ───────────────────────────────────`,` await sm.waitForState(deviceId, 'battery', s => !s.sleeping, 30_000)`,``,`── Subscribe to changes ─────────────────────────────────`,` const off = device.state.battery.subscribe(s => console.log(s))`,``,`── Quick info ───────────────────────────────────────────`,` info.name device name`,` info.addonId owning addon`,` sm.dump(deviceId) full debug dump`];case`system`:return[``,`── Lookups ──────────────────────────────────────────────`,` sm.getDeviceById(8)`,` sm.getDeviceByName('Sala da pranzo')`,` sm.getDevicesByAddon('reolink')`,` sm.getDevicesByType(DeviceType.Camera)`,``,`── Filters (typed query) ────────────────────────────────`,` sm.query({ addonId: 'reolink', online: true })`,` sm.query({ caps: ['battery', 'snapshot'] })`,` sm.query({ name: /^Cam-/ })`,``,`── Cross-device ─────────────────────────────────────────`,` sm.whereState('battery', s => s.percentage < 20).length`,` sm.mapState('battery', s => s.percentage)`,` sm.countByCap('snapshot')`,``,`── Batch action ─────────────────────────────────────────`,` await sm.invokeCap('snapshot', 'getSnapshot', {}, { parallelism: 4 })`,``,`── Listen ───────────────────────────────────────────────`,` sm.listenCap('motion', (id, s) => console.log(id, s))`,` sm.onDeviceAdded((id, info) => console.log('+', info.name))`,``,`── Diagnostics ──────────────────────────────────────────`,` sm.summary()`,` sm.dump(8)`];case`provider`:return[``,` devices.map(d => d.name)`,` await getIntegration()`,` sm.getDevicesByAddon('<this-addon-id>').length`];case`addon`:return[``,` manifest.name`,` manifest.version`,` declaration`]}}function ja(e){let t=[``,`Scope: ${e.type}`,``];switch(e.type){case`system`:return[...t,`Primary API — sm (SystemMirror):`,` sm.getDeviceById(id) DeviceProxy | null (sync)`,` sm.getDeviceByName(name) DeviceProxy | null`,` sm.getDeviceByStableId(sid) DeviceProxy | null`,` sm.getAllDevices() readonly DeviceProxy[]`,` sm.getDeviceInfo(id) DeviceInfo | null`,` sm.summary() fleet stats`,``,`Filters — sm.query({...}):`,` sm.query({ addonId: 'reolink', online: true })`,` sm.query({ caps: ['battery', 'snapshot'] }) // ALL caps required`,` sm.query({ anyCap: ['ptz', 'motion'] }) // ANY cap`,` sm.query({ name: { contains: 'sala' } }) // case-insensitive`,` sm.query({ name: /^Cam-\\d+$/ })`,` sm.query({ type: DeviceType.Camera })`,` sm.query({ parentDeviceId: 8 }) // accessories of cam 8`,` sm.query({ where: (info, dev) => dev.state.battery.value?.sleeping })`,``,`State queries:`,` sm.whereState('battery', s => s.percentage < 20)`,` sm.mapState('battery', s => s.percentage)`,` sm.findState('motion', s => s.detected)`,` sm.countByCap('snapshot')`,``,`Listeners (return unsubscribe fn):`,` sm.listen((id, cap, slice) => …) // every state change`,` sm.listenCap('motion', (id, slice) => …)`,` sm.listenDevice(8, (id, cap, slice) => …)`,` sm.onDeviceAdded((id, info) => …)`,` sm.onDeviceRemoved((id, info) => …)`,``,`Wait primitives:`,` await sm.waitForState(8, 'battery', s => !s.sleeping, 30_000)`,` await sm.waitForDevice(99, 30_000)`,``,`Batch:`,` await sm.invokeCap('snapshot', 'getSnapshot', {}, { parallelism: 4 })`,` await sm.forEachCap('reboot', d => d.reboot.reboot({}))`,``,`Diagnostics:`,` sm.dump(8) debug dump (one device)`,` sm.dump() full fleet dump`,` sm.summary() breakdown by cap/addon/type`,``,`Legacy: deviceRegistry, addonRegistry, eventBus, devices(), addons()`];case`device`:return[...t,`Pre-bound variables:`,` device DeviceProxy for this device (sync state + async methods)`,` deviceId number`,` info DeviceInfo metadata (name, addonId, type, online, …)`,` sm SystemMirror (full cluster view)`,` rawDevice legacy IDevice instance (escape hatch)`,``,`Reactive state (sync, zero round-trip):`,` device.state.battery.value BatteryStatus | undefined`,` device.state.battery.value?.sleeping`,` device.state.battery.value?.percentage`,` device.state.motion.value?.detected`,` device.state.switch.value?.on`,` device.state.brightness.value?.percentage`,` device.state.doorbell.value?.lastPressedAt`,``,`Cap actions (async, through wrapper chain):`,` await device.snapshot.getSnapshot({})`,` await device.snapshot.getSnapshot({ streamId: 'high' })`,` await device.ptz.move({ direction: 'left', steps: 1 })`,` await device.ptz.goToPreset({ presetId: 'home' })`,` await device.switch.setState({ on: true })`,` await device.brightness.setBrightness({ percentage: 60 })`,` await device.reboot.reboot({})`,``,`Subscribe to slice changes:`,` const off = device.state.battery.subscribe(s => console.log(s))`,` // off() to unsubscribe`,``,`Wait for a state condition:`,` await sm.waitForState(deviceId, 'battery', s => !s.sleeping, 30_000)`,``,`Diagnostics:`,` info.name device name`,` info.addonId which addon owns it`,` info.online transport health`,` sm.dump(deviceId) full debug dump (binding + state + info)`];case`provider`:return[...t,`Pre-bound variables:`,` devices Devices belonging to this provider (raw IDevice[])`,` getIntegration() Integration metadata`,``,`For typed device access use the SystemMirror:`,` await getSystemMirror()`,` sm.getDevicesByAddon('this-addon-id')`];case`addon`:return[...t,`Pre-bound variables:`,` manifest { name, version, ... }`,` declaration addon declaration`,` source addon source location`,``,`Examples:`,` manifest.name`,` manifest.version`]}}function Ma({scope:n,greeting:i,className:a}){let o=S(),[s,f]=c(()=>{let e=[];return i&&e.push({id:Q(),kind:`info`,text:i}),e.push({id:Q(),kind:`info`,text:`scope: ${Oa(n)} — type help or context for available commands`}),e}),[p,m]=c(``),[h,g]=c([]),[_,v]=c(-1),y=t(null),b=t(null);d(()=>{let e=b.current;e&&(e.scrollTop=e.scrollHeight)},[s]);let x=e(()=>{y.current?.focus()},[]),C=l({mutationFn:e=>o.trpcClient.repl.execute.mutate({code:e,scope:n}),onSuccess:e=>{let t=e??{},n=typeof t.output==`string`?t.output:e==null?`undefined`:typeof e==`string`?e:JSON.stringify(e,null,2),r=t.type===`error`;f(e=>[...e,{id:Q(),kind:r?`error`:`result`,text:n}])},onError:e=>{let t=e instanceof Error?e.message:String(e);f(e=>[...e,{id:Q(),kind:`error`,text:t}])}});function w(e){let t=e.trim();if(t){if(t===`clear`){f([{id:Q(),kind:`info`,text:`scope: ${Oa(n)}`}]),m(``);return}if(t===`help`){f(e=>[...e,{id:Q(),kind:`input`,text:`> ${t}`},...ka(n).map(e=>({id:Q(),kind:`info`,text:e}))]),m(``);return}if(t===`context`){f(e=>[...e,{id:Q(),kind:`input`,text:`> ${t}`},...ja(n).map(e=>({id:Q(),kind:`info`,text:e}))]),m(``);return}if(t===`examples`){f(e=>[...e,{id:Q(),kind:`input`,text:`> ${t}`},...Aa(n).map(e=>({id:Q(),kind:`info`,text:e}))]),m(``);return}g(e=>[...e,t]),v(-1),f(e=>[...e,{id:Q(),kind:`input`,text:`> ${t}`}]),m(``),C.mutate(t)}}function T(e){if(e.key===`Enter`){e.preventDefault(),w(p);return}if(e.key===`ArrowUp`){if(e.preventDefault(),h.length===0)return;let t=_===-1?h.length-1:Math.max(0,_-1);v(t),m(h[t]??``);return}if(e.key===`ArrowDown`){if(e.preventDefault(),_===-1)return;let t=_+1;t>=h.length?(v(-1),m(``)):(v(t),m(h[t]??``));return}e.ctrlKey&&e.key===`l`&&(e.preventDefault(),f([{id:Q(),kind:`info`,text:`scope: ${Oa(n)}`}]))}let E={input:`text-zinc-300`,result:`text-emerald-300`,error:`text-red-300`,info:`text-zinc-400`};return r(`div`,{className:`flex flex-col bg-[#0c0a09] rounded-lg border border-border overflow-hidden font-mono text-xs ${a??``}`,onClick:x,children:[r(`div`,{ref:b,className:`flex-1 overflow-y-auto p-3 space-y-1 min-h-[120px]`,children:[s.map(e=>u(`pre`,{className:`whitespace-pre-wrap break-words leading-relaxed ${E[e.kind]}`,children:e.text},e.id)),C.isPending&&u(`span`,{className:`text-zinc-500 animate-pulse`,children:`…thinking`})]}),r(`div`,{className:`flex items-center gap-2 border-t border-zinc-800 px-3 py-2 bg-[#0c0a09]`,children:[u(`span`,{className:`text-emerald-400 flex-shrink-0 select-none font-bold`,children:`>`}),u(`input`,{ref:y,value:p,onChange:e=>m(e.target.value),onKeyDown: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 Na(e,t){return e===null?null:{playbackUrl:e.url,...e.format===void 0?{}:{playbackFormat:e.format},playbackAuthToken:t,...e.label===void 0?{}:{playbackLabel:e.label}}}n();function Pa({deviceId:e,intercomAvailable:t=!1}){let n=S(),r=typeof window<`u`?b():``,a=Number.isFinite(e),s=Ta(a?e:null),c=Bi(a?[e]:[]),l=i(()=>{if(!a)return;let e=[];for(let t of c.rows){let n=pt(t);n!==null&&e.push(n)}return e},[a,c.rows]),{streams:d,pipelineMetrics:f,createSession:p,sendAnswer:m,handleOffer:h,getIceServers:g,addIceCandidate:_,getIceCandidates:v,closeSession:x,getSessionState:C,applyDownlinkProbe:w}=xe(n.trpcClient,a?e:null),T=y(a?e:null,{width:za}),E=Ea(a&&t?e:null),O=E.state===`requesting-mic`||E.state===`starting`||E.state===`connecting`||E.state===`stopping`,k=E.isTalking||O,A=()=>{E.state===`idle`||E.state===`error`?E.start():E.state!==`stopping`&&E.stop()},j=D(),M=Oe(),N=typeof window<`u`?window.localStorage.getItem(`camstack_admin_token`):null,P=Na(M.request,N),F=j.length>0?u(o,{children:j.map(e=>u(`div`,{className:`absolute inset-0`,children:e.node},e.id))}):null;return u(Rn,{serverUrl:r,createSession:p,sendAnswer:m,handleOffer:h,getIceServers:g,addIceCandidate:_,getIceCandidates:v,closeSession:x,getSessionState:C,applyDownlinkProbe:w,...P===null?{}:{...P,onExitPlayback:()=>M.clear()},streams:d,pipelineMetrics:f,phase:s.phase,detections:s,...l===void 0?{}:{stationaryObjects:l},defaultShowDetections:!0,defaultShowMotion:!0,showPlayStop:!0,snapshotSrc:T.src,...T.src?{posterUrl:T.src}:{},snapshotLoading:T.loading,onRefreshSnapshot:T.refresh,intercomAvailable:t,intercomShown:k,onIntercomToggle:A,extraOverlay:F,chromeless:!0,className:`h-full`})}function Fa({deviceId:e,containerDeviceId:t}){return Number.isFinite(e)?u(`div`,{className:`flex flex-col h-full`,children:u(Pn,{...t===void 0?{deviceId:e}:{containerDeviceId:t},limit:50,maxHeight:`max-h-full`,showScope:!1,showFilters:!1})}):r(`div`,{className:`flex items-center justify-center h-full text-[11px] text-foreground-subtle italic`,children:[`Device #`,e,` not loaded.`]})}function Ia({deviceId:e}){if(!Number.isFinite(e))return r(`div`,{className:`flex items-center justify-center h-full text-[11px] text-foreground-subtle italic`,children:[`Device #`,e,` not loaded.`]});let t=[`CamStack REPL — device #${e}`,``,` device.state.battery.value sync state read`,` await device.snapshot.getSnapshot({}) cap action`,``,` type 'examples' for more, 'context' for the full API`].join(`
2
- `);return u(Ma,{scope:{type:`device`,deviceId:e},greeting:t,className:`h-full border-0 rounded-none`})}function La({deviceId:e}){return Number.isFinite(e)?u(`div`,{className:`flex flex-col h-full overflow-y-auto`,children:u(ft,{deviceId:e,limit:50,maxHeight:`max-h-full`})}):r(`div`,{className:`flex items-center justify-center h-full text-[11px] text-foreground-subtle italic`,children:[`Device #`,e,` not loaded.`]})}function Ra({deviceId:e}){return Number.isFinite(e)?u(`div`,{className:`flex flex-col h-full overflow-y-auto`,children:u(Vt,{deviceId:e,limit:50,maxHeight:`max-h-full`})}):r(`div`,{className:`flex items-center justify-center h-full text-[11px] text-foreground-subtle italic`,children:[`Device #`,e,` not loaded.`]})}var za=960;function Ba(e){return new Set(e.filter(e=>{let t=e.nativeAddonId?.trim()??``;return t!==``&&t!==`composer`}).map(e=>e.capName))}function Va(e){return e.kind===`known`?null:e}function Ha(e,t){return e.composable.kind===`known`?e.composable.value.has(t)?{kind:`present`,mode:`add`}:{kind:`absent`}:e.composable}function Ua(e){if(e.deviceType!==q.Camera)return{kind:`absent`};switch(e.cameraSensors){case`pending`:return{kind:`pending`};case`unknown`:return{kind:`unknown`,reason:`camera sensors could not be checked`};case`absent`:return{kind:`absent`};case`present`:return{kind:`present`,mode:`add`}}}function Wa(e,t){if(e===`motion`)return Ua(t);let n=Va(t.nativeCaps);if(n!==null)return n;let r=t.nativeCaps.kind===`known`?t.nativeCaps.value:new Set;switch(e){case`doorbell`:return r.has(`doorbell`)?{kind:`absent`}:Ha(t,`doorbell`);case`battery`:return r.has(`battery`)?{kind:`present`,mode:`replace`}:Ha(t,`battery`);case`consumables`:return r.has(`consumables`)?{kind:`absent`}:Ha(t,`consumables`)}}function Ga({onAdvanced:e}){let{t}=X();return e===void 0?null:u(`button`,{type:`button`,className:`rounded text-left text-[11px] text-primary hover:underline focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary`,onClick:e,children:t(`customize.advancedLink`)})}function Ka(e){if(e.status===`pending`)return{kind:`pending`};if(e.status===`error`)return{kind:`unknown`,reason:e.error?.message??`the request failed`};let t=e.data;if(t===void 0)return{kind:`pending`};if(t.state===`not-loaded`)return{kind:`not-loaded`,reason:t.reason};if(t.view===null)return{kind:`none`};let n=Br(t.view.block);return n===null?{kind:`unknown`,reason:`block ${t.view.block.id} is not a composition`}:{kind:`present`,view:t.view,composition:n}}function qa(e){return e.kind===`present`?e.composition:null}function Ja(e,t){let{hidden:n,...r}=e??{},i=t?{...r,hidden:!0}:r;return Object.keys(i).length===0?null:i}function Ya(e){return typeof e.linkDeviceId==`number`}var Xa=new Set(Object.values(J));function Za(e){return Xa.has(e)}var Qa={[q.Switch]:[J.Siren,J.Floodlight,J.Spotlight,J.PirSensor,J.Chime,J.Autotrack,J.Nightvision,J.PrivacyMask,J.BinaryHelper],[q.Light]:[J.Floodlight,J.Spotlight,J.Nightvision],[q.Siren]:[J.Siren],[q.Button]:[J.Doorbell],[q.Sensor]:[J.MotionSensor,J.ContactSensor,J.LeakSensor,J.SmokeSensor,J.COSensor,J.GasSensor,J.TamperSensor,J.VibrationSensor,J.ConnectivitySensor,J.SoundSensor,J.BinarySensor,J.TemperatureSensor,J.HumiditySensor,J.AmbientLightSensor,J.PressureSensor,J.WindSensor,J.RainSensor,J.UvSensor,J.SolarRadiationSensor,J.SoilMoistureSensor,J.PowerSensor,J.EnergySensor,J.VoltageSensor,J.CurrentSensor,J.AirQualitySensor,J.BatterySensor,J.NumericSensor,J.EnumSensor,J.DateTimeSensor,J.GenericSensor],[q.Control]:[J.NumericControl,J.SelectControl,J.TextControl,J.DateTimeControl],[q.Notifier]:[J.MobilePushNotifier,J.MessagingNotifier,J.EmailNotifier,J.GenericNotifier]};function $a(e){for(let t of Object.values(q))if(t===e)return!0;return!1}function eo(e){return $a(e)?Qa[e]??[]:[]}function to(e,t){let n=eo(t);return e==null||e===``||n.includes(e)?n:[...n,e]}n();function no({device:e}){let{t}=X(),n=s(),[i,a]=c(null),o=()=>a(null),l={onSuccess:()=>{o(),n.invalidateQueries({queryKey:[[`deviceManager`]]})},onError:e=>a(e.message)},d=Se(),f=B(),h=e.display?.hidden===!0;return r(`section`,{"aria-label":t(`customize.identity.title`),className:`${p} ${m}`,children:[r(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4`,children:[u(ai,{deviceId:e.id,initialName:e.name,label:t(`customize.identity.name`),layout:`stacked`,onError:a,onSaved:o,onCancel:o}),u(ri,{deviceId:e.id,initialLocation:e.location,label:t(`customize.identity.room`),layout:`stacked`,onError:a,onSaved:o,onCancel:o}),u(Xr,{label:t(`customize.identity.hidden`),layout:`stacked`,value:u(xn,{"aria-label":t(`deviceDisplay.hideFromLists`),checked:h,disabled:f.isPending,onChange:t=>f.mutate({deviceId:e.id,display:Ja(e.display,t.target.checked)},l)})}),u(Xr,{label:t(`customize.identity.role`),layout:`stacked`,value:Ya(e)?u(`span`,{children:ro(e.role,t(`customize.identity.noRole`))}):u(_e,{"aria-label":t(`customize.identity.role`),value:e.role??``,disabled:d.isPending,options:[{value:``,label:t(`customize.identity.noRole`)},...to(e.role,e.type).map(e=>({value:e,label:ro(e,t(`customize.identity.noRole`))}))],onChange:t=>d.mutate({deviceId:e.id,role:t.target.value===``?null:t.target.value},l)})})]}),i!==null&&u(`p`,{role:`alert`,className:`mt-2 text-xs text-danger break-words`,children:i})]})}function ro(e,t){return e==null||e===``?t:Za(e)?ue(e).label:e}function io(e,t){if(e.kind!==`known`||typeof t!=`string`||t.length===0)return null;let n=_t(e.value,t),r=new Map(e.value.map(e=>[e.id,e])),i=new Map;for(let e of n){let t=r.get(e)?.parentDeviceId,n=t==null?void 0:r.get(t);n!==void 0&&n.type===`container`&&i.set(e,n.name)}return{location:t,ids:n,containers:i}}function ao(e,t,n){return Gt(e,t?.ids??new Set,n)}function oo(e,t){return e?.containers.get(t)??null}function so(e,t){return e===null||t.length===0?e:{...e,ids:new Set([...e.ids].filter(e=>!t.includes(e)))}}function co(e,t,n){return e.kind===`known`?ao(e.value,t,n).suggested.length:0}function lo(e,t){let n=[t,e.detail].filter(e=>e!==null&&e!==``);return n.length===0?null:n.join(` · `)}function uo({location:e,devices:t,action:n,onPick:i,onPickAll:a}){let{t:o}=X();if(t.length===0)return null;let s=o(`customize.suggest.heading`,{location:e});return r(`section`,{"aria-label":s,className:`flex flex-col gap-1`,children:[r(`div`,{className:`flex min-h-7 items-center gap-2`,children:[u(`h3`,{className:`${f} min-w-0 flex-1`,children:s}),a!==void 0&&t.length>1&&u(K,{variant:`ghost`,size:`sm`,onClick:a,children:o(`customize.suggest.addAll`,{count:t.length})})]}),u(`ul`,{className:`flex flex-col divide-y divide-border rounded-md border border-border`,children:t.map(e=>{let t=lo(e,e.container===null||e.name.includes(e.container)?null:o(`customize.suggest.in`,{container:e.container}));return r(`li`,{className:`${_} flex items-center gap-3`,children:[r(`div`,{className:`min-w-0 flex-1`,children:[u(`div`,{className:`text-xs text-foreground break-words`,children:e.name}),t!==null&&u(`div`,{className:`text-[11px] text-foreground-subtle break-words`,children:t})]}),u(K,{variant:`outline`,size:`sm`,"aria-label":o(n===`add`?`customize.suggest.addNamed`:`customize.suggest.useNamed`,{name:e.name}),onClick:()=>i(e.id),children:o(n===`add`?`customize.suggest.add`:`customize.suggest.use`)})]},e.id)})})]})}n();function fo(e){return e===`pending`?`pending`:e===`error`?`failed`:`answered`}function po({excludeDeviceIds:e,room:t,onSelect:n}){let{t:a}=X(),s=At({projection:`slim`}),c=s.status===`success`?s.data:null,l=i(()=>{if(c===null)return[];let t=new Set(e);return Si(c).filter(e=>!t.has(e.id))},[c,e]),d=i(()=>new Map(l.map(e=>[e.id,e])),[l]),f=i(()=>ao(l,t,e=>e.id),[l,t]),p=i(()=>f.others.map(e=>({id:e.id,name:e.name,type:e.type,...e.location===null?{}:{location:e.location}})),[f.others]);if(s.status===`error`)return u(H,{title:a(`customize.picker.devicesFailed`),message:s.error?.message??``});let m=e=>{let t=d.get(e);t!==void 0&&n(t)};return r(o,{children:[t!==null&&u(uo,{location:t.location,devices:f.suggested.map(e=>({id:e.id,name:e.name,container:oo(t,e.id),detail:e.type})),action:`use`,onPick:m}),p.length===0&&f.suggested.length>0?null:u(kt,{devices:p,listState:fo(s.status),value:[],onChange:e=>{let t=e.at(-1);t!==void 0&&m(t)},noun:`device`,emptyLabel:a(`customize.assign.none`),showAll:!0,testId:`customize-field-device-picker`})]})}function mo({open:e,title:t,targetKind:n,excludeDeviceIds:i,room:a=null,confirmLabel:s,extra:l,extraComplete:d=!0,onConfirm:f,onClose:p}){let{t:m}=X(),[h,g]=c(null),[_,v]=c(null),y=()=>{g(null),v(null),p()};return u(R,{open:e,onOpenChange:e=>e?void 0:y(),children:r(ze,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,"aria-label":t,children:[u(De,{children:u(Xt,{children:t})}),u(In,{className:`flex flex-col gap-3 p-2 sm:p-4`,children:e&&r(o,{children:[r(`section`,{"aria-label":m(`customize.assign.stepDevice`),className:`flex flex-col gap-1`,children:[u(`h3`,{className:`text-[10px] sm:text-[11px] font-semibold text-foreground uppercase tracking-wider`,children:m(`customize.assign.stepDevice`)}),h===null?u(po,{excludeDeviceIds:i,room:a,onSelect:g}):r(`p`,{className:`flex items-center gap-2 text-xs text-foreground`,children:[h.name,u(K,{variant:`ghost`,size:`sm`,onClick:()=>{g(null),v(null)},children:m(`customize.assign.change`)})]})]}),h!==null&&r(`section`,{"aria-label":m(`customize.assign.stepField`),className:`flex flex-col gap-1`,children:[u(`h3`,{className:`text-[10px] sm:text-[11px] font-semibold text-foreground uppercase tracking-wider`,children:m(`customize.assign.stepField`)}),u(bi,{device:h,targetKind:n,selected:_===null?null:{cap:_.cap,path:_.path},onPick:v,onBack:()=>{g(null),v(null)}})]}),h!==null&&l!==void 0&&r(`section`,{"aria-label":m(`customize.assign.stepDetails`),className:`flex flex-col gap-1`,children:[u(`h3`,{className:`text-[10px] sm:text-[11px] font-semibold text-foreground uppercase tracking-wider`,children:m(`customize.assign.stepDetails`)}),l]})]})}),r(re,{children:[u(K,{variant:`ghost`,onClick:y,children:m(`customize.assign.cancel`)}),u(K,{disabled:_===null||!d,onClick:()=>{_!==null&&(f(_),g(null),v(null))},children:s})]})]})})}function ho(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function go(e,t){let n=Pi(e,t);return n===void 0?{kind:`absent`}:{kind:`value`,value:n}}function _o(e,t,n){return ho(t)?go(t,n):e.status===`error`?{kind:`unknown`,reason:e.error?.message??`the value could not be read`}:e.status===`pending`||e.data===void 0?{kind:`pending`}:e.data===null?{kind:`absent`}:go(e.data,n)}function vo(e,t,n){let r=e?`active`:`muted`;return t.cap===`contact`&&t.path===`entryOpen`?{text:e?n.open:n.closed,tone:r}:gr[t.cap]===t.path?{text:e?n.active:n.inactive,tone:r}:{text:String(e),tone:`normal`}}function yo(e,t,n){switch(e.kind){case`pending`:return{text:`…`,tone:`muted`};case`unknown`:return{text:`?`,title:e.reason,tone:`warning`};case`absent`:return{text:`—`,tone:`muted`};case`value`:{let r=e.value;return r===null?{text:`—`,tone:`muted`}:typeof r==`boolean`?vo(r,t,n):typeof r==`number`?{text:t.path===`percentage`?`${Math.round(r)} %`:String(r),tone:`normal`}:typeof r==`string`?{text:r,tone:`normal`}:{text:JSON.stringify(r),tone:`normal`}}}}var bo=0;function xo(e){let t=S(),n=Hn({deviceId:e?.deviceId??bo,capName:e?.cap??``},{enabled:e!==null}),r=wn(t.trpcClient,e?.deviceId??null,e?.cap??``);return e===null?{kind:`absent`}:_o({status:n.status,data:n.data,error:n.error===null||n.error===void 0?null:{message:n.error.message}},r,e.path)}var So={muted:`text-foreground-subtle`,active:`text-success`,normal:`text-foreground`,warning:`text-warning`};function Co({target:e}){let{t}=X(),n=xo(e);return e===null?null:u(wo,{display:yo(n,e,{active:t(`customize.assign.value.active`),inactive:t(`customize.assign.value.inactive`),open:t(`customize.assign.value.open`),closed:t(`customize.assign.value.closed`)})})}function wo({display:e}){return u(`span`,{className:`text-xs ${So[e.tone]}`,title:e.title,children:e.text})}function $({name:e,detail:t,meta:n,value:i,shown:a,problem:o,onRemove:s,removeLabel:c,busy:l=!1}){return r(`li`,{className:`${_} grid grid-cols-[minmax(0,1fr)_auto] items-center gap-x-3 gap-y-1 sm:grid-cols-[minmax(0,2fr)_minmax(0,1fr)_minmax(0,1fr)_1.75rem]`,children:[r(`div`,{className:`min-w-0`,children:[u(`div`,{className:`text-xs text-foreground break-words`,children:e}),t!==null&&u(`div`,{className:`text-[11px] text-foreground-subtle break-words`,children:t}),o!==void 0&&u(`div`,{role:`alert`,className:`text-[11px] text-warning break-words`,children:o})]}),u(`div`,{className:`row-start-2 col-start-1 text-[11px] text-foreground-subtle empty:hidden sm:row-start-auto sm:col-start-auto sm:empty:block`,children:n}),u(`div`,{className:`row-start-3 col-start-1 empty:hidden sm:row-start-auto sm:col-start-auto sm:empty:block`,children:a===void 0?u(Co,{target:i}):a!==null&&u(wo,{display:a})}),u(`div`,{className:`row-start-1 col-start-2 flex justify-end sm:row-start-auto sm:col-start-auto`,children:s!==void 0&&u(Ge,{icon:yt,variant:`ghost`,size:`sm`,"aria-label":c,disabled:l,onClick:s})})]})}function To({id:e,...t}){return u(ke,{headingId:`customize-${e}`,...t})}function Eo({id:e,icon:t,title:n,headerControl:i,addLabel:a,onAdd:s,addDisabled:c=!1,notices:l,suggestion:d,children:f}){let{t:p}=X(),m=s!==void 0&&a!==void 0;return r(To,{id:e,icon:t,title:n,actions:r(o,{children:[i,m&&!c&&d!==void 0&&d.count>0&&r(K,{variant:`ghost`,size:`sm`,onClick:d.onOpen,children:[u(Zt,{className:`h-3.5 w-3.5`,"aria-hidden":!0}),p(`customize.suggest.hint`,{count:d.count,location:d.location})]}),m&&u(K,{variant:`outline`,size:`sm`,disabled:c,onClick:s,children:a})]}),children:[l!==void 0&&u(`div`,{className:`flex flex-col gap-1 px-3 pt-2 empty:hidden sm:px-4`,children:l}),u(`ul`,{className:`flex flex-col divide-y divide-border`,children:f})]})}function Do({availability:e}){let{t}=X();return e.kind===`pending`?u(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:t(`customize.assign.checking`)}):e.kind===`unknown`?u(`p`,{role:`alert`,className:`text-xs text-warning`,children:t(`customize.assign.unknown`,{reason:e.reason})}):null}function Oo(e,t){if(e.status===`error`)return{kind:`unknown`,reason:e.error?.message??`the request failed`};let n=e.data;return e.status===`pending`||n===void 0?{kind:`pending`}:{kind:`known`,value:t(n)}}var ko=[{id:`motion`,labelKey:`customize.assign.filters.motion`,caps:[`motion`]},{id:`contact`,labelKey:`customize.assign.filters.contact`,caps:[`contact`]},{id:`all`,labelKey:`customize.assign.filters.all`,caps:yr}];function Ao(e,t){return t!==null&&e.includes(t)?t:yr.find(t=>e.includes(t))??null}function jo(e,t){let n=[e,t].filter(e=>e!==null&&e!==``);return n.length===0?null:n.join(` · `)}function Mo(e,t){if(e.id===t.hostId||e.type===q.Container||t.excludeCameras&&e.isCamera)return!1;let n=Y({addonId:e.addonId,stableId:e.stableId});return!t.assigned.has(n)}function No(e){return e.devices.flatMap(t=>{if(!Mo(t,e))return[];let n=e.capIndex.get(t.id)??[],r=Ao(n,e.preferredCap);if(r===null)return[];let i=gr[r];return[{deviceId:t.id,ref:{addonId:t.addonId,stableId:t.stableId},name:t.name,detail:jo(t.integration,t.location),meta:r,caps:n,value:i===void 0?null:{deviceId:t.id,cap:r,path:i}}]}).toSorted((e,t)=>e.name.localeCompare(t.name))}function Po(e,t,n){let r=zn(t);return e.filter(e=>{if(n!==null&&!e.caps.some(e=>n.caps.includes(e)))return!1;if(r.length===0)return!0;let t=bt({id:e.deviceId,name:e.name,...e.detail===null?{}:{detail:e.detail},...e.meta===null?{}:{type:e.meta}});return r.every(e=>t.includes(e))})}function Fo(e){let t=e.find(e=>e.query.status===`error`);if(t!==void 0)return{kind:`unknown`,reason:t.query.error?.message??`the request failed`};if(e.some(e=>e.query.status!==`success`||e.query.data===void 0))return{kind:`pending`};let n=new Map;for(let t of e)for(let e of t.query.data??[])n.set(e,[...n.get(e)??[],t.cap]);return{kind:`known`,value:n}}function Io(e,t){let n=Cn.useQueries(n=>e.map(e=>n.deviceManager.listDeviceIdsByCaps({capNames:[e]},{enabled:t})));return Fo(e.map((e,t)=>{let r=n[t];return{cap:e,query:r===void 0?{status:`pending`}:{status:r.status,data:r.data,error:r.error===null?null:{message:r.error.message}}}}))}n();function Lo(e,t){let n=$e(e,t);return n.kind===`resolved`?n.integration.name:null}function Ro(e){let t=At({projection:`slim`},{enabled:e}),{data:n}=gt(void 0,{enabled:e}),r=t.error===null||t.error===void 0?null:t.error.message;return i(()=>Oo({status:t.status,data:t.data,error:r===null?null:{message:r}},e=>e.map(e=>({id:e.id,name:e.name,addonId:e.addonId,stableId:e.stableId,type:e.type,location:e.location,isCamera:e.isCamera,integration:Lo(e,n),parentDeviceId:e.parentDeviceId,primaryChildEntityId:e.primaryChildEntityId??null,role:e.role??null}))),[t.status,t.data,r,n])}function zo(e){let t=Ro(e.enabled),n=Io(yr,e.enabled);return t.kind===`unknown`?t:n.kind===`unknown`?n:t.kind===`pending`||n.kind===`pending`?{kind:`pending`}:{kind:`known`,value:No({devices:t.value,capIndex:n.value,hostId:e.hostId,excludeCameras:e.excludeCameras,assigned:e.assigned,preferredCap:e.preferredCap})}}n();function Bo(e,t){let n=typeof e==`string`&&e.length>0,r=Ro(t&&n);return i(()=>t?io(r,e):null,[t,r,e])}function Vo(){let{t:e}=X(),t=nt();return(n,r)=>t({title:e(`customize.assign.removeConfirm.title`),message:r?`${e(`customize.assign.removeConfirm.message`,{what:n})} ${e(`customize.assign.removeConfirm.last`)}`:e(`customize.assign.removeConfirm.message`,{what:n}),confirmLabel:e(`customize.assign.removeConfirm.confirm`),variant:`danger`})}n();function Ho(e){return e===null?null:Ei(e,`replace`)?`replace`:Ei(e,`add`)?`add`:null}function Uo({device:e,handle:t,availability:n,onAdvanced:i}){let{t:a}=X(),s=Vo(),[l,d]=c(!1),[f,p]=c(null),m=qa(t.state),h=zi(m,`battery`),g=Ho(h),_=g===null?null:yi(h?.fields.percentage),v=Ro(_!==null),y=so(Bo(e.location,n.kind===`present`&&h===null),[e.id]);if(n.kind===`absent`)return null;let b=n.kind===`present`?n.mode:null,x=t.state.kind===`none`||t.state.kind===`present`,S=_===null||v.kind!==`known`?null:v.value.find(e=>Y({addonId:e.addonId,stableId:e.stableId})===Y(_.source))??null,C=_===null?``:S?.name??Y(_.source),w=async e=>{let n=await t.save(e);p(n.kind===`refused`?n.reason:null)},T=async()=>{if(m===null)return;let e=hi(m,`battery`);await s(a(`customize.battery.removeWhat`,{name:C}),e===null)&&await w(e)},E=b!==null&&x&&h===null&&!t.saving;return r(o,{children:[r(Eo,{id:`battery`,icon:Ht,title:a(`customize.battery.title`),addLabel:a(b===`replace`?`customize.battery.replace`:`customize.battery.add`),onAdd:E?()=>d(!0):void 0,...y===null?{}:{suggestion:{count:y.ids.size,location:y.location,onOpen:()=>d(!0)}},notices:r(o,{children:[u(Do,{availability:n}),_!==null&&v.kind===`unknown`&&u(`p`,{role:`alert`,className:`text-xs text-warning break-words`,children:a(`customize.assign.devicesUnreadable`,{reason:v.reason})}),f!==null&&u(`p`,{role:`alert`,className:`text-xs text-danger break-words`,children:f})]}),children:[b===`replace`&&x&&u($,{name:a(`customize.battery.native`),detail:null,meta:a(h===null?`customize.assign.native`:`customize.battery.nativeReplaced`),value:h===null?{deviceId:e.id,cap:`battery`,path:`percentage`}:null,removeLabel:``}),h===null&&b===`add`&&x&&u(`li`,{className:`px-3 sm:px-4 py-1.5 sm:py-2 text-[11px] text-foreground-subtle`,children:a(`customize.assign.none`)}),_!==null&&u($,{name:C,detail:`${_.cap}.${_.fieldPath}`,meta:a(g===`replace`?`customize.assign.replaces`:`customize.assign.adds`),value:S===null?null:{deviceId:S.id,cap:_.cap,path:_.fieldPath},problem:S===null&&v.kind===`known`?a(`customize.assign.missingKept`):void 0,onRemove:x?()=>void T():void 0,removeLabel:a(`customize.assign.removeNamed`,{name:C}),busy:t.saving}),h!==null&&_===null&&u($,{name:a(`customize.battery.otherFormula`),detail:null,meta:u(Ga,{onAdvanced:i}),value:{deviceId:e.id,cap:`battery`,path:`percentage`},removeLabel:``})]}),u(mo,{open:l,title:a(b===`replace`?`customize.battery.replace`:`customize.battery.add`),targetKind:`number`,excludeDeviceIds:[e.id],room:y,confirmLabel:a(`customize.assign.add`),onConfirm:e=>{d(!1);let n=b===null?null:Ii({percentage:{source:e.ref,cap:e.cap,fieldPath:e.path,kind:e.kind},mode:b});n===null?p(a(`customize.assign.pickUnusable`)):w(vi(m,t.target,n))},onClose:()=>d(!1)})]})}n();function Wo(e,t){let n=e.source;if(n===null||t.kind!==`known`)return null;let r=Y(n.source);return t.value.find(e=>Y({addonId:e.addonId,stableId:e.stableId})===r)??null}function Go(e){let t=typeof e==`number`?e:typeof e==`string`?Number(e):NaN;return Number.isFinite(t)?t:null}function Ko({device:e,handle:t,availability:n,onAdvanced:i}){let{t:a}=X(),s=Vo(),[l,d]=c(!1),[f,p]=c(``),[m,h]=c(`percent`),[g,_]=c(null),v=qa(t.state),y=zi(v,`consumables`),b=wi(y),x=Ro(b.some(e=>e.source!==null)),S=b.flatMap(e=>{let t=Wo(e,x);return t===null?[]:[t.id]}),C=so(Bo(e.location,n.kind===`present`),[e.id,...S]);if(n.kind===`absent`)return null;let w=t.state.kind===`none`||t.state.kind===`present`,T=n.kind===`present`&&w&&!t.saving,E=Ti(f),D=b.find(e=>e.key===E)??null,O=D!==null,k=f.trim()!==``&&E===``,A=async e=>{let n=await t.save(e);_(n.kind===`refused`?n.reason:null)},j=()=>{d(!1),p(``),h(`percent`)},M=async e=>{if(y===null||v===null)return;let n=Li(y,e.key),r=n===null?hi(v,`consumables`):vi(v,t.target,n);await s(a(`customize.consumables.removeWhat`,{name:e.label}),r===null)&&await A(r)},N=r(`div`,{className:`flex flex-wrap items-end gap-2`,children:[r(`label`,{className:`flex w-full flex-col gap-1 text-[11px] text-foreground-subtle sm:w-56`,children:[a(`customize.consumables.name`),u(Ue,{"aria-label":a(`customize.consumables.name`),value:f,onChange:e=>p(e.target.value)})]}),r(`label`,{className:`flex w-full flex-col gap-1 text-[11px] text-foreground-subtle sm:w-40`,children:[a(`customize.consumables.unit`),u(_e,{"aria-label":a(`customize.consumables.unit`),value:m,options:Oi.map(e=>({value:e,label:a(`customize.consumables.units.${e}`)})),onChange:e=>{let t=Oi.find(t=>t===e.target.value);t!==void 0&&h(t)}})]}),O&&u(`p`,{role:`alert`,className:`basis-full text-xs text-warning`,children:a(`customize.consumables.takenBy`,{name:D.label})}),k&&u(`p`,{role:`alert`,className:`basis-full text-xs text-warning`,children:a(`customize.consumables.keyless`)})]});return r(o,{children:[r(Eo,{id:`consumables`,icon:un,title:a(`customize.consumables.title`),addLabel:a(`customize.consumables.add`),onAdd:T?()=>d(!0):void 0,...C===null?{}:{suggestion:{count:C.ids.size,location:C.location,onOpen:()=>d(!0)}},notices:r(o,{children:[u(Do,{availability:n}),x.kind===`unknown`&&b.some(e=>e.source!==null)&&u(`p`,{role:`alert`,className:`text-xs text-warning break-words`,children:a(`customize.assign.devicesUnreadable`,{reason:x.reason})}),g!==null&&u(`p`,{role:`alert`,className:`text-xs text-danger break-words`,children:g})]}),children:[b.map(e=>{let n=e.source;if(e.unit===null||n===null)return u($,{name:e.label,detail:a(`customize.consumables.otherFormula`),meta:u(Ga,{onAdvanced:i}),value:null,removeLabel:``},e.key);let r=Wo(e,x),o=r?.name??Y(n.source);return u($,{name:e.label,detail:`${a(`customize.consumables.units.${e.unit}`)} · ${o}`,meta:`${n.cap}.${n.fieldPath}`,value:r===null?null:{deviceId:r.id,cap:n.cap,path:n.fieldPath},problem:r===null&&x.kind===`known`?a(`customize.assign.missingKept`):void 0,onRemove:w?()=>void M(e):void 0,removeLabel:a(`customize.assign.removeNamed`,{name:e.label}),busy:t.saving},e.key)}),b.length===0&&n.kind===`present`&&w&&u(`li`,{className:`px-3 sm:px-4 py-1.5 sm:py-2 text-[11px] text-foreground-subtle`,children:a(`customize.assign.none`)})]}),u(mo,{open:l,title:a(`customize.consumables.pickTitle`),targetKind:`number`,excludeDeviceIds:[e.id],room:C,confirmLabel:a(`customize.assign.add`),extra:N,extraComplete:E!==``&&!O,onConfirm:e=>{let n=Go(e.value);if(n!==null&&(n<0||m===`percent`&&n>100)){j(),_(a(`customize.consumables.outOfRange`,{value:n}));return}let r=Ci(y,{key:E,label:f,remaining:{source:e.ref,cap:e.cap,fieldPath:e.path,kind:e.kind},unit:m});j(),r===null?_(a(`customize.assign.pickUnusable`)):A(vi(v,t.target,r))},onClose:j})]})}n();function qo(e){return e.kind===`pending`?`pending`:e.kind===`unknown`?`failed`:`answered`}function Jo(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 Yo({open:e,title:t,selection:n,candidates:a,filters:o,room:s=null,confirmLabel:l,onConfirm:f,onClose:p}){let{t:m}=X(),[h,g]=c(null),[_,v]=c([]),y=o?.find(e=>e.id===h)??o?.[0]??null,b=a.kind===`known`?a.value:[],x=a.kind===`known`?Po(a.value,``,y):[],S=ao(b,s,e=>e.deviceId).suggested,C=ao(x,s,e=>e.deviceId).others,w=i(()=>Jo(C),[C]),T=qo(a),E=b.filter(e=>_.includes(e.deviceId));d(()=>{e||(v([]),g(null))},[e]);let D=()=>{v([]),g(null),p()},O=e=>{e.length!==0&&(f(e),v([]),g(null))},k=()=>O(E);return u(R,{open:e,onOpenChange:e=>e?void 0:D(),children:r(ze,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,"aria-label":t,children:[u(De,{children:u(Xt,{children:t})}),r(In,{className:`flex flex-col gap-2 p-2 sm:p-4`,children:[o!==void 0&&o.length>0&&u(`div`,{className:`flex flex-wrap gap-1`,role:`tablist`,"aria-label":m(`customize.assign.filtersLabel`),children:o.map(e=>u(`button`,{type:`button`,role:`tab`,"aria-selected":(y?.id??null)===e.id,className:`inline-flex items-center gap-1 rounded-full border px-1.5 py-0.5 text-[10px] font-medium transition-colors ${(y?.id??null)===e.id?`border-primary/50 bg-primary/15 text-primary`:`border-border bg-surface text-foreground-subtle hover:bg-surface-hover`}`,onClick:()=>g(e.id),children:m(e.labelKey)},e.id))}),s!==null&&u(uo,{location:s.location,devices:S.map(e=>({id:e.deviceId,name:e.name,container:oo(s,e.deviceId),detail:e.detail})),action:`add`,onPick:e=>O(S.filter(t=>t.deviceId===e)),...n===`multi`?{onPickAll:()=>O(S)}:{}}),a.kind===`unknown`?u(`p`,{role:`alert`,className:`text-xs text-warning`,children:m(`customize.assign.unknown`,{reason:a.reason})}):w.length===0&&S.length>0?null:u(kt,{devices:w,listState:T,value:_,onChange:e=>v(n===`single`?e.length>0?[e[e.length-1]]:[]:e),noun:`device`,emptyLabel:m(`customize.assign.none`),showAll:!0,testId:`customize-device-picker`})]}),r(re,{children:[u(K,{variant:`ghost`,onClick:D,children:m(`customize.picker.cancel`)}),u(K,{disabled:E.length===0,onClick:k,children:l(E.length)})]})]})})}function Xo(e){if(e===null)return[];let t=ki(e);return Mi(e).map(e=>{let n=Y(e);return{key:n,ref:e,caps:t.filter(e=>Y(e.source)===n).map(e=>e.cap)}})}function Zo(e,t){let n=ki(e);if(n.length===0)return!1;let{enabled:r,...i}=e,{enabled:a,...o}=Nr({camera:t,sources:n,enabled:!0});return Ri(i,o)}function Qo(e){return e?.enabled!==!1}function $o(e,t,n){let r=[...e===null?[]:ki(e),...n.flatMap(e=>zr(e.ref,e.caps))];return r.length===0?null:Nr({camera:t,sources:r,enabled:Qo(e)})}function es(e,t,n){let r=ki(e).filter(e=>Y(e.source)!==n);return r.length===0?null:Nr({camera:t,sources:r,enabled:Qo(e)})}function ts(e,t){return{...e,enabled:t}}n();function ns({device:e,handle:t,availability:n,onAdvanced:i}){let{t:a}=X(),s=Vo(),[l,d]=c(!1),[f,p]=c(null),m=qa(t.state),h=zi(m,`doorbell`),g=h===null||Zo(h,t.target),_=g?Xo(h):[],v=Ro(_.length>0),y=n.kind===`present`&&g,b=Bo(e.location,y),x=zo({hostId:e.id,excludeCameras:!1,assigned:new Set(_.map(e=>e.key)),preferredCap:null,enabled:l||b!==null});if(n.kind===`absent`)return null;let S=t.state.kind===`none`||t.state.kind===`present`,C=S&&!t.saving,w=n.kind===`present`&&C&&g,T=async e=>{let n=e===null?m===null?null:hi(m,`doorbell`):vi(m,t.target,e),r=await t.save(n);p(r.kind===`refused`?r.reason:null)},E=async(e,n)=>{if(h===null||m===null)return;let r=es(h,t.target,e.key),i=r===null&&hi(m,`doorbell`)===null;await s(a(`customize.doorbell.removeWhat`,{name:n}),i)&&await T(r)},D=e=>v.kind===`known`?v.value.find(t=>Y({addonId:t.addonId,stableId:t.stableId})===e.key)??null:null;return r(o,{children:[r(Eo,{id:`doorbell`,icon:Lt,title:a(`customize.doorbell.title`),headerControl:h===null?void 0:r(`label`,{className:`flex items-center gap-1.5 text-[11px] text-foreground`,children:[u(xn,{"aria-label":a(`customize.doorbell.active`),checked:h.enabled!==!1,disabled:!C,onChange:e=>void T(ts(h,e.target.checked))}),a(`customize.doorbell.active`)]}),addLabel:a(`customize.doorbell.add`),onAdd:w?()=>d(!0):void 0,...b===null?{}:{suggestion:{count:co(x,b,e=>e.deviceId),location:b.location,onOpen:()=>d(!0)}},notices:r(o,{children:[u(Do,{availability:n}),v.kind===`unknown`&&u(`p`,{role:`alert`,className:`text-xs text-warning break-words`,children:a(`customize.assign.devicesUnreadable`,{reason:v.reason})}),f!==null&&u(`p`,{role:`alert`,className:`text-xs text-danger break-words`,children:f})]}),children:[_.map(e=>{let n=D(e),r=n?.name??e.key,i=Ao(e.caps,null),o=i===null?void 0:gr[i];return u($,{name:r,detail:n===null?null:jo(n.integration,n.location),meta:e.caps.join(`, `),value:n!==null&&i!==null&&o!==void 0?{deviceId:n.id,cap:i,path:o}:null,problem:n===null&&v.kind===`known`?a(`customize.assign.missingKept`):void 0,onRemove:S?()=>void E(e,r):void 0,removeLabel:a(`customize.assign.removeNamed`,{name:r}),busy:t.saving},e.key)}),!g&&u($,{name:a(`customize.doorbell.otherFormula`),detail:null,meta:u(Ga,{onAdvanced:i}),value:null,removeLabel:``}),h===null&&n.kind===`present`&&S&&u(`li`,{className:`px-3 sm:px-4 py-1.5 sm:py-2 text-[11px] text-foreground-subtle`,children:a(`customize.assign.none`)})]}),u(Yo,{open:l,title:a(`customize.doorbell.pickTitle`),selection:`multi`,candidates:x,room:b,confirmLabel:e=>a(`customize.assign.addCount`,{count:e}),onConfirm:e=>{d(!1),T($o(h,t.target,e.map(e=>({ref:e.ref,caps:e.caps}))))},onClose:()=>d(!1)})]})}function rs(e){return e.slot===`linked-devices`}function is(e){if(e.status===`error`)return{kind:`unknown`,reason:e.error?.message??`the request failed`};if(e.status===`pending`||e.data===void 0)return{kind:`pending`};for(let t of e.data)if(t.state===`ok`&&t.slot===`linked-devices`&&rs(t.value))return{kind:`present`,slot:t,value:t.value};let t=e.data.find(e=>e.state===`unreachable`);return t!==void 0&&t.state===`unreachable`?{kind:`unknown`,reason:t.reason}:{kind:`absent`}}function as(e,t){let n=t.trackedDeviceIds??[],r=e=>t=>({deviceId:t.deviceId,name:t.name,health:t.health,implied:e,tracked:n.includes(t.deviceId)});return[...e.sources.map(r(!1)),...(e.impliedSources??[]).map(r(!0))]}function os(e,t){let n=new Set([...e.sources,...e.impliedSources??[]].map(e=>e.deviceId));return(t.trackedDeviceIds??[]).filter(e=>!n.has(e))}function ss(e,t){return{...e,deviceIds:[...e.deviceIds,...t.filter(t=>!e.deviceIds.includes(t))]}}function cs(e,t){return{...e,deviceIds:e.deviceIds.filter(e=>e!==t),...e.trackedDeviceIds===void 0?{}:{trackedDeviceIds:e.trackedDeviceIds.filter(e=>e!==t)}}}function ls(e,t,n){let r=e.trackedDeviceIds??[],i=n?[...r.filter(e=>e!==t),t]:r.filter(e=>e!==t);return{...e,trackedDeviceIds:i}}function us(e,t,n){return e.flatMap(e=>{let r=t.get(e.deviceId);return n.has(e.deviceId)||r===void 0?[]:[{deviceId:e.deviceId,ref:{addonId:r.addonId,stableId:r.stableId},name:e.parentName===null?e.name:`${e.parentName} · ${e.name}`,detail:jo(r.integration,e.location),meta:e.type,caps:[],value:null}]})}n();function ds(e){return e==null?null:e.message}function fs({device:e}){let{t}=X(),n=s(),i=Vo(),a=br.includes(e.type),[l,d]=c(!1),[f,p]=c(!1),[m,h]=c(null),g=L({deviceId:e.id},{enabled:a}),_=is({status:g.status,data:g.data,error:ds(g.error)===null?null:{message:ds(g.error)??``}}),v=_.kind===`present`?_.slot.slotRef:``,y=_.kind===`present`?[...as(_.slot,_.value).map(e=>e.deviceId),...os(_.slot,_.value)]:[],b=We(),x=Ro(a&&_.kind===`present`&&(l||y.length>0)),S=Bo(e.location,a&&_.kind===`present`),C=Un({deviceId:e.id,slotRef:v},{enabled:(l||S!==null)&&_.kind===`present`});if(!a||_.kind===`absent`)return null;if(_.kind!==`present`)return u(Eo,{id:`linked`,icon:Bn,title:t(`customize.linked.title`),notices:_.kind===`pending`?u(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:t(`customize.assign.checking`)}):u(`p`,{role:`alert`,className:`text-xs text-warning break-words`,children:t(`customize.assign.unknown`,{reason:_.reason})}),children:null});let w=_.value,T=new Map(x.kind===`known`?x.value.map(e=>[e.id,e]):[]),E=w.trackedDeviceIds!==void 0,D=(e,t)=>{let n=T.get(e.deviceId);return{...e,name:e.name??n?.name??null,type:n?.type??null,detail:n===void 0?null:jo(n.integration,n.location),orphan:t}},O=[...as(_.slot,w).map(e=>D(e,!1)),...os(_.slot,w).map(e=>D({deviceId:e,name:null,health:`ok`,implied:!1,tracked:!0},!0))],k=new Set(y),A=x.kind===`unknown`?x:C.status===`error`?{kind:`unknown`,reason:ds(C.error)??`the request failed`}:x.kind===`pending`||C.status===`pending`||C.data===void 0?{kind:`pending`}:{kind:`known`,value:us(C.data.candidates,T,k)},j=async r=>{if(f){h(t(`customize.saveInFlight`));return}p(!0),h(null);try{await b.mutateAsync({deviceId:e.id,slotRef:_.slot.slotRef,value:r}),await g.refetch(),await n.invalidateQueries({queryKey:[[`deviceManager`]]})}catch(e){h(e instanceof Error?e.message:String(e))}finally{p(!1)}},M=async e=>{await i(t(`customize.linked.removeWhat`,{name:e.name??`#${e.deviceId}`}),!1)&&await j(cs(w,e.deviceId))},N=[{key:`device`,header:t(`customize.linked.device`),cell:e=>r(`div`,{className:`flex flex-col min-w-0`,children:[u(`span`,{className:`truncate text-xs text-foreground`,children:e.name??`#${e.deviceId}`}),e.detail!==null&&u(`span`,{className:`truncate text-[11px] text-foreground-subtle`,children:e.detail}),e.orphan&&u(`span`,{className:`text-[11px] text-foreground-subtle`,children:t(`customize.linked.notLinked`)}),e.health!==`ok`&&u(`span`,{role:`alert`,className:`text-[11px] text-warning`,children:t(`customize.linked.health.${e.health}`)})]})},{key:`type`,header:t(`customize.linked.type`),headerClassName:`hidden sm:table-cell`,cellClassName:`hidden sm:table-cell text-xs text-foreground-subtle`,cell:e=>e.type===null?`—`:Ye(e.type).label},{key:`controls`,header:t(`customize.linked.controls`),headerClassName:`hidden md:table-cell`,cellClassName:`hidden md:table-cell text-xs text-foreground-subtle`,cell:e=>e.orphan?`—`:t(`customize.linked.yes`)},...E?[{key:`tracked`,header:t(`customize.linked.tracked`),cellClassName:`text-right`,headerClassName:`text-right`,cell:e=>u(on,{checked:e.tracked,disabled:f,"aria-label":t(`customize.linked.trackFor`,{name:e.name??e.deviceId}),onCheckedChange:t=>void j(ls(w,e.deviceId,t))})}]:[],{key:`remove`,header:``,cellClassName:`text-right w-10`,cell:e=>e.implied||e.orphan?null:u(Ge,{icon:yt,variant:`ghost`,size:`sm`,"aria-label":t(`customize.assign.removeNamed`,{name:e.name??e.deviceId}),disabled:f,onClick:t=>{t.stopPropagation(),M(e)}})}];return r(o,{children:[u(Eo,{id:`linked`,icon:Bn,title:t(`customize.linked.title`),addLabel:t(`customize.linked.add`),onAdd:f?void 0:()=>d(!0),...S===null?{}:{suggestion:{count:co(A,S,e=>e.deviceId),location:S.location,onOpen:()=>d(!0)}},notices:r(o,{children:[x.kind===`unknown`&&u(`p`,{role:`alert`,className:`text-xs text-warning break-words`,children:t(`customize.assign.devicesUnreadable`,{reason:x.reason})}),m!==null&&u(`p`,{role:`alert`,className:`text-xs text-danger break-words`,children:m})]}),children:r(`li`,{className:`list-none px-3 py-2 sm:px-4`,children:[O.length===0?u(`p`,{className:`text-[11px] text-foreground-subtle`,children:t(`customize.assign.none`)}):u(hn,{mode:`generic`,items:O,getKey:e=>String(e.deviceId),getSearchText:e=>[e.name??``,e.detail??``,e.type??``,String(e.deviceId)].join(` `),getFilterType:e=>e.type===null?null:Ye(e.type).label,columns:N,searchPlaceholder:t(`customize.assign.search`),emptyLabel:t(`customize.assign.none`)}),O.some(e=>!e.orphan)&&u(`p`,{className:`mt-2 text-[10px] text-foreground-subtle`,children:t(`customize.linked.controlsAlways`)}),E&&u(`p`,{className:`mt-0.5 text-[10px] text-foreground-subtle`,children:t(`customize.linked.trackedHint`)})]})}),u(Yo,{open:l,title:t(`customize.linked.pickTitle`),selection:`multi`,candidates:A,room:S,confirmLabel:e=>t(`customize.assign.addCount`,{count:e}),onConfirm:e=>{d(!1),j(ss(w,e.map(e=>e.deviceId)))},onClose:()=>d(!1)})]})}function ps(e){return e===null||e.state===`unreadable`?null:e.state===`configured`?e.sensors:[]}function ms(e){return{addonId:e.addonId,stableId:e.stableId,mode:e.mode}}function hs(e){return e.length===0?null:{sensors:[...e]}}function gs(e,t){let n=new Set(e.map(hr));return hs([...e.map(ms),...t.filter(e=>!n.has(hr(e))).map(e=>({...e,mode:vr}))])}function _s(e,t,n){return hs(e.map(e=>hr(e)===t?{...ms(e),mode:n}:ms(e)))}function vs(e,t){return hs(e.filter(e=>hr(e)!==t).map(ms))}function ys(e){return e?.state===`configured`&&e.cameraMotion!==void 0}function bs(e){return e===null||e.state===`unreadable`?null:e.state===`configured`?e.cameraMotion??`always`:`always`}function xs(e){return e===null||e.state===`unreadable`?!1:e.state===`not-configured`||ys(e)}function Ss(e){return e?.state===`configured`&&(e.notForwarded!==void 0||e.notEnforced!==void 0)}function Cs(e,t,n){if(e!==`present`||t===null||n)return{kind:`none`};let r=t.cameraLevel;return r===void 0?{kind:`unknown`}:{kind:`level`,detected:r.detected,atMs:r.atMs}}n();var ws=5e3;function Ts(e){return e.state===`missing`||e.state===`unreadable`?e.stableId:e.name}function Es({device:e,availability:n,sensors:i}){let{t:a}=X(),s=Vo(),l=gn(),[f,p]=c(!1),[m,h]=c(null),g=t(!1),[_,v]=c(!1),[y,b]=c(!1),x=i.status,S=t(i.refetch);S.current=i.refetch,d(()=>{let e=setInterval(()=>{g.current||S.current()},ws);return()=>clearInterval(e)},[]);let C=ps(x);d(()=>{x!==null&&b(!1)},[x]);let w=i.presence===`present`&&xs(x)&&!y?C:null,T=Ro(C!==null&&C.length>0),E=Bo(e.location,w!==null&&n.kind===`present`),D=zo({hostId:e.id,excludeCameras:!0,assigned:new Set((C??[]).map(hr)),preferredCap:`motion`,enabled:f||E!==null});if(n.kind===`absent`)return null;let O=ys(x),k=Ss(x)?`passes`:bs(x),A=Cs(i.presence,x,y),j=A.kind===`none`?null:A.kind===`unknown`?{text:`?`,tone:`warning`,title:a(`customize.motion.cameraLevelUnknown`)}:{text:a(A.detected?`customize.assign.value.active`:`customize.assign.value.inactive`),tone:A.detected?`active`:`muted`,title:a(`customize.motion.cameraLevelOwn`,{at:new Date(A.atMs).toLocaleTimeString()})},M=_||l.isPending,N=async t=>{if(g.current){h(a(`customize.saveInFlight`));return}g.current=!0,v(!0);try{await l.mutateAsync({deviceId:e.id,config:t}),h(null),await i.refetch()===`failed`&&b(!0)}catch(e){h(e instanceof Error?e.message:String(e))}finally{g.current=!1,v(!1)}},P=async e=>{w!==null&&await s(a(`customize.motion.removeWhat`,{name:Ts(e)}),!1)&&await N(vs(w,hr(e)))},F=e=>{if(T.kind!==`known`||!(`deviceId`in e))return null;let t=T.value.find(t=>t.id===e.deviceId);return t===void 0?null:jo(t.integration,t.location)};return r(o,{children:[r(Eo,{id:`motion`,icon:V,title:a(`customize.motion.title`),addLabel:a(`customize.motion.add`),onAdd:w!==null&&n.kind===`present`?()=>p(!0):void 0,addDisabled:M,...E===null?{}:{suggestion:{count:co(D,E,e=>e.deviceId),location:E.location,onOpen:()=>p(!0)}},notices:r(o,{children:[u(Do,{availability:n}),i.presence===`pending`&&n.kind!==`pending`&&u(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:a(`customize.motion.reading`)}),x?.state===`unreadable`&&u(`p`,{role:`alert`,className:`text-xs text-warning break-words`,children:a(`customize.motion.unreadable`,{reason:x.reason})}),x?.state===`configured`&&!xs(x)&&u(`p`,{role:`alert`,className:`text-xs text-warning`,children:a(`customize.motion.olderOrchestrator`)}),y&&u(`p`,{role:`alert`,className:`text-xs text-warning`,children:a(`customize.motion.refetchFailed`)}),x?.state===`configured`&&x.notForwarded!==void 0&&u(`p`,{role:`alert`,className:`text-xs text-warning`,children:a(`customize.motion.notForwarded.${x.notForwarded}`)}),x?.state===`configured`&&x.notEnforced!==void 0&&u(`p`,{role:`alert`,className:`text-xs text-warning`,children:a(`customize.motion.notEnforced`)}),T.kind===`unknown`&&u(`p`,{role:`alert`,className:`text-xs text-warning break-words`,children:a(`customize.assign.devicesUnreadable`,{reason:T.reason})}),m!==null&&u(`p`,{role:`alert`,className:`text-xs text-danger break-words`,children:m})]}),children:[u($,{name:a(`customize.motion.camera`),detail:null,meta:k===null?a(`customize.assign.native`):`${a(`customize.motion.cameraState.${k}`)} · ${a(`customize.assign.native`)}`,value:null,shown:j,removeLabel:``}),(C??[]).map(e=>{let t=hr(e),n=Ts(e),r=e.state===`ready`?Ao(e.caps,`motion`):null,i=r===null?void 0:gr[r];return u($,{name:n,detail:F(e),meta:O&&w!==null?u(_e,{"aria-label":a(`customize.motion.modeFor`,{name:n}),value:e.mode,disabled:M,options:_r.options.map(e=>({value:e,label:a(`customize.motion.mode.${e}`)})),onChange:e=>{let n=_r.safeParse(e.target.value);n.success&&w!==null&&N(_s(w,t,n.data))}}):a(`customize.motion.mode.${e.mode}`),value:r!==null&&i!==void 0&&`deviceId`in e?{deviceId:e.deviceId,cap:r,path:i}:null,problem:e.state===`ready`?void 0:e.reason===e.state?a(`customize.motion.state.${e.state}`):`${a(`customize.motion.state.${e.state}`)}: ${e.reason}`,onRemove:w===null?void 0:()=>void P(e),removeLabel:a(`customize.assign.removeNamed`,{name:n}),busy:M},t)})]}),u(Yo,{open:f,title:a(`customize.motion.pickTitle`),selection:`multi`,candidates:D,room:E,filters:ko,confirmLabel:e=>a(`customize.assign.addCount`,{count:e}),onConfirm:e=>{if(p(!1),w===null)return;let t=gs(w,e.map(e=>e.ref));if(t!==null&&t.sensors.length>8){h(a(`customize.motion.tooMany`,{max:8}));return}N(t)},onClose:()=>p(!1)})]})}var Ds={"numeric-sensor":{fieldPath:`value`,unitField:`unit`},"temperature-sensor":{fieldPath:`celsius`,unitField:`unit`},"humidity-sensor":{fieldPath:`percent`,unitField:`unit`},"pressure-sensor":{fieldPath:`hpa`,unitField:`unit`},"ambient-light-sensor":{fieldPath:`lux`,unitField:`unit`}},Os=new Set([q.Camera]);function ks(e){return e.unitField===null?[e.fieldPath]:[e.fieldPath,e.unitField]}function As(e,t){if(Os.has(e))return{kind:`absent`};let n=null;for(let[e,r]of Object.entries(Ds))if(t.has(e)){n={cap:e,fieldPath:r.fieldPath,unitField:r.unitField};break}let r=null;for(let e of Lr)if(t.has(e)){let t=gr[e];if(t!==void 0){r={cap:e,fieldPath:t};break}}return n===null&&r===null?{kind:`absent`}:{kind:`present`,convert:n,invert:r}}function js(e){return Fr(e.from,e.to)?jr(e):null}function Ms(e){return Sr(e)}var Ns=/^convert\(v,\s*"[^"]*",\s*"[^"]*"\)$/;function Ps(e){return e!==void 0&&Ns.test(e.expr)}function Fs(e){return e===void 0||e.expr===`!v`||Ns.test(e.expr)?!1:e.bindings.v!==void 0}function Is(e){let t=e.expr.trim();if(t===``)return{kind:`refused`,reason:`expression is empty`};let n={kind:`expression`,expr:t,bindings:{v:{kind:`from`,source:e.self,cap:e.cap,fieldPath:e.fieldPath}}},r=Or({source:n,now:Date.now(),read:()=>({state:`fresh`,value:e.probe})});return r.state===`unavailable`?{kind:`refused`,reason:r.reason}:{kind:`ok`,feature:{kind:`fields`,cap:e.cap,fields:{[e.fieldPath]:n}}}}function Ls(e,t,n){if(e===null)return null;let r=zi(e,n.cap);if(r===null)return e;let i=new Set(ks(n)),a=Object.fromEntries(Object.entries(r.fields).filter(([e])=>!i.has(e)));return Object.keys(a).length===0?hi(e,n.cap):vi(e,t,{kind:`fields`,cap:n.cap,...r.enabled===void 0?{}:{enabled:r.enabled},fields:a,...r.items===void 0?{}:{items:r.items}})}n();function Rs(e){if(typeof e!=`object`||!e)return;let t=Reflect.get(e,`unit`);return typeof t==`string`?t:void 0}function zs(e,t){if(typeof e!=`object`||!e)return;let n=Reflect.get(e,t);return typeof n==`number`&&Number.isFinite(n)?n:void 0}function Bs(e,t){let n=zi(e,t.cap);if(n===null)return;let r=n.fields[t.fieldPath];return r!==void 0&&r.kind===`expression`?r:void 0}function Vs(e,t){let n=Bs(e,t);return n===void 0||!Ps(n)?null:/^convert\(v,\s*"[^"]*",\s*"([^"]*)"\)$/.exec(n.expr)?.[1]??null}function Hs(e,t){let n=Bs(e,t);return n===void 0||!Fs(n)?null:n.expr}function Us(e,t,n){let r=zi(e,t);if(r===null)return!1;let i=r.fields[n];return i!==void 0&&i.kind===`expression`&&i.expr===`!v`}function Ws(e){return typeof e==`number`||typeof e==`boolean`||typeof e==`string`?String(e):e===null?`null`:JSON.stringify(e)}function Gs({device:e,target:t,handle:n,facts:i}){let{t:a}=X(),o=S(),[s,l]=c(null),[d,f]=c(``),[h,g]=c(null),_=i.nativeCaps.kind===`known`?i.nativeCaps.value:null,v=_===null?null:As(e.type,_),y=v?.kind===`present`?v.convert?.cap??``:``,b=wn(o.trpcClient,e.id,y);if(i.nativeCaps.kind===`pending`)return u(`section`,{className:`${p} ${m}`,children:u(Do,{availability:{kind:`pending`}})});if(i.nativeCaps.kind===`unknown`)return u(`section`,{className:`${p} ${m}`,children:u(Do,{availability:{kind:`unknown`,reason:i.nativeCaps.reason}})});if(v===null||v.kind===`absent`)return null;let x=qa(n.state),C=v.convert,w=v.invert,T=C===null?void 0:Rs(b),E=T===void 0?void 0:Rr(T)??T,D=E===void 0?void 0:Ar(E),O=C===null?null:Vs(x,C),k=C===null?null:Hs(x,C),A=h??k??``,j=w===null?!1:Us(x,w.cap,w.fieldPath),M=n.state.kind===`none`||n.state.kind===`present`,N=C===null?0:zs(b,C.fieldPath)??0,P=C!==null&&A.trim()!==``?{kind:`expression`,expr:A.trim(),bindings:{v:{kind:`from`,source:t,cap:C.cap,fieldPath:C.fieldPath}}}:null,F=P===null||C===null?null:Ai(P,new Map([[wr(t,C.cap),b===void 0?{kind:`pending`}:{kind:`value`,slice:b}]]),Date.now()),I=async e=>{let t=await n.save(e);l(t.kind===`refused`?t.reason:null)},ee=async()=>{if(C===null||E===void 0||d===``)return;let e=js({self:t,cap:C.cap,fieldPath:C.fieldPath,from:E,to:d,unitField:C.unitField});if(e===null){l(a(`customize.numericTransforms.convertRefused`));return}g(null),await I(vi(x,t,e))},L=async()=>{C!==null&&(await I(Ls(x,t,C)),f(``))},te=async()=>{if(C===null)return;let e=Is({self:t,cap:C.cap,fieldPath:C.fieldPath,expr:A,probe:N});if(e.kind===`refused`){l(e.reason);return}f(``),await I(vi(x,t,e.feature))},R=async()=>{C!==null&&(await I(Ls(x,t,C)),g(``))},z=async()=>{if(w===null)return;let e=Ms({self:t,cap:w.cap});if(e===null){l(a(`customize.numericTransforms.invertRefused`));return}await I(vi(x,t,e))},ne=async()=>{w===null||x===null||await I(hi(x,w.cap))};return u(To,{id:`numeric-transforms`,icon:Hi,title:a(`customize.numericTransforms.title`),testId:`numeric-transforms-card`,children:r(`div`,{className:`${m} flex flex-col gap-3`,children:[u(`p`,{className:`text-[11px] text-foreground-subtle`,children:a(`customize.numericTransforms.blurb`)}),s!==null&&u(`p`,{role:`alert`,className:`text-[11px] text-danger break-words`,children:s}),C!==null&&r(`div`,{className:`flex flex-col gap-2`,"data-testid":`numeric-convert`,children:[u(`label`,{className:`text-[11px] font-medium text-foreground`,children:a(`customize.numericTransforms.publishUnit`)}),u(`p`,{className:`text-[11px] text-foreground-subtle`,children:E===void 0?a(`customize.numericTransforms.fromUnknown`):a(`customize.numericTransforms.fromUnit`,{unit:E})}),u(`div`,{className:`w-full sm:max-w-xs`,children:u(Qt,{dimension:D,value:d===``?O??``:d,onChange:e=>{f(e),e!==``&&g(``)},disabled:!M||n.saving||E===void 0,"aria-label":a(`customize.numericTransforms.toUnit`),inheritLabel:a(`customize.numericTransforms.pickUnit`),emptyReason:a(`customize.numericTransforms.fromUnknown`)})}),r(`div`,{className:`flex flex-wrap gap-2`,children:[u(K,{size:`sm`,disabled:!M||n.saving||E===void 0||d===``||d===E,onClick:()=>void ee(),children:a(`customize.numericTransforms.applyConvert`)}),O!==null&&u(K,{size:`sm`,variant:`outline`,disabled:!M||n.saving,onClick:()=>void L(),children:a(`customize.numericTransforms.clearConvert`)})]})]}),C!==null&&r(`div`,{className:`flex flex-col gap-2`,"data-testid":`numeric-script`,children:[u(Ni,{label:a(`customize.numericTransforms.script`),value:A,bindings:[`v`],onChange:e=>{g(e),e.trim()!==``&&f(``)}}),u(`p`,{className:`text-[11px] text-foreground-subtle`,children:a(`customize.numericTransforms.scriptBlurb`)}),F!==null&&u(`p`,{role:`status`,className:`text-[11px] font-mono text-foreground`,"data-testid":`numeric-script-preview`,children:F.kind===`value`?a(`customize.numericTransforms.preview`,{source:Ws(N),result:Ws(F.value)}):F.kind===`waiting`?a(`customize.numericTransforms.previewWaiting`):F.kind===`unavailable`?a(`customize.numericTransforms.previewError`,{reason:F.reason}):a(`customize.numericTransforms.previewRuntimeOnly`)}),r(`div`,{className:`flex flex-wrap gap-2`,children:[u(K,{size:`sm`,disabled:!M||n.saving||A.trim()===``,onClick:()=>void te(),children:a(`customize.numericTransforms.applyScript`)}),k!==null&&u(K,{size:`sm`,variant:`outline`,disabled:!M||n.saving,onClick:()=>void R(),children:a(`customize.numericTransforms.clearScript`)})]})]}),w!==null&&r(`div`,{className:`flex flex-col gap-2`,"data-testid":`numeric-invert`,children:[u(`label`,{className:`text-[11px] font-medium text-foreground`,children:a(`customize.numericTransforms.invert`)}),u(`p`,{className:`text-[11px] text-foreground-subtle`,children:a(`customize.numericTransforms.invertBlurb`)}),u(`div`,{className:`flex flex-wrap gap-2`,children:j?u(K,{size:`sm`,variant:`outline`,disabled:!M||n.saving,onClick:()=>void ne(),children:a(`customize.numericTransforms.clearInvert`)}):u(K,{size:`sm`,disabled:!M||n.saving,onClick:()=>void z(),children:a(`customize.numericTransforms.applyInvert`)})})]})]})})}n();function Ks(e){return e instanceof Error?e.message:String(e)}function qs(e){let n=ne({addonId:e.addonId,stableId:e.stableId}),r=Ie(),i=Ce(),a=te(),o=Ka({status:n.status,data:n.data,error:n.error===null||n.error===void 0?null:{message:n.error.message}}),{t:s}=X(),l=t(!1),[u,d]=c(!1),f=async e=>{let t=xi(o,e);try{switch(t.kind){case`refused`:return{kind:`refused`,reason:t.reason};case`noop`:return{kind:`saved`};case`create`:await r.mutateAsync({block:t.input});break;case`update`:await i.mutateAsync({blockId:t.blockId,expectedUpdatedAt:t.expectedUpdatedAt,block:{composition:t.composition}});break;case`delete`:await a.mutateAsync({blockId:t.blockId});break}return await n.refetch(),{kind:`saved`}}catch(e){return{kind:`refused`,reason:Ks(e)}}};return{target:e,state:o,saving:u||r.isPending||i.isPending||a.isPending,save:async e=>{if(l.current)return{kind:`refused`,reason:s(`customize.saveInFlight`)};l.current=!0,d(!0);try{return await f(e)}finally{l.current=!1,d(!1)}}}}var Js=`pipeline-orchestrator`;function Ys(e){return e.status===`pending`?`pending`:e.status===`error`?`unknown`:e.data===void 0?`pending`:e.data.cameraSensors===void 0?`absent`:`present`}function Xs(e,t){return e===`absent`?`absent`:Ys(t)}async function Zs(e){try{return(await e()).isError?`failed`:`answered`}catch{return`failed`}}function Qs(e,t){let n=Wn(Js),r=Be({deviceId:e},{enabled:t&&n!==`absent`}),i=()=>Zs(r.refetch);return t?{presence:Xs(n,{status:r.status,data:r.data}),status:r.data?.cameraSensors??null,refetch:i}:{presence:`absent`,status:null,refetch:i}}function $s(e,t){let n=Ee({deviceType:e.type}),r=Wt({deviceId:e.id}),i=An({deviceId:e.id}),a=Oo(n,e=>new Set(e.caps.map(e=>e.cap))),o=Oo(r,e=>Ba(e.entries)),s=Oo(i,e=>e);return{deviceType:e.type,composable:a,nativeCaps:o,wireable:s,composed:new Set((t?.features??[]).map(e=>e.cap))}}var ec={kind:`unknown`,reason:`the composer reports no value for this field`};function tc(e,t){let n=Y(e);return t.get(n)??n}function nc(e,t,n){let r=n.nativeCaps.has(e.cap)?`replaced`:`added`,i=t.filter(t=>t.cap===e.cap&&t.origin===`composed`);if(e.cap===`doorbell`){let t=Mi(e).map(e=>tc(e,n.sourceNames)).join(` + `),a=i.find(e=>e.field===`lastPressedAt`);return[{key:`doorbell`,label:`doorbell`,origin:{kind:r,from:t},value:a?.value??ec}]}return e.cap===`consumables`?wi(e).map(e=>{let t=t=>Ur(Ir,e.key,t),a=i.find(e=>e.field===t(`level`)||e.field===t(`remaining.value`)),o=e.source===null?``:tc(e.source.source,n.sourceNames);return{key:`consumables.${e.key}`,label:`consumables · ${e.label}`,origin:{kind:r,from:o},value:a?.value??ec}}):i.map(e=>({key:e.key,label:`${e.cap}.${e.field}`,origin:{kind:r,from:e.from},value:e.value}))}function rc(e){let t=Di({composition:e.composition,nativeCaps:e.nativeCaps,state:e.state,nativeFields:new Map,snapshot:null,sourceNames:e.sourceNames});return e.composition.features.flatMap(n=>n.kind===`fields`?nc(n,t,e):[])}function ic(e,t){if(e?.state!==`configured`||e.sensors.length===0)return null;let n=e.cameraMotion===`never`?[]:[t.camera],r=e.sensors.map(e=>t.sensor(e.state===`missing`||e.state===`unreadable`?e.stableId:e.name,e.mode));return[...n,...r].join(` + `)}var ac=`${_} grid grid-cols-1 gap-x-3 gap-y-0.5 items-baseline sm:grid-cols-[minmax(0,1fr)_minmax(0,2fr)_minmax(0,1.5fr)]`,oc=`font-mono text-[11px] text-foreground break-words`,sc=`text-[11px] text-foreground-subtle break-words`,cc=`text-[11px] break-words sm:text-right`;function lc({device:e,composition:t,state:n,nativeCaps:i,cameraSensors:a}){let{t:o}=X(),s=t!==null&&n!==null,c=Ro(s),l=new Map(c.kind===`known`?c.value.map(e=>[Y({addonId:e.addonId,stableId:e.stableId}),e.name]):[]),d=s&&i.kind===`known`?rc({composition:t,nativeCaps:i.value,state:n,sourceNames:l}):[],f=s&&i.kind===`known`&&d.length===0&&t.features.length>0,p=ic(a,{camera:o(`customize.changes.motion.camera`),sensor:(e,t)=>o(`customize.changes.motion.${t}`,{name:e})}),m=s&&i.kind!==`known`;return d.length===0&&p===null&&!m&&!f?null:r(To,{id:`changes`,icon:Nn,title:o(`customize.changes.title`),children:[m&&u(`p`,{role:i.kind===`unknown`?`alert`:`status`,className:`px-3 sm:px-4 py-1.5 sm:py-2 text-[11px] text-foreground-subtle`,children:i.kind===`unknown`?o(`customize.changes.unknown`,{reason:i.reason}):o(`customize.changes.reading`)}),f&&u(`p`,{className:`px-3 sm:px-4 py-1.5 sm:py-2 text-[11px] text-foreground-subtle`,children:o(`customize.changes.noRows`)}),r(`ul`,{className:`divide-y divide-border`,children:[d.map(e=>r(`li`,{className:ac,children:[u(`span`,{className:oc,children:e.label}),u(`span`,{className:sc,children:c.kind===`known`?o(`customize.changes.origin.${e.origin.kind}`,{from:e.origin.from}):o(`customize.changes.originUnread.${c.kind}`,{kind:o(`customize.changes.kind.${e.origin.kind}`),reason:c.kind===`unknown`?c.reason:``})}),u(`span`,{className:cc,children:u(uc,{value:e.value})})]},e.key)),p!==null&&r(`li`,{className:ac,children:[u(`span`,{className:oc,children:`motion`}),u(`span`,{className:sc,children:p}),u(`span`,{className:cc,children:u(Co,{target:{deviceId:e.id,cap:`motion`,path:`detected`}})})]})]})]})}function uc({value:e}){let{t}=X();switch(e.kind){case`value`:return r(`span`,{children:[ji(e.value,!0),e.staleReason!==null&&r(`span`,{className:`text-warning`,children:[` `,`·`,` `,t(`customize.changes.value.stale`,{reason:e.staleReason})]})]});case`unavailable`:return u(`span`,{className:`text-warning`,children:t(`customize.changes.value.unavailable`,{reason:e.reason})});case`unknown`:return u(`span`,{className:`text-foreground-subtle`,children:t(`customize.changes.value.unknown`,{reason:e.reason})});case`off`:return u(`span`,{className:`text-foreground-subtle`,children:t(`customize.status.off`)})}}n();function dc({deviceId:e,activeSubTab:t,onSubTabChange:n}){let{t:r}=X(),i=Tn({deviceId:e}),a=i.data;return a==null?i.status===`error`?u(H,{title:r(`customize.deviceUnreadable`),message:i.error?.message??``,onRetry:()=>void i.refetch()}):a===null?u(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:r(`customize.noSuchDevice`,{deviceId:e})}):u(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:r(`customize.loadingDevice`)}):a.addonId===`composer`?u(fc,{device:a}):u(pc,{device:a,target:{addonId:a.addonId,stableId:a.stableId},activeSubTab:t,onSubTabChange:n})}function fc({device:e}){let{t}=X(),n=e.stableId.startsWith(`composed-`)?e.stableId.slice(Er.length):null;return r(`section`,{className:`${p} ${m} flex flex-col gap-2`,children:[u(`p`,{className:`text-xs text-foreground`,children:t(`customize.composed.body`)}),n!==null&&u(oi,{className:`text-[11px] text-primary hover:underline`,to:fi(n),children:t(`customize.composed.edit`)})]})}function pc({device:e,target:t,activeSubTab:n,onSubTabChange:i}){let a=qs(t),o=Wn(`composer`),{t:s}=X(),c=Qs(e.id,e.type===q.Camera),l=$s(e,qa(a.state)),d={deviceType:e.type,composable:l.composable,nativeCaps:l.nativeCaps,cameraSensors:c.presence},f=()=>i(ci),p=a.state.kind===`none`||a.state.kind===`present`;return n===`advanced`?r(`div`,{className:`flex flex-col gap-3`,children:[u(hc,{state:a.state}),p&&u(mc,{device:e,target:t,handle:a,facts:l,onDone:()=>i(`main`)})]}):r(`div`,{className:`flex flex-col gap-3`,children:[u(no,{device:e}),o===`absent`&&u(`p`,{role:`alert`,className:`text-xs text-warning`,children:s(`customize.composerAbsent`)}),a.state.kind!==`none`&&u(hc,{state:a.state}),u(ns,{device:e,handle:a,availability:Wa(`doorbell`,d),onAdvanced:f}),u(Es,{device:e,handle:a,availability:Wa(`motion`,d),sensors:c}),u(Uo,{device:e,handle:a,availability:Wa(`battery`,d),onAdvanced:f}),u(Ko,{device:e,handle:a,availability:Wa(`consumables`,d),onAdvanced:f}),u(Gs,{device:e,target:t,handle:a,facts:l}),u(fs,{device:e}),u(lc,{device:e,composition:qa(a.state),state:a.state.kind===`present`?a.state.view.state:null,nativeCaps:l.nativeCaps,cameraSensors:c.status}),r(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[p?u(Ga,{onAdvanced:f}):u(`span`,{}),u(gc,{handle:a})]})]})}function mc({device:e,target:t,handle:n,facts:r,onDone:i}){let a=n.state.kind===`present`?n.state:null;return u(Fi,{initial:a===null?gi(t):_i(a.composition,``),blockId:a===null?null:a.view.block.id,deviceType:e.type,targetName:e.name,nativeCaps:r.nativeCaps,targetFields:r.wireable,onCancel:i,save:async e=>{let t=await n.save(e);return t.kind===`saved`&&i(),t}})}function hc({state:e}){let{t}=X();switch(e.kind){case`pending`:return u(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:t(`customize.status.pending`)});case`unknown`:return u(H,{title:t(`customize.status.unknownTitle`),message:e.reason});case`not-loaded`:return u(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:t(`customize.status.notLoaded`,{reason:e.reason})});case`none`:return null;case`present`:{let n=e.view.block;return r(`div`,{className:`flex flex-wrap items-center gap-2`,children:[u(Sn,{variant:n.status===`running`?`success`:n.status===`failed`?`danger`:`warning`,children:t(`customize.blockStatus.${n.status}`)}),!n.enabled&&u(Sn,{variant:`default`,children:t(`customize.status.off`)}),n.lastError!==void 0&&u(`span`,{className:`text-[11px] text-foreground-muted break-words`,children:n.lastError}),e.view.state.kind===`unreachable`&&u(`span`,{className:`text-[11px] text-warning`,children:t(`customize.status.composerUnreachable`,{reason:e.view.state.error})})]})}}}function gc({handle:e}){let{t}=X(),n=nt(),[i,a]=c(null);if(e.state.kind!==`present`)return null;let o=async()=>{if(!await n({title:t(`customize.remove.title`),message:t(`customize.remove.message`),confirmLabel:t(`customize.remove.confirm`),variant:`danger`}))return;let r=await e.save(null);a(r.kind===`refused`?r.reason:null)};return r(`div`,{className:`flex flex-col items-start gap-1`,children:[u(K,{variant:`danger`,size:`sm`,disabled:e.saving,onClick:()=>void o(),children:t(`customize.remove.button`)}),i!==null&&u(`p`,{role:`alert`,className:`text-[11px] text-danger break-words`,children:i})]})}var _c=`overview`;function vc(e,t){return e.some(e=>e.id===t)?t:_c}function yc({deviceId:e}){let t=s(),n=Number.isFinite(e),{data:i}=Tn({deviceId:e},{enabled:n}),a=typeof i?.type==`string`?i.type:`camera`;vn([`deviceManager`,`getBindings`],[`capability.binding-changed`]);let{data:o,isLoading:c,isError:l,error:d}=Wt({deviceId:e},{enabled:n}),{data:f}=It({deviceType:a},{enabled:!!a}),p=ce({onSuccess:()=>{t.invalidateQueries({queryKey:[[`deviceManager`,`getBindings`]]})}});if(c)return u(`div`,{className:`p-4`,children:u(`div`,{className:`h-20 rounded-lg border border-border bg-surface animate-pulse`})});if(l)return r(`div`,{className:`p-4 text-xs text-red-400`,children:[`Failed to load bindings: `,d instanceof Error?d.message:String(d)]});let m=new Map,h={};for(let e of f??[])h[e.capName]=e.wrappers;for(let e of o?.entries??[])m.set(e.capName,{...e,wrappers:h[e.capName]??[]});for(let e of f??[])m.has(e.capName)||m.set(e.capName,{capName:e.capName,kind:`unbound`,providerAddonId:``,providerNodeId:``,nativeAddonId:``,wrappers:e.wrappers});let g=[...m.values()].toSorted((e,t)=>e.capName.localeCompare(t.capName));if(g.length===0)return r(`div`,{className:`flex flex-col items-center justify-center gap-2 p-8 text-foreground-subtle`,children:[u(qn,{className:`h-8 w-8 opacity-40`}),u(`p`,{className:`text-xs`,children:`No capability providers applicable to this device yet.`}),u(`p`,{className:`text-[10px] opacity-60`,children:`Native providers show up here as soon as the owning addon registers them.`})]});let _=g.filter(e=>e.kind!==`unbound`).length;return r(`div`,{className:`flex flex-col gap-3 p-1`,children:[r(`div`,{className:`text-[11px] text-foreground-subtle`,children:[u(`span`,{className:`font-medium text-foreground`,children:_}),` of `,g.length,` capabilit`,g.length===1?`y`:`ies`,` bound — rows marked `,u(`em`,{children:`unbound`}),` have a wrapper available you can activate.`]}),u(ae,{columns:[{key:`capability`,header:`Capability`,render:e=>u(`span`,{className:`font-mono text-foreground`,children:e.capName})},{key:`kind`,header:`Kind`,render:e=>u(bc,{kind:e.kind})},{key:`provider`,header:`Active Provider`,render:e=>u(`span`,{className:`font-mono text-foreground-subtle`,children:e.providerAddonId||u(`span`,{className:`opacity-40`,children:`—`})})},{key:`node`,header:`Node`,render:e=>e.providerNodeId?u(xc,{nodeId:e.providerNodeId}):u(`span`,{className:`text-[10px] opacity-40`,children:`—`})},{key:`native`,header:`Native`,render:e=>u(`span`,{className:`font-mono text-foreground-subtle`,children:e.nativeAddonId||u(`span`,{className:`opacity-40`,children:`—`})})},{key:`wrapper`,header:`Wrapper`,render:t=>{let n=t.kind===`wrapped`?t.providerAddonId:null;return u(Sc,{wrappers:t.wrappers,activeWrapperId:n,disabled:p.isPending,onPick:r=>{let i=n===r;p.mutate({deviceId:e,capName:t.capName,wrapperAddonId:r,active:!i})}})}}],rows:g,rowKey:e=>e.capName,minWidthPx:720})]})}function bc({kind:e}){return e===`native`?r(`span`,{className:`inline-flex items-center gap-1 rounded-md border border-success/30 text-success bg-success/5 px-1.5 py-0.5 text-[10px] font-medium`,children:[u(U,{className:`h-3 w-3`}),`native`]}):e===`wrapped`?r(`span`,{className:`inline-flex items-center gap-1 rounded-md border border-primary/30 text-primary bg-primary/5 px-1.5 py-0.5 text-[10px] font-medium`,children:[u(pr,{className:`h-3 w-3`}),`wrapped`]}):e===`linked`?r(`span`,{className:`inline-flex items-center gap-1 rounded-md border border-warning/30 text-warning bg-warning/5 px-1.5 py-0.5 text-[10px] font-medium`,children:[u(Bn,{className:`h-3 w-3`}),`linked`]}):r(`span`,{className:`inline-flex items-center gap-1 rounded-md border border-border text-foreground-subtle/70 px-1.5 py-0.5 text-[10px] font-medium`,children:[u(jt,{className:`h-3 w-3`}),`unbound`]})}function xc({nodeId:e}){return u(`span`,{className:`inline-flex items-center rounded-md border border-border px-1.5 py-0.5 font-mono text-[10px] ${e===`hub`?`text-foreground-subtle`:`text-foreground`}`,children:e})}function Sc({wrappers:e,activeWrapperId:t,disabled:n,onPick:i}){return e.length===0?u(`span`,{className:`text-[10px] opacity-40`,children:`none available`}):u(`div`,{className:`flex flex-wrap gap-1`,children:e.map(e=>{let a=e===t;return r(`button`,{disabled:n,onClick:()=>i(e),title:a?`Click to deactivate (revert to native)`:`Activate wrapper ${e}`,className:`inline-flex items-center gap-1 rounded-md border px-1.5 py-0.5 font-mono text-[10px] transition-colors disabled:opacity-50 ${a?`border-primary/40 bg-primary/10 text-primary`:`border-border text-foreground-subtle hover:text-foreground hover:bg-surface-hover`}`,children:[u(a?bn:C,{className:`h-3 w-3`}),e]},e)})})}function Cc({deviceId:e,activeSubTab:t,onSubTabChange:n,deviceType:i,isAdmin:a}){return r(`div`,{className:`flex flex-col gap-3`,children:[di(i,a)&&u(Jt,{deviceId:e,readOnly:!0}),u(Jr,{deviceId:e,activeSubTab:t,onSubTabChange:n})]})}n();var wc=new Set([`package-detection`]);function Tc(e){return e?.settings!==void 0&&Object.keys(e.settings).length>0?`accelerator`:`camera`}function Ec(e){return e===`camera`?`this camera`:e===`node`?`node pin`:`hardware default`}function Dc(e){let{stored:t,draft:n,below:r,boundKeys:i}=e,a=n?.modelId===void 0?t?.modelId:n.modelId??void 0,o=Vr(n?.settings??t?.settings,r,i),s={...a===void 0?{}:{modelId:a},...o===void 0?{}:{settings:o}};return Object.keys(s).length>0?s:null}function Oc(e,t){return(e?.modelId??null)===(t?.modelId??null)&&Mr(e?.settings??{},t?.settings??{})}function kc({deviceId:e}){let t=s(),n=S().trpcClient,l=Ln({deviceId:e},{refetchOnMount:`always`}),d=ie({deviceId:e},{refetchOnMount:`always`}),p=ve(void 0,{refetchOnMount:`always`}),m=mr(Rt({addonId:`pipeline-orchestrator`}).data??null);vn([`nodes`,`topology`],[`agent.online`,`agent.offline`,`agent.unregistered`,`addon.installed`,`addon.uninstalled`]);let{nodes:h}=Ne(),_=i(()=>{let e=new Set((p.data??[]).map(e=>e.nodeId));return h.filter(t=>t.isOnline&&e.has(t.id)).map(e=>({id:e.id,name:e.name}))},[p.data,h]),v=_.map(e=>e.id).join(`,`),y=a({enabled:_.length>0,queryKey:[[`pipelineExecutor`,`getSchema`],`camera-step-schemas`,v],queryFn:async()=>{let e={};for(let t of _)try{e[t.id]=await n.pipelineExecutor.getSchema.query({nodeId:t.id})}catch{}return e}}),b=a({enabled:_.length>0,queryKey:[[`pipelineOrchestrator`,`getNodeInferenceDevices`],`camera-step`,v],queryFn:async()=>{let e={};for(let t of _)try{e[t.id]=(await n.pipelineOrchestrator.getNodeInferenceDevices.query({nodeId:t.id})).devices}catch{e[t.id]=[]}return e}}),x=()=>{t.invalidateQueries({queryKey:[[`pipelineOrchestrator`,`getCameraSettings`]]}),t.invalidateQueries({queryKey:[[`pipelineOrchestrator`,`getCameraStepOverrides`]]})},C=Xe({onSuccess:x}),w=de(),T=rt(),[E,D]=c(null),[O,k]=c(null),[A,j]=c(null),[M,N]=c(!1),[F,I]=c(null),ee=y.data??{},L=b.data??{},te=d.data??{},R=l.data??null,z=_.map(e=>ee[e.id]).find(e=>e!==void 0)??null,ne=i(()=>z?Fe(z):[],[z]),re=i(()=>rr(ne),[ne]),[B,V]=c(!1),H=i(()=>or(_,L,B),[_,L,B]),ae=i(()=>or(_,L,!0),[_,L]),oe=i(()=>or(_,L).length,[_,L]),se=(e,t)=>Zn(ee[e.nodeId],t),U=(e,t)=>te[e.nodeId]?.[e.deviceKey]?.[t],ce=(e,t)=>dr(L[e.nodeId]??[],e.deviceKey,t)??{},le=e=>{if(wc.has(e))return{kind:`zone-driven`};let t=Zn(z,e)?.enabledByDefault??!0,n=R?.stepToggles?.[e];return{kind:`gate`,effectiveOn:n??t,defaultOn:t,explicit:n!==void 0}},ue=(e,t,n)=>{let r=n?.stepId===t?n:null;return{node:ce(e,t),camera:r?.camera??R?.stepSettings?.[t],accelerator:r?.perAccelerator[e.id]?.settings??U(e,t)?.settings}},fe=(e,t,n)=>{let r=n?.stepId===t?n.perAccelerator[e.id]?.modelId:void 0;return r===void 0?U(e,t)?.modelId:r??void 0},W=(e,t)=>{let n=se(t,e),r=le(e),i=ar(e),a=Qn(ee[t.nodeId],t,U(t,`object-detection`)?.modelId),o=ue(t,e,null),s=Pr(o.node,o.camera,o.accelerator);return cr({addon:n,acc:t,gatedOn:r.kind===`gate`?r.effectiveOn:!0,model:n?ir(n,t,{nodePin:t.device.steps?.[e]?.modelId,cameraPin:U(t,e)?.modelId}):{modelId:void 0,source:`default`},...tr(e,s,a)&&a?{rootName:a.name}:{},...i?{clusterModelId:m[e]??i.defaultModelId}:{}})},pe=re.map(({node:e})=>({addonId:e.addonId,name:e.addonName,fieldLabels:sr(Zn(z,e.addonId))}));return p.isLoading||_.length>0&&(y.isLoading||b.isLoading)?u(`div`,{className:`animate-pulse p-4 text-xs text-foreground-subtle`,children:`Loading pipeline…`}):_.length===0?u(`div`,{className:`p-4 text-xs text-foreground-subtle`,children:`No pipeline node is online.`}):z===null?u(`div`,{className:`p-4 text-xs text-foreground-subtle`,children:`Catalog unavailable.`}):u(Xn,{tree:ne,searchRows:pe,accelerators:H,cellState:W,stepBadge:e=>u(P,{gate:le(e)}),disabledCount:ur(Object.fromEntries(_.map(e=>[e.id,L[e.id]??[]]))),showDisabled:B,onShowDisabledChange:V,dirty:E!==null,onDiscard:()=>D(null),summary:r(`span`,{className:g,children:[`This camera is balanced across `,oe,` accelerator`,oe===1?``:`s`,` at every session start · ovr = this camera overrides the node`]}),label:`Detection steps of this camera`,renderDetail:({stepId:t,accelerator:n,matchedField:i,closeButton:a,onEscape:s,headingRef:c})=>{let l=n??H[0],d=l?se(l,t)??Zn(z,t):null;if(d===null||l===void 0)return u(`div`,{className:`p-4 text-xs text-foreground-subtle`,children:`No step selected.`});let p=E?.stepId===t?E:null,m=Dn(d),h=Cr(m),_=ue(l,t,p),v=Pr(_.node,_.camera,_.accelerator),y=Qn(ee[l.nodeId],l,U(l,`object-detection`)?.modelId),b=ir(d,l,{nodePin:l.device.steps?.[t]?.modelId,cameraPin:fe(l,t,p)}).modelId,S=Pr(_.node,_.camera),P=Dr(_.accelerator,S,h),L=ar(t),te=le(t),ne=m.find(e=>`label`in e&&e.label===i)?.key??null,re=n===null?null:`${t}|${n.id}`,ie=n===null?`camera`:O?.key===re?O.scope:Tc(U(n,t)),B=e=>{I(null),D(n=>e(n?.stepId===t?n:{stepId:t,perAccelerator:{}}))},V=(e,t)=>B(n=>({...n,perAccelerator:{...n.perAccelerator,[e.id]:{...n.perAccelerator[e.id],...t}}})),oe=e=>B(n=>{let r=_.accelerator??{},i=kr(n.camera??R?.stepSettings?.[t],e,r,h),a={...n.perAccelerator};for(let r of ae){let i=n.perAccelerator[r.id]?.settings??U(r,t)?.settings;i!==void 0&&(a[r.id]={...a[r.id],settings:xr(i,e,h)})}return{...n,camera:i,perAccelerator:a}}),de=async()=>{if(p!==null){N(!0);try{let n=R?.stepSettings?.[t];p.camera!==void 0&&!Mr(p.camera,n??{})&&await T.mutateAsync({deviceId:e,addonId:t,settings:Object.keys(p.camera).length>0?{...p.camera}:null});let r=p.camera??n;for(let n of ae){let i=p.perAccelerator[n.id];if(i===void 0)continue;let a=U(n,t),o=Dc({stored:a,draft:i,below:Pr(ce(n,t),r),boundKeys:h});Oc(o,a)||await w.mutateAsync({deviceId:e,agentNodeId:n.nodeId,deviceKey:n.deviceKey,addonId:t,patch:o})}D(null),I({kind:`saved`})}catch(e){I({kind:`error`,error:e instanceof Error?e.message:`Save failed`})}finally{N(!1),x()}}},W=p===null?0:+(p.camera!==void 0&&!Mr(p.camera,R?.stepSettings?.[t]??{}))+Object.values(p.perAccelerator).length,pe=e=>{let n=se(e,t)??d,i=fe(e,t,p),a=e.device.steps?.[t]?.modelId,s=ir(n,e,{nodePin:a,cameraPin:i}),c=ue(e,t,p),l=Qn(ee[e.nodeId],e,U(e,`object-detection`)?.modelId),f=tr(t,Pr(c.node,c.camera,c.accelerator),l),m=$n(n,e)?f&&l?u(ht,{rootModel:l,stepModelId:s.modelId}):void 0:r(o,{children:[`No `,e.device.format,` build of this step — it does not run on this accelerator.`]});return{label:e.label,format:e.device.format,modelId:s.modelId,source:s.source,sourceLabel:Ec(s.source),models:pn(n.models??[],e.device.format),defaultModelId:n.defaultModelIdByFormat?.[e.device.format]??n.defaultModelId,expanded:A===e.id,onToggle:()=>j(t=>t===e.id?null:e.id),onChangeModel:t=>V(e,{modelId:t}),...i===void 0?{}:{onReset:()=>V(e,{modelId:null}),resetLabel:a===void 0?`Reset to hardware default`:`Reset to node pin`},...m===void 0?{}:{note:m},changed:p?.perAccelerator[e.id]?.modelId!==void 0}},me=L===null&&m.length>0?n===null?u(`p`,{className:g,children:`Applies to: all accelerators of this camera.`}):r(`div`,{className:`flex flex-wrap items-center gap-2`,children:[u(`span`,{className:`text-[11px] font-medium text-foreground`,children:`Applies to`}),u(Yt,{label:`Settings apply to`,options:[{value:`accelerator`,label:`This accelerator`},{value:`camera`,label:`All accelerators of this camera`}],value:ie,onChange:e=>re!==null&&k({key:re,scope:e})})]}):void 0;return u(Re,{ref:c,title:n===null?`${d.name} · this camera`:`${d.name} · ${n.label}`,subtitle:n===null?`${d.slot} · every accelerator this camera runs on`:`${d.slot} · ${n.device.format}`,leading:a,onEscape:s,headerActions:u(qt,{gate:te,busy:C.isPending,onSet:n=>C.mutate({deviceId:e,addonId:t,enabled:n})}),saveBar:{dirtyCount:W,saving:M,status:F?.kind??null,...F?.error===void 0?{}:{error:F.error},onSave:()=>void de(),onDiscard:()=>D(null),...me===void 0?{}:{scope:me}},children:r(`div`,{className:`space-y-3`,children:[r(`section`,{className:`space-y-2`,"aria-label":`Model`,children:[u(`h3`,{className:f,children:`Model`}),L===null?n===null?u(er,{rows:H.map(e=>{let n=ir(se(e,t)??d,e,{nodePin:e.device.steps?.[t]?.modelId,cameraPin:fe(e,t,p)});return{id:e.id,label:e.label,modelId:n.modelId,sourceLabel:Ec(n.source)}})}):u(Fn,{...pe(n)},n.id):u(lr,{step:L,engineFormat:l.device.format,runnableModelIds:pn(d.models??[],l.device.format).map(e=>e.id)})]}),L===null&&(m.length>0||y!==void 0)&&u(`section`,{"aria-label":`Settings`,className:`border-t border-border/60 pt-2`,children:u(Ac,{addon:d,fields:m,layers:_,scope:ie,viewed:n,modelId:dn(d,b,v,y),root:y,pinned:n===null?[]:P,highlightKey:ne,onChangeCamera:e=>B(t=>({...t,camera:e})),onChangeAccelerator:e=>V(l,{settings:e}),onApplyToAll:oe,onFollowNode:()=>V(l,{settings:P.reduce((e,t)=>xr(e,t,h),{..._.accelerator})})})}),u(Yn,{addonId:t,highlightLabel:i})]})})}})}function Ac({addon:e,fields:t,layers:n,scope:i,viewed:a,modelId:o,root:s,pinned:c,highlightKey:l,onChangeCamera:d,onChangeAccelerator:f,onApplyToAll:p,onFollowNode:m}){nr(l===null?null:en(l));let h=a!==null&&n.accelerator!==void 0;return u(Et,{addon:e,fields:t,layers:{node:n.node,...n.camera===void 0?{}:{camera:n.camera},...h?{accelerator:n.accelerator}:{}},target:i,labels:{...a===null?{}:{accelerator:`This accelerator`},camera:`All accelerators`,node:`Node`},modelId:o,...s===void 0?{}:{rootModel:s},pinnedKeys:c,highlightKey:l,onChangeLayer:i===`camera`?d:f,...c.length>0?{headerActions:r(`button`,{type:`button`,className:w,onClick:m,children:[`Follow the node for `,c.length,` pinned field`,c.length===1?``:`s`]})}:{},fieldActions:(e,t)=>a!==null&&t===`accelerator`?u(`button`,{type:`button`,className:w,onClick:()=>p(e),children:`Apply to all accelerators`}):null})}var jc=[{id:`object-detection`,label:`Object detection`,icon:`scan-search`},{id:`tracking`,label:`Tracking`,icon:`route`},{id:`motion`,label:`Motion`,icon:`activity`},{id:`stationary`,label:`Stationary`,icon:`square-parking`},{id:`zones`,label:`Zones`,icon:`shapes`},{id:`audio`,label:`Audio`,icon:`volume-2`},{id:`cluster`,label:`Cluster`,icon:`server`}],Mc={"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 Nc(e){return Mc[e]??`object-detection`}n();var Pc=`steps`,Fc=`settings`,Ic=new Set([Pc,Fc]);function Lc(e){return e.location===`top-tab`&&(e.tab===`detection-pipeline`||e.tab===`zones`)}function Rc({deviceId:t,activeSubTab:n,onSubTabChange:i}){return r(_n,{value:n&&Ic.has(n)?n:Pc,onValueChange:e(e=>{i?.(e)},[i]),className:`flex flex-col`,children:[r(it,{className:`flex-shrink-0`,children:[u(Ze,{value:Pc,children:`Steps`}),u(Ze,{value:Fc,children:`Settings`})]}),u(fe,{value:Pc,children:u(kc,{deviceId:t})}),u(fe,{value:Fc,children:u(Jr,{deviceId:t,sectionFilter:Lc,subTabGrouping:{groupOf:e=>Nc(e.id),tabs:jc}})})]})}var zc=`Notifications`,Bc=`This camera never notifies — no rule, no target, no alarm. Existing events, tracks and recordings are unaffected.`;function Vc(e){let{mutedDeviceIds:t,deviceId:n}=e,r=t===null?null:!t.includes(n),i=e.pendingOn??null;return{label:zc,on:r===null?null:i??r,available:r!==null,costWhenOff:Bc}}function Hc(e,t){return!e.available||e.on===null?null:{deviceId:t,muted:e.on}}n();function Uc(e){if(typeof e!=`object`||!e)return null;let t={...e}.mutedDeviceIds;return Array.isArray(t)?t.filter(e=>typeof e==`number`):null}function Wc({deviceId:t}){let n=s(),i=Number.isFinite(t),[a,o]=c(null),[l,d]=c(null),f=Vc({mutedDeviceIds:Uc(Ft({},{enabled:i}).data),deviceId:t,pendingOn:l}),p=sn({onError:e=>{console.error(`[DeviceNotificationMute] mute write failed — reverting`,{tags:{deviceId:t},meta:{error:e instanceof Error?e.message:String(e)}}),d(null),o(e instanceof Error?e.message:String(e)),n.invalidateQueries({queryKey:[[`notificationRules`,`listDeviceMutes`]]})},onSuccess:()=>{o(null),d(null),n.invalidateQueries({queryKey:[[`notificationRules`]]})}}),m=e(()=>{let e=Hc(f,t);e!==null&&(d(!e.muted),p.mutate(e))},[t,p,f]),h=f.on===null,g=f.on===!1,_=g?fn:Lt;return r(`div`,{className:`rounded-lg border border-border bg-surface overflow-hidden`,children:[r(`div`,{className:`border-b border-border px-4 py-2 flex items-center justify-between gap-2`,children:[u(`h2`,{className:`text-xs font-semibold text-foreground uppercase tracking-wider`,children:`Notifications`}),g&&u(`span`,{className:`rounded bg-warning/20 px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-wide text-warning`,children:`muted`})]}),r(`div`,{className:`px-4 py-3 flex items-start gap-3`,children:[r(`button`,{type:`button`,role:`switch`,"aria-label":f.label,"aria-checked":f.on===!0,disabled:!f.available||p.isPending,onClick:m,title:h?`Notification mute — state unknown; the notification centre did not answer.`:g?`Muted. ${f.costWhenOff}`:`Notifying. Muting it: ${f.costWhenOff}`,className:`inline-flex items-center gap-1.5 rounded-lg border px-2 py-1.5 text-[11px] font-medium transition-colors disabled:cursor-not-allowed ${a===null?h?`border-dashed border-border text-foreground-subtle/50`:g?`border-warning/40 text-warning hover:bg-warning/10`:`border-success/30 text-success hover:bg-success/10`:`border-danger/50 text-danger bg-danger/5`}`,children:[u(_,{className:`h-3.5 w-3.5`}),u(`span`,{children:h?`Unknown`:g?`Muted`:`Notifying`})]}),u(`p`,{className:`flex-1 text-[11px] leading-relaxed text-foreground-subtle`,children:a===null?h?`The notification centre did not answer, so this device’s mute state is unknown.`:f.costWhenOff:`Write failed: ${a}`})]})]})}function Gc(e,t){return{switchId:e,label:Hr[e].label,detail:t===void 0||t.length===0?null:t}}function Kc(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 qc(e){let t=Kc(e),n=new Set(e.sourceStillLive),r=e.sourceStillLive.map(e=>Gc(e,t.get(e)?.detail)),i=[...t.values()].filter(e=>e.outcome===`not-offered`&&!n.has(e.switchId)).map(e=>Gc(e.switchId,e.detail));return{inheritedId:e.sourceId,retiredId:e.targetId,swapped:e.swapped,verdict:r.length===0?`quiet`:`still-live`,stillLive:r,neverOffered:i}}n();function Jc(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 Yc({deviceId:e,deviceName:t}){let{t:n}=X(),a=nt(),[o,s]=c(null),l=At({isCamera:!0,projection:`slim`}),d=ut(),f=l.data!==void 0,p=i(()=>l.data===void 0?[]:Jc(l.data,e),[l.data,e]),m=p.find(e=>e.id===o)??null,h=d.data===void 0?null:qc(d.data),g=d.error===null?null:d.error.message,_=async()=>{m===null||m.id===e||await a({title:n(`deviceMigrate.confirmTitle`,`Replace “{{source}}” with “{{target}}”?`,{source:t,target:m.name}),message:n(`deviceMigrate.confirmMessage`,`“{{target}}” takes over number {{sourceId}}. That number is what every recording, event, rule, zone and home-automation export of “{{source}}” is filed under, so all of it follows the number to the new hardware and keeps working. “{{source}}” is switched off and handed number {{targetId}} in exchange. This swaps two device identities and cannot be undone from here.`,{source:t,target:m.name,sourceId:e,targetId:m.id}),confirmLabel:n(`deviceMigrate.confirmAction`,`Migrate`),variant:`danger`})&&d.mutate({sourceId:e,targetId:m.id})};return r(`div`,{className:`rounded-lg border border-border bg-surface px-4 py-3`,children:[r(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[r(`div`,{className:`min-w-0`,children:[u(`h2`,{className:`text-xs font-semibold uppercase tracking-wider text-foreground`,children:n(`deviceMigrate.title`,`Migrate to…`)}),u(`p`,{className:`mt-0.5 text-[11px] text-foreground-subtle`,children:n(`deviceMigrate.subtitle`,`Replace this camera with other hardware you have already adopted. The new camera inherits number {{deviceId}}, so recordings, rules and integrations follow it.`,{deviceId:e})})]}),r(`div`,{className:`flex shrink-0 items-center gap-2`,children:[r(`select`,{"aria-label":n(`deviceMigrate.pickerLabel`,`Replacement camera`),className:`rounded-md border border-border bg-background px-2 py-1.5 text-xs text-foreground disabled:opacity-50`,disabled:!f||p.length===0||d.isPending,value:o===null?``:String(o),onChange:e=>{let t=e.target.value;s(t===``?null:Number(t))},children:[u(`option`,{value:``,children:f?n(`deviceMigrate.pickerPlaceholder`,`Select a camera…`):n(`deviceMigrate.pickerPending`,`Reading the fleet…`)}),p.map(e=>r(`option`,{value:String(e.id),children:[e.name,` (#`,e.id,`)`]},e.id))]}),r(`button`,{type:`button`,disabled:m===null||d.isPending,onClick:()=>{_()},className:`inline-flex shrink-0 items-center gap-1.5 rounded-md border border-border bg-background px-3 py-1.5 text-xs font-medium text-foreground hover:bg-surface disabled:opacity-50`,children:[u(Hi,{className:`h-3 w-3`}),d.isPending?n(`deviceMigrate.running`,`Migrating…`):n(`deviceMigrate.action`,`Migrate`)]})]})]}),f&&p.length===0&&u(`p`,{className:`mt-2 text-[11px] text-foreground-subtle`,children:n(`deviceMigrate.noTargets`,`No other camera is adopted, so there is nothing to migrate to.`)}),g!==null&&u(`p`,{className:`mt-2 text-[11px] text-danger`,children:n(`deviceMigrate.failed`,`Migration failed: {{error}}`,{error:g})}),h!==null&&u(Xc,{report:h})]})}function Xc({report:e}){let{t}=X(),n=e.verdict===`quiet`;return r(`div`,{className:`mt-3 space-y-2 border-t border-border pt-3`,children:[u(`p`,{className:`text-[11px] text-foreground-subtle`,children:t(`deviceMigrate.swapped`,`The replacement now answers on number {{inheritedId}}; the old camera was handed number {{retiredId}}.`,{inheritedId:e.inheritedId,retiredId:e.retiredId})}),n?r(`div`,{className:`flex items-start gap-2 rounded-md border border-success/30 bg-success/5 px-3 py-2`,children:[u(je,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-success`}),u(`p`,{className:`text-[11px] leading-relaxed text-foreground`,children:t(`deviceMigrate.quiet`,`Every function on the replaced camera was switched off — the old hardware is quiet.`)})]}):r(`div`,{className:`rounded-md border border-warning/40 bg-warning/5 px-3 py-2`,children:[r(`div`,{className:`flex items-start gap-2`,children:[u(lt,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-warning`}),u(`p`,{className:`text-[11px] leading-relaxed text-foreground`,children:t(`deviceMigrate.stillLive`,`The replaced camera could not be reached, so these functions are STILL RUNNING on the old hardware. Nothing here failed to migrate — but until you unplug it or reach it physically, it can still produce data.`)})]}),u(`ul`,{className:`mt-2 space-y-1 pl-5`,children:e.stillLive.map(e=>r(`li`,{className:`text-[11px] text-foreground`,children:[u(`span`,{className:`font-medium`,children:e.label}),e.detail!==null&&r(`span`,{className:`text-foreground-subtle`,children:[` — `,e.detail]})]},e.switchId))})]}),e.neverOffered.length>0&&r(`div`,{className:`rounded-md border border-border px-3 py-2`,children:[r(`div`,{className:`flex items-start gap-2`,children:[u(Jn,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),u(`p`,{className:`text-[11px] leading-relaxed text-foreground-subtle`,children:t(`deviceMigrate.neverOffered`,`The replaced camera never offered these, so there was nothing to switch off. They are not running.`)})]}),u(`ul`,{className:`mt-2 space-y-1 pl-5`,children:e.neverOffered.map(e=>u(`li`,{className:`text-[11px] text-foreground-subtle`,children:e.label},e.switchId))})]})]})}n();function Zc({deviceId:e}){let[t,n]=c(null),i=tt({onSuccess:e=>{n(e.changed?`Re-aligned with source — ${e.rebuiltChildren} child${e.rebuiltChildren===1?``:`ren`} rebuilt.`:`Already up to date.`)},onError:e=>n(`Re-sync failed: ${e.message}`)});return r(`div`,{className:`rounded-lg border border-border bg-surface px-4 py-3`,children:[r(`div`,{className:`flex items-center justify-between gap-3`,children:[r(`div`,{children:[u(`h2`,{className:`text-xs font-semibold uppercase tracking-wider text-foreground`,children:`Re-sync`}),u(`p`,{className:`mt-0.5 text-[11px] text-foreground-subtle`,children:`Re-align this device's type, role, capabilities and units with its source.`})]}),r(`button`,{type:`button`,disabled:i.isPending,onClick:()=>{n(null),i.mutate({camDeviceId:e})},className:`inline-flex shrink-0 items-center gap-1.5 rounded-md border border-border bg-background px-3 py-1.5 text-xs font-medium text-foreground hover:bg-surface disabled:opacity-50`,children:[u(Qe,{className:`h-3 w-3 ${i.isPending?`animate-spin`:``}`}),i.isPending?`Re-syncing…`:`Re-sync`]})]}),t!==null&&u(`p`,{className:`mt-2 text-[11px] text-foreground-subtle`,children:t})]})}function Qc(e){return e<1e3?`${e.toFixed(0)} kbps`:`${(e/1e3).toFixed(1)} Mbps`}function $c({device:e}){let t=si(),n=typeof e.id==`number`?e.id:null,i=String(e.type??``),a=i===q.Camera,o=i===q.Hub,s=e.features??[],c=s.includes(Wr.Resyncable),{data:l}=W({deviceId:n??0},{enabled:n!==null&&a,refetchInterval:5e3}),d=l?.streams??{},f=Object.entries(d),p=s.includes(Wr.DoorbellButton),m=Ut(p?{deviceId:n??void 0,historyLimit:10}:void 0),h=m.latest?Date.now()-m.latest.timestamp<3e4:!1;return r(`div`,{className:`space-y-5`,children:[o&&n!==null&&u(ee,{deviceId:n,onOpenChild:e=>t(`/devices/${e}`)}),c&&n!==null&&u(Zc,{deviceId:n}),a&&n!==null&&u(Yc,{deviceId:n,deviceName:String(e.name??``)}),n!==null&&u(Wc,{deviceId:n}),a&&n!==null&&u(Le,{widgetId:`pipeline-orchestrator/pipeline-quick-stats`,host:`device-tab`,deviceId:n}),p&&u(Vn,{history:m.history,latestIsFresh:h}),a&&n!==null&&u(Le,{widgetId:`stream-broker/stream-broker-panel`,host:`device-tab`,deviceId:n}),a&&f.length>0&&r(`div`,{className:`@container rounded-lg border border-border bg-surface overflow-hidden`,style:{containerType:`inline-size`},children:[u(`div`,{className:`border-b border-border px-4 py-2`,children:u(`h2`,{className:`text-xs font-semibold text-foreground uppercase tracking-wider`,children:`Stream Network`})}),u(`div`,{className:`divide-y divide-border`,children:f.map(([e,t])=>r(`div`,{className:`px-4 py-2.5`,children:[r(`div`,{className:`flex items-center gap-2 mb-2`,children:[u(Ot,{className:`h-3 w-3 text-foreground-subtle`}),u(`span`,{className:`text-[11px] font-medium text-foreground`,children:e})]}),r(`div`,{className:`grid grid-cols-2 @[640px]:grid-cols-4 gap-2`,children:[u(el,{label:`Nominal`,value:Qc(t.nominalBitrateKbps??0)}),u(el,{label:`Observed`,value:Qc(t.observedBitrateKbps??0)}),u(el,{label:`Peak`,value:Qc(t.peakBitrateKbps??0)}),u(el,{label:`Packet Loss`,value:`${(t.packetLossPercent??0).toFixed(2)}%`,warning:(t.packetLossPercent??0)>1})]})]},e))})]}),u(mi,{}),n!==null&&u(Yr,{deviceId:n})]})}function el({label:e,value:t,warning:n}){return r(`div`,{children:[u(`p`,{className:`text-[10px] text-foreground-subtle`,children:e}),u(`p`,{className:`text-xs font-medium ${n?`text-warning`:`text-foreground`}`,children:t})]})}var tl=[{id:`overview`,label:`Overview`,cameraOnly:!1,adminOnly:!1},{id:`config`,label:`Config`,cameraOnly:!1,adminOnly:!1},{id:pi,label:`Customize`,cameraOnly:!1,adminOnly:!0},{id:`detection-pipeline`,label:`Detection pipeline`,cameraOnly:!0,adminOnly:!1},{id:`bindings`,label:`Bindings`,cameraOnly:!0,adminOnly:!1}];function nl(e,t){let n=e===q.Camera;return tl.filter(e=>(n||!e.cameraOnly)&&(t||!e.adminOnly)).map(({id:e,label:t})=>({id:e,label:t}))}function rl({provider:e,integrationId:t,name:n}){let r=si(),i=t===null?`/integrations`:`/integrations/${t}`,a=n===null?`Open integrations`:`Open integration ${n}`;return u(`button`,{type:`button`,onClick:()=>r(i),className:`shrink-0 rounded-md transition-opacity hover:opacity-80 focus:outline-none focus-visible:ring-1 focus-visible:ring-primary/50`,title:a,"aria-label":a,children:u(Qr,{type:e,size:`lg`})})}n();var il=[{id:`logs`,icon:Je,label:`Logs`},{id:`repl`,icon:li,label:`REPL`},{id:`events`,icon:Mt,label:`Events`},{id:`state`,icon:se,label:`State`}];function al(){let n=ti(),a=Number(n.deviceId),l=Number.isFinite(a),d=si(),f=s(),p=nt(),m=S(),{user:h}=ni(),g=h?.isAdmin===!0,[_,y]=Gr(),b=_.get(`tab`)??`overview`,C=_.get(`sub`),[w,T]=c(`logs`),E=`device-detail.left-col-width-px`,[D,A]=c(()=>{if(typeof window>`u`)return null;let e=window.localStorage.getItem(E),t=e?Number(e):NaN;return Number.isFinite(t)&&t>0?t:null}),j=t(D);j.current=D;function M(e){e.preventDefault();let t=e.clientX,n=e.currentTarget.previousElementSibling?.getBoundingClientRect().width??D??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(E,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:N,isLoading:P,isError:ee}=Tn({deviceId:a},{enabled:l,refetchInterval:5e3,retry:1}),{data:L}=wt({deviceId:a},{enabled:l}),te=i(()=>{let e=L?.settings?.sections??[],t=L?.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($r)&&r.add(Kr),[...r].map(e=>e===`export`?{id:e,label:ui,isAddonContrib:!0}:{id:e,label:Tr[e]?.label??e,isAddonContrib:!0})},[L]),R=N,z=String(R?.name??n.deviceId??`Device`),ne=R?.online===!0,re=ne?`online`:`offline`,ie=String(R?.addonId??`rtsp`),B=R?.features??[],V=R?.type,H=V===q.Camera,{data:ae}=ii(l?a:0),se=V===q.Container,U=i(()=>(ae??[]).map(e=>({id:e.id,stableId:e.stableId,type:e.type,...e.sourceInfo?{sourceInfo:{id:e.sourceInfo.id}}:{}})),[ae]),ce=i(()=>se?nn(U,typeof R?.linkDeviceId==`number`?R.linkDeviceId:null,typeof R?.primaryChildEntityId==`string`?R.primaryChildEntityId:null)?.id??null:null,[se,U,R?.linkDeviceId,R?.primaryChildEntityId]),{data:le}=wt({deviceId:ce??0},{enabled:ce!==null}),ue=i(()=>{if(ce===null)return[];let e=le?.settings?.sections??[],t=le?.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:Tr[e]?.label??e,isAddonContrib:!0,childDeviceId:ce}))},[ce,le]),de=typeof R?.parentDeviceId==`number`?R.parentDeviceId:null,{data:fe}=Tn({deviceId:de??0},{enabled:de!==null}),W=On(),he=R?.disabled!==!0,ge=i(()=>{let e=L?.settings?.sections??[],t=L?.live?.sections??[];return ei([...e,...t],V,g,L!==void 0)},[L,V,g]),_e=i(()=>{let e=new Set,t=[];for(let n of[...nl(V,g),...te,...ue])n.id===`config`&&!ge||e.has(n.id)||(e.add(n.id),t.push(n));return t},[V,g,te,ue,ge]),ve=i(()=>vc(_e,b),[_e,b]),xe=e(e=>{y(t=>{let n=new URLSearchParams(t);e===`overview`?n.delete(`tab`):n.set(`tab`,e),n.delete(`sub`);for(let e of fr)n.delete(e);return n},{replace:!0})},[y]),Se=e(e=>{y(t=>{let n=new URLSearchParams(t);return n.set(`sub`,e),n},{replace:!0})},[y]),Ce=(ae??[]).length>0,Te=i(()=>il.filter(({featureGate:e})=>!e||B.includes(e)),[B]),{data:Ee}=gt(void 0),De=i(()=>R?$e(R,Ee):null,[R,Ee]),G=De?.kind===`resolved`?De.integration:null,Oe=G===null?De?.kind===`unknown`?`Loading integration…`:De?.kind===`orphan`?`Missing integration`:`No integration`:G.name,ke=G!==null&&G.addonId===ie?G.name:ie,Ae=xt({onSuccess:()=>{f.invalidateQueries({queryKey:[[`deviceManager`]]}),d(G?.id?`/integrations/${G.id}`:`/integrations`)}}),je=yn({onSuccess:()=>{f.invalidateQueries({queryKey:[[`deviceManager`]]})}}),Ne=Me({onSuccess:()=>{f.invalidateQueries({queryKey:[[`deviceManager`]]})}}),Pe=St(),K=I({onSuccess:()=>{f.invalidateQueries({queryKey:[[`deviceManager`]]})}}),Fe=B.includes(Wr.Rebootable),Ie=B.includes(Wr.BatteryOperated),Le=cn(m.trpcClient,Ie&&l?a:null),Re=kn(m.trpcClient,l?a:null),[ze,Be]=c(!1),Ve=async()=>{if(!ze){Be(!0);try{let e=z.replace(/[^a-zA-Z0-9_.-]+/g,`_`),t=new Date().toISOString().replace(/[:.]/g,`-`);await Vi(`${v}/${String(a)}.jpg?force=1`,`${e}-${t}.jpg`)}finally{Be(!1)}}},He=je.isPending||Ne.isPending,{data:Ue}=be({deviceId:a},{enabled:l,refetchInterval:1e4}),We=Ue?.agentNodeId??null,Ge=typeof We==`string`&&We.length>0&&!We.startsWith(`addon:`)?We:void 0,{data:Je}=mt({deviceId:a,...Ge?{nodeId:Ge}:{}},{enabled:l,refetchInterval:3e3,retry:!1}),{data:Ye}=pe({deviceId:a},{enabled:l,refetchInterval:3e3,retry:!1}),Xe=Ye?.level?.dbfs??null;function Ze(){if(!l)return null;switch(ve){case`overview`:return u($c,{device:R??{}});case`config`:return u(Cc,{deviceId:a,activeSubTab:C,onSubTabChange:Se,deviceType:V,isAdmin:g});case`detection-pipeline`:return u(Rc,{deviceId:a,activeSubTab:C,onSubTabChange:Se});case`bindings`:return u(yc,{deviceId:a});case pi:return u(dc,{deviceId:a,activeSubTab:C,onSubTabChange:Se});default:{let e=ve,t=te.some(t=>t.id===e),n=ue.find(t=>t.id===e);if(!t&&n===void 0)return null;let r=n?.childDeviceId??a;if(e===`export`)return u(Jr,{deviceId:a,sectionFilter:$r,activeSubTab:C,onSubTabChange:Se});let i=u(Jr,{deviceId:r,sectionFilter:t=>t.location===`top-tab`&&(t.tab===e||e===`detection-pipeline`&&t.tab===`zones`),flattenSubTabs:e===`detection-pipeline`,activeSubTab:C,onSubTabChange:Se});return n!==void 0&&r!==a?u(Ke,{deviceId:r,children:i}):i}}}return l?P?r(`div`,{className:`flex flex-col h-full`,children:[r(`div`,{className:`border-b border-border bg-surface px-6 py-4`,children:[u(`div`,{className:`h-4 w-48 rounded bg-surface-hover animate-pulse mb-3`}),u(`div`,{className:`h-8 w-64 rounded bg-surface-hover animate-pulse`})]}),u(`div`,{className:`flex-1 p-6`,children:u(`div`,{className:`h-40 rounded-lg border border-border bg-surface animate-pulse`})})]}):ee||!N?r(`div`,{className:`flex flex-col items-center justify-center h-full gap-3 text-foreground-subtle`,children:[u(`p`,{className:`text-lg font-semibold text-foreground`,children:`Device not found`}),r(`p`,{className:`text-xs`,children:[`No device with ID`,` `,r(`code`,{className:`font-mono bg-surface px-1.5 py-0.5 rounded text-[11px]`,children:[`#`,a]})]}),u(`button`,{onClick:()=>d(`/integrations`),className:`mt-2 rounded-lg bg-primary px-4 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 transition-colors`,children:`Back to Integrations`})]}):r(`div`,{className:`absolute inset-0 flex flex-col overflow-clip`,children:[r(`div`,{className:`border-b border-border bg-surface px-6 py-3 flex-shrink-0`,children:[u(`div`,{className:`mb-2`,children:u(Gn,{items:[{label:`Integrations`,onClick:()=>d(`/integrations`)},G===null?{label:Oe}:{label:Oe,onClick:()=>d(`/integrations/${G.id}`)},{label:z}]})}),r(`div`,{className:`flex items-center gap-2 sm:gap-3`,children:[G!==null&&u(rl,{provider:G.addonId,integrationId:G.id,name:G.name}),r(`div`,{className:`min-w-0 flex-1`,children:[r(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[u(`h1`,{className:`text-sm sm:text-base font-semibold text-foreground truncate`,children:z}),u(ye,{status:re}),Ie&&u(oe,{status:Le,variant:`full`}),u(qe,{status:Re})]}),de!==null&&fe&&r(`button`,{type:`button`,onClick:()=>d(`/devices/${de}`),className:`text-[10px] text-foreground-subtle hover:text-primary transition-colors mt-0.5 inline-flex items-center gap-1`,title:`Open parent device ${fe.name}`,children:[u(`span`,{children:`↑`}),u(`span`,{className:`truncate`,children:String(fe.name??`Device #${de}`)})]}),u(`div`,{className:`hidden md:flex items-center gap-3 mt-0.5 text-[10px] text-foreground-subtle`,children:B.length>0&&u(Zr,{capabilities:B})})]}),Je&&u(`div`,{className:`hidden lg:flex`,children:u(ol,{metrics:Je,dbfs:Xe})}),r(`div`,{className:`flex items-center gap-1 shrink-0`,children:[r(`button`,{onClick:async()=>{he?await p({title:`Disable "${z}"?`,message:`The device will stop processing streams and events. You can re-enable it later.`,confirmLabel:`Disable`,variant:`danger`})&&Ne.mutate({deviceId:a}):je.mutate({deviceId:a})},disabled:He,title:he?`Disable device`:`Enable device`,className:`inline-flex items-center gap-1.5 rounded-lg px-2 sm:px-2.5 py-1.5 text-[11px] font-medium border transition-colors disabled:opacity-50 ${he?`border-success/30 text-success hover:bg-success/10`:`border-border text-foreground-subtle/50 hover:text-foreground hover:bg-surface-hover`}`,children:[u(Pt,{className:`h-3.5 w-3.5`}),u(`span`,{className:`hidden sm:inline`,children:He?`Updating…`:he?`Enabled`:`Disabled`})]}),u(`div`,{className:`hidden sm:block h-5 w-px bg-border mx-1`}),H&&r(o,{children:[u(Qi,{deviceId:a}),u(`div`,{className:`hidden sm:block h-5 w-px bg-border mx-1`})]}),u(ea,{deviceId:a}),u(me,{triggerClassName:`ml-1`,items:[{id:`snapshot`,label:`Take snapshot`,description:`Fetch a fresh frame and download it.`,icon:x,disabled:ze,onClick:()=>{Ve()}},{id:`reboot`,label:`Reboot device`,description:`Camera goes offline for ~30 seconds.`,icon:at,hidden:!Fe,disabled:Pe.isPending,danger:!0,onClick:async()=>{await p({title:`Reboot "${z}"?`,message:`The camera will go offline for around 30 seconds while the firmware reboots.`,confirmLabel:`Reboot`,variant:`danger`})&&Pe.mutate({deviceId:a})}},{id:`restart-addon`,label:`Restart addon`,description:`Bounces every device served by ${ke}.`,icon:Qe,disabled:K.isPending,danger:!0,onClick:async()=>{await p({title:`Restart "${ke}"?`,message:`Restarting the addon will briefly disconnect every device served by it (not just "${z}"). Streams will reconnect automatically.`,confirmLabel:`Restart`,variant:`danger`})&&K.mutate({addonId:ie})}},{id:`delete`,label:`Delete device`,description:`Remove the device and all its settings.`,icon:O,separatorBefore:!0,disabled:Ae.isPending,danger:!0,onClick:async()=>{await p({title:`Delete "${z}"?`,message:`This will remove the device and all its settings. This action cannot be undone.`,confirmLabel:`Delete`,variant:`danger`})&&Ae.mutate({deviceId:a})}}]})]})]})]}),u(Ke,{deviceId:a,device:R??void 0,children:u(we,{children:u(F,{children:u(k,{children:u(Ct,{children:r(`main`,{className:W?`flex-1 overflow-y-auto flex flex-col`:`flex-1 min-h-0 overflow-hidden flex flex-row`,children:[r(`div`,{className:W?`flex flex-col bg-surface`:`${D===null?`w-1/2 lg:w-1/3`:``} flex-shrink-0 flex flex-col bg-surface min-h-0 overflow-hidden`,style:!W&&D!==null?{width:`${String(D)}px`}:void 0,children:[u(`div`,{className:H?`flex-shrink-0 border-b border-border-subtle bg-black`:W?`flex-shrink-0 border-b border-border-subtle bg-surface`:`max-h-[55%] shrink-0 overflow-y-auto border-b border-border-subtle bg-surface`,children:H?u(Pa,{deviceId:a,intercomAvailable:B.includes(Wr.TwoWayAudio)}):u(wa,{deviceId:a,deviceName:z,deviceType:V??`unknown`,provider:ie,isOnline:ne,features:B})}),r(`div`,{className:W?`flex flex-col border-b border-border`:`flex-1 min-h-0 flex flex-col overflow-hidden`,children:[u(`div`,{className:`flex-shrink-0 border-b border-border-subtle px-2 py-1.5`,children:u(`div`,{className:`flex gap-1 overflow-x-auto -mx-1 px-1 pb-0.5`,children:Te.map(({id:e,label:t,icon:n})=>r(`button`,{onClick:()=>T(e),title:t,className:`flex items-center gap-1 rounded px-2 py-1 text-[10px] font-medium transition-colors flex-shrink-0 ${w===e?`bg-primary/15 text-primary`:`text-foreground-subtle hover:text-foreground hover:bg-surface-hover`}`,children:[u(n,{className:`h-3 w-3`}),t]},e))})}),r(`div`,{className:W?`h-72 overflow-hidden`:`flex-1 min-h-0 overflow-hidden`,children:[w===`logs`&&u(Fa,{deviceId:a,containerDeviceId:V===`container`?a:void 0}),w===`repl`&&u(Ia,{deviceId:a}),w===`events`&&u(La,{deviceId:a}),w===`state`&&u(Ra,{deviceId:a})]})]})]}),!W&&u(`div`,{role:`separator`,"aria-orientation":`vertical`,title:`Drag to resize`,onMouseDown:M,className:`flex-shrink-0 w-1 cursor-col-resize bg-border hover:bg-primary/40 transition-colors group relative z-10`,children:u(`span`,{className:`absolute inset-y-0 -left-1 -right-1`})}),r(`div`,{className:W?`flex flex-col`:`flex-1 min-w-0 min-h-0 flex flex-col overflow-hidden`,children:[u(`div`,{className:`flex-shrink-0 border-b border-border bg-surface px-4`,children:u(`div`,{className:`flex flex-nowrap overflow-x-auto md:flex-wrap md:overflow-x-visible items-center gap-0`,children:_e.map(e=>{let t=ve===e.id;return r(`button`,{onClick:()=>xe(e.id),className:`relative flex-shrink-0 px-3 py-2 text-xs font-medium transition-colors ${t?`text-primary`:`text-foreground-subtle hover:text-foreground`}`,children:[e.label,t&&u(`span`,{className:`absolute bottom-0 left-0 right-0 h-0.5 rounded-full bg-primary`})]},e.id)})})}),r(`div`,{className:W?`p-3 flex flex-col gap-3`:`flex-1 min-h-0 overflow-y-auto p-4 flex flex-col gap-3`,children:[ve===`overview`&&Ce&&u(ta,{parentDeviceId:a}),Ze()]})]})]})})})})})})]}):r(`div`,{className:`flex flex-col items-center justify-center h-full gap-3 text-foreground-subtle`,children:[u(`p`,{className:`text-lg font-semibold text-foreground`,children:`Invalid device id`}),r(`p`,{className:`text-xs`,children:[`The URL segment`,` `,u(`code`,{className:`font-mono bg-surface px-1.5 py-0.5 rounded text-[11px]`,children:n.deviceId}),` `,`is not a number.`]}),u(`button`,{onClick:()=>d(`/integrations`),className:`mt-2 rounded-lg bg-primary px-4 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 transition-colors`,children:`Back to Integrations`})]})}function ol({metrics:e,dbfs:t}){let n=Ve(e.phase??`idle`);return r(`div`,{className:`flex items-center gap-3 flex-shrink-0`,children:[r(`div`,{className:`flex items-center gap-1.5`,children:[u(`span`,{className:`h-1.5 w-1.5 rounded-full ${n.dotClass}`}),u(`span`,{className:`text-[10px] font-medium ${n.textColor}`,children:n.label})]}),u(`div`,{className:`h-3 w-px bg-border`}),r(`div`,{className:`flex items-center gap-1 text-[10px] text-foreground-subtle`,children:[u(V,{className:`h-3 w-3`}),u(`span`,{className:`text-foreground tabular-nums`,children:(e.actualFps??0).toFixed(1)}),u(`span`,{children:`fps`})]}),r(`div`,{className:`flex items-center gap-1 text-[10px] text-foreground-subtle`,children:[u(He,{className:`h-3 w-3`}),u(`span`,{className:`text-foreground tabular-nums`,children:(e.avgInferenceTimeMs??0).toFixed(0)}),u(`span`,{children:`ms`})]}),r(`div`,{className:`flex items-center gap-1 text-[10px] text-foreground-subtle`,title:`Current audio level (dBFS)`,children:[u(Bt,{className:`h-3 w-3`}),u(`span`,{className:`text-foreground tabular-nums`,children:t==null?`—`:t.toFixed(0)}),u(`span`,{children:`dB`})]}),(e.queueDepth??0)>0&&r(`span`,{className:`text-[10px] text-warning tabular-nums`,children:[`q:`,e.queueDepth]})]})}export{al as DeviceDetailPage};
@@ -1 +0,0 @@
1
- import{Q as e,S as t,W as n,a as r,b as i,o as a,q as o,x as s}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-DhP-Lgiq.js";import{at as c,gt as l,ht as u,st as d,vt as f}from"./player-overlays-EDVR7CqJ.js";import{$d as p,Al as m,Bu as h,Cd as g,Cl as _,Cn as v,Dl as y,Dn as b,El as x,Fl as S,Ft as C,Id as w,Ln as T,Ml as E,Mu as D,N as O,Nl as ee,Ol as k,On as A,Ot as te,P as j,Pl as ne,Rn as M,Ru as N,Sd as P,Sl as re,Tl as F,Tn as I,Tr as L,U as ie,Ul as R,W as ae,Wu as oe,Xn as se,Yn as z,_d as B,ad as ce,au as le,bl as ue,da as de,hu as fe,in as V,jl as pe,kl as me,kn as H,nd as he,rr as ge,ru as U,wl as _e,wn as W,wr as ve,xd as ye,xl as be,yd as xe,zu as G}from"./src-BEsQ_4LU.js";import{t as Se}from"./history-COLYUTit.js";import{t as Ce}from"./monitor-smartphone-Dpm4bhCz.js";import{_ as K,a as we,b as Te,c as Ee,d as De,f as Oe,g as ke,h as q,i as Ae,l as je,m as Me,n as Ne,o as Pe,p as Fe,s as Ie,t as Le,u as Re,v as J,y as Y}from"./SessionsList-C_zY2zSb.js";import{a as ze,i as Be,o as Ve,s as He}from"./client-B2uiK_6q.js";import{$ as Ue,R as X,X as We,Y as Ge,c as Ke,it as qe,p as Je,rt as Ye,s as Xe,tt as Ze}from"./index-L63cSV_9.js";import{t as Qe}from"./AdminPage-BSFohA3i.js";import{t as $e}from"./AdminTabs-CYT0Gfgp.js";import{n as et,r as tt,t as nt}from"./AddonIntegrationBody-PmjCQ2Ms.js";import{n as rt,t as it}from"./addon-display-names-BkwMrExv.js";var at=f(`book-open`,[[`path`,{d:`M12 7v14`,key:`1akyts`}],[`path`,{d:`M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z`,key:`ruj8y`}]]),ot=f(`key-square`,[[`path`,{d:`M12.4 2.7a2.5 2.5 0 0 1 3.4 0l5.5 5.5a2.5 2.5 0 0 1 0 3.4l-3.7 3.7a2.5 2.5 0 0 1-3.4 0L8.7 9.8a2.5 2.5 0 0 1 0-3.4z`,key:`165ttr`}],[`path`,{d:`m14 7 3 3`,key:`1r5n42`}],[`path`,{d:`m9.4 10.6-6.814 6.814A2 2 0 0 0 2 18.828V21a1 1 0 0 0 1 1h3a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h1a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h.172a2 2 0 0 0 1.414-.586l.814-.814`,key:`1ubxi2`}]]);e();function st(){let e=z(),t=U.useUtils(),r=Y(),{data:i,isLoading:a}=k(),c=n(()=>i??[],[i]),l=U.useQueries(e=>c.map(t=>e.userManagement.listExternalIdentities({userId:t.id}))),u=U.auth.listLoginMethods.useQuery(),[d,f]=o(null),p=ne({onSuccess:()=>void t.userManagement.listExternalIdentities.invalidate(),onError:e=>f(`Remove failed: ${e.message}`)}),m=n(()=>new Map((u.data??[]).flatMap(e=>e.kind===`redirect`?[[e.id,e.label]]:[])),[u.data]),h=c.flatMap((e,t)=>l[t]?.data??[]),g=h.map(e=>({...De(e,r),kind:m.get(e.provider)??e.provider})),_=async t=>{let n=h.find(e=>Re(e)===t.id);n!==void 0&&await e({title:`Remove sign-in link`,message:`"${t.ownerName}" will no longer be able to sign in with this ${t.kind} account.`,confirmLabel:`Remove`,variant:`danger`})&&(f(null),p.mutate({userId:n.userId,provider:n.provider,subject:n.subject}))};return s(K,{notice:J(d),onDismissNotice:()=>{f(null)},id:`external-identities`,title:`Sign-in links`,icon:qe,description:`External accounts (single sign-on) each user linked to their CamStack account. Only the owner can link one, from their profile; an admin can remove it.`,children:s(q,{rows:g,label:`sign-in links`,isLoading:a||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:`Remove`,icon:Te,isAvailable:()=>!0,onRun:e=>void _(e),busyId:null,disabled:p.isPending}})})}e();function ct(){let e=z(),t=a(),r=Y(),i=F(),[c,l]=o(null),u=m({onSuccess:()=>void t.invalidateQueries({queryKey:[[`userManagement`,`listApiKeys`]]}),onError:e=>l(`Revoke failed: ${e.message}`)}),f=n(()=>(i.data??[]).map(e=>je(e,r)),[i.data,r]),p=async t=>{await e({title:`Revoke "${t.name}"?`,message:`Any client using this key loses access immediately. This cannot be undone.`,confirmLabel:`Revoke`,variant:`danger`})&&(l(null),u.mutate({id:t.id}))};return s(K,{notice:J(c),onDismissNotice:()=>{l(null)},id:`legacy-api-keys`,title:`Legacy API keys`,icon:Se,description:`Keys from before scoped tokens. Nothing creates them any more; revoke them and issue a scoped token instead.`,children:s(q,{rows:f,label:`legacy API keys`,isLoading:i.isLoading,loadError:i.isError?i.error?.message??`Request failed`:null,emptyText:`No legacy API keys.`,action:{label:`Revoke`,icon:d,isAvailable:()=>!0,onRun:e=>void p(e),busyId:u.isPending?u.variables?.id??null:null,disabled:u.isPending}})})}e();function lt(e){if(e.type===`category`){let t=e.target??``;return t===`device`?`all devices`:`all ${t}`}if(e.type===`device`)return`device:[${(e.targets??[]).join(`,`)}]`;let t=e;return`${t.type}:${t.target??``}`}function ut(){let e=z(),t=a(),r=y(),[i,c]=o(null),l=pe({onSuccess:()=>void t.invalidateQueries({queryKey:[[`userManagement`,`listOauthSessions`]]}),onError:e=>c(`Revoke failed: ${e.message}`)}),u=n(()=>(r.data??[]).map(e=>Oe(e,e.scopes.map(lt).join(`, `))),[r.data]),f=async t=>{await e({title:`Revoke the "${t.name}" link?`,message:`${t.name} loses access for ${t.ownerName} on its next call. Linking it again needs the account-link flow from the start.`,confirmLabel:`Revoke`,variant:`danger`})&&(c(null),l.mutate({id:t.id}))},p=l.isPending?l.variables?.id??null:null;return s(K,{notice:J(i),onDismissNotice:()=>{c(null)},id:`linked-apps`,title:`Linked apps`,icon:xe,description:`External integrations (Alexa, …) linked to this hub through OAuth. Revoking one stops that integration on its next call.`,children:s(q,{rows:u,label:`linked apps`,isLoading:r.isLoading,loadError:r.isError?r.error?.message??`Request failed`:null,emptyText:`No linked apps — an integration appears here once it completes the account-link flow.`,expiresNone:`—`,action:{label:`Revoke`,icon:d,isAvailable:e=>e.status===`active`,onRun:e=>void f(e),busyId:p,disabled:l.isPending}})})}e();var dt={one:`session`,many:`sessions`};function ft(){let e=z(),t=U.useUtils(),r=Y(),i=U.auth.listSessions.useQuery(),[a,c]=o(null),l=()=>void t.auth.listSessions.invalidate(),u=U.auth.revokeSessions.useMutation({onSuccess:l,onError:e=>c(`Sign out failed: ${e.message}`)}),d=ke(`login-session`,dt,l),f=n(()=>(i.data??[]).map(e=>Fe(e,r,{client:e=>we(e).label,method:Pe})),[i.data,r]),p=async t=>{await e({title:`Sign out this session`,message:`${t.ownerName} on ${t.name} will have to sign in again.`,confirmLabel:`Sign out`,variant:`danger`})&&(c(null),u.mutate({id:t.id}))};return s(K,{notice:J(a,d.outcome),onDismissNotice:()=>{c(null),d.dismiss()},id:`login-sessions`,title:`Login sessions`,icon:Ce,description:`Every browser and app signed in to this hub, for every user. Signing one out ends it at once; it has to sign in again. Your own current session is marked and never included in a bulk sign-out.`,children:s(q,{rows:f,label:`sessions`,isLoading:i.isLoading,loadError:i.isError?i.error?.message??`Request failed`:null,emptyText:`No active sessions.`,action:{label:`Sign out`,icon:Ze,isAvailable:e=>e.status===`active`,onRun:e=>void p(e),busyId:u.isPending&&u.variables!==void 0&&`id`in u.variables?u.variables.id:null,disabled:u.isPending||d.busy},bulk:{revoke:d,noun:dt,isSelectable:e=>e.status===`active`}})})}e();function pt({users:e,onClose:n,onSubmit:r,submitting:i}){let{user:a}=X(),c=a?.isAdmin===!0?null:a?.scopes??[],[l,u]=o(e[0]?.id??``),[d,f]=o(``),[p,m]=o([{type:`capability`,target:``,access:[`view`,`create`]}]),[h,g]=o(``),_=j(p),y=l!==``&&d.trim().length>0&&p.length>0&&_===null&&!i;return s(v,{open:!0,onOpenChange:e=>!e&&n(),children:t(I,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,children:[s(A,{children:s(H,{children:`Create scoped token`})}),t(W,{className:`space-y-3`,children:[t(`div`,{className:`space-y-1`,children:[s(V,{htmlFor:`scoped-token-user`,children:`On behalf of user`}),s(T,{id:`scoped-token-user`,value:l,onChange:e=>u(e.target.value),options:e.map(e=>({value:e.id,label:e.username}))})]}),t(`div`,{className:`space-y-1`,children:[s(V,{htmlFor:`scoped-token-name`,children:`Name`}),s(R,{id:`scoped-token-name`,value:d,onChange:e=>f(e.target.value),placeholder:`cloudflare-tunnel-route`})]}),t(`div`,{className:`space-y-1`,children:[s(V,{children:`Scopes`}),s(O,{value:p,onChange:m,clampToParent:c}),_&&s(`p`,{className:`text-[10px] text-danger`,children:_}),s(`p`,{className:`text-[10px] text-foreground-subtle`,children:`Each scope picks a (cap or addon) target + one or more access flavours. The token can access ONLY what's listed.`})]}),t(`div`,{className:`space-y-1`,children:[s(V,{htmlFor:`scoped-token-days`,children:`Expires in (days)`}),s(R,{id:`scoped-token-days`,type:`number`,min:1,value:h,onChange:e=>g(e.target.value),placeholder:`30`}),s(`p`,{className:`text-[10px] text-foreground-subtle`,children:`Leave blank for non-expiring.`})]})]}),t(b,{children:[s(M,{type:`button`,variant:`outline`,size:`sm`,onClick:n,children:`Cancel`}),t(M,{type:`button`,variant:`primary`,size:`sm`,onClick:()=>{let e=parseInt(h,10),t=Number.isFinite(e)&&e>0?Date.now()+e*864e5:void 0;r({userId:l,name:d.trim(),scopes:p,expiresAt:t})},disabled:!y,children:[i?s(B,{className:`h-3.5 w-3.5 animate-spin`,"aria-hidden":!0}):s(N,{className:`h-3.5 w-3.5`,"aria-hidden":!0}),`Issue token`]})]})]})})}function mt({token:e,label:n,onClose:r}){return s(v,{open:!0,onOpenChange:e=>!e&&r(),children:t(I,{width:`md`,scroll:`body`,children:[s(A,{children:s(H,{children:`Token: ${n}`})}),t(W,{className:`space-y-3`,children:[s(`div`,{className:`rounded-md border border-warning/30 bg-warning/10 px-3 py-2 text-xs text-warning`,children:`Copy this token now. Once you close this dialog the secret cannot be displayed again.`}),s(`div`,{className:`select-all break-all rounded-md border border-border bg-background p-2 font-mono text-[11px] text-foreground`,children:e})]}),t(b,{children:[s(te,{value:e,label:`Copy`,srLabel:`token`}),s(M,{type:`button`,variant:`primary`,size:`sm`,onClick:r,children:`Done`})]})]})})}e();function ht(e){return e.type===`device`?`device:[${ae(e.selector)}]`:`${e.type}:${e.target??``}`}function gt(){let e=z(),r=a(),i=Y(),{data:c,isLoading:l}=k(),u=n(()=>c??[],[c]),f=U.useQueries(e=>u.map(t=>e.userManagement.listScopedTokens({userId:t.id}))),[p,m]=o(null),[h,g]=o(!1),[_,v]=o(null),y=()=>void r.invalidateQueries({queryKey:[[`userManagement`,`listScopedTokens`]]}),b=ue({onSuccess:({token:e,record:t})=>{y(),g(!1),v({token:e,label:t.name})},onError:e=>m(`Create failed: ${e.message}`)}),x=E({onSuccess:y,onError:e=>m(`Revoke failed: ${e.message}`)}),S=Date.now(),C=u.flatMap((e,t)=>(f[t]?.data??[]).map(t=>Me(t,e.id,i,t.scopes.map(ht).join(`, `),S))),w=f.find(e=>e.isError)?.error?.message??null,T=async t=>{await e({title:`Revoke "${t.name}"?`,message:`${t.ownerName}'s scoped token stops working on its next use. This cannot be undone.`,confirmLabel:`Revoke`,variant:`danger`})&&(m(null),x.mutate({id:t.id}))};return t(K,{notice:J(p),onDismissNotice:()=>{m(null)},id:`scoped-tokens`,title:`Scoped tokens`,icon:P,description:`Tokens issued on behalf of a user for one narrow surface — an addon, an integration, a capability or some devices. Every token must be scoped, so revoking one has a predictable blast radius.`,actions:t(M,{type:`button`,variant:`primary`,size:`sm`,onClick:()=>g(!0),disabled:u.length===0,title:u.length===0?`Create a user first`:`Issue a scoped token`,children:[s(N,{className:`h-3.5 w-3.5`,"aria-hidden":!0}),`New token`]}),children:[s(q,{rows:C,label:`scoped tokens`,isLoading:l||f.some(e=>e.isLoading),loadError:w,emptyText:`No scoped tokens.`,action:{label:`Revoke`,icon:d,isAvailable:()=>!0,onRun:e=>void T(e),busyId:x.isPending?x.variables?.id??null:null,disabled:x.isPending}}),h&&s(pt,{users:u.map(e=>({id:e.id,username:e.username})),onClose:()=>g(!1),onSubmit:e=>b.mutate({userId:e.userId,name:e.name,scopes:e.scopes,...e.expiresAt===void 0?{}:{expiresAt:e.expiresAt}}),submitting:b.isPending}),_!==null&&s(mt,{token:_.token,label:_.label,onClose:()=>v(null)})]})}e();var _t={one:`admin token`,many:`admin tokens`},vt=7,yt=90,bt=80;function xt(e){let t=Number(e);return Number.isInteger(t)&&t>=1&&t<=yt?t:null}function St(){let{user:e}=X();return e?.isAdmin?s(Ct,{}):null}function Ct(){let e=z(),r=U.useUtils(),i=U.auth.listAdminTokens.useQuery(),a=Y(),{requestProof:c,dialog:l}=Ae(`Creating an admin token`),[u,f]=o(``),[p,m]=o(String(vt)),[h,g]=o(null),[_,v]=o(!1),[y,b]=o(null),x=()=>{r.auth.listAdminTokens.invalidate(),r.auth.listAuthAudit.invalidate()},S=U.auth.createAdminToken.useMutation({onSuccess:({token:e,record:t})=>{x(),f(``),m(String(vt)),b({token:e,label:t.name})},onError:e=>g(`Create failed: ${e.message}`)}),C=U.auth.revokeAdminToken.useMutation({onSuccess:x,onError:e=>g(`Revoke failed: ${e.message}`)}),w=ke(`admin-token`,_t,x),T=Date.now(),E=n(()=>(i.data??[]).map(e=>Ee(e,a,T)),[i.data,a]),D=u.trim(),O=xt(p),ee=D.length>0&&D.length<=bt&&O!==null&&!S.isPending&&!_,k=async()=>{if(!ee||O===null)return;g(null),v(!0);let e=await c();v(!1),e!==null&&S.mutate({name:D,expiresInDays:O,reauthToken:e})},A=async t=>{await e({title:`Revoke admin token "${t.name}"?`,message:`Every script using it loses access immediately. This cannot be undone.`,confirmLabel:`Revoke`,variant:`danger`})&&(g(null),C.mutate({id:t.id}))};return t(`div`,{"data-testid":`admin-tokens`,children:[l,t(K,{id:`admin-tokens`,title:`Admin tokens`,icon:G,tone:`danger`,notice:J(h,w.outcome),onDismissNotice:()=>{g(null),w.dismiss()},description:t(`div`,{className:`space-y-1`,children:[t(`p`,{children:[`An admin token acts as a `,s(`strong`,{children:`full administrator`}),` for scripts, e.g.`,` `,s(`code`,{className:`font-mono`,children:`node scripts/hub/hub.mjs --token-file <file> …`}),`. Anyone holding it can do anything an admin can.`]}),s(`p`,{children:`It expires in at most 90 days and every use is audited. Creating one asks you to confirm it is you.`})]}),children:[t(`form`,{className:`grid grid-cols-1 items-end gap-2 sm:grid-cols-[1fr_120px_auto]`,onSubmit:e=>{e.preventDefault(),k()},children:[t(`div`,{className:`space-y-1`,children:[s(V,{htmlFor:`admin-token-name`,children:`Token name`}),s(R,{id:`admin-token-name`,value:u,maxLength:bt,onChange:e=>f(e.target.value),placeholder:`nightly-backup`})]}),t(`div`,{className:`space-y-1`,children:[s(V,{htmlFor:`admin-token-days`,children:`Expires in (days)`}),s(R,{id:`admin-token-days`,type:`number`,min:1,max:yt,value:p,onChange:e=>m(e.target.value),state:O===null?`error`:`default`})]}),t(M,{type:`submit`,variant:`danger`,size:`sm`,disabled:!ee,children:[S.isPending||_?s(B,{className:`h-3.5 w-3.5 animate-spin`}):s(G,{className:`h-3.5 w-3.5`}),`Create admin token`]})]}),O===null&&t(`div`,{className:`text-[11px] text-danger`,children:[`Expiry must be a whole number of days, 1 to `,yt,`.`]}),s(q,{rows:E,label:`admin tokens`,isLoading:i.isLoading,loadError:i.isError?i.error?.message??`Request failed`:null,emptyText:`No admin tokens.`,action:{label:`Revoke`,icon:d,isAvailable:e=>e.status===`active`,onRun:e=>void A(e),busyId:C.isPending?C.variables?.id??null:null,disabled:C.isPending||w.busy},bulk:{revoke:w,noun:_t,isSelectable:e=>e.status===`active`}})]}),y&&s(mt,{token:y.token,label:y.label,onClose:()=>b(null)})]})}var wt={"share-link":`share links`,"admin-token":`admin tokens`,"login-session":`login sessions`};function Z(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:null}function Tt(e,t){let n=Z(e,`tokenId`);return Z(e,`name`)??(n===null?void 0:t.get(n))??n??`?`}function Et(e){return e.filter(e=>e!==null)}function Dt(e){let t=Z(e,`prefix`);return t===null?null:`Prefix ${t}…`}function Ot(e,t){let n=e.detail??{};switch(e.action){case`admin-token-created`:{let e=n.expiresAt;return{title:`Admin token "${Tt(n,t)}" created`,details:Et([Dt(n),typeof e==`number`?`Expires ${Ie(e)}`:null])}}case`admin-token-used`:{let e=Z(n,`path`);return{title:`Admin token "${Tt(n,t)}" used`,details:Et([Dt(n),e===null?null:`Call ${e}`])}}case`admin-token-revoked`:return{title:`Admin token "${Tt(n,t)}" revoked`,details:Et([Dt(n)])};case`credentials-revoked`:{let e=Z(n,`kind`)??`credential`,t=n.revoked,r=n.skipped,i=wt[e]??`${e}s`;return{title:`${typeof t==`number`?String(t):`?`} ${i} revoked in bulk`,details:Et([typeof r==`number`&&r>0?`${String(r)} skipped`:null,Z(n,`ids`)===null?null:`Ids ${Z(n,`ids`)??``}`])}}case`second-factor-skipped`:{let e=Z(n,`method`),t=Z(n,`factors`);return{title:`Second factor skipped on a trusted network`,details:Et([e===null?null:`Signed in with ${Pe(e)}`,t===null?null:`Skipped: ${t.split(`,`).join(`, `)}`])}}default:return{title:e.action,details:Object.entries(n).map(([e,t])=>`${e}: ${String(t)}`)}}}e();var kt=100;function At(){let{user:e}=X();return e?.isAdmin?s(Mt,{}):null}function jt(){let{data:e}=k(),{data:t}=U.auth.listAdminTokens.useQuery();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.name);return{userNameById:n,tokenNameById:r}},[e,t])}function Mt(){let e=U.auth.listAuthAudit.useQuery({limit:kt}),{userNameById:n,tokenNameById:r}=jt(),i=e.data??[];return t(`div`,{"data-testid":`auth-audit`,className:`rounded-lg border border-border bg-surface overflow-hidden`,children:[t(`div`,{className:`px-4 py-2.5 border-b border-border flex items-center gap-2`,children:[s(oe,{className:`h-3.5 w-3.5 text-foreground-subtle`}),s(`div`,{className:`text-xs font-semibold text-foreground`,children:`Authentication audit`}),t(`span`,{className:`ml-auto text-[10px] text-foreground-subtle`,children:[`Latest `,kt,`, newest first`]})]}),s(`div`,{className:`p-4`,children:e.isLoading?t(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[s(B,{className:`h-3.5 w-3.5 animate-spin`}),`Loading audit trail…`]}):e.isError?t(`div`,{className:`text-[11px] text-danger`,children:[`Could not load the audit trail: `,e.error?.message??`Request failed`]}):i.length===0?s(`div`,{className:`rounded border border-dashed border-border px-3 py-4 text-xs text-foreground-subtle text-center`,children:`No authentication events recorded yet.`}):s(`ul`,{className:`divide-y divide-border rounded-md border border-border max-h-[420px] overflow-y-auto`,children:i.map(e=>s(Nt,{record:e,userName:e.userId===void 0?null:n.get(e.userId)??e.userId,tokenNameById:r},e.id))})})]})}function Nt({record:e,userName:n,tokenNameById:r}){let i=Ot(e,r);return t(`li`,{"data-testid":`auth-audit-row`,className:`px-3 py-2 text-xs space-y-0.5`,children:[t(`div`,{className:`flex flex-wrap items-baseline gap-x-2`,children:[s(`span`,{className:`font-medium text-foreground`,children:i.title}),s(`span`,{className:`ml-auto text-[10px] text-foreground-subtle`,children:Ie(e.at)})]}),t(`div`,{className:`flex flex-wrap gap-x-3 text-[11px] text-foreground-subtle`,children:[n!==null&&s(`span`,{className:`text-foreground`,children:n}),e.ip!==void 0&&s(`span`,{className:`font-mono`,children:e.ip}),i.details.map(e=>s(`span`,{className:`font-mono`,children:e},e))]})]})}var Q={loginSessions:`login-sessions`,linkedApps:`linked-apps`,scopedTokens:`scoped-tokens`,adminTokens:`admin-tokens`,shareLinks:`share-links`,legacyApiKeys:`legacy-api-keys`,externalIdentities:`external-identities`,audit:`auth-audit`},Pt={state:`ok`,stateLabel:`available`,showState:!1};function $(e,t,n,r){return{id:e,name:t,fallbackIcon:n,...Pt,render:r}}function Ft(){let e=F(),t=(e.data??[]).length>0;return s(tt,{icon:ot,title:`Tokens & sessions`,subtitle:`Every credential this hub honours — who holds it, what it can reach, when it was last used and when it expires. Pick a kind; revoke one, or select several and revoke them after typing the count.`,groups:[{id:`sessions`,label:`Sessions`,entries:[$(Q.loginSessions,`Login sessions`,Ce,()=>s(ft,{})),$(Q.linkedApps,`Linked apps`,xe,()=>s(ut,{}))]},{id:`tokens`,label:`Tokens`,entries:[$(Q.scopedTokens,`Scoped tokens`,P,()=>s(gt,{})),$(Q.adminTokens,`Admin tokens`,G,()=>s(St,{})),$(Q.shareLinks,`Share links`,h,()=>s(Ne,{})),...t?[$(Q.legacyApiKeys,`Legacy API keys`,Se,()=>s(ct,{}))]:[]]},{id:`identity`,label:`Identity`,entries:[$(Q.externalIdentities,`Sign-in links`,qe,()=>s(st,{})),$(Q.audit,`Audit`,oe,()=>s(At,{}))]}],isLoading:e.isLoading,emptyTitle:`No credential kinds`,emptyDescription:`This hub offers no credential kinds.`})}e();var It=3e4,Lt=[{capName:`auth-provider`,stageBadge:null},{capName:`user-passkeys`,stageBadge:`Second factor`}],Rt={title:`Authentication`,subtitle:`Login providers (local password, OIDC, SAML) and second-factor providers (passkeys / WebAuthn). They run in parallel — enable or disable each independently; disabling one only removes that method, local password login is unaffected.`,emptyTitle:`No authentication providers registered`,emptyDescription:`Local auth should always be available — if this list is empty the local-auth builtin failed to register. Check the Addons page for load errors.`,installLabel:`Add provider`};function zt(e){return e===`local-auth`?{headline:`Username + password (local).`,icon:ot,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:Ye,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.`,"Set the redirect URI to `https://<this-hub>/addon/<addon-id>/callback`.",`Paste issuer + credentials in the Settings panel below — saves on every change.`,`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:Ye,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:D,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:D,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 Bt(){let e=L({capName:Lt[0].capName},{refetchInterval:It}),t=L({capName:Lt[1].capName},{refetchInterval:It}),r=ve(void 0,{refetchInterval:It}),i=n(()=>it(r.data??[]),[r.data]),a=n(()=>{let n=[],r=[e.data??[],t.data??[]];for(let[e,t]of Lt.entries())for(let a of r[e]??[])n.push({addonId:a.addonId,displayName:i.get(a.addonId)??a.addonId,isActive:a.isActive,capName:t.capName,stageBadge:t.stageBadge});return n},[e.data,t.data,i]),o=[{id:`authentication`,label:`Authentication providers`,install:{capability:Lt[0].capName,label:Rt.installLabel},entries:a.map(e=>({id:e.addonId,name:e.displayName,fallbackIcon:N,...rt(e.isActive),render:()=>s(nt,{addonId:e.addonId,displayName:e.displayName,capName:e.capName,isActive:e.isActive,badges:e.stageBadge===null?null:s(ge,{variant:`info`,className:et,children:e.stageBadge}),panels:[{id:`about`,title:`About`,icon:zt(e.addonId).icon,content:s(Vt,{addonId:e.addonId})}]})}))}];return s(tt,{icon:N,title:Rt.title,subtitle:Rt.subtitle,groups:o,isLoading:e.isLoading||t.isLoading,emptyTitle:Rt.emptyTitle,emptyDescription:Rt.emptyDescription})}function Vt({addonId:e}){let n=zt(e),r=n.icon;return t(`div`,{className:`space-y-3 rounded-lg border border-border bg-surface p-2 sm:p-4`,children:[t(`div`,{className:`flex items-start gap-2.5`,children:[s(r,{className:`h-4 w-4 mt-0.5 text-primary shrink-0`}),s(`div`,{className:`text-xs text-foreground font-medium`,children:n.headline})]}),s(`ul`,{className:`text-xs text-foreground-subtle space-y-1.5 pl-6 list-disc`,children:n.bullets.map((e,t)=>s(`li`,{children:e},t))}),n.setupSteps&&n.setupSteps.length>0&&t(`div`,{className:`rounded-md border border-border bg-surface-hover/40 px-3 py-2.5 space-y-1.5`,children:[t(`div`,{className:`flex items-center gap-1.5 text-[10px] font-semibold text-foreground-subtle uppercase tracking-wide`,children:[s(at,{className:`h-3 w-3`}),`Setup steps`]}),s(`ol`,{className:`text-xs text-foreground space-y-0.5 pl-4 list-decimal`,children:n.setupSteps.map((e,t)=>s(`li`,{children:e},t))})]}),e===`local-auth`&&t(`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:[s(g,{className:`h-3.5 w-3.5 mt-0.5 text-info shrink-0`}),t(`span`,{children:[`TOTP / 2FA is self-service: each user enrols from their own profile page —`,` `,s(Ge,{to:`/system/my-access`,className:`underline text-primary`,children:`My access`}),` `,`→ “Two-factor authentication” → Enable 2FA. Admins can only remove a user’s active enrollment (lost device) from the`,` `,s(Ge,{to:`/system/identity?tab=users`,className:`underline text-primary`,children:`Users`}),` `,`page via Actions → “Remove 2FA”.`]})]})]})}function Ht({userId:e,username:n,onClose:r}){let i=z(),a=U.useUtils(),o=x({userId:e}),c=U.auth.listLoginMethods.useQuery(),l=ne({onSuccess:()=>void a.userManagement.listExternalIdentities.invalidate()}),u=new Map((c.data??[]).flatMap(e=>e.kind===`redirect`?[[e.id,e.label]]:[])),d=o.data??[],f=async(t,r)=>{await i({title:`Remove sign-in link`,message:`"${n}" will no longer be able to sign in with this ${r} account.`,confirmLabel:`Remove`,variant:`danger`})&&l.mutate({userId:e,provider:t.provider,subject:t.subject})};return s(v,{open:!0,onOpenChange:e=>!e&&r(),children:t(I,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`external-identities-modal`,children:[s(A,{children:t(H,{className:`flex items-center gap-2`,children:[s(xe,{className:`h-4 w-4 text-primary`}),t(`span`,{children:[`Linked sign-in accounts`,t(`span`,{className:`mt-0.5 block text-[11px] font-normal text-foreground-subtle`,children:[`User: `,s(`span`,{className:`font-mono`,children:n})]})]})]})}),s(W,{className:`space-y-3`,children:o.isLoading?t(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[s(B,{className:`h-3.5 w-3.5 animate-spin`}),`Loading…`]}):d.length===0?s(`p`,{className:`text-xs text-foreground-subtle`,children:`No linked accounts. Only the user can link one, from their own profile page.`}):s(`ul`,{className:`divide-y divide-border rounded-md border border-border`,children:d.map(e=>{let n=u.get(e.provider),r=n??e.provider;return t(`li`,{className:`flex items-center gap-3 px-3 py-2 text-xs`,children:[t(`div`,{className:`flex-1 min-w-0`,children:[t(`div`,{className:`font-medium text-foreground truncate`,children:[r,n===void 0&&s(`span`,{className:`ml-2 rounded bg-foreground-subtle/15 px-1.5 py-0.5 text-[10px] font-normal text-foreground-subtle`,children:`provider unavailable`})]}),t(`div`,{className:`text-[11px] text-foreground-subtle truncate`,children:[e.label??e.subject,` ·`,` `,new Date(e.linkedAt).toLocaleDateString()]})]}),t(`button`,{onClick:()=>void f(e,r),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:[s(Te,{className:`h-3 w-3`}),`Remove`]})]},`${e.provider}|${e.subject}`)})})}),s(b,{children:s(M,{onClick:r,variant:`secondary`,children:`Close`})})]})})}function Ut({userId:e,username:n,onClose:r}){let o=a(),c=z(),l=_e({userId:e}),u=l.data,d=()=>o.invalidateQueries({queryKey:[[`userManagement`,`getTotpStatus`]]}),f=_({onSuccess:()=>{d(),r()}}),m=l.isLoading?`loading`:u?.enabled?`enrolled`:`not_enrolled`;return s(v,{open:!0,onOpenChange:e=>!e&&r(),children:t(I,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,children:[s(A,{children:t(H,{className:`flex items-center gap-2`,children:[s(D,{className:`h-4 w-4 text-primary`}),t(`span`,{children:[`Two-factor authentication`,t(`span`,{className:`mt-0.5 block text-[11px] font-normal text-foreground-subtle`,children:[`User: `,s(`span`,{className:`font-mono`,children:n})]})]})]})}),t(W,{className:`space-y-4`,children:[m===`loading`&&t(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[s(B,{className:`h-3.5 w-3.5 animate-spin`}),`Checking status…`]}),m===`not_enrolled`&&t(`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:[s(g,{className:`h-4 w-4 mt-0.5 shrink-0`}),t(`div`,{children:[s(`div`,{className:`font-medium text-foreground`,children:`2FA not enrolled`}),s(`p`,{className:`mt-0.5`,children:`Only the user themselves can enable 2FA, from their own profile page.`})]})]}),m===`enrolled`&&u&&t(i,{children:[t(`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:[s(p,{className:`h-4 w-4 mt-0.5 text-emerald-500 shrink-0`}),t(`div`,{className:`text-xs text-foreground space-y-0.5`,children:[s(`div`,{className:`font-medium`,children:`2FA is active`}),t(`div`,{className:`text-foreground-subtle`,children:[`Enrolled on`,` `,u.confirmedAt?new Date(u.confirmedAt).toLocaleString():`—`]})]})]}),s(`div`,{className:`text-[11px] text-foreground-subtle`,children:`Removing here clears the server-side secret. Use this only when the user has lost access — they'll have to re-enroll from their profile page afterwards.`}),t(`div`,{className:`flex justify-end gap-2`,children:[s(M,{onClick:r,variant:`secondary`,children:`Close`}),t(`button`,{onClick:async()=>{await c({title:`Remove 2FA`,message:`Remove two-factor authentication for "${n}"? They'll be able to log in with just their password until they re-enroll from their own profile page.`,confirmLabel:`Remove`,variant:`danger`})&&f.mutate({userId:e})},disabled:f.isPending,className:`rounded bg-danger px-3 py-1.5 text-xs font-medium text-white hover:bg-danger/90 disabled:opacity-50 inline-flex items-center gap-1`,children:[f.isPending?s(B,{className:`h-3 w-3 animate-spin`}):s(le,{className:`h-3 w-3`}),`Remove 2FA`]})]})]})]})]})})}e();function Wt({userId:e,username:n,onClose:r}){let{user:i,logout:a}=X(),c=i?.id===e,l=z(),u=U.useUtils(),d=U.auth.listSessions.useQuery({userId:e}),[f,p]=o(null),m=U.auth.revokeSessions.useMutation({onSuccess:(e,t)=>{if(c&&`userId`in t){a();return}u.auth.listSessions.invalidate()},onError:e=>p(`Sign out failed: ${e.message}`)}),h=async e=>{await l({title:`Sign out this session`,message:`"${n}" on ${we(e.client).label} will have to sign in again.`,confirmLabel:`Sign out`,variant:`danger`})&&(p(null),m.mutate({id:e.id}))},g=async()=>{await l({title:`Sign out everywhere`,message:c?`Every session of your own account ends, this browser included: you will be signed out here too.`:`Every session of "${n}" ends at once; each device has to sign in again.`,confirmLabel:`Sign out everywhere`,variant:`danger`})&&(p(null),m.mutate({userId:e}))},_=m.isPending&&m.variables!==void 0&&`id`in m.variables?m.variables.id:null;return s(v,{open:!0,onOpenChange:e=>!e&&r(),children:t(I,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`user-sessions-modal`,children:[s(A,{children:t(H,{className:`flex items-center gap-2`,children:[s(Ce,{className:`h-4 w-4 text-primary`}),t(`span`,{children:[`Active sessions`,t(`span`,{className:`mt-0.5 block text-[11px] font-normal text-foreground-subtle`,children:[`User: `,s(`span`,{className:`font-mono`,children:n})]})]})]})}),t(W,{className:`space-y-3`,children:[f!==null&&s(`div`,{className:`text-[11px] text-danger`,children:f}),s(Le,{sessions:d.data??[],isLoading:d.isLoading,loadError:d.isError?d.error?.message??`Request failed`:null,emptyText:`No active sessions.`,onRevoke:e=>void h(e),revokingId:_})]}),t(b,{className:`justify-between`,children:[t(`button`,{onClick:()=>void g(),disabled:m.isPending||(d.data??[]).length===0,className:`inline-flex items-center gap-1.5 rounded border border-danger/40 px-2.5 py-1 text-[11px] font-medium text-danger hover:bg-danger/10 disabled:opacity-50`,children:[m.isPending&&_===null?s(B,{className:`h-3 w-3 animate-spin`}):s(Ze,{className:`h-3 w-3`}),`Sign out everywhere`]}),s(M,{onClick:r,variant:`secondary`,children:`Close`})]})]})})}function Gt({icon:e,label:n,count:r,all:i,total:a}){return t(`div`,{className:`flex items-center gap-2 text-[11px]`,children:[s(e,{className:`h-3 w-3 shrink-0 text-foreground-subtle`}),s(`span`,{className:`min-w-0 flex-1 text-foreground-subtle`,children:n}),s(`span`,{className:r===0?`text-foreground-subtle`:`font-medium text-foreground`,children:r===0?`none`:i?`all ${a}`:`${r} of ${a}`})]})}function Kt({scopes:e,isAdmin:n,invalidReason:a}){let o=c(),l=r({queryKey:[`auth`,`previewScope`,e,n],enabled:a===null,queryFn:()=>o.trpcClient.auth.previewScope.query({scopes:[...e],isAdmin:n})}),{data:u}=de({projection:`slim`}),f=u?.length??0;if(a!==null)return s(`div`,{className:`rounded-lg border border-border bg-surface p-3`,children:t(`p`,{className:`flex items-center gap-1.5 text-[11px] text-warning`,children:[s(G,{className:`h-3 w-3 shrink-0`}),a]})});if(l.isLoading)return t(`div`,{className:`flex items-center gap-2 rounded-lg border border-border bg-surface p-3 text-[11px] text-foreground-subtle`,children:[s(B,{className:`h-3 w-3 animate-spin`}),`Resolving…`]});if(l.isError||!l.data)return s(`div`,{className:`rounded-lg border border-border bg-surface p-3`,children:s(`p`,{className:`text-[11px] text-danger`,children:`Could not resolve this grant set. Saving is still allowed — the server enforces the same rules either way.`})});let p=l.data;return s(`div`,{className:`space-y-2 rounded-lg border border-border bg-surface p-3`,children:p.isAdmin?t(`p`,{className:`text-[11px] text-foreground`,children:[s(`span`,{className:`font-medium`,children:`Administrator`}),` — unrestricted. Grants are ignored for an admin.`]}):t(i,{children:[s(Gt,{icon:w,label:`Devices they can see`,count:p.device.view.deviceCount,all:p.device.view.all,total:f}),s(Gt,{icon:ce,label:`Devices they can operate`,count:p.device.create.deviceCount,all:p.device.create.all,total:f}),s(Gt,{icon:d,label:`Devices they can delete`,count:p.device.delete.deviceCount,all:p.device.delete.all,total:f}),t(`div`,{className:`border-t border-border pt-2 text-[10px] text-foreground-subtle`,children:[`System access: `,p.system.length===0?`none`:p.system.join(`, `),p.capabilities.length>0&&t(i,{children:[` · Extra capabilities: `,p.capabilities.map(e=>e.name).join(`, `)]}),p.addons.length>0&&t(i,{children:[` · Addons: `,p.addons.map(e=>e.name).join(`, `)]})]}),p.device.view.deviceCount===0&&s(`p`,{className:`text-[10px] text-warning`,children:`This user will not be able to see any device.`})]})})}e();function qt(e){let t=Ve(e);return t===null?{mode:e.length===0?`role`:`advanced`,roleId:null,selector:{kind:`all`},includeLinked:!0,advancedScopes:e}:{mode:`role`,roleId:t.roleId,selector:t.selector,includeLinked:t.includeLinked,advancedScopes:e}}function Jt(e){return e.mode===`advanced`?e.advancedScopes:e.roleId===null?[]:ze({roleId:e.roleId,selector:e.selector,includeLinked:e.includeLinked})}function Yt({user:e,onClose:r,onSubmit:a,submitting:c,callerScopes:d}){let f=n(()=>qt(e.scopes??[]),[e.scopes]),[p,m]=o(f),[h,g]=o(f.mode===`advanced`),_=n(()=>Jt(p),[p]),y=!e.isAdmin&&p.mode===`role`&&p.roleId===null,x=n(()=>e.isAdmin?null:p.mode===`role`&&p.roleId===null?`Pick what this user can do to see the result.`:j(_),[e.isAdmin,p.mode,p.roleId,_]),S=e=>m({...p,...e});return s(v,{open:!0,onOpenChange:e=>!e&&r(),children:t(I,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,className:`md:max-w-2xl`,children:[t(A,{children:[t(H,{children:[`Access — `,e.username]}),s(`p`,{className:`text-[10px] text-foreground-subtle`,children:e.isAdmin?`This user is an administrator — they can do everything, and the settings below are ignored.`:`Choose what they can do, then which devices it applies to.`})]}),t(W,{className:`space-y-4`,children:[y&&t(`div`,{className:`flex items-start gap-2 rounded-lg border border-warning/40 bg-warning/10 p-3`,children:[s(G,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-warning`}),t(`p`,{className:`text-[11px] text-foreground`,children:[s(`span`,{className:`font-medium`,children:`No access.`}),` `,t(`span`,{className:`text-foreground-subtle`,children:[e.username,` cannot see or do anything yet. Configure it below.`]})]})]}),t(`section`,{className:`space-y-2`,children:[s(`h3`,{className:`text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:`1 · What can they do`}),s(`div`,{className:`space-y-1.5`,children:Be.map(e=>{let n=p.mode===`role`&&p.roleId===e.id;return t(`label`,{className:`flex cursor-pointer items-start gap-2 rounded-lg border p-2.5 transition-colors ${n?`border-primary bg-primary/5`:`border-border hover:bg-foreground-subtle/5`}`,children:[s(`input`,{type:`radio`,name:`access-role`,checked:n,onChange:()=>S({mode:`role`,roleId:e.id}),className:`mt-0.5 border-border focus:ring-primary`}),t(`span`,{className:`min-w-0`,children:[s(`span`,{className:`block text-[12px] font-medium text-foreground`,children:e.label}),s(`span`,{className:`mt-0.5 block text-[10px] text-foreground-subtle`,children:e.description})]})]},e.id)})}),t(`button`,{type:`button`,onClick:()=>{if(!h){m({...p,mode:`advanced`,advancedScopes:_}),g(!0);return}g(!1),m(qt(p.advancedScopes))},className:`inline-flex items-center gap-1 rounded px-1.5 py-1 text-[10px] text-foreground-subtle transition-colors hover:bg-foreground-subtle/10 hover:text-foreground`,children:[s(h?l:u,{className:`h-3 w-3`}),`Advanced — edit raw grants`]}),h&&t(`div`,{className:`rounded-lg border border-border p-2`,children:[s(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:`One row per grant. Anything expressible here overrides the three roles above; close this section to go back to them.`}),s(O,{value:p.advancedScopes,onChange:e=>S({mode:`advanced`,advancedScopes:e}),clampToParent:d,emptyHint:t(i,{children:[`No grants.`,` `,s(`span`,{className:`font-medium text-foreground`,children:e.username}),` cannot call any protected endpoint until one is added.`]})})]})]}),p.mode===`role`&&t(`section`,{className:`space-y-2`,children:[s(`h3`,{className:`text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:`2 · On which devices`}),s(ie,{value:p.selector,onChange:e=>S({selector:e}),includeLinked:p.includeLinked,onIncludeLinkedChange:e=>S({includeLinked:e}),clampToDeviceIds:null})]}),t(`section`,{className:`space-y-2`,children:[s(`h3`,{className:`text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:p.mode===`role`?`3 · Result`:`2 · Result`}),s(Kt,{scopes:_,isAdmin:e.isAdmin,invalidReason:x})]})]}),t(b,{children:[s(M,{variant:`outline`,size:`sm`,onClick:r,children:`Cancel`}),s(M,{size:`sm`,onClick:()=>a([..._]),disabled:c||x!==null,children:c?s(B,{className:`h-3 w-3 animate-spin`}):`Save access`})]})]})})}e();var Xt=8;function Zt(){let e=a(),{user:n}=X(),[r,i]=o(!1),[c,l]=o(``),[u,f]=o(``),[p,m]=o(!1),[h,g]=o(null),{data:_,isLoading:v,isError:y}=k(),b=z(),x=se(),w=()=>e.invalidateQueries({queryKey:[[`userManagement`,`listUsers`]]}),T=be({onSuccess:()=>{w(),i(!1),l(``),f(``),m(!1),g(null)},onError:e=>{g(e instanceof Error?e.message:`Failed to create user`)}}),E=re({onSuccess:w}),O=S({onSuccess:w}),A=me({onSuccess:w}),te=ee({onSuccess:()=>{w(),ne(null)}}),[j,ne]=o(null),[M,P]=o(null),[F,I]=o(null),[L,ie]=o(null),R=_??[];async function ae(e){await b({title:`Delete user`,message:`Permanently delete user "${e.username}"? This cannot be undone — any active sessions will be revoked on next request.`,confirmLabel:`Delete`,variant:`danger`})&&E.mutate({id:e.id})}async function oe(e){let t=await x({title:`Reset password`,message:`Set a new password for "${e.username}".`,label:`New password`,inputType:`password`,placeholder:`At least 8 characters`,confirmLabel:`Continue`,validate:e=>e.length<Xt?`Password must be at least ${String(Xt)} characters.`:null});t===null||t.length===0||await b({title:`Reset password`,message:`Reset the password for "${e.username}"? They will need to use the new password on their next login.`,confirmLabel:`Reset`})&&A.mutate({id:e.id,newPassword:t})}function ce(e,t){t!==e.isAdmin&&O.mutate({id:e.id,isAdmin:t})}function ue(e){return e?new Date(typeof e==`number`?e:String(e)).toLocaleDateString(`en-GB`,{day:`2-digit`,month:`short`,year:`numeric`}):`—`}return t(Qe,{children:[s(`div`,{className:`flex items-center justify-end`,children:t(`button`,{onClick:()=>i(!0),className:`inline-flex items-center gap-1.5 rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground shadow-sm hover:bg-primary/90`,children:[s(he,{className:`h-3.5 w-3.5`}),`Create User`]})}),r&&t(`div`,{className:`rounded-lg border border-border bg-surface p-4 space-y-3`,children:[t(`div`,{className:`flex items-center justify-between`,children:[s(`span`,{className:`text-xs font-medium text-foreground`,children:`New User`}),s(`button`,{onClick:()=>i(!1),className:`text-foreground-subtle hover:text-foreground`,children:s(le,{className:`h-4 w-4`})})]}),t(`div`,{className:`grid grid-cols-3 gap-3`,children:[t(`div`,{className:`space-y-1`,children:[s(`label`,{className:`text-[10px] text-foreground-subtle uppercase tracking-wide`,children:`Username`}),s(`input`,{type:`text`,value:c,onChange:e=>l(e.target.value),placeholder:`john`,className:`w-full rounded border border-border bg-background px-2 py-1.5 text-xs text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary`})]}),t(`div`,{className:`space-y-1`,children:[s(`label`,{className:`text-[10px] text-foreground-subtle uppercase tracking-wide`,children:`Password`}),s(`input`,{type:`password`,value:u,onChange:e=>f(e.target.value),placeholder:`••••••••`,className:`w-full rounded border border-border bg-background px-2 py-1.5 text-xs text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary`})]}),t(`div`,{className:`space-y-1`,children:[s(`label`,{className:`text-[10px] text-foreground-subtle uppercase tracking-wide`,children:`Admin`}),t(`label`,{className:`flex items-center gap-2 rounded border border-border bg-background px-2 py-1.5 text-xs text-foreground cursor-pointer`,children:[s(`input`,{type:`checkbox`,checked:p,onChange:e=>m(e.target.checked),className:`rounded border-border focus:ring-primary`}),s(`span`,{className:`text-foreground-subtle`,children:`Unrestricted access`})]})]})]}),h&&s(`p`,{className:`text-[10px] text-danger`,children:h}),t(`div`,{className:`flex justify-end gap-2`,children:[s(`button`,{onClick:()=>i(!1),className:`rounded px-3 py-1.5 text-xs text-foreground-subtle border border-border hover:text-foreground`,children:`Cancel`}),s(`button`,{onClick:()=>T.mutate({username:c,password:u,isAdmin:p}),disabled:T.isPending||!c||!u,className:`rounded bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50`,children:T.isPending?`Creating...`:`Create`})]})]}),v&&s(`div`,{className:`text-xs text-foreground-subtle animate-pulse`,children:`Loading...`}),y&&s(`div`,{className:`text-xs text-danger`,children:`Failed to load`}),!v&&!y&&R.length===0&&s(`div`,{className:`text-xs text-foreground-subtle`,children:`No data`}),(()=>{let e=e=>E.isPending&&E.variables?.id===e.id||O.isPending&&O.variables?.id===e.id||A.isPending&&A.variables?.id===e.id;return s(C,{columns:[{key:`username`,header:`Username`,render:e=>e.username},{key:`isAdmin`,header:`Admin`,render:n=>t(`label`,{className:`inline-flex items-center gap-1.5 text-xs cursor-pointer`,children:[s(`input`,{type:`checkbox`,checked:n.isAdmin,onChange:e=>ce(n,e.target.checked),disabled:e(n),className:`rounded border-border focus:ring-primary disabled:opacity-50`}),s(`span`,{className:n.isAdmin?`text-primary font-medium`:`text-foreground-subtle`,children:n.isAdmin?`Admin`:`Regular`})]})},{key:`scopes`,header:`Access`,render:e=>e.isAdmin?s(`span`,{className:`text-[10px] italic text-foreground-subtle`,children:`everything (admin)`}):t(`button`,{onClick:()=>ne(e),className:`inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-[10px] hover:bg-foreground-subtle/10`,title:`Configure access`,children:[s(N,{className:`h-3 w-3 shrink-0 text-foreground-subtle`}),s(Qt,{scopes:e.scopes??[]})]})},{key:`createdAt`,header:`Created`,render:e=>s(`span`,{className:`text-foreground-subtle`,children:ue(e.createdAt)})},{key:`actions`,header:`Actions`,align:`right`,render:r=>{let i=e(r);return t(`div`,{className:`flex items-center justify-end gap-1`,children:[r.id!==n?.id&&r.totpEnabled&&t(`button`,{onClick:()=>P(r),disabled:i,className:`inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-foreground-subtle hover:bg-foreground-subtle/10 hover:text-foreground disabled:opacity-50`,title:`Remove two-factor authentication`,children:[s(D,{className:`h-3 w-3`}),`Remove 2FA`]}),t(`button`,{onClick:()=>I(r),disabled:i,className:`inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-foreground-subtle hover:bg-foreground-subtle/10 hover:text-foreground disabled:opacity-50`,title:`Linked sign-in accounts`,children:[s(xe,{className:`h-3 w-3`}),`Sign-in links`]}),t(`button`,{onClick:()=>ie(r),disabled:i,className:`inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-foreground-subtle hover:bg-foreground-subtle/10 hover:text-foreground disabled:opacity-50`,title:`Active sessions`,children:[s(Ce,{className:`h-3 w-3`}),`Sessions`]}),t(`button`,{onClick:()=>oe(r),disabled:i,className:`inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-foreground-subtle hover:bg-foreground-subtle/10 hover:text-foreground disabled:opacity-50`,title:`Reset password`,children:[s(ye,{className:`h-3 w-3`}),`Reset password`]}),t(`button`,{onClick:()=>ae(r),disabled:i,className:`inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-danger hover:bg-danger/10 disabled:opacity-50`,title:`Delete user`,children:[i?s(B,{className:`h-3 w-3 animate-spin`}):s(d,{className:`h-3 w-3`}),`Delete`]})]})}}],rows:R,rowKey:e=>e.id,minWidthPx:560})})(),M&&s(Ut,{userId:M.id,username:M.username,onClose:()=>P(null)}),F&&s(Ht,{userId:F.id,username:F.username,onClose:()=>I(null)}),L&&s(Wt,{userId:L.id,username:L.username,onClose:()=>ie(null)}),j&&s($t,{user:j,onClose:()=>ne(null),onSubmit:e=>te.mutate({userId:j.id,scopes:e}),submitting:te.isPending})]})}function Qt({scopes:e}){if(e.length===0)return s(`span`,{className:`font-medium text-warning`,children:`No access`});let n=Ve(e);return n===null?t(`span`,{className:`text-foreground-subtle`,children:[`Custom · `,e.length,` grant`,e.length===1?``:`s`]}):t(`span`,{className:`text-foreground-subtle`,children:[s(`span`,{className:`font-medium text-foreground`,children:He(n.roleId).label}),` ·`,` `,ae(n.selector)]})}function $t(e){let{user:t}=X(),n=t?.isAdmin===!0;return s(Yt,{...e,callerScopes:n?null:t?.scopes??[]})}var en={"api-keys":Q.scopedTokens,"linked-sessions":Q.linkedApps};function tn(){let[e]=Ue(),t=en[e.get(`tab`)??``];return t===void 0?s(`div`,{className:`flex flex-col p-4`,children:s($e,{tabs:[{id:`users`,label:`Users`,icon:fe,content:s(Zt,{})},{id:Ke.access.tab,label:`Tokens & sessions`,icon:P,content:s(Ft,{}),ownedParams:Xe},{id:Ke.authentication.tab,label:`Authentication`,icon:N,content:s(Bt,{}),ownedParams:Xe}]})}):s(We,{to:Je(`access`,{integration:t}),replace:!0})}export{tn as IdentityPage};
@@ -1 +0,0 @@
1
- import{I as e,K as t,Q as n,S as r,W as i,o as a,q as o,x as s,z as c}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-DhP-Lgiq.js";import{at as l,gt as u,ht as d,mt as f,st as p,vt as m}from"./player-overlays-EDVR7CqJ.js";import{Ar as h,Cn as g,Gi as _,Id as v,J as y,Jd as b,Ji as x,Ki as S,La as C,On as w,Qd as T,Qi as E,Qu as D,Tn as O,Vu as k,Wi as A,Wu as j,X as M,Xi as ee,Xl as N,Xu as P,Yu as te,Zi as F,_d as I,_n as L,ao as R,au as z,ba as B,bu as V,co as H,cu as U,da as W,fr as G,io as K,kn as q,kt as J,na as ne,nd as re,nn as ie,no as ae,oa as Y,oo as X,pr as oe,q as se,qi as ce,ql as le,ra as ue,rf as de,ro as fe,to as pe,va as Z,vt as me,wn as he,xf as ge,zt as _e}from"./src-BEsQ_4LU.js";import{Er as ve}from"./client-B2uiK_6q.js";import{t as ye}from"./useTranslation-Bc5yH9V9.js";import{$ as be,I as xe,Q as Se,Z as Ce,q as we}from"./index-L63cSV_9.js";import{t as Te}from"./NodeAddonsSettingsPanel-DsaDhenp.js";import{t as Ee}from"./device-integration-icon-CB229zfO.js";import{n as De,r as Oe,t as ke}from"./ScanNetworkModal-LKDbSzGe.js";var Ae=m(`search-x`,[[`path`,{d:`m13.5 8.5-5 5`,key:`1cs55j`}],[`path`,{d:`m8.5 8.5 5 5`,key:`a8mexj`}],[`circle`,{cx:`11`,cy:`11`,r:`8`,key:`4ej97u`}],[`path`,{d:`m21 21-4.3-4.3`,key:`1qie3q`}]]);n();function Q(e){let t=[];for(let n of e)n.type===`probe`&&t.push(n.key),n.type===`group`&&`fields`in n&&t.push(...Q(n.fields));return t}function je(t,n,r){let[a,s]=o(`idle`),[c,l]=o({}),u=i(()=>{let e=[];for(let n of t.sections)e.push(...Q(n.fields));return e},[t]),d=u.length>0&&r!==void 0,f=e(e=>{l(t=>{if(!t[e])return t;let n={...t};return delete n[e],n})},[]);return{testAllStatus:a,hasProbeFields:d,probeResults:c,handleTestAll:e(async()=>{if(!r)return;let e=u.filter(e=>{let t=n[e];return t!=null&&String(t).trim()!==``});if(e.length===0)return;s(`testing`);let t={};for(let n of e)t[n]={status:`probing`};l(t);let i=await Promise.allSettled(e.map(async e=>{try{return{key:e,result:await r(e,n[e])}}catch(t){return{key:e,result:{status:`error`,error:t instanceof Error?t.message:String(t)}}}})),a={};for(let e of i)if(e.status===`fulfilled`){let{key:t,result:n}=e.value;a[t]={status:n.status===`ok`?`ok`:`error`,result:n}}l(a),s(`idle`)},[r,u,n]),clearProbeResult:f}}n();function Me(e){let t=[];for(let n of e)`required`in n&&n.required===!0&&`key`in n&&n.key&&t.push(n.key),n.type===`group`&&`fields`in n&&t.push(...Me(n.fields));return t}function Ne(e){return e==null?!0:typeof e==`string`?e.trim()===``:!1}function Pe(e,t={}){for(let n of e){if(n.type===`group`&&`fields`in n){Pe(n.fields,t);continue}`key`in n&&n.key&&`default`in n&&n.default!==void 0&&(t[n.key]=n.default)}return t}function Fe(){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?`probe-${crypto.randomUUID()}`:`probe-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function Ie({open:t,integrationId:n,addonId:l,onClose:d}){let{t:f}=ye(),p=a(),[m,h]=o({}),[g,_]=o(!1),[v,y]=o(null),[b,x]=o(Fe),S=Z({addonId:l},{enabled:t}),w=S.data?.deviceType??null,T=Y({addonId:l,type:w??ve.Camera},{enabled:t&&S.isSuccess&&w!==null}),E=T.data??null;c(()=>{t&&(h(E?Pe(E.sections.flatMap(e=>e.fields)):{}),x(Fe()),_(!1),y(null))},[t,n,E]);let D=i(()=>({...m,_probeRequestId:b}),[m,b]),O=F({onSuccess:()=>{p.invalidateQueries({queryKey:[[`deviceManager`]]})}}),k=C(),A=e(async(e,t)=>{_(!0);let n=await k.mutateAsync({addonId:l,type:w??ve.Camera,key:e,value:t,formValues:D});return n.status===`ok`&&n.suggestedValues&&h(e=>{let t=!1,r={...e};for(let[i,a]of Object.entries(n.suggestedValues??{}))Ne(e[i])&&!Ne(a)&&(r[i]=a,t=!0);return t?r:e}),n},[k,l,D,w]),{testAllStatus:M,hasProbeFields:ee,probeResults:N,handleTestAll:P,clearProbeResult:te}=je(E??{sections:[]},m,A);async function L(e){y(null);try{await O.mutateAsync({addonId:l,type:w??ve.Camera,config:m,integrationId:n}),e?h(E?Pe(E.sections.flatMap(e=>e.fields)):{}):d()}catch(e){y(e instanceof Error?e.message:String(e))}}if(!t)return null;let R=Me((E?.sections??[]).flatMap(e=>e.fields)).filter(e=>Ne(m[e])),B=R.length===0,H=S.isLoading||w!==null&&T.isLoading,W=S.isError||S.isSuccess&&w===null||T.isError||T.isSuccess&&E===null;return r(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center`,children:[s(`div`,{className:`absolute inset-0 bg-black/60`,onClick:d}),r(`div`,{className:`relative z-10 flex w-full max-w-2xl flex-col max-h-[calc(90dvh-2*max(env(safe-area-inset-top),env(safe-area-inset-bottom)))] rounded-xl border border-border bg-background shadow-2xl`,children:[r(`div`,{className:`flex items-center justify-between border-b border-border px-5 py-4 shrink-0`,children:[s(`h2`,{className:`text-sm font-semibold text-foreground`,children:f(`integrations.addDevice`)}),s(`button`,{onClick:d,className:`rounded-md p-1 text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,children:s(z,{className:`h-4 w-4`})})]}),s(`div`,{className:`flex-1 min-h-0 overflow-y-auto px-5 py-4 space-y-3`,children:H?s(`div`,{className:`flex items-center justify-center py-8`,children:s(I,{className:`h-5 w-5 animate-spin text-primary`})}):W?r(`div`,{className:`flex items-start gap-3 rounded-lg border border-destructive/40 bg-destructive/10 px-4 py-3`,children:[s(V,{className:`h-4 w-4 text-destructive mt-0.5 shrink-0`}),r(`div`,{className:`space-y-1`,children:[s(`p`,{className:`text-xs font-medium text-destructive`,children:`Provider unavailable`}),r(`p`,{className:`text-xs text-foreground-subtle`,children:[`The addon `,s(`span`,{className:`font-mono`,children:l}),` is not ready or does not support manual device creation. Check that the integration is online and try again.`]})]})]}):s(xe,{schema:E,values:m,onChange:h,onTestField:A,probeResults:N,onClearProbe:te})}),!W&&!H&&r(`div`,{className:`border-t border-border bg-surface/50 shrink-0`,children:[r(`button`,{type:`button`,onClick:()=>_(e=>!e),className:`flex w-full items-center justify-between px-5 py-2 text-[11px] text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,children:[r(`span`,{className:`flex items-center gap-2`,children:[s(j,{className:`h-3.5 w-3.5`}),`Test logs`,s(`span`,{className:`font-mono text-[9px] opacity-60`,children:b.slice(0,14)})]}),s(u,{className:`h-3.5 w-3.5 transition-transform ${g?`rotate-180`:``}`})]}),g&&s(`div`,{className:`border-t border-border max-h-64 overflow-hidden`,children:s(me,{addonId:l,requestId:b,limit:50,maxHeight:`max-h-64`,showFilters:!1,showScope:!1,className:`border-0 rounded-none`})})]}),!W&&!H&&(v||R.length>0)&&s(`div`,{className:`border-t border-destructive/30 bg-destructive/5 px-5 py-2 shrink-0`,children:r(`div`,{className:`flex items-start gap-2`,children:[s(V,{className:`h-3.5 w-3.5 text-destructive mt-0.5 shrink-0`}),s(`p`,{className:`text-[11px] text-destructive`,children:v||`Required: ${R.join(`, `)}`})]})}),r(`div`,{className:`flex items-center justify-between border-t border-border px-5 py-3 shrink-0`,children:[r(`div`,{className:`flex items-center gap-2`,children:[s(`button`,{onClick:d,className:`rounded-lg border border-border px-3 py-1.5 text-xs text-foreground-subtle hover:text-foreground transition-colors`,children:f(`integrations.cancel`)}),!W&&ee&&r(`button`,{type:`button`,onClick:P,disabled:M===`testing`,className:`inline-flex items-center gap-1.5 rounded-lg border border-border px-3 py-1.5 text-xs font-medium text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors disabled:opacity-50`,children:[M===`testing`?s(I,{className:`h-3.5 w-3.5 animate-spin`}):s(U,{className:`h-3.5 w-3.5`}),`Test All`]})]}),r(`div`,{className:`flex items-center gap-2`,children:[s(`button`,{onClick:()=>L(!0),disabled:W||!B||O.isPending,className:`rounded-lg border border-border px-3 py-1.5 text-xs text-foreground hover:bg-surface-hover transition-colors disabled:opacity-50`,children:f(`integrations.saveAndNew`)}),s(`button`,{onClick:()=>L(!1),disabled:W||!B||O.isPending,className:`rounded-lg bg-primary px-4 py-1.5 text-xs font-medium text-primary-foreground shadow-sm disabled:opacity-50`,children:O.isPending?f(`integrations.saving`):f(`integrations.save`)})]})]})]})]})}var Le=1500;function $({addonId:e,integrationId:t,jobId:n,onFinished:i}){let{t:a}=ye(),o=A(),c=(ce({addonId:e,integrationId:t},{refetchInterval:e=>(e.state.data??[]).some(e=>e.state===`running`)?Le:!1}).data??[]).find(e=>e.jobId===n);if(!c)return null;let l=c.state===`running`,u=c.processed,d=c.total>0?Math.round(u/c.total*100):0;!l&&c.finishedAt!==null&&i();let f=[`${u}/${c.total} ${a(`integrations.adoptJobProcessed`,{defaultValue:`processed`})}`];c.adopted>0&&f.push(`${c.adopted} ${a(`integrations.adoptJobAdded`,{defaultValue:`added`})}`),c.alreadyAdopted>0&&f.push(`${c.alreadyAdopted} ${a(`integrations.adoptJobSkipped`,{defaultValue:`already there`})}`),c.failed>0&&f.push(`${c.failed} ${a(`integrations.adoptJobFailed`,{defaultValue:`failed`})}`);let p=f.join(` · `);return r(`div`,{className:`border-t border-border px-5 py-3 shrink-0 space-y-2`,children:[r(`div`,{className:`flex items-center gap-2`,children:[l?s(I,{className:`h-3.5 w-3.5 animate-spin text-primary shrink-0`}):c.failed>0?s(V,{className:`h-3.5 w-3.5 text-destructive shrink-0`}):c.state===`cancelled`?s(b,{className:`h-3.5 w-3.5 text-foreground-subtle shrink-0`}):s(T,{className:`h-3.5 w-3.5 text-primary shrink-0`}),s(`p`,{className:`text-[11px] text-foreground`,children:p}),l&&s(`button`,{onClick:()=>o.mutate({jobId:n}),className:`ml-auto rounded-lg border border-border px-2 py-1 text-[11px] text-foreground-subtle hover:text-foreground transition-colors`,children:a(`integrations.adoptJobCancel`,{defaultValue:`Stop`})})]}),s(`div`,{className:`h-1 w-full rounded-full bg-border overflow-hidden`,children:s(`div`,{className:`h-full bg-primary transition-all`,style:{width:`${d}%`},role:`progressbar`,"aria-valuenow":d,"aria-valuemin":0,"aria-valuemax":100})}),c.results.filter(e=>e.outcome===`failed`).slice(0,5).map(e=>r(`p`,{className:`text-[11px] text-destructive`,children:[e.childNativeId,`: `,e.error]},e.childNativeId))]})}function Re(e){let t=e.metadata;return[e.name,e.childNativeId,t.model,t.manufacturer,t.integration,t.externalLocation].filter(e=>typeof e==`string`&&e.length>0).join(` `)}n();var ze=`devices`,Be={id:ze,label:`Devices`,isDefault:!0},Ve=2e4,He=100;function Ue({addonId:n,integrationId:i,onClose:l}){let{t:u}=ye(),d=a(),[f,p]=o(new Set),[m,h]=o(new Set),[g,v]=o(new Map),[y,b]=o(null),{data:C}=fe(),w=(C??[]).find(e=>e.addonId===n)?.supportsLocationImport??!1,[T,E]=o(!0),D=_({addonId:n,integrationId:i}).data?.filters,O=D&&D.length>0?D:[Be],[k,A]=o(O.find(e=>e.isDefault)?.id??(O.some(e=>e.id===ze)?ze:O[0].id)),j=k!==ze,M=x(),P=S({addonId:n,integrationId:i,page:1,pageSize:Ve,filter:k}),F=P.refetch,L=M.mutate,R=e(()=>{L({addonId:n,integrationId:i},{onSettled:()=>{F()}})},[L,n,i,F]),B=t(null);c(()=>{let e=`${n}::${i}`;B.current===e||P.isLoading||(B.current=e,(P.data?.candidates.length??0)===0&&R())},[n,i,P.isLoading,P.data,R]);let H=M.isPending,U=M.isError?M.error instanceof Error?M.error.message:String(M.error):null,W=typeof M.data?.lastError==`string`&&M.data.lastError.length>0?M.data.lastError:null,G=P.data?.candidates??[],K=P.isError?P.error instanceof Error?P.error.message:String(P.error):null,q=ee(),[J,ne]=o(null),re=e(e=>{e.alreadyAdopted||p(t=>{let n=new Set(t);return n.has(e.childNativeId)?n.delete(e.childNativeId):n.add(e.childNativeId),n})},[]),ie=e(e=>{h(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),ae=e((e,t)=>{v(n=>{let r=new Map(n),i=r.get(e)?.hiddenChildIds??new Set,a=new Set(i);return a.has(t)?a.delete(t):a.add(t),a.size===0?r.delete(e):r.set(e,{hiddenChildIds:a}),r})},[]),Y=e(e=>{let t={};for(let n of e){let e=g.get(n);e&&e.hiddenChildIds.size>0&&(t[n]={hiddenChildIds:[...e.hiddenChildIds]})}return Object.keys(t).length>0?t:void 0},[g]),X=e(async()=>{b(null);let e=[...f];if(e.length!==0)try{let t=Y(e),{jobId:r}=await q.mutateAsync({addonId:n,integrationId:i,filter:k,childNativeIds:e,...t?{perCandidate:t}:{},...w?{importLocations:T}:{}});ne(r),p(new Set),v(new Map)}catch(e){b(e instanceof Error?e.message:String(e))}},[f,Y,q,n,i,k,w,T]),oe=t(null),ce=e(()=>{J===null||oe.current===J||(oe.current=J,F(),d.invalidateQueries({queryKey:[[`integrations`]]}),d.invalidateQueries({queryKey:[[`deviceManager`]]}))},[J,F,d]),ue=e(e=>{A(e),p(new Set),h(new Set),v(new Map),b(null)},[]),pe=f.size,Z=J!==null&&pe===0&&!q.isPending;return r(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center`,children:[s(`div`,{className:`absolute inset-0 bg-black/60`,onClick:l}),r(`div`,{className:`relative z-10 flex w-full max-w-3xl flex-col h-[85vh] rounded-xl border border-border bg-background shadow-2xl`,children:[r(`div`,{className:`flex items-center justify-between border-b border-border px-5 py-4 shrink-0`,children:[r(`div`,{className:`min-w-0`,children:[s(`h2`,{className:`text-sm font-semibold text-foreground`,children:u(`integrations.adoptDevices`,{defaultValue:`Adopt devices`})}),s(`p`,{className:`text-[11px] text-foreground-subtle mt-0.5`,children:u(`integrations.adoptDevicesHint`,{defaultValue:`Preview the candidate devices and add the ones you want.`})})]}),r(`div`,{className:`flex items-center gap-3 shrink-0`,children:[w&&r(`label`,{className:`flex items-center gap-1.5 cursor-pointer text-[11px] text-foreground-subtle hover:text-foreground transition-colors`,children:[s(`input`,{type:`checkbox`,checked:T,onChange:e=>E(e.target.checked),className:`accent-primary`}),u(`integrations.importLocations`,{defaultValue:`Import locations from the integration`})]}),s(`button`,{onClick:l,className:`rounded-md p-1 text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,"aria-label":`Close`,children:s(z,{className:`h-4 w-4`})})]})]}),r(`div`,{className:`flex-1 min-h-0 px-5 py-3 flex flex-col gap-2 overflow-hidden`,children:[(U??K??W)&&G.length===0&&s(`div`,{className:`rounded-lg border border-destructive/30 bg-destructive/5 px-4 py-3 shrink-0`,children:r(`div`,{className:`flex items-start gap-2`,children:[s(V,{className:`h-3.5 w-3.5 text-destructive mt-0.5 shrink-0`}),r(`div`,{className:`min-w-0`,children:[s(`p`,{className:`text-xs font-medium text-destructive`,children:u(`integrations.adoptRefreshFailed`,{defaultValue:`Could not discover devices.`})}),s(`p`,{className:`text-[11px] text-destructive/90 mt-0.5`,children:U??K??W})]})]})}),O.length>1&&s(We,{filters:O,activeFilter:k,onSelect:ue}),s(`div`,{className:`flex-1 min-h-0`,children:s(se,{mode:`generic`,items:G,pageSize:He,getKey:e=>e.childNativeId,getSearchText:Re,getFilterType:e=>e.type,filterOptions:le(),filterLabel:u(`integrations.adoptColType`,{defaultValue:`Type`}),isLoading:P.isLoading||H&&G.length===0,searchPlaceholder:u(`integrations.adoptSearch`,{defaultValue:`Search candidates…`}),emptyLabel:(U??K??W)&&G.length===0?``:u(`integrations.adoptNoCandidates`,{defaultValue:`No candidate devices found.`}),toolbar:r(`button`,{type:`button`,onClick:R,disabled:H,title:u(`integrations.adoptRefreshTitle`,{defaultValue:`Re-scan Home Assistant for devices`}),className:`inline-flex items-center gap-1.5 rounded-lg border border-border bg-surface px-2.5 py-1.5 text-xs text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors disabled:opacity-60 shrink-0`,children:[s(te,{className:`h-3.5 w-3.5 ${H?`animate-spin`:``}`}),u(`integrations.adoptRefresh`,{defaultValue:`Refresh`})]}),columns:[{key:`name`,header:u(`integrations.adoptColName`,{defaultValue:`Name`}),headerClassName:`w-[55%]`,cell:e=>s(Ge,{candidate:e,expandable:!j,expanded:m.has(e.childNativeId),onToggleExpand:()=>ie(e.childNativeId),adoptedLabel:u(`integrations.adoptAlready`,{defaultValue:`Adopted`})})},{key:`type`,header:u(`integrations.adoptColType`,{defaultValue:`Type`}),headerClassName:`w-[30%] hidden sm:table-cell`,cellClassName:`hidden sm:table-cell`,cell:e=>{let t=N(e.type),n=t.icon;return r(`span`,{className:`inline-flex items-center gap-1.5 text-[10px] text-foreground-subtle`,children:[s(n,{className:`h-3.5 w-3.5 shrink-0`}),t.label]})}},{key:`select`,header:``,headerClassName:`w-[15%] text-right`,cellClassName:`text-right`,cell:e=>s(`div`,{className:`flex items-center justify-end`,children:s(`button`,{onClick:()=>re(e),disabled:e.alreadyAdopted,"aria-label":f.has(e.childNativeId)?`Deselect`:`Select`,className:`inline-flex h-5 w-5 items-center justify-center rounded border ${f.has(e.childNativeId)?`border-primary bg-primary`:`border-border`} ${e.alreadyAdopted?`cursor-not-allowed opacity-50`:``}`,children:f.has(e.childNativeId)&&s(de,{className:`h-3 w-3 text-primary-foreground`})})})}],isExpanded:e=>!j&&m.has(e.childNativeId),renderExpanded:j?void 0:e=>s(Ke,{candidate:e,hiddenChildIds:g.get(e.childNativeId)?.hiddenChildIds??new Set,onToggleChildHidden:t=>ae(e.childNativeId,t)}),rowClassName:e=>e.alreadyAdopted?`opacity-60`:f.has(e.childNativeId)?`bg-primary/5`:``})})]}),y&&s(`div`,{className:`border-t border-destructive/30 bg-destructive/5 px-5 py-2 shrink-0`,children:r(`div`,{className:`flex items-start gap-2`,children:[s(V,{className:`h-3.5 w-3.5 text-destructive mt-0.5 shrink-0`}),s(`p`,{className:`text-[11px] text-destructive`,children:y})]})}),J!==null&&s($,{addonId:n,integrationId:i,jobId:J,onFinished:ce}),r(`div`,{className:`flex items-center justify-between border-t border-border px-5 py-3 shrink-0`,children:[s(`div`,{}),r(`div`,{className:`flex items-center gap-2`,children:[s(`button`,{onClick:l,className:`rounded-lg border border-border px-3 py-1.5 text-xs text-foreground-subtle hover:text-foreground transition-colors`,children:u(`integrations.cancel`,{defaultValue:`Cancel`})}),r(`button`,{onClick:Z?l:X,disabled:!Z&&(pe===0||q.isPending),className:`inline-flex items-center gap-1.5 rounded-lg bg-primary px-4 py-1.5 text-xs font-medium text-primary-foreground shadow-sm disabled:opacity-50 disabled:cursor-not-allowed`,children:[q.isPending&&s(I,{className:`h-3.5 w-3.5 animate-spin`}),Z?u(`integrations.close`,{defaultValue:`Close`}):u(`integrations.addSelected`,{defaultValue:`Add selected`}),!Z&&pe>0?` (${pe})`:``]})]})]})]})]})}function We({filters:e,activeFilter:t,onSelect:n}){return s(`div`,{role:`tablist`,"aria-label":`Discovery granularity`,className:`inline-flex shrink-0 self-start rounded-lg border border-border bg-surface p-0.5`,children:e.map(e=>{let r=e.id===t;return s(`button`,{type:`button`,role:`tab`,"aria-selected":r,onClick:()=>n(e.id),className:`rounded-md px-3 py-1 text-xs font-medium transition-colors ${r?`bg-primary text-primary-foreground shadow-sm`:`text-foreground-subtle hover:text-foreground hover:bg-surface-hover`}`,children:e.label},e.id)})})}function Ge({candidate:e,expandable:t,expanded:n,onToggleExpand:i,adoptedLabel:a}){let o=(e.children??[]).length;return r(`div`,{className:`flex items-center gap-2.5 min-w-0`,children:[t&&o>0?r(`button`,{type:`button`,onClick:i,"aria-label":n?`Collapse`:`Expand`,"aria-expanded":n,className:`flex h-5 flex-shrink-0 items-center justify-center gap-0.5 rounded px-0.5 text-[10px] text-foreground-subtle transition-colors hover:bg-surface-hover hover:text-foreground`,children:[s(n?u:d,{className:`h-3.5 w-3.5`}),o]}):s(`span`,{className:`flex h-5 w-5 flex-shrink-0 items-center justify-center text-foreground-subtle/40`,children:`—`}),s(`span`,{className:`truncate text-xs font-medium text-foreground`,children:e.name}),e.alreadyAdopted&&s(`span`,{className:`rounded-full bg-success/10 px-2 py-0.5 text-[9px] font-medium text-success shrink-0`,children:a})]})}function Ke({candidate:e,hiddenChildIds:t,onToggleChildHidden:n}){let i=e.children??[];return i.length===0?null:s(`div`,{className:`space-y-1 py-1`,children:i.map(e=>{let i=t.has(e.childNativeId),a=e.capabilities??[];return r(`div`,{className:`flex items-center gap-2 rounded px-2 py-1 ${i?`opacity-50`:``}`,children:[s(`span`,{className:`text-[11px] text-foreground truncate flex-1 min-w-0`,children:e.name}),a.length>0&&s(`span`,{className:`text-[9px] text-foreground-subtle truncate`,children:a.join(`, `)}),s(`button`,{onClick:()=>n(e.childNativeId),"aria-label":i?`Show child`:`Hide child`,title:i?`Show after adopt`:`Hide after adopt`,className:`flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors flex-shrink-0`,children:s(i?f:v,{className:`h-3 w-3`})})]},e.childNativeId)})})}n();function qe(e){let t=[];for(let n of e){if(n.type===`group`){t.push(...qe(n.fields));continue}`key`in n&&typeof n.key==`string`&&t.push(n.key)}return t}function Je(e,t){if(!e)return{};let n=new Set(e.sections.flatMap(e=>qe(e.fields))),r={};for(let e of n)Object.prototype.hasOwnProperty.call(t,e)&&(r[e]=t[e]);return r}function Ye(e){return{...e.tabs?{tabs:e.tabs}:{},sections:e.sections.map(e=>({...e,fields:e.fields.map(e=>{if(`value`in e){let{value:t,...n}=e;return n}return e})}))}}function Xe({integrationId:e,addonId:t,name:n,kind:o,mode:c,brokerKind:l,canTest:u=!1,trpc:d,onClose:f}){let{t:p}=ye(),m=a(),{data:h,isLoading:_}=K({id:e},{enabled:c===`account`||c===`broker`}),v=i(()=>{let e=h?.brokerId;return typeof e==`string`?e:null},[h]),{data:y,isLoading:b}=G({addonId:t,nodeId:`hub`},{enabled:c===`account`}),x=i(()=>y?Ye(y):null,[y]),S=X(),C=(t,n)=>{S.mutate({id:e,settings:t,...n?{secretKeys:[...n]}:{}},{onSuccess:()=>{m.invalidateQueries(),f()}})};return s(g,{open:!0,onOpenChange:e=>!e&&f(),children:r(O,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,children:[s(w,{children:r(q,{children:[p(`integrations.editConfig`,{defaultValue:`Edit configuration`}),` — `,n]})}),s(he,{children:c===`broker`?l?r(`div`,{className:`space-y-3`,children:[s(`p`,{className:`text-[11px] text-foreground-subtle`,children:p(`integrations.relinkBrokerHelp`,{defaultValue:`Choose the broker this integration connects through. Picking a different broker re-points it and restarts the addon.`})}),v&&r(`p`,{className:`text-[11px] text-foreground`,children:[p(`integrations.currentBroker`,{defaultValue:`Current broker`}),`:`,` `,s(`span`,{className:`font-mono text-foreground-subtle`,children:v})]}),S.isPending?r(`div`,{className:`flex items-center gap-2 text-[11px] text-foreground-subtle`,children:[s(I,{className:`h-3 w-3 animate-spin`}),p(`integrations.saving`,{defaultValue:`Saving…`})]}):s(Oe,{kind:l,onResolved:e=>{C({brokerId:e})},onBack:f}),S.isError&&s(`p`,{className:`text-[11px] text-danger`,children:p(`integrations.relinkFailed`,{defaultValue:`Failed to update broker link.`})})]}):s(`p`,{className:`text-[11px] text-danger`,children:p(`integrations.noBrokerKind`,{defaultValue:`This integration declares device-adoption but its addon manifest has no brokerKind.`})}):c===`account`?_||b?r(`div`,{className:`flex items-center gap-2 text-[11px] text-foreground-subtle`,children:[s(I,{className:`h-3 w-3 animate-spin`}),p(`integrations.loading`,{defaultValue:`Loading…`})]}):s(De,{addonId:t,configSchema:x,canTest:u,initialName:n,initialConfig:Je(x,h??{}),submitLabel:p(`integrations.save`,{defaultValue:`Save`}),hideName:!0,onSave:({config:e,secretKeys:t})=>C(e,t),onBack:f}):s(L,{trpc:d,addonId:t,nodeId:`hub`,title:n})})]})})}function Ze(e){return e==null?!1:e.sections.some(e=>e.fields.length>0)}n();function Qe(){let{t}=ye(),{integrationId:n}=Se(),u=a(),d=Ce(),[f,m]=be(),_=l(),[v,b]=o(!1),[x,S]=o(!1),[C,T]=o(!1),[A,ee]=o(!1),{data:N,isLoading:te}=ae({id:n??``},{enabled:!!n}),{data:F}=G({addonId:N?.addonId??``,nodeId:`hub`},{enabled:!!N?.addonId}),{data:L,isSuccess:z}=fe(),V=i(()=>{let e=N?.addonId;return!e||!z?null:(L??[]).find(t=>t.addonId===e)?.kind===`device-adoption`?`device-adoption`:`device-provider`},[L,N?.addonId,z]),{data:U}=ne({}),K=i(()=>(U?.providers??[]).some(e=>e.addonId===N?.addonId),[U,N?.addonId]),Y=V!==null,X=N?.info?.fixed===!0,ce=Y?V===`device-adoption`?t(`integrations.adoptDevices`,{defaultValue:`Adopt devices`}):t(`integrations.addDevice`):t(`integrations.addDeviceLoading`,{defaultValue:`Loading…`}),le=i(()=>{let e=N?.addonId;return!e||!z?null:(L??[]).find(t=>t.addonId===e)?.brokerKind??null},[L,N?.addonId,z]),de=i(()=>{let e=N?.addonId;return!e||!z?!1:(L??[]).find(t=>t.addonId===e)?.canTest===!0},[L,N?.addonId,z]),Z=i(()=>{let e=N?.addonId;return!e||!z?null:(L??[]).find(t=>t.addonId===e)?.mode??null},[L,N?.addonId,z]);c(()=>{f.get(`add`)===`1`&&Y&&(b(!0),m(e=>{let t=new URLSearchParams(e);return t.delete(`add`),t},{replace:!0}))},[f,Y,m]);let ve=F!=null&&Array.isArray(F.sections)&&F.sections.some(e=>e.fields.length>0),{data:xe}=oe({addonId:N?.addonId??``,nodeId:`hub`},{enabled:!!N?.addonId&&Z!==`account`}),we=Z!==null&&Z!==`account`&&Ze(xe),De=i(()=>N?.addonId?[N.addonId]:[],[N?.addonId]),{data:Oe}=W({projection:`slim`},{refetchInterval:3e4}),Q=[[`integrations`,`get`],{input:{id:n??``},type:`query`}],je=H({onMutate:async e=>{await u.cancelQueries({queryKey:Q});let t=u.getQueryData(Q);return t!=null&&u.setQueryData(Q,{...t,enabled:e.enabled}),{previous:t}},onError:(e,t,n)=>{let r=n;r?.previous!=null&&u.setQueryData(Q,r.previous)},onSettled:()=>{u.invalidateQueries({queryKey:[[`integrations`]]}),u.invalidateQueries({queryKey:[[`deviceManager`]]})}}),Me=pe({onSuccess:()=>{u.invalidateQueries({queryKey:[[`integrations`]]}),u.invalidateQueries({queryKey:[[`deviceManager`]]}),d(`/integrations`)}}),Ne=h({onSuccess:()=>{u.invalidateQueries({queryKey:[[`integrations`]]}),u.invalidateQueries({queryKey:[[`deviceManager`]]})}}),Pe=B({onSuccess:()=>{u.invalidateQueries({queryKey:[[`deviceManager`]]})}}),Fe=E({onSuccess:()=>{u.invalidateQueries({queryKey:[[`deviceManager`]]})}}),Le=ue({onSuccess:()=>{u.invalidateQueries({queryKey:[[`deviceManager`]]})}}),$=i(()=>Oe??[],[Oe]),Re=i(()=>{let e=new Map;for(let t of $)e.set(t.id,{id:t.id,name:t.name??t.stableId??`#${String(t.id)}`});return e},[$]),ze=e(e=>Re.get(e)??null,[Re]),{data:Be}=R(void 0),Ve=i(()=>y(Be),[Be]),He=e(e=>d(`/devices/${String(e)}`),[d]),We=i(()=>{let e=N?.id;return e?$.filter(t=>{let n=Ve(t);return n.kind===`resolved`&&n.integration.id===e}):[]},[$,N?.id,Ve]),Ge=i(()=>Be===void 0?null:M(We).length,[Be,We])??`…`;return te?r(`div`,{className:`p-4`,children:[s(`div`,{className:`h-16 rounded-lg bg-surface animate-pulse mb-4`}),s(`div`,{className:`h-40 rounded-lg bg-surface animate-pulse`})]}):N?r(`div`,{className:`p-4 space-y-4 overflow-x-hidden`,children:[s(_e,{items:[{label:`Integrations`,onClick:()=>d(`/integrations`)},{label:N.name}]}),r(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[r(`div`,{className:`flex items-center gap-3 min-w-0`,children:[s($e,{addonId:N.addonId}),r(`div`,{className:`min-w-0`,children:[s(`h1`,{className:`text-lg font-semibold text-foreground truncate`,children:N.name}),r(`p`,{className:`text-[11px] text-foreground-subtle mt-0.5 truncate`,children:[N.addonId,` · `,Ge,` `,t(`integrations.devices`)]})]})]}),r(`div`,{className:`flex flex-wrap items-center justify-end gap-2`,children:[K&&r(`button`,{onClick:()=>S(!0),className:`flex items-center gap-1.5 rounded-lg border border-border bg-surface px-2.5 py-1.5 text-xs font-medium text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,title:`Scan the network for devices (incl. a different subnet)`,children:[s(D,{className:`h-3.5 w-3.5`}),`Scan network`]}),!X&&r(`button`,{onClick:()=>b(!0),disabled:!Y,className:`flex items-center gap-1.5 rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground shadow-sm disabled:opacity-50 disabled:cursor-not-allowed`,title:ce,children:[s(re,{className:`h-3.5 w-3.5`}),ce]}),r(`div`,{className:`inline-flex items-center gap-2 rounded-lg border px-3 py-1.5 transition-colors ${je.isPending?`opacity-60`:``} ${N.enabled?`border-success/30 bg-success/5`:`border-border bg-surface`}`,title:t(`integrations.toggleHint`,{defaultValue:`Click to toggle`}),children:[s(ie,{checked:N.enabled,onCheckedChange:e=>je.mutate({id:n,enabled:e}),disabled:je.isPending,"aria-label":N.enabled?`Disable integration`:`Enable integration`}),s(`span`,{className:`text-[11px] font-medium ${N.enabled?`text-success`:`text-foreground-subtle`}`,children:N.enabled?`Enabled`:`Disabled`}),je.isPending&&s(I,{className:`h-3 w-3 animate-spin text-foreground-subtle`})]}),Z!==`standalone`&&(ve||V===`device-adoption`)&&r(`button`,{onClick:()=>T(!0),className:`flex items-center gap-1.5 rounded-lg border border-border bg-surface px-3 py-1.5 text-[11px] text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,children:[s(k,{className:`h-3 w-3`}),t(`integrations.config`)]}),r(`button`,{onClick:()=>ee(!0),className:`flex items-center gap-1.5 rounded-lg border border-border bg-surface px-3 py-1.5 text-[11px] text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,title:t(`integrations.logs`,{defaultValue:`View logs`}),children:[s(j,{className:`h-3 w-3`}),t(`integrations.logs`,{defaultValue:`Logs`})]}),s(J,{label:`Restart`,icon:P,title:`Restart "${N.name}"?`,description:`Restarting the addon will briefly disconnect every device backed by it (${Ge} active). Streams will reconnect automatically.`,confirmLabel:`Restart`,triggerVariant:`outline`,confirmVariant:`danger`,disabled:Ne.isPending,action:()=>Ne.mutateAsync({addonId:N.addonId})}),!X&&n&&s(J,{label:t(`integrations.delete`,{defaultValue:`Delete`}),icon:p,title:t(`integrations.deleteTitle`,{defaultValue:`Delete integration?`}),description:t(`integrations.deleteWarning`,{defaultValue:`This removes the integration "{{name}}" and its {{count}} device(s). The addon will restart. This cannot be undone.`,name:N.name,count:Ge}),confirmLabel:t(`integrations.confirmDelete`,{defaultValue:`Delete integration`}),triggerVariant:`outline`,confirmVariant:`danger`,className:`border-danger bg-danger/10 text-danger hover:bg-danger hover:text-background`,disabled:Me.isPending,action:()=>Me.mutateAsync({id:n})})]})]}),we&&s(Te,{nodeId:null,addonIds:De,level:`global`,surface:`integration`,title:t(`integrations.settings`,{defaultValue:`Settings`})}),s(se,{context:`integration-detail`,devices:$,trpc:_.trpcClient,integrationOf:Ve,forceIntegrationId:N.id,urlScope:`root`,lsKey:`integration-detail:${N.addonId}`,resolveIntegrationIcon:Ee,resolveParent:ze,onNavigate:He,batchActions:{remove:Pe.mutate,disable:Fe.mutate,enable:Le.mutate},...X?{}:{onDeleteDevice:e=>Pe.mutate({deviceId:e.id})}}),v&&n&&V===`device-adoption`&&s(Ue,{addonId:N.addonId,integrationId:n,onClose:()=>b(!1)}),v&&n&&V===`device-provider`&&s(Ie,{open:v,integrationId:n,addonId:N.addonId,onClose:()=>b(!1)}),x&&N&&s(ke,{open:x,scope:{addonId:N.addonId,label:N.name},onClose:()=>S(!1)}),C&&n&&V!==null&&Z!==null&&s(Xe,{integrationId:n,addonId:N.addonId,name:N.name,kind:V,mode:Z,brokerKind:le,canTest:de,trpc:_.trpcClient,onClose:()=>T(!1)}),A&&s(g,{open:!0,onOpenChange:e=>!e&&ee(!1),children:r(O,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,className:`md:max-w-5xl md:h-[80vh]`,children:[s(w,{className:`mb-0`,children:r(q,{className:`flex items-center gap-2 min-w-0`,children:[s(j,{className:`h-4 w-4 text-primary shrink-0`}),s(`span`,{className:`truncate`,children:N.name}),r(`span`,{className:`text-[10px] text-foreground-subtle font-mono truncate font-normal`,children:[N.addonId,n?` · ${n}`:``]})]})}),s(he,{className:`min-h-0 overflow-hidden p-0`,children:s(me,{addonId:N.addonId,limit:200,maxHeight:`max-h-full`,showScope:!1,className:`h-full border-0 rounded-none`})})]})})]}):r(`div`,{className:`flex flex-col items-center justify-center py-20 px-6 text-center gap-4`,children:[s(`div`,{className:`flex h-12 w-12 items-center justify-center rounded-full bg-foreground-subtle/10`,children:s(Ae,{className:`h-6 w-6 text-foreground-subtle`})}),r(`div`,{className:`space-y-1 max-w-sm`,children:[s(`h2`,{className:`text-sm font-semibold text-foreground`,children:t(`integrations.integrationNotFound`,{defaultValue:`Integration not found`})}),s(`p`,{className:`text-[11px] text-foreground-subtle`,children:t(`integrations.integrationNotFoundHint`,{defaultValue:`The integration "{{id}}" does not exist. It may have been deleted, or the URL may be wrong.`,id:n??``})})]}),r(`button`,{onClick:()=>d(`/integrations`),className:`inline-flex items-center gap-1.5 rounded-lg border border-border bg-surface px-3 py-1.5 text-[11px] font-medium text-foreground hover:bg-surface-hover transition-colors`,children:[s(ge,{className:`h-3 w-3`}),t(`integrations.backToList`,{defaultValue:`Back to integrations`})]})]})}function $e({addonId:e}){let t=we(e),[n,r]=o(!1);return!t||n?null:s(`img`,{src:t,alt:``,className:`h-8 w-8 rounded-lg shrink-0`,onError:()=>r(!0)})}export{Qe as IntegrationDetailPage};
@@ -1 +0,0 @@
1
- import{Q as e,S as t,W as n,b as r,o as i,q 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-DhP-Lgiq.js";import{st as s}from"./player-overlays-EDVR7CqJ.js";import{Bu as c,Cn as l,En as u,Fn as d,G as f,K as p,On as m,Ri as h,Rn as g,Tn as _,Yn as v,Zu as y,_d as b,ad as x,ci as S,cu as C,di as w,fi as T,gi as E,hi as D,kn as ee,li as te,md as ne,mi as re,nd as ie,pi as ae,rr as O,td as k,wn as A,wr as j}from"./src-BEsQ_4LU.js";import{t as M}from"./monitor-smartphone-Dpm4bhCz.js";import{Cr as N,Nt as P,tr as F}from"./client-B2uiK_6q.js";import{I,Z as L}from"./index-L63cSV_9.js";import{t as R}from"./BrokerForm-AegeAXg9.js";import{n as z,r as B,t as V}from"./AddonIntegrationBody-PmjCQ2Ms.js";e();var H=`kind`,U=`name`,W=`restore`,G=`restoreId`;function K(e){return{sections:[{id:`broker-identity`,title:`Broker`,columns:1,fields:[{type:`select`,key:H,label:`Kind`,options:e.map(e=>({value:e.key,label:e.label})),disabled:e.length<=1},{type:`text`,key:U,label:`Name`,placeholder:`My Home Assistant`,required:!0},{type:`boolean`,key:W,label:`Restore a broker that was removed, under its original id`,description:`Devices remember the broker id they were discovered under, so restoring the original id reconnects them instead of needing re-discovery. An id that is still in use is refused.`},{type:`text`,key:G,label:`Original broker id`,placeholder:`ha_004`,required:!0,showWhen:{field:W,equals:!0}}]}]}}function q(e){let t=t=>{let n=e[t];return typeof n==`string`?n.trim():``},n=t(H);if(n===``)return{ok:!1,problem:`Pick a kind.`};let r=t(U);if(r===``)return{ok:!1,problem:`Enter a name before saving.`};if(e.restore!==!0)return{ok:!0,identity:{kindKey:n,name:r,restoreId:null}};let i=t(G);return i===``?{ok:!1,problem:`Enter the original id, or turn restore off to create a new broker.`}:{ok:!0,identity:{kindKey:n,name:r,restoreId:i}}}var oe={"home-assistant":`Home Assistant`,mqtt:`MQTT`};function J(e){return oe[e]??e}function se(e){return Array.isArray(e)?e.filter(e=>typeof e==`object`&&!!e&&typeof e.addonId==`string`&&Array.isArray(e.kinds)):[]}var ce={connected:`success`,connecting:`warning`,disconnected:`default`,"auth-failed":`danger`,unreachable:`danger`,error:`danger`};function le({status:e}){return o(O,{variant:ce[e],className:`text-[10px]`,children:e})}function ue(e){return Array.isArray(e)?e.filter(e=>typeof e==`object`&&!!e&&typeof e.id==`string`):[]}function Y({title:e,subtitle:n,onClose:r,children:i}){return o(l,{open:!0,onOpenChange:e=>!e&&r(),children:t(_,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,children:[t(m,{children:[o(ee,{children:e}),n&&o(u,{children:n})]}),o(A,{className:`space-y-3 pr-1`,children:i})]})})}function de({kinds:e,onClose:r,onDone:s}){let c=i(),l=n(()=>K(e.map(e=>({key:X(e),label:e.label}))),[e]),[u,f]=a(()=>({[H]:X(e[0]),[U]:``,[W]:!1,[G]:``})),[p,m]=a(null),h=e.find(e=>X(e)===u.kind)??e[0],g=h?.kind??``,_=h?.addonId,v=S({onSuccess:()=>{c.invalidateQueries({queryKey:[[`broker`,`list`]]}),s()}}),y=e=>{let t=q(u);if(!t.ok){m(t.problem);return}m(null);let{name:n,restoreId:r}=t.identity;v.mutate({kind:g,name:n,settings:e,...r===null?{}:{id:r},..._===void 0?{}:{addonId:_}})};return t(Y,{title:`Add broker`,subtitle:`Register a message broker for exporters and automations.`,onClose:v.isPending?()=>{}:r,children:[o(I,{schema:l,values:u,onChange:f}),p!==null&&o(d,{message:p}),v.isError&&o(d,{message:v.error instanceof Error?v.error.message:String(v.error)}),g&&o(R,{kind:g,..._===void 0?{}:{addonId:_},onSubmit:y,onCancel:r,submitLabel:v.isPending?`Adding…`:`Add broker`,disabled:v.isPending},X(h))]})}function X(e){return e===void 0?``:`${e.addonId??``}::${e.kind}`}function fe({broker:e,onClose:r,onDone:a}){let s=i(),c=te({id:e.id,addonId:e.addonId}),l=D({onSuccess:()=>{s.invalidateQueries({queryKey:[[`broker`,`list`]]}),s.invalidateQueries({queryKey:[[`broker`,`getSettings`],{input:{id:e.id,addonId:e.addonId}}]}),a()}}),u=n(()=>{let e=c.data;return e&&typeof e==`object`?{...e}:{}},[c.data]);return o(Y,{title:`Edit ${e.name}`,subtitle:`${J(e.kind)} · ${e.id}`,onClose:l.isPending?()=>{}:r,children:c.isLoading?t(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[o(b,{className:`h-3.5 w-3.5 animate-spin`}),` Loading settings…`]}):c.isError?t(`div`,{className:`space-y-3`,children:[o(d,{message:`Failed to load settings: ${c.error instanceof Error?c.error.message:`Unknown error`}`}),o(`div`,{className:`flex justify-end`,children:o(g,{variant:`outline`,size:`sm`,onClick:r,children:`Close`})})]}):t(`div`,{className:`space-y-3`,children:[l.isError&&o(d,{message:l.error instanceof Error?l.error.message:String(l.error)}),o(R,{kind:e.kind,addonId:e.addonId,initialValues:u,onSubmit:t=>{l.mutate({id:e.id,settings:t,addonId:e.addonId})},onCancel:r,submitLabel:l.isPending?`Saving…`:`Save`,disabled:l.isPending})]})})}function pe({broker:e,onEdit:n}){let r=i(),c=v(),[l,u]=a(null),d=E({onSuccess:e=>u(e.ok?{ok:!0}:{ok:!1,error:e.error}),onError:e=>u({ok:!1,error:e instanceof Error?e.message:String(e)})}),f=re({onSuccess:()=>{r.invalidateQueries({queryKey:[[`broker`,`list`]]})}}),p=async()=>{await c({title:`Delete broker`,message:`Delete broker "${e.name}"? Integrations that depend on it will stop working.`,confirmLabel:`Delete`,variant:`danger`})&&f.mutate({id:e.id,addonId:e.addonId})};return t(`tr`,{className:`border-b border-border last:border-0`,children:[o(`td`,{className:`px-3 py-2 text-xs text-foreground font-medium`,children:e.name}),o(`td`,{className:`px-3 py-2 text-xs text-foreground-subtle`,children:J(e.kind)}),t(`td`,{className:`px-3 py-2`,children:[o(le,{status:e.status}),l&&o(`span`,{className:`ml-2 text-[10px] ${l.ok?`text-success`:`text-danger`}`,children:l.ok?`OK`:l.error??`failed`})]}),o(`td`,{className:`px-3 py-2`,children:t(`div`,{className:`flex items-center justify-end gap-1.5`,children:[t(g,{variant:`outline`,size:`sm`,onClick:()=>d.mutate({id:e.id,addonId:e.addonId}),disabled:d.isPending,title:`Test connection`,children:[d.isPending?o(b,{className:`h-3 w-3 animate-spin`}):o(C,{className:`h-3 w-3`}),`Test`]}),t(g,{variant:`outline`,size:`sm`,onClick:()=>n(e),title:`Edit`,children:[o(x,{className:`h-3 w-3`}),` Edit`]}),t(g,{variant:`outline`,size:`sm`,className:`border-danger/40 text-danger hover:bg-danger/10`,onClick:()=>{p()},disabled:f.isPending,title:`Delete`,children:[f.isPending?o(b,{className:`h-3 w-3 animate-spin`}):o(s,{className:`h-3 w-3`}),`Delete`]})]})})]})}function me({addonId:e}={}){let r=T({}),i=ae(),s=n(()=>ue(r.data).filter(t=>e===void 0||t.addonId===e),[r.data,e]),[c,l]=a(!1),[u,d]=a(null),f=n(()=>{let t=new Map;for(let n of se(i.data))if(!(e!==void 0&&n.addonId!==e))for(let e of n.kinds)t.set(`${n.addonId}::${e.kind}`,{addonId:n.addonId,kind:e.kind,label:e.label});for(let e of s)[...t.values()].some(t=>t.kind===e.kind)||t.set(`::${e.kind}`,{kind:e.kind,label:J(e.kind)});return[...t.values()]},[s,i.data,e]);return t(`div`,{className:`space-y-3`,children:[o(`div`,{className:`flex items-center justify-end`,children:t(g,{variant:`primary`,size:`sm`,onClick:()=>l(!0),disabled:f.length===0,title:f.length===0?`No broker providers available`:void 0,children:[o(ie,{className:`h-3.5 w-3.5`}),` Add broker`]})}),o(`div`,{className:`rounded-lg border border-border bg-surface overflow-x-auto`,children:t(`table`,{className:`w-full min-w-[36rem] border-collapse`,children:[o(`thead`,{children:t(`tr`,{className:`border-b border-border bg-background/50`,children:[o(`th`,{className:`px-3 py-2 text-left text-[10px] font-semibold uppercase tracking-wider text-foreground-subtle`,children:`Name`}),o(`th`,{className:`px-3 py-2 text-left text-[10px] font-semibold uppercase tracking-wider text-foreground-subtle`,children:`Kind`}),o(`th`,{className:`px-3 py-2 text-left text-[10px] font-semibold uppercase tracking-wider text-foreground-subtle`,children:`Status`}),o(`th`,{className:`px-3 py-2 text-right text-[10px] font-semibold uppercase tracking-wider text-foreground-subtle`,children:`Actions`})]})}),t(`tbody`,{children:[r.isLoading&&o(`tr`,{children:t(`td`,{colSpan:4,className:`px-3 py-6 text-center text-xs text-foreground-subtle`,children:[o(b,{className:`inline h-4 w-4 animate-spin`}),` Loading brokers…`]})}),r.isError&&o(`tr`,{children:t(`td`,{colSpan:4,className:`px-3 py-4 text-center text-xs text-danger`,children:[`Failed to load brokers:`,` `,r.error instanceof Error?r.error.message:`Unknown error`]})}),!r.isLoading&&!r.isError&&s.length===0&&o(`tr`,{children:o(`td`,{colSpan:4,className:`px-3 py-6 text-center text-xs text-foreground-subtle`,children:`No brokers registered yet. Add one to publish device events for downstream automations.`})}),s.map(e=>o(pe,{broker:e,onEdit:d},e.id))]})]})}),c&&o(de,{kinds:f,onClose:()=>l(!1),onDone:()=>l(!1)}),u&&o(fe,{broker:u,onClose:()=>d(null),onDone:()=>d(null)})]})}function he(e){if(typeof e==`string`)return e;if(typeof e==`object`&&e){let t=e.name;if(typeof t==`string`)return t}return null}function Z(e){let t=e,n=t?.manifest;if(n?.id===void 0)return null;let r=(n.capabilities??[]).map(he).filter(e=>e!==null);return{addonId:n.id,displayName:n.packageDisplayName??n.name??n.id,capNames:r,processState:t?.process?.state??null}}function ge(e,t){return Object.entries(e).filter(([,e])=>e===t).map(([e])=>e)}function _e(e,t){return t.find(t=>e.capNames.includes(t))??null}function Q(e){switch(e){case`running`:return{state:`ok`,label:`running`};case`crashed`:case`failed`:return{state:`error`,label:e};case`stopped`:case`disabled`:return{state:`off`,label:`stopped`};default:return{state:`unknown`,label:e??`unknown`}}}e();var $=1e4,ve=[{kind:`device-export`,label:`Device export`,icon:c,installLabel:`Add export`},{kind:`email`,label:`Email`,icon:ne,installLabel:`Add email provider`},{kind:`broker`,label:`Message brokers`,icon:y,installLabel:`Add broker addon`}];function ye(){let e=j(void 0,{refetchInterval:$}),i=L();return o(B,{icon:k,title:`Connectivity`,subtitle:`External systems this hub talks to — device exporters, email relays and message brokers.`,groups:n(()=>{let n=(e.data??[]).map(Z).filter(e=>e!==null);return ve.map(e=>{let a=ge(P,e.kind),s=n.flatMap(n=>{let s=_e(n,a);if(s===null)return[];let c=Q(n.processState);return[{id:n.addonId,name:n.displayName,fallbackIcon:e.icon,state:c.state,stateLabel:c.label,render:()=>o(V,{addonId:n.addonId,displayName:n.displayName,capName:s,isActive:n.processState===`running`,badges:t(r,{children:[o(xe,{processState:n.processState}),o(Se,{kind:e.kind,addonId:n.addonId})]}),lead:e.kind===`device-export`?o(p,{addonId:n.addonId}):void 0,panels:be(e.kind,n.addonId,e=>i(`/devices/${e}`))})}]});return{id:e.kind,label:e.label,entries:s,install:{capability:a[0]??e.kind,label:e.installLabel}}})},[e.data,i]),isLoading:e.isLoading,emptyTitle:`No external systems installed`,emptyDescription:`Install an export, email or broker addon to connect this hub to another system.`,legacyGroupParam:`tab`})}function be(e,t,n){return e===`device-export`?[{id:`devices`,title:`Devices`,icon:M,placement:`end`,content:o(f,{addonId:t,onOpenDevice:n,showSetup:!1})}]:e===`broker`?[{id:`connections`,title:`Connections`,icon:y,content:o(me,{addonId:t})}]:[]}function xe({processState:e}){let{state:t,label:n}=Q(e);return o(O,{variant:t===`ok`?`success`:t===`error`?`danger`:`default`,className:`${z} capitalize`,children:n})}function Se({kind:e,addonId:t}){return e===`broker`?o(Ce,{addonId:t}):e===`device-export`?o(we,{addonId:t}):null}function Ce({addonId:e}){let{data:t}=w({addonId:e},{refetchInterval:$,retry:!1}),n=N.safeParse(t);if(!n.success)return null;let{brokerCount:r,connectedCount:i}=n.data;return o(O,{variant:`info`,className:z,children:`${r} connection${r===1?``:`s`}${i>0?` · ${i} connected`:``}`})}function we({addonId:e}){let{data:t}=h({addonId:e},{refetchInterval:$,retry:!1}),n=F.safeParse(t);if(!n.success)return null;let{linkState:r,exposedDeviceCount:i}=n.data;return o(O,{variant:r===`linked`?`success`:r===`error`?`danger`:`default`,className:z,children:`${r} · ${i} exposed`})}export{ye as IntegrationsPage};