tmex-cli 0.7.0 → 0.8.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.7.0",
3
+ "version": "0.8.0",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "tmex": "./bin/tmex.js",
@@ -18,7 +18,7 @@
18
18
  "scripts": {
19
19
  "clean": "rm -rf dist resources/fe-dist resources/gateway-drizzle",
20
20
  "bundle:resources": "bash ./scripts/bundle-resources.sh",
21
- "build:runtime": "bun build src/runtime/server.ts --outdir ./dist/runtime --target bun --format esm",
21
+ "build:runtime": "bun build src/runtime/server.ts --outdir ./dist/runtime --target bun --format esm && bash ./scripts/copy-runtime-assets.sh",
22
22
  "build:cli": "bun build src/cli-node.ts --outfile ./dist/cli-node.js --target node --format esm",
23
23
  "build": "bun run clean && bun run bundle:resources && bun run build:runtime && bun run build:cli",
24
24
  "release": "npm publish",
@@ -0,0 +1,26 @@
1
+ var jt=Object.defineProperty;var $t=(n,e,t)=>e in n?jt(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var p=(n,e,t)=>$t(n,typeof e!="symbol"?e+"":e,t);import{c as Ye,u as Ke,j as f,X as qt,r as d,M as J,a5 as At,a6 as Ot,a7 as dt,t as xe,a8 as Xt,a9 as it,aa as Qt,E as kt,ab as ot,F as ce,ac as Jt,C as It,ad as Nt,ae as _e,af as Zt,L as $e,n as en,B as fe,T as tn,K as ut,ag as nn,ah as sn,ai as rn,A as on,q as ln,s as an,v as cn,w as dn,x as un,y as hn,z as fn,aj as mn,ak as pn}from"./index-DPqBlAbb.js";import{R as wn}from"./refresh-cw-C1HbpgDO.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=Ye("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=Ye("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=Ye("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=Ye("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){p(this,"kind","canvas");p(this,"mainCanvas");p(this,"selectionCanvas");p(this,"cursorCanvas");p(this,"mainContext");p(this,"selectionContext");p(this,"cursorContext");p(this,"theme");p(this,"fontFamily");p(this,"fontSize");p(this,"cellDimensions",{width:9,height:17});p(this,"deviceCellWidth",9);p(this,"deviceCellHeight",17);p(this,"dpr",1);p(this,"cols",0);p(this,"rows",0);p(this,"lastCursor",null);p(this,"frameCount",0);p(this,"lastDrawnRows",[]);p(this,"colorCache",new Map);p(this,"fontCache",new Map);p(this,"cursorBlinkVisible",!0);p(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,h=i*l;for(const a of[this.mainCanvas,this.selectionCanvas,this.cursorCanvas])a.width=u,a.height=h,a.style.width=`${u/r}px`,a.style.height=`${h/r}px`;for(const a of[this.mainContext,this.selectionContext,this.cursorContext])a.setTransform(1,0,0,1,0,0),a.textBaseline="top",a.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,h=l.style.inverse?l.fgColor??t.foreground:l.bgColor??t.background,a=l.style.inverse?l.bgColor??t.background:l.fgColor??t.foreground,x=l.widthKind==="wide"?this.deviceCellWidth*2:this.deviceCellWidth;if((h.r!==t.background.r||h.g!==t.background.g||h.b!==t.background.b)&&(this.mainContext.fillStyle=this.toCss(h),this.mainContext.fillRect(u,s,x,this.deviceCellHeight)),!l.text||l.style.invisible)continue;this.mainContext.fillStyle=this.toCss(a);const v=l.codepoints.length===1&&Mn(l.codepoints[0])?l.codepoints[0]:null;v!==null?this.drawBlockElement(v,u,s,x,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(x-o,o),o),l.style.strikethrough&&this.mainContext.fillRect(u,Math.round(s+this.deviceCellHeight*.55),Math.max(x-o,o),o),l.style.overline&&this.mainContext.fillRect(u,s+o,Math.max(x-o,o),o)}}drawBlockElement(e,t,s,i,r){const o=this.mainContext,l=E=>Math.round(i*E/8),u=E=>Math.round(r*E/8),h=(E,b,z,w)=>{o.fillRect(t+E,s+b,z-E,w-b)};if(e===9600){h(0,0,i,u(4));return}if(e>=9601&&e<=9608){h(0,u(8-(e-9600)),i,r);return}if(e>=9609&&e<=9615){h(0,0,l(9616-e),r);return}if(e===9616){h(l(4),0,i,r);return}const a=vn.get(e);if(a!==void 0){const E=o.globalAlpha;o.globalAlpha=E*a,h(0,0,i,r),o.globalAlpha=E;return}if(e===9620){h(0,0,i,u(1));return}if(e===9621){h(l(7),0,i,r);return}const x=Cn.get(e)??0,v=l(4),O=u(4);x&1&&h(0,0,v,O),x&2&&h(v,0,i,O),x&4&&h(0,O,v,r),x&8&&h(v,O,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)),h=t.cursor??t.foreground,a=this.toCss(h);this.cursorContext.fillStyle=a,this.cursorContext.strokeStyle=a,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 Te=0,In=-2,Nn=1,Hn=2,Pn=3,Bn=10,Ln=11,Fn=12,Gn=13,Un=14,zn=15,Yn=16,Kn=17,Vn=1,Wn=2,jn=1,$n=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 Re(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===In)return null;if(s!==Te)throw new Error(`ghostty optional color read failed with result ${s}`);return Re(n.bindings,t.ptr)}finally{t.free()}}function de(n,e){const t=n.bindings.allocU8();try{const s=e(t);if(typeof s=="number"&&s!==Te)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!==Te)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!==Te)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!==Te)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!==Te)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,$n,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(Re(n.bindings,l))}const i=e.view.getUint8(n.bindings.field("GhosttyRenderStateColors","cursor_has_value").offset)!==0,r=de(n,o=>n.bindings.getRenderStateValueResult(n.renderStateHandle,Un,o));return{cols:Ie(n,o=>n.bindings.getRenderStateValueResult(n.renderStateHandle,Nn,o)),rows:Ie(n,o=>n.bindings.getRenderStateValueResult(n.renderStateHandle,Hn,o)),dirty:ss(nt(n,o=>n.bindings.getRenderStateValueResult(n.renderStateHandle,Pn,o))),colors:{background:Re(n.bindings,e.ptr+n.bindings.field("GhosttyRenderStateColors","background").offset),foreground:Re(n.bindings,e.ptr+n.bindings.field("GhosttyRenderStateColors","foreground").offset),cursor:i?Re(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:de(n,o=>n.bindings.getRenderStateValueResult(n.renderStateHandle,Ln,o)),blinking:de(n,o=>n.bindings.getRenderStateValueResult(n.renderStateHandle,Fn,o)),passwordInput:de(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?de(n,o=>n.bindings.getRenderStateValueResult(n.renderStateHandle,Kn,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,h=>n.bindings.getRenderStateRowCellValueResult(n.rowCellsHandle,jn,h)),o=as(n),l=is(nt(n,h=>n.bindings.getRawCellValueResult(r,ts,h))),u={x:i,text:cs(o),codepoints:o,widthKind:l,hasText:de(n,h=>n.bindings.getRawCellValueResult(r,ns,h)),style:ls(n),fgColor:ft(n,h=>n.bindings.getRenderStateRowCellValueResult(n.rowCellsHandle,Jn,h)),bgColor:ft(n,h=>n.bindings.getRenderStateRowCellValueResult(n.rowCellsHandle,Qn,h))};s.push(u),i+=1}return{y:e,dirty:de(n,r=>n.bindings.getRenderStateRowValueResult(n.rowIteratorHandle,Vn,r)),wrap:de(n,r=>n.bindings.getRawRowValueResult(t,Zn,r)),wrapContinuation:de(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 Ht(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 Ht(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:Ht(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 a=s==null?void 0:s(l),x=a?gt(a,i.end.col):i.end.col;o.push({row:u,x:i.start.col,width:x-i.start.col+1});continue}if(l===i.start.line){const a=s?Math.max(s(l).colChars.length-i.start.col,0):Number.MAX_SAFE_INTEGER;o.push({row:u,x:i.start.col,width:a});continue}if(l===i.end.line){const a=s==null?void 0:s(l),x=a?gt(a,i.end.col):i.end.col;o.push({row:u,x:0,width:x+1});continue}const h=s?s(l).colChars.length:Number.MAX_SAFE_INTEGER;o.push({row:u,x:0,width:h})}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=new URL("/assets/ghostty-vt-BKQMf-5X.wasm",import.meta.url).href,Le=0,xt=-3,As=11,Os=12,ks=13,Is=14,Ns=1,Hs=2,Ps=9,Bs=1,Ls=0,Fs=1,Gs=2,Us=0,zs=1,Ys=2,Ks=4,Vs=2004,Ws=9,js=1e3,$s=1002,qs=1003,Xs=1005,Tt=1006,Qs=1015,bt=1016;let Je=null;function I(n,e){if(n!==Le)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){p(this,"exports");p(this,"layout");p(this,"decoder",new TextDecoder);p(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 I(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){I(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=(a,x)=>{const[v,O,E]=Ut(x);this.setField(a.view,"GhosttyColorRgb","r",v),this.setField(a.view,"GhosttyColorRgb","g",O),this.setField(a.view,"GhosttyColorRgb","b",E)};u(s,t.foreground),u(i,t.background),u(r,t.cursor);const h=this.bytes(l,o.length*3);o.forEach(([a,x,v],O)=>{const E=O*3;h[E]=a,h[E+1]=x,h[E+2]=v});try{I(this.exports.ghostty_terminal_set(e,As,s.ptr),"ghostty_terminal_set(foreground)"),I(this.exports.ghostty_terminal_set(e,Os,i.ptr),"ghostty_terminal_set(background)"),I(this.exports.ghostty_terminal_set(e,ks,r.ptr),"ghostty_terminal_set(cursor)"),I(this.exports.ghostty_terminal_set(e,Is,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 I(this.exports.ghostty_terminal_get(e,Ns,t),"ghostty_terminal_get(cols)"),I(this.exports.ghostty_terminal_get(e,Hs,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 I(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 I(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){I(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")),h=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 a=this.field("GhosttyFormatterTerminalOptions","selection").offset;return i.view.setUint32(a,s.selectionPtr??0,!0),I(this.exports.ghostty_formatter_terminal_new(0,h,e,i.ptr),"ghostty_formatter_terminal_new"),this.readPointer(h)}finally{i.free(),this.freeOpaque(h)}}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)!==Le?(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 h=r-1;h>=0&&(l=this.resolveViewportGridRef(e,i-1,h),!l);h-=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 h=this.field("GhosttySelection","start").offset,a=this.field("GhosttySelection","end").offset;return this.bytes(u.ptr+h,this.typeSize("GhosttyGridRef")).set(this.bytes(o.ptr,this.typeSize("GhosttyGridRef"))),this.bytes(u.ptr+a,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{I(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 I(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){I(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){I(this.getRenderStateValueResult(e,t,s),"ghostty_render_state_get")}setRenderStateValue(e,t,s){I(this.exports.ghostty_render_state_set(e,t,s),"ghostty_render_state_set")}getRenderStateColors(e,t){I(this.exports.ghostty_render_state_colors_get(e,t),"ghostty_render_state_colors_get")}createRenderStateRowIterator(){const e=this.allocOpaque();try{return I(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){I(this.getRenderStateRowValueResult(e,t,s),"ghostty_render_state_row_get")}setRenderStateRowValue(e,t,s){I(this.exports.ghostty_render_state_row_set(e,t,s),"ghostty_render_state_row_set")}createRenderStateRowCells(){const e=this.allocOpaque();try{return I(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){I(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){I(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){I(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){I(this.getRawCellValueResult(e,t,s),"ghostty_cell_get")}createKeyEncoder(){const e=this.allocOpaque();try{return I(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{I(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,Ks,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,$s),o=this.isTerminalModeEnabled(t,js),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 h=Math.max(1,Math.floor(s.x/Math.max(1,s.cellWidth))+1),a=Math.max(1,Math.floor(s.y/Math.max(1,s.cellHeight))+1),x=Math.round(s.x+1),v=Math.round(s.y+1);let O=s.action==="release"&&!this.isTerminalModeEnabled(t,Tt)&&!this.isTerminalModeEnabled(t,bt)?3:u;if(s.action==="motion"&&(O+=32),O+=Zs(s.mods),this.isTerminalModeEnabled(t,bt)){const E=s.action==="release"?"m":"M";return`\x1B[<${O};${x};${v}${E}`}if(this.isTerminalModeEnabled(t,Tt)){const E=s.action==="release"?"m":"M";return`\x1B[<${O};${h};${a}${E}`}if(this.isTerminalModeEnabled(t,Qs))return`\x1B[${O};${h};${a}M`;if(this.isTerminalModeEnabled(t,Xs)||o||r||i||l){const E=Ze(O),b=Ze(h),z=Ze(a);return!E||!b||!z?null:`\x1B[M${E}${b}${z}`}return null}encodeKeyEvent(e,t,s){if(s.keyCode<=0)return null;const i=this.allocOpaque();let r=0,o=null;try{return I(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!==Le&&I(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{I(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,Vs),o=this.exports.ghostty_paste_encode(s.ptr,s.len,r?1:0,0,0,i);o!==xt&&o!==Le&&I(o,"ghostty_paste_encode(size)");const l=Math.max(0,this.readUsize(i));if(l===0)return"";const u=this.allocBytes(l),h=this.allocUsize();try{return I(this.exports.ghostty_paste_encode(s.ptr,s.len,r?1:0,u,l,h),"ghostty_paste_encode"),this.readOwnedUtf8(u,this.readUsize(h))}finally{this.freeBytes(u,l),this.freeUsize(h)}}finally{s.free(),this.freeUsize(i)}}}async function sr(n){const e=n.startsWith("file://"),t=e?decodeURIComponent(new URL(n).pathname):n;if((e||t.startsWith("/")||t.startsWith("./")||t.startsWith("../")||/^[A-Za-z]:[\\/]/.test(t))&&typeof Bun<"u")return Bun.file(t).arrayBuffer();const i=await fetch(n);if(!i.ok)throw new Error(`failed to load ghostty wasm: ${i.status} ${i.statusText}`);return i.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,Ce=24,et=9,Ne=17,ir=48,Yt="ghostty-official",Fe=9,Ge=1e3,Ue=1002,ze=1003,tt=1007,He=1047,Pe=1049,or=[Fe,Ge,Ue,ze],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(){p(this,"active",{baseY:0,viewportY:0,length:Ce,getLine:e=>{const t=e-this.active.viewportY,s=this.visibleLines[t];return typeof s=="string"?new cr(s):null}});p(this,"visibleLines",Array.from({length:Ce},()=>""))}setViewport(e,t,s,i){this.active.viewportY=e,this.active.baseY=t,this.active.length=s,this.visibleLines=i}}const ur={deleteContentBackward:"Backspace",deleteContentForward:"Delete",insertLineBreak:"Enter",insertParagraph:"Enter"};function hr(n){return!(n.key.length===1&&!n.ctrlKey&&!n.altKey&&!n.metaKey)}function fr(n,e){const t=n.slice(0,e).map(s=>s.text);for(;t.length<e;)t.push("");return t}function Be(n){return zt({shiftKey:!!n.shiftKey,ctrlKey:!!n.ctrlKey,altKey:!!n.altKey,metaKey:!!n.metaKey,getModifierState:()=>!1})}class mr{constructor(){p(this,"terminal",null)}activate(e){this.terminal=e instanceof Ve?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 Ve{constructor(e,t,s,i,r,o){p(this,"buffer",new dr);p(this,"_core",{_renderService:{dimensions:{css:{cell:{width:et,height:Ne}}}}});p(this,"options");p(this,"element",null);p(this,"textarea",null);p(this,"cols",Et);p(this,"rows",Ce);p(this,"bindings");p(this,"terminalHandle");p(this,"keyEncoderHandle");p(this,"mouseEncoderHandle");p(this,"renderState");p(this,"dataListeners",new Set);p(this,"selectionListeners",new Set);p(this,"lastNotifiedSelectionText",null);p(this,"addons",new Set);p(this,"screenElement",null);p(this,"renderer",null);p(this,"renderRaf",null);p(this,"disposed",!1);p(this,"disableStdin");p(this,"customKeyEventHandler",()=>!0);p(this,"imeIsComposing",!1);p(this,"lastCompositionCommit",null);p(this,"selectionState",Bt());p(this,"lineCache",new Map);p(this,"lastViewportOffset",0);p(this,"lastViewportRows",Ce);p(this,"lastRenderedRows",[]);p(this,"pointerDrag",{active:!1,moved:!1,mode:"character",lastClientX:null,lastClientY:null});p(this,"autoScrollTimer",null);p(this,"domEventDisposers",[]);p(this,"copyShortcutSuppressed",!1);p(this,"scrollbarThumb",null);p(this,"scrollbarFadeTimer",null);p(this,"pressedMouseButtons",new Set);p(this,"wheelPixelDelta",0);p(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,Ce,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 Ve(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(He)||this.isModeEnabled(Pe)}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(Fe),mouseNormal:this.isModeEnabled(Ge),mouseButton:this.isModeEnabled(Ue),mouseAny:this.isModeEnabled(ze),mouseUtf8:this.isModeEnabled(1005),mouseSgr:this.isModeEnabled(1006),mouseSgrPixels:this.isModeEnabled(1016),mouseUrxvt:this.isModeEnabled(1015),altScroll:this.isModeEnabled(tt),altScreen1047:this.isModeEnabled(He),altScreen1049:this.isModeEnabled(Pe)}}restoreModeSnapshot(e){this.bindings.setTerminalMode(this.terminalHandle,Fe,e.mouseX10),this.bindings.setTerminalMode(this.terminalHandle,Ge,e.mouseNormal),this.bindings.setTerminalMode(this.terminalHandle,Ue,e.mouseButton),this.bindings.setTerminalMode(this.terminalHandle,ze,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,He,e.altScreen1047),this.bindings.setTerminalMode(this.terminalHandle,Pe,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:Be(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:Be(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:Be(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:Be(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)||!hr(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"||r.isComposing||this.imeIsComposing)return;const o=ur[r.inputType??""];if(o){r.preventDefault();const h=this.encodeSyntheticKey(o);h&&this.emitData(h),this.clearTextarea();return}const l=r.data??"";if(!l)return;const u=this.lastCompositionCommit;if(u&&u.data===l&&Date.now()-u.at<40){this.lastCompositionCommit=null,r.preventDefault(),this.clearTextarea();return}this.lastCompositionCommit=null,r.preventDefault(),this.emitData(l),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)})}encodeSyntheticKey(e){const t={code:e,key:e,shiftKey:!1,ctrlKey:!1,altKey:!1,metaKey:!1,repeat:!1,isComposing:!1,getModifierState:()=>!1};return this.encodeKeyboardEvent(t,"press")}getInputRoutingState(){const e=this.isModeEnabled(Fe)||this.isModeEnabled(Ge)||this.isModeEnabled(Ue)||this.isModeEnabled(ze),t=this.isModeEnabled(He)||this.isModeEnabled(Pe);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 a=st(r);a.cursor.x!==null&&a.cursor.y!==null&&(o=a.cursor.x,l=a.cursor.y)}finally{Xe(r)}const u=o*s,h=l*i;e.style.left=`${u}px`,e.style.top=`${h}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 h of i)this.lineCache.set(e.offset+h.y,yt(h.cells,h.wrap));const r=bs(this.selectionState,this.lastViewportOffset,this.lastViewportRows,h=>this.getLineModel(h)),o=this.getSelectionText();this.renderer.render({meta:s,rows:i,cellDimensions:this.cellDimensions(),selectionRects:r,selectionColor:this.options.theme.selectionBackground});const l=fr(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 v;const s=(v=this.screenElement)==null?void 0:v.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),h=Math.max(this.lastViewportRows-1,0),a=Math.max(0,Math.min(u,Math.floor(o/i))),x=Math.max(0,Math.min(h,Math.floor(l/r)));return{line:this.lastViewportOffset+x,col:a}}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 pr(n){return Ve.create(n)}function wr({visible:n,canPaste:e,onCopy:t,onPaste:s,onDismiss:i}){const{t:r}=Ke();if(!n)return null;const o=l=>{l.preventDefault()};return f.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:[f.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:[f.jsx(Tn,{className:"h-4 w-4"}),r("terminal.copy")]}),e&&f.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:[f.jsx(_n,{className:"h-4 w-4"}),r("terminal.paste")]}),f.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:f.jsx(qt,{className:"h-4 w-4"})})]})}function Kt(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 yr="\x1B[?1049h\x1B[H\x1B[2J";function gr(n){return yr+Kt(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 Sr=1.3,_r=36,xr=500,Tr=12;function br(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,h=0,a=0,x=null,v=!1;const O=()=>{x!==null&&(clearTimeout(x),x=null)},E=T=>T?!!(T.closest(".scrollbar")||T.closest(".slider")||T.closest(".xterm-scroll-area")):!1,b=(T,R,P)=>{const U=P instanceof Element?P:null;if(E(U))return!0;const Q=document.elementFromPoint(T,R);if(E(Q))return!0;const S=s.querySelector(".xterm");if(!(S instanceof HTMLElement))return!1;const C=S.getBoundingClientRect(),F=T>=C.left&&T<=C.right,j=R>=C.top&&R<=C.bottom;return!F||!j?!1:T>=C.right-_r},z=()=>[s.querySelector(".xterm-viewport"),s.querySelector(".xterm-scrollable-element")].filter(R=>R instanceof HTMLElement),w=T=>{if(o===null)return null;for(let R=0;R<T.length;R+=1){const P=T.item(R);if(P&&P.identifier===o)return P}return null},N=T=>{if(O(),T.touches.length!==1)return;const R=T.touches.item(0);R&&(o=R.identifier,r=R.clientY,u=0,l=b(R.clientX,R.clientY,T.target),h=R.clientX,a=R.clientY,v=!1,l||(x=setTimeout(()=>{var U;x=null;const P=(e==null?void 0:e())??null;(U=P==null?void 0:P.startTouchSelection)!=null&&U.call(P,h,a,"word")&&(v=!0)},xr)))},Y=T=>{var F,j,M,X,q,te,ne,D,re;const R=w(T.touches)??T.touches.item(0);if(!R)return;if(v){const B=(e==null?void 0:e())??null;(F=B==null?void 0:B.updateTouchSelection)==null||F.call(B,R.clientX,R.clientY),T.cancelable&&T.preventDefault();return}if(x!==null&&Math.hypot(R.clientX-h,R.clientY-a)>Tr&&O(),l||(l=b(R.clientX,R.clientY,T.target),l&&(u=0)),l)return;const P=R.clientY,U=r-P;if(r=P,U===0)return;let Q=!1,S=!1;const C=(e==null?void 0:e())??null;if(C){const B=C==null?void 0:C._core,V=((q=(X=(M=(j=B==null?void 0:B._renderService)==null?void 0:j.dimensions)==null?void 0:M.css)==null?void 0:X.cell)==null?void 0:q.height)??18;u+=U*Sr;const L=u>0?Math.floor(u/V):Math.ceil(u/V);if(typeof C.handleViewportGesture=="function")L!==0&&(Q=C.handleViewportGesture({source:"touch",deltaY:L*V,clientX:R.clientX,clientY:R.clientY}),u-=L*V);else if(L!==0){const $=((ne=(te=C.buffer)==null?void 0:te.active)==null?void 0:ne.viewportY)??0;C.scrollLines(L);const le=((re=(D=C.buffer)==null?void 0:D.active)==null?void 0:re.viewportY)??0;Q=$!==le,S=L<0&&$<=0&&le<=0,u-=L*V}}else{const B=z();if(B.length===0)return;for(const V of B){const L=V.scrollTop;V.scrollTop+=U;const $=V.scrollTop;Math.abs($-L)>0&&(Q=!0),U<0&&$<=0&&(S=!0)}if(!Q){const V=s.querySelector(".xterm");if(V instanceof HTMLElement){const L=new WheelEvent("wheel",{bubbles:!0,cancelable:!0,deltaMode:WheelEvent.DOM_DELTA_PIXEL,deltaY:U}),$=V.dispatchEvent(L);Q=L.defaultPrevented||!$}}}T.cancelable&&(Q||S)&&T.preventDefault()},K=T=>{var P;if(O(),!(o===null||!w(T.changedTouches))&&(o=null,u=0,l=!1,v)){v=!1;const U=(e==null?void 0:e())??null;(P=U==null?void 0:U.endTouchSelection)==null||P.call(U)}},H=T=>{v&&T.preventDefault()};return s.addEventListener("touchstart",N,{passive:!0}),s.addEventListener("touchmove",Y,{passive:!1}),s.addEventListener("touchend",K,{passive:!0}),s.addEventListener("touchcancel",K,{passive:!0}),s.addEventListener("contextmenu",H),()=>{t.current=!1,O(),s.removeEventListener("touchstart",N),s.removeEventListener("touchmove",Y),s.removeEventListener("touchend",K),s.removeEventListener("touchcancel",K),s.removeEventListener("contextmenu",H)}},[n,e]),t}function Er({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 Rr({currentSize:n,containerSize:e,force:t=!1}){return t?!0:n.cols!==e.cols||n.rows!==e.rows}function Cr({deviceId:n,paneId:e,deviceConnected:t,isSelectionInvalid:s,onResize:i,onSync:r,getContainerRect:o}){const l=d.useRef(null),u=d.useRef(null),h=d.useRef(null),a=d.useRef(null),x=d.useRef(0),v=d.useRef([]),O=d.useRef(null),E=d.useRef(null),b=d.useRef(o),z=d.useRef(!1),w=d.useRef(i),N=d.useRef(r);d.useEffect(()=>{w.current=i},[i]),d.useEffect(()=>{N.current=r},[r]),d.useEffect(()=>{b.current=o},[o]);const Y=d.useCallback(()=>{var te,ne,D,re,B,V,L,$,le,_;const S=E.current,C=O.current;if(!S||!C||!S.element)return null;let F;try{const g=C.proposeDimensions();if(!g)throw new Error("fitAddon.proposeDimensions() returned null");F=Math.max(2,g.cols)}catch{const g=S._core,k=((re=(D=(ne=(te=g==null?void 0:g._renderService)==null?void 0:te.dimensions)==null?void 0:ne.css)==null?void 0:D.cell)==null?void 0:re.width)??9,W=(B=b.current)==null?void 0:B.call(b);if(!W||W.width===0)return null;F=Math.max(2,Math.floor(W.width/k))}const j=(V=b.current)==null?void 0:V.call(b);if(!j||j.height===0)return null;const M=S._core,X=((_=(le=($=(L=M==null?void 0:M._renderService)==null?void 0:L.dimensions)==null?void 0:$.css)==null?void 0:le.cell)==null?void 0:_.height)??17,q=Math.max(2,Math.floor(j.height/X));return{cols:F,rows:q}},[]),K=d.useCallback((S,C)=>{const F=E.current;F&&(F.cols===S&&F.rows===C||F.resize(S,C))},[]),H=d.useCallback((S,C=!1)=>{if(!n||!e||!t||s&&S!=="sync"||!C&&Date.now()<x.current||!E.current)return!1;const j=Y();if(!j)return!1;const{cols:M,rows:X}=j,q=h.current;return!C&&q&&q.cols===M&&q.rows===X?(K(M,X),!0):(K(M,X),S==="sync"?N.current(M,X):w.current(M,X),h.current={cols:M,rows:X},a.current={cols:M,rows:X,at:Date.now()},!0)},[K,t,n,s,Y,e]),T=d.useCallback((S="resize",C={})=>{const{immediate:F=!1,force:j=!1}=C;u.current!==null&&(window.clearTimeout(u.current),u.current=null),l.current!==null&&(cancelAnimationFrame(l.current),l.current=null);const M=()=>{l.current=requestAnimationFrame(()=>{l.current=null,H(S,j)})};if(F){M();return}u.current=window.setTimeout(()=>{u.current=null,M()},150)},[H]),R=d.useCallback(()=>{for(const S of v.current)window.clearTimeout(S);v.current=[]},[]),P=d.useCallback(()=>{var C;R(),T("sync",{immediate:!0,force:!0});const S=window.setTimeout(()=>{T("sync",{immediate:!0,force:!0})},60);v.current.push(S),typeof document<"u"&&"fonts"in document&&((C=document.fonts)!=null&&C.ready)&&document.fonts.ready.then(()=>{T("sync",{immediate:!0,force:!0})}).catch(()=>{})},[R,T]);d.useEffect(()=>{let S=null;const C=()=>{S!==null&&cancelAnimationFrame(S),S=requestAnimationFrame(()=>{S=null,T("resize")})};return window.addEventListener("resize",C),()=>{window.removeEventListener("resize",C),S!==null&&cancelAnimationFrame(S)}},[T]),d.useEffect(()=>{const S=()=>{var te;const M=E.current,X=Y();if(!M||!X)return;if(!Rr({currentSize:{cols:Math.max(2,M.cols),rows:Math.max(2,M.rows)},containerSize:X})){(te=M.refresh)==null||te.call(M);return}T("sync",{force:!0})},C=()=>{if(document.visibilityState!=="visible"){z.current=!0;return}z.current&&(z.current=!1,S())},F=()=>{z.current=!0},j=()=>{z.current&&(z.current=!1,S())};return document.addEventListener("visibilitychange",C),window.addEventListener("blur",F),window.addEventListener("focus",j),()=>{document.removeEventListener("visibilitychange",C),window.removeEventListener("blur",F),window.removeEventListener("focus",j)}},[Y,T]),d.useEffect(()=>()=>{R(),u.current!==null&&window.clearTimeout(u.current),l.current!==null&&cancelAnimationFrame(l.current)},[R]);const U=d.useCallback(S=>{O.current=S},[]),Q=d.useCallback(S=>{E.current=S},[]);return{scheduleResize:T,runPostSelectResize:P,clearPostSelectResizeTimers:R,setFitAddon:U,setTerminal:Q,lastReportedSize:h,pendingLocalSize:a,suppressLocalResizeUntil:x}}const vr={fontFamily:Xt,fontSize:13,scrollback:1e4},rt="tmex:terminal-mode-cache";function Mr(n,e){try{const t=sessionStorage.getItem(rt);return t?JSON.parse(t)[`${n}:${e}`]??null:null}catch{return null}}function Dr(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 Ar(){return{mouseX10:!1,mouseNormal:!0,mouseButton:!1,mouseAny:!1,mouseUtf8:!1,mouseSgr:!0,mouseSgrPixels:!1,mouseUrxvt:!1,altScroll:!0,altScreen1047:!1,altScreen1049:!1}}function Or(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=Ar();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 kr(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 Ir(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 Vt=d.forwardRef(({deviceId:n,paneId:e,theme:t,inputMode:s,deviceConnected:i,isSelectionInvalid:r,onResize:o,onSync:l,children:u},h)=>{const[a,x]=d.useState(null),[v,O]=d.useState(!1),E=J(_=>_.sendInput),{t:b}=Ke(),z=d.useMemo(()=>{switch(t){case"light":return Ot;default:return At}},[t]),w=d.useRef(null),N=d.useRef(null),Y=d.useRef(null),K=d.useRef(n),H=d.useRef(e),T=d.useRef(n),R=d.useRef(e),P=d.useRef(i&&!r),U=d.useRef(s),Q=d.useRef(z),S=d.useRef(!1),C=d.useRef(!1),F=d.useRef(null),j=d.useRef(!1),M=d.useCallback((_,g,k)=>{!(_!=null&&_.exportModeSnapshot)||!g||!k||Dr(g,k,_.exportModeSnapshot())},[]),X=d.useCallback(()=>a,[a]);br(w,X),d.useEffect(()=>{K.current=n,H.current=e,C.current=!1},[n,e]),d.useEffect(()=>{P.current=i&&!r},[i,r]),d.useEffect(()=>{U.current=s},[s]),d.useEffect(()=>{Q.current=z},[z]);const q=d.useCallback(_=>{if(!_||s!=="direct"||!P.current)return;const g=K.current,k=H.current;!g||!k||E(g,k,_,!1)},[s,E]),{pendingLocalSize:te,scheduleResize:ne,runPostSelectResize:D,setFitAddon:re,setTerminal:B}=Cr({deviceId:n,paneId:e,deviceConnected:i,isSelectionInvalid:r,onResize:o,onSync:l,getContainerRect:()=>{const _=w.current;if(!_)return null;const g=_.getBoundingClientRect();return{width:g.width,height:g.height}}});d.useEffect(()=>{let _=!1,g=null;return pr({...vr,theme:Q.current,disableStdin:U.current==="editor"}).then(k=>{if(_){k.dispose();return}g=k,N.current&&k.open(N.current),kr(k),x(k)}),()=>{_=!0,x(null),Ir(g),g==null||g.dispose()}},[]),d.useEffect(()=>{!a||!("setTheme"in a)||a.setTheme(z)},[a,z]),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 V=d.useMemo(()=>a?{onResetTerminal:_=>{K.current===_&&(M(a,T.current,R.current),j.current=!0,a.reset(),S.current=!1,D())},onApplyHistory:(_,g,k)=>{var ie;if(K.current!==_)return;const W=Or(Mr(K.current,H.current),k);W&&((ie=a.restoreModeSnapshot)==null||ie.call(a,W));const G=k?gr(g):Kt(g);C.current=!0,a.write(G),j.current=!1,T.current=K.current,R.current=H.current,M(a,K.current,H.current)},onFlushBuffer:(_,g)=>{if(K.current===_){for(const k of g){const W=Mt(k,S.current);S.current=W.endedWithCR,a.write(W.normalized)}C.current&&(a.buffer.active.baseY<=1&&a.scrollToTop(),C.current=!1),T.current=K.current,R.current=H.current,M(a,K.current,H.current)}},onOutput:(_,g,k)=>{if(K.current!==_||H.current!==g)return;const W=Mt(k,S.current);S.current=W.endedWithCR,a.write(W.normalized),C.current&&(a.buffer.active.baseY<=1&&a.scrollToTop(),C.current=!1),T.current=K.current,R.current=H.current,M(a,K.current,H.current)}}:{},[a,M,D]);d.useEffect(()=>{a?F.current!==a&&(S.current=!1,T.current=K.current,R.current=H.current,F.current=a):F.current=null},[a]),d.useEffect(()=>{if(!(!a||!n||!e))return()=>{if(j.current){j.current=!1;return}M(a,T.current,R.current)}},[n,a,e,M]),d.useEffect(()=>{dt(V)},[V]),d.useEffect(()=>()=>{dt({})},[]),d.useEffect(()=>{if(!a){Y.current=null,re(null),B(null);return}const _=new mr;return a.loadAddon(_),Y.current=_,re(_),B(a),D(),()=>{try{_.dispose()}finally{Y.current=null,re(null),B(null)}}},[a,D,re,B]),d.useEffect(()=>{const _=w.current;if(!_)return;let g=null;const k=new ResizeObserver(()=>{g!==null&&cancelAnimationFrame(g),g=requestAnimationFrame(()=>{g=null,ne("resize")})});return k.observe(_),()=>{k.disconnect(),g!==null&&cancelAnimationFrame(g)}},[ne]),d.useEffect(()=>{if(!a||!n||!e)return;const _=a.onData(g=>{!i||r||q(g)});return a.attachCustomKeyEventHandler(g=>!i||r||g.type!=="keydown"||s!=="direct"?!0:g.shiftKey&&g.key==="Enter"?(g.preventDefault(),q("\x1B[13;2u"),!1):!0),()=>{_.dispose(),a.attachCustomKeyEventHandler(()=>!0)}},[a,i,r,s,q,n,e]),d.useEffect(()=>{if(!(a!=null&&a.onSelectionChange)){O(!1);return}const _=a.onSelectionChange(g=>{O(!!g)});return()=>{_.dispose(),O(!1)}},[a]);const L=d.useCallback(()=>{var g;if(!a)return;const _=((g=a.getSelection)==null?void 0:g.call(a))??"";_&&Gt(_).then(()=>{xe.success(b("terminal.copied"))}).catch(()=>{xe.error(b("terminal.copyFailed"))}).finally(()=>{var k;(k=a.clearSelection)==null||k.call(a),a.focus()})},[a,b]),$=d.useCallback(()=>{var g;if(!a)return;((g=navigator.clipboard)!=null&&g.readText?navigator.clipboard.readText():Promise.reject(new Error("clipboard unavailable"))).then(k=>{var W;k&&a.paste(k),(W=a.clearSelection)==null||W.call(a),a.focus()}).catch(()=>{xe.error(b("terminal.pasteFailed"))})},[a,b]),le=d.useCallback(()=>{var _;(_=a==null?void 0:a.clearSelection)==null||_.call(a),a==null||a.focus()},[a]);return d.useImperativeHandle(h,()=>({write:_=>a==null?void 0:a.write(_),reset:()=>{a==null||a.reset(),S.current=!1},scrollToBottom:()=>a==null?void 0:a.scrollToBottom(),resize:(_,g)=>a==null?void 0:a.resize(_,g),getTerminal:()=>a??null,getSize:()=>a?{cols:Math.max(2,a.cols),rows:Math.max(2,a.rows)}:null,runPostSelectResize:()=>D(),scheduleResize:(_,g)=>ne(_,g),calculateSizeFromContainer:()=>{var Me,oe,ye,ue,ae,Z,ge,he,Se,be,De,Ae,Oe,ke,Ee,c;const _=w.current,g=a,k=Y.current;if(!_||!g)return null;const W=_.getBoundingClientRect();if(W.width===0||W.height===0)return null;const G=g._core;let ie;if(k)try{const m=k.proposeDimensions();if(m)ie=Math.max(2,m.cols);else{const y=((ue=(ye=(oe=(Me=G==null?void 0:G._renderService)==null?void 0:Me.dimensions)==null?void 0:oe.css)==null?void 0:ye.cell)==null?void 0:ue.width)??9;ie=Math.max(2,Math.floor(W.width/y))}}catch{const m=((he=(ge=(Z=(ae=G==null?void 0:G._renderService)==null?void 0:ae.dimensions)==null?void 0:Z.css)==null?void 0:ge.cell)==null?void 0:he.width)??9;ie=Math.max(2,Math.floor(W.width/m))}else{const m=((Ae=(De=(be=(Se=G==null?void 0:G._renderService)==null?void 0:Se.dimensions)==null?void 0:be.css)==null?void 0:De.cell)==null?void 0:Ae.width)??9;ie=Math.max(2,Math.floor(W.width/m))}const pe=((c=(Ee=(ke=(Oe=G==null?void 0:G._renderService)==null?void 0:Oe.dimensions)==null?void 0:ke.css)==null?void 0:Ee.cell)==null?void 0:c.height)??17,We=Math.max(2,Math.floor(W.height/pe));return{cols:ie,rows:We}},getPendingLocalSize:()=>te.current}),[a,te,D,ne]),f.jsxs("div",{className:"flex h-full w-full flex-col",style:{backgroundColor:z.background},"data-terminal-engine":Yt,children:[f.jsxs("div",{ref:w,className:"relative min-h-0 w-full flex-1",children:[f.jsx("div",{ref:N,className:"absolute inset-0"}),f.jsx(wr,{visible:v,canPaste:s==="direct"&&i&&!r,onCopy:L,onPaste:$,onDismiss:le})]}),u]})});Vt.displayName="Terminal";const Nr=1200,Hr=2e3;function me(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<Nr);return t.length===0?null:t.reduce((s,i)=>i.at>s.at?i:s)}function ve(n,e=Date.now()){return!n||e-n.at>Hr?null:n}function Pr(n){const e=n.now??Date.now(),t=Wt(n.recentSelectRequests,e);if(t&&!me(t,n.activePaneFromEvent)||me(n.currentRoute,n.activePaneFromEvent)||me(n.lastHandledActive,n.activePaneFromEvent))return!0;const s=ve(n.pendingUserSelection,e);return!!(s&&!me(s,n.activePaneFromEvent))}function Br(n){const e=n.now??Date.now(),t=Wt(n.recentSelectRequests,e),s=ve(n.pendingUserSelection,e);return!!(s&&!me(s,n.snapshotActive)||t&&!me(t,n.snapshotActive))}function Lr(n){const e=n.now??Date.now(),t=ve(n.pendingUserSelection,e);return!(t&&me(t,n.routeTarget)||n.snapshotActive&&me(n.snapshotActive,n.routeTarget))}const Fr=[{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 f.jsx("div",{className:"terminal-shortcuts-strip","data-testid":"terminal-shortcuts-strip",children:f.jsx("div",{className:"shortcut-row flex items-center gap-1.5 py-2 overflow-x-auto scrollbar-thin","data-testid":"editor-shortcuts-row",children:Fr.map(o=>f.jsx(fe,{variant:"ghost",size:"sm",className:"terminal-shortcut-btn 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 Yr(){var Ee;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),h=d.useRef(!1),a=d.useRef(!1),x=d.useRef(null),v=J(c=>c.selectPane),O=J(c=>e?c.snapshots[e]:void 0),E=J(c=>{var m;return e?(m=c.deviceErrors)==null?void 0:m[e]:void 0}),b=J(c=>{var m;return e?((m=c.deviceConnected)==null?void 0:m[e])??!1:!1}),z=kt(c=>{var m;return((m=c.settings)==null?void 0:m.siteName)??"tmex"}),w=d.useMemo(()=>ot(s),[s]),N=d.useMemo(()=>e&&w?`${e}:${w}`:null,[e,w]),[Y,K]=d.useState(!1),[H,T]=d.useState(""),R=d.useRef(!1),P=!b||!w,[U,Q]=d.useState(!1),S=ce(c=>c.inputMode),C=ce(c=>c.theme),F=ce(c=>c.editorSendWithEnter),j=ce(c=>c.setEditorSendWithEnter),M=ce(c=>c.addEditorHistory),X=ce(c=>c.setEditorDraft),q=ce(c=>c.removeEditorDraft),te=ce(c=>N?c.editorDrafts[N]??"":""),ne=d.useMemo(()=>Jt(),[]),D=(Ee=O==null?void 0:O.session)==null?void 0:Ee.windows,re=C==="light"?Ot:At,{data:B}=It({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}),V=d.useMemo(()=>{if(e)return B==null?void 0:B.devices.find(c=>c.id===e)},[e,B==null?void 0:B.devices]),L=d.useMemo(()=>{if(!(!t||!D))return D.find(c=>c.id===t)},[t,D]),$=d.useMemo(()=>{if(!(!w||!L))return L.panes.find(c=>c.id===w)},[w,L]),le=!!D,W=!!(le&&!!t&&!L||le&&!!t&&!!w&&!!L&&!$?n("wsError.checkGateway"):null),G=!!(b&&w&&!W),ie=d.useMemo(()=>{if(!L||!$)return null;const c=(V==null?void 0:V.name)??e;return Nt({paneIdx:$.index,windowIdx:L.index,paneTitle:$.title,windowName:L.name,windowCustomName:L.customName,deviceName:c})},[V==null?void 0:V.name,e,$,L]),pe=d.useMemo(()=>{if(!D||D.length===0)return null;const c=D.find(y=>y.active),m=c==null?void 0:c.panes.find(y=>y.active);return!c||!m?null:{windowId:c.id,paneId:m.id}},[D]),We=d.useCallback((c,m)=>{!e||!w||J.getState().resizePane(e,w,c,m)},[e,w]),Me=d.useCallback((c,m)=>{!e||!w||J.getState().syncPaneSize(e,w,c,m)},[e,w]),oe=d.useCallback((c,m)=>{const y=u.current,A=(y==null?void 0:y.calculateSizeFromContainer())??(y==null?void 0:y.getSize())??void 0;if(A)return A;if(!c||!m||!D)return;const ee=D.find(we=>we.id===c),se=ee==null?void 0:ee.panes.find(we=>we.id===m);if(!(!se||se.width<=1||se.height<=1))return{cols:se.width,rows:se.height}},[D]);d.useEffect(()=>{const c=()=>{K(window.innerWidth<768||"ontouchstart"in window)};return c(),window.addEventListener("resize",c),()=>window.removeEventListener("resize",c)},[]),d.useEffect(()=>{if(!Y||!ne||a.current)return;a.current=!0;const c=()=>{window.scrollTo(0,1)},m=window.requestAnimationFrame(c),y=window.setTimeout(c,120),A=window.setTimeout(c,420);return()=>{window.cancelAnimationFrame(m),window.clearTimeout(y),window.clearTimeout(A)}},[ne,Y]),d.useEffect(()=>{e&&(h.current=!1,ge.current=null,he.current=null,x.current=null,ue.current=[])},[e]),d.useEffect(()=>{b||(h.current=!1)},[b]),d.useEffect(()=>{if(!e||!b||!t||!D)return;if(D.length===0){i("/devices",{replace:!0});return}const c=D.find(y=>y.id===t);if(!c)return;if(!w){const y=c.panes.find(A=>A.active)??c.panes[0];y&&i(`/devices/${e}/windows/${t}/panes/${_e(y.id)}`,{replace:!0});return}if(!c.panes.find(y=>y.id===w)){const y=c.panes.find(A=>A.active)??c.panes[0];y&&i(`/devices/${e}/windows/${t}/panes/${_e(y.id)}`,{replace:!0});return}},[e,b,D,t,w,i]),d.useEffect(()=>{if(!e||!b||!D||D.length===0||t&&w||h.current)return;const c=D.find(y=>y.active)??D[0],m=c.panes.find(y=>y.active)??c.panes[0];m&&(h.current=!0,i(`/devices/${e}/windows/${c.id}/panes/${_e(m.id)}`,{replace:!0}))},[b,e,i,w,t,D]);const ye=d.useRef(null);d.useEffect(()=>{ye.current=null},[e,w]),d.useEffect(()=>{if(!e||!t||!w||P||!b)return;const c=`${e}:${t}:${w}`;if(ye.current===c)return;ye.current=c;const m=oe(t,w);ae(t,w),v(e,t,w,m)},[b,e,oe,P,w,v,t]),d.useEffect(()=>{if(!e||!b||!t||!w)return;const c={windowId:t,paneId:w};Lr({routeTarget:c,snapshotActive:pe,pendingUserSelection:x.current})&&(x.current={windowId:c.windowId,paneId:c.paneId,at:Date.now()})},[b,e,w,pe,t]);const ue=d.useRef([]),ae=d.useCallback((c,m)=>{const y=Date.now(),A=[...ue.current.filter(ee=>y-ee.at<2e3),{windowId:c,paneId:m,at:y}];ue.current=A.slice(-8)},[]),Z=J(c=>e?c.activePaneFromEvent[e]:void 0),ge=d.useRef(null);d.useEffect(()=>{if(!e||!b||!t||!w||!Z)return;const c=Date.now(),m=ve(x.current,c);if(x.current=m,Pr({now:c,pendingUserSelection:m,activePaneFromEvent:Z,currentRoute:{windowId:t,paneId:w},recentSelectRequests:ue.current,lastHandledActive:ge.current}))return;ge.current={...Z},m&&m.windowId===Z.windowId&&m.paneId===Z.paneId&&(x.current=null);const y=oe(Z.windowId,Z.paneId);ae(Z.windowId,Z.paneId),v(e,Z.windowId,Z.paneId,y),i(`/devices/${e}/windows/${Z.windowId}/panes/${_e(Z.paneId)}`,{replace:!0})},[e,b,t,w,Z,ae,oe,v,i]);const he=d.useRef(null);d.useEffect(()=>{if(!e||!b||!D||D.length===0)return;const c=ue.current,m=D.find(je=>je.active);if(!m)return;const y=m.panes.find(je=>je.active);if(!y)return;const A={windowId:m.id,paneId:y.id},ee=Date.now(),se=ve(x.current,ee);if(x.current=se,Br({now:ee,pendingUserSelection:se,snapshotActive:A,recentSelectRequests:c})||he.current&&he.current.windowId===A.windowId&&he.current.paneId===A.paneId||(he.current={...A},se&&se.windowId===A.windowId&&se.paneId===A.paneId&&(x.current=null),t===A.windowId&&w===A.paneId))return;const we=oe(A.windowId,A.paneId);ae(A.windowId,A.paneId),v(e,A.windowId,A.paneId,we),i(`/devices/${e}/windows/${A.windowId}/panes/${_e(A.paneId)}`,{replace:!0})},[e,b,D,t,w,ae,oe,v,i]);const Se=J(c=>e?c.pendingCreateWindowAt[e]:void 0);d.useEffect(()=>{if(!e||!b||!Se)return;const c=5e3,m=Date.now()-Se;if(m>c){J.getState().clearPendingCreateWindow(e);return}if(!pe){const ee=window.setTimeout(()=>{J.getState().clearPendingCreateWindow(e)},c-m);return()=>window.clearTimeout(ee)}const y=pe;if(t===y.windowId&&w===y.paneId){const ee=window.setTimeout(()=>{J.getState().clearPendingCreateWindow(e)},c-m);return()=>window.clearTimeout(ee)}x.current={windowId:y.windowId,paneId:y.paneId,at:Date.now()};const A=oe(y.windowId,y.paneId);ae(y.windowId,y.paneId),v(e,y.windowId,y.paneId,A),i(`/devices/${e}/windows/${y.windowId}/panes/${_e(y.paneId)}`,{replace:!0}),J.getState().clearPendingCreateWindow(e)},[e,b,Se,pe,t,w,ae,oe,v,i]),d.useEffect(()=>{if(!G||!$||P)return;const c=u.current,m=c==null?void 0:c.getTerminal();if(!m)return;const y=Math.max(2,Math.floor($.width||0)),A=Math.max(2,Math.floor($.height||0));if(!y||!A)return;const ee=Date.now(),se={cols:y,rows:A},we=(c==null?void 0:c.getPendingLocalSize())??null;Er({now:ee,remoteSize:se,pendingLocalSize:we})&&(m.cols===y&&m.rows===A||m.resize(y,A))},[G,P,$]),d.useEffect(()=>{const c=window.requestAnimationFrame(()=>{var y;(y=u.current)==null||y.scrollToBottom()}),m=window.setTimeout(()=>{var y;(y=u.current)==null||y.scrollToBottom()},120);return()=>{window.cancelAnimationFrame(c),window.clearTimeout(m)}},[S]),d.useEffect(()=>{E!=null&&E.message&&xe.error(E.message)},[E==null?void 0:E.message]),d.useEffect(()=>(document.title=Zt(ie),()=>{document.title=z}),[z,ie]),d.useEffect(()=>{const c=()=>{var m;(m=u.current)==null||m.scrollToBottom()};return window.addEventListener("tmex:jump-to-latest",c),()=>{window.removeEventListener("tmex:jump-to-latest",c)}},[]),d.useEffect(()=>{const c=m=>{const{deviceId:y,windowId:A,paneId:ee}=m.detail;y===e&&(x.current={windowId:A,paneId:ee,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 be=d.useCallback(c=>{if(!e||!w||!G)return;J.getState().sendInput(e,w,c,!1)},[G,e,w]),De=d.useCallback(()=>{if(!G){xe.error(n("wsError.checkGateway"));return}if(!e||!w||!H.trim())return;Q(!0),window.setTimeout(()=>Q(!1),150);const c=F?`${H}\r`:H;J.getState().sendInput(e,w,c,!1),M(H),N&&q(N),T("")},[M,G,e,N,F,H,q,w,n]),Ae=d.useCallback(()=>{if(!G){xe.error(n("wsError.checkGateway"));return}if(!e||!w||!H.trim())return;Q(!0),window.setTimeout(()=>Q(!1),150);const c=H.split(/\r?\n/),m=J.getState();for(const y of c)y.trim()&&m.sendInput(e,w,`${y}\r`,!1);M(H),N&&q(N),T("")},[M,G,e,N,H,q,w,n]),Oe=d.useCallback(()=>{var c;(c=l.current)==null||c.focus({preventScroll:!0})},[]);if(!e)return f.jsx("div",{className:"flex h-full items-center justify-center p-4",children:f.jsx("div",{className:"rounded-lg border border-dashed border-border px-4 py-3 text-sm text-muted-foreground",children:n("device.noDevices")})});const ke=!b&&!E;return f.jsxs("div",{className:"flex h-full min-h-0 flex-col bg-background","data-testid":"device-page",children:[f.jsxs("div",{className:`flex-1 relative overflow-hidden min-h-0 min-w-0 ${Y&&S==="editor"?"pb-1":""}`,children:[f.jsx("div",{className:"h-full px-3 py-1 min-h-0 min-w-0 w-full relative flex rounded-xl",style:{backgroundColor:re.background},children:b&&w?f.jsx("div",{ref:r,className:"flex-1 h-full min-h-0 w-full","data-virtual-keyboard-avoid":!0,children:f.jsx(Vt,{ref:u,deviceId:e,paneId:w,theme:C,inputMode:S,deviceConnected:b,isSelectionInvalid:W,onResize:We,onSync:Me,children:S==="direct"&&f.jsx(Dt,{onSend:be,disabled:!G,isMobile:Y,inputMode:S})},`${e}:${w}`)}):f.jsx("div",{className:"absolute inset-0 flex flex-col items-center justify-center p-8 text-center",children:f.jsx("div",{className:"max-w-sm space-y-4",children:b?t?f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"h-12 w-12 rounded-full bg-muted flex items-center justify-center mx-auto",children:f.jsx($e,{className:"h-6 w-6 text-muted-foreground animate-spin"})}),f.jsx("h3",{className:"text-lg font-medium",children:n("terminal.connecting")})]}):f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"h-12 w-12 rounded-full bg-muted flex items-center justify-center mx-auto",children:f.jsx("span",{className:"text-2xl text-muted-foreground",children:"📋"})}),f.jsx("h3",{className:"text-lg font-medium",children:n("window.noWindowSelected")}),f.jsx("p",{className:"text-sm text-muted-foreground",children:n("window.selectWindowToStart")})]}):f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"h-12 w-12 rounded-full bg-muted flex items-center justify-center mx-auto",children:f.jsx("span",{className:"text-2xl text-muted-foreground",children:"🔌"})}),f.jsx("h3",{className:"text-lg font-medium",children:n("device.disconnected")}),f.jsx("p",{className:"text-sm text-muted-foreground",children:n("device.connectToStart")})]})})})}),ke&&f.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background/85 backdrop-blur-sm","data-testid":"terminal-status-overlay",children:f.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:[f.jsx("div",{className:"h-7 w-7 rounded-full border-2 border-primary border-t-transparent animate-spin"}),f.jsx("span",{className:"text-xs text-muted-foreground","data-testid":"terminal-status-text",children:n("terminal.connecting")})]})})]}),S==="editor"&&f.jsxs("div",{ref:o,"data-virtual-keyboard-avoid":!0,className:"editor-mode-input bg-card/85 backdrop-blur-sm",children:[Y&&f.jsx(Dt,{onSend:be,onFocusEditor:Oe,disabled:!G,isMobile:Y,inputMode:S}),f.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:H,onChange:c=>{const m=c.target.value;if(T(m),!!N){if(m){X(N,m);return}q(N)}},placeholder:n("terminal.inputPlaceholder"),onCompositionStart:()=>{R.current=!0},onCompositionEnd:()=>{R.current=!1}}),f.jsx("div",{className:"actions mt-2",children:f.jsxs("div",{className:"send-row flex flex-wrap items-center justify-end gap-2","data-testid":"editor-send-row",children:[f.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:[f.jsx(en,{size:"sm",checked:F,onCheckedChange:c=>j(!!c)}),f.jsx("span",{children:n("terminal.editorSendWithEnter")})]}),f.jsxs(fe,{variant:"outline",size:"sm","data-testid":"editor-clear",onMouseDown:c=>c.preventDefault(),onClick:()=>{var c;T(""),N&&q(N),Y&&S==="editor"&&((c=l.current)==null||c.focus({preventScroll:!0}))},title:n("terminal.clear"),children:[f.jsx(tn,{className:"h-4 w-4"}),n("terminal.clear")]}),f.jsxs(fe,{variant:"secondary",size:"sm","data-testid":"editor-send-line-by-line",onMouseDown:c=>c.preventDefault(),onClick:()=>{var c;Ae(),Y&&S==="editor"&&((c=l.current)==null||c.focus({preventScroll:!0}))},disabled:!G||U,children:[U?f.jsx($e,{className:"h-4 w-4 animate-spin"}):f.jsx(ut,{className:"h-4 w-4"}),n("terminal.editorSendLineByLine")]}),f.jsxs(fe,{variant:"default",size:"sm","data-testid":"editor-send",onMouseDown:c=>c.preventDefault(),onClick:()=>{var c;De(),Y&&S==="editor"&&((c=l.current)==null||c.focus({preventScroll:!0}))},disabled:!G||U,children:[U?f.jsx($e,{className:"h-4 w-4 animate-spin"}):f.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=J(a=>a.snapshots),r=kt(a=>{var x;return((x=a.settings)==null?void 0:x.siteName)??"tmex"}),o=n?i[n]:void 0,l=d.useMemo(()=>{var a;if(!(!e||!((a=o==null?void 0:o.session)!=null&&a.windows)))return o.session.windows.find(x=>x.id===e)},[e,o]),u=d.useMemo(()=>{if(!(!s||!l))return l.panes.find(a=>a.id===s)},[s,l]),h=d.useMemo(()=>l&&u?Nt({paneIdx:u.index,windowIdx:l.index,paneTitle:u.title,windowName:l.name,windowCustomName:l.customName,deviceName:r}):n??"",[l,u,r,n]);return f.jsx(f.Fragment,{children:h})}function Vr(){const{t:n}=Ke(),{deviceId:e,paneId:t}=it(),s=t?ot(t):void 0,i=ce(N=>N.inputMode),r=ce(N=>N.setInputMode),o=J(N=>{var Y;return e?((Y=N.deviceConnected)==null?void 0:Y[e])??!1:!1}),[l,u]=d.useState(!1),[h,a]=d.useState(!1),x=!!(s&&o),O=(It({queryKey:pn(e??"",s??""),queryFn:()=>mn(e??"",s??""),enabled:!!(e&&s),throwOnError:!1}).data??[]).some(N=>N.enabled),E=()=>{r(i==="direct"?"editor":"direct")},b=()=>{window.dispatchEvent(new CustomEvent("tmex:jump-to-latest"))},z=()=>{u(!0)},w=()=>{window.location.reload()};return f.jsxs(f.Fragment,{children:[f.jsx(fe,{variant:"ghost",size:"icon-sm",onClick:z,"aria-label":n("nav.refreshPage"),title:n("nav.refreshPage"),children:f.jsx(wn,{className:"h-4 w-4"})}),f.jsx(fe,{variant:"ghost",size:"icon-sm",onClick:E,disabled:!x,"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"?f.jsx(nn,{className:"h-4 w-4"}):f.jsx(En,{className:"h-4 w-4"})}),f.jsx(fe,{variant:"ghost",size:"icon-sm",onClick:b,disabled:!x,"aria-label":n("nav.jumpToLatest"),title:n("nav.jumpToLatest"),children:f.jsx(gn,{className:"h-4 w-4"})}),f.jsxs(fe,{variant:"ghost",size:"icon-sm",className:"relative",onClick:()=>a(!0),disabled:!s,"data-testid":"watch-open-button","aria-label":n("watch.title"),title:n("watch.title"),children:[f.jsx(sn,{className:"h-4 w-4"}),O&&f.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&&f.jsx(rn,{open:h,onOpenChange:a,deviceId:e,paneId:s}),f.jsx(on,{open:l,onOpenChange:u,children:f.jsxs(ln,{children:[f.jsxs(an,{children:[f.jsx(cn,{children:n("nav.refreshPage")}),f.jsx(dn,{children:n("nav.refreshPageConfirm")})]}),f.jsxs(un,{children:[f.jsx(hn,{onClick:()=>u(!1),children:n("common.cancel")}),f.jsx(fn,{onClick:w,children:n("common.confirm")})]})]})})]})}export{Vr as PageActions,Kr as PageTitle,Yr as default};
26
+ //# sourceMappingURL=DevicePage-BXgCF7q_.js.map
@@ -0,0 +1,2 @@
1
+ import{u as N,r as j,a as Z,C as ee,M as se,b as M,j as e,N as G,B as w,P as W,A as ae,q as te,s as ie,O as ne,T as Y,v as re,w as ce,x as oe,y as de,z as le,Q as me,t as v,R as he,U as pe,V as ue,W as xe,Y as $,p as ve,Z as ye,_ as je,o as O,$ as ge,a0 as fe,a1 as we,a2 as Ne,D as De,d as Ce,e as be,f as Se,g as Ee,I as x,S as B,h as Q,i as z,k as V,l as g,a3 as Me,m as Pe}from"./index-DPqBlAbb.js";import{C as S,c as E,a as Ke,b as Ie,d as $e}from"./card-BfO0Uw5Q.js";function p(s){const c=s.trim();return c||void 0}function ke(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 Ae(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 Te(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 U(s,c){try{return(await s.json()).error??c}catch{return c}}function Le(){const{t:s}=N(),[c,m]=j.useState(!1),[a,y]=j.useState(null),[n,o]=j.useState(null),l=Z();j.useEffect(()=>{const r=()=>m(!0);return window.addEventListener("tmex:open-add-device",r),()=>window.removeEventListener("tmex:open-add-device",r)},[]);const{data:d,isLoading:u,isError:P}=ee({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=se(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(G,{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:()=>m(!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(Fe,{device:r,onEdit:()=>y(r),onDelete:()=>o(r)},r.id))}),c&&e.jsx(J,{mode:"create",onClose:()=>m(!1)}),a&&e.jsx(J,{mode:"edit",device:a,onClose:()=>y(null)}),e.jsx(ae,{open:n!==null,onOpenChange:r=>!r&&o(null),children:e.jsxs(te,{children:[e.jsxs(ie,{children:[e.jsx(ne,{className:"bg-destructive/10",children:e.jsx(Y,{className:"h-5 w-5 text-destructive"})}),e.jsx(re,{children:s("device.deleteConfirm")}),e.jsx(ce,{children:s("device.deleteDescription",{name:(n==null?void 0:n.name)??""})})]}),e.jsxs(oe,{children:[e.jsx(de,{children:s("common.cancel")}),e.jsx(le,{variant:"destructive",disabled:!n||C.isPending,onClick:()=>{n&&(C.mutate(n.id),o(null))},children:s("common.delete")})]})]})})]})}function Fe({device:s,onEdit:c,onDelete:m}){const{t:a}=N(),y=s.type==="local"?e.jsx(G,{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(Ke,{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(Ie,{className:"line-clamp-1 text-sm",title:s.name,children:s.name}),e.jsx($e,{className:"line-clamp-1 text-xs",children:n})]})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1",children:e.jsxs(he,{children:[e.jsx(pe,{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(ue,{className:"h-4 w-4"})}),e.jsxs(xe,{align:"end",children:[e.jsxs($,{"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($,{"data-testid":`device-card-test-${s.id}`,onClick:()=>o.mutate(),disabled:o.isPending,children:[e.jsx(ye,{className:"h-4 w-4"}),a("common.test")]}),e.jsx(je,{}),e.jsxs($,{"data-testid":`device-card-delete-${s.id}`,variant:"destructive",onClick:m,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(ge,{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(we,{to:`/devices/${s.id}`,"data-testid":`device-card-connect-${s.id}`,className:Ne({variant:"default",size:"sm"}),children:a("device.connect")})})]})]})}function J({mode:s,device:c,onClose:m}){const{t:a}=N(),y=Z(),[n,o]=j.useState(ke(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 U(i,a("device.createFailed")));return i.json()},onSuccess:()=>{y.invalidateQueries({queryKey:["devices"]}),v.success(a("common.success")),m()},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 U(i,a("device.updateFailed")));return i.json()},onSuccess:()=>{y.invalidateQueries({queryKey:["devices"]}),v.success(a("common.success")),m()},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(Ae(n)):await C.mutateAsync(Te(n))}catch{}finally{d(!1)}},r=`${s}-device-name`,K=`${s}-device-type`,k=`${s}-device-host`,A=`${s}-device-port`,T=`${s}-device-username`,F=`${s}-device-session`,H=`${s}-device-auth-mode`,R=`${s}-device-password`,L=`${s}-device-private-key`,q=`${s}-device-private-key-passphrase`,_={local:a("device.typeLocal"),ssh:a("device.typeSSH")},X={password:a("device.authPassword"),key:a("device.authKey"),agent:a("device.authAgent"),configRef:"SSH Config"},I=t=>e.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:t}),h=(t,i,f)=>e.jsxs("label",{className:"block text-xs font-medium text-foreground",htmlFor:t,children:[i,f&&e.jsx("span",{className:"ml-0.5 text-destructive",children:"*"})]});return e.jsx(De,{open:!0,onOpenChange:t=>!t&&m(),children:e.jsxs(Ce,{"data-testid":"device-dialog",className:"w-full max-w-2xl",children:[e.jsxs(be,{children:[e.jsx(Se,{children:a(u?"device.editDevice":"device.addDevice")}),e.jsx(Ee,{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:[I(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:[h(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:[h(K,a("device.type")),e.jsxs(B,{value:n.type,onValueChange:t=>{if(!t)return;const i=t;o(f=>({...f,type:i,authMode:i==="local"?"auto":f.authMode==="auto"?"password":f.authMode}))},disabled:u,children:[e.jsx(Q,{id:K,"data-testid":"device-type-select",className:"w-full",children:e.jsx(z,{placeholder:a("device.type"),children:t=>_[t]??""})}),e.jsxs(V,{children:[e.jsx(g,{value:"local",children:a("device.typeLocal")}),e.jsx(g,{value:"ssh",children:a("device.typeSSH")})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[h(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:[I(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:[h(k,a("device.host")),e.jsx(x,{id:k,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:[h(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:[h(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:[h(`${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:[I(a("device.sectionAuth")),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[h(H,a("device.authMode")),e.jsxs(B,{value:n.authMode,onValueChange:t=>{t&&o(i=>({...i,authMode:t}))},children:[e.jsx(Q,{id:H,className:"w-full",children:e.jsx(z,{placeholder:a("device.authMode"),children:t=>X[t]??""})}),e.jsxs(V,{children:[e.jsx(g,{value:"password",children:a("device.authPassword")}),e.jsx(g,{value:"key",children:a("device.authKey")}),e.jsx(g,{value:"agent",children:a("device.authAgent")}),e.jsx(g,{value:"configRef",children:"SSH Config"})]})]})]}),n.authMode==="password"&&e.jsxs("div",{className:"space-y-1.5",children:[h(R,a("device.password")),e.jsx(x,{id:R,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:[h(L,a("device.privateKey")),e.jsx(Me,{id:L,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:[h(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(Pe,{children:[e.jsx(w,{type:"button",variant:"outline",onClick:m,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 Oe(){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{Oe as PageActions,qe as PageTitle,Le as default};
2
+ //# sourceMappingURL=DevicesPage-JZ_FB4Hs.js.map
@@ -0,0 +1,22 @@
1
+ import{c as V,u as K,a as O,r as c,b as v,t as h,j as e,D as Qe,d as Ue,e as He,f as Ve,g as Je,I as C,S as J,h as W,i as G,k as Z,l as Q,m as We,B as y,L,P as Ge,n as A,o as Ze,X as rs,p as os,T as X,A as he,q as ue,s as ge,v as xe,w as pe,x as fe,y as je,z as ye,C as R,E as Xe,F as Ie,G as Re,H as Ye,J as cs,K as ds}from"./index-DPqBlAbb.js";import{C as q,a as D,b as _,c as I}from"./card-BfO0Uw5Q.js";import{R as ms}from"./refresh-cw-C1HbpgDO.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 hs=[["path",{d:"M2.97 12.92A2 2 0 0 0 2 14.63v3.24a2 2 0 0 0 .97 1.71l3 1.8a2 2 0 0 0 2.06 0L12 19v-5.5l-5-3-4.03 2.42Z",key:"lc1i9w"}],["path",{d:"m7 16.5-4.74-2.85",key:"1o9zyk"}],["path",{d:"m7 16.5 5-3",key:"va8pkn"}],["path",{d:"M7 16.5v5.17",key:"jnp8gn"}],["path",{d:"M12 13.5V19l3.97 2.38a2 2 0 0 0 2.06 0l3-1.8a2 2 0 0 0 .97-1.71v-3.24a2 2 0 0 0-.97-1.71L17 10.5l-5 3Z",key:"8zsnat"}],["path",{d:"m17 16.5-5-3",key:"8arw3v"}],["path",{d:"m17 16.5 4.74-2.85",key:"8rfmw"}],["path",{d:"M17 16.5v5.17",key:"k6z78m"}],["path",{d:"M7.97 4.42A2 2 0 0 0 7 6.13v4.37l5 3 5-3V6.13a2 2 0 0 0-.97-1.71l-3-1.8a2 2 0 0 0-2.06 0l-3 1.8Z",key:"1xygjf"}],["path",{d:"M12 8 7.26 5.15",key:"1vbdud"}],["path",{d:"m12 8 4.74-2.85",key:"3rx089"}],["path",{d:"M12 13.5V8",key:"1io7kd"}]],us=V("boxes",hs);/**
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 gs=[["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"}]],xs=V("rotate-ccw",gs);/**
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 ps=[["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"}]],$=V("save",ps);/**
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 fs=[["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"}]],Le=V("shield",fs);async function B(s,i){try{return(await s.json()).error??i}catch{return i}}const js=["openai-chat","openai-responses"],H="h-9 w-full";function ys({open:s,onOpenChange:i,provider:n}){const{t:a}=K(),d=O(),u=!!n,[w,p]=c.useState(""),[l,x]=c.useState(""),[f,m]=c.useState("openai-chat"),[j,b]=c.useState("");c.useEffect(()=>{s&&(p((n==null?void 0:n.name)??""),x((n==null?void 0:n.baseUrl)??""),m((n==null?void 0:n.protocol)??"openai-chat"),b(""))},[s,n]);const N=v({mutationFn:async()=>{const g={name:w.trim(),protocol:f,baseUrl:l.trim(),apiKey:j.trim(),enabled:!0},M=await fetch("/api/llm/providers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(g)});if(!M.ok)throw new Error(await B(M,a("settings.llm.createFailed")));return await M.json()},onSuccess:async g=>{await d.invalidateQueries({queryKey:["llm-providers"]}),g.modelsError?h.warning(a("settings.llm.modelsFetchFailed",{error:g.modelsError})):h.success(a("common.success")),i(!1)},onError:g=>{h.error(g instanceof Error?g.message:a("common.error"))}}),T=v({mutationFn:async()=>{if(!n)throw new Error(a("settings.llm.updateFailed"));const g={name:w.trim(),baseUrl:l.trim(),protocol:f};j.trim()&&(g.apiKey=j.trim());const M=await fetch(`/api/llm/providers/${n.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(g)});if(!M.ok)throw new Error(await B(M,a("settings.llm.updateFailed")));return await M.json()},onSuccess:async g=>{await d.invalidateQueries({queryKey:["llm-providers"]}),g.modelsError?h.warning(a("settings.llm.modelsFetchFailed",{error:g.modelsError})):h.success(a("common.success")),i(!1)},onError:g=>{h.error(g instanceof Error?g.message:a("common.error"))}}),E=N.isPending||T.isPending,r=w.trim().length>0&&l.trim().length>0&&(u||j.trim().length>0),P=()=>{!r||E||(u?T.mutate():N.mutate())};return e.jsx(Qe,{open:s,onOpenChange:i,children:e.jsxs(Ue,{className:"sm:max-w-lg","data-testid":u?`llm-provider-edit-modal-${n==null?void 0:n.id}`:"llm-provider-add-modal",children:[e.jsxs(He,{children:[e.jsx(Ve,{children:a(u?"settings.llm.editProvider":"settings.llm.addProvider")}),e.jsx(Je,{children:a("settings.llm.formHint")})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"block text-sm font-medium",htmlFor:"llm-form-name",children:a("settings.llm.name")}),e.jsx(C,{id:"llm-form-name","data-testid":"llm-provider-name-input",value:w,onChange:g=>p(g.target.value),placeholder:a("settings.llm.namePlaceholder"),className:H})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"block text-sm font-medium",htmlFor:"llm-form-baseurl",children:a("settings.llm.baseUrl")}),e.jsx(C,{id:"llm-form-baseurl","data-testid":"llm-provider-baseurl-input",value:l,onChange:g=>x(g.target.value),placeholder:a("settings.llm.baseUrlPlaceholder"),className:H}),e.jsx("p",{className:"text-xs text-muted-foreground",children:a("settings.llm.baseUrlHint")})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"block text-sm font-medium",htmlFor:"llm-form-protocol",children:a("settings.llm.protocol")}),e.jsxs(J,{value:f,onValueChange:g=>{g&&m(g)},children:[e.jsx(W,{id:"llm-form-protocol","data-testid":"llm-provider-protocol-select",className:H,children:e.jsx(G,{})}),e.jsx(Z,{children:js.map(g=>e.jsx(Q,{value:g,children:g},g))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"block text-sm font-medium",htmlFor:"llm-form-apikey",children:a("settings.llm.apiKey")}),e.jsx(C,{id:"llm-form-apikey","data-testid":"llm-provider-apikey-input","data-key-set":n!=null&&n.hasApiKey?"true":"false",type:"password",value:j,onChange:g=>b(g.target.value),placeholder:n!=null&&n.hasApiKey?a("settings.llm.apiKeySetPlaceholder"):a("settings.llm.apiKeyPlaceholder"),className:H})]})]}),e.jsxs(We,{children:[e.jsx(y,{variant:"outline",onClick:()=>i(!1),disabled:E,children:a("common.cancel")}),e.jsxs(y,{"data-testid":"llm-provider-form-submit",onClick:P,disabled:!r||E,children:[E?e.jsx(L,{className:"h-4 w-4 animate-spin"}):e.jsx($,{className:"h-4 w-4"}),a("common.save")]})]})]})})}function ws({models:s,onChange:i}){const{t:n}=K(),[a,d]=c.useState(""),u=(l,x)=>{i(s.map(f=>f.id===l?{...f,enabled:x}:f))},w=l=>{i(s.filter(x=>x.id!==l))},p=()=>{const l=a.trim();if(l){if(s.some(x=>x.id===l)){d("");return}i([...s,{id:l,source:"manual",enabled:!0}]),d("")}};return e.jsxs("div",{className:"space-y-3","data-testid":"llm-provider-models",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(C,{value:a,onChange:l=>d(l.target.value),onKeyDown:l=>{l.key==="Enter"&&(l.preventDefault(),p())},placeholder:n("settings.llm.addModelPlaceholder"),className:"h-9","data-testid":"llm-provider-add-model-input"}),e.jsxs(y,{type:"button",variant:"outline",size:"lg",onClick:p,disabled:!a.trim(),"data-testid":"llm-provider-add-model",children:[e.jsx(Ge,{className:"h-4 w-4"}),n("common.add")]})]}),s.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:n("settings.llm.modelsNotFetched")}):e.jsx("ul",{className:"max-h-56 space-y-1 overflow-y-auto rounded-lg border border-border bg-background p-2",children:s.map(l=>e.jsxs("li",{className:"flex items-center justify-between gap-2 rounded-md px-2 py-1.5","data-testid":`llm-provider-model-${l.id}`,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(A,{checked:l.enabled,onCheckedChange:x=>u(l.id,!!x),"data-testid":`llm-provider-model-toggle-${l.id}`}),e.jsx("span",{className:"truncate font-mono text-xs",children:l.id}),l.source==="manual"&&e.jsx(Ze,{variant:"secondary",children:n("settings.llm.modelManual")})]}),l.source==="manual"&&e.jsx(y,{type:"button",variant:"ghost",size:"icon-sm",onClick:()=>w(l.id),"data-testid":`llm-provider-model-remove-${l.id}`,children:e.jsx(rs,{className:"h-4 w-4"})})]},l.id))})]})}function bs(s){return s.modelDetails.map(i=>({id:i.id,source:i.source,enabled:i.enabled}))}function vs({open:s,onOpenChange:i,provider:n}){const{t:a}=K(),d=O(),[u,w]=c.useState([]);c.useEffect(()=>{s&&w(bs(n))},[s,n]);const p=v({mutationFn:async()=>{const l=u.filter(j=>j.source==="manual").map(j=>j.id),x=u.filter(j=>!j.enabled).map(j=>j.id),f={manualModels:l,disabledModels:x},m=await fetch(`/api/llm/providers/${n.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(f)});if(!m.ok)throw new Error(await B(m,a("settings.llm.updateFailed")));return await m.json()},onSuccess:async l=>{await d.invalidateQueries({queryKey:["llm-providers"]}),l.modelsError?h.warning(a("settings.llm.modelsFetchFailed",{error:l.modelsError})):h.success(a("common.success")),i(!1)},onError:l=>{h.error(l instanceof Error?l.message:a("common.error"))}});return e.jsx(Qe,{open:s,onOpenChange:i,children:e.jsxs(Ue,{className:"sm:max-w-lg","data-testid":`llm-provider-models-modal-${n.id}`,children:[e.jsxs(He,{children:[e.jsx(Ve,{children:a("settings.llm.modelsTitle",{name:n.name})}),e.jsx(Je,{children:a("settings.llm.modelsHint")})]}),e.jsx(ws,{models:u,onChange:w}),e.jsxs(We,{children:[e.jsx(y,{variant:"outline",onClick:()=>i(!1),disabled:p.isPending,children:a("common.cancel")}),e.jsxs(y,{"data-testid":`llm-provider-models-save-${n.id}`,onClick:()=>p.mutate(),disabled:p.isPending,children:[p.isPending?e.jsx(L,{className:"h-4 w-4 animate-spin"}):e.jsx($,{className:"h-4 w-4"}),a("common.save")]})]})]})})}function Ns(s){try{const i=new URL(s);return`${i.protocol}//${i.host}${i.pathname==="/"?"":i.pathname}`}catch{return s}}function ks({provider:s,onEdit:i}){const{t:n}=K(),a=O(),[d,u]=c.useState(!1),[w,p]=c.useState(!1),l=v({mutationFn:async m=>{const j=await fetch(`/api/llm/providers/${s.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:m})});if(!j.ok)throw new Error(await B(j,n("settings.llm.updateFailed")))},onSuccess:async()=>{await a.invalidateQueries({queryKey:["llm-providers"]})},onError:m=>{h.error(m instanceof Error?m.message:n("common.error"))}}),x=v({mutationFn:async()=>{const m=await fetch(`/api/llm/providers/${s.id}/refresh-models`,{method:"POST"});if(!m.ok)throw new Error(await B(m,n("settings.llm.refreshModelsFailed")))},onSuccess:async()=>{await a.invalidateQueries({queryKey:["llm-providers"]}),h.success(n("common.success"))},onError:m=>{h.error(m instanceof Error?m.message:n("common.error"))}}),f=v({mutationFn:async()=>{const m=await fetch(`/api/llm/providers/${s.id}`,{method:"DELETE"});if(!m.ok)throw new Error(await B(m,n("settings.llm.deleteFailed")))},onSuccess:async()=>{await a.invalidateQueries({queryKey:["llm-providers"]}),await a.invalidateQueries({queryKey:["llm-settings"]}),h.success(n("common.success"))},onError:m=>{h.error(m instanceof Error?m.message:n("common.error"))}});return e.jsxs("div",{className:"flex flex-col gap-3 rounded-lg border border-border bg-card p-3 sm:flex-row sm:items-center sm:justify-between","data-testid":`llm-provider-row-${s.id}`,"data-provider-name":s.name,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx(A,{checked:s.enabled,disabled:l.isPending,onCheckedChange:m=>l.mutate(!!m),"data-testid":`llm-provider-enabled-${s.id}`}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"truncate font-medium",children:s.name}),e.jsx(Ze,{variant:"outline",children:s.protocol})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{className:"truncate font-mono",children:Ns(s.baseUrl)}),e.jsx("span",{"aria-hidden":!0,children:"·"}),e.jsx("span",{className:"whitespace-nowrap",children:n("settings.llm.modelsCount",{total:s.models.length})})]})]})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[e.jsx(y,{variant:"ghost",size:"icon-sm",title:n("settings.llm.refreshModels"),"data-testid":`llm-provider-refresh-models-${s.id}`,onClick:()=>x.mutate(),disabled:x.isPending,children:x.isPending?e.jsx(L,{className:"h-4 w-4 animate-spin"}):e.jsx(ms,{className:"h-4 w-4"})}),e.jsx(y,{variant:"ghost",size:"icon-sm",title:n("settings.llm.models"),"data-testid":`llm-provider-models-${s.id}`,onClick:()=>p(!0),children:e.jsx(us,{className:"h-4 w-4"})}),e.jsx(y,{variant:"ghost",size:"icon-sm",title:n("common.edit"),"data-testid":`llm-provider-edit-${s.id}`,onClick:()=>i(s),children:e.jsx(os,{className:"h-4 w-4"})}),e.jsx(y,{variant:"ghost",size:"icon-sm",title:n("common.delete"),"data-testid":`llm-provider-delete-${s.id}`,onClick:()=>u(!0),disabled:f.isPending,children:e.jsx(X,{className:"h-4 w-4 text-destructive"})})]}),e.jsx(vs,{open:w,onOpenChange:p,provider:s}),e.jsx(he,{open:d,onOpenChange:u,children:e.jsxs(ue,{children:[e.jsxs(ge,{children:[e.jsx(xe,{children:n("settings.llm.deleteProvider")}),e.jsx(pe,{children:n("settings.llm.deleteConfirm",{name:s.name})})]}),e.jsxs(fe,{children:[e.jsx(je,{onClick:()=>u(!1),children:n("common.cancel")}),e.jsx(ye,{variant:"destructive","data-testid":`llm-provider-delete-confirm-${s.id}`,onClick:()=>{f.mutate(),u(!1)},children:n("common.confirm")})]})]})})]})}function Cs(){var x;const{t:s}=K(),[i,n]=c.useState(!1),[a,d]=c.useState(void 0),u=R({queryKey:["llm-providers"],queryFn:async()=>{const f=await fetch("/api/llm/providers");if(!f.ok)throw new Error(await B(f,s("settings.llm.loadFailed")));return await f.json()}}),w=((x=u.data)==null?void 0:x.providers)??[],p=()=>{d(void 0),n(!0)},l=f=>{d(f),n(!0)};return e.jsxs(e.Fragment,{children:[e.jsxs(q,{className:"border-0 ring-0","data-testid":"llm-providers-section",children:[e.jsxs(D,{className:"flex flex-row items-center justify-between gap-2",children:[e.jsx(_,{children:s("settings.llm.title")}),e.jsxs(y,{"data-testid":"llm-provider-add",onClick:p,children:[e.jsx(Ge,{className:"h-4 w-4"}),s("settings.llm.addProvider")]})]}),e.jsxs(I,{className:"space-y-3",children:[u.isLoading&&e.jsx("div",{className:"text-sm text-muted-foreground",children:s("common.loading")}),!u.isLoading&&w.length===0&&e.jsx("div",{className:"text-sm text-muted-foreground","data-testid":"llm-providers-empty",children:s("settings.llm.empty")}),w.map(f=>e.jsx(ks,{provider:f,onEdit:l},f.id))]})]}),e.jsx(ys,{open:i,onOpenChange:n,provider:a}),e.jsx(Ss,{providers:w})]})}const ce="__none__";function Ss({providers:s}){var T,E;const{t:i}=K(),n=O(),[a,d]=c.useState(null),[u,w]=c.useState(""),p=R({queryKey:["llm-settings"],queryFn:async()=>{const r=await fetch("/api/llm/settings");if(!r.ok)throw new Error(await B(r,i("settings.llm.settingsLoadFailed")));return await r.json()}}),l=((T=p.data)==null?void 0:T.settings.defaultProviderId)??null,x=((E=p.data)==null?void 0:E.settings.defaultModelId)??"",f=!!p.data;c.useEffect(()=>{f&&(d(l),w(x))},[f,l,x]);const m=v({mutationFn:async()=>{const r={defaultProviderId:a,defaultModelId:u.trim()||null},P=await fetch("/api/llm/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!P.ok)throw new Error(await B(P,i("settings.llm.settingsSaveFailed")))},onSuccess:async()=>{await n.invalidateQueries({queryKey:["llm-settings"]}),h.success(i("common.success"))},onError:r=>{h.error(r instanceof Error?r.message:i("common.error"))}}),j=s.filter(r=>r.enabled),b=s.find(r=>r.id===a),N=(b==null?void 0:b.models)??[];return e.jsxs(q,{className:"border-0 ring-0","data-testid":"llm-defaults-section",children:[e.jsx(D,{children:e.jsx(_,{children:i("settings.llm.defaults")})}),e.jsxs(I,{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:i("settings.llm.defaultProvider")}),e.jsxs(J,{value:a??ce,onValueChange:r=>{r&&d(r===ce?null:r)},children:[e.jsx(W,{id:"llm-default-provider-select","data-testid":"llm-default-provider-select",className:"h-9 w-full",children:e.jsx(G,{children:(b==null?void 0:b.name)??i("settings.llm.defaultProviderNone")})}),e.jsxs(Z,{children:[e.jsx(Q,{value:ce,children:i("settings.llm.defaultProviderNone")}),j.map(r=>e.jsx(Q,{value:r.id,children:r.name},r.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-medium",htmlFor:"llm-default-model-input",children:i("settings.llm.defaultModel")}),e.jsx(C,{id:"llm-default-model-input","data-testid":"llm-default-model-input",list:"llm-default-model-options",value:u,onChange:r=>w(r.target.value),placeholder:i("settings.llm.defaultModelPlaceholder"),className:"h-9"}),e.jsx("datalist",{id:"llm-default-model-options",children:N.map(r=>e.jsx("option",{value:r},r))})]})]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(y,{variant:"default","data-testid":"llm-defaults-save",onClick:()=>m.mutate(),disabled:m.isPending||p.isLoading,className:"w-full sm:w-auto",children:[m.isPending?e.jsx(L,{className:"h-4 w-4 animate-spin"}):e.jsx($,{className:"h-4 w-4"}),i("settings.llm.saveDefaults")]})})]})]})}const Es=["none","tavily","brave"];async function de(s,i){try{return(await s.json()).error??i}catch{return i}}function Ps(){var E;const{t:s}=K(),i=O(),[n,a]=c.useState("none"),[d,u]=c.useState(""),[w,p]=c.useState(""),[l,x]=c.useState(null),f=R({queryKey:["llm-settings"],queryFn:async()=>{const r=await fetch("/api/llm/settings");if(!r.ok)throw new Error(await de(r,s("settings.search.loadFailed")));return await r.json()}}),m=(E=f.data)==null?void 0:E.settings,j=m==null?void 0:m.searchProvider;c.useEffect(()=>{j&&a(j)},[j]);const b=v({mutationFn:async()=>{const r={searchProvider:n};d.trim()&&(r.tavilyApiKey=d.trim()),w.trim()&&(r.braveApiKey=w.trim());const P=await fetch("/api/llm/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!P.ok)throw new Error(await de(P,s("settings.search.saveFailed")))},onSuccess:async()=>{u(""),p(""),await i.invalidateQueries({queryKey:["llm-settings"]}),h.success(s("common.success"))},onError:r=>{h.error(r instanceof Error?r.message:s("common.error"))}}),N=v({mutationFn:async r=>{const P={[r]:""},g=await fetch("/api/llm/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(P)});if(!g.ok)throw new Error(await de(g,s("settings.search.saveFailed")))},onSuccess:async()=>{await i.invalidateQueries({queryKey:["llm-settings"]}),h.success(s("common.success"))},onError:r=>{h.error(r instanceof Error?r.message:s("common.error"))}}),T=r=>r==="none"?s("settings.search.providerNone"):r==="tavily"?"Tavily":"Brave";return e.jsxs(q,{className:"border-0 ring-0","data-testid":"settings-search-section",children:[e.jsx(D,{children:e.jsx(_,{children:s("settings.search.title")})}),e.jsxs(I,{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(J,{value:n,onValueChange:r=>{r&&a(r)},children:[e.jsx(W,{id:"search-provider-select","data-testid":"settings-search-provider-select",className:"w-full min-h-10",children:e.jsx(G,{children:T(n)})}),e.jsx(Z,{children:Es.map(r=>e.jsx(Q,{value:r,children:T(r)},r))})]})]}),e.jsx(Oe,{id:"search-tavily-key-input",testId:"settings-search-tavily",label:s("settings.search.tavilyApiKey"),value:d,hasKey:(m==null?void 0:m.hasTavilyApiKey)??!1,onChange:u,onClear:()=>x("tavilyApiKey"),clearing:N.isPending&&N.variables==="tavilyApiKey"}),e.jsx(Oe,{id:"search-brave-key-input",testId:"settings-search-brave",label:s("settings.search.braveApiKey"),value:w,hasKey:(m==null?void 0:m.hasBraveApiKey)??!1,onChange:p,onClear:()=>x("braveApiKey"),clearing:N.isPending&&N.variables==="braveApiKey"}),e.jsx(he,{open:l!==null,onOpenChange:r=>{r||x(null)},children:e.jsxs(ue,{children:[e.jsxs(ge,{children:[e.jsx(xe,{children:s("settings.search.clearKey")}),e.jsx(pe,{children:s("settings.search.clearKeyConfirm")})]}),e.jsxs(fe,{children:[e.jsx(je,{children:s("common.cancel")}),e.jsx(ye,{"data-testid":"settings-search-clear-confirm",onClick:()=>{l&&N.mutate(l),x(null)},children:s("settings.search.clearKey")})]})]})}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(y,{variant:"default","data-testid":"settings-search-save",onClick:()=>b.mutate(),disabled:b.isPending||f.isLoading,className:"w-full sm:w-auto",children:[b.isPending?e.jsx(L,{className:"h-4 w-4 animate-spin"}):e.jsx($,{className:"h-4 w-4"}),s("common.save")]})})]})]})}function Oe({id:s,testId:i,label:n,value:a,hasKey:d,onChange:u,onClear:w,clearing:p}){const{t:l}=K();return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-medium",htmlFor:s,children:n}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(C,{id:s,"data-testid":`${i}-input`,"data-key-set":d?"true":"false",type:"password",value:a,onChange:x=>u(x.target.value),placeholder:l(d?"settings.search.keySetPlaceholder":"settings.search.keyPlaceholder"),className:"min-h-10"}),d&&e.jsxs(y,{variant:"outline",size:"sm","data-testid":`${i}-clear`,onClick:w,disabled:p,className:"shrink-0",children:[e.jsx(X,{className:"h-4 w-4"}),l("settings.search.clearKey")]})]})]})}const me=["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 F(s,i){try{return(await s.json()).error??i}catch{return i}}function As(){var $e,qe,De,_e;const{t:s}=K(),i=O(),{refreshSettings:n}=Xe(),[a,d]=c.useState("site"),u=Ie(t=>t.theme),w=Ie(t=>t.setTheme),p=u==="dark",[l,x]=c.useState("tmex"),[f,m]=c.useState(window.location.origin),[j,b]=c.useState("en_US"),[N,T]=c.useState(6),[E,r]=c.useState(3),[P,g]=c.useState(!0),[M,o]=c.useState(!0),[S,z]=c.useState(!0),[we,be]=c.useState(!0),[ve,Ne]=c.useState(2),[ke,Ce]=c.useState(10),[es,ss]=c.useState(!1),[Y,Se]=c.useState(""),[ee,Ee]=c.useState(""),[ts,as]=c.useState(null),[se,Pe]=c.useState(""),[te,Fe]=c.useState(""),[ae,Te]=c.useState(me),ns=t=>{const k=t?"dark":"light";w(k),document.documentElement.classList.toggle("dark",k==="dark")},ne=R({queryKey:["site-settings"],queryFn:async()=>{const t=await fetch("/api/settings/site");if(!t.ok)throw new Error(await F(t,s("settings.loadFailed")));return await t.json()}}),ie=R({queryKey:["telegram-bots"],queryFn:async()=>{const t=await fetch("/api/settings/telegram/bots");if(!t.ok)throw new Error(await F(t,s("telegram.loadBotsFailed")));return await t.json()}});c.useEffect(()=>{var k;const t=(k=ne.data)==null?void 0:k.settings;t&&(x(t.siteName),m(t.siteUrl),b(t.language??"en_US"),T(t.bellThrottleSeconds),r(t.notificationThrottleSeconds??3),g(t.enableBrowserBellToast??!0),o(t.enableBrowserNotificationToast??!0),z(t.enableTelegramBellPush??!0),be(t.enableTelegramNotificationPush??!0),Ne(t.sshReconnectMaxRetries),Ce(t.sshReconnectDelaySeconds))},[($e=ne.data)==null?void 0:$e.settings]);const Me=v({mutationFn:async()=>{const k=await fetch("/api/settings/site",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({siteName:l,siteUrl:f,language:j,bellThrottleSeconds:N,notificationThrottleSeconds:E,enableBrowserBellToast:P,enableBrowserNotificationToast:M,enableTelegramBellPush:S,enableTelegramNotificationPush:we,sshReconnectMaxRetries:ve,sshReconnectDelaySeconds:ke})});if(!k.ok)throw new Error(await F(k,s("settings.saveFailed")))},onSuccess:async()=>{var t,k;await Promise.all([i.invalidateQueries({queryKey:["site-settings"]}),n()]),h.success(s("settings.settingsSaved")),((k=(t=ne.data)==null?void 0:t.settings)==null?void 0:k.language)!==j&&(cs.changeLanguage(j),ss(!0))},onError:t=>{h.error(t instanceof Error?t.message:s("common.error"))}}),le=v({mutationFn:async()=>{const t=await fetch("/api/settings/telegram/bots",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:Y,token:ee,enabled:!0,allowAuthRequests:!0})});if(!t.ok)throw new Error(await F(t,s("telegram.createFailed")))},onSuccess:async()=>{Se(""),Ee(""),await i.invalidateQueries({queryKey:["telegram-bots"]}),h.success(s("common.success"))},onError:t=>{h.error(t instanceof Error?t.message:s("common.error"))}}),Ke=((qe=ie.data)==null?void 0:qe.bots)??[],re=R({queryKey:["webhooks"],queryFn:async()=>{const t=await fetch("/api/webhooks");if(!t.ok)throw new Error(await F(t,s("webhook.loadFailed")));return await t.json()}}),oe=v({mutationFn:async()=>{const t=await fetch("/api/webhooks",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:se,secret:te,eventMask:ae})});if(!t.ok)throw new Error(await F(t,s("webhook.createFailed")))},onSuccess:async()=>{Pe(""),Fe(""),Te(me),await i.invalidateQueries({queryKey:["webhooks"]}),h.success(s("common.success"))},onError:t=>{h.error(t instanceof Error?t.message:s("common.error"))}}),Ae=v({mutationFn:async t=>{const k=await fetch(`/api/webhooks/${t}`,{method:"DELETE"});if(!k.ok)throw new Error(await F(k,s("webhook.deleteFailed")))},onSuccess:async()=>{await i.invalidateQueries({queryKey:["webhooks"]}),h.success(s("common.success"))},onError:t=>{h.error(t instanceof Error?t.message:s("common.error"))}}),Be=((De=re.data)==null?void 0:De.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(y,{type:"button",size:"sm",variant:a==="site"?"default":"outline","data-testid":"settings-tab-site",onClick:()=>d("site"),children:s("settings.siteSettings")}),e.jsx(y,{type:"button",size:"sm",variant:a==="notifications"?"default":"outline","data-testid":"settings-tab-notifications",onClick:()=>d("notifications"),children:s("settings.notificationsTab")}),e.jsx(y,{type:"button",size:"sm",variant:a==="telegram"?"default":"outline","data-testid":"settings-tab-telegram",onClick:()=>d("telegram"),children:s("telegram.title")}),e.jsx(y,{type:"button",size:"sm",variant:a==="webhooks"?"default":"outline","data-testid":"settings-tab-webhooks",onClick:()=>d("webhooks"),children:s("webhook.title")}),e.jsx(y,{type:"button",size:"sm",variant:a==="llm"?"default":"outline","data-testid":"settings-tab-llm",onClick:()=>d("llm"),children:s("settings.llm.title")}),e.jsx(y,{type:"button",size:"sm",variant:a==="search"?"default":"outline","data-testid":"settings-tab-search",onClick:()=>d("search"),children:s("settings.search.title")})]}),a==="site"&&e.jsxs(q,{className:"border-0 ring-0",children:[e.jsx(D,{children:e.jsx(_,{children:s("settings.siteSettings")})}),e.jsxs(I,{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(C,{id:"site-name-input",value:l,onChange:t=>x(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(C,{id:"site-url-input",value:f,onChange:t=>m(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(J,{value:j,onValueChange:t=>{t&&b(t)},children:[e.jsx(W,{id:"language-select","data-testid":"settings-language-select",className:"w-full min-h-10",children:e.jsx(G,{placeholder:s("settings.language"),children:((_e=Re.locales.find(t=>t.code===j))==null?void 0:_e.nativeName)??j})}),e.jsx(Z,{className:"max-h-[var(--tmex-viewport-height)]",children:Re.locales.map(t=>e.jsx(Q,{value:t.code,children:t.nativeName},t.code))})]}),es&&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(A,{checked:p,onCheckedChange:t=>ns(!!t),"data-testid":"settings-theme-toggle"})]})})]})]}),a==="notifications"&&e.jsxs(q,{className:"border-0 ring-0",children:[e.jsx(D,{children:e.jsx(_,{children:s("settings.notificationsTab")})}),e.jsxs(I,{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(A,{checked:P,onCheckedChange:t=>g(!!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(A,{checked:S,onCheckedChange:t=>z(!!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(A,{checked:M,onCheckedChange:t=>o(!!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(A,{checked:we,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(C,{id:"bell-throttle-input",type:"number",value:N,min:0,max:300,onChange:t=>T(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(C,{id:"notification-throttle-input",type:"number",value:E,min:0,max:300,onChange:t=>r(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(C,{id:"ssh-reconnect-retries-input",type:"number",value:ve,min:0,max:20,onChange:t=>Ne(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(C,{id:"ssh-reconnect-delay-input",type:"number",value:ke,min:1,max:300,onChange:t=>Ce(Number(t.target.value)),className:"min-h-10"})]})]})]})]}),a==="telegram"&&e.jsxs(q,{className:"border-0 ring-0",children:[e.jsx(D,{children:e.jsx(_,{children:s("telegram.title")})}),e.jsxs(I,{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(C,{id:"new-bot-name",value:Y,onChange:t=>Se(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(C,{id:"new-bot-token",type:"password",value:ee,onChange:t=>Ee(t.target.value),placeholder:s("telegram.botTokenPlaceholder"),className:"min-h-10"})]}),e.jsx("div",{className:"md:col-span-2",children:e.jsxs(y,{variant:"default",className:"w-full md:w-auto","data-testid":"telegram-add-bot",onClick:()=>le.mutate(),disabled:le.isPending||!Y.trim()||!ee.trim(),children:[le.isPending?e.jsx(L,{className:"h-4 w-4 animate-spin"}):e.jsx($,{className:"h-4 w-4"}),s("telegram.addBot")]})})]})}),e.jsxs("div",{className:"space-y-3",children:[ie.isLoading&&e.jsx("div",{className:"text-sm text-muted-foreground",children:s("common.loading")}),!ie.isLoading&&Ke.length===0&&e.jsx("div",{className:"text-sm text-muted-foreground",children:s("telegram.addBot")}),Ke.map(t=>e.jsx(Fs,{bot:t,expanded:ts===t.id,onToggleExpand:()=>{as(k=>k===t.id?null:t.id)}},t.id))]})]})]}),a==="webhooks"&&e.jsxs(q,{className:"border-0 ring-0",children:[e.jsx(D,{children:e.jsx(_,{children:s("webhook.title")})}),e.jsxs(I,{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(C,{id:"webhook-url-input","data-testid":"webhook-url-input",value:se,onChange:t=>Pe(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(C,{id:"webhook-secret-input","data-testid":"webhook-secret-input",value:te,onChange:t=>Fe(t.target.value),placeholder:s("webhook.secretPlaceholder"),className:"min-h-10"})]}),e.jsx("div",{className:"md:col-span-2",children:e.jsxs(y,{variant:"default",className:"w-full md:w-auto","data-testid":"webhook-add",onClick:()=>oe.mutate(),disabled:oe.isPending||!se.trim()||!te.trim()||ae.length===0,children:[oe.isPending?e.jsx(L,{className:"h-4 w-4 animate-spin"}):e.jsx($,{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:me.map(t=>{const k=ae.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(A,{checked:k,"data-testid":`webhook-event-${t}`,onCheckedChange:is=>{Te(U=>is?U.includes(t)?U:[...U,t]:U.filter(ls=>ls!==t))}})]},t)})})]}),e.jsxs("div",{className:"space-y-2",children:[re.isLoading&&e.jsx("div",{className:"text-sm text-muted-foreground",children:s("common.loading")}),!re.isLoading&&Be.length===0&&e.jsx("div",{className:"text-sm text-muted-foreground",children:s("webhook.empty")}),Be.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(Ye(j))})]}),e.jsx(y,{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(X,{className:"h-4 w-4"})})]},t.id))]})]})]}),a==="llm"&&e.jsx(Cs,{}),a==="search"&&e.jsx(Ps,{}),(a==="site"||a==="notifications")&&e.jsx("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-end",children:e.jsxs(y,{variant:"default","data-testid":"settings-save",onClick:()=>Me.mutate(),disabled:Me.isPending,className:"w-full sm:w-auto",children:[e.jsx($,{className:"h-4 w-4"}),s("common.save")]})})]})}function Fs({bot:s,expanded:i,onToggleExpand:n}){var M;const{t:a}=K(),d=O(),[u,w]=c.useState(s.name),[p,l]=c.useState(""),[x,f]=c.useState(s.enabled),[m,j]=c.useState(s.allowAuthRequests);c.useEffect(()=>{w(s.name),f(s.enabled),j(s.allowAuthRequests)},[s.allowAuthRequests,s.enabled,s.name]);const b=R({queryKey:["telegram-bot-chats",s.id],enabled:i,queryFn:async()=>{const o=await fetch(`/api/settings/telegram/bots/${s.id}/chats`);if(!o.ok)throw new Error(await F(o,a("telegram.loadChatsFailed")));return await o.json()}}),N=c.useMemo(()=>{var S;const o=((S=b.data)==null?void 0:S.chats)??[];return{pending:o.filter(z=>z.status==="pending"),authorized:o.filter(z=>z.status==="authorized")}},[(M=b.data)==null?void 0:M.chats]),T=v({mutationFn:async()=>{const o={name:u,enabled:x,allowAuthRequests:m};p.trim()&&(o.token=p.trim());const S=await fetch(`/api/settings/telegram/bots/${s.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!S.ok)throw new Error(await F(S,a("telegram.updateFailed")))},onSuccess:async()=>{l(""),await d.invalidateQueries({queryKey:["telegram-bots"]}),h.success(a("common.success"))},onError:o=>{h.error(o instanceof Error?o.message:a("common.error"))}}),E=v({mutationFn:async()=>{const o=await fetch(`/api/settings/telegram/bots/${s.id}`,{method:"DELETE"});if(!o.ok)throw new Error(await F(o,a("telegram.deleteFailed")))},onSuccess:async()=>{await d.invalidateQueries({queryKey:["telegram-bots"]}),h.success(a("common.success"))},onError:o=>{h.error(o instanceof Error?o.message:a("common.error"))}}),r=v({mutationFn:async o=>{const S=await fetch(`/api/settings/telegram/bots/${s.id}/chats/${encodeURIComponent(o)}/approve`,{method:"POST"});if(!S.ok)throw new Error(await F(S,a("telegram.approveFailed")))},onSuccess:async()=>{await Promise.all([d.invalidateQueries({queryKey:["telegram-bots"]}),d.invalidateQueries({queryKey:["telegram-bot-chats",s.id]})]),h.success(a("common.success"))},onError:o=>{h.error(o instanceof Error?o.message:a("common.error"))}}),P=v({mutationFn:async o=>{const S=await fetch(`/api/settings/telegram/bots/${s.id}/chats/${encodeURIComponent(o)}`,{method:"DELETE"});if(!S.ok)throw new Error(await F(S,a("telegram.removeFailed")))},onSuccess:async()=>{await Promise.all([d.invalidateQueries({queryKey:["telegram-bots"]}),d.invalidateQueries({queryKey:["telegram-bot-chats",s.id]})]),h.success(a("common.success"))},onError:o=>{h.error(o instanceof Error?o.message:a("common.error"))}}),g=v({mutationFn:async o=>{const S=await fetch(`/api/settings/telegram/bots/${s.id}/chats/${encodeURIComponent(o)}/test`,{method:"POST"});if(!S.ok)throw new Error(await F(S,a("telegram.testMessageFailed")))},onSuccess:()=>{h.success(a("common.success"))},onError:o=>{h.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":`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(y,{variant:"ghost","data-testid":`telegram-bot-toggle-${s.id}`,onClick:n,children:a(i?"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:a("telegram.botName")}),e.jsx(C,{id:`bot-name-${s.id}`,value:u,onChange:o=>w(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:`bot-token-${s.id}`,children:a("telegram.botToken")}),e.jsx(C,{id:`bot-token-${s.id}`,type:"password",value:p,onChange:o=>l(o.target.value),placeholder:a("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:a("common.enabled")}),e.jsx(A,{checked:x,onCheckedChange:o=>f(!!o)})]})}),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:a("telegram.allowAuthRequests")}),e.jsx(A,{checked:m,onCheckedChange:o=>j(!!o)})]})})]}),e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-end",children:[e.jsxs(y,{variant:"destructive","data-testid":`telegram-bot-delete-${s.id}`,onClick:()=>E.mutate(),className:"w-full sm:w-auto",children:[e.jsx(X,{className:"h-4 w-4"}),a("telegram.deleteBot")]}),e.jsxs(y,{variant:"default","data-testid":`telegram-bot-save-${s.id}`,onClick:()=>T.mutate(),className:"w-full sm:w-auto",children:[e.jsx($,{className:"h-4 w-4"}),a("common.save")]})]}),i&&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(Le,{className:"h-4 w-4"}),a("telegram.pendingChats")]}),N.pending.length===0&&e.jsx("div",{className:"text-xs text-muted-foreground",children:"-"}),N.pending.map(o=>e.jsx(ze,{chat:o,pending:!0,onApprove:()=>r.mutate(o.chatId),onDelete:()=>P.mutate(o.chatId)},`${o.botId}-${o.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(Le,{className:"h-4 w-4"}),a("telegram.chats")]}),N.authorized.length===0&&e.jsx("div",{className:"text-xs text-muted-foreground",children:"-"}),N.authorized.map(o=>e.jsx(ze,{chat:o,pending:!1,onTest:()=>g.mutate(o.chatId),onDelete:()=>P.mutate(o.chatId)},`${o.botId}-${o.chatId}`))]}),b.isLoading&&e.jsx("div",{className:"lg:col-span-2 text-xs text-muted-foreground",children:a("common.loading")})]})]})}function ze({chat:s,pending:i,onApprove:n,onDelete:a,onTest:d}){const{t:u}=K(),w=Xe(p=>{var l;return((l=p.settings)==null?void 0:l.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:[u("telegram.chatId"),":",s.chatId]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:new Date(s.appliedAt).toLocaleString(Ye(w))}),e.jsx("div",{className:"flex items-center justify-end gap-2 pt-1",children:i?e.jsxs(e.Fragment,{children:[e.jsx(y,{variant:"outline",size:"sm",onClick:a,children:u("telegram.reject")}),e.jsx(y,{variant:"default",size:"sm",onClick:n,children:u("telegram.authorize")})]}):e.jsxs(e.Fragment,{children:[e.jsxs(y,{variant:"secondary",size:"sm",onClick:d,children:[e.jsx(ds,{className:"h-3.5 w-3.5"}),u("telegram.sendTestMessage")]}),e.jsx(y,{variant:"destructive",size:"sm",onClick:a,children:u("common.delete")})]})})]})}function Bs(){const{t:s}=K();return e.jsx(e.Fragment,{children:s("sidebar.settings")})}function $s(){const{t:s}=K(),[i,n]=c.useState(!1),a=v({mutationFn:async()=>{const d=await fetch("/api/settings/restart",{method:"POST"});if(!d.ok)throw new Error(await F(d,s("settings.restartFailed")))},onSuccess:()=>{h.success(s("settings.restartScheduled"))},onError:d=>{h.error(d instanceof Error?d.message:s("common.error"))}});return e.jsxs(e.Fragment,{children:[e.jsx(y,{variant:"ghost",size:"icon-sm",onClick:()=>n(!0),disabled:a.isPending,"aria-label":s("settings.restartGateway"),title:s("settings.restartGateway"),className:"text-destructive hover:text-destructive hover:bg-destructive/10",children:e.jsx(xs,{className:"h-4 w-4"})}),e.jsx(he,{open:i,onOpenChange:n,children:e.jsxs(ue,{children:[e.jsxs(ge,{children:[e.jsx(xe,{children:s("settings.restartGateway")}),e.jsx(pe,{children:s("settings.restartConfirm")})]}),e.jsxs(fe,{children:[e.jsx(je,{onClick:()=>n(!1),children:s("common.cancel")}),e.jsx(ye,{variant:"destructive",onClick:()=>{a.mutate(),n(!1)},children:s("common.confirm")})]})]})})]})}export{$s as PageActions,Bs as PageTitle,As as default};
22
+ //# sourceMappingURL=SettingsPage-D-ttUVSw.js.map
@@ -0,0 +1,2 @@
1
+ import{j as r,a4 as d}from"./index-DPqBlAbb.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-BfO0Uw5Q.js.map