@camstack/addon-admin-ui 1.2.688 → 1.2.690
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/CHANGELOG.md +20 -0
- package/dist/assets/Addons-Ckr6vlsW.js +5 -0
- package/dist/assets/{AdminPage-BGtK1GBq.js → AdminPage-z8USGyNk.js} +1 -1
- package/dist/assets/{AdminSectionedPage-CRtQpSxT.js → AdminSectionedPage-CtcZ5jHa.js} +1 -1
- package/dist/assets/AiProfiles-DZj0TWuh.js +3 -0
- package/dist/assets/Archive-B0FJwta9.js +1 -0
- package/dist/assets/ArchiveCamera-DdovP4ro.js +1 -0
- package/dist/assets/{BootstrapSettingsForm-BS87l0cS.js → BootstrapSettingsForm-CKBDm4C-.js} +1 -1
- package/dist/assets/Build-B3CB1er7.js +40 -0
- package/dist/assets/{Calendars-CF3LuetJ.js → Calendars-DeXYk6f7.js} +1 -1
- package/dist/assets/{CameraGrids-6UFohBNL.js → CameraGrids-A_aGLmzE.js} +1 -1
- package/dist/assets/{Cluster-mnQtI40N.js → Cluster-D2auKPXI.js} +1 -1
- package/dist/assets/{CompositionBlockEditor-CY2C2J8Z.js → CompositionBlockEditor-DtVxeX5F.js} +2 -2
- package/dist/assets/CompositionEditorPage-BvetDCib.js +1 -0
- package/dist/assets/Data-oQJyojZK.js +2 -0
- package/dist/assets/DeviceDetail-DPxmWhcP.js +1 -0
- package/dist/assets/{Devices-MX4ikexb.js → Devices-3Lm2uV9o.js} +1 -1
- package/dist/assets/EmbedDevicePage-BgNfY1Ap.js +1 -0
- package/dist/assets/{EmbedPlayerPage-DRlowAOp.js → EmbedPlayerPage-BFXQpQxb.js} +1 -1
- package/dist/assets/History-jl2iyeKb.js +1 -0
- package/dist/assets/Identity-BpPWgRxJ.js +1 -0
- package/dist/assets/InstancesTable-DIKWKA5W.js +1 -0
- package/dist/assets/IntegrationDetail-ClVirS0M.js +1 -0
- package/dist/assets/{Integrations-DpijggGk.js → Integrations-CldsYVl0.js} +2 -2
- package/dist/assets/Integrations-CprYyiDb.js +1 -0
- package/dist/assets/Library-B86tjZ0-.js +1 -0
- package/dist/assets/Locations-CpNbotTl.js +3 -0
- package/dist/assets/Logs-DSr8wCY-.js +1 -0
- package/dist/assets/{MaskShapeCanvas-DjZ_ENJI.js → MaskShapeCanvas-_BFcQxc-.js} +1 -1
- package/dist/assets/{MotionZonesSettings-BRV1q6cp.js → MotionZonesSettings-DJDcu3fl.js} +1 -1
- package/dist/assets/MyAccess-DqKyBAxI.js +2 -0
- package/dist/assets/{Network-A8Hzlr9I.js → Network-Csm4YFXB.js} +1 -1
- package/dist/assets/NodeAddonsSettingsPanel-FjpwQjGM.js +2 -0
- package/dist/assets/Notifications-B-JLj82A.js +1 -0
- package/dist/assets/PanelContent-DJ8p-hQ1.js +2 -0
- package/dist/assets/Pipeline-DIXgco7S.js +1 -0
- package/dist/assets/{PrivacyMaskSettings-YvPDriCm.js → PrivacyMaskSettings-Dx5nRU-t.js} +1 -1
- package/dist/assets/{SceneMonitorEditor-DH2-nekM.js → SceneMonitorEditor-DFZ94G-a.js} +1 -1
- package/dist/assets/{ServerShell-W8Wp5cGt.js → ServerShell-BYRylYTw.js} +1 -1
- package/dist/assets/SessionsList-BcO2x9OZ.js +2 -0
- package/dist/assets/{Showroom-DFesEW-P.js → Showroom-DO1bQcNO.js} +1 -1
- package/dist/assets/StorageLocationsTable-BymZx5tG.js +1 -0
- package/dist/assets/System-dsyXpTx9.js +1 -0
- package/dist/assets/TemplateEditorDialog-DJIaNKn3.js +1 -0
- package/dist/assets/Terminal-BiXbwaPr.js +3 -0
- package/dist/assets/{TerminalPanel-J1w2vmDS.js → TerminalPanel-BeJx-I2E.js} +2 -2
- package/dist/assets/{TrainingProviders-BFbXHvOM.js → TrainingProviders-CPV9_SJC.js} +1 -1
- package/dist/assets/{Viewer-ZYjr8fFf.js → Viewer-BN42pCqQ.js} +1 -1
- package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-D3ruWlC-.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-DQNUYumg.js} +1 -1
- package/dist/assets/{action-draft-DNplCdnd.js → action-draft-BBdPH6FV.js} +1 -1
- package/dist/assets/{ai-page.helpers-CLp_BM_b.js → ai-page.helpers-ChgVcsV9.js} +1 -1
- package/dist/assets/{assignment-candidates-Cs1bHYCE.js → assignment-candidates-Bs3KAjz2.js} +1 -1
- package/dist/assets/{authed-media-D3P2p3qZ.js → authed-media-BK50tJc4.js} +1 -1
- package/dist/assets/{board-model-CEczoawG.js → board-model-CWzkqJEj.js} +1 -1
- package/dist/assets/circle-play-BxUrE_Qy.js +1 -0
- package/dist/assets/client-DhfZUoXe.js +1120 -0
- package/dist/assets/{command-vocab-Dp8EnV9z.js → command-vocab-B3pUOKtp.js} +1 -1
- package/dist/assets/device-detail-B0RHrAPi.js +1 -0
- package/dist/assets/{device-integration-icon-CGnRiBbM.js → device-integration-icon-JcMIVFtX.js} +1 -1
- package/dist/assets/device-picker-model-B2oUIKRS.js +1 -0
- package/dist/assets/{dist-DVUXvJ_X.js → dist-BNuE6NKf.js} +1 -1
- package/dist/assets/dist-CyFeeFb8.js +1120 -0
- package/dist/assets/{format-BqZcr5Z7.js → format-iFFzavy7.js} +1 -1
- package/dist/assets/{hostInit-BCFIcylY.js → hostInit-CzaZPFle.js} +1 -1
- package/dist/assets/i18n-DCYaeyv_.js +1 -0
- package/dist/assets/icons-CXirq6Hu.js +1 -0
- package/dist/assets/index-CpurjMmX.css +2 -0
- package/dist/assets/index-DPyWa2vo.js +6 -0
- package/dist/assets/{linked-devices-model-BIS0JhHd.js → linked-devices-model-CuXMtCW5.js} +1 -1
- package/dist/assets/{mf-entry-bootstrap-0-8782dcf2.js → mf-entry-bootstrap-0-02bb2c8e.js} +2 -2
- package/dist/assets/mount-B2oUIKRS.js +1 -0
- package/dist/assets/{notification-rule-status-ikR-6LJe.js → notification-rule-status-zg20pl7f.js} +1 -1
- package/dist/assets/player-overlays-BF9w4QU-.js +1 -0
- package/dist/assets/remoteEntry-ZZWQQQTl.js +1 -0
- package/dist/assets/square-check-big-DAcFGNUN.js +1 -0
- package/dist/assets/src-D9hgltMI.js +279 -0
- package/dist/assets/{sso-popup-Dd0yy6b3.js → sso-popup-CdVjmZ9n.js} +1 -1
- package/dist/assets/{step-inspector-model-Dbe3pGib.js → step-inspector-model-CxSQZZiN.js} +1 -1
- package/dist/assets/terminal-Dgb4lrgM.js +1 -0
- package/dist/assets/use-archive-data-D7nUbRKv.js +1 -0
- package/dist/assets/use-paged-list-DTJY2xpg.js +1 -0
- package/dist/assets/{use-scenes-feed-Cbr4UyCd.js → use-scenes-feed-BW5wMevx.js} +1 -1
- package/dist/assets/{useAdminDeviceRemoval-DNwUFqF2.js → useAdminDeviceRemoval-kU8epr6n.js} +1 -1
- package/dist/assets/useEventInvalidation-B2oUIKRS.js +1 -0
- package/dist/assets/{useNodeUrlSelection-Cbif6CY8.js → useNodeUrlSelection-CfN-OrGq.js} +1 -1
- package/dist/assets/user-x-DkWcmF99.js +1 -0
- package/dist/assets/variable-DTEpBbRf.js +1 -0
- package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-CExmog1q.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-D3AQM66O.js} +2 -2
- package/dist/index.html +10 -10
- package/dist/server/addon.js +243 -4
- package/package.json +2 -2
- package/dist/assets/Addons-2wfM1edN.js +0 -5
- package/dist/assets/AiProfiles-BHwb3nSo.js +0 -3
- package/dist/assets/Build-DIVuAKYP.js +0 -42
- package/dist/assets/CompositionEditorPage-B37HL2Dz.js +0 -1
- package/dist/assets/Data-C7m-cbr4.js +0 -2
- package/dist/assets/DeviceDetail-BBiCkxxi.js +0 -2
- package/dist/assets/EmbedDevicePage-DHBOCKzI.js +0 -1
- package/dist/assets/History-DqZqNlZz.js +0 -1
- package/dist/assets/Identity-CM4Ortr-.js +0 -1
- package/dist/assets/InstancesTable-CT4Kr3zo.js +0 -1
- package/dist/assets/IntegrationDetail-CsdGAa7R.js +0 -1
- package/dist/assets/Integrations-Dl7VYw1x.js +0 -1
- package/dist/assets/Library-Bp85cSAL.js +0 -1
- package/dist/assets/Locations-IZq43PGv.js +0 -3
- package/dist/assets/Logs-CrDOCX6k.js +0 -1
- package/dist/assets/MyAccess-d5w8yPDS.js +0 -2
- package/dist/assets/NodeAddonsSettingsPanel-CFTTKJTW.js +0 -2
- package/dist/assets/Notifications-yofgwGYi.js +0 -1
- package/dist/assets/Pipeline-C58uJw5q.js +0 -1
- package/dist/assets/Recordings-CNS2YQnv.js +0 -1
- package/dist/assets/SessionsList-CYvDTfln.js +0 -2
- package/dist/assets/StorageLocationsTable-D7z9VM03.js +0 -1
- package/dist/assets/System-B8KmJqiE.js +0 -1
- package/dist/assets/TemplateEditorDialog-DTAAJR9z.js +0 -1
- package/dist/assets/Terminal-D0cZGsnW.js +0 -3
- package/dist/assets/archive-ChKlYFY2.js +0 -1
- package/dist/assets/client-DIFc5Ulp.js +0 -1120
- package/dist/assets/device-detail-D28nIlrx.js +0 -1
- package/dist/assets/device-picker-model-DMqoJA3J.js +0 -1
- package/dist/assets/dist-GJ2aJJ7U.js +0 -1120
- package/dist/assets/i18n-CmzYiG85.js +0 -1
- package/dist/assets/icons-Cjxpx-EC.js +0 -1
- package/dist/assets/index-CJG5kQrR.css +0 -2
- package/dist/assets/index-CqFqTrNf.js +0 -4
- package/dist/assets/mount-DMqoJA3J.js +0 -1
- package/dist/assets/player-overlays-Cro1Q2AX.js +0 -1
- package/dist/assets/remoteEntry-Cr4tLhkx.js +0 -1
- package/dist/assets/src-o5EApxkv.js +0 -279
- package/dist/assets/terminal-DU-tvcEm.js +0 -1
- package/dist/assets/use-stationary-objects-tm2lHAjw.js +0 -1
- package/dist/assets/useEventInvalidation-DMqoJA3J.js +0 -1
- package/dist/assets/user-x-BcmVBo8D.js +0 -1
- package/dist/assets/variable-Cq3v1-Kt.js +0 -1
|
@@ -1,42 +0,0 @@
|
|
|
1
|
-
import{C as e,E as t,H as n,J as r,K as i,P as a,R as o,S as s,V as c,Y as l,a as u,et as d,k as f,o as p,t as m,x as h,z as g}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{$a as _,Dt as v,Gi as y,Ka as b,La as x,Lr as S,Ma as C,Tt as w,Vn as T,Xr as E,Zt as D,ar as O,ct as ee,ea as k,ft as A,ir as j,ki as M,la as N,ln as P,ma as F,ot as I,qn as L,ti as R,tn as z,ur as B,xi as V,yt as te,za as H,zr as U}from"./player-overlays-Cro1Q2AX.js";import{$a as W,$o as G,Bo as ne,Co as re,Do as K,Eo as ie,Fo as ae,Fr as oe,Go as se,Ho as ce,Io as le,Ir as ue,Jo as de,Ko as fe,Lo as pe,Lr as me,Mo as he,Nc as ge,No as _e,Oo as ve,Pr as ye,Qo as be,Qt as xe,Ro as Se,Rr as Ce,Rs as we,So as Te,Ta as Ee,To as De,Ts as Oe,Uo as ke,Vo as Ae,Wo as je,Xo as Me,Ya as Ne,Yo as Pe,Zo as Fe,_s as Ie,aa as Le,as as Re,ba as ze,es as Be,fs as Ve,is as He,jo as Ue,jr as We,ko as Ge,ls as Ke,ns as qe,oa as Je,os as Ye,qo as Xe,ra as Ze,ro as Qe,rs as $e,ss as et,to as tt,ts as nt,vs as rt,zo as it}from"./client-DIFc5Ulp.js";import{t as at}from"./chevron-down-CBb-F8DT.js";import{o as ot}from"./terminal-DU-tvcEm.js";import{i as st,n as ct,r as lt,t as ut}from"./variable-Cq3v1-Kt.js";import{r as dt}from"./shapes-D4IRNSXI.js";import{$f as ft,$i as pt,$o as mt,Bi as ht,D as gt,Dn as _t,E as vt,Ea as yt,Ep as bt,Fa as xt,Fd as St,Fr as Ct,Gf as wt,Gi as Tt,Hi as Et,Ia as Dt,Id as Ot,Ji as kt,Jo as At,Ki as jt,Ko as Mt,La as Nt,Ld as Pt,Li as Ft,Ls as It,Ma as Lt,Md as Rt,Mr as zt,Na as Bt,Nd as Vt,Nr as Ht,Ns as Ut,Or as Wt,Pd as Gt,Rd as Kt,Ri as qt,S as Jt,Tc as Yt,Ui as Xt,Vi as Zt,Ws as Qt,Xf as q,Zo as $t,_ as en,_f as tn,ad as nn,ap as rn,b as an,ci as on,ct as sn,dc as cn,dp as ln,ea as un,ei as dn,en as fn,ff as pn,g as mn,ga as J,gf as hn,h as gn,hc as _n,hr as vn,ip as Y,ja as yn,jd as bn,jn as xn,k as Sn,kn as Cn,ni as wn,ns as Tn,nt as En,oc as Dn,pa as On,pr as kn,q as An,qo as jn,ri as Mn,rs as Nn,rt as Pn,ti as Fn,ts as In,ui as Ln,up as Rn,ut as zn,va as X,vf as Bn,x as Vn,y as Hn,ya as Un,yf as Wn,za as Gn,zi as Kn}from"./src-o5EApxkv.js";import{t as Z}from"./i18n-CmzYiG85.js";import{t as Q}from"./useTranslation-BJr-n0es.js";import{At as qn,H as Jn,Nt as Yn,b as Xn,di as Zn,g as Qn,gi as $n,h as er,mi as tr,n as nr,t as rr,ui as ir}from"./index-CqFqTrNf.js";import{t as ar}from"./AdminSectionedPage-CRtQpSxT.js";import{n as or}from"./format-BqZcr5Z7.js";import{a as sr,c as cr,f as lr,r as ur}from"./command-vocab-Dp8EnV9z.js";import{a as dr,i as fr,n as pr,o as mr,r as hr,s as gr}from"./action-draft-DNplCdnd.js";import{C as _r,Ct as vr,Ot as yr,a as br,at as xr,b as Sr,g as Cr,i as wr,kt as Tr,n as Er,nt as Dr,o as Or,r as kr,t as Ar,w as jr,wt as Mr,y as Nr}from"./CompositionBlockEditor-CY2C2J8Z.js";import{_ as Pr,a as Fr,c as Ir,d as Lr,f as Rr,g as zr,h as Br,i as Vr,l as Hr,m as Ur,n as Wr,o as Gr,p as Kr,r as qr,s as Jr,u as Yr,v as Xr,y as Zr}from"./TemplateEditorDialog-DTAAJR9z.js";var Qr=`const AUTOMATION_RECIPE =`,$r=`// 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 ei(e){return e.includes(Qr)}function ti(e){return!ei(e.code)}function ni(e){let t=e.indexOf(Qr);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 ri(e){let t=ni(e);if(t===null)return{ok:!1,reason:Z.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:Z.t(`helpers.recipeFromCode.badJson`,{detail:t})}}let r=ne.safeParse(n);if(!r.success){let e=r.error.issues[0];return{ok:!1,reason:e===void 0?Z.t(`helpers.recipeFromCode.schemaMismatch`):Z.t(`helpers.recipeFromCode.schemaMismatchAt`,{path:e.path.join(`.`),message:e.message})}}return{ok:!0,recipe:r.data}}function ii(e){let t=ni(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)}${$r}${e.slice(i)}`}var ai=e=>e.tags,oi=e=>[e.name],si=e=>e.tags,ci=e=>[e.name],li=e=>e.tags,ui=e=>[e.name],di=e=>e.tags,fi=e=>[e.name];d();function pi({subject:e,subjectKey:t,saving:n,error:r,onSave:i,onClose:a}){return s(Ft,{open:e!==null,onOpenChange:e=>!e&&!n&&a(),children:s(Kn,{width:`md`,placement:`sheet-on-mobile`,"data-testid":`quick-edit-dialog`,children:e!==null&&s(mi,{subject:e,saving:n,error:r,onSave:i,onClose:a},t)})})}function mi({subject:t,saving:n,error:r,onSave:i,onClose:a}){let{t:o}=Q(),[c,u]=l(t.name),[d,f]=l(t.tags),p=c.trim()!==``&&!n;return e(h,{children:[s(Et,{children:s(Xt,{children:o(`build.quickEdit.title`,`Quick edit`)})}),e(qt,{className:`space-y-3`,children:[s(zn,{label:o(`build.quickEdit.name`,`Name`),children:s(Y,{value:c,maxLength:120,onChange:e=>u(e.target.value),"data-testid":`quick-edit-name`})}),e(`div`,{className:`text-sm`,children:[s(`span`,{className:`text-foreground-subtle`,children:o(`common.tags`,`Tags`)}),s(mn,{className:`mt-1`,value:d,onChange:f,label:o(`common.tags`,`Tags`)})]}),r!==null&&s(J,{message:r})]}),e(Zt,{children:[s(q,{variant:`ghost`,onClick:a,disabled:n,children:o(`common.cancel`,`Cancel`)}),e(q,{disabled:!p,onClick:()=>i({name:c.trim(),tags:d}),"data-testid":`quick-edit-save`,children:[n&&s(S,{className:`h-4 w-4 animate-spin`}),` `,o(`common.save`,`Save`)]})]})]})}var hi=[`mon`,`tue`,`wed`,`thu`,`fri`,`sat`,`sun`],gi=720,_i=1440;function vi(e){if(e===null)return yi();let{id:t,createdAt:n,updatedAt:r,...i}=e;return i}function yi(){return{name:``,enabled:!0,priority:0,maxLateMs:ae,profiles:[bi(`profile-1`,`Every day`)]}}function bi(e,t){return{id:e,name:t,enabled:!0,days:[...hi],points:[]}}function xi(e,t,n){return{id:t,at:{kind:`clock`,hh:Math.floor(n/60),mm:n%60},mode:e,steps:[]}}function Si(e,t){let n=t.length+1;for(;t.includes(`${e}-${String(n)}`);)n+=1;return`${e}-${String(n)}`}function Ci(e){return e.location===null?null:{lat:e.location.latitude,lon:e.location.longitude,timeZone:e.timeZone}}function wi(e,t){let n=new Intl.DateTimeFormat(`en-US`,{timeZone:t,hourCycle:`h23`,hour:`2-digit`,minute:`2-digit`}).formatToParts(new Date(e)),r=e=>Number(n.find(t=>t.type===e)?.value??0);return r(`hour`)*60+r(`minute`)}function Ti(e,t=Date.now()){return Ie(t,e.timeZone)}function Ei(e,t,n){let r=Ci(t);if(r===null)return e.kind===`clock`?e.hh*60+e.mm:null;let i=rt(e,n,r);return i===null?null:wi(i,t.timeZone)}function Di(e,t,n){return e.kind===`sun`?Ei({...e,offsetMin:0},t,n):null}function Oi(e,t,n){if(e.kind===`clock`)return{kind:`clock`,hh:Math.floor(t/60),mm:t%60};if(e.kind===`sun`&&n!==null){let r=Math.max(-720,Math.min(gi,t-n));return{...e,offsetMin:r}}return e}function ki(e){let t=/^([01]\d|2[0-3]):([0-5]\d)$/.exec(e);return t===null?null:{kind:`clock`,hh:Number(t[1]),mm:Number(t[2])}}function Ai(e,t){return`${String(e).padStart(2,`0`)}:${String(t).padStart(2,`0`)}`}function ji(e){return Ai(Math.floor(e/60),e%60)}function Mi(e,t,n){let r=e.flatMap(e=>{let r=Ei(e.at,t,n);return r===null?[]:[{point:e,minute:r}]}).toSorted((e,t)=>e.minute-t.minute);return r.flatMap((e,t)=>{if(e.point.mode!==`hold`)return[];let n=r[t+1];return[{id:e.point.id,fromMinute:e.minute,toMinute:n===void 0?_i:n.minute}]})}function Ni(e,t){let n=le.safeParse(e);if(!n.success)return{ok:!1,issues:n.error.issues.map(e=>({path:e.path.join(`.`),message:e.message}))};let r=pe(n.data,t);return r.ok?{ok:!0,input:n.data}:{ok:!1,issues:r.issues}}function Pi(e,t){return{name:t.name,code:e.code,...e.files===void 0?{}:{files:e.files},...e.entry===void 0?{}:{entry:e.entry},enabled:e.enabled,placement:e.placement,...e.integrationId===void 0?{}:{integrationId:e.integrationId},...e.settingsSchema===void 0?{}:{settingsSchema:e.settingsSchema},tags:[...t.tags]}}function Fi(e,t){let n=Pi(e,t);if(t.name===e.name)return n;let r=ri(e.code);if(!r.ok)return n;try{return{...n,code:he({name:t.name,recipe:r.recipe})}}catch{return n}}function Ii(e,t){return pr({...hr(e),name:t.name,tags:t.tags})}function Li(e,t){return{...vi(e),name:t.name,tags:[...t.tags]}}function Ri(e,t){return{id:e.id,kind:e.kind,name:t.name,payload:e.payload,tags:t.tags}}function zi(e){return{name:e.name,tags:e.tags??[]}}function Bi({testId:t,icon:n,title:r,badges:i,onClose:a,onQuickEdit:o,headerActions:c,onSave:l,saveDisabled:u=!1,saving:d=!1,saveTestId:f,footerActions:p,footerStatus:m,notices:h,side:g,bare:_=!1,children:v}){let{t:y}=Q();return e(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3`,"data-testid":t,children:[e(`header`,{className:`flex shrink-0 flex-wrap items-center gap-2 border-b border-border pb-2`,children:[s(q,{size:`sm`,variant:`ghost`,onClick:a,"aria-label":y(`build.editor.back`,`Back to the list`),"data-testid":`build-editor-back`,children:s(x,{className:`h-4 w-4`,"aria-hidden":!0})}),s(n,{className:`h-4 w-4 shrink-0 text-foreground-muted`,"aria-hidden":!0}),s(`h3`,{className:`min-w-0 flex-1 truncate text-sm font-semibold`,children:r}),i,o!==void 0&&s(rn,{icon:B,size:`sm`,variant:`ghost`,"aria-label":y(`build.quickEdit.action`,`Quick edit`),title:y(`build.quickEdit.action`,`Quick edit`),onClick:o,"data-testid":`build-editor-quick-edit`}),c]}),e(`div`,{className:`min-h-0 flex-1 overflow-y-auto lg:grid lg:grid-rows-[minmax(0,1fr)] lg:gap-4 lg:overflow-hidden ${g===void 0?`lg:grid-cols-1`:`lg:grid-cols-[minmax(0,1fr)_22rem]`}`,"data-testid":`build-editor-body`,children:[s(`div`,{className:`space-y-4 lg:min-h-0 lg:overflow-y-auto lg:pr-1`,children:v}),g!==void 0&&s(`div`,{className:`order-first mb-4 lg:order-last lg:mb-0 lg:flex lg:min-h-0 lg:flex-col lg:overflow-hidden`,children:g})]}),h!==void 0&&s(`div`,{className:`shrink-0 space-y-2`,children:h}),!_&&e(`footer`,{className:`flex shrink-0 flex-wrap items-center gap-2 border-t border-border pt-2`,children:[l!==void 0&&e(q,{onClick:l,disabled:d||u,"data-testid":f,children:[d&&s(S,{className:`h-4 w-4 animate-spin`}),` `,y(`common.save`,`Save`)]}),p,s(q,{variant:`ghost`,onClick:a,disabled:d,children:y(`common.close`,`Close`)}),m!==void 0&&s(`span`,{className:`ml-auto flex items-center gap-2 text-xs text-foreground-subtle`,children:m})]})]})}var Vi=`when`;function Hi(e){return e===void 0||e.trim()===``?null:e}function Ui(e){let t=e.slice(e.lastIndexOf(`.`)+1),n=Number(t);return Number.isInteger(n)?n:0}function Wi(e){return e===`ok`?`pass`:e===`error`||e===`failed-continued`||e===`timed-out`?`fail`:`idle`}function Gi(e){return e.steps.map(e=>({index:Ui(e.path),tone:Wi(e.outcome),message:Hi(e.message)}))}function Ki(e){let t=e.trigger.outcome===`pass`?`pass`:`fail`,n=Hi(e.trigger.reason),r=e.conditions.find(e=>e.path===Vi);return t===`fail`||r===void 0?{tone:t,reason:n}:r.outcome===`fail`?{tone:`fail`,reason:Hi(r.reason)??n}:{tone:r.outcome===`pass`?`pass`:`idle`,reason:n}}function qi(e,t){return e.outcome===`ran`?{tone:`pass`,reason:null}:e.outcome===`failed`||e.outcome===`aborted`?{tone:`fail`,reason:t.find(e=>e.tone===`fail`)?.message??null}:{tone:`idle`,reason:Hi(e.verdict?.reason)}}function Ji(e){let t=Gi(e);return{when:Ki(e),thenBlock:qi(e,t),steps:t}}function Yi(e,t){return e===null?null:e.steps.find(e=>e.index===t)?.tone??`idle`}function Xi(e){return e===null?{kind:`unknown`}:{kind:`value`,text:Array.isArray(e)?e.join(`, `):String(e)}}function Zi(e){return{kind:e.kind,tone:Wi(e.outcome),message:Hi(e.message)}}function Qi(e){if(e===void 0)return null;if(e===`else`)return{kind:`else`};let t=Number(e.slice(e.lastIndexOf(`.`)+1));return Number.isInteger(t)?{kind:`branch`,index:t}:null}function $i(e,t){return t===void 0?null:e===void 0?t:`${e}.${t}`}function ea(e){return{vars:Object.entries(e.trigger.vars).map(([e,t])=>({name:e,value:Xi(t)})),conditions:e.conditions.map(e=>({path:e.path,depth:e.path.split(`.`).length-1,kind:e.kind,outcome:e.outcome,reason:Hi(e.reason),subject:$i(e.cap,e.fieldPath),operator:e.operator??null,deviceId:e.deviceId??null,expected:e.expected===void 0?null:Xi(e.expected),observed:e.observed===void 0?null:Xi(e.observed),rawExpected:e.expected,rawObserved:e.observed})),steps:e.steps.map(e=>({index:Ui(e.path),kind:e.kind,tone:Wi(e.outcome),message:Hi(e.message),args:Object.entries(e.args??{}).map(([e,t])=>({name:e,value:Xi(t)})),devices:(e.devices??[]).map(e=>({deviceId:e.deviceId,tone:e.outcome===`ok`?`pass`:`fail`,message:Hi(e.message)})),chose:Qi(e.branch),nested:(e.steps??[]).map(e=>({...Zi(e),chose:Qi(e.branch),rounds:e.iterations??null,inner:(e.steps??[]).map(Zi)})),rounds:e.iterations??null}))}}function ta(e){let t=ea(e);return{nodes:new Map(t.conditions.map(e=>[e.path,e])),triggerPath:e.trigger.path??null,vars:t.vars}}var na=6;function ra(e,t,n){if(typeof e!=`number`||t===void 0||n===void 0)return Xi(e);let r=Ve(e,t,n);return r===void 0?Xi(e):{kind:`value`,text:`${String(Number(r.toPrecision(na)))} ${n}`}}function ia(e){let t=e.steps.find(e=>e.outcome===`error`),n=t===void 0?Hi(e.verdict?.reason)??Hi(e.trigger.reason):Hi(t.message);return{stepsRun:e.steps.filter(e=>e.outcome===`ok`).length,stepsTotal:e.steps.length,reason:n}}d();var aa={ran:`success`,failed:`danger`,aborted:`danger`,"skipped-trigger":`neutral`,"skipped-conditions":`warning`,"skipped-cooldown":`neutral`,"skipped-overlap":`neutral`},oa={pass:`border-success/50 bg-success/10`,fail:`border-danger/50 bg-danger/10`,idle:`border-border bg-surface text-foreground-subtle`},sa={pass:`text-success`,fail:`text-danger`,idle:`text-foreground-subtle`};function ca(){let{t:e}=Q();return t=>{switch(t){case`ran`:return e(`flow.runs.outcomeRan`,`Ran`);case`failed`:return e(`flow.runs.outcomeFailed`,`Failed`);case`aborted`:return e(`flow.runs.outcomeAborted`,`Stopped`);case`skipped-trigger`:return e(`flow.runs.outcomeSkippedTrigger`,`Trigger not met`);case`skipped-conditions`:return e(`flow.runs.outcomeSkippedConditions`,`Skipped by conditions`);case`skipped-cooldown`:return e(`flow.runs.outcomeSkippedCooldown`,`Skipped by cooldown`);default:return e(`flow.runs.outcomeSkippedOverlap`,`Skipped by run mode`)}}}var la={done:`success`,missed:`warning`,inactive:`neutral`,"condition-false":`neutral`,failed:`danger`,held:`success`,"gave-up":`danger`,overridden:`info`,"suspended-manual":`warning`};function ua(){let{t:e}=Q();return t=>{switch(t){case`done`:return e(`flow.runs.schedulerDone`,`Done`);case`missed`:return e(`flow.runs.schedulerMissed`,`Missed`);case`inactive`:return e(`flow.runs.schedulerInactive`,`Not active`);case`condition-false`:return e(`flow.runs.schedulerConditionFalse`,`Condition not met`);case`failed`:return e(`flow.runs.schedulerFailed`,`Failed`);case`held`:return e(`flow.runs.schedulerHeld`,`Held`);case`gave-up`:return e(`flow.runs.schedulerGaveUp`,`Gave up`);case`overridden`:return e(`flow.runs.schedulerOverridden`,`Changed by hand`);default:return e(`flow.runs.schedulerSuspendedManual`,`Paused by hand`)}}}var da=`max-h-64`,fa=`lg:max-h-none lg:min-h-0 lg:flex-1`;function pa(){let e=ln(),t=Rn();return e||t}function ma({expanded:t,onToggle:n}){let{t:r}=Q();return e(q,{variant:`unstyled`,type:`button`,"aria-expanded":t,"data-testid":`runs-toggle`,onClick:n,className:`flex w-full items-center gap-2 px-3 py-2 text-left text-xs text-foreground-muted hover:bg-surface-hover`,children:[s(ft,{expanded:t}),s(`span`,{children:t?r(`flow.runs.hide`,`Hide runs`):r(`flow.runs.show`,`Show runs`)})]})}function ha({run:t}){let{t:n}=Q(),r=ca(),i=ia(t);return e(`p`,{className:`flex flex-wrap items-center gap-x-2 gap-y-1 border-t border-border-subtle bg-primary/5 px-3 py-2 text-xs`,"data-testid":`run-summary`,children:[s(X,{variant:aa[t.outcome],children:r(t.outcome)}),i.reason!==null&&s(`span`,{className:`min-w-0 break-words text-foreground`,children:i.reason}),i.stepsTotal>0&&s(`span`,{className:`text-foreground-subtle`,children:n(`flow.runs.stepsRan`,`{{run}} of {{total}} steps ran`,{run:i.stepsRun,total:i.stepsTotal})})]})}function ga({traces:t,selectedId:n,onSelect:r}){let{t:i}=Q(),a=ca(),o=ua(),c=pa(),[u,d]=l(null),f=u??!c,p=t===void 0?[]:t.toReversed(),m=p.find(e=>e.runId===n)??null;return e(zt,{headingId:`runs-heading`,title:i(`flow.runs.title`,`Runs`),icon:E,fill:!0,children:[s(ma,{expanded:f,onToggle:()=>d(!f)}),f?t===void 0?s(Un,{className:`m-3 h-16`}):p.length===0?s(pt,{title:i(`flow.runs.emptyTitle`,`No runs yet`),description:i(`flow.runs.emptyDescription`,`Each run appears here with what it decided.`)}):e(h,{children:[s(`ul`,{className:`${da} ${fa} divide-y divide-border-subtle overflow-y-auto`,"data-testid":`runs-panel`,children:p.map(t=>{let i=t.runId===n;return s(`li`,{children:e(q,{variant:`unstyled`,type:`button`,"aria-pressed":i,onClick:()=>r(i?null:t.runId),className:`flex w-full flex-col gap-1 px-3 py-2 text-left hover:bg-surface-hover ${i?`bg-primary/10`:``}`,children:[e(`span`,{className:`flex flex-wrap items-center gap-2`,children:[t.scheduler===void 0?s(X,{variant:aa[t.outcome],children:a(t.outcome)}):s(X,{variant:la[t.scheduler],children:o(t.scheduler)}),t.repeat>1&&s(X,{variant:`neutral`,style:`outline`,children:`x${String(t.repeat)}`}),s(`span`,{className:`text-xs text-foreground-subtle`,children:or(t.lastAt)})]}),s(`span`,{className:`truncate text-sm text-foreground`,children:t.trigger.reason})]})},t.runId)})}),m!==null&&s(ha,{run:m}),s(`p`,{className:`border-t border-border-subtle px-3 py-2 text-xs text-foreground-subtle`,children:i(`flow.runs.hint`,`Select a run to colour the blocks: green passed, red failed, grey not evaluated.`)})]}):m!==null&&s(ha,{run:m})]})}function _a(e){return oa[e]}var va={pass:`border-success/50`,fail:`border-danger/50`,idle:`border-border`};function ya(e){return va[e]}function ba({step:t,title:n,hint:r,trace:i,children:a}){return e(`section`,{className:`rounded-lg border p-3 ${i===null?`border-border bg-surface`:oa[i.tone]}`,"data-testid":`block-${t}`,children:[e(`div`,{className:`mb-2 flex flex-wrap items-baseline gap-2`,children:[s(`h4`,{className:`text-sm font-semibold uppercase tracking-wide`,children:n}),r!==void 0&&s(`span`,{className:`text-xs text-foreground-subtle`,children:r})]}),i!==null&&i.reason!==null&&s(`p`,{className:`mb-2 text-xs font-medium ${sa[i.tone]}`,children:i.reason}),s(`div`,{className:`space-y-2`,children:a})]})}var xa=[`count`,`while`,`until`,`forEach`],Sa=2,Ca=10,wa={kind:`all`,children:[]};function Ta(e){return e===`count`||e===`while`||e===`until`||e===`forEach`}function Ea(e,t){return Number.isFinite(e)?Math.min(t,Math.max(1,Math.round(e))):1}function Da(e){return Ea(e,20)}function Oa(e){return Ea(e,50)}function ka(e){switch(e){case`count`:return{by:e,count:Sa};case`while`:case`until`:return{by:e,when:wa,maxIterations:Ca};case`forEach`:return{by:e,target:{kind:`devices`,ids:[]}}}}function Aa(e,t){if(e.by!==`while`&&e.by!==`until`)return e;let{waitS:n,...r}=e;return t===null?r:{...r,waitS:Ea(t,ce)}}function ja(){return{kind:`repeat`,loop:ka(`count`),steps:[]}}var Ma=[`s`,`min`,`h`],Na={s:1,min:60,h:3600};function Pa(e){return e===`s`||e===`min`||e===`h`}function Fa(e){return e%Na.h===0?{value:e/Na.h,unit:`h`}:e%Na.min===0?{value:e/Na.min,unit:`min`}:{value:e,unit:`s`}}function Ia(e,t){let n=Math.round(e*Na[t]);return Number.isFinite(n)?Math.min(Math.max(n,1),ke):1}function La(){return{kind:`wait-until`,when:{kind:`all`,children:[]},timeoutS:600,onTimeout:`continue`}}var Ra=[`eq`,`ne`,`gt`,`gte`,`lt`,`lte`,`contains`,`in`];function za(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 Ra}}function Ba(e){switch(e){case`eq`:return Z.t(`helpers.recipeParts.op_eq`);case`ne`:return Z.t(`helpers.recipeParts.op_ne`);case`gt`:return Z.t(`helpers.recipeParts.op_gt`);case`gte`:return Z.t(`helpers.recipeParts.op_gte`);case`lt`:return Z.t(`helpers.recipeParts.op_lt`);case`lte`:return Z.t(`helpers.recipeParts.op_lte`);case`contains`:return Z.t(`helpers.recipeParts.op_contains`);default:return Z.t(`helpers.recipeParts.op_in`)}}function Va(e){return za(e).map(e=>({value:e,label:Ba(e)}))}Te.filter(e=>re(e).role===`event`),Te.filter(e=>re(e).role===`state`);function Ha(e){return Z.t(`${re(e).i18nKey}.label`)}function Ua(e){return Z.t(`${re(e).i18nKey}.description`)}function Wa(e){return Z.t(`${re(e).i18nKey}.example`)}var Ga={when:{kind:`all`,children:[]},actions:[]};function Ka(e){return De(e)}function qa(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
|
-
`};case`action`:return{kind:e,actionId:``};case`stop`:return{kind:e,reason:``,outcome:`ok`};case`set`:return{kind:e,vars:{}};case`wait-until`:return La();case`parallel`:return{kind:e,steps:[]};case`repeat`:return ja();case`choose`:return{kind:e,branches:[{if:{kind:`all`,children:[]},steps:[]}]};default:return{kind:`command`,target:{kind:`devices`,ids:[]},actionId:``}}}function Ja(e,t,n){return e.map((e,r)=>r===t?n:e)}function Ya(e,t){return e.filter((e,n)=>n!==t)}function Xa(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=Ya(e,t);return[...a.slice(0,i),r,...a.slice(i)]}function Za(e,t){return{...e,actions:[...t]}}var Qa={pass:`success`,fail:`danger`,"not-evaluated":`neutral`},$a={pass:`success`,fail:`danger`,idle:`neutral`};function eo({value:e}){let{t}=Q();return e.kind===`unknown`?s(`span`,{className:`italic text-foreground-subtle`,"data-testid":`trace-value-unknown`,children:t(`flow.runs.unknownValue`,`unknown`)}):s(`span`,{className:`font-mono text-foreground`,children:e.text})}function to(){let{t:e}=Q();return t=>t===`pass`?e(`flow.runs.nodePass`,`Passed`):t===`fail`?e(`flow.runs.nodeFail`,`Failed`):e(`flow.runs.nodeNotEvaluated`,`Not evaluated`)}function no(e){let t=Pe.safeParse(e);return t.success?Ba(t.data):e}function ro({items:t,testId:n}){return t.length===0?null:s(`dl`,{className:`grid grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-0.5 text-[11px]`,"data-testid":n,children:t.map(t=>e(`div`,{className:`contents`,children:[s(`dt`,{className:`text-foreground-subtle`,children:t.name}),s(`dd`,{className:`break-words`,children:s(eo,{value:t.value})})]},t.name))})}function io({node:t,vars:n=[],expected:r,observed:i}){let{t:a}=Q(),o=to(),c=t.subject===null?null:`${t.subject}${t.operator===null?``:` ${no(t.operator)}`}`;return e(`div`,{className:`space-y-1 border-t border-border-subtle pt-2 text-xs`,"data-testid":`trace-result`,"data-outcome":t.outcome,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[s(X,{variant:Qa[t.outcome],children:o(t.outcome)}),t.reason!==null&&s(`span`,{className:`min-w-0 break-words text-foreground`,children:t.reason})]}),c!==null&&s(`div`,{className:`text-[11px] text-foreground-subtle`,children:c}),(r!==null||i!==null)&&e(`div`,{className:`flex flex-wrap gap-x-3 text-[11px] text-foreground-subtle`,children:[r!==null&&e(`span`,{"data-testid":`trace-expected`,children:[a(`flow.runs.expected`,`Expected`),` `,s(eo,{value:r})]}),i!==null&&e(`span`,{"data-testid":`trace-observed`,children:[a(`flow.runs.observed`,`Observed`),` `,s(eo,{value:i})]})]}),s(ro,{testId:`trace-vars`,items:n})]})}function ao({step:t,deviceName:n}){let{t:r}=Q(),i=t.tone===`pass`?r(`flow.runs.stepOk`,`OK`):t.tone===`fail`?r(`flow.runs.stepError`,`Error`):r(`flow.runs.stepNotRun`,`Not run`);return e(`div`,{className:`space-y-1 border-t border-border-subtle pt-2 text-xs`,"data-testid":`step-result`,"data-tone":t.tone,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[s(X,{variant:$a[t.tone],children:i}),t.message!==null&&s(`span`,{className:`min-w-0 break-words text-foreground`,children:t.message})]}),t.chose!==null&&s(`div`,{className:`text-foreground-subtle`,"data-testid":`step-chose`,children:t.chose.kind===`else`?r(`flow.runs.choseElse`,`Ran the "otherwise" list`):r(`flow.runs.choseBranch`,`Ran branch {{n}}`,{n:t.chose.index+1})}),t.rounds!==null&&t.nested.length>0&&s(`div`,{className:`text-foreground-subtle`,"data-testid":`step-last-round`,children:r(`flow.runs.lastRound`,`The last of {{n}} rounds:`,{n:t.rounds})}),t.nested.length>0&&s(`ol`,{className:`space-y-0.5 text-[11px]`,"data-testid":`step-nested`,children:t.nested.map((t,n)=>e(`li`,{className:`space-y-0.5`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(X,{variant:$a[t.tone],children:[String(n+1),` · `,t.kind]}),t.message!==null&&s(`span`,{className:`min-w-0 break-words text-foreground-subtle`,children:t.message}),t.chose!==null&&s(`span`,{className:`text-foreground-subtle`,"data-testid":`nested-chose-${String(n)}`,children:t.chose.kind===`else`?r(`flow.runs.choseElse`,`Ran the "otherwise" list`):r(`flow.runs.choseBranch`,`Ran branch {{n}}`,{n:t.chose.index+1})}),t.rounds!==null&&t.inner.length>0&&s(`span`,{className:`text-foreground-subtle`,"data-testid":`nested-rounds-${String(n)}`,children:r(`flow.runs.lastRound`,`The last of {{n}} rounds:`,{n:t.rounds})})]}),t.inner.length>0&&s(`ol`,{className:`space-y-0.5 border-l border-border-subtle pl-2`,"data-testid":`nested-inner-${String(n)}`,children:t.inner.map((t,n)=>e(`li`,{className:`flex flex-wrap items-center gap-2`,children:[e(X,{variant:$a[t.tone],children:[String(n+1),` · `,t.kind]}),t.message!==null&&s(`span`,{className:`min-w-0 break-words text-foreground-subtle`,children:t.message})]},String(n)))})]},String(n)))}),s(ro,{testId:`step-args`,items:t.args}),t.devices.length>0&&s(`ul`,{className:`space-y-0.5 text-[11px]`,"data-testid":`step-devices`,children:t.devices.map(t=>e(`li`,{className:`flex flex-wrap items-center gap-2`,children:[s(X,{variant:$a[t.tone],children:n(t.deviceId)}),t.message!==null&&s(`span`,{className:`min-w-0 break-words text-foreground-subtle`,children:t.message})]},t.deviceId))})]})}d();function $({children:e}){return s(`span`,{className:`mb-1 block text-xs text-foreground-subtle`,children:e})}function oo(e){let t=Yr(e.deviceId);if(t.data!==void 0)return Ir(t.data,e.cap).find(t=>t.path===e.fieldPath)}function so({value:t,devices:n,onChange:r}){let{t:i,i18n:a}=Q(),[o,c]=l(!1),u=n.find(e=>e.id===t.deviceId),d=t.deviceId===0?i(`automation.fieldPicker.pickAValue`,`Pick a device value…`):`${u?.name??`#${String(t.deviceId)}`}${t.cap===``?``:` · ${Mr(t.cap,t.fieldPath,a.language)}`}`;return e(`div`,{className:`min-w-[14rem] max-w-full flex-[2]`,children:[s($,{children:i(`automation.fieldPicker.value`,`Device value`)}),e(q,{variant:`outline`,className:`w-full min-w-0 justify-between`,"data-testid":`field-picker-open`,onClick:()=>c(!0),children:[s(`span`,{className:`w-0 flex-1 truncate text-left`,children:d}),s(at,{className:`size-3.5 shrink-0`})]}),o&&s(co,{value:t,onCancel:()=>c(!1),onConfirm:e=>{c(!1),r(e)}})]})}function co({value:t,onCancel:n,onConfirm:r}){let{t:i}=Q(),a=It({projection:`slim`}),[o,c]=l(null),[u,d]=l(!1),[f,p]=l(t.cap===``?null:{cap:t.cap,path:t.fieldPath});!u&&a.status===`success`&&(d(!0),c(yr(a.data).find(e=>e.id===t.deviceId)??null));let m=i(`automation.fieldPicker.title`,`Device value`);return s(Pn,{open:!0,onClose:n,title:m,width:`xl`,fill:!0,testId:`field-picker-dialog`,footer:e(h,{children:[s(q,{variant:`ghost`,onClick:n,children:i(`common.cancel`,`Cancel`)}),s(q,{disabled:o===null||f===null,"data-testid":`field-picker-confirm`,onClick:()=>{o===null||f===null||r({deviceId:o.id,cap:f.cap,fieldPath:f.path})},children:i(`automation.fieldPicker.use`,`Use this value`)})]}),children:s(xr,{kind:`formula`,intent:`value`,enabled:!0,fillHeight:!0,hostId:-1,destination:{cap:`automation`,targetId:`field`,title:m,pickerTargetKind:null},device:o,field:f,excludeTypes:Kr,onDeviceChange:c,onFieldChange:p})})}var lo=1e4;function uo(e,t,n){let r=Object.fromEntries(Object.entries(e??{}).filter(([e])=>e!==t)),i=n===null?r:{...r,[t]:n};return Object.keys(i).length===0?void 0:i}function fo(e,t){return{kind:`action`,actionId:e.actionId,...t===void 0?{}:{variables:t}}}function po({step:t,onChange:n}){let{t:r}=Q(),i=Dt({},{refetchInterval:lo});if(i.data===void 0)return s(Un,{className:`h-8 w-64`});let a=i.data.find(e=>e.id===t.actionId),o=t.actionId!==``&&a===void 0;return e(`div`,{className:`space-y-2`,"data-testid":`run-action-step`,children:[e(`label`,{className:`block max-w-sm`,children:[s($,{children:r(`automation.runAction.action`,`Action`)}),s(A,{value:t.actionId,onChange:e=>n({kind:`action`,actionId:e.target.value}),options:[{value:``,label:r(`automation.runAction.pick`,`Pick an action`)},...o?[{value:t.actionId,label:r(`automation.runAction.missing`,`Missing action ({{id}})`,{id:t.actionId})}]:[],...i.data.map(e=>({value:e.id,label:e.name}))]})]}),o&&s(`p`,{className:`text-xs text-danger`,children:r(`automation.runAction.missingHint`,`This action no longer exists. Pick another, or the step will fail.`)}),(a?.variables??[]).length>0&&s(`div`,{className:`flex flex-wrap items-end gap-3`,children:(a?.variables??[]).map(e=>s(mo,{variable:e,value:t.variables?.[e.name],onChange:r=>n(fo(t,uo(t.variables,e.name,r)))},e.name))})]})}function mo({variable:t,value:n,onChange:r}){let{t:i}=Q(),a=t.label??t.name,o=t.default===void 0?i(`automation.runAction.required`,`required`):i(`automation.runAction.defaultIs`,`default {{value}}`,{value:String(t.default)});if(t.type===`boolean`||t.type===`select`){let c=t.type===`boolean`?[{value:`true`,label:i(`common.yes`,`Yes`)},{value:`false`,label:i(`common.no`,`No`)}]:(t.options??[]).map(e=>({value:e,label:e}));return e(`label`,{className:`block`,children:[s($,{children:a}),s(Br,{widthClass:`w-40`,value:n===void 0?``:String(n),onChange:e=>{e.target.value===``?r(null):r(t.type===`boolean`?e.target.value===`true`:e.target.value)},options:[{value:``,label:o},...c]})]})}return t.type===`number`?e(`label`,{className:`block`,children:[s($,{children:a}),s(zr,{className:`w-40`,placeholder:o,value:typeof n==`number`?n:void 0,onValue:r})]}):e(`label`,{className:`block`,children:[s($,{children:a}),s(Y,{className:`w-40`,placeholder:o,value:n===void 0?``:String(n),onChange:e=>r(e.target.value===``?null:e.target.value)})]})}function ho({onMove:e,label:t,reason:n,testId:r,children:i}){let a=e===null?n:t;return s(`span`,{className:`inline-flex`,title:a,"data-testid":`${r}-wrap`,children:s(q,{variant:`ghost`,disabled:e===null,onClick:e??void 0,"aria-label":t,title:a,"data-testid":r,children:i})})}function go({move:t,texts:n}){let{t:r}=Q(),i=n??{up:r(`automation.whenTree.moveUp`,`Move up`),down:r(`automation.whenTree.moveDown`,`Move down`),atFirst:r(`automation.whenTree.alreadyFirst`,`Already first in this block`),atLast:r(`automation.whenTree.alreadyLast`,`Already last in this block`)};return e(h,{children:[s(ho,{onMove:t.up,label:i.up,reason:i.atFirst,testId:`move-up`,children:s(C,{className:`h-3.5 w-3.5`})}),s(ho,{onMove:t.down,label:i.down,reason:i.atLast,testId:`move-down`,children:s(H,{className:`h-3.5 w-3.5`})})]})}var _o=[`command`,`action`,`wait`,`set`,`stop`],vo=[`command`,`action`,`wait`];function yo(e){return xo(e)&&vo.includes(e.kind)}var bo={kind:`all`,children:[]};function xo(e){return _o.includes(e.kind)?!(`if`in e)&&!(`else`in e):!1}function So(){return{if:bo,steps:[]}}function Co(e){return e.branches.length<6}function wo(e){return Co(e)?{...e,branches:[...e.branches,So()]}:e}function To(e){return e.branches.length>1}function Eo(e,t){return To(e)?{...e,branches:e.branches.filter((e,n)=>n!==t)}:e}function Do(e,t,n){return{...e,branches:e.branches.map((e,r)=>r===t?n:e)}}function Oo(e,t){let{else:n,...r}=e;return t===void 0?r:{...r,else:[...t]}}var ko=[..._o,`wait-until`,`choose`,`parallel`,`repeat`];function Ao(e){return e<2?ko:_o}function jo(e){if(xo(e))return!0;switch(e.kind){case`wait-until`:case`parallel`:return!0;case`repeat`:return e.steps.every(xo);case`choose`:return e.branches.every(e=>e.steps.every(xo))&&(e.else??[]).every(xo);default:return!1}}var Mo=[`border-chart-series-a`,`border-chart-series-f`,`border-chart-series-b`,`border-chart-series-d`];function No(e,t){let n=Mo.length;return(e+1+t%(n-1))%n}function Po(e,t){let n=0;return e.map(e=>nt(e)?null:No(t,n++))}function Fo(e){return Mo[e%Mo.length]??Mo[0]}function Io(e){let t=[],n=0;return be(e,e=>{Be(e)&&(n+=1,e.id!==void 0&&t.push({id:e.id,ordinal:n,leaf:e}))}),t}function Lo(e){return G(e.when)?!0:e.actions.some(e=>je(e).some(e=>G(e.when)))}function Ro(e){let t=1;for(;e.has(`t${t}`);)t+=1;return`t${t}`}function zo(e,t){if(nt(e)){if(!Be(e)||e.id!==void 0)return e;let n=Ro(t);return t.add(n),{...e,id:n}}if(e.kind===`not`){let n=zo(e.child,t);return n===e.child?e:{...e,child:n}}let n=e.children.map(e=>zo(e,t));return n.every((t,n)=>t===e.children[n])?e:{...e,children:n}}function Bo(e){if(!Lo(e))return e;let t=new Set(Io(e.when).map(e=>e.id)),n=zo(e.when,t);return n===e.when?e:{...e,when:n}}function Vo(e,t,n){let r=e.leafIds.includes(t)?e.leafIds.filter(e=>e!==t):[...e.leafIds,t];return{kind:`triggered-by`,leafIds:n.filter(e=>r.includes(e))}}function Ho(e,t){return e.leafIds.filter(e=>!t.includes(e))}d();var Uo=[],Wo=f(null);function Go({when:e,children:t}){let n=i(()=>Io(e),[e]);return s(Wo.Provider,{value:n,children:t})}function Ko(){return g(Wo)??Uo}function qo(){return g(Wo)!==null}var Jo=[`triggered-by`];function Yo(e){return{label:Ha(e),description:Ua(e),example:Wa(e)}}function Xo({open:e,onOpenChange:t,mode:n,context:r,underNot:i,treeFull:a,current:o,onPick:c}){let{t:l}=Q(),u=qo();return s(Hn,{open:e,onOpenChange:t,title:n===`add`?l(`automation.leafPicker.title`,`Add a row`):l(`automation.leafPicker.changeTitle`,`Change the row type`),context:r,underNot:i,treeFull:a,...n===`change`&&o!==void 0?{current:o}:{},...u?{}:{hidden:Jo},recentKey:`automation-${r}`,textsOf:Yo,categoryLabelOf:e=>l(`automation.leafPicker.category.${e}`),reasonOf:e=>l(`automation.leafPicker.reason.${e}`),onPick:e=>{c(e),t(!1)}})}var Zo=`none`;function Qo(e){if(e.trim()===``)return;let t=Number(e);if(!(Number.isNaN(t)||t<=0))return Math.round(t*1e3)}function $o({hold:t,modes:n,onChange:r}){let{t:i}=Q(),a={held:i(`automation.hold.held`,`held`),stable:i(`automation.hold.stable`,`stable`)},o=e=>{if(e===Zo){r(void 0);return}let i=n.find(t=>t===e);if(i===void 0)return;let a=t?.ms??3e4;r(i===`stable`&&t?.tolerance!==void 0?{ms:a,mode:i,tolerance:t.tolerance}:{ms:a,mode:i})};return e(h,{children:[e(`label`,{className:`w-32`,children:[s($,{children:i(`automation.hold.label`,`For`)}),s(A,{value:t?.mode??Zo,onChange:e=>o(e.target.value),options:[{value:Zo,label:i(`automation.hold.none`,`no hold`)},...n.map(e=>({value:e,label:a[e]}))]})]}),t!==void 0&&e(`label`,{className:`w-24`,children:[s($,{children:i(`automation.hold.seconds`,`Seconds`)}),s(Y,{type:`number`,min:1,value:String(t.ms/1e3),onChange:e=>{let n=Qo(e.target.value);r(n===void 0?void 0:{...t,ms:n})}})]}),t?.mode===`stable`&&e(`label`,{className:`w-28`,children:[s($,{children:i(`automation.hold.tolerance`,`± tolerance`)}),s(Y,{type:`number`,min:0,step:`any`,value:t.tolerance===void 0?``:String(t.tolerance),placeholder:`0`,onChange:e=>{let n=e.target.value.trim(),i=n===``?NaN:Number(n),{tolerance:a,...o}=t;r(Number.isNaN(i)||i<0?o:{...o,tolerance:i})}})]})]})}function es({value:t,field:n,deviceId:r,cap:i,onChange:a}){let{t:o}=Q(),c=ss(n,r,i);if(n?.kind===`boolean`)return s(A,{value:t===!0?`true`:`false`,onChange:e=>a(e.target.value===`true`),options:[{value:`true`,label:o(`common.true`)},{value:`false`,label:o(`common.false`)}]});if(n?.kind===`enum`&&n.enumValues!==void 0&&n.enumValues.length>0)return s(A,{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:[s(Y,{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?s(`span`,{className:`text-xs text-foreground-subtle`,children:c.unit}):null]})}return s(Y,{value:String(t),placeholder:o(`common.valueWord`),onChange:e=>a(e.target.value)})}function ts({value:e,field:t,deviceId:n,cap:r,onChange:i}){let{t:a}=Q(),o=ss(t,n,r);return s(Y,{value:(o?e.map(e=>typeof e==`number`?o.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=>o?o.fromDisplayValue(e):e):n)}})}function ns(e){return typeof e==`object`&&!Ke(e)}function rs(e){return Ke(e)?e.value:ns(e)?e[0]??``:e}function is(e){return Ke(e)?[e.value]:ns(e)?e:typeof e==`boolean`?[]:[e]}function as(e){let t=e?.quantity;if(!(e?.kind!==`number`||t===void 0)&&!(!ge(t)||t===`none`||t===`device`))return Ge(t).length>0?t:void 0}function os(e,t){if(!(e===void 0||e===`none`)){if(e!==`device`)return e;if(!(t===void 0||t===`device`||t===`none`))return t}}function ss(e,t,n){let r=_t(),i=t??0,a=e?.kind===`number`&&e.quantity!==void 0,{data:o}=Ut({deviceId:i},{enabled:a&&i>0}),s=o?.sourceInfo?.quantity,c=ge(s)?s:void 0,l=os(e?.quantity,c);if(l===void 0)return;let u=o?.display;return fn({quantity:l,display:u,capName:n,unitPreferences:r})}function cs({leaf:t,devices:n,onChange:r}){let{t:i}=Q(),a={deviceId:t.deviceId,cap:t.cap,fieldPath:t.fieldPath},o=oo(a),c=Va(o?.kind),l=t.operator===`in`,u=as(o),d=u===void 0?void 0:ve(u),f=e=>{let{unit:n,...i}=t;r({...i,deviceId:e.deviceId,cap:e.cap,fieldPath:e.fieldPath})},p=e=>{let n=ls(e,c),{unit:i,...a}=t;r({...n===`in`?a:t,operator:n,value:n===`in`?[...is(t.value)]:rs(t.value)})};return e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[s(so,{value:a,devices:n,onChange:f}),e(`label`,{className:`min-w-[8rem]`,children:[s($,{children:i(`automation.conditionRow.comparison`,`Comparison`)}),s(A,{value:t.operator,onChange:e=>p(e.target.value),options:c.map(e=>({value:e.value,label:e.label}))})]}),e(`label`,{className:`min-w-[9rem] flex-1`,children:[s($,{children:i(`automation.conditionRow.value`,`Value`)}),l?s(ts,{value:is(t.value),field:o,deviceId:t.deviceId,cap:t.cap,onChange:e=>r({...t,value:[...e]})}):u!==void 0&&d!==void 0?s(gt,{quantity:u,storedUnit:d,value:typeof t.value==`number`?t.value:void 0,unit:t.unit,"aria-label":i(`automation.conditionRow.value`,`Value`),onChange:e=>{let n=Sn(e,d);r({...t,value:n.value,unit:n.unit})}}):s(es,{value:rs(t.value),field:o,deviceId:t.deviceId,cap:t.cap,onChange:e=>r({...t,value:e})})]}),s($o,{hold:t.for,modes:[`held`,`stable`],onChange:e=>{let{for:n,...i}=t;r(e===void 0?i:{...i,for:e})}})]})}function ls(e,t){return t.find(t=>t.value===e)?.value??`eq`}function us({leaf:t,onChange:n}){let{t:r}=Q();return e(`label`,{className:`min-w-[14rem] flex-1`,children:[s($,{children:r(`automation.triggerEditor.cronExpression`,`Cron expression`)}),s(Y,{value:t.cron,placeholder:`0 30 23 * * *`,onChange:e=>n({kind:`schedule`,cron:e.target.value})}),s(`span`,{className:`mt-1 block text-xs text-foreground-subtle`,children:s(ir,{i18nKey:`automation.triggerEditor.cronHint`,components:{code:s(`code`,{})}})})]})}function ds(){return s(`p`,{className:`text-xs text-foreground-subtle`,children:s(ir,{i18nKey:`automation.triggerEditor.manualHint`,components:{b:s(`strong`,{})}})})}function fs(e,t){return{kind:`device-becomes`,deviceId:e.deviceId,cap:e.cap,fieldPath:e.fieldPath,...t.becomes===void 0?{}:{becomes:t.becomes},...t.operator===void 0||t.value===void 0?{}:{operator:t.operator,value:t.value},...t.hold===void 0?{}:{for:t.hold},...t.debounceMs===void 0?{}:{debounceMs:t.debounceMs}}}function ps(e){return e.operator===void 0?e.becomes===void 0?`any`:`becomes`:e.operator}var ms=[`any`,`becomes`,`gt`,`gte`,`lt`,`lte`,`between`,`outside`];function hs(e){return e===`between`||e===`outside`}function gs(e){if(e.trim()===``)return;let t=Number(e);return Number.isNaN(t)?void 0:t}function _s(e){return typeof e==`number`?e:void 0}function vs({leaf:t,devices:n,onChange:r}){let{t:i}=Q(),a={deviceId:t.deviceId,cap:t.cap,fieldPath:t.fieldPath},o=oo(a),c=Re(t),l=ps(t),u=_s(t.value),d=Array.isArray(t.value)?[t.value[0],t.value[1]]:[void 0,void 0],f={...t.becomes===void 0?{}:{becomes:t.becomes},...t.operator===void 0||t.value===void 0?{}:{operator:t.operator,value:t.value},...c===void 0?{}:{hold:c},...t.debounceMs===void 0?{}:{debounceMs:t.debounceMs}},{becomes:p,operator:m,value:g,..._}=f,v=e=>{if(e===`any`){r(fs(a,_));return}if(e===`becomes`){r(fs(a,{..._,becomes:``}));return}let t=He.safeParse(e);t.success&&r(fs(a,{..._,operator:t.data,value:hs(t.data)?[0,0]:0}))},y={any:i(`automation.triggerEditor.anyChange`,`any change`),becomes:i(`automation.triggerEditor.becomesValue`,`becomes a value`),gt:i(`automation.triggerEditor.crossesAbove`,`rises above`),gte:i(`automation.triggerEditor.reachesAtLeast`,`reaches at least`),lt:i(`automation.triggerEditor.dropsBelow`,`drops below`),lte:i(`automation.triggerEditor.reachesAtMost`,`reaches at most`),between:i(`automation.triggerEditor.entersRange`,`enters the range`),outside:i(`automation.triggerEditor.leavesRange`,`leaves the range`),eq:i(`automation.triggerEditor.becomesValue`,`becomes a value`),ne:i(`automation.triggerEditor.stopsBeing`,`stops being`)};return e(h,{children:[s(so,{value:a,devices:n,onChange:e=>r(fs(e,f))}),e(`label`,{className:`min-w-[10rem]`,children:[s($,{children:i(`automation.triggerEditor.becomes`,`Becomes`)}),s(A,{value:l,onChange:e=>v(e.target.value),options:ms.map(e=>({value:e,label:y[e]}))})]}),l===`becomes`&&t.becomes!==void 0&&e(`div`,{className:`min-w-[9rem] flex-1`,children:[s($,{children:i(`automation.conditionRow.value`,`Value`)}),s(es,{value:t.becomes,field:o,deviceId:a.deviceId,cap:a.cap,onChange:e=>r(fs(a,{...f,becomes:e}))})]}),t.operator!==void 0&&!hs(l)&&e(`label`,{className:`w-28`,children:[s($,{children:i(`automation.conditionRow.value`,`Value`)}),s(Y,{type:`number`,step:`any`,value:u===void 0?``:String(u),onChange:e=>{let n=gs(e.target.value);n!==void 0&&r(fs(a,{...f,operator:t.operator,value:n}))}})]}),t.operator!==void 0&&hs(l)&&[0,1].map(n=>e(`label`,{className:`w-24`,children:[s($,{children:n===0?i(`automation.triggerEditor.rangeFrom`,`From`):i(`automation.triggerEditor.rangeTo`,`To`)}),s(Y,{type:`number`,step:`any`,value:d[n]===void 0?``:String(d[n]),onChange:e=>{let i=gs(e.target.value);if(i===void 0)return;let o=[d[0]??0,d[1]??0];o[n]=i,r(fs(a,{...f,operator:t.operator,value:o}))}})]},n)),s($o,{hold:c,modes:[`held`,`stable`],onChange:e=>{let{hold:t,...n}=f;r(fs(a,e===void 0?n:{...n,hold:e}))}}),e(`label`,{className:`w-28`,children:[s($,{children:i(`automation.triggerEditor.debounceS`,`Debounce (s)`)}),s(Y,{type:`number`,min:0,value:t.debounceMs===void 0?``:String(t.debounceMs/1e3),placeholder:`0`,onChange:e=>r(fs(a,{...f,debounceMs:ys(e.target.value)}))})]})]})}function ys(e){if(e.trim()===``)return;let t=Number(e);if(!(Number.isNaN(t)||t<0))return Math.round(t*1e3)}function bs({leaf:e,devices:t=[],onChange:n}){return s(`div`,{className:`w-full min-w-0`,children:s(xr,{kind:`event`,shape:`category`,devicePickerTestId:`trigger-event-device`,excludeTypes:Kr,deviceId:e.deviceId??null,category:e.category,knownDevices:t.map(e=>({id:e.id,name:e.name,...e.type===void 0?{}:{type:e.type}})),onDeviceChange:t=>n({kind:`device-event`,category:e.category,...t===null?{}:{deviceId:t}}),onCategoryChange:t=>n({kind:`device-event`,category:t,...e.deviceId===void 0?{}:{deviceId:e.deviceId}})})})}function xs(e,t){let n=e.find(e=>e.id===t.deviceId);return{kind:`global`,sourceStableId:n?.stableId??``,...n?.addonId===void 0?{}:{addonId:n.addonId},cap:t.cap,fieldPath:t.fieldPath}}function Ss(e,t){if(t.addonId!==void 0)return e.find(e=>e.stableId===t.sourceStableId&&e.addonId===t.addonId)?.id??0;let n=e.filter(e=>e.stableId===t.sourceStableId);return n.length===1?n[0]?.id??0:0}var Cs={kind:`global`,sourceStableId:``,cap:``,fieldPath:``};function ws({leaf:t,devices:n,onChange:r}){let{t:i}=Q(),a=Object.entries(t.bindings),o=e=>{r({...t,bindings:e})};return e(`div`,{className:`space-y-2`,children:[e(`div`,{className:`block`,children:[s(en,{label:i(`automation.expressionLeafRow.expression`,`Expression`),value:t.expr,placeholder:i(`automation.expressionLeafRow.indoorOutdoor5`,`indoor - outdoor > 5`),bindings:Object.keys(t.bindings),onChange:e=>r({...t,expr:e})}),s(`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&&s(`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])=>s(Ts,{alias:e,source:r,devices:n,onRename:n=>o(Os(t.bindings,e,n)),onChange:n=>o({...t.bindings,[e]:n}),onRemove:()=>o(ks(t.bindings,e))},e)),e(q,{variant:`ghost`,onClick:()=>o({...t.bindings,[Ds(t.bindings)]:Cs}),children:[s(j,{className:`h-3.5 w-3.5`}),` `,i(`common.name`)]})]}),s(`div`,{className:`flex flex-wrap items-end gap-2`,children:s($o,{hold:t.for,modes:[`held`],onChange:e=>{let{for:n,...i}=t;r(e===void 0?i:{...i,for:e})}})})]})}function Ts({alias:t,source:n,devices:r,onRename:i,onChange:a,onRemove:o}){let{t:c}=Q(),l=n.kind===`literal`,u=l?{deviceId:0,cap:``,fieldPath:``}:{deviceId:n.kind===`global`?Ss(r,n):0,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:[s($,{children:c(`automation.expressionLeafRow.name`,`Name`)}),s(Y,{value:t,placeholder:c(`automation.expressionLeafRow.aliasExample`),onChange:e=>i(e.target.value)})]}),e(`label`,{className:`w-36`,children:[s($,{children:c(`automation.expressionLeafRow.reads`,`Reads`)}),s(A,{value:l?`literal`:`global`,onChange:e=>a(e.target.value===`literal`?{kind:`literal`,value:``}:Cs),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:[s($,{children:c(`automation.expressionLeafRow.constant`,`Constant`)}),s(Y,{value:n.value===null?``:String(n.value),placeholder:`5`,onChange:e=>a({kind:`literal`,value:Es(e.target.value)})})]}):s(so,{value:u,devices:r,onChange:e=>a(xs(r,e))}),s(q,{variant:`ghost`,onClick:o,title:c(`automation.expressionLeafRow.removeThisName`,`Remove this name`),children:s(z,{className:`h-3.5 w-3.5`})})]})}function Es(e){let t=e.trim();return t===`true`?!0:t===`false`?!1:t!==``&&!Number.isNaN(Number(t))?Number(t):e}function Ds(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 Os(e,t,n){let r={};for(let[i,a]of Object.entries(e))i===t?r[n]=a:r[i]=a;return r}function ks(e,t){let n={};for(let[r,i]of Object.entries(e))r!==t&&(n[r]=i);return n}var As=`event-emitter`;function js(e){if(e.status===`pending`)return{kind:`pending`};if(e.status===`error`)return{kind:`unknown`};let t=Ue.safeParse(e.data);return t.success?{kind:`known`,vocabulary:Oe(t.data)}:{kind:`unknown`}}function Ms(e){let t=new Map;for(let n of e)n.source!==void 0&&!t.has(n.source.id)&&t.set(n.source.id,n.source);return[...t.values()]}function Ns(e,t){let n=new Map;for(let r of e)t!==void 0&&r.source?.id!==t||n.has(r.id)||n.set(r.id,r);return[...n.values()]}function Ps(e,t){return{kind:`device-fired`,...e.id===void 0?{}:{id:e.id},deviceId:t}}function Fs(e,t,n){let{sourceIds:r,eventIds:i,...a}=e,o=new Set(Ns(n,t).map(e=>e.id)),s=(i??[]).filter(e=>o.has(e));return{...a,...t===void 0?{}:{sourceIds:[t]},...s.length===0?{}:{eventIds:s}}}function Is(e,t){let{eventIds:n,...r}=e;return{...r,...t===void 0?{}:{eventIds:[t]}}}function Ls(e,t){let n=new Set(Ms(t).map(e=>e.id)),r=new Set(t.map(e=>e.id));return{sourceIds:(e.sourceIds??[]).filter(e=>!n.has(e)),eventIds:(e.eventIds??[]).filter(e=>!r.has(e))}}var Rs=``,zs={caps:[As]};function Bs({leaf:t,hideDevice:n=!1,onChange:r}){let{t:i}=Q(),a=t.deviceId>0,o=_n({deviceId:t.deviceId,capName:As},{enabled:a}),c=js({status:o.status,data:o.data}),l=c.kind===`known`?c.vocabulary:[],u=Ms(l),d=t.sourceIds?.[0],f=t.eventIds?.[0],p=Ns(l,d),m=c.kind===`known`?Ls(t,l):null,g=i(`automation.fired.anyEvent`,`Any event`),_=c.kind===`pending`?i(`automation.fired.loading`,`Reading what this device can fire…`):i(`automation.fired.unknown`,`What this device can fire could not be read.`);return e(h,{children:[!n&&e(`div`,{className:`min-w-[13rem] flex-1`,children:[s($,{children:i(`automation.fired.device`,`Device`)}),s(On,{pick:`device`,requires:zs,recentKey:`automation-device-fired`,value:a?{deviceId:t.deviceId}:null,onChange:e=>r(Ps(t,e?.deviceId??0))})]}),a&&c.kind!==`known`&&s(`p`,{className:`min-w-[13rem] flex-1 text-xs ${c.kind===`unknown`?`text-warning`:`text-foreground-subtle`}`,"data-testid":`fired-vocabulary-${c.kind}`,children:_}),a&&c.kind===`known`&&u.length>0&&e(`label`,{className:`min-w-[11rem] flex-1`,children:[s($,{children:i(`automation.fired.source`,`From`)}),s(A,{"data-testid":`fired-source`,value:d??Rs,onChange:e=>r(Fs(t,e.target.value===Rs?void 0:e.target.value,l)),options:[{value:Rs,label:i(`automation.fired.anySource`,`Any button`)},...u.map(e=>({value:e.id,label:e.label})),...(m?.sourceIds??[]).map(e=>({value:e,label:i(`automation.fired.gone`,`{{id}} (no longer declared)`,{id:e})}))]})]}),a&&c.kind===`known`&&e(`label`,{className:`min-w-[11rem] flex-1`,children:[s($,{children:i(`automation.fired.event`,`Event`)}),s(A,{"data-testid":`fired-event`,value:f??Rs,onChange:e=>r(Is(t,e.target.value===Rs?void 0:e.target.value)),options:[{value:Rs,label:g},...p.map(e=>({value:e.id,label:e.label})),...(m?.eventIds??[]).map(e=>({value:e,label:i(`automation.fired.gone`,`{{id}} (no longer declared)`,{id:e})}))]})]}),m!==null&&m.sourceIds.length+m.eventIds.length>0&&s(`p`,{className:`basis-full text-xs text-warning`,"data-testid":`fired-stale`,children:i(`automation.fired.staleHint`,`This row names something the device no longer declares, so it will not start a run. Pick again.`)}),(t.kinds!==void 0||t.match!==void 0)&&s(`p`,{className:`basis-full text-xs text-foreground-subtle`,"data-testid":`fired-extra`,children:i(`automation.fired.extraHint`,`This row also carries filters set outside the editor ({{what}}); they are kept as they are.`,{what:[...t.kinds??[],...(t.match??[]).map(e=>`${e.path} = ${String(e.equals)}`)].join(`, `)})})]})}var Vs=`text-xs text-foreground-subtle`;function Hs({children:e}){return s(`span`,{className:Vs,children:e})}function Us(e,t){return e.includes(t)?e.filter(e=>e!==t):[...e,t]}function Ws({selected:t,onChange:n}){let{t:r}=Q();return e(`div`,{className:`space-y-1`,children:[s(Hs,{children:r(`flow.scene.cameras`,`Cameras`)}),s(On,{multiple:!0,pick:`device`,noun:`camera`,fixedTypes:Ur,recentKey:`build-cameras`,value:jt(t),testId:`scene-cameras`,onChange:e=>n(Tt(e))})]})}function Gs({device:t,deviceId:n,selected:r,onToggle:i}){let a=wt({deviceId:n});return a.data===void 0||a.data.length===0?null:e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[s(`span`,{className:Vs,children:t?.name??`#${String(n)}`}),a.data.map(e=>s(q,{size:`sm`,variant:r.includes(e.id)?`primary`:`outline`,"aria-pressed":r.includes(e.id),onClick:()=>i(e.id),children:e.name},e.id))]})}function Ks({devices:t,deviceIds:n,selected:r,onChange:i}){let{t:a}=Q();if(n.length===0)return null;let o=e=>{let t=Us(r,e);i(t.length===0?void 0:t)};return e(`div`,{className:`space-y-1`,children:[s(Hs,{children:a(`flow.scene.zones`,`Zones`)}),s(`div`,{className:`space-y-2`,children:n.map(e=>s(Gs,{device:t.find(t=>t.id===e),deviceId:e,selected:r,onToggle:o},e))}),s(`p`,{className:Vs,children:r.length===0?a(`flow.scene.wholeScene`,`None picked: the whole scene counts.`):a(`flow.scene.zonesPicked`,`Only these zones count.`)})]})}var qs=[`animal`,`person`,`vehicle`,`package`,`other`];function Js(e){return qs.find(t=>t===e)??`other`}function Ys(e){switch(e){case`animal`:return{macro:`animal`};case`person`:return{macro:`person`};case`vehicle`:return{macro:`vehicle`};case`package`:return{macro:`package`};default:return{macro:`other`,className:``}}}function Xs(){let{t:e}=Q();return t=>{switch(t){case`person`:return e(`flow.class.person`,`Person`);case`vehicle`:return e(`flow.class.vehicle`,`Vehicle`);case`animal`:return e(`flow.class.animal`,`Animal`);case`package`:return e(`flow.class.package`,`Package`);default:return e(`automation.whenTree.macroOther`,`Other class`)}}}function Zs(e,t){let n={kind:`sub-class`,className:t};switch(e){case`animal`:return{macro:e,label:n};case`package`:return{macro:e,label:n};case`vehicle`:return{macro:e,label:n};default:return{macro:`person`}}}var Qs=[`automation`,`class-taxonomy`];function $s(){let e=te();return xe(u({queryKey:Qs,retry:!1,staleTime:1/0,queryFn:()=>e.trpcClient.notificationRules.getConditionCatalog.query({})}).data?.taxonomy)}function ec(e,t,n){let r=n?.groups.find(t=>t.key===e),i=r===void 0?et(e).filter(t=>t!==e).map(e=>({value:e,label:e})):r.options.filter(t=>t.value!==e).map(e=>({value:e.value,label:e.label}));return t!==void 0&&!i.some(e=>e.value===t)?[...i,{value:t,label:t}]:i}function tc({subject:e,onChange:t}){let{t:n}=Q(),r=e.label?.kind===`sub-class`?e.label.className:void 0,i=$s(),a=ec(e.macro,r,i);return a.length===0?null:s(A,{"aria-label":n(`automation.whenTree.labelAria`,`Narrow to`),"data-testid":`subject-label`,value:r??``,options:[{value:``,label:n(`automation.whenTree.anyLabel`,`Any`)},...a],onChange:n=>{let r=n.target.value;t(r===``?Ys(e.macro):Zs(e.macro,r))}})}function nc({onChange:e,subject:t}){let{t:n}=Q(),r=Yt(),i=t.macro===`person`?t.label:void 0,a=r.data??[],o=a.map(e=>({value:e.id,label:e.name}));return i!==void 0&&!a.some(e=>e.id===i.identityId)&&o.push({value:i.identityId,label:i.name}),s(A,{"aria-label":n(`automation.whenTree.labelAria`,`Narrow to`),"data-testid":`subject-label`,value:i?.identityId??``,options:[{value:``,label:n(`automation.whenTree.anyPerson`,`Anyone`)},...o],onChange:t=>{let n=t.target.value,r=o.find(e=>e.value===n);e(n===``||r===void 0?{macro:`person`}:{macro:`person`,label:{kind:`identity`,identityId:n,name:r.label}})}})}var rc=`plate:`,ic=`class:`,ac=200;function oc({onChange:e,subject:t}){let{t:n}=Q(),r=nn({includeCrops:!1,limit:ac}),i=t.macro===`vehicle`?t.label:void 0,a=i?.kind===`plate`?i.text:void 0,o=$s(),c=i?.kind===`sub-class`?i.className:void 0,l=[...new Set((r.data??[]).map(e=>e.text))];a!==void 0&&!l.includes(a)&&l.push(a);let u=a===void 0?c===void 0?``:`${ic}${c}`:`${rc}${a}`;return s(A,{"aria-label":n(`automation.whenTree.labelAria`,`Narrow to`),"data-testid":`subject-label`,value:u,options:[{value:``,label:n(`automation.whenTree.anyLabel`,`Any`)},...ec(`vehicle`,c,o).map(e=>({value:`${ic}${e.value}`,label:e.label})),...l.map(e=>({value:`${rc}${e}`,label:n(`automation.whenTree.plateOption`,`Plate {{text}}`,{text:e})}))],onChange:t=>{let n=t.target.value;n.startsWith(rc)?e({macro:`vehicle`,label:{kind:`plate`,text:n.slice(6)}}):n.startsWith(ic)?e({macro:`vehicle`,label:{kind:`sub-class`,className:n.slice(6)}}):e({macro:`vehicle`})}})}function sc({subject:t,classLabelsOnly:n,verb:r,onChange:i,onRemove:a}){let{t:o}=Q(),c=Xs(),l=t.macro===`other`?[]:Ye[t.macro],u=l.some(e=>e.kind===`cap`&&e.label===`identity`),d=l.some(e=>e.kind===`cap`&&e.label===`plate`);return e(`div`,{className:`flex flex-wrap items-center gap-2`,"data-testid":`subject-row`,children:[s(`div`,{className:`w-36`,children:s(A,{"aria-label":o(`automation.whenTree.macroAria`,`Class`),"data-testid":`subject-macro`,value:t.macro,options:qs.map(e=>({value:e,label:c(e)})),onChange:e=>{let n=Js(e.target.value);n!==t.macro&&i(Ys(n))}})}),s(`span`,{className:`text-sm text-foreground-muted`,children:r}),t.macro===`other`?s(Y,{className:`w-40`,"aria-label":o(`automation.whenTree.className`,`Class name`),"data-testid":`subject-class-name`,placeholder:o(`automation.whenTree.classNamePlaceholder`,`Class name`),value:t.className,onChange:e=>i({macro:`other`,className:e.target.value})}):u&&!n?s(`div`,{className:`w-44`,children:s(nc,{subject:t,onChange:i})}):d&&!n?s(`div`,{className:`w-44`,children:s(oc,{subject:t,onChange:i})}):!u&&s(`div`,{className:`w-44`,children:s(tc,{subject:t,onChange:i})}),a!==null&&s(q,{variant:`ghost`,onClick:a,title:o(`automation.whenTree.removeClass`,`Remove this class`),children:s(z,{className:`h-3.5 w-3.5`})})]})}function cc({subjects:t,optional:n,classLabelsOnly:r,verb:i,onChange:a}){let{t:o}=Q(),c=n||t.length>1;return e(`div`,{className:`space-y-2`,"data-testid":`subject-picker`,children:[t.map((e,n)=>s(sc,{subject:e,classLabelsOnly:r,verb:n===0?i:o(`automation.whenTree.orSubject`,`or`),onChange:e=>a(t.map((t,r)=>r===n?e:t)),onRemove:c?()=>a(t.filter((e,t)=>t!==n)):null},`${e.macro}-${String(n)}`)),t.length===0&&s(`p`,{className:`text-xs text-foreground-subtle`,children:o(`flow.scene.anyClass`,`None picked: any class counts.`)}),e(q,{variant:`ghost`,size:`sm`,onClick:()=>a([...t,Ys(`person`)]),children:[s(j,{className:`h-3.5 w-3.5`}),` `,t.length===0?o(`automation.whenTree.onlySomeClasses`,`Only some classes`):o(`automation.whenTree.addClass`,`Add a class`)]})]})}var lc=100;function uc({leaf:t,devices:n,onChange:r}){let{t:i}=Q(),a=Math.round((t.minScore??0)*lc),o=e=>{let{zones:n,...i}=t;r(e===void 0?i:{...i,zones:[...e]})},c=e=>{let{minScore:n,...i}=t;r(e<=0?i:{...i,minScore:e/lc})};return e(`div`,{className:`w-full space-y-3`,"data-testid":`detection-fields`,children:[s(cc,{subjects:t.subjects,optional:!1,classLabelsOnly:!1,verb:i(`automation.whenTree.detected`,`detected`),onChange:e=>r({...t,subjects:[...e]})}),s(Ws,{selected:t.deviceIds,onChange:e=>r({...t,deviceIds:[...e]})}),s(Ks,{devices:n,deviceIds:t.deviceIds,selected:t.zones??[],onChange:o}),e(`div`,{className:`space-y-1`,children:[s(Hs,{children:a===0?i(`flow.scene.minScoreAny`,`Minimum score: any`):i(`flow.scene.minScore`,`Minimum score: {{value}}`,{value:(a/lc).toFixed(2)})}),s(b,{min:0,max:lc,value:a,"aria-label":i(`flow.scene.minScoreAria`,`Minimum score`),className:`block w-full max-w-sm accent-primary`,onChange:e=>c(Number(e.target.value))})]})]})}function dc({leaf:t,devices:n,onChange:r}){let{t:i}=Q();return e(`div`,{className:`w-full space-y-3`,"data-testid":`stationary-fields`,children:[s(cc,{subjects:t.subjects??[],optional:!0,classLabelsOnly:!0,verb:i(`automation.whenTree.parked`,`object`),onChange:e=>{let{subjects:n,...i}=t;r(e.length===0?i:{...i,subjects:[...e]})}}),s(Ws,{selected:t.deviceIds,onChange:e=>r({...t,deviceIds:[...e]})}),s(Ks,{devices:n,deviceIds:t.deviceIds,selected:t.zones??[],onChange:e=>{let{zones:n,...i}=t;r(e===void 0?i:{...i,zones:[...e]})}}),s(An,{label:i(`flow.scene.firesWhen`,`Fires when it`),value:t.phase,onChange:e=>r({...t,phase:e}),options:[{value:`appeared`,label:i(`flow.scene.phaseAppeared`,`Stopped (parked)`)},{value:`departed`,label:i(`flow.scene.phaseDeparted`,`Left`)}]})]})}function fc({leaf:t,onChange:n}){let{t:r}=Q();return e(`div`,{className:`flex items-center gap-2`,"data-testid":`interval-fields`,children:[s(Hs,{children:r(`flow.scene.every`,`Every`)}),s(zr,{"aria-label":r(`flow.scene.intervalMinutes`,`Minutes`),className:`w-20`,value:t.minutes,onValue:e=>{e!==null&&n({kind:`interval`,minutes:Math.round(e)})}}),s(Hs,{children:r(`flow.scene.minutes`,`minutes`)})]})}function pc({leaf:t,devices:n,onChange:r}){let{t:i}=Q(),a=e=>{let{subjects:n,...i}=t;r(e.length===0?i:{...i,subjects:[...e]})},o=e=>{let{zones:n,...i}=t;r(e===void 0?i:{...i,zones:[...e]})},c=e=>{let{zones:n,...i}=t;r({...i,deviceId:e})};return e(`div`,{className:`space-y-3`,"data-testid":`stationary-present-fields`,children:[e(`div`,{className:`space-y-1`,children:[s(Hs,{children:i(`flow.scene.parkedOn`,`An object is parked on`)}),s(On,{pick:`device`,noun:`camera`,fixedTypes:Ur,recentKey:`build-cameras`,clearable:!1,value:t.deviceId>0?{deviceId:t.deviceId}:null,testId:`stationary-present-camera`,onChange:e=>{e!==null&&e.deviceId!==t.deviceId&&c(e.deviceId)}})]}),s(cc,{subjects:t.subjects??[],optional:!0,classLabelsOnly:!0,verb:i(`automation.whenTree.isParked`,`is parked`),onChange:a}),e(`div`,{className:`flex items-center gap-2`,children:[s(Hs,{children:i(`flow.scene.minCount`,`At least`)}),s(zr,{"aria-label":i(`flow.scene.minCountAria`,`Minimum parked objects`),"data-testid":`stationary-present-min-count`,className:`w-20`,value:t.minCount??1,onValue:e=>{let{minCount:n,...i}=t;r(e===null||e<=1?i:{...i,minCount:Math.floor(e)})}}),s(Hs,{children:i(`flow.scene.minCountUnit`,`parked objects`)})]}),s(Ks,{devices:n,deviceIds:t.deviceId>0?[t.deviceId]:[],selected:t.zones??[],onChange:o})]})}var mc=[`mon`,`tue`,`wed`,`thu`,`fri`,`sat`,`sun`],hc=[`sunrise`,`sunset`,`dawn`,`dusk`],gc={from:{kind:`clock`,hh:22,mm:0},to:{kind:`clock`,hh:6,mm:0}};function _c(e,t){return{kind:`time-is`,...e===void 0?{}:{between:e},...t===void 0?{}:{days:[...t]}}}function vc(e){return e.days??mc}function yc(e,t){let n=vc(e),r=n.includes(t)?n.filter(e=>e!==t):mc.filter(e=>e===t||n.includes(e)),i=r.length===mc.length;return _c(e.between,i&&e.between!==void 0?void 0:r)}function bc(e,t){if(t){let t=e.days!==void 0&&e.days.length===mc.length;return _c(e.between??gc,t?void 0:e.days)}return _c(void 0,vc(e))}function xc(e,t,n){return _c({...e.between??gc,[t]:n},e.days)}function Sc(e){return e===`sun`?{kind:`sun`,event:`sunset`,offsetMin:0}:{kind:`clock`,hh:12,mm:0}}function Cc(e){return e.kind===`date`?Sc(`clock`):e}function wc(e){let t=e.between;return t===void 0||t.from.kind!==`clock`||t.to.kind!==`clock`?!1:t.to.hh*60+t.to.mm<=t.from.hh*60+t.from.mm}function Tc(e,t){if(t===void 0)return null;let n=Se(e,t)[0];return n===void 0?null:`${n.path}: ${n.message}`}function Ec({label:t,testId:n,end:r,onChange:i}){let{t:a}=Q(),o=e=>`${t}: ${e}`;return e(`div`,{role:`group`,"aria-label":t,"data-testid":n,children:[s($,{children:t}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[s(A,{wrapperClassName:`relative w-40`,"aria-label":t,value:r.kind,options:[{value:`clock`,label:a(`schedulers.point.clock`,`At a time`)},{value:`sun`,label:a(`schedulers.point.sun`,`At a sun event`)}],onChange:e=>{let t=e.target.value;(t===`clock`||t===`sun`)&&t!==r.kind&&i(Sc(t))}}),r.kind===`clock`&&s(Y,{type:`time`,className:`w-28`,"aria-label":o(a(`schedulers.point.time`,`Time`)),value:Ai(r.hh,r.mm),onChange:e=>{let t=ki(e.target.value);t!==null&&t.kind===`clock`&&i(t)}}),r.kind===`sun`&&e(h,{children:[s(A,{wrapperClassName:`relative w-40`,"aria-label":o(a(`schedulers.point.sunEvent`,`Sun event`)),value:r.event,options:hc.map(e=>({value:e,label:a(`schedulers.sun.${e}`,e)})),onChange:e=>{let t=hc.find(t=>t===e.target.value);t!==void 0&&i({...r,event:t})}}),s(zr,{"aria-label":o(a(`schedulers.point.offset`,`Offset (minutes, negative = before)`)),title:a(`schedulers.point.offset`,`Offset (minutes, negative = before)`),className:`w-20`,value:r.offsetMin,onValue:e=>{e!==null&&i({...r,offsetMin:Math.round(e)})}})]})]})]})}function Dc({leaf:t,onChange:n}){let{t:r}=Q(),i=t.between,a=vc(t);return e(`div`,{className:`flex w-full flex-col gap-2`,"data-testid":`time-is-fields`,children:[e(`div`,{className:`flex flex-wrap items-end gap-x-4 gap-y-2`,children:[e(`label`,{children:[s($,{children:r(`automation.timeIs.window`,`Time of day`)}),s(A,{wrapperClassName:`relative w-40`,"aria-label":r(`automation.timeIs.window`,`Time of day`),value:i===void 0?`whole-day`:`between`,options:[{value:`between`,label:r(`automation.timeIs.between`,`Between two times`)},{value:`whole-day`,label:r(`automation.timeIs.wholeDay`,`The whole day`)}],onChange:e=>n(bc(t,e.target.value===`between`))})]}),i!==void 0&&e(h,{children:[s(Ec,{label:r(`automation.timeIs.from`,`From`),testId:`time-is-from`,end:Cc(i.from),onChange:e=>n(xc(t,`from`,e))}),s(Ec,{label:r(`automation.timeIs.to`,`To`),testId:`time-is-to`,end:Cc(i.to),onChange:e=>n(xc(t,`to`,e))})]})]}),e(`div`,{children:[s($,{children:r(`schedulers.profile.days`,`Days`)}),s(`div`,{className:`flex flex-wrap gap-1`,role:`group`,"aria-label":r(`schedulers.profile.days`,`Days`),children:mc.map(e=>{let i=a.includes(e);return s(q,{size:`sm`,variant:i?`primary`:`outline`,"aria-pressed":i,onClick:()=>n(yc(t,e)),children:r(`schedulers.day.${e}`,e)},e)})}),a.length===0&&s(`p`,{className:`mt-1 text-xs text-warning`,"data-testid":`time-is-no-days`,children:r(`automation.timeIs.noDays`,`Pick at least one day.`)}),wc(t)&&s(`p`,{className:`mt-1 text-xs text-foreground-subtle`,"data-testid":`time-is-wraps`,children:r(`automation.timeIs.wraps`,`This window ends the next day. The days are the days it starts on.`)})]})]})}function Oc(e,t){let n=e.leaf;if(n.kind!==`device-becomes`&&n.kind!==`device-event`&&n.kind!==`device-fired`)return;let r=t.find(e=>e.id===n.deviceId)?.name;return n.kind===`device-becomes`?r:n.kind===`device-fired`?[r,[...n.sourceIds??[],...n.eventIds??[]].join(` `)].filter(e=>e!==void 0&&e!==``).join(` · `)||void 0:r===void 0?n.category:`${n.category} · ${r}`}function kc({leaf:t,devices:n,onChange:r}){let{t:i}=Q(),a=Ko(),o=a.map(e=>e.id),c=Ho(t,o),l=i(`automation.triggeredBy.triggers`,`Started by`);return e(`div`,{children:[s($,{children:l}),a.length===0?s(`p`,{className:`text-xs text-warning`,"data-testid":`triggered-by-no-rows`,children:i(`automation.triggeredBy.noRows`,`This automation has no trigger row to choose. Add one to the rules first.`)}):s(`div`,{className:`flex flex-wrap gap-1`,role:`group`,"aria-label":l,children:a.map(e=>{let i=t.leafIds.includes(e.id),a=Oc(e,n);return s(q,{size:`sm`,variant:i?`primary`:`outline`,"aria-pressed":i,className:`h-auto min-h-8 whitespace-normal py-1 text-left`,onClick:()=>r(Vo(t,e.id,o)),children:`${e.ordinal}. ${Ha(e.leaf.kind)}${a===void 0?``:` · ${a}`}`},e.id)})}),a.length>0&&t.leafIds.length===0&&s(`p`,{className:`mt-1 text-xs text-warning`,"data-testid":`triggered-by-none-picked`,children:i(`automation.triggeredBy.nonePicked`,`Pick at least one trigger.`)}),c.length>0&&s(`p`,{className:`mt-1 text-xs text-warning`,"data-testid":`triggered-by-missing`,children:i(`automation.triggeredBy.missing`,{count:c.length,defaultValue_one:`{{count}} chosen trigger no longer exists. Press a trigger to drop it.`,defaultValue_other:`{{count}} chosen triggers no longer exist. Press a trigger to drop them.`})})]})}function Ac(e){return e.kind===`all`||e.kind===`any`}function jc(e){return[`when`,...e].join(`.`)}function Mc(e){let t=e.when;return Ac(t)?t:{kind:`all`,children:[t]}}function Nc(e,t){return{...e,when:t}}function Pc(e){return Nc(e,Mc(e))}function Fc(e,t){let[n,...r]=t;if(n===void 0)return e;if(e.kind===`not`)return n===0?Fc(e.child,r):null;if(nt(e))return null;let i=e.children[n];return i===void 0?null:Fc(i,r)}function Ic(e,t,n){let[r,...i]=t;if(r===void 0)return n(e);if(e.kind===`not`){if(r!==0)return e;let t=Ic(e.child,i,n);return t===null?null:{kind:`not`,child:t}}if(nt(e))return e;let a=e.children[r];if(a===void 0)return e;let o=Ic(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 Lc(e,t,n){let r=Mc(e);return Nc(e,Ic(r,t,n)??{kind:r.kind,children:[]})}function Rc(e){return{kind:e,children:[Ka(`device-is`)]}}function zc(e,t,n){return Lc(e,t,e=>Ac(e)?{kind:e.kind,children:[...e.children,n]}:e)}function Bc(e,t,n){return Lc(e,t,()=>n)}function Vc(e,t){return Lc(e,t,()=>null)}function Hc(e,t,n){return Lc(e,t,e=>Ac(e)?{kind:n,children:e.children}:e)}function Uc(e,t){return t.length===0?e:Lc(e,t,e=>({kind:`not`,child:e}))}function Wc(e,t){return Lc(e,t,e=>e.kind===`not`?e.child:e)}function Gc(e,t){if(e.kind===t)return e;if(e.kind===`device-is`&&t===`device-becomes`){let{deviceId:n,cap:r,fieldPath:i,operator:a,value:o}=e,s={kind:t,deviceId:n,cap:r,fieldPath:i};return a===`eq`&&!Array.isArray(o)&&typeof o!=`object`?{...s,becomes:o}:s}if(e.kind===`device-becomes`&&t===`device-is`){let{deviceId:n,cap:r,fieldPath:i,becomes:a}=e;return{kind:t,deviceId:n,cap:r,fieldPath:i,operator:`eq`,value:a??``}}let n=Ka(t);return Be(e)&&e.id!==void 0&&Be(n)?{...n,id:e.id}:n}function Kc(e){let t=Mc(e),n=t.children.length===0;return{depth:n?0:$e(t),leaves:n?0:Fe(t),depthLimit:4,leafLimit:32}}function qc(e,t){let n=Mc(e),r=1,i=n;for(let e of t){let t=Fc(i,[e]);if(t===null)break;r+=1,i=t}return r+2<=4}function Jc(e,t,n){let r=t[t.length-1];if(r===void 0)return e;let i=t.slice(0,-1),a=Fc(Mc(e),i);if(a===null||!Ac(a))return e;let o=r+n;return o<0||o>=a.children.length?e:Lc(e,i,()=>({kind:a.kind,children:Xa(a.children,r,o)}))}function Yc(e,t,n){let r=jc(t),i=jc(n),a=e=>e===r||e.startsWith(`${r}.`)?i+e.slice(r.length):e===i||e.startsWith(`${i}.`)?r+e.slice(i.length):e;return new Set([...e].map(a))}function Xc(e,t){return nt(e)?t(e.kind):e.kind===`not`?`NOT ${Xc(e.child,t)}`:e.children.map(e=>Zc(e,t)).join(` · `)}function Zc(e,t){return Ac(e)?`${e.kind.toUpperCase()} (${Xc(e,t)})`:Xc(e,t)}d();function Qc({leaf:t,devices:n,context:r,underNot:i,toneClass:a,result:o,onNegate:c,move:u,onChange:d,onRemove:f}){let{t:p}=Q(),[m,h]=l(!1),g=Be(t);return e(`div`,{className:`rounded border p-2 ${a}`,"data-testid":`when-row`,"data-kind":t.kind,children:[e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[e(`div`,{className:`min-w-[13rem] max-w-xs flex-1`,children:[s($,{children:p(`automation.whenTree.rowType`,`Row type`)}),e(q,{variant:`outline`,"data-testid":`when-row-type`,className:`w-full justify-between`,onClick:()=>h(!0),title:p(`automation.leafPicker.changeType`,`Change type`),children:[s(`span`,{className:`truncate`,children:Ha(t.kind)}),s(`span`,{className:`text-foreground-subtle`,children:p(`automation.leafPicker.changeType`,`Change type`)})]}),s(Xo,{open:m,onOpenChange:h,mode:`change`,context:r,underNot:i,treeFull:!1,current:t.kind,onPick:e=>{e!==t.kind&&d(Gc(t,e))}})]}),s(X,{variant:g?`info`:`neutral`,"data-testid":`when-row-nature`,children:g?p(`automation.whenTree.natureEvent`,`Event`):p(`automation.whenTree.natureState`,`State`)}),s(`span`,{className:`flex-1`}),u!==void 0&&s(go,{move:u}),c!==null&&s(q,{variant:`ghost`,onClick:c,title:p(`automation.whenTree.negateRow`,`Invert this row (NOT)`),children:`NOT`}),s(q,{variant:`ghost`,onClick:f,title:p(`automation.whenTree.removeRow`,`Remove this row`),children:s(z,{className:`h-3.5 w-3.5`})})]}),s(`div`,{className:`mt-2 flex flex-wrap items-end gap-2`,children:s($c,{leaf:t,devices:n,onChange:d})}),o!==void 0&&s(`div`,{className:`mt-2`,children:o})]})}function $c({leaf:e,devices:t,onChange:n}){switch(e.kind){case`device-becomes`:return s(vs,{leaf:e,devices:t,onChange:n});case`device-event`:return s(bs,{leaf:e,devices:t,onChange:n});case`device-fired`:return s(Bs,{leaf:e,onChange:n});case`schedule`:return s(us,{leaf:e,onChange:n});case`interval`:return s(fc,{leaf:e,onChange:n});case`manual`:return s(ds,{});case`detection`:return s(uc,{leaf:e,devices:t,onChange:n});case`stationary`:return s(dc,{leaf:e,devices:t,onChange:n});case`device-is`:return s(cs,{leaf:e,devices:t,onChange:n});case`stationary-present`:return s(pc,{leaf:e,devices:t,onChange:n});case`expression`:return s(ws,{leaf:e,devices:t,onChange:n});case`time-is`:return s(Dc,{leaf:e,onChange:n});case`triggered-by`:return s(kc,{leaf:e,devices:t,onChange:n})}}d();function el(e){return e===`any`?`any`:`all`}function tl(e){return e===`pass`?`pass`:e===`fail`?`fail`:`idle`}function nl(e,t,n=!0){return e===void 0?t:n?_a(tl(e)):ya(tl(e))}function rl(e,t){return e.run?.nodes.get(jc(t))}function il({recipe:t,devices:n,onChange:r,run:i=null,hideRule:a=!1,context:o=`trigger`}){let{t:c}=Q(),u=Mc(t),d=Kc(t),[f,p]=l(()=>new Set),m={leafContext:o,recipe:t,devices:n,run:i,onChange:r,reshape:e=>{p(new Set),r(e)},collapsed:f,toggleCollapsed:e=>{let t=jc(e);p(e=>e.has(t)?new Set([...e].filter(e=>e!==t)):new Set([...e,t]))},moveControls:(e,n)=>{let i=e[e.length-1]??0,a=n=>()=>{let a=[...e.slice(0,-1),i+n];p(t=>Yc(t,e,a)),r(Jc(t,e,n))};return{up:i>0?a(-1):null,down:i<n-1?a(1):null}}},h=u.children.length===0;return e(`div`,{className:`space-y-2`,"data-testid":`when-tree`,children:[!a&&s(`p`,{className:`text-xs text-foreground-subtle`,children:c(`automation.whenTree.rule`,`An event starts a run when it happens and everything here is true at that moment. With only states, a run starts when they become true.`)}),s(pl,{block:u,path:[],ctx:m,underNot:!1,rail:0,budgetText:c(`automation.whenTree.budget`,{depth:d.depth,depthLimit:d.depthLimit,leaves:d.leaves,leafLimit:d.leafLimit}),move:null,emptyHint:h&&!a?c(`automation.whenTree.empty`,`Add a row to say when this runs. Without one nothing can ever start this automation.`):null})]})}function al({node:e,path:t,ctx:n,underNot:r,move:i,rail:a}){return nt(e)?s(ol,{leaf:e,path:t,ctx:n,underNot:r,move:i}):e.kind===`not`?s(fl,{child:e.child,path:t,ctx:n,move:i,rail:a}):s(pl,{block:e,path:t,ctx:n,underNot:r,move:i,rail:a,budgetText:null,emptyHint:null})}function ol({leaf:e,path:t,ctx:n,underNot:r,move:i}){let a=rl(n,t),o=n.run!==null&&n.run.triggerPath===jc(t)?n.run.vars:void 0;return s(Qc,{leaf:e,devices:n.devices,context:n.leafContext,underNot:r,toneClass:nl(a?.outcome,`border-border`),result:a===void 0?void 0:s(sl,{leaf:e,node:a,vars:o}),onNegate:r?null:()=>n.reshape(Uc(n.recipe,t)),...i===null?{}:{move:i},onChange:e=>n.onChange(Bc(n.recipe,t,e)),onRemove:()=>n.reshape(Vc(n.recipe,t))})}function sl({leaf:e,node:t,vars:n}){return e.kind===`device-is`&&e.unit!==void 0?s(cl,{leaf:e,node:t,vars:n}):s(io,{node:t,vars:n,expected:t.expected,observed:t.observed})}function cl({leaf:e,node:t,vars:n}){let r=as(oo({deviceId:e.deviceId,cap:e.cap,fieldPath:e.fieldPath})),i=r===void 0?void 0:ve(r),a=t=>t===void 0?null:ra(t,i,e.unit);return s(io,{node:t,vars:n,expected:a(t.rawExpected),observed:a(t.rawObserved)})}function ll({node:e}){return e===void 0?null:s(io,{node:e,expected:null,observed:null})}function ul({expanded:e,onToggle:t}){let{t:n}=Q(),r=e?n(`automation.whenTree.collapse`,`Collapse this block`):n(`automation.whenTree.expand`,`Expand this block`);return s(q,{variant:`ghost`,"aria-expanded":e,"aria-label":r,title:r,onClick:t,children:s(ft,{expanded:e})})}function dl({node:e}){let{t}=Q(),n=`${t(`automation.whenTree.rowCount`,{count:Fe(e)})} · ${Xc(e,Ha)}`;return s(`p`,{"data-testid":`when-block-summary`,title:n,className:`break-words text-xs text-foreground-muted sm:truncate`,children:n})}function fl({child:t,path:n,ctx:r,move:i,rail:a}){let{t:o}=Q(),c=!r.collapsed.has(jc(n));return e(`div`,{className:`space-y-1.5 rounded border p-2 ${nl(rl(r,n)?.outcome,`border-warning/40`,!1)}`,"data-testid":`when-not`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[s(ul,{expanded:c,onToggle:()=>r.toggleCollapsed(n)}),s(X,{variant:`warning`,children:`NOT`}),s(`span`,{className:`text-xs text-foreground-subtle`,children:o(`automation.whenTree.notHint`,`True when what is below is not`)}),s(`span`,{className:`flex-1`}),i!==null&&s(go,{move:i}),e(q,{variant:`ghost`,onClick:()=>r.reshape(Wc(r.recipe,n)),title:o(`automation.whenTree.removeNot`,`Remove the NOT, keeping what is inside`),children:[s(ct,{className:`h-3.5 w-3.5`}),` `,o(`automation.whenTree.removeNotLabel`,`Remove NOT`)]})]}),s(ll,{node:rl(r,n)}),c?s(`div`,{className:`pl-3`,children:s(al,{node:t,path:[...n,0],ctx:r,underNot:!0,move:null,rail:a})}):s(dl,{node:t})]})}function pl({block:t,path:n,ctx:r,underNot:i,move:a,rail:o,budgetText:c,emptyHint:u}){let{t:d}=Q(),f=n.length===0,p=f||!r.collapsed.has(jc(n)),m=qc(r.recipe,n),[h,g]=l(!1),_=Po(t.children,o),v=[{value:`all`,label:d(`automation.whenTree.allOf`,`All of (AND)`)},{value:`any`,label:d(`automation.whenTree.anyOf`,`Any of (OR)`)}];return e(`div`,{className:`space-y-2 rounded border p-2 ${nl(rl(r,n)?.outcome,`border-border`,!1)}`,"data-testid":`when-block`,"data-kind":t.kind,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[!f&&s(ul,{expanded:p,onToggle:()=>r.toggleCollapsed(n)}),s(`div`,{className:`w-40`,children:s(A,{"aria-label":d(`automation.whenTree.blockKind`,`How the rows below combine`),"data-testid":`when-block-kind`,value:t.kind,options:v,onChange:e=>r.onChange(Hc(r.recipe,n,el(e.target.value)))})}),c!==null&&s(`span`,{className:`text-xs text-foreground-subtle`,children:c}),s(`span`,{className:`flex-1`}),a!==null&&s(go,{move:a}),!f&&!i&&s(q,{variant:`ghost`,onClick:()=>r.reshape(Uc(r.recipe,n)),title:d(`automation.whenTree.negateBlock`,`Invert this block (NOT)`),children:`NOT`}),!f&&s(q,{variant:`ghost`,onClick:()=>r.reshape(Vc(r.recipe,n)),title:d(`automation.whenTree.removeBlock`,`Delete this block and everything in it`),children:s(z,{className:`h-3.5 w-3.5`})})]}),s(ll,{node:rl(r,n)}),u!==null&&s(`p`,{className:`text-xs text-foreground-subtle`,children:u}),!p&&s(dl,{node:t}),p&&t.children.length>0&&s(`div`,{className:`space-y-1.5 border-l-2 pl-3 ${Fo(o)}`,"data-testid":`when-block-rail`,"data-rail":o,children:t.children.map((e,i)=>s(al,{node:e,path:[...n,i],ctx:r,underNot:!1,move:r.moveControls([...n,i],t.children.length),rail:_[i]??o},jc([...n,i])))}),p&&e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(q,{variant:`outline`,onClick:()=>g(!0),title:d(`automation.whenTree.addRowTitle`,`Add one row: an event or a state`),children:[s(j,{className:`h-4 w-4`}),` `,d(`automation.whenTree.addRow`,`Add row`)]}),s(Xo,{open:h,onOpenChange:g,mode:`add`,context:r.leafContext,underNot:i,treeFull:Fe(Mc(r.recipe))>=32,onPick:e=>r.onChange(zc(r.recipe,n,Ka(e)))}),e(q,{variant:`outline`,disabled:!m,onClick:()=>r.onChange(zc(r.recipe,n,Rc(t.kind===`all`?`any`:`all`))),title:m?d(`automation.whenTree.addBlockTitle`,`Add a nested block of rows`):d(`automation.whenTree.tooDeep`,`The rules nest at most {{max}} levels deep`,{max:Kc(r.recipe).depthLimit}),children:[s(j,{className:`h-4 w-4`}),` `,d(`automation.whenTree.addBlock`,`Add block`)]})]})]})}var ml={kind:`all`,children:[]};function hl(e){return e.kind===`wait`||e.kind===`command`}function gl(e){return!nt(e)&&e.kind!==`not`&&e.children.length===0?null:qe(e)}function _l(e){let{if:t,else:n,...r}=e;return r}function vl({when:t,devices:n,hint:r,onChange:i,children:a}){let{t:o}=Q(),c=t===void 0?null:{when:t,actions:[]},l=t===void 0?null:gl(t);return e(`div`,{className:`space-y-2 border-t border-border-subtle pt-2`,children:[s(on,{checked:t!==void 0,label:o(`automation.stepGuard.if`,`Only if…`),"aria-label":o(`automation.stepGuard.if`,`Only if…`),onCheckedChange:e=>i(e?ml:void 0)}),c!==null&&e(h,{children:[s(`p`,{className:`text-xs text-foreground-subtle`,children:r}),s(il,{hideRule:!0,context:`guard`,recipe:c,devices:n,onChange:e=>i(e.when)}),l!==null&&s(J,{variant:`warning`,message:l}),a]})]})}function yl({step:t,devices:n,devicesState:r,variables:i,onChange:a}){let{t:o}=Q();return e(vl,{when:t.if,devices:n,hint:o(`automation.stepGuard.hint`,`Checked when this step is reached. If a state cannot be read, the step and its else are both skipped.`),onChange:e=>a(e===void 0?_l(t):{...t,if:e}),children:[s(on,{checked:t.else!==void 0,label:o(`automation.stepGuard.else`,`Otherwise, run…`),"aria-label":o(`automation.stepGuard.else`,`Otherwise, run…`),onCheckedChange:e=>{if(e)a({...t,else:[]});else{let{else:e,...n}=t;a(n)}}}),t.else!==void 0&&s(`div`,{className:`border-l-2 border-border-subtle pl-3`,children:s(Pl,{nested:!0,actions:t.else,devices:n,...r===void 0?{}:{devicesState:r},...i===void 0?{}:{variables:i},allowedKinds:[`command`,`wait`],onChange:e=>a({...t,else:e.filter(hl)})})})]})}function bl({index:t,step:n,devices:r,devicesState:i,variables:a,depth:o=0,roundDevices:c,onChange:l}){let{t:u}=Q(),d={nested:!0,flowControl:!0,devices:r,depth:o+1,allowedKinds:Ao(o+1),...c===void 0?{}:{roundDevices:c},...i===void 0?{}:{devicesState:i},...a===void 0?{}:{variables:a}};return e(`div`,{className:`space-y-3`,children:[s(`p`,{className:`text-xs text-foreground-subtle`,children:u(`automation.choose.hint`,`Read top to bottom: the first branch whose condition is true runs, and only that one. If a condition cannot be read, nothing runs.`)}),n.branches.map((i,a)=>{let o={when:i.if,actions:[]},c=gl(i.if);return e(`div`,{className:`space-y-2 border-l-2 border-border-subtle pl-3`,"data-testid":`choose-branch-${String(t)}-${String(a)}`,children:[e(`div`,{className:`flex items-center gap-2`,children:[s($,{children:a===0?u(`automation.choose.if`,`If`):u(`automation.choose.elseIf`,`Otherwise, if`)}),s(q,{variant:`ghost`,className:`ml-auto`,disabled:!To(n),"data-testid":`choose-remove-${String(t)}-${String(a)}`,onClick:()=>l(Eo(n,a)),title:To(n)?u(`automation.choose.removeBranch`,`Remove this branch`):u(`automation.choose.lastBranch`,`A choose keeps at least one branch`),children:s(z,{className:`h-3.5 w-3.5`})})]}),s(il,{hideRule:!0,context:`guard`,recipe:o,devices:r,onChange:e=>l(Do(n,a,{...i,if:e.when}))}),c!==null&&s(J,{variant:`warning`,message:c}),s($,{children:u(`automation.choose.then`,`Then run`)}),s(Pl,{...d,actions:i.steps,onChange:e=>l(Do(n,a,{...i,steps:e.filter(jo)}))})]},String(a))}),e(q,{variant:`outline`,"data-testid":`choose-add-${String(t)}`,disabled:!Co(n),onClick:()=>l(wo(n)),title:Co(n)?void 0:u(`automation.choose.maxBranches`,`A choose takes at most 6 branches`),children:[s(j,{className:`h-4 w-4`}),` `,u(`automation.choose.addBranch`,`Add a branch`)]}),s(on,{"data-testid":`choose-else-${String(t)}`,checked:n.else!==void 0,label:u(`automation.choose.else`,`Otherwise, run…`),"aria-label":u(`automation.choose.else`,`Otherwise, run…`),onCheckedChange:e=>l(Oo(n,e?[]:void 0))}),n.else!==void 0&&s(`div`,{className:`border-l-2 border-border-subtle pl-3`,children:s(Pl,{...d,actions:n.else,onChange:e=>l(Oo(n,e.filter(jo)))})})]})}function xl(e){return Object.entries(e).map(([e,t])=>({name:e,value:t}))}function Sl(e){return Object.fromEntries(e.map(e=>[e.name,e.value]))}function Cl(e,t,n){let r=xl(e);return r.some((e,r)=>r!==t&&e.name===n)?e:Sl(r.map((e,r)=>r===t?{...e,name:n}:e))}function wl(e,t,n){return Sl(xl(e).map((e,r)=>r===t?{...e,value:n}:e))}function Tl(e){return!Object.keys(e).includes(``)}function El(e){return Tl(e)?{...e,"":``}:e}function Dl(e,t){return Sl(xl(e).filter((e,n)=>n!==t))}var Ol=`{{vars.name}}`;function kl({index:t,vars:n,onChange:r}){let{t:i}=Q();return e(`div`,{className:`space-y-2`,children:[xl(n).map((a,o)=>e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[e(`label`,{className:`w-40`,children:[s($,{children:i(`automation.actionList.setName`,`Variable`)}),s(Y,{"data-testid":`set-name-${String(t)}-${String(o)}`,value:a.name,spellCheck:!1,onChange:e=>r(Cl(n,o,e.target.value))})]}),e(`label`,{className:`min-w-40 flex-1`,children:[s($,{children:i(`automation.actionList.setValue`,`Value`)}),s(Y,{"data-testid":`set-value-${String(t)}-${String(o)}`,value:String(a.value),onChange:e=>r(wl(n,o,e.target.value))})]}),s(q,{variant:`ghost`,onClick:()=>r(Dl(n,o)),title:i(`automation.actionList.setRemove`,`Remove this variable`),children:s(z,{className:`h-3.5 w-3.5`})})]},String(o))),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(q,{variant:`outline`,"data-testid":`set-add-${String(t)}`,disabled:!Tl(n),onClick:()=>r(El(n)),children:[s(j,{className:`h-4 w-4`}),` `,i(`automation.actionList.setAdd`,`Add a variable`)]}),s(`span`,{className:`text-xs text-foreground-subtle`,children:i(`automation.actionList.setHint`,`The steps after this one can use it as {{slot}}.`,{slot:Ol,interpolation:{escapeValue:!1}})})]})]})}function Al({index:t,step:n,devices:r,devicesState:i,variables:a,depth:o=0,roundDevices:c,onChange:l}){let{t:u}=Q(),{loop:d}=n,f={count:u(`automation.repeat.byCount`,`A number of times`),while:u(`automation.repeat.byWhile`,`While a condition is true`),until:u(`automation.repeat.byUntil`,`Until a condition is true`),forEach:u(`automation.repeat.byForEach`,`Once for each device`)},p=d.by===`while`||d.by===`until`,m=p?gl(d.when):null,g={name:Ae,hint:u(`automation.repeat.itemHint`,`the device of this round`)},_=d.by===`forEach`?[...a??[],g]:a,v=d.by===`forEach`?d.target.ids:c;return e(`div`,{className:`space-y-2`,children:[s(`div`,{className:`w-64`,children:s(A,{"data-testid":`repeat-by-${String(t)}`,"aria-label":u(`automation.repeat.by`,`Repeat`),value:d.by,onChange:e=>{let t=e.target.value;Ta(t)&&t!==d.by&&l({...n,loop:ka(t)})},options:xa.map(e=>({value:e,label:f[e]}))})}),d.by===`count`&&e(`label`,{className:`block w-24`,children:[s($,{children:u(`automation.repeat.count`,`Times`)}),s(Y,{type:`number`,min:1,max:20,"data-testid":`repeat-count-${String(t)}`,value:String(d.count),onChange:e=>l({...n,loop:{...d,count:Da(Number(e.target.value))}})})]}),p&&e(h,{children:[s(`p`,{className:`text-xs text-foreground-subtle`,children:d.by===`while`?u(`automation.repeat.whileHint`,`Read before each round: if it is not true at the start, nothing runs. A condition that cannot be read ends the loop.`):u(`automation.repeat.untilHint`,`Read after each round, so the steps run at least once. A condition that cannot be read ends the loop.`)}),s(il,{hideRule:!0,context:`guard`,recipe:{when:d.when,actions:[]},devices:r,onChange:e=>l({...n,loop:{...d,when:e.when}})}),m!==null&&s(J,{variant:`warning`,message:m}),e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[e(`label`,{className:`w-28`,children:[s($,{children:u(`automation.repeat.max`,`At most (rounds)`)}),s(Y,{type:`number`,min:1,max:50,"data-testid":`repeat-max-${String(t)}`,value:String(d.maxIterations),onChange:e=>l({...n,loop:{...d,maxIterations:Oa(Number(e.target.value))}})})]}),e(`label`,{className:`w-40`,children:[s($,{children:u(`automation.repeat.wait`,`Pause between rounds (s)`)}),s(Y,{type:`number`,min:1,max:3600,"data-testid":`repeat-wait-${String(t)}`,value:d.waitS===void 0?``:String(d.waitS),placeholder:u(`automation.repeat.noWait`,`none`),onChange:e=>l({...n,loop:Aa(d,e.target.value===``?null:Number(e.target.value))})})]})]}),s(`p`,{className:`text-xs text-foreground-subtle`,children:u(`automation.repeat.maxHint`,`A loop that reaches its maximum stops there, is marked in the run, and the run goes on.`)})]}),d.by===`forEach`&&e(`div`,{className:`space-y-1`,children:[s(On,{multiple:!0,pick:`device`,maxItems:50,value:d.target.ids.map(e=>({deviceId:e})),onChange:e=>l({...n,loop:{...d,target:{kind:`devices`,ids:e.map(e=>e.deviceId)}}})}),s(`p`,{className:`text-xs text-foreground-subtle`,children:u(`automation.repeat.forEachHint`,`One round per device, in this order. In a round the steps read the device as the variable "item".`)})]}),s($,{children:u(`automation.repeat.steps`,`Each time, run`)}),s(`div`,{className:`border-l-2 border-border-subtle pl-3`,"data-testid":`repeat-steps-${String(t)}`,children:s(Pl,{nested:!0,flowControl:!0,actions:n.steps,devices:r,depth:o+1,allowedKinds:Ao(o+1),maxSteps:10,...i===void 0?{}:{devicesState:i},..._===void 0?{}:{variables:_},...v===void 0?{}:{roundDevices:v},onChange:e=>l({...n,steps:e.filter(jo)})})})]})}function jl({index:t,step:n,devices:r,onChange:i}){let{t:a}=Q(),o={when:n.when,actions:[]},c=gl(n.when),l=Fa(n.timeoutS),u={s:a(`automation.waitUntil.unitSeconds`,`seconds`),min:a(`automation.waitUntil.unitMinutes`,`minutes`),h:a(`automation.waitUntil.unitHours`,`hours`)};return e(`div`,{className:`space-y-2`,children:[s(`p`,{className:`text-xs text-foreground-subtle`,children:a(`automation.waitUntil.hint`,`The run pauses here until this is true. A value that cannot be read is not "true": the run keeps waiting.`)}),s(il,{hideRule:!0,context:`guard`,recipe:o,devices:r,onChange:e=>i({...n,when:e.when})}),c!==null&&s(J,{variant:`warning`,message:c}),e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[e(`label`,{className:`w-24`,children:[s($,{children:a(`automation.waitUntil.timeout`,`At most`)}),s(Y,{type:`number`,min:1,"data-testid":`wait-until-timeout-${String(t)}`,value:String(l.value),onChange:e=>i({...n,timeoutS:Ia(Number(e.target.value),l.unit)})})]}),s(`div`,{className:`w-32`,children:s(A,{"data-testid":`wait-until-unit-${String(t)}`,"aria-label":a(`automation.waitUntil.unit`,`Unit`),value:l.unit,onChange:e=>i({...n,timeoutS:Ia(l.value,Pa(e.target.value)?e.target.value:l.unit)}),options:Ma.map(e=>({value:e,label:u[e]}))})}),e(`label`,{className:`min-w-56 flex-1`,children:[s($,{children:a(`automation.waitUntil.onTimeout`,`If it does not happen in time`)}),s(A,{"data-testid":`wait-until-on-timeout-${String(t)}`,value:n.onTimeout,onChange:e=>i({...n,onTimeout:e.target.value===`stop`?`stop`:`continue`}),options:[{value:`continue`,label:a(`automation.waitUntil.continue`,`Go on with the next step`)},{value:`stop`,label:a(`automation.waitUntil.stop`,`Stop the run as a failure`)}]})]})]})]})}var Ml=[{value:`command`,labelKey:`automation.actionList.kindCap`},{value:`action`,labelKey:`automation.actionList.kindAction`},{value:`wait`,labelKey:`automation.actionList.kindWait`},{value:`wait-until`,labelKey:`automation.actionList.kindWaitUntil`},{value:`set`,labelKey:`automation.actionList.kindSet`},{value:`stop`,labelKey:`automation.actionList.kindStop`},{value:`choose`,labelKey:`automation.actionList.kindChoose`},{value:`parallel`,labelKey:`automation.actionList.kindParallel`},{value:`repeat`,labelKey:`automation.actionList.kindRepeat`},{value:`code`,labelKey:`automation.actionList.kindCode`}],Nl=[`set`,`stop`,`choose`,`wait-until`,`parallel`,`repeat`];function Pl({actions:t,devices:n,devicesState:r=`answered`,allowedKinds:i,variables:a=[],stepTones:o,stepResults:c,nested:l=!1,flowControl:u=!1,maxSteps:d,roundDevices:f,depth:p=0,onChange:m}){let{t:h}=Q(),g=Ml.filter(e=>(i===void 0||i.includes(e.value))&&(u||!Nl.includes(e.value))),_=h(`automation.actionList.flowGuardHint`,`Checked when this step is reached. If it is false, or a state cannot be read, the step does nothing.`),v={up:h(`automation.actionList.runThisStepEarlier`,`Run this step earlier`),down:h(`automation.actionList.runThisStepLater`,`Run this step later`),atFirst:h(`automation.actionList.alreadyFirstStep`,`This step already runs first`),atLast:h(`automation.actionList.alreadyLastStep`,`This step already runs last`)};return e(`div`,{className:`space-y-2`,children:[t.length===0&&s(`p`,{className:`text-xs text-warning`,children:h(`automation.actionList.noActionsYetAnAutomation`,`No actions yet. An automation that does nothing is not an automation.`)}),t.map((i,d)=>e(`div`,{className:`space-y-2 rounded border p-3 ${o===void 0?`border-border`:_a(o[d]??`idle`)}`,children:[e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[s(X,{variant:`default`,children:d+1}),e(`label`,{className:`w-40`,children:[s($,{children:h(`automation.actionList.step`,`Step`)}),s(A,{"data-testid":`step-kind-${String(d)}`,value:i.kind,onChange:e=>m(Ja(t,d,qa(Fl(e.target.value)))),options:g.map(e=>({value:e.value,label:h(e.labelKey)}))})]}),e(`div`,{className:`ml-auto flex items-center gap-1`,children:[s(go,{move:{up:d===0?null:()=>m(Xa(t,d,d-1)),down:d===t.length-1?null:()=>m(Xa(t,d,d+1))},texts:v}),s(q,{variant:`ghost`,onClick:()=>m(Ya(t,d)),title:h(`automation.actionList.removeThisStep`,`Remove this step`),children:s(z,{className:`h-3.5 w-3.5`})})]})]}),i.kind===`wait`&&e(`label`,{className:`block w-32`,children:[s($,{children:h(`automation.actionList.seconds`,`Seconds`)}),s(Y,{type:`number`,min:0,max:3600,value:String(i.seconds),onChange:e=>m(Ja(t,d,{...i,seconds:Number(e.target.value)}))})]}),i.kind===`stop`&&e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[e(`label`,{className:`min-w-48 flex-1`,children:[s($,{children:h(`automation.actionList.stopReason`,`Reason`)}),s(Y,{"data-testid":`stop-reason-${String(d)}`,value:i.reason,maxLength:200,onChange:e=>m(Ja(t,d,{...i,reason:e.target.value}))})]}),e(`label`,{className:`w-48`,children:[s($,{children:h(`automation.actionList.stopOutcome`,`The run ends as`)}),s(A,{"data-testid":`stop-outcome-${String(d)}`,value:i.outcome,onChange:e=>m(Ja(t,d,{...i,outcome:e.target.value===`failed`?`failed`:`ok`})),options:[{value:`ok`,label:h(`automation.actionList.stopOk`,`A success`)},{value:`failed`,label:h(`automation.actionList.stopFailed`,`A failure`)}]})]})]}),i.kind===`set`&&s(kl,{index:d,vars:i.vars,onChange:e=>m(Ja(t,d,{...i,vars:e}))}),i.kind===`wait-until`&&s(jl,{index:d,step:i,devices:n,onChange:e=>m(Ja(t,d,e))}),i.kind===`repeat`&&s(Al,{index:d,step:i,devices:n,devicesState:r,variables:a,depth:p,...f===void 0?{}:{roundDevices:f},onChange:e=>m(Ja(t,d,e))}),i.kind===`parallel`&&e(`div`,{className:`space-y-2`,"data-testid":`parallel-steps-${String(d)}`,children:[s(`p`,{className:`text-xs text-foreground-subtle`,children:h(`automation.parallel.hint`,`These start together and the run goes on when all are done. If one fails, the run fails once the others finished.`)}),s(`div`,{className:`border-l-2 border-border-subtle pl-3`,children:s(Pl,{nested:!0,flowControl:!0,actions:i.steps,devices:n,devicesState:r,variables:a,allowedKinds:vo,depth:p+1,...f===void 0?{}:{roundDevices:f},maxSteps:5,onChange:e=>m(Ja(t,d,{...i,steps:e.filter(yo)}))})})]}),i.kind===`choose`&&s(bl,{index:d,step:i,devices:n,devicesState:r,variables:a,depth:p,...f===void 0?{}:{roundDevices:f},onChange:e=>m(Ja(t,d,e))}),!l&&(i.kind===`stop`||i.kind===`set`)&&s(vl,{when:i.if,devices:n,hint:_,onChange:e=>{let{if:n,...r}=i;m(Ja(t,d,e===void 0?r:{...r,if:e}))}}),i.kind===`code`&&e(`label`,{className:`block`,children:[s($,{children:h(`automation.actionList.code`,`Code`)}),s(Ln,{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:i.code,spellCheck:!1,onChange:e=>m(Ja(t,d,{kind:`code`,code:e.target.value}))}),s(`span`,{className:`mt-1 block text-xs text-foreground-subtle`,children:s(ir,{i18nKey:`automation.actionList.codeHint`,components:{code:s(`code`,{})}})})]}),i.kind===`command`&&s(Rr,{step:i,devices:n,variables:a,...f===void 0?{}:{roundDevices:f},onChange:e=>m(Ja(t,d,{...e,...i.continueOnError===!0?{continueOnError:!0}:{},...i.if===void 0?{}:{if:i.if},...i.else===void 0?{}:{else:i.else}}))}),i.kind===`action`&&s(po,{step:i,onChange:e=>m(Ja(t,d,{...e,...i.continueOnError===!0?{continueOnError:!0}:{}}))}),u&&(i.kind===`command`||i.kind===`action`)&&s(on,{"data-testid":`continue-on-error-${String(d)}`,checked:i.continueOnError===!0,label:h(`automation.actionList.continueOnError`,`Continue if this step fails`),"aria-label":h(`automation.actionList.continueOnError`,`Continue if this step fails`),onCheckedChange:e=>{let{continueOnError:n,...r}=i;m(Ja(t,d,e?{...r,continueOnError:!0}:r))}}),!l&&(i.kind===`wait`||i.kind===`command`)&&s(yl,{step:i,devices:n,devicesState:r,variables:a,onChange:e=>m(Ja(t,d,e))}),c?.[d]!==void 0&&s(ao,{step:c[d],deviceName:e=>n.find(t=>t.id===e)?.name??`#${String(e)}`})]},`${i.kind}-${String(d)}`)),e(`div`,{className:`flex items-center gap-2`,children:[e(q,{variant:`outline`,disabled:d!==void 0&&t.length>=d,onClick:()=>m([...t,qa(g[0]?.value??`command`)]),children:[s(j,{className:`h-4 w-4`}),` `,h(`automation.actionList.addStep`)]}),t.length>1&&s(`span`,{className:`text-xs text-foreground-subtle`,children:h(`automation.actionList.stepsRunInOrderAnd`,`Steps run in order and stop at the first failure.`)})]})]})}function Fl(e){return Ml.find(t=>t.value===e)?.value??`command`}function Il(e,t){return e.map(e=>({name:e.name,hint:e.label??t(`flow.scope.type_${e.type}`,e.type)}))}function Ll(e,t){return _e(e).map(e=>({name:e.name,hint:t(`flow.scope.${e.hintKey??e.name}`,e.description)}))}function Rl(e){return e.some(e=>e.required===!0&&e.default===void 0)}function zl(e){return Object.fromEntries(e.map(e=>[e.name,e.default??(e.type===`boolean`?!1:void 0)]))}function Bl(e){return e===void 0?!1:typeof e==`string`?e.trim()!==``:typeof e==`number`?Number.isFinite(e):!0}function Vl(e,t){return e.filter(e=>e.required===!0&&!Bl(t[e.name])).map(e=>e.name)}function Hl(e,t){let n={};for(let r of e){let e=t[r.name];Bl(e)&&(n[r.name]=e)}return n}d();function Ul({variable:e,value:t,onChange:n}){let{t:r}=Q(),i=e.label??e.name;return e.type===`number`?s(zr,{"aria-label":i,value:typeof t==`number`?t:void 0,onValue:e=>n(e??void 0)}):e.type===`boolean`?s(Br,{widthClass:`w-28`,"aria-label":i,value:t===!0?`yes`:`no`,onChange:e=>n(e.target.value===`yes`),options:[{value:`yes`,label:r(`common.yes`,`Yes`)},{value:`no`,label:r(`common.no`,`No`)}]}):e.type===`select`?s(Br,{widthClass:`w-48`,"aria-label":i,value:typeof t==`string`?t:``,onChange:e=>n(e.target.value===``?void 0:e.target.value),options:[{value:``,label:r(`actions.editor.runDialog.choose`,`Choose…`)},...(e.options??[]).map(e=>({value:e,label:e}))]}):s(Y,{"aria-label":i,value:typeof t==`string`?t:``,onChange:e=>n(e.target.value)})}function Wl({actionName:t,variables:n,running:r,onRun:i,onCancel:a}){let{t:o}=Q(),[c,u]=l(()=>zl(n)),d=Vl(n,c);return s(Ft,{open:!0,onOpenChange:e=>!e&&a(),children:e(Kn,{"aria-label":o(`actions.editor.runDialog.title`,`Run {{name}}`,{name:t}),children:[e(Et,{children:[s(Xt,{children:o(`actions.editor.runDialog.title`,`Run {{name}}`,{name:t})}),s(ht,{children:o(`actions.editor.runDialog.description`,`Give the variables this run should use.`)})]}),s(`div`,{className:`space-y-3`,"data-testid":`run-variables-form`,children:n.map(t=>e(`label`,{className:`block space-y-1`,children:[e(`span`,{className:`text-xs text-foreground-subtle`,children:[t.label??t.name,t.required===!0?` *`:``]}),s(Ul,{variable:t,value:c[t.name],onChange:e=>u({...c,[t.name]:e})})]},t.name))}),e(Zt,{className:`flex flex-wrap gap-2`,children:[s(q,{variant:`ghost`,onClick:a,children:o(`common.cancel`,`Cancel`)}),e(q,{disabled:r||d.length>0,onClick:()=>i(Hl(n,c)),children:[r?s(S,{className:`h-4 w-4 animate-spin`}):s(O,{className:`h-4 w-4`}),` `,o(`actions.editor.runNow`,`Run now`)]})]})]})})}var Gl=[`number`,`string`,`boolean`,`select`];function Kl(e,t){return{name:e.name,...e.label===void 0?{}:{label:e.label},type:t,...t===`select`?{options:e.options??[`option`]}:{}}}function ql(e,t){let n=t.split(`,`).map(e=>e.trim()).filter(e=>e!==``),r=e.default!==void 0&&typeof e.default==`string`&&n.includes(e.default),{default:i,...a}=e;return{...r?e:a,options:n.length===0?[`option`]:n}}function Jl(e,t){let{default:n,...r}=e;return t===null?r:{...r,default:t}}function Yl(e,t){let{label:n,...r}=e;return t.trim()===``?r:{...r,label:t}}function Xl({variables:t,onChange:n,onRename:r}){let{t:i}=Q(),a=e=>{switch(e){case`number`:return i(`actions.variables.typeNumber`,`number`);case`string`:return i(`actions.variables.typeText`,`text`);case`boolean`:return i(`actions.variables.typeBoolean`,`yes / no`);default:return i(`actions.variables.typeSelect`,`select`)}},o=(e,r)=>n(t.map((t,n)=>n===e?r:t));return s(zt,{headingId:`vars-heading`,title:i(`actions.variables.title`,`Variables`),icon:ut,actions:e(q,{variant:`outline`,size:`sm`,onClick:()=>n([...t,dr(t)]),children:[s(j,{className:`h-4 w-4`}),` `,i(`actions.variables.add`,`Variable`)]}),children:e(`div`,{className:`space-y-3 p-3`,children:[t.map((c,l)=>e(`div`,{className:`grid gap-2 sm:grid-cols-[1fr_1fr_8rem_1fr_1.2fr_auto] sm:items-end`,"data-testid":`variable-row`,children:[e(`label`,{className:`space-y-1`,children:[s(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.name`,`Name`)}),s(Y,{"aria-label":i(`actions.variables.nameAria`,`Variable name`),value:c.name,"aria-invalid":!fr(c.name),onChange:e=>r(l,e.target.value)})]}),e(`label`,{className:`space-y-1`,children:[s(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.label`,`Label`)}),s(Y,{"aria-label":i(`actions.variables.label`,`Label`),value:c.label??``,onChange:e=>o(l,Yl(c,e.target.value))})]}),e(`label`,{className:`space-y-1`,children:[s(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.type`,`Type`)}),s(Br,{widthClass:`w-full`,"aria-label":i(`actions.variables.type`,`Type`),value:c.type,options:Gl.map(e=>({value:e,label:a(e)})),onChange:e=>{let t=Gl.find(t=>t===e.target.value);t!==void 0&&o(l,Kl(c,t))}})]}),e(`label`,{className:`space-y-1`,children:[s(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.default`,`Default`)}),s(Zl,{variable:c,onChange:e=>o(l,Jl(c,e))})]}),e(`label`,{className:`space-y-1`,children:[s(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.options`,`Options`)}),s(Y,{"aria-label":i(`actions.variables.options`,`Options`),value:(c.options??[]).join(`, `),disabled:c.type!==`select`,placeholder:i(`actions.variables.optionsHint`,`Only for a select`),onChange:e=>o(l,ql(c,e.target.value))})]}),s(q,{variant:`ghost`,"aria-label":i(`actions.variables.remove`,`Remove variable`),onClick:()=>n(t.filter((e,t)=>t!==l)),children:s(z,{className:`h-4 w-4`})})]},`${String(l)}`)),s(`p`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.hint`,`Callers can override a variable. In a step, the {x} button puts one in an argument.`)})]})})}function Zl({variable:e,onChange:t}){let{t:n}=Q(),r=n(`actions.variables.default`,`Default`);if(e.type===`number`)return s(zr,{"aria-label":r,value:typeof e.default==`number`?e.default:void 0,onValue:t});if(e.type===`boolean`||e.type===`select`){let i=e.type===`boolean`?[{value:`true`,label:n(`common.yes`,`Yes`)},{value:`false`,label:n(`common.no`,`No`)}]:(e.options??[]).map(e=>({value:e,label:e}));return s(Br,{widthClass:`w-full`,"aria-label":r,value:e.default===void 0?``:String(e.default),options:[{value:``,label:n(`actions.variables.noDefault`,`None`)},...i],onChange:n=>{n.target.value===``?t(null):t(e.type===`boolean`?n.target.value===`true`:n.target.value)}})}return s(Y,{"aria-label":r,value:typeof e.default==`string`?e.default:``,onChange:e=>t(e.target.value===``?null:e.target.value)})}d();var Ql=5e3;function $l(e){return e.kind===`command`||e.kind===`wait`}function eu(e){return e instanceof Error?e.message:String(e)}function tu(){let{t:e}=Q();return t=>{switch(t.kind){case`name`:return e(`actions.editor.problemName`,`Give the action a name.`);case`no-steps`:return e(`actions.editor.problemNoSteps`,`Add at least one step.`);case`undeclared`:return e(`actions.editor.problemUndeclared`,`A step uses {{name}}, which is not declared under Variables.`,{name:t.name});case`duplicate`:return e(`actions.editor.problemDuplicate`,`The variable {{name}} is declared twice.`,{name:t.name});case`bad-name`:return e(`actions.editor.problemBadName`,`The variable name "{{name}}" must start with a letter and use letters, digits or _.`,{name:t.name});default:return t.message}}}function nu({entry:t,onClose:n,onSaved:a,onQuickEdit:o,preset:u=null}){let{t:d}=Q(),f=p(),m=ee(),g=Hr(),_=tu(),[v,y]=l(()=>hr(t)),b=JSON.stringify(t?.tags??[]),x=t?.name;c(()=>{x!==void 0&&y(e=>({...e,name:x,tags:JSON.parse(b)}))},[x,b]);let S=r(!1);c(()=>{if(t!==null||u!==`trigger-alarm`||S.current)return;let e=g.find(e=>e.type===we.AlarmPanel);e!==void 0&&(S.current=!0,y(gr(e.id,d(`actions.editor.triggerAlarmName`,`Trigger the alarm`))))},[g,t,u,d]);let[C,w]=l(null),[T,E]=l(!1),D=t!==null&&t.readOnly,k=()=>{f.invalidateQueries({queryKey:[[`actions`]]})},A=Lt({onSuccess:e=>{k(),a(e.action.id)}}),j=Gn({onSuccess:k}),M=Bt({onSuccess:()=>{k(),n()}}),N=Nt({onSuccess:k}),P=xt({actionId:t?.id??`none`},{enabled:t!==null,refetchInterval:Ql}),F=P.data?.traces.find(e=>e.runId===C)??null,I=i(()=>F===null?null:Ji(F),[F]),L=i(()=>F===null?null:ea(F).steps,[F]),R=pr(v),B=i(()=>Il(v.variables,d),[v.variables,d]),V=A.isPending||j.isPending,te=A.error??j.error??M.error??N.error,H=Rl(t?.variables??[]),W=()=>{R.ok&&(t===null?A.mutate({action:R.input}):j.mutate({actionId:t.id,action:R.input}))},G=e(h,{children:[!R.ok&&!D&&v.name!==``&&s(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:_(R.reason)}),te!==null&&s(J,{message:eu(te)})]});return e(h,{children:[e(Bi,{testId:`action-editor`,icon:U,title:t===null?d(`actions.list.new`,`New action`):t.name,badges:s(X,{variant:D?`info`:`primary`,children:D?t?.addonId??``:d(`actions.source.internal`,`Internal`)}),onClose:n,onQuickEdit:D?void 0:o,onSave:D?void 0:W,saveDisabled:!R.ok,saving:V,notices:G,footerActions:e(h,{children:[t!==null&&e(q,{variant:`outline`,disabled:N.isPending,onClick:()=>H?E(!0):N.mutate({actionId:t.id}),children:[s(O,{className:`h-4 w-4`}),` `,d(`actions.editor.runNow`,`Run now`)]}),t!==null&&!D&&e(q,{variant:`ghost`,disabled:M.isPending,onClick:()=>{m({title:d(`actions.editor.deleteTitle`,`Delete this action?`),message:d(`actions.editor.deleteMessage`,`{{name}} will be deleted, and removed from every camera that links it.`,{name:t.name}),confirmLabel:d(`common.delete`,`Delete`),variant:`danger`}).then(e=>{e&&M.mutate({actionId:t.id})})},children:[s(z,{className:`h-4 w-4`}),` `,d(`common.delete`,`Delete`)]})]}),side:s(ga,{traces:t===null?[]:P.data?.traces,selectedId:C,onSelect:w}),children:[s(Y,{"aria-label":d(`actions.editor.name`,`Name`),className:`max-w-xs`,value:v.name,disabled:D,placeholder:d(`actions.editor.namePlaceholder`,`What this action does`),onChange:e=>y({...v,name:e.target.value})}),D?s(`p`,{className:`rounded-md border border-border bg-surface p-3 text-sm text-foreground-muted`,children:d(`actions.editor.readOnly`,`This action is declared by {{addon}}. Edit it there; you can run it from here.`,{addon:t?.addonId??``})}):e(h,{children:[s(Xl,{variables:v.variables,onChange:e=>y({...v,variables:e}),onRename:(e,t)=>y(mr(v,e,t))}),s(ba,{step:`steps`,title:d(`actions.editor.steps`,`Steps`),trace:I===null?null:I.thenBlock,children:s(Pl,{actions:v.steps,devices:g,allowedKinds:[`command`,`wait`],stepTones:I===null?void 0:v.steps.map((e,t)=>Yi(I,t)??`idle`),stepResults:L===null?void 0:v.steps.map((e,t)=>L.find(e=>e.index===t)),variables:B,onChange:e=>y({...v,steps:e.filter($l)})})})]})]}),T&&t!==null&&s(Wl,{actionName:t.name,variables:t.variables??[],running:N.isPending,onCancel:()=>E(!1),onRun:e=>{N.mutate({actionId:t.id,variables:e}),E(!1)}})]})}d();var ru=5e3;function iu(e){return e instanceof Error?e.message:String(e)}function au(){let{t:e}=Q();return t=>t.status.isRunning?{variant:`info`,label:e(`actions.status.running`,`Running`)}:t.status.lastError===null?t.status.lastRunAt===null?{variant:`neutral`,label:e(`actions.status.neverRan`,`Never ran`)}:{variant:`success`,label:e(`actions.status.ok`,`OK`)}:{variant:`danger`,label:e(`actions.status.failed`,`Failed`)}}function ou({createRequested:t=!1,onCreateConsumed:n}){let{t:r}=Q(),[a]=$n(),o=p(),u=au(),{state:d,openNew:f,openEdit:m,close:g}=En({editKey:`action`,newKey:`new`}),_=Dt({},{refetchInterval:ru}),v=Nt({onSuccess:()=>void o.invalidateQueries({queryKey:[[`actions`]]})}),[y,b]=l(null),x=Gn({onSuccess:()=>{b(null),o.invalidateQueries({queryKey:[[`actions`]]})}});c(()=>{t&&(f(),n?.())},[t,n,f]);let S=_.data??[],C=d.mode===`edit`?S.find(e=>e.id===d.id)??null:null,w=i(()=>[{key:`name`,header:r(`actions.list.name`,`Name`),render:e=>s(`span`,{className:`font-medium`,children:e.name}),sortValue:e=>e.name},{key:`source`,header:r(`actions.list.source`,`Source`),render:e=>e.readOnly?s(X,{variant:`info`,children:e.addonId}):s(X,{variant:`primary`,children:r(`actions.source.internal`,`Internal`)}),sortValue:e=>e.addonId},{key:`lastRun`,header:r(`actions.list.lastRun`,`Last run`),render:e=>e.status.lastRunAt===null?s(`span`,{className:`text-foreground-subtle`,children:`-`}):or(e.status.lastRunAt),sortValue:e=>e.status.lastRunAt},{key:`status`,header:r(`actions.list.status`,`Status`),render:e=>{let t=u(e);return s(`span`,{title:e.status.lastError??void 0,children:s(X,{variant:t.variant,children:t.label})})},notSortableReason:r(`actions.list.statusNotSortable`,`Derived from the latest run`)},{key:`run`,align:`right`,render:t=>e(`span`,{className:`inline-flex items-center justify-end gap-1`,children:[!t.readOnly&&s(rn,{icon:B,size:`sm`,variant:`ghost`,"aria-label":r(`build.quickEdit.action`,`Quick edit`),"data-testid":`action-quick-edit-${t.id}`,onClick:e=>{e.stopPropagation(),b(t.id)}}),e(q,{variant:`outline`,size:`sm`,disabled:v.isPending||t.status.isRunning,"aria-label":r(`actions.list.runAria`,`Run {{name}}`,{name:t.name}),onClick:e=>{e.stopPropagation(),v.mutate({actionId:t.id})},children:[s(O,{className:`h-4 w-4`}),` `,r(`actions.list.run`,`Run`)]})]}),notSortableReason:r(`actions.list.runNotSortable`,`A control`)}],[v,u,r]),T=y===null?null:S.find(e=>e.id===y)??null,E=T===null?null:s(pi,{subject:zi(T),subjectKey:T.id,saving:x.isPending,error:x.error===null?null:iu(x.error),onSave:e=>{let t=Ii(T,e);t.ok&&x.mutate({actionId:T.id,action:t.input})},onClose:()=>{x.reset(),b(null)}});return d.mode===`closed`?e(`div`,{className:`space-y-3`,children:[s(`p`,{className:`text-xs text-foreground-subtle`,children:r(`actions.list.hint`,`Actions are things this installation can do. Run one here, link it to a camera, or use it in an automation.`)}),v.error!=null&&s(J,{message:iu(v.error)}),_.data===void 0?_.error==null?s(Un,{className:`h-24 w-full`}):s(J,{title:r(`actions.list.couldNotRead`,`Could not read the actions`),message:iu(_.error),onRetry:()=>void _.refetch()}):S.length===0?s(pt,{icon:U,title:r(`actions.list.emptyTitle`,`No actions yet`),description:r(`actions.list.emptyDescription`,`An action is a short list of commands, such as feeding the dog, that you can reuse.`),action:e(q,{onClick:f,children:[s(j,{className:`h-4 w-4`}),` `,r(`actions.list.new`,`New action`)]})}):e(h,{children:[_.error!=null&&s(J,{title:r(`actions.list.couldNotRead`,`Could not read the actions`),message:iu(_.error),onRetry:()=>void _.refetch()}),s(gn,{section:`actions`,getTags:si,searchText:ci,searchLabel:r(`actions.list.search`,`Search actions`),columns:w,rows:S,rowKey:e=>e.id,pageSize:25,maxBodyHeight:Ct,emptyMessage:r(`actions.list.emptyTitle`,`No actions yet`),onRowClick:e=>m(e.id)})]}),E]}):e(h,{children:[s(nu,{entry:C,onClose:g,onSaved:e=>{m(e),b(e)},onQuickEdit:C===null?void 0:()=>b(C.id),preset:d.mode===`new`?a.get(`preset`):null},C?.id??`new`),E]})}d();function su({code:t,error:n,canEject:r,ejecting:i,onEject:a}){let{t:o}=Q(),[c,u]=l(!1),d=ee(),f=async()=>{await d({title:o(`automation.generatedCodePanel.ejectToCodeThisCannot`,`Eject to code — this cannot be undone`),message:o(`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:o(`automation.generatedCodePanel.ejectToCode`,`Eject to code`),cancelLabel:o(`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(q,{variant:`ghost`,onClick:()=>u(!c),children:[s(c?at:k,{className:`h-4 w-4`}),o(`automation.generatedCodePanel.generatedCode`,`Generated code`)]}),s(`span`,{className:`text-xs text-foreground-subtle`,children:o(`automation.generatedCodePanel.derivedFromTheRecipeAbove`,`Derived from the recipe above — regenerated on every save, never edited here.`)}),e(q,{className:`ml-auto`,variant:`ghost`,disabled:!r||t===null||i,onClick:()=>void f(),title:r?o(`automation.generatedCodePanel.takePermanentOwnershipOfThis`,`Take permanent ownership of this code as a script`):o(`automation.generatedCodePanel.saveTheAutomationFirstThere`,`Save the automation first — there is no stored block to eject yet`),children:[s(ot,{className:`h-4 w-4`}),` `,o(`automation.generatedCodePanel.eject`)]})]}),c&&s(`div`,{className:`border-t border-border p-3`,children:t===null?s(`p`,{className:`text-xs text-warning`,children:n??o(`automation.generatedCodePanel.theRecipeIsNotComplete`,`The recipe is not complete enough to generate a block yet.`)}):s(Wt,{maxHeight:420,children:t})})]})}var cu=[`single`,`restart`,`queued`,`parallel`,`cooldown`],lu=2,uu=30;function du(e){return e.runMode??{mode:`single`}}function fu(e,t){let{runMode:n,...r}=e;return t.mode===`single`?r:{...r,runMode:t}}function pu(e){switch(e){case`queued`:return{mode:`queued`,max:lu};case`parallel`:return{mode:`parallel`,max:lu};case`cooldown`:return{mode:`cooldown`,minutes:uu};case`restart`:return{mode:`restart`};default:return{mode:`single`}}}function mu(e){return cu.find(t=>t===e)??`single`}function hu({value:t,onChange:n}){let{t:r}=Q(),i={single:r(`flow.runMode.single`,`Skip it`),restart:r(`flow.runMode.restart`,`Restart the run`),queued:r(`flow.runMode.queued`,`Queue it`),parallel:r(`flow.runMode.parallel`,`Run at the same time`),cooldown:r(`flow.runMode.cooldown`,`Wait after a run`)},a={single:r(`flow.runMode.singleHint`,`A trigger that arrives during a run is dropped.`),restart:r(`flow.runMode.restartHint`,`The run in progress stops and a new one starts.`),queued:r(`flow.runMode.queuedHint`,`Triggers wait their turn, up to the limit.`),parallel:r(`flow.runMode.parallelHint`,`Runs overlap, up to the limit.`),cooldown:r(`flow.runMode.cooldownHint`,`No new run until this long after the last one began.`)};return e(`div`,{className:`flex flex-wrap items-end gap-3`,"data-testid":`run-mode`,children:[e(`label`,{className:`space-y-1`,children:[s(`span`,{className:`block text-xs text-foreground-subtle`,children:r(`flow.runMode.label`,`When it is already running`)}),s(Br,{widthClass:`w-56`,value:t.mode,options:cu.map(e=>({value:e,label:i[e]})),onChange:e=>n(pu(mu(e.target.value)))})]}),(t.mode===`queued`||t.mode===`parallel`)&&e(`label`,{className:`space-y-1`,children:[s(`span`,{className:`block text-xs text-foreground-subtle`,children:r(`flow.runMode.max`,`Up to`)}),s(zr,{className:`w-20`,"aria-label":r(`flow.runMode.max`,`Up to`),value:t.max,onValue:e=>{e!==null&&n({mode:t.mode,max:Math.round(e)})}})]}),t.mode===`cooldown`&&e(`label`,{className:`space-y-1`,children:[s(`span`,{className:`block text-xs text-foreground-subtle`,children:r(`flow.runMode.minutes`,`Minutes`)}),s(zr,{className:`w-20`,"aria-label":r(`flow.runMode.minutes`,`Minutes`),value:t.minutes,onValue:e=>{e!==null&&n({mode:`cooldown`,minutes:Math.round(e)})}})]}),s(`p`,{className:`basis-full text-xs text-foreground-subtle`,children:a[t.mode]})]})}var gu;function _u(){return gu??=K(We),gu}function vu(e,t=_u()){return ie(e,t)}d();var yu=`hub`,bu=5e3;function xu({existing:t,title:n,onQuickEdit:r,initialRecipe:a,saving:o,saveError:u,ejecting:d,onSave:f,onEject:p,onCancel:m,onSaveAsTemplate:g,savingAsTemplate:_=!1}){let{t:y}=Q(),[b,x]=l(t?.name??``),S=t?.name;c(()=>{S!==void 0&&x(S)},[S]);let[C,w]=l(()=>Pc(a)),E=e=>w(Bo(e)),[D,O]=l(!1),[ee,k]=l(null),A=$t({blockId:t?.id??`none`},{enabled:t!==null,refetchInterval:bu}),j=A.data?.traces.find(e=>e.runId===ee)??null,M=i(()=>j===null?null:Ji(j),[j]),N=i(()=>Ll(C.when,y),[C.when,y]),P=i(()=>j===null?null:ta(j),[j]),F=i(()=>j===null?null:ea(j).steps,[j]),I=Hr(),L=se(C),R=i(()=>Su(C),[C]),z=i(()=>Cu(b.trim()===``?`Untitled automation`:b.trim(),C),[b,C]),B=pn().data,V=i(()=>R===null?Tc(C,B):null,[C,B,R]),te=b.trim()===``,H=te||L!==null||R!==null||V!==null||z.code===null;return s(Bi,{testId:`automation-editor`,icon:v,title:n,onClose:m,onQuickEdit:r,onSave:()=>{z.code!==null&&f({name:b.trim(),code:z.code,enabled:t?.enabled??!0,placement:yu,...t?.tags===void 0?{}:{tags:t.tags}})},saveDisabled:H,saving:o,notices:e(h,{children:[L!==null&&s(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:L}),L===null&&R!==null&&s(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:R}),L===null&&V!==null&&s(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,"data-testid":`automation-site-error`,children:V}),u!==null&&s(`p`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:u})]}),footerActions:e(h,{children:[e(q,{variant:`ghost`,onClick:()=>O(!D),disabled:t===null,title:t===null?y(`automation.automationEditor.logsAppearOnceTheAutomation`,`Logs appear once the automation has been saved and started`):y(`automation.automationEditor.showThisAutomationSProcess`,`Show this automation's process logs`),"data-testid":`automation-logs-toggle`,"aria-expanded":D,children:[s(T,{className:`h-4 w-4`}),` `,y(`common.logs`),` `,s(ft,{expanded:D})]}),g!==void 0&&s(q,{variant:`outline`,disabled:o||_||H,onClick:()=>g({name:b.trim(),recipe:C}),"data-testid":`automation-save-as-template`,children:y(`build.templates.saveAsTemplate`,`Save as template`)})]}),footerStatus:te&&s(X,{variant:`warning`,children:y(`automation.automationEditor.nameRequired`,`Name required`)}),side:s(ga,{traces:t===null?[]:A.data?.traces,selectedId:ee,onSelect:k}),children:e(Go,{when:C.when,children:[e(`label`,{className:`block max-w-md text-sm`,children:[s(`span`,{className:`text-foreground-subtle`,children:y(`automation.automationEditor.name`,`Name`)}),s(Y,{className:`mt-1`,value:b,onChange:e=>x(e.target.value),placeholder:y(`automation.automationEditor.whatThisAutomationDoes`,`What this automation does`)})]}),s(ba,{step:`when`,title:y(`automation.automationEditor.when`,`When`),trace:M===null?null:M.when,children:s(il,{recipe:C,devices:I,run:P,onChange:E})}),s(ba,{step:`then`,title:y(`automation.automationEditor.then`,`Then`),trace:M===null?null:M.thenBlock,hint:y(`automation.automationEditor.inThisOrderStoppingAt`,`In this order, stopping at the first failure.`),children:s(Pl,{flowControl:!0,actions:C.actions,devices:I,variables:N,stepTones:M===null?void 0:C.actions.map((e,t)=>Yi(M,t)??`idle`),stepResults:F===null?void 0:C.actions.map((e,t)=>F.find(e=>e.index===t)),onChange:e=>E(Za(C,e))})}),s(ba,{step:`mode`,title:y(`flow.runMode.title`,`Overlap`),trace:null,hint:y(`flow.runMode.hint`,`What happens when a trigger arrives mid-run.`),children:s(hu,{value:du(C),onChange:e=>E(fu(C,e))})}),s(su,{code:z.code,error:z.error,canEject:t!==null,ejecting:d,onEject:p}),D&&t!==null&&e(`div`,{className:`rounded border border-border`,"data-testid":`automation-logs-panel`,children:[s(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:s(ir,{i18nKey:`common.logsOf`,values:{id:Ze(t.id)},components:{code:s(`code`,{})}})}),s(kn,{addonId:Ze(t.id),maxHeight:`max-h-64`,showFilters:!1})]})]})})}function Su(e){let t=ne.safeParse(e);if(t.success)return null;let n=t.error.issues[0];return n===void 0?Z.t(`helpers.automationEditor.incomplete`):`${n.path.length===0?``:`${n.path.join(`.`)}: `}${n.message}`}function Cu(e,t){let n=vu(t);if(!n.ok)return{code:null,error:n.error};try{return{code:he({name:e,recipe:n.recipe}),error:null}}catch(e){return{code:null,error:e instanceof Error?e.message:String(e)}}}function wu(e){if(!e.enabled)return{tone:`idle`,label:Z.t(`helpers.coreBlockStatus.disabled`),detail:Z.t(`helpers.coreBlockStatus.disabledDetail`)};switch(e.status){case`running`:return{tone:`ok`,label:Z.t(`helpers.coreBlockStatus.running`),detail:Z.t(`helpers.coreBlockStatus.runningDetail`)};case`starting`:return{tone:`pending`,label:Z.t(`helpers.coreBlockStatus.starting`),detail:e.lastError??Z.t(`helpers.coreBlockStatus.startingDetail`)};case`failed`:return{tone:`error`,label:Z.t(`helpers.coreBlockStatus.failed`),detail:e.lastError??Z.t(`helpers.coreBlockStatus.failedDetail`)};default:return{tone:`error`,label:Z.t(`helpers.coreBlockStatus.notRunning`),detail:e.lastError??Z.t(`helpers.coreBlockStatus.notRunningDetail`)}}}function Tu(e){switch(e){case`ok`:return`success`;case`pending`:return`warning`;case`error`:return`danger`;default:return`default`}}function Eu(e,t){let n=e.find(e=>e.id===t.id);return n===void 0?t:n.updatedAt>=t.updatedAt?n:t}function Du(e){let t=e=>{let t=wu(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 Ou(e){if(e.length===0)return Z.t(`helpers.coreBlockStatus.noBlocks`);let t=e.filter(e=>wu(e).tone===`error`).length,n=e.filter(e=>wu(e).tone===`ok`).length,r=[Z.t(`helpers.coreBlockStatus.blocks`,{count:e.length})];return n>0&&r.push(Z.t(`helpers.coreBlockStatus.runningCount`,{count:n})),t>0&&r.push(Z.t(`helpers.coreBlockStatus.notRunningCount`,{count:t})),r.join(` · `)}var ku=3e4;function Au({block:t,logsOpen:n,unreadable:r,flagged:i=!1}){let a=_(),{t:o}=Q(),c=wu(t),l=xn(t.updatedAt,a);return e(`div`,{className:`min-w-0`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[s(`span`,{className:`truncate font-medium`,children:t.name}),s(X,{variant:Tu(c.tone),children:c.label}),i&&s(X,{variant:`warning`,"data-testid":`automation-flagged-badge`,children:o(`build.templates.flagged`,`Flagged`)}),l!==null&&s(`span`,{className:`text-xs text-foreground-subtle`,children:o(`common.edited`,{when:l})})]}),(c.tone===`error`||c.tone===`pending`)&&s(`p`,{className:`mt-0.5 text-xs text-foreground-subtle`,children:c.detail}),r!==null&&s(`p`,{className:`mt-0.5 text-xs text-warning`,children:o(`automation.editor.listUnreadable`,{reason:r})}),n&&e(`div`,{className:`mt-2 rounded border border-border`,children:[s(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:s(ir,{i18nKey:`common.logsOf`,values:{id:Ze(t.id)},components:{code:s(`code`,{})}})}),s(kn,{addonId:Ze(t.id),maxHeight:`max-h-64`,showFilters:!1})]})]})}var ju=2;function Mu(e){let t=[];if(be(e.when,e=>{Be(e)&&t.push(Ha(e.kind))}),t.length===0)return Fe(e.when)===0?``:Z.t(`automation.whenTree.stateOnly`);let n=[...new Set(t)],r=n.slice(0,ju).join(`, `),i=n.length-ju;return i>0?`${r} +${i}`:r}function Nu({recipe:e}){let{t}=Q();if(e===null)return s(`span`,{className:`text-foreground-subtle`,children:`-`});let n=Mu(e);return n===``?s(`span`,{className:`text-foreground-subtle`,children:t(`automation.automationList.noTrigger`,`No trigger`)}):s(`span`,{children:n})}function Pu({blockId:t}){let{t:n}=Q(),r=$t({blockId:t},{refetchInterval:ku});if(r.data===void 0)return r.error===null||r.error===void 0?s(Un,{className:`h-4 w-16`}):s(`span`,{className:`text-foreground-subtle`,children:n(`automation.automationList.lastRunUnknown`,`Unknown`)});let i=r.data.traces.findLast(e=>!e.outcome.startsWith(`skipped-`));if(i===void 0)return s(`span`,{className:`text-foreground-subtle`,children:n(`automation.automationList.neverRan`,`Never ran`)});let a=i.outcome===`failed`||i.outcome===`aborted`;return e(`span`,{className:`inline-flex items-center gap-2`,children:[or(i.lastAt),a&&s(X,{variant:`danger`,children:n(`automation.automationList.lastRunFailed`,`Failed`)})]})}function Fu({block:e,disabled:t,onToggle:n}){let{t:r}=Q();return s(`span`,{className:`inline-flex`,onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),children:s(on,{checked:e.enabled,disabled:t,onCheckedChange:n,"aria-label":e.enabled?r(`automation.automationList.disableNamed`,`Disable {{name}}`,{name:e.name}):r(`automation.automationList.enableNamed`,`Enable {{name}}`,{name:e.name})})})}function Iu({unreadable:e,onEdit:t,onQuickEdit:n,onToggleLogs:r,onDelete:i}){let{t:a}=Q();return s(`span`,{className:`inline-flex justify-end`,onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),children:s(Cn,{items:[{id:`edit`,label:a(`common.edit`,`Edit`),icon:B,disabled:e!==null,description:e===null?void 0:a(`automation.automationList.thisBlockCannotBeOpened`,`This block cannot be opened visually`),onClick:t},{id:`quick-edit`,label:a(`build.quickEdit.action`,`Quick edit`),icon:P,onClick:n},{id:`run`,label:a(`automation.automationList.runActions`,`Run actions`),icon:O,disabled:!0,description:a(`automation.automationList.runNotAvailable`,`Not available yet`),onClick:()=>void 0},{id:`logs`,label:a(`automation.automationList.logs`,`Logs`),icon:T,onClick:r},{id:`delete`,label:a(`common.delete`,`Delete`),icon:z,danger:!0,separatorBefore:!0,onClick:i}]})})}function Lu({onCreate:t}){let{t:n}=Q();return s(pt,{icon:v,title:n(`automation.automationList.noAutomationsYet`,`No automations yet.`),action:e(q,{onClick:t,"data-testid":`automation-empty-new`,children:[s(j,{className:`h-4 w-4`}),` `,n(`automation.automationList.newAutomation`,`New automation`)]})})}d();function Ru({open:t,onBlank:n,onTemplate:r,onClose:i}){let{t:a}=Q(),o=Wn({kind:`automation`},{enabled:t}),l=o.data!==void 0&&o.data.length===0;return c(()=>{t&&l&&n()},[t,l,n]),s(Ft,{open:t&&!l,onOpenChange:e=>!e&&i(),children:e(Kn,{width:`md`,placement:`sheet-on-mobile`,children:[s(Et,{children:s(Xt,{children:a(`build.templates.newAutomationTitle`,`New automation`)})}),e(qt,{className:`space-y-2`,"data-testid":`new-automation-chooser`,children:[s(q,{variant:`outline`,className:`h-auto w-full justify-start whitespace-normal py-2 text-left`,onClick:n,"data-testid":`new-automation-blank`,children:e(`span`,{className:`block`,children:[s(`span`,{className:`block font-medium`,children:a(`build.templates.blank`,`Blank`)}),s(`span`,{className:`block text-xs text-foreground-muted`,children:a(`build.templates.blankHint`,`Start from an empty trigger and steps.`)})]})}),o.data===void 0?s(Un,{className:`h-10 w-full`}):o.data.map(t=>s(q,{variant:`outline`,className:`h-auto w-full justify-start whitespace-normal py-2 text-left`,onClick:()=>r(t.id),"data-testid":`new-automation-template-${t.id}`,children:e(`span`,{className:`block`,children:[s(`span`,{className:`block font-medium`,children:t.name}),s(`span`,{className:`block text-xs text-foreground-muted`,children:ye.safeParse(t.payload).data?.description??a(`build.templates.fromTemplateHint`,`From a template — only its inputs to fill in.`)})]})},t.id))]})]})})}var zu=``;function Bu(e,t){if(e===null)return null;let n=t.roomId?.trim().toLowerCase();return[...e.byId.values()].filter(e=>(t.deviceType===void 0||e.type===t.deviceType)&&(n===void 0||e.location?.trim().toLowerCase()===n)).map(e=>e.id)}var Vu=[];function Hu(e,t){let n=yn(),r=e.kind===`devices`?e.ids:e.kind===`domain`?Bu(n,e)??Vu:Vu,i=Tr(r),a=e.kind===`domain`?n!==null&&(r.length===0||i.data!==void 0):i.data!==void 0,o=r.map(e=>{let n=t.find(t=>t.id===e)?.type;return{id:e,caps:i.data?.get(e)??[],...n===void 0?{}:{type:n}}});return{known:a,actions:a?e.kind===`domain`?Pr(o).filter(e=>!Xr(e)):Zr(o,e,{}):[]}}function Uu({target:t,value:n,onChange:r,devices:i,disabled:a=!1,testId:o=`template-action-select`}){let{t:c,i18n:l}=Q(),u=lr(l.language),{known:d,actions:f}=Hu(t,i),p=n===void 0?void 0:f.find(e=>e.id===n.actionId),m=p===void 0||n===void 0?{}:cr([p],n)?.values??sr(p),g=(e,n)=>{let i=f.find(t=>t.id===e);if(i===void 0){r(void 0);return}r(ur(i,t,n??sr(i)))},_=d?c(`build.templates.choose`,`Choose…`):c(`build.templates.readingActions`,`Reading what these devices can do…`),v=n===void 0?{value:zu,label:_}:{value:n.actionId,label:d?c(`build.templates.actionNotOffered`,`{{id}} (not offered)`,{id:n.actionId}):_};return e(h,{children:[s(A,{"data-testid":o,"aria-label":c(`build.templates.actionLabel`,`Action`),disabled:a||!d,value:n?.actionId??zu,onChange:e=>g(e.target.value,null),options:[...p===void 0?[v]:[],...f.map(e=>({value:e.id,label:e.label[u]}))]}),p!==void 0&&p.openArgs.length>0&&s(Lr,{action:p,deviceId:t.kind===`devices`&&t.ids.length===1?t.ids[0]??null:null,values:m,locale:u,variables:[],onChange:e=>g(p.id,e)})]})}function Wu({devices:e,...t}){let{i18n:n}=Q(),r=lr(n.language),i=t=>{let n=Jt(t.target),{known:i,actions:a}=Hu(t.target,e),o=a.find(e=>e.id===t.actionId);return{label:`${o?.label[r]??t.actionId} · ${n}`,warning:i&&o===void 0}};return s(an,{...t,useEntryLabel:i,renderEditor:t=>s(Uu,{...t,devices:e})})}function Gu(e){return Array.isArray(e)?e:[]}function Ku(e){return Gu(e).flatMap(e=>{let t=Me.safeParse(e);return t.success&&t.data.kind===`device-fired`?[t.data]:[]})}function qu(e){return Gu(e).flatMap(e=>{let t=it.safeParse(e);return t.success?[t.data]:[]})}function Ju(e){return e.length===0?void 0:e.map(e=>({...e}))}d();var Yu=`s`,Xu=60;function Zu(e){return e!==void 0&&e>=Xu&&e%Xu===0?`min`:Yu}function Qu({value:e,min:t,max:n,disabled:r=!1,"aria-label":i,onChange:a}){let[o,c]=l(()=>Zu(e));return s(gt,{quantity:`duration`,storedUnit:Yu,unit:o,value:e,disabled:r,...t===void 0?{}:{min:t},...n===void 0?{}:{max:n},...i===void 0?{}:{"aria-label":i},onChange:e=>{c(e.unit);try{a(Math.round(Sn(e,Yu).value))}catch{a(void 0)}}})}var $u=`hub`;function ed(e){switch(e.kind){case`number`:case`duration`:case`text`:case`select`:case`boolean`:return e.default;default:return}}function td(e){return{min:e.minRows??(e.optional===!0?0:1),max:e.maxRows??20}}function nd(e){let t={};for(let n of e.inputs){let e=ed(n);e!==void 0&&(t[n.key]=e)}return t}function rd(e){let t={};for(let n of e.inputs){if(n.kind===`group`){t[n.key]=Array.from({length:td(n).min},()=>nd(n));continue}let e=ed(n);e!==void 0&&(t[n.key]=e)}return t}function id(e){let t={};for(let n of e.inputs){if(n.kind===`group`){t[n.key]=Array.from({length:td(n).min},()=>rd(n));continue}let e=ed(n);e!==void 0&&(t[n.key]=e)}return t}function ad(e,t,n){let{[t]:r,...i}=e;return n===void 0?i:{...i,[t]:n}}function od(e,t){let n=e[t];return Array.isArray(n)?n.filter(e=>typeof e==`object`&&!!e&&!Array.isArray(e)):[]}function sd(e,t,n,r,i){let a=od(e,t).map((e,t)=>{if(t!==n)return e;let{[r]:a,...o}=e;return i===void 0?o:{...o,[r]:i}});return{...e,[t]:a}}function cd(e,t){let n=od(e,t.key);return n.length>=td(t).max?e:{...e,[t.key]:[...n,rd(t)]}}function ld(e,t,n){let r=od(e,t.key);return r.length<=td(t).min?e:{...e,[t.key]:r.filter((e,t)=>t!==n)}}function ud(e,t){let n=e[t];return Array.isArray(n)?n.filter(e=>typeof e==`object`&&!!e&&!Array.isArray(e)):[]}function dd(e,t){let n=od(e,t.groupKey)[t.index];return n===void 0?[]:ud(n,t.group.key)}function fd(e,t,n){return sd(e,t.groupKey,t.index,t.group.key,[...n])}function pd(e,t,n,r,i){return fd(e,t,dd(e,t).map((e,t)=>{if(t!==n)return e;let{[r]:a,...o}=e;return i===void 0?o:{...o,[r]:i}}))}function md(e,t){let n=dd(e,t);return n.length>=td(t.group).max?e:fd(e,t,[...n,nd(t.group)])}function hd(e,t,n){let r=dd(e,t);return r.length<=td(t.group).min?e:fd(e,t,r.filter((e,t)=>t!==n))}function gd(e,t){return e.filter(e=>e.input===t)}function _d(e,t){let n=new Set(t.map(e=>e.key));return e.filter(e=>e.input===void 0||!n.has(e.input.split(`.`)[0]??``))}function vd(e,t,n){let r=vu(t);if(!r.ok)return{ok:!1,problems:[{code:`invalid-recipe`,detail:r.error}]};try{return{ok:!0,recipe:r.recipe,input:{name:e,code:he({name:e,recipe:r.recipe}),enabled:n,placement:$u}}}catch(e){return{ok:!1,problems:[{code:`invalid-recipe`,detail:e instanceof Error?e.message:String(e)}]}}}function yd(e,t,n,r,i){let a=Ce(e,t,n);return a.ok?vd(r,a.recipe,i):a}function bd(e,t,n){return vd(t,ue(e),n)}d();var xd=2;function Sd(e){return typeof e==`number`?[e]:Array.isArray(e)?e.filter(e=>typeof e==`number`):[]}function Cd(e){let t=Xe.safeParse(e);return t.success?t.data:void 0}function wd(e){let t=fe.safeParse(e);return t.success?t.data:void 0}function Td({problems:e}){return e.map(e=>s(`p`,{role:`alert`,className:`basis-full text-xs text-danger`,children:e.detail},`${e.input??``}|${e.detail}`))}function Ed({payload:e,values:t,problems:n,disabled:r=!1,onChange:i}){return s(`div`,{className:`space-y-4`,"data-testid":`template-inputs-form`,children:e.inputs.map(e=>e.kind===`group`?s(Od,{group:e,values:t,problems:n,disabled:r,onChange:i},e.key):s(Id,{input:e,siblingValues:t,address:e.key,problems:n,disabled:r,onChange:n=>i(ad(t,e.key,n))},e.key))})}function Dd({noun:t,disabled:n,testId:r,onClick:i}){let{t:a}=Q();return e(q,{size:`sm`,variant:`outline`,disabled:n,onClick:i,"data-testid":r,children:[s(j,{className:`h-3.5 w-3.5`,"aria-hidden":!0}),t===void 0?a(`build.templates.addRow`,`Add row`):a(`build.templates.addNamed`,`Add {{noun}}`,{noun:t})]})}function Od({group:t,values:n,problems:r,disabled:i,onChange:a}){let o=od(n,t.key),c=td(t);return e(`section`,{className:`space-y-2`,"data-testid":`template-group-${t.key}`,children:[s(`h4`,{className:`text-sm font-medium text-foreground`,children:t.label}),s(Td,{problems:gd(r,t.key)}),o.map((e,l)=>s(Nd,{group:t,values:n,row:e,index:l,removable:o.length>c.min,problems:r,disabled:i,onChange:a},l)),s(Dd,{noun:t.rowLabel,disabled:i||o.length>=c.max,testId:`template-group-${t.key}-add`,onClick:()=>a(cd(n,t))})]})}function kd(e,t){let n=e.find(e=>e.kind===`device`);if(n===void 0)return;let r=Sd(t[n.key])[0];if(r===void 0)return;let i=e.find(e=>e.kind===`event`&&e.deviceInput===n.key);return{deviceId:r,event:i===void 0?void 0:Cd(t[i.key])}}function Ad(e,t){let n=e.inputs.filter(e=>e.kind!==`group`),r=n.flatMap(e=>e.kind===`entries`&&e.entry===`trigger`?Ku(t[e.key]).map(e=>({deviceId:e.deviceId,event:{eventIds:e.eventIds,sourceIds:e.sourceIds}})):[]);if(r.length>0)return r;let i=kd(n,t);if(i!==void 0)return[i];for(let n of e.inputs){if(n.kind!==`group`)continue;let e=ud(t,n.key).map(e=>kd(n.inputs,e)).filter(e=>e!==void 0);if(e.length>0)return e}return[]}function jd({entry:e}){let t=yt(e.deviceId,`compact`),n=e.event!==void 0,r=_n({deviceId:e.deviceId,capName:As},{enabled:n}),i=js({status:r.status,data:r.data}),a=n&&i.kind===`known`?i.vocabulary:[],o=e.event?.sourceIds?.[0],s=e.event?.eventIds?.[0],c=a.find(e=>e.source?.id===o)?.source?.label,l=a.find(e=>e.id===s&&(o===void 0||e.source?.id===o))?.label;return[t,o===void 0?void 0:c??o,s===void 0?void 0:l??s].filter(e=>e!==void 0).join(` · `)}function Md({group:t,row:r}){let{t:i}=Q(),a=Ad(t,r);if(a.length===0)return t.rowLabel===void 0?i(`build.templates.newRow`,`New row`):i(`build.templates.newNamed`,`New {{noun}}`,{noun:t.rowLabel});let o=a.slice(0,xd),c=a.length-o.length;return e(h,{children:[o.map((t,r)=>e(n,{children:[r>0&&`, `,s(jd,{entry:t})]},r)),c>0&&` +${String(c)}`]})}function Nd({group:t,values:n,row:r,index:i,removable:a,problems:o,disabled:c,onChange:l}){let{t:u}=Q(),d=`${t.key}.${String(i)}`,f=t.rowLabel;return e(`div`,{className:`space-y-3 rounded-md border border-border bg-surface p-3`,"data-testid":`template-group-${t.key}-row`,children:[e(`div`,{className:`flex items-center justify-between gap-2`,children:[s(`span`,{className:`min-w-0 truncate text-sm font-medium text-foreground`,"data-testid":`template-group-${t.key}-summary`,children:s(Md,{group:t,row:r})}),s(rn,{icon:z,size:`sm`,variant:`ghost`,"aria-label":f===void 0?u(`build.templates.removeRow`,`Remove row`):u(`build.templates.removeNamed`,`Remove {{noun}}`,{noun:f}),disabled:c||!a,onClick:()=>l(ld(n,t,i))})]}),t.inputs.map(e=>e.kind===`group`?s(Pd,{at:{groupKey:t.key,index:i,group:e},rows:ud(r,e.key),address:`${d}.${e.key}`,values:n,problems:o,disabled:c,onChange:l},e.key):s(Id,{input:e,siblingValues:r,address:`${d}.${e.key}`,problems:o,disabled:c,onChange:r=>l(sd(n,t.key,i,e.key,r))},e.key))]})}function Pd({at:t,rows:n,address:r,values:i,problems:a,disabled:o,onChange:c}){let{t:l}=Q(),u=t.group,d=td(u),f=u.rowLabel;return e(`div`,{className:`space-y-2`,"data-testid":`template-nested-${r}`,children:[s(`h5`,{className:`text-xs font-medium text-foreground-muted`,children:u.label}),s(Td,{problems:gd(a,r)}),n.map((p,m)=>{let h=`${r}.${String(m)}`;return e(`div`,{className:`flex flex-wrap items-start gap-2`,"data-testid":`template-nested-${r}-row`,children:[u.inputs.map(e=>s(Fd,{input:e,row:p,address:`${h}.${e.key}`,disabled:o,onChange:n=>c(pd(i,t,m,e.key,n))},e.key)),s(rn,{icon:w,size:`sm`,variant:`ghost`,className:`mt-5`,"aria-label":f===void 0?l(`build.templates.removeRow`,`Remove row`):l(`build.templates.removeNamed`,`Remove {{noun}}`,{noun:f}),disabled:o||n.length<=d.min,onClick:()=>c(hd(i,t,m))}),s(Td,{problems:u.inputs.flatMap(e=>gd(a,`${h}.${e.key}`))})]},m)}),s(Dd,{noun:f,disabled:o||n.length>=d.max,testId:`template-nested-${r}-add`,onClick:()=>c(md(i,t))})]})}function Fd({input:t,row:n,address:r,disabled:i,onChange:a}){let o=s(Rd,{input:t,value:n[t.key],siblingValues:n,address:r,disabled:i,inline:!0,onChange:a});return t.kind===`event`||t.kind===`action`||t.kind===`boolean`?o:e(`div`,{className:`min-w-[13rem] flex-1`,children:[s($,{children:t.label}),o]})}function Id({input:e,siblingValues:t,address:n,problems:r,disabled:i,onChange:a}){let o=gd(r,n),c=o.length===0?void 0:o.map(e=>e.detail).join(` `),l=t[e.key];return s(zn,{label:e.label,required:e.optional!==!0,...e.description===void 0?{}:{description:e.description},...c===void 0?{}:{error:c},className:`min-w-0`,children:s(Rd,{input:e,value:l,siblingValues:t,address:n,disabled:i,onChange:a})})}function Ld(e,t,n,r,i,a){let o=e.maxItems;return e.entry===`trigger`?s(Vn,{testId:`template-input-${r}`,recentKey:`template-input-${e.key}`,disabled:n,...o===void 0?{}:{maxItems:o},value:Ku(t),onChange:e=>a(Ju(e))}):s(Wu,{testId:`template-input-${r}`,recentKey:`template-input-${e.key}`,disabled:n,devices:i,...o===void 0?{}:{maxItems:o},value:qu(t),onChange:e=>a(Ju(e))})}function Rd({input:e,value:t,siblingValues:n,address:r,disabled:i,inline:a=!1,onChange:o}){let{t:c}=Q(),l=Hr();switch(e.kind){case`device`:{let n=e.filter?.capability===void 0?{}:{requires:{caps:[e.filter.capability]}},a=e.filter?.role===void 0?{}:{fixedTypes:[e.filter.role]};if(e.multiple===!0)return s(On,{pick:`device`,multiple:!0,...n,...a,recentKey:`template-input-${e.key}`,testId:`template-input-${r}`,disabled:i,value:Sd(t).map(e=>({deviceId:e})),onChange:e=>{let t=e.map(e=>e.deviceId);o(t.length===0?void 0:t)}});let c=Sd(t)[0];return s(On,{pick:`device`,...n,...a,recentKey:`template-input-${e.key}`,testId:`template-input-${r}`,disabled:i,value:c===void 0?null:{deviceId:c},onChange:e=>o(e===null?void 0:e.deviceId)})}case`event`:{let i=Sd(n[e.deviceInput])[0];if(i===void 0)return s(`p`,{className:`min-w-[11rem] flex-1 py-1.5 text-xs text-foreground-subtle`,"data-testid":`template-input-${r}`,children:c(`build.templates.pickDeviceFirst`,`Pick the device first.`)});let l=Cd(t),u=s(Bs,{leaf:{kind:`device-fired`,deviceId:i,...l?.eventIds===void 0?{}:{eventIds:l.eventIds},...l?.sourceIds===void 0?{}:{sourceIds:l.sourceIds},...l?.kinds===void 0?{}:{kinds:l.kinds}},hideDevice:!0,onChange:e=>{let t={...e.eventIds===void 0?{}:{eventIds:e.eventIds},...e.sourceIds===void 0?{}:{sourceIds:e.sourceIds},...e.kinds===void 0?{}:{kinds:e.kinds}};o(Xe.safeParse(t).success?t:void 0)}});return a?u:s(`div`,{className:`flex flex-wrap items-end gap-2`,"data-testid":`template-input-${r}`,children:u})}case`action`:{let a=e.deviceInput===void 0?[]:Sd(n[e.deviceInput]);if(e.deviceInput!==void 0&&a.length===0)return s(`p`,{className:`min-w-[11rem] flex-1 py-1.5 text-xs text-foreground-subtle`,"data-testid":`template-input-${r}`,children:c(`build.templates.pickDevicesFirst`,`Pick the devices first.`)});let u={kind:`devices`,ids:[...a]},d=wd(t);return s(Uu,{target:u,devices:l,value:d===void 0?void 0:{kind:`command`,target:u,actionId:d.actionId,...d.args===void 0?{}:{args:d.args}},disabled:i,testId:`template-input-${r}`,onChange:e=>o(e===void 0?void 0:{actionId:e.actionId,...e.args===void 0?{}:{args:e.args}})})}case`entries`:return Ld(e,t,i,r,l,o);case`duration`:return s(`span`,{"data-testid":`template-input-${r}`,children:s(Qu,{value:typeof t==`number`?t:void 0,disabled:i,...e.min===void 0?{}:{min:e.min},...e.max===void 0?{}:{max:e.max},"aria-label":e.label,onChange:o})});case`number`:return s(Y,{type:`number`,"data-testid":`template-input-${r}`,disabled:i,value:typeof t==`number`?String(t):``,...e.min===void 0?{}:{min:e.min},...e.max===void 0?{}:{max:e.max},onChange:e=>{let t=e.target.value===``?void 0:Number(e.target.value);o(t===void 0||Number.isNaN(t)?void 0:t)}});case`text`:return s(Y,{"data-testid":`template-input-${r}`,disabled:i,value:typeof t==`string`?t:``,...e.maxLength===void 0?{}:{maxLength:e.maxLength},onChange:e=>o(e.target.value===``?void 0:e.target.value)});case`select`:return s(A,{"data-testid":`template-input-${r}`,disabled:i,value:typeof t==`string`?t:``,options:[...e.optional===!0||typeof t!=`string`?[{value:``,label:c(`build.templates.choose`,`Choose…`)}]:[],...e.options.map(e=>({value:e.value,label:e.label}))],onChange:e=>o(e.target.value===``?void 0:e.target.value)});case`boolean`:return s(on,{"data-testid":`template-input-${r}`,disabled:i,checked:t===!0,onCheckedChange:e=>o(e),label:e.label});case`time-window`:return s(zd,{testId:`template-input-${r}`,value:t,disabled:i,onChange:o})}}function zd({testId:t,value:n,disabled:r,onChange:i}){let{t:a}=Q(),o=de.safeParse(n),c=o.success?{kind:`time-is`,...o.data}:null;return e(`div`,{className:`flex flex-col gap-2`,"data-testid":t,children:[s(on,{"data-testid":`${t}-limit`,disabled:r,checked:c!==null,onCheckedChange:e=>{if(!e)return i(void 0);let{kind:t,...n}=bc({kind:`time-is`},!0);i(n)},label:a(`build.templates.timeWindow.limit`,`Only run at certain times`)}),c===null?null:s(`fieldset`,{disabled:r,className:`contents`,children:s(Dc,{leaf:c,onChange:e=>{if(e.days?.length===0)return;let{kind:t,...n}=e;i(n)}})})]})}d();function Bd({templateId:t,templateName:n,payload:r,existing:a,currentRecipe:o,initialName:c,initialValues:u,storedProblems:d,saving:f,saveError:p,onSave:m,onCancel:h}){let{t:g}=Q(),_=ee(),[v,y]=l(c),[b,x]=l(u),[C,w]=l(!1),T=a?.enabled??!0,E=d.length>0,D=i(()=>r===null?null:yd(t,r,b,v.trim(),T),[r,t,b,v,T]),O=C&&D!==null&&!D.ok?D.problems:[],k=v.trim()===``,A=()=>{w(!0),!(D===null||!D.ok||k)&&m(D.input)},j=async()=>{if(o===null||!await _({title:g(`build.templates.convertTitle`,`Convert to a free automation?`),message:g(`build.templates.convertMessage`,`{{name}} keeps running as it is, but stops following the template.`,{name:v.trim()===``?c:v.trim()}),confirmLabel:g(`build.templates.convert`,`Convert to a free automation`)}))return;let e=bd(o,v.trim()===``?c:v.trim(),T);e.ok&&m(e.input)};return e(`div`,{className:`space-y-4`,"data-testid":`template-instance-editor`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2 text-xs text-foreground-subtle`,children:[s(`span`,{children:n===null?g(`build.templates.templateGone`,`The template of this automation no longer exists.`):g(`build.templates.fromTemplate`,`From the template {{name}}`,{name:n})}),E&&s(X,{variant:`warning`,"data-testid":`template-flagged-badge`,children:g(`build.templates.flagged`,`Flagged`)})]}),E&&e(`div`,{className:`space-y-1 rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,"data-testid":`template-flagged-problems`,children:[s(`p`,{className:`font-medium`,children:g(`build.templates.flaggedExplain`,`The template changed and these values no longer fit. The automation keeps running as it last did.`)}),s(`ul`,{className:`list-disc space-y-0.5 pl-4`,children:d.map(e=>s(`li`,{children:e.detail},`${e.input??``}:${e.detail}`))})]}),e(`label`,{className:`block max-w-md text-sm`,children:[s(`span`,{className:`text-foreground-subtle`,children:g(`automation.automationEditor.name`,`Name`)}),s(Y,{className:`mt-1`,value:v,onChange:e=>y(e.target.value),"data-testid":`template-instance-name`})]}),r!==null&&s(Ed,{payload:r,values:b,problems:O,disabled:f,onChange:x}),r!==null&&_d(O,r.inputs).map(e=>s(`p`,{role:`alert`,className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:e.detail},e.detail)),p!==null&&s(`p`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:p}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[r!==null&&e(q,{onClick:A,disabled:f||k,"data-testid":`template-instance-save`,children:[f&&s(S,{className:`h-4 w-4 animate-spin`}),` `,g(`common.save`,`Save`)]}),a!==null&&o!==null&&s(q,{variant:`outline`,onClick:()=>void j(),disabled:f,"data-testid":`template-instance-convert`,children:g(`build.templates.convert`,`Convert to a free automation`)}),s(q,{variant:`ghost`,onClick:h,disabled:f,children:g(`common.close`,`Close`)}),k&&s(X,{variant:`warning`,children:g(`automation.automationEditor.nameRequired`,`Name required`)})]})]})}function Vd({templateId:e,existing:t,recipe:n,saving:r,saveError:i,onSave:a,onCancel:o}){let{t:c}=Q(),l=Bn({id:e});if(l.status===`error`)return s(J,{title:c(`build.templates.loadFailed`,`Could not read the template`),message:l.error.message,onRetry:()=>void l.refetch()});if(l.data===void 0)return s(Un,{className:`h-24 w-full`});let u=l.data,d=u===null?null:ye.safeParse(u.payload);if(d!==null&&!d.success)return s(J,{title:c(`build.templates.unreadable`,`This template cannot be read`),message:d.error.issues[0]?.message??``});let f=d===null?null:d.data,p=n?.template;return s(Bd,{templateId:e,templateName:u===null?null:u.name,payload:f,existing:t,currentRecipe:n,initialName:t?.name??u?.name??``,initialValues:p?.values??(f===null?{}:id(f)),storedProblems:p?.problems??[],saving:r,saveError:i,onSave:a,onCancel:o},t?.id??`new:${e}`)}var Hd=`fromTemplate`;d();var Ud=[`coreBlocks`,`list`],Wd=5e3;function Gd(e){return e instanceof Error?e.message:String(e)}function Kd({onOpenScripts:t,createRequested:n=!1,onCreateConsumed:r}){let{t:a}=Q(),d=te(),{state:f,openNew:p,openEdit:h,close:g}=En({editKey:`block`,newKey:`new`}),_=ee(),[y,b]=l(null),[x,S]=l(null),[C,w]=l(!1),[T,E]=l(null),[D,O]=l(null),[k,A]=$n(),j=tr(),M=hn(),N=k.get(Hd),P=f.mode!==`closed`;c(()=>{n&&(w(!0),r?.())},[n,r]),c(()=>{N!==null&&(E(N),A(e=>{let t=new URLSearchParams(e);return t.delete(Hd),t},{replace:!0}))},[N,A]);let F=o(()=>{w(!1),p()},[p]),I=u({queryKey:Ud,refetchInterval:Wd,queryFn:async()=>(await d.trpcClient.coreBlocks.list.query({})).blocks}),L=()=>{I.refetch()},R=e=>{g(),E(null),L(),qn({title:a(`build.automationsTab.saved`,`Automation saved`),message:e.name,severity:`info`})},z=m({mutationFn:e=>d.trpcClient.coreBlocks.create.mutate({block:e}),onSuccess:e=>{R(e.block),S(e.block.id)}}),B=m({mutationFn:e=>d.trpcClient.coreBlocks.update.mutate({blockId:e.block.id,block:Fi(e.block,e.values)}),onSuccess:()=>{S(null),L()}}),V=m({mutationFn:e=>d.trpcClient.coreBlocks.update.mutate(e),onSuccess:e=>R(e.block)}),H=m({mutationFn:e=>d.trpcClient.coreBlocks.delete.mutate({blockId:e}),onSuccess:L}),U=m({mutationFn:e=>d.trpcClient.coreBlocks.setEnabled.mutate(e),onSuccess:L}),W=m({mutationFn:e=>d.trpcClient.coreBlocks.update.mutate({blockId:e.id,block:{name:e.name,...e.tags===void 0?{}:{tags:e.tags},code:ii(e.code),enabled:e.enabled,placement:e.placement,...e.integrationId===void 0?{}:{integrationId:e.integrationId}}}),onSuccess:e=>{g(),L(),t(e.block.id)}}),G=I.data,ne=Du((G??[]).filter(e=>ei(e.code))),re=G!==void 0&&ne.length===0,K=f.mode===`edit`?ne.find(e=>e.id===f.id)??null:null,ie=f.mode===`edit`&&G!==void 0&&K===null;c(()=>{ie&&g()},[ie,g]);let ae=K===null?null:ri(K.code),oe=ae!==null&&ae.ok?ae.recipe.template:void 0,se=async e=>{let{template:t,...n}=e.recipe,r={version:1,body:n,inputs:[],bindings:[]};O(null);try{let t=await M.mutateAsync({kind:`automation`,name:e.name,payload:r});t.status===`refused`?O(t.detail):j(nr(t.template.id))}catch(e){O(Gd(e))}},ce=z.error===null?V.error===null?W.error===null?null:Gd(W.error):Gd(V.error):Gd(z.error),le=i(()=>[{key:`name`,header:a(`build.automationsTab.automation`,`Automation`),nowrap:!1,render:e=>{let t=ri(e.code);return s(Au,{block:e,logsOpen:y===e.id,unreadable:t.ok?null:t.reason,flagged:t.ok&&t.recipe.template?.problems!==void 0})},sortValue:e=>e.name},{key:`trigger`,header:a(`build.automationsTab.trigger`,`Trigger`),render:e=>{let t=ri(e.code);return s(Nu,{recipe:t.ok?t.recipe:null})},notSortableReason:a(`build.automationsTab.triggerNotSortable`,`Read from the recipe`)},{key:`lastRun`,header:a(`build.automationsTab.lastRun`,`Last run`),render:e=>s(Pu,{blockId:e.id}),notSortableReason:a(`build.automationsTab.lastRunNotSortable`,`Read per automation`)},{key:`enabled`,header:a(`build.automationsTab.enabled`,`Enabled`),render:e=>s(Fu,{block:e,disabled:U.isPending,onToggle:t=>U.mutate({blockId:e.id,enabled:t})}),sortValue:e=>+!!e.enabled},{key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,render:e=>{let t=ri(e.code);return s(Iu,{unreadable:t.ok?null:t.reason,onEdit:()=>h(e.id),onQuickEdit:()=>S(e.id),onToggleLogs:()=>b(y===e.id?null:e.id),onDelete:()=>{_({title:a(`automation.automationList.deleteThisAutomation`,`Delete this automation?`),message:a(`automation.automationList.deleteMessage`,`{{name}} will be deleted. This cannot be undone.`,{name:e.name}),confirmLabel:a(`common.delete`,`Delete`),variant:`danger`}).then(t=>{t&&H.mutate(e.id)})}})}}],[_,y,h,H,U,a]),ue=()=>{z.reset(),V.reset(),E(null),g()},de=x===null?null:(G??[]).find(e=>e.id===x)??null,fe=de===null?null:s(pi,{subject:zi(de),subjectKey:de.id,saving:B.isPending,error:B.error===null?null:Gd(B.error),onSave:e=>B.mutate({block:de,values:e}),onClose:()=>{B.reset(),S(null)}});return T!==null&&!P?e(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3`,"data-testid":`automation-editor-panel`,children:[e(`h3`,{className:`flex items-center gap-2 text-sm font-semibold`,children:[s(v,{className:`h-4 w-4 text-foreground-muted`}),a(`build.automationsTab.newAutomation`,`New automation`)]}),s(Vd,{templateId:T,existing:null,recipe:null,saving:z.isPending,saveError:ce,onSave:e=>z.mutate(e),onCancel:ue})]}):P?f.mode===`edit`&&K===null?s(Un,{className:`h-24 w-full`}):K!==null&&oe!==void 0&&ae!==null&&ae.ok?e(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3`,"data-testid":`automation-editor-panel`,children:[e(`h3`,{className:`flex items-center gap-2 text-sm font-semibold`,children:[s(v,{className:`h-4 w-4 text-foreground-muted`}),a(`build.automationsTab.edit`,`Edit {{name}}`,{name:K.name})]}),s(Vd,{templateId:oe.templateId,existing:K,recipe:ae.recipe,saving:V.isPending,saveError:ce,onSave:e=>V.mutate({blockId:K.id,block:{...e,tags:e.tags??K.tags}}),onCancel:ue})]}):e(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3`,"data-testid":`automation-editor-panel`,children:[s(xu,{existing:K,initialRecipe:ae!==null&&ae.ok?ae.recipe:Ga,saving:z.isPending||V.isPending,saveError:ce,ejecting:W.isPending,title:K===null?a(`build.automationsTab.newAutomation`,`New automation`):a(`build.automationsTab.edit`,`Edit {{name}}`,{name:K.name}),onQuickEdit:K===null?void 0:()=>S(K.id),onSave:e=>{K===null?z.mutate(e):V.mutate({blockId:K.id,block:e})},onEject:()=>{K!==null&&W.mutate(K)},onSaveAsTemplate:e=>void se(e),savingAsTemplate:M.isPending,onCancel:()=>{z.reset(),V.reset(),W.reset(),g()}},K?.id??`new`),H.error!=null&&s(J,{message:Gd(H.error)}),D!==null&&s(J,{message:D}),fe]}):e(`div`,{className:`space-y-3`,children:[s(`p`,{className:`text-xs text-foreground-subtle`,children:G===void 0?``:Ou(ne)}),I.error!=null&&s(J,{title:a(`build.automationsTab.couldNotReadTheAutomations`,`Could not read the automations`),message:Gd(I.error),onRetry:L}),re?s(Lu,{onCreate:()=>w(!0)}):s(gn,{section:`automations`,getTags:ai,searchText:oi,searchLabel:a(`build.automationsTab.search`,`Search automations`),columns:le,rows:ne,rowKey:e=>e.id,pageSize:25,maxBodyHeight:Ct,emptyMessage:G===void 0?a(`build.automationsTab.loadingAutomations`,`Loading automations…`):a(`build.automationsTab.noAutomationsYet`,`No automations yet.`),onRowClick:e=>h(e.id)}),H.error!=null&&s(J,{message:Gd(H.error)}),U.error!=null&&s(J,{message:Gd(U.error)}),s(Ru,{open:C,onBlank:F,onTemplate:e=>{w(!1),E(e)},onClose:()=>w(!1)}),fe]})}var qd={kind:`all`,children:[]};function Jd({value:t,devices:n,label:r,onChange:i}){let{t:a}=Q(),o=t===void 0?null:{when:t,actions:[]};return e(`div`,{className:`space-y-2`,children:[s(on,{checked:t!==void 0,label:r,"aria-label":r,onCheckedChange:e=>i(e?qd:void 0)}),o!==null&&e(h,{children:[s(`p`,{className:`text-xs text-foreground-subtle`,children:a(`schedulers.activeWhen.hint`,`Only states count here, such as "someone is home". While they are false, nothing runs and holds pause.`)}),s(il,{recipe:o,devices:n,onChange:e=>i(e.when)})]})]})}var Yd=[`sunrise`,`sunset`,`dawn`,`dusk`],Xd=6e4;function Zd(e){return e.kind===`command`||e.kind===`wait`}function Qd(e,t){let n={id:e.id,at:e.at,mode:t,steps:t===`release`?[]:e.steps,...e.conditions===void 0?{}:{conditions:e.conditions}};return t===`hold`?{...n,...e.override===void 0?{}:{override:e.override},...e.maxHoldAttempts===void 0?{}:{maxHoldAttempts:e.maxHoldAttempts}}:n}function $d({point:t,devices:n,site:r,localDate:i,issues:a,onChange:o,onRemove:c}){let{t:l}=Q(),u=t.at,d=u.kind===`sun`?Ei(u,r,i):null,f=Di(u,r,i),p=t.override??{mode:`respect`},m=e=>o({...t,at:e});return e(`div`,{className:`space-y-3`,"data-testid":`point-editor`,children:[e(`div`,{className:`flex flex-wrap items-end gap-3`,children:[e(`label`,{className:`space-y-1 text-xs text-foreground-muted`,children:[s(`span`,{children:l(`schedulers.point.kind`,`Point type`)}),s(A,{"aria-label":l(`schedulers.point.kind`,`Point type`),value:t.mode,options:[{value:`edge`,label:l(`schedulers.point.edge`,`Edge: run once`)},{value:`hold`,label:l(`schedulers.point.hold`,`Hold: keep true`)},{value:`release`,label:l(`schedulers.point.release`,`Release: end the hold`)}],onChange:e=>{let n=e.target.value;(n===`edge`||n===`hold`||n===`release`)&&o(Qd(t,n))}})]}),e(`label`,{className:`space-y-1 text-xs text-foreground-muted`,children:[s(`span`,{children:l(`schedulers.point.when`,`When`)}),s(A,{"aria-label":l(`schedulers.point.when`,`When`),value:u.kind===`sun`?`sun`:`clock`,options:[{value:`clock`,label:l(`schedulers.point.clock`,`At a time`)},{value:`sun`,label:l(`schedulers.point.sun`,`At a sun event`)}],onChange:e=>{e.target.value===`sun`?m({kind:`sun`,event:`sunset`,offsetMin:0}):m({kind:`clock`,hh:12,mm:0})}})]}),u.kind===`clock`&&e(`label`,{className:`space-y-1 text-xs text-foreground-muted`,children:[s(`span`,{children:l(`schedulers.point.time`,`Time`)}),s(Y,{type:`time`,"aria-label":l(`schedulers.point.time`,`Time`),value:Ai(u.hh,u.mm),onChange:e=>{let t=ki(e.target.value);t!==null&&m(t)}})]}),u.kind===`sun`&&e(h,{children:[e(`label`,{className:`space-y-1 text-xs text-foreground-muted`,children:[s(`span`,{children:l(`schedulers.point.sunEvent`,`Sun event`)}),s(A,{"aria-label":l(`schedulers.point.sunEvent`,`Sun event`),value:u.event,options:Yd.map(e=>({value:e,label:l(`schedulers.sun.${e}`,e)})),onChange:e=>{let t=Yd.find(t=>t===e.target.value);t!==void 0&&m({...u,event:t})}})]}),e(`label`,{className:`space-y-1 text-xs text-foreground-muted`,children:[s(`span`,{children:l(`schedulers.point.offset`,`Offset (minutes, negative = before)`)}),s(zr,{"aria-label":l(`schedulers.point.offset`,`Offset (minutes, negative = before)`),className:`w-28`,value:u.offsetMin,onValue:e=>{e!==null&&m({...u,offsetMin:Math.round(e)})}})]}),s(`p`,{className:`pb-2 text-xs text-foreground-muted`,"data-testid":`sun-computed`,children:d===null||f===null?l(`schedulers.point.sunUnknown`,`No time today: the site location is not set.`):l(`schedulers.point.sunComputed`,`Today at {{time}} ({{zone}})`,{time:ji(d),zone:r.timeZone})})]}),e(q,{variant:`ghost`,className:`ml-auto`,onClick:c,"aria-label":l(`schedulers.point.remove`,`Remove point`),children:[s(z,{className:`h-4 w-4`}),` `,l(`schedulers.point.remove`,`Remove point`)]})]}),t.mode!==`release`&&s(Pl,{actions:t.steps,devices:n,allowedKinds:[`command`,`wait`],onChange:e=>o({...t,steps:e.filter(Zd)})}),t.mode===`release`&&s(`p`,{className:`text-xs text-foreground-subtle`,children:l(`schedulers.point.releaseHint`,`A release ends the running hold without doing anything to the devices.`)}),t.mode===`hold`&&e(`div`,{className:`flex flex-wrap items-end gap-3`,children:[e(`label`,{className:`space-y-1 text-xs text-foreground-muted`,children:[s(`span`,{children:l(`schedulers.point.override`,`If someone changes it by hand`)}),s(A,{"aria-label":l(`schedulers.point.override`,`If someone changes it by hand`),value:p.mode,options:[{value:`respect`,label:l(`schedulers.point.respect`,`Leave it alone`)},{value:`reassert`,label:l(`schedulers.point.reassert`,`Put the hold back after a while`)}],onChange:e=>o({...t,override:e.target.value===`reassert`?{mode:`reassert`,graceMs:10*Xd}:{mode:`respect`}})})]}),p.mode===`reassert`&&e(`label`,{className:`space-y-1 text-xs text-foreground-muted`,children:[s(`span`,{children:l(`schedulers.point.grace`,`Wait (minutes)`)}),s(zr,{"aria-label":l(`schedulers.point.grace`,`Wait (minutes)`),className:`w-24`,value:p.graceMs/Xd,onValue:e=>{e!==null&&o({...t,override:{mode:`reassert`,graceMs:Math.max(0,Math.round(e*Xd))}})}})]})]}),a.length>0&&s(`ul`,{className:`space-y-1 rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:a.map(e=>s(`li`,{children:e.message},`${e.path}:${e.message}`))})]})}d();var ef=5e3,tf=600,nf=6e4,rf={timeZone:`UTC`,location:null};function af(e){return e instanceof Error?e.message:String(e)}function of(e,t){let[n,r]=l(e);return c(()=>{let n=setTimeout(()=>r(e),t);return()=>clearTimeout(n)},[e,t]),n}function sf(e,t){return t(`schedulers.day.${e}`,e)}function cf({entry:t,onClose:n,onSaved:r,onQuickEdit:a}){let{t:o}=Q(),u=p(),d=ee(),f=Hr(),m=pn(),h=m.data??rf,[g,_]=l(()=>vi(t)),v=JSON.stringify(t?.tags??[]),y=t?.name;c(()=>{y!==void 0&&_(e=>({...e,name:y,tags:JSON.parse(v)}))},[y,v]);let[b,x]=l(()=>g.profiles[0]?.id??``),[S,C]=l(null),[w,T]=l(null),E=()=>{u.invalidateQueries({queryKey:[[`schedulers`]]})},D=Rt({onSuccess:e=>{E(),r(e.scheduler.id)}}),O=Kt({onSuccess:E}),k=Vt({onSuccess:()=>{E(),n()}}),A=St({schedulerId:t?.id??`none`},{enabled:t!==null,refetchInterval:ef}),M=i(()=>Ni(g,h),[g,h]),P=g.profiles.some(e=>e.points.some(e=>e.mode===`hold`)),F=of(M.ok?M.input:null,tf),I=bn(F===null?{scheduler:g}:t===null?{scheduler:F}:{scheduler:F,schedulerId:t.id},{enabled:F!==null&&P&&m.data!==void 0}),L=g.profiles.find(e=>e.id===b)??g.profiles[0],R=L===void 0?-1:g.profiles.indexOf(L),B=Ti(h),V=L?.points.find(e=>e.id===S)??null,te=L===void 0||V===null?-1:L.points.indexOf(V),H=M.ok?[]:M.issues,U=e=>H.filter(t=>t.path===e||t.path.startsWith(`${e}.`)),W=e=>_({...g,profiles:g.profiles.map((t,n)=>n===R?e:t)}),G=e=>{L!==void 0&&W({...L,points:L.points.map(t=>t.id===e.id?e:t)})},ne=i(()=>L===void 0?[]:L.points.flatMap(e=>{let t=Ei(e.at,h,B);if(t===null)return[];let n=e.at.kind===`sun`?`${o(`schedulers.sun.${e.at.event}`,e.at.event)} ${e.at.offsetMin>=0?`+`:``}${String(e.at.offsetMin)} (${ji(t)})`:Ai(e.at.hh,e.at.mm);return[{id:e.id,minute:t,label:n,tone:e.mode===`hold`?`success`:e.mode===`release`?`neutral`:`primary`,draggable:e.at.kind===`clock`||e.at.kind===`sun`&&Di(e.at,h,B)!==null}]}),[L,h,B,o]),re=i(()=>L===void 0?[]:Mi(L.points,h,B),[L,h,B]),K=(e,t)=>{let n=L?.points.find(t=>t.id===e);n!==void 0&&G({...n,at:Oi(n.at,t,Di(n.at,h,B))})},ie=e=>{if(L===void 0)return;let t=Si(`point`,g.profiles.flatMap(e=>e.points.map(e=>e.id)));W({...L,points:[...L.points,xi(e,t,720)]}),C(t)},ae=()=>{let e=Si(`profile`,g.profiles.map(e=>e.id));_({...g,profiles:[...g.profiles,bi(e,o(`schedulers.profile.newName`,`New profile`))]}),x(e),C(null)},oe=D.isPending||O.isPending,se=D.error??O.error??k.error;return e(Bi,{testId:`scheduler-editor`,icon:N,title:t===null?o(`schedulers.list.new`,`New scheduler`):t.name,onClose:n,onQuickEdit:a,onSave:()=>{M.ok&&(t===null?D.mutate({scheduler:M.input}):O.mutate({schedulerId:t.id,scheduler:M.input}))},saveDisabled:!M.ok||m.data===void 0,saving:oe,notices:se===null?null:s(J,{message:af(se)}),footerActions:t===null?null:e(q,{variant:`ghost`,disabled:k.isPending,onClick:()=>{d({title:o(`schedulers.editor.deleteTitle`,`Delete this scheduler?`),message:o(`schedulers.editor.deleteMessage`,`{{name}} will be deleted and any hold it keeps will stop.`,{name:t.name}),confirmLabel:o(`common.delete`,`Delete`),variant:`danger`}).then(e=>{e&&k.mutate({schedulerId:t.id})})},children:[s(z,{className:`h-4 w-4`}),` `,o(`common.delete`,`Delete`)]}),side:s(ga,{traces:t===null?[]:A.data?.traces,selectedId:w,onSelect:T}),children:[s(Y,{"aria-label":o(`schedulers.editor.name`,`Name`),className:`max-w-xs`,value:g.name,placeholder:o(`schedulers.editor.namePlaceholder`,`What this scheduler does`),onChange:e=>_({...g,name:e.target.value})}),e(zt,{headingId:`scheduler-settings`,title:o(`schedulers.editor.settings`,`Settings`),children:[e(`div`,{className:`divide-y divide-border px-3`,children:[s(Ht,{label:o(`schedulers.editor.enabled`,`Enabled`),children:s(on,{checked:g.enabled,"aria-label":o(`schedulers.editor.enabled`,`Enabled`),onCheckedChange:e=>_({...g,enabled:e})})}),s(Ht,{label:o(`schedulers.editor.priority`,`Priority (higher wins a conflict)`),children:s(zr,{"aria-label":o(`schedulers.editor.priority`,`Priority (higher wins a conflict)`),className:`w-24`,value:g.priority,onValue:e=>{e!==null&&_({...g,priority:Math.round(e)})}})}),s(Ht,{label:o(`schedulers.editor.maxLate`,`Run a missed point up to (minutes late)`),children:s(zr,{"aria-label":o(`schedulers.editor.maxLate`,`Run a missed point up to (minutes late)`),className:`w-24`,value:g.maxLateMs/nf,onValue:e=>{e!==null&&_({...g,maxLateMs:Math.round(e*nf)})}})})]}),e(`div`,{className:`p-3`,children:[s(Jd,{value:g.activeWhen,devices:f,label:o(`schedulers.editor.activeWhen`,`Only when a condition holds`),onChange:e=>{let{activeWhen:t,...n}=g;_(e===void 0?n:{...n,activeWhen:e})}}),U(`activeWhen`).map(e=>s(`p`,{className:`mt-1 text-xs text-warning`,children:e.message},e.message))]})]}),s(zt,{headingId:`scheduler-profiles`,title:o(`schedulers.editor.profiles`,`Profiles`),actions:e(q,{variant:`outline`,size:`sm`,onClick:ae,children:[s(j,{className:`h-4 w-4`}),` `,o(`schedulers.profile.add`,`Add profile`)]}),children:e(`div`,{className:`space-y-3 p-3`,children:[s(`p`,{className:`text-xs text-foreground-subtle`,children:o(`schedulers.profile.hint`,`Each day, the first profile in this order whose days and condition hold is the one that runs.`)}),L!==void 0&&e(dn,{value:L.id,onValueChange:e=>{x(e),C(null)},appearance:`pills`,children:[s(wn,{children:g.profiles.map(e=>s(Mn,{value:e.id,children:e.name},e.id))}),e(Fn,{value:L.id,className:`space-y-3 pt-3`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[s(Y,{"aria-label":o(`schedulers.profile.name`,`Profile name`),className:`max-w-xs`,value:L.name,onChange:e=>W({...L,name:e.target.value})}),s(on,{checked:L.enabled,label:o(`schedulers.profile.enabled`,`Enabled`),onCheckedChange:e=>W({...L,enabled:e})}),g.profiles.length>1&&e(q,{variant:`ghost`,size:`sm`,onClick:()=>{_({...g,profiles:g.profiles.filter(e=>e.id!==L.id)}),x(``),C(null)},children:[s(z,{className:`h-4 w-4`}),` `,o(`schedulers.profile.remove`,`Remove profile`)]})]}),s(`div`,{className:`flex flex-wrap gap-1`,role:`group`,"aria-label":o(`schedulers.profile.days`,`Days`),children:hi.map(e=>{let t=L.days.includes(e);return s(q,{size:`sm`,variant:t?`primary`:`outline`,"aria-pressed":t,onClick:()=>W({...L,days:t?L.days.filter(t=>t!==e):hi.filter(t=>t===e||L.days.includes(t))}),children:sf(e,o)},e)})}),U(`profiles.${String(R)}.days`).map(e=>s(`p`,{className:`text-xs text-warning`,children:o(`schedulers.profile.daysNeeded`,`Pick at least one day.`)},e.message)),s(Jd,{value:L.activeWhen,devices:f,label:o(`schedulers.profile.activeWhen`,`This profile only when a condition holds`),onChange:e=>{let{activeWhen:t,...n}=L;W(e===void 0?n:{...n,activeWhen:e})}}),s(vt,{ariaLabel:o(`schedulers.timeline.label`,`Day timeline`),markers:ne,bands:re,selectedId:S,onSelect:C,onMove:K}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(q,{variant:`outline`,size:`sm`,onClick:()=>ie(`edge`),children:[s(j,{className:`h-4 w-4`}),` `,o(`schedulers.point.addEdge`,`Edge`)]}),e(q,{variant:`outline`,size:`sm`,onClick:()=>ie(`hold`),children:[s(j,{className:`h-4 w-4`}),` `,o(`schedulers.point.addHold`,`Hold`)]}),e(q,{variant:`outline`,size:`sm`,onClick:()=>ie(`release`),children:[s(j,{className:`h-4 w-4`}),` `,o(`schedulers.point.addRelease`,`Release`)]}),s(X,{variant:`neutral`,children:h.timeZone})]}),L.points.length===0&&s(`p`,{className:`text-xs text-foreground-subtle`,children:o(`schedulers.timeline.empty`,`Add a point to place something on the day.`)}),V!==null&&s($d,{point:V,devices:f,site:h,localDate:B,issues:U(`profiles.${String(R)}.points.${String(te)}`),onChange:G,onRemove:()=>{W({...L,points:L.points.filter(e=>e.id!==V.id)}),C(null)}},V.id)]})]})]})}),I.data!==void 0&&I.data.conflicts.length>0&&s(`ul`,{className:`space-y-1 rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:I.data.conflicts.map(e=>s(`li`,{children:o(`schedulers.conflict.message`,`{{other}} wants device {{device}} in another state from {{from}} to {{to}} ({{winner}}).`,{other:e.other.schedulerName,device:e.deviceId,from:ji(e.fromMinute),to:ji(e.toMinute),winner:e.winner===`mine`?o(`schedulers.conflict.mine`,`this one wins`):e.winner===`other`?o(`schedulers.conflict.other`,`the other one wins`):o(`schedulers.conflict.tie`,`the one that started first wins`)})},`${e.other.schedulerId}:${e.other.pointId}:${e.mine.pointId}:${String(e.deviceId)}`))}),!M.ok&&g.name!==``&&H.length>0&&V===null&&s(`ul`,{className:`space-y-1 rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:H.map(e=>s(`li`,{children:e.message},`${e.path}:${e.message}`))})]})}d();var lf=5e3;function uf(e){return e instanceof Error?e.message:String(e)}function df({createRequested:t=!1,onCreateConsumed:n}){let{t:r}=Q(),a=p(),{state:o,openNew:u,openEdit:d,close:f}=En({editKey:`scheduler`,newKey:`new`}),m=Ot({},{refetchInterval:lf}),g=Gt({},{refetchInterval:lf}),_=Pt({onSuccess:()=>void a.invalidateQueries({queryKey:[[`schedulers`]]})}),[v,y]=l(null),b=Kt({onSuccess:()=>{y(null),a.invalidateQueries({queryKey:[[`schedulers`]]})}});c(()=>{t&&(u(),n?.())},[t,n,u]);let x=m.data??[],S=o.mode===`edit`?x.find(e=>e.id===o.id)??null:null,C=e=>{if(!e.enabled)return{variant:`neutral`,label:r(`schedulers.status.off`,`Off`)};let t=g.data?.find(t=>t.schedulerId===e.id);return t===void 0?{variant:`neutral`,label:`-`}:t.hold===null?{variant:`neutral`,label:r(`schedulers.status.idle`,`Idle`)}:t.hold.suspendedInactive?{variant:`warning`,label:r(`schedulers.status.paused`,`Paused`)}:t.hold.targets.some(e=>e.status===`gave-up`)?{variant:`danger`,label:r(`schedulers.status.gaveUp`,`Gave up`)}:{variant:`success`,label:r(`schedulers.status.holding`,`Holding`)}},w=i(()=>[{key:`name`,header:r(`schedulers.list.name`,`Name`),render:e=>s(`span`,{className:`font-medium`,children:e.name}),sortValue:e=>e.name},{key:`enabled`,header:r(`schedulers.list.enabled`,`Enabled`),render:e=>s(`span`,{onClick:e=>e.stopPropagation(),children:s(on,{checked:e.enabled,disabled:_.isPending,"aria-label":r(`schedulers.list.enabledAria`,`Enable {{name}}`,{name:e.name}),onCheckedChange:t=>_.mutate({schedulerId:e.id,enabled:t})})}),sortValue:e=>Number(e.enabled)},{key:`profiles`,header:r(`schedulers.list.profiles`,`Profiles`),render:e=>String(e.profiles.length),sortValue:e=>e.profiles.length},{key:`priority`,header:r(`schedulers.list.priority`,`Priority`),render:e=>String(e.priority),sortValue:e=>e.priority},{key:`status`,header:r(`schedulers.list.status`,`Now`),render:e=>{let t=C(e);return s(X,{variant:t.variant,children:t.label})},notSortableReason:r(`schedulers.list.statusNotSortable`,`Derived from the live hold`)},{key:`updated`,header:r(`schedulers.list.updated`,`Updated`),render:e=>or(e.updatedAt),sortValue:e=>e.updatedAt},{key:`quick-edit`,align:`right`,render:e=>s(rn,{icon:B,size:`sm`,variant:`ghost`,"aria-label":r(`build.quickEdit.action`,`Quick edit`),"data-testid":`scheduler-quick-edit-${e.id}`,onClick:t=>{t.stopPropagation(),y(e.id)}}),notSortableReason:r(`schedulers.list.actionNotSortable`,`A control`)}],[_,g.data,r]),T=v===null?null:x.find(e=>e.id===v)??null,E=T===null?null:s(pi,{subject:zi(T),subjectKey:T.id,saving:b.isPending,error:b.error===null?null:uf(b.error),onSave:e=>{let t=Li(T,e);b.mutate({schedulerId:T.id,scheduler:t})},onClose:()=>{b.reset(),y(null)}});return o.mode===`closed`?e(`div`,{className:`space-y-3`,children:[s(`p`,{className:`text-xs text-foreground-subtle`,children:r(`schedulers.list.hint`,`A scheduler does things over the day: run something at a time or at sunset, or keep a device in a state for a stretch of time.`)}),_.error!=null&&s(J,{message:uf(_.error)}),m.data===void 0?m.error==null?s(Un,{className:`h-24 w-full`}):s(J,{title:r(`schedulers.list.couldNotRead`,`Could not read the schedulers`),message:uf(m.error),onRetry:()=>void m.refetch()}):x.length===0?s(pt,{icon:N,title:r(`schedulers.list.emptyTitle`,`No schedulers yet`),description:r(`schedulers.list.emptyDescription`,`A scheduler turns the garden lights on at sunset and off at 23:00, every day or only on some days.`),action:e(q,{onClick:u,children:[s(j,{className:`h-4 w-4`}),` `,r(`schedulers.list.new`,`New scheduler`)]})}):s(gn,{section:`schedulers`,getTags:li,searchText:ui,searchLabel:r(`schedulers.list.search`,`Search schedulers`),columns:w,rows:x,rowKey:e=>e.id,pageSize:25,maxBodyHeight:Ct,emptyMessage:r(`schedulers.list.emptyTitle`,`No schedulers yet`),onRowClick:e=>d(e.id)}),E]}):e(h,{children:[s(cf,{entry:S,onClose:f,onSaved:e=>{d(e),y(e)},onQuickEdit:S===null?void 0:()=>y(S.id)},S?.id??`new`),E]})}async function ff(e,t){let n=`${Qe}${e}`;return(await t())?.find(e=>e.stableId===n)?.id??null}var pf=10,mf=400;async function hf(e,t,n=mf){for(let r=0;r<pf;r+=1){let r=await ff(e,t);if(r!==null)return r;await new Promise(e=>setTimeout(e,n))}return null}var gf=`media-player`;function _f(e){return e===we.MediaPlayer?`media-source`:`none`}function vf(e){return e===we.MediaPlayer?{fieldChoice:`operator`,purpose:`member`,multiple:!1,max:1,deviceTypes:[we.MediaPlayer],accept:[{cap:gf,fieldPath:`state`,valueKind:`state`}],history:{required:!1,minRetentionMs:null},mustBindCaps:[gf],exclude:[]}:null}function yf(e){return e===null||e.cap!==`media-player`?[]:[{kind:`fields`,cap:gf,fields:{},commands:Object.fromEntries(Object.keys(Ee()).map(t=>[t,{kind:`forward`,source:e.source,cap:gf,method:t}]))}]}function bf(e,t){let n=e===we.MediaPlayer?yf(t):[];return{target:{kind:`new`,type:e},features:n}}d();function xf({onTitle:t}){let{t:n}=Q(),r=_(),i=tr(),a=Jr(),o=Dn(),u=Qt({addonId:`composer`}),[d,f]=l(we.Sensor),[p,m]=l(``),[h,g]=l([]),[v,y]=l(null),b=h[0]??null,x=vf(d),S=bf(d,b);c(()=>{t(n(`helper.newDevice`))},[t,n]);let C=async()=>{y(null);try{let e=p.trim(),{block:t}=await a.mutateAsync({block:{...e===``?{}:{name:e},enabled:!0,composition:S}}),r=await hf(t.id,async()=>(await u.refetch()).data??u.data);if(r===null){y(n(`helper.devicePending`));return}e!==``&&await o.mutateAsync({deviceId:r,name:e}),i(er(r),{replace:!0})}catch(e){y(e instanceof Error?e.message:String(e))}};return e(`div`,{className:`flex flex-col gap-3`,"data-testid":`device-create-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`),s(A,{value:d,onChange:e=>{let t=Object.values(we).find(t=>t===e.target.value);t!==void 0&&(f(t),g([]))},options:Object.values(we).map(e=>({value:e,label:bt(e,r).label}))})]}),e(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[n(`compositionEditor.name`),s(Y,{"aria-label":n(`compositionEditor.name`),value:p,onChange:e=>m(e.target.value)})]})]}),x!==null&&e(`div`,{className:`flex flex-col gap-1`,"data-testid":`device-create-source`,children:[s(`p`,{className:`text-[11px] text-foreground-muted`,children:n(`helper.deviceSource.${_f(d)}`)}),s(xr,{kind:`members`,request:x,enabled:!0,members:h,onMembersChange:g,onRefuse:()=>void 0})]}),v!==null&&s(`p`,{role:`alert`,className:`text-xs text-danger`,children:v}),s(q,{disabled:a.isPending,onClick:()=>void C(),children:n(`compositionEditor.save`)})]})}d();function Sf({preset:t,saving:n,onSave:r,onBack:a}){let{t:o,i18n:c}=Q(),u=Dr(!0),[d,f]=l({}),[p,m]=l(o(t.nameKey)),[h,g]=l(null),[_,v]=l([]),[y,b]=l(!1),x=i(()=>u.kind===`known`?new Map(u.value.map(e=>[W({addonId:e.addonId,stableId:e.stableId}),e.name])):new Map,[u]),S=i(()=>new Set(Object.values(d).flatMap(e=>e===void 0?[]:[W(e)])),[d]),C=i(()=>u.kind===`known`?{kind:`known`,value:_r(u.value,S)}:u,[u,S]),w=kr(t,d),T=u.kind===`known`?jr(u.value,w,!1):null,E=t.build(d),D=wr(t,d),O=(e,t)=>{v([]),f(n=>({...n,[e]:t}))},ee=e=>x.get(W(e))??e.stableId;return e(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3`,"data-testid":`preset-wizard`,children:[s(`p`,{className:`text-[11px] text-foreground-muted`,children:o(t.descriptionKey)}),e(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[o(`preset.name`),s(Y,{"aria-label":o(`preset.name`),value:p,onChange:e=>m(e.target.value)})]}),s(`ul`,{className:`flex flex-col gap-2`,"aria-label":o(`preset.slots`),children:t.slots.map(t=>{let n=d[t.key];return e(`li`,{className:`grid grid-cols-1 gap-1 sm:grid-cols-[minmax(0,1fr)_auto] sm:items-center`,"data-testid":`preset-slot-${t.key}`,children:[e(`div`,{className:`min-w-0`,children:[e(`div`,{className:`text-xs text-foreground`,children:[o(t.labelKey),t.optionalGroup===void 0?` *`:``]}),e(`div`,{className:`text-[11px] text-foreground-muted break-words`,children:[vr(t.expectedCap,c.language),t.optionalGroup===void 0?``:` · ${o(`preset.optional`)}`]})]}),e(`div`,{className:`flex flex-wrap gap-1`,children:[s(q,{variant:`outline`,size:`sm`,onClick:()=>g(t),children:n===void 0?o(`preset.choose`):ee(n)}),n!==void 0&&t.optionalGroup!==void 0&&s(q,{variant:`ghost`,size:`sm`,onClick:()=>O(t.key,void 0),children:o(`preset.clear`)})]})]},t.key)})}),E===null&&D.length>0&&s(`p`,{className:`text-[11px] text-foreground-muted`,"data-testid":`preset-missing`,children:o(`preset.missing`,{slots:D.map(e=>o(e.labelKey)).join(`, `)})}),E!==null&&e(`section`,{className:`flex flex-col gap-1`,"data-testid":`preset-preview`,children:[s(`h3`,{className:`text-xs font-medium text-foreground`,children:o(`preset.preview`)}),s(`ul`,{className:`flex flex-col gap-1 text-[11px] text-foreground-muted`,children:E.features.map(e=>e.kind===`fields`?s(`li`,{children:o(`preset.previewFeature`,{cap:vr(e.cap,c.language),fields:Object.keys(e.fields).length,commands:Object.keys(e.commands??{}).length+Object.values(e.items??{}).filter(e=>e.reset!==void 0).length})},e.cap):null)})]}),s(Or,{lines:_,testId:`preset-refusals`}),e(`div`,{className:`mt-auto flex flex-wrap gap-2`,children:[s(q,{disabled:E===null||n||y,onClick:()=>{E===null||y||(b(!0),r(E,p.trim()).then(e=>{e.kind===`refused`&&v(e.lines)}).finally(()=>b(!1)))},"data-testid":`preset-create`,children:o(`preset.create`)}),s(q,{variant:`ghost`,onClick:a,children:o(`preset.back`)})]}),s(Sr,{open:h!==null,title:h===null?``:o(`preset.pickTitle`,{slot:o(h.labelKey)}),selection:`single`,candidates:C,room:T,confirmLabel:()=>o(`preset.pickConfirm`),onConfirm:e=>{let t=e[0],n=h;g(null),t!==void 0&&n!==null&&O(n.key,t.ref)},onClose:()=>g(null)})]})}d();var Cf=`preset`;function wf({mode:e,onTitle:t}){return s(e===`helper`?Tf:xf,{onTitle:t})}function Tf({onTitle:e}){let{t}=Q(),n=tr(),i=Jr(),a=Dn(),o=Qt({addonId:`composer`}),[u,d]=l(null),[f,p]=l(!1),[m,h]=$n(),g=br(m.get(Cf)),_=g===null?Ef(u,t):t(g.labelKey);c(()=>{f||e(_)},[e,_,f]);let v=e=>h(t=>{let n=new URLSearchParams(t);return e===null?n.delete(Cf):n.set(Cf,e),n},{replace:!0}),y=async(e,r)=>{try{let{block:s}=await i.mutateAsync({block:{...r===``?{}:{name:r},enabled:!0,composition:e}}),c=await hf(s.id,async()=>(await o.refetch()).data??o.data);return c===null?{kind:`refused`,lines:Cr(t(`helper.devicePending`))}:(r!==``&&await a.mutateAsync({deviceId:c,name:r}),n(er(c),{replace:!0}),{kind:`saved`,deviceId:c})}catch(e){return{kind:`refused`,lines:Cr(e instanceof Error?e.message:String(e))}}},b=r(null);return f?s(xf,{onTitle:e}):g===null?s(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3`,"data-testid":`composition-create-form`,children:s(Er,{fillHeight:!0,onDevice:()=>p(!0),onPreset:v,purpose:`create`,initial:null,start:`template`,saving:i.isPending,onDraftChange:d,onSave:async(e,r)=>{let s=null,c=await Nr(e,async(c,l)=>{let u=b.current,d;if(u!==null&&u.draft===e)d=u.blockId;else{let{block:t}=await i.mutateAsync({block:{...l===``?{}:{name:l},enabled:!0,composition:c}});d=t.id,b.current={draft:e,blockId:d}}let f=await hf(d,async()=>(await o.refetch()).data??o.data);if(f===null)throw Error(t(`helper.devicePending`));s=f,b.current=null,l!==``&&await a.mutateAsync({deviceId:f,name:l}),r===`open`&&n(Qn(f),{replace:!0})}),l=s;return c.length>0||l===null?{kind:`refused`,lines:Df(c,t)}:{kind:`saved`,deviceId:l}}})}):s(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3`,"data-testid":`composition-create-form`,children:s(Sf,{preset:g,saving:i.isPending,onSave:y,onBack:()=>v(null)})})}function Ef(e,t){if(e===null)return t(`helper.newComposed`);if(e.kind===`statistic`)return t(`helper.newTitle.statistic`);if(e.kind===`integral`)return t(`helper.newTitle.integral`);if(e.kind===`arithmetic`)return t(`helper.newTitle.${e.op}`);if(e.kind===`threshold`||e.kind===`expression`||e.kind===`derivative`)return t(`helper.newTitle.${e.kind}`);let n=ze(e.templateId);return t(n===null?`helper.newComposed`:`helper.newTitle.${n.id}`)}function Df(e,t){return e.length>0?e:Cr(t(`helper.devicePending`))}function Of(e){let t=e.helper;if(t===void 0)return{section:`advanced`,kind:null};switch(t.kind){case`group`:return{section:`group`,kind:t.templateId};case`arithmetic`:return{section:`calculation`,kind:t.op};case`expression`:return{section:`advanced`,kind:`expression`};default:return{section:`calculation`,kind:t.kind}}}function kf(e){return{state:`answered`,byRef:new Map(e.map(e=>[W(e),e]))}}function Af(e,t){if(e.state!==`unanswered`)return e.byRef.get(W(t))??null}function jf(e){return e===void 0?`unknown`:e===null?`missing`:`present`}function Mf(e){return tt(e).map(e=>e.source)}function Nf(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(...Mf(t));for(let t of Object.values(e.items??{}))for(let e of Object.values(t.fields))n.push(...Mf(e))}let r=new Set;return n.filter(e=>{let t=W(e);return r.has(t)?!1:(r.add(t),!0)})}function Pf(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:Z.t(`helpers.compositionRows.running`),reason:null};let r=[...t.length>0?[Z.t(`helpers.compositionRows.fieldsUnavailable`,{count:t.length})]:[],...n.length>0?[Z.t(`helpers.compositionRows.fieldsStale`,{count:n.length})]:[]].join(`, `),i=t[0]??n[0],a=i===void 0?``:` — ${i.cap}.${i.path}: ${i.reason??Z.t(`helpers.compositionRows.noReason`)}`;return{tone:`pending`,label:Z.t(`helpers.compositionRows.running`),reason:`${r}${a}`}}function Ff(e,t){let n=e.reason??t??null;switch(e.status){case`running`:return Pf(e);case`degraded`:return{tone:`pending`,label:Z.t(`helpers.compositionRows.degraded`),reason:n??Z.t(`helpers.compositionRows.degradedReason`)};case`starting`:return{tone:`pending`,label:Z.t(`helpers.compositionRows.starting`),reason:n};case`failed`:return{tone:`error`,label:Z.t(`helpers.compositionRows.failed`),reason:n??Z.t(`helpers.compositionRows.failedReason`)};default:return{tone:`error`,label:Z.t(`helpers.compositionRows.notRunning`),reason:n??Z.t(`helpers.compositionRows.notRunningReason`)}}}function If(e){let{block:t,state:n}=e;if(!t.enabled)return{tone:`idle`,label:Z.t(`helpers.compositionRows.off`),reason:null};if(n.kind===`unreachable`)return{tone:`pending`,label:Z.t(`helpers.compositionRows.unknown`),reason:Z.t(`helpers.compositionRows.unreachable`,{error:n.error})};if(n.state!==null)return Ff(n.state,t.lastError);let r=t.lastError===void 0?t.status:`${t.status}: ${t.lastError}`;return{tone:`pending`,label:Z.t(`helpers.compositionRows.notReported`),reason:Z.t(`helpers.compositionRows.noRecord`,{stored:r})}}function Lf(e){return W(e)}function Rf(e,t){let n=Af(t,e);return{key:W(e),label:n?n.name:Lf(e),presence:jf(n),deviceId:n?n.id:null}}function zf(e){return e.state.kind===`answered`&&e.state.state!==null?e.state.state.deviceId:null}function Bf(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:Ne(e.block.id),a=W(i),o=Nf(e).filter(e=>W(e)!==a).map(e=>Rf(e,t)),s=n.features.map(e=>e.enabled===!1?Z.t(`helpers.compositionRows.featureOff`,{cap:e.cap}):e.cap),c=Af(t,i),l=zf(e),u=If(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}`,origin:Of(n),features:s,state:u,sources:o,reportedDeviceId:l,tags:c?.tags??[]};let d=jf(c);return{blockId:e.block.id,kind:`customization`,name:c?c.name:Lf(r.device),namePresence:d,type:c?c.type:null,origin:Of(n),features:s,state:u,sources:o,reportedDeviceId:l,tags:c?.tags??[]}}function Vf(e){return e.state.tone===`error`?0:e.state.tone===`pending`?1:e.state.tone===`ok`?2:3}function Hf(e,t){return Vf(e)-Vf(t)||e.name.localeCompare(t.name)}function Uf(e,t){let n=e.flatMap(e=>{let n=Bf(e,t);return n===null?[]:[n]});return{composed:n.filter(e=>e.kind===`composed`).toSorted(Hf),customizations:n.filter(e=>e.kind===`customization`).toSorted(Hf)}}d();var Wf=1e4;function Gf(e){return e instanceof Error?e.message:typeof e==`object`&&e&&`message`in e?String(e.message):String(e)}function Kf(){let e=Jn();return e.data===void 0?{state:`unanswered`,reason:e.error==null?Z.t(`build.customDeviceTab.deviceListPending`):Z.t(`build.customDeviceTab.deviceListUnreadable`,{error:Gf(e.error)})}:kf(e.data)}function qf(e,t){return e===`blank`?`blank`:e===`helper`||e===`1`||t?`helper`:null}function Jf({createRequested:t=!1,onCreateConsumed:n}={}){let{t:r}=Q(),[i,a]=$n(),o=mt({},{refetchInterval:Wf}),c=Kf(),u=En({editKey:`block`,newKey:`new`}),d=u.state.mode===`edit`?u.state.id:null,f=d===null?qf(i.get(`new`),t):null,p=f!==null,[m,g]=l(``),[_,v]=l(null),y=ee(),b=Mt(),[x,S]=l(null),C=Dn(),w=cn(),T=()=>{u.close(),a(()=>{let e=new URLSearchParams(window.location.search);return e.delete(`new`),e.delete(`block`),e},{replace:!0}),n?.()},E=o.data,D=Xf(E,o.error,()=>void o.refetch(),c,{onEditComposed:e=>u.openEdit(e),onQuickEdit:e=>S(e.blockId),deleting:b.isPending,onDelete:e=>{y({title:r(`build.customDeviceTab.deleteThisComposedDevice`,`Delete this composed device?`),message:r(`build.customDeviceTab.deleteMessage`,`{{name}} will be deleted. This cannot be undone.`,{name:e.name}),confirmLabel:r(`common.delete`,`Delete`),variant:`danger`}).then(t=>{t&&b.mutate({blockId:e.blockId},{onSuccess:()=>void o.refetch()})})}}),O=E===void 0||E.state===`not-loaded`?[]:Uf(E.views,c).composed,k=x===null?null:O.find(e=>e.blockId===x)??null,A=k?.reportedDeviceId??null,j=async(e,t)=>{let n=e.reportedDeviceId;if(n!==null){v(null);try{t.name!==e.name&&await C.mutateAsync({deviceId:n,name:t.name}),await w.mutateAsync({deviceId:n,tags:[...t.tags]}),S(null),o.refetch()}catch(e){v(Gf(e))}}},M=k===null||A===null?null:s(pi,{subject:{name:k.name,tags:k.tags},subjectKey:k.blockId,saving:C.isPending||w.isPending,error:_,onSave:e=>void j(k,e),onClose:()=>{v(null),S(null)}});if(p||d!==null){let t=d===null?null:O.find(e=>e.blockId===d)??null;return e(h,{children:[e(Bi,{testId:`composed-device-editor`,icon:F,title:d===null?m||r(f===`blank`?`helper.newComposition`:`helper.newComposed`):r(`build.customDeviceTab.editComposedDevice`,`Edit composed device`),onClose:T,onQuickEdit:t?.reportedDeviceId==null?void 0:()=>S(t.blockId),bare:!0,children:[d!==null&&s(Ar,{blockId:d,fillHeight:!0}),f!==null&&s(wf,{mode:f,onTitle:g},f)]}),M]})}return e(h,{children:[D,M,b.error!=null&&s(J,{message:Gf(b.error)})]})}function Yf(t){return s(kt,{children:e(`div`,{className:`space-y-1 p-4`,children:[s(`p`,{className:`text-sm text-warning`,children:Z.t(`build.customDeviceTab.theCompositionStoreHasNot`,`The composition store has not been read yet.`)}),e(`p`,{className:`text-xs text-foreground-subtle`,children:[Z.t(`build.customDeviceTab.thisIsNotTheSame`,`This is not the same as having none — the list appears once the hub has read it (`),t,`).`]})]})})}function Xf(e,t,n,r,i){if(t!=null&&e===void 0)return s(J,{title:Z.t(`build.customDeviceTab.couldNotReadTheCompositions`,`Could not read the compositions`),message:Gf(t),onRetry:n});if(e===void 0)return s(`p`,{className:`p-4 text-sm text-foreground-subtle`,children:Z.t(`build.customDeviceTab.loadingCompositions`,`Loading compositions…`)});if(e.state===`not-loaded`)return Yf(e.reason);let a=t==null?null:Gf(t);return s(Zf,{lists:Uf(e.views,r),fleet:r,refreshError:a,handlers:i})}function Zf({lists:t,fleet:n,refreshError:r,handlers:i}){let{t:a}=Q();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.`]}),s(Qf,{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`,handlers:i}),s(Qf,{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`,handlers:i})]})}function Qf({title:t,hint:n,rows:r,nameHeader:i,emptyMessage:a,kind:o,handlers:c}){let{t:l}=Q();return e(`section`,{className:`space-y-2`,"aria-label":t,children:[e(`div`,{children:[s(`h3`,{className:`font-medium`,children:t}),s(`p`,{className:`text-xs text-foreground-subtle`,children:n})]}),s(gn,{section:o===`composed`?`composed-devices`:`customizations`,getTags:$f,searchText:ep,searchLabel:l(`build.customDeviceTab.search`,`Search {{list}}`,{list:t}),columns:tp(i,o,c,l),rows:r,rowKey:e=>e.blockId,pageSize:25,maxBodyHeight:Ct,emptyMessage:a,onRowClick:o===`composed`?e=>c.onEditComposed(e.blockId):void 0})]})}function $f(e){return e.tags}function ep(e){return[e.name,e.type??``,...e.features]}function tp(t,n,r,i){let a=[{key:`name`,header:t,sortValue:e=>e.name.toLowerCase(),render:e=>s(rp,{row:e})},{key:`type`,header:Z.t(`build.customDeviceTab.type`,`Type`),sortValue:e=>e.type,render:e=>s(`span`,{className:`text-xs text-foreground-subtle`,children:e.type??Z.t(`common.unknownWord`)})},...n===`composed`?[{key:`origin`,header:Z.t(`build.customDeviceTab.builtAs`,`Built as`),sortValue:e=>np(e.origin,i),render:e=>s(X,{variant:`default`,"data-testid":`composed-origin-badge`,children:np(e.origin,i)})}]:[],{key:`state`,header:Z.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:[s(X,{variant:Tu(t.state.tone),children:t.state.label}),t.state.reason!==null&&s(`p`,{className:`max-w-md whitespace-normal text-xs text-foreground-subtle`,children:t.state.reason})]})},{key:`sources`,header:Z.t(`build.customDeviceTab.sources`,`Sources`),nowrap:!1,notSortableReason:`A list of devices has no single order.`,render:e=>s(ap,{sources:e.sources})}];return n===`composed`&&a.push({key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,nowrap:!0,render:t=>e(`div`,{className:`flex justify-end gap-1`,children:[t.reportedDeviceId!==null&&s(rn,{icon:B,variant:`ghost`,"aria-label":i(`build.quickEdit.action`,`Quick edit`),"data-testid":`composed-quick-edit-${t.blockId}`,onClick:e=>{e.stopPropagation(),r.onQuickEdit(t)}}),s(q,{variant:`ghost`,title:i(`common.edit`,`Edit`),onClick:e=>{e.stopPropagation(),r.onEditComposed(t.blockId)},children:i(`common.edit`,`Edit`)}),s(q,{variant:`ghost`,title:i(`common.delete`,`Delete`),disabled:r.deleting,"aria-label":i(`common.delete`,`Delete`),onClick:e=>{e.stopPropagation(),r.onDelete(t)},children:s(z,{className:`h-4 w-4`})})]})}),a}function np(e,t){let n=e.kind===null?null:t(`helper.template.${e.kind}`);return e.section===`group`?t(`helper.badge.group`,{kind:n}):e.section===`calculation`?t(`helper.badge.calculation`,{kind:n}):n===null?t(`helper.badge.advanced`):t(`helper.badge.advancedKind`,{kind:n})}function rp({row:t}){let{t:n}=Q();return e(`div`,{className:`space-y-0.5`,children:[s(ip,{row:t}),t.namePresence===`missing`&&s(`span`,{className:`ml-1.5 text-[10px] text-danger`,children:n(`build.customDeviceTab.deviceMissing`,`device missing`)}),s(`p`,{className:`text-[11px] text-foreground-subtle`,children:t.features.join(`, `)})]})}function ip({row:e}){let{t}=Q(),n=yt(e.reportedDeviceId??0,`compact`,e.name),r=e.reportedDeviceId===null?e.name:n;return e.reportedDeviceId===null?e.kind===`composed`?s(`span`,{className:`text-xs font-medium text-foreground`,children:e.name}):s(`span`,{className:`text-xs text-foreground-subtle`,children:t(`build.customDeviceTab.notReported`,{name:r})}):s(Zn,{to:e.kind===`composed`?Qn(e.reportedDeviceId):er(e.reportedDeviceId),className:`text-xs font-medium text-foreground hover:underline`,onClick:e=>e.stopPropagation(),children:r})}function ap({sources:t}){let{t:n}=Q();return t.length===0?s(`span`,{className:`text-xs text-foreground-subtle`,children:`—`}):s(`ul`,{className:`space-y-0.5`,children:t.map(t=>e(`li`,{className:`text-xs`,children:[t.deviceId===null?s(`span`,{className:t.presence===`missing`?`text-danger`:`text-foreground`,children:t.label}):s(Zn,{to:`/devices/${String(t.deviceId)}`,className:`hover:underline`,children:t.label}),t.presence===`missing`&&s(`span`,{className:`ml-1.5 text-[10px] text-danger`,children:n(`common.missing`)})]},t.key))})}function op(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 sp(e){if(Array.isArray(e))return e}function cp(e,t,n){return(t=_p(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function lp(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 up(){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 dp(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 fp(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?dp(Object(n),!0).forEach(function(t){cp(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):dp(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function pp(e,t){if(e==null)return{};var n,r,i=mp(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 mp(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 hp(e,t){return sp(e)||lp(e,t)||vp(e,t)||up()}function gp(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 _p(e){var t=gp(e,`string`);return typeof t==`symbol`?t:t+``}function vp(e,t){if(e){if(typeof e==`string`)return op(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)?op(e,t):void 0}}function yp(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function bp(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 xp(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?bp(Object(n),!0).forEach(function(t){yp(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):bp(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function Sp(){var e=[...arguments];return function(t){return e.reduceRight(function(e,t){return t(e)},t)}}function Cp(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 wp(e){return{}.toString.call(e).includes(`Object`)}function Tp(e){return!Object.keys(e).length}function Ep(e){return typeof e==`function`}function Dp(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Op(e,t){return wp(t)||Np(`changeType`),Object.keys(t).some(function(t){return!Dp(e,t)})&&Np(`changeField`),t}function kp(e){Ep(e)||Np(`selectorType`)}function Ap(e){Ep(e)||wp(e)||Np(`handlerType`),wp(e)&&Object.values(e).some(function(e){return!Ep(e)})&&Np(`handlersType`)}function jp(e){e||Np(`initialIsRequired`),wp(e)||Np(`initialType`),Tp(e)&&Np(`initialContent`)}function Mp(e,t){throw Error(e[t]||e.default)}var Np=Cp(Mp)({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"}),Pp={changes:Op,selector:kp,handler:Ap,initial:jp};function Fp(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};Pp.initial(e),Pp.handler(t);var n={current:e},r=Cp(Rp)(n,t),i=Cp(Lp)(n),a=Cp(Pp.changes)(e),o=Cp(Ip)(n);function s(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:function(e){return e};return Pp.selector(e),e(n.current)}function c(e){Sp(r,i,a,o)(e)}return[s,c]}function Ip(e,t){return Ep(t)?t(e.current):t}function Lp(e,t){return e.current=xp(xp({},e.current),t),t}function Rp(e,t,n){return Ep(t)?t(e.current):Object.keys(n).forEach(function(n){return t[n]?.call(t,e.current[n])}),n}var zp={create:Fp},Bp={paths:{vs:`https://cdn.jsdelivr.net/npm/monaco-editor@0.55.1/min/vs`}};function Vp(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 Hp(e){return{}.toString.call(e).includes(`Object`)}function Up(e){return e||qp(`configIsRequired`),Hp(e)||qp(`configType`),e.urls?(Wp(),{paths:{vs:e.urls.monacoBase}}):e}function Wp(){console.warn(Kp.deprecation)}function Gp(e,t){throw Error(e[t]||e.default)}var Kp={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
|
-
`},qp=Vp(Gp)(Kp),Jp={config:Up},Yp=function(){var e=[...arguments];return function(t){return e.reduceRight(function(e,t){return t(e)},t)}};function Xp(e,t){return Object.keys(t).forEach(function(n){t[n]instanceof Object&&e[n]&&Object.assign(t[n],Xp(e[n],t[n]))}),fp(fp({},e),t)}var Zp={type:`cancelation`,msg:`operation is manually canceled`};function Qp(e){var t=!1,n=new Promise(function(n,r){e.then(function(e){return t?r(Zp):n(e)}),e.catch(r)});return n.cancel=function(){return t=!0},n}var $p=[`monaco`],em=hp(zp.create({config:Bp,isInitialized:!1,resolve:null,reject:null,monaco:null}),2),tm=em[0],nm=em[1];function rm(e){var t=Jp.config(e),n=t.monaco,r=pp(t,$p);nm(function(e){return{config:Xp(e.config,r),monaco:n}})}function im(){var e=tm(function(e){return{monaco:e.monaco,isInitialized:e.isInitialized,resolve:e.resolve}});if(!e.isInitialized){if(nm({isInitialized:!0}),e.monaco)return e.resolve(e.monaco),Qp(dm);if(window.monaco&&window.monaco.editor)return lm(window.monaco),e.resolve(window.monaco),Qp(dm);Yp(am,sm)(cm)}return Qp(dm)}function am(e){return document.body.appendChild(e)}function om(e){var t=document.createElement(`script`);return e&&(t.src=e),t}function sm(e){var t=tm(function(e){return{config:e.config,reject:e.reject}}),n=om(`${t.config.paths.vs}/loader.js`);return n.onload=function(){return e()},n.onerror=t.reject,n}function cm(){var e=tm(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;lm(n),e.resolve(n)},function(t){e.reject(t)})}function lm(e){tm().monaco||nm({monaco:e})}function um(){return tm(function(e){return e.monaco})}var dm=new Promise(function(e,t){return nm({resolve:e,reject:t})}),fm={config:rm,init:im,__getMonacoInstance:um};d();var pm={wrapper:{display:`flex`,position:`relative`,textAlign:`initial`},fullWidth:{width:`100%`},hide:{display:`none`}},mm={container:{display:`flex`,height:`100%`,width:`100%`,justifyContent:`center`,alignItems:`center`}};function hm({children:e}){return t.createElement(`div`,{style:mm.container},e)}var gm=hm;function _m({width:e,height:n,isEditorReady:r,loading:i,_ref:a,className:o,wrapperProps:s}){return t.createElement(`section`,{style:{...pm.wrapper,width:e,height:n},...s},!r&&t.createElement(gm,null,i),t.createElement(`div`,{ref:a,style:{...pm.fullWidth,...!r&&pm.hide},className:o}))}var vm=a(_m);function ym(e){c(e,[])}var bm=ym;function xm(e,t,n=!0){let i=r(!0);c(i.current||!n?()=>{i.current=!1}:e,t)}var Sm=xm;function Cm(){}function wm(e,t,n,r){return Tm(e,r)||Em(e,t,n,r)}function Tm(e,t){return e.editor.getModel(Dm(e,t))}function Em(e,t,n,r){return e.editor.createModel(t,n,r?Dm(e,r):void 0)}function Dm(e,t){return e.Uri.parse(t)}function Om({original:e,modified:n,language:i,originalLanguage:a,modifiedLanguage:s,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=Cm,onMount:S=Cm}){let[C,w]=l(!1),[T,E]=l(!0),D=r(null),O=r(null),ee=r(null),k=r(S),A=r(x),j=r(!1);bm(()=>{let e=fm.init();return e.then(e=>(O.current=e)&&E(!1)).catch(e=>e?.type!==`cancelation`&&console.error(`Monaco initialization: error:`,e)),()=>D.current?P():e.cancel()}),Sm(()=>{if(D.current&&O.current){let t=D.current.getOriginalEditor(),n=wm(O.current,e||``,a||i||`text`,u||``);n!==t.getModel()&&t.setModel(n)}},[u],C),Sm(()=>{if(D.current&&O.current){let e=D.current.getModifiedEditor(),t=wm(O.current,n||``,s||i||`text`,d||``);t!==e.getModel()&&e.setModel(t)}},[d],C),Sm(()=>{let e=D.current.getModifiedEditor();e.getOption(O.current.editor.EditorOption.readOnly)?e.setValue(n||``):n!==e.getValue()&&(e.executeEdits(``,[{range:e.getModel().getFullModelRange(),text:n||``,forceMoveMarkers:!0}]),e.pushUndoStop())},[n],C),Sm(()=>{D.current?.getModel()?.original.setValue(e||``)},[e],C),Sm(()=>{let{original:e,modified:t}=D.current.getModel();O.current.editor.setModelLanguage(e,a||i||`text`),O.current.editor.setModelLanguage(t,s||i||`text`)},[i,a,s],C),Sm(()=>{O.current?.editor.setTheme(m)},[m],C),Sm(()=>{D.current?.updateOptions(g)},[g],C);let M=o(()=>{if(!O.current)return;A.current(O.current);let t=wm(O.current,e||``,a||i||`text`,u||``),r=wm(O.current,n||``,s||i||`text`,d||``);D.current?.setModel({original:t,modified:r})},[i,n,s,e,a,u,d]),N=o(()=>{!j.current&&ee.current&&(D.current=O.current.editor.createDiffEditor(ee.current,{automaticLayout:!0,...g}),M(),O.current?.editor.setTheme(m),w(!0),j.current=!0)},[g,m,M]);c(()=>{C&&k.current(D.current,O.current)},[C]),c(()=>{!T&&!C&&N()},[T,C,N]);function P(){let e=D.current?.getModel();f||e?.original?.dispose(),p||e?.modified?.dispose(),D.current?.dispose()}return t.createElement(vm,{width:v,height:_,isEditorReady:C,loading:h,_ref:ee,className:y,wrapperProps:b})}a(Om);function km(e){let t=r();return c(()=>{t.current=e},[e]),t.current}var Am=km,jm=new Map;function Mm({defaultValue:e,defaultLanguage:n,defaultPath:i,value:a,language:s,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=Cm,onMount:C=Cm,onChange:w,onValidate:T=Cm}){let[E,D]=l(!1),[O,ee]=l(!0),k=r(null),A=r(null),j=r(null),M=r(C),N=r(S),P=r(),F=r(a),I=Am(u),L=r(!1),R=r(!1);bm(()=>{let e=fm.init();return e.then(e=>(k.current=e)&&ee(!1)).catch(e=>e?.type!==`cancelation`&&console.error(`Monaco initialization: error:`,e)),()=>A.current?B():e.cancel()}),Sm(()=>{let t=wm(k.current,e||a||``,n||s||``,u||i||``);t!==A.current?.getModel()&&(g&&jm.set(I,A.current?.saveViewState()),A.current?.setModel(t),g&&A.current?.restoreViewState(jm.get(u)))},[u],E),Sm(()=>{A.current?.updateOptions(m)},[m],E),Sm(()=>{!A.current||a===void 0||(A.current.getOption(k.current.editor.EditorOption.readOnly)?A.current.setValue(a):a!==A.current.getValue()&&(R.current=!0,A.current.executeEdits(``,[{range:A.current.getModel().getFullModelRange(),text:a,forceMoveMarkers:!0}]),A.current.pushUndoStop(),R.current=!1))},[a],E),Sm(()=>{let e=A.current?.getModel();e&&s&&k.current?.editor.setModelLanguage(e,s)},[s],E),Sm(()=>{f!==void 0&&A.current?.revealLine(f)},[f],E),Sm(()=>{k.current?.editor.setTheme(d)},[d],E);let z=o(()=>{if(!(!j.current||!k.current)&&!L.current){N.current(k.current);let t=u||i,r=wm(k.current,a||e||``,n||s||``,t||``);A.current=k.current?.editor.create(j.current,{model:r,automaticLayout:!0,...m},h),g&&A.current.restoreViewState(jm.get(t)),k.current.editor.setTheme(d),f!==void 0&&A.current.revealLine(f),D(!0),L.current=!0}},[e,n,i,a,s,u,m,h,g,d,f]);c(()=>{E&&M.current(A.current,k.current)},[E]),c(()=>{!O&&!E&&z()},[O,E,z]),F.current=a,c(()=>{E&&w&&(P.current?.dispose(),P.current=A.current?.onDidChangeModelContent(e=>{R.current||w(A.current.getValue(),e)}))},[E,w]),c(()=>{if(E){let e=k.current.editor.onDidChangeMarkers(e=>{let t=A.current.getModel()?.uri;if(t&&e.find(e=>e.path===t.path)){let e=k.current.editor.getModelMarkers({resource:t});T?.(e)}});return()=>{e?.dispose()}}return()=>{}},[E,T]);function B(){P.current?.dispose(),_?g&&jm.set(u,A.current.saveViewState()):A.current.getModel()?.dispose(),A.current.dispose()}return t.createElement(vm,{width:v,height:y,isEditorReady:E,loading:p,_ref:j,className:b,wrapperProps:x})}var Nm=a(Mm);d();function Pm(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 Fm={target:99,module:99,moduleResolution:2,strict:!0,noImplicitAny:!0,strictNullChecks:!0,allowNonTsExtensions:!0,isolatedModules:!0};function Im(e,t){let n=e.languages.typescript.typescriptDefaults;n.setCompilerOptions({...n.getCompilerOptions(),...Fm}),n.setExtraLibs(t.map(e=>({filePath:e.filePath,content:e.content})))}function Lm({value:e,onChange:t,extraLibs:n=[],path:i=`file:///block.ts`,onDiagnostics:a,readOnly:l=!1,heightPx:u=420,dark:d=!0}){let f=r(null),p=o((e,t)=>{if(f.current=t,Im(t,n),a===void 0)return;let r=e.getModel();if(r===null)return;let i=()=>{a(t.editor.getModelMarkers({resource:r.uri}).map(e=>({line:e.startLineNumber,column:e.startColumn,message:e.message,severity:e.severity})))};t.editor.onDidChangeMarkers(i),i()},[n,a]);return c(()=>{let e=f.current;e!==null&&Im(e,n)},[n]),s(Nm,{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 Rm(e){return e.some(e=>e.severity>=8)}var zm=[{id:`blank`,name:`Blank script`,get description(){return Z.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 Bm(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 Vm=zm.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 Hm({existing:e,dirty:t,saving:n,restarting:r}){return e===null?Z.t(`helpers.restartGate.saveFirstNoProcess`):n?Z.t(`helpers.restartGate.saving`):r?Z.t(`helpers.restartGate.restarting`):t?Z.t(`helpers.restartGate.saveFirstDirty`):e.enabled?null:Z.t(`helpers.restartGate.disabled`)}d();var Um=5e3;function Wm(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 Gm({blockId:t}){let{t:n}=Q(),r=Ze(t),a=It({addonId:r,projection:`slim`},{refetchInterval:Um}),o=i(()=>Wm(a.data),[a.data]);return a.isLoading?e(`p`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[s(S,{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:[s(`h4`,{className:`text-sm font-medium`,children:n(`build.scriptDevicesPanel.devices`,`Devices`)}),s(`p`,{className:`text-xs text-foreground-subtle`,children:s(ir,{i18nKey:`build.scriptDevicesPanel.declaredBy`,values:{addonId:r},components:{code:s(`code`,{className:`text-[11px]`})}})})]}),s(X,{variant:`default`,children:o.length})]}),o.length===0?s(`p`,{className:`text-xs text-foreground-subtle`,children:s(ir,{i18nKey:`build.scriptDevicesPanel.noDevices`,components:{code:s(`code`,{})}})}):s(`ul`,{className:`space-y-3`,children:o.map(t=>s(`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:[s(Zn,{to:`/devices/${String(t.id)}`,className:`text-sm font-medium hover:underline`,title:n(`build.scriptDevicesPanel.openDeviceDetail`,`Open device detail`),children:s(un,{device:{id:t.id,name:t.name,type:t.type,stableId:t.stableId??``,parentDeviceId:null},form:`compact`})}),s(X,{variant:`info`,style:`outline`,children:t.type}),t.stableId!==void 0&&e(`span`,{className:`text-[11px] text-foreground-subtle`,children:[`stableId `,s(`code`,{children:t.stableId})]}),e(`span`,{className:`text-[11px] text-foreground-subtle`,children:[`#`,t.id]})]})},t.id))})]})}d();function Km(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 qm(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 Jm(e){switch(e){case`refresh-channel-catalog`:return Z.t(`build.scriptSettingsPanel.enableChannel`);case`send-tv-schedule-now`:return Z.t(`build.scriptSettingsPanel.enableTv`);case`refresh-nordvpn-catalog`:return Z.t(`build.scriptSettingsPanel.enableNord`);case`probe-nordvpn-italy`:return Z.t(`build.scriptSettingsPanel.enableItaly`);case`test-nordvpn-endpoint`:return Z.t(`build.scriptSettingsPanel.enableVpn`);case`refresh-unifi-catalog`:return Z.t(`build.scriptSettingsPanel.enableUnifi`)}}function Ym(e){if(typeof e!=`object`||!e||!(`key`in e))return null;let t=Reflect.get(e,`key`);return typeof t==`string`?t:null}function Xm(e){if(!(typeof e!=`object`||!e||!(`value`in e)))return Reflect.get(e,`value`)}function Zm(e){let t={};for(let n of e.sections)for(let e of n.fields){let n=Ym(e);n!==null&&(t[n]=Xm(e))}return t}function Qm(e){return typeof e!=`object`||!e?!1:Array.isArray(Reflect.get(e,`sections`))}function $m({blockId:t}){let{t:n}=Q(),r=te(),a=jn({blockId:t},{retry:!1}),c=At({blockId:t},{refetchInterval:1e4,retry:!1}),u=Nn({onSuccess:()=>{c.refetch()}}),d=In(),f=Tn(),[p,m]=l(null),[h,g]=l(null),[_,v]=l(null),[y,b]=l(!1),x=Qm(c.data)?c.data:null,C=i(()=>x===null?{}:Zm(x),[x]),w=p??C,T=o(e=>{m(e)},[]),E=p!==null,D=o(()=>{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]),O=o(async(e,n)=>{if(Km(e)){b(!0),g(null),v(null);try{p!==null&&(await r.trpcClient.coreBlocks.updateBlockSettings.mutate({blockId:t,patch:p}),m(null)),await r.trpcClient.coreBlocks.updateBlockSettings.mutate({blockId:t,patch:qm(e)}),a.data?.block?.enabled!==!0&&(await f.mutateAsync({blockId:t,enabled:!0}),v(Jm(e))),await d.mutateAsync({blockId:t}),await c.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,a.data?.block?.enabled,p,d,f,c,r.trpcClient.coreBlocks]);return c.isLoading?e(`p`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[s(S,{className:`h-3.5 w-3.5 animate-spin`}),` `,n(`build.scriptSettingsPanel.loading`)]}):c.isError?e(`p`,{className:`text-xs text-danger`,"data-testid":`script-settings-error`,children:[n(`build.scriptSettingsPanel.couldNotLoadSettings`,`Could not load settings:`),` `,c.error instanceof Error?c.error.message:String(c.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:[s(`h4`,{className:`text-sm font-medium`,children:n(`build.scriptSettingsPanel.settings`,`Settings`)}),s(`p`,{className:`text-xs text-foreground-subtle`,children:s(ir,{i18nKey:`build.scriptSettingsPanel.declaredBy`,components:{code:s(`code`,{})}})})]}),e(q,{size:`sm`,variant:`primary`,onClick:D,disabled:!E||u.isPending||y,children:[u.isPending&&s(S,{className:`h-3.5 w-3.5 animate-spin`}),n(`build.scriptSettingsPanel.saveSettings`,`Save settings`)]})]}),s(Yn,{schema:x,values:w,onChange:T,onAction:O}),h===null?null:s(`p`,{className:`text-xs text-danger`,"data-testid":`script-settings-save-error`,children:h}),_===null?null:s(`p`,{className:`text-xs text-foreground-subtle`,"data-testid":`script-settings-info`,children:_})]})}d();var eh=`hub`;function th({existing:t,typeDefs:n,typeDefsLoading:r,saving:a,saveError:o,restarting:u,restartError:d,onRestart:f,onSave:p,onCancel:g,title:_,onQuickEdit:v}){let{t:b}=Q(),x=te(),C=ee(),{resolvedMode:w}=vn(),E=Je({code:t?.code??Vm,files:t?.files,entry:t?.entry}),[O,k]=l(t?.name??``),j=t?.name;c(()=>{j!==void 0&&k(j)},[j]);let[M,N]=l(E.files),[P,F]=l(E.entry),[I,R]=l(E.entry),[z,B]=l(t?.placement??eh),[V,H]=l(t?.integrationId??``),[U,W]=l([]),[G,ne]=l(!1),[re,K]=l(`blank`),[ie,ae]=l(null),[oe,se]=l(``),ce=M[I]??``,le=e=>{N(t=>({...t,[I]:e}))},ue=Object.keys(M).toSorted(),de=zm.length>1,fe=i(()=>[...n?.libs??[],...Pm(M,I)],[n?.libs,M,I]),pe=m({mutationFn:()=>x.trpcClient.coreBlocks.compile.mutate({files:M,entry:P})}),me=i(()=>U.filter(e=>e.severity>=8),[U]),he=Rm(U),ge=O.trim()===``,_e=t===null?null:Je(t),ve=t===null||_e===null||JSON.stringify(M)!==JSON.stringify(_e.files)||P!==_e.entry||O.trim()!==t.name||z!==t.placement||(V.trim()===``?void 0:V.trim())!==t.integrationId,ye=()=>{pe.reset(),p({name:O.trim(),files:M,entry:P,enabled:t?.enabled??!0,placement:z,...t?.tags===void 0?{}:{tags:t.tags},...V.trim()===``?{}:{integrationId:V.trim()}})},be=()=>{let e=Bm(Object.keys(M));N(t=>({...t,[e]:``})),R(e),ae(e),se(e)},xe=e=>{ae(e),se(e)},Se=()=>{if(ie===null)return;let e=ie,t=oe.trim();if(ae(null),!(t===``||t===e)){if(M[t]!==void 0){R(t);return}N(n=>{let r={};for(let[i,a]of Object.entries(n))r[i===e?t:i]=a;return r}),P===e&&F(t),R(t)}},Ce=async e=>{let t=zm.find(t=>t.id===e);if(t===void 0)return;let n=zm.find(e=>e.id===`blank`);!(n!==void 0&&JSON.stringify(M)===JSON.stringify(n.files)&&P===n.entry)&&!await C({title:b(`build.blockEditor.loadExample`,`Load example`),message:b(`build.blockEditor.replaceTheCurrentEditorContents`,`Replace the current editor contents with this example?`),confirmLabel:b(`build.blockEditor.replace`,`Replace`),variant:`warning`})||(K(e),N({...t.files}),F(t.entry),R(t.entry),(O.trim()===``||re===`blank`)&&k(t.id===`blank`?``:t.name))},we=t===null?null:wu(t),Te=Hm({existing:t,dirty:ve,saving:a,restarting:u}),Ee=e(h,{children:[e(q,{variant:`outline`,onClick:()=>pe.mutate(),disabled:pe.isPending||a,title:b(`build.blockEditor.typeCheckOnTheNode`,`Type-check on the node without saving`),children:[pe.isPending&&s(S,{className:`h-4 w-4 animate-spin`}),` `,b(`common.compile`)]}),e(q,{variant:`outline`,onClick:()=>f?.(),disabled:Te!==null||f===void 0,title:Te??b(`build.blockEditor.stopTheProcessAndLet`,`Stop the process and let the supervisor bring it back`),children:[u?s(L,{className:`h-4 w-4 animate-spin`}):s(L,{className:`h-4 w-4`}),` `,b(`build.blockEditor.restart`,`Restart`)]}),e(q,{variant:`ghost`,onClick:()=>ne(!G),title:b(`build.blockEditor.showThisScriptSProcess`,`Show this script's process logs`),"data-testid":`script-logs-toggle`,"aria-expanded":G,children:[s(T,{className:`h-4 w-4`}),` `,b(`common.logs`),` `,s(ft,{expanded:G})]})]});return e(Bi,{testId:`block-editor`,icon:st,title:_,badges:we===null?null:s(X,{variant:Tu(we.tone),children:we.label}),onClose:g,onQuickEdit:v,onSave:ye,saveDisabled:he||ge,saving:a,footerActions:Ee,footerStatus:e(h,{children:[e(`span`,{children:[b(`build.blockEditor.errorsCount`,{count:me.length}),ve&&t!==null?` · ${b(`build.blockEditor.unsavedChanges`)}`:``]}),ge&&s(X,{variant:`warning`,children:b(`build.blockEditor.nameRequired`,`Name required`)})]}),notices:e(h,{children:[me.length>0&&e(`div`,{className:`space-y-1 rounded border border-danger/40 bg-danger/10 p-3 text-xs`,children:[s(`p`,{className:`font-medium text-danger`,children:b(`build.blockEditor.errorsCannotSave`,{count:me.length})}),me.slice(0,5).map(e=>s(`p`,{className:`text-danger`,children:b(`build.blockEditor.diagnosticLine`,{line:e.line,message:e.message})},`${String(e.line)}:${String(e.column)}:${e.message}`)),me.length>5&&s(`p`,{className:`text-foreground-subtle`,children:b(`build.blockEditor.moreErrors`,{count:me.length-5})})]}),pe.data!==void 0&&(pe.data.ok?e(`p`,{className:`flex items-center gap-2 text-xs text-success`,children:[s(y,{className:`h-3.5 w-3.5`}),` `,b(`build.blockEditor.compiledOk`)]}):e(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:[pe.data.line!==void 0&&s(`span`,{className:`mr-1`,children:b(`build.blockEditor.errorLine`,{line:String(pe.data.line)})}),pe.data.error??b(`build.blockEditor.theCodeDoesNotCompile`,`the code does not compile`)]})),pe.error!==null&&e(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:[b(`build.blockEditor.couldNotReachTheCompiler`,`Could not reach the compiler:`),` `,nh(pe.error)]}),o!==null&&s(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:o}),d!==null&&s(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:d})]}),children:[e(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[e(`label`,{className:`block text-sm`,children:[s(`span`,{className:`text-foreground-subtle`,children:b(`build.blockEditor.name`,`Name`)}),s(Y,{className:`mt-1`,value:O,onChange:e=>k(e.target.value),placeholder:b(`build.blockEditor.whatThisScriptDoes`,`What this script does`)})]}),e(`label`,{className:`block text-sm`,children:[s(`span`,{className:`text-foreground-subtle`,children:b(`build.blockEditor.integrationOptional`,`Integration (optional)`)}),s(Y,{className:`mt-1`,value:V,onChange:e=>H(e.target.value),placeholder:b(`build.blockEditor.leaveEmptyForTheShared`,`Leave empty for the shared system integration`)})]})]}),t===null&&de&&e(`label`,{className:`block text-sm`,children:[s(`span`,{className:`text-foreground-subtle`,children:b(`build.blockEditor.startFrom`,`Start from`)}),s(A,{className:`mt-1 w-full`,value:re,onChange:e=>void Ce(e.target.value),"data-testid":`script-example-select`,children:zm.map(t=>e(`option`,{value:t.id,children:[t.name,` — `,t.description]},t.id))})]}),e(`div`,{children:[s(sn,{selectedNodeId:z,onSelect:B,label:b(`build.blockEditor.runsOn`,`Runs on`),alwaysShow:!0}),z!==eh&&e(`p`,{className:`mt-2 flex items-start gap-2 text-xs text-warning`,children:[s(D,{className:`mt-0.5 h-3.5 w-3.5 shrink-0`}),s(`span`,{children:s(ir,{i18nKey:`build.blockEditor.hubOnlyWarning`,components:{strong:s(`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:[ue.map(t=>ie===t?s(Y,{value:oe,onChange:e=>se(e.target.value),onBlur:()=>Se(),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),Se()),e.key===`Escape`&&(e.preventDefault(),ae(null))},className:`h-7 w-36 px-2 py-0 text-xs`,autoFocus:!0,"data-testid":`script-file-rename`,"aria-label":b(`build.blockEditor.renameFile`,`Rename file`)},t):e(q,{variant:`unstyled`,type:`button`,className:`rounded px-2 py-1 text-xs ${t===I?`bg-muted font-medium text-foreground`:`text-foreground-subtle hover:text-foreground`}`,onClick:()=>R(t),onDoubleClick:()=>xe(t),title:b(`build.blockEditor.doubleClickToRename`,`Double-click to rename`),"data-testid":`script-file-tab-${t}`,children:[t,t===P?` · ${b(`build.blockEditor.entry`)}`:``]},t)),s(q,{variant:`unstyled`,type:`button`,className:`ml-1 rounded px-2 py-1 text-xs text-foreground-subtle hover:text-foreground`,onClick:be,"data-testid":`script-file-add`,children:b(`build.blockEditor.file`,`+ file`)}),I!==P&&s(q,{variant:`unstyled`,type:`button`,className:`rounded px-2 py-1 text-xs text-foreground-subtle hover:text-foreground`,onClick:()=>F(I),title:b(`build.blockEditor.useThisFileAsThe`,`Use this file as the compile entry`),children:b(`build.blockEditor.setAsEntry`,`Set as entry`)})]}),r?s(`p`,{className:`p-4 text-sm text-foreground-subtle`,children:b(`build.blockEditor.loadingTheNodeSType`,`Loading the node's type definitions…`)}):s(Lm,{value:ce,onChange:le,path:`file:///${I}`,extraLibs:fe,onDiagnostics:W,dark:w===`dark`,heightPx:560})]}),n!==void 0&&n.libs.length===0&&s(`p`,{className:`text-xs text-warning`,children:b(`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.`)}),t!==null&&e(`div`,{className:`space-y-3`,children:[s($m,{blockId:t.id}),s(Gm,{blockId:t.id})]}),G&&e(`div`,{className:`rounded border border-border`,"data-testid":`script-logs-panel`,children:[s(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:t===null?b(`build.blockEditor.logsAppearOnceTheScript`,`Logs appear once the script has been saved and started.`):s(h,{children:s(ir,{i18nKey:`build.blockEditor.logsOf`,values:{id:Ze(t.id)},components:{code:s(`code`,{})}})})}),t!==null&&s(kn,{addonId:Ze(t.id),maxHeight:`max-h-[560px]`,showFilters:!1})]})]})}function nh(e){return e instanceof Error?e.message:String(e)}d();var rh=[`coreBlocks`,`list`],ih=[`coreBlocks`,`getTypeDefs`],ah=5e3;function oh(e){return e instanceof Error?e.message:String(e)}function sh({initialBlockId:t,onBlockIdChange:n,createRequested:a=!1,onCreateConsumed:o}={}){let d=_(),{t:f}=Q(),p=te(),{state:g,openNew:v,openEdit:y,close:b}=En({editKey:`block`,newKey:`new`}),[x,S]=l(null),C=ee(),[w,E]=l(null),[D,O]=l(null),k=u({queryKey:rh,refetchInterval:ah,queryFn:async()=>(await p.trpcClient.coreBlocks.list.query({})).blocks}),A=g.mode!==`closed`,j=u({queryKey:ih,enabled:A,staleTime:1/0,gcTime:1/0,queryFn:()=>p.trpcClient.coreBlocks.getTypeDefs.query({})}),M=()=>{k.refetch()},N=r(null),P=k.data;c(()=>{t===void 0||N.current===t||P?.find(e=>e.id===t&&Le(e)===`code`)!==void 0&&(N.current=t,y(t),n?.(t))},[t,P,y,n]),c(()=>{a&&(S(null),v(),n?.(null),o?.())},[a,o,n,v]);let F=m({mutationFn:e=>p.trpcClient.coreBlocks.create.mutate({block:e}),onSuccess:e=>{S(e.block),y(e.block.id),n?.(e.block.id),M(),E(e.block.id)}}),I=m({mutationFn:e=>p.trpcClient.coreBlocks.update.mutate({blockId:e.block.id,block:Pi(e.block,e.values)}),onSuccess:e=>{S(e.block),E(null),M()}}),R=m({mutationFn:e=>p.trpcClient.coreBlocks.update.mutate(e),onSuccess:e=>{S(e.block),y(e.block.id),n?.(e.block.id),M()}}),V=m({mutationFn:e=>p.trpcClient.coreBlocks.delete.mutate({blockId:e}),onSuccess:M}),H=m({mutationFn:e=>p.trpcClient.coreBlocks.setEnabled.mutate(e),onSuccess:M}),U=m({mutationFn:e=>p.trpcClient.coreBlocks.restart.mutate({blockId:e}),onSuccess:M}),W=Du((k.data??[]).filter(e=>Le(e)===`code`&&ti(e))),G=k.data!==void 0&&W.length===0,ne=F.isPending||R.isPending,re=F.error===null?R.error===null?null:oh(R.error):oh(F.error),K=g.mode===`edit`?W.find(e=>e.id===g.id)??(x!==null&&x.id===g.id?x:null):null,ie=g.mode===`new`||K===null?null:Eu(W,K),ae=i(()=>[{key:`name`,header:f(`build.scriptsTab.name`,`Name`),render:t=>{let n=wu(t),r=xn(t.updatedAt,d);return e(`div`,{className:`min-w-0`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[s(`span`,{className:`truncate font-medium`,children:t.name}),s(X,{variant:Tu(n.tone),children:n.label}),s(X,{variant:`info`,children:t.placement}),r!==null&&s(`span`,{className:`text-xs text-foreground-subtle`,children:f(`common.edited`,{when:r})})]}),s(`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:[s(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:s(ir,{i18nKey:`common.logsOf`,values:{id:Ze(t.id)},components:{code:s(`code`,{})}})}),s(kn,{addonId:Ze(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 r=H.isPending||V.isPending,i=U.isPending&&U.variables===t.id;return e(`div`,{className:`flex justify-end gap-1`,children:[s(q,{variant:`ghost`,onClick:e=>{e.stopPropagation(),S(t),y(t.id),n?.(t.id)},title:f(`common.edit`,`Edit`),children:f(`common.edit`,`Edit`)}),s(rn,{icon:B,variant:`ghost`,"aria-label":f(`build.quickEdit.action`,`Quick edit`),onClick:e=>{e.stopPropagation(),E(t.id)}}),s(q,{variant:`ghost`,onClick:e=>{e.stopPropagation(),U.mutate(t.id)},disabled:r||i||!t.enabled,title:t.enabled?f(`build.scriptsTab.restart`,`Restart`):f(`build.scriptsTab.enableItInsteadADisabled`,`Enable it instead — a disabled script has no process`),children:s(L,{className:`h-4 w-4${i?` animate-spin`:``}`})}),s(q,{variant:`ghost`,onClick:e=>{e.stopPropagation(),O(D===t.id?null:t.id)},title:f(`build.scriptsTab.logs`,`Logs`),children:s(T,{className:`h-4 w-4`})}),s(q,{variant:`ghost`,onClick:e=>{e.stopPropagation(),H.mutate({blockId:t.id,enabled:!t.enabled})},disabled:r,title:t.enabled?f(`common.disable`,`Disable`):f(`common.enable`,`Enable`),children:t.enabled?f(`common.disable`,`Disable`):f(`common.enable`,`Enable`)}),s(q,{variant:`ghost`,onClick:e=>{e.stopPropagation(),C({title:f(`build.scriptsTab.deleteThisScript`,`Delete this script?`),message:f(`build.scriptsTab.deleteMessage`,`{{name}} and its source will be deleted. This cannot be undone.`,{name:t.name}),confirmLabel:f(`common.delete`,`Delete`),variant:`danger`}).then(e=>{e&&V.mutate(t.id)})},title:f(`common.delete`,`Delete`),children:s(z,{className:`h-4 w-4`})})]})}}],[C,D,n,y,V,U.isPending,U.variables,H,f]),oe=()=>{F.reset(),R.reset(),U.reset(),S(null),b(),n?.(null)},se=w===null?null:W.find(e=>e.id===w)??(x!==null&&x.id===w?x:null),ce=se===null?null:s(pi,{subject:zi(se),subjectKey:se.id,saving:I.isPending,error:I.error===null?null:oh(I.error),onSave:e=>I.mutate({block:se,values:e}),onClose:()=>{I.reset(),E(null)}});return A?e(h,{children:[s(`div`,{className:`flex min-h-0 flex-1 flex-col`,"data-testid":`script-editor-panel`,children:s(th,{existing:ie,typeDefs:j.data,typeDefsLoading:j.isLoading,saving:ne,saveError:re,restarting:U.isPending,restartError:U.error===null?null:oh(U.error),onRestart:ie===null?void 0:()=>U.mutate(ie.id),onSave:e=>{let t=ie;t===null?F.mutate(e):R.mutate({blockId:t.id,block:e})},onCancel:oe,title:ie===null?f(`build.scriptsTab.newScript`,`New script`):f(`build.scriptsTab.edit`,`Edit {{name}}`,{name:ie.name}),onQuickEdit:ie===null?void 0:()=>E(ie.id)})}),ce]}):e(`div`,{className:`space-y-3`,children:[s(`p`,{className:`text-xs text-foreground-subtle`,children:k.data===void 0?``:Ou(W)}),k.error!=null&&s(J,{title:f(`build.scriptsTab.couldNotReadTheScripts`,`Could not read the scripts`),message:oh(k.error),onRetry:M}),s(gn,{section:`scripts`,getTags:ai,searchText:oi,searchLabel:f(`build.scriptsTab.search`,`Search scripts`),columns:ae,rows:W,rowKey:e=>e.id,pageSize:25,maxBodyHeight:Ct,emptyMessage:G?f(`build.scriptsTab.noScriptsYetAScript`,`No scripts yet. A script is TypeScript the hub runs in its own process.`):k.data===void 0?f(`build.scriptsTab.loadingScripts`,`Loading scripts…`):f(`build.scriptsTab.noScriptsYet`,`No scripts yet.`),onRowClick:e=>{S(e),y(e.id),n?.(e.id)}}),ce,V.error!=null&&s(J,{message:oh(V.error)}),H.error!=null&&s(J,{message:oh(H.error)}),U.error!=null&&s(J,{message:oh(U.error)})]})}function ch({draft:e,saving:t,error:n,onSave:r,onClose:i,onQuickEdit:a}){let{t:o}=Q(),c=Vr(e,t);return s(Bi,{testId:`remote-template-editor`,icon:lt,title:e.id===null?o(`remote.templates.newTitle`):c.name.trim()===``?o(`remote.templates.editTitle`):c.name,onClose:i,onQuickEdit:a,headerActions:s(qr,{editor:c}),onSave:()=>{let e=c.toDraft();e!==null&&r(e)},saveDisabled:!c.canSave,saving:t,saveTestId:`template-save`,children:s(Wr,{editor:c,draftId:e.id,error:n})})}function lh(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function uh(e){return lh(e)&&typeof e.kind==`string`}function dh(e){let t=e.actions;return uh(e.when)&&Array.isArray(t)&&t.every(uh)}function fh(e){return dh(e)?e:null}function ph(e){return{...e}}var mh=[`device-becomes`,`device-event`,`device-fired`,`device-is`,`stationary-present`],hh=[`version`,`deviceId`];function gh(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function _h(e){let t=e.kind;return typeof t==`string`?t:void 0}function vh(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function yh(e){return e.map(String).join(`.`)}function bh(e){let t=e.replace(/[^A-Za-z0-9]+/g,` `).trim().split(` `).filter(e=>e!==``).map((e,t)=>(t===0?e.charAt(0).toLowerCase():e.charAt(0).toUpperCase())+e.slice(1)).join(``);return(/^[A-Za-z]/.test(t)?t:`input${t}`).slice(0,40)}function xh(e){return oe.test(e)}function Sh(e,t){let n=xh(t)?t:bh(t),r=new Set(e.map(e=>e.key));if(!r.has(n))return n;for(let e=2;e<100;e+=1){let t=`${n.slice(0,37)}${String(e)}`;if(!r.has(t))return t}return n}function Ch(e,t,n){if(Array.isArray(e)){e.forEach((e,r)=>Ch(e,[...t,r],n));return}if(!gh(e))return;let r=_h(e);r!==void 0&&mh.includes(r)&&n.push({path:[...t,`deviceId`],kind:`device`,where:r,keyHint:`device`,labelHint:`Device`}),r===`device-fired`&&n.push({path:t,kind:`event`,where:r,keyHint:`event`,labelHint:`Event`}),r===`command`&&(n.push({path:[...t,`target`],kind:`device`,as:`target`,multiple:!0,where:r,keyHint:`targets`,labelHint:`Devices`}),n.push({path:t,kind:`action`,where:r,keyHint:`action`,labelHint:`Action`}));for(let[i,a]of Object.entries(e)){if(typeof a==`number`&&Number.isFinite(a)&&!hh.includes(i)){n.push({path:[...t,i],kind:i===`seconds`?`duration`:`number`,where:r??i,current:a,keyHint:i,labelHint:i===`seconds`?`Seconds`:i});continue}Ch(a,[...t,i],n)}}function wh(e,t){let n=[];Ch(e,[],n);let r=t.flatMap(e=>e.kind===`value`?[e.path]:[]);return n.filter(e=>!r.some(t=>vh(t,e.path))).map(e=>({id:`${yh(e.path)}:${e.kind}`,path:e.path,kind:e.kind,where:e.where,suggestedKey:e.keyHint,suggestedLabel:e.labelHint,...e.as===void 0?{}:{as:e.as},...e.multiple===void 0?{}:{multiple:e.multiple},...e.current===void 0?{}:{current:e.current}}))}function Th(e,t){let n={key:t.key,label:t.label,...t.optional?{optional:!0}:{}};switch(e.kind){case`device`:return{kind:`device`,...n,...e.multiple===!0?{multiple:!0}:{}};case`event`:return{kind:`event`,...n,deviceInput:t.deviceInput??``};case`action`:return{kind:`action`,...n,...t.deviceInput===void 0||t.deviceInput===``?{}:{deviceInput:t.deviceInput}};case`duration`:return{kind:`duration`,...n,...e.current===void 0?{}:{default:Math.max(0,e.current)}};case`number`:return{kind:`number`,...n,...e.current===void 0?{}:{default:e.current}}}}function Eh(e,t,n){if(!xh(n.key))return`key`;if(e.inputs.some(e=>e.key===n.key))return`key-taken`;if(n.label.trim()===``)return`label`;if(t.kind===`event`){let t=e.inputs.find(e=>e.key===n.deviceInput);if(t===void 0||t.kind!==`device`)return`device-input`}return null}function Dh(e,t,n){let r={kind:`value`,input:n.key,path:[...t.path],...t.as===void 0?{}:{as:t.as}};return{...e,inputs:[...e.inputs,Th(t,{...n,label:n.label.trim()})],bindings:[...e.bindings,r]}}function Oh(e,t){return{...e,inputs:e.inputs.filter(e=>e.key!==t),bindings:e.bindings.filter(e=>e.input!==t)}}function kh(e,t,n){return{...e,inputs:e.inputs.map(e=>e.key===t?n:e)}}var Ah=(e,t)=>t in e;function jh(e,t){return Ah(t,`optional`)?t.optional===!0?{optional:!0}:{}:e.optional===!0?{optional:!0}:{}}function Mh(e,t,n,r){return Ah(e,t)?r(e[t]):n}var Nh=e=>typeof e==`number`?e:void 0,Ph=e=>typeof e==`string`&&e!==``?e:void 0,Fh=e=>typeof e==`boolean`?e:void 0;function Ih(e,t){let n=t.label??e.label,r={key:e.key,label:n,...jh(e,t)},i=e.description===void 0?{}:{description:e.description};switch(e.kind){case`number`:case`duration`:{let n=Mh(t,`min`,e.min,Nh),a=Mh(t,`max`,e.max,Nh),o=Mh(t,`default`,e.default,Nh);return{kind:e.kind,...r,...i,...n===void 0?{}:{min:n},...a===void 0?{}:{max:a},...o===void 0?{}:{default:o}}}case`text`:{let n=Mh(t,`default`,e.default,Ph);return{kind:`text`,...r,...i,...e.maxLength===void 0?{}:{maxLength:e.maxLength},...n===void 0?{}:{default:n}}}case`time-window`:return{kind:`time-window`,...r,...i};case`entries`:return{kind:`entries`,...r,...i,entry:e.entry,allow:e.allow,...e.maxItems===void 0?{}:{maxItems:e.maxItems}};case`boolean`:{let n=Mh(t,`default`,e.default,Fh);return{kind:`boolean`,...r,...i,...n===void 0?{}:{default:n}}}case`select`:{let n=t.options===void 0||t.options.length===0?e.options:[...t.options],a=Mh(t,`default`,e.default,Ph);return{kind:`select`,...r,...i,options:n,...a===void 0?{}:{default:a}}}case`device`:{let n=Ah(t,`capability`)?Ph(t.capability):e.filter?.capability,a=Ah(t,`role`)?Ph(t.role):e.filter?.role,o={...n===void 0?{}:{capability:n},...a===void 0?{}:{role:a}};return{kind:`device`,...r,...i,...e.multiple===!0?{multiple:!0}:{},...Object.keys(o).length===0?{}:{filter:o}}}case`event`:return{kind:`event`,...r,...i,deviceInput:t.deviceInput??e.deviceInput};case`action`:{let n=Ah(t,`deviceInput`)?Ph(t.deviceInput):e.deviceInput;return{kind:`action`,...r,...i,...n===void 0?{}:{deviceInput:n}}}}}function Lh(e){return e.map(e=>`${e.value} = ${e.label}`).join(`
|
|
41
|
-
`)}function Rh(e){return e.split(`
|
|
42
|
-
`).map(e=>e.trim()).filter(e=>e!==``).map(e=>{let t=e.indexOf(`=`),n=(t<0?e:e.slice(0,t)).trim(),r=(t<0?e:e.slice(t+1)).trim();return{value:n,label:r===``?n:r}}).filter(e=>e.value!==``)}d();function zh({payload:t,readOnly:n,onChange:r}){let{t:i}=Q(),[a,o]=l(null);return e(`div`,{className:`space-y-3`,"data-testid":`template-inputs-panel`,children:[t.inputs.length===0?s(`p`,{className:`text-sm text-foreground-muted`,children:i(`build.templates.noInputs`,`No inputs yet. Mark a field of the automation as an input to ask for it each time.`)}):s(`ul`,{className:`space-y-2`,children:t.inputs.map(c=>e(`li`,{className:`rounded-md border border-border bg-surface p-3`,"data-testid":`template-input-row-${c.key}`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[s(`span`,{className:`min-w-0 flex-1 truncate text-sm font-medium text-foreground`,children:c.label}),s(X,{variant:`neutral`,children:c.kind}),c.optional===!0&&s(X,{variant:`neutral`,children:i(`build.templates.optional`,`Optional`)}),s(`code`,{className:`text-xs text-foreground-subtle`,children:c.key}),c.kind===`group`?s(`span`,{className:`text-xs text-foreground-subtle`,children:i(`build.templates.groupReadOnly`,`Repeatable group — shipped templates only`)}):!n&&e(h,{children:[s(rn,{icon:B,size:`sm`,variant:`ghost`,"aria-label":i(`common.edit`,`Edit`),onClick:()=>o(a===c.key?null:c.key),"data-testid":`template-input-edit-${c.key}`}),s(rn,{icon:z,size:`sm`,variant:`ghost`,"aria-label":i(`common.delete`,`Delete`),onClick:()=>{o(null),r(Oh(t,c.key))},"data-testid":`template-input-remove-${c.key}`})]})]}),c.kind===`group`&&s(`ul`,{className:`mt-2 space-y-0.5 pl-3 text-xs text-foreground-muted`,children:c.inputs.map(t=>e(`li`,{children:[t.label,` `,e(`span`,{className:`text-foreground-subtle`,children:[`(`,t.kind,`)`]})]},t.key))}),a===c.key&&c.kind!==`group`&&s(Vh,{input:c,deviceInputs:t.inputs.filter(e=>e.kind===`device`),onChange:e=>r(kh(t,c.key,e))})]},c.key))}),!n&&s(Wh,{payload:t,onChange:r})]})}function Bh(e){if(e===``)return;let t=Number(e);return Number.isNaN(t)?void 0:t}function Vh({input:t,deviceInputs:n,onChange:r}){let{t:i}=Q();return e(`div`,{className:`mt-3 grid gap-3 sm:grid-cols-2`,"data-testid":`template-input-editor-${t.key}`,children:[s(zn,{label:i(`build.templates.label`,`Label`),children:s(Y,{value:t.label,maxLength:80,onChange:e=>r(Ih(t,{label:e.target.value})),"data-testid":`template-input-label`})}),s(zn,{label:i(`build.templates.requiredField`,`Required`),children:s(on,{checked:t.optional!==!0,onCheckedChange:e=>r(Ih(t,{optional:!e})),label:i(`build.templates.requiredField`,`Required`),"data-testid":`template-input-required`})}),(t.kind===`number`||t.kind===`duration`)&&e(h,{children:[s(zn,{label:i(`build.templates.min`,`Minimum`),children:t.kind===`duration`?s(`span`,{"data-testid":`template-input-min`,children:s(Qu,{value:t.min,"aria-label":i(`build.templates.min`,`Minimum`),onChange:e=>r(Ih(t,{min:e}))})}):s(Y,{type:`number`,value:t.min===void 0?``:String(t.min),onChange:e=>r(Ih(t,{min:Bh(e.target.value)})),"data-testid":`template-input-min`})}),s(zn,{label:i(`build.templates.max`,`Maximum`),children:t.kind===`duration`?s(`span`,{"data-testid":`template-input-max`,children:s(Qu,{value:t.max,"aria-label":i(`build.templates.max`,`Maximum`),onChange:e=>r(Ih(t,{max:e}))})}):s(Y,{type:`number`,value:t.max===void 0?``:String(t.max),onChange:e=>r(Ih(t,{max:Bh(e.target.value)})),"data-testid":`template-input-max`})}),s(zn,{label:i(`build.templates.default`,`Default`),children:t.kind===`duration`?s(`span`,{"data-testid":`template-input-default`,children:s(Qu,{value:t.default,"aria-label":i(`build.templates.default`,`Default`),onChange:e=>r(Ih(t,{default:e}))})}):s(Y,{type:`number`,value:t.default===void 0?``:String(t.default),onChange:e=>r(Ih(t,{default:Bh(e.target.value)})),"data-testid":`template-input-default`})})]}),t.kind===`text`&&s(zn,{label:i(`build.templates.default`,`Default`),children:s(Y,{value:t.default??``,onChange:e=>r(Ih(t,{default:e.target.value===``?void 0:e.target.value}))})}),t.kind===`boolean`&&s(zn,{label:i(`build.templates.default`,`Default`),children:s(on,{checked:t.default===!0,onCheckedChange:e=>r(Ih(t,{default:e})),label:i(`build.templates.default`,`Default`)})}),t.kind===`select`&&s(zn,{label:i(`build.templates.options`,`Options`),description:i(`build.templates.optionsHint`,`One per line: value = label`),className:`sm:col-span-2`,children:s(Hh,{options:t.options,onChange:e=>r(Ih(t,{options:e}))})}),t.kind===`device`&&e(h,{children:[s(zn,{label:i(`build.templates.filterCapability`,`Only devices with capability`),children:s(Y,{value:t.filter?.capability??``,onChange:e=>r(Ih(t,{capability:e.target.value})),"data-testid":`template-input-filter-capability`})}),s(zn,{label:i(`build.templates.filterRole`,`Only devices of type`),children:s(Y,{value:t.filter?.role??``,onChange:e=>r(Ih(t,{role:e.target.value}))})})]}),(t.kind===`event`||t.kind===`action`)&&s(zn,{label:i(`build.templates.readsDevice`,`Reads the device input`),children:s(A,{value:t.deviceInput??``,options:[...t.kind===`action`?[{value:``,label:i(`build.templates.anyAction`,`Any action`)}]:[],...n.map(e=>({value:e.key,label:e.label}))],onChange:e=>r(Ih(t,{deviceInput:e.target.value}))})})]})}function Hh({options:e,onChange:t}){let[n,r]=l(()=>Lh(e));return s(Ln,{rows:4,value:n,onChange:e=>{r(e.target.value),t(Rh(e.target.value))},"data-testid":`template-input-options`})}function Uh(e,t){return`${{device:t(`build.templates.kindDevice`,`Device`),event:t(`build.templates.kindEvent`,`Event`),action:t(`build.templates.kindAction`,`Action`),duration:t(`build.templates.kindDuration`,`Duration`),number:t(`build.templates.kindNumber`,`Number`)}[e.kind]} — ${e.where} · ${e.path.map(String).join(`.`)}`}function Wh({payload:t,onChange:n}){let{t:r}=Q(),a=i(()=>wh(t.body,t.bindings),[t.body,t.bindings]),[o,c]=l(``),[u,d]=l(``),[f,p]=l(!1),[m,g]=l(``),_=a.find(e=>e.id===o),v=t.inputs.filter(e=>e.kind===`device`),y=_?.kind===`event`;if(a.length===0)return s(`p`,{className:`text-xs text-foreground-subtle`,"data-testid":`template-nothing-to-mark`,children:r(`build.templates.nothingToMark`,`Every field that can be an input already is.`)});let b=_===void 0?null:{key:Sh(t.inputs,bh(u===``?_.suggestedKey:u)),label:u.trim()===``?_.suggestedLabel:u.trim(),optional:f,..._.kind===`event`||_.kind===`action`?{deviceInput:m===``?v[0]?.key:m}:{}},x=_===void 0||b===null?`field`:Eh(t,_,b);return e(`div`,{className:`space-y-3 rounded-md border border-dashed border-border p-3`,"data-testid":`template-mark-as-input`,children:[s(`p`,{className:`text-sm font-medium text-foreground`,children:r(`build.templates.markAsInput`,`Mark as input`)}),e(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[s(zn,{label:r(`build.templates.markField`,`Field`),className:`sm:col-span-2`,children:s(A,{value:o,options:[{value:``,label:r(`build.templates.pickField`,`Choose a field of the automation…`)},...a.map(e=>({value:e.id,label:Uh(e,r)}))],onChange:e=>{c(e.target.value),d(``)},"data-testid":`template-mark-field`})}),_!==void 0&&e(h,{children:[s(zn,{label:r(`build.templates.label`,`Label`),children:s(Y,{value:u,placeholder:_.suggestedLabel,maxLength:80,onChange:e=>d(e.target.value),"data-testid":`template-mark-label`})}),s(zn,{label:r(`build.templates.requiredField`,`Required`),children:s(on,{checked:!f,onCheckedChange:e=>p(!e),label:r(`build.templates.requiredField`,`Required`)})}),(_.kind===`event`||_.kind===`action`)&&s(zn,{label:r(`build.templates.readsDevice`,`Reads the device input`),...y&&v.length===0?{error:r(`build.templates.markDeviceFirst`,`Mark the device as an input first.`)}:{},children:s(A,{value:m===``?v[0]?.key??``:m,options:[..._.kind===`action`?[{value:``,label:r(`build.templates.anyAction`,`Any action`)}]:[],...v.map(e=>({value:e.key,label:e.label}))],onChange:e=>g(e.target.value)})})]})]}),e(q,{size:`sm`,disabled:x!==null||_===void 0||b===null,onClick:()=>{_===void 0||b===null||x!==null||(n(Dh(t,_,b)),c(``),d(``),p(!1))},"data-testid":`template-mark-add`,children:[s(j,{className:`h-3.5 w-3.5`,"aria-hidden":!0}),r(`build.templates.addInput`,`Add input`)]})]})}d();function Gh(e,t){let n=URL.createObjectURL(new Blob([t],{type:`application/json`})),r=document.createElement(`a`);r.href=n,r.download=e,r.click(),URL.revokeObjectURL(n)}function Kh(e){let t=e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``);return`${t===``?`automation-template`:t}.json`}function qh({template:t,saving:n,error:r,onSave:a,onDuplicate:o,onClose:u,onQuickEdit:d}){let{t:f}=Q(),p=t.builtIn,[m,g]=l(t.name);c(()=>g(t.name),[t.name]);let[_,v]=l(t.payload),y=Hr(),b=i(()=>fh(_.body),[_.body]),x=i(()=>ye.safeParse(_),[_]),S=!p&&m.trim()!==``&&x.success&&!n,C=e=>v({..._,body:ph(Bo(e))}),w=()=>({id:t.id,kind:`automation`,name:m.trim(),payload:_,...t.tags===void 0?{}:{tags:t.tags}}),T=e(h,{children:[!p&&!x.success&&s(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:x.error.issues[0]?.message??``}),r!==null&&s(`p`,{role:`alert`,className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:r})]});return e(Bi,{testId:`automation-template-editor`,icon:dt,title:t.id===null?f(`build.templates.newAutomationTemplate`,`New automation template`):m,badges:p?s(X,{variant:`neutral`,"data-testid":`template-builtin-badge`,children:f(`build.templates.builtIn`,`Built-in`)}):null,onClose:u,onQuickEdit:p?void 0:d,onSave:p?void 0:()=>a(w()),saveDisabled:!S,saving:n,saveTestId:`template-save`,notices:T,footerActions:e(h,{children:[p&&e(q,{onClick:()=>o(w()),"data-testid":`template-duplicate`,children:[s(M,{className:`h-4 w-4`,"aria-hidden":!0}),f(`remote.templates.duplicate`,`Duplicate`)]}),e(q,{variant:`outline`,disabled:!x.success,onClick:()=>{x.success&&Gh(Kh(m),JSON.stringify(me(m.trim(),x.data),null,2))},"data-testid":`template-export`,children:[s(V,{className:`h-4 w-4`,"aria-hidden":!0}),f(`build.templates.exportJson`,`Export JSON`)]})]}),side:s(zt,{headingId:`template-inputs`,title:f(`build.templates.inputs`,`Inputs`),children:s(`div`,{className:`p-3`,children:s(zh,{payload:_,readOnly:p,onChange:v})})}),children:[p&&s(`p`,{className:`text-xs text-foreground-muted`,children:f(`build.templates.builtInHint`,`Shipped with CamStack and read-only. Duplicate it to make a copy you can change.`)}),e(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[s(zn,{label:f(`remote.templates.name`,`Name`),children:s(Y,{value:m,maxLength:120,disabled:p,onChange:e=>g(e.target.value),"data-testid":`template-name`})}),s(zn,{label:f(`build.templates.description`,`Description`),children:s(Ln,{rows:2,value:_.description??``,disabled:p,maxLength:500,onChange:e=>{let{description:t,...n}=_;v(e.target.value===``?n:{...n,description:e.target.value})},"data-testid":`template-description`})})]}),s(zt,{headingId:`template-body`,title:f(`build.templates.body`,`Automation`),children:s(`div`,{className:`space-y-4 p-3`,"data-testid":`template-body-editor`,children:b===null?s(`pre`,{className:`max-h-96 overflow-auto rounded bg-surface-hover p-3 text-xs`,children:JSON.stringify(_.body,null,2)}):s(`div`,{className:`space-y-4`,inert:p,children:e(Go,{when:b.when,children:[e(`div`,{children:[s(`p`,{className:`mb-1 text-xs font-medium uppercase text-foreground-subtle`,children:f(`automation.automationEditor.when`,`When`)}),s(il,{recipe:b,devices:y,onChange:C})]}),e(`div`,{children:[s(`p`,{className:`mb-1 text-xs font-medium uppercase text-foreground-subtle`,children:f(`automation.automationEditor.then`,`Then`)}),s(Pl,{flowControl:!0,actions:b.actions,devices:y,onChange:e=>C(Za(b,e))})]}),e(`div`,{children:[s(`p`,{className:`mb-1 text-xs font-medium uppercase text-foreground-subtle`,children:f(`flow.runMode.title`,`Overlap`)}),s(hu,{value:du(b),onChange:e=>C(fu(b,e))})]})]})})})})]})}d();function Jh(e){let t=ye.safeParse(e.payload);return t.success?{id:e.id,name:e.name,payload:t.data,builtIn:e.builtIn===!0,tags:e.tags??[]}:null}function Yh(e,t){return[...e.devices.length===0?[]:[t(`remote.templates.inUseMessage`,{devices:e.devices.map(e=>e.name).join(`, `)})],...e.automations.length===0?[]:[t(`build.templates.inUseAutomations`,{automations:e.automations.map(e=>e.name).join(`, `)})]]}function Xh({createRequested:t=!1,onCreateConsumed:n}){let{t:r}=Q(),a=p(),o=tr(),u=Wn({}),d=hn(),[f,m]=l(null),g=Fr({onCreated:m}),_=tn(),y=ee(),b=I(),[x,S]=l(null),[C,w]=l(null),[T,E]=l(!1),[D,O]=$n(),k=D.get(rr),A=e=>{if(g.clearError(),e.kind===`automation`){S(null),w(Jh(e));return}w(null),S({id:e.id,kind:e.kind,name:e.name,payload:e.payload,tags:e.tags??[]})};c(()=>{t&&(E(!0),n?.())},[t,n]),c(()=>{if(k===null||u.data===void 0)return;let e=u.data.find(e=>e.id===k);e!==void 0&&A(e),O(e=>{let t=new URLSearchParams(e);return t.delete(rr),t},{replace:!0})},[k,u.data,O]);let N=async(e,t)=>{await g.save(Ri(e,t))&&(m(null),w(n=>n?.id===e.id?{...n,name:t.name,tags:t.tags}:n),S(n=>n?.id===e.id?{...n,name:t.name,tags:t.tags}:n))},F=()=>void a.invalidateQueries({queryKey:[[`template`]]}),L=async e=>{await g.save(e)&&(S(null),w(null))},R=async e=>{try{let t=await d.mutateAsync({kind:e.kind,name:r(`remote.templates.copyName`,{name:e.name}),payload:e.payload});return F(),t.status===`saved`?t.template.id:null}catch(e){return await b({title:r(`remote.templates.duplicateFailed`),message:e instanceof Error?e.message:String(e),variant:`danger`}),null}},V=async e=>{let t=u.data?.find(t=>t.id===e.id);t!==void 0&&await R(t)!==null&&w(null)},te=async e=>{if(await y({title:r(`remote.templates.deleteTitle`,{name:e.name}),message:r(`remote.templates.deleteMessage`),confirmLabel:r(`common.delete`),variant:`danger`}))try{let t=await _.mutateAsync({id:e.id});if(t.status===`in-use`){await b({title:r(`remote.templates.inUseTitle`,{name:e.name}),message:Yh(t,r).join(` `),variant:`warning`});return}if(t.status===`read-only`){await b({title:r(`build.templates.readOnlyTitle`,{name:e.name}),message:r(`build.templates.readOnlyMessage`),variant:`warning`});return}F()}catch(e){await b({title:r(`remote.templates.deleteFailed`),message:e instanceof Error?e.message:String(e),variant:`danger`})}},H=i(()=>[{key:`name`,header:r(`remote.templates.name`),sortValue:e=>e.name.toLowerCase(),render:t=>e(`span`,{className:`flex flex-wrap items-center gap-2`,children:[s(`span`,{className:`font-medium text-foreground`,children:t.name}),t.builtIn===!0&&s(X,{variant:`neutral`,children:r(`build.templates.builtIn`,`Built-in`)})]})},{key:`kind`,header:r(`remote.templates.kind.label`),sortValue:e=>e.kind,render:e=>s(X,{variant:`neutral`,children:Gr(e.kind).label(r)})},{key:`summary`,header:r(`remote.templates.summary`),notSortableReason:`A sentence built from the payload.`,render:e=>s(`span`,{className:`text-foreground-muted`,children:Gr(e.kind).summary(e.payload,r)})},{key:`updated`,header:r(`remote.templates.updated`),sortValue:e=>e.updatedAt,render:e=>s(`span`,{className:`text-foreground-muted`,children:e.builtIn===!0?``:new Date(e.updatedAt).toLocaleDateString()})},{key:`actions`,align:`right`,notSortableReason:`Row actions.`,render:e=>s(Cn,{title:r(`remote.templates.actionsFor`,{name:e.name}),items:[...e.kind===`automation`?[{id:`create-automation`,label:r(`build.templates.createAutomation`,`Create automation`),icon:v,onClick:()=>void o(`/build?tab=automations&${Hd}=${encodeURIComponent(e.id)}`)}]:[],{id:`edit`,label:e.builtIn===!0?r(`build.templates.view`,`View`):r(`common.edit`),icon:B,onClick:()=>A(e)},...e.builtIn===!0?[]:[{id:`quick-edit`,label:r(`build.quickEdit.action`,`Quick edit`),icon:P,onClick:()=>{g.clearError(),m(e.id)}}],{id:`duplicate`,label:r(`remote.templates.duplicate`),icon:M,onClick:()=>void R(e)},...e.builtIn===!0?[]:[{id:`delete`,label:r(`common.delete`),icon:z,danger:!0,onClick:()=>void te(e)}]]})}],[r]),U=u.data??[],W=f===null?null:U.find(e=>e.id===f)??null,G=W===null?null:s(pi,{subject:zi(W),subjectKey:W.id,saving:g.saving,error:g.error,onSave:e=>void N(W,e),onClose:()=>{g.clearError(),m(null)}}),ne=e=>e===null?void 0:()=>m(e);return x===null?C===null?e(`div`,{className:`space-y-3`,children:[s(`p`,{className:`text-xs text-foreground-subtle`,children:r(`remote.templates.subtitle`)}),u.status===`error`?s(J,{title:r(`remote.templates.loadFailed`),message:u.error.message,onRetry:()=>void u.refetch()}):u.data===void 0?s(Un,{className:`h-32 w-full`}):U.length===0?s(pt,{icon:lt,title:r(`remote.templates.emptyTitle`),description:r(`remote.templates.emptyDescription`),action:s(q,{size:`sm`,onClick:()=>E(!0),children:r(`remote.templates.new`)})}):s(gn,{section:`templates`,getTags:di,searchText:fi,searchLabel:r(`build.templates.search`,`Search templates`),columns:H,rows:U,rowKey:e=>e.id,maxBodyHeight:Ct,defaultSort:{columnKey:`name`,dir:`asc`},onRowClick:A}),G,s(Ft,{open:T,onOpenChange:e=>!e&&E(!1),children:e(Kn,{width:`md`,placement:`sheet-on-mobile`,children:[s(Et,{children:s(Xt,{children:r(`remote.templates.new`)})}),e(qt,{className:`space-y-2`,"data-testid":`new-template-chooser`,children:[e(q,{variant:`outline`,className:`h-auto w-full justify-start whitespace-normal py-2 text-left`,onClick:()=>{g.clearError(),E(!1),S({id:null,kind:`remote`,name:``,payload:Gr(`remote`).emptyPayload()})},"data-testid":`new-template-remote`,children:[s(j,{className:`h-4 w-4 shrink-0`,"aria-hidden":!0}),e(`span`,{className:`block`,children:[s(`span`,{className:`block font-medium`,children:Gr(`remote`).label(r)}),s(`span`,{className:`block text-xs text-foreground-muted`,children:r(`build.templates.newRemoteHint`,`The button layout of a remote.`)})]})]}),e(q,{variant:`outline`,className:`h-auto w-full justify-start whitespace-normal py-2 text-left`,onClick:()=>{g.clearError(),E(!1),w({id:null,name:``,payload:ye.parse(Gr(`automation`).emptyPayload()),builtIn:!1})},"data-testid":`new-template-automation`,children:[s(j,{className:`h-4 w-4 shrink-0`,"aria-hidden":!0}),e(`span`,{className:`block`,children:[s(`span`,{className:`block font-medium`,children:Gr(`automation`).label(r)}),s(`span`,{className:`block text-xs text-foreground-muted`,children:r(`build.templates.newAutomationHint`,`An automation with inputs, so each copy only asks for its devices.`)})]})]})]})]})})]}):e(h,{children:[s(qh,{template:C,saving:g.saving,error:g.error,onSave:e=>void L(e),onDuplicate:e=>void V(e),onClose:()=>w(null),onQuickEdit:ne(C.id)},C.id??`new`),G]}):e(h,{children:[s(ch,{draft:x,saving:g.saving,error:g.error,onSave:e=>void L(e),onClose:()=>S(null),onQuickEdit:ne(x.id)},x.id??`new`),G]})}var Zh=[`automations`,`actions`,`schedulers`,`scripts`,`custom-device`,`templates`];function Qh(e){return e!==null&&Zh.some(t=>t===e)}var $h=[`coreBlocks`,`list`,`build-counts`],eg=[`schedulers`,`list`,`build-counts`],tg=[`actions`,`list`,`build-counts`],ng=[`block`,`action`,`scheduler`,`create`,`new`,`edit`,Hd];function rg(e){return e.filter(e=>Le(e)===`code`&&ti(e)).length}function ig(e){return e.filter(e=>ei(e.code)).length}function ag(e,t){return t===null?e:`${e} (${String(t)})`}function og(){let{t}=Q(),n=te(),[r,i]=$n(),a=r.get(`tab`),o=Qh(a)?a:`automations`,c=r.get(`create`)===`1`,l=u({queryKey:$h,refetchInterval:5e3,queryFn:async()=>(await n.trpcClient.coreBlocks.list.query({})).blocks}).data,d=l===void 0?null:rg(l),f=l===void 0?null:ig(l),p=u({queryKey:tg,refetchInterval:1e4,queryFn:async()=>n.trpcClient.actions.list.query({})}),m=p.data===void 0?null:p.data.length,h=u({queryKey:eg,refetchInterval:1e4,queryFn:async()=>n.trpcClient.schedulers.list.query({})}),g=h.data===void 0?null:h.data.length,_=u({queryKey:[`coreBlocks`,`listCompositions`,`build-counts`],refetchInterval:1e4,queryFn:async()=>n.trpcClient.coreBlocks.listCompositions.query({})}),v=_.data?.state===`loaded`?_.data.views.length:null,y=Wn({}).data?.length??null,b=e=>{i(()=>{let t=new URLSearchParams(window.location.search);return t.set(`tab`,`scripts`),t.delete(`create`),e===void 0?t.delete(`block`):t.set(`block`,e),t},{replace:!0})},x=e=>{i(()=>{let t=new URLSearchParams(window.location.search);return t.set(`tab`,`scripts`),t.delete(`create`),e===null?t.delete(`block`):t.set(`block`,e),t},{replace:!0})},S=()=>{i(e=>{let t=new URLSearchParams(e);return t.set(`create`,`1`),t.delete(`block`),t},{replace:!0})},C=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})},w=()=>{i(()=>{let e=new URLSearchParams(window.location.search);return e.delete(`create`),e},{replace:!0})},T=o===`automations`?t(`build.newAutomation`,`New automation`):o===`actions`?t(`build.newAction`,`New action`):o===`schedulers`?t(`build.newScheduler`,`New scheduler`):o===`templates`?t(`build.newTemplate`,`New template`):t(`build.newScript`,`New script`),E=Xn(`/build`,{t,isAdmin:!0})??{icon:R,title:t(`nav.build`,`Build-your-self`)};return s(ar,{icon:E.icon,title:E.title,subtitle:t(`build.automationsScriptsAndComposedDevices`,`Automations, scripts and composed devices — what this installation does on its own.`),defaultSection:`automations`,sectionsLabel:`${E.title} sections`,fill:!0,actions:o===`custom-device`?e(q,{type:`button`,onClick:()=>C(`helper`),"data-testid":`build-new-composed`,children:[s(j,{className:`h-4 w-4`}),` `,t(`helper.newComposed`)]}):e(q,{type:`button`,onClick:S,"data-testid":`build-new`,children:[s(j,{className:`h-4 w-4`}),` `,T]}),sections:[{id:`automations`,label:ag(t(`build.tabAutomations`,`Automations`),f),ownedParams:ng,content:s(Kd,{onOpenScripts:b,createRequested:o===`automations`&&c,onCreateConsumed:w})},{id:`actions`,label:ag(t(`build.tabActions`,`Actions`),m),ownedParams:ng,content:s(ou,{createRequested:o===`actions`&&c,onCreateConsumed:w})},{id:`schedulers`,label:ag(t(`build.tabSchedulers`,`Schedulers`),g),ownedParams:ng,content:s(df,{createRequested:o===`schedulers`&&c,onCreateConsumed:w})},{id:`scripts`,label:ag(t(`build.tabCode`,`Code`),d),ownedParams:ng,content:s(sh,{initialBlockId:o===`scripts`?r.get(`block`)??void 0:void 0,onBlockIdChange:x,createRequested:o===`scripts`&&c,onCreateConsumed:w})},{id:`custom-device`,label:ag(t(`build.tabCustomDevice`,`Custom Device`),v),ownedParams:ng,content:s(Jf,{createRequested:o===`custom-device`&&c,onCreateConsumed:w})},{id:`templates`,label:ag(t(`build.tabTemplates`,`Templates`),y),ownedParams:ng,content:s(Xh,{createRequested:o===`templates`&&c,onCreateConsumed:w})}]})}export{og as BuildPage};
|