@camstack/addon-admin-ui 1.2.435 → 1.2.436
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{AddonAssetIcon-DwyvMm0j.js → AddonAssetIcon-BPpbpBRb.js} +1 -1
- package/dist/assets/Addons-BKpZvzxZ.js +4 -0
- package/dist/assets/{AdminPage-Dla2hgly.js → AdminPage-Dq8Ikceb.js} +1 -1
- package/dist/assets/{AdminSectionedPage-C6laWV2D.js → AdminSectionedPage-CMXlVHaE.js} +1 -1
- package/dist/assets/AiProfiles-BNa-wvuk.js +3 -0
- package/dist/assets/{BrokerForm-XPsm7VqN.js → BrokerForm-CTEvkdiJ.js} +1 -1
- package/dist/assets/Build-BtwPkUNT.js +40 -0
- package/dist/assets/{Calendars-D9aQ6xfy.js → Calendars-BDEesia0.js} +1 -1
- package/dist/assets/Cluster-CPOYtnsH.js +1 -0
- package/dist/assets/ClusterStepModel-CD3lGILg.js +1 -0
- package/dist/assets/{CompositionEditor-Djw5jKF1.js → CompositionEditor-thMDSEPc.js} +1 -1
- package/dist/assets/CompositionEditorPage-sur0OoTs.js +1 -0
- package/dist/assets/Data-DYZzdYTt.js +2 -0
- package/dist/assets/DeviceDetail-Dfkdbk5S.js +2 -0
- package/dist/assets/{DeviceDoActionFields-DLWA9-J9.js → DeviceDoActionFields-C3Dz4KrE.js} +1 -1
- package/dist/assets/{Devices-C1k3PqRv.js → Devices-xUTbIFJe.js} +1 -1
- package/dist/assets/{EmbedPlayerPage-Dz0lVYTn.js → EmbedPlayerPage-DYCZQ47V.js} +1 -1
- package/dist/assets/Identity-DRemX8Kt.js +1 -0
- package/dist/assets/IntegrationDetail-CVONA8Vu.js +1 -0
- package/dist/assets/IntegrationHub-CKPuIBCW.js +1 -0
- package/dist/assets/{Integrations-B3EhTwi-.js → Integrations-D8689xLx.js} +1 -1
- package/dist/assets/Integrations-RmhoSCir.js +1 -0
- package/dist/assets/{Library-BLUxFISX.js → Library-bvbXCasj.js} +1 -1
- package/dist/assets/Locations-DvnbXzXE.js +3 -0
- package/dist/assets/{Logs-C5wdcV2o.js → Logs-BCis7K87.js} +1 -1
- package/dist/assets/{MaskShapeCanvas-WPSz6MvT.js → MaskShapeCanvas-BDELFcW-.js} +1 -1
- package/dist/assets/{MotionZonesSettings-CxZucl1G.js → MotionZonesSettings-B4Sz3Hxi.js} +1 -1
- package/dist/assets/MyAccess-SjNSbZFI.js +2 -0
- package/dist/assets/Network-BvT1oKui.js +1 -0
- package/dist/assets/{NodeAddonsSettingsPanel-CSyREPja.js → NodeAddonsSettingsPanel-DPOu3bzA.js} +1 -1
- package/dist/assets/Notifications-CdyKO4mW.js +1 -0
- package/dist/assets/{PrivacyMaskSettings-DQ7Xe8cq.js → PrivacyMaskSettings-DHIoMgiM.js} +1 -1
- package/dist/assets/Recordings-DaqBEWTR.js +1 -0
- package/dist/assets/{ScanNetworkModal-Dw7_YiJk.js → ScanNetworkModal-C5ek4_xr.js} +1 -1
- package/dist/assets/{SceneMonitorEditor-CQtUJ-Cg.js → SceneMonitorEditor-BPo9HYQH.js} +1 -1
- package/dist/assets/SessionsList-CLdfIlct.js +2 -0
- package/dist/assets/{Showroom-DZRq9gks.js → Showroom-DNWKiETZ.js} +1 -1
- package/dist/assets/{System-n6EeqhH2.js → System-BEpuTl2A.js} +1 -1
- package/dist/assets/{Terminal-Dt_ribAu.js → Terminal-CZxQeSQv.js} +3 -3
- package/dist/assets/{Viewer-DbBh61dj.js → Viewer-DRzTXkJf.js} +1 -1
- package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-CEvIRFB4.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-C5raVFJt.js} +1 -1
- package/dist/assets/{addon-icons-context-r49093mC.js → addon-icons-context-PT674I68.js} +1 -1
- package/dist/assets/{archive-CgDcyTmT.js → archive-Ciq6-gRM.js} +1 -1
- package/dist/assets/{authed-media-CN55sP4S.js → authed-media-Dj1jG_u8.js} +1 -1
- package/dist/assets/{bell-off-CdHPL528.js → bell-off-BSKweN0I.js} +1 -1
- package/dist/assets/{board-model-DXmUHcnO.js → board-model-5GbhsRIK.js} +1 -1
- package/dist/assets/{boxes-DJvrVSZy.js → boxes-Be_6S2Ig.js} +1 -1
- package/dist/assets/circle-slash-CtNDkZYp.js +1 -0
- package/dist/assets/client-CPwvt_HG.js +358 -0
- package/dist/assets/{cloud-upload-BkTrXwKr.js → cloud-upload-B9nCTjv1.js} +1 -1
- package/dist/assets/crop-D5vMVrdf.js +1 -0
- package/dist/assets/{device-integration-icon-CViPS882.js → device-integration-icon-C31xC4qv.js} +1 -1
- package/dist/assets/device-picker-model-zmV5eDza.js +1 -0
- package/dist/assets/{dist-0P_zMe7Y.js → dist-B6sP5E_m.js} +1 -1
- package/dist/assets/dist-Sy-AM1_J.js +358 -0
- package/dist/assets/{eraser-BCiOGK5K.js → eraser-BIioNznG.js} +1 -1
- package/dist/assets/{hard-drive-download-Df-zlQQG.js → hard-drive-download-B4JsHavv.js} +1 -1
- package/dist/assets/{history-CWpQe6k9.js → history-DjLzg0Rr.js} +1 -1
- package/dist/assets/{hostInit-Cnw529bc.js → hostInit-BwwyWMg1.js} +1 -1
- package/dist/assets/i18n-GaxP0h6E.js +1 -0
- package/dist/assets/{icons-aI8aLvw4.js → icons-4P43FpmR.js} +1 -1
- package/dist/assets/index-i0Y8_-ur.css +2 -0
- package/dist/assets/{index-DkNBNJNl.js → index-tgPOSbne.js} +3 -3
- package/dist/assets/{key-CZcpRn4A.js → key-BMcy7xHz.js} +1 -1
- package/dist/assets/{key-round-BBPO5HDK.js → key-round-C__KHy-x.js} +1 -1
- package/dist/assets/{layers-DLOgDOBH.js → layers-Dbn6yDeS.js} +1 -1
- package/dist/assets/{linked-devices-model-f_SAvOZs.js → linked-devices-model-D8dKG29p.js} +1 -1
- package/dist/assets/{list-ordered-BaNkdvWk.js → list-ordered-CwWFTuog.js} +1 -1
- package/dist/assets/{location-owned-usage-BFxIuzRL.js → location-owned-usage-kz2UtPi1.js} +1 -1
- package/dist/assets/{log-in-CL3_o1dD.js → log-in-D-fa0CNC.js} +1 -1
- package/dist/assets/{memory-stick-CHkvUw7C.js → memory-stick-BNvRqOgn.js} +1 -1
- package/dist/assets/{message-square-plus-CIeWtcNn.js → message-square-plus-yiE3dC2J.js} +1 -1
- package/dist/assets/{mf-entry-bootstrap-0-657dd3ff.js → mf-entry-bootstrap-0-3d7ac4be.js} +2 -2
- package/dist/assets/{mic-off-DS8OGDQW.js → mic-off-Ct9OQSHX.js} +1 -1
- package/dist/assets/{monitor-off-DC9Xug5Z.js → monitor-off-gNZ5sErH.js} +1 -1
- package/dist/assets/{monitor-smartphone-CS_5BZqr.js → monitor-smartphone-B9ZL4epZ.js} +1 -1
- package/dist/assets/mount-zmV5eDza.js +1 -0
- package/dist/assets/{notification-schedule-field-aMkV5LtX.js → notification-schedule-field-91fTFul7.js} +1 -1
- package/dist/assets/{octagon-alert-Cdtac8l_.js → octagon-alert-CkSZIflH.js} +1 -1
- package/dist/assets/{player-overlays-CZXV2ES3.js → player-overlays-CVyuEj4x.js} +1 -1
- package/dist/assets/{recycle-wY_-o-u0.js → recycle-CH0GJM3I.js} +1 -1
- package/dist/assets/remoteEntry-CEVdKgl-.js +1 -0
- package/dist/assets/{scan-eye-A6IBODIs.js → scan-eye-D6obPT9p.js} +1 -1
- package/dist/assets/{scissors-BzZpfzIa.js → scissors-BXMmNEgj.js} +1 -1
- package/dist/assets/{search-x-DqjVJK7_.js → search-x-ByAKuo4f.js} +1 -1
- package/dist/assets/{send-BDCQEx8-.js → send-CholqiEk.js} +1 -1
- package/dist/assets/{settings-2-BBgeb4tF.js → settings-2-3k9hj27t.js} +1 -1
- package/dist/assets/{speaker-Bw_8wVkA.js → speaker-Ca4eeGU9.js} +1 -1
- package/dist/assets/src-D7EY8vSW.js +67 -0
- package/dist/assets/{timer-reset-CNH944ar.js → timer-reset-bq-8RFf6.js} +1 -1
- package/dist/assets/{ungroup-D4fdKtA6.js → ungroup-DMrJzuO_.js} +1 -1
- package/dist/assets/{unlink-BKDNubwr.js → unlink-CgiLXfCU.js} +1 -1
- package/dist/assets/{usb-CU5DhEWn.js → usb-BpqC1Eim.js} +1 -1
- package/dist/assets/{use-scenes-feed-Bk660KRI.js → use-scenes-feed-CtmmYk4L.js} +1 -1
- package/dist/assets/{use-stationary-objects-BVxOU14q.js → use-stationary-objects-DsURgc1b.js} +1 -1
- package/dist/assets/useEventInvalidation-zmV5eDza.js +1 -0
- package/dist/assets/{useNodeUrlSelection-Bg0rHiIl.js → useNodeUrlSelection-nj7EK04j.js} +1 -1
- package/dist/assets/user-round-B0EP32hl.js +1 -0
- package/dist/assets/{user-x-DRzptq94.js → user-x-CpjXT41_.js} +1 -1
- package/dist/assets/{video-CEzO-5-D.js → video-BAANd9N-.js} +1 -1
- package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-DzDhE-1_.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-Bp8_lhik.js} +2 -2
- package/dist/index.html +11 -11
- package/dist/server/addon.js +44 -22
- package/package.json +1 -1
- package/dist/assets/Addons-N1hcMjwi.js +0 -4
- package/dist/assets/AiProfiles-CW5cr9nz.js +0 -3
- package/dist/assets/Build-Dg7gaee7.js +0 -40
- package/dist/assets/Cluster-NV3ZrTk7.js +0 -1
- package/dist/assets/ClusterStepModel-BUROhnKA.js +0 -1
- package/dist/assets/CompositionEditorPage-BNAhOgDE.js +0 -1
- package/dist/assets/Data-Bkq3Cr_h.js +0 -2
- package/dist/assets/DeviceDetail-BR_FSl-i.js +0 -2
- package/dist/assets/Identity-CJN1MNrJ.js +0 -1
- package/dist/assets/IntegrationDetail-DomJ4oV8.js +0 -1
- package/dist/assets/IntegrationHub-BTJM3uSD.js +0 -1
- package/dist/assets/Integrations-w1Zb-AYc.js +0 -1
- package/dist/assets/Locations-5WWzr64x.js +0 -3
- package/dist/assets/MyAccess-2bAujGDI.js +0 -2
- package/dist/assets/Network-DFt5Vib8.js +0 -1
- package/dist/assets/Notifications-KG9O3i8q.js +0 -1
- package/dist/assets/Recordings-BbQTlUaN.js +0 -1
- package/dist/assets/SessionsList-BuiRHWv-.js +0 -2
- package/dist/assets/circle-slash-BvkFL8F1.js +0 -1
- package/dist/assets/client-CVIfL49c.js +0 -358
- package/dist/assets/crop-DUVdBcFC.js +0 -1
- package/dist/assets/device-picker-model-mxypQ5EF.js +0 -1
- package/dist/assets/dist-U5_IP253.js +0 -358
- package/dist/assets/i18n-CmGpgquB.js +0 -1
- package/dist/assets/index-DKqvG7BE.css +0 -2
- package/dist/assets/mount-mxypQ5EF.js +0 -1
- package/dist/assets/remoteEntry-BFNP-i5_.js +0 -1
- package/dist/assets/src-DOs8Kg5s.js +0 -67
- package/dist/assets/useEventInvalidation-mxypQ5EF.js +0 -1
- package/dist/assets/user-round-CYlbEszq.js +0 -1
|
@@ -1,40 +0,0 @@
|
|
|
1
|
-
import{$ as e,B as t,G as n,J as r,L as i,N as a,S as o,T as s,a as c,b as l,q as u,t as d,x as f}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEHpkaJP.js";import{It as p,Ji as m,Nt as h,On as g,Pn as _,Wi as v,_i as y,_n as b,ar as x,di as S,fn as C,ia as w,kn as T,ot as E,pt as D,xr as O,yi as k}from"./player-overlays-CZXV2ES3.js";import{t as A}from"./boxes-DJvrVSZy.js";import{n as j,r as M,t as N}from"./ungroup-D4fdKtA6.js";import{o as P}from"./video-CEzO-5-D.js";import{Dr as F,Fr as I,Ir as L,Lr as R,Mr as z,Nr as B,Or as V,Pr as H,Sr as ee,Ti as te,Wt as ne,fr as re,hr as ie,mr as ae,pr as oe}from"./client-CVIfL49c.js";import{$l as U,Bn as W,Di as se,Dt as ce,Fi as le,Ii as ue,Jl as G,L as de,Ln as fe,Lt as K,Mi as pe,Ni as me,Oi as he,Pi as ge,Pn as _e,Ql as ve,Ti as ye,Tt as be,U as xe,Ut as Se,Wt as Ce,Xl as we,Zl as Te,Zn as Ee,an as De,ar as q,ha as Oe,ki as ke,vt as Ae,z as je}from"./src-DOs8Kg5s.js";import{t as J}from"./i18n-CmGpgquB.js";import{t as Y}from"./useTranslation-D3Is_4B6.js";import{C as Me,L as Ne,U as Pe,X as Fe,Y as X,et as Ie,x as Le}from"./index-DkNBNJNl.js";import{t as Re}from"./AdminSectionedPage-C6laWV2D.js";import{t as ze}from"./DeviceDoActionFields-DLWA9-J9.js";import{E as Be,O as Ve,t as He}from"./CompositionEditor-Djw5jKF1.js";var Ue=`const AUTOMATION_RECIPE =`,We=`// 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 Ge(e){return e.includes(Ue)}function Ke(e){let t=e.indexOf(Ue);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 qe(e){let t=Ke(e);if(t===null)return{ok:!1,reason:J.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:J.t(`helpers.recipeFromCode.badJson`,{detail:t})}}let r=H.safeParse(n);if(!r.success){let e=r.error.issues[0];return{ok:!1,reason:e===void 0?J.t(`helpers.recipeFromCode.schemaMismatch`):J.t(`helpers.recipeFromCode.schemaMismatchAt`,{path:e.path.join(`.`),message:e.message})}}return{ok:!0,recipe:r.data}}function Je(e){let t=Ke(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)}${We}${e.slice(i)}`}e();var Ye=6e4;function Xe(){let e=Oe({projection:`slim`});return n(()=>(e.data??[]).filter(e=>ne(String(e.type))).map(e=>({id:e.id,name:e.name,stableId:e.stableId,type:String(e.type),location:e.location??null})).toSorted((e,t)=>e.name.localeCompare(t.name)),[e.data])}function Ze(e){let t=E();return c({queryKey:[`automation`,`wireable-fields`,e],enabled:e>0,staleTime:Ye,queryFn:async()=>(await t.trpcClient.deviceManager.getWireableFields.query({deviceId:e})).caps})}function Qe(e,t){return e.find(e=>e.cap===t)?.fields??[]}function Z({children:e}){return f(`span`,{className:`mb-1 block text-xs text-foreground-subtle`,children:e})}function $e(e){let t=Ze(e.deviceId);if(t.data!==void 0)return Qe(t.data,e.cap).find(t=>t.path===e.fieldPath)}function et({value:e,devices:t,onChange:n}){let{t:r}=Y(),i=Ze(e.deviceId),a=i.data??[],s=Qe(a,e.cap);return o(l,{children:[o(`label`,{className:`min-w-[10rem] flex-1`,children:[f(Z,{children:r(`automation.fieldPicker.device`,`Device`)}),f(G,{value:String(e.deviceId),onChange:e=>n({deviceId:Number(e.target.value),cap:``,fieldPath:``}),options:[{value:`0`,label:r(`automation.fieldPicker.selectADevice`,`Select a device…`)},...t.map(e=>({value:String(e.id),label:e.name}))]})]}),o(`label`,{className:`min-w-[9rem] flex-1`,children:[f(Z,{children:r(`automation.fieldPicker.capability`,`Capability`)}),f(G,{value:e.cap,disabled:e.deviceId===0,onChange:t=>n({...e,cap:t.target.value,fieldPath:``}),options:[{value:``,label:tt(e.deviceId,a.length,i.isLoading)},...a.map(e=>({value:e.cap,label:e.cap}))]})]}),o(`label`,{className:`min-w-[9rem] flex-1`,children:[f(Z,{children:r(`automation.fieldPicker.field`,`Field`)}),f(G,{value:e.fieldPath,disabled:e.cap===``,onChange:t=>n({...e,fieldPath:t.target.value}),options:[{value:``,label:s.length===0?r(`automation.fieldPicker.noReadableFields`,`No readable fields`):r(`automation.fieldPicker.selectAField`,`Select a field…`)},...s.map(e=>({value:e.path,label:`${e.path} (${e.kind})`}))]})]})]})}function tt(e,t,n){return e===0?J.t(`automation.fieldPicker.pickDeviceFirst`):n?J.t(`automation.fieldPicker.readingDevice`):t===0?J.t(`automation.fieldPicker.noReadableCaps`):J.t(`automation.fieldPicker.selectCap`)}var nt=[`eq`,`ne`,`gt`,`gte`,`lt`,`lte`,`contains`,`in`];function rt(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 nt}}function it(e){switch(e){case`eq`:return J.t(`helpers.recipeParts.op_eq`);case`ne`:return J.t(`helpers.recipeParts.op_ne`);case`gt`:return J.t(`helpers.recipeParts.op_gt`);case`gte`:return J.t(`helpers.recipeParts.op_gte`);case`lt`:return J.t(`helpers.recipeParts.op_lt`);case`lte`:return J.t(`helpers.recipeParts.op_lte`);case`contains`:return J.t(`helpers.recipeParts.op_contains`);default:return J.t(`helpers.recipeParts.op_in`)}}function at(e){return rt(e).map(e=>({value:e,label:it(e)}))}function ot(e){switch(e){case`device-state`:return J.t(`helpers.recipeParts.trigger_device_state`);case`device-event`:return J.t(`helpers.recipeParts.trigger_device_event`);case`schedule`:return J.t(`helpers.recipeParts.trigger_schedule`);default:return J.t(`helpers.recipeParts.trigger_manual`)}}var st={triggers:[],actions:[]};function ct(e){switch(e){case`device-state`:return{kind:e,deviceId:0,cap:``,fieldPath:``};case`device-event`:return{kind:e,category:``};case`schedule`:return{kind:e,cron:`0 30 23 * * *`};default:return{kind:`manual`}}}function lt(e){switch(e){case`wait`:return{kind:e,seconds:5};case`code`:return{kind:e,code:`// runs inside this automation, with ctx in scope
|
|
4
|
-
`};default:return{kind:`cap`,deviceId:0,cap:``,method:``}}}function ut(){return{kind:`condition`,deviceId:0,cap:``,fieldPath:``,operator:`eq`,value:``}}function dt(){return{kind:`expression`,expr:``,bindings:{}}}function ft(e,t,n){return e.map((e,r)=>r===t?n:e)}function pt(e,t){return e.filter((e,n)=>n!==t)}function mt(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=pt(e,t);return[...a.slice(0,i),r,...a.slice(i)]}function ht(e,t){return{...e,triggers:[...t]}}function gt(e,t){return{...e,actions:[...t]}}var _t=[{value:`cap`,labelKey:`automation.actionList.kindCap`},{value:`wait`,labelKey:`automation.actionList.kindWait`},{value:`code`,labelKey:`automation.actionList.kindCode`}];function vt({actions:e,devices:t,devicesState:n=`answered`,onChange:r}){let{t:i}=Y();return o(`div`,{className:`space-y-2`,children:[e.length===0&&f(`p`,{className:`text-xs text-warning`,children:i(`automation.actionList.noActionsYetAnAutomation`,`No actions yet. An automation that does nothing is not an automation.`)}),e.map((a,s)=>o(`div`,{className:`rounded border border-border p-3 space-y-2`,children:[o(`div`,{className:`flex flex-wrap items-end gap-2`,children:[f(q,{variant:`default`,children:s+1}),o(`label`,{className:`w-40`,children:[f(Z,{children:i(`automation.actionList.step`,`Step`)}),f(G,{value:a.kind,onChange:t=>r(ft(e,s,lt(yt(t.target.value)))),options:_t.map(e=>({value:e.value,label:i(e.labelKey)}))})]}),o(`div`,{className:`ml-auto flex items-center gap-1`,children:[f(W,{variant:`ghost`,disabled:s===0,onClick:()=>r(mt(e,s,s-1)),title:i(`automation.actionList.runThisStepEarlier`,`Run this step earlier`),children:f(v,{className:`h-3.5 w-3.5`})}),f(W,{variant:`ghost`,disabled:s===e.length-1,onClick:()=>r(mt(e,s,s+1)),title:i(`automation.actionList.runThisStepLater`,`Run this step later`),children:f(m,{className:`h-3.5 w-3.5`})}),f(W,{variant:`ghost`,onClick:()=>r(pt(e,s)),title:i(`automation.actionList.removeThisStep`,`Remove this step`),children:f(p,{className:`h-3.5 w-3.5`})})]})]}),a.kind===`wait`&&o(`label`,{className:`block w-32`,children:[f(Z,{children:i(`automation.actionList.seconds`,`Seconds`)}),f(U,{type:`number`,min:0,max:300,value:String(a.seconds),onChange:t=>r(ft(e,s,{kind:`wait`,seconds:Number(t.target.value)}))})]}),a.kind===`code`&&o(`label`,{className:`block`,children:[f(Z,{children:i(`automation.actionList.code`,`Code`)}),f(`textarea`,{className:`h-32 w-full rounded-md border border-border bg-surface p-2 font-mono text-xs text-foreground focus:outline-none focus:ring-1 focus:ring-primary`,value:a.code,spellCheck:!1,onChange:t=>r(ft(e,s,{kind:`code`,code:t.target.value}))}),f(`span`,{className:`mt-1 block text-xs text-foreground-subtle`,children:f(X,{i18nKey:`automation.actionList.codeHint`,components:{code:f(`code`,{})}})})]}),a.kind===`cap`&&f(xt,{action:a,devices:t,devicesState:n,onChange:t=>r(ft(e,s,t))})]},`${a.kind}-${String(s)}`)),o(`div`,{className:`flex items-center gap-2`,children:[o(W,{variant:`outline`,onClick:()=>r([...e,lt(`cap`)]),children:[f(g,{className:`h-4 w-4`}),` `,i(`automation.actionList.addStep`)]}),e.length>1&&f(`span`,{className:`text-xs text-foreground-subtle`,children:i(`automation.actionList.stepsRunInOrderAnd`,`Steps run in order and stop at the first failure.`)})]})]})}function yt(e){return _t.find(t=>t.value===e)?.value??`cap`}function bt(e){return typeof e==`number`?e:typeof e==`object`&&e&&`$var`in e?{$var:e.$var}:[...e]}function xt({action:e,devices:t,devicesState:n,onChange:r}){return f(ze,{value:e,allowTriggerDevice:!0,allowMultiSameFamily:!0,devices:t,listState:n,onChange:e=>r({kind:`cap`,deviceId:bt(e.deviceId),cap:e.cap,method:e.method,...e.args===void 0?{}:{args:{...e.args}}})})}function St({value:e,field:t,onChange:n}){let{t:r}=Y();return t?.kind===`boolean`?f(G,{value:e===!0?`true`:`false`,onChange:e=>n(e.target.value===`true`),options:[{value:`true`,label:r(`common.true`)},{value:`false`,label:r(`common.false`)}]}):t?.kind===`enum`&&t.enumValues!==void 0&&t.enumValues.length>0?f(G,{value:String(e),onChange:e=>n(e.target.value),options:t.enumValues.map(e=>({value:e,label:e}))}):t?.kind===`number`?f(U,{type:`number`,value:typeof e==`number`?String(e):``,placeholder:`0`,onChange:e=>{let t=Number(e.target.value);e.target.value!==``&&!Number.isNaN(t)&&n(t)}}):f(U,{value:String(e),placeholder:r(`common.valueWord`),onChange:e=>n(e.target.value)})}function Ct({value:e,field:t,onChange:n}){let{t:r}=Y();return f(U,{value:e.join(`, `),placeholder:r(`automation.valueInput.oneTwoThree`,`one, two, three`),onChange:e=>{let r=e.target.value.split(`,`).map(e=>e.trim()).filter(e=>e!==``);n(t?.kind===`number`?r.map(e=>Number(e)).filter(e=>!Number.isNaN(e)):r)}})}function wt(e){return typeof e==`object`}function Tt(e){return wt(e)?e[0]??``:e}function Et(e){return wt(e)?e:typeof e==`boolean`?[]:[e]}function Dt({leaf:e,devices:t,onChange:n}){let{t:r}=Y(),i={deviceId:e.deviceId,cap:e.cap,fieldPath:e.fieldPath},a=$e(i),s=at(a?.kind),c=e.operator===`in`,l=t=>{n({...e,deviceId:t.deviceId,cap:t.cap,fieldPath:t.fieldPath})},u=t=>{let r=Ot(t,s);n({...e,operator:r,value:r===`in`?Et(e.value):Tt(e.value)})};return o(`div`,{className:`flex flex-wrap items-end gap-2`,children:[f(et,{value:i,devices:t,onChange:l}),o(`label`,{className:`min-w-[8rem]`,children:[f(Z,{children:r(`automation.conditionRow.comparison`,`Comparison`)}),f(G,{value:e.operator,onChange:e=>u(e.target.value),options:s.map(e=>({value:e.value,label:e.label}))})]}),o(`label`,{className:`min-w-[9rem] flex-1`,children:[f(Z,{children:r(`automation.conditionRow.value`,`Value`)}),c?f(Ct,{value:Et(e.value),field:a,onChange:t=>n({...e,value:t})}):f(St,{value:Tt(e.value),field:a,onChange:t=>n({...e,value:t})})]})]})}function Ot(e,t){return t.find(t=>t.value===e)?.value??`eq`}var kt={kind:`global`,sourceStableId:``,cap:``,fieldPath:``};function At({leaf:e,devices:t,onChange:n}){let{t:r}=Y(),i=Object.entries(e.bindings),a=t=>{n({kind:`expression`,expr:e.expr,bindings:t})};return o(`div`,{className:`space-y-2`,children:[o(`label`,{className:`block`,children:[f(Z,{children:r(`automation.expressionLeafRow.expression`,`Expression`)}),f(U,{value:e.expr,placeholder:r(`automation.expressionLeafRow.indoorOutdoor5`,`indoor - outdoor > 5`),onChange:t=>n({kind:`expression`,expr:t.target.value,bindings:e.bindings})}),f(`span`,{className:`mt-1 block text-xs text-foreground-subtle`,children:r(`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.`)})]}),o(`div`,{className:`space-y-1.5`,children:[i.length===0&&f(`p`,{className:`text-xs text-foreground-subtle`,children:r(`automation.expressionLeafRow.noNamesBoundYetAn`,`No names bound yet. An expression reads devices only through these.`)}),i.map(([n,r])=>f(jt,{alias:n,source:r,devices:t,onRename:t=>a(Lt(e.bindings,n,t)),onChange:t=>a({...e.bindings,[n]:t}),onRemove:()=>a(Rt(e.bindings,n))},n)),o(W,{variant:`ghost`,onClick:()=>a({...e.bindings,[It(e.bindings)]:kt}),children:[f(g,{className:`h-3.5 w-3.5`}),` `,r(`common.name`)]})]})]})}function jt({alias:e,source:t,devices:n,onRename:r,onChange:i,onRemove:a}){let{t:s}=Y(),c=t.kind===`literal`,l=c?{deviceId:0,cap:``,fieldPath:``}:{deviceId:Pt(n,Nt(t)),cap:t.cap,fieldPath:t.fieldPath};return o(`div`,{className:`flex flex-wrap items-end gap-2 rounded border border-border p-2`,children:[o(`label`,{className:`w-32`,children:[f(Z,{children:s(`automation.expressionLeafRow.name`,`Name`)}),f(U,{value:e,placeholder:s(`automation.expressionLeafRow.aliasExample`),onChange:e=>r(e.target.value)})]}),o(`label`,{className:`w-36`,children:[f(Z,{children:s(`automation.expressionLeafRow.reads`,`Reads`)}),f(G,{value:c?`literal`:`global`,onChange:e=>i(e.target.value===`literal`?{kind:`literal`,value:``}:kt),options:[{value:`global`,label:s(`automation.expressionLeafRow.aDeviceField`,`A device field`)},{value:`literal`,label:s(`automation.expressionLeafRow.aConstant`,`A constant`)}]})]}),c?o(`label`,{className:`min-w-[9rem] flex-1`,children:[f(Z,{children:s(`automation.expressionLeafRow.constant`,`Constant`)}),f(U,{value:t.value===null?``:String(t.value),placeholder:`5`,onChange:e=>i({kind:`literal`,value:Mt(e.target.value)})})]}):f(et,{value:l,devices:n,onChange:e=>i({kind:`global`,sourceStableId:Ft(n,e.deviceId),cap:e.cap,fieldPath:e.fieldPath})}),f(W,{variant:`ghost`,onClick:a,title:s(`automation.expressionLeafRow.removeThisName`,`Remove this name`),children:f(p,{className:`h-3.5 w-3.5`})})]})}function Mt(e){let t=e.trim();return t===`true`?!0:t===`false`?!1:t!==``&&!Number.isNaN(Number(t))?Number(t):e}function Nt(e){return e.kind===`global`?e.sourceStableId:``}function Pt(e,t){return e.find(e=>e.stableId===t)?.id??0}function Ft(e,t){return e.find(e=>e.id===t)?.stableId??``}function It(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 Lt(e,t,n){let r={};for(let[i,a]of Object.entries(e))i===t?r[n]=a:r[i]=a;return r}function Rt(e,t){let n={};for(let[r,i]of Object.entries(e))r!==t&&(n[r]=i);return n}function zt(e){return e.kind===`all`||e.kind===`any`}function Q(e){let t=e.conditions;return t===void 0?{kind:`all`,children:[]}:zt(t)?t:{kind:`all`,children:[t]}}function Bt(e,t){return t===null||zt(t)&&t.children.length===0?{triggers:e.triggers,actions:e.actions}:{triggers:e.triggers,actions:e.actions,conditions:t}}function Vt(e){return Bt(e,Q(e))}function Ht(e,t){if(t.length===0)return e;let[n,...r]=t;if(n===void 0)return e;if(e.kind===`not`)return n===0?Ht(e.child,r):null;if(!zt(e))return null;let i=e.children[n];return i===void 0?null:Ht(i,r)}function Ut(e,t,n){if(t.length===0)return n(e);let[r,...i]=t;if(r===void 0)return n(e);if(e.kind===`not`){if(r!==0)return e;let t=Ut(e.child,i,n);return t===null?null:{kind:`not`,child:t}}if(!zt(e))return e;let a=e.children[r];if(a===void 0)return e;let o=Ut(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 Wt(e){return e===null?null:R({triggers:[{kind:`manual`}],actions:[{kind:`wait`,seconds:0}],conditions:e})}function Gt(e){let t=Q(e);return{depth:t.children.length===0?0:I(t),leaves:t.children.length===0?0:L(t),depthLimit:3,leafLimit:32}}function Kt(e,t){let n=Wt(t);return n===null?{ok:!0,recipe:Bt(e,t)}:{ok:!1,reason:n}}function qt(e,t){let n=Q(e);return Kt(e,{kind:n.kind,children:[...n.children,t]})}function Jt(e,t,n){return Bt(e,Ut(Q(e),t,()=>n))}function Yt(e,t){return Bt(e,Ut(Q(e),t,()=>null))}function Xt(e,t,n){return Bt(e,Ut(Q(e),t,e=>zt(e)?{kind:n,children:e.children}:e))}function Zt(e,t){return Ht(Q(e),t)===null?{ok:!1,reason:J.t(`helpers.recipeOps.rowGone`)}:Kt(e,Ut(Q(e),t,e=>e.kind===`not`?e.child:{kind:`not`,child:e}))}function Qt(e){if(e.length===0)return null;let t=e[e.length-1];return t===void 0?null:{path:e.slice(0,-1),index:t}}function $t(e,t,n){if(t.length<2)return{ok:!1,reason:J.t(`helpers.recipeOps.selectTwo`)};if(new Set(t.map(e=>e.slice(0,-1).join(`/`))).size!==1)return{ok:!1,reason:J.t(`helpers.recipeOps.differentGroups`)};let r=Qt(t[0]??[]);if(r===null)return{ok:!1,reason:J.t(`helpers.recipeOps.rootGroup`)};let i=Q(e),a=Ht(i,r.path);if(a===null||!zt(a))return{ok:!1,reason:J.t(`helpers.recipeOps.insideNot`)};let o=[...t.map(e=>e[e.length-1]??-1)].sort((e,t)=>e-t),s=o.map(e=>a.children[e]).filter(e=>e!==void 0);if(s.length!==o.length)return{ok:!1,reason:J.t(`helpers.recipeOps.selectedGone`)};let c=a.children.filter((e,t)=>!o.includes(t)),l=o[0]??0,u={kind:n,children:s},d={kind:a.kind,children:[...c.slice(0,l),u,...c.slice(l)]};return Kt(e,Ut(i,r.path,()=>d))}function en(e,t){if(t.length===0)return{ok:!1,reason:J.t(`helpers.recipeOps.outerNotGroup`)};let n=Q(e),r=Ht(n,t);if(r===null)return{ok:!1,reason:J.t(`helpers.recipeOps.groupGone`)};if(r.kind===`not`)return Kt(e,Ut(n,t,()=>r.child));if(!zt(r))return{ok:!1,reason:J.t(`helpers.recipeOps.rowIsCondition`)};let i=Qt(t);if(i===null)return{ok:!1,reason:J.t(`helpers.recipeOps.noParent`)};let a=Ht(n,i.path);if(a===null||!zt(a))return{ok:!1,reason:J.t(`helpers.recipeOps.groupInNot`)};let o={kind:a.kind,children:[...a.children.slice(0,i.index),...r.children,...a.children.slice(i.index+1)]};return Kt(e,Ut(n,i.path,()=>o))}e();var tn=[{value:`all`,labelKey:`automation.conditionTree.allOf`},{value:`any`,labelKey:`automation.conditionTree.anyOf`}];function nn(e){return e.join(`/`)}function rn(e){return e===``?[]:e.split(`/`).map(e=>Number(e))}function an({recipe:e,devices:t,onChange:i}){let{t:a}=Y(),[s,c]=r([]),[l,u]=r(null),d=Q(e),p=Gt(e),m=n(()=>s.map(rn),[s]),h=e=>{if(!e.ok){u(e.reason);return}u(null),c([]),i(e.recipe)},_=$t(e,m,`all`),v=$t(e,m,`any`),y=m.length===1?Zt(e,m[0]??[]):{ok:!1,reason:a(`automation.conditionTree.selectOneNegate`)},b={devices:t,selected:new Set(s),onToggleSelect:e=>c(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e]),onUpdate:(t,n)=>i(Jt(e,t,n)),onRemove:t=>{c([]),i(Yt(e,t))},onSetKind:(t,n)=>i(Xt(e,t,n)),onUngroup:t=>h(en(e,t))};return o(`div`,{className:`space-y-2`,children:[o(`div`,{className:`flex flex-wrap items-center gap-2`,children:[f(q,{variant:`default`,children:a(`automation.conditionTree.andOnlyIf`,`And only if`)}),f(`div`,{className:`w-32`,children:f(G,{value:d.kind,onChange:t=>i(Xt(e,[],on(t.target.value))),options:tn.map(e=>({value:e.value,label:a(e.labelKey)}))})}),f(`span`,{className:`text-xs text-foreground-subtle`,children:a(`automation.conditionTree.budget`,{depth:p.depth,depthLimit:p.depthLimit,leaves:p.leaves,leafLimit:p.leafLimit})})]}),d.children.length===0?f(`p`,{className:`text-xs text-foreground-subtle`,children:a(`automation.conditionTree.noConditionsTheActionsRun`,`No conditions. The actions run every time a trigger fires.`)}):f(sn,{container:d,path:[],handlers:b}),o(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(W,{variant:`outline`,onClick:()=>h(qt(e,ut())),title:a(`automation.conditionTree.compareOneDeviceFieldTo`,`Compare one device field to a value`),children:[f(g,{className:`h-4 w-4`}),` `,a(`automation.conditionTree.addCondition`)]}),o(W,{variant:`outline`,onClick:()=>h(qt(e,dt())),title:a(`automation.conditionTree.arithmeticAcrossDeviceFieldsThe`,`Arithmetic across device fields — the bounded expression engine`),children:[f(M,{className:`h-4 w-4`}),` `,a(`automation.conditionTree.addExpression`)]}),f(`span`,{className:`mx-1 h-5 w-px bg-border`}),f(W,{variant:`ghost`,disabled:!_.ok,onClick:()=>h(_),title:_.ok?a(`automation.conditionTree.allSelectedRowsMustBe`,`All selected rows must be true`):_.reason,children:a(`automation.conditionTree.groupAsAll`,`Group as ALL`)}),f(W,{variant:`ghost`,disabled:!v.ok,onClick:()=>h(v),title:v.ok?a(`automation.conditionTree.anyOneOfTheSelected`,`Any one of the selected rows is enough`):v.reason,children:a(`automation.conditionTree.groupAsAny`,`Group as ANY`)}),f(W,{variant:`ghost`,disabled:!y.ok,onClick:()=>h(y),title:y.ok?a(`automation.conditionTree.invertTheSelectedRow`,`Invert the selected row`):y.reason,children:`NOT`}),s.length>0&&f(`span`,{className:`text-xs text-foreground-subtle`,children:a(`common.selectedCount`,{count:s.length})})]}),l!==null&&f(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-2 text-xs text-warning`,children:l})]})}function on(e){return e===`any`?`any`:`all`}function sn({container:e,path:t,handlers:n}){return f(`div`,{className:`space-y-1.5`,children:e.children.map((e,r)=>f(cn,{node:e,path:[...t,r],handlers:n},nn([...t,r])))})}function cn({node:e,path:t,handlers:n}){let{t:r}=Y(),i=nn(t),a=f(De,{checked:n.selected.has(i),onChange:()=>n.onToggleSelect(i),"aria-label":r(`automation.conditionTree.selectThisRowForGrouping`,`Select this row for grouping`)});return zt(e)?o(`div`,{className:`rounded border border-border bg-surface-subtle/40 p-2`,children:[o(`div`,{className:`mb-1.5 flex flex-wrap items-center gap-2`,children:[a,f(`div`,{className:`w-32`,children:f(G,{value:e.kind,onChange:e=>n.onSetKind(t,on(e.target.value)),options:tn.map(e=>({value:e.value,label:r(e.labelKey)}))})}),o(W,{variant:`ghost`,onClick:()=>n.onUngroup(t),title:r(`automation.conditionTree.dissolveThisGroupKeepingIts`,`Dissolve this group, keeping its rows`),children:[f(N,{className:`h-3.5 w-3.5`}),` `,r(`automation.conditionTree.ungroup`)]}),f(W,{variant:`ghost`,onClick:()=>n.onRemove(t),title:r(`automation.conditionTree.deleteThisGroupAndEverything`,`Delete this group and everything in it`),children:f(p,{className:`h-3.5 w-3.5`})})]}),f(`div`,{className:`pl-4`,children:f(sn,{container:e,path:t,handlers:n})})]}):e.kind===`not`?o(`div`,{className:`rounded border border-border p-2`,children:[o(`div`,{className:`mb-1.5 flex flex-wrap items-center gap-2`,children:[a,f(q,{variant:`warning`,children:`NOT`}),o(W,{variant:`ghost`,onClick:()=>n.onUngroup(t),title:r(`automation.conditionTree.removeTheNotKeepingThe`,`Remove the NOT, keeping the row`),children:[f(N,{className:`h-3.5 w-3.5`}),` `,r(`automation.conditionTree.removeNot`)]})]}),f(`div`,{className:`pl-4`,children:f(cn,{node:e.child,path:[...t,0],handlers:n})})]}):o(`div`,{className:`flex items-start gap-2 rounded border border-border p-2`,children:[f(`div`,{className:`pt-6`,children:a}),f(`div`,{className:`min-w-0 flex-1`,children:e.kind===`condition`?f(Dt,{leaf:e,devices:n.devices,onChange:e=>n.onUpdate(t,e)}):f(At,{leaf:e,devices:n.devices,onChange:e=>n.onUpdate(t,e)})}),f(W,{variant:`ghost`,onClick:()=>n.onRemove(t),title:r(`automation.conditionTree.removeThisCondition`,`Remove this condition`),children:f(p,{className:`h-3.5 w-3.5`})})]})}e();function ln({code:e,error:t,canEject:n,ejecting:i,onEject:a}){let{t:s}=Y(),[c,l]=r(!1),u=Ee(),d=async()=>{await u({title:s(`automation.generatedCodePanel.ejectToCodeThisCannot`,`Eject to code — this cannot be undone`),message:s(`automation.generatedCodePanel.theRecipeIsRemovedFrom`,`The recipe is removed from the block and it becomes an ordinary script. The visual editor will no longer open it, and there is no way back to it except authoring a new automation from scratch. The code itself is kept exactly as it is now.`),confirmLabel:s(`automation.generatedCodePanel.ejectToCode`,`Eject to code`),cancelLabel:s(`automation.generatedCodePanel.keepItVisual`,`Keep it visual`),variant:`warning`})&&a()};return o(`div`,{className:`rounded border border-border`,children:[o(`div`,{className:`flex flex-wrap items-center gap-2 px-3 py-2`,children:[o(W,{variant:`ghost`,onClick:()=>l(!c),children:[f(c?k:y,{className:`h-4 w-4`}),s(`automation.generatedCodePanel.generatedCode`,`Generated code`)]}),f(`span`,{className:`text-xs text-foreground-subtle`,children:s(`automation.generatedCodePanel.derivedFromTheRecipeAbove`,`Derived from the recipe above — regenerated on every save, never edited here.`)}),o(W,{className:`ml-auto`,variant:`ghost`,disabled:!n||e===null||i,onClick:()=>void d(),title:n?s(`automation.generatedCodePanel.takePermanentOwnershipOfThis`,`Take permanent ownership of this code as a script`):s(`automation.generatedCodePanel.saveTheAutomationFirstThere`,`Save the automation first — there is no stored block to eject yet`),children:[f(P,{className:`h-4 w-4`}),` `,s(`automation.generatedCodePanel.eject`)]})]}),c&&f(`div`,{className:`border-t border-border p-3`,children:e===null?f(`p`,{className:`text-xs text-warning`,children:t??s(`automation.generatedCodePanel.theRecipeIsNotComplete`,`The recipe is not complete enough to generate a block yet.`)}):f(K,{maxHeight:420,children:e})})]})}var un=[`device-state`,`device-event`,`schedule`,`manual`],dn=Object.values(te).sort((e,t)=>e.localeCompare(t));function fn({triggers:e,devices:t,onChange:n}){let{t:r}=Y();return o(`div`,{className:`space-y-2`,children:[e.length===0&&f(`p`,{className:`text-xs text-warning`,children:r(`automation.triggerEditor.noTriggersYetWithoutOne`,`No triggers yet. Without one nothing can ever start this automation — not even "Run actions", which needs a manual trigger to have somewhere to arrive.`)}),e.map((r,i)=>f(pn,{trigger:r,devices:t,position:i,onChange:t=>n(ft(e,i,t)),onRemove:()=>n(pt(e,i))},`${r.kind}-${String(i)}`)),o(W,{variant:`outline`,onClick:()=>n([...e,ct(`device-state`)]),title:r(`automation.triggerEditor.addAnotherWayThisAutomation`,`Add another way this automation can start`),children:[f(g,{className:`h-4 w-4`}),` `,r(`automation.triggerEditor.trigger`)]})]})}function pn({trigger:e,devices:t,position:n,onChange:r,onRemove:i}){let{t:a}=Y();return o(`div`,{className:`rounded border border-border p-3`,children:[o(`div`,{className:`flex flex-wrap items-end gap-2`,children:[f(q,{variant:`default`,children:n===0?a(`automation.triggerEditor.when`,`When`):a(`automation.triggerEditor.orWhen`,`or when`)}),o(`label`,{className:`min-w-[13rem] flex-1`,children:[f(Z,{children:a(`automation.triggerEditor.trigger`,`Trigger`)}),f(G,{value:e.kind,onChange:e=>r(ct(mn(e.target.value))),options:un.map(e=>({value:e,label:ot(e)}))})]}),f(W,{variant:`ghost`,onClick:i,title:a(`automation.triggerEditor.removeThisTrigger`,`Remove this trigger`),children:f(p,{className:`h-4 w-4`})})]}),o(`div`,{className:`mt-2 flex flex-wrap items-end gap-2`,children:[e.kind===`device-state`&&f(gn,{trigger:e,devices:t,onChange:r}),e.kind===`device-event`&&f(vn,{trigger:e,devices:t,onChange:r}),e.kind===`schedule`&&o(`label`,{className:`min-w-[14rem] flex-1`,children:[f(Z,{children:a(`automation.triggerEditor.cronExpression`,`Cron expression`)}),f(U,{value:e.cron,placeholder:`0 30 23 * * *`,onChange:e=>r({kind:`schedule`,cron:e.target.value})}),f(`span`,{className:`mt-1 block text-xs text-foreground-subtle`,children:f(X,{i18nKey:`automation.triggerEditor.cronHint`,components:{code:f(`code`,{})}})})]}),e.kind===`manual`&&f(`p`,{className:`text-xs text-foreground-subtle`,children:f(X,{i18nKey:`automation.triggerEditor.manualHint`,components:{b:f(`strong`,{})}})})]})]})}function mn(e){return un.find(t=>t===e)??`manual`}function hn(e,t){return{kind:`device-state`,deviceId:e.deviceId,cap:e.cap,fieldPath:e.fieldPath,...t.becomes===void 0?{}:{becomes:t.becomes},...t.edge===void 0?{}:{edge:t.edge},...t.forMs===void 0?{}:{forMs:t.forMs},...t.debounceMs===void 0?{}:{debounceMs:t.debounceMs}}}function gn({trigger:e,devices:t,onChange:n}){let{t:r}=Y(),i={deviceId:e.deviceId,cap:e.cap,fieldPath:e.fieldPath},a=$e(i),s={...e.becomes===void 0?{}:{becomes:e.becomes},...e.edge===void 0?{}:{edge:e.edge},...e.forMs===void 0?{}:{forMs:e.forMs},...e.debounceMs===void 0?{}:{debounceMs:e.debounceMs}};return o(l,{children:[f(et,{value:i,devices:t,onChange:e=>n(hn(e,s))}),o(`div`,{className:`min-w-[11rem] flex-1`,children:[f(Z,{children:r(`automation.triggerEditor.becomes`,`Becomes`)}),o(`div`,{className:`flex items-center gap-2`,children:[o(`label`,{className:`flex items-center gap-1.5 text-xs text-foreground-subtle`,children:[f(De,{checked:e.becomes===void 0,onChange:e=>n(hn(i,{...s,...e.target.checked?{becomes:void 0}:{becomes:``}}))}),r(`automation.triggerEditor.anyChange`,`any change`)]}),e.becomes!==void 0&&f(St,{value:e.becomes,field:a,onChange:e=>n(hn(i,{...s,becomes:e}))})]})]}),o(`label`,{className:`flex items-center gap-1.5 text-xs text-foreground-subtle`,children:[f(De,{checked:e.edge===!0,onChange:e=>n(hn(i,{...s,...e.target.checked?{edge:!0}:{edge:void 0}}))}),r(`automation.triggerEditor.onlyOnAChange`,`only on a change`)]}),o(`label`,{className:`w-28`,children:[f(Z,{children:r(`automation.triggerEditor.heldForS`,`Held for (s)`)}),f(U,{type:`number`,min:0,value:e.forMs===void 0?``:String(e.forMs/1e3),placeholder:`0`,onChange:e=>n(hn(i,{...s,forMs:_n(e.target.value)}))})]}),o(`label`,{className:`w-28`,children:[f(Z,{children:r(`automation.triggerEditor.debounceS`,`Debounce (s)`)}),f(U,{type:`number`,min:0,value:e.debounceMs===void 0?``:String(e.debounceMs/1e3),placeholder:`0`,onChange:e=>n(hn(i,{...s,debounceMs:_n(e.target.value)}))})]})]})}function _n(e){if(e.trim()===``)return;let t=Number(e);if(!(Number.isNaN(t)||t<0))return Math.round(t*1e3)}function vn({trigger:e,devices:t,onChange:n}){let{t:r}=Y();return o(l,{children:[o(`label`,{className:`min-w-[15rem] flex-1`,children:[f(Z,{children:r(`automation.triggerEditor.eventCategory`,`Event category`)}),f(G,{value:e.category,onChange:t=>n({kind:`device-event`,category:t.target.value,...e.deviceId===void 0?{}:{deviceId:e.deviceId}}),options:[{value:``,label:r(`automation.triggerEditor.selectAnEvent`,`Select an event…`)},...dn.map(e=>({value:e,label:e}))]})]}),o(`label`,{className:`min-w-[11rem] flex-1`,children:[f(Z,{children:r(`automation.triggerEditor.fromDevice`,`From device`)}),f(G,{value:e.deviceId===void 0?``:String(e.deviceId),onChange:t=>n({kind:`device-event`,category:e.category,...t.target.value===``?{}:{deviceId:Number(t.target.value)}}),options:[{value:``,label:r(`automation.triggerEditor.anyDevice`,`Any device`)},...t.map(e=>({value:String(e.id),label:e.name}))]})]})]})}e();var yn=`hub`;function bn({existing:e,initialRecipe:t,saving:i,saveError:a,ejecting:s,onSave:c,onEject:l,onCancel:u}){let{t:d}=Y(),[p,m]=r(e?.name??``),[h,g]=r(()=>Vt(t)),[_,v]=r(!1),y=Xe(),b=R(h),S=n(()=>Sn(h),[h]),w=n(()=>Cn(p.trim()===``?`Untitled automation`:p.trim(),h),[p,h]),T=p.trim()===``,E=T||b!==null||S!==null||w.code===null;return o(`div`,{className:`space-y-4`,children:[f(`div`,{className:`flex flex-wrap items-center gap-2`,children:f(q,{variant:`info`,children:d(`automation.automationEditor.runsOnTheHub`,`runs on the hub`)})}),o(`label`,{className:`block max-w-md text-sm`,children:[f(`span`,{className:`text-foreground-subtle`,children:d(`automation.automationEditor.name`,`Name`)}),f(U,{className:`mt-1`,value:p,onChange:e=>m(e.target.value),placeholder:d(`automation.automationEditor.whatThisAutomationDoes`,`What this automation does`)})]}),f(xn,{step:`1`,title:d(`automation.automationEditor.when`,`When`),subtitle:d(`automation.automationEditor.anyOneOfTheseStarts`,`Any one of these starts a run.`),children:f(fn,{triggers:h.triggers,devices:y,onChange:e=>g(ht(h,e))})}),f(xn,{step:`2`,title:d(`automation.automationEditor.andOnlyIf`,`And only if`),subtitle:d(`automation.automationEditor.checkedAfterATriggerFires`,`Checked after a trigger fires. Nothing runs unless this is true.`),children:f(an,{recipe:h,devices:y,onChange:g})}),f(xn,{step:`3`,title:d(`automation.automationEditor.then`,`Then`),subtitle:d(`automation.automationEditor.inThisOrderStoppingAt`,`In this order, stopping at the first failure.`),children:f(vt,{actions:h.actions,devices:y,onChange:e=>g(gt(h,e))})}),f(ln,{code:w.code,error:w.error,canEject:e!==null,ejecting:s,onEject:l}),b!==null&&f(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:b}),b===null&&S!==null&&f(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:S}),a!==null&&f(`p`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:a}),o(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(W,{onClick:()=>{w.code!==null&&c({name:p.trim(),code:w.code,enabled:e?.enabled??!0,placement:yn})},disabled:i||E,children:[i&&f(x,{className:`h-4 w-4 animate-spin`}),` `,d(`common.save`)]}),o(W,{variant:`ghost`,onClick:()=>v(!_),disabled:e===null,title:e===null?d(`automation.automationEditor.logsAppearOnceTheAutomation`,`Logs appear once the automation has been saved and started`):d(`automation.automationEditor.showThisAutomationSProcess`,`Show this automation's process logs`),"data-testid":`automation-logs-toggle`,children:[f(C,{className:`h-4 w-4`}),` `,d(`common.logs`),` `,_?`▾`:`▸`]}),f(W,{variant:`ghost`,onClick:u,disabled:i,children:d(`common.close`,`Close`)}),T&&f(q,{variant:`warning`,children:d(`automation.automationEditor.nameRequired`,`Name required`)})]}),_&&e!==null&&o(`div`,{className:`rounded border border-border`,"data-testid":`automation-logs-panel`,children:[f(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:f(X,{i18nKey:`common.logsOf`,values:{id:re(e.id)},components:{code:f(`code`,{})}})}),f(be,{addonId:re(e.id),maxHeight:`max-h-64`,showFilters:!1})]})]})}function xn({step:e,title:t,subtitle:n,children:r}){return o(`section`,{className:`border-l-2 border-border pl-4`,children:[o(`div`,{className:`mb-2 flex flex-wrap items-baseline gap-2`,children:[f(`span`,{className:`text-xs font-mono text-foreground-subtle`,children:e}),f(`h4`,{className:`text-sm font-medium uppercase tracking-wide`,children:t}),f(`span`,{className:`text-xs text-foreground-subtle`,children:n})]}),r]})}function Sn(e){let t=H.safeParse(e);if(t.success)return null;let n=t.error.issues[0];return n===void 0?J.t(`helpers.automationEditor.incomplete`):`${n.path.length===0?``:`${n.path.join(`.`)}: `}${n.message}`}function Cn(e,t){try{return{code:B({name:e,recipe:t}),error:null}}catch(e){return{code:null,error:e instanceof Error?e.message:String(e)}}}function wn(e){if(!e.enabled)return{tone:`idle`,label:J.t(`helpers.coreBlockStatus.disabled`),detail:J.t(`helpers.coreBlockStatus.disabledDetail`)};switch(e.status){case`running`:return{tone:`ok`,label:J.t(`helpers.coreBlockStatus.running`),detail:J.t(`helpers.coreBlockStatus.runningDetail`)};case`starting`:return{tone:`pending`,label:J.t(`helpers.coreBlockStatus.starting`),detail:e.lastError??J.t(`helpers.coreBlockStatus.startingDetail`)};case`failed`:return{tone:`error`,label:J.t(`helpers.coreBlockStatus.failed`),detail:e.lastError??J.t(`helpers.coreBlockStatus.failedDetail`)};default:return{tone:`error`,label:J.t(`helpers.coreBlockStatus.notRunning`),detail:e.lastError??J.t(`helpers.coreBlockStatus.notRunningDetail`)}}}function Tn(e){switch(e){case`ok`:return`success`;case`pending`:return`warning`;case`error`:return`danger`;default:return`default`}}function En(e,t){let n=e.find(e=>e.id===t.id);return n===void 0?t:n.updatedAt>=t.updatedAt?n:t}function Dn(e){let t=e=>{let t=wn(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 On(e){if(e.length===0)return J.t(`helpers.coreBlockStatus.noBlocks`);let t=e.filter(e=>wn(e).tone===`error`).length,n=e.filter(e=>wn(e).tone===`ok`).length,r=[J.t(`helpers.coreBlockStatus.blocks`,{count:e.length})];return n>0&&r.push(J.t(`helpers.coreBlockStatus.runningCount`,{count:n})),t>0&&r.push(J.t(`helpers.coreBlockStatus.notRunningCount`,{count:t})),r.join(` · `)}function kn({block:e,busy:t,confirming:n,logsOpen:r,unreadable:i,onEdit:a,onToggle:s,onToggleLogs:c,onAskDelete:l,onCancelDelete:u,onConfirmDelete:d}){let m=w(),{t:h}=Y(),g=wn(e),v=Ae(e.updatedAt,m);return o(`li`,{className:`flex flex-col gap-2 p-3`,children:[o(`div`,{className:`flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-3`,children:[o(`div`,{className:`min-w-0 flex-1`,children:[o(`div`,{className:`flex flex-wrap items-center gap-2`,children:[f(`span`,{className:`truncate font-medium`,children:e.name}),f(q,{variant:Tn(g.tone),children:g.label}),v!==null&&f(`span`,{className:`text-xs text-foreground-subtle`,children:h(`common.edited`,{when:v})})]}),f(`p`,{className:`mt-0.5 text-xs text-foreground-subtle`,children:g.detail}),i!==null&&f(`p`,{className:`mt-0.5 text-xs text-warning`,children:h(`automation.editor.listUnreadable`,{reason:i})})]}),n?o(`div`,{className:`flex justify-end gap-1`,children:[f(`span`,{className:`text-xs text-foreground-subtle`,children:h(`automation.automationList.deleteThisAutomation`,`Delete this automation?`)}),f(W,{variant:`danger`,onClick:e=>{e.stopPropagation(),d()},disabled:t,children:h(`common.delete`,`Delete`)}),f(W,{variant:`ghost`,onClick:e=>{e.stopPropagation(),u()},children:h(`common.cancel`,`Cancel`)})]}):o(`div`,{className:`flex justify-end gap-1`,children:[f(W,{variant:`ghost`,onClick:e=>{e.stopPropagation(),a()},disabled:i!==null,title:i===null?h(`common.edit`,`Edit`):h(`automation.automationList.thisBlockCannotBeOpened`,`This block cannot be opened visually`),children:f(_,{className:`h-4 w-4`})}),o(we,{children:[f(ve,{children:f(W,{variant:`ghost`,disabled:!0,title:h(`automation.automationList.runActions`,`Run actions`),children:f(T,{className:`h-4 w-4`})})}),f(Te,{children:h(`automation.automationList.runningAnAutomationByHand`,`Running an automation by hand needs the automation-control authority, which is not wired up yet. There is deliberately no second way to execute one.`)})]}),f(W,{variant:`ghost`,onClick:e=>{e.stopPropagation(),c()},title:h(`automation.automationList.logs`,`Logs`),children:f(C,{className:`h-4 w-4`})}),f(W,{variant:`ghost`,onClick:t=>{t.stopPropagation(),s(!e.enabled)},disabled:t,title:e.enabled?h(`common.disable`,`Disable`):h(`common.enable`,`Enable`),children:e.enabled?h(`common.disable`,`Disable`):h(`common.enable`,`Enable`)}),f(W,{variant:`ghost`,onClick:e=>{e.stopPropagation(),l()},title:h(`common.delete`,`Delete`),children:f(p,{className:`h-4 w-4`})})]})]}),r&&o(`div`,{className:`rounded border border-border`,children:[f(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:f(X,{i18nKey:`common.logsOf`,values:{id:re(e.id)},components:{code:f(`code`,{})}})}),f(be,{addonId:re(e.id),maxHeight:`max-h-64`,showFilters:!1})]})]})}function An({onCreate:e}){let{t}=Y();return f(_e,{children:o(`div`,{className:`space-y-2 p-4`,children:[f(`p`,{className:`text-sm text-foreground`,children:t(`automation.automationList.noAutomationsYet`,`No automations yet.`)}),f(`p`,{className:`max-w-2xl text-xs text-foreground-subtle`,children:t(`automation.automationList.anAutomationIsATrigger`,`An automation is a trigger, a set of conditions and a list of actions. It compiles to an ordinary block and runs in its own supervised process — there is no separate engine, so anything that goes wrong shows up here with a reason.`)}),f(W,{onClick:e,children:t(`automation.automationList.newAutomation`,`New automation`)})]})})}e();var jn=[`coreBlocks`,`list`],Mn=5e3;function Nn(e){return e instanceof Error?e.message:String(e)}function Pn({onOpenScripts:e,initialBlockId:i,onBlockIdChange:a,createRequested:s=!1,onCreateConsumed:l}){let{t:p}=Y(),m=E(),{state:h,openNew:g,openEdit:_,close:v}=de({editKey:`block`,newKey:`new`}),[y,b]=r(null),[x,S]=r(null),[C,w]=r(null),T=u(null),O=h.mode!==`closed`;t(()=>{s&&(b(null),g(),a?.(null),l?.())},[s,l,a,g]);let k=c({queryKey:jn,refetchInterval:Mn,queryFn:async()=>(await m.trpcClient.coreBlocks.list.query({})).blocks}),A=()=>{k.refetch()},j=k.data;t(()=>{i===void 0||T.current===i||j?.find(e=>e.id===i&&Ge(e.code))!==void 0&&(T.current=i,_(i),a?.(i))},[i,j,_,a]);let M=d({mutationFn:e=>m.trpcClient.coreBlocks.create.mutate({block:e}),onSuccess:e=>{b(e.block),_(e.block.id),a?.(e.block.id),A()}}),N=d({mutationFn:e=>m.trpcClient.coreBlocks.update.mutate(e),onSuccess:e=>{b(e.block),_(e.block.id),a?.(e.block.id),A()}}),P=d({mutationFn:e=>m.trpcClient.coreBlocks.delete.mutate({blockId:e}),onSuccess:()=>{S(null),A()}}),F=d({mutationFn:e=>m.trpcClient.coreBlocks.setEnabled.mutate(e),onSuccess:A}),I=d({mutationFn:e=>m.trpcClient.coreBlocks.update.mutate({blockId:e.id,block:{name:e.name,code:Je(e.code),enabled:e.enabled,placement:e.placement,...e.integrationId===void 0?{}:{integrationId:e.integrationId}}}),onSuccess:t=>{v(),b(null),A(),e(t.block.id)}}),L=k.data,R=Dn((L??[]).filter(e=>Ge(e.code))),z=L!==void 0&&R.length===0,B=h.mode===`edit`?R.find(e=>e.id===h.id)??(y!==null&&y.id===h.id?y:null):null,V=h.mode===`new`||B===null?null:En(R,B),H=V===null?null:qe(V.code),ee=M.error===null?N.error===null?I.error===null?null:Nn(I.error):Nn(N.error):Nn(M.error),te=n(()=>[{key:`row`,header:p(`build.automationsTab.automation`,`Automation`),nowrap:!1,notSortableReason:`Composite status row`,render:e=>{let t=qe(e.code);return f(`ul`,{className:`list-none`,children:f(kn,{block:e,busy:F.isPending||P.isPending,confirming:x===e.id,logsOpen:C===e.id,unreadable:t.ok?null:t.reason,onEdit:()=>{b(e),_(e.id),a?.(e.id)},onToggle:t=>F.mutate({blockId:e.id,enabled:t}),onToggleLogs:()=>w(C===e.id?null:e.id),onAskDelete:()=>S(e.id),onCancelDelete:()=>S(null),onConfirmDelete:()=>P.mutate(e.id)})})},sortValue:e=>e.name}],[x,C,a,_,P,F,p]);return o(`div`,{className:`space-y-3`,children:[f(`p`,{className:`text-xs text-foreground-subtle`,children:L===void 0?``:On(R)}),k.error!=null&&f(fe,{title:p(`build.automationsTab.couldNotReadTheAutomations`,`Could not read the automations`),message:Nn(k.error),onRetry:A}),z?f(An,{onCreate:()=>{b(null),g(),a?.(null)}}):f(Se,{columns:te,rows:R,rowKey:e=>e.id,pageSize:25,maxBodyHeight:Ce,emptyMessage:L===void 0?p(`build.automationsTab.loadingAutomations`,`Loading automations…`):p(`build.automationsTab.noAutomationsYet`,`No automations yet.`),onRowClick:e=>{b(e),_(e.id),a?.(e.id)}}),f(je,{open:O,onClose:()=>{M.reset(),N.reset(),I.reset(),b(null),v(),a?.(null)},title:V===null?p(`build.automationsTab.newAutomation`,`New automation`):p(`build.automationsTab.edit`,`Edit {{name}}`,{name:V.name}),icon:D,width:`xl`,testId:`automation-editor-panel`,children:f(bn,{existing:V,initialRecipe:H!==null&&H.ok?H.recipe:st,saving:M.isPending||N.isPending,saveError:ee,ejecting:I.isPending,onSave:e=>{V===null?M.mutate(e):N.mutate({blockId:V.id,block:e})},onEject:()=>{V!==null&&I.mutate(V)},onCancel:()=>{M.reset(),N.reset(),I.reset(),b(null),v(),a?.(null)}},V?.id??`new`)}),P.error!=null&&f(fe,{message:Nn(P.error)}),F.error!=null&&f(fe,{message:Nn(F.error)})]})}function Fn(e){return{state:`answered`,byRef:new Map(e.map(e=>[F(e),e]))}}function In(e,t){if(e.state!==`unanswered`)return e.byRef.get(F(t))??null}function Ln(e){return e===void 0?`unknown`:e===null?`missing`:`present`}function Rn(e){return V(e).map(e=>e.source)}function zn(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(...Rn(t));for(let t of Object.values(e.items??{}))for(let e of Object.values(t.fields))n.push(...Rn(e))}let r=new Set;return n.filter(e=>{let t=F(e);return r.has(t)?!1:(r.add(t),!0)})}function Bn(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:J.t(`helpers.compositionRows.running`),reason:null};let r=[...t.length>0?[J.t(`helpers.compositionRows.fieldsUnavailable`,{count:t.length})]:[],...n.length>0?[J.t(`helpers.compositionRows.fieldsStale`,{count:n.length})]:[]].join(`, `),i=t[0]??n[0],a=i===void 0?``:` — ${i.cap}.${i.path}: ${i.reason??J.t(`helpers.compositionRows.noReason`)}`;return{tone:`pending`,label:J.t(`helpers.compositionRows.running`),reason:`${r}${a}`}}function Vn(e,t){let n=e.reason??t??null;switch(e.status){case`running`:return Bn(e);case`degraded`:return{tone:`pending`,label:J.t(`helpers.compositionRows.degraded`),reason:n??J.t(`helpers.compositionRows.degradedReason`)};case`starting`:return{tone:`pending`,label:J.t(`helpers.compositionRows.starting`),reason:n};case`failed`:return{tone:`error`,label:J.t(`helpers.compositionRows.failed`),reason:n??J.t(`helpers.compositionRows.failedReason`)};default:return{tone:`error`,label:J.t(`helpers.compositionRows.notRunning`),reason:n??J.t(`helpers.compositionRows.notRunningReason`)}}}function Hn(e){let{block:t,state:n}=e;if(!t.enabled)return{tone:`idle`,label:J.t(`helpers.compositionRows.off`),reason:null};if(n.kind===`unreachable`)return{tone:`pending`,label:J.t(`helpers.compositionRows.unknown`),reason:J.t(`helpers.compositionRows.unreachable`,{error:n.error})};if(n.state!==null)return Vn(n.state,t.lastError);let r=t.lastError===void 0?t.status:`${t.status}: ${t.lastError}`;return{tone:`pending`,label:J.t(`helpers.compositionRows.notReported`),reason:J.t(`helpers.compositionRows.noRecord`,{stored:r})}}function Un(e){return F(e)}function Wn(e,t){let n=In(t,e);return{key:F(e),label:n?n.name:Un(e),presence:Ln(n),deviceId:n?n.id:null}}function Gn(e){return e.state.kind===`answered`&&e.state.state!==null?e.state.state.deviceId:null}function Kn(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:ee(e.block.id),a=F(i),o=zn(e).filter(e=>F(e)!==a).map(e=>Wn(e,t)),s=n.features.map(e=>e.enabled===!1?J.t(`helpers.compositionRows.featureOff`,{cap:e.cap}):e.cap),c=In(t,i),l=Gn(e),u=Hn(e);if(r.kind===`new`)return{blockId:e.block.id,kind:`composed`,name:e.block.name,namePresence:`present`,type:r.role===void 0?r.type:`${r.type} · ${r.role}`,features:s,state:u,sources:o,reportedDeviceId:l};let d=Ln(c);return{blockId:e.block.id,kind:`customization`,name:c?c.name:Un(r.device),namePresence:d,type:c?c.type:null,features:s,state:u,sources:o,reportedDeviceId:l}}function qn(e){return e.state.tone===`error`?0:e.state.tone===`pending`?1:e.state.tone===`ok`?2:3}function Jn(e,t){return qn(e)-qn(t)||e.name.localeCompare(t.name)}function Yn(e,t){let n=e.flatMap(e=>{let n=Kn(e,t);return n===null?[]:[n]});return{composed:n.filter(e=>e.kind===`composed`).toSorted(Jn),customizations:n.filter(e=>e.kind===`customization`).toSorted(Jn)}}e();var Xn=1e4;function Zn(e){return e instanceof Error?e.message:typeof e==`object`&&e&&`message`in e?String(e.message):String(e)}function Qn(e){let t=e.trim();return t===``?{}:{name:t}}function $n(){let e=Pe();return e.data===void 0?{state:`unanswered`,reason:e.error==null?J.t(`build.customDeviceTab.deviceListPending`):J.t(`build.customDeviceTab.deviceListUnreadable`,{error:Zn(e.error)})}:Fn(e.data)}function er({createRequested:e=!1,onCreateConsumed:n}={}){let{t:r}=Y(),i=pe({},{refetchInterval:Xn}),a=$n(),s=de({editKey:`block`,newKey:`new`});t(()=>{e&&(s.openNew(),n?.())},[e]);let c=i.data;if(i.error!=null&&c===void 0)return f(fe,{title:r(`build.customDeviceTab.couldNotReadTheCompositions`,`Could not read the compositions`),message:Zn(i.error),onRetry:()=>void i.refetch()});if(c===void 0)return f(`p`,{className:`p-4 text-sm text-foreground-subtle`,children:r(`build.customDeviceTab.loadingCompositions`,`Loading compositions…`)});if(c.state===`not-loaded`)return f(_e,{children:o(`div`,{className:`space-y-1 p-4`,children:[f(`p`,{className:`text-sm text-warning`,children:r(`build.customDeviceTab.theCompositionStoreHasNot`,`The composition store has not been read yet.`)}),o(`p`,{className:`text-xs text-foreground-subtle`,children:[r(`build.customDeviceTab.thisIsNotTheSame`,`This is not the same as having none — the list appears once the hub has read it (`),c.reason,`).`]})]})});let u=i.error==null?null:Zn(i.error),d=Yn(c.views,a),p=s.state.mode===`edit`?s.state.id:null,m=s.state.mode===`new`;return o(l,{children:[f(rr,{lists:d,fleet:a,refreshError:u,onEditComposed:e=>s.openEdit(e)}),f(je,{open:m||p!==null,onClose:()=>s.close(),title:m?r(`build.customDeviceTab.newComposedDevice`,`New composed device`):r(`build.customDeviceTab.editComposedDevice`,`Edit composed device`),icon:A,width:`xl`,testId:`composed-device-editor`,children:m?f(tr,{onClose:()=>s.close(),onCreated:e=>{i.refetch(),s.openEdit(e)}}):p===null?null:f(nr,{blockId:p,onClose:()=>s.close(),onSaved:()=>void i.refetch()})})]})}function tr({onClose:e,onCreated:t}){let n=ye();return f(He,{initial:Ve(z.Sensor),blockId:null,deviceType:z.Sensor,nativeCaps:null,targetFields:null,showTemplates:!0,onCancel:e,save:async(e,r)=>{try{let{block:i}=await n.mutateAsync({block:{...Qn(r),enabled:!0,composition:e}});return t(i.id),{kind:`saved`}}catch(e){return{kind:`refused`,reason:Zn(e)}}}})}function nr({blockId:e,onClose:t,onSaved:n}){let{t:r}=Y(),i=ue(),a=ke({blockId:e});if(a.status===`pending`)return f(`p`,{role:`status`,children:r(`compositionEditor.loading`)});if(a.status===`error`)return f(fe,{title:r(`compositionEditor.loadFailed`),message:a.error.message});if(a.data.state===`not-loaded`)return f(`p`,{role:`status`,children:r(`customize.status.notLoaded`,{reason:a.data.reason})});let o=a.data.view;if(o===null)return f(`p`,{children:r(`compositionEditor.notFound`,{blockId:e})});let s=oe(o.block);if(s===null)return f(`p`,{children:r(`compositionEditor.notComposition`)});if(s.target.kind===`existing`){let e=o.state.kind===`answered`?o.state.state?.deviceId??null:null;return e===null?f(`p`,{children:r(`compositionEditor.customizationUnknownDevice`)}):f(Fe,{className:`text-primary`,to:Le(e),children:r(`compositionEditor.openOnDevice`)})}return f(He,{initial:Be(s,o.block.name),blockId:o.block.id,deviceType:s.target.type,nativeCaps:null,targetFields:null,onCancel:t,save:async(e,t)=>{try{return await i.mutateAsync({blockId:o.block.id,expectedUpdatedAt:o.block.updatedAt,block:{...Qn(t),composition:e}}),await a.refetch(),n(),{kind:`saved`}}catch(e){return{kind:`refused`,reason:Zn(e)}}}},`${o.block.id}@${o.block.updatedAt}`)}function rr({lists:e,fleet:t,refreshError:n,onEditComposed:r}){let{t:i}=Y();return o(`div`,{className:`space-y-4`,children:[n!==null&&o(`p`,{className:`text-xs text-warning`,children:[i(`build.customDeviceTab.showingTheLastAnswerThe`,`Showing the last answer — the latest refresh failed:`),` `,n]}),t.state===`unanswered`&&o(`p`,{className:`text-xs text-warning`,children:[i(`build.customDeviceTab.deviceNamesAreShownAs`,`Device names are shown as references:`),` `,t.reason,`. No source is marked missing until it has.`]}),f(ir,{title:i(`build.customDeviceTab.composedDevices`,`Composed devices`),hint:i(`build.customDeviceTab.aNewDeviceWhoseState`,`A new device whose state is derived from other devices.`),rows:e.composed,nameHeader:`Name`,emptyMessage:i(`build.customDeviceTab.noComposedDevices`,`No composed devices.`),kind:`composed`,onEditComposed:r}),f(ir,{title:i(`build.customDeviceTab.customizations`,`Customizations`),hint:i(`build.customDeviceTab.fieldsAddedToOrReplaced`,`Fields added to or replaced on an existing device — one per device, edited from the device.`),rows:e.customizations,nameHeader:`Device`,emptyMessage:i(`build.customDeviceTab.noCustomizations`,`No customizations.`),kind:`customization`,onEditComposed:r})]})}function ir({title:e,hint:t,rows:n,nameHeader:r,emptyMessage:i,kind:a,onEditComposed:s}){return o(`section`,{className:`space-y-2`,"aria-label":e,children:[o(`div`,{children:[f(`h3`,{className:`font-medium`,children:e}),f(`p`,{className:`text-xs text-foreground-subtle`,children:t})]}),f(_e,{variant:`flat`,className:`p-0`,children:f(Se,{columns:ar(r,a,s),rows:n,rowKey:e=>e.blockId,minWidthPx:760,bordered:!1,maxBodyHeight:Ce,emptyMessage:i,onRowClick:a===`composed`?e=>s(e.blockId):void 0})})]})}function ar(e,t,n){let r=[{key:`name`,header:e,sortValue:e=>e.name.toLowerCase(),render:e=>f(or,{row:e})},{key:`type`,header:J.t(`build.customDeviceTab.type`,`Type`),sortValue:e=>e.type,render:e=>f(`span`,{className:`text-xs text-foreground-subtle`,children:e.type??J.t(`common.unknownWord`)})},{key:`state`,header:J.t(`build.customDeviceTab.state`,`State`),nowrap:!1,notSortableReason:`A state and its reason are read together, not ordered.`,render:e=>o(`div`,{className:`space-y-0.5`,children:[f(q,{variant:Tn(e.state.tone),children:e.state.label}),e.state.reason!==null&&f(`p`,{className:`max-w-md whitespace-normal text-xs text-foreground-subtle`,children:e.state.reason})]})},{key:`sources`,header:J.t(`build.customDeviceTab.sources`,`Sources`),nowrap:!1,notSortableReason:`A list of devices has no single order.`,render:e=>f(cr,{sources:e.sources})}];return t===`composed`&&r.push({key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,nowrap:!0,render:e=>f(`div`,{className:`flex justify-end gap-1`,children:f(W,{type:`button`,size:`sm`,variant:`secondary`,onClick:t=>{t.stopPropagation(),n(e.blockId)},children:J.t(`common.edit`,`Edit`)})})}),r}function or({row:e}){let{t}=Y();return o(`div`,{className:`space-y-0.5`,children:[f(sr,{row:e}),e.namePresence===`missing`&&f(`span`,{className:`ml-1.5 text-[10px] text-danger`,children:t(`build.customDeviceTab.deviceMissing`,`device missing`)}),f(`p`,{className:`text-[11px] text-foreground-subtle`,children:e.features.join(`, `)})]})}function sr({row:e}){let{t}=Y();return e.kind===`composed`?f(`span`,{className:`text-xs font-medium text-foreground`,children:e.name}):e.reportedDeviceId===null?f(`span`,{className:`text-xs text-foreground-subtle`,children:t(`build.customDeviceTab.notReported`,{name:e.name})}):f(Fe,{to:Le(e.reportedDeviceId),className:`text-xs text-foreground hover:underline`,onClick:e=>e.stopPropagation(),children:e.name})}function cr({sources:e}){let{t}=Y();return e.length===0?f(`span`,{className:`text-xs text-foreground-subtle`,children:`—`}):f(`ul`,{className:`space-y-0.5`,children:e.map(e=>o(`li`,{className:`text-xs`,children:[e.deviceId===null?f(`span`,{className:e.presence===`missing`?`text-danger`:`text-foreground`,children:e.label}):f(Fe,{to:`/devices/${String(e.deviceId)}`,className:`hover:underline`,children:e.label}),e.presence===`missing`&&f(`span`,{className:`ml-1.5 text-[10px] text-danger`,children:t(`common.missing`)})]},e.key))})}function lr(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 ur(e){if(Array.isArray(e))return e}function dr(e,t,n){return(t=br(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function fr(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 pr(){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 mr(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 hr(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?mr(Object(n),!0).forEach(function(t){dr(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):mr(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function gr(e,t){if(e==null)return{};var n,r,i=_r(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 _r(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 vr(e,t){return ur(e)||fr(e,t)||xr(e,t)||pr()}function yr(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 br(e){var t=yr(e,`string`);return typeof t==`symbol`?t:t+``}function xr(e,t){if(e){if(typeof e==`string`)return lr(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)?lr(e,t):void 0}}function Sr(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Cr(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 wr(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?Cr(Object(n),!0).forEach(function(t){Sr(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Cr(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function Tr(){var e=[...arguments];return function(t){return e.reduceRight(function(e,t){return t(e)},t)}}function Er(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 Dr(e){return{}.toString.call(e).includes(`Object`)}function Or(e){return!Object.keys(e).length}function kr(e){return typeof e==`function`}function Ar(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function jr(e,t){return Dr(t)||Ir(`changeType`),Object.keys(t).some(function(t){return!Ar(e,t)})&&Ir(`changeField`),t}function Mr(e){kr(e)||Ir(`selectorType`)}function Nr(e){kr(e)||Dr(e)||Ir(`handlerType`),Dr(e)&&Object.values(e).some(function(e){return!kr(e)})&&Ir(`handlersType`)}function Pr(e){e||Ir(`initialIsRequired`),Dr(e)||Ir(`initialType`),Or(e)&&Ir(`initialContent`)}function Fr(e,t){throw Error(e[t]||e.default)}var Ir=Er(Fr)({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"}),Lr={changes:jr,selector:Mr,handler:Nr,initial:Pr};function Rr(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};Lr.initial(e),Lr.handler(t);var n={current:e},r=Er(Vr)(n,t),i=Er(Br)(n),a=Er(Lr.changes)(e),o=Er(zr)(n);function s(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:function(e){return e};return Lr.selector(e),e(n.current)}function c(e){Tr(r,i,a,o)(e)}return[s,c]}function zr(e,t){return kr(t)?t(e.current):t}function Br(e,t){return e.current=wr(wr({},e.current),t),t}function Vr(e,t,n){return kr(t)?t(e.current):Object.keys(n).forEach(function(n){return t[n]?.call(t,e.current[n])}),n}var Hr={create:Rr},Ur={paths:{vs:`https://cdn.jsdelivr.net/npm/monaco-editor@0.55.1/min/vs`}};function Wr(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 Gr(e){return{}.toString.call(e).includes(`Object`)}function Kr(e){return e||Xr(`configIsRequired`),Gr(e)||Xr(`configType`),e.urls?(qr(),{paths:{vs:e.urls.monacoBase}}):e}function qr(){console.warn(Yr.deprecation)}function Jr(e,t){throw Error(e[t]||e.default)}var Yr={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
|
-
`},Xr=Wr(Jr)(Yr),Zr={config:Kr},Qr=function(){var e=[...arguments];return function(t){return e.reduceRight(function(e,t){return t(e)},t)}};function $r(e,t){return Object.keys(t).forEach(function(n){t[n]instanceof Object&&e[n]&&Object.assign(t[n],$r(e[n],t[n]))}),hr(hr({},e),t)}var ei={type:`cancelation`,msg:`operation is manually canceled`};function ti(e){var t=!1,n=new Promise(function(n,r){e.then(function(e){return t?r(ei):n(e)}),e.catch(r)});return n.cancel=function(){return t=!0},n}var ni=[`monaco`],ri=vr(Hr.create({config:Ur,isInitialized:!1,resolve:null,reject:null,monaco:null}),2),ii=ri[0],ai=ri[1];function oi(e){var t=Zr.config(e),n=t.monaco,r=gr(t,ni);ai(function(e){return{config:$r(e.config,r),monaco:n}})}function si(){var e=ii(function(e){return{monaco:e.monaco,isInitialized:e.isInitialized,resolve:e.resolve}});if(!e.isInitialized){if(ai({isInitialized:!0}),e.monaco)return e.resolve(e.monaco),ti(mi);if(window.monaco&&window.monaco.editor)return fi(window.monaco),e.resolve(window.monaco),ti(mi);Qr(ci,ui)(di)}return ti(mi)}function ci(e){return document.body.appendChild(e)}function li(e){var t=document.createElement(`script`);return e&&(t.src=e),t}function ui(e){var t=ii(function(e){return{config:e.config,reject:e.reject}}),n=li(`${t.config.paths.vs}/loader.js`);return n.onload=function(){return e()},n.onerror=t.reject,n}function di(){var e=ii(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;fi(n),e.resolve(n)},function(t){e.reject(t)})}function fi(e){ii().monaco||ai({monaco:e})}function pi(){return ii(function(e){return e.monaco})}var mi=new Promise(function(e,t){return ai({resolve:e,reject:t})}),hi={config:oi,init:si,__getMonacoInstance:pi};e();var gi={wrapper:{display:`flex`,position:`relative`,textAlign:`initial`},fullWidth:{width:`100%`},hide:{display:`none`}},_i={container:{display:`flex`,height:`100%`,width:`100%`,justifyContent:`center`,alignItems:`center`}};function vi({children:e}){return s.createElement(`div`,{style:_i.container},e)}var yi=vi;function bi({width:e,height:t,isEditorReady:n,loading:r,_ref:i,className:a,wrapperProps:o}){return s.createElement(`section`,{style:{...gi.wrapper,width:e,height:t},...o},!n&&s.createElement(yi,null,r),s.createElement(`div`,{ref:i,style:{...gi.fullWidth,...!n&&gi.hide},className:a}))}var xi=a(bi);function Si(e){t(e,[])}var Ci=Si;function wi(e,n,r=!0){let i=u(!0);t(i.current||!r?()=>{i.current=!1}:e,n)}var $=wi;function Ti(){}function Ei(e,t,n,r){return Di(e,r)||Oi(e,t,n,r)}function Di(e,t){return e.editor.getModel(ki(e,t))}function Oi(e,t,n,r){return e.editor.createModel(t,n,r?ki(e,r):void 0)}function ki(e,t){return e.Uri.parse(t)}function Ai({original:e,modified:n,language:a,originalLanguage:o,modifiedLanguage:c,originalModelPath:l,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=Ti,onMount:S=Ti}){let[C,w]=r(!1),[T,E]=r(!0),D=u(null),O=u(null),k=u(null),A=u(S),j=u(x),M=u(!1);Ci(()=>{let e=hi.init();return e.then(e=>(O.current=e)&&E(!1)).catch(e=>e?.type!==`cancelation`&&console.error(`Monaco initialization: error:`,e)),()=>D.current?F():e.cancel()}),$(()=>{if(D.current&&O.current){let t=D.current.getOriginalEditor(),n=Ei(O.current,e||``,o||a||`text`,l||``);n!==t.getModel()&&t.setModel(n)}},[l],C),$(()=>{if(D.current&&O.current){let e=D.current.getModifiedEditor(),t=Ei(O.current,n||``,c||a||`text`,d||``);t!==e.getModel()&&e.setModel(t)}},[d],C),$(()=>{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),$(()=>{D.current?.getModel()?.original.setValue(e||``)},[e],C),$(()=>{let{original:e,modified:t}=D.current.getModel();O.current.editor.setModelLanguage(e,o||a||`text`),O.current.editor.setModelLanguage(t,c||a||`text`)},[a,o,c],C),$(()=>{O.current?.editor.setTheme(m)},[m],C),$(()=>{D.current?.updateOptions(g)},[g],C);let N=i(()=>{if(!O.current)return;j.current(O.current);let t=Ei(O.current,e||``,o||a||`text`,l||``),r=Ei(O.current,n||``,c||a||`text`,d||``);D.current?.setModel({original:t,modified:r})},[a,n,c,e,o,l,d]),P=i(()=>{!M.current&&k.current&&(D.current=O.current.editor.createDiffEditor(k.current,{automaticLayout:!0,...g}),N(),O.current?.editor.setTheme(m),w(!0),M.current=!0)},[g,m,N]);t(()=>{C&&A.current(D.current,O.current)},[C]),t(()=>{!T&&!C&&P()},[T,C,P]);function F(){let e=D.current?.getModel();f||e?.original?.dispose(),p||e?.modified?.dispose(),D.current?.dispose()}return s.createElement(xi,{width:v,height:_,isEditorReady:C,loading:h,_ref:k,className:y,wrapperProps:b})}a(Ai);function ji(e){let n=u();return t(()=>{n.current=e},[e]),n.current}var Mi=ji,Ni=new Map;function Pi({defaultValue:e,defaultLanguage:n,defaultPath:a,value:o,language:c,path:l,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=Ti,onMount:C=Ti,onChange:w,onValidate:T=Ti}){let[E,D]=r(!1),[O,k]=r(!0),A=u(null),j=u(null),M=u(null),N=u(C),P=u(S),F=u(),I=u(o),L=Mi(l),R=u(!1),z=u(!1);Ci(()=>{let e=hi.init();return e.then(e=>(A.current=e)&&k(!1)).catch(e=>e?.type!==`cancelation`&&console.error(`Monaco initialization: error:`,e)),()=>j.current?V():e.cancel()}),$(()=>{let t=Ei(A.current,e||o||``,n||c||``,l||a||``);t!==j.current?.getModel()&&(g&&Ni.set(L,j.current?.saveViewState()),j.current?.setModel(t),g&&j.current?.restoreViewState(Ni.get(l)))},[l],E),$(()=>{j.current?.updateOptions(m)},[m],E),$(()=>{!j.current||o===void 0||(j.current.getOption(A.current.editor.EditorOption.readOnly)?j.current.setValue(o):o!==j.current.getValue()&&(z.current=!0,j.current.executeEdits(``,[{range:j.current.getModel().getFullModelRange(),text:o,forceMoveMarkers:!0}]),j.current.pushUndoStop(),z.current=!1))},[o],E),$(()=>{let e=j.current?.getModel();e&&c&&A.current?.editor.setModelLanguage(e,c)},[c],E),$(()=>{f!==void 0&&j.current?.revealLine(f)},[f],E),$(()=>{A.current?.editor.setTheme(d)},[d],E);let B=i(()=>{if(!(!M.current||!A.current)&&!R.current){P.current(A.current);let t=l||a,r=Ei(A.current,o||e||``,n||c||``,t||``);j.current=A.current?.editor.create(M.current,{model:r,automaticLayout:!0,...m},h),g&&j.current.restoreViewState(Ni.get(t)),A.current.editor.setTheme(d),f!==void 0&&j.current.revealLine(f),D(!0),R.current=!0}},[e,n,a,o,c,l,m,h,g,d,f]);t(()=>{E&&N.current(j.current,A.current)},[E]),t(()=>{!O&&!E&&B()},[O,E,B]),I.current=o,t(()=>{E&&w&&(F.current?.dispose(),F.current=j.current?.onDidChangeModelContent(e=>{z.current||w(j.current.getValue(),e)}))},[E,w]),t(()=>{if(E){let e=A.current.editor.onDidChangeMarkers(e=>{let t=j.current.getModel()?.uri;if(t&&e.find(e=>e.path===t.path)){let e=A.current.editor.getModelMarkers({resource:t});T?.(e)}});return()=>{e?.dispose()}}return()=>{}},[E,T]);function V(){F.current?.dispose(),_?g&&Ni.set(l,j.current.saveViewState()):j.current.getModel()?.dispose(),j.current.dispose()}return s.createElement(xi,{width:v,height:y,isEditorReady:E,loading:p,_ref:M,className:b,wrapperProps:x})}var Fi=a(Pi);e();function Ii(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 Li={target:99,module:99,moduleResolution:2,strict:!0,noImplicitAny:!0,strictNullChecks:!0,allowNonTsExtensions:!0,isolatedModules:!0};function Ri(e,t){let n=e.languages.typescript.typescriptDefaults;n.setCompilerOptions({...n.getCompilerOptions(),...Li}),n.setExtraLibs(t.map(e=>({filePath:e.filePath,content:e.content})))}function zi({value:e,onChange:n,extraLibs:r=[],path:a=`file:///block.ts`,onDiagnostics:o,readOnly:s=!1,heightPx:c=420,dark:l=!0}){let d=u(null),p=i((e,t)=>{if(d.current=t,Ri(t,r),o===void 0)return;let n=e.getModel();if(n===null)return;let i=()=>{o(t.editor.getModelMarkers({resource:n.uri}).map(e=>({line:e.startLineNumber,column:e.startColumn,message:e.message,severity:e.severity})))};t.editor.onDidChangeMarkers(i),i()},[r,o]);return t(()=>{let e=d.current;e!==null&&Ri(e,r)},[r]),f(Fi,{height:c,defaultLanguage:`typescript`,path:a,theme:l?`vs-dark`:`vs`,value:e,onChange:e=>n(e??``),onMount:p,options:{readOnly:s,minimap:{enabled:!1},fontSize:12,lineNumbers:`on`,scrollBeyondLastLine:!1,automaticLayout:!0,tabSize:2,renderWhitespace:`selection`}})}function Bi(e){return e.some(e=>e.severity>=8)}var Vi=[{id:`blank`,name:`Blank script`,get description(){return J.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 Hi(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 Ui=Vi.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 Wi({existing:e,dirty:t,saving:n,restarting:r}){return e===null?J.t(`helpers.restartGate.saveFirstNoProcess`):n?J.t(`helpers.restartGate.saving`):r?J.t(`helpers.restartGate.restarting`):t?J.t(`helpers.restartGate.saveFirstDirty`):e.enabled?null:J.t(`helpers.restartGate.disabled`)}e();var Gi=5e3;function Ki(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 qi({blockId:e}){let{t}=Y(),r=re(e),i=Oe({addonId:r,projection:`slim`},{refetchInterval:Gi}),a=n(()=>Ki(i.data),[i.data]);return i.isLoading?o(`p`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[f(x,{className:`h-3.5 w-3.5 animate-spin`}),` `,t(`build.scriptDevicesPanel.loading`)]}):i.isError?o(`p`,{className:`text-xs text-danger`,children:[t(`build.scriptDevicesPanel.couldNotListDevices`,`Could not list devices:`),` `,i.error instanceof Error?i.error.message:String(i.error)]}):o(`section`,{className:`space-y-3 rounded border border-border p-3`,"data-testid":`script-devices-panel`,children:[o(`div`,{className:`flex items-center justify-between gap-2`,children:[o(`div`,{children:[f(`h4`,{className:`text-sm font-medium`,children:t(`build.scriptDevicesPanel.devices`,`Devices`)}),f(`p`,{className:`text-xs text-foreground-subtle`,children:f(X,{i18nKey:`build.scriptDevicesPanel.declaredBy`,values:{addonId:r},components:{code:f(`code`,{className:`text-[11px]`})}})})]}),f(q,{variant:`default`,children:a.length})]}),a.length===0?f(`p`,{className:`text-xs text-foreground-subtle`,children:f(X,{i18nKey:`build.scriptDevicesPanel.noDevices`,components:{code:f(`code`,{})}})}):f(`ul`,{className:`space-y-3`,children:a.map(e=>f(`li`,{className:`rounded border border-border/80 px-3 py-2`,"data-testid":`script-device-${e.id}`,children:o(`div`,{className:`flex flex-wrap items-baseline gap-2`,children:[f(Fe,{to:`/devices/${String(e.id)}`,className:`text-sm font-medium hover:underline`,title:t(`build.scriptDevicesPanel.openDeviceDetail`,`Open device detail`),children:e.name}),f(q,{variant:`info`,style:`outline`,children:e.type}),e.stableId!==void 0&&o(`span`,{className:`text-[11px] text-foreground-subtle`,children:[`stableId `,f(`code`,{children:e.stableId})]}),o(`span`,{className:`text-[11px] text-foreground-subtle`,children:[`#`,e.id]})]})},e.id))})]})}e();function Ji(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 Yi(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 Xi(e){switch(e){case`refresh-channel-catalog`:return J.t(`build.scriptSettingsPanel.enableChannel`);case`send-tv-schedule-now`:return J.t(`build.scriptSettingsPanel.enableTv`);case`refresh-nordvpn-catalog`:return J.t(`build.scriptSettingsPanel.enableNord`);case`probe-nordvpn-italy`:return J.t(`build.scriptSettingsPanel.enableItaly`);case`test-nordvpn-endpoint`:return J.t(`build.scriptSettingsPanel.enableVpn`);case`refresh-unifi-catalog`:return J.t(`build.scriptSettingsPanel.enableUnifi`)}}function Zi(e){if(typeof e!=`object`||!e||!(`key`in e))return null;let t=Reflect.get(e,`key`);return typeof t==`string`?t:null}function Qi(e){if(!(typeof e!=`object`||!e||!(`value`in e)))return Reflect.get(e,`value`)}function $i(e){let t={};for(let n of e.sections)for(let e of n.fields){let n=Zi(e);n!==null&&(t[n]=Qi(e))}return t}function ea(e){return typeof e!=`object`||!e?!1:Array.isArray(Reflect.get(e,`sections`))}function ta({blockId:e}){let{t}=Y(),a=E(),s=se({blockId:e},{retry:!1}),c=he({blockId:e},{refetchInterval:1e4,retry:!1}),l=le({onSuccess:()=>{c.refetch()}}),u=me(),d=ge(),[p,m]=r(null),[h,g]=r(null),[_,v]=r(null),[y,b]=r(!1),S=ea(c.data)?c.data:null,C=n(()=>S===null?{}:$i(S),[S]),w=p??C,T=i(e=>{m(e)},[]),D=p!==null,O=i(()=>{p!==null&&(g(null),l.mutate({blockId:e,patch:p},{onSuccess:()=>m(null),onError:e=>g(e instanceof Error?e.message:String(e))}))},[e,p,l]),k=i(async(t,n)=>{if(Ji(t)){b(!0),g(null),v(null);try{p!==null&&(await a.trpcClient.coreBlocks.updateBlockSettings.mutate({blockId:e,patch:p}),m(null)),await a.trpcClient.coreBlocks.updateBlockSettings.mutate({blockId:e,patch:Yi(t)}),s.data?.block?.enabled!==!0&&(await d.mutateAsync({blockId:e,enabled:!0}),v(Xi(t))),await u.mutateAsync({blockId:e}),await c.refetch(),t===`send-tv-schedule-now`?v(`Sending tonight’s schedule now…`):t===`probe-nordvpn-italy`?v(`Probing NordVPN Italy stations (no UniFi change)…`):t===`test-nordvpn-endpoint`?v(`Testing VPN endpoint on UniFi…`):t===`refresh-nordvpn-catalog`?v(`Refreshing NordVPN Italy catalog…`):t===`refresh-unifi-catalog`&&v(`Refreshing UniFi ID catalogs…`)}catch(e){g(e instanceof Error?e.message:String(e))}finally{b(!1)}}},[e,s.data?.block?.enabled,p,u,d,c,a.trpcClient.coreBlocks]);return c.isLoading?o(`p`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[f(x,{className:`h-3.5 w-3.5 animate-spin`}),` `,t(`build.scriptSettingsPanel.loading`)]}):c.isError?o(`p`,{className:`text-xs text-danger`,"data-testid":`script-settings-error`,children:[t(`build.scriptSettingsPanel.couldNotLoadSettings`,`Could not load settings:`),` `,c.error instanceof Error?c.error.message:String(c.error)]}):S===null?null:o(`section`,{className:`space-y-3 rounded border border-border p-3`,"data-testid":`script-settings-panel`,children:[o(`div`,{className:`flex items-center justify-between gap-2`,children:[o(`div`,{children:[f(`h4`,{className:`text-sm font-medium`,children:t(`build.scriptSettingsPanel.settings`,`Settings`)}),f(`p`,{className:`text-xs text-foreground-subtle`,children:f(X,{i18nKey:`build.scriptSettingsPanel.declaredBy`,components:{code:f(`code`,{})}})})]}),o(W,{size:`sm`,variant:`primary`,onClick:O,disabled:!D||l.isPending||y,children:[l.isPending&&f(x,{className:`h-3.5 w-3.5 animate-spin`}),t(`build.scriptSettingsPanel.saveSettings`,`Save settings`)]})]}),f(Ne,{schema:S,values:w,onChange:T,onAction:k}),h===null?null:f(`p`,{className:`text-xs text-danger`,"data-testid":`script-settings-save-error`,children:h}),_===null?null:f(`p`,{className:`text-xs text-foreground-subtle`,"data-testid":`script-settings-info`,children:_})]})}e();var na=`hub`;function ra({existing:e,typeDefs:t,typeDefsLoading:i,saving:a,saveError:s,restarting:c,restartError:u,onRestart:p,onSave:m,onCancel:g}){let{t:_}=Y(),v=E(),y=Ee(),{resolvedMode:w}=ce(),T=ie({code:e?.code??Ui,files:e?.files,entry:e?.entry}),[D,O]=r(e?.name??``),[k,A]=r(T.files),[j,M]=r(T.entry),[N,P]=r(T.entry),[F,I]=r(e?.placement??na),[L,R]=r(e?.integrationId??``),[z,B]=r([]),[V,H]=r(!1),[ee,te]=r(`blank`),[ne,ae]=r(null),[oe,se]=r(``),le=k[N]??``,ue=e=>{A(t=>({...t,[N]:e}))},G=Object.keys(k).toSorted(),de=Vi.length>1,fe=n(()=>[...t?.libs??[],...Ii(k,N)],[t?.libs,k,N]),K=d({mutationFn:()=>v.trpcClient.coreBlocks.compile.mutate({files:k,entry:j})}),pe=n(()=>z.filter(e=>e.severity>=8),[z]),me=Bi(z),he=D.trim()===``,ge=e===null?null:ie(e),_e=e===null||ge===null||JSON.stringify(k)!==JSON.stringify(ge.files)||j!==ge.entry||D.trim()!==e.name||F!==e.placement||(L.trim()===``?void 0:L.trim())!==e.integrationId,ve=()=>{K.reset(),m({name:D.trim(),files:k,entry:j,enabled:e?.enabled??!0,placement:F,...L.trim()===``?{}:{integrationId:L.trim()}})},ye=()=>{let e=Hi(Object.keys(k));A(t=>({...t,[e]:``})),P(e),ae(e),se(e)},Se=e=>{ae(e),se(e)},Ce=()=>{if(ne===null)return;let e=ne,t=oe.trim();if(ae(null),!(t===``||t===e)){if(k[t]!==void 0){P(t);return}A(n=>{let r={};for(let[i,a]of Object.entries(n))r[i===e?t:i]=a;return r}),j===e&&M(t),P(t)}},we=async e=>{let t=Vi.find(t=>t.id===e);if(t===void 0)return;let n=Vi.find(e=>e.id===`blank`);!(n!==void 0&&JSON.stringify(k)===JSON.stringify(n.files)&&j===n.entry)&&!await y({title:_(`build.blockEditor.loadExample`,`Load example`),message:_(`build.blockEditor.replaceTheCurrentEditorContents`,`Replace the current editor contents with this example?`),confirmLabel:_(`build.blockEditor.replace`,`Replace`),variant:`warning`})||(te(e),A({...t.files}),M(t.entry),P(t.entry),(D.trim()===``||ee===`blank`)&&O(t.id===`blank`?``:t.name))},Te=e===null?null:wn(e),De=Wi({existing:e,dirty:_e,saving:a,restarting:c});return o(`div`,{className:`space-y-4`,children:[Te!==null&&f(`div`,{className:`flex flex-wrap items-center gap-2`,children:f(q,{variant:Tn(Te.tone),children:Te.label})}),o(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[o(`label`,{className:`block text-sm`,children:[f(`span`,{className:`text-foreground-subtle`,children:_(`build.blockEditor.name`,`Name`)}),f(U,{className:`mt-1`,value:D,onChange:e=>O(e.target.value),placeholder:_(`build.blockEditor.whatThisScriptDoes`,`What this script does`)})]}),o(`label`,{className:`block text-sm`,children:[f(`span`,{className:`text-foreground-subtle`,children:_(`build.blockEditor.integrationOptional`,`Integration (optional)`)}),f(U,{className:`mt-1`,value:L,onChange:e=>R(e.target.value),placeholder:_(`build.blockEditor.leaveEmptyForTheShared`,`Leave empty for the shared system integration`)})]})]}),e===null&&de&&o(`label`,{className:`block text-sm`,children:[f(`span`,{className:`text-foreground-subtle`,children:_(`build.blockEditor.startFrom`,`Start from`)}),f(`select`,{className:`mt-1 w-full rounded border border-border bg-surface px-2 py-1.5 text-sm`,value:ee,onChange:e=>void we(e.target.value),"data-testid":`script-example-select`,children:Vi.map(e=>o(`option`,{value:e.id,children:[e.name,` — `,e.description]},e.id))})]}),o(`div`,{children:[f(xe,{selectedNodeId:F,onSelect:I,label:_(`build.blockEditor.runsOn`,`Runs on`),alwaysShow:!0}),F!==na&&o(`p`,{className:`mt-2 flex items-start gap-2 text-xs text-warning`,children:[f(h,{className:`mt-0.5 h-3.5 w-3.5 shrink-0`}),f(`span`,{children:f(X,{i18nKey:`build.blockEditor.hubOnlyWarning`,components:{strong:f(`strong`,{})}})})]})]}),o(`div`,{className:`flex min-h-[56vh] flex-col rounded border border-border`,children:[o(`div`,{className:`flex flex-wrap items-center gap-1 border-b border-border px-2 py-1.5`,children:[G.map(e=>ne===e?f(U,{value:oe,onChange:e=>se(e.target.value),onBlur:()=>Ce(),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),Ce()),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":_(`build.blockEditor.renameFile`,`Rename file`)},e):o(`button`,{type:`button`,className:`rounded px-2 py-1 text-xs ${e===N?`bg-muted font-medium text-foreground`:`text-foreground-subtle hover:text-foreground`}`,onClick:()=>P(e),onDoubleClick:()=>Se(e),title:_(`build.blockEditor.doubleClickToRename`,`Double-click to rename`),"data-testid":`script-file-tab-${e}`,children:[e,e===j?` · ${_(`build.blockEditor.entry`)}`:``]},e)),f(`button`,{type:`button`,className:`ml-1 rounded px-2 py-1 text-xs text-foreground-subtle hover:text-foreground`,onClick:ye,"data-testid":`script-file-add`,children:_(`build.blockEditor.file`,`+ file`)}),N!==j&&f(`button`,{type:`button`,className:`rounded px-2 py-1 text-xs text-foreground-subtle hover:text-foreground`,onClick:()=>M(N),title:_(`build.blockEditor.useThisFileAsThe`,`Use this file as the compile entry`),children:_(`build.blockEditor.setAsEntry`,`Set as entry`)})]}),i?f(`p`,{className:`p-4 text-sm text-foreground-subtle`,children:_(`build.blockEditor.loadingTheNodeSType`,`Loading the node's type definitions…`)}):f(zi,{value:le,onChange:ue,path:`file:///${N}`,extraLibs:fe,onDiagnostics:B,dark:w===`dark`,heightPx:560})]}),t!==void 0&&t.libs.length===0&&f(`p`,{className:`text-xs text-warning`,children:_(`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.`)}),pe.length>0&&o(`div`,{className:`space-y-1 rounded border border-danger/40 bg-danger/10 p-3 text-xs`,children:[f(`p`,{className:`font-medium text-danger`,children:_(`build.blockEditor.errorsCannotSave`,{count:pe.length})}),pe.slice(0,5).map(e=>f(`p`,{className:`text-danger`,children:_(`build.blockEditor.diagnosticLine`,{line:e.line,message:e.message})},`${String(e.line)}:${String(e.column)}:${e.message}`)),pe.length>5&&f(`p`,{className:`text-foreground-subtle`,children:_(`build.blockEditor.moreErrors`,{count:pe.length-5})})]}),K.data!==void 0&&(K.data.ok?o(`p`,{className:`flex items-center gap-2 text-xs text-success`,children:[f(S,{className:`h-3.5 w-3.5`}),` `,_(`build.blockEditor.compiledOk`)]}):o(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:[K.data.line!==void 0&&f(`span`,{className:`mr-1`,children:_(`build.blockEditor.errorLine`,{line:String(K.data.line)})}),K.data.error??_(`build.blockEditor.theCodeDoesNotCompile`,`the code does not compile`)]})),K.error!==null&&o(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:[_(`build.blockEditor.couldNotReachTheCompiler`,`Could not reach the compiler:`),` `,ia(K.error)]}),s!==null&&f(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:s}),u!==null&&f(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:u}),e!==null&&o(`div`,{className:`space-y-3`,children:[f(ta,{blockId:e.id}),f(qi,{blockId:e.id})]}),o(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(W,{variant:`outline`,onClick:()=>K.mutate(),disabled:K.isPending||a,title:_(`build.blockEditor.typeCheckOnTheNode`,`Type-check on the node without saving`),children:[K.isPending&&f(x,{className:`h-4 w-4 animate-spin`}),` `,_(`common.compile`)]}),o(W,{onClick:ve,disabled:a||me||he,children:[a&&f(x,{className:`h-4 w-4 animate-spin`}),` `,_(`common.save`)]}),o(W,{variant:`outline`,onClick:()=>p?.(),disabled:De!==null||p===void 0,title:De??_(`build.blockEditor.stopTheProcessAndLet`,`Stop the process and let the supervisor bring it back`),children:[c?f(b,{className:`h-4 w-4 animate-spin`}):f(b,{className:`h-4 w-4`}),` `,_(`build.blockEditor.restart`,`Restart`)]}),o(W,{variant:`ghost`,onClick:()=>H(!V),title:_(`build.blockEditor.showThisScriptSProcess`,`Show this script's process logs`),"data-testid":`script-logs-toggle`,children:[f(C,{className:`h-4 w-4`}),` `,_(`common.logs`),` `,V?`▾`:`▸`]}),f(W,{variant:`ghost`,onClick:g,disabled:a,children:_(`common.close`,`Close`)}),o(`span`,{className:`ml-auto text-xs text-foreground-subtle`,children:[_(`build.blockEditor.errorsCount`,{count:pe.length}),_e&&e!==null?` · ${_(`build.blockEditor.unsavedChanges`)}`:``]}),he&&f(q,{variant:`warning`,children:_(`build.blockEditor.nameRequired`,`Name required`)})]}),V&&o(`div`,{className:`rounded border border-border`,"data-testid":`script-logs-panel`,children:[f(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:e===null?_(`build.blockEditor.logsAppearOnceTheScript`,`Logs appear once the script has been saved and started.`):f(l,{children:f(X,{i18nKey:`build.blockEditor.logsOf`,values:{id:re(e.id)},components:{code:f(`code`,{})}})})}),e!==null&&f(be,{addonId:re(e.id),maxHeight:`max-h-[560px]`,showFilters:!1})]})]})}function ia(e){return e instanceof Error?e.message:String(e)}e();var aa=[`coreBlocks`,`list`],oa=[`coreBlocks`,`getTypeDefs`],sa=5e3;function ca(e){return e instanceof Error?e.message:String(e)}function la({initialBlockId:e,onBlockIdChange:i,createRequested:a=!1,onCreateConsumed:s}={}){let l=w(),{t:m}=Y(),h=E(),{state:g,openNew:_,openEdit:v,close:y}=de({editKey:`block`,newKey:`new`}),[x,S]=r(null),[T,D]=r(null),[O,k]=r(null),A=c({queryKey:aa,refetchInterval:sa,queryFn:async()=>(await h.trpcClient.coreBlocks.list.query({})).blocks}),M=g.mode!==`closed`,N=c({queryKey:oa,enabled:M,staleTime:1/0,gcTime:1/0,queryFn:()=>h.trpcClient.coreBlocks.getTypeDefs.query({})}),P=()=>{A.refetch()},F=u(null),I=A.data;t(()=>{e===void 0||F.current===e||I?.find(t=>t.id===e&&ae(t)===`code`)!==void 0&&(F.current=e,v(e),i?.(e))},[e,I,v,i]),t(()=>{a&&(S(null),_(),i?.(null),s?.())},[a,s,i,_]);let L=d({mutationFn:e=>h.trpcClient.coreBlocks.create.mutate({block:e}),onSuccess:e=>{S(e.block),v(e.block.id),i?.(e.block.id),P()}}),R=d({mutationFn:e=>h.trpcClient.coreBlocks.update.mutate(e),onSuccess:e=>{S(e.block),v(e.block.id),i?.(e.block.id),P()}}),z=d({mutationFn:e=>h.trpcClient.coreBlocks.delete.mutate({blockId:e}),onSuccess:()=>{D(null),P()}}),B=d({mutationFn:e=>h.trpcClient.coreBlocks.setEnabled.mutate(e),onSuccess:P}),V=d({mutationFn:e=>h.trpcClient.coreBlocks.restart.mutate({blockId:e}),onSuccess:P}),H=Dn((A.data??[]).filter(e=>ae(e)===`code`)),ee=A.data!==void 0&&H.length===0,te=L.isPending||R.isPending,ne=L.error===null?R.error===null?null:ca(R.error):ca(L.error),ie=g.mode===`edit`?H.find(e=>e.id===g.id)??(x!==null&&x.id===g.id?x:null):null,oe=g.mode===`new`||ie===null?null:En(H,ie),U=n(()=>[{key:`name`,header:m(`build.scriptsTab.name`,`Name`),render:e=>{let t=wn(e),n=Ae(e.updatedAt,l);return o(`div`,{className:`min-w-0`,children:[o(`div`,{className:`flex flex-wrap items-center gap-2`,children:[f(`span`,{className:`truncate font-medium`,children:e.name}),f(q,{variant:Tn(t.tone),children:t.label}),f(q,{variant:`info`,children:e.placement}),n!==null&&f(`span`,{className:`text-xs text-foreground-subtle`,children:m(`common.edited`,{when:n})})]}),f(`p`,{className:`mt-0.5 text-xs text-foreground-subtle`,children:t.detail}),O===e.id&&o(`div`,{className:`mt-2 rounded border border-border`,children:[f(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:f(X,{i18nKey:`common.logsOf`,values:{id:re(e.id)},components:{code:f(`code`,{})}})}),f(be,{addonId:re(e.id),maxHeight:`max-h-64`,showFilters:!1})]})]})},sortValue:e=>e.name,nowrap:!1},{key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,render:e=>{let t=B.isPending||z.isPending,n=V.isPending&&V.variables===e.id;return T===e.id?o(`div`,{className:`flex justify-end gap-1`,children:[f(`span`,{className:`text-xs text-foreground-subtle`,children:m(`build.scriptsTab.deleteThisScript`,`Delete this script?`)}),f(W,{variant:`danger`,onClick:()=>z.mutate(e.id),disabled:t,children:m(`common.delete`,`Delete`)}),f(W,{variant:`ghost`,onClick:()=>D(null),children:m(`common.cancel`,`Cancel`)})]}):o(`div`,{className:`flex justify-end gap-1`,children:[f(W,{variant:`ghost`,onClick:t=>{t.stopPropagation(),S(e),v(e.id),i?.(e.id)},title:m(`common.edit`,`Edit`),children:m(`common.edit`,`Edit`)}),f(W,{variant:`ghost`,onClick:t=>{t.stopPropagation(),V.mutate(e.id)},disabled:t||n||!e.enabled,title:e.enabled?m(`build.scriptsTab.restart`,`Restart`):m(`build.scriptsTab.enableItInsteadADisabled`,`Enable it instead — a disabled script has no process`),children:f(b,{className:`h-4 w-4${n?` animate-spin`:``}`})}),f(W,{variant:`ghost`,onClick:t=>{t.stopPropagation(),k(O===e.id?null:e.id)},title:m(`build.scriptsTab.logs`,`Logs`),children:f(C,{className:`h-4 w-4`})}),f(W,{variant:`ghost`,onClick:t=>{t.stopPropagation(),B.mutate({blockId:e.id,enabled:!e.enabled})},disabled:t,title:e.enabled?m(`common.disable`,`Disable`):m(`common.enable`,`Enable`),children:e.enabled?m(`common.disable`,`Disable`):m(`common.enable`,`Enable`)}),f(W,{variant:`ghost`,onClick:t=>{t.stopPropagation(),D(e.id)},title:m(`common.delete`,`Delete`),children:f(p,{className:`h-4 w-4`})})]})}}],[T,O,i,v,z,V.isPending,V.variables,B,m]);return o(`div`,{className:`space-y-3`,children:[f(`p`,{className:`text-xs text-foreground-subtle`,children:A.data===void 0?``:On(H)}),A.error!=null&&f(fe,{title:m(`build.scriptsTab.couldNotReadTheScripts`,`Could not read the scripts`),message:ca(A.error),onRetry:P}),f(Se,{columns:U,rows:H,rowKey:e=>e.id,pageSize:25,maxBodyHeight:Ce,emptyMessage:ee?m(`build.scriptsTab.noScriptsYetAScript`,`No scripts yet. A script is TypeScript the hub runs in its own process.`):A.data===void 0?m(`build.scriptsTab.loadingScripts`,`Loading scripts…`):m(`build.scriptsTab.noScriptsYet`,`No scripts yet.`),onRowClick:e=>{S(e),v(e.id),i?.(e.id)}}),f(je,{open:M,onClose:()=>{L.reset(),R.reset(),V.reset(),S(null),y(),i?.(null)},title:oe===null?m(`build.scriptsTab.newScript`,`New script`):m(`build.scriptsTab.edit`,`Edit {{name}}`,{name:oe.name}),icon:j,width:`xl`,testId:`script-editor-panel`,children:f(ra,{existing:oe,typeDefs:N.data,typeDefsLoading:N.isLoading,saving:te,saveError:ne,restarting:V.isPending,restartError:V.error===null?null:ca(V.error),onRestart:oe===null?void 0:()=>V.mutate(oe.id),onSave:e=>{let t=oe;t===null?L.mutate(e):R.mutate({blockId:t.id,block:e})},onCancel:()=>{L.reset(),R.reset(),V.reset(),S(null),y(),i?.(null)}})}),z.error!=null&&f(fe,{message:ca(z.error)}),B.error!=null&&f(fe,{message:ca(B.error)}),V.error!=null&&f(fe,{message:ca(V.error)})]})}var ua=[`automations`,`scripts`,`custom-device`];function da(e){return e!==null&&ua.some(t=>t===e)}var fa=[`coreBlocks`,`list`,`build-counts`],pa=[`block`,`create`];function ma(e){return e.filter(e=>ae(e)===`code`).length}function ha(e){return e.filter(e=>Ge(e.code)).length}function ga(e,t){return t===null?e:`${e} (${String(t)})`}function _a(){let{t:e}=Y(),t=E(),[n,r]=Ie(),i=n.get(`tab`),a=da(i)?i:`automations`,s=n.get(`create`)===`1`,l=c({queryKey:fa,refetchInterval:5e3,queryFn:async()=>(await t.trpcClient.coreBlocks.list.query({})).blocks}).data,u=l===void 0?null:ma(l),d=l===void 0?null:ha(l),p=c({queryKey:[`coreBlocks`,`listCompositions`,`build-counts`],refetchInterval:1e4,queryFn:async()=>t.trpcClient.coreBlocks.listCompositions.query({})}),m=p.data?.state===`loaded`?p.data.views.length:null,h=e=>{r(t=>{let n=new URLSearchParams(t);return n.set(`tab`,`scripts`),n.delete(`create`),e===void 0?n.delete(`block`):n.set(`block`,e),n},{replace:!0})},_=e=>{r(t=>{let n=new URLSearchParams(t);return n.set(`tab`,`automations`),n.delete(`create`),e===null?n.delete(`block`):n.set(`block`,e),n},{replace:!0})},v=e=>{r(t=>{let n=new URLSearchParams(t);return n.set(`tab`,`scripts`),n.delete(`create`),e===null?n.delete(`block`):n.set(`block`,e),n},{replace:!0})},y=()=>{r(e=>{let t=new URLSearchParams(e);return t.set(`create`,`1`),t.delete(`block`),t},{replace:!0})},b=()=>{r(e=>{let t=new URLSearchParams(e);return t.delete(`create`),t},{replace:!0})},x=a===`automations`?`New automation`:a===`scripts`?`New script`:`New composition`,S=Me(`/build`,{t:e,isAdmin:!0})??{icon:O,title:e(`nav.build`,`Build-your-self`)};return f(Re,{icon:S.icon,title:S.title,subtitle:e(`build.automationsScriptsAndComposedDevices`,`Automations, scripts and composed devices — what this installation does on its own.`),defaultSection:`automations`,sectionsLabel:`${S.title} sections`,fill:!0,actions:o(W,{type:`button`,onClick:y,"data-testid":`build-new`,children:[f(g,{className:`h-4 w-4`}),` `,x]}),sections:[{id:`automations`,label:ga(`Automations`,d),ownedParams:pa,content:f(Pn,{onOpenScripts:h,initialBlockId:a===`automations`?n.get(`block`)??void 0:void 0,onBlockIdChange:_,createRequested:a===`automations`&&s,onCreateConsumed:b})},{id:`scripts`,label:ga(`Scripts`,u),ownedParams:pa,content:f(la,{initialBlockId:a===`scripts`?n.get(`block`)??void 0:void 0,onBlockIdChange:v,createRequested:a===`scripts`&&s,onCreateConsumed:b})},{id:`custom-device`,label:ga(`Custom Device`,m),ownedParams:pa,content:f(er,{createRequested:a===`custom-device`&&s,onCreateConsumed:b})}]})}export{_a as BuildPage};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{$ as e,B as t,G as n,H as r,J as i,L as a,S as o,b as s,o as c,q as l,x as u}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEHpkaJP.js";import{D as d,It as f,Jr as p,Nt as m,Oi as h,On as g,Pn as _,Rn as v,Rr as y,Sn as b,Yi as x,_i as S,_n as C,ai as w,ar as T,bi as E,bn as D,di as O,dn as k,dt as A,fn as j,on as M,ot as ee,pi as N,un as P,yi as te,yn as F}from"./player-overlays-CZXV2ES3.js";import{t as ne}from"./hard-drive-download-Df-zlQQG.js";import{t as re}from"./memory-stick-CHkvUw7C.js";import{t as ie}from"./unlink-BKDNubwr.js";import{$r as ae,Qr as oe,ei as se,ri as ce}from"./client-CVIfL49c.js";import{$l as I,$o as le,An as ue,Bn as L,Dn as de,En as fe,Fs as pe,G as me,Ht as he,Ic as ge,Ko as _e,Lc as ve,Ln as ye,M as be,On as xe,Qs as Se,Rc as Ce,Rn as we,Tn as Te,Tt as Ee,U as De,Us as Oe,Ut as ke,Vt as Ae,Wt as je,Xt as Me,Zn as R,ac as Ne,ar as Pe,cr as Fe,dr as Ie,es as Le,gu as z,ha as Re,hu as ze,jn as Be,kn as Ve,lr as He,ns as Ue,ol as We,qo as Ge,ts as Ke,ur as qe,wt as Je,yu as B,zc as Ye}from"./src-DOs8Kg5s.js";import{t as V}from"./i18n-CmGpgquB.js";import{t as H}from"./useTranslation-D3Is_4B6.js";import{S as Xe,et as Ze}from"./index-DkNBNJNl.js";import{t as Qe}from"./AdminPage-Dla2hgly.js";import{t as $e}from"./NodeAddonsSettingsPanel-CSyREPja.js";import{f as et,l as tt,m as nt,u as rt}from"./board-model-DXmUHcnO.js";import{t as U}from"./format-size-DIxKXxtj.js";import{n as it,t as at}from"./useNodeUrlSelection-Bg0rHiIl.js";e();var ot={unpaired:`Not paired`,pending:`Pairing…`,paired:`Paired`},st=new Set([`paired`,`rejected`,`failed`,`expired`]);function W(e){return st.has(e)}function ct(e){return e.replace(/\D/g,``).slice(0,6)}function lt(e){return e.length===6}function ut(e,t){let n=Math.max(0,Math.ceil((e-t)/1e3)),r=Math.floor(n/60),i=n%60;return`${r}:${String(i).padStart(2,`0`)}`}function dt(e,t){return e.includes(`:`)?`[${e}]:${t}`:`${e}:${t}`}function ft(e){return e.length<=23?e:`${e.slice(0,20)}…`}function pt({view:e,beginError:t}){if(e===null)return t===null?`sending`:`send-failed`;switch(e.state){case`paired`:return`paired`;case`rejected`:return`rejected`;case`failed`:return`failed`;case`expired`:return`expired`;case`completing`:return`completing`;case`awaiting-confirmation`:return e.hubConfirmed&&!e.agentConfirmed?`awaiting-agent`:e.agentConfirmed&&!e.hubConfirmed?`awaiting-hub`:`awaiting-both`}}function mt(e){return e===`awaiting-both`||e===`awaiting-hub`}var ht={sending:`Sending the pairing offer to the agent…`,"send-failed":`The agent could not be reached`,"awaiting-both":`Waiting for both confirmations`,"awaiting-agent":`Confirmed here — waiting for the agent`,"awaiting-hub":`The agent is confirmed — now confirm here`,completing:`Issuing the node certificate…`,paired:`Paired`,rejected:`Pairing was rejected`,failed:`Pairing failed`,expired:`The pairing expired`},gt=2e3,_t=1e3;function vt(e){return e.message.length>0?e.message:V.t(`pairing.agentsFoundSection.requestFailed`)}function yt(e){return e.length===6?`${e.slice(0,3)} ${e.slice(3)}`:e}function bt(e){let[n,r]=i(()=>Date.now());return t(()=>{if(!e)return;let t=setInterval(()=>r(Date.now()),_t);return()=>clearInterval(t)},[e]),n}function xt({target:e,onClose:n,onSettled:r,onOpenNode:a}){let{t:c}=H(),[d,f]=i(null),[p,m]=i(null),[h,g]=i(``),[_,v]=i(null),y=l(null),b=B.agentPairing.beginPairing.useMutation(),x=B.agentPairing.confirmPairing.useMutation(),S=B.agentPairing.rejectPairing.useMutation();t(()=>{if(e===null){y.current=null,f(null),m(null),g(``),v(null);return}y.current!==e&&(y.current=e,b.mutateAsync({host:e.host,port:e.port}).then(t=>{y.current===e&&f(t.pairingId)}).catch(t=>{y.current===e&&m(vt(t))}))},[e]);let C=B.agentPairing.getPairing.useQuery({pairingId:d??``},{enabled:d!==null,refetchInterval:e=>{let t=e.state.data?.state;return t!==void 0&&W(t)?!1:gt}}),w=St(x.data??S.data??null,C.data??null),E=pt({view:w,beginError:p}),D=w!==null&&W(w.state),O=l(!1);t(()=>{if(!D){O.current=!1;return}O.current||(O.current=!0,r())},[D,r]);let k=bt(w!==null&&!D),A=()=>{d===null||!lt(h)||(v(null),x.mutate({pairingId:d,code:h},{onError:e=>{v(vt(e)),g(``)}}))};return u(Te,{open:e!==null,onOpenChange:e=>!e&&n(),children:o(de,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,children:[o(ue,{children:[u(Be,{children:c(`pairing.pairingDialog.title`,{node:e?.nodeId??``})}),u(xe,{children:e===null?``:c(`pairing.pairingDialog.eachScreenShowsACode`,`Each screen shows a code; you type the code from the OTHER screen. Agent at {{value1}}`,{value1:dt(e.host,e.port)})})]}),o(fe,{className:`space-y-4`,children:[u(Ct,{phase:E}),E===`send-failed`&&p!==null&&u(ye,{title:c(`pairing.pairingDialog.couldNotStartThePairing`,`Could not start the pairing`),message:p}),w!==null&&!D&&u(wt,{view:w,phase:E,now:k,typed:h,onType:e=>g(ct(e)),onSubmit:A,confirmError:_,busy:x.isPending}),E===`paired`&&w!==null&&u(Tt,{nodeId:w.nodeId,onOpenNode:a,onClose:n}),D&&E!==`paired`&&w?.failure!=null&&u(ye,{message:w.failure})]}),u(Ve,{children:D||E===`send-failed`?u(L,{type:`button`,variant:`outline`,onClick:n,children:c(`common.close`,`Close`)}):o(s,{children:[u(L,{type:`button`,variant:`outline`,disabled:S.isPending,onClick:()=>{if(d===null){n();return}S.mutate({pairingId:d},{onSettled:n})},children:c(`pairing.pairingDialog.reject`,`Reject`)}),mt(E)&&o(L,{type:`button`,disabled:!lt(h)||x.isPending,onClick:A,children:[x.isPending&&u(T,{className:`h-4 w-4 animate-spin`}),c(`common.confirm`,`Confirm`)]})]})})]})})}function St(e,t){if(t===null)return e;if(e===null)return t;let n=e=>(W(e.state)?10:e.state===`completing`?5:0)+ +!!e.hubConfirmed+ +!!e.agentConfirmed;return n(e)>n(t)?e:t}function Ct({phase:e}){let t=e===`sending`||e===`completing`,n=e===`paired`,r=e===`rejected`||e===`failed`||e===`expired`||e===`send-failed`;return o(`p`,{role:`status`,className:`flex items-center gap-2 text-sm font-medium ${n?`text-success`:r?`text-danger`:`text-foreground`}`,children:[t&&u(T,{className:`h-4 w-4 animate-spin`}),n&&u(O,{className:`h-4 w-4`}),r&&u(w,{className:`h-4 w-4`}),ht[e]]})}function wt({view:e,phase:t,now:n,typed:r,onType:i,onSubmit:a,confirmError:s,busy:c}){let{t:l}=H();return o(`div`,{className:`space-y-4`,children:[o(`section`,{"aria-label":l(`pairing.pairingDialog.codeOnThisHub`,`Code on this hub`),className:`rounded-md border border-border bg-surface p-3`,children:[u(`p`,{className:`text-xs text-foreground-muted`,children:l(`pairing.pairingDialog.codeOnThisHubRead`,`Code on this hub — read it out to the agent`)}),u(`p`,{"data-testid":`hub-code`,className:`mt-1 font-mono text-3xl font-semibold tracking-widest text-foreground`,children:yt(e.code)}),u(`p`,{className:`mt-2 text-xs text-foreground-muted`,children:l(`pairing.pairingDialog.onTheAgentEnterThis`,`On the agent, enter this code and the agent’s local PIN (shown on the agent’s console or log, or on its own screen).`)})]}),mt(t)?u(`form`,{className:`space-y-2`,onSubmit:e=>{e.preventDefault(),a()},children:u(me,{label:l(`pairing.pairingDialog.codeShownOnTheAgent`,`Code shown on the agent`),description:l(`pairing.pairingDialog.typeTheSixDigitsThe`,`Type the six digits the agent displays. Do not copy the code above.`),...s===null?{}:{error:s},children:u(I,{value:r,onChange:e=>i(e.target.value),inputMode:`numeric`,autoComplete:`off`,spellCheck:!1,placeholder:`000000`,maxLength:6,disabled:c,"aria-label":l(`pairing.pairingDialog.codeShownOnTheAgent`,`Code shown on the agent`),className:`font-mono tracking-widest`})})}):u(`p`,{className:`text-xs text-foreground-muted`,children:t===`awaiting-agent`?l(`pairing.pairingDialog.youConfirmedHereTheAgent`,`You confirmed here. The agent still has to enter the hub code and its PIN.`):l(`pairing.pairingDialog.working`,`Working…`)}),o(`ul`,{className:`flex flex-wrap gap-x-4 gap-y-1 text-xs text-foreground-muted`,children:[u(`li`,{children:e.hubConfirmed?l(`pairing.pairingDialog.hubConfirmed`,`Hub: confirmed`):l(`pairing.pairingDialog.hubNotConfirmed`,`Hub: not confirmed`)}),u(`li`,{children:e.agentConfirmed?l(`pairing.pairingDialog.agentConfirmed`,`Agent: confirmed`):l(`pairing.pairingDialog.agentNotConfirmed`,`Agent: not confirmed`)}),u(`li`,{"data-testid":`countdown`,children:l(`pairing.pairingDialog.expiresIn`,{countdown:ut(e.expiresAt,n)})})]})]})}function Tt({nodeId:e,onOpenNode:t,onClose:n}){let{t:r}=H(),{nodes:i}=ze(),a=i?.some(t=>t.id===e&&t.isOnline)===!0;return o(`div`,{className:`space-y-2 rounded-md border border-success/40 bg-success/10 p-3 text-sm`,children:[o(`p`,{className:`flex items-center gap-2 text-success`,children:[u(M,{className:`h-4 w-4`}),a?r(`pairing.pairingDialog.joinedAndRegisteredItsCapabilities`,`{{nodeId}} joined and registered its capabilities.`,{nodeId:e}):r(`pairing.pairingDialog.holdsItsCertificateWaitingFor`,`{{nodeId}} holds its certificate. Waiting for it to connect and register its capabilities…`,{nodeId:e})]}),u(L,{type:`button`,size:`sm`,variant:`outline`,disabled:!a,onClick:()=>{n(),t(e)},children:r(`pairing.pairingDialog.openNode`,`Open node`)})]})}var Et={paired:`success`,pending:`warning`,unpaired:`default`};function Dt({state:e,connected:t}){let{t:n}=H();return o(`span`,{className:`inline-flex items-center gap-1.5`,children:[u(Pe,{variant:Et[e],className:`text-[10px]`,children:ot[e]}),e===`paired`&&u(`span`,{className:`text-[10px] text-foreground-muted`,children:t?n(`common.connected`):n(`pairing.agentStateBadge.notConnected`,`not connected`)})]})}e();var G={pending:0,unpaired:1,paired:2};function Ot(e){if(e.trim().length===0)return;let t=Number(e);return Number.isInteger(t)&&t>=1&&t<=65535?t:null}function kt({onOpenNode:e}){let{t}=H(),r=R(),a=B.useUtils(),c=B.agentPairing.listDiscoveredAgents.useQuery(void 0,{refetchInterval:15e3}),[l,f]=i(null),[p,m]=i(null),[h,_]=i(!1),[v,y]=i(``),[x,S]=i(``),[C,w]=i(null),[E,D]=i(!1),O=()=>void a.agentPairing.listDiscoveredAgents.invalidate(),k=B.agentPairing.addAgentByAddress.useMutation({onSuccess:()=>{_(!1),y(``),S(``),w(null),O()},onError:e=>w(e.message)}),A=B.agentPairing.unpairAgent.useMutation({onSuccess:e=>{m({tone:`success`,message:`${e.nodeId}: ${e.next}${e.agentNotified?``:` The agent could not be told; forget the hub on its own page.`}`}),O()},onError:e=>m({tone:`danger`,message:t(`pairing.agentsFoundSection.unpairFailed`,`Unpair failed: {{message}}`,{message:e.message})})}),j=n(()=>(c.data?.agents??[]).toSorted((e,t)=>G[e.state]-G[t.state]),[c.data]),M=async()=>{D(!0);try{await a.agentPairing.listDiscoveredAgents.fetch({refresh:!0}),O()}finally{D(!1)}},ee=()=>{let e=Ot(x);if(e===null){w(`The port must be a whole number between 1 and 65535.`);return}w(null),k.mutate({host:v.trim(),...e===void 0?{}:{port:e}})},N=async e=>{await r({title:t(`pairing.agentsFoundSection.unpair`,`Unpair {{nodeId}}`,{nodeId:e.nodeId}),message:t(`pairing.agentsFoundSection.sCertificatesAreRevokedAt`,`{{nodeId}}'s certificates are revoked at once and it is disconnected from the mesh. It must be paired again before it can rejoin.`,{nodeId:e.nodeId}),confirmLabel:t(`pairing.agentsFoundSection.unpair2`,`Unpair`),variant:`danger`})&&(m(null),A.mutate({nodeId:e.nodeId}))},P=n(()=>[{key:`node`,header:t(`pairing.agentsFoundSection.node`,`Node`),render:e=>u(`span`,{className:`font-medium text-foreground`,children:e.nodeId}),sortValue:e=>e.nodeId},{key:`address`,header:t(`pairing.agentsFoundSection.address`,`Address`),render:e=>u(`span`,{className:`font-mono text-xs`,children:dt(e.host,e.port)}),sortValue:e=>e.host},{key:`version`,header:t(`pairing.agentsFoundSection.version`,`Version`),render:e=>e.version??`—`,sortValue:e=>e.version},{key:`state`,header:t(`pairing.agentsFoundSection.state`,`State`),render:e=>u(Dt,{state:e.state,connected:e.connected}),sortValue:e=>G[e.state]},{key:`fingerprint`,header:t(`pairing.agentsFoundSection.certificate`,`Certificate`),render:e=>e.fingerprint===null?`—`:u(`span`,{className:`font-mono text-xs`,title:e.fingerprint,children:ft(e.fingerprint)}),sortValue:e=>e.fingerprint},{key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,render:e=>e.state===`unpaired`?u(L,{type:`button`,size:`sm`,onClick:()=>f({nodeId:e.nodeId,host:e.host,port:e.port}),children:t(`pairing.agentsFoundSection.pair`,`Pair`)}):e.state===`paired`?u(L,{type:`button`,size:`sm`,variant:`outline`,disabled:A.isPending,onClick:()=>void N(e),children:t(`pairing.agentsFoundSection.unpair2`,`Unpair`)}):null}],[A.isPending,t]);return o(Ae,{headingId:`agents-found`,title:t(`pairing.agentsFoundSection.agentsFoundOnTheNetwork`,`Agents found on the network`),icon:b,testId:`agents-found`,actions:o(s,{children:[o(L,{type:`button`,size:`sm`,variant:`outline`,disabled:E,onClick:()=>void M(),children:[E?u(T,{className:`h-3.5 w-3.5 animate-spin`}):u(F,{className:`h-3.5 w-3.5`}),t(`pairing.agentsFoundSection.scan`,`Scan`)]}),o(L,{type:`button`,size:`sm`,onClick:()=>_(e=>!e),children:[u(g,{className:`h-3.5 w-3.5`}),t(`pairing.agentsFoundSection.addByAddress`,`Add by address`)]})]}),children:[o(`div`,{className:`${d} space-y-3`,children:[u(`p`,{className:`text-[11px] leading-relaxed text-foreground-muted`,children:t(`pairing.agentsFoundSection.anAgentHoldsNoSecret`,`An agent holds no secret: pairing issues it a certificate after you confirm the same six digits on this page and on the agent. Discovery needs the agent on its own IP or host networking; a Docker bridge hides it — add it by address.`)}),h&&o(`form`,{"aria-label":t(`pairing.agentsFoundSection.addAgentByAddress`,`Add agent by address`),className:`flex flex-wrap items-start gap-2`,onSubmit:e=>{e.preventDefault(),v.trim().length>0&&!k.isPending&&ee()},children:[u(me,{label:t(`pairing.agentsFoundSection.address`,`Address`),description:t(`pairing.agentsFoundSection.aPrivateOrLocalAddress`,`A private or local address only.`),...C===null?{}:{error:C},children:u(I,{value:v,onChange:e=>y(e.target.value),placeholder:`192.168.1.50`,"aria-label":t(`pairing.agentsFoundSection.agentAddress`,`Agent address`),autoComplete:`off`})}),u(me,{label:t(`pairing.agentsFoundSection.port`,`Port`),description:t(`pairing.agentsFoundSection.optional`,`Optional.`),children:u(I,{value:x,onChange:e=>S(e.target.value),placeholder:`4444`,inputMode:`numeric`,"aria-label":t(`pairing.agentsFoundSection.agentPort`,`Agent port`),className:`w-24`})}),o(L,{type:`submit`,size:`sm`,className:`mt-5`,disabled:v.trim().length===0||k.isPending,children:[k.isPending&&u(T,{className:`h-3.5 w-3.5 animate-spin`}),t(`common.add`,`Add`)]})]}),p!==null&&u(`p`,{role:`status`,className:`rounded border px-3 py-2 text-xs ${p.tone===`success`?`border-success/30 text-foreground`:`border-danger/40 text-danger`}`,children:p.message}),c.isError?u(ye,{title:t(`pairing.agentsFoundSection.couldNotListAgents`,`Could not list agents`),message:c.error?.message??t(`pairing.agentsFoundSection.requestFailed`,`Request failed`),onRetry:O}):c.isLoading?u(`p`,{className:`py-4 text-center text-xs text-foreground-muted`,children:t(`pairing.agentsFoundSection.lookingForAgents`,`Looking for agents…`)}):j.length===0?u(we,{icon:b,title:t(`pairing.agentsFoundSection.noAgentsFound`,`No agents found`),description:t(`pairing.agentsFoundSection.nothingIsAdvertisingOnThis`,`Nothing is advertising on this network. Start the agent on its own IP (or host networking), or add it by address.`)}):u(ke,{columns:P,rows:j,rowKey:e=>e.nodeId,minWidthPx:720,defaultSort:{columnKey:`state`,dir:`asc`}})]}),u(xt,{target:l,onClose:()=>f(null),onSettled:O,onOpenNode:e})]})}function At(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function jt(e){if(!At(e))return null;let t=e.ticket;if(typeof t!=`string`||t.length===0)return null;let n=e.dashboardUrl;return typeof n==`string`&&n.length>0?{ticket:t,dashboardUrl:n}:{ticket:t}}function Mt(e){let t=e.trim();return!(t.length===0||t.includes(`/`)||t.includes(`?`)||t.includes(`#`)||t.includes(`@`)||t.includes(`:`))}function K(e){return e.startsWith(`172.17.`)}function Nt(e){let t=/^100\.(\d+)\./.exec(e);if(t===null)return!1;let n=Number(t[1]);return n>=64&&n<=127}function Pt(e){if(e.startsWith(`10.`)||e.startsWith(`192.168.`))return!0;let t=/^172\.(\d+)\./.exec(e);if(t===null)return!1;let n=Number(t[1]);return n>=16&&n<=31&&!K(e)}function Ft(e,t){if(typeof t==`string`&&Mt(t))return t.trim();let n=e.filter(e=>!e.includes(`:`)),r=n.find(e=>!e.startsWith(`127.`)&&!e.startsWith(`169.254.`)&&!K(e)&&!Nt(e)&&Pt(e));if(r!==void 0)return r;for(let e of n)if(!e.startsWith(`127.`)&&!e.startsWith(`169.254.`)&&!K(e))return e;return null}function It(e){return`http://${e}:4444/`}function Lt(e,t){let n=new URL(It(e));return n.searchParams.set(`ticket`,t),n.toString()}function Rt(){return window.open(`about:blank`,`_blank`)}function zt(e,t){return e===null||e.closed?!1:(e.location.href=t,!0)}function Bt({node:e}){let{info:t}=Xe();return!e.isHub||t===null?u(`span`,{className:`text-sm font-semibold shrink-0`,children:e.name}):o(s,{children:[u(`span`,{className:`text-sm font-semibold shrink-0`,"data-testid":`node-title-name`,children:t.name}),t.name!==e.id&&u(`span`,{className:`text-xs text-foreground-subtle shrink-0`,"data-testid":`node-title-id`,children:e.id})]})}e();function Vt(e){if(e<60)return`${e}s`;let t=Math.floor(e/60);if(t<60)return`${t}m`;let n=Math.floor(t/60);return n<24?`${n}h ${t%60}m`:`${Math.floor(n/24)}d ${n%24}h`}function Ht(e){return e===`running`?`running`:e===`crashed`||e===`failed`?`error`:`stopped`}var Ut=[`trace`,`debug`,`info`,`warn`,`error`];function Wt({proc:e,nodeId:t,defaultExpanded:n,activePanel:r,onTogglePanel:a}){let{t:s}=H(),c=e.services??[],l=c.length===1,[d,f]=i(l||n),[p,m]=i(null),[g,_]=i(`info`),v=e.name.includes(`(core)`),y=Le(),b=Ke(),x=Ue(),w=async e=>{m(e);try{await y.mutateAsync({nodeId:t,addonId:e})}catch(e){console.error(`Failed to restart addon:`,e)}finally{m(null)}},T=async()=>{m(e.name);try{await b.mutateAsync({nodeId:t,processName:e.name})}catch(e){console.error(`Failed to restart process:`,e)}finally{m(null)}},E=async n=>{let r=`${t}/${e.name}`;try{await x.mutateAsync({nodeId:r,level:n}),_(n)}catch(e){console.error(`Failed to set log level:`,e)}};return o(`div`,{className:`border border-border/50 rounded-lg overflow-hidden`,children:[o(`div`,{role:l?void 0:`button`,tabIndex:l?void 0:0,onClick:l?void 0:()=>f(!d),onKeyDown:l?void 0:e=>{(e.key===`Enter`||e.key===` `)&&f(!d)},className:`flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 w-full px-3 py-2 bg-muted/20 transition-colors text-left select-none ${l?``:`hover:bg-muted/40 cursor-pointer`}`,children:[l?u(`span`,{className:`h-3 w-3 shrink-0`}):u(d?te:S,{className:`h-3 w-3 text-muted-foreground shrink-0`}),v?u(P,{className:`h-3.5 w-3.5 text-primary shrink-0`}):u(h,{className:`h-3.5 w-3.5 text-warning shrink-0`}),u(`span`,{className:`text-xs font-semibold min-w-0 flex-1 basis-full truncate sm:basis-auto`,children:e.name}),o(`span`,{className:`text-[10px] text-muted-foreground tabular-nums shrink-0`,children:[`PID `,e.pid]}),u(be,{status:Ht(e.state),label:e.state}),u(`span`,{className:`text-[10px] text-muted-foreground tabular-nums shrink-0`,children:s(`cluster.forksTab.cpu`,{percent:e.cpuPercent})}),u(`span`,{className:`text-[10px] text-muted-foreground tabular-nums shrink-0`,children:U(e.memoryRss)}),u(`span`,{className:`text-[10px] text-muted-foreground tabular-nums shrink-0`,children:Vt(e.uptimeSeconds)}),!v&&o(`div`,{className:`flex items-center gap-1`,onClick:e=>e.stopPropagation(),children:[o(Fe,{children:[u(Ie,{className:`text-[9px] px-1.5 py-0.5 rounded border border-border text-muted-foreground hover:text-foreground hover:bg-muted transition-colors font-mono`,title:s(`cluster.forksTab.setLogLevel`,`Set log level`),children:g}),u(He,{align:`end`,className:`min-w-[70px] py-0.5`,children:Ut.map(e=>u(qe,{onClick:()=>E(e),className:`h-auto px-2 py-1 text-[10px] font-mono ${e===g?`text-primary font-semibold`:``}`,children:e},e))})]}),u(`button`,{onClick:T,disabled:p===e.name,className:`p-1 rounded hover:bg-muted text-muted-foreground hover:text-foreground transition-colors disabled:opacity-50`,title:s(`cluster.forksTab.restartProcess`,`Restart process`),children:u(C,{className:`h-3 w-3 ${p===e.name?`animate-spin`:``}`})})]})]}),d&&c.length>0&&u(`div`,{className:`divide-y divide-border/30`,children:c.map(e=>o(`div`,{children:[o(`div`,{className:`flex items-center gap-2 px-3 py-1.5 pl-9 hover:bg-muted/10 transition-colors`,children:[u(`div`,{className:`h-1.5 w-1.5 rounded-full shrink-0 ${e.status===`running`?`bg-success`:`bg-muted-foreground/30`}`}),u(`span`,{className:`text-xs font-medium flex-1 min-w-0 truncate`,children:e.addonId}),e.capabilities.length>0&&o(`div`,{className:`flex gap-1 flex-shrink-0`,children:[e.capabilities.slice(0,3).map(e=>u(`span`,{className:`text-[9px] px-1 py-0.5 rounded bg-info/10 text-info truncate max-w-[80px]`,children:e},e)),e.capabilities.length>3&&o(`span`,{className:`text-[9px] text-muted-foreground`,children:[`+`,e.capabilities.length-3]})]}),o(`div`,{className:`flex items-center gap-1 shrink-0`,children:[u(`button`,{onClick:()=>a(e.addonId,`logs`),className:`p-0.5 rounded transition-colors ${r?.addonId===e.addonId&&r.type===`logs`?`bg-primary/10 text-primary`:`hover:bg-muted text-muted-foreground hover:text-foreground`}`,title:s(`cluster.forksTab.showLogsFor`,`Show logs for {{addonId}}`,{addonId:e.addonId}),children:u(j,{className:`h-3 w-3`})}),u(`button`,{onClick:()=>a(e.addonId,`events`),className:`p-0.5 rounded transition-colors ${r?.addonId===e.addonId&&r.type===`events`?`bg-primary/10 text-primary`:`hover:bg-muted text-muted-foreground hover:text-foreground`}`,title:s(`cluster.forksTab.showEventsFor`,`Show events for {{addonId}}`,{addonId:e.addonId}),children:u(D,{className:`h-3 w-3`})}),u(`button`,{onClick:()=>w(e.addonId),disabled:p===e.addonId,className:`p-0.5 rounded hover:bg-muted text-muted-foreground hover:text-foreground transition-colors disabled:opacity-50`,title:s(`cluster.forksTab.restart`,`Restart {{addonId}}`,{addonId:e.addonId}),children:u(C,{className:`h-3 w-3 ${p===e.addonId?`animate-spin`:``}`})})]})]}),r?.addonId===e.addonId&&r.type===`logs`&&u(`div`,{className:`border-t border-border/40 bg-muted/5`,children:u(Ee,{addonId:e.addonId,agentId:t,maxHeight:`max-h-48`,showFilters:!1,onClose:()=>a(e.addonId,`logs`)})}),r?.addonId===e.addonId&&r.type===`events`&&u(`div`,{className:`border-t border-border/40 bg-muted/5`,children:u(Je,{addonId:e.addonId,category:`addon.*`,maxHeight:`max-h-48`,onClose:()=>a(e.addonId,`events`)})})]},e.addonId))}),d&&c.length===0&&u(`div`,{className:`px-3 py-2 pl-9 text-[10px] text-muted-foreground`,children:s(`cluster.forksTab.noServices`,`No services`)})]})}function Gt({nodeId:e,processes:t}){let{t:n}=H(),[r,a]=i(null),o=(e,t)=>{a(n=>n?.addonId===e&&n.type===t?null:{addonId:e,type:t})};return t.length===0?u(`div`,{className:`py-4 text-xs text-muted-foreground text-center`,children:n(`cluster.forksTab.noProcessesOnThisNode`,`No processes on this node`)}):u(`div`,{className:`space-y-2 py-1`,children:t.map((t,n)=>u(Wt,{proc:t,nodeId:e,defaultExpanded:n===0,activePanel:r,onTogglePanel:o},t.name))})}var Kt={system:0,managed:1,root:2};e();function qt(e){return e<60?`${e}s`:e<3600?`${Math.floor(e/60)}m ${e%60}s`:e<86400?`${Math.floor(e/3600)}h ${Math.floor(e%3600/60)}m`:`${Math.floor(e/86400)}d ${Math.floor(e%86400/3600)}h`}function Jt(e,t=80){return e.length<=t?e:`…${e.slice(e.length-t+1)}`}function Yt({nodeId:e}){let{t}=H(),r=c(),i=z(`metrics.node-processes-snapshot`,t=>t.nodeId===e),{data:a}=Ge({nodeId:e}),s=i?.processes??a,l=n(()=>s?[...s]:[],[s]),d=n(()=>[{key:`classification`,header:t(`cluster.processesTab.class`,`Class`),sortValue:e=>Kt[e.classification],render:e=>u(`span`,{className:`inline-block rounded-full px-1.5 py-0.5 text-[10px] font-medium ${e.classification===`root`?`bg-info/20 text-info`:e.classification===`system`?`bg-foreground-subtle/20 text-foreground-subtle`:`bg-success/20 text-success`}`,children:e.classification})},{key:`pid`,header:`PID`,align:`right`,sortValue:e=>e.pid,render:e=>u(`span`,{className:`font-mono`,children:e.pid})},{key:`ppid`,header:`PPID`,align:`right`,sortValue:e=>e.ppid,render:e=>u(`span`,{className:`font-mono text-foreground-subtle`,children:e.ppid})},{key:`addonId`,header:t(`cluster.processesTab.addon`,`Addon`),sortValue:e=>e.addonId,render:e=>u(`span`,{className:`text-foreground-subtle text-[11px]`,children:e.addonId??`—`})},{key:`command`,header:t(`cluster.processesTab.command`,`Command`),nowrap:!1,render:e=>u(`span`,{className:`font-mono text-[10px] text-foreground-subtle break-all`,children:Jt(e.command)})},{key:`cpuPercent`,header:t(`cluster.processesTab.cpu`,`CPU%`),align:`right`,sortValue:e=>e.cpuPercent,render:e=>e.cpuPercent.toFixed(1)},{key:`memoryRssBytes`,header:`RSS`,align:`right`,sortValue:e=>e.memoryRssBytes,render:e=>U(e.memoryRssBytes)},{key:`uptimeSec`,header:t(`cluster.processesTab.uptime`,`Uptime`),align:`right`,sortValue:e=>e.uptimeSec,render:e=>u(`span`,{className:`text-foreground-subtle`,children:qt(e.uptimeSec)})}],[t]);return o(`div`,{className:`space-y-4`,children:[u(`div`,{className:`flex items-start justify-end gap-4`,children:o(`button`,{type:`button`,onClick:()=>r.invalidateQueries({queryKey:[[`metricsProvider`,`listNodeProcesses`]]}),className:`inline-flex items-center gap-1 rounded border border-border px-2 py-1 text-[11px] text-foreground hover:bg-surface-hover`,children:[u(F,{className:`h-3 w-3`}),` `,t(`common.refresh`)]})}),u(ke,{columns:d,rows:l,rowKey:e=>e.pid,minWidthPx:880,maxBodyHeight:je,emptyMessage:t(`cluster.processesTab.scanning`,`Scanning…`)})]})}var q={width:320,height:64},Xt=.8,J=Math.ceil(8*Xt-3)+1,Y=q.width+34,Zt=q.height+J+1+11,Qt=J+q.height+1+3+Math.ceil(8*Xt),$t=[1,2,5,10],en=[1,2,4,8,16,32,64,128,256,512,1024],tn=[1,1.5,2,2.5,3,4,5],nn=[4,3,5,2],rn=1e-9;function an(e,t){if(!Number.isFinite(e)||e<=0)return!1;if(t===`bytes`){if(!Number.isInteger(e))return!1;let t=e/1024**Math.floor(Math.log(e)/Math.log(1024));return tn.some(e=>Math.abs(t-e)<rn)}let n=e/10**Math.floor(Math.log10(e));return tn.some(e=>Math.abs(n-e)<rn)}function on(e,t,n){let r=0;for(let t of e)t!==null&&t>r&&(r=t);if(r<=t)return t;if(n===`bytes`){let e=1024**Math.floor(Math.log(r)/Math.log(1024));for(let t of en){let n=t*e;if(n>=r)return n}return 1024*e}let i=10**Math.floor(Math.log10(r));for(let e of $t){let t=e*i;if(t>=r)return t}return 10*i}function sn(e,t){if(!Number.isFinite(e)||e<=0)return[];let n=nn.find(n=>an(e/n,t))??nn[nn.length-1],r=e/n,i=[];for(let e=1;e<=n;e++)i.push(r*e);return i}var cn=2.5;function ln(e){return e*cn}function un(e,t,n,r){if(e.length===0)return[];let i=e[0].atMs,a=e.at(-1).atMs-i,o=n<=0?1:n,s=r!==void 0&&r>0?r:null;return e.map((r,c)=>{let l=a>0?(r.atMs-i)/a*t.width:c/Math.max(1,e.length-1)*t.width,u=c>0?e[c-1]:void 0;return{x:l,y:r.value===null?null:t.height-Math.min(r.value,n)/o*t.height,gapBefore:s!==null&&u!==void 0&&r.atMs-u.atMs>s}})}function dn(e){let t=[],n=!1;for(let r of e){if(r.y===null){n=!1;continue}r.gapBefore&&(n=!1),t.push(`${n?`L`:`M`}${r.x.toFixed(1)},${r.y.toFixed(1)}`),n=!0}return t.join(` `)}function fn(e,t){let n=[],r=[],i=()=>{if(r.length<2){r=[];return}let e=r.map((e,t)=>`${t===0?`M`:`L`}${e.x.toFixed(1)},${e.top.toFixed(1)}`),t=[...r].reverse().map(e=>`L${e.x.toFixed(1)},${e.bottom.toFixed(1)}`);n.push(`${e.join(` `)} ${t.join(` `)} Z`),r=[]};for(let n=0;n<e.length;n++){let a=e[n],o=t[n];if(!a||!o||a.y===null||o.y===null){i();continue}(a.gapBefore||o.gapBefore)&&i(),r.push({x:a.x,top:a.y,bottom:o.y})}return i(),n.join(` `)}function pn(e,t,n=3){if(e.length<2||n<2)return[];let r=e[0].atMs,i=e.at(-1).atMs-r;if(i<=0)return[];let a=[];for(let e=0;e<n;e++){let o=e/(n-1);a.push({atMs:r+i*o,x:o*t.width,anchor:e===0?`start`:e===n-1?`end`:`middle`})}return a}function mn(e){return e.length<2?0:Math.max(0,e.at(-1).atMs-e[0].atMs)}function hn(e){let t=[];for(let n=1;n<e.length;n++){let r=e[n];r.gapBefore&&t.push({fromX:e[n-1].x,toX:r.x})}return t}function gn(e,t){if(e.length===0)return null;let n=0,r=1/0;for(let i=0;i<e.length;i++){let a=Math.abs(e[i].x-t);a<r&&(r=a,n=i)}return n}e();var X={main:`var(--color-chart-series-a)`,gc:`var(--color-chart-series-b)`},Z=q,_n={height:Zt};function vn({title:e,points:t,mainLabel:a,gcLabel:c,formatValue:d,emptyMessage:f,gapMs:p}){let{t:m}=H(),h=r(),g=l(null),[_,v]=i(null),y=n(()=>{let e=t.map(e=>({atMs:e.atMs,value:e.main===null||e.gc===null?null:e.main+e.gc})),n=t.map(e=>({atMs:e.atMs,value:e.main})),r=on(e.map(e=>e.value),25,`linear`),i=un(e,Z,r,p),a=un(n,Z,r,p),o=a.map(e=>({x:e.x,y:e.y===null?null:Z.height,gapBefore:e.gapBefore}));return{max:r,ticks:sn(r,`linear`),upper:i,middle:a,base:o,gaps:hn(i),times:pn(e,Z),spanMs:mn(e)}},[t,p]),b=t.at(-1),x=_===null?void 0:t[_.index],S=x??b;return t.length===0||y.upper.every(e=>e.y===null)?u(Q,{title:e,children:u(An,{message:f})}):u(Q,{title:e,legend:o(s,{children:[u(On,{color:X.main,label:a}),u(On,{color:X.gc,label:c})]}),readout:S&&S.main!==null&&S.gc!==null?o(s,{children:[x!==void 0&&u(Dn,{atMs:x.atMs,spanMs:y.spanMs}),u(kn,{color:X.main,text:d(S.main)}),u(kn,{color:X.gc,text:d(S.gc)})]}):null,children:o(`svg`,{ref:g,viewBox:`0 0 ${Y} ${Zt}`,preserveAspectRatio:`none`,className:`w-full`,style:_n,role:`img`,"aria-label":m(`load.loadChart.andOverTime`,`{{title}}: {{mainLabel}} and {{gcLabel}} over time`,{title:e,mainLabel:a,gcLabel:c}),onMouseLeave:()=>v(null),onMouseMove:e=>{let t=e.currentTarget.getBoundingClientRect();if(t.width===0)return;let n=(e.clientX-t.left)/t.width*Y-34,r=gn(y.upper,n);r!==null&&v({index:r,xPx:y.upper[r].x})},children:[u(bn,{ticks:y.ticks,max:y.max,formatValue:d}),u(En,{ticks:y.times,spanMs:y.spanMs}),o(`g`,{transform:`translate(34,${J})`,clipPath:`url(#${h})`,children:[u(`clipPath`,{id:h,children:u(`rect`,{x:0,y:0,width:Z.width,height:Z.height})}),u(xn,{spans:y.gaps}),u(`path`,{d:fn(y.middle,y.base),fill:X.main,fillOpacity:.85}),u(`path`,{d:fn(y.upper,y.middle),fill:X.gc,fillOpacity:.85,stroke:`var(--color-surface, transparent)`,strokeWidth:2}),u(`path`,{d:dn(y.upper),fill:`none`,stroke:X.gc,strokeWidth:2}),_!==null&&u(`line`,{x1:_.xPx,x2:_.xPx,y1:0,y2:Z.height,stroke:`currentColor`,strokeWidth:1,className:`text-foreground-subtle`})]})]})})}function yn({title:e,points:t,formatValue:r,emptyMessage:a,axisFloor:c,axisScale:d=`linear`,gapMs:f}){let p=l(null),[m,h]=i(null),g=n(()=>{let e=on(t.map(e=>e.value),c,d),n=un(t,Z,e,f);return{max:e,ticks:sn(e,d),projected:n,gaps:hn(n),times:pn(t,Z),spanMs:mn(t)}},[t,c,d,f]),_=m===null?void 0:t[m.index],v=_??t.at(-1)??void 0;return t.length===0||g.projected.every(e=>e.y===null)?u(Q,{title:e,children:u(An,{message:a})}):u(Q,{title:e,readout:v&&v.value!==null?o(s,{children:[_!==void 0&&u(Dn,{atMs:_.atMs,spanMs:g.spanMs}),u(kn,{color:X.main,text:r(v.value)})]}):null,children:o(`svg`,{ref:p,viewBox:`0 0 ${Y} ${Zt}`,preserveAspectRatio:`none`,className:`w-full`,style:_n,role:`img`,"aria-label":e,onMouseLeave:()=>h(null),onMouseMove:e=>{let t=e.currentTarget.getBoundingClientRect();if(t.width===0)return;let n=(e.clientX-t.left)/t.width*Y-34,r=gn(g.projected,n);r!==null&&h({index:r,xPx:g.projected[r].x})},children:[u(bn,{ticks:g.ticks,max:g.max,formatValue:r}),u(En,{ticks:g.times,spanMs:g.spanMs}),o(`g`,{transform:`translate(34,${J})`,children:[u(xn,{spans:g.gaps}),u(`path`,{d:dn(g.projected),fill:`none`,stroke:X.main,strokeWidth:2}),m!==null&&u(`line`,{x1:m.xPx,x2:m.xPx,y1:0,y2:Z.height,stroke:`currentColor`,strokeWidth:1,className:`text-foreground-subtle`})]})]})})}function bn({ticks:e,max:t,formatValue:n}){let r=t<=0?1:t;return u(`g`,{className:`text-foreground-subtle`,children:e.map(e=>{let t=J+Z.height-e/r*Z.height;return o(`g`,{children:[u(`line`,{x1:34,x2:34+Z.width,y1:t,y2:t,stroke:`currentColor`,strokeWidth:.5,strokeOpacity:.3}),u(`text`,{x:0,y:t+3,fontSize:8,fill:`currentColor`,children:n(e)})]},e)})})}function xn({spans:e}){let{t}=H();return e.length===0?null:u(`g`,{className:`text-foreground-subtle`,children:e.map(e=>u(`rect`,{x:e.fromX,y:0,width:Math.max(1,e.toX-e.fromX),height:Z.height,fill:`currentColor`,fillOpacity:.12,children:u(`title`,{children:t(`load.loadChart.noSamplesInThisInterval`,`No samples in this interval — nothing was measured, nothing is drawn.`)})},`${e.fromX}-${e.toX}`))})}var Sn=10*6e4,Cn={hour:`2-digit`,minute:`2-digit`},wn={hour:`2-digit`,minute:`2-digit`,second:`2-digit`};function Tn(e,t){return new Date(e).toLocaleTimeString(void 0,t<Sn?wn:Cn)}function En({ticks:e,spanMs:t}){return e.length===0?null:u(`g`,{className:`text-foreground-subtle`,children:e.map(e=>u(`text`,{x:34+e.x,y:Qt,fontSize:8,textAnchor:e.anchor,fill:`currentColor`,children:Tn(e.atMs,t)},e.atMs))})}function Dn({atMs:e,spanMs:t}){return u(`span`,{className:`text-[10px] tabular-nums text-foreground-subtle`,children:Tn(e,t)})}function Q({title:e,legend:t,readout:n,children:r}){return o(`div`,{className:`min-w-0`,children:[o(`div`,{className:`flex items-baseline justify-between gap-2 mb-1`,children:[u(`span`,{className:`text-[10px] uppercase tracking-wider text-foreground-subtle`,children:e}),u(`div`,{className:`flex items-center gap-2`,children:n})]}),r,t&&u(`div`,{className:`flex items-center gap-3 mt-1`,children:t})]})}function On({color:e,label:t}){return o(`span`,{className:`inline-flex items-center gap-1 text-[9px] text-foreground-subtle`,children:[u(`span`,{className:`inline-block h-2 w-2 rounded-[2px]`,style:{backgroundColor:e}}),t]})}function kn({color:e,text:t}){return o(`span`,{className:`inline-flex items-center gap-1 text-[11px] tabular-nums text-foreground`,children:[u(`span`,{className:`inline-block h-2 w-2 rounded-[2px]`,style:{backgroundColor:e}}),t]})}function An({message:e}){return u(`div`,{className:`h-16 flex items-center justify-center rounded border border-dashed border-border text-[10px] text-foreground-subtle text-center px-2`,children:e})}function jn(e,t){let n=e.at(-1);return n===void 0?[t]:t.atMs>n.atMs?[...e,t]:e.some(e=>e.atMs===t.atMs)?e:[...e,t].toSorted((e,t)=>e.atMs-t.atMs)}function Mn(e,t,n,r){let i=e.get(t),a=jn(i?.points??[],r);if(i!==void 0&&a===i.points)return e;let o=new Map(e);return o.set(t,{key:t,kind:n,points:a.slice(Math.max(0,a.length-720))}),o}function Nn(e,t,n){let r=e;for(let e of ce(t,n))r=Mn(r,e.key,e.kind,e.point);return r}function Pn(e,t){let n=e;for(let e of t)for(let t of e.points)n=Mn(n,e.key,e.kind,t);return n}function Fn(e){let t=null;for(let n of e.values()){let e=n.points.at(-1);e!==void 0&&(t===null||e.atMs>t)&&(t=e.atMs)}return t}var In=12e4;function Ln(e,t){return e===null?!1:t-e>In}function Rn(e){let t=e=>{let t=e.points.at(-1);return t===void 0?-1:t.cpuMainPercent!==null&&t.cpuGcPercent!==null?t.cpuMainPercent+t.cpuGcPercent:t.cpuLifetimePercent};return[...e.values()].toSorted((e,n)=>{let r=t(n)-t(e);return r===0?e.key.localeCompare(n.key):r})}function zn(e){for(let t of e.values()){let e=t.points.at(-1);if(e&&e.cpuMainPercent!==null)return!0}return!1}var Bn={key:`cpu`,dir:`desc`};function Vn(e){let t=e.points.at(-1);return t===void 0?null:t.cpuMainPercent!==null&&t.cpuGcPercent!==null?t.cpuMainPercent+t.cpuGcPercent:t.cpuLifetimePercent}function Hn(e){return e.points.at(-1)?.memoryRssBytes??null}function Un(e,t,n){let r=n.trim().toLowerCase();return r===``?!0:e.toLowerCase().includes(r)||t.toLowerCase().includes(r)}function Wn(e,t){return t===`memory`?Hn(e):Vn(e)}function Gn(e,t,n){let r=e.filter(e=>t.selectedKeys.size>0&&!t.selectedKeys.has(e.key)?!1:Un(n(e),e.key,t.search)),i=(e,t)=>e.key.localeCompare(t.key);return[...r].toSorted((e,r)=>{if(t.sort.key===`name`){let a=n(e).localeCompare(n(r)),o=t.sort.dir===`asc`?a:-a;return o===0?i(e,r):o}let a=Wn(e,t.sort.key),o=Wn(r,t.sort.key);if(a===null&&o===null)return i(e,r);if(a===null)return 1;if(o===null)return-1;let s=t.sort.dir===`desc`?o-a:a-o;return s===0?i(e,r):s})}e();function Kn(e,n=720){let r=z(`metrics.node-processes-snapshot`,t=>t.nodeId===e),[a,o]=i(new Map),[s,c]=i(void 0),u=l(null),{data:d,isPending:f}=_e({forNodeId:e,sinceMs:s,maxPoints:n});t(()=>{d!==void 0&&o(e=>{let t=Pn(e,d.series);return u.current=Fn(t),t})},[d]);let p=r?.timestamp;t(()=>{r==null||p===void 0||(Ln(u.current,p)&&c(u.current??0),o(e=>{let t=Nn(e,r.processes,p);return u.current=Fn(t),t}))},[p]),t(()=>{o(new Map),c(void 0),u.current=null},[e]);let m=0;for(let e of a.values())m=Math.max(m,e.points.length);return{series:Rn(a),sampleCount:m,threadSplitAvailable:zn(a),loadingRetained:f,durable:d?.durable??null,bucketMs:d?.bucketMs??null,cadenceMs:d?.cadenceMs??null,retainedSamples:d?.retainedSamples??null}}var qn=`__unclaimed__`;function Jn(e,t){return{kind:e,deviceId:t,cpu:0,cpuKnown:!0,rss:0,rssKnown:!0,count:0,roles:new Set}}function Yn(e,t){return{key:e,kind:t.kind,deviceId:t.deviceId,cpuSeconds:t.cpuKnown?Math.round(t.cpu*100)/100:null,rssBytes:t.rssKnown?t.rss:null,unitCount:t.count,roles:[...t.roles].sort()}}function Xn(e,t){let n=new Map,r=new Set;for(let t of e){t.pid!==void 0&&r.add(t.pid);let e=t.deviceId!==null&&t.attribution!==`unattributable`,i=e?`device:${t.deviceId}`:`shared:${t.role}`,a=n.get(i)??Jn(e?`camera`:`shared`,e?t.deviceId:null);a.count+=1,a.roles.add(t.role),t.cpuSeconds===void 0?a.cpuKnown=!1:a.cpu+=t.cpuSeconds,t.rssBytes===void 0?a.rssKnown=!1:a.rss+=t.rssBytes,n.set(i,a)}let i=[...n.entries()].map(([e,t])=>Yn(e,t));if(t===void 0)return i;let a=t.filter(e=>!r.has(e.pid));if(a.length===0)return i;let o=Jn(`unclaimed`,null);for(let e of a)o.count+=1,o.rss+=e.memoryRssBytes;return o.cpuKnown=!1,[...i,Yn(qn,o)]}var Zn=[{family:`decode`,attribution:`measured`,unit:`one forked decode-worker child per decode SESSION`,perCamera:!0,wiredToday:!0,missingLink:``,evidence:[`packages/addon-pipeline/src/session-decode/fork-decode-worker.ts:118`,`packages/addon-pipeline/src/session-decode/fork-decode-worker.ts:131`,`packages/addon-pipeline/src/pipeline-runner/index.ts:2765`,`packages/types/src/process/child-cost-registry.ts:188`]},{family:`transcode`,attribution:`measured`,unit:`one ffmpeg child per (camera, encode plan)`,perCamera:!0,wiredToday:!0,missingLink:``,evidence:[`packages/addon-pipeline/src/stream-broker/stream-broker/egress-transcode-manager.ts:960`,`packages/addon-pipeline/src/stream-broker/stream-broker/transcode-egress.ts:282`,`packages/addon-pipeline/src/stream-broker/stream-broker/transcode-egress.ts:324`,`packages/types/src/ffmpeg/sharing-key.ts:139`]},{family:`recording`,attribution:`measured`,unit:`one passthrough ffmpeg per (camera, profile)`,perCamera:!0,wiredToday:!0,missingLink:``,evidence:[`packages/addon-pipeline/src/recorder/addon/segment-writer.ts:33`,`packages/addon-pipeline/src/recorder/addon/segment-writer.ts:217`,`packages/addon-pipeline/src/recorder/addon/segment-writer.ts:279`,`packages/addon-pipeline/src/recorder/addon/recording-controller.ts:1710`]},{family:`detection`,attribution:`accounted`,unit:`a SHARED inference pool per (node, runtime, device) — no per-camera process`,perCamera:!1,wiredToday:!0,missingLink:"Nothing is missing for COUNTING — per-camera inference milliseconds, processed/shed frames and bytes-to-pool are already accumulated. What is missing is any basis for CPU seconds: `deviceId` reaches the pool as a diagnostic label and selects nothing, so cost can only ever be apportioned, never measured. Since 2026-08-27 the pool DECLARES this itself, contributing `deviceId: null` + `attribution: unattributable` rather than leaving an observer to infer it — the renunciation is data, and it is still refused by the chart gate.",evidence:[`packages/addon-pipeline/src/detection-pipeline/provider.ts:540`,`packages/addon-pipeline/src/detection-pipeline/engine/shared-inference-pool.ts:413`,`packages/types/src/interfaces/inference-engine.ts:24`,`packages/addon-pipeline/src/pipeline-runner/timing-sampler.ts:63`,`packages/addon-pipeline/src/pipeline-runner/runner.ts:353`,`packages/addon-pipeline/src/pipeline-runner/runner.ts:849`,`packages/addon-pipeline/src/pipeline-runner/frame-lazy-metrics.ts:100`]},{family:`streaming`,attribution:`measured`,unit:"one StreamBroker per `${deviceId}/${camStreamId}`, with an exact RTP ring byte counter",perCamera:!0,wiredToday:!1,missingLink:"The ffmpeg-backed ingest is now reported per camera, but that is the minority path. `rtpRingBytes` — the exact figure for the in-process case — is maintained on every push and drop and is still private and absent from `getStats()`. The three `EncodedRingBuffer`s track packets and duration and have no byte accumulator at all; the only byte figure they offer is `preRollBudgetBytes`, which is a BUDGET, not an occupancy.",evidence:[`packages/addon-pipeline/src/stream-broker/stream-broker/stream-broker.ts:2895`,`packages/addon-pipeline/src/stream-broker/rtsp/ffmpeg-push-reader.ts:189`,`packages/addon-pipeline/src/stream-broker/stream-broker/stream-broker.ts:494`,`packages/addon-pipeline/src/stream-broker/stream-broker/stream-broker.ts:498`,`packages/addon-pipeline/src/stream-broker/stream-broker/stream-broker.ts:2505`,`packages/addon-pipeline/src/stream-broker/stream-broker/pre-roll.ts:269`]}];function Qn(e){return e.attribution===`measured`&&e.wiredToday}function $n(){let e=new Set;for(let t of Zn)Qn(t)&&e.add(t.family);return e}var er=$n();function tr(e){return!er.has(e.role)||e.deviceId===null?!1:e.attribution===`measured`}function nr(e){return`${e.addonId}${e.role}${e.unit}${e.pid??`-`}`}function rr(){return{cpuSeconds:0,cpuKnown:!0,rssBytes:0,rssKnown:!0,unitCount:0,roles:new Set}}function ir(e,t,n){if(t.cpuSeconds===void 0)return null;if(e===void 0)return t.startedAtMs===void 0||t.startedAtMs<n?null:t.cpuSeconds;if(e.cpuSeconds===void 0||e.startedAtMs===void 0||t.startedAtMs===void 0||e.startedAtMs!==t.startedAtMs)return null;let r=t.cpuSeconds-e.cpuSeconds;return r<0?null:r}function ar(e){return Math.round(e*10)/10}function or(e,t){let n=t.atMs-e.atMs;if(n<=0)return[];let r=n/1e3,i=new Map;for(let t of e.entries)tr(t)&&i.set(nr(t),t);let a=new Map,o=new Set;for(let n of t.entries){if(!tr(n)||n.deviceId===null)continue;let t=nr(n);o.add(t);let r=a.get(n.deviceId)??rr();r.unitCount+=1,r.roles.add(n.role);let s=ir(i.get(t),n,e.atMs);s===null?r.cpuKnown=!1:r.cpuSeconds+=s,n.rssBytes===void 0?r.rssKnown=!1:r.rssBytes+=n.rssBytes,a.set(n.deviceId,r)}for(let[e,t]of i){if(o.has(e)||t.deviceId===null)continue;let n=a.get(t.deviceId);n!==void 0&&(n.cpuKnown=!1)}return[...a.entries()].map(([e,n])=>({deviceId:e,point:{atMs:t.atMs,cpuPercent:n.cpuKnown?ar(n.cpuSeconds/r*100):null,rssBytes:n.rssKnown?n.rssBytes:null,unitCount:n.unitCount,roles:[...n.roles].toSorted()}}))}function sr(e,t){if(t.length===0)return e;let n=new Map(e);for(let e of t){let t=n.get(e.deviceId),r=t?.points.at(-1);if(r!==void 0&&e.point.atMs<=r.atMs)continue;let i=[...t?.points??[],e.point];n.set(e.deviceId,{deviceId:e.deviceId,points:i.slice(Math.max(0,i.length-720))})}return n}function cr(e){let t=e=>{for(let t=e.points.length-1;t>=0;t--){let n=e.points[t]?.cpuPercent;if(n!=null)return n}return-1};return[...e.values()].toSorted((e,n)=>{let r=t(n)-t(e);return r===0?e.deviceId-n.deviceId:r})}function lr(e){let t=e.indexOf(`@`);return t===-1?{addonId:e,nodeId:null}:{addonId:e.slice(0,t),nodeId:e.slice(t+1)}}function ur(e,t){let n=lr(e);return n.nodeId===null?t.isHub:n.nodeId===t.nodeId}function dr(e,t){return e.filter(e=>ur(e.addonId,t))}e();function fr(e){let n=z(`metrics.node-processes-snapshot`,t=>t.nodeId===e.nodeId),r=We(void 0,{staleTime:1/0,refetchOnWindowFocus:!1}),[a,o]=i(new Map),s=l(null),c=l(r.refetch);c.current=r.refetch;let u=n?.timestamp;t(()=>{u!==void 0&&c.current()},[u]),t(()=>{o(new Map),s.current=null},[e.nodeId,e.isHub]);let d=r.data,f=r.dataUpdatedAt;t(()=>{if(d===void 0||f===0)return;let t={atMs:f,entries:dr(d,e)},n=s.current;if(s.current=t,n===null)return;let r=or(n,t);r.length!==0&&o(e=>sr(e,r))},[d,f,e.nodeId,e.isHub]);let p=d===void 0?[]:dr(d,e),m=n?.processes,h=Xn(p,m);return{series:cr(a),unclaimed:h.find(e=>e.kind===`unclaimed`)??null,loading:r.isPending,error:r.error===null?null:r.error.message}}function pr(e){let t=new Map;for(let n of e){let e=n.name?.trim();e===void 0||e===``||t.set(n.id,e)}return t}var mr=25,hr=64*1024*1024,gr=1e4;function _r({scope:e,cadenceMs:t}){let{t:n}=H(),r=fr(e),{data:i=[]}=Re({isCamera:!0,projection:`slim`}),a=pr(i),s=ln(t??gr);return o(`section`,{className:`space-y-3`,children:[r.error!==null&&o(`div`,{className:`flex items-start gap-2 rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2 text-[11px] text-destructive`,children:[u(m,{className:`h-3 w-3 mt-0.5 shrink-0`}),u(`span`,{children:n(`cameraLoad.readFailed`,`Could not read the load contributions: {{error}}. This is a failed read, NOT an idle cluster.`,{error:r.error})})]}),u(yr,{unclaimed:r.unclaimed}),r.series.length===0&&r.error===null&&u(`div`,{className:`rounded-md border border-dashed border-border px-3 py-6 text-center text-[11px] text-foreground-subtle`,children:r.loading?n(`cameraLoad.loading`,`Reading what the addons report…`):n(`cameraLoad.waitingWindow`,`No per-camera window yet.`)}),u(`div`,{className:`space-y-3`,children:r.series.map(e=>o(`div`,{className:`rounded-lg border border-border p-3`,children:[o(`div`,{className:`flex items-baseline justify-between gap-2 mb-2`,children:[u(vr,{deviceId:e.deviceId,name:a.get(e.deviceId)}),u(`span`,{className:`text-[10px] text-foreground-subtle`,children:n(`cameraLoad.unitCount`,`{{count}} unit(s): {{roles}}`,{count:e.points.at(-1)?.unitCount??0,roles:(e.points.at(-1)?.roles??[]).join(`, `)})})]}),o(`div`,{className:`grid grid-cols-1 md:grid-cols-2 gap-4`,children:[u(yn,{title:n(`cameraLoad.cpuTitle`,`CPU % of one core (delta)`),points:e.points.map(e=>({atMs:e.atMs,value:e.cpuPercent})),formatValue:e=>`${e.toFixed(1)}%`,axisFloor:mr,gapMs:s,emptyMessage:n(`cameraLoad.cpuUnavailable`,`No measurable window yet.`)}),u(yn,{title:n(`cameraLoad.memoryTitle`,`Memory RSS`),points:e.points.map(e=>({atMs:e.atMs,value:e.rssBytes})),formatValue:U,axisFloor:hr,axisScale:`bytes`,gapMs:s,emptyMessage:n(`cameraLoad.memoryUnavailable`,`No memory reported.`)})]})]},e.deviceId))})]})}function vr({deviceId:e,name:t}){let{t:n}=H();return t===void 0?u(`span`,{className:`text-xs font-medium text-foreground`,children:n(`cameraLoad.deviceLabel`,`Camera {{deviceId}}`,{deviceId:e})}):o(`span`,{className:`flex items-baseline gap-1.5 min-w-0`,children:[u(`span`,{className:`text-xs font-medium text-foreground truncate`,children:t}),o(`span`,{className:`shrink-0 text-[10px] font-mono text-foreground-subtle`,children:[`#`,e]})]})}function yr({unclaimed:e}){let{t}=H();return e===null||e.unitCount===0?null:u(`div`,{className:`flex items-center gap-2`,children:u(`span`,{className:`text-[10px] px-1.5 py-0.5 rounded-full bg-warning/10 text-warning font-medium tabular-nums`,children:t(`cameraLoad.unclaimedBadge`,`{{count}} unclaimed · {{rss}}`,{count:e.unitCount,rss:e.rssBytes===null?`—`:U(e.rssBytes)})})})}e();var br=256*1024*1024,xr=1e4;function Sr({nodeId:e,isHub:t}){let{t:r}=H(),{series:a,sampleCount:s,threadSplitAvailable:c,loadingRetained:l,bucketMs:d,cadenceMs:f}=Kn(e),[p,h]=i(``),[g,_]=i(new Set),[v,y]=i(Bn),b=e=>e.key===`__root__`?r(`clusterLoad.bucketRoot`,`Node supervisor`):e.key===`__unattributed__`?r(`clusterLoad.bucketUnattributed`,`Unattributed processes`):e.key,x=ln(d??f??xr),S=n(()=>Gn(a,{search:p,selectedKeys:g,sort:v},b),[a,p,g,v]),C=e=>{_(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})};return o(`div`,{className:`space-y-4`,children:[u(Cr,{bucketMs:d,cadenceMs:f}),!c&&s>0&&o(`div`,{className:`flex items-start gap-2 rounded-md border border-warning/40 bg-warning/5 px-3 py-2 text-[11px] text-warning`,children:[u(m,{className:`h-3 w-3 mt-0.5 shrink-0`}),u(`span`,{children:r(`clusterLoad.noThreadSplit`,`No thread-level CPU split on this node — /proc/<pid>/task is Linux-only, and the first sample after a restart has no window to measure. CPU below falls back to the ps lifetime AVERAGE, which is not a rate.`)})]}),s===0&&u(`div`,{className:`rounded-md border border-dashed border-border px-3 py-6 text-center text-[11px] text-foreground-subtle`,children:l?r(`clusterLoad.loadingRetained`,`Reading the retained series from this node…`):r(`clusterLoad.waitingFirstSample`,`No retained samples for this node — waiting for the next snapshot (up to 20s). The chart needs two to draw a rate.`)}),a.length>0&&o(`div`,{className:`space-y-2`,children:[o(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(`label`,{className:`relative flex-1 min-w-[160px]`,children:[u(k,{className:`pointer-events-none absolute left-2 top-1/2 h-3 w-3 -translate-y-1/2 text-foreground-subtle`}),u(`input`,{type:`search`,value:p,onChange:e=>h(e.target.value),placeholder:r(`clusterLoad.searchPlaceholder`,`Find a runner…`),"aria-label":r(`clusterLoad.searchLabel`,`Find a runner`),className:`w-full rounded border border-border bg-background py-1 pl-7 pr-2 text-[11px] text-foreground placeholder:text-foreground-subtle`})]}),u(wr,{sort:v,onChange:y})]}),o(`div`,{className:`flex flex-wrap items-center gap-1`,children:[a.map(e=>{let t=g.has(e.key);return u(`button`,{type:`button`,"aria-pressed":t,onClick:()=>C(e.key),className:`rounded-full border px-2 py-0.5 text-[10px] transition-colors ${t?`border-primary bg-primary/10 text-primary`:`border-border text-foreground-subtle hover:text-foreground`}`,children:b(e)},e.key)}),g.size>0&&o(`button`,{type:`button`,onClick:()=>_(new Set),className:`inline-flex items-center gap-1 rounded-full border border-border px-2 py-0.5 text-[10px] text-foreground-subtle hover:text-foreground`,children:[u(A,{className:`h-2.5 w-2.5`}),r(`clusterLoad.clearFilter`,`All runners`)]})]})]}),a.length>0&&S.length===0&&u(`div`,{className:`rounded-md border border-dashed border-border px-3 py-6 text-center text-[11px] text-foreground-subtle`,children:r(`clusterLoad.noMatches`,`No runner matches this search on {{count}} present. The node is reporting — the filter is hiding them.`,{count:a.length})}),u(`div`,{className:`space-y-3`,children:S.map(e=>o(`div`,{className:`rounded-lg border border-border p-3`,children:[o(`div`,{className:`flex items-baseline justify-between gap-2 mb-2`,children:[u(`span`,{className:`text-xs font-medium text-foreground`,children:b(e)}),u(`span`,{className:`text-[10px] text-foreground-subtle`,children:r(`clusterLoad.processCount`,`{{count}} process(es)`,{count:e.points.at(-1)?.processCount??0})})]}),o(`div`,{className:`grid grid-cols-1 md:grid-cols-2 gap-4`,children:[u(vn,{title:c?r(`clusterLoad.cpuTitle`,`CPU % of one core`):r(`clusterLoad.cpuTitleLifetime`,`CPU % (ps lifetime average)`),mainLabel:r(`clusterLoad.seriesMain`,`Main threads`),gcLabel:r(`clusterLoad.seriesGc`,`GC / V8 helpers`),points:e.points.map(e=>({atMs:e.atMs,main:e.cpuMainPercent,gc:e.cpuGcPercent})),formatValue:e=>`${e.toFixed(0)}%`,gapMs:x,emptyMessage:r(`clusterLoad.cpuUnavailable`,`No thread split on this node. Lifetime average: {{avg}}%`,{avg:(e.points.at(-1)?.cpuLifetimePercent??0).toFixed(1)})}),u(yn,{title:r(`clusterLoad.memoryTitle`,`Memory RSS`),points:e.points.map(e=>({atMs:e.atMs,value:e.memoryRssBytes})),formatValue:U,axisFloor:br,axisScale:`bytes`,gapMs:x,emptyMessage:r(`clusterLoad.memoryUnavailable`,`No memory samples yet.`)})]})]},e.key))}),u(_r,{scope:{nodeId:e,isHub:t},cadenceMs:f})]})}function Cr({bucketMs:e,cadenceMs:t}){let{t:n}=H();return e===null?null:u(`p`,{className:`text-[10px] text-foreground-subtle`,children:t!==null&&e>t?n(`clusterLoad.captionBucket`,`1 point = {{bucket}}s (bucket MAXIMUM, not a mean)`,{bucket:Math.round(e/1e3)}):n(`clusterLoad.captionRaw`,`1 point = 1 snapshot`)})}function wr({sort:e,onChange:t}){let{t:n}=H(),r=[{key:`cpu`,label:n(`clusterLoad.sortCpu`,`CPU`)},{key:`memory`,label:n(`clusterLoad.sortMemory`,`Memory`)},{key:`name`,label:n(`clusterLoad.sortName`,`Name`)}];return o(`div`,{className:`flex items-center gap-1`,children:[u(`span`,{className:`text-[10px] text-foreground-subtle`,children:n(`clusterLoad.sortBy`,`Sort by`)}),r.map(n=>{let r=e.key===n.key;return o(`button`,{type:`button`,"aria-pressed":r,onClick:()=>t(r?{key:n.key,dir:e.dir===`desc`?`asc`:`desc`}:{key:n.key,dir:n.key===`name`?`asc`:`desc`}),className:`rounded border px-1.5 py-0.5 text-[10px] transition-colors ${r?`border-primary bg-primary/10 text-primary`:`border-border text-foreground-subtle hover:text-foreground`}`,children:[n.label,r&&(e.dir===`desc`?` ↓`:` ↑`)]},n.key)})]})}var Tr=`No per-node settings on this node. Every other setting these addons expose is one value for the whole cluster — edit those in System → Settings, not here.`;function Er({nodeId:e,addonIds:t}){let{t:n}=H();return t.length===0?u(`div`,{className:`py-4 text-xs text-muted-foreground text-center`,children:n(`cluster.nodeDetailSettingsTab.noAddonsOnThisNode`,`No addons on this node`)}):u(`div`,{className:`w-full py-2`,children:u($e,{nodeId:e,addonIds:t,level:`global`,fieldScope:`perNode`,emptyMessage:Tr,selfTabbed:!0})})}e();function Dr({nodeId:e,addons:t}){let{t:r}=H(),i=c(),{data:a,isLoading:o}=pe({nodeId:e}),s=n(()=>{let e=new Map;for(let n of t)for(let t of n.capabilities){let r=e.get(t)??[];r.push(n.id),e.set(t,r)}return[...e.entries()].toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>({capName:e,providers:t}))},[t]),l=Ne({onSuccess:()=>{i.invalidateQueries({queryKey:[[`pipelineOrchestrator`,`getCapabilityBindings`]]})}});return s.length===0?u(`div`,{className:`py-4 text-xs text-muted-foreground text-center`,children:r(`cluster.nodeDetailCapabilitiesTab.noCapabilitiesOnThisNode`,`No capabilities on this node`)}):u(ke,{columns:[{key:`capName`,header:r(`cluster.nodeDetailCapabilitiesTab.capability`,`Capability`),width:`w-1/2`,sortValue:e=>e.capName,render:e=>u(`span`,{className:`font-medium`,children:e.capName})},{key:`provider`,header:r(`cluster.nodeDetailCapabilitiesTab.boundProvider`,`Bound provider`),render:t=>{let n=a?.[t.capName]??t.providers[0]??``,i=t.providers.length===1;return u(`select`,{value:n,onChange:n=>l.mutate({nodeId:e,capName:t.capName,addonId:n.target.value}),disabled:i||l.isPending||o,className:`w-full rounded-md border border-border bg-surface px-2 py-1 text-xs text-foreground focus:outline-none focus:ring-1 focus:ring-primary disabled:opacity-60`,title:i?r(`cluster.nodeDetailCapabilitiesTab.onlyOneProviderInstalledChoice`,`Only one provider installed — choice becomes available once a second addon registers this capability`):void 0,children:t.providers.map(e=>u(`option`,{value:e,children:e},e))})}}],rows:s,rowKey:e=>e.capName,minWidthPx:520,maxBodyHeight:je})}e();function Or(e){if(e==null)return`—`;let t=Math.floor(e/1e3),n=Math.floor(t/86400),r=Math.floor(t%86400/3600),i=Math.floor(t%3600/60);return n>0?`${n}d ${r}h ${i}m`:r>0?`${r}h ${i}m`:`${i}m`}function kr(e){let{t}=H(),[n,r]=i(!1),[a,s]=i(e.name),l=c(),d=le({onSuccess:()=>{l.invalidateQueries({queryKey:[[`nodes`,`topology`]]})}}),f=(e.localIps??[]).filter(e=>!e.includes(`:`)),p=(e.localIps??[]).filter(e=>e.includes(`:`)),m=async()=>{if(!a.trim()||a===e.name){r(!1);return}try{await d.mutateAsync({nodeId:e.nodeId,name:a.trim()}),r(!1)}catch(e){console.error(`Rename failed:`,e)}},h=[[`Node ID`,u(`span`,{className:`font-mono text-xs`,children:e.nodeId})],[`Display Name`,n?o(`div`,{className:`flex items-center gap-1.5`,children:[u(`input`,{type:`text`,className:`flex-1 px-2 py-0.5 text-xs border border-border rounded bg-background focus:outline-none focus:ring-1 focus:ring-primary`,value:a,onChange:e=>s(e.target.value),onKeyDown:e=>{e.key===`Enter`&&m(),e.key===`Escape`&&r(!1)},disabled:d.isPending,autoFocus:!0}),u(`button`,{onClick:()=>void m(),disabled:d.isPending,className:`p-0.5 text-success hover:bg-success/10 rounded`,title:t(`common.save`,`Save`),children:u(E,{className:`h-3.5 w-3.5`})}),u(`button`,{onClick:()=>r(!1),className:`p-0.5 text-muted-foreground hover:bg-muted rounded`,title:t(`common.cancel`,`Cancel`),children:u(A,{className:`h-3.5 w-3.5`})})]}):o(`div`,{className:`flex items-center gap-1.5`,children:[u(`span`,{className:`text-xs`,children:e.name}),!e.isHub&&u(`button`,{onClick:()=>{s(e.name),r(!0)},className:`p-0.5 text-muted-foreground hover:text-primary rounded`,title:t(`cluster.nodeInfoTab.rename`,`Rename`),children:u(_,{className:`h-3 w-3`})})]})],[`Hostname`,u(`span`,{className:`text-xs`,children:e.hostname})],[`Role`,e.isHub?u(`span`,{className:`text-[10px] px-1.5 py-0.5 rounded bg-primary/10 text-primary font-medium`,children:t(`cluster.nodeInfoTab.hub`,`Hub`)}):u(`span`,{className:`text-[10px] px-1.5 py-0.5 rounded bg-muted text-muted-foreground font-medium`,children:t(`cluster.nodeInfoTab.agent`,`Agent`)})],[`Root Package`,e.rootPackage?o(`span`,{className:`font-mono text-xs`,children:[e.rootPackage.name,`@`,e.rootPackage.version]}):u(`span`,{className:`text-xs text-muted-foreground`,children:`—`})],[`Platform`,o(`span`,{className:`text-xs`,children:[e.platform,` / `,e.arch]})],[`CPU`,o(`span`,{className:`text-xs`,children:[e.cpuModel??`—`,` (`,t(`cluster.nodeInfoTab.cores`,{count:e.cpuCores}),`)`]})],[`Memory`,u(`span`,{className:`text-xs`,children:e.memoryMB>0?t(`cluster.nodeInfoTab.gb`,`{{value1}} GB`,{value1:(e.memoryMB/1024).toFixed(1)}):`—`})],[`Uptime`,u(`span`,{className:`text-xs`,children:Or(e.uptime)})],[`Engines`,e.engines.length>0?u(`div`,{className:`flex flex-wrap gap-1`,children:e.engines.map(e=>u(`span`,{className:`text-[9px] px-1.5 py-0.5 rounded-full bg-primary/10 text-primary font-medium`,children:e},e))}):u(`span`,{className:`text-xs text-muted-foreground`,children:`—`})]];return f.length>0&&h.push([`IPv4`,u(`div`,{className:`flex flex-wrap gap-1.5`,children:f.map((e,t)=>u(`span`,{className:`font-mono text-xs px-1.5 py-0.5 rounded bg-muted`,children:e},`${e}-${t}`))})]),p.length>0&&h.push([`IPv6`,u(`div`,{className:`flex flex-wrap gap-1.5`,children:p.map((e,t)=>u(`span`,{className:`font-mono text-[10px] px-1.5 py-0.5 rounded bg-muted truncate max-w-[280px]`,title:e,children:e},`${e}-${t}`))})]),u(`div`,{className:`py-2`,children:u(`table`,{className:`w-full text-sm`,children:u(`tbody`,{children:h.map(([e,t],n)=>o(`tr`,{className:n%2==0?`bg-muted/20`:``,children:[u(`td`,{className:`py-1.5 px-2 text-xs font-medium text-muted-foreground w-28 align-top whitespace-nowrap`,children:e}),u(`td`,{className:`py-1.5 px-2`,children:t})]},e))})})})}e();function Ar({nodeId:e,value:n,detectedHosts:r,status:a,errorMessage:s,onCommit:c}){let{t:l}=H(),[d,f]=i(n??``);t(()=>{f(n??``)},[n]);let p=r[0],m=p===void 0?`auto-detect`:`auto: ${p}`,h=a===`pending`,g=d.trim(),_=g!==(n??``),v=_&&!h,y=()=>{v&&c(e,g.length>0?g:null)};return o(`div`,{className:`flex items-center gap-1.5`,children:[u(I,{"aria-label":l(`placementBoard.reachableHostInput.reachableHostFor`,`Reachable host for {{nodeId}}`,{nodeId:e}),type:`text`,inputMode:`url`,autoComplete:`off`,spellCheck:!1,placeholder:m,value:d,disabled:h,onChange:e=>f(e.target.value),onBlur:y,onKeyDown:e=>{e.key===`Enter`&&y(),e.key===`Escape`&&f(n??``)},className:`w-36`}),o(L,{variant:`outline`,size:`sm`,onClick:y,disabled:!v,"aria-label":l(`placementBoard.reachableHostInput.saveReachableHostFor`,`Save reachable host for {{nodeId}}`,{nodeId:e}),title:l(`placementBoard.reachableHostInput.saveReachableHost`,`Save reachable host`),children:[h?u(T,{className:`h-3 w-3 animate-spin`,"aria-hidden":`true`}):u(E,{className:`h-3 w-3`,"aria-hidden":`true`}),l(`common.save`,`Save`)]}),!_&&!h&&a===`success`&&u(E,{className:`h-3.5 w-3.5 shrink-0 text-success`,"aria-label":l(`placementBoard.reachableHostInput.saved`,`Saved`),role:`img`}),a===`error`&&u(`span`,{title:s??l(`placementBoard.reachableHostInput.failedToSaveReachableHost`,`Failed to save reachable host`),children:u(N,{className:`h-3.5 w-3.5 shrink-0 text-danger`,"aria-label":s??l(`placementBoard.reachableHostInput.failedToSaveReachableHost`,`Failed to save reachable host`),role:`img`})})]})}e();function jr(e){let t=ae.safeParse(et(e,`color`));return t.success?t.data:null}function Mr(e,t){return t.variables?.agentNodeId===e?t.isPending?`pending`:t.isError?`error`:t.isSuccess?`success`:`idle`:`idle`}function Nr({nodeId:e,detectedHosts:t}){let{t:r}=H(),i=c(),a=Oe(void 0),s=Se({onSuccess:()=>tt(i)}),l=Se({onSuccess:()=>tt(i)}),d=n(()=>a.data?.find(t=>t.nodeId===e)?.settings,[a.data,e]),f=jr(d)??(a.isLoading?null:se(e)),p=nt(d,`reachableHost`),m=Mr(e,s),h=m===`error`?rt(s.error):null,g=t.filter(e=>!e.includes(`:`)),_=t=>{t!==f&&l.mutate({agentNodeId:e,color:t})};return o(`div`,{className:`rounded-lg border border-border bg-surface/40 divide-y divide-border px-3`,children:[u(he,{label:r(`nodes.general.nodeColour`,`Node colour`),children:u(`div`,{role:`group`,"aria-label":r(`nodes.general.nodeColourGroup`,`Node colour`),className:`flex flex-wrap gap-2`,children:oe.map(e=>{let t=f===e;return u(L,{type:`button`,role:`radio`,"aria-checked":t,"aria-label":e,variant:`outline`,size:`sm`,disabled:a.isLoading||l.isPending,title:e,onClick:()=>_(e),className:`h-6 w-6 min-w-6 shrink-0 rounded-full border-0 p-0 ${Me(e)} ${t?`ring-2 ring-primary ring-offset-2 ring-offset-background`:`opacity-80 hover:opacity-100`}`,children:u(`span`,{className:`sr-only`,children:e})},e)})})}),u(he,{label:r(`nodes.general.reachableHost`,`Reachable host`),children:u(Ar,{nodeId:e,value:p,detectedHosts:g,status:m,errorMessage:h,onCommit:(e,t)=>{s.mutate({agentNodeId:e,reachableHost:t})}})})]})}e();var Pr=[[`serverManagement`,`getServerPackageStatus`]];function Fr({label:e,tone:t}){return u(`span`,{className:`inline-flex items-center rounded px-2 py-0.5 text-[11px] font-medium ${{neutral:`bg-surface-muted text-foreground-subtle`,ok:`bg-success/15 text-success`,info:`bg-info/15 text-info`,warn:`bg-warning/15 text-warning`,error:`bg-danger/15 text-danger`}[t]}`,children:e})}function $({label:e,value:t}){return o(`div`,{className:`flex items-center justify-between gap-4 text-sm`,children:[u(`span`,{className:`text-foreground-subtle`,children:e}),u(`span`,{className:`font-mono text-foreground`,children:t??`—`})]})}function Ir({runningVersion:e,latestVersion:t,seedVersion:n,nodeRuntimeVersion:r,labelRunning:i,labelLatest:a,labelSeed:s,labelRuntime:c}){return u(`div`,{className:`flex flex-wrap gap-x-3 gap-y-1 text-sm`,children:[{key:`running`,label:i,value:e},{key:`latest`,label:a,value:t},{key:`seed`,label:s,value:n},{key:`runtime`,label:c,value:r}].map(({key:e,label:t,value:n})=>o(`span`,{className:`inline-flex items-baseline gap-1`,children:[u(`span`,{className:`text-foreground-subtle`,children:t}),u(`span`,{className:`font-mono text-foreground`,children:n??`—`})]},e))})}var Lr={ok:`border-success/40 bg-success/10 text-success`,warn:`border-warning/40 bg-warning/10 text-warning`,error:`border-danger/40 bg-danger/10 text-danger`};function Rr(e){return e.outcome===`failed`?`error`:(e.outcome,e.accepted?`ok`:`warn`)}function zr(e,t){let n=t instanceof Error?t.message:String(t);return`${e(`serverManagement.outcomeDropped`,`The connection dropped and the result could not be confirmed. The node may be restarting — re-check the version above.`)} — ${n}`}function Br({node:e}){let{t}=H(),n=c(),r=R(),[s,l]=i(!1),[d,f]=i(null),p=e.isHub?void 0:{nodeId:e.id},m=Ce(p,{refetchInterval:1e4,enabled:e.isOnline,retry:1}),h=m.data??null,g=a(()=>{n.invalidateQueries({queryKey:Pr})},[n]),_=ve({onSettled:g}),v=ge({onSettled:g}),y=Ye({onSettled:g}),b=a(async()=>{if(h?.latestVersion==null){f({tone:`warn`,text:t(`serverManagement.outcomeNoTarget`,`No target version is known for this node — run "Check for update" first.`)});return}if(await r({title:t(`serverManagement.confirmUpdateTitle`,`Update node root package`),message:t(`serverManagement.confirmUpdateBody`,`Install {{pkg}}@{{version}} on "{{node}}" and restart to apply.`,{pkg:h.packageName,version:h.latestVersion,node:e.name}),confirmLabel:t(`serverManagement.confirmUpdateAction`,`Update & restart`)})){f(null);try{let e=await v.mutateAsync({version:h.latestVersion,...p});f({tone:Rr(e),text:e.message}),e.restarting&&l(!0)}catch(e){f({tone:`warn`,text:zr(t,e)})}}},[v,r,e.name,p,h,t]),S=a(async()=>{if(await r({title:t(`serverManagement.confirmRestartTitle`,`Restart node`),message:t(`serverManagement.confirmRestartBody`,`Restart "{{node}}"? In-flight requests to this node are dropped.`,{node:e.name}),confirmLabel:t(`serverManagement.confirmRestartAction`,`Restart`),variant:`warning`})){f(null);try{let e=await y.mutateAsync(p);f({tone:Rr(e),text:e.message}),e.restarting&&l(!0)}catch(e){f({tone:`warn`,text:zr(t,e)})}}},[r,e.name,y,p,t]),w=()=>{switch(h?.bootMode){case`data-root`:return{label:t(`serverManagement.bootDataRoot`,`runtime-updatable`),tone:`ok`};case`workspace`:return{label:t(`serverManagement.bootWorkspace`,`dev workspace`),tone:`info`};default:return{label:t(`serverManagement.bootBaked`,`baked image seed`),tone:`neutral`}}},E=()=>{if(h==null)return null;switch(h.updateState){case`checking`:return{label:t(`serverManagement.stateChecking`,`checking…`),tone:`info`};case`staging`:return{label:t(`serverManagement.stateStaging`,`updating…`),tone:`info`};case`pending-restart`:return{label:t(`serverManagement.statePending`,`restart pending`),tone:`warn`};default:return h.restartRequired===!0?{label:t(`serverManagement.stateRestartRequired`,`restart required`),tone:`warn`}:h.updateAvailable?{label:t(`serverManagement.stateUpdateAvailable`,`update available`),tone:`warn`}:{label:t(`serverManagement.stateUpToDate`,`up to date`),tone:`ok`}}},D=h?.bootMode===`workspace`,O=e.isOnline&&h!=null&&!D&&h.updateAvailable&&h.updateState===`idle`&&!v.isPending,k=e.isOnline&&h!=null&&h.updateState===`idle`&&!y.isPending,A=e.isOnline?E():null;return o(`div`,{className:`space-y-4 py-2`,children:[o(`div`,{className:`flex items-center justify-between gap-3`,children:[o(`div`,{className:`flex items-center gap-2 min-w-0`,children:[u(`span`,{className:`font-mono text-xs text-foreground-subtle truncate`,children:h?.packageName??e.rootPackage?.name??`@camstack/server`}),e.isOnline&&h!=null&&u(Fr,{...w()})]}),A!=null&&u(Fr,{...A})]}),!e.isOnline&&u($,{label:t(`serverManagement.lastReportedVersion`,`Last reported version`),value:e.rootPackage?.version??null}),e.isOnline&&m.isLoading&&o(`div`,{className:`flex items-center gap-2 text-sm text-foreground-subtle`,children:[u(T,{className:`h-4 w-4 animate-spin`}),t(`common.loading`,`Loading…`)]}),e.isOnline&&m.isError&&o(`div`,{className:`space-y-1.5`,children:[u(`p`,{className:`text-sm text-danger`,children:t(`serverManagement.loadError`,`Could not load the node root-package status.`)}),e.rootPackage!=null&&u($,{label:t(`serverManagement.lastReportedVersion`,`Last reported version`),value:e.rootPackage.version})]}),e.isOnline&&h!=null&&o(`div`,{className:`space-y-1.5`,children:[u(Ir,{runningVersion:h.runningVersion,latestVersion:h.latestVersion,seedVersion:h.seedVersion,nodeRuntimeVersion:h.nodeRuntimeVersion,labelRunning:t(`serverManagement.runningVersionShort`,`Running`),labelLatest:t(`serverManagement.latestVersionShort`,`Latest`),labelSeed:t(`serverManagement.imageSeedShort`,`Seed`),labelRuntime:t(`serverManagement.nodeRuntimeVersionShort`,`Node.js`)}),h.pendingVersion!=null&&u($,{label:t(`serverManagement.pendingVersion`,`Staged (applies on restart)`),value:h.pendingVersion}),h.installedVersion!=null&&h.installedVersion!==h.runningVersion&&u($,{label:t(`serverManagement.installedVersion`,`Installed on disk (runs after restart)`),value:h.installedVersion})]}),e.isOnline&&h?.imageContract?.state===`behind-series`&&o(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs leading-relaxed text-danger`,children:[u(`p`,{className:`mb-0.5 font-semibold`,children:t(`serverManagement.imageContractDiverged`,`Container image diverges from the deployment contract`)}),u(`p`,{children:h.imageContract.message})]}),e.isOnline&&D&&u(`p`,{className:`text-xs text-foreground-subtle`,children:t(`serverManagement.workspaceNote`,`Development workspace detected — runtime updates are disabled (the dev loop resolves code from the workspace).`)}),d!=null&&u(`p`,{role:`status`,className:`rounded border px-2 py-1.5 text-xs leading-relaxed ${Lr[d.tone]}`,children:d.text}),s&&o(`div`,{className:`flex items-center gap-2 text-sm text-warning`,children:[u(T,{className:`h-4 w-4 animate-spin`}),t(`serverManagement.nodeRestarting`,`The node is restarting to apply the change…`)]}),e.isOnline&&o(`div`,{className:`flex flex-wrap items-center gap-2 pt-1`,children:[o(`button`,{type:`button`,className:`inline-flex items-center gap-1.5 rounded border border-border px-2.5 py-1.5 text-xs font-medium text-foreground hover:bg-surface-muted disabled:opacity-50`,disabled:_.isPending||h?.updateState===`staging`,onClick:()=>_.mutate(p),children:[_.isPending?u(T,{className:`h-3.5 w-3.5 animate-spin`}):u(F,{className:`h-3.5 w-3.5`}),t(`serverManagement.checkForUpdate`,`Check for update`)]}),O&&o(`button`,{type:`button`,className:`inline-flex items-center gap-1.5 rounded bg-primary px-2.5 py-1.5 text-xs font-medium text-primary-foreground hover:opacity-90 disabled:opacity-50`,onClick:()=>void b(),children:[v.isPending?u(T,{className:`h-3.5 w-3.5 animate-spin`}):u(x,{className:`h-3.5 w-3.5`}),t(`serverManagement.updateTo`,`Update to {{version}}`,{version:h?.latestVersion??``})]}),o(`button`,{type:`button`,className:`inline-flex items-center gap-1.5 rounded border border-border px-2.5 py-1.5 text-xs font-medium text-foreground hover:bg-surface-muted disabled:opacity-50`,disabled:!k,onClick:()=>void S(),children:[y.isPending?u(T,{className:`h-3.5 w-3.5 animate-spin`}):u(C,{className:`h-3.5 w-3.5`}),t(`serverManagement.restart`,`Restart`)]})]}),e.isOnline&&h?.lastCheckedAtMs!=null&&o(`p`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[u(ne,{className:`h-3 w-3`}),t(`serverManagement.lastChecked`,`Last checked: {{when}}`,{when:new Date(h.lastCheckedAtMs).toLocaleString()})]})]})}e();function Vr(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=Reflect.get(e,`reachableHost`);return typeof t==`string`&&t.length>0?t:null}function Hr({node:e}){let{t}=H(),r=ee(),l=c(),d=R(),[m,h]=i(!1),[g,_]=i(`info`),[v,b]=i(!1),[x,S]=i(null),C=e.processes??[],w=e.addons.map(e=>e.id),T=Oe(void 0),E=n(()=>{let t=T.data?.find(t=>t.nodeId===e.id);return Vr(t?.settings)},[T.data,e.id]),[D,O]=i(!1),[k,A]=i(null),[j,M]=i(null),N=a(async()=>{if(D||e.isHub)return;let t=Ft(e.localIps??[],E);if(t===null){A(`No LAN IPv4 on this node — open its :4444 URL by hand.`),M(null);return}let n=Rt();O(!0),A(null),M(null);try{let i=jt(await r.trpcClient.addons.custom.mutate({addonId:`system-config`,action:`mintAgentUiUnlockTicket`,input:{nodeId:e.id,dashboardBaseUrl:It(t)}})),a=i===null?null:i.dashboardUrl??Lt(t,i.ticket);if(a===null){n?.close(),A(`Hub did not return an unlock ticket.`);return}zt(n,a)||(M(a),A(`Browser blocked the new tab — click the link below (or allow popups for this site).`))}catch(e){n?.close(),A(e instanceof Error?e.message:String(e))}finally{O(!1)}},[e.id,e.isHub,e.localIps,D,E,r.trpcClient]),P=async()=>{if(!v){b(!0),S(null);try{await r.trpcClient.pipelineOrchestrator.removeAgentSettings.mutate({agentNodeId:e.id}).catch(()=>void 0);let t=await r.trpcClient.clusterNodes.forgetNode.mutate({nodeId:e.id});S({tone:t.stillListed?`warn`:`ok`,text:t.message}),t.stillListed||l.invalidateQueries({queryKey:[[`nodes`,`topology`]]})}catch(e){S({tone:`warn`,text:t(`cluster.nodeCard.forgetFailed`,{error:e instanceof Error?e.message:String(e)})})}finally{b(!1)}}},te=async()=>{if(!m&&await d({title:t(`cluster.nodeCard.unpair`,`Unpair {{name}}`,{name:e.name}),message:t(`cluster.nodeCard.unpairItDisconnectsAndMust`,`Unpair {{name}}? It disconnects and must be paired again.`,{name:e.name}),confirmLabel:t(`cluster.nodeCard.unpair2`,`Unpair`),variant:`danger`})){h(!0),S(null);try{let t=await r.trpcClient.agentPairing.unpairAgent.mutate({nodeId:e.id});S({tone:t.agentNotified?`ok`:`warn`,text:`${t.nodeId}: ${t.next}${t.agentNotified?``:` The agent could not be told; forget the hub on its own page.`}`}),l.invalidateQueries({queryKey:[[`nodes`,`topology`]]})}catch(e){S({tone:`warn`,text:t(`cluster.nodeCard.unpairFailed`,{error:e instanceof Error?e.message:String(e)})})}finally{h(!1)}}},F=e.isHub?null:o(L,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>void te(),disabled:m,title:t(`cluster.nodeCard.unpairThisNodeRevokesIts`,`Unpair this node — revokes its certificates; it must be paired again to rejoin`),children:[u(ie,{className:`h-3 w-3`,"aria-hidden":!0}),m?t(`cluster.nodeCard.unpairing`,`Unpairing…`):t(`cluster.nodeCard.unpair2`,`Unpair`)]});return e.isOnline?o(`div`,{className:`border border-border rounded-xl`,children:[o(`div`,{className:`flex min-w-0 flex-wrap items-center gap-x-3 gap-y-2 px-4 py-3 bg-muted/30 border-b border-border rounded-t-xl`,children:[o(`div`,{className:`flex min-w-0 flex-1 basis-full items-center gap-x-2 gap-y-1 sm:basis-auto sm:flex-initial`,children:[u(`div`,{className:`w-2.5 h-2.5 rounded-full bg-success shrink-0`}),u(Bt,{node:e}),o(`span`,{className:`text-xs text-muted-foreground min-w-0 truncate`,children:[e.cpuModel??e.platform,` ·`,` `,e.memoryMB>0?t(`cluster.nodeCard.gb`,`{{value1}}GB`,{value1:Math.round(e.memoryMB/1024)}):``,` `,`· `,e.arch]})]}),e.engines.map(e=>u(`span`,{className:`text-[9px] px-1.5 py-0.5 rounded-full bg-primary/10 text-primary font-medium shrink-0`,children:e},e)),o(`div`,{className:`flex min-w-0 flex-wrap items-center justify-end gap-x-3 gap-y-1 text-xs text-muted-foreground w-full sm:ml-auto sm:w-auto`,children:[!e.isHub&&o(`button`,{type:`button`,onClick:()=>void N(),disabled:D,title:t(`cluster.nodeCard.openThisAgentSStatus`,`Open this agent's status dashboard (unlocks with a short-lived hub ticket)`),className:`inline-flex items-center gap-1 rounded border border-border px-2 py-1 text-xs text-foreground hover:bg-surface-hover disabled:opacity-50`,children:[u(y,{className:`h-3 w-3`}),D?t(`cluster.nodeCard.opening`,`Opening…`):t(`cluster.nodeCard.openDashboard`,`Open dashboard`)]}),F,o(`span`,{className:`flex items-center gap-1`,children:[u(p,{className:`h-3 w-3`}),` `,e.cpuPercent,`%`]}),o(`span`,{className:`flex items-center gap-1`,children:[u(re,{className:`h-3 w-3`}),` `,e.memoryPercent,`%`]})]})]}),x!=null&&u(`p`,{role:`status`,className:`px-4 pt-2 text-xs ${x.tone===`ok`?`text-success`:`text-warning`}`,children:x.text}),(k!==null||j!==null)&&o(`p`,{role:`status`,className:`px-4 pt-2 text-xs text-warning`,children:[k,j!==null&&o(s,{children:[` `,u(`a`,{href:j,target:`_blank`,rel:`noreferrer`,className:`underline text-foreground`,children:t(`cluster.nodeCard.openDashboard`,`Open dashboard`)})]})]}),u(`div`,{className:`sticky top-0 z-20 flex border-b border-border px-4 bg-background overflow-x-auto`,children:[`info`,`forks`,`processes`,`load`,`settings`,`capabilities`].map(e=>u(`button`,{onClick:()=>_(e),className:`shrink-0 whitespace-nowrap px-3 py-2 text-xs font-medium border-b-2 transition-colors ${g===e?`border-primary text-primary`:`border-transparent text-muted-foreground hover:text-foreground`}`,children:e===`info`?t(`cluster.nodeCard.general`,`General`):e===`forks`?t(`cluster.nodeCard.forks`,`Forks ({{length}})`,{length:C.length}):e===`processes`?t(`cluster.nodeCard.processes`,`Processes`):e===`load`?t(`cluster.nodeCard.load`,`Load`):e===`settings`?t(`cluster.nodeCard.settings`,`Settings`):t(`cluster.nodeCard.capabilities`,`Capabilities`)},e))}),o(`div`,{className:`px-4 py-2`,children:[g===`info`&&o(`div`,{className:`space-y-3`,children:[u(kr,{nodeId:e.id,name:e.name,hostname:e.hostname,platform:e.platform,arch:e.arch,cpuModel:e.cpuModel,cpuCores:e.cpuCores,memoryMB:e.memoryMB,engines:e.engines,isHub:e.isHub,uptime:e.uptime,localIps:e.localIps,rootPackage:e.rootPackage}),u(Nr,{nodeId:e.id,detectedHosts:e.localIps??[]}),u(`div`,{className:`border-t border-border pt-1`,children:u(Br,{node:{id:e.id,name:e.name,isHub:e.isHub,isOnline:e.isOnline,rootPackage:e.rootPackage??null}})})]}),g===`forks`&&u(Gt,{nodeId:e.id,processes:C}),g===`processes`&&u(Yt,{nodeId:e.id}),g===`load`&&u(Sr,{nodeId:e.id,isHub:e.isHub}),g===`settings`&&u(Er,{nodeId:e.id,addonIds:w}),g===`capabilities`&&u(Dr,{nodeId:e.id,addons:e.addons})]})]}):o(`div`,{className:`border border-border rounded-xl overflow-hidden opacity-60`,children:[o(`div`,{className:`flex min-w-0 flex-wrap items-center gap-x-3 gap-y-2 px-4 py-3 bg-muted/30`,children:[u(`div`,{className:`w-2.5 h-2.5 rounded-full bg-destructive shrink-0`}),u(Bt,{node:e}),o(`span`,{className:`text-xs text-muted-foreground min-w-0 truncate`,children:[e.cpuModel??e.platform,` ·`,` `,e.memoryMB>0?t(`cluster.nodeCard.gb`,`{{value1}}GB`,{value1:Math.round(e.memoryMB/1024)}):``,` `,`· `,e.arch]}),e.engines.map(e=>u(`span`,{className:`text-[9px] px-1.5 py-0.5 rounded-full bg-primary/10 text-primary font-medium`,children:e},e)),e.rootPackage&&o(`span`,{className:`text-[10px] font-mono px-1.5 py-0.5 rounded bg-muted text-muted-foreground`,children:[e.rootPackage.name,`@`,e.rootPackage.version]}),u(`span`,{className:`ml-auto text-xs px-2 py-0.5 rounded-full bg-destructive/10 text-destructive`,children:t(`common.offline`)})]}),o(`div`,{className:`flex items-center justify-between gap-3 px-4 py-3`,children:[o(`span`,{className:`text-xs text-muted-foreground`,children:[e.lastSeen?u(`span`,{className:`mr-1`,children:t(`cluster.nodeCard.lastSeen`,{when:new Date(e.lastSeen).toLocaleString()})}):null,t(`cluster.nodeCard.addonsAssigned`,{count:e.addons.length})]}),o(`div`,{className:`flex shrink-0 items-center gap-2`,children:[F,o(`button`,{type:`button`,onClick:()=>void P(),disabled:v,title:t(`cluster.nodeCard.forgetThisNodeRemovesIts`,`Forget this node — removes its saved history and pipeline assignments`),className:`flex items-center gap-1 text-xs px-2 py-1 rounded-md border border-border text-muted-foreground hover:text-destructive hover:border-destructive/50 disabled:opacity-50 transition-colors`,children:[u(f,{className:`h-3 w-3`}),v?t(`cluster.nodeCard.forgetting`,`Forgetting…`):t(`cluster.nodeCard.forgetNode`,`Forget node`)]})]})]}),x!=null&&u(`p`,{role:`status`,className:`px-4 pb-3 text-xs leading-relaxed ${x.tone===`ok`?`text-success`:`text-warning`}`,children:x.text})]})}var Ur=3,Wr=7e3;function Gr(e){return[...e].sort((e,t)=>e.isHub===t.isHub?0:e.isHub?1:-1)}function Kr(e){return e.isHub?{}:{nodeId:e.id}}function qr(e){return e.updateState===`staging`||e.updateState===`pending-restart`||e.pendingVersion!==null?!0:!e.updateAvailable}async function Jr(e,t){let n=Kr(e),r=V.t(`helpers.clusterUpdateAll.noAnswer`);for(let i=1;i<=Ur;i+=1)try{let r=await t.readStatus(n);return qr(r)?{nodeId:e.id,nodeName:e.name,outcome:`applied`,detail:V.t(`helpers.clusterUpdateAll.landed`,{state:r.updateState,version:r.runningVersion??V.t(`helpers.clusterUpdateAll.unknown`)})}:{nodeId:e.id,nodeName:e.name,outcome:`failed`,detail:V.t(`helpers.clusterUpdateAll.unchanged`,{version:r.runningVersion??V.t(`helpers.clusterUpdateAll.unknown`)})}}catch(e){r=e instanceof Error?e.message:String(e),i<Ur&&await t.wait(Wr)}return{nodeId:e.id,nodeName:e.name,outcome:`unconfirmed`,detail:V.t(`helpers.clusterUpdateAll.unconfirmed`,{attempts:Ur,error:r})}}function Yr(e){return e.accepted?`applied`:e.outcome===`failed`?`failed`:`refused`}async function Xr(e,t){let n=[];for(let r of Gr(e))try{let e=await t.apply(Kr(r));n.push({nodeId:r.id,nodeName:r.name,outcome:Yr(e),detail:e.message})}catch{n.push(await Jr(r,t))}return n}e();function Zr(){let{nodes:e,isLoading:t}=ze(),r=n(()=>e??[],[e]);return{nodes:r,isLoading:t&&r.length===0}}var Qr={applied:`border-success/40 bg-success/10 text-success`,refused:`border-warning/40 bg-warning/10 text-warning`,failed:`border-danger/40 bg-danger/10 text-danger`,unconfirmed:`border-warning/40 bg-warning/10 text-warning`};function $r(){let{t:e}=H(),r=R(),{nodes:c,isLoading:l}=Zr(),[d,f]=Ze(),{selection:p,selectNode:m}=at(c),h=p.node,g=n(()=>c.filter(e=>e.isOnline),[c]),_=g.length,y=c.filter(e=>!e.isOnline).length,b=ge(),S=ee(),[C,w]=i(!1),[E,D]=i([]),O=d.get(`unlockNode`),k=d.get(`returnTo`),[A,j]=i(null);t(()=>{if(O===null||k===null)return;let e=!1;return(async()=>{try{let t=await S.trpcClient.addons.custom.mutate({addonId:`system-config`,action:`mintAgentUiUnlockTicket`,input:{nodeId:O,dashboardBaseUrl:k}});if(e)return;let n=jt(t),r=n===null?null:n.dashboardUrl??(()=>{let e=new URL(k);return e.searchParams.set(`ticket`,n.ticket),e.toString()})();if(r===null){j(`Could not mint an unlock ticket.`);return}let i=new URLSearchParams(d);i.delete(`unlockNode`),i.delete(`returnTo`),f(i,{replace:!0}),window.location.assign(r)}catch(t){e||j(t instanceof Error?t.message:String(t))}})(),()=>{e=!0}},[O,k,d,f,S.trpcClient]);let M=a(async()=>{let t=g.map(e=>({id:e.id,name:e.name,isHub:e.isHub}));if(await r({title:e(`serverManagement.confirmUpdateAllTitle`,`Update all nodes`),message:e(`serverManagement.confirmUpdateAllBody`,`Update and restart every online node, agents first, hub last. Up-to-date nodes are skipped; this page reconnects when the hub comes back.`),confirmLabel:e(`serverManagement.confirmUpdateAllAction`,`Update all & restart`),variant:`warning`})){w(!0),D([]);try{D(await Xr(t,{apply:e=>b.mutateAsync(e),readStatus:e=>S.trpcClient.serverManagement.getServerPackageStatus.query(e),wait:e=>new Promise(t=>setTimeout(t,e))}))}finally{w(!1)}}},[b,r,g,S,e]);return o(Qe,{icon:v,title:e(`nav.nodes`,`Nodes`),subtitle:e(`cluster.subtitle`,`One node at a time — topology and packages. Agents join by pairing (certificate, no shared secret).`),actions:o(s,{children:[_>0&&u(`span`,{className:`rounded-full bg-success/10 px-2 py-0.5 text-xs text-success`,children:e(`common.onlineCount`,{count:_})}),y>0&&u(`span`,{className:`rounded-full bg-destructive/10 px-2 py-0.5 text-xs text-destructive`,children:e(`common.offlineCount`,{count:y})}),_>1&&o(L,{type:`button`,size:`sm`,disabled:C,title:e(`serverManagement.updateAllHint`,`Sequenced agents-first, hub-last — up-to-date nodes are skipped.`),onClick:()=>void M(),children:[C?u(T,{className:`h-3.5 w-3.5 animate-spin`}):u(x,{className:`h-3.5 w-3.5`}),e(`serverManagement.updateAll`,`Update all nodes`)]})]}),children:[E.length>0&&u(`ul`,{"aria-label":`update-all-report`,className:`flex flex-col gap-1 text-xs`,children:E.map(e=>o(`li`,{"data-outcome":e.outcome,className:`rounded border px-2 py-1 ${Qr[e.outcome]}`,children:[u(`span`,{className:`font-medium`,children:e.nodeName}),u(`span`,{className:`mx-1 uppercase tracking-wide`,children:e.outcome}),u(`span`,{className:`opacity-80`,children:e.detail})]},e.nodeId))}),A!==null&&o(`p`,{role:`alert`,className:`rounded border border-warning/40 bg-warning/10 px-3 py-2 text-xs text-warning`,children:[e(`system.cluster.unlockFromAgentFailed`,`Unlock from agent failed:`),` `,A]}),u(kt,{onOpenNode:m}),l?u(`div`,{className:`flex items-center justify-center py-12 text-muted-foreground`,children:e(`system.cluster.loadingClusterTopology`,`Loading cluster topology...`)}):h===null?u(`div`,{className:`rounded-md border border-dashed border-border px-3 py-6 text-center text-xs text-foreground-subtle`,children:e(`cluster.noNodes`,`No nodes in this cluster yet.`)}):o(`div`,{className:`flex flex-col gap-3`,children:[u(it,{staleNodeId:p.staleNodeId,shownNodeName:h.name}),u(De,{selectedNodeId:h.id,onSelect:m,allowOffline:!0,alwaysShow:!0}),u(Hr,{node:h})]})]})}export{$r as ClusterPage};
|