tmex-cli 0.6.7 → 0.7.0

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tmex-cli",
3
- "version": "0.6.7",
3
+ "version": "0.7.0",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "tmex": "./bin/tmex.js",
@@ -0,0 +1,26 @@
1
+ var $t=Object.defineProperty;var jt=(n,e,t)=>e in n?$t(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var m=(n,e,t)=>jt(n,typeof e!="symbol"?e+"":e,t);import{c as Ve,y as Ke,v as h,X as qt,w as d,aa as Z,ax as At,ay as Ot,az as dt,t as _e,aA as Xt,aB as it,a8 as Qt,ao as kt,aC as ot,ap as ae,aD as Jt,ab as Ht,ag as It,aE as Se,aF as Zt,L as je,ae as en,G as he,T as tn,aG as nn,aH as sn,aI as rn,aJ as on,a0 as ln,a1 as an,a2 as cn,a3 as dn,a4 as un,a5 as hn,a6 as fn,a7 as mn}from"./index-BhWcb9L_.js";import{S as ut}from"./send-XA81w52-.js";import{R as pn}from"./refresh-cw-DfNqpalN.js";import{K as wn}from"./keyboard-B6P8isCn.js";/**
2
+ * @license lucide-react v0.564.0 - ISC
3
+ *
4
+ * This source code is licensed under the ISC license.
5
+ * See the LICENSE file in the root directory of this source tree.
6
+ */const yn=[["path",{d:"M12 17V3",key:"1cwfxf"}],["path",{d:"m6 11 6 6 6-6",key:"12ii2o"}],["path",{d:"M19 21H5",key:"150jfl"}]],gn=Ve("arrow-down-to-line",yn);/**
7
+ * @license lucide-react v0.564.0 - ISC
8
+ *
9
+ * This source code is licensed under the ISC license.
10
+ * See the LICENSE file in the root directory of this source tree.
11
+ */const Sn=[["path",{d:"M11 14h10",key:"1w8e9d"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v1.344",key:"1e62lh"}],["path",{d:"m17 18 4-4-4-4",key:"z2g111"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 1.793-1.113",key:"bjbb7m"}],["rect",{x:"8",y:"2",width:"8",height:"4",rx:"1",key:"ublpy"}]],_n=Ve("clipboard-paste",Sn);/**
12
+ * @license lucide-react v0.564.0 - ISC
13
+ *
14
+ * This source code is licensed under the ISC license.
15
+ * See the LICENSE file in the root directory of this source tree.
16
+ */const xn=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],Tn=Ve("copy",xn);/**
17
+ * @license lucide-react v0.564.0 - ISC
18
+ *
19
+ * This source code is licensed under the ISC license.
20
+ * See the LICENSE file in the root directory of this source tree.
21
+ */const bn=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]],En=Ve("smartphone",bn);function Rn(n){return`rgb(${n.r} ${n.g} ${n.b})`}const Cn=new Map([[9622,4],[9623,8],[9624,1],[9625,13],[9626,9],[9627,7],[9628,11],[9629,2],[9630,6],[9631,14]]),vn=new Map([[9617,.25],[9618,.5],[9619,.75]]);function Mn(n){return n>=9600&&n<=9631}function qe(n){const e=n.getContext("2d");if(!e)throw new Error("2d canvas context unavailable");return e}class Dn{constructor(e){m(this,"kind","canvas");m(this,"mainCanvas");m(this,"selectionCanvas");m(this,"cursorCanvas");m(this,"mainContext");m(this,"selectionContext");m(this,"cursorContext");m(this,"theme");m(this,"fontFamily");m(this,"fontSize");m(this,"cellDimensions",{width:9,height:17});m(this,"deviceCellWidth",9);m(this,"deviceCellHeight",17);m(this,"dpr",1);m(this,"cols",0);m(this,"rows",0);m(this,"lastCursor",null);m(this,"frameCount",0);m(this,"lastDrawnRows",[]);m(this,"colorCache",new Map);m(this,"fontCache",new Map);m(this,"cursorBlinkVisible",!0);m(this,"cursorBlinkTimer",null);this.theme=e.theme,this.fontFamily=e.fontFamily,this.fontSize=e.fontSize,e.screenElement.style.position="relative",e.screenElement.style.overflow="hidden",this.mainCanvas=document.createElement("canvas"),this.selectionCanvas=document.createElement("canvas"),this.cursorCanvas=document.createElement("canvas");for(const[t,s]of[[this.mainCanvas,"main"],[this.selectionCanvas,"selection"],[this.cursorCanvas,"cursor"]])t.dataset.layer=s,t.style.position="absolute",t.style.inset="0",t.style.width="100%",t.style.height="100%",t.style.pointerEvents="none",e.screenElement.appendChild(t);this.mainContext=qe(this.mainCanvas),this.selectionContext=qe(this.selectionCanvas),this.cursorContext=qe(this.cursorCanvas)}setTheme(e){this.theme=e,this.colorCache.clear()}render(e){if(this.frameCount+=1,this.lastDrawnRows=[],this.cellDimensions=e.cellDimensions,this.resize(e.meta.cols,e.meta.rows),this.drawSelection(e.selectionRects??[],e.selectionColor??this.theme.selectionBackground),e.meta.dirty==="clean"){this.drawCursor(e.meta);return}const s=e.meta.dirty==="full"?e.rows:e.rows.filter(i=>i.dirty);for(const i of s)this.drawRow(i,e.meta.colors),this.lastDrawnRows.push(i.y);this.drawCursor(e.meta)}getDebugState(){return{kind:this.kind,frameCount:this.frameCount,lastDrawnRows:[...this.lastDrawnRows]}}dispose(){this.mainCanvas.remove(),this.selectionCanvas.remove(),this.cursorCanvas.remove(),this.colorCache.clear(),this.fontCache.clear(),this.lastCursor=null,this.stopCursorBlink()}startCursorBlink(){this.cursorBlinkTimer||(this.cursorBlinkTimer=setInterval(()=>{this.cursorBlinkVisible=!this.cursorBlinkVisible,this.cursorCanvas.style.opacity=this.cursorBlinkVisible?"1":"0"},1e3))}stopCursorBlink(){this.cursorBlinkTimer&&(clearInterval(this.cursorBlinkTimer),this.cursorBlinkTimer=null),this.cursorBlinkVisible=!0,this.cursorCanvas.style.opacity="1"}resize(e,t){const s=Math.max(1,e),i=Math.max(1,t),r=Math.max(1,globalThis.devicePixelRatio??1),o=Math.max(1,Math.round(this.cellDimensions.width*r)),l=Math.max(1,Math.round(this.cellDimensions.height*r));if(this.cols===s&&this.rows===i&&this.dpr===r&&this.deviceCellWidth===o&&this.deviceCellHeight===l)return;this.cols=s,this.rows=i,this.dpr=r,this.deviceCellWidth=o,this.deviceCellHeight=l;const u=s*o,a=i*l;for(const f of[this.mainCanvas,this.selectionCanvas,this.cursorCanvas])f.width=u,f.height=a,f.style.width=`${u/r}px`,f.style.height=`${a/r}px`;for(const f of[this.mainContext,this.selectionContext,this.cursorContext])f.setTransform(1,0,0,1,0,0),f.textBaseline="top",f.imageSmoothingEnabled=!1}drawSelection(e,t){if(this.selectionContext.clearRect(0,0,this.selectionCanvas.width,this.selectionCanvas.height),e.length!==0){this.selectionContext.fillStyle=t;for(const s of e)this.selectionContext.fillRect(s.x*this.deviceCellWidth,s.row*this.deviceCellHeight,s.width*this.deviceCellWidth,this.deviceCellHeight)}}drawRow(e,t){const s=e.y*this.deviceCellHeight,i=this.cols*this.deviceCellWidth,r=this.toCss(t.background),o=Math.max(1,Math.round(this.dpr));this.mainContext.clearRect(0,s,i,this.deviceCellHeight),this.mainContext.fillStyle=r,this.mainContext.fillRect(0,s,i,this.deviceCellHeight);for(const l of e.cells){if(l.widthKind==="spacer-tail"||l.widthKind==="spacer-head")continue;const u=l.x*this.deviceCellWidth,a=l.style.inverse?l.fgColor??t.foreground:l.bgColor??t.background,f=l.style.inverse?l.bgColor??t.background:l.fgColor??t.foreground,_=l.widthKind==="wide"?this.deviceCellWidth*2:this.deviceCellWidth;if((a.r!==t.background.r||a.g!==t.background.g||a.b!==t.background.b)&&(this.mainContext.fillStyle=this.toCss(a),this.mainContext.fillRect(u,s,_,this.deviceCellHeight)),!l.text||l.style.invisible)continue;this.mainContext.fillStyle=this.toCss(f);const C=l.codepoints.length===1&&Mn(l.codepoints[0])?l.codepoints[0]:null;C!==null?this.drawBlockElement(C,u,s,_,this.deviceCellHeight):(this.mainContext.font=this.resolveFont(l.style),this.mainContext.fillText(l.text,u,s)),l.style.underline>0&&this.mainContext.fillRect(u,s+this.deviceCellHeight-2*o,Math.max(_-o,o),o),l.style.strikethrough&&this.mainContext.fillRect(u,Math.round(s+this.deviceCellHeight*.55),Math.max(_-o,o),o),l.style.overline&&this.mainContext.fillRect(u,s+o,Math.max(_-o,o),o)}}drawBlockElement(e,t,s,i,r){const o=this.mainContext,l=b=>Math.round(i*b/8),u=b=>Math.round(r*b/8),a=(b,E,z,w)=>{o.fillRect(t+b,s+E,z-b,w-E)};if(e===9600){a(0,0,i,u(4));return}if(e>=9601&&e<=9608){a(0,u(8-(e-9600)),i,r);return}if(e>=9609&&e<=9615){a(0,0,l(9616-e),r);return}if(e===9616){a(l(4),0,i,r);return}const f=vn.get(e);if(f!==void 0){const b=o.globalAlpha;o.globalAlpha=b*f,a(0,0,i,r),o.globalAlpha=b;return}if(e===9620){a(0,0,i,u(1));return}if(e===9621){a(l(7),0,i,r);return}const _=Cn.get(e)??0,C=l(4),I=u(4);_&1&&a(0,0,C,I),_&2&&a(C,0,i,I),_&4&&a(0,I,C,r),_&8&&a(C,I,i,r)}drawCursor(e){const t=e.colors,s=e.cursor,i=this.lastCursor;if(this.cursorContext.clearRect(0,0,this.cursorCanvas.width,this.cursorCanvas.height),!s.visible||s.x===null||s.y===null){this.lastCursor=null,this.stopCursorBlink();return}const r=s.x*this.deviceCellWidth,o=s.y*this.deviceCellHeight,l=s.wideTail?this.deviceCellWidth*2:this.deviceCellWidth,u=Math.max(1,Math.round(this.dpr)),a=t.cursor??t.foreground,f=this.toCss(a);this.cursorContext.fillStyle=f,this.cursorContext.strokeStyle=f,this.cursorContext.globalAlpha=.7,this.cursorContext.fillRect(r,o+this.deviceCellHeight-2*u,Math.max(l-u,u),2*u),this.cursorContext.globalAlpha=1,this.startCursorBlink(),this.lastCursor={x:s.x,y:s.y,style:s.style},i&&(i.x!==this.lastCursor.x||i.y!==this.lastCursor.y||i.style!==this.lastCursor.style)&&this.lastDrawnRows.push(i.y)}resolveFont(e){const t=this.fontSize*this.dpr,s=[e.italic?"italic":"normal",e.bold?"700":"400",`${t}px`,this.fontFamily].join("|"),i=this.fontCache.get(s);if(i)return i;const r=`${e.italic?"italic ":""}${e.bold?"700 ":""}${t}px ${this.fontFamily}`;return this.fontCache.set(s,r),r}toCss(e){const t=`${e.r},${e.g},${e.b}`,s=this.colorCache.get(t);if(s)return s;const i=Rn(e);return this.colorCache.set(t,i),i}}const An=0,On={Backquote:1,Backslash:2,BracketLeft:3,BracketRight:4,Comma:5,Digit0:6,Digit1:7,Digit2:8,Digit3:9,Digit4:10,Digit5:11,Digit6:12,Digit7:13,Digit8:14,Digit9:15,Equal:16,IntlBackslash:17,IntlRo:18,IntlYen:19,KeyA:20,KeyB:21,KeyC:22,KeyD:23,KeyE:24,KeyF:25,KeyG:26,KeyH:27,KeyI:28,KeyJ:29,KeyK:30,KeyL:31,KeyM:32,KeyN:33,KeyO:34,KeyP:35,KeyQ:36,KeyR:37,KeyS:38,KeyT:39,KeyU:40,KeyV:41,KeyW:42,KeyX:43,KeyY:44,KeyZ:45,Minus:46,Period:47,Quote:48,Semicolon:49,Slash:50,AltLeft:51,AltRight:52,Backspace:53,CapsLock:54,ContextMenu:55,ControlLeft:56,ControlRight:57,Enter:58,MetaLeft:59,MetaRight:60,ShiftLeft:61,ShiftRight:62,Space:63,Tab:64,Convert:65,KanaMode:66,NonConvert:67,Delete:68,End:69,Help:70,Home:71,Insert:72,PageDown:73,PageUp:74,ArrowDown:75,ArrowLeft:76,ArrowRight:77,ArrowUp:78,NumLock:79,Numpad0:80,Numpad1:81,Numpad2:82,Numpad3:83,Numpad4:84,Numpad5:85,Numpad6:86,Numpad7:87,Numpad8:88,Numpad9:89,NumpadAdd:90,NumpadBackspace:91,NumpadClear:92,NumpadClearEntry:93,NumpadComma:94,NumpadDecimal:95,NumpadDivide:96,NumpadEnter:97,NumpadEqual:98,NumpadMemoryAdd:99,NumpadMemoryClear:100,NumpadMemoryRecall:101,NumpadMemoryStore:102,NumpadMemorySubtract:103,NumpadMultiply:104,NumpadParenLeft:105,NumpadParenRight:106,NumpadSubtract:107,NumpadSeparator:108,NumpadUp:109,NumpadDown:110,NumpadRight:111,NumpadLeft:112,NumpadBegin:113,NumpadHome:114,NumpadEnd:115,NumpadInsert:116,NumpadDelete:117,NumpadPageUp:118,NumpadPageDown:119,Escape:120,F1:121,F2:122,F3:123,F4:124,F5:125,F6:126,F7:127,F8:128,F9:129,F10:130,F11:131,F12:132,F13:133,F14:134,F15:135,F16:136,F17:137,F18:138,F19:139,F20:140,F21:141,F22:142,F23:143,F24:144,F25:145,Fn:146,FnLock:147,PrintScreen:148,ScrollLock:149,Pause:150,BrowserBack:151,BrowserFavorites:152,BrowserForward:153,BrowserHome:154,BrowserRefresh:155,BrowserSearch:156,BrowserStop:157,Eject:158,LaunchApp1:159,LaunchApp2:160,LaunchMail:161,MediaPlayPause:162,MediaSelect:163,MediaStop:164,MediaTrackNext:165,MediaTrackPrevious:166,Power:167,Sleep:168,AudioVolumeDown:169,AudioVolumeMute:170,AudioVolumeUp:171,WakeUp:172,Copy:173,Cut:174,Paste:175},lt={Backquote:"`",Backslash:"\\",BracketLeft:"[",BracketRight:"]",Comma:",",Equal:"=",Minus:"-",Period:".",Quote:"'",Semicolon:";",Slash:"/",Space:" ",IntlBackslash:"\\",IntlYen:"¥",IntlRo:"\\"};for(let n=0;n<=9;n+=1)lt[`Digit${n}`]=String(n);for(let n=0;n<26;n+=1){const e=String.fromCharCode(65+n),t=String.fromCharCode(97+n);lt[`Key${e}`]=t}function ht(n){return On[n]??An}function kn(n){const e=lt[n];return e?e.codePointAt(0)??null:null}const xe=0,Hn=-2,In=1,Nn=2,Pn=3,Bn=10,Ln=11,Fn=12,Gn=13,Un=14,zn=15,Yn=16,Vn=17,Kn=1,Wn=2,$n=1,jn=2,qn=3,Xn=4,Qn=5,Jn=6,Zn=1,es=2,ts=3,ns=4;function at(n){if(n.disposed||n.renderStateHandle===0)throw new Error("render state resources already disposed")}function ss(n){switch(n){case 2:return"full";case 1:return"partial";default:return"clean"}}function rs(n){switch(n){case 0:return"bar";case 2:return"underline";case 3:return"block-hollow";default:return"block"}}function is(n){switch(n){case 1:return"wide";case 2:return"spacer-tail";case 3:return"spacer-head";default:return"narrow"}}function Ee(n,e){return{r:n.view().getUint8(e),g:n.view().getUint8(e+1),b:n.view().getUint8(e+2)}}function ft(n,e){const t=n.bindings.allocStruct("GhosttyColorRgb");try{const s=e(t.ptr);if(s===Hn)return null;if(s!==xe)throw new Error(`ghostty optional color read failed with result ${s}`);return Ee(n.bindings,t.ptr)}finally{t.free()}}function ce(n,e){const t=n.bindings.allocU8();try{const s=e(t);if(typeof s=="number"&&s!==xe)throw new Error(`ghostty bool read failed with result ${s}`);return n.bindings.readU8(t)!==0}finally{n.bindings.freeU8(t)}}function Ie(n,e){const t=n.bindings.allocBytes(2);try{const s=e(t);if(typeof s=="number"&&s!==xe)throw new Error(`ghostty u16 read failed with result ${s}`);return n.bindings.view().getUint16(t,!0)}finally{n.bindings.freeBytes(t,2)}}function os(n,e){const t=n.bindings.allocBytes(4);try{const s=e(t);if(typeof s=="number"&&s!==xe)throw new Error(`ghostty u32 read failed with result ${s}`);return n.bindings.view().getUint32(t,!0)}finally{n.bindings.freeBytes(t,4)}}function nt(n,e){const t=n.bindings.allocBytes(4);try{const s=e(t);if(typeof s=="number"&&s!==xe)throw new Error(`ghostty enum read failed with result ${s}`);return n.bindings.view().getInt32(t,!0)}finally{n.bindings.freeBytes(t,4)}}function mt(n,e){const t=n.bindings.allocBytes(8);try{const s=e(t);if(typeof s=="number"&&s!==xe)throw new Error(`ghostty u64 read failed with result ${s}`);return n.bindings.readU64(t)}finally{n.bindings.freeBytes(t,8)}}function ls(n){const e=n.bindings.allocStruct("GhosttyStyle");try{n.bindings.setField(e.view,"GhosttyStyle","size",n.bindings.typeSize("GhosttyStyle")),n.bindings.getRenderStateRowCellValue(n.rowCellsHandle,jn,e.ptr);const t=s=>n.bindings.field("GhosttyStyle",s).offset;return{bold:e.view.getUint8(t("bold"))!==0,italic:e.view.getUint8(t("italic"))!==0,faint:e.view.getUint8(t("faint"))!==0,blink:e.view.getUint8(t("blink"))!==0,inverse:e.view.getUint8(t("inverse"))!==0,invisible:e.view.getUint8(t("invisible"))!==0,strikethrough:e.view.getUint8(t("strikethrough"))!==0,overline:e.view.getUint8(t("overline"))!==0,underline:e.view.getInt32(t("underline"),!0)}}finally{e.free()}}function as(n){const e=os(n,s=>n.bindings.getRenderStateRowCellValueResult(n.rowCellsHandle,qn,s));if(e===0)return[];const t=n.bindings.allocBytes(e*4);try{n.bindings.getRenderStateRowCellValue(n.rowCellsHandle,Xn,t);const s=[];for(let i=0;i<e;i+=1)s.push(n.bindings.view().getUint32(t+i*4,!0));return s}finally{n.bindings.freeBytes(t,e*4)}}function cs(n){if(n.length===0)return"";try{return String.fromCodePoint(...n)}catch{return""}}function ds(n){let e="";for(const t of n)if(!(t.widthKind==="spacer-tail"||t.widthKind==="spacer-head")){if(t.text){e+=t.text;continue}t.widthKind==="narrow"&&(e+=" ")}return e}function us(n){const e=n.bindings.allocStruct("GhosttyRenderStateColors");try{n.bindings.setField(e.view,"GhosttyRenderStateColors","size",n.bindings.typeSize("GhosttyRenderStateColors")),n.bindings.getRenderStateColors(n.renderStateHandle,e.ptr);const t=n.bindings.field("GhosttyRenderStateColors","palette").offset,s=[];for(let o=0;o<256;o+=1){const l=e.ptr+t+o*3;s.push(Ee(n.bindings,l))}const i=e.view.getUint8(n.bindings.field("GhosttyRenderStateColors","cursor_has_value").offset)!==0,r=ce(n,o=>n.bindings.getRenderStateValueResult(n.renderStateHandle,Un,o));return{cols:Ie(n,o=>n.bindings.getRenderStateValueResult(n.renderStateHandle,In,o)),rows:Ie(n,o=>n.bindings.getRenderStateValueResult(n.renderStateHandle,Nn,o)),dirty:ss(nt(n,o=>n.bindings.getRenderStateValueResult(n.renderStateHandle,Pn,o))),colors:{background:Ee(n.bindings,e.ptr+n.bindings.field("GhosttyRenderStateColors","background").offset),foreground:Ee(n.bindings,e.ptr+n.bindings.field("GhosttyRenderStateColors","foreground").offset),cursor:i?Ee(n.bindings,e.ptr+n.bindings.field("GhosttyRenderStateColors","cursor").offset):null,palette:s},cursor:{style:rs(nt(n,o=>n.bindings.getRenderStateValueResult(n.renderStateHandle,Bn,o))),visible:ce(n,o=>n.bindings.getRenderStateValueResult(n.renderStateHandle,Ln,o)),blinking:ce(n,o=>n.bindings.getRenderStateValueResult(n.renderStateHandle,Fn,o)),passwordInput:ce(n,o=>n.bindings.getRenderStateValueResult(n.renderStateHandle,Gn,o)),x:r?Ie(n,o=>n.bindings.getRenderStateValueResult(n.renderStateHandle,zn,o)):null,y:r?Ie(n,o=>n.bindings.getRenderStateValueResult(n.renderStateHandle,Yn,o)):null,wideTail:r?ce(n,o=>n.bindings.getRenderStateValueResult(n.renderStateHandle,Vn,o)):!1}}}finally{e.free()}}function hs(n,e){const t=mt(n,r=>n.bindings.getRenderStateRowValueResult(n.rowIteratorHandle,Wn,r));n.bindings.bindRenderStateRowCells(n.rowIteratorHandle,n.rowCellsHandle);const s=[];let i=0;for(;n.bindings.nextRenderStateRowCell(n.rowCellsHandle);){const r=mt(n,a=>n.bindings.getRenderStateRowCellValueResult(n.rowCellsHandle,$n,a)),o=as(n),l=is(nt(n,a=>n.bindings.getRawCellValueResult(r,ts,a))),u={x:i,text:cs(o),codepoints:o,widthKind:l,hasText:ce(n,a=>n.bindings.getRawCellValueResult(r,ns,a)),style:ls(n),fgColor:ft(n,a=>n.bindings.getRenderStateRowCellValueResult(n.rowCellsHandle,Jn,a)),bgColor:ft(n,a=>n.bindings.getRenderStateRowCellValueResult(n.rowCellsHandle,Qn,a))};s.push(u),i+=1}return{y:e,dirty:ce(n,r=>n.bindings.getRenderStateRowValueResult(n.rowIteratorHandle,Kn,r)),wrap:ce(n,r=>n.bindings.getRawRowValueResult(t,Zn,r)),wrapContinuation:ce(n,r=>n.bindings.getRawRowValueResult(t,es,r)),text:ds(s),cells:s}}function pt(n){return{bindings:n,renderStateHandle:n.createRenderState(),rowIteratorHandle:n.createRenderStateRowIterator(),rowCellsHandle:n.createRenderStateRowCells(),snapshotVersion:0,disposed:!1,cachedMeta:null}}function wt(n,e){at(n),n.bindings.updateRenderState(n.renderStateHandle,e),n.bindings.bindRenderStateRowIterator(n.renderStateHandle,n.rowIteratorHandle),n.snapshotVersion+=1,n.cachedMeta=null}function st(n){return at(n),n.cachedMeta||(n.cachedMeta=us(n)),n.cachedMeta}function*fs(n){at(n);const e=st(n);n.bindings.bindRenderStateRowIterator(n.renderStateHandle,n.rowIteratorHandle);let t=0;for(;t<e.rows&&n.bindings.nextRenderStateRowIterator(n.rowIteratorHandle);)yield hs(n,t),t+=1}function Xe(n){n.disposed||(n.disposed=!0,n.rowCellsHandle!==0&&(n.bindings.freeRenderStateRowCells(n.rowCellsHandle),n.rowCellsHandle=0),n.rowIteratorHandle!==0&&(n.bindings.freeRenderStateRowIterator(n.rowIteratorHandle),n.rowIteratorHandle=0),n.renderStateHandle!==0&&(n.bindings.freeRenderState(n.renderStateHandle),n.renderStateHandle=0),n.cachedMeta=null)}const ms={colChars:[],contentCols:0,wrappedToNext:!1};function ps(n){for(let e=n.length-1;e>=0;e-=1){const t=n[e];if(t!==null&&t!==""&&t!==" ")return e+1}return 0}function yt(n,e=!1){const t=[];for(const s of n){if(s.widthKind==="spacer-tail"){t.push(null);continue}if(s.widthKind==="spacer-head"){t.push("");continue}t.push(s.text||" ")}return{colChars:t,contentCols:ps(t),wrappedToNext:e}}function ws(n,e){return Math.max(0,Math.min(Math.max(n.colChars.length-1,0),Math.floor(e)))}function ct(n,e){let t=ws(n,e);for(;t>0&&n.colChars[t]===null;)t-=1;return t}function Qe(n,e){let t=e;for(;t>0&&n.colChars[t]===null;)t-=1;return n.colChars[t]||""}function gt(n,e){let t=e;for(;t+1<n.colChars.length&&n.colChars[t+1]===null;)t+=1;return t}function ys(n,e){return n.line<e.line?{start:n,end:e}:n.line>e.line?{start:e,end:n}:n.col<=e.col?{start:n,end:e}:{start:e,end:n}}function gs(n,e,t){if(t.colChars.length===0)return{start:{line:n,col:0},end:{line:n,col:0}};const s=ct(t,e),i=l=>/[\p{L}\p{N}_-]/u.test(l);if(!i(Qe(t,s)))return{start:{line:n,col:s},end:{line:n,col:s}};let r=s,o=s;for(;r>0&&i(Qe(t,r-1));)r-=1;for(;o+1<t.colChars.length&&i(Qe(t,o+1));)o+=1;return{start:{line:n,col:r},end:{line:n,col:o}}}function Nt(n,e){const t=Math.max(e.contentCols-1,0);return{start:{line:n,col:0},end:{line:n,col:t}}}function Pt(n,e,t){const s=t(n.line);switch(e){case"word":return gs(n.line,n.col,s);case"line":return Nt(n.line,s);default:{const i=ct(s,n.col);return{start:{line:n.line,col:i},end:{line:n.line,col:i}}}}}function Bt(){return{anchor:null,focus:null,mode:"character"}}function St(n){return!!(n.anchor&&n.focus)}function Ss(){return Bt()}function _s(n,e,t){const s=Pt(e,e.mode,t);return{anchor:s.start,focus:s.end,mode:e.mode}}function _t(n,e,t){return n.anchor?n.mode==="line"?{...n,focus:Nt(e.line,t(e.line)).end}:n.mode==="word"?{...n,focus:Pt(e,"word",t).end}:{...n,focus:{line:e.line,col:ct(t(e.line),e.col)}}:n}function Lt(n){return!n.anchor||!n.focus?null:ys(n.anchor,n.focus)}function xs(n,e,t){const s=n.wrappedToNext?n.colChars.length-1:n.contentCols-1,i=Math.min(t,s);let r=Math.max(0,e);for(;r>0&&n.colChars[r]===null;)r-=1;if(r>i)return"";let o="";for(let l=r;l<=i;l+=1)o+=n.colChars[l]??"";return o}function Ts(n,e){const t=Lt(n);if(!t)return null;let s="";for(let i=t.start.line;i<=t.end.line;i+=1){const r=e(i),o=i===t.start.line?t.start.col:0,l=i===t.end.line?t.end.col:r.colChars.length-1;s+=xs(r,o,l),i<t.end.line&&!r.wrappedToNext&&(s+=`
22
+ `)}return s}function bs(n,e,t,s){const i=Lt(n);if(!i)return[];const r=e+t-1,o=[];for(let l=Math.max(i.start.line,e);l<=Math.min(i.end.line,r);l+=1){const u=l-e;if(l===i.start.line&&l===i.end.line){const f=s==null?void 0:s(l),_=f?gt(f,i.end.col):i.end.col;o.push({row:u,x:i.start.col,width:_-i.start.col+1});continue}if(l===i.start.line){const f=s?Math.max(s(l).colChars.length-i.start.col,0):Number.MAX_SAFE_INTEGER;o.push({row:u,x:i.start.col,width:f});continue}if(l===i.end.line){const f=s==null?void 0:s(l),_=f?gt(f,i.end.col):i.end.col;o.push({row:u,x:0,width:_+1});continue}const a=s?s(l).colChars.length:Number.MAX_SAFE_INTEGER;o.push({row:u,x:0,width:a})}return o}function Ft(){var e;if(typeof navigator>"u")return!1;const n=((e=navigator.userAgentData)==null?void 0:e.platform)??navigator.platform??"";return/mac|iphone|ipad|ipod/iu.test(n)?!0:/mac os x/iu.test(navigator.userAgent??"")}function Es(n){return n.altKey?!1:!!(Ft()?n.metaKey:n.ctrlKey)}function Rs(n){return Es(n)&&n.key.toLowerCase()==="c"}function Cs(n){return n.shiftKey&&n.key==="Insert"&&!n.ctrlKey&&!n.altKey&&!n.metaKey?!0:n.altKey||n.key.toLowerCase()!=="v"?!1:!!(Ft()?n.metaKey:n.ctrlKey)}async function Gt(n){var t;if(!n)return;if(typeof navigator<"u"&&((t=navigator.clipboard)!=null&&t.writeText))try{await navigator.clipboard.writeText(n);return}catch{}if(typeof document>"u"||typeof document.execCommand!="function")throw new Error("clipboard unavailable");const e=document.createElement("textarea");e.value=n,e.setAttribute("readonly","true"),e.style.position="fixed",e.style.left="-9999px",e.style.top="0",document.body.appendChild(e);try{if(e.select(),!document.execCommand("copy"))throw new Error("execCommand copy failed")}finally{e.remove()}}async function vs(n){n&&await Gt(n)}function Ms(n,e){return!e||!n.clipboardData?!1:(n.clipboardData.setData("text/plain",e),n.preventDefault(),!0)}const Ds="/assets/ghostty-vt-BKQMf-5X.wasm",Fe=0,xt=-3,As=11,Os=12,ks=13,Hs=14,Is=1,Ns=2,Ps=9,Bs=1,Ls=0,Fs=1,Gs=2,Us=0,zs=1,Ys=2,Vs=4,Ks=2004,Ws=9,$s=1e3,js=1002,qs=1003,Xs=1005,Tt=1006,Qs=1015,bt=1016;let Je=null;function H(n,e){if(n!==Fe)throw new Error(`${e} failed with result ${n}`)}function Ut(n){const e=n.trim().replace(/^#/,"");if(e.length!==6)throw new Error(`expected #RRGGBB color, received: ${n}`);return[Number.parseInt(e.slice(0,2),16),Number.parseInt(e.slice(2,4),16),Number.parseInt(e.slice(4,6),16)]}function Js(n){const t=[...[n.black,n.red,n.green,n.yellow,n.blue,n.magenta,n.cyan,n.white,n.brightBlack,n.brightRed,n.brightGreen,n.brightYellow,n.brightBlue,n.brightMagenta,n.brightCyan,n.brightWhite].map(Ut)],s=[0,95,135,175,215,255];for(const i of s)for(const r of s)for(const o of s)t.push([i,r,o]);for(let i=0;i<24;i+=1){const r=8+i*10;t.push([r,r,r])}return t}function Zs(n){let e=0;return n&1&&(e+=4),n&4&&(e+=8),n&2&&(e+=16),e}function Ze(n){return n<0||n>223?null:String.fromCharCode(n+32)}function er(n){switch(n){case 1:return 0;case 3:return 1;case 2:return 2;case 4:return 64;case 5:return 65;case 6:return 66;case 7:return 67;case 8:return 128;case 9:return 129;case null:case void 0:return 3;default:return null}}function zt(n){var t,s;let e=0;return n.shiftKey&&(e|=1),n.ctrlKey&&(e|=2),n.altKey&&(e|=4),n.metaKey&&(e|=8),(t=n.getModifierState)!=null&&t.call(n,"CapsLock")&&(e|=16),(s=n.getModifierState)!=null&&s.call(n,"NumLock")&&(e|=32),e}class tr{constructor(e,t,s){this.bindings=e,this.typeName=t,this.ptr=s}get view(){return this.bindings.view(this.ptr,this.bindings.typeSize(this.typeName))}free(){this.bindings.freeBytes(this.ptr,this.bindings.typeSize(this.typeName))}}class nr{constructor(e,t){m(this,"exports");m(this,"layout");m(this,"decoder",new TextDecoder);m(this,"encoder",new TextEncoder);this.exports=e,this.layout=t}buffer(){return this.exports.memory.buffer}bytes(e=0,t=this.buffer().byteLength-e){return new Uint8Array(this.buffer(),e,t)}view(e=0,t=this.buffer().byteLength-e){return new DataView(this.buffer(),e,t)}typeSize(e){const t=this.layout[e];if(!t)throw new Error(`unknown ghostty type: ${e}`);return t.size}field(e,t){const s=this.layout[e],i=s==null?void 0:s.fields[t];if(!s||!i)throw new Error(`unknown ghostty field: ${e}.${t}`);return i}allocStruct(e){const t=this.allocBytes(this.typeSize(e));return this.bytes(t,this.typeSize(e)).fill(0),new tr(this,e,t)}allocBytes(e){return this.exports.ghostty_wasm_alloc_u8_array(e)}freeBytes(e,t){this.exports.ghostty_wasm_free_u8_array(e,t)}allocOpaque(){return this.exports.ghostty_wasm_alloc_opaque()}freeOpaque(e){this.exports.ghostty_wasm_free_opaque(e)}allocU8(){return this.exports.ghostty_wasm_alloc_u8()}freeU8(e){this.exports.ghostty_wasm_free_u8(e)}allocUsize(){return this.exports.ghostty_wasm_alloc_usize()}freeUsize(e){this.exports.ghostty_wasm_free_usize(e)}readPointer(e){return this.view().getUint32(e,!0)}readU8(e){return this.view().getUint8(e)}readUsize(e){return this.view().getUint32(e,!0)}readU64(e){return this.view().getBigUint64(e,!0)}setField(e,t,s,i){const r=this.field(t,s),o=r.offset;switch(r.type){case"u8":case"bool":e.setUint8(o,Number(i));return;case"u16":e.setUint16(o,Number(i),!0);return;case"u32":e.setUint32(o,Number(i),!0);return;case"u64":e.setBigUint64(o,BigInt(i),!0);return;case"usize":{e.setUint32(o,Number(i),!0);return}case"i32":case"enum":e.setInt32(o,Number(i),!0);return;default:throw new Error(`unsupported field type ${t}.${s}: ${r.type}`)}}writeString(e){const t=this.encoder.encode(e),s=this.allocBytes(t.length);return this.bytes(s,t.length).set(t),{ptr:s,len:t.length,free:()=>this.freeBytes(s,t.length)}}writeBytes(e){const t=this.allocBytes(e.length);return this.bytes(t,e.length).set(e),{ptr:t,len:e.length,free:()=>this.freeBytes(t,e.length)}}readOwnedUtf8(e,t){return this.decoder.decode(this.bytes(e,t))}createTerminal(e,t,s){const i=this.allocStruct("GhosttyTerminalOptions");this.setField(i.view,"GhosttyTerminalOptions","cols",e),this.setField(i.view,"GhosttyTerminalOptions","rows",t),this.setField(i.view,"GhosttyTerminalOptions","max_scrollback",s);const r=this.allocOpaque();try{return H(this.exports.ghostty_terminal_new(0,r,i.ptr),"ghostty_terminal_new"),this.readPointer(r)}finally{i.free(),this.freeOpaque(r)}}freeTerminal(e){this.exports.ghostty_terminal_free(e)}writeVt(e,t){const s=typeof t=="string"?this.encoder.encode(t):t,i=this.writeBytes(s);try{this.exports.ghostty_terminal_vt_write(e,i.ptr,i.len)}finally{i.free()}}resetTerminal(e){this.exports.ghostty_terminal_reset(e)}resizeTerminal(e,t,s,i){H(this.exports.ghostty_terminal_resize(e,t,s,Math.max(1,Math.round(i.width)),Math.max(1,Math.round(i.height))),"ghostty_terminal_resize")}scrollViewportDelta(e,t){const s=this.allocStruct("GhosttyTerminalScrollViewport");try{this.setField(s.view,"GhosttyTerminalScrollViewport","tag",Gs),s.view.setBigInt64(this.field("GhosttyTerminalScrollViewport","value").offset,BigInt(t),!0),this.exports.ghostty_terminal_scroll_viewport(e,s.ptr)}finally{s.free()}}scrollViewportTop(e){const t=this.allocStruct("GhosttyTerminalScrollViewport");try{this.setField(t.view,"GhosttyTerminalScrollViewport","tag",Ls),this.exports.ghostty_terminal_scroll_viewport(e,t.ptr)}finally{t.free()}}scrollViewportBottom(e){const t=this.allocStruct("GhosttyTerminalScrollViewport");try{this.setField(t.view,"GhosttyTerminalScrollViewport","tag",Fs),this.exports.ghostty_terminal_scroll_viewport(e,t.ptr)}finally{t.free()}}setTerminalTheme(e,t){const s=this.allocStruct("GhosttyColorRgb"),i=this.allocStruct("GhosttyColorRgb"),r=this.allocStruct("GhosttyColorRgb"),o=Js(t),l=this.allocBytes(o.length*3),u=(f,_)=>{const[C,I,b]=Ut(_);this.setField(f.view,"GhosttyColorRgb","r",C),this.setField(f.view,"GhosttyColorRgb","g",I),this.setField(f.view,"GhosttyColorRgb","b",b)};u(s,t.foreground),u(i,t.background),u(r,t.cursor);const a=this.bytes(l,o.length*3);o.forEach(([f,_,C],I)=>{const b=I*3;a[b]=f,a[b+1]=_,a[b+2]=C});try{H(this.exports.ghostty_terminal_set(e,As,s.ptr),"ghostty_terminal_set(foreground)"),H(this.exports.ghostty_terminal_set(e,Os,i.ptr),"ghostty_terminal_set(background)"),H(this.exports.ghostty_terminal_set(e,ks,r.ptr),"ghostty_terminal_set(cursor)"),H(this.exports.ghostty_terminal_set(e,Hs,l),"ghostty_terminal_set(palette)")}finally{s.free(),i.free(),r.free(),this.freeBytes(l,o.length*3)}}readTerminalSize(e){const t=this.allocBytes(2),s=this.allocBytes(2);try{return H(this.exports.ghostty_terminal_get(e,Is,t),"ghostty_terminal_get(cols)"),H(this.exports.ghostty_terminal_get(e,Ns,s),"ghostty_terminal_get(rows)"),{cols:this.view().getUint16(t,!0),rows:this.view().getUint16(s,!0)}}finally{this.freeBytes(t,2),this.freeBytes(s,2)}}readScrollbar(e){const t=this.allocStruct("GhosttyTerminalScrollbar");try{return H(this.exports.ghostty_terminal_get(e,Ps,t.ptr),"ghostty_terminal_get(scrollbar)"),{total:Number(t.view.getBigUint64(this.field("GhosttyTerminalScrollbar","total").offset,!0)),offset:Number(t.view.getBigUint64(this.field("GhosttyTerminalScrollbar","offset").offset,!0)),len:Number(t.view.getBigUint64(this.field("GhosttyTerminalScrollbar","len").offset,!0))}}finally{t.free()}}isTerminalModeEnabled(e,t){const s=this.allocU8();try{return H(this.exports.ghostty_terminal_mode_get(e,t,s),"ghostty_terminal_mode_get"),this.readU8(s)!==0}finally{this.freeU8(s)}}setTerminalMode(e,t,s){H(this.exports.ghostty_terminal_mode_set(e,t,s?1:0),"ghostty_terminal_mode_set")}createFormatter(e,t,s){const i=this.allocStruct("GhosttyFormatterTerminalOptions"),r=this.field("GhosttyFormatterTerminalOptions","extra").offset,o=this.view(i.ptr+r,this.typeSize("GhosttyFormatterTerminalExtra")),l=this.field("GhosttyFormatterTerminalExtra","screen").offset,u=this.view(i.ptr+r+l,this.typeSize("GhosttyFormatterScreenExtra")),a=this.allocOpaque();try{this.setField(i.view,"GhosttyFormatterTerminalOptions","size",this.typeSize("GhosttyFormatterTerminalOptions")),this.setField(i.view,"GhosttyFormatterTerminalOptions","emit",t),this.setField(i.view,"GhosttyFormatterTerminalOptions","unwrap",s.unwrap),this.setField(i.view,"GhosttyFormatterTerminalOptions","trim",s.trim),this.setField(o,"GhosttyFormatterTerminalExtra","size",this.typeSize("GhosttyFormatterTerminalExtra")),this.setField(o,"GhosttyFormatterTerminalExtra","palette",s.includePalette),this.setField(u,"GhosttyFormatterScreenExtra","size",this.typeSize("GhosttyFormatterScreenExtra"));const f=this.field("GhosttyFormatterTerminalOptions","selection").offset;return i.view.setUint32(f,s.selectionPtr??0,!0),H(this.exports.ghostty_formatter_terminal_new(0,a,e,i.ptr),"ghostty_formatter_terminal_new"),this.readPointer(a)}finally{i.free(),this.freeOpaque(a)}}freeFormatter(e){this.exports.ghostty_formatter_free(e)}resolveViewportGridRef(e,t,s){const i=this.allocStruct("GhosttyPoint"),r=this.allocStruct("GhosttyGridRef");try{this.setField(i.view,"GhosttyPoint","tag",Bs);const o=this.field("GhosttyPoint","value").offset,l=this.view(i.ptr+o,this.typeSize("GhosttyPointCoordinate"));return this.setField(l,"GhosttyPointCoordinate","x",t),this.setField(l,"GhosttyPointCoordinate","y",s),this.exports.ghostty_terminal_grid_ref(e,i.ptr,r.ptr)!==Fe?(r.free(),null):r}finally{i.free()}}createViewportSelection(e,t,s){const i=Math.max(1,Math.floor(t)),r=Math.max(1,Math.floor(s)),o=this.resolveViewportGridRef(e,0,0);if(!o)return null;let l=null;for(let a=r-1;a>=0&&(l=this.resolveViewportGridRef(e,i-1,a),!l);a-=1);if(!l)return o.free(),null;const u=this.allocStruct("GhosttySelection");try{this.setField(u.view,"GhosttySelection","size",this.typeSize("GhosttySelection")),this.setField(u.view,"GhosttySelection","rectangle",!1);const a=this.field("GhosttySelection","start").offset,f=this.field("GhosttySelection","end").offset;return this.bytes(u.ptr+a,this.typeSize("GhosttyGridRef")).set(this.bytes(o.ptr,this.typeSize("GhosttyGridRef"))),this.bytes(u.ptr+f,this.typeSize("GhosttyGridRef")).set(this.bytes(l.ptr,this.typeSize("GhosttyGridRef"))),u}finally{o.free(),l.free()}}formatViewport(e,t,s,i){const r=this.readTerminalSize(e),o=this.createViewportSelection(e,Math.max(1,Math.min(r.cols,i.cols)),Math.max(1,Math.min(r.rows,i.rows))),l=this.createFormatter(e,t,{...s,selectionPtr:(o==null?void 0:o.ptr)??null});try{return this.formatFormatter(l)}finally{this.freeFormatter(l),o==null||o.free()}}formatFormatter(e){const t=this.allocOpaque(),s=this.allocUsize();try{H(this.exports.ghostty_formatter_format_alloc(e,0,t,s),"ghostty_formatter_format_alloc");const i=this.readPointer(t),r=this.readUsize(s),o=this.buffer().byteLength;try{if(r===0||i===0)return"";if(i<0||i>o||r>o-i)throw new Error(`ghostty_formatter_format_alloc returned invalid slice ptr=${i} len=${r} mem=${o}`);return this.readOwnedUtf8(i,r)}finally{r>0&&i!==0&&this.exports.ghostty_free(0,i,r)}}finally{this.freeOpaque(t),this.freeUsize(s)}}createRenderState(){const e=this.allocOpaque();try{return H(this.exports.ghostty_render_state_new(0,e),"ghostty_render_state_new"),this.readPointer(e)}finally{this.freeOpaque(e)}}freeRenderState(e){this.exports.ghostty_render_state_free(e)}updateRenderState(e,t){H(this.exports.ghostty_render_state_update(e,t),"ghostty_render_state_update")}getRenderStateValueResult(e,t,s){return this.exports.ghostty_render_state_get(e,t,s)}getRenderStateValue(e,t,s){H(this.getRenderStateValueResult(e,t,s),"ghostty_render_state_get")}setRenderStateValue(e,t,s){H(this.exports.ghostty_render_state_set(e,t,s),"ghostty_render_state_set")}getRenderStateColors(e,t){H(this.exports.ghostty_render_state_colors_get(e,t),"ghostty_render_state_colors_get")}createRenderStateRowIterator(){const e=this.allocOpaque();try{return H(this.exports.ghostty_render_state_row_iterator_new(0,e),"ghostty_render_state_row_iterator_new"),this.readPointer(e)}finally{this.freeOpaque(e)}}freeRenderStateRowIterator(e){this.exports.ghostty_render_state_row_iterator_free(e)}bindRenderStateRowIterator(e,t){const s=this.allocOpaque();try{this.view(s,4).setUint32(0,t,!0),this.getRenderStateValue(e,4,s)}finally{this.freeOpaque(s)}}nextRenderStateRowIterator(e){return this.exports.ghostty_render_state_row_iterator_next(e)!==0}getRenderStateRowValueResult(e,t,s){return this.exports.ghostty_render_state_row_get(e,t,s)}getRenderStateRowValue(e,t,s){H(this.getRenderStateRowValueResult(e,t,s),"ghostty_render_state_row_get")}setRenderStateRowValue(e,t,s){H(this.exports.ghostty_render_state_row_set(e,t,s),"ghostty_render_state_row_set")}createRenderStateRowCells(){const e=this.allocOpaque();try{return H(this.exports.ghostty_render_state_row_cells_new(0,e),"ghostty_render_state_row_cells_new"),this.readPointer(e)}finally{this.freeOpaque(e)}}freeRenderStateRowCells(e){this.exports.ghostty_render_state_row_cells_free(e)}bindRenderStateRowCells(e,t){const s=this.allocOpaque();try{this.view(s,4).setUint32(0,t,!0),this.getRenderStateRowValue(e,3,s)}finally{this.freeOpaque(s)}}nextRenderStateRowCell(e){return this.exports.ghostty_render_state_row_cells_next(e)!==0}selectRenderStateRowCell(e,t){H(this.exports.ghostty_render_state_row_cells_select(e,t),"ghostty_render_state_row_cells_select")}getRenderStateRowCellValueResult(e,t,s){return this.exports.ghostty_render_state_row_cells_get(e,t,s)}getRenderStateRowCellValue(e,t,s){H(this.getRenderStateRowCellValueResult(e,t,s),"ghostty_render_state_row_cells_get")}getRawRowValueResult(e,t,s){return this.exports.ghostty_row_get(e,t,s)}getRawRowValue(e,t,s){H(this.getRawRowValueResult(e,t,s),"ghostty_row_get")}getRawCellValueResult(e,t,s){return this.exports.ghostty_cell_get(e,t,s)}getRawCellValue(e,t,s){H(this.getRawCellValueResult(e,t,s),"ghostty_cell_get")}createKeyEncoder(){const e=this.allocOpaque();try{return H(this.exports.ghostty_key_encoder_new(0,e),"ghostty_key_encoder_new"),this.readPointer(e)}finally{this.freeOpaque(e)}}freeKeyEncoder(e){this.exports.ghostty_key_encoder_free(e)}createMouseEncoder(){const e=this.allocOpaque(),t=this.allocU8();try{H(this.exports.ghostty_mouse_encoder_new(0,e),"ghostty_mouse_encoder_new");const s=this.readPointer(e);return this.view().setUint8(t,1),this.exports.ghostty_mouse_encoder_setopt(s,Vs,t),s}finally{this.freeU8(t),this.freeOpaque(e)}}freeMouseEncoder(e){this.exports.ghostty_mouse_encoder_free(e)}resetMouseEncoder(e){this.exports.ghostty_mouse_encoder_reset(e)}encodeMouseEvent(e,t,s){const i=this.isTerminalModeEnabled(t,qs),r=this.isTerminalModeEnabled(t,js),o=this.isTerminalModeEnabled(t,$s),l=this.isTerminalModeEnabled(t,Ws);if(!i&&!r&&!o&&!l||s.action==="motion"&&!(i||r&&s.anyButtonPressed)||l&&s.action!=="press"||!i&&!r&&!l&&s.action==="motion")return null;const u=er(s.button);if(u===null)return null;const a=Math.max(1,Math.floor(s.x/Math.max(1,s.cellWidth))+1),f=Math.max(1,Math.floor(s.y/Math.max(1,s.cellHeight))+1),_=Math.round(s.x+1),C=Math.round(s.y+1);let I=s.action==="release"&&!this.isTerminalModeEnabled(t,Tt)&&!this.isTerminalModeEnabled(t,bt)?3:u;if(s.action==="motion"&&(I+=32),I+=Zs(s.mods),this.isTerminalModeEnabled(t,bt)){const b=s.action==="release"?"m":"M";return`\x1B[<${I};${_};${C}${b}`}if(this.isTerminalModeEnabled(t,Tt)){const b=s.action==="release"?"m":"M";return`\x1B[<${I};${a};${f}${b}`}if(this.isTerminalModeEnabled(t,Qs))return`\x1B[${I};${a};${f}M`;if(this.isTerminalModeEnabled(t,Xs)||o||r||i||l){const b=Ze(I),E=Ze(a),z=Ze(f);return!b||!E||!z?null:`\x1B[M${b}${E}${z}`}return null}encodeKeyEvent(e,t,s){if(s.keyCode<=0)return null;const i=this.allocOpaque();let r=0,o=null;try{return H(this.exports.ghostty_key_event_new(0,i),"ghostty_key_event_new"),r=this.readPointer(i),this.exports.ghostty_key_encoder_setopt_from_terminal(e,t),this.exports.ghostty_key_event_set_action(r,s.action==="release"?Us:s.action==="repeat"?Ys:zs),this.exports.ghostty_key_event_set_key(r,s.keyCode),this.exports.ghostty_key_event_set_mods(r,s.mods),this.exports.ghostty_key_event_set_consumed_mods(r,0),this.exports.ghostty_key_event_set_composing(r,s.composing?1:0),s.utf8&&(o=this.writeString(s.utf8),this.exports.ghostty_key_event_set_utf8(r,o.ptr,o.len)),typeof s.unshiftedCodepoint=="number"&&this.exports.ghostty_key_event_set_unshifted_codepoint(r,s.unshiftedCodepoint),this.encodeKeyHandle(e,r)}finally{o==null||o.free(),r!==0&&this.exports.ghostty_key_event_free(r),this.freeOpaque(i)}}encodeKeyHandle(e,t){const s=this.allocUsize();try{const i=this.exports.ghostty_key_encoder_encode(e,t,0,0,s);i!==xt&&i!==Fe&&H(i,"ghostty_key_encoder_encode(size)");const r=Math.max(0,this.readUsize(s));if(r===0)return null;const o=this.allocBytes(r),l=this.allocUsize();try{H(this.exports.ghostty_key_encoder_encode(e,t,o,r,l),"ghostty_key_encoder_encode");const u=this.readUsize(l);return u===0?null:this.readOwnedUtf8(o,u)}finally{this.freeBytes(o,r),this.freeUsize(l)}}finally{this.freeUsize(s)}}encodePaste(e,t){const s=this.writeString(t),i=this.allocUsize();try{const r=this.isTerminalModeEnabled(e,Ks),o=this.exports.ghostty_paste_encode(s.ptr,s.len,r?1:0,0,0,i);o!==xt&&o!==Fe&&H(o,"ghostty_paste_encode(size)");const l=Math.max(0,this.readUsize(i));if(l===0)return"";const u=this.allocBytes(l),a=this.allocUsize();try{return H(this.exports.ghostty_paste_encode(s.ptr,s.len,r?1:0,u,l,a),"ghostty_paste_encode"),this.readOwnedUtf8(u,this.readUsize(a))}finally{this.freeBytes(u,l),this.freeUsize(a)}}finally{s.free(),this.freeUsize(i)}}}async function sr(n){if((n.startsWith("/")||n.startsWith("./")||n.startsWith("../")||/^[A-Za-z]:[\\/]/.test(n))&&typeof Bun<"u")return Bun.file(n).arrayBuffer();const t=await fetch(n);if(!t.ok)throw new Error(`failed to load ghostty wasm: ${t.status} ${t.statusText}`);return t.arrayBuffer()}async function rr(){return Je||(Je=(async()=>{const n=await sr(Ds),t=(await WebAssembly.instantiate(n,{env:{log(){}}})).instance.exports,s=new Uint8Array(t.memory.buffer),i=t.ghostty_type_json();let r=i;for(;s[r]!==0;)r+=1;const o=JSON.parse(new TextDecoder().decode(s.subarray(i,r)));return new nr(t,o)})()),Je}const Et=80,Re=24,et=9,Ne=17,ir=48,Yt="ghostty-official",Ge=9,Ue=1e3,ze=1002,Ye=1003,tt=1007,Pe=1047,Be=1049,or=[Ge,Ue,ze,Ye],Rt=1,Ct=3,vt=2,lr=4,ar=5;class cr{constructor(e){this.content=e}translateToString(e){return e?this.content.replace(/\s+$/u,""):this.content}}class dr{constructor(){m(this,"active",{baseY:0,viewportY:0,length:Re,getLine:e=>{const t=e-this.active.viewportY,s=this.visibleLines[t];return typeof s=="string"?new cr(s):null}});m(this,"visibleLines",Array.from({length:Re},()=>""))}setViewport(e,t,s,i){this.active.viewportY=e,this.active.baseY=t,this.active.length=s,this.visibleLines=i}}function ur(n){return!(n.key.length===1&&!n.ctrlKey&&!n.altKey&&!n.metaKey)}function hr(n,e){const t=n.slice(0,e).map(s=>s.text);for(;t.length<e;)t.push("");return t}function Le(n){return zt({shiftKey:!!n.shiftKey,ctrlKey:!!n.ctrlKey,altKey:!!n.altKey,metaKey:!!n.metaKey,getModifierState:()=>!1})}class fr{constructor(){m(this,"terminal",null)}activate(e){this.terminal=e instanceof We?e:null}fit(){const e=this.proposeDimensions();!this.terminal||!e||this.terminal.resize(e.cols,e.rows)}proposeDimensions(){var e;return((e=this.terminal)==null?void 0:e.measureSizeFromElement())??null}dispose(){this.terminal=null}}class We{constructor(e,t,s,i,r,o){m(this,"buffer",new dr);m(this,"_core",{_renderService:{dimensions:{css:{cell:{width:et,height:Ne}}}}});m(this,"options");m(this,"element",null);m(this,"textarea",null);m(this,"cols",Et);m(this,"rows",Re);m(this,"bindings");m(this,"terminalHandle");m(this,"keyEncoderHandle");m(this,"mouseEncoderHandle");m(this,"renderState");m(this,"dataListeners",new Set);m(this,"selectionListeners",new Set);m(this,"lastNotifiedSelectionText",null);m(this,"addons",new Set);m(this,"screenElement",null);m(this,"renderer",null);m(this,"renderRaf",null);m(this,"disposed",!1);m(this,"disableStdin");m(this,"customKeyEventHandler",()=>!0);m(this,"imeIsComposing",!1);m(this,"lastCompositionCommit",null);m(this,"selectionState",Bt());m(this,"lineCache",new Map);m(this,"lastViewportOffset",0);m(this,"lastViewportRows",Re);m(this,"lastRenderedRows",[]);m(this,"pointerDrag",{active:!1,moved:!1,mode:"character",lastClientX:null,lastClientY:null});m(this,"autoScrollTimer",null);m(this,"domEventDisposers",[]);m(this,"copyShortcutSuppressed",!1);m(this,"scrollbarThumb",null);m(this,"scrollbarFadeTimer",null);m(this,"pressedMouseButtons",new Set);m(this,"wheelPixelDelta",0);m(this,"mouseDragActive",!1);this.bindings=e,this.terminalHandle=t,this.keyEncoderHandle=s,this.mouseEncoderHandle=i,this.renderState=r,this.options=o,this.disableStdin=!!o.disableStdin}static async create(e){const t=await rr(),s=t.createTerminal(Et,Re,e.scrollback);let i=0,r=0,o=null;try{return t.setTerminalTheme(s,e.theme),i=t.createKeyEncoder(),r=t.createMouseEncoder(),o=pt(t),new We(t,s,i,r,o,e)}catch(l){throw o&&Xe(o),i!==0&&t.freeKeyEncoder(i),r!==0&&t.freeMouseEncoder(r),t.freeTerminal(s),l}}open(e){if(this.disposed||this.element)return;const t=document.createElement("div");t.className="xterm",t.style.position="absolute",t.style.inset="0",t.style.overflow="hidden",t.style.width="100%",t.style.height="100%",t.style.backgroundColor=this.options.theme.background,t.style.color=this.options.theme.foreground,t.style.fontFamily=this.options.fontFamily,t.style.fontSize=`${this.options.fontSize}px`,t.style.lineHeight="1.2";const s=document.createElement("div");s.className="xterm-viewport",s.style.width="100%",s.style.height="100%",s.style.overflow="hidden",s.style.position="relative";const i=document.createElement("div");i.className="xterm-screen",i.style.width="100%",i.style.height="100%",i.style.position="relative",i.style.userSelect="none",i.style.webkitUserSelect="none",i.style.backgroundColor=this.options.theme.background;const r=document.createElement("div");r.className="xterm-helper-textarea",r.setAttribute("aria-label","Terminal Input"),r.setAttribute("role","textbox"),r.setAttribute("contenteditable","true"),r.setAttribute("autocorrect","off"),r.setAttribute("autocapitalize","off"),r.setAttribute("spellcheck","false"),r.style.position="absolute",r.style.opacity="1",r.style.pointerEvents="none",r.style.left="0",r.style.top="0",r.style.minWidth="1px",r.style.minHeight="1px",r.style.whiteSpace="pre",r.style.border="0",r.style.padding="0",r.style.margin="0",r.style.color=this.options.theme.foreground,r.style.backgroundColor="transparent",r.style.caretColor="transparent",r.style.overflow="visible",r.style.outline="none",r.style.boxShadow="none",r.style.fontFamily=this.options.fontFamily,r.style.fontSize=`${this.options.fontSize}px`,r.style.userSelect="text",r.style.webkitUserSelect="text";const o=document.createElement("div");o.className="xterm-scrollbar-track",o.style.position="absolute",o.style.top="0",o.style.right="0",o.style.width="8px",o.style.height="100%",o.style.backgroundColor="transparent",o.style.pointerEvents="none";const l=document.createElement("div");l.className="xterm-scrollbar-thumb",l.style.position="absolute",l.style.top="0",l.style.right="0",l.style.width="6px",l.style.marginRight="1px",l.style.borderRadius="3px",l.style.backgroundColor="rgba(128, 128, 128, 0.5)",l.style.pointerEvents="none",l.style.transition="opacity 0.15s ease",l.style.opacity="0",o.appendChild(l),s.appendChild(i),t.appendChild(s),t.appendChild(r),t.appendChild(o),e.appendChild(t),this.element=t,this.screenElement=i,this.textarea=r,this.scrollbarThumb=l,this.renderer=new Dn({screenElement:i,theme:this.options.theme,fontFamily:this.options.fontFamily,fontSize:this.options.fontSize}),this.syncInputState(),this.bindDomEvents(),this.updateCellDimensions();const u=this.measureSizeFromElement();u?this.resize(u.cols,u.rows):this.render()}loadAddon(e){e.activate(this),this.addons.add(e)}onData(e){return this.dataListeners.add(e),{dispose:()=>{this.dataListeners.delete(e)}}}attachCustomKeyEventHandler(e){this.customKeyEventHandler=e}onSelectionChange(e){return this.selectionListeners.add(e),{dispose:()=>{this.selectionListeners.delete(e)}}}hasSelection(){return St(this.selectionState)}getSelection(){return this.getSelectionText()??""}clearSelection(){this.disposed||this.clearSelectionState()}startTouchSelection(e,t,s="word"){return this.disposed?!1:this.beginSelectionAt(e,t,s)}updateTouchSelection(e,t){this.disposed||this.updateSelectionDrag(e,t)}endTouchSelection(){this.disposed||!this.pointerDrag.active||(this.stopAutoScroll(),this.pointerDrag.active=!1,this.render())}write(e){if(this.disposed)return;const t=this.isAltScreenActive();this.bindings.writeVt(this.terminalHandle,e);const s=this.isAltScreenActive();t&&!s&&this.clearMouseTrackingModes(),this.scheduleRender()}clearMouseTrackingModes(){if(!this.disposed){for(const e of or)this.bindings.setTerminalMode(this.terminalHandle,e,!1);this.bindings.resetMouseEncoder(this.mouseEncoderHandle),this.pressedMouseButtons.clear(),this.mouseDragActive=!1}}isAltScreenActive(){return this.isModeEnabled(Pe)||this.isModeEnabled(Be)}reset(){this.disposed||(this.lineCache.clear(),this.clearSelectionState(!1),this.bindings.resetTerminal(this.terminalHandle),this.scheduleRender())}refresh(){this.disposed||this.render()}resize(e,t){if(this.disposed)return;const s=Math.max(2,Math.floor(e)),i=Math.max(2,Math.floor(t));this.cols=s,this.rows=i,this.clearSelectionState(!1),this.bindings.resizeTerminal(this.terminalHandle,s,i,this.cellDimensions()),this.bindings.resetMouseEncoder(this.mouseEncoderHandle),this.scheduleRender()}scrollLines(e){this.disposed||e===0||(this.bindings.scrollViewportDelta(this.terminalHandle,e),this.render())}scrollToTop(){this.disposed||(this.bindings.scrollViewportTop(this.terminalHandle),this.render())}scrollToBottom(){this.disposed||(this.bindings.scrollViewportBottom(this.terminalHandle),this.render())}exportModeSnapshot(){return{mouseX10:this.isModeEnabled(Ge),mouseNormal:this.isModeEnabled(Ue),mouseButton:this.isModeEnabled(ze),mouseAny:this.isModeEnabled(Ye),mouseUtf8:this.isModeEnabled(1005),mouseSgr:this.isModeEnabled(1006),mouseSgrPixels:this.isModeEnabled(1016),mouseUrxvt:this.isModeEnabled(1015),altScroll:this.isModeEnabled(tt),altScreen1047:this.isModeEnabled(Pe),altScreen1049:this.isModeEnabled(Be)}}restoreModeSnapshot(e){this.bindings.setTerminalMode(this.terminalHandle,Ge,e.mouseX10),this.bindings.setTerminalMode(this.terminalHandle,Ue,e.mouseNormal),this.bindings.setTerminalMode(this.terminalHandle,ze,e.mouseButton),this.bindings.setTerminalMode(this.terminalHandle,Ye,e.mouseAny),this.bindings.setTerminalMode(this.terminalHandle,1005,e.mouseUtf8),this.bindings.setTerminalMode(this.terminalHandle,1006,e.mouseSgr),this.bindings.setTerminalMode(this.terminalHandle,1016,e.mouseSgrPixels),this.bindings.setTerminalMode(this.terminalHandle,1015,e.mouseUrxvt),this.bindings.setTerminalMode(this.terminalHandle,tt,e.altScroll),this.bindings.setTerminalMode(this.terminalHandle,Pe,e.altScreen1047),this.bindings.setTerminalMode(this.terminalHandle,Be,e.altScreen1049),this.bindings.resetMouseEncoder(this.mouseEncoderHandle)}handleViewportGesture(e){if(this.disposed||e.deltaY===0)return!1;const t=this.gestureToLines(e);if(t===0)return!1;const s=this.getInputRoutingState();if(s.mouseReporting){const i=t<0?lr:ar;let r=!1;for(let o=0;o<Math.abs(t);o+=1)r=this.emitMouseInput({action:"press",button:i,clientX:e.clientX,clientY:e.clientY,mods:Le(e),anyButtonPressed:this.pressedMouseButtons.size>0})||r;return r}return s.altScroll?this.emitAltScrollInput(t):(this.scrollLines(t),!0)}paste(e){if(this.disposed||this.disableStdin||!e)return;const t=this.bindings.encodePaste(this.terminalHandle,e);t&&this.emitData(t)}focus(){var e;(e=this.textarea)==null||e.focus({preventScroll:!0})}getRendererKind(){var e;return((e=this.renderer)==null?void 0:e.kind)??"unknown"}setTheme(e){var t;this.bindings.setTerminalTheme(this.terminalHandle,e),this.options.theme=e,this.element&&(this.element.style.backgroundColor=e.background,this.element.style.color=e.foreground),this.screenElement&&(this.screenElement.style.backgroundColor=e.background),(t=this.renderer)==null||t.setTheme(e),this.scheduleRender()}setDisableStdin(e){this.disableStdin=e,this.syncInputState()}measureSizeFromElement(){const e=this.element;if(!e)return null;const t=e.getBoundingClientRect(),{width:s,height:i}=this.cellDimensions();return t.width===0||t.height===0||s<=0||i<=0?null:{cols:Math.max(2,Math.floor(t.width/s)),rows:Math.max(2,Math.floor(t.height/i))}}dispose(){var e,t;if(!this.disposed){this.disposed=!0,this.renderRaf!==null&&(cancelAnimationFrame(this.renderRaf),this.renderRaf=null),this.stopAutoScroll(),this.updateSelectionTextProbe(null),this.clearDomEventListeners(),this.scrollbarFadeTimer&&(clearTimeout(this.scrollbarFadeTimer),this.scrollbarFadeTimer=null);for(const s of this.addons)s.dispose();this.addons.clear(),(e=this.renderer)==null||e.dispose(),this.renderer=null,(t=this.element)==null||t.remove(),this.element=null,this.screenElement=null,this.textarea=null,this.scrollbarThumb=null,Xe(this.renderState),this.bindings.freeMouseEncoder(this.mouseEncoderHandle),this.bindings.freeKeyEncoder(this.keyEncoderHandle),this.bindings.freeTerminal(this.terminalHandle)}}cellDimensions(){return this._core._renderService.dimensions.css.cell}syncInputState(){this.textarea&&(this.textarea.readOnly=this.disableStdin,this.textarea.tabIndex=this.disableStdin?-1:0,this.disableStdin&&document.activeElement===this.textarea&&this.textarea.blur())}bindDomEvents(){const e=this.element,t=this.textarea;if(!e||!t)return;e.addEventListener("click",()=>{this.disableStdin||this.focus()}),(this.screenElement??e).addEventListener("mousedown",r=>{if(r instanceof MouseEvent){if(this.disableStdin||this.focus(),this.getInputRoutingState().mouseReporting){const o=this.mouseButtonFromEvent(r);if(o===null)return;this.clearSelectionState(),this.pressedMouseButtons.add(o),this.mouseDragActive=!0,this.emitMouseInput({action:"press",button:o,clientX:r.clientX,clientY:r.clientY,mods:Le(r),anyButtonPressed:!0}),r.preventDefault();return}r.button===0&&(this.mouseDragActive=!0,this.beginPointerSelection(r),r.preventDefault())}}),e.addEventListener("wheel",r=>{this.handleViewportGesture({source:"wheel",deltaY:r.deltaY,deltaMode:r.deltaMode,clientX:r.clientX,clientY:r.clientY,shiftKey:r.shiftKey,ctrlKey:r.ctrlKey,altKey:r.altKey,metaKey:r.metaKey})&&r.preventDefault()},{passive:!1});const i=typeof window<"u"&&typeof window.addEventListener=="function"?window:null;if(i){const r=l=>{if(this.mouseDragActive){if(this.getInputRoutingState().mouseReporting){this.emitMouseInput({action:"motion",button:this.mouseButtonFromButtons(l.buttons),clientX:l.clientX,clientY:l.clientY,mods:Le(l),anyButtonPressed:this.pressedMouseButtons.size>0||l.buttons>0});return}this.updatePointerSelection(l)}},o=l=>{if(this.mouseDragActive){if(this.mouseDragActive=!1,this.getInputRoutingState().mouseReporting){const u=this.mouseButtonFromEvent(l);u!==null&&this.pressedMouseButtons.delete(u),this.emitMouseInput({action:"release",button:u,clientX:l.clientX,clientY:l.clientY,mods:Le(l),anyButtonPressed:this.pressedMouseButtons.size>0});return}this.finishPointerSelection(l)}};i.addEventListener("mousemove",r),i.addEventListener("mouseup",o),this.domEventDisposers.push(()=>{i.removeEventListener("mousemove",r),i.removeEventListener("mouseup",o)})}t.addEventListener("keydown",r=>{const o=this.getSelectionText();if(o&&Rs(r)){r.preventDefault(),vs(o).catch(()=>{}),this.clearSelectionState(),this.copyShortcutSuppressed=!0,this.clearTextarea();return}if(!this.customKeyEventHandler(r)||this.disableStdin||this.imeIsComposing||r.keyCode===229||Cs(r)||!ur(r))return;const l=this.encodeKeyboardEvent(r,r.repeat?"repeat":"press");l&&(r.preventDefault(),this.emitData(l),this.clearTextarea())}),t.addEventListener("keyup",r=>{if(this.copyShortcutSuppressed){const l=r.key.toLowerCase();if(l==="c"){r.preventDefault();return}if(l==="control"||l==="meta"||l==="os"){this.copyShortcutSuppressed=!1,r.preventDefault();return}}if(this.disableStdin||this.imeIsComposing)return;const o=this.encodeKeyboardEvent(r,"release");o&&(r.preventDefault(),this.emitData(o),this.clearTextarea())}),t.addEventListener("compositionstart",()=>{this.imeIsComposing=!0,this.lastCompositionCommit=null,this.syncTextareaPositionToCursor()}),t.addEventListener("compositionupdate",()=>{this.syncTextareaPositionToCursor()}),t.addEventListener("compositionend",r=>{this.imeIsComposing=!1;const o=r.data??"";o&&(this.lastCompositionCommit={data:o,at:Date.now()},this.emitData(o),this.clearTextarea())}),t.addEventListener("beforeinput",r=>{if(this.disableStdin||r.inputType==="insertFromPaste")return;const o=r.data??"";if(!o||r.isComposing||this.imeIsComposing)return;const l=this.lastCompositionCommit;if(l&&l.data===o&&Date.now()-l.at<40){this.lastCompositionCommit=null,r.preventDefault(),this.clearTextarea();return}this.lastCompositionCommit=null,r.preventDefault(),this.emitData(o),this.clearTextarea()}),t.addEventListener("paste",r=>{var l;if(this.disableStdin)return;const o=((l=r.clipboardData)==null?void 0:l.getData("text/plain"))??"";o&&(r.preventDefault(),this.paste(o),this.clearTextarea())}),t.addEventListener("copy",r=>{const o=this.getSelectionText();o&&Ms(r,o)}),t.addEventListener("input",()=>{if(this.disableStdin||this.imeIsComposing)return;const r=t.textContent??"";if(!r){this.clearTextarea();return}const o=this.lastCompositionCommit;if(o&&o.data===r&&Date.now()-o.at<40){this.lastCompositionCommit=null,this.clearTextarea();return}this.lastCompositionCommit=null,this.emitData(r),this.clearTextarea()})}encodeKeyboardEvent(e,t){const s=ht(e.code);if(s===0)return null;const i=e.key.length===1&&!e.ctrlKey&&!e.metaKey?e.key:null;return this.bindings.encodeKeyEvent(this.keyEncoderHandle,this.terminalHandle,{action:t,keyCode:s,mods:zt(e),composing:e.isComposing,utf8:i,unshiftedCodepoint:kn(e.code)})}getInputRoutingState(){const e=this.isModeEnabled(Ge)||this.isModeEnabled(Ue)||this.isModeEnabled(ze)||this.isModeEnabled(Ye),t=this.isModeEnabled(Pe)||this.isModeEnabled(Be);return{mouseReporting:e,altScroll:!e&&t&&this.isModeEnabled(tt)}}gestureToLines(e){const t=this.cellDimensions().height||Ne;if(e.source==="wheel"){if(e.deltaMode===1)return this.wheelPixelDelta=0,e.deltaY>0?Math.ceil(e.deltaY):Math.floor(e.deltaY);if(e.deltaMode===2){this.wheelPixelDelta=0;const i=Math.max(1,this.rows),r=e.deltaY*i;return r>0?Math.ceil(r):Math.floor(r)}this.wheelPixelDelta+=e.deltaY;const s=this.wheelPixelDelta>0?Math.floor(this.wheelPixelDelta/t):Math.ceil(this.wheelPixelDelta/t);return s!==0&&(this.wheelPixelDelta-=s*t),s}return e.deltaY>0?Math.ceil(e.deltaY/t):Math.floor(e.deltaY/t)}isModeEnabled(e){return this.bindings.isTerminalModeEnabled(this.terminalHandle,e)}mouseButtonFromEvent(e){switch(e.button){case 0:return Rt;case 1:return Ct;case 2:return vt;default:return null}}mouseButtonFromButtons(e){return e&1?Rt:e&4?Ct:e&2?vt:null}pointerPositionFromClient(e,t){var o;const s=(o=this.screenElement)==null?void 0:o.getBoundingClientRect();if(!s)return null;const i=Math.max(1,s.width),r=Math.max(1,s.height);return{x:Math.max(0,Math.min(i-1,e-s.left)),y:Math.max(0,Math.min(r-1,t-s.top))}}emitMouseInput(e){var o;if(this.disableStdin)return!1;const t=this.pointerPositionFromClient(e.clientX,e.clientY);if(!t)return!1;const s=this.cellDimensions(),i=(o=this.screenElement)==null?void 0:o.getBoundingClientRect();if(!i)return!1;const r=this.bindings.encodeMouseEvent(this.mouseEncoderHandle,this.terminalHandle,{action:e.action,button:e.button,mods:e.mods,x:t.x,y:t.y,anyButtonPressed:e.anyButtonPressed,screenWidth:Math.max(1,Math.round(i.width)),screenHeight:Math.max(1,Math.round(i.height)),cellWidth:Math.max(1,Math.round(s.width||et)),cellHeight:Math.max(1,Math.round(s.height||Ne))});return r?(this.emitData(r),!0):!1}emitAltScrollInput(e){const t=ht(e<0?"ArrowUp":"ArrowDown");if(t===0)return!1;let s=!1;for(let i=0;i<Math.abs(e);i+=1){const r=this.bindings.encodeKeyEvent(this.keyEncoderHandle,this.terminalHandle,{action:"press",keyCode:t,mods:0,composing:!1,utf8:null,unshiftedCodepoint:null});r&&(this.emitData(r),s=!0)}return s}emitData(e){for(const t of this.dataListeners)t(e)}clearTextarea(){this.textarea&&(this.textarea.textContent="")}syncTextareaPositionToCursor(){const e=this.textarea,t=this.screenElement;if(!e||!t)return;const{width:s,height:i}=this.cellDimensions();if(s<=0||i<=0)return;const r=pt(this.bindings);let o=0,l=0;try{wt(r,this.terminalHandle);const f=st(r);f.cursor.x!==null&&f.cursor.y!==null&&(o=f.cursor.x,l=f.cursor.y)}finally{Xe(r)}const u=o*s,a=l*i;e.style.left=`${u}px`,e.style.top=`${a}px`,e.style.width=`${Math.max(1,s)}px`,e.style.height=`${Math.max(1,i)}px`,e.style.lineHeight=`${i}px`,e.style.fontFamily=this.options.fontFamily,e.style.fontSize=`${this.options.fontSize}px`}scheduleRender(){this.renderRaf===null&&(this.renderRaf=requestAnimationFrame(()=>{this.renderRaf=null,this.render()}))}render(){if(this.disposed||!this.screenElement||!this.renderer)return;const e=this.bindings.readScrollbar(this.terminalHandle),t=Math.max(1,e.len||this.rows);wt(this.renderState,this.terminalHandle);const s=st(this.renderState),i=Array.from(fs(this.renderState));this.cols=Math.max(2,s.cols),this.rows=Math.max(2,s.rows||t),this.lastViewportOffset=e.offset,this.lastViewportRows=this.rows,this.lastRenderedRows=i;for(const a of i)this.lineCache.set(e.offset+a.y,yt(a.cells,a.wrap));const r=bs(this.selectionState,this.lastViewportOffset,this.lastViewportRows,a=>this.getLineModel(a)),o=this.getSelectionText();this.renderer.render({meta:s,rows:i,cellDimensions:this.cellDimensions(),selectionRects:r,selectionColor:this.options.theme.selectionBackground});const l=hr(i,this.rows),u=Math.max(0,e.total-e.len);this.buffer.setViewport(e.offset,u,e.total,l),this.updateSelectionTextProbe(o),this.updateScrollbar(e)}updateScrollbar(e){var u;const t=this.scrollbarThumb;if(!t)return;const s=((u=this.screenElement)==null?void 0:u.clientHeight)??0;if(s===0||e.total<=e.len){t.style.opacity="0";return}const i=e.len/e.total,r=Math.max(20,i*s),l=e.offset/Math.max(1,e.total-e.len)*(s-r);t.style.height=`${r}px`,t.style.transform=`translateY(${l}px)`,t.style.opacity="1",this.scrollbarFadeTimer&&clearTimeout(this.scrollbarFadeTimer),this.scrollbarFadeTimer=setTimeout(()=>{t.style.opacity="0"},800)}updateCellDimensions(){if(!this.element)return;const e=document.createElement("span");e.textContent="WWWWWWWWWW",e.style.position="absolute",e.style.visibility="hidden",e.style.whiteSpace="pre",e.style.fontFamily=this.options.fontFamily,e.style.fontSize=`${this.options.fontSize}px`,e.style.lineHeight="1.2",this.element.appendChild(e);const t=e.getBoundingClientRect();e.remove();const s=Math.max(1,globalThis.devicePixelRatio??1),i=t.width>0?t.width/10:et,r=t.height>0?t.height:Ne;this._core._renderService.dimensions.css.cell.width=Math.max(1,Math.round(i*s))/s,this._core._renderService.dimensions.css.cell.height=Math.max(1,Math.round(r*s))/s}clearSelectionState(e=!0){this.selectionState=Ss(),this.pressedMouseButtons.clear(),this.wheelPixelDelta=0,this.pointerDrag={active:!1,moved:!1,mode:"character",lastClientX:null,lastClientY:null},this.copyShortcutSuppressed=!1,this.stopAutoScroll(),this.updateSelectionTextProbe(null),e&&this.screenElement&&this.renderer&&this.render()}beginSelectionAt(e,t,s){const i=this.hitTest(e,t);return i?(this.pointerDrag={active:!0,moved:!1,mode:s,lastClientX:e,lastClientY:t},this.selectionState=_s(this.selectionState,{...i,mode:s},r=>this.getLineModel(r)),this.updateAutoScroll(),this.render(),!0):!1}updateSelectionDrag(e,t){if(!this.pointerDrag.active)return;const s=this.hitTest(e,t);this.pointerDrag.lastClientX=e,this.pointerDrag.lastClientY=t,s&&(this.pointerDrag.moved=!0,this.selectionState=_t(this.selectionState,s,i=>this.getLineModel(i)),this.render()),this.updateAutoScroll()}beginPointerSelection(e){this.beginSelectionAt(e.clientX,e.clientY,this.selectionModeFromClickDetail(e.detail))}updatePointerSelection(e){this.updateSelectionDrag(e.clientX,e.clientY)}finishPointerSelection(e){var s,i,r,o;if(!this.pointerDrag.active||e.button!==0)return;this.pointerDrag.lastClientX=e.clientX,this.pointerDrag.lastClientY=e.clientY,this.stopAutoScroll();const t=this.pointerDrag.mode==="character"&&!this.pointerDrag.moved&&((s=this.selectionState.anchor)==null?void 0:s.line)===((i=this.selectionState.focus)==null?void 0:i.line)&&((r=this.selectionState.anchor)==null?void 0:r.col)===((o=this.selectionState.focus)==null?void 0:o.col);if(this.pointerDrag.active=!1,t){this.clearSelectionState();return}this.render()}selectionModeFromClickDetail(e){return e>=3?"line":e===2?"word":"character"}hitTest(e,t){var C;const s=(C=this.screenElement)==null?void 0:C.getBoundingClientRect();if(!s)return null;const{width:i,height:r}=this.cellDimensions();if(i<=0||r<=0)return null;const o=e-s.left,l=t-s.top,u=Math.max(this.cols-1,0),a=Math.max(this.lastViewportRows-1,0),f=Math.max(0,Math.min(u,Math.floor(o/i))),_=Math.max(0,Math.min(a,Math.floor(l/r)));return{line:this.lastViewportOffset+_,col:f}}getLineModel(e){const t=this.lineCache.get(e);if(t)return t;const s=e-this.lastViewportOffset,i=this.lastRenderedRows[s];return i?yt(i.cells,i.wrap):ms}getSelectionText(){return St(this.selectionState)?Ts(this.selectionState,e=>this.getLineModel(e)):null}updateSelectionTextProbe(e){if(globalThis.__tmexE2eTerminalSelectionText=e,e!==this.lastNotifiedSelectionText){this.lastNotifiedSelectionText=e;for(const t of this.selectionListeners)t(e)}}updateAutoScroll(){var s;if(!this.pointerDrag.active||this.pointerDrag.lastClientY===null){this.stopAutoScroll();return}const e=(s=this.screenElement)==null?void 0:s.getBoundingClientRect();if(!e){this.stopAutoScroll();return}if(!(this.pointerDrag.lastClientY<e.top||this.pointerDrag.lastClientY>e.bottom)){this.stopAutoScroll();return}this.autoScrollTimer===null&&(this.autoScrollTimer=setInterval(()=>{this.stepAutoScroll()},ir))}stepAutoScroll(){var i;if(!this.pointerDrag.active||this.pointerDrag.lastClientX===null||this.pointerDrag.lastClientY===null){this.stopAutoScroll();return}const e=(i=this.screenElement)==null?void 0:i.getBoundingClientRect();if(!e){this.stopAutoScroll();return}let t=0;if(this.pointerDrag.lastClientY<e.top?t=-1:this.pointerDrag.lastClientY>e.bottom&&(t=1),t===0){this.stopAutoScroll();return}this.bindings.scrollViewportDelta(this.terminalHandle,t),this.render();const s=this.hitTest(this.pointerDrag.lastClientX,this.pointerDrag.lastClientY);s&&(this.selectionState=_t(this.selectionState,s,r=>this.getLineModel(r)),this.pointerDrag.moved=!0,this.render())}stopAutoScroll(){this.autoScrollTimer!==null&&(clearInterval(this.autoScrollTimer),this.autoScrollTimer=null)}clearDomEventListeners(){for(;this.domEventDisposers.length>0;){const e=this.domEventDisposers.pop();e==null||e()}}}async function mr(n){return We.create(n)}function pr({visible:n,canPaste:e,onCopy:t,onPaste:s,onDismiss:i}){const{t:r}=Ke();if(!n)return null;const o=l=>{l.preventDefault()};return h.jsxs("div",{className:"absolute top-2 left-1/2 z-20 flex -translate-x-1/2 items-center gap-1 rounded-lg border bg-background/95 p-1 shadow-md backdrop-blur","data-testid":"terminal-selection-toolbar",children:[h.jsxs("button",{type:"button",className:"flex h-9 items-center gap-1.5 rounded-md px-3 text-sm font-medium hover:bg-accent hover:text-accent-foreground",onMouseDown:o,onClick:t,"data-testid":"terminal-selection-copy",children:[h.jsx(Tn,{className:"h-4 w-4"}),r("terminal.copy")]}),e&&h.jsxs("button",{type:"button",className:"flex h-9 items-center gap-1.5 rounded-md px-3 text-sm font-medium hover:bg-accent hover:text-accent-foreground",onMouseDown:o,onClick:s,"data-testid":"terminal-selection-paste",children:[h.jsx(_n,{className:"h-4 w-4"}),r("terminal.paste")]}),h.jsx("button",{type:"button",className:"flex h-9 w-9 items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-accent-foreground",onMouseDown:o,onClick:i,"aria-label":r("terminal.clearSelection"),"data-testid":"terminal-selection-dismiss",children:h.jsx(qt,{className:"h-4 w-4"})})]})}function Vt(n){if(!n)return n;const e=n.replace(/\r\n/g,`
23
+ `);return(e.endsWith(`
24
+ `)?e.slice(0,-1):e).replace(/\n/g,`\r
25
+ `)}const wr="\x1B[?1049h\x1B[H\x1B[2J";function yr(n){return wr+Vt(n)}function Mt(n,e){let t=e,s=0;for(const l of n)l===10&&!t&&(s+=1),t=l===13;const i=t;if(s===0)return{normalized:n,endedWithCR:i};const r=new Uint8Array(n.length+s);let o=0;t=e;for(const l of n)l===10&&!t&&(r[o]=13,o+=1),r[o]=l,o+=1,t=l===13;return{normalized:r,endedWithCR:i}}const gr=1.3,Sr=36,_r=500,xr=12;function Tr(n,e){const t=d.useRef(!1);return d.useEffect(()=>{const s=n.current;if(!s||!(window.innerWidth<768||navigator.maxTouchPoints>0||"ontouchstart"in window))return;t.current=!0;let r=0,o=null,l=!1,u=0,a=0,f=0,_=null,C=!1;const I=()=>{_!==null&&(clearTimeout(_),_=null)},b=T=>T?!!(T.closest(".scrollbar")||T.closest(".slider")||T.closest(".xterm-scroll-area")):!1,E=(T,v,P)=>{const F=P instanceof Element?P:null;if(b(F))return!0;const K=document.elementFromPoint(T,v);if(b(K))return!0;const S=s.querySelector(".xterm");if(!(S instanceof HTMLElement))return!1;const R=S.getBoundingClientRect(),B=T>=R.left&&T<=R.right,G=v>=R.top&&v<=R.bottom;return!B||!G?!1:T>=R.right-Sr},z=()=>[s.querySelector(".xterm-viewport"),s.querySelector(".xterm-scrollable-element")].filter(v=>v instanceof HTMLElement),w=T=>{if(o===null)return null;for(let v=0;v<T.length;v+=1){const P=T.item(v);if(P&&P.identifier===o)return P}return null},k=T=>{if(I(),T.touches.length!==1)return;const v=T.touches.item(0);v&&(o=v.identifier,r=v.clientY,u=0,l=E(v.clientX,v.clientY,T.target),a=v.clientX,f=v.clientY,C=!1,l||(_=setTimeout(()=>{var F;_=null;const P=(e==null?void 0:e())??null;(F=P==null?void 0:P.startTouchSelection)!=null&&F.call(P,a,f,"word")&&(C=!0)},_r)))},A=T=>{var B,G,N,j,J,te,se,O,ie;const v=w(T.touches)??T.touches.item(0);if(!v)return;if(C){const U=(e==null?void 0:e())??null;(B=U==null?void 0:U.updateTouchSelection)==null||B.call(U,v.clientX,v.clientY),T.cancelable&&T.preventDefault();return}if(_!==null&&Math.hypot(v.clientX-a,v.clientY-f)>xr&&I(),l||(l=E(v.clientX,v.clientY,T.target),l&&(u=0)),l)return;const P=v.clientY,F=r-P;if(r=P,F===0)return;let K=!1,S=!1;const R=(e==null?void 0:e())??null;if(R){const U=R==null?void 0:R._core,Y=((J=(j=(N=(G=U==null?void 0:U._renderService)==null?void 0:G.dimensions)==null?void 0:N.css)==null?void 0:j.cell)==null?void 0:J.height)??18;u+=F*gr;const L=u>0?Math.floor(u/Y):Math.ceil(u/Y);if(typeof R.handleViewportGesture=="function")L!==0&&(K=R.handleViewportGesture({source:"touch",deltaY:L*Y,clientX:v.clientX,clientY:v.clientY}),u-=L*Y);else if(L!==0){const $=((se=(te=R.buffer)==null?void 0:te.active)==null?void 0:se.viewportY)??0;R.scrollLines(L);const g=((ie=(O=R.buffer)==null?void 0:O.active)==null?void 0:ie.viewportY)??0;K=$!==g,S=L<0&&$<=0&&g<=0,u-=L*Y}}else{const U=z();if(U.length===0)return;for(const Y of U){const L=Y.scrollTop;Y.scrollTop+=F;const $=Y.scrollTop;Math.abs($-L)>0&&(K=!0),F<0&&$<=0&&(S=!0)}if(!K){const Y=s.querySelector(".xterm");if(Y instanceof HTMLElement){const L=new WheelEvent("wheel",{bubbles:!0,cancelable:!0,deltaMode:WheelEvent.DOM_DELTA_PIXEL,deltaY:F}),$=Y.dispatchEvent(L);K=L.defaultPrevented||!$}}}T.cancelable&&(K||S)&&T.preventDefault()},W=T=>{var P;if(I(),!(o===null||!w(T.changedTouches))&&(o=null,u=0,l=!1,C)){C=!1;const F=(e==null?void 0:e())??null;(P=F==null?void 0:F.endTouchSelection)==null||P.call(F)}},V=T=>{C&&T.preventDefault()};return s.addEventListener("touchstart",k,{passive:!0}),s.addEventListener("touchmove",A,{passive:!1}),s.addEventListener("touchend",W,{passive:!0}),s.addEventListener("touchcancel",W,{passive:!0}),s.addEventListener("contextmenu",V),()=>{t.current=!1,I(),s.removeEventListener("touchstart",k),s.removeEventListener("touchmove",A),s.removeEventListener("touchend",W),s.removeEventListener("touchcancel",W),s.removeEventListener("contextmenu",V)}},[n,e]),t}function br({now:n,remoteSize:e,pendingLocalSize:t,ttlMs:s=2e3}){return!t||n-t.at>s?!0:t.cols===e.cols&&t.rows===e.rows}function Er({currentSize:n,containerSize:e,force:t=!1}){return t?!0:n.cols!==e.cols||n.rows!==e.rows}function Rr({deviceId:n,paneId:e,deviceConnected:t,isSelectionInvalid:s,onResize:i,onSync:r,getContainerRect:o}){const l=d.useRef(null),u=d.useRef(null),a=d.useRef(null),f=d.useRef(null),_=d.useRef(0),C=d.useRef([]),I=d.useRef(null),b=d.useRef(null),E=d.useRef(o),z=d.useRef(!1),w=d.useRef(i),k=d.useRef(r);d.useEffect(()=>{w.current=i},[i]),d.useEffect(()=>{k.current=r},[r]),d.useEffect(()=>{E.current=o},[o]);const A=d.useCallback(()=>{var te,se,O,ie,U,Y,L,$,g,x;const S=b.current,R=I.current;if(!S||!R||!S.element)return null;let B;try{const M=R.proposeDimensions();if(!M)throw new Error("fitAddon.proposeDimensions() returned null");B=Math.max(2,M.cols)}catch{const M=S._core,q=((ie=(O=(se=(te=M==null?void 0:M._renderService)==null?void 0:te.dimensions)==null?void 0:se.css)==null?void 0:O.cell)==null?void 0:ie.width)??9,X=(U=E.current)==null?void 0:U.call(E);if(!X||X.width===0)return null;B=Math.max(2,Math.floor(X.width/q))}const G=(Y=E.current)==null?void 0:Y.call(E);if(!G||G.height===0)return null;const N=S._core,j=((x=(g=($=(L=N==null?void 0:N._renderService)==null?void 0:L.dimensions)==null?void 0:$.css)==null?void 0:g.cell)==null?void 0:x.height)??17,J=Math.max(2,Math.floor(G.height/j));return{cols:B,rows:J}},[]),W=d.useCallback((S,R)=>{const B=b.current;B&&(B.cols===S&&B.rows===R||B.resize(S,R))},[]),V=d.useCallback((S,R=!1)=>{if(!n||!e||!t||s&&S!=="sync"||!R&&Date.now()<_.current||!b.current)return!1;const G=A();if(!G)return!1;const{cols:N,rows:j}=G,J=a.current;return!R&&J&&J.cols===N&&J.rows===j?(W(N,j),!0):(W(N,j),S==="sync"?k.current(N,j):w.current(N,j),a.current={cols:N,rows:j},f.current={cols:N,rows:j,at:Date.now()},!0)},[W,t,n,s,A,e]),T=d.useCallback((S="resize",R={})=>{const{immediate:B=!1,force:G=!1}=R;u.current!==null&&(window.clearTimeout(u.current),u.current=null),l.current!==null&&(cancelAnimationFrame(l.current),l.current=null);const N=()=>{l.current=requestAnimationFrame(()=>{l.current=null,V(S,G)})};if(B){N();return}u.current=window.setTimeout(()=>{u.current=null,N()},150)},[V]),v=d.useCallback(()=>{for(const S of C.current)window.clearTimeout(S);C.current=[]},[]),P=d.useCallback(()=>{var R;v(),T("sync",{immediate:!0,force:!0});const S=window.setTimeout(()=>{T("sync",{immediate:!0,force:!0})},60);C.current.push(S),typeof document<"u"&&"fonts"in document&&((R=document.fonts)!=null&&R.ready)&&document.fonts.ready.then(()=>{T("sync",{immediate:!0,force:!0})}).catch(()=>{})},[v,T]);d.useEffect(()=>{let S=null;const R=()=>{S!==null&&cancelAnimationFrame(S),S=requestAnimationFrame(()=>{S=null,T("resize")})};return window.addEventListener("resize",R),()=>{window.removeEventListener("resize",R),S!==null&&cancelAnimationFrame(S)}},[T]),d.useEffect(()=>{const S=()=>{var te;const N=b.current,j=A();if(!N||!j)return;if(!Er({currentSize:{cols:Math.max(2,N.cols),rows:Math.max(2,N.rows)},containerSize:j})){(te=N.refresh)==null||te.call(N);return}T("sync",{force:!0})},R=()=>{if(document.visibilityState!=="visible"){z.current=!0;return}z.current&&(z.current=!1,S())},B=()=>{z.current=!0},G=()=>{z.current&&(z.current=!1,S())};return document.addEventListener("visibilitychange",R),window.addEventListener("blur",B),window.addEventListener("focus",G),()=>{document.removeEventListener("visibilitychange",R),window.removeEventListener("blur",B),window.removeEventListener("focus",G)}},[A,T]),d.useEffect(()=>()=>{v(),u.current!==null&&window.clearTimeout(u.current),l.current!==null&&cancelAnimationFrame(l.current)},[v]);const F=d.useCallback(S=>{I.current=S},[]),K=d.useCallback(S=>{b.current=S},[]);return{scheduleResize:T,runPostSelectResize:P,clearPostSelectResizeTimers:v,setFitAddon:F,setTerminal:K,lastReportedSize:a,pendingLocalSize:f,suppressLocalResizeUntil:_}}const Cr={fontFamily:Xt,fontSize:13,scrollback:1e4},rt="tmex:terminal-mode-cache";function vr(n,e){try{const t=sessionStorage.getItem(rt);return t?JSON.parse(t)[`${n}:${e}`]??null:null}catch{return null}}function Mr(n,e,t){try{const s=sessionStorage.getItem(rt),i=s?JSON.parse(s):{},r=`${n}:${e}`;t?i[r]=t:delete i[r],sessionStorage.setItem(rt,JSON.stringify(i))}catch{}}function Dr(){return{mouseX10:!1,mouseNormal:!0,mouseButton:!1,mouseAny:!1,mouseUtf8:!1,mouseSgr:!0,mouseSgrPixels:!1,mouseUrxvt:!1,altScroll:!0,altScreen1047:!1,altScreen1049:!1}}function Ar(n,e){if(!e)return n?{...n,mouseX10:!1,mouseNormal:!1,mouseButton:!1,mouseAny:!1,mouseUtf8:!1,mouseSgrPixels:!1,mouseUrxvt:!1,altScreen1047:!1,altScreen1049:!1}:null;const t=Dr();if(!n)return t;const s=n.mouseNormal||n.mouseButton||n.mouseAny;return{...n,mouseX10:!1,mouseUtf8:!1,mouseSgr:!0,mouseSgrPixels:!1,mouseUrxvt:!1,altScroll:!0,altScreen1047:!1,altScreen1049:!1,mouseNormal:s?n.mouseNormal:t.mouseNormal}}function Or(n){var t;const e=globalThis;e.__tmexE2eXterm=n,e.__tmexE2eTerminal=n,e.__tmexE2eTerminalEngine=Yt,e.__tmexE2eTerminalRenderer=((t=n.getRendererKind)==null?void 0:t.call(n))??null}function kr(n){if(!n)return;const e=globalThis;e.__tmexE2eTerminal!==n&&e.__tmexE2eXterm!==n||(e.__tmexE2eXterm=null,e.__tmexE2eTerminal=null,e.__tmexE2eTerminalEngine=null,e.__tmexE2eTerminalRenderer=null,e.__tmexE2eTerminalSelectionText=null)}const Kt=d.forwardRef(({deviceId:n,paneId:e,theme:t,inputMode:s,deviceConnected:i,isSelectionInvalid:r,onResize:o,onSync:l},u)=>{const[a,f]=d.useState(null),[_,C]=d.useState(!1),I=Z(g=>g.sendInput),{t:b}=Ke(),E=d.useMemo(()=>{switch(t){case"light":return Ot;default:return At}},[t]),z=d.useRef(null),w=d.useRef(null),k=d.useRef(null),A=d.useRef(n),W=d.useRef(e),V=d.useRef(n),T=d.useRef(e),v=d.useRef(i&&!r),P=d.useRef(s),F=d.useRef(E),K=d.useRef(!1),S=d.useRef(!1),R=d.useRef(null),B=d.useRef(!1),G=d.useCallback((g,x,M)=>{!(g!=null&&g.exportModeSnapshot)||!x||!M||Mr(x,M,g.exportModeSnapshot())},[]),N=d.useCallback(()=>a,[a]);Tr(z,N),d.useEffect(()=>{A.current=n,W.current=e,S.current=!1},[n,e]),d.useEffect(()=>{v.current=i&&!r},[i,r]),d.useEffect(()=>{P.current=s},[s]),d.useEffect(()=>{F.current=E},[E]);const j=d.useCallback(g=>{if(!g||s!=="direct"||!v.current)return;const x=A.current,M=W.current;!x||!M||I(x,M,g,!1)},[s,I]),{pendingLocalSize:J,scheduleResize:te,runPostSelectResize:se,setFitAddon:O,setTerminal:ie}=Rr({deviceId:n,paneId:e,deviceConnected:i,isSelectionInvalid:r,onResize:o,onSync:l,getContainerRect:()=>{const g=z.current;if(!g)return null;const x=g.getBoundingClientRect();return{width:x.width,height:x.height}}});d.useEffect(()=>{let g=!1,x=null;return mr({...Cr,theme:F.current,disableStdin:P.current==="editor"}).then(M=>{if(g){M.dispose();return}x=M,w.current&&M.open(w.current),Or(M),f(M)}),()=>{g=!0,f(null),kr(x),x==null||x.dispose()}},[]),d.useEffect(()=>{!a||!("setTheme"in a)||a.setTheme(E)},[a,E]),d.useEffect(()=>{!a||!("setDisableStdin"in a)||a.setDisableStdin(s==="editor")},[a,s]),d.useEffect(()=>{!a||s!=="direct"||window.innerWidth<768||"ontouchstart"in window||a.focus()},[a,s]);const U=d.useMemo(()=>a?{onResetTerminal:g=>{A.current===g&&(G(a,V.current,T.current),B.current=!0,a.reset(),K.current=!1,se())},onApplyHistory:(g,x,M)=>{var Q;if(A.current!==g)return;const q=Ar(vr(A.current,W.current),M);q&&((Q=a.restoreModeSnapshot)==null||Q.call(a,q));const X=M?yr(x):Vt(x);S.current=!0,a.write(X),B.current=!1,V.current=A.current,T.current=W.current,G(a,A.current,W.current)},onFlushBuffer:(g,x)=>{if(A.current===g){for(const M of x){const q=Mt(M,K.current);K.current=q.endedWithCR,a.write(q.normalized)}S.current&&(a.buffer.active.baseY<=1&&a.scrollToTop(),S.current=!1),V.current=A.current,T.current=W.current,G(a,A.current,W.current)}},onOutput:(g,x,M)=>{if(A.current!==g||W.current!==x)return;const q=Mt(M,K.current);K.current=q.endedWithCR,a.write(q.normalized),S.current&&(a.buffer.active.baseY<=1&&a.scrollToTop(),S.current=!1),V.current=A.current,T.current=W.current,G(a,A.current,W.current)}}:{},[a,G,se]);d.useEffect(()=>{a?R.current!==a&&(K.current=!1,V.current=A.current,T.current=W.current,R.current=a):R.current=null},[a]),d.useEffect(()=>{if(!(!a||!n||!e))return()=>{if(B.current){B.current=!1;return}G(a,V.current,T.current)}},[n,a,e,G]),d.useEffect(()=>{dt(U)},[U]),d.useEffect(()=>()=>{dt({})},[]),d.useEffect(()=>{if(!a){k.current=null,O(null),ie(null);return}const g=new fr;return a.loadAddon(g),k.current=g,O(g),ie(a),se(),()=>{try{g.dispose()}finally{k.current=null,O(null),ie(null)}}},[a,se,O,ie]),d.useEffect(()=>{const g=z.current;if(!g)return;let x=null;const M=new ResizeObserver(()=>{x!==null&&cancelAnimationFrame(x),x=requestAnimationFrame(()=>{x=null,te("resize")})});return M.observe(g),()=>{M.disconnect(),x!==null&&cancelAnimationFrame(x)}},[te]),d.useEffect(()=>{if(!a||!n||!e)return;const g=a.onData(x=>{!i||r||j(x)});return a.attachCustomKeyEventHandler(x=>!i||r||x.type!=="keydown"||s!=="direct"?!0:x.shiftKey&&x.key==="Enter"?(x.preventDefault(),j("\x1B[13;2u"),!1):!0),()=>{g.dispose(),a.attachCustomKeyEventHandler(()=>!0)}},[a,i,r,s,j,n,e]),d.useEffect(()=>{if(!(a!=null&&a.onSelectionChange)){C(!1);return}const g=a.onSelectionChange(x=>{C(!!x)});return()=>{g.dispose(),C(!1)}},[a]);const Y=d.useCallback(()=>{var x;if(!a)return;const g=((x=a.getSelection)==null?void 0:x.call(a))??"";g&&Gt(g).then(()=>{_e.success(b("terminal.copied"))}).catch(()=>{_e.error(b("terminal.copyFailed"))}).finally(()=>{var M;(M=a.clearSelection)==null||M.call(a),a.focus()})},[a,b]),L=d.useCallback(()=>{var x;if(!a)return;((x=navigator.clipboard)!=null&&x.readText?navigator.clipboard.readText():Promise.reject(new Error("clipboard unavailable"))).then(M=>{var q;M&&a.paste(M),(q=a.clearSelection)==null||q.call(a),a.focus()}).catch(()=>{_e.error(b("terminal.pasteFailed"))})},[a,b]),$=d.useCallback(()=>{var g;(g=a==null?void 0:a.clearSelection)==null||g.call(a),a==null||a.focus()},[a]);return d.useImperativeHandle(u,()=>({write:g=>a==null?void 0:a.write(g),reset:()=>{a==null||a.reset(),K.current=!1},scrollToBottom:()=>a==null?void 0:a.scrollToBottom(),resize:(g,x)=>a==null?void 0:a.resize(g,x),getTerminal:()=>a??null,getSize:()=>a?{cols:Math.max(2,a.cols),rows:Math.max(2,a.rows)}:null,runPostSelectResize:()=>se(),scheduleResize:(g,x)=>te(g,x),calculateSizeFromContainer:()=>{var Me,De,oe,we,de,le,ee,ye,ue,ge,Te,Ae,Oe,ke,He,be;const g=z.current,x=a,M=k.current;if(!g||!x)return null;const q=g.getBoundingClientRect();if(q.width===0||q.height===0)return null;const X=x._core;let Q;if(M)try{const c=M.proposeDimensions();if(c)Q=Math.max(2,c.cols);else{const p=((we=(oe=(De=(Me=X==null?void 0:X._renderService)==null?void 0:Me.dimensions)==null?void 0:De.css)==null?void 0:oe.cell)==null?void 0:we.width)??9;Q=Math.max(2,Math.floor(q.width/p))}}catch{const c=((ye=(ee=(le=(de=X==null?void 0:X._renderService)==null?void 0:de.dimensions)==null?void 0:le.css)==null?void 0:ee.cell)==null?void 0:ye.width)??9;Q=Math.max(2,Math.floor(q.width/c))}else{const c=((Ae=(Te=(ge=(ue=X==null?void 0:X._renderService)==null?void 0:ue.dimensions)==null?void 0:ge.css)==null?void 0:Te.cell)==null?void 0:Ae.width)??9;Q=Math.max(2,Math.floor(q.width/c))}const ve=((be=(He=(ke=(Oe=X==null?void 0:X._renderService)==null?void 0:Oe.dimensions)==null?void 0:ke.css)==null?void 0:He.cell)==null?void 0:be.height)??17,me=Math.max(2,Math.floor(q.height/ve));return{cols:Q,rows:me}},getPendingLocalSize:()=>J.current}),[a,J,se,te]),h.jsxs("div",{ref:z,className:"h-full w-full relative",style:{backgroundColor:E.background},"data-terminal-engine":Yt,children:[h.jsx("div",{ref:w,className:"absolute inset-0"}),h.jsx(pr,{visible:_,canPaste:s==="direct"&&i&&!r,onCopy:Y,onPaste:L,onDismiss:$})]})});Kt.displayName="Terminal";const Hr=1200,Ir=2e3;function fe(n,e){return!n||!e?!1:n.windowId===e.windowId&&n.paneId===e.paneId}function Wt(n,e){const t=n.filter(s=>e-s.at<Hr);return t.length===0?null:t.reduce((s,i)=>i.at>s.at?i:s)}function Ce(n,e=Date.now()){return!n||e-n.at>Ir?null:n}function Nr(n){const e=n.now??Date.now(),t=Wt(n.recentSelectRequests,e);if(t&&!fe(t,n.activePaneFromEvent)||fe(n.currentRoute,n.activePaneFromEvent)||fe(n.lastHandledActive,n.activePaneFromEvent))return!0;const s=Ce(n.pendingUserSelection,e);return!!(s&&!fe(s,n.activePaneFromEvent))}function Pr(n){const e=n.now??Date.now(),t=Wt(n.recentSelectRequests,e),s=Ce(n.pendingUserSelection,e);return!!(s&&!fe(s,n.snapshotActive)||t&&!fe(t,n.snapshotActive))}function Br(n){const e=n.now??Date.now(),t=Ce(n.pendingUserSelection,e);return!(t&&fe(t,n.routeTarget)||n.snapshotActive&&fe(n.snapshotActive,n.routeTarget))}const Lr=[{key:"enter",label:"ENTER",payload:"\r"},{key:"ctrl-c",label:"CTRL-C",payload:""},{key:"ctrl-d",label:"CTRL-D",payload:""},{key:"up",label:"↑",payload:"\x1B[A"},{key:"down",label:"↓",payload:"\x1B[B"},{key:"left",label:"←",payload:"\x1B[D"},{key:"right",label:"→",payload:"\x1B[C"},{key:"shift-enter",label:"SHIFT+ENTER",payload:"\x1B[13;2u"},{key:"tab",label:"TAB",payload:" "},{key:"backspace",label:"BACKSPACE",payload:"\b"},{key:"esc",label:"ESC",payload:"\x1B"},{key:"delete",label:"DELETE",payload:""},{key:":",label:":",payload:":"},{key:"/",label:"/",payload:"/"},{key:"'",label:"'",payload:"'"},{key:'"',label:'"',payload:'"'},{key:"`",label:"`",payload:"`"}],Dt=d.memo(function({onSend:e,onFocusEditor:t,disabled:s,isMobile:i,inputMode:r}){return h.jsx("div",{className:"terminal-shortcuts-strip my-2 bg-muted rounded-xl","data-testid":"terminal-shortcuts-strip",children:h.jsx("div",{className:"shortcut-row flex items-center gap-1.5 p-2 overflow-x-auto scrollbar-thin","data-testid":"editor-shortcuts-row",children:Lr.map(o=>h.jsx(he,{variant:"secondary",size:"sm",className:"h-7 min-w-9 px-2.5 rounded-full text-[11px] font-medium tracking-wide shrink-0 [@media(any-pointer:coarse)]:h-9 [@media(any-pointer:coarse)]:min-w-10 [@media(any-pointer:coarse)]:px-3",title:o.label,"aria-label":o.label,"data-testid":`editor-shortcut-${o.key}`,onMouseDown:l=>l.preventDefault(),onClick:()=>{e(o.payload),i&&r==="editor"&&(t==null||t())},disabled:s,children:o.label},o.key))})})});function Vr(){var be;const{t:n}=Ke(),{deviceId:e,windowId:t,paneId:s}=it(),i=Qt(),r=d.useRef(null),o=d.useRef(null),l=d.useRef(null),u=d.useRef(null),a=d.useRef(!1),f=d.useRef(!1),_=d.useRef(null),C=Z(c=>c.selectPane),I=Z(c=>e?c.snapshots[e]:void 0),b=Z(c=>{var p;return e?(p=c.deviceErrors)==null?void 0:p[e]:void 0}),E=Z(c=>{var p;return e?((p=c.deviceConnected)==null?void 0:p[e])??!1:!1}),z=kt(c=>{var p;return((p=c.settings)==null?void 0:p.siteName)??"tmex"}),w=d.useMemo(()=>ot(s),[s]),k=d.useMemo(()=>e&&w?`${e}:${w}`:null,[e,w]),[A,W]=d.useState(!1),[V,T]=d.useState(""),v=d.useRef(!1),P=!E||!w,[F,K]=d.useState(!1),S=ae(c=>c.inputMode),R=ae(c=>c.theme),B=ae(c=>c.editorSendWithEnter),G=ae(c=>c.setEditorSendWithEnter),N=ae(c=>c.addEditorHistory),j=ae(c=>c.setEditorDraft),J=ae(c=>c.removeEditorDraft),te=ae(c=>k?c.editorDrafts[k]??"":""),se=d.useMemo(()=>Jt(),[]),O=(be=I==null?void 0:I.session)==null?void 0:be.windows,ie=R==="light"?Ot:At,{data:U}=Ht({queryKey:["devices"],queryFn:async()=>{const c=await fetch("/api/devices");if(!c.ok)throw new Error("Failed to fetch devices");return c.json()},throwOnError:!1}),Y=d.useMemo(()=>{if(e)return U==null?void 0:U.devices.find(c=>c.id===e)},[e,U==null?void 0:U.devices]),L=d.useMemo(()=>{if(!(!t||!O))return O.find(c=>c.id===t)},[t,O]),$=d.useMemo(()=>{if(!(!w||!L))return L.panes.find(c=>c.id===w)},[w,L]),g=!!O,X=!!(g&&!!t&&!L||g&&!!t&&!!w&&!!L&&!$?n("wsError.checkGateway"):null),Q=!!(E&&w&&!X),ve=d.useMemo(()=>{if(!L||!$)return null;const c=(Y==null?void 0:Y.name)??e;return It({paneIdx:$.index,windowIdx:L.index,paneTitle:$.title,windowName:L.name,windowCustomName:L.customName,deviceName:c})},[Y==null?void 0:Y.name,e,$,L]),me=d.useMemo(()=>{if(!O||O.length===0)return null;const c=O.find(y=>y.active),p=c==null?void 0:c.panes.find(y=>y.active);return!c||!p?null:{windowId:c.id,paneId:p.id}},[O]),Me=d.useCallback((c,p)=>{!e||!w||Z.getState().resizePane(e,w,c,p)},[e,w]),De=d.useCallback((c,p)=>{!e||!w||Z.getState().syncPaneSize(e,w,c,p)},[e,w]),oe=d.useCallback((c,p)=>{const y=u.current,D=(y==null?void 0:y.calculateSizeFromContainer())??(y==null?void 0:y.getSize())??void 0;if(D)return D;if(!c||!p||!O)return;const ne=O.find(pe=>pe.id===c),re=ne==null?void 0:ne.panes.find(pe=>pe.id===p);if(!(!re||re.width<=1||re.height<=1))return{cols:re.width,rows:re.height}},[O]);d.useEffect(()=>{const c=()=>{W(window.innerWidth<768||"ontouchstart"in window)};return c(),window.addEventListener("resize",c),()=>window.removeEventListener("resize",c)},[]),d.useEffect(()=>{if(!A||!se||f.current)return;f.current=!0;const c=()=>{window.scrollTo(0,1)},p=window.requestAnimationFrame(c),y=window.setTimeout(c,120),D=window.setTimeout(c,420);return()=>{window.cancelAnimationFrame(p),window.clearTimeout(y),window.clearTimeout(D)}},[se,A]),d.useEffect(()=>{e&&(a.current=!1,ye.current=null,ue.current=null,_.current=null,de.current=[])},[e]),d.useEffect(()=>{E||(a.current=!1)},[E]),d.useEffect(()=>{if(!e||!E||!t||!O)return;if(O.length===0){i("/devices",{replace:!0});return}const c=O.find(y=>y.id===t);if(!c)return;if(!w){const y=c.panes.find(D=>D.active)??c.panes[0];y&&i(`/devices/${e}/windows/${t}/panes/${Se(y.id)}`,{replace:!0});return}if(!c.panes.find(y=>y.id===w)){const y=c.panes.find(D=>D.active)??c.panes[0];y&&i(`/devices/${e}/windows/${t}/panes/${Se(y.id)}`,{replace:!0});return}},[e,E,O,t,w,i]),d.useEffect(()=>{if(!e||!E||!O||O.length===0||t&&w||a.current)return;const c=O.find(y=>y.active)??O[0],p=c.panes.find(y=>y.active)??c.panes[0];p&&(a.current=!0,i(`/devices/${e}/windows/${c.id}/panes/${Se(p.id)}`,{replace:!0}))},[E,e,i,w,t,O]);const we=d.useRef(null);d.useEffect(()=>{we.current=null},[e,w]),d.useEffect(()=>{if(!e||!t||!w||P||!E)return;const c=`${e}:${t}:${w}`;if(we.current===c)return;we.current=c;const p=oe(t,w);le(t,w),C(e,t,w,p)},[E,e,oe,P,w,C,t]),d.useEffect(()=>{if(!e||!E||!t||!w)return;const c={windowId:t,paneId:w};Br({routeTarget:c,snapshotActive:me,pendingUserSelection:_.current})&&(_.current={windowId:c.windowId,paneId:c.paneId,at:Date.now()})},[E,e,w,me,t]);const de=d.useRef([]),le=d.useCallback((c,p)=>{const y=Date.now(),D=[...de.current.filter(ne=>y-ne.at<2e3),{windowId:c,paneId:p,at:y}];de.current=D.slice(-8)},[]),ee=Z(c=>e?c.activePaneFromEvent[e]:void 0),ye=d.useRef(null);d.useEffect(()=>{if(!e||!E||!t||!w||!ee)return;const c=Date.now(),p=Ce(_.current,c);if(_.current=p,Nr({now:c,pendingUserSelection:p,activePaneFromEvent:ee,currentRoute:{windowId:t,paneId:w},recentSelectRequests:de.current,lastHandledActive:ye.current}))return;ye.current={...ee},p&&p.windowId===ee.windowId&&p.paneId===ee.paneId&&(_.current=null);const y=oe(ee.windowId,ee.paneId);le(ee.windowId,ee.paneId),C(e,ee.windowId,ee.paneId,y),i(`/devices/${e}/windows/${ee.windowId}/panes/${Se(ee.paneId)}`,{replace:!0})},[e,E,t,w,ee,le,oe,C,i]);const ue=d.useRef(null);d.useEffect(()=>{if(!e||!E||!O||O.length===0)return;const c=de.current,p=O.find($e=>$e.active);if(!p)return;const y=p.panes.find($e=>$e.active);if(!y)return;const D={windowId:p.id,paneId:y.id},ne=Date.now(),re=Ce(_.current,ne);if(_.current=re,Pr({now:ne,pendingUserSelection:re,snapshotActive:D,recentSelectRequests:c})||ue.current&&ue.current.windowId===D.windowId&&ue.current.paneId===D.paneId||(ue.current={...D},re&&re.windowId===D.windowId&&re.paneId===D.paneId&&(_.current=null),t===D.windowId&&w===D.paneId))return;const pe=oe(D.windowId,D.paneId);le(D.windowId,D.paneId),C(e,D.windowId,D.paneId,pe),i(`/devices/${e}/windows/${D.windowId}/panes/${Se(D.paneId)}`,{replace:!0})},[e,E,O,t,w,le,oe,C,i]);const ge=Z(c=>e?c.pendingCreateWindowAt[e]:void 0);d.useEffect(()=>{if(!e||!E||!ge)return;const c=5e3,p=Date.now()-ge;if(p>c){Z.getState().clearPendingCreateWindow(e);return}if(!me){const ne=window.setTimeout(()=>{Z.getState().clearPendingCreateWindow(e)},c-p);return()=>window.clearTimeout(ne)}const y=me;if(t===y.windowId&&w===y.paneId){const ne=window.setTimeout(()=>{Z.getState().clearPendingCreateWindow(e)},c-p);return()=>window.clearTimeout(ne)}_.current={windowId:y.windowId,paneId:y.paneId,at:Date.now()};const D=oe(y.windowId,y.paneId);le(y.windowId,y.paneId),C(e,y.windowId,y.paneId,D),i(`/devices/${e}/windows/${y.windowId}/panes/${Se(y.paneId)}`,{replace:!0}),Z.getState().clearPendingCreateWindow(e)},[e,E,ge,me,t,w,le,oe,C,i]),d.useEffect(()=>{if(!Q||!$||P)return;const c=u.current,p=c==null?void 0:c.getTerminal();if(!p)return;const y=Math.max(2,Math.floor($.width||0)),D=Math.max(2,Math.floor($.height||0));if(!y||!D)return;const ne=Date.now(),re={cols:y,rows:D},pe=(c==null?void 0:c.getPendingLocalSize())??null;br({now:ne,remoteSize:re,pendingLocalSize:pe})&&(p.cols===y&&p.rows===D||p.resize(y,D))},[Q,P,$]),d.useEffect(()=>{const c=window.requestAnimationFrame(()=>{var y;(y=u.current)==null||y.scrollToBottom()}),p=window.setTimeout(()=>{var y;(y=u.current)==null||y.scrollToBottom()},120);return()=>{window.cancelAnimationFrame(c),window.clearTimeout(p)}},[S]),d.useEffect(()=>{b!=null&&b.message&&_e.error(b.message)},[b==null?void 0:b.message]),d.useEffect(()=>(document.title=Zt(ve),()=>{document.title=z}),[z,ve]),d.useEffect(()=>{const c=()=>{var p;(p=u.current)==null||p.scrollToBottom()};return window.addEventListener("tmex:jump-to-latest",c),()=>{window.removeEventListener("tmex:jump-to-latest",c)}},[]),d.useEffect(()=>{const c=p=>{const{deviceId:y,windowId:D,paneId:ne}=p.detail;y===e&&(_.current={windowId:D,paneId:ne,at:Date.now()})};return window.addEventListener("tmex:user-initiated-selection",c),()=>{window.removeEventListener("tmex:user-initiated-selection",c)}},[e]),d.useEffect(()=>{T(te)},[te]);const Te=d.useCallback(c=>{if(!e||!w||!Q)return;Z.getState().sendInput(e,w,c,!1)},[Q,e,w]),Ae=d.useCallback(()=>{if(!Q){_e.error(n("wsError.checkGateway"));return}if(!e||!w||!V.trim())return;K(!0),window.setTimeout(()=>K(!1),150);const c=B?`${V}\r`:V;Z.getState().sendInput(e,w,c,!1),N(V),k&&J(k),T("")},[N,Q,e,k,B,V,J,w,n]),Oe=d.useCallback(()=>{if(!Q){_e.error(n("wsError.checkGateway"));return}if(!e||!w||!V.trim())return;K(!0),window.setTimeout(()=>K(!1),150);const c=V.split(/\r?\n/),p=Z.getState();for(const y of c)y.trim()&&p.sendInput(e,w,`${y}\r`,!1);N(V),k&&J(k),T("")},[N,Q,e,k,V,J,w,n]),ke=d.useCallback(()=>{var c;(c=l.current)==null||c.focus({preventScroll:!0})},[]);if(!e)return h.jsx("div",{className:"flex h-full items-center justify-center p-4",children:h.jsx("div",{className:"rounded-lg border border-dashed border-border px-4 py-3 text-sm text-muted-foreground",children:n("device.noDevices")})});const He=!E&&!b;return h.jsxs("div",{className:"flex h-full min-h-0 flex-col bg-background","data-testid":"device-page",children:[h.jsxs("div",{className:`flex-1 relative overflow-hidden min-h-0 min-w-0 ${A&&S==="editor"?"pb-1":""}`,children:[h.jsx("div",{className:"h-full px-3 py-1 min-h-0 min-w-0 w-full relative flex rounded-xl",style:{backgroundColor:ie.background},children:E&&w?h.jsx("div",{ref:r,className:"flex-1 h-full min-h-0 w-full","data-virtual-keyboard-avoid":!0,children:h.jsx(Kt,{ref:u,deviceId:e,paneId:w,theme:R,inputMode:S,deviceConnected:E,isSelectionInvalid:X,onResize:Me,onSync:De},`${e}:${w}`)}):h.jsx("div",{className:"absolute inset-0 flex flex-col items-center justify-center p-8 text-center",children:h.jsx("div",{className:"max-w-sm space-y-4",children:E?t?h.jsxs(h.Fragment,{children:[h.jsx("div",{className:"h-12 w-12 rounded-full bg-muted flex items-center justify-center mx-auto",children:h.jsx(je,{className:"h-6 w-6 text-muted-foreground animate-spin"})}),h.jsx("h3",{className:"text-lg font-medium",children:n("terminal.connecting")})]}):h.jsxs(h.Fragment,{children:[h.jsx("div",{className:"h-12 w-12 rounded-full bg-muted flex items-center justify-center mx-auto",children:h.jsx("span",{className:"text-2xl text-muted-foreground",children:"📋"})}),h.jsx("h3",{className:"text-lg font-medium",children:n("window.noWindowSelected")}),h.jsx("p",{className:"text-sm text-muted-foreground",children:n("window.selectWindowToStart")})]}):h.jsxs(h.Fragment,{children:[h.jsx("div",{className:"h-12 w-12 rounded-full bg-muted flex items-center justify-center mx-auto",children:h.jsx("span",{className:"text-2xl text-muted-foreground",children:"🔌"})}),h.jsx("h3",{className:"text-lg font-medium",children:n("device.disconnected")}),h.jsx("p",{className:"text-sm text-muted-foreground",children:n("device.connectToStart")})]})})})}),He&&h.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background/85 backdrop-blur-sm","data-testid":"terminal-status-overlay",children:h.jsxs("div",{className:"flex flex-col items-center gap-2 rounded-lg border border-border bg-card/90 px-4 py-3 shadow-sm",children:[h.jsx("div",{className:"h-7 w-7 rounded-full border-2 border-primary border-t-transparent animate-spin"}),h.jsx("span",{className:"text-xs text-muted-foreground","data-testid":"terminal-status-text",children:n("terminal.connecting")})]})})]}),S==="direct"&&h.jsx("div",{className:"",children:h.jsx(Dt,{onSend:Te,disabled:!Q,isMobile:A,inputMode:S})}),S==="editor"&&h.jsxs("div",{ref:o,"data-virtual-keyboard-avoid":!0,className:"editor-mode-input bg-card/85 backdrop-blur-sm",children:[A&&h.jsx(Dt,{onSend:Te,onFocusEditor:ke,disabled:!Q,isMobile:A,inputMode:S}),h.jsx("textarea",{ref:l,"data-testid":"editor-input",className:"min-h-[88px] max-h-[28vh] w-full resize-y rounded-lg border border-border bg-background px-3 py-2 text-sm text-foreground shadow-xs outline-none transition-colors focus:border-ring",value:V,onChange:c=>{const p=c.target.value;if(T(p),!!k){if(p){j(k,p);return}J(k)}},placeholder:n("terminal.inputPlaceholder"),onCompositionStart:()=>{v.current=!0},onCompositionEnd:()=>{v.current=!1}}),h.jsx("div",{className:"actions mt-2",children:h.jsxs("div",{className:"send-row flex flex-wrap items-center justify-end gap-2","data-testid":"editor-send-row",children:[h.jsxs("div",{className:"send-with-enter-toggle mr-auto flex items-center gap-2 text-xs text-muted-foreground","data-testid":"editor-send-with-enter-toggle",children:[h.jsx(en,{size:"sm",checked:B,onCheckedChange:c=>G(!!c)}),h.jsx("span",{children:n("terminal.editorSendWithEnter")})]}),h.jsxs(he,{variant:"outline",size:"sm","data-testid":"editor-clear",onMouseDown:c=>c.preventDefault(),onClick:()=>{var c;T(""),k&&J(k),A&&S==="editor"&&((c=l.current)==null||c.focus({preventScroll:!0}))},title:n("terminal.clear"),children:[h.jsx(tn,{className:"h-4 w-4"}),n("terminal.clear")]}),h.jsxs(he,{variant:"secondary",size:"sm","data-testid":"editor-send-line-by-line",onMouseDown:c=>c.preventDefault(),onClick:()=>{var c;Oe(),A&&S==="editor"&&((c=l.current)==null||c.focus({preventScroll:!0}))},disabled:!Q||F,children:[F?h.jsx(je,{className:"h-4 w-4 animate-spin"}):h.jsx(ut,{className:"h-4 w-4"}),n("terminal.editorSendLineByLine")]}),h.jsxs(he,{variant:"default",size:"sm","data-testid":"editor-send",onMouseDown:c=>c.preventDefault(),onClick:()=>{var c;Ae(),A&&S==="editor"&&((c=l.current)==null||c.focus({preventScroll:!0}))},disabled:!Q||F,children:[F?h.jsx(je,{className:"h-4 w-4 animate-spin"}):h.jsx(ut,{className:"h-4 w-4"}),n("common.send")]})]})})]})]})}function Kr(){const{deviceId:n,windowId:e,paneId:t}=it(),s=t?ot(t):void 0,i=Z(f=>f.snapshots),r=kt(f=>{var _;return((_=f.settings)==null?void 0:_.siteName)??"tmex"}),o=n?i[n]:void 0,l=d.useMemo(()=>{var f;if(!(!e||!((f=o==null?void 0:o.session)!=null&&f.windows)))return o.session.windows.find(_=>_.id===e)},[e,o]),u=d.useMemo(()=>{if(!(!s||!l))return l.panes.find(f=>f.id===s)},[s,l]),a=d.useMemo(()=>l&&u?It({paneIdx:u.index,windowIdx:l.index,paneTitle:u.title,windowName:l.name,windowCustomName:l.customName,deviceName:r}):n??"",[l,u,r,n]);return h.jsx(h.Fragment,{children:a})}function Wr(){const{t:n}=Ke(),{deviceId:e,paneId:t}=it(),s=t?ot(t):void 0,i=ae(k=>k.inputMode),r=ae(k=>k.setInputMode),o=Z(k=>{var A;return e?((A=k.deviceConnected)==null?void 0:A[e])??!1:!1}),[l,u]=d.useState(!1),[a,f]=d.useState(!1),_=!!(s&&o),I=(Ht({queryKey:sn(e??"",s??""),queryFn:()=>nn(e??"",s??""),enabled:!!(e&&s),throwOnError:!1}).data??[]).some(k=>k.enabled),b=()=>{r(i==="direct"?"editor":"direct")},E=()=>{window.dispatchEvent(new CustomEvent("tmex:jump-to-latest"))},z=()=>{u(!0)},w=()=>{window.location.reload()};return h.jsxs(h.Fragment,{children:[h.jsx(he,{variant:"ghost",size:"icon-sm",onClick:z,"aria-label":n("nav.refreshPage"),title:n("nav.refreshPage"),children:h.jsx(pn,{className:"h-4 w-4"})}),h.jsx(he,{variant:"ghost",size:"icon-sm",onClick:b,disabled:!_,"data-testid":"terminal-input-mode-toggle","aria-label":n(i==="direct"?"nav.switchToEditor":"nav.switchToDirect"),title:n(i==="direct"?"nav.switchToEditor":"nav.switchToDirect"),children:i==="direct"?h.jsx(wn,{className:"h-4 w-4"}):h.jsx(En,{className:"h-4 w-4"})}),h.jsx(he,{variant:"ghost",size:"icon-sm",onClick:E,disabled:!_,"aria-label":n("nav.jumpToLatest"),title:n("nav.jumpToLatest"),children:h.jsx(gn,{className:"h-4 w-4"})}),h.jsxs(he,{variant:"ghost",size:"icon-sm",className:"relative",onClick:()=>f(!0),disabled:!s,"data-testid":"watch-open-button","aria-label":n("watch.title"),title:n("watch.title"),children:[h.jsx(rn,{className:"h-4 w-4"}),I&&h.jsx("span",{className:"absolute right-1 top-1 h-1.5 w-1.5 rounded-full bg-primary","data-testid":"watch-active-indicator"})]}),e&&s&&h.jsx(on,{open:a,onOpenChange:f,deviceId:e,paneId:s}),h.jsx(ln,{open:l,onOpenChange:u,children:h.jsxs(an,{children:[h.jsxs(cn,{children:[h.jsx(dn,{children:n("nav.refreshPage")}),h.jsx(un,{children:n("nav.refreshPageConfirm")})]}),h.jsxs(hn,{children:[h.jsx(fn,{onClick:()=>u(!1),children:n("common.cancel")}),h.jsx(mn,{onClick:w,children:n("common.confirm")})]})]})})]})}export{Wr as PageActions,Kr as PageTitle,Vr as default};
26
+ //# sourceMappingURL=DevicePage-BEEZURRu.js.map
@@ -0,0 +1,12 @@
1
+ import{c as U,y as N,w as j,ah as G,ab as se,aa as ae,ai as M,v as e,M as Z,G as w,U as W,a0 as te,a1 as ie,a2 as ne,as as re,T as Y,a3 as ce,a4 as oe,a5 as de,a6 as le,a7 as he,H as me,t as v,J as pe,N as ue,O as xe,P as I,Q as ve,R as ye,I as O,at as je,ac as fe,au as ge,av as we,V as Ne,W as De,Y as Ce,Z as be,aw as Se,_ as x,aj as z,ak as Q,al as B,am as _,an as f,af as Ee,$ as Me}from"./index-BhWcb9L_.js";import{C as S,c as E,a as Pe,b as ke,d as Ke}from"./card-BHK15lCp.js";/**
2
+ * @license lucide-react v0.564.0 - ISC
3
+ *
4
+ * This source code is licensed under the ISC license.
5
+ * See the LICENSE file in the root directory of this source tree.
6
+ */const Ie=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]],$e=U("ellipsis",Ie);/**
7
+ * @license lucide-react v0.564.0 - ISC
8
+ *
9
+ * This source code is licensed under the ISC license.
10
+ * See the LICENSE file in the root directory of this source tree.
11
+ */const Ae=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]],Te=U("zap",Ae);function p(s){const c=s.trim();return c||void 0}function Fe(s){return s?{name:s.name,type:s.type,host:s.host??"",port:s.port??22,username:s.username??"",sshConfigRef:s.sshConfigRef??"",session:s.session??"tmex",authMode:s.type==="local"?"auto":s.authMode,password:"",privateKey:"",privateKeyPassphrase:""}:{name:"",type:"local",host:"",port:22,username:"",sshConfigRef:"",session:"tmex",authMode:"auto",password:"",privateKey:"",privateKeyPassphrase:""}}function He(s){if(s.type==="local")return{name:s.name.trim(),type:"local",session:p(s.session)??"tmex",authMode:"auto"};const c={name:s.name.trim(),type:"ssh",host:p(s.host),port:s.port,username:p(s.username),sshConfigRef:p(s.sshConfigRef),session:p(s.session)??"tmex",authMode:s.authMode};return s.authMode==="password"&&(c.password=s.password),s.authMode==="key"&&(c.privateKey=s.privateKey,c.privateKeyPassphrase=s.privateKeyPassphrase||void 0),c}function Le(s){if(s.type==="local")return{name:s.name.trim(),session:p(s.session)??"tmex",authMode:"auto"};const c={name:s.name.trim(),host:p(s.host),port:s.port,username:p(s.username),sshConfigRef:p(s.sshConfigRef),session:p(s.session)??"tmex",authMode:s.authMode};return s.authMode==="password"&&s.password&&(c.password=s.password),s.authMode==="key"&&s.privateKey&&(c.privateKey=s.privateKey,c.privateKeyPassphrase=s.privateKeyPassphrase||void 0),c}async function V(s,c){try{return(await s.json()).error??c}catch{return c}}function ze(){const{t:s}=N(),[c,h]=j.useState(!1),[a,y]=j.useState(null),[n,o]=j.useState(null),l=G();j.useEffect(()=>{const r=()=>h(!0);return window.addEventListener("tmex:open-add-device",r),()=>window.removeEventListener("tmex:open-add-device",r)},[]);const{data:d,isLoading:u,isError:P}=se({queryKey:["devices"],queryFn:async()=>{const r=await fetch("/api/devices");if(!r.ok)throw new Error(s("device.loadFailed"));return r.json()},throwOnError:!1}),D=ae(r=>r.hydrateDeviceErrors);j.useEffect(()=>{d!=null&&d.devices&&D(d.devices.map(r=>({deviceId:r.id,lastError:r.lastError??null,lastErrorType:r.lastErrorType??null})))},[d,D]);const C=M({mutationFn:async r=>{if(!(await fetch(`/api/devices/${r}`,{method:"DELETE"})).ok)throw new Error(s("device.deleteFailed"))},onSuccess:()=>{l.invalidateQueries({queryKey:["devices"]}),v.success(s("common.success"))},onError:r=>{v.error(r instanceof Error?r.message:s("common.error"))}}),b=(d==null?void 0:d.devices)??[];return e.jsxs("div",{className:"mx-auto flex w-full max-w-6xl flex-col gap-3 p-3 pb-[calc(1rem+env(safe-area-inset-bottom))] sm:gap-4 sm:p-5","data-testid":"devices-page",children:[u?e.jsx(S,{children:e.jsx(E,{className:"py-16 text-center text-sm text-muted-foreground",children:s("common.loading")})}):P?e.jsx(S,{children:e.jsx(E,{className:"py-16 text-center text-sm text-destructive",children:s("device.loadFailed")})}):b.length===0?e.jsx(S,{children:e.jsxs(E,{className:"space-y-4 py-14 text-center",children:[e.jsx("div",{className:"mx-auto flex h-12 w-12 items-center justify-center rounded-xl border border-border bg-muted",children:e.jsx(Z,{className:"h-6 w-6 text-muted-foreground"})}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"text-lg font-medium",children:s("device.noDevices")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:s("device.addDevice")})]}),e.jsxs(w,{variant:"default","data-testid":"devices-add-empty",onClick:()=>h(!0),children:[e.jsx(W,{className:"h-4 w-4"}),s("device.addDevice")]})]})}):e.jsx("div",{className:"grid gap-3 lg:grid-cols-2",children:b.map(r=>e.jsx(Re,{device:r,onEdit:()=>y(r),onDelete:()=>o(r)},r.id))}),c&&e.jsx(J,{mode:"create",onClose:()=>h(!1)}),a&&e.jsx(J,{mode:"edit",device:a,onClose:()=>y(null)}),e.jsx(te,{open:n!==null,onOpenChange:r=>!r&&o(null),children:e.jsxs(ie,{children:[e.jsxs(ne,{children:[e.jsx(re,{className:"bg-destructive/10",children:e.jsx(Y,{className:"h-5 w-5 text-destructive"})}),e.jsx(ce,{children:s("device.deleteConfirm")}),e.jsx(oe,{children:s("device.deleteDescription",{name:(n==null?void 0:n.name)??""})})]}),e.jsxs(de,{children:[e.jsx(le,{children:s("common.cancel")}),e.jsx(he,{variant:"destructive",disabled:!n||C.isPending,onClick:()=>{n&&(C.mutate(n.id),o(null))},children:s("common.delete")})]})]})})]})}function Re({device:s,onEdit:c,onDelete:h}){const{t:a}=N(),y=s.type==="local"?e.jsx(Z,{className:"h-4 w-4"}):e.jsx(me,{className:"h-4 w-4"}),n=s.type==="local"?a("device.typeLocal"):`${s.username??"-"}@${s.host??"-"}:${s.port??22}`,o=M({mutationFn:async()=>{const l=await fetch(`/api/devices/${s.id}/test-connection`,{method:"POST"});let d=null;try{d=await l.json()}catch{d=null}if(!l.ok){const u=d;throw new Error((u==null?void 0:u.error)??a("common.error"))}return d},onSuccess:l=>{v.success(l.message??a("common.success"))},onError:l=>{v.error(l instanceof Error?l.message:a("common.error"))}});return e.jsxs(S,{"data-testid":"device-card","data-device-id":s.id,"data-device-name":s.name,className:"overflow-hidden",children:[e.jsxs(Pe,{className:"space-y-2 pb-2",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2.5",children:[e.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-md border border-border bg-muted text-muted-foreground",children:y}),e.jsxs("div",{className:"min-w-0 space-y-0.5",children:[e.jsx(ke,{className:"line-clamp-1 text-sm",title:s.name,children:s.name}),e.jsx(Ke,{className:"line-clamp-1 text-xs",children:n})]})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1",children:e.jsxs(pe,{children:[e.jsx(ue,{render:e.jsx(w,{variant:"ghost",size:"icon-sm","data-testid":`device-card-actions-${s.id}`,"aria-label":a("common.edit"),title:a("common.edit")}),children:e.jsx($e,{className:"h-4 w-4"})}),e.jsxs(xe,{align:"end",children:[e.jsxs(I,{"data-testid":`device-card-edit-${s.id}`,onClick:c,children:[e.jsx(ve,{className:"h-4 w-4"}),a("common.edit")]}),s.type==="ssh"&&e.jsxs(I,{"data-testid":`device-card-test-${s.id}`,onClick:()=>o.mutate(),disabled:o.isPending,children:[e.jsx(Te,{className:"h-4 w-4"}),a("common.test")]}),e.jsx(ye,{}),e.jsxs(I,{"data-testid":`device-card-delete-${s.id}`,variant:"destructive",onClick:h,children:[e.jsx(Y,{className:"h-4 w-4"}),a("common.delete")]})]})]})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx(O,{variant:"outline",className:"text-[11px] font-normal",children:s.type==="local"?a("device.typeLocal"):a("device.typeSSHBadge")}),s.session&&e.jsx(O,{variant:"outline",className:"text-[11px] font-normal",children:s.session}),e.jsx(je,{deviceId:s.id})]})]}),e.jsxs(E,{className:"pt-0",children:[e.jsx(fe,{className:"mb-2"}),e.jsx("div",{className:"flex items-center justify-end",children:e.jsx(ge,{to:`/devices/${s.id}`,"data-testid":`device-card-connect-${s.id}`,className:we({variant:"default",size:"sm"}),children:a("device.connect")})})]})]})}function J({mode:s,device:c,onClose:h}){const{t:a}=N(),y=G(),[n,o]=j.useState(Fe(c)),[l,d]=j.useState(!1),u=s==="edit",P=n.type==="ssh",D=M({mutationFn:async t=>{const i=await fetch("/api/devices",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!i.ok)throw new Error(await V(i,a("device.createFailed")));return i.json()},onSuccess:()=>{y.invalidateQueries({queryKey:["devices"]}),v.success(a("common.success")),h()},onError:t=>{v.error(t instanceof Error?t.message:a("common.error"))}}),C=M({mutationFn:async t=>{if(!c)throw new Error(a("apiError.deviceNotFound"));const i=await fetch(`/api/devices/${c.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!i.ok)throw new Error(await V(i,a("device.updateFailed")));return i.json()},onSuccess:()=>{y.invalidateQueries({queryKey:["devices"]}),v.success(a("common.success")),h()},onError:t=>{v.error(t instanceof Error?t.message:a("common.error"))}}),b=async t=>{t.preventDefault(),d(!0);try{s==="create"?await D.mutateAsync(He(n)):await C.mutateAsync(Le(n))}catch{}finally{d(!1)}},r=`${s}-device-name`,k=`${s}-device-type`,$=`${s}-device-host`,A=`${s}-device-port`,T=`${s}-device-username`,F=`${s}-device-session`,H=`${s}-device-auth-mode`,L=`${s}-device-password`,R=`${s}-device-private-key`,q=`${s}-device-private-key-passphrase`,X={local:a("device.typeLocal"),ssh:a("device.typeSSH")},ee={password:a("device.authPassword"),key:a("device.authKey"),agent:a("device.authAgent"),configRef:"SSH Config"},K=t=>e.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:t}),m=(t,i,g)=>e.jsxs("label",{className:"block text-xs font-medium text-foreground",htmlFor:t,children:[i,g&&e.jsx("span",{className:"ml-0.5 text-destructive",children:"*"})]});return e.jsx(Ne,{open:!0,onOpenChange:t=>!t&&h(),children:e.jsxs(De,{"data-testid":"device-dialog",className:"w-full max-w-2xl",children:[e.jsxs(Ce,{children:[e.jsx(be,{children:a(u?"device.editDevice":"device.addDevice")}),e.jsx(Se,{children:a(u?"device.editDeviceDescription":"device.addDeviceDescription")})]}),e.jsxs("form",{onSubmit:b,className:"space-y-4",children:[e.jsxs("div",{className:"-mr-2 max-h-[min(70vh,720px)] space-y-5 overflow-y-auto pr-2",children:[e.jsxs("section",{className:"space-y-2.5",children:[K(a("device.sectionBasic")),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5 sm:col-span-2",children:[m(r,a("device.name"),!0),e.jsx(x,{id:r,"data-testid":"device-name-input",type:"text",value:n.name,onChange:t=>o(i=>({...i,name:t.target.value})),placeholder:a("device.namePlaceholder"),required:!0})]}),e.jsxs("div",{className:"space-y-1.5",children:[m(k,a("device.type")),e.jsxs(z,{value:n.type,onValueChange:t=>{if(!t)return;const i=t;o(g=>({...g,type:i,authMode:i==="local"?"auto":g.authMode==="auto"?"password":g.authMode}))},disabled:u,children:[e.jsx(Q,{id:k,"data-testid":"device-type-select",className:"w-full",children:e.jsx(B,{placeholder:a("device.type"),children:t=>X[t]??""})}),e.jsxs(_,{children:[e.jsx(f,{value:"local",children:a("device.typeLocal")}),e.jsx(f,{value:"ssh",children:a("device.typeSSH")})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[m(F,a("device.session")),e.jsx(x,{id:F,"data-testid":"device-session-input",type:"text",value:n.session,onChange:t=>o(i=>({...i,session:t.target.value})),placeholder:a("device.sessionPlaceholder")})]})]})]}),P&&e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"space-y-2.5",children:[K(a("device.sectionConnection")),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsxs("div",{className:"space-y-1.5 sm:col-span-2",children:[m($,a("device.host")),e.jsx(x,{id:$,type:"text",value:n.host,onChange:t=>o(i=>({...i,host:t.target.value})),placeholder:a("device.hostPlaceholder")})]}),e.jsxs("div",{className:"space-y-1.5",children:[m(A,a("device.port")),e.jsx(x,{id:A,type:"number",value:n.port,onChange:t=>o(i=>({...i,port:Number.parseInt(t.target.value||"22",10)})),min:1,max:65535})]}),e.jsxs("div",{className:"space-y-1.5 sm:col-span-2",children:[m(T,a("device.username")),e.jsx(x,{id:T,type:"text",value:n.username,onChange:t=>o(i=>({...i,username:t.target.value})),placeholder:a("device.usernamePlaceholder")})]}),e.jsxs("div",{className:"space-y-1.5",children:[m(`${s}-device-ssh-config-ref`,"SSH Config"),e.jsx(x,{id:`${s}-device-ssh-config-ref`,type:"text",value:n.sshConfigRef,onChange:t=>o(i=>({...i,sshConfigRef:t.target.value})),placeholder:"~/.ssh/config"})]})]})]}),e.jsxs("section",{className:"space-y-2.5",children:[K(a("device.sectionAuth")),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[m(H,a("device.authMode")),e.jsxs(z,{value:n.authMode,onValueChange:t=>{t&&o(i=>({...i,authMode:t}))},children:[e.jsx(Q,{id:H,className:"w-full",children:e.jsx(B,{placeholder:a("device.authMode"),children:t=>ee[t]??""})}),e.jsxs(_,{children:[e.jsx(f,{value:"password",children:a("device.authPassword")}),e.jsx(f,{value:"key",children:a("device.authKey")}),e.jsx(f,{value:"agent",children:a("device.authAgent")}),e.jsx(f,{value:"configRef",children:"SSH Config"})]})]})]}),n.authMode==="password"&&e.jsxs("div",{className:"space-y-1.5",children:[m(L,a("device.password")),e.jsx(x,{id:L,type:"password",value:n.password,onChange:t=>o(i=>({...i,password:t.target.value}))})]}),n.authMode==="key"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1.5",children:[m(R,a("device.privateKey")),e.jsx(Ee,{id:R,value:n.privateKey,onChange:t=>o(i=>({...i,privateKey:t.target.value})),className:"h-28 font-mono text-xs",placeholder:a("device.privateKeyPlaceholder")})]}),e.jsxs("div",{className:"space-y-1.5",children:[m(q,a("device.passphrase")),e.jsx(x,{id:q,type:"password",value:n.privateKeyPassphrase,onChange:t=>o(i=>({...i,privateKeyPassphrase:t.target.value}))})]})]})]})]})]})]}),e.jsxs(Me,{children:[e.jsx(w,{type:"button",variant:"outline",onClick:h,children:a("common.cancel")}),e.jsx(w,{type:"submit",variant:"default","data-testid":"device-dialog-save",disabled:l,children:a(l?"common.saving":"common.save")})]})]})]})})}function Qe(){const{t:s}=N();return e.jsx(e.Fragment,{children:s("sidebar.manageDevices")})}function Be(){const{t:s}=N(),c=()=>{window.dispatchEvent(new CustomEvent("tmex:open-add-device"))};return e.jsx(w,{variant:"ghost",size:"icon-sm","data-testid":"devices-add",onClick:c,"aria-label":s("sidebar.addDevice"),title:s("sidebar.addDevice"),children:e.jsx(W,{className:"h-4 w-4"})})}export{Be as PageActions,Qe as PageTitle,ze as default};
12
+ //# sourceMappingURL=DevicesPage-_lgEXguX.js.map
@@ -0,0 +1,17 @@
1
+ import{c as de,y as A,ah as Q,w as r,ab as I,ai as S,t as m,v as e,_ as v,aj as z,ak as H,al as V,am as J,an as U,G as x,L as D,ae as $,T as G,a0 as me,a1 as he,a2 as ue,a3 as ge,a4 as xe,a5 as pe,a6 as fe,a7 as je,ao as Ue,ap as Re,aq as Ie,ar as Qe,s as Ze}from"./index-BhWcb9L_.js";import{C as M,a as q,b as _,c as R}from"./card-BHK15lCp.js";import{R as es}from"./refresh-cw-DfNqpalN.js";import{S as ss}from"./send-XA81w52-.js";/**
2
+ * @license lucide-react v0.564.0 - ISC
3
+ *
4
+ * This source code is licensed under the ISC license.
5
+ * See the LICENSE file in the root directory of this source tree.
6
+ */const ts=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]],as=de("rotate-ccw",ts);/**
7
+ * @license lucide-react v0.564.0 - ISC
8
+ *
9
+ * This source code is licensed under the ISC license.
10
+ * See the LICENSE file in the root directory of this source tree.
11
+ */const ns=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]],B=de("save",ns);/**
12
+ * @license lucide-react v0.564.0 - ISC
13
+ *
14
+ * This source code is licensed under the ISC license.
15
+ * See the LICENSE file in the root directory of this source tree.
16
+ */const is=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]],Oe=de("shield",is),ze=["openai-chat","openai-responses"];async function O(s,a){try{return(await s.json()).error??a}catch{return a}}function ls(){var b;const{t:s}=A(),a=Q(),[h,n]=r.useState(""),[d,p]=r.useState(""),[w,f]=r.useState("openai-chat"),[u,y]=r.useState(""),N=I({queryKey:["llm-providers"],queryFn:async()=>{const c=await fetch("/api/llm/providers");if(!c.ok)throw new Error(await O(c,s("settings.llm.loadFailed")));return await c.json()}}),g=S({mutationFn:async()=>{const c={name:h.trim(),protocol:w,baseUrl:d.trim(),apiKey:u.trim(),enabled:!0},E=await fetch("/api/llm/providers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!E.ok)throw new Error(await O(E,s("settings.llm.createFailed")));return await E.json()},onSuccess:async c=>{n(""),p(""),f("openai-chat"),y(""),await a.invalidateQueries({queryKey:["llm-providers"]}),c.modelsError?m.warning(s("settings.llm.modelsFetchFailed",{error:c.modelsError})):m.success(s("common.success"))},onError:c=>{m.error(c instanceof Error?c.message:s("common.error"))}}),j=((b=N.data)==null?void 0:b.providers)??[];return e.jsxs(e.Fragment,{children:[e.jsxs(M,{className:"border-0 ring-0","data-testid":"llm-providers-section",children:[e.jsx(q,{children:e.jsx(_,{children:s("settings.llm.title")})}),e.jsxs(R,{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-12 md:items-end",children:[e.jsxs("div",{className:"md:col-span-3 space-y-2",children:[e.jsx("label",{className:"block text-sm font-medium",htmlFor:"new-llm-provider-name",children:s("settings.llm.name")}),e.jsx(v,{id:"new-llm-provider-name","data-testid":"llm-provider-name-input",value:h,onChange:c=>n(c.target.value),placeholder:s("settings.llm.namePlaceholder"),className:"min-h-10"})]}),e.jsxs("div",{className:"md:col-span-4 space-y-2",children:[e.jsx("label",{className:"block text-sm font-medium",htmlFor:"new-llm-provider-baseurl",children:s("settings.llm.baseUrl")}),e.jsx(v,{id:"new-llm-provider-baseurl","data-testid":"llm-provider-baseurl-input",value:d,onChange:c=>p(c.target.value),placeholder:s("settings.llm.baseUrlPlaceholder"),className:"min-h-10"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:s("settings.llm.baseUrlHint")})]}),e.jsxs("div",{className:"md:col-span-2 space-y-2",children:[e.jsx("label",{className:"block text-sm font-medium",htmlFor:"new-llm-provider-protocol",children:s("settings.llm.protocol")}),e.jsxs(z,{value:w,onValueChange:c=>{c&&f(c)},children:[e.jsx(H,{id:"new-llm-provider-protocol","data-testid":"llm-provider-protocol-select",className:"w-full min-h-10",children:e.jsx(V,{})}),e.jsx(J,{children:ze.map(c=>e.jsx(U,{value:c,children:c},c))})]})]}),e.jsxs("div",{className:"md:col-span-3 space-y-2",children:[e.jsx("label",{className:"block text-sm font-medium",htmlFor:"new-llm-provider-apikey",children:s("settings.llm.apiKey")}),e.jsx(v,{id:"new-llm-provider-apikey","data-testid":"llm-provider-apikey-input",type:"password",value:u,onChange:c=>y(c.target.value),placeholder:s("settings.llm.apiKeyPlaceholder"),className:"min-h-10"})]})]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(x,{variant:"default","data-testid":"llm-provider-add",onClick:()=>g.mutate(),disabled:g.isPending||!h.trim()||!d.trim()||!u.trim(),className:"w-full sm:w-auto",children:[g.isPending?e.jsx(D,{className:"h-4 w-4 animate-spin"}):e.jsx(B,{className:"h-4 w-4"}),s("settings.llm.addProvider")]})}),e.jsxs("div",{className:"space-y-3",children:[N.isLoading&&e.jsx("div",{className:"text-sm text-muted-foreground",children:s("common.loading")}),!N.isLoading&&j.length===0&&e.jsx("div",{className:"text-sm text-muted-foreground","data-testid":"llm-providers-empty",children:s("settings.llm.empty")}),j.map(c=>e.jsx(rs,{provider:c},c.id))]})]})]}),e.jsx(os,{providers:j})]})}function rs({provider:s}){const{t:a}=A(),h=Q(),[n,d]=r.useState(s.name),[p,w]=r.useState(s.baseUrl),[f,u]=r.useState(s.protocol),[y,N]=r.useState(""),[g,j]=r.useState(s.enabled),[b,c]=r.useState(!1),[E,F]=r.useState(!1);r.useEffect(()=>{d(s.name),w(s.baseUrl),u(s.protocol),j(s.enabled)},[s.name,s.baseUrl,s.protocol,s.enabled]);const i=S({mutationFn:async()=>{const o={name:n.trim(),baseUrl:p.trim(),protocol:f,enabled:g};y.trim()&&(o.apiKey=y.trim());const l=await fetch(`/api/llm/providers/${s.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!l.ok)throw new Error(await O(l,a("settings.llm.updateFailed")));return await l.json()},onSuccess:async o=>{N(""),await h.invalidateQueries({queryKey:["llm-providers"]}),o.modelsError?m.warning(a("settings.llm.modelsFetchFailed",{error:o.modelsError})):m.success(a("common.success"))},onError:o=>{m.error(o instanceof Error?o.message:a("common.error"))}}),P=S({mutationFn:async()=>{const o=await fetch(`/api/llm/providers/${s.id}`,{method:"DELETE"});if(!o.ok)throw new Error(await O(o,a("settings.llm.deleteFailed")))},onSuccess:async()=>{await h.invalidateQueries({queryKey:["llm-providers"]}),await h.invalidateQueries({queryKey:["llm-settings"]}),m.success(a("common.success"))},onError:o=>{m.error(o instanceof Error?o.message:a("common.error"))}}),K=S({mutationFn:async()=>{const o=await fetch(`/api/llm/providers/${s.id}/refresh-models`,{method:"POST"});if(!o.ok)throw new Error(await O(o,a("settings.llm.refreshModelsFailed")))},onSuccess:async()=>{await h.invalidateQueries({queryKey:["llm-providers"]}),m.success(a("common.success"))},onError:o=>{m.error(o instanceof Error?o.message:a("common.error"))}});return e.jsxs("div",{className:"space-y-4 rounded-md border-0 bg-card p-4","data-testid":`llm-provider-card-${s.id}`,"data-provider-name":s.name,children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-12 md:items-end",children:[e.jsxs("div",{className:"md:col-span-3 space-y-2",children:[e.jsx("label",{className:"block text-sm font-medium",htmlFor:`llm-provider-name-${s.id}`,children:a("settings.llm.name")}),e.jsx(v,{id:`llm-provider-name-${s.id}`,value:n,onChange:o=>d(o.target.value),className:"min-h-10"})]}),e.jsxs("div",{className:"md:col-span-4 space-y-2",children:[e.jsx("label",{className:"block text-sm font-medium",htmlFor:`llm-provider-baseurl-${s.id}`,children:a("settings.llm.baseUrl")}),e.jsx(v,{id:`llm-provider-baseurl-${s.id}`,value:p,onChange:o=>w(o.target.value),className:"min-h-10"})]}),e.jsxs("div",{className:"md:col-span-2 space-y-2",children:[e.jsx("label",{className:"block text-sm font-medium",htmlFor:`llm-provider-protocol-${s.id}`,children:a("settings.llm.protocol")}),e.jsxs(z,{value:f,onValueChange:o=>{o&&u(o)},children:[e.jsx(H,{id:`llm-provider-protocol-${s.id}`,className:"w-full min-h-10",children:e.jsx(V,{})}),e.jsx(J,{children:ze.map(o=>e.jsx(U,{value:o,children:o},o))})]})]}),e.jsxs("div",{className:"md:col-span-3 space-y-2",children:[e.jsx("label",{className:"block text-sm font-medium",htmlFor:`llm-provider-apikey-${s.id}`,children:a("settings.llm.apiKey")}),e.jsx(v,{id:`llm-provider-apikey-${s.id}`,"data-testid":`llm-provider-apikey-${s.id}`,"data-key-set":s.hasApiKey?"true":"false",type:"password",value:y,onChange:o=>N(o.target.value),placeholder:s.hasApiKey?a("settings.llm.apiKeySetPlaceholder"):a("settings.llm.apiKeyPlaceholder"),className:"min-h-10"})]})]}),e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"flex min-h-10 items-center gap-3 rounded-lg border border-border bg-background px-3 py-2",children:[e.jsx("span",{className:"text-sm font-medium",children:a("common.enabled")}),e.jsx($,{checked:g,onCheckedChange:o=>j(!!o),"data-testid":`llm-provider-enabled-${s.id}`})]}),e.jsxs(x,{variant:"outline",size:"sm","data-testid":`llm-provider-refresh-models-${s.id}`,onClick:()=>K.mutate(),disabled:K.isPending,children:[K.isPending?e.jsx(D,{className:"h-4 w-4 animate-spin"}):e.jsx(es,{className:"h-4 w-4"}),a("settings.llm.refreshModels")]}),e.jsx(x,{variant:"ghost",size:"sm","data-testid":`llm-provider-toggle-models-${s.id}`,onClick:()=>c(o=>!o),children:s.models.length>0?a("settings.llm.modelsCount",{total:s.models.length}):a("settings.llm.modelsNotFetched")})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(x,{variant:"destructive",size:"sm","data-testid":`llm-provider-delete-${s.id}`,onClick:()=>F(!0),disabled:P.isPending,children:[e.jsx(G,{className:"h-4 w-4"}),a("common.delete")]}),e.jsxs(x,{variant:"default",size:"sm","data-testid":`llm-provider-save-${s.id}`,onClick:()=>i.mutate(),disabled:i.isPending||!n.trim()||!p.trim(),children:[i.isPending?e.jsx(D,{className:"h-4 w-4 animate-spin"}):e.jsx(B,{className:"h-4 w-4"}),a("common.save")]})]})]}),b&&s.models.length>0&&e.jsx("div",{className:"max-h-48 overflow-y-auto rounded-lg border border-border bg-background p-3","data-testid":`llm-provider-models-${s.id}`,children:e.jsx("ul",{className:"space-y-1",children:s.models.map(o=>e.jsx("li",{className:"font-mono text-xs text-muted-foreground",children:o},o))})}),e.jsx(me,{open:E,onOpenChange:F,children:e.jsxs(he,{children:[e.jsxs(ue,{children:[e.jsx(ge,{children:a("settings.llm.deleteProvider")}),e.jsx(xe,{children:a("settings.llm.deleteConfirm",{name:s.name})})]}),e.jsxs(pe,{children:[e.jsx(fe,{onClick:()=>F(!1),children:a("common.cancel")}),e.jsx(je,{variant:"destructive","data-testid":`llm-provider-delete-confirm-${s.id}`,onClick:()=>{P.mutate(),F(!1)},children:a("common.confirm")})]})]})})]})}const re="__none__";function os({providers:s}){var E,F;const{t:a}=A(),h=Q(),[n,d]=r.useState(null),[p,w]=r.useState(""),f=I({queryKey:["llm-settings"],queryFn:async()=>{const i=await fetch("/api/llm/settings");if(!i.ok)throw new Error(await O(i,a("settings.llm.settingsLoadFailed")));return await i.json()}}),u=((E=f.data)==null?void 0:E.settings.defaultProviderId)??null,y=((F=f.data)==null?void 0:F.settings.defaultModelId)??"",N=!!f.data;r.useEffect(()=>{N&&(d(u),w(y))},[N,u,y]);const g=S({mutationFn:async()=>{const i={defaultProviderId:n,defaultModelId:p.trim()||null},P=await fetch("/api/llm/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!P.ok)throw new Error(await O(P,a("settings.llm.settingsSaveFailed")))},onSuccess:async()=>{await h.invalidateQueries({queryKey:["llm-settings"]}),m.success(a("common.success"))},onError:i=>{m.error(i instanceof Error?i.message:a("common.error"))}}),j=s.filter(i=>i.enabled),b=s.find(i=>i.id===n),c=(b==null?void 0:b.models)??[];return e.jsxs(M,{className:"border-0 ring-0","data-testid":"llm-defaults-section",children:[e.jsx(q,{children:e.jsx(_,{children:a("settings.llm.defaults")})}),e.jsxs(R,{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-medium",htmlFor:"llm-default-provider-select",children:a("settings.llm.defaultProvider")}),e.jsxs(z,{value:n??re,onValueChange:i=>{i&&d(i===re?null:i)},children:[e.jsx(H,{id:"llm-default-provider-select","data-testid":"llm-default-provider-select",className:"w-full min-h-10",children:e.jsx(V,{children:(b==null?void 0:b.name)??a("settings.llm.defaultProviderNone")})}),e.jsxs(J,{children:[e.jsx(U,{value:re,children:a("settings.llm.defaultProviderNone")}),j.map(i=>e.jsx(U,{value:i.id,children:i.name},i.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-medium",htmlFor:"llm-default-model-input",children:a("settings.llm.defaultModel")}),e.jsx(v,{id:"llm-default-model-input","data-testid":"llm-default-model-input",list:"llm-default-model-options",value:p,onChange:i=>w(i.target.value),placeholder:a("settings.llm.defaultModelPlaceholder"),className:"min-h-10"}),e.jsx("datalist",{id:"llm-default-model-options",children:c.map(i=>e.jsx("option",{value:i},i))})]})]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(x,{variant:"default","data-testid":"llm-defaults-save",onClick:()=>g.mutate(),disabled:g.isPending||f.isLoading,className:"w-full sm:w-auto",children:[g.isPending?e.jsx(D,{className:"h-4 w-4 animate-spin"}):e.jsx(B,{className:"h-4 w-4"}),a("settings.llm.saveDefaults")]})})]})]})}const cs=["none","tavily","brave"];async function oe(s,a){try{return(await s.json()).error??a}catch{return a}}function ds(){var F;const{t:s}=A(),a=Q(),[h,n]=r.useState("none"),[d,p]=r.useState(""),[w,f]=r.useState(""),[u,y]=r.useState(null),N=I({queryKey:["llm-settings"],queryFn:async()=>{const i=await fetch("/api/llm/settings");if(!i.ok)throw new Error(await oe(i,s("settings.search.loadFailed")));return await i.json()}}),g=(F=N.data)==null?void 0:F.settings,j=g==null?void 0:g.searchProvider;r.useEffect(()=>{j&&n(j)},[j]);const b=S({mutationFn:async()=>{const i={searchProvider:h};d.trim()&&(i.tavilyApiKey=d.trim()),w.trim()&&(i.braveApiKey=w.trim());const P=await fetch("/api/llm/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!P.ok)throw new Error(await oe(P,s("settings.search.saveFailed")))},onSuccess:async()=>{p(""),f(""),await a.invalidateQueries({queryKey:["llm-settings"]}),m.success(s("common.success"))},onError:i=>{m.error(i instanceof Error?i.message:s("common.error"))}}),c=S({mutationFn:async i=>{const P={[i]:""},K=await fetch("/api/llm/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(P)});if(!K.ok)throw new Error(await oe(K,s("settings.search.saveFailed")))},onSuccess:async()=>{await a.invalidateQueries({queryKey:["llm-settings"]}),m.success(s("common.success"))},onError:i=>{m.error(i instanceof Error?i.message:s("common.error"))}}),E=i=>i==="none"?s("settings.search.providerNone"):i==="tavily"?"Tavily":"Brave";return e.jsxs(M,{className:"border-0 ring-0","data-testid":"settings-search-section",children:[e.jsx(q,{children:e.jsx(_,{children:s("settings.search.title")})}),e.jsxs(R,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-medium",htmlFor:"search-provider-select",children:s("settings.search.provider")}),e.jsxs(z,{value:h,onValueChange:i=>{i&&n(i)},children:[e.jsx(H,{id:"search-provider-select","data-testid":"settings-search-provider-select",className:"w-full min-h-10",children:e.jsx(V,{children:E(h)})}),e.jsx(J,{children:cs.map(i=>e.jsx(U,{value:i,children:E(i)},i))})]})]}),e.jsx(De,{id:"search-tavily-key-input",testId:"settings-search-tavily",label:s("settings.search.tavilyApiKey"),value:d,hasKey:(g==null?void 0:g.hasTavilyApiKey)??!1,onChange:p,onClear:()=>y("tavilyApiKey"),clearing:c.isPending&&c.variables==="tavilyApiKey"}),e.jsx(De,{id:"search-brave-key-input",testId:"settings-search-brave",label:s("settings.search.braveApiKey"),value:w,hasKey:(g==null?void 0:g.hasBraveApiKey)??!1,onChange:f,onClear:()=>y("braveApiKey"),clearing:c.isPending&&c.variables==="braveApiKey"}),e.jsx(me,{open:u!==null,onOpenChange:i=>{i||y(null)},children:e.jsxs(he,{children:[e.jsxs(ue,{children:[e.jsx(ge,{children:s("settings.search.clearKey")}),e.jsx(xe,{children:s("settings.search.clearKeyConfirm")})]}),e.jsxs(pe,{children:[e.jsx(fe,{children:s("common.cancel")}),e.jsx(je,{"data-testid":"settings-search-clear-confirm",onClick:()=>{u&&c.mutate(u),y(null)},children:s("settings.search.clearKey")})]})]})}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(x,{variant:"default","data-testid":"settings-search-save",onClick:()=>b.mutate(),disabled:b.isPending||N.isLoading,className:"w-full sm:w-auto",children:[b.isPending?e.jsx(D,{className:"h-4 w-4 animate-spin"}):e.jsx(B,{className:"h-4 w-4"}),s("common.save")]})})]})]})}function De({id:s,testId:a,label:h,value:n,hasKey:d,onChange:p,onClear:w,clearing:f}){const{t:u}=A();return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-medium",htmlFor:s,children:h}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(v,{id:s,"data-testid":`${a}-input`,"data-key-set":d?"true":"false",type:"password",value:n,onChange:y=>p(y.target.value),placeholder:u(d?"settings.search.keySetPlaceholder":"settings.search.keyPlaceholder"),className:"min-h-10"}),d&&e.jsxs(x,{variant:"outline",size:"sm","data-testid":`${a}-clear`,onClick:w,disabled:f,className:"shrink-0",children:[e.jsx(G,{className:"h-4 w-4"}),u("settings.search.clearKey")]})]})]})}const ce=["terminal_bell","terminal_notification","tmux_window_close","tmux_pane_close","device_tmux_missing","device_disconnect","session_created","session_closed","agent_confirmation_pending","agent_turn_finished","agent_error","watch_triggered","watch_model_unavailable","watch_rule_error"];async function T(s,a){try{return(await s.json()).error??a}catch{return a}}function ps(){var Be,Me,qe,_e;const{t:s}=A(),a=Q(),{refreshSettings:h}=Ue(),[n,d]=r.useState("site"),p=Re(t=>t.theme),w=Re(t=>t.setTheme),f=p==="dark",[u,y]=r.useState("tmex"),[N,g]=r.useState(window.location.origin),[j,b]=r.useState("en_US"),[c,E]=r.useState(6),[F,i]=r.useState(3),[P,K]=r.useState(!0),[o,l]=r.useState(!0),[C,L]=r.useState(!0),[ye,be]=r.useState(!0),[we,ve]=r.useState(2),[Ne,ke]=r.useState(10),[He,Ve]=r.useState(!1),[X,Ce]=r.useState(""),[Y,Se]=r.useState(""),[Je,We]=r.useState(null),[Z,Ee]=r.useState(""),[ee,Pe]=r.useState(""),[se,Fe]=r.useState(ce),Ge=t=>{const k=t?"dark":"light";w(k),document.documentElement.classList.toggle("dark",k==="dark")},te=I({queryKey:["site-settings"],queryFn:async()=>{const t=await fetch("/api/settings/site");if(!t.ok)throw new Error(await T(t,s("settings.loadFailed")));return await t.json()}}),ae=I({queryKey:["telegram-bots"],queryFn:async()=>{const t=await fetch("/api/settings/telegram/bots");if(!t.ok)throw new Error(await T(t,s("telegram.loadBotsFailed")));return await t.json()}});r.useEffect(()=>{var k;const t=(k=te.data)==null?void 0:k.settings;t&&(y(t.siteName),g(t.siteUrl),b(t.language??"en_US"),E(t.bellThrottleSeconds),i(t.notificationThrottleSeconds??3),K(t.enableBrowserBellToast??!0),l(t.enableBrowserNotificationToast??!0),L(t.enableTelegramBellPush??!0),be(t.enableTelegramNotificationPush??!0),ve(t.sshReconnectMaxRetries),ke(t.sshReconnectDelaySeconds))},[(Be=te.data)==null?void 0:Be.settings]);const Te=S({mutationFn:async()=>{const k=await fetch("/api/settings/site",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({siteName:u,siteUrl:N,language:j,bellThrottleSeconds:c,notificationThrottleSeconds:F,enableBrowserBellToast:P,enableBrowserNotificationToast:o,enableTelegramBellPush:C,enableTelegramNotificationPush:ye,sshReconnectMaxRetries:we,sshReconnectDelaySeconds:Ne})});if(!k.ok)throw new Error(await T(k,s("settings.saveFailed")))},onSuccess:async()=>{var t,k;await Promise.all([a.invalidateQueries({queryKey:["site-settings"]}),h()]),m.success(s("settings.settingsSaved")),((k=(t=te.data)==null?void 0:t.settings)==null?void 0:k.language)!==j&&(Ze.changeLanguage(j),Ve(!0))},onError:t=>{m.error(t instanceof Error?t.message:s("common.error"))}}),ne=S({mutationFn:async()=>{const t=await fetch("/api/settings/telegram/bots",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:X,token:Y,enabled:!0,allowAuthRequests:!0})});if(!t.ok)throw new Error(await T(t,s("telegram.createFailed")))},onSuccess:async()=>{Ce(""),Se(""),await a.invalidateQueries({queryKey:["telegram-bots"]}),m.success(s("common.success"))},onError:t=>{m.error(t instanceof Error?t.message:s("common.error"))}}),Ke=((Me=ae.data)==null?void 0:Me.bots)??[],ie=I({queryKey:["webhooks"],queryFn:async()=>{const t=await fetch("/api/webhooks");if(!t.ok)throw new Error(await T(t,s("webhook.loadFailed")));return await t.json()}}),le=S({mutationFn:async()=>{const t=await fetch("/api/webhooks",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:Z,secret:ee,eventMask:se})});if(!t.ok)throw new Error(await T(t,s("webhook.createFailed")))},onSuccess:async()=>{Ee(""),Pe(""),Fe(ce),await a.invalidateQueries({queryKey:["webhooks"]}),m.success(s("common.success"))},onError:t=>{m.error(t instanceof Error?t.message:s("common.error"))}}),Ae=S({mutationFn:async t=>{const k=await fetch(`/api/webhooks/${t}`,{method:"DELETE"});if(!k.ok)throw new Error(await T(k,s("webhook.deleteFailed")))},onSuccess:async()=>{await a.invalidateQueries({queryKey:["webhooks"]}),m.success(s("common.success"))},onError:t=>{m.error(t instanceof Error?t.message:s("common.error"))}}),$e=((qe=ie.data)==null?void 0:qe.webhooks)??[];return e.jsxs("div",{className:"mx-auto flex w-full max-w-6xl flex-col gap-4 p-3 pb-[calc(2rem+env(safe-area-inset-bottom))] sm:gap-6 sm:p-5","data-testid":"settings-page",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(x,{type:"button",size:"sm",variant:n==="site"?"default":"outline","data-testid":"settings-tab-site",onClick:()=>d("site"),children:s("settings.siteSettings")}),e.jsx(x,{type:"button",size:"sm",variant:n==="notifications"?"default":"outline","data-testid":"settings-tab-notifications",onClick:()=>d("notifications"),children:s("settings.notificationsTab")}),e.jsx(x,{type:"button",size:"sm",variant:n==="telegram"?"default":"outline","data-testid":"settings-tab-telegram",onClick:()=>d("telegram"),children:s("telegram.title")}),e.jsx(x,{type:"button",size:"sm",variant:n==="webhooks"?"default":"outline","data-testid":"settings-tab-webhooks",onClick:()=>d("webhooks"),children:s("webhook.title")}),e.jsx(x,{type:"button",size:"sm",variant:n==="llm"?"default":"outline","data-testid":"settings-tab-llm",onClick:()=>d("llm"),children:s("settings.llm.title")}),e.jsx(x,{type:"button",size:"sm",variant:n==="search"?"default":"outline","data-testid":"settings-tab-search",onClick:()=>d("search"),children:s("settings.search.title")})]}),n==="site"&&e.jsxs(M,{className:"border-0 ring-0",children:[e.jsx(q,{children:e.jsx(_,{children:s("settings.siteSettings")})}),e.jsxs(R,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-medium",htmlFor:"site-name-input",children:s("settings.siteName")}),e.jsx(v,{id:"site-name-input",value:u,onChange:t=>y(t.target.value),placeholder:s("settings.siteNamePlaceholder"),className:"min-h-10"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-medium",htmlFor:"site-url-input",children:s("settings.siteUrl")}),e.jsx(v,{id:"site-url-input",value:N,onChange:t=>g(t.target.value),placeholder:s("settings.siteUrlPlaceholder"),className:"min-h-10"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-medium",htmlFor:"language-select",children:s("settings.language")}),e.jsxs(z,{value:j,onValueChange:t=>{t&&b(t)},children:[e.jsx(H,{id:"language-select","data-testid":"settings-language-select",className:"w-full min-h-10",children:e.jsx(V,{placeholder:s("settings.language"),children:((_e=Ie.locales.find(t=>t.code===j))==null?void 0:_e.nativeName)??j})}),e.jsx(J,{className:"max-h-[var(--tmex-viewport-height)]",children:Ie.locales.map(t=>e.jsx(U,{value:t.code,children:t.nativeName},t.code))})]}),He&&e.jsx("p",{className:"mt-1 text-xs text-primary","data-testid":"settings-refresh-notice",children:s("settings.refreshToApply")})]}),e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"flex min-h-10 items-center justify-between gap-4 rounded-lg border border-border bg-card px-4 py-2.5",children:[e.jsx("div",{className:"min-w-0 pr-2",children:e.jsx("div",{className:"text-sm font-medium",children:s("settings.theme")})}),e.jsx($,{checked:f,onCheckedChange:t=>Ge(!!t),"data-testid":"settings-theme-toggle"})]})})]})]}),n==="notifications"&&e.jsxs(M,{className:"border-0 ring-0",children:[e.jsx(q,{children:e.jsx(_,{children:s("settings.notificationsTab")})}),e.jsxs(R,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex min-h-10 items-center justify-between gap-4 rounded-lg border border-border bg-card px-4 py-2.5",children:[e.jsx("div",{className:"min-w-0 pr-2",children:e.jsx("div",{className:"text-sm font-medium",children:s("settings.enableBrowserBellToast")})}),e.jsx($,{checked:P,onCheckedChange:t=>K(!!t),"data-testid":"settings-enable-browser-bell-toast"})]}),e.jsxs("div",{className:"flex min-h-10 items-center justify-between gap-4 rounded-lg border border-border bg-card px-4 py-2.5",children:[e.jsx("div",{className:"min-w-0 pr-2",children:e.jsx("div",{className:"text-sm font-medium",children:s("settings.enableTelegramBellPush")})}),e.jsx($,{checked:C,onCheckedChange:t=>L(!!t),"data-testid":"settings-enable-telegram-bell-push"})]}),e.jsxs("div",{className:"flex min-h-10 items-center justify-between gap-4 rounded-lg border border-border bg-card px-4 py-2.5",children:[e.jsx("div",{className:"min-w-0 pr-2",children:e.jsx("div",{className:"text-sm font-medium",children:s("settings.enableBrowserNotificationToast")})}),e.jsx($,{checked:o,onCheckedChange:t=>l(!!t),"data-testid":"settings-enable-browser-notification-toast"})]}),e.jsxs("div",{className:"flex min-h-10 items-center justify-between gap-4 rounded-lg border border-border bg-card px-4 py-2.5",children:[e.jsx("div",{className:"min-w-0 pr-2",children:e.jsx("div",{className:"text-sm font-medium",children:s("settings.enableTelegramNotificationPush")})}),e.jsx($,{checked:ye,onCheckedChange:t=>be(!!t),"data-testid":"settings-enable-telegram-notification-push"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-medium",htmlFor:"bell-throttle-input",children:s("settings.bellThrottle")}),e.jsx(v,{id:"bell-throttle-input",type:"number",value:c,min:0,max:300,onChange:t=>E(Number(t.target.value)),className:"min-h-10"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-medium",htmlFor:"notification-throttle-input",children:s("settings.notificationThrottle")}),e.jsx(v,{id:"notification-throttle-input",type:"number",value:F,min:0,max:300,onChange:t=>i(Number(t.target.value)),className:"min-h-10"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-medium",htmlFor:"ssh-reconnect-retries-input",children:s("settings.sshReconnectMaxRetries")}),e.jsx(v,{id:"ssh-reconnect-retries-input",type:"number",value:we,min:0,max:20,onChange:t=>ve(Number(t.target.value)),className:"min-h-10"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-medium",htmlFor:"ssh-reconnect-delay-input",children:s("settings.sshReconnectDelay")}),e.jsx(v,{id:"ssh-reconnect-delay-input",type:"number",value:Ne,min:1,max:300,onChange:t=>ke(Number(t.target.value)),className:"min-h-10"})]})]})]})]}),n==="telegram"&&e.jsxs(M,{className:"border-0 ring-0",children:[e.jsx(q,{children:e.jsx(_,{children:s("telegram.title")})}),e.jsxs(R,{className:"space-y-6",children:[e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-12 md:items-end",children:[e.jsxs("div",{className:"md:col-span-4 space-y-2",children:[e.jsx("label",{className:"block text-sm font-medium",htmlFor:"new-bot-name",children:s("telegram.botName")}),e.jsx(v,{id:"new-bot-name",value:X,onChange:t=>Ce(t.target.value),placeholder:s("telegram.botNamePlaceholder"),className:"min-h-10"})]}),e.jsxs("div",{className:"md:col-span-6 space-y-2",children:[e.jsx("label",{className:"block text-sm font-medium",htmlFor:"new-bot-token",children:s("telegram.botToken")}),e.jsx(v,{id:"new-bot-token",type:"password",value:Y,onChange:t=>Se(t.target.value),placeholder:s("telegram.botTokenPlaceholder"),className:"min-h-10"})]}),e.jsx("div",{className:"md:col-span-2",children:e.jsxs(x,{variant:"default",className:"w-full md:w-auto","data-testid":"telegram-add-bot",onClick:()=>ne.mutate(),disabled:ne.isPending||!X.trim()||!Y.trim(),children:[ne.isPending?e.jsx(D,{className:"h-4 w-4 animate-spin"}):e.jsx(B,{className:"h-4 w-4"}),s("telegram.addBot")]})})]})}),e.jsxs("div",{className:"space-y-3",children:[ae.isLoading&&e.jsx("div",{className:"text-sm text-muted-foreground",children:s("common.loading")}),!ae.isLoading&&Ke.length===0&&e.jsx("div",{className:"text-sm text-muted-foreground",children:s("telegram.addBot")}),Ke.map(t=>e.jsx(ms,{bot:t,expanded:Je===t.id,onToggleExpand:()=>{We(k=>k===t.id?null:t.id)}},t.id))]})]})]}),n==="webhooks"&&e.jsxs(M,{className:"border-0 ring-0",children:[e.jsx(q,{children:e.jsx(_,{children:s("webhook.title")})}),e.jsxs(R,{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-12 md:items-end",children:[e.jsxs("div",{className:"md:col-span-6 space-y-2",children:[e.jsx("label",{className:"block text-sm font-medium",htmlFor:"webhook-url-input",children:s("webhook.url")}),e.jsx(v,{id:"webhook-url-input","data-testid":"webhook-url-input",value:Z,onChange:t=>Ee(t.target.value),placeholder:"https://example.com/webhook",className:"min-h-10"})]}),e.jsxs("div",{className:"md:col-span-4 space-y-2",children:[e.jsx("label",{className:"block text-sm font-medium",htmlFor:"webhook-secret-input",children:s("webhook.secret")}),e.jsx(v,{id:"webhook-secret-input","data-testid":"webhook-secret-input",value:ee,onChange:t=>Pe(t.target.value),placeholder:s("webhook.secretPlaceholder"),className:"min-h-10"})]}),e.jsx("div",{className:"md:col-span-2",children:e.jsxs(x,{variant:"default",className:"w-full md:w-auto","data-testid":"webhook-add",onClick:()=>le.mutate(),disabled:le.isPending||!Z.trim()||!ee.trim()||se.length===0,children:[le.isPending?e.jsx(D,{className:"h-4 w-4 animate-spin"}):e.jsx(B,{className:"h-4 w-4"}),s("webhook.add")]})})]}),e.jsxs("div",{className:"space-y-3 rounded-lg border border-border bg-card px-4 py-3",children:[e.jsx("div",{className:"text-sm font-medium",children:s("webhook.eventMask")}),e.jsx("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:ce.map(t=>{const k=se.includes(t);return e.jsxs("div",{className:"flex min-h-10 items-center justify-between gap-4 rounded-lg border border-border bg-background px-3 py-2",children:[e.jsx("div",{className:"min-w-0 pr-2 text-sm font-medium",children:s(`notification.eventType.${t}`)}),e.jsx($,{checked:k,"data-testid":`webhook-event-${t}`,onCheckedChange:Xe=>{Fe(W=>Xe?W.includes(t)?W:[...W,t]:W.filter(Ye=>Ye!==t))}})]},t)})})]}),e.jsxs("div",{className:"space-y-2",children:[ie.isLoading&&e.jsx("div",{className:"text-sm text-muted-foreground",children:s("common.loading")}),!ie.isLoading&&$e.length===0&&e.jsx("div",{className:"text-sm text-muted-foreground",children:s("webhook.empty")}),$e.map(t=>e.jsxs("div",{"data-testid":"webhook-item","data-webhook-url":t.url,className:"flex items-center justify-between gap-3 rounded-lg border border-border bg-card px-4 py-2.5",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:t.url}),e.jsx("div",{className:"text-xs text-muted-foreground",children:new Date(t.createdAt).toLocaleString(Qe(j))})]}),e.jsx(x,{variant:"ghost",size:"icon-sm","data-testid":"webhook-delete",onClick:()=>Ae.mutate(t.id),disabled:Ae.isPending,"aria-label":s("common.delete"),title:s("common.delete"),children:e.jsx(G,{className:"h-4 w-4"})})]},t.id))]})]})]}),n==="llm"&&e.jsx(ls,{}),n==="search"&&e.jsx(ds,{}),(n==="site"||n==="notifications")&&e.jsx("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-end",children:e.jsxs(x,{variant:"default","data-testid":"settings-save",onClick:()=>Te.mutate(),disabled:Te.isPending,className:"w-full sm:w-auto",children:[e.jsx(B,{className:"h-4 w-4"}),s("common.save")]})})]})}function ms({bot:s,expanded:a,onToggleExpand:h}){var o;const{t:n}=A(),d=Q(),[p,w]=r.useState(s.name),[f,u]=r.useState(""),[y,N]=r.useState(s.enabled),[g,j]=r.useState(s.allowAuthRequests);r.useEffect(()=>{w(s.name),N(s.enabled),j(s.allowAuthRequests)},[s.allowAuthRequests,s.enabled,s.name]);const b=I({queryKey:["telegram-bot-chats",s.id],enabled:a,queryFn:async()=>{const l=await fetch(`/api/settings/telegram/bots/${s.id}/chats`);if(!l.ok)throw new Error(await T(l,n("telegram.loadChatsFailed")));return await l.json()}}),c=r.useMemo(()=>{var C;const l=((C=b.data)==null?void 0:C.chats)??[];return{pending:l.filter(L=>L.status==="pending"),authorized:l.filter(L=>L.status==="authorized")}},[(o=b.data)==null?void 0:o.chats]),E=S({mutationFn:async()=>{const l={name:p,enabled:y,allowAuthRequests:g};f.trim()&&(l.token=f.trim());const C=await fetch(`/api/settings/telegram/bots/${s.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!C.ok)throw new Error(await T(C,n("telegram.updateFailed")))},onSuccess:async()=>{u(""),await d.invalidateQueries({queryKey:["telegram-bots"]}),m.success(n("common.success"))},onError:l=>{m.error(l instanceof Error?l.message:n("common.error"))}}),F=S({mutationFn:async()=>{const l=await fetch(`/api/settings/telegram/bots/${s.id}`,{method:"DELETE"});if(!l.ok)throw new Error(await T(l,n("telegram.deleteFailed")))},onSuccess:async()=>{await d.invalidateQueries({queryKey:["telegram-bots"]}),m.success(n("common.success"))},onError:l=>{m.error(l instanceof Error?l.message:n("common.error"))}}),i=S({mutationFn:async l=>{const C=await fetch(`/api/settings/telegram/bots/${s.id}/chats/${encodeURIComponent(l)}/approve`,{method:"POST"});if(!C.ok)throw new Error(await T(C,n("telegram.approveFailed")))},onSuccess:async()=>{await Promise.all([d.invalidateQueries({queryKey:["telegram-bots"]}),d.invalidateQueries({queryKey:["telegram-bot-chats",s.id]})]),m.success(n("common.success"))},onError:l=>{m.error(l instanceof Error?l.message:n("common.error"))}}),P=S({mutationFn:async l=>{const C=await fetch(`/api/settings/telegram/bots/${s.id}/chats/${encodeURIComponent(l)}`,{method:"DELETE"});if(!C.ok)throw new Error(await T(C,n("telegram.removeFailed")))},onSuccess:async()=>{await Promise.all([d.invalidateQueries({queryKey:["telegram-bots"]}),d.invalidateQueries({queryKey:["telegram-bot-chats",s.id]})]),m.success(n("common.success"))},onError:l=>{m.error(l instanceof Error?l.message:n("common.error"))}}),K=S({mutationFn:async l=>{const C=await fetch(`/api/settings/telegram/bots/${s.id}/chats/${encodeURIComponent(l)}/test`,{method:"POST"});if(!C.ok)throw new Error(await T(C,n("telegram.testMessageFailed")))},onSuccess:()=>{m.success(n("common.success"))},onError:l=>{m.error(l instanceof Error?l.message:n("common.error"))}});return e.jsxs("div",{className:"space-y-4 rounded-md border-0 bg-card p-4","data-testid":`telegram-bot-card-${s.id}`,"data-bot-name":s.name,children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:s.name}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[s.authorizedCount," / ",s.pendingCount]})]}),e.jsx(x,{variant:"ghost","data-testid":`telegram-bot-toggle-${s.id}`,onClick:h,children:n(a?"common.collapse":"common.expand")})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-12 md:items-end",children:[e.jsxs("div",{className:"md:col-span-3 space-y-2",children:[e.jsx("label",{className:"block text-sm font-medium",htmlFor:`bot-name-${s.id}`,children:n("telegram.botName")}),e.jsx(v,{id:`bot-name-${s.id}`,value:p,onChange:l=>w(l.target.value),className:"min-h-10"})]}),e.jsxs("div",{className:"md:col-span-4 space-y-2",children:[e.jsx("label",{className:"block text-sm font-medium",htmlFor:`bot-token-${s.id}`,children:n("telegram.botToken")}),e.jsx(v,{id:`bot-token-${s.id}`,type:"password",value:f,onChange:l=>u(l.target.value),placeholder:n("telegram.tokenPlaceholder"),className:"min-h-10"})]}),e.jsx("div",{className:"md:col-span-2",children:e.jsxs("div",{className:"flex min-h-10 items-center justify-between gap-3 rounded-lg border border-border bg-background px-3 py-2.5",children:[e.jsx("span",{className:"text-sm font-medium",children:n("common.enabled")}),e.jsx($,{checked:y,onCheckedChange:l=>N(!!l)})]})}),e.jsx("div",{className:"md:col-span-3",children:e.jsxs("div",{className:"flex min-h-10 items-center justify-between gap-3 rounded-lg border border-border bg-background px-3 py-2.5",children:[e.jsx("span",{className:"text-sm font-medium",children:n("telegram.allowAuthRequests")}),e.jsx($,{checked:g,onCheckedChange:l=>j(!!l)})]})})]}),e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-end",children:[e.jsxs(x,{variant:"destructive","data-testid":`telegram-bot-delete-${s.id}`,onClick:()=>F.mutate(),className:"w-full sm:w-auto",children:[e.jsx(G,{className:"h-4 w-4"}),n("telegram.deleteBot")]}),e.jsxs(x,{variant:"default","data-testid":`telegram-bot-save-${s.id}`,onClick:()=>E.mutate(),className:"w-full sm:w-auto",children:[e.jsx(B,{className:"h-4 w-4"}),n("common.save")]})]}),a&&e.jsxs("div",{className:"grid grid-cols-1 gap-4 border-t border-border pt-4 lg:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-sm font-semibold flex items-center gap-1",children:[e.jsx(Oe,{className:"h-4 w-4"}),n("telegram.pendingChats")]}),c.pending.length===0&&e.jsx("div",{className:"text-xs text-muted-foreground",children:"-"}),c.pending.map(l=>e.jsx(Le,{chat:l,pending:!0,onApprove:()=>i.mutate(l.chatId),onDelete:()=>P.mutate(l.chatId)},`${l.botId}-${l.chatId}`))]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-sm font-semibold flex items-center gap-1",children:[e.jsx(Oe,{className:"h-4 w-4"}),n("telegram.chats")]}),c.authorized.length===0&&e.jsx("div",{className:"text-xs text-muted-foreground",children:"-"}),c.authorized.map(l=>e.jsx(Le,{chat:l,pending:!1,onTest:()=>K.mutate(l.chatId),onDelete:()=>P.mutate(l.chatId)},`${l.botId}-${l.chatId}`))]}),b.isLoading&&e.jsx("div",{className:"lg:col-span-2 text-xs text-muted-foreground",children:n("common.loading")})]})]})}function Le({chat:s,pending:a,onApprove:h,onDelete:n,onTest:d}){const{t:p}=A(),w=Ue(f=>{var u;return((u=f.settings)==null?void 0:u.language)??"en_US"});return e.jsxs("div",{className:"space-y-2 rounded border-0 bg-background p-3",children:[e.jsx("div",{className:"text-sm font-medium truncate",title:s.displayName,children:s.displayName}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[p("telegram.chatId"),":",s.chatId]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:new Date(s.appliedAt).toLocaleString(Qe(w))}),e.jsx("div",{className:"flex items-center justify-end gap-2 pt-1",children:a?e.jsxs(e.Fragment,{children:[e.jsx(x,{variant:"outline",size:"sm",onClick:n,children:p("telegram.reject")}),e.jsx(x,{variant:"default",size:"sm",onClick:h,children:p("telegram.authorize")})]}):e.jsxs(e.Fragment,{children:[e.jsxs(x,{variant:"secondary",size:"sm",onClick:d,children:[e.jsx(ss,{className:"h-3.5 w-3.5"}),p("telegram.sendTestMessage")]}),e.jsx(x,{variant:"destructive",size:"sm",onClick:n,children:p("common.delete")})]})})]})}function fs(){const{t:s}=A();return e.jsx(e.Fragment,{children:s("sidebar.settings")})}function js(){const{t:s}=A(),[a,h]=r.useState(!1),n=S({mutationFn:async()=>{const d=await fetch("/api/settings/restart",{method:"POST"});if(!d.ok)throw new Error(await T(d,s("settings.restartFailed")))},onSuccess:()=>{m.success(s("settings.restartScheduled"))},onError:d=>{m.error(d instanceof Error?d.message:s("common.error"))}});return e.jsxs(e.Fragment,{children:[e.jsx(x,{variant:"ghost",size:"icon-sm",onClick:()=>h(!0),disabled:n.isPending,"aria-label":s("settings.restartGateway"),title:s("settings.restartGateway"),className:"text-destructive hover:text-destructive hover:bg-destructive/10",children:e.jsx(as,{className:"h-4 w-4"})}),e.jsx(me,{open:a,onOpenChange:h,children:e.jsxs(he,{children:[e.jsxs(ue,{children:[e.jsx(ge,{children:s("settings.restartGateway")}),e.jsx(xe,{children:s("settings.restartConfirm")})]}),e.jsxs(pe,{children:[e.jsx(fe,{onClick:()=>h(!1),children:s("common.cancel")}),e.jsx(je,{variant:"destructive",onClick:()=>{n.mutate(),h(!1)},children:s("common.confirm")})]})]})})]})}export{js as PageActions,fs as PageTitle,ps as default};
17
+ //# sourceMappingURL=SettingsPage-D2jiLXqU.js.map
@@ -0,0 +1,2 @@
1
+ import{v as r,x as d}from"./index-BhWcb9L_.js";function o({className:a,size:t="default",...s}){return r.jsx("div",{"data-slot":"card","data-size":t,className:d("ring-foreground/10 bg-card text-card-foreground gap-4 overflow-hidden rounded-xl py-4 text-sm ring-1 has-data-[slot=card-footer]:pb-0 has-[>img:first-child]:pt-0 data-[size=sm]:gap-3 data-[size=sm]:py-3 data-[size=sm]:has-data-[slot=card-footer]:pb-0 *:[img:first-child]:rounded-t-xl *:[img:last-child]:rounded-b-xl group/card flex flex-col",a),...s})}function i({className:a,...t}){return r.jsx("div",{"data-slot":"card-header",className:d("gap-1 rounded-t-xl px-4 group-data-[size=sm]/card:px-3 [.border-b]:pb-4 group-data-[size=sm]/card:[.border-b]:pb-3 group/card-header @container/card-header grid auto-rows-min items-start has-data-[slot=card-action]:grid-cols-[1fr_auto] has-data-[slot=card-description]:grid-rows-[auto_auto]",a),...t})}function c({className:a,...t}){return r.jsx("div",{"data-slot":"card-title",className:d("text-base leading-snug font-medium group-data-[size=sm]/card:text-sm",a),...t})}function n({className:a,...t}){return r.jsx("div",{"data-slot":"card-description",className:d("text-muted-foreground text-sm",a),...t})}function u({className:a,...t}){return r.jsx("div",{"data-slot":"card-content",className:d("px-4 group-data-[size=sm]/card:px-3",a),...t})}export{o as C,i as a,c as b,u as c,n as d};
2
+ //# sourceMappingURL=card-BHK15lCp.js.map