@camstack/addon-admin-ui 1.2.483 → 1.2.484
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{AddonAssetIcon-DG82cOOB.js → AddonAssetIcon-3vq-0y-v.js} +1 -1
- package/dist/assets/{Addons-B7pn0v6S.js → Addons-Bk1BZHnK.js} +1 -1
- package/dist/assets/{AdminPage-CNutWOEU.js → AdminPage-QmLz5qjj.js} +1 -1
- package/dist/assets/{AdminSectionedPage-Dm8ND20L.js → AdminSectionedPage-DYCbg6TR.js} +1 -1
- package/dist/assets/AiProfiles-ZWSpLyRc.js +3 -0
- package/dist/assets/{BrokerForm-DijcT6td.js → BrokerForm-C0PFW-8b.js} +1 -1
- package/dist/assets/Build-Dnm_I3D9.js +40 -0
- package/dist/assets/{Calendars-Ck9cG0iB.js → Calendars-DvjofwPU.js} +1 -1
- package/dist/assets/{Cluster-yiPXhRl-.js → Cluster-CrfYNPnJ.js} +1 -1
- package/dist/assets/{CompositionBlockEditor-BxkWKOxd.js → CompositionBlockEditor-BcDYEyOm.js} +1 -1
- package/dist/assets/{CompositionEditorPage-C7aaI4Ga.js → CompositionEditorPage-DpKcmhYi.js} +1 -1
- package/dist/assets/{Data-Cker1tA1.js → Data-BqyCS1VW.js} +1 -1
- package/dist/assets/DeviceDetail-DfLnQGqY.js +2 -0
- package/dist/assets/{DeviceDoActionFields-CP-EliT2.js → DeviceDoActionFields-CJj4-67I.js} +1 -1
- package/dist/assets/{Devices-DmVvfG_b.js → Devices-DQnrgH0r.js} +1 -1
- package/dist/assets/{EmbedPlayerPage-CoSlXnQ9.js → EmbedPlayerPage-D6aNp4TG.js} +1 -1
- package/dist/assets/HelperWizard-BM-npSft.js +2 -0
- package/dist/assets/{History-gocAbU36.js → History-DZ_p9s8N.js} +1 -1
- package/dist/assets/Identity-B-pYFi7F.js +1 -0
- package/dist/assets/{IntegrationDetail-B17OUQKx.js → IntegrationDetail-CvtkeTns.js} +1 -1
- package/dist/assets/{IntegrationHub-D6NA9UIc.js → IntegrationHub-Crv-Ut8D.js} +1 -1
- package/dist/assets/{Integrations-UBtD6K0x.js → Integrations-BpVqgjFG.js} +1 -1
- package/dist/assets/{Integrations-DHGfNtpw.js → Integrations-tTRZOlex.js} +1 -1
- package/dist/assets/{Library-BbuNPwa4.js → Library-BFFl1PFs.js} +1 -1
- package/dist/assets/{Locations-BHhCef1F.js → Locations-sD9PMtF8.js} +2 -2
- package/dist/assets/{Logs-BdiPIKKN.js → Logs-ByKgDjzR.js} +1 -1
- package/dist/assets/{MaskShapeCanvas-B-Co3EcK.js → MaskShapeCanvas-CzHUGkc7.js} +1 -1
- package/dist/assets/{MotionZonesSettings-rYNi0IyL.js → MotionZonesSettings-sCDWBSMu.js} +1 -1
- package/dist/assets/{MyAccess-DqlunIKb.js → MyAccess-_FlzEnLb.js} +1 -1
- package/dist/assets/{Network-rDYYtzyq.js → Network-U-uppn3V.js} +1 -1
- package/dist/assets/{NodeAddonsSettingsPanel-mj1x8pib.js → NodeAddonsSettingsPanel-DOuw1uWS.js} +1 -1
- package/dist/assets/Notifications-AkbB0Ya7.js +1 -0
- package/dist/assets/Pipeline-CMwJb0kX.js +1 -0
- package/dist/assets/{PrivacyMaskSettings-B_ZOhHsa.js → PrivacyMaskSettings-DH3PZaEy.js} +1 -1
- package/dist/assets/{Recordings-CHeLoIRU.js → Recordings-BJVAQK7Q.js} +1 -1
- package/dist/assets/{ScanNetworkModal-DDNyXnXJ.js → ScanNetworkModal-qjbQd1Q4.js} +1 -1
- package/dist/assets/{SceneMonitorEditor-CyHwjdzH.js → SceneMonitorEditor-CLWf6Z9-.js} +1 -1
- package/dist/assets/{SessionsList-B27Ne5e_.js → SessionsList-DSaSTSfg.js} +1 -1
- package/dist/assets/{Showroom-CxOhuFLC.js → Showroom-yf_2TnT8.js} +1 -1
- package/dist/assets/{System-T0PZXCE1.js → System-BKoiOnT6.js} +1 -1
- package/dist/assets/{Terminal-BA3WpGbf.js → Terminal-CGMRAh-D.js} +1 -1
- package/dist/assets/{Viewer-BIZ2-AWC.js → Viewer-CTvuCeo6.js} +1 -1
- package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-XyNfp-21.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-DAW63rZZ.js} +1 -1
- package/dist/assets/{addon-icons-context-IF2bAKB7.js → addon-icons-context-Bzdujcmt.js} +1 -1
- package/dist/assets/{archive-DwK992kq.js → archive-dvL2Bchb.js} +1 -1
- package/dist/assets/{assignment-candidates-BfYuVkll.js → assignment-candidates-Zc8Nwi6m.js} +1 -1
- package/dist/assets/{authed-media-2wArFI8C.js → authed-media-B6hJJcft.js} +1 -1
- package/dist/assets/{bell-off-BT9N_y5z.js → bell-off-C3flB_OF.js} +1 -1
- package/dist/assets/{board-model-C79CsHea.js → board-model-h3RS4HY8.js} +1 -1
- package/dist/assets/{boxes-Brm6PKBJ.js → boxes-BiMbpzNh.js} +1 -1
- package/dist/assets/chart-column-BMpUb2lF.js +1 -0
- package/dist/assets/circle-slash-B8Tjloe5.js +1 -0
- package/dist/assets/client-Ct1F5MoE.js +358 -0
- package/dist/assets/{cloud-upload-BWBb35pQ.js → cloud-upload-CAJgV_u1.js} +1 -1
- package/dist/assets/crop-CS-td_0y.js +1 -0
- package/dist/assets/{device-integration-icon-CfmyHq1L.js → device-integration-icon-DukkUZAm.js} +1 -1
- package/dist/assets/device-picker-model-P-UzQOB7.js +1 -0
- package/dist/assets/dist-B89wGMMB.js +358 -0
- package/dist/assets/{dist-v4PTiFhI.js → dist-CPp8d_RN.js} +1 -1
- package/dist/assets/{eraser-DOQYm-bd.js → eraser-BL6nSeLQ.js} +1 -1
- package/dist/assets/{format-DZdW_-La.js → format-ChtZgmyh.js} +1 -1
- package/dist/assets/{hard-drive-download-BomHKdQ6.js → hard-drive-download-ysGKYLwW.js} +1 -1
- package/dist/assets/{hostInit-Y3_WOWpF.js → hostInit-CDPK_pyj.js} +1 -1
- package/dist/assets/i18n-DJ4egBMY.js +1 -0
- package/dist/assets/icons-B7uNvSe0.js +1 -0
- package/dist/assets/index-hKEeWkm1.js +4 -0
- package/dist/assets/{key-round-HMiyn866.js → key-round-BDT5O9Ed.js} +1 -1
- package/dist/assets/{key-BjcxiZfv.js → key-xS-HUgNI.js} +1 -1
- package/dist/assets/{layers-71beSjbX.js → layers-BeRWYCde.js} +1 -1
- package/dist/assets/{linked-devices-model-CGjAZM4f.js → linked-devices-model-DOZONZiM.js} +1 -1
- package/dist/assets/{list-ordered-B00NsDtF.js → list-ordered-DKzGLPr6.js} +1 -1
- package/dist/assets/{location-owned-usage-C-GlyOpT.js → location-owned-usage-BxmUSyXj.js} +1 -1
- package/dist/assets/{log-in-CqClOuyv.js → log-in-53JDrQ-P.js} +1 -1
- package/dist/assets/{memory-stick-GbtuW7Ii.js → memory-stick-B9PVELyF.js} +1 -1
- package/dist/assets/{message-square-plus-BCFV5CXr.js → message-square-plus-B32IU45x.js} +1 -1
- package/dist/assets/{mf-entry-bootstrap-0-426ce71a.js → mf-entry-bootstrap-0-65d35510.js} +2 -2
- package/dist/assets/{mic-off-COk2FYD5.js → mic-off-B0w-1GrV.js} +1 -1
- package/dist/assets/{monitor-off-nojFqJI5.js → monitor-off-Cz2SxBVE.js} +1 -1
- package/dist/assets/{monitor-smartphone-BuxgqmtR.js → monitor-smartphone-Cqk6Z8Hg.js} +1 -1
- package/dist/assets/mount-P-UzQOB7.js +1 -0
- package/dist/assets/{player-overlays-BoPcGTkt.js → player-overlays-Cs6l33cj.js} +1 -1
- package/dist/assets/{recycle-Cbhp7tZj.js → recycle-DpB4QxbX.js} +1 -1
- package/dist/assets/remoteEntry-BGbchE1L.js +1 -0
- package/dist/assets/{scan-eye-COINNEut.js → scan-eye-DcYrgFOu.js} +1 -1
- package/dist/assets/{scissors-CU5rKPA8.js → scissors-_j_D3ONm.js} +1 -1
- package/dist/assets/{search-x-BEiDgxD-.js → search-x-9dPd-b95.js} +1 -1
- package/dist/assets/{send-CNx75CN6.js → send-D42ODbS7.js} +1 -1
- package/dist/assets/{settings-2-yfTMebsz.js → settings-2-zgGmo4c8.js} +1 -1
- package/dist/assets/{speaker-DzqHMf19.js → speaker-DIPHxIQ6.js} +1 -1
- package/dist/assets/src-DFzrn-CX.js +67 -0
- package/dist/assets/{step-inspector-model-BPPs6HSK.js → step-inspector-model-CS79liRv.js} +1 -1
- package/dist/assets/{table-2-CysTnRKy.js → table-2-lftK0wHb.js} +1 -1
- package/dist/assets/{timer-reset-BgIXd7hf.js → timer-reset-catAE_r9.js} +1 -1
- package/dist/assets/{ungroup-fAQCZXka.js → ungroup-BKImeHER.js} +1 -1
- package/dist/assets/{unlink-DSg9bFwt.js → unlink-Behl018w.js} +1 -1
- package/dist/assets/{usb-D-DRV1uf.js → usb-D5kzB8kq.js} +1 -1
- package/dist/assets/{use-scenes-feed-DO_UdVPf.js → use-scenes-feed-CGDnep25.js} +1 -1
- package/dist/assets/{use-stationary-objects-BXlbjYsd.js → use-stationary-objects-D_R5OahX.js} +1 -1
- package/dist/assets/useEventInvalidation-P-UzQOB7.js +1 -0
- package/dist/assets/{useNodeUrlSelection-BtOB6Z9m.js → useNodeUrlSelection-PBAYjRo5.js} +1 -1
- package/dist/assets/user-round-BJVl6LX9.js +1 -0
- package/dist/assets/{user-x-CPWIU9qV.js → user-x-COQ6vhb4.js} +1 -1
- package/dist/assets/{video-BM3o6nmQ.js → video-Byw3ItoR.js} +1 -1
- package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-Bw4dQyg1.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-CsFmgfi4.js} +2 -2
- package/dist/index.html +9 -9
- package/dist/server/addon.js +169 -29
- package/package.json +1 -1
- package/dist/assets/AiProfiles-CaJWaXuB.js +0 -3
- package/dist/assets/Build-Cq96yUoY.js +0 -40
- package/dist/assets/DeviceDetail-CIT2D5yf.js +0 -2
- package/dist/assets/HelperWizard-DS_R_NlR.js +0 -2
- package/dist/assets/Identity-CuazTQNS.js +0 -1
- package/dist/assets/Notifications-RMkYxLsU.js +0 -1
- package/dist/assets/Pipeline-DeamCmUq.js +0 -1
- package/dist/assets/circle-slash-DbVS3C3N.js +0 -1
- package/dist/assets/client-xX9FBBul.js +0 -358
- package/dist/assets/crop-Cwf2hMEp.js +0 -1
- package/dist/assets/device-picker-model-BqREn4Hm.js +0 -1
- package/dist/assets/dist-BBQqVqgg.js +0 -358
- package/dist/assets/i18n-B_TdOOX_.js +0 -1
- package/dist/assets/icons-GyTqKSGv.js +0 -1
- package/dist/assets/index-Df_Bqvin.js +0 -4
- package/dist/assets/mount-BqREn4Hm.js +0 -1
- package/dist/assets/remoteEntry-C1jeRZii.js +0 -1
- package/dist/assets/src-B9Sp1iss.js +0 -67
- package/dist/assets/useEventInvalidation-BqREn4Hm.js +0 -1
- package/dist/assets/user-round-DKD1XSci.js +0 -1
|
@@ -1,40 +0,0 @@
|
|
|
1
|
-
import{C as e,E as t,J as n,K as r,P as i,R as a,S as o,V as s,Y as c,a as l,et as u,t as d,x as f}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{An as p,In as m,Ji as h,Lt as g,Pt as _,Qi as v,Si as y,Tr as b,bi as x,ca as S,jn as C,mi as w,mn as T,ot as E,pt as D,sr as O,yn as k}from"./player-overlays-BoPcGTkt.js";import{Ai as A,Ca as j,Hi as M,Mi as N,Ni as P,Ra as F,Vi as I,bi as L,dn as R,ei as z,gi as B,ji as V,ki as H,ni as ee,pi as te,ri as ne,ui as re,xi as ie}from"./client-xX9FBBul.js";import{t as U}from"./boxes-Brm6PKBJ.js";import{n as ae,r as oe,t as se}from"./ungroup-fAQCZXka.js";import{s as ce}from"./video-BM3o6nmQ.js";import{Ba as le,Cn as ue,Do as de,Er as W,Lr as fe,Na as pe,Pa as me,Pr as he,Qr as ge,Qt as _e,Ra as ve,Sd as ye,So as be,Uo as xe,Va as Se,Wn as Ce,_n as we,cd as Te,ei as G,ht as Ee,id as K,in as De,ja as Oe,ld as q,od as ke,pt as Ae,qt as je,sd as Me,si as J,tn as Ne,vo as Pe,wd as Fe,wn as Ie,xr as Le,yt as Re,za as ze}from"./src-B9Sp1iss.js";import{t as Y}from"./i18n-B_TdOOX_.js";import{t as X}from"./useTranslation-BJr-n0es.js";import{P as Be,S as Ve,ar as He,h as Ue,hr as We,lr as Z,m as Ge,pr as Ke,ur as qe}from"./index-Df_Bqvin.js";import{t as Je}from"./AdminSectionedPage-Dm8ND20L.js";import{t as Ye}from"./DeviceDoActionFields-CP-EliT2.js";import{B as Xe,p as Ze,t as Qe,u as $e}from"./HelperWizard-DS_R_NlR.js";import{t as et}from"./CompositionBlockEditor-BxkWKOxd.js";var tt=`const AUTOMATION_RECIPE =`,nt=`// EJECTED from the visual automation editor — this file is now hand-owned.
|
|
2
|
-
// The recipe that produced it was removed with it, on purpose: while it was
|
|
3
|
-
// here the editor could re-open this block and overwrite everything below.`;function rt(e){return e.includes(tt)}function it(e){let t=e.indexOf(tt);if(t<0)return null;let n=e.indexOf(`{`,t+25);if(n<0)return null;let r=0,i=!1,a=!1;for(let o=n;o<e.length;o+=1){let s=e.charAt(o);if(i){a?a=!1:s===`\\`?a=!0:s===`"`&&(i=!1);continue}if(s===`"`){i=!0;continue}if(s===`{`)r+=1;else if(s===`}`&&(--r,r===0))return{declStart:t,literalEnd:o+1,json:e.slice(n,o+1)}}return null}function at(e){let t=it(e);if(t===null)return{ok:!1,reason:Y.t(`helpers.recipeFromCode.noLiteral`)};let n;try{n=JSON.parse(t.json)}catch(e){let t=e instanceof Error?e.message:String(e);return{ok:!1,reason:Y.t(`helpers.recipeFromCode.badJson`,{detail:t})}}let r=A.safeParse(n);if(!r.success){let e=r.error.issues[0];return{ok:!1,reason:e===void 0?Y.t(`helpers.recipeFromCode.schemaMismatch`):Y.t(`helpers.recipeFromCode.schemaMismatchAt`,{path:e.path.join(`.`),message:e.message})}}return{ok:!0,recipe:r.data}}function ot(e){let t=it(e);if(t===null)return e;let n=e.slice(t.literalEnd),r=/^\s*as\s+const/.exec(n),i=t.literalEnd+(r===null?0:r[0].length);return`${e.slice(0,t.declStart)}${nt}${e.slice(i)}`}u();var st=6e4;function ct(){let e=be({projection:`slim`});return r(()=>(e.data??[]).filter(e=>R(String(e.type))).map(e=>({id:e.id,name:e.name,stableId:e.stableId,type:String(e.type),location:e.location??null})).toSorted((e,t)=>e.name.localeCompare(t.name)),[e.data])}function lt(e){let t=E();return l({queryKey:[`automation`,`wireable-fields`,e],enabled:e>0,staleTime:st,queryFn:async()=>(await t.trpcClient.deviceManager.getWireableFields.query({deviceId:e})).caps})}function ut(e,t){return e.find(e=>e.cap===t)?.fields??[]}function Q({children:e}){return o(`span`,{className:`mb-1 block text-xs text-foreground-subtle`,children:e})}function dt(e){let t=lt(e.deviceId);if(t.data!==void 0)return ut(t.data,e.cap).find(t=>t.path===e.fieldPath)}function ft({value:t,devices:n,onChange:r}){let{t:i}=X(),a=lt(t.deviceId),s=a.data??[],c=ut(s,t.cap);return e(f,{children:[e(`label`,{className:`min-w-[10rem] flex-1`,children:[o(Q,{children:i(`automation.fieldPicker.device`,`Device`)}),o(K,{value:String(t.deviceId),onChange:e=>r({deviceId:Number(e.target.value),cap:``,fieldPath:``}),options:[{value:`0`,label:i(`automation.fieldPicker.selectADevice`,`Select a device…`)},...n.map(e=>({value:String(e.id),label:e.name}))]})]}),e(`label`,{className:`min-w-[9rem] flex-1`,children:[o(Q,{children:i(`automation.fieldPicker.capability`,`Capability`)}),o(K,{value:t.cap,disabled:t.deviceId===0,onChange:e=>r({...t,cap:e.target.value,fieldPath:``}),options:[{value:``,label:pt(t.deviceId,s.length,a.isLoading)},...s.map(e=>({value:e.cap,label:e.cap}))]})]}),e(`label`,{className:`min-w-[9rem] flex-1`,children:[o(Q,{children:i(`automation.fieldPicker.field`,`Field`)}),o(K,{value:t.fieldPath,disabled:t.cap===``,onChange:e=>r({...t,fieldPath:e.target.value}),options:[{value:``,label:c.length===0?i(`automation.fieldPicker.noReadableFields`,`No readable fields`):i(`automation.fieldPicker.selectAField`,`Select a field…`)},...c.map(e=>({value:e.path,label:`${e.path} (${e.kind})`}))]})]})]})}function pt(e,t,n){return e===0?Y.t(`automation.fieldPicker.pickDeviceFirst`):n?Y.t(`automation.fieldPicker.readingDevice`):t===0?Y.t(`automation.fieldPicker.noReadableCaps`):Y.t(`automation.fieldPicker.selectCap`)}var mt=[`eq`,`ne`,`gt`,`gte`,`lt`,`lte`,`contains`,`in`];function ht(e){switch(e){case`boolean`:return[`eq`,`ne`];case`number`:return[`eq`,`ne`,`gt`,`gte`,`lt`,`lte`];case`string`:case`enum`:return[`eq`,`ne`,`contains`,`in`];default:return mt}}function gt(e){switch(e){case`eq`:return Y.t(`helpers.recipeParts.op_eq`);case`ne`:return Y.t(`helpers.recipeParts.op_ne`);case`gt`:return Y.t(`helpers.recipeParts.op_gt`);case`gte`:return Y.t(`helpers.recipeParts.op_gte`);case`lt`:return Y.t(`helpers.recipeParts.op_lt`);case`lte`:return Y.t(`helpers.recipeParts.op_lte`);case`contains`:return Y.t(`helpers.recipeParts.op_contains`);default:return Y.t(`helpers.recipeParts.op_in`)}}function _t(e){return ht(e).map(e=>({value:e,label:gt(e)}))}function vt(e){switch(e){case`device-state`:return Y.t(`helpers.recipeParts.trigger_device_state`);case`device-event`:return Y.t(`helpers.recipeParts.trigger_device_event`);case`schedule`:return Y.t(`helpers.recipeParts.trigger_schedule`);default:return Y.t(`helpers.recipeParts.trigger_manual`)}}var yt={triggers:[],actions:[]};function bt(e){switch(e){case`device-state`:return{kind:e,deviceId:0,cap:``,fieldPath:``};case`device-event`:return{kind:e,category:``};case`schedule`:return{kind:e,cron:`0 30 23 * * *`};default:return{kind:`manual`}}}function xt(e){switch(e){case`wait`:return{kind:e,seconds:5};case`code`:return{kind:e,code:`// runs inside this automation, with ctx in scope
|
|
4
|
-
`};default:return{kind:`cap`,deviceId:0,cap:``,method:``}}}function St(){return{kind:`condition`,deviceId:0,cap:``,fieldPath:``,operator:`eq`,value:``}}function Ct(){return{kind:`expression`,expr:``,bindings:{}}}function wt(e,t,n){return e.map((e,r)=>r===t?n:e)}function Tt(e,t){return e.filter((e,n)=>n!==t)}function Et(e,t,n){let r=e[t];if(r===void 0)return e;let i=Math.min(Math.max(n,0),e.length-1);if(i===t)return e;let a=Tt(e,t);return[...a.slice(0,i),r,...a.slice(i)]}function Dt(e,t){return{...e,triggers:[...t]}}function Ot(e,t){return{...e,actions:[...t]}}var kt=[{value:`cap`,labelKey:`automation.actionList.kindCap`},{value:`wait`,labelKey:`automation.actionList.kindWait`},{value:`code`,labelKey:`automation.actionList.kindCode`}];function At({actions:t,devices:n,devicesState:r=`answered`,onChange:i}){let{t:a}=X();return e(`div`,{className:`space-y-2`,children:[t.length===0&&o(`p`,{className:`text-xs text-warning`,children:a(`automation.actionList.noActionsYetAnAutomation`,`No actions yet. An automation that does nothing is not an automation.`)}),t.map((s,c)=>e(`div`,{className:`rounded border border-border p-3 space-y-2`,children:[e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[o(J,{variant:`default`,children:c+1}),e(`label`,{className:`w-40`,children:[o(Q,{children:a(`automation.actionList.step`,`Step`)}),o(K,{value:s.kind,onChange:e=>i(wt(t,c,xt(jt(e.target.value)))),options:kt.map(e=>({value:e.value,label:a(e.labelKey)}))})]}),e(`div`,{className:`ml-auto flex items-center gap-1`,children:[o(G,{variant:`ghost`,disabled:c===0,onClick:()=>i(Et(t,c,c-1)),title:a(`automation.actionList.runThisStepEarlier`,`Run this step earlier`),children:o(h,{className:`h-3.5 w-3.5`})}),o(G,{variant:`ghost`,disabled:c===t.length-1,onClick:()=>i(Et(t,c,c+1)),title:a(`automation.actionList.runThisStepLater`,`Run this step later`),children:o(v,{className:`h-3.5 w-3.5`})}),o(G,{variant:`ghost`,onClick:()=>i(Tt(t,c)),title:a(`automation.actionList.removeThisStep`,`Remove this step`),children:o(g,{className:`h-3.5 w-3.5`})})]})]}),s.kind===`wait`&&e(`label`,{className:`block w-32`,children:[o(Q,{children:a(`automation.actionList.seconds`,`Seconds`)}),o(q,{type:`number`,min:0,max:300,value:String(s.seconds),onChange:e=>i(wt(t,c,{kind:`wait`,seconds:Number(e.target.value)}))})]}),s.kind===`code`&&e(`label`,{className:`block`,children:[o(Q,{children:a(`automation.actionList.code`,`Code`)}),o(`textarea`,{className:`h-32 w-full rounded-md border border-border bg-surface p-2 font-mono text-xs text-foreground focus:outline-none focus:ring-1 focus:ring-primary`,value:s.code,spellCheck:!1,onChange:e=>i(wt(t,c,{kind:`code`,code:e.target.value}))}),o(`span`,{className:`mt-1 block text-xs text-foreground-subtle`,children:o(Z,{i18nKey:`automation.actionList.codeHint`,components:{code:o(`code`,{})}})})]}),s.kind===`cap`&&o(Nt,{action:s,devices:n,devicesState:r,onChange:e=>i(wt(t,c,e))})]},`${s.kind}-${String(c)}`)),e(`div`,{className:`flex items-center gap-2`,children:[e(G,{variant:`outline`,onClick:()=>i([...t,xt(`cap`)]),children:[o(p,{className:`h-4 w-4`}),` `,a(`automation.actionList.addStep`)]}),t.length>1&&o(`span`,{className:`text-xs text-foreground-subtle`,children:a(`automation.actionList.stepsRunInOrderAnd`,`Steps run in order and stop at the first failure.`)})]})]})}function jt(e){return kt.find(t=>t.value===e)?.value??`cap`}function Mt(e){return typeof e==`number`?e:typeof e==`object`&&e&&`$var`in e?{$var:e.$var}:[...e]}function Nt({action:e,devices:t,devicesState:n,onChange:r}){return o(Ye,{value:e,allowTriggerDevice:!0,allowMultiSameFamily:!0,devices:t,listState:n,onChange:e=>r({kind:`cap`,deviceId:Mt(e.deviceId),cap:e.cap,method:e.method,...e.args===void 0?{}:{args:{...e.args}}})})}function Pt({value:t,field:n,deviceId:r,cap:i,onChange:a}){let{t:s}=X(),c=Bt(n,r,i);if(n?.kind===`boolean`)return o(K,{value:t===!0?`true`:`false`,onChange:e=>a(e.target.value===`true`),options:[{value:`true`,label:s(`common.true`)},{value:`false`,label:s(`common.false`)}]});if(n?.kind===`enum`&&n.enumValues!==void 0&&n.enumValues.length>0)return o(K,{value:String(t),onChange:e=>a(e.target.value),options:n.enumValues.map(e=>({value:e,label:e}))});if(n?.kind===`number`){let n=typeof t==`number`&&c?c.toDisplayValue(t):t;return e(`span`,{className:`inline-flex items-center gap-1`,children:[o(q,{type:`number`,value:typeof n==`number`?String(n):``,placeholder:`0`,onChange:e=>{let t=Number(e.target.value);e.target.value!==``&&!Number.isNaN(t)&&a(c?c.fromDisplayValue(t):t)}}),c!==void 0&&c.unit.length>0?o(`span`,{className:`text-xs text-foreground-subtle`,children:c.unit}):null]})}return o(q,{value:String(t),placeholder:s(`common.valueWord`),onChange:e=>a(e.target.value)})}function Ft({value:e,field:t,deviceId:n,cap:r,onChange:i}){let{t:a}=X(),s=Bt(t,n,r);return o(q,{value:(s?e.map(e=>typeof e==`number`?s.toDisplayValue(e):e):e).join(`, `),placeholder:a(`automation.valueInput.oneTwoThree`,`one, two, three`),onChange:e=>{let n=e.target.value.split(`,`).map(e=>e.trim()).filter(e=>e!==``);i(t?.kind===`number`?n.map(e=>Number(e)).filter(e=>!Number.isNaN(e)).map(e=>s?s.fromDisplayValue(e):e):n)}})}function It(e){return typeof e==`object`}function Lt(e){return It(e)?e[0]??``:e}function Rt(e){return It(e)?e:typeof e==`boolean`?[]:[e]}function zt(e,t){if(!(e===void 0||e===`none`)){if(e!==`device`)return e;if(!(t===void 0||t===`device`||t===`none`))return t}}function Bt(e,t,n){let r=t??0,i=e?.kind===`number`&&e.quantity!==void 0,{data:a}=Pe({deviceId:r},{enabled:i&&r>0}),o=a?.sourceInfo?.quantity,s=j(o)?o:void 0,c=zt(e?.quantity,s);if(c===void 0)return;let l=a?.display;return _e({quantity:c,display:l,capName:n})}function Vt({leaf:t,devices:n,onChange:r}){let{t:i}=X(),a={deviceId:t.deviceId,cap:t.cap,fieldPath:t.fieldPath},s=dt(a),c=_t(s?.kind),l=t.operator===`in`,u=e=>{r({...t,deviceId:e.deviceId,cap:e.cap,fieldPath:e.fieldPath})},d=e=>{let n=Ht(e,c);r({...t,operator:n,value:n===`in`?Rt(t.value):Lt(t.value)})};return e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[o(ft,{value:a,devices:n,onChange:u}),e(`label`,{className:`min-w-[8rem]`,children:[o(Q,{children:i(`automation.conditionRow.comparison`,`Comparison`)}),o(K,{value:t.operator,onChange:e=>d(e.target.value),options:c.map(e=>({value:e.value,label:e.label}))})]}),e(`label`,{className:`min-w-[9rem] flex-1`,children:[o(Q,{children:i(`automation.conditionRow.value`,`Value`)}),l?o(Ft,{value:Rt(t.value),field:s,deviceId:t.deviceId,cap:t.cap,onChange:e=>r({...t,value:e})}):o(Pt,{value:Lt(t.value),field:s,deviceId:t.deviceId,cap:t.cap,onChange:e=>r({...t,value:e})})]})]})}function Ht(e,t){return t.find(t=>t.value===e)?.value??`eq`}var Ut={kind:`global`,sourceStableId:``,cap:``,fieldPath:``};function Wt({leaf:t,devices:n,onChange:r}){let{t:i}=X(),a=Object.entries(t.bindings),s=e=>{r({kind:`expression`,expr:t.expr,bindings:e})};return e(`div`,{className:`space-y-2`,children:[e(`label`,{className:`block`,children:[o(Q,{children:i(`automation.expressionLeafRow.expression`,`Expression`)}),o(q,{value:t.expr,placeholder:i(`automation.expressionLeafRow.indoorOutdoor5`,`indoor - outdoor > 5`),onChange:e=>r({kind:`expression`,expr:e.target.value,bindings:t.bindings})}),o(`span`,{className:`mt-1 block text-xs text-foreground-subtle`,children:i(`automation.expressionLeafRow.mustEvaluateToTrueOr`,`Must evaluate to true or false. Every name in it has to be bound below — an unbound name is refused when the automation is saved, not when it runs.`)})]}),e(`div`,{className:`space-y-1.5`,children:[a.length===0&&o(`p`,{className:`text-xs text-foreground-subtle`,children:i(`automation.expressionLeafRow.noNamesBoundYetAn`,`No names bound yet. An expression reads devices only through these.`)}),a.map(([e,r])=>o(Gt,{alias:e,source:r,devices:n,onRename:n=>s(Zt(t.bindings,e,n)),onChange:n=>s({...t.bindings,[e]:n}),onRemove:()=>s(Qt(t.bindings,e))},e)),e(G,{variant:`ghost`,onClick:()=>s({...t.bindings,[Xt(t.bindings)]:Ut}),children:[o(p,{className:`h-3.5 w-3.5`}),` `,i(`common.name`)]})]})]})}function Gt({alias:t,source:n,devices:r,onRename:i,onChange:a,onRemove:s}){let{t:c}=X(),l=n.kind===`literal`,u=l?{deviceId:0,cap:``,fieldPath:``}:{deviceId:Jt(r,qt(n)),cap:n.cap,fieldPath:n.fieldPath};return e(`div`,{className:`flex flex-wrap items-end gap-2 rounded border border-border p-2`,children:[e(`label`,{className:`w-32`,children:[o(Q,{children:c(`automation.expressionLeafRow.name`,`Name`)}),o(q,{value:t,placeholder:c(`automation.expressionLeafRow.aliasExample`),onChange:e=>i(e.target.value)})]}),e(`label`,{className:`w-36`,children:[o(Q,{children:c(`automation.expressionLeafRow.reads`,`Reads`)}),o(K,{value:l?`literal`:`global`,onChange:e=>a(e.target.value===`literal`?{kind:`literal`,value:``}:Ut),options:[{value:`global`,label:c(`automation.expressionLeafRow.aDeviceField`,`A device field`)},{value:`literal`,label:c(`automation.expressionLeafRow.aConstant`,`A constant`)}]})]}),l?e(`label`,{className:`min-w-[9rem] flex-1`,children:[o(Q,{children:c(`automation.expressionLeafRow.constant`,`Constant`)}),o(q,{value:n.value===null?``:String(n.value),placeholder:`5`,onChange:e=>a({kind:`literal`,value:Kt(e.target.value)})})]}):o(ft,{value:u,devices:r,onChange:e=>a({kind:`global`,sourceStableId:Yt(r,e.deviceId),cap:e.cap,fieldPath:e.fieldPath})}),o(G,{variant:`ghost`,onClick:s,title:c(`automation.expressionLeafRow.removeThisName`,`Remove this name`),children:o(g,{className:`h-3.5 w-3.5`})})]})}function Kt(e){let t=e.trim();return t===`true`?!0:t===`false`?!1:t!==``&&!Number.isNaN(Number(t))?Number(t):e}function qt(e){return e.kind===`global`?e.sourceStableId:``}function Jt(e,t){return e.find(e=>e.stableId===t)?.id??0}function Yt(e,t){return e.find(e=>e.id===t)?.stableId??``}function Xt(e){for(let t=0;t<26;t+=1){let n=String.fromCharCode(97+t);if(!(n in e))return n}return`n${String(Object.keys(e).length)}`}function Zt(e,t,n){let r={};for(let[i,a]of Object.entries(e))i===t?r[n]=a:r[i]=a;return r}function Qt(e,t){let n={};for(let[r,i]of Object.entries(e))r!==t&&(n[r]=i);return n}function $t(e){return e.kind===`all`||e.kind===`any`}function en(e){let t=e.conditions;return t===void 0?{kind:`all`,children:[]}:$t(t)?t:{kind:`all`,children:[t]}}function tn(e,t){return t===null||$t(t)&&t.children.length===0?{triggers:e.triggers,actions:e.actions}:{triggers:e.triggers,actions:e.actions,conditions:t}}function nn(e){return tn(e,en(e))}function rn(e,t){if(t.length===0)return e;let[n,...r]=t;if(n===void 0)return e;if(e.kind===`not`)return n===0?rn(e.child,r):null;if(!$t(e))return null;let i=e.children[n];return i===void 0?null:rn(i,r)}function an(e,t,n){if(t.length===0)return n(e);let[r,...i]=t;if(r===void 0)return n(e);if(e.kind===`not`){if(r!==0)return e;let t=an(e.child,i,n);return t===null?null:{kind:`not`,child:t}}if(!$t(e))return e;let a=e.children[r];if(a===void 0)return e;let o=an(a,i,n),s=o===null?[...e.children.slice(0,r),...e.children.slice(r+1)]:[...e.children.slice(0,r),o,...e.children.slice(r+1)];return s.length===0?null:{kind:e.kind,children:s}}function on(e){return e===null?null:P({triggers:[{kind:`manual`}],actions:[{kind:`wait`,seconds:0}],conditions:e})}function sn(e){let t=en(e);return{depth:t.children.length===0?0:V(t),leaves:t.children.length===0?0:N(t),depthLimit:3,leafLimit:32}}function cn(e,t){let n=on(t);return n===null?{ok:!0,recipe:tn(e,t)}:{ok:!1,reason:n}}function ln(e,t){let n=en(e);return cn(e,{kind:n.kind,children:[...n.children,t]})}function un(e,t,n){return tn(e,an(en(e),t,()=>n))}function dn(e,t){return tn(e,an(en(e),t,()=>null))}function fn(e,t,n){return tn(e,an(en(e),t,e=>$t(e)?{kind:n,children:e.children}:e))}function pn(e,t){return rn(en(e),t)===null?{ok:!1,reason:Y.t(`helpers.recipeOps.rowGone`)}:cn(e,an(en(e),t,e=>e.kind===`not`?e.child:{kind:`not`,child:e}))}function mn(e){if(e.length===0)return null;let t=e[e.length-1];return t===void 0?null:{path:e.slice(0,-1),index:t}}function hn(e,t,n){if(t.length<2)return{ok:!1,reason:Y.t(`helpers.recipeOps.selectTwo`)};if(new Set(t.map(e=>e.slice(0,-1).join(`/`))).size!==1)return{ok:!1,reason:Y.t(`helpers.recipeOps.differentGroups`)};let r=mn(t[0]??[]);if(r===null)return{ok:!1,reason:Y.t(`helpers.recipeOps.rootGroup`)};let i=en(e),a=rn(i,r.path);if(a===null||!$t(a))return{ok:!1,reason:Y.t(`helpers.recipeOps.insideNot`)};let o=[...t.map(e=>e[e.length-1]??-1)].sort((e,t)=>e-t),s=o.map(e=>a.children[e]).filter(e=>e!==void 0);if(s.length!==o.length)return{ok:!1,reason:Y.t(`helpers.recipeOps.selectedGone`)};let c=a.children.filter((e,t)=>!o.includes(t)),l=o[0]??0,u={kind:n,children:s},d={kind:a.kind,children:[...c.slice(0,l),u,...c.slice(l)]};return cn(e,an(i,r.path,()=>d))}function gn(e,t){if(t.length===0)return{ok:!1,reason:Y.t(`helpers.recipeOps.outerNotGroup`)};let n=en(e),r=rn(n,t);if(r===null)return{ok:!1,reason:Y.t(`helpers.recipeOps.groupGone`)};if(r.kind===`not`)return cn(e,an(n,t,()=>r.child));if(!$t(r))return{ok:!1,reason:Y.t(`helpers.recipeOps.rowIsCondition`)};let i=mn(t);if(i===null)return{ok:!1,reason:Y.t(`helpers.recipeOps.noParent`)};let a=rn(n,i.path);if(a===null||!$t(a))return{ok:!1,reason:Y.t(`helpers.recipeOps.groupInNot`)};let o={kind:a.kind,children:[...a.children.slice(0,i.index),...r.children,...a.children.slice(i.index+1)]};return cn(e,an(n,i.path,()=>o))}u();var _n=[{value:`all`,labelKey:`automation.conditionTree.allOf`},{value:`any`,labelKey:`automation.conditionTree.anyOf`}];function vn(e){return e.join(`/`)}function yn(e){return e===``?[]:e.split(`/`).map(e=>Number(e))}function bn({recipe:t,devices:n,onChange:i}){let{t:a}=X(),[s,l]=c([]),[u,d]=c(null),f=en(t),m=sn(t),h=r(()=>s.map(yn),[s]),g=e=>{if(!e.ok){d(e.reason);return}d(null),l([]),i(e.recipe)},_=hn(t,h,`all`),v=hn(t,h,`any`),y=h.length===1?pn(t,h[0]??[]):{ok:!1,reason:a(`automation.conditionTree.selectOneNegate`)},b={devices:n,selected:new Set(s),onToggleSelect:e=>l(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e]),onUpdate:(e,n)=>i(un(t,e,n)),onRemove:e=>{l([]),i(dn(t,e))},onSetKind:(e,n)=>i(fn(t,e,n)),onUngroup:e=>g(gn(t,e))};return e(`div`,{className:`space-y-2`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(J,{variant:`default`,children:a(`automation.conditionTree.andOnlyIf`,`And only if`)}),o(`div`,{className:`w-32`,children:o(K,{value:f.kind,onChange:e=>i(fn(t,[],xn(e.target.value))),options:_n.map(e=>({value:e.value,label:a(e.labelKey)}))})}),o(`span`,{className:`text-xs text-foreground-subtle`,children:a(`automation.conditionTree.budget`,{depth:m.depth,depthLimit:m.depthLimit,leaves:m.leaves,leafLimit:m.leafLimit})})]}),f.children.length===0?o(`p`,{className:`text-xs text-foreground-subtle`,children:a(`automation.conditionTree.noConditionsTheActionsRun`,`No conditions. The actions run every time a trigger fires.`)}):o(Sn,{container:f,path:[],handlers:b}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(G,{variant:`outline`,onClick:()=>g(ln(t,St())),title:a(`automation.conditionTree.compareOneDeviceFieldTo`,`Compare one device field to a value`),children:[o(p,{className:`h-4 w-4`}),` `,a(`automation.conditionTree.addCondition`)]}),e(G,{variant:`outline`,onClick:()=>g(ln(t,Ct())),title:a(`automation.conditionTree.arithmeticAcrossDeviceFieldsThe`,`Arithmetic across device fields — the bounded expression engine`),children:[o(oe,{className:`h-4 w-4`}),` `,a(`automation.conditionTree.addExpression`)]}),o(`span`,{className:`mx-1 h-5 w-px bg-border`}),o(G,{variant:`ghost`,disabled:!_.ok,onClick:()=>g(_),title:_.ok?a(`automation.conditionTree.allSelectedRowsMustBe`,`All selected rows must be true`):_.reason,children:a(`automation.conditionTree.groupAsAll`,`Group as ALL`)}),o(G,{variant:`ghost`,disabled:!v.ok,onClick:()=>g(v),title:v.ok?a(`automation.conditionTree.anyOneOfTheSelected`,`Any one of the selected rows is enough`):v.reason,children:a(`automation.conditionTree.groupAsAny`,`Group as ANY`)}),o(G,{variant:`ghost`,disabled:!y.ok,onClick:()=>g(y),title:y.ok?a(`automation.conditionTree.invertTheSelectedRow`,`Invert the selected row`):y.reason,children:`NOT`}),s.length>0&&o(`span`,{className:`text-xs text-foreground-subtle`,children:a(`common.selectedCount`,{count:s.length})})]}),u!==null&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-2 text-xs text-warning`,children:u})]})}function xn(e){return e===`any`?`any`:`all`}function Sn({container:e,path:t,handlers:n}){return o(`div`,{className:`space-y-1.5`,children:e.children.map((e,r)=>o(Cn,{node:e,path:[...t,r],handlers:n},vn([...t,r])))})}function Cn({node:t,path:n,handlers:r}){let{t:i}=X(),a=vn(n),s=o(Ce,{checked:r.selected.has(a),onChange:()=>r.onToggleSelect(a),"aria-label":i(`automation.conditionTree.selectThisRowForGrouping`,`Select this row for grouping`)});return $t(t)?e(`div`,{className:`rounded border border-border bg-surface-subtle/40 p-2`,children:[e(`div`,{className:`mb-1.5 flex flex-wrap items-center gap-2`,children:[s,o(`div`,{className:`w-32`,children:o(K,{value:t.kind,onChange:e=>r.onSetKind(n,xn(e.target.value)),options:_n.map(e=>({value:e.value,label:i(e.labelKey)}))})}),e(G,{variant:`ghost`,onClick:()=>r.onUngroup(n),title:i(`automation.conditionTree.dissolveThisGroupKeepingIts`,`Dissolve this group, keeping its rows`),children:[o(se,{className:`h-3.5 w-3.5`}),` `,i(`automation.conditionTree.ungroup`)]}),o(G,{variant:`ghost`,onClick:()=>r.onRemove(n),title:i(`automation.conditionTree.deleteThisGroupAndEverything`,`Delete this group and everything in it`),children:o(g,{className:`h-3.5 w-3.5`})})]}),o(`div`,{className:`pl-4`,children:o(Sn,{container:t,path:n,handlers:r})})]}):t.kind===`not`?e(`div`,{className:`rounded border border-border p-2`,children:[e(`div`,{className:`mb-1.5 flex flex-wrap items-center gap-2`,children:[s,o(J,{variant:`warning`,children:`NOT`}),e(G,{variant:`ghost`,onClick:()=>r.onUngroup(n),title:i(`automation.conditionTree.removeTheNotKeepingThe`,`Remove the NOT, keeping the row`),children:[o(se,{className:`h-3.5 w-3.5`}),` `,i(`automation.conditionTree.removeNot`)]})]}),o(`div`,{className:`pl-4`,children:o(Cn,{node:t.child,path:[...n,0],handlers:r})})]}):e(`div`,{className:`flex items-start gap-2 rounded border border-border p-2`,children:[o(`div`,{className:`pt-6`,children:s}),o(`div`,{className:`min-w-0 flex-1`,children:t.kind===`condition`?o(Vt,{leaf:t,devices:r.devices,onChange:e=>r.onUpdate(n,e)}):o(Wt,{leaf:t,devices:r.devices,onChange:e=>r.onUpdate(n,e)})}),o(G,{variant:`ghost`,onClick:()=>r.onRemove(n),title:i(`automation.conditionTree.removeThisCondition`,`Remove this condition`),children:o(g,{className:`h-3.5 w-3.5`})})]})}u();function wn({code:t,error:n,canEject:r,ejecting:i,onEject:a}){let{t:s}=X(),[l,u]=c(!1),d=ge(),f=async()=>{await d({title:s(`automation.generatedCodePanel.ejectToCodeThisCannot`,`Eject to code — this cannot be undone`),message:s(`automation.generatedCodePanel.theRecipeIsRemovedFrom`,`The recipe is removed from the block and it becomes an ordinary script. The visual editor will no longer open it, and there is no way back to it except authoring a new automation from scratch. The code itself is kept exactly as it is now.`),confirmLabel:s(`automation.generatedCodePanel.ejectToCode`,`Eject to code`),cancelLabel:s(`automation.generatedCodePanel.keepItVisual`,`Keep it visual`),variant:`warning`})&&a()};return e(`div`,{className:`rounded border border-border`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2 px-3 py-2`,children:[e(G,{variant:`ghost`,onClick:()=>u(!l),children:[o(l?y:x,{className:`h-4 w-4`}),s(`automation.generatedCodePanel.generatedCode`,`Generated code`)]}),o(`span`,{className:`text-xs text-foreground-subtle`,children:s(`automation.generatedCodePanel.derivedFromTheRecipeAbove`,`Derived from the recipe above — regenerated on every save, never edited here.`)}),e(G,{className:`ml-auto`,variant:`ghost`,disabled:!r||t===null||i,onClick:()=>void f(),title:r?s(`automation.generatedCodePanel.takePermanentOwnershipOfThis`,`Take permanent ownership of this code as a script`):s(`automation.generatedCodePanel.saveTheAutomationFirstThere`,`Save the automation first — there is no stored block to eject yet`),children:[o(ce,{className:`h-4 w-4`}),` `,s(`automation.generatedCodePanel.eject`)]})]}),l&&o(`div`,{className:`border-t border-border p-3`,children:t===null?o(`p`,{className:`text-xs text-warning`,children:n??s(`automation.generatedCodePanel.theRecipeIsNotComplete`,`The recipe is not complete enough to generate a block yet.`)}):o(we,{maxHeight:420,children:t})})]})}var Tn=[`device-state`,`device-event`,`schedule`,`manual`],En=Object.values(F).sort((e,t)=>e.localeCompare(t));function Dn({triggers:t,devices:n,onChange:r}){let{t:i}=X();return e(`div`,{className:`space-y-2`,children:[t.length===0&&o(`p`,{className:`text-xs text-warning`,children:i(`automation.triggerEditor.noTriggersYetWithoutOne`,`No triggers yet. Without one nothing can ever start this automation — not even "Run actions", which needs a manual trigger to have somewhere to arrive.`)}),t.map((e,i)=>o(On,{trigger:e,devices:n,position:i,onChange:e=>r(wt(t,i,e)),onRemove:()=>r(Tt(t,i))},`${e.kind}-${String(i)}`)),e(G,{variant:`outline`,onClick:()=>r([...t,bt(`device-state`)]),title:i(`automation.triggerEditor.addAnotherWayThisAutomation`,`Add another way this automation can start`),children:[o(p,{className:`h-4 w-4`}),` `,i(`automation.triggerEditor.trigger`)]})]})}function On({trigger:t,devices:n,position:r,onChange:i,onRemove:a}){let{t:s}=X();return e(`div`,{className:`rounded border border-border p-3`,children:[e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[o(J,{variant:`default`,children:r===0?s(`automation.triggerEditor.when`,`When`):s(`automation.triggerEditor.orWhen`,`or when`)}),e(`label`,{className:`min-w-[13rem] flex-1`,children:[o(Q,{children:s(`automation.triggerEditor.trigger`,`Trigger`)}),o(K,{value:t.kind,onChange:e=>i(bt(kn(e.target.value))),options:Tn.map(e=>({value:e,label:vt(e)}))})]}),o(G,{variant:`ghost`,onClick:a,title:s(`automation.triggerEditor.removeThisTrigger`,`Remove this trigger`),children:o(g,{className:`h-4 w-4`})})]}),e(`div`,{className:`mt-2 flex flex-wrap items-end gap-2`,children:[t.kind===`device-state`&&o(jn,{trigger:t,devices:n,onChange:i}),t.kind===`device-event`&&o(Nn,{trigger:t,devices:n,onChange:i}),t.kind===`schedule`&&e(`label`,{className:`min-w-[14rem] flex-1`,children:[o(Q,{children:s(`automation.triggerEditor.cronExpression`,`Cron expression`)}),o(q,{value:t.cron,placeholder:`0 30 23 * * *`,onChange:e=>i({kind:`schedule`,cron:e.target.value})}),o(`span`,{className:`mt-1 block text-xs text-foreground-subtle`,children:o(Z,{i18nKey:`automation.triggerEditor.cronHint`,components:{code:o(`code`,{})}})})]}),t.kind===`manual`&&o(`p`,{className:`text-xs text-foreground-subtle`,children:o(Z,{i18nKey:`automation.triggerEditor.manualHint`,components:{b:o(`strong`,{})}})})]})]})}function kn(e){return Tn.find(t=>t===e)??`manual`}function An(e,t){return{kind:`device-state`,deviceId:e.deviceId,cap:e.cap,fieldPath:e.fieldPath,...t.becomes===void 0?{}:{becomes:t.becomes},...t.edge===void 0?{}:{edge:t.edge},...t.forMs===void 0?{}:{forMs:t.forMs},...t.debounceMs===void 0?{}:{debounceMs:t.debounceMs}}}function jn({trigger:t,devices:n,onChange:r}){let{t:i}=X(),a={deviceId:t.deviceId,cap:t.cap,fieldPath:t.fieldPath},s=dt(a),c={...t.becomes===void 0?{}:{becomes:t.becomes},...t.edge===void 0?{}:{edge:t.edge},...t.forMs===void 0?{}:{forMs:t.forMs},...t.debounceMs===void 0?{}:{debounceMs:t.debounceMs}};return e(f,{children:[o(ft,{value:a,devices:n,onChange:e=>r(An(e,c))}),e(`div`,{className:`min-w-[11rem] flex-1`,children:[o(Q,{children:i(`automation.triggerEditor.becomes`,`Becomes`)}),e(`div`,{className:`flex items-center gap-2`,children:[e(`label`,{className:`flex items-center gap-1.5 text-xs text-foreground-subtle`,children:[o(Ce,{checked:t.becomes===void 0,onChange:e=>r(An(a,{...c,...e.target.checked?{becomes:void 0}:{becomes:``}}))}),i(`automation.triggerEditor.anyChange`,`any change`)]}),t.becomes!==void 0&&o(Pt,{value:t.becomes,field:s,deviceId:a.deviceId,cap:a.cap,onChange:e=>r(An(a,{...c,becomes:e}))})]})]}),e(`label`,{className:`flex items-center gap-1.5 text-xs text-foreground-subtle`,children:[o(Ce,{checked:t.edge===!0,onChange:e=>r(An(a,{...c,...e.target.checked?{edge:!0}:{edge:void 0}}))}),i(`automation.triggerEditor.onlyOnAChange`,`only on a change`)]}),e(`label`,{className:`w-28`,children:[o(Q,{children:i(`automation.triggerEditor.heldForS`,`Held for (s)`)}),o(q,{type:`number`,min:0,value:t.forMs===void 0?``:String(t.forMs/1e3),placeholder:`0`,onChange:e=>r(An(a,{...c,forMs:Mn(e.target.value)}))})]}),e(`label`,{className:`w-28`,children:[o(Q,{children:i(`automation.triggerEditor.debounceS`,`Debounce (s)`)}),o(q,{type:`number`,min:0,value:t.debounceMs===void 0?``:String(t.debounceMs/1e3),placeholder:`0`,onChange:e=>r(An(a,{...c,debounceMs:Mn(e.target.value)}))})]})]})}function Mn(e){if(e.trim()===``)return;let t=Number(e);if(!(Number.isNaN(t)||t<0))return Math.round(t*1e3)}function Nn({trigger:t,devices:n,onChange:r}){let{t:i}=X();return e(f,{children:[e(`label`,{className:`min-w-[15rem] flex-1`,children:[o(Q,{children:i(`automation.triggerEditor.eventCategory`,`Event category`)}),o(K,{value:t.category,onChange:e=>r({kind:`device-event`,category:e.target.value,...t.deviceId===void 0?{}:{deviceId:t.deviceId}}),options:[{value:``,label:i(`automation.triggerEditor.selectAnEvent`,`Select an event…`)},...En.map(e=>({value:e,label:e}))]})]}),e(`label`,{className:`min-w-[11rem] flex-1`,children:[o(Q,{children:i(`automation.triggerEditor.fromDevice`,`From device`)}),o(K,{value:t.deviceId===void 0?``:String(t.deviceId),onChange:e=>r({kind:`device-event`,category:t.category,...e.target.value===``?{}:{deviceId:Number(e.target.value)}}),options:[{value:``,label:i(`automation.triggerEditor.anyDevice`,`Any device`)},...n.map(e=>({value:String(e.id),label:e.name}))]})]})]})}u();var Pn=`hub`;function Fn({existing:t,initialRecipe:n,saving:i,saveError:a,ejecting:s,onSave:l,onEject:u,onCancel:d}){let{t:f}=X(),[p,m]=c(t?.name??``),[h,g]=c(()=>nn(n)),[_,v]=c(!1),y=ct(),b=P(h),x=r(()=>Ln(h),[h]),S=r(()=>Rn(p.trim()===``?`Untitled automation`:p.trim(),h),[p,h]),C=p.trim()===``,w=C||b!==null||x!==null||S.code===null;return e(`div`,{className:`space-y-4`,children:[o(`div`,{className:`flex flex-wrap items-center gap-2`,children:o(J,{variant:`info`,children:f(`automation.automationEditor.runsOnTheHub`,`runs on the hub`)})}),e(`label`,{className:`block max-w-md text-sm`,children:[o(`span`,{className:`text-foreground-subtle`,children:f(`automation.automationEditor.name`,`Name`)}),o(q,{className:`mt-1`,value:p,onChange:e=>m(e.target.value),placeholder:f(`automation.automationEditor.whatThisAutomationDoes`,`What this automation does`)})]}),o(In,{step:`1`,title:f(`automation.automationEditor.when`,`When`),subtitle:f(`automation.automationEditor.anyOneOfTheseStarts`,`Any one of these starts a run.`),children:o(Dn,{triggers:h.triggers,devices:y,onChange:e=>g(Dt(h,e))})}),o(In,{step:`2`,title:f(`automation.automationEditor.andOnlyIf`,`And only if`),subtitle:f(`automation.automationEditor.checkedAfterATriggerFires`,`Checked after a trigger fires. Nothing runs unless this is true.`),children:o(bn,{recipe:h,devices:y,onChange:g})}),o(In,{step:`3`,title:f(`automation.automationEditor.then`,`Then`),subtitle:f(`automation.automationEditor.inThisOrderStoppingAt`,`In this order, stopping at the first failure.`),children:o(At,{actions:h.actions,devices:y,onChange:e=>g(Ot(h,e))})}),o(wn,{code:S.code,error:S.error,canEject:t!==null,ejecting:s,onEject:u}),b!==null&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:b}),b===null&&x!==null&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:x}),a!==null&&o(`p`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:a}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(G,{onClick:()=>{S.code!==null&&l({name:p.trim(),code:S.code,enabled:t?.enabled??!0,placement:Pn})},disabled:i||w,children:[i&&o(O,{className:`h-4 w-4 animate-spin`}),` `,f(`common.save`)]}),e(G,{variant:`ghost`,onClick:()=>v(!_),disabled:t===null,title:t===null?f(`automation.automationEditor.logsAppearOnceTheAutomation`,`Logs appear once the automation has been saved and started`):f(`automation.automationEditor.showThisAutomationSProcess`,`Show this automation's process logs`),"data-testid":`automation-logs-toggle`,children:[o(T,{className:`h-4 w-4`}),` `,f(`common.logs`),` `,_?`▾`:`▸`]}),o(G,{variant:`ghost`,onClick:d,disabled:i,children:f(`common.close`,`Close`)}),C&&o(J,{variant:`warning`,children:f(`automation.automationEditor.nameRequired`,`Name required`)})]}),_&&t!==null&&e(`div`,{className:`rounded border border-border`,"data-testid":`automation-logs-panel`,children:[o(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:o(Z,{i18nKey:`common.logsOf`,values:{id:z(t.id)},components:{code:o(`code`,{})}})}),o(Ne,{addonId:z(t.id),maxHeight:`max-h-64`,showFilters:!1})]})]})}function In({step:t,title:n,subtitle:r,children:i}){return e(`section`,{className:`border-l-2 border-border pl-4`,children:[e(`div`,{className:`mb-2 flex flex-wrap items-baseline gap-2`,children:[o(`span`,{className:`text-xs font-mono text-foreground-subtle`,children:t}),o(`h4`,{className:`text-sm font-medium uppercase tracking-wide`,children:n}),o(`span`,{className:`text-xs text-foreground-subtle`,children:r})]}),i]})}function Ln(e){let t=A.safeParse(e);if(t.success)return null;let n=t.error.issues[0];return n===void 0?Y.t(`helpers.automationEditor.incomplete`):`${n.path.length===0?``:`${n.path.join(`.`)}: `}${n.message}`}function Rn(e,t){try{return{code:H({name:e,recipe:t}),error:null}}catch(e){return{code:null,error:e instanceof Error?e.message:String(e)}}}function zn(e){if(!e.enabled)return{tone:`idle`,label:Y.t(`helpers.coreBlockStatus.disabled`),detail:Y.t(`helpers.coreBlockStatus.disabledDetail`)};switch(e.status){case`running`:return{tone:`ok`,label:Y.t(`helpers.coreBlockStatus.running`),detail:Y.t(`helpers.coreBlockStatus.runningDetail`)};case`starting`:return{tone:`pending`,label:Y.t(`helpers.coreBlockStatus.starting`),detail:e.lastError??Y.t(`helpers.coreBlockStatus.startingDetail`)};case`failed`:return{tone:`error`,label:Y.t(`helpers.coreBlockStatus.failed`),detail:e.lastError??Y.t(`helpers.coreBlockStatus.failedDetail`)};default:return{tone:`error`,label:Y.t(`helpers.coreBlockStatus.notRunning`),detail:e.lastError??Y.t(`helpers.coreBlockStatus.notRunningDetail`)}}}function Bn(e){switch(e){case`ok`:return`success`;case`pending`:return`warning`;case`error`:return`danger`;default:return`default`}}function Vn(e,t){let n=e.find(e=>e.id===t.id);return n===void 0?t:n.updatedAt>=t.updatedAt?n:t}function Hn(e){let t=e=>{let t=zn(e).tone;return t===`error`?0:t===`pending`?1:t===`ok`?2:3};return[...e].sort((e,n)=>t(e)-t(n)||e.name.localeCompare(n.name))}function Un(e){if(e.length===0)return Y.t(`helpers.coreBlockStatus.noBlocks`);let t=e.filter(e=>zn(e).tone===`error`).length,n=e.filter(e=>zn(e).tone===`ok`).length,r=[Y.t(`helpers.coreBlockStatus.blocks`,{count:e.length})];return n>0&&r.push(Y.t(`helpers.coreBlockStatus.runningCount`,{count:n})),t>0&&r.push(Y.t(`helpers.coreBlockStatus.notRunningCount`,{count:t})),r.join(` · `)}function Wn({block:t,busy:n,confirming:r,logsOpen:i,unreadable:a,onEdit:s,onToggle:c,onToggleLogs:l,onAskDelete:u,onCancelDelete:d,onConfirmDelete:f}){let p=S(),{t:h}=X(),_=zn(t),v=je(t.updatedAt,p);return e(`li`,{className:`flex flex-col gap-2 p-3`,children:[e(`div`,{className:`flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-3`,children:[e(`div`,{className:`min-w-0 flex-1`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(`span`,{className:`truncate font-medium`,children:t.name}),o(J,{variant:Bn(_.tone),children:_.label}),v!==null&&o(`span`,{className:`text-xs text-foreground-subtle`,children:h(`common.edited`,{when:v})})]}),o(`p`,{className:`mt-0.5 text-xs text-foreground-subtle`,children:_.detail}),a!==null&&o(`p`,{className:`mt-0.5 text-xs text-warning`,children:h(`automation.editor.listUnreadable`,{reason:a})})]}),r?e(`div`,{className:`flex justify-end gap-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:h(`automation.automationList.deleteThisAutomation`,`Delete this automation?`)}),o(G,{variant:`danger`,onClick:e=>{e.stopPropagation(),f()},disabled:n,children:h(`common.delete`,`Delete`)}),o(G,{variant:`ghost`,onClick:e=>{e.stopPropagation(),d()},children:h(`common.cancel`,`Cancel`)})]}):e(`div`,{className:`flex justify-end gap-1`,children:[o(G,{variant:`ghost`,onClick:e=>{e.stopPropagation(),s()},disabled:a!==null,title:a===null?h(`common.edit`,`Edit`):h(`automation.automationList.thisBlockCannotBeOpened`,`This block cannot be opened visually`),children:o(m,{className:`h-4 w-4`})}),e(ke,{children:[o(Te,{children:o(G,{variant:`ghost`,disabled:!0,title:h(`automation.automationList.runActions`,`Run actions`),children:o(C,{className:`h-4 w-4`})})}),o(Me,{children:h(`automation.automationList.runningAnAutomationByHand`,`Running an automation by hand needs the automation-control authority, which is not wired up yet. There is deliberately no second way to execute one.`)})]}),o(G,{variant:`ghost`,onClick:e=>{e.stopPropagation(),l()},title:h(`automation.automationList.logs`,`Logs`),children:o(T,{className:`h-4 w-4`})}),o(G,{variant:`ghost`,onClick:e=>{e.stopPropagation(),c(!t.enabled)},disabled:n,title:t.enabled?h(`common.disable`,`Disable`):h(`common.enable`,`Enable`),children:t.enabled?h(`common.disable`,`Disable`):h(`common.enable`,`Enable`)}),o(G,{variant:`ghost`,onClick:e=>{e.stopPropagation(),u()},title:h(`common.delete`,`Delete`),children:o(g,{className:`h-4 w-4`})})]})]}),i&&e(`div`,{className:`rounded border border-border`,children:[o(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:o(Z,{i18nKey:`common.logsOf`,values:{id:z(t.id)},components:{code:o(`code`,{})}})}),o(Ne,{addonId:z(t.id),maxHeight:`max-h-64`,showFilters:!1})]})]})}function Gn({onCreate:t}){let{t:n}=X();return o(Le,{children:e(`div`,{className:`space-y-2 p-4`,children:[o(`p`,{className:`text-sm text-foreground`,children:n(`automation.automationList.noAutomationsYet`,`No automations yet.`)}),o(`p`,{className:`max-w-2xl text-xs text-foreground-subtle`,children:n(`automation.automationList.anAutomationIsATrigger`,`An automation is a trigger, a set of conditions and a list of actions. It compiles to an ordinary block and runs in its own supervised process — there is no separate engine, so anything that goes wrong shows up here with a reason.`)}),o(G,{onClick:t,children:n(`automation.automationList.newAutomation`,`New automation`)})]})})}u();var Kn=[`coreBlocks`,`list`],qn=5e3;function Jn(e){return e instanceof Error?e.message:String(e)}function Yn({onOpenScripts:t,initialBlockId:i,onBlockIdChange:a,createRequested:u=!1,onCreateConsumed:f}){let{t:p}=X(),m=E(),{state:h,openNew:g,openEdit:_,close:v}=Ae({editKey:`block`,newKey:`new`}),[y,b]=c(null),[x,S]=c(null),[C,w]=c(null),T=n(null),O=h.mode!==`closed`;s(()=>{u&&(b(null),g(),a?.(null),f?.())},[u,f,a,g]);let k=l({queryKey:Kn,refetchInterval:qn,queryFn:async()=>(await m.trpcClient.coreBlocks.list.query({})).blocks}),A=()=>{k.refetch()},j=k.data;s(()=>{i===void 0||T.current===i||j?.find(e=>e.id===i&&rt(e.code))!==void 0&&(T.current=i,_(i),a?.(i))},[i,j,_,a]);let M=d({mutationFn:e=>m.trpcClient.coreBlocks.create.mutate({block:e}),onSuccess:e=>{b(e.block),_(e.block.id),a?.(e.block.id),A()}}),N=d({mutationFn:e=>m.trpcClient.coreBlocks.update.mutate(e),onSuccess:e=>{b(e.block),_(e.block.id),a?.(e.block.id),A()}}),P=d({mutationFn:e=>m.trpcClient.coreBlocks.delete.mutate({blockId:e}),onSuccess:()=>{S(null),A()}}),F=d({mutationFn:e=>m.trpcClient.coreBlocks.setEnabled.mutate(e),onSuccess:A}),I=d({mutationFn:e=>m.trpcClient.coreBlocks.update.mutate({blockId:e.id,block:{name:e.name,code:ot(e.code),enabled:e.enabled,placement:e.placement,...e.integrationId===void 0?{}:{integrationId:e.integrationId}}}),onSuccess:e=>{v(),b(null),A(),t(e.block.id)}}),L=k.data,R=Hn((L??[]).filter(e=>rt(e.code))),z=L!==void 0&&R.length===0,B=h.mode===`edit`?R.find(e=>e.id===h.id)??(y!==null&&y.id===h.id?y:null):null,V=h.mode===`new`||B===null?null:Vn(R,B),H=V===null?null:at(V.code),ee=M.error===null?N.error===null?I.error===null?null:Jn(I.error):Jn(N.error):Jn(M.error),te=r(()=>[{key:`row`,header:p(`build.automationsTab.automation`,`Automation`),nowrap:!1,notSortableReason:`Composite status row`,render:e=>{let t=at(e.code);return o(`ul`,{className:`list-none`,children:o(Wn,{block:e,busy:F.isPending||P.isPending,confirming:x===e.id,logsOpen:C===e.id,unreadable:t.ok?null:t.reason,onEdit:()=>{b(e),_(e.id),a?.(e.id)},onToggle:t=>F.mutate({blockId:e.id,enabled:t}),onToggleLogs:()=>w(C===e.id?null:e.id),onAskDelete:()=>S(e.id),onCancelDelete:()=>S(null),onConfirmDelete:()=>P.mutate(e.id)})})},sortValue:e=>e.name}],[x,C,a,_,P,F,p]);return e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:L===void 0?``:Un(R)}),k.error!=null&&o(W,{title:p(`build.automationsTab.couldNotReadTheAutomations`,`Could not read the automations`),message:Jn(k.error),onRetry:A}),z?o(Gn,{onCreate:()=>{b(null),g(),a?.(null)}}):o(ue,{columns:te,rows:R,rowKey:e=>e.id,pageSize:25,maxBodyHeight:Ie,emptyMessage:L===void 0?p(`build.automationsTab.loadingAutomations`,`Loading automations…`):p(`build.automationsTab.noAutomationsYet`,`No automations yet.`),onRowClick:e=>{b(e),_(e.id),a?.(e.id)}}),o(Ee,{open:O,onClose:()=>{M.reset(),N.reset(),I.reset(),b(null),v(),a?.(null)},title:V===null?p(`build.automationsTab.newAutomation`,`New automation`):p(`build.automationsTab.edit`,`Edit {{name}}`,{name:V.name}),icon:D,width:`xl`,testId:`automation-editor-panel`,children:o(Fn,{existing:V,initialRecipe:H!==null&&H.ok?H.recipe:yt,saving:M.isPending||N.isPending,saveError:ee,ejecting:I.isPending,onSave:e=>{V===null?M.mutate(e):N.mutate({blockId:V.id,block:e})},onEject:()=>{V!==null&&I.mutate(V)},onCancel:()=>{M.reset(),N.reset(),I.reset(),b(null),v(),a?.(null)}},V?.id??`new`)}),P.error!=null&&o(W,{message:Jn(P.error)}),F.error!=null&&o(W,{message:Jn(F.error)})]})}u();function Xn({mode:e,onTitle:t}){return o(e===`helper`?Zn:Qn,{onTitle:t})}function Zn({onTitle:e}){let{t}=X(),n=Ke(),r=Oe(),i=xe(),a=de({addonId:`composer`}),[l,u]=c(null),d=er(l,t);return s(()=>{e(d)},[e,d]),o(`div`,{className:`flex flex-col gap-3`,"data-testid":`composition-create-form`,children:o(Qe,{purpose:`create`,initial:null,start:`template`,saving:r.isPending,onDraftChange:u,onSave:async(e,o)=>{let s=null,c=await Ze(e,async(e,c)=>{let{block:l}=await r.mutateAsync({block:{...c===``?{}:{name:c},enabled:!0,composition:e}}),u=await tr(l.id,async()=>(await a.refetch()).data??a.data);if(u===null)throw Error(t(`helper.devicePending`));s=u,c!==``&&await i.mutateAsync({deviceId:u,name:c}),o===`open`&&n(Ue(u),{replace:!0})}),l=s;return c.length>0||l===null?{kind:`refused`,lines:nr(c,t)}:{kind:`saved`,deviceId:l}}})})}function Qn({onTitle:t}){let{t:n}=X(),r=S(),i=Ke(),a=Oe(),l=xe(),u=de({addonId:`composer`}),[d,f]=c(M.Sensor),[p,m]=c(I.TemperatureSensor),[h,g]=c(``),[_,v]=c(null),y=Xe({type:d,role:p});return s(()=>{t(n(`helper.newComposition`))},[t,n]),e(`div`,{className:`flex flex-col gap-3`,"data-testid":`blank-composition-form`,children:[e(`div`,{className:`grid grid-cols-1 gap-2 sm:grid-cols-2`,children:[e(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[n(`compositionEditor.targetType`),o(K,{value:d,onChange:e=>{let t=Object.values(M).find(t=>t===e.target.value);t!==void 0&&f(t)},options:Object.values(M).map(e=>({value:e,label:Fe(e,r).label}))})]}),e(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[n(`customize.identity.role`),o(K,{value:p??``,onChange:e=>m(Object.values(I).find(t=>t===e.target.value)??null),options:[{value:``,label:n(`customize.identity.noRole`)},...Object.values(I).map(e=>({value:e,label:ye(e,r).label}))]})]}),e(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[n(`compositionEditor.name`),o(q,{"aria-label":n(`compositionEditor.name`),value:h,onChange:e=>g(e.target.value)})]})]}),_!==null&&o(`p`,{role:`alert`,className:`text-xs text-danger`,children:_}),o(G,{disabled:y===null||a.isPending,onClick:()=>{y!==null&&$n({composition:y,name:h,create:e=>a.mutateAsync({block:e}),rename:(e,t)=>l.mutateAsync({deviceId:e,name:t}),readFleet:async()=>(await u.refetch()).data??u.data,onError:e=>v(e),onOpen:e=>i(Ge(e),{replace:!0}),pending:n(`helper.devicePending`)})},children:n(`compositionEditor.save`)})]})}async function $n(e){e.onError(null);try{let t=e.name.trim(),{block:n}=await e.create({...t===``?{}:{name:t},enabled:!0,composition:e.composition}),r=await tr(n.id,e.readFleet);if(r===null){e.onError(e.pending);return}t!==``&&await e.rename(r,t),e.onOpen(r)}catch(t){e.onError(t instanceof Error?t.message:String(t))}}function er(e,t){if(e===null)return t(`helper.newHelper`);if(e.templateId===`appliance`&&e.appliance!==null)return t(`helper.newTitle.${e.appliance}`);if(e.templateId===`appliance`)return t(`helper.newHelper`);let n=re(e.templateId);return t(n===null?`helper.newHelper`:`helper.newTitle.${n.id}`)}async function tr(e,t){let n=`${te}${e}`;return(await t())?.find(e=>e.stableId===n)?.id??null}function nr(e,t){return e.length>0?e:$e(t(`helper.devicePending`))}function rr(e){return{state:`answered`,byRef:new Map(e.map(e=>[L(e),e]))}}function ir(e,t){if(e.state!==`unanswered`)return e.byRef.get(L(t))??null}function ar(e){return e===void 0?`unknown`:e===null?`missing`:`present`}function or(e){return ie(e).map(e=>e.source)}function sr(e){let t=e.block.source?.kind===`composition`?e.block.source.composition:null;if(t===null)return[];let n=[];for(let e of t.features){if(e.kind===`passthrough`){n.push(e.source);continue}for(let t of Object.values(e.fields))n.push(...or(t));for(let t of Object.values(e.items??{}))for(let e of Object.values(t.fields))n.push(...or(e))}let r=new Set;return n.filter(e=>{let t=L(e);return r.has(t)?!1:(r.add(t),!0)})}function cr(e){let t=e.fields.filter(e=>e.state===`unavailable`),n=e.fields.filter(e=>e.state===`stale`);if(t.length===0&&n.length===0)return{tone:`ok`,label:Y.t(`helpers.compositionRows.running`),reason:null};let r=[...t.length>0?[Y.t(`helpers.compositionRows.fieldsUnavailable`,{count:t.length})]:[],...n.length>0?[Y.t(`helpers.compositionRows.fieldsStale`,{count:n.length})]:[]].join(`, `),i=t[0]??n[0],a=i===void 0?``:` — ${i.cap}.${i.path}: ${i.reason??Y.t(`helpers.compositionRows.noReason`)}`;return{tone:`pending`,label:Y.t(`helpers.compositionRows.running`),reason:`${r}${a}`}}function lr(e,t){let n=e.reason??t??null;switch(e.status){case`running`:return cr(e);case`degraded`:return{tone:`pending`,label:Y.t(`helpers.compositionRows.degraded`),reason:n??Y.t(`helpers.compositionRows.degradedReason`)};case`starting`:return{tone:`pending`,label:Y.t(`helpers.compositionRows.starting`),reason:n};case`failed`:return{tone:`error`,label:Y.t(`helpers.compositionRows.failed`),reason:n??Y.t(`helpers.compositionRows.failedReason`)};default:return{tone:`error`,label:Y.t(`helpers.compositionRows.notRunning`),reason:n??Y.t(`helpers.compositionRows.notRunningReason`)}}}function ur(e){let{block:t,state:n}=e;if(!t.enabled)return{tone:`idle`,label:Y.t(`helpers.compositionRows.off`),reason:null};if(n.kind===`unreachable`)return{tone:`pending`,label:Y.t(`helpers.compositionRows.unknown`),reason:Y.t(`helpers.compositionRows.unreachable`,{error:n.error})};if(n.state!==null)return lr(n.state,t.lastError);let r=t.lastError===void 0?t.status:`${t.status}: ${t.lastError}`;return{tone:`pending`,label:Y.t(`helpers.compositionRows.notReported`),reason:Y.t(`helpers.compositionRows.noRecord`,{stored:r})}}function dr(e){return L(e)}function fr(e,t){let n=ir(t,e);return{key:L(e),label:n?n.name:dr(e),presence:ar(n),deviceId:n?n.id:null}}function pr(e){return e.state.kind===`answered`&&e.state.state!==null?e.state.state.deviceId:null}function mr(e,t){let n=e.block.source?.kind===`composition`?e.block.source.composition:null;if(n===null)return null;let r=n.target,i=r.kind===`existing`?r.device:B(e.block.id),a=L(i),o=sr(e).filter(e=>L(e)!==a).map(e=>fr(e,t)),s=n.features.map(e=>e.enabled===!1?Y.t(`helpers.compositionRows.featureOff`,{cap:e.cap}):e.cap),c=ir(t,i),l=pr(e),u=ur(e);if(r.kind===`new`)return{blockId:e.block.id,kind:`composed`,name:e.block.name,namePresence:`present`,type:r.role===void 0?r.type:`${r.type} · ${r.role}`,features:s,state:u,sources:o,reportedDeviceId:l};let d=ar(c);return{blockId:e.block.id,kind:`customization`,name:c?c.name:dr(r.device),namePresence:d,type:c?c.type:null,features:s,state:u,sources:o,reportedDeviceId:l}}function hr(e){return e.state.tone===`error`?0:e.state.tone===`pending`?1:e.state.tone===`ok`?2:3}function gr(e,t){return hr(e)-hr(t)||e.name.localeCompare(t.name)}function _r(e,t){let n=e.flatMap(e=>{let n=mr(e,t);return n===null?[]:[n]});return{composed:n.filter(e=>e.kind===`composed`).toSorted(gr),customizations:n.filter(e=>e.kind===`customization`).toSorted(gr)}}u();var vr=1e4;function yr(e){return e instanceof Error?e.message:typeof e==`object`&&e&&`message`in e?String(e.message):String(e)}function br(){let e=He();return e.data===void 0?{state:`unanswered`,reason:e.error==null?Y.t(`build.customDeviceTab.deviceListPending`):Y.t(`build.customDeviceTab.deviceListUnreadable`,{error:yr(e.error)})}:rr(e.data)}function xr(e,t){return e===`blank`?`blank`:e===`helper`||e===`1`||t?`helper`:null}function Sr({createRequested:t=!1,onCreateConsumed:n}={}){let{t:r}=X(),[i,a]=We(),s=ve({},{refetchInterval:vr}),l=br(),u=Ae({editKey:`block`,newKey:`new`}),d=u.state.mode===`edit`?u.state.id:null,p=d===null?xr(i.get(`new`),t):null,m=p!==null,[h,g]=c(``),_=()=>{u.close(),a(()=>{let e=new URLSearchParams(window.location.search);return e.delete(`new`),e.delete(`block`),e},{replace:!0}),n?.()},v=s.data;return e(f,{children:[wr(v,s.error,()=>void s.refetch(),l,{onEditComposed:e=>u.openEdit(e)}),o(Ee,{open:m||d!==null,onClose:_,title:m?h||r(p===`blank`?`helper.newComposition`:`helper.newHelper`):r(`build.customDeviceTab.editComposedDevice`,`Edit composed device`),icon:U,width:`xl`,testId:`composed-device-editor`,children:m&&p!==null?o(Xn,{mode:p,onTitle:g},p):d===null?null:o(et,{blockId:d})})]})}function Cr(t){return o(Le,{children:e(`div`,{className:`space-y-1 p-4`,children:[o(`p`,{className:`text-sm text-warning`,children:Y.t(`build.customDeviceTab.theCompositionStoreHasNot`,`The composition store has not been read yet.`)}),e(`p`,{className:`text-xs text-foreground-subtle`,children:[Y.t(`build.customDeviceTab.thisIsNotTheSame`,`This is not the same as having none — the list appears once the hub has read it (`),t,`).`]})]})})}function wr(e,t,n,r,i){if(t!=null&&e===void 0)return o(W,{title:Y.t(`build.customDeviceTab.couldNotReadTheCompositions`,`Could not read the compositions`),message:yr(t),onRetry:n});if(e===void 0)return o(`p`,{className:`p-4 text-sm text-foreground-subtle`,children:Y.t(`build.customDeviceTab.loadingCompositions`,`Loading compositions…`)});if(e.state===`not-loaded`)return Cr(e.reason);let a=t==null?null:yr(t);return o(Tr,{lists:_r(e.views,r),fleet:r,refreshError:a,onEditComposed:i.onEditComposed})}function Tr({lists:t,fleet:n,refreshError:r,onEditComposed:i}){let{t:a}=X();return e(`div`,{className:`space-y-4`,children:[r!==null&&e(`p`,{className:`text-xs text-warning`,children:[a(`build.customDeviceTab.showingTheLastAnswerThe`,`Showing the last answer — the latest refresh failed:`),` `,r]}),n.state===`unanswered`&&e(`p`,{className:`text-xs text-warning`,children:[a(`build.customDeviceTab.deviceNamesAreShownAs`,`Device names are shown as references:`),` `,n.reason,`. No source is marked missing until it has.`]}),o(Er,{title:a(`build.customDeviceTab.composedDevices`,`Composed devices`),hint:a(`build.customDeviceTab.aNewDeviceWhoseState`,`A new device whose state is derived from other devices.`),rows:t.composed,nameHeader:`Name`,emptyMessage:a(`build.customDeviceTab.noComposedDevices`,`No composed devices.`),kind:`composed`,onEditComposed:i}),o(Er,{title:a(`build.customDeviceTab.customizations`,`Customizations`),hint:a(`build.customDeviceTab.fieldsAddedToOrReplaced`,`Fields added to or replaced on an existing device — one per device, edited from the device.`),rows:t.customizations,nameHeader:`Device`,emptyMessage:a(`build.customDeviceTab.noCustomizations`,`No customizations.`),kind:`customization`,onEditComposed:i})]})}function Er({title:t,hint:n,rows:r,nameHeader:i,emptyMessage:a,kind:s,onEditComposed:c}){return e(`section`,{className:`space-y-2`,"aria-label":t,children:[e(`div`,{children:[o(`h3`,{className:`font-medium`,children:t}),o(`p`,{className:`text-xs text-foreground-subtle`,children:n})]}),o(Le,{variant:`flat`,className:`p-0`,children:o(ue,{columns:Dr(i,s,c),rows:r,rowKey:e=>e.blockId,minWidthPx:760,bordered:!1,maxBodyHeight:Ie,emptyMessage:a,onRowClick:s===`composed`?e=>c(e.blockId):void 0})})]})}function Dr(t,n,r){let i=[{key:`name`,header:t,sortValue:e=>e.name.toLowerCase(),render:e=>o(Or,{row:e})},{key:`type`,header:Y.t(`build.customDeviceTab.type`,`Type`),sortValue:e=>e.type,render:e=>o(`span`,{className:`text-xs text-foreground-subtle`,children:e.type??Y.t(`common.unknownWord`)})},{key:`state`,header:Y.t(`build.customDeviceTab.state`,`State`),nowrap:!1,notSortableReason:`A state and its reason are read together, not ordered.`,render:t=>e(`div`,{className:`space-y-0.5`,children:[o(J,{variant:Bn(t.state.tone),children:t.state.label}),t.state.reason!==null&&o(`p`,{className:`max-w-md whitespace-normal text-xs text-foreground-subtle`,children:t.state.reason})]})},{key:`sources`,header:Y.t(`build.customDeviceTab.sources`,`Sources`),nowrap:!1,notSortableReason:`A list of devices has no single order.`,render:e=>o(Ar,{sources:e.sources})}];return n===`composed`&&i.push({key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,nowrap:!0,render:e=>o(`div`,{className:`flex justify-end gap-1`,children:o(G,{type:`button`,size:`sm`,variant:`secondary`,onClick:t=>{t.stopPropagation(),r(e.blockId)},children:Y.t(`common.edit`,`Edit`)})})}),i}function Or({row:t}){let{t:n}=X();return e(`div`,{className:`space-y-0.5`,children:[o(kr,{row:t}),t.namePresence===`missing`&&o(`span`,{className:`ml-1.5 text-[10px] text-danger`,children:n(`build.customDeviceTab.deviceMissing`,`device missing`)}),o(`p`,{className:`text-[11px] text-foreground-subtle`,children:t.features.join(`, `)})]})}function kr({row:e}){let{t}=X(),n=fe(e.reportedDeviceId??0,`compact`,e.name),r=e.reportedDeviceId===null?e.name:n;return e.reportedDeviceId===null?e.kind===`composed`?o(`span`,{className:`text-xs font-medium text-foreground`,children:e.name}):o(`span`,{className:`text-xs text-foreground-subtle`,children:t(`build.customDeviceTab.notReported`,{name:r})}):o(qe,{to:e.kind===`composed`?Ue(e.reportedDeviceId):Ge(e.reportedDeviceId),className:`text-xs font-medium text-foreground hover:underline`,onClick:e=>e.stopPropagation(),children:r})}function Ar({sources:t}){let{t:n}=X();return t.length===0?o(`span`,{className:`text-xs text-foreground-subtle`,children:`—`}):o(`ul`,{className:`space-y-0.5`,children:t.map(t=>e(`li`,{className:`text-xs`,children:[t.deviceId===null?o(`span`,{className:t.presence===`missing`?`text-danger`:`text-foreground`,children:t.label}):o(qe,{to:`/devices/${String(t.deviceId)}`,className:`hover:underline`,children:t.label}),t.presence===`missing`&&o(`span`,{className:`ml-1.5 text-[10px] text-danger`,children:n(`common.missing`)})]},t.key))})}function jr(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function Mr(e){if(Array.isArray(e))return e}function Nr(e,t,n){return(t=Hr(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Pr(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t!==0)for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}}function Fr(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
5
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Ir(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function Lr(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?Ir(Object(n),!0).forEach(function(t){Nr(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Ir(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function Rr(e,t){if(e==null)return{};var n,r,i=zr(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function zr(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function Br(e,t){return Mr(e)||Pr(e,t)||Ur(e,t)||Fr()}function Vr(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function Hr(e){var t=Vr(e,`string`);return typeof t==`symbol`?t:t+``}function Ur(e,t){if(e){if(typeof e==`string`)return jr(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?jr(e,t):void 0}}function Wr(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Gr(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function Kr(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?Gr(Object(n),!0).forEach(function(t){Wr(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Gr(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function qr(){var e=[...arguments];return function(t){return e.reduceRight(function(e,t){return t(e)},t)}}function Jr(e){return function t(){var n=this,r=[...arguments];return r.length>=e.length?e.apply(this,r):function(){var e=[...arguments];return t.apply(n,[].concat(r,e))}}}function Yr(e){return{}.toString.call(e).includes(`Object`)}function Xr(e){return!Object.keys(e).length}function Zr(e){return typeof e==`function`}function Qr(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function $r(e,t){return Yr(t)||ii(`changeType`),Object.keys(t).some(function(t){return!Qr(e,t)})&&ii(`changeField`),t}function ei(e){Zr(e)||ii(`selectorType`)}function ti(e){Zr(e)||Yr(e)||ii(`handlerType`),Yr(e)&&Object.values(e).some(function(e){return!Zr(e)})&&ii(`handlersType`)}function ni(e){e||ii(`initialIsRequired`),Yr(e)||ii(`initialType`),Xr(e)&&ii(`initialContent`)}function ri(e,t){throw Error(e[t]||e.default)}var ii=Jr(ri)({initialIsRequired:`initial state is required`,initialType:`initial state should be an object`,initialContent:`initial state shouldn't be an empty object`,handlerType:`handler should be an object or a function`,handlersType:`all handlers should be a functions`,selectorType:`selector should be a function`,changeType:`provided value of changes should be an object`,changeField:`it seams you want to change a field in the state which is not specified in the "initial" state`,default:"an unknown error accured in `state-local` package"}),ai={changes:$r,selector:ei,handler:ti,initial:ni};function oi(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};ai.initial(e),ai.handler(t);var n={current:e},r=Jr(li)(n,t),i=Jr(ci)(n),a=Jr(ai.changes)(e),o=Jr(si)(n);function s(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:function(e){return e};return ai.selector(e),e(n.current)}function c(e){qr(r,i,a,o)(e)}return[s,c]}function si(e,t){return Zr(t)?t(e.current):t}function ci(e,t){return e.current=Kr(Kr({},e.current),t),t}function li(e,t,n){return Zr(t)?t(e.current):Object.keys(n).forEach(function(n){return t[n]?.call(t,e.current[n])}),n}var ui={create:oi},di={paths:{vs:`https://cdn.jsdelivr.net/npm/monaco-editor@0.55.1/min/vs`}};function fi(e){return function t(){var n=this,r=[...arguments];return r.length>=e.length?e.apply(this,r):function(){var e=[...arguments];return t.apply(n,[].concat(r,e))}}}function pi(e){return{}.toString.call(e).includes(`Object`)}function mi(e){return e||vi(`configIsRequired`),pi(e)||vi(`configType`),e.urls?(hi(),{paths:{vs:e.urls.monacoBase}}):e}function hi(){console.warn(_i.deprecation)}function gi(e,t){throw Error(e[t]||e.default)}var _i={configIsRequired:`the configuration object is required`,configType:`the configuration object should be an object`,default:"an unknown error accured in `@monaco-editor/loader` package",deprecation:`Deprecation warning!
|
|
6
|
-
You are using deprecated way of configuration.
|
|
7
|
-
|
|
8
|
-
Instead of using
|
|
9
|
-
monaco.config({ urls: { monacoBase: '...' } })
|
|
10
|
-
use
|
|
11
|
-
monaco.config({ paths: { vs: '...' } })
|
|
12
|
-
|
|
13
|
-
For more please check the link https://github.com/suren-atoyan/monaco-loader#config
|
|
14
|
-
`},vi=fi(gi)(_i),yi={config:mi},bi=function(){var e=[...arguments];return function(t){return e.reduceRight(function(e,t){return t(e)},t)}};function xi(e,t){return Object.keys(t).forEach(function(n){t[n]instanceof Object&&e[n]&&Object.assign(t[n],xi(e[n],t[n]))}),Lr(Lr({},e),t)}var Si={type:`cancelation`,msg:`operation is manually canceled`};function Ci(e){var t=!1,n=new Promise(function(n,r){e.then(function(e){return t?r(Si):n(e)}),e.catch(r)});return n.cancel=function(){return t=!0},n}var wi=[`monaco`],Ti=Br(ui.create({config:di,isInitialized:!1,resolve:null,reject:null,monaco:null}),2),Ei=Ti[0],Di=Ti[1];function Oi(e){var t=yi.config(e),n=t.monaco,r=Rr(t,wi);Di(function(e){return{config:xi(e.config,r),monaco:n}})}function ki(){var e=Ei(function(e){return{monaco:e.monaco,isInitialized:e.isInitialized,resolve:e.resolve}});if(!e.isInitialized){if(Di({isInitialized:!0}),e.monaco)return e.resolve(e.monaco),Ci(Ii);if(window.monaco&&window.monaco.editor)return Pi(window.monaco),e.resolve(window.monaco),Ci(Ii);bi(Ai,Mi)(Ni)}return Ci(Ii)}function Ai(e){return document.body.appendChild(e)}function ji(e){var t=document.createElement(`script`);return e&&(t.src=e),t}function Mi(e){var t=Ei(function(e){return{config:e.config,reject:e.reject}}),n=ji(`${t.config.paths.vs}/loader.js`);return n.onload=function(){return e()},n.onerror=t.reject,n}function Ni(){var e=Ei(function(e){return{config:e.config,resolve:e.resolve,reject:e.reject}}),t=window.require;t.config(e.config),t([`vs/editor/editor.main`],function(t){var n=t.m||t;Pi(n),e.resolve(n)},function(t){e.reject(t)})}function Pi(e){Ei().monaco||Di({monaco:e})}function Fi(){return Ei(function(e){return e.monaco})}var Ii=new Promise(function(e,t){return Di({resolve:e,reject:t})}),Li={config:Oi,init:ki,__getMonacoInstance:Fi};u();var Ri={wrapper:{display:`flex`,position:`relative`,textAlign:`initial`},fullWidth:{width:`100%`},hide:{display:`none`}},zi={container:{display:`flex`,height:`100%`,width:`100%`,justifyContent:`center`,alignItems:`center`}};function Bi({children:e}){return t.createElement(`div`,{style:zi.container},e)}var Vi=Bi;function Hi({width:e,height:n,isEditorReady:r,loading:i,_ref:a,className:o,wrapperProps:s}){return t.createElement(`section`,{style:{...Ri.wrapper,width:e,height:n},...s},!r&&t.createElement(Vi,null,i),t.createElement(`div`,{ref:a,style:{...Ri.fullWidth,...!r&&Ri.hide},className:o}))}var Ui=i(Hi);function Wi(e){s(e,[])}var Gi=Wi;function Ki(e,t,r=!0){let i=n(!0);s(i.current||!r?()=>{i.current=!1}:e,t)}var $=Ki;function qi(){}function Ji(e,t,n,r){return Yi(e,r)||Xi(e,t,n,r)}function Yi(e,t){return e.editor.getModel(Zi(e,t))}function Xi(e,t,n,r){return e.editor.createModel(t,n,r?Zi(e,r):void 0)}function Zi(e,t){return e.Uri.parse(t)}function Qi({original:e,modified:r,language:i,originalLanguage:o,modifiedLanguage:l,originalModelPath:u,modifiedModelPath:d,keepCurrentOriginalModel:f=!1,keepCurrentModifiedModel:p=!1,theme:m=`light`,loading:h=`Loading...`,options:g={},height:_=`100%`,width:v=`100%`,className:y,wrapperProps:b={},beforeMount:x=qi,onMount:S=qi}){let[C,w]=c(!1),[T,E]=c(!0),D=n(null),O=n(null),k=n(null),A=n(S),j=n(x),M=n(!1);Gi(()=>{let e=Li.init();return e.then(e=>(O.current=e)&&E(!1)).catch(e=>e?.type!==`cancelation`&&console.error(`Monaco initialization: error:`,e)),()=>D.current?F():e.cancel()}),$(()=>{if(D.current&&O.current){let t=D.current.getOriginalEditor(),n=Ji(O.current,e||``,o||i||`text`,u||``);n!==t.getModel()&&t.setModel(n)}},[u],C),$(()=>{if(D.current&&O.current){let e=D.current.getModifiedEditor(),t=Ji(O.current,r||``,l||i||`text`,d||``);t!==e.getModel()&&e.setModel(t)}},[d],C),$(()=>{let e=D.current.getModifiedEditor();e.getOption(O.current.editor.EditorOption.readOnly)?e.setValue(r||``):r!==e.getValue()&&(e.executeEdits(``,[{range:e.getModel().getFullModelRange(),text:r||``,forceMoveMarkers:!0}]),e.pushUndoStop())},[r],C),$(()=>{D.current?.getModel()?.original.setValue(e||``)},[e],C),$(()=>{let{original:e,modified:t}=D.current.getModel();O.current.editor.setModelLanguage(e,o||i||`text`),O.current.editor.setModelLanguage(t,l||i||`text`)},[i,o,l],C),$(()=>{O.current?.editor.setTheme(m)},[m],C),$(()=>{D.current?.updateOptions(g)},[g],C);let N=a(()=>{if(!O.current)return;j.current(O.current);let t=Ji(O.current,e||``,o||i||`text`,u||``),n=Ji(O.current,r||``,l||i||`text`,d||``);D.current?.setModel({original:t,modified:n})},[i,r,l,e,o,u,d]),P=a(()=>{!M.current&&k.current&&(D.current=O.current.editor.createDiffEditor(k.current,{automaticLayout:!0,...g}),N(),O.current?.editor.setTheme(m),w(!0),M.current=!0)},[g,m,N]);s(()=>{C&&A.current(D.current,O.current)},[C]),s(()=>{!T&&!C&&P()},[T,C,P]);function F(){let e=D.current?.getModel();f||e?.original?.dispose(),p||e?.modified?.dispose(),D.current?.dispose()}return t.createElement(Ui,{width:v,height:_,isEditorReady:C,loading:h,_ref:k,className:y,wrapperProps:b})}i(Qi);function $i(e){let t=n();return s(()=>{t.current=e},[e]),t.current}var ea=$i,ta=new Map;function na({defaultValue:e,defaultLanguage:r,defaultPath:i,value:o,language:l,path:u,theme:d=`light`,line:f,loading:p=`Loading...`,options:m={},overrideServices:h={},saveViewState:g=!0,keepCurrentModel:_=!1,width:v=`100%`,height:y=`100%`,className:b,wrapperProps:x={},beforeMount:S=qi,onMount:C=qi,onChange:w,onValidate:T=qi}){let[E,D]=c(!1),[O,k]=c(!0),A=n(null),j=n(null),M=n(null),N=n(C),P=n(S),F=n(),I=n(o),L=ea(u),R=n(!1),z=n(!1);Gi(()=>{let e=Li.init();return e.then(e=>(A.current=e)&&k(!1)).catch(e=>e?.type!==`cancelation`&&console.error(`Monaco initialization: error:`,e)),()=>j.current?V():e.cancel()}),$(()=>{let t=Ji(A.current,e||o||``,r||l||``,u||i||``);t!==j.current?.getModel()&&(g&&ta.set(L,j.current?.saveViewState()),j.current?.setModel(t),g&&j.current?.restoreViewState(ta.get(u)))},[u],E),$(()=>{j.current?.updateOptions(m)},[m],E),$(()=>{!j.current||o===void 0||(j.current.getOption(A.current.editor.EditorOption.readOnly)?j.current.setValue(o):o!==j.current.getValue()&&(z.current=!0,j.current.executeEdits(``,[{range:j.current.getModel().getFullModelRange(),text:o,forceMoveMarkers:!0}]),j.current.pushUndoStop(),z.current=!1))},[o],E),$(()=>{let e=j.current?.getModel();e&&l&&A.current?.editor.setModelLanguage(e,l)},[l],E),$(()=>{f!==void 0&&j.current?.revealLine(f)},[f],E),$(()=>{A.current?.editor.setTheme(d)},[d],E);let B=a(()=>{if(!(!M.current||!A.current)&&!R.current){P.current(A.current);let t=u||i,n=Ji(A.current,o||e||``,r||l||``,t||``);j.current=A.current?.editor.create(M.current,{model:n,automaticLayout:!0,...m},h),g&&j.current.restoreViewState(ta.get(t)),A.current.editor.setTheme(d),f!==void 0&&j.current.revealLine(f),D(!0),R.current=!0}},[e,r,i,o,l,u,m,h,g,d,f]);s(()=>{E&&N.current(j.current,A.current)},[E]),s(()=>{!O&&!E&&B()},[O,E,B]),I.current=o,s(()=>{E&&w&&(F.current?.dispose(),F.current=j.current?.onDidChangeModelContent(e=>{z.current||w(j.current.getValue(),e)}))},[E,w]),s(()=>{if(E){let e=A.current.editor.onDidChangeMarkers(e=>{let t=j.current.getModel()?.uri;if(t&&e.find(e=>e.path===t.path)){let e=A.current.editor.getModelMarkers({resource:t});T?.(e)}});return()=>{e?.dispose()}}return()=>{}},[E,T]);function V(){F.current?.dispose(),_?g&&ta.set(u,j.current.saveViewState()):j.current.getModel()?.dispose(),j.current.dispose()}return t.createElement(Ui,{width:v,height:y,isEditorReady:E,loading:p,_ref:M,className:b,wrapperProps:x})}var ra=i(na);u();function ia(e,t){let n=[];for(let[r,i]of Object.entries(e))r!==t&&(n.push({filePath:`file:///${r}`,content:i}),r.endsWith(`.ts`)&&n.push({filePath:`file:///${r.slice(0,-3)}.js`,content:i}));return n}var aa={target:99,module:99,moduleResolution:2,strict:!0,noImplicitAny:!0,strictNullChecks:!0,allowNonTsExtensions:!0,isolatedModules:!0};function oa(e,t){let n=e.languages.typescript.typescriptDefaults;n.setCompilerOptions({...n.getCompilerOptions(),...aa}),n.setExtraLibs(t.map(e=>({filePath:e.filePath,content:e.content})))}function sa({value:e,onChange:t,extraLibs:r=[],path:i=`file:///block.ts`,onDiagnostics:c,readOnly:l=!1,heightPx:u=420,dark:d=!0}){let f=n(null),p=a((e,t)=>{if(f.current=t,oa(t,r),c===void 0)return;let n=e.getModel();if(n===null)return;let i=()=>{c(t.editor.getModelMarkers({resource:n.uri}).map(e=>({line:e.startLineNumber,column:e.startColumn,message:e.message,severity:e.severity})))};t.editor.onDidChangeMarkers(i),i()},[r,c]);return s(()=>{let e=f.current;e!==null&&oa(e,r)},[r]),o(ra,{height:u,defaultLanguage:`typescript`,path:i,theme:d?`vs-dark`:`vs`,value:e,onChange:e=>t(e??``),onMount:p,options:{readOnly:l,minimap:{enabled:!1},fontSize:12,lineNumbers:`on`,scrollBeyondLastLine:!1,automaticLayout:!0,tabSize:2,renderWhitespace:`selection`}})}function ca(e){return e.some(e=>e.severity>=8)}var la=[{id:`blank`,name:`Blank script`,get description(){return Y.t(`helpers.buildExamples.blankDescription`)},entry:`main.ts`,files:{"main.ts":`import type { AddonContext } from '@camstack/types'
|
|
15
|
-
|
|
16
|
-
/**
|
|
17
|
-
* A core block. Runs in its own process, with the same \`ctx\` an addon gets.
|
|
18
|
-
* Return a function to release whatever you took (timers, sockets, listeners).
|
|
19
|
-
*
|
|
20
|
-
* Declaring devices: import { reconcileBlockDevices, exposeBlockDevices } from
|
|
21
|
-
* '@camstack/types' and hang them off the shared Blocks integration.
|
|
22
|
-
*/
|
|
23
|
-
export default function block(ctx: AddonContext) {
|
|
24
|
-
ctx.logger.info('hello from a core block')
|
|
25
|
-
|
|
26
|
-
const timer = setInterval(() => {
|
|
27
|
-
ctx.logger.info('tick')
|
|
28
|
-
}, 60_000)
|
|
29
|
-
|
|
30
|
-
return () => {
|
|
31
|
-
clearInterval(timer)
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
`}}];function ua(e){let t=e instanceof Set?e:new Set(e);if(!t.has(`file.ts`))return`file.ts`;let n=2;for(;t.has(`file-${String(n)}.ts`);)n+=1;return`file-${String(n)}.ts`}var da=la.find(e=>e.id===`blank`)?.files[`main.ts`]??`import type { AddonContext } from '@camstack/types'
|
|
35
|
-
|
|
36
|
-
export default function block(ctx: AddonContext) {
|
|
37
|
-
ctx.logger.info('hello from a core block')
|
|
38
|
-
return () => undefined
|
|
39
|
-
}
|
|
40
|
-
`;function fa({existing:e,dirty:t,saving:n,restarting:r}){return e===null?Y.t(`helpers.restartGate.saveFirstNoProcess`):n?Y.t(`helpers.restartGate.saving`):r?Y.t(`helpers.restartGate.restarting`):t?Y.t(`helpers.restartGate.saveFirstDirty`):e.enabled?null:Y.t(`helpers.restartGate.disabled`)}u();var pa=5e3;function ma(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!=`object`||!n)continue;let e=Reflect.get(n,`id`),r=Reflect.get(n,`name`),i=Reflect.get(n,`type`),a=Reflect.get(n,`stableId`);typeof e!=`number`||typeof r!=`string`||typeof i!=`string`||t.push({id:e,name:r,type:i,...typeof a==`string`?{stableId:a}:{}})}return t}function ha({blockId:t}){let{t:n}=X(),i=z(t),a=be({addonId:i,projection:`slim`},{refetchInterval:pa}),s=r(()=>ma(a.data),[a.data]);return a.isLoading?e(`p`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[o(O,{className:`h-3.5 w-3.5 animate-spin`}),` `,n(`build.scriptDevicesPanel.loading`)]}):a.isError?e(`p`,{className:`text-xs text-danger`,children:[n(`build.scriptDevicesPanel.couldNotListDevices`,`Could not list devices:`),` `,a.error instanceof Error?a.error.message:String(a.error)]}):e(`section`,{className:`space-y-3 rounded border border-border p-3`,"data-testid":`script-devices-panel`,children:[e(`div`,{className:`flex items-center justify-between gap-2`,children:[e(`div`,{children:[o(`h4`,{className:`text-sm font-medium`,children:n(`build.scriptDevicesPanel.devices`,`Devices`)}),o(`p`,{className:`text-xs text-foreground-subtle`,children:o(Z,{i18nKey:`build.scriptDevicesPanel.declaredBy`,values:{addonId:i},components:{code:o(`code`,{className:`text-[11px]`})}})})]}),o(J,{variant:`default`,children:s.length})]}),s.length===0?o(`p`,{className:`text-xs text-foreground-subtle`,children:o(Z,{i18nKey:`build.scriptDevicesPanel.noDevices`,components:{code:o(`code`,{})}})}):o(`ul`,{className:`space-y-3`,children:s.map(t=>o(`li`,{className:`rounded border border-border/80 px-3 py-2`,"data-testid":`script-device-${t.id}`,children:e(`div`,{className:`flex flex-wrap items-baseline gap-2`,children:[o(qe,{to:`/devices/${String(t.id)}`,className:`text-sm font-medium hover:underline`,title:n(`build.scriptDevicesPanel.openDeviceDetail`,`Open device detail`),children:o(he,{device:{id:t.id,name:t.name,type:t.type,stableId:t.stableId??``,parentDeviceId:null},form:`compact`})}),o(J,{variant:`info`,style:`outline`,children:t.type}),t.stableId!==void 0&&e(`span`,{className:`text-[11px] text-foreground-subtle`,children:[`stableId `,o(`code`,{children:t.stableId})]}),e(`span`,{className:`text-[11px] text-foreground-subtle`,children:[`#`,t.id]})]})},t.id))})]})}u();function ga(e){return e===`refresh-channel-catalog`||e===`send-tv-schedule-now`||e===`refresh-nordvpn-catalog`||e===`probe-nordvpn-italy`||e===`test-nordvpn-endpoint`||e===`refresh-unifi-catalog`}function _a(e){let t=Date.now();switch(e){case`refresh-channel-catalog`:return{channelCatalogRefreshAt:t};case`send-tv-schedule-now`:return{sendNowAt:t};case`refresh-nordvpn-catalog`:return{nordVpnCatalogRefreshAt:t};case`probe-nordvpn-italy`:return{nordVpnProbeAt:t};case`test-nordvpn-endpoint`:return{nordVpnTestAt:t};case`refresh-unifi-catalog`:return{unifiCatalogRefreshAt:t}}}function va(e){switch(e){case`refresh-channel-catalog`:return Y.t(`build.scriptSettingsPanel.enableChannel`);case`send-tv-schedule-now`:return Y.t(`build.scriptSettingsPanel.enableTv`);case`refresh-nordvpn-catalog`:return Y.t(`build.scriptSettingsPanel.enableNord`);case`probe-nordvpn-italy`:return Y.t(`build.scriptSettingsPanel.enableItaly`);case`test-nordvpn-endpoint`:return Y.t(`build.scriptSettingsPanel.enableVpn`);case`refresh-unifi-catalog`:return Y.t(`build.scriptSettingsPanel.enableUnifi`)}}function ya(e){if(typeof e!=`object`||!e||!(`key`in e))return null;let t=Reflect.get(e,`key`);return typeof t==`string`?t:null}function ba(e){if(!(typeof e!=`object`||!e||!(`value`in e)))return Reflect.get(e,`value`)}function xa(e){let t={};for(let n of e.sections)for(let e of n.fields){let n=ya(e);n!==null&&(t[n]=ba(e))}return t}function Sa(e){return typeof e!=`object`||!e?!1:Array.isArray(Reflect.get(e,`sections`))}function Ca({blockId:t}){let{t:n}=X(),i=E(),s=pe({blockId:t},{retry:!1}),l=me({blockId:t},{refetchInterval:1e4,retry:!1}),u=Se({onSuccess:()=>{l.refetch()}}),d=ze(),f=le(),[p,m]=c(null),[h,g]=c(null),[_,v]=c(null),[y,b]=c(!1),x=Sa(l.data)?l.data:null,S=r(()=>x===null?{}:xa(x),[x]),C=p??S,w=a(e=>{m(e)},[]),T=p!==null,D=a(()=>{p!==null&&(g(null),u.mutate({blockId:t,patch:p},{onSuccess:()=>m(null),onError:e=>g(e instanceof Error?e.message:String(e))}))},[t,p,u]),k=a(async(e,n)=>{if(ga(e)){b(!0),g(null),v(null);try{p!==null&&(await i.trpcClient.coreBlocks.updateBlockSettings.mutate({blockId:t,patch:p}),m(null)),await i.trpcClient.coreBlocks.updateBlockSettings.mutate({blockId:t,patch:_a(e)}),s.data?.block?.enabled!==!0&&(await f.mutateAsync({blockId:t,enabled:!0}),v(va(e))),await d.mutateAsync({blockId:t}),await l.refetch(),e===`send-tv-schedule-now`?v(`Sending tonight’s schedule now…`):e===`probe-nordvpn-italy`?v(`Probing NordVPN Italy stations (no UniFi change)…`):e===`test-nordvpn-endpoint`?v(`Testing VPN endpoint on UniFi…`):e===`refresh-nordvpn-catalog`?v(`Refreshing NordVPN Italy catalog…`):e===`refresh-unifi-catalog`&&v(`Refreshing UniFi ID catalogs…`)}catch(e){g(e instanceof Error?e.message:String(e))}finally{b(!1)}}},[t,s.data?.block?.enabled,p,d,f,l,i.trpcClient.coreBlocks]);return l.isLoading?e(`p`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[o(O,{className:`h-3.5 w-3.5 animate-spin`}),` `,n(`build.scriptSettingsPanel.loading`)]}):l.isError?e(`p`,{className:`text-xs text-danger`,"data-testid":`script-settings-error`,children:[n(`build.scriptSettingsPanel.couldNotLoadSettings`,`Could not load settings:`),` `,l.error instanceof Error?l.error.message:String(l.error)]}):x===null?null:e(`section`,{className:`space-y-3 rounded border border-border p-3`,"data-testid":`script-settings-panel`,children:[e(`div`,{className:`flex items-center justify-between gap-2`,children:[e(`div`,{children:[o(`h4`,{className:`text-sm font-medium`,children:n(`build.scriptSettingsPanel.settings`,`Settings`)}),o(`p`,{className:`text-xs text-foreground-subtle`,children:o(Z,{i18nKey:`build.scriptSettingsPanel.declaredBy`,components:{code:o(`code`,{})}})})]}),e(G,{size:`sm`,variant:`primary`,onClick:D,disabled:!T||u.isPending||y,children:[u.isPending&&o(O,{className:`h-3.5 w-3.5 animate-spin`}),n(`build.scriptSettingsPanel.saveSettings`,`Save settings`)]})]}),o(Be,{schema:x,values:C,onChange:w,onAction:k}),h===null?null:o(`p`,{className:`text-xs text-danger`,"data-testid":`script-settings-save-error`,children:h}),_===null?null:o(`p`,{className:`text-xs text-foreground-subtle`,"data-testid":`script-settings-info`,children:_})]})}u();var wa=`hub`;function Ta({existing:t,typeDefs:n,typeDefsLoading:i,saving:a,saveError:s,restarting:l,restartError:u,onRestart:p,onSave:m,onCancel:h}){let{t:g}=X(),v=E(),y=ge(),{resolvedMode:b}=De(),x=ne({code:t?.code??da,files:t?.files,entry:t?.entry}),[S,C]=c(t?.name??``),[D,A]=c(x.files),[j,M]=c(x.entry),[N,P]=c(x.entry),[F,I]=c(t?.placement??wa),[L,R]=c(t?.integrationId??``),[B,V]=c([]),[H,ee]=c(!1),[te,re]=c(`blank`),[ie,U]=c(null),[ae,oe]=c(``),se=D[N]??``,ce=e=>{A(t=>({...t,[N]:e}))},le=Object.keys(D).toSorted(),ue=la.length>1,de=r(()=>[...n?.libs??[],...ia(D,N)],[n?.libs,D,N]),W=d({mutationFn:()=>v.trpcClient.coreBlocks.compile.mutate({files:D,entry:j})}),fe=r(()=>B.filter(e=>e.severity>=8),[B]),pe=ca(B),me=S.trim()===``,he=t===null?null:ne(t),_e=t===null||he===null||JSON.stringify(D)!==JSON.stringify(he.files)||j!==he.entry||S.trim()!==t.name||F!==t.placement||(L.trim()===``?void 0:L.trim())!==t.integrationId,ve=()=>{W.reset(),m({name:S.trim(),files:D,entry:j,enabled:t?.enabled??!0,placement:F,...L.trim()===``?{}:{integrationId:L.trim()}})},ye=()=>{let e=ua(Object.keys(D));A(t=>({...t,[e]:``})),P(e),U(e),oe(e)},be=e=>{U(e),oe(e)},xe=()=>{if(ie===null)return;let e=ie,t=ae.trim();if(U(null),!(t===``||t===e)){if(D[t]!==void 0){P(t);return}A(n=>{let r={};for(let[i,a]of Object.entries(n))r[i===e?t:i]=a;return r}),j===e&&M(t),P(t)}},Se=async e=>{let t=la.find(t=>t.id===e);if(t===void 0)return;let n=la.find(e=>e.id===`blank`);!(n!==void 0&&JSON.stringify(D)===JSON.stringify(n.files)&&j===n.entry)&&!await y({title:g(`build.blockEditor.loadExample`,`Load example`),message:g(`build.blockEditor.replaceTheCurrentEditorContents`,`Replace the current editor contents with this example?`),confirmLabel:g(`build.blockEditor.replace`,`Replace`),variant:`warning`})||(re(e),A({...t.files}),M(t.entry),P(t.entry),(S.trim()===``||te===`blank`)&&C(t.id===`blank`?``:t.name))},Ce=t===null?null:zn(t),we=fa({existing:t,dirty:_e,saving:a,restarting:l});return e(`div`,{className:`space-y-4`,children:[Ce!==null&&o(`div`,{className:`flex flex-wrap items-center gap-2`,children:o(J,{variant:Bn(Ce.tone),children:Ce.label})}),e(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[e(`label`,{className:`block text-sm`,children:[o(`span`,{className:`text-foreground-subtle`,children:g(`build.blockEditor.name`,`Name`)}),o(q,{className:`mt-1`,value:S,onChange:e=>C(e.target.value),placeholder:g(`build.blockEditor.whatThisScriptDoes`,`What this script does`)})]}),e(`label`,{className:`block text-sm`,children:[o(`span`,{className:`text-foreground-subtle`,children:g(`build.blockEditor.integrationOptional`,`Integration (optional)`)}),o(q,{className:`mt-1`,value:L,onChange:e=>R(e.target.value),placeholder:g(`build.blockEditor.leaveEmptyForTheShared`,`Leave empty for the shared system integration`)})]})]}),t===null&&ue&&e(`label`,{className:`block text-sm`,children:[o(`span`,{className:`text-foreground-subtle`,children:g(`build.blockEditor.startFrom`,`Start from`)}),o(`select`,{className:`mt-1 w-full rounded border border-border bg-surface px-2 py-1.5 text-sm`,value:te,onChange:e=>void Se(e.target.value),"data-testid":`script-example-select`,children:la.map(t=>e(`option`,{value:t.id,children:[t.name,` — `,t.description]},t.id))})]}),e(`div`,{children:[o(Re,{selectedNodeId:F,onSelect:I,label:g(`build.blockEditor.runsOn`,`Runs on`),alwaysShow:!0}),F!==wa&&e(`p`,{className:`mt-2 flex items-start gap-2 text-xs text-warning`,children:[o(_,{className:`mt-0.5 h-3.5 w-3.5 shrink-0`}),o(`span`,{children:o(Z,{i18nKey:`build.blockEditor.hubOnlyWarning`,components:{strong:o(`strong`,{})}})})]})]}),e(`div`,{className:`flex min-h-[56vh] flex-col rounded border border-border`,children:[e(`div`,{className:`flex flex-wrap items-center gap-1 border-b border-border px-2 py-1.5`,children:[le.map(t=>ie===t?o(q,{value:ae,onChange:e=>oe(e.target.value),onBlur:()=>xe(),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),xe()),e.key===`Escape`&&(e.preventDefault(),U(null))},className:`h-7 w-36 px-2 py-0 text-xs`,autoFocus:!0,"data-testid":`script-file-rename`,"aria-label":g(`build.blockEditor.renameFile`,`Rename file`)},t):e(`button`,{type:`button`,className:`rounded px-2 py-1 text-xs ${t===N?`bg-muted font-medium text-foreground`:`text-foreground-subtle hover:text-foreground`}`,onClick:()=>P(t),onDoubleClick:()=>be(t),title:g(`build.blockEditor.doubleClickToRename`,`Double-click to rename`),"data-testid":`script-file-tab-${t}`,children:[t,t===j?` · ${g(`build.blockEditor.entry`)}`:``]},t)),o(`button`,{type:`button`,className:`ml-1 rounded px-2 py-1 text-xs text-foreground-subtle hover:text-foreground`,onClick:ye,"data-testid":`script-file-add`,children:g(`build.blockEditor.file`,`+ file`)}),N!==j&&o(`button`,{type:`button`,className:`rounded px-2 py-1 text-xs text-foreground-subtle hover:text-foreground`,onClick:()=>M(N),title:g(`build.blockEditor.useThisFileAsThe`,`Use this file as the compile entry`),children:g(`build.blockEditor.setAsEntry`,`Set as entry`)})]}),i?o(`p`,{className:`p-4 text-sm text-foreground-subtle`,children:g(`build.blockEditor.loadingTheNodeSType`,`Loading the node's type definitions…`)}):o(sa,{value:se,onChange:ce,path:`file:///${N}`,extraLibs:de,onDiagnostics:V,dark:b===`dark`,heightPx:560})]}),n!==void 0&&n.libs.length===0&&o(`p`,{className:`text-xs text-warning`,children:g(`build.blockEditor.theNodeReturnedNoType`,`The node returned no type definitions, so this code is NOT being checked against the system's types. The server-side compile still applies on save.`)}),fe.length>0&&e(`div`,{className:`space-y-1 rounded border border-danger/40 bg-danger/10 p-3 text-xs`,children:[o(`p`,{className:`font-medium text-danger`,children:g(`build.blockEditor.errorsCannotSave`,{count:fe.length})}),fe.slice(0,5).map(e=>o(`p`,{className:`text-danger`,children:g(`build.blockEditor.diagnosticLine`,{line:e.line,message:e.message})},`${String(e.line)}:${String(e.column)}:${e.message}`)),fe.length>5&&o(`p`,{className:`text-foreground-subtle`,children:g(`build.blockEditor.moreErrors`,{count:fe.length-5})})]}),W.data!==void 0&&(W.data.ok?e(`p`,{className:`flex items-center gap-2 text-xs text-success`,children:[o(w,{className:`h-3.5 w-3.5`}),` `,g(`build.blockEditor.compiledOk`)]}):e(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:[W.data.line!==void 0&&o(`span`,{className:`mr-1`,children:g(`build.blockEditor.errorLine`,{line:String(W.data.line)})}),W.data.error??g(`build.blockEditor.theCodeDoesNotCompile`,`the code does not compile`)]})),W.error!==null&&e(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:[g(`build.blockEditor.couldNotReachTheCompiler`,`Could not reach the compiler:`),` `,Ea(W.error)]}),s!==null&&o(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:s}),u!==null&&o(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:u}),t!==null&&e(`div`,{className:`space-y-3`,children:[o(Ca,{blockId:t.id}),o(ha,{blockId:t.id})]}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(G,{variant:`outline`,onClick:()=>W.mutate(),disabled:W.isPending||a,title:g(`build.blockEditor.typeCheckOnTheNode`,`Type-check on the node without saving`),children:[W.isPending&&o(O,{className:`h-4 w-4 animate-spin`}),` `,g(`common.compile`)]}),e(G,{onClick:ve,disabled:a||pe||me,children:[a&&o(O,{className:`h-4 w-4 animate-spin`}),` `,g(`common.save`)]}),e(G,{variant:`outline`,onClick:()=>p?.(),disabled:we!==null||p===void 0,title:we??g(`build.blockEditor.stopTheProcessAndLet`,`Stop the process and let the supervisor bring it back`),children:[l?o(k,{className:`h-4 w-4 animate-spin`}):o(k,{className:`h-4 w-4`}),` `,g(`build.blockEditor.restart`,`Restart`)]}),e(G,{variant:`ghost`,onClick:()=>ee(!H),title:g(`build.blockEditor.showThisScriptSProcess`,`Show this script's process logs`),"data-testid":`script-logs-toggle`,children:[o(T,{className:`h-4 w-4`}),` `,g(`common.logs`),` `,H?`▾`:`▸`]}),o(G,{variant:`ghost`,onClick:h,disabled:a,children:g(`common.close`,`Close`)}),e(`span`,{className:`ml-auto text-xs text-foreground-subtle`,children:[g(`build.blockEditor.errorsCount`,{count:fe.length}),_e&&t!==null?` · ${g(`build.blockEditor.unsavedChanges`)}`:``]}),me&&o(J,{variant:`warning`,children:g(`build.blockEditor.nameRequired`,`Name required`)})]}),H&&e(`div`,{className:`rounded border border-border`,"data-testid":`script-logs-panel`,children:[o(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:t===null?g(`build.blockEditor.logsAppearOnceTheScript`,`Logs appear once the script has been saved and started.`):o(f,{children:o(Z,{i18nKey:`build.blockEditor.logsOf`,values:{id:z(t.id)},components:{code:o(`code`,{})}})})}),t!==null&&o(Ne,{addonId:z(t.id),maxHeight:`max-h-[560px]`,showFilters:!1})]})]})}function Ea(e){return e instanceof Error?e.message:String(e)}u();var Da=[`coreBlocks`,`list`],Oa=[`coreBlocks`,`getTypeDefs`],ka=5e3;function Aa(e){return e instanceof Error?e.message:String(e)}function ja({initialBlockId:t,onBlockIdChange:i,createRequested:a=!1,onCreateConsumed:u}={}){let f=S(),{t:p}=X(),m=E(),{state:h,openNew:_,openEdit:v,close:y}=Ae({editKey:`block`,newKey:`new`}),[b,x]=c(null),[C,w]=c(null),[D,O]=c(null),A=l({queryKey:Da,refetchInterval:ka,queryFn:async()=>(await m.trpcClient.coreBlocks.list.query({})).blocks}),j=h.mode!==`closed`,M=l({queryKey:Oa,enabled:j,staleTime:1/0,gcTime:1/0,queryFn:()=>m.trpcClient.coreBlocks.getTypeDefs.query({})}),N=()=>{A.refetch()},P=n(null),F=A.data;s(()=>{t===void 0||P.current===t||F?.find(e=>e.id===t&&ee(e)===`code`)!==void 0&&(P.current=t,v(t),i?.(t))},[t,F,v,i]),s(()=>{a&&(x(null),_(),i?.(null),u?.())},[a,u,i,_]);let I=d({mutationFn:e=>m.trpcClient.coreBlocks.create.mutate({block:e}),onSuccess:e=>{x(e.block),v(e.block.id),i?.(e.block.id),N()}}),L=d({mutationFn:e=>m.trpcClient.coreBlocks.update.mutate(e),onSuccess:e=>{x(e.block),v(e.block.id),i?.(e.block.id),N()}}),R=d({mutationFn:e=>m.trpcClient.coreBlocks.delete.mutate({blockId:e}),onSuccess:()=>{w(null),N()}}),B=d({mutationFn:e=>m.trpcClient.coreBlocks.setEnabled.mutate(e),onSuccess:N}),V=d({mutationFn:e=>m.trpcClient.coreBlocks.restart.mutate({blockId:e}),onSuccess:N}),H=Hn((A.data??[]).filter(e=>ee(e)===`code`)),te=A.data!==void 0&&H.length===0,ne=I.isPending||L.isPending,re=I.error===null?L.error===null?null:Aa(L.error):Aa(I.error),ie=h.mode===`edit`?H.find(e=>e.id===h.id)??(b!==null&&b.id===h.id?b:null):null,U=h.mode===`new`||ie===null?null:Vn(H,ie),oe=r(()=>[{key:`name`,header:p(`build.scriptsTab.name`,`Name`),render:t=>{let n=zn(t),r=je(t.updatedAt,f);return e(`div`,{className:`min-w-0`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(`span`,{className:`truncate font-medium`,children:t.name}),o(J,{variant:Bn(n.tone),children:n.label}),o(J,{variant:`info`,children:t.placement}),r!==null&&o(`span`,{className:`text-xs text-foreground-subtle`,children:p(`common.edited`,{when:r})})]}),o(`p`,{className:`mt-0.5 text-xs text-foreground-subtle`,children:n.detail}),D===t.id&&e(`div`,{className:`mt-2 rounded border border-border`,children:[o(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:o(Z,{i18nKey:`common.logsOf`,values:{id:z(t.id)},components:{code:o(`code`,{})}})}),o(Ne,{addonId:z(t.id),maxHeight:`max-h-64`,showFilters:!1})]})]})},sortValue:e=>e.name,nowrap:!1},{key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,render:t=>{let n=B.isPending||R.isPending,r=V.isPending&&V.variables===t.id;return C===t.id?e(`div`,{className:`flex justify-end gap-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:p(`build.scriptsTab.deleteThisScript`,`Delete this script?`)}),o(G,{variant:`danger`,onClick:()=>R.mutate(t.id),disabled:n,children:p(`common.delete`,`Delete`)}),o(G,{variant:`ghost`,onClick:()=>w(null),children:p(`common.cancel`,`Cancel`)})]}):e(`div`,{className:`flex justify-end gap-1`,children:[o(G,{variant:`ghost`,onClick:e=>{e.stopPropagation(),x(t),v(t.id),i?.(t.id)},title:p(`common.edit`,`Edit`),children:p(`common.edit`,`Edit`)}),o(G,{variant:`ghost`,onClick:e=>{e.stopPropagation(),V.mutate(t.id)},disabled:n||r||!t.enabled,title:t.enabled?p(`build.scriptsTab.restart`,`Restart`):p(`build.scriptsTab.enableItInsteadADisabled`,`Enable it instead — a disabled script has no process`),children:o(k,{className:`h-4 w-4${r?` animate-spin`:``}`})}),o(G,{variant:`ghost`,onClick:e=>{e.stopPropagation(),O(D===t.id?null:t.id)},title:p(`build.scriptsTab.logs`,`Logs`),children:o(T,{className:`h-4 w-4`})}),o(G,{variant:`ghost`,onClick:e=>{e.stopPropagation(),B.mutate({blockId:t.id,enabled:!t.enabled})},disabled:n,title:t.enabled?p(`common.disable`,`Disable`):p(`common.enable`,`Enable`),children:t.enabled?p(`common.disable`,`Disable`):p(`common.enable`,`Enable`)}),o(G,{variant:`ghost`,onClick:e=>{e.stopPropagation(),w(t.id)},title:p(`common.delete`,`Delete`),children:o(g,{className:`h-4 w-4`})})]})}}],[C,D,i,v,R,V.isPending,V.variables,B,p]);return e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:A.data===void 0?``:Un(H)}),A.error!=null&&o(W,{title:p(`build.scriptsTab.couldNotReadTheScripts`,`Could not read the scripts`),message:Aa(A.error),onRetry:N}),o(ue,{columns:oe,rows:H,rowKey:e=>e.id,pageSize:25,maxBodyHeight:Ie,emptyMessage:te?p(`build.scriptsTab.noScriptsYetAScript`,`No scripts yet. A script is TypeScript the hub runs in its own process.`):A.data===void 0?p(`build.scriptsTab.loadingScripts`,`Loading scripts…`):p(`build.scriptsTab.noScriptsYet`,`No scripts yet.`),onRowClick:e=>{x(e),v(e.id),i?.(e.id)}}),o(Ee,{open:j,onClose:()=>{I.reset(),L.reset(),V.reset(),x(null),y(),i?.(null)},title:U===null?p(`build.scriptsTab.newScript`,`New script`):p(`build.scriptsTab.edit`,`Edit {{name}}`,{name:U.name}),icon:ae,width:`xl`,testId:`script-editor-panel`,children:o(Ta,{existing:U,typeDefs:M.data,typeDefsLoading:M.isLoading,saving:ne,saveError:re,restarting:V.isPending,restartError:V.error===null?null:Aa(V.error),onRestart:U===null?void 0:()=>V.mutate(U.id),onSave:e=>{let t=U;t===null?I.mutate(e):L.mutate({blockId:t.id,block:e})},onCancel:()=>{I.reset(),L.reset(),V.reset(),x(null),y(),i?.(null)}})}),R.error!=null&&o(W,{message:Aa(R.error)}),B.error!=null&&o(W,{message:Aa(B.error)}),V.error!=null&&o(W,{message:Aa(V.error)})]})}var Ma=[`automations`,`scripts`,`custom-device`];function Na(e){return e!==null&&Ma.some(t=>t===e)}var Pa=[`coreBlocks`,`list`,`build-counts`],Fa=[`block`,`create`,`new`];function Ia(e){return e.filter(e=>ee(e)===`code`).length}function La(e){return e.filter(e=>rt(e.code)).length}function Ra(e,t){return t===null?e:`${e} (${String(t)})`}function za(){let{t}=X(),n=E(),[r,i]=We(),a=r.get(`tab`),s=Na(a)?a:`automations`,c=r.get(`create`)===`1`,u=l({queryKey:Pa,refetchInterval:5e3,queryFn:async()=>(await n.trpcClient.coreBlocks.list.query({})).blocks}).data,d=u===void 0?null:Ia(u),f=u===void 0?null:La(u),m=l({queryKey:[`coreBlocks`,`listCompositions`,`build-counts`],refetchInterval:1e4,queryFn:async()=>n.trpcClient.coreBlocks.listCompositions.query({})}),h=m.data?.state===`loaded`?m.data.views.length:null,g=e=>{i(t=>{let n=new URLSearchParams(t);return n.set(`tab`,`scripts`),n.delete(`create`),e===void 0?n.delete(`block`):n.set(`block`,e),n},{replace:!0})},_=e=>{i(t=>{let n=new URLSearchParams(t);return n.set(`tab`,`automations`),n.delete(`create`),e===null?n.delete(`block`):n.set(`block`,e),n},{replace:!0})},v=e=>{i(t=>{let n=new URLSearchParams(t);return n.set(`tab`,`scripts`),n.delete(`create`),e===null?n.delete(`block`):n.set(`block`,e),n},{replace:!0})},y=()=>{i(e=>{let t=new URLSearchParams(e);return t.set(`create`,`1`),t.delete(`block`),t},{replace:!0})},x=e=>{i(()=>{let t=new URLSearchParams(window.location.search);return t.set(`tab`,`custom-device`),t.delete(`block`),t.delete(`create`),t.set(`new`,e),t},{replace:!0})},S=()=>{i(()=>{let e=new URLSearchParams(window.location.search);return e.delete(`create`),e},{replace:!0})},C=s===`automations`?`New automation`:`New script`,w=Ve(`/build`,{t,isAdmin:!0})??{icon:b,title:t(`nav.build`,`Build-your-self`)};return o(Je,{icon:w.icon,title:w.title,subtitle:t(`build.automationsScriptsAndComposedDevices`,`Automations, scripts and composed devices — what this installation does on its own.`),defaultSection:`automations`,sectionsLabel:`${w.title} sections`,fill:!0,actions:s===`custom-device`?e(`div`,{className:`flex flex-wrap gap-2`,children:[e(G,{type:`button`,variant:`outline`,onClick:()=>x(`blank`),"data-testid":`build-new-composition`,children:[o(p,{className:`h-4 w-4`}),` `,t(`helper.newComposition`)]}),e(G,{type:`button`,onClick:()=>x(`helper`),"data-testid":`build-new-helper`,children:[o(p,{className:`h-4 w-4`}),` `,t(`helper.newHelper`)]})]}):e(G,{type:`button`,onClick:y,"data-testid":`build-new`,children:[o(p,{className:`h-4 w-4`}),` `,C]}),sections:[{id:`automations`,label:Ra(`Automations`,f),ownedParams:Fa,content:o(Yn,{onOpenScripts:g,initialBlockId:s===`automations`?r.get(`block`)??void 0:void 0,onBlockIdChange:_,createRequested:s===`automations`&&c,onCreateConsumed:S})},{id:`scripts`,label:Ra(`Scripts`,d),ownedParams:Fa,content:o(ja,{initialBlockId:s===`scripts`?r.get(`block`)??void 0:void 0,onBlockIdChange:v,createRequested:s===`scripts`&&c,onCreateConsumed:S})},{id:`custom-device`,label:Ra(`Custom Device`,h),ownedParams:Fa,content:o(Sr,{createRequested:s===`custom-device`&&c,onCreateConsumed:S})}]})}export{za as BuildPage};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{C as e,J as t,K as n,R as r,S as i,V as a,Y as o,a as s,et as c,o as l,t as u,x as d}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{Bn as f,Br as p,Ci as m,Ct as h,D as g,Dn as _,G as v,J as y,K as b,Kn as x,Lt as S,O as C,Oi as w,Qt as T,Ri as E,Sn as D,T as O,V as k,Vr as A,W as j,Yn as M,Yr as ee,Z as N,Zn as te,Zr as ne,_t as P,bn as re,ca as ie,dt as F,fn as ae,ht as oe,mi as se,mn as I,na as L,nr as R,ot as z,q as ce,qn as B,r as le,sr as ue,t as de,tn as fe,ui as V,ur as H,wr as pe,xn as me,yn as he,z as ge,zi as _e}from"./player-overlays-BoPcGTkt.js";import{Bi as ve,Fn as ye,Gt as be,Hi as U,In as xe,Jt as Se,Kt as W,Lr as Ce,Nn as we,Pn as Te,Ri as Ee,Ta as De,Vi as G,Wn as Oe,Wr as ke,Xt as Ae,Yt as je,bi as Me,d as K,pi as Ne,qt as Pe,ti as Fe,ui as Ie,wa as Le,xa as Re}from"./client-xX9FBBul.js";import{t as ze}from"./archive-DwK992kq.js";import{i as Be,n as Ve,r as He,t as Ue}from"./scan-eye-COINNEut.js";import{t as We}from"./bell-off-BT9N_y5z.js";import{t as Ge}from"./boxes-Brm6PKBJ.js";import{n as Ke}from"./video-BM3o6nmQ.js";import{t as qe}from"./circle-slash-DbVS3C3N.js";import{t as Je}from"./layers-71beSjbX.js";import{$ as Ye,$t as Xe,At as Ze,Bl as Qe,Bn as $e,Cn as et,Co as tt,Cr as nt,Ct as rt,En as it,Eo as at,Er as q,Es as ot,Fa as st,Fc as ct,Fr as lt,Ft as ut,Ga as dt,Gc as ft,Gt as pt,Ha as mt,Hn as ht,Hr as gt,Ht as _t,I as vt,Ia as yt,Ii as bt,Ir as xt,It as St,Ja as Ct,Jn as wt,Jo as Tt,Jt as Et,Ko as Dt,Kt as Ot,La as kt,Lr as At,Ma as jt,Mn as Mt,Mo as Nt,Mt as Pt,Nn as Ft,Or as It,Pn as Lt,Pt as Rt,Qi as zt,Qo as Bt,Qr as Vt,R as Ht,Rr as Ut,Rt as Wt,Sd as Gt,So as Kt,Sr as qt,Td as Jt,Tl as Yt,Ts as Xt,Uc as Zt,Un as Qt,Uo as $t,Vn as en,Vt as tn,Wa as nn,Wc as rn,Wn as an,Wt as on,X as sn,Xt as cn,Y as ln,Ya as un,Yn as dn,Yt as fn,Zc as pn,Zt as mn,_r as hn,a as gn,ao as _n,at as vn,bo as yn,br as bn,bs as xn,bt as Sn,c as Cn,cc as wn,dd as Tn,dr as En,ei as J,en as Dn,et as On,fd as kn,fl as An,fr as jn,gc as Mn,gd as Nn,gi as Pn,gl as Fn,gr as In,hl as Ln,ho as Rn,i as zn,id as Bn,it as Vn,ja as Hn,jn as Un,ko as Wn,l as Gn,li as Kn,ln as qn,lo as Jn,md as Yn,ml as Xn,mo as Zn,mr as Qn,nl as $n,nt as er,o as tr,ot as nr,pd as rr,pl as ir,pr as ar,qa as or,qc as sr,qr as cr,r as lr,rt as ur,si as dr,tn as fr,ud as pr,ui as mr,vc as hr,vd as gr,vo as _r,vr,wd as yr,ws as br,wt as xr,xn as Sr,xo as Cr,yd as wr,yn as Tr,yo as Er,yr as Dr,zn as Or,zo as kr,zt as Ar}from"./src-B9Sp1iss.js";import{t as Y}from"./i18n-B_TdOOX_.js";import{t as X}from"./useTranslation-BJr-n0es.js";import"./mount-BqREn4Hm.js";import{$n as jr,A as Mr,D as Nr,E as Pr,O as Fr,cr as Ir,er as Lr,hr as Rr,ir as zr,j as Br,k as Vr,lr as Hr,mr as Ur,nr as Wr,or as Z,p as Gr,pr as Kr,rr as qr,sr as Jr,tr as Yr,ur as Xr}from"./index-Df_Bqvin.js";import{A as Zr,C as Qr,D as $r,E as ei,F as ti,G as ni,H as ri,I as ii,K as ai,L as oi,M as si,N as ci,O as li,P as ui,R as di,S as fi,T as pi,U as mi,V as hi,W as gi,_ as _i,a as vi,b as yi,c as bi,d as xi,f as Si,g as Ci,h as wi,i as Ti,j as Ei,k as Di,l as Oi,m as ki,n as Ai,o as ji,p as Mi,q as Ni,r as Pi,s as Fi,t as Ii,v as Li,w as Ri,x as zi,y as Bi,z as Vi}from"./HelperWizard-DS_R_NlR.js";import{r as Hi,t as Ui}from"./assignment-candidates-BfYuVkll.js";import{_ as Wi,b as Gi,i as Ki,m as qi,o as Ji,t as Yi}from"./step-inspector-model-BPPs6HSK.js";import"./useEventInvalidation-BqREn4Hm.js";import{t as Xi}from"./use-stationary-objects-BXlbjYsd.js";import{n as Zi,t as Qi}from"./format-DZdW_-La.js";import{a as $i,i as ea,n as ta,o as na,r as ra,s as ia,t as aa}from"./linked-devices-model-CGjAZM4f.js";import{t as oa}from"./authed-media-2wArFI8C.js";c();function sa(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 ca(e){if(typeof e!=`object`||!e)return null;let t=e.switches;if(!Array.isArray(t))return null;let n=t.map(sa).filter(e=>e!==null);return n.length===0?null:n}var la=[[/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 ua(e){for(let[t,n]of la)if(t.test(e))return n;return`generic`}function da(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(Y.t(`helpers.cameraSwitchRows.off`,{list:r(t)})),n.length>0&&i.push(Y.t(`helpers.cameraSwitchRows.unknown`,{list:r(n)})),{offIds:t,unknownIds:n,summary:i.length===0?Y.t(`helpers.cameraSwitchRows.allOn`):i.join(` · `)}}var fa={stream:D,detection:Ue,privacy:p,microphone:te,speaker:h,listening:Ve,archive:ze,recording:He,notifications:E,generic:fe};function pa({deviceId:t}){let{t:n}=X(),a=l(),s=Number.isFinite(t),[c,u]=o(null),[d,f]=o(!1),p=sr({deviceId:t},{enabled:s});lr([`pipelineOrchestrator`,`getCameraSwitches`],[`capability.binding-changed`]);let m=ca(p.data),h=Fn({onError:(e,n)=>{console.error(`[CameraFunctionSwitches] switch write failed — reverting`,{tags:{deviceId:t},meta:{switchId:n.switchId,error:e instanceof Error?e.message:String(e)}}),a.invalidateQueries({queryKey:[[`pipelineOrchestrator`,`getCameraSwitches`]]}),u({id:n.switchId,message:e instanceof Error?e.message:String(e)})},onSuccess:()=>{u(null),a.invalidateQueries({queryKey:[[`pipelineOrchestrator`]]}),a.invalidateQueries({queryKey:[[`deviceManager`]]}),a.invalidateQueries({queryKey:[[`recording`]]})}}),g=r(e=>{!e.available||e.on===null||h.mutate({deviceId:t,switchId:e.id,enabled:!e.on})},[t,h]);if(m===null)return null;let _=da(m),v=e=>c?.id===e.id?c.message:null;return e(kn,{open:d,onOpenChange:f,children:[e(Yn,{"aria-label":n(`device.cameraFunctionSwitches.cameraFunctions`,`Camera functions`),title:_.summary,className:`inline-flex items-center gap-1 rounded-lg border px-2 py-1.5 text-[11px] font-medium transition-colors ${c===null?_.offIds.length>0?`border-warning/40 text-warning hover:bg-warning/10`:`border-border text-foreground-subtle hover:text-foreground hover:bg-surface-hover`:`border-danger/50 text-danger bg-danger/5`}`,children:[i(fe,{className:`h-3.5 w-3.5`}),i(`span`,{className:`hidden lg:inline`,children:n(`device.cameraFunctionSwitches.functions`,`Functions`)}),_.offIds.length>0&&i(`span`,{className:`rounded bg-warning/20 px-1 text-[9px] font-semibold uppercase tracking-wide`,children:n(`device.cameraFunctionSwitches.offCount`,{count:_.offIds.length})})]}),e(rr,{align:`end`,className:`min-w-[240px] max-h-[60vh] overflow-y-auto p-1`,children:[i(`div`,{className:`px-2 py-1 text-[10px] uppercase tracking-wider text-foreground-subtle`,children:n(`device.cameraFunctionSwitches.cameraFunctions`,`Camera functions`)}),i(`ul`,{className:`space-y-0.5`,children:m.map(e=>i(`li`,{children:i(ma,{row:e,failure:v(e),onToggle:()=>g(e)})},e.id))})]})]})}function ma({row:t,failure:n,onToggle:r}){let{t:a}=X(),o=fa[ua(t.label)],s=t.on===null,c=t.on===!1,l=n===null?s?t.unavailableReason??`The source that owns this did not answer.`:t.costWhenOff:`Write failed: ${n}`,u=n===null?s?t.unavailableReason??`unknown`:null:`write failed`;return e(`button`,{type:`button`,role:`switch`,"aria-label":t.label,"aria-checked":t.on===!0,disabled:!t.available,onClick:r,title:l,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:[i(o,{className:`h-3.5 w-3.5 shrink-0 ${n===null?s?`text-foreground-subtle/50`:c?`text-warning`:`text-success`:`text-danger`}`}),e(`span`,{className:`flex-1 min-w-0 truncate`,children:[t.label,u!==null&&e(`span`,{className:`ml-1 text-[10px] text-foreground-subtle`,children:[`· `,u]})]}),i(`span`,{className:`shrink-0 rounded px-1 py-0.5 text-[9px] font-semibold uppercase tracking-wide ${s?`bg-surface-hover text-foreground-subtle/60`:c?`bg-warning/20 text-warning`:`bg-success/20 text-success`}`,children:s?`—`:a(c?`common.off`:`common.on`)})]})}function ha({deviceId:t}){let n=tn(z().trpcClient,t);return n===null?null:e(`a`,{href:n.url,target:`_blank`,rel:`noopener noreferrer`,title:`${n.label} — ${n.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:[i(A,{className:`h-3.5 w-3.5`}),i(`span`,{className:`hidden sm:inline`,children:n.label})]})}function ga({parentDeviceId:t}){let{t:n}=X(),r=Kr(),a=z(),{data:o,isLoading:s,isError:c}=zr(t),{data:l}=_r({deviceId:t},{enabled:Number.isFinite(t)});if(s)return i(`div`,{className:`rounded-lg border border-border bg-surface p-3`,children:i(`p`,{className:`text-[10px] text-foreground-subtle`,children:n(`common.loading`,{defaultValue:`Loading…`})})});if(c)return i(`div`,{className:`rounded-lg border border-border bg-surface p-3`,children:i(`p`,{className:`text-[10px] text-warning`,children:n(`integrations.childrenLoadError`,{defaultValue:`Failed to load children`})})});let u=(o??[]).filter(e=>e.display?.hidden!==!0);if(u.length===0)return null;let d=St(l?.stableId??``,u,l?.childLayout),f=d.ungrouped,p=e=>r(`/devices/${String(e)}`),m=l?.name??``,h=(e,t)=>i(Rt,{trpc:a.trpcClient,device:{...t,name:_t(t,m)},variant:`minimal`,onNavigate:p},e),g=f.some(e=>!!e.role),_=f.some(e=>!e.role),v=g&&!_?n(`device.accessories`,{defaultValue:`Accessories`}):!g&&_?n(`device.adoptedDevices`,{defaultValue:`Adopted devices`}):n(`device.children`,{defaultValue:`Children`}),y=f.length>0?e(`div`,{className:`rounded-lg border border-border bg-surface p-3`,children:[i(`div`,{className:`text-[10px] font-semibold uppercase tracking-wide text-foreground-subtle mb-1.5`,children:v}),i(`div`,{className:`space-y-1`,children:f.map(e=>h(e.id,e))})]}):null,b=d.disabledSection===void 0?null:i(ut,{title:n(`device.disabledSection`,{defaultValue:`Disabled`}),count:d.disabledSection.children.length,defaultOpen:!1,children:i(`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:e(`div`,{className:`space-y-2`,children:[y,b]});let x=_&&!g;return e(`div`,{className:`space-y-2`,children:[x?y:null,d.sections.map(e=>i(ut,{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 _a({deviceId:e}){let t=z(),{data:n,isLoading:r}=qr(e),{data:a,isLoading:o}=zr(e),s=r||o,c=(a??[]).map(e=>({id:e.id,stableId:e.stableId,type:e.type,name:e.name,features:e.features,...e.sourceInfo?{sourceInfo:{id:e.sourceInfo.id}}:{}})),l=typeof n?.linkDeviceId==`number`?n.linkDeviceId:null,u=typeof n?.primaryChildEntityId==`string`?n.primaryChildEntityId:null;return s?i(`div`,{className:`h-full min-h-32 w-full animate-pulse rounded-lg bg-surface`,"aria-hidden":`true`}):i(`div`,{className:`flex h-full w-full flex-col`,children:i(on,{trpc:t.trpcClient,children:c,linkDeviceId:l,primaryChildEntityId:u})})}c();function va({dev:t,busy:n,setBusy:r}){let{t:a}=X(),s=t?.motionTrigger,c=y(t?.state.motionTrigger),[l,u]=o(!1);if(!s)return null;let d=c?.enabled===!0,f=c!==void 0,p=async()=>{if(n||!f)return;let e=!d;r(!0),u(!0);try{await s.setMotionTrigger({enabled:e})}finally{r(!1),u(!1)}},m=l?d?`Disabling…`:`Enabling…`:f?d?`On motion: on`:`On motion: off`:`On motion: …`;return e(`button`,{type:`button`,onClick:()=>{p()},disabled:n||!f,title:f?d?a(`hero.motionTriggerToggle.disableTriggerOnMotion`,`Disable trigger on motion`):a(`hero.motionTriggerToggle.enableTriggerOnMotion`,`Enable trigger on motion`):a(`hero.motionTriggerToggle.awaitingState`,`Awaiting state…`),"aria-pressed":d,className:`inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-[11px] font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${d?`border-primary/50 bg-primary/15 text-primary`:`border-border bg-surface text-foreground-subtle hover:text-foreground`}`,children:[i(L,{className:`h-3 w-3`}),i(`span`,{children:m})]})}c();function Q({deviceId:t,deviceType:n,features:r}){let a=z(),s=Et(n)?.HeroCard??fn,c=b(a.trpcClient,t),l=y(c?.state.deviceStatus),[u,d]=o(!1),f=l!==void 0&&l.online===!1,p=f?l.lastChangedAt:null;return e(`div`,{className:`flex h-full w-full flex-col items-stretch gap-3 p-3 sm:p-4`,children:[f?i(`div`,{className:`flex justify-center`,children:i(Ot,{lastChangedAt:p})}):null,i(s,{trpc:a.trpcClient,deviceId:t,features:r}),i(`div`,{className:`flex justify-center`,children:i(va,{dev:c,busy:u,setBusy:d})})]})}function ya({deviceId:e,features:t}){return i(`div`,{className:`flex h-full w-full flex-col items-stretch gap-3 p-3 sm:p-4`,children:i(cn,{trpc:z().trpcClient,deviceId:e,features:t})})}function ba({deviceId:e,features:t}){return i(`div`,{className:`flex h-full w-full flex-col items-stretch p-3 sm:p-4`,children:i(fn,{trpc:z().trpcClient,deviceId:e,features:t})})}function xa(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=xa(e.data);return t===null?e.eventType:Y.t(`helpers.eventEmitterFormat.buttonHeadline`,{channel:String(t),eventType:e.eventType})}var Ca=1e3,wa=60*Ca,Ta=60*wa,Ea=24*Ta;function Da(e,t){if(e==null||e<=0)return`—`;let n=t-e;return n<Ca?Y.t(`helpers.relativeTime.justNow`):n<wa?Y.t(`helpers.relativeTime.secondsAgo`,{count:Math.floor(n/Ca)}):n<Ta?Y.t(`helpers.relativeTime.minutesAgo`,{count:Math.floor(n/wa)}):n<Ea?Y.t(`helpers.relativeTime.hoursAgo`,{count:Math.floor(n/Ta)}):Y.t(`helpers.relativeTime.daysAgo`,{count:Math.floor(n/Ea)})}c();var Oa=1500,ka=15e3,Aa=1e3;function ja({deviceId:n}){let{t:r}=X(),s=b(z().trpcClient,n)?.state.eventEmitter,c=y(s);a(()=>{if(!s)return;s.refresh();let e=setInterval(()=>{s.refresh()},ka);return()=>{clearInterval(e)}},[s]);let l=c?.lastEvent??null,u=l?.seq??null,d=t(null),[f,p]=o(!1);a(()=>{if(u===null)return;let e=d.current;if(d.current=u,e===null||e===u)return;p(!0);let t=setTimeout(()=>{p(!1)},Oa);return()=>{clearTimeout(t)}},[u]);let[m,h]=o(()=>Date.now());a(()=>{let e=setInterval(()=>{h(Date.now())},Aa);return()=>{clearInterval(e)}},[]);let g=Sa(l),_=c?.eventTypes??[],v=c?.eventCountSinceStart??0,S=c!==void 0,C=xa(l?.data);return e(`div`,{className:`flex h-full w-full flex-col items-center justify-center gap-3 p-4`,children:[i(`div`,{"data-testid":`event-emitter-indicator`,"data-flashing":String(f),className:`flex h-24 w-24 items-center justify-center rounded-full border-2 transition-all ${f?`border-primary bg-primary/20 text-primary shadow-lg shadow-primary/30 scale-105`:`border-border bg-surface text-foreground-subtle`}`,"aria-live":`polite`,title:g??r(`hero.eventEmitterHero.noPressRecorded`,`No press recorded`),children:i(f?x:pe,{className:`h-10 w-10`})}),e(`div`,{className:`text-center`,children:[C!==null&&i(`div`,{className:`text-xs font-semibold uppercase tracking-wide text-primary`,children:r(`hero.eventEmitterHero.button`,`Button {{value1}}`,{value1:String(C)})}),i(`div`,{"data-testid":`event-emitter-headline`,className:`text-sm font-semibold ${g?`text-foreground`:`text-foreground-subtle`}`,children:g??(S?r(`hero.eventEmitterHero.noPressRecorded`,`No press recorded`):r(`hero.eventEmitterHero.awaitingState`,`Awaiting state…`))}),i(`div`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:l?Da(l.timestamp,m):r(`hero.eventEmitterHero.waitingForTheFirstEvent`,`Waiting for the first event`)})]}),_.length>0&&i(`div`,{className:`flex max-w-full flex-wrap justify-center gap-1`,children:_.map(e=>i(`span`,{"data-testid":`event-emitter-chip`,className:`rounded-full border px-2 py-0.5 text-[10px] font-medium ${e===l?.eventType?`border-primary bg-primary/15 text-primary`:`border-border bg-surface text-foreground-subtle`}`,children:e},e))}),i(`div`,{className:`text-[10px] text-foreground-subtle`,children:r(`hero.eventEmitterHero.sinceStart`,{count:v})})]})}function Ma({deviceName:t,deviceType:n,provider:r,isOnline:a,features:o}){let{t:s}=X();return e(`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:[i(Jr,{type:r,size:`lg`}),e(`div`,{children:[i(`div`,{className:`text-sm font-semibold text-foreground`,children:t}),i(`div`,{className:`text-[10px] text-foreground-subtle uppercase tracking-wider mt-0.5`,children:n})]}),e(`div`,{className:`flex items-center gap-2 flex-wrap justify-center`,children:[i(vn,{status:a?`online`:`offline`}),o.length>0&&i(Ir,{capabilities:o})]}),i(`div`,{className:`text-[10px] text-foreground-subtle italic max-w-xs mt-1`,children:s(`hero.genericHero.noLiveViewForThis`,`No live view for this device type. Use the Config tab or the shortcut row to interact.`)})]})}c();function Na({deviceId:t}){let{t:r}=X(),a=l(),o=nn({deviceId:t},{refetchInterval:1e4,retry:!1}),s=dt({onSuccess:()=>{a.invalidateQueries({queryKey:[[`deviceDiscovery`,`listDiscovered`]]}),a.invalidateQueries({queryKey:[[`deviceDiscovery`,`getStatus`]]})}}),c=n(()=>Pa(o.data??[]),[o.data]);return e(`div`,{className:`flex h-full w-full flex-col gap-3 p-3 sm:p-4`,children:[e(`div`,{className:`flex flex-wrap items-stretch gap-2 sm:gap-3`,children:[i(Fa,{label:r(`hero.hubHero.discovered`,`Discovered`),value:c.total,icon:i(f,{className:`h-3.5 w-3.5`})}),i(Fa,{label:r(`hero.hubHero.adopted`,`Adopted`),value:c.adopted,accent:`success`}),i(Fa,{label:r(`hero.hubHero.available`,`Available`),value:c.available,accent:c.available>0?`primary`:void 0}),e(`button`,{type:`button`,onClick:()=>{s.mutateAsync({deviceId:t}).catch(()=>{})},disabled:s.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:[s.isPending?i(ue,{className:`h-3.5 w-3.5 animate-spin`}):i(me,{className:`h-3.5 w-3.5`}),i(`span`,{className:`hidden sm:inline`,children:r(`hero.hubHero.discover`,`Discover`)})]})]}),e(`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:[i(Ia,{icon:i(oe,{className:`h-3 w-3 text-emerald-500`}),label:r(`hero.hubHero.online`,`{{online}} online`,{online:c.online})}),i(Ia,{icon:i(B,{className:`h-3 w-3 text-amber-500`}),label:r(`hero.hubHero.sleeping`,`{{sleeping}} sleeping`,{sleeping:c.sleeping})}),i(Ia,{icon:i(P,{className:`h-3 w-3 text-destructive`}),label:r(`hero.hubHero.offline`,`{{offline}} offline`,{offline:c.offline})}),c.unknown>0?i(Ia,{icon:i(V,{className:`h-3 w-3 text-foreground-subtle`}),label:r(`hero.hubHero.unknown`,`{{unknown}} unknown`,{unknown:c.unknown})}):null]})]})}function Pa(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 Fa({label:t,value:n,icon:r,accent:a}){return e(`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 ${a===`success`?`bg-emerald-500/10 border-emerald-500/30 text-emerald-500`:a===`primary`?`bg-primary/10 border-primary/30 text-primary`:`bg-surface-hover border-border text-foreground`}`,children:[e(`div`,{className:`flex items-center gap-1.5 text-[10px] uppercase tracking-wider opacity-70 truncate`,children:[r,i(`span`,{className:`truncate`,children:t})]}),i(`div`,{className:`text-xl sm:text-2xl font-semibold tabular-nums leading-none`,children:n})]})}function Ia({icon:t,label:n}){return e(`span`,{className:`inline-flex items-center gap-1`,children:[t,i(`span`,{children:n})]})}var La={[U.Switch]:Q,[U.Siren]:Q,[U.Light]:Q,[U.Sensor]:Q,[U.Button]:Q,[U.Hub]:Na,[U.Cover]:ya,[U.Valve]:Q,[U.Humidifier]:Q,[U.WaterHeater]:Q,[U.Container]:_a,[U.Lock]:Q,[U.Fan]:Q,[U.Thermostat]:Q,[U.Climate]:Q,[U.MediaPlayer]:Q,[U.Control]:Q,[U.AlarmPanel]:Q,[U.EventEmitter]:ja,[U.Notifier]:ba,[U.Script]:Q,[U.Automation]:Q,[U.Presence]:Q,[U.Update]:Q,[U.Vacuum]:Q,[U.LawnMower]:Q,[U.Weather]:Q,[U.Image]:Q,[U.PetFeeder]:Q,[U.Dishwasher]:Q};function Ra(e){return La[e]??Ma}function za({deviceId:e}){let t=ce(z().trpcClient,e,e=>e.runningState);if(t===void 0||t.running!==!0&&t.running!==!1)return i(d,{});let n=t.running;return i(Ft,{running:n,since:t?.since??null,phase:t?.phase??null,className:`px-3 pt-2 sm:px-4`})}function Ba(t){let n=Ra(t.deviceType);return e(d,{children:[i(za,{deviceId:t.deviceId}),i(n,{...t})]})}function Va({deviceId:e,widgets:t}){return t.length===0?null:i(`div`,{className:`flex flex-col gap-3 px-3 pb-3 sm:px-4 sm:pb-4`,"data-testid":`device-hero-widgets`,children:t.map(t=>{let n=i(En,{widgetId:t.widgetId,deviceId:t.deviceId});return i(`div`,{children:t.deviceId===e?n:i(cr,{deviceId:t.deviceId,children:n})},t.widgetId)})})}function Ha(e){return e.sections.filter(e=>e.location===`hero`).flatMap(t=>t.fields.flatMap(n=>{if(typeof n!=`object`||!n)return[];let r=Reflect.get(n,`type`),i=Reflect.get(n,`widgetId`);return r!==`widget`||typeof i!=`string`||i.length===0?[]:[{widgetId:i,deviceId:e.deviceId,order:t.order??0}]}))}function Ua(e){let t=Ha(e),n=new Set(t.map(e=>e.widgetId)),r=e.child===void 0?[]:Ha(e.child),i=[...t,...r.filter(e=>!n.has(e.widgetId))],a=new Set;return i.filter(e=>a.has(e.widgetId)?!1:(a.add(e.widgetId),!0)).sort((e,t)=>e.order-t.order)}function Wa(e){return tr(z().trpcClient,e)}c();function Ga(e){let[n,i]=o(`idle`),[s,c]=o(null),l=t(null),u=t(null),d=t(null),f=t(!0),p=Xt(),m=br(),h=ot(),g=r(()=>{if(l.current){try{l.current.close()}catch{}l.current=null}if(u.current){for(let e of u.current.getTracks())try{e.stop()}catch{}u.current=null}d.current=null},[]),_=r(async()=>{if(n===`idle`)return;i(`stopping`);let t=d.current;if(t&&e!==null)try{await Promise.race([h.mutateAsync({deviceId:e,sessionId:t}),new Promise((e,t)=>setTimeout(()=>t(Error(`server stopSession timeout`)),2e3))])}catch(e){console.warn(`[intercom] server stopSession failed (continuing teardown)`,e)}g(),f.current&&(i(`idle`),c(null))},[n,e,h,g]),v=r(async()=>{if(e===null||n!==`idle`&&n!==`error`)return;c(null);let t=null,r=null,a=null;try{i(`requesting-mic`),t=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}),u.current=t,i(`starting`);let n=await p.mutateAsync({deviceId:e});a=n.sessionId,d.current=a,i(`connecting`),r=new RTCPeerConnection,l.current=r,r.oniceconnectionstatechange=()=>{if(!f.current)return;let e=r.iceConnectionState;e===`connected`||e===`completed`?i(`talking`):(e===`failed`||e===`closed`||e===`disconnected`)&&f.current&&(c(e===`failed`?`WebRTC connection failed`:null),_())};for(let e of t.getAudioTracks())r.addTrack(e,t);await r.setRemoteDescription({type:`offer`,sdp:n.sdpOffer});let o=await r.createAnswer();await r.setLocalDescription(o);let s=r.localDescription?.sdp??o.sdp??``;await m.mutateAsync({deviceId:e,sessionId:a,sdpAnswer:s})}catch(n){let o=n instanceof Error?n.message:String(n);if(console.warn(`[intercom] start failed`,n),r)try{r.close()}catch{}if(t)for(let e of t.getTracks())try{e.stop()}catch{}if(l.current=null,u.current=null,a!==null)try{await h.mutateAsync({deviceId:e,sessionId:a})}catch{}d.current=null,f.current&&(c(o),i(`error`))}},[e,n,p,m,h,_]);return a(()=>(f.current=!0,()=>{f.current=!1;let t=d.current;if(t!==null&&e!==null&&h.mutate({deviceId:e,sessionId:t}),l.current){try{l.current.close()}catch{}l.current=null}if(u.current){for(let e of u.current.getTracks())try{e.stop()}catch{}u.current=null}d.current=null}),[e]),{state:n,error:s,start:v,stop:_,isTalking:n===`talking`}}c();var Ka=0;function $(){return++Ka}function qa(e){switch(e.type){case`system`:return`system`;case`device`:return`#${e.deviceId}`;case`provider`:return e.providerId;case`addon`:return e.addonId}}function Ja(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 Ya(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 Xa(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 Za({scope:n,greeting:s,className:c}){let{t:l}=X(),d=z(),[f,p]=o(()=>{let e=[];return s&&e.push({id:$(),kind:`info`,text:s}),e.push({id:$(),kind:`info`,text:`scope: ${qa(n)} — type help or context for available commands`}),e}),[m,h]=o(``),[g,_]=o([]),[v,y]=o(-1),b=t(null),x=t(null);a(()=>{let e=x.current;e&&(e.scrollTop=e.scrollHeight)},[f]);let S=r(()=>{b.current?.focus()},[]),C=u({mutationFn:e=>d.trpcClient.repl.execute.mutate({code:e,scope:n}),onSuccess:e=>{let t=e??{},n=typeof t.output==`string`?t.output:e==null?`undefined`:typeof e==`string`?e:JSON.stringify(e,null,2),r=t.type===`error`;p(e=>[...e,{id:$(),kind:r?`error`:`result`,text:n}])},onError:e=>{let t=e instanceof Error?e.message:String(e);p(e=>[...e,{id:$(),kind:`error`,text:t}])}});function w(e){let t=e.trim();if(t){if(t===`clear`){p([{id:$(),kind:`info`,text:`scope: ${qa(n)}`}]),h(``);return}if(t===`help`){p(e=>[...e,{id:$(),kind:`input`,text:`> ${t}`},...Ja(n).map(e=>({id:$(),kind:`info`,text:e}))]),h(``);return}if(t===`context`){p(e=>[...e,{id:$(),kind:`input`,text:`> ${t}`},...Xa(n).map(e=>({id:$(),kind:`info`,text:e}))]),h(``);return}if(t===`examples`){p(e=>[...e,{id:$(),kind:`input`,text:`> ${t}`},...Ya(n).map(e=>({id:$(),kind:`info`,text:e}))]),h(``);return}_(e=>[...e,t]),y(-1),p(e=>[...e,{id:$(),kind:`input`,text:`> ${t}`}]),h(``),C.mutate(t)}}function T(e){if(e.key===`Enter`){e.preventDefault(),w(m);return}if(e.key===`ArrowUp`){if(e.preventDefault(),g.length===0)return;let t=v===-1?g.length-1:Math.max(0,v-1);y(t),h(g[t]??``);return}if(e.key===`ArrowDown`){if(e.preventDefault(),v===-1)return;let t=v+1;t>=g.length?(y(-1),h(``)):(y(t),h(g[t]??``));return}e.ctrlKey&&e.key===`l`&&(e.preventDefault(),p([{id:$(),kind:`info`,text:`scope: ${qa(n)}`}]))}let E={input:`text-zinc-300`,result:`text-emerald-300`,error:`text-red-300`,info:`text-zinc-400`};return e(`div`,{className:`flex flex-col bg-[#0c0a09] rounded-lg border border-border overflow-hidden font-mono text-xs ${c??``}`,onClick:S,children:[e(`div`,{ref:x,className:`flex-1 overflow-y-auto p-3 space-y-1 min-h-[120px]`,children:[f.map(e=>i(`pre`,{className:`whitespace-pre-wrap break-words leading-relaxed ${E[e.kind]}`,children:e.text},e.id)),C.isPending&&i(`span`,{className:`text-zinc-500 animate-pulse`,children:l(`shared.replTerminal.thinking`,`…thinking`)})]}),e(`div`,{className:`flex items-center gap-2 border-t border-zinc-800 px-3 py-2 bg-[#0c0a09]`,children:[i(`span`,{className:`text-emerald-400 flex-shrink-0 select-none font-bold`,children:l(`shared.replTerminal.text`,`>`)}),i(`input`,{ref:b,value:m,onChange:e=>h(e.target.value),onKeyDown:T,disabled:C.isPending,placeholder:`device.state.battery.value`,autoFocus:!0,className:`flex-1 bg-transparent text-zinc-100 placeholder:text-zinc-600 focus:outline-none caret-emerald-400 disabled:opacity-50`,spellCheck:!1,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`off`})]})]})}function Qa(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}}}c();function $a({deviceId:e,intercomAvailable:t=!1}){let r=z(),a=typeof window<`u`?N():``,o=Number.isFinite(e),s=Wa(o?e:null),c=Xi(o?[e]:[]),l=n(()=>{if(!o)return;let e=[];for(let t of c.rows){let n=gn(t);n!==null&&e.push(n)}return e},[o,c.rows]),{streams:u,pipelineMetrics:f,createSession:p,sendAnswer:m,handleOffer:h,getIceServers:g,addIceCandidate:_,getIceCandidates:y,closeSession:b,getSessionState:x,applyDownlinkProbe:S}=Tr(r.trpcClient,o?e:null),C=v(o?e:null,{width:io}),w=Ga(o&&t?e:null),T=w.state===`requesting-mic`||w.state===`starting`||w.state===`connecting`||w.state===`stopping`,E=w.isTalking||T,D=()=>{w.state===`idle`||w.state===`error`?w.start():w.state!==`stopping`&&w.stop()},O=le(),k=nt(),A=typeof window<`u`?window.localStorage.getItem(`camstack_admin_token`):null,j=Qa(k.request,A),M=O.length>0?i(d,{children:O.map(e=>i(`div`,{className:`absolute inset-0`,children:e.node},e.id))}):null;return i(ln,{serverUrl:a,createSession:p,sendAnswer:m,handleOffer:h,getIceServers:g,addIceCandidate:_,getIceCandidates:y,closeSession:b,getSessionState:x,applyDownlinkProbe:S,...j===null?{}:{...j,onExitPlayback:()=>k.clear()},streams:u,pipelineMetrics:f,phase:s.phase,detections:s,...l===void 0?{}:{stationaryObjects:l},defaultShowDetections:!0,defaultShowMotion:!0,showPlayStop:!0,snapshotSrc:C.src,...C.src?{posterUrl:C.src}:{},snapshotLoading:C.loading,onRefreshSnapshot:C.refresh,intercomAvailable:t,intercomShown:E,onIntercomToggle:D,extraOverlay:M,chromeless:!0,className:`h-full`})}function eo({deviceId:e,containerDeviceId:t}){let{t:n}=X();return Number.isFinite(e)?i(`div`,{className:`flex flex-col h-full`,children:i(fr,{...t===void 0?{deviceId:e}:{containerDeviceId:t},limit:50,maxHeight:`max-h-full`,showScope:!1,showFilters:!1})}):i(`div`,{className:`flex items-center justify-center h-full text-[11px] text-foreground-subtle italic`,children:n(`device.panelContent.notLoaded`,{id:e})})}function to({deviceId:e}){let{t}=X();if(!Number.isFinite(e))return i(`div`,{className:`flex items-center justify-center h-full text-[11px] text-foreground-subtle italic`,children:t(`device.panelContent.notLoaded`,{id:e})});let n=[`CamStack REPL — device #${e}`,``,` device.state.battery.value sync state read`,` await device.snapshot.getSnapshot({}) cap action`,``,` type 'examples' for more, 'context' for the full API`].join(`
|
|
2
|
-
`);return i(Za,{scope:{type:`device`,deviceId:e},greeting:n,className:`h-full border-0 rounded-none`})}function no({deviceId:e}){let{t}=X();return Number.isFinite(e)?i(`div`,{className:`flex flex-col h-full overflow-y-auto`,children:i(Dn,{deviceId:e,limit:50,maxHeight:`max-h-full`})}):i(`div`,{className:`flex items-center justify-center h-full text-[11px] text-foreground-subtle italic`,children:t(`device.panelContent.notLoaded`,{id:e})})}function ro({deviceId:e}){let{t}=X();return Number.isFinite(e)?i(`div`,{className:`flex flex-col h-full overflow-y-auto`,children:i(Xe,{deviceId:e,limit:50,maxHeight:`max-h-full`})}):i(`div`,{className:`flex items-center justify-center h-full text-[11px] text-foreground-subtle italic`,children:t(`device.panelContent.notLoaded`,{id:e})})}var io=960;function ao({initialName:e,label:t=`Name`,layout:n=`inline`,bound:r}){return i(Z,{label:t,layout:n,value:i(`input`,{type:`text`,value:r.value,"aria-label":t,placeholder:e,onChange:e=>r.onChange(e.target.value),className:`flex-1 min-w-0 w-full px-1.5 py-0.5 text-[11px] bg-background border border-border rounded focus:outline-none focus:border-primary`})})}c();function oo({label:t=`Location`,layout:r=`inline`,bound:a}){let{t:o}=X(),{data:s}=at(),c=s??[],l=a.value.trim().toLowerCase(),u=n(()=>l.length===0?[]:c.filter(e=>e.toLowerCase()!==l&&e.toLowerCase().includes(l)),[c,l]);return i(Z,{label:t,layout:r,value:e(`div`,{className:`relative`,children:[i(`input`,{type:`text`,value:a.value,"aria-label":t,onChange:e=>a.onChange(e.target.value),placeholder:o(`shared.locationRow.roomAreaOrLeaveEmpty`,`Room / area (or leave empty to clear)`),className:`flex-1 min-w-0 w-full px-1.5 py-0.5 text-[11px] bg-background border border-border rounded focus:outline-none focus:border-primary`}),u.length>0&&i(`div`,{className:`absolute z-10 left-0 right-0 mt-0.5 max-h-40 overflow-y-auto rounded-md border border-border bg-surface shadow-md`,children:u.map(t=>e(`button`,{type:`button`,onClick:()=>a.onChange(t),className:`w-full flex items-center gap-2 px-2 py-1 text-left text-[11px] hover:bg-surface-hover`,children:[i(R,{className:`h-3 w-3 text-foreground-subtle flex-shrink-0`}),i(`span`,{className:`truncate`,children:t})]},t))})]})})}var so=`w-full min-w-0 px-1.5 py-0.5 text-[11px] bg-background border border-border rounded focus:outline-none focus:border-primary disabled:opacity-50 disabled:cursor-not-allowed`,co=0,lo=10;function uo(e){if(e.trim()===``)return``;let t=Number.parseInt(e,10);return Number.isFinite(t)?String(t<co?co:t>lo?lo:t):``}function fo({value:e,onChange:t,disabled:n=!1,placeholder:r,className:a,id:o,"aria-label":s}){return i(`input`,{type:`number`,min:co,max:lo,step:1,id:o,className:a??so,"aria-label":s,placeholder:r,value:e,onChange:e=>{t(uo(e.target.value))},disabled:n})}function po({deviceName:t,value:n,inheritedIcon:r,inheritedLabel:a,disabled:o,onChange:s}){let{t:c}=X(),l={trigger:c(`deviceDisplay.pickIcon`,{name:t}),panel:c(`deviceDisplay.iconFor`,{name:t}),searchPlaceholder:c(`deviceDisplay.iconSearchPlaceholder`),clear:a,noMatches:c(`deviceDisplay.iconNoMatches`)};return e(`div`,{className:`flex items-center gap-2`,children:[i(Tn,{value:n===``?null:n,onPick:e=>s(e??``),categoryLabel:e=>c(`deviceDisplay.iconCategory.${e}`,{defaultValue:ke(e)}),fallbackGlyph:r,labels:l,disabled:o}),i(`span`,{className:`text-[11px] text-foreground-subtle`,children:n===``?a:n})]})}var mo=`w-full min-w-0 px-1.5 py-0.5 text-[11px] bg-background border border-border rounded focus:outline-none focus:border-primary disabled:opacity-50`;function ho(e){if(e.trim()===``)return;let t=Number.parseInt(e,10);return Number.isFinite(t)?t:void 0}function go({device:t,role:n,display:r,onChange:a}){let o=ie();wr();let{t:s}=X(),c=l(),u=n===null?void 0:mn[n],f=u?.kind===`numeric`,p=n!==null||t.parentDeviceId!==null&&t.parentDeviceId!==void 0,m=t.sourceInfo?.quantity,h=u?.kind===`numeric`?u.quantity??(m!==void 0&&m!==`device`?m:void 0):void 0,g=h===void 0?void 0:Re(h),_=g===void 0?void 0:Oe(g),{data:v}=yn({},{staleTime:6e4,enabled:n!==null}),y=Dt({onSuccess:()=>{c.invalidateQueries({queryKey:[[`deviceManager`]]})}}),b=()=>{if(n===null)return;let e=ho(r.precision),t={...r.icon===``?{}:{icon:r.icon},...r.unit===``?{}:{unit:r.unit},...e===void 0?{}:{precision:e}};y.mutate({defaults:{...v?.defaults,[n]:t}})},x=n===null?void 0:v?.defaults?.[n]?.icon,S=x===void 0?void 0:gr(x),C=n===null?yr(t.type,o):Gt(n,o),w={icon:S??C.icon,label:S===void 0?C.label:String(x)},T=n===null&&t.type===U.Container?s(`deviceDisplay.inheritedContainer`):S===void 0?s(`deviceDisplay.inherited`,{name:w.label}):s(`deviceDisplay.inheritedRoleDefault`,{icon:w.label,role:C.label}),E=n===null?``:Gt(n,o).label;return e(`div`,{className:`mt-3 divide-y divide-border border-t border-border`,children:[i(Z,{label:s(`deviceDisplay.icon`),value:i(po,{deviceName:t.name,value:r.icon,inheritedIcon:w.icon,inheritedLabel:T,disabled:!1,onChange:e=>a({icon:e})})}),p&&i(Z,{label:s(`deviceDisplay.label`),value:i(`input`,{type:`text`,className:mo,"aria-label":s(`deviceDisplay.label`),placeholder:n===null?t.name:E,value:r.label,onChange:e=>a({label:e.target.value})})}),f&&e(d,{children:[i(Z,{label:s(`deviceDisplay.unit`),value:i(vt,{dimension:_,value:r.unit,onChange:e=>a({unit:e}),disabled:!1,"aria-label":s(`deviceDisplay.unit`),inheritLabel:s(`deviceDisplay.unitSource`,{unit:g===void 0?``:` (${g})`}),emptyReason:s(`deviceDisplay.unitSource`,{unit:``})})}),i(Z,{label:s(`deviceDisplay.precision`),value:i(fo,{"aria-label":s(`deviceDisplay.precision`),placeholder:s(`deviceDisplay.precisionInherit`),value:r.precision,onChange:e=>a({precision:e}),disabled:!1})})]}),n!==null&&i(`div`,{className:`px-3 sm:px-4 py-2`,children:i(J,{type:`button`,variant:`outline`,size:`sm`,onClick:b,disabled:y.isPending,title:s(`deviceDisplay.setRoleDefaultTitle`,{role:E}),children:s(`deviceDisplay.setRoleDefault`,{role:E})})})]})}function _o(e){return typeof e.linkDeviceId==`number`}var vo=new Set(Object.values(G));function yo(e){return vo.has(e)}var bo={[U.Switch]:[G.Siren,G.Floodlight,G.Spotlight,G.PirSensor,G.Chime,G.Autotrack,G.Nightvision,G.PrivacyMask,G.BinaryHelper],[U.Light]:[G.Floodlight,G.Spotlight,G.Nightvision],[U.Siren]:[G.Siren],[U.Button]:[G.Doorbell],[U.Sensor]:[G.MotionSensor,G.ContactSensor,G.LeakSensor,G.SmokeSensor,G.COSensor,G.GasSensor,G.TamperSensor,G.VibrationSensor,G.ConnectivitySensor,G.SoundSensor,G.BinarySensor,G.TemperatureSensor,G.HumiditySensor,G.AmbientLightSensor,G.PressureSensor,G.WindSensor,G.RainSensor,G.UvSensor,G.SolarRadiationSensor,G.SoilMoistureSensor,G.PowerSensor,G.EnergySensor,G.VoltageSensor,G.CurrentSensor,G.AirQualitySensor,G.BatterySensor,G.NumericSensor,G.EnumSensor,G.DateTimeSensor,G.GenericSensor],[U.Control]:[G.NumericControl,G.SelectControl,G.TextControl,G.DateTimeControl],[U.Notifier]:[G.MobilePushNotifier,G.MessagingNotifier,G.EmailNotifier,G.GenericNotifier]};function xo(e){for(let t of Object.values(U))if(t===e)return!0;return!1}function So(e){return xo(e)?bo[e]??[]:[]}function Co(e,t){let n=So(t);return e==null||e===``||n.includes(e)?n:[...n,e]}function wo({device:t}){let{t:n}=X(),r=ie(),a=Yr(),o=a?.identity??null,s=o?.name??t.name,c=o?.location??t.location??``,l=o?.role??t.role??null,u=o?.display.hidden??t.display?.hidden===!0,d=a!==null&&o!==null;return e(`section`,{"aria-label":n(`customize.identity.title`),className:`${C} ${g}`,children:[e(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4`,children:[d?i(ao,{deviceId:t.id,initialName:s,label:n(`customize.identity.name`),layout:`stacked`,bound:{value:s,onChange:a.setIdentityName}}):i(Z,{label:n(`customize.identity.name`),layout:`stacked`,value:s}),d?i(oo,{deviceId:t.id,initialLocation:c,label:n(`customize.identity.room`),layout:`stacked`,bound:{value:c,onChange:a.setIdentityLocation}}):i(Z,{label:n(`customize.identity.room`),layout:`stacked`,value:c===``?n(`common.unset`):c}),i(Z,{label:n(`customize.identity.type`),layout:`stacked`,value:t.type}),i(Z,{label:n(`customize.identity.hidden`),layout:`stacked`,value:i(an,{"aria-label":n(`deviceDisplay.hideFromLists`),checked:u,disabled:!d,onChange:e=>a?.setIdentityDisplay({hidden:e.target.checked})})}),i(Z,{label:n(`customize.identity.role`),layout:`stacked`,value:_o(t)||!d?i(`span`,{children:To(l,n(`customize.identity.noRole`),r)}):i(Bn,{"aria-label":n(`customize.identity.role`),value:l??``,options:[{value:``,label:n(`customize.identity.noRole`)},...Co(l,t.type).map(e=>({value:e,label:To(e,n(`customize.identity.noRole`),r)}))],onChange:e=>a.setIdentityRole(e.target.value===``?null:e.target.value)})})]}),o!==null&&a!==null&&i(go,{device:t,role:l,display:o.display,onChange:a.setIdentityDisplay})]})}function To(e,t,n){return e==null||e===``?t:yo(e)?Gt(e,n).label:e}function Eo(e){let t=Te({draft:{kind:`pulse`,cap:e.cap,targetId:e.targetId,enabled:e.enabled,debounceMs:e.debounceMs,...e.edges===void 0?{}:{edges:[...e.edges]},sources:e.sources.map(e=>({addonId:e.addonId,stableId:e.stableId,cap:e.cap,fieldPath:e.fieldPath}))},device:e.device,changedAtFields:e.sources.map(e=>e.changedAtField)});return t.ok?t.value:null}function Do(e){let t=ye({draft:{kind:`span`,cap:e.cap,targetId:e.targetId,timeoutMs:e.timeoutMs,...e.cooldownMs===void 0?{}:{cooldownMs:e.cooldownMs},sources:e.sources.map(e=>({addonId:e.addonId,stableId:e.stableId,cap:e.cap,fieldPath:e.fieldPath,mode:e.mode}))},device:e.device});return t.ok?t.value:null}function Oo(e,t){return{deviceId:e,config:t.config}}function ko(e,t){return{deviceId:e,patch:{motionCooldownMs:t}}}async function Ao(e,t,n,r){await n(Oo(e,t)),await r(ko(e,t.timeoutMs))}c();function jo(t){let{t:n}=X(),r=t.mode===`change`?n(`customize.scalar.changeTitle`,{title:t.title}):n(`customize.scalar.addTitle`,{title:t.title});return i(jn,{open:t.open,onOpenChange:e=>!e&&t.onClose(),children:e(Qn,{width:`xl`,placement:`sheet-on-mobile`,scroll:`body`,"aria-label":r,children:[i(hn,{children:i(vr,{children:r})}),t.open?i(Mo,{...t}):null]})})}function Mo(t){let{t:r}=X(),a=Kt({projection:`slim`}),s=Di(n(()=>a.status===`success`?ui(a.data):[],[a.status,a.data]),t.sources[0]),[c,l]=o(()=>No(t.sources)),[u,f]=o(null),[p,m]=o(!1);!p&&s!==null&&(f(s),m(!0));let[h,g]=o(t.edge),[_,v]=o(t.debounceMs/1e3),y=Po(c),b=y.length===0?null:Eo({cap:t.cap,targetId:t.targetId,device:t.target,enabled:t.enabled,debounceMs:Math.round(_*1e3),edges:[h],sources:y}),x=y[0]??null,S=Bt({deviceId:c[0]?.deviceId??0}),C=Io(S.status===`success`?S.data:void 0,x),w=je(Pe,C,Math.round(_*1e3));return e(d,{children:[e(ar,{className:`flex flex-col gap-3 p-2 sm:p-4`,children:[i(`p`,{className:`text-[11px] text-foreground-muted`,children:r(`customize.event.pulseBody`)}),i(li,{kind:`event`,shape:`pulse`,enabled:t.open,hostId:t.host.id,devicePickerTestId:`event-pulse-picker`,destination:{cap:t.cap,targetId:t.targetId,title:t.title},device:u,picked:c,onDeviceChange:f,onPickedChange:l,edges:t.edges,edge:h,onEdgeChange:g,debounceSec:_,onDebounceSecChange:v,sourceModes:[],timeoutSec:0,onTimeoutSecChange:()=>void 0,cooldownSec:null,onCooldownSecChange:()=>void 0}),C.kind===`level`?i(`p`,{role:`status`,className:`text-[11px] text-foreground-subtle`,children:r(Fo(C,w.lastPressedAt))}):null]}),e(In,{className:`flex flex-wrap gap-2`,children:[i(J,{variant:`ghost`,onClick:t.onClose,children:r(`customize.scalar.cancel`)}),i(J,{"data-testid":`event-save`,disabled:!t.canSave||b===null,onClick:()=>{b!==null&&t.onSave(b)},children:r(`customize.scalar.save`)})]})]})}function No(e){return e.map(e=>({deviceId:0,addonId:e.addonId,stableId:e.stableId,cap:e.cap,fieldPath:e.fieldPath,deviceName:e.stableId,changedAtField:e.changedAtField}))}function Po(e){return e.map(e=>({addonId:e.addonId,stableId:e.stableId,cap:e.cap,fieldPath:e.fieldPath,changedAtField:e.changedAtField??Ee[e.cap]??`lastChangedAt`}))}function Fo(e,t){return e.kind===`unread`?`customize.event.previewWaiting`:e.active&&t===null?`customize.event.previewAlreadyOn`:t===null?`customize.event.previewQuiet`:`customize.event.previewCounted`}function Io(e,t){if(e===void 0||t===null)return{kind:`unread`};let n=e[t.cap],r=n===void 0?void 0:ci(n,t.fieldPath),i=Ee[t.cap]??t.changedAtField,a=n===void 0?void 0:ci(n,i);return typeof r==`boolean`?{kind:`level`,active:r,changedAt:typeof a==`number`&&Number.isFinite(a)?a:null}:{kind:`unread`}}function Lo(e,t,n){if(e===`pending`)return{kind:`pending`,seconds:null};if(e===`unknown`||e==null)return{kind:`unknown`,seconds:null};if(!e)return{kind:`quiet`,seconds:null};let r=Ro(t,n);return r===null?{kind:`unknown`,seconds:null}:{kind:`active`,seconds:r}}function Ro(e,t){if(e==null||!Number.isFinite(e)||e<Qi)return null;let n=Math.floor((t-e)/1e3);return n<0?0:n}function zo(e,t){if(e===`pending`)return{kind:`pending`,lastPressedAt:null,pressCount:null};if(e===`unknown`)return{kind:`unknown`,lastPressedAt:null,pressCount:null};let n=typeof e==`number`&&Number.isFinite(e)&&e>=Qi?e:null,r=typeof t==`number`&&Number.isFinite(t)&&t>=0?t:null;return n===null?{kind:`none`,lastPressedAt:null,pressCount:r}:{kind:`ring`,lastPressedAt:n,pressCount:r}}c();var Bo={id:0,name:``,type:`unknown`,stableId:``,parentDeviceId:null};function Vo({device:t,handle:n,availability:r,cap:a,title:s,view:c}){let{t:l,i18n:u}=X(),f=ti(),[p,m]=o(!1),[h,g]=o(null),_=mi(n.state),v=ii(_,a),y=Uo(n,v),b=y.kind===`known`&&y.value!==null?we({feature:y.value,device:n.target,cap:a,targetId:c.id,timestampPath:c.timestampPath,counterPath:c.counterPath}):null,x=b!==null,S=ni(x),C=b?.draft.sources[0]??null,w=C===null||S.kind!==`known`?null:S.value.find(e=>Me({addonId:e.addonId,stableId:e.stableId})===Me(C))??null,T=Wo(x,S.kind,w!==null),E=xt(w===null?Bo:Zr(w),`compact`),D=xt(t,`full`),O=be({cap:a,targetId:c.id,device:n.target,timestampPath:c.timestampPath,counterPath:c.counterPath,apply:c.apply,stored:y,sourcePresence:T,sourceUnknownReason:S.kind===`unknown`?S.reason:null}),k=n.state.kind===`none`||n.state.kind===`present`;if(r.kind===`absent`||!c.deviceTypes.includes(t.type))return null;let A=async e=>{let t=await n.save(e);g(t.kind===`refused`?t.reason:null)},j=Go(b),M=b?.draft.edges?.[0],ee=M!==void 0&&c.edges.includes(M)?M:c.defaultEdge,N=C===null?``:ri(C.cap,C.fieldPath,u.language),te=y.kind===`known`&&y.value===null,ne=!x&&y.kind===`known`&&y.value!==null;return e(d,{children:[i(Ni,{id:a,icon:_e,title:s,testId:`event-card-${a}`,actions:e(d,{children:[v!==null&&e(`label`,{className:`flex items-center gap-1.5 text-[11px] text-foreground`,children:[i(an,{"aria-label":l(`customize.doorbell.active`),checked:v.enabled!==!1,disabled:!k||n.saving,onChange:e=>{A(di(_,n.target,{...v,enabled:e.target.checked}))}}),l(`customize.doorbell.active`)]}),i(dr,{children:l(pi(O.text,O.status.state))})]}),children:i(`div`,{className:`flex flex-col gap-2 px-3 py-2 sm:px-4`,children:r.kind===`pending`||r.kind===`present`&&!k?i(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:l(`customize.event.checking`)}):r.kind===`unknown`?i(q,{title:l(`customize.scalar.unreadable`),message:r.reason}):e(d,{children:[x&&C!==null&&i(`p`,{className:`text-xs text-foreground`,children:l(`customize.scalar.override`,{name:w===null?C.stableId:E,field:N})}),x&&i(Ho,{deviceId:t.id,cap:a,timestampPath:c.timestampPath,counterPath:c.counterPath,startedAt:n.state.kind===`present`?n.state.view.block.createdAt:null}),ne&&v!==null&&e(`p`,{className:`text-xs text-foreground flex flex-wrap items-center gap-1`,children:[l(`customize.doorbell.otherFormula`),i(zi,{handle:n,cap:a,fieldPath:c.counterPath})]}),te&&i(`p`,{className:`text-xs text-foreground-subtle`,children:l(`customize.scalar.noOverride`)}),h!==null&&i(`p`,{role:`alert`,className:`text-xs text-danger break-words`,children:h}),e(`div`,{className:`flex flex-wrap gap-2`,children:[x&&i(J,{variant:`outline`,size:`sm`,disabled:n.saving,onClick:()=>m(!0),children:l(`customize.scalar.change`)}),x&&i(J,{variant:`ghost`,size:`sm`,disabled:n.saving,onClick:()=>{if(_===null)return;let e=Vi(_,a);f(l(`customize.doorbell.removeWhat`,{name:w===null?D:E}),e===null).then(t=>{t&&A(e)})},children:l(`customize.scalar.remove`)}),te&&i(J,{variant:`outline`,size:`sm`,"data-testid":`event-add-${a}`,disabled:n.saving,onClick:()=>m(!0),children:l(`customize.scalar.add`)})]})]})})}),i(jo,{open:p,mode:x?`change`:`add`,title:s,cap:a,targetId:c.id,host:t,target:n.target,enabled:v?.enabled!==!1,debounceMs:b?.draft.debounceMs??c.debounceMs,edges:c.edges,edge:ee,sources:j,canSave:k&&!n.saving,onClose:()=>m(!1),onSave:e=>{m(!1),A(di(_,n.target,e))}})]})}function Ho({deviceId:t,cap:n,timestampPath:r,counterPath:a,startedAt:o}){let{t:s}=X(),c=si({deviceId:t,cap:n,path:r}),l=si({deviceId:t,cap:n,path:a}),u=zo(c.kind===`pending`?`pending`:c.kind!==`value`||typeof c.value!=`number`?`unknown`:c.value,l.kind===`value`&&typeof l.value==`number`?l.value:null);return u.kind===`pending`?i(`p`,{role:`status`,className:`text-[11px] text-foreground-subtle`,children:s(`customize.event.checking`)}):u.kind===`unknown`?i(`p`,{role:`status`,className:`text-[11px] text-foreground-subtle`,children:s(`customize.event.doorbellLast.unknown`)}):u.kind===`none`?e(`p`,{role:`status`,className:`text-[11px] text-foreground-subtle`,children:[s(`customize.event.doorbellLast.none`,{when:o===null?``:Zi(o)}),u.pressCount===null?``:` · ${s(`customize.event.doorbellCount`,{count:u.pressCount})}`]}):e(`p`,{role:`status`,className:`text-[11px] text-foreground`,children:[s(`customize.event.doorbellLast.ring`,{when:Zi(u.lastPressedAt)}),u.pressCount===null?``:` · ${s(`customize.event.doorbellCount`,{count:u.pressCount})}`]})}function Uo(e,t){return e.state.kind===`pending`?{kind:`pending`}:e.state.kind===`unknown`||e.state.kind===`not-loaded`?{kind:`unknown`,reason:e.state.reason}:{kind:`known`,value:t}}function Wo(e,t,n){return e?t===`pending`?`pending`:t===`unknown`?`unknown`:n?`present`:`absent`:`present`}function Go(e){return e===null?[]:e.draft.sources.map((t,n)=>({addonId:t.addonId,stableId:t.stableId,cap:t.cap,fieldPath:t.fieldPath,changedAtField:e.changedAtFields[n]??``}))}c();function Ko(t){let{t:n}=X(),r=t.mode===`change`?n(`customize.scalar.changeTitle`,{title:t.title}):n(`customize.scalar.addTitle`,{title:t.title});return i(jn,{open:t.open,onOpenChange:e=>!e&&t.onClose(),children:e(Qn,{width:`xl`,placement:`sheet-on-mobile`,scroll:`body`,"aria-label":r,children:[i(hn,{children:i(vr,{children:r})}),t.open?i(qo,{...t}):null]})})}function qo(t){let{t:r}=X(),a=Kt({projection:`slim`}),s=Di(n(()=>a.status===`success`?ui(a.data):[],[a.status,a.data]),t.sources[0]),[c,l]=o(()=>Jo(t.sources)),[u,f]=o(null),[p,m]=o(!1);!p&&s!==null&&(f(s),m(!0));let[h,g]=o(t.timeoutMs/1e3),[_,v]=o((t.cooldownMs??0)/1e3),y=Yo(c),b=Do({cap:t.cap,targetId:t.targetId,device:t.target,timeoutMs:Math.round(h*1e3),cooldownMs:t.cooldownMs===null?void 0:Math.round(_*1e3),sources:y}),x=c[0];return e(d,{children:[e(ar,{className:`flex flex-col gap-3 p-2 sm:p-4`,children:[i(`p`,{className:`text-[11px] text-foreground-muted`,children:r(`customize.event.spanBody`)}),i(li,{kind:`event`,shape:`span`,enabled:t.open,hostId:t.host.id,devicePickerTestId:`event-span-picker`,destination:{cap:t.cap,targetId:t.targetId,title:t.title},device:u,picked:c,onDeviceChange:f,onPickedChange:e=>l(e.filter(e=>!(e.addonId===t.host.addonId&&e.stableId===t.host.stableId))),edges:[],edge:`rising`,onEdgeChange:()=>void 0,debounceSec:0,onDebounceSecChange:()=>void 0,sourceModes:t.sourceModes,timeoutSec:h,onTimeoutSecChange:g,cooldownSec:t.cooldownMs===null?null:_,onCooldownSecChange:v}),x!==void 0&&i(Xo,{deviceId:x.deviceId,cap:x.cap,fieldPath:x.fieldPath,timeoutMs:Math.round(h*1e3)})]}),e(In,{className:`flex flex-wrap gap-2`,children:[i(J,{variant:`ghost`,onClick:t.onClose,children:r(`customize.scalar.cancel`)}),i(J,{"data-testid":`event-save`,disabled:!t.canSave||b===null,onClick:()=>{b!==null&&t.onSave(b)},children:r(`customize.scalar.save`)})]})]})}function Jo(e){return e.map(e=>({deviceId:0,addonId:e.addonId,stableId:e.stableId,cap:e.cap,fieldPath:e.fieldPath,deviceName:e.label.length>0?e.label:e.stableId,mode:e.mode}))}function Yo(e){return e.map(e=>({addonId:e.addonId,stableId:e.stableId,cap:e.cap,fieldPath:e.fieldPath,mode:e.mode??`in-addition`,label:e.deviceName}))}function Xo({deviceId:e,cap:t,fieldPath:n,timeoutMs:r}){let{t:a}=X(),o=si({deviceId:e,cap:t,path:n}),s=o.kind===`value`&&typeof o.value==`boolean`?{kind:`level`,active:o.value,changedAt:null}:{kind:`unread`},c=Ae(Se,s,{timeoutMs:r,cooldownMs:0,nowMs:Date.now()});return s.kind===`unread`?null:i(`p`,{role:`status`,className:`text-[11px] text-foreground-subtle`,children:a(Zo(s,c.open))})}function Zo(e,t){return e.kind===`unread`?`customize.event.previewWaiting`:t?`customize.event.previewMotionOn`:e.active?`customize.event.previewSensorOn`:`customize.event.previewMotionOff`}c();function Qo({device:n,availability:r,cap:a,title:s,view:c,sensors:l}){let{t:u}=X(),f=ir(),p=ct(),m=Pn({addonId:`pipeline-orchestrator`,deviceId:n.id,nodeId:`hub`}),[h,g]=o(!1),[_,v]=o(null),y=t(!1),[b,x]=o(!1),S=es(l),C=ni(!0),w=W(c.id,S),T=is(Wi(m.data).motionCooldownMs,c.timeoutMs);if(r.kind===`absent`||!c.deviceTypes.includes(n.type))return null;let E=b||f.isPending||p.isPending,D=w.writable&&!E&&r.kind===`present`,O=async e=>{if(!w.writable||y.current){v(u(`customize.saveInFlight`));return}y.current=!0,x(!0);try{await Ao(n.id,e,async e=>{await f.mutateAsync({deviceId:e.deviceId,config:e.config===null?null:{sensors:e.config.sensors.map(e=>({addonId:e.addonId,stableId:e.stableId,mode:e.mode}))}})},async e=>{let t={motionCooldownMs:e.patch.motionCooldownMs};await p.mutateAsync({deviceId:e.deviceId,patch:t})}),v(null),await l.refetch()===`failed`&&v(u(`customize.motion.refetchFailed`))}catch(e){v(e instanceof Error?e.message:String(e))}finally{y.current=!1,x(!1)}},k=w.rows.map(e=>({addonId:e.addonId,stableId:e.stableId,cap:`binary`,fieldPath:`on`,mode:e.mode,label:e.name}));return e(d,{children:[i(Ni,{id:a,icon:L,title:s,testId:`event-card-${a}`,actions:i(dr,{children:u(pi(w.text,w.status.state))}),children:i(`div`,{className:`flex flex-col gap-2 px-3 py-2 sm:px-4`,children:r.kind===`pending`||S.kind===`pending`?i(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:u(`customize.motion.reading`)}):r.kind===`unknown`||S.kind===`unknown`?i(ts,{reason:rs(S)||(r.kind===`unknown`?r.reason:``)}):e(d,{children:[i($o,{deviceId:n.id}),w.rows.length===0?i(`p`,{className:`text-xs text-foreground-subtle`,children:u(`customize.scalar.noOverride`)}):i(`ul`,{className:`flex flex-col gap-1`,children:w.rows.map(t=>e(`li`,{className:`text-xs text-foreground`,children:[i(ns,{row:t,fleet:C}),t.reason===null?``:` — ${u(`customize.motion.state.${t.state}`)}`]},t.key))}),i(`p`,{className:`text-[11px] text-foreground-subtle`,children:u(`customize.event.timeoutSeconds`,{seconds:T/1e3})}),_!==null&&i(`p`,{role:`alert`,className:`text-xs text-danger break-words`,children:_}),i(`div`,{className:`flex flex-wrap gap-2`,children:i(J,{variant:`outline`,size:`sm`,"data-testid":`event-add-${a}`,disabled:!D,onClick:()=>g(!0),children:w.rows.length===0?u(`customize.scalar.add`):u(`customize.scalar.change`)})})]})})}),i(Ko,{open:h,mode:w.rows.length===0?`add`:`change`,title:s,cap:a,targetId:c.id,host:n,target:{addonId:n.addonId,stableId:n.stableId},timeoutMs:T,cooldownMs:c.cooldownMs,sourceModes:c.sourceModes,sources:k,canSave:D,onClose:()=>g(!1),onSave:e=>{g(!1),O(e)}})]})}function $o({deviceId:e}){let{t}=X(),n=si({deviceId:e,cap:`motion`,path:`detected`}),r=si({deviceId:e,cap:`motion`,path:`lastDetectedAt`}),a=Lo(n.kind===`pending`?`pending`:n.kind!==`value`||typeof n.value!=`boolean`?`unknown`:n.value,r.kind===`value`&&typeof r.value==`number`?r.value:null,Date.now());return i(`p`,{role:`status`,className:`text-xs text-foreground`,children:t(a.kind===`active`?`customize.event.motionNow.active`:`customize.event.motionNow.${a.kind}`,a.seconds===null?void 0:{seconds:a.seconds})})}function es(e){return e.presence===`pending`?{kind:`pending`}:e.status===null?{kind:`unknown`,reason:e.failureReason}:{kind:`known`,value:e.status}}function ts({reason:e}){let{t}=X(),n=e.trim();return n.length===0?i(q,{message:t(`customize.motion.unreadableBare`)}):i(q,{title:t(`customize.motion.unreadable`,{reason:n}),message:n})}function ns({row:e,fleet:t}){let n=Ut();if(t.kind!==`known`)return e.name;let r=t.value.find(t=>t.addonId===e.addonId&&t.stableId===e.stableId);return r===void 0?e.name:Ei(Zr(r),t.value.map(Zr),n)}function rs(e){return e.kind===`unknown`?e.reason??``:e.kind===`known`&&e.value.state===`unreadable`?e.value.reason:``}function is(e,t){return e!==null&&Number.isFinite(e)?e:t}var as=xe;function os(e,t){let n=as[e];return n===void 0?null:n.targets.find(e=>e.id===t)??null}function ss({device:e,handle:t,facts:n,sensors:r}){let{t:a}=X();return i(d,{children:ei().map(o=>{let s=o.pulse??o.span;if(s===null||!s.deviceTypes.includes(e.type))return null;let c=os(o.cap,s.id);if(c===null)return null;let l=a(o.pulse===null?`customize.motion.title`:`customize.doorbell.title`),u=fi(Ri(o.cap,c),n);return o.pulse===null?o.span===null?null:i(Qo,{device:e,availability:u,cap:o.cap,title:l,view:o.span,sensors:r},o.cap):i(Vo,{device:e,handle:t,availability:u,cap:o.cap,title:l,view:o.pulse},o.cap)})})}function cs({id:t,icon:n,title:r,headerControl:a,addLabel:o,onAdd:s,addDisabled:c=!1,notices:l,suggestion:u,children:f}){let{t:p}=X(),m=s!==void 0&&o!==void 0;return e(Ni,{id:t,icon:n,title:r,actions:e(d,{children:[a,m&&!c&&u!==void 0&&u.count>0&&e(J,{variant:`ghost`,size:`sm`,onClick:u.onOpen,children:[i(T,{className:`h-3.5 w-3.5`,"aria-hidden":!0}),p(`customize.suggest.hint`,{count:u.count,location:u.location})]}),m&&i(J,{variant:`outline`,size:`sm`,disabled:c,onClick:s,children:o})]}),children:[l!==void 0&&i(`div`,{className:`flex flex-col gap-1 px-3 pt-2 empty:hidden sm:px-4`,children:l}),i(`ul`,{className:`flex flex-col divide-y divide-border`,children:f})]})}function ls(e,t){if(e.kind!==`known`||typeof t!=`string`||t.length===0)return null;let n=mr(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 us(e,t,n){return Kn(e,t?.ids??new Set,n)}function ds(e,t){return e?.containers.get(t)??null}function fs(e,t,n){return e.kind===`known`?us(e.value,t,n).suggested.length:0}function ps({device:t,action:n,onPick:r}){let{t:a}=X(),o=At(t.id,`compact`,t.name),s=[t.container===null||o.includes(t.container)?null:a(`customize.suggest.in`,{container:t.container}),t.detail].filter(e=>e!==null&&e!==``).join(` · `);return e(`li`,{className:`${O} flex items-center gap-3`,children:[e(`div`,{className:`min-w-0 flex-1`,children:[i(`div`,{className:`text-xs text-foreground break-words`,children:o}),s!==``&&i(`div`,{className:`text-[11px] text-foreground-subtle break-words`,children:s})]}),i(J,{variant:`outline`,size:`sm`,"aria-label":a(n===`add`?`customize.suggest.addNamed`:`customize.suggest.useNamed`,{name:o}),onClick:()=>r(t.id),children:a(n===`add`?`customize.suggest.add`:`customize.suggest.use`)})]})}function ms({location:t,devices:n,action:r,onPick:a,onPickAll:o}){let{t:s}=X();if(n.length===0)return null;let c=s(`customize.suggest.heading`,{location:t});return e(`section`,{"aria-label":c,className:`flex flex-col gap-1`,children:[e(`div`,{className:`flex min-h-7 items-center gap-2`,children:[i(`h3`,{className:`${k} min-w-0 flex-1`,children:c}),o!==void 0&&n.length>1&&i(J,{variant:`ghost`,size:`sm`,onClick:o,children:s(`customize.suggest.addAll`,{count:n.length})})]}),i(`ul`,{className:`flex flex-col divide-y divide-border rounded-md border border-border`,children:n.map(e=>i(ps,{device:e,action:r,onPick:a},e.id))})]})}c();function hs(e){return e.kind===`pending`?`pending`:e.kind===`unknown`?`failed`:`answered`}function gs(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 _s({open:t,title:r,selection:s,candidates:c,filters:l,room:u=null,confirmLabel:d,onConfirm:f,onClose:p}){let{t:m}=X(),[h,g]=o(null),[_,v]=o([]),y=l?.find(e=>e.id===h)??l?.[0]??null,b=c.kind===`known`?c.value:[],x=c.kind===`known`?Hi(c.value,``,y):[],S=us(b,u,e=>e.deviceId).suggested,C=us(x,u,e=>e.deviceId).others,w=n(()=>gs(C),[C]),T=hs(c),E=b.filter(e=>_.includes(e.deviceId));a(()=>{t||(v([]),g(null))},[t]);let D=()=>{v([]),g(null),p()},O=e=>{e.length!==0&&(f(e),v([]),g(null))},k=()=>O(E);return i(jn,{open:t,onOpenChange:e=>e?void 0:D(),children:e(Qn,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,"aria-label":r,children:[i(hn,{children:i(vr,{children:r})}),e(ar,{className:`flex flex-col gap-2 p-2 sm:p-4`,children:[l!==void 0&&l.length>0&&i(`div`,{className:`flex flex-wrap gap-1`,role:`tablist`,"aria-label":m(`customize.assign.filtersLabel`),children:l.map(e=>i(`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))}),u!==null&&i(ms,{location:u.location,devices:S.map(e=>({id:e.deviceId,name:e.name,container:ds(u,e.deviceId),detail:e.detail})),action:`add`,onPick:e=>O(S.filter(t=>t.deviceId===e)),...s===`multi`?{onPickAll:()=>O(S)}:{}}),c.kind===`unknown`?i(`p`,{role:`alert`,className:`text-xs text-warning`,children:m(`customize.assign.unknown`,{reason:c.reason})}):w.length===0&&S.length>0?null:i(Ht,{devices:w,listState:T,value:_,onChange:e=>v(s===`single`?e.length>0?[e[e.length-1]]:[]:e),noun:`device`,emptyLabel:m(`customize.assign.none`),showAll:!0,testId:`customize-device-picker`})]}),e(In,{children:[i(J,{variant:`ghost`,onClick:D,children:m(`customize.picker.cancel`)}),i(J,{disabled:E.length===0,onClick:k,children:d(E.length)})]})]})})}c();function vs(e,t){let r=typeof e==`string`&&e.length>0,i=ni(t&&r);return n(()=>t?ls(i,e):null,[t,i,e])}c();function ys(e){return e==null?null:e.message}function bs({device:t}){let n=ie(),{t:r}=X(),a=l(),s=ti(),c=Ce.includes(t.type),[u,f]=o(!1),[p,m]=o(!1),[h,g]=o(null),_=Ct({deviceId:t.id},{enabled:c}),v=ra({status:_.status,data:_.data,error:ys(_.error)===null?null:{message:ys(_.error)??``}}),y=v.kind===`present`?v.slot.slotRef:``,b=v.kind===`present`?[...ta(v.slot,v.value).map(e=>e.deviceId),...ea(v.slot,v.value)]:[],x=un(),S=ni(c&&v.kind===`present`&&(u||b.length>0)),C=vs(t.location,c&&v.kind===`present`),w=or({deviceId:t.id,slotRef:y},{enabled:(u||C!==null)&&v.kind===`present`});if(!c||v.kind===`absent`)return null;if(v.kind!==`present`)return i(cs,{id:`linked`,icon:H,title:r(`customize.linked.title`),notices:v.kind===`pending`?i(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:r(`customize.assign.checking`)}):i(`p`,{role:`alert`,className:`text-xs text-warning break-words`,children:r(`customize.assign.unknown`,{reason:v.reason})}),children:null});let T=v.value,E=new Map(S.kind===`known`?S.value.map(e=>[e.id,e]):[]),D=T.trackedDeviceIds!==void 0,O=(e,t)=>{let n=E.get(e.deviceId);return{...e,name:e.name??n?.name??null,type:n?.type??null,detail:n===void 0?null:Ui(n.integration,n.location),orphan:t}},k=[...ta(v.slot,T).map(e=>O(e,!1)),...ea(v.slot,T).map(e=>O({deviceId:e,name:null,health:`ok`,implied:!1,tracked:!0},!0))],A=new Set(b),j=S.kind===`unknown`?S:w.status===`error`?{kind:`unknown`,reason:ys(w.error)??r(`helpers.customize.requestFailed`)}:S.kind===`pending`||w.status===`pending`||w.data===void 0?{kind:`pending`}:{kind:`known`,value:aa(w.data.candidates,E,A)},M=async e=>{if(p){g(r(`customize.saveInFlight`));return}m(!0),g(null);try{await x.mutateAsync({deviceId:t.id,slotRef:v.slot.slotRef,value:e}),await _.refetch(),await a.invalidateQueries({queryKey:[[`deviceManager`]]})}catch(e){g(e instanceof Error?e.message:String(e))}finally{m(!1)}},ee=async e=>{await s(r(`customize.linked.removeWhat`,{name:e.name??`#${e.deviceId}`}),!1)&&await M(ia(T,e.deviceId))},N=[{key:`device`,header:r(`customize.linked.device`),cell:t=>e(`div`,{className:`flex flex-col min-w-0`,children:[i(`span`,{className:`truncate text-xs text-foreground`,children:t.name??`#${t.deviceId}`}),t.detail!==null&&i(`span`,{className:`truncate text-[11px] text-foreground-subtle`,children:t.detail}),t.orphan&&i(`span`,{className:`text-[11px] text-foreground-subtle`,children:r(`customize.linked.notLinked`)}),t.health!==`ok`&&i(`span`,{role:`alert`,className:`text-[11px] text-warning`,children:r(`customize.linked.health.${t.health}`)})]})},{key:`type`,header:r(`customize.linked.type`),headerClassName:`hidden sm:table-cell`,cellClassName:`hidden sm:table-cell text-xs text-foreground-subtle`,cell:e=>e.type===null?`—`:yr(e.type,n).label},{key:`controls`,header:r(`customize.linked.controls`),headerClassName:`hidden md:table-cell`,cellClassName:`hidden md:table-cell text-xs text-foreground-subtle`,cell:e=>e.orphan?`—`:r(`customize.linked.yes`)},...D?[{key:`tracked`,header:r(`customize.linked.tracked`),cellClassName:`text-right`,headerClassName:`text-right`,cell:e=>i(Qt,{checked:e.tracked,disabled:p,"aria-label":r(`customize.linked.trackFor`,{name:e.name??e.deviceId}),onCheckedChange:t=>void M(na(T,e.deviceId,t))})}]:[],{key:`remove`,header:``,cellClassName:`text-right w-10`,cell:e=>e.implied||e.orphan?null:i(pr,{icon:F,variant:`ghost`,size:`sm`,"aria-label":r(`customize.assign.removeNamed`,{name:e.name??e.deviceId}),disabled:p,onClick:t=>{t.stopPropagation(),ee(e)}})}];return e(d,{children:[i(cs,{id:`linked`,icon:H,title:r(`customize.linked.title`),addLabel:r(`customize.linked.add`),onAdd:p?void 0:()=>f(!0),...C===null?{}:{suggestion:{count:fs(j,C,e=>e.deviceId),location:C.location,onOpen:()=>f(!0)}},notices:e(d,{children:[S.kind===`unknown`&&i(`p`,{role:`alert`,className:`text-xs text-warning break-words`,children:r(`customize.assign.devicesUnreadable`,{reason:S.reason})}),h!==null&&i(`p`,{role:`alert`,className:`text-xs text-danger break-words`,children:h})]}),children:e(`li`,{className:`list-none px-3 py-2 sm:px-4`,children:[k.length===0?i(`p`,{className:`text-[11px] text-foreground-subtle`,children:r(`customize.assign.none`)}):i(Ze,{mode:`generic`,items:k,getKey:e=>String(e.deviceId),getSearchText:e=>[e.name??``,e.detail??``,e.type??``,String(e.deviceId)].join(` `),getFilterType:e=>e.type===null?null:yr(e.type,n).label,columns:N,searchPlaceholder:r(`customize.assign.search`),emptyLabel:r(`customize.assign.none`)}),k.some(e=>!e.orphan)&&i(`p`,{className:`mt-2 text-[10px] text-foreground-subtle`,children:r(`customize.linked.controlsAlways`)}),D&&i(`p`,{className:`mt-0.5 text-[10px] text-foreground-subtle`,children:r(`customize.linked.trackedHint`)})]})}),i(_s,{open:u,title:r(`customize.linked.pickTitle`),selection:`multi`,candidates:j,room:C,confirmLabel:e=>r(`customize.assign.addCount`,{count:e}),onConfirm:e=>{f(!1),M($i(T,e.map(e=>e.deviceId)))},onClose:()=>f(!1)})]})}c();function xs(e){return e instanceof Error?e.message:String(e)}function Ss(e){let n=yt({addonId:e.addonId,stableId:e.stableId}),r=Hn(),i=mt(),a=jt(),s=gi({status:n.status,data:n.data,error:n.error===null||n.error===void 0?null:{message:n.error.message}}),{t:c}=X(),l=t(!1),[u,d]=o(!1),f=async e=>{let t=oi(s,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:xs(e)}}};return{target:e,state:s,saving:u||r.isPending||i.isPending||a.isPending,save:async e=>{if(l.current)return{kind:`refused`,reason:c(`customize.saveInFlight`)};l.current=!0,d(!0);try{return await f(e)}finally{l.current=!1,d(!1)}}}}var Cs=`pipeline-orchestrator`;function ws(e){return e.data===void 0?e.status===`pending`?`pending`:e.status===`error`?`unknown`:`pending`:e.data.cameraSensors===void 0?`absent`:`present`}function Ts(e,t){return e===`absent`?`absent`:ws(t)}async function Es(e){try{return(await e()).isError?`failed`:`answered`}catch{return`failed`}}function Ds(e,t){let n=It(Cs),r=ft({deviceId:e},{enabled:t&&n!==`absent`}),i=()=>Es(r.refetch),a=r.data===void 0&&r.status===`error`?r.error?.message??null:null;return t?{presence:Ts(n,{status:r.status,data:r.data}),status:r.data?.cameraSensors??null,failureReason:a,refetch:i}:{presence:`absent`,status:null,failureReason:null,refetch:i}}function Os(e,t){let n=kt({deviceType:e.type}),r=Rn({deviceId:e.id}),i=Cr({deviceId:e.id}),a=ai(n,e=>new Set(e.caps.map(e=>e.cap))),o=ai(r,e=>Qr(e.entries)),s=ai(i,e=>e);return{deviceType:e.type,composable:a,nativeCaps:o,wireable:s,composed:new Set((t?.features??[]).map(e=>e.cap))}}function ks(e,t,n){let r=t.kind===`known`&&t.value.has(`consumables`),i=si(r?{deviceId:e,cap:Li,path:Bi}:null);return yi(t,n,r?i:null)}c();function As({device:t}){let{t:r}=X(),a=t.stableId.startsWith(`composed-`)?t.stableId.slice(Ne.length):null,o=st({blockId:a??``},{enabled:a!==null}),s=mt(),c=$t(),l=kr(),u=n(()=>{let e=new Set;for(let{cap:t}of wi())e.add(t);for(let{cap:t}of _i())e.add(t);for(let{cap:t}of ei())e.add(t);return e},[]);if(a===null)return i(`p`,{className:`text-xs text-foreground-subtle`,children:r(`customize.composed.missingBlock`)});if(o.status===`pending`)return i(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:r(`customize.loadingDevice`)});if(o.status===`error`)return i(q,{title:r(`customize.composed.loadFailed`),message:o.error.message,onRetry:()=>void o.refetch()});if(o.data.state===`not-loaded`)return i(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:r(`customize.status.notLoaded`,{reason:o.data.reason})});let d=o.data.view;if(d===null)return i(`p`,{className:`text-xs text-foreground-subtle`,children:r(`customize.composed.notFound`)});let f=Fe(d.block);if(f===null)return i(`p`,{className:`text-xs text-foreground-subtle`,children:r(`compositionEditor.notComposition`)});if(ji(f)){let n=Pi(f.helper,t.name,t.location??``);return n===null?i(`p`,{role:`alert`,children:r(`helper.unreadable`)}):e(`div`,{className:`flex flex-col gap-3`,children:[i(wo,{device:t}),i(Ii,{purpose:`edit`,initial:n,start:`parameters`,saving:s.isPending,onSave:async e=>{let n=await Mi(e,async(n,r)=>{await s.mutateAsync({blockId:d.block.id,expectedUpdatedAt:d.block.updatedAt,block:{composition:n,...r===``?{}:{name:r}}}),r!==``&&r!==t.name&&await c.mutateAsync({deviceId:t.id,name:r}),e.room.trim()!==``&&e.room.trim()!==(t.location??``)&&await l.mutateAsync({deviceId:t.id,location:e.room.trim()}),await o.refetch()});return n.length>0?{kind:`refused`,lines:n}:{kind:`saved`,deviceId:t.id}}})]})}let p={target:{addonId:t.addonId,stableId:t.stableId},state:{kind:`present`,view:d,composition:f},saving:s.isPending,save:async e=>{if(e===null)return{kind:`refused`,reason:r(`customize.composed.noDelete`)};try{return await s.mutateAsync({blockId:d.block.id,expectedUpdatedAt:d.block.updatedAt,block:{composition:e}}),await o.refetch(),{kind:`saved`}}catch(e){return{kind:`refused`,reason:e instanceof Error?e.message:String(e)}}}};return e(`div`,{className:`flex flex-col gap-3`,children:[i(wo,{device:t}),hi(f)===`incomplete`&&i(dr,{variant:`warning`,children:r(`customize.blockStatus.incomplete`)}),i($r,{device:t,handle:p,skipCaps:u})]})}c();function js({deviceId:e}){let{t}=X(),n=_r({deviceId:e}),r=n.data;if(r==null)return n.status===`error`?i(q,{title:t(`customize.deviceUnreadable`),message:n.error?.message??``,onRetry:()=>void n.refetch()}):r===null?i(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:t(`customize.noSuchDevice`,{deviceId:e})}):i(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:t(`customize.loadingDevice`)});let a=r.addonId===`composer`?i(As,{device:r}):i(Ms,{device:r,target:{addonId:r.addonId,stableId:r.stableId}});return i(Lr,{deviceId:r.id,seed:{name:r.name,location:r.location??``,role:r.role??null,display:r.display},children:a})}function Ms({device:t,target:r}){let a=Ss(r),o=It(`composer`),{t:s}=X(),c=Ds(t.id,t.type===U.Camera),l=Os(t,mi(a.state)),u=ks(t.id,l.nativeCaps,l.wireable),d={deviceType:t.type,composable:l.composable,nativeCaps:l.nativeCaps,cameraSensors:c.presence},f=n(()=>{let e=new Set;for(let{cap:t}of wi())e.add(t);for(let{cap:t}of _i())e.add(t);for(let{cap:t}of ei())e.add(t);return e},[]);return e(`div`,{className:`flex flex-col gap-3`,children:[i(wo,{device:t}),o===`absent`&&i(`p`,{role:`alert`,className:`text-xs text-warning`,children:s(`customize.composerAbsent`)}),a.state.kind!==`none`&&i(Ns,{state:a.state}),i(ss,{device:t,handle:a,facts:d,sensors:c}),i(ki,{device:t,handle:a,facts:d}),i(Ci,{device:t,handle:a,facts:d,defaults:u}),i($r,{device:t,handle:a,skipCaps:f}),i(bs,{device:t})]})}function Ns({state:t}){let{t:n}=X();switch(t.kind){case`pending`:return i(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:n(`customize.status.pending`)});case`unknown`:return i(q,{title:n(`customize.status.unknownTitle`),message:t.reason});case`not-loaded`:return i(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:n(`customize.status.notLoaded`,{reason:t.reason})});case`none`:return null;case`present`:{let r=t.view.block;return e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[i(dr,{variant:r.status===`running`?`success`:r.status===`failed`?`danger`:`warning`,children:n(`customize.blockStatus.${r.status}`)}),!r.enabled&&i(dr,{variant:`default`,children:n(`customize.status.off`)}),r.lastError!==void 0&&i(`span`,{className:`text-[11px] text-foreground-muted break-words`,children:r.lastError}),t.view.state.kind===`unreachable`&&i(`span`,{className:`text-[11px] text-warning`,children:n(`customize.status.composerUnreachable`,{reason:t.view.state.error})})]})}}}var Ps=`overview`;function Fs(e,t){return e.some(e=>e.id===t)?t:Ps}function Is({deviceId:t}){let{t:n}=X(),r=l(),a=Number.isFinite(t),{data:o}=_r({deviceId:t},{enabled:a}),s=typeof o?.type==`string`?o.type:`camera`;lr([`deviceManager`,`getBindings`],[`capability.binding-changed`]);let{data:c,isLoading:u,isError:d,error:f}=Rn({deviceId:t},{enabled:a}),{data:p}=tt({deviceType:s},{enabled:!!s}),m=Tt({onSuccess:()=>{r.invalidateQueries({queryKey:[[`deviceManager`,`getBindings`]]})}});if(u)return i(`div`,{className:`p-4`,children:i(`div`,{className:`h-20 rounded-lg border border-border bg-surface animate-pulse`})});if(d)return e(`div`,{className:`p-4 text-xs text-red-400`,children:[n(`device.bindingsTab.failedToLoadBindings`,`Failed to load bindings:`),` `,f instanceof Error?f.message:String(f)]});let h=new Map,g={};for(let e of p??[])g[e.capName]=e.wrappers;for(let e of c?.entries??[])h.set(e.capName,{...e,wrappers:g[e.capName]??[]});for(let e of p??[])h.has(e.capName)||h.set(e.capName,{capName:e.capName,kind:`unbound`,providerAddonId:``,providerNodeId:``,nativeAddonId:``,wrappers:e.wrappers});let _=[...h.values()].toSorted((e,t)=>e.capName.localeCompare(t.capName));if(_.length===0)return e(`div`,{className:`flex flex-col items-center justify-center gap-2 p-8 text-foreground-subtle`,children:[i(Ge,{className:`h-8 w-8 opacity-40`}),i(`p`,{className:`text-xs`,children:n(`device.bindingsTab.noCapabilityProvidersApplicableTo`,`No capability providers applicable to this device yet.`)}),i(`p`,{className:`text-[10px] opacity-60`,children:n(`device.bindingsTab.nativeProvidersShowUpHere`,`Native providers show up here as soon as the owning addon registers them.`)})]});let v=_.filter(e=>e.kind!==`unbound`).length,y=[{key:`capability`,header:n(`device.bindingsTab.capability`,`Capability`),render:e=>i(`span`,{className:`font-mono text-foreground`,children:e.capName})},{key:`kind`,header:n(`device.bindingsTab.kind`,`Kind`),render:e=>i(Ls,{kind:e.kind})},{key:`provider`,header:n(`device.bindingsTab.activeProvider`,`Active Provider`),render:e=>i(`span`,{className:`font-mono text-foreground-subtle`,children:e.providerAddonId||i(`span`,{className:`opacity-40`,children:`—`})})},{key:`node`,header:n(`device.bindingsTab.node`,`Node`),render:e=>e.providerNodeId?i(Rs,{nodeId:e.providerNodeId}):i(`span`,{className:`text-[10px] opacity-40`,children:`—`})},{key:`native`,header:n(`device.bindingsTab.kindNative`,`Native`),render:e=>i(`span`,{className:`font-mono text-foreground-subtle`,children:e.nativeAddonId||i(`span`,{className:`opacity-40`,children:`—`})})},{key:`wrapper`,header:n(`device.bindingsTab.wrapper`,`Wrapper`),render:e=>{let n=e.kind===`wrapped`?e.providerAddonId:null;return i(zs,{wrappers:e.wrappers,activeWrapperId:n,disabled:m.isPending,onPick:r=>{let i=n===r;m.mutate({deviceId:t,capName:e.capName,wrapperAddonId:r,active:!i})}})}}];return e(`div`,{className:`flex flex-col gap-3 p-1`,children:[i(`div`,{className:`text-[11px] text-foreground-subtle`,children:i(Hr,{i18nKey:`device.bindingsTab.boundSummary`,count:_.length,values:{bound:v},components:{b:i(`span`,{className:`font-medium text-foreground`}),em:i(`em`,{})}})}),i(et,{columns:y,rows:_,rowKey:e=>e.capName,minWidthPx:720})]})}function Ls({kind:t}){let{t:n}=X();return t===`native`?e(`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:[i(ae,{className:`h-3 w-3`}),n(`device.bindingsTab.kindNative`)]}):t===`wrapped`?e(`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:[i(Je,{className:`h-3 w-3`}),n(`device.bindingsTab.wrapped`)]}):t===`linked`?e(`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:[i(H,{className:`h-3 w-3`}),n(`device.bindingsTab.linked`)]}):e(`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:[i(M,{className:`h-3 w-3`}),n(`common.unbound`)]})}function Rs({nodeId:e}){return i(`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 zs({wrappers:t,activeWrapperId:n,disabled:r,onPick:a}){let{t:o}=X();return t.length===0?i(`span`,{className:`text-[10px] opacity-40`,children:o(`device.bindingsTab.noneAvailable`,`none available`)}):i(`div`,{className:`flex flex-wrap gap-1`,children:t.map(t=>{let s=t===n;return e(`button`,{disabled:r,onClick:()=>a(t),title:s?o(`device.bindingsTab.clickToDeactivateRevertTo`,`Click to deactivate (revert to native)`):o(`device.bindingsTab.activateWrapper`,`Activate wrapper {{wrapperId}}`,{wrapperId:t}),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 ${s?`border-primary/40 bg-primary/10 text-primary`:`border-border text-foreground-subtle hover:text-foreground hover:bg-surface-hover`}`,children:[i(s?m:re,{className:`h-3 w-3`}),t]},t)})})}function Bs({deviceId:t,activeSubTab:n,onSubTabChange:r,deviceType:a,isAdmin:o}){return e(`div`,{className:`flex flex-col gap-3`,children:[Fr(a,o)&&i(bn,{deviceId:t,readOnly:!0}),i(Pr,{deviceId:t,activeSubTab:n,onSubTabChange:r})]})}c();var Vs=[[`pipelineOrchestrator`,`getCameraDetectionSource`]];function Hs(e){let t=l(),n=Zt({deviceId:e},{refetchOnMount:`always`}),i=An(),[a,s]=o(null),[c,u]=o(null),d=r(async n=>{u(null),s(n);try{await i.mutateAsync({deviceId:e,source:n}),await t.invalidateQueries({queryKey:Vs})}catch(e){u(e instanceof Error?e.message:`Could not change the root detector`),await t.invalidateQueries({queryKey:Vs})}finally{s(null)}},[e,i,t]),f=n.data??null;return{view:f,isLoading:n.isLoading,source:a??f?.source??null,saving:a!==null,error:c,pick:d}}var Us=`object-detection`;function Ws(e){return[e.addonId,...e.children.flatMap(Ws)]}function Gs(e,t){if(e===`pipeline`)return new Set;let n=Ks(t,Us);return n===void 0?new Set:new Set(e===`onboard`?[n.addonId]:Ws(n))}function Ks(e,t){for(let n of e){if(n.addonId===t)return n;let e=Ks(n.children,t);if(e!==void 0)return e}}function qs(e,t){return e===`onboard`?Y.t(`helpers.detectionSourceModel.badgeCameraAi`):t===`object-detection`?Y.t(`helpers.detectionSourceModel.badgeNoRoot`):Y.t(`helpers.detectionSourceModel.badgeIdle`)}function Js(e){switch(e){case`pipeline`:return Y.t(`helpers.detectionSourceModel.explainPipeline`);case`onboard`:return Y.t(`helpers.detectionSourceModel.explainOnboard`);case`none`:return Y.t(`helpers.detectionSourceModel.explainNone`)}}function Ys(e){switch(e){case`boxed`:return``;case`while-streaming`:return Y.t(`helpers.detectionSourceModel.geometryWhileStreaming`);case`flag-only`:return Y.t(`helpers.detectionSourceModel.geometryFlagOnly`);case`unknown`:return Y.t(`helpers.detectionSourceModel.geometryUnknown`)}}function Xs(e,t){return e===`onboard`?Y.t(`helpers.detectionSourceModel.noticeOnboard`):t===`object-detection`?Y.t(`helpers.detectionSourceModel.noticeNoRoot`):Y.t(`helpers.detectionSourceModel.noticeIdle`)}var Zs=[`pl-2`,`pl-6`,`pl-10`,`pl-14`],Qs={detector:`success`,cropper:`info`,classifier:`primary`,refiner:`warning`,"audio-classifier":`neutral`};function $s(e){return Zs[Math.min(e,Zs.length-1)]??`pl-2`}function ec(e){return e.zoneDriven?{kind:`zone-driven`}:{kind:`gate`,effectiveOn:e.ownOn,defaultOn:e.defaultOn,explicit:e.choice!==`auto`}}function tc(e,t,n){return e.kind===`parent`?n:qs(e.source,t)}function nc({inputs:t,outputs:n}){return t.length===0&&n.length===0?null:e(`span`,{className:`inline-flex flex-wrap items-center gap-1`,children:[t.map(e=>i(dr,{size:`sm`,variant:`info`,children:e},`in-${e}`)),t.length>0&&n.length>0&&i(`span`,{className:`text-[10px] text-foreground-subtle`,"aria-hidden":!0,children:`→`}),n.map(e=>i(dr,{size:`sm`,variant:`success`,children:e},`out-${e}`))]})}function rc({rows:t,label:n,selectedId:r,busy:a,onOpen:o,onSet:s}){let{t:c}=X(),l=e=>{switch(e){case`detector`:return c(`device.cameraStepInspector.kindDetector`,`detector`);case`cropper`:return c(`device.cameraStepInspector.kindCropper`,`cropper`);case`classifier`:return c(`device.cameraStepInspector.kindClassifier`,`classifier`);case`refiner`:return c(`device.cameraStepInspector.kindRefiner`,`refiner`);case`audio-classifier`:return c(`device.cameraStepInspector.kindAudio`,`audio`)}},u=c(`device.cameraStepInspector.offBecauseParent`,`Off because its parent is off`);return i(`ul`,{"aria-label":n,className:`divide-y divide-border rounded-md border border-border`,children:t.map(t=>{let n=t.stepId===r,c=t.blocked===null?null:tc(t.blocked,t.stepId,u);return e(`li`,{"data-step":t.stepId,"data-runs":t.runs?`yes`:`no`,className:`flex flex-wrap items-center gap-x-2 gap-y-1.5 py-2 pr-2 ${$s(t.depth)} ${n?`bg-primary/10`:t.runs?``:`bg-muted/40`}`,children:[e(`button`,{type:`button`,"aria-expanded":n,onClick:()=>o(t.stepId),className:`flex min-w-0 flex-1 flex-wrap items-center gap-x-2 gap-y-1 text-left`,children:[i(`span`,{className:`text-sm font-medium ${t.runs?`text-foreground`:`text-foreground-muted`}`,children:t.name}),i(dr,{size:`sm`,variant:Qs[t.kind],children:l(t.kind)}),i(nc,{inputs:t.inputs,outputs:t.outputs}),c!==null&&i(`span`,{className:`text-[11px] text-warning`,children:c})]}),i(Vn,{gate:ec(t),busy:a,onSet:e=>s(t.stepId,e)})]},t.stepId)})})}function ic(e,t){let n=e?.[t];return n===void 0?`auto`:n?`on`:`off`}function ac(e,t){return e===`auto`?t:e===`on`}function oc(e,t,n){return e!==`onboard`&&e!==`none`||!n.has(t)?null:{kind:`source`,source:e}}function sc(e,t,n,r,i){let a=e.zoneDrivenIds??new Set;return t.flatMap(t=>{let o=a.has(t.addonId),s=ic(e.toggles,t.addonId),c=e.defaults[t.addonId]??!0,l=o||ac(s,c),u=r===null?oc(e.source,t.addonId,i):{kind:`parent`,ancestorId:r.stepId},d={stepId:t.addonId,name:t.addonName,kind:t.slot,depth:n,inputs:t.inputClasses,outputs:t.outputClasses,choice:s,defaultOn:c,ownOn:l,runs:u===null&&l,blocked:u,zoneDriven:o},f=l?r:{stepId:t.addonId};return[d,...sc(e,t.children,n+1,f,i)]})}function cc(e){let t=e.source===null?new Set:Gs(e.source,e.tree);return sc(e,e.tree,0,null,t)}function lc({source:t,geometry:n,saving:r,error:a,onPick:o}){let{t:s}=X(),c=n===`flag-only`,l=Ys(n);return e(`section`,{"aria-label":s(`device.detectionSourceControl.rootDetector`,`Root detector`),"aria-busy":r,className:`space-y-1.5 rounded-md border border-border bg-surface px-3 py-2`,children:[e(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-1.5`,children:[i(`h3`,{className:k,children:s(`device.detectionSourceControl.rootDetector`,`Root detector`)}),i(ur,{label:s(`device.detectionSourceControl.rootDetector`,`Root detector`),value:t,onChange:e=>{!r&&e!==t&&o(e)},options:[{value:`pipeline`,label:s(`device.detectionSourceControl.thisNode`,`This node`)},{value:`onboard`,label:s(`device.detectionSourceControl.cameraOnboardAi`,`Camera onboard AI`),disabled:c&&t!==`onboard`,reason:l},{value:`none`,label:s(`device.detectionSourceControl.none`,`None`)}]}),r&&i(`span`,{className:`text-[10px] text-foreground-subtle`,children:s(`device.detectionSourceControl.saving`,`Saving…`)})]}),e(`p`,{className:ge,children:[Js(t),` `,s(`device.detectionSourceControl.oneRoot`)]}),l!==``&&i(`p`,{className:`text-[10px] text-foreground-subtle`,children:l}),a!==null&&i(`p`,{role:`alert`,className:`text-[11px] text-danger`,children:a})]})}c();var uc=new Set([`package-detection`]),dc=`/system/pipeline?view=nodes`;function fc(e){return Object.fromEntries(e.slots.flatMap(e=>e.addons.map(e=>[e.id,e.enabledByDefault??!0])))}function pc({deviceId:a}){let{t:c}=X(),u=Vt(),d=Nn(),f=l(),p=z().trpcClient,m=t(null),h=t(null),g=rn({deviceId:a},{refetchOnMount:`always`}),_=$n(void 0,{refetchOnMount:`always`});lr([`nodes`,`topology`],[`agent.online`,`agent.offline`,`agent.unregistered`,`addon.installed`,`addon.uninstalled`]);let{nodes:v}=Jt(),y=n(()=>{let e=new Set((_.data??[]).map(e=>e.nodeId));return v.filter(t=>t.isOnline&&e.has(t.id)).map(e=>({id:e.id,name:e.name}))},[_.data,v]),b=y.map(e=>e.id).join(`,`),x=s({enabled:y.length>0,queryKey:[[`pipelineExecutor`,`getSchema`],`camera-step-schemas`,b],queryFn:async()=>{let e={};for(let t of y)try{e[t.id]=await p.pipelineExecutor.getSchema.query({nodeId:t.id})}catch{}return e}}),S=r(()=>{f.invalidateQueries({queryKey:[[`pipelineOrchestrator`,`getCameraSettings`]]})},[f]),C=Ln({onSuccess:S}),w=Xn(),[T,E]=o(null),[D,O]=o(!1),[k,A]=o(null),j=Hs(a),M=x.data??{},ee=g.data??null,N=y.map(e=>M[e.id]).find(e=>e!==void 0)??null,te=n(()=>N?sn(N):[],[N]),ne=n(()=>N===null?[]:cc({tree:te,toggles:ee?.stepToggles,defaults:fc(N),source:j.source,zoneDrivenIds:uc}),[te,N,ee?.stepToggles,j.source]),{selection:P,open:re,close:ie}=qi(n(()=>ne.map(e=>e.stepId),[ne]),[]),ae=y[0]?.id,oe=r(async e=>{if(T!==null){if(!await u({title:c(`stepInspector.stepMatrixFrame.discardUnsavedChanges`,`Discard unsaved changes?`),message:c(`stepInspector.stepMatrixFrame.thisStepHasChangesThat`,`This step has changes that are not saved yet.`),confirmLabel:c(`stepInspector.stepMatrixFrame.discard`,`Discard`),variant:`danger`}))return;E(null)}e()},[u,T,c]),se=e=>{e!==P.stepId&&oe(()=>re({stepId:e}))},I=()=>{oe(()=>ie())};if(_.isLoading||y.length>0&&x.isLoading)return i(`div`,{className:`animate-pulse p-4 text-xs text-foreground-subtle`,children:c(`device.cameraStepInspector.loadingPipeline`,`Loading pipeline…`)});if(y.length===0)return i(`div`,{className:`p-4 text-xs text-foreground-subtle`,children:c(`device.cameraStepInspector.noPipelineNodeIsOnline`,`No pipeline node is online.`)});if(N===null)return i(`div`,{className:`p-4 text-xs text-foreground-subtle`,children:c(`device.cameraStepInspector.catalogUnavailable`,`Catalog unavailable.`)});let L=e=>_.data?.find(e=>e.nodeId===ae)?.settings.stepSettings?.[e]??{},R=ne.find(e=>e.stepId===P.stepId)??null,ce=R===null?null:Ki(N,R.stepId),B=d?i(On,{onClick:I}):i(pr,{icon:F,variant:`ghost`,size:`sm`,"aria-label":c(`common.close`,`Close`),onClick:I});return e(`div`,{ref:m,className:`space-y-2`,children:[j.view?.onboard.available===!0&&j.source!==null&&i(lc,{source:j.source,geometry:j.view.onboard.geometry,saving:j.saving,error:j.error,onPick:e=>void j.pick(e)}),i(`p`,{className:ge,children:i(Hr,{i18nKey:`device.cameraStepInspector.modelsChosenByAccelerators`,components:{nodes:i(Xr,{to:dc,className:`font-medium text-primary hover:underline`})}})}),P.staleStepId!==null&&i(`p`,{className:`rounded-md border border-warning/40 bg-warning/10 px-3 py-1.5 text-[11px] text-warning`,children:c(`stepInspector.stepMatrixFrame.staleStep`,{id:P.staleStepId})}),i(rc,{rows:ne,label:c(`device.cameraStepInspector.detectionStepsOfThisCamera`,`Detection steps of this camera`),selectedId:P.stepId,busy:C.isPending,onOpen:se,onSet:(e,t)=>C.mutate({deviceId:a,addonId:e,enabled:t})}),i(er,{open:R!==null&&ce!==null,anchor:m,onClose:I,label:c(`stepInspector.stepMatrixFrame.stepSettings`,`Step settings`),children:R!==null&&ce!==null&&i(mc,{addon:ce,nodeBag:L(R.stepId),storedCamera:ee?.stepSettings?.[R.stepId],draft:T?.stepId===R.stepId?T:null,saving:D,status:k,notice:R.blocked?.kind===`source`?Xs(R.blocked.source,R.stepId):null,closeButton:B,onEscape:I,headingRef:e=>{h.current=e},onDraft:e=>{A(null),E({stepId:R.stepId,camera:e})},onDiscard:()=>E(null),onSave:async e=>{O(!0);try{await w.mutateAsync({deviceId:a,addonId:R.stepId,settings:Object.keys(e).length>0?{...e}:null}),E(null),A({kind:`saved`})}catch(e){A({kind:`error`,error:e instanceof Error?e.message:c(`device.cameraStepInspector.saveFailed`)})}finally{O(!1),S()}}})})]})}function mc({addon:t,nodeBag:n,storedCamera:r,draft:a,saving:o,status:s,notice:c,closeButton:l,onEscape:u,headingRef:d,onDraft:f,onDiscard:p,onSave:m}){let{t:h}=X(),g=wt(t),_=Yi(g),v=Ji(g),y=a?.camera??r,b=a!==null&&!K(a.camera,r??{});return i(Ye,{ref:d,title:h(`device.cameraStepInspector.thisCamera`,`{{name}} · this camera`,{name:t.name}),subtitle:t.slot,leading:l,onEscape:u,..._.length>0?{saveBar:{dirtyCount:+!!b,saving:o,status:s?.kind??null,...s?.error===void 0?{}:{error:s.error},onSave:()=>void m(a?.camera??r??{}),onDiscard:p,scope:i(`p`,{className:ge,children:h(`device.cameraStepInspector.appliesToAllAcceleratorsOf`,`Applies to: all accelerators of this camera.`)})}}:{},children:e(`div`,{className:`space-y-3`,children:[c!==null&&i(`p`,{role:`note`,className:`rounded-md border border-warning/40 bg-warning/10 px-3 py-1.5 text-[11px] text-warning`,children:c}),_.length>0?i(hc,{addon:t,fields:_,nodeBag:n,cameraBag:y,onChange:f}):i(`p`,{className:ge,children:h(`device.cameraStepInspector.noCameraSettings`,`This step has no settings on this camera.`)}),v&&i(`p`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`accelerator-only-thresholds`,children:h(`device.cameraStepInspector.thresholdsAreTheAccelerators`,`Confidence thresholds belong to the model, so they are set on the accelerator that runs it (Pipeline → Nodes), not per camera.`)})]})})}function hc({addon:e,fields:t,nodeBag:n,cameraBag:r,onChange:a}){let{t:o}=X();return i(dn,{addon:e,fields:t,layers:{node:n,...r===void 0?{}:{camera:r}},target:`camera`,labels:{camera:o(`device.cameraStepInspector.layerCamera`,`This camera`),node:o(`device.cameraStepInspector.layerNode`,`Node`)},modelId:e.defaultModelId,onChangeLayer:a})}function gc(e,t,n){return{id:e,get label(){return Y.t(t)},icon:n}}var _c=[gc(`object-detection`,`helpers.detectionSettingsGroups.objectDetection`,`scan-search`),gc(`tracking`,`helpers.detectionSettingsGroups.tracking`,`route`),gc(`motion`,`helpers.detectionSettingsGroups.motion`,`activity`),gc(`stationary`,`helpers.detectionSettingsGroups.stationary`,`square-parking`),gc(`zones`,`helpers.detectionSettingsGroups.zones`,`shapes`),gc(`audio`,`helpers.detectionSettingsGroups.audio`,`volume-2`),gc(`cluster`,`helpers.detectionSettingsGroups.cluster`,`server`)],vc={"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 yc(e){return vc[e]??`object-detection`}c();var bc=`steps`,xc=`settings`,Sc=new Set([bc,xc]);function Cc(e){return e.location===`top-tab`&&(e.tab===`detection-pipeline`||e.tab===`zones`)}function wc({deviceId:t,activeSubTab:n,onSubTabChange:a}){let{t:o}=X();return e(Or,{value:n&&Sc.has(n)?n:bc,onValueChange:r(e=>{a?.(e)},[a]),className:`flex flex-col`,children:[e(en,{className:`flex-shrink-0`,children:[i(ht,{value:bc,children:o(`device.detectionPipelineTab.steps`,`Steps`)}),i(ht,{value:xc,children:o(`device.detectionPipelineTab.settings`,`Settings`)})]}),i($e,{value:bc,children:i(pc,{deviceId:t})}),i($e,{value:xc,children:i(Pr,{deviceId:t,sectionFilter:Cc,subTabGrouping:{groupOf:e=>yc(e.id),tabs:_c}})})]})}var Tc=`Notifications`,Ec={i18nKey:`device.deviceNotificationMute.cameraCostWhenOff`,text:`This camera never notifies — no rule, no target, no alarm. Existing events, tracks and recordings are unaffected.`},Dc={i18nKey:`device.deviceNotificationMute.deviceCostWhenOff`,text:`This device never notifies — no rule, no target, no alarm.`};function Oc(e){let{mutedDeviceIds:t,deviceId:n}=e,r=t===null?null:!t.includes(n),i=e.pendingOn??null;return{label:Tc,on:r===null?null:i??r,available:r!==null,costWhenOff:e.isCamera?Ec:Dc}}function kc(e,t){return!e.available||e.on===null?null:{deviceId:t,muted:e.on}}c();function Ac(e){if(typeof e!=`object`||!e)return null;let t={...e}.mutedDeviceIds;return Array.isArray(t)?t.filter(e=>typeof e==`number`):null}function jc({deviceId:t,isCamera:n}){let{t:a}=X(),s=l(),c=Number.isFinite(t),[u,d]=o(null),[f,p]=o(null),m=Oc({mutedDeviceIds:Ac(Mn({},{enabled:c}).data),deviceId:t,isCamera:n,pendingOn:f}),h=a(m.costWhenOff.i18nKey,m.costWhenOff.text),g=hr({onError:e=>{console.error(`[DeviceNotificationMute] mute write failed — reverting`,{tags:{deviceId:t},meta:{error:e instanceof Error?e.message:String(e)}}),p(null),d(e instanceof Error?e.message:String(e)),s.invalidateQueries({queryKey:[[`notificationRules`,`listDeviceMutes`]]})},onSuccess:()=>{d(null),p(null),s.invalidateQueries({queryKey:[[`notificationRules`]]})}}),_=r(()=>{let e=kc(m,t);e!==null&&(p(!e.muted),g.mutate(e))},[t,g,m]),v=m.on===null,y=m.on===!1,b=y?We:_e;return e(`div`,{className:`rounded-lg border border-border bg-surface overflow-hidden`,children:[e(`div`,{className:`border-b border-border px-4 py-2 flex items-center justify-between gap-2`,children:[i(`h2`,{className:`text-xs font-semibold text-foreground uppercase tracking-wider`,children:a(`device.deviceNotificationMute.notifications`,`Notifications`)}),y&&i(`span`,{className:`rounded bg-warning/20 px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-wide text-warning`,children:a(`common.muted`)})]}),e(`div`,{className:`px-4 py-3 flex items-start gap-3`,children:[e(`button`,{type:`button`,role:`switch`,"aria-label":m.label,"aria-checked":m.on===!0,disabled:!m.available||g.isPending,onClick:_,title:v?a(`device.deviceNotificationMute.notificationMuteStateUnknownThe`,`Notification mute — state unknown; the notification centre did not answer.`):y?a(`device.deviceNotificationMute.muted`,`Muted. {{costWhenOff}}`,{costWhenOff:h}):a(`device.deviceNotificationMute.notifyingMutingIt`,`Notifying. Muting it: {{costWhenOff}}`,{costWhenOff:h}),className:`inline-flex items-center gap-1.5 rounded-lg border px-2 py-1.5 text-[11px] font-medium transition-colors disabled:cursor-not-allowed ${u===null?v?`border-dashed border-border text-foreground-subtle/50`:y?`border-warning/40 text-warning hover:bg-warning/10`:`border-success/30 text-success hover:bg-success/10`:`border-danger/50 text-danger bg-danger/5`}`,children:[i(b,{className:`h-3.5 w-3.5`}),i(`span`,{children:v?a(`device.deviceNotificationMute.unknown`,`Unknown`):y?a(`device.deviceNotificationMute.muted2`,`Muted`):a(`device.deviceNotificationMute.notifying`,`Notifying`)})]}),i(`p`,{className:`flex-1 text-[11px] leading-relaxed text-foreground-subtle`,children:u===null?v?a(`device.deviceNotificationMute.theNotificationCentreDidNot`,`The notification centre did not answer, so this device’s mute state is unknown.`):h:a(`device.deviceNotificationMute.writeFailed`,`Write failed: {{failure}}`,{failure:u})})]})]})}c();function Mc({template:t,members:n,fleet:a,fleetKind:s,snapshot:c,nameOf:l}){let{t:u}=X(),[f,p]=o(()=>new Map),m=r((e,t)=>{p(n=>{if(Rc(n.get(e),t))return n;let r=new Map(n);return r.set(e,t),r})},[]);if(t.family!==`actuator`)return null;let h=Ai(c),g=t.id===`light`?xi(n.map(e=>f.get(Lc(e))??{kind:`pending`})):null;return e(d,{children:[t.id===`light`&&n.map(e=>i(Fc,{member:e,row:Ic(a,e),fleetKind:s,onRead:m},Lc(e))),g!==null&&i(Nc,{view:g}),e(`div`,{"data-testid":`helper-commands`,children:[i(`h3`,{className:`text-[10px] font-semibold uppercase tracking-wider text-foreground-subtle`,children:u(`helper.commandTitle`)}),h.kind===`pending`&&i(`p`,{role:`status`,className:`mt-1 text-xs text-foreground-subtle`,children:u(`helper.reportingPending`)}),h.kind===`unavailable`&&i(q,{title:u(`helper.outputUnavailable`),message:h.message}),h.kind===`none`&&i(`p`,{className:`mt-1 text-xs text-foreground-muted`,children:u(`helper.commandNone`)}),h.kind===`rows`&&i(Pc,{view:h,nameOf:l})]})]})}function Nc({view:t}){let{t:n}=X();return e(`div`,{"data-testid":`helper-shared-caps`,children:[i(`h3`,{className:`text-[10px] font-semibold uppercase tracking-wider text-foreground-subtle`,children:n(`helper.sharedCaps`)}),t.kind===`pending`&&i(`p`,{role:`status`,className:`mt-1 text-xs text-foreground-subtle`,children:n(`helper.sharedPending`)}),t.kind===`unavailable`&&i(`p`,{role:`status`,className:`mt-1 text-xs text-foreground-subtle`,children:n(`helper.sharedUnavailable`)}),t.kind===`ready`&&t.caps.length<=1&&i(`p`,{className:`mt-1 text-xs text-foreground-muted`,children:n(`helper.sharedNone`)}),t.kind===`ready`&&t.caps.length>1&&e(`ul`,{className:`mt-1 flex flex-col gap-0.5 text-xs text-foreground`,children:[t.caps.filter(e=>e!==`switch`).map(e=>i(`li`,{children:n(`helper.cap.${e}`)},e)),t.modes.map(e=>i(`li`,{children:n(`helper.mode.${e}`)},e))]})]})}function Pc({view:t,nameOf:n}){let{t:r}=X();return i(`ul`,{className:`mt-1 flex flex-col gap-0.5 text-xs text-foreground`,"data-testid":`helper-command-rows`,children:t.rows.map(t=>e(`li`,{children:[n(t.deviceId),` — `,r(`helper.cap.${t.cap}`),` —`,` `,t.ok?r(`helper.commandOk`):r(`helper.commandFailed`),t.error===null?``:` — ${t.error}`]},`${t.deviceId}:${t.cap}:${t.at}`))})}function Fc({member:e,row:t,fleetKind:n,onRead:r}){let i=Lc(e),o=Rn({deviceId:t?.id??0},{enabled:n===`answered`&&t!==null});return a(()=>{if(n!==`answered`){r(i,{kind:`pending`});return}if(t===null){r(i,{kind:`ready`,caps:[],features:[]});return}if(o.status===`pending`){r(i,{kind:`pending`});return}if(o.status===`error`){r(i,{kind:`error`});return}r(i,{kind:`ready`,caps:o.data.entries.map(e=>e.capName),features:[...t.features]})},[o.data,o.status,n,i,r,t]),null}function Ic(e,t){let n=e.find(e=>e.addonId===t.source.addonId&&e.stableId===t.source.stableId);return n===void 0?null:{id:n.id,name:n.name,features:n.features}}function Lc(e){return`${e.source.addonId}/${e.source.stableId}`}function Rc(e,t){return e===void 0||e.kind!==t.kind?!1:e.kind!==`ready`||t.kind!==`ready`?!0:e.caps.join(`\0`)===t.caps.join(`\0`)&&e.features.join(`\0`)===t.features.join(`\0`)}c();function zc({deviceId:t,stableId:n}){let{t:a}=X(),s=n.startsWith(`composed-`)?n.slice(Ne.length):null,c=st({blockId:s??``},{enabled:s!==null}),l=Bt({deviceId:t},{enabled:s!==null}),u=Kt({projection:`slim`},{enabled:s!==null}),[d,f]=o(()=>new Map),p=gt(),m=Ut(),h=r((e,t)=>{f(n=>{let r=n.get(e);if(r?.name===t.name&&r.presence===t.presence)return n;let i=new Map(n);return i.set(e,t),i})},[]);if(s===null)return null;if(c.status===`pending`)return i(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:a(`helper.checking`)});if(c.status===`error`)return i(q,{title:a(`helper.outputUnavailable`),message:c.error.message});if(c.data.state!==`loaded`||c.data.view===null)return null;let _=Fe(c.data.view.block);if(_===null||!ji(_))return null;let v=_.helper;if(v.kind!==`group`)return null;let y=Ie(v.templateId);if(y===null)return null;let b=Hc(l.status,l.data,l.error?.message),x=Oi(b,y),S=vi(b),C=u.status===`success`?u.data.map(Uc):[],w=Wc(u.status),T=bi(v.members.map(e=>d.get(Vc(e))??{name:e.source.stableId,presence:`unknown`})),E=x.kind===`number`?x.unit===void 0?String(x.value):`${x.value} ${x.unit}`:x.kind===`boolean`?x.value?a(`helper.on`):a(`helper.off`):x.kind===`empty`?a(`helper.noReading`):null;return i(Sr,{headingId:`helper-group-status`,title:a(`helper.statusTitle`),icon:Ge,testId:`helper-group-status`,children:e(`div`,{className:`${g} flex flex-col gap-3`,children:[v.members.map(e=>i(Bc,{member:e,row:C.find(t=>t.addonId===e.source.addonId&&t.stableId===e.source.stableId)??null,fleetKind:w,onLive:h},Vc(e))),x.kind===`pending`&&i(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:a(`helper.outputPending`)}),x.kind===`unavailable`&&i(q,{title:a(`helper.outputUnavailable`),message:x.message}),E!==null&&i(nr,{value:E,label:a(`helper.template.${y.id}`)}),S.kind===`pending`&&i(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:a(`helper.reportingPending`)}),S.kind===`unavailable`&&i(q,{title:a(`helper.outputUnavailable`),message:S.message}),S.kind===`absent`&&i(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:a(`helper.reportingAbsent`)}),S.kind===`ready`&&i(`p`,{className:`text-sm text-foreground`,"data-testid":`helper-reporting`,children:a(`helper.reporting`,{included:S.included,total:S.total})}),S.kind===`ready`&&S.excluded>0&&e(`div`,{children:[i(`h3`,{className:`text-[10px] font-semibold uppercase tracking-wider text-foreground-subtle`,children:a(`helper.excluded`)}),T.kind===`pending`?i(`p`,{role:`status`,className:`mt-1 text-xs text-foreground-subtle`,children:a(`helper.excludedPending`)}):T.names.length===0?i(`p`,{className:`mt-1 text-xs text-foreground-muted`,children:a(`helper.excludedUnnamed`)}):i(`ul`,{className:`mt-1 flex flex-col gap-0.5 text-xs text-foreground`,"data-testid":`helper-excluded`,children:T.names.map(e=>i(`li`,{children:e},e))})]}),i(Mc,{template:y,members:v.members,fleet:C.map(e=>({id:e.id,name:e.name,addonId:e.addonId,stableId:e.stableId,features:e.features})),fleetKind:w,snapshot:b,nameOf:e=>{if(p===null)return C.find(t=>t.id===e)?.name??String(e);let t=p.byId.get(e);return t===void 0?String(e):lt(t,`compact`,p,m)}})]})})}function Bc({member:e,row:t,fleetKind:n,onLive:r}){let i=t?.online===!0,o=Bt({deviceId:t?.id??0},{enabled:n===`answered`&&t!==null&&i}),s=Ti(o.status,o.status===`success`?Si(o.data):void 0,e.cap,e.fieldPath),c=Fi({fleet:n,deviceOnline:n===`answered`?t===null?null:t.online:!0,field:s}),l=t?.name??e.source.stableId,u=At(t?.id??0,`compact`,l),d=t===null?l:u,f=Vc(e);return a(()=>{r(f,{name:d,presence:c})},[f,d,r,c]),null}function Vc(e){return`${e.source.addonId}/${e.source.stableId}/${e.cap}.${e.fieldPath}`}function Hc(e,t,n){return e===`pending`?{kind:`pending`}:e===`error`?{kind:`error`,message:n??``}:{kind:`answered`,caps:Si(t)}}function Uc(e){return{id:e.id,name:e.name,online:e.online,addonId:e.addonId,stableId:e.stableId,features:e.features??[]}}function Wc(e){return e===`pending`?`pending`:e===`error`?`error`:`answered`}function Gc(e,t){return{switchId:e,label:Le[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}}c();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:t,deviceName:r}){let{t:a}=X(),s=Vt(),[c,l]=o(null),u=Kt({isCamera:!0,projection:`slim`}),d=Wn(),f=u.data!==void 0,p=n(()=>u.data===void 0?[]:Jc(u.data,t),[u.data,t]),m=p.find(e=>e.id===c)??null,h=d.data===void 0?null:qc(d.data),g=d.error===null?null:d.error.message,_=async()=>{m===null||m.id===t||await s({title:a(`deviceMigrate.confirmTitle`,`Replace “{{source}}” with “{{target}}”?`,{source:r,target:m.name}),message:a(`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:r,target:m.name,sourceId:t,targetId:m.id}),confirmLabel:a(`deviceMigrate.confirmAction`,`Migrate`),variant:`danger`})&&d.mutate({sourceId:t,targetId:m.id})};return e(`div`,{className:`rounded-lg border border-border bg-surface px-4 py-3`,children:[e(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[e(`div`,{className:`min-w-0`,children:[i(`h2`,{className:`text-xs font-semibold uppercase tracking-wider text-foreground`,children:a(`deviceMigrate.title`,`Migrate to…`)}),i(`p`,{className:`mt-0.5 text-[11px] text-foreground-subtle`,children:a(`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:t})})]}),e(`div`,{className:`flex shrink-0 items-center gap-2`,children:[e(`select`,{"aria-label":a(`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:c===null?``:String(c),onChange:e=>{let t=e.target.value;l(t===``?null:Number(t))},children:[i(`option`,{value:``,children:f?a(`deviceMigrate.pickerPlaceholder`,`Select a camera…`):a(`deviceMigrate.pickerPending`,`Reading the fleet…`)}),p.map(t=>e(`option`,{value:String(t.id),children:[t.name,` (#`,t.id,`)`]},t.id))]}),e(`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:[i(Be,{className:`h-3 w-3`}),d.isPending?a(`deviceMigrate.running`,`Migrating…`):a(`deviceMigrate.action`,`Migrate`)]})]})]}),f&&p.length===0&&i(`p`,{className:`mt-2 text-[11px] text-foreground-subtle`,children:a(`deviceMigrate.noTargets`,`No other camera is adopted, so there is nothing to migrate to.`)}),g!==null&&i(`p`,{className:`mt-2 text-[11px] text-danger`,children:a(`deviceMigrate.failed`,`Migration failed: {{error}}`,{error:g})}),h!==null&&i(Xc,{report:h})]})}function Xc({report:t}){let{t:n}=X(),r=t.verdict===`quiet`;return e(`div`,{className:`mt-3 space-y-2 border-t border-border pt-3`,children:[i(`p`,{className:`text-[11px] text-foreground-subtle`,children:n(`deviceMigrate.swapped`,`The replacement now answers on number {{inheritedId}}; the old camera was handed number {{retiredId}}.`,{inheritedId:t.inheritedId,retiredId:t.retiredId})}),r?e(`div`,{className:`flex items-start gap-2 rounded-md border border-success/30 bg-success/5 px-3 py-2`,children:[i(se,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-success`}),i(`p`,{className:`text-[11px] leading-relaxed text-foreground`,children:n(`deviceMigrate.quiet`,`Every function on the replaced camera was switched off — the old hardware is quiet.`)})]}):e(`div`,{className:`rounded-md border border-warning/40 bg-warning/5 px-3 py-2`,children:[e(`div`,{className:`flex items-start gap-2`,children:[i(D,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-warning`}),i(`p`,{className:`text-[11px] leading-relaxed text-foreground`,children:n(`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.`)})]}),i(`ul`,{className:`mt-2 space-y-1 pl-5`,children:t.stillLive.map(t=>e(`li`,{className:`text-[11px] text-foreground`,children:[i(`span`,{className:`font-medium`,children:t.label}),t.detail!==null&&e(`span`,{className:`text-foreground-subtle`,children:[` — `,t.detail]})]},t.switchId))})]}),t.neverOffered.length>0&&e(`div`,{className:`rounded-md border border-border px-3 py-2`,children:[e(`div`,{className:`flex items-start gap-2`,children:[i(qe,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),i(`p`,{className:`text-[11px] leading-relaxed text-foreground-subtle`,children:n(`deviceMigrate.neverOffered`,`The replaced camera never offered these, so there was nothing to switch off. They are not running.`)})]}),i(`ul`,{className:`mt-2 space-y-1 pl-5`,children:t.neverOffered.map(e=>i(`li`,{className:`text-[11px] text-foreground-subtle`,children:e.label},e.switchId))})]})]})}c();function Zc({deviceId:t}){let{t:n}=X(),[r,a]=o(null),s=_n({onSuccess:e=>{a(e.changed?`Re-aligned with source — ${e.rebuiltChildren} child${e.rebuiltChildren===1?``:`ren`} rebuilt.`:`Already up to date.`)},onError:e=>a(`Re-sync failed: ${e.message}`)});return e(`div`,{className:`rounded-lg border border-border bg-surface px-4 py-3`,children:[e(`div`,{className:`flex items-center justify-between gap-3`,children:[e(`div`,{children:[i(`h2`,{className:`text-xs font-semibold uppercase tracking-wider text-foreground`,children:n(`device.resyncButton.reSync`,`Re-sync`)}),i(`p`,{className:`mt-0.5 text-[11px] text-foreground-subtle`,children:n(`device.resyncButton.reAlignThisDeviceS`,`Re-align this device's type, role, capabilities and units with its source.`)})]}),e(`button`,{type:`button`,disabled:s.isPending,onClick:()=>{a(null),s.mutate({camDeviceId:t})},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:[i(me,{className:`h-3 w-3 ${s.isPending?`animate-spin`:``}`}),s.isPending?n(`device.resyncButton.reSyncing`,`Re-syncing…`):n(`device.resyncButton.reSync`,`Re-sync`)]})]}),r!==null&&i(`p`,{className:`mt-2 text-[11px] text-foreground-subtle`,children:r})]})}function Qc(e){return e<1e3?`${e.toFixed(0)} kbps`:`${(e/1e3).toFixed(1)} Mbps`}function $c({device:t}){let{t:n}=X(),r=Kr(),a=typeof t.id==`number`?t.id:null,o=typeof t.name==`string`?t.name:``,s=At(a??0,`full`,o),c=String(t.type??``),l=c===U.Camera,u=c===U.Hub,d=t.features??[],f=d.includes(ve.Resyncable),{data:p}=wn({deviceId:a??0},{enabled:a!==null&&l,refetchInterval:5e3}),m=p?.streams??{},h=Object.entries(m),g=d.includes(ve.DoorbellButton),_=zn(g?{deviceId:a??void 0,historyLimit:10}:void 0),v=_.latest?Date.now()-_.latest.timestamp<3e4:!1;return e(`div`,{className:`space-y-5`,children:[t.addonId===`composer`&&a!==null&&typeof t.stableId==`string`&&i(zc,{deviceId:a,stableId:t.stableId}),u&&a!==null&&i(xr,{deviceId:a,onOpenChild:e=>r(`/devices/${e}`)}),f&&a!==null&&i(Zc,{deviceId:a}),l&&a!==null&&i(Yc,{deviceId:a,deviceName:s}),a!==null&&i(jc,{deviceId:a,isCamera:l}),l&&a!==null&&i(En,{widgetId:`pipeline-orchestrator/pipeline-quick-stats`,host:`device-tab`,deviceId:a}),g&&i(rt,{history:_.history,latestIsFresh:v}),l&&a!==null&&i(En,{widgetId:`stream-broker/stream-broker-panel`,host:`device-tab`,deviceId:a}),l&&h.length>0&&e(`div`,{className:`@container rounded-lg border border-border bg-surface overflow-hidden`,style:{containerType:`inline-size`},children:[i(`div`,{className:`border-b border-border px-4 py-2`,children:i(`h2`,{className:`text-xs font-semibold text-foreground uppercase tracking-wider`,children:n(`device.overviewTab.streamNetwork`,`Stream Network`)})}),i(`div`,{className:`divide-y divide-border`,children:h.map(([t,r])=>e(`div`,{className:`px-4 py-2.5`,children:[e(`div`,{className:`flex items-center gap-2 mb-2`,children:[i(oe,{className:`h-3 w-3 text-foreground-subtle`}),i(`span`,{className:`text-[11px] font-medium text-foreground`,children:t})]}),e(`div`,{className:`grid grid-cols-2 @[640px]:grid-cols-4 gap-2`,children:[i(el,{label:n(`device.overviewTab.nominal`,`Nominal`),value:Qc(r.nominalBitrateKbps??0)}),i(el,{label:n(`device.overviewTab.observed`,`Observed`),value:Qc(r.observedBitrateKbps??0)}),i(el,{label:n(`device.overviewTab.peak`,`Peak`),value:Qc(r.peakBitrateKbps??0)}),i(el,{label:n(`device.overviewTab.packetLoss`,`Packet Loss`),value:`${(r.packetLossPercent??0).toFixed(2)}%`,warning:(r.packetLossPercent??0)>1})]})]},t))})]}),i(Wr,{})]})}function el({label:t,value:n,warning:r}){return e(`div`,{children:[i(`p`,{className:`text-[10px] text-foreground-subtle`,children:t}),i(`p`,{className:`text-xs font-medium ${r?`text-warning`:`text-foreground`}`,children:n})]})}var tl=`history`,nl=[{id:`overview`,labelKey:`helpers.structuralTabs.overview`,cameraOnly:!1,adminOnly:!1},{id:`config`,labelKey:`helpers.structuralTabs.config`,cameraOnly:!1,adminOnly:!1},{id:Gr,labelKey:`helpers.structuralTabs.customize`,cameraOnly:!1,adminOnly:!0},{id:tl,labelKey:`helpers.structuralTabs.history`,cameraOnly:!1,adminOnly:!1},{id:`detection-pipeline`,labelKey:`helpers.structuralTabs.detectionPipeline`,cameraOnly:!0,adminOnly:!1},{id:`bindings`,labelKey:`helpers.structuralTabs.bindings`,cameraOnly:!0,adminOnly:!1}],rl=new Set([U.Hub,U.Container]);function il(e,t){let n=e===U.Camera,r=e===void 0||!rl.has(e);return nl.filter(e=>(n||!e.cameraOnly)&&(t||!e.adminOnly)&&(r||e.id!==`history`)).map(({id:e,labelKey:t})=>({id:e,label:Y.t(t)}))}function al({provider:e,integrationId:t,name:n}){let r=Kr(),a=t===null?`/integrations`:`/integrations/${t}`,o=n===null?`Open integrations`:`Open integration ${n}`;return i(`button`,{type:`button`,onClick:()=>r(a),className:`shrink-0 rounded-md transition-opacity hover:opacity-80 focus:outline-none focus-visible:ring-1 focus-visible:ring-primary/50`,title:o,"aria-label":o,children:i(Jr,{type:e,size:`lg`})})}c();var ol=[{id:`logs`,icon:I,labelKey:`common.logs`},{id:`repl`,icon:Ke,labelKey:`deviceDetail.repl`},{id:`events`,icon:E,labelKey:`common.events`},{id:`state`,icon:ee,labelKey:`common.state`}];function sl(){let{t:a}=X(),s=ie(),c=Ur(),u=Number(c.deviceId),f=Number.isFinite(u),p=Kr(),m=l(),h=Vt(),g=z(),{user:v}=jr(),y=v?.isAdmin===!0,[b,x]=Rr(),C=b.get(`tab`)??`overview`,T=b.get(`sub`),[E,D]=o(`logs`),O=`device-detail.left-col-width-px`,[k,A]=o(()=>{if(typeof window>`u`)return null;let e=window.localStorage.getItem(O),t=e?Number(e):NaN;return Number.isFinite(t)&&t>0?t:null}),M=t(k);M.current=k;function ee(e){e.preventDefault();let t=e.clientX,n=e.currentTarget.previousElementSibling?.getBoundingClientRect().width??k??0,r=Math.max(330,Math.floor(window.innerWidth*.7)),i=e=>{A(Math.max(280,Math.min(r,n+(e.clientX-t))))},a=()=>{document.removeEventListener(`mousemove`,i),document.removeEventListener(`mouseup`,a);let e=M.current;if(e!==null)try{window.localStorage.setItem(O,String(Math.round(e)))}catch{}document.body.style.userSelect=``,document.body.style.cursor=``};document.body.style.userSelect=`none`,document.body.style.cursor=`col-resize`,document.addEventListener(`mousemove`,i),document.addEventListener(`mouseup`,a)}let{data:N,isLoading:te,isError:ne}=_r({deviceId:u},{enabled:f,refetchInterval:5e3,retry:1}),{data:P}=Er({deviceId:u},{enabled:f}),re=n(()=>{let e=P?.settings?.sections??[],t=P?.live?.sections??[],n=[...e,...t],r=new Set;for(let e of n)e.location===`top-tab`&&e.tab&&r.add(e.tab===`zones`?`detection-pipeline`:e.tab);return n.some(Br)&&r.add(Vr),[...r].map(e=>e===`export`?{id:e,label:Mr,isAddonContrib:!0}:{id:e,label:De[e]?.label??e,isAddonContrib:!0})},[P]),F=N,ae=String(F?.name??c.deviceId??`Device`),oe=F?.online===!0,se=oe?`online`:`offline`,I=String(F?.addonId??`rtsp`),L=F?.features??[],R=F?.type,B=R===U.Camera,{data:le}=zr(f?u:0),ue=R===U.Container,fe=n(()=>(le??[]).map(e=>({id:e.id,stableId:e.stableId,type:e.type,...e.sourceInfo?{sourceInfo:{id:e.sourceInfo.id}}:{}})),[le]),V=n(()=>ue?pt(fe,typeof F?.linkDeviceId==`number`?F.linkDeviceId:null,typeof F?.primaryChildEntityId==`string`?F.primaryChildEntityId:null)?.id??null:null,[ue,fe,F?.linkDeviceId,F?.primaryChildEntityId]),{data:H}=Er({deviceId:V??0},{enabled:V!==null}),pe=n(()=>{if(V===null)return[];let e=H?.settings?.sections??[],t=H?.live?.sections??[],n=new Set;for(let r of[...e,...t])r.location===`top-tab`&&r.tab&&n.add(r.tab);return[...n].map(e=>({id:e,label:De[e]?.label??e,isAddonContrib:!0,childDeviceId:V}))},[V,H]),ge=n(()=>Ua({sections:[...P?.settings?.sections??[],...P?.live?.sections??[]],deviceId:u,...V===null?{}:{child:{sections:[...H?.settings?.sections??[],...H?.live?.sections??[]],deviceId:V}}}),[P,H,u,V]),_e=typeof F?.parentDeviceId==`number`?F.parentDeviceId:null,{data:ye}=_r({deviceId:_e??0},{enabled:_e!==null}),be={id:Number.isFinite(u)?u:0,name:ae,type:`unknown`,stableId:``,parentDeviceId:null},xe=xt(F??be,`full`),Se=xt(ye??be,`full`),W=Nn(),Ce=F?.disabled!==!0,we=n(()=>{let e=P?.settings?.sections??[],t=P?.live?.sections??[];return Nr([...e,...t],R,y,P!==void 0)},[P,R,y]),Te=n(()=>{let e=new Set,t=[];for(let n of[...il(R,y),...re,...pe])n.id===`config`&&!we||e.has(n.id)||(e.add(n.id),t.push(n));return t},[R,y,re,pe,we]),Ee=n(()=>Fs(Te,C),[Te,C]),G=r(e=>{x(t=>{let n=new URLSearchParams(t);e===`overview`?n.delete(`tab`):n.set(`tab`,e),n.delete(`sub`);for(let e of Gi)n.delete(e);return n},{replace:!0})},[x]),Oe=r(e=>{x(t=>{let n=new URLSearchParams(t);return n.set(`sub`,e),n},{replace:!0})},[x]),ke=(le??[]).length>0,Ae=n(()=>ol.filter(({featureGate:e})=>!e||L.includes(e)),[L]),{data:je}=xn(void 0),Me=n(()=>F?Pt(F,je):null,[F,je]),K=Me?.kind===`resolved`?Me.integration:null,Ne=K===null?Me?.kind===`unknown`?a(`deviceDetail.loadingIntegration`):Me?.kind===`orphan`?a(`deviceDetail.missingIntegration`):a(`deviceDetail.noIntegration`):K.name,Pe=K!==null&&K.addonId===I?K.name:I,Fe=Nt({onSuccess:()=>{m.invalidateQueries({queryKey:[[`deviceManager`]]}),p(K?.id?`/integrations/${K.id}`:`/integrations`)}}),Ie=Zn({onSuccess:()=>{m.invalidateQueries({queryKey:[[`deviceManager`]]})}}),Le=Jn({onSuccess:()=>{m.invalidateQueries({queryKey:[[`deviceManager`]]})}}),Re=Qe(),ze=bt({onSuccess:()=>{m.invalidateQueries({queryKey:[[`deviceManager`]]})}}),Be=L.includes(ve.Rebootable),Ve=L.includes(ve.BatteryOperated),He=Ar(g.trpcClient,Ve&&f?u:null),Ue=Wt(g.trpcClient,f?u:null),We=ce(g.trpcClient,f?u:null,e=>e.runningState),Ge=We===void 0||We.running===null?null:We.running,Ke=yr(R??`unknown`,s).icon,[qe,Je]=o(!1),Ye=async()=>{if(!qe){Je(!0);try{let e=xe.replace(/[^a-zA-Z0-9_.-]+/g,`_`),t=new Date().toISOString().replace(/[:.]/g,`-`);await oa(`${j}/${String(u)}.jpg?force=1`,`${e}-${t}.jpg`)}finally{Je(!1)}}},Xe=Ie.isPending||Le.isPending,{data:Ze}=pn({deviceId:u},{enabled:f&&B,refetchInterval:1e4}),$e=Ze?.agentNodeId??null,et=typeof $e==`string`&&$e.length>0&&!$e.startsWith(`addon:`)?$e:void 0,{data:tt}=Yt({deviceId:u,...et?{nodeId:et}:{}},{enabled:f&&B,refetchInterval:3e3,retry:!1}),{data:nt}=zt({deviceId:u},{enabled:f&&B,refetchInterval:3e3,retry:!1}),rt=nt?.level?.dbfs??null;function at(){if(!f)return null;switch(Ee){case`overview`:return i($c,{device:F??{}});case`config`:return i(Bs,{deviceId:u,activeSubTab:T,onSubTabChange:Oe,deviceType:R,isAdmin:y});case`detection-pipeline`:return i(wc,{deviceId:u,activeSubTab:T,onSubTabChange:Oe});case`bindings`:return i(Is,{deviceId:u});case tl:return i(Gn,{deviceId:u,onNavigate:e=>p(e)});case Gr:return i(js,{deviceId:u});default:{let e=Ee,t=re.some(t=>t.id===e),n=pe.find(t=>t.id===e);if(!t&&n===void 0)return null;let r=n?.childDeviceId??u;if(e===`export`)return i(Pr,{deviceId:u,sectionFilter:Br,activeSubTab:T,onSubTabChange:Oe});let a=i(Pr,{deviceId:r,sectionFilter:t=>t.location===`top-tab`&&(t.tab===e||e===`detection-pipeline`&&t.tab===`zones`),flattenSubTabs:e===`detection-pipeline`,activeSubTab:T,onSubTabChange:Oe});return n!==void 0&&r!==u?i(cr,{deviceId:r,children:a}):a}}}return f?te?e(`div`,{className:`flex flex-col h-full`,children:[e(`div`,{className:`border-b border-border bg-surface px-6 py-4`,children:[i(`div`,{className:`h-4 w-48 rounded bg-surface-hover animate-pulse mb-3`}),i(`div`,{className:`h-8 w-64 rounded bg-surface-hover animate-pulse`})]}),i(`div`,{className:`flex-1 p-6`,children:i(`div`,{className:`h-40 rounded-lg border border-border bg-surface animate-pulse`})})]}):ne||!N?e(`div`,{className:`flex flex-col items-center justify-center h-full gap-3 text-foreground-subtle`,children:[i(`p`,{className:`text-lg font-semibold text-foreground`,children:a(`deviceDetail.deviceNotFound`,`Device not found`)}),i(`p`,{className:`text-xs`,children:i(Hr,{i18nKey:`deviceDetail.noDeviceWithId`,values:{id:u},components:{code:i(`code`,{className:`font-mono bg-surface px-1.5 py-0.5 rounded text-[11px]`})}})}),i(`button`,{onClick:()=>p(`/integrations`),className:`mt-2 rounded-lg bg-primary px-4 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 transition-colors`,children:a(`deviceDetail.backToIntegrations`,`Back to Integrations`)})]}):e(`div`,{className:`absolute inset-0 flex flex-col overflow-clip`,children:[e(`div`,{className:`border-b border-border bg-surface px-6 py-3 flex-shrink-0`,children:[i(`div`,{className:`mb-2`,children:i(it,{items:[{label:a(`deviceDetail.integrations`,`Integrations`),onClick:()=>p(`/integrations`)},K===null?{label:Ne}:{label:Ne,onClick:()=>p(`/integrations/${K.id}`)},{label:xe}]})}),e(`div`,{className:`flex items-center gap-2 sm:gap-3`,children:[K!==null&&i(al,{provider:K.addonId,integrationId:K.id,name:K.name}),i(Mt,{running:Ge,children:i(Ke,{className:`h-5 w-5 text-foreground-subtle shrink-0`,"aria-hidden":!0})}),e(`div`,{className:`min-w-0 flex-1`,children:[e(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[i(`h1`,{className:`text-sm sm:text-base font-semibold text-foreground truncate`,children:xe}),i(vn,{status:se}),Ve&&i(Lt,{status:He,variant:`full`}),i(Un,{status:Ue})]}),_e!==null&&ye&&e(`button`,{type:`button`,onClick:()=>p(`/devices/${_e}`),className:`text-[10px] text-foreground-subtle hover:text-primary transition-colors mt-0.5 inline-flex items-center gap-1`,title:a(`deviceDetail.openParentDevice`,`Open parent device {{name}}`,{name:Se}),children:[i(`span`,{children:`↑`}),i(`span`,{className:`truncate`,children:Se})]}),i(`div`,{className:`hidden md:flex items-center gap-3 mt-0.5 text-[10px] text-foreground-subtle`,children:L.length>0&&i(Ir,{capabilities:L})})]}),tt&&i(`div`,{className:`hidden lg:flex`,children:i(cl,{metrics:tt,dbfs:rt})}),e(`div`,{className:`flex items-center gap-1 shrink-0`,children:[e(`button`,{onClick:async()=>{Ce?await h({title:a(`deviceDetail.disable`,`Disable "{{name}}"?`,{name:xe}),message:a(`deviceDetail.theDeviceWillStopProcessing`,`The device will stop processing streams and events. You can re-enable it later.`),confirmLabel:a(`common.disable`,`Disable`),variant:`danger`})&&Le.mutate({deviceId:u}):Ie.mutate({deviceId:u})},disabled:Xe,title:Ce?a(`deviceDetail.disableDevice`,`Disable device`):a(`deviceDetail.enableDevice`,`Enable device`),className:`inline-flex items-center gap-1.5 rounded-lg px-2 sm:px-2.5 py-1.5 text-[11px] font-medium border transition-colors disabled:opacity-50 ${Ce?`border-success/30 text-success hover:bg-success/10`:`border-border text-foreground-subtle/50 hover:text-foreground hover:bg-surface-hover`}`,children:[i(_,{className:`h-3.5 w-3.5`}),i(`span`,{className:`hidden sm:inline`,children:Xe?a(`deviceDetail.updating`,`Updating…`):Ce?a(`deviceDetail.enabled`,`Enabled`):a(`deviceDetail.disabled`,`Disabled`)})]}),i(`div`,{className:`hidden sm:block h-5 w-px bg-border mx-1`}),B&&e(d,{children:[i(pa,{deviceId:u}),i(`div`,{className:`hidden sm:block h-5 w-px bg-border mx-1`})]}),i(ha,{deviceId:u}),i(Sn,{triggerClassName:`ml-1`,items:[{id:`snapshot`,label:a(`deviceDetail.takeSnapshot`,`Take snapshot`),description:a(`deviceDetail.fetchAFreshFrameAnd`,`Fetch a fresh frame and download it.`),icon:w,disabled:qe,onClick:()=>{Ye()}},{id:`reboot`,label:a(`deviceDetail.rebootDevice`,`Reboot device`),description:a(`deviceDetail.cameraGoesOfflineFor30`,`Camera goes offline for ~30 seconds.`),icon:he,hidden:!Be,disabled:Re.isPending,danger:!0,onClick:async()=>{await h({title:a(`deviceDetail.reboot`,`Reboot "{{name}}"?`,{name:xe}),message:a(`deviceDetail.theCameraWillGoOffline`,`The camera will go offline for around 30 seconds while the firmware reboots.`),confirmLabel:a(`deviceDetail.reboot2`,`Reboot`),variant:`danger`})&&Re.mutate({deviceId:u})}},{id:`restart-addon`,label:a(`deviceDetail.restartAddon`,`Restart addon`),description:a(`deviceDetail.bouncesEveryDeviceServedBy`,`Bounces every device served by {{servingAddonLabel}}.`,{servingAddonLabel:Pe}),icon:me,disabled:ze.isPending,danger:!0,onClick:async()=>{await h({title:a(`deviceDetail.restart`,`Restart "{{servingAddonLabel}}"?`,{servingAddonLabel:Pe}),message:a(`deviceDetail.restartingTheAddonWillBriefly`,`Restarting the addon will briefly disconnect every device served by it (not just "{{name}}"). Streams will reconnect automatically.`,{name:xe}),confirmLabel:a(`deviceDetail.restart2`,`Restart`),variant:`danger`})&&ze.mutate({addonId:I})}},{id:`delete`,label:a(`deviceDetail.deleteDevice`,`Delete device`),description:a(`deviceDetail.removeTheDeviceAndAll`,`Remove the device and all its settings.`),icon:S,separatorBefore:!0,disabled:Fe.isPending,danger:!0,onClick:async()=>{await h({title:a(`deviceDetail.delete`,`Delete "{{name}}"?`,{name:xe}),message:a(`deviceDetail.thisWillRemoveTheDevice`,`This will remove the device and all its settings. This action cannot be undone.`),confirmLabel:a(`common.delete`,`Delete`),variant:`danger`})&&Fe.mutate({deviceId:u})}}]})]})]})]}),i(cr,{deviceId:u,device:F??void 0,children:i(qt,{children:i(Dr,{children:i(de,{children:i(Cn,{children:e(`main`,{className:W?`flex-1 overflow-y-auto flex flex-col`:`flex-1 min-h-0 overflow-hidden flex flex-row`,children:[e(`div`,{className:W?`flex flex-col bg-surface`:`${k===null?`w-1/2 lg:w-1/3`:``} flex-shrink-0 flex flex-col bg-surface min-h-0 overflow-y-auto`,style:!W&&k!==null?{width:`${String(k)}px`}:void 0,children:[i(`div`,{className:B?`flex-shrink-0 border-b border-border-subtle bg-black`:W?`flex-shrink-0 border-b border-border-subtle bg-surface`:`shrink-0 border-b border-border-subtle bg-surface`,children:B?i($a,{deviceId:u,intercomAvailable:L.includes(ve.TwoWayAudio)}):e(`div`,{children:[i(Ba,{deviceId:u,deviceName:xe,deviceType:R??`unknown`,provider:I,isOnline:oe,features:L}),i(Va,{deviceId:u,widgets:ge})]})}),B&&ge.length>0&&i(`div`,{className:`flex-shrink-0 border-b border-border-subtle bg-surface pt-3 sm:pt-4`,children:i(Va,{deviceId:u,widgets:ge})}),e(`div`,{className:W?`flex flex-col border-b border-border`:`flex-1 min-h-64 flex flex-col overflow-hidden`,children:[i(`div`,{className:`flex-shrink-0 border-b border-border-subtle px-2 py-1.5`,children:i(`div`,{className:`flex gap-1 overflow-x-auto -mx-1 px-1 pb-0.5`,children:Ae.map(({id:t,labelKey:n,icon:r})=>{let o=E===t;return e(`button`,{onClick:()=>D(t),title:a(n),className:`flex items-center gap-1 rounded px-2 py-1 text-[10px] font-medium transition-colors flex-shrink-0 ${o?`bg-primary/15 text-primary`:`text-foreground-subtle hover:text-foreground hover:bg-surface-hover`}`,children:[i(r,{className:`h-3 w-3`}),a(n)]},t)})})}),e(`div`,{className:W?`h-72 overflow-hidden`:`flex-1 min-h-0 overflow-hidden`,children:[E===`logs`&&i(eo,{deviceId:u,containerDeviceId:R===`container`?u:void 0}),E===`repl`&&i(to,{deviceId:u}),E===`events`&&i(no,{deviceId:u}),E===`state`&&i(ro,{deviceId:u})]})]})]}),!W&&i(`div`,{role:`separator`,"aria-orientation":`vertical`,title:a(`deviceDetail.dragToResize`,`Drag to resize`),onMouseDown:ee,className:`flex-shrink-0 w-1 cursor-col-resize bg-border hover:bg-primary/40 transition-colors group relative z-10`,children:i(`span`,{className:`absolute inset-y-0 -left-1 -right-1`})}),e(`div`,{className:W?`flex flex-col`:`flex-1 min-w-0 min-h-0 flex flex-col overflow-hidden`,children:[i(`div`,{className:`flex-shrink-0 border-b border-border bg-surface px-4`,children:i(`div`,{className:`flex flex-nowrap overflow-x-auto md:flex-wrap md:overflow-x-visible items-center gap-0`,children:Te.map(t=>{let n=Ee===t.id;return e(`button`,{onClick:()=>G(t.id),className:`relative flex-shrink-0 px-3 py-2 text-xs font-medium transition-colors ${n?`text-primary`:`text-foreground-subtle hover:text-foreground`}`,children:[t.label,n&&i(`span`,{className:`absolute bottom-0 left-0 right-0 h-0.5 rounded-full bg-primary`})]},t.id)})})}),e(`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:[Ee===`overview`&&ke&&i(ga,{parentDeviceId:u}),at()]})]})]})})})})})})]}):e(`div`,{className:`flex flex-col items-center justify-center h-full gap-3 text-foreground-subtle`,children:[i(`p`,{className:`text-lg font-semibold text-foreground`,children:a(`deviceDetail.invalidDeviceId`,`Invalid device id`)}),i(`p`,{className:`text-xs`,children:i(Hr,{i18nKey:`deviceDetail.invalidSegment`,values:{segment:c.deviceId},components:{code:i(`code`,{className:`font-mono bg-surface px-1.5 py-0.5 rounded text-[11px]`})}})}),i(`button`,{onClick:()=>p(`/integrations`),className:`mt-2 rounded-lg bg-primary px-4 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 transition-colors`,children:a(`deviceDetail.backToIntegrations`,`Back to Integrations`)})]})}function cl({metrics:t,dbfs:n}){let r=ie(),{t:a}=X(),o=qn(t.phase??`idle`,r);return e(`div`,{className:`flex items-center gap-3 flex-shrink-0`,children:[e(`div`,{className:`flex items-center gap-1.5`,children:[i(`span`,{className:`h-1.5 w-1.5 rounded-full ${o.dotClass}`}),i(`span`,{className:`text-[10px] font-medium ${o.textColor}`,children:o.label})]}),i(`div`,{className:`h-3 w-px bg-border`}),e(`div`,{className:`flex items-center gap-1 text-[10px] text-foreground-subtle`,children:[i(L,{className:`h-3 w-3`}),i(`span`,{className:`text-foreground tabular-nums`,children:(t.actualFps??0).toFixed(1)}),i(`span`,{children:a(`common.fpsWord`)})]}),e(`div`,{className:`flex items-center gap-1 text-[10px] text-foreground-subtle`,children:[i(ne,{className:`h-3 w-3`}),i(`span`,{className:`text-foreground tabular-nums`,children:(t.avgInferenceTimeMs??0).toFixed(0)}),i(`span`,{children:`ms`})]}),e(`div`,{className:`flex items-center gap-1 text-[10px] text-foreground-subtle`,title:a(`deviceDetail.currentAudioLevelDbfs`,`Current audio level (dBFS)`),children:[i(h,{className:`h-3 w-3`}),i(`span`,{className:`text-foreground tabular-nums`,children:n==null?`—`:n.toFixed(0)}),i(`span`,{children:`dB`})]}),(t.queueDepth??0)>0&&e(`span`,{className:`text-[10px] text-warning tabular-nums`,children:[`q:`,t.queueDepth]})]})}export{sl as DeviceDetailPage};
|