dal-code 1.0.29 → 1.0.31
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +11 -0
- package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-guard/package.json +4 -4
- package/dist/node_modules/@dalcode/dal-guard/src/index.js +1 -1
- package/dist/node_modules/@dalcode/dal-guard/src/mode.js +2 -2
- package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
- package/dist/node_modules/@dalcode/dal-interactive/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-lsp/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-mcp/package.json +5 -5
- package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +2 -2
- package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
- package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.js +2 -2
- package/dist/node_modules/@dalcode/dal-plugins/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-review/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-rewind/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-router/package.json +4 -4
- package/dist/node_modules/@dalcode/dal-skills/package.json +4 -3
- package/dist/node_modules/@dalcode/dal-skills/src/catalog.js +2 -0
- package/dist/node_modules/@dalcode/dal-skills/src/index.js +12 -11
- package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
- package/dist/node_modules/@dalcode/dal-telemetry/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-terminal/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-tool-catalog/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-web/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-workflow/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-workflow/src/todo.js +2 -2
- package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
- package/dist/node_modules/@earendil-works/chord/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-agent-core/package.json +2 -2
- package/dist/node_modules/@earendil-works/pi-ai/dist/cli.js +0 -0
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-ai-gateway.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/github-copilot.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/google-vertex.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/google.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/meta.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode-go.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/radius.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/opencode-go.js +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/package.json +2 -2
- package/dist/node_modules/@earendil-works/pi-client/package.json +3 -3
- package/dist/node_modules/@earendil-works/pi-codemode/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-coding-agent/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-mcp/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-protocol/package.json +2 -2
- package/dist/node_modules/@earendil-works/pi-server/package.json +3 -3
- package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +2 -2
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/dist/bundle/chunks/anthropic-messages-AZKHNVAG.js +0 -5
- package/dist/bundle/chunks/anthropic.js +0 -74
- package/dist/bundle/chunks/azure-openai-responses-LA3FYF3J.js +0 -1
- package/dist/bundle/chunks/bedrock-converse-stream.js +0 -82
- package/dist/bundle/chunks/chunk-4HEMJ3PG.js +0 -1140
- package/dist/bundle/chunks/chunk-4L3WN2XY.js +0 -1
- package/dist/bundle/chunks/chunk-4UTLMBZZ.js +0 -13
- package/dist/bundle/chunks/chunk-4XT6IQQ6.js +0 -1
- package/dist/bundle/chunks/chunk-5M7W2EDY.js +0 -3
- package/dist/bundle/chunks/chunk-5ULSWE2O.js +0 -43
- package/dist/bundle/chunks/chunk-6CYCI3EJ.js +0 -11
- package/dist/bundle/chunks/chunk-7ZC4UXSL.js +0 -1
- package/dist/bundle/chunks/chunk-ABVPQ2YN.js +0 -14
- package/dist/bundle/chunks/chunk-DRQDKNXA.js +0 -1
- package/dist/bundle/chunks/chunk-F5ZABL6Z.js +0 -19
- package/dist/bundle/chunks/chunk-GYI2XXNW.js +0 -10
- package/dist/bundle/chunks/chunk-H3QXYIF7.js +0 -30
- package/dist/bundle/chunks/chunk-HC56T2OZ.js +0 -134
- package/dist/bundle/chunks/chunk-HMFU7ZIF.js +0 -1
- package/dist/bundle/chunks/chunk-JEMNLK2O.js +0 -10
- package/dist/bundle/chunks/chunk-L2ZPNLYD.js +0 -1
- package/dist/bundle/chunks/chunk-LPXNMA2W.js +0 -1
- package/dist/bundle/chunks/chunk-PGXDEOVV.js +0 -1
- package/dist/bundle/chunks/chunk-PJACZCIR.js +0 -1
- package/dist/bundle/chunks/chunk-PMRZO46Y.js +0 -1
- package/dist/bundle/chunks/chunk-PRRNXB7S.js +0 -1
- package/dist/bundle/chunks/chunk-PRXLTI3Y.js +0 -81
- package/dist/bundle/chunks/chunk-Q6IMZXWD.js +0 -129
- package/dist/bundle/chunks/chunk-R4YWRKK4.js +0 -7
- package/dist/bundle/chunks/chunk-RDZVAGPR.js +0 -1
- package/dist/bundle/chunks/chunk-S3GGRYIO.js +0 -5
- package/dist/bundle/chunks/chunk-TEPMHNKQ.js +0 -1
- package/dist/bundle/chunks/chunk-TRDNDS6A.js +0 -3
- package/dist/bundle/chunks/chunk-USJZMAIR.js +0 -1
- package/dist/bundle/chunks/chunk-UTB4DTYQ.js +0 -1
- package/dist/bundle/chunks/chunk-WXULTH2D.js +0 -1
- package/dist/bundle/chunks/chunk-YKF7PQCJ.js +0 -1
- package/dist/bundle/chunks/chunk-YTERFI73.js +0 -1
- package/dist/bundle/chunks/chunk-ZBURYEWF.js +0 -1
- package/dist/bundle/chunks/chunk-ZKDITC7J.js +0 -35
- package/dist/bundle/chunks/cli-2LJMKSUZ.js +0 -50
- package/dist/bundle/chunks/cloudflare-workers-ai-system-one-6WEJUIW2.js +0 -1
- package/dist/bundle/chunks/codemode-worker.js +0 -470
- package/dist/bundle/chunks/dist-37IE4EWG.js +0 -10
- package/dist/bundle/chunks/easter-egg-3d-GHWWTBZN.js +0 -1
- package/dist/bundle/chunks/execute-JU22LJZT.js +0 -489
- package/dist/bundle/chunks/github-copilot.js +0 -1
- package/dist/bundle/chunks/google-generative-ai-RFPHNE43.js +0 -1
- package/dist/bundle/chunks/google-vertex-QDNCMHLE.js +0 -1
- package/dist/bundle/chunks/http-proxy-6TR4MP55.js +0 -1
- package/dist/bundle/chunks/https-proxy-agent-2VXB7436.js +0 -12
- package/dist/bundle/chunks/image-resize-worker.js +0 -1
- package/dist/bundle/chunks/jiti-loader-C3NU2SDH.js +0 -20
- package/dist/bundle/chunks/jiti-static-loader-E6ANQD5T.js +0 -1
- package/dist/bundle/chunks/kimi-coding.js +0 -1
- package/dist/bundle/chunks/lib-TEDK3E5I.js +0 -8
- package/dist/bundle/chunks/llama-cpp-classify-FYN623RH.js +0 -21
- package/dist/bundle/chunks/meta.js +0 -1
- package/dist/bundle/chunks/mistral-conversations-YHX5TRKG.js +0 -4
- package/dist/bundle/chunks/multipart-parser-SQ6GDJL7.js +0 -2
- package/dist/bundle/chunks/node-N5BSDOA5.js +0 -15
- package/dist/bundle/chunks/node-TWVVAGPO.js +0 -1
- package/dist/bundle/chunks/openai-chatgpt.js +0 -74
- package/dist/bundle/chunks/openai-codex-responses-UZEMMAYZ.js +0 -9
- package/dist/bundle/chunks/openai-codex.js +0 -74
- package/dist/bundle/chunks/openai-completions-H6WMELZZ.js +0 -6
- package/dist/bundle/chunks/openai-decisions-URHWCZPN.js +0 -4
- package/dist/bundle/chunks/openai-responses-7X65PCAB.js +0 -2
- package/dist/bundle/chunks/openrouter-images-DUPG5DZO.js +0 -1
- package/dist/bundle/chunks/openrouter.js +0 -74
- package/dist/bundle/chunks/pi-messages-YHKPQIHC.js +0 -7
- package/dist/bundle/chunks/radius.js +0 -74
- package/dist/bundle/chunks/runtime-LLITCT4N.js +0 -1
- package/dist/bundle/chunks/src-UK77SYZE.js +0 -3
- package/dist/bundle/chunks/typesafe-system-one-N7PKHI2N.js +0 -1
- package/dist/bundle/chunks/virtual-modules-H32OTUCD.js +0 -1
- package/dist/bundle/chunks/xai.js +0 -1
- package/dist/bundle/cli-runtime.js +0 -2
- package/dist/bundle/cli.js +0 -2
- package/dist/bundle/index.js +0 -1
- package/dist/bundle/rpc-entry.js +0 -2
- package/dist/core/key-id-schema.js +0 -1
- package/dist/core/keybindings-schema.js +0 -1
- package/dist/core/settings-defaults.js +0 -1
- package/dist/core/settings-schema.js +0 -1
- package/dist/modes/interactive/components/daxnuts.js +0 -1
- package/dist/modes/interactive/theme/theme-schema.js +0 -12
- package/dist/modes/interactive/theme/theme-tokens.js +0 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/compat-schema.js +0 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/model-schema.js +0 -1
|
@@ -1,134 +0,0 @@
|
|
|
1
|
-
var rh=Object.defineProperty;var a=(e,t)=>rh(e,"name",{value:t,configurable:!0});import{createRequire as ih}from"node:module";const M0=ih(import.meta.url);import{require_bash as sh,require_c as nh,require_core as oh,require_cpp as lh,require_csharp as ah,require_dart as hh,require_go as uh,require_groovy as ch,require_java as dh,require_javascript as ph,require_json as fh,require_kotlin as gh,require_lua as mh,require_nix as xh,require_perl as bh,require_php as yh,require_python as wh,require_ruby as kh,require_rust as vh,require_scala as Sh,require_swift as Ch,require_typescript as Th}from"./chunk-S3GGRYIO.js";import{__commonJS as ie,__export as Ah,__require as Re,__toESM as q}from"./chunk-4L3WN2XY.js";var Mh=ie({"node_modules/isexe/windows.js"(e,t){t.exports=n,n.sync=o;var r=Re("fs");function i(l,h){var u=h.pathExt!==void 0?h.pathExt:process.env.PATHEXT;if(!u||(u=u.split(";"),u.indexOf("")!==-1))return!0;for(var d=0;d<u.length;d++){var c=u[d].toLowerCase();if(c&&l.substr(-c.length).toLowerCase()===c)return!0}return!1}a(i,"checkPathExt");function s(l,h,u){return!l.isSymbolicLink()&&!l.isFile()?!1:i(h,u)}a(s,"checkStat");function n(l,h,u){r.stat(l,function(d,c){u(d,d?!1:s(c,l,h))})}a(n,"isexe");function o(l,h){return s(r.statSync(l),l,h)}a(o,"sync")}}),Bh=ie({"node_modules/isexe/mode.js"(e,t){t.exports=i,i.sync=s;var r=Re("fs");function i(l,h,u){r.stat(l,function(d,c){u(d,d?!1:n(c,h))})}a(i,"isexe");function s(l,h){return n(r.statSync(l),h)}a(s,"sync");function n(l,h){return l.isFile()&&o(l,h)}a(n,"checkStat");function o(l,h){var u=l.mode,d=l.uid,c=l.gid,p=h.uid!==void 0?h.uid:process.getuid&&process.getuid(),f=h.gid!==void 0?h.gid:process.getgid&&process.getgid(),g=parseInt("100",8),x=parseInt("010",8),m=parseInt("001",8),b=g|x,C=u&m||u&x&&c===f||u&g&&d===p||u&b&&p===0;return C}a(o,"checkMode")}}),Rh=ie({"node_modules/isexe/index.js"(e,t){var r=Re("fs"),i;process.platform==="win32"||global.TESTING_WINDOWS?i=Mh():i=Bh(),t.exports=s,s.sync=n;function s(o,l,h){if(typeof l=="function"&&(h=l,l={}),!h){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(u,d){s(o,l||{},function(c,p){c?d(c):u(p)})})}i(o,l||{},function(u,d){u&&(u.code==="EACCES"||l&&l.ignoreErrors)&&(u=null,d=!1),h(u,d)})}a(s,"isexe");function n(o,l){try{return i.sync(o,l||{})}catch(h){if(l&&l.ignoreErrors||h.code==="EACCES")return!1;throw h}}a(n,"sync")}}),Eh=ie({"node_modules/which/which.js"(e,t){var r=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",i=Re("path"),s=r?";":":",n=Rh(),o=a(d=>Object.assign(new Error(`not found: ${d}`),{code:"ENOENT"}),"getNotFoundError"),l=a((d,c)=>{let p=c.colon||s,f=d.match(/\//)||r&&d.match(/\\/)?[""]:[...r?[process.cwd()]:[],...(c.path||process.env.PATH||"").split(p)],g=r?c.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",x=r?g.split(p):[""];return r&&d.indexOf(".")!==-1&&x[0]!==""&&x.unshift(""),{pathEnv:f,pathExt:x,pathExtExe:g}},"getPathInfo"),h=a((d,c,p)=>{typeof c=="function"&&(p=c,c={}),c||(c={});let{pathEnv:f,pathExt:g,pathExtExe:x}=l(d,c),m=[],b=a(S=>new Promise((y,k)=>{if(S===f.length)return c.all&&m.length?y(m):k(o(d));let v=f[S],B=/^".*"$/.test(v)?v.slice(1,-1):v,M=i.join(B,d),w=!B&&/^\.[\\\/]/.test(d)?d.slice(0,2)+M:M;y(C(w,S,0))}),"step"),C=a((S,y,k)=>new Promise((v,B)=>{if(k===g.length)return v(b(y+1));let M=g[k];n(S+M,{pathExt:x},(w,A)=>{if(!w&&A)if(c.all)m.push(S+M);else return v(S+M);return v(C(S,y,k+1))})}),"subStep");return p?b(0).then(S=>p(null,S),p):b(0)},"which"),u=a((d,c)=>{c=c||{};let{pathEnv:p,pathExt:f,pathExtExe:g}=l(d,c),x=[];for(let m=0;m<p.length;m++){let b=p[m],C=/^".*"$/.test(b)?b.slice(1,-1):b,S=i.join(C,d),y=!C&&/^\.[\\\/]/.test(d)?d.slice(0,2)+S:S;for(let k=0;k<f.length;k++){let v=y+f[k];try{if(n.sync(v,{pathExt:g}))if(c.all)x.push(v);else return v}catch{}}}if(c.all&&x.length)return x;if(c.nothrow)return null;throw o(d)},"whichSync");t.exports=h,h.sync=u}}),Ih=ie({"node_modules/path-key/index.js"(e,t){"use strict";var r=a((i={})=>{let s=i.env||process.env;return(i.platform||process.platform)!=="win32"?"PATH":Object.keys(s).reverse().find(n=>n.toUpperCase()==="PATH")||"Path"},"pathKey");t.exports=r,t.exports.default=r}}),Lh=ie({"node_modules/cross-spawn/lib/util/resolveCommand.js"(e,t){"use strict";var r=Re("path"),i=Eh(),s=Ih();function n(l,h){let u=l.options.env||process.env,d=process.cwd(),c=l.options.cwd!=null,p=c&&process.chdir!==void 0&&!process.chdir.disabled;if(p)try{process.chdir(l.options.cwd)}catch{}let f;try{f=i.sync(l.command,{path:u[s({env:u})],pathExt:h?r.delimiter:void 0})}catch{}finally{p&&process.chdir(d)}return f&&(f=r.resolve(c?l.options.cwd:"",f)),f}a(n,"resolveCommandAttempt");function o(l){return n(l)||n(l,!0)}a(o,"resolveCommand"),t.exports=o}}),Ph=ie({"node_modules/cross-spawn/lib/util/escape.js"(e,t){"use strict";var r=/([()\][%!^"`<>&|;, *?])/g;function i(n){return n=n.replace(r,"^$1"),n}a(i,"escapeCommand");function s(n,o){return n=`${n}`,n=n.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),n=n.replace(/(?=(\\+?)?)\1$/,"$1$1"),n=`"${n}"`,n=n.replace(r,"^$1"),o&&(n=n.replace(r,"^$1")),n}a(s,"escapeArgument"),t.exports.command=i,t.exports.argument=s}}),$h=ie({"node_modules/shebang-regex/index.js"(e,t){"use strict";t.exports=/^#!(.*)/}}),_h=ie({"node_modules/shebang-command/index.js"(e,t){"use strict";var r=$h();t.exports=(i="")=>{let s=i.match(r);if(!s)return null;let[n,o]=s[0].replace(/#! ?/,"").split(" "),l=n.split("/").pop();return l==="env"?o:o?`${l} ${o}`:l}}}),Oh=ie({"node_modules/cross-spawn/lib/util/readShebang.js"(e,t){"use strict";var r=Re("fs"),i=_h();function s(n){let o=Buffer.alloc(150),l;try{l=r.openSync(n,"r"),r.readSync(l,o,0,150,0),r.closeSync(l)}catch{}return i(o.toString())}a(s,"readShebang"),t.exports=s}}),Dh=ie({"node_modules/cross-spawn/lib/parse.js"(e,t){"use strict";var r=Re("path"),i=Lh(),s=Ph(),n=Oh(),o=process.platform==="win32",l=/\.(?:com|exe)$/i,h=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function u(p){p.file=i(p);let f=p.file&&n(p.file);return f?(p.args.unshift(p.file),p.command=f,i(p)):p.file}a(u,"detectShebang");function d(p){if(!o)return p;let f=u(p),g=!l.test(f);if(p.options.forceShell||g){let x=h.test(f);p.command=r.normalize(p.command),p.command=s.command(p.command),p.args=p.args.map(b=>s.argument(b,x));let m=[p.command].concat(p.args).join(" ");p.args=["/d","/s","/c",`"${m}"`],p.command=process.env.comspec||"cmd.exe",p.options.windowsVerbatimArguments=!0}return p}a(d,"parseNonShell");function c(p,f,g){f&&!Array.isArray(f)&&(g=f,f=null),f=f?f.slice(0):[],g=Object.assign({},g);let x={command:p,args:f,options:g,file:void 0,original:{command:p,args:f}};return g.shell?x:d(x)}a(c,"parse"),t.exports=c}}),Fh=ie({"node_modules/cross-spawn/lib/enoent.js"(e,t){"use strict";var r=process.platform==="win32";function i(l,h){return Object.assign(new Error(`${h} ${l.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${h} ${l.command}`,path:l.command,spawnargs:l.args})}a(i,"notFoundError");function s(l,h){if(!r)return;let u=l.emit;l.emit=function(d,c){if(d==="exit"){let p=n(c,h);if(p)return u.call(l,"error",p)}return u.apply(l,arguments)}}a(s,"hookChildProcess");function n(l,h){return r&&l===1&&!h.file?i(h.original,"spawn"):null}a(n,"verifyENOENT");function o(l,h){return r&&l===1&&!h.file?i(h.original,"spawnSync"):null}a(o,"verifyENOENTSync"),t.exports={hookChildProcess:s,verifyENOENT:n,verifyENOENTSync:o,notFoundError:i}}}),Ks=ie({"node_modules/cross-spawn/index.js"(e,t){"use strict";var r=Re("child_process"),i=Dh(),s=Fh();function n(l,h,u){let d=i(l,h,u),c=r.spawn(d.command,d.args,d.options);return s.hookChildProcess(c,d),c}a(n,"spawn2");function o(l,h,u){let d=i(l,h,u),c=r.spawnSync(d.command,d.args,d.options);return c.error=c.error||s.verifyENOENTSync(c.status,d),c}a(o,"spawnSync"),t.exports=n,t.exports.spawn=n,t.exports.sync=o,t.exports._parse=i,t.exports._enoent=s}});import{accessSync as Us,constants as js,existsSync as We,readFileSync as or,realpathSync as Nh}from"fs";import{createRequire as Wh}from"module";import{homedir as li}from"os";import{basename as zs,dirname as J,join as D,resolve as He,sep as Gs,win32 as Hh}from"path";import{fileURLToPath as Vh}from"url";var Ys=q(Ks(),1);import{spawn as qh,spawnSync as Kh}from"node:child_process";var Uh=100;function jh(e,t,r){return process.platform==="win32"?(0,Ys.default)(e,t,r):qh(e,t,r)}a(jh,"spawnProcess");function lr(e,t,r){return process.platform==="win32"?Ys.default.sync(e,t,r):Kh(e,t,r)}a(lr,"spawnProcessSync");function zh(e){return new Promise((t,r)=>{let i=!1,s=!1,n=null,o,l=e.stdout===null,h=e.stderr===null,u=a(()=>{o&&(clearTimeout(o),o=void 0),e.removeListener("error",m),e.removeListener("exit",b),e.removeListener("close",C),e.stdout?.removeListener("end",g),e.stderr?.removeListener("end",x),e.stdout?.removeListener("data",f),e.stderr?.removeListener("data",f)},"cleanup"),d=a(S=>{i||(i=!0,u(),e.stdout?.destroy(),e.stderr?.destroy(),t(S))},"finalize"),c=a(()=>{!s||i||l&&h&&d(n)},"maybeFinalizeAfterExit"),p=a(()=>{o&&clearTimeout(o),o=setTimeout(()=>d(n),Uh)},"armIdleTimer"),f=a(()=>{s&&!i&&p()},"onData"),g=a(()=>{l=!0,c()},"onStdoutEnd"),x=a(()=>{h=!0,c()},"onStderrEnd"),m=a(S=>{i||(i=!0,u(),r(S))},"onError"),b=a(S=>{s=!0,n=S,c(),i||p()},"onExit"),C=a(S=>{d(S)},"onClose");e.stdout?.once("end",g),e.stderr?.once("end",x),e.stdout?.on("data",f),e.stderr?.on("data",f),e.once("error",m),e.once("exit",b),e.once("close",C)})}a(zh,"waitForChildProcess");import{realpathSync as Gh,statSync as Yh}from"node:fs";import{homedir as Xh}from"node:os";import{isAbsolute as Xs,join as Qh,resolve as Qs,relative as Zh,sep as Zs}from"node:path";import{fileURLToPath as Jh}from"node:url";var eu=/[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g;function tu(e){try{return Gh(e)}catch{return e}}a(tu,"canonicalizePath");function ru(e){try{let t=Yh(e,{bigint:!0});return`${t.dev}:${t.ino}:${t.size}:${t.mtimeNs}:${t.ctimeNs}`}catch{return}}a(ru,"getFileRevision");function iu(e){let t=e.trim();return!(t.startsWith("npm:")||t.startsWith("git:")||t.startsWith("github:")||t.startsWith("http:")||t.startsWith("https:")||t.startsWith("ssh:")||t.startsWith("builtin:"))}a(iu,"isLocalPath");function su(e){if(!e.startsWith("/")||e.startsWith("//")||e.includes("\\"))return e;let t=e.match(/^\/(?:mnt\/|cygdrive\/)?([a-z])(?:\/(.*))?$/i);if(!t)return e;let r=t[2]?.replaceAll("/","\\");return`${t[1].toUpperCase()}:\\${r??""}`}a(su,"normalizeWindowsShellPath");function Pt(e,t={}){let r=t.trim?e.trim():e;if(t.normalizeUnicodeSpaces&&(r=r.replace(eu," ")),t.stripAtPrefix&&r.startsWith("@")&&(r=r.slice(1)),process.platform==="win32"&&(r=su(r)),t.expandTilde??!0){let i=t.homeDir??Xh();if(r==="~")return i;if(r.startsWith("~/")||process.platform==="win32"&&r.startsWith("~\\"))return Qh(i,r.slice(2))}return/^file:\/\//.test(r)?Jh(r):r}a(Pt,"normalizePath");function ar(e,t=process.cwd(),r={}){let i=Pt(e,r),s=Pt(t);return Xs(i)?Qs(i):Qs(s,i)}a(ar,"resolvePath");function Js(e,t){let r=ar(t),i=ar(e,r),s=Zh(r,i);return s===""||s!==".."&&!s.startsWith(`..${Zs}`)&&!Xs(s)?s||".":void 0}a(Js,"getCwdRelativePath");function nu(e,t){let r=ar(e,t);return(Js(r,t)??r).split(Zs).join("/")}a(nu,"formatPathRelativeToCwdOrAbsolute");function ou(e){let t=process.platform==="darwin"?["com.dropbox.ignored","com.apple.fileprovider.ignore#P"]:process.platform==="linux"?["user.com.dropbox.ignored"]:[];for(let r of t)process.platform==="darwin"?lr("xattr",["-w",r,"1",e],{encoding:"utf-8",stdio:"ignore"}):lr("setfattr",["-n",r,"-v","1",e],{encoding:"utf-8",stdio:"ignore"})}a(ou,"markPathIgnoredByCloudSync");function en(e){return e.startsWith("\uFEFF")?{bom:"\uFEFF",text:e.slice(1)}:{bom:"",text:e}}a(en,"splitBom");function Ve(e){return en(e).text}a(Ve,"stripBom");var lu=Vh(import.meta.url),tn=J(lu),Ee=import.meta.url.includes("$bunfs")||import.meta.url.includes("~BUN")||import.meta.url.includes("%7EBUN"),au=!!process.versions.bun,rn=!0;function hu(e){return e.startsWith("https://")||e.startsWith("http://")}a(hu,"isUrlInstallSpec");function sn(e){return typeof e=="string"?{packageName:e,installSpec:e}:{packageName:e.packageName,installSpec:e.installSpec??e.packageName}}a(sn,"normalizeSelfUpdatePackageTarget");function hr(e,t){return t?{...e,display:`${t.display} && ${e.display}`,steps:[t,e]}:e}a(hr,"makeSelfUpdateCommand");function Ie(e,t){return{command:e,args:t,display:[e,...t].map(r=>/\s/.test(r)?`"${r}"`:r).join(" ")}}a(Ie,"makeSelfUpdateCommandStep");function ai(){if(Ee)return"bun-binary";let e=`${tn}\0${process.execPath||""}`.toLowerCase().replace(/\\/g,"/");return e.includes("/pnpm/")||e.includes("/.pnpm/")?"pnpm":e.includes("/yarn/")||e.includes("/.yarn/")?"yarn":au||e.includes("/install/global/node_modules/")?"bun":e.includes("/npm/")||e.includes("/node_modules/")?"npm":"unknown"}a(ai,"detectInstallMethod");function nn(){let e=X(),t=process.platform==="win32"||e.includes("\\")?Hh:{basename:zs,dirname:J},r=t.dirname(e),i;if(t.basename(r).startsWith("@")&&t.basename(t.dirname(r))==="node_modules"?i=t.dirname(r):t.basename(r)==="node_modules"&&(i=r),!i)return;let s=t.dirname(i);if(t.basename(s)==="lib")return{root:i,prefix:t.dirname(s)}}a(nn,"getInferredNpmInstall");function on(e,t,r=t,i){let s=sn(r),n=s.packageName===yn&&!hu(s.installSpec)?[`--${$u}:registry=${vn}/`]:[];switch(e){case"bun-binary":return;case"pnpm":{let o=lt("pnpm",["root","-g"])?void 0:/^(.*[\\/]global[\\/][^\\/]+)[\\/]\.pnpm[\\/]/.exec(X()),l=o?[`--config.global-bin-dir=${process.env.PNPM_HOME||J(J(o[1]))}`]:[];return hr(Ie("pnpm",["install","-g","--ignore-scripts","--config.minimumReleaseAge=0",...l,...n,s.installSpec]),s.packageName===t?void 0:Ie("pnpm",["remove","-g",...l,t]))}case"yarn":return hr(Ie("yarn",["global","add","--ignore-scripts",...n,s.installSpec]),s.packageName===t?void 0:Ie("yarn",["global","remove",t]));case"bun":return hr(Ie("bun",["install","-g","--ignore-scripts","--minimum-release-age=0",...n,s.installSpec]),s.packageName===t?void 0:Ie("bun",["uninstall","-g",t]));case"npm":{let[o="npm",...l]=i??[],h=i?.length?void 0:nn(),u=[...l,...h?["--prefix",h.prefix]:[]],d=Ie(o,[...u,"install","-g","--ignore-scripts","--min-release-age=0",...n,s.installSpec]),c=s.packageName===t?void 0:Ie(o,[...u,"uninstall","-g",t]);return hr(d,c)}case"unknown":return}}a(on,"getSelfUpdateCommandForMethod");function lt(e,t,r={}){let i=lr(e,t,{encoding:"utf-8",stdio:["ignore","pipe","pipe"]});if(i.status===0)return i.stdout.trim()||void 0;if(r.requireSuccess){let s=i.error?.message||i.stderr.trim()||`exit code ${i.status??"unknown"}`;throw new Error(`Failed to run ${[e,...t].join(" ")}: ${s}`)}}a(lt,"readCommandOutput");function uu(e,t,r){switch(e){case"npm":{let i=!!r?.length,[s="npm",...n]=r??[];if(i&&s==="bun"){let h=lt(s,[...n,"pm","bin","-g"],{requireSuccess:!0}),u=[D(li(),".bun","install","global","node_modules")];return h&&u.push(D(J(h),"install","global","node_modules")),u}let o=lt(s,[...n,"root","-g"],{requireSuccess:i}),l=i?void 0:nn();return[o,l?.root].filter(h=>!!h)}case"pnpm":{let i=lt("pnpm",["root","-g"]);if(i)return[i,J(i)];let s=/^(.*[\\/]global[\\/][^\\/]+)[\\/]\.pnpm[\\/]/.exec(X());return s?[s[1]]:[]}case"yarn":{let i=lt("yarn",["global","dir"]);return i?[i,D(i,"node_modules")]:[]}case"bun":{let i=lt("bun",["pm","bin","-g"]),s=[D(li(),".bun","install","global","node_modules")];return i&&s.push(D(J(i),"install","global","node_modules")),s}case"bun-binary":case"unknown":return[]}}a(uu,"getGlobalPackageRoots");function ln(e,t){let r=He(e);if(!We(r))return;let i=r;if(t)try{i=Nh(r)}catch{return}return process.platform==="win32"&&(i=i.toLowerCase()),i}a(ln,"normalizeExistingPathForComparison");function an(e){return Array.from(new Set([ln(e,!1),ln(e,!0)].filter(t=>!!t)))}a(an,"getPathComparisonCandidates");function cu(){let e=process.argv[1];if(!e)return;let t=J(e);for(;t!==J(t);){if(We(D(t,"package.json")))return t;t=J(t)}}a(cu,"getEntrypointPackageDir");function hn(){let e=X();try{return Us(e,js.W_OK),Us(J(e),js.W_OK),!0}catch{return!1}}a(hn,"isSelfUpdatePathWritable");function un(e,t,r){let i=[X(),cu()].filter(s=>!!s).flatMap(s=>an(s));return uu(e,t,r).some(s=>an(s).some(n=>{let o=n.endsWith(Gs)?n:`${n}${Gs}`;return i.some(l=>l.startsWith(o))}))}a(un,"isManagedByGlobalPackageManager");function du(e,t,r=e){let i=ai(),s=on(i,e,r,t);if(!(!s||!un(i,e,t)||!hn()))return s}a(du,"getSelfUpdateCommand");function pu(e,t,r=e){let i=ai(),s=sn(r);if(i==="bun-binary")return`Download from: ${Ke==="pi"?"https://github.com/earendil-works/pi/releases/latest":kn}`;let n=on(i,e,s,t);return n?un(i,e,t)&&!hn()?`This installation is managed by a global ${i} install, but the install path is not writable. Update it yourself with: ${n.display}`:`This installation is not managed by a global ${i} install. Update it with the package manager, wrapper, or source checkout that provides it.`:`Update ${s.installSpec} using the package manager, wrapper, or source checkout that provides this installation.`}a(pu,"getSelfUpdateUnavailableInstruction");function fu(e){let t=e;for(;t!==J(t);){if(We(D(t,"package.json"))){let r=J(t);return zs(t)==="dist"&&We(D(r,"package.json"))?r:t}t=J(t)}return e}a(fu,"findNodePackageDir");function X(){let e=process.env.PI_PACKAGE_DIR;return e?Pt(e):Ee?J(process.execPath):fu(tn)}a(X,"getPackageDir");function cn(){if(Ee)return D(X(),"theme");let e=X(),t=We(D(e,"src"))?"src":"dist";return D(e,t,"modes","interactive","theme")}a(cn,"getThemesDir");function gu(){if(Ee)return D(X(),"export-html");let e=X(),t=We(D(e,"src"))?"src":"dist";return D(e,t,"core","export-html")}a(gu,"getExportTemplateDir");function mu(){return D(X(),"package.json")}a(mu,"getPackageJsonPath");function xu(){return He(D(X(),"README.md"))}a(xu,"getReadmePath");function bu(){return He(D(X(),"docs"))}a(bu,"getDocsPath");function dn(){return He(D(X(),"examples"))}a(dn,"getExamplesPath");function yu(){return He(D(X(),"dal-docs"))}a(yu,"getDalDocsPath");function wu(){return He(D(dn(),"extensions","official"))}a(wu,"getOfficialExtensionsPath");var ku="@deepailab/dal-official-extensions";function vu(e){try{return JSON.parse(Ve(or(D(e,"package.json"),"utf-8"))).name===ku}catch{return!1}}a(vu,"isOfficialExtensionsPackage");function Su(){return He(D(X(),"CHANGELOG.md"))}a(Su,"getChangelogPath");function Cu(){if(Ee)return D(X(),"assets");let e=X(),t=We(D(e,"src"))?"src":"dist";return D(e,t,"modes","interactive","assets")}a(Cu,"getInteractiveAssetsDir");function Tu(e){return D(Cu(),e)}a(Tu,"getBundledInteractiveAssetPath");var pn;function Au(){return pn??=Wh(import.meta.url).resolve("quickjs-wasi/quickjs.wasm"),pn}a(Au,"getQuickJSWasmPath");function Mu(e,t){if(e==="bun-binary")return"./src/extensions/codemode/worker.ts";if(e==="bundled-node")return new URL("./codemode-worker.js",t)}a(Mu,"resolveCodemodeWorkerSpecifier");var fn;function Bu(){let e=Ee?"bun-binary":rn?"bundled-node":"unbundled",t=Mu(e,import.meta.url);return e!=="bundled-node"||!(t instanceof URL)?t:(fn??=new URL(`data:text/javascript;base64,${or(t).toString("base64")}`),fn)}a(Bu,"getCodemodeWorkerSpecifier");function Ru(e=gn){if(Ee||!e)return;let t;try{t=JSON.parse(Ve(or(e,"utf-8")))}catch(r){return r.code==="ENOENT"?{kind:"removed"}:void 0}return t.version&&t.version!==bn?{kind:"updated",version:t.version}:void 0}a(Ru,"detectInstallChange");var qe={},gn;try{let e=mu();qe=JSON.parse(Ve(or(e,"utf-8"))),gn=e}catch(e){if(e.code!=="ENOENT")throw e}var mn=qe.piConfig?.name,Eu=qe.name||"@earendil-works/pi-coding-agent",Ke=mn||"pi",Iu=qe.piConfig?.title||(mn?Ke:"\u03C0"),xn=qe.piConfig?.configDir||".dal",Lu=Ke!=="pi",Pu=[".agents",".claude"],bn=qe.version||"0.0.0",W0=qe.piConfig?.upstreamPi,yn="@deepailab/dal",$u="@deepailab",wn="DeepAILab-Team/dal-dist",kn=`https://github.com/${wn}/releases`,vn="https://git.siweibot.com/api/packages/gitea/npm",Sn=`${Ke.toUpperCase()}_CODING_AGENT_DIR`,_u=`${Ke.toUpperCase()}_CODING_AGENT_SESSION_DIR`;function Cn(e){return Pt(e)}a(Cn,"expandTildePath");function Ou(e,t=`https://gist.github.com/${e}`){let r=process.env.DAL_SHARE_VIEWER_URL||process.env.PI_SHARE_VIEWER_URL;return r?`${r}#${e}`:t}a(Ou,"getShareViewerUrl");function at(){let e=process.env[Sn];return e?Cn(e):D(li(),xn,"agent")}a(at,"getAgentDir");function hi(){return D(at(),"themes")}a(hi,"getCustomThemesDir");function Du(){return D(at(),"settings.json")}a(Du,"getSettingsPath");function Fu(){return D(at(),"bin")}a(Fu,"getBinDir");function Nu(){return D(at(),"sessions")}a(Nu,"getSessionsDir");function Wu(){return D(at(),`${Ke}-debug.log`)}a(Wu,"getDebugLogPath");function Hu(e,t,r){let i=e.indexOf(t);if(i===-1)return e;let s=t.length,n=0,o="";do o+=e.slice(n,i)+t+r,n=i+s,i=e.indexOf(t,n);while(i!==-1);return o+=e.slice(n),o}a(Hu,"stringReplaceAll");function Vu(e,t,r,i){let s=0,n="";do{let o=e[i-1]==="\r";n+=e.slice(s,o?i-1:i)+t+(o?`\r
|
|
2
|
-
`:`
|
|
3
|
-
`)+r,s=i+1,i=e.indexOf(`
|
|
4
|
-
`,s)}while(i!==-1);return n+=e.slice(s),n}a(Vu,"stringEncaseCRLFWithFirstIndex");var Tn=a((e=0)=>t=>`\x1B[${t+e}m`,"wrapAnsi16"),ui=a((e=0)=>t=>`\x1B[${38+e};5;${t}m`,"wrapAnsi256"),ci=a((e=0)=>(t,r,i)=>`\x1B[${38+e};2;${t};${r};${i}m`,"wrapAnsi16m"),qu=a(e=>`\x1B[58;5;${e<90?e-30:e-90+8}m`,"wrapUnderlineAnsi"),N={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],underlineDouble:["4:2",24],underlineCurly:["4:3",24],underlineDotted:["4:4",24],underlineDashed:["4:5",24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]},underlineColor:{underlineBlack:["58;5;0",59],underlineRed:["58;5;1",59],underlineGreen:["58;5;2",59],underlineYellow:["58;5;3",59],underlineBlue:["58;5;4",59],underlineMagenta:["58;5;5",59],underlineCyan:["58;5;6",59],underlineWhite:["58;5;7",59],underlineBlackBright:["58;5;8",59],underlineGray:["58;5;8",59],underlineGrey:["58;5;8",59],underlineRedBright:["58;5;9",59],underlineGreenBright:["58;5;10",59],underlineYellowBright:["58;5;11",59],underlineBlueBright:["58;5;12",59],underlineMagentaBright:["58;5;13",59],underlineCyanBright:["58;5;14",59],underlineWhiteBright:["58;5;15",59]}},H0=Object.keys(N.modifier),Ku=Object.keys(N.color),Uu=Object.keys(N.bgColor),V0=Object.keys(N.underlineColor),q0=[...Ku,...Uu];function ju(){let e=new Map;for(let[t,r]of Object.entries(N)){for(let[i,s]of Object.entries(r))N[i]={open:`\x1B[${s[0]}m`,close:`\x1B[${s[1]}m`},r[i]=N[i],e.set(Number.parseInt(s[0],10),s[1]);Object.defineProperty(N,t,{value:r,enumerable:!1})}return Object.defineProperty(N,"codes",{value:e,enumerable:!1}),N.color.close="\x1B[39m",N.bgColor.close="\x1B[49m",N.underlineColor.close="\x1B[59m",N.color.ansi=Tn(),N.color.ansi256=ui(),N.color.ansi16m=ci(),N.bgColor.ansi=Tn(10),N.bgColor.ansi256=ui(10),N.bgColor.ansi16m=ci(10),N.underlineColor.ansi=qu,N.underlineColor.ansi256=ui(20),N.underlineColor.ansi16m=ci(20),Object.defineProperties(N,{rgbToAnsi256:{value(t,r,i){return t===r&&r===i?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(r/255*5)+Math.round(i/255*5)},enumerable:!1},hexToRgb:{value(t){let r=/[\da-f]{6}|[\da-f]{3}/i.exec(t.toString(16));if(!r)return[0,0,0];let[i]=r;i.length===3&&(i=[...i].map(n=>n+n).join(""));let s=Number.parseInt(i,16);return[s>>16&255,s>>8&255,s&255]},enumerable:!1},hexToAnsi256:{value:a(t=>N.rgbToAnsi256(...N.hexToRgb(t)),"value"),enumerable:!1},ansi256ToAnsi:{value(t){if(t<8)return 30+t;if(t<16)return 90+(t-8);let r,i,s;if(t>=232)r=((t-232)*10+8)/255,i=r,s=r;else{t-=16;let l=t%36;r=Math.floor(t/36)/5,i=Math.floor(l/6)/5,s=l%6/5}let n=Math.max(r,i,s)*2;if(n===0)return 30;let o=30+(Math.round(s)<<2|Math.round(i)<<1|Math.round(r));return n===2&&(o+=60),o},enumerable:!1},rgbToAnsi:{value:a((t,r,i)=>N.ansi256ToAnsi(N.rgbToAnsi256(t,r,i)),"value"),enumerable:!1},hexToAnsi:{value:a(t=>N.ansi256ToAnsi(N.hexToAnsi256(t)),"value"),enumerable:!1}}),N}a(ju,"assembleStyles");var zu=ju(),we=zu;import di from"node:process";import Gu from"node:os";import An from"node:tty";function ne(e,t=globalThis.Deno?globalThis.Deno.args:di.argv){let r=e.startsWith("-")?"":e.length===1?"-":"--",i=t.indexOf(r+e),s=t.indexOf("--");return i!==-1&&(s===-1||i<s)}a(ne,"hasFlag");var{env:H}=di,ur;ne("no-color")||ne("no-colors")||ne("color=false")||ne("color=never")?ur=0:(ne("color")||ne("colors")||ne("color=true")||ne("color=always"))&&(ur=1);function Mn(){return/^\d+$/.test(H.FORCE_COLOR)}a(Mn,"hasNumericForceColor");function Yu(){if("FORCE_COLOR"in H){if(H.FORCE_COLOR==="false")return 0;if(H.FORCE_COLOR==="true"||H.FORCE_COLOR.length===0)return 1;if(Mn())return Math.min(Number.parseInt(H.FORCE_COLOR,10),3)}}a(Yu,"envForceColor");function Xu(e){return e===0?!1:{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}a(Xu,"translateLevel");function Qu(e,{streamIsTTY:t,sniffFlags:r=!0}={}){let i=Yu();i!==void 0&&(ur=i);let s=r?ur:i;if(s===0)return 0;if(r){if(ne("color=16m")||ne("color=full")||ne("color=truecolor"))return 3;if(ne("color=256"))return 2}if(s!==void 0&&Mn())return s;if("TF_BUILD"in H&&"AGENT_NAME"in H)return 1;if(e&&!t&&s===void 0)return 0;let n=s||0;if(H.TERM==="dumb")return n;if(di.platform==="win32"){let o=Gu.release().split(".");return Number(o[0])>=10&&Number(o[2])>=10586?Number(o[2])>=14931?3:2:1}if("CI"in H)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(o=>o in H)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(o=>o in H)||H.CI_NAME==="codeship"?1:n;if("TEAMCITY_VERSION"in H)return/^(?:9\.0*[1-9]\d*\.|\d{2,}\.)/.test(H.TEAMCITY_VERSION)?1:0;if(H.COLORTERM==="truecolor"||H.TERM==="xterm-kitty"||H.TERM==="xterm-ghostty"||H.TERM==="wezterm")return 3;if("TERM_PROGRAM"in H){let o=Number.parseInt((H.TERM_PROGRAM_VERSION||"").split(".",1)[0],10);switch(H.TERM_PROGRAM){case"iTerm.app":return o>=3?3:2;case"Apple_Terminal":return 2}}return/-256(?:color)?$/i.test(H.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(H.TERM)||"COLORTERM"in H?1:n}a(Qu,"_supportsColor");function Bn(e,t={}){let r=Qu(e,{streamIsTTY:e&&e.isTTY,...t});return Xu(r)}a(Bn,"createSupportsColor");var Zu={stdout:Bn({isTTY:An.isatty(1)}),stderr:Bn({isTTY:An.isatty(2)})},Ju=Zu,{stdout:Rn,stderr:En}=Ju,$t=Symbol("GENERATOR"),_t=Symbol("STYLER"),cr=Symbol("IS_EMPTY"),dr=Symbol("LEVEL"),Ot=Object.create(null),In=a(e=>{if(!Number.isSafeInteger(e)||e<0||e>3)throw new Error("The `level` should be an integer from 0 to 3")},"assertValidLevel"),ec={enumerable:!0,get(){return this[dr]},set(e){In(e),this[dr]=e}},tc=a((e,t={})=>{t.level!==void 0&&In(t.level);let r=Rn?Rn.level:0;e[dr]=t.level===void 0?r:t.level},"applyOptions"),rc=a(e=>{let t=a((...r)=>r.join(" "),"chalk2");return tc(t,e),Object.setPrototypeOf(t,Dt.prototype),t},"chalkFactory");function Dt(e){return rc(e)}a(Dt,"createChalk"),Object.setPrototypeOf(Dt.prototype,Function.prototype);for(let[e,t]of Object.entries(we))Ot[e]={get(){let r=pi(this,Ln(t.open,t.close,this[_t]),this[cr]);return Object.defineProperty(this,e,{value:r}),r}};Ot.visible={get(){let e=pi(this,this[_t],!0);return Object.defineProperty(this,"visible",{value:e}),e}};var ic=a((e,t)=>{let r=we[t];if(e==="rgb"){let s=a((n,o,l)=>r.ansi(we.rgbToAnsi(n,o,l)),"ansi2");return[s,s,(n,o,l)=>r.ansi256(we.rgbToAnsi256(n,o,l)),r.ansi16m]}if(e==="hex"){let s=a(n=>r.ansi(we.hexToAnsi(n)),"ansi2");return[s,s,n=>r.ansi256(we.hexToAnsi256(n)),n=>r.ansi16m(...we.hexToRgb(n))]}let i=a(s=>r.ansi(we.ansi256ToAnsi(s)),"ansi");return[i,i,r.ansi256,r.ansi256]},"createModelConverters"),sc=["rgb","hex","ansi256"];for(let e of sc){let t=e[0].toUpperCase()+e.slice(1);for(let[r,i]of[[e,"color"],["bg"+t,"bgColor"],["underline"+t,"underlineColor"]]){let{close:s}=we[i],n=ic(e,i);Ot[r]={get(){let o=a(function(l,h,u){let d=n[this.level](l,h,u);return pi(this,Ln(d,s,this[_t]),this[cr])},"styleFunction");return Object.defineProperty(this,r,{value:o}),o}}}}var nc=Object.defineProperties(()=>{},{...Ot,level:{enumerable:!0,get(){return this[$t].level},set(e){this[$t].level=e}}}),Ln=a((e,t,r)=>{let i,s;return r===void 0?(i=e,s=t):(i=r.openAll+e,s=t+r.closeAll),{open:e,close:t,openAll:i,closeAll:s,parent:r}},"createStyler"),pi=a((e,t,r)=>{let i=a((...s)=>s.length===1?fi(i,""+s[0]):s.length===2?fi(i,s[0]+" "+s[1]):fi(i,s.join(" ")),"builder");return Object.setPrototypeOf(i,nc),i[$t]=e[$t]??e,i[_t]=t,i[cr]=r,i},"createBuilder"),fi=a((e,t)=>{if(e[$t][dr]<=0||!t)return e[cr]?"":t;let r=e[_t];if(r===void 0)return t;let{openAll:i,closeAll:s}=r;if(t.includes("\x1B"))for(;r!==void 0;)t=Hu(t,r.close,r.open),r=r.parent;let n=t.indexOf(`
|
|
5
|
-
`);return n!==-1&&(t=Vu(t,s,i,n)),i+t+s},"applyStyle");Object.defineProperties(Dt.prototype,{...Ot,level:ec});var oc=Dt(),z0=Dt({level:En?En.level:0}),ht=oc,lc=[161,161,164,164,167,168,170,170,173,174,176,180,182,186,188,191,198,198,208,208,215,216,222,225,230,230,232,234,236,237,240,240,242,243,247,250,252,252,254,254,257,257,273,273,275,275,283,283,294,295,299,299,305,307,312,312,319,322,324,324,328,331,333,333,338,339,358,359,363,363,462,462,464,464,466,466,468,468,470,470,472,472,474,474,476,476,593,593,609,609,708,708,711,711,713,715,717,717,720,720,728,731,733,733,735,735,768,879,913,929,931,937,945,961,963,969,1025,1025,1040,1103,1105,1105,8208,8208,8211,8214,8216,8217,8220,8221,8224,8226,8228,8231,8240,8240,8242,8243,8245,8245,8251,8251,8254,8254,8308,8308,8319,8319,8321,8324,8364,8364,8451,8451,8453,8453,8457,8457,8467,8467,8470,8470,8481,8482,8486,8486,8491,8491,8531,8532,8539,8542,8544,8555,8560,8569,8585,8585,8592,8601,8632,8633,8658,8658,8660,8660,8679,8679,8704,8704,8706,8707,8711,8712,8715,8715,8719,8719,8721,8721,8725,8725,8730,8730,8733,8736,8739,8739,8741,8741,8743,8748,8750,8750,8756,8759,8764,8765,8776,8776,8780,8780,8786,8786,8800,8801,8804,8807,8810,8811,8814,8815,8834,8835,8838,8839,8853,8853,8857,8857,8869,8869,8895,8895,8978,8978,9312,9449,9451,9547,9552,9587,9600,9615,9618,9621,9632,9633,9635,9641,9650,9651,9654,9655,9660,9661,9664,9665,9670,9672,9675,9675,9678,9681,9698,9701,9711,9711,9733,9734,9737,9737,9742,9743,9756,9756,9758,9758,9792,9792,9794,9794,9824,9825,9827,9829,9831,9834,9836,9837,9839,9839,9886,9887,9919,9919,9926,9933,9935,9939,9941,9953,9955,9955,9960,9961,9963,9969,9972,9972,9974,9977,9979,9980,9982,9983,10045,10045,10102,10111,11094,11097,12872,12879,57344,63743,65024,65039,65533,65533,127232,127242,127248,127277,127280,127337,127344,127373,127375,127376,127387,127404,917760,917999,983040,1048573,1048576,1114109],ac=12288,hc=65510,uc=[12288,12288,65281,65376,65504,65510],cc=4352,dc=262141,Pn=[4352,4447,8986,8987,9001,9002,9193,9196,9200,9200,9203,9203,9725,9726,9748,9749,9776,9783,9800,9811,9855,9855,9866,9871,9875,9875,9889,9889,9898,9899,9917,9918,9924,9925,9934,9934,9940,9940,9962,9962,9970,9971,9973,9973,9978,9978,9981,9981,9989,9989,9994,9995,10024,10024,10060,10060,10062,10062,10067,10069,10071,10071,10133,10135,10160,10160,10175,10175,11035,11036,11088,11088,11093,11093,11904,11929,11931,12019,12032,12245,12272,12287,12289,12350,12353,12438,12441,12543,12549,12591,12593,12686,12688,12773,12783,12830,12832,12871,12880,42124,42128,42182,43360,43388,44032,55203,63744,64255,65040,65049,65072,65106,65108,65126,65128,65131,94176,94180,94192,94198,94208,101589,101631,101662,101760,101874,110576,110579,110581,110587,110589,110590,110592,110882,110898,110898,110928,110930,110933,110933,110948,110951,110960,111355,119552,119638,119648,119670,126980,126980,127183,127183,127374,127374,127377,127386,127488,127490,127504,127547,127552,127560,127568,127569,127584,127589,127744,127776,127789,127797,127799,127868,127870,127891,127904,127946,127951,127955,127968,127984,127988,127988,127992,128062,128064,128064,128066,128252,128255,128317,128331,128334,128336,128359,128378,128378,128405,128406,128420,128420,128507,128591,128640,128709,128716,128716,128720,128722,128725,128728,128732,128735,128747,128748,128756,128764,128992,129003,129008,129008,129292,129338,129340,129349,129351,129535,129648,129660,129664,129674,129678,129734,129736,129736,129741,129756,129759,129770,129775,129784,131072,196605,196608,262141],gi=a((e,t)=>{let r=0,i=Math.floor(e.length/2)-1;for(;r<=i;){let s=Math.floor((r+i)/2),n=s*2;if(t<e[n])i=s-1;else if(t>e[n+1])r=s+1;else return!0}return!1},"isInRange"),$n=19968,[pc,fc]=gc(Pn);function gc(e){let t=e[0],r=e[1];for(let i=0;i<e.length;i+=2){let s=e[i],n=e[i+1];if($n>=s&&$n<=n)return[s,n];n-s>r-t&&(t=s,r=n)}return[t,r]}a(gc,"findWideFastPathRange");var mc=a(e=>e<161||e>1114109?!1:gi(lc,e),"isAmbiguous"),xc=a(e=>e<ac||e>hc?!1:gi(uc,e),"isFullWidth"),bc=a(e=>e>=pc&&e<=fc?!0:e<cc||e>dc?!1:gi(Pn,e),"isWide");function yc(e){if(!Number.isSafeInteger(e))throw new TypeError(`Expected a code point, got \`${typeof e}\`.`)}a(yc,"validate");function _n(e,{ambiguousAsWide:t=!1}={}){return yc(e),xc(e)||bc(e)||t&&mc(e)?2:1}a(_n,"eastAsianWidth");var oe=new Intl.Segmenter(void 0,{granularity:"grapheme"}),wc=new Intl.Segmenter(void 0,{granularity:"word"});function mi(){return oe}a(mi,"getGraphemeSegmenter");function xi(){return wc}a(xi,"getWordSegmenter");function kc(e){let t=e.codePointAt(0);return t>=126976&&t<=130047||t>=8960&&t<=9215||t>=9728&&t<=10175||t>=11088&&t<=11093||e.includes("\uFE0F")||e.length>2}a(kc,"couldBeEmoji");var vc=new RegExp("^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Mark}|\\p{Surrogate})+$","v"),Sc=new RegExp("^[\\p{Default_Ignorable_Code_Point}\\p{Control}\\p{Format}\\p{Mark}\\p{Surrogate}]+","v"),Cc=new RegExp("^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Format}|\\p{Mark}|\\p{Surrogate})$","v"),Tc=new RegExp("^\\p{Mark}$","v"),On=new RegExp("^(?:[\\p{Spacing_Mark}--[\\u1734\\u302E\\u302F]]|[\\u065F\\u0F7F\\u102B\\u102C\\u1031\\u1033-\\u1035\\u1038\\u103A-\\u103E])+$","v"),Ac=new RegExp("^\\p{RGI_Emoji}$","v"),Mc=512,Ft=new Map,Nt=/[\p{Script_Extensions=Han}\p{Script_Extensions=Hiragana}\p{Script_Extensions=Katakana}\p{Script_Extensions=Hangul}\p{Script_Extensions=Bopomofo}]/u,Bc=new RegExp(`(?:(?=\\p{Punctuation})${Nt.source}|[\uFF0C\uFF0E\uFF1A\uFF1B\uFF01\uFF1F\uFF08\uFF09\uFF3B\uFF3D\uFF5B\uFF5D\u201C\u201D\u2018\u2019\u2026\u2014])`,"u"),pr=new RegExp(`(?:\\s|${Bc.source})`,"u"),Dn=new RegExp(`(?:^|${pr.source})`,"u");function bi(e){for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r<32||r>126)return!1}return!0}a(bi,"isPrintableAscii");function Rc(e,t){if(t<=0||e.length===0)return{text:"",width:0};if(bi(e)){let h=e.slice(0,t);return{text:h,width:h.length}}let r=e.includes("\x1B"),i=e.includes(" ");if(!r&&!i){let h="",u=0;for(let{segment:d}of oe.segment(e)){let c=ke(d);if(u+c>t)break;h+=d,u+=c}return{text:h,width:u}}let s="",n=0,o=0,l="";for(;o<e.length;){let h=j(e,o);if(h){l+=h.code,o+=h.length;continue}if(e[o]===" "){if(n+3>t)break;l&&(s+=l,l=""),s+=" ",n+=3,o++;continue}let u=o;for(;u<e.length&&e[u]!==" "&&!j(e,u);)u++;for(let{segment:d}of oe.segment(e.slice(o,u))){let c=ke(d);if(n+c>t)return{text:s,width:n};l&&(s+=l,l=""),s+=d,n+=c}o=u}return{text:s,width:n}}a(Rc,"truncateFragmentToWidth");function yi(e,t,r,i,s,n){let o="\x1B[0m",l=_c(e),h=t+i,u;return r.length>0?u=`${e}${l}${o}${r}${o}`:u=`${e}${l}${o}`,n?u+" ".repeat(Math.max(0,s-h)):u}a(yi,"finalizeTruncatedResult");function ke(e){if(e.length===1){let o=e.charCodeAt(0);if(o>=32&&o<=126)return 1;if(o===9)return 3}if(On.test(e))return[...e].length;if(vc.test(e))return 0;if(kc(e)&&Ac.test(e))return 2;let t=e.replace(Sc,""),r=t.codePointAt(0);if(r===void 0)return 0;if(r>=127462&&r<=127487)return 2;let i=_n(r),s=!1,n=[...t];for(let o of n.slice(1))if(On.test(o))i+=1,s=!1;else if(Tc.test(o))s=!0;else if(!Cc.test(o)){let l=o.codePointAt(0);s||l>=65280&&l<=65519?i+=_n(l):(l===3635||l===3763)&&(i+=1),s=!1}return i}a(ke,"graphemeWidth");function T(e){if(e.length===0)return 0;let t=Pc(e);if(t!==-1)return t;let r=Ft.get(e);if(r!==void 0)return r;let i=e;e.includes(" ")&&(i=i.replace(/\t/g," "));let s=i.indexOf("\x1B");if(s!==-1){let o="",l=0;for(;s!==-1;){let h=Wt(i,s);h>0?(o+=i.slice(l,s),s+=h,l=s):s++,s=i.indexOf("\x1B",s)}i=o+i.slice(l)}let n=0;for(let{segment:o}of oe.segment(i))n+=ke(o);if(Ft.size>=Mc){let o=Ft.keys().next().value;o!==void 0&&Ft.delete(o)}return Ft.set(e,n),n}a(T,"visibleWidth");function fr(e){if(!e.includes("\x1B"))return e;let t="",r=0;for(;r<e.length;){let i=j(e,r);if(i){r+=i.length;continue}t+=e[r],r++}return t}a(fr,"stripTerminalSequences");function wi(e,t){let r=0,i=0;for(;i<e.length;){let s=j(e,i);if(s){i+=s.length;continue}let n=i;for(;n<e.length&&!j(e,n);)n++;for(let{segment:o}of oe.segment(e.slice(i,n))){let l=ke(o);if(l>0&&t>=r&&t<r+l)return{start:r,end:r+l};r+=l}i=n}}a(wi,"getGraphemeCellRange");function Fn(e,t){let r,i=0,s=0;for(;s<e.length;){let n=j(e,s);if(n){let l=/^\x1b\]8;[^;]*;([^\x07\x1b]*)(?:\x07|\x1b\\)$/.exec(n.code);l&&(r=l[1]||void 0),s+=n.length;continue}let o=s;for(;o<e.length&&!j(e,o);)o++;for(let{segment:l}of oe.segment(e.slice(s,o))){let h=l===" "?3:ke(l);if(t>=i&&t<i+h)return r;i+=h}s=o}}a(Fn,"getOsc8LinkAtColumn");var Ec=/[\u0e33\u0eb3]/,Ic=/[\u0e33\u0eb3]/g,Nn=/[\u0000-\u0008\u000b\u000c\u000e-\u001a\u001c-\u001f\u007f-\u009f]/;function Lc(e){let t=e;Ec.test(t)&&(t=t.replace(Ic,n=>n==="\u0E33"?"\u0E4D\u0E32":"\u0ECD\u0EB2"));let r=Nn.test(t);if(!t.includes(" ")&&!r)return t;let i="",s=0;for(;s<t.length;){let n=j(t,s);if(n){i+=n.code,s+=n.length;continue}let o=t[s];o===" "?i+=" ":Nn.test(o)||(i+=o),s++}return i}a(Lc,"normalizeTerminalOutput");function j(e,t){let r=Wt(e,t);return r>0?{code:e.substring(t,t+r),length:r}:null}a(j,"extractAnsiCode");function Pc(e){let t=0,r=0;for(;r<e.length;){let i=e.charCodeAt(r);if(i>=32&&i<=126)t++,r++;else if(i===9)t+=3,r++;else if(i===27){let s=Wt(e,r);if(s===0)return-1;r+=s}else return-1}return t}a(Pc,"asciiVisibleWidth");function Wt(e,t){if(t>=e.length||e.charCodeAt(t)!==27)return 0;let r=e[t+1];if(r==="["){let i=t+2;for(;i<e.length;){let s=e.charCodeAt(i);if(s<64||s>126){i++;continue}return i+1-t}return 0}if(r==="]"||r==="_"){for(let i=t+2;i<e.length;i++){let s=e.charCodeAt(i);if(s===7)return i+1-t;if(s===27&&e[i+1]==="\\")return i+2-t}return 0}return 0}a(Wt,"ansiCodeLength");function Wn(e){if(!e.startsWith("\x1B]8;"))return;let t=e.endsWith("\x07")?"\x07":"\x1B\\",r=e.slice(4,t==="\x07"?-1:-2),i=r.indexOf(";");if(i===-1)return;let s=r.slice(0,i),n=r.slice(i+1);return n?{params:s,url:n,terminator:t}:null}a(Wn,"parseOsc8Hyperlink");function $c(e){return`\x1B]8;${e.params};${e.url}${e.terminator}`}a($c,"formatOsc8Hyperlink");function Hn(e){return`\x1B]8;;${e}`}a(Hn,"formatOsc8Close");function _c(e){if(!e.includes("\x1B]8;"))return"";let t=null,r=0;for(;r<e.length;){let i=j(e,r);if(i){let s=Wn(i.code);s!==void 0&&(t=s),r+=i.length}else r++}return t?Hn(t.terminator):""}a(_c,"getActiveOsc8Close");var gr=class{static{a(this,"AnsiCodeTracker")}bold=!1;dim=!1;italic=!1;underline=!1;blink=!1;inverse=!1;hidden=!1;strikethrough=!1;fgColor=null;bgColor=null;activeHyperlink=null;process(e){let t=Wn(e);if(t!==void 0){this.activeHyperlink=t;return}if(!e.endsWith("m"))return;let r=e.match(/\x1b\[([\d;]*)m/);if(!r)return;let i=r[1];if(i===""||i==="0"){this.reset();return}let s=i.split(";"),n=0;for(;n<s.length;){let o=Number.parseInt(s[n],10);if(o===38||o===48){if(s[n+1]==="5"&&s[n+2]!==void 0){let l=`${s[n]};${s[n+1]};${s[n+2]}`;o===38?this.fgColor=l:this.bgColor=l,n+=3;continue}else if(s[n+1]==="2"&&s[n+4]!==void 0){let l=`${s[n]};${s[n+1]};${s[n+2]};${s[n+3]};${s[n+4]}`;o===38?this.fgColor=l:this.bgColor=l,n+=5;continue}}switch(o){case 0:this.reset();break;case 1:this.bold=!0;break;case 2:this.dim=!0;break;case 3:this.italic=!0;break;case 4:this.underline=!0;break;case 5:this.blink=!0;break;case 7:this.inverse=!0;break;case 8:this.hidden=!0;break;case 9:this.strikethrough=!0;break;case 21:this.bold=!1;break;case 22:this.bold=!1,this.dim=!1;break;case 23:this.italic=!1;break;case 24:this.underline=!1;break;case 25:this.blink=!1;break;case 27:this.inverse=!1;break;case 28:this.hidden=!1;break;case 29:this.strikethrough=!1;break;case 39:this.fgColor=null;break;case 49:this.bgColor=null;break;default:o>=30&&o<=37||o>=90&&o<=97?this.fgColor=String(o):(o>=40&&o<=47||o>=100&&o<=107)&&(this.bgColor=String(o));break}n++}}reset(){this.bold=!1,this.dim=!1,this.italic=!1,this.underline=!1,this.blink=!1,this.inverse=!1,this.hidden=!1,this.strikethrough=!1,this.fgColor=null,this.bgColor=null}clear(){this.reset(),this.activeHyperlink=null}getActiveCodes(){let e=[];this.bold&&e.push("1"),this.dim&&e.push("2"),this.italic&&e.push("3"),this.underline&&e.push("4"),this.blink&&e.push("5"),this.inverse&&e.push("7"),this.hidden&&e.push("8"),this.strikethrough&&e.push("9"),this.fgColor&&e.push(this.fgColor),this.bgColor&&e.push(this.bgColor);let t=e.length>0?`\x1B[${e.join(";")}m`:"";return this.activeHyperlink&&(t+=$c(this.activeHyperlink)),t}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 e="";return this.underline&&(e+="\x1B[24m"),this.activeHyperlink&&(e+=Hn(this.activeHyperlink.terminator)),e}};function ki(e,t){let r=e.indexOf("\x1B");for(;r!==-1;){let i=Wt(e,r);i>0?(t.process(e.substring(r,r+i)),r+=i):r++,r=e.indexOf("\x1B",r)}}a(ki,"updateTrackerFromText");function Oc(e){let t=new gr;return ki(e,t),t.getActiveBackgroundCode()}a(Oc,"getActiveBackgroundAnsi");function*Dc(e){for(let{segment:t}of oe.segment(e))yield t}a(Dc,"graphemeSegments");function Fc(e){let t=[],r="",i="",s=null,n=0,o=a(()=>{r&&(t.push(r),r="",s=null)},"flushCurrent");for(;n<e.length;){let l=j(e,n);if(l){i+=l.code,n+=l.length;continue}let h=e.indexOf("\x1B",n+1);for(;h!==-1&&Wt(e,h)===0;)h=e.indexOf("\x1B",h+1);h===-1&&(h=e.length);let u=e.slice(n,h),d=bi(u);for(let c of d?u:Dc(u)){let p=c===" ";if(!d&&!p&&Nt.test(c)){o();let g=i+c;i="",t.push(g);continue}let f=p?"space":"word";r&&s!==f&&o(),i&&(r+=i,i=""),s=f,r+=c}n=h}return i&&(r?r+=i:t.length>0?t[t.length-1]+=i:r=i),r&&t.push(r),t}a(Fc,"splitIntoTokensWithAnsi");function vi(e){for(let t of e)Number(t)}a(vi,"flattenLines");function ve(e,t){if(!e)return[""];let r=e.split(/\r\n|\r|\n/),i=[],s=new gr;for(let n of r){let o=i.length>0?s.getActiveCodes():"",l=Nc(o+n,t);for(let h of l)i.push(h);ki(n,s)}return i.length>0?i:[""]}a(ve,"wrapTextWithAnsi");function Nc(e,t){if(!e)return[""];if(T(e)<=t)return[e];let r=[],i=new gr,s=Fc(e),n="",o=0;for(let l of s){let h=T(l),u=l.trim()==="";if(h>t&&!u){if(n){let c=i.getLineEndReset();c&&(n+=c),r.push(n),n="",o=0}let d=Wc(l,t,i);for(let c=0;c<d.length-1;c++)r.push(d[c]);n=d[d.length-1],o=T(n);continue}if(o+h>t&&o>0){let d=n.trimEnd(),c=i.getLineEndReset();c&&(d+=c),r.push(d),u?(n=i.getActiveCodes(),o=0):(n=i.getActiveCodes()+l,o=h)}else n+=l,o+=h;ki(l,i)}return n&&r.push(n),r.length>0?r.map(l=>l.trimEnd()):[""]}a(Nc,"wrapSingleLine");var Vn=/[(){}[\]<>.,;:'"!?+\-=*/\\|&%^$#@~`]/;function xe(e){return/\s/.test(e)}a(xe,"isWhitespaceChar");function Wc(e,t,r){let i=[],s=r.getActiveCodes(),n=0,o=0,l=[];for(;o<e.length;){let h=j(e,o);if(h)l.push({type:"ansi",value:h.code}),o+=h.length;else{let u=o;for(;u<e.length&&!j(e,u);)u++;let d=e.slice(o,u);for(let c of oe.segment(d))l.push({type:"grapheme",value:c.segment});o=u}}for(let h of l){if(h.type==="ansi"){s+=h.value,r.process(h.value);continue}let u=h.value;if(!u)continue;let d=T(u);if(n+d>t){let c=r.getLineEndReset();c&&(s+=c),i.push(s),s=r.getActiveCodes(),n=0}s+=u,n+=d}return s&&i.push(s),i.length>0?i:[""]}a(Wc,"breakLongWord");function mr(e,t,r){let i=T(e),s=Math.max(0,t-i),n=" ".repeat(s),o=e+n;return r(o)}a(mr,"applyBackgroundToLine");function K(e,t,r="...",i=!1){if(t<=0)return"";if(e.length===0)return i?" ".repeat(t):"";let s=T(r);if(s>=t){let x=T(e);if(x<=t)return i?e+" ".repeat(t-x):e;let m=Rc(r,t);return m.width===0?i?" ".repeat(t):"":yi("",0,m.text,m.width,t,i)}if(bi(e)){if(e.length<=t)return i?e+" ".repeat(t-e.length):e;let x=t-s;return yi(e.slice(0,x),x,r,s,t,i)}let n=t-s,o="",l="",h=0,u=0,d=!0,c=!1,p=!1,f=e.includes("\x1B"),g=e.includes(" ");if(!f&&!g){for(let{segment:x}of oe.segment(e)){let m=ke(x);if(d&&u+m<=n?(o+=x,u+=m):d=!1,h+=m,h>t){c=!0;break}}p=!c}else{let x=0;for(;x<e.length;){let m=j(e,x);if(m){l+=m.code,x+=m.length;continue}if(e[x]===" "){if(d&&u+3<=n?(l&&(o+=l,l=""),o+=" ",u+=3):(d=!1,l=""),h+=3,h>t){c=!0;break}x++;continue}let b=x;for(;b<e.length&&e[b]!==" "&&!j(e,b);)b++;for(let{segment:C}of oe.segment(e.slice(x,b))){let S=ke(C);if(d&&u+S<=n?(l&&(o+=l,l=""),o+=C,u+=S):(d=!1,l=""),h+=S,h>t){c=!0;break}}if(c)break;x=b}p=x>=e.length}return!c&&p?i?e+" ".repeat(Math.max(0,t-h)):e:yi(o,u,r,s,t,i)}a(K,"truncateToWidth");function Y(e,t,r,i=!1){return qn(e,t,r,i).text}a(Y,"sliceByColumn");function qn(e,t,r,i=!1){if(r<=0)return{text:"",width:0};let s=t+r,n="",o=0,l=0,h=0,u="";for(;h<e.length;){let d=j(e,h);if(d){l>=t&&l<s?(n+=u+d.code,u=""):l<t&&(u+=d.code),h+=d.length;continue}let c=h;for(;c<e.length&&!j(e,c);)c++;for(let{segment:p}of oe.segment(e.slice(h,c))){let f=ke(p),g=l>=t&&l<s,x=!i||l+f<=s;if(g&&x&&(u&&(n+=u,u=""),n+=p,o+=f),l+=f,l>=s)break}if(h=c,l>=s)break}return{text:n,width:o}}a(qn,"sliceWithWidth");var Si=new gr;function Hc(e,t,r,i,s=!1){let n="",o=0,l="",h=0,u=0,d=0,c="",p=!1,f=r+i;for(Si.clear();d<e.length;){let g=j(e,d);if(g){Si.process(g.code),u<t?c+=g.code:u>=r&&u<f&&(p||g.code.startsWith("\x1B_"))&&(l+=g.code),d+=g.length;continue}let x=d;for(;x<e.length&&!j(e,x);)x++;for(let{segment:m}of oe.segment(e.slice(d,x))){let b=ke(m);if(u<t&&u+b<=t?(c&&(n+=c,c=""),n+=m,o+=b):u>=r&&u<f&&(!s||u+b<=f)&&(p||(l+=Si.getActiveCodes(),p=!0),l+=m,h+=b),u+=b,i<=0?u>=t:u>=f)break}if(d=x,i<=0?u>=t:u>=f)break}return{before:n,beforeWidth:o,after:l,afterWidth:h}}a(Hc,"extractSegments");var xr=a((e,[t,r,i])=>e.map(s=>s[0]*t+s[1]*r+s[2]*i),"multiply"),Vc=[[.4122214694707629,.5363325372617349,.0514459932675022],[.2119034958178251,.6806995506452344,.1073969535369405],[.0883024591900564,.2817188391361215,.6299787016738222]],qc=[[.210454268309314,.793617774702305,-.0040720430116193],[1.9779985324311684,-2.42859224204858,.450593709617411],[.0259040424655478,.7827717124575296,-.8086757549230774]],br=[[1,.3963377773761749,.2158037573099136],[1,-.1055613458156586,-.0638541728258133],[1,-.0894841775298119,-1.2914855480194092]],Ci=[[4.076741636075958,-3.307711539258063,.2309699031821043],[-1.2684379732850315,2.609757349287688,-.341319376002657],[-.0041960761386756,-.7034186179359362,1.7076146940746117]],Kn=[[[-1.8817031,-.80936501],[1.19086277,1.76576728,.59662641,.75515197,.56771245]],[[1.8144408,-1.19445267],[.73956515,-.45954404,.08285427,.12541073,-.14503204]],[[.13110758,1.81333971],[1.35733652,-.00915799,-1.1513021,-.50559606,.00692167]]],yr=.206,Ti=.03,wr=(1+yr)/(1+Ti),kr=a(e=>.5*(wr*e-yr+Math.sqrt((wr*e-yr)**2+4*Ti*wr*e)),"oklabToOkhslLightness"),Kc=a(e=>(e*e+yr*e)/(wr*(e+Ti)),"okhslToOklabLightness"),Uc=a(e=>e>.0031308?1.055*e**(1/2.4)-.055:12.92*e,"linearToSrgb"),jc=a(e=>e<=.04045?e/12.92:((e+.055)/1.055)**2.4,"srgbToLinear");function Ai(e){return xr(Ci,xr(br,e).map(t=>t**3))}a(Ai,"oklabToLinearSrgb");function zc(e){return xr(qc,xr(Vc,e).map(Math.cbrt))}a(zc,"linearSrgbToOklab");function Un({r:e,g:t,b:r}){return zc([e/255,t/255,r/255].map(jc))}a(Un,"rgbToOklab");function Mi(e){let[t,r,i]=e.map(s=>Math.round(Math.min(1,Math.max(0,Uc(s)))*255));return{r:t,g:r,b:i}}a(Mi,"linearSrgbToRgb");function jn(e,t){return[br[0],br[1],br[2]].map(r=>r[1]*e+r[2]*t)}a(jn,"lmsSlopes");function Gc(e,t){let r=Kn.findIndex(([[m,b]],C)=>C===2||m*e+b*t>1),[i,s,n,o,l]=Kn[r][1],h=Ci[r],u=i+s*e+n*t+o*e*e+l*e*t,d=jn(e,t),c=d.map(m=>1+u*m),p=a(m=>m.reduce((b,C,S)=>b+h[S]*C,0),"dot"),f=p(c.map(m=>m**3)),g=p(c.map((m,b)=>3*d[b]*m**2)),x=p(c.map((m,b)=>6*d[b]**2*m));return u-f*g/(g*g-.5*f*x)}a(Gc,"maxSaturation");function Yc(e,t){let r=Gc(e,t),i=Math.cbrt(1/Math.max(...Ai([1,r*e,r*t])));return[i,i*r]}a(Yc,"cusp");function Xc(e,t,r,[i,s]){if(r<=i)return s*r/i;let n=s*(r-1)/(i-1),o=jn(e,t),l=o.map(f=>r+n*f),h=l.map(f=>f**3),u=l.map((f,g)=>3*o[g]*f**2),d=l.map((f,g)=>6*o[g]**2*f),c=a((f,g)=>f[0]*g[0]+f[1]*g[1]+f[2]*g[2],"dot"),p=Ci.map(f=>{let g=c(f,h)-1,x=c(f,u),m=c(f,d),b=x/(x*x-.5*g*m);return b>=0?-g*b:Number.MAX_VALUE});return n+Math.min(...p)}a(Xc,"maxChroma");function zn(e,t,r){let i=Yc(t,r),s=Xc(t,r,e,i),n=s/Math.min(e*(i[1]/i[0]),(1-e)*(i[1]/(1-i[0]))),o=.11516993+1/(7.4477897+4.1590124*r+t*(-2.19557347+1.75198401*r+t*(-2.13704948-10.02301043*r+t*(-4.24894561+5.38770819*r+4.69891013*t)))),l=.11239642+1/(1.6132032-.68124379*r+t*(.40370612+.90148123*r+t*(-.27087943+.6122399*r+t*(.00299215-.45399568*r-.14661872*t)))),h=.9*n*Math.sqrt(Math.sqrt(1/(1/(e*o)**4+1/((1-e)*l)**4)));return[Math.sqrt(1/(1/(e*.4)**2+1/((1-e)*.8)**2)),h,s]}a(zn,"chromaStops");function Qc(e,t,r){let i=Kc(r),s=[i,0,0];if(i>0&&i<1&&t>0){let n=2*Math.PI*((e%360+360)%360)/360,o=Math.cos(n),l=Math.sin(n),[h,u,d]=zn(i,o,l),c;if(t<.8){let p=1.25*t,f=.8*h;c=p*f/(1-(1-f/u)*p)}else{let p=5*(t-.8),f=.2*u**2*1.25**2/h;c=u+p*f/(1-(1-f/(d-u))*p)}s=[i,c*o,c*l]}return Mi(Ai(s))}a(Qc,"okhslToRgb");function Zc(e){let[t,r,i]=Un(e),s=Math.hypot(r,i),n=kr(t);if(s<1e-9||n<=0||n>=1)return{h:0,s:0,l:n};let o=(Math.atan2(i,r)*180/Math.PI+360)%360,[l,h,u]=zn(t,r/s,i/s),d;if(s<h){let c=.8*l;d=.8*(s/(c+(1-c/h)*s))}else{let c=.2*h**2*1.5625/l,p=s-h;d=.8+.2*(p/(c+(1-c/(u-h))*p))}return{h:o,s:Math.min(1,Math.max(0,d)),l:n}}a(Zc,"rgbToOkhsl");function Le(e,t){if(!Number.isFinite(e))throw new Error(`${t} must be finite`)}a(Le,"requireFinite");function vr(e){if(!Number.isInteger(e)||e<0||e>255)throw new Error(`ANSI color index must be an integer from 0 to 255: ${e}`);return Object.freeze({kind:"indexed",index:e})}a(vr,"indexedColor");function Se(e,t,r){for(let[i,s]of[["r",e],["g",t],["b",r]])if(Le(s,i),s<0||s>255)throw new Error(`${i} must be between 0 and 255: ${s}`);return Object.freeze({kind:"rgb",r:e,g:t,b:r})}a(Se,"rgbColor");function Sr(e,t,r){if(Le(e,"l"),Le(t,"c"),Le(r,"h"),e<0||e>1)throw new Error(`l must be between 0 and 1: ${e}`);if(t<0)throw new Error(`c must not be negative: ${t}`);return Object.freeze({kind:"oklch",l:e,c:t,h:(r%360+360)%360})}a(Sr,"oklchColor");var ut=String.raw`[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?`,Jc=new RegExp(`^oklch\\(\\s*(${ut})(%)?\\s+(${ut})\\s+(${ut})(?:deg)?\\s*\\)$`,"i"),ed=new RegExp(`^okhsl\\(\\s*(${ut})(?:deg)?\\s+(${ut})(%)?\\s+(${ut})(%)?\\s*\\)$`,"i");function Ht(e,t,r){if(Le(e,"h"),Le(t,"s"),Le(r,"l"),t<0||t>1)throw new Error(`s must be between 0 and 1: ${t}`);if(r<0||r>1)throw new Error(`l must be between 0 and 1: ${r}`);let{r:i,g:s,b:n}=Qc(e,t,r);return Se(i,s,n)}a(Ht,"okhslColor");function Gn(e){return Zc(Te(e))}a(Gn,"colorToOkhsl");function Pe(e){if(typeof e=="number")return vr(e);let t=/^#([\da-f]{3}|[\da-f]{6})$/i.exec(e);if(t){let s=t[1].length===3?[...t[1]].map(n=>n+n).join(""):t[1];return Se(Number.parseInt(s.slice(0,2),16),Number.parseInt(s.slice(2,4),16),Number.parseInt(s.slice(4,6),16))}let r=Jc.exec(e);if(r){let s=Number.parseFloat(r[1])/(r[2]?100:1);return Sr(s,Number.parseFloat(r[3]),Number.parseFloat(r[4]))}let i=ed.exec(e);if(i){let s=Number.parseFloat(i[2])/(i[3]?100:1),n=Number.parseFloat(i[4])/(i[5]?100:1);return Ht(Number.parseFloat(i[1]),s,n)}throw new Error(`Invalid color value: ${e}`)}a(Pe,"parseColor");var td=[{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],Yn=Array.from({length:24},(e,t)=>8+t*10);function rd(e){if(e<16)return{...td[e]};if(e<232){let r=e-16;return{r:Ce[Math.floor(r/36)],g:Ce[Math.floor(r%36/6)],b:Ce[r%6]}}let t=8+(e-232)*10;return{r:t,g:t,b:t}}a(rd,"indexedToRgb");function Xn(e){return e.every(t=>t>=-1e-7&&t<=1+1e-7)}a(Xn,"isInSrgbGamut");function id({l:e,c:t,h:r}){let i=r*Math.PI/180,s=Math.cos(i),n=Math.sin(i),o=a(c=>Ai([e,c*s,c*n]),"atChroma"),l=o(t);if(Xn(l))return Mi(l);let h=o(0),u=0,d=t;for(let c=0;c<20;c++){let p=(u+d)/2,f=o(p);Xn(f)?(u=p,h=f):d=p}return Mi(h)}a(id,"oklchToRgb");function Te(e){switch(e.kind){case"indexed":return rd(e.index);case"rgb":return{r:e.r,g:e.g,b:e.b};case"oklch":return id(e)}}a(Te,"colorToRgb");function Ue(e){if(e.kind==="oklch")return{l:e.l,c:e.c,h:e.h};let[t,r,i]=Un(Te(e));return{l:t,c:Math.hypot(r,i),h:(Math.atan2(i,r)*180/Math.PI+360)%360}}a(Ue,"colorToOklch");function Cr(e){let{r:t,g:r,b:i}=Te(e),s=a(n=>Math.round(n).toString(16).padStart(2,"0"),"channel");return`#${s(t)}${s(r)}${s(i)}`}a(Cr,"colorToHex");function Bi(e,t,r,i="oklch"){if(Le(r,"amount"),r<0||r>1)throw new Error(`amount must be between 0 and 1: ${r}`);if(i==="srgb"){let h=Te(e),u=Te(t);return Se(h.r+(u.r-h.r)*r,h.g+(u.g-h.g)*r,h.b+(u.b-h.b)*r)}let s=Ue(e),n=Ue(t),o=s.c<1e-7?n.h:s.h,l=((n.c<1e-7?o:n.h)-o+540)%360-180;return Sr(s.l+(n.l-s.l)*r,s.c+(n.c-s.c)*r,o+l*r)}a(Bi,"mixColors");function Tr(e,t){let r=0,i=1/0;for(let s=0;s<e.length;s++){let n=Math.abs(t-e[s]);n<i&&(r=s,i=n)}return r}a(Tr,"findClosest");function Qn(e,t){let r=e.r-t.r,i=e.g-t.g,s=e.b-t.b;return r*r*.299+i*i*.587+s*s*.114}a(Qn,"colorDistance");function sd(e){let t=Tr(Ce,e.r),r=Tr(Ce,e.g),i=Tr(Ce,e.b),s={r:Ce[t],g:Ce[r],b:Ce[i]},n=16+36*t+6*r+i,o=Math.round(.299*e.r+.587*e.g+.114*e.b),l=Tr(Yn,o),h=Yn[l];return Math.max(e.r,e.g,e.b)-Math.min(e.r,e.g,e.b)<10&&Qn(e,{r:h,g:h,b:h})<Qn(e,s)?232+l:n}a(sd,"rgbToAnsi256");function Zn(e,t,r){if(e.kind==="indexed")return`\x1B[${r?48:38};5;${e.index}m`;let i=Te(e);return t==="truecolor"?`\x1B[${r?48:38};2;${Math.round(i.r)};${Math.round(i.g)};${Math.round(i.b)}m`:`\x1B[${r?48:38};5;${sd(i)}m`}a(Zn,"colorAnsi");function Vt(e,t){return Zn(e,t,!1)}a(Vt,"foregroundAnsi");function qt(e,t){return Zn(e,t,!0)}a(qt,"backgroundAnsi");function nd(e,t,r){return Ri(e,t.fg&&Vt(t.fg,r),t.bg&&qt(t.bg,r),t)}a(nd,"styleText");function Ri(e,t,r,i){let s="",n="";return t&&(s+=t,n="\x1B[39m"),r&&(s+=r,n=`\x1B[49m${n}`),i.bold&&(s+="\x1B[1m"),i.dim&&(s+="\x1B[2m"),(i.bold||i.dim)&&(n=`\x1B[22m${n}`),i.italic&&(s+="\x1B[3m",n=`\x1B[23m${n}`),i.underline&&(s+="\x1B[4m",n=`\x1B[24m${n}`),i.inverse&&(s+="\x1B[7m",n=`\x1B[27m${n}`),i.strikethrough&&(s+="\x1B[9m",n=`\x1B[29m${n}`),`${s}${e}${n}`}a(Ri,"styleTextWithAnsi");var Q=!1;function Ar(e){Q=e}a(Ar,"setKittyProtocolActive");function od(){return Q}a(od,"isKittyProtocolActive");var Jn={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:a(e=>`ctrl+${e}`,"ctrl"),shift:a(e=>`shift+${e}`,"shift"),alt:a(e=>`alt+${e}`,"alt"),super:a(e=>`super+${e}`,"super"),ctrlShift:a(e=>`ctrl+shift+${e}`,"ctrlShift"),shiftCtrl:a(e=>`shift+ctrl+${e}`,"shiftCtrl"),ctrlAlt:a(e=>`ctrl+alt+${e}`,"ctrlAlt"),altCtrl:a(e=>`alt+ctrl+${e}`,"altCtrl"),shiftAlt:a(e=>`shift+alt+${e}`,"shiftAlt"),altShift:a(e=>`alt+shift+${e}`,"altShift"),ctrlSuper:a(e=>`ctrl+super+${e}`,"ctrlSuper"),superCtrl:a(e=>`super+ctrl+${e}`,"superCtrl"),shiftSuper:a(e=>`shift+super+${e}`,"shiftSuper"),superShift:a(e=>`super+shift+${e}`,"superShift"),altSuper:a(e=>`alt+super+${e}`,"altSuper"),superAlt:a(e=>`super+alt+${e}`,"superAlt"),ctrlShiftAlt:a(e=>`ctrl+shift+alt+${e}`,"ctrlShiftAlt"),ctrlShiftSuper:a(e=>`ctrl+shift+super+${e}`,"ctrlShiftSuper")},$e=new Set(["`","-","=","[","]","\\",";","'",",",".","/","!","@","#","$","%","^","&","*","(",")","_","+","|","~","{","}",":","<",">","?"]),eo=new Set("~!@#$%^&*()_+|{}:<>?"),ld=["shift","alt","ctrl","super"],R={shift:1,alt:2,ctrl:4,super:8},je=192,_={escape:27,tab:9,enter:13,space:32,backspace:127,kpEnter:57414},U={up:-1,down:-2,right:-3,left:-4},F={delete:-10,insert:-11,pageUp:-12,pageDown:-13,home:-14,end:-15},ad=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,U.left],[57418,U.right],[57419,U.up],[57420,U.down],[57421,F.pageUp],[57422,F.pageDown],[57423,F.home],[57424,F.end],[57425,F.insert],[57426,F.delete]]);function ct(e){return ad.get(e)??e}a(ct,"normalizeKittyFunctionalCodepoint");function Kt(e,t){return(t&~je&R.shift)!==0&&e>=65&&e<=90?e+32:e}a(Kt,"normalizeShiftedLetterIdentityCodepoint");function Mr(e,t,r){if(e===void 0||(t&R.shift)===0)return;let i=ct(e);if(r.has(String.fromCharCode(i)))return{codepoint:i,modifier:t&~R.shift}}a(Mr,"getLogicalShiftedSymbolCandidate");var le={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~"]},hd={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$"]},ud={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^"]},cd={"\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"},te=a((e,t)=>t.includes(e),"matchesLegacySequence"),se=a((e,t,r)=>r===R.shift?te(e,hd[t]):r===R.ctrl?te(e,ud[t]):!1,"matchesLegacyModifierSequence"),Br="press";function Ei(e){return e.includes("\x1B[200~")?!1:!!(e.includes(":3u")||e.includes(":3~")||e.includes(":3A")||e.includes(":3B")||e.includes(":3C")||e.includes(":3D")||e.includes(":3H")||e.includes(":3F"))}a(Ei,"isKeyRelease");function dd(e){return e.includes("\x1B[200~")?!1:!!(e.includes(":2u")||e.includes(":2~")||e.includes(":2A")||e.includes(":2B")||e.includes(":2C")||e.includes(":2D")||e.includes(":2H")||e.includes(":2F"))}a(dd,"isKeyRepeat");function Rr(e){if(!e)return"press";let t=parseInt(e,10);return t===2?"repeat":t===3?"release":"press"}a(Rr,"parseEventType");function to(e){let t=e.match(/^\x1b\[(\d+)(?::(\d*))?(?::(\d+))?(?:;(\d+))?(?::(\d+))?u$/);if(t){let n=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,h=t[4]?parseInt(t[4],10):1,u=Rr(t[5]);return Br=u,{codepoint:n,shiftedKey:o,baseLayoutKey:l,modifier:h-1,eventType:u}}let r=e.match(/^\x1b\[1;(\d+)(?::(\d+))?([ABCD])$/);if(r){let n=parseInt(r[1],10),o=Rr(r[2]),l={A:-1,B:-2,C:-3,D:-4};return Br=o,{codepoint:l[r[3]],modifier:n-1,eventType:o}}let i=e.match(/^\x1b\[(\d+)(?:;(\d+))?(?::(\d+))?~$/);if(i){let n=parseInt(i[1],10),o=i[2]?parseInt(i[2],10):1,l=Rr(i[3]),h={2:F.insert,3:F.delete,5:F.pageUp,6:F.pageDown,7:F.home,8:F.end}[n];if(h!==void 0)return Br=l,{codepoint:h,modifier:o-1,eventType:l}}let s=e.match(/^\x1b\[1;(\d+)(?::(\d+))?([HF])$/);if(s){let n=parseInt(s[1],10),o=Rr(s[2]),l=s[3]==="H"?F.home:F.end;return Br=o,{codepoint:l,modifier:n-1,eventType:o}}return null}a(to,"parseKittySequence");function E(e,t,r){let i=to(e);if(!i)return!1;let s=i.modifier&~je,n=r&~je,o=Kt(ct(i.codepoint),i.modifier),l=Kt(ct(t),r);if(s===n&&o===l)return!0;let h=Mr(i.shiftedKey,s,$e);if(h&&(h.modifier&~je)===n&&h.codepoint===ct(t))return!0;if(s!==n)return!1;if(i.baseLayoutKey!==void 0&&i.baseLayoutKey===t){let u=o,d=u>=97&&u<=122,c=$e.has(String.fromCharCode(u));if(!d&&!c)return!0}return!1}a(E,"matchesKittySequence");function Er(e){let t=e.match(/^\x1b\[27;(\d+);(\d+)~$/);if(!t)return null;let r=parseInt(t[1],10);return{codepoint:parseInt(t[2],10),modifier:r-1}}a(Er,"parseModifyOtherKeysSequence");function ae(e,t,r){let i=Er(e);return i?i.codepoint===t&&i.modifier===r:!1}a(ae,"matchesModifyOtherKeys");function ro(){return!!process.env.WT_SESSION&&!process.env.SSH_CONNECTION&&!process.env.SSH_CLIENT&&!process.env.SSH_TTY}a(ro,"isWindowsTerminalSession");function io(e,t){return e==="\x7F"?t===0:e!=="\b"?!1:ro()?t===R.ctrl:t===0}a(io,"matchesRawBackspace");function pd(e){let t=e.toLowerCase(),r=t.charCodeAt(0);return r>=97&&r<=122||t==="["||t==="\\"||t==="]"||t==="_"?String.fromCharCode(r&31):t==="-"?"":null}a(pd,"rawCtrlChar");function so(e){return e>="0"&&e<="9"}a(so,"isDigitKey");function Ut(e,t,r){let i=Er(e);if(!i)return!1;if(i.modifier===r&&Kt(i.codepoint,i.modifier)===Kt(t,r))return!0;let s=Mr(i.codepoint,i.modifier,eo);return s?.modifier===r&&s.codepoint===t}a(Ut,"matchesPrintableModifyOtherKeys");function fd(e,t){let r=[],i=t&~je,s=R.shift|R.ctrl|R.alt|R.super;if((i&~s)===0)return i&R.shift&&r.push("shift"),i&R.ctrl&&r.push("ctrl"),i&R.alt&&r.push("alt"),i&R.super&&r.push("super"),r.length>0?`${r.join("+")}+${e}`:e}a(fd,"formatKeyNameWithModifiers");function gd(e){let t=e.toLowerCase(),r=new Set;for(;;){let i=ld.find(s=>t.startsWith(`${s}+`));if(!i)break;if(r.has(i))return null;r.add(i),t=t.slice(i.length+1)}return!t||t.includes("+")&&t!=="+"?null:{key:t,ctrl:r.has("ctrl"),shift:r.has("shift"),alt:r.has("alt"),super:r.has("super")}}a(gd,"parseKeyId");function _e(e,t){let r=gd(t);if(!r)return!1;let{key:i,ctrl:s,shift:n,alt:o,super:l}=r,h=0;switch(n&&(h|=R.shift),o&&(h|=R.alt),s&&(h|=R.ctrl),l&&(h|=R.super),i){case"escape":case"esc":return h!==0?!1:e==="\x1B"||E(e,_.escape,0)||ae(e,_.escape,0);case"space":return!Q&&(h===R.ctrl&&e==="\0"||h===R.alt&&e==="\x1B ")?!0:h===0?e===" "||E(e,_.space,0)||ae(e,_.space,0):E(e,_.space,h)||ae(e,_.space,h);case"tab":return h===R.shift?e==="\x1B[Z"||E(e,_.tab,R.shift)||ae(e,_.tab,R.shift):h===0?e===" "||E(e,_.tab,0):E(e,_.tab,h)||ae(e,_.tab,h);case"enter":case"return":return h===R.shift?E(e,_.enter,R.shift)||E(e,_.kpEnter,R.shift)||ae(e,_.enter,R.shift)?!0:Q?e==="\x1B\r"||e===`
|
|
6
|
-
`:!1:h===R.alt?E(e,_.enter,R.alt)||E(e,_.kpEnter,R.alt)||ae(e,_.enter,R.alt)?!0:Q?!1:e==="\x1B\r":h===0?e==="\r"||!Q&&e===`
|
|
7
|
-
`||e==="\x1BOM"||E(e,_.enter,0)||E(e,_.kpEnter,0):E(e,_.enter,h)||E(e,_.kpEnter,h)||ae(e,_.enter,h);case"backspace":return h===R.alt?e==="\x1B\x7F"||e==="\x1B\b"?!0:E(e,_.backspace,R.alt)||ae(e,_.backspace,R.alt):h===R.ctrl?io(e,R.ctrl)?!0:E(e,_.backspace,R.ctrl)||ae(e,_.backspace,R.ctrl):h===0?io(e,0)||E(e,_.backspace,0)||ae(e,_.backspace,0):E(e,_.backspace,h)||ae(e,_.backspace,h);case"insert":return h===0?te(e,le.insert)||E(e,F.insert,0):se(e,"insert",h)?!0:E(e,F.insert,h);case"delete":return h===0?te(e,le.delete)||E(e,F.delete,0):se(e,"delete",h)?!0:E(e,F.delete,h);case"clear":return h===0?te(e,le.clear):se(e,"clear",h);case"home":return h===0?te(e,le.home)||E(e,F.home,0):se(e,"home",h)?!0:E(e,F.home,h);case"end":return h===0?te(e,le.end)||E(e,F.end,0):se(e,"end",h)?!0:E(e,F.end,h);case"pageup":return h===0?te(e,le.pageUp)||E(e,F.pageUp,0):se(e,"pageUp",h)?!0:E(e,F.pageUp,h);case"pagedown":return h===0?te(e,le.pageDown)||E(e,F.pageDown,0):se(e,"pageDown",h)?!0:E(e,F.pageDown,h);case"up":return h===R.alt?e==="\x1Bp"||E(e,U.up,R.alt):h===0?te(e,le.up)||E(e,U.up,0):se(e,"up",h)?!0:E(e,U.up,h);case"down":return h===R.alt?e==="\x1Bn"||E(e,U.down,R.alt):h===0?te(e,le.down)||E(e,U.down,0):se(e,"down",h)?!0:E(e,U.down,h);case"left":return h===R.alt?e==="\x1B[1;3D"||!Q&&e==="\x1BB"||e==="\x1Bb"||E(e,U.left,R.alt):h===R.ctrl?e==="\x1B[1;5D"||se(e,"left",R.ctrl)||E(e,U.left,R.ctrl):h===0?te(e,le.left)||E(e,U.left,0):se(e,"left",h)?!0:E(e,U.left,h);case"right":return h===R.alt?e==="\x1B[1;3C"||!Q&&e==="\x1BF"||e==="\x1Bf"||E(e,U.right,R.alt):h===R.ctrl?e==="\x1B[1;5C"||se(e,"right",R.ctrl)||E(e,U.right,R.ctrl):h===0?te(e,le.right)||E(e,U.right,0):se(e,"right",h)?!0:E(e,U.right,h);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 h!==0?!1:te(e,le[i])}if(i.length===1&&(i>="a"&&i<="z"||so(i)||$e.has(i))){let u=i.charCodeAt(0),d=pd(i),c=i>="a"&&i<="z",p=so(i);return h===R.ctrl+R.alt&&!Q&&d&&e===`\x1B${d}`||h===R.alt&&!Q&&(c||p||$e.has(i))&&e===`\x1B${i}`?!0:h===R.ctrl?d&&e===d?!0:E(e,u,R.ctrl)||Ut(e,u,R.ctrl):h===R.shift+R.ctrl?E(e,u,R.shift+R.ctrl)||Ut(e,u,R.shift+R.ctrl):h===R.shift?c&&e===i.toUpperCase()?!0:E(e,u,R.shift)||Ut(e,u,R.shift):h!==0?E(e,u,h)||Ut(e,u,h):e===i||E(e,u,0)||Ut(e,u,0)}return!1}a(_e,"matchesKey");function no(e,t,r){let i=ct(e),s=Kt(i,t),n=s>=97&&s<=122,o=s>=48&&s<=57,l=$e.has(String.fromCharCode(s)),h=n||o||l?s:r??s,u;if(h===_.escape?u="escape":h===_.tab?u="tab":h===_.enter||h===_.kpEnter?u="enter":h===_.space?u="space":h===_.backspace?u="backspace":h===F.delete?u="delete":h===F.insert?u="insert":h===F.home?u="home":h===F.end?u="end":h===F.pageUp?u="pageUp":h===F.pageDown?u="pageDown":h===U.up?u="up":h===U.down?u="down":h===U.left?u="left":h===U.right?u="right":(h>=48&&h<=57||h>=97&&h<=122||$e.has(String.fromCharCode(h)))&&(u=String.fromCharCode(h)),!!u)return fd(u,t)}a(no,"formatParsedKey");function md(e){let t=to(e);if(t){let s=Mr(t.shiftedKey,t.modifier,$e);return no(s?.codepoint??t.codepoint,s?.modifier??t.modifier,t.baseLayoutKey)}let r=Er(e);if(r){let s=Mr(r.codepoint,r.modifier,eo);return no(s?.codepoint??r.codepoint,s?.modifier??r.modifier)}if(Q&&(e==="\x1B\r"||e===`
|
|
8
|
-
`))return"shift+enter";let i=cd[e];if(i)return i;if(e==="\x1B")return"escape";if(e==="")return"ctrl+\\";if(e==="")return"ctrl+]";if(e==="")return"ctrl+-";if(e==="\x1B\x1B")return"ctrl+alt+[";if(e==="\x1B")return"ctrl+alt+\\";if(e==="\x1B")return"ctrl+alt+]";if(e==="\x1B")return"ctrl+alt+-";if(e===" ")return"tab";if(e==="\r"||!Q&&e===`
|
|
9
|
-
`||e==="\x1BOM")return"enter";if(e==="\0")return"ctrl+space";if(e===" ")return"space";if(e==="\x7F")return"backspace";if(e==="\b")return ro()?"ctrl+backspace":"backspace";if(e==="\x1B[Z")return"shift+tab";if(!Q&&e==="\x1B\r")return"alt+enter";if(!Q&&e==="\x1B ")return"alt+space";if(e==="\x1B\x7F"||e==="\x1B\b")return"alt+backspace";if(!Q&&e==="\x1BB")return"alt+left";if(!Q&&e==="\x1BF")return"alt+right";if(!Q&&e.length===2&&e[0]==="\x1B"){let s=e.charCodeAt(1);if(s>=1&&s<=26)return`ctrl+alt+${String.fromCharCode(s+96)}`;let n=String.fromCharCode(s);if(s>=97&&s<=122||s>=48&&s<=57||$e.has(n))return`alt+${n}`}if(e==="\x1B[A")return"up";if(e==="\x1B[B")return"down";if(e==="\x1B[C")return"right";if(e==="\x1B[D")return"left";if(e==="\x1B[H"||e==="\x1BOH")return"home";if(e==="\x1B[F"||e==="\x1BOF")return"end";if(e==="\x1B[3~")return"delete";if(e==="\x1B[5~")return"pageUp";if(e==="\x1B[6~")return"pageDown";if(e.length===1){let s=e.charCodeAt(0);if(s>=1&&s<=26)return`ctrl+${String.fromCharCode(s+96)}`;if(s>=32&&s<=126)return e}}a(md,"parseKey");var xd=/^\x1b\[(\d+)(?::(\d*))?(?::(\d+))?(?:;(\d+))?(?::(\d+))?u$/,bd=R.shift|je;function Ii(e){let t=e.match(xd);if(!t)return;let r=Number.parseInt(t[1]??"",10);if(!Number.isFinite(r))return;let i=t[2]&&t[2].length>0?Number.parseInt(t[2],10):void 0,s=t[4]?Number.parseInt(t[4],10):1,n=Number.isFinite(s)?s-1:0;if((n&~bd)!==0||n&(R.alt|R.ctrl))return;let o=r;if(n&R.shift&&typeof i=="number"&&(o=i),o=ct(o),!(!Number.isFinite(o)||o<32))try{return String.fromCodePoint(o)}catch{return}}a(Ii,"decodeKittyPrintable");function yd(e){let t=Er(e);if(!(!t||(t.modifier&~je&~R.shift)!==0)&&!(!Number.isFinite(t.codepoint)||t.codepoint<32))try{return String.fromCodePoint(t.codepoint)}catch{return}}a(yd,"decodeModifyOtherKeysPrintable");function oo(e){return Ii(e)??yd(e)}a(oo,"decodePrintableKey");var Li={"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 lo(e){if(e===void 0)return[];let t=Array.isArray(e)?e:[e],r=new Set,i=[];for(let s of t)r.has(s)||(r.add(s),i.push(s));return i}a(lo,"normalizeKeys");var Pi=class{static{a(this,"KeybindingsManager")}definitions;userBindings;keysById=new Map;conflicts=[];constructor(e,t={}){this.definitions=e,this.userBindings=t,this.rebuild()}rebuild(){this.keysById.clear(),this.conflicts=[];let e=new Map;for(let[t,r]of Object.entries(this.userBindings))if(t in this.definitions)for(let i of lo(r)){let s=e.get(i)??new Set;s.add(t),e.set(i,s)}for(let[t,r]of e)r.size>1&&this.conflicts.push({key:t,keybindings:[...r]});for(let[t,r]of Object.entries(this.definitions)){let i=this.userBindings[t],s=lo(i===void 0?r.defaultKeys:i);this.keysById.set(t,s)}}matches(e,t){let r=this.keysById.get(t)??[];for(let i of r)if(_e(e,i))return!0;return!1}getKeys(e){return[...this.keysById.get(e)??[]]}getDefinition(e){return this.definitions[e]}getConflicts(){return this.conflicts.map(e=>({...e,keybindings:[...e.keybindings]}))}setUserBindings(e){this.userBindings=e,this.rebuild()}getUserBindings(){return{...this.userBindings}}getResolvedBindings(){let e={};for(let t of Object.keys(this.definitions)){let r=this.keysById.get(t)??[];e[t]=r.length===1?r[0]:[...r]}return e}},Ir=null;function ao(e){Ir=e}a(ao,"setKeybindings");function ue(){return Ir||(Ir=new Pi(Li)),Ir}a(ue,"getKeybindings");var ho={};Ah(ho,{Box:a(()=>dl,"Box"),CURSOR_MARKER:a(()=>Fe,"CURSOR_MARKER"),CancellableLoader:a(()=>gl,"CancellableLoader"),CombinedAutocompleteProvider:a(()=>Wo,"CombinedAutocompleteProvider"),Container:a(()=>Ne,"Container"),Editor:a(()=>Il,"Editor"),HStack:a(()=>rf,"HStack"),Image:a(()=>_l,"Image"),Input:a(()=>Ur,"Input"),Key:a(()=>Jn,"Key"),KeybindingsManager:a(()=>Pi,"KeybindingsManager"),Loader:a(()=>is,"Loader"),Markdown:a(()=>Wl,"Markdown"),Marked:a(()=>Or,"Marked"),MouseRegion:a(()=>Hl,"MouseRegion"),ProcessTerminal:a(()=>ra,"ProcessTerminal"),ScrollView:a(()=>ps,"ScrollView"),SelectList:a(()=>ss,"SelectList"),SettingsList:a(()=>Vl,"SettingsList"),Spacer:a(()=>ql,"Spacer"),StdinBuffer:a(()=>Xl,"StdinBuffer"),TUI_KEYBINDINGS:a(()=>Li,"TUI_KEYBINDINGS"),Text:a(()=>rs,"Text"),TruncatedText:a(()=>Kl,"TruncatedText"),TuiAltScreen:a(()=>ba,"TuiAltScreen"),TuiMainScreen:a(()=>Sa,"TuiMainScreen"),VStack:a(()=>Ul,"VStack"),allocateImageId:a(()=>zo,"allocateImageId"),backgroundAnsi:a(()=>qt,"backgroundAnsi"),calculateImageRows:a(()=>Np,"calculateImageRows"),colorToHex:a(()=>Cr,"colorToHex"),colorToOkhsl:a(()=>Gn,"colorToOkhsl"),colorToOklch:a(()=>Ue,"colorToOklch"),colorToRgb:a(()=>Te,"colorToRgb"),compositeTuiLine:a(()=>Xe,"compositeTuiLine"),decodeKittyPrintable:a(()=>Ii,"decodeKittyPrintable"),deleteAllKittyImages:a(()=>Yo,"deleteAllKittyImages"),deleteKittyImage:a(()=>Gi,"deleteKittyImage"),detectCapabilities:a(()=>ji,"detectCapabilities"),encodeITerm2:a(()=>Qo,"encodeITerm2"),encodeKitty:a(()=>Go,"encodeKitty"),foregroundAnsi:a(()=>Vt,"foregroundAnsi"),formatProgramStatus:a(()=>Xr,"formatProgramStatus"),fuzzyFilter:a(()=>Qt,"fuzzyFilter"),fuzzyMatch:a(()=>Ki,"fuzzyMatch"),getCapabilities:a(()=>pe,"getCapabilities"),getCellDimensions:a(()=>Ui,"getCellDimensions"),getGifDimensions:a(()=>sl,"getGifDimensions"),getImageDimensions:a(()=>Zi,"getImageDimensions"),getJpegDimensions:a(()=>il,"getJpegDimensions"),getKeybindings:a(()=>ue,"getKeybindings"),getNativeClipboard:a(()=>zl,"getNativeClipboard"),getOsc8LinkAtColumn:a(()=>Fn,"getOsc8LinkAtColumn"),getPngDimensions:a(()=>Qi,"getPngDimensions"),getTerminalColorMode:a(()=>Fr,"getTerminalColorMode"),getWebpDimensions:a(()=>nl,"getWebpDimensions"),hyperlink:a(()=>Nr,"hyperlink"),imageFallback:a(()=>Wr,"imageFallback"),indexedColor:a(()=>vr,"indexedColor"),isAppleTerminalSession:a(()=>ms,"isAppleTerminalSession"),isFocusable:a(()=>Ji,"isFocusable"),isKeyRelease:a(()=>Ei,"isKeyRelease"),isKeyRepeat:a(()=>dd,"isKeyRepeat"),isKittyProtocolActive:a(()=>od,"isKittyProtocolActive"),isViewportTUI:a(()=>ul,"isViewportTUI"),matchesKey:a(()=>_e,"matchesKey"),mixColors:a(()=>Bi,"mixColors"),okhslColor:a(()=>Ht,"okhslColor"),oklabToOkhslLightness:a(()=>kr,"oklabToOkhslLightness"),oklchColor:a(()=>Sr,"oklchColor"),parseColor:a(()=>Pe,"parseColor"),parseKey:a(()=>md,"parseKey"),parseTerminalColorSchemeReport:a(()=>Ho,"parseTerminalColorSchemeReport"),renderFakeCursor:a(()=>Zt,"renderFakeCursor"),renderImage:a(()=>ol,"renderImage"),renderLatex:a(()=>us,"renderLatex"),resetCapabilitiesCache:a(()=>Lp,"resetCapabilitiesCache"),rgbColor:a(()=>Se,"rgbColor"),setCapabilities:a(()=>zi,"setCapabilities"),setCapabilityOverrides:a(()=>Uo,"setCapabilityOverrides"),setCellDimensions:a(()=>qo,"setCellDimensions"),setImageTranscoder:a(()=>$l,"setImageTranscoder"),setKeybindings:a(()=>ao,"setKeybindings"),setKittyProtocolActive:a(()=>Ar,"setKittyProtocolActive"),sliceByColumn:a(()=>Y,"sliceByColumn"),stripTerminalSequences:a(()=>fr,"stripTerminalSequences"),styleText:a(()=>nd,"styleText"),styleTextWithAnsi:a(()=>Ri,"styleTextWithAnsi"),truncateToWidth:a(()=>K,"truncateToWidth"),visibleWidth:a(()=>T,"visibleWidth"),wrapTextWithAnsi:a(()=>ve,"wrapTextWithAnsi")});function $i(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}a($i,"A");var ze=$i();function uo(e){ze=e}a(uo,"j");var Ge={exec:a(()=>null,"exec")};function dt(e){let t=[];return r=>{let i=Math.max(0,Math.min(3,r-1)),s=t[i];return s||(s=e(i),t[i]=s),s}}a(dt,"I");function P(e,t=""){let r=typeof e=="string"?e:e.source,i={replace:a((s,n)=>{let o=typeof n=="string"?n:n.source;return o=o.replace(Z.caret,"$1"),r=r.replace(s,o),i},"replace"),getRegex:a(()=>new RegExp(r,t),"getRegex")};return i}a(P,"k");var wd=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),Z={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:a(e=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),"listItemRegex"),nextBulletRegex:dt(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:dt(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:dt(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:dt(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:dt(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:dt(e=>new RegExp(`^ {0,${e}}>`))},kd=/^(?:[ \t]*(?:\n|$))+/,vd=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Sd=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,jt=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Cd=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,_i=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,co=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,po=P(co).replace(/bull/g,_i).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Td=P(co).replace(/bull/g,_i).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Oi=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,Ad=/^[^\n]+/,Di=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Md=P(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Di).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Bd=P(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,_i).getRegex(),Lr="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",Fi=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Rd=P("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",Fi).replace("tag",Lr).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),fo=a(e=>P(Oi).replace("hr",jt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list",e).replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Lr).getRegex(),"le"),Ed=fo(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),Id=fo(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),Ld=P(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Id).getRegex(),Ni={blockquote:Ld,code:vd,def:Md,fences:Sd,heading:Cd,hr:jt,html:Rd,lheading:po,list:Bd,newline:kd,paragraph:Ed,table:Ge,text:Ad},go=P("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",jt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Lr).getRegex(),Pd={...Ni,lheading:Td,table:go,paragraph:P(Oi).replace("hr",jt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",go).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Lr).getRegex()},$d={...Ni,html:P(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Fi).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Ge,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:P(Oi).replace("hr",jt).replace("heading",` *#{1,6} *[^
|
|
10
|
-
]`).replace("lheading",po).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},_d=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Od=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,mo=/^( {2,}|\\)\n(?!\s*$)/,Dd=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Ae=/[\p{P}\p{S}]/u,pt=/[\s\p{P}\p{S}]/u,zt=/[^\s\p{P}\p{S}]/u,Fd=P(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,pt).getRegex(),Nd=/[\p{Pi}\p{Ps}"']/u,xo=/(?!~)[\p{P}\p{S}]/u,Wd=/(?!~)[\s\p{P}\p{S}]/u,Hd=/(?:[^\s\p{P}\p{S}]|~)/u,Vd=P(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",wd?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),bo=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,qd=P(bo,"u").replace(/punct/g,Ae).getRegex(),Kd=P(bo,"u").replace(/punct/g,xo).getRegex(),Ud=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,jd=P(Ud,"u").replace(/openQuote/g,Nd).replace(/punct/g,Ae).getRegex(),yo="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",zd=P(yo,"gu").replace(/notPunctSpace/g,zt).replace(/punctSpace/g,pt).replace(/punct/g,Ae).getRegex(),Gd=P(yo,"gu").replace(/notPunctSpace/g,Hd).replace(/punctSpace/g,Wd).replace(/punct/g,xo).getRegex(),Yd="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",Xd=P(Yd,"gu").replace(/notPunctSpace/g,zt).replace(/punctSpace/g,pt).replace(/punct/g,Ae).getRegex(),Qd=P("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,zt).replace(/punctSpace/g,pt).replace(/punct/g,Ae).getRegex(),Zd="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",Jd=P(Zd,"gu").replace(/notPunctSpace/g,zt).replace(/punctSpace/g,pt).replace(/punct/g,Ae).getRegex(),ep=P(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Ae).getRegex(),tp="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",rp=P(tp,"gu").replace(/notPunctSpace/g,zt).replace(/punctSpace/g,pt).replace(/punct/g,Ae).getRegex(),ip=P(/\\(punct)/,"gu").replace(/punct/g,Ae).getRegex(),sp=P(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),np=P(Fi).replace("(?:-->|$)","-->").getRegex(),op=P("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",np).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Pr=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,lp=P(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",Pr).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),wo=P(/^!?\[(label)\]\[(ref)\]/).replace("label",Pr).replace("ref",Di).getRegex(),ko=P(/^!?\[(ref)\](?:\[\])?/).replace("ref",Di).getRegex(),ap=P("reflink|nolink(?!\\()","g").replace("reflink",wo).replace("nolink",ko).getRegex(),vo=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Wi={_backpedal:Ge,anyPunctuation:ip,autolink:sp,blockSkip:Vd,br:mo,code:Od,del:Ge,delLDelim:Ge,delRDelim:Ge,emStrongLDelim:qd,emStrongRDelimAst:zd,emStrongRDelimUnd:Qd,escape:_d,link:lp,nolink:ko,punctuation:Fd,reflink:wo,reflinkSearch:ap,tag:op,text:Dd,url:Ge},hp={...Wi,emStrongLDelim:jd,emStrongRDelimAst:Xd,emStrongRDelimUnd:Jd,link:P(/^!?\[(label)\]\((.*?)\)/).replace("label",Pr).getRegex(),reflink:P(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Pr).getRegex()},Hi={...Wi,emStrongRDelimAst:Gd,emStrongLDelim:Kd,delLDelim:ep,delRDelim:rp,url:P(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",vo).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:P(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",vo).getRegex()},up={...Hi,br:P(mo).replace("{2,}","*").getRegex(),text:P(Hi.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},$r={normal:Ni,gfm:Pd,pedantic:$d},Gt={normal:Wi,gfm:Hi,breaks:up,pedantic:hp},cp={"&":"&","<":"<",">":">",'"':""","'":"'"},So=a(e=>cp[e],"ge");function be(e,t){if(t){if(Z.escapeTest.test(e))return e.replace(Z.escapeReplace,So)}else if(Z.escapeTestNoEncode.test(e))return e.replace(Z.escapeReplaceNoEncode,So);return e}a(be,"T");function Co(e){try{e=encodeURI(e).replace(Z.percentDecode,"%")}catch{return null}return e}a(Co,"Y");function To(e,t){let r=e.replace(Z.findPipe,(n,o,l)=>{let h=!1,u=o;for(;--u>=0&&l[u]==="\\";)h=!h;return h?"|":" |"}),i=r.split(Z.splitPipe),s=0;if(i[0].trim()||i.shift(),i.length>0&&!i.at(-1)?.trim()&&i.pop(),t)if(i.length>t)i.splice(t);else for(;i.length<t;)i.push("");for(;s<i.length;s++)i[s]=i[s].trim().replace(Z.slashPipe,"|");return i}a(To,"ee");function Oe(e,t,r){let i=e.length;if(i===0)return"";let s=0;for(;s<i;){let n=e.charAt(i-s-1);if(n===t&&!r)s++;else if(n!==t&&r)s++;else break}return e.slice(0,i-s)}a(Oe,"$");function Ao(e){let t=e.split(`
|
|
11
|
-
`),r=t.length-1;for(;r>=0&&Z.blankLine.test(t[r]);)r--;return t.length-r<=2?e:t.slice(0,r+1).join(`
|
|
12
|
-
`)}a(Ao,"te");function dp(e,t){if(e.indexOf(t[1])===-1)return-1;let r=0;for(let i=0;i<e.length;i++)if(e[i]==="\\")i++;else if(e[i]===t[0])r++;else if(e[i]===t[1]&&(r--,r<0))return i;return r>0?-2:-1}a(dp,"fe");function pp(e,t=0){let r=t,i="";for(let s of e)if(s===" "){let n=4-r%4;i+=" ".repeat(n),r+=n}else i+=s,r++;return i}a(pp,"me");function Mo(e,t,r,i,s){let n=t.href,o=t.title||null,l=e[1].replace(s.other.outputLinkReplace,"$1"),h=e[0].charAt(0)==="!";i.state.inLink=!0;let u=i.state.linkEmitted,d=i.state.inRawBlock;i.state.linkEmitted=!1;let c=i.inlineTokens(l),p=i.state.linkEmitted;if(i.state.linkEmitted=u,i.state.inLink=!1,!h){if(p){i.state.inRawBlock=d;return}i.state.linkEmitted=!0}return{type:h?"image":"link",raw:r,href:n,title:o,text:l,tokens:c}}a(Mo,"xe");function fp(e,t,r){let i=e.match(r.other.indentCodeCompensation);if(i===null)return t;let s=i[1];return t.split(`
|
|
13
|
-
`).map(n=>{let o=n.match(r.other.beginningSpace);if(o===null)return n;let[l]=o;return l.length>=s.length?n.slice(s.length):n}).join(`
|
|
14
|
-
`)}a(fp,"kt");var Yt=class{static{a(this,"y")}options;rules;lexer;constructor(e){this.options=e||ze}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let r=this.options.pedantic?t[0]:Ao(t[0]),i=r.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:r,codeBlockStyle:"indented",text:i}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let r=t[0],i=fp(r,t[3]||"",this.rules);return{type:"code",raw:r,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:i}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let r=t[2].trim();if(this.rules.other.endingHash.test(r)){let i=Oe(r,"#");(this.options.pedantic||!i||this.rules.other.endingSpaceChar.test(i))&&(r=i.trim())}return{type:"heading",raw:Oe(t[0],`
|
|
15
|
-
`),depth:t[1].length,text:r,tokens:this.lexer.inline(r)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:Oe(t[0],`
|
|
16
|
-
`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let r=Oe(t[0],`
|
|
17
|
-
`).split(`
|
|
18
|
-
`),i="",s="",n=[];for(;r.length>0;){let o=!1,l=[],h;for(h=0;h<r.length;h++)if(this.rules.other.blockquoteStart.test(r[h]))l.push(r[h]),o=!0;else if(!o)l.push(r[h]);else break;r=r.slice(h);let u=l.join(`
|
|
19
|
-
`),d=u.replace(this.rules.other.blockquoteSetextReplace,`
|
|
20
|
-
$1`).replace(this.rules.other.blockquoteSetextReplace2,"");i=i?`${i}
|
|
21
|
-
${u}`:u,s=s?`${s}
|
|
22
|
-
${d}`:d;let c=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(d,n,!0),this.lexer.state.top=c,r.length===0)break;let p=n.at(-1);if(p?.type==="code")break;if(p?.type==="blockquote"){let f=p,g=r.join(`
|
|
23
|
-
`),x=f.raw+`
|
|
24
|
-
`+g.replace(this.rules.other.blockquoteSetextReplace2,""),m=this.blockquote(x);n[n.length-1]=m,i=`${i}
|
|
25
|
-
${g}`,s=s.substring(0,s.length-f.text.length)+m.text;break}else if(p?.type==="list"){let f=p,g=f.raw+`
|
|
26
|
-
`+r.join(`
|
|
27
|
-
`),x=this.list(g);n[n.length-1]=x,i=i.substring(0,i.length-p.raw.length)+x.raw,s=s.substring(0,s.length-f.raw.length)+x.raw,r=g.substring(n.at(-1).raw.length).split(`
|
|
28
|
-
`);continue}}return{type:"blockquote",raw:i,tokens:n,text:s}}}list(e){let t=this.rules.block.list.exec(e);if(t){let r=t[1].trim(),i=r.length>1,s={type:"list",raw:"",ordered:i,start:i?+r.slice(0,-1):"",loose:!1,items:[]};r=i?`\\d{1,9}\\${r.slice(-1)}`:`\\${r}`,this.options.pedantic&&(r=i?r:"[*+-]");let n=this.rules.other.listItemRegex(r),o=!1;for(;e;){let h=!1,u="",d="";if(!(t=n.exec(e))||this.rules.block.hr.test(e))break;u=t[0],e=e.substring(u.length);let c=pp(t[2].split(`
|
|
29
|
-
`,1)[0],t[1].length),p=e.split(`
|
|
30
|
-
`,1)[0],f=!c.trim(),g=0;if(this.options.pedantic?(g=2,d=c.trimStart()):f?g=t[1].length+1:(g=c.search(this.rules.other.nonSpaceChar),g=g>4?1:g,d=c.slice(g),g+=t[1].length),f&&this.rules.other.blankLine.test(p)&&(u+=p+`
|
|
31
|
-
`,e=e.substring(p.length+1),h=!0),!h){let x=this.rules.other.nextBulletRegex(g),m=this.rules.other.hrRegex(g),b=this.rules.other.fencesBeginRegex(g),C=this.rules.other.headingBeginRegex(g),S=this.rules.other.htmlBeginRegex(g),y=this.rules.other.blockquoteBeginRegex(g);for(;e;){let k=e.split(`
|
|
32
|
-
`,1)[0],v;if(p=k,this.options.pedantic?(p=p.replace(this.rules.other.listReplaceNesting," "),v=p):v=p.replace(this.rules.other.tabCharGlobal," "),b.test(p)||C.test(p)||S.test(p)||y.test(p)||x.test(p)||m.test(p))break;if(v.search(this.rules.other.nonSpaceChar)>=g||!p.trim())d+=`
|
|
33
|
-
`+v.slice(g);else{if(f||c.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||b.test(c)||C.test(c)||m.test(c))break;d+=`
|
|
34
|
-
`+p}f=!p.trim(),u+=k+`
|
|
35
|
-
`,e=e.substring(k.length+1),c=v.slice(g)}}s.loose||(o?s.loose=!0:this.rules.other.doubleBlankLine.test(u)&&(o=!0)),s.items.push({type:"list_item",raw:u,task:!!this.options.gfm&&this.rules.other.listIsTask.test(d),loose:!1,text:d,tokens:[]}),s.raw+=u}let l=s.items.at(-1);if(l)l.raw=l.raw.trimEnd(),l.text=l.text.trimEnd();else return;s.raw=s.raw.trimEnd();for(let h of s.items)if(this.lexer.state.top=!1,h.tokens=this.lexer.blockTokens(h.text,[]),!s.loose){let u=h.tokens.filter(c=>c.type==="space"),d=u.length>0&&u.some(c=>this.rules.other.anyLine.test(c.raw));s.loose=d}for(let h of s.items){let u=h.tokens[0];if(h.task&&(u?.type==="text"||u?.type==="paragraph")){h.text=h.text.replace(this.rules.other.listReplaceTask,""),u.raw=u.raw.replace(this.rules.other.listReplaceTask,""),u.text=u.text.replace(this.rules.other.listReplaceTask,"");for(let c=this.lexer.inlineQueue.length-1;c>=0;c--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[c].src)){this.lexer.inlineQueue[c].src=this.lexer.inlineQueue[c].src.replace(this.rules.other.listReplaceTask,"");break}let d=this.rules.other.listTaskCheckbox.exec(h.raw);if(d){let c={type:"checkbox",raw:d[0]+" ",checked:d[0]!=="[ ]"};h.checked=c.checked,s.loose?h.tokens[0]&&["paragraph","text"].includes(h.tokens[0].type)&&"tokens"in h.tokens[0]&&h.tokens[0].tokens?(h.tokens[0].raw=c.raw+h.tokens[0].raw,h.tokens[0].text=c.raw+h.tokens[0].text,h.tokens[0].tokens.unshift(c)):h.tokens.unshift({type:"paragraph",raw:c.raw,text:c.raw,tokens:[c]}):h.tokens.unshift(c)}}else h.task&&(h.task=!1)}if(s.loose)for(let h of s.items){h.loose=!0;for(let u of h.tokens)u.type==="text"&&(u.type="paragraph")}return s}}html(e){let t=this.rules.block.html.exec(e);if(t){let r=Ao(t[0]);return{type:"html",block:!0,raw:r,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:r}}}def(e){let t=this.rules.block.def.exec(e);if(t){let r=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),i=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",s=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:r,raw:Oe(t[0],`
|
|
36
|
-
`),href:i,title:s}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let r=To(t[1]),i=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),s=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
|
|
37
|
-
`):[],n={type:"table",raw:Oe(t[0],`
|
|
38
|
-
`),header:[],align:[],rows:[]};if(r.length===i.length){for(let o of i)this.rules.other.tableAlignRight.test(o)?n.align.push("right"):this.rules.other.tableAlignCenter.test(o)?n.align.push("center"):this.rules.other.tableAlignLeft.test(o)?n.align.push("left"):n.align.push(null);for(let o=0;o<r.length;o++)n.header.push({text:r[o],tokens:this.lexer.inline(r[o]),header:!0,align:n.align[o]});for(let o of s)n.rows.push(To(o,n.header.length).map((l,h)=>({text:l,tokens:this.lexer.inline(l),header:!1,align:n.align[h]})));return n}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let r=t[1].trim();return{type:"heading",raw:Oe(t[0],`
|
|
39
|
-
`),depth:t[2].charAt(0)==="="?1:2,text:r,tokens:this.lexer.inline(r)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let r=t[1].charAt(t[1].length-1)===`
|
|
40
|
-
`?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:r,tokens:this.lexer.inline(r)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let r=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(r)){if(!this.rules.other.endAngleBracket.test(r))return;let n=Oe(r.slice(0,-1),"\\");if((r.length-n.length)%2===0)return}else{let n=dp(t[2],"()");if(n===-2)return;if(n>-1){let o=(t[0].indexOf("!")===0?5:4)+t[1].length+n;t[2]=t[2].substring(0,n),t[0]=t[0].substring(0,o).trim(),t[3]=""}}let i=t[2],s="";if(this.options.pedantic){let n=this.rules.other.pedanticHrefTitle.exec(i);n&&(i=n[1],s=n[3])}else s=t[3]?t[3].slice(1,-1):"";return i=i.trim(),this.rules.other.startAngleBracket.test(i)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(r)?i=i.slice(1):i=i.slice(1,-1)),Mo(t,{href:i&&i.replace(this.rules.inline.anyPunctuation,"$1"),title:s&&s.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let r;if((r=this.rules.inline.reflink.exec(e))||(r=this.rules.inline.nolink.exec(e))){let i=(r[2]||r[1]).replace(this.rules.other.multipleSpaceGlobal," "),s=t[i.toLowerCase()];if(!s){let n=r[0].charAt(0);return{type:"text",raw:n,text:n}}return Mo(r,s,r[0],this.lexer,this.rules)}}emStrong(e,t,r=""){let i=this.rules.inline.emStrongLDelim.exec(e);if(!(!i||!i[1]&&!i[2]&&!i[3]&&!i[4]||i[4]&&r.match(this.rules.other.unicodeAlphaNumeric))&&(!(i[1]||i[3])||!r||this.rules.inline.punctuation.exec(r))){let s=[...i[0]].length-1,n,o,l=s,h=0,u=i[0][0],d=r===u,c=u==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,t=t.slice(-1*e.length+s);(i=c.exec(t))!==null;){if(n=i[1]||i[2]||i[3]||i[4]||i[5]||i[6],!n)continue;if(o=[...n].length,i[3]||i[4]){l+=o;continue}else if(i[5]||i[6]){if(s%3&&!((s+o)%3)){h+=o;continue}if(d)break}if(l-=o,l>0)continue;o=Math.min(o,o+l+h);let p=[...i[0]][0].length,f=e.slice(0,s+i.index+p+o);if(Math.min(s,o)%2){let x=f.slice(1,-1);return{type:"em",raw:f,text:x,tokens:this.lexer.inlineTokens(x)}}let g=f.slice(2,-2);return{type:"strong",raw:f,text:g,tokens:this.lexer.inlineTokens(g)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let r=t[2].replace(this.rules.other.newLineCharGlobal," "),i=this.rules.other.nonSpaceChar.test(r),s=this.rules.other.startingSpaceChar.test(r)&&this.rules.other.endingSpaceChar.test(r);return i&&s&&(r=r.substring(1,r.length-1)),{type:"codespan",raw:t[0],text:r}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,r=""){let i=this.rules.inline.delLDelim.exec(e);if(i&&(!i[1]||!r||this.rules.inline.punctuation.exec(r))){let s=[...i[0]].length-1,n,o,l=s,h=this.rules.inline.delRDelim;for(h.lastIndex=0,t=t.slice(-1*e.length+s);(i=h.exec(t))!==null;){if(n=i[1]||i[2]||i[3]||i[4]||i[5]||i[6],!n||(o=[...n].length,o!==s))continue;if(i[3]||i[4]){l+=o;continue}if(l-=o,l>0)continue;o=Math.min(o,o+l);let u=[...i[0]][0].length,d=e.slice(0,s+i.index+u+o),c=d.slice(s,-s);return{type:"del",raw:d,text:c,tokens:this.lexer.inlineTokens(c)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let r,i;return t[2]==="@"?(r=t[1],i="mailto:"+r):(r=t[1],i=r),{type:"link",raw:t[0],text:r,href:i,tokens:[{type:"text",raw:r,text:r}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let r,i;if(t[2]==="@")r=t[0],i="mailto:"+r;else{let s;do s=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(s!==t[0]);r=t[0],t[1]==="www."?i="http://"+t[0]:i=t[0]}return{type:"link",raw:t[0],text:r,href:i,tokens:[{type:"text",raw:r,text:r}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let r=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:r}}}},ce=class Vs{static{a(this,"l")}tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||ze,this.options.tokenizer=this.options.tokenizer||new Yt,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,linkEmitted:!1,top:!0};let r={other:Z,block:$r.normal,inline:Gt.normal};this.options.pedantic?(r.block=$r.pedantic,r.inline=Gt.pedantic):this.options.gfm&&(r.block=$r.gfm,this.options.breaks?r.inline=Gt.breaks:r.inline=Gt.gfm),this.tokenizer.rules=r}static get rules(){return{block:$r,inline:Gt}}static lex(t,r){return new Vs(r).lex(t)}static lexInline(t,r){return new Vs(r).inlineTokens(t)}lex(t){t=t.replace(Z.carriageReturn,`
|
|
41
|
-
`),this.blockTokens(t,this.tokens);for(let r=0;r<this.inlineQueue.length;r++){let i=this.inlineQueue[r];this.inlineTokens(i.src,i.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(t,r=[],i=!1){this.tokenizer.lexer=this,this.options.pedantic&&(t=t.replace(Z.tabCharGlobal," ").replace(Z.spaceLine,""));let s=1/0;for(;t;){if(t.length<s)s=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}let n;if(this.options.extensions?.block?.some(l=>(n=l.call({lexer:this},t,r))?(t=t.substring(n.raw.length),r.push(n),!0):!1))continue;if(n=this.tokenizer.space(t)){t=t.substring(n.raw.length);let l=r.at(-1);n.raw.length===1&&l!==void 0?l.raw+=`
|
|
42
|
-
`:r.push(n);continue}if(n=this.tokenizer.code(t)){t=t.substring(n.raw.length);let l=r.at(-1);l?.type==="paragraph"||l?.type==="text"?(l.raw+=(l.raw.endsWith(`
|
|
43
|
-
`)?"":`
|
|
44
|
-
`)+n.raw,l.text+=`
|
|
45
|
-
`+n.text,this.inlineQueue.at(-1).src=l.text):r.push(n);continue}if(n=this.tokenizer.fences(t)){t=t.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.heading(t)){t=t.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.hr(t)){t=t.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.blockquote(t)){t=t.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.list(t)){t=t.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.html(t)){t=t.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.def(t)){t=t.substring(n.raw.length);let l=r.at(-1);l?.type==="paragraph"||l?.type==="text"?(l.raw+=(l.raw.endsWith(`
|
|
46
|
-
`)?"":`
|
|
47
|
-
`)+n.raw,l.text+=`
|
|
48
|
-
`+n.raw,this.inlineQueue.at(-1).src=l.text):this.tokens.links[n.tag]||(this.tokens.links[n.tag]={href:n.href,title:n.title},r.push(n));continue}if(n=this.tokenizer.table(t)){t=t.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.lheading(t)){t=t.substring(n.raw.length),r.push(n);continue}let o=t;if(this.options.extensions?.startBlock){let l=1/0,h=t.slice(1),u;this.options.extensions.startBlock.forEach(d=>{u=d.call({lexer:this},h),typeof u=="number"&&u>=0&&(l=Math.min(l,u))}),l<1/0&&l>=0&&(o=t.substring(0,l+1))}if(this.state.top&&(n=this.tokenizer.paragraph(o))){let l=r.at(-1);i&&l?.type==="paragraph"?(l.raw+=(l.raw.endsWith(`
|
|
49
|
-
`)?"":`
|
|
50
|
-
`)+n.raw,l.text+=`
|
|
51
|
-
`+n.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=l.text):r.push(n),i=o.length!==t.length,t=t.substring(n.raw.length);continue}if(n=this.tokenizer.text(t)){t=t.substring(n.raw.length);let l=r.at(-1);l?.type==="text"?(l.raw+=(l.raw.endsWith(`
|
|
52
|
-
`)?"":`
|
|
53
|
-
`)+n.raw,l.text+=`
|
|
54
|
-
`+n.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=l.text):r.push(n);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return this.state.top=!0,r}inline(t,r=[]){return this.inlineQueue.push({src:t,tokens:r}),r}linkInText(t){if(!t.includes("["))return!1;let r=this.tokenizer.rules.inline.link;for(let i of t.matchAll(this.tokenizer.rules.inline.blockSkip))if(r.test(i[0])&&t.charAt(i.index-1)!=="!")return!0;for(let i of t.matchAll(this.tokenizer.rules.inline.reflinkSearch)){let s=i[0],n=s.lastIndexOf("[");if(!(s.charAt(0)==="!"||!Object.hasOwn(this.tokens.links,s.slice(n+1,-1)))&&!(n>1&&this.linkInText(s.slice(1,n-1))))return!0}return!1}inlineTokens(t,r=[]){this.tokenizer.lexer=this;let i=t;if(this.tokens.links&&t.includes("[")){let l=this.tokenizer.rules.inline.reflinkSearch,h=a(u=>{let d=u.lastIndexOf("[");if(!Object.hasOwn(this.tokens.links,u.slice(d+1,-1)))return u;if(d>1&&u.charAt(0)!=="!"){let c=u.slice(1,d-1);if(this.linkInText(c))return"["+c.replace(l,h)+"]["+"a".repeat(u.length-d-2)+"]"}return"["+"a".repeat(u.length-2)+"]"},"u");i=i.replace(l,h)}i=i.replace(this.tokenizer.rules.inline.anyPunctuation,l=>"+".repeat(l.length)),i=i.replace(this.tokenizer.rules.inline.blockSkip,(l,h,u)=>{let d=u?u.length:0;return l.slice(0,d)+"["+"a".repeat(l.length-d-2)+"]"}),i=this.options.hooks?.emStrongMask?.call({lexer:this},i)??i;let s=!1,n="",o=1/0;for(;t;){if(t.length<o)o=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}s||(n=""),s=!1;let l;if(this.options.extensions?.inline?.some(u=>(l=u.call({lexer:this},t,r))?(t=t.substring(l.raw.length),r.push(l),!0):!1))continue;if(l=this.tokenizer.escape(t)){t=t.substring(l.raw.length),r.push(l);continue}if(l=this.tokenizer.tag(t)){t=t.substring(l.raw.length),r.push(l);continue}if(l=this.tokenizer.link(t)){t=t.substring(l.raw.length),r.push(l);continue}if(l=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(l.raw.length);let u=r.at(-1);l.type==="text"&&u?.type==="text"?(u.raw+=l.raw,u.text+=l.text):r.push(l);continue}if(l=this.tokenizer.emStrong(t,i,n)){t=t.substring(l.raw.length),r.push(l);continue}if(l=this.tokenizer.codespan(t)){t=t.substring(l.raw.length),r.push(l);continue}if(l=this.tokenizer.br(t)){t=t.substring(l.raw.length),r.push(l);continue}if(l=this.tokenizer.del(t,i,n)){t=t.substring(l.raw.length),r.push(l);continue}if(l=this.tokenizer.autolink(t)){t=t.substring(l.raw.length),r.push(l);continue}if(!this.state.inLink&&(l=this.tokenizer.url(t))){t=t.substring(l.raw.length),r.push(l);continue}let h=t;if(this.options.extensions?.startInline){let u=1/0,d=t.slice(1),c;this.options.extensions.startInline.forEach(p=>{c=p.call({lexer:this},d),typeof c=="number"&&c>=0&&(u=Math.min(u,c))}),u<1/0&&u>=0&&(h=t.substring(0,u+1))}if(l=this.tokenizer.inlineText(h)){t=t.substring(l.raw.length),l.raw.slice(-1)!=="_"&&(n=l.raw.slice(-1)),s=!0;let u=r.at(-1);u?.type==="text"?(u.raw+=l.raw,u.text+=l.text):r.push(l);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return r}infiniteLoopError(t){let r="Infinite loop on byte: "+t;if(this.options.silent)console.error(r);else throw new Error(r)}},_r=class{static{a(this,"P")}options;parser;constructor(e){this.options=e||ze}space(e){return""}code({text:e,lang:t,escaped:r}){let i=(t||"").match(Z.notSpaceStart)?.[0],s=e.replace(Z.endingNewline,"")+`
|
|
55
|
-
`;return i?'<pre><code class="language-'+be(i)+'">'+(r?s:be(s,!0))+`</code></pre>
|
|
56
|
-
`:"<pre><code>"+(r?s:be(s,!0))+`</code></pre>
|
|
57
|
-
`}blockquote({tokens:e}){return`<blockquote>
|
|
58
|
-
${this.parser.parse(e)}</blockquote>
|
|
59
|
-
`}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
|
|
60
|
-
`}hr(e){return`<hr>
|
|
61
|
-
`}list(e){let t=e.ordered,r=e.start,i="";for(let o=0;o<e.items.length;o++){let l=e.items[o];i+=this.listitem(l)}let s=t?"ol":"ul",n=t&&r!==1?' start="'+r+'"':"";return"<"+s+n+`>
|
|
62
|
-
`+i+"</"+s+`>
|
|
63
|
-
`}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>
|
|
64
|
-
`}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
|
|
65
|
-
`}table(e){let t="",r="";for(let s=0;s<e.header.length;s++)r+=this.tablecell(e.header[s]);t+=this.tablerow({text:r});let i="";for(let s=0;s<e.rows.length;s++){let n=e.rows[s];r="";for(let o=0;o<n.length;o++)r+=this.tablecell(n[o]);i+=this.tablerow({text:r})}return i&&(i=`<tbody>${i}</tbody>`),`<table>
|
|
66
|
-
<thead>
|
|
67
|
-
`+t+`</thead>
|
|
68
|
-
`+i+`</table>
|
|
69
|
-
`}tablerow({text:e}){return`<tr>
|
|
70
|
-
${e}</tr>
|
|
71
|
-
`}tablecell(e){let t=this.parser.parseInline(e.tokens),r=e.header?"th":"td";return(e.align?`<${r} align="${e.align}">`:`<${r}>`)+t+`</${r}>
|
|
72
|
-
`}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${be(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:r}){let i=this.parser.parseInline(r),s=Co(e);if(s===null)return i;e=s;let n='<a href="'+e+'"';return t&&(n+=' title="'+be(t)+'"'),n+=">"+i+"</a>",n}image({href:e,title:t,text:r,tokens:i}){i&&(r=this.parser.parseInline(i,this.parser.textRenderer));let s=Co(e);if(s===null)return be(r);e=s;let n=`<img src="${e}" alt="${be(r)}"`;return t&&(n+=` title="${be(t)}"`),n+=">",n}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:be(e.text)}},Vi=class{static{a(this,"L")}strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},de=class qs{static{a(this,"l2")}options;renderer;textRenderer;constructor(t){this.options=t||ze,this.options.renderer=this.options.renderer||new _r,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Vi}static parse(t,r){return new qs(r).parse(t)}static parseInline(t,r){return new qs(r).parseInline(t)}parse(t){this.renderer.parser=this;let r="";for(let i=0;i<t.length;i++){let s=t[i];if(this.options.extensions?.renderers?.[s.type]){let o=s,l=this.options.extensions.renderers[o.type].call({parser:this},o);if(l!==!1||!["space","hr","heading","code","table","blockquote","list","checkbox","html","def","paragraph","text"].includes(o.type)){r+=l||"";continue}}let n=s;switch(n.type){case"space":{r+=this.renderer.space(n);break}case"hr":{r+=this.renderer.hr(n);break}case"heading":{r+=this.renderer.heading(n);break}case"code":{r+=this.renderer.code(n);break}case"table":{r+=this.renderer.table(n);break}case"blockquote":{r+=this.renderer.blockquote(n);break}case"list":{r+=this.renderer.list(n);break}case"checkbox":{r+=this.renderer.checkbox(n);break}case"html":{r+=this.renderer.html(n);break}case"def":{r+=this.renderer.def(n);break}case"paragraph":{r+=this.renderer.paragraph(n);break}case"text":{r+=this.renderer.text(n);break}default:{let o='Token with "'+n.type+'" type was not found.';if(this.options.silent)return console.error(o),"";throw new Error(o)}}}return r}parseInline(t,r=this.renderer){this.renderer.parser=this;let i="";for(let s=0;s<t.length;s++){let n=t[s];if(this.options.extensions?.renderers?.[n.type]){let l=this.options.extensions.renderers[n.type].call({parser:this},n);if(l!==!1||!["escape","html","link","image","checkbox","strong","em","codespan","br","del","text"].includes(n.type)){i+=l||"";continue}}let o=n;switch(o.type){case"escape":{i+=r.text(o);break}case"html":{i+=r.html(o);break}case"link":{i+=r.link(o);break}case"image":{i+=r.image(o);break}case"checkbox":{i+=r.checkbox(o);break}case"strong":{i+=r.strong(o);break}case"em":{i+=r.em(o);break}case"codespan":{i+=r.codespan(o);break}case"br":{i+=r.br(o);break}case"del":{i+=r.del(o);break}case"text":{i+=r.text(o);break}default:{let l='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(l),"";throw new Error(l)}}}return i}},Xt=class{static{a(this,"S")}options;block;constructor(e){this.options=e||ze}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?ce.lex:ce.lexInline}provideParser(e=this.block){return e?de.parse:de.parseInline}},Or=class{static{a(this,"Z")}defaults=$i();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=de;Renderer=_r;TextRenderer=Vi;Lexer=ce;Tokenizer=Yt;Hooks=Xt;constructor(...e){this.use(...e)}walkTokens(e,t){let r=[];for(let i of e)switch(r=r.concat(t.call(this,i)),i.type){case"table":{let s=i;for(let n of s.header)r=r.concat(this.walkTokens(n.tokens,t));for(let n of s.rows)for(let o of n)r=r.concat(this.walkTokens(o.tokens,t));break}case"list":{let s=i;r=r.concat(this.walkTokens(s.items,t));break}default:{let s=i;this.defaults.extensions?.childTokens?.[s.type]?this.defaults.extensions.childTokens[s.type].forEach(n=>{let o=s[n].flat(1/0);r=r.concat(this.walkTokens(o,t))}):s.tokens&&(r=r.concat(this.walkTokens(s.tokens,t)))}}return r}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(r=>{let i={...r};if(i.async=this.defaults.async||i.async||!1,r.extensions&&(r.extensions.forEach(s=>{if(!s.name)throw new Error("extension name required");if("renderer"in s){let n=t.renderers[s.name];n?t.renderers[s.name]=function(...o){let l=s.renderer.apply(this,o);return l===!1&&(l=n.apply(this,o)),l}:t.renderers[s.name]=s.renderer}if("tokenizer"in s){if(!s.level||s.level!=="block"&&s.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let n=t[s.level];n?n.unshift(s.tokenizer):t[s.level]=[s.tokenizer],s.start&&(s.level==="block"?t.startBlock?t.startBlock.push(s.start):t.startBlock=[s.start]:s.level==="inline"&&(t.startInline?t.startInline.push(s.start):t.startInline=[s.start]))}"childTokens"in s&&s.childTokens&&(t.childTokens[s.name]=s.childTokens)}),i.extensions=t),r.renderer){let s=this.defaults.renderer||new _r(this.defaults);for(let n in r.renderer){if(!(n in s))throw new Error(`renderer '${n}' does not exist`);if(["options","parser"].includes(n))continue;let o=n,l=r.renderer[o],h=s[o];s[o]=(...u)=>{let d=l.apply(s,u);return d===!1&&(d=h.apply(s,u)),d||""}}i.renderer=s}if(r.tokenizer){let s=this.defaults.tokenizer||new Yt(this.defaults);for(let n in r.tokenizer){if(!(n in s))throw new Error(`tokenizer '${n}' does not exist`);if(["options","rules","lexer"].includes(n))continue;let o=n,l=r.tokenizer[o],h=s[o];s[o]=(...u)=>{let d=l.apply(s,u);return d===!1&&(d=h.apply(s,u)),d}}i.tokenizer=s}if(r.hooks){let s=this.defaults.hooks||new Xt;for(let n in r.hooks){if(!(n in s))throw new Error(`hook '${n}' does not exist`);if(["options","block"].includes(n))continue;let o=n,l=r.hooks[o],h=s[o];Xt.passThroughHooks.has(n)?s[o]=u=>{if(this.defaults.async&&Xt.passThroughHooksRespectAsync.has(n))return(async()=>{let c=await l.call(s,u);return h.call(s,c)})();let d=l.call(s,u);return h.call(s,d)}:s[o]=(...u)=>{if(this.defaults.async)return(async()=>{let c=await l.apply(s,u);return c===!1&&(c=await h.apply(s,u)),c})();let d=l.apply(s,u);return d===!1&&(d=h.apply(s,u)),d}}i.hooks=s}if(r.walkTokens){let s=this.defaults.walkTokens,n=r.walkTokens;i.walkTokens=function(o){let l=[];return l.push(n.call(this,o)),s&&(l=l.concat(s.call(this,o))),l}}this.defaults={...this.defaults,...i}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return ce.lex(e,t??this.defaults)}parser(e,t){return de.parse(e,t??this.defaults)}parseMarkdown(e){return(t,r)=>{let i={...r},s={...this.defaults,...i},n=this.onError(!!s.silent,!!s.async);if(this.defaults.async===!0&&i.async===!1)return n(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||t===null)return n(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return n(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(s.hooks&&(s.hooks.options=s,s.hooks.block=e),s.async)return(async()=>{let o=s.hooks?await s.hooks.preprocess(t):t,l=await(s.hooks?await s.hooks.provideLexer(e):e?ce.lex:ce.lexInline)(o,s),h=s.hooks?await s.hooks.processAllTokens(l):l;s.walkTokens&&await Promise.all(this.walkTokens(h,s.walkTokens));let u=await(s.hooks?await s.hooks.provideParser(e):e?de.parse:de.parseInline)(h,s);return s.hooks?await s.hooks.postprocess(u):u})().catch(n);try{s.hooks&&(t=s.hooks.preprocess(t));let o=(s.hooks?s.hooks.provideLexer(e):e?ce.lex:ce.lexInline)(t,s);s.hooks&&(o=s.hooks.processAllTokens(o)),s.walkTokens&&this.walkTokens(o,s.walkTokens);let l=(s.hooks?s.hooks.provideParser(e):e?de.parse:de.parseInline)(o,s);return s.hooks&&(l=s.hooks.postprocess(l)),l}catch(o){return n(o)}}}onError(e,t){return r=>{if(r.message+=`
|
|
73
|
-
Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error occurred:</p><pre>"+be(r.message+"",!0)+"</pre>";return t?Promise.resolve(i):i}if(t)return Promise.reject(r);throw r}}},Ye=new Or;function W(e,t){return Ye.parse(e,t)}a(W,"f"),W.options=W.setOptions=function(e){return Ye.setOptions(e),W.defaults=Ye.defaults,uo(W.defaults),W},W.getDefaults=$i,W.defaults=ze;function gp(...e){return Ye.use(...e),W.defaults=Ye.defaults,uo(W.defaults),W}a(gp,"dt"),W.use=gp,W.walkTokens=function(e,t){return Ye.walkTokens(e,t)},W.parseInline=Ye.parseInline,W.Parser=de,W.parser=de.parse,W.Renderer=_r,W.TextRenderer=Vi,W.Lexer=ce,W.lexer=ce.lex,W.Tokenizer=Yt,W.Hooks=Xt,W.parse=W;var G0=W.options,Y0=W.setOptions,X0=W.walkTokens,Q0=W.parseInline,Z0=de.parse,J0=ce.lex;import{spawn as mp}from"child_process";import{readdirSync as xp,statSync as Bo}from"fs";import{homedir as Ro}from"os";import{basename as qi,dirname as Dr,join as De}from"path";function Ki(e,t){let r=e.toLowerCase(),i=t.toLowerCase(),s=a(d=>{if(d.length===0)return{matches:!0,score:0};if(d.length>i.length)return{matches:!1,score:0};let c=0,p=0,f=-1,g=0;for(;c<d.length;){let x=i.indexOf(d[c],f+1);if(x===-1)break;let m=x===0||/[\s\-_./:]/.test(i[x-1]);f===x-1?(g++,p-=g*5):(g=0,f>=0&&(p+=(x-f-1)*2)),m&&(p-=10),p+=x*.1,f=x,c++}return c<d.length?{matches:!1,score:0}:(d===i&&(p-=100),{matches:!0,score:p})},"matchQuery"),n=s(r);if(n.matches)return n;let o=r.match(/^(?<letters>[a-z]+)(?<digits>[0-9]+)$/),l=r.match(/^(?<digits>[0-9]+)(?<letters>[a-z]+)$/),h=o?`${o.groups?.digits??""}${o.groups?.letters??""}`:l?`${l.groups?.letters??""}${l.groups?.digits??""}`:"";if(!h)return n;let u=s(h);return u.matches?{matches:!0,score:u.score+5}:n}a(Ki,"fuzzyMatch");function Qt(e,t,r){if(!t.trim())return e;let i=t.trim().split(/[\s/]+/).filter(n=>n.length>0);if(i.length===0)return e;let s=[];for(let n of e){let o=r(n),l=0,h=!0;for(let u of i){let d=Ki(u,o);if(d.matches)l+=d.score;else{h=!1;break}}h&&s.push({item:n,totalScore:l})}return s.sort((n,o)=>n.totalScore-o.totalScore),s.map(n=>n.item)}a(Qt,"fuzzyFilter");var Eo=new Set([" "," ",'"',"'","="]),Io=new RegExp(`${Dn.source}$`,"u"),Lo={"(":")","[":"]","{":"}","<":">","`":"`"};function Me(e){return e.replace(/\\/g,"/")}a(Me,"toDisplayPath");function bp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}a(bp,"escapeRegex");function yp(e){let t=Me(e);if(!t.includes("/"))return t;let r=t.endsWith("/"),i=t.replace(/^\/+|\/+$/g,"");if(!i)return t;let s="[\\\\/]",n=i.split("/").filter(Boolean).map(l=>bp(l));if(n.length===0)return t;let o=n.join(s);return r&&(o+=s),o}a(yp,"buildFdPathQuery");function Po(e){let t=-1,r=0;for(let i of e)r+=i.length,(Eo.has(i)||pr.test(i))&&(t=r-1);return t}a(Po,"findLastDelimiter");function $o(e){let t=e;for(;t.length>0;){let r=Lo[t[0]];if(!r||t.includes(r,1))break;t=t.slice(1)}return t}a($o,"stripLeadingWrappers");function wp(e){let t=!1,r=-1;for(let i=0;i<e.length;i+=1)e[i]==='"'&&(t=!t,t&&(r=i));return t?r:null}a(wp,"findUnclosedQuoteStart");function _o(e,t){let r=t;for(;r>0&&Lo[e[r-1]];)r-=1;return Eo.has(e[r-1]??"")||Io.test(e.slice(0,r))}a(_o,"isTokenStart");function Oo(e){let t=wp(e);return t===null?null:t>0&&e[t-1]==="@"?_o(e,t-1)?e.slice(t-1):null:_o(e,t)?e.slice(t):null}a(Oo,"extractQuotedPrefix");function Do(e){return e.startsWith('@"')?{rawPrefix:e.slice(2),isAtPrefix:!0,isQuotedPrefix:!0}:e.startsWith('"')?{rawPrefix:e.slice(1),isAtPrefix:!1,isQuotedPrefix:!0}:e.startsWith("@")?{rawPrefix:e.slice(1),isAtPrefix:!0,isQuotedPrefix:!1}:{rawPrefix:e,isAtPrefix:!1,isQuotedPrefix:!1}}a(Do,"parsePathPrefix");function Fo(e,t){let r=t.isQuotedPrefix||pr.test(e),i=t.isAtPrefix?"@":"";return r?`${`${i}"`}${e}"`:`${i}${e}`}a(Fo,"buildCompletionValue");async function No(e,t,r,i,s,n){let o=["--base-directory",e,"--max-results",String(i),"--type","f","--type","d","--follow","--hidden","--exclude",".git","--exclude",".git/*","--exclude",".git/**"];return n!==void 0&&o.push("--max-depth",String(n)),Me(r).includes("/")&&o.push("--full-path"),r&&o.push(yp(r)),await new Promise(l=>{if(s.aborted){l([]);return}let h=mp(t,o,{stdio:["ignore","pipe","pipe"]}),u="",d=!1,c=a(f=>{d||(d=!0,s.removeEventListener("abort",p),l(f))},"finish"),p=a(()=>{h.exitCode===null&&h.kill("SIGKILL")},"onAbort");s.addEventListener("abort",p,{once:!0}),h.stdout.setEncoding("utf-8"),h.stdout.on("data",f=>{u+=f}),h.on("error",()=>{c([])}),h.on("close",f=>{if(s.aborted||f!==0||!u){c([]);return}let g=u.trim().split(`
|
|
74
|
-
`).filter(Boolean),x=[];for(let m of g){let b=Me(m),C=b.endsWith("/"),S=C?b.slice(0,-1):b;S===".git"||S.startsWith(".git/")||S.includes("/.git/")||x.push({path:b,isDirectory:C})}c(x)})})}a(No,"walkDirectoryWithFd");var Wo=class{static{a(this,"CombinedAutocompleteProvider")}commands;basePath;fdPath;constructor(e=[],t,r=null){this.commands=e,this.basePath=t,this.fdPath=r}async getSuggestions(e,t,r,i){let s=(e[t]||"").slice(0,r),n=this.extractAtPrefix(s);if(n){let{rawPrefix:u,isQuotedPrefix:d}=Do(n),c=await this.getFuzzyFileSuggestions(u,{isQuotedPrefix:d,signal:i.signal});return c.length===0?null:{items:c,prefix:n}}let o=s.trimStart();if(!i.force&&o.startsWith("/")){let u=o.indexOf(" ");if(u===-1){let g=o.slice(1),x=this.commands.map(y=>{let k="name"in y?y.name:y.value,v="argumentHint"in y&&y.argumentHint?y.argumentHint:void 0,B=y.description??"",M=v?B?`${v} \u2014 ${B}`:v:B;return{name:k,label:k,description:M||void 0}}),m=Qt(x,g,y=>y.name.startsWith("skill:")?y.name.slice(6):y.name),b=new Set(m),C=Qt(x.filter(y=>y.name.startsWith("skill:")&&!b.has(y)),g,y=>y.name),S=[...m,...C].map(y=>({value:y.name,label:y.name,...y.description&&{description:y.description}}));return S.length===0?null:{items:S,prefix:o}}let d=o.slice(1,u),c=o.slice(u+1),p=this.commands.find(g=>("name"in g?g.name:g.value)===d);if(!p||!("getArgumentCompletions"in p)||!p.getArgumentCompletions)return null;let f=await p.getArgumentCompletions(c);return!Array.isArray(f)||f.length===0?null:{items:f,prefix:c}}let l=this.extractPathPrefix(s,i.force??!1);if(l===null)return null;let h=this.getFileSuggestions(l);return h.length===0?null:{items:h,prefix:l}}applyCompletion(e,t,r,i,s){let n=e[t]||"",o=n.slice(0,r-s.length),l=n.slice(r),h=s.startsWith('"')||s.startsWith('@"'),u=l.startsWith('"'),d=i.value.endsWith('"'),c=h&&d&&u?l.slice(1):l;if(s.startsWith("/")&&o.trim()===""&&!s.slice(1).includes("/")){let C=`${o}/${i.value} ${c}`,S=[...e];return S[t]=C,{lines:S,cursorLine:t,cursorCol:o.length+i.value.length+2}}if(s.startsWith("@")){let C=i.label.endsWith("/"),S=C?"":" ",y=`${o+i.value}${S}${c}`,k=[...e];k[t]=y;let v=i.value.endsWith('"'),B=C&&v?i.value.length-1:i.value.length;return{lines:k,cursorLine:t,cursorCol:o.length+B+S.length}}let p=n.slice(0,r);if(p.includes("/")&&p.includes(" ")){let C=o+i.value+c,S=[...e];S[t]=C;let y=i.label.endsWith("/"),k=i.value.endsWith('"'),v=y&&k?i.value.length-1:i.value.length;return{lines:S,cursorLine:t,cursorCol:o.length+v}}let f=o+i.value+c,g=[...e];g[t]=f;let x=i.label.endsWith("/"),m=i.value.endsWith('"'),b=x&&m?i.value.length-1:i.value.length;return{lines:g,cursorLine:t,cursorCol:o.length+b}}extractAtPrefix(e){let t=Oo(e);if(t?.startsWith('@"'))return t;let r=Po(e),i=$o(r===-1?e:e.slice(r+1));return i.startsWith("@")?i:null}extractPathPrefix(e,t=!1){let r=Oo(e);if(r)return r;let i=Po(e),s=$o(i===-1?e:e.slice(i+1));return t||s.includes("/")||s.startsWith(".")||s.startsWith("~/")||s===""&&e!==""&&Io.test(e)?s:null}expandHomePath(e){if(e.startsWith("~/")){let t=De(Ro(),e.slice(2));return e.endsWith("/")&&!t.endsWith("/")?`${t}/`:t}else if(e==="~")return Ro();return e}resolveScopedFuzzyQuery(e){let t=Me(e),r=t.lastIndexOf("/");if(r===-1)return null;let i=t.slice(0,r+1),s=t.slice(r+1),n;i.startsWith("~/")?n=this.expandHomePath(i):i.startsWith("/")||/^[a-zA-Z]:[/\\]/.test(i)?n=i:n=De(this.basePath,i);try{if(!Bo(n).isDirectory())return null}catch{return null}return{baseDir:n,query:s,displayBase:i}}scopedPathForDisplay(e,t){let r=Me(t);return e==="/"?`/${r}`:`${Me(e)}${r}`}getFileSuggestions(e){try{let t,r,{rawPrefix:i,isAtPrefix:s,isQuotedPrefix:n}=Do(e),o=i;if(o.startsWith("~")&&(o=this.expandHomePath(o)),i===""||i==="./"||i==="../"||i==="~"||i==="~/"||i==="/"||s&&i==="")i.startsWith("~")||o.startsWith("/")?t=o:t=De(this.basePath,o),r="";else if(i.endsWith("/"))i.startsWith("~")||o.startsWith("/")?t=o:t=De(this.basePath,o),r="";else{let u=Dr(o),d=qi(o);i.startsWith("~")||o.startsWith("/")?t=u:t=De(this.basePath,u),r=d}let l=xp(t,{withFileTypes:!0}),h=[];for(let u of l){if(!u.name.toLowerCase().startsWith(r.toLowerCase()))continue;let d=u.isDirectory();if(!d&&u.isSymbolicLink())try{let m=De(t,u.name);d=Bo(m).isDirectory()}catch{}let c,p=u.name,f=i;if(f.endsWith("/"))c=f+p;else if(f.includes("/")||f.includes("\\"))if(f.startsWith("~/")){let m=f.slice(2),b=Dr(m);c=`~/${b==="."?p:De(b,p)}`}else if(f.startsWith("/")){let m=Dr(f);m==="/"?c=`/${p}`:c=`${m}/${p}`}else c=De(Dr(f),p),f.startsWith("./")&&!c.startsWith("./")&&(c=`./${c}`);else f.startsWith("~")?c=`~/${p}`:c=p;c=Me(c);let g=d?`${c}/`:c,x=Fo(g,{isDirectory:d,isAtPrefix:s,isQuotedPrefix:n});h.push({value:x,label:p+(d?"/":"")})}return h.sort((u,d)=>{let c=u.label.endsWith("/"),p=d.label.endsWith("/");return c&&!p?-1:!c&&p?1:u.label.localeCompare(d.label)}),h}catch{return[]}}scoreEntry(e,t,r){let i=qi(e).toLowerCase(),s=t.toLowerCase(),n=0;return i===s?n=100:i.startsWith(s)?n=80:i.includes(s)?n=50:e.toLowerCase().includes(s)&&(n=30),r&&n>0&&(n+=10),n}async getBaseDirSuggestions(e,t,r){return!this.fdPath||r.aborted?[]:await No(e,this.fdPath,t,100,r,1)}async getFuzzyFileSuggestions(e,t){if(!this.fdPath||t.signal.aborted)return[];try{let r=this.resolveScopedFuzzyQuery(e),i=r?.baseDir??this.basePath,s=r?.query??e,n=await this.getBaseDirSuggestions(i,s,t.signal),o=await No(i,this.fdPath,s,100,t.signal),l=new Set(n.map(p=>p.path)),h=[...n,...o.filter(p=>l.has(p.path)?!1:(l.add(p.path),!0))];if(t.signal.aborted)return[];let u=h.map(p=>({...p,score:s?this.scoreEntry(p.path,s,p.isDirectory):1})).filter(p=>p.score>0);u.sort((p,f)=>{let g=f.score-p.score;if(g!==0)return g;let x=Me(p.path).split("/").filter(Boolean).length,m=Me(f.path).split("/").filter(Boolean).length,b=x-m;if(b!==0)return b;let C=p.path.length-f.path.length;return C!==0?C:p.path.localeCompare(f.path)});let d=u.slice(0,20),c=[];for(let{path:p,isDirectory:f}of d){let g=f?p.slice(0,-1):p,x=r?this.scopedPathForDisplay(r.displayBase,g):g,m=qi(g),b=f?`${x}/`:x,C=Fo(b,{isDirectory:f,isAtPrefix:!0,isQuotedPrefix:t.isQuotedPrefix});c.push({value:C,label:m+(f?"/":""),description:x})}return c}catch{return[]}}shouldTriggerFileCompletion(e,t,r){let i=(e[t]||"").slice(0,r);return!(i.trim().startsWith("/")&&!i.trim().includes(" "))}};import{performance as ft}from"node:perf_hooks";function kp(e){let t=e.startsWith("#")?e.slice(1):e,r=parseInt(t.slice(0,2),16),i=parseInt(t.slice(2,4),16),s=parseInt(t.slice(4,6),16);return{r,g:i,b:s}}a(kp,"hexToRgb");function gt(e){if(!/^[0-9a-f]+$/i.test(e))return;let t=16**e.length-1;if(!(t<=0))return Math.round(parseInt(e,16)/t*255)}a(gt,"parseOscHexChannel");var vp=/^\x1b\](?:(1[01])|4;(\d{1,3}));([^\x07\x1b]*)(?:\x07|\x1b\\)$/i,Sp=/^(?:\x1b\[\?997;(1|2)n)+$/;function Cp(e){let t=e.match(vp);return t?{target:t[1]==="10"?"foreground":t[1]==="11"?"background":Number.parseInt(t[2],10),rgb:Tp(t[3])}:void 0}a(Cp,"parseOscColorResponse");function Tp(e){let t=e.trim();if(t.startsWith("#")){let u=t.slice(1);if(/^[0-9a-f]{6}$/i.test(u))return kp(t);if(/^[0-9a-f]{12}$/i.test(u)){let d=gt(u.slice(0,4)),c=gt(u.slice(4,8)),p=gt(u.slice(8,12));return d!==void 0&&c!==void 0&&p!==void 0?{r:d,g:c,b:p}:void 0}return}let r=t.replace(/^rgba?:/i,""),[i,s,n]=r.split("/");if(i===void 0||s===void 0||n===void 0)return;let o=gt(i),l=gt(s),h=gt(n);return o!==void 0&&l!==void 0&&h!==void 0?{r:o,g:l,b:h}:void 0}a(Tp,"parseOscColorValue");function Ho(e){let t=e.match(Sp);if(t)return t[1]==="2"?"light":"dark"}a(Ho,"parseTerminalColorSchemeReport");import{execSync as Ap}from"node:child_process";import{homedir as Mp}from"node:os";import{isAbsolute as Bp}from"node:path";import{pathToFileURL as Rp}from"node:url";var mt=null,xt={},Vo={widthPx:9,heightPx:18};function Ui(){return Vo}a(Ui,"getCellDimensions");function qo(e){Vo=e}a(qo,"setCellDimensions");function Ep(){try{return Ap("tmux display-message -p '#{client_termfeatures}'",{encoding:"utf8",timeout:250,stdio:["ignore","pipe","ignore"]}).split(",").map(e=>e.trim()).includes("hyperlinks")}catch{return!1}}a(Ep,"probeTmuxHyperlinks");function Ip(e){let t=process.env.TERM_PROGRAM?.toLowerCase()||"",r=process.env.TERMINAL_EMULATOR?.toLowerCase()||"",i=process.env.TERM?.toLowerCase()||"",s=process.env.COLORTERM?.toLowerCase()||"",n=s==="truecolor"||s==="24bit"||i.endsWith("-direct"),o=process.platform==="win32";return process.env.TMUX||i.startsWith("tmux")?{images:null,trueColor:n,hyperlinks:e()}:i.startsWith("screen")?{images:null,trueColor:n,hyperlinks:!1}:t==="herdr"?{images:null,trueColor:n,hyperlinks:!0}:process.env.KITTY_WINDOW_ID||t==="kitty"?{images:"kitty",trueColor:!0,hyperlinks:!0}:t==="ghostty"||i.includes("ghostty")||process.env.GHOSTTY_RESOURCES_DIR?{images:"kitty",trueColor:!0,hyperlinks:!0}:process.env.WEZTERM_PANE||t==="wezterm"?{images:"kitty",trueColor:!0,hyperlinks:!0}:t==="warpterminal"||process.env.WARP_SESSION_ID||process.env.WARP_TERMINAL_SESSION_UUID?{images:"kitty",trueColor:!0,hyperlinks:!0}:process.env.ITERM_SESSION_ID||t==="iterm.app"?{images:"iterm2",trueColor:!0,hyperlinks:!0}:process.env.WT_SESSION?{images:null,trueColor:!0,hyperlinks:!0}:t==="alacritty"||t==="vscode"||t==="zed"?{images:null,trueColor:!0,hyperlinks:!0}:r==="jetbrains-jediterm"?{images:null,trueColor:!0,hyperlinks:!1}:o?{images:null,trueColor:!0,hyperlinks:!1}:{images:null,trueColor:n,hyperlinks:!1}}a(Ip,"detectCapabilitiesFromEnvironment");function Ko(e){return e==="1"?!0:e==="0"?!1:void 0}a(Ko,"parseBooleanCapabilityOverride");function ji(e=Ep){let t=Ko(process.env.PI_HYPERLINKS),r=Ip(t===void 0?e:()=>t),i=process.env.PI_IMAGE_PROTOCOL?.toLowerCase(),s=i==="kitty"||i==="iterm2"?i:i==="none"||i==="0"?null:void 0,n=Ko(process.env.PI_TRUE_COLOR);return{...r,...s!==void 0?{images:s}:{},...n!==void 0?{trueColor:n}:{},...t!==void 0?{hyperlinks:t}:{}}}a(ji,"detectCapabilities");function pe(){if(!mt){let e=xt.hyperlinks;mt={...ji(e===void 0?void 0:()=>e),...xt}}return mt}a(pe,"getCapabilities");function Fr(e=pe()){return e.trueColor?"truecolor":"256color"}a(Fr,"getTerminalColorMode");function Lp(){mt=null}a(Lp,"resetCapabilitiesCache");function Uo(e){xt.images===e.images&&xt.trueColor===e.trueColor&&xt.hyperlinks===e.hyperlinks||(xt={...e},mt=null)}a(Uo,"setCapabilityOverrides");function zi(e){mt=e}a(zi,"setCapabilities");var bt="\x1B_G",jo="\x1B]1337;File=";function z(e){return e.startsWith(bt)||e.startsWith(jo)?!0:e.includes(bt)||e.includes(jo)}a(z,"isImageLine");function zo(){return Math.floor(Math.random()*4294967294)+1}a(zo,"allocateImageId");function Go(e,t={}){let r=["a=T","f=100","q=2"];if(t.moveCursor===!1&&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}`),e.length<=4096)return`\x1B_G${r.join(",")};${e}\x1B\\`;let i=[],s=0,n=!0;for(;s<e.length;){let o=e.slice(s,s+4096),l=s+4096>=e.length;n?(i.push(`\x1B_G${r.join(",")},m=1;${o}\x1B\\`),n=!1):l?i.push(`\x1B_Gm=0;${o}\x1B\\`):i.push(`\x1B_Gm=1;${o}\x1B\\`),s+=4096}return i.join("")}a(Go,"encodeKitty");function Gi(e){return`\x1B_Ga=d,d=I,i=${e},q=2\x1B\\`}a(Gi,"deleteKittyImage");function Yo(){return"\x1B_Ga=d,d=A,q=2\x1B\\"}a(Yo,"deleteAllKittyImages");function Xo(){return"\x1B_Ga=d,d=a,q=2\x1B\\"}a(Xo,"deleteAllKittyPlacements");function Qo(e,t={}){let r=[`inline=${t.inline!==!1?1:0}`,`size=${Buffer.byteLength(e,"base64")}`];if(t.width!==void 0&&r.push(`width=${t.width}`),t.height!==void 0&&r.push(`height=${t.height}`),t.name){let i=Buffer.from(t.name).toString("base64");r.push(`name=${i}`)}return t.preserveAspectRatio===!1&&r.push("preserveAspectRatio=0"),`\x1B]1337;File=${r.join(";")}:${e}\x07`}a(Qo,"encodeITerm2");var yt=new Map,Zo=0;function Pp(e){if(Zo+=1,yt.delete(e.imageId),yt.set(e.imageId,{...e,transmissionGeneration:Zo}),yt.size>1e3){let t=yt.keys().next().value;t!==void 0&&yt.delete(t)}}a(Pp,"registerKittyImageMetadata");function Yi(e){let t=/(?:^|,)i=(\d+)(?:,|$)/.exec(e)?.[1];return t===void 0?void 0:yt.get(Number.parseInt(t,10))}a(Yi,"getRegisteredKittyImageMetadataFromControls");function $p(e){let t=/\x1b_G([^;]*);/.exec(e)?.[1];return t===void 0?void 0:Yi(t)}a($p,"getRegisteredKittyImageMetadata");function Jo(e){let t=/(?:^|,)r=(\d+)(?:,|$)/.exec(e)?.[1];if(t===void 0)return;let r=Number.parseInt(t,10);return r>0?r:void 0}a(Jo,"getExplicitKittyImageRows");function _p(e,t){return Jo(e)??t}a(_p,"getKittyImageRowsFromControls");function Xi(e){let t=$p(e);if(t)return{imageId:t.imageId,columns:t.columns,rows:t.rows,widthPx:t.widthPx,heightPx:t.heightPx}}a(Xi,"getKittyImageMetadata");var Op=new Set(["i","p","x","y","w","h","X","Y","c","r","C","U","z","P","Q","H","V"]);function Dp(e){let t=/\x1b_G([^;]*);/.exec(e)?.[1];if(t===void 0)return;let r=Jo(t);return r!==void 0?r:Yi(t)?.rows}a(Dp,"getKittyImagePlacementRows");function Fp(e){let t=/\x1b_G([^;]*);/.exec(e);if(!t)return;let r=Yi(t[1]);if(!r)return;let i=t.index,s=t[1],n;for(;;){let l=e.indexOf("\x1B\\",i+bt.length);if(l===-1)return;if(n=l+2,!/(?:^|,)m=1(?:,|$)/.test(s))break;if(i=n,!e.startsWith(bt,i))return;let h=e.indexOf(";",i+bt.length);if(h===-1)return;s=e.slice(i+bt.length,h)}let o=`\x1B_Ga=p,q=2,${t[1].split(",").filter(l=>Op.has(l.split("=",1)[0]??"")).join(",")}\x1B\\`;return{imageId:r.imageId,transmissionGeneration:r.transmissionGeneration,transmissionBytes:n-t.index,estimatedDecodedBytes:r.widthPx*r.heightPx*4,rows:_p(t[1],r.rows),sequence:o,replacementLine:`${e.slice(0,t.index)}${o}${e.slice(n)}`}}a(Fp,"getKittyImagePlacement");function el(e,t,r){let i=Xi(e),s=/\x1b_G([^;]*);/.exec(e);if(!i||!s||t<0||t>=i.rows||r<=0)return e;let n=Math.min(r,i.rows-t);if(t===0&&n===i.rows)return e;let o=Math.floor(i.heightPx*t/i.rows),l=Math.ceil(i.heightPx*(t+n)/i.rows),h=Math.max(1,Math.min(i.heightPx,l)-o),u=s[1].split(",").filter(d=>!/^[yhr]=/.test(d));return u.push(`y=${o}`,`h=${h}`,`r=${n}`),`${e.slice(0,s.index)}\x1B_G${u.join(",")};${e.slice(s.index+s[0].length)}`}a(el,"cropKittyImageLine");function tl(e,t){if(e<=1)return e;let r=e-1,i=Math.max(e/t,t/e);return Math.max(r/t,t/r)<i?r:e}a(tl,"chooseLessDistortedCellCount");function rl(e,t,r,i={widthPx:9,heightPx:18},s=!1){let n=Math.max(1,Math.floor(t)),o=r===void 0?void 0:Math.max(1,Math.floor(r)),l=Math.max(1,e.widthPx),h=Math.max(1,e.heightPx),u=n*i.widthPx/l,d=o===void 0?u:o*i.heightPx/h,c=Math.min(u,d),p=l*c,f=h*c,g=Math.max(1,Math.min(n,Math.ceil(p/i.widthPx))),x=f/i.heightPx,m=Math.max(1,Math.ceil(x));if(o!==void 0&&(m=Math.min(o,m)),!s)return{columns:g,rows:m};if(u<=d){let b=g*i.widthPx*h/(l*i.heightPx);m=tl(m,b)}else{let b=m*i.heightPx*l/(h*i.widthPx);g=tl(g,b)}return{columns:g,rows:m}}a(rl,"calculateImageCellSize");function Np(e,t,r={widthPx:9,heightPx:18}){return rl(e,t,void 0,r).rows}a(Np,"calculateImageRows");function Qi(e){try{let t=Buffer.from(e,"base64");if(t.length<24||t[0]!==137||t[1]!==80||t[2]!==78||t[3]!==71)return null;let r=t.readUInt32BE(16),i=t.readUInt32BE(20);return{widthPx:r,heightPx:i}}catch{return null}}a(Qi,"getPngDimensions");function il(e){try{let t=Buffer.from(e,"base64");if(t.length<2||t[0]!==255||t[1]!==216)return null;let r=2;for(;r<t.length-9;){if(t[r]!==255){r++;continue}let i=t[r+1];if(i>=192&&i<=194){let n=t.readUInt16BE(r+5);return{widthPx:t.readUInt16BE(r+7),heightPx:n}}if(r+3>=t.length)return null;let s=t.readUInt16BE(r+2);if(s<2)return null;r+=2+s}return null}catch{return null}}a(il,"getJpegDimensions");function sl(e){try{let t=Buffer.from(e,"base64");if(t.length<10)return null;let r=t.slice(0,6).toString("ascii");if(r!=="GIF87a"&&r!=="GIF89a")return null;let i=t.readUInt16LE(6),s=t.readUInt16LE(8);return{widthPx:i,heightPx:s}}catch{return null}}a(sl,"getGifDimensions");function nl(e){try{let t=Buffer.from(e,"base64");if(t.length<30)return null;let r=t.slice(0,4).toString("ascii"),i=t.slice(8,12).toString("ascii");if(r!=="RIFF"||i!=="WEBP")return null;let s=t.slice(12,16).toString("ascii");if(s==="VP8 "){if(t.length<30)return null;let n=t.readUInt16LE(26)&16383,o=t.readUInt16LE(28)&16383;return{widthPx:n,heightPx:o}}else if(s==="VP8L"){if(t.length<25)return null;let n=t.readUInt32LE(21),o=(n&16383)+1,l=(n>>14&16383)+1;return{widthPx:o,heightPx:l}}else if(s==="VP8X"){if(t.length<30)return null;let n=(t[24]|t[25]<<8|t[26]<<16)+1,o=(t[27]|t[28]<<8|t[29]<<16)+1;return{widthPx:n,heightPx:o}}return null}catch{return null}}a(nl,"getWebpDimensions");function Zi(e,t){return t==="image/png"?Qi(e):t==="image/jpeg"?il(e):t==="image/gif"?sl(e):t==="image/webp"?nl(e):null}a(Zi,"getImageDimensions");function ol(e,t,r={}){let i=pe();if(!i.images)return null;let s=r.maxWidthCells??80,n=rl(t,s,r.maxHeightCells,Ui(),i.images==="kitty");return i.images==="kitty"?(r.imageId!==void 0&&Pp({imageId:r.imageId,columns:n.columns,rows:n.rows,widthPx:t.widthPx,heightPx:t.heightPx}),{sequence:Go(e,{columns:n.columns,rows:n.rows,imageId:r.imageId,moveCursor:r.moveCursor}),columns:n.columns,rows:n.rows,imageId:r.imageId}):i.images==="iterm2"?{sequence:Qo(e,{width:n.columns,height:"auto",preserveAspectRatio:r.preserveAspectRatio??!0}),columns:n.columns,rows:n.rows}:null}a(ol,"renderImage");function Nr(e,t){return`\x1B]8;;${t}\x1B\\${e}\x1B]8;;\x1B\\`}a(Nr,"hyperlink");function Wp(e){let t=Mp();return t&&(e===t||e.startsWith(`${t}/`)||e.startsWith(`${t}\\`))?`~${e.slice(t.length)}`:e}a(Wp,"shortenImagePath");function Wr(e,t,r){let i=[];if(r){let s=Wp(r);pe().hyperlinks&&Bp(r)?i.push(Nr(s,Rp(r).href)):i.push(s)}return i.push(`[${e}]`),t&&i.push(`${t.widthPx}x${t.heightPx}`),`[Image: ${i.join(" ")}]`}a(Wr,"imageFallback");function wt(e,t){let r=e.handleMouse?.(t);if(r){if("target"in r){let i=r;return i.focus&&e.handleInput?{...i,focusTarget:e}:i}if(!(!r.handled&&!r.capture&&!r.focus))return{...r,handled:!0,...r.focus?{focusTarget:e}:{},target:{component:e,originX:t.screenX-t.x,originY:t.screenY-t.y,width:t.width,height:t.height}}}}a(wt,"dispatchMouseEvent");function Hp(e,t){return{...e,x:e.screenX-t.originX,y:e.screenY-t.originY,width:t.width,height:t.height}}a(Hp,"retargetMouseEvent");var Hr=16,Vp=2+Hr,qp=`\x1B]10;?\x07\x1B]11;?\x07${Array.from({length:Hr},(e,t)=>`\x1B]4;${t};?\x07`).join("")}\x1B[c`,Kp=/^\x1b\[\?[\d;]*c$/;function Ji(e){return e!==null&&"focused"in e}a(Ji,"isFocusable");var Fe="\x1B_pi:c\x07",es="\x1B_pi:fc\x07",ll="\x1B_pi:/fc\x07",Up=/(\x1b_pi:c\x07)\x1b_pi:fc\x07(.*?)(?:\x1b_pi:\/fc\x07|$)/s;function Zt(e){return`${es}${e}${ll}`}a(Zt,"renderFakeCursor");function al(e,t){if(e===void 0)return;if(typeof e=="number")return e;let r=e.match(/^(\d+(?:\.\d+)?)%$/);if(r)return Math.floor(t*parseFloat(r[1])/100)}a(al,"parseSizeValue");var Jt=new WeakMap;function kt(e){let t=e,r=Jt.get(t);for(;r;)r.children[r.children.length-1]!==t&&r.layoutGeneration++,t=r,r=Jt.get(r)}a(kt,"bumpLayoutAncestors");var Ne=class{static{a(this,"Container")}children=[];mouseLayout;layoutGeneration=0;addChild(e){this.children.push(e),Jt.set(e,this),this.layoutGeneration++,kt(this)}removeChild(e){let t=this.children.indexOf(e);t!==-1&&(this.children.splice(t,1),Jt.delete(e),this.layoutGeneration++,kt(this))}clear(){for(let e of this.children)Jt.delete(e);this.children=[],this.layoutGeneration++,kt(this)}invalidate(){this.layoutGeneration++,kt(this);for(let e of this.children)e.invalidate?.()}handleMouse(e){if(e.y<0||e.y>=e.height)return;let t=this.mouseLayout?.width===e.width?this.mouseLayout.children:this.children.map(i=>({component:i,height:i.render(e.width).length})),r=0;for(let{component:i,height:s}of t){if(e.y>=r&&e.y<r+s){let n=wt(i,{...e,y:e.y-r,height:s});return n?.focus&&this.handleInput?{...n,focusTarget:this}:n}r+=s}}render(e){let t=[],r=[];for(let i of this.children){let s=i.render(e);r.push({component:i,height:s.length});for(let n of s)t.push(n)}return this.mouseLayout={width:e,children:r},t}};function ts(){return pe().hyperlinks?"\x1B[0m\x1B]8;;\x07":"\x1B[0m"}a(ts,"segmentReset");function Xe(e,t,r,i,s){if(z(e))return e;let n=r+i,o=Hc(e,r,n,s-n,!0),l=qn(t,0,i,!0),h=Math.max(0,r-o.beforeWidth),u=Math.max(0,i-l.width),d=Math.max(r,o.beforeWidth),c=Math.max(i,l.width),p=Math.max(0,s-d-c),f=Math.max(0,p-o.afterWidth),g=o.before+" ".repeat(h)+ts()+l.text+" ".repeat(u)+ts()+o.after+" ".repeat(f);return T(g)<=s?g:Y(g,0,s,!0)}a(Xe,"compositeTuiLine");var hl=Symbol.for("@earendil-works/pi-tui/viewport");function ul(e){return e[hl]===!0}a(ul,"isViewportTUI");var cl=class oi extends Ne{static{a(this,"_TuiBase")}terminal;focusedComponent=null;inputListeners=new Set;onDebug;renderRequested=!1;immediateRenderScheduled=!1;renderTimer;lastRenderAt=0;static MIN_RENDER_INTERVAL_MS=16;frameStatsEnabled=process.env.DAL_FRAME_STATS==="1";frameDurations=[];frameStatsWrite=0;static FRAME_STATS_CAP=256;showHardwareCursor=process.env.PI_HARDWARE_CURSOR==="1";clearOnShrink=process.env.PI_CLEAR_ON_SHRINK==="1";fullRedrawCount=0;stopped=!1;pendingTerminalColorQueries=[];terminalColorSchemeListeners=new Set;terminalColorSchemeNotificationsEnabled=!1;logDirectory;focusOrderCounter=0;overlayStack=[];renderedOverlayLayouts=[];get hasOverlayEntries(){return this.overlayStack.length>0}overlayFocusRestore={status:"inactive"};constructor(t,r,i){super(),this.terminal=t,this.logDirectory=i,r!==void 0&&(this.showHardwareCursor=r)}resetRenderState(){}beforeTerminalStart(){}afterTerminalStart(){}beforeTerminalStop(t){}afterTerminalStop(t){}get fullRedraws(){return this.fullRedrawCount}getShowHardwareCursor(){return this.showHardwareCursor}setShowHardwareCursor(t){this.showHardwareCursor!==t&&(this.showHardwareCursor=t,t||this.hideTerminalCursor(),this.requestRender())}getClearOnShrink(){return this.clearOnShrink}setClearOnShrink(t){this.clearOnShrink=t}getFocusedComponent(){return this.focusedComponent}setFocus(t){this.setFocusInternal({component:t,overlayFocusRestore:"clear"})}setFocusInternal({component:t,overlayFocusRestore:r}){let i=this.focusedComponent,s=t,n=i?this.overlayStack.find(u=>u.component===i&&this.isOverlayVisible(u)):void 0,o=s?this.overlayStack.some(u=>u.component===s):!1,l=this.getVisibleOverlayFocusRestore();s&&!o?l.status==="blocked"&&l.blockedBy===i?l.resume.status==="focus-target"||!this.isComponentMounted(l.blockedBy)?s=this.resolveBlockedOverlayFocusResume(l):this.overlayFocusRestore={status:"blocked",overlay:l.overlay,blockedBy:s,resume:l.resume}:n&&l.status!=="inactive"&&l.overlay===n&&!this.isOverlayFocusAncestor(n,s)&&(this.overlayFocusRestore={status:"blocked",overlay:n,blockedBy:s,resume:{status:"restore-overlay"}}):s===null&&(l.status==="blocked"&&l.blockedBy===i?s=this.resolveBlockedOverlayFocusResume(l):r==="clear"&&this.clearOverlayFocusRestore()),Ji(this.focusedComponent)&&(this.focusedComponent.focused=!1),this.focusedComponent=s,Ji(s)&&(s.focused=!0);let h=s?this.overlayStack.find(u=>u.component===s&&this.isOverlayVisible(u)):void 0;h&&(this.overlayFocusRestore={status:"eligible",overlay:h})}clearOverlayFocusRestore(){this.overlayFocusRestore={status:"inactive"}}clearOverlayFocusRestoreFor(t){this.overlayFocusRestore.status!=="inactive"&&this.overlayFocusRestore.overlay===t&&this.clearOverlayFocusRestore()}resolveBlockedOverlayFocusResume(t){return t.resume.status==="restore-overlay"?t.overlay.component:(this.clearOverlayFocusRestore(),t.resume.target)}getVisibleOverlayFocusRestore(){let t=this.overlayFocusRestore;return t.status==="inactive"?t:!this.overlayStack.includes(t.overlay)||!this.isOverlayVisible(t.overlay)?{status:"inactive"}:t}isOverlayFocusAncestor(t,r){let i=new Set,s=t.preFocus;for(;s&&!i.has(s);){if(i.add(s),s===r)return!0;s=this.overlayStack.find(n=>n.component===s)?.preFocus??null}return!1}retargetOverlayPreFocus(t){for(let r of this.overlayStack)r!==t&&r.preFocus===t.component&&(r.preFocus=t.preFocus)}getMountedRoots(){return this.children}isComponentMounted(t){return this.getMountedRoots().some(r=>this.containsComponent(r,t))}containsComponent(t,r){return t===r?!0:t instanceof Ne?t.children.some(i=>this.containsComponent(i,r)):!1}showOverlay(t,r){let i={component:t,...r===void 0?{}:{options:r},preFocus:this.focusedComponent,hidden:!1,focusOrder:++this.focusOrderCounter};return this.overlayStack.push(i),!r?.nonCapturing&&this.isOverlayVisible(i)&&this.setFocus(t),this.hideTerminalCursor(),this.requestRender(),{hide:a(()=>{let s=this.overlayStack.indexOf(i);if(s!==-1){if(this.clearOverlayFocusRestoreFor(i),this.retargetOverlayPreFocus(i),this.overlayStack.splice(s,1),this.focusedComponent===t){let n=this.getTopmostVisibleOverlay();this.setFocus(n?.component??i.preFocus)}this.overlayStack.length===0&&this.hideTerminalCursor(),this.requestRender()}},"hide"),setHidden:a(s=>{if(i.hidden!==s){if(i.hidden=s,s){if(this.clearOverlayFocusRestoreFor(i),this.focusedComponent===t){let n=this.getTopmostVisibleOverlay();this.setFocus(n?.component??i.preFocus)}}else!r?.nonCapturing&&this.isOverlayVisible(i)&&(i.focusOrder=++this.focusOrderCounter,this.setFocus(t));this.requestRender()}},"setHidden"),isHidden:a(()=>i.hidden,"isHidden"),focus:a(()=>{!this.overlayStack.includes(i)||!this.isOverlayVisible(i)||(i.focusOrder=++this.focusOrderCounter,this.setFocus(t),this.requestRender())},"focus"),unfocus:a(s=>{let n=this.focusedComponent===t,o=this.overlayFocusRestore,l=o.status!=="inactive"&&o.overlay===i;if(!(!n&&!l)){if(o.status==="blocked"&&o.overlay===i&&this.focusedComponent===o.blockedBy){s?this.overlayFocusRestore={status:"blocked",overlay:i,blockedBy:o.blockedBy,resume:{status:"focus-target",target:s.target}}:this.clearOverlayFocusRestore(),this.requestRender();return}if(this.clearOverlayFocusRestoreFor(i),n||s){let h=this.getTopmostVisibleOverlay(),u=h&&h!==i?h.component:i.preFocus;this.setFocus(s?s.target:u)}this.requestRender()}},"unfocus"),isFocused:a(()=>this.focusedComponent===t,"isFocused"),getBounds:a(()=>{if(!(!this.overlayStack.includes(i)||!this.isOverlayVisible(i)||!i.bounds))return{...i.bounds}},"getBounds")}}hideOverlay(){let t=this.overlayStack[this.overlayStack.length-1];if(t){if(this.clearOverlayFocusRestoreFor(t),this.retargetOverlayPreFocus(t),this.overlayStack.pop(),this.focusedComponent===t.component){let r=this.getTopmostVisibleOverlay();this.setFocus(r?.component??t.preFocus)}this.overlayStack.length===0&&this.hideTerminalCursor(),this.requestRender()}}hideTerminalCursor(){this.stopped||this.terminal.hideCursor()}hasOverlay(){return this.overlayStack.some(t=>this.isOverlayVisible(t))}isOverlayFocused(){return this.overlayStack.some(t=>t.component===this.focusedComponent&&this.isOverlayVisible(t))}resolveMouseFocusTarget(t){for(let r=this.overlayStack.length-1;r>=0;r--){let i=this.overlayStack[r];if(this.isOverlayVisible(i)&&this.containsComponent(i.component,t))return i.component}return t}dispatchMouseToOverlay(t){for(let r=this.renderedOverlayLayouts.length-1;r>=0;r--){let i=this.renderedOverlayLayouts[r];if(t.screenX<i.col||t.screenX>=i.col+i.width||t.screenY<i.row||t.screenY>=i.row+i.height)continue;let s=wt(i.entry.component,{...t,x:t.screenX-i.col,y:t.screenY-i.row,width:i.width,height:i.height});return s?{hit:!0,result:s.focus?{...s,focusTarget:i.entry.component}:s}:{hit:!0}}return{hit:!1}}isOverlayVisible(t){return t.hidden?!1:t.options?.visible?t.options.visible(this.terminal.columns,this.terminal.rows):!0}getTopmostVisibleOverlay(){let t;for(let r of this.overlayStack)r.options?.nonCapturing||!this.isOverlayVisible(r)||(!t||r.focusOrder>t.focusOrder)&&(t=r);return t}invalidate(){for(let t of this.getMountedRoots())t.invalidate();for(let t of this.overlayStack)t.component.invalidate()}start(){this.stopped=!1,this.beforeTerminalStart(),this.terminal.start(t=>this.handleTerminalInput(t),()=>this.requestRender()),this.afterTerminalStart(),this.terminal.hideCursor(),this.terminalColorSchemeNotificationsEnabled&&this.terminal.write("\x1B[?2031h"),this.queryCellSize(),this.requestRender()}addInputListener(t){return this.inputListeners.add(t),()=>{this.inputListeners.delete(t)}}removeInputListener(t){this.inputListeners.delete(t)}onTerminalColorSchemeChange(t){return this.terminalColorSchemeListeners.add(t),()=>{this.terminalColorSchemeListeners.delete(t)}}setTerminalColorSchemeNotifications(t){this.terminalColorSchemeNotificationsEnabled!==t&&(this.terminalColorSchemeNotificationsEnabled=t,this.stopped||this.terminal.write(t?"\x1B[?2031h":"\x1B[?2031l"))}queryCellSize(){pe().images&&this.terminal.write("\x1B[16t")}stop(t={}){this.flushFrameStats(),this.stopped=!0,this.cancelRenderTimer(),this.terminalColorSchemeNotificationsEnabled&&this.terminal.write("\x1B[?2031l"),this.beforeTerminalStop(t),this.terminal.showCursor(),this.terminal.stop(),this.afterTerminalStop(t)}renderNow(t=!1){t&&this.resetRenderState(),this.renderRequested=!1,this.cancelRenderTimer(),this.lastRenderAt=ft.now(),this.runDoRender()}requestRender(t=!1){if(t){this.resetRenderState(),this.requestImmediateRender();return}this.renderRequested||(this.renderRequested=!0,process.nextTick(()=>this.scheduleRender()))}requestImmediateRender(){this.cancelRenderTimer(),this.renderRequested=!0,!this.immediateRenderScheduled&&(this.immediateRenderScheduled=!0,process.nextTick(()=>{this.immediateRenderScheduled=!1,!(this.stopped||!this.renderRequested)&&(this.cancelRenderTimer(),this.renderRequested=!1,this.lastRenderAt=ft.now(),this.runDoRender())}))}cancelRenderTimer(){this.renderTimer&&(clearTimeout(this.renderTimer),this.renderTimer=void 0)}runDoRender(){let t=ft.now();if(this.doRender(),this.frameStatsEnabled){let r=ft.now()-t;this.frameDurations.length<oi.FRAME_STATS_CAP?this.frameDurations.push(r):(this.frameDurations[this.frameStatsWrite]=r,this.frameStatsWrite=(this.frameStatsWrite+1)%oi.FRAME_STATS_CAP)}}flushFrameStats(){if(!this.frameStatsEnabled||this.frameDurations.length===0)return;let t=[...this.frameDurations].sort((s,n)=>s-n),r=a(s=>t[Math.min(t.length-1,Math.floor(t.length*s))],"at2"),i=(process.env.TERM??"").slice(0,24);process.stderr.write(`tui_frame p50_ms=${r(.5).toFixed(2)} p95_ms=${r(.95).toFixed(2)} frames=${t.length} cols=${this.terminal.columns} rows=${this.terminal.rows} term=${i}
|
|
75
|
-
`)}scheduleRender(){if(this.stopped||this.renderTimer||!this.renderRequested)return;let t=ft.now()-this.lastRenderAt,r=Math.max(0,oi.MIN_RENDER_INTERVAL_MS-t);this.renderTimer=setTimeout(()=>{this.renderTimer=void 0,!(this.stopped||!this.renderRequested)&&(this.renderRequested=!1,this.lastRenderAt=ft.now(),this.runDoRender(),this.renderRequested&&this.scheduleRender())},r)}handleTerminalInput(t){if(this.consumeTerminalColorResponse(t)||this.consumeTerminalColorSchemeReport(t))return;if(this.inputListeners.size>0){let i=t;for(let s of this.inputListeners){let n=s(i);if(n?.consume)return;n?.data!==void 0&&(i=n.data)}if(i.length===0)return;t=i}if(this.consumeCellSizeResponse(t))return;if(_e(t,"shift+ctrl+d")&&this.onDebug){this.onDebug();return}let r=this.overlayStack.find(i=>i.component===this.focusedComponent);if(r&&!this.isOverlayVisible(r)){let i=this.getTopmostVisibleOverlay();i?this.setFocus(i.component):this.setFocusInternal({component:r.preFocus,overlayFocusRestore:"preserve"})}if(!this.overlayStack.some(i=>i.component===this.focusedComponent)){let i=this.getVisibleOverlayFocusRestore();i.status==="eligible"?this.setFocus(i.overlay.component):i.status==="blocked"&&i.blockedBy!==this.focusedComponent&&(i.resume.status==="restore-overlay"?this.setFocus(i.overlay.component):(this.clearOverlayFocusRestore(),this.setFocus(i.resume.target)))}if(this.focusedComponent?.handleInput){if(Ei(t)&&!this.focusedComponent.wantsKeyRelease)return;this.focusedComponent.handleInput(t),this.requestImmediateRender()}}consumeTerminalColorResponse(t){let r=this.pendingTerminalColorQueries[0];if(!r)return!1;if(Kp.test(t))return this.pendingTerminalColorQueries.shift(),this.completeTerminalColorQuery(r),!0;let i=Cp(t);if(!i)return!1;let{target:s,rgb:n}=i,o=String(s);return!r.deliver||r.replied.has(o)||(r.replied.add(o),s==="foreground"?r.foreground=n:s==="background"?r.background=n:s<Hr&&(r.palette[s]=n),r.replied.size===Vp&&this.completeTerminalColorQuery(r)),!0}terminalColorQueryResult(t){let r=t.palette.every(i=>i!==void 0)?t.palette:void 0;return{foreground:t.foreground,background:t.background,palette:r}}completeTerminalColorQuery(t){let r=t.deliver;t.deliver=void 0,clearTimeout(t.timer),r?.(this.terminalColorQueryResult(t))}consumeTerminalColorSchemeReport(t){let r=Ho(t);if(!r)return!1;for(let i of this.terminalColorSchemeListeners)i(r);return!0}consumeCellSizeResponse(t){let r=t.match(/^\x1b\[6;(\d+);(\d+)t$/);if(!r)return!1;let i=parseInt(r[1],10),s=parseInt(r[2],10);return i<=0||s<=0||(qo({widthPx:s,heightPx:i}),this.invalidate(),this.requestRender()),!0}resolveOverlayLayout(t,r,i,s){let n=t??{},o=typeof n.margin=="number"?{top:n.margin,right:n.margin,bottom:n.margin,left:n.margin}:n.margin??{},l=Math.max(0,o.top??0),h=Math.max(0,o.right??0),u=Math.max(0,o.bottom??0),d=Math.max(0,o.left??0),c=Math.max(1,i-d-h),p=Math.max(1,s-l-u),f=al(n.width,i)??Math.min(80,c);n.minWidth!==void 0&&(f=Math.max(f,n.minWidth)),f=Math.max(1,Math.min(f,c));let g=al(n.maxHeight,s);g!==void 0&&(g=Math.max(1,Math.min(g,p)));let x=g!==void 0?Math.min(r,g):r,m,b;if(n.row!==void 0)if(typeof n.row=="string"){let C=n.row.match(/^(\d+(?:\.\d+)?)%$/);if(C){let S=Math.max(0,p-x),y=parseFloat(C[1])/100;m=l+Math.floor(S*y)}else m=this.resolveAnchorRow("center",x,p,l)}else m=n.row;else{let C=n.anchor??"center";m=this.resolveAnchorRow(C,x,p,l)}if(n.col!==void 0)if(typeof n.col=="string"){let C=n.col.match(/^(\d+(?:\.\d+)?)%$/);if(C){let S=Math.max(0,c-f),y=parseFloat(C[1])/100;b=d+Math.floor(S*y)}else b=this.resolveAnchorCol("center",f,c,d)}else b=n.col;else{let C=n.anchor??"center";b=this.resolveAnchorCol(C,f,c,d)}return n.offsetY!==void 0&&(m+=n.offsetY),n.offsetX!==void 0&&(b+=n.offsetX),m=Math.max(l,Math.min(m,s-u-x)),b=Math.max(d,Math.min(b,i-h-f)),{width:f,row:m,col:b,maxHeight:g}}resolveAnchorRow(t,r,i,s){switch(t){case"top-left":case"top-center":case"top-right":return s;case"bottom-left":case"bottom-center":case"bottom-right":return s+i-r;case"left-center":case"center":case"right-center":return s+Math.floor((i-r)/2)}}resolveAnchorCol(t,r,i,s){switch(t){case"top-left":case"left-center":case"bottom-left":return s;case"top-right":case"right-center":case"bottom-right":return s+i-r;case"top-center":case"center":case"bottom-center":return s+Math.floor((i-r)/2)}}compositeOverlays(t,r,i){if(this.overlayStack.length===0)return this.renderedOverlayLayouts=[],t;let s=[...t];for(let d of this.overlayStack)d.bounds=void 0;let n=[],o=s.length,l=this.overlayStack.filter(d=>this.isOverlayVisible(d));l.sort((d,c)=>d.focusOrder-c.focusOrder);for(let d of l){let{component:c,options:p}=d,{width:f,maxHeight:g}=this.resolveOverlayLayout(p,0,r,i),x=this.resolveFakeCursors(c.render(f));g!==void 0&&x.length>g&&(x=x.slice(0,g));let{row:m,col:b}=this.resolveOverlayLayout(p,x.length,r,i);d.bounds={row:m,col:b,width:f,height:x.length},n.push({entry:d,overlayLines:x,row:m,col:b,w:f}),o=Math.max(o,m+x.length)}this.renderedOverlayLayouts=n.map(({entry:d,row:c,col:p,w:f,overlayLines:g})=>({entry:d,row:c,col:p,width:f,height:g.length}));let h=Math.max(s.length,i,o);for(;s.length<h;)s.push("");let u=Math.max(0,h-i);for(let{overlayLines:d,row:c,col:p,w:f}of n)for(let g=0;g<d.length;g++){let x=u+c+g;if(x>=0&&x<s.length){let m=T(d[g])>f?Y(d[g],0,f,!0):d[g];s[x]=this.compositeLineAt(s[x],m,p,f,r)}}return s}applyLineResets(t){let r=ts();for(let i=0;i<t.length;i++){let s=t[i];z(s)||(t[i]=Lc(s)+r)}return t}compositeLineAt(t,r,i,s,n){return Xe(t,r,i,s,n)}extractCursorPosition(t,r){let i=Math.max(0,t.length-r);for(let s=t.length-1;s>=i;s--){let n=t[s],o=n.indexOf(Fe);if(o!==-1){let l=n.slice(0,o),h=T(l);return t[s]=n.slice(0,o)+n.slice(o+Fe.length),{row:s,col:h}}}return null}resolveFakeCursors(t){return t.map(r=>r.includes(es)?(this.showHardwareCursor?r.replace(Up,"$1$2"):r).replaceAll(es,"\x1B[7m").replaceAll(ll,"\x1B[27m"):r)}queryTerminalColors({timeoutMs:t,onLateReply:r}){return new Promise(i=>{let s={palette:Array.from({length:Hr},()=>{}),replied:new Set,deliver:i,timer:void 0};s.timer=setTimeout(()=>{s.deliver=r,i(this.terminalColorQueryResult(s))},t),this.pendingTerminalColorQueries.push(s),this.terminal.write(qp)})}},dl=class{static{a(this,"Box")}children=[];paddingX;paddingY;bgFn;cache;mouseLayout;constructor(e=1,t=1,r){this.paddingX=e,this.paddingY=t,this.bgFn=r}addChild(e){this.children.push(e),this.invalidateCache()}removeChild(e){let t=this.children.indexOf(e);t!==-1&&(this.children.splice(t,1),this.invalidateCache())}clear(){this.children=[],this.invalidateCache()}setBgFn(e){this.bgFn=e}setPaddingX(e){this.paddingX=e,this.invalidateCache()}invalidateCache(){this.cache=void 0}matchCache(e,t,r){let i=this.cache;return!!i&&i.width===e&&i.bgSample===r&&i.childLines.length===t.length&&i.childLines.every((s,n)=>s===t[n])}invalidate(){this.invalidateCache();for(let e of this.children)e.invalidate?.()}handleMouse(e){let t=Math.max(1,e.width-this.paddingX*2),r=e.y-this.paddingY,i=e.x-this.paddingX;if(r<0||i<0||i>=t)return;let s=this.mouseLayout?.width===t?this.mouseLayout.children:this.children.map(o=>({component:o,height:o.render(t).length})),n=0;for(let{component:o,height:l}of s){if(r>=n&&r<n+l)return wt(o,{...e,x:i,y:r-n,width:t,height:l});n+=l}}render(e){if(this.children.length===0)return[];let t=Math.max(1,e-this.paddingX*2),r=" ".repeat(this.paddingX),i=[],s=[];for(let l of this.children){let h=l.render(t);s.push({component:l,height:h.length});for(let u of h)i.push(u)}if(this.mouseLayout={width:t,children:s},i.length===0)return[];let n=this.bgFn?this.bgFn("test"):void 0;if(this.matchCache(e,i,n))return this.cache.lines;let o=[];for(let l=0;l<this.paddingY;l++)o.push(this.applyBg("",e));for(let l of i)o.push(this.applyBg(r+l,e));for(let l=0;l<this.paddingY;l++)o.push(this.applyBg("",e));return vi(o),this.cache={childLines:i,width:e,bgSample:n,lines:o},o}applyBg(e,t){let r=T(e),i=Math.max(0,t-r),s=e+" ".repeat(i);return this.bgFn?this.bgFn(s):s}},rs=class{static{a(this,"Text")}text;paddingX;paddingY;customBgFn;cachedText;cachedWidth;cachedLines;constructor(e="",t=1,r=1,i){this.text=e,this.paddingX=t,this.paddingY=r,this.customBgFn=i}setText(e){this.text=e,this.invalidate()}setCustomBgFn(e){this.customBgFn=e,this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}setPaddingX(e){this.paddingX=e,this.invalidate()}invalidate(){this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0,kt(this)}render(e){if(this.cachedLines&&this.cachedText===this.text&&this.cachedWidth===e)return this.cachedLines;if(!this.text||this.text.trim()===""){let c=[];return this.cachedText=this.text,this.cachedWidth=e,this.cachedLines=c,c}let t=this.text.replace(/\t/g," "),r=Math.min(this.paddingX,Math.max(0,Math.floor((e-1)/2))),i=Math.max(1,e-r*2),s=ve(t,i),n=" ".repeat(r),o=" ".repeat(r),l=[];for(let c of s){let p=n+c+o;if(this.customBgFn)l.push(mr(p,e,this.customBgFn));else{let f=T(p),g=Math.max(0,e-f);l.push(p+" ".repeat(g))}}let h=" ".repeat(e),u=[];for(let c=0;c<this.paddingY;c++){let p=this.customBgFn?mr(h,e,this.customBgFn):h;u.push(p)}let d=[...u,...l,...u];return vi(d),this.cachedText=this.text,this.cachedWidth=e,this.cachedLines=d,d.length>0?d:[""]}},pl=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],fl=80,is=class extends rs{static{a(this,"Loader")}frames=[...pl];intervalMs=fl;currentFrame=0;intervalId=null;ui=null;renderIndicatorVerbatim=!1;spinnerColorFn;messageColorFn;message="Loading...";constructor(e,t,r,i="Loading...",s){super("",1,0),this.ui=e,this.spinnerColorFn=t,this.messageColorFn=r,this.message=i,this.setIndicator(s)}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]:[...pl],this.intervalMs=e?.intervalMs&&e.intervalMs>0?e.intervalMs:fl,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)}updatingDisplay=!1;updateDisplay(){if(!this.updatingDisplay){this.updatingDisplay=!0;try{let e=this.getRenderedIndicator(),t=e.length>0?`${e} `:"";this.setText(`${t}${this.messageColorFn(this.message)}`),this.ui&&this.ui.requestRender()}finally{this.updatingDisplay=!1}}}},gl=class extends is{static{a(this,"CancellableLoader")}abortController=new AbortController;onAbort;get signal(){return this.abortController.signal}get aborted(){return this.abortController.signal.aborted}handleInput(e){ue().matches(e,"tui.select.cancel")&&(this.abortController.abort(),this.onAbort?.())}dispose(){this.stop()}},ml=class{static{a(this,"KillRing")}ring=[];push(e,t){if(e)if(t.accumulate&&this.ring.length>0){let r=this.ring.pop();this.ring.push(t.prepend?e+r:r+e)}else this.ring.push(e)}peek(){return this.ring.length>0?this.ring[this.ring.length-1]:void 0}rotate(){if(this.ring.length>1){let e=this.ring.pop();this.ring.unshift(e)}}get length(){return this.ring.length}},xl=class{static{a(this,"UndoStack")}stack=[];push(e){this.stack.push(structuredClone(e))}pop(){return this.stack.pop()}clear(){this.stack.length=0}get length(){return this.stack.length}},bl=xi();function yl(e,t,r){if(t<=0)return 0;let i=e.slice(0,t),s=r?.segment,n=r?.isAtomicSegment,o=s?[...s(i)]:[...bl.segment(i)],l=t;for(;o.length>0&&!n?.(o[o.length-1]?.segment||"")&&xe(o[o.length-1]?.segment||"");)l-=o.pop()?.segment.length||0;if(o.length===0)return l;let h=o[o.length-1];if(n?.(h.segment))l-=h.segment.length;else if(h.isWordLike){let u=h.segment,d=[...u.matchAll(new RegExp(Vn,"g"))];if(d.length<=0)l-=u.length;else{let c=d[d.length-1];l-=u.length-(c.index+c[0].length)}}else for(;o.length>0&&!n?.(o[o.length-1]?.segment||"")&&!o[o.length-1]?.isWordLike&&!xe(o[o.length-1]?.segment||"");)l-=o.pop()?.segment.length||0;return l}a(yl,"findWordBackward");function wl(e,t,r){if(t>=e.length)return e.length;let i=e.slice(t),s=r?.segment,n=r?.isAtomicSegment,o=(s?s(i):bl.segment(i))[Symbol.iterator](),l=o.next(),h=t;for(;!l.done&&!n?.(l.value.segment)&&xe(l.value.segment);)h+=l.value.segment.length,l=o.next();if(l.done)return h;if(n?.(l.value.segment))h+=l.value.segment.length;else if(l.value.isWordLike)h+=Vn.exec(l.value.segment)?.index??l.value.segment.length;else for(;!l.done&&!n?.(l.value.segment)&&!l.value.isWordLike&&!xe(l.value.segment);)h+=l.value.segment.length,l=o.next();return h}a(wl,"findWordForward");var kl=32,vl=2,jp=10,zp=a(e=>e.replace(/[\r\n]+/g," ").trim(),"normalizeToSingleLine"),Gp=a((e,t,r)=>Math.max(t,Math.min(e,r)),"clamp"),ss=class{static{a(this,"SelectList")}items=[];filteredItems=[];selectedIndex=0;mousePressedIndex;maxVisible=5;theme;layout;onSelect;onCancel;onSelectionChange;constructor(e,t,r,i={}){this.items=e,this.filteredItems=e,this.maxVisible=t,this.theme=r,this.layout=i}setFilter(e){this.filteredItems=this.items.filter(t=>t.value.toLowerCase().startsWith(e.toLowerCase())),this.selectedIndex=0}setSelectedIndex(e){this.selectedIndex=Math.max(0,Math.min(e,this.filteredItems.length-1))}invalidate(){}render(e){let t=[];if(this.filteredItems.length===0)return t.push(this.theme.noMatch(" No matching commands")),t;let r=this.getPrimaryColumnWidth(),{startIndex:i,endIndex:s}=this.getVisibleRange();for(let n=i;n<s;n++){let o=this.filteredItems[n];if(!o)continue;let l=n===this.selectedIndex,h=o.description?zp(o.description):void 0;t.push(this.renderItem(o,l,e,h,r))}if(i>0||s<this.filteredItems.length){let n=` (${this.selectedIndex+1}/${this.filteredItems.length})`;t.push(this.theme.scrollInfo(K(n,e-2,"")))}return t}handleMouse(e){if(this.filteredItems.length===0)return;if(e.type==="wheel"&&e.wheelDelta){let s=e.wheelDelta<0?-1:1,n=this.selectedIndex;return this.selectedIndex=Math.max(0,Math.min(this.filteredItems.length-1,this.selectedIndex+s)),this.selectedIndex!==n&&this.notifySelectionChange(),{handled:!0,render:this.selectedIndex!==n}}if(e.button!=="left"||e.type!=="press"&&e.type!=="click")return;let{startIndex:t,endIndex:r}=this.getVisibleRange(),i=t+e.y;if(!(i<t||i>=r)){if(e.type==="press")return this.mousePressedIndex=i,this.selectedIndex!==i&&(this.selectedIndex=i,this.notifySelectionChange()),{handled:!0,focus:!0};if(e.type==="click"){let s=this.mousePressedIndex??i;this.mousePressedIndex=void 0;let n=this.selectedIndex!==s;this.selectedIndex=s,n&&this.notifySelectionChange();let o=this.filteredItems[this.selectedIndex];return o&&this.onSelect?.(o),{handled:!0}}}}handleInput(e){let t=ue();if(t.matches(e,"tui.select.up"))this.selectedIndex=this.selectedIndex===0?this.filteredItems.length-1:this.selectedIndex-1,this.notifySelectionChange();else if(t.matches(e,"tui.select.down"))this.selectedIndex=this.selectedIndex===this.filteredItems.length-1?0:this.selectedIndex+1,this.notifySelectionChange();else if(t.matches(e,"tui.select.confirm")){let r=this.filteredItems[this.selectedIndex];r&&this.onSelect&&this.onSelect(r)}else t.matches(e,"tui.select.cancel")&&this.onCancel&&this.onCancel()}getVisibleRange(){let e=Math.max(0,Math.min(this.selectedIndex-Math.floor(this.maxVisible/2),this.filteredItems.length-this.maxVisible));return{startIndex:e,endIndex:Math.min(e+this.maxVisible,this.filteredItems.length)}}renderItem(e,t,r,i,s){let n=t?"\u2192 ":" ",o=T(n);if(i&&r>40){let u=Math.max(1,Math.min(s,r-o-4)),d=Math.max(1,u-vl),c=this.truncatePrimary(e,t,d,u),p=T(c),f=" ".repeat(Math.max(1,u-p)),g=o+p+f.length,x=r-g-2;if(x>jp){let m=K(i,x,"");if(t)return this.theme.selectedText(`${n}${c}${f}${m}`);let b=this.theme.description(f+m);return n+c+b}}let l=r-o-2,h=this.truncatePrimary(e,t,l,l);return t?this.theme.selectedText(`${n}${h}`):n+h}getPrimaryColumnWidth(){let{min:e,max:t}=this.getPrimaryColumnBounds(),r=this.filteredItems.reduce((i,s)=>Math.max(i,T(this.getDisplayValue(s))+vl),0);return Gp(r,e,t)}getPrimaryColumnBounds(){let e=this.layout.minPrimaryColumnWidth??this.layout.maxPrimaryColumnWidth??kl,t=this.layout.maxPrimaryColumnWidth??this.layout.minPrimaryColumnWidth??kl;return{min:Math.max(1,Math.min(e,t)),max:Math.max(1,Math.max(e,t))}}truncatePrimary(e,t,r,i){let s=this.getDisplayValue(e),n=this.layout.truncatePrimary?this.layout.truncatePrimary({text:s,maxWidth:r,columnWidth:i,item:e,isSelected:t}):K(s,r,"");return K(n,r,"")}getDisplayValue(e){return e.label||e.value}notifySelectionChange(){let e=this.filteredItems[this.selectedIndex];e&&this.onSelectionChange&&this.onSelectionChange(e)}getSelectedItem(){return this.filteredItems[this.selectedIndex]||null}},Sl=mi(),Yp=xi(),Cl=/\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]/g,Tl=/^\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]$/;function vt(e){return e.length>=10&&Tl.test(e)}a(vt,"isPasteMarker");function Xp(e,t,r){if(r.size===0||!e.includes("[paste #"))return t.segment(e);let i=[];for(let l of e.matchAll(Cl)){let h=Number.parseInt(l[1],10);r.has(h)&&i.push({start:l.index,end:l.index+l[0].length})}if(i.length===0)return t.segment(e);let s=t.segment(e),n=[],o=0;for(let l of s){for(;o<i.length&&i[o].end<=l.index;)o++;let h=o<i.length?i[o]:null;if(h&&l.index>=h.start&&l.index<h.end){if(l.index===h.start){let u=e.slice(h.start,h.end);n.push({segment:u,index:h.start,input:e})}}else n.push(l)}return n}a(Xp,"segmentWithMarkers");function ns(e,t,r){if(!e||t<=0)return[{text:"",startIndex:0,endIndex:0}];if(T(e)<=t)return[{text:e,startIndex:0,endIndex:e.length}];let i=[],s=r??[...Sl.segment(e)],n=0,o=0,l=-1,h=0;for(let u=0;u<s.length;u++){let d=s[u],c=d.segment,p=T(c),f=d.index,g=!vt(c)&&xe(c);if(n+p>t&&(l>=0&&n-h+p<=t?(i.push({text:e.slice(o,l),startIndex:o,endIndex:l}),o=l,n-=h):o<f&&(i.push({text:e.slice(o,f),startIndex:o,endIndex:f}),o=f,n=0),l=-1),p>t){let m=ns(c,t);for(let C=0;C<m.length-1;C++){let S=m[C];i.push({text:S.text,startIndex:f+S.startIndex,endIndex:f+S.endIndex})}let b=m[m.length-1];o=f+b.startIndex,n=T(b.text),l=-1;continue}n+=p;let x=s[u+1];if(g&&x&&(vt(x.segment)||!xe(x.segment)))l=x.index,h=n;else if(!g&&x&&!xe(x.segment)){let m=!vt(c)&&Nt.test(c),b=!vt(x.segment)&&Nt.test(x.segment);(m||b)&&(l=x.index,h=n)}}return i.push({text:e.slice(o),startIndex:o,endIndex:e.length}),i}a(ns,"wordWrapLine");var Qp={minPrimaryColumnWidth:12,maxPrimaryColumnWidth:32},Zp=20,Al=["@","#"],os=new RegExp(`(?:(?!${pr.source}).)*`,"u"),Ml=`${Dn.source}[([{<\`]*`;function Bl(e){return e.replace(/[\\^$.*+?()[\]{}|-]/g,"\\$&")}a(Bl,"escapeCharacterClass");function Rl(e){return new RegExp(`${Ml}(?:@"[^"]*|[${e.map(Bl).join("")}]${os.source})$`,"u")}a(Rl,"buildTriggerPattern");function El(e){let t=e.filter(r=>r!=="@").map(Bl);return new RegExp(`${Ml}(?:@(?:"[^"]*|${os.source})|[${t.join("")}]${os.source})$`,"u")}a(El,"buildDebouncePattern");function Jp(e,t,r){let i=Math.max(0,r),s=` ${e} ${t} more `,n=T(s);if(n+2<=i){let d=Math.floor((i-n)/2);return"\u2500".repeat(d)+s+"\u2500".repeat(i-d-n)}let o=`\u2500\u2500\u2500 ${e} ${t} more `,l=i-T(o);if(l>=0)return o+"\u2500".repeat(l);let h="...".slice(0,i),u=i-T(h);return Y(o,0,u,!0)+h}a(Jp,"createScrollBorder");var Il=class{static{a(this,"Editor")}state={lines:[""],cursorLine:0,cursorCol:0};focused=!1;tui;theme;paddingX=0;borderStyle="line";placeholder="";lastWidth=80;renderedVisibleLineCount=1;renderedAutocompleteHeight=0;scrollOffset=0;borderColor;autocompleteProvider;autocompleteTriggerCharacters=[...Al];autocompleteTriggerPattern=Rl(this.autocompleteTriggerCharacters);autocompleteDebouncePattern=El(this.autocompleteTriggerCharacters);autocompleteList;autocompleteState=null;autocompletePrefix="";autocompleteMaxVisible=5;autocompleteAbort;autocompleteDebounceTimer;autocompleteRequestTask=Promise.resolve();autocompleteStartToken=0;autocompleteRequestId=0;pastes=new Map;pasteCounter=0;pasteBuffer="";isInPaste=!1;history=[];historyIndex=-1;historyDraft=null;killRing=new ml;lastAction=null;jumpMode=null;preferredVisualCol=null;snappedFromCursorCol=null;undoStack=new xl;onSubmit;onChange;disableSubmit=!1;constructor(e,t,r={}){this.tui=e,this.theme=t,this.borderColor=t.borderColor,this.borderStyle=r.borderStyle==="box"?"box":"line",this.placeholder=r.placeholder??"";let i=r.paddingX??0;this.paddingX=Number.isFinite(i)?Math.max(0,Math.floor(i)):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(e,t){return Xp(e,t==="word"?Yp:Sl,this.validPasteIds())}getPaddingX(){return this.paddingX}setPaddingX(e){let t=Number.isFinite(e)?Math.max(0,Math.floor(e)):0;this.paddingX!==t&&(this.paddingX=t,this.tui.requestRender())}setPlaceholder(e){let t=e??"";this.placeholder!==t&&(this.placeholder=t,this.tui.requestRender())}getAutocompleteMaxVisible(){return this.autocompleteMaxVisible}setAutocompleteMaxVisible(e){let t=Number.isFinite(e)?Math.max(3,Math.min(20,Math.floor(e))):5;this.autocompleteMaxVisible!==t&&(this.autocompleteMaxVisible=t,this.tui.requestRender())}setAutocompleteProvider(e){this.cancelAutocomplete(),this.autocompleteProvider=e,this.setAutocompleteTriggerCharacters(e.triggerCharacters??[])}addToHistory(e){let t=e.trim();t&&(this.history.length>0&&this.history[0]===t||(this.history.unshift(t),this.history.length>100&&this.history.pop()))}isEditorEmpty(){return this.state.lines.length===1&&this.state.lines[0]===""}isOnFirstVisualLine(){let e=this.buildVisualLineMap(this.lastWidth);return this.findCurrentVisualLine(e)===0}isOnLastVisualLine(){let e=this.buildVisualLineMap(this.lastWidth);return this.findCurrentVisualLine(e)===e.length-1}navigateHistory(e){if(this.lastAction=null,this.history.length===0)return;let t=this.historyIndex-e;if(!(t<-1||t>=this.history.length))if(this.historyIndex===-1&&t>=0&&(this.pushUndoSnapshot(),this.historyDraft=structuredClone(this.state)),this.historyIndex=t,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]||"",e===-1?"start":"end")}exitHistoryBrowsing(){this.historyIndex=-1,this.historyDraft=null}setTextInternal(e,t="end"){let r=e.split(`
|
|
76
|
-
`);this.state.lines=r.length===0?[""]:r,this.state.cursorLine=t==="start"?0:this.state.lines.length-1,this.setCursorCol(t==="start"?0:this.state.lines[this.state.cursorLine]?.length||0),this.scrollOffset=0,this.onChange&&this.onChange(this.getText())}invalidate(){}renderHorizontalBorder(e,t,r){let i=this.borderStyle==="box",s=i?Math.max(0,t-2):t,n=e==="top"?"\u2191":"\u2193",o=r>0?Jp(n,r,s):"\u2500".repeat(s);if(!i)return this.borderColor(o);let l=e==="top"?"\u256D":"\u2570",h=e==="top"?"\u256E":"\u256F";return this.borderColor(`${l}${o}${h}`)}renderTopBorder(e,t){return this.renderHorizontalBorder("top",e,t)}renderBottomBorder(e,t){return this.renderHorizontalBorder("bottom",e,t)}render(e){let t=this.borderStyle==="box",r=Math.max(1,e-(t?1:0)*2),i=t?Math.max(1,this.paddingX):this.paddingX,s=Math.max(0,Math.floor((r-1)/2)),n=Math.min(i,s),o=Math.max(1,r-n*2),l=Math.max(1,o-(n?0:1));this.lastWidth=l;let h=a(y=>this.borderColor(y),"paintEdge"),u=this.layoutText(l),d=this.tui.terminal.rows,c=Math.max(5,Math.floor(d*.3)),p=u.findIndex(y=>y.hasCursor);p===-1&&(p=0),p<this.scrollOffset?this.scrollOffset=p:p>=this.scrollOffset+c&&(this.scrollOffset=p-c+1);let f=Math.max(0,u.length-c);this.scrollOffset=Math.max(0,Math.min(this.scrollOffset,f));let g=u.slice(this.scrollOffset,this.scrollOffset+c);this.renderedVisibleLineCount=g.length;let x=[],m=" ".repeat(n),b=m;x.push(this.renderTopBorder(e,this.scrollOffset));let C=this.focused;for(let y of g){let k=y.text,v=T(y.text),B=!1;if(y.hasCursor&&y.cursorPos!==void 0){let L=k.slice(0,y.cursorPos),I=k.slice(y.cursorPos),V=C?Fe:"";if(I.length>0){let O=[...this.segment(I,"grapheme")][0]?.segment||"",G=I.slice(O.length),he=Zt(O);k=L+V+he+G}else{let O=Zt(" ");if(k=L+V+O,v=v+1,v>o&&n>0&&(B=!0),this.placeholder&&this.getText().length===0){let G=this.theme.placeholder??(ot=>ot),he=Math.max(0,o-v);if(he>0){let ot=K(this.placeholder,he,"...");k+=G(ot),v+=T(ot)}}}}let M=" ".repeat(Math.max(0,o-v)),w=B?b.slice(1):b,A=`${m}${k}${M}${w}`;t?x.push(`${h("\u2502")}${A}${h("\u2502")}`):x.push(A)}let S=u.length-(this.scrollOffset+g.length);if(x.push(this.renderBottomBorder(e,S)),this.renderedAutocompleteHeight=0,this.autocompleteState&&this.autocompleteList){let y=this.autocompleteList.render(o);this.renderedAutocompleteHeight=y.length;for(let k of y){let v=T(k),B=" ".repeat(Math.max(0,o-v)),M=`${m}${k}${B}${b}`;t?x.push(`${h("\u2502")}${M}${h("\u2502")}`):x.push(M)}}return x}handleMouse(e){let t=this.renderedVisibleLineCount+2;if(this.autocompleteState&&this.autocompleteList&&e.y>=t&&e.y<t+this.renderedAutocompleteHeight){let g=Math.max(0,Math.floor((e.width-1)/2)),x=Math.min(this.paddingX,g),m=Math.max(1,e.width-x*2),b=this.autocompleteList.handleMouse?.({...e,x:e.x-x,y:e.y-t,width:m,height:this.renderedAutocompleteHeight});return b?{...b,focus:!0}:void 0}if(e.type!=="click"||e.button!=="left")return;if(e.y<=0||e.y>this.renderedVisibleLineCount)return{handled:!0,focus:!0};let r=this.buildVisualLineMap(this.lastWidth),i=this.scrollOffset+e.y-1,s=r[i];if(!s)return{handled:!0,focus:!0};let n=this.state.lines[s.logicalLine]??"",o=s.startCol+s.length,l=n.slice(s.startCol,o),h=Math.max(0,Math.floor((e.width-1)/2)),u=Math.min(this.paddingX,h),d=Math.max(0,e.x-u),c=0,p=l.length,f=0;for(let g of this.segment(l,"grapheme")){let x=c+T(g.segment);if(f=g.index,d<x){p=g.index;break}c=x}return!(i===r.length-1||r[i+1]?.logicalLine!==s.logicalLine)&&p===l.length&&l.length>0&&(p=f),this.state.cursorLine=s.logicalLine,this.setCursorCol(s.startCol+p),this.lastAction=null,this.exitHistoryBrowsing(),this.autocompleteState&&this.updateAutocomplete(),{handled:!0,focus:!0}}handleInput(e){let t=ue();if(this.jumpMode!==null){if(t.matches(e,"tui.editor.jumpForward")||t.matches(e,"tui.editor.jumpBackward")){this.jumpMode=null;return}let i=oo(e)??(e.charCodeAt(0)>=32?e:void 0);if(i!==void 0){let s=this.jumpMode;this.jumpMode=null,this.jumpToChar(i,s);return}this.jumpMode=null}if(e.includes("\x1B[200~")&&(this.isInPaste=!0,this.pasteBuffer="",e=e.replace("\x1B[200~","")),this.isInPaste){this.pasteBuffer+=e;let i=this.pasteBuffer.indexOf("\x1B[201~");if(i!==-1){let s=this.pasteBuffer.substring(0,i);s.length>0&&this.handlePaste(s),this.isInPaste=!1;let n=this.pasteBuffer.substring(i+6);this.pasteBuffer="",n.length>0&&this.handleInput(n);return}return}if(t.matches(e,"tui.input.copy"))return;if(t.matches(e,"tui.editor.undo")){this.undo();return}if(this.autocompleteState&&this.autocompleteList){if(t.matches(e,"tui.select.cancel")){this.cancelAutocomplete();return}if(t.matches(e,"tui.select.up")||t.matches(e,"tui.select.down")){this.autocompleteList.handleInput(e);return}if(t.matches(e,"tui.input.tab")){let i=this.autocompleteList.getSelectedItem();if(i&&this.autocompleteProvider){this.pushUndoSnapshot(),this.lastAction=null;let s=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,i,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(t.matches(e,"tui.select.confirm")){let i=this.autocompleteList.getSelectedItem();if(i&&this.autocompleteProvider){this.pushUndoSnapshot(),this.lastAction=null;let s=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,i,this.autocompletePrefix);if(this.state.lines=s.lines,this.state.cursorLine=s.cursorLine,this.setCursorCol(s.cursorCol),this.autocompletePrefix.startsWith("/"))this.cancelAutocomplete();else{this.cancelAutocomplete(),this.onChange&&this.onChange(this.getText());return}}}}if(t.matches(e,"tui.input.tab")&&!this.autocompleteState){this.handleTabCompletion();return}if(t.matches(e,"tui.editor.deleteToLineEnd")){this.deleteToEndOfLine();return}if(t.matches(e,"tui.editor.deleteToLineStart")){this.deleteToStartOfLine();return}if(t.matches(e,"tui.editor.deleteWordBackward")){this.deleteWordBackwards();return}if(t.matches(e,"tui.editor.deleteWordForward")){this.deleteWordForward();return}if(t.matches(e,"tui.editor.deleteCharBackward")||_e(e,"shift+backspace")){this.handleBackspace();return}if(t.matches(e,"tui.editor.deleteCharForward")||_e(e,"shift+delete")){this.handleForwardDelete();return}if(t.matches(e,"tui.editor.yank")){this.yank();return}if(t.matches(e,"tui.editor.yankPop")){this.yankPop();return}if(t.matches(e,"tui.editor.historyPrevious")){this.cancelAutocomplete(),this.navigateHistory(-1);return}if(t.matches(e,"tui.editor.historyNext")){this.cancelAutocomplete(),this.navigateHistory(1);return}if(t.matches(e,"tui.editor.cursorLineStart")){this.moveToLineStart();return}if(t.matches(e,"tui.editor.cursorLineEnd")){this.moveToLineEnd();return}if(t.matches(e,"tui.editor.cursorWordLeft")){this.moveWordBackwards();return}if(t.matches(e,"tui.editor.cursorWordRight")){this.moveWordForwards();return}if(t.matches(e,"tui.input.newLine")||e.charCodeAt(0)===10&&e.length>1||e==="\x1B\r"||e==="\x1B[13;2~"||e.length>1&&e.includes("\x1B")&&e.includes("\r")||e===`
|
|
77
|
-
`&&e.length===1){if(this.shouldSubmitOnBackslashEnter(e,t)){this.handleBackspace(),this.submitValue();return}this.addNewLine();return}if(t.matches(e,"tui.input.submit")){if(this.disableSubmit)return;let i=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>0&&i[this.state.cursorCol-1]==="\\"){this.handleBackspace(),this.addNewLine();return}this.submitValue();return}if(t.matches(e,"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(t.matches(e,"tui.editor.cursorDown")){this.historyIndex>-1&&this.isOnLastVisualLine()?this.navigateHistory(1):this.isOnLastVisualLine()?this.moveToLineEnd():this.moveCursor(1,0);return}if(t.matches(e,"tui.editor.cursorRight")){this.moveCursor(0,1);return}if(t.matches(e,"tui.editor.cursorLeft")){this.moveCursor(0,-1);return}if(t.matches(e,"tui.editor.pageUp")){this.pageScroll(-1);return}if(t.matches(e,"tui.editor.pageDown")){this.pageScroll(1);return}if(t.matches(e,"tui.editor.jumpForward")){this.jumpMode="forward";return}if(t.matches(e,"tui.editor.jumpBackward")){this.jumpMode="backward";return}if(_e(e,"shift+space")){this.insertCharacter(" ");return}let r=oo(e);if(r!==void 0){this.insertCharacter(r);return}e.charCodeAt(0)>=32&&this.insertCharacter(e)}layoutText(e){let t=[];if(this.state.lines.length===0||this.state.lines.length===1&&this.state.lines[0]==="")return t.push({text:"",hasCursor:!0,cursorPos:0}),t;for(let r=0;r<this.state.lines.length;r++){let i=this.state.lines[r]||"",s=r===this.state.cursorLine;if(T(i)<=e)s?t.push({text:i,hasCursor:!0,cursorPos:this.state.cursorCol}):t.push({text:i,hasCursor:!1});else{let n=ns(i,e,[...this.segment(i,"grapheme")]);for(let o=0;o<n.length;o++){let l=n[o];if(!l)continue;let h=this.state.cursorCol,u=o===n.length-1,d=!1,c=0;s&&(u?(d=h>=l.startIndex,c=h-l.startIndex):(d=h>=l.startIndex&&h<l.endIndex,d&&(c=h-l.startIndex,c>l.text.length&&(c=l.text.length)))),d?t.push({text:l.text,hasCursor:!0,cursorPos:c}):t.push({text:l.text,hasCursor:!1})}}}return t}getText(){return this.state.lines.join(`
|
|
78
|
-
`)}expandPasteMarkers(e){let t=e;for(let[r,i]of this.pastes){let s=new RegExp(`\\[paste #${r}( (\\+\\d+ lines|\\d+ chars))?\\]`,"g");t=t.replace(s,()=>i)}return t}getExpandedText(){return this.expandPasteMarkers(this.state.lines.join(`
|
|
79
|
-
`))}getLines(){return[...this.state.lines]}getCursor(){return{line:this.state.cursorLine,col:this.state.cursorCol}}setText(e){this.cancelAutocomplete(),this.lastAction=null,this.exitHistoryBrowsing();let t=this.normalizeText(e);this.getText()!==t&&this.pushUndoSnapshot(),this.pastes.clear(),this.pasteCounter=0,this.setTextInternal(t)}insertTextAtCursor(e){e&&(this.cancelAutocomplete(),this.pushUndoSnapshot(),this.lastAction=null,this.exitHistoryBrowsing(),this.insertTextAtCursorInternal(e))}normalizeText(e){return e.replace(/\r\n/g,`
|
|
80
|
-
`).replace(/\r/g,`
|
|
81
|
-
`).replace(/\t/g," ")}insertTextAtCursorInternal(e){if(!e)return;let t=this.normalizeText(e),r=t.split(`
|
|
82
|
-
`),i=this.state.lines[this.state.cursorLine]||"",s=i.slice(0,this.state.cursorCol),n=i.slice(this.state.cursorCol);r.length===1?(this.state.lines[this.state.cursorLine]=s+t+n,this.setCursorCol(this.state.cursorCol+t.length)):(this.state.lines=[...this.state.lines.slice(0,this.state.cursorLine),s+r[0],...r.slice(1,-1),r[r.length-1]+n,...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(e,t){this.exitHistoryBrowsing(),t||((xe(e)||this.lastAction!=="type-word")&&this.pushUndoSnapshot(),this.lastAction="type-word");let r=this.state.lines[this.state.cursorLine]||"",i=r.slice(0,this.state.cursorCol),s=r.slice(this.state.cursorCol);if(this.state.lines[this.state.cursorLine]=i+e+s,this.setCursorCol(this.state.cursorCol+e.length),this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else if(e==="/"&&this.isAtStartOfMessage())this.tryTriggerAutocomplete();else if(this.autocompleteTriggerCharacters.includes(e)){let n=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.autocompleteTriggerPattern.test(n)&&this.tryTriggerAutocomplete()}else if(/[a-zA-Z0-9.\-_]/.test(e)||Nt.test(e)){let n=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(n)?this.tryTriggerAutocomplete():this.autocompleteTriggerPattern.test(n)&&this.tryTriggerAutocomplete()}}handlePaste(e){this.cancelAutocomplete(),this.exitHistoryBrowsing(),this.lastAction=null,this.pushUndoSnapshot();let t=e.replace(/\x1b\[(\d+);5u/g,(n,o)=>{let l=Number(o);return l>=97&&l<=122?String.fromCharCode(l-96):l>=65&&l<=90?String.fromCharCode(l-64):n}),r=this.normalizeText(t).split("").filter(n=>n===`
|
|
83
|
-
`||n.charCodeAt(0)>=32).join("");if(/^[/~.]/.test(r)){let n=this.state.lines[this.state.cursorLine]||"",o=this.state.cursorCol>0?n[this.state.cursorCol-1]:"";o&&/\w/.test(o)&&(r=` ${r}`)}let i=r.split(`
|
|
84
|
-
`),s=r.length;if(i.length>10||s>1e3){this.pasteCounter++;let n=this.pasteCounter;this.pastes.set(n,r);let o=i.length>10?`[paste #${n} +${i.length} lines]`:`[paste #${n} ${s} chars]`;this.insertTextAtCursorInternal(o);return}if(i.length===1){this.insertTextAtCursorInternal(r);return}this.insertTextAtCursorInternal(r)}addNewLine(){this.cancelAutocomplete(),this.exitHistoryBrowsing(),this.lastAction=null,this.pushUndoSnapshot();let e=this.state.lines[this.state.cursorLine]||"",t=e.slice(0,this.state.cursorCol),r=e.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=t,this.state.lines.splice(this.state.cursorLine+1,0,r),this.state.cursorLine++,this.setCursorCol(0),this.onChange&&this.onChange(this.getText())}shouldSubmitOnBackslashEnter(e,t){if(this.disableSubmit||!_e(e,"enter"))return!1;let r=t.getKeys("tui.input.submit");if(!(r.includes("shift+enter")||r.includes("shift+return")))return!1;let i=this.state.lines[this.state.cursorLine]||"";return this.state.cursorCol>0&&i[this.state.cursorCol-1]==="\\"}submitValue(){this.cancelAutocomplete();let e=this.expandPasteMarkers(this.state.lines.join(`
|
|
85
|
-
`)).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(e)}handleBackspace(){if(this.exitHistoryBrowsing(),this.lastAction=null,this.state.cursorCol>0){this.pushUndoSnapshot();let e=this.state.lines[this.state.cursorLine]||"",t=e.slice(0,this.state.cursorCol),r=[...this.segment(t,"grapheme")],i=r[r.length-1],s=i?i.segment.length:1,n=Tl.exec(i.segment);if(n){let h=Number(n[1]);this.pastes.delete(h),this.pasteCounter--;let u=[...this.pastes.keys()].filter(d=>d>h).sort((d,c)=>d-c);for(let d of u)this.pastes.set(d-1,this.pastes.get(d)),this.pastes.delete(d);this.state.lines=this.state.lines.map(d=>d.replace(Cl,(c,p,f)=>{let g=Number(p);return g<=h?c:`[paste #${g-1}${f}]`}))}e=this.state.lines[this.state.cursorLine]||"";let o=e.slice(0,this.state.cursorCol-s),l=e.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=o+l,this.setCursorCol(this.state.cursorCol-s)}else if(this.state.cursorLine>0){this.pushUndoSnapshot();let e=this.state.lines[this.state.cursorLine]||"",t=this.state.lines[this.state.cursorLine-1]||"";this.state.lines[this.state.cursorLine-1]=t+e,this.state.lines.splice(this.state.cursorLine,1),this.state.cursorLine--,this.setCursorCol(t.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(e){this.state.cursorCol=e,this.preferredVisualCol=null,this.snappedFromCursorCol=null}moveToVisualLine(e,t,r){let i=e[t],s=e[r];if(!(i&&s))return;let n;if(this.snappedFromCursorCol!==null){let p=this.findVisualLineAt(e,i.logicalLine,this.snappedFromCursorCol);n=this.snappedFromCursorCol-e[p].startCol}else n=this.state.cursorCol-i.startCol;let o=t===e.length-1||e[t+1]?.logicalLine!==i.logicalLine?i.length:Math.max(0,i.length-1),l=r===e.length-1||e[r+1]?.logicalLine!==s.logicalLine?s.length:Math.max(0,s.length-1),h=this.computeVerticalMoveColumn(n,o,l);this.state.cursorLine=s.logicalLine;let u=s.startCol+h,d=this.state.lines[s.logicalLine]||"";this.state.cursorCol=Math.min(u,d.length);let c=[...this.segment(d,"grapheme")];for(let p of c){if(p.index>this.state.cursorCol)break;if(!(p.segment.length<=1)&&this.state.cursorCol<p.index+p.segment.length){let f=p.index<s.startCol,g=r>t;if(f&&g){let x=p.index+p.segment.length,m=r+1;for(;m<e.length&&e[m].logicalLine===s.logicalLine&&e[m].startCol<x;)m++;if(m<e.length){this.moveToVisualLine(e,t,m);return}}this.snappedFromCursorCol=this.state.cursorCol,this.state.cursorCol=p.index;return}}this.snappedFromCursorCol=null}computeVerticalMoveColumn(e,t,r){let i=this.preferredVisualCol!==null,s=e<t,n=r<e;if(!i||s)return n?(this.preferredVisualCol=e,r):(this.preferredVisualCol=null,e);let o=r<this.preferredVisualCol;if(n||o)return r;let l=this.preferredVisualCol;return this.preferredVisualCol=null,l}moveToLineStart(){this.lastAction=null,this.setCursorCol(0)}moveToLineEnd(){this.lastAction=null;let e=this.state.lines[this.state.cursorLine]||"";this.setCursorCol(e.length)}deleteToStartOfLine(){this.exitHistoryBrowsing();let e=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>0){this.pushUndoSnapshot();let t=e.slice(0,this.state.cursorCol);this.killRing.push(t,{prepend:!0,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=e.slice(this.state.cursorCol),this.setCursorCol(0)}else if(this.state.cursorLine>0){this.pushUndoSnapshot(),this.killRing.push(`
|
|
86
|
-
`,{prepend:!0,accumulate:this.lastAction==="kill"}),this.lastAction="kill";let t=this.state.lines[this.state.cursorLine-1]||"";this.state.lines[this.state.cursorLine-1]=t+e,this.state.lines.splice(this.state.cursorLine,1),this.state.cursorLine--,this.setCursorCol(t.length)}this.onChange&&this.onChange(this.getText())}deleteToEndOfLine(){this.exitHistoryBrowsing();let e=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol<e.length){this.pushUndoSnapshot();let t=e.slice(this.state.cursorCol);this.killRing.push(t,{prepend:!1,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=e.slice(0,this.state.cursorCol)}else if(this.state.cursorLine<this.state.lines.length-1){this.pushUndoSnapshot(),this.killRing.push(`
|
|
87
|
-
`,{prepend:!1,accumulate:this.lastAction==="kill"}),this.lastAction="kill";let t=this.state.lines[this.state.cursorLine+1]||"";this.state.lines[this.state.cursorLine]=e+t,this.state.lines.splice(this.state.cursorLine+1,1)}this.onChange&&this.onChange(this.getText())}deleteWordBackwards(){this.exitHistoryBrowsing();let e=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol===0){if(this.state.cursorLine>0){this.pushUndoSnapshot(),this.killRing.push(`
|
|
88
|
-
`,{prepend:!0,accumulate:this.lastAction==="kill"}),this.lastAction="kill";let t=this.state.lines[this.state.cursorLine-1]||"";this.state.lines[this.state.cursorLine-1]=t+e,this.state.lines.splice(this.state.cursorLine,1),this.state.cursorLine--,this.setCursorCol(t.length)}}else{this.pushUndoSnapshot();let t=this.lastAction==="kill",r=this.state.cursorCol;this.moveWordBackwards();let i=this.state.cursorCol;this.setCursorCol(r);let s=e.slice(i,this.state.cursorCol);this.killRing.push(s,{prepend:!0,accumulate:t}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=e.slice(0,i)+e.slice(this.state.cursorCol),this.setCursorCol(i)}this.onChange&&this.onChange(this.getText())}deleteWordForward(){this.exitHistoryBrowsing();let e=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>=e.length){if(this.state.cursorLine<this.state.lines.length-1){this.pushUndoSnapshot(),this.killRing.push(`
|
|
89
|
-
`,{prepend:!1,accumulate:this.lastAction==="kill"}),this.lastAction="kill";let t=this.state.lines[this.state.cursorLine+1]||"";this.state.lines[this.state.cursorLine]=e+t,this.state.lines.splice(this.state.cursorLine+1,1)}}else{this.pushUndoSnapshot();let t=this.lastAction==="kill",r=this.state.cursorCol;this.moveWordForwards();let i=this.state.cursorCol;this.setCursorCol(r);let s=e.slice(this.state.cursorCol,i);this.killRing.push(s,{prepend:!1,accumulate:t}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=e.slice(0,this.state.cursorCol)+e.slice(i)}this.onChange&&this.onChange(this.getText())}handleForwardDelete(){this.exitHistoryBrowsing(),this.lastAction=null;let e=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol<e.length){this.pushUndoSnapshot();let t=e.slice(this.state.cursorCol),r=[...this.segment(t,"grapheme")][0],i=r?r.segment.length:1,s=e.slice(0,this.state.cursorCol),n=e.slice(this.state.cursorCol+i);this.state.lines[this.state.cursorLine]=s+n}else if(this.state.cursorLine<this.state.lines.length-1){this.pushUndoSnapshot();let t=this.state.lines[this.state.cursorLine+1]||"";this.state.lines[this.state.cursorLine]=e+t,this.state.lines.splice(this.state.cursorLine+1,1)}if(this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else{let t=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(t)?this.tryTriggerAutocomplete():this.autocompleteTriggerPattern.test(t)&&this.tryTriggerAutocomplete()}}buildVisualLineMap(e){let t=[];for(let r=0;r<this.state.lines.length;r++){let i=this.state.lines[r]||"",s=T(i);if(i.length===0)t.push({logicalLine:r,startCol:0,length:0});else if(s<=e)t.push({logicalLine:r,startCol:0,length:i.length});else{let n=ns(i,e,[...this.segment(i,"grapheme")]);for(let o of n)t.push({logicalLine:r,startCol:o.startIndex,length:o.endIndex-o.startIndex})}}return t}findVisualLineAt(e,t,r){for(let i=0;i<e.length;i++){let s=e[i];if(!s||s.logicalLine!==t)continue;let n=r-s.startCol,o=i===e.length-1||e[i+1]?.logicalLine!==s.logicalLine;if(n>=0&&(n<s.length||o&&n===s.length))return i}return e.length-1}findCurrentVisualLine(e){return this.findVisualLineAt(e,this.state.cursorLine,this.state.cursorCol)}moveCursor(e,t){this.lastAction=null;let r=this.buildVisualLineMap(this.lastWidth),i=this.findCurrentVisualLine(r);if(e!==0){let s=i+e;s>=0&&s<r.length&&this.moveToVisualLine(r,i,s)}if(t!==0){let s=this.state.lines[this.state.cursorLine]||"";if(t>0)if(this.state.cursorCol<s.length){let n=s.slice(this.state.cursorCol),o=[...this.segment(n,"grapheme")][0];this.setCursorCol(this.state.cursorCol+(o?o.segment.length:1))}else if(this.state.cursorLine<this.state.lines.length-1)this.state.cursorLine++,this.setCursorCol(0);else{let n=r[i];n&&(this.preferredVisualCol=this.state.cursorCol-n.startCol)}else if(this.state.cursorCol>0){let n=s.slice(0,this.state.cursorCol),o=[...this.segment(n,"grapheme")],l=o[o.length-1];this.setCursorCol(this.state.cursorCol-(l?l.segment.length:1))}else if(this.state.cursorLine>0){this.state.cursorLine--;let n=this.state.lines[this.state.cursorLine]||"";this.setCursorCol(n.length)}}this.autocompleteState&&this.updateAutocomplete()}pageScroll(e){this.lastAction=null;let t=this.tui.terminal.rows,r=Math.max(5,Math.floor(t*.3)),i=this.buildVisualLineMap(this.lastWidth),s=this.findCurrentVisualLine(i),n=Math.max(0,Math.min(i.length-1,s+e*r));this.moveToVisualLine(i,s,n)}moveWordBackwards(){this.lastAction=null;let e=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol===0){if(this.state.cursorLine>0){this.state.cursorLine--;let t=this.state.lines[this.state.cursorLine]||"";this.setCursorCol(t.length)}return}this.setCursorCol(yl(e,this.state.cursorCol,{segment:a(t=>this.segment(t,"word"),"segment"),isAtomicSegment:vt}))}yank(){if(this.killRing.length===0)return;this.pushUndoSnapshot();let e=this.killRing.peek();this.insertYankedText(e),this.lastAction="yank"}yankPop(){if(this.lastAction!=="yank"||this.killRing.length<=1)return;this.pushUndoSnapshot(),this.deleteYankedText(),this.killRing.rotate();let e=this.killRing.peek();this.insertYankedText(e),this.lastAction="yank"}insertYankedText(e){this.exitHistoryBrowsing();let t=e.split(`
|
|
90
|
-
`);if(t.length===1){let r=this.state.lines[this.state.cursorLine]||"",i=r.slice(0,this.state.cursorCol),s=r.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=i+e+s,this.setCursorCol(this.state.cursorCol+e.length)}else{let r=this.state.lines[this.state.cursorLine]||"",i=r.slice(0,this.state.cursorCol),s=r.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=i+(t[0]||"");for(let o=1;o<t.length-1;o++)this.state.lines.splice(this.state.cursorLine+o,0,t[o]||"");let n=this.state.cursorLine+t.length-1;this.state.lines.splice(n,0,(t[t.length-1]||"")+s),this.state.cursorLine=n,this.setCursorCol((t[t.length-1]||"").length)}this.onChange&&this.onChange(this.getText())}deleteYankedText(){let e=this.killRing.peek();if(!e)return;let t=e.split(`
|
|
91
|
-
`);if(t.length===1){let r=this.state.lines[this.state.cursorLine]||"",i=e.length,s=r.slice(0,this.state.cursorCol-i),n=r.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=s+n,this.setCursorCol(this.state.cursorCol-i)}else{let r=this.state.cursorLine-(t.length-1),i=(this.state.lines[r]||"").length-(t[0]||"").length,s=(this.state.lines[this.state.cursorLine]||"").slice(this.state.cursorCol),n=(this.state.lines[r]||"").slice(0,i);this.state.lines.splice(r,t.length,n+s),this.state.cursorLine=r,this.setCursorCol(i)}this.onChange&&this.onChange(this.getText())}pushUndoSnapshot(){this.undoStack.push({state:this.state,pastes:this.pastes,pasteCounter:this.pasteCounter})}undo(){this.exitHistoryBrowsing();let e=this.undoStack.pop();e&&(Object.assign(this.state,e.state),this.pastes=e.pastes,this.pasteCounter=e.pasteCounter,this.lastAction=null,this.preferredVisualCol=null,this.onChange&&this.onChange(this.getText()))}jumpToChar(e,t){this.lastAction=null;let r=t==="forward",i=this.state.lines,s=r?i.length:-1,n=r?1:-1;for(let o=this.state.cursorLine;o!==s;o+=n){let l=i[o]||"",h=o===this.state.cursorLine?r?this.state.cursorCol+1:this.state.cursorCol-1:void 0,u=r?l.indexOf(e,h):l.lastIndexOf(e,h);if(u!==-1){this.state.cursorLine=o,this.setCursorCol(u);return}}}moveWordForwards(){this.lastAction=null;let e=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>=e.length){this.state.cursorLine<this.state.lines.length-1&&(this.state.cursorLine++,this.setCursorCol(0));return}this.setCursorCol(wl(e,this.state.cursorCol,{segment:a(t=>this.segment(t,"word"),"segment"),isAtomicSegment:vt}))}isSlashMenuAllowed(){return this.state.cursorLine===0}isAtStartOfMessage(){if(!this.isSlashMenuAllowed())return!1;let e=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);return e.trim()===""||e.trim()==="/"}isInSlashCommandContext(e){return this.isSlashMenuAllowed()&&e.trimStart().startsWith("/")}getBestAutocompleteMatchIndex(e,t){if(!t)return-1;let r=-1;for(let i=0;i<e.length;i++){let s=e[i].value;if(s===t)return i;r===-1&&s.startsWith(t)&&(r=i)}return r}createAutocompleteList(e,t){let r=e.startsWith("/")?Qp:void 0,i=new ss(t,this.autocompleteMaxVisible,this.theme.selectList,r);return i.onSelect=s=>{if(!this.autocompleteProvider)return;this.pushUndoSnapshot(),this.lastAction=null;let n=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,s,this.autocompletePrefix);this.state.lines=n.lines,this.state.cursorLine=n.cursorLine,this.setCursorCol(n.cursorCol),this.cancelAutocomplete(),this.onChange?.(this.getText())},i}tryTriggerAutocomplete(e=!1){this.requestAutocomplete({force:!1,explicitTab:e})}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(!0)}handleSlashCommandCompletion(){this.requestAutocomplete({force:!1,explicitTab:!0})}forceFileAutocomplete(e=!1){this.requestAutocomplete({force:!0,explicitTab:e})}requestAutocomplete(e){if(!this.autocompleteProvider||e.force&&!(!this.autocompleteProvider.shouldTriggerFileCompletion||this.autocompleteProvider.shouldTriggerFileCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol)))return;this.cancelAutocompleteRequest();let t=++this.autocompleteStartToken,r=this.getAutocompleteDebounceMs(e);if(r>0){this.autocompleteDebounceTimer=setTimeout(()=>{this.autocompleteDebounceTimer=void 0,this.startAutocompleteRequest(t,e)},r);return}this.startAutocompleteRequest(t,e)}async startAutocompleteRequest(e,t){let r=this.autocompleteRequestTask;this.autocompleteRequestTask=(async()=>{if(await r,e!==this.autocompleteStartToken||!this.autocompleteProvider)return;let i=new AbortController;this.autocompleteAbort=i;let s=++this.autocompleteRequestId,n=this.getText(),o=this.state.cursorLine,l=this.state.cursorCol;await this.runAutocompleteRequest(s,i,n,o,l,t)})(),await this.autocompleteRequestTask}setAutocompleteTriggerCharacters(e){let t=[...Al];for(let r of e)r.length!==1||r==="/"||xe(r)||t.includes(r)||t.push(r);this.autocompleteTriggerCharacters=t,this.autocompleteTriggerPattern=Rl(t),this.autocompleteDebouncePattern=El(t)}getAutocompleteDebounceMs(e){if(e.explicitTab||e.force)return 0;let t=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);return this.autocompleteDebouncePattern.test(t)?Zp:0}async runAutocompleteRequest(e,t,r,i,s,n){if(!this.autocompleteProvider)return;let o=await this.autocompleteProvider.getSuggestions(this.state.lines,this.state.cursorLine,this.state.cursorCol,{signal:t.signal,force:n.force});if(this.isAutocompleteRequestCurrent(e,t,r,i,s)){if(this.autocompleteAbort=void 0,!o||!Array.isArray(o.items)||o.items.length===0){this.cancelAutocomplete(),this.tui.requestRender();return}if(n.force&&n.explicitTab&&o.items.length===1){let l=o.items[0];this.pushUndoSnapshot(),this.lastAction=null;let h=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,l,o.prefix);this.state.lines=h.lines,this.state.cursorLine=h.cursorLine,this.setCursorCol(h.cursorCol),this.onChange&&this.onChange(this.getText()),this.tui.requestRender();return}this.applyAutocompleteSuggestions(o,n.force?"force":"regular"),this.tui.requestRender()}}isAutocompleteRequestCurrent(e,t,r,i,s){return!t.signal.aborted&&e===this.autocompleteRequestId&&this.getText()===r&&this.state.cursorLine===i&&this.state.cursorCol===s}applyAutocompleteSuggestions(e,t){this.autocompletePrefix=e.prefix,this.autocompleteList=this.createAutocompleteList(e.prefix,e.items);let r=this.getBestAutocompleteMatchIndex(e.items,e.prefix);r>=0&&this.autocompleteList.setSelectedIndex(r),this.autocompleteState=t}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:!1})}},Vr=Symbol.for("@earendil-works/pi-tui/layout-node");function qr(e){let t=e;return typeof t[Vr]=="function"?t[Vr]():void 0}a(qr,"getLayoutNode");function ef(e){return!("render"in e)}a(ef,"isStackEntry");function Qe(e,t){return e===void 0||!Number.isFinite(e)?t:Math.max(0,Math.floor(e))}a(Qe,"normalizeSize");var Ll=class extends Ne{static{a(this,"Stack")}entries=[];gap;align;padX;padY;constructor(e=[],t={}){super(),this.gap=Qe(t.gap,0),this.align=t.align??"stretch",this.padX=Qe(t.padX,0),this.padY=Qe(t.padY,0);for(let r of e)ef(r)?this.addChild(r.component,r):this.addChild(r)}addChild(e,t={}){super.addChild(e),this.entries.push({component:e,...t.basis===void 0?{}:{basis:t.basis},...t.grow===void 0?{}:{grow:Qe(t.grow,0)},...t.shrink===void 0?{}:{shrink:Qe(t.shrink,1)},...t.minSize===void 0?{}:{minSize:Qe(t.minSize,0)},...t.maxSize===void 0?{}:{maxSize:Qe(t.maxSize,Number.MAX_SAFE_INTEGER)},...t.visible===void 0?{}:{visible:t.visible}})}removeChild(e){super.removeChild(e);let t=this.entries.findIndex(r=>r.component===e);t!==-1&&this.entries.splice(t,1)}clear(){super.clear(),this.entries.length=0}[Vr](){return{type:this.layoutType,entries:this.entries,gap:this.gap,align:this.align,...this.padX>0?{padX:this.padX}:{},...this.padY>0?{padY:this.padY}:{}}}};function ls(e,t){return e.filter(r=>r.visible?.(t)??!0)}a(ls,"visibleStackEntries");function tf(e,t){let r=Math.max(0,Math.floor(t.minSize??0)),i=Math.max(r,Math.floor(t.maxSize??Number.MAX_SAFE_INTEGER));return Math.max(r,Math.min(i,Math.max(0,Math.floor(e))))}a(tf,"clampSize");function Pl(e,t,r,i){let s=r;for(;s>0;){let n=t.map((h,u)=>({entry:h,index:u})).filter(({entry:h,index:u})=>i==="grow"?(h.grow??0)>0&&e[u]<(h.maxSize??Number.MAX_SAFE_INTEGER):(h.shrink??1)>0&&e[u]>(h.minSize??0));if(n.length===0)return;let o=n.reduce((h,{entry:u,index:d})=>h+(i==="grow"?u.grow??0:(u.shrink??1)*Math.max(1,e[d])),0),l=0;for(let{entry:h,index:u}of n){if(s<=0)break;let d=i==="grow"?h.grow??0:(h.shrink??1)*Math.max(1,e[u]),c=Math.max(1,Math.floor(s*d/o)),p=i==="grow"?(h.maxSize??Number.MAX_SAFE_INTEGER)-e[u]:e[u]-(h.minSize??0),f=Math.min(s,c,p);f<=0||(e[u]=e[u]+(i==="grow"?f:-f),s-=f,l+=f)}if(l===0)return}}a(Pl,"distribute");function Kr(e,t,r,i){let s=e.map((l,h)=>tf(l.basis===void 0||l.basis==="auto"?t[h]??0:l.basis,l));if(r===void 0)return s;let n=Math.max(0,Math.floor(r)-Math.max(0,e.length-1)*i),o=s.reduce((l,h)=>l+h,0);return o<n?Pl(s,e,n-o,"grow"):o>n&&Pl(s,e,o-n,"shrink"),s}a(Kr,"allocateStackSizes");var rf=class extends Ll{static{a(this,"HStack")}layoutType="hstack";constructor(e=[],t={}){super(e,t)}render(e){let t=Math.max(1,e),r={width:t,height:Number.MAX_SAFE_INTEGER},i=ls(this.entries,r);if(i.length===0)return[];let s=i.map(d=>d.component.render(t).reduce((c,p)=>Math.max(c,T(p)),0)),n=Kr(i,s,t,this.gap),o=i.map((d,c)=>n[c]===0?[]:d.component.render(n[c])),l=o.reduce((d,c)=>Math.max(d,c.length),0),h=Array.from({length:l},()=>""),u=0;for(let d=0;d<o.length;d++){let c=o[d],p=n[d],f=0;this.align==="center"?f=Math.floor((l-c.length)/2):this.align==="end"&&(f=l-c.length);for(let g=0;g<c.length;g++){let x=g+f;x<0||x>=h.length||(h[x]=Xe(h[x],c[g],u,p,t))}u+=p+this.gap}return h}},as,Ze=new Map;function $l(e){as=e,Ze.clear()}a($l,"setImageTranscoder");function sf(e,t){if(!as)return null;let r=Ze.get(e),i=r===void 0?as(e,t):r;return Ze.delete(e),Ze.set(e,i),Ze.size>32&&Ze.delete(Ze.keys().next().value),i}a(sf,"toPng");var _l=class{static{a(this,"Image")}base64Data;mimeType;dimensions;theme;options;imageId;pngData;cachedLines;cachedWidth;constructor(e,t,r,i={},s){this.base64Data=e,this.mimeType=t,this.theme=r,this.options=i,this.dimensions=s||Zi(e,t)||{widthPx:800,heightPx:600},this.imageId=i.imageId}getImageId(){return this.imageId}invalidate(){this.cachedLines=void 0,this.cachedWidth=void 0}render(e){if(this.cachedLines&&this.cachedWidth===e)return this.cachedLines;let t=Math.max(1,Math.min(e-2,this.options.maxWidthCells??60)),r=Ui(),i=Math.max(1,Math.ceil(t*r.widthPx/r.heightPx)),s=this.options.maxHeightCells??i,n=pe(),o=this.base64Data,l=this.dimensions;n.images==="kitty"&&this.mimeType!=="image/png"&&(this.pngData??=sf(this.base64Data,this.mimeType)??void 0,o=this.pngData??null,o&&(l=Qi(o)??l));let h;if(n.images&&o){n.images==="kitty"&&this.imageId===void 0&&(this.imageId=zo());let u=ol(o,l,{maxWidthCells:t,maxHeightCells:s,imageId:this.imageId,moveCursor:!1});if(u)if(u.imageId&&(this.imageId=u.imageId),n.images==="kitty"){h=[u.sequence];for(let d=0;d<u.rows-1;d++)h.push("")}else{h=[];for(let p=0;p<u.rows-1;p++)h.push("");let d=u.rows-1,c=d>0?`\x1B[${d}A`:"";h.push(c+u.sequence)}else{let d=Wr(this.mimeType,this.dimensions,this.options.filename);h=[K(this.theme.fallbackColor(d),e)]}}else{let u=Wr(this.mimeType,this.dimensions,this.options.filename);h=[K(this.theme.fallbackColor(u),e)]}return this.cachedLines=h,this.cachedWidth=e,h}},Je=mi(),Ur=class{static{a(this,"Input")}value="";cursor=0;prompt;placeholder;placeholderStyle;renderedStartColumn=0;onSubmit;onEscape;focused=!1;pasteBuffer="";isInPaste=!1;killRing=new ml;lastAction=null;undoStack=new xl;constructor(e={}){this.prompt=e.prompt??"> ",this.placeholder=e.placeholder??"",this.placeholderStyle=e.placeholderStyle??(t=>t)}getValue(){return this.value}setValue(e){this.value=e,this.cursor=Math.min(this.cursor,e.length)}handleInput(e){if(e.includes("\x1B[200~")&&(this.isInPaste=!0,this.pasteBuffer="",e=e.replace("\x1B[200~","")),this.isInPaste){this.pasteBuffer+=e;let i=this.pasteBuffer.indexOf("\x1B[201~");if(i!==-1){let s=this.pasteBuffer.substring(0,i);this.handlePaste(s),this.isInPaste=!1;let n=this.pasteBuffer.substring(i+6);this.pasteBuffer="",n&&this.handleInput(n)}return}let t=ue();if(t.matches(e,"tui.select.cancel")){this.onEscape&&this.onEscape();return}if(t.matches(e,"tui.editor.undo")){this.undo();return}if(t.matches(e,"tui.input.submit")||e===`
|
|
92
|
-
`){this.onSubmit&&this.onSubmit(this.value);return}if(t.matches(e,"tui.editor.deleteCharBackward")){this.handleBackspace();return}if(t.matches(e,"tui.editor.deleteCharForward")){this.handleForwardDelete();return}if(t.matches(e,"tui.editor.deleteWordBackward")){this.deleteWordBackwards();return}if(t.matches(e,"tui.editor.deleteWordForward")){this.deleteWordForward();return}if(t.matches(e,"tui.editor.deleteToLineStart")){this.deleteToLineStart();return}if(t.matches(e,"tui.editor.deleteToLineEnd")){this.deleteToLineEnd();return}if(t.matches(e,"tui.editor.yank")){this.yank();return}if(t.matches(e,"tui.editor.yankPop")){this.yankPop();return}if(t.matches(e,"tui.editor.cursorLeft")){if(this.lastAction=null,this.cursor>0){let i=this.value.slice(0,this.cursor),s=[...Je.segment(i)],n=s[s.length-1];this.cursor-=n?n.segment.length:1}return}if(t.matches(e,"tui.editor.cursorRight")){if(this.lastAction=null,this.cursor<this.value.length){let i=this.value.slice(this.cursor),s=[...Je.segment(i)][0];this.cursor+=s?s.segment.length:1}return}if(t.matches(e,"tui.editor.cursorLineStart")){this.lastAction=null,this.cursor=0;return}if(t.matches(e,"tui.editor.cursorLineEnd")){this.lastAction=null,this.cursor=this.value.length;return}if(t.matches(e,"tui.editor.cursorWordLeft")){this.moveWordBackwards();return}if(t.matches(e,"tui.editor.cursorWordRight")){this.moveWordForwards();return}let r=Ii(e);if(r!==void 0){this.insertCharacter(r);return}[...e].some(i=>{let s=i.charCodeAt(0);return s<32||s===127||s>=128&&s<=159})||this.insertCharacter(e)}handleMouse(e){if(e.type!=="press"||e.button!=="left"||e.y!==0)return;let t=Math.max(0,e.x-T(this.prompt)),r=this.renderedStartColumn+t,i=0;this.cursor=this.value.length;for(let s of Je.segment(this.value)){let n=i+T(s.segment);if(r<n){this.cursor=s.index;break}i=n}return this.lastAction=null,{handled:!0,focus:!0}}insertCharacter(e){(xe(e)||this.lastAction!=="type-word")&&this.pushUndo(),this.lastAction="type-word",this.value=this.value.slice(0,this.cursor)+e+this.value.slice(this.cursor),this.cursor+=e.length}handleBackspace(){if(this.lastAction=null,this.cursor>0){this.pushUndo();let e=this.value.slice(0,this.cursor),t=[...Je.segment(e)],r=t[t.length-1],i=r?r.segment.length:1;this.value=this.value.slice(0,this.cursor-i)+this.value.slice(this.cursor),this.cursor-=i}}handleForwardDelete(){if(this.lastAction=null,this.cursor<this.value.length){this.pushUndo();let e=this.value.slice(this.cursor),t=[...Je.segment(e)][0],r=t?t.segment.length:1;this.value=this.value.slice(0,this.cursor)+this.value.slice(this.cursor+r)}}deleteToLineStart(){if(this.cursor===0)return;this.pushUndo();let e=this.value.slice(0,this.cursor);this.killRing.push(e,{prepend:!0,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 e=this.value.slice(this.cursor);this.killRing.push(e,{prepend:!1,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.value=this.value.slice(0,this.cursor)}deleteWordBackwards(){if(this.cursor===0)return;let e=this.lastAction==="kill";this.pushUndo();let t=this.cursor;this.moveWordBackwards();let r=this.cursor;this.cursor=t;let i=this.value.slice(r,this.cursor);this.killRing.push(i,{prepend:!0,accumulate:e}),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 e=this.lastAction==="kill";this.pushUndo();let t=this.cursor;this.moveWordForwards();let r=this.cursor;this.cursor=t;let i=this.value.slice(this.cursor,r);this.killRing.push(i,{prepend:!1,accumulate:e}),this.lastAction="kill",this.value=this.value.slice(0,this.cursor)+this.value.slice(r)}yank(){let e=this.killRing.peek();e&&(this.pushUndo(),this.value=this.value.slice(0,this.cursor)+e+this.value.slice(this.cursor),this.cursor+=e.length,this.lastAction="yank")}yankPop(){if(this.lastAction!=="yank"||this.killRing.length<=1)return;this.pushUndo();let e=this.killRing.peek()||"";this.value=this.value.slice(0,this.cursor-e.length)+this.value.slice(this.cursor),this.cursor-=e.length,this.killRing.rotate();let t=this.killRing.peek()||"";this.value=this.value.slice(0,this.cursor)+t+this.value.slice(this.cursor),this.cursor+=t.length,this.lastAction="yank"}pushUndo(){this.undoStack.push({value:this.value,cursor:this.cursor})}undo(){let e=this.undoStack.pop();e&&(this.value=e.value,this.cursor=e.cursor,this.lastAction=null)}moveWordBackwards(){this.cursor!==0&&(this.lastAction=null,this.cursor=yl(this.value,this.cursor))}moveWordForwards(){this.cursor>=this.value.length||(this.lastAction=null,this.cursor=wl(this.value,this.cursor))}handlePaste(e){this.lastAction=null,this.pushUndo();let t=e.replace(/\r\n/g,"").replace(/\r/g,"").replace(/\n/g,"").replace(/\t/g," ");this.value=this.value.slice(0,this.cursor)+t+this.value.slice(this.cursor),this.cursor+=t.length}invalidate(){}render(e){let t=e-T(this.prompt);if(t<=0)return[K(this.prompt,e,"")];if(this.value.length===0&&this.placeholder){let g=K(this.placeholder,t,""),x=[...Je.segment(g)][0]?.segment??" ",m=g.slice(x.length),b=this.focused?Fe:"",C=Zt(this.placeholderStyle(x)),S=b+C+this.placeholderStyle(m),y=" ".repeat(Math.max(0,t-T(S)));return[this.prompt+S+y]}let r="",i=this.cursor;this.renderedStartColumn=0;let s=T(this.value);if(s<t)r=this.value;else{let g=this.cursor===this.value.length?t-1:t,x=T(this.value.slice(0,this.cursor));if(g>0){let m=Math.floor(g/2),b=0;x<m?b=0:x>s-m?b=Math.max(0,s-g):b=Math.max(0,x-m),this.renderedStartColumn=b,r=Y(this.value,b,g,!0),i=Y(this.value,b,Math.max(0,x-b),!0).length}else r="",i=0}let n=[...Je.segment(r.slice(i))][0],o=r.slice(0,i),l=n?.segment??" ",h=r.slice(i+l.length),u=this.focused?Fe:"",d=Zt(l),c=o+u+d+h,p=T(c),f=" ".repeat(Math.max(0,t-p));return[this.prompt+c+f]}},nf={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:":"},of=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"]),lf=new Set(["argmax","argmin","inf","injlim","lim","liminf","limsup","max","min","projlim","sup"]),af=new Set(["bigcap","bigcup","bigodot","bigoplus","bigotimes","bigsqcup","biguplus","bigvee","bigwedge","coprod","int","iint","iiint","oint","prod","sum"]),hf=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"]),uf={"<":"\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"},cf={C:"\u2102",H:"\u210D",N:"\u2115",P:"\u2119",Q:"\u211A",R:"\u211D",Z:"\u2124"},df={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"},pf={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"},ff=new Set([",",":",";"," ",">","enspace","enskip","medspace","quad","qquad","thickspace","thinspace"]),gf=new Set(["!","negmedspace","negthickspace","negthinspace"]),Ol="\0",mf=new Set(["bf","cal","it","rm","sf","sl","tt"]),xf=new Set(["displaystyle","limits","nolimits","scriptstyle","scriptscriptstyle","textstyle"]),bf=new Set(["big","Big","bigg","Bigg","bigl","Bigl","biggl","Biggl","bigr","Bigr","biggr","Biggr"]),yf=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"]),wf={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 kf(e,t){let r="";for(let i of e){let s=t[i];if(s===void 0)return;r+=s}return r}a(kf,"replaceCharacters");function Dl(e){return e.trim().replace(/\s*([=+-])\s*/g,"$1")}a(Dl,"normalizeScriptValue");function hs(e,t){return kf(Dl(e),t==="sub"?pf:df)}a(hs,"formatUnicodeScript");function et(e,t){e=Dl(e);let r=hs(e,t);if(r!==void 0)return r;let i=t==="sub"?"_":"^";return Array.from(e).length===1||t==="sub"&&/^[A-Za-z]+$/.test(e)?`${i}${e}`:`${i}(${e})`}a(et,"formatScript");function vf(e,t){e=e.trim(),t=t.trim();let r=/^[\p{L}\p{N}.]+$/u.test(e),i=/^[\p{N}.]+$/u.test(t)||Array.from(t).length===1;return`${r?e:`(${e})`}/${i?t:`(${t})`}`}a(vf,"formatFraction");function jr(e,t="\u221A"){return e=e.trim(),/^[\p{L}\p{N}.]+$/u.test(e)?`${t}${e}`:`${t}(${e})`}a(jr,"formatRoot");var Fl="\u{F0004}",tt="\u{F0005}",Sf=/(?<=[\p{L}\p{N})\]}\u{f0001}])\u{f0004}/gu,Cf=/\u{f0005}(?=[\p{L}\p{N}√\u{f0000}])/gu;function rt(e){return e.replace(Sf," ").replaceAll(Fl,"").replace(Cf," ").replaceAll(tt,"").split(`
|
|
93
|
-
`).map(t=>t.replace(/[ \t]+/g," ").trim()).filter((t,r,i)=>t.length>0||r>0&&r<i.length-1).join(`
|
|
94
|
-
`).trim()}a(rt,"normalizeOutput");var St="\u{F0000}",er="\u{F0001}",Tf=/\u{f0000}(\d+)\u{f0001}/gu,Af=/\u{f0000}(\d+)\u{f0001}$/u,zr="\u{F0002}";function Be(e,t,r=!1){let i=Math.max(0,t-T(e)),s=r?Math.floor(i/2):0;return`${" ".repeat(s)}${e}${" ".repeat(i-s)}`}a(Be,"padLayoutLine");function Mf(e){if(e.length===0)return{lines:[""],width:0,baseline:0};let t=Math.max(...e.map(s=>s.baseline)),r=Math.max(...e.map(s=>s.lines.length-s.baseline-1)),i=[];for(let s=0;s<=t+r;s++){let n="";for(let o of e){let l=s-t+o.baseline;n+=l>=0&&l<o.lines.length?Be(o.lines[l]??"",o.width):" ".repeat(o.width)}i.push(n.trimEnd())}return{lines:i,width:e.reduce((s,n)=>s+n.width,0),baseline:t}}a(Mf,"joinLayouts");function tr(e,t){let r=[],i=0;for(let s of e.split(`
|
|
95
|
-
`)){let n=[],o=0,l;for(let u of s.matchAll(Tf)){let d=u.index,c=t[Number(u[1])];if(c){if(d>o){let p=s.slice(o,d),f=(l?p.trimStart():p).trimEnd(),g=l?.type==="matrix"&&/^\s/.test(p),x=c.type==="matrix"&&/\s$/.test(p),m=f?`${g?" ":""}${f}${x?" ":""}`:g||x?" ":"";n.push({lines:[m],width:T(m),baseline:0})}if(c.type==="fraction"){let p=tr(c.numerator,t),f=tr(c.denominator,t),g=Math.max(p.width,f.width,1),x=g+2;n.push({lines:[...p.lines.map(m=>Be(m,x,!0)),` ${"\u2500".repeat(g)} `,...f.lines.map(m=>Be(m,x,!0))],width:x,baseline:p.lines.length})}else if(c.type==="operator"){let p=Math.max(T(c.operator),c.lower===void 0?0:T(c.lower),c.upper===void 0?0:T(c.upper)),f=[];c.upper!==void 0&&f.push(`${Be(c.upper,p,!0)} `),f.push(`${Be(c.operator,p,!0)} `),c.lower!==void 0&&f.push(`${Be(c.lower,p,!0)} `),n.push({lines:f,width:p+1,baseline:c.upper===void 0?0:1})}else if(c.type==="script"){let p=c.upper===void 0?void 0:tr(c.upper,t),f=c.lower===void 0?void 0:tr(c.lower,t),g=Math.max(p?.width??0,f?.width??0);n.push({lines:[...p?.lines.map(x=>Be(x,g))??[]," ".repeat(g),...f?.lines.map(x=>Be(x,g))??[]],width:g,baseline:p?.lines.length??0})}else{let p=Math.max(0,...c.lines.map(f=>T(f)));n.push({lines:c.lines.map(f=>Be(f,p)),width:p,baseline:c.baseline})}o=d+u[0].length,l=c}}if(o<s.length){let u=s.slice(o),d=l?u.trimStart():u,c=l?.type==="matrix"&&/^\s/.test(u)?` ${d}`:d;n.push({lines:[c],width:T(c),baseline:0})}let h=Mf(n);r.length===0&&(i=h.baseline),r.push(...h.lines)}return{lines:r,width:Math.max(0,...r.map(s=>T(s))),baseline:i}}a(tr,"renderLayout");var Bf=class th{static{a(this,"_LatexParser")}source;layoutNodes;display;position=0;supported=!0;stackFractions=!0;scriptDepth=0;constructor(t,r,i){this.source=t,this.layoutNodes=r,this.display=i}render(){let t=this.parseSequence();if(!(!this.supported||this.position!==this.source.length))return rt(t)}parseSequence(t){let r="";for(;this.position<this.source.length;){let i=this.source[this.position];if(t&&i===t)return this.position++,r;if(i==="}")return this.supported=!1,r;if(i==="{"){this.position++,r+=this.parseSequence("}");continue}if(i==="\\"){let s=this.parseCommand();s===Ol?(r=r.trimEnd(),r.endsWith(tt)&&(r=r.slice(0,-tt.length))):r+=s;continue}if(i==="^"||i==="_"){this.position++,r=r.trimEnd();let s=this.parseScripts(i);r.endsWith(tt)?r=`${r.slice(0,-tt.length)}${s}${tt}`:r+=s;continue}if(/\s/.test(i)){r+=this.parseWhitespace();continue}if(i==="="||i==="<"||i===">"){r=`${r.trimEnd()} ${i} `,this.position++;continue}if(i==="&"){this.position++;continue}if(i==="~"){this.position++,r+=" ";continue}if(i==="."){let s=Af.exec(r),n=s?this.layoutNodes[Number(s[1])]:void 0;if(n?.type==="matrix"){let o=n.lines.length-1;n.lines[o]=`${n.lines[o]??""}${i}`,this.position++;continue}}r+=i,this.position++}return t&&(this.supported=!1),r}parseScripts(t){let r={},i=[],s=a(c=>{let p=c==="_"?"sub":"sup";this.scriptDepth++;try{r[p]=this.parseRequiredArgument(!1)}finally{this.scriptDepth--}i.push(p)},"parse");s(t);let n=this.position;for(;n<this.source.length&&/\s/.test(this.source[n]??"");)n++;let o=this.source[n];(o==="^"||o==="_")&&o!==t&&(this.position=n+1,s(o));let l=r.sub===void 0?void 0:hs(r.sub,"sub"),h=r.sup===void 0?void 0:hs(r.sup,"sup"),u=![r.sub,r.sup].some(c=>c!==void 0&&(c.includes("/")||!c.includes(St)&&Array.from(c).length>1&&!/[A-Z*∗]/.test(c)));if(!(this.display&&u&&(this.scriptDepth>0||r.sub!==void 0&&l===void 0||r.sup!==void 0&&h===void 0)))return i.map(c=>c==="sub"?l??et(r.sub??"",c):h??et(r.sup??"",c)).join("");let d=this.layoutNodes.push({type:"script",lower:r.sub===void 0?void 0:rt(r.sub),upper:r.sup===void 0?void 0:rt(r.sup)})-1;return`${St}${d}${er}`}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=!1,"";let t="",r=this.source[this.position]??"";if(r===`
|
|
96
|
-
`||r==="\r")return this.position++,r==="\r"&&this.source[this.position]===`
|
|
97
|
-
`&&this.position++," ";if(/[A-Za-z]/.test(r)){let n=this.position;for(;this.position<this.source.length&&/[A-Za-z]/.test(this.source[this.position]??"");)this.position++;t=this.source.slice(n,this.position)}else t=r,this.position++;if(t==="\\")return`
|
|
98
|
-
`;if(ff.has(t))return" ";if(gf.has(t))return Ol;if(mf.has(t)){for(;this.position<this.source.length&&/\s/.test(this.source[this.position]??"");)this.position++;return""}if(xf.has(t))return"";if(t==="{"||t==="}"||t==="$"||t==="%"||t==="#"||t==="_"||t==="&")return t;if(t==="|")return"\u2016";if(t==="not"){let n=this.parseRequiredArgument(!1).trim(),o=uf[n];if(o!==void 0)return` ${o} `;let l=Array.from(n);return l.length===0?(this.supported=!1,""):` ${l[0]}\u0338${l.slice(1).join("")} `}if(lf.has(t))return this.parseOperator(t,"bracket",!0,!0);let i=nf[t];if(i!==void 0)return af.has(t)?this.parseOperator(i,"script",!0):t==="cdot"||t==="times"||hf.has(t)?` ${i} `:i;if(of.has(t))return`${Fl}${t}${tt}`;if(bf.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 n=this.display&&this.stackFractions&&t!=="tfrac",o=this.parseRequiredArgument(!n),l=this.parseRequiredArgument(!n);if(n){let h=this.layoutNodes.push({type:"fraction",numerator:rt(o),denominator:rt(l)})-1;return`${St}${h}${er}`}return vf(o,l)}if(t==="sqrt"){let n=this.parseOptionalArgument()?.trim(),o=this.parseRequiredArgument();return n===void 0||n==="2"?jr(o):n==="3"?jr(o,"\u221B"):n==="4"?jr(o,"\u221C"):`${et(n,"sup")}${jr(o)}`}if(t==="boxed"||t==="fbox")return`[${this.parseRequiredArgument().trim()}]`;if(t==="binom"||t==="dbinom"||t==="tbinom")return`(${this.parseRequiredArgument()} choose ${this.parseRequiredArgument()})`;let s=wf[t];if(s!==void 0){let n=this.parseRequiredArgument();return Array.from(n).length===1?`${n}${s}`:`${t}(${n})`}if(t==="mathbb"){let n=this.parseRequiredArgument();return Array.from(n,o=>cf[o]??o).join("")}if(t==="operatorname"){let n=this.source[this.position]==="*";n&&this.position++;let o=rt(this.parseRequiredArgument()).trim();return this.parseOperator(o,"bracket",n,!0)}if(t==="mod"||t==="bmod")return" mod ";if(t==="pmod"||t==="pod"){let n=this.parseRequiredArgument().trim();return t==="pmod"?` (mod ${n})`:` (${n})`}if(t==="overset"||t==="stackrel"){let n=this.parseRequiredArgument();return`${this.parseRequiredArgument().trim()}${et(n,"sup")}`}if(t==="underset"){let n=this.parseRequiredArgument();return`${this.parseRequiredArgument().trim()}${et(n,"sub")}`}if(yf.has(t)){let n=this.parseRequiredArgument();return t.startsWith("text")||t==="mbox"?n:n.trim()}return t==="begin"?this.parseEnvironment():t==="end"?(this.supported=!1,""):(this.supported=!1,`\\${t}`)}parseOperator(t,r,i,s=!1){let n=i,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&&(n=l[1]==="limits",this.position=o+l[0].length);let h,u;for(;;){let c=this.position;for(;c<this.source.length&&/[ \t]/.test(this.source[c]??"");)c++;let p=this.source[c];if(p!=="_"&&p!=="^")break;this.position=c+1;let f=rt(this.parseRequiredArgument(!1)).replaceAll(" ","");p==="_"?(h!==void 0&&(this.supported=!1),h=f):(u!==void 0&&(this.supported=!1),u=f)}if(this.display&&n&&(h!==void 0||u!==void 0)){let c=this.layoutNodes.push({type:"operator",operator:t,lower:h,upper:u})-1;return`${St}${c}${er}`}let d=t;return h!==void 0&&(d+=r==="bracket"?`[${h}]`:et(h,"sub")),u!==void 0&&(d+=et(u,"sup")),s?` ${d} `:d}parseRequiredArgument(t=!0){let r=this.stackFractions;this.stackFractions=r&&t;let i=this.parseRequiredArgumentValue();return this.stackFractions=r,i}parseRequiredArgumentValue(){for(;this.position<this.source.length&&/\s/.test(this.source[this.position]??"");)this.position++;if(this.position>=this.source.length)return this.supported=!1,"";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=!1;return}let r=this.source.slice(this.position+1,t);return this.position=t+1,this.renderNested(r)}readRawGroup(){for(;this.position<this.source.length&&/[ \t]/.test(this.source[this.position]??"");)this.position++;if(this.source[this.position]!=="{"){this.supported=!1;return}let t=++this.position,r=1;for(;this.position<this.source.length;){let i=this.source[this.position];if(i==="\\"){this.position+=2;continue}if(i==="{"&&r++,i==="}"&&r--,r===0){let s=this.source.slice(t,this.position);return this.position++,s}this.position++}this.supported=!1}splitEnvironmentRows(t){return t.split(/\\\\(?:\[[^\]\n]*\])?/)}parseEnvironment(){let t=this.readRawGroup();if(!t)return"";let r=`\\end{${t}}`,i=this.source.indexOf(r,this.position);if(i<0)return this.supported=!1,"";let s=this.source.slice(this.position,i);if(this.position=i+r.length,t==="equation"||t==="equation*"||t==="displaymath")return this.renderNested(s).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 n=["alignedat","alignat","alignat*"].includes(t),o=n?s.replace(/^\s*\{[^}]*\}/,""):s;return this.splitEnvironmentRows(o).map(l=>{let h=l.split("&"),u=n?Array.from({length:Math.ceil(h.length/2)},(d,c)=>h.slice(c*2,c*2+2).join("")).join(" "):h.join("");return this.renderNested(u).trim()}).filter(Boolean).join(`
|
|
99
|
-
`)}if(t==="cases"||t==="cases*")return this.renderCases(s);if(["array","matrix","smallmatrix","pmatrix","bmatrix","Bmatrix","vmatrix","Vmatrix"].includes(t)){let n=t==="array"?s.replace(/^\s*\{[^}]*\}/,""):s;return this.renderMatrix(t,n)}return this.supported=!1,s}renderCases(t){let r=this.splitEnvironmentRows(t).map(u=>u.split("&").map(d=>this.renderNested(d,!1).trim())).filter(u=>u.some(Boolean)),i=Math.max(0,...r.map(u=>T((u[0]??"").replace(/,\s*$/,"")))),s=r.map(u=>{let d=(u[0]??"").replace(/,\s*$/,""),c=u[1]??"";if(!c)return d;let p=/^(?:if|when|for|otherwise)\b/i.test(c)?" ":" if ";return`${d}${zr.repeat(i-T(d))}${p}${c}`});if(s.length<=1)return s.length===0?"":`\u23A7 ${s[0]}`;let n=Math.floor(s.length/2),o=[...s];s.length%2===0&&o.splice(n,0,void 0);let l=o.map((u,d)=>{let c=d===0?"\u23A7":d===o.length-1?"\u23A9":"\u23A8";return u===void 0?c:`${c} ${u}`}),h=this.layoutNodes.push({type:"matrix",lines:l,baseline:n})-1;return`${St}${h}${er}`}renderMatrix(t,r){let i=this.splitEnvironmentRows(r).map(u=>u.split("&").map(d=>this.renderNested(d,!1).trim())).filter(u=>u.some(Boolean)),s=Math.max(0,...i.map(u=>u.length)),n=Array.from({length:s},(u,d)=>Math.max(0,...i.map(c=>T(c[d]??"")))),o=i.map(u=>Array.from({length:s},(d,c)=>{let p=u[c]??"";return`${p}${zr.repeat(Math.max(0,(n[c]??0)-T(p)))}`}).join(" \u2502 ")),l;if(t==="array"||t==="matrix"||t==="smallmatrix")l=o;else{let u={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(!u)return this.supported=!1,o.join(`
|
|
100
|
-
`);l=o.map((d,c)=>{let p=c===0?u[0]:c===o.length-1?u[4]:u[2],f=c===0?u[1]:c===o.length-1?u[5]:u[3];return`${p} ${d} ${f}`})}if(l.length<=1)return l[0]??"";let h=this.layoutNodes.push({type:"matrix",lines:l,baseline:0})-1;return`${St}${h}${er}`}renderNested(t,r=!0){let i=new th(t,this.layoutNodes,this.display&&r).render();return i===void 0?(this.supported=!1,t):i}};function us(e,t={}){let r=[],i=new Bf(e,r,t.display===!0).render();if(i===void 0)return;if(r.length===0)return i.replaceAll(zr," ");let s=tr(i,r).lines,n=Math.min(...s.filter(o=>o.trim()).map(o=>o.length-o.trimStart().length));return s.map(o=>o.slice(n).trimEnd()).join(`
|
|
101
|
-
`).trimEnd().replaceAll(zr," ")}a(us,"renderLatex");var Rf=/^(~~)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/,Ef=class extends Yt{static{a(this,"StrictStrikethroughTokenizer")}del(e){let t=Rf.exec(e);if(!t)return;let r=t[2];return{type:"del",raw:t[0],text:r,tokens:this.lexer.inlineTokens(r)}}};function If(e,t){let r=0;for(let i=t-1;i>=0&&e[i]==="\\";i--)r++;return r%2===1}a(If,"isEscaped");function Lf(e,t,r){let i=e.indexOf(t,r);for(;i>=0&&If(e,i);)i=e.indexOf(t,i+t.length);return i}a(Lf,"findClosingDelimiter");function Nl(e){return/\\[A-Za-z]+|[_^=+*/<>()[\]|±≤≥≠≈∈→⇒∞∫∑√-]/.test(e)}a(Nl,"looksLikePendingDollarMath");function Pf(e){let t="",r="";if(e.startsWith("$$"))t="$$",r="$$";else if(e.startsWith("\\("))t="\\(",r="\\)";else if(e.startsWith("\\["))t="\\[",r="\\]";else if(e.startsWith("$")&&!/^\$\s/.test(e))t="$",r="$";else return;let i=Lf(e,r,t.length);if(i>=0&&t==="$"&&(/\s$/.test(e.slice(t.length,i))||/^\d/.test(e.slice(i+1))||/^[A-Z_][A-Z0-9_]*(?:[^A-Za-z0-9_\s])?$/.test(e.slice(t.length,i))&&/^[A-Za-z_][A-Za-z0-9_]*/.test(e.slice(i+1))||e.slice(t.length,i).includes("`")))return;if(i<0){let n=e.slice(t.length);return t.startsWith("\\")||Nl(n)?{type:"latex",raw:e,text:n,pending:!0}:void 0}let s=e.slice(t.length,i);return!s||s.includes(`
|
|
102
|
-
`)?void 0:{type:"latex",raw:e.slice(0,i+r.length),text:s}}a(Pf,"tokenizeInlineLatex");function $f(e){let t=/^ {0,3}\$\$[ \t]*(?:\n)?([\s\S]*?)\$\$[ \t]*(?:\n|$)/.exec(e);if(t?.[1])return{type:"latexBlock",raw:t[0],text:t[1].trim()};let r=/^ {0,3}\\\[[ \t]*(?:\n)?([\s\S]*?)\\\][ \t]*(?:\n|$)/.exec(e);if(r?.[1])return{type:"latexBlock",raw:r[0],text:r[1].trim()};let i=/^ {0,3}\\\[[ \t]*(?:\n)?([\s\S]*)$/.exec(e);if(i)return{type:"latexBlock",raw:i[0],text:i[1],pending:!0};let s=/^ {0,3}\$\$[ \t]*(?:\n)?([\s\S]*)$/.exec(e);if(s?.[1]&&Nl(s[1]))return{type:"latexBlock",raw:s[0],text:s[1],pending:!0}}a($f,"tokenizeBlockLatex");var _f=[{name:"latexBlock",level:"block",start(e){let t=/(?:^|\n) {0,3}(?:\$\$|\\\[)/.exec(e);return t?t.index+(t[0].startsWith(`
|
|
103
|
-
`)?1:0):void 0},tokenizer:$f},{name:"latex",level:"inline",start(e){let t=[e.indexOf("$"),e.indexOf("\\("),e.indexOf("\\[")].filter(r=>r>=0);return t.length>0?Math.min(...t):void 0},tokenizer:Pf}];function cs(e){let t=e[e.length-1];if(t?.type==="list"){cs(t.items[t.items.length-1]?.tokens??[]);return}if(t?.type==="blockquote"){cs(t.tokens??[]);return}if(t?.type!=="code")return;let r=/^(`{3,}|~{3,})/.exec(t.raw)?.[1],i=t.raw.split(`
|
|
104
|
-
`).pop();!r||!i||i.length>=r.length||i!==r[0]?.repeat(i.length)||(t.text=t.text.slice(0,-i.length).replace(/\n$/,""))}a(cs,"trimPartialClosingFences");var ds=new Or;ds.setOptions({tokenizer:new Ef}),ds.use({extensions:[..._f]});var Wl=class{static{a(this,"Markdown")}text;paddingX;paddingY;defaultTextStyle;theme;options;defaultStylePrefix;cachedText;cachedWidth;cachedLines;cachedTokens;constructor(e,t,r,i,s,n){this.text=e,this.paddingX=t,this.paddingY=r,this.theme=i,this.defaultTextStyle=s,this.options=n?{...n}:{}}setText(e){this.text=e,this.invalidate()}invalidate(){this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0,kt(this)}render(e){if(this.cachedLines&&this.cachedText===this.text&&this.cachedWidth===e)return this.cachedLines;let t=Math.max(1,e-this.paddingX*2),r=this.options.transform?.(this.text,t)??this.text;if(!r||r.trim()===""){let x=[];return this.cachedText=this.text,this.cachedWidth=e,this.cachedLines=x,x}let i=r.replace(/\t/g," "),s=this.cachedTokens?.deref(),n=s?.source===i?s.tokens:void 0;n||(n=ds.lexer(i),cs(n),this.cachedTokens=new WeakRef({source:i,tokens:n}));let o=[];for(let x=0;x<n.length;x++){let m=n[x],b=n[x+1],C=this.renderToken(m,t,b?.type);for(let S of C)o.push(S)}let l=[];for(let x of o)if(z(x))l.push(x);else for(let m of ve(x,t))l.push(m);let h=" ".repeat(this.paddingX),u=" ".repeat(this.paddingX),d=this.defaultTextStyle?.bgColor,c=[];for(let x of l){if(z(x)){c.push(x);continue}let m=h+x+u;if(d)c.push(mr(m,e,d));else{let b=T(m),C=Math.max(0,e-b);c.push(m+" ".repeat(C))}}let p=" ".repeat(e),f=[];for(let x=0;x<this.paddingY;x++){let m=d?mr(p,e,d):p;f.push(m)}let g=f.concat(c,f);return vi(g),this.cachedText=this.text,this.cachedWidth=e,this.cachedLines=g,g.length>0?g:[""]}applyDefaultStyle(e){if(!this.defaultTextStyle)return e;let t=e;return this.defaultTextStyle.color&&(t=this.defaultTextStyle.color(t)),this.defaultTextStyle.bold&&(t=this.theme.bold(t)),this.defaultTextStyle.italic&&(t=this.theme.italic(t)),this.defaultTextStyle.strikethrough&&(t=this.theme.strikethrough(t)),this.defaultTextStyle.underline&&(t=this.theme.underline(t)),t}getDefaultStylePrefix(){if(!this.defaultTextStyle)return"";if(this.defaultStylePrefix!==void 0)return this.defaultStylePrefix;let e="\0",t=e;this.defaultTextStyle.color&&(t=this.defaultTextStyle.color(t)),this.defaultTextStyle.bold&&(t=this.theme.bold(t)),this.defaultTextStyle.italic&&(t=this.theme.italic(t)),this.defaultTextStyle.strikethrough&&(t=this.theme.strikethrough(t)),this.defaultTextStyle.underline&&(t=this.theme.underline(t));let r=t.indexOf(e);return this.defaultStylePrefix=r>=0?t.slice(0,r):"",this.defaultStylePrefix}getStylePrefix(e){let t=e("\0"),r=t.indexOf("\0");return r>=0?t.slice(0,r):""}getDefaultInlineStyleContext(){return{applyText:a(e=>this.applyDefaultStyle(e),"applyText"),stylePrefix:this.getDefaultStylePrefix()}}renderToken(e,t,r,i){let s=[];switch(e.type){case"heading":{let n=e.depth,o=`${"#".repeat(n)} `,l;n===1?l=a(c=>this.theme.heading(this.theme.bold(this.theme.underline(c))),"headingStyleFn"):l=a(c=>this.theme.heading(this.theme.bold(c)),"headingStyleFn");let h={applyText:l,stylePrefix:this.getStylePrefix(l)},u=this.renderInlineTokens(e.tokens||[],h),d=n>=3?l(o)+u:u;s.push(d),r&&r!=="space"&&s.push("");break}case"paragraph":{let n=this.renderInlineTokens(e.tokens||[],i);s.push(n),r&&r!=="list"&&r!=="space"&&s.push("");break}case"text":s.push(this.renderInlineTokens([e],i));break;case"latexBlock":{let n=e,o=!n.pending&&this.options.renderLatex!==!1?us(n.text,{display:!0})??n.raw.trim():n.raw.trim();for(let l of o.split(`
|
|
105
|
-
`))s.push(this.applyDefaultStyle(l));r&&r!=="space"&&s.push("");break}case"code":{let n=this.theme.codeBlockIndent??" ";if(s.push(this.theme.codeBlockBorder(`\`\`\`${e.lang||""}`)),this.theme.highlightCode){let o=this.theme.highlightCode(e.text,e.lang);for(let l of o)s.push(`${n}${l}`)}else{let o=e.text.split(`
|
|
106
|
-
`);for(let l of o)s.push(`${n}${this.theme.codeBlock(l)}`)}s.push(this.theme.codeBlockBorder("```")),r&&r!=="space"&&s.push("");break}case"list":{let n=this.renderList(e,0,t,i);s.push(...n);break}case"table":{let n=this.renderTable(e,t,r,i);s.push(...n);break}case"blockquote":{let n=a(p=>this.theme.quote(this.theme.italic(p)),"quoteStyle"),o=this.getStylePrefix(n),l=a(p=>{if(!o)return n(p);let f=p.replace(/\x1b\[0m/g,`\x1B[0m${o}`);return n(f)},"applyQuoteStyle"),h=Math.max(1,t-2),u={applyText:a(p=>p,"applyText"),stylePrefix:o},d=e.tokens||[],c=[];for(let p=0;p<d.length;p++){let f=d[p],g=d[p+1];c.push(...this.renderToken(f,h,g?.type,u))}for(;c.length>0&&c[c.length-1]==="";)c.pop();for(let p of c){let f=l(p),g=ve(f,h);for(let x of g)s.push(this.theme.quoteBorder("\u2502 ")+x)}r&&r!=="space"&&s.push("");break}case"hr":s.push(this.theme.hr("\u2500".repeat(Math.min(t,80)))),r&&r!=="space"&&s.push("");break;case"html":"raw"in e&&typeof e.raw=="string"&&s.push(this.applyDefaultStyle(e.raw.trim()));break;case"space":s.push("");break;default:"text"in e&&typeof e.text=="string"&&s.push(e.text)}return s}renderInlineTokens(e,t){let r="",i=t??this.getDefaultInlineStyleContext(),{applyText:s,stylePrefix:n}=i,o=a(l=>l.split(`
|
|
107
|
-
`).map(h=>s(h)).join(`
|
|
108
|
-
`),"applyTextWithNewlines");for(let l of e)switch(l.type){case"latex":{let h=l,u=!h.pending&&this.options.renderLatex!==!1?us(h.text)??h.raw:h.raw;r+=o(u);break}case"escape":r+=o(this.options.preserveBackslashEscapes?l.raw:l.text);break;case"text":l.tokens&&l.tokens.length>0?r+=this.renderInlineTokens(l.tokens,i):r+=o(l.text);break;case"paragraph":r+=this.renderInlineTokens(l.tokens||[],i);break;case"strong":{let h=this.renderInlineTokens(l.tokens||[],i);r+=this.theme.bold(h)+n;break}case"em":{let h=this.renderInlineTokens(l.tokens||[],i);r+=this.theme.italic(h)+n;break}case"codespan":r+=this.theme.code(l.text)+n;break;case"link":{let h=this.renderInlineTokens(l.tokens||[],i),u=this.theme.link(this.theme.underline(h));if(pe().hyperlinks)r+=Nr(u,l.href)+n;else{let d=l.href.startsWith("mailto:")?l.href.slice(7):l.href;l.text===l.href||l.text===d?r+=u+n:r+=u+this.theme.linkUrl(` (${l.href})`)+n}break}case"br":r+=`
|
|
109
|
-
`;break;case"del":{let h=this.renderInlineTokens(l.tokens||[],i);r+=this.theme.strikethrough(h)+n;break}case"html":"raw"in l&&typeof l.raw=="string"&&(r+=o(l.raw));break;default:"text"in l&&typeof l.text=="string"&&(r+=o(l.text))}for(;n&&r.endsWith(n);)r=r.slice(0,-n.length);return r}getOrderedListMarker(e){let t=/^(?: {0,3})(\d{1,9}[.)])[ \t]+/.exec(e.raw);return t?`${t[1]} `:void 0}getUnorderedListMarker(e){let t=/^(?: {0,3})([-+*])(?:[ \t]+|(?=\r?\n|$))/.exec(e.raw);return t?`${t[1]} `:void 0}renderList(e,t,r,i){let s=[],n=" ".repeat(t),o=typeof e.start=="number"?e.start:1;for(let l=0;l<e.items.length;l++){let h=e.items[l],u=l===e.items.length-1,d=e.ordered?this.options.preserveOrderedListMarkers?this.getOrderedListMarker(h)??`${o+l}. `:`${o+l}. `:this.options.preserveOrderedListMarkers?this.getUnorderedListMarker(h)??"- ":"- ",c=h.task?`[${h.checked?"x":" "}] `:"",p=d+c,f=n+this.theme.listBullet(p),g=n+" ".repeat(T(p)),x=Math.max(1,r-T(f)),m=!1;for(let b of h.tokens){if(b.type==="list"){s.push(...this.renderList(b,t+1,r,i)),m=!0;continue}let C=this.renderToken(b,x,void 0,i);for(let S of C)for(let y of ve(S,x)){let k=m?g:f;s.push(k+y),m=!0}}m||s.push(f),e.loose&&!u&&s.push("")}return s}getLongestWordWidth(e,t){let r=e.split(/\s+/).filter(s=>s.length>0),i=0;for(let s of r)i=Math.max(i,T(s));return t===void 0?i:Math.min(i,t)}wrapCellText(e,t,r=""){let i=ve(e,Math.max(1,t));return i.map((s,n)=>{let o=n<i.length-1?"\x1B[22;23;24;25;27;28;29;39m":"";return`${s}${o}${r}`})}renderTable(e,t,r,i){let s=[],n=e.header.length;if(n===0)return s;let o=3*n+1,l=t-o;if(l<n){let y=e.raw?ve(e.raw,t):[];return r&&r!=="space"&&y.push(""),y}let h=30,u=[],d=[];for(let y=0;y<n;y++){let k=this.renderInlineTokens(e.header[y].tokens||[],i);u[y]=T(k),d[y]=Math.max(1,this.getLongestWordWidth(k,h))}for(let y of e.rows)for(let k=0;k<y.length;k++){let v=this.renderInlineTokens(y[k].tokens||[],i);u[k]=Math.max(u[k]||0,T(v)),d[k]=Math.max(d[k]||1,this.getLongestWordWidth(v,h))}let c=d,p=c.reduce((y,k)=>y+k,0);if(p>l){c=new Array(n).fill(1);let y=l-n;if(y>0){let k=d.reduce((w,A)=>w+Math.max(0,A-1),0),v=d.map(w=>{let A=Math.max(0,w-1);return k>0?Math.floor(A/k*y):0});for(let w=0;w<n;w++)c[w]+=v[w]??0;let B=v.reduce((w,A)=>w+A,0),M=y-B;for(let w=0;M>0&&w<n;w++)c[w]++,M--}p=c.reduce((k,v)=>k+v,0)}let f=u.reduce((y,k)=>y+k,0)+o,g;if(f<=t)g=u.map((y,k)=>Math.max(y,c[k]));else{let y=u.reduce((M,w,A)=>M+Math.max(0,w-c[A]),0),k=Math.max(0,l-p);g=c.map((M,w)=>{let A=u[w],L=Math.max(0,A-M),I=0;return y>0&&(I=Math.floor(L/y*k)),M+I});let v=g.reduce((M,w)=>M+w,0),B=l-v;for(;B>0;){let M=!1;for(let w=0;w<n&&B>0;w++)g[w]<u[w]&&(g[w]++,B--,M=!0);if(!M)break}}let x=g.map(y=>"\u2500".repeat(y));s.push(`\u250C\u2500${x.join("\u2500\u252C\u2500")}\u2500\u2510`);let m=e.header.map((y,k)=>{let v=this.renderInlineTokens(y.tokens||[],i);return this.wrapCellText(v,g[k],i?.stylePrefix)}),b=Math.max(...m.map(y=>y.length));for(let y=0;y<b;y++){let k=m.map((v,B)=>{let M=v[y]||"",w=M+" ".repeat(Math.max(0,g[B]-T(M)));return this.theme.bold(w)});s.push(`\u2502 ${k.join(" \u2502 ")} \u2502`)}let C=`\u251C\u2500${g.map(y=>"\u2500".repeat(y)).join("\u2500\u253C\u2500")}\u2500\u2524`;s.push(C);for(let y=0;y<e.rows.length;y++){let k=e.rows[y].map((B,M)=>{let w=this.renderInlineTokens(B.tokens||[],i);return this.wrapCellText(w,g[M],i?.stylePrefix)}),v=Math.max(...k.map(B=>B.length));for(let B=0;B<v;B++){let M=k.map((w,A)=>{let L=w[B]||"";return L+" ".repeat(Math.max(0,g[A]-T(L)))});s.push(`\u2502 ${M.join(" \u2502 ")} \u2502`)}y<e.rows.length-1&&s.push(C)}let S=g.map(y=>"\u2500".repeat(y));return s.push(`\u2514\u2500${S.join("\u2500\u2534\u2500")}\u2500\u2518`),r&&r!=="space"&&s.push(""),s}},Hl=class{static{a(this,"MouseRegion")}child;onMouse;constructor(e,t){this.child=e,this.onMouse=t}render(e){return this.child.render(e)}handleMouse(e){return wt(this.child,e)??this.onMouse(e)}invalidate(){this.child.invalidate()}},ps=class extends Ne{static{a(this,"ScrollView")}child;followEnd;primary;overscroll;scrollbarTrackStyle;scrollbarThumbStyle;currentScrollbar;scrollbarHideDelayMs;currentScrollTop=0;contentHeight=0;currentViewportHeight=0;followingEnd;followSuppressedAtEnd=!1;unreadLines=0;trackedContentHeight=0;hasLaidOut=!1;requestRenderCallback;transientScrollbarVisible=!1;scrollbarActive=!1;scrollbarHideTimer;constructor(e,t={}){if(super(),t.axis!==void 0&&t.axis!=="vertical")throw new Error(`Unsupported ScrollView axis: ${t.axis}`);this.child=e,this.children.push(e),this.followEnd=(t.follow??"none")==="end",this.followingEnd=this.followEnd,this.primary=t.primary??!1,this.overscroll=t.overscroll??"chain",this.currentScrollbar=t.scrollbar??"hidden",this.scrollbarTrackStyle=t.scrollbarTrackStyle??(r=>`\x1B[90m${r}\x1B[39m`),this.scrollbarThumbStyle=t.scrollbarThumbStyle??(r=>`\x1B[37m${r}\x1B[39m`),this.scrollbarHideDelayMs=Math.max(0,Math.floor(t.scrollbarHideDelayMs??1e3))}get scrollTop(){return this.currentScrollTop}get isFollowingEnd(){return this.followingEnd}get unreadCount(){return this.unreadLines}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=!0,this.scrollbarHideTimer&&(clearTimeout(this.scrollbarHideTimer),this.scrollbarHideTimer=void 0),!this.scrollbarActive&&(this.scrollbarHideTimer=setTimeout(()=>{this.scrollbarHideTimer=void 0,this.transientScrollbarVisible=!1,this.requestRenderCallback?.()},this.scrollbarHideDelayMs),this.scrollbarHideTimer.unref()))}hideTransientScrollbar(){this.transientScrollbarVisible=!1,this.scrollbarHideTimer&&(clearTimeout(this.scrollbarHideTimer),this.scrollbarHideTimer=void 0)}setScrollbarActive(e){e!==this.scrollbarActive&&(this.scrollbarActive=e,this.markScrollbarActivity(),this.requestRenderCallback?.())}scrollTo(e,t={}){let r=Number.isFinite(e)?Math.trunc(e):this.currentScrollTop,i=Math.max(0,this.contentHeight-this.currentViewportHeight),s=Math.max(0,Math.min(i,r)),n=t.disableFollow===!0&&s===i,o=!n&&this.followEnd&&s===i;if(s===this.currentScrollTop&&o===this.followingEnd&&n===this.followSuppressedAtEnd)return;let l=s!==this.currentScrollTop;this.currentScrollTop=s,this.followingEnd=o,this.followSuppressedAtEnd=n,this.followingEnd&&(this.unreadLines=0),l&&this.markScrollbarActivity(),this.requestRenderCallback?.()}scrollBy(e){let t=Number.isFinite(e)?Math.trunc(e):0;if(t===0)return 0;let r=Math.max(0,this.contentHeight-this.currentViewportHeight),i=this.followingEnd?r:this.currentScrollTop,s=Math.max(0,Math.min(r,i+t)),n=s-i,o=this.followingEnd;return this.currentScrollTop=s,this.followingEnd=this.followEnd&&s===r,this.followSuppressedAtEnd=!1,this.followingEnd&&(this.unreadLines=0),n!==0&&this.markScrollbarActivity(),(n!==0||this.followingEnd!==o)&&this.requestRenderCallback?.(),t-n}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=!1,this.followingEnd&&(this.unreadLines=0),e&&(this.markScrollbarActivity(),this.requestRenderCallback?.())}scrollToEnd(){let e=Math.max(0,this.contentHeight-this.currentViewportHeight),t=this.currentScrollTop!==e||this.followingEnd!==this.followEnd;this.currentScrollTop=e,this.followingEnd=this.followEnd,this.followSuppressedAtEnd=!1,this.unreadLines=0,t&&(this.markScrollbarActivity(),this.requestRenderCallback?.())}updateLayout(e,t,r){let i=Math.max(0,Math.floor(e));this.hasLaidOut&&!this.followingEnd&&i>this.trackedContentHeight&&(this.unreadLines+=i-this.trackedContentHeight),this.hasLaidOut=!0,this.trackedContentHeight=i,this.contentHeight=i,this.currentViewportHeight=Math.max(0,Math.floor(t)),this.requestRenderCallback=r;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=!1),this.followEnd&&this.currentScrollTop===s&&!this.followSuppressedAtEnd&&(this.followingEnd=!0),this.followingEnd&&(this.unreadLines=0),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 t=this.getContentWidth(e),r=this.child.render(t);return t===e?r:r.map(i=>`${i} `)}[Vr](){return{type:"scroll",component:this.child,state:this}}},Vl=class{static{a(this,"SettingsList")}items;filteredItems;theme;selectedIndex=0;mousePressedIndex;maxVisible;onChange;onCancel;searchInput;searchEnabled;submenuComponent=null;submenuItemIndex=null;navigateAfterClose=null;constructor(e,t,r,i,s,n={}){this.items=e,this.filteredItems=e,this.maxVisible=t,this.theme=r,this.onChange=i,this.onCancel=s,this.searchEnabled=n.enableSearch??!1,this.searchEnabled&&(this.searchInput=new Ur)}updateValue(e,t){let r=this.items.find(i=>i.id===e);r&&(r.currentValue=t)}selectItem(e){let t=(this.searchEnabled?this.filteredItems:this.items).findIndex(r=>r.id===e);t!==-1&&(this.selectedIndex=t)}invalidate(){this.submenuComponent?.invalidate?.()}render(e){return this.submenuComponent?this.submenuComponent.render(e):this.renderMainList(e)}renderMainList(e){let t=[];if(this.searchEnabled&&this.searchInput&&(t.push(...this.searchInput.render(e)),t.push("")),this.items.length===0)return t.push(this.theme.hint(" No settings available")),this.searchEnabled&&this.addHintLine(t,e),t;let r=this.getDisplayItems();if(r.length===0)return t.push(K(this.theme.hint(" No matching settings"),e)),this.addHintLine(t,e),t;let{startIndex:i,endIndex:s}=this.getVisibleRange(r),n=Math.min(36,Math.max(...this.items.map(l=>T(l.label))));for(let l=i;l<s;l++){let h=r[l];if(!h)continue;let u=l===this.selectedIndex,d=u?this.theme.cursor:" ",c=T(d),p=h.label+" ".repeat(Math.max(0,n-T(h.label))),f=this.theme.label(p,u),g=" ",x=c+n+T(g),m=e-x-2,b=this.theme.value(K(h.currentValue,m,""),u);t.push(K(d+f+g+b,e))}if(i>0||s<r.length){let l=` (${this.selectedIndex+1}/${r.length})`;t.push(this.theme.hint(K(l,e-2,"")))}let o=r[this.selectedIndex];if(o?.description){t.push("");let l=ve(o.description,e-4);for(let h of l)t.push(this.theme.description(` ${h}`))}return this.addHintLine(t,e),t}handleMouse(e){if(this.submenuComponent){let o=this.submenuComponent.handleMouse?.(e);return o?{...o,focus:!0}:void 0}if(this.searchEnabled&&this.searchInput){if(e.y===0){let o=this.searchInput.handleMouse?.(e);return o?{...o,focus:!0}:void 0}if(e.y===1)return}let t=this.getDisplayItems();if(t.length===0)return;if(e.type==="wheel"&&e.wheelDelta){let o=e.wheelDelta<0?-1:1,l=this.selectedIndex;return this.selectedIndex=Math.max(0,Math.min(t.length-1,this.selectedIndex+o)),{handled:!0,render:this.selectedIndex!==l}}if(e.button!=="left"||e.type!=="press"&&e.type!=="click")return;let r=this.searchEnabled?2:0,{startIndex:i,endIndex:s}=this.getVisibleRange(t),n=i+e.y-r;if(!(n<i||n>=s)){if(e.type==="press")return this.mousePressedIndex=n,this.selectedIndex=n,{handled:!0,focus:!0};if(e.type==="click")return this.selectedIndex=this.mousePressedIndex??n,this.mousePressedIndex=void 0,this.activateItem(),{handled:!0}}}handleInput(e){if(this.submenuComponent){this.submenuComponent.handleInput?.(e);return}let t=ue(),r=this.getDisplayItems();if(t.matches(e,"tui.select.up")){if(r.length===0)return;this.selectedIndex=this.selectedIndex===0?r.length-1:this.selectedIndex-1}else if(t.matches(e,"tui.select.down")){if(r.length===0)return;this.selectedIndex=this.selectedIndex===r.length-1?0:this.selectedIndex+1}else t.matches(e,"tui.select.confirm")||e===" "&&(!this.searchEnabled||this.searchInput?.getValue().length===0)?this.activateItem():t.matches(e,"tui.select.cancel")?this.onCancel():this.searchEnabled&&this.searchInput&&(this.searchInput.handleInput(e),this.applyFilter(this.searchInput.getValue()))}getDisplayItems(){return this.searchEnabled?this.filteredItems:this.items}getVisibleRange(e){let t=Math.max(0,Math.min(this.selectedIndex-Math.floor(this.maxVisible/2),e.length-this.maxVisible));return{startIndex:t,endIndex:Math.min(t+this.maxVisible,e.length)}}activateItem(){let e=this.getDisplayItems()[this.selectedIndex];if(e){if(e.submenu)this.submenuItemIndex=this.selectedIndex,this.submenuComponent=e.submenu(e.currentValue,(t,r)=>{t!==void 0&&(e.currentValue=t,this.onChange(e.id,t)),r?.navigateTo&&(this.navigateAfterClose=r.navigateTo),this.closeSubmenu()});else if(e.values&&e.values.length>0){let t=(e.values.indexOf(e.currentValue)+1)%e.values.length,r=e.values[t];e.currentValue=r,this.onChange(e.id,r)}}}closeSubmenu(){if(this.submenuComponent=null,this.navigateAfterClose!==null){let e=this.navigateAfterClose;this.navigateAfterClose=null,this.submenuItemIndex=null,this.selectItem(e),this.activateItem()}else this.submenuItemIndex!==null&&(this.selectedIndex=this.submenuItemIndex,this.submenuItemIndex=null)}applyFilter(e){this.filteredItems=Qt(this.items,e,t=>t.label),this.selectedIndex=0}addHintLine(e,t){e.push(""),e.push(K(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"),t))}},ql=class{static{a(this,"Spacer")}lines;constructor(e=1){this.lines=e}setLines(e){this.lines=e}invalidate(){}render(e){let t=[];for(let r=0;r<this.lines;r++)t.push("");return t}},Kl=class{static{a(this,"TruncatedText")}text;paddingX;paddingY;constructor(e,t=0,r=0){this.text=e,this.paddingX=t,this.paddingY=r}invalidate(){}render(e){let t=[],r=" ".repeat(e);for(let f=0;f<this.paddingY;f++)t.push(r);let i=Math.max(1,e-this.paddingX*2),s=this.text,n=this.text.indexOf(`
|
|
110
|
-
`);n!==-1&&(s=this.text.substring(0,n));let o=K(s,i),l=" ".repeat(this.paddingX),h=" ".repeat(this.paddingX),u=l+o+h,d=T(u),c=Math.max(0,e-d),p=u+" ".repeat(c);t.push(p);for(let f=0;f<this.paddingY;f++)t.push(r);return t}},Ul=class extends Ll{static{a(this,"VStack")}layoutType="vstack";constructor(e=[],t={}){super(e,t)}render(e){let t=this.padX,r=this.padY,i={width:Math.max(1,Math.max(1,e)-t*2),height:Number.MAX_SAFE_INTEGER},s=ls(this.entries,i),n=s.map(d=>d.component.render(i.width)),o=Kr(s,n.map(d=>d.length),void 0,this.gap),l=[],h=t>0?" ".repeat(t):"",u=" ".repeat(Math.max(0,e));for(let d=0;d<r;d++)l.push(u);for(let d=0;d<s.length;d++){if(d>0)for(let p=0;p<this.gap;p++)l.push(h);let c=n[d].slice(0,o[d]);l.push(...t>0?c.map(p=>h+p):c);for(let p=c.length;p<o[d];p++)l.push(h)}for(let d=0;d<r;d++)l.push(u);return l}};import{createRequire as Of}from"node:module";import*as Df from"node:path";import{createRequire as Ff}from"node:module";import{dirname as fs,join as Gr}from"node:path";import{fileURLToPath as Nf}from"node:url";var Wf=Ff(import.meta.url),Hf="@earendil-works/pi-tui";function Vf(e,t={}){let r=fs(Nf(t.moduleUrl??import.meta.url)),i=[];try{let s=(t.resolvePackage??Wf.resolve)(Hf);i.push(Gr(fs(s),"..",e))}catch{}return i.push(Gr(r,"..",e),Gr(r,e),Gr(fs(t.execPath??process.execPath),e)),Array.from(new Set(i))}a(Vf,"getNativeModuleCandidates");var qf=Of(import.meta.url),Yr=new Map;function jl(e,t=""){let r=process.arch;if(r!=="x64"&&r!=="arm64")return;let i=Df.join("native",e,"prebuilds",`${e}-${r}`,`${e}-platform${t}.node`);if(Yr.has(i))return Yr.get(i);for(let s of Vf(i))try{let n=qf(s);if(typeof n?.getText=="function"&&typeof n.getImage=="function")return Yr.set(i,n),n}catch{}Yr.set(i,void 0)}a(jl,"loadNativePlatformHelper");function gs(){if(!(process.platform!=="darwin"&&process.platform!=="win32"))return jl(process.platform)}a(gs,"getNativePlatformHelper");function zl(){if(process.platform!=="linux")return gs();if(process.env.DISPLAY)return jl("linux","-x11")}a(zl,"getNativeClipboard");var Kf="\x1B]7501;?\x1B\\";function Uf(e){return/^\x1b\]7501;\?[^\x07\x1b]*(?:\x07|\x1b\\)$/.test(e)}a(Uf,"isProgramStatusReply");var jf=/^[A-Za-z0-9_.+-]{1,32}$/,zf=/[\u0000-\u001f\u007f-\u009f]+/g,Gf=2048;function Yf(e,t){if(Buffer.byteLength(e,"utf8")<=t)return e;let r=0,i=0;for(let s of e){let n=Buffer.byteLength(s,"utf8");if(r+n>t)break;r+=n,i+=s.length}return e.slice(0,i)}a(Yf,"truncateUtf8");function Xr(e){let t=[`state=${e.state}`];e.app!==void 0&&jf.test(e.app)&&t.push(`app=${e.app}`),e.state==="blocked"&&e.kind&&t.push(`kind=${e.kind}`);let r=Yf((e.message??"").replace(zf," ").trim(),Gf);return r&&t.push(`msg=${Buffer.from(r,"utf8").toString("base64")}`),`\x1B]7501;${t.join(":")}\x1B\\`}a(Xr,"formatProgramStatus");import{EventEmitter as Xf}from"events";var fe="\x1B",Qf=50,Zf=10,Gl="\x1B[200~",Qr="\x1B[201~",Jf=50;function eg(e){if(!e.startsWith(fe))return"not-escape";if(e.length===1)return"incomplete";let t=e.slice(1);return t.startsWith("[")?t.startsWith("[M")?e.length>=6?"complete":"incomplete":tg(e):t.startsWith("]")?rg(e):t.startsWith("P")?ig(e):t.startsWith("_")?sg(e):t.startsWith("O")?t.length>=2?"complete":"incomplete":(t.length,"complete")}a(eg,"isCompleteSequence");function tg(e){if(!e.startsWith(`${fe}[`))return"complete";if(e.length<3)return"incomplete";let t=e.slice(2),r=t[t.length-1],i=r.charCodeAt(0);if(i>=64&&i<=126){if(t.startsWith("<")){if(/^<\d+;\d+;\d+[Mm]$/.test(t))return"complete";if(r==="M"||r==="m"){let s=t.slice(1,-1).split(";");if(s.length===3&&s.every(n=>/^\d+$/.test(n)))return"complete"}return"incomplete"}return"complete"}return"incomplete"}a(tg,"isCompleteCsiSequence");function rg(e){return!e.startsWith(`${fe}]`)||e.endsWith(`${fe}\\`)||e.endsWith("\x07")?"complete":"incomplete"}a(rg,"isCompleteOscSequence");function ig(e){return!e.startsWith(`${fe}P`)||e.endsWith(`${fe}\\`)?"complete":"incomplete"}a(ig,"isCompleteDcsSequence");function sg(e){return!e.startsWith(`${fe}_`)||e.endsWith(`${fe}\\`)?"complete":"incomplete"}a(sg,"isCompleteApcSequence");function ng(e){let t=e.match(/^\x1b\[(\d+)(?::\d*)?(?::\d+)?u$/);if(!t)return;let r=parseInt(t[1],10);return r>=32?r:void 0}a(ng,"parseUnmodifiedKittyPrintableCodepoint");function Yl(e){let t=[],r=0;for(;r<e.length;){let i=e.slice(r);if(i.startsWith(fe)){let s=1;for(;s<=i.length;){let n=i.slice(0,s),o=eg(n);if(o==="complete"){if(n==="\x1B\x1B"){let l=i[s];if(l==="["||l==="]"||l==="O"||l==="P"||l==="_"){t.push(fe),r+=1;break}}t.push(n),r+=s;break}else if(o==="incomplete")s++;else{t.push(n),r+=s;break}}if(s>i.length)return{sequences:t,remainder:i}}else{let s=i.codePointAt(0)>65535?2:1;t.push(i.slice(0,s)),r+=s}}return{sequences:t,remainder:""}}a(Yl,"extractCompleteSequences");var Xl=class extends Xf{static{a(this,"StdinBuffer")}buffer="";timeout=null;timeoutMs;escapeTimeoutMs;pasteMode=!1;pasteBuffer="";pendingKittyPrintableCodepoint;pendingKittyPrintableAt=0;constructor(e={}){super(),this.timeoutMs=e.timeout??Qf,this.escapeTimeoutMs=e.escapeTimeout??Zf}process(e){this.timeout&&(clearTimeout(this.timeout),this.timeout=null);let t;if(Buffer.isBuffer(e))if(e.length===1&&e[0]>127){let s=e[0]-128;t=`\x1B${String.fromCharCode(s)}`}else t=e.toString();else t=e;if(t.length===0&&this.buffer.length===0){this.emitDataSequence("");return}if(this.buffer+=t,this.pasteMode){this.pasteBuffer+=this.buffer,this.buffer="";let s=this.pasteBuffer.indexOf(Qr);if(s!==-1){let n=this.pasteBuffer.slice(0,s),o=this.pasteBuffer.slice(s+Qr.length);this.pasteMode=!1,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0,this.emit("paste",n),o.length>0&&this.process(o)}return}let r=this.buffer.indexOf(Gl);if(r!==-1){if(r>0){let n=this.buffer.slice(0,r),o=Yl(n);for(let l of o.sequences)this.emitDataSequence(l)}this.pendingKittyPrintableCodepoint=void 0,this.buffer=this.buffer.slice(r+Gl.length),this.pasteMode=!0,this.pasteBuffer=this.buffer,this.buffer="";let s=this.pasteBuffer.indexOf(Qr);if(s!==-1){let n=this.pasteBuffer.slice(0,s),o=this.pasteBuffer.slice(s+Qr.length);this.pasteMode=!1,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0,this.emit("paste",n),o.length>0&&this.process(o)}return}let i=Yl(this.buffer);this.buffer=i.remainder;for(let s of i.sequences)this.emitDataSequence(s);if(this.buffer.length>0){let s=this.buffer===fe?this.escapeTimeoutMs:this.timeoutMs;this.timeout=setTimeout(()=>{let n=this.flush();for(let o of n)this.emitDataSequence(o)},s)}}emitDataSequence(e){let t=e.length===1?e.codePointAt(0):void 0;if(t!==void 0&&t===this.pendingKittyPrintableCodepoint&&Date.now()-this.pendingKittyPrintableAt<Jf){this.pendingKittyPrintableCodepoint=void 0;return}this.pendingKittyPrintableCodepoint=ng(e),this.pendingKittyPrintableAt=Date.now(),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=!1,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0}getBuffer(){return this.buffer}destroy(){this.clear()}};import*as Ql from"node:fs";import*as og from"node:path";function lg(e){let t=gs();if(!t?.isModifierPressed)return!1;try{return t.isModifierPressed(e)===!0}catch{return!1}}a(lg,"isNativeModifierPressed");function ag(e){if(e.startsWith("\x1B[<")){let t=e.slice(3);return/^<\d+;\d+;\d+[Mm]$/.test(t)||/^\d+;\d+;\d+[Mm]$/.test(t.replace(/^</,""))}return e.startsWith("\x1B[M")&&e.length>=6}a(ag,"isMouseReport");var hg=1e3,Zl="\x1B]9;4;3\x07",Jl="\x1B]9;4;0\x07",ug="\x1B[13;2u",cg=7,dg=150,pg=`\x1B[>${cg}u\x1B[?u`,fg="\x1B[c";function ea(e){let t=e.match(/^\x1b\[\?(\d+)u$/);if(t)return{type:"kitty-flags",flags:Number.parseInt(t[1],10)};if(/^\x1b\[\?[\d;]*c$/.test(e))return{type:"device-attributes"}}a(ea,"parseKeyboardProtocolNegotiationSequence");function ta(e){return e==="\x1B["||/^\x1b\[\?[\d;]*$/.test(e)}a(ta,"isKeyboardProtocolNegotiationSequencePrefix");function ms(){return process.platform==="darwin"&&process.env.TERM_PROGRAM==="Apple_Terminal"}a(ms,"isAppleTerminalSession");function gg(){if(!(process.platform==="win32"||process.pid<=0))try{process.kill(process.pid,"SIGWINCH")}catch{}}a(gg,"refreshTerminalDimensions");function mg(e,t,r){return t&&e==="\r"&&r?ug:e}a(mg,"normalizeNativeShiftEnterInput");var xg=10,bg=100;function yg(e=process.env){let t=Number(e.PI_TUI_ESC_TIMEOUT);return Number.isFinite(t)&&t>0?t:e.SSH_CONNECTION||e.SSH_TTY?bg:xg}a(yg,"resolveEscapeTimeoutMs");var ra=class{static{a(this,"ProcessTerminal")}wasRaw=!1;inputHandler;resizeHandler;_kittyProtocolActive=!1;_modifyOtherKeysActive=!1;keyboardProtocolPushed=!1;pendingKeyboardProtocolDeviceAttributes=0;keyboardProtocolNegotiationBuffer="";keyboardProtocolBufferFlushTimer;stdinBuffer;mouseHandlerActive=!1;setMouseHandlerActive(e){this.mouseHandlerActive=e}stdinDataHandler;progressInterval;programStatus;programStatusSupported=!1;programStatusQueryPending=!1;writeLogPath=(()=>{let e=process.env.PI_TUI_WRITE_LOG||"";if(!e)return"";try{if(Ql.statSync(e).isDirectory()){let t=new Date,r=`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}_${String(t.getHours()).padStart(2,"0")}-${String(t.getMinutes()).padStart(2,"0")}-${String(t.getSeconds()).padStart(2,"0")}`;return og.join(e,`tui-${r}-${process.pid}.log`)}}catch{}return e})();get kittyProtocolActive(){return this._kittyProtocolActive}get modifyOtherKeysActive(){return this._modifyOtherKeysActive}start(e,t){this.inputHandler=e,this.resizeHandler=t,this.wasRaw=process.stdin.isRaw||!1,process.stdin.setRawMode&&process.stdin.setRawMode(!0),process.stdin.setEncoding("utf8"),process.stdin.resume(),process.stdout.write("\x1B[?2004h"),process.stdout.on("resize",this.resizeHandler),gg(),this.enableWindowsVTInput(),this.queryAndEnableKittyProtocol()}setupStdinBuffer(){this.stdinBuffer=new Xl({escapeTimeout:yg()}),this.stdinBuffer.on("data",e=>{if(Uf(e)){this.programStatusQueryPending&&(this.programStatusQueryPending=!1,this.programStatusSupported=!0,this.writeProgramStatus());return}let t=this.readKeyboardProtocolNegotiationSequence(e);if(t==="pending"){this.scheduleKeyboardProtocolNegotiationBufferFlush();return}t&&this.handleKeyboardProtocolNegotiationSequence(t.parsed)||!this.mouseHandlerActive&&ag(e)||this.forwardInputSequence(t?.sequence??e)}),this.stdinBuffer.on("paste",e=>{this.inputHandler&&this.inputHandler(`\x1B[200~${e}\x1B[201~`)}),this.stdinDataHandler=e=>{this.stdinBuffer.process(e)}}queryAndEnableKittyProtocol(){this.setupStdinBuffer(),process.stdin.on("data",this.stdinDataHandler),this.keyboardProtocolPushed=!0,this.pendingKeyboardProtocolDeviceAttributes+=1,this.clearKeyboardProtocolNegotiationBuffer();let e=process.env.PI_PROGRAM_STATUS;this.programStatusSupported=e==="1",this.programStatusQueryPending=e!=="1"&&e!=="0";let t=this.programStatusQueryPending?Kf:"";process.stdout.write(`${pg}${t}${fg}`),this.writeProgramStatus()}handleKeyboardProtocolNegotiationSequence(e){if(this.clearKeyboardProtocolNegotiationBuffer(),e.type==="device-attributes"){if(this.pendingKeyboardProtocolDeviceAttributes===0)return!1;this.pendingKeyboardProtocolDeviceAttributes-=1,this.pendingKeyboardProtocolDeviceAttributes===0&&(this.programStatusQueryPending=!1)}return e.type==="kitty-flags"?(e.flags!==0?(this.disableModifyOtherKeys(),this._kittyProtocolActive||(this._kittyProtocolActive=!0,Ar(!0))):this.enableModifyOtherKeys(),!0):(this._kittyProtocolActive||this.enableModifyOtherKeys(),!0)}readKeyboardProtocolNegotiationSequence(e){if(this.keyboardProtocolNegotiationBuffer){let r=this.keyboardProtocolNegotiationBuffer+e,i=ea(r);if(i)return this.clearKeyboardProtocolNegotiationBuffer(),{parsed:i,sequence:r};if(ta(r))return this.setKeyboardProtocolNegotiationBuffer(r),"pending";this.flushKeyboardProtocolNegotiationBufferAsInput()}let t=ea(e);if(t)return{parsed:t,sequence:e};if(ta(e))return this.setKeyboardProtocolNegotiationBuffer(e),"pending"}setKeyboardProtocolNegotiationBuffer(e){this.clearKeyboardProtocolNegotiationBufferFlushTimer(),this.keyboardProtocolNegotiationBuffer=e}clearKeyboardProtocolNegotiationBuffer(){this.clearKeyboardProtocolNegotiationBufferFlushTimer(),this.keyboardProtocolNegotiationBuffer=""}flushKeyboardProtocolNegotiationBufferAsInput(){if(!this.keyboardProtocolNegotiationBuffer)return;let e=this.keyboardProtocolNegotiationBuffer;this.clearKeyboardProtocolNegotiationBuffer(),this.forwardInputSequence(e)}scheduleKeyboardProtocolNegotiationBufferFlush(){!this.keyboardProtocolNegotiationBuffer||this.keyboardProtocolBufferFlushTimer||(this.keyboardProtocolBufferFlushTimer=setTimeout(()=>{this.keyboardProtocolBufferFlushTimer=void 0,this.flushKeyboardProtocolNegotiationBufferAsInput()},dg))}clearKeyboardProtocolNegotiationBufferFlushTimer(){this.keyboardProtocolBufferFlushTimer&&(clearTimeout(this.keyboardProtocolBufferFlushTimer),this.keyboardProtocolBufferFlushTimer=void 0)}forwardInputSequence(e){if(!this.inputHandler)return;let t=e==="\r"&&(ms()||process.platform==="win32"),r=mg(e,t,t&&lg("shift"));this.inputHandler(r)}enableModifyOtherKeys(){this._kittyProtocolActive||this._modifyOtherKeysActive||(process.stdout.write("\x1B[>4;2m"),this._modifyOtherKeysActive=!0)}disableModifyOtherKeys(){this._modifyOtherKeysActive&&(process.stdout.write("\x1B[>4;0m"),this._modifyOtherKeysActive=!1)}enableWindowsVTInput(){if(process.platform==="win32")try{gs()?.enableVirtualTerminalInput?.()}catch{}}async drainInput(e=1e3,t=50){let r=this.keyboardProtocolPushed||this._kittyProtocolActive;this.clearKeyboardProtocolNegotiationBuffer(),r&&(process.stdout.write("\x1B[<u"),this.keyboardProtocolPushed=!1,this._kittyProtocolActive=!1,Ar(!1)),this.disableModifyOtherKeys();let i=this.inputHandler;this.inputHandler=void 0;let s=Date.now(),n=a(()=>{s=Date.now()},"onData");process.stdin.on("data",n);let o=Date.now()+e;try{for(;;){let l=Date.now(),h=o-l;if(h<=0||l-s>=t)break;await new Promise(u=>setTimeout(u,Math.min(t,h)))}}finally{process.stdin.removeListener("data",n),this.inputHandler=i}}stop(){this.clearProgressInterval()&&process.stdout.write(Jl),this.programStatusSupported&&this.programStatus&&process.stdout.write(Xr({state:"clear"})),this.programStatusSupported=!1,this.programStatusQueryPending=!1,process.stdout.write("\x1B[?2004l");let e=this.keyboardProtocolPushed||this._kittyProtocolActive;this.clearKeyboardProtocolNegotiationBuffer(),e&&(process.stdout.write("\x1B[<u"),this.keyboardProtocolPushed=!1,this._kittyProtocolActive=!1,Ar(!1)),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(e){if(process.stdout.write(e),this.writeLogPath)try{Ql.appendFileSync(this.writeLogPath,e,{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(e){e>0?process.stdout.write(`\x1B[${e}B`):e<0&&process.stdout.write(`\x1B[${-e}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(e){process.stdout.write(`\x1B]0;${e}\x07`)}setProgramStatus(e){this.programStatus=e.state==="clear"?void 0:e,this.programStatusSupported&&process.stdout.write(Xr(e))}writeProgramStatus(){this.programStatusSupported&&this.programStatus&&process.stdout.write(Xr(this.programStatus))}setProgress(e){e?(process.stdout.write(Zl),this.progressInterval||(this.progressInterval=setInterval(()=>{process.stdout.write(Zl)},hg))):(this.clearProgressInterval(),process.stdout.write(Jl))}clearProgressInterval(){return this.progressInterval?(clearInterval(this.progressInterval),this.progressInterval=void 0,!0):!1}},wg=mi(),kg=/^[\x20-\x7e]*$/;function vg(e){let t=[],r=[],i=0,s=!1,n=a(()=>{s&&(t.push(" "),i+=1,s=!1)},"appendSeparator");for(let o=0;o<e.length;o++){let l=fr(e[o]??""),h=0;if(kg.test(l)){let u=0;for(;u<l.length;){if(l.charCodeAt(u)===32){i>0&&(s=!0),h+=1,u+=1;continue}let d=u+1;for(;d<l.length&&l.charCodeAt(d)!==32;)d+=1;n();let c=l.slice(u,d);t.push(c),r.push({textStart:i,textEnd:i+c.length,row:o,startCol:h,endCol:h+c.length,linearColumns:!0}),i+=c.length,h+=c.length,u=d}}else for(let u of wg.segment(l)){let d=u.segment,c=T(d);if(/^\s+$/u.test(d)){i>0&&(s=!0),h+=c;continue}n(),t.push(d),r.push({textStart:i,textEnd:i+d.length,row:o,startCol:h,endCol:h+c,linearColumns:!1}),i+=d.length,h+=c}i>0&&(s=!0)}return{text:t.join(""),spans:r}}a(vg,"buildSearchCorpus");function Sg(e){return e.replace(/\s+/gu," ").trim()}a(Sg,"normalizeQuery");function Cg(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}a(Cg,"escapeRegExp");function Tg(e,t){if(!t)return[];let r=new RegExp(Cg(t),"giu"),i=[],s=0;for(let n of e.text.matchAll(r)){let o=n.index,l=o+n[0].length;for(;s<e.spans.length&&e.spans[s].textEnd<=o;)s+=1;let h=[];for(let u=s;u<e.spans.length;u++){let d=e.spans[u];if(d.textStart>=l)break;if(d.textEnd<=o)continue;let c=d.linearColumns?d.startCol+Math.max(o,d.textStart)-d.textStart:d.startCol,p=d.linearColumns?d.startCol+Math.min(l,d.textEnd)-d.textStart:d.endCol,f=h[h.length-1];f&&f.row===d.row&&c<=f.endCol?f.endCol=Math.max(f.endCol,p):h.push({row:d.row,startCol:c,endCol:p})}for(;s<e.spans.length&&e.spans[s].textEnd<=l;)s+=1;h.length>0&&i.push({segments:h})}return i}a(Tg,"findSearchCorpusMatches");var Ag=class{static{a(this,"AltScreenSearchIndex")}sourceLines;corpus;normalizedQuery;matches=[];search(e,t){let r=this.sourceLines?.length!==e.length;if(!r&&this.sourceLines){for(let n=0;n<e.length;n++)if(this.sourceLines[n]!==e[n]){r=!0;break}}(r||!this.corpus)&&(this.sourceLines=Array.from(e),this.corpus=vg(e));let i=Sg(t),s=r||i!==this.normalizedQuery;return s&&(this.normalizedQuery=i,this.matches=Tg(this.corpus,i)),{matches:this.matches,changed:s}}};function ia(e){let t=e.segments[0],r=e.segments[e.segments.length-1];return t&&r?`${t.row}:${t.startCol}:${r.row}:${r.endCol}`:""}a(ia,"getAltScreenSearchMatchKey");var Mg=class{static{a(this,"AltScreenSearchComponent")}input=new Ur({prompt:" ",placeholder:"Find in transcript",placeholderStyle:a(e=>`\x1B[2m${e}\x1B[22m`,"placeholderStyle")});onQueryChange;navigationButtonStyle;resultCount=0;resultIndex=-1;previousButtonStart=-1;previousButtonEnd=-1;nextButtonStart=-1;nextButtonEnd=-1;hoveredNavigationDirection;_focused=!1;constructor(e,t=r=>r){this.onQueryChange=e,this.navigationButtonStyle=t}get focused(){return this._focused}set focused(e){this._focused=e,this.input.focused=e}setResult(e,t){this.resultIndex=e,this.resultCount=t}getNavigationDirectionAt(e,t){if(e===2){if(t>=this.previousButtonStart&&t<this.previousButtonEnd)return-1;if(t>=this.nextButtonStart&&t<this.nextButtonEnd)return 1}}setHoveredNavigationDirection(e){return e===this.hoveredNavigationDirection?!1:(this.hoveredNavigationDirection=e,!0)}handleInput(e){let t=this.input.getValue();this.input.handleInput(e);let r=this.input.getValue();r!==t&&this.onQueryChange(r)}invalidate(){this.input.invalidate()}render(e){let t=Math.max(1,e),r=Math.max(0,t-2),i=a(L=>L?L.split("+").map(I=>process.platform==="darwin"&&I.toLowerCase()==="alt"?"Option":I.charAt(0).toUpperCase()+I.slice(1)).join("+"):"Unbound","formatKey"),s=ue(),n=i(s.getKeys("tui.altScreen.searchPrevious")[0]),o=i(s.getKeys("tui.altScreen.searchNext")[0]),l=this.input.getValue()?this.resultCount===0?"No matches":`${this.resultIndex+1}/${this.resultCount}`:"",h=Math.max(0,r-3),u=K(l,h,""),d=u?`\x1B[2m ${u} \x1B[22m`:"",c=Math.max(0,r-T(d)),p=K(this.input.render(Math.max(1,c))[0]??"",c,""),f=" ".repeat(Math.max(0,c-T(p))),g=`${p}${f}${d}`,x=`\u2191 ${n}`,m=`\u2193 ${o}`,b=" \xB7 ",C=1,S=Math.max(0,r-C*2-1),y=T(x)+T(b)+T(m);y>S&&(x="\u2191",m="\u2193",b=" ",y=T(x)+T(b)+T(m));let k=y<=S,v=k?this.navigationButtonStyle(x,this.hoveredNavigationDirection===-1)+b+this.navigationButtonStyle(m,this.hoveredNavigationDirection===1):"",B=k?C*2:0,M=v&&r>y+B?1:0,w=Math.max(0,r-(k?y:0)-B-M),A=1+w+C;return this.previousButtonStart=k?A:-1,this.previousButtonEnd=k?A+T(x):-1,this.nextButtonStart=k?this.previousButtonEnd+T(b):-1,this.nextButtonEnd=k?this.nextButtonStart+T(m):-1,t===1?["\u250C","\u2502","\u2514"]:[`\u250C${"\u2500".repeat(r)}\u2510`,`\u2502${g}\u2502`,`\u2514${"\u2500".repeat(w)}${v?" ":""}${v}${v?" ":""}${"\u2500".repeat(M)}\u2518`]}},Bg=1e3,Rg=class{static{a(this,"AltScreenFlashContainer")}entries=[];nextId=0;requestRender;constructor(e){this.requestRender=e}flash(e,t=Bg){let r=this.nextId++,i=setTimeout(()=>{let s=this.entries.findIndex(n=>n.id===r);s!==-1&&(this.entries.splice(s,1),this.requestRender())},Math.max(0,t));i.unref(),this.entries.push({id:r,message:e,timer:i}),this.requestRender()}dispose(){for(let e of this.entries)clearTimeout(e.timer);this.entries.length=0}invalidate(){}render(e){return this.entries.map(t=>`\x1B[7m${K(` ${t.message} `,e,"")}\x1B[27m`)}},Eg=/^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/,sa=new WeakMap;function rr(e,t,r,i,s){let n=i===0?0:t.prefix[i-1]??0;for(let o=i;o<r.length;o++){let l=ir(e,r[o],s);t.heights[o]=l,n+=l,t.prefix[o]=n}t.heights.length=r.length,t.prefix.length=r.length,t.total=n,t.lastChild=r.length===0?void 0:r[r.length-1]}a(rr,"remeasureExactContainerRange");function na(e,t,r){let i=t.children,s=sa.get(t);if(!s||s.width!==r)return s={width:r,generation:t.layoutGeneration,lastChild:void 0,heights:[],prefix:[],total:0},sa.set(t,s),rr(e,s,i,0,r),s;let n=s.generation!==t.layoutGeneration;if(s.generation=t.layoutGeneration,i.length<s.heights.length)return rr(e,s,i,0,r),s;if(i.length>s.heights.length){let o=s.lastChild,l=s.heights.length===0||o===i[s.heights.length-1];return rr(e,s,i,l?s.heights.length:0,r),s}if(n)return rr(e,s,i,0,r),s;if(i.length>0){let o=i[i.length-1];if(o!==s.lastChild)return rr(e,s,i,0,r),s;let l=s.heights[i.length-1],h=ir(e,o,r);if(h!==l){s.heights[i.length-1]=h;let u=(i.length===1?0:s.prefix[i.length-2])+h;s.prefix[i.length-1]=u,s.total=u}}return s}a(na,"syncExactContainerMetrics");function Ig(e,t){let r=0,i=e.length;for(;r<i;){let s=r+i>>1;(e[s]??0)>t?i=s:r=s+1}return r}a(Ig,"firstIndexPast");function Ct(e,t){let r=Math.max(e.x,t.x),i=Math.max(e.y,t.y),s=Math.min(e.x+e.width,t.x+t.width),n=Math.min(e.y+e.height,t.y+t.height);return{x:r,y:i,width:Math.max(0,s-r),height:Math.max(0,n-i)}}a(Ct,"intersect");function oa(e,t,r){let i=Math.max(1,Math.floor(r)),s=e.renderCache.get(t);s||(s=new Map,e.renderCache.set(t,s));let n=s.get(i);return n||(n=t.render(i),s.set(i,n)),n}a(oa,"renderCached");function ir(e,t,r){let i=Math.max(1,Math.floor(r));return Zr(t)&&!qr(t)?na(e,t,i).total:t.render(i).length}a(ir,"measureHeight");function la(e,t,r){if(Zr(t)&&!qr(t)){let i=0;for(let s of t.children)i=Math.max(i,la(e,s,r));return i}return t.render(Math.max(1,Math.floor(r))).reduce((i,s)=>Math.max(i,T(s)),0)}a(la,"measureWidth");function xs(e,t){return e.parent=t,e}a(xs,"withParent");function aa(e,t){e.rect.y+=t;for(let r of e.children)aa(r,t)}a(aa,"translateBox");function ha(e,t){e.clip=Ct(t,e.rect);for(let r of e.children)ha(r,e.clip)}a(ha,"updateClips");function Zr(e){return e.constructor===Ne}a(Zr,"isExactContainer");function Lg(e,t,r,i,s,n,o){let l=t.children,h=na(e,t,s),u=n===void 0?h.total:Math.max(0,Math.floor(n)),d={x:r,y:i,width:s,height:u},c={component:t,rect:d,clip:Ct(o,d),children:[],layer:0};if(l.length===0||c.clip.height<=0)return c;let p=Ig(h.prefix,c.clip.y-i),f=c.clip.y+c.clip.height-i;for(let g=p;g<l.length;g++){let x=h.heights[g],m=i+(g===0?0:h.prefix[g-1]);if(m>=c.clip.y+c.clip.height||(x>0&&m<c.clip.y+c.clip.height&&m+x>c.clip.y&&c.children.push(xs(Tt(e,l[g],r,m,s,x,c.clip),c)),g>0&&h.prefix[g-1]>=f))break}return c}a(Lg,"layoutExactContainer");function Pg(e,t,r,i,s,n,o){let l=oa(e,t,s),h=n===void 0?l.length:Math.max(0,Math.floor(n)),u=0;if(l.length>h&&h>0){let d=l.findIndex(c=>c.includes(Fe));d>=h&&(u=d-h+1)}return{component:t,rect:{x:r,y:i,width:s,height:h},clip:Ct(o,{x:r,y:i,width:s,height:h}),children:[],lines:l,lineOffset:u,layer:0}}a(Pg,"layoutLeaf");function Tt(e,t,r,i,s,n,o){let l=Math.max(1,Math.floor(s)),h=qr(t);if(!h)return Zr(t)?Lg(e,t,r,i,l,n,o):Pg(e,t,r,i,l,n,o);if(h.type==="scroll"){let v=h.state.getContentWidth(l),B=Zr(h.component),M=h.state.scrollTop,w,A;if(B){A=ir(e,h.component,v);let he=n===void 0?A:Math.max(0,Math.floor(n));h.state.updateLayout(A,he,e.requestRender),w=Tt(e,h.component,r,i-h.state.scrollTop,v,void 0,o)}else{w=Tt(e,h.component,r,i-M,v,void 0,o),A=w.rect.height;let he=n===void 0?A:Math.max(0,Math.floor(n));h.state.updateLayout(A,he,e.requestRender),aa(w,M-h.state.scrollTop)}let L=n===void 0?A:Math.max(0,Math.floor(n)),I=h.state;(h.state.primary||!e.primaryScrollView)&&(e.primaryScrollView=I);let V={x:r,y:i,width:l,height:L},O=Ct(o,V),G={component:t,rect:V,clip:O,children:[w],scrollView:I,scrollContentLines:B?void 0:oa(e,h.component,v),layer:0};return w.parent=G,ha(w,O),G}let u=ls(h.entries,e.viewport),d=Math.max(0,u.length-1)*h.gap,c=Math.max(0,Math.floor(h.padX??0)),p=Math.max(0,Math.floor(h.padY??0)),f=Math.max(1,l-c*2),g=r+c;if(h.type==="vstack"){let v=u.map(O=>typeof O.basis=="number"?O.basis:ir(e,O.component,f)),B=n===void 0?void 0:Math.max(0,Math.floor(n)-p*2),M=Kr(u,v,B,h.gap),w=M.reduce((O,G)=>O+G,0)+d+p*2,A=n===void 0?w:Math.max(0,Math.floor(n)),L={x:r,y:i,width:l,height:A},I={component:t,rect:L,clip:Ct(o,L),children:[],layer:0},V=i+p;for(let O=0;O<u.length;O++)I.children.push(xs(Tt(e,u[O].component,g,V,f,M[O],I.clip),I)),V+=M[O]+h.gap;return I}let x=u.map(v=>typeof v.basis=="number"?v.basis:la(e,v.component,f)),m=Kr(u,x,f,h.gap),b=u.map((v,B)=>ir(e,v.component,Math.max(1,m[B]))),C=n===void 0?b.reduce((v,B)=>Math.max(v,B),0):Math.max(0,n),S={x:r,y:i,width:l,height:C},y={component:t,rect:S,clip:Ct(o,S),children:[],layer:0},k=g;for(let v=0;v<u.length;v++){let B=b[v],M=h.align==="stretch"?C:Math.min(C,B),w=i;h.align==="center"?w+=Math.floor((C-M)/2):h.align==="end"&&(w+=C-M);let A=m[v];A===0?y.children.push({component:u[v].component,rect:{x:k,y:w,width:0,height:M},clip:{x:k,y:w,width:0,height:0},children:[],parent:y,layer:0}):y.children.push(xs(Tt(e,u[v].component,k,w,A,M,y.clip),y)),k+=A+h.gap}return y}a(Tt,"layoutComponent");function $g(e,t,r,i,s){if(z(e))return e;let n=wi(e,t),o=n?.start??t,l=n?.end??t+1,h=Y(e,0,o,!0),u=Y(e,o,l-o,!0),d=Y(e,l,Math.max(0,r-l),!0),c="",p=0;for(;p<u.length;){let b=j(u,p);if(!b)break;c+=b.code,p+=b.length}let f=" ".repeat(Math.max(0,o-T(h))),g=" ".repeat(Math.max(0,t-o)),x=" ".repeat(Math.max(0,l-t-1)),m=`\x1B[0m${pe().hyperlinks?"\x1B]8;;\x07":""}${s?Oc(c):""}`;return`${h}${f}${m}${g}${i}${x}${d}`}a($g,"replaceScrollbarCell");function sr(e,t=!1){if(!e.scrollView||e.rect.width<=0||e.rect.height<=0)return;let r=e.children[0]?.rect.height??e.scrollContentLines?.length??0,i=e.rect.height,s=t&&e.scrollView.scrollbar==="auto"&&r>i;if(!e.scrollView.isScrollbarVisible&&!s)return;let n=Math.min(2,i),o=Math.max(n,Math.min(i,Math.round(i*i/r))),l=Math.max(0,r-i),h=i-o,u=l===0?0:Math.round(e.scrollView.scrollTop/l*h),d=e.rect.x+e.rect.width-1;if(!(d<e.clip.x||d>=e.clip.x+e.clip.width))return{column:d,trackTop:e.rect.y,trackHeight:i,thumbTop:e.rect.y+u,thumbHeight:o,maxScrollTop:l}}a(sr,"getScrollbarGeometry");function _g(e,t,r){let i=sr(e);if(!(!i||!e.scrollView))for(let s=0;s<i.trackHeight;s++){let n=i.trackTop+s;if(n<e.clip.y||n>=e.clip.y+e.clip.height||n<0||n>=t.length)continue;let o=n>=i.thumbTop&&n<i.thumbTop+i.thumbHeight?e.scrollView.scrollbarThumbStyle(e.scrollView.isScrollbarActive?"\u2588":"\u2503"):e.scrollView.scrollbarTrackStyle("\u2502");t[n]=$g(t[n]??"",i.column,r,o,e.scrollView.scrollbar!=="always")}}a(_g,"paintScrollbar");function Og(e,t,r){let i=e.scrollView?.unreadCount??0;if(i<=0||e.clip.height<=0)return;let s=Math.min(t.length,e.clip.y+e.clip.height)-1;if(s<e.clip.y||s<0)return;let n=`\x1B[7m +${i} \x1B[27m`,o=T(n),l=Math.max(e.clip.x,e.rect.x+e.rect.width-o);t[s]=Xe(t[s]??"",n,l,o,r)}a(Og,"paintUnreadIndicator");function ua(e,t,r){if(e.lines){let i=e.lineOffset??0,s=Math.max(e.rect.y,e.clip.y,0),n=Math.min(e.rect.y+e.rect.height,e.clip.y+e.clip.height,t.length);for(let o=s;o<n;o++){let l=e.lines[i+o-e.rect.y];if(l===void 0)continue;let h=l.replace(Eg,""),u=Xi(h);if(u){let d=Math.min(t.length,e.clip.y+e.clip.height),c=Math.min(u.rows,d-o);c<u.rows&&(h=el(h,0,c))}e.rect.x===0&&e.rect.width>=r&&(z(h)||!t[o])?t[o]=h:t[o]=Xe(t[o]??"",h,e.rect.x,e.rect.width,r)}}for(let i of e.children)ua(i,t,r);if(e.scrollView&&e.scrollContentLines&&e.scrollView.scrollTop>0&&e.rect.height>0)for(let i=e.scrollView.scrollTop-1;i>=0;i--){let s=e.scrollContentLines[i]??"",n=Xi(s);if(n){let o=e.scrollView.scrollTop-i;if(o<n.rows){let l=Math.min(e.rect.height,n.rows-o),h=el(s,o,l);e.rect.x===0&&e.rect.width>=r&&(t[e.rect.y]=h)}break}if(s!=="")break}_g(e,t,r),Og(e,t,r)}a(ua,"paintBox");function ca(e,t,r,i){let s=Math.max(1,Math.floor(t)),n=Math.max(1,Math.floor(r)),o={viewport:{width:s,height:n},renderCache:new Map,requestRender:i,primaryScrollView:void 0},l=Tt(o,e,0,0,s,n,{x:0,y:0,width:s,height:n}),h=Array.from({length:n},()=>"");return ua(l,h,s),{root:l,width:s,height:n,lines:h,...o.primaryScrollView===void 0?{}:{primaryScrollView:o.primaryScrollView}}}a(ca,"renderLayoutFrame");function bs(e,t,r){return t>=e.x&&t<e.x+e.width&&r>=e.y&&r<e.y+e.height}a(bs,"containsPoint");function Dg(e,t,r){let i=[],s=a((n,o)=>{if(bs(n.clip,t,r)){i.push({box:n,depth:o});for(let l of n.children)s(l,o+1)}},"visit");return s(e.root,0),i.sort((n,o)=>o.box.layer-n.box.layer||o.depth-n.depth),i.map(({box:n})=>n)}a(Dg,"getLayoutBoxesAt");function ge(e,t){let r=a(i=>{if(i.scrollView===t)return i;for(let s of i.children){let n=r(s);if(n)return n}},"visit");return r(e.root)}a(ge,"getScrollViewBox");function ys(e,t,r){let i=[],s=a((n,o)=>{if(bs(n.clip,t,r)){n.scrollView&&bs(n.rect,t,r)&&i.push({scrollView:n.scrollView,depth:o});for(let l of n.children)s(l,o+1)}},"visit");return s(e.root,0),i.sort((n,o)=>o.depth-n.depth),i.map(n=>n.scrollView)}a(ys,"getScrollViewsAt");function Fg(){let e=process.env;return process.platform==="darwin"&&e.SSH_CONNECTION===void 0&&e.SSH_CLIENT===void 0&&e.SSH_TTY===void 0}a(Fg,"terminalAcceleratesWheel");var Ng=class{static{a(this,"WheelScrollAccelerator")}lines;accelerate;lastTime=Number.NEGATIVE_INFINITY;lastDirection=0;averageGap;carry=0;constructor(e="auto",t=!Fg()){this.lines=e,this.accelerate=t}setLines(e){this.lines=e,this.reset()}next(e,t){if(this.lines!=="auto")return Number.isFinite(this.lines)?Math.max(1,Math.floor(this.lines)):1;if(!this.accelerate)return 1;let r=t-this.lastTime,i=e===this.lastDirection&&r<=200;if(this.lastTime=t,this.lastDirection=e,!i)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,n=Math.floor(s);return this.carry=s-n,n}reset(){this.lastTime=Number.NEGATIVE_INFINITY,this.lastDirection=0,this.averageGap=void 0,this.carry=0}},Wg="\x1B[?1049h",da="\x1B[?1049l",pa="\x1B[?7l",fa="\x1B[?7h",Hg="\x1B[?1000h\x1B[?1002h\x1B[?1004h\x1B[?1006h",Vg="\x1B[?1000h\x1B[?1002h\x1B[?1003h\x1B[?1004h\x1B[?1006h",qg="\x1B[?1006l\x1B[?1004l\x1B[?1003l\x1B[?1002l\x1B[?1000l",Kg="\x1B[I",Ug="\x1B[O",Jr="\x1B[?2026h",ei="\x1B[?2026l",ga=/^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/,jg=/^\x1b\]133;A(?:\x07|\x1b\\)/,ma=4,zg=5,Gg=16,Yg=32*1024*1024,Xg=64*1024*1024,xa=500,Qg=5e3,Zg=new Set(["/","-"]),Jg=xi(),ba=class extends cl{static{a(this,"TuiAltScreen")}mode="fullscreen";[hl]=!0;previousScreen=[];lastDocument=[];previousScreenWidth=0;previousScreenHeight=0;layoutRoot;currentLayout;implicitDocument;implicitScrollView;flashes;altScreenActive=!1;imageProtocol=null;savedCapabilities;uploadedKittyImages=new Map;selectionAnchor;selectionFocus;selectionGranularity="character";selectionInitialRange;lastClick;selectionDragPointer;selectionAutoScrollDirection=0;selectionAutoScrollTimer;selectionPressActive=!1;scrollbarDrag;scrollbarHover;scrollToEndIndicatorRect;activeSearch;pressedUrl;selectionDragged=!1;mouseCapture;mousePressTarget;mousePressPoint;mousePressMoved=!1;lastComponentClick;wheelScroll;mouseEnabled;searchMatchStyle;searchCurrentMatchStyle;searchNavigationButtonStyle;scrollToEndIndicator;openUrl;onRightClickPaste;copyOnSelect;copySelection;constructor(e,t,r,i={}){super(e,t,r),this.implicitDocument={render:a(s=>super.render(s),"render"),handleMouse:a(s=>super.handleMouse(s),"handleMouse"),invalidate:a(()=>{for(let s of this.children)s.invalidate()},"invalidate")},this.implicitScrollView=new ps(this.implicitDocument,{follow:"end",primary:!0}),this.flashes=new Rg(()=>this.requestRender()),this.wheelScroll=new Ng(i.wheelScrollLines??1),this.mouseEnabled=i.mouse??!0,this.searchMatchStyle=i.searchMatchStyle??(s=>`\x1B[4m${s}\x1B[24m`),this.searchCurrentMatchStyle=i.searchCurrentMatchStyle??(s=>`\x1B[1;7m${s}\x1B[22;27m`),this.searchNavigationButtonStyle=i.searchNavigationButtonStyle??(s=>s),this.scrollToEndIndicator=i.scrollToEndIndicator,this.openUrl=i.openUrl,this.onRightClickPaste=i.onRightClickPaste,this.copyOnSelect=i.copyOnSelect??!0,this.copySelection=i.copySelection,this.addInputListener(s=>this.handleViewportInput(s))}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):!1}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=!1,this.stopScrollbarHover(),this.stopScrollbarDrag(),this.flashes.dispose(),this.altScreenActive=!0;let e=pe();this.imageProtocol=e.images,this.uploadedKittyImages.clear(),e.images==="iterm2"&&(this.savedCapabilities=e,zi({...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=!1,this.clearComponentMouseGesture(),this.lastComponentClick=void 0,this.resetRenderState();let t=process.env.TERM?.toLowerCase()??"",r=process.env.TMUX!==void 0||process.env.ZELLIJ!==void 0||process.env.STY!==void 0||t.startsWith("tmux")||t.startsWith("screen")?Hg:Vg;this.terminal.setMouseHandlerActive?.(this.mouseEnabled),this.terminal.write(`${Wg}${pa}${this.mouseEnabled?r:""}\x1B[2J\x1B[H\x1B[?25l`)}beforeTerminalStop(e){this.closeSearch(),this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.stopScrollbarHover(),this.stopScrollbarDrag(),this.clearComponentMouseGesture(),this.flashes.dispose(),this.altScreenActive&&(this.terminal.setMouseHandlerActive?.(!1),this.terminal.write(`${Jr}${this.deleteKittyImages()}${qg}${fa}${ei}`),this.uploadedKittyImages.clear())}afterTerminalStop(e){if(this.altScreenActive){if(this.altScreenActive=!1,e.preserveScreen)this.terminal.write(`${Jr}${da}\x1B[?25h${ei}`);else{let t=Math.max(1,this.terminal.columns),r=this.resolveFakeCursors(this.render(t)).map(s=>s.replace(ga,""));this.lastDocument=this.applyLineResets(r.map(s=>s.replaceAll(Fe,""))).map(s=>z(s)||T(s)<=t?s:Y(s,0,t,!0));let i=`${Jr}${da}${pa}`;for(let s=0;s<this.lastDocument.length;s++)s>0&&(i+=`\r
|
|
111
|
-
`),i+=`\r\x1B[2K${this.lastDocument[s]??""}`;i+=`\x1B[0m${fa}\r
|
|
112
|
-
\x1B[?25h${ei}`,this.terminal.write(i)}this.savedCapabilities&&(zi(this.savedCapabilities),this.savedCapabilities=void 0)}}deleteKittyImages(){return this.imageProtocol==="kitty"?Yo():""}prepareKittyScreen(e){let t=new Set,r=e.map(l=>{let h=Fp(l);if(!h)return l;t.add(h.imageId);let u=this.uploadedKittyImages.get(h.imageId),d={transmissionGeneration:h.transmissionGeneration,transmissionBytes:h.transmissionBytes,estimatedDecodedBytes:h.estimatedDecodedBytes};return u&&this.uploadedKittyImages.delete(h.imageId),this.uploadedKittyImages.set(h.imageId,d),u?.transmissionGeneration===h.transmissionGeneration?h.replacementLine:l}),i=0,s=0,n=0;for(let[l,h]of this.uploadedKittyImages)t.has(l)||(i+=1,s+=h.transmissionBytes,n+=h.estimatedDecodedBytes);let o="";for(let[l,h]of this.uploadedKittyImages){if(i<=Gg&&s<=Yg&&n<=Xg)break;t.has(l)||(o+=Gi(l),this.uploadedKittyImages.delete(l),i-=1,s-=h.transmissionBytes,n-=h.estimatedDecodedBytes)}return{lines:r,evictedImageDeletion:o}}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 t=this.getPrimaryScrollView(),r=ge(this.currentLayout,t)?.scrollContentLines;if(r){for(let i=t.scrollTop+e;i>=0&&i<r.length;i+=e)if(jg.test(r[i]??"")){t.scrollTo(i),this.requestRender();return}}}toggleSearch(){if(this.activeSearch){this.closeSearch();return}let e=new Mg(r=>this.updateSearchQuery(r),this.searchNavigationButtonStyle),t={component:e,index:new Ag,query:"",matches:[],selectedIndex:-1,anchorRow:this.getPrimaryScrollView().scrollTop,selectionMode:"query"};this.activeSearch=t,t.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 t=this.activeSearch;if(!t||e===t.query)return;let r=t.matches[t.selectedIndex];t.anchorRow=r?.segments[0]?.row??this.getPrimaryScrollView().scrollTop,t.query=e,t.selectionMode="query",t.component.setResult(-1,0),this.requestRender()}navigateSearch(e){let t=this.activeSearch;t?.query&&(t.selectionMode=e<0?"previous":"next",this.requestRender())}getSearchNavigationDirectionAt(e,t){let r=this.activeSearch,i=r?.overlay?.getBounds();if(!(!r||!i)&&!(e<i.col||e>=i.col+i.width||t<i.row||t>=i.row+i.height))return r.component.getNavigationDirectionAt(t-i.row,e-i.col)}handleSearchMouseEvent(e){let t=this.activeSearch;if(!t)return!1;let r=this.getSearchNavigationDirectionAt(e.x,e.y);return t.component.setHoveredNavigationDirection(r)&&this.requestRender(),r===void 0||e.release||(e.button&32)!==0||(e.button&3)!==0?!1:(this.navigateSearch(r),!0)}refreshSearch(e){let t=this.activeSearch;if(!t)return!1;let r=e.primaryScrollView??this.implicitScrollView,i=ge(e,r),s=i?.scrollContentLines;if(!s||!t.query.trim())return t.matches=[],t.selectedIndex=-1,t.selectedKey=void 0,t.selectionMode="retain",t.component.setResult(-1,0),!1;let n=t.selectionMode!=="retain",o=t.index.search(s,t.query),l=o.matches;if(t.matches=l,!o.changed&&t.selectionMode==="retain")return!1;let h=o.changed?t.selectedKey?l.findIndex(m=>ia(m)===t.selectedKey):-1:t.selectedIndex,u=-1;if(l.length>0)if(t.selectionMode==="query"){let m=0,b=l.length;for(;m<b;){let C=m+Math.floor((b-m)/2);(l[C].segments[0]?.row??0)<t.anchorRow?m=C+1:b=C}u=m<l.length?m:0}else if(t.selectionMode==="next"){let m=h>=0?h:Math.min(t.selectedIndex,l.length-1);u=m<0?0:(m+1)%l.length}else if(t.selectionMode==="previous"){let m=h>=0?h:Math.min(t.selectedIndex,l.length-1);u=m<0?l.length-1:(m-1+l.length)%l.length}else u=h>=0?h:Math.min(Math.max(0,t.selectedIndex),l.length-1);if(t.selectedIndex=u,t.selectedKey=u>=0?ia(l[u]):void 0,t.selectionMode="retain",t.component.setResult(u,l.length),!n)return!1;let d=l[u],c=d?.segments[0],p=d?.segments[d.segments.length-1];if(!i||!c||!p||r.viewportHeight<=0)return!1;let f=r.scrollTop,g=f+r.viewportHeight-1,x=f;return(c.row<f||p.row>g)&&(x=c.row-Math.floor(r.viewportHeight/3)),r.scrollTo(x,{disableFollow:!0}),r.scrollTop!==f}flash(e,t){this.flashes.flash(e,t)}shouldDeferViewportInputToOverlay(){return this.isOverlayFocused()&&this.activeSearch?.overlay?.isFocused()!==!0}clearComponentMouseGesture(){this.mouseCapture=void 0,this.mousePressTarget=void 0,this.mousePressPoint=void 0,this.mousePressMoved=!1}handleViewportInput(e){if(e===Ug){let n=this.selectionPressActive,o=n&&this.getSelectionBounds()!==void 0;return this.selectionPressActive=!1,this.stopSelectionAutoScroll(),this.stopScrollbarHover(),this.activeSearch?.component.setHoveredNavigationDirection(void 0)&&this.requestRender(),this.stopScrollbarDrag(),this.pressedUrl=void 0,this.selectionDragged=!1,this.clearComponentMouseGesture(),this.lastComponentClick=void 0,n&&(this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,o&&this.requestRender()),this.lastClick=void 0,{consume:!0}}if(e===Kg)return{consume:!0};let t=this.parseWheelEvent(e);if(t){let n=this.wheelScroll.next(t.direction,performance.now()),o=t.direction*((t.button&8)!==0?n*zg:n),l=this.createMouseEvent("wheel",t.button,t.x,t.y,{wheelDelta:o}),h=this.dispatchMouseToOverlay(l),u=h.result??(h.hit?void 0:this.dispatchMouseToLayout(l));return u?(this.applyMouseDispatchResult(l,u)&&this.requestRender(),{consume:!0}):this.shouldDeferViewportInputToOverlay()?void 0:(this.routeWheel(t,o),{consume:!0})}let r=this.parseSgrMouseEvent(e);if(r)return this.handleMouseEvent(r),{consume:!0};if(this.isMouseSequence(e))return{consume:!0};let i=ue(),s=Ei(e);if(i.matches(e,"tui.altScreen.search"))return s||this.toggleSearch(),{consume:!0};if(this.activeSearch?.overlay?.isFocused()){if(i.matches(e,"tui.altScreen.searchNext"))return s||this.navigateSearch(1),{consume:!0};if(i.matches(e,"tui.altScreen.searchPrevious"))return s||this.navigateSearch(-1),{consume:!0};if(i.matches(e,"tui.altScreen.searchClose"))return s||this.closeSearch(),{consume:!0}}if(!this.shouldDeferViewportInputToOverlay()){if(i.matches(e,"tui.altScreen.pageUp"))return s||this.scrollBy(-Math.max(1,this.getPrimaryScrollView().viewportHeight-ma)),{consume:!0};if(i.matches(e,"tui.altScreen.pageDown"))return s||this.scrollBy(Math.max(1,this.getPrimaryScrollView().viewportHeight-ma)),{consume:!0};if(i.matches(e,"tui.altScreen.halfPageUp"))return s||this.scrollBy(-Math.max(1,Math.floor(this.getPrimaryScrollView().viewportHeight/2))),{consume:!0};if(i.matches(e,"tui.altScreen.halfPageDown"))return s||this.scrollBy(Math.max(1,Math.floor(this.getPrimaryScrollView().viewportHeight/2))),{consume:!0};if(i.matches(e,"tui.altScreen.lineUp"))return s||this.scrollBy(-1),{consume:!0};if(i.matches(e,"tui.altScreen.lineDown"))return s||this.scrollBy(1),{consume:!0};if(i.matches(e,"tui.altScreen.previousPrompt"))return s||this.scrollToPrompt(-1),{consume:!0};if(i.matches(e,"tui.altScreen.nextPrompt"))return s||this.scrollToPrompt(1),{consume:!0};if(i.matches(e,"tui.altScreen.top"))return s||this.scrollToTop(),{consume:!0};if(i.matches(e,"tui.altScreen.bottom"))return s||this.scrollToBottom(),{consume:!0}}}decodeMouseButton(e){switch(e&3){case 0:return"left";case 1:return"middle";case 2:return"right";default:return"none"}}createMouseEvent(e,t,r,i,s={}){return{type:e,button:e==="wheel"?"none":this.decodeMouseButton(t),x:r,y:i,screenX:r,screenY:i,width:Math.max(1,this.terminal.columns),height:Math.max(1,this.terminal.rows),shift:(t&4)!==0,alt:(t&8)!==0,ctrl:(t&16)!==0,...s.wheelDelta===void 0?{}:{wheelDelta:s.wheelDelta},...s.clickCount===void 0?{}:{clickCount:s.clickCount}}}dispatchMouseToLayout(e){if(!this.currentLayout)return;let t=new Set,r=Dg(this.currentLayout,e.screenX,e.screenY);for(let i of r){if(t.has(i.component)||qr(i.component)&&i.component.handleMouse===Ne.prototype.handleMouse)continue;t.add(i.component);let s=wt(i.component,{...e,x:e.screenX-i.rect.x,y:e.screenY-i.rect.y,width:i.rect.width,height:i.rect.height});if(s)return s}}applyMouseDispatchResult(e,t){let r=this.resolveMouseFocusTarget(t.focusTarget??t.target.component),i=t.focus===!0&&this.getFocusedComponent()!==r;return t.focus&&this.setFocus(r),t.capture&&(this.mouseCapture=t.target),t.render??(i||e.type==="press"||e.type==="click"||e.type==="drag"||e.type==="wheel")}dispatchMouseToTarget(e,t){return wt(t.component,Hp(e,t))}getComponentClickCount(e,t,r){let i=Date.now(),s=this.lastComponentClick,n=s&&i-s.timestamp<=xa&&s.component===e.component&&s.x===t&&s.y===r?s.count%3+1:1;return this.lastComponentClick={timestamp:i,count:n,component:e.component,x:t,y:r},n}clearTextSelection(){this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,this.pressedUrl=void 0,this.selectionDragged=!1}handleMouseEvent(e){let t=(e.button&32)!==0,r=e.release?"release":t?this.decodeMouseButton(e.button)==="none"?"move":"drag":"press",i=this.createMouseEvent(r,e.button,e.x,e.y);if(this.mouseCapture||this.mousePressTarget){let o=this.mouseCapture??this.mousePressTarget;this.mousePressPoint&&(e.x!==this.mousePressPoint.x||e.y!==this.mousePressPoint.y)&&(this.mousePressMoved=!0,this.lastComponentClick=void 0);let l=!1,h=this.dispatchMouseToTarget(i,o);if(h&&(l=this.applyMouseDispatchResult(i,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(o,e.x,e.y)}),d=this.dispatchMouseToTarget(u,o);d&&(l=this.applyMouseDispatchResult(u,d)||l)}this.clearComponentMouseGesture()}l&&this.requestRender();return}if(this.handleSearchMouseEvent(e))return;let s=this.dispatchMouseToOverlay(i);if(s.hit)this.stopScrollbarHover();else{if(this.handleScrollToEndIndicatorMouseEvent(e))return;let o=this.handleScrollbarMouseEvent(e);if(this.scrollbarDrag||this.updateScrollbarHover(e.x,e.y),o)return}let n=s.result??(s.hit?void 0:this.dispatchMouseToLayout(i));if(n){let o=this.applyMouseDispatchResult(i,n);r==="press"&&(this.clearTextSelection(),this.mousePressTarget=n.target,this.mousePressPoint={x:e.x,y:e.y},this.mousePressMoved=!1),o&&this.requestRender();return}this.handleRightClickPaste(e)||this.handleSelectionMouseEvent(e)}parseWheelEvent(e){let t=/^\x1b\[<(\d+);(\d+);(\d+)[Mm]$/.exec(e);if(t){let r=Number.parseInt(t[1],10);if((r&64)===0)return;let i=r&3;return i!==0&&i!==1?void 0:{direction:i===0?-1:1,x:Number.parseInt(t[2],10)-1,y:Number.parseInt(t[3],10)-1,button:r}}if(e.length===6&&e.startsWith("\x1B[M")){let r=e.charCodeAt(3)-32;if((r&64)===0)return;let i=r&3;return i!==0&&i!==1?void 0:{direction:i===0?-1:1,x:e.charCodeAt(4)-33,y:e.charCodeAt(5)-33,button:r}}}routeWheel(e,t){let r=t,i=new Set;for(let n of this.currentLayout?ys(this.currentLayout,e.x,e.y):[])if(i.add(n),r=n.scrollBy(r),r===0||n.overscroll==="contain")break;let s=this.getPrimaryScrollView();r!==0&&!i.has(s)&&s.scrollBy(r),this.updateScrollbarHover(e.x,e.y),this.requestRender()}parseSgrMouseEvent(e){let t=/^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/.exec(e);if(t)return{button:Number.parseInt(t[1],10),x:Number.parseInt(t[2],10)-1,y:Number.parseInt(t[3],10)-1,release:t[4]==="m"}}handleRightClickPaste(e){if(!this.onRightClickPaste||process.platform!=="win32"||process.env.TERM_PROGRAM?.toLowerCase()==="vscode"||e.release||e.button!==2)return!1;try{this.onRightClickPaste()}catch{}return!0}handleScrollToEndIndicatorMouseEvent(e){let t=this.scrollToEndIndicatorRect;return!t||e.release||(e.button&32)!==0||(e.button&3)!==0||e.y!==t.row||e.x<t.column||e.x>=t.column+t.width?!1:(this.scrollToBottom(),!0)}getScrollbarTargetAt(e,t,r=!1){if(!(this.hasOverlay()||!this.currentLayout))for(let i of ys(this.currentLayout,e,t)){let s=ge(this.currentLayout,i),n=s?sr(s,r):void 0;if(n&&e===n.column&&t>=n.trackTop&&t<n.trackTop+n.trackHeight)return{scrollView:i,geometry:n}}}setScrollbarHover(e){e!==this.scrollbarHover&&(this.scrollbarHover?.setScrollbarActive(!1),this.scrollbarHover=e,this.scrollbarHover?.setScrollbarActive(!0))}updateScrollbarHover(e,t){this.setScrollbarHover(this.getScrollbarTargetAt(e,t,!0)?.scrollView)}stopScrollbarHover(){this.setScrollbarHover(void 0)}scrollScrollbarToPointer(e,t,r,i){let s=t.trackHeight-t.thumbHeight,n=Math.max(0,Math.min(s,r-t.trackTop-i)),o=s===0?0:Math.round(n/s*t.maxScrollTop);e.scrollTo(o)}handleScrollbarMouseEvent(e){if(this.scrollbarDrag){if(e.release)return this.stopScrollbarDrag(),!0;let s=this.currentLayout?ge(this.currentLayout,this.scrollbarDrag.scrollView):void 0,n=s?sr(s):void 0;return n&&this.scrollScrollbarToPointer(this.scrollbarDrag.scrollView,n,e.y,this.scrollbarDrag.grabOffset),!0}if(e.release||(e.button&32)!==0||(e.button&3)!==0)return!1;let t=this.getScrollbarTargetAt(e.x,e.y);if(!t)return!1;this.stopSelectionAutoScroll(),this.selectionPressActive=!1,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=!1,this.setScrollbarHover(t.scrollView);let r=e.y>=t.geometry.thumbTop&&e.y<t.geometry.thumbTop+t.geometry.thumbHeight,i=r?e.y-t.geometry.thumbTop:Math.floor(t.geometry.thumbHeight/2);return r||this.scrollScrollbarToPointer(t.scrollView,t.geometry,e.y,i),this.scrollbarDrag={scrollView:t.scrollView,grabOffset:i},!0}stopScrollbarDrag(){this.scrollbarDrag=void 0}getScrollSelectionPoint(e,t,r){if(!this.currentLayout)return;let i=ge(this.currentLayout,e);if(!i||i.rect.height<=0||i.clip.height<=0)return;let s=Math.max(0,i.rect.y,i.clip.y),n=Math.min(this.terminal.rows-1,i.rect.y+i.rect.height-1,i.clip.y+i.clip.height-1);if(n<s)return;let o=Math.max(s,Math.min(n,r)),l=Math.max(0,(i.scrollContentLines?.length??1)-1);return{row:Math.max(0,Math.min(l,e.scrollTop+o-i.rect.y)),col:Math.max(0,Math.min(i.rect.width-1,t-i.rect.x)),scrollView:e}}getSelectionPoint(e,t){if(t){let r=this.getScrollSelectionPoint(t,e.x,e.y);if(r)return r}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 t=ge(this.currentLayout,e.scrollView)?.scrollContentLines;if(t)return t[e.row]??""}return this.previousScreen[e.row]??""}getWordSelection(e){let t=fr(this.getSelectionSourceLine(e)),r=[],i=0;for(let h of Jg.segment(t)){let u=i+T(h.segment),d=Zg.has(h.segment);r.push({start:i,end:u,selectable:h.isWordLike===!0||d,joiner:d}),i=u}let s=r.findIndex(h=>e.col>=h.start&&e.col<h.end);if(s<0)return;let n=a((h,u)=>h.selectable&&u.selectable&&(h.joiner||u.joiner),"canJoin"),o=r[s].start,l=r[s].end;for(let h=s;h>0&&n(r[h-1],r[h]);h--)o=r[h-1].start;for(let h=s;h<r.length-1&&n(r[h],r[h+1]);h++)l=r[h+1].end;return{start:{...e,col:o},end:{...e,col:l,boundary:!0}}}getLineSelection(e){return{start:{...e,col:0},end:{...e,col:T(this.getSelectionSourceLine(e)),boundary:!0}}}updateSelectionFocus(e){if(this.selectionGranularity==="character"||!this.selectionInitialRange){this.selectionFocus=e;return}let t=this.selectionGranularity==="word"?this.getWordSelection(e):this.getLineSelection(e);if(!t)return;let r=this.selectionInitialRange;t.start.row<r.start.row||t.start.row===r.start.row&&t.start.col<r.start.col?(this.selectionAnchor=r.end,this.selectionFocus=t.start):(this.selectionAnchor=r.start,this.selectionFocus=t.end)}getClickCount(e,t){let r=Date.now(),i=this.lastClick,s=t&&i&&r-i.timestamp<=xa&&i.row===e.row&&i.scrollView===e.scrollView&&i.wordStart===t.start.col&&i.wordEnd===t.end.col?i.count%3+1:1;return this.lastClick=t?{timestamp:r,count:s,row:e.row,scrollView:e.scrollView,wordStart:t.start.col,wordEnd:t.end.col}:void 0,s}updateSelectionAutoScroll(e){let t=this.selectionAnchor?.scrollView;if(!t||!this.currentLayout){this.stopSelectionAutoScroll();return}let r=ge(this.currentLayout,t);if(!r||r.rect.height<=0||r.clip.height<=0){this.stopSelectionAutoScroll();return}let i=Math.max(0,r.rect.y,r.clip.y),s=Math.min(this.terminal.rows-1,r.rect.y+r.rect.height-1,r.clip.y+r.clip.height-1);if(this.selectionDragPointer={x:e.x,y:e.y},this.selectionAutoScrollDirection=e.y<=i?-1:e.y>=s?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,t=this.selectionDragPointer,r=this.selectionAutoScrollDirection;if(!e||!t||r===0){this.stopSelectionAutoScroll();return}if(e.scrollBy(r)===r){this.stopSelectionAutoScroll();return}let i=this.getScrollSelectionPoint(e,t.x,t.y);i&&this.updateSelectionFocus(i),this.requestRender()}stopSelectionAutoScroll(){this.selectionAutoScrollTimer&&(clearInterval(this.selectionAutoScrollTimer),this.selectionAutoScrollTimer=void 0),this.selectionAutoScrollDirection=0,this.selectionDragPointer=void 0}handleSelectionMouseEvent(e){let t=e.button&3;if(t!==0&&!(e.release&&t===3))return;let r=this.selectionAnchor?.scrollView,i=this.getSelectionPoint(e,r);if(e.release){if(!this.selectionPressActive||(this.selectionPressActive=!1,this.stopSelectionAutoScroll(),!this.selectionAnchor))return;this.updateSelectionFocus(i);let u=!this.selectionDragged&&this.selectionAnchor.scrollView===i.scrollView&&this.selectionAnchor.row===i.row&&this.selectionAnchor.col===i.col,d=u?this.pressedUrl:void 0;if(this.pressedUrl=void 0,d&&this.openUrl){this.selectionAnchor=void 0,this.selectionFocus=void 0;try{this.openUrl(d)}catch{}this.requestRender();return}if(u){let c=this.createMouseEvent("click",e.button,e.x,e.y,{clickCount:this.lastClick?.count??1}),p=this.dispatchMouseToOverlay(c),f=p.result??(p.hit?void 0:this.dispatchMouseToLayout(c));if(f){let g=this.applyMouseDispatchResult(c,f);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=!0,this.lastClick=void 0,this.pressedUrl=void 0,this.updateSelectionFocus(i),this.updateSelectionAutoScroll(e),this.requestRender();return}this.stopSelectionAutoScroll(),this.selectionPressActive=!0;let s=!this.hasOverlay()&&this.currentLayout?ys(this.currentLayout,e.x,e.y)[0]:void 0,n=this.getSelectionPoint(e,s),o=this.getWordSelection(n),l=this.getClickCount(n,o),h=l===2?o:l===3?this.getLineSelection(n):void 0;this.selectionGranularity=h?l===2?"word":"line":"character",this.selectionInitialRange=h,this.selectionAnchor=h?.start??n,this.selectionFocus=h?.end??n,this.selectionDragged=!1,this.pressedUrl=h?void 0:Fn(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,t,r,i=0,s=T(e)){let n=T(e),o=Math.max(0,i),l=Math.min(n,s);return t===r.start.row&&(o=wi(e,r.start.col)?.start??Math.min(r.start.col,n)),t===r.end.row&&(l=r.end.boundary?Math.min(r.end.col,n):wi(e,r.end.col)?.end??Math.min(r.end.col+1,n)),{start:Math.max(i,o),end:Math.min(s,l)}}getActiveSelectionText(){let e=this.getSelectionBounds();if(!e)return;let t=this.previousScreen;if(e.start.scrollView){if(!this.currentLayout)return;let s=ge(this.currentLayout,e.start.scrollView);if(!s?.scrollContentLines)return;t=s.scrollContentLines}let r=[];for(let s=e.start.row;s<=e.end.row;s++){let n=t[s]??"",o=this.getSelectionColumns(n,s,e);r.push(fr(Y(n,o.start,Math.max(0,o.end-o.start),!0)).trimEnd())}let i=r.join(`
|
|
113
|
-
`);return i.length===0?void 0:i}async copySelectionToClipboard(){let e=this.getActiveSelectionText();return e?this.copyTextToClipboard(e):!1}async copyTextToClipboard(e){if(this.copySelection){let t=await this.copySelection(e),r=t===!0;return this.flash(r?"Copied!":typeof t=="string"?t:"Copy failed",r?void 0:Qg),r}return this.terminal.write(`\x1B]52;c;${Buffer.from(e).toString("base64")}\x07`),this.flash("Copied!"),!0}applySearchTextHighlight(e,t){let r=t?this.searchCurrentMatchStyle:this.searchMatchStyle,i="",s=0,n=0;for(;n<e.length;){let o=j(e,n);if(!o){n+=1;continue}n>s&&(i+=r(e.slice(s,n))),i+=o.code,n+=o.length,s=n}return s<e.length&&(i+=r(e.slice(s))),i}applySearchHighlights(e,t){let r=this.activeSearch;if(!r||r.selectedIndex<0||r.matches.length===0)return e;let i=t.primaryScrollView??this.implicitScrollView,s=ge(t,i);if(!s)return e;let n=new Map,o=sr(s)?.column,l=Math.max(0,s.rect.y,s.clip.y),h=Math.min(e.length,s.rect.y+s.rect.height,s.clip.y+s.clip.height),u=Math.max(0,s.rect.x,s.clip.x),d=Math.min(this.terminal.columns,s.rect.x+s.rect.width,s.clip.x+s.clip.width,o??Number.POSITIVE_INFINITY),c=i.scrollTop+l-s.rect.y,p=i.scrollTop+h-s.rect.y-1,f=0,g=r.matches.length;for(;f<g;){let m=f+Math.floor((g-f)/2),b=r.matches[m];(b.segments[b.segments.length-1]?.row??-1)<c?f=m+1:g=m}for(let m=f;m<r.matches.length;m++){let b=r.matches[m];if((b.segments[0]?.row??0)>p)break;for(let C of b.segments){let S=s.rect.y+C.row-i.scrollTop;if(S<l||S>=h)continue;let y=Math.max(u,s.rect.x+C.startCol),k=Math.min(d,s.rect.x+C.endCol);if(k<=y)continue;let v=n.get(S)??[];v.push({startCol:y,endCol:k,current:m===r.selectedIndex}),n.set(S,v)}}let x=[...e];for(let[m,b]of n){let C=x[m]??"";if(z(C))continue;let S=T(C);for(let y of b.sort((k,v)=>v.startCol-k.startCol)){let k=Math.min(y.startCol,S),v=Math.min(y.endCol,S);if(v<=k)continue;let B=Y(C,0,k,!0),M=Y(C,k,v-k,!0),w=Y(C,v,Math.max(0,S-v),!0);C=`${B}${this.applySearchTextHighlight(M,y.current)}${w}`}x[m]=C}return x}applySelectionHighlight(e){let t="\x1B[7m",r=0;for(;r<e.length;){let i=j(e,r);if(!i){t+=e[r],r+=1;continue}t+=i.code,i.code.endsWith("m")&&(t+="\x1B[7m"),r+=i.length}return`${t}\x1B[27m`}applySelection(e,t=this.currentLayout){let r=this.getSelectionBounds();if(!r)return e;let i=r,s=0,n=e.length-1,o=0,l=this.terminal.columns;if(r.start.scrollView){if(!t)return e;let h=ge(t,r.start.scrollView);if(!h)return e;s=Math.max(0,h.rect.y,h.clip.y),n=Math.min(e.length-1,h.rect.y+h.rect.height-1,h.clip.y+h.clip.height-1),o=Math.max(0,h.rect.x,h.clip.x),l=Math.min(this.terminal.columns,h.rect.x+h.rect.width,h.clip.x+h.clip.width),i={start:{...r.start,row:h.rect.y+r.start.row-r.start.scrollView.scrollTop,col:h.rect.x+r.start.col},end:{...r.end,row:h.rect.y+r.end.row-r.start.scrollView.scrollTop,col:h.rect.x+r.end.col}}}return e.map((h,u)=>{if(u<s||u>n||u<i.start.row||u>i.end.row||z(h))return h;let d=T(h),c=this.getSelectionColumns(h,u,i,o,l);if(c.end<=c.start)return h;let p=Y(h,0,c.start,!0),f=Y(h,c.start,c.end-c.start,!0),g=Y(h,c.end,Math.max(0,d-c.end),!0);return`${p}${this.applySelectionHighlight(f)}${g}`})}isMouseSequence(e){return/^\x1b\[<\d+;\d+;\d+[Mm]$/.test(e)||e.length===6&&e.startsWith("\x1B[M")}compositeScrollToEndIndicator(e,t,r){this.scrollToEndIndicatorRect=void 0;let i=t.primaryScrollView??this.implicitScrollView;if(!this.scrollToEndIndicator||!i.followEnd||i.isFollowingEnd)return e;let s=ge(t,i),n=s?.clip;if(!n||n.width<=0||n.height<=0)return e;let o=n.y+n.height-1;if(o>=e.length||z(e[o]??""))return e;let l=s?sr(s)?.column:void 0,h=K(this.scrollToEndIndicator(),n.width,""),u=T(h),d=n.x+Math.floor((n.width-u)/2),c=l??n.x+n.width,p=Math.max(0,c-d),f=K(h,p,""),g=T(f);if(g===0)return e;let x=[...e];return x[o]=Xe(x[o]??"",f,d,g,r),this.scrollToEndIndicatorRect={row:o,column:d,width:g},x}compositeFlashes(e,t,r){let i=this.flashes.render(t).slice(-r);if(i.length===0)return e;let s=[...e];for(;s.length<r;)s.push("");for(let n=0;n<i.length;n++){let o=i[n],l=T(o);l!==0&&(s[n]=Xe(s[n]??"",o,t-l,l,t))}return s}doRender(){if(this.stopped||!this.altScreenActive)return;let e=Math.max(1,this.terminal.columns),t=Math.max(1,this.terminal.rows),r=this.layoutRoot??this.implicitScrollView,i=ca(r,e,t,()=>this.requestRender());this.refreshSearch(i)&&(i=ca(r,e,t,()=>this.requestRender()));let s=this.resolveFakeCursors(i.lines.map(m=>m.replace(ga,"")));s=this.applySearchHighlights(s,i),s=this.compositeScrollToEndIndicator(s,i,e),s=this.compositeOverlays(s,e,t),s.length>t&&(s=s.slice(s.length-t)),s=this.applySelection(s,i),s=this.compositeFlashes(s,e,t);let n=this.extractCursorPosition(s,t);s=this.applyLineResets(s).map(m=>z(m)||T(m)<=e?m:Y(m,0,e,!0));let o=this.previousScreen.length===0||this.previousScreenWidth!==e||this.previousScreenHeight!==t,l=s.map((m,b)=>m!==this.previousScreen[b]),h=s.some((m,b)=>l[b]&&(z(m)||z(this.previousScreen[b]??""))),u=!!process.env.WEZTERM_PANE||process.env.TERM_PROGRAM?.toLowerCase()==="wezterm",d=!h&&u&&this.imageProtocol==="kitty"&&l.some(Boolean)&&s.some((m,b)=>{let C=Dp(m);if(C===void 0)return!1;for(let S=b;S<b+C;S++)if(l[S])return!0;return!1}),c=h||d,p=o||c,f=this.uploadedKittyImages.size>0,g=p&&this.imageProtocol==="kitty"?this.prepareKittyScreen(s):{lines:s,evictedImageDeletion:""},x=Jr;if(o){this.fullRedrawCount+=1;let m=this.imageProtocol==="kitty"&&f?Xo():this.deleteKittyImages();x+=`${m}\x1B[2J`}else c&&(this.imageProtocol==="iterm2"?x+="\x1B[2J":this.imageProtocol==="kitty"&&(x+=Xo()));if(x+=g.evictedImageDeletion,p&&this.imageProtocol==="kitty"&&s.some(z)&&u){for(let m=0;m<t;m++)!o&&!c&&s[m]===this.previousScreen[m]||(x+=`\x1B[${m+1};1H\x1B[2K`);for(let m=0;m<t;m++)!o&&!c&&s[m]===this.previousScreen[m]||z(g.lines[m]??"")||(x+=`\x1B[${m+1};1H${g.lines[m]??""}`);for(let m=0;m<t;m++)!o&&!c&&s[m]===this.previousScreen[m]||z(g.lines[m]??"")&&(x+=`\x1B[${m+1};1H${g.lines[m]??""}`)}else for(let m=0;m<t;m++)!o&&!c&&s[m]===this.previousScreen[m]||(x+=`\x1B[${m+1};1H\x1B[2K${g.lines[m]??""}`);n?(x+=`\x1B[${n.row+1};${Math.min(e,n.col)+1}H`,x+=this.getShowHardwareCursor()?"\x1B[?25h":"\x1B[?25l"):x+="\x1B[?25l",x+=ei,this.terminal.write(x),this.previousScreen=s,this.previousScreenWidth=e,this.previousScreenHeight=t,this.currentLayout=i}};import*as At from"node:fs";import*as ya from"node:os";import*as Mt from"node:path";var wa="\x1B_G",ka=1024*1024,ws=class{static{a(this,"BoundedTerminalWriter")}buffer="";writtenChars=0;write;constructor(e){this.write=e}append(e){let t=0;for(;t<e.length;){let r=ka-this.buffer.length;if(r===0){this.flush();continue}let i=Math.min(e.length,t+r);if(i<e.length&&e.charCodeAt(i-1)>=55296&&e.charCodeAt(i-1)<=56319&&e.charCodeAt(i)>=56320&&e.charCodeAt(i)<=57343&&i--,i===t){this.flush();continue}this.buffer+=e.slice(t,i),t=i,this.buffer.length===ka&&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 va(e){let t=e.indexOf(wa);if(t===-1)return;let r=t+wa.length,i=e.indexOf(";",r);if(i===-1)return;let s=[],n=1;for(let o of e.slice(r,i).split(",")){let[l,h]=o.split("=",2);if(h===void 0)continue;let u=Number(h);!Number.isInteger(u)||u<=0||u>4294967295||(l==="i"?s.push(u):l==="r"&&(n=u))}return{ids:s,rows:n}}a(va,"parseKittyImageHeader");function ks(e){return va(e)?.ids??[]}a(ks,"extractKittyImageIds");function em(e){return va(e)?.rows??1}a(em,"extractKittyImageRows");function tm(){return!!process.env.TERMUX_VERSION}a(tm,"isTermuxSession");var Sa=class extends cl{static{a(this,"TuiMainScreen")}mode="regular";previousLines=[];previousKittyImageIds=new Set;previousWidth=0;previousHeight=0;cursorRow=0;hardwareCursorRow=0;maxLinesRendered=0;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(t=>z(t)?"":t),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 t=this.previousLines.length-this.hardwareCursorRow;t>0?this.terminal.write(`\x1B[${t}B`):t<0&&this.terminal.write(`\x1B[${-t}A`),this.terminal.write(`\r
|
|
114
|
-
`)}collectKittyImageIds(e){let t=new Set;for(let r of e)for(let i of ks(r))t.add(i);return t}deleteKittyImages(e){let t="";for(let r of e)t+=Gi(r);return t}getKittyImageReservedRows(e,t,r=e.length-1){let i=em(e[t]??"");if(i<=1)return 1;let s=Math.min(i,r-t+1,e.length-t),n=1;for(;n<s;){let o=e[t+n]??"";if(z(o)||T(o)>0)break;n++}return n}expandChangedRangeForKittyImages(e,t,r){let i=e,s=t,n=a(o=>{for(let l=0;l<o.length;l++){if(ks(o[l]).length===0)continue;let h=l+this.getKittyImageReservedRows(o,l)-1;(l>=e||l<=t&&h>=e)&&(i=Math.min(i,l),s=Math.max(s,h))}},"expandForLines");return n(this.previousLines),n(r),{firstChanged:i,lastChanged:s}}deleteChangedKittyImages(e,t){if(e<0||t<e)return"";let r=new Set,i=Math.min(t,this.previousLines.length-1);for(let s=e;s<=i;s++)for(let n of ks(this.previousLines[s]??""))r.add(n);return this.deleteKittyImages(r)}doRender(){if(this.stopped)return;let e=this.terminal.columns,t=this.terminal.rows,r=this.previousWidth!==0&&this.previousWidth!==e,i=this.previousHeight!==0&&this.previousHeight!==t,s=this.previousHeight>0?this.previousViewportTop+this.previousHeight:t,n=i?Math.max(0,s-t):this.previousViewportTop,o=n,l=this.hardwareCursorRow,h=a(w=>{let A=l-n;return w-o-A},"computeLineDiff"),u=this.resolveFakeCursors(this.render(e));this.hasOverlayEntries&&(u=this.compositeOverlays(u,e,t));let d=this.extractCursorPosition(u,t);u=this.applyLineResets(u);let c=a(w=>{this.fullRedrawCount+=1;let A=new ws(I=>this.terminal.write(I));A.append("\x1B[?2026h"),w&&(A.append(this.deleteKittyImages(this.previousKittyImageIds)),A.append("\x1B[2J\x1B[H\x1B[3J"));for(let I=0;I<u.length;I++){I>0&&A.append(`\r
|
|
115
|
-
`);let V=u[I],O=z(V)?this.getKittyImageReservedRows(u,I):1;if(O>1&&O<=t){for(let G=1;G<O;G++)A.append(`\r
|
|
116
|
-
`);A.append(`\x1B[${O-1}A`),A.append(V),A.append(`\x1B[${O-1}B`),I+=O-1;continue}A.append(V)}A.append("\x1B[?2026l"),A.flush(),this.cursorRow=Math.max(0,u.length-1),this.hardwareCursorRow=this.cursorRow,w?this.maxLinesRendered=u.length:this.maxLinesRendered=Math.max(this.maxLinesRendered,u.length);let L=Math.max(t,u.length);this.previousViewportTop=Math.max(0,L-t),this.positionHardwareCursor(d,u.length),this.previousLines=u,this.previousKittyImageIds=this.collectKittyImageIds(u),this.previousWidth=e,this.previousHeight=t},"fullRender"),p=process.env.PI_TUI_DEBUG_REDRAW==="1"?this.logDirectory:void 0,f=a(w=>{if(p===void 0)return;let A=Mt.join(p,"pi-tui-debug.log"),L=`[${new Date().toISOString()}] fullRender: ${w} (prev=${this.previousLines.length}, new=${u.length}, height=${t})
|
|
117
|
-
`;At.mkdirSync(Mt.dirname(A),{recursive:!0}),At.appendFileSync(A,L)},"logRedraw");if(this.previousLines.length===0&&!r&&!i){f("first render"),c(!1);return}if(r){f(`terminal width changed (${this.previousWidth} -> ${e})`),c(!0);return}if(i&&!tm()){f(`terminal height changed (${this.previousHeight} -> ${t})`),c(!0);return}if(this.getClearOnShrink()&&u.length<this.maxLinesRendered&&!this.hasOverlayEntries){f(`clearOnShrink (maxLinesRendered=${this.maxLinesRendered})`),c(!0);return}let g=-1,x=-1,m=Math.max(u.length,this.previousLines.length);for(let w=0;w<m;w++){let A=w<this.previousLines.length?this.previousLines[w]:"",L=w<u.length?u[w]:"";A!==L&&(g===-1&&(g=w),x=w)}let b=u.length>this.previousLines.length;if(b&&(g===-1&&(g=this.previousLines.length),x=u.length-1),g!==-1){let w=this.expandChangedRangeForKittyImages(g,x,u);g=w.firstChanged,x=w.lastChanged}let C=b&&g===this.previousLines.length&&g>0;if(g===-1){this.positionHardwareCursor(d,u.length),this.previousViewportTop=n,this.previousHeight=t;return}if(g>=u.length){if(this.previousLines.length>u.length){let w=new ws(G=>this.terminal.write(G));w.append("\x1B[?2026h"),w.append(this.deleteChangedKittyImages(g,x));let A=Math.max(0,u.length-1);if(A<n){f(`deleted lines moved viewport up (${A} < ${n})`),c(!0);return}let L=h(A);L>0?w.append(`\x1B[${L}B`):L<0&&w.append(`\x1B[${-L}A`),w.append("\r");let I=this.previousLines.length-u.length;if(I>t){f(`extraLines > height (${I} > ${t})`),c(!0);return}let V=u.length===0?0:1;I>0&&V>0&&w.append(`\x1B[${V}B`);for(let G=0;G<I;G++)w.append("\r\x1B[2K"),G<I-1&&w.append("\x1B[1B");let O=Math.max(0,I-1+V);O>0&&w.append(`\x1B[${O}A`),w.append("\x1B[?2026l"),w.flush(),this.cursorRow=A,this.hardwareCursorRow=A}this.positionHardwareCursor(d,u.length),this.previousLines=u,this.previousKittyImageIds=this.collectKittyImageIds(u),this.previousWidth=e,this.previousHeight=t,this.previousViewportTop=n;return}if(g<n){f(`firstChanged < viewportTop (${g} < ${n})`),c(!0);return}let S=new ws(w=>this.terminal.write(w));S.append("\x1B[?2026h"),S.append(this.deleteChangedKittyImages(g,x));let y=n+t-1,k=C?g-1:g;if(k>y){let w=Math.max(0,Math.min(t-1,l-n)),A=t-1-w;A>0&&S.append(`\x1B[${A}B`);let L=k-y;S.append(`\r
|
|
118
|
-
`.repeat(L)),n+=L,o+=L,l=k}let v=h(k);v>0?S.append(`\x1B[${v}B`):v<0&&S.append(`\x1B[${-v}A`),S.append(C?`\r
|
|
119
|
-
`:"\r");let B=Math.min(x,u.length-1);for(let w=g;w<=B;w++){w>g&&S.append(`\r
|
|
120
|
-
`);let A=u[w],L=z(A),I=L?this.getKittyImageReservedRows(u,w,B):1;if(I>1){let V=w-o;if(V<0||V+I>t){f(`kitty image pre-clear would scroll (${V} + ${I} > ${t})`),c(!0);return}S.append("\x1B[2K");for(let O=1;O<I;O++)S.append(`\r
|
|
121
|
-
\x1B[2K`);S.append(`\x1B[${I-1}A`),S.append(A),S.append(`\x1B[${I-1}B`),w+=I-1;continue}if(S.append("\x1B[2K"),!L&&T(A)>e){let V=Mt.join(this.logDirectory??ya.tmpdir(),"pi-tui-crash.log"),O=[`Crash at ${new Date().toISOString()}`,`Terminal width: ${e}`,`Line ${w} visible width: ${T(A)}`,"","=== All rendered lines ===",...u.map((he,ot)=>`[${ot}] (w=${T(he)}) ${he}`),""].join(`
|
|
122
|
-
`);At.mkdirSync(Mt.dirname(V),{recursive:!0}),At.writeFileSync(V,O),this.stop();let G=[`Rendered line ${w} exceeds terminal width (${T(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: ${V}`].join(`
|
|
123
|
-
`);throw new Error(G)}S.append(A)}let M=B;if(this.previousLines.length>u.length){if(B<u.length-1){let A=u.length-1-B;S.append(`\x1B[${A}B`),M=u.length-1}let w=this.previousLines.length-u.length;for(let A=u.length;A<this.previousLines.length;A++)S.append(`\r
|
|
124
|
-
\x1B[2K`);S.append(`\x1B[${w}A`)}if(S.append("\x1B[?2026l"),process.env.PI_TUI_DEBUG==="1"){let w=Mt.join(ya.tmpdir(),"tui");At.mkdirSync(w,{recursive:!0});let A=Mt.join(w,`render-${Date.now()}-${Math.random().toString(36).slice(2)}.log`),L=[`firstChanged: ${g}`,`viewportTop: ${o}`,`cursorRow: ${this.cursorRow}`,`height: ${t}`,`lineDiff: ${v}`,`hardwareCursorRow: ${l}`,`renderEnd: ${B}`,`finalCursorRow: ${M}`,`cursorPos: ${JSON.stringify(d)}`,`newLines.length: ${u.length}`,`previousLines.length: ${this.previousLines.length}`,"","=== newLines ===",JSON.stringify(u,null,2),"","=== previousLines ===",JSON.stringify(this.previousLines,null,2),"","=== buffer ===",`[${S.length} chars written in bounded chunks]`].join(`
|
|
125
|
-
`);At.writeFileSync(A,L)}S.flush(),this.cursorRow=Math.max(0,u.length-1),this.hardwareCursorRow=M,this.maxLinesRendered=Math.max(this.maxLinesRendered,u.length),this.previousViewportTop=Math.max(n,M-t+1),this.positionHardwareCursor(d,u.length),this.previousLines=u,this.previousKittyImageIds=this.collectKittyImageIds(u),this.previousWidth=e,this.previousHeight=t}positionHardwareCursor(e,t){if(!e||t<=0){this.terminal.hideCursor();return}let r=Math.max(0,Math.min(e.row,t-1)),i=Math.max(0,e.col),s=r-this.hardwareCursorRow,n="";s>0?n+=`\x1B[${s}B`:s<0&&(n+=`\x1B[${-s}A`),n+=`\x1B[${i+1}G`,n&&this.terminal.write(n),this.hardwareCursorRow=r,this.getShowHardwareCursor()?this.terminal.showCursor():this.terminal.hideCursor()}};import*as ye from"node:fs";import*as Bt from"node:path";import{watch as rm}from"node:fs";var im=5e3;function vs(e){if(e)try{e.close()}catch{}}a(vs,"closeWatcher");function Ca(e,t,r){try{let i=rm(e,t);return i.on("error",r),i}catch{return r(),null}}a(Ca,"watchWithErrorHandler");var ti=q(oh(),1),sm=q(sh(),1),nm=q(nh(),1),om=q(lh(),1),lm=q(ah(),1),am=q(hh(),1),hm=q(uh(),1),um=q(ch(),1),cm=q(dh(),1),dm=q(ph(),1),pm=q(fh(),1),fm=q(gh(),1),gm=q(mh(),1),mm=q(xh(),1),xm=q(bh(),1),bm=q(yh(),1),ym=q(wh(),1),wm=q(kh(),1),km=q(vh(),1),vm=q(Sh(),1),Sm=q(Ch(),1),Cm=q(Th(),1);function Ta(e){if(!(!Number.isInteger(e)||e<0||e>1114111))return String.fromCodePoint(e)}a(Ta,"decodeCodePoint");function Tm(e){switch(e){case"amp":return"&";case"lt":return"<";case"gt":return">";case"quot":return'"';case"apos":return"'"}if(e.startsWith("#x")||e.startsWith("#X"))return Ta(Number.parseInt(e.slice(2),16));if(e.startsWith("#"))return Ta(Number.parseInt(e.slice(1),10))}a(Tm,"decodeHtmlEntity");function Am(e,t){let r=e.indexOf(";",t+1);if(r===-1||r-t>16)return;let i=e.slice(t+1,r),s=Tm(i);if(s!==void 0)return{text:s,length:r-t+1}}a(Am,"decodeHtmlEntityAt");var Mm={python:ym.default,java:cm.default,go:hm.default,javascript:dm.default,json:pm.default,cpp:om.default,typescript:Cm.default,php:bm.default,ruby:wm.default,c:nm.default,csharp:lm.default,nix:mm.default,bash:sm.default,rust:km.default,scala:vm.default,kotlin:fm.default,swift:Sm.default,dart:am.default,groovy:um.default,perl:xm.default,lua:gm.default};for(let[e,t]of Object.entries(Mm))ti.default.registerLanguage(e,t);var Ss;function Bm(){return Ss||(Ss=new Promise(e=>{setImmediate(()=>{import("./lib-TEDK3E5I.js").then(()=>e(),()=>{e()})})})),Ss}a(Bm,"loadAllHighlightLanguages");var Aa="</span>",Ma="hljs-";function Rm(e){let t=/\sclass\s*=\s*(?:"([^"]*)"|'([^']*)')/.exec(e),r=t?.[1]??t?.[2];if(r){for(let i of r.split(/\s+/))if(i.startsWith(Ma))return i.slice(Ma.length)}}a(Rm,"getScopeFromSpanTag");function Em(e,t){let r=t[e];if(r)return r;let i=e.indexOf(".");if(i!==-1){let n=t[e.slice(0,i)];if(n)return n}let s=e.indexOf("-");if(s!==-1){let n=t[e.slice(0,s)];if(n)return n}}a(Em,"getScopeFormatter");function Im(e,t){for(let r=e.length-1;r>=0;r--){let i=e[r];if(!i)continue;let s=Em(i,t);if(s)return s}return t.default}a(Im,"getActiveFormatter");function Lm(e,t){if(!e.startsWith("<span",t))return!1;let r=e[t+5];return r===">"||r===" "||r===" "||r===`
|
|
126
|
-
`||r==="\r"}a(Lm,"isSpanOpenTagStart");function Pm(e,t={}){let r="",i="",s=[],n=a(()=>{if(!i)return;let l=Im(s,t);r+=l?i.split(`
|
|
127
|
-
`).map(h=>h&&l(h)).join(`
|
|
128
|
-
`):i,i=""},"flushText"),o=0;for(;o<e.length;){if(Lm(e,o)){let l=e.indexOf(">",o+5);if(l!==-1){n();let h=e.slice(o,l+1),u=Rm(h);s.push(u),o=l+1;continue}}if(e.startsWith(Aa,o)){n(),s.length>0&&s.pop(),o+=Aa.length;continue}if(e[o]==="&"){let l=Am(e,o);if(l){i+=l.text,o+=l.length;continue}}i+=e[o],o++}return n(),r}a(Pm,"renderHighlightedHtml");function Ba(e,t={}){let r=t.language?ti.default.highlight(e,{language:t.language,ignoreIllegals:t.ignoreIllegals}).value:ti.default.highlightAuto(e,t.languageSubset).value;return Pm(r,t.theme)}a(Ba,"highlight");function Ra(e){return ti.default.getLanguage(e)!==void 0}a(Ra,"supportsLanguage");var ee="system",Cs={neutral:{hue:231.49,saturation:{min:.02,max:.08},slot:8},blue:{hue:231.49,saturation:{min:.1,max:.68},slot:4},green:{hue:158.68,saturation:{min:.1,max:.76},slot:2},red:{hue:20,saturation:{min:.1,max:.92},slot:1},yellow:{hue:82.36,saturation:{min:.5,max:1},slot:3},orange:{hue:52,saturation:{min:.12,max:.85},slot:3},violet:{hue:295,saturation:{min:.2,max:.6},slot:5},calamine:{hue:202.43,saturation:{min:.1,max:.74},slot:6},thinkingSlate:{hue:231.49,saturation:{min:.08,max:.2},slot:4},thinkingBlue:{hue:231.49,saturation:{min:.2,max:.45},slot:4},thinkingPeriwinkle:{hue:263.25,saturation:{min:.3,max:.6},slot:6},thinkingViolet:{hue:295,saturation:{min:.4,max:.75},slot:5},thinkingMagenta:{hue:337.5,saturation:{min:.5,max:.85},slot:13},thinkingRed:{hue:20,saturation:{min:.95,max:1},slot:1}},Ts={selectedBg:"blue",searchMatchBg:"orange",userMessageBg:"blue",customMessageBg:"violet",toolPendingBg:"neutral",toolSuccessBg:"green",toolErrorBg:"red",text:"neutral",userMessageText:"neutral",customMessageText:"neutral",toolTitle:"neutral",syntaxOperator:"neutral",syntaxPunctuation:"neutral",muted:"neutral",dim:"neutral",thinkingText:"neutral",toolOutput:"neutral",mdLinkUrl:"neutral",mdQuote:"neutral",mdQuoteBorder:"neutral",mdHr:"neutral",mdCodeBlockBorder:"neutral",toolDiffContext:"neutral",syntaxComment:"neutral",scrollbarTrack:"neutral",scrollbarThumb:"neutral",searchMatchText:"neutral",borderMuted:"neutral",accent:"violet",borderAccent:"violet",customMessageLabel:"violet",mdCode:"violet",mdListBullet:"violet",syntaxType:"violet",border:"blue",mdLink:"blue",syntaxKeyword:"blue",syntaxVariable:"calamine",success:"green",mdCodeBlock:"green",toolDiffAdded:"green",bashMode:"green",syntaxNumber:"green",error:"red",toolDiffRemoved:"red",warning:"yellow",mdHeading:"yellow",syntaxFunction:"yellow",syntaxString:"orange",thinkingOff:"neutral",thinkingMinimal:"thinkingSlate",thinkingLow:"thinkingBlue",thinkingMedium:"thinkingPeriwinkle",thinkingHigh:"thinkingViolet",thinkingXhigh:"thinkingMagenta",thinkingMax:"thinkingRed"},Ea={syntaxString:2,syntaxNumber:5,searchMatchBg:3},$m={panel:{dark:{coefficients:[.29131,-.39746,2.33185,-.85524,-1.2076,.86276],reachable:[0,.979]},light:{coefficients:[-3.74073,27.94549,-78.44258,112.6798,-79.60015,22.11277],reachable:[.348,1]}},track:{dark:{coefficients:[.39028,-.23015,.83573,2.43829,-4.38292,2.01582],reachable:[0,.946]},light:{coefficients:[-5.24921,38.37322,-107.28833,152.10005,-106.17127,29.18061],reachable:[.368,1]}},thinking0:{dark:{coefficients:[.52988,-.05809,-.30924,4.63567,-6.52933,2.89108],reachable:[0,.873]},light:{coefficients:[-28.27749,182.85284,-469.62416,603.15916,-384.59976,97.35147],reachable:[.51,1]}},thinking1:{dark:{coefficients:[.55278,-.03667,-.45659,4.95347,-6.90265,3.0706],reachable:[0,.858]},light:{coefficients:[-37.10484,235.86282,-596.62344,754.3633,-474.00763,118.3551],reachable:[.535,1]}},thinking2:{dark:{coefficients:[.57486,-.01765,-.58987,5.25227,-7.27175,3.25532],reachable:[0,.842]},light:{coefficients:[-59.89653,377.05024,-945.07843,1182.03145,-734.96375,181.68658],reachable:[.556,1]}},thinking3:{dark:{coefficients:[.59621,-62e-5,-.71148,5.53588,-7.6392,3.44606],reachable:[0,.827]},light:{coefficients:[-72.07122,445.84082,-1099.57352,1353.88793,-829.53392,202.26164],reachable:[.58,1]}},thinking4:{dark:{coefficients:[.61691,.01462,-.82288,5.80651,-8.00641,3.64333],reachable:[0,.811]},light:{coefficients:[-110.14338,674.21488,-1645.75941,2004.32367,-1215.15899,293.3183],reachable:[.6,1]}},thinking5:{dark:{coefficients:[.63702,.02826,-.92498,6.06465,-8.37246,3.84651],reachable:[0,.795]},light:{coefficients:[-175.47701,1063.54495,-2570.70594,3098.80776,-1860.15527,444.76392],reachable:[.62,1]}},thinking6:{dark:{coefficients:[.65658,.04044,-1.01835,6.30989,-8.73529,4.05439],reachable:[0,.779]},light:{coefficients:[-183.81712,1094.70055,-2602.68539,3088.71276,-1826.91131,430.75931],reachable:[.643,1]}},subtle:{dark:{coefficients:[.56762,-.02475,-.5383,5.12628,-7.10931,3.17324],reachable:[0,.848]},light:{coefficients:[-232.85459,1376.54473,-3249.11801,3827.91186,-2248.29472,526.55751],reachable:[.657,1]}},thumb:{dark:{coefficients:[.60323,.00278,-.73328,5.57157,-7.68067,3.46933],reachable:[0,.823]},light:{coefficients:[-82.89897,511.01355,-1255.98095,1540.76821,-940.68087,228.58523],reachable:[.586,1]}},readable:{dark:{coefficients:[.66937,.04704,-1.06871,6.43941,-8.9332,4.17229],reachable:[0,.77]},light:{coefficients:[-1554.52576,8733.56817,-19604.93507,21977.72696,-12300.99599,2749.81288],reachable:[.751,1]}},emphasis:{dark:{coefficients:[.7303,.07695,-1.31626,7.1681,-10.14436,4.92846],reachable:[0,.712]},light:{coefficients:[-4948.31942,26870.91986,-58334.48399,63280.17197,-34298.01053,7430.30146],reachable:[.811,1]}},textOnPanel:{dark:{coefficients:[.86713,.05232,-.89428,4.79014,-5.5432,1.75023],reachable:[0,.542]},light:{coefficients:[-8570.89457,43954.60805,-90084.00702,92220.6791,-47152.15802,9632.27113],reachable:[.867,1]}},text:{dark:{coefficients:[.89242,.02311,-.44862,2.34417,-.06084,-2.63844],reachable:[0,.5]},light:{coefficients:[-2004.67048,6664.47299,-6060.70202,-1792.61209,5133.82359,-1939.85583],reachable:[.894,1]}}},me=["toolPendingBg","toolSuccessBg","toolErrorBg"],ri=["userMessageBg","customMessageBg"],As=["userMessageBg","toolPendingBg","toolSuccessBg","toolErrorBg","selectedBg","searchMatchBg","customMessageBg"],_m=["thinkingOff","thinkingMinimal","thinkingLow","thinkingMedium","thinkingHigh","thinkingXhigh","thinkingMax"],Om=["thinking0","thinking1","thinking2","thinking3","thinking4","thinking5","thinking6"],it=a((e,t,r)=>e.map(i=>({token:i,on:t,level:r})),"each"),ii=[...it(As,["background"],"panel"),{token:"text",on:["background"],level:"text"},{token:"text",on:["selectedBg"],level:"textOnPanel"},{token:"userMessageText",on:["userMessageBg"],level:"textOnPanel"},{token:"toolTitle",on:me,level:"textOnPanel"},...it(["accent","success","error","warning"],["background","selectedBg",...me],"readable"),{token:"muted",on:["background","selectedBg","customMessageBg",...me],level:"readable"},{token:"dim",on:["background","selectedBg","customMessageBg",...me],level:"subtle"},{token:"thinkingText",on:["background"],level:"readable"},{token:"customMessageText",on:["customMessageBg",...me],level:"readable"},{token:"customMessageLabel",on:["background","customMessageBg","selectedBg",...me],level:"readable"},{token:"toolOutput",on:["background",...me],level:"readable"},...it(["mdHeading","mdLink","mdLinkUrl","mdCode","mdQuote","mdCodeBlockBorder","mdListBullet"],["background",...ri],"readable"),{token:"mdCodeBlock",on:["background",...ri,...me],level:"readable"},...it(["toolDiffAdded","toolDiffRemoved","toolDiffContext"],["background",...me],"readable"),...it(["syntaxComment","syntaxKeyword","syntaxFunction","syntaxVariable","syntaxString","syntaxNumber","syntaxType","syntaxOperator","syntaxPunctuation"],["background",...ri,...me],"readable"),{token:"searchMatchText",on:["searchMatchBg"],level:"readable"},...it(["bashMode","border","borderAccent"],["background"],"readable"),{token:"borderMuted",on:["background"],level:"subtle"},...it(["mdQuoteBorder","mdHr"],["background",...ri,...me],"readable"),{token:"scrollbarTrack",on:["background"],level:"track"},{token:"scrollbarThumb",on:["scrollbarTrack"],level:"thumb"},..._m.map((e,t)=>({token:e,on:["background"],level:Om[t]}))],Dm={dark:"readable",light:"subtle"},Fm="emphasis",Ia=["text","userMessageText","toolTitle"],Ms=4.5,Nm=(()=>{let e=[],t=a(r=>{if(!e.includes(r)){for(let i of ii)if(i.token===r)for(let s of i.on)s!=="background"&&t(s);e.push(r)}},"visit");for(let r of ii)t(r.token);return e})();function Rt(e){return Ue(Se(e.r,e.g,e.b)).l}a(Rt,"oklabLightness");function La({r:e,g:t,b:r}){let i=a(s=>{let n=s/255;return n<=.04045?n/12.92:((n+.055)/1.055)**2.4},"linear");return .2126*i(e)+.7152*i(t)+.0722*i(r)}a(La,"relativeLuminance");function si(e,t){let r=La(e),i=La(t);return(Math.max(r,i)+.05)/(Math.min(r,i)+.05)}a(si,"wcagContrast");function Pa(e,t){let r={r:255,g:255,b:255},i={r:0,g:0,b:0},s=si(r,e),n=si(i,e);if(t){let o=Rt(t),l=Rt(e);if(Math.abs(o-l)>.05){let h=o>l?"dark":"light";if((h==="dark"?s:n)>=Ms)return h}}return s>=n?"dark":"light"}a(Pa,"terminalAppearance");var Wm=a((e,t,r)=>Math.min(r,Math.max(t,e)),"clamp2");function $a({r:e,g:t,b:r}){return`#${[e,t,r].map(i=>Math.round(i).toString(16).padStart(2,"0")).join("")}`}a($a,"hexOf");function _a(e){let t=a(r=>Math.exp(-((r-.5)**2)/.125),"gaussian");return(t(e)-t(0))/(1-t(0))}a(_a,"bellWeight");function Oa({saturation:{min:e,max:t}},r){let i=t>0?e/t:1;return i+(1-i)*_a(r)}a(Oa,"saturationCurve");function Da(e,t,r){let i=$m[e][t];if(!(r<i.reachable[0]||r>i.reachable[1]))return i.coefficients.reduce((s,n,o)=>s+n*r**o,0)}a(Da,"levelTarget");function Hm(e){let t=Wm(e.saturation??1,0,1),{background:r,foreground:i}=e;if(!r)return qm(t,e.appearanceHint);let s=e.palette?.length===16?e.palette.map(Na):void 0,n=Pa(r,i),o=n==="dark",l=o?1:0,h=Rt(r),u=a((y,k)=>{let v=kr(k),B=Cs[Ts[y]];if(!s){let{min:M,max:w}=B.saturation;return Ht(B.hue,(M+(w-M)*_a(v))*t,v)}return Wa(s[Ea[y]??B.slot],B,v,t)},"paint"),d=a((y,k,v)=>{let B=Da(y,n,k);if(B===void 0&&v===0)return;let M=(B??l)-k,w=(Da(Dm[n],n,k)??l)-k,A=Math.abs(M)>Math.abs(w)?M-(M-w)*Math.min(v,1):M;return k+A*(1-Math.max(0,v-1))},"target"),c=o?{r:255,g:255,b:255}:{r:0,g:0,b:0},p=a(y=>si(c,y)>=Ms,"readable"),f=a((y,k)=>{let v=u(y,k);if(p(v))return v;let[B,M]=[h,k];for(let w=0;w<20;w++){let A=(B+M)/2;p(u(y,A))?B=A:M=A}return u(y,B)},"limitPanel"),g=a(y=>{let k=new Map([["background",r]]);for(let v of Nm){let B=[];for(let w of ii)if(w.token===v)for(let A of w.on){let L=d(w.level,Rt(k.get(A)??r),y);if(L===void 0||L<0||L>1)return;B.push(L)}let M=o?Math.max(...B):Math.min(...B);k.set(v,As.includes(v)?f(v,M):u(v,M))}return k},"solve"),x=0,m=g(0);if(!m){let[y,k]=[0,2];m=g(k);for(let v=0;v<20;v++){let B=(y+k)/2,M=g(B);M?[k,m]=[B,M]:y=B}x=k}let b=m??new Map,C=a(y=>ii.filter(k=>k.token===y).flatMap(k=>k.on.map(v=>b.get(v)??r)),"surfacesOf"),S={};for(let y of Object.keys(Ts)){let k=b.get(y);S[y]=k?$a(k):""}for(let y of Ia){let k=C(y),v=b.get(y);if(i){let B=k.map(M=>d(Fm,Rt(M),x));if(B.every(M=>M!==void 0&&M>=0&&M<=1)){let M=o?Math.max(...B):Math.min(...B),w=Rt(i);if(o?w>=M:w<=M){S[y]="";continue}v=Wa(Na(i),Cs.neutral,kr(M),t)}}v&&(S[y]=$a(Vm(v,k,o)))}return{colors:S,dim:[],appearance:n}}a(Hm,"generateSystemThemeColors");function Fa({r:e,g:t,b:r}){return Gn(Se(e,t,r))}a(Fa,"okhslOf");function Na(e){return{...Fa(e),chroma:Ue(Se(e.r,e.g,e.b)).c}}a(Na,"sourceOf");function Wa(e,t,r,i){let s=Oa(t,e.l),n=s>0?Math.min(1,Oa(t,r)/s):1,o=Ht(e.h,e.s*n*i,r),l=e.chroma*n*i,{l:h,c:u}=Ue(o);return u<=l?o:Te(Sr(h,l,e.h))}a(Wa,"anchored");function Vm(e,t,r){let i=a(c=>t.every(p=>si(c,p)>=Ms),"meets");if(i(e))return e;let{h:s,s:n,l:o}=Fa(e),l=a(c=>Ht(s,n,c),"at2"),h=r?1:0;if(!i(l(h)))return l(h);let[u,d]=[o,h];for(let c=0;c<20;c++){let p=(u+d)/2;i(l(p))?d=p:u=p}return l(d)}a(Vm,"withTextContrast");function qm(e,t){let r={},i=[];for(let[s,n]of Object.entries(Ts)){if(As.includes(s)){r[s]="";continue}let o=n==="neutral";r[s]=!o&&e>0?Ea[s]??Cs[n].slot:"",o&&!Ia.includes(s)&&i.push(s)}return{colors:r,dim:i,appearance:t}}a(qm,"indexedColors");function Km(e){for(let[t,r]of Object.entries(e)){if(r.fallback===void 0)continue;let i=e[r.fallback];if(i===void 0)throw new Error(`Theme token ${t} has unknown fallback ${r.fallback}`);if(i.slot!==r.slot)throw new Error(`Theme token ${t} has fallback ${r.fallback} in a different color slot`)}return e}a(Km,"defineThemeTokens");var Bs=Km({accent:{slot:"foreground",description:"Primary accent color (logo, selected items, cursor)"},border:{slot:"foreground",description:"Normal borders"},borderAccent:{slot:"foreground",description:"Highlighted borders"},borderMuted:{slot:"foreground",description:"Subtle borders"},success:{slot:"foreground",description:"Success states"},error:{slot:"foreground",description:"Error states"},warning:{slot:"foreground",description:"Warning states"},muted:{slot:"foreground",description:"Secondary/dimmed text"},dim:{slot:"foreground",description:"Very dimmed text (more subtle than muted)"},text:{slot:"foreground",description:"Default text color (usually empty string)"},thinkingText:{slot:"foreground",description:"Thinking block text color"},scrollbarTrack:{slot:"foreground",description:"Fullscreen scrollbar track foreground (falls back to muted when omitted)",fallback:"muted"},scrollbarThumb:{slot:"foreground",description:"Fullscreen scrollbar thumb foreground (falls back to text when omitted)",fallback:"text"},selectedBg:{slot:"background",description:"Selected item background"},searchMatchBg:{slot:"background",description:"Transcript search match background and current-match text (falls back to selectedBg when omitted)",fallback:"selectedBg"},searchMatchText:{slot:"foreground",description:"Transcript search match text and current-match background (falls back to text when omitted)",fallback:"text"},userMessageBg:{slot:"background",description:"User message background"},userMessageText:{slot:"foreground",description:"User message text color"},customMessageBg:{slot:"background",description:"Custom message background (hook-injected messages)"},customMessageText:{slot:"foreground",description:"Custom message text color"},customMessageLabel:{slot:"foreground",description:"Custom message type label color"},toolPendingBg:{slot:"background",description:"Tool execution box (pending state)"},toolSuccessBg:{slot:"background",description:"Tool execution box (success state)"},toolErrorBg:{slot:"background",description:"Tool execution box (error state)"},toolTitle:{slot:"foreground",description:"Tool execution box title color"},toolOutput:{slot:"foreground",description:"Tool execution box output text color"},mdHeading:{slot:"foreground",description:"Markdown heading text"},mdLink:{slot:"foreground",description:"Markdown link text"},mdLinkUrl:{slot:"foreground",description:"Markdown link URL"},mdCode:{slot:"foreground",description:"Markdown inline code"},mdCodeBlock:{slot:"foreground",description:"Markdown code block content"},mdCodeBlockBorder:{slot:"foreground",description:"Markdown code block fences"},mdQuote:{slot:"foreground",description:"Markdown blockquote text"},mdQuoteBorder:{slot:"foreground",description:"Markdown blockquote border"},mdHr:{slot:"foreground",description:"Markdown horizontal rule"},mdListBullet:{slot:"foreground",description:"Markdown list bullets/numbers"},toolDiffAdded:{slot:"foreground",description:"Added lines in tool diffs"},toolDiffRemoved:{slot:"foreground",description:"Removed lines in tool diffs"},toolDiffContext:{slot:"foreground",description:"Context lines in tool diffs"},syntaxComment:{slot:"foreground",description:"Syntax highlighting: comments"},syntaxKeyword:{slot:"foreground",description:"Syntax highlighting: keywords"},syntaxFunction:{slot:"foreground",description:"Syntax highlighting: function names"},syntaxVariable:{slot:"foreground",description:"Syntax highlighting: variable names"},syntaxString:{slot:"foreground",description:"Syntax highlighting: string literals"},syntaxNumber:{slot:"foreground",description:"Syntax highlighting: number literals"},syntaxType:{slot:"foreground",description:"Syntax highlighting: type names"},syntaxOperator:{slot:"foreground",description:"Syntax highlighting: operators"},syntaxPunctuation:{slot:"foreground",description:"Syntax highlighting: punctuation"},thinkingOff:{slot:"foreground",description:"Thinking level border: off"},thinkingMinimal:{slot:"foreground",description:"Thinking level border: minimal"},thinkingLow:{slot:"foreground",description:"Thinking level border: low"},thinkingMedium:{slot:"foreground",description:"Thinking level border: medium"},thinkingHigh:{slot:"foreground",description:"Thinking level border: high"},thinkingXhigh:{slot:"foreground",description:"Thinking level border: xhigh"},thinkingMax:{slot:"foreground",description:"Thinking level border: max (falls back to thinkingXhigh when omitted)",fallback:"thinkingXhigh"},bashMode:{slot:"foreground",description:"Editor border color in bash mode"}}),Rs;function Um(e){Rs=e}a(Um,"setThemeJsonValidator");function Es(e,t,r=new Set){if(typeof e=="number"||e===""||e.startsWith("#")||/^ok(lch|hsl)\(/i.test(e))return e;if(r.has(e))throw new Error(`Circular variable reference detected: ${e}`);if(!(e in t))throw new Error(`Variable reference not found: ${e}`);return r.add(e),Es(t[e],t,r)}a(Es,"resolveVarRefs");function jm(e,t={}){let r={};for(let[i,s]of Object.entries(e))r[i]=Es(s,t);return r}a(jm,"resolveThemeColors");function Is(e){let t={...e};for(let[r,i]of Object.entries(Bs)){if(!("fallback"in i))continue;let s=r;if(t[s]!==void 0)continue;let n=i.fallback,o=t[n];if(o===void 0)throw new Error(`Theme token ${r} has unresolved fallback ${i.fallback}`);t[s]=o}return t}a(Is,"withThemeTokenFallbacks");var ni={},Ls=!1,Ha;function zm(e){ni={...e},Ls=!1}a(zm,"setTerminalColors");function Gm(e){Ha=e}a(Gm,"setTerminalColorScheme");function Ym(){Ls=!0}a(Ym,"markTerminalColorsPending");var Xm={dark:{foreground:Pe("#e5e5e7"),background:Pe("#000000")},light:{foreground:Pe("#000000"),background:Pe("#ffffff")}};function Va(e){let t=e.filter(r=>r.kind!=="indexed"||r.index>=16);if(t.length!==0)return t.reduce((r,i)=>r+Ue(i).l,0)/t.length}a(Va,"averageLightness");function Qm(e,t){let r=Va(e),i=Va(t);if(r!==void 0&&i!==void 0)return i<r?"dark":"light";if(i!==void 0)return i<.5?"dark":"light";if(r!==void 0)return r>.5?"dark":"light"}a(Qm,"detectAppearance");var Ps=class{static{a(this,"Theme")}name;sourcePath;sourceInfo;mode;fgAnsi=new Map;bgAnsi=new Map;concreteColors={};defaultForegroundTokens=[];defaultBackgroundTokens=[];dimTokens;ownAppearance;resolvedColors;constructor(e,t,r,i={}){this.name=i.name,this.sourcePath=i.sourcePath,this.sourceInfo=i.sourceInfo,this.mode=r,this.dimTokens=new Set(i.dim);let{fgColors:s,bgColors:n}=Os(Is({...e,...t})),o=[],l=[],h=a((u,d,c)=>{if(d==="")return(c?this.defaultBackgroundTokens:this.defaultForegroundTokens).push(u),c?"\x1B[49m":"\x1B[39m";let p=Pe(d);return this.concreteColors[u]=p,(c?l:o).push(p),c?qt(p,r):Vt(p,r)},"addToken");for(let[u,d]of Object.entries(s))this.fgAnsi.set(u,h(u,d,!1));for(let[u,d]of Object.entries(n))this.bgAnsi.set(u,h(u,d,!0));this.ownAppearance=i.appearance??Qm(o,l)}get appearance(){return this.ownAppearance??Fs()}get colors(){let e=ni;if(this.resolvedColors?.terminal!==e){let t=Xm[this.appearance],r=a((o,l)=>o?Se(o.r,o.g,o.b):l,"toColor"),i=r(e.foreground,t.foreground),s=r(e.background,t.background),n={...this.concreteColors};for(let o of this.defaultForegroundTokens)n[o]=i;for(let o of this.defaultBackgroundTokens)n[o]=s;for(let o of this.dimTokens){let l=n[o];l&&(n[o]=Bi(l,s,.4))}this.resolvedColors={terminal:e,colors:Object.freeze(n)}}return this.resolvedColors.colors}style(e,t){let{fg:r,bg:i}=t;return typeof r=="string"&&this.dimTokens.has(r)&&(t={...t,dim:!0}),Ri(e,r===void 0?void 0:typeof r=="string"?this.tokenAnsi(this.fgAnsi,r):Vt(r,this.mode),i===void 0?void 0:typeof i=="string"?this.tokenAnsi(this.bgAnsi,i):qt(i,this.mode),t)}fg(e,t){let r=this.tokenAnsi(this.fgAnsi,e);return this.dimTokens.has(e)?`${r}\x1B[2m${t}\x1B[22;39m`:`${r}${t}\x1B[39m`}bg(e,t){return`${this.tokenAnsi(this.bgAnsi,e)}${t}\x1B[49m`}tokenAnsi(e,t){let r=e.get(t);if(r===void 0)throw new Error(`Unknown theme color: ${t}`);return r}bold(e){return ht.bold(e)}italic(e){return ht.italic(e)}underline(e){return ht.underline(e)}inverse(e){return ht.inverse(e)}strikethrough(e){return ht.strikethrough(e)}getFgAnsi(e){let t=this.tokenAnsi(this.fgAnsi,e);return this.dimTokens.has(e)?`${t}\x1B[2m`:t}getBgAnsi(e){return this.tokenAnsi(this.bgAnsi,e)}getColorMode(){return this.mode}getThinkingBorderColor(e){switch(e){case"off":return t=>this.fg("thinkingOff",t);case"minimal":return t=>this.fg("thinkingMinimal",t);case"low":return t=>this.fg("thinkingLow",t);case"medium":return t=>this.fg("thinkingMedium",t);case"high":return t=>this.fg("thinkingHigh",t);case"xhigh":return t=>this.fg("thinkingXhigh",t);case"max":return t=>this.fg("thinkingMax",t);default:return t=>this.fg("thinkingOff",t)}}getBashModeBorderColor(){return e=>this.fg("bashMode",e)}},$s;function qa(){if(!$s){let e=cn(),t=Bt.join(e,"dark.json"),r=Bt.join(e,"light.json");$s={dark:JSON.parse(Ve(ye.readFileSync(t,"utf-8"))),light:JSON.parse(Ve(ye.readFileSync(r,"utf-8")))}}return $s}a(qa,"getBuiltinThemes");function Zm(){return Ka().map(({name:e})=>e)}a(Zm,"getAvailableThemes");function Ka(){let e=cn(),t=[],r=new Set,i=a(s=>{r.has(s.name)||(r.add(s.name),t.push(s))},"addTheme");i({name:ee,path:void 0});for(let s of Object.keys(qa()))i({name:s,path:Bt.join(e,`${s}.json`)});for(let s of Jm())i(s);for(let[s,n]of Lt.entries())i({name:s,path:n.sourcePath});return t.sort((s,n)=>s.name===ee?-1:n.name===ee?1:s.name.localeCompare(n.name))}a(Ka,"getAvailableThemesWithPaths");function Jm(){let e=hi(),t=[];if(!ye.existsSync(e))return t;for(let r of ye.readdirSync(e)){if(!r.endsWith(".json"))continue;let i=Bt.join(e,r);try{let s=Ds(i);s.name&&t.push({name:s.name,path:i})}catch{}}return t}a(Jm,"getCustomThemeInfos");function e0(e){if(e.includes("/"))throw new Error(`Invalid theme name "${e}": theme names cannot contain "/" because it is reserved for automatic light/dark theme settings.`)}a(e0,"assertThemeNameIsValid");function t0(e,t){if(Rs)return Rs(e,t);if(typeof t!="object"||t===null||!("colors"in t))throw new Error(`Invalid theme "${e}": expected an object with a "colors" map.`);return t}a(t0,"parseThemeJson");function _s(e,t){let r;try{r=JSON.parse(Ve(t))}catch(i){throw new Error(`Failed to parse theme ${e}: ${i}`)}return t0(e,r)}a(_s,"parseThemeJsonContent");function Ua(e){let t=qa();if(e in t)return t[e];let r=Lt.get(e);if(r?.sourcePath){let o=ye.readFileSync(r.sourcePath,"utf-8");return _s(r.sourcePath,o)}if(r)throw new Error(`Theme "${e}" does not have a source path for export`);let i=hi(),s=Bt.join(i,`${e}.json`);if(!ye.existsSync(s))throw new Error(`Theme not found: ${e}`);let n=ye.readFileSync(s,"utf-8");return _s(e,n)}a(Ua,"loadThemeJson");function Os(e){let t={},r={};for(let[i,s]of Object.entries(e))Bs[i].slot==="background"?r[i]=s:t[i]=s;return{fgColors:t,bgColors:r}}a(Os,"splitThemeColors");function ja(e,t,r){let i=t??Fr(),s=Is(jm(e.colors,e.vars)),{fgColors:n,bgColors:o}=Os(s);return new Ps(n,o,i,{name:e.name,sourcePath:r,appearance:e.appearance})}a(ja,"createTheme");function r0(e){let t=Hm({...ni,saturation:Ls?0:1,appearanceHint:Fs()}),{fgColors:r,bgColors:i}=Os(Is(t.colors));return new Ps(r,i,e??Fr(),{name:ee,appearance:t.appearance,dim:t.dim})}a(r0,"createSystemTheme");function Ds(e,t){let r=ye.readFileSync(e,"utf-8"),i=_s(e,r);return ja(i,t,e)}a(Ds,"loadThemeFromPath");function Et(e,t){if(e===ee)return r0(t);let r=Lt.get(e);if(r)return r;let i=Ua(e);return ja(i,t)}a(Et,"loadTheme");function i0(e){try{return Et(e)}catch{return}}a(i0,"getThemeByName");function za(e){if(!e)return;let t=e.indexOf("/");if(t===-1||e.indexOf("/",t+1)!==-1)return;let r=e.slice(0,t).trim(),i=e.slice(t+1).trim();if(!(!r||!i))return{lightTheme:r,darkTheme:i}}a(za,"parseAutoThemeSetting");function s0(e,t){let r=za(e);if(r)return t==="light"?r.lightTheme:r.darkTheme;if(!e?.includes("/")&&typeof e=="string")return e}a(s0,"resolveThemeSetting");function n0(e=process.env){let t=e.COLORFGBG?.split(";").at(-1)?.trim();if(!t||!/^\d{1,2}$/.test(t))return;let r=Number(t);if(!(r>15))return r<=6||r===8?"dark":"light"}a(n0,"detectColorFgBgTheme");function o0(e={},t,r=process.env){let{background:i,foreground:s}=e;return i?Pa(i,s):t??n0(r)??"dark"}a(o0,"detectTerminalTheme");function Fs(){return o0(ni,Ha)}a(Fs,"getTerminalTheme");var Ga=Symbol.for("@earendil-works/pi-coding-agent:theme"),l0=Symbol.for("@mariozechner/pi-coding-agent:theme"),$=new Proxy({},{get(e,t){let r=globalThis[Ga];if(!r)throw new Error("Theme not initialized. Call initTheme() first.");return r[t]}});function It(e){globalThis[Ga]=e,globalThis[l0]=e}a(It,"setGlobalTheme");var re,nr,st,nt,Lt=new Map;function a0(e){Lt.clear();for(let t of e)t.name&&(e0(t.name),Lt.set(t.name,t))}a(a0,"setRegisteredThemes");function h0(e,t=!1){let r=e??ee;re=r;try{It(Et(r)),t&&Ya()}catch{re=ee,It(Et(ee))}}a(h0,"initTheme");function u0(e,t=!1){re=e;try{return It(Et(e)),t&&Ya(),nt&&nt(),{success:!0}}catch(r){return re=ee,It(Et(ee)),{success:!1,error:r instanceof Error?r.message:String(r)}}}a(u0,"setTheme");function c0(e){It(e),re="<in-memory>",Ns(),nt&&nt()}a(c0,"setThemeInstance");function d0(e){nt=e}a(d0,"onThemeChange");function Ya(){if(Ns(),!re||re==="dark"||re==="light"||re===ee)return;let e=hi(),t=re,r=`${t}.json`,i=Bt.join(e,r);if(!ye.existsSync(i))return;let s=a(()=>{st&&clearTimeout(st),st=setTimeout(()=>{if(st=void 0,re===t&&ye.existsSync(i))try{let n=Ds(i);Lt.set(t,n),It(n),nt&&nt()}catch{}},100)},"scheduleReload");nr=Ca(e,(n,o)=>{if(re===t){if(!o){s();return}o===r&&s()}},()=>{vs(nr),nr=void 0})??void 0}a(Ya,"startThemeWatcher");function Ns(){st&&(clearTimeout(st),st=void 0),vs(nr),nr=void 0}a(Ns,"stopThemeWatcher");function p0(e){let t=Et(e??re??ee).colors;return Object.fromEntries(Object.entries(t).map(([r,i])=>[r,Cr(i)]))}a(p0,"getResolvedThemeColors");function f0(e){let t=e??re??ee;if(t===ee)return{};try{let r=Ua(t),i=r.export;if(!i)return{};let s=r.vars??{},n=a(o=>{if(o===void 0)return;let l=Es(o,s);if(typeof l=="number")return Cr(vr(l));if(l!=="")return/^okhsl\(/i.test(l)?Cr(Pe(l)):l},"resolve2");return{pageBg:n(i.pageBg),cardBg:n(i.cardBg),infoBg:n(i.infoBg)}}catch{return{}}}a(f0,"getThemeExportColors");var Xa,Ws;function g0(e){return{keyword:a(t=>e.fg("syntaxKeyword",t),"keyword"),built_in:a(t=>e.fg("syntaxType",t),"built_in"),literal:a(t=>e.fg("syntaxNumber",t),"literal"),number:a(t=>e.fg("syntaxNumber",t),"number"),regexp:a(t=>e.fg("syntaxString",t),"regexp"),string:a(t=>e.fg("syntaxString",t),"string"),subst:a(t=>e.fg("text",t),"subst"),comment:a(t=>e.fg("syntaxComment",t),"comment"),doctag:a(t=>e.fg("syntaxComment",t),"doctag"),meta:a(t=>e.fg("muted",t),"meta"),function:a(t=>e.fg("syntaxFunction",t),"function"),title:a(t=>e.fg("syntaxFunction",t),"title"),class:a(t=>e.fg("syntaxType",t),"class"),type:a(t=>e.fg("syntaxType",t),"type"),tag:a(t=>e.fg("syntaxPunctuation",t),"tag"),name:a(t=>e.fg("syntaxKeyword",t),"name"),attr:a(t=>e.fg("syntaxVariable",t),"attr"),variable:a(t=>e.fg("syntaxVariable",t),"variable"),params:a(t=>e.fg("syntaxVariable",t),"params"),operator:a(t=>e.fg("syntaxOperator",t),"operator"),punctuation:a(t=>e.fg("syntaxPunctuation",t),"punctuation"),emphasis:a(t=>e.italic(t),"emphasis"),strong:a(t=>e.bold(t),"strong"),link:a(t=>e.underline(t),"link"),addition:a(t=>e.fg("toolDiffAdded",t),"addition"),deletion:a(t=>e.fg("toolDiffRemoved",t),"deletion")}}a(g0,"buildCliHighlightTheme");function Qa(e){return(Xa!==e||!Ws)&&(Xa=e,Ws=g0(e)),Ws}a(Qa,"getCliHighlightTheme");function m0(e,t){let r=t&&Ra(t)?t:void 0;if(!r)return e.split(`
|
|
129
|
-
`).map(s=>$.fg("mdCodeBlock",s));let i={language:r,ignoreIllegals:!0,theme:Qa($)};try{return Ba(e,i).split(`
|
|
130
|
-
`)}catch{return e.split(`
|
|
131
|
-
`)}}a(m0,"highlightCode");function x0(e){let t=e.split(".").pop()?.toLowerCase();return t?{ts:"typescript",tsx:"typescript",js:"javascript",jsx:"javascript",mjs:"javascript",cjs:"javascript",py:"python",rb:"ruby",rs:"rust",go:"go",java:"java",kt:"kotlin",swift:"swift",c:"c",h:"c",cpp:"cpp",cc:"cpp",cxx:"cpp",hpp:"cpp",cs:"csharp",php:"php",sh:"bash",bash:"bash",zsh:"bash",fish:"fish",ps1:"powershell",sql:"sql",html:"html",htm:"html",css:"css",scss:"scss",sass:"sass",less:"less",json:"json",yaml:"yaml",yml:"yaml",toml:"toml",xml:"xml",md:"markdown",markdown:"markdown",dockerfile:"dockerfile",makefile:"makefile",cmake:"cmake",lua:"lua",perl:"perl",r:"r",scala:"scala",clj:"clojure",ex:"elixir",exs:"elixir",erl:"erlang",hs:"haskell",ml:"ocaml",vim:"vim",graphql:"graphql",proto:"protobuf",tf:"hcl",hcl:"hcl"}[t]:void 0}a(x0,"getLanguageFromPath");function b0(){return{heading:a(e=>$.fg("mdHeading",e),"heading"),link:a(e=>$.fg("mdLink",e),"link"),linkUrl:a(e=>$.fg("mdLinkUrl",e),"linkUrl"),code:a(e=>$.fg("mdCode",e),"code"),codeBlock:a(e=>$.fg("mdCodeBlock",e),"codeBlock"),codeBlockBorder:a(e=>$.fg("mdCodeBlockBorder",e),"codeBlockBorder"),quote:a(e=>$.fg("mdQuote",e),"quote"),quoteBorder:a(e=>$.fg("mdQuoteBorder",e),"quoteBorder"),hr:a(e=>$.fg("mdHr",e),"hr"),listBullet:a(e=>$.fg("mdListBullet",e),"listBullet"),bold:a(e=>$.bold(e),"bold"),italic:a(e=>$.italic(e),"italic"),underline:a(e=>$.underline(e),"underline"),strikethrough:a(e=>$.strikethrough(e),"strikethrough"),highlightCode:a((e,t)=>{let r=t&&Ra(t)?t:void 0;if(!r)return e.split(`
|
|
132
|
-
`).map(s=>$.fg("mdCodeBlock",s));let i={language:r,ignoreIllegals:!0,theme:Qa($)};try{return Ba(e,i).split(`
|
|
133
|
-
`)}catch{return e.split(`
|
|
134
|
-
`).map(s=>$.fg("mdCodeBlock",s))}},"highlightCode")}}a(b0,"getMarkdownTheme");function Za(){return{selectedPrefix:a(e=>$.fg("accent",e),"selectedPrefix"),selectedText:a(e=>$.fg("accent",e),"selectedText"),description:a(e=>$.fg("muted",e),"description"),scrollInfo:a(e=>$.fg("muted",e),"scrollInfo"),noMatch:a(e=>$.fg("muted",e),"noMatch")}}a(Za,"getSelectListTheme");function y0(){return{borderColor:a(e=>$.fg("border",e),"borderColor"),selectList:Za(),placeholder:a(e=>$.fg("dim",e),"placeholder")}}a(y0,"getEditorTheme");function w0(){return{label:a((e,t)=>t?$.fg("accent",e):e,"label"),value:a((e,t)=>t?$.fg("accent",e):$.fg("muted",e),"value"),description:a(e=>$.fg("dim",e),"description"),cursor:$.fg("accent","\u2192 "),hint:a(e=>$.fg("dim",e),"hint")}}a(w0,"getSettingsListTheme");function k0(e,t){let r=process.platform==="darwin"&&e.toLowerCase()==="alt"?"option":e;return t.capitalize?r.charAt(0).toUpperCase()+r.slice(1):r}a(k0,"formatKeyPart");function Hs(e,t={}){return e.split("/").map(r=>r.split("+").map(i=>k0(i,t)).join("+")).join("/")}a(Hs,"formatKeyText");function Ja(e,t={}){return e.length===0?"":Hs(e.join("/"),t)}a(Ja,"formatKeys");function eh(e){return Ja(ue().getKeys(e))}a(eh,"keyText");function v0(e){return Ja(ue().getKeys(e),{capitalize:!0})}a(v0,"keyDisplayText");function S0(e,t){return $.fg("dim",eh(e))+$.fg("muted",` ${t}`)}a(S0,"keyHint");function C0(e,t){return $.fg("dim",Hs(e))+$.fg("muted",` ${t}`)}a(C0,"rawKeyHint");export{Ke as APP_NAME,Iu as APP_TITLE,dl as Box,xn as CONFIG_DIR_NAME,gl as CancellableLoader,Wo as CombinedAutocompleteProvider,Ne as Container,kn as DAL_RELEASES_URL,wn as DAL_RELEASE_REPO,yn as DAL_UPDATE_PACKAGE,vn as DAL_UPDATE_REGISTRY,Sn as ENV_AGENT_DIR,_u as ENV_SESSION_DIR,Il as Editor,im as FS_WATCH_RETRY_DELAY_MS,Lu as IS_WHITE_LABEL_BUILD,_l as Image,Ur as Input,Jn as Key,Pi as KeybindingsManager,is as Loader,Wl as Markdown,Hl as MouseRegion,Eu as PACKAGE_NAME,ra as ProcessTerminal,Pu as SHARED_SKILL_CONFIG_DIRS,ee as SYSTEM_THEME_NAME,ps as ScrollView,ss as SelectList,Vl as SettingsList,ql as Spacer,Bs as THEME_TOKENS,Li as TUI_KEYBINDINGS,rs as Text,Ps as Theme,Kl as TruncatedText,ba as TuiAltScreen,Sa as TuiMainScreen,bn as VERSION,Ul as VStack,Or as Z,qt as backgroundAnsi,tu as canonicalizePath,vs as closeWatcher,Te as colorToRgb,ji as detectCapabilities,Ru as detectInstallChange,ai as detectInstallMethod,ho as dist_exports,Cn as expandTildePath,Vt as foregroundAnsi,Hs as formatKeyText,nu as formatPathRelativeToCwdOrAbsolute,Qt as fuzzyFilter,Ki as fuzzyMatch,at as getAgentDir,Zm as getAvailableThemes,Ka as getAvailableThemesWithPaths,Fu as getBinDir,Tu as getBundledInteractiveAssetPath,pe as getCapabilities,Su as getChangelogPath,Bu as getCodemodeWorkerSpecifier,Js as getCwdRelativePath,yu as getDalDocsPath,Wu as getDebugLogPath,bu as getDocsPath,y0 as getEditorTheme,dn as getExamplesPath,gu as getExportTemplateDir,ru as getFileRevision,Zi as getImageDimensions,ue as getKeybindings,x0 as getLanguageFromPath,b0 as getMarkdownTheme,zl as getNativeClipboard,wu as getOfficialExtensionsPath,X as getPackageDir,Au as getQuickJSWasmPath,xu as getReadmePath,p0 as getResolvedThemeColors,Za as getSelectListTheme,du as getSelfUpdateCommand,pu as getSelfUpdateUnavailableInstruction,Nu as getSessionsDir,w0 as getSettingsListTheme,Du as getSettingsPath,Ou as getShareViewerUrl,Fr as getTerminalColorMode,Fs as getTerminalTheme,i0 as getThemeByName,f0 as getThemeExportColors,m0 as highlightCode,Nr as hyperlink,Wr as imageFallback,vr as indexedColor,h0 as initTheme,ms as isAppleTerminalSession,Ee as isBunBinary,rn as isBundledNode,iu as isLocalPath,vu as isOfficialExtensionsPackage,ul as isViewportTUI,v0 as keyDisplayText,S0 as keyHint,eh as keyText,Bm as loadAllHighlightLanguages,Ds as loadThemeFromPath,ou as markPathIgnoredByCloudSync,Ym as markTerminalColorsPending,_e as matchesKey,Bi as mixColors,Pt as normalizePath,d0 as onThemeChange,za as parseAutoThemeSetting,Pe as parseColor,C0 as rawKeyHint,Ks as require_cross_spawn,ar as resolvePath,s0 as resolveThemeSetting,Se as rgbColor,Uo as setCapabilityOverrides,$l as setImageTranscoder,ao as setKeybindings,a0 as setRegisteredThemes,Gm as setTerminalColorScheme,zm as setTerminalColors,u0 as setTheme,c0 as setThemeInstance,Um as setThemeJsonValidator,Y as sliceByColumn,ht as source_default,jh as spawnProcess,lr as spawnProcessSync,en as splitBom,Ns as stopThemeWatcher,Ve as stripBom,$ as theme,K as truncateToWidth,T as visibleWidth,zh as waitForChildProcess,Ca as watchWithErrorHandler,ve as wrapTextWithAnsi};
|