@easbot/tui 0.3.43 → 0.3.45

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,10 +1,10 @@
1
- import*as fe from'fs';import {readdirSync,statSync}from'fs';import*as As from'os';import {homedir}from'os';import*as Ae from'path';import {join,dirname,basename,isAbsolute}from'path';import {Filesystem,Glob}from'@easbot/utils';import {eastAsianWidth}from'get-east-asian-width';import {performance as performance$1}from'perf_hooks';import {execSync}from'child_process';import {pathToFileURL,fileURLToPath}from'url';import {Marked,Tokenizer}from'marked';import {createRequire}from'module';import {EventEmitter}from'events';var Ps=Object.defineProperty;var Os=(i,t,e)=>t in i?Ps(i,t,{enumerable:true,configurable:true,writable:true,value:e}):i[t]=e;var d=(i,t,e)=>Os(i,typeof t!="symbol"?t+"":t,e);function Ti(i,t){let e=i.toLowerCase(),r=t.toLowerCase(),n=h=>{if(h.length===0)return {matches:true,score:0};if(h.length>r.length)return {matches:false,score:0};let u=0,p=0,f=-1,b=0;for(;u<h.length;){let m=r.indexOf(h[u],f+1);if(m===-1)break;let g=m===0||/[\s\-_./:]/.test(r[m-1]);f===m-1?(b++,p-=b*5):(b=0,f>=0&&(p+=(m-f-1)*2)),g&&(p-=10),p+=m*.1,f=m,u++;}return u<h.length?{matches:false,score:0}:(h===r&&(p-=100),{matches:true,score:p})},s=n(e);if(s.matches)return s;let o=e.match(/^(?<letters>[a-z]+)(?<digits>[0-9]+)$/),l=e.match(/^(?<digits>[0-9]+)(?<letters>[a-z]+)$/),a=o?`${o.groups?.digits??""}${o.groups?.letters??""}`:l?`${l.groups?.letters??""}${l.groups?.digits??""}`:"";if(!a)return s;let c=n(a);return c.matches?{matches:true,score:c.score+5}:s}function Re(i,t,e){if(!t.trim())return i;let r=t.trim().split(/[\s/]+/).filter(s=>s.length>0);if(r.length===0)return i;let n=[];for(let s of i){let o=e(s),l=0,a=true;for(let c of r){let h=Ti(c,o);if(h.matches)l+=h.score;else {a=false;break}}a&&n.push({item:s,totalScore:l});}return n.sort((s,o)=>s.totalScore-o.totalScore),n.map(s=>s.item)}var Z=new Intl.Segmenter(void 0,{granularity:"grapheme"}),$s=new Intl.Segmenter(void 0,{granularity:"word"});function Pe(){return Z}function Oe(){return $s}function _s(i){let t=i.codePointAt(0);return t>=126976&&t<=130047||t>=8960&&t<=9215||t>=9728&&t<=10175||t>=11088&&t<=11093||i.includes("\uFE0F")||i.length>2}var Ks=new RegExp("^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Mark}|\\p{Surrogate})+$","v"),Bs=new RegExp("^[\\p{Default_Ignorable_Code_Point}\\p{Control}\\p{Format}\\p{Mark}\\p{Surrogate}]+","v"),Ds=new RegExp("^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Format}|\\p{Mark}|\\p{Surrogate})$","v"),Ns=new RegExp("^\\p{Mark}$","v"),Ii=new RegExp("^(?:[\\p{Spacing_Mark}--[\\u1734\\u302E\\u302F]]|[\\u065F\\u0F7F\\u102B\\u102C\\u1031\\u1033-\\u1035\\u1038\\u103A-\\u103E])+$","v"),Fs=new RegExp("^\\p{RGI_Emoji}$","v"),Ws=512,tt=new Map,$e=/[\p{Script_Extensions=Han}\p{Script_Extensions=Hiragana}\p{Script_Extensions=Katakana}\p{Script_Extensions=Hangul}\p{Script_Extensions=Bopomofo}]/u,Vs=new RegExp(`(?:(?=\\p{Punctuation})${$e.source}|[\uFF0C\uFF0E\uFF1A\uFF1B\uFF01\uFF1F\uFF08\uFF09\uFF3B\uFF3D\uFF5B\uFF5D\u201C\u201D\u2018\u2019\u2026\u2014])`,"u"),_e=new RegExp(`(?:\\s|${Vs.source})`,"u"),wt=new RegExp(`(?:^|${_e.source})`,"u");function br(i){for(let t=0;t<i.length;t++){let e=i.charCodeAt(t);if(e<32||e>126)return false}return true}function Hs(i,t){if(t<=0||i.length===0)return {text:"",width:0};if(br(i)){let a=i.slice(0,t);return {text:a,width:a.length}}let e=i.includes("\x1B"),r=i.includes(" ");if(!e&&!r){let a="",c=0;for(let{segment:h}of Z.segment(i)){let u=le(h);if(c+u>t)break;a+=h,c+=u;}return {text:a,width:c}}let n="",s=0,o=0,l="";for(;o<i.length;){let a=W(i,o);if(a){l+=a.code,o+=a.length;continue}if(i[o]===" "){if(s+3>t)break;l&&(n+=l,l=""),n+=" ",s+=3,o++;continue}let c=o;for(;c<i.length&&i[c]!==" "&&!W(i,c);)c++;for(let{segment:h}of Z.segment(i.slice(o,c))){let u=le(h);if(s+u>t)return {text:n,width:s};l&&(n+=l,l=""),n+=h,s+=u;}o=c;}return {text:n,width:s}}function mr(i,t,e,r,n,s){let o="\x1B[0m",l=Ys(i),a=t+r,c;return e.length>0?c=`${i}${l}${o}${e}${o}`:c=`${i}${l}${o}`,s?c+" ".repeat(Math.max(0,n-a)):c}function le(i){if(i.length===1){let o=i.charCodeAt(0);if(o>=32&&o<=126)return 1;if(o===9)return 3}if(Ii.test(i))return [...i].length;if(Ks.test(i))return 0;if(_s(i)&&Fs.test(i))return 2;let t=i.replace(Bs,""),e=t.codePointAt(0);if(e===void 0)return 0;if(e>=127462&&e<=127487)return 2;let r=eastAsianWidth(e),n=false,s=[...t];for(let o of s.slice(1))if(Ii.test(o))r+=1,n=false;else if(Ns.test(o))n=true;else if(!Ds.test(o)){let l=o.codePointAt(0);n||l>=65280&&l<=65519?r+=eastAsianWidth(l):(l===3635||l===3763)&&(r+=1),n=false;}return r}function S(i){if(i.length===0)return 0;let t=Gs(i);if(t!==-1)return t;let e=tt.get(i);if(e!==void 0)return e;let r=i;i.includes(" ")&&(r=r.replace(/\t/g," "));let n=r.indexOf("\x1B");if(n!==-1){let o="",l=0;for(;n!==-1;){let a=it(r,n);a>0?(o+=r.slice(l,n),n+=a,l=n):n++,n=r.indexOf("\x1B",n);}r=o+r.slice(l);}let s=0;for(let{segment:o}of Z.segment(r))s+=le(o);if(tt.size>=Ws){let o=tt.keys().next().value;o!==void 0&&tt.delete(o);}return tt.set(i,s),s}function Ke(i){if(!i.includes("\x1B"))return i;let t="",e=0;for(;e<i.length;){let r=W(i,e);if(r){e+=r.length;continue}t+=i[e],e++;}return t}function rt(i,t){let e=0,r=0;for(;r<i.length;){let n=W(i,r);if(n){r+=n.length;continue}let s=r;for(;s<i.length&&!W(i,s);)s++;for(let{segment:o}of Z.segment(i.slice(r,s))){let l=le(o);if(l>0&&t>=e&&t<e+l)return {start:e,end:e+l};e+=l;}r=s;}}function xr(i,t){let e,r=0,n=0;for(;n<i.length;){let s=W(i,n);if(s){let l=/^\x1b\]8;[^;]*;([^\x07\x1b]*)(?:\x07|\x1b\\)$/.exec(s.code);l&&(e=l[1]||void 0),n+=s.length;continue}let o=n;for(;o<i.length&&!W(i,o);)o++;for(let{segment:l}of Z.segment(i.slice(n,o))){let a=l===" "?3:le(l);if(t>=r&&t<r+a)return e;r+=a;}n=o;}}var Us=/[\u0e33\u0eb3]/,qs=/[\u0e33\u0eb3]/g;function Li(i){let t=i;if(Us.test(t)&&(t=t.replace(qs,n=>n==="\u0E33"?"\u0E4D\u0E32":"\u0ECD\u0EB2")),!t.includes(" "))return t;let e="",r=0;for(;r<t.length;){let n=W(t,r);if(n){e+=n.code,r+=n.length;continue}e+=t[r]===" "?" ":t[r],r++;}return e}function W(i,t){let e=it(i,t);return e>0?{code:i.substring(t,t+e),length:e}:null}function Gs(i){let t=0,e=0;for(;e<i.length;){let r=i.charCodeAt(e);if(r>=32&&r<=126)t++,e++;else if(r===9)t+=3,e++;else if(r===27){let n=it(i,e);if(n===0)return -1;e+=n;}else return -1}return t}function it(i,t){if(t>=i.length||i.charCodeAt(t)!==27)return 0;let e=i[t+1];if(e==="["){for(let r=t+2;r<i.length;r++){let n=i.charCodeAt(r);if(n===109||n===71||n===75||n===72||n===74)return r+1-t}return 0}if(e==="]"||e==="_"){for(let r=t+2;r<i.length;r++){let n=i.charCodeAt(r);if(n===7)return r+1-t;if(n===27&&i[r+1]==="\\")return r+2-t}return 0}return 0}function ki(i){if(!i.startsWith("\x1B]8;"))return;let t=i.endsWith("\x07")?"\x07":"\x1B\\",e=i.slice(4,t==="\x07"?-1:-2),r=e.indexOf(";");if(r===-1)return;let n=e.slice(0,r),s=e.slice(r+1);return s?{params:n,url:s,terminator:t}:null}function zs(i){return `\x1B]8;${i.params};${i.url}${i.terminator}`}function Ai(i){return `\x1B]8;;${i}`}function Ys(i){if(!i.includes("\x1B]8;"))return "";let t=null,e=0;for(;e<i.length;){let r=W(i,e);if(r){let n=ki(r.code);n!==void 0&&(t=n),e+=r.length;}else e++;}return t?Ai(t.terminator):""}var Ee=class{constructor(){d(this,"bold",false);d(this,"dim",false);d(this,"italic",false);d(this,"underline",false);d(this,"blink",false);d(this,"inverse",false);d(this,"hidden",false);d(this,"strikethrough",false);d(this,"fgColor",null);d(this,"bgColor",null);d(this,"activeHyperlink",null);}process(t){let e=ki(t);if(e!==void 0){this.activeHyperlink=e;return}if(!t.endsWith("m"))return;let r=t.match(/\x1b\[([\d;]*)m/);if(!r)return;let n=r[1]??"";if(n===""||n==="0"){this.reset();return}let s=n.split(";"),o=0;for(;o<s.length;){let l=Number.parseInt(s[o]??"",10);if(l===38||l===48){if(s[o+1]==="5"&&s[o+2]!==void 0){let a=`${s[o]};${s[o+1]};${s[o+2]}`;l===38?this.fgColor=a:this.bgColor=a,o+=3;continue}else if(s[o+1]==="2"&&s[o+4]!==void 0){let a=`${s[o]};${s[o+1]};${s[o+2]};${s[o+3]};${s[o+4]}`;l===38?this.fgColor=a:this.bgColor=a,o+=5;continue}}switch(l){case 0:this.reset();break;case 1:this.bold=true;break;case 2:this.dim=true;break;case 3:this.italic=true;break;case 4:this.underline=true;break;case 5:this.blink=true;break;case 7:this.inverse=true;break;case 8:this.hidden=true;break;case 9:this.strikethrough=true;break;case 21:this.bold=false;break;case 22:this.bold=false,this.dim=false;break;case 23:this.italic=false;break;case 24:this.underline=false;break;case 25:this.blink=false;break;case 27:this.inverse=false;break;case 28:this.hidden=false;break;case 29:this.strikethrough=false;break;case 39:this.fgColor=null;break;case 49:this.bgColor=null;break;default:l>=30&&l<=37||l>=90&&l<=97?this.fgColor=String(l):(l>=40&&l<=47||l>=100&&l<=107)&&(this.bgColor=String(l));break}o++;}}reset(){this.bold=false,this.dim=false,this.italic=false,this.underline=false,this.blink=false,this.inverse=false,this.hidden=false,this.strikethrough=false,this.fgColor=null,this.bgColor=null;}clear(){this.reset(),this.activeHyperlink=null;}getActiveCodes(){let t=[];this.bold&&t.push("1"),this.dim&&t.push("2"),this.italic&&t.push("3"),this.underline&&t.push("4"),this.blink&&t.push("5"),this.inverse&&t.push("7"),this.hidden&&t.push("8"),this.strikethrough&&t.push("9"),this.fgColor&&t.push(this.fgColor),this.bgColor&&t.push(this.bgColor);let e=t.length>0?`\x1B[${t.join(";")}m`:"";return this.activeHyperlink&&(e+=zs(this.activeHyperlink)),e}getActiveBackgroundCode(){return this.bgColor?`\x1B[${this.bgColor}m`:""}hasActiveCodes(){return this.bold||this.dim||this.italic||this.underline||this.blink||this.inverse||this.hidden||this.strikethrough||this.fgColor!==null||this.bgColor!==null||this.activeHyperlink!==null}getLineEndReset(){let t="";return this.underline&&(t+="\x1B[24m"),this.activeHyperlink&&(t+=Ai(this.activeHyperlink.terminator)),t}};function yr(i,t){let e=i.indexOf("\x1B");for(;e!==-1;){let r=it(i,e);r>0?(t.process(i.substring(e,e+r)),e+=r):e++,e=i.indexOf("\x1B",e);}}function Ri(i){let t=new Ee;return yr(i,t),t.getActiveBackgroundCode()}function*js(i){for(let{segment:t}of Z.segment(i))yield t;}function Xs(i){let t=[],e="",r="",n=null,s=0,o=()=>{e&&(t.push(e),e="",n=null);};for(;s<i.length;){let l=W(i,s);if(l){r+=l.code,s+=l.length;continue}let a=i.indexOf("\x1B",s+1);for(;a!==-1&&it(i,a)===0;)a=i.indexOf("\x1B",a+1);a===-1&&(a=i.length);let c=i.slice(s,a),h=br(c);for(let u of h?c:js(c)){let p=u===" ";if(!h&&!p&&$e.test(u)){o();let b=r+u;r="",t.push(b);continue}let f=p?"space":"word";e&&n!==f&&o(),r&&(e+=r,r=""),n=f,e+=u;}s=a;}return r&&(e?e+=r:t.length>0?t[t.length-1]+=r:e=r),e&&t.push(e),t}function Be(i){for(let t of i)Number(t);}function se(i,t){if(!i)return [""];let e=i.split(/\r\n|\r|\n/),r=[],n=new Ee;for(let s of e){let o=r.length>0?n.getActiveCodes():"",l=Qs(o+s,t);for(let a of l)r.push(a);yr(s,n);}return r.length>0?r:[""]}function Qs(i,t){if(!i)return [""];if(S(i)<=t)return [i];let r=[],n=new Ee,s=Xs(i),o="",l=0;for(let a of s){let c=S(a),h=a.trim()==="";if(c>t&&!h){if(o){let f=n.getLineEndReset();f&&(o+=f),r.push(o),o="",l=0;}let p=Zs(a,t,n);for(let f=0;f<p.length-1;f++)r.push(p[f]);o=p[p.length-1],l=S(o);continue}if(l+c>t&&l>0){let p=o.trimEnd(),f=n.getLineEndReset();f&&(p+=f),r.push(p),h?(o=n.getActiveCodes(),l=0):(o=n.getActiveCodes()+a,l=c);}else o+=a,l+=c;yr(a,n);}return o&&r.push(o),r.length>0?r.map(a=>a.trimEnd()):[""]}var vr=/[(){}[\]<>.,;:'"!?+\-=*/\\|&%^$#@~`]/;function X(i){return /\s/.test(i)}function Zs(i,t,e){let r=[],n=e.getActiveCodes(),s=0,o=0,l=[];for(;o<i.length;){let a=W(i,o);if(a)l.push({type:"ansi",value:a.code}),o+=a.length;else {let c=o;for(;c<i.length&&!W(i,c);)c++;let h=i.slice(o,c);for(let u of Z.segment(h))l.push({type:"grapheme",value:u.segment});o=c;}}for(let a of l){if(a.type==="ansi"){n+=a.value,e.process(a.value);continue}let c=a.value;if(!c)continue;let h=S(c);if(s+h>t){let u=e.getLineEndReset();u&&(n+=u),r.push(n),n=e.getActiveCodes(),s=0;}n+=c,s+=h;}return n&&r.push(n),r.length>0?r:[""]}function De(i,t,e){let r=S(i),n=Math.max(0,t-r),s=" ".repeat(n),o=i+s;return e(o)}function N(i,t,e="...",r=false){if(t<=0)return "";if(i.length===0)return r?" ".repeat(t):"";let n=S(e);if(n>=t){let m=S(i);if(m<=t)return r?i+" ".repeat(t-m):i;let g=Hs(e,t);return g.width===0?r?" ".repeat(t):"":mr("",0,g.text,g.width,t,r)}if(br(i)){if(i.length<=t)return r?i+" ".repeat(t-i.length):i;let m=t-n;return mr(i.slice(0,m),m,e,n,t,r)}let s=t-n,o="",l="",a=0,c=0,h=true,u=false,p=false,f=i.includes("\x1B"),b=i.includes(" ");if(!f&&!b){for(let{segment:m}of Z.segment(i)){let g=le(m);if(h&&c+g<=s?(o+=m,c+=g):h=false,a+=g,a>t){u=true;break}}p=!u;}else {let m=0;for(;m<i.length;){let g=W(i,m);if(g){l+=g.code,m+=g.length;continue}if(i[m]===" "){if(h&&c+3<=s?(l&&(o+=l,l=""),o+=" ",c+=3):(h=false,l=""),a+=3,a>t){u=true;break}m++;continue}let x=m;for(;x<i.length&&i[x]!==" "&&!W(i,x);)x++;for(let{segment:v}of Z.segment(i.slice(m,x))){let y=le(v);if(h&&c+y<=s?(l&&(o+=l,l=""),o+=v,c+=y):(h=false,l=""),a+=y,a>t){u=true;break}}if(u)break;m=x;}p=m>=i.length;}return !u&&p?r?i+" ".repeat(Math.max(0,t-a)):i:mr(o,c,e,n,t,r)}function V(i,t,e,r=false){return Sr(i,t,e,r).text}function Sr(i,t,e,r=false){if(e<=0)return {text:"",width:0};let n=t+e,s="",o=0,l=0,a=0,c="";for(;a<i.length;){let h=W(i,a);if(h){l>=t&&l<n?(s+=c+h.code,c=""):l<t&&(c+=h.code),a+=h.length;continue}let u=a;for(;u<i.length&&!W(i,u);)u++;for(let{segment:p}of Z.segment(i.slice(a,u))){let f=le(p),b=l>=t&&l<n,m=!r||l+f<=n;if(b&&m&&(c&&(s+=c,c=""),s+=p,o+=f),l+=f,l>=n)break}if(a=u,l>=n)break}return {text:s,width:o}}var gr=new Ee;function Ei(i,t,e,r,n=false){let s="",o=0,l="",a=0,c=0,h=0,u="",p=false,f=e+r;for(gr.clear();h<i.length;){let b=W(i,h);if(b){gr.process(b.code),c<t?u+=b.code:c>=e&&c<f&&(p||b.code.startsWith("\x1B_"))&&(l+=b.code),h+=b.length;continue}let m=h;for(;m<i.length&&!W(i,m);)m++;for(let{segment:g}of Z.segment(i.slice(h,m))){let x=le(g);if(c<t&&c+x<=t?(u&&(s+=u,u=""),s+=g,o+=x):c>=e&&c<f&&(!n||c+x<=f)&&(p||(l+=gr.getActiveCodes(),p=true),l+=g,a+=x),c+=x,r<=0?c>=t:c>=f)break}if(h=m,r<=0?c>=t:c>=f)break}return {before:s,beforeWidth:o,after:l,afterWidth:a}}var Bi=new Set([" "," ",'"',"'","="]),J="#",Mt="@",Mr=`${J}"`,Di=`${Mt}"`,Ni=new RegExp(`${wt.source}$`,"u"),Fi={"(":")","[":"]","{":"}","<":">","`":"`"};function Wi(i){return Filesystem.toUnixPath(i)}function Ir(i){let t=-1,e=0;for(let r of i)e+=r.length,(Bi.has(r)||_e.test(r))&&(t=e-1);return t}function Lr(i){let t=i;for(;t.length>0;){let e=Fi[t[0]];if(!e||t.includes(e,1))break;t=t.slice(1);}return t}function eo(i){let t=false,e=-1;for(let r=0;r<i.length;r+=1)i[r]==='"'&&(t=!t,t&&(e=r));return t?e:null}function Oi(i,t){let e=t;for(;e>0&&Fi[i[e-1]];)e-=1;return Bi.has(i[e-1]??"")||Ni.test(i.slice(0,e))}function kr(i){let t=eo(i);return t===null?null:t>0&&i[t-1]===J?Oi(i,t-1)?i.slice(t-1):null:Oi(i,t)?i.slice(t):null}function to(i){let t=i.indexOf(":");return t===-1||t===i.length-1?i:i.slice(t+1)}function $i(i){return i.startsWith(Mr)?{rawPrefix:i.slice(2),isFilePrefix:true,isQuotedPrefix:true}:i.startsWith('"')?{rawPrefix:i.slice(1),isFilePrefix:false,isQuotedPrefix:true}:i.startsWith(J)?{rawPrefix:i.slice(1),isFilePrefix:true,isQuotedPrefix:false}:{rawPrefix:i,isFilePrefix:false,isQuotedPrefix:false}}function _i(i,t){let e=t.isQuotedPrefix||_e.test(i),r=t.isFilePrefix?J:"";return e?`${`${r}"`}${i}"`:`${r}${i}`}var Vi="{dirs}/{wildcard}";function ro(i,t,e){return i.replace(/\{dirs\}/g,t.join("/")).replace(/\{wildcard\}/g,e).replace(/^\//,"")}function io(i,t){let e=Filesystem.toUnixPath(i);if(e.split("/").some(a=>a===".."))return null;let r,n,s;e==="~"||e.startsWith("~/")?(r=Filesystem.normalize("~"),n="~/",s=e==="~"?"":e.slice(2)):e.startsWith("/")?(r="/",n="/",s=e.slice(1)):(r=t,n="",s=e);let o=s.endsWith("/"),l=s.split("/").filter(a=>a!==""&&a!==".");return {scanRoot:r,dirSegments:o?l:l.slice(0,-1),fileFilter:o?"":l[l.length-1]??"",displayPrefix:n}}async function no(i,t,e){if(e.aborted)return [];let r;try{r=await Glob.scan(t,{cwd:i.scanRoot,include:"all",dot:!0,symlink:!0,ignore:await so(i.scanRoot)});}catch{return []}if(e.aborted)return [];let n=[];for(let s of r){let o=Wi(s),l=oo(i.scanRoot,o);n.push({path:l?`${o}/`:o,isDirectory:l});}return n}async function so(i){let t=[...Glob.DEFAULT_IGNORE_PATTERNS];for(let e of [".gitignore",".ignore"])try{let r=await Glob.parseGitignore(Filesystem.join(i,e));r.length>0&&t.push(...r);}catch{}return t}function oo(i,t){try{return statSync(Filesystem.join(i,t)).isDirectory()}catch{return false}}function Hi(i){let t=kr(i);if(t?.startsWith(Mr))return t;let e=Ir(i),r=Lr(e===-1?i:i.slice(e+1));return r.startsWith(J)?r:null}function Ui(i){let t=kr(i);if(t?.startsWith(Di))return t;let e=Ir(i),r=Lr(e===-1?i:i.slice(e+1));return r.startsWith(Mt)?r:null}var Tr=class{constructor(t=[],e,r,n){d(this,"commands");d(this,"basePath");d(this,"commandSource");d(this,"attachmentGlobPattern");d(this,"attachmentWildcard");this.commands=t,this.basePath=e,this.commandSource=r,this.attachmentGlobPattern=n?.attachmentGlobPattern??Vi,this.attachmentWildcard=n?.attachmentWildcard??"*";}setCommands(t){this.commands=t;}async resolveCommands(t){if(!this.commandSource)return this.commands;let e;try{e=await this.commandSource();}catch{return this.commands}return t.aborted?[]:[...this.commands,...e]}async getSuggestions(t,e,r,n){let o=(t[e]||"").slice(0,r),l=this.extractFilePrefix(o);if(l){let{rawPrefix:u,isQuotedPrefix:p}=$i(l),f=await this.getFuzzyFileSuggestions(u,{isQuotedPrefix:p,signal:n.signal});return f.length===0?null:{items:f,prefix:l}}if(this.extractAgentPrefix(o))return null;let a=o.trimStart();if(!n.force&&a.startsWith("/")){let u=a.indexOf(" ");if(u===-1){let x=a.slice(1),v=await this.resolveCommands(n.signal);if(n.signal.aborted)return null;let y=v.map(M=>{let E="name"in M?M.name:M.value,P="argumentHint"in M&&M.argumentHint?M.argumentHint:void 0,C=M.description??"",A=P?C?`${P} \u2014 ${C}`:P:C,D="group"in M?M.group:void 0,K="label"in M&&M.label?M.label:E,U="matchAlias"in M&&M.matchAlias?M.matchAlias:to(E);return {name:E,label:K,description:A||void 0,group:D,matchAlias:U}}),w=Re(y,x,M=>M.matchAlias),I=new Set(w),T=Re(y.filter(M=>M.matchAlias!==M.name&&!I.has(M)),x,M=>M.name),L=[...w,...T].map(M=>({value:M.name,label:M.label,...M.description&&{description:M.description},...M.group&&{group:M.group}}));return L.length===0?null:{items:L,prefix:a}}let p=a.slice(1,u),f=a.slice(u+1),b=await this.resolveCommands(n.signal);if(n.signal.aborted)return null;let m=b.find(x=>("name"in x?x.name:x.value)===p);if(!m||!("getArgumentCompletions"in m)||!m.getArgumentCompletions)return null;let g=await m.getArgumentCompletions(f);return !Array.isArray(g)||g.length===0?null:{items:g,prefix:f}}let c=this.extractPathPrefix(o,n.force??false);if(c===null)return null;let h=this.getFileSuggestions(c);return h.length===0?null:{items:h,prefix:c}}applyCompletion(t,e,r,n,s){let o=t[e]||"",l=o.slice(0,r-s.length),a=o.slice(r),c=s.startsWith('"')||s.startsWith(Mr)||s.startsWith(Di),h=a.startsWith('"'),u=n.value.endsWith('"'),p=c&&u&&h?a.slice(1):a;if(s.startsWith("/")&&l.trim()===""&&!s.slice(1).includes("/")){let w=`${l}/${n.value} ${p}`,I=[...t];return I[e]=w,{lines:I,cursorLine:e,cursorCol:l.length+n.value.length+2}}if(s.startsWith(J)||s.startsWith(Mt)){let w=n.label.endsWith("/"),I=w?"":" ",T=`${l+n.value}${I}${p}`,L=[...t];L[e]=T;let M=n.value.endsWith('"'),E=w&&M?n.value.length-1:n.value.length;return {lines:L,cursorLine:e,cursorCol:l.length+E+I.length}}let b=o.slice(0,r);if(b.includes("/")&&b.includes(" ")){let w=l+n.value+p,I=[...t];I[e]=w;let T=n.label.endsWith("/"),L=n.value.endsWith('"'),M=T&&L?n.value.length-1:n.value.length;return {lines:I,cursorLine:e,cursorCol:l.length+M}}let m=l+n.value+p,g=[...t];g[e]=m;let x=n.label.endsWith("/"),v=n.value.endsWith('"'),y=x&&v?n.value.length-1:n.value.length;return {lines:g,cursorLine:e,cursorCol:l.length+y}}extractFilePrefix(t){return Hi(t)}extractAgentPrefix(t){return Ui(t)}extractPathPrefix(t,e=false){let r=kr(t);if(r)return r;let n=Ir(t),s=Lr(n===-1?t:t.slice(n+1));return e||s.includes("/")||s.startsWith(".")||s.startsWith("~/")||s===""&&t!==""&&Ni.test(t)?s:null}expandHomePath(t){if(t.startsWith("~/")){let e=join(homedir(),t.slice(2));return t.endsWith("/")&&!e.endsWith("/")?`${e}/`:e}else if(t==="~")return homedir();return t}getFileSuggestions(t){try{let e,r,{rawPrefix:n,isFilePrefix:s,isQuotedPrefix:o}=$i(t),l=n;if(l.startsWith("~")&&(l=this.expandHomePath(l)),n===""||n==="./"||n==="../"||n==="~"||n==="~/"||n==="/"||s&&n==="")n.startsWith("~")||l.startsWith("/")?e=l:e=join(this.basePath,l),r="";else if(n.endsWith("/"))n.startsWith("~")||l.startsWith("/")?e=l:e=join(this.basePath,l),r="";else {let u=dirname(l),p=basename(l);n.startsWith("~")||l.startsWith("/")?e=u:e=join(this.basePath,u),r=p;}let c=readdirSync(e,{withFileTypes:!0}),h=[];for(let u of c){if(!u.name.toLowerCase().startsWith(r.toLowerCase()))continue;let p=u.isDirectory();if(!p&&u.isSymbolicLink())try{let v=join(e,u.name);p=statSync(v).isDirectory();}catch{}let f,b=u.name,m=n;if(m.endsWith("/"))f=m+b;else if(m.includes("/")||m.includes("\\"))if(m.startsWith("~/")){let v=m.slice(2),y=dirname(v);f=`~/${y==="."?b:join(y,b)}`;}else if(m.startsWith("/")){let v=dirname(m);v==="/"?f=`/${b}`:f=`${v}/${b}`;}else f=join(dirname(m),b),m.startsWith("./")&&!f.startsWith("./")&&(f=`./${f}`);else m.startsWith("~")?f=`~/${b}`:f=b;f=Wi(f);let g=p?`${f}/`:f,x=_i(g,{isDirectory:p,isFilePrefix:s,isQuotedPrefix:o});h.push({value:x,label:b+(p?"/":"")});}return h.sort((u,p)=>{let f=u.label.endsWith("/"),b=p.label.endsWith("/");return f&&!b?-1:!f&&b?1:u.label.localeCompare(p.label)}),h}catch{return []}}scoreEntry(t,e,r){let s=basename(t).toLowerCase(),o=e.toLowerCase(),l=0;return s===o?l=100:s.startsWith(o)?l=80:s.includes(o)?l=50:t.toLowerCase().includes(o)&&(l=30),r&&l>0&&(l+=10),l}async getBaseDirSuggestions(t,e,r){return r.aborted?[]:await no(t,e,r)}async getFuzzyFileSuggestions(t,e){if(e.signal.aborted)return [];try{let r=io(t,this.basePath);if(!r)return [];let n=ro(this.attachmentGlobPattern,r.dirSegments,this.attachmentWildcard),s=await this.getBaseDirSuggestions(r,n,e.signal);if(e.signal.aborted)return [];let o=s.map(c=>({...c,score:r.fileFilter?this.scoreEntry(c.path,r.fileFilter,c.isDirectory):1})).filter(c=>c.score>0);o.sort((c,h)=>{let u=h.score-c.score;if(u!==0)return u;let p=c.path.length-h.path.length;return p!==0?p:c.path.localeCompare(h.path)});let l=o.slice(0,20),a=[];for(let{path:c,isDirectory:h}of l){let u=h?c.slice(0,-1):c,p=`${r.displayPrefix}${u}`,f=basename(u),b=h?`${p}/`:p,m=_i(b,{isDirectory:h,isFilePrefix:!0,isQuotedPrefix:e.isQuotedPrefix});a.push({value:m,label:f+(h?"/":""),description:p});}return a}catch{return []}}shouldTriggerFileCompletion(t,e,r){let s=(t[e]||"").slice(0,r);return !(s.trim().startsWith("/")&&!s.trim().includes(" "))}};var kt=(i,[t,e,r])=>i.map(n=>n[0]*t+n[1]*e+n[2]*r),ao=[[.4122214694707629,.5363325372617349,.0514459932675022],[.2119034958178251,.6806995506452344,.1073969535369405],[.0883024591900564,.2817188391361215,.6299787016738222]],lo=[[.210454268309314,.793617774702305,-0.0040720430116193],[1.9779985324311684,-2.42859224204858,.450593709617411],[.0259040424655478,.7827717124575296,-0.8086757549230774]],It=[[1,.3963377773761749,.2158037573099136],[1,-0.1055613458156586,-0.0638541728258133],[1,-0.0894841775298119,-1.2914855480194092]],Ar=[[4.076741636075958,-3.307711539258063,.2309699031821043],[-1.2684379732850315,2.609757349287688,-0.341319376002657],[-0.0041960761386756,-0.7034186179359362,1.7076146940746117]],qi=[[[-1.8817031,-0.80936501],[1.19086277,1.76576728,.59662641,.75515197,.56771245]],[[1.8144408,-1.19445267],[.73956515,-0.45954404,.08285427,.12541073,-0.14503204]],[[.13110758,1.81333971],[1.35733652,-915799e-8,-1.1513021,-0.50559606,.00692167]]],At=.206,Rr=.03,Lt=(1+At)/(1+Rr),Gi=i=>.5*(Lt*i-At+Math.sqrt((Lt*i-At)**2+4*Rr*Lt*i)),co=i=>(i*i+At*i)/(Lt*(i+Rr)),uo=i=>i>.0031308?1.055*i**(1/2.4)-.055:12.92*i,ho=i=>i<=.04045?i/12.92:((i+.055)/1.055)**2.4;function Rt(i){return kt(Ar,kt(It,i).map(t=>t**3))}function po(i){return kt(lo,kt(ao,i).map(Math.cbrt))}function Er({r:i,g:t,b:e}){return po([i/255,t/255,e/255].map(ho))}function Et(i){let[t,e,r]=i.map(n=>Math.round(Math.min(1,Math.max(0,uo(n)))*255));return {r:t,g:e,b:r}}function zi(i,t){return [It[0],It[1],It[2]].map(e=>e[1]*i+e[2]*t)}function fo(i,t){let e=qi.findIndex(([[g,x]],v)=>v===2||g*i+x*t>1),[r,n,s,o,l]=qi[e][1],a=Ar[e],c=r+n*i+s*t+o*i*i+l*i*t,h=zi(i,t),u=h.map(g=>1+c*g),p=g=>g.reduce((x,v,y)=>x+a[y]*v,0),f=p(u.map(g=>g**3)),b=p(u.map((g,x)=>3*h[x]*g**2)),m=p(u.map((g,x)=>6*h[x]**2*g));return c-f*b/(b*b-.5*f*m)}function mo(i,t){let e=fo(i,t),r=Math.cbrt(1/Math.max(...Rt([1,e*i,e*t])));return [r,r*e]}function go(i,t,e,[r,n]){if(e<=r)return n*e/r;let s=n*(e-1)/(r-1),o=zi(i,t),l=o.map(f=>e+s*f),a=l.map(f=>f**3),c=l.map((f,b)=>3*o[b]*f**2),h=l.map((f,b)=>6*o[b]**2*f),u=(f,b)=>f[0]*b[0]+f[1]*b[1]+f[2]*b[2],p=Ar.map(f=>{let b=u(f,a)-1,m=u(f,c),g=u(f,h),x=m/(m*m-.5*b*g);return x>=0?-b*x:Number.MAX_VALUE});return s+Math.min(...p)}function Yi(i,t,e){let r=mo(t,e),n=go(t,e,i,r),s=n/Math.min(i*(r[1]/r[0]),(1-i)*(r[1]/(1-r[0]))),o=.11516993+1/(7.4477897+4.1590124*e+t*(-2.19557347+1.75198401*e+t*(-2.13704948-10.02301043*e+t*(-4.24894561+5.38770819*e+4.69891013*t)))),l=.11239642+1/(1.6132032-.68124379*e+t*(.40370612+.90148123*e+t*(-0.27087943+.6122399*e+t*(.00299215-.45399568*e-.14661872*t)))),a=.9*s*Math.sqrt(Math.sqrt(1/(1/(i*o)**4+1/((1-i)*l)**4)));return [Math.sqrt(1/(1/(i*.4)**2+1/((1-i)*.8)**2)),a,n]}function ji(i,t,e){let r=co(e),n=[r,0,0];if(r>0&&r<1&&t>0){let s=2*Math.PI*((i%360+360)%360)/360,o=Math.cos(s),l=Math.sin(s),[a,c,h]=Yi(r,o,l),u;if(t<.8){let p=1.25*t,f=.8*a;u=p*f/(1-(1-f/c)*p);}else {let p=5*(t-.8),f=.2*c**2*1.25**2/a;u=c+p*f/(1-(1-f/(h-c))*p);}n=[r,u*o,u*l];}return Et(Rt(n))}function Xi(i){let[t,e,r]=Er(i),n=Math.hypot(e,r),s=Gi(t);if(n<1e-9||s<=0||s>=1)return {h:0,s:0,l:s};let o=(Math.atan2(r,e)*180/Math.PI+360)%360,[l,a,c]=Yi(t,e/n,r/n),h;if(n<a){let u=.8*l;h=.8*(n/(u+(1-u/a)*n));}else {let u=.2*a**2*1.5625/l,p=n-a;h=.8+.2*(p/(u+(1-u/(c-a))*p));}return {h:o,s:Math.min(1,Math.max(0,h)),l:s}}function ge(i,t){if(!Number.isFinite(i))throw new Error(`${t} must be finite`)}function en(i){if(!Number.isInteger(i)||i<0||i>255)throw new Error(`ANSI color index must be an integer from 0 to 255: ${i}`);return Object.freeze({kind:"indexed",index:i})}function Ot(i,t,e){for(let[r,n]of [["r",i],["g",t],["b",e]])if(ge(n,r),n<0||n>255)throw new Error(`${r} must be between 0 and 255: ${n}`);return Object.freeze({kind:"rgb",r:i,g:t,b:e})}function Or(i,t,e){if(ge(i,"l"),ge(t,"c"),ge(e,"h"),i<0||i>1)throw new Error(`l must be between 0 and 1: ${i}`);if(t<0)throw new Error(`c must not be negative: ${t}`);return Object.freeze({kind:"oklch",l:i,c:t,h:(e%360+360)%360})}var Ne=String.raw`[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?`,bo=new RegExp(`^oklch\\(\\s*(${Ne})(%)?\\s+(${Ne})\\s+(${Ne})(?:deg)?\\s*\\)$`,"i"),xo=new RegExp(`^okhsl\\(\\s*(${Ne})(?:deg)?\\s+(${Ne})(%)?\\s+(${Ne})(%)?\\s*\\)$`,"i");function tn(i,t,e){if(ge(i,"h"),ge(t,"s"),ge(e,"l"),t<0||t>1)throw new Error(`s must be between 0 and 1: ${t}`);if(e<0||e>1)throw new Error(`l must be between 0 and 1: ${e}`);let{r,g:n,b:s}=ji(i,t,e);return Ot(r,n,s)}function yo(i){return Xi(ye(i))}function vo(i){if(typeof i=="number")return en(i);let e=/^#([\da-f]{3}|[\da-f]{6})$/i.exec(i)?.[1];if(e){let s=e.length===3?[...e].map(o=>o+o).join(""):e;return Ot(Number.parseInt(s.slice(0,2),16),Number.parseInt(s.slice(2,4),16),Number.parseInt(s.slice(4,6),16))}let r=bo.exec(i);if(r){let s=Number.parseFloat(r[1])/(r[2]?100:1);return Or(s,Number.parseFloat(r[3]),Number.parseFloat(r[4]))}let n=xo.exec(i);if(n){let s=Number.parseFloat(n[2])/(n[3]?100:1),o=Number.parseFloat(n[4])/(n[5]?100:1);return tn(Number.parseFloat(n[1]),s,o)}throw new Error(`Invalid color value: ${i}`)}var So=[{r:0,g:0,b:0},{r:128,g:0,b:0},{r:0,g:128,b:0},{r:128,g:128,b:0},{r:0,g:0,b:128},{r:128,g:0,b:128},{r:0,g:128,b:128},{r:192,g:192,b:192},{r:128,g:128,b:128},{r:255,g:0,b:0},{r:0,g:255,b:0},{r:255,g:255,b:0},{r:0,g:0,b:255},{r:255,g:0,b:255},{r:0,g:255,b:255},{r:255,g:255,b:255}],ce=[0,95,135,175,215,255],Qi=Array.from({length:24},(i,t)=>8+t*10);function Co(i){if(i<16)return {...So[i]};if(i<232){let e=i-16;return {r:ce[Math.floor(e/36)],g:ce[Math.floor(e%36/6)],b:ce[e%6]}}let t=8+(i-232)*10;return {r:t,g:t,b:t}}function Zi(i){return i.every(e=>e>=-1e-7&&e<=1+1e-7)}function wo({l:i,c:t,h:e}){let r=e*Math.PI/180,n=Math.cos(r),s=Math.sin(r),o=u=>Rt([i,u*n,u*s]),l=o(t);if(Zi(l))return Et(l);let a=o(0),c=0,h=t;for(let u=0;u<20;u++){let p=(c+h)/2,f=o(p);Zi(f)?(c=p,a=f):h=p;}return Et(a)}function ye(i){switch(i.kind){case "indexed":return Co(i.index);case "rgb":return {r:i.r,g:i.g,b:i.b};case "oklch":return wo(i)}}function Pr(i){if(i.kind==="oklch")return {l:i.l,c:i.c,h:i.h};let[t,e,r]=Er(ye(i));return {l:t,c:Math.hypot(e,r),h:(Math.atan2(r,e)*180/Math.PI+360)%360}}function To(i){let{r:t,g:e,b:r}=ye(i),n=s=>Math.round(s).toString(16).padStart(2,"0");return `#${n(t)}${n(e)}${n(r)}`}function Mo(i,t,e,r="oklch"){if(ge(e,"amount"),e<0||e>1)throw new Error(`amount must be between 0 and 1: ${e}`);if(r==="srgb"){let c=ye(i),h=ye(t);return Ot(c.r+(h.r-c.r)*e,c.g+(h.g-c.g)*e,c.b+(h.b-c.b)*e)}let n=Pr(i),s=Pr(t),o=n.c<1e-7?s.h:n.h,a=((s.c<1e-7?o:s.h)-o+540)%360-180;return Or(n.l+(s.l-n.l)*e,n.c+(s.c-n.c)*e,o+a*e)}function Pt(i,t){let e=0,r=1/0;for(let n=0;n<i.length;n++){let s=Math.abs(t-i[n]);s<r&&(e=n,r=s);}return e}function Ji(i,t){let e=i.r-t.r,r=i.g-t.g,n=i.b-t.b;return e*e*.299+r*r*.587+n*n*.114}function Io(i){let t=Pt(ce,i.r),e=Pt(ce,i.g),r=Pt(ce,i.b),n={r:ce[t],g:ce[e],b:ce[r]},s=16+36*t+6*e+r,o=Math.round(.299*i.r+.587*i.g+.114*i.b),l=Pt(Qi,o),a=Qi[l];return Math.max(i.r,i.g,i.b)-Math.min(i.r,i.g,i.b)<10&&Ji(i,{r:a,g:a,b:a})<Ji(i,n)?232+l:s}function rn(i,t,e){if(i.kind==="indexed")return `\x1B[${e?48:38};5;${i.index}m`;let r=ye(i);return t==="truecolor"?`\x1B[${e?48:38};2;${Math.round(r.r)};${Math.round(r.g)};${Math.round(r.b)}m`:`\x1B[${e?48:38};5;${Io(r)}m`}function nn(i,t){return rn(i,t,false)}function sn(i,t){return rn(i,t,true)}function Lo(i,t,e){return on(i,t.fg&&nn(t.fg,e),t.bg&&sn(t.bg,e),t)}function on(i,t,e,r){let n="",s="";return t&&(n+=t,s="\x1B[39m"),e&&(n+=e,s=`\x1B[49m${s}`),r.bold&&(n+="\x1B[1m"),r.dim&&(n+="\x1B[2m"),(r.bold||r.dim)&&(s=`\x1B[22m${s}`),r.italic&&(n+="\x1B[3m",s=`\x1B[23m${s}`),r.underline&&(n+="\x1B[4m",s=`\x1B[24m${s}`),r.inverse&&(n+="\x1B[7m",s=`\x1B[27m${s}`),r.strikethrough&&(n+="\x1B[9m",s=`\x1B[29m${s}`),`${n}${i}${s}`}var q=false;function at(i){q=i;}function ko(){return q}var Ao={escape:"escape",esc:"esc",enter:"enter",return:"return",tab:"tab",space:"space",backspace:"backspace",delete:"delete",insert:"insert",clear:"clear",home:"home",end:"end",pageUp:"pageUp",pageDown:"pageDown",up:"up",down:"down",left:"left",right:"right",f1:"f1",f2:"f2",f3:"f3",f4:"f4",f5:"f5",f6:"f6",f7:"f7",f8:"f8",f9:"f9",f10:"f10",f11:"f11",f12:"f12",backtick:"`",hyphen:"-",equals:"=",leftbracket:"[",rightbracket:"]",backslash:"\\",semicolon:";",quote:"'",comma:",",period:".",slash:"/",exclamation:"!",at:"@",hash:"#",dollar:"$",percent:"%",caret:"^",ampersand:"&",asterisk:"*",leftparen:"(",rightparen:")",underscore:"_",plus:"+",pipe:"|",tilde:"~",leftbrace:"{",rightbrace:"}",colon:":",lessthan:"<",greaterthan:">",question:"?",ctrl:i=>`ctrl+${i}`,shift:i=>`shift+${i}`,alt:i=>`alt+${i}`,super:i=>`super+${i}`,ctrlShift:i=>`ctrl+shift+${i}`,shiftCtrl:i=>`shift+ctrl+${i}`,ctrlAlt:i=>`ctrl+alt+${i}`,altCtrl:i=>`alt+ctrl+${i}`,shiftAlt:i=>`shift+alt+${i}`,altShift:i=>`alt+shift+${i}`,ctrlSuper:i=>`ctrl+super+${i}`,superCtrl:i=>`super+ctrl+${i}`,shiftSuper:i=>`shift+super+${i}`,superShift:i=>`super+shift+${i}`,altSuper:i=>`alt+super+${i}`,superAlt:i=>`super+alt+${i}`,ctrlShiftAlt:i=>`ctrl+shift+alt+${i}`,ctrlShiftSuper:i=>`ctrl+shift+super+${i}`},be=new Set(["`","-","=","[","]","\\",";","'",",",".","/","!","@","#","$","%","^","&","*","(",")","_","+","|","~","{","}",":","<",">","?"]),un=new Set("~!@#$%^&*()_+|{}:<>?"),Ro=["shift","alt","ctrl","super"],k={shift:1,alt:2,ctrl:4,super:8},_={escape:27,tab:9,enter:13,space:32,backspace:127,kpEnter:57414},H={up:-1,down:-2,right:-3,left:-4},B={delete:-10,insert:-11,pageUp:-12,pageDown:-13,home:-14,end:-15},Eo=new Map([[57399,48],[57400,49],[57401,50],[57402,51],[57403,52],[57404,53],[57405,54],[57406,55],[57407,56],[57408,57],[57409,46],[57410,47],[57411,42],[57412,45],[57413,43],[57415,61],[57416,44],[57417,H.left],[57418,H.right],[57419,H.up],[57420,H.down],[57421,B.pageUp],[57422,B.pageDown],[57423,B.home],[57424,B.end],[57425,B.insert],[57426,B.delete]]);function Fe(i){return Eo.get(i)??i}function ot(i,t){return (t&-193&k.shift)!==0&&i>=65&&i<=90?i+32:i}function Kt(i,t,e){if(i===void 0||(t&k.shift)===0)return;let r=Fe(i);if(e.has(String.fromCharCode(r)))return {codepoint:r,modifier:t&-2}}var ee={up:["\x1B[A","\x1BOA"],down:["\x1B[B","\x1BOB"],right:["\x1B[C","\x1BOC"],left:["\x1B[D","\x1BOD"],home:["\x1B[H","\x1BOH","\x1B[1~","\x1B[7~"],end:["\x1B[F","\x1BOF","\x1B[4~","\x1B[8~"],insert:["\x1B[2~"],delete:["\x1B[3~"],pageUp:["\x1B[5~","\x1B[[5~"],pageDown:["\x1B[6~","\x1B[[6~"],clear:["\x1B[E","\x1BOE"],f1:["\x1BOP","\x1B[11~","\x1B[[A"],f2:["\x1BOQ","\x1B[12~","\x1B[[B"],f3:["\x1BOR","\x1B[13~","\x1B[[C"],f4:["\x1BOS","\x1B[14~","\x1B[[D"],f5:["\x1B[15~","\x1B[[E"],f6:["\x1B[17~"],f7:["\x1B[18~"],f8:["\x1B[19~"],f9:["\x1B[20~"],f10:["\x1B[21~"],f11:["\x1B[23~"],f12:["\x1B[24~"]},Po={up:["\x1B[a"],down:["\x1B[b"],right:["\x1B[c"],left:["\x1B[d"],clear:["\x1B[e"],insert:["\x1B[2$"],delete:["\x1B[3$"],pageUp:["\x1B[5$"],pageDown:["\x1B[6$"],home:["\x1B[7$"],end:["\x1B[8$"]},Oo={up:["\x1BOa"],down:["\x1BOb"],right:["\x1BOc"],left:["\x1BOd"],clear:["\x1BOe"],insert:["\x1B[2^"],delete:["\x1B[3^"],pageUp:["\x1B[5^"],pageDown:["\x1B[6^"],home:["\x1B[7^"],end:["\x1B[8^"]},$o={"\x1BOA":"up","\x1BOB":"down","\x1BOC":"right","\x1BOD":"left","\x1BOH":"home","\x1BOF":"end","\x1B[E":"clear","\x1BOE":"clear","\x1BOe":"ctrl+clear","\x1B[e":"shift+clear","\x1B[2~":"insert","\x1B[2$":"shift+insert","\x1B[2^":"ctrl+insert","\x1B[3$":"shift+delete","\x1B[3^":"ctrl+delete","\x1B[[5~":"pageUp","\x1B[[6~":"pageDown","\x1B[a":"shift+up","\x1B[b":"shift+down","\x1B[c":"shift+right","\x1B[d":"shift+left","\x1BOa":"ctrl+up","\x1BOb":"ctrl+down","\x1BOc":"ctrl+right","\x1BOd":"ctrl+left","\x1B[5$":"shift+pageUp","\x1B[6$":"shift+pageDown","\x1B[7$":"shift+home","\x1B[8$":"shift+end","\x1B[5^":"ctrl+pageUp","\x1B[6^":"ctrl+pageDown","\x1B[7^":"ctrl+home","\x1B[8^":"ctrl+end","\x1BOP":"f1","\x1BOQ":"f2","\x1BOR":"f3","\x1BOS":"f4","\x1B[11~":"f1","\x1B[12~":"f2","\x1B[13~":"f3","\x1B[14~":"f4","\x1B[[A":"f1","\x1B[[B":"f2","\x1B[[C":"f3","\x1B[[D":"f4","\x1B[[E":"f5","\x1B[15~":"f5","\x1B[17~":"f6","\x1B[18~":"f7","\x1B[19~":"f8","\x1B[20~":"f9","\x1B[21~":"f10","\x1B[23~":"f11","\x1B[24~":"f12","\x1Bb":"alt+left","\x1Bf":"alt+right","\x1Bp":"alt+up","\x1Bn":"alt+down"},j=(i,t)=>t.includes(i),Q=(i,t,e)=>e===k.shift?j(i,Po[t]):e===k.ctrl?j(i,Oo[t]):false;function lt(i){return i.includes("\x1B[200~")?false:!!(i.includes(":3u")||i.includes(":3~")||i.includes(":3A")||i.includes(":3B")||i.includes(":3C")||i.includes(":3D")||i.includes(":3H")||i.includes(":3F"))}function _o(i){return i.includes("\x1B[200~")?false:!!(i.includes(":2u")||i.includes(":2~")||i.includes(":2A")||i.includes(":2B")||i.includes(":2C")||i.includes(":2D")||i.includes(":2H")||i.includes(":2F"))}function _t(i){if(!i)return "press";let t=parseInt(i,10);return t===2?"repeat":t===3?"release":"press"}function hn(i){let t=i.match(/^\x1b\[(\d+)(?::(\d*))?(?::(\d+))?(?:;(\d+))?(?::(\d+))?u$/);if(t){let s=parseInt(t[1],10),o=t[2]&&t[2].length>0?parseInt(t[2],10):void 0,l=t[3]?parseInt(t[3],10):void 0,a=t[4]?parseInt(t[4],10):1,c=_t(t[5]);return {codepoint:s,shiftedKey:o,baseLayoutKey:l,modifier:a-1,eventType:c}}let e=i.match(/^\x1b\[1;(\d+)(?::(\d+))?([ABCD])$/);if(e){let s=parseInt(e[1],10),o=_t(e[2]),l={A:-1,B:-2,C:-3,D:-4};return {codepoint:l[e[3]],modifier:s-1,eventType:o}}let r=i.match(/^\x1b\[(\d+)(?:;(\d+))?(?::(\d+))?~$/);if(r){let s=parseInt(r[1],10),o=r[2]?parseInt(r[2],10):1,l=_t(r[3]),c={2:B.insert,3:B.delete,5:B.pageUp,6:B.pageDown,7:B.home,8:B.end}[s];if(c!==void 0)return {codepoint:c,modifier:o-1,eventType:l}}let n=i.match(/^\x1b\[1;(\d+)(?::(\d+))?([HF])$/);if(n){let s=parseInt(n[1],10),o=_t(n[2]),l=n[3]==="H"?B.home:B.end;return {codepoint:l,modifier:s-1,eventType:o}}return null}function R(i,t,e){let r=hn(i);if(!r)return false;let n=r.modifier&-193,s=e&-193,o=ot(Fe(r.codepoint),r.modifier),l=ot(Fe(t),e);if(n===s&&o===l)return true;let a=Kt(r.shiftedKey,n,be);if(a&&(a.modifier&-193)===s&&a.codepoint===Fe(t))return true;if(n!==s)return false;if(r.baseLayoutKey!==void 0&&r.baseLayoutKey===t){let c=o,h=c>=97&&c<=122,u=be.has(String.fromCharCode(c));if(!h&&!u)return true}return false}function Bt(i){let t=i.match(/^\x1b\[27;(\d+);(\d+)~$/);if(!t)return null;let e=parseInt(t[1],10);return {codepoint:parseInt(t[2],10),modifier:e-1}}function te(i,t,e){let r=Bt(i);return r?r.codepoint===t&&r.modifier===e:false}function dn(){return !!process.env.WT_SESSION&&!process.env.SSH_CONNECTION&&!process.env.SSH_CLIENT&&!process.env.SSH_TTY}function an(i,t){return i==="\x7F"?t===0:i!=="\b"?false:dn()?t===k.ctrl:t===0}function Ko(i){let t=i.toLowerCase(),e=t.charCodeAt(0);return e>=97&&e<=122||t==="["||t==="\\"||t==="]"||t==="_"?String.fromCharCode(e&31):t==="-"?"":null}function ln(i){return i>="0"&&i<="9"}function st(i,t,e){let r=Bt(i);if(!r)return false;if(r.modifier===e&&ot(r.codepoint,r.modifier)===ot(t,e))return true;let s=Kt(r.codepoint,r.modifier,un);return s?.modifier===e&&s.codepoint===t}function Bo(i,t){let e=[],r=t&-193;if((r&-16)===0)return r&k.shift&&e.push("shift"),r&k.ctrl&&e.push("ctrl"),r&k.alt&&e.push("alt"),r&k.super&&e.push("super"),e.length>0?`${e.join("+")}+${i}`:i}function Do(i){let t=i.toLowerCase(),e=new Set;for(;;){let r=Ro.find(n=>t.startsWith(`${n}+`));if(!r)break;if(e.has(r))return null;e.add(r),t=t.slice(r.length+1);}return !t||t.includes("+")&&t!=="+"?null:{key:t,ctrl:e.has("ctrl"),shift:e.has("shift"),alt:e.has("alt"),super:e.has("super")}}function ae(i,t){let e=Do(t);if(!e)return false;let{key:r,ctrl:n,shift:s,alt:o,super:l}=e,a=0;switch(s&&(a|=k.shift),o&&(a|=k.alt),n&&(a|=k.ctrl),l&&(a|=k.super),r){case "escape":case "esc":return a!==0?false:i==="\x1B"||R(i,_.escape,0)||te(i,_.escape,0);case "space":return !q&&(a===k.ctrl&&i==="\0"||a===k.alt&&i==="\x1B ")?true:a===0?i===" "||R(i,_.space,0)||te(i,_.space,0):R(i,_.space,a)||te(i,_.space,a);case "tab":return a===k.shift?i==="\x1B[Z"||R(i,_.tab,k.shift)||te(i,_.tab,k.shift):a===0?i===" "||R(i,_.tab,0):R(i,_.tab,a)||te(i,_.tab,a);case "enter":case "return":return a===k.shift?R(i,_.enter,k.shift)||R(i,_.kpEnter,k.shift)||te(i,_.enter,k.shift)?true:q?i==="\x1B\r"||i===`
2
- `:false:a===k.alt?R(i,_.enter,k.alt)||R(i,_.kpEnter,k.alt)||te(i,_.enter,k.alt)?true:q?false:i==="\x1B\r":a===0?i==="\r"||!q&&i===`
3
- `||i==="\x1BOM"||R(i,_.enter,0)||R(i,_.kpEnter,0):R(i,_.enter,a)||R(i,_.kpEnter,a)||te(i,_.enter,a);case "backspace":return a===k.alt?i==="\x1B\x7F"||i==="\x1B\b"?true:R(i,_.backspace,k.alt)||te(i,_.backspace,k.alt):a===k.ctrl?an(i,k.ctrl)?true:R(i,_.backspace,k.ctrl)||te(i,_.backspace,k.ctrl):a===0?an(i,0)||R(i,_.backspace,0)||te(i,_.backspace,0):R(i,_.backspace,a)||te(i,_.backspace,a);case "insert":return a===0?j(i,ee.insert)||R(i,B.insert,0):Q(i,"insert",a)?true:R(i,B.insert,a);case "delete":return a===0?j(i,ee.delete)||R(i,B.delete,0):Q(i,"delete",a)?true:R(i,B.delete,a);case "clear":return a===0?j(i,ee.clear):Q(i,"clear",a);case "home":return a===0?j(i,ee.home)||R(i,B.home,0):Q(i,"home",a)?true:R(i,B.home,a);case "end":return a===0?j(i,ee.end)||R(i,B.end,0):Q(i,"end",a)?true:R(i,B.end,a);case "pageup":return a===0?j(i,ee.pageUp)||R(i,B.pageUp,0):Q(i,"pageUp",a)?true:R(i,B.pageUp,a);case "pagedown":return a===0?j(i,ee.pageDown)||R(i,B.pageDown,0):Q(i,"pageDown",a)?true:R(i,B.pageDown,a);case "up":return a===k.alt?i==="\x1Bp"||R(i,H.up,k.alt):a===0?j(i,ee.up)||R(i,H.up,0):Q(i,"up",a)?true:R(i,H.up,a);case "down":return a===k.alt?i==="\x1Bn"||R(i,H.down,k.alt):a===0?j(i,ee.down)||R(i,H.down,0):Q(i,"down",a)?true:R(i,H.down,a);case "left":return a===k.alt?i==="\x1B[1;3D"||!q&&i==="\x1BB"||i==="\x1Bb"||R(i,H.left,k.alt):a===k.ctrl?i==="\x1B[1;5D"||Q(i,"left",k.ctrl)||R(i,H.left,k.ctrl):a===0?j(i,ee.left)||R(i,H.left,0):Q(i,"left",a)?true:R(i,H.left,a);case "right":return a===k.alt?i==="\x1B[1;3C"||!q&&i==="\x1BF"||i==="\x1Bf"||R(i,H.right,k.alt):a===k.ctrl?i==="\x1B[1;5C"||Q(i,"right",k.ctrl)||R(i,H.right,k.ctrl):a===0?j(i,ee.right)||R(i,H.right,0):Q(i,"right",a)?true:R(i,H.right,a);case "f1":case "f2":case "f3":case "f4":case "f5":case "f6":case "f7":case "f8":case "f9":case "f10":case "f11":case "f12":return a!==0?false:j(i,ee[r])}if(r.length===1&&(r>="a"&&r<="z"||ln(r)||be.has(r))){let c=r.charCodeAt(0),h=Ko(r),u=r>="a"&&r<="z",p=ln(r);return a===k.ctrl+k.alt&&!q&&h&&i===`\x1B${h}`||a===k.alt&&!q&&(u||p||be.has(r))&&i===`\x1B${r}`?true:a===k.ctrl?h&&i===h?true:R(i,c,k.ctrl)||st(i,c,k.ctrl):a===k.shift+k.ctrl?R(i,c,k.shift+k.ctrl)||st(i,c,k.shift+k.ctrl):a===k.shift?u&&i===r.toUpperCase()?true:R(i,c,k.shift)||st(i,c,k.shift):a!==0?R(i,c,a)||st(i,c,a):i===r||R(i,c,0)||st(i,c,0)}return false}function cn(i,t,e){let r=Fe(i),n=ot(r,t),s=n>=97&&n<=122,o=n>=48&&n<=57,l=be.has(String.fromCharCode(n)),a=s||o||l?n:e??n,c;if(a===_.escape?c="escape":a===_.tab?c="tab":a===_.enter||a===_.kpEnter?c="enter":a===_.space?c="space":a===_.backspace?c="backspace":a===B.delete?c="delete":a===B.insert?c="insert":a===B.home?c="home":a===B.end?c="end":a===B.pageUp?c="pageUp":a===B.pageDown?c="pageDown":a===H.up?c="up":a===H.down?c="down":a===H.left?c="left":a===H.right?c="right":(a>=48&&a<=57||a>=97&&a<=122||be.has(String.fromCharCode(a)))&&(c=String.fromCharCode(a)),!!c)return Bo(c,t)}function No(i){let t=hn(i);if(t){let n=Kt(t.shiftedKey,t.modifier,be);return cn(n?.codepoint??t.codepoint,n?.modifier??t.modifier,t.baseLayoutKey)}let e=Bt(i);if(e){let n=Kt(e.codepoint,e.modifier,un);return cn(n?.codepoint??e.codepoint,n?.modifier??e.modifier)}if(q&&(i==="\x1B\r"||i===`
4
- `))return "shift+enter";let r=$o[i];if(r)return r;if(i==="\x1B")return "escape";if(i==="")return "ctrl+\\";if(i==="")return "ctrl+]";if(i==="")return "ctrl+-";if(i==="\x1B\x1B")return "ctrl+alt+[";if(i==="\x1B")return "ctrl+alt+\\";if(i==="\x1B")return "ctrl+alt+]";if(i==="\x1B")return "ctrl+alt+-";if(i===" ")return "tab";if(i==="\r"||!q&&i===`
5
- `||i==="\x1BOM")return "enter";if(i==="\0")return "ctrl+space";if(i===" ")return "space";if(i==="\x7F")return "backspace";if(i==="\b")return dn()?"ctrl+backspace":"backspace";if(i==="\x1B[Z")return "shift+tab";if(!q&&i==="\x1B\r")return "alt+enter";if(!q&&i==="\x1B ")return "alt+space";if(i==="\x1B\x7F"||i==="\x1B\b")return "alt+backspace";if(!q&&i==="\x1BB")return "alt+left";if(!q&&i==="\x1BF")return "alt+right";if(!q&&i.length===2&&i[0]==="\x1B"){let n=i.charCodeAt(1);if(n>=1&&n<=26)return `ctrl+alt+${String.fromCharCode(n+96)}`;let s=String.fromCharCode(n);if(n>=97&&n<=122||n>=48&&n<=57||be.has(s))return `alt+${s}`}if(i==="\x1B[A")return "up";if(i==="\x1B[B")return "down";if(i==="\x1B[C")return "right";if(i==="\x1B[D")return "left";if(i==="\x1B[H"||i==="\x1BOH"||i==="\x1B[1~"||i==="\x1B[7~")return "home";if(i==="\x1B[F"||i==="\x1BOF"||i==="\x1B[4~"||i==="\x1B[8~")return "end";if(i==="\x1B[3~")return "delete";if(i==="\x1B[5~")return "pageUp";if(i==="\x1B[6~")return "pageDown";if(i.length===1){let n=i.charCodeAt(0);if(n>=1&&n<=26)return `ctrl+${String.fromCharCode(n+96)}`;if(n>=32&&n<=126)return i}}var Fo=/^\x1b\[(\d+)(?::(\d*))?(?::(\d+))?(?:;(\d+))?(?::(\d+))?u$/;function Dt(i){let t=i.match(Fo);if(!t)return;let e=Number.parseInt(t[1]??"",10);if(!Number.isFinite(e))return;let r=t[2]&&t[2].length>0?Number.parseInt(t[2],10):void 0,n=t[4]?Number.parseInt(t[4],10):1,s=Number.isFinite(n)?n-1:0;if((s&-194)!==0||s&(k.alt|k.ctrl))return;let o=e;if(s&k.shift&&typeof r=="number"&&(o=r),o=Fe(o),!(!Number.isFinite(o)||o<32))try{return String.fromCodePoint(o)}catch{return}}function Vo(i){let t=Bt(i);if(!(!t||(t.modifier&-193&-2)!==0)&&!(!Number.isFinite(t.codepoint)||t.codepoint<32))try{return String.fromCodePoint(t.codepoint)}catch{return}}function $r(i){return Dt(i)??Vo(i)}function Ho(i){let t=i.startsWith("#")?i.slice(1):i,e=parseInt(t.slice(0,2),16),r=parseInt(t.slice(2,4),16),n=parseInt(t.slice(4,6),16);return {r:e,g:r,b:n}}function ue(i){if(!/^[0-9a-f]+$/i.test(i))return;let t=16**i.length-1;if(!(t<=0))return Math.round(parseInt(i,16)/t*255)}var Uo=/^\x1b\](?:(1[01])|4;(\d{1,3}));([^\x07\x1b]*)(?:\x07|\x1b\\)$/i,qo=/^(?:\x1b\[\?997;(1|2)n)+$/;function pn(i){let t=i.match(Uo);return t?{target:t[1]==="10"?"foreground":t[1]==="11"?"background":Number.parseInt(t[2],10),rgb:Go(t[3])}:void 0}function Go(i){let t=i.trim();if(t.startsWith("#")){let c=t.slice(1);if(/^[0-9a-f]{6}$/i.test(c))return Ho(t);if(/^[0-9a-f]{3}$/i.test(c)){let h=ue(c.slice(0,1)),u=ue(c.slice(1,2)),p=ue(c.slice(2,3));return h!==void 0&&u!==void 0&&p!==void 0?{r:h,g:u,b:p}:void 0}if(/^[0-9a-f]{12}$/i.test(c)){let h=ue(c.slice(0,4)),u=ue(c.slice(4,8)),p=ue(c.slice(8,12));return h!==void 0&&u!==void 0&&p!==void 0?{r:h,g:u,b:p}:void 0}return}let e=t.replace(/^rgba?:/i,""),[r,n,s]=e.split("/");if(r===void 0||n===void 0||s===void 0)return;let o=ue(r),l=ue(n),a=ue(s);return o!==void 0&&l!==void 0&&a!==void 0?{r:o,g:l,b:a}:void 0}function _r(i){let t=i.match(qo);if(t)return t[1]==="2"?"light":"dark"}var Ue=null,Ve={},xn={widthPx:9,heightPx:18};function Nt(){return xn}function Kr(i){xn=i;}function Qo(){try{return execSync("tmux display-message -p '#{client_termfeatures}'",{encoding:"utf8",timeout:250,stdio:["ignore","pipe","ignore"]}).split(",").map(t=>t.trim()).includes("hyperlinks")}catch{return false}}function Zo(i){let t=process.env.TERM_PROGRAM?.toLowerCase()||"",e=process.env.TERMINAL_EMULATOR?.toLowerCase()||"",r=process.env.TERM?.toLowerCase()||"",n=process.env.COLORTERM?.toLowerCase()||"",s=n==="truecolor"||n==="24bit"||r.endsWith("-direct"),o=process.platform==="win32";return process.env.TMUX||r.startsWith("tmux")?{images:null,trueColor:s,hyperlinks:i()}:r.startsWith("screen")?{images:null,trueColor:s,hyperlinks:false}:t==="herdr"?{images:"kitty",trueColor:s,hyperlinks:true}:process.env.KITTY_WINDOW_ID||t==="kitty"?{images:"kitty",trueColor:true,hyperlinks:true}:t==="ghostty"||r.includes("ghostty")||process.env.GHOSTTY_RESOURCES_DIR?{images:"kitty",trueColor:true,hyperlinks:true}:process.env.WEZTERM_PANE||t==="wezterm"?{images:"kitty",trueColor:true,hyperlinks:true}:t==="warpterminal"||process.env.WARP_SESSION_ID||process.env.WARP_TERMINAL_SESSION_UUID?{images:"kitty",trueColor:true,hyperlinks:true}:process.env.ITERM_SESSION_ID||t==="iterm.app"?{images:"iterm2",trueColor:true,hyperlinks:true}:process.env.WT_SESSION?{images:null,trueColor:true,hyperlinks:true}:t==="alacritty"||t==="vscode"||t==="zed"?{images:null,trueColor:true,hyperlinks:true}:e==="jetbrains-jediterm"?{images:null,trueColor:true,hyperlinks:false}:o?{images:null,trueColor:true,hyperlinks:false}:{images:null,trueColor:s,hyperlinks:false}}function fn(i){return i==="1"?true:i==="0"?false:void 0}function yn(i=Qo){let t=fn(process.env.PI_HYPERLINKS),e=Zo(t===void 0?i:()=>t),r=process.env.PI_IMAGE_PROTOCOL?.toLowerCase(),n=r==="kitty"||r==="iterm2"?r:r==="none"||r==="0"?null:void 0,s=fn(process.env.PI_TRUE_COLOR);return {...e,...n!==void 0?{images:n}:{},...s!==void 0?{trueColor:s}:{},...t!==void 0?{hyperlinks:t}:{}}}function re(){if(!Ue){let i=Ve.hyperlinks;Ue={...yn(i===void 0?void 0:()=>i),...Ve};}return Ue}function Jo(i=re()){return i.trueColor?"truecolor":"256color"}function ea(){Ue=null;}function ta(i){Ve.images===i.images&&Ve.trueColor===i.trueColor&&Ve.hyperlinks===i.hyperlinks||(Ve={...i},Ue=null);}function Ft(i){Ue=i;}var He="\x1B_G",mn="\x1B]1337;File=";function F(i){return i.startsWith(He)||i.startsWith(mn)?true:i.includes(He)||i.includes(mn)}function Br(){return Math.floor(Math.random()*4294967294)+1}function vn(i,t={}){let r=["a=T","f=100","q=2"];if(t.moveCursor===false&&r.push("C=1"),t.columns&&r.push(`c=${t.columns}`),t.rows&&r.push(`r=${t.rows}`),t.imageId&&r.push(`i=${t.imageId}`),i.length<=4096)return `\x1B_G${r.join(",")};${i}\x1B\\`;let n=[],s=0,o=true;for(;s<i.length;){let l=i.slice(s,s+4096),a=s+4096>=i.length;o?(n.push(`\x1B_G${r.join(",")},m=1;${l}\x1B\\`),o=false):a?n.push(`\x1B_Gm=0;${l}\x1B\\`):n.push(`\x1B_Gm=1;${l}\x1B\\`),s+=4096;}return n.join("")}function ct(i){return `\x1B_Ga=d,d=I,i=${i},q=2\x1B\\`}function Dr(){return "\x1B_Ga=d,d=A,q=2\x1B\\"}function Nr(){return "\x1B_Ga=d,d=a,q=2\x1B\\"}function Sn(i,t={}){let e=[`inline=${t.inline!==false?1:0}`,`size=${Buffer.byteLength(i,"base64")}`];if(t.width!==void 0&&e.push(`width=${t.width}`),t.height!==void 0&&e.push(`height=${t.height}`),t.name){let r=Buffer.from(t.name).toString("base64");e.push(`name=${r}`);}return t.preserveAspectRatio===false&&e.push("preserveAspectRatio=0"),`\x1B]1337;File=${e.join(";")}:${i}\x07`}var We=new Map,gn=0;function ra(i){if(gn+=1,We.delete(i.imageId),We.set(i.imageId,{...i,transmissionGeneration:gn}),We.size>1e3){let t=We.keys().next().value;t!==void 0&&We.delete(t);}}function Fr(i){let t=/(?:^|,)i=(\d+)(?:,|$)/.exec(i)?.[1];return t===void 0?void 0:We.get(Number.parseInt(t,10))}function ia(i){let t=/\x1b_G([^;]*);/.exec(i)?.[1];return t===void 0?void 0:Fr(t)}function Cn(i){let t=/(?:^|,)r=(\d+)(?:,|$)/.exec(i)?.[1];if(t===void 0)return;let e=Number.parseInt(t,10);return e>0?e:void 0}function na(i,t){return Cn(i)??t}function Wt(i){let t=ia(i);if(t)return {imageId:t.imageId,columns:t.columns,rows:t.rows,widthPx:t.widthPx,heightPx:t.heightPx}}var sa=new Set(["i","p","x","y","w","h","X","Y","c","r","C","U","z","P","Q","H","V"]);function wn(i){let t=/\x1b_G([^;]*);/.exec(i)?.[1];if(t===void 0)return;let e=Cn(t);return e!==void 0?e:Fr(t)?.rows}function Tn(i){let t=/\x1b_G([^;]*);/.exec(i),e=t?.[1];if(!t||e===void 0)return;let r=Fr(e);if(!r)return;let n=t.index,s=e,o;for(;;){let c=i.indexOf("\x1B\\",n+He.length);if(c===-1)return;if(o=c+2,!/(?:^|,)m=1(?:,|$)/.test(s))break;if(n=o,!i.startsWith(He,n))return;let h=i.indexOf(";",n+He.length);if(h===-1)return;s=i.slice(n+He.length,h);}let a=`\x1B_Ga=p,q=2,${e.split(",").filter(c=>sa.has(c.split("=",1)[0]??"")).join(",")}\x1B\\`;return {imageId:r.imageId,transmissionGeneration:r.transmissionGeneration,transmissionBytes:o-t.index,estimatedDecodedBytes:r.widthPx*r.heightPx*4,rows:na(e,r.rows),sequence:a,replacementLine:`${i.slice(0,t.index)}${a}${i.slice(o)}`}}function Wr(i,t,e){let r=Wt(i),n=/\x1b_G([^;]*);/.exec(i),s=n?.[1];if(!r||!n||s===void 0||t<0||t>=r.rows||e<=0)return i;let o=Math.min(e,r.rows-t);if(t===0&&o===r.rows)return i;let l=Math.floor(r.heightPx*t/r.rows),a=Math.ceil(r.heightPx*(t+o)/r.rows),c=Math.max(1,Math.min(r.heightPx,a)-l),h=s.split(",").filter(u=>!/^[yhr]=/.test(u));return h.push(`y=${l}`,`h=${c}`,`r=${o}`),`${i.slice(0,n.index)}\x1B_G${h.join(",")};${i.slice(n.index+n[0].length)}`}function bn(i,t){if(i<=1)return i;let e=i-1,r=Math.max(i/t,t/i);return Math.max(e/t,t/e)<r?e:i}function Mn(i,t,e,r={widthPx:9,heightPx:18},n=false){let s=Math.max(1,Math.floor(t)),o=e===void 0?void 0:Math.max(1,Math.floor(e)),l=Math.max(1,i.widthPx),a=Math.max(1,i.heightPx),c=s*r.widthPx/l,h=o===void 0?c:o*r.heightPx/a,u=Math.min(c,h),p=l*u,f=a*u,b=Math.max(1,Math.min(s,Math.ceil(p/r.widthPx))),m=f/r.heightPx,g=Math.max(1,Math.ceil(m));if(o!==void 0&&(g=Math.min(o,g)),!n)return {columns:b,rows:g};if(c<=h){let x=b*r.widthPx*a/(l*r.heightPx);g=bn(g,x);}else {let x=g*r.heightPx*l/(a*r.widthPx);b=bn(b,x);}return {columns:b,rows:g}}function oa(i,t,e={widthPx:9,heightPx:18}){return Mn(i,t,void 0,e).rows}function Vt(i){try{let t=Buffer.from(i,"base64");if(t.length<24||t[0]!==137||t[1]!==80||t[2]!==78||t[3]!==71)return null;let e=t.readUInt32BE(16),r=t.readUInt32BE(20);return {widthPx:e,heightPx:r}}catch{return null}}function In(i){try{let t=Buffer.from(i,"base64");if(t.length<2||t[0]!==255||t[1]!==216)return null;let e=2;for(;e<t.length-9;){if(t[e]!==255){e++;continue}let r=t[e+1]??0;if(r>=192&&r<=194){let s=t.readUInt16BE(e+5);return {widthPx:t.readUInt16BE(e+7),heightPx:s}}if(e+3>=t.length)return null;let n=t.readUInt16BE(e+2);if(n<2)return null;e+=2+n;}return null}catch{return null}}function Ln(i){try{let t=Buffer.from(i,"base64");if(t.length<10)return null;let e=t.slice(0,6).toString("ascii");if(e!=="GIF87a"&&e!=="GIF89a")return null;let r=t.readUInt16LE(6),n=t.readUInt16LE(8);return {widthPx:r,heightPx:n}}catch{return null}}function kn(i){try{let t=Buffer.from(i,"base64");if(t.length<30)return null;let e=t.slice(0,4).toString("ascii"),r=t.slice(8,12).toString("ascii");if(e!=="RIFF"||r!=="WEBP")return null;let n=t.slice(12,16).toString("ascii");if(n==="VP8 "){if(t.length<30)return null;let s=t.readUInt16LE(26)&16383,o=t.readUInt16LE(28)&16383;return {widthPx:s,heightPx:o}}else if(n==="VP8L"){if(t.length<25)return null;let s=t.readUInt32LE(21),o=(s&16383)+1,l=(s>>14&16383)+1;return {widthPx:o,heightPx:l}}else if(n==="VP8X"){if(t.length<30)return null;let s=((t[24]??0)|(t[25]??0)<<8|(t[26]??0)<<16)+1,o=((t[27]??0)|(t[28]??0)<<8|(t[29]??0)<<16)+1;return {widthPx:s,heightPx:o}}return null}catch{return null}}function Vr(i,t){return t==="image/png"?Vt(i):t==="image/jpeg"?In(i):t==="image/gif"?Ln(i):t==="image/webp"?kn(i):null}function Hr(i,t,e={}){let r=re();if(!r.images)return null;let n=e.maxWidthCells??80,s=Mn(t,n,e.maxHeightCells,Nt(),r.images==="kitty");return r.images==="kitty"?(e.imageId!==void 0&&ra({imageId:e.imageId,columns:s.columns,rows:s.rows,widthPx:t.widthPx,heightPx:t.heightPx}),{sequence:vn(i,{columns:s.columns,rows:s.rows,imageId:e.imageId,moveCursor:e.moveCursor}),columns:s.columns,rows:s.rows,imageId:e.imageId}):r.images==="iterm2"?{sequence:Sn(i,{width:s.columns,height:"auto",preserveAspectRatio:e.preserveAspectRatio??true}),columns:s.columns,rows:s.rows}:null}function Ht(i,t){return `\x1B]8;;${t}\x1B\\${i}\x1B]8;;\x1B\\`}function aa(i){let t=homedir();return t&&(i===t||i.startsWith(`${t}/`)||i.startsWith(`${t}\\`))?`~${i.slice(t.length)}`:i}function Ut(i,t,e){let r=[];if(e){let n=aa(e);re().hyperlinks&&isAbsolute(e)?r.push(Ht(n,pathToFileURL(e).href)):r.push(n);}return r.push(`[${i}]`),t&&r.push(`${t.widthPx}x${t.heightPx}`),`[Image: ${r.join(" ")}]`}function he(i,t){let e=i.handleMouse?.(t);if(e){if("target"in e){let r=e;return r.focus&&i.handleInput?{...r,focusTarget:i}:r}if(!(!e.handled&&!e.capture&&!e.focus))return {...e,handled:true,...e.focus?{focusTarget:i}:{},target:{component:i,originX:t.screenX-t.x,originY:t.screenY-t.y,width:t.width,height:t.height}}}}function Rn(i,t){return {...i,x:i.screenX-t.originX,y:i.screenY-t.originY,width:t.width,height:t.height}}var Gt=16,la=2+Gt,ca=`\x1B]10;?\x07\x1B]11;?\x07${Array.from({length:Gt},(i,t)=>`\x1B]4;${t};?\x07`).join("")}\x1B[c`,ua=/^\x1b\[\?[\d;]*c$/;function Ur(i){return i!==null&&"focused"in i}var ie="\x1B_pi:c\x07",qr="\x1B_pi:fc\x07",En="\x1B_pi:/fc\x07",ha=/(\x1b_pi:c\x07)\x1b_pi:fc\x07(.*?)(?:\x1b_pi:\/fc\x07|$)/s;function Se(i){return `${qr}${i}${En}`}function An(i,t){if(i===void 0)return;if(typeof i=="number")return i;let e=i.match(/^(\d+(?:\.\d+)?)%$/);if(e)return Math.floor(t*parseFloat(e[1])/100)}var oe=class{constructor(){d(this,"children",[]);d(this,"mouseLayout");}addChild(t){this.children.push(t);}removeChild(t){let e=this.children.indexOf(t);e!==-1&&this.children.splice(e,1);}clear(){this.children=[];}invalidate(){for(let t of this.children)t.invalidate?.();}handleMouse(t){if(t.y<0||t.y>=t.height)return;let e=this.mouseLayout?.width===t.width?this.mouseLayout.children:this.children.map(n=>({component:n,height:n.render(t.width).length})),r=0;for(let{component:n,height:s}of e){if(t.y>=r&&t.y<r+s){let o=he(n,{...t,y:t.y-r,height:s});return o?.focus&&this.handleInput?{...o,focusTarget:this}:o}r+=s;}}render(t){let e=[],r=[];for(let n of this.children){let s=n.render(t);r.push({component:n,height:s.length});for(let o of s)e.push(o);}return this.mouseLayout={width:t,children:r},e}},Gr="\x1B[0m\x1B]8;;\x07";function de(i,t,e,r,n){if(F(i))return i;let s=e+r,o=Ei(i,e,s,n-s,true),l=Sr(t,0,r,true),a=Math.max(0,e-o.beforeWidth),c=Math.max(0,r-l.width),h=Math.max(e,o.beforeWidth),u=Math.max(r,l.width),p=Math.max(0,n-h-u),f=Math.max(0,p-o.afterWidth),b=o.before+" ".repeat(a)+Gr+l.text+" ".repeat(c)+Gr+o.after+" ".repeat(f);return S(b)<=n?b:V(b,0,n,true)}var zr=Symbol.for("@earendil-works/pi-tui/viewport");function da(i){return i[zr]===true}var zt=class zt extends oe{constructor(e,r,n){super();d(this,"terminal");d(this,"focusedComponent",null);d(this,"inputListeners",new Set);d(this,"onDebug");d(this,"renderRequested",false);d(this,"immediateRenderScheduled",false);d(this,"renderTimer");d(this,"lastRenderAt",0);d(this,"showHardwareCursor",false);d(this,"clearOnShrink",false);d(this,"fullRedrawCount",0);d(this,"stopped",false);d(this,"pendingTerminalColorQueries",[]);d(this,"terminalColorSchemeListeners",new Set);d(this,"terminalColorSchemeNotificationsEnabled",false);d(this,"logDirectory");d(this,"focusOrderCounter",0);d(this,"overlayStack",[]);d(this,"renderedOverlayLayouts",[]);d(this,"overlayFocusRestore",{status:"inactive"});this.terminal=e,this.logDirectory=n,r!==void 0&&(this.showHardwareCursor=r);}get hasOverlayEntries(){return this.overlayStack.length>0}resetRenderState(){}beforeTerminalStart(){}afterTerminalStart(){}beforeTerminalStop(e){}afterTerminalStop(e){}get fullRedraws(){return this.fullRedrawCount}getShowHardwareCursor(){return this.showHardwareCursor}setShowHardwareCursor(e){this.showHardwareCursor!==e&&(this.showHardwareCursor=e,e||this.hideTerminalCursor(),this.requestRender());}getClearOnShrink(){return this.clearOnShrink}setClearOnShrink(e){this.clearOnShrink=e;}getFocusedComponent(){return this.focusedComponent}setFocus(e){this.setFocusInternal({component:e,overlayFocusRestore:"clear"});}setFocusInternal({component:e,overlayFocusRestore:r}){let n=this.focusedComponent,s=e,o=n?this.overlayStack.find(h=>h.component===n&&this.isOverlayVisible(h)):void 0,l=s?this.overlayStack.some(h=>h.component===s):false,a=this.getVisibleOverlayFocusRestore();s&&!l?a.status==="blocked"&&a.blockedBy===n?a.resume.status==="focus-target"||!this.isComponentMounted(a.blockedBy)?s=this.resolveBlockedOverlayFocusResume(a):this.overlayFocusRestore={status:"blocked",overlay:a.overlay,blockedBy:s,resume:a.resume}:o&&a.status!=="inactive"&&a.overlay===o&&!this.isOverlayFocusAncestor(o,s)&&(this.overlayFocusRestore={status:"blocked",overlay:o,blockedBy:s,resume:{status:"restore-overlay"}}):s===null&&(a.status==="blocked"&&a.blockedBy===n?s=this.resolveBlockedOverlayFocusResume(a):r==="clear"&&this.clearOverlayFocusRestore()),Ur(this.focusedComponent)&&(this.focusedComponent.focused=false),this.focusedComponent=s,Ur(s)&&(s.focused=true);let c=s?this.overlayStack.find(h=>h.component===s&&this.isOverlayVisible(h)):void 0;c&&(this.overlayFocusRestore={status:"eligible",overlay:c});}clearOverlayFocusRestore(){this.overlayFocusRestore={status:"inactive"};}clearOverlayFocusRestoreFor(e){this.overlayFocusRestore.status!=="inactive"&&this.overlayFocusRestore.overlay===e&&this.clearOverlayFocusRestore();}resolveBlockedOverlayFocusResume(e){return e.resume.status==="restore-overlay"?e.overlay.component:(this.clearOverlayFocusRestore(),e.resume.target)}getVisibleOverlayFocusRestore(){let e=this.overlayFocusRestore;return e.status==="inactive"?e:!this.overlayStack.includes(e.overlay)||!this.isOverlayVisible(e.overlay)?{status:"inactive"}:e}isOverlayFocusAncestor(e,r){let n=new Set,s=e.preFocus;for(;s&&!n.has(s);){if(n.add(s),s===r)return true;s=this.overlayStack.find(o=>o.component===s)?.preFocus??null;}return false}retargetOverlayPreFocus(e){for(let r of this.overlayStack)r!==e&&r.preFocus===e.component&&(r.preFocus=e.preFocus);}getMountedRoots(){return this.children}isComponentMounted(e){return this.getMountedRoots().some(r=>this.containsComponent(r,e))}containsComponent(e,r){return e===r?true:e instanceof oe?e.children.some(n=>this.containsComponent(n,r)):false}showOverlay(e,r){let n={component:e,...r===void 0?{}:{options:r},preFocus:this.focusedComponent,hidden:false,focusOrder:++this.focusOrderCounter};return this.overlayStack.push(n),!r?.nonCapturing&&this.isOverlayVisible(n)&&this.setFocus(e),this.hideTerminalCursor(),this.requestRender(),{hide:()=>{let s=this.overlayStack.indexOf(n);if(s!==-1){if(this.clearOverlayFocusRestoreFor(n),this.retargetOverlayPreFocus(n),this.overlayStack.splice(s,1),this.focusedComponent===e){let o=this.getTopmostVisibleOverlay();this.setFocus(o?.component??n.preFocus);}this.overlayStack.length===0&&this.hideTerminalCursor(),this.requestRender();}},setHidden:s=>{if(n.hidden!==s){if(n.hidden=s,s){if(this.clearOverlayFocusRestoreFor(n),this.focusedComponent===e){let o=this.getTopmostVisibleOverlay();this.setFocus(o?.component??n.preFocus);}}else !r?.nonCapturing&&this.isOverlayVisible(n)&&(n.focusOrder=++this.focusOrderCounter,this.setFocus(e));this.requestRender();}},isHidden:()=>n.hidden,focus:()=>{!this.overlayStack.includes(n)||!this.isOverlayVisible(n)||(n.focusOrder=++this.focusOrderCounter,this.setFocus(e),this.requestRender());},unfocus:s=>{let o=this.focusedComponent===e,l=this.overlayFocusRestore,a=l.status!=="inactive"&&l.overlay===n;if(!(!o&&!a)){if(l.status==="blocked"&&l.overlay===n&&this.focusedComponent===l.blockedBy){s?this.overlayFocusRestore={status:"blocked",overlay:n,blockedBy:l.blockedBy,resume:{status:"focus-target",target:s.target}}:this.clearOverlayFocusRestore(),this.requestRender();return}if(this.clearOverlayFocusRestoreFor(n),o||s){let c=this.getTopmostVisibleOverlay(),h=c&&c!==n?c.component:n.preFocus;this.setFocus(s?s.target:h);}this.requestRender();}},isFocused:()=>this.focusedComponent===e,getBounds:()=>{if(!(!this.overlayStack.includes(n)||!this.isOverlayVisible(n)||!n.bounds))return {...n.bounds}}}}hideOverlay(){let e=this.overlayStack[this.overlayStack.length-1];if(e){if(this.clearOverlayFocusRestoreFor(e),this.retargetOverlayPreFocus(e),this.overlayStack.pop(),this.focusedComponent===e.component){let r=this.getTopmostVisibleOverlay();this.setFocus(r?.component??e.preFocus);}this.overlayStack.length===0&&this.hideTerminalCursor(),this.requestRender();}}hideTerminalCursor(){this.stopped||this.terminal.hideCursor();}hasOverlay(){return this.overlayStack.some(e=>this.isOverlayVisible(e))}isOverlayFocused(){return this.overlayStack.some(e=>e.component===this.focusedComponent&&this.isOverlayVisible(e))}resolveMouseFocusTarget(e){for(let r=this.overlayStack.length-1;r>=0;r--){let n=this.overlayStack[r];if(this.isOverlayVisible(n)&&this.containsComponent(n.component,e))return n.component}return e}dispatchMouseToOverlay(e){for(let r=this.renderedOverlayLayouts.length-1;r>=0;r--){let n=this.renderedOverlayLayouts[r];if(e.screenX<n.col||e.screenX>=n.col+n.width||e.screenY<n.row||e.screenY>=n.row+n.height)continue;let s=he(n.entry.component,{...e,x:e.screenX-n.col,y:e.screenY-n.row,width:n.width,height:n.height});return s?{hit:true,result:s.focus?{...s,focusTarget:n.entry.component}:s}:{hit:true}}return {hit:false}}isOverlayVisible(e){return e.hidden?false:e.options?.visible?e.options.visible(this.terminal.columns,this.terminal.rows):true}getTopmostVisibleOverlay(){let e;for(let r of this.overlayStack)r.options?.nonCapturing||!this.isOverlayVisible(r)||(!e||r.focusOrder>e.focusOrder)&&(e=r);return e}invalidate(){for(let e of this.getMountedRoots())e.invalidate();for(let e of this.overlayStack)e.component.invalidate();}start(){this.stopped=false,this.beforeTerminalStart(),this.terminal.start(e=>this.handleTerminalInput(e),()=>this.requestRender()),this.afterTerminalStart(),this.terminal.hideCursor(),this.terminalColorSchemeNotificationsEnabled&&this.terminal.write("\x1B[?2031h"),this.queryCellSize(),this.requestRender();}addInputListener(e){return this.inputListeners.add(e),()=>{this.inputListeners.delete(e);}}removeInputListener(e){this.inputListeners.delete(e);}onTerminalColorSchemeChange(e){return this.terminalColorSchemeListeners.add(e),()=>{this.terminalColorSchemeListeners.delete(e);}}setTerminalColorSchemeNotifications(e){this.terminalColorSchemeNotificationsEnabled!==e&&(this.terminalColorSchemeNotificationsEnabled=e,this.stopped||this.terminal.write(e?"\x1B[?2031h":"\x1B[?2031l"));}queryCellSize(){re().images&&this.terminal.write("\x1B[16t");}stop(e={}){this.stopped=true,this.cancelRenderTimer(),this.terminalColorSchemeNotificationsEnabled&&this.terminal.write("\x1B[?2031l"),this.beforeTerminalStop(e),this.afterTerminalStop(e),this.terminal.showCursor(),this.terminal.stop();}renderNow(e=false){e&&this.resetRenderState(),this.renderRequested=false,this.cancelRenderTimer(),this.lastRenderAt=performance$1.now(),this.doRender();}requestRender(e=false){if(e){this.resetRenderState(),this.requestImmediateRender();return}this.renderRequested||(this.renderRequested=true,process.nextTick(()=>this.scheduleRender()));}requestImmediateRender(){this.cancelRenderTimer(),this.renderRequested=true,!this.immediateRenderScheduled&&(this.immediateRenderScheduled=true,process.nextTick(()=>{this.immediateRenderScheduled=false,!(this.stopped||!this.renderRequested)&&(this.cancelRenderTimer(),this.renderRequested=false,this.lastRenderAt=performance$1.now(),this.doRender());}));}cancelRenderTimer(){this.renderTimer&&(clearTimeout(this.renderTimer),this.renderTimer=void 0);}scheduleRender(){if(this.stopped||this.renderTimer||!this.renderRequested)return;let e=performance$1.now()-this.lastRenderAt,r=Math.max(0,zt.MIN_RENDER_INTERVAL_MS-e);this.renderTimer=setTimeout(()=>{this.renderTimer=void 0,!(this.stopped||!this.renderRequested)&&(this.renderRequested=false,this.lastRenderAt=performance$1.now(),this.doRender(),this.renderRequested&&this.scheduleRender());},r);}handleTerminalInput(e){if(this.consumeTerminalColorResponse(e)||this.consumeTerminalColorSchemeReport(e))return;if(this.inputListeners.size>0){let s=e;for(let o of this.inputListeners){let l=o(s);if(l?.consume)return;l?.data!==void 0&&(s=l.data);}if(s.length===0)return;e=s;}if(this.consumeCellSizeResponse(e))return;if(ae(e,"shift+ctrl+d")&&this.onDebug){this.onDebug();return}let r=this.overlayStack.find(s=>s.component===this.focusedComponent);if(r&&!this.isOverlayVisible(r)){let s=this.getTopmostVisibleOverlay();s?this.setFocus(s.component):this.setFocusInternal({component:r.preFocus,overlayFocusRestore:"preserve"});}if(!this.overlayStack.some(s=>s.component===this.focusedComponent)){let s=this.getVisibleOverlayFocusRestore();s.status==="eligible"?this.setFocus(s.overlay.component):s.status==="blocked"&&s.blockedBy!==this.focusedComponent&&(s.resume.status==="restore-overlay"?this.setFocus(s.overlay.component):(this.clearOverlayFocusRestore(),this.setFocus(s.resume.target)));}if(this.focusedComponent?.handleInput){if(lt(e)&&!this.focusedComponent.wantsKeyRelease)return;this.focusedComponent.handleInput(e),this.requestImmediateRender();}}consumeTerminalColorResponse(e){let r=this.pendingTerminalColorQueries[0];if(!r)return false;if(ua.test(e))return this.pendingTerminalColorQueries.shift(),this.completeTerminalColorQuery(r),true;let n=pn(e);if(!n)return false;let{target:s,rgb:o}=n,l=String(s);return !r.deliver||r.replied.has(l)||(r.replied.add(l),s==="foreground"?r.foreground=o:s==="background"?r.background=o:s<Gt&&(r.palette[s]=o),r.replied.size===la&&this.completeTerminalColorQuery(r)),true}terminalColorQueryResult(e){let r=e.palette.every(n=>n!==void 0)?e.palette:void 0;return {foreground:e.foreground,background:e.background,palette:r}}completeTerminalColorQuery(e){let r=e.deliver;e.deliver=void 0,clearTimeout(e.timer),r?.(this.terminalColorQueryResult(e));}consumeTerminalColorSchemeReport(e){let r=_r(e);if(!r)return false;for(let n of this.terminalColorSchemeListeners)n(r);return true}consumeCellSizeResponse(e){let r=e.match(/^\x1b\[6;(\d+);(\d+)t$/);if(!r)return false;let n=parseInt(r[1],10),s=parseInt(r[2],10);return n<=0||s<=0||(Kr({widthPx:s,heightPx:n}),this.invalidate(),this.requestRender()),true}resolveOverlayLayout(e,r,n,s){let o=e??{},l=typeof o.margin=="number"?{top:o.margin,right:o.margin,bottom:o.margin,left:o.margin}:o.margin??{},a=Math.max(0,l.top??0),c=Math.max(0,l.right??0),h=Math.max(0,l.bottom??0),u=Math.max(0,l.left??0),p=Math.max(1,n-u-c),f=Math.max(1,s-a-h),b=An(o.width,n)??Math.min(80,p);o.minWidth!==void 0&&(b=Math.max(b,o.minWidth)),b=Math.max(1,Math.min(b,p));let m=An(o.maxHeight,s);m!==void 0&&(m=Math.max(1,Math.min(m,f)));let g=m!==void 0?Math.min(r,m):r,x,v;if(o.row!==void 0)if(typeof o.row=="string"){let y=o.row.match(/^(\d+(?:\.\d+)?)%$/);if(y){let w=Math.max(0,f-g),I=parseFloat(y[1])/100;x=a+Math.floor(w*I);}else x=this.resolveAnchorRow("center",g,f,a);}else x=o.row;else {let y=o.anchor??"center";x=this.resolveAnchorRow(y,g,f,a);}if(o.col!==void 0)if(typeof o.col=="string"){let y=o.col.match(/^(\d+(?:\.\d+)?)%$/);if(y){let w=Math.max(0,p-b),I=parseFloat(y[1])/100;v=u+Math.floor(w*I);}else v=this.resolveAnchorCol("center",b,p,u);}else v=o.col;else {let y=o.anchor??"center";v=this.resolveAnchorCol(y,b,p,u);}return o.offsetY!==void 0&&(x+=o.offsetY),o.offsetX!==void 0&&(v+=o.offsetX),x=Math.max(a,Math.min(x,s-h-g)),v=Math.max(u,Math.min(v,n-c-b)),{width:b,row:x,col:v,maxHeight:m}}resolveAnchorRow(e,r,n,s){switch(e){case "top-left":case "top-center":case "top-right":return s;case "bottom-left":case "bottom-center":case "bottom-right":return s+n-r;case "left-center":case "center":case "right-center":return s+Math.floor((n-r)/2)}}resolveAnchorCol(e,r,n,s){switch(e){case "top-left":case "left-center":case "bottom-left":return s;case "top-right":case "right-center":case "bottom-right":return s+n-r;case "top-center":case "center":case "bottom-center":return s+Math.floor((n-r)/2)}}compositeOverlays(e,r,n){if(this.overlayStack.length===0)return this.renderedOverlayLayouts=[],e;let s=[...e];for(let u of this.overlayStack)u.bounds=void 0;let o=[],l=s.length,a=this.overlayStack.filter(u=>this.isOverlayVisible(u));a.sort((u,p)=>u.focusOrder-p.focusOrder);for(let u of a){let{component:p,options:f}=u,{width:b,maxHeight:m}=this.resolveOverlayLayout(f,0,r,n),g=this.resolveFakeCursors(p.render(b));m!==void 0&&g.length>m&&(g=g.slice(0,m));let{row:x,col:v}=this.resolveOverlayLayout(f,g.length,r,n);u.bounds={row:x,col:v,width:b,height:g.length},o.push({entry:u,overlayLines:g,row:x,col:v,w:b}),l=Math.max(l,x+g.length);}this.renderedOverlayLayouts=o.map(({entry:u,row:p,col:f,w:b,overlayLines:m})=>({entry:u,row:p,col:f,width:b,height:m.length}));let c=Math.max(s.length,n,l);for(;s.length<c;)s.push("");let h=Math.max(0,c-n);for(let{overlayLines:u,row:p,col:f,w:b}of o)for(let m=0;m<u.length;m++){let g=h+p+m;if(g>=0&&g<s.length){let x=u[m]??"",v=S(x)>b?V(x,0,b,true):x;s[g]=this.compositeLineAt(s[g]??"",v,f,b,r);}}return s}applyLineResets(e){let r=Gr;for(let n=0;n<e.length;n++){let s=e[n]??"";F(s)||(e[n]=Li(s)+r);}return e}compositeLineAt(e,r,n,s,o){return de(e,r,n,s,o)}extractCursorPosition(e,r){let n=Math.max(0,e.length-r);for(let s=e.length-1;s>=n;s--){let o=e[s]??"",l=o.indexOf(ie);if(l!==-1){let a=o.slice(0,l),c=S(a);return e[s]=o.slice(0,l)+o.slice(l+ie.length),{row:s,col:c}}}return null}resolveFakeCursors(e){return e.map(r=>r.includes(qr)?(this.showHardwareCursor?r.replace(ha,"$1$2"):r).replaceAll(qr,"\x1B[7m").replaceAll(En,"\x1B[27m"):r)}queryTerminalColors({timeoutMs:e,onLateReply:r}){return new Promise(n=>{let s={palette:Array.from({length:Gt},()=>{}),replied:new Set,deliver:n,timer:void 0};s.timer=setTimeout(()=>{s.deliver=r,n(this.terminalColorQueryResult(s));},e),this.pendingTerminalColorQueries.push(s),this.terminal.write(ca);})}};d(zt,"MIN_RENDER_INTERVAL_MS",16);var qe=zt;var Yr=class{constructor(t=1,e=1,r){d(this,"children",[]);d(this,"paddingX");d(this,"paddingY");d(this,"bgFn");d(this,"cache");d(this,"mouseLayout");this.paddingX=t,this.paddingY=e,this.bgFn=r;}addChild(t){this.children.push(t),this.invalidateCache();}removeChild(t){let e=this.children.indexOf(t);e!==-1&&(this.children.splice(e,1),this.invalidateCache());}clear(){this.children=[],this.invalidateCache();}setBgFn(t){this.bgFn=t;}setPaddingX(t){this.paddingX=t,this.invalidateCache();}invalidateCache(){this.cache=void 0;}matchCache(t,e,r){let n=this.cache;return !!n&&n.width===t&&n.bgSample===r&&n.childLines.length===e.length&&n.childLines.every((s,o)=>s===e[o])}invalidate(){this.invalidateCache();for(let t of this.children)t.invalidate?.();}handleMouse(t){let e=Math.max(1,t.width-this.paddingX*2),r=t.y-this.paddingY,n=t.x-this.paddingX;if(r<0||n<0||n>=e)return;let s=this.mouseLayout?.width===e?this.mouseLayout.children:this.children.map(l=>({component:l,height:l.render(e).length})),o=0;for(let{component:l,height:a}of s){if(r>=o&&r<o+a)return he(l,{...t,x:n,y:r-o,width:e,height:a});o+=a;}}render(t){if(this.children.length===0)return [];let e=Math.max(1,t-this.paddingX*2),r=" ".repeat(this.paddingX),n=[],s=[];for(let a of this.children){let c=a.render(e);s.push({component:a,height:c.length});for(let h of c)n.push(h);}if(this.mouseLayout={width:e,children:s},n.length===0)return [];let o=this.bgFn?this.bgFn("test"):void 0;if(this.matchCache(t,n,o))return this.cache.lines;let l=[];for(let a=0;a<this.paddingY;a++)l.push(this.applyBg("",t));for(let a of n)l.push(this.applyBg(r+a,t));for(let a=0;a<this.paddingY;a++)l.push(this.applyBg("",t));return Be(l),this.cache={childLines:n,width:t,bgSample:o,lines:l},l}applyBg(t,e){let r=S(t),n=Math.max(0,e-r),s=t+" ".repeat(n);return this.bgFn?this.bgFn(s):s}};var Pn={"tui.editor.cursorUp":{defaultKeys:"up",description:"Move cursor up"},"tui.editor.cursorDown":{defaultKeys:"down",description:"Move cursor down"},"tui.editor.historyPrevious":{defaultKeys:[],description:"Select previous prompt history entry"},"tui.editor.historyNext":{defaultKeys:[],description:"Select next prompt history entry"},"tui.editor.cursorLeft":{defaultKeys:["left","ctrl+b"],description:"Move cursor left"},"tui.editor.cursorRight":{defaultKeys:["right","ctrl+f"],description:"Move cursor right"},"tui.editor.cursorWordLeft":{defaultKeys:["alt+left","ctrl+left","alt+b"],description:"Move cursor word left"},"tui.editor.cursorWordRight":{defaultKeys:["alt+right","ctrl+right","alt+f"],description:"Move cursor word right"},"tui.editor.cursorLineStart":{defaultKeys:["home","ctrl+a"],description:"Move to line start"},"tui.editor.cursorLineEnd":{defaultKeys:["end","ctrl+e"],description:"Move to line end"},"tui.editor.jumpForward":{defaultKeys:"ctrl+]",description:"Jump forward to character"},"tui.editor.jumpBackward":{defaultKeys:"ctrl+alt+]",description:"Jump backward to character"},"tui.editor.pageUp":{defaultKeys:["pageUp","ctrl+pageUp"],description:"Page up"},"tui.editor.pageDown":{defaultKeys:["pageDown","ctrl+pageDown"],description:"Page down"},"tui.editor.deleteCharBackward":{defaultKeys:"backspace",description:"Delete character backward"},"tui.editor.deleteCharForward":{defaultKeys:["delete","ctrl+d"],description:"Delete character forward"},"tui.editor.deleteWordBackward":{defaultKeys:["ctrl+w","alt+backspace"],description:"Delete word backward"},"tui.editor.deleteWordForward":{defaultKeys:["alt+d","alt+delete"],description:"Delete word forward"},"tui.editor.deleteToLineStart":{defaultKeys:"ctrl+u",description:"Delete to line start"},"tui.editor.deleteToLineEnd":{defaultKeys:"ctrl+k",description:"Delete to line end"},"tui.editor.yank":{defaultKeys:"ctrl+y",description:"Yank"},"tui.editor.yankPop":{defaultKeys:"alt+y",description:"Yank pop"},"tui.editor.undo":{defaultKeys:"ctrl+-",description:"Undo"},"tui.input.newLine":{defaultKeys:["shift+enter","ctrl+j"],description:"Insert newline"},"tui.input.submit":{defaultKeys:"enter",description:"Submit input"},"tui.input.tab":{defaultKeys:"tab",description:"Tab / autocomplete"},"tui.input.copy":{defaultKeys:"ctrl+c",description:"Copy selection"},"tui.select.up":{defaultKeys:"up",description:"Move selection up"},"tui.select.down":{defaultKeys:"down",description:"Move selection down"},"tui.select.pageUp":{defaultKeys:"pageUp",description:"Selection page up"},"tui.select.pageDown":{defaultKeys:"pageDown",description:"Selection page down"},"tui.select.confirm":{defaultKeys:"enter",description:"Confirm selection"},"tui.select.cancel":{defaultKeys:["escape","ctrl+c"],description:"Cancel selection"},"tui.altScreen.pageUp":{defaultKeys:"pageUp",description:"Scroll viewport up one page"},"tui.altScreen.pageDown":{defaultKeys:"pageDown",description:"Scroll viewport down one page"},"tui.altScreen.halfPageUp":{defaultKeys:[],description:"Scroll viewport up half a page"},"tui.altScreen.halfPageDown":{defaultKeys:[],description:"Scroll viewport down half a page"},"tui.altScreen.lineUp":{defaultKeys:[],description:"Scroll viewport up one line"},"tui.altScreen.lineDown":{defaultKeys:[],description:"Scroll viewport down one line"},"tui.altScreen.previousPrompt":{defaultKeys:["ctrl+shift+up","ctrl+up"],description:"Jump to previous semantic prompt"},"tui.altScreen.nextPrompt":{defaultKeys:["ctrl+shift+down","ctrl+down"],description:"Jump to next semantic prompt"},"tui.altScreen.search":{defaultKeys:"ctrl+shift+f",description:"Search the primary scroll view"},"tui.altScreen.searchNext":{defaultKeys:["enter","ctrl+g"],description:"Select the next search match"},"tui.altScreen.searchPrevious":{defaultKeys:["shift+enter","ctrl+shift+g"],description:"Select the previous search match"},"tui.altScreen.searchClose":{defaultKeys:"escape",description:"Close transcript search"},"tui.altScreen.top":{defaultKeys:"ctrl+home",description:"Scroll viewport to top"},"tui.altScreen.bottom":{defaultKeys:"ctrl+end",description:"Scroll viewport to bottom"}};function jr(i){if(i===void 0)return [];let t=Array.isArray(i)?i:[i],e=new Set,r=[];for(let n of t)e.has(n)||(e.add(n),r.push(n));return r}var jt=class{constructor(t,e={}){d(this,"definitions");d(this,"userBindings");d(this,"keysById",new Map);d(this,"conflicts",[]);this.definitions=t,this.userBindings=e,this.rebuild();}rebuild(){this.keysById.clear(),this.conflicts=[];let t=new Map;for(let[e,r]of Object.entries(this.userBindings))if(e in this.definitions)for(let n of jr(r)){let s=t.get(n)??new Set;s.add(e),t.set(n,s);}for(let[e,r]of t)r.size>1&&this.conflicts.push({key:e,keybindings:[...r]});for(let[e,r]of Object.entries(this.definitions)){let n=this.userBindings[e],s=jr(n===void 0?r.defaultKeys:n);this.keysById.set(e,s);}}matches(t,e){let r=this.keysById.get(e)??[];for(let n of r)if(ae(t,n))return true;return false}getKeys(t){return [...this.keysById.get(t)??[]]}getDefinition(t){let e=this.definitions[t];if(!e)throw new Error(`Unknown keybinding: ${t}`);return e}getConflicts(){return this.conflicts.map(t=>({...t,keybindings:[...t.keybindings]}))}setUserBindings(t){this.userBindings=t,this.rebuild();}getUserBindings(){return {...this.userBindings}}getResolvedBindings(){let t={};for(let e of Object.keys(this.definitions)){let r=this.keysById.get(e)??[];t[e]=r.length===1?r[0]:[...r];}return t}},Yt=null;function pa(i){Yt=i;}function G(){return Yt||(Yt=new jt(Pn)),Yt}var ut=class{constructor(t="",e=1,r=1,n){d(this,"text");d(this,"paddingX");d(this,"paddingY");d(this,"customBgFn");d(this,"cachedText");d(this,"cachedWidth");d(this,"cachedLines");this.text=t,this.paddingX=e,this.paddingY=r,this.customBgFn=n;}setText(t){this.text=t,this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0;}setCustomBgFn(t){this.customBgFn=t,this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0;}setPaddingX(t){this.paddingX=t,this.invalidate();}invalidate(){this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0;}render(t){if(this.cachedLines&&this.cachedText===this.text&&this.cachedWidth===t)return this.cachedLines;if(!this.text||this.text.trim()===""){let p=[];return this.cachedText=this.text,this.cachedWidth=t,this.cachedLines=p,p}let e=this.text.replace(/\t/g," "),r=Math.min(this.paddingX,Math.max(0,Math.floor((t-1)/2))),n=Math.max(1,t-r*2),s=se(e,n),o=" ".repeat(r),l=" ".repeat(r),a=[];for(let p of s){let f=o+p+l;if(this.customBgFn)a.push(De(f,t,this.customBgFn));else {let b=S(f),m=Math.max(0,t-b);a.push(f+" ".repeat(m));}}let c=" ".repeat(t),h=[];for(let p=0;p<this.paddingY;p++){let f=this.customBgFn?De(c,t,this.customBgFn):c;h.push(f);}let u=[...h,...a,...h];return Be(u),this.cachedText=this.text,this.cachedWidth=t,this.cachedLines=u,u.length>0?u:[""]}};var On=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],$n=80,ht=class extends ut{constructor(e,r,n,s="Loading...",o){super("",1,0);d(this,"frames",[...On]);d(this,"intervalMs",$n);d(this,"currentFrame",0);d(this,"intervalId",null);d(this,"ui",null);d(this,"renderIndicatorVerbatim",false);d(this,"spinnerColorFn");d(this,"messageColorFn");d(this,"message","Loading...");this.ui=e,this.spinnerColorFn=r,this.messageColorFn=n,this.message=s,this.setIndicator(o);}render(e){return ["",...super.render(e)]}start(){this.updateDisplay(),this.restartAnimation();}stop(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null);}setMessage(e){this.message=e,this.updateDisplay();}invalidate(){super.invalidate(),this.updateDisplay();}setIndicator(e){this.renderIndicatorVerbatim=e!==void 0,this.frames=e?.frames!==void 0?[...e.frames]:[...On],this.intervalMs=e?.intervalMs&&e.intervalMs>0?e.intervalMs:$n,this.currentFrame=0,this.start();}restartAnimation(){this.stop(),!(this.frames.length<=1)&&(this.intervalId=setInterval(()=>{this.currentFrame=(this.currentFrame+1)%this.frames.length,this.updateDisplay();},this.intervalMs));}getRenderedIndicator(){let e=this.frames[this.currentFrame]??"";return this.renderIndicatorVerbatim?e:this.spinnerColorFn(e)}updateDisplay(){let e=this.getRenderedIndicator(),r=e.length>0?`${e} `:"";this.setText(`${r}${this.messageColorFn(this.message)}`),this.ui&&this.ui.requestRender();}};var Xr=class extends ht{constructor(){super(...arguments);d(this,"abortController",new AbortController);d(this,"onAbort");}get signal(){return this.abortController.signal}get aborted(){return this.abortController.signal.aborted}handleInput(e){G().matches(e,"tui.select.cancel")&&(this.abortController.abort(),this.onAbort?.());}dispose(){this.stop();}};var Ge=class{constructor(){d(this,"ring",[]);}push(t,e){if(t)if(e.accumulate&&this.ring.length>0){let r=this.ring.pop();this.ring.push(e.prepend?t+r:r+t);}else this.ring.push(t);}peek(){return this.ring.length>0?this.ring[this.ring.length-1]:void 0}rotate(){if(this.ring.length>1){let t=this.ring.pop();this.ring.unshift(t);}}get length(){return this.ring.length}};var ze=class{constructor(){d(this,"stack",[]);}push(t){this.stack.push(structuredClone(t));}pop(){return this.stack.pop()}clear(){this.stack.length=0;}get length(){return this.stack.length}};var _n=Oe();function Xt(i,t,e){if(t<=0)return 0;let r=i.slice(0,t),n=e?.segment,s=e?.isAtomicSegment,o=n?[...n(r)]:[..._n.segment(r)],l=t;for(;o.length>0&&!s?.(o[o.length-1]?.segment||"")&&X(o[o.length-1]?.segment||"");)l-=o.pop()?.segment.length||0;if(o.length===0)return l;let a=o[o.length-1];if(s?.(a.segment))l-=a.segment.length;else if(a.isWordLike){let c=a.segment,h=[...c.matchAll(new RegExp(vr,"g"))];if(h.length<=0)l-=c.length;else {let u=h[h.length-1];l-=c.length-(u.index+u[0].length);}}else for(;o.length>0&&!s?.(o[o.length-1]?.segment||"")&&!o[o.length-1]?.isWordLike&&!X(o[o.length-1]?.segment||"");)l-=o.pop()?.segment.length||0;return l}function Qt(i,t,e){if(t>=i.length)return i.length;let r=i.slice(t),n=e?.segment,s=e?.isAtomicSegment,l=(n?n(r):_n.segment(r))[Symbol.iterator](),a=l.next(),c=t;for(;!a.done&&!s?.(a.value.segment)&&X(a.value.segment);)c+=a.value.segment.length,a=l.next();if(a.done)return c;if(s?.(a.value.segment))c+=a.value.segment.length;else if(a.value.isWordLike)c+=vr.exec(a.value.segment)?.index??a.value.segment.length;else for(;!a.done&&!s?.(a.value.segment)&&!a.value.isWordLike&&!X(a.value.segment);)c+=a.value.segment.length,a=l.next();return c}var Kn=32,Bn=2,fa=10,ma=i=>i.replace(/[\r\n]+/g," ").trim(),ga=(i,t,e)=>Math.max(t,Math.min(i,e)),dt=class{constructor(t,e,r,n={}){d(this,"items",[]);d(this,"filteredItems",[]);d(this,"selectedIndex",0);d(this,"mousePressedIndex");d(this,"maxVisible",5);d(this,"theme");d(this,"layout");d(this,"onSelect");d(this,"onCancel");d(this,"onSelectionChange");this.items=t,this.filteredItems=t,this.maxVisible=e,this.theme=r,this.layout=n;}setFilter(t){this.filteredItems=this.items.filter(e=>e.value.toLowerCase().startsWith(t.toLowerCase())),this.selectedIndex=0;}setSelectedIndex(t){this.selectedIndex=Math.max(0,Math.min(t,this.filteredItems.length-1));}invalidate(){}render(t){let e=[];if(this.filteredItems.length===0)return e.push(this.theme.noMatch(" No matching commands")),e;let r=this.getPrimaryColumnWidth(),{startIndex:n,endIndex:s}=this.getVisibleRange(this.selectedIndex);for(let o=n;o<s;o+=1){let l=this.filteredItems[o];if(!l)continue;let a=o===this.selectedIndex,c=l.description?ma(l.description):void 0;e.push(this.renderItem(l,a,t,c,r));}if(n>0||s<this.filteredItems.length){let o=` (${this.selectedIndex+1}/${this.filteredItems.length})`;e.push(this.theme.scrollInfo(N(o,t-2,"")));}return e}handleMouse(t){if(this.filteredItems.length===0)return;if(t.type==="wheel"&&t.wheelDelta){let s=t.wheelDelta<0?-1:1,o=this.selectedIndex;return this.selectedIndex=Math.max(0,Math.min(this.filteredItems.length-1,this.selectedIndex+s)),this.selectedIndex!==o&&this.notifySelectionChange(),{handled:true,render:this.selectedIndex!==o}}if(t.button!=="left"||t.type!=="press"&&t.type!=="click")return;let{startIndex:e,endIndex:r}=this.getVisibleRange(this.selectedIndex),n=e+t.y;if(!(n<e||n>=r)&&this.filteredItems[n]){if(t.type==="press")return this.mousePressedIndex=n,this.selectedIndex!==n&&(this.selectedIndex=n,this.notifySelectionChange()),{handled:true,focus:true};if(t.type==="click"){let s=this.mousePressedIndex??n;this.mousePressedIndex=void 0;let o=this.selectedIndex!==s;this.selectedIndex=s,o&&this.notifySelectionChange();let l=this.filteredItems[this.selectedIndex];return l&&this.onSelect?.(l),{handled:true}}}}handleInput(t){let e=G();if(e.matches(t,"tui.select.up"))this.selectedIndex=this.selectedIndex===0?this.filteredItems.length-1:this.selectedIndex-1,this.notifySelectionChange();else if(e.matches(t,"tui.select.down"))this.selectedIndex=this.selectedIndex===this.filteredItems.length-1?0:this.selectedIndex+1,this.notifySelectionChange();else if(e.matches(t,"tui.select.confirm")){let r=this.filteredItems[this.selectedIndex];r&&this.onSelect&&this.onSelect(r);}else e.matches(t,"tui.select.cancel")&&this.onCancel&&this.onCancel();}getVisibleRange(t){let e=this.filteredItems.length,r=Math.max(0,Math.min(t,e-1)),n=Math.max(0,Math.min(r-Math.floor(this.maxVisible/2),e-this.maxVisible));return {startIndex:n,endIndex:Math.min(n+this.maxVisible,e)}}renderItem(t,e,r,n,s){let o=e?"\u2192 ":" ",l=S(o);if(n&&r>40){let h=Math.max(1,Math.min(s,r-l-4)),u=Math.max(1,h-Bn),p=this.truncatePrimary(t,e,u,h),f=S(p),b=" ".repeat(Math.max(1,h-f)),m=l+f+b.length,g=r-m-2;if(g>fa){let x=N(n,g,"");if(e)return this.theme.selectedText(`${o}${p}${b}${x}`);let v=this.theme.description(b+x);return o+p+v}}let a=r-l-2,c=this.truncatePrimary(t,e,a,a);return e?this.theme.selectedText(`${o}${c}`):o+c}getPrimaryColumnWidth(){let{min:t,max:e}=this.getPrimaryColumnBounds(),r=this.filteredItems.reduce((n,s)=>Math.max(n,S(this.getDisplayValue(s))+Bn),0);return ga(r,t,e)}getPrimaryColumnBounds(){let t=this.layout.minPrimaryColumnWidth??this.layout.maxPrimaryColumnWidth??Kn,e=this.layout.maxPrimaryColumnWidth??this.layout.minPrimaryColumnWidth??Kn;return {min:Math.max(1,Math.min(t,e)),max:Math.max(1,Math.max(t,e))}}truncatePrimary(t,e,r,n){let s=this.getDisplayValue(t),o=this.layout.truncatePrimary?this.layout.truncatePrimary({text:s,maxWidth:r,columnWidth:n,item:t,isSelected:e}):N(s,r,"");return N(o,r,"")}getDisplayValue(t){return t.label||t.value}notifySelectionChange(){let t=this.filteredItems[this.selectedIndex];t&&this.onSelectionChange&&this.onSelectionChange(t);}getSelectedItem(){return this.filteredItems[this.selectedIndex]||null}};var Hn=Pe(),ba=Oe(),Un=/\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]/g,qn=/^\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]$/;function Ye(i){return i.length>=10&&qn.test(i)}function xa(i,t,e){if(e.size===0||!i.includes("[paste #"))return t.segment(i);let r=[];for(let l of i.matchAll(Un)){let a=Number.parseInt(l[1],10);e.has(a)&&r.push({start:l.index,end:l.index+l[0].length});}if(r.length===0)return t.segment(i);let n=t.segment(i),s=[],o=0;for(let l of n){for(;o<r.length&&r[o].end<=l.index;)o++;let a=o<r.length?r[o]:null;if(a&&l.index>=a.start&&l.index<a.end){if(l.index===a.start){let c=i.slice(a.start,a.end);s.push({segment:c,index:a.start,input:i});}}else s.push(l);}return s}function Qr(i,t,e){if(!i||t<=0)return [{text:"",startIndex:0,endIndex:0}];if(S(i)<=t)return [{text:i,startIndex:0,endIndex:i.length}];let n=[],s=e??[...Hn.segment(i)],o=0,l=0,a=-1,c=0;for(let h=0;h<s.length;h++){let u=s[h],p=u.segment,f=S(p),b=u.index,m=!Ye(p)&&X(p);if(o+f>t&&(a>=0&&o-c+f<=t?(n.push({text:i.slice(l,a),startIndex:l,endIndex:a}),l=a,o-=c):l<b&&(n.push({text:i.slice(l,b),startIndex:l,endIndex:b}),l=b,o=0),a=-1),f>t){let x=Qr(p,t);for(let y=0;y<x.length-1;y++){let w=x[y];n.push({text:w.text,startIndex:b+w.startIndex,endIndex:b+w.endIndex});}let v=x[x.length-1];l=b+v.startIndex,o=S(v.text),a=-1;continue}o+=f;let g=s[h+1];if(m&&g&&(Ye(g.segment)||!X(g.segment)))a=g.index,c=o;else if(!m&&g&&!X(g.segment)){let x=!Ye(p)&&$e.test(p),v=!Ye(g.segment)&&$e.test(g.segment);(x||v)&&(a=g.index,c=o);}}return n.push({text:i.slice(l),startIndex:l,endIndex:i.length}),n}var ya={minPrimaryColumnWidth:12,maxPrimaryColumnWidth:32},va=20,Dn=[J],Zr=new RegExp(`(?:(?!${_e.source}).)*`,"u"),Gn=`${wt.source}[([{<\`]*`;function Zt(i){return i.replace(/[\\^$.*+?()[\]{}|-]/g,"\\$&")}function Nn(i){return i.label.endsWith("/")}function Fn(i){let t=Zt(J);return new RegExp(`${Gn}(?:${t}"[^"]*|[${i.map(Zt).join("")}]${Zr.source})$`,"u")}function Wn(i){let t=Zt(J),e=i.filter(r=>r!==J).map(Zt);return new RegExp(`${Gn}(?:${t}(?:"[^"]*|${Zr.source})|[${e.join("")}]${Zr.source})$`,"u")}function Vn(i,t,e){let r=Math.max(0,e),n=` ${i} ${t} more `,s=S(n);if(s+2<=r){let h=Math.floor((r-s)/2);return "\u2500".repeat(h)+n+"\u2500".repeat(r-h-s)}let o=`\u2500\u2500\u2500 ${i} ${t} more `,l=r-S(o);if(l>=0)return o+"\u2500".repeat(l);let a="...".slice(0,r),c=r-S(a);return V(o,0,c,true)+a}var Jr=class{constructor(t,e,r={}){d(this,"state",{lines:[""],cursorLine:0,cursorCol:0});d(this,"focused",false);d(this,"tui");d(this,"theme");d(this,"paddingX",0);d(this,"lastWidth",80);d(this,"renderedVisibleLineCount",1);d(this,"renderedAutocompleteHeight",0);d(this,"scrollOffset",0);d(this,"borderColor");d(this,"autocompleteProvider");d(this,"autocompleteTriggerCharacters",[...Dn]);d(this,"autocompleteTriggerPattern",Fn(this.autocompleteTriggerCharacters));d(this,"autocompleteDebouncePattern",Wn(this.autocompleteTriggerCharacters));d(this,"autocompleteList");d(this,"autocompleteState",null);d(this,"autocompletePrefix","");d(this,"autocompleteMaxVisible",5);d(this,"autocompleteAbort");d(this,"autocompleteDebounceTimer");d(this,"autocompleteRequestTask",Promise.resolve());d(this,"autocompleteStartToken",0);d(this,"autocompleteRequestId",0);d(this,"pastes",new Map);d(this,"pasteCounter",0);d(this,"pasteBuffer","");d(this,"isInPaste",false);d(this,"history",[]);d(this,"historyIndex",-1);d(this,"historyDraft",null);d(this,"killRing",new Ge);d(this,"lastAction",null);d(this,"jumpMode",null);d(this,"preferredVisualCol",null);d(this,"snappedFromCursorCol",null);d(this,"undoStack",new ze);d(this,"onSubmit");d(this,"onChange");d(this,"disableSubmit",false);d(this,"shouldAutoSubmitSlashCommand");this.tui=t,this.theme=e,this.borderColor=e.borderColor;let n=r.paddingX??0;this.paddingX=Number.isFinite(n)?Math.max(0,Math.floor(n)):0;let s=r.autocompleteMaxVisible??5;this.autocompleteMaxVisible=Number.isFinite(s)?Math.max(3,Math.min(20,Math.floor(s))):5;}validPasteIds(){return new Set(this.pastes.keys())}segment(t,e){return xa(t,e==="word"?ba:Hn,this.validPasteIds())}getPaddingX(){return this.paddingX}setPaddingX(t){let e=Number.isFinite(t)?Math.max(0,Math.floor(t)):0;this.paddingX!==e&&(this.paddingX=e,this.tui.requestRender());}getAutocompleteMaxVisible(){return this.autocompleteMaxVisible}setAutocompleteMaxVisible(t){let e=Number.isFinite(t)?Math.max(3,Math.min(20,Math.floor(t))):5;this.autocompleteMaxVisible!==e&&(this.autocompleteMaxVisible=e,this.tui.requestRender());}setAutocompleteProvider(t){this.cancelAutocomplete(),this.autocompleteProvider=t,this.setAutocompleteTriggerCharacters(t.triggerCharacters??[]);}addToHistory(t){let e=t.trim();e&&(this.history.length>0&&this.history[0]===e||(this.history.unshift(e),this.history.length>100&&this.history.pop()));}isEditorEmpty(){return this.state.lines.length===1&&this.state.lines[0]===""}isOnFirstVisualLine(){let t=this.buildVisualLineMap(this.lastWidth);return this.findCurrentVisualLine(t)===0}isOnLastVisualLine(){let t=this.buildVisualLineMap(this.lastWidth);return this.findCurrentVisualLine(t)===t.length-1}navigateHistory(t){if(this.lastAction=null,this.history.length===0)return;let e=this.historyIndex-t;if(!(e<-1||e>=this.history.length))if(this.historyIndex===-1&&e>=0&&(this.pushUndoSnapshot(),this.historyDraft=structuredClone(this.state)),this.historyIndex=e,this.historyIndex===-1){let r=this.historyDraft;this.historyDraft=null,r?(this.state=r,this.preferredVisualCol=null,this.snappedFromCursorCol=null,this.scrollOffset=0,this.onChange&&this.onChange(this.getText())):this.setTextInternal("");}else this.setTextInternal(this.history[this.historyIndex]||"",t===-1?"start":"end");}exitHistoryBrowsing(){this.historyIndex=-1,this.historyDraft=null;}setTextInternal(t,e="end"){let r=t.split(`
6
- `);this.state.lines=r.length===0?[""]:r,this.state.cursorLine=e==="start"?0:this.state.lines.length-1,this.setCursorCol(e==="start"?0:this.state.lines[this.state.cursorLine]?.length||0),this.scrollOffset=0,this.onChange&&this.onChange(this.getText());}invalidate(){}renderTopBorder(t,e){let r=e>0?Vn("\u2191",e,t):"\u2500".repeat(t);return this.borderColor(r)}renderBottomBorder(t,e){let r=e>0?Vn("\u2193",e,t):"\u2500".repeat(t);return this.borderColor(r)}render(t){let e=Math.max(0,Math.floor((t-1)/2)),r=Math.min(this.paddingX,e),n=Math.max(1,t-r*2),s=Math.max(1,n-(r?0:1));this.lastWidth=s;let o=this.layoutText(s),l=this.tui.terminal.rows,a=Math.max(5,Math.floor(l*.3)),c=o.findIndex(x=>x.hasCursor);c===-1&&(c=0),c<this.scrollOffset?this.scrollOffset=c:c>=this.scrollOffset+a&&(this.scrollOffset=c-a+1);let h=Math.max(0,o.length-a);this.scrollOffset=Math.max(0,Math.min(this.scrollOffset,h));let u=o.slice(this.scrollOffset,this.scrollOffset+a);this.renderedVisibleLineCount=u.length;let p=[],f=" ".repeat(r),b=f;p.push(this.renderTopBorder(t,this.scrollOffset));let m=this.focused;for(let x of u){let v=x.text,y=S(x.text),w=false;if(x.hasCursor&&x.cursorPos!==void 0){let L=v.slice(0,x.cursorPos),M=v.slice(x.cursorPos),E=m?ie:"";if(M.length>0){let C=[...this.segment(M,"grapheme")][0]?.segment||"",A=M.slice(C.length),D=Se(C);v=L+E+D+A;}else {let P=Se(" ");v=L+E+P,y=y+1,y>n&&r>0&&(w=true);}}let I=" ".repeat(Math.max(0,n-y)),T=w?b.slice(1):b;p.push(`${f}${v}${I}${T}`);}let g=o.length-(this.scrollOffset+u.length);if(p.push(this.renderBottomBorder(t,g)),this.renderedAutocompleteHeight=0,this.autocompleteState&&this.autocompleteList){let x=this.autocompleteList.render(n);this.renderedAutocompleteHeight=x.length;for(let v of x){let y=S(v),w=" ".repeat(Math.max(0,n-y));p.push(`${f}${v}${w}${b}`);}}return p}handleMouse(t){let e=this.renderedVisibleLineCount+2;if(this.autocompleteState&&this.autocompleteList&&t.y>=e&&t.y<e+this.renderedAutocompleteHeight){let g=Math.max(0,Math.floor((t.width-1)/2)),x=Math.min(this.paddingX,g),v=Math.max(1,t.width-x*2),y=this.autocompleteList.handleMouse?.({...t,x:t.x-x,y:t.y-e,width:v,height:this.renderedAutocompleteHeight});return y?{...y,focus:true}:void 0}if(t.type!=="click"||t.button!=="left")return;if(t.y<=0||t.y>this.renderedVisibleLineCount)return {handled:true,focus:true};let r=this.buildVisualLineMap(this.lastWidth),n=this.scrollOffset+t.y-1,s=r[n];if(!s)return {handled:true,focus:true};let o=this.state.lines[s.logicalLine]??"",l=s.startCol+s.length,a=o.slice(s.startCol,l),c=Math.max(0,Math.floor((t.width-1)/2)),h=Math.min(this.paddingX,c),u=Math.max(0,t.x-h),p=0,f=a.length,b=0;for(let g of this.segment(a,"grapheme")){let x=p+S(g.segment);if(b=g.index,u<x){f=g.index;break}p=x;}return !(n===r.length-1||r[n+1]?.logicalLine!==s.logicalLine)&&f===a.length&&a.length>0&&(f=b),this.state.cursorLine=s.logicalLine,this.setCursorCol(s.startCol+f),this.lastAction=null,this.exitHistoryBrowsing(),this.autocompleteState&&this.updateAutocomplete(),{handled:true,focus:true}}handleInput(t){let e=G();if(this.jumpMode!==null){if(e.matches(t,"tui.editor.jumpForward")||e.matches(t,"tui.editor.jumpBackward")){this.jumpMode=null;return}let n=$r(t)??(t.charCodeAt(0)>=32?t:void 0);if(n!==void 0){let s=this.jumpMode;this.jumpMode=null,this.jumpToChar(n,s);return}this.jumpMode=null;}if(t.includes("\x1B[200~")&&(this.isInPaste=true,this.pasteBuffer="",t=t.replace("\x1B[200~","")),this.isInPaste){this.pasteBuffer+=t;let n=this.pasteBuffer.indexOf("\x1B[201~");if(n!==-1){let s=this.pasteBuffer.substring(0,n);s.length>0&&this.handlePaste(s),this.isInPaste=false;let o=this.pasteBuffer.substring(n+6);this.pasteBuffer="",o.length>0&&this.handleInput(o);return}return}if(e.matches(t,"tui.input.copy"))return;if(e.matches(t,"tui.editor.undo")){this.undo();return}if(this.autocompleteState&&this.autocompleteList){if(e.matches(t,"tui.select.cancel")){this.cancelAutocomplete();return}if(e.matches(t,"tui.select.up")||e.matches(t,"tui.select.down")){this.autocompleteList.handleInput(t);return}if(e.matches(t,"tui.input.tab")){let n=this.autocompleteList.getSelectedItem();if(n&&this.autocompleteProvider){this.pushUndoSnapshot(),this.lastAction=null;let s=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,n,this.autocompletePrefix);this.state.lines=s.lines,this.state.cursorLine=s.cursorLine,this.setCursorCol(s.cursorCol),this.cancelAutocomplete(),this.onChange&&this.onChange(this.getText());}return}if(e.matches(t,"tui.select.confirm")){let n=this.autocompleteList.getSelectedItem();if(n&&this.autocompleteProvider){this.pushUndoSnapshot(),this.lastAction=null;let s=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,n,this.autocompletePrefix);if(this.state.lines=s.lines,this.state.cursorLine=s.cursorLine,this.setCursorCol(s.cursorCol),this.autocompletePrefix.startsWith("/")){if(this.cancelAutocomplete(),!(this.shouldAutoSubmitSlashCommand?.(n,this.autocompletePrefix)??true)){this.onChange&&this.onChange(this.getText());return}}else {this.cancelAutocomplete(),this.onChange&&this.onChange(this.getText()),Nn(n)&&this.tryTriggerAutocomplete();return}}}}if(e.matches(t,"tui.input.tab")&&!this.autocompleteState){this.handleTabCompletion();return}if(e.matches(t,"tui.editor.deleteToLineEnd")){this.deleteToEndOfLine();return}if(e.matches(t,"tui.editor.deleteToLineStart")){this.deleteToStartOfLine();return}if(e.matches(t,"tui.editor.deleteWordBackward")){this.deleteWordBackwards();return}if(e.matches(t,"tui.editor.deleteWordForward")){this.deleteWordForward();return}if(e.matches(t,"tui.editor.deleteCharBackward")||ae(t,"shift+backspace")){this.handleBackspace();return}if(e.matches(t,"tui.editor.deleteCharForward")||ae(t,"shift+delete")){this.handleForwardDelete();return}if(e.matches(t,"tui.editor.yank")){this.yank();return}if(e.matches(t,"tui.editor.yankPop")){this.yankPop();return}if(e.matches(t,"tui.editor.historyPrevious")){this.cancelAutocomplete(),this.navigateHistory(-1);return}if(e.matches(t,"tui.editor.historyNext")){this.cancelAutocomplete(),this.navigateHistory(1);return}if(e.matches(t,"tui.editor.cursorLineStart")){this.moveToLineStart();return}if(e.matches(t,"tui.editor.cursorLineEnd")){this.moveToLineEnd();return}if(e.matches(t,"tui.editor.cursorWordLeft")){this.moveWordBackwards();return}if(e.matches(t,"tui.editor.cursorWordRight")){this.moveWordForwards();return}if(e.matches(t,"tui.input.newLine")||t.charCodeAt(0)===10&&t.length>1||t==="\x1B\r"||t==="\x1B[13;2~"||t.length>1&&t.includes("\x1B")&&t.includes("\r")||t===`
7
- `&&t.length===1){if(this.shouldSubmitOnBackslashEnter(t,e)){this.handleBackspace(),this.submitValue();return}this.addNewLine();return}if(e.matches(t,"tui.input.submit")){if(this.disableSubmit)return;let n=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>0&&n[this.state.cursorCol-1]==="\\"){this.handleBackspace(),this.addNewLine();return}this.submitValue();return}if(e.matches(t,"tui.editor.cursorUp")){this.isOnFirstVisualLine()&&(this.isEditorEmpty()||this.historyIndex>-1||this.state.cursorCol===0)?this.navigateHistory(-1):this.isOnFirstVisualLine()?this.moveToLineStart():this.moveCursor(-1,0);return}if(e.matches(t,"tui.editor.cursorDown")){this.historyIndex>-1&&this.isOnLastVisualLine()?this.navigateHistory(1):this.isOnLastVisualLine()?this.moveToLineEnd():this.moveCursor(1,0);return}if(e.matches(t,"tui.editor.cursorRight")){this.moveCursor(0,1);return}if(e.matches(t,"tui.editor.cursorLeft")){this.moveCursor(0,-1);return}if(e.matches(t,"tui.editor.pageUp")){this.pageScroll(-1);return}if(e.matches(t,"tui.editor.pageDown")){this.pageScroll(1);return}if(e.matches(t,"tui.editor.jumpForward")){this.jumpMode="forward";return}if(e.matches(t,"tui.editor.jumpBackward")){this.jumpMode="backward";return}if(ae(t,"shift+space")){this.insertCharacter(" ");return}let r=$r(t);if(r!==void 0){this.insertCharacter(r);return}t.charCodeAt(0)>=32&&this.insertCharacter(t);}layoutText(t){let e=[];if(this.state.lines.length===0||this.state.lines.length===1&&this.state.lines[0]==="")return e.push({text:"",hasCursor:true,cursorPos:0}),e;for(let r=0;r<this.state.lines.length;r++){let n=this.state.lines[r]||"",s=r===this.state.cursorLine;if(S(n)<=t)s?e.push({text:n,hasCursor:true,cursorPos:this.state.cursorCol}):e.push({text:n,hasCursor:false});else {let l=Qr(n,t,[...this.segment(n,"grapheme")]);for(let a=0;a<l.length;a++){let c=l[a];if(!c)continue;let h=this.state.cursorCol,u=a===l.length-1,p=false,f=0;s&&(u?(p=h>=c.startIndex,f=h-c.startIndex):(p=h>=c.startIndex&&h<c.endIndex,p&&(f=h-c.startIndex,f>c.text.length&&(f=c.text.length)))),p?e.push({text:c.text,hasCursor:true,cursorPos:f}):e.push({text:c.text,hasCursor:false});}}}return e}getText(){return this.state.lines.join(`
1
+ import*as pe from'fs';import {readdirSync,statSync}from'fs';import*as Ls from'os';import {homedir}from'os';import*as Ae from'path';import {join,dirname,basename,isAbsolute}from'path';import {Ansi,Filesystem,Glob}from'@easbot/utils';import {performance as performance$1}from'perf_hooks';import {execSync}from'child_process';import {pathToFileURL,fileURLToPath}from'url';import {Marked,Tokenizer}from'marked';import {createRequire}from'module';import {EventEmitter}from'events';var Rs=Object.defineProperty;var Es=(i,t,e)=>t in i?Rs(i,t,{enumerable:true,configurable:true,writable:true,value:e}):i[t]=e;var d=(i,t,e)=>Es(i,typeof t!="symbol"?t+"":t,e);function wi(i,t){let e=i.toLowerCase(),r=t.toLowerCase(),n=h=>{if(h.length===0)return {matches:true,score:0};if(h.length>r.length)return {matches:false,score:0};let u=0,p=0,f=-1,b=0;for(;u<h.length;){let m=r.indexOf(h[u],f+1);if(m===-1)break;let g=m===0||/[\s\-_./:]/.test(r[m-1]);f===m-1?(b++,p-=b*5):(b=0,f>=0&&(p+=(m-f-1)*2)),g&&(p-=10),p+=m*.1,f=m,u++;}return u<h.length?{matches:false,score:0}:(h===r&&(p-=100),{matches:true,score:p})},s=n(e);if(s.matches)return s;let o=e.match(/^(?<letters>[a-z]+)(?<digits>[0-9]+)$/),l=e.match(/^(?<digits>[0-9]+)(?<letters>[a-z]+)$/),a=o?`${o.groups?.digits??""}${o.groups?.letters??""}`:l?`${l.groups?.letters??""}${l.groups?.digits??""}`:"";if(!a)return s;let c=n(a);return c.matches?{matches:true,score:c.score+5}:s}function Re(i,t,e){if(!t.trim())return i;let r=t.trim().split(/[\s/]+/).filter(s=>s.length>0);if(r.length===0)return i;let n=[];for(let s of i){let o=e(s),l=0,a=true;for(let c of r){let h=wi(c,o);if(h.matches)l+=h.score;else {a=false;break}}a&&n.push({item:s,totalScore:l});}return n.sort((s,o)=>s.totalScore-o.totalScore),n.map(s=>s.item)}var oe=new Intl.Segmenter(void 0,{granularity:"grapheme"}),Ps=new Intl.Segmenter(void 0,{granularity:"word"});function Pe(){return Ansi.getGraphemeSegmenter()}function Oe(){return Ps}var $e=/[\p{Script_Extensions=Han}\p{Script_Extensions=Hiragana}\p{Script_Extensions=Katakana}\p{Script_Extensions=Hangul}\p{Script_Extensions=Bopomofo}]/u,Os=new RegExp(`(?:(?=\\p{Punctuation})${$e.source}|[\uFF0C\uFF0E\uFF1A\uFF1B\uFF01\uFF1F\uFF08\uFF09\uFF3B\uFF3D\uFF5B\uFF5D\u201C\u201D\u2018\u2019\u2026\u2014])`,"u"),Ke=new RegExp(`(?:\\s|${Os.source})`,"u"),Ct=new RegExp(`(?:^|${Ke.source})`,"u");function gr(i){for(let t=0;t<i.length;t++){let e=i.charCodeAt(t);if(e<32||e>126)return false}return true}function $s(i,t){if(t<=0||i.length===0)return {text:"",width:0};if(gr(i)){let a=i.slice(0,t);return {text:a,width:a.length}}let e=i.includes("\x1B"),r=i.includes(" ");if(!e&&!r){let a="",c=0;for(let{segment:h}of oe.segment(i)){let u=me(h);if(c+u>t)break;a+=h,c+=u;}return {text:a,width:c}}let n="",s=0,o=0,l="";for(;o<i.length;){let a=W(i,o);if(a){l+=a.code,o+=a.length;continue}if(i[o]===" "){if(s+3>t)break;l&&(n+=l,l=""),n+=" ",s+=3,o++;continue}let c=o;for(;c<i.length&&i[c]!==" "&&!W(i,c);)c++;for(let{segment:h}of oe.segment(i.slice(o,c))){let u=me(h);if(s+u>t)return {text:n,width:s};l&&(n+=l,l=""),n+=h,s+=u;}o=c;}return {text:n,width:s}}function fr(i,t,e,r,n,s){let o="\x1B[0m",l=Ds(i),a=t+r,c;return e.length>0?c=`${i}${l}${o}${e}${o}`:c=`${i}${l}${o}`,s?c+" ".repeat(Math.max(0,n-a)):c}function me(i){return Ansi.graphemeWidth(i)}function S(i){return Ansi.visibleWidth(i)}function Be(i){if(!i.includes("\x1B"))return i;let t="",e=0;for(;e<i.length;){let r=W(i,e);if(r){e+=r.length;continue}t+=i[e],e++;}return t}function tt(i,t){let e=0,r=0;for(;r<i.length;){let n=W(i,r);if(n){r+=n.length;continue}let s=r;for(;s<i.length&&!W(i,s);)s++;for(let{segment:o}of oe.segment(i.slice(r,s))){let l=me(o);if(l>0&&t>=e&&t<e+l)return {start:e,end:e+l};e+=l;}r=s;}}function br(i,t){let e,r=0,n=0;for(;n<i.length;){let s=W(i,n);if(s){let l=/^\x1b\]8;[^;]*;([^\x07\x1b]*)(?:\x07|\x1b\\)$/.exec(s.code);l&&(e=l[1]||void 0),n+=s.length;continue}let o=n;for(;o<i.length&&!W(i,o);)o++;for(let{segment:l}of oe.segment(i.slice(n,o))){let a=l===" "?3:me(l);if(t>=r&&t<r+a)return e;r+=a;}n=o;}}var Ks=/[\u0e33\u0eb3]/,Bs=/[\u0e33\u0eb3]/g;function Ti(i){let t=i;if(Ks.test(t)&&(t=t.replace(Bs,n=>n==="\u0E33"?"\u0E4D\u0E32":"\u0ECD\u0EB2")),!t.includes(" "))return t;let e="",r=0;for(;r<t.length;){let n=W(t,r);if(n){e+=n.code,r+=n.length;continue}e+=t[r]===" "?" ":t[r],r++;}return e}function W(i,t){return Ansi.extractAnsiCode(i,t)}function Mi(i,t){if(t>=i.length||i.charCodeAt(t)!==27)return 0;let e=i[t+1];if(e==="["){for(let r=t+2;r<i.length;r++){let n=i.charCodeAt(r);if(n===109||n===71||n===75||n===72||n===74)return r+1-t}return 0}if(e==="]"||e==="_"){for(let r=t+2;r<i.length;r++){let n=i.charCodeAt(r);if(n===7)return r+1-t;if(n===27&&i[r+1]==="\\")return r+2-t}return 0}return 0}function Ii(i){if(!i.startsWith("\x1B]8;"))return;let t=i.endsWith("\x07")?"\x07":"\x1B\\",e=i.slice(4,t==="\x07"?-1:-2),r=e.indexOf(";");if(r===-1)return;let n=e.slice(0,r),s=e.slice(r+1);return s?{params:n,url:s,terminator:t}:null}function _s(i){return `\x1B]8;${i.params};${i.url}${i.terminator}`}function Li(i){return `\x1B]8;;${i}`}function Ds(i){if(!i.includes("\x1B]8;"))return "";let t=null,e=0;for(;e<i.length;){let r=W(i,e);if(r){let n=Ii(r.code);n!==void 0&&(t=n),e+=r.length;}else e++;}return t?Li(t.terminator):""}var Ee=class{constructor(){d(this,"bold",false);d(this,"dim",false);d(this,"italic",false);d(this,"underline",false);d(this,"blink",false);d(this,"inverse",false);d(this,"hidden",false);d(this,"strikethrough",false);d(this,"fgColor",null);d(this,"bgColor",null);d(this,"activeHyperlink",null);}process(t){let e=Ii(t);if(e!==void 0){this.activeHyperlink=e;return}if(!t.endsWith("m"))return;let r=t.match(/\x1b\[([\d;]*)m/);if(!r)return;let n=r[1]??"";if(n===""||n==="0"){this.reset();return}let s=n.split(";"),o=0;for(;o<s.length;){let l=Number.parseInt(s[o]??"",10);if(l===38||l===48){if(s[o+1]==="5"&&s[o+2]!==void 0){let a=`${s[o]};${s[o+1]};${s[o+2]}`;l===38?this.fgColor=a:this.bgColor=a,o+=3;continue}else if(s[o+1]==="2"&&s[o+4]!==void 0){let a=`${s[o]};${s[o+1]};${s[o+2]};${s[o+3]};${s[o+4]}`;l===38?this.fgColor=a:this.bgColor=a,o+=5;continue}}switch(l){case 0:this.reset();break;case 1:this.bold=true;break;case 2:this.dim=true;break;case 3:this.italic=true;break;case 4:this.underline=true;break;case 5:this.blink=true;break;case 7:this.inverse=true;break;case 8:this.hidden=true;break;case 9:this.strikethrough=true;break;case 21:this.bold=false;break;case 22:this.bold=false,this.dim=false;break;case 23:this.italic=false;break;case 24:this.underline=false;break;case 25:this.blink=false;break;case 27:this.inverse=false;break;case 28:this.hidden=false;break;case 29:this.strikethrough=false;break;case 39:this.fgColor=null;break;case 49:this.bgColor=null;break;default:l>=30&&l<=37||l>=90&&l<=97?this.fgColor=String(l):(l>=40&&l<=47||l>=100&&l<=107)&&(this.bgColor=String(l));break}o++;}}reset(){this.bold=false,this.dim=false,this.italic=false,this.underline=false,this.blink=false,this.inverse=false,this.hidden=false,this.strikethrough=false,this.fgColor=null,this.bgColor=null;}clear(){this.reset(),this.activeHyperlink=null;}getActiveCodes(){let t=[];this.bold&&t.push("1"),this.dim&&t.push("2"),this.italic&&t.push("3"),this.underline&&t.push("4"),this.blink&&t.push("5"),this.inverse&&t.push("7"),this.hidden&&t.push("8"),this.strikethrough&&t.push("9"),this.fgColor&&t.push(this.fgColor),this.bgColor&&t.push(this.bgColor);let e=t.length>0?`\x1B[${t.join(";")}m`:"";return this.activeHyperlink&&(e+=_s(this.activeHyperlink)),e}getActiveBackgroundCode(){return this.bgColor?`\x1B[${this.bgColor}m`:""}hasActiveCodes(){return this.bold||this.dim||this.italic||this.underline||this.blink||this.inverse||this.hidden||this.strikethrough||this.fgColor!==null||this.bgColor!==null||this.activeHyperlink!==null}getLineEndReset(){let t="";return this.underline&&(t+="\x1B[24m"),this.activeHyperlink&&(t+=Li(this.activeHyperlink.terminator)),t}};function yr(i,t){let e=i.indexOf("\x1B");for(;e!==-1;){let r=Mi(i,e);r>0?(t.process(i.substring(e,e+r)),e+=r):e++,e=i.indexOf("\x1B",e);}}function ki(i){let t=new Ee;return yr(i,t),t.getActiveBackgroundCode()}function*Ns(i){for(let{segment:t}of oe.segment(i))yield t;}function Fs(i){let t=[],e="",r="",n=null,s=0,o=()=>{e&&(t.push(e),e="",n=null);};for(;s<i.length;){let l=W(i,s);if(l){r+=l.code,s+=l.length;continue}let a=i.indexOf("\x1B",s+1);for(;a!==-1&&Mi(i,a)===0;)a=i.indexOf("\x1B",a+1);a===-1&&(a=i.length);let c=i.slice(s,a),h=gr(c);for(let u of h?c:Ns(c)){let p=u===" ";if(!h&&!p&&$e.test(u)){o();let b=r+u;r="",t.push(b);continue}let f=p?"space":"word";e&&n!==f&&o(),r&&(e+=r,r=""),n=f,e+=u;}s=a;}return r&&(e?e+=r:t.length>0?t[t.length-1]+=r:e=r),e&&t.push(e),t}function _e(i){for(let t of i)Number(t);}function ne(i,t){if(!i)return [""];let e=i.split(/\r\n|\r|\n/),r=[],n=new Ee;for(let s of e){let o=r.length>0?n.getActiveCodes():"",l=Ws(o+s,t);for(let a of l)r.push(a);yr(s,n);}return r.length>0?r:[""]}function Ws(i,t){if(!i)return [""];if(S(i)<=t)return [i];let r=[],n=new Ee,s=Fs(i),o="",l=0;for(let a of s){let c=S(a),h=a.trim()==="";if(c>t&&!h){if(o){let f=n.getLineEndReset();f&&(o+=f),r.push(o),o="",l=0;}let p=Vs(a,t,n);for(let f=0;f<p.length-1;f++)r.push(p[f]);o=p[p.length-1],l=S(o);continue}if(l+c>t&&l>0){let p=o.trimEnd(),f=n.getLineEndReset();f&&(p+=f),r.push(p),h?(o=n.getActiveCodes(),l=0):(o=n.getActiveCodes()+a,l=c);}else o+=a,l+=c;yr(a,n);}return o&&r.push(o),r.length>0?r.map(a=>a.trimEnd()):[""]}var xr=/[(){}[\]<>.,;:'"!?+\-=*/\\|&%^$#@~`]/;function X(i){return /\s/.test(i)}function Vs(i,t,e){let r=[],n=e.getActiveCodes(),s=0,o=0,l=[];for(;o<i.length;){let a=W(i,o);if(a)l.push({type:"ansi",value:a.code}),o+=a.length;else {let c=o;for(;c<i.length&&!W(i,c);)c++;let h=i.slice(o,c);for(let u of oe.segment(h))l.push({type:"grapheme",value:u.segment});o=c;}}for(let a of l){if(a.type==="ansi"){n+=a.value,e.process(a.value);continue}let c=a.value;if(!c)continue;let h=S(c);if(s+h>t){let u=e.getLineEndReset();u&&(n+=u),r.push(n),n=e.getActiveCodes(),s=0;}n+=c,s+=h;}return n&&r.push(n),r.length>0?r:[""]}function De(i,t,e){let r=S(i),n=Math.max(0,t-r),s=" ".repeat(n),o=i+s;return e(o)}function N(i,t,e="...",r=false){if(t<=0)return "";if(i.length===0)return r?" ".repeat(t):"";let n=S(e);if(n>=t){let m=S(i);if(m<=t)return r?i+" ".repeat(t-m):i;let g=$s(e,t);return g.width===0?r?" ".repeat(t):"":fr("",0,g.text,g.width,t,r)}if(gr(i)){if(i.length<=t)return r?i+" ".repeat(t-i.length):i;let m=t-n;return fr(i.slice(0,m),m,e,n,t,r)}let s=t-n,o="",l="",a=0,c=0,h=true,u=false,p=false,f=i.includes("\x1B"),b=i.includes(" ");if(!f&&!b){for(let{segment:m}of oe.segment(i)){let g=me(m);if(h&&c+g<=s?(o+=m,c+=g):h=false,a+=g,a>t){u=true;break}}p=!u;}else {let m=0;for(;m<i.length;){let g=W(i,m);if(g){l+=g.code,m+=g.length;continue}if(i[m]===" "){if(h&&c+3<=s?(l&&(o+=l,l=""),o+=" ",c+=3):(h=false,l=""),a+=3,a>t){u=true;break}m++;continue}let y=m;for(;y<i.length&&i[y]!==" "&&!W(i,y);)y++;for(let{segment:v}of oe.segment(i.slice(m,y))){let x=me(v);if(h&&c+x<=s?(l&&(o+=l,l=""),o+=v,c+=x):(h=false,l=""),a+=x,a>t){u=true;break}}if(u)break;m=y;}p=m>=i.length;}return !u&&p?r?i+" ".repeat(Math.max(0,t-a)):i:fr(o,c,e,n,t,r)}function V(i,t,e,r=false){return vr(i,t,e,r).text}function vr(i,t,e,r=false){if(e<=0)return {text:"",width:0};let n=t+e,s="",o=0,l=0,a=0,c="";for(;a<i.length;){let h=W(i,a);if(h){l>=t&&l<n?(s+=c+h.code,c=""):l<t&&(c+=h.code),a+=h.length;continue}let u=a;for(;u<i.length&&!W(i,u);)u++;for(let{segment:p}of oe.segment(i.slice(a,u))){let f=me(p),b=l>=t&&l<n,m=!r||l+f<=n;if(b&&m&&(c&&(s+=c,c=""),s+=p,o+=f),l+=f,l>=n)break}if(a=u,l>=n)break}return {text:s,width:o}}var mr=new Ee;function Ai(i,t,e,r,n=false){let s="",o=0,l="",a=0,c=0,h=0,u="",p=false,f=e+r;for(mr.clear();h<i.length;){let b=W(i,h);if(b){mr.process(b.code),c<t?u+=b.code:c>=e&&c<f&&(p||b.code.startsWith("\x1B_"))&&(l+=b.code),h+=b.length;continue}let m=h;for(;m<i.length&&!W(i,m);)m++;for(let{segment:g}of oe.segment(i.slice(h,m))){let y=me(g);if(c<t&&c+y<=t?(u&&(s+=u,u=""),s+=g,o+=y):c>=e&&c<f&&(!n||c+y<=f)&&(p||(l+=mr.getActiveCodes(),p=true),l+=g,a+=y),c+=y,r<=0?c>=t:c>=f)break}if(h=m,r<=0?c>=t:c>=f)break}return {before:s,beforeWidth:o,after:l,afterWidth:a}}var Ki=new Set([" "," ",'"',"'","="]),J="#",Tt="@",Tr=`${J}"`,Bi=`${Tt}"`,_i=new RegExp(`${Ct.source}$`,"u"),Di={"(":")","[":"]","{":"}","<":">","`":"`"};function Ni(i){return Filesystem.toUnixPath(i)}function Mr(i){let t=-1,e=0;for(let r of i)e+=r.length,(Ki.has(r)||Ke.test(r))&&(t=e-1);return t}function Ir(i){let t=i;for(;t.length>0;){let e=Di[t[0]];if(!e||t.includes(e,1))break;t=t.slice(1);}return t}function Us(i){let t=false,e=-1;for(let r=0;r<i.length;r+=1)i[r]==='"'&&(t=!t,t&&(e=r));return t?e:null}function Ei(i,t){let e=t;for(;e>0&&Di[i[e-1]];)e-=1;return Ki.has(i[e-1]??"")||_i.test(i.slice(0,e))}function Lr(i){let t=Us(i);return t===null?null:t>0&&i[t-1]===J?Ei(i,t-1)?i.slice(t-1):null:Ei(i,t)?i.slice(t):null}function qs(i){let t=i.indexOf(":");return t===-1||t===i.length-1?i:i.slice(t+1)}function Pi(i){return i.startsWith(Tr)?{rawPrefix:i.slice(2),isFilePrefix:true,isQuotedPrefix:true}:i.startsWith('"')?{rawPrefix:i.slice(1),isFilePrefix:false,isQuotedPrefix:true}:i.startsWith(J)?{rawPrefix:i.slice(1),isFilePrefix:true,isQuotedPrefix:false}:{rawPrefix:i,isFilePrefix:false,isQuotedPrefix:false}}function Oi(i,t){let e=t.isQuotedPrefix||Ke.test(i),r=t.isFilePrefix?J:"";return e?`${`${r}"`}${i}"`:`${r}${i}`}var Fi="{dirs}/{wildcard}";function Gs(i,t,e){return i.replace(/\{dirs\}/g,t.join("/")).replace(/\{wildcard\}/g,e).replace(/^\//,"")}function zs(i,t){let e=Filesystem.toUnixPath(i);if(e.split("/").some(a=>a===".."))return null;let r,n,s;e==="~"||e.startsWith("~/")?(r=Filesystem.normalize("~"),n="~/",s=e==="~"?"":e.slice(2)):e.startsWith("/")?(r="/",n="/",s=e.slice(1)):(r=t,n="",s=e);let o=s.endsWith("/"),l=s.split("/").filter(a=>a!==""&&a!==".");return {scanRoot:r,dirSegments:o?l:l.slice(0,-1),fileFilter:o?"":l[l.length-1]??"",displayPrefix:n}}async function Ys(i,t,e){if(e.aborted)return [];let r;try{r=await Glob.scan(t,{cwd:i.scanRoot,include:"all",dot:!0,symlink:!0,ignore:await js(i.scanRoot)});}catch{return []}if(e.aborted)return [];let n=[];for(let s of r){let o=Ni(s),l=Xs(i.scanRoot,o);n.push({path:l?`${o}/`:o,isDirectory:l});}return n}async function js(i){let t=[...Glob.DEFAULT_IGNORE_PATTERNS];for(let e of [".gitignore",".ignore"])try{let r=await Glob.parseGitignore(Filesystem.join(i,e));r.length>0&&t.push(...r);}catch{}return t}function Xs(i,t){try{return statSync(Filesystem.join(i,t)).isDirectory()}catch{return false}}function Wi(i){let t=Lr(i);if(t?.startsWith(Tr))return t;let e=Mr(i),r=Ir(e===-1?i:i.slice(e+1));return r.startsWith(J)?r:null}function Vi(i){let t=Lr(i);if(t?.startsWith(Bi))return t;let e=Mr(i),r=Ir(e===-1?i:i.slice(e+1));return r.startsWith(Tt)?r:null}var wr=class{constructor(t=[],e,r,n){d(this,"commands");d(this,"basePath");d(this,"commandSource");d(this,"attachmentGlobPattern");d(this,"attachmentWildcard");this.commands=t,this.basePath=e,this.commandSource=r,this.attachmentGlobPattern=n?.attachmentGlobPattern??Fi,this.attachmentWildcard=n?.attachmentWildcard??"*";}setCommands(t){this.commands=t;}async resolveCommands(t){if(!this.commandSource)return this.commands;let e;try{e=await this.commandSource();}catch{return this.commands}return t.aborted?[]:[...this.commands,...e]}async getSuggestions(t,e,r,n){let o=(t[e]||"").slice(0,r),l=this.extractFilePrefix(o);if(l){let{rawPrefix:u,isQuotedPrefix:p}=Pi(l),f=await this.getFuzzyFileSuggestions(u,{isQuotedPrefix:p,signal:n.signal});return f.length===0?null:{items:f,prefix:l}}if(this.extractAgentPrefix(o))return null;let a=o.trimStart();if(!n.force&&a.startsWith("/")){let u=a.indexOf(" ");if(u===-1){let y=a.slice(1),v=await this.resolveCommands(n.signal);if(n.signal.aborted)return null;let x=v.map(M=>{let E="name"in M?M.name:M.value,P="argumentHint"in M&&M.argumentHint?M.argumentHint:void 0,C=M.description??"",A=P?C?`${P} \u2014 ${C}`:P:C,D="group"in M?M.group:void 0,B="label"in M&&M.label?M.label:E,U="matchAlias"in M&&M.matchAlias?M.matchAlias:qs(E);return {name:E,label:B,description:A||void 0,group:D,matchAlias:U}}),w=Re(x,y,M=>M.matchAlias),I=new Set(w),T=Re(x.filter(M=>M.matchAlias!==M.name&&!I.has(M)),y,M=>M.name),L=[...w,...T].map(M=>({value:M.name,label:M.label,...M.description&&{description:M.description},...M.group&&{group:M.group}}));return L.length===0?null:{items:L,prefix:a}}let p=a.slice(1,u),f=a.slice(u+1),b=await this.resolveCommands(n.signal);if(n.signal.aborted)return null;let m=b.find(y=>("name"in y?y.name:y.value)===p);if(!m||!("getArgumentCompletions"in m)||!m.getArgumentCompletions)return null;let g=await m.getArgumentCompletions(f);return !Array.isArray(g)||g.length===0?null:{items:g,prefix:f}}let c=this.extractPathPrefix(o,n.force??false);if(c===null)return null;let h=this.getFileSuggestions(c);return h.length===0?null:{items:h,prefix:c}}applyCompletion(t,e,r,n,s){let o=t[e]||"",l=o.slice(0,r-s.length),a=o.slice(r),c=s.startsWith('"')||s.startsWith(Tr)||s.startsWith(Bi),h=a.startsWith('"'),u=n.value.endsWith('"'),p=c&&u&&h?a.slice(1):a;if(s.startsWith("/")&&l.trim()===""&&!s.slice(1).includes("/")){let w=`${l}/${n.value} ${p}`,I=[...t];return I[e]=w,{lines:I,cursorLine:e,cursorCol:l.length+n.value.length+2}}if(s.startsWith(J)||s.startsWith(Tt)){let w=n.label.endsWith("/"),I=w?"":" ",T=`${l+n.value}${I}${p}`,L=[...t];L[e]=T;let M=n.value.endsWith('"'),E=w&&M?n.value.length-1:n.value.length;return {lines:L,cursorLine:e,cursorCol:l.length+E+I.length}}let b=o.slice(0,r);if(b.includes("/")&&b.includes(" ")){let w=l+n.value+p,I=[...t];I[e]=w;let T=n.label.endsWith("/"),L=n.value.endsWith('"'),M=T&&L?n.value.length-1:n.value.length;return {lines:I,cursorLine:e,cursorCol:l.length+M}}let m=l+n.value+p,g=[...t];g[e]=m;let y=n.label.endsWith("/"),v=n.value.endsWith('"'),x=y&&v?n.value.length-1:n.value.length;return {lines:g,cursorLine:e,cursorCol:l.length+x}}extractFilePrefix(t){return Wi(t)}extractAgentPrefix(t){return Vi(t)}extractPathPrefix(t,e=false){let r=Lr(t);if(r)return r;let n=Mr(t),s=Ir(n===-1?t:t.slice(n+1));return e||s.includes("/")||s.startsWith(".")||s.startsWith("~/")||s===""&&t!==""&&_i.test(t)?s:null}expandHomePath(t){if(t.startsWith("~/")){let e=join(homedir(),t.slice(2));return t.endsWith("/")&&!e.endsWith("/")?`${e}/`:e}else if(t==="~")return homedir();return t}getFileSuggestions(t){try{let e,r,{rawPrefix:n,isFilePrefix:s,isQuotedPrefix:o}=Pi(t),l=n;if(l.startsWith("~")&&(l=this.expandHomePath(l)),n===""||n==="./"||n==="../"||n==="~"||n==="~/"||n==="/"||s&&n==="")n.startsWith("~")||l.startsWith("/")?e=l:e=join(this.basePath,l),r="";else if(n.endsWith("/"))n.startsWith("~")||l.startsWith("/")?e=l:e=join(this.basePath,l),r="";else {let u=dirname(l),p=basename(l);n.startsWith("~")||l.startsWith("/")?e=u:e=join(this.basePath,u),r=p;}let c=readdirSync(e,{withFileTypes:!0}),h=[];for(let u of c){if(!u.name.toLowerCase().startsWith(r.toLowerCase()))continue;let p=u.isDirectory();if(!p&&u.isSymbolicLink())try{let v=join(e,u.name);p=statSync(v).isDirectory();}catch{}let f,b=u.name,m=n;if(m.endsWith("/"))f=m+b;else if(m.includes("/")||m.includes("\\"))if(m.startsWith("~/")){let v=m.slice(2),x=dirname(v);f=`~/${x==="."?b:join(x,b)}`;}else if(m.startsWith("/")){let v=dirname(m);v==="/"?f=`/${b}`:f=`${v}/${b}`;}else f=join(dirname(m),b),m.startsWith("./")&&!f.startsWith("./")&&(f=`./${f}`);else m.startsWith("~")?f=`~/${b}`:f=b;f=Ni(f);let g=p?`${f}/`:f,y=Oi(g,{isDirectory:p,isFilePrefix:s,isQuotedPrefix:o});h.push({value:y,label:b+(p?"/":"")});}return h.sort((u,p)=>{let f=u.label.endsWith("/"),b=p.label.endsWith("/");return f&&!b?-1:!f&&b?1:u.label.localeCompare(p.label)}),h}catch{return []}}scoreEntry(t,e,r){let s=basename(t).toLowerCase(),o=e.toLowerCase(),l=0;return s===o?l=100:s.startsWith(o)?l=80:s.includes(o)?l=50:t.toLowerCase().includes(o)&&(l=30),r&&l>0&&(l+=10),l}async getBaseDirSuggestions(t,e,r){return r.aborted?[]:await Ys(t,e,r)}async getFuzzyFileSuggestions(t,e){if(e.signal.aborted)return [];try{let r=zs(t,this.basePath);if(!r)return [];let n=Gs(this.attachmentGlobPattern,r.dirSegments,this.attachmentWildcard),s=await this.getBaseDirSuggestions(r,n,e.signal);if(e.signal.aborted)return [];let o=s.map(c=>({...c,score:r.fileFilter?this.scoreEntry(c.path,r.fileFilter,c.isDirectory):1})).filter(c=>c.score>0);o.sort((c,h)=>{let u=h.score-c.score;if(u!==0)return u;let p=c.path.length-h.path.length;return p!==0?p:c.path.localeCompare(h.path)});let l=o.slice(0,20),a=[];for(let{path:c,isDirectory:h}of l){let u=h?c.slice(0,-1):c,p=`${r.displayPrefix}${u}`,f=basename(u),b=h?`${p}/`:p,m=Oi(b,{isDirectory:h,isFilePrefix:!0,isQuotedPrefix:e.isQuotedPrefix});a.push({value:m,label:f+(h?"/":""),description:p});}return a}catch{return []}}shouldTriggerFileCompletion(t,e,r){let s=(t[e]||"").slice(0,r);return !(s.trim().startsWith("/")&&!s.trim().includes(" "))}};var Lt=(i,[t,e,r])=>i.map(n=>n[0]*t+n[1]*e+n[2]*r),Qs=[[.4122214694707629,.5363325372617349,.0514459932675022],[.2119034958178251,.6806995506452344,.1073969535369405],[.0883024591900564,.2817188391361215,.6299787016738222]],Js=[[.210454268309314,.793617774702305,-0.0040720430116193],[1.9779985324311684,-2.42859224204858,.450593709617411],[.0259040424655478,.7827717124575296,-0.8086757549230774]],Mt=[[1,.3963377773761749,.2158037573099136],[1,-0.1055613458156586,-0.0638541728258133],[1,-0.0894841775298119,-1.2914855480194092]],kr=[[4.076741636075958,-3.307711539258063,.2309699031821043],[-1.2684379732850315,2.609757349287688,-0.341319376002657],[-0.0041960761386756,-0.7034186179359362,1.7076146940746117]],Hi=[[[-1.8817031,-0.80936501],[1.19086277,1.76576728,.59662641,.75515197,.56771245]],[[1.8144408,-1.19445267],[.73956515,-0.45954404,.08285427,.12541073,-0.14503204]],[[.13110758,1.81333971],[1.35733652,-915799e-8,-1.1513021,-0.50559606,.00692167]]],kt=.206,Ar=.03,It=(1+kt)/(1+Ar),Ui=i=>.5*(It*i-kt+Math.sqrt((It*i-kt)**2+4*Ar*It*i)),Zs=i=>(i*i+kt*i)/(It*(i+Ar)),eo=i=>i>.0031308?1.055*i**(1/2.4)-.055:12.92*i,to=i=>i<=.04045?i/12.92:((i+.055)/1.055)**2.4;function At(i){return Lt(kr,Lt(Mt,i).map(t=>t**3))}function ro(i){return Lt(Js,Lt(Qs,i).map(Math.cbrt))}function Rr({r:i,g:t,b:e}){return ro([i/255,t/255,e/255].map(to))}function Rt(i){let[t,e,r]=i.map(n=>Math.round(Math.min(1,Math.max(0,eo(n)))*255));return {r:t,g:e,b:r}}function qi(i,t){return [Mt[0],Mt[1],Mt[2]].map(e=>e[1]*i+e[2]*t)}function io(i,t){let e=Hi.findIndex(([[g,y]],v)=>v===2||g*i+y*t>1),[r,n,s,o,l]=Hi[e][1],a=kr[e],c=r+n*i+s*t+o*i*i+l*i*t,h=qi(i,t),u=h.map(g=>1+c*g),p=g=>g.reduce((y,v,x)=>y+a[x]*v,0),f=p(u.map(g=>g**3)),b=p(u.map((g,y)=>3*h[y]*g**2)),m=p(u.map((g,y)=>6*h[y]**2*g));return c-f*b/(b*b-.5*f*m)}function no(i,t){let e=io(i,t),r=Math.cbrt(1/Math.max(...At([1,e*i,e*t])));return [r,r*e]}function so(i,t,e,[r,n]){if(e<=r)return n*e/r;let s=n*(e-1)/(r-1),o=qi(i,t),l=o.map(f=>e+s*f),a=l.map(f=>f**3),c=l.map((f,b)=>3*o[b]*f**2),h=l.map((f,b)=>6*o[b]**2*f),u=(f,b)=>f[0]*b[0]+f[1]*b[1]+f[2]*b[2],p=kr.map(f=>{let b=u(f,a)-1,m=u(f,c),g=u(f,h),y=m/(m*m-.5*b*g);return y>=0?-b*y:Number.MAX_VALUE});return s+Math.min(...p)}function Gi(i,t,e){let r=no(t,e),n=so(t,e,i,r),s=n/Math.min(i*(r[1]/r[0]),(1-i)*(r[1]/(1-r[0]))),o=.11516993+1/(7.4477897+4.1590124*e+t*(-2.19557347+1.75198401*e+t*(-2.13704948-10.02301043*e+t*(-4.24894561+5.38770819*e+4.69891013*t)))),l=.11239642+1/(1.6132032-.68124379*e+t*(.40370612+.90148123*e+t*(-0.27087943+.6122399*e+t*(.00299215-.45399568*e-.14661872*t)))),a=.9*s*Math.sqrt(Math.sqrt(1/(1/(i*o)**4+1/((1-i)*l)**4)));return [Math.sqrt(1/(1/(i*.4)**2+1/((1-i)*.8)**2)),a,n]}function zi(i,t,e){let r=Zs(e),n=[r,0,0];if(r>0&&r<1&&t>0){let s=2*Math.PI*((i%360+360)%360)/360,o=Math.cos(s),l=Math.sin(s),[a,c,h]=Gi(r,o,l),u;if(t<.8){let p=1.25*t,f=.8*a;u=p*f/(1-(1-f/c)*p);}else {let p=5*(t-.8),f=.2*c**2*1.25**2/a;u=c+p*f/(1-(1-f/(h-c))*p);}n=[r,u*o,u*l];}return Rt(At(n))}function Yi(i){let[t,e,r]=Rr(i),n=Math.hypot(e,r),s=Ui(t);if(n<1e-9||s<=0||s>=1)return {h:0,s:0,l:s};let o=(Math.atan2(r,e)*180/Math.PI+360)%360,[l,a,c]=Gi(t,e/n,r/n),h;if(n<a){let u=.8*l;h=.8*(n/(u+(1-u/a)*n));}else {let u=.2*a**2*1.5625/l,p=n-a;h=.8+.2*(p/(u+(1-u/(c-a))*p));}return {h:o,s:Math.min(1,Math.max(0,h)),l:s}}function ge(i,t){if(!Number.isFinite(i))throw new Error(`${t} must be finite`)}function Ji(i){if(!Number.isInteger(i)||i<0||i>255)throw new Error(`ANSI color index must be an integer from 0 to 255: ${i}`);return Object.freeze({kind:"indexed",index:i})}function Pt(i,t,e){for(let[r,n]of [["r",i],["g",t],["b",e]])if(ge(n,r),n<0||n>255)throw new Error(`${r} must be between 0 and 255: ${n}`);return Object.freeze({kind:"rgb",r:i,g:t,b:e})}function Pr(i,t,e){if(ge(i,"l"),ge(t,"c"),ge(e,"h"),i<0||i>1)throw new Error(`l must be between 0 and 1: ${i}`);if(t<0)throw new Error(`c must not be negative: ${t}`);return Object.freeze({kind:"oklch",l:i,c:t,h:(e%360+360)%360})}var Ne=String.raw`[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?`,oo=new RegExp(`^oklch\\(\\s*(${Ne})(%)?\\s+(${Ne})\\s+(${Ne})(?:deg)?\\s*\\)$`,"i"),ao=new RegExp(`^okhsl\\(\\s*(${Ne})(?:deg)?\\s+(${Ne})(%)?\\s+(${Ne})(%)?\\s*\\)$`,"i");function Zi(i,t,e){if(ge(i,"h"),ge(t,"s"),ge(e,"l"),t<0||t>1)throw new Error(`s must be between 0 and 1: ${t}`);if(e<0||e>1)throw new Error(`l must be between 0 and 1: ${e}`);let{r,g:n,b:s}=zi(i,t,e);return Pt(r,n,s)}function lo(i){return Yi(xe(i))}function co(i){if(typeof i=="number")return Ji(i);let e=/^#([\da-f]{3}|[\da-f]{6})$/i.exec(i)?.[1];if(e){let s=e.length===3?[...e].map(o=>o+o).join(""):e;return Pt(Number.parseInt(s.slice(0,2),16),Number.parseInt(s.slice(2,4),16),Number.parseInt(s.slice(4,6),16))}let r=oo.exec(i);if(r){let s=Number.parseFloat(r[1])/(r[2]?100:1);return Pr(s,Number.parseFloat(r[3]),Number.parseFloat(r[4]))}let n=ao.exec(i);if(n){let s=Number.parseFloat(n[2])/(n[3]?100:1),o=Number.parseFloat(n[4])/(n[5]?100:1);return Zi(Number.parseFloat(n[1]),s,o)}throw new Error(`Invalid color value: ${i}`)}var uo=[{r:0,g:0,b:0},{r:128,g:0,b:0},{r:0,g:128,b:0},{r:128,g:128,b:0},{r:0,g:0,b:128},{r:128,g:0,b:128},{r:0,g:128,b:128},{r:192,g:192,b:192},{r:128,g:128,b:128},{r:255,g:0,b:0},{r:0,g:255,b:0},{r:255,g:255,b:0},{r:0,g:0,b:255},{r:255,g:0,b:255},{r:0,g:255,b:255},{r:255,g:255,b:255}],le=[0,95,135,175,215,255],ji=Array.from({length:24},(i,t)=>8+t*10);function ho(i){if(i<16)return {...uo[i]};if(i<232){let e=i-16;return {r:le[Math.floor(e/36)],g:le[Math.floor(e%36/6)],b:le[e%6]}}let t=8+(i-232)*10;return {r:t,g:t,b:t}}function Xi(i){return i.every(e=>e>=-1e-7&&e<=1+1e-7)}function po({l:i,c:t,h:e}){let r=e*Math.PI/180,n=Math.cos(r),s=Math.sin(r),o=u=>At([i,u*n,u*s]),l=o(t);if(Xi(l))return Rt(l);let a=o(0),c=0,h=t;for(let u=0;u<20;u++){let p=(c+h)/2,f=o(p);Xi(f)?(c=p,a=f):h=p;}return Rt(a)}function xe(i){switch(i.kind){case "indexed":return ho(i.index);case "rgb":return {r:i.r,g:i.g,b:i.b};case "oklch":return po(i)}}function Er(i){if(i.kind==="oklch")return {l:i.l,c:i.c,h:i.h};let[t,e,r]=Rr(xe(i));return {l:t,c:Math.hypot(e,r),h:(Math.atan2(r,e)*180/Math.PI+360)%360}}function fo(i){let{r:t,g:e,b:r}=xe(i),n=s=>Math.round(s).toString(16).padStart(2,"0");return `#${n(t)}${n(e)}${n(r)}`}function mo(i,t,e,r="oklch"){if(ge(e,"amount"),e<0||e>1)throw new Error(`amount must be between 0 and 1: ${e}`);if(r==="srgb"){let c=xe(i),h=xe(t);return Pt(c.r+(h.r-c.r)*e,c.g+(h.g-c.g)*e,c.b+(h.b-c.b)*e)}let n=Er(i),s=Er(t),o=n.c<1e-7?s.h:n.h,a=((s.c<1e-7?o:s.h)-o+540)%360-180;return Pr(n.l+(s.l-n.l)*e,n.c+(s.c-n.c)*e,o+a*e)}function Et(i,t){let e=0,r=1/0;for(let n=0;n<i.length;n++){let s=Math.abs(t-i[n]);s<r&&(e=n,r=s);}return e}function Qi(i,t){let e=i.r-t.r,r=i.g-t.g,n=i.b-t.b;return e*e*.299+r*r*.587+n*n*.114}function go(i){let t=Et(le,i.r),e=Et(le,i.g),r=Et(le,i.b),n={r:le[t],g:le[e],b:le[r]},s=16+36*t+6*e+r,o=Math.round(.299*i.r+.587*i.g+.114*i.b),l=Et(ji,o),a=ji[l];return Math.max(i.r,i.g,i.b)-Math.min(i.r,i.g,i.b)<10&&Qi(i,{r:a,g:a,b:a})<Qi(i,n)?232+l:s}function en(i,t,e){if(i.kind==="indexed")return `\x1B[${e?48:38};5;${i.index}m`;let r=xe(i);return t==="truecolor"?`\x1B[${e?48:38};2;${Math.round(r.r)};${Math.round(r.g)};${Math.round(r.b)}m`:`\x1B[${e?48:38};5;${go(r)}m`}function tn(i,t){return en(i,t,false)}function rn(i,t){return en(i,t,true)}function bo(i,t,e){return nn(i,t.fg&&tn(t.fg,e),t.bg&&rn(t.bg,e),t)}function nn(i,t,e,r){let n="",s="";return t&&(n+=t,s="\x1B[39m"),e&&(n+=e,s=`\x1B[49m${s}`),r.bold&&(n+="\x1B[1m"),r.dim&&(n+="\x1B[2m"),(r.bold||r.dim)&&(s=`\x1B[22m${s}`),r.italic&&(n+="\x1B[3m",s=`\x1B[23m${s}`),r.underline&&(n+="\x1B[4m",s=`\x1B[24m${s}`),r.inverse&&(n+="\x1B[7m",s=`\x1B[27m${s}`),r.strikethrough&&(n+="\x1B[9m",s=`\x1B[29m${s}`),`${n}${i}${s}`}var q=false;function st(i){q=i;}function yo(){return q}var xo={escape:"escape",esc:"esc",enter:"enter",return:"return",tab:"tab",space:"space",backspace:"backspace",delete:"delete",insert:"insert",clear:"clear",home:"home",end:"end",pageUp:"pageUp",pageDown:"pageDown",up:"up",down:"down",left:"left",right:"right",f1:"f1",f2:"f2",f3:"f3",f4:"f4",f5:"f5",f6:"f6",f7:"f7",f8:"f8",f9:"f9",f10:"f10",f11:"f11",f12:"f12",backtick:"`",hyphen:"-",equals:"=",leftbracket:"[",rightbracket:"]",backslash:"\\",semicolon:";",quote:"'",comma:",",period:".",slash:"/",exclamation:"!",at:"@",hash:"#",dollar:"$",percent:"%",caret:"^",ampersand:"&",asterisk:"*",leftparen:"(",rightparen:")",underscore:"_",plus:"+",pipe:"|",tilde:"~",leftbrace:"{",rightbrace:"}",colon:":",lessthan:"<",greaterthan:">",question:"?",ctrl:i=>`ctrl+${i}`,shift:i=>`shift+${i}`,alt:i=>`alt+${i}`,super:i=>`super+${i}`,ctrlShift:i=>`ctrl+shift+${i}`,shiftCtrl:i=>`shift+ctrl+${i}`,ctrlAlt:i=>`ctrl+alt+${i}`,altCtrl:i=>`alt+ctrl+${i}`,shiftAlt:i=>`shift+alt+${i}`,altShift:i=>`alt+shift+${i}`,ctrlSuper:i=>`ctrl+super+${i}`,superCtrl:i=>`super+ctrl+${i}`,shiftSuper:i=>`shift+super+${i}`,superShift:i=>`super+shift+${i}`,altSuper:i=>`alt+super+${i}`,superAlt:i=>`super+alt+${i}`,ctrlShiftAlt:i=>`ctrl+shift+alt+${i}`,ctrlShiftSuper:i=>`ctrl+shift+super+${i}`},be=new Set(["`","-","=","[","]","\\",";","'",",",".","/","!","@","#","$","%","^","&","*","(",")","_","+","|","~","{","}",":","<",">","?"]),ln=new Set("~!@#$%^&*()_+|{}:<>?"),vo=["shift","alt","ctrl","super"],k={shift:1,alt:2,ctrl:4,super:8},K={escape:27,tab:9,enter:13,space:32,backspace:127,kpEnter:57414},H={up:-1,down:-2,right:-3,left:-4},_={delete:-10,insert:-11,pageUp:-12,pageDown:-13,home:-14,end:-15},So=new Map([[57399,48],[57400,49],[57401,50],[57402,51],[57403,52],[57404,53],[57405,54],[57406,55],[57407,56],[57408,57],[57409,46],[57410,47],[57411,42],[57412,45],[57413,43],[57415,61],[57416,44],[57417,H.left],[57418,H.right],[57419,H.up],[57420,H.down],[57421,_.pageUp],[57422,_.pageDown],[57423,_.home],[57424,_.end],[57425,_.insert],[57426,_.delete]]);function Fe(i){return So.get(i)??i}function nt(i,t){return (t&-193&k.shift)!==0&&i>=65&&i<=90?i+32:i}function Kt(i,t,e){if(i===void 0||(t&k.shift)===0)return;let r=Fe(i);if(e.has(String.fromCharCode(r)))return {codepoint:r,modifier:t&-2}}var Z={up:["\x1B[A","\x1BOA"],down:["\x1B[B","\x1BOB"],right:["\x1B[C","\x1BOC"],left:["\x1B[D","\x1BOD"],home:["\x1B[H","\x1BOH","\x1B[1~","\x1B[7~"],end:["\x1B[F","\x1BOF","\x1B[4~","\x1B[8~"],insert:["\x1B[2~"],delete:["\x1B[3~"],pageUp:["\x1B[5~","\x1B[[5~"],pageDown:["\x1B[6~","\x1B[[6~"],clear:["\x1B[E","\x1BOE"],f1:["\x1BOP","\x1B[11~","\x1B[[A"],f2:["\x1BOQ","\x1B[12~","\x1B[[B"],f3:["\x1BOR","\x1B[13~","\x1B[[C"],f4:["\x1BOS","\x1B[14~","\x1B[[D"],f5:["\x1B[15~","\x1B[[E"],f6:["\x1B[17~"],f7:["\x1B[18~"],f8:["\x1B[19~"],f9:["\x1B[20~"],f10:["\x1B[21~"],f11:["\x1B[23~"],f12:["\x1B[24~"]},Co={up:["\x1B[a"],down:["\x1B[b"],right:["\x1B[c"],left:["\x1B[d"],clear:["\x1B[e"],insert:["\x1B[2$"],delete:["\x1B[3$"],pageUp:["\x1B[5$"],pageDown:["\x1B[6$"],home:["\x1B[7$"],end:["\x1B[8$"]},wo={up:["\x1BOa"],down:["\x1BOb"],right:["\x1BOc"],left:["\x1BOd"],clear:["\x1BOe"],insert:["\x1B[2^"],delete:["\x1B[3^"],pageUp:["\x1B[5^"],pageDown:["\x1B[6^"],home:["\x1B[7^"],end:["\x1B[8^"]},To={"\x1BOA":"up","\x1BOB":"down","\x1BOC":"right","\x1BOD":"left","\x1BOH":"home","\x1BOF":"end","\x1B[E":"clear","\x1BOE":"clear","\x1BOe":"ctrl+clear","\x1B[e":"shift+clear","\x1B[2~":"insert","\x1B[2$":"shift+insert","\x1B[2^":"ctrl+insert","\x1B[3$":"shift+delete","\x1B[3^":"ctrl+delete","\x1B[[5~":"pageUp","\x1B[[6~":"pageDown","\x1B[a":"shift+up","\x1B[b":"shift+down","\x1B[c":"shift+right","\x1B[d":"shift+left","\x1BOa":"ctrl+up","\x1BOb":"ctrl+down","\x1BOc":"ctrl+right","\x1BOd":"ctrl+left","\x1B[5$":"shift+pageUp","\x1B[6$":"shift+pageDown","\x1B[7$":"shift+home","\x1B[8$":"shift+end","\x1B[5^":"ctrl+pageUp","\x1B[6^":"ctrl+pageDown","\x1B[7^":"ctrl+home","\x1B[8^":"ctrl+end","\x1BOP":"f1","\x1BOQ":"f2","\x1BOR":"f3","\x1BOS":"f4","\x1B[11~":"f1","\x1B[12~":"f2","\x1B[13~":"f3","\x1B[14~":"f4","\x1B[[A":"f1","\x1B[[B":"f2","\x1B[[C":"f3","\x1B[[D":"f4","\x1B[[E":"f5","\x1B[15~":"f5","\x1B[17~":"f6","\x1B[18~":"f7","\x1B[19~":"f8","\x1B[20~":"f9","\x1B[21~":"f10","\x1B[23~":"f11","\x1B[24~":"f12","\x1Bb":"alt+left","\x1Bf":"alt+right","\x1Bp":"alt+up","\x1Bn":"alt+down"},j=(i,t)=>t.includes(i),Q=(i,t,e)=>e===k.shift?j(i,Co[t]):e===k.ctrl?j(i,wo[t]):false;function ot(i){return i.includes("\x1B[200~")?false:!!(i.includes(":3u")||i.includes(":3~")||i.includes(":3A")||i.includes(":3B")||i.includes(":3C")||i.includes(":3D")||i.includes(":3H")||i.includes(":3F"))}function Mo(i){return i.includes("\x1B[200~")?false:!!(i.includes(":2u")||i.includes(":2~")||i.includes(":2A")||i.includes(":2B")||i.includes(":2C")||i.includes(":2D")||i.includes(":2H")||i.includes(":2F"))}function $t(i){if(!i)return "press";let t=parseInt(i,10);return t===2?"repeat":t===3?"release":"press"}function cn(i){let t=i.match(/^\x1b\[(\d+)(?::(\d*))?(?::(\d+))?(?:;(\d+))?(?::(\d+))?u$/);if(t){let s=parseInt(t[1],10),o=t[2]&&t[2].length>0?parseInt(t[2],10):void 0,l=t[3]?parseInt(t[3],10):void 0,a=t[4]?parseInt(t[4],10):1,c=$t(t[5]);return {codepoint:s,shiftedKey:o,baseLayoutKey:l,modifier:a-1,eventType:c}}let e=i.match(/^\x1b\[1;(\d+)(?::(\d+))?([ABCD])$/);if(e){let s=parseInt(e[1],10),o=$t(e[2]),l={A:-1,B:-2,C:-3,D:-4};return {codepoint:l[e[3]],modifier:s-1,eventType:o}}let r=i.match(/^\x1b\[(\d+)(?:;(\d+))?(?::(\d+))?~$/);if(r){let s=parseInt(r[1],10),o=r[2]?parseInt(r[2],10):1,l=$t(r[3]),c={2:_.insert,3:_.delete,5:_.pageUp,6:_.pageDown,7:_.home,8:_.end}[s];if(c!==void 0)return {codepoint:c,modifier:o-1,eventType:l}}let n=i.match(/^\x1b\[1;(\d+)(?::(\d+))?([HF])$/);if(n){let s=parseInt(n[1],10),o=$t(n[2]),l=n[3]==="H"?_.home:_.end;return {codepoint:l,modifier:s-1,eventType:o}}return null}function R(i,t,e){let r=cn(i);if(!r)return false;let n=r.modifier&-193,s=e&-193,o=nt(Fe(r.codepoint),r.modifier),l=nt(Fe(t),e);if(n===s&&o===l)return true;let a=Kt(r.shiftedKey,n,be);if(a&&(a.modifier&-193)===s&&a.codepoint===Fe(t))return true;if(n!==s)return false;if(r.baseLayoutKey!==void 0&&r.baseLayoutKey===t){let c=o,h=c>=97&&c<=122,u=be.has(String.fromCharCode(c));if(!h&&!u)return true}return false}function Bt(i){let t=i.match(/^\x1b\[27;(\d+);(\d+)~$/);if(!t)return null;let e=parseInt(t[1],10);return {codepoint:parseInt(t[2],10),modifier:e-1}}function ee(i,t,e){let r=Bt(i);return r?r.codepoint===t&&r.modifier===e:false}function un(){return !!process.env.WT_SESSION&&!process.env.SSH_CONNECTION&&!process.env.SSH_CLIENT&&!process.env.SSH_TTY}function sn(i,t){return i==="\x7F"?t===0:i!=="\b"?false:un()?t===k.ctrl:t===0}function Io(i){let t=i.toLowerCase(),e=t.charCodeAt(0);return e>=97&&e<=122||t==="["||t==="\\"||t==="]"||t==="_"?String.fromCharCode(e&31):t==="-"?"":null}function on(i){return i>="0"&&i<="9"}function it(i,t,e){let r=Bt(i);if(!r)return false;if(r.modifier===e&&nt(r.codepoint,r.modifier)===nt(t,e))return true;let s=Kt(r.codepoint,r.modifier,ln);return s?.modifier===e&&s.codepoint===t}function Lo(i,t){let e=[],r=t&-193;if((r&-16)===0)return r&k.shift&&e.push("shift"),r&k.ctrl&&e.push("ctrl"),r&k.alt&&e.push("alt"),r&k.super&&e.push("super"),e.length>0?`${e.join("+")}+${i}`:i}function ko(i){let t=i.toLowerCase(),e=new Set;for(;;){let r=vo.find(n=>t.startsWith(`${n}+`));if(!r)break;if(e.has(r))return null;e.add(r),t=t.slice(r.length+1);}return !t||t.includes("+")&&t!=="+"?null:{key:t,ctrl:e.has("ctrl"),shift:e.has("shift"),alt:e.has("alt"),super:e.has("super")}}function ae(i,t){let e=ko(t);if(!e)return false;let{key:r,ctrl:n,shift:s,alt:o,super:l}=e,a=0;switch(s&&(a|=k.shift),o&&(a|=k.alt),n&&(a|=k.ctrl),l&&(a|=k.super),r){case "escape":case "esc":return a!==0?false:i==="\x1B"||R(i,K.escape,0)||ee(i,K.escape,0);case "space":return !q&&(a===k.ctrl&&i==="\0"||a===k.alt&&i==="\x1B ")?true:a===0?i===" "||R(i,K.space,0)||ee(i,K.space,0):R(i,K.space,a)||ee(i,K.space,a);case "tab":return a===k.shift?i==="\x1B[Z"||R(i,K.tab,k.shift)||ee(i,K.tab,k.shift):a===0?i===" "||R(i,K.tab,0):R(i,K.tab,a)||ee(i,K.tab,a);case "enter":case "return":return a===k.shift?R(i,K.enter,k.shift)||R(i,K.kpEnter,k.shift)||ee(i,K.enter,k.shift)?true:q?i==="\x1B\r"||i===`
2
+ `:false:a===k.alt?R(i,K.enter,k.alt)||R(i,K.kpEnter,k.alt)||ee(i,K.enter,k.alt)?true:q?false:i==="\x1B\r":a===0?i==="\r"||!q&&i===`
3
+ `||i==="\x1BOM"||R(i,K.enter,0)||R(i,K.kpEnter,0):R(i,K.enter,a)||R(i,K.kpEnter,a)||ee(i,K.enter,a);case "backspace":return a===k.alt?i==="\x1B\x7F"||i==="\x1B\b"?true:R(i,K.backspace,k.alt)||ee(i,K.backspace,k.alt):a===k.ctrl?sn(i,k.ctrl)?true:R(i,K.backspace,k.ctrl)||ee(i,K.backspace,k.ctrl):a===0?sn(i,0)||R(i,K.backspace,0)||ee(i,K.backspace,0):R(i,K.backspace,a)||ee(i,K.backspace,a);case "insert":return a===0?j(i,Z.insert)||R(i,_.insert,0):Q(i,"insert",a)?true:R(i,_.insert,a);case "delete":return a===0?j(i,Z.delete)||R(i,_.delete,0):Q(i,"delete",a)?true:R(i,_.delete,a);case "clear":return a===0?j(i,Z.clear):Q(i,"clear",a);case "home":return a===0?j(i,Z.home)||R(i,_.home,0):Q(i,"home",a)?true:R(i,_.home,a);case "end":return a===0?j(i,Z.end)||R(i,_.end,0):Q(i,"end",a)?true:R(i,_.end,a);case "pageup":return a===0?j(i,Z.pageUp)||R(i,_.pageUp,0):Q(i,"pageUp",a)?true:R(i,_.pageUp,a);case "pagedown":return a===0?j(i,Z.pageDown)||R(i,_.pageDown,0):Q(i,"pageDown",a)?true:R(i,_.pageDown,a);case "up":return a===k.alt?i==="\x1Bp"||R(i,H.up,k.alt):a===0?j(i,Z.up)||R(i,H.up,0):Q(i,"up",a)?true:R(i,H.up,a);case "down":return a===k.alt?i==="\x1Bn"||R(i,H.down,k.alt):a===0?j(i,Z.down)||R(i,H.down,0):Q(i,"down",a)?true:R(i,H.down,a);case "left":return a===k.alt?i==="\x1B[1;3D"||!q&&i==="\x1BB"||i==="\x1Bb"||R(i,H.left,k.alt):a===k.ctrl?i==="\x1B[1;5D"||Q(i,"left",k.ctrl)||R(i,H.left,k.ctrl):a===0?j(i,Z.left)||R(i,H.left,0):Q(i,"left",a)?true:R(i,H.left,a);case "right":return a===k.alt?i==="\x1B[1;3C"||!q&&i==="\x1BF"||i==="\x1Bf"||R(i,H.right,k.alt):a===k.ctrl?i==="\x1B[1;5C"||Q(i,"right",k.ctrl)||R(i,H.right,k.ctrl):a===0?j(i,Z.right)||R(i,H.right,0):Q(i,"right",a)?true:R(i,H.right,a);case "f1":case "f2":case "f3":case "f4":case "f5":case "f6":case "f7":case "f8":case "f9":case "f10":case "f11":case "f12":return a!==0?false:j(i,Z[r])}if(r.length===1&&(r>="a"&&r<="z"||on(r)||be.has(r))){let c=r.charCodeAt(0),h=Io(r),u=r>="a"&&r<="z",p=on(r);return a===k.ctrl+k.alt&&!q&&h&&i===`\x1B${h}`||a===k.alt&&!q&&(u||p||be.has(r))&&i===`\x1B${r}`?true:a===k.ctrl?h&&i===h?true:R(i,c,k.ctrl)||it(i,c,k.ctrl):a===k.shift+k.ctrl?R(i,c,k.shift+k.ctrl)||it(i,c,k.shift+k.ctrl):a===k.shift?u&&i===r.toUpperCase()?true:R(i,c,k.shift)||it(i,c,k.shift):a!==0?R(i,c,a)||it(i,c,a):i===r||R(i,c,0)||it(i,c,0)}return false}function an(i,t,e){let r=Fe(i),n=nt(r,t),s=n>=97&&n<=122,o=n>=48&&n<=57,l=be.has(String.fromCharCode(n)),a=s||o||l?n:e??n,c;if(a===K.escape?c="escape":a===K.tab?c="tab":a===K.enter||a===K.kpEnter?c="enter":a===K.space?c="space":a===K.backspace?c="backspace":a===_.delete?c="delete":a===_.insert?c="insert":a===_.home?c="home":a===_.end?c="end":a===_.pageUp?c="pageUp":a===_.pageDown?c="pageDown":a===H.up?c="up":a===H.down?c="down":a===H.left?c="left":a===H.right?c="right":(a>=48&&a<=57||a>=97&&a<=122||be.has(String.fromCharCode(a)))&&(c=String.fromCharCode(a)),!!c)return Lo(c,t)}function Ao(i){let t=cn(i);if(t){let n=Kt(t.shiftedKey,t.modifier,be);return an(n?.codepoint??t.codepoint,n?.modifier??t.modifier,t.baseLayoutKey)}let e=Bt(i);if(e){let n=Kt(e.codepoint,e.modifier,ln);return an(n?.codepoint??e.codepoint,n?.modifier??e.modifier)}if(q&&(i==="\x1B\r"||i===`
4
+ `))return "shift+enter";let r=To[i];if(r)return r;if(i==="\x1B")return "escape";if(i==="")return "ctrl+\\";if(i==="")return "ctrl+]";if(i==="")return "ctrl+-";if(i==="\x1B\x1B")return "ctrl+alt+[";if(i==="\x1B")return "ctrl+alt+\\";if(i==="\x1B")return "ctrl+alt+]";if(i==="\x1B")return "ctrl+alt+-";if(i===" ")return "tab";if(i==="\r"||!q&&i===`
5
+ `||i==="\x1BOM")return "enter";if(i==="\0")return "ctrl+space";if(i===" ")return "space";if(i==="\x7F")return "backspace";if(i==="\b")return un()?"ctrl+backspace":"backspace";if(i==="\x1B[Z")return "shift+tab";if(!q&&i==="\x1B\r")return "alt+enter";if(!q&&i==="\x1B ")return "alt+space";if(i==="\x1B\x7F"||i==="\x1B\b")return "alt+backspace";if(!q&&i==="\x1BB")return "alt+left";if(!q&&i==="\x1BF")return "alt+right";if(!q&&i.length===2&&i[0]==="\x1B"){let n=i.charCodeAt(1);if(n>=1&&n<=26)return `ctrl+alt+${String.fromCharCode(n+96)}`;let s=String.fromCharCode(n);if(n>=97&&n<=122||n>=48&&n<=57||be.has(s))return `alt+${s}`}if(i==="\x1B[A")return "up";if(i==="\x1B[B")return "down";if(i==="\x1B[C")return "right";if(i==="\x1B[D")return "left";if(i==="\x1B[H"||i==="\x1BOH"||i==="\x1B[1~"||i==="\x1B[7~")return "home";if(i==="\x1B[F"||i==="\x1BOF"||i==="\x1B[4~"||i==="\x1B[8~")return "end";if(i==="\x1B[3~")return "delete";if(i==="\x1B[5~")return "pageUp";if(i==="\x1B[6~")return "pageDown";if(i.length===1){let n=i.charCodeAt(0);if(n>=1&&n<=26)return `ctrl+${String.fromCharCode(n+96)}`;if(n>=32&&n<=126)return i}}var Ro=/^\x1b\[(\d+)(?::(\d*))?(?::(\d+))?(?:;(\d+))?(?::(\d+))?u$/;function _t(i){let t=i.match(Ro);if(!t)return;let e=Number.parseInt(t[1]??"",10);if(!Number.isFinite(e))return;let r=t[2]&&t[2].length>0?Number.parseInt(t[2],10):void 0,n=t[4]?Number.parseInt(t[4],10):1,s=Number.isFinite(n)?n-1:0;if((s&-194)!==0||s&(k.alt|k.ctrl))return;let o=e;if(s&k.shift&&typeof r=="number"&&(o=r),o=Fe(o),!(!Number.isFinite(o)||o<32))try{return String.fromCodePoint(o)}catch{return}}function Po(i){let t=Bt(i);if(!(!t||(t.modifier&-193&-2)!==0)&&!(!Number.isFinite(t.codepoint)||t.codepoint<32))try{return String.fromCodePoint(t.codepoint)}catch{return}}function Or(i){return _t(i)??Po(i)}function Oo(i){let t=i.startsWith("#")?i.slice(1):i,e=parseInt(t.slice(0,2),16),r=parseInt(t.slice(2,4),16),n=parseInt(t.slice(4,6),16);return {r:e,g:r,b:n}}function ce(i){if(!/^[0-9a-f]+$/i.test(i))return;let t=16**i.length-1;if(!(t<=0))return Math.round(parseInt(i,16)/t*255)}var $o=/^\x1b\](?:(1[01])|4;(\d{1,3}));([^\x07\x1b]*)(?:\x07|\x1b\\)$/i,Ko=/^(?:\x1b\[\?997;(1|2)n)+$/;function hn(i){let t=i.match($o);return t?{target:t[1]==="10"?"foreground":t[1]==="11"?"background":Number.parseInt(t[2],10),rgb:Bo(t[3])}:void 0}function Bo(i){let t=i.trim();if(t.startsWith("#")){let c=t.slice(1);if(/^[0-9a-f]{6}$/i.test(c))return Oo(t);if(/^[0-9a-f]{3}$/i.test(c)){let h=ce(c.slice(0,1)),u=ce(c.slice(1,2)),p=ce(c.slice(2,3));return h!==void 0&&u!==void 0&&p!==void 0?{r:h,g:u,b:p}:void 0}if(/^[0-9a-f]{12}$/i.test(c)){let h=ce(c.slice(0,4)),u=ce(c.slice(4,8)),p=ce(c.slice(8,12));return h!==void 0&&u!==void 0&&p!==void 0?{r:h,g:u,b:p}:void 0}return}let e=t.replace(/^rgba?:/i,""),[r,n,s]=e.split("/");if(r===void 0||n===void 0||s===void 0)return;let o=ce(r),l=ce(n),a=ce(s);return o!==void 0&&l!==void 0&&a!==void 0?{r:o,g:l,b:a}:void 0}function $r(i){let t=i.match(Ko);if(t)return t[1]==="2"?"light":"dark"}var Ue=null,Ve={},gn={widthPx:9,heightPx:18};function Dt(){return gn}function Kr(i){gn=i;}function Wo(){try{return execSync("tmux display-message -p '#{client_termfeatures}'",{encoding:"utf8",timeout:250,stdio:["ignore","pipe","ignore"]}).split(",").map(t=>t.trim()).includes("hyperlinks")}catch{return false}}function Vo(i){let t=process.env.TERM_PROGRAM?.toLowerCase()||"",e=process.env.TERMINAL_EMULATOR?.toLowerCase()||"",r=process.env.TERM?.toLowerCase()||"",n=process.env.COLORTERM?.toLowerCase()||"",s=n==="truecolor"||n==="24bit"||r.endsWith("-direct"),o=process.platform==="win32";return process.env.TMUX||r.startsWith("tmux")?{images:null,trueColor:s,hyperlinks:i()}:r.startsWith("screen")?{images:null,trueColor:s,hyperlinks:false}:t==="herdr"?{images:"kitty",trueColor:s,hyperlinks:true}:process.env.KITTY_WINDOW_ID||t==="kitty"?{images:"kitty",trueColor:true,hyperlinks:true}:t==="ghostty"||r.includes("ghostty")||process.env.GHOSTTY_RESOURCES_DIR?{images:"kitty",trueColor:true,hyperlinks:true}:process.env.WEZTERM_PANE||t==="wezterm"?{images:"kitty",trueColor:true,hyperlinks:true}:t==="warpterminal"||process.env.WARP_SESSION_ID||process.env.WARP_TERMINAL_SESSION_UUID?{images:"kitty",trueColor:true,hyperlinks:true}:process.env.ITERM_SESSION_ID||t==="iterm.app"?{images:"iterm2",trueColor:true,hyperlinks:true}:process.env.WT_SESSION?{images:null,trueColor:true,hyperlinks:true}:t==="alacritty"||t==="vscode"||t==="zed"?{images:null,trueColor:true,hyperlinks:true}:e==="jetbrains-jediterm"?{images:null,trueColor:true,hyperlinks:false}:o?{images:null,trueColor:true,hyperlinks:false}:{images:null,trueColor:s,hyperlinks:false}}function dn(i){return i==="1"?true:i==="0"?false:void 0}function bn(i=Wo){let t=dn(process.env.PI_HYPERLINKS),e=Vo(t===void 0?i:()=>t),r=process.env.PI_IMAGE_PROTOCOL?.toLowerCase(),n=r==="kitty"||r==="iterm2"?r:r==="none"||r==="0"?null:void 0,s=dn(process.env.PI_TRUE_COLOR);return {...e,...n!==void 0?{images:n}:{},...s!==void 0?{trueColor:s}:{},...t!==void 0?{hyperlinks:t}:{}}}function te(){if(!Ue){let i=Ve.hyperlinks;Ue={...bn(i===void 0?void 0:()=>i),...Ve};}return Ue}function Ho(i=te()){return i.trueColor?"truecolor":"256color"}function Uo(){Ue=null;}function qo(i){Ve.images===i.images&&Ve.trueColor===i.trueColor&&Ve.hyperlinks===i.hyperlinks||(Ve={...i},Ue=null);}function Nt(i){Ue=i;}var He="\x1B_G",pn="\x1B]1337;File=";function F(i){return i.startsWith(He)||i.startsWith(pn)?true:i.includes(He)||i.includes(pn)}function Br(){return Math.floor(Math.random()*4294967294)+1}function yn(i,t={}){let r=["a=T","f=100","q=2"];if(t.moveCursor===false&&r.push("C=1"),t.columns&&r.push(`c=${t.columns}`),t.rows&&r.push(`r=${t.rows}`),t.imageId&&r.push(`i=${t.imageId}`),i.length<=4096)return `\x1B_G${r.join(",")};${i}\x1B\\`;let n=[],s=0,o=true;for(;s<i.length;){let l=i.slice(s,s+4096),a=s+4096>=i.length;o?(n.push(`\x1B_G${r.join(",")},m=1;${l}\x1B\\`),o=false):a?n.push(`\x1B_Gm=0;${l}\x1B\\`):n.push(`\x1B_Gm=1;${l}\x1B\\`),s+=4096;}return n.join("")}function at(i){return `\x1B_Ga=d,d=I,i=${i},q=2\x1B\\`}function _r(){return "\x1B_Ga=d,d=A,q=2\x1B\\"}function Dr(){return "\x1B_Ga=d,d=a,q=2\x1B\\"}function xn(i,t={}){let e=[`inline=${t.inline!==false?1:0}`,`size=${Buffer.byteLength(i,"base64")}`];if(t.width!==void 0&&e.push(`width=${t.width}`),t.height!==void 0&&e.push(`height=${t.height}`),t.name){let r=Buffer.from(t.name).toString("base64");e.push(`name=${r}`);}return t.preserveAspectRatio===false&&e.push("preserveAspectRatio=0"),`\x1B]1337;File=${e.join(";")}:${i}\x07`}var We=new Map,fn=0;function Go(i){if(fn+=1,We.delete(i.imageId),We.set(i.imageId,{...i,transmissionGeneration:fn}),We.size>1e3){let t=We.keys().next().value;t!==void 0&&We.delete(t);}}function Nr(i){let t=/(?:^|,)i=(\d+)(?:,|$)/.exec(i)?.[1];return t===void 0?void 0:We.get(Number.parseInt(t,10))}function zo(i){let t=/\x1b_G([^;]*);/.exec(i)?.[1];return t===void 0?void 0:Nr(t)}function vn(i){let t=/(?:^|,)r=(\d+)(?:,|$)/.exec(i)?.[1];if(t===void 0)return;let e=Number.parseInt(t,10);return e>0?e:void 0}function Yo(i,t){return vn(i)??t}function Ft(i){let t=zo(i);if(t)return {imageId:t.imageId,columns:t.columns,rows:t.rows,widthPx:t.widthPx,heightPx:t.heightPx}}var jo=new Set(["i","p","x","y","w","h","X","Y","c","r","C","U","z","P","Q","H","V"]);function Sn(i){let t=/\x1b_G([^;]*);/.exec(i)?.[1];if(t===void 0)return;let e=vn(t);return e!==void 0?e:Nr(t)?.rows}function Cn(i){let t=/\x1b_G([^;]*);/.exec(i),e=t?.[1];if(!t||e===void 0)return;let r=Nr(e);if(!r)return;let n=t.index,s=e,o;for(;;){let c=i.indexOf("\x1B\\",n+He.length);if(c===-1)return;if(o=c+2,!/(?:^|,)m=1(?:,|$)/.test(s))break;if(n=o,!i.startsWith(He,n))return;let h=i.indexOf(";",n+He.length);if(h===-1)return;s=i.slice(n+He.length,h);}let a=`\x1B_Ga=p,q=2,${e.split(",").filter(c=>jo.has(c.split("=",1)[0]??"")).join(",")}\x1B\\`;return {imageId:r.imageId,transmissionGeneration:r.transmissionGeneration,transmissionBytes:o-t.index,estimatedDecodedBytes:r.widthPx*r.heightPx*4,rows:Yo(e,r.rows),sequence:a,replacementLine:`${i.slice(0,t.index)}${a}${i.slice(o)}`}}function Fr(i,t,e){let r=Ft(i),n=/\x1b_G([^;]*);/.exec(i),s=n?.[1];if(!r||!n||s===void 0||t<0||t>=r.rows||e<=0)return i;let o=Math.min(e,r.rows-t);if(t===0&&o===r.rows)return i;let l=Math.floor(r.heightPx*t/r.rows),a=Math.ceil(r.heightPx*(t+o)/r.rows),c=Math.max(1,Math.min(r.heightPx,a)-l),h=s.split(",").filter(u=>!/^[yhr]=/.test(u));return h.push(`y=${l}`,`h=${c}`,`r=${o}`),`${i.slice(0,n.index)}\x1B_G${h.join(",")};${i.slice(n.index+n[0].length)}`}function mn(i,t){if(i<=1)return i;let e=i-1,r=Math.max(i/t,t/i);return Math.max(e/t,t/e)<r?e:i}function wn(i,t,e,r={widthPx:9,heightPx:18},n=false){let s=Math.max(1,Math.floor(t)),o=e===void 0?void 0:Math.max(1,Math.floor(e)),l=Math.max(1,i.widthPx),a=Math.max(1,i.heightPx),c=s*r.widthPx/l,h=o===void 0?c:o*r.heightPx/a,u=Math.min(c,h),p=l*u,f=a*u,b=Math.max(1,Math.min(s,Math.ceil(p/r.widthPx))),m=f/r.heightPx,g=Math.max(1,Math.ceil(m));if(o!==void 0&&(g=Math.min(o,g)),!n)return {columns:b,rows:g};if(c<=h){let y=b*r.widthPx*a/(l*r.heightPx);g=mn(g,y);}else {let y=g*r.heightPx*l/(a*r.widthPx);b=mn(b,y);}return {columns:b,rows:g}}function Xo(i,t,e={widthPx:9,heightPx:18}){return wn(i,t,void 0,e).rows}function Wt(i){try{let t=Buffer.from(i,"base64");if(t.length<24||t[0]!==137||t[1]!==80||t[2]!==78||t[3]!==71)return null;let e=t.readUInt32BE(16),r=t.readUInt32BE(20);return {widthPx:e,heightPx:r}}catch{return null}}function Tn(i){try{let t=Buffer.from(i,"base64");if(t.length<2||t[0]!==255||t[1]!==216)return null;let e=2;for(;e<t.length-9;){if(t[e]!==255){e++;continue}let r=t[e+1]??0;if(r>=192&&r<=194){let s=t.readUInt16BE(e+5);return {widthPx:t.readUInt16BE(e+7),heightPx:s}}if(e+3>=t.length)return null;let n=t.readUInt16BE(e+2);if(n<2)return null;e+=2+n;}return null}catch{return null}}function Mn(i){try{let t=Buffer.from(i,"base64");if(t.length<10)return null;let e=t.slice(0,6).toString("ascii");if(e!=="GIF87a"&&e!=="GIF89a")return null;let r=t.readUInt16LE(6),n=t.readUInt16LE(8);return {widthPx:r,heightPx:n}}catch{return null}}function In(i){try{let t=Buffer.from(i,"base64");if(t.length<30)return null;let e=t.slice(0,4).toString("ascii"),r=t.slice(8,12).toString("ascii");if(e!=="RIFF"||r!=="WEBP")return null;let n=t.slice(12,16).toString("ascii");if(n==="VP8 "){if(t.length<30)return null;let s=t.readUInt16LE(26)&16383,o=t.readUInt16LE(28)&16383;return {widthPx:s,heightPx:o}}else if(n==="VP8L"){if(t.length<25)return null;let s=t.readUInt32LE(21),o=(s&16383)+1,l=(s>>14&16383)+1;return {widthPx:o,heightPx:l}}else if(n==="VP8X"){if(t.length<30)return null;let s=((t[24]??0)|(t[25]??0)<<8|(t[26]??0)<<16)+1,o=((t[27]??0)|(t[28]??0)<<8|(t[29]??0)<<16)+1;return {widthPx:s,heightPx:o}}return null}catch{return null}}function Wr(i,t){return t==="image/png"?Wt(i):t==="image/jpeg"?Tn(i):t==="image/gif"?Mn(i):t==="image/webp"?In(i):null}function Vr(i,t,e={}){let r=te();if(!r.images)return null;let n=e.maxWidthCells??80,s=wn(t,n,e.maxHeightCells,Dt(),r.images==="kitty");return r.images==="kitty"?(e.imageId!==void 0&&Go({imageId:e.imageId,columns:s.columns,rows:s.rows,widthPx:t.widthPx,heightPx:t.heightPx}),{sequence:yn(i,{columns:s.columns,rows:s.rows,imageId:e.imageId,moveCursor:e.moveCursor}),columns:s.columns,rows:s.rows,imageId:e.imageId}):r.images==="iterm2"?{sequence:xn(i,{width:s.columns,height:"auto",preserveAspectRatio:e.preserveAspectRatio??true}),columns:s.columns,rows:s.rows}:null}function Vt(i,t){return `\x1B]8;;${t}\x1B\\${i}\x1B]8;;\x1B\\`}function Qo(i){let t=homedir();return t&&(i===t||i.startsWith(`${t}/`)||i.startsWith(`${t}\\`))?`~${i.slice(t.length)}`:i}function Ht(i,t,e){let r=[];if(e){let n=Qo(e);te().hyperlinks&&isAbsolute(e)?r.push(Vt(n,pathToFileURL(e).href)):r.push(n);}return r.push(`[${i}]`),t&&r.push(`${t.widthPx}x${t.heightPx}`),`[Image: ${r.join(" ")}]`}function ue(i,t){let e=i.handleMouse?.(t);if(e){if("target"in e){let r=e;return r.focus&&i.handleInput?{...r,focusTarget:i}:r}if(!(!e.handled&&!e.capture&&!e.focus))return {...e,handled:true,...e.focus?{focusTarget:i}:{},target:{component:i,originX:t.screenX-t.x,originY:t.screenY-t.y,width:t.width,height:t.height}}}}function kn(i,t){return {...i,x:i.screenX-t.originX,y:i.screenY-t.originY,width:t.width,height:t.height}}var qt=16,Jo=2+qt,Zo=`\x1B]10;?\x07\x1B]11;?\x07${Array.from({length:qt},(i,t)=>`\x1B]4;${t};?\x07`).join("")}\x1B[c`,ea=/^\x1b\[\?[\d;]*c$/;function Hr(i){return i!==null&&"focused"in i}var re="\x1B_pi:c\x07",Ur="\x1B_pi:fc\x07",An="\x1B_pi:/fc\x07",ta=/(\x1b_pi:c\x07)\x1b_pi:fc\x07(.*?)(?:\x1b_pi:\/fc\x07|$)/s;function Se(i){return `${Ur}${i}${An}`}function Ln(i,t){if(i===void 0)return;if(typeof i=="number")return i;let e=i.match(/^(\d+(?:\.\d+)?)%$/);if(e)return Math.floor(t*parseFloat(e[1])/100)}var se=class{constructor(){d(this,"children",[]);d(this,"mouseLayout");}addChild(t){this.children.push(t);}removeChild(t){let e=this.children.indexOf(t);e!==-1&&this.children.splice(e,1);}clear(){this.children=[];}invalidate(){for(let t of this.children)t.invalidate?.();}handleMouse(t){if(t.y<0||t.y>=t.height)return;let e=this.mouseLayout?.width===t.width?this.mouseLayout.children:this.children.map(n=>({component:n,height:n.render(t.width).length})),r=0;for(let{component:n,height:s}of e){if(t.y>=r&&t.y<r+s){let o=ue(n,{...t,y:t.y-r,height:s});return o?.focus&&this.handleInput?{...o,focusTarget:this}:o}r+=s;}}render(t){let e=[],r=[];for(let n of this.children){let s=n.render(t);r.push({component:n,height:s.length});for(let o of s)e.push(o);}return this.mouseLayout={width:t,children:r},e}},qr="\x1B[0m\x1B]8;;\x07";function he(i,t,e,r,n){if(F(i))return i;let s=e+r,o=Ai(i,e,s,n-s,true),l=vr(t,0,r,true),a=Math.max(0,e-o.beforeWidth),c=Math.max(0,r-l.width),h=Math.max(e,o.beforeWidth),u=Math.max(r,l.width),p=Math.max(0,n-h-u),f=Math.max(0,p-o.afterWidth),b=o.before+" ".repeat(a)+qr+l.text+" ".repeat(c)+qr+o.after+" ".repeat(f);return S(b)<=n?b:V(b,0,n,true)}var Gr=Symbol.for("@earendil-works/pi-tui/viewport");function ra(i){return i[Gr]===true}var Gt=class Gt extends se{constructor(e,r,n){super();d(this,"terminal");d(this,"focusedComponent",null);d(this,"inputListeners",new Set);d(this,"onDebug");d(this,"renderRequested",false);d(this,"immediateRenderScheduled",false);d(this,"renderTimer");d(this,"lastRenderAt",0);d(this,"showHardwareCursor",false);d(this,"clearOnShrink",false);d(this,"fullRedrawCount",0);d(this,"stopped",false);d(this,"pendingTerminalColorQueries",[]);d(this,"terminalColorSchemeListeners",new Set);d(this,"terminalColorSchemeNotificationsEnabled",false);d(this,"logDirectory");d(this,"focusOrderCounter",0);d(this,"overlayStack",[]);d(this,"renderedOverlayLayouts",[]);d(this,"overlayFocusRestore",{status:"inactive"});this.terminal=e,this.logDirectory=n,r!==void 0&&(this.showHardwareCursor=r);}get hasOverlayEntries(){return this.overlayStack.length>0}resetRenderState(){}beforeTerminalStart(){}afterTerminalStart(){}beforeTerminalStop(e){}afterTerminalStop(e){}get fullRedraws(){return this.fullRedrawCount}getShowHardwareCursor(){return this.showHardwareCursor}setShowHardwareCursor(e){this.showHardwareCursor!==e&&(this.showHardwareCursor=e,e||this.hideTerminalCursor(),this.requestRender());}getClearOnShrink(){return this.clearOnShrink}setClearOnShrink(e){this.clearOnShrink=e;}getFocusedComponent(){return this.focusedComponent}setFocus(e){this.setFocusInternal({component:e,overlayFocusRestore:"clear"});}setFocusInternal({component:e,overlayFocusRestore:r}){let n=this.focusedComponent,s=e,o=n?this.overlayStack.find(h=>h.component===n&&this.isOverlayVisible(h)):void 0,l=s?this.overlayStack.some(h=>h.component===s):false,a=this.getVisibleOverlayFocusRestore();s&&!l?a.status==="blocked"&&a.blockedBy===n?a.resume.status==="focus-target"||!this.isComponentMounted(a.blockedBy)?s=this.resolveBlockedOverlayFocusResume(a):this.overlayFocusRestore={status:"blocked",overlay:a.overlay,blockedBy:s,resume:a.resume}:o&&a.status!=="inactive"&&a.overlay===o&&!this.isOverlayFocusAncestor(o,s)&&(this.overlayFocusRestore={status:"blocked",overlay:o,blockedBy:s,resume:{status:"restore-overlay"}}):s===null&&(a.status==="blocked"&&a.blockedBy===n?s=this.resolveBlockedOverlayFocusResume(a):r==="clear"&&this.clearOverlayFocusRestore()),Hr(this.focusedComponent)&&(this.focusedComponent.focused=false),this.focusedComponent=s,Hr(s)&&(s.focused=true);let c=s?this.overlayStack.find(h=>h.component===s&&this.isOverlayVisible(h)):void 0;c&&(this.overlayFocusRestore={status:"eligible",overlay:c});}clearOverlayFocusRestore(){this.overlayFocusRestore={status:"inactive"};}clearOverlayFocusRestoreFor(e){this.overlayFocusRestore.status!=="inactive"&&this.overlayFocusRestore.overlay===e&&this.clearOverlayFocusRestore();}resolveBlockedOverlayFocusResume(e){return e.resume.status==="restore-overlay"?e.overlay.component:(this.clearOverlayFocusRestore(),e.resume.target)}getVisibleOverlayFocusRestore(){let e=this.overlayFocusRestore;return e.status==="inactive"?e:!this.overlayStack.includes(e.overlay)||!this.isOverlayVisible(e.overlay)?{status:"inactive"}:e}isOverlayFocusAncestor(e,r){let n=new Set,s=e.preFocus;for(;s&&!n.has(s);){if(n.add(s),s===r)return true;s=this.overlayStack.find(o=>o.component===s)?.preFocus??null;}return false}retargetOverlayPreFocus(e){for(let r of this.overlayStack)r!==e&&r.preFocus===e.component&&(r.preFocus=e.preFocus);}getMountedRoots(){return this.children}isComponentMounted(e){return this.getMountedRoots().some(r=>this.containsComponent(r,e))}containsComponent(e,r){return e===r?true:e instanceof se?e.children.some(n=>this.containsComponent(n,r)):false}showOverlay(e,r){let n={component:e,...r===void 0?{}:{options:r},preFocus:this.focusedComponent,hidden:false,focusOrder:++this.focusOrderCounter};return this.overlayStack.push(n),!r?.nonCapturing&&this.isOverlayVisible(n)&&this.setFocus(e),this.hideTerminalCursor(),this.requestRender(),{hide:()=>{let s=this.overlayStack.indexOf(n);if(s!==-1){if(this.clearOverlayFocusRestoreFor(n),this.retargetOverlayPreFocus(n),this.overlayStack.splice(s,1),this.focusedComponent===e){let o=this.getTopmostVisibleOverlay();this.setFocus(o?.component??n.preFocus);}this.overlayStack.length===0&&this.hideTerminalCursor(),this.requestRender();}},setHidden:s=>{if(n.hidden!==s){if(n.hidden=s,s){if(this.clearOverlayFocusRestoreFor(n),this.focusedComponent===e){let o=this.getTopmostVisibleOverlay();this.setFocus(o?.component??n.preFocus);}}else !r?.nonCapturing&&this.isOverlayVisible(n)&&(n.focusOrder=++this.focusOrderCounter,this.setFocus(e));this.requestRender();}},isHidden:()=>n.hidden,focus:()=>{!this.overlayStack.includes(n)||!this.isOverlayVisible(n)||(n.focusOrder=++this.focusOrderCounter,this.setFocus(e),this.requestRender());},unfocus:s=>{let o=this.focusedComponent===e,l=this.overlayFocusRestore,a=l.status!=="inactive"&&l.overlay===n;if(!(!o&&!a)){if(l.status==="blocked"&&l.overlay===n&&this.focusedComponent===l.blockedBy){s?this.overlayFocusRestore={status:"blocked",overlay:n,blockedBy:l.blockedBy,resume:{status:"focus-target",target:s.target}}:this.clearOverlayFocusRestore(),this.requestRender();return}if(this.clearOverlayFocusRestoreFor(n),o||s){let c=this.getTopmostVisibleOverlay(),h=c&&c!==n?c.component:n.preFocus;this.setFocus(s?s.target:h);}this.requestRender();}},isFocused:()=>this.focusedComponent===e,getBounds:()=>{if(!(!this.overlayStack.includes(n)||!this.isOverlayVisible(n)||!n.bounds))return {...n.bounds}}}}hideOverlay(){let e=this.overlayStack[this.overlayStack.length-1];if(e){if(this.clearOverlayFocusRestoreFor(e),this.retargetOverlayPreFocus(e),this.overlayStack.pop(),this.focusedComponent===e.component){let r=this.getTopmostVisibleOverlay();this.setFocus(r?.component??e.preFocus);}this.overlayStack.length===0&&this.hideTerminalCursor(),this.requestRender();}}hideTerminalCursor(){this.stopped||this.terminal.hideCursor();}hasOverlay(){return this.overlayStack.some(e=>this.isOverlayVisible(e))}isOverlayFocused(){return this.overlayStack.some(e=>e.component===this.focusedComponent&&this.isOverlayVisible(e))}resolveMouseFocusTarget(e){for(let r=this.overlayStack.length-1;r>=0;r--){let n=this.overlayStack[r];if(this.isOverlayVisible(n)&&this.containsComponent(n.component,e))return n.component}return e}dispatchMouseToOverlay(e){for(let r=this.renderedOverlayLayouts.length-1;r>=0;r--){let n=this.renderedOverlayLayouts[r];if(e.screenX<n.col||e.screenX>=n.col+n.width||e.screenY<n.row||e.screenY>=n.row+n.height)continue;let s=ue(n.entry.component,{...e,x:e.screenX-n.col,y:e.screenY-n.row,width:n.width,height:n.height});return s?{hit:true,result:s.focus?{...s,focusTarget:n.entry.component}:s}:{hit:true}}return {hit:false}}isOverlayVisible(e){return e.hidden?false:e.options?.visible?e.options.visible(this.terminal.columns,this.terminal.rows):true}getTopmostVisibleOverlay(){let e;for(let r of this.overlayStack)r.options?.nonCapturing||!this.isOverlayVisible(r)||(!e||r.focusOrder>e.focusOrder)&&(e=r);return e}invalidate(){for(let e of this.getMountedRoots())e.invalidate();for(let e of this.overlayStack)e.component.invalidate();}start(){this.stopped=false,this.beforeTerminalStart(),this.terminal.start(e=>this.handleTerminalInput(e),()=>this.requestRender()),this.afterTerminalStart(),this.terminal.hideCursor(),this.terminalColorSchemeNotificationsEnabled&&this.terminal.write("\x1B[?2031h"),this.queryCellSize(),this.requestRender();}addInputListener(e){return this.inputListeners.add(e),()=>{this.inputListeners.delete(e);}}removeInputListener(e){this.inputListeners.delete(e);}onTerminalColorSchemeChange(e){return this.terminalColorSchemeListeners.add(e),()=>{this.terminalColorSchemeListeners.delete(e);}}setTerminalColorSchemeNotifications(e){this.terminalColorSchemeNotificationsEnabled!==e&&(this.terminalColorSchemeNotificationsEnabled=e,this.stopped||this.terminal.write(e?"\x1B[?2031h":"\x1B[?2031l"));}queryCellSize(){te().images&&this.terminal.write("\x1B[16t");}stop(e={}){this.stopped=true,this.cancelRenderTimer(),this.terminalColorSchemeNotificationsEnabled&&this.terminal.write("\x1B[?2031l"),this.beforeTerminalStop(e),this.afterTerminalStop(e),this.terminal.showCursor(),this.terminal.stop();}renderNow(e=false){e&&this.resetRenderState(),this.renderRequested=false,this.cancelRenderTimer(),this.lastRenderAt=performance$1.now(),this.doRender();}requestRender(e=false){if(e){this.resetRenderState(),this.requestImmediateRender();return}this.renderRequested||(this.renderRequested=true,process.nextTick(()=>this.scheduleRender()));}requestImmediateRender(){this.cancelRenderTimer(),this.renderRequested=true,!this.immediateRenderScheduled&&(this.immediateRenderScheduled=true,process.nextTick(()=>{this.immediateRenderScheduled=false,!(this.stopped||!this.renderRequested)&&(this.cancelRenderTimer(),this.renderRequested=false,this.lastRenderAt=performance$1.now(),this.doRender());}));}cancelRenderTimer(){this.renderTimer&&(clearTimeout(this.renderTimer),this.renderTimer=void 0);}scheduleRender(){if(this.stopped||this.renderTimer||!this.renderRequested)return;let e=performance$1.now()-this.lastRenderAt,r=Math.max(0,Gt.MIN_RENDER_INTERVAL_MS-e);this.renderTimer=setTimeout(()=>{this.renderTimer=void 0,!(this.stopped||!this.renderRequested)&&(this.renderRequested=false,this.lastRenderAt=performance$1.now(),this.doRender(),this.renderRequested&&this.scheduleRender());},r);}handleTerminalInput(e){if(this.consumeTerminalColorResponse(e)||this.consumeTerminalColorSchemeReport(e))return;if(this.inputListeners.size>0){let s=e;for(let o of this.inputListeners){let l=o(s);if(l?.consume)return;l?.data!==void 0&&(s=l.data);}if(s.length===0)return;e=s;}if(this.consumeCellSizeResponse(e))return;if(ae(e,"shift+ctrl+d")&&this.onDebug){this.onDebug();return}let r=this.overlayStack.find(s=>s.component===this.focusedComponent);if(r&&!this.isOverlayVisible(r)){let s=this.getTopmostVisibleOverlay();s?this.setFocus(s.component):this.setFocusInternal({component:r.preFocus,overlayFocusRestore:"preserve"});}if(!this.overlayStack.some(s=>s.component===this.focusedComponent)){let s=this.getVisibleOverlayFocusRestore();s.status==="eligible"?this.setFocus(s.overlay.component):s.status==="blocked"&&s.blockedBy!==this.focusedComponent&&(s.resume.status==="restore-overlay"?this.setFocus(s.overlay.component):(this.clearOverlayFocusRestore(),this.setFocus(s.resume.target)));}if(this.focusedComponent?.handleInput){if(ot(e)&&!this.focusedComponent.wantsKeyRelease)return;this.focusedComponent.handleInput(e),this.requestImmediateRender();}}consumeTerminalColorResponse(e){let r=this.pendingTerminalColorQueries[0];if(!r)return false;if(ea.test(e))return this.pendingTerminalColorQueries.shift(),this.completeTerminalColorQuery(r),true;let n=hn(e);if(!n)return false;let{target:s,rgb:o}=n,l=String(s);return !r.deliver||r.replied.has(l)||(r.replied.add(l),s==="foreground"?r.foreground=o:s==="background"?r.background=o:s<qt&&(r.palette[s]=o),r.replied.size===Jo&&this.completeTerminalColorQuery(r)),true}terminalColorQueryResult(e){let r=e.palette.every(n=>n!==void 0)?e.palette:void 0;return {foreground:e.foreground,background:e.background,palette:r}}completeTerminalColorQuery(e){let r=e.deliver;e.deliver=void 0,clearTimeout(e.timer),r?.(this.terminalColorQueryResult(e));}consumeTerminalColorSchemeReport(e){let r=$r(e);if(!r)return false;for(let n of this.terminalColorSchemeListeners)n(r);return true}consumeCellSizeResponse(e){let r=e.match(/^\x1b\[6;(\d+);(\d+)t$/);if(!r)return false;let n=parseInt(r[1],10),s=parseInt(r[2],10);return n<=0||s<=0||(Kr({widthPx:s,heightPx:n}),this.invalidate(),this.requestRender()),true}resolveOverlayLayout(e,r,n,s){let o=e??{},l=typeof o.margin=="number"?{top:o.margin,right:o.margin,bottom:o.margin,left:o.margin}:o.margin??{},a=Math.max(0,l.top??0),c=Math.max(0,l.right??0),h=Math.max(0,l.bottom??0),u=Math.max(0,l.left??0),p=Math.max(1,n-u-c),f=Math.max(1,s-a-h),b=Ln(o.width,n)??Math.min(80,p);o.minWidth!==void 0&&(b=Math.max(b,o.minWidth)),b=Math.max(1,Math.min(b,p));let m=Ln(o.maxHeight,s);m!==void 0&&(m=Math.max(1,Math.min(m,f)));let g=m!==void 0?Math.min(r,m):r,y,v;if(o.row!==void 0)if(typeof o.row=="string"){let x=o.row.match(/^(\d+(?:\.\d+)?)%$/);if(x){let w=Math.max(0,f-g),I=parseFloat(x[1])/100;y=a+Math.floor(w*I);}else y=this.resolveAnchorRow("center",g,f,a);}else y=o.row;else {let x=o.anchor??"center";y=this.resolveAnchorRow(x,g,f,a);}if(o.col!==void 0)if(typeof o.col=="string"){let x=o.col.match(/^(\d+(?:\.\d+)?)%$/);if(x){let w=Math.max(0,p-b),I=parseFloat(x[1])/100;v=u+Math.floor(w*I);}else v=this.resolveAnchorCol("center",b,p,u);}else v=o.col;else {let x=o.anchor??"center";v=this.resolveAnchorCol(x,b,p,u);}return o.offsetY!==void 0&&(y+=o.offsetY),o.offsetX!==void 0&&(v+=o.offsetX),y=Math.max(a,Math.min(y,s-h-g)),v=Math.max(u,Math.min(v,n-c-b)),{width:b,row:y,col:v,maxHeight:m}}resolveAnchorRow(e,r,n,s){switch(e){case "top-left":case "top-center":case "top-right":return s;case "bottom-left":case "bottom-center":case "bottom-right":return s+n-r;case "left-center":case "center":case "right-center":return s+Math.floor((n-r)/2)}}resolveAnchorCol(e,r,n,s){switch(e){case "top-left":case "left-center":case "bottom-left":return s;case "top-right":case "right-center":case "bottom-right":return s+n-r;case "top-center":case "center":case "bottom-center":return s+Math.floor((n-r)/2)}}compositeOverlays(e,r,n){if(this.overlayStack.length===0)return this.renderedOverlayLayouts=[],e;let s=[...e];for(let u of this.overlayStack)u.bounds=void 0;let o=[],l=s.length,a=this.overlayStack.filter(u=>this.isOverlayVisible(u));a.sort((u,p)=>u.focusOrder-p.focusOrder);for(let u of a){let{component:p,options:f}=u,{width:b,maxHeight:m}=this.resolveOverlayLayout(f,0,r,n),g=this.resolveFakeCursors(p.render(b));m!==void 0&&g.length>m&&(g=g.slice(0,m));let{row:y,col:v}=this.resolveOverlayLayout(f,g.length,r,n);u.bounds={row:y,col:v,width:b,height:g.length},o.push({entry:u,overlayLines:g,row:y,col:v,w:b}),l=Math.max(l,y+g.length);}this.renderedOverlayLayouts=o.map(({entry:u,row:p,col:f,w:b,overlayLines:m})=>({entry:u,row:p,col:f,width:b,height:m.length}));let c=Math.max(s.length,n,l);for(;s.length<c;)s.push("");let h=Math.max(0,c-n);for(let{overlayLines:u,row:p,col:f,w:b}of o)for(let m=0;m<u.length;m++){let g=h+p+m;if(g>=0&&g<s.length){let y=u[m]??"",v=S(y)>b?V(y,0,b,true):y;s[g]=this.compositeLineAt(s[g]??"",v,f,b,r);}}return s}applyLineResets(e){let r=qr;for(let n=0;n<e.length;n++){let s=e[n]??"";F(s)||(e[n]=Ti(s)+r);}return e}compositeLineAt(e,r,n,s,o){return he(e,r,n,s,o)}extractCursorPosition(e,r){let n=Math.max(0,e.length-r);for(let s=e.length-1;s>=n;s--){let o=e[s]??"",l=o.indexOf(re);if(l!==-1){let a=o.slice(0,l),c=S(a);return e[s]=o.slice(0,l)+o.slice(l+re.length),{row:s,col:c}}}return null}resolveFakeCursors(e){return e.map(r=>r.includes(Ur)?(this.showHardwareCursor?r.replace(ta,"$1$2"):r).replaceAll(Ur,"\x1B[7m").replaceAll(An,"\x1B[27m"):r)}queryTerminalColors({timeoutMs:e,onLateReply:r}){return new Promise(n=>{let s={palette:Array.from({length:qt},()=>{}),replied:new Set,deliver:n,timer:void 0};s.timer=setTimeout(()=>{s.deliver=r,n(this.terminalColorQueryResult(s));},e),this.pendingTerminalColorQueries.push(s),this.terminal.write(Zo);})}};d(Gt,"MIN_RENDER_INTERVAL_MS",16);var qe=Gt;var zr=class{constructor(t=1,e=1,r){d(this,"children",[]);d(this,"paddingX");d(this,"paddingY");d(this,"bgFn");d(this,"cache");d(this,"mouseLayout");this.paddingX=t,this.paddingY=e,this.bgFn=r;}addChild(t){this.children.push(t),this.invalidateCache();}removeChild(t){let e=this.children.indexOf(t);e!==-1&&(this.children.splice(e,1),this.invalidateCache());}clear(){this.children=[],this.invalidateCache();}setBgFn(t){this.bgFn=t;}setPaddingX(t){this.paddingX=t,this.invalidateCache();}invalidateCache(){this.cache=void 0;}matchCache(t,e,r){let n=this.cache;return !!n&&n.width===t&&n.bgSample===r&&n.childLines.length===e.length&&n.childLines.every((s,o)=>s===e[o])}invalidate(){this.invalidateCache();for(let t of this.children)t.invalidate?.();}handleMouse(t){let e=Math.max(1,t.width-this.paddingX*2),r=t.y-this.paddingY,n=t.x-this.paddingX;if(r<0||n<0||n>=e)return;let s=this.mouseLayout?.width===e?this.mouseLayout.children:this.children.map(l=>({component:l,height:l.render(e).length})),o=0;for(let{component:l,height:a}of s){if(r>=o&&r<o+a)return ue(l,{...t,x:n,y:r-o,width:e,height:a});o+=a;}}render(t){if(this.children.length===0)return [];let e=Math.max(1,t-this.paddingX*2),r=" ".repeat(this.paddingX),n=[],s=[];for(let a of this.children){let c=a.render(e);s.push({component:a,height:c.length});for(let h of c)n.push(h);}if(this.mouseLayout={width:e,children:s},n.length===0)return [];let o=this.bgFn?this.bgFn("test"):void 0;if(this.matchCache(t,n,o))return this.cache.lines;let l=[];for(let a=0;a<this.paddingY;a++)l.push(this.applyBg("",t));for(let a of n)l.push(this.applyBg(r+a,t));for(let a=0;a<this.paddingY;a++)l.push(this.applyBg("",t));return _e(l),this.cache={childLines:n,width:t,bgSample:o,lines:l},l}applyBg(t,e){let r=S(t),n=Math.max(0,e-r),s=t+" ".repeat(n);return this.bgFn?this.bgFn(s):s}};var Rn={"tui.editor.cursorUp":{defaultKeys:"up",description:"Move cursor up"},"tui.editor.cursorDown":{defaultKeys:"down",description:"Move cursor down"},"tui.editor.historyPrevious":{defaultKeys:[],description:"Select previous prompt history entry"},"tui.editor.historyNext":{defaultKeys:[],description:"Select next prompt history entry"},"tui.editor.cursorLeft":{defaultKeys:["left","ctrl+b"],description:"Move cursor left"},"tui.editor.cursorRight":{defaultKeys:["right","ctrl+f"],description:"Move cursor right"},"tui.editor.cursorWordLeft":{defaultKeys:["alt+left","ctrl+left","alt+b"],description:"Move cursor word left"},"tui.editor.cursorWordRight":{defaultKeys:["alt+right","ctrl+right","alt+f"],description:"Move cursor word right"},"tui.editor.cursorLineStart":{defaultKeys:["home","ctrl+a"],description:"Move to line start"},"tui.editor.cursorLineEnd":{defaultKeys:["end","ctrl+e"],description:"Move to line end"},"tui.editor.jumpForward":{defaultKeys:"ctrl+]",description:"Jump forward to character"},"tui.editor.jumpBackward":{defaultKeys:"ctrl+alt+]",description:"Jump backward to character"},"tui.editor.pageUp":{defaultKeys:["pageUp","ctrl+pageUp"],description:"Page up"},"tui.editor.pageDown":{defaultKeys:["pageDown","ctrl+pageDown"],description:"Page down"},"tui.editor.deleteCharBackward":{defaultKeys:"backspace",description:"Delete character backward"},"tui.editor.deleteCharForward":{defaultKeys:["delete","ctrl+d"],description:"Delete character forward"},"tui.editor.deleteWordBackward":{defaultKeys:["ctrl+w","alt+backspace"],description:"Delete word backward"},"tui.editor.deleteWordForward":{defaultKeys:["alt+d","alt+delete"],description:"Delete word forward"},"tui.editor.deleteToLineStart":{defaultKeys:"ctrl+u",description:"Delete to line start"},"tui.editor.deleteToLineEnd":{defaultKeys:"ctrl+k",description:"Delete to line end"},"tui.editor.yank":{defaultKeys:"ctrl+y",description:"Yank"},"tui.editor.yankPop":{defaultKeys:"alt+y",description:"Yank pop"},"tui.editor.undo":{defaultKeys:"ctrl+-",description:"Undo"},"tui.input.newLine":{defaultKeys:["shift+enter","ctrl+j"],description:"Insert newline"},"tui.input.submit":{defaultKeys:"enter",description:"Submit input"},"tui.input.tab":{defaultKeys:"tab",description:"Tab / autocomplete"},"tui.input.copy":{defaultKeys:"ctrl+c",description:"Copy selection"},"tui.select.up":{defaultKeys:"up",description:"Move selection up"},"tui.select.down":{defaultKeys:"down",description:"Move selection down"},"tui.select.pageUp":{defaultKeys:"pageUp",description:"Selection page up"},"tui.select.pageDown":{defaultKeys:"pageDown",description:"Selection page down"},"tui.select.confirm":{defaultKeys:"enter",description:"Confirm selection"},"tui.select.cancel":{defaultKeys:["escape","ctrl+c"],description:"Cancel selection"},"tui.altScreen.pageUp":{defaultKeys:"pageUp",description:"Scroll viewport up one page"},"tui.altScreen.pageDown":{defaultKeys:"pageDown",description:"Scroll viewport down one page"},"tui.altScreen.halfPageUp":{defaultKeys:[],description:"Scroll viewport up half a page"},"tui.altScreen.halfPageDown":{defaultKeys:[],description:"Scroll viewport down half a page"},"tui.altScreen.lineUp":{defaultKeys:[],description:"Scroll viewport up one line"},"tui.altScreen.lineDown":{defaultKeys:[],description:"Scroll viewport down one line"},"tui.altScreen.previousPrompt":{defaultKeys:["ctrl+shift+up","ctrl+up"],description:"Jump to previous semantic prompt"},"tui.altScreen.nextPrompt":{defaultKeys:["ctrl+shift+down","ctrl+down"],description:"Jump to next semantic prompt"},"tui.altScreen.search":{defaultKeys:"ctrl+shift+f",description:"Search the primary scroll view"},"tui.altScreen.searchNext":{defaultKeys:["enter","ctrl+g"],description:"Select the next search match"},"tui.altScreen.searchPrevious":{defaultKeys:["shift+enter","ctrl+shift+g"],description:"Select the previous search match"},"tui.altScreen.searchClose":{defaultKeys:"escape",description:"Close transcript search"},"tui.altScreen.top":{defaultKeys:"ctrl+home",description:"Scroll viewport to top"},"tui.altScreen.bottom":{defaultKeys:"ctrl+end",description:"Scroll viewport to bottom"}};function Yr(i){if(i===void 0)return [];let t=Array.isArray(i)?i:[i],e=new Set,r=[];for(let n of t)e.has(n)||(e.add(n),r.push(n));return r}var Yt=class{constructor(t,e={}){d(this,"definitions");d(this,"userBindings");d(this,"keysById",new Map);d(this,"conflicts",[]);this.definitions=t,this.userBindings=e,this.rebuild();}rebuild(){this.keysById.clear(),this.conflicts=[];let t=new Map;for(let[e,r]of Object.entries(this.userBindings))if(e in this.definitions)for(let n of Yr(r)){let s=t.get(n)??new Set;s.add(e),t.set(n,s);}for(let[e,r]of t)r.size>1&&this.conflicts.push({key:e,keybindings:[...r]});for(let[e,r]of Object.entries(this.definitions)){let n=this.userBindings[e],s=Yr(n===void 0?r.defaultKeys:n);this.keysById.set(e,s);}}matches(t,e){let r=this.keysById.get(e)??[];for(let n of r)if(ae(t,n))return true;return false}getKeys(t){return [...this.keysById.get(t)??[]]}getDefinition(t){let e=this.definitions[t];if(!e)throw new Error(`Unknown keybinding: ${t}`);return e}getConflicts(){return this.conflicts.map(t=>({...t,keybindings:[...t.keybindings]}))}setUserBindings(t){this.userBindings=t,this.rebuild();}getUserBindings(){return {...this.userBindings}}getResolvedBindings(){let t={};for(let e of Object.keys(this.definitions)){let r=this.keysById.get(e)??[];t[e]=r.length===1?r[0]:[...r];}return t}},zt=null;function ia(i){zt=i;}function G(){return zt||(zt=new Yt(Rn)),zt}var lt=class{constructor(t="",e=1,r=1,n){d(this,"text");d(this,"paddingX");d(this,"paddingY");d(this,"customBgFn");d(this,"cachedText");d(this,"cachedWidth");d(this,"cachedLines");this.text=t,this.paddingX=e,this.paddingY=r,this.customBgFn=n;}setText(t){this.text=t,this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0;}setCustomBgFn(t){this.customBgFn=t,this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0;}setPaddingX(t){this.paddingX=t,this.invalidate();}invalidate(){this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0;}render(t){if(this.cachedLines&&this.cachedText===this.text&&this.cachedWidth===t)return this.cachedLines;if(!this.text||this.text.trim()===""){let p=[];return this.cachedText=this.text,this.cachedWidth=t,this.cachedLines=p,p}let e=this.text.replace(/\t/g," "),r=Math.min(this.paddingX,Math.max(0,Math.floor((t-1)/2))),n=Math.max(1,t-r*2),s=ne(e,n),o=" ".repeat(r),l=" ".repeat(r),a=[];for(let p of s){let f=o+p+l;if(this.customBgFn)a.push(De(f,t,this.customBgFn));else {let b=S(f),m=Math.max(0,t-b);a.push(f+" ".repeat(m));}}let c=" ".repeat(t),h=[];for(let p=0;p<this.paddingY;p++){let f=this.customBgFn?De(c,t,this.customBgFn):c;h.push(f);}let u=[...h,...a,...h];return _e(u),this.cachedText=this.text,this.cachedWidth=t,this.cachedLines=u,u.length>0?u:[""]}};var En=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Pn=80,ct=class extends lt{constructor(e,r,n,s="Loading...",o){super("",1,0);d(this,"frames",[...En]);d(this,"intervalMs",Pn);d(this,"currentFrame",0);d(this,"intervalId",null);d(this,"ui",null);d(this,"renderIndicatorVerbatim",false);d(this,"spinnerColorFn");d(this,"messageColorFn");d(this,"message","Loading...");this.ui=e,this.spinnerColorFn=r,this.messageColorFn=n,this.message=s,this.setIndicator(o);}render(e){return ["",...super.render(e)]}start(){this.updateDisplay(),this.restartAnimation();}stop(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null);}setMessage(e){this.message=e,this.updateDisplay();}invalidate(){super.invalidate(),this.updateDisplay();}setIndicator(e){this.renderIndicatorVerbatim=e!==void 0,this.frames=e?.frames!==void 0?[...e.frames]:[...En],this.intervalMs=e?.intervalMs&&e.intervalMs>0?e.intervalMs:Pn,this.currentFrame=0,this.start();}restartAnimation(){this.stop(),!(this.frames.length<=1)&&(this.intervalId=setInterval(()=>{this.currentFrame=(this.currentFrame+1)%this.frames.length,this.updateDisplay();},this.intervalMs));}getRenderedIndicator(){let e=this.frames[this.currentFrame]??"";return this.renderIndicatorVerbatim?e:this.spinnerColorFn(e)}updateDisplay(){let e=this.getRenderedIndicator(),r=e.length>0?`${e} `:"";this.setText(`${r}${this.messageColorFn(this.message)}`),this.ui&&this.ui.requestRender();}};var jr=class extends ct{constructor(){super(...arguments);d(this,"abortController",new AbortController);d(this,"onAbort");}get signal(){return this.abortController.signal}get aborted(){return this.abortController.signal.aborted}handleInput(e){G().matches(e,"tui.select.cancel")&&(this.abortController.abort(),this.onAbort?.());}dispose(){this.stop();}};var Ge=class{constructor(){d(this,"ring",[]);}push(t,e){if(t)if(e.accumulate&&this.ring.length>0){let r=this.ring.pop();this.ring.push(e.prepend?t+r:r+t);}else this.ring.push(t);}peek(){return this.ring.length>0?this.ring[this.ring.length-1]:void 0}rotate(){if(this.ring.length>1){let t=this.ring.pop();this.ring.unshift(t);}}get length(){return this.ring.length}};var ze=class{constructor(){d(this,"stack",[]);}push(t){this.stack.push(structuredClone(t));}pop(){return this.stack.pop()}clear(){this.stack.length=0;}get length(){return this.stack.length}};var On=Oe();function jt(i,t,e){if(t<=0)return 0;let r=i.slice(0,t),n=e?.segment,s=e?.isAtomicSegment,o=n?[...n(r)]:[...On.segment(r)],l=t;for(;o.length>0&&!s?.(o[o.length-1]?.segment||"")&&X(o[o.length-1]?.segment||"");)l-=o.pop()?.segment.length||0;if(o.length===0)return l;let a=o[o.length-1];if(s?.(a.segment))l-=a.segment.length;else if(a.isWordLike){let c=a.segment,h=[...c.matchAll(new RegExp(xr,"g"))];if(h.length<=0)l-=c.length;else {let u=h[h.length-1];l-=c.length-(u.index+u[0].length);}}else for(;o.length>0&&!s?.(o[o.length-1]?.segment||"")&&!o[o.length-1]?.isWordLike&&!X(o[o.length-1]?.segment||"");)l-=o.pop()?.segment.length||0;return l}function Xt(i,t,e){if(t>=i.length)return i.length;let r=i.slice(t),n=e?.segment,s=e?.isAtomicSegment,l=(n?n(r):On.segment(r))[Symbol.iterator](),a=l.next(),c=t;for(;!a.done&&!s?.(a.value.segment)&&X(a.value.segment);)c+=a.value.segment.length,a=l.next();if(a.done)return c;if(s?.(a.value.segment))c+=a.value.segment.length;else if(a.value.isWordLike)c+=xr.exec(a.value.segment)?.index??a.value.segment.length;else for(;!a.done&&!s?.(a.value.segment)&&!a.value.isWordLike&&!X(a.value.segment);)c+=a.value.segment.length,a=l.next();return c}var $n=32,Kn=2,na=10,sa=i=>i.replace(/[\r\n]+/g," ").trim(),oa=(i,t,e)=>Math.max(t,Math.min(i,e)),ut=class{constructor(t,e,r,n={}){d(this,"items",[]);d(this,"filteredItems",[]);d(this,"selectedIndex",0);d(this,"mousePressedIndex");d(this,"maxVisible",5);d(this,"theme");d(this,"layout");d(this,"onSelect");d(this,"onCancel");d(this,"onSelectionChange");this.items=t,this.filteredItems=t,this.maxVisible=e,this.theme=r,this.layout=n;}setFilter(t){this.filteredItems=this.items.filter(e=>e.value.toLowerCase().startsWith(t.toLowerCase())),this.selectedIndex=0;}setSelectedIndex(t){this.selectedIndex=Math.max(0,Math.min(t,this.filteredItems.length-1));}invalidate(){}render(t){let e=[];if(this.filteredItems.length===0)return e.push(this.theme.noMatch(" No matching commands")),e;let r=this.getPrimaryColumnWidth(),{startIndex:n,endIndex:s}=this.getVisibleRange(this.selectedIndex);for(let o=n;o<s;o+=1){let l=this.filteredItems[o];if(!l)continue;let a=o===this.selectedIndex,c=l.description?sa(l.description):void 0;e.push(this.renderItem(l,a,t,c,r));}if(n>0||s<this.filteredItems.length){let o=` (${this.selectedIndex+1}/${this.filteredItems.length})`;e.push(this.theme.scrollInfo(N(o,t-2,"")));}return e}handleMouse(t){if(this.filteredItems.length===0)return;if(t.type==="wheel"&&t.wheelDelta){let s=t.wheelDelta<0?-1:1,o=this.selectedIndex;return this.selectedIndex=Math.max(0,Math.min(this.filteredItems.length-1,this.selectedIndex+s)),this.selectedIndex!==o&&this.notifySelectionChange(),{handled:true,render:this.selectedIndex!==o}}if(t.button!=="left"||t.type!=="press"&&t.type!=="click")return;let{startIndex:e,endIndex:r}=this.getVisibleRange(this.selectedIndex),n=e+t.y;if(!(n<e||n>=r)&&this.filteredItems[n]){if(t.type==="press")return this.mousePressedIndex=n,this.selectedIndex!==n&&(this.selectedIndex=n,this.notifySelectionChange()),{handled:true,focus:true};if(t.type==="click"){let s=this.mousePressedIndex??n;this.mousePressedIndex=void 0;let o=this.selectedIndex!==s;this.selectedIndex=s,o&&this.notifySelectionChange();let l=this.filteredItems[this.selectedIndex];return l&&this.onSelect?.(l),{handled:true}}}}handleInput(t){let e=G();if(e.matches(t,"tui.select.up"))this.selectedIndex=this.selectedIndex===0?this.filteredItems.length-1:this.selectedIndex-1,this.notifySelectionChange();else if(e.matches(t,"tui.select.down"))this.selectedIndex=this.selectedIndex===this.filteredItems.length-1?0:this.selectedIndex+1,this.notifySelectionChange();else if(e.matches(t,"tui.select.confirm")){let r=this.filteredItems[this.selectedIndex];r&&this.onSelect&&this.onSelect(r);}else e.matches(t,"tui.select.cancel")&&this.onCancel&&this.onCancel();}getVisibleRange(t){let e=this.filteredItems.length,r=Math.max(0,Math.min(t,e-1)),n=Math.max(0,Math.min(r-Math.floor(this.maxVisible/2),e-this.maxVisible));return {startIndex:n,endIndex:Math.min(n+this.maxVisible,e)}}renderItem(t,e,r,n,s){let o=e?"\u2192 ":" ",l=S(o);if(n&&r>40){let h=Math.max(1,Math.min(s,r-l-4)),u=Math.max(1,h-Kn),p=this.truncatePrimary(t,e,u,h),f=S(p),b=" ".repeat(Math.max(1,h-f)),m=l+f+b.length,g=r-m-2;if(g>na){let y=N(n,g,"");if(e)return this.theme.selectedText(`${o}${p}${b}${y}`);let v=this.theme.description(b+y);return o+p+v}}let a=r-l-2,c=this.truncatePrimary(t,e,a,a);return e?this.theme.selectedText(`${o}${c}`):o+c}getPrimaryColumnWidth(){let{min:t,max:e}=this.getPrimaryColumnBounds(),r=this.filteredItems.reduce((n,s)=>Math.max(n,S(this.getDisplayValue(s))+Kn),0);return oa(r,t,e)}getPrimaryColumnBounds(){let t=this.layout.minPrimaryColumnWidth??this.layout.maxPrimaryColumnWidth??$n,e=this.layout.maxPrimaryColumnWidth??this.layout.minPrimaryColumnWidth??$n;return {min:Math.max(1,Math.min(t,e)),max:Math.max(1,Math.max(t,e))}}truncatePrimary(t,e,r,n){let s=this.getDisplayValue(t),o=this.layout.truncatePrimary?this.layout.truncatePrimary({text:s,maxWidth:r,columnWidth:n,item:t,isSelected:e}):N(s,r,"");return N(o,r,"")}getDisplayValue(t){return t.label||t.value}notifySelectionChange(){let t=this.filteredItems[this.selectedIndex];t&&this.onSelectionChange&&this.onSelectionChange(t);}getSelectedItem(){return this.filteredItems[this.selectedIndex]||null}};var Wn=Pe(),aa=Oe(),Vn=/\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]/g,Hn=/^\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]$/;function Ye(i){return i.length>=10&&Hn.test(i)}function la(i,t,e){if(e.size===0||!i.includes("[paste #"))return t.segment(i);let r=[];for(let l of i.matchAll(Vn)){let a=Number.parseInt(l[1],10);e.has(a)&&r.push({start:l.index,end:l.index+l[0].length});}if(r.length===0)return t.segment(i);let n=t.segment(i),s=[],o=0;for(let l of n){for(;o<r.length&&r[o].end<=l.index;)o++;let a=o<r.length?r[o]:null;if(a&&l.index>=a.start&&l.index<a.end){if(l.index===a.start){let c=i.slice(a.start,a.end);s.push({segment:c,index:a.start,input:i});}}else s.push(l);}return s}function Xr(i,t,e){if(!i||t<=0)return [{text:"",startIndex:0,endIndex:0}];if(S(i)<=t)return [{text:i,startIndex:0,endIndex:i.length}];let n=[],s=e??[...Wn.segment(i)],o=0,l=0,a=-1,c=0;for(let h=0;h<s.length;h++){let u=s[h],p=u.segment,f=S(p),b=u.index,m=!Ye(p)&&X(p);if(o+f>t&&(a>=0&&o-c+f<=t?(n.push({text:i.slice(l,a),startIndex:l,endIndex:a}),l=a,o-=c):l<b&&(n.push({text:i.slice(l,b),startIndex:l,endIndex:b}),l=b,o=0),a=-1),f>t){let y=Xr(p,t);for(let x=0;x<y.length-1;x++){let w=y[x];n.push({text:w.text,startIndex:b+w.startIndex,endIndex:b+w.endIndex});}let v=y[y.length-1];l=b+v.startIndex,o=S(v.text),a=-1;continue}o+=f;let g=s[h+1];if(m&&g&&(Ye(g.segment)||!X(g.segment)))a=g.index,c=o;else if(!m&&g&&!X(g.segment)){let y=!Ye(p)&&$e.test(p),v=!Ye(g.segment)&&$e.test(g.segment);(y||v)&&(a=g.index,c=o);}}return n.push({text:i.slice(l),startIndex:l,endIndex:i.length}),n}var ca={minPrimaryColumnWidth:12,maxPrimaryColumnWidth:32},ua=20,Bn=[J],Qr=new RegExp(`(?:(?!${Ke.source}).)*`,"u"),Un=`${Ct.source}[([{<\`]*`;function Qt(i){return i.replace(/[\\^$.*+?()[\]{}|-]/g,"\\$&")}function _n(i){return i.label.endsWith("/")}function Dn(i){let t=Qt(J);return new RegExp(`${Un}(?:${t}"[^"]*|[${i.map(Qt).join("")}]${Qr.source})$`,"u")}function Nn(i){let t=Qt(J),e=i.filter(r=>r!==J).map(Qt);return new RegExp(`${Un}(?:${t}(?:"[^"]*|${Qr.source})|[${e.join("")}]${Qr.source})$`,"u")}function Fn(i,t,e){let r=Math.max(0,e),n=` ${i} ${t} more `,s=S(n);if(s+2<=r){let h=Math.floor((r-s)/2);return "\u2500".repeat(h)+n+"\u2500".repeat(r-h-s)}let o=`\u2500\u2500\u2500 ${i} ${t} more `,l=r-S(o);if(l>=0)return o+"\u2500".repeat(l);let a="...".slice(0,r),c=r-S(a);return V(o,0,c,true)+a}var Jr=class{constructor(t,e,r={}){d(this,"state",{lines:[""],cursorLine:0,cursorCol:0});d(this,"focused",false);d(this,"tui");d(this,"theme");d(this,"paddingX",0);d(this,"lastWidth",80);d(this,"renderedVisibleLineCount",1);d(this,"renderedAutocompleteHeight",0);d(this,"scrollOffset",0);d(this,"borderColor");d(this,"autocompleteProvider");d(this,"autocompleteTriggerCharacters",[...Bn]);d(this,"autocompleteTriggerPattern",Dn(this.autocompleteTriggerCharacters));d(this,"autocompleteDebouncePattern",Nn(this.autocompleteTriggerCharacters));d(this,"autocompleteList");d(this,"autocompleteState",null);d(this,"autocompletePrefix","");d(this,"autocompleteMaxVisible",5);d(this,"autocompleteAbort");d(this,"autocompleteDebounceTimer");d(this,"autocompleteRequestTask",Promise.resolve());d(this,"autocompleteStartToken",0);d(this,"autocompleteRequestId",0);d(this,"pastes",new Map);d(this,"pasteCounter",0);d(this,"pasteBuffer","");d(this,"isInPaste",false);d(this,"history",[]);d(this,"historyIndex",-1);d(this,"historyDraft",null);d(this,"killRing",new Ge);d(this,"lastAction",null);d(this,"jumpMode",null);d(this,"preferredVisualCol",null);d(this,"snappedFromCursorCol",null);d(this,"undoStack",new ze);d(this,"onSubmit");d(this,"onChange");d(this,"disableSubmit",false);d(this,"shouldAutoSubmitSlashCommand");this.tui=t,this.theme=e,this.borderColor=e.borderColor;let n=r.paddingX??0;this.paddingX=Number.isFinite(n)?Math.max(0,Math.floor(n)):0;let s=r.autocompleteMaxVisible??5;this.autocompleteMaxVisible=Number.isFinite(s)?Math.max(3,Math.min(20,Math.floor(s))):5;}validPasteIds(){return new Set(this.pastes.keys())}segment(t,e){return la(t,e==="word"?aa:Wn,this.validPasteIds())}getPaddingX(){return this.paddingX}setPaddingX(t){let e=Number.isFinite(t)?Math.max(0,Math.floor(t)):0;this.paddingX!==e&&(this.paddingX=e,this.tui.requestRender());}getAutocompleteMaxVisible(){return this.autocompleteMaxVisible}setAutocompleteMaxVisible(t){let e=Number.isFinite(t)?Math.max(3,Math.min(20,Math.floor(t))):5;this.autocompleteMaxVisible!==e&&(this.autocompleteMaxVisible=e,this.tui.requestRender());}setAutocompleteProvider(t){this.cancelAutocomplete(),this.autocompleteProvider=t,this.setAutocompleteTriggerCharacters(t.triggerCharacters??[]);}addToHistory(t){let e=t.trim();e&&(this.history.length>0&&this.history[0]===e||(this.history.unshift(e),this.history.length>100&&this.history.pop()));}isEditorEmpty(){return this.state.lines.length===1&&this.state.lines[0]===""}isOnFirstVisualLine(){let t=this.buildVisualLineMap(this.lastWidth);return this.findCurrentVisualLine(t)===0}isOnLastVisualLine(){let t=this.buildVisualLineMap(this.lastWidth);return this.findCurrentVisualLine(t)===t.length-1}navigateHistory(t){if(this.lastAction=null,this.history.length===0)return;let e=this.historyIndex-t;if(!(e<-1||e>=this.history.length))if(this.historyIndex===-1&&e>=0&&(this.pushUndoSnapshot(),this.historyDraft=structuredClone(this.state)),this.historyIndex=e,this.historyIndex===-1){let r=this.historyDraft;this.historyDraft=null,r?(this.state=r,this.preferredVisualCol=null,this.snappedFromCursorCol=null,this.scrollOffset=0,this.onChange&&this.onChange(this.getText())):this.setTextInternal("");}else this.setTextInternal(this.history[this.historyIndex]||"",t===-1?"start":"end");}exitHistoryBrowsing(){this.historyIndex=-1,this.historyDraft=null;}setTextInternal(t,e="end"){let r=t.split(`
6
+ `);this.state.lines=r.length===0?[""]:r,this.state.cursorLine=e==="start"?0:this.state.lines.length-1,this.setCursorCol(e==="start"?0:this.state.lines[this.state.cursorLine]?.length||0),this.scrollOffset=0,this.onChange&&this.onChange(this.getText());}invalidate(){}renderTopBorder(t,e){let r=e>0?Fn("\u2191",e,t):"\u2500".repeat(t);return this.borderColor(r)}renderBottomBorder(t,e){let r=e>0?Fn("\u2193",e,t):"\u2500".repeat(t);return this.borderColor(r)}render(t){let e=Math.max(0,Math.floor((t-1)/2)),r=Math.min(this.paddingX,e),n=Math.max(1,t-r*2),s=Math.max(1,n-(r?0:1));this.lastWidth=s;let o=this.layoutText(s),l=this.tui.terminal.rows,a=Math.max(5,Math.floor(l*.3)),c=o.findIndex(y=>y.hasCursor);c===-1&&(c=0),c<this.scrollOffset?this.scrollOffset=c:c>=this.scrollOffset+a&&(this.scrollOffset=c-a+1);let h=Math.max(0,o.length-a);this.scrollOffset=Math.max(0,Math.min(this.scrollOffset,h));let u=o.slice(this.scrollOffset,this.scrollOffset+a);this.renderedVisibleLineCount=u.length;let p=[],f=" ".repeat(r),b=f;p.push(this.renderTopBorder(t,this.scrollOffset));let m=this.focused;for(let y of u){let v=y.text,x=S(y.text),w=false;if(y.hasCursor&&y.cursorPos!==void 0){let L=v.slice(0,y.cursorPos),M=v.slice(y.cursorPos),E=m?re:"";if(M.length>0){let C=[...this.segment(M,"grapheme")][0]?.segment||"",A=M.slice(C.length),D=Se(C);v=L+E+D+A;}else {let P=Se(" ");v=L+E+P,x=x+1,x>n&&r>0&&(w=true);}}let I=" ".repeat(Math.max(0,n-x)),T=w?b.slice(1):b;p.push(`${f}${v}${I}${T}`);}let g=o.length-(this.scrollOffset+u.length);if(p.push(this.renderBottomBorder(t,g)),this.renderedAutocompleteHeight=0,this.autocompleteState&&this.autocompleteList){let y=this.autocompleteList.render(n);this.renderedAutocompleteHeight=y.length;for(let v of y){let x=S(v),w=" ".repeat(Math.max(0,n-x));p.push(`${f}${v}${w}${b}`);}}return p}handleMouse(t){let e=this.renderedVisibleLineCount+2;if(this.autocompleteState&&this.autocompleteList&&t.y>=e&&t.y<e+this.renderedAutocompleteHeight){let g=Math.max(0,Math.floor((t.width-1)/2)),y=Math.min(this.paddingX,g),v=Math.max(1,t.width-y*2),x=this.autocompleteList.handleMouse?.({...t,x:t.x-y,y:t.y-e,width:v,height:this.renderedAutocompleteHeight});return x?{...x,focus:true}:void 0}if(t.type!=="click"||t.button!=="left")return;if(t.y<=0||t.y>this.renderedVisibleLineCount)return {handled:true,focus:true};let r=this.buildVisualLineMap(this.lastWidth),n=this.scrollOffset+t.y-1,s=r[n];if(!s)return {handled:true,focus:true};let o=this.state.lines[s.logicalLine]??"",l=s.startCol+s.length,a=o.slice(s.startCol,l),c=Math.max(0,Math.floor((t.width-1)/2)),h=Math.min(this.paddingX,c),u=Math.max(0,t.x-h),p=0,f=a.length,b=0;for(let g of this.segment(a,"grapheme")){let y=p+S(g.segment);if(b=g.index,u<y){f=g.index;break}p=y;}return !(n===r.length-1||r[n+1]?.logicalLine!==s.logicalLine)&&f===a.length&&a.length>0&&(f=b),this.state.cursorLine=s.logicalLine,this.setCursorCol(s.startCol+f),this.lastAction=null,this.exitHistoryBrowsing(),this.autocompleteState&&this.updateAutocomplete(),{handled:true,focus:true}}handleInput(t){let e=G();if(this.jumpMode!==null){if(e.matches(t,"tui.editor.jumpForward")||e.matches(t,"tui.editor.jumpBackward")){this.jumpMode=null;return}let n=Or(t)??(t.charCodeAt(0)>=32?t:void 0);if(n!==void 0){let s=this.jumpMode;this.jumpMode=null,this.jumpToChar(n,s);return}this.jumpMode=null;}if(t.includes("\x1B[200~")&&(this.isInPaste=true,this.pasteBuffer="",t=t.replace("\x1B[200~","")),this.isInPaste){this.pasteBuffer+=t;let n=this.pasteBuffer.indexOf("\x1B[201~");if(n!==-1){let s=this.pasteBuffer.substring(0,n);s.length>0&&this.handlePaste(s),this.isInPaste=false;let o=this.pasteBuffer.substring(n+6);this.pasteBuffer="",o.length>0&&this.handleInput(o);return}return}if(e.matches(t,"tui.input.copy"))return;if(e.matches(t,"tui.editor.undo")){this.undo();return}if(this.autocompleteState&&this.autocompleteList){if(e.matches(t,"tui.select.cancel")){this.cancelAutocomplete();return}if(e.matches(t,"tui.select.up")||e.matches(t,"tui.select.down")){this.autocompleteList.handleInput(t);return}if(e.matches(t,"tui.input.tab")){let n=this.autocompleteList.getSelectedItem();if(n&&this.autocompleteProvider){this.pushUndoSnapshot(),this.lastAction=null;let s=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,n,this.autocompletePrefix);this.state.lines=s.lines,this.state.cursorLine=s.cursorLine,this.setCursorCol(s.cursorCol),this.cancelAutocomplete(),this.onChange&&this.onChange(this.getText());}return}if(e.matches(t,"tui.select.confirm")){let n=this.autocompleteList.getSelectedItem();if(n&&this.autocompleteProvider){this.pushUndoSnapshot(),this.lastAction=null;let s=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,n,this.autocompletePrefix);if(this.state.lines=s.lines,this.state.cursorLine=s.cursorLine,this.setCursorCol(s.cursorCol),this.autocompletePrefix.startsWith("/")){if(this.cancelAutocomplete(),!(this.shouldAutoSubmitSlashCommand?.(n,this.autocompletePrefix)??true)){this.onChange&&this.onChange(this.getText());return}}else {this.cancelAutocomplete(),this.onChange&&this.onChange(this.getText()),_n(n)&&this.tryTriggerAutocomplete();return}}}}if(e.matches(t,"tui.input.tab")&&!this.autocompleteState){this.handleTabCompletion();return}if(e.matches(t,"tui.editor.deleteToLineEnd")){this.deleteToEndOfLine();return}if(e.matches(t,"tui.editor.deleteToLineStart")){this.deleteToStartOfLine();return}if(e.matches(t,"tui.editor.deleteWordBackward")){this.deleteWordBackwards();return}if(e.matches(t,"tui.editor.deleteWordForward")){this.deleteWordForward();return}if(e.matches(t,"tui.editor.deleteCharBackward")||ae(t,"shift+backspace")){this.handleBackspace();return}if(e.matches(t,"tui.editor.deleteCharForward")||ae(t,"shift+delete")){this.handleForwardDelete();return}if(e.matches(t,"tui.editor.yank")){this.yank();return}if(e.matches(t,"tui.editor.yankPop")){this.yankPop();return}if(e.matches(t,"tui.editor.historyPrevious")){this.cancelAutocomplete(),this.navigateHistory(-1);return}if(e.matches(t,"tui.editor.historyNext")){this.cancelAutocomplete(),this.navigateHistory(1);return}if(e.matches(t,"tui.editor.cursorLineStart")){this.moveToLineStart();return}if(e.matches(t,"tui.editor.cursorLineEnd")){this.moveToLineEnd();return}if(e.matches(t,"tui.editor.cursorWordLeft")){this.moveWordBackwards();return}if(e.matches(t,"tui.editor.cursorWordRight")){this.moveWordForwards();return}if(e.matches(t,"tui.input.newLine")||t.charCodeAt(0)===10&&t.length>1||t==="\x1B\r"||t==="\x1B[13;2~"||t.length>1&&t.includes("\x1B")&&t.includes("\r")||t===`
7
+ `&&t.length===1){if(this.shouldSubmitOnBackslashEnter(t,e)){this.handleBackspace(),this.submitValue();return}this.addNewLine();return}if(e.matches(t,"tui.input.submit")){if(this.disableSubmit)return;let n=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>0&&n[this.state.cursorCol-1]==="\\"){this.handleBackspace(),this.addNewLine();return}this.submitValue();return}if(e.matches(t,"tui.editor.cursorUp")){this.isOnFirstVisualLine()&&(this.isEditorEmpty()||this.historyIndex>-1||this.state.cursorCol===0)?this.navigateHistory(-1):this.isOnFirstVisualLine()?this.moveToLineStart():this.moveCursor(-1,0);return}if(e.matches(t,"tui.editor.cursorDown")){this.historyIndex>-1&&this.isOnLastVisualLine()?this.navigateHistory(1):this.isOnLastVisualLine()?this.moveToLineEnd():this.moveCursor(1,0);return}if(e.matches(t,"tui.editor.cursorRight")){this.moveCursor(0,1);return}if(e.matches(t,"tui.editor.cursorLeft")){this.moveCursor(0,-1);return}if(e.matches(t,"tui.editor.pageUp")){this.pageScroll(-1);return}if(e.matches(t,"tui.editor.pageDown")){this.pageScroll(1);return}if(e.matches(t,"tui.editor.jumpForward")){this.jumpMode="forward";return}if(e.matches(t,"tui.editor.jumpBackward")){this.jumpMode="backward";return}if(ae(t,"shift+space")){this.insertCharacter(" ");return}let r=Or(t);if(r!==void 0){this.insertCharacter(r);return}t.charCodeAt(0)>=32&&this.insertCharacter(t);}layoutText(t){let e=[];if(this.state.lines.length===0||this.state.lines.length===1&&this.state.lines[0]==="")return e.push({text:"",hasCursor:true,cursorPos:0}),e;for(let r=0;r<this.state.lines.length;r++){let n=this.state.lines[r]||"",s=r===this.state.cursorLine;if(S(n)<=t)s?e.push({text:n,hasCursor:true,cursorPos:this.state.cursorCol}):e.push({text:n,hasCursor:false});else {let l=Xr(n,t,[...this.segment(n,"grapheme")]);for(let a=0;a<l.length;a++){let c=l[a];if(!c)continue;let h=this.state.cursorCol,u=a===l.length-1,p=false,f=0;s&&(u?(p=h>=c.startIndex,f=h-c.startIndex):(p=h>=c.startIndex&&h<c.endIndex,p&&(f=h-c.startIndex,f>c.text.length&&(f=c.text.length)))),p?e.push({text:c.text,hasCursor:true,cursorPos:f}):e.push({text:c.text,hasCursor:false});}}}return e}getText(){return this.state.lines.join(`
8
8
  `)}expandPasteMarkers(t){let e=t;for(let[r,n]of this.pastes){let s=new RegExp(`\\[paste #${r}( (\\+\\d+ lines|\\d+ chars))?\\]`,"g");e=e.replace(s,()=>n);}return e}getExpandedText(){return this.expandPasteMarkers(this.state.lines.join(`
9
9
  `))}getLines(){return [...this.state.lines]}getCursor(){return {line:this.state.cursorLine,col:this.state.cursorCol}}setText(t){this.cancelAutocomplete(),this.lastAction=null,this.exitHistoryBrowsing();let e=this.normalizeText(t);this.getText()!==e&&this.pushUndoSnapshot(),this.pastes.clear(),this.pasteCounter=0,this.setTextInternal(e);}insertTextAtCursor(t){t&&(this.cancelAutocomplete(),this.pushUndoSnapshot(),this.lastAction=null,this.exitHistoryBrowsing(),this.insertTextAtCursorInternal(t));}normalizeText(t){return t.replace(/\r\n/g,`
10
10
  `).replace(/\r/g,`
@@ -12,44 +12,44 @@ import*as fe from'fs';import {readdirSync,statSync}from'fs';import*as As from'os
12
12
  `),n=this.state.lines[this.state.cursorLine]||"",s=n.slice(0,this.state.cursorCol),o=n.slice(this.state.cursorCol);r.length===1?(this.state.lines[this.state.cursorLine]=s+e+o,this.setCursorCol(this.state.cursorCol+e.length)):(this.state.lines=[...this.state.lines.slice(0,this.state.cursorLine),s+r[0],...r.slice(1,-1),r[r.length-1]+o,...this.state.lines.slice(this.state.cursorLine+1)],this.state.cursorLine+=r.length-1,this.setCursorCol((r[r.length-1]||"").length)),this.onChange&&this.onChange(this.getText());}insertCharacter(t,e){this.exitHistoryBrowsing(),e||((X(t)||this.lastAction!=="type-word")&&this.pushUndoSnapshot(),this.lastAction="type-word");let r=this.state.lines[this.state.cursorLine]||"",n=r.slice(0,this.state.cursorCol),s=r.slice(this.state.cursorCol);if(this.state.lines[this.state.cursorLine]=n+t+s,this.setCursorCol(this.state.cursorCol+t.length),this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else if(t==="/"&&this.isAtStartOfMessage())this.tryTriggerAutocomplete();else if(this.autocompleteTriggerCharacters.includes(t)){let l=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.autocompleteTriggerPattern.test(l)&&this.tryTriggerAutocomplete();}else if(/[a-zA-Z0-9.\-_]/.test(t)||$e.test(t)){let l=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(l)?this.tryTriggerAutocomplete():this.autocompleteTriggerPattern.test(l)&&this.tryTriggerAutocomplete();}}handlePaste(t){this.cancelAutocomplete(),this.exitHistoryBrowsing(),this.lastAction=null,this.pushUndoSnapshot();let e=t.replace(/\x1b\[(\d+);5u/g,(l,a)=>{let c=Number(a);return c>=97&&c<=122?String.fromCharCode(c-96):c>=65&&c<=90?String.fromCharCode(c-64):l}),n=this.normalizeText(e).split("").filter(l=>l===`
13
13
  `||l.charCodeAt(0)>=32).join("");if(/^[/~.]/.test(n)){let l=this.state.lines[this.state.cursorLine]||"",a=this.state.cursorCol>0?l[this.state.cursorCol-1]:"";a&&/\w/.test(a)&&(n=` ${n}`);}let s=n.split(`
14
14
  `),o=n.length;if(s.length>10||o>1e3){this.pasteCounter++;let l=this.pasteCounter;this.pastes.set(l,n);let a=s.length>10?`[paste #${l} +${s.length} lines]`:`[paste #${l} ${o} chars]`;this.insertTextAtCursorInternal(a);return}if(s.length===1){this.insertTextAtCursorInternal(n);return}this.insertTextAtCursorInternal(n);}addNewLine(){this.cancelAutocomplete(),this.exitHistoryBrowsing(),this.lastAction=null,this.pushUndoSnapshot();let t=this.state.lines[this.state.cursorLine]||"",e=t.slice(0,this.state.cursorCol),r=t.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=e,this.state.lines.splice(this.state.cursorLine+1,0,r),this.state.cursorLine++,this.setCursorCol(0),this.onChange&&this.onChange(this.getText());}shouldSubmitOnBackslashEnter(t,e){if(this.disableSubmit||!ae(t,"enter"))return false;let r=e.getKeys("tui.input.submit");if(!(r.includes("shift+enter")||r.includes("shift+return")))return false;let s=this.state.lines[this.state.cursorLine]||"";return this.state.cursorCol>0&&s[this.state.cursorCol-1]==="\\"}submitValue(){this.cancelAutocomplete();let t=this.expandPasteMarkers(this.state.lines.join(`
15
- `)).trim();this.state={lines:[""],cursorLine:0,cursorCol:0},this.pastes.clear(),this.pasteCounter=0,this.exitHistoryBrowsing(),this.scrollOffset=0,this.undoStack.clear(),this.lastAction=null,this.onChange&&this.onChange(""),this.onSubmit&&this.onSubmit(t);}handleBackspace(){if(this.exitHistoryBrowsing(),this.lastAction=null,this.state.cursorCol>0){this.pushUndoSnapshot();let t=this.state.lines[this.state.cursorLine]||"",e=t.slice(0,this.state.cursorCol),r=[...this.segment(e,"grapheme")],n=r[r.length-1],s=n?n.segment.length:1,o=qn.exec(n?.segment??"");if(o){let c=Number(o[1]);this.pastes.delete(c),this.pasteCounter--;let h=[...this.pastes.keys()].filter(u=>u>c).sort((u,p)=>u-p);for(let u of h)this.pastes.set(u-1,this.pastes.get(u)),this.pastes.delete(u);this.state.lines=this.state.lines.map(u=>u.replace(Un,(p,f,b)=>{let m=Number(f);return m<=c?p:`[paste #${m-1}${b}]`}));}t=this.state.lines[this.state.cursorLine]||"";let l=t.slice(0,this.state.cursorCol-s),a=t.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=l+a,this.setCursorCol(this.state.cursorCol-s);}else if(this.state.cursorLine>0){this.pushUndoSnapshot();let t=this.state.lines[this.state.cursorLine]||"",e=this.state.lines[this.state.cursorLine-1]||"";this.state.lines[this.state.cursorLine-1]=e+t,this.state.lines.splice(this.state.cursorLine,1),this.state.cursorLine--,this.setCursorCol(e.length);}if(this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else {let e=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(e)?this.tryTriggerAutocomplete():this.autocompleteTriggerPattern.test(e)&&this.tryTriggerAutocomplete();}}setCursorCol(t){this.state.cursorCol=t,this.preferredVisualCol=null,this.snappedFromCursorCol=null;}moveToVisualLine(t,e,r){let n=t[e],s=t[r];if(!(n&&s))return;let o;if(this.snappedFromCursorCol!==null){let m=this.findVisualLineAt(t,n.logicalLine,this.snappedFromCursorCol);o=this.snappedFromCursorCol-(t[m]?.startCol??0);}else o=this.state.cursorCol-n.startCol;let a=e===t.length-1||t[e+1]?.logicalLine!==n.logicalLine?n.length:Math.max(0,n.length-1),h=r===t.length-1||t[r+1]?.logicalLine!==s.logicalLine?s.length:Math.max(0,s.length-1),u=this.computeVerticalMoveColumn(o,a,h);this.state.cursorLine=s.logicalLine;let p=s.startCol+u,f=this.state.lines[s.logicalLine]||"";this.state.cursorCol=Math.min(p,f.length);let b=[...this.segment(f,"grapheme")];for(let m of b){if(m.index>this.state.cursorCol)break;if(!(m.segment.length<=1)&&this.state.cursorCol<m.index+m.segment.length){let g=m.index<s.startCol,x=r>e;if(g&&x){let v=m.index+m.segment.length,y=r+1;for(;y<t.length&&t[y]?.logicalLine===s.logicalLine&&(t[y]?.startCol??0)<v;)y++;if(y<t.length){this.moveToVisualLine(t,e,y);return}}this.snappedFromCursorCol=this.state.cursorCol,this.state.cursorCol=m.index;return}}this.snappedFromCursorCol=null;}computeVerticalMoveColumn(t,e,r){let n=this.preferredVisualCol!==null,s=t<e,o=r<t;if(!n||s)return o?(this.preferredVisualCol=t,r):(this.preferredVisualCol=null,t);let l=r<this.preferredVisualCol;if(o||l)return r;let a=this.preferredVisualCol;return this.preferredVisualCol=null,a}moveToLineStart(){this.lastAction=null,this.setCursorCol(0);}moveToLineEnd(){this.lastAction=null;let t=this.state.lines[this.state.cursorLine]||"";this.setCursorCol(t.length);}deleteToStartOfLine(){this.exitHistoryBrowsing();let t=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>0){this.pushUndoSnapshot();let e=t.slice(0,this.state.cursorCol);this.killRing.push(e,{prepend:true,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=t.slice(this.state.cursorCol),this.setCursorCol(0);}else if(this.state.cursorLine>0){this.pushUndoSnapshot(),this.killRing.push(`
15
+ `)).trim();this.state={lines:[""],cursorLine:0,cursorCol:0},this.pastes.clear(),this.pasteCounter=0,this.exitHistoryBrowsing(),this.scrollOffset=0,this.undoStack.clear(),this.lastAction=null,this.onChange&&this.onChange(""),this.onSubmit&&this.onSubmit(t);}handleBackspace(){if(this.exitHistoryBrowsing(),this.lastAction=null,this.state.cursorCol>0){this.pushUndoSnapshot();let t=this.state.lines[this.state.cursorLine]||"",e=t.slice(0,this.state.cursorCol),r=[...this.segment(e,"grapheme")],n=r[r.length-1],s=n?n.segment.length:1,o=Hn.exec(n?.segment??"");if(o){let c=Number(o[1]);this.pastes.delete(c),this.pasteCounter--;let h=[...this.pastes.keys()].filter(u=>u>c).sort((u,p)=>u-p);for(let u of h)this.pastes.set(u-1,this.pastes.get(u)),this.pastes.delete(u);this.state.lines=this.state.lines.map(u=>u.replace(Vn,(p,f,b)=>{let m=Number(f);return m<=c?p:`[paste #${m-1}${b}]`}));}t=this.state.lines[this.state.cursorLine]||"";let l=t.slice(0,this.state.cursorCol-s),a=t.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=l+a,this.setCursorCol(this.state.cursorCol-s);}else if(this.state.cursorLine>0){this.pushUndoSnapshot();let t=this.state.lines[this.state.cursorLine]||"",e=this.state.lines[this.state.cursorLine-1]||"";this.state.lines[this.state.cursorLine-1]=e+t,this.state.lines.splice(this.state.cursorLine,1),this.state.cursorLine--,this.setCursorCol(e.length);}if(this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else {let e=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(e)?this.tryTriggerAutocomplete():this.autocompleteTriggerPattern.test(e)&&this.tryTriggerAutocomplete();}}setCursorCol(t){this.state.cursorCol=t,this.preferredVisualCol=null,this.snappedFromCursorCol=null;}moveToVisualLine(t,e,r){let n=t[e],s=t[r];if(!(n&&s))return;let o;if(this.snappedFromCursorCol!==null){let m=this.findVisualLineAt(t,n.logicalLine,this.snappedFromCursorCol);o=this.snappedFromCursorCol-(t[m]?.startCol??0);}else o=this.state.cursorCol-n.startCol;let a=e===t.length-1||t[e+1]?.logicalLine!==n.logicalLine?n.length:Math.max(0,n.length-1),h=r===t.length-1||t[r+1]?.logicalLine!==s.logicalLine?s.length:Math.max(0,s.length-1),u=this.computeVerticalMoveColumn(o,a,h);this.state.cursorLine=s.logicalLine;let p=s.startCol+u,f=this.state.lines[s.logicalLine]||"";this.state.cursorCol=Math.min(p,f.length);let b=[...this.segment(f,"grapheme")];for(let m of b){if(m.index>this.state.cursorCol)break;if(!(m.segment.length<=1)&&this.state.cursorCol<m.index+m.segment.length){let g=m.index<s.startCol,y=r>e;if(g&&y){let v=m.index+m.segment.length,x=r+1;for(;x<t.length&&t[x]?.logicalLine===s.logicalLine&&(t[x]?.startCol??0)<v;)x++;if(x<t.length){this.moveToVisualLine(t,e,x);return}}this.snappedFromCursorCol=this.state.cursorCol,this.state.cursorCol=m.index;return}}this.snappedFromCursorCol=null;}computeVerticalMoveColumn(t,e,r){let n=this.preferredVisualCol!==null,s=t<e,o=r<t;if(!n||s)return o?(this.preferredVisualCol=t,r):(this.preferredVisualCol=null,t);let l=r<this.preferredVisualCol;if(o||l)return r;let a=this.preferredVisualCol;return this.preferredVisualCol=null,a}moveToLineStart(){this.lastAction=null,this.setCursorCol(0);}moveToLineEnd(){this.lastAction=null;let t=this.state.lines[this.state.cursorLine]||"";this.setCursorCol(t.length);}deleteToStartOfLine(){this.exitHistoryBrowsing();let t=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>0){this.pushUndoSnapshot();let e=t.slice(0,this.state.cursorCol);this.killRing.push(e,{prepend:true,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=t.slice(this.state.cursorCol),this.setCursorCol(0);}else if(this.state.cursorLine>0){this.pushUndoSnapshot(),this.killRing.push(`
16
16
  `,{prepend:true,accumulate:this.lastAction==="kill"}),this.lastAction="kill";let e=this.state.lines[this.state.cursorLine-1]||"";this.state.lines[this.state.cursorLine-1]=e+t,this.state.lines.splice(this.state.cursorLine,1),this.state.cursorLine--,this.setCursorCol(e.length);}this.onChange&&this.onChange(this.getText());}deleteToEndOfLine(){this.exitHistoryBrowsing();let t=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol<t.length){this.pushUndoSnapshot();let e=t.slice(this.state.cursorCol);this.killRing.push(e,{prepend:false,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=t.slice(0,this.state.cursorCol);}else if(this.state.cursorLine<this.state.lines.length-1){this.pushUndoSnapshot(),this.killRing.push(`
17
17
  `,{prepend:false,accumulate:this.lastAction==="kill"}),this.lastAction="kill";let e=this.state.lines[this.state.cursorLine+1]||"";this.state.lines[this.state.cursorLine]=t+e,this.state.lines.splice(this.state.cursorLine+1,1);}this.onChange&&this.onChange(this.getText());}deleteWordBackwards(){this.exitHistoryBrowsing();let t=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol===0){if(this.state.cursorLine>0){this.pushUndoSnapshot(),this.killRing.push(`
18
18
  `,{prepend:true,accumulate:this.lastAction==="kill"}),this.lastAction="kill";let e=this.state.lines[this.state.cursorLine-1]||"";this.state.lines[this.state.cursorLine-1]=e+t,this.state.lines.splice(this.state.cursorLine,1),this.state.cursorLine--,this.setCursorCol(e.length);}}else {this.pushUndoSnapshot();let e=this.lastAction==="kill",r=this.state.cursorCol;this.moveWordBackwards();let n=this.state.cursorCol;this.setCursorCol(r);let s=t.slice(n,this.state.cursorCol);this.killRing.push(s,{prepend:true,accumulate:e}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=t.slice(0,n)+t.slice(this.state.cursorCol),this.setCursorCol(n);}this.onChange&&this.onChange(this.getText());}deleteWordForward(){this.exitHistoryBrowsing();let t=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>=t.length){if(this.state.cursorLine<this.state.lines.length-1){this.pushUndoSnapshot(),this.killRing.push(`
19
- `,{prepend:false,accumulate:this.lastAction==="kill"}),this.lastAction="kill";let e=this.state.lines[this.state.cursorLine+1]||"";this.state.lines[this.state.cursorLine]=t+e,this.state.lines.splice(this.state.cursorLine+1,1);}}else {this.pushUndoSnapshot();let e=this.lastAction==="kill",r=this.state.cursorCol;this.moveWordForwards();let n=this.state.cursorCol;this.setCursorCol(r);let s=t.slice(this.state.cursorCol,n);this.killRing.push(s,{prepend:false,accumulate:e}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=t.slice(0,this.state.cursorCol)+t.slice(n);}this.onChange&&this.onChange(this.getText());}handleForwardDelete(){this.exitHistoryBrowsing(),this.lastAction=null;let t=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol<t.length){this.pushUndoSnapshot();let e=t.slice(this.state.cursorCol),n=[...this.segment(e,"grapheme")][0],s=n?n.segment.length:1,o=t.slice(0,this.state.cursorCol),l=t.slice(this.state.cursorCol+s);this.state.lines[this.state.cursorLine]=o+l;}else if(this.state.cursorLine<this.state.lines.length-1){this.pushUndoSnapshot();let e=this.state.lines[this.state.cursorLine+1]||"";this.state.lines[this.state.cursorLine]=t+e,this.state.lines.splice(this.state.cursorLine+1,1);}if(this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else {let r=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(r)?this.tryTriggerAutocomplete():this.autocompleteTriggerPattern.test(r)&&this.tryTriggerAutocomplete();}}buildVisualLineMap(t){let e=[];for(let r=0;r<this.state.lines.length;r++){let n=this.state.lines[r]||"",s=S(n);if(n.length===0)e.push({logicalLine:r,startCol:0,length:0});else if(s<=t)e.push({logicalLine:r,startCol:0,length:n.length});else {let o=Qr(n,t,[...this.segment(n,"grapheme")]);for(let l of o)e.push({logicalLine:r,startCol:l.startIndex,length:l.endIndex-l.startIndex});}}return e}findVisualLineAt(t,e,r){for(let n=0;n<t.length;n++){let s=t[n];if(!s||s.logicalLine!==e)continue;let o=r-s.startCol,l=n===t.length-1||t[n+1]?.logicalLine!==s.logicalLine;if(o>=0&&(o<s.length||l&&o===s.length))return n}return t.length-1}findCurrentVisualLine(t){return this.findVisualLineAt(t,this.state.cursorLine,this.state.cursorCol)}moveCursor(t,e){this.lastAction=null;let r=this.buildVisualLineMap(this.lastWidth),n=this.findCurrentVisualLine(r);if(t!==0){let s=n+t;s>=0&&s<r.length&&this.moveToVisualLine(r,n,s);}if(e!==0){let s=this.state.lines[this.state.cursorLine]||"";if(e>0)if(this.state.cursorCol<s.length){let o=s.slice(this.state.cursorCol),a=[...this.segment(o,"grapheme")][0];this.setCursorCol(this.state.cursorCol+(a?a.segment.length:1));}else if(this.state.cursorLine<this.state.lines.length-1)this.state.cursorLine++,this.setCursorCol(0);else {let o=r[n];o&&(this.preferredVisualCol=this.state.cursorCol-o.startCol);}else if(this.state.cursorCol>0){let o=s.slice(0,this.state.cursorCol),l=[...this.segment(o,"grapheme")],a=l[l.length-1];this.setCursorCol(this.state.cursorCol-(a?a.segment.length:1));}else if(this.state.cursorLine>0){this.state.cursorLine--;let o=this.state.lines[this.state.cursorLine]||"";this.setCursorCol(o.length);}}this.autocompleteState&&this.updateAutocomplete();}pageScroll(t){this.lastAction=null;let e=this.tui.terminal.rows,r=Math.max(5,Math.floor(e*.3)),n=this.buildVisualLineMap(this.lastWidth),s=this.findCurrentVisualLine(n),o=Math.max(0,Math.min(n.length-1,s+t*r));this.moveToVisualLine(n,s,o);}moveWordBackwards(){this.lastAction=null;let t=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol===0){if(this.state.cursorLine>0){this.state.cursorLine--;let e=this.state.lines[this.state.cursorLine]||"";this.setCursorCol(e.length);}return}this.setCursorCol(Xt(t,this.state.cursorCol,{segment:e=>this.segment(e,"word"),isAtomicSegment:Ye}));}yank(){if(this.killRing.length===0)return;this.pushUndoSnapshot();let t=this.killRing.peek();this.insertYankedText(t),this.lastAction="yank";}yankPop(){if(this.lastAction!=="yank"||this.killRing.length<=1)return;this.pushUndoSnapshot(),this.deleteYankedText(),this.killRing.rotate();let t=this.killRing.peek();this.insertYankedText(t),this.lastAction="yank";}insertYankedText(t){this.exitHistoryBrowsing();let e=t.split(`
19
+ `,{prepend:false,accumulate:this.lastAction==="kill"}),this.lastAction="kill";let e=this.state.lines[this.state.cursorLine+1]||"";this.state.lines[this.state.cursorLine]=t+e,this.state.lines.splice(this.state.cursorLine+1,1);}}else {this.pushUndoSnapshot();let e=this.lastAction==="kill",r=this.state.cursorCol;this.moveWordForwards();let n=this.state.cursorCol;this.setCursorCol(r);let s=t.slice(this.state.cursorCol,n);this.killRing.push(s,{prepend:false,accumulate:e}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=t.slice(0,this.state.cursorCol)+t.slice(n);}this.onChange&&this.onChange(this.getText());}handleForwardDelete(){this.exitHistoryBrowsing(),this.lastAction=null;let t=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol<t.length){this.pushUndoSnapshot();let e=t.slice(this.state.cursorCol),n=[...this.segment(e,"grapheme")][0],s=n?n.segment.length:1,o=t.slice(0,this.state.cursorCol),l=t.slice(this.state.cursorCol+s);this.state.lines[this.state.cursorLine]=o+l;}else if(this.state.cursorLine<this.state.lines.length-1){this.pushUndoSnapshot();let e=this.state.lines[this.state.cursorLine+1]||"";this.state.lines[this.state.cursorLine]=t+e,this.state.lines.splice(this.state.cursorLine+1,1);}if(this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else {let r=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(r)?this.tryTriggerAutocomplete():this.autocompleteTriggerPattern.test(r)&&this.tryTriggerAutocomplete();}}buildVisualLineMap(t){let e=[];for(let r=0;r<this.state.lines.length;r++){let n=this.state.lines[r]||"",s=S(n);if(n.length===0)e.push({logicalLine:r,startCol:0,length:0});else if(s<=t)e.push({logicalLine:r,startCol:0,length:n.length});else {let o=Xr(n,t,[...this.segment(n,"grapheme")]);for(let l of o)e.push({logicalLine:r,startCol:l.startIndex,length:l.endIndex-l.startIndex});}}return e}findVisualLineAt(t,e,r){for(let n=0;n<t.length;n++){let s=t[n];if(!s||s.logicalLine!==e)continue;let o=r-s.startCol,l=n===t.length-1||t[n+1]?.logicalLine!==s.logicalLine;if(o>=0&&(o<s.length||l&&o===s.length))return n}return t.length-1}findCurrentVisualLine(t){return this.findVisualLineAt(t,this.state.cursorLine,this.state.cursorCol)}moveCursor(t,e){this.lastAction=null;let r=this.buildVisualLineMap(this.lastWidth),n=this.findCurrentVisualLine(r);if(t!==0){let s=n+t;s>=0&&s<r.length&&this.moveToVisualLine(r,n,s);}if(e!==0){let s=this.state.lines[this.state.cursorLine]||"";if(e>0)if(this.state.cursorCol<s.length){let o=s.slice(this.state.cursorCol),a=[...this.segment(o,"grapheme")][0];this.setCursorCol(this.state.cursorCol+(a?a.segment.length:1));}else if(this.state.cursorLine<this.state.lines.length-1)this.state.cursorLine++,this.setCursorCol(0);else {let o=r[n];o&&(this.preferredVisualCol=this.state.cursorCol-o.startCol);}else if(this.state.cursorCol>0){let o=s.slice(0,this.state.cursorCol),l=[...this.segment(o,"grapheme")],a=l[l.length-1];this.setCursorCol(this.state.cursorCol-(a?a.segment.length:1));}else if(this.state.cursorLine>0){this.state.cursorLine--;let o=this.state.lines[this.state.cursorLine]||"";this.setCursorCol(o.length);}}this.autocompleteState&&this.updateAutocomplete();}pageScroll(t){this.lastAction=null;let e=this.tui.terminal.rows,r=Math.max(5,Math.floor(e*.3)),n=this.buildVisualLineMap(this.lastWidth),s=this.findCurrentVisualLine(n),o=Math.max(0,Math.min(n.length-1,s+t*r));this.moveToVisualLine(n,s,o);}moveWordBackwards(){this.lastAction=null;let t=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol===0){if(this.state.cursorLine>0){this.state.cursorLine--;let e=this.state.lines[this.state.cursorLine]||"";this.setCursorCol(e.length);}return}this.setCursorCol(jt(t,this.state.cursorCol,{segment:e=>this.segment(e,"word"),isAtomicSegment:Ye}));}yank(){if(this.killRing.length===0)return;this.pushUndoSnapshot();let t=this.killRing.peek();this.insertYankedText(t),this.lastAction="yank";}yankPop(){if(this.lastAction!=="yank"||this.killRing.length<=1)return;this.pushUndoSnapshot(),this.deleteYankedText(),this.killRing.rotate();let t=this.killRing.peek();this.insertYankedText(t),this.lastAction="yank";}insertYankedText(t){this.exitHistoryBrowsing();let e=t.split(`
20
20
  `);if(e.length===1){let r=this.state.lines[this.state.cursorLine]||"",n=r.slice(0,this.state.cursorCol),s=r.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=n+t+s,this.setCursorCol(this.state.cursorCol+t.length);}else {let r=this.state.lines[this.state.cursorLine]||"",n=r.slice(0,this.state.cursorCol),s=r.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=n+(e[0]||"");for(let l=1;l<e.length-1;l++)this.state.lines.splice(this.state.cursorLine+l,0,e[l]||"");let o=this.state.cursorLine+e.length-1;this.state.lines.splice(o,0,(e[e.length-1]||"")+s),this.state.cursorLine=o,this.setCursorCol((e[e.length-1]||"").length);}this.onChange&&this.onChange(this.getText());}deleteYankedText(){let t=this.killRing.peek();if(!t)return;let e=t.split(`
21
- `);if(e.length===1){let r=this.state.lines[this.state.cursorLine]||"",n=t.length,s=r.slice(0,this.state.cursorCol-n),o=r.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=s+o,this.setCursorCol(this.state.cursorCol-n);}else {let r=this.state.cursorLine-(e.length-1),n=(this.state.lines[r]||"").length-(e[0]||"").length,s=(this.state.lines[this.state.cursorLine]||"").slice(this.state.cursorCol),o=(this.state.lines[r]||"").slice(0,n);this.state.lines.splice(r,e.length,o+s),this.state.cursorLine=r,this.setCursorCol(n);}this.onChange&&this.onChange(this.getText());}pushUndoSnapshot(){this.undoStack.push({state:this.state,pastes:this.pastes,pasteCounter:this.pasteCounter});}undo(){this.exitHistoryBrowsing();let t=this.undoStack.pop();t&&(Object.assign(this.state,t.state),this.pastes=t.pastes,this.pasteCounter=t.pasteCounter,this.lastAction=null,this.preferredVisualCol=null,this.snappedFromCursorCol=null,this.onChange&&this.onChange(this.getText()));}jumpToChar(t,e){this.lastAction=null;let r=e==="forward",n=this.state.lines,s=r?n.length:-1,o=r?1:-1;for(let l=this.state.cursorLine;l!==s;l+=o){let a=n[l]||"",c=l===this.state.cursorLine,h;if(c)if(r)h=this.state.cursorCol+1;else {let p=this.state.cursorCol-1;if(p<0)continue;h=p;}let u=r?a.indexOf(t,h):a.lastIndexOf(t,h);if(u!==-1){this.state.cursorLine=l,this.setCursorCol(u);return}}}moveWordForwards(){this.lastAction=null;let t=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>=t.length){this.state.cursorLine<this.state.lines.length-1&&(this.state.cursorLine++,this.setCursorCol(0));return}this.setCursorCol(Qt(t,this.state.cursorCol,{segment:e=>this.segment(e,"word"),isAtomicSegment:Ye}));}isSlashMenuAllowed(){return this.state.cursorLine===0}isAtStartOfMessage(){if(!this.isSlashMenuAllowed())return false;let e=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);return e.trim()===""||e.trim()==="/"}isInSlashCommandContext(t){return this.isSlashMenuAllowed()&&t.trimStart().startsWith("/")}getBestAutocompleteMatchIndex(t,e){if(!e)return -1;let r=e.startsWith("/")?e.slice(1):e;if(!r)return -1;let n=-1;for(let s=0;s<t.length;s++){let o=t[s].value;if(o===r)return s;n===-1&&o.startsWith(r)&&(n=s);}return n}createAutocompleteList(t,e){let r=t.startsWith("/")?ya:void 0,n=new dt(e,this.autocompleteMaxVisible,this.theme.selectList,r);return n.onSelect=s=>{if(!this.autocompleteProvider)return;this.pushUndoSnapshot(),this.lastAction=null;let o=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,s,this.autocompletePrefix);this.state.lines=o.lines,this.state.cursorLine=o.cursorLine,this.setCursorCol(o.cursorCol),this.cancelAutocomplete(),this.onChange?.(this.getText()),Nn(s)&&this.tryTriggerAutocomplete();},n}tryTriggerAutocomplete(t=false){this.requestAutocomplete({force:false,explicitTab:t});}handleTabCompletion(){if(!this.autocompleteProvider)return;let e=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(e)&&!e.trimStart().includes(" ")?this.handleSlashCommandCompletion():this.forceFileAutocomplete(true);}handleSlashCommandCompletion(){this.requestAutocomplete({force:false,explicitTab:true});}forceFileAutocomplete(t=false){this.requestAutocomplete({force:true,explicitTab:t});}requestAutocomplete(t){if(!this.autocompleteProvider||t.force&&!(!this.autocompleteProvider.shouldTriggerFileCompletion||this.autocompleteProvider.shouldTriggerFileCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol)))return;this.cancelAutocompleteRequest();let e=++this.autocompleteStartToken,r=this.getAutocompleteDebounceMs(t);if(r>0){this.autocompleteDebounceTimer=setTimeout(()=>{this.autocompleteDebounceTimer=void 0,this.startAutocompleteRequest(e,t);},r);return}this.startAutocompleteRequest(e,t);}async startAutocompleteRequest(t,e){let r=this.autocompleteRequestTask;this.autocompleteRequestTask=(async()=>{if(await r,t!==this.autocompleteStartToken||!this.autocompleteProvider)return;let n=new AbortController;this.autocompleteAbort=n;let s=++this.autocompleteRequestId,o=this.getText(),l=this.state.cursorLine,a=this.state.cursorCol;await this.runAutocompleteRequest(s,n,o,l,a,e);})(),await this.autocompleteRequestTask;}setAutocompleteTriggerCharacters(t){let e=[...Dn];for(let r of t)r.length!==1||r==="/"||X(r)||e.includes(r)||e.push(r);this.autocompleteTriggerCharacters=e,this.autocompleteTriggerPattern=Fn(e),this.autocompleteDebouncePattern=Wn(e);}getAutocompleteDebounceMs(t){if(t.explicitTab||t.force)return 0;let r=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);return this.autocompleteDebouncePattern.test(r)?va:0}async runAutocompleteRequest(t,e,r,n,s,o){if(!this.autocompleteProvider)return;let l=await this.autocompleteProvider.getSuggestions(this.state.lines,this.state.cursorLine,this.state.cursorCol,{signal:e.signal,force:o.force});if(this.isAutocompleteRequestCurrent(t,e,r,n,s)){if(this.autocompleteAbort=void 0,!l||!Array.isArray(l.items)||l.items.length===0){this.cancelAutocomplete(),this.tui.requestRender();return}if(o.force&&o.explicitTab&&l.items.length===1){let a=l.items[0];this.pushUndoSnapshot(),this.lastAction=null;let c=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,a,l.prefix);this.state.lines=c.lines,this.state.cursorLine=c.cursorLine,this.setCursorCol(c.cursorCol),this.onChange&&this.onChange(this.getText()),this.tui.requestRender();return}this.applyAutocompleteSuggestions(l,o.force?"force":"regular"),this.tui.requestRender();}}isAutocompleteRequestCurrent(t,e,r,n,s){return !e.signal.aborted&&t===this.autocompleteRequestId&&this.getText()===r&&this.state.cursorLine===n&&this.state.cursorCol===s}applyAutocompleteSuggestions(t,e){this.autocompletePrefix=t.prefix,this.autocompleteList=this.createAutocompleteList(t.prefix,t.items);let r=this.getBestAutocompleteMatchIndex(t.items,t.prefix);r>=0&&this.autocompleteList.setSelectedIndex(r),this.autocompleteState=e;}cancelAutocompleteRequest(){this.autocompleteStartToken+=1,this.autocompleteDebounceTimer&&(clearTimeout(this.autocompleteDebounceTimer),this.autocompleteDebounceTimer=void 0),this.autocompleteAbort?.abort(),this.autocompleteAbort=void 0;}clearAutocompleteUi(){this.autocompleteState=null,this.autocompleteList=void 0,this.autocompletePrefix="";}cancelAutocomplete(){this.cancelAutocompleteRequest(),this.clearAutocompleteUi();}isShowingAutocomplete(){return this.autocompleteState!==null}updateAutocomplete(){!this.autocompleteState||!this.autocompleteProvider||this.requestAutocomplete({force:this.autocompleteState==="force",explicitTab:false});}};var je=Symbol.for("@earendil-works/pi-tui/layout-node");function Jt(i){let t=i;return typeof t[je]=="function"?t[je]():void 0}function Sa(i){return !("render"in i)}function pt(i,t){return i===void 0||!Number.isFinite(i)?t:Math.max(0,Math.floor(i))}var Xe=class extends oe{constructor(e=[],r={}){super();d(this,"entries",[]);d(this,"gap");d(this,"align");this.gap=pt(r.gap,0),this.align=r.align??"stretch";for(let n of e)Sa(n)?this.addChild(n.component,n):this.addChild(n);}addChild(e,r={}){super.addChild(e),this.entries.push({component:e,...r.basis===void 0?{}:{basis:r.basis},...r.grow===void 0?{}:{grow:pt(r.grow,0)},...r.shrink===void 0?{}:{shrink:pt(r.shrink,1)},...r.minSize===void 0?{}:{minSize:pt(r.minSize,0)},...r.maxSize===void 0?{}:{maxSize:pt(r.maxSize,Number.MAX_SAFE_INTEGER)},...r.visible===void 0?{}:{visible:r.visible}});}removeChild(e){super.removeChild(e);let r=this.entries.findIndex(n=>n.component===e);r!==-1&&this.entries.splice(r,1);}clear(){super.clear(),this.entries.length=0;}[je](){return {type:this.layoutType,entries:this.entries,gap:this.gap,align:this.align}}};function Qe(i,t){return i.filter(e=>e.visible?.(t)??true)}function Ca(i,t){let e=Math.max(0,Math.floor(t.minSize??0)),r=Math.max(e,Math.floor(t.maxSize??Number.MAX_SAFE_INTEGER));return Math.max(e,Math.min(r,Math.max(0,Math.floor(i))))}function zn(i,t,e,r){let n=e;for(;n>0;){let s=t.map((a,c)=>({entry:a,index:c})).filter(({entry:a,index:c})=>r==="grow"?(a.grow??0)>0&&i[c]<(a.maxSize??Number.MAX_SAFE_INTEGER):(a.shrink??1)>0&&i[c]>(a.minSize??0));if(s.length===0)return;let o=s.reduce((a,{entry:c,index:h})=>a+(r==="grow"?c.grow??0:(c.shrink??1)*Math.max(1,i[h])),0),l=0;for(let{entry:a,index:c}of s){if(n<=0)break;let h=r==="grow"?a.grow??0:(a.shrink??1)*Math.max(1,i[c]),u=Math.max(1,Math.floor(n*h/o)),p=r==="grow"?(a.maxSize??Number.MAX_SAFE_INTEGER)-i[c]:i[c]-(a.minSize??0),f=Math.min(n,u,p);f<=0||(i[c]=i[c]+(r==="grow"?f:-f),n-=f,l+=f);}if(l===0)return}}function Ce(i,t,e,r){let n=i.map((l,a)=>Ca(l.basis===void 0||l.basis==="auto"?t[a]??0:l.basis,l));if(e===void 0)return n;let s=Math.max(0,Math.floor(e)-Math.max(0,i.length-1)*r),o=n.reduce((l,a)=>l+a,0);return o<s?zn(n,i,s-o,"grow"):o>s&&zn(n,i,o-s,"shrink"),n}var ei=class extends Xe{constructor(e=[],r={}){super(e,r);d(this,"layoutType","hstack");}render(e){let r=Math.max(1,e),n={width:r,height:Number.MAX_SAFE_INTEGER},s=Qe(this.entries,n);if(s.length===0)return [];let o=s.map(p=>p.component.render(r).reduce((b,m)=>Math.max(b,S(m)),0)),l=Ce(s,o,r,this.gap),a=s.map((p,f)=>l[f]===0?[]:p.component.render(l[f])),c=a.reduce((p,f)=>Math.max(p,f.length),0),h=Array.from({length:c},()=>""),u=0;for(let p=0;p<a.length;p++){let f=a[p],b=l[p],m=0;this.align==="center"?m=Math.floor((c-f.length)/2):this.align==="end"&&(m=c-f.length);for(let g=0;g<f.length;g++){let x=g+m;x<0||x>=h.length||(h[x]=de(h[x],f[g],u,b,r));}u+=b+this.gap;}return h}};var ti,we=new Map;function wa(i){ti=i,we.clear();}function Ta(i,t){if(!ti)return null;let e=we.get(i),r=e===void 0?ti(i,t):e;return we.delete(i),we.set(i,r),we.size>32&&we.delete(we.keys().next().value),r}var ri=class{constructor(t,e,r,n={},s){d(this,"base64Data");d(this,"mimeType");d(this,"dimensions");d(this,"theme");d(this,"options");d(this,"imageId");d(this,"pngData");d(this,"cachedLines");d(this,"cachedWidth");this.base64Data=t,this.mimeType=e,this.theme=r,this.options=n,this.dimensions=s||Vr(t,e)||{widthPx:800,heightPx:600},this.imageId=n.imageId;}getImageId(){return this.imageId}invalidate(){this.cachedLines=void 0,this.cachedWidth=void 0;}render(t){if(this.cachedLines&&this.cachedWidth===t)return this.cachedLines;let e=Math.max(1,Math.min(t-2,this.options.maxWidthCells??60)),r=Nt(),n=Math.max(1,Math.ceil(e*r.widthPx/r.heightPx)),s=this.options.maxHeightCells??n,o=re(),l=this.base64Data,a=this.dimensions;o.images==="kitty"&&this.mimeType!=="image/png"&&(this.pngData??(this.pngData=Ta(this.base64Data,this.mimeType)??void 0),l=this.pngData??null,l&&(a=Vt(l)??a));let c;if(o.images&&l){o.images==="kitty"&&this.imageId===void 0&&(this.imageId=Br());let h=Hr(l,a,{maxWidthCells:e,maxHeightCells:s,imageId:this.imageId,moveCursor:false});if(h)if(h.imageId&&(this.imageId=h.imageId),o.images==="kitty"){c=[h.sequence];for(let u=0;u<h.rows-1;u++)c.push("");}else {c=[];for(let f=0;f<h.rows-1;f++)c.push("");let u=h.rows-1,p=u>0?`\x1B[${u}A`:"";c.push(p+h.sequence);}else {let u=Ut(this.mimeType,this.dimensions,this.options.filename);c=[N(this.theme.fallbackColor(u),t)];}}else {let h=Ut(this.mimeType,this.dimensions,this.options.filename);c=[N(this.theme.fallbackColor(h),t)];}return this.cachedLines=c,this.cachedWidth=t,c}};var Te=Pe(),Me=class{constructor(t={}){d(this,"value","");d(this,"cursor",0);d(this,"prompt");d(this,"placeholder");d(this,"placeholderStyle");d(this,"renderedStartColumn",0);d(this,"onSubmit");d(this,"onEscape");d(this,"focused",false);d(this,"pasteBuffer","");d(this,"isInPaste",false);d(this,"killRing",new Ge);d(this,"lastAction",null);d(this,"undoStack",new ze);this.prompt=t.prompt??"> ",this.placeholder=t.placeholder??"",this.placeholderStyle=t.placeholderStyle??(e=>e);}getValue(){return this.value}setValue(t){this.value=t,this.cursor=Math.min(this.cursor,t.length);}handleInput(t){if(t.includes("\x1B[200~")&&(this.isInPaste=true,this.pasteBuffer="",t=t.replace("\x1B[200~","")),this.isInPaste){this.pasteBuffer+=t;let s=this.pasteBuffer.indexOf("\x1B[201~");if(s!==-1){let o=this.pasteBuffer.substring(0,s);this.handlePaste(o),this.isInPaste=false;let l=this.pasteBuffer.substring(s+6);this.pasteBuffer="",l&&this.handleInput(l);}return}let e=G();if(e.matches(t,"tui.select.cancel")){this.onEscape&&this.onEscape();return}if(e.matches(t,"tui.editor.undo")){this.undo();return}if(e.matches(t,"tui.input.submit")||t===`
22
- `){this.onSubmit&&this.onSubmit(this.value);return}if(e.matches(t,"tui.editor.deleteCharBackward")){this.handleBackspace();return}if(e.matches(t,"tui.editor.deleteCharForward")){this.handleForwardDelete();return}if(e.matches(t,"tui.editor.deleteWordBackward")){this.deleteWordBackwards();return}if(e.matches(t,"tui.editor.deleteWordForward")){this.deleteWordForward();return}if(e.matches(t,"tui.editor.deleteToLineStart")){this.deleteToLineStart();return}if(e.matches(t,"tui.editor.deleteToLineEnd")){this.deleteToLineEnd();return}if(e.matches(t,"tui.editor.yank")){this.yank();return}if(e.matches(t,"tui.editor.yankPop")){this.yankPop();return}if(e.matches(t,"tui.editor.cursorLeft")){if(this.lastAction=null,this.cursor>0){let s=this.value.slice(0,this.cursor),o=[...Te.segment(s)],l=o[o.length-1];this.cursor-=l?l.segment.length:1;}return}if(e.matches(t,"tui.editor.cursorRight")){if(this.lastAction=null,this.cursor<this.value.length){let s=this.value.slice(this.cursor),l=[...Te.segment(s)][0];this.cursor+=l?l.segment.length:1;}return}if(e.matches(t,"tui.editor.cursorLineStart")){this.lastAction=null,this.cursor=0;return}if(e.matches(t,"tui.editor.cursorLineEnd")){this.lastAction=null,this.cursor=this.value.length;return}if(e.matches(t,"tui.editor.cursorWordLeft")){this.moveWordBackwards();return}if(e.matches(t,"tui.editor.cursorWordRight")){this.moveWordForwards();return}let r=Dt(t);if(r!==void 0){this.insertCharacter(r);return}[...t].some(s=>{let o=s.charCodeAt(0);return o<32||o===127||o>=128&&o<=159})||this.insertCharacter(t);}handleMouse(t){if(t.type!=="press"||t.button!=="left"||t.y!==0)return;let e=Math.max(0,t.x-2),r=this.renderedStartColumn+e,n=0;this.cursor=this.value.length;for(let s of Te.segment(this.value)){let o=n+S(s.segment);if(r<o){this.cursor=s.index;break}n=o;}return this.lastAction=null,{handled:true,focus:true}}insertCharacter(t){(X(t)||this.lastAction!=="type-word")&&this.pushUndo(),this.lastAction="type-word",this.value=this.value.slice(0,this.cursor)+t+this.value.slice(this.cursor),this.cursor+=t.length;}handleBackspace(){if(this.lastAction=null,this.cursor>0){this.pushUndo();let t=this.value.slice(0,this.cursor),e=[...Te.segment(t)],r=e[e.length-1],n=r?r.segment.length:1;this.value=this.value.slice(0,this.cursor-n)+this.value.slice(this.cursor),this.cursor-=n;}}handleForwardDelete(){if(this.lastAction=null,this.cursor<this.value.length){this.pushUndo();let t=this.value.slice(this.cursor),r=[...Te.segment(t)][0],n=r?r.segment.length:1;this.value=this.value.slice(0,this.cursor)+this.value.slice(this.cursor+n);}}deleteToLineStart(){if(this.cursor===0)return;this.pushUndo();let t=this.value.slice(0,this.cursor);this.killRing.push(t,{prepend:true,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.value=this.value.slice(this.cursor),this.cursor=0;}deleteToLineEnd(){if(this.cursor>=this.value.length)return;this.pushUndo();let t=this.value.slice(this.cursor);this.killRing.push(t,{prepend:false,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.value=this.value.slice(0,this.cursor);}deleteWordBackwards(){if(this.cursor===0)return;let t=this.lastAction==="kill";this.pushUndo();let e=this.cursor;this.moveWordBackwards();let r=this.cursor;this.cursor=e;let n=this.value.slice(r,this.cursor);this.killRing.push(n,{prepend:true,accumulate:t}),this.lastAction="kill",this.value=this.value.slice(0,r)+this.value.slice(this.cursor),this.cursor=r;}deleteWordForward(){if(this.cursor>=this.value.length)return;let t=this.lastAction==="kill";this.pushUndo();let e=this.cursor;this.moveWordForwards();let r=this.cursor;this.cursor=e;let n=this.value.slice(this.cursor,r);this.killRing.push(n,{prepend:false,accumulate:t}),this.lastAction="kill",this.value=this.value.slice(0,this.cursor)+this.value.slice(r);}yank(){let t=this.killRing.peek();t&&(this.pushUndo(),this.value=this.value.slice(0,this.cursor)+t+this.value.slice(this.cursor),this.cursor+=t.length,this.lastAction="yank");}yankPop(){if(this.lastAction!=="yank"||this.killRing.length<=1)return;this.pushUndo();let t=this.killRing.peek()||"";this.value=this.value.slice(0,this.cursor-t.length)+this.value.slice(this.cursor),this.cursor-=t.length,this.killRing.rotate();let e=this.killRing.peek()||"";this.value=this.value.slice(0,this.cursor)+e+this.value.slice(this.cursor),this.cursor+=e.length,this.lastAction="yank";}pushUndo(){this.undoStack.push({value:this.value,cursor:this.cursor});}undo(){let t=this.undoStack.pop();t&&(this.value=t.value,this.cursor=t.cursor,this.lastAction=null);}moveWordBackwards(){this.cursor!==0&&(this.lastAction=null,this.cursor=Xt(this.value,this.cursor));}moveWordForwards(){this.cursor>=this.value.length||(this.lastAction=null,this.cursor=Qt(this.value,this.cursor));}handlePaste(t){this.lastAction=null,this.pushUndo();let e=t.replace(/\r\n/g,"").replace(/\r/g,"").replace(/\n/g,"").replace(/\t/g," ");this.value=this.value.slice(0,this.cursor)+e+this.value.slice(this.cursor),this.cursor+=e.length;}invalidate(){}render(t){let e=t-S(this.prompt);if(e<=0)return [N(this.prompt,t,"")];if(this.value.length===0&&this.placeholder){let x=N(this.placeholder,e,""),y=[...Te.segment(x)][0]?.segment??" ",w=x.slice(y.length),I=this.focused?ie:"",T=Se(this.placeholderStyle(y)),L=I+T+this.placeholderStyle(w),M=" ".repeat(Math.max(0,e-S(L)));return [this.prompt+L+M]}let r="",n=this.cursor;this.renderedStartColumn=0;let s=S(this.value);if(s<e)r=this.value;else {let x=this.cursor===this.value.length?e-1:e,v=S(this.value.slice(0,this.cursor));if(x>0){let y=Math.floor(x/2),w=0;v<y?w=0:v>s-y?w=Math.max(0,s-x):w=Math.max(0,v-y),this.renderedStartColumn=w,r=V(this.value,w,x,true),n=V(this.value,w,Math.max(0,v-w),true).length;}else r="",n=0;}let l=[...Te.segment(r.slice(n))][0],a=r.slice(0,n),c=l?.segment??" ",h=r.slice(n+c.length),u=this.focused?ie:"",p=Se(c),f=a+u+p+h,b=S(f),m=" ".repeat(Math.max(0,e-b));return [this.prompt+f+m]}};var Ma={alpha:"\u03B1",beta:"\u03B2",gamma:"\u03B3",delta:"\u03B4",epsilon:"\u03F5",varepsilon:"\u03B5",zeta:"\u03B6",eta:"\u03B7",theta:"\u03B8",vartheta:"\u03D1",iota:"\u03B9",kappa:"\u03BA",varkappa:"\u03F0",lambda:"\u03BB",mu:"\u03BC",nu:"\u03BD",xi:"\u03BE",pi:"\u03C0",varpi:"\u03D6",rho:"\u03C1",varrho:"\u03F1",sigma:"\u03C3",varsigma:"\u03C2",tau:"\u03C4",upsilon:"\u03C5",phi:"\u03D5",varphi:"\u03C6",chi:"\u03C7",psi:"\u03C8",omega:"\u03C9",Gamma:"\u0393",Delta:"\u0394",Theta:"\u0398",Lambda:"\u039B",Xi:"\u039E",Pi:"\u03A0",Sigma:"\u03A3",Upsilon:"\u03A5",Phi:"\u03A6",Psi:"\u03A8",Omega:"\u03A9",pm:"\xB1",mp:"\u2213",times:"\xD7",div:"\xF7",cdot:"\xB7",ast:"\u2217",star:"\u22C6",circ:"\u2218",bullet:"\u2022",oplus:"\u2295",ominus:"\u2296",otimes:"\u2297",oslash:"\u2298",odot:"\u2299",bigcirc:"\u25CB",dagger:"\u2020",ddagger:"\u2021",amalg:"\u2A3F",uplus:"\u228E",sqcap:"\u2293",sqcup:"\u2294",bowtie:"\u22C8",Join:"\u22C8",ltimes:"\u22C9",rtimes:"\u22CA",leftouterjoin:"\u27D5",rightouterjoin:"\u27D6",fullouterjoin:"\u27D7",triangleleft:"\u25C1",triangleright:"\u25B7",wr:"\u2240",cap:"\u2229",cup:"\u222A",bigcap:"\u22C2",bigcup:"\u22C3",bigwedge:"\u22C0",bigvee:"\u22C1",bigsqcup:"\u2A06",biguplus:"\u2A04",bigoplus:"\u2A01",bigotimes:"\u2A02",bigodot:"\u2A00",setminus:"\u2216",in:"\u2208",notin:"\u2209",ni:"\u220B",subset:"\u2282",supset:"\u2283",subseteq:"\u2286",supseteq:"\u2287",sqsubset:"\u228F",sqsupset:"\u2290",sqsubseteq:"\u2291",sqsupseteq:"\u2292",prec:"\u227A",preceq:"\u227C",succ:"\u227B",succeq:"\u227D",ll:"\u226A",gg:"\u226B",le:"\u2264",leq:"\u2264",leqslant:"\u2264",ge:"\u2265",geq:"\u2265",geqslant:"\u2265",ne:"\u2260",neq:"\u2260",equiv:"\u2261",approx:"\u2248",sim:"\u223C",simeq:"\u2243",cong:"\u2245",asymp:"\u224D",doteq:"\u2250",propto:"\u221D",parallel:"\u2225",perp:"\u22A5",mid:"\u2223",vdash:"\u22A2",dashv:"\u22A3",models:"\u22A8",Vdash:"\u22A9",Vvdash:"\u22AA",nvdash:"\u22AC",nvDash:"\u22AD",forall:"\u2200",exists:"\u2203",nexists:"\u2204",neg:"\xAC",land:"\u2227",wedge:"\u2227",lor:"\u2228",vee:"\u2228",to:"\u2192",rightarrow:"\u2192",longrightarrow:"\u2192",leftarrow:"\u2190",longleftarrow:"\u2190",gets:"\u2190",leftrightarrow:"\u2194",longleftrightarrow:"\u2194",hookleftarrow:"\u21A9",hookrightarrow:"\u21AA",twoheadleftarrow:"\u219E",twoheadrightarrow:"\u21A0",leftharpoonup:"\u21BC",leftharpoondown:"\u21BD",rightharpoonup:"\u21C0",rightharpoondown:"\u21C1",rightleftharpoons:"\u21CC",leftrightharpoons:"\u21CB",nearrow:"\u2197",searrow:"\u2198",swarrow:"\u2199",nwarrow:"\u2196",rightsquigarrow:"\u21DD",leadsto:"\u21DD",Rightarrow:"\u21D2",Longrightarrow:"\u21D2",Leftarrow:"\u21D0",Longleftarrow:"\u21D0",Leftrightarrow:"\u21D4",Longleftrightarrow:"\u21D4",implies:"\u21D2",iff:"\u21D4",mapsto:"\u21A6",longmapsto:"\u21A6",uparrow:"\u2191",downarrow:"\u2193",partial:"\u2202",nabla:"\u2207",int:"\u222B",iint:"\u222C",iiint:"\u222D",oint:"\u222E",sum:"\u2211",prod:"\u220F",coprod:"\u2210",infty:"\u221E",emptyset:"\u2205",varnothing:"\u2205",angle:"\u2220",therefore:"\u2234",because:"\u2235",aleph:"\u2135",beth:"\u2136",gimel:"\u2137",daleth:"\u2138",top:"\u22A4",bot:"\u22A5",triangle:"\u25B3",square:"\u25A1",lozenge:"\u25CA",checkmark:"\u2713",complement:"\u2201",wp:"\u2118",prime:"\u2032",ldots:"\u2026",dots:"\u2026",cdots:"\u22EF",vdots:"\u22EE",ddots:"\u22F1",ell:"\u2113",hbar:"\u210F",Im:"\u2111",Re:"\u211C",langle:"\u27E8",rangle:"\u27E9",vert:"|",lvert:"|",rvert:"|",Vert:"\u2016",lVert:"\u2016",rVert:"\u2016",lbrace:"{",rbrace:"}",backslash:"\\",lfloor:"\u230A",rfloor:"\u230B",lceil:"\u2308",rceil:"\u2309",colon:":"},Ia=new Set(["arccos","arcsin","arctan","arg","cos","cosh","cot","coth","csc","deg","det","dim","exp","gcd","hom","inf","ker","lg","lim","liminf","limsup","ln","log","max","min","Pr","sec","sin","sinh","sup","tan","tanh"]),La=new Set(["argmax","argmin","inf","injlim","lim","liminf","limsup","max","min","projlim","sup"]),ka=new Set(["bigcap","bigcup","bigodot","bigoplus","bigotimes","bigsqcup","biguplus","bigvee","bigwedge","coprod","int","iint","iiint","oint","prod","sum"]),Aa=new Set(["Leftarrow","Leftrightarrow","Longleftarrow","Longleftrightarrow","Longrightarrow","Rightarrow","Join","Vdash","Vvdash","approx","asymp","bowtie","cong","dashv","fullouterjoin","doteq","downarrow","equiv","ge","geq","geqslant","gets","gg","hookleftarrow","hookrightarrow","iff","implies","in","leadsto","le","leftarrow","leftharpoondown","leftharpoonup","leftrightarrow","leftrightharpoons","leftouterjoin","leq","leqslant","ll","longleftarrow","longleftrightarrow","longmapsto","longrightarrow","ltimes","mapsto","mid","models","ne","nearrow","neq","ni","notin","nvdash","nvDash","nwarrow","parallel","perp","prec","preceq","propto","rightharpoondown","rightharpoonup","rightleftharpoons","rightouterjoin","rightarrow","rightsquigarrow","rtimes","searrow","sim","simeq","sqsubset","sqsubseteq","sqsupset","sqsupseteq","subset","subseteq","succ","succeq","supset","supseteq","swarrow","to","triangleleft","triangleright","twoheadleftarrow","twoheadrightarrow","uparrow","vdash"]),Ra={"<":"\u226E",">":"\u226F","=":"\u2260","\u2208":"\u2209","\u220B":"\u220C","\u2223":"\u2224","\u2225":"\u2226","\u223C":"\u2241","\u2243":"\u2244","\u2245":"\u2247","\u2248":"\u2249","\u2261":"\u2262","\u2264":"\u2270","\u2265":"\u2271","\u227A":"\u2280","\u227B":"\u2281","\u2282":"\u2284","\u2283":"\u2285","\u2286":"\u2288","\u2287":"\u2289","\u22A2":"\u22AC","\u22A8":"\u22AD","\u2194":"\u21AE","\u2190":"\u219A","\u2192":"\u219B","\u21D2":"\u21CF","\u21D0":"\u21CD","\u21D4":"\u21CE","\u227C":"\u22E0","\u227D":"\u22E1"},Ea={C:"\u2102",H:"\u210D",N:"\u2115",P:"\u2119",Q:"\u211A",R:"\u211D",Z:"\u2124"},Pa={0:"\u2070",1:"\xB9",2:"\xB2",3:"\xB3",4:"\u2074",5:"\u2075",6:"\u2076",7:"\u2077",8:"\u2078",9:"\u2079","+":"\u207A","-":"\u207B","=":"\u207C","(":"\u207D",")":"\u207E",a:"\u1D43",b:"\u1D47",c:"\u1D9C",d:"\u1D48",e:"\u1D49",f:"\u1DA0",g:"\u1D4D",h:"\u02B0",i:"\u2071",j:"\u02B2",k:"\u1D4F",l:"\u02E1",m:"\u1D50",n:"\u207F",o:"\u1D52",p:"\u1D56",r:"\u02B3",s:"\u02E2",t:"\u1D57",u:"\u1D58",v:"\u1D5B",w:"\u02B7",x:"\u02E3",y:"\u02B8",z:"\u1DBB"},Oa={0:"\u2080",1:"\u2081",2:"\u2082",3:"\u2083",4:"\u2084",5:"\u2085",6:"\u2086",7:"\u2087",8:"\u2088",9:"\u2089","+":"\u208A","-":"\u208B","=":"\u208C","(":"\u208D",")":"\u208E",a:"\u2090",e:"\u2091",h:"\u2095",i:"\u1D62",j:"\u2C7C",k:"\u2096",l:"\u2097",m:"\u2098",n:"\u2099",o:"\u2092",p:"\u209A",r:"\u1D63",s:"\u209B",t:"\u209C",u:"\u1D64",v:"\u1D65",x:"\u2093"},$a=new Set([",",":",";"," ",">","enspace","enskip","medspace","quad","qquad","thickspace","thinspace"]),_a=new Set(["!","negmedspace","negthickspace","negthinspace"]),Yn="\0",Ka=new Set(["bf","cal","it","rm","sf","sl","tt"]),Ba=new Set(["displaystyle","limits","nolimits","scriptstyle","scriptscriptstyle","textstyle"]),Da=new Set(["big","Big","bigg","Bigg","bigl","Bigl","biggl","Biggl","bigr","Bigr","biggr","Biggr"]),Na=new Set(["emph","mathcal","mathbf","mathfrak","mathit","mathrm","mathnormal","mathscr","mathsf","mathtt","mathup","mbox","overbrace","pmb","smash","substack","text","textbf","textit","textmd","textnormal","textrm","textsc","textsf","textsl","texttt","textup","underbrace","bm","boldsymbol"]),Fa={acute:"\u0301",bar:"\u0305",breve:"\u0306",check:"\u030C",ddot:"\u0308",dot:"\u0307",grave:"\u0300",hat:"\u0302",mathring:"\u030A",overleftarrow:"\u20D6",overleftrightarrow:"\u20E1",overline:"\u0305",overrightarrow:"\u20D7",tilde:"\u0303",underline:"\u0332",vec:"\u20D7",widehat:"\u0302",widetilde:"\u0303"};function Wa(i,t){let e="";for(let r of i){let n=t[r];if(n===void 0)return;e+=n;}return e}function jn(i){return i.trim().replace(/\s*([=+-])\s*/g,"$1")}function ii(i,t){return Wa(jn(i),t==="sub"?Oa:Pa)}function Ie(i,t){i=jn(i);let e=ii(i,t);if(e!==void 0)return e;let r=t==="sub"?"_":"^";return Array.from(i).length===1||t==="sub"&&/^[A-Za-z]+$/.test(i)?`${r}${i}`:`${r}(${i})`}function Va(i,t){i=i.trim(),t=t.trim();let e=/^[\p{L}\p{N}.]+$/u.test(i),r=/^[\p{N}.]+$/u.test(t)||Array.from(t).length===1;return `${e?i:`(${i})`}/${r?t:`(${t})`}`}function er(i,t="\u221A"){return i=i.trim(),/^[\p{L}\p{N}.]+$/u.test(i)?`${t}${i}`:`${t}(${i})`}var Xn="\u{F0004}",ke="\u{F0005}",Ha=/(?<=[\p{L}\p{N})\]}\u{f0001}])\u{f0004}/gu,Ua=/\u{f0005}(?=[\p{L}\p{N}√\u{f0000}])/gu;function Le(i){return i.replace(Ha," ").replaceAll(Xn,"").replace(Ua," ").replaceAll(ke,"").split(`
21
+ `);if(e.length===1){let r=this.state.lines[this.state.cursorLine]||"",n=t.length,s=r.slice(0,this.state.cursorCol-n),o=r.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=s+o,this.setCursorCol(this.state.cursorCol-n);}else {let r=this.state.cursorLine-(e.length-1),n=(this.state.lines[r]||"").length-(e[0]||"").length,s=(this.state.lines[this.state.cursorLine]||"").slice(this.state.cursorCol),o=(this.state.lines[r]||"").slice(0,n);this.state.lines.splice(r,e.length,o+s),this.state.cursorLine=r,this.setCursorCol(n);}this.onChange&&this.onChange(this.getText());}pushUndoSnapshot(){this.undoStack.push({state:this.state,pastes:this.pastes,pasteCounter:this.pasteCounter});}undo(){this.exitHistoryBrowsing();let t=this.undoStack.pop();t&&(Object.assign(this.state,t.state),this.pastes=t.pastes,this.pasteCounter=t.pasteCounter,this.lastAction=null,this.preferredVisualCol=null,this.snappedFromCursorCol=null,this.onChange&&this.onChange(this.getText()));}jumpToChar(t,e){this.lastAction=null;let r=e==="forward",n=this.state.lines,s=r?n.length:-1,o=r?1:-1;for(let l=this.state.cursorLine;l!==s;l+=o){let a=n[l]||"",c=l===this.state.cursorLine,h;if(c)if(r)h=this.state.cursorCol+1;else {let p=this.state.cursorCol-1;if(p<0)continue;h=p;}let u=r?a.indexOf(t,h):a.lastIndexOf(t,h);if(u!==-1){this.state.cursorLine=l,this.setCursorCol(u);return}}}moveWordForwards(){this.lastAction=null;let t=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>=t.length){this.state.cursorLine<this.state.lines.length-1&&(this.state.cursorLine++,this.setCursorCol(0));return}this.setCursorCol(Xt(t,this.state.cursorCol,{segment:e=>this.segment(e,"word"),isAtomicSegment:Ye}));}isSlashMenuAllowed(){return this.state.cursorLine===0}isAtStartOfMessage(){if(!this.isSlashMenuAllowed())return false;let e=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);return e.trim()===""||e.trim()==="/"}isInSlashCommandContext(t){return this.isSlashMenuAllowed()&&t.trimStart().startsWith("/")}getBestAutocompleteMatchIndex(t,e){if(!e)return -1;let r=e.startsWith("/")?e.slice(1):e;if(!r)return -1;let n=-1;for(let s=0;s<t.length;s++){let o=t[s].value;if(o===r)return s;n===-1&&o.startsWith(r)&&(n=s);}return n}createAutocompleteList(t,e){let r=t.startsWith("/")?ca:void 0,n=new ut(e,this.autocompleteMaxVisible,this.theme.selectList,r);return n.onSelect=s=>{if(!this.autocompleteProvider)return;this.pushUndoSnapshot(),this.lastAction=null;let o=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,s,this.autocompletePrefix);this.state.lines=o.lines,this.state.cursorLine=o.cursorLine,this.setCursorCol(o.cursorCol),this.cancelAutocomplete(),this.onChange?.(this.getText()),_n(s)&&this.tryTriggerAutocomplete();},n}tryTriggerAutocomplete(t=false){this.requestAutocomplete({force:false,explicitTab:t});}handleTabCompletion(){if(!this.autocompleteProvider)return;let e=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(e)&&!e.trimStart().includes(" ")?this.handleSlashCommandCompletion():this.forceFileAutocomplete(true);}handleSlashCommandCompletion(){this.requestAutocomplete({force:false,explicitTab:true});}forceFileAutocomplete(t=false){this.requestAutocomplete({force:true,explicitTab:t});}requestAutocomplete(t){if(!this.autocompleteProvider||t.force&&!(!this.autocompleteProvider.shouldTriggerFileCompletion||this.autocompleteProvider.shouldTriggerFileCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol)))return;this.cancelAutocompleteRequest();let e=++this.autocompleteStartToken,r=this.getAutocompleteDebounceMs(t);if(r>0){this.autocompleteDebounceTimer=setTimeout(()=>{this.autocompleteDebounceTimer=void 0,this.startAutocompleteRequest(e,t);},r);return}this.startAutocompleteRequest(e,t);}async startAutocompleteRequest(t,e){let r=this.autocompleteRequestTask;this.autocompleteRequestTask=(async()=>{if(await r,t!==this.autocompleteStartToken||!this.autocompleteProvider)return;let n=new AbortController;this.autocompleteAbort=n;let s=++this.autocompleteRequestId,o=this.getText(),l=this.state.cursorLine,a=this.state.cursorCol;await this.runAutocompleteRequest(s,n,o,l,a,e);})(),await this.autocompleteRequestTask;}setAutocompleteTriggerCharacters(t){let e=[...Bn];for(let r of t)r.length!==1||r==="/"||X(r)||e.includes(r)||e.push(r);this.autocompleteTriggerCharacters=e,this.autocompleteTriggerPattern=Dn(e),this.autocompleteDebouncePattern=Nn(e);}getAutocompleteDebounceMs(t){if(t.explicitTab||t.force)return 0;let r=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);return this.autocompleteDebouncePattern.test(r)?ua:0}async runAutocompleteRequest(t,e,r,n,s,o){if(!this.autocompleteProvider)return;let l=await this.autocompleteProvider.getSuggestions(this.state.lines,this.state.cursorLine,this.state.cursorCol,{signal:e.signal,force:o.force});if(this.isAutocompleteRequestCurrent(t,e,r,n,s)){if(this.autocompleteAbort=void 0,!l||!Array.isArray(l.items)||l.items.length===0){this.cancelAutocomplete(),this.tui.requestRender();return}if(o.force&&o.explicitTab&&l.items.length===1){let a=l.items[0];this.pushUndoSnapshot(),this.lastAction=null;let c=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,a,l.prefix);this.state.lines=c.lines,this.state.cursorLine=c.cursorLine,this.setCursorCol(c.cursorCol),this.onChange&&this.onChange(this.getText()),this.tui.requestRender();return}this.applyAutocompleteSuggestions(l,o.force?"force":"regular"),this.tui.requestRender();}}isAutocompleteRequestCurrent(t,e,r,n,s){return !e.signal.aborted&&t===this.autocompleteRequestId&&this.getText()===r&&this.state.cursorLine===n&&this.state.cursorCol===s}applyAutocompleteSuggestions(t,e){this.autocompletePrefix=t.prefix,this.autocompleteList=this.createAutocompleteList(t.prefix,t.items);let r=this.getBestAutocompleteMatchIndex(t.items,t.prefix);r>=0&&this.autocompleteList.setSelectedIndex(r),this.autocompleteState=e;}cancelAutocompleteRequest(){this.autocompleteStartToken+=1,this.autocompleteDebounceTimer&&(clearTimeout(this.autocompleteDebounceTimer),this.autocompleteDebounceTimer=void 0),this.autocompleteAbort?.abort(),this.autocompleteAbort=void 0;}clearAutocompleteUi(){this.autocompleteState=null,this.autocompleteList=void 0,this.autocompletePrefix="";}cancelAutocomplete(){this.cancelAutocompleteRequest(),this.clearAutocompleteUi();}isShowingAutocomplete(){return this.autocompleteState!==null}updateAutocomplete(){!this.autocompleteState||!this.autocompleteProvider||this.requestAutocomplete({force:this.autocompleteState==="force",explicitTab:false});}};var je=Symbol.for("@earendil-works/pi-tui/layout-node");function Jt(i){let t=i;return typeof t[je]=="function"?t[je]():void 0}function ha(i){return !("render"in i)}function ht(i,t){return i===void 0||!Number.isFinite(i)?t:Math.max(0,Math.floor(i))}var Xe=class extends se{constructor(e=[],r={}){super();d(this,"entries",[]);d(this,"gap");d(this,"align");this.gap=ht(r.gap,0),this.align=r.align??"stretch";for(let n of e)ha(n)?this.addChild(n.component,n):this.addChild(n);}addChild(e,r={}){super.addChild(e),this.entries.push({component:e,...r.basis===void 0?{}:{basis:r.basis},...r.grow===void 0?{}:{grow:ht(r.grow,0)},...r.shrink===void 0?{}:{shrink:ht(r.shrink,1)},...r.minSize===void 0?{}:{minSize:ht(r.minSize,0)},...r.maxSize===void 0?{}:{maxSize:ht(r.maxSize,Number.MAX_SAFE_INTEGER)},...r.visible===void 0?{}:{visible:r.visible}});}removeChild(e){super.removeChild(e);let r=this.entries.findIndex(n=>n.component===e);r!==-1&&this.entries.splice(r,1);}clear(){super.clear(),this.entries.length=0;}[je](){return {type:this.layoutType,entries:this.entries,gap:this.gap,align:this.align}}};function Qe(i,t){return i.filter(e=>e.visible?.(t)??true)}function da(i,t){let e=Math.max(0,Math.floor(t.minSize??0)),r=Math.max(e,Math.floor(t.maxSize??Number.MAX_SAFE_INTEGER));return Math.max(e,Math.min(r,Math.max(0,Math.floor(i))))}function qn(i,t,e,r){let n=e;for(;n>0;){let s=t.map((a,c)=>({entry:a,index:c})).filter(({entry:a,index:c})=>r==="grow"?(a.grow??0)>0&&i[c]<(a.maxSize??Number.MAX_SAFE_INTEGER):(a.shrink??1)>0&&i[c]>(a.minSize??0));if(s.length===0)return;let o=s.reduce((a,{entry:c,index:h})=>a+(r==="grow"?c.grow??0:(c.shrink??1)*Math.max(1,i[h])),0),l=0;for(let{entry:a,index:c}of s){if(n<=0)break;let h=r==="grow"?a.grow??0:(a.shrink??1)*Math.max(1,i[c]),u=Math.max(1,Math.floor(n*h/o)),p=r==="grow"?(a.maxSize??Number.MAX_SAFE_INTEGER)-i[c]:i[c]-(a.minSize??0),f=Math.min(n,u,p);f<=0||(i[c]=i[c]+(r==="grow"?f:-f),n-=f,l+=f);}if(l===0)return}}function Ce(i,t,e,r){let n=i.map((l,a)=>da(l.basis===void 0||l.basis==="auto"?t[a]??0:l.basis,l));if(e===void 0)return n;let s=Math.max(0,Math.floor(e)-Math.max(0,i.length-1)*r),o=n.reduce((l,a)=>l+a,0);return o<s?qn(n,i,s-o,"grow"):o>s&&qn(n,i,o-s,"shrink"),n}var Zr=class extends Xe{constructor(e=[],r={}){super(e,r);d(this,"layoutType","hstack");}render(e){let r=Math.max(1,e),n={width:r,height:Number.MAX_SAFE_INTEGER},s=Qe(this.entries,n);if(s.length===0)return [];let o=s.map(p=>p.component.render(r).reduce((b,m)=>Math.max(b,S(m)),0)),l=Ce(s,o,r,this.gap),a=s.map((p,f)=>l[f]===0?[]:p.component.render(l[f])),c=a.reduce((p,f)=>Math.max(p,f.length),0),h=Array.from({length:c},()=>""),u=0;for(let p=0;p<a.length;p++){let f=a[p],b=l[p],m=0;this.align==="center"?m=Math.floor((c-f.length)/2):this.align==="end"&&(m=c-f.length);for(let g=0;g<f.length;g++){let y=g+m;y<0||y>=h.length||(h[y]=he(h[y],f[g],u,b,r));}u+=b+this.gap;}return h}};var ei,we=new Map;function pa(i){ei=i,we.clear();}function fa(i,t){if(!ei)return null;let e=we.get(i),r=e===void 0?ei(i,t):e;return we.delete(i),we.set(i,r),we.size>32&&we.delete(we.keys().next().value),r}var ti=class{constructor(t,e,r,n={},s){d(this,"base64Data");d(this,"mimeType");d(this,"dimensions");d(this,"theme");d(this,"options");d(this,"imageId");d(this,"pngData");d(this,"cachedLines");d(this,"cachedWidth");this.base64Data=t,this.mimeType=e,this.theme=r,this.options=n,this.dimensions=s||Wr(t,e)||{widthPx:800,heightPx:600},this.imageId=n.imageId;}getImageId(){return this.imageId}invalidate(){this.cachedLines=void 0,this.cachedWidth=void 0;}render(t){if(this.cachedLines&&this.cachedWidth===t)return this.cachedLines;let e=Math.max(1,Math.min(t-2,this.options.maxWidthCells??60)),r=Dt(),n=Math.max(1,Math.ceil(e*r.widthPx/r.heightPx)),s=this.options.maxHeightCells??n,o=te(),l=this.base64Data,a=this.dimensions;o.images==="kitty"&&this.mimeType!=="image/png"&&(this.pngData??(this.pngData=fa(this.base64Data,this.mimeType)??void 0),l=this.pngData??null,l&&(a=Wt(l)??a));let c;if(o.images&&l){o.images==="kitty"&&this.imageId===void 0&&(this.imageId=Br());let h=Vr(l,a,{maxWidthCells:e,maxHeightCells:s,imageId:this.imageId,moveCursor:false});if(h)if(h.imageId&&(this.imageId=h.imageId),o.images==="kitty"){c=[h.sequence];for(let u=0;u<h.rows-1;u++)c.push("");}else {c=[];for(let f=0;f<h.rows-1;f++)c.push("");let u=h.rows-1,p=u>0?`\x1B[${u}A`:"";c.push(p+h.sequence);}else {let u=Ht(this.mimeType,this.dimensions,this.options.filename);c=[N(this.theme.fallbackColor(u),t)];}}else {let h=Ht(this.mimeType,this.dimensions,this.options.filename);c=[N(this.theme.fallbackColor(h),t)];}return this.cachedLines=c,this.cachedWidth=t,c}};var Te=Pe(),Me=class{constructor(t={}){d(this,"value","");d(this,"cursor",0);d(this,"prompt");d(this,"placeholder");d(this,"placeholderStyle");d(this,"renderedStartColumn",0);d(this,"onSubmit");d(this,"onEscape");d(this,"focused",false);d(this,"pasteBuffer","");d(this,"isInPaste",false);d(this,"killRing",new Ge);d(this,"lastAction",null);d(this,"undoStack",new ze);this.prompt=t.prompt??"> ",this.placeholder=t.placeholder??"",this.placeholderStyle=t.placeholderStyle??(e=>e);}getValue(){return this.value}setValue(t){this.value=t,this.cursor=Math.min(this.cursor,t.length);}handleInput(t){if(t.includes("\x1B[200~")&&(this.isInPaste=true,this.pasteBuffer="",t=t.replace("\x1B[200~","")),this.isInPaste){this.pasteBuffer+=t;let s=this.pasteBuffer.indexOf("\x1B[201~");if(s!==-1){let o=this.pasteBuffer.substring(0,s);this.handlePaste(o),this.isInPaste=false;let l=this.pasteBuffer.substring(s+6);this.pasteBuffer="",l&&this.handleInput(l);}return}let e=G();if(e.matches(t,"tui.select.cancel")){this.onEscape&&this.onEscape();return}if(e.matches(t,"tui.editor.undo")){this.undo();return}if(e.matches(t,"tui.input.submit")||t===`
22
+ `){this.onSubmit&&this.onSubmit(this.value);return}if(e.matches(t,"tui.editor.deleteCharBackward")){this.handleBackspace();return}if(e.matches(t,"tui.editor.deleteCharForward")){this.handleForwardDelete();return}if(e.matches(t,"tui.editor.deleteWordBackward")){this.deleteWordBackwards();return}if(e.matches(t,"tui.editor.deleteWordForward")){this.deleteWordForward();return}if(e.matches(t,"tui.editor.deleteToLineStart")){this.deleteToLineStart();return}if(e.matches(t,"tui.editor.deleteToLineEnd")){this.deleteToLineEnd();return}if(e.matches(t,"tui.editor.yank")){this.yank();return}if(e.matches(t,"tui.editor.yankPop")){this.yankPop();return}if(e.matches(t,"tui.editor.cursorLeft")){if(this.lastAction=null,this.cursor>0){let s=this.value.slice(0,this.cursor),o=[...Te.segment(s)],l=o[o.length-1];this.cursor-=l?l.segment.length:1;}return}if(e.matches(t,"tui.editor.cursorRight")){if(this.lastAction=null,this.cursor<this.value.length){let s=this.value.slice(this.cursor),l=[...Te.segment(s)][0];this.cursor+=l?l.segment.length:1;}return}if(e.matches(t,"tui.editor.cursorLineStart")){this.lastAction=null,this.cursor=0;return}if(e.matches(t,"tui.editor.cursorLineEnd")){this.lastAction=null,this.cursor=this.value.length;return}if(e.matches(t,"tui.editor.cursorWordLeft")){this.moveWordBackwards();return}if(e.matches(t,"tui.editor.cursorWordRight")){this.moveWordForwards();return}let r=_t(t);if(r!==void 0){this.insertCharacter(r);return}[...t].some(s=>{let o=s.charCodeAt(0);return o<32||o===127||o>=128&&o<=159})||this.insertCharacter(t);}handleMouse(t){if(t.type!=="press"||t.button!=="left"||t.y!==0)return;let e=Math.max(0,t.x-2),r=this.renderedStartColumn+e,n=0;this.cursor=this.value.length;for(let s of Te.segment(this.value)){let o=n+S(s.segment);if(r<o){this.cursor=s.index;break}n=o;}return this.lastAction=null,{handled:true,focus:true}}insertCharacter(t){(X(t)||this.lastAction!=="type-word")&&this.pushUndo(),this.lastAction="type-word",this.value=this.value.slice(0,this.cursor)+t+this.value.slice(this.cursor),this.cursor+=t.length;}handleBackspace(){if(this.lastAction=null,this.cursor>0){this.pushUndo();let t=this.value.slice(0,this.cursor),e=[...Te.segment(t)],r=e[e.length-1],n=r?r.segment.length:1;this.value=this.value.slice(0,this.cursor-n)+this.value.slice(this.cursor),this.cursor-=n;}}handleForwardDelete(){if(this.lastAction=null,this.cursor<this.value.length){this.pushUndo();let t=this.value.slice(this.cursor),r=[...Te.segment(t)][0],n=r?r.segment.length:1;this.value=this.value.slice(0,this.cursor)+this.value.slice(this.cursor+n);}}deleteToLineStart(){if(this.cursor===0)return;this.pushUndo();let t=this.value.slice(0,this.cursor);this.killRing.push(t,{prepend:true,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.value=this.value.slice(this.cursor),this.cursor=0;}deleteToLineEnd(){if(this.cursor>=this.value.length)return;this.pushUndo();let t=this.value.slice(this.cursor);this.killRing.push(t,{prepend:false,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.value=this.value.slice(0,this.cursor);}deleteWordBackwards(){if(this.cursor===0)return;let t=this.lastAction==="kill";this.pushUndo();let e=this.cursor;this.moveWordBackwards();let r=this.cursor;this.cursor=e;let n=this.value.slice(r,this.cursor);this.killRing.push(n,{prepend:true,accumulate:t}),this.lastAction="kill",this.value=this.value.slice(0,r)+this.value.slice(this.cursor),this.cursor=r;}deleteWordForward(){if(this.cursor>=this.value.length)return;let t=this.lastAction==="kill";this.pushUndo();let e=this.cursor;this.moveWordForwards();let r=this.cursor;this.cursor=e;let n=this.value.slice(this.cursor,r);this.killRing.push(n,{prepend:false,accumulate:t}),this.lastAction="kill",this.value=this.value.slice(0,this.cursor)+this.value.slice(r);}yank(){let t=this.killRing.peek();t&&(this.pushUndo(),this.value=this.value.slice(0,this.cursor)+t+this.value.slice(this.cursor),this.cursor+=t.length,this.lastAction="yank");}yankPop(){if(this.lastAction!=="yank"||this.killRing.length<=1)return;this.pushUndo();let t=this.killRing.peek()||"";this.value=this.value.slice(0,this.cursor-t.length)+this.value.slice(this.cursor),this.cursor-=t.length,this.killRing.rotate();let e=this.killRing.peek()||"";this.value=this.value.slice(0,this.cursor)+e+this.value.slice(this.cursor),this.cursor+=e.length,this.lastAction="yank";}pushUndo(){this.undoStack.push({value:this.value,cursor:this.cursor});}undo(){let t=this.undoStack.pop();t&&(this.value=t.value,this.cursor=t.cursor,this.lastAction=null);}moveWordBackwards(){this.cursor!==0&&(this.lastAction=null,this.cursor=jt(this.value,this.cursor));}moveWordForwards(){this.cursor>=this.value.length||(this.lastAction=null,this.cursor=Xt(this.value,this.cursor));}handlePaste(t){this.lastAction=null,this.pushUndo();let e=t.replace(/\r\n/g,"").replace(/\r/g,"").replace(/\n/g,"").replace(/\t/g," ");this.value=this.value.slice(0,this.cursor)+e+this.value.slice(this.cursor),this.cursor+=e.length;}invalidate(){}render(t){let e=t-S(this.prompt);if(e<=0)return [N(this.prompt,t,"")];if(this.value.length===0&&this.placeholder){let y=N(this.placeholder,e,""),x=[...Te.segment(y)][0]?.segment??" ",w=y.slice(x.length),I=this.focused?re:"",T=Se(this.placeholderStyle(x)),L=I+T+this.placeholderStyle(w),M=" ".repeat(Math.max(0,e-S(L)));return [this.prompt+L+M]}let r="",n=this.cursor;this.renderedStartColumn=0;let s=S(this.value);if(s<e)r=this.value;else {let y=this.cursor===this.value.length?e-1:e,v=S(this.value.slice(0,this.cursor));if(y>0){let x=Math.floor(y/2),w=0;v<x?w=0:v>s-x?w=Math.max(0,s-y):w=Math.max(0,v-x),this.renderedStartColumn=w,r=V(this.value,w,y,true),n=V(this.value,w,Math.max(0,v-w),true).length;}else r="",n=0;}let l=[...Te.segment(r.slice(n))][0],a=r.slice(0,n),c=l?.segment??" ",h=r.slice(n+c.length),u=this.focused?re:"",p=Se(c),f=a+u+p+h,b=S(f),m=" ".repeat(Math.max(0,e-b));return [this.prompt+f+m]}};var ma={alpha:"\u03B1",beta:"\u03B2",gamma:"\u03B3",delta:"\u03B4",epsilon:"\u03F5",varepsilon:"\u03B5",zeta:"\u03B6",eta:"\u03B7",theta:"\u03B8",vartheta:"\u03D1",iota:"\u03B9",kappa:"\u03BA",varkappa:"\u03F0",lambda:"\u03BB",mu:"\u03BC",nu:"\u03BD",xi:"\u03BE",pi:"\u03C0",varpi:"\u03D6",rho:"\u03C1",varrho:"\u03F1",sigma:"\u03C3",varsigma:"\u03C2",tau:"\u03C4",upsilon:"\u03C5",phi:"\u03D5",varphi:"\u03C6",chi:"\u03C7",psi:"\u03C8",omega:"\u03C9",Gamma:"\u0393",Delta:"\u0394",Theta:"\u0398",Lambda:"\u039B",Xi:"\u039E",Pi:"\u03A0",Sigma:"\u03A3",Upsilon:"\u03A5",Phi:"\u03A6",Psi:"\u03A8",Omega:"\u03A9",pm:"\xB1",mp:"\u2213",times:"\xD7",div:"\xF7",cdot:"\xB7",ast:"\u2217",star:"\u22C6",circ:"\u2218",bullet:"\u2022",oplus:"\u2295",ominus:"\u2296",otimes:"\u2297",oslash:"\u2298",odot:"\u2299",bigcirc:"\u25CB",dagger:"\u2020",ddagger:"\u2021",amalg:"\u2A3F",uplus:"\u228E",sqcap:"\u2293",sqcup:"\u2294",bowtie:"\u22C8",Join:"\u22C8",ltimes:"\u22C9",rtimes:"\u22CA",leftouterjoin:"\u27D5",rightouterjoin:"\u27D6",fullouterjoin:"\u27D7",triangleleft:"\u25C1",triangleright:"\u25B7",wr:"\u2240",cap:"\u2229",cup:"\u222A",bigcap:"\u22C2",bigcup:"\u22C3",bigwedge:"\u22C0",bigvee:"\u22C1",bigsqcup:"\u2A06",biguplus:"\u2A04",bigoplus:"\u2A01",bigotimes:"\u2A02",bigodot:"\u2A00",setminus:"\u2216",in:"\u2208",notin:"\u2209",ni:"\u220B",subset:"\u2282",supset:"\u2283",subseteq:"\u2286",supseteq:"\u2287",sqsubset:"\u228F",sqsupset:"\u2290",sqsubseteq:"\u2291",sqsupseteq:"\u2292",prec:"\u227A",preceq:"\u227C",succ:"\u227B",succeq:"\u227D",ll:"\u226A",gg:"\u226B",le:"\u2264",leq:"\u2264",leqslant:"\u2264",ge:"\u2265",geq:"\u2265",geqslant:"\u2265",ne:"\u2260",neq:"\u2260",equiv:"\u2261",approx:"\u2248",sim:"\u223C",simeq:"\u2243",cong:"\u2245",asymp:"\u224D",doteq:"\u2250",propto:"\u221D",parallel:"\u2225",perp:"\u22A5",mid:"\u2223",vdash:"\u22A2",dashv:"\u22A3",models:"\u22A8",Vdash:"\u22A9",Vvdash:"\u22AA",nvdash:"\u22AC",nvDash:"\u22AD",forall:"\u2200",exists:"\u2203",nexists:"\u2204",neg:"\xAC",land:"\u2227",wedge:"\u2227",lor:"\u2228",vee:"\u2228",to:"\u2192",rightarrow:"\u2192",longrightarrow:"\u2192",leftarrow:"\u2190",longleftarrow:"\u2190",gets:"\u2190",leftrightarrow:"\u2194",longleftrightarrow:"\u2194",hookleftarrow:"\u21A9",hookrightarrow:"\u21AA",twoheadleftarrow:"\u219E",twoheadrightarrow:"\u21A0",leftharpoonup:"\u21BC",leftharpoondown:"\u21BD",rightharpoonup:"\u21C0",rightharpoondown:"\u21C1",rightleftharpoons:"\u21CC",leftrightharpoons:"\u21CB",nearrow:"\u2197",searrow:"\u2198",swarrow:"\u2199",nwarrow:"\u2196",rightsquigarrow:"\u21DD",leadsto:"\u21DD",Rightarrow:"\u21D2",Longrightarrow:"\u21D2",Leftarrow:"\u21D0",Longleftarrow:"\u21D0",Leftrightarrow:"\u21D4",Longleftrightarrow:"\u21D4",implies:"\u21D2",iff:"\u21D4",mapsto:"\u21A6",longmapsto:"\u21A6",uparrow:"\u2191",downarrow:"\u2193",partial:"\u2202",nabla:"\u2207",int:"\u222B",iint:"\u222C",iiint:"\u222D",oint:"\u222E",sum:"\u2211",prod:"\u220F",coprod:"\u2210",infty:"\u221E",emptyset:"\u2205",varnothing:"\u2205",angle:"\u2220",therefore:"\u2234",because:"\u2235",aleph:"\u2135",beth:"\u2136",gimel:"\u2137",daleth:"\u2138",top:"\u22A4",bot:"\u22A5",triangle:"\u25B3",square:"\u25A1",lozenge:"\u25CA",checkmark:"\u2713",complement:"\u2201",wp:"\u2118",prime:"\u2032",ldots:"\u2026",dots:"\u2026",cdots:"\u22EF",vdots:"\u22EE",ddots:"\u22F1",ell:"\u2113",hbar:"\u210F",Im:"\u2111",Re:"\u211C",langle:"\u27E8",rangle:"\u27E9",vert:"|",lvert:"|",rvert:"|",Vert:"\u2016",lVert:"\u2016",rVert:"\u2016",lbrace:"{",rbrace:"}",backslash:"\\",lfloor:"\u230A",rfloor:"\u230B",lceil:"\u2308",rceil:"\u2309",colon:":"},ga=new Set(["arccos","arcsin","arctan","arg","cos","cosh","cot","coth","csc","deg","det","dim","exp","gcd","hom","inf","ker","lg","lim","liminf","limsup","ln","log","max","min","Pr","sec","sin","sinh","sup","tan","tanh"]),ba=new Set(["argmax","argmin","inf","injlim","lim","liminf","limsup","max","min","projlim","sup"]),ya=new Set(["bigcap","bigcup","bigodot","bigoplus","bigotimes","bigsqcup","biguplus","bigvee","bigwedge","coprod","int","iint","iiint","oint","prod","sum"]),xa=new Set(["Leftarrow","Leftrightarrow","Longleftarrow","Longleftrightarrow","Longrightarrow","Rightarrow","Join","Vdash","Vvdash","approx","asymp","bowtie","cong","dashv","fullouterjoin","doteq","downarrow","equiv","ge","geq","geqslant","gets","gg","hookleftarrow","hookrightarrow","iff","implies","in","leadsto","le","leftarrow","leftharpoondown","leftharpoonup","leftrightarrow","leftrightharpoons","leftouterjoin","leq","leqslant","ll","longleftarrow","longleftrightarrow","longmapsto","longrightarrow","ltimes","mapsto","mid","models","ne","nearrow","neq","ni","notin","nvdash","nvDash","nwarrow","parallel","perp","prec","preceq","propto","rightharpoondown","rightharpoonup","rightleftharpoons","rightouterjoin","rightarrow","rightsquigarrow","rtimes","searrow","sim","simeq","sqsubset","sqsubseteq","sqsupset","sqsupseteq","subset","subseteq","succ","succeq","supset","supseteq","swarrow","to","triangleleft","triangleright","twoheadleftarrow","twoheadrightarrow","uparrow","vdash"]),va={"<":"\u226E",">":"\u226F","=":"\u2260","\u2208":"\u2209","\u220B":"\u220C","\u2223":"\u2224","\u2225":"\u2226","\u223C":"\u2241","\u2243":"\u2244","\u2245":"\u2247","\u2248":"\u2249","\u2261":"\u2262","\u2264":"\u2270","\u2265":"\u2271","\u227A":"\u2280","\u227B":"\u2281","\u2282":"\u2284","\u2283":"\u2285","\u2286":"\u2288","\u2287":"\u2289","\u22A2":"\u22AC","\u22A8":"\u22AD","\u2194":"\u21AE","\u2190":"\u219A","\u2192":"\u219B","\u21D2":"\u21CF","\u21D0":"\u21CD","\u21D4":"\u21CE","\u227C":"\u22E0","\u227D":"\u22E1"},Sa={C:"\u2102",H:"\u210D",N:"\u2115",P:"\u2119",Q:"\u211A",R:"\u211D",Z:"\u2124"},Ca={0:"\u2070",1:"\xB9",2:"\xB2",3:"\xB3",4:"\u2074",5:"\u2075",6:"\u2076",7:"\u2077",8:"\u2078",9:"\u2079","+":"\u207A","-":"\u207B","=":"\u207C","(":"\u207D",")":"\u207E",a:"\u1D43",b:"\u1D47",c:"\u1D9C",d:"\u1D48",e:"\u1D49",f:"\u1DA0",g:"\u1D4D",h:"\u02B0",i:"\u2071",j:"\u02B2",k:"\u1D4F",l:"\u02E1",m:"\u1D50",n:"\u207F",o:"\u1D52",p:"\u1D56",r:"\u02B3",s:"\u02E2",t:"\u1D57",u:"\u1D58",v:"\u1D5B",w:"\u02B7",x:"\u02E3",y:"\u02B8",z:"\u1DBB"},wa={0:"\u2080",1:"\u2081",2:"\u2082",3:"\u2083",4:"\u2084",5:"\u2085",6:"\u2086",7:"\u2087",8:"\u2088",9:"\u2089","+":"\u208A","-":"\u208B","=":"\u208C","(":"\u208D",")":"\u208E",a:"\u2090",e:"\u2091",h:"\u2095",i:"\u1D62",j:"\u2C7C",k:"\u2096",l:"\u2097",m:"\u2098",n:"\u2099",o:"\u2092",p:"\u209A",r:"\u1D63",s:"\u209B",t:"\u209C",u:"\u1D64",v:"\u1D65",x:"\u2093"},Ta=new Set([",",":",";"," ",">","enspace","enskip","medspace","quad","qquad","thickspace","thinspace"]),Ma=new Set(["!","negmedspace","negthickspace","negthinspace"]),Gn="\0",Ia=new Set(["bf","cal","it","rm","sf","sl","tt"]),La=new Set(["displaystyle","limits","nolimits","scriptstyle","scriptscriptstyle","textstyle"]),ka=new Set(["big","Big","bigg","Bigg","bigl","Bigl","biggl","Biggl","bigr","Bigr","biggr","Biggr"]),Aa=new Set(["emph","mathcal","mathbf","mathfrak","mathit","mathrm","mathnormal","mathscr","mathsf","mathtt","mathup","mbox","overbrace","pmb","smash","substack","text","textbf","textit","textmd","textnormal","textrm","textsc","textsf","textsl","texttt","textup","underbrace","bm","boldsymbol"]),Ra={acute:"\u0301",bar:"\u0305",breve:"\u0306",check:"\u030C",ddot:"\u0308",dot:"\u0307",grave:"\u0300",hat:"\u0302",mathring:"\u030A",overleftarrow:"\u20D6",overleftrightarrow:"\u20E1",overline:"\u0305",overrightarrow:"\u20D7",tilde:"\u0303",underline:"\u0332",vec:"\u20D7",widehat:"\u0302",widetilde:"\u0303"};function Ea(i,t){let e="";for(let r of i){let n=t[r];if(n===void 0)return;e+=n;}return e}function zn(i){return i.trim().replace(/\s*([=+-])\s*/g,"$1")}function ri(i,t){return Ea(zn(i),t==="sub"?wa:Ca)}function Ie(i,t){i=zn(i);let e=ri(i,t);if(e!==void 0)return e;let r=t==="sub"?"_":"^";return Array.from(i).length===1||t==="sub"&&/^[A-Za-z]+$/.test(i)?`${r}${i}`:`${r}(${i})`}function Pa(i,t){i=i.trim(),t=t.trim();let e=/^[\p{L}\p{N}.]+$/u.test(i),r=/^[\p{N}.]+$/u.test(t)||Array.from(t).length===1;return `${e?i:`(${i})`}/${r?t:`(${t})`}`}function Zt(i,t="\u221A"){return i=i.trim(),/^[\p{L}\p{N}.]+$/u.test(i)?`${t}${i}`:`${t}(${i})`}var Yn="\u{F0004}",ke="\u{F0005}",Oa=/(?<=[\p{L}\p{N})\]}\u{f0001}])\u{f0004}/gu,$a=/\u{f0005}(?=[\p{L}\p{N}√\u{f0000}])/gu;function Le(i){return i.replace(Oa," ").replaceAll(Yn,"").replace($a," ").replaceAll(ke,"").split(`
23
23
  `).map(t=>t.replace(/[ \t]+/g," ").trim()).filter((t,e,r)=>t.length>0||e>0&&e<r.length-1).join(`
24
- `).trim()}var Ze="\u{F0000}",ft="\u{F0001}",qa=/\u{f0000}(\d+)\u{f0001}/gu,Ga=/\u{f0000}(\d+)\u{f0001}$/u,tr="\u{F0002}";function pe(i,t,e=false){let r=Math.max(0,t-S(i)),n=e?Math.floor(r/2):0;return `${" ".repeat(n)}${i}${" ".repeat(r-n)}`}function za(i){if(i.length===0)return {lines:[""],width:0,baseline:0};let t=Math.max(...i.map(n=>n.baseline)),e=Math.max(...i.map(n=>n.lines.length-n.baseline-1)),r=[];for(let n=0;n<=t+e;n++){let s="";for(let o of i){let l=n-t+o.baseline;s+=l>=0&&l<o.lines.length?pe(o.lines[l]??"",o.width):" ".repeat(o.width);}r.push(s.trimEnd());}return {lines:r,width:i.reduce((n,s)=>n+s.width,0),baseline:t}}function mt(i,t){let e=[],r=0;for(let n of i.split(`
25
- `)){let s=[],o=0,l;for(let c of n.matchAll(qa)){let h=c.index,u=t[Number(c[1])];if(u){if(h>o){let p=n.slice(o,h),f=(l?p.trimStart():p).trimEnd(),b=l?.type==="matrix"&&/^\s/.test(p),m=u.type==="matrix"&&/\s$/.test(p),g=f?`${b?" ":""}${f}${m?" ":""}`:b||m?" ":"";s.push({lines:[g],width:S(g),baseline:0});}if(u.type==="fraction"){let p=mt(u.numerator,t),f=mt(u.denominator,t),b=Math.max(p.width,f.width,1),m=b+2;s.push({lines:[...p.lines.map(g=>pe(g,m,true)),` ${"\u2500".repeat(b)} `,...f.lines.map(g=>pe(g,m,true))],width:m,baseline:p.lines.length});}else if(u.type==="operator"){let p=Math.max(S(u.operator),u.lower===void 0?0:S(u.lower),u.upper===void 0?0:S(u.upper)),f=[];u.upper!==void 0&&f.push(`${pe(u.upper,p,true)} `),f.push(`${pe(u.operator,p,true)} `),u.lower!==void 0&&f.push(`${pe(u.lower,p,true)} `),s.push({lines:f,width:p+1,baseline:u.upper===void 0?0:1});}else if(u.type==="script"){let p=u.upper===void 0?void 0:mt(u.upper,t),f=u.lower===void 0?void 0:mt(u.lower,t),b=Math.max(p?.width??0,f?.width??0);s.push({lines:[...p?.lines.map(m=>pe(m,b))??[]," ".repeat(b),...f?.lines.map(m=>pe(m,b))??[]],width:b,baseline:p?.lines.length??0});}else {let p=Math.max(0,...u.lines.map(f=>S(f)));s.push({lines:u.lines.map(f=>pe(f,p)),width:p,baseline:u.baseline});}o=h+c[0].length,l=u;}}if(o<n.length){let c=n.slice(o),h=l?c.trimStart():c,u=l?.type==="matrix"&&/^\s/.test(c)?` ${h}`:h;s.push({lines:[u],width:S(u),baseline:0});}let a=za(s);e.length===0&&(r=a.baseline),e.push(...a.lines);}return {lines:e,width:Math.max(0,...e.map(n=>S(n))),baseline:r}}var ni=class i{constructor(t,e,r){d(this,"source");d(this,"layoutNodes");d(this,"display");d(this,"position",0);d(this,"supported",true);d(this,"stackFractions",true);d(this,"scriptDepth",0);this.source=t,this.layoutNodes=e,this.display=r;}render(){let t=this.parseSequence();if(!(!this.supported||this.position!==this.source.length))return Le(t)}parseSequence(t){let e="";for(;this.position<this.source.length;){let r=this.source[this.position]??"";if(t&&r===t)return this.position++,e;if(r==="}")return this.supported=false,e;if(r==="{"){this.position++,e+=this.parseSequence("}");continue}if(r==="\\"){let n=this.parseCommand();n===Yn?(e=e.trimEnd(),e.endsWith(ke)&&(e=e.slice(0,-ke.length))):e+=n;continue}if(r==="^"||r==="_"){this.position++,e=e.trimEnd();let n=this.parseScripts(r);e.endsWith(ke)?e=`${e.slice(0,-ke.length)}${n}${ke}`:e+=n;continue}if(/\s/.test(r)){e+=this.parseWhitespace();continue}if(r==="="||r==="<"||r===">"){e=`${e.trimEnd()} ${r} `,this.position++;continue}if(r==="&"){this.position++;continue}if(r==="~"){this.position++,e+=" ";continue}if(r==="."){let n=Ga.exec(e),s=n?this.layoutNodes[Number(n[1])]:void 0;if(s?.type==="matrix"){let o=s.lines.length-1;s.lines[o]=`${s.lines[o]??""}${r}`,this.position++;continue}}e+=r,this.position++;}return t&&(this.supported=false),e}parseScripts(t){let e={},r=[],n=p=>{let f=p==="_"?"sub":"sup";this.scriptDepth++;try{e[f]=this.parseRequiredArgument(!1);}finally{this.scriptDepth--;}r.push(f);};n(t);let s=this.position;for(;s<this.source.length&&/\s/.test(this.source[s]??"");)s++;let o=this.source[s];(o==="^"||o==="_")&&o!==t&&(this.position=s+1,n(o));let l=e.sub===void 0?void 0:ii(e.sub,"sub"),a=e.sup===void 0?void 0:ii(e.sup,"sup"),c=![e.sub,e.sup].some(p=>p!==void 0&&(p.includes("/")||!p.includes(Ze)&&Array.from(p).length>1&&!/[A-Z*∗]/.test(p)));if(!(this.display&&c&&(this.scriptDepth>0||e.sub!==void 0&&l===void 0||e.sup!==void 0&&a===void 0)))return r.map(p=>p==="sub"?l??Ie(e.sub??"",p):a??Ie(e.sup??"",p)).join("");let u=this.layoutNodes.push({type:"script",lower:e.sub===void 0?void 0:Le(e.sub),upper:e.sup===void 0?void 0:Le(e.sup)})-1;return `${Ze}${u}${ft}`}parseWhitespace(){for(;this.position<this.source.length&&/\s/.test(this.source[this.position]??"");)this.position++;return " "}parseCommand(){if(this.position++,this.position>=this.source.length)return this.supported=false,"";let t="",e=this.source[this.position]??"";if(e===`
24
+ `).trim()}var Je="\u{F0000}",dt="\u{F0001}",Ka=/\u{f0000}(\d+)\u{f0001}/gu,Ba=/\u{f0000}(\d+)\u{f0001}$/u,er="\u{F0002}";function de(i,t,e=false){let r=Math.max(0,t-S(i)),n=e?Math.floor(r/2):0;return `${" ".repeat(n)}${i}${" ".repeat(r-n)}`}function _a(i){if(i.length===0)return {lines:[""],width:0,baseline:0};let t=Math.max(...i.map(n=>n.baseline)),e=Math.max(...i.map(n=>n.lines.length-n.baseline-1)),r=[];for(let n=0;n<=t+e;n++){let s="";for(let o of i){let l=n-t+o.baseline;s+=l>=0&&l<o.lines.length?de(o.lines[l]??"",o.width):" ".repeat(o.width);}r.push(s.trimEnd());}return {lines:r,width:i.reduce((n,s)=>n+s.width,0),baseline:t}}function pt(i,t){let e=[],r=0;for(let n of i.split(`
25
+ `)){let s=[],o=0,l;for(let c of n.matchAll(Ka)){let h=c.index,u=t[Number(c[1])];if(u){if(h>o){let p=n.slice(o,h),f=(l?p.trimStart():p).trimEnd(),b=l?.type==="matrix"&&/^\s/.test(p),m=u.type==="matrix"&&/\s$/.test(p),g=f?`${b?" ":""}${f}${m?" ":""}`:b||m?" ":"";s.push({lines:[g],width:S(g),baseline:0});}if(u.type==="fraction"){let p=pt(u.numerator,t),f=pt(u.denominator,t),b=Math.max(p.width,f.width,1),m=b+2;s.push({lines:[...p.lines.map(g=>de(g,m,true)),` ${"\u2500".repeat(b)} `,...f.lines.map(g=>de(g,m,true))],width:m,baseline:p.lines.length});}else if(u.type==="operator"){let p=Math.max(S(u.operator),u.lower===void 0?0:S(u.lower),u.upper===void 0?0:S(u.upper)),f=[];u.upper!==void 0&&f.push(`${de(u.upper,p,true)} `),f.push(`${de(u.operator,p,true)} `),u.lower!==void 0&&f.push(`${de(u.lower,p,true)} `),s.push({lines:f,width:p+1,baseline:u.upper===void 0?0:1});}else if(u.type==="script"){let p=u.upper===void 0?void 0:pt(u.upper,t),f=u.lower===void 0?void 0:pt(u.lower,t),b=Math.max(p?.width??0,f?.width??0);s.push({lines:[...p?.lines.map(m=>de(m,b))??[]," ".repeat(b),...f?.lines.map(m=>de(m,b))??[]],width:b,baseline:p?.lines.length??0});}else {let p=Math.max(0,...u.lines.map(f=>S(f)));s.push({lines:u.lines.map(f=>de(f,p)),width:p,baseline:u.baseline});}o=h+c[0].length,l=u;}}if(o<n.length){let c=n.slice(o),h=l?c.trimStart():c,u=l?.type==="matrix"&&/^\s/.test(c)?` ${h}`:h;s.push({lines:[u],width:S(u),baseline:0});}let a=_a(s);e.length===0&&(r=a.baseline),e.push(...a.lines);}return {lines:e,width:Math.max(0,...e.map(n=>S(n))),baseline:r}}var ii=class i{constructor(t,e,r){d(this,"source");d(this,"layoutNodes");d(this,"display");d(this,"position",0);d(this,"supported",true);d(this,"stackFractions",true);d(this,"scriptDepth",0);this.source=t,this.layoutNodes=e,this.display=r;}render(){let t=this.parseSequence();if(!(!this.supported||this.position!==this.source.length))return Le(t)}parseSequence(t){let e="";for(;this.position<this.source.length;){let r=this.source[this.position]??"";if(t&&r===t)return this.position++,e;if(r==="}")return this.supported=false,e;if(r==="{"){this.position++,e+=this.parseSequence("}");continue}if(r==="\\"){let n=this.parseCommand();n===Gn?(e=e.trimEnd(),e.endsWith(ke)&&(e=e.slice(0,-ke.length))):e+=n;continue}if(r==="^"||r==="_"){this.position++,e=e.trimEnd();let n=this.parseScripts(r);e.endsWith(ke)?e=`${e.slice(0,-ke.length)}${n}${ke}`:e+=n;continue}if(/\s/.test(r)){e+=this.parseWhitespace();continue}if(r==="="||r==="<"||r===">"){e=`${e.trimEnd()} ${r} `,this.position++;continue}if(r==="&"){this.position++;continue}if(r==="~"){this.position++,e+=" ";continue}if(r==="."){let n=Ba.exec(e),s=n?this.layoutNodes[Number(n[1])]:void 0;if(s?.type==="matrix"){let o=s.lines.length-1;s.lines[o]=`${s.lines[o]??""}${r}`,this.position++;continue}}e+=r,this.position++;}return t&&(this.supported=false),e}parseScripts(t){let e={},r=[],n=p=>{let f=p==="_"?"sub":"sup";this.scriptDepth++;try{e[f]=this.parseRequiredArgument(!1);}finally{this.scriptDepth--;}r.push(f);};n(t);let s=this.position;for(;s<this.source.length&&/\s/.test(this.source[s]??"");)s++;let o=this.source[s];(o==="^"||o==="_")&&o!==t&&(this.position=s+1,n(o));let l=e.sub===void 0?void 0:ri(e.sub,"sub"),a=e.sup===void 0?void 0:ri(e.sup,"sup"),c=![e.sub,e.sup].some(p=>p!==void 0&&(p.includes("/")||!p.includes(Je)&&Array.from(p).length>1&&!/[A-Z*∗]/.test(p)));if(!(this.display&&c&&(this.scriptDepth>0||e.sub!==void 0&&l===void 0||e.sup!==void 0&&a===void 0)))return r.map(p=>p==="sub"?l??Ie(e.sub??"",p):a??Ie(e.sup??"",p)).join("");let u=this.layoutNodes.push({type:"script",lower:e.sub===void 0?void 0:Le(e.sub),upper:e.sup===void 0?void 0:Le(e.sup)})-1;return `${Je}${u}${dt}`}parseWhitespace(){for(;this.position<this.source.length&&/\s/.test(this.source[this.position]??"");)this.position++;return " "}parseCommand(){if(this.position++,this.position>=this.source.length)return this.supported=false,"";let t="",e=this.source[this.position]??"";if(e===`
26
26
  `||e==="\r")return this.position++,e==="\r"&&this.source[this.position]===`
27
27
  `&&this.position++," ";if(/[A-Za-z]/.test(e)){let s=this.position;for(;this.position<this.source.length&&/[A-Za-z]/.test(this.source[this.position]??"");)this.position++;t=this.source.slice(s,this.position);}else t=e,this.position++;if(t==="\\")return `
28
- `;if($a.has(t))return " ";if(_a.has(t))return Yn;if(Ka.has(t)){for(;this.position<this.source.length&&/\s/.test(this.source[this.position]??"");)this.position++;return ""}if(Ba.has(t))return "";if(t==="{"||t==="}"||t==="$"||t==="%"||t==="#"||t==="_"||t==="&")return t;if(t==="|")return "\u2016";if(t==="not"){let s=this.parseRequiredArgument(false).trim(),o=Ra[s];if(o!==void 0)return ` ${o} `;let l=Array.from(s);return l.length===0?(this.supported=false,""):` ${l[0]}\u0338${l.slice(1).join("")} `}if(La.has(t))return this.parseOperator(t,"bracket",true,true);let r=Ma[t];if(r!==void 0)return ka.has(t)?this.parseOperator(r,"script",true):t==="cdot"||t==="times"||Aa.has(t)?` ${r} `:r;if(Ia.has(t))return `${Xn}${t}${ke}`;if(Da.has(t))return "";if(t==="left"||t==="middle"||t==="right")return this.source[this.position]==="."&&this.position++,"";if(t==="frac"||t==="dfrac"||t==="tfrac"){let s=this.display&&this.stackFractions&&t!=="tfrac",o=this.parseRequiredArgument(!s),l=this.parseRequiredArgument(!s);if(s){let a=this.layoutNodes.push({type:"fraction",numerator:Le(o),denominator:Le(l)})-1;return `${Ze}${a}${ft}`}return Va(o,l)}if(t==="sqrt"){let s=this.parseOptionalArgument()?.trim(),o=this.parseRequiredArgument();return s===void 0||s==="2"?er(o):s==="3"?er(o,"\u221B"):s==="4"?er(o,"\u221C"):`${Ie(s,"sup")}${er(o)}`}if(t==="boxed"||t==="fbox")return `[${this.parseRequiredArgument().trim()}]`;if(t==="binom"||t==="dbinom"||t==="tbinom")return `(${this.parseRequiredArgument()} choose ${this.parseRequiredArgument()})`;let n=Fa[t];if(n!==void 0){let s=this.parseRequiredArgument();return Array.from(s).length===1?`${s}${n}`:`${t}(${s})`}if(t==="mathbb"){let s=this.parseRequiredArgument();return Array.from(s,o=>Ea[o]??o).join("")}if(t==="operatorname"){let s=this.source[this.position]==="*";s&&this.position++;let o=Le(this.parseRequiredArgument()).trim();return this.parseOperator(o,"bracket",s,true)}if(t==="mod"||t==="bmod")return " mod ";if(t==="pmod"||t==="pod"){let s=this.parseRequiredArgument().trim();return t==="pmod"?` (mod ${s})`:` (${s})`}if(t==="overset"||t==="stackrel"){let s=this.parseRequiredArgument();return `${this.parseRequiredArgument().trim()}${Ie(s,"sup")}`}if(t==="underset"){let s=this.parseRequiredArgument();return `${this.parseRequiredArgument().trim()}${Ie(s,"sub")}`}if(Na.has(t)){let s=this.parseRequiredArgument();return t.startsWith("text")||t==="mbox"?s:s.trim()}return t==="begin"?this.parseEnvironment():t==="end"?(this.supported=false,""):(this.supported=false,`\\${t}`)}parseOperator(t,e,r,n=false){let s=r,o=this.position;for(;o<this.source.length&&/[ \t]/.test(this.source[o]??"");)o++;let l=/^\\(limits|nolimits)(?![A-Za-z])/.exec(this.source.slice(o));l&&(s=l[1]==="limits",this.position=o+l[0].length);let a,c;for(;;){let u=this.position;for(;u<this.source.length&&/[ \t]/.test(this.source[u]??"");)u++;let p=this.source[u];if(p!=="_"&&p!=="^")break;this.position=u+1;let f=Le(this.parseRequiredArgument(false)).replaceAll(" ","");p==="_"?(a!==void 0&&(this.supported=false),a=f):(c!==void 0&&(this.supported=false),c=f);}if(this.display&&s&&(a!==void 0||c!==void 0)){let u=this.layoutNodes.push({type:"operator",operator:t,lower:a,upper:c})-1;return `${Ze}${u}${ft}`}let h=t;return a!==void 0&&(h+=e==="bracket"?`[${a}]`:Ie(a,"sub")),c!==void 0&&(h+=Ie(c,"sup")),n?` ${h} `:h}parseRequiredArgument(t=true){let e=this.stackFractions;this.stackFractions=e&&t;let r=this.parseRequiredArgumentValue();return this.stackFractions=e,r}parseRequiredArgumentValue(){for(;this.position<this.source.length&&/\s/.test(this.source[this.position]??"");)this.position++;if(this.position>=this.source.length)return this.supported=false,"";if(this.source[this.position]==="{")return this.position++,this.parseSequence("}");if(this.source[this.position]==="\\")return this.parseCommand();let t=this.source[this.position]??"";return this.position++,t}parseOptionalArgument(){for(;this.position<this.source.length&&/[ \t]/.test(this.source[this.position]??"");)this.position++;if(this.source[this.position]!=="[")return;let t=this.source.indexOf("]",this.position+1);if(t<0){this.supported=false;return}let e=this.source.slice(this.position+1,t);return this.position=t+1,this.renderNested(e)}readRawGroup(){for(;this.position<this.source.length&&/[ \t]/.test(this.source[this.position]??"");)this.position++;if(this.source[this.position]!=="{"){this.supported=false;return}let t=++this.position,e=1;for(;this.position<this.source.length;){let r=this.source[this.position]??"";if(r==="\\"){this.position+=2;continue}if(r==="{"&&e++,r==="}"&&e--,e===0){let n=this.source.slice(t,this.position);return this.position++,n}this.position++;}this.supported=false;}splitEnvironmentRows(t){return t.split(/\\\\(?:\[[^\]\n]*\])?/)}parseEnvironment(){let t=this.readRawGroup();if(!t)return "";let e=`\\end{${t}}`,r=this.source.indexOf(e,this.position);if(r<0)return this.supported=false,"";let n=this.source.slice(this.position,r);if(this.position=r+e.length,t==="equation"||t==="equation*"||t==="displaymath")return this.renderNested(n).trim();if(t==="aligned"||t==="align"||t==="align*"||t==="alignedat"||t==="alignat"||t==="alignat*"||t==="gather"||t==="gathered"||t==="multline"||t==="multline*"||t==="split"){let s=["alignedat","alignat","alignat*"].includes(t),o=s?n.replace(/^\s*\{[^}]*\}/,""):n;return this.splitEnvironmentRows(o).map(l=>{let a=l.split("&"),c=s?Array.from({length:Math.ceil(a.length/2)},(h,u)=>a.slice(u*2,u*2+2).join("")).join(" "):a.join("");return this.renderNested(c).trim()}).filter(Boolean).join(`
29
- `)}if(t==="cases"||t==="cases*")return this.renderCases(n);if(["array","matrix","smallmatrix","pmatrix","bmatrix","Bmatrix","vmatrix","Vmatrix"].includes(t)){let s=t==="array"?n.replace(/^\s*\{[^}]*\}/,""):n;return this.renderMatrix(t,s)}return this.supported=false,n}renderCases(t){let e=this.splitEnvironmentRows(t).map(c=>c.split("&").map(h=>this.renderNested(h,false).trim())).filter(c=>c.some(Boolean)),r=Math.max(0,...e.map(c=>S((c[0]??"").replace(/,\s*$/,"")))),n=e.map(c=>{let h=(c[0]??"").replace(/,\s*$/,""),u=c[1]??"";if(!u)return h;let p=/^(?:if|when|for|otherwise)\b/i.test(u)?" ":" if ";return `${h}${tr.repeat(r-S(h))}${p}${u}`});if(n.length<=1)return n.length===0?"":`\u23A7 ${n[0]}`;let s=Math.floor(n.length/2),o=[...n];n.length%2===0&&o.splice(s,0,void 0);let l=o.map((c,h)=>{let u=h===0?"\u23A7":h===o.length-1?"\u23A9":"\u23A8";return c===void 0?u:`${u} ${c}`}),a=this.layoutNodes.push({type:"matrix",lines:l,baseline:s})-1;return `${Ze}${a}${ft}`}renderMatrix(t,e){let r=this.splitEnvironmentRows(e).map(c=>c.split("&").map(h=>this.renderNested(h,false).trim())).filter(c=>c.some(Boolean)),n=Math.max(0,...r.map(c=>c.length)),s=Array.from({length:n},(c,h)=>Math.max(0,...r.map(u=>S(u[h]??"")))),o=r.map(c=>Array.from({length:n},(h,u)=>{let p=c[u]??"";return `${p}${tr.repeat(Math.max(0,(s[u]??0)-S(p)))}`}).join(" \u2502 ")),l;if(t==="array"||t==="matrix"||t==="smallmatrix")l=o;else {let h={pmatrix:["\u239B","\u239E","\u239C","\u239F","\u239D","\u23A0"],bmatrix:["\u23A1","\u23A4","\u23A2","\u23A5","\u23A3","\u23A6"],Bmatrix:["\u23A7","\u23AB","\u23A8","\u23AC","\u23A9","\u23AD"],vmatrix:["\u2502","\u2502","\u2502","\u2502","\u2502","\u2502"],Vmatrix:["\u2551","\u2551","\u2551","\u2551","\u2551","\u2551"]}[t];if(!h)return this.supported=false,o.join(`
30
- `);l=o.map((u,p)=>{let f=p===0?h[0]:p===o.length-1?h[4]:h[2],b=p===0?h[1]:p===o.length-1?h[5]:h[3];return `${f} ${u} ${b}`});}if(l.length<=1)return l[0]??"";let a=this.layoutNodes.push({type:"matrix",lines:l,baseline:0})-1;return `${Ze}${a}${ft}`}renderNested(t,e=true){let r=new i(t,this.layoutNodes,this.display&&e).render();return r===void 0?(this.supported=false,t):r}};function rr(i,t={}){let e=[],r=new ni(i,e,t.display===true).render();if(r===void 0)return;if(e.length===0)return r.replaceAll(tr," ");let n=mt(r,e).lines,s=Math.min(...n.filter(o=>o.trim()).map(o=>o.length-o.trimStart().length));return n.map(o=>o.slice(s).trimEnd()).join(`
31
- `).trimEnd().replaceAll(tr," ")}var Xa=/^(~~)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/,si=class extends Tokenizer{del(t){let e=Xa.exec(t);if(!e)return;let r=e[2]??"";return {type:"del",raw:e[0],text:r,tokens:this.lexer.inlineTokens(r)}}};function Qa(i,t){let e=0;for(let r=t-1;r>=0&&i[r]==="\\";r--)e++;return e%2===1}function Za(i,t,e){let r=i.indexOf(t,e);for(;r>=0&&Qa(i,r);)r=i.indexOf(t,r+t.length);return r}function Qn(i){return /\\[A-Za-z]+|[_^=+*/<>()[\]|±≤≥≠≈∈→⇒∞∫∑√-]/.test(i)}function Ja(i){let t="",e="";if(i.startsWith("$$"))t="$$",e="$$";else if(i.startsWith("\\("))t="\\(",e="\\)";else if(i.startsWith("\\["))t="\\[",e="\\]";else if(i.startsWith("$")&&!/^\$\s/.test(i))t="$",e="$";else return;let r=Za(i,e,t.length);if(r>=0&&t==="$"&&(/\s$/.test(i.slice(t.length,r))||/^\d/.test(i.slice(r+1))||/^[A-Z_][A-Z0-9_]*(?:[^A-Za-z0-9_\s])?$/.test(i.slice(t.length,r))&&/^[A-Za-z_][A-Za-z0-9_]*/.test(i.slice(r+1))||i.slice(t.length,r).includes("`")))return;if(r<0){let o=i.slice(t.length);return t.startsWith("\\")||Qn(o)?{type:"latex",raw:i,text:o,pending:true}:void 0}let n=i.slice(t.length,r);return !n||n.includes(`
32
- `)?void 0:{type:"latex",raw:i.slice(0,r+e.length),text:n}}function el(i){let t=/^ {0,3}\$\$[ \t]*(?:\n)?([\s\S]*?)\$\$[ \t]*(?:\n|$)/.exec(i);if(t?.[1])return {type:"latexBlock",raw:t[0],text:t[1].trim()};let e=/^ {0,3}\\\[[ \t]*(?:\n)?([\s\S]*?)\\\][ \t]*(?:\n|$)/.exec(i);if(e?.[1])return {type:"latexBlock",raw:e[0],text:e[1].trim()};let r=/^ {0,3}\\\[[ \t]*(?:\n)?([\s\S]*)$/.exec(i);if(r)return {type:"latexBlock",raw:r[0],text:r[1]??"",pending:true};let n=/^ {0,3}\$\$[ \t]*(?:\n)?([\s\S]*)$/.exec(i);if(n?.[1]&&Qn(n[1]))return {type:"latexBlock",raw:n[0],text:n[1],pending:true}}var tl=[{name:"latexBlock",level:"block",start(i){let t=/(?:^|\n) {0,3}(?:\$\$|\\\[)/.exec(i);return t?t.index+(t[0].startsWith(`
33
- `)?1:0):void 0},tokenizer:el},{name:"latex",level:"inline",start(i){let t=[i.indexOf("$"),i.indexOf("\\("),i.indexOf("\\[")].filter(e=>e>=0);return t.length>0?Math.min(...t):void 0},tokenizer:Ja}];function oi(i){let t=i[i.length-1];if(t?.type==="list"){oi(t.items[t.items.length-1]?.tokens??[]);return}if(t?.type==="blockquote"){oi(t.tokens??[]);return}if(t?.type!=="code")return;let e=/^(`{3,}|~{3,})/.exec(t.raw)?.[1],r=t.raw.split(`
34
- `).pop();!e||!r||r.length>=e.length||r!==e[0]?.repeat(r.length)||(t.text=t.text.slice(0,-r.length).replace(/\n$/,""));}var li=new Marked;li.setOptions({tokenizer:new si});li.use({extensions:[...tl]});var ai=class{constructor(t,e,r,n,s,o){d(this,"text");d(this,"paddingX");d(this,"paddingY");d(this,"defaultTextStyle");d(this,"theme");d(this,"options");d(this,"defaultStylePrefix");d(this,"cachedText");d(this,"cachedWidth");d(this,"cachedLines");d(this,"cachedTokens");this.text=t,this.paddingX=e,this.paddingY=r,this.theme=n,this.defaultTextStyle=s,this.options=o?{...o}:{};}setText(t){this.text=t,this.invalidate();}invalidate(){this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0;}render(t){if(this.cachedLines&&this.cachedText===this.text&&this.cachedWidth===t)return this.cachedLines;let e=Math.max(1,t-this.paddingX*2),r=this.options.transform?.(this.text,e)??this.text;if(!r||r.trim()===""){let g=[];return this.cachedText=this.text,this.cachedWidth=t,this.cachedLines=g,g}let n=r.replace(/\t/g," "),s=this.cachedTokens?.deref(),o=s?.source===n?s.tokens:void 0;o||(o=li.lexer(n),oi(o),this.cachedTokens=new WeakRef({source:n,tokens:o}));let l=[];for(let g=0;g<o.length;g++){let x=o[g],v=o[g+1],y=this.renderToken(x,e,v?.type);for(let w of y)l.push(w);}let a=[];for(let g of l)if(F(g))a.push(g);else for(let x of se(g,e))a.push(x);let c=" ".repeat(this.paddingX),h=" ".repeat(this.paddingX),u=this.defaultTextStyle?.bgColor,p=[];for(let g of a){if(F(g)){p.push(g);continue}let x=c+g+h;if(u)p.push(De(x,t,u));else {let v=S(x),y=Math.max(0,t-v);p.push(x+" ".repeat(y));}}let f=" ".repeat(t),b=[];for(let g=0;g<this.paddingY;g++){let x=u?De(f,t,u):f;b.push(x);}let m=b.concat(p,b);return Be(m),this.cachedText=this.text,this.cachedWidth=t,this.cachedLines=m,m.length>0?m:[""]}applyDefaultStyle(t){if(!this.defaultTextStyle)return t;let e=t;return this.defaultTextStyle.color&&(e=this.defaultTextStyle.color(e)),this.defaultTextStyle.bold&&(e=this.theme.bold(e)),this.defaultTextStyle.italic&&(e=this.theme.italic(e)),this.defaultTextStyle.strikethrough&&(e=this.theme.strikethrough(e)),this.defaultTextStyle.underline&&(e=this.theme.underline(e)),e}getDefaultStylePrefix(){if(!this.defaultTextStyle)return "";if(this.defaultStylePrefix!==void 0)return this.defaultStylePrefix;let t="\0",e=t;this.defaultTextStyle.color&&(e=this.defaultTextStyle.color(e)),this.defaultTextStyle.bold&&(e=this.theme.bold(e)),this.defaultTextStyle.italic&&(e=this.theme.italic(e)),this.defaultTextStyle.strikethrough&&(e=this.theme.strikethrough(e)),this.defaultTextStyle.underline&&(e=this.theme.underline(e));let r=e.indexOf(t);return this.defaultStylePrefix=r>=0?e.slice(0,r):"",this.defaultStylePrefix}getStylePrefix(t){let r=t("\0"),n=r.indexOf("\0");return n>=0?r.slice(0,n):""}getDefaultInlineStyleContext(){return {applyText:t=>this.applyDefaultStyle(t),stylePrefix:this.getDefaultStylePrefix()}}renderToken(t,e,r,n){let s=[];switch(t.type){case "heading":{let o=t.depth,l=`${"#".repeat(o)} `,a;o===1?a=p=>this.theme.heading(this.theme.bold(this.theme.underline(p))):a=p=>this.theme.heading(this.theme.bold(p));let c={applyText:a,stylePrefix:this.getStylePrefix(a)},h=this.renderInlineTokens(t.tokens||[],c),u=o>=3?a(l)+h:h;s.push(u),r&&r!=="space"&&s.push("");break}case "paragraph":{let o=this.renderInlineTokens(t.tokens||[],n);s.push(o),r&&r!=="list"&&r!=="space"&&s.push("");break}case "text":s.push(this.renderInlineTokens([t],n));break;case "latexBlock":{let o=t,l=!o.pending&&this.options.renderLatex!==false?rr(o.text,{display:true})??o.raw.trim():o.raw.trim();for(let a of l.split(`
28
+ `;if(Ta.has(t))return " ";if(Ma.has(t))return Gn;if(Ia.has(t)){for(;this.position<this.source.length&&/\s/.test(this.source[this.position]??"");)this.position++;return ""}if(La.has(t))return "";if(t==="{"||t==="}"||t==="$"||t==="%"||t==="#"||t==="_"||t==="&")return t;if(t==="|")return "\u2016";if(t==="not"){let s=this.parseRequiredArgument(false).trim(),o=va[s];if(o!==void 0)return ` ${o} `;let l=Array.from(s);return l.length===0?(this.supported=false,""):` ${l[0]}\u0338${l.slice(1).join("")} `}if(ba.has(t))return this.parseOperator(t,"bracket",true,true);let r=ma[t];if(r!==void 0)return ya.has(t)?this.parseOperator(r,"script",true):t==="cdot"||t==="times"||xa.has(t)?` ${r} `:r;if(ga.has(t))return `${Yn}${t}${ke}`;if(ka.has(t))return "";if(t==="left"||t==="middle"||t==="right")return this.source[this.position]==="."&&this.position++,"";if(t==="frac"||t==="dfrac"||t==="tfrac"){let s=this.display&&this.stackFractions&&t!=="tfrac",o=this.parseRequiredArgument(!s),l=this.parseRequiredArgument(!s);if(s){let a=this.layoutNodes.push({type:"fraction",numerator:Le(o),denominator:Le(l)})-1;return `${Je}${a}${dt}`}return Pa(o,l)}if(t==="sqrt"){let s=this.parseOptionalArgument()?.trim(),o=this.parseRequiredArgument();return s===void 0||s==="2"?Zt(o):s==="3"?Zt(o,"\u221B"):s==="4"?Zt(o,"\u221C"):`${Ie(s,"sup")}${Zt(o)}`}if(t==="boxed"||t==="fbox")return `[${this.parseRequiredArgument().trim()}]`;if(t==="binom"||t==="dbinom"||t==="tbinom")return `(${this.parseRequiredArgument()} choose ${this.parseRequiredArgument()})`;let n=Ra[t];if(n!==void 0){let s=this.parseRequiredArgument();return Array.from(s).length===1?`${s}${n}`:`${t}(${s})`}if(t==="mathbb"){let s=this.parseRequiredArgument();return Array.from(s,o=>Sa[o]??o).join("")}if(t==="operatorname"){let s=this.source[this.position]==="*";s&&this.position++;let o=Le(this.parseRequiredArgument()).trim();return this.parseOperator(o,"bracket",s,true)}if(t==="mod"||t==="bmod")return " mod ";if(t==="pmod"||t==="pod"){let s=this.parseRequiredArgument().trim();return t==="pmod"?` (mod ${s})`:` (${s})`}if(t==="overset"||t==="stackrel"){let s=this.parseRequiredArgument();return `${this.parseRequiredArgument().trim()}${Ie(s,"sup")}`}if(t==="underset"){let s=this.parseRequiredArgument();return `${this.parseRequiredArgument().trim()}${Ie(s,"sub")}`}if(Aa.has(t)){let s=this.parseRequiredArgument();return t.startsWith("text")||t==="mbox"?s:s.trim()}return t==="begin"?this.parseEnvironment():t==="end"?(this.supported=false,""):(this.supported=false,`\\${t}`)}parseOperator(t,e,r,n=false){let s=r,o=this.position;for(;o<this.source.length&&/[ \t]/.test(this.source[o]??"");)o++;let l=/^\\(limits|nolimits)(?![A-Za-z])/.exec(this.source.slice(o));l&&(s=l[1]==="limits",this.position=o+l[0].length);let a,c;for(;;){let u=this.position;for(;u<this.source.length&&/[ \t]/.test(this.source[u]??"");)u++;let p=this.source[u];if(p!=="_"&&p!=="^")break;this.position=u+1;let f=Le(this.parseRequiredArgument(false)).replaceAll(" ","");p==="_"?(a!==void 0&&(this.supported=false),a=f):(c!==void 0&&(this.supported=false),c=f);}if(this.display&&s&&(a!==void 0||c!==void 0)){let u=this.layoutNodes.push({type:"operator",operator:t,lower:a,upper:c})-1;return `${Je}${u}${dt}`}let h=t;return a!==void 0&&(h+=e==="bracket"?`[${a}]`:Ie(a,"sub")),c!==void 0&&(h+=Ie(c,"sup")),n?` ${h} `:h}parseRequiredArgument(t=true){let e=this.stackFractions;this.stackFractions=e&&t;let r=this.parseRequiredArgumentValue();return this.stackFractions=e,r}parseRequiredArgumentValue(){for(;this.position<this.source.length&&/\s/.test(this.source[this.position]??"");)this.position++;if(this.position>=this.source.length)return this.supported=false,"";if(this.source[this.position]==="{")return this.position++,this.parseSequence("}");if(this.source[this.position]==="\\")return this.parseCommand();let t=this.source[this.position]??"";return this.position++,t}parseOptionalArgument(){for(;this.position<this.source.length&&/[ \t]/.test(this.source[this.position]??"");)this.position++;if(this.source[this.position]!=="[")return;let t=this.source.indexOf("]",this.position+1);if(t<0){this.supported=false;return}let e=this.source.slice(this.position+1,t);return this.position=t+1,this.renderNested(e)}readRawGroup(){for(;this.position<this.source.length&&/[ \t]/.test(this.source[this.position]??"");)this.position++;if(this.source[this.position]!=="{"){this.supported=false;return}let t=++this.position,e=1;for(;this.position<this.source.length;){let r=this.source[this.position]??"";if(r==="\\"){this.position+=2;continue}if(r==="{"&&e++,r==="}"&&e--,e===0){let n=this.source.slice(t,this.position);return this.position++,n}this.position++;}this.supported=false;}splitEnvironmentRows(t){return t.split(/\\\\(?:\[[^\]\n]*\])?/)}parseEnvironment(){let t=this.readRawGroup();if(!t)return "";let e=`\\end{${t}}`,r=this.source.indexOf(e,this.position);if(r<0)return this.supported=false,"";let n=this.source.slice(this.position,r);if(this.position=r+e.length,t==="equation"||t==="equation*"||t==="displaymath")return this.renderNested(n).trim();if(t==="aligned"||t==="align"||t==="align*"||t==="alignedat"||t==="alignat"||t==="alignat*"||t==="gather"||t==="gathered"||t==="multline"||t==="multline*"||t==="split"){let s=["alignedat","alignat","alignat*"].includes(t),o=s?n.replace(/^\s*\{[^}]*\}/,""):n;return this.splitEnvironmentRows(o).map(l=>{let a=l.split("&"),c=s?Array.from({length:Math.ceil(a.length/2)},(h,u)=>a.slice(u*2,u*2+2).join("")).join(" "):a.join("");return this.renderNested(c).trim()}).filter(Boolean).join(`
29
+ `)}if(t==="cases"||t==="cases*")return this.renderCases(n);if(["array","matrix","smallmatrix","pmatrix","bmatrix","Bmatrix","vmatrix","Vmatrix"].includes(t)){let s=t==="array"?n.replace(/^\s*\{[^}]*\}/,""):n;return this.renderMatrix(t,s)}return this.supported=false,n}renderCases(t){let e=this.splitEnvironmentRows(t).map(c=>c.split("&").map(h=>this.renderNested(h,false).trim())).filter(c=>c.some(Boolean)),r=Math.max(0,...e.map(c=>S((c[0]??"").replace(/,\s*$/,"")))),n=e.map(c=>{let h=(c[0]??"").replace(/,\s*$/,""),u=c[1]??"";if(!u)return h;let p=/^(?:if|when|for|otherwise)\b/i.test(u)?" ":" if ";return `${h}${er.repeat(r-S(h))}${p}${u}`});if(n.length<=1)return n.length===0?"":`\u23A7 ${n[0]}`;let s=Math.floor(n.length/2),o=[...n];n.length%2===0&&o.splice(s,0,void 0);let l=o.map((c,h)=>{let u=h===0?"\u23A7":h===o.length-1?"\u23A9":"\u23A8";return c===void 0?u:`${u} ${c}`}),a=this.layoutNodes.push({type:"matrix",lines:l,baseline:s})-1;return `${Je}${a}${dt}`}renderMatrix(t,e){let r=this.splitEnvironmentRows(e).map(c=>c.split("&").map(h=>this.renderNested(h,false).trim())).filter(c=>c.some(Boolean)),n=Math.max(0,...r.map(c=>c.length)),s=Array.from({length:n},(c,h)=>Math.max(0,...r.map(u=>S(u[h]??"")))),o=r.map(c=>Array.from({length:n},(h,u)=>{let p=c[u]??"";return `${p}${er.repeat(Math.max(0,(s[u]??0)-S(p)))}`}).join(" \u2502 ")),l;if(t==="array"||t==="matrix"||t==="smallmatrix")l=o;else {let h={pmatrix:["\u239B","\u239E","\u239C","\u239F","\u239D","\u23A0"],bmatrix:["\u23A1","\u23A4","\u23A2","\u23A5","\u23A3","\u23A6"],Bmatrix:["\u23A7","\u23AB","\u23A8","\u23AC","\u23A9","\u23AD"],vmatrix:["\u2502","\u2502","\u2502","\u2502","\u2502","\u2502"],Vmatrix:["\u2551","\u2551","\u2551","\u2551","\u2551","\u2551"]}[t];if(!h)return this.supported=false,o.join(`
30
+ `);l=o.map((u,p)=>{let f=p===0?h[0]:p===o.length-1?h[4]:h[2],b=p===0?h[1]:p===o.length-1?h[5]:h[3];return `${f} ${u} ${b}`});}if(l.length<=1)return l[0]??"";let a=this.layoutNodes.push({type:"matrix",lines:l,baseline:0})-1;return `${Je}${a}${dt}`}renderNested(t,e=true){let r=new i(t,this.layoutNodes,this.display&&e).render();return r===void 0?(this.supported=false,t):r}};function tr(i,t={}){let e=[],r=new ii(i,e,t.display===true).render();if(r===void 0)return;if(e.length===0)return r.replaceAll(er," ");let n=pt(r,e).lines,s=Math.min(...n.filter(o=>o.trim()).map(o=>o.length-o.trimStart().length));return n.map(o=>o.slice(s).trimEnd()).join(`
31
+ `).trimEnd().replaceAll(er," ")}var Fa=/^(~~)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/,ni=class extends Tokenizer{del(t){let e=Fa.exec(t);if(!e)return;let r=e[2]??"";return {type:"del",raw:e[0],text:r,tokens:this.lexer.inlineTokens(r)}}};function Wa(i,t){let e=0;for(let r=t-1;r>=0&&i[r]==="\\";r--)e++;return e%2===1}function Va(i,t,e){let r=i.indexOf(t,e);for(;r>=0&&Wa(i,r);)r=i.indexOf(t,r+t.length);return r}function jn(i){return /\\[A-Za-z]+|[_^=+*/<>()[\]|±≤≥≠≈∈→⇒∞∫∑√-]/.test(i)}function Ha(i){let t="",e="";if(i.startsWith("$$"))t="$$",e="$$";else if(i.startsWith("\\("))t="\\(",e="\\)";else if(i.startsWith("\\["))t="\\[",e="\\]";else if(i.startsWith("$")&&!/^\$\s/.test(i))t="$",e="$";else return;let r=Va(i,e,t.length);if(r>=0&&t==="$"&&(/\s$/.test(i.slice(t.length,r))||/^\d/.test(i.slice(r+1))||/^[A-Z_][A-Z0-9_]*(?:[^A-Za-z0-9_\s])?$/.test(i.slice(t.length,r))&&/^[A-Za-z_][A-Za-z0-9_]*/.test(i.slice(r+1))||i.slice(t.length,r).includes("`")))return;if(r<0){let o=i.slice(t.length);return t.startsWith("\\")||jn(o)?{type:"latex",raw:i,text:o,pending:true}:void 0}let n=i.slice(t.length,r);return !n||n.includes(`
32
+ `)?void 0:{type:"latex",raw:i.slice(0,r+e.length),text:n}}function Ua(i){let t=/^ {0,3}\$\$[ \t]*(?:\n)?([\s\S]*?)\$\$[ \t]*(?:\n|$)/.exec(i);if(t?.[1])return {type:"latexBlock",raw:t[0],text:t[1].trim()};let e=/^ {0,3}\\\[[ \t]*(?:\n)?([\s\S]*?)\\\][ \t]*(?:\n|$)/.exec(i);if(e?.[1])return {type:"latexBlock",raw:e[0],text:e[1].trim()};let r=/^ {0,3}\\\[[ \t]*(?:\n)?([\s\S]*)$/.exec(i);if(r)return {type:"latexBlock",raw:r[0],text:r[1]??"",pending:true};let n=/^ {0,3}\$\$[ \t]*(?:\n)?([\s\S]*)$/.exec(i);if(n?.[1]&&jn(n[1]))return {type:"latexBlock",raw:n[0],text:n[1],pending:true}}var qa=[{name:"latexBlock",level:"block",start(i){let t=/(?:^|\n) {0,3}(?:\$\$|\\\[)/.exec(i);return t?t.index+(t[0].startsWith(`
33
+ `)?1:0):void 0},tokenizer:Ua},{name:"latex",level:"inline",start(i){let t=[i.indexOf("$"),i.indexOf("\\("),i.indexOf("\\[")].filter(e=>e>=0);return t.length>0?Math.min(...t):void 0},tokenizer:Ha}];function si(i){let t=i[i.length-1];if(t?.type==="list"){si(t.items[t.items.length-1]?.tokens??[]);return}if(t?.type==="blockquote"){si(t.tokens??[]);return}if(t?.type!=="code")return;let e=/^(`{3,}|~{3,})/.exec(t.raw)?.[1],r=t.raw.split(`
34
+ `).pop();!e||!r||r.length>=e.length||r!==e[0]?.repeat(r.length)||(t.text=t.text.slice(0,-r.length).replace(/\n$/,""));}var ai=new Marked;ai.setOptions({tokenizer:new ni});ai.use({extensions:[...qa]});var oi=class{constructor(t,e,r,n,s,o){d(this,"text");d(this,"paddingX");d(this,"paddingY");d(this,"defaultTextStyle");d(this,"theme");d(this,"options");d(this,"defaultStylePrefix");d(this,"cachedText");d(this,"cachedWidth");d(this,"cachedLines");d(this,"cachedTokens");this.text=t,this.paddingX=e,this.paddingY=r,this.theme=n,this.defaultTextStyle=s,this.options=o?{...o}:{};}setText(t){this.text=t,this.invalidate();}invalidate(){this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0;}render(t){if(this.cachedLines&&this.cachedText===this.text&&this.cachedWidth===t)return this.cachedLines;let e=Math.max(1,t-this.paddingX*2),r=this.options.transform?.(this.text,e)??this.text;if(!r||r.trim()===""){let g=[];return this.cachedText=this.text,this.cachedWidth=t,this.cachedLines=g,g}let n=r.replace(/\t/g," "),s=this.cachedTokens?.deref(),o=s?.source===n?s.tokens:void 0;o||(o=ai.lexer(n),si(o),this.cachedTokens=new WeakRef({source:n,tokens:o}));let l=[];for(let g=0;g<o.length;g++){let y=o[g],v=o[g+1],x=this.renderToken(y,e,v?.type);for(let w of x)l.push(w);}let a=[];for(let g of l)if(F(g))a.push(g);else for(let y of ne(g,e))a.push(y);let c=" ".repeat(this.paddingX),h=" ".repeat(this.paddingX),u=this.defaultTextStyle?.bgColor,p=[];for(let g of a){if(F(g)){p.push(g);continue}let y=c+g+h;if(u)p.push(De(y,t,u));else {let v=S(y),x=Math.max(0,t-v);p.push(y+" ".repeat(x));}}let f=" ".repeat(t),b=[];for(let g=0;g<this.paddingY;g++){let y=u?De(f,t,u):f;b.push(y);}let m=b.concat(p,b);return _e(m),this.cachedText=this.text,this.cachedWidth=t,this.cachedLines=m,m.length>0?m:[""]}applyDefaultStyle(t){if(!this.defaultTextStyle)return t;let e=t;return this.defaultTextStyle.color&&(e=this.defaultTextStyle.color(e)),this.defaultTextStyle.bold&&(e=this.theme.bold(e)),this.defaultTextStyle.italic&&(e=this.theme.italic(e)),this.defaultTextStyle.strikethrough&&(e=this.theme.strikethrough(e)),this.defaultTextStyle.underline&&(e=this.theme.underline(e)),e}getDefaultStylePrefix(){if(!this.defaultTextStyle)return "";if(this.defaultStylePrefix!==void 0)return this.defaultStylePrefix;let t="\0",e=t;this.defaultTextStyle.color&&(e=this.defaultTextStyle.color(e)),this.defaultTextStyle.bold&&(e=this.theme.bold(e)),this.defaultTextStyle.italic&&(e=this.theme.italic(e)),this.defaultTextStyle.strikethrough&&(e=this.theme.strikethrough(e)),this.defaultTextStyle.underline&&(e=this.theme.underline(e));let r=e.indexOf(t);return this.defaultStylePrefix=r>=0?e.slice(0,r):"",this.defaultStylePrefix}getStylePrefix(t){let r=t("\0"),n=r.indexOf("\0");return n>=0?r.slice(0,n):""}getDefaultInlineStyleContext(){return {applyText:t=>this.applyDefaultStyle(t),stylePrefix:this.getDefaultStylePrefix()}}renderToken(t,e,r,n){let s=[];switch(t.type){case "heading":{let o=t.depth,l=`${"#".repeat(o)} `,a;o===1?a=p=>this.theme.heading(this.theme.bold(this.theme.underline(p))):a=p=>this.theme.heading(this.theme.bold(p));let c={applyText:a,stylePrefix:this.getStylePrefix(a)},h=this.renderInlineTokens(t.tokens||[],c),u=o>=3?a(l)+h:h;s.push(u),r&&r!=="space"&&s.push("");break}case "paragraph":{let o=this.renderInlineTokens(t.tokens||[],n);s.push(o),r&&r!=="list"&&r!=="space"&&s.push("");break}case "text":s.push(this.renderInlineTokens([t],n));break;case "latexBlock":{let o=t,l=!o.pending&&this.options.renderLatex!==false?tr(o.text,{display:true})??o.raw.trim():o.raw.trim();for(let a of l.split(`
35
35
  `))s.push(this.applyDefaultStyle(a));r&&r!=="space"&&s.push("");break}case "code":{let o=this.theme.codeBlockIndent??" ";if(s.push(this.theme.codeBlockBorder(`\`\`\`${t.lang||""}`)),this.theme.highlightCode){let l=this.theme.highlightCode(t.text,t.lang);for(let a of l)s.push(`${o}${a}`);}else {let l=t.text.split(`
36
- `);for(let a of l)s.push(`${o}${this.theme.codeBlock(a)}`);}s.push(this.theme.codeBlockBorder("```")),r&&r!=="space"&&s.push("");break}case "list":{let o=this.renderList(t,0,e,n);s.push(...o);break}case "table":{let o=this.renderTable(t,e,r,n);s.push(...o);break}case "blockquote":{let o=f=>this.theme.quote(this.theme.italic(f)),l=this.getStylePrefix(o),a=f=>{if(!l)return o(f);let b=f.replace(/\x1b\[0m/g,`\x1B[0m${l}`);return o(b)},c=Math.max(1,e-2),h={applyText:f=>f,stylePrefix:l},u=t.tokens||[],p=[];for(let f=0;f<u.length;f++){let b=u[f],m=u[f+1];p.push(...this.renderToken(b,c,m?.type,h));}for(;p.length>0&&p[p.length-1]==="";)p.pop();for(let f of p){let b=a(f),m=se(b,c);for(let g of m)s.push(this.theme.quoteBorder("\u2502 ")+g);}r&&r!=="space"&&s.push("");break}case "hr":s.push(this.theme.hr("\u2500".repeat(Math.min(e,80)))),r&&r!=="space"&&s.push("");break;case "html":"raw"in t&&typeof t.raw=="string"&&s.push(this.applyDefaultStyle(t.raw.trim()));break;case "space":s.push("");break;default:"text"in t&&typeof t.text=="string"&&s.push(t.text);}return s}renderInlineTokens(t,e){let r="",n=e??this.getDefaultInlineStyleContext(),{applyText:s,stylePrefix:o}=n,l=a=>a.split(`
36
+ `);for(let a of l)s.push(`${o}${this.theme.codeBlock(a)}`);}s.push(this.theme.codeBlockBorder("```")),r&&r!=="space"&&s.push("");break}case "list":{let o=this.renderList(t,0,e,n);s.push(...o);break}case "table":{let o=this.renderTable(t,e,r,n);s.push(...o);break}case "blockquote":{let o=f=>this.theme.quote(this.theme.italic(f)),l=this.getStylePrefix(o),a=f=>{if(!l)return o(f);let b=f.replace(/\x1b\[0m/g,`\x1B[0m${l}`);return o(b)},c=Math.max(1,e-2),h={applyText:f=>f,stylePrefix:l},u=t.tokens||[],p=[];for(let f=0;f<u.length;f++){let b=u[f],m=u[f+1];p.push(...this.renderToken(b,c,m?.type,h));}for(;p.length>0&&p[p.length-1]==="";)p.pop();for(let f of p){let b=a(f),m=ne(b,c);for(let g of m)s.push(this.theme.quoteBorder("\u2502 ")+g);}r&&r!=="space"&&s.push("");break}case "hr":s.push(this.theme.hr("\u2500".repeat(Math.min(e,80)))),r&&r!=="space"&&s.push("");break;case "html":"raw"in t&&typeof t.raw=="string"&&s.push(this.applyDefaultStyle(t.raw.trim()));break;case "space":s.push("");break;default:"text"in t&&typeof t.text=="string"&&s.push(t.text);}return s}renderInlineTokens(t,e){let r="",n=e??this.getDefaultInlineStyleContext(),{applyText:s,stylePrefix:o}=n,l=a=>a.split(`
37
37
  `).map(h=>s(h)).join(`
38
- `);for(let a of t)switch(a.type){case "latex":{let c=a,h=!c.pending&&this.options.renderLatex!==false?rr(c.text)??c.raw:c.raw;r+=l(h);break}case "escape":r+=l(this.options.preserveBackslashEscapes?a.raw:a.text);break;case "text":a.tokens&&a.tokens.length>0?r+=this.renderInlineTokens(a.tokens,n):r+=l(a.text);break;case "paragraph":r+=this.renderInlineTokens(a.tokens||[],n);break;case "strong":{let c=this.renderInlineTokens(a.tokens||[],n);r+=this.theme.bold(c)+o;break}case "em":{let c=this.renderInlineTokens(a.tokens||[],n);r+=this.theme.italic(c)+o;break}case "codespan":r+=this.theme.code(a.text)+o;break;case "link":{let c=this.renderInlineTokens(a.tokens||[],n),h=this.theme.link(this.theme.underline(c));if(re().hyperlinks)r+=Ht(h,a.href)+o;else {let u=a.href.startsWith("mailto:")?a.href.slice(7):a.href;a.text===a.href||a.text===u?r+=h+o:r+=h+this.theme.linkUrl(` (${a.href})`)+o;}break}case "br":r+=`
39
- `;break;case "del":{let c=this.renderInlineTokens(a.tokens||[],n);r+=this.theme.strikethrough(c)+o;break}case "html":"raw"in a&&typeof a.raw=="string"&&(r+=l(a.raw));break;default:"text"in a&&typeof a.text=="string"&&(r+=l(a.text));}for(;o&&r.endsWith(o);)r=r.slice(0,-o.length);return r}getOrderedListMarker(t){let e=/^(?: {0,3})(\d{1,9}[.)])[ \t]+/.exec(t.raw);return e?`${e[1]} `:void 0}getUnorderedListMarker(t){let e=/^(?: {0,3})([-+*])(?:[ \t]+|(?=\r?\n|$))/.exec(t.raw);return e?`${e[1]} `:void 0}renderList(t,e,r,n){let s=[],o=" ".repeat(e),l=typeof t.start=="number"?t.start:1;for(let a=0;a<t.items.length;a++){let c=t.items[a],h=a===t.items.length-1,u=t.ordered?this.options.preserveOrderedListMarkers?this.getOrderedListMarker(c)??`${l+a}. `:`${l+a}. `:this.options.preserveOrderedListMarkers?this.getUnorderedListMarker(c)??"- ":"- ",p=c.task?`[${c.checked?"x":" "}] `:"",f=u+p,b=o+this.theme.listBullet(f),m=o+" ".repeat(S(f)),g=Math.max(1,r-S(b)),x=false;for(let v of c.tokens??[]){if(v.type==="list"){s.push(...this.renderList(v,e+1,r,n)),x=true;continue}let y=this.renderToken(v,g,void 0,n);for(let w of y)for(let I of se(w,g)){let T=x?m:b;s.push(T+I),x=true;}}x||s.push(b),t.loose&&!h&&s.push("");}return s}getLongestWordWidth(t,e){let r=t.split(/\s+/).filter(s=>s.length>0),n=0;for(let s of r)n=Math.max(n,S(s));return e===void 0?n:Math.min(n,e)}wrapCellText(t,e,r=""){let n=se(t,Math.max(1,e));return n.map((s,o)=>{let l=o<n.length-1?"\x1B[22;23;24;25;27;28;29;39m":"";return `${s}${l}${r}`})}renderTable(t,e,r,n){let s=[],o=t.header.length;if(o===0)return s;let l=3*o+1,a=e-l;if(a<o){let T=t.raw?se(t.raw,e):[];return r&&r!=="space"&&T.push(""),T}let c=30,h=[],u=[];for(let T=0;T<o;T++){let L=this.renderInlineTokens(t.header[T]?.tokens||[],n);h[T]=S(L),u[T]=Math.max(1,this.getLongestWordWidth(L,c));}for(let T of t.rows)for(let L=0;L<T.length;L++){let M=this.renderInlineTokens(T[L]?.tokens||[],n);h[L]=Math.max(h[L]||0,S(M)),u[L]=Math.max(u[L]||1,this.getLongestWordWidth(M,c));}let p=u,f=p.reduce((T,L)=>T+L,0);if(f>a){p=new Array(o).fill(1);let T=a-o;if(T>0){let L=u.reduce((C,A)=>C+Math.max(0,A-1),0),M=u.map(C=>{let A=Math.max(0,C-1);return L>0?Math.floor(A/L*T):0});for(let C=0;C<o;C++)p[C]=(p[C]??0)+(M[C]??0);let E=M.reduce((C,A)=>C+A,0),P=T-E;for(let C=0;P>0&&C<o;C++)p[C]=(p[C]??0)+1,P--;}f=p.reduce((L,M)=>L+M,0);}let b=h.reduce((T,L)=>T+L,0)+l,m;if(b<=e)m=h.map((T,L)=>Math.max(T,p[L]??0));else {let T=h.reduce((P,C,A)=>P+Math.max(0,C-(p[A]??0)),0),L=Math.max(0,a-f);m=p.map((P,C)=>{let A=h[C]??0,D=Math.max(0,A-P),K=0;return T>0&&(K=Math.floor(D/T*L)),P+K});let M=m.reduce((P,C)=>P+C,0),E=a-M;for(;E>0;){let P=false;for(let C=0;C<o&&E>0;C++)(m[C]??0)<(h[C]??0)&&(m[C]=(m[C]??0)+1,E--,P=true);if(!P)break}}let g=m.map(T=>"\u2500".repeat(T));s.push(`\u250C\u2500${g.join("\u2500\u252C\u2500")}\u2500\u2510`);let x=t.header.map((T,L)=>{let M=this.renderInlineTokens(T.tokens||[],n);return this.wrapCellText(M,m[L]??0,n?.stylePrefix)}),v=Math.max(...x.map(T=>T.length));for(let T=0;T<v;T++){let L=x.map((M,E)=>{let P=M[T]||"",C=P+" ".repeat(Math.max(0,(m[E]??0)-S(P)));return this.theme.bold(C)});s.push(`\u2502 ${L.join(" \u2502 ")} \u2502`);}let w=`\u251C\u2500${m.map(T=>"\u2500".repeat(T)).join("\u2500\u253C\u2500")}\u2500\u2524`;s.push(w);for(let T=0;T<t.rows.length;T++){let M=(t.rows[T]??[]).map((P,C)=>{let A=this.renderInlineTokens(P.tokens||[],n);return this.wrapCellText(A,m[C]??0,n?.stylePrefix)}),E=Math.max(...M.map(P=>P.length));for(let P=0;P<E;P++){let C=M.map((A,D)=>{let K=A[P]||"";return K+" ".repeat(Math.max(0,(m[D]??0)-S(K)))});s.push(`\u2502 ${C.join(" \u2502 ")} \u2502`);}T<t.rows.length-1&&s.push(w);}let I=m.map(T=>"\u2500".repeat(T));return s.push(`\u2514\u2500${I.join("\u2500\u2534\u2500")}\u2500\u2518`),r&&r!=="space"&&s.push(""),s}};var ci=class{constructor(t,e){d(this,"child");d(this,"onMouse");this.child=t,this.onMouse=e;}render(t){return this.child.render(t)}handleMouse(t){return he(this.child,t)??this.onMouse(t)}invalidate(){this.child.invalidate();}};var gt=class extends oe{constructor(e,r={}){super();d(this,"child");d(this,"followEnd");d(this,"primary");d(this,"overscroll");d(this,"scrollbarTrackStyle");d(this,"scrollbarThumbStyle");d(this,"currentScrollbar");d(this,"scrollbarHideDelayMs");d(this,"currentScrollTop",0);d(this,"contentHeight",0);d(this,"currentViewportHeight",0);d(this,"followingEnd");d(this,"followSuppressedAtEnd",false);d(this,"requestRenderCallback");d(this,"transientScrollbarVisible",false);d(this,"scrollbarActive",false);d(this,"scrollbarHideTimer");if(r.axis!==void 0&&r.axis!=="vertical")throw new Error(`Unsupported ScrollView axis: ${r.axis}`);this.child=e,this.children.push(e),this.followEnd=(r.follow??"none")==="end",this.followingEnd=this.followEnd,this.primary=r.primary??false,this.overscroll=r.overscroll??"chain",this.currentScrollbar=r.scrollbar??"hidden",this.scrollbarTrackStyle=r.scrollbarTrackStyle??(n=>`\x1B[90m${n}\x1B[39m`),this.scrollbarThumbStyle=r.scrollbarThumbStyle??(n=>`\x1B[37m${n}\x1B[39m`),this.scrollbarHideDelayMs=Math.max(0,Math.floor(r.scrollbarHideDelayMs??1e3));}get scrollTop(){return this.currentScrollTop}get isFollowingEnd(){return this.followingEnd}get viewportHeight(){return this.currentViewportHeight}get scrollbar(){return this.currentScrollbar}get isScrollbarVisible(){return this.scrollbar==="always"?this.currentViewportHeight>0:this.scrollbar==="auto"&&this.contentHeight>this.currentViewportHeight&&this.transientScrollbarVisible}get isScrollbarActive(){return this.scrollbarActive}setScrollbar(e){e!==this.currentScrollbar&&(this.currentScrollbar=e,e!=="auto"?this.hideTransientScrollbar():this.scrollbarActive&&this.markScrollbarActivity(),this.requestRenderCallback?.());}getContentWidth(e){return this.scrollbar==="always"&&e>1?e-1:e}markScrollbarActivity(){this.scrollbar!=="auto"||this.contentHeight<=this.currentViewportHeight||(this.transientScrollbarVisible=true,this.scrollbarHideTimer&&(clearTimeout(this.scrollbarHideTimer),this.scrollbarHideTimer=void 0),!this.scrollbarActive&&(this.scrollbarHideTimer=setTimeout(()=>{this.scrollbarHideTimer=void 0,this.transientScrollbarVisible=false,this.requestRenderCallback?.();},this.scrollbarHideDelayMs),this.scrollbarHideTimer.unref()));}hideTransientScrollbar(){this.transientScrollbarVisible=false,this.scrollbarHideTimer&&(clearTimeout(this.scrollbarHideTimer),this.scrollbarHideTimer=void 0);}setScrollbarActive(e){e!==this.scrollbarActive&&(this.scrollbarActive=e,this.markScrollbarActivity(),this.requestRenderCallback?.());}scrollTo(e,r={}){let n=Number.isFinite(e)?Math.trunc(e):this.currentScrollTop,s=Math.max(0,this.contentHeight-this.currentViewportHeight),o=Math.max(0,Math.min(s,n)),l=r.disableFollow===true&&o===s,a=!l&&this.followEnd&&o===s;if(o===this.currentScrollTop&&a===this.followingEnd&&l===this.followSuppressedAtEnd)return;let c=o!==this.currentScrollTop;this.currentScrollTop=o,this.followingEnd=a,this.followSuppressedAtEnd=l,c&&this.markScrollbarActivity(),this.requestRenderCallback?.();}scrollBy(e){let r=Number.isFinite(e)?Math.trunc(e):0;if(r===0)return 0;let n=Math.max(0,this.contentHeight-this.currentViewportHeight),s=this.followingEnd?n:this.currentScrollTop,o=Math.max(0,Math.min(n,s+r)),l=o-s,a=this.followingEnd;return this.currentScrollTop=o,this.followingEnd=this.followEnd&&o===n,this.followSuppressedAtEnd=false,l!==0&&this.markScrollbarActivity(),(l!==0||this.followingEnd!==a)&&this.requestRenderCallback?.(),r-l}scrollToStart(){let e=this.currentScrollTop!==0||this.followingEnd!==(this.followEnd&&this.contentHeight<=this.currentViewportHeight);this.currentScrollTop=0,this.followingEnd=this.followEnd&&this.contentHeight<=this.currentViewportHeight,this.followSuppressedAtEnd=false,e&&(this.markScrollbarActivity(),this.requestRenderCallback?.());}scrollToEnd(){let e=Math.max(0,this.contentHeight-this.currentViewportHeight),r=this.currentScrollTop!==e||this.followingEnd!==this.followEnd;this.currentScrollTop=e,this.followingEnd=this.followEnd,this.followSuppressedAtEnd=false,r&&(this.markScrollbarActivity(),this.requestRenderCallback?.());}updateLayout(e,r,n){this.contentHeight=Math.max(0,Math.floor(e)),this.currentViewportHeight=Math.max(0,Math.floor(r)),this.requestRenderCallback=n;let s=Math.max(0,this.contentHeight-this.currentViewportHeight);this.followingEnd?this.currentScrollTop=s:this.currentScrollTop=Math.max(0,Math.min(this.currentScrollTop,s)),this.currentScrollTop<s&&(this.followSuppressedAtEnd=false),this.followEnd&&this.currentScrollTop===s&&!this.followSuppressedAtEnd&&(this.followingEnd=true),this.contentHeight<=this.currentViewportHeight&&this.hideTransientScrollbar();}addChild(e){throw new Error("ScrollView has exactly one child")}removeChild(e){throw new Error("ScrollView child cannot be removed")}clear(){throw new Error("ScrollView child cannot be cleared")}render(e){let r=this.getContentWidth(e),n=this.child.render(r);return r===e?n:n.map(s=>`${s} `)}[je](){return {type:"scroll",component:this.child,state:this}}};var ui=class{constructor(t,e,r,n,s,o={}){d(this,"items");d(this,"filteredItems");d(this,"theme");d(this,"selectedIndex",0);d(this,"mousePressedIndex");d(this,"maxVisible");d(this,"onChange");d(this,"onCancel");d(this,"searchInput");d(this,"searchEnabled");d(this,"submenuComponent",null);d(this,"submenuItemIndex",null);d(this,"navigateAfterClose",null);this.items=t,this.filteredItems=t,this.maxVisible=e,this.theme=r,this.onChange=n,this.onCancel=s,this.searchEnabled=o.enableSearch??false,this.searchEnabled&&(this.searchInput=new Me);}updateValue(t,e){let r=this.items.find(n=>n.id===t);r&&(r.currentValue=e);}selectItem(t){let r=(this.searchEnabled?this.filteredItems:this.items).findIndex(n=>n.id===t);r!==-1&&(this.selectedIndex=r);}invalidate(){this.submenuComponent?.invalidate?.();}render(t){return this.submenuComponent?this.submenuComponent.render(t):this.renderMainList(t)}renderMainList(t){let e=[];if(this.searchEnabled&&this.searchInput&&(e.push(...this.searchInput.render(t)),e.push("")),this.items.length===0)return e.push(this.theme.hint(" No settings available")),this.searchEnabled&&this.addHintLine(e,t),e;let r=this.getDisplayItems();if(r.length===0)return e.push(N(this.theme.hint(" No matching settings"),t)),this.addHintLine(e,t),e;let{startIndex:n,endIndex:s}=this.getVisibleRange(r),o=Math.min(36,Math.max(...this.items.map(c=>S(c.label)))),l=Math.max(S(this.theme.cursor),2);for(let c=n;c<s;c++){let h=r[c];if(!h)continue;let u=c===this.selectedIndex,p=u?this.theme.cursor:" ",f=p+" ".repeat(Math.max(0,l-S(p))),b=h.label+" ".repeat(Math.max(0,o-S(h.label))),m=this.theme.label(b,u),g=" ",x=l+o+S(g),v=t-x-2,y=this.theme.value(N(h.currentValue,v,""),u);e.push(N(f+m+g+y,t));}if(n>0||s<r.length){let c=` (${this.selectedIndex+1}/${r.length})`;e.push(this.theme.hint(N(c,t-2,"")));}let a=r[this.selectedIndex];if(a?.description){e.push("");let c=se(a.description,t-4);for(let h of c)e.push(this.theme.description(` ${h}`));}return this.addHintLine(e,t),e}handleMouse(t){if(this.submenuComponent){let l=this.submenuComponent.handleMouse?.(t);return l?{...l,focus:true}:void 0}if(this.searchEnabled&&this.searchInput){if(t.y===0){let l=this.searchInput.handleMouse?.(t);return l?{...l,focus:true}:void 0}if(t.y===1)return}let e=this.getDisplayItems();if(e.length===0)return;if(t.type==="wheel"&&t.wheelDelta){let l=t.wheelDelta<0?-1:1,a=this.selectedIndex;return this.selectedIndex=Math.max(0,Math.min(e.length-1,this.selectedIndex+l)),{handled:true,render:this.selectedIndex!==a}}if(t.button!=="left"||t.type!=="press"&&t.type!=="click")return;let r=this.searchEnabled?2:0,{startIndex:n,endIndex:s}=this.getVisibleRange(e),o=n+t.y-r;if(!(o<n||o>=s)){if(t.type==="press")return this.mousePressedIndex=o,this.selectedIndex=o,{handled:true,focus:true};if(t.type==="click")return this.selectedIndex=this.mousePressedIndex??o,this.mousePressedIndex=void 0,this.activateItem(),{handled:true}}}handleInput(t){if(this.submenuComponent){this.submenuComponent.handleInput?.(t);return}let e=G(),r=this.getDisplayItems();if(e.matches(t,"tui.select.up")){if(r.length===0)return;this.selectedIndex=this.selectedIndex===0?r.length-1:this.selectedIndex-1;}else if(e.matches(t,"tui.select.down")){if(r.length===0)return;this.selectedIndex=this.selectedIndex===r.length-1?0:this.selectedIndex+1;}else e.matches(t,"tui.select.confirm")||t===" "&&(!this.searchEnabled||this.searchInput?.getValue().length===0)?this.activateItem():e.matches(t,"tui.select.cancel")?this.onCancel():this.searchEnabled&&this.searchInput&&(this.searchInput.handleInput(t),this.applyFilter(this.searchInput.getValue()));}getDisplayItems(){return this.searchEnabled?this.filteredItems:this.items}getVisibleRange(t){let e=Math.max(0,Math.min(this.selectedIndex-Math.floor(this.maxVisible/2),t.length-this.maxVisible));return {startIndex:e,endIndex:Math.min(e+this.maxVisible,t.length)}}activateItem(){let t=this.getDisplayItems()[this.selectedIndex];if(t){if(t.submenu)this.submenuItemIndex=this.selectedIndex,this.submenuComponent=t.submenu(t.currentValue,(e,r)=>{e!==void 0&&(t.currentValue=e,this.onChange(t.id,e)),r?.navigateTo&&(this.navigateAfterClose=r.navigateTo),this.closeSubmenu();});else if(t.values&&t.values.length>0){let r=(t.values.indexOf(t.currentValue)+1)%t.values.length,n=t.values[r];t.currentValue=n,this.onChange(t.id,n);}}}closeSubmenu(){if(this.submenuComponent=null,this.navigateAfterClose!==null){let t=this.navigateAfterClose;this.navigateAfterClose=null,this.submenuItemIndex=null,this.selectItem(t),this.activateItem();}else this.submenuItemIndex!==null&&(this.selectedIndex=this.submenuItemIndex,this.submenuItemIndex=null);}applyFilter(t){this.filteredItems=Re(this.items,t,e=>e.label),this.selectedIndex=0;}addHintLine(t,e){t.push(""),t.push(N(this.theme.hint(this.searchEnabled?" Type to search \xB7 Enter/Space to change \xB7 Esc to cancel":" Enter/Space to change \xB7 Esc to cancel"),e));}};var hi=class{constructor(t=1){d(this,"lines");this.lines=t;}setLines(t){this.lines=t;}invalidate(){}render(t){let e=[];for(let r=0;r<this.lines;r++)e.push("");return e}};var di=class{constructor(t,e=0,r=0){d(this,"text");d(this,"paddingX");d(this,"paddingY");this.text=t,this.paddingX=e,this.paddingY=r;}invalidate(){}render(t){let e=[],r=" ".repeat(t);for(let b=0;b<this.paddingY;b++)e.push(r);let n=Math.max(1,t-this.paddingX*2),s=this.text,o=this.text.indexOf(`
40
- `);o!==-1&&(s=this.text.substring(0,o));let l=N(s,n),a=" ".repeat(this.paddingX),c=" ".repeat(this.paddingX),h=a+l+c,u=S(h),p=Math.max(0,t-u),f=h+" ".repeat(p);e.push(f);for(let b=0;b<this.paddingY;b++)e.push(r);return e}};var pi=class extends Xe{constructor(e=[],r={}){super(e,r);d(this,"layoutType","vstack");}render(e){let r={width:Math.max(1,e),height:Number.MAX_SAFE_INTEGER},n=Qe(this.entries,r),s=n.map(a=>a.component.render(r.width)),o=Ce(n,s.map(a=>a.length),void 0,this.gap),l=[];for(let a=0;a<n.length;a++){if(a>0)for(let h=0;h<this.gap;h++)l.push("");let c=s[a].slice(0,o[a]);l.push(...c);for(let h=c.length;h<o[a];h++)l.push("");}return l}};var fi=class{constructor(t=80,e=24){d(this,"writes",[]);d(this,"inputHandler");d(this,"resizeHandler");d(this,"programStatuses",[]);d(this,"progressStates",[]);d(this,"_columns");d(this,"_rows");d(this,"_kittyActive",false);this._columns=t,this._rows=e;}start(t,e){this.inputHandler=t,this.resizeHandler=e;}async drainInput(t,e){}stop(){this.inputHandler=void 0,this.resizeHandler=void 0;}write(t){this.writes.push(t);}get columns(){return this._columns}get rows(){return this._rows}get kittyProtocolActive(){return this._kittyActive}setColumns(t){this._columns=t;}setRows(t){this._rows=t;}feedInput(t){this.inputHandler?.(t);}resize(t,e){this._columns=t,this._rows=e,this.resizeHandler?.();}moveBy(t){t>0?this.write(`\x1B[${t}B`):t<0&&this.write(`\x1B[${-t}A`);}hideCursor(){this.write("\x1B[?25l");}showCursor(){this.write("\x1B[?25h");}clearLine(){this.write("\x1B[K");}clearFromCursor(){this.write("\x1B[J");}clearScreen(){this.write("\x1B[2J\x1B[H");}setTitle(t){this.write(`\x1B]0;${t}\x07`);}setProgramStatus(t){this.programStatuses.push(t);}setProgress(t){this.progressStates.push(t);}output(){return this.writes.join("")}};var nl=createRequire(import.meta.url),sl="@earendil-works/pi-tui";function Zn(i,t={}){let e=dirname(fileURLToPath(t.moduleUrl??import.meta.url)),r=[];r.push(join(e,"..",i)),r.push(join(e,"..","dist","assets","node",i));try{let n=(t.resolvePackage??nl.resolve)(sl);r.push(join(dirname(n),"..",i));}catch{}return r.push(join(e,i),join(dirname(t.execPath??process.execPath),i)),Array.from(new Set(r))}var al=createRequire(import.meta.url),ir=new Map;function es(i,t=""){let e=process.arch;if(e!=="x64"&&e!=="arm64")return;let r=Ae.join("native",i,"prebuilds",`${i}-${e}`,`${i}-platform${t}.node`);if(ir.has(r))return ir.get(r);for(let n of Zn(r))try{let s=al(n);if(typeof s?.getText=="function"&&typeof s.getImage=="function")return ir.set(r,s),s}catch{}ir.set(r,void 0);}function xt(){if(!(process.platform!=="darwin"&&process.platform!=="win32"))return es(process.platform)}function ll(){if(process.platform!=="linux")return xt();if(process.env.DISPLAY)return es("linux","-x11")}function gi(i){let t=xt();if(!t?.isModifierPressed)return false;try{return t.isModifierPressed(i)===!0}catch{return false}}var ts="\x1B]7501;?\x1B\\";function rs(i){return /^\x1b\]7501;\?[^\x07\x1b]*(?:\x07|\x1b\\)$/.test(i)}var cl=/^[A-Za-z0-9_.+-]{1,32}$/,ul=/[\u0000-\u001f\u007f-\u009f]+/g,hl=2048;function dl(i,t){if(Buffer.byteLength(i,"utf8")<=t)return i;let e=0,r=0;for(let n of i){let s=Buffer.byteLength(n,"utf8");if(e+s>t)break;e+=s,r+=n.length;}return i.slice(0,r)}function yt(i){let t=[`state=${i.state}`];i.app!==void 0&&cl.test(i.app)&&t.push(`app=${i.app}`),i.state==="blocked"&&i.kind&&t.push(`kind=${i.kind}`);let e=dl((i.message??"").replace(ul," ").trim(),hl);return e&&t.push(`msg=${Buffer.from(e,"utf8").toString("base64")}`),`\x1B]7501;${t.join(":")}\x1B\\`}var z="\x1B",fl=50,ml=10,is="\x1B[200~",nr="\x1B[201~",ss=/^\x1b(?:\](?:1[01];|4;\d{1,3};|7501;\?)|P>\||_G(?:[a-z]=\d+,)*[a-z]=\d+;)/;function os(i){return i.startsWith(`${z}]`)||i.startsWith(`${z}P`)||i.startsWith(`${z}_`)}function gl(i){if(!i.startsWith(z))return "not-escape";if(i.length===1)return "incomplete";let t=i.slice(1);return t.startsWith("[")?t.startsWith("[M")?i.length>=6?"complete":"incomplete":bl(i):t.startsWith("]")?xl(i):t.startsWith("P")?yl(i):t.startsWith("_")?vl(i):t.startsWith("O")?t.length>=2?"complete":"incomplete":(t.length===1,"complete")}function bl(i){if(!i.startsWith(`${z}[`))return "complete";if(i.length<3)return "incomplete";let t=i.slice(2),e=t[t.length-1],r=e.charCodeAt(0);if(r>=64&&r<=126){if(t.startsWith("<")){if(/^<\d+;\d+;\d+[Mm]$/.test(t))return "complete";if(e==="M"||e==="m"){let s=t.slice(1,-1).split(";");if(s.length===3&&s.every(o=>/^\d+$/.test(o)))return "complete"}return "incomplete"}return "complete"}return "incomplete"}function xl(i){return !i.startsWith(`${z}]`)||i.endsWith(`${z}\\`)||i.endsWith("\x07")?"complete":"incomplete"}function yl(i){return !i.startsWith(`${z}P`)||i.endsWith(`${z}\\`)?"complete":"incomplete"}function vl(i){return !i.startsWith(`${z}_`)||i.endsWith(`${z}\\`)?"complete":"incomplete"}function Sl(i){let t=i.match(/^\x1b\[(\d+)(?::\d*)?(?::\d+)?u$/);if(!t)return;let e=parseInt(t[1],10);return e>=32?e:void 0}function ns(i){let t=[],e=0;for(;e<i.length;){let r=i.slice(e);if(r.startsWith(z)){let n=os(r)&&ss.test(r),s=1;for(;s<=r.length;){if(n&&s>2){let a=r[s-1];if(a===""||a===""){e+=s;break}if(a===z&&s<r.length&&r[s]!=="\\"){e+=s-1;break}}let o=r.slice(0,s),l=gl(o);if(l==="complete"){if(o==="\x1B\x1B"){let a=r[s];if(a==="["||a==="]"||a==="O"||a==="P"||a==="_"){t.push(z),e+=1;break}}t.push(o),e+=s;break}else if(l==="incomplete")s++;else {t.push(o),e+=s;break}}if(s>r.length)return {sequences:t,remainder:r}}else t.push(r[0]),e++;}return {sequences:t,remainder:""}}var vt=class extends EventEmitter{constructor(e={}){super();d(this,"buffer","");d(this,"timeout",null);d(this,"timeoutMs");d(this,"escapeTimeoutMs");d(this,"pasteMode",false);d(this,"pasteBuffer","");d(this,"pendingKittyPrintableCodepoint");this.timeoutMs=e.timeout??fl,this.escapeTimeoutMs=e.escapeTimeout??ml;}process(e){this.timeout&&(clearTimeout(this.timeout),this.timeout=null);let r;if(Buffer.isBuffer(e))if(e.length===1&&e[0]>127){let o=e[0]-128;r=`\x1B${String.fromCharCode(o)}`;}else r=e.toString();else r=e;if(r.length===0&&this.buffer.length===0){this.emitDataSequence("");return}if(this.buffer+=r,this.pasteMode){this.pasteBuffer+=this.buffer,this.buffer="";let o=this.pasteBuffer.indexOf(nr);if(o!==-1){let l=this.pasteBuffer.slice(0,o),a=this.pasteBuffer.slice(o+nr.length);this.pasteMode=false,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0,this.emit("paste",l),a.length>0&&this.process(a);}return}let n=this.buffer.indexOf(is);if(n!==-1){if(n>0){let l=this.buffer.slice(0,n),a=ns(l);for(let c of a.sequences)this.emitDataSequence(c);}this.pendingKittyPrintableCodepoint=void 0,this.buffer=this.buffer.slice(n+is.length),this.pasteMode=true,this.pasteBuffer=this.buffer,this.buffer="";let o=this.pasteBuffer.indexOf(nr);if(o!==-1){let l=this.pasteBuffer.slice(0,o),a=this.pasteBuffer.slice(o+nr.length);this.pasteMode=false,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0,this.emit("paste",l),a.length>0&&this.process(a);}return}let s=ns(this.buffer);this.buffer=s.remainder;for(let o of s.sequences)this.emitDataSequence(o);if(this.buffer.length>0){if(ss.test(this.buffer))return;let o=this.buffer===z?this.escapeTimeoutMs:this.timeoutMs;this.timeout=setTimeout(()=>{let l=this.flush();for(let a of l)a.length>2&&os(a)?(this.emitDataSequence(a.slice(0,2)),this.process(a.slice(2))):this.emitDataSequence(a);},o);}}emitDataSequence(e){let r=e.length===1?e.codePointAt(0):void 0;if(r!==void 0&&r===this.pendingKittyPrintableCodepoint){this.pendingKittyPrintableCodepoint=void 0;return}this.pendingKittyPrintableCodepoint=Sl(e),this.emit("data",e);}flush(){if(this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.buffer.length===0)return [];let e=[this.buffer];return this.buffer="",this.pendingKittyPrintableCodepoint=void 0,e}clear(){this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.buffer="",this.pasteMode=false,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0;}getBuffer(){return this.buffer}destroy(){this.clear();}};var Cl=1e3,as="\x1B]9;4;3\x07",ls="\x1B]9;4;0\x07",wl="\x1B[13;2u",Tl=7,Ml=150,Il=`\x1B[>${Tl}u\x1B[?u`,Ll="\x1B[c";function cs(i){let t=i.match(/^\x1b\[\?(\d+)u$/);if(t)return {type:"kitty-flags",flags:Number.parseInt(t[1],10)};if(/^\x1b\[\?[\d;]*c$/.test(i))return {type:"device-attributes"}}function us(i){return i==="\x1B["||/^\x1b\[\?[\d;]*$/.test(i)}function ds(){return process.platform==="darwin"&&process.env.TERM_PROGRAM==="Apple_Terminal"}function kl(){if(!(process.platform==="win32"||process.pid<=0))try{process.kill(process.pid,"SIGWINCH");}catch{}}function Al(i,t,e){return t&&i==="\r"&&e?wl:i}var Rl=10,El=100;function Pl(i=process.env){let t=Number(i.PI_TUI_ESC_TIMEOUT);return Number.isFinite(t)&&t>0?t:i.SSH_CONNECTION||i.SSH_TTY?El:Rl}var bi=class{constructor(){d(this,"wasRaw",false);d(this,"inputHandler");d(this,"resizeHandler");d(this,"_kittyProtocolActive",false);d(this,"_modifyOtherKeysActive",false);d(this,"keyboardProtocolPushed",false);d(this,"pendingKeyboardProtocolDeviceAttributes",0);d(this,"keyboardProtocolNegotiationBuffer","");d(this,"keyboardProtocolBufferFlushTimer");d(this,"stdinBuffer");d(this,"stdinDataHandler");d(this,"progressInterval");d(this,"programStatus");d(this,"programStatusSupported",false);d(this,"programStatusQueryPending",false);d(this,"writeLogPath",(()=>{let t=process.env.PI_TUI_WRITE_LOG||"";if(!t)return "";try{if(fe.statSync(t).isDirectory()){let e=new Date,r=`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")}_${String(e.getHours()).padStart(2,"0")}-${String(e.getMinutes()).padStart(2,"0")}-${String(e.getSeconds()).padStart(2,"0")}`;return Ae.join(t,`tui-${r}-${process.pid}.log`)}}catch{}return t})());}get kittyProtocolActive(){return this._kittyProtocolActive}get modifyOtherKeysActive(){return this._modifyOtherKeysActive}start(t,e){this.inputHandler=t,this.resizeHandler=e,this.wasRaw=process.stdin.isRaw||false,process.stdin.setRawMode&&process.stdin.setRawMode(true),process.stdin.setEncoding("utf8"),process.stdin.resume(),process.stdout.write("\x1B[?2004h"),process.stdout.on("resize",this.resizeHandler),kl(),this.enableWindowsVTInput(),this.queryAndEnableKittyProtocol();}setupStdinBuffer(){this.stdinBuffer=new vt({escapeTimeout:Pl()}),this.stdinBuffer.on("data",t=>{if(rs(t)){this.programStatusQueryPending&&(this.programStatusQueryPending=false,this.programStatusSupported=true,this.writeProgramStatus());return}let e=this.readKeyboardProtocolNegotiationSequence(t);if(e==="pending"){this.scheduleKeyboardProtocolNegotiationBufferFlush();return}e&&this.handleKeyboardProtocolNegotiationSequence(e.parsed)||this.forwardInputSequence(e?.sequence??t);}),this.stdinBuffer.on("paste",t=>{this.inputHandler&&this.inputHandler(`\x1B[200~${t}\x1B[201~`);}),this.stdinDataHandler=t=>{this.stdinBuffer.process(t);};}queryAndEnableKittyProtocol(){this.setupStdinBuffer(),process.stdin.on("data",this.stdinDataHandler),this.keyboardProtocolPushed=true,this.pendingKeyboardProtocolDeviceAttributes+=1,this.clearKeyboardProtocolNegotiationBuffer();let t=process.env.PI_PROGRAM_STATUS;this.programStatusSupported=t==="1",this.programStatusQueryPending=t!=="1"&&t!=="0";let e=this.programStatusQueryPending?ts:"";process.stdout.write(`${Il}${e}${Ll}`),this.writeProgramStatus();}handleKeyboardProtocolNegotiationSequence(t){if(this.clearKeyboardProtocolNegotiationBuffer(),t.type==="device-attributes"){if(this.pendingKeyboardProtocolDeviceAttributes===0)return false;this.pendingKeyboardProtocolDeviceAttributes-=1,this.pendingKeyboardProtocolDeviceAttributes===0&&(this.programStatusQueryPending=false);}return t.type==="kitty-flags"?(t.flags!==0?(this.disableModifyOtherKeys(),this._kittyProtocolActive||(this._kittyProtocolActive=true,at(true))):this.enableModifyOtherKeys(),true):(this._kittyProtocolActive||this.enableModifyOtherKeys(),true)}readKeyboardProtocolNegotiationSequence(t){if(this.keyboardProtocolNegotiationBuffer){let r=this.keyboardProtocolNegotiationBuffer+t,n=cs(r);if(n)return this.clearKeyboardProtocolNegotiationBuffer(),{parsed:n,sequence:r};if(us(r))return this.setKeyboardProtocolNegotiationBuffer(r),"pending";this.flushKeyboardProtocolNegotiationBufferAsInput();}let e=cs(t);if(e)return {parsed:e,sequence:t};if(us(t))return this.setKeyboardProtocolNegotiationBuffer(t),"pending"}setKeyboardProtocolNegotiationBuffer(t){this.clearKeyboardProtocolNegotiationBufferFlushTimer(),this.keyboardProtocolNegotiationBuffer=t;}clearKeyboardProtocolNegotiationBuffer(){this.clearKeyboardProtocolNegotiationBufferFlushTimer(),this.keyboardProtocolNegotiationBuffer="";}flushKeyboardProtocolNegotiationBufferAsInput(){if(!this.keyboardProtocolNegotiationBuffer)return;let t=this.keyboardProtocolNegotiationBuffer;this.clearKeyboardProtocolNegotiationBuffer(),this.forwardInputSequence(t);}scheduleKeyboardProtocolNegotiationBufferFlush(){!this.keyboardProtocolNegotiationBuffer||this.keyboardProtocolBufferFlushTimer||(this.keyboardProtocolBufferFlushTimer=setTimeout(()=>{this.keyboardProtocolBufferFlushTimer=void 0,this.flushKeyboardProtocolNegotiationBufferAsInput();},Ml));}clearKeyboardProtocolNegotiationBufferFlushTimer(){this.keyboardProtocolBufferFlushTimer&&(clearTimeout(this.keyboardProtocolBufferFlushTimer),this.keyboardProtocolBufferFlushTimer=void 0);}forwardInputSequence(t){if(!this.inputHandler)return;let e=t==="\r"&&(ds()||process.platform==="win32"),r=Al(t,e,e&&gi("shift"));this.inputHandler(r);}enableModifyOtherKeys(){this._kittyProtocolActive||this._modifyOtherKeysActive||(process.stdout.write("\x1B[>4;2m"),this._modifyOtherKeysActive=true);}disableModifyOtherKeys(){this._modifyOtherKeysActive&&(process.stdout.write("\x1B[>4;0m"),this._modifyOtherKeysActive=false);}enableWindowsVTInput(){if(process.platform==="win32")try{xt()?.enableVirtualTerminalInput?.();}catch{}}async drainInput(t=1e3,e=50){let r=this.keyboardProtocolPushed||this._kittyProtocolActive;this.clearKeyboardProtocolNegotiationBuffer(),r&&(process.stdout.write("\x1B[<u"),this.keyboardProtocolPushed=false,this._kittyProtocolActive=false,at(false)),this.disableModifyOtherKeys();let n=this.inputHandler;this.inputHandler=void 0;let s=Date.now(),o=()=>{s=Date.now();};process.stdin.on("data",o);let l=Date.now()+t;try{for(;;){let a=Date.now(),c=l-a;if(c<=0||a-s>=e)break;await new Promise(h=>setTimeout(h,Math.min(e,c)));}}finally{process.stdin.removeListener("data",o),this.inputHandler=n;}}stop(){this.clearProgressInterval()&&process.stdout.write(ls),this.programStatusSupported&&this.programStatus&&process.stdout.write(yt({state:"clear"})),this.programStatusSupported=false,this.programStatusQueryPending=false,process.stdout.write("\x1B[?2004l");let t=this.keyboardProtocolPushed||this._kittyProtocolActive;this.clearKeyboardProtocolNegotiationBuffer(),t&&(process.stdout.write("\x1B[<u"),this.keyboardProtocolPushed=false,this._kittyProtocolActive=false,at(false)),this.disableModifyOtherKeys(),this.stdinBuffer&&(this.stdinBuffer.destroy(),this.stdinBuffer=void 0),this.stdinDataHandler&&(process.stdin.removeListener("data",this.stdinDataHandler),this.stdinDataHandler=void 0),this.inputHandler=void 0,this.resizeHandler&&(process.stdout.removeListener("resize",this.resizeHandler),this.resizeHandler=void 0),process.stdin.pause(),process.stdin.setRawMode&&process.stdin.setRawMode(this.wasRaw);}write(t){if(process.stdout.write(t),this.writeLogPath)try{fe.appendFileSync(this.writeLogPath,t,{encoding:"utf8"});}catch{}}get columns(){return process.stdout.columns||Number(process.env.COLUMNS)||80}get rows(){return process.stdout.rows||Number(process.env.LINES)||24}moveBy(t){t>0?process.stdout.write(`\x1B[${t}B`):t<0&&process.stdout.write(`\x1B[${-t}A`);}hideCursor(){process.stdout.write("\x1B[?25l");}showCursor(){process.stdout.write("\x1B[?25h");}clearLine(){process.stdout.write("\x1B[K");}clearFromCursor(){process.stdout.write("\x1B[J");}clearScreen(){process.stdout.write("\x1B[2J\x1B[H");}setTitle(t){process.stdout.write(`\x1B]0;${t}\x07`);}setProgramStatus(t){this.programStatus=t.state==="clear"?void 0:t,this.programStatusSupported&&process.stdout.write(yt(t));}writeProgramStatus(){this.programStatusSupported&&this.programStatus&&process.stdout.write(yt(this.programStatus));}setProgress(t){t?(process.stdout.write(as),this.progressInterval||(this.progressInterval=setInterval(()=>{process.stdout.write(as);},Cl))):(this.clearProgressInterval(),process.stdout.write(ls));}clearProgressInterval(){return this.progressInterval?(clearInterval(this.progressInterval),this.progressInterval=void 0,true):false}};var Ol=Pe(),$l=/^[\x20-\x7e]*$/;function _l(i){let t=[],e=[],r=0,n=false,s=()=>{n&&(t.push(" "),r+=1,n=false);};for(let o=0;o<i.length;o++){let l=Ke(i[o]??""),a=0;if($l.test(l)){let c=0;for(;c<l.length;){if(l.charCodeAt(c)===32){r>0&&(n=true),a+=1,c+=1;continue}let h=c+1;for(;h<l.length&&l.charCodeAt(h)!==32;)h+=1;s();let u=l.slice(c,h);t.push(u),e.push({textStart:r,textEnd:r+u.length,row:o,startCol:a,endCol:a+u.length,linearColumns:true}),r+=u.length,a+=u.length,c=h;}}else for(let c of Ol.segment(l)){let h=c.segment,u=S(h);if(/^\s+$/u.test(h)){r>0&&(n=true),a+=u;continue}s(),t.push(h),e.push({textStart:r,textEnd:r+h.length,row:o,startCol:a,endCol:a+u,linearColumns:false}),r+=h.length,a+=u;}r>0&&(n=true);}return {text:t.join(""),spans:e}}function Kl(i){return i.replace(/\s+/gu," ").trim()}function Bl(i){return i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Dl(i,t){if(!t)return [];let e=new RegExp(Bl(t),"giu"),r=[],n=0;for(let s of i.text.matchAll(e)){let o=s.index,l=o+s[0].length;for(;n<i.spans.length&&i.spans[n].textEnd<=o;)n+=1;let a=[];for(let c=n;c<i.spans.length;c++){let h=i.spans[c];if(h.textStart>=l)break;if(h.textEnd<=o)continue;let u=h.linearColumns?h.startCol+Math.max(o,h.textStart)-h.textStart:h.startCol,p=h.linearColumns?h.startCol+Math.min(l,h.textEnd)-h.textStart:h.endCol,f=a[a.length-1];f&&f.row===h.row&&u<=f.endCol?f.endCol=Math.max(f.endCol,p):a.push({row:h.row,startCol:u,endCol:p});}for(;n<i.spans.length&&i.spans[n].textEnd<=l;)n+=1;a.length>0&&r.push({segments:a});}return r}var or=class{constructor(){d(this,"sourceLines");d(this,"corpus");d(this,"normalizedQuery");d(this,"matches",[]);}search(t,e){let r=this.sourceLines?.length!==t.length;if(!r&&this.sourceLines){for(let o=0;o<t.length;o++)if(this.sourceLines[o]!==t[o]){r=true;break}}(r||!this.corpus)&&(this.sourceLines=Array.from(t),this.corpus=_l(t));let n=Kl(e),s=r||n!==this.normalizedQuery;return s&&(this.normalizedQuery=n,this.matches=Dl(this.corpus,n)),{matches:this.matches,changed:s}}};function xi(i){let t=i.segments[0],e=i.segments[i.segments.length-1];return t&&e?`${t.row}:${t.startCol}:${e.row}:${e.endCol}`:""}var ar=class{constructor(t,e=r=>r){d(this,"input",new Me({prompt:" ",placeholder:"Find in transcript",placeholderStyle:t=>`\x1B[2m${t}\x1B[22m`}));d(this,"onQueryChange");d(this,"navigationButtonStyle");d(this,"resultCount",0);d(this,"resultIndex",-1);d(this,"previousButtonStart",-1);d(this,"previousButtonEnd",-1);d(this,"nextButtonStart",-1);d(this,"nextButtonEnd",-1);d(this,"hoveredNavigationDirection");d(this,"_focused",false);this.onQueryChange=t,this.navigationButtonStyle=e;}get focused(){return this._focused}set focused(t){this._focused=t,this.input.focused=t;}setResult(t,e){this.resultIndex=t,this.resultCount=e;}getNavigationDirectionAt(t,e){if(t===2){if(e>=this.previousButtonStart&&e<this.previousButtonEnd)return -1;if(e>=this.nextButtonStart&&e<this.nextButtonEnd)return 1}}setHoveredNavigationDirection(t){return t===this.hoveredNavigationDirection?false:(this.hoveredNavigationDirection=t,true)}handleInput(t){let e=this.input.getValue();this.input.handleInput(t);let r=this.input.getValue();r!==e&&this.onQueryChange(r);}invalidate(){this.input.invalidate();}render(t){let e=Math.max(1,t),r=Math.max(0,e-2),n=D=>D?D.split("+").map(K=>process.platform==="darwin"&&K.toLowerCase()==="alt"?"Option":K.charAt(0).toUpperCase()+K.slice(1)).join("+"):"Unbound",s=G(),o=n(s.getKeys("tui.altScreen.searchPrevious")[0]),l=n(s.getKeys("tui.altScreen.searchNext")[0]),c=this.input.getValue()?this.resultCount===0?"No matches":`${this.resultIndex+1}/${this.resultCount}`:"",h=Math.max(0,r-3),u=N(c,h,""),p=u?`\x1B[2m ${u} \x1B[22m`:"",f=Math.max(0,r-S(p)),b=N(this.input.render(Math.max(1,f))[0]??"",f,""),m=" ".repeat(Math.max(0,f-S(b))),g=`${b}${m}${p}`,x=`\u2191 ${o}`,v=`\u2193 ${l}`,y=" \xB7 ",w=1,I=Math.max(0,r-w*2-1),T=S(x)+S(y)+S(v);T>I&&(x="\u2191",v="\u2193",y=" ",T=S(x)+S(y)+S(v));let L=T<=I,M=L?this.navigationButtonStyle(x,this.hoveredNavigationDirection===-1)+y+this.navigationButtonStyle(v,this.hoveredNavigationDirection===1):"",E=L?w*2:0,P=M&&r>T+E?1:0,C=Math.max(0,r-(L?T:0)-E-P),A=1+C+w;return this.previousButtonStart=L?A:-1,this.previousButtonEnd=L?A+S(x):-1,this.nextButtonStart=L?this.previousButtonEnd+S(y):-1,this.nextButtonEnd=L?this.nextButtonStart+S(v):-1,e===1?["\u250C","\u2502","\u2514"]:[`\u250C${"\u2500".repeat(r)}\u2510`,`\u2502${g}\u2502`,`\u2514${"\u2500".repeat(C)}${M?" ":""}${M}${M?" ":""}${"\u2500".repeat(P)}\u2518`]}};var Nl=1e3,lr=class{constructor(t){d(this,"entries",[]);d(this,"nextId",0);d(this,"requestRender");this.requestRender=t;}flash(t,e=Nl){let r=this.nextId++,n=setTimeout(()=>{let s=this.entries.findIndex(o=>o.id===r);s!==-1&&(this.entries.splice(s,1),this.requestRender());},Math.max(0,e));n.unref(),this.entries.push({id:r,message:t,timer:n}),this.requestRender();}dispose(){for(let t of this.entries)clearTimeout(t.timer);this.entries.length=0;}invalidate(){}render(t){return this.entries.map(e=>`\x1B[7m${N(` ${e.message} `,t,"")}\x1B[27m`)}};var Fl=/^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/;function St(i,t){let e=Math.max(i.x,t.x),r=Math.max(i.y,t.y),n=Math.min(i.x+i.width,t.x+t.width),s=Math.min(i.y+i.height,t.y+t.height);return {x:e,y:r,width:Math.max(0,n-e),height:Math.max(0,s-r)}}function ur(i,t,e){let r=Math.max(1,Math.floor(e)),n=i.renderCache.get(t);n||(n=new Map,i.renderCache.set(t,n));let s=n.get(r);return s||(s=t.render(r),n.set(r,s)),s}function ps(i,t,e){return ur(i,t,e).length}function Wl(i,t,e){return ur(i,t,e).reduce((r,n)=>Math.max(r,S(n)),0)}function fs(i,t){return i.parent=t,i}function ms(i,t){i.rect.y+=t;for(let e of i.children)ms(e,t);}function gs(i,t){i.clip=St(t,i.rect);for(let e of i.children)gs(e,i.clip);}function cr(i,t,e,r,n,s,o){let l=Math.max(1,Math.floor(n)),a=Jt(t);if(!a){let v=ur(i,t,l),y=s===void 0?v.length:Math.max(0,Math.floor(s)),w=0;if(v.length>y&&y>0){let I=v.findIndex(T=>T.includes(ie));I>=y&&(w=I-y+1);}return {component:t,rect:{x:e,y:r,width:l,height:y},clip:St(o,{x:e,y:r,width:l,height:y}),children:[],lines:v,lineOffset:w,layer:0}}if(a.type==="scroll"){let v=a.state.scrollTop,y=a.state.getContentWidth(l),w=cr(i,a.component,e,r-v,y,void 0,o),I=w.rect.height,T=s===void 0?I:Math.max(0,Math.floor(s));a.state.updateLayout(I,T,i.requestRender),ms(w,v-a.state.scrollTop);let L=a.state;(a.state.primary||!i.primaryScrollView)&&(i.primaryScrollView=L);let M={x:e,y:r,width:l,height:T},E=St(o,M),P={component:t,rect:M,clip:E,children:[w],scrollView:L,scrollContentLines:ur(i,a.component,y),layer:0};return w.parent=P,gs(w,E),P}let c=Qe(a.entries,i.viewport),h=Math.max(0,c.length-1)*a.gap;if(a.type==="vstack"){let v=c.map(E=>typeof E.basis=="number"?E.basis:ps(i,E.component,l)),y=Ce(c,v,s,a.gap),w=y.reduce((E,P)=>E+P,0)+h,I=s===void 0?w:Math.max(0,Math.floor(s)),T={x:e,y:r,width:l,height:I},L={component:t,rect:T,clip:St(o,T),children:[],layer:0},M=r;for(let E=0;E<c.length;E++)L.children.push(fs(cr(i,c[E].component,e,M,l,y[E],L.clip),L)),M+=y[E]+a.gap;return L}let u=c.map(v=>typeof v.basis=="number"?v.basis:Wl(i,v.component,l)),p=Ce(c,u,l,a.gap),f=c.map((v,y)=>ps(i,v.component,Math.max(1,p[y]))),b=s===void 0?f.reduce((v,y)=>Math.max(v,y),0):Math.max(0,s),m={x:e,y:r,width:l,height:b},g={component:t,rect:m,clip:St(o,m),children:[],layer:0},x=e;for(let v=0;v<c.length;v++){let y=f[v],w=a.align==="stretch"?b:Math.min(b,y),I=r;a.align==="center"?I+=Math.floor((b-w)/2):a.align==="end"&&(I+=b-w);let T=p[v];T===0?g.children.push({component:c[v].component,rect:{x,y:I,width:0,height:w},clip:{x,y:I,width:0,height:0},children:[],parent:g,layer:0}):g.children.push(fs(cr(i,c[v].component,x,I,T,w,g.clip),g)),x+=T+a.gap;}return g}function Vl(i,t,e,r,n){if(F(i))return i;let s=rt(i,t),o=s?.start??t,l=s?.end??t+1,a=V(i,0,o,true),c=V(i,o,l-o,true),h=V(i,l,Math.max(0,e-l),true),u="",p=0;for(;p<c.length;){let x=W(c,p);if(!x)break;u+=x.code,p+=x.length;}let f=" ".repeat(Math.max(0,o-S(a))),b=" ".repeat(Math.max(0,t-o)),m=" ".repeat(Math.max(0,l-t-1)),g=`\x1B[0m\x1B]8;;\x07${n?Ri(u):""}`;return `${a}${f}${g}${b}${r}${m}${h}`}function Je(i,t=false){if(!i.scrollView||i.rect.width<=0||i.rect.height<=0)return;let e=i.children[0]?.rect.height??i.scrollContentLines?.length??0,r=i.rect.height,n=t&&i.scrollView.scrollbar==="auto"&&e>r;if(!i.scrollView.isScrollbarVisible&&!n)return;let s=Math.min(2,r),o=Math.max(s,Math.min(r,Math.round(r*r/e))),l=Math.max(0,e-r),a=r-o,c=l===0?0:Math.round(i.scrollView.scrollTop/l*a),h=i.rect.x+i.rect.width-1;if(!(h<i.clip.x||h>=i.clip.x+i.clip.width))return {column:h,trackTop:i.rect.y,trackHeight:r,thumbTop:i.rect.y+c,thumbHeight:o,maxScrollTop:l}}function Hl(i,t,e){let r=Je(i);if(!(!r||!i.scrollView))for(let n=0;n<r.trackHeight;n++){let s=r.trackTop+n;if(s<i.clip.y||s>=i.clip.y+i.clip.height||s<0||s>=t.length)continue;let l=s>=r.thumbTop&&s<r.thumbTop+r.thumbHeight?i.scrollView.scrollbarThumbStyle(i.scrollView.isScrollbarActive?"\u2588":"\u2503"):i.scrollView.scrollbarTrackStyle("\u2502");t[s]=Vl(t[s]??"",r.column,e,l,i.scrollView.scrollbar!=="always");}}function bs(i,t,e){if(i.lines){let r=i.lineOffset??0,n=Math.max(i.rect.y,i.clip.y,0),s=Math.min(i.rect.y+i.rect.height,i.clip.y+i.clip.height,t.length);for(let o=n;o<s;o++){let l=i.lines[r+o-i.rect.y];if(l===void 0)continue;let a=l.replace(Fl,""),c=Wt(a);if(c){let h=Math.min(t.length,i.clip.y+i.clip.height),u=Math.min(c.rows,h-o);u<c.rows&&(a=Wr(a,0,u));}i.rect.x===0&&i.rect.width>=e&&(F(a)||!t[o])?t[o]=a:t[o]=de(t[o]??"",a,i.rect.x,i.rect.width,e);}}for(let r of i.children)bs(r,t,e);if(i.scrollView&&i.scrollContentLines&&i.scrollView.scrollTop>0&&i.rect.height>0)for(let r=i.scrollView.scrollTop-1;r>=0;r--){let n=i.scrollContentLines[r]??"",s=Wt(n);if(s){let o=i.scrollView.scrollTop-r;if(o<s.rows){let l=Math.min(i.rect.height,s.rows-o),a=Wr(n,o,l);i.rect.x===0&&i.rect.width>=e&&(t[i.rect.y]=a);}break}if(n!=="")break}Hl(i,t,e);}function vi(i,t,e,r){let n=Math.max(1,Math.floor(t)),s=Math.max(1,Math.floor(e)),o={viewport:{width:n,height:s},renderCache:new Map,requestRender:r,primaryScrollView:void 0},l=cr(o,i,0,0,n,s,{x:0,y:0,width:n,height:s}),a=Array.from({length:s},()=>"");return bs(l,a,n),{root:l,width:n,height:s,lines:a,...o.primaryScrollView===void 0?{}:{primaryScrollView:o.primaryScrollView}}}function yi(i,t,e){return t>=i.x&&t<i.x+i.width&&e>=i.y&&e<i.y+i.height}function xs(i,t,e){let r=[],n=(s,o)=>{if(yi(s.clip,t,e)){r.push({box:s,depth:o});for(let l of s.children)n(l,o+1);}};return n(i.root,0),r.sort((s,o)=>o.box.layer-s.box.layer||o.depth-s.depth),r.map(({box:s})=>s)}function ne(i,t){let e=r=>{if(r.scrollView===t)return r;for(let n of r.children){let s=e(n);if(s)return s}};return e(i.root)}function hr(i,t,e){let r=[],n=(s,o)=>{if(yi(s.clip,t,e)){s.scrollView&&yi(s.rect,t,e)&&r.push({scrollView:s.scrollView,depth:o});for(let l of s.children)n(l,o+1);}};return n(i.root,0),r.sort((s,o)=>o.depth-s.depth),r.map(s=>s.scrollView)}function Ul(){let i=process.env;return process.platform==="darwin"&&i.SSH_CONNECTION===void 0&&i.SSH_CLIENT===void 0&&i.SSH_TTY===void 0}var dr=class{constructor(t="auto",e=!Ul()){d(this,"lines");d(this,"accelerate");d(this,"lastTime",Number.NEGATIVE_INFINITY);d(this,"lastDirection",0);d(this,"averageGap");d(this,"carry",0);this.lines=t,this.accelerate=e;}setLines(t){this.lines=t,this.reset();}next(t,e){if(this.lines!=="auto")return Number.isFinite(this.lines)?Math.max(1,Math.floor(this.lines)):1;if(!this.accelerate)return 1;let r=e-this.lastTime,n=t===this.lastDirection&&r<=200;if(this.lastTime=e,this.lastDirection=t,!n)return this.averageGap=void 0,this.carry=0,1;if(r<5)return 1;this.averageGap=this.averageGap===void 0?r:(this.averageGap+r)/2;let s=Math.min(6,Math.max(1,100/this.averageGap))+this.carry,o=Math.floor(s);return this.carry=s-o,o}reset(){this.lastTime=Number.NEGATIVE_INFINITY,this.lastDirection=0,this.averageGap=void 0,this.carry=0;}};var ql="\x1B[?1049h",ys="\x1B[?1049l",vs="\x1B[?7l",Ss="\x1B[?7h",Gl="\x1B[?1000h\x1B[?1002h\x1B[?1004h\x1B[?1006h",zl="\x1B[?1000h\x1B[?1002h\x1B[?1003h\x1B[?1004h\x1B[?1006h",Yl="\x1B[?1006l\x1B[?1004l\x1B[?1003l\x1B[?1002l\x1B[?1000l",jl="\x1B[I",Xl="\x1B[O",pr="\x1B[?2026h",fr="\x1B[?2026l",Cs=/^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/,Ql=/^\x1b\]133;A(?:\x07|\x1b\\)/,ws=4,Zl=5,Jl=16,ec=32*1024*1024,tc=64*1024*1024,Ts=500,rc=5e3,ic=new Set(["/","-"]),nc=Oe(),Ms,Is,Si=class extends(Is=qe,Ms=zr,Is){constructor(e,r,n,s={}){super(e,r,n);d(this,"mode","fullscreen");d(this,Ms,true);d(this,"previousScreen",[]);d(this,"lastDocument",[]);d(this,"previousScreenWidth",0);d(this,"previousScreenHeight",0);d(this,"layoutRoot");d(this,"currentLayout");d(this,"implicitDocument");d(this,"implicitScrollView");d(this,"flashes");d(this,"altScreenActive",false);d(this,"imageProtocol",null);d(this,"savedCapabilities");d(this,"uploadedKittyImages",new Map);d(this,"selectionAnchor");d(this,"selectionFocus");d(this,"selectionGranularity","character");d(this,"selectionInitialRange");d(this,"lastClick");d(this,"selectionDragPointer");d(this,"selectionAutoScrollDirection",0);d(this,"selectionAutoScrollTimer");d(this,"selectionPressActive",false);d(this,"scrollbarDrag");d(this,"scrollbarHover");d(this,"scrollToEndIndicatorRect");d(this,"activeSearch");d(this,"pressedUrl");d(this,"selectionDragged",false);d(this,"mouseCapture");d(this,"mousePressTarget");d(this,"mousePressPoint");d(this,"mousePressMoved",false);d(this,"lastComponentClick");d(this,"wheelScroll");d(this,"mouseEnabled");d(this,"searchMatchStyle");d(this,"searchCurrentMatchStyle");d(this,"searchNavigationButtonStyle");d(this,"scrollToEndIndicator");d(this,"openUrl");d(this,"onRightClickPaste");d(this,"copyOnSelect");d(this,"copySelection");this.implicitDocument={render:o=>super.render(o),handleMouse:o=>super.handleMouse(o),invalidate:()=>{for(let o of this.children)o.invalidate();}},this.implicitScrollView=new gt(this.implicitDocument,{follow:"end",primary:true}),this.flashes=new lr(()=>this.requestRender()),this.wheelScroll=new dr(s.wheelScrollLines??1),this.mouseEnabled=s.mouse??true,this.searchMatchStyle=s.searchMatchStyle??(o=>`\x1B[4m${o}\x1B[24m`),this.searchCurrentMatchStyle=s.searchCurrentMatchStyle??(o=>`\x1B[1;7m${o}\x1B[22;27m`),this.searchNavigationButtonStyle=s.searchNavigationButtonStyle??(o=>o),this.scrollToEndIndicator=s.scrollToEndIndicator,this.openUrl=s.openUrl,this.onRightClickPaste=s.onRightClickPaste,this.copyOnSelect=s.copyOnSelect??true,this.copySelection=s.copySelection,this.addInputListener(o=>this.handleViewportInput(o));}get viewportTop(){return this.getPrimaryScrollView().scrollTop}get isFollowingOutput(){return this.getPrimaryScrollView().isFollowingEnd}setWheelScrollLines(e){this.wheelScroll.setLines(e);}getCopyOnSelect(){return this.copyOnSelect}setCopyOnSelect(e){this.copyOnSelect=e;}hasActiveSelection(){return this.getActiveSelectionText()!==void 0}async copyActiveSelectionToClipboard(){let e=this.getActiveSelectionText();return e?this.copyTextToClipboard(e):false}resetTextSelection(){this.clearTextSelection(),this.lastClick=void 0;}getScreenLines(){return [...this.previousScreen]}setLayoutRoot(e){this.layoutRoot!==e&&(this.layoutRoot=e,this.currentLayout=void 0,this.requestRender());}render(e){return this.layoutRoot?.render(e)??super.render(e)}getMountedRoots(){return this.layoutRoot?[this.layoutRoot]:this.children}getPrimaryScrollView(){return this.currentLayout?.primaryScrollView??this.implicitScrollView}beforeTerminalStart(){this.stopSelectionAutoScroll(),this.selectionPressActive=false,this.stopScrollbarHover(),this.stopScrollbarDrag(),this.flashes.dispose(),this.altScreenActive=true;let e=re();this.imageProtocol=e.images,this.uploadedKittyImages.clear(),e.images==="iterm2"&&(this.savedCapabilities=e,Ft({...e,images:null}),this.invalidate()),this.lastDocument=[],this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,this.lastClick=void 0,this.pressedUrl=void 0,this.selectionDragged=false,this.clearComponentMouseGesture(),this.lastComponentClick=void 0,this.resetRenderState();let r=process.env.TERM?.toLowerCase()??"",n=process.env.TMUX!==void 0||process.env.ZELLIJ!==void 0||process.env.STY!==void 0||r.startsWith("tmux")||r.startsWith("screen")?Gl:zl;this.terminal.write(`${ql}${vs}${this.mouseEnabled?n:""}\x1B[2J\x1B[H\x1B[?25l`);}beforeTerminalStop(e){this.closeSearch(),this.stopSelectionAutoScroll(),this.selectionPressActive=false,this.stopScrollbarHover(),this.stopScrollbarDrag(),this.clearComponentMouseGesture(),this.flashes.dispose(),this.altScreenActive&&(this.terminal.write(`${pr}${this.deleteKittyImages()}${this.mouseEnabled?Yl:""}${Ss}${fr}`),this.uploadedKittyImages.clear());}afterTerminalStop(e){if(this.altScreenActive){if(this.altScreenActive=false,e.preserveScreen)this.terminal.write(`${pr}${ys}\x1B[?25h${fr}`);else {let r=Math.max(1,this.terminal.columns),n=this.resolveFakeCursors(this.render(r)).map(o=>o.replace(Cs,""));this.lastDocument=this.applyLineResets(n.map(o=>o.replaceAll(ie,""))).map(o=>F(o)||S(o)<=r?o:V(o,0,r,true));let s=`${pr}${ys}${vs}`;for(let o=0;o<this.lastDocument.length;o++)o>0&&(s+=`\r
41
- `),s+=`\r\x1B[2K${this.lastDocument[o]??""}`;s+=`\x1B[0m${Ss}\r
42
- \x1B[?25h${fr}`,this.terminal.write(s);}this.savedCapabilities&&(Ft(this.savedCapabilities),this.savedCapabilities=void 0);}}deleteKittyImages(){return this.imageProtocol==="kitty"?Dr():""}prepareKittyScreen(e){let r=new Set,n=e.map(c=>{let h=Tn(c);if(!h)return c;r.add(h.imageId);let u=this.uploadedKittyImages.get(h.imageId),p={transmissionGeneration:h.transmissionGeneration,transmissionBytes:h.transmissionBytes,estimatedDecodedBytes:h.estimatedDecodedBytes};return u&&this.uploadedKittyImages.delete(h.imageId),this.uploadedKittyImages.set(h.imageId,p),u?.transmissionGeneration===h.transmissionGeneration?h.replacementLine:c}),s=0,o=0,l=0;for(let[c,h]of this.uploadedKittyImages)r.has(c)||(s+=1,o+=h.transmissionBytes,l+=h.estimatedDecodedBytes);let a="";for(let[c,h]of this.uploadedKittyImages){if(s<=Jl&&o<=ec&&l<=tc)break;r.has(c)||(a+=ct(c),this.uploadedKittyImages.delete(c),s-=1,o-=h.transmissionBytes,l-=h.estimatedDecodedBytes);}return {lines:n,evictedImageDeletion:a}}resetRenderState(){this.previousScreen=[],this.previousScreenWidth=0,this.previousScreenHeight=0,this.currentLayout=void 0;}scrollBy(e){this.getPrimaryScrollView().scrollBy(e),this.requestRender();}scrollToTop(){this.getPrimaryScrollView().scrollToStart(),this.requestRender();}scrollToBottom(){this.getPrimaryScrollView().scrollToEnd(),this.requestRender();}scrollToPrompt(e){if(!this.currentLayout)return;let r=this.getPrimaryScrollView(),n=ne(this.currentLayout,r)?.scrollContentLines;if(n){for(let s=r.scrollTop+e;s>=0&&s<n.length;s+=e)if(Ql.test(n[s]??"")){r.scrollTo(s),this.requestRender();return}}}toggleSearch(){if(this.activeSearch){this.closeSearch();return}let e=new ar(n=>this.updateSearchQuery(n),this.searchNavigationButtonStyle),r={component:e,index:new or,query:"",matches:[],selectedIndex:-1,anchorRow:this.getPrimaryScrollView().scrollTop,selectionMode:"query"};this.activeSearch=r,r.overlay=this.showOverlay(e,{anchor:"top-right",width:"40%",minWidth:32,margin:1});}closeSearch(){let e=this.activeSearch;e&&(this.activeSearch=void 0,e.overlay?.hide(),this.requestRender());}updateSearchQuery(e){let r=this.activeSearch;if(!r||e===r.query)return;let n=r.matches[r.selectedIndex];r.anchorRow=n?.segments[0]?.row??this.getPrimaryScrollView().scrollTop,r.query=e,r.selectionMode="query",r.component.setResult(-1,0),this.requestRender();}navigateSearch(e){let r=this.activeSearch;r?.query&&(r.selectionMode=e<0?"previous":"next",this.requestRender());}getSearchNavigationDirectionAt(e,r){let n=this.activeSearch,s=n?.overlay?.getBounds();if(!(!n||!s)&&!(e<s.col||e>=s.col+s.width||r<s.row||r>=s.row+s.height))return n.component.getNavigationDirectionAt(r-s.row,e-s.col)}handleSearchMouseEvent(e){let r=this.activeSearch;if(!r)return false;let n=this.getSearchNavigationDirectionAt(e.x,e.y);return r.component.setHoveredNavigationDirection(n)&&this.requestRender(),n===void 0||e.release||(e.button&32)!==0||(e.button&3)!==0?false:(this.navigateSearch(n),true)}refreshSearch(e){let r=this.activeSearch;if(!r)return false;let n=e.primaryScrollView??this.implicitScrollView,s=ne(e,n),o=s?.scrollContentLines;if(!o||!r.query.trim())return r.matches=[],r.selectedIndex=-1,r.selectedKey=void 0,r.selectionMode="retain",r.component.setResult(-1,0),false;let l=r.selectionMode!=="retain",a=r.index.search(o,r.query),c=a.matches;if(r.matches=c,!a.changed&&r.selectionMode==="retain")return false;let h=a.changed?r.selectedKey?c.findIndex(v=>xi(v)===r.selectedKey):-1:r.selectedIndex,u=-1;if(c.length>0)if(r.selectionMode==="query"){let v=0,y=c.length;for(;v<y;){let w=v+Math.floor((y-v)/2);(c[w].segments[0]?.row??0)<r.anchorRow?v=w+1:y=w;}u=v<c.length?v:0;}else if(r.selectionMode==="next"){let v=h>=0?h:Math.min(r.selectedIndex,c.length-1);u=v<0?0:(v+1)%c.length;}else if(r.selectionMode==="previous"){let v=h>=0?h:Math.min(r.selectedIndex,c.length-1);u=v<0?c.length-1:(v-1+c.length)%c.length;}else u=h>=0?h:Math.min(Math.max(0,r.selectedIndex),c.length-1);if(r.selectedIndex=u,r.selectedKey=u>=0?xi(c[u]):void 0,r.selectionMode="retain",r.component.setResult(u,c.length),!l)return false;let p=c[u],f=p?.segments[0],b=p?.segments[p.segments.length-1];if(!s||!f||!b||n.viewportHeight<=0)return false;let m=n.scrollTop,g=m+n.viewportHeight-1,x=m;return (f.row<m||b.row>g)&&(x=f.row-Math.floor(n.viewportHeight/3)),n.scrollTo(x,{disableFollow:true}),n.scrollTop!==m}flash(e,r){this.flashes.flash(e,r);}shouldDeferViewportInputToOverlay(){return this.isOverlayFocused()&&this.activeSearch?.overlay?.isFocused()!==true}clearComponentMouseGesture(){this.mouseCapture=void 0,this.mousePressTarget=void 0,this.mousePressPoint=void 0,this.mousePressMoved=false;}handleViewportInput(e){if(e===Xl){let l=this.selectionPressActive,a=l&&this.getSelectionBounds()!==void 0;return this.selectionPressActive=false,this.stopSelectionAutoScroll(),this.stopScrollbarHover(),this.activeSearch?.component.setHoveredNavigationDirection(void 0)&&this.requestRender(),this.stopScrollbarDrag(),this.pressedUrl=void 0,this.selectionDragged=false,this.clearComponentMouseGesture(),this.lastComponentClick=void 0,l&&(this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,a&&this.requestRender()),this.lastClick=void 0,{consume:true}}if(e===jl)return {consume:true};let r=this.parseWheelEvent(e);if(r){let l=this.wheelScroll.next(r.direction,performance.now()),a=r.direction*((r.button&8)!==0?l*Zl:l),c=this.createMouseEvent("wheel",r.button,r.x,r.y,{wheelDelta:a}),h=this.dispatchMouseToOverlay(c),u=h.result??(h.hit?void 0:this.dispatchMouseToLayout(c));return u?(this.applyMouseDispatchResult(c,u)&&this.requestRender(),{consume:true}):(this.routeWheel(r,a),{consume:true})}let n=this.parseSgrMouseEvent(e);if(n)return this.handleMouseEvent(n),{consume:true};if(this.isMouseSequence(e))return {consume:true};let s=G(),o=lt(e);if(s.matches(e,"tui.altScreen.search"))return o||this.toggleSearch(),{consume:true};if(this.activeSearch?.overlay?.isFocused()){if(s.matches(e,"tui.altScreen.searchNext"))return o||this.navigateSearch(1),{consume:true};if(s.matches(e,"tui.altScreen.searchPrevious"))return o||this.navigateSearch(-1),{consume:true};if(s.matches(e,"tui.altScreen.searchClose"))return o||this.closeSearch(),{consume:true}}if(!this.shouldDeferViewportInputToOverlay()){if(s.matches(e,"tui.altScreen.pageUp"))return o||this.scrollBy(-Math.max(1,this.getPrimaryScrollView().viewportHeight-ws)),{consume:true};if(s.matches(e,"tui.altScreen.pageDown"))return o||this.scrollBy(Math.max(1,this.getPrimaryScrollView().viewportHeight-ws)),{consume:true};if(s.matches(e,"tui.altScreen.halfPageUp"))return o||this.scrollBy(-Math.max(1,Math.floor(this.getPrimaryScrollView().viewportHeight/2))),{consume:true};if(s.matches(e,"tui.altScreen.halfPageDown"))return o||this.scrollBy(Math.max(1,Math.floor(this.getPrimaryScrollView().viewportHeight/2))),{consume:true};if(s.matches(e,"tui.altScreen.lineUp"))return o||this.scrollBy(-1),{consume:true};if(s.matches(e,"tui.altScreen.lineDown"))return o||this.scrollBy(1),{consume:true};if(s.matches(e,"tui.altScreen.previousPrompt"))return o||this.scrollToPrompt(-1),{consume:true};if(s.matches(e,"tui.altScreen.nextPrompt"))return o||this.scrollToPrompt(1),{consume:true};if(s.matches(e,"tui.altScreen.top"))return o||this.scrollToTop(),{consume:true};if(s.matches(e,"tui.altScreen.bottom"))return o||this.scrollToBottom(),{consume:true}}}decodeMouseButton(e){switch(e&3){case 0:return "left";case 1:return "middle";case 2:return "right";default:return "none"}}createMouseEvent(e,r,n,s,o={}){return {type:e,button:e==="wheel"?"none":this.decodeMouseButton(r),x:n,y:s,screenX:n,screenY:s,width:Math.max(1,this.terminal.columns),height:Math.max(1,this.terminal.rows),shift:(r&4)!==0,alt:(r&8)!==0,ctrl:(r&16)!==0,...o.wheelDelta===void 0?{}:{wheelDelta:o.wheelDelta},...o.clickCount===void 0?{}:{clickCount:o.clickCount}}}dispatchMouseToLayout(e){if(!this.currentLayout)return;let r=new Set,n=xs(this.currentLayout,e.screenX,e.screenY);for(let s of n){if(r.has(s.component)||Jt(s.component)&&s.component.handleMouse===oe.prototype.handleMouse)continue;r.add(s.component);let o=he(s.component,{...e,x:e.screenX-s.rect.x,y:e.screenY-s.rect.y,width:s.rect.width,height:s.rect.height});if(o)return o}}applyMouseDispatchResult(e,r){let n=this.resolveMouseFocusTarget(r.focusTarget??r.target.component),s=r.focus===true&&this.getFocusedComponent()!==n;return r.focus&&this.setFocus(n),r.capture&&(this.mouseCapture=r.target),r.render??(s||e.type==="press"||e.type==="click"||e.type==="drag"||e.type==="wheel")}dispatchMouseToTarget(e,r){return he(r.component,Rn(e,r))}getComponentClickCount(e,r,n){let s=Date.now(),o=this.lastComponentClick,l=o&&s-o.timestamp<=Ts&&o.component===e.component&&o.x===r&&o.y===n?o.count%3+1:1;return this.lastComponentClick={timestamp:s,count:l,component:e.component,x:r,y:n},l}clearTextSelection(){this.stopSelectionAutoScroll(),this.selectionPressActive=false,this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,this.pressedUrl=void 0,this.selectionDragged=false;}handleMouseEvent(e){let r=(e.button&32)!==0,n=e.release?"release":r?this.decodeMouseButton(e.button)==="none"?"move":"drag":"press",s=this.createMouseEvent(n,e.button,e.x,e.y);if(this.mouseCapture||this.mousePressTarget){let a=this.mouseCapture??this.mousePressTarget;this.mousePressPoint&&(e.x!==this.mousePressPoint.x||e.y!==this.mousePressPoint.y)&&(this.mousePressMoved=true,this.lastComponentClick=void 0);let c=false,h=this.dispatchMouseToTarget(s,a);if(h&&(c=this.applyMouseDispatchResult(s,h)),e.release){if(!this.mousePressMoved&&this.mousePressPoint?.x===e.x&&this.mousePressPoint.y===e.y){let u=this.createMouseEvent("click",e.button,e.x,e.y,{clickCount:this.getComponentClickCount(a,e.x,e.y)}),p=this.dispatchMouseToTarget(u,a);p&&(c=this.applyMouseDispatchResult(u,p)||c);}this.clearComponentMouseGesture();}c&&this.requestRender();return}if(this.handleSearchMouseEvent(e))return;let o=this.dispatchMouseToOverlay(s);if(o.hit)this.stopScrollbarHover();else {if(this.handleScrollToEndIndicatorMouseEvent(e))return;let a=this.handleScrollbarMouseEvent(e);if(this.scrollbarDrag||this.updateScrollbarHover(e.x,e.y),a)return}let l=o.result??(o.hit?void 0:this.dispatchMouseToLayout(s));if(l){let a=this.applyMouseDispatchResult(s,l);n==="press"&&(this.clearTextSelection(),this.mousePressTarget=l.target,this.mousePressPoint={x:e.x,y:e.y},this.mousePressMoved=false),a&&this.requestRender();return}this.handleRightClickPaste(e)||this.handleSelectionMouseEvent(e);}parseWheelEvent(e){let r=/^\x1b\[<(\d+);(\d+);(\d+)[Mm]$/.exec(e);if(r){let n=Number.parseInt(r[1],10);if((n&64)===0)return;let s=n&3;return s!==0&&s!==1?void 0:{direction:s===0?-1:1,x:Number.parseInt(r[2],10)-1,y:Number.parseInt(r[3],10)-1,button:n}}if(e.length===6&&e.startsWith("\x1B[M")){let n=e.charCodeAt(3)-32;if((n&64)===0)return;let s=n&3;return s!==0&&s!==1?void 0:{direction:s===0?-1:1,x:e.charCodeAt(4)-33,y:e.charCodeAt(5)-33,button:n}}}routeWheel(e,r){let n=r,s=new Set;for(let l of this.currentLayout?hr(this.currentLayout,e.x,e.y):[])if(s.add(l),n=l.scrollBy(n),n===0||l.overscroll==="contain")break;let o=this.getPrimaryScrollView();n!==0&&!s.has(o)&&o.scrollBy(n),this.updateScrollbarHover(e.x,e.y),this.requestRender();}parseSgrMouseEvent(e){let r=/^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/.exec(e);if(r)return {button:Number.parseInt(r[1],10),x:Number.parseInt(r[2],10)-1,y:Number.parseInt(r[3],10)-1,release:r[4]==="m"}}handleRightClickPaste(e){if(!this.onRightClickPaste||process.platform!=="win32"||process.env.TERM_PROGRAM?.toLowerCase()==="vscode"||e.release||e.button!==2)return false;try{this.onRightClickPaste();}catch{}return true}handleScrollToEndIndicatorMouseEvent(e){let r=this.scrollToEndIndicatorRect;return !r||e.release||(e.button&32)!==0||(e.button&3)!==0||e.y!==r.row||e.x<r.column||e.x>=r.column+r.width?false:(this.scrollToBottom(),true)}getScrollbarTargetAt(e,r,n=false){if(!(this.hasOverlay()||!this.currentLayout))for(let s of hr(this.currentLayout,e,r)){let o=ne(this.currentLayout,s),l=o?Je(o,n):void 0;if(l&&e===l.column&&r>=l.trackTop&&r<l.trackTop+l.trackHeight)return {scrollView:s,geometry:l}}}setScrollbarHover(e){e!==this.scrollbarHover&&(this.scrollbarHover?.setScrollbarActive(false),this.scrollbarHover=e,this.scrollbarHover?.setScrollbarActive(true));}updateScrollbarHover(e,r){this.setScrollbarHover(this.getScrollbarTargetAt(e,r,true)?.scrollView);}stopScrollbarHover(){this.setScrollbarHover(void 0);}scrollScrollbarToPointer(e,r,n,s){let o=r.trackHeight-r.thumbHeight,l=Math.max(0,Math.min(o,n-r.trackTop-s)),a=o===0?0:Math.round(l/o*r.maxScrollTop);e.scrollTo(a);}handleScrollbarMouseEvent(e){if(this.scrollbarDrag){if(e.release)return this.stopScrollbarDrag(),true;let o=this.currentLayout?ne(this.currentLayout,this.scrollbarDrag.scrollView):void 0,l=o?Je(o):void 0;return l&&this.scrollScrollbarToPointer(this.scrollbarDrag.scrollView,l,e.y,this.scrollbarDrag.grabOffset),true}if(e.release||(e.button&32)!==0||(e.button&3)!==0)return false;let r=this.getScrollbarTargetAt(e.x,e.y);if(!r)return false;this.stopSelectionAutoScroll(),this.selectionPressActive=false,this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,this.lastClick=void 0,this.pressedUrl=void 0,this.selectionDragged=false,this.setScrollbarHover(r.scrollView);let n=e.y>=r.geometry.thumbTop&&e.y<r.geometry.thumbTop+r.geometry.thumbHeight,s=n?e.y-r.geometry.thumbTop:Math.floor(r.geometry.thumbHeight/2);return n||this.scrollScrollbarToPointer(r.scrollView,r.geometry,e.y,s),this.scrollbarDrag={scrollView:r.scrollView,grabOffset:s},true}stopScrollbarDrag(){this.scrollbarDrag=void 0;}getScrollSelectionPoint(e,r,n){if(!this.currentLayout)return;let s=ne(this.currentLayout,e);if(!s||s.rect.height<=0||s.clip.height<=0)return;let o=Math.max(0,s.rect.y,s.clip.y),l=Math.min(this.terminal.rows-1,s.rect.y+s.rect.height-1,s.clip.y+s.clip.height-1);if(l<o)return;let a=Math.max(o,Math.min(l,n)),c=Math.max(0,(s.scrollContentLines?.length??1)-1);return {row:Math.max(0,Math.min(c,e.scrollTop+a-s.rect.y)),col:Math.max(0,Math.min(s.rect.width-1,r-s.rect.x)),scrollView:e}}getSelectionPoint(e,r){if(r){let n=this.getScrollSelectionPoint(r,e.x,e.y);if(n)return n}return {row:Math.max(0,Math.min(this.terminal.rows-1,e.y)),col:Math.max(0,Math.min(this.terminal.columns-1,e.x))}}getSelectionSourceLine(e){if(e.scrollView&&this.currentLayout){let r=ne(this.currentLayout,e.scrollView)?.scrollContentLines;if(r)return r[e.row]??""}return this.previousScreen[e.row]??""}getWordSelection(e){let r=Ke(this.getSelectionSourceLine(e)),n=[],s=0;for(let u of nc.segment(r)){let p=s+S(u.segment),f=ic.has(u.segment);n.push({start:s,end:p,selectable:u.isWordLike===true||f,joiner:f}),s=p;}let o=n.findIndex(u=>e.col>=u.start&&e.col<u.end);if(o<0)return;let l=(u,p)=>u.selectable&&p.selectable&&(u.joiner||p.joiner),a=n[o],c=a.start,h=a.end;for(let u=o;u>0&&l(n[u-1],n[u]);u--)c=n[u-1].start;for(let u=o;u<n.length-1&&l(n[u],n[u+1]);u++)h=n[u+1].end;return {start:{...e,col:c},end:{...e,col:h,boundary:true}}}getLineSelection(e){return {start:{...e,col:0},end:{...e,col:S(this.getSelectionSourceLine(e)),boundary:true}}}updateSelectionFocus(e){if(this.selectionGranularity==="character"||!this.selectionInitialRange){this.selectionFocus=e;return}let r=this.selectionGranularity==="word"?this.getWordSelection(e):this.getLineSelection(e);if(!r)return;let n=this.selectionInitialRange;r.start.row<n.start.row||r.start.row===n.start.row&&r.start.col<n.start.col?(this.selectionAnchor=n.end,this.selectionFocus=r.start):(this.selectionAnchor=n.start,this.selectionFocus=r.end);}getClickCount(e,r){let n=Date.now(),s=this.lastClick,o=r&&s&&n-s.timestamp<=Ts&&s.row===e.row&&s.scrollView===e.scrollView&&s.wordStart===r.start.col&&s.wordEnd===r.end.col?s.count%3+1:1;return this.lastClick=r?{timestamp:n,count:o,row:e.row,scrollView:e.scrollView,wordStart:r.start.col,wordEnd:r.end.col}:void 0,o}updateSelectionAutoScroll(e){let r=this.selectionAnchor?.scrollView;if(!r||!this.currentLayout){this.stopSelectionAutoScroll();return}let n=ne(this.currentLayout,r);if(!n||n.rect.height<=0||n.clip.height<=0){this.stopSelectionAutoScroll();return}let s=Math.max(0,n.rect.y,n.clip.y),o=Math.min(this.terminal.rows-1,n.rect.y+n.rect.height-1,n.clip.y+n.clip.height-1);if(this.selectionDragPointer={x:e.x,y:e.y},this.selectionAutoScrollDirection=e.y<=s?-1:e.y>=o?1:0,this.selectionAutoScrollDirection===0){this.stopSelectionAutoScroll();return}this.selectionAutoScrollTimer||(this.selectionAutoScrollTimer=setInterval(()=>this.autoScrollSelection(),50),this.selectionAutoScrollTimer.unref());}autoScrollSelection(){let e=this.selectionAnchor?.scrollView,r=this.selectionDragPointer,n=this.selectionAutoScrollDirection;if(!e||!r||n===0){this.stopSelectionAutoScroll();return}if(e.scrollBy(n)===n){this.stopSelectionAutoScroll();return}let o=this.getScrollSelectionPoint(e,r.x,r.y);o&&this.updateSelectionFocus(o),this.requestRender();}stopSelectionAutoScroll(){this.selectionAutoScrollTimer&&(clearInterval(this.selectionAutoScrollTimer),this.selectionAutoScrollTimer=void 0),this.selectionAutoScrollDirection=0,this.selectionDragPointer=void 0;}handleSelectionMouseEvent(e){let r=e.button&3;if(r!==0&&!(e.release&&r===3))return;let n=this.selectionAnchor?.scrollView,s=this.getSelectionPoint(e,n);if(e.release){if(!this.selectionPressActive||(this.selectionPressActive=false,this.stopSelectionAutoScroll(),!this.selectionAnchor))return;this.updateSelectionFocus(s);let u=!this.selectionDragged&&this.selectionAnchor.scrollView===s.scrollView&&this.selectionAnchor.row===s.row&&this.selectionAnchor.col===s.col,p=u?this.pressedUrl:void 0;if(this.pressedUrl=void 0,p&&this.openUrl){this.selectionAnchor=void 0,this.selectionFocus=void 0;try{this.openUrl(p);}catch{}this.requestRender();return}if(u){let f=this.createMouseEvent("click",e.button,e.x,e.y,{clickCount:this.lastClick?.count??1}),b=this.dispatchMouseToOverlay(f),m=b.result??(b.hit?void 0:this.dispatchMouseToLayout(f));if(m){let g=this.applyMouseDispatchResult(f,m);this.clearTextSelection(),g&&this.requestRender();return}}this.copyOnSelect&&this.copySelectionToClipboard(),this.requestRender();return}if((e.button&32)!==0){if(!this.selectionPressActive||!this.selectionAnchor)return;this.selectionDragged=true,this.lastClick=void 0,this.pressedUrl=void 0,this.updateSelectionFocus(s),this.updateSelectionAutoScroll(e),this.requestRender();return}this.stopSelectionAutoScroll(),this.selectionPressActive=true;let o=!this.hasOverlay()&&this.currentLayout?hr(this.currentLayout,e.x,e.y)[0]:void 0,l=this.getSelectionPoint(e,o),a=this.getWordSelection(l),c=this.getClickCount(l,a),h=c===2?a:c===3?this.getLineSelection(l):void 0;this.selectionGranularity=h?c===2?"word":"line":"character",this.selectionInitialRange=h,this.selectionAnchor=h?.start??l,this.selectionFocus=h?.end??l,this.selectionDragged=false,this.pressedUrl=h?void 0:xr(this.previousScreen[Math.max(0,Math.min(this.terminal.rows-1,e.y))]??"",Math.max(0,Math.min(this.terminal.columns-1,e.x))),this.requestRender();}getSelectionBounds(){if(!this.selectionAnchor||!this.selectionFocus||this.selectionAnchor.scrollView!==this.selectionFocus.scrollView)return;let e=this.selectionAnchor.row<this.selectionFocus.row||this.selectionAnchor.row===this.selectionFocus.row&&this.selectionAnchor.col<this.selectionFocus.col;if(!(this.selectionAnchor.row===this.selectionFocus.row&&this.selectionAnchor.col===this.selectionFocus.col))return e?{start:this.selectionAnchor,end:this.selectionFocus}:{start:this.selectionFocus,end:this.selectionAnchor}}getSelectionColumns(e,r,n,s=0,o=S(e)){let l=S(e),a=Math.max(0,s),c=Math.min(l,o);return r===n.start.row&&(a=rt(e,n.start.col)?.start??Math.min(n.start.col,l)),r===n.end.row&&(c=n.end.boundary?Math.min(n.end.col,l):rt(e,n.end.col)?.end??Math.min(n.end.col+1,l)),{start:Math.max(s,a),end:Math.min(o,c)}}getActiveSelectionText(){let e=this.getSelectionBounds();if(!e)return;let r=this.previousScreen;if(e.start.scrollView){if(!this.currentLayout)return;let o=ne(this.currentLayout,e.start.scrollView);if(!o?.scrollContentLines)return;r=o.scrollContentLines;}let n=[];for(let o=e.start.row;o<=e.end.row;o++){let l=r[o]??"",a=this.getSelectionColumns(l,o,e);n.push(Ke(V(l,a.start,Math.max(0,a.end-a.start),true)).trimEnd());}let s=n.join(`
43
- `);return s.length===0?void 0:s}async copySelectionToClipboard(){let e=this.getActiveSelectionText();return e?this.copyTextToClipboard(e):false}async copyTextToClipboard(e){if(this.copySelection){let r=await this.copySelection(e),n=r===true;return this.flash(n?"Copied!":typeof r=="string"?r:"Copy failed",n?void 0:rc),n}return this.terminal.write(`\x1B]52;c;${Buffer.from(e).toString("base64")}\x07`),this.flash("Copied!"),true}applySearchTextHighlight(e,r){let n=r?this.searchCurrentMatchStyle:this.searchMatchStyle,s="",o=0,l=0;for(;l<e.length;){let a=W(e,l);if(!a){l+=1;continue}l>o&&(s+=n(e.slice(o,l))),s+=a.code,l+=a.length,o=l;}return o<e.length&&(s+=n(e.slice(o))),s}applySearchHighlights(e,r){let n=this.activeSearch;if(!n||n.selectedIndex<0||n.matches.length===0)return e;let s=r.primaryScrollView??this.implicitScrollView,o=ne(r,s);if(!o)return e;let l=new Map,a=Je(o)?.column,c=Math.max(0,o.rect.y,o.clip.y),h=Math.min(e.length,o.rect.y+o.rect.height,o.clip.y+o.clip.height),u=Math.max(0,o.rect.x,o.clip.x),p=Math.min(this.terminal.columns,o.rect.x+o.rect.width,o.clip.x+o.clip.width,a??Number.POSITIVE_INFINITY),f=s.scrollTop+c-o.rect.y,b=s.scrollTop+h-o.rect.y-1,m=0,g=n.matches.length;for(;m<g;){let v=m+Math.floor((g-m)/2),y=n.matches[v];(y.segments[y.segments.length-1]?.row??-1)<f?m=v+1:g=v;}for(let v=m;v<n.matches.length;v++){let y=n.matches[v];if((y.segments[0]?.row??0)>b)break;for(let w of y.segments){let I=o.rect.y+w.row-s.scrollTop;if(I<c||I>=h)continue;let T=Math.max(u,o.rect.x+w.startCol),L=Math.min(p,o.rect.x+w.endCol);if(L<=T)continue;let M=l.get(I)??[];M.push({startCol:T,endCol:L,current:v===n.selectedIndex}),l.set(I,M);}}let x=[...e];for(let[v,y]of l){let w=x[v]??"";if(F(w))continue;let I=S(w);for(let T of y.sort((L,M)=>M.startCol-L.startCol)){let L=Math.min(T.startCol,I),M=Math.min(T.endCol,I);if(M<=L)continue;let E=V(w,0,L,true),P=V(w,L,M-L,true),C=V(w,M,Math.max(0,I-M),true);w=`${E}${this.applySearchTextHighlight(P,T.current)}${C}`;}x[v]=w;}return x}applySelectionHighlight(e){let r="\x1B[7m",n=0;for(;n<e.length;){let s=W(e,n);if(!s){r+=e[n],n+=1;continue}r+=s.code,s.code.endsWith("m")&&(r+="\x1B[7m"),n+=s.length;}return `${r}\x1B[27m`}applySelection(e,r=this.currentLayout){let n=this.getSelectionBounds();if(!n)return e;let s=n,o=0,l=e.length-1,a=0,c=this.terminal.columns;if(n.start.scrollView){if(!r)return e;let h=ne(r,n.start.scrollView);if(!h)return e;o=Math.max(0,h.rect.y,h.clip.y),l=Math.min(e.length-1,h.rect.y+h.rect.height-1,h.clip.y+h.clip.height-1),a=Math.max(0,h.rect.x,h.clip.x),c=Math.min(this.terminal.columns,h.rect.x+h.rect.width,h.clip.x+h.clip.width),s={start:{...n.start,row:h.rect.y+n.start.row-n.start.scrollView.scrollTop,col:h.rect.x+n.start.col},end:{...n.end,row:h.rect.y+n.end.row-n.start.scrollView.scrollTop,col:h.rect.x+n.end.col}};}return e.map((h,u)=>{if(u<o||u>l||u<s.start.row||u>s.end.row||F(h))return h;let p=S(h),f=this.getSelectionColumns(h,u,s,a,c);if(f.end<=f.start)return h;let b=V(h,0,f.start,true),m=V(h,f.start,f.end-f.start,true),g=V(h,f.end,Math.max(0,p-f.end),true);return `${b}${this.applySelectionHighlight(m)}${g}`})}isMouseSequence(e){return /^\x1b\[<\d+;\d+;\d+[Mm]$/.test(e)||e.length===6&&e.startsWith("\x1B[M")}compositeScrollToEndIndicator(e,r,n){this.scrollToEndIndicatorRect=void 0;let s=r.primaryScrollView??this.implicitScrollView;if(!this.scrollToEndIndicator||!s.followEnd||s.isFollowingEnd)return e;let o=ne(r,s),l=o?.clip;if(!l||l.width<=0||l.height<=0)return e;let a=l.y+l.height-1;if(a>=e.length||F(e[a]??""))return e;let c=o?Je(o)?.column:void 0,h=N(this.scrollToEndIndicator(),l.width,""),u=S(h),p=l.x+Math.floor((l.width-u)/2),f=c??l.x+l.width,b=Math.max(0,f-p),m=N(h,b,""),g=S(m);if(g===0)return e;let x=[...e];return x[a]=de(x[a]??"",m,p,g,n),this.scrollToEndIndicatorRect={row:a,column:p,width:g},x}compositeFlashes(e,r,n){let s=this.flashes.render(r).slice(-n);if(s.length===0)return e;let o=[...e];for(;o.length<n;)o.push("");for(let l=0;l<s.length;l++){let a=s[l],c=S(a);c!==0&&(o[l]=de(o[l]??"",a,r-c,c,r));}return o}doRender(){if(this.stopped||!this.altScreenActive)return;let e=Math.max(1,this.terminal.columns),r=Math.max(1,this.terminal.rows),n=this.layoutRoot??this.implicitScrollView,s=vi(n,e,r,()=>this.requestRender());this.refreshSearch(s)&&(s=vi(n,e,r,()=>this.requestRender()));let o=this.resolveFakeCursors(s.lines.map(y=>y.replace(Cs,"")));o=this.applySearchHighlights(o,s),o=this.compositeScrollToEndIndicator(o,s,e),o=this.compositeOverlays(o,e,r),o.length>r&&(o=o.slice(o.length-r)),o=this.applySelection(o,s),o=this.compositeFlashes(o,e,r);let l=this.extractCursorPosition(o,r);o=this.applyLineResets(o).map(y=>F(y)||S(y)<=e?y:V(y,0,e,true));let a=this.previousScreen.length===0||this.previousScreenWidth!==e||this.previousScreenHeight!==r,c=o.map((y,w)=>y!==this.previousScreen[w]),h=o.some((y,w)=>c[w]&&(F(y)||F(this.previousScreen[w]??""))),u=!!process.env.WEZTERM_PANE||process.env.TERM_PROGRAM?.toLowerCase()==="wezterm",p=!h&&u&&this.imageProtocol==="kitty"&&c.some(Boolean)&&o.some((y,w)=>{let I=wn(y);if(I===void 0)return false;for(let T=w;T<w+I;T++)if(c[T])return true;return false}),f=h||p,b=a||f,m=this.uploadedKittyImages.size>0,g=b&&this.imageProtocol==="kitty"?this.prepareKittyScreen(o):{lines:o,evictedImageDeletion:""},x=pr;if(a){this.fullRedrawCount+=1;let y=this.imageProtocol==="kitty"&&m?Nr():this.deleteKittyImages();x+=`${y}\x1B[2J`;}else f&&(this.imageProtocol==="iterm2"?x+="\x1B[2J":this.imageProtocol==="kitty"&&(x+=Nr()));if(x+=g.evictedImageDeletion,b&&this.imageProtocol==="kitty"&&o.some(F)&&u){for(let y=0;y<r;y++)!a&&!f&&o[y]===this.previousScreen[y]||(x+=`\x1B[${y+1};1H\x1B[2K`);for(let y=0;y<r;y++)!a&&!f&&o[y]===this.previousScreen[y]||F(g.lines[y]??"")||(x+=`\x1B[${y+1};1H${g.lines[y]??""}`);for(let y=0;y<r;y++)!a&&!f&&o[y]===this.previousScreen[y]||F(g.lines[y]??"")&&(x+=`\x1B[${y+1};1H${g.lines[y]??""}`);}else for(let y=0;y<r;y++)!a&&!f&&o[y]===this.previousScreen[y]||(x+=`\x1B[${y+1};1H\x1B[2K${g.lines[y]??""}`);l?(x+=`\x1B[${l.row+1};${Math.min(e,l.col)+1}H`,x+=this.getShowHardwareCursor()?"\x1B[?25h":"\x1B[?25l"):x+="\x1B[?25l",x+=fr,this.terminal.write(x),this.previousScreen=o,this.previousScreenWidth=e,this.previousScreenHeight=r,this.currentLayout=s;}};var Ls="\x1B_G",ks=1024*1024,Ct=class{constructor(t){d(this,"buffer","");d(this,"writtenChars",0);d(this,"write");this.write=t;}append(t){let e=0;for(;e<t.length;){let r=ks-this.buffer.length;if(r===0){this.flush();continue}let n=Math.min(t.length,e+r);if(n<t.length&&t.charCodeAt(n-1)>=55296&&t.charCodeAt(n-1)<=56319&&t.charCodeAt(n)>=56320&&t.charCodeAt(n)<=57343&&n--,n===e){this.flush();continue}this.buffer+=t.slice(e,n),e=n,this.buffer.length===ks&&this.flush();}}flush(){this.buffer&&(this.write(this.buffer),this.writtenChars+=this.buffer.length,this.buffer="");}get length(){return this.writtenChars+this.buffer.length}};function Rs(i){let t=i.indexOf(Ls);if(t===-1)return;let e=t+Ls.length,r=i.indexOf(";",e);if(r===-1)return;let n=[],s=1;for(let o of i.slice(e,r).split(",")){let[l,a]=o.split("=",2);if(a===void 0)continue;let c=Number(a);!Number.isInteger(c)||c<=0||c>4294967295||(l==="i"?n.push(c):l==="r"&&(s=c));}return {ids:n,rows:s}}function Ci(i){return Rs(i)?.ids??[]}function sc(i){return Rs(i)?.rows??1}function oc(){return !!process.env.TERMUX_VERSION}var wi=class extends qe{constructor(){super(...arguments);d(this,"mode","regular");d(this,"previousLines",[]);d(this,"previousKittyImageIds",new Set);d(this,"previousWidth",0);d(this,"previousHeight",0);d(this,"cursorRow",0);d(this,"hardwareCursorRow",0);d(this,"maxLinesRendered",0);d(this,"previousViewportTop",0);}captureRenderState(){return {previousLines:[...this.previousLines],previousWidth:this.previousWidth,previousHeight:this.previousHeight,cursorRow:this.cursorRow,hardwareCursorRow:this.hardwareCursorRow,maxLinesRendered:this.maxLinesRendered,previousViewportTop:this.previousViewportTop}}restoreRenderState(e){this.previousLines=e.previousLines.map(r=>F(r)?"":r),this.previousKittyImageIds=new Set,this.previousWidth=e.previousWidth,this.previousHeight=e.previousHeight,this.cursorRow=e.cursorRow,this.hardwareCursorRow=e.hardwareCursorRow,this.maxLinesRendered=e.maxLinesRendered,this.previousViewportTop=e.previousViewportTop;}resetRenderState(){this.previousLines=[],this.previousWidth=-1,this.previousHeight=-1,this.cursorRow=0,this.hardwareCursorRow=0,this.maxLinesRendered=0,this.previousViewportTop=0;}beforeTerminalStop(e){if(e.preserveScreen||this.previousLines.length===0)return;this.terminal.write(" ");let n=this.previousLines.length-this.hardwareCursorRow;n>0?this.terminal.write(`\x1B[${n}B`):n<0&&this.terminal.write(`\x1B[${-n}A`),this.terminal.write(`\r
44
- `);}collectKittyImageIds(e){let r=new Set;for(let n of e)for(let s of Ci(n))r.add(s);return r}deleteKittyImages(e){let r="";for(let n of e)r+=ct(n);return r}getKittyImageReservedRows(e,r,n=e.length-1){let s=sc(e[r]??"");if(s<=1)return 1;let o=Math.min(s,n-r+1,e.length-r),l=1;for(;l<o;){let a=e[r+l]??"";if(F(a)||S(a)>0)break;l++;}return l}expandChangedRangeForKittyImages(e,r,n){let s=e,o=r,l=a=>{for(let c=0;c<a.length;c++){if(Ci(a[c]??"").length===0)continue;let h=c+this.getKittyImageReservedRows(a,c)-1;(c>=e||c<=r&&h>=e)&&(s=Math.min(s,c),o=Math.max(o,h));}};return l(this.previousLines),l(n),{firstChanged:s,lastChanged:o}}deleteChangedKittyImages(e,r){if(e<0||r<e)return "";let n=new Set,s=Math.min(r,this.previousLines.length-1);for(let o=e;o<=s;o++)for(let l of Ci(this.previousLines[o]??""))n.add(l);return this.deleteKittyImages(n)}doRender(){if(this.stopped)return;let e=this.terminal.columns,r=this.terminal.rows,n=this.previousWidth!==0&&this.previousWidth!==e,s=this.previousHeight!==0&&this.previousHeight!==r,o=this.previousHeight>0?this.previousViewportTop+this.previousHeight:r,l=s?Math.max(0,o-r):this.previousViewportTop,a=l,c=this.hardwareCursorRow,h=C=>{let A=c-l;return C-a-A},u=this.resolveFakeCursors(this.render(e));this.hasOverlayEntries&&(u=this.compositeOverlays(u,e,r));let p=this.extractCursorPosition(u,r);u=this.applyLineResets(u);let f=C=>{this.fullRedrawCount+=1;let A=new Ct(K=>this.terminal.write(K));A.append("\x1B[?2026h"),C&&(A.append(this.deleteKittyImages(this.previousKittyImageIds)),A.append("\x1B[2J\x1B[H\x1B[3J"));for(let K=0;K<u.length;K++){K>0&&A.append(`\r
45
- `);let U=u[K]??"",Y=F(U)?this.getKittyImageReservedRows(u,K):1;if(Y>1&&Y<=r){for(let et=1;et<Y;et++)A.append(`\r
46
- `);A.append(`\x1B[${Y-1}A`),A.append(U),A.append(`\x1B[${Y-1}B`),K+=Y-1;continue}A.append(U);}A.append("\x1B[?2026l"),A.flush(),this.cursorRow=Math.max(0,u.length-1),this.hardwareCursorRow=this.cursorRow,C?this.maxLinesRendered=u.length:this.maxLinesRendered=Math.max(this.maxLinesRendered,u.length);let D=Math.max(r,u.length);this.previousViewportTop=Math.max(0,D-r),this.positionHardwareCursor(p,u.length),this.previousLines=u,this.previousKittyImageIds=this.collectKittyImageIds(u),this.previousWidth=e,this.previousHeight=r;},b=process.env.PI_TUI_DEBUG_REDRAW==="1"?this.logDirectory:void 0,m=C=>{if(b===void 0)return;let A=Ae.join(b,"pi-tui-debug.log"),D=`[${new Date().toISOString()}] fullRender: ${C} (prev=${this.previousLines.length}, new=${u.length}, height=${r})
47
- `;fe.mkdirSync(Ae.dirname(A),{recursive:true}),fe.appendFileSync(A,D);};if(this.previousLines.length===0&&!n&&!s){m("first render"),f(false);return}if(n){m(`terminal width changed (${this.previousWidth} -> ${e})`),f(true);return}if(s&&!oc()){m(`terminal height changed (${this.previousHeight} -> ${r})`),f(true);return}if(this.getClearOnShrink()&&u.length<this.maxLinesRendered&&!this.hasOverlayEntries){m(`clearOnShrink (maxLinesRendered=${this.maxLinesRendered})`),f(true);return}let g=-1,x=-1,v=Math.max(u.length,this.previousLines.length);for(let C=0;C<v;C++){let A=C<this.previousLines.length?this.previousLines[C]:"",D=C<u.length?u[C]:"";A!==D&&(g===-1&&(g=C),x=C);}let y=u.length>this.previousLines.length;if(y&&(g===-1&&(g=this.previousLines.length),x=u.length-1),g!==-1){let C=this.expandChangedRangeForKittyImages(g,x,u);g=C.firstChanged,x=C.lastChanged;}let w=y&&g===this.previousLines.length&&g>0;if(g===-1){this.positionHardwareCursor(p,u.length),this.previousViewportTop=l,this.previousHeight=r;return}if(g>=u.length){if(this.previousLines.length>u.length){let C=new Ct(Y=>this.terminal.write(Y));C.append("\x1B[?2026h"),C.append(this.deleteChangedKittyImages(g,x));let A=Math.max(0,u.length-1);if(A<l){m(`deleted lines moved viewport up (${A} < ${l})`),f(true);return}let D=h(A);D>0?C.append(`\x1B[${D}B`):D<0&&C.append(`\x1B[${-D}A`),C.append("\r");let K=this.previousLines.length-u.length;if(K>r){m(`extraLines > height (${K} > ${r})`),f(true);return}let U=u.length===0?0:1;K>0&&U>0&&C.append(`\x1B[${U}B`);for(let Y=0;Y<K;Y++)C.append("\r\x1B[2K"),Y<K-1&&C.append("\x1B[1B");let me=Math.max(0,K-1+U);me>0&&C.append(`\x1B[${me}A`),C.append("\x1B[?2026l"),C.flush(),this.cursorRow=A,this.hardwareCursorRow=A;}this.positionHardwareCursor(p,u.length),this.previousLines=u,this.previousKittyImageIds=this.collectKittyImageIds(u),this.previousWidth=e,this.previousHeight=r,this.previousViewportTop=l;return}if(g<l){m(`firstChanged < viewportTop (${g} < ${l})`),f(true);return}let I=new Ct(C=>this.terminal.write(C));I.append("\x1B[?2026h"),I.append(this.deleteChangedKittyImages(g,x));let T=l+r-1,L=w?g-1:g;if(L>T){let C=Math.max(0,Math.min(r-1,c-l)),A=r-1-C;A>0&&I.append(`\x1B[${A}B`);let D=L-T;I.append(`\r
38
+ `);for(let a of t)switch(a.type){case "latex":{let c=a,h=!c.pending&&this.options.renderLatex!==false?tr(c.text)??c.raw:c.raw;r+=l(h);break}case "escape":r+=l(this.options.preserveBackslashEscapes?a.raw:a.text);break;case "text":a.tokens&&a.tokens.length>0?r+=this.renderInlineTokens(a.tokens,n):r+=l(a.text);break;case "paragraph":r+=this.renderInlineTokens(a.tokens||[],n);break;case "strong":{let c=this.renderInlineTokens(a.tokens||[],n);r+=this.theme.bold(c)+o;break}case "em":{let c=this.renderInlineTokens(a.tokens||[],n);r+=this.theme.italic(c)+o;break}case "codespan":r+=this.theme.code(a.text)+o;break;case "link":{let c=this.renderInlineTokens(a.tokens||[],n),h=this.theme.link(this.theme.underline(c));if(te().hyperlinks)r+=Vt(h,a.href)+o;else {let u=a.href.startsWith("mailto:")?a.href.slice(7):a.href;a.text===a.href||a.text===u?r+=h+o:r+=h+this.theme.linkUrl(` (${a.href})`)+o;}break}case "br":r+=`
39
+ `;break;case "del":{let c=this.renderInlineTokens(a.tokens||[],n);r+=this.theme.strikethrough(c)+o;break}case "html":"raw"in a&&typeof a.raw=="string"&&(r+=l(a.raw));break;default:"text"in a&&typeof a.text=="string"&&(r+=l(a.text));}for(;o&&r.endsWith(o);)r=r.slice(0,-o.length);return r}getOrderedListMarker(t){let e=/^(?: {0,3})(\d{1,9}[.)])[ \t]+/.exec(t.raw);return e?`${e[1]} `:void 0}getUnorderedListMarker(t){let e=/^(?: {0,3})([-+*])(?:[ \t]+|(?=\r?\n|$))/.exec(t.raw);return e?`${e[1]} `:void 0}renderList(t,e,r,n){let s=[],o=" ".repeat(e),l=typeof t.start=="number"?t.start:1;for(let a=0;a<t.items.length;a++){let c=t.items[a],h=a===t.items.length-1,u=t.ordered?this.options.preserveOrderedListMarkers?this.getOrderedListMarker(c)??`${l+a}. `:`${l+a}. `:this.options.preserveOrderedListMarkers?this.getUnorderedListMarker(c)??"- ":"- ",p=c.task?`[${c.checked?"x":" "}] `:"",f=u+p,b=o+this.theme.listBullet(f),m=o+" ".repeat(S(f)),g=Math.max(1,r-S(b)),y=false;for(let v of c.tokens??[]){if(v.type==="list"){s.push(...this.renderList(v,e+1,r,n)),y=true;continue}let x=this.renderToken(v,g,void 0,n);for(let w of x)for(let I of ne(w,g)){let T=y?m:b;s.push(T+I),y=true;}}y||s.push(b),t.loose&&!h&&s.push("");}return s}getLongestWordWidth(t,e){let r=t.split(/\s+/).filter(s=>s.length>0),n=0;for(let s of r)n=Math.max(n,S(s));return e===void 0?n:Math.min(n,e)}wrapCellText(t,e,r=""){return ne(t,Math.max(1,e)).map(s=>`${s}${r}`)}renderTable(t,e,r,n){let s=[],o=t.header.length;if(o===0)return s;let l=3*o+1,a=e-l;if(a<o){let T=t.raw?ne(t.raw,e):[];return r&&r!=="space"&&T.push(""),T}let c=30,h=[],u=[];for(let T=0;T<o;T++){let L=this.renderInlineTokens(t.header[T]?.tokens||[],n);h[T]=S(L),u[T]=Math.max(1,this.getLongestWordWidth(L,c));}for(let T of t.rows)for(let L=0;L<T.length;L++){let M=this.renderInlineTokens(T[L]?.tokens||[],n);h[L]=Math.max(h[L]||0,S(M)),u[L]=Math.max(u[L]||1,this.getLongestWordWidth(M,c));}let p=u,f=p.reduce((T,L)=>T+L,0);if(f>a){p=new Array(o).fill(1);let T=a-o;if(T>0){let L=u.reduce((C,A)=>C+Math.max(0,A-1),0),M=u.map(C=>{let A=Math.max(0,C-1);return L>0?Math.floor(A/L*T):0});for(let C=0;C<o;C++)p[C]=(p[C]??0)+(M[C]??0);let E=M.reduce((C,A)=>C+A,0),P=T-E;for(let C=0;P>0&&C<o;C++)p[C]=(p[C]??0)+1,P--;}f=p.reduce((L,M)=>L+M,0);}let b=h.reduce((T,L)=>T+L,0)+l,m;if(b<=e)m=h.map((T,L)=>Math.max(T,p[L]??0));else {let T=h.reduce((P,C,A)=>P+Math.max(0,C-(p[A]??0)),0),L=Math.max(0,a-f);m=p.map((P,C)=>{let A=h[C]??0,D=Math.max(0,A-P),B=0;return T>0&&(B=Math.floor(D/T*L)),P+B});let M=m.reduce((P,C)=>P+C,0),E=a-M;for(;E>0;){let P=false;for(let C=0;C<o&&E>0;C++)(m[C]??0)<(h[C]??0)&&(m[C]=(m[C]??0)+1,E--,P=true);if(!P)break}}let g=m.map(T=>"\u2500".repeat(T));s.push(`\u250C\u2500${g.join("\u2500\u252C\u2500")}\u2500\u2510`);let y=t.header.map((T,L)=>{let M=this.renderInlineTokens(T.tokens||[],n);return this.wrapCellText(M,m[L]??0,n?.stylePrefix)}),v=Math.max(...y.map(T=>T.length));for(let T=0;T<v;T++){let L=y.map((M,E)=>{let P=M[T]||"",C=P+" ".repeat(Math.max(0,(m[E]??0)-S(P)));return this.theme.bold(C)});s.push(`\u2502 ${L.join(" \u2502 ")} \u2502`);}let w=`\u251C\u2500${m.map(T=>"\u2500".repeat(T)).join("\u2500\u253C\u2500")}\u2500\u2524`;s.push(w);for(let T=0;T<t.rows.length;T++){let M=(t.rows[T]??[]).map((P,C)=>{let A=this.renderInlineTokens(P.tokens||[],n);return this.wrapCellText(A,m[C]??0,n?.stylePrefix)}),E=Math.max(...M.map(P=>P.length));for(let P=0;P<E;P++){let C=M.map((A,D)=>{let B=A[P]||"";return B+" ".repeat(Math.max(0,(m[D]??0)-S(B)))});s.push(`\u2502 ${C.join(" \u2502 ")} \u2502`);}T<t.rows.length-1&&s.push(w);}let I=m.map(T=>"\u2500".repeat(T));return s.push(`\u2514\u2500${I.join("\u2500\u2534\u2500")}\u2500\u2518`),r&&r!=="space"&&s.push(""),s}};var li=class{constructor(t,e){d(this,"child");d(this,"onMouse");this.child=t,this.onMouse=e;}render(t){return this.child.render(t)}handleMouse(t){return ue(this.child,t)??this.onMouse(t)}invalidate(){this.child.invalidate();}};var ft=class extends se{constructor(e,r={}){super();d(this,"child");d(this,"followEnd");d(this,"primary");d(this,"overscroll");d(this,"scrollbarTrackStyle");d(this,"scrollbarThumbStyle");d(this,"currentScrollbar");d(this,"scrollbarHideDelayMs");d(this,"currentScrollTop",0);d(this,"contentHeight",0);d(this,"currentViewportHeight",0);d(this,"followingEnd");d(this,"followSuppressedAtEnd",false);d(this,"requestRenderCallback");d(this,"transientScrollbarVisible",false);d(this,"scrollbarActive",false);d(this,"scrollbarHideTimer");if(r.axis!==void 0&&r.axis!=="vertical")throw new Error(`Unsupported ScrollView axis: ${r.axis}`);this.child=e,this.children.push(e),this.followEnd=(r.follow??"none")==="end",this.followingEnd=this.followEnd,this.primary=r.primary??false,this.overscroll=r.overscroll??"chain",this.currentScrollbar=r.scrollbar??"hidden",this.scrollbarTrackStyle=r.scrollbarTrackStyle??(n=>`\x1B[90m${n}\x1B[39m`),this.scrollbarThumbStyle=r.scrollbarThumbStyle??(n=>`\x1B[37m${n}\x1B[39m`),this.scrollbarHideDelayMs=Math.max(0,Math.floor(r.scrollbarHideDelayMs??1e3));}get scrollTop(){return this.currentScrollTop}get isFollowingEnd(){return this.followingEnd}get viewportHeight(){return this.currentViewportHeight}get scrollbar(){return this.currentScrollbar}get isScrollbarVisible(){return this.scrollbar==="always"?this.currentViewportHeight>0:this.scrollbar==="auto"&&this.contentHeight>this.currentViewportHeight&&this.transientScrollbarVisible}get isScrollbarActive(){return this.scrollbarActive}setScrollbar(e){e!==this.currentScrollbar&&(this.currentScrollbar=e,e!=="auto"?this.hideTransientScrollbar():this.scrollbarActive&&this.markScrollbarActivity(),this.requestRenderCallback?.());}getContentWidth(e){return this.scrollbar==="always"&&e>1?e-1:e}markScrollbarActivity(){this.scrollbar!=="auto"||this.contentHeight<=this.currentViewportHeight||(this.transientScrollbarVisible=true,this.scrollbarHideTimer&&(clearTimeout(this.scrollbarHideTimer),this.scrollbarHideTimer=void 0),!this.scrollbarActive&&(this.scrollbarHideTimer=setTimeout(()=>{this.scrollbarHideTimer=void 0,this.transientScrollbarVisible=false,this.requestRenderCallback?.();},this.scrollbarHideDelayMs),this.scrollbarHideTimer.unref()));}hideTransientScrollbar(){this.transientScrollbarVisible=false,this.scrollbarHideTimer&&(clearTimeout(this.scrollbarHideTimer),this.scrollbarHideTimer=void 0);}setScrollbarActive(e){e!==this.scrollbarActive&&(this.scrollbarActive=e,this.markScrollbarActivity(),this.requestRenderCallback?.());}scrollTo(e,r={}){let n=Number.isFinite(e)?Math.trunc(e):this.currentScrollTop,s=Math.max(0,this.contentHeight-this.currentViewportHeight),o=Math.max(0,Math.min(s,n)),l=r.disableFollow===true&&o===s,a=!l&&this.followEnd&&o===s;if(o===this.currentScrollTop&&a===this.followingEnd&&l===this.followSuppressedAtEnd)return;let c=o!==this.currentScrollTop;this.currentScrollTop=o,this.followingEnd=a,this.followSuppressedAtEnd=l,c&&this.markScrollbarActivity(),this.requestRenderCallback?.();}scrollBy(e){let r=Number.isFinite(e)?Math.trunc(e):0;if(r===0)return 0;let n=Math.max(0,this.contentHeight-this.currentViewportHeight),s=this.followingEnd?n:this.currentScrollTop,o=Math.max(0,Math.min(n,s+r)),l=o-s,a=this.followingEnd;return this.currentScrollTop=o,this.followingEnd=this.followEnd&&o===n,this.followSuppressedAtEnd=false,l!==0&&this.markScrollbarActivity(),(l!==0||this.followingEnd!==a)&&this.requestRenderCallback?.(),r-l}scrollToStart(){let e=this.currentScrollTop!==0||this.followingEnd!==(this.followEnd&&this.contentHeight<=this.currentViewportHeight);this.currentScrollTop=0,this.followingEnd=this.followEnd&&this.contentHeight<=this.currentViewportHeight,this.followSuppressedAtEnd=false,e&&(this.markScrollbarActivity(),this.requestRenderCallback?.());}scrollToEnd(){let e=Math.max(0,this.contentHeight-this.currentViewportHeight),r=this.currentScrollTop!==e||this.followingEnd!==this.followEnd;this.currentScrollTop=e,this.followingEnd=this.followEnd,this.followSuppressedAtEnd=false,r&&(this.markScrollbarActivity(),this.requestRenderCallback?.());}updateLayout(e,r,n){this.contentHeight=Math.max(0,Math.floor(e)),this.currentViewportHeight=Math.max(0,Math.floor(r)),this.requestRenderCallback=n;let s=Math.max(0,this.contentHeight-this.currentViewportHeight);this.followingEnd?this.currentScrollTop=s:this.currentScrollTop=Math.max(0,Math.min(this.currentScrollTop,s)),this.currentScrollTop<s&&(this.followSuppressedAtEnd=false),this.followEnd&&this.currentScrollTop===s&&!this.followSuppressedAtEnd&&(this.followingEnd=true),this.contentHeight<=this.currentViewportHeight&&this.hideTransientScrollbar();}addChild(e){throw new Error("ScrollView has exactly one child")}removeChild(e){throw new Error("ScrollView child cannot be removed")}clear(){throw new Error("ScrollView child cannot be cleared")}render(e){let r=this.getContentWidth(e),n=this.child.render(r);return r===e?n:n.map(s=>`${s} `)}[je](){return {type:"scroll",component:this.child,state:this}}};var ci=class{constructor(t,e,r,n,s,o={}){d(this,"items");d(this,"filteredItems");d(this,"theme");d(this,"selectedIndex",0);d(this,"mousePressedIndex");d(this,"maxVisible");d(this,"onChange");d(this,"onCancel");d(this,"searchInput");d(this,"searchEnabled");d(this,"submenuComponent",null);d(this,"submenuItemIndex",null);d(this,"navigateAfterClose",null);this.items=t,this.filteredItems=t,this.maxVisible=e,this.theme=r,this.onChange=n,this.onCancel=s,this.searchEnabled=o.enableSearch??false,this.searchEnabled&&(this.searchInput=new Me);}updateValue(t,e){let r=this.items.find(n=>n.id===t);r&&(r.currentValue=e);}selectItem(t){let r=(this.searchEnabled?this.filteredItems:this.items).findIndex(n=>n.id===t);r!==-1&&(this.selectedIndex=r);}invalidate(){this.submenuComponent?.invalidate?.();}render(t){return this.submenuComponent?this.submenuComponent.render(t):this.renderMainList(t)}renderMainList(t){let e=[];if(this.searchEnabled&&this.searchInput&&(e.push(...this.searchInput.render(t)),e.push("")),this.items.length===0)return e.push(this.theme.hint(" No settings available")),this.searchEnabled&&this.addHintLine(e,t),e;let r=this.getDisplayItems();if(r.length===0)return e.push(N(this.theme.hint(" No matching settings"),t)),this.addHintLine(e,t),e;let{startIndex:n,endIndex:s}=this.getVisibleRange(r),o=Math.min(36,Math.max(...this.items.map(c=>S(c.label)))),l=Math.max(S(this.theme.cursor),2);for(let c=n;c<s;c++){let h=r[c];if(!h)continue;let u=c===this.selectedIndex,p=u?this.theme.cursor:" ",f=p+" ".repeat(Math.max(0,l-S(p))),b=h.label+" ".repeat(Math.max(0,o-S(h.label))),m=this.theme.label(b,u),g=" ",y=l+o+S(g),v=t-y-2,x=this.theme.value(N(h.currentValue,v,""),u);e.push(N(f+m+g+x,t));}if(n>0||s<r.length){let c=` (${this.selectedIndex+1}/${r.length})`;e.push(this.theme.hint(N(c,t-2,"")));}let a=r[this.selectedIndex];if(a?.description){e.push("");let c=ne(a.description,t-4);for(let h of c)e.push(this.theme.description(` ${h}`));}return this.addHintLine(e,t),e}handleMouse(t){if(this.submenuComponent){let l=this.submenuComponent.handleMouse?.(t);return l?{...l,focus:true}:void 0}if(this.searchEnabled&&this.searchInput){if(t.y===0){let l=this.searchInput.handleMouse?.(t);return l?{...l,focus:true}:void 0}if(t.y===1)return}let e=this.getDisplayItems();if(e.length===0)return;if(t.type==="wheel"&&t.wheelDelta){let l=t.wheelDelta<0?-1:1,a=this.selectedIndex;return this.selectedIndex=Math.max(0,Math.min(e.length-1,this.selectedIndex+l)),{handled:true,render:this.selectedIndex!==a}}if(t.button!=="left"||t.type!=="press"&&t.type!=="click")return;let r=this.searchEnabled?2:0,{startIndex:n,endIndex:s}=this.getVisibleRange(e),o=n+t.y-r;if(!(o<n||o>=s)){if(t.type==="press")return this.mousePressedIndex=o,this.selectedIndex=o,{handled:true,focus:true};if(t.type==="click")return this.selectedIndex=this.mousePressedIndex??o,this.mousePressedIndex=void 0,this.activateItem(),{handled:true}}}handleInput(t){if(this.submenuComponent){this.submenuComponent.handleInput?.(t);return}let e=G(),r=this.getDisplayItems();if(e.matches(t,"tui.select.up")){if(r.length===0)return;this.selectedIndex=this.selectedIndex===0?r.length-1:this.selectedIndex-1;}else if(e.matches(t,"tui.select.down")){if(r.length===0)return;this.selectedIndex=this.selectedIndex===r.length-1?0:this.selectedIndex+1;}else e.matches(t,"tui.select.confirm")||t===" "&&(!this.searchEnabled||this.searchInput?.getValue().length===0)?this.activateItem():e.matches(t,"tui.select.cancel")?this.onCancel():this.searchEnabled&&this.searchInput&&(this.searchInput.handleInput(t),this.applyFilter(this.searchInput.getValue()));}getDisplayItems(){return this.searchEnabled?this.filteredItems:this.items}getVisibleRange(t){let e=Math.max(0,Math.min(this.selectedIndex-Math.floor(this.maxVisible/2),t.length-this.maxVisible));return {startIndex:e,endIndex:Math.min(e+this.maxVisible,t.length)}}activateItem(){let t=this.getDisplayItems()[this.selectedIndex];if(t){if(t.submenu)this.submenuItemIndex=this.selectedIndex,this.submenuComponent=t.submenu(t.currentValue,(e,r)=>{e!==void 0&&(t.currentValue=e,this.onChange(t.id,e)),r?.navigateTo&&(this.navigateAfterClose=r.navigateTo),this.closeSubmenu();});else if(t.values&&t.values.length>0){let r=(t.values.indexOf(t.currentValue)+1)%t.values.length,n=t.values[r];t.currentValue=n,this.onChange(t.id,n);}}}closeSubmenu(){if(this.submenuComponent=null,this.navigateAfterClose!==null){let t=this.navigateAfterClose;this.navigateAfterClose=null,this.submenuItemIndex=null,this.selectItem(t),this.activateItem();}else this.submenuItemIndex!==null&&(this.selectedIndex=this.submenuItemIndex,this.submenuItemIndex=null);}applyFilter(t){this.filteredItems=Re(this.items,t,e=>e.label),this.selectedIndex=0;}addHintLine(t,e){t.push(""),t.push(N(this.theme.hint(this.searchEnabled?" Type to search \xB7 Enter/Space to change \xB7 Esc to cancel":" Enter/Space to change \xB7 Esc to cancel"),e));}};var ui=class{constructor(t=1){d(this,"lines");this.lines=t;}setLines(t){this.lines=t;}invalidate(){}render(t){let e=[];for(let r=0;r<this.lines;r++)e.push("");return e}};var hi=class{constructor(t,e=0,r=0){d(this,"text");d(this,"paddingX");d(this,"paddingY");this.text=t,this.paddingX=e,this.paddingY=r;}invalidate(){}render(t){let e=[],r=" ".repeat(t);for(let b=0;b<this.paddingY;b++)e.push(r);let n=Math.max(1,t-this.paddingX*2),s=this.text,o=this.text.indexOf(`
40
+ `);o!==-1&&(s=this.text.substring(0,o));let l=N(s,n),a=" ".repeat(this.paddingX),c=" ".repeat(this.paddingX),h=a+l+c,u=S(h),p=Math.max(0,t-u),f=h+" ".repeat(p);e.push(f);for(let b=0;b<this.paddingY;b++)e.push(r);return e}};var di=class extends Xe{constructor(e=[],r={}){super(e,r);d(this,"layoutType","vstack");}render(e){let r={width:Math.max(1,e),height:Number.MAX_SAFE_INTEGER},n=Qe(this.entries,r),s=n.map(a=>a.component.render(r.width)),o=Ce(n,s.map(a=>a.length),void 0,this.gap),l=[];for(let a=0;a<n.length;a++){if(a>0)for(let h=0;h<this.gap;h++)l.push("");let c=s[a].slice(0,o[a]);l.push(...c);for(let h=c.length;h<o[a];h++)l.push("");}return l}};var pi=class{constructor(t=80,e=24){d(this,"writes",[]);d(this,"inputHandler");d(this,"resizeHandler");d(this,"programStatuses",[]);d(this,"progressStates",[]);d(this,"_columns");d(this,"_rows");d(this,"_kittyActive",false);this._columns=t,this._rows=e;}start(t,e){this.inputHandler=t,this.resizeHandler=e;}async drainInput(t,e){}stop(){this.inputHandler=void 0,this.resizeHandler=void 0;}write(t){this.writes.push(t);}get columns(){return this._columns}get rows(){return this._rows}get kittyProtocolActive(){return this._kittyActive}setColumns(t){this._columns=t;}setRows(t){this._rows=t;}feedInput(t){this.inputHandler?.(t);}resize(t,e){this._columns=t,this._rows=e,this.resizeHandler?.();}moveBy(t){t>0?this.write(`\x1B[${t}B`):t<0&&this.write(`\x1B[${-t}A`);}hideCursor(){this.write("\x1B[?25l");}showCursor(){this.write("\x1B[?25h");}clearLine(){this.write("\x1B[K");}clearFromCursor(){this.write("\x1B[J");}clearScreen(){this.write("\x1B[2J\x1B[H");}setTitle(t){this.write(`\x1B]0;${t}\x07`);}setProgramStatus(t){this.programStatuses.push(t);}setProgress(t){this.progressStates.push(t);}output(){return this.writes.join("")}};var Ya=createRequire(import.meta.url),ja="@earendil-works/pi-tui";function Xn(i,t={}){let e=dirname(fileURLToPath(t.moduleUrl??import.meta.url)),r=[];r.push(join(e,"..",i)),r.push(join(e,"..","dist","assets","node",i));try{let n=(t.resolvePackage??Ya.resolve)(ja);r.push(join(dirname(n),"..",i));}catch{}return r.push(join(e,i),join(dirname(t.execPath??process.execPath),i)),Array.from(new Set(r))}var Qa=createRequire(import.meta.url),rr=new Map;function Jn(i,t=""){let e=process.arch;if(e!=="x64"&&e!=="arm64")return;let r=Ae.join("native",i,"prebuilds",`${i}-${e}`,`${i}-platform${t}.node`);if(rr.has(r))return rr.get(r);for(let n of Xn(r))try{let s=Qa(n);if(typeof s?.getText=="function"&&typeof s.getImage=="function")return rr.set(r,s),s}catch{}rr.set(r,void 0);}function gt(){if(!(process.platform!=="darwin"&&process.platform!=="win32"))return Jn(process.platform)}function Ja(){if(process.platform!=="linux")return gt();if(process.env.DISPLAY)return Jn("linux","-x11")}function mi(i){let t=gt();if(!t?.isModifierPressed)return false;try{return t.isModifierPressed(i)===!0}catch{return false}}var Zn="\x1B]7501;?\x1B\\";function es(i){return /^\x1b\]7501;\?[^\x07\x1b]*(?:\x07|\x1b\\)$/.test(i)}var Za=/^[A-Za-z0-9_.+-]{1,32}$/,el=/[\u0000-\u001f\u007f-\u009f]+/g,tl=2048;function rl(i,t){if(Buffer.byteLength(i,"utf8")<=t)return i;let e=0,r=0;for(let n of i){let s=Buffer.byteLength(n,"utf8");if(e+s>t)break;e+=s,r+=n.length;}return i.slice(0,r)}function bt(i){let t=[`state=${i.state}`];i.app!==void 0&&Za.test(i.app)&&t.push(`app=${i.app}`),i.state==="blocked"&&i.kind&&t.push(`kind=${i.kind}`);let e=rl((i.message??"").replace(el," ").trim(),tl);return e&&t.push(`msg=${Buffer.from(e,"utf8").toString("base64")}`),`\x1B]7501;${t.join(":")}\x1B\\`}var z="\x1B",nl=50,sl=10,ts="\x1B[200~",ir="\x1B[201~",is=/^\x1b(?:\](?:1[01];|4;\d{1,3};|7501;\?)|P>\||_G(?:[a-z]=\d+,)*[a-z]=\d+;)/;function ns(i){return i.startsWith(`${z}]`)||i.startsWith(`${z}P`)||i.startsWith(`${z}_`)}function ol(i){if(!i.startsWith(z))return "not-escape";if(i.length===1)return "incomplete";let t=i.slice(1);return t.startsWith("[")?t.startsWith("[M")?i.length>=6?"complete":"incomplete":al(i):t.startsWith("]")?ll(i):t.startsWith("P")?cl(i):t.startsWith("_")?ul(i):t.startsWith("O")?t.length>=2?"complete":"incomplete":(t.length===1,"complete")}function al(i){if(!i.startsWith(`${z}[`))return "complete";if(i.length<3)return "incomplete";let t=i.slice(2),e=t[t.length-1],r=e.charCodeAt(0);if(r>=64&&r<=126){if(t.startsWith("<")){if(/^<\d+;\d+;\d+[Mm]$/.test(t))return "complete";if(e==="M"||e==="m"){let s=t.slice(1,-1).split(";");if(s.length===3&&s.every(o=>/^\d+$/.test(o)))return "complete"}return "incomplete"}return "complete"}return "incomplete"}function ll(i){return !i.startsWith(`${z}]`)||i.endsWith(`${z}\\`)||i.endsWith("\x07")?"complete":"incomplete"}function cl(i){return !i.startsWith(`${z}P`)||i.endsWith(`${z}\\`)?"complete":"incomplete"}function ul(i){return !i.startsWith(`${z}_`)||i.endsWith(`${z}\\`)?"complete":"incomplete"}function hl(i){let t=i.match(/^\x1b\[(\d+)(?::\d*)?(?::\d+)?u$/);if(!t)return;let e=parseInt(t[1],10);return e>=32?e:void 0}function rs(i){let t=[],e=0;for(;e<i.length;){let r=i.slice(e);if(r.startsWith(z)){let n=ns(r)&&is.test(r),s=1;for(;s<=r.length;){if(n&&s>2){let a=r[s-1];if(a===""||a===""){e+=s;break}if(a===z&&s<r.length&&r[s]!=="\\"){e+=s-1;break}}let o=r.slice(0,s),l=ol(o);if(l==="complete"){if(o==="\x1B\x1B"){let a=r[s];if(a==="["||a==="]"||a==="O"||a==="P"||a==="_"){t.push(z),e+=1;break}}t.push(o),e+=s;break}else if(l==="incomplete")s++;else {t.push(o),e+=s;break}}if(s>r.length)return {sequences:t,remainder:r}}else t.push(r[0]),e++;}return {sequences:t,remainder:""}}var yt=class extends EventEmitter{constructor(e={}){super();d(this,"buffer","");d(this,"timeout",null);d(this,"timeoutMs");d(this,"escapeTimeoutMs");d(this,"pasteMode",false);d(this,"pasteBuffer","");d(this,"pendingKittyPrintableCodepoint");this.timeoutMs=e.timeout??nl,this.escapeTimeoutMs=e.escapeTimeout??sl;}process(e){this.timeout&&(clearTimeout(this.timeout),this.timeout=null);let r;if(Buffer.isBuffer(e))if(e.length===1&&e[0]>127){let o=e[0]-128;r=`\x1B${String.fromCharCode(o)}`;}else r=e.toString();else r=e;if(r.length===0&&this.buffer.length===0){this.emitDataSequence("");return}if(this.buffer+=r,this.pasteMode){this.pasteBuffer+=this.buffer,this.buffer="";let o=this.pasteBuffer.indexOf(ir);if(o!==-1){let l=this.pasteBuffer.slice(0,o),a=this.pasteBuffer.slice(o+ir.length);this.pasteMode=false,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0,this.emit("paste",l),a.length>0&&this.process(a);}return}let n=this.buffer.indexOf(ts);if(n!==-1){if(n>0){let l=this.buffer.slice(0,n),a=rs(l);for(let c of a.sequences)this.emitDataSequence(c);}this.pendingKittyPrintableCodepoint=void 0,this.buffer=this.buffer.slice(n+ts.length),this.pasteMode=true,this.pasteBuffer=this.buffer,this.buffer="";let o=this.pasteBuffer.indexOf(ir);if(o!==-1){let l=this.pasteBuffer.slice(0,o),a=this.pasteBuffer.slice(o+ir.length);this.pasteMode=false,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0,this.emit("paste",l),a.length>0&&this.process(a);}return}let s=rs(this.buffer);this.buffer=s.remainder;for(let o of s.sequences)this.emitDataSequence(o);if(this.buffer.length>0){if(is.test(this.buffer))return;let o=this.buffer===z?this.escapeTimeoutMs:this.timeoutMs;this.timeout=setTimeout(()=>{let l=this.flush();for(let a of l)a.length>2&&ns(a)?(this.emitDataSequence(a.slice(0,2)),this.process(a.slice(2))):this.emitDataSequence(a);},o);}}emitDataSequence(e){let r=e.length===1?e.codePointAt(0):void 0;if(r!==void 0&&r===this.pendingKittyPrintableCodepoint){this.pendingKittyPrintableCodepoint=void 0;return}this.pendingKittyPrintableCodepoint=hl(e),this.emit("data",e);}flush(){if(this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.buffer.length===0)return [];let e=[this.buffer];return this.buffer="",this.pendingKittyPrintableCodepoint=void 0,e}clear(){this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.buffer="",this.pasteMode=false,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0;}getBuffer(){return this.buffer}destroy(){this.clear();}};var dl=1e3,ss="\x1B]9;4;3\x07",os="\x1B]9;4;0\x07",pl="\x1B[13;2u",fl=7,ml=150,gl=`\x1B[>${fl}u\x1B[?u`,bl="\x1B[c";function as(i){let t=i.match(/^\x1b\[\?(\d+)u$/);if(t)return {type:"kitty-flags",flags:Number.parseInt(t[1],10)};if(/^\x1b\[\?[\d;]*c$/.test(i))return {type:"device-attributes"}}function ls(i){return i==="\x1B["||/^\x1b\[\?[\d;]*$/.test(i)}function us(){return process.platform==="darwin"&&process.env.TERM_PROGRAM==="Apple_Terminal"}function yl(){if(!(process.platform==="win32"||process.pid<=0))try{process.kill(process.pid,"SIGWINCH");}catch{}}function xl(i,t,e){return t&&i==="\r"&&e?pl:i}var vl=10,Sl=100;function Cl(i=process.env){let t=Number(i.PI_TUI_ESC_TIMEOUT);return Number.isFinite(t)&&t>0?t:i.SSH_CONNECTION||i.SSH_TTY?Sl:vl}var gi=class{constructor(){d(this,"wasRaw",false);d(this,"inputHandler");d(this,"resizeHandler");d(this,"_kittyProtocolActive",false);d(this,"_modifyOtherKeysActive",false);d(this,"keyboardProtocolPushed",false);d(this,"pendingKeyboardProtocolDeviceAttributes",0);d(this,"keyboardProtocolNegotiationBuffer","");d(this,"keyboardProtocolBufferFlushTimer");d(this,"stdinBuffer");d(this,"stdinDataHandler");d(this,"progressInterval");d(this,"programStatus");d(this,"programStatusSupported",false);d(this,"programStatusQueryPending",false);d(this,"writeLogPath",(()=>{let t=process.env.PI_TUI_WRITE_LOG||"";if(!t)return "";try{if(pe.statSync(t).isDirectory()){let e=new Date,r=`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")}_${String(e.getHours()).padStart(2,"0")}-${String(e.getMinutes()).padStart(2,"0")}-${String(e.getSeconds()).padStart(2,"0")}`;return Ae.join(t,`tui-${r}-${process.pid}.log`)}}catch{}return t})());}get kittyProtocolActive(){return this._kittyProtocolActive}get modifyOtherKeysActive(){return this._modifyOtherKeysActive}start(t,e){this.inputHandler=t,this.resizeHandler=e,this.wasRaw=process.stdin.isRaw||false,process.stdin.setRawMode&&process.stdin.setRawMode(true),process.stdin.setEncoding("utf8"),process.stdin.resume(),process.stdout.write("\x1B[?2004h"),process.stdout.on("resize",this.resizeHandler),yl(),this.enableWindowsVTInput(),this.queryAndEnableKittyProtocol();}setupStdinBuffer(){this.stdinBuffer=new yt({escapeTimeout:Cl()}),this.stdinBuffer.on("data",t=>{if(es(t)){this.programStatusQueryPending&&(this.programStatusQueryPending=false,this.programStatusSupported=true,this.writeProgramStatus());return}let e=this.readKeyboardProtocolNegotiationSequence(t);if(e==="pending"){this.scheduleKeyboardProtocolNegotiationBufferFlush();return}e&&this.handleKeyboardProtocolNegotiationSequence(e.parsed)||this.forwardInputSequence(e?.sequence??t);}),this.stdinBuffer.on("paste",t=>{this.inputHandler&&this.inputHandler(`\x1B[200~${t}\x1B[201~`);}),this.stdinDataHandler=t=>{this.stdinBuffer.process(t);};}queryAndEnableKittyProtocol(){this.setupStdinBuffer(),process.stdin.on("data",this.stdinDataHandler),this.keyboardProtocolPushed=true,this.pendingKeyboardProtocolDeviceAttributes+=1,this.clearKeyboardProtocolNegotiationBuffer();let t=process.env.PI_PROGRAM_STATUS;this.programStatusSupported=t==="1",this.programStatusQueryPending=t!=="1"&&t!=="0";let e=this.programStatusQueryPending?Zn:"";process.stdout.write(`${gl}${e}${bl}`),this.writeProgramStatus();}handleKeyboardProtocolNegotiationSequence(t){if(this.clearKeyboardProtocolNegotiationBuffer(),t.type==="device-attributes"){if(this.pendingKeyboardProtocolDeviceAttributes===0)return false;this.pendingKeyboardProtocolDeviceAttributes-=1,this.pendingKeyboardProtocolDeviceAttributes===0&&(this.programStatusQueryPending=false);}return t.type==="kitty-flags"?(t.flags!==0?(this.disableModifyOtherKeys(),this._kittyProtocolActive||(this._kittyProtocolActive=true,st(true))):this.enableModifyOtherKeys(),true):(this._kittyProtocolActive||this.enableModifyOtherKeys(),true)}readKeyboardProtocolNegotiationSequence(t){if(this.keyboardProtocolNegotiationBuffer){let r=this.keyboardProtocolNegotiationBuffer+t,n=as(r);if(n)return this.clearKeyboardProtocolNegotiationBuffer(),{parsed:n,sequence:r};if(ls(r))return this.setKeyboardProtocolNegotiationBuffer(r),"pending";this.flushKeyboardProtocolNegotiationBufferAsInput();}let e=as(t);if(e)return {parsed:e,sequence:t};if(ls(t))return this.setKeyboardProtocolNegotiationBuffer(t),"pending"}setKeyboardProtocolNegotiationBuffer(t){this.clearKeyboardProtocolNegotiationBufferFlushTimer(),this.keyboardProtocolNegotiationBuffer=t;}clearKeyboardProtocolNegotiationBuffer(){this.clearKeyboardProtocolNegotiationBufferFlushTimer(),this.keyboardProtocolNegotiationBuffer="";}flushKeyboardProtocolNegotiationBufferAsInput(){if(!this.keyboardProtocolNegotiationBuffer)return;let t=this.keyboardProtocolNegotiationBuffer;this.clearKeyboardProtocolNegotiationBuffer(),this.forwardInputSequence(t);}scheduleKeyboardProtocolNegotiationBufferFlush(){!this.keyboardProtocolNegotiationBuffer||this.keyboardProtocolBufferFlushTimer||(this.keyboardProtocolBufferFlushTimer=setTimeout(()=>{this.keyboardProtocolBufferFlushTimer=void 0,this.flushKeyboardProtocolNegotiationBufferAsInput();},ml));}clearKeyboardProtocolNegotiationBufferFlushTimer(){this.keyboardProtocolBufferFlushTimer&&(clearTimeout(this.keyboardProtocolBufferFlushTimer),this.keyboardProtocolBufferFlushTimer=void 0);}forwardInputSequence(t){if(!this.inputHandler)return;let e=t==="\r"&&(us()||process.platform==="win32"),r=xl(t,e,e&&mi("shift"));this.inputHandler(r);}enableModifyOtherKeys(){this._kittyProtocolActive||this._modifyOtherKeysActive||(process.stdout.write("\x1B[>4;2m"),this._modifyOtherKeysActive=true);}disableModifyOtherKeys(){this._modifyOtherKeysActive&&(process.stdout.write("\x1B[>4;0m"),this._modifyOtherKeysActive=false);}enableWindowsVTInput(){if(process.platform==="win32")try{gt()?.enableVirtualTerminalInput?.();}catch{}}async drainInput(t=1e3,e=50){let r=this.keyboardProtocolPushed||this._kittyProtocolActive;this.clearKeyboardProtocolNegotiationBuffer(),r&&(process.stdout.write("\x1B[<u"),this.keyboardProtocolPushed=false,this._kittyProtocolActive=false,st(false)),this.disableModifyOtherKeys();let n=this.inputHandler;this.inputHandler=void 0;let s=Date.now(),o=()=>{s=Date.now();};process.stdin.on("data",o);let l=Date.now()+t;try{for(;;){let a=Date.now(),c=l-a;if(c<=0||a-s>=e)break;await new Promise(h=>setTimeout(h,Math.min(e,c)));}}finally{process.stdin.removeListener("data",o),this.inputHandler=n;}}stop(){this.clearProgressInterval()&&process.stdout.write(os),this.programStatusSupported&&this.programStatus&&process.stdout.write(bt({state:"clear"})),this.programStatusSupported=false,this.programStatusQueryPending=false,process.stdout.write("\x1B[?2004l");let t=this.keyboardProtocolPushed||this._kittyProtocolActive;this.clearKeyboardProtocolNegotiationBuffer(),t&&(process.stdout.write("\x1B[<u"),this.keyboardProtocolPushed=false,this._kittyProtocolActive=false,st(false)),this.disableModifyOtherKeys(),this.stdinBuffer&&(this.stdinBuffer.destroy(),this.stdinBuffer=void 0),this.stdinDataHandler&&(process.stdin.removeListener("data",this.stdinDataHandler),this.stdinDataHandler=void 0),this.inputHandler=void 0,this.resizeHandler&&(process.stdout.removeListener("resize",this.resizeHandler),this.resizeHandler=void 0),process.stdin.pause(),process.stdin.setRawMode&&process.stdin.setRawMode(this.wasRaw);}write(t){if(process.stdout.write(t),this.writeLogPath)try{pe.appendFileSync(this.writeLogPath,t,{encoding:"utf8"});}catch{}}get columns(){return process.stdout.columns||Number(process.env.COLUMNS)||80}get rows(){return process.stdout.rows||Number(process.env.LINES)||24}moveBy(t){t>0?process.stdout.write(`\x1B[${t}B`):t<0&&process.stdout.write(`\x1B[${-t}A`);}hideCursor(){process.stdout.write("\x1B[?25l");}showCursor(){process.stdout.write("\x1B[?25h");}clearLine(){process.stdout.write("\x1B[K");}clearFromCursor(){process.stdout.write("\x1B[J");}clearScreen(){process.stdout.write("\x1B[2J\x1B[H");}setTitle(t){process.stdout.write(`\x1B]0;${t}\x07`);}setProgramStatus(t){this.programStatus=t.state==="clear"?void 0:t,this.programStatusSupported&&process.stdout.write(bt(t));}writeProgramStatus(){this.programStatusSupported&&this.programStatus&&process.stdout.write(bt(this.programStatus));}setProgress(t){t?(process.stdout.write(ss),this.progressInterval||(this.progressInterval=setInterval(()=>{process.stdout.write(ss);},dl))):(this.clearProgressInterval(),process.stdout.write(os));}clearProgressInterval(){return this.progressInterval?(clearInterval(this.progressInterval),this.progressInterval=void 0,true):false}};var wl=Pe(),Tl=/^[\x20-\x7e]*$/;function Ml(i){let t=[],e=[],r=0,n=false,s=()=>{n&&(t.push(" "),r+=1,n=false);};for(let o=0;o<i.length;o++){let l=Be(i[o]??""),a=0;if(Tl.test(l)){let c=0;for(;c<l.length;){if(l.charCodeAt(c)===32){r>0&&(n=true),a+=1,c+=1;continue}let h=c+1;for(;h<l.length&&l.charCodeAt(h)!==32;)h+=1;s();let u=l.slice(c,h);t.push(u),e.push({textStart:r,textEnd:r+u.length,row:o,startCol:a,endCol:a+u.length,linearColumns:true}),r+=u.length,a+=u.length,c=h;}}else for(let c of wl.segment(l)){let h=c.segment,u=S(h);if(/^\s+$/u.test(h)){r>0&&(n=true),a+=u;continue}s(),t.push(h),e.push({textStart:r,textEnd:r+h.length,row:o,startCol:a,endCol:a+u,linearColumns:false}),r+=h.length,a+=u;}r>0&&(n=true);}return {text:t.join(""),spans:e}}function Il(i){return i.replace(/\s+/gu," ").trim()}function Ll(i){return i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function kl(i,t){if(!t)return [];let e=new RegExp(Ll(t),"giu"),r=[],n=0;for(let s of i.text.matchAll(e)){let o=s.index,l=o+s[0].length;for(;n<i.spans.length&&i.spans[n].textEnd<=o;)n+=1;let a=[];for(let c=n;c<i.spans.length;c++){let h=i.spans[c];if(h.textStart>=l)break;if(h.textEnd<=o)continue;let u=h.linearColumns?h.startCol+Math.max(o,h.textStart)-h.textStart:h.startCol,p=h.linearColumns?h.startCol+Math.min(l,h.textEnd)-h.textStart:h.endCol,f=a[a.length-1];f&&f.row===h.row&&u<=f.endCol?f.endCol=Math.max(f.endCol,p):a.push({row:h.row,startCol:u,endCol:p});}for(;n<i.spans.length&&i.spans[n].textEnd<=l;)n+=1;a.length>0&&r.push({segments:a});}return r}var sr=class{constructor(){d(this,"sourceLines");d(this,"corpus");d(this,"normalizedQuery");d(this,"matches",[]);}search(t,e){let r=this.sourceLines?.length!==t.length;if(!r&&this.sourceLines){for(let o=0;o<t.length;o++)if(this.sourceLines[o]!==t[o]){r=true;break}}(r||!this.corpus)&&(this.sourceLines=Array.from(t),this.corpus=Ml(t));let n=Il(e),s=r||n!==this.normalizedQuery;return s&&(this.normalizedQuery=n,this.matches=kl(this.corpus,n)),{matches:this.matches,changed:s}}};function bi(i){let t=i.segments[0],e=i.segments[i.segments.length-1];return t&&e?`${t.row}:${t.startCol}:${e.row}:${e.endCol}`:""}var or=class{constructor(t,e=r=>r){d(this,"input",new Me({prompt:" ",placeholder:"Find in transcript",placeholderStyle:t=>`\x1B[2m${t}\x1B[22m`}));d(this,"onQueryChange");d(this,"navigationButtonStyle");d(this,"resultCount",0);d(this,"resultIndex",-1);d(this,"previousButtonStart",-1);d(this,"previousButtonEnd",-1);d(this,"nextButtonStart",-1);d(this,"nextButtonEnd",-1);d(this,"hoveredNavigationDirection");d(this,"_focused",false);this.onQueryChange=t,this.navigationButtonStyle=e;}get focused(){return this._focused}set focused(t){this._focused=t,this.input.focused=t;}setResult(t,e){this.resultIndex=t,this.resultCount=e;}getNavigationDirectionAt(t,e){if(t===2){if(e>=this.previousButtonStart&&e<this.previousButtonEnd)return -1;if(e>=this.nextButtonStart&&e<this.nextButtonEnd)return 1}}setHoveredNavigationDirection(t){return t===this.hoveredNavigationDirection?false:(this.hoveredNavigationDirection=t,true)}handleInput(t){let e=this.input.getValue();this.input.handleInput(t);let r=this.input.getValue();r!==e&&this.onQueryChange(r);}invalidate(){this.input.invalidate();}render(t){let e=Math.max(1,t),r=Math.max(0,e-2),n=D=>D?D.split("+").map(B=>process.platform==="darwin"&&B.toLowerCase()==="alt"?"Option":B.charAt(0).toUpperCase()+B.slice(1)).join("+"):"Unbound",s=G(),o=n(s.getKeys("tui.altScreen.searchPrevious")[0]),l=n(s.getKeys("tui.altScreen.searchNext")[0]),c=this.input.getValue()?this.resultCount===0?"No matches":`${this.resultIndex+1}/${this.resultCount}`:"",h=Math.max(0,r-3),u=N(c,h,""),p=u?`\x1B[2m ${u} \x1B[22m`:"",f=Math.max(0,r-S(p)),b=N(this.input.render(Math.max(1,f))[0]??"",f,""),m=" ".repeat(Math.max(0,f-S(b))),g=`${b}${m}${p}`,y=`\u2191 ${o}`,v=`\u2193 ${l}`,x=" \xB7 ",w=1,I=Math.max(0,r-w*2-1),T=S(y)+S(x)+S(v);T>I&&(y="\u2191",v="\u2193",x=" ",T=S(y)+S(x)+S(v));let L=T<=I,M=L?this.navigationButtonStyle(y,this.hoveredNavigationDirection===-1)+x+this.navigationButtonStyle(v,this.hoveredNavigationDirection===1):"",E=L?w*2:0,P=M&&r>T+E?1:0,C=Math.max(0,r-(L?T:0)-E-P),A=1+C+w;return this.previousButtonStart=L?A:-1,this.previousButtonEnd=L?A+S(y):-1,this.nextButtonStart=L?this.previousButtonEnd+S(x):-1,this.nextButtonEnd=L?this.nextButtonStart+S(v):-1,e===1?["\u250C","\u2502","\u2514"]:[`\u250C${"\u2500".repeat(r)}\u2510`,`\u2502${g}\u2502`,`\u2514${"\u2500".repeat(C)}${M?" ":""}${M}${M?" ":""}${"\u2500".repeat(P)}\u2518`]}};var Al=1e3,ar=class{constructor(t){d(this,"entries",[]);d(this,"nextId",0);d(this,"requestRender");this.requestRender=t;}flash(t,e=Al){let r=this.nextId++,n=setTimeout(()=>{let s=this.entries.findIndex(o=>o.id===r);s!==-1&&(this.entries.splice(s,1),this.requestRender());},Math.max(0,e));n.unref(),this.entries.push({id:r,message:t,timer:n}),this.requestRender();}dispose(){for(let t of this.entries)clearTimeout(t.timer);this.entries.length=0;}invalidate(){}render(t){return this.entries.map(e=>`\x1B[7m${N(` ${e.message} `,t,"")}\x1B[27m`)}};var Rl=/^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/;function xt(i,t){let e=Math.max(i.x,t.x),r=Math.max(i.y,t.y),n=Math.min(i.x+i.width,t.x+t.width),s=Math.min(i.y+i.height,t.y+t.height);return {x:e,y:r,width:Math.max(0,n-e),height:Math.max(0,s-r)}}function cr(i,t,e){let r=Math.max(1,Math.floor(e)),n=i.renderCache.get(t);n||(n=new Map,i.renderCache.set(t,n));let s=n.get(r);return s||(s=t.render(r),n.set(r,s)),s}function hs(i,t,e){return cr(i,t,e).length}function El(i,t,e){return cr(i,t,e).reduce((r,n)=>Math.max(r,S(n)),0)}function ds(i,t){return i.parent=t,i}function ps(i,t){i.rect.y+=t;for(let e of i.children)ps(e,t);}function fs(i,t){i.clip=xt(t,i.rect);for(let e of i.children)fs(e,i.clip);}function lr(i,t,e,r,n,s,o){let l=Math.max(1,Math.floor(n)),a=Jt(t);if(!a){let v=cr(i,t,l),x=s===void 0?v.length:Math.max(0,Math.floor(s)),w=0;if(v.length>x&&x>0){let I=v.findIndex(T=>T.includes(re));I>=x&&(w=I-x+1);}return {component:t,rect:{x:e,y:r,width:l,height:x},clip:xt(o,{x:e,y:r,width:l,height:x}),children:[],lines:v,lineOffset:w,layer:0}}if(a.type==="scroll"){let v=a.state.scrollTop,x=a.state.getContentWidth(l),w=lr(i,a.component,e,r-v,x,void 0,o),I=w.rect.height,T=s===void 0?I:Math.max(0,Math.floor(s));a.state.updateLayout(I,T,i.requestRender),ps(w,v-a.state.scrollTop);let L=a.state;(a.state.primary||!i.primaryScrollView)&&(i.primaryScrollView=L);let M={x:e,y:r,width:l,height:T},E=xt(o,M),P={component:t,rect:M,clip:E,children:[w],scrollView:L,scrollContentLines:cr(i,a.component,x),layer:0};return w.parent=P,fs(w,E),P}let c=Qe(a.entries,i.viewport),h=Math.max(0,c.length-1)*a.gap;if(a.type==="vstack"){let v=c.map(E=>typeof E.basis=="number"?E.basis:hs(i,E.component,l)),x=Ce(c,v,s,a.gap),w=x.reduce((E,P)=>E+P,0)+h,I=s===void 0?w:Math.max(0,Math.floor(s)),T={x:e,y:r,width:l,height:I},L={component:t,rect:T,clip:xt(o,T),children:[],layer:0},M=r;for(let E=0;E<c.length;E++)L.children.push(ds(lr(i,c[E].component,e,M,l,x[E],L.clip),L)),M+=x[E]+a.gap;return L}let u=c.map(v=>typeof v.basis=="number"?v.basis:El(i,v.component,l)),p=Ce(c,u,l,a.gap),f=c.map((v,x)=>hs(i,v.component,Math.max(1,p[x]))),b=s===void 0?f.reduce((v,x)=>Math.max(v,x),0):Math.max(0,s),m={x:e,y:r,width:l,height:b},g={component:t,rect:m,clip:xt(o,m),children:[],layer:0},y=e;for(let v=0;v<c.length;v++){let x=f[v],w=a.align==="stretch"?b:Math.min(b,x),I=r;a.align==="center"?I+=Math.floor((b-w)/2):a.align==="end"&&(I+=b-w);let T=p[v];T===0?g.children.push({component:c[v].component,rect:{x:y,y:I,width:0,height:w},clip:{x:y,y:I,width:0,height:0},children:[],parent:g,layer:0}):g.children.push(ds(lr(i,c[v].component,y,I,T,w,g.clip),g)),y+=T+a.gap;}return g}function Pl(i,t,e,r,n){if(F(i))return i;let s=tt(i,t),o=s?.start??t,l=s?.end??t+1,a=V(i,0,o,true),c=V(i,o,l-o,true),h=V(i,l,Math.max(0,e-l),true),u="",p=0;for(;p<c.length;){let y=W(c,p);if(!y)break;u+=y.code,p+=y.length;}let f=" ".repeat(Math.max(0,o-S(a))),b=" ".repeat(Math.max(0,t-o)),m=" ".repeat(Math.max(0,l-t-1)),g=`\x1B[0m\x1B]8;;\x07${n?ki(u):""}`;return `${a}${f}${g}${b}${r}${m}${h}`}function Ze(i,t=false){if(!i.scrollView||i.rect.width<=0||i.rect.height<=0)return;let e=i.children[0]?.rect.height??i.scrollContentLines?.length??0,r=i.rect.height,n=t&&i.scrollView.scrollbar==="auto"&&e>r;if(!i.scrollView.isScrollbarVisible&&!n)return;let s=Math.min(2,r),o=Math.max(s,Math.min(r,Math.round(r*r/e))),l=Math.max(0,e-r),a=r-o,c=l===0?0:Math.round(i.scrollView.scrollTop/l*a),h=i.rect.x+i.rect.width-1;if(!(h<i.clip.x||h>=i.clip.x+i.clip.width))return {column:h,trackTop:i.rect.y,trackHeight:r,thumbTop:i.rect.y+c,thumbHeight:o,maxScrollTop:l}}function Ol(i,t,e){let r=Ze(i);if(!(!r||!i.scrollView))for(let n=0;n<r.trackHeight;n++){let s=r.trackTop+n;if(s<i.clip.y||s>=i.clip.y+i.clip.height||s<0||s>=t.length)continue;let l=s>=r.thumbTop&&s<r.thumbTop+r.thumbHeight?i.scrollView.scrollbarThumbStyle(i.scrollView.isScrollbarActive?"\u2588":"\u2503"):i.scrollView.scrollbarTrackStyle("\u2502");t[s]=Pl(t[s]??"",r.column,e,l,i.scrollView.scrollbar!=="always");}}function ms(i,t,e){if(i.lines){let r=i.lineOffset??0,n=Math.max(i.rect.y,i.clip.y,0),s=Math.min(i.rect.y+i.rect.height,i.clip.y+i.clip.height,t.length);for(let o=n;o<s;o++){let l=i.lines[r+o-i.rect.y];if(l===void 0)continue;let a=l.replace(Rl,""),c=Ft(a);if(c){let h=Math.min(t.length,i.clip.y+i.clip.height),u=Math.min(c.rows,h-o);u<c.rows&&(a=Fr(a,0,u));}i.rect.x===0&&i.rect.width>=e&&(F(a)||!t[o])?t[o]=a:t[o]=he(t[o]??"",a,i.rect.x,i.rect.width,e);}}for(let r of i.children)ms(r,t,e);if(i.scrollView&&i.scrollContentLines&&i.scrollView.scrollTop>0&&i.rect.height>0)for(let r=i.scrollView.scrollTop-1;r>=0;r--){let n=i.scrollContentLines[r]??"",s=Ft(n);if(s){let o=i.scrollView.scrollTop-r;if(o<s.rows){let l=Math.min(i.rect.height,s.rows-o),a=Fr(n,o,l);i.rect.x===0&&i.rect.width>=e&&(t[i.rect.y]=a);}break}if(n!=="")break}Ol(i,t,e);}function xi(i,t,e,r){let n=Math.max(1,Math.floor(t)),s=Math.max(1,Math.floor(e)),o={viewport:{width:n,height:s},renderCache:new Map,requestRender:r,primaryScrollView:void 0},l=lr(o,i,0,0,n,s,{x:0,y:0,width:n,height:s}),a=Array.from({length:s},()=>"");return ms(l,a,n),{root:l,width:n,height:s,lines:a,...o.primaryScrollView===void 0?{}:{primaryScrollView:o.primaryScrollView}}}function yi(i,t,e){return t>=i.x&&t<i.x+i.width&&e>=i.y&&e<i.y+i.height}function gs(i,t,e){let r=[],n=(s,o)=>{if(yi(s.clip,t,e)){r.push({box:s,depth:o});for(let l of s.children)n(l,o+1);}};return n(i.root,0),r.sort((s,o)=>o.box.layer-s.box.layer||o.depth-s.depth),r.map(({box:s})=>s)}function ie(i,t){let e=r=>{if(r.scrollView===t)return r;for(let n of r.children){let s=e(n);if(s)return s}};return e(i.root)}function ur(i,t,e){let r=[],n=(s,o)=>{if(yi(s.clip,t,e)){s.scrollView&&yi(s.rect,t,e)&&r.push({scrollView:s.scrollView,depth:o});for(let l of s.children)n(l,o+1);}};return n(i.root,0),r.sort((s,o)=>o.depth-s.depth),r.map(s=>s.scrollView)}function $l(){let i=process.env;return process.platform==="darwin"&&i.SSH_CONNECTION===void 0&&i.SSH_CLIENT===void 0&&i.SSH_TTY===void 0}var hr=class{constructor(t="auto",e=!$l()){d(this,"lines");d(this,"accelerate");d(this,"lastTime",Number.NEGATIVE_INFINITY);d(this,"lastDirection",0);d(this,"averageGap");d(this,"carry",0);this.lines=t,this.accelerate=e;}setLines(t){this.lines=t,this.reset();}next(t,e){if(this.lines!=="auto")return Number.isFinite(this.lines)?Math.max(1,Math.floor(this.lines)):1;if(!this.accelerate)return 1;let r=e-this.lastTime,n=t===this.lastDirection&&r<=200;if(this.lastTime=e,this.lastDirection=t,!n)return this.averageGap=void 0,this.carry=0,1;if(r<5)return 1;this.averageGap=this.averageGap===void 0?r:(this.averageGap+r)/2;let s=Math.min(6,Math.max(1,100/this.averageGap))+this.carry,o=Math.floor(s);return this.carry=s-o,o}reset(){this.lastTime=Number.NEGATIVE_INFINITY,this.lastDirection=0,this.averageGap=void 0,this.carry=0;}};var Kl="\x1B[?1049h",bs="\x1B[?1049l",ys="\x1B[?7l",xs="\x1B[?7h",Bl="\x1B[?1000h\x1B[?1002h\x1B[?1004h\x1B[?1006h",_l="\x1B[?1000h\x1B[?1002h\x1B[?1003h\x1B[?1004h\x1B[?1006h",Dl="\x1B[?1006l\x1B[?1004l\x1B[?1003l\x1B[?1002l\x1B[?1000l",Nl="\x1B[I",Fl="\x1B[O",dr="\x1B[?2026h",pr="\x1B[?2026l",vs=/^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/,Wl=/^\x1b\]133;A(?:\x07|\x1b\\)/,Ss=4,Vl=5,Hl=16,Ul=32*1024*1024,ql=64*1024*1024,Cs=500,Gl=5e3,zl=new Set(["/","-"]),Yl=Oe(),ws,Ts,vi=class extends(Ts=qe,ws=Gr,Ts){constructor(e,r,n,s={}){super(e,r,n);d(this,"mode","fullscreen");d(this,ws,true);d(this,"previousScreen",[]);d(this,"lastDocument",[]);d(this,"previousScreenWidth",0);d(this,"previousScreenHeight",0);d(this,"layoutRoot");d(this,"currentLayout");d(this,"implicitDocument");d(this,"implicitScrollView");d(this,"flashes");d(this,"altScreenActive",false);d(this,"imageProtocol",null);d(this,"savedCapabilities");d(this,"uploadedKittyImages",new Map);d(this,"selectionAnchor");d(this,"selectionFocus");d(this,"selectionGranularity","character");d(this,"selectionInitialRange");d(this,"lastClick");d(this,"selectionDragPointer");d(this,"selectionAutoScrollDirection",0);d(this,"selectionAutoScrollTimer");d(this,"selectionPressActive",false);d(this,"scrollbarDrag");d(this,"scrollbarHover");d(this,"scrollToEndIndicatorRect");d(this,"activeSearch");d(this,"pressedUrl");d(this,"selectionDragged",false);d(this,"mouseCapture");d(this,"mousePressTarget");d(this,"mousePressPoint");d(this,"mousePressMoved",false);d(this,"lastComponentClick");d(this,"wheelScroll");d(this,"mouseEnabled");d(this,"searchMatchStyle");d(this,"searchCurrentMatchStyle");d(this,"searchNavigationButtonStyle");d(this,"scrollToEndIndicator");d(this,"openUrl");d(this,"onRightClickPaste");d(this,"copyOnSelect");d(this,"copySelection");this.implicitDocument={render:o=>super.render(o),handleMouse:o=>super.handleMouse(o),invalidate:()=>{for(let o of this.children)o.invalidate();}},this.implicitScrollView=new ft(this.implicitDocument,{follow:"end",primary:true}),this.flashes=new ar(()=>this.requestRender()),this.wheelScroll=new hr(s.wheelScrollLines??1),this.mouseEnabled=s.mouse??true,this.searchMatchStyle=s.searchMatchStyle??(o=>`\x1B[4m${o}\x1B[24m`),this.searchCurrentMatchStyle=s.searchCurrentMatchStyle??(o=>`\x1B[1;7m${o}\x1B[22;27m`),this.searchNavigationButtonStyle=s.searchNavigationButtonStyle??(o=>o),this.scrollToEndIndicator=s.scrollToEndIndicator,this.openUrl=s.openUrl,this.onRightClickPaste=s.onRightClickPaste,this.copyOnSelect=s.copyOnSelect??true,this.copySelection=s.copySelection,this.addInputListener(o=>this.handleViewportInput(o));}get viewportTop(){return this.getPrimaryScrollView().scrollTop}get isFollowingOutput(){return this.getPrimaryScrollView().isFollowingEnd}setWheelScrollLines(e){this.wheelScroll.setLines(e);}getCopyOnSelect(){return this.copyOnSelect}setCopyOnSelect(e){this.copyOnSelect=e;}hasActiveSelection(){return this.getActiveSelectionText()!==void 0}async copyActiveSelectionToClipboard(){let e=this.getActiveSelectionText();return e?this.copyTextToClipboard(e):false}resetTextSelection(){this.clearTextSelection(),this.lastClick=void 0;}getScreenLines(){return [...this.previousScreen]}setLayoutRoot(e){this.layoutRoot!==e&&(this.layoutRoot=e,this.currentLayout=void 0,this.requestRender());}render(e){return this.layoutRoot?.render(e)??super.render(e)}getMountedRoots(){return this.layoutRoot?[this.layoutRoot]:this.children}getPrimaryScrollView(){return this.currentLayout?.primaryScrollView??this.implicitScrollView}beforeTerminalStart(){this.stopSelectionAutoScroll(),this.selectionPressActive=false,this.stopScrollbarHover(),this.stopScrollbarDrag(),this.flashes.dispose(),this.altScreenActive=true;let e=te();this.imageProtocol=e.images,this.uploadedKittyImages.clear(),e.images==="iterm2"&&(this.savedCapabilities=e,Nt({...e,images:null}),this.invalidate()),this.lastDocument=[],this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,this.lastClick=void 0,this.pressedUrl=void 0,this.selectionDragged=false,this.clearComponentMouseGesture(),this.lastComponentClick=void 0,this.resetRenderState();let r=process.env.TERM?.toLowerCase()??"",n=process.env.TMUX!==void 0||process.env.ZELLIJ!==void 0||process.env.STY!==void 0||r.startsWith("tmux")||r.startsWith("screen")?Bl:_l;this.terminal.write(`${Kl}${ys}${this.mouseEnabled?n:""}\x1B[2J\x1B[H\x1B[?25l`);}beforeTerminalStop(e){this.closeSearch(),this.stopSelectionAutoScroll(),this.selectionPressActive=false,this.stopScrollbarHover(),this.stopScrollbarDrag(),this.clearComponentMouseGesture(),this.flashes.dispose(),this.altScreenActive&&(this.terminal.write(`${dr}${this.deleteKittyImages()}${this.mouseEnabled?Dl:""}${xs}${pr}`),this.uploadedKittyImages.clear());}afterTerminalStop(e){if(this.altScreenActive){if(this.altScreenActive=false,e.preserveScreen)this.terminal.write(`${dr}${bs}\x1B[?25h${pr}`);else {let r=Math.max(1,this.terminal.columns),n=this.resolveFakeCursors(this.render(r)).map(o=>o.replace(vs,""));this.lastDocument=this.applyLineResets(n.map(o=>o.replaceAll(re,""))).map(o=>F(o)||S(o)<=r?o:V(o,0,r,true));let s=`${dr}${bs}${ys}`;for(let o=0;o<this.lastDocument.length;o++)o>0&&(s+=`\r
41
+ `),s+=`\r\x1B[2K${this.lastDocument[o]??""}`;s+=`\x1B[0m${xs}\r
42
+ \x1B[?25h${pr}`,this.terminal.write(s);}this.savedCapabilities&&(Nt(this.savedCapabilities),this.savedCapabilities=void 0);}}deleteKittyImages(){return this.imageProtocol==="kitty"?_r():""}prepareKittyScreen(e){let r=new Set,n=e.map(c=>{let h=Cn(c);if(!h)return c;r.add(h.imageId);let u=this.uploadedKittyImages.get(h.imageId),p={transmissionGeneration:h.transmissionGeneration,transmissionBytes:h.transmissionBytes,estimatedDecodedBytes:h.estimatedDecodedBytes};return u&&this.uploadedKittyImages.delete(h.imageId),this.uploadedKittyImages.set(h.imageId,p),u?.transmissionGeneration===h.transmissionGeneration?h.replacementLine:c}),s=0,o=0,l=0;for(let[c,h]of this.uploadedKittyImages)r.has(c)||(s+=1,o+=h.transmissionBytes,l+=h.estimatedDecodedBytes);let a="";for(let[c,h]of this.uploadedKittyImages){if(s<=Hl&&o<=Ul&&l<=ql)break;r.has(c)||(a+=at(c),this.uploadedKittyImages.delete(c),s-=1,o-=h.transmissionBytes,l-=h.estimatedDecodedBytes);}return {lines:n,evictedImageDeletion:a}}resetRenderState(){this.previousScreen=[],this.previousScreenWidth=0,this.previousScreenHeight=0,this.currentLayout=void 0;}scrollBy(e){this.getPrimaryScrollView().scrollBy(e),this.requestRender();}scrollToTop(){this.getPrimaryScrollView().scrollToStart(),this.requestRender();}scrollToBottom(){this.getPrimaryScrollView().scrollToEnd(),this.requestRender();}scrollToPrompt(e){if(!this.currentLayout)return;let r=this.getPrimaryScrollView(),n=ie(this.currentLayout,r)?.scrollContentLines;if(n){for(let s=r.scrollTop+e;s>=0&&s<n.length;s+=e)if(Wl.test(n[s]??"")){r.scrollTo(s),this.requestRender();return}}}toggleSearch(){if(this.activeSearch){this.closeSearch();return}let e=new or(n=>this.updateSearchQuery(n),this.searchNavigationButtonStyle),r={component:e,index:new sr,query:"",matches:[],selectedIndex:-1,anchorRow:this.getPrimaryScrollView().scrollTop,selectionMode:"query"};this.activeSearch=r,r.overlay=this.showOverlay(e,{anchor:"top-right",width:"40%",minWidth:32,margin:1});}closeSearch(){let e=this.activeSearch;e&&(this.activeSearch=void 0,e.overlay?.hide(),this.requestRender());}updateSearchQuery(e){let r=this.activeSearch;if(!r||e===r.query)return;let n=r.matches[r.selectedIndex];r.anchorRow=n?.segments[0]?.row??this.getPrimaryScrollView().scrollTop,r.query=e,r.selectionMode="query",r.component.setResult(-1,0),this.requestRender();}navigateSearch(e){let r=this.activeSearch;r?.query&&(r.selectionMode=e<0?"previous":"next",this.requestRender());}getSearchNavigationDirectionAt(e,r){let n=this.activeSearch,s=n?.overlay?.getBounds();if(!(!n||!s)&&!(e<s.col||e>=s.col+s.width||r<s.row||r>=s.row+s.height))return n.component.getNavigationDirectionAt(r-s.row,e-s.col)}handleSearchMouseEvent(e){let r=this.activeSearch;if(!r)return false;let n=this.getSearchNavigationDirectionAt(e.x,e.y);return r.component.setHoveredNavigationDirection(n)&&this.requestRender(),n===void 0||e.release||(e.button&32)!==0||(e.button&3)!==0?false:(this.navigateSearch(n),true)}refreshSearch(e){let r=this.activeSearch;if(!r)return false;let n=e.primaryScrollView??this.implicitScrollView,s=ie(e,n),o=s?.scrollContentLines;if(!o||!r.query.trim())return r.matches=[],r.selectedIndex=-1,r.selectedKey=void 0,r.selectionMode="retain",r.component.setResult(-1,0),false;let l=r.selectionMode!=="retain",a=r.index.search(o,r.query),c=a.matches;if(r.matches=c,!a.changed&&r.selectionMode==="retain")return false;let h=a.changed?r.selectedKey?c.findIndex(v=>bi(v)===r.selectedKey):-1:r.selectedIndex,u=-1;if(c.length>0)if(r.selectionMode==="query"){let v=0,x=c.length;for(;v<x;){let w=v+Math.floor((x-v)/2);(c[w].segments[0]?.row??0)<r.anchorRow?v=w+1:x=w;}u=v<c.length?v:0;}else if(r.selectionMode==="next"){let v=h>=0?h:Math.min(r.selectedIndex,c.length-1);u=v<0?0:(v+1)%c.length;}else if(r.selectionMode==="previous"){let v=h>=0?h:Math.min(r.selectedIndex,c.length-1);u=v<0?c.length-1:(v-1+c.length)%c.length;}else u=h>=0?h:Math.min(Math.max(0,r.selectedIndex),c.length-1);if(r.selectedIndex=u,r.selectedKey=u>=0?bi(c[u]):void 0,r.selectionMode="retain",r.component.setResult(u,c.length),!l)return false;let p=c[u],f=p?.segments[0],b=p?.segments[p.segments.length-1];if(!s||!f||!b||n.viewportHeight<=0)return false;let m=n.scrollTop,g=m+n.viewportHeight-1,y=m;return (f.row<m||b.row>g)&&(y=f.row-Math.floor(n.viewportHeight/3)),n.scrollTo(y,{disableFollow:true}),n.scrollTop!==m}flash(e,r){this.flashes.flash(e,r);}shouldDeferViewportInputToOverlay(){return this.isOverlayFocused()&&this.activeSearch?.overlay?.isFocused()!==true}clearComponentMouseGesture(){this.mouseCapture=void 0,this.mousePressTarget=void 0,this.mousePressPoint=void 0,this.mousePressMoved=false;}handleViewportInput(e){if(e===Fl){let l=this.selectionPressActive,a=l&&this.getSelectionBounds()!==void 0;return this.selectionPressActive=false,this.stopSelectionAutoScroll(),this.stopScrollbarHover(),this.activeSearch?.component.setHoveredNavigationDirection(void 0)&&this.requestRender(),this.stopScrollbarDrag(),this.pressedUrl=void 0,this.selectionDragged=false,this.clearComponentMouseGesture(),this.lastComponentClick=void 0,l&&(this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,a&&this.requestRender()),this.lastClick=void 0,{consume:true}}if(e===Nl)return {consume:true};let r=this.parseWheelEvent(e);if(r){let l=this.wheelScroll.next(r.direction,performance.now()),a=r.direction*((r.button&8)!==0?l*Vl:l),c=this.createMouseEvent("wheel",r.button,r.x,r.y,{wheelDelta:a}),h=this.dispatchMouseToOverlay(c),u=h.result??(h.hit?void 0:this.dispatchMouseToLayout(c));return u?(this.applyMouseDispatchResult(c,u)&&this.requestRender(),{consume:true}):(this.routeWheel(r,a),{consume:true})}let n=this.parseSgrMouseEvent(e);if(n)return this.handleMouseEvent(n),{consume:true};if(this.isMouseSequence(e))return {consume:true};let s=G(),o=ot(e);if(s.matches(e,"tui.altScreen.search"))return o||this.toggleSearch(),{consume:true};if(this.activeSearch?.overlay?.isFocused()){if(s.matches(e,"tui.altScreen.searchNext"))return o||this.navigateSearch(1),{consume:true};if(s.matches(e,"tui.altScreen.searchPrevious"))return o||this.navigateSearch(-1),{consume:true};if(s.matches(e,"tui.altScreen.searchClose"))return o||this.closeSearch(),{consume:true}}if(!this.shouldDeferViewportInputToOverlay()){if(s.matches(e,"tui.altScreen.pageUp"))return o||this.scrollBy(-Math.max(1,this.getPrimaryScrollView().viewportHeight-Ss)),{consume:true};if(s.matches(e,"tui.altScreen.pageDown"))return o||this.scrollBy(Math.max(1,this.getPrimaryScrollView().viewportHeight-Ss)),{consume:true};if(s.matches(e,"tui.altScreen.halfPageUp"))return o||this.scrollBy(-Math.max(1,Math.floor(this.getPrimaryScrollView().viewportHeight/2))),{consume:true};if(s.matches(e,"tui.altScreen.halfPageDown"))return o||this.scrollBy(Math.max(1,Math.floor(this.getPrimaryScrollView().viewportHeight/2))),{consume:true};if(s.matches(e,"tui.altScreen.lineUp"))return o||this.scrollBy(-1),{consume:true};if(s.matches(e,"tui.altScreen.lineDown"))return o||this.scrollBy(1),{consume:true};if(s.matches(e,"tui.altScreen.previousPrompt"))return o||this.scrollToPrompt(-1),{consume:true};if(s.matches(e,"tui.altScreen.nextPrompt"))return o||this.scrollToPrompt(1),{consume:true};if(s.matches(e,"tui.altScreen.top"))return o||this.scrollToTop(),{consume:true};if(s.matches(e,"tui.altScreen.bottom"))return o||this.scrollToBottom(),{consume:true}}}decodeMouseButton(e){switch(e&3){case 0:return "left";case 1:return "middle";case 2:return "right";default:return "none"}}createMouseEvent(e,r,n,s,o={}){return {type:e,button:e==="wheel"?"none":this.decodeMouseButton(r),x:n,y:s,screenX:n,screenY:s,width:Math.max(1,this.terminal.columns),height:Math.max(1,this.terminal.rows),shift:(r&4)!==0,alt:(r&8)!==0,ctrl:(r&16)!==0,...o.wheelDelta===void 0?{}:{wheelDelta:o.wheelDelta},...o.clickCount===void 0?{}:{clickCount:o.clickCount}}}dispatchMouseToLayout(e){if(!this.currentLayout)return;let r=new Set,n=gs(this.currentLayout,e.screenX,e.screenY);for(let s of n){if(r.has(s.component)||Jt(s.component)&&s.component.handleMouse===se.prototype.handleMouse)continue;r.add(s.component);let o=ue(s.component,{...e,x:e.screenX-s.rect.x,y:e.screenY-s.rect.y,width:s.rect.width,height:s.rect.height});if(o)return o}}applyMouseDispatchResult(e,r){let n=this.resolveMouseFocusTarget(r.focusTarget??r.target.component),s=r.focus===true&&this.getFocusedComponent()!==n;return r.focus&&this.setFocus(n),r.capture&&(this.mouseCapture=r.target),r.render??(s||e.type==="press"||e.type==="click"||e.type==="drag"||e.type==="wheel")}dispatchMouseToTarget(e,r){return ue(r.component,kn(e,r))}getComponentClickCount(e,r,n){let s=Date.now(),o=this.lastComponentClick,l=o&&s-o.timestamp<=Cs&&o.component===e.component&&o.x===r&&o.y===n?o.count%3+1:1;return this.lastComponentClick={timestamp:s,count:l,component:e.component,x:r,y:n},l}clearTextSelection(){this.stopSelectionAutoScroll(),this.selectionPressActive=false,this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,this.pressedUrl=void 0,this.selectionDragged=false;}handleMouseEvent(e){let r=(e.button&32)!==0,n=e.release?"release":r?this.decodeMouseButton(e.button)==="none"?"move":"drag":"press",s=this.createMouseEvent(n,e.button,e.x,e.y);if(this.mouseCapture||this.mousePressTarget){let a=this.mouseCapture??this.mousePressTarget;this.mousePressPoint&&(e.x!==this.mousePressPoint.x||e.y!==this.mousePressPoint.y)&&(this.mousePressMoved=true,this.lastComponentClick=void 0);let c=false,h=this.dispatchMouseToTarget(s,a);if(h&&(c=this.applyMouseDispatchResult(s,h)),e.release){if(!this.mousePressMoved&&this.mousePressPoint?.x===e.x&&this.mousePressPoint.y===e.y){let u=this.createMouseEvent("click",e.button,e.x,e.y,{clickCount:this.getComponentClickCount(a,e.x,e.y)}),p=this.dispatchMouseToTarget(u,a);p&&(c=this.applyMouseDispatchResult(u,p)||c);}this.clearComponentMouseGesture();}c&&this.requestRender();return}if(this.handleSearchMouseEvent(e))return;let o=this.dispatchMouseToOverlay(s);if(o.hit)this.stopScrollbarHover();else {if(this.handleScrollToEndIndicatorMouseEvent(e))return;let a=this.handleScrollbarMouseEvent(e);if(this.scrollbarDrag||this.updateScrollbarHover(e.x,e.y),a)return}let l=o.result??(o.hit?void 0:this.dispatchMouseToLayout(s));if(l){let a=this.applyMouseDispatchResult(s,l);n==="press"&&(this.clearTextSelection(),this.mousePressTarget=l.target,this.mousePressPoint={x:e.x,y:e.y},this.mousePressMoved=false),a&&this.requestRender();return}this.handleRightClickPaste(e)||this.handleSelectionMouseEvent(e);}parseWheelEvent(e){let r=/^\x1b\[<(\d+);(\d+);(\d+)[Mm]$/.exec(e);if(r){let n=Number.parseInt(r[1],10);if((n&64)===0)return;let s=n&3;return s!==0&&s!==1?void 0:{direction:s===0?-1:1,x:Number.parseInt(r[2],10)-1,y:Number.parseInt(r[3],10)-1,button:n}}if(e.length===6&&e.startsWith("\x1B[M")){let n=e.charCodeAt(3)-32;if((n&64)===0)return;let s=n&3;return s!==0&&s!==1?void 0:{direction:s===0?-1:1,x:e.charCodeAt(4)-33,y:e.charCodeAt(5)-33,button:n}}}routeWheel(e,r){let n=r,s=new Set;for(let l of this.currentLayout?ur(this.currentLayout,e.x,e.y):[])if(s.add(l),n=l.scrollBy(n),n===0||l.overscroll==="contain")break;let o=this.getPrimaryScrollView();n!==0&&!s.has(o)&&o.scrollBy(n),this.updateScrollbarHover(e.x,e.y),this.requestRender();}parseSgrMouseEvent(e){let r=/^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/.exec(e);if(r)return {button:Number.parseInt(r[1],10),x:Number.parseInt(r[2],10)-1,y:Number.parseInt(r[3],10)-1,release:r[4]==="m"}}handleRightClickPaste(e){if(!this.onRightClickPaste||process.platform!=="win32"||process.env.TERM_PROGRAM?.toLowerCase()==="vscode"||e.release||e.button!==2)return false;try{this.onRightClickPaste();}catch{}return true}handleScrollToEndIndicatorMouseEvent(e){let r=this.scrollToEndIndicatorRect;return !r||e.release||(e.button&32)!==0||(e.button&3)!==0||e.y!==r.row||e.x<r.column||e.x>=r.column+r.width?false:(this.scrollToBottom(),true)}getScrollbarTargetAt(e,r,n=false){if(!(this.hasOverlay()||!this.currentLayout))for(let s of ur(this.currentLayout,e,r)){let o=ie(this.currentLayout,s),l=o?Ze(o,n):void 0;if(l&&e===l.column&&r>=l.trackTop&&r<l.trackTop+l.trackHeight)return {scrollView:s,geometry:l}}}setScrollbarHover(e){e!==this.scrollbarHover&&(this.scrollbarHover?.setScrollbarActive(false),this.scrollbarHover=e,this.scrollbarHover?.setScrollbarActive(true));}updateScrollbarHover(e,r){this.setScrollbarHover(this.getScrollbarTargetAt(e,r,true)?.scrollView);}stopScrollbarHover(){this.setScrollbarHover(void 0);}scrollScrollbarToPointer(e,r,n,s){let o=r.trackHeight-r.thumbHeight,l=Math.max(0,Math.min(o,n-r.trackTop-s)),a=o===0?0:Math.round(l/o*r.maxScrollTop);e.scrollTo(a);}handleScrollbarMouseEvent(e){if(this.scrollbarDrag){if(e.release)return this.stopScrollbarDrag(),true;let o=this.currentLayout?ie(this.currentLayout,this.scrollbarDrag.scrollView):void 0,l=o?Ze(o):void 0;return l&&this.scrollScrollbarToPointer(this.scrollbarDrag.scrollView,l,e.y,this.scrollbarDrag.grabOffset),true}if(e.release||(e.button&32)!==0||(e.button&3)!==0)return false;let r=this.getScrollbarTargetAt(e.x,e.y);if(!r)return false;this.stopSelectionAutoScroll(),this.selectionPressActive=false,this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,this.lastClick=void 0,this.pressedUrl=void 0,this.selectionDragged=false,this.setScrollbarHover(r.scrollView);let n=e.y>=r.geometry.thumbTop&&e.y<r.geometry.thumbTop+r.geometry.thumbHeight,s=n?e.y-r.geometry.thumbTop:Math.floor(r.geometry.thumbHeight/2);return n||this.scrollScrollbarToPointer(r.scrollView,r.geometry,e.y,s),this.scrollbarDrag={scrollView:r.scrollView,grabOffset:s},true}stopScrollbarDrag(){this.scrollbarDrag=void 0;}getScrollSelectionPoint(e,r,n){if(!this.currentLayout)return;let s=ie(this.currentLayout,e);if(!s||s.rect.height<=0||s.clip.height<=0)return;let o=Math.max(0,s.rect.y,s.clip.y),l=Math.min(this.terminal.rows-1,s.rect.y+s.rect.height-1,s.clip.y+s.clip.height-1);if(l<o)return;let a=Math.max(o,Math.min(l,n)),c=Math.max(0,(s.scrollContentLines?.length??1)-1);return {row:Math.max(0,Math.min(c,e.scrollTop+a-s.rect.y)),col:Math.max(0,Math.min(s.rect.width-1,r-s.rect.x)),scrollView:e}}getSelectionPoint(e,r){if(r){let n=this.getScrollSelectionPoint(r,e.x,e.y);if(n)return n}return {row:Math.max(0,Math.min(this.terminal.rows-1,e.y)),col:Math.max(0,Math.min(this.terminal.columns-1,e.x))}}getSelectionSourceLine(e){if(e.scrollView&&this.currentLayout){let r=ie(this.currentLayout,e.scrollView)?.scrollContentLines;if(r)return r[e.row]??""}return this.previousScreen[e.row]??""}getWordSelection(e){let r=Be(this.getSelectionSourceLine(e)),n=[],s=0;for(let u of Yl.segment(r)){let p=s+S(u.segment),f=zl.has(u.segment);n.push({start:s,end:p,selectable:u.isWordLike===true||f,joiner:f}),s=p;}let o=n.findIndex(u=>e.col>=u.start&&e.col<u.end);if(o<0)return;let l=(u,p)=>u.selectable&&p.selectable&&(u.joiner||p.joiner),a=n[o],c=a.start,h=a.end;for(let u=o;u>0&&l(n[u-1],n[u]);u--)c=n[u-1].start;for(let u=o;u<n.length-1&&l(n[u],n[u+1]);u++)h=n[u+1].end;return {start:{...e,col:c},end:{...e,col:h,boundary:true}}}getLineSelection(e){return {start:{...e,col:0},end:{...e,col:S(this.getSelectionSourceLine(e)),boundary:true}}}updateSelectionFocus(e){if(this.selectionGranularity==="character"||!this.selectionInitialRange){this.selectionFocus=e;return}let r=this.selectionGranularity==="word"?this.getWordSelection(e):this.getLineSelection(e);if(!r)return;let n=this.selectionInitialRange;r.start.row<n.start.row||r.start.row===n.start.row&&r.start.col<n.start.col?(this.selectionAnchor=n.end,this.selectionFocus=r.start):(this.selectionAnchor=n.start,this.selectionFocus=r.end);}getClickCount(e,r){let n=Date.now(),s=this.lastClick,o=r&&s&&n-s.timestamp<=Cs&&s.row===e.row&&s.scrollView===e.scrollView&&s.wordStart===r.start.col&&s.wordEnd===r.end.col?s.count%3+1:1;return this.lastClick=r?{timestamp:n,count:o,row:e.row,scrollView:e.scrollView,wordStart:r.start.col,wordEnd:r.end.col}:void 0,o}updateSelectionAutoScroll(e){let r=this.selectionAnchor?.scrollView;if(!r||!this.currentLayout){this.stopSelectionAutoScroll();return}let n=ie(this.currentLayout,r);if(!n||n.rect.height<=0||n.clip.height<=0){this.stopSelectionAutoScroll();return}let s=Math.max(0,n.rect.y,n.clip.y),o=Math.min(this.terminal.rows-1,n.rect.y+n.rect.height-1,n.clip.y+n.clip.height-1);if(this.selectionDragPointer={x:e.x,y:e.y},this.selectionAutoScrollDirection=e.y<=s?-1:e.y>=o?1:0,this.selectionAutoScrollDirection===0){this.stopSelectionAutoScroll();return}this.selectionAutoScrollTimer||(this.selectionAutoScrollTimer=setInterval(()=>this.autoScrollSelection(),50),this.selectionAutoScrollTimer.unref());}autoScrollSelection(){let e=this.selectionAnchor?.scrollView,r=this.selectionDragPointer,n=this.selectionAutoScrollDirection;if(!e||!r||n===0){this.stopSelectionAutoScroll();return}if(e.scrollBy(n)===n){this.stopSelectionAutoScroll();return}let o=this.getScrollSelectionPoint(e,r.x,r.y);o&&this.updateSelectionFocus(o),this.requestRender();}stopSelectionAutoScroll(){this.selectionAutoScrollTimer&&(clearInterval(this.selectionAutoScrollTimer),this.selectionAutoScrollTimer=void 0),this.selectionAutoScrollDirection=0,this.selectionDragPointer=void 0;}handleSelectionMouseEvent(e){let r=e.button&3;if(r!==0&&!(e.release&&r===3))return;let n=this.selectionAnchor?.scrollView,s=this.getSelectionPoint(e,n);if(e.release){if(!this.selectionPressActive||(this.selectionPressActive=false,this.stopSelectionAutoScroll(),!this.selectionAnchor))return;this.updateSelectionFocus(s);let u=!this.selectionDragged&&this.selectionAnchor.scrollView===s.scrollView&&this.selectionAnchor.row===s.row&&this.selectionAnchor.col===s.col,p=u?this.pressedUrl:void 0;if(this.pressedUrl=void 0,p&&this.openUrl){this.selectionAnchor=void 0,this.selectionFocus=void 0;try{this.openUrl(p);}catch{}this.requestRender();return}if(u){let f=this.createMouseEvent("click",e.button,e.x,e.y,{clickCount:this.lastClick?.count??1}),b=this.dispatchMouseToOverlay(f),m=b.result??(b.hit?void 0:this.dispatchMouseToLayout(f));if(m){let g=this.applyMouseDispatchResult(f,m);this.clearTextSelection(),g&&this.requestRender();return}}this.copyOnSelect&&this.copySelectionToClipboard(),this.requestRender();return}if((e.button&32)!==0){if(!this.selectionPressActive||!this.selectionAnchor)return;this.selectionDragged=true,this.lastClick=void 0,this.pressedUrl=void 0,this.updateSelectionFocus(s),this.updateSelectionAutoScroll(e),this.requestRender();return}this.stopSelectionAutoScroll(),this.selectionPressActive=true;let o=!this.hasOverlay()&&this.currentLayout?ur(this.currentLayout,e.x,e.y)[0]:void 0,l=this.getSelectionPoint(e,o),a=this.getWordSelection(l),c=this.getClickCount(l,a),h=c===2?a:c===3?this.getLineSelection(l):void 0;this.selectionGranularity=h?c===2?"word":"line":"character",this.selectionInitialRange=h,this.selectionAnchor=h?.start??l,this.selectionFocus=h?.end??l,this.selectionDragged=false,this.pressedUrl=h?void 0:br(this.previousScreen[Math.max(0,Math.min(this.terminal.rows-1,e.y))]??"",Math.max(0,Math.min(this.terminal.columns-1,e.x))),this.requestRender();}getSelectionBounds(){if(!this.selectionAnchor||!this.selectionFocus||this.selectionAnchor.scrollView!==this.selectionFocus.scrollView)return;let e=this.selectionAnchor.row<this.selectionFocus.row||this.selectionAnchor.row===this.selectionFocus.row&&this.selectionAnchor.col<this.selectionFocus.col;if(!(this.selectionAnchor.row===this.selectionFocus.row&&this.selectionAnchor.col===this.selectionFocus.col))return e?{start:this.selectionAnchor,end:this.selectionFocus}:{start:this.selectionFocus,end:this.selectionAnchor}}getSelectionColumns(e,r,n,s=0,o=S(e)){let l=S(e),a=Math.max(0,s),c=Math.min(l,o);return r===n.start.row&&(a=tt(e,n.start.col)?.start??Math.min(n.start.col,l)),r===n.end.row&&(c=n.end.boundary?Math.min(n.end.col,l):tt(e,n.end.col)?.end??Math.min(n.end.col+1,l)),{start:Math.max(s,a),end:Math.min(o,c)}}getActiveSelectionText(){let e=this.getSelectionBounds();if(!e)return;let r=this.previousScreen;if(e.start.scrollView){if(!this.currentLayout)return;let o=ie(this.currentLayout,e.start.scrollView);if(!o?.scrollContentLines)return;r=o.scrollContentLines;}let n=[];for(let o=e.start.row;o<=e.end.row;o++){let l=r[o]??"",a=this.getSelectionColumns(l,o,e);n.push(Be(V(l,a.start,Math.max(0,a.end-a.start),true)).trimEnd());}let s=n.join(`
43
+ `);return s.length===0?void 0:s}async copySelectionToClipboard(){let e=this.getActiveSelectionText();return e?this.copyTextToClipboard(e):false}async copyTextToClipboard(e){if(this.copySelection){let r=await this.copySelection(e),n=r===true;return this.flash(n?"Copied!":typeof r=="string"?r:"Copy failed",n?void 0:Gl),n}return this.terminal.write(`\x1B]52;c;${Buffer.from(e).toString("base64")}\x07`),this.flash("Copied!"),true}applySearchTextHighlight(e,r){let n=r?this.searchCurrentMatchStyle:this.searchMatchStyle,s="",o=0,l=0;for(;l<e.length;){let a=W(e,l);if(!a){l+=1;continue}l>o&&(s+=n(e.slice(o,l))),s+=a.code,l+=a.length,o=l;}return o<e.length&&(s+=n(e.slice(o))),s}applySearchHighlights(e,r){let n=this.activeSearch;if(!n||n.selectedIndex<0||n.matches.length===0)return e;let s=r.primaryScrollView??this.implicitScrollView,o=ie(r,s);if(!o)return e;let l=new Map,a=Ze(o)?.column,c=Math.max(0,o.rect.y,o.clip.y),h=Math.min(e.length,o.rect.y+o.rect.height,o.clip.y+o.clip.height),u=Math.max(0,o.rect.x,o.clip.x),p=Math.min(this.terminal.columns,o.rect.x+o.rect.width,o.clip.x+o.clip.width,a??Number.POSITIVE_INFINITY),f=s.scrollTop+c-o.rect.y,b=s.scrollTop+h-o.rect.y-1,m=0,g=n.matches.length;for(;m<g;){let v=m+Math.floor((g-m)/2),x=n.matches[v];(x.segments[x.segments.length-1]?.row??-1)<f?m=v+1:g=v;}for(let v=m;v<n.matches.length;v++){let x=n.matches[v];if((x.segments[0]?.row??0)>b)break;for(let w of x.segments){let I=o.rect.y+w.row-s.scrollTop;if(I<c||I>=h)continue;let T=Math.max(u,o.rect.x+w.startCol),L=Math.min(p,o.rect.x+w.endCol);if(L<=T)continue;let M=l.get(I)??[];M.push({startCol:T,endCol:L,current:v===n.selectedIndex}),l.set(I,M);}}let y=[...e];for(let[v,x]of l){let w=y[v]??"";if(F(w))continue;let I=S(w);for(let T of x.sort((L,M)=>M.startCol-L.startCol)){let L=Math.min(T.startCol,I),M=Math.min(T.endCol,I);if(M<=L)continue;let E=V(w,0,L,true),P=V(w,L,M-L,true),C=V(w,M,Math.max(0,I-M),true);w=`${E}${this.applySearchTextHighlight(P,T.current)}${C}`;}y[v]=w;}return y}applySelectionHighlight(e){let r="\x1B[7m",n=0;for(;n<e.length;){let s=W(e,n);if(!s){r+=e[n],n+=1;continue}r+=s.code,s.code.endsWith("m")&&(r+="\x1B[7m"),n+=s.length;}return `${r}\x1B[27m`}applySelection(e,r=this.currentLayout){let n=this.getSelectionBounds();if(!n)return e;let s=n,o=0,l=e.length-1,a=0,c=this.terminal.columns;if(n.start.scrollView){if(!r)return e;let h=ie(r,n.start.scrollView);if(!h)return e;o=Math.max(0,h.rect.y,h.clip.y),l=Math.min(e.length-1,h.rect.y+h.rect.height-1,h.clip.y+h.clip.height-1),a=Math.max(0,h.rect.x,h.clip.x),c=Math.min(this.terminal.columns,h.rect.x+h.rect.width,h.clip.x+h.clip.width),s={start:{...n.start,row:h.rect.y+n.start.row-n.start.scrollView.scrollTop,col:h.rect.x+n.start.col},end:{...n.end,row:h.rect.y+n.end.row-n.start.scrollView.scrollTop,col:h.rect.x+n.end.col}};}return e.map((h,u)=>{if(u<o||u>l||u<s.start.row||u>s.end.row||F(h))return h;let p=S(h),f=this.getSelectionColumns(h,u,s,a,c);if(f.end<=f.start)return h;let b=V(h,0,f.start,true),m=V(h,f.start,f.end-f.start,true),g=V(h,f.end,Math.max(0,p-f.end),true);return `${b}${this.applySelectionHighlight(m)}${g}`})}isMouseSequence(e){return /^\x1b\[<\d+;\d+;\d+[Mm]$/.test(e)||e.length===6&&e.startsWith("\x1B[M")}compositeScrollToEndIndicator(e,r,n){this.scrollToEndIndicatorRect=void 0;let s=r.primaryScrollView??this.implicitScrollView;if(!this.scrollToEndIndicator||!s.followEnd||s.isFollowingEnd)return e;let o=ie(r,s),l=o?.clip;if(!l||l.width<=0||l.height<=0)return e;let a=l.y+l.height-1;if(a>=e.length||F(e[a]??""))return e;let c=o?Ze(o)?.column:void 0,h=N(this.scrollToEndIndicator(),l.width,""),u=S(h),p=l.x+Math.floor((l.width-u)/2),f=c??l.x+l.width,b=Math.max(0,f-p),m=N(h,b,""),g=S(m);if(g===0)return e;let y=[...e];return y[a]=he(y[a]??"",m,p,g,n),this.scrollToEndIndicatorRect={row:a,column:p,width:g},y}compositeFlashes(e,r,n){let s=this.flashes.render(r).slice(-n);if(s.length===0)return e;let o=[...e];for(;o.length<n;)o.push("");for(let l=0;l<s.length;l++){let a=s[l],c=S(a);c!==0&&(o[l]=he(o[l]??"",a,r-c,c,r));}return o}doRender(){if(this.stopped||!this.altScreenActive)return;let e=Math.max(1,this.terminal.columns),r=Math.max(1,this.terminal.rows),n=this.layoutRoot??this.implicitScrollView,s=xi(n,e,r,()=>this.requestRender());this.refreshSearch(s)&&(s=xi(n,e,r,()=>this.requestRender()));let o=this.resolveFakeCursors(s.lines.map(x=>x.replace(vs,"")));o=this.applySearchHighlights(o,s),o=this.compositeScrollToEndIndicator(o,s,e),o=this.compositeOverlays(o,e,r),o.length>r&&(o=o.slice(o.length-r)),o=this.applySelection(o,s),o=this.compositeFlashes(o,e,r);let l=this.extractCursorPosition(o,r);o=this.applyLineResets(o).map(x=>F(x)||S(x)<=e?x:V(x,0,e,true));let a=this.previousScreen.length===0||this.previousScreenWidth!==e||this.previousScreenHeight!==r,c=o.map((x,w)=>x!==this.previousScreen[w]),h=o.some((x,w)=>c[w]&&(F(x)||F(this.previousScreen[w]??""))),u=!!process.env.WEZTERM_PANE||process.env.TERM_PROGRAM?.toLowerCase()==="wezterm",p=!h&&u&&this.imageProtocol==="kitty"&&c.some(Boolean)&&o.some((x,w)=>{let I=Sn(x);if(I===void 0)return false;for(let T=w;T<w+I;T++)if(c[T])return true;return false}),f=h||p,b=a||f,m=this.uploadedKittyImages.size>0,g=b&&this.imageProtocol==="kitty"?this.prepareKittyScreen(o):{lines:o,evictedImageDeletion:""},y=dr;if(a){this.fullRedrawCount+=1;let x=this.imageProtocol==="kitty"&&m?Dr():this.deleteKittyImages();y+=`${x}\x1B[2J`;}else f&&(this.imageProtocol==="iterm2"?y+="\x1B[2J":this.imageProtocol==="kitty"&&(y+=Dr()));if(y+=g.evictedImageDeletion,b&&this.imageProtocol==="kitty"&&o.some(F)&&u){for(let x=0;x<r;x++)!a&&!f&&o[x]===this.previousScreen[x]||(y+=`\x1B[${x+1};1H\x1B[2K`);for(let x=0;x<r;x++)!a&&!f&&o[x]===this.previousScreen[x]||F(g.lines[x]??"")||(y+=`\x1B[${x+1};1H${g.lines[x]??""}`);for(let x=0;x<r;x++)!a&&!f&&o[x]===this.previousScreen[x]||F(g.lines[x]??"")&&(y+=`\x1B[${x+1};1H${g.lines[x]??""}`);}else for(let x=0;x<r;x++)!a&&!f&&o[x]===this.previousScreen[x]||(y+=`\x1B[${x+1};1H\x1B[2K${g.lines[x]??""}`);l?(y+=`\x1B[${l.row+1};${Math.min(e,l.col)+1}H`,y+=this.getShowHardwareCursor()?"\x1B[?25h":"\x1B[?25l"):y+="\x1B[?25l",y+=pr,this.terminal.write(y),this.previousScreen=o,this.previousScreenWidth=e,this.previousScreenHeight=r,this.currentLayout=s;}};var Ms="\x1B_G",Is=1024*1024,vt=class{constructor(t){d(this,"buffer","");d(this,"writtenChars",0);d(this,"write");this.write=t;}append(t){let e=0;for(;e<t.length;){let r=Is-this.buffer.length;if(r===0){this.flush();continue}let n=Math.min(t.length,e+r);if(n<t.length&&t.charCodeAt(n-1)>=55296&&t.charCodeAt(n-1)<=56319&&t.charCodeAt(n)>=56320&&t.charCodeAt(n)<=57343&&n--,n===e){this.flush();continue}this.buffer+=t.slice(e,n),e=n,this.buffer.length===Is&&this.flush();}}flush(){this.buffer&&(this.write(this.buffer),this.writtenChars+=this.buffer.length,this.buffer="");}get length(){return this.writtenChars+this.buffer.length}};function ks(i){let t=i.indexOf(Ms);if(t===-1)return;let e=t+Ms.length,r=i.indexOf(";",e);if(r===-1)return;let n=[],s=1;for(let o of i.slice(e,r).split(",")){let[l,a]=o.split("=",2);if(a===void 0)continue;let c=Number(a);!Number.isInteger(c)||c<=0||c>4294967295||(l==="i"?n.push(c):l==="r"&&(s=c));}return {ids:n,rows:s}}function Si(i){return ks(i)?.ids??[]}function jl(i){return ks(i)?.rows??1}function Xl(){return !!process.env.TERMUX_VERSION}var Ci=class extends qe{constructor(){super(...arguments);d(this,"mode","regular");d(this,"previousLines",[]);d(this,"previousKittyImageIds",new Set);d(this,"previousWidth",0);d(this,"previousHeight",0);d(this,"cursorRow",0);d(this,"hardwareCursorRow",0);d(this,"maxLinesRendered",0);d(this,"previousViewportTop",0);}captureRenderState(){return {previousLines:[...this.previousLines],previousWidth:this.previousWidth,previousHeight:this.previousHeight,cursorRow:this.cursorRow,hardwareCursorRow:this.hardwareCursorRow,maxLinesRendered:this.maxLinesRendered,previousViewportTop:this.previousViewportTop}}restoreRenderState(e){this.previousLines=e.previousLines.map(r=>F(r)?"":r),this.previousKittyImageIds=new Set,this.previousWidth=e.previousWidth,this.previousHeight=e.previousHeight,this.cursorRow=e.cursorRow,this.hardwareCursorRow=e.hardwareCursorRow,this.maxLinesRendered=e.maxLinesRendered,this.previousViewportTop=e.previousViewportTop;}resetRenderState(){this.previousLines=[],this.previousWidth=-1,this.previousHeight=-1,this.cursorRow=0,this.hardwareCursorRow=0,this.maxLinesRendered=0,this.previousViewportTop=0;}beforeTerminalStop(e){if(e.preserveScreen||this.previousLines.length===0)return;this.terminal.write(" ");let n=this.previousLines.length-this.hardwareCursorRow;n>0?this.terminal.write(`\x1B[${n}B`):n<0&&this.terminal.write(`\x1B[${-n}A`),this.terminal.write(`\r
44
+ `);}collectKittyImageIds(e){let r=new Set;for(let n of e)for(let s of Si(n))r.add(s);return r}deleteKittyImages(e){let r="";for(let n of e)r+=at(n);return r}getKittyImageReservedRows(e,r,n=e.length-1){let s=jl(e[r]??"");if(s<=1)return 1;let o=Math.min(s,n-r+1,e.length-r),l=1;for(;l<o;){let a=e[r+l]??"";if(F(a)||S(a)>0)break;l++;}return l}expandChangedRangeForKittyImages(e,r,n){let s=e,o=r,l=a=>{for(let c=0;c<a.length;c++){if(Si(a[c]??"").length===0)continue;let h=c+this.getKittyImageReservedRows(a,c)-1;(c>=e||c<=r&&h>=e)&&(s=Math.min(s,c),o=Math.max(o,h));}};return l(this.previousLines),l(n),{firstChanged:s,lastChanged:o}}deleteChangedKittyImages(e,r){if(e<0||r<e)return "";let n=new Set,s=Math.min(r,this.previousLines.length-1);for(let o=e;o<=s;o++)for(let l of Si(this.previousLines[o]??""))n.add(l);return this.deleteKittyImages(n)}doRender(){if(this.stopped)return;let e=this.terminal.columns,r=this.terminal.rows,n=this.previousWidth!==0&&this.previousWidth!==e,s=this.previousHeight!==0&&this.previousHeight!==r,o=this.previousHeight>0?this.previousViewportTop+this.previousHeight:r,l=s?Math.max(0,o-r):this.previousViewportTop,a=l,c=this.hardwareCursorRow,h=C=>{let A=c-l;return C-a-A},u=this.resolveFakeCursors(this.render(e));this.hasOverlayEntries&&(u=this.compositeOverlays(u,e,r));let p=this.extractCursorPosition(u,r);u=this.applyLineResets(u);let f=C=>{this.fullRedrawCount+=1;let A=new vt(B=>this.terminal.write(B));A.append("\x1B[?2026h"),C&&(A.append(this.deleteKittyImages(this.previousKittyImageIds)),A.append("\x1B[2J\x1B[H\x1B[3J"));for(let B=0;B<u.length;B++){B>0&&A.append(`\r
45
+ `);let U=u[B]??"",Y=F(U)?this.getKittyImageReservedRows(u,B):1;if(Y>1&&Y<=r){for(let et=1;et<Y;et++)A.append(`\r
46
+ `);A.append(`\x1B[${Y-1}A`),A.append(U),A.append(`\x1B[${Y-1}B`),B+=Y-1;continue}A.append(U);}A.append("\x1B[?2026l"),A.flush(),this.cursorRow=Math.max(0,u.length-1),this.hardwareCursorRow=this.cursorRow,C?this.maxLinesRendered=u.length:this.maxLinesRendered=Math.max(this.maxLinesRendered,u.length);let D=Math.max(r,u.length);this.previousViewportTop=Math.max(0,D-r),this.positionHardwareCursor(p,u.length),this.previousLines=u,this.previousKittyImageIds=this.collectKittyImageIds(u),this.previousWidth=e,this.previousHeight=r;},b=process.env.PI_TUI_DEBUG_REDRAW==="1"?this.logDirectory:void 0,m=C=>{if(b===void 0)return;let A=Ae.join(b,"pi-tui-debug.log"),D=`[${new Date().toISOString()}] fullRender: ${C} (prev=${this.previousLines.length}, new=${u.length}, height=${r})
47
+ `;pe.mkdirSync(Ae.dirname(A),{recursive:true}),pe.appendFileSync(A,D);};if(this.previousLines.length===0&&!n&&!s){m("first render"),f(false);return}if(n){m(`terminal width changed (${this.previousWidth} -> ${e})`),f(true);return}if(s&&!Xl()){m(`terminal height changed (${this.previousHeight} -> ${r})`),f(true);return}if(this.getClearOnShrink()&&u.length<this.maxLinesRendered&&!this.hasOverlayEntries){m(`clearOnShrink (maxLinesRendered=${this.maxLinesRendered})`),f(true);return}let g=-1,y=-1,v=Math.max(u.length,this.previousLines.length);for(let C=0;C<v;C++){let A=C<this.previousLines.length?this.previousLines[C]:"",D=C<u.length?u[C]:"";A!==D&&(g===-1&&(g=C),y=C);}let x=u.length>this.previousLines.length;if(x&&(g===-1&&(g=this.previousLines.length),y=u.length-1),g!==-1){let C=this.expandChangedRangeForKittyImages(g,y,u);g=C.firstChanged,y=C.lastChanged;}let w=x&&g===this.previousLines.length&&g>0;if(g===-1){this.positionHardwareCursor(p,u.length),this.previousViewportTop=l,this.previousHeight=r;return}if(g>=u.length){if(this.previousLines.length>u.length){let C=new vt(Y=>this.terminal.write(Y));C.append("\x1B[?2026h"),C.append(this.deleteChangedKittyImages(g,y));let A=Math.max(0,u.length-1);if(A<l){m(`deleted lines moved viewport up (${A} < ${l})`),f(true);return}let D=h(A);D>0?C.append(`\x1B[${D}B`):D<0&&C.append(`\x1B[${-D}A`),C.append("\r");let B=this.previousLines.length-u.length;if(B>r){m(`extraLines > height (${B} > ${r})`),f(true);return}let U=u.length===0?0:1;B>0&&U>0&&C.append(`\x1B[${U}B`);for(let Y=0;Y<B;Y++)C.append("\r\x1B[2K"),Y<B-1&&C.append("\x1B[1B");let fe=Math.max(0,B-1+U);fe>0&&C.append(`\x1B[${fe}A`),C.append("\x1B[?2026l"),C.flush(),this.cursorRow=A,this.hardwareCursorRow=A;}this.positionHardwareCursor(p,u.length),this.previousLines=u,this.previousKittyImageIds=this.collectKittyImageIds(u),this.previousWidth=e,this.previousHeight=r,this.previousViewportTop=l;return}if(g<l){m(`firstChanged < viewportTop (${g} < ${l})`),f(true);return}let I=new vt(C=>this.terminal.write(C));I.append("\x1B[?2026h"),I.append(this.deleteChangedKittyImages(g,y));let T=l+r-1,L=w?g-1:g;if(L>T){let C=Math.max(0,Math.min(r-1,c-l)),A=r-1-C;A>0&&I.append(`\x1B[${A}B`);let D=L-T;I.append(`\r
48
48
  `.repeat(D)),l+=D,a+=D,c=L;}let M=h(L);M>0?I.append(`\x1B[${M}B`):M<0&&I.append(`\x1B[${-M}A`),I.append(w?`\r
49
- `:"\r");let E=Math.min(x,u.length-1);for(let C=g;C<=E;C++){C>g&&I.append(`\r
50
- `);let A=u[C]??"",D=F(A),K=D?this.getKittyImageReservedRows(u,C,E):1;if(K>1){let U=C-a;if(U<0||U+K>r){m(`kitty image pre-clear would scroll (${U} + ${K} > ${r})`),f(true);return}I.append("\x1B[2K");for(let me=1;me<K;me++)I.append(`\r
51
- \x1B[2K`);I.append(`\x1B[${K-1}A`),I.append(A),I.append(`\x1B[${K-1}B`),C+=K-1;continue}if(I.append("\x1B[2K"),!D&&S(A)>e){let U=Ae.join(this.logDirectory??As.tmpdir(),"pi-tui-crash.log"),me=[`Crash at ${new Date().toISOString()}`,`Terminal width: ${e}`,`Line ${C} visible width: ${S(A)}`,"","=== All rendered lines ===",...u.map((et,Es)=>`[${Es}] (w=${S(et)}) ${et}`),""].join(`
52
- `);fe.mkdirSync(Ae.dirname(U),{recursive:true}),fe.writeFileSync(U,me),this.stop();let Y=[`Rendered line ${C} exceeds terminal width (${S(A)} > ${e}).`,"","This is likely caused by a custom TUI component not truncating its output.","Use visibleWidth() to measure and truncateToWidth() to truncate lines.","",`Debug log written to: ${U}`].join(`
49
+ `:"\r");let E=Math.min(y,u.length-1);for(let C=g;C<=E;C++){C>g&&I.append(`\r
50
+ `);let A=u[C]??"",D=F(A),B=D?this.getKittyImageReservedRows(u,C,E):1;if(B>1){let U=C-a;if(U<0||U+B>r){m(`kitty image pre-clear would scroll (${U} + ${B} > ${r})`),f(true);return}I.append("\x1B[2K");for(let fe=1;fe<B;fe++)I.append(`\r
51
+ \x1B[2K`);I.append(`\x1B[${B-1}A`),I.append(A),I.append(`\x1B[${B-1}B`),C+=B-1;continue}if(I.append("\x1B[2K"),!D&&S(A)>e){let U=Ae.join(this.logDirectory??Ls.tmpdir(),"pi-tui-crash.log"),fe=[`Crash at ${new Date().toISOString()}`,`Terminal width: ${e}`,`Line ${C} visible width: ${S(A)}`,"","=== All rendered lines ===",...u.map((et,As)=>`[${As}] (w=${S(et)}) ${et}`),""].join(`
52
+ `);pe.mkdirSync(Ae.dirname(U),{recursive:true}),pe.writeFileSync(U,fe),this.stop();let Y=[`Rendered line ${C} exceeds terminal width (${S(A)} > ${e}).`,"","This is likely caused by a custom TUI component not truncating its output.","Use visibleWidth() to measure and truncateToWidth() to truncate lines.","",`Debug log written to: ${U}`].join(`
53
53
  `);throw new Error(Y)}I.append(A);}let P=E;if(this.previousLines.length>u.length){if(E<u.length-1){let A=u.length-1-E;I.append(`\x1B[${A}B`),P=u.length-1;}let C=this.previousLines.length-u.length;for(let A=u.length;A<this.previousLines.length;A++)I.append(`\r
54
- \x1B[2K`);I.append(`\x1B[${C}A`);}if(I.append("\x1B[?2026l"),process.env.PI_TUI_DEBUG==="1"){let C="/tmp/tui";fe.mkdirSync(C,{recursive:true});let A=Ae.join(C,`render-${Date.now()}-${Math.random().toString(36).slice(2)}.log`),D=[`firstChanged: ${g}`,`viewportTop: ${a}`,`cursorRow: ${this.cursorRow}`,`height: ${r}`,`lineDiff: ${M}`,`hardwareCursorRow: ${c}`,`renderEnd: ${E}`,`finalCursorRow: ${P}`,`cursorPos: ${JSON.stringify(p)}`,`newLines.length: ${u.length}`,`previousLines.length: ${this.previousLines.length}`,"","=== newLines ===",JSON.stringify(u,null,2),"","=== previousLines ===",JSON.stringify(this.previousLines,null,2),"","=== buffer ===",`[${I.length} chars written in bounded chunks]`].join(`
55
- `);fe.writeFileSync(A,D);}I.flush(),this.cursorRow=Math.max(0,u.length-1),this.hardwareCursorRow=P,this.maxLinesRendered=Math.max(this.maxLinesRendered,u.length),this.previousViewportTop=Math.max(l,P-r+1),this.positionHardwareCursor(p,u.length),this.previousLines=u,this.previousKittyImageIds=this.collectKittyImageIds(u),this.previousWidth=e,this.previousHeight=r;}positionHardwareCursor(e,r){if(!e||r<=0){this.terminal.hideCursor();return}let n=Math.max(0,Math.min(e.row,r-1)),s=Math.max(0,e.col),o=n-this.hardwareCursorRow,l="";o>0?l+=`\x1B[${o}B`:o<0&&(l+=`\x1B[${-o}A`),l+=`\x1B[${s+1}G`,l&&this.terminal.write(l),this.hardwareCursorRow=n,this.getShowHardwareCursor()?this.terminal.showCursor():this.terminal.hideCursor();}};export{Mt as AGENT_ATTACHMENT_SYMBOL,Yr as Box,ie as CURSOR_MARKER,Xr as CancellableLoader,Tr as CombinedAutocompleteProvider,oe as Container,Vi as DEFAULT_ATTACHMENT_GLOB_PATTERN,Jr as Editor,J as FILE_ATTACHMENT_SYMBOL,ei as HStack,ri as Image,Me as Input,Ao as Key,jt as KeybindingsManager,ht as Loader,ai as Markdown,fi as MockTerminal,ci as MouseRegion,bi as ProcessTerminal,gt as ScrollView,dt as SelectList,ui as SettingsList,hi as Spacer,vt as StdinBuffer,Pn as TUI_KEYBINDINGS,ut as Text,di as TruncatedText,Si as TuiAltScreen,wi as TuiMainScreen,pi as VStack,Br as allocateImageId,sn as backgroundAnsi,oa as calculateImageRows,To as colorToHex,yo as colorToOkhsl,Pr as colorToOklch,ye as colorToRgb,de as compositeTuiLine,Dt as decodeKittyPrintable,Dr as deleteAllKittyImages,ct as deleteKittyImage,yn as detectCapabilities,Sn as encodeITerm2,vn as encodeKitty,Ui as extractAgentAttachmentPrefix,Hi as extractFileAttachmentPrefix,nn as foregroundAnsi,yt as formatProgramStatus,Re as fuzzyFilter,Ti as fuzzyMatch,re as getCapabilities,Nt as getCellDimensions,Ln as getGifDimensions,Vr as getImageDimensions,In as getJpegDimensions,G as getKeybindings,ll as getNativeClipboard,xr as getOsc8LinkAtColumn,Vt as getPngDimensions,Jo as getTerminalColorMode,kn as getWebpDimensions,Ht as hyperlink,Ut as imageFallback,en as indexedColor,ds as isAppleTerminalSession,Ur as isFocusable,lt as isKeyRelease,_o as isKeyRepeat,ko as isKittyProtocolActive,gi as isNativeModifierPressed,da as isViewportTUI,ae as matchesKey,Mo as mixColors,tn as okhslColor,Gi as oklabToOkhslLightness,Or as oklchColor,vo as parseColor,No as parseKey,_r as parseTerminalColorSchemeReport,Se as renderFakeCursor,Hr as renderImage,rr as renderLatex,ea as resetCapabilitiesCache,Ot as rgbColor,Ft as setCapabilities,ta as setCapabilityOverrides,Kr as setCellDimensions,wa as setImageTranscoder,pa as setKeybindings,at as setKittyProtocolActive,V as sliceByColumn,Ke as stripTerminalSequences,Lo as styleText,on as styleTextWithAnsi,N as truncateToWidth,S as visibleWidth,se as wrapTextWithAnsi};
54
+ \x1B[2K`);I.append(`\x1B[${C}A`);}if(I.append("\x1B[?2026l"),process.env.PI_TUI_DEBUG==="1"){let C="/tmp/tui";pe.mkdirSync(C,{recursive:true});let A=Ae.join(C,`render-${Date.now()}-${Math.random().toString(36).slice(2)}.log`),D=[`firstChanged: ${g}`,`viewportTop: ${a}`,`cursorRow: ${this.cursorRow}`,`height: ${r}`,`lineDiff: ${M}`,`hardwareCursorRow: ${c}`,`renderEnd: ${E}`,`finalCursorRow: ${P}`,`cursorPos: ${JSON.stringify(p)}`,`newLines.length: ${u.length}`,`previousLines.length: ${this.previousLines.length}`,"","=== newLines ===",JSON.stringify(u,null,2),"","=== previousLines ===",JSON.stringify(this.previousLines,null,2),"","=== buffer ===",`[${I.length} chars written in bounded chunks]`].join(`
55
+ `);pe.writeFileSync(A,D);}I.flush(),this.cursorRow=Math.max(0,u.length-1),this.hardwareCursorRow=P,this.maxLinesRendered=Math.max(this.maxLinesRendered,u.length),this.previousViewportTop=Math.max(l,P-r+1),this.positionHardwareCursor(p,u.length),this.previousLines=u,this.previousKittyImageIds=this.collectKittyImageIds(u),this.previousWidth=e,this.previousHeight=r;}positionHardwareCursor(e,r){if(!e||r<=0){this.terminal.hideCursor();return}let n=Math.max(0,Math.min(e.row,r-1)),s=Math.max(0,e.col),o=n-this.hardwareCursorRow,l="";o>0?l+=`\x1B[${o}B`:o<0&&(l+=`\x1B[${-o}A`),l+=`\x1B[${s+1}G`,l&&this.terminal.write(l),this.hardwareCursorRow=n,this.getShowHardwareCursor()?this.terminal.showCursor():this.terminal.hideCursor();}};export{Tt as AGENT_ATTACHMENT_SYMBOL,zr as Box,re as CURSOR_MARKER,jr as CancellableLoader,wr as CombinedAutocompleteProvider,se as Container,Fi as DEFAULT_ATTACHMENT_GLOB_PATTERN,Jr as Editor,J as FILE_ATTACHMENT_SYMBOL,Zr as HStack,ti as Image,Me as Input,xo as Key,Yt as KeybindingsManager,ct as Loader,oi as Markdown,pi as MockTerminal,li as MouseRegion,gi as ProcessTerminal,ft as ScrollView,ut as SelectList,ci as SettingsList,ui as Spacer,yt as StdinBuffer,Rn as TUI_KEYBINDINGS,lt as Text,hi as TruncatedText,vi as TuiAltScreen,Ci as TuiMainScreen,di as VStack,Br as allocateImageId,rn as backgroundAnsi,Xo as calculateImageRows,fo as colorToHex,lo as colorToOkhsl,Er as colorToOklch,xe as colorToRgb,he as compositeTuiLine,_t as decodeKittyPrintable,_r as deleteAllKittyImages,at as deleteKittyImage,bn as detectCapabilities,xn as encodeITerm2,yn as encodeKitty,Vi as extractAgentAttachmentPrefix,Wi as extractFileAttachmentPrefix,tn as foregroundAnsi,bt as formatProgramStatus,Re as fuzzyFilter,wi as fuzzyMatch,te as getCapabilities,Dt as getCellDimensions,Mn as getGifDimensions,Wr as getImageDimensions,Tn as getJpegDimensions,G as getKeybindings,Ja as getNativeClipboard,br as getOsc8LinkAtColumn,Wt as getPngDimensions,Ho as getTerminalColorMode,In as getWebpDimensions,Vt as hyperlink,Ht as imageFallback,Ji as indexedColor,us as isAppleTerminalSession,Hr as isFocusable,ot as isKeyRelease,Mo as isKeyRepeat,yo as isKittyProtocolActive,mi as isNativeModifierPressed,ra as isViewportTUI,ae as matchesKey,mo as mixColors,Zi as okhslColor,Ui as oklabToOkhslLightness,Pr as oklchColor,co as parseColor,Ao as parseKey,$r as parseTerminalColorSchemeReport,Se as renderFakeCursor,Vr as renderImage,tr as renderLatex,Uo as resetCapabilitiesCache,Pt as rgbColor,Nt as setCapabilities,qo as setCapabilityOverrides,Kr as setCellDimensions,pa as setImageTranscoder,ia as setKeybindings,st as setKittyProtocolActive,V as sliceByColumn,Be as stripTerminalSequences,bo as styleText,nn as styleTextWithAnsi,N as truncateToWidth,S as visibleWidth,ne as wrapTextWithAnsi};