UNPKG

vibetunnel

Version:

Terminal sharing server with web interface - supports macOS, Linux, and headless environments

40 lines (37 loc) 849 kB
var no=Object.create;var Gi=Object.defineProperty;var Br=Object.getOwnPropertyDescriptor;var oo=Object.getOwnPropertyNames;var ao=Object.getPrototypeOf,lo=Object.prototype.hasOwnProperty;var ki=(c,i)=>()=>(c&&(i=c(c=0)),i);var co=(c,i)=>()=>(i||c((i={exports:{}}).exports,i),i.exports),Rr=(c,i)=>{for(var e in i)Gi(c,e,{get:i[e],enumerable:!0})},ho=(c,i,e,t)=>{if(i&&typeof i=="object"||typeof i=="function")for(let s of oo(i))!lo.call(c,s)&&s!==e&&Gi(c,s,{get:()=>i[s],enumerable:!(t=Br(i,s))||t.enumerable});return c};var uo=(c,i,e)=>(e=c!=null?no(ao(c)):{},ho(i||!c||!c.__esModule?Gi(e,"default",{value:c,enumerable:!0}):e,c));var d=(c,i,e,t)=>{for(var s=t>1?void 0:t?Br(i,e):i,n=c.length-1,o;n>=0;n--)(o=c[n])&&(s=(t?o(i,e,s):o(s))||s);return t&&s&&Gi(i,e,s),s};var ye=ki(()=>{});var me,Qi,Yi,Dr=ki(()=>{globalThis.crypto?.subtle&&(me=globalThis.crypto.subtle);Qi=class Qi{constructor(i){this.keys=new Map;this.cryptoErrorShown=!1;this.storageKey=i||Qi.DEFAULT_STORAGE_KEY,this.loadKeysFromStorage()}ensureCryptoAvailable(){if(!me)throw this.cryptoErrorShown||(this.showCryptoError(),this.cryptoErrorShown=!0),new Error("Web Crypto API is not available")}showCryptoError(){if(!document.body){console.error("Web Crypto API not available and DOM not ready to show error");return}let i=window.location.hostname,e=i.match(/^(192\.168\.|10\.|172\.(1[6-9]|2[0-9]|3[0-1])\.)/),t=i!=="localhost"&&i!=="127.0.0.1",s=`SSH key operations are unavailable because the Web Crypto API is not accessible. `;if(e||t&&window.location.protocol==="http:"?(e&&window.location.protocol==="https:"?s+=`Even though you're using HTTPS, browsers block the Web Crypto API on local network IPs. `:s+=`This happens when accessing VibeTunnel over HTTP from non-localhost addresses. `,s+=`To fix this, use one of these methods: `,s+=`1. Access via http://localhost:4020 instead `,s+=` - Use SSH tunnel: ssh -L 4020:localhost:4020 user@server `,s+=`2. Enable HTTPS on the server (recommended for production) `,s+=`3. For Chrome: Enable insecure origins at chrome://flags/#unsafely-treat-insecure-origin-as-secure `,s+=` - Add your server URL (e.g., http://192.168.1.100:4020) `,s+=` - Restart Chrome after changing the flag `,s+=" - Note: Firefox also enforces these restrictions since v75"):(s+=`Your browser may not support the Web Crypto API or it may be disabled. `,s+="Please use a modern browser (Chrome 60+, Firefox 75+, Safari 11+)."),!document.querySelector("#crypto-error-style")){let n=document.createElement("style");n.id="crypto-error-style",n.textContent=` .crypto-error-banner { position: fixed; top: 0; left: 0; right: 0; background: #dc2626; color: white; padding: 16px; z-index: 9999; font-family: monospace; white-space: pre-wrap; box-shadow: 0 2px 10px rgba(0,0,0,0.3); } `,document.head.appendChild(n)}if(!document.querySelector(".crypto-error-banner")){let n=document.createElement("div");n.className="crypto-error-banner",n.textContent=s,document.body.appendChild(n)}}isUnlocked(){return!0}async addKey(i,e){if(this.ensureCryptoAvailable(),!me)throw new Error("Crypto not available");try{let t=await this.parsePrivateKey(e),s=this.generateKeyId(),n={id:s,name:i,publicKey:t.publicKey,privateKey:e,algorithm:"Ed25519",encrypted:t.encrypted,fingerprint:t.fingerprint,createdAt:new Date().toISOString()};return this.keys.set(s,n),this.saveKeysToStorage(),s}catch(t){throw new Error(`Failed to add SSH key: ${t}`)}}removeKey(i){this.keys.delete(i),this.saveKeysToStorage()}listKeys(){return Array.from(this.keys.values()).map(i=>({id:i.id,name:i.name,publicKey:i.publicKey,algorithm:i.algorithm,encrypted:i.encrypted,fingerprint:i.fingerprint,createdAt:i.createdAt}))}async sign(i,e){if(this.ensureCryptoAvailable(),!me)throw new Error("Crypto not available");let t=this.keys.get(i);if(!t)throw new Error("SSH key not found");if(!t.privateKey)throw new Error("Private key not available for signing");try{let s=t.privateKey;if(t.encrypted){let a=await this.promptForPassword(t.name);if(!a)throw new Error("Password required for encrypted key");s=await this.decryptPrivateKey(t.privateKey,a)}let n=await this.importPrivateKey(s,t.algorithm),o=this.base64ToArrayBuffer(e),r=await me.sign({name:"Ed25519"},n,o);return{signature:this.arrayBufferToBase64(r),algorithm:t.algorithm}}catch(s){throw new Error(`Failed to sign data: ${s}`)}}async generateKeyPair(i,e){if(this.ensureCryptoAvailable(),!me)throw new Error("Crypto not available");console.log(`\u{1F511} SSH Agent: Starting Ed25519 key generation for "${i}"`);try{let s=await me.generateKey({name:"Ed25519"},!0,["sign","verify"]),n=await me.exportKey("pkcs8",s.privateKey),o=await me.exportKey("raw",s.publicKey),r=this.arrayBufferToPEM(n,"PRIVATE KEY"),a=this.convertEd25519ToSSHPublicKey(o),m=!!e;e&&(r=await this.encryptPrivateKey(r,e));let p=this.generateKeyId(),h={id:p,name:i,publicKey:a,privateKey:r,algorithm:"Ed25519",encrypted:m,fingerprint:await this.generateFingerprint(a),createdAt:new Date().toISOString()};return this.keys.set(p,h),await this.saveKeysToStorage(),console.log(`\u{1F511} SSH Agent: Key "${i}" generated successfully with ID: ${p}`),{keyId:p,privateKeyPEM:r}}catch(t){throw new Error(`Failed to generate key pair: ${t}`)}}getPublicKey(i){let e=this.keys.get(i);return e?e.publicKey:null}getPrivateKey(i){let e=this.keys.get(i);return e?e.privateKey:null}async parsePrivateKey(i){let e=i.includes("BEGIN ENCRYPTED PRIVATE KEY")||i.includes("Proc-Type: 4,ENCRYPTED");if(i.includes("BEGIN PRIVATE KEY")||i.includes("BEGIN ENCRYPTED PRIVATE KEY")){let t="ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIImported...";return{publicKey:t,algorithm:"Ed25519",fingerprint:await this.generateFingerprint(t),encrypted:e}}throw new Error("Only Ed25519 private keys are supported")}async importPrivateKey(i,e){if(!me)throw new Error("Crypto not available");let t=i.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").replace(/\s/g,""),s=this.base64ToArrayBuffer(t);return me.importKey("pkcs8",s,{name:"Ed25519"},!1,["sign"])}convertEd25519ToSSHPublicKey(i){let e=new Uint8Array(i),s=new TextEncoder().encode("ssh-ed25519"),n=new ArrayBuffer(4+s.length+4+e.length),o=new DataView(n),r=new Uint8Array(n),a=0;return o.setUint32(a,s.length,!1),a+=4,r.set(s,a),a+=s.length,o.setUint32(a,e.length,!1),a+=4,r.set(e,a),`ssh-ed25519 ${this.arrayBufferToBase64(n)}`}async generateFingerprint(i){if(!me)throw new Error("Crypto not available");let e=new TextEncoder,t=await me.digest("SHA-256",e.encode(i));return this.arrayBufferToBase64(t).substring(0,16)}generateKeyId(){return window.crypto.randomUUID()}arrayBufferToBase64(i){let e=new Uint8Array(i),t="";for(let s=0;s<e.length;s++)t+=String.fromCharCode(e[s]);return btoa(t)}base64ToArrayBuffer(i){let e=atob(i),t=new Uint8Array(e.length);for(let s=0;s<e.length;s++)t[s]=e.charCodeAt(s);return t.buffer}arrayBufferToPEM(i,e){let s=this.arrayBufferToBase64(i).match(/.{1,64}/g)||[];return`-----BEGIN ${e}----- ${s.join(` `)} -----END ${e}-----`}async loadKeysFromStorage(){try{let i=localStorage.getItem(this.storageKey);if(i){let e=JSON.parse(i);this.keys.clear(),e.forEach(t=>this.keys.set(t.id,t))}}catch(i){console.error("Failed to load SSH keys from storage:",i)}}async saveKeysToStorage(){try{let i=Array.from(this.keys.values());localStorage.setItem(this.storageKey,JSON.stringify(i))}catch(i){console.error("Failed to save SSH keys to storage:",i)}}async encryptPrivateKey(i,e){if(!me)throw new Error("Crypto not available");let t=new TextEncoder,s=t.encode(i),n=await me.importKey("raw",t.encode(e),{name:"PBKDF2"},!1,["deriveKey"]),o=crypto.getRandomValues(new Uint8Array(16)),r=await me.deriveKey({name:"PBKDF2",salt:o,iterations:1e5,hash:"SHA-256"},n,{name:"AES-GCM",length:256},!1,["encrypt"]),a=crypto.getRandomValues(new Uint8Array(12)),m=await me.encrypt({name:"AES-GCM",iv:a},r,s),p=new Uint8Array(o.length+a.length+m.byteLength);return p.set(o,0),p.set(a,o.length),p.set(new Uint8Array(m),o.length+a.length),`-----BEGIN ENCRYPTED PRIVATE KEY----- ${this.arrayBufferToBase64(p.buffer)} -----END ENCRYPTED PRIVATE KEY-----`}async decryptPrivateKey(i,e){if(!me)throw new Error("Crypto not available");let t=i.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----","").replace("-----END ENCRYPTED PRIVATE KEY-----","").replace(/\s/g,""),s=this.base64ToArrayBuffer(t),n=new Uint8Array(s),o=n.slice(0,16),r=n.slice(16,28),a=n.slice(28),m=new TextEncoder,p=await me.importKey("raw",m.encode(e),{name:"PBKDF2"},!1,["deriveKey"]),h=await me.deriveKey({name:"PBKDF2",salt:o,iterations:1e5,hash:"SHA-256"},p,{name:"AES-GCM",length:256},!1,["decrypt"]),v=await me.decrypt({name:"AES-GCM",iv:r},h,a);return new TextDecoder().decode(v)}async promptForPassword(i){return window.prompt(`Enter password for SSH key "${i}":`)}};Qi.DEFAULT_STORAGE_KEY="vibetunnel_ssh_keys";Yi=Qi});var Hr={};Rr(Hr,{AuthClient:()=>Xi,authClient:()=>K});var Se,nt,Xi,K,Me=ki(()=>{ye();q();Dr();Se=P("auth-client"),nt=class nt{constructor(){this.currentUser=null;this.sshAgent=new Yi,this.loadCurrentUser()}getSSHAgent(){return this.sshAgent}isAuthenticated(){return this.currentUser!==null&&this.isTokenValid()}getCurrentUser(){return this.currentUser}async getCurrentSystemUser(){try{let i=await fetch("/api/auth/current-user");if(i.ok)return(await i.json()).userId;throw new Error("Failed to get current user")}catch(i){throw Se.error("Failed to get current system user:",i),i}}async getUserAvatar(i){try{let r=await fetch(`/api/auth/avatar/${i}`);if(r.ok){let a=await r.json();if(a.avatar&&a.avatar.startsWith("data:"))return a.avatar}}catch(r){Se.error("Failed to get user avatar:",r)}let e=getComputedStyle(document.documentElement),t=e.getPropertyValue("--color-text-dim").trim().split(" ").map(r=>Number.parseInt(r)),s=e.getPropertyValue("--color-text-muted").trim().split(" ").map(r=>Number.parseInt(r)),n=`rgb(${t.join(", ")})`,o=`rgb(${s.join(", ")})`;return"data:image/svg+xml;base64,"+btoa(` <svg width="48" height="48" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg"> <circle cx="24" cy="24" r="24" fill="${n}"/> <circle cx="24" cy="18" r="8" fill="${o}"/> <path d="M8 38c0-8.837 7.163-16 16-16s16 7.163 16 16" fill="${o}"/> </svg> `)}async authenticateWithSSHKey(i,e){try{if(!this.sshAgent.isUnlocked())return{success:!1,error:"SSH agent is locked"};let t=await this.createChallenge(i),s=await this.sshAgent.sign(e,t.challenge),n=this.sshAgent.getPublicKey(e);if(!n)return{success:!1,error:"SSH key not found"};let r=await(await fetch("/api/auth/ssh-key",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({challengeId:t.challengeId,publicKey:n,signature:s.signature})})).json();return Se.log("\u{1F510} SSH key auth server response:",r),r.success?(Se.log("\u2705 SSH key auth successful, setting current user"),this.setCurrentUser({userId:r.userId,token:r.token,authMethod:"ssh-key",loginTime:Date.now()}),Se.log("\u{1F464} Current user set:",this.getCurrentUser())):Se.log("\u274C SSH key auth failed:",r.error),r}catch(t){return Se.error("SSH key authentication failed:",t),{success:!1,error:"SSH key authentication failed"}}}async authenticateWithPassword(i,e){try{let s=await(await fetch("/api/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({userId:i,password:e})})).json();return s.success&&this.setCurrentUser({userId:s.userId,token:s.token,authMethod:"password",loginTime:Date.now()}),s}catch(t){return Se.error("Password authentication failed:",t),{success:!1,error:"Password authentication failed"}}}async authenticate(i){if(Se.log("\u{1F680} Starting SSH authentication for user:",i),this.sshAgent.isUnlocked()){let e=this.sshAgent.listKeys();Se.log("\u{1F5DD}\uFE0F Found SSH keys:",e.length,e.map(t=>({id:t.id,name:t.name})));for(let t of e)try{Se.log(`\u{1F511} Trying SSH key: ${t.name} (${t.id})`);let s=await this.authenticateWithSSHKey(i,t.id);if(Se.log(`\u{1F3AF} SSH key ${t.name} result:`,s),s.success)return Se.log(`\u2705 Authenticated with SSH key: ${t.name}`),s}catch(s){Se.warn(`\u274C SSH key authentication failed for key ${t.name}:`,s)}}else Se.log("\u{1F512} SSH agent is locked");return{success:!1,error:"SSH key authentication failed. Password authentication required."}}async logout(){try{this.currentUser?.token&&await fetch("/api/auth/logout",{method:"POST",headers:{Authorization:`Bearer ${this.currentUser.token}`,"Content-Type":"application/json"}})}catch(i){Se.warn("Server logout failed:",i)}finally{this.clearCurrentUser()}}getAuthHeader(){return this.currentUser?.token?{Authorization:`Bearer ${this.currentUser.token}`}:{}}async fetch(i,e){let t={...this.getAuthHeader(),...e?.headers||{}};return fetch(i,{...e,headers:t})}async verifyToken(){if(!this.currentUser?.token)return!1;try{return(await(await fetch("/api/auth/verify",{headers:{Authorization:`Bearer ${this.currentUser.token}`}})).json()).valid}catch(i){return Se.error("Token verification failed:",i),!1}}async unlockSSHAgent(i){return!0}lockSSHAgent(){}isSSHAgentUnlocked(){return!0}async createChallenge(i){let e=await fetch("/api/auth/challenge",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({userId:i})});if(!e.ok)throw new Error("Failed to create authentication challenge");return e.json()}setCurrentUser(i){this.currentUser=i,this.saveCurrentUser()}clearCurrentUser(){this.currentUser=null,localStorage.removeItem(nt.TOKEN_KEY),localStorage.removeItem(nt.USER_KEY)}saveCurrentUser(){this.currentUser&&(localStorage.setItem(nt.TOKEN_KEY,this.currentUser.token),localStorage.setItem(nt.USER_KEY,JSON.stringify({userId:this.currentUser.userId,authMethod:this.currentUser.authMethod,loginTime:this.currentUser.loginTime})))}loadCurrentUser(){try{let i=localStorage.getItem(nt.TOKEN_KEY),e=localStorage.getItem(nt.USER_KEY);if(i&&e){let t=JSON.parse(e);this.currentUser={token:i,userId:t.userId,authMethod:t.authMethod,loginTime:t.loginTime},this.verifyToken().then(s=>{s||this.clearCurrentUser()})}}catch(i){Se.error("Failed to load current user:",i),this.clearCurrentUser()}}isTokenValid(){if(!this.currentUser)return!1;let i=Date.now()-this.currentUser.loginTime,e=1440*60*1e3;return i<e}};nt.TOKEN_KEY="vibetunnel_auth_token",nt.USER_KEY="vibetunnel_user_data";Xi=nt,K=new Xi});async function fo(){let c=Date.now();if(_i&&c-_i.timestamp<mo)return _i.noAuth;try{let i=await fetch("/api/auth/config");if(i.ok)return _i={noAuth:(await i.json()).noAuth===!0,timestamp:c},_i.noAuth}catch{}return!1}function go(c){return c.map(i=>{if(typeof i=="object"&&i!==null)try{return JSON.stringify(i,null,2)}catch{return String(i)}return i})}async function vo(c,i,e){try{let{authClient:t}=await Promise.resolve().then(()=>(Me(),Hr)),s=t.getAuthHeader(),n=await fo();if(!s.Authorization&&!n)return;let o={"Content-Type":"application/json"};s.Authorization&&(o.Authorization=s.Authorization),await fetch("/api/logs/client",{method:"POST",headers:o,body:JSON.stringify({level:c,module:i,args:go(e)})})}catch{}}function P(c){let i=e=>(...t)=>{e==="debug"&&!po||(console[e](`[${c}]`,...t),vo(e,c,t))};return{log:i("log"),warn:i("warn"),error:i("error"),debug:i("debug")}}var po,_i,mo,q=ki(()=>{ye();po=!1,_i=null,mo=6e4});var zn={};Rr(zn,{TerminalRenderer:()=>br,decodeBinaryBuffer:()=>On,renderLineFromBuffer:()=>Hn,renderLineFromCells:()=>Fn});function Dn(c){return c.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Hn(c,i,e=-1){let t="",s="",n="",o="",r=()=>{if(s){let a=Dn(s);t+=`<span class="${n}"${o?` style="${o}"`:""}>${a}</span>`,s=""}};for(let a=0;a<c.length;a++){if(c.getCell(a,i),!i)continue;let m=i.getChars()||" ";if(i.getWidth()===0)continue;let{classes:h,style:v}=jo(i,a===e);(h!==n||v!==o)&&(r(),n=h,o=v),s+=m}return r(),t}function Fn(c,i=-1){let e="",t="",s="",n="",o=()=>{if(t){let a=Dn(t);e+=`<span class="${s}"${n?` style="${n}"`:""}>${a}</span>`,t=""}},r=0;for(let a of c){if(a.width===0)continue;let{classes:m,style:p}=Go(a,r===i);(m!==s||p!==n)&&(o(),s=m,n=p),t+=a.char,r+=a.width}return o(),e||(e='<span class="terminal-char">&nbsp;</span>'),e}function jo(c,i){let e="terminal-char",t="";i&&(e+=" cursor");let s=c.getFgColor();if(s!==void 0){if(typeof s=="number"&&s>=0&&s<=255)t+=`color: var(--terminal-color-${s});`;else if(typeof s=="number"&&s>255){let o=s>>16&255,r=s>>8&255,a=s&255;t+=`color: rgb(${o}, ${r}, ${a});`}}let n=c.getBgColor();if(n!==void 0){if(typeof n=="number"&&n>=0&&n<=255)t+=`background-color: var(--terminal-color-${n});`;else if(typeof n=="number"&&n>255){let o=n>>16&255,r=n>>8&255,a=n&255;t+=`background-color: rgb(${o}, ${r}, ${a});`}}if(c.isBold()&&(e+=" bold"),c.isItalic()&&(e+=" italic"),c.isUnderline()&&(e+=" underline"),c.isDim()&&(e+=" dim"),c.isStrikethrough()&&(e+=" strikethrough"),c.isInverse()){let o=t.match(/color: ([^;]+);/)?.[1],r=t.match(/background-color: ([^;]+);/)?.[1];o&&r?(t=t.replace(/color: [^;]+;/,`color: ${r};`),t=t.replace(/background-color: [^;]+;/,`background-color: ${o};`)):o?(t=t.replace(/color: [^;]+;/,"color: #1e1e1e;"),t+=`background-color: ${o};`):t+="color: #1e1e1e; background-color: #d4d4d4;"}return c.isInvisible()&&(t+="opacity: 0;"),{classes:e,style:t}}function Go(c,i){let e="terminal-char",t="";if(i&&(e+=" cursor"),c.fg!==void 0)if(c.fg>=0&&c.fg<=255)t+=`color: var(--terminal-color-${c.fg});`;else{let n=c.fg>>16&255,o=c.fg>>8&255,r=c.fg&255;t+=`color: rgb(${n}, ${o}, ${r});`}else t+="color: #d4d4d4;";if(c.bg!==void 0)if(c.bg>=0&&c.bg<=255)t+=`background-color: var(--terminal-color-${c.bg});`;else{let n=c.bg>>16&255,o=c.bg>>8&255,r=c.bg&255;t+=`background-color: rgb(${n}, ${o}, ${r});`}let s=c.attributes||0;if(s&1&&(e+=" bold"),s&2&&(e+=" italic"),s&4&&(e+=" underline"),s&8&&(e+=" dim"),s&64&&(e+=" strikethrough"),s&16){let n=t.match(/color: ([^;]+);/)?.[1],o=t.match(/background-color: ([^;]+);/)?.[1];n&&o?(t=t.replace(/color: [^;]+;/,`color: ${o};`),t=t.replace(/background-color: [^;]+;/,`background-color: ${n};`)):n?(t=t.replace(/color: [^;]+;/,"color: #1e1e1e;"),t+=`background-color: ${n};`):t+="color: #1e1e1e; background-color: #d4d4d4;"}return s&32&&(t+="opacity: 0;"),{classes:e,style:t}}function On(c){let i=new DataView(c),e=0,t=i.getUint16(e,!0);if(e+=2,t!==22100)throw new Error("Invalid buffer format");let s=i.getUint8(e++);if(s!==1)throw new Error(`Unsupported buffer version: ${s}`);let n=i.getUint8(e++),o=i.getUint32(e,!0);e+=4;let r=i.getUint32(e,!0);e+=4;let a=i.getInt32(e,!0);e+=4;let m=i.getInt32(e,!0);e+=4;let p=i.getInt32(e,!0);e+=4,e+=4;let h=[],v=new Uint8Array(c);for(;e<v.length;){let f=v[e++];if(f===254){let w=v[e++];for(let x=0;x<w;x++)h.push([{char:" ",width:1}])}else if(f===253){let w=i.getUint16(e,!0);e+=2;let x=[];for(let l=0;l<w;l++){let g=Yo(v,e);e=g.offset,x.push(g.cell)}h.push(x)}}return{cols:o,rows:r,viewportY:a,cursorX:m,cursorY:p,cells:h}}function Yo(c,i){let e=c[i++],t=!!(e&128),s=!!(e&64),n=!!(e&32),o=!!(e&16),r=!!(e&8),a=!!(e&4),m=e&3;if(e===0)return{cell:{char:" ",width:1},offset:i};let p;if(m===0)p=" ";else if(s){let v=c[i++],f=c.slice(i,i+v);p=new TextDecoder().decode(f),i+=v}else p=String.fromCharCode(c[i++]);let h={char:p,width:1};if(t){let v=c[i++];v!==0&&(h.attributes=v),n&&(r?(h.fg=c[i]<<16|c[i+1]<<8|c[i+2],i+=3):h.fg=c[i++]),o&&(a?(h.bg=c[i]<<16|c[i+1]<<8|c[i+2],i+=3):h.bg=c[i++])}return{cell:h,offset:i}}var br,yr=ki(()=>{br={renderLineFromBuffer:Hn,renderLineFromCells:Fn,decodeBinaryBuffer:On}});var Yn=co(Gn=>{(()=>{"use strict";var c={349:(o,r,a)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.CircularList=void 0;let m=a(460),p=a(844);class h extends p.Disposable{constructor(f){super(),this._maxLength=f,this.onDeleteEmitter=this.register(new m.EventEmitter),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this.register(new m.EventEmitter),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this.register(new m.EventEmitter),this.onTrim=this.onTrimEmitter.event,this._array=new Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(f){if(this._maxLength===f)return;let w=new Array(f);for(let x=0;x<Math.min(f,this.length);x++)w[x]=this._array[this._getCyclicIndex(x)];this._array=w,this._maxLength=f,this._startIndex=0}get length(){return this._length}set length(f){if(f>this._length)for(let w=this._length;w<f;w++)this._array[w]=void 0;this._length=f}get(f){return this._array[this._getCyclicIndex(f)]}set(f,w){this._array[this._getCyclicIndex(f)]=w}push(f){this._array[this._getCyclicIndex(this._length)]=f,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++}recycle(){if(this._length!==this._maxLength)throw new Error("Can only recycle when the buffer is full");return this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1),this._array[this._getCyclicIndex(this._length-1)]}get isFull(){return this._length===this._maxLength}pop(){return this._array[this._getCyclicIndex(this._length---1)]}splice(f,w,...x){if(w){for(let l=f;l<this._length-w;l++)this._array[this._getCyclicIndex(l)]=this._array[this._getCyclicIndex(l+w)];this._length-=w,this.onDeleteEmitter.fire({index:f,amount:w})}for(let l=this._length-1;l>=f;l--)this._array[this._getCyclicIndex(l+x.length)]=this._array[this._getCyclicIndex(l)];for(let l=0;l<x.length;l++)this._array[this._getCyclicIndex(f+l)]=x[l];if(x.length&&this.onInsertEmitter.fire({index:f,amount:x.length}),this._length+x.length>this._maxLength){let l=this._length+x.length-this._maxLength;this._startIndex+=l,this._length=this._maxLength,this.onTrimEmitter.fire(l)}else this._length+=x.length}trimStart(f){f>this._length&&(f=this._length),this._startIndex+=f,this._length-=f,this.onTrimEmitter.fire(f)}shiftElements(f,w,x){if(!(w<=0)){if(f<0||f>=this._length)throw new Error("start argument out of range");if(f+x<0)throw new Error("Cannot shift elements in list beyond index 0");if(x>0){for(let g=w-1;g>=0;g--)this.set(f+g+x,this.get(f+g));let l=f+w+x-this._length;if(l>0)for(this._length+=l;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let l=0;l<w;l++)this.set(f+l+x,this.get(f+l))}}_getCyclicIndex(f){return(this._startIndex+f)%this._maxLength}}r.CircularList=h},439:(o,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.clone=void 0,r.clone=function a(m,p=5){if(typeof m!="object")return m;let h=Array.isArray(m)?[]:{};for(let v in m)h[v]=p<=1?m[v]:m[v]&&a(m[v],p-1);return h}},969:(o,r,a)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.CoreTerminal=void 0;let m=a(844),p=a(585),h=a(348),v=a(866),f=a(744),w=a(302),x=a(83),l=a(460),g=a(753),y=a(480),b=a(994),k=a(282),E=a(435),A=a(981),B=a(660),L=!1;class N extends m.Disposable{get onScroll(){return this._onScrollApi||(this._onScrollApi=this.register(new l.EventEmitter),this._onScroll.event(O=>{this._onScrollApi?.fire(O.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(O){for(let F in O)this.optionsService.options[F]=O[F]}constructor(O){super(),this._windowsWrappingHeuristics=this.register(new m.MutableDisposable),this._onBinary=this.register(new l.EventEmitter),this.onBinary=this._onBinary.event,this._onData=this.register(new l.EventEmitter),this.onData=this._onData.event,this._onLineFeed=this.register(new l.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onResize=this.register(new l.EventEmitter),this.onResize=this._onResize.event,this._onWriteParsed=this.register(new l.EventEmitter),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this.register(new l.EventEmitter),this._instantiationService=new h.InstantiationService,this.optionsService=this.register(new w.OptionsService(O)),this._instantiationService.setService(p.IOptionsService,this.optionsService),this._bufferService=this.register(this._instantiationService.createInstance(f.BufferService)),this._instantiationService.setService(p.IBufferService,this._bufferService),this._logService=this.register(this._instantiationService.createInstance(v.LogService)),this._instantiationService.setService(p.ILogService,this._logService),this.coreService=this.register(this._instantiationService.createInstance(x.CoreService)),this._instantiationService.setService(p.ICoreService,this.coreService),this.coreMouseService=this.register(this._instantiationService.createInstance(g.CoreMouseService)),this._instantiationService.setService(p.ICoreMouseService,this.coreMouseService),this.unicodeService=this.register(this._instantiationService.createInstance(y.UnicodeService)),this._instantiationService.setService(p.IUnicodeService,this.unicodeService),this._charsetService=this._instantiationService.createInstance(b.CharsetService),this._instantiationService.setService(p.ICharsetService,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(B.OscLinkService),this._instantiationService.setService(p.IOscLinkService,this._oscLinkService),this._inputHandler=this.register(new E.InputHandler(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this.register((0,l.forwardEvent)(this._inputHandler.onLineFeed,this._onLineFeed)),this.register(this._inputHandler),this.register((0,l.forwardEvent)(this._bufferService.onResize,this._onResize)),this.register((0,l.forwardEvent)(this.coreService.onData,this._onData)),this.register((0,l.forwardEvent)(this.coreService.onBinary,this._onBinary)),this.register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom())),this.register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this.register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],()=>this._handleWindowsPtyOptionChange())),this.register(this._bufferService.onScroll(F=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp,source:0}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this.register(this._inputHandler.onScroll(F=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp,source:0}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this.register(new A.WriteBuffer((F,U)=>this._inputHandler.parse(F,U))),this.register((0,l.forwardEvent)(this._writeBuffer.onWriteParsed,this._onWriteParsed))}write(O,F){this._writeBuffer.write(O,F)}writeSync(O,F){this._logService.logLevel<=p.LogLevelEnum.WARN&&!L&&(this._logService.warn("writeSync is unreliable and will be removed soon."),L=!0),this._writeBuffer.writeSync(O,F)}input(O,F=!0){this.coreService.triggerDataEvent(O,F)}resize(O,F){isNaN(O)||isNaN(F)||(O=Math.max(O,f.MINIMUM_COLS),F=Math.max(F,f.MINIMUM_ROWS),this._bufferService.resize(O,F))}scroll(O,F=!1){this._bufferService.scroll(O,F)}scrollLines(O,F,U){this._bufferService.scrollLines(O,F,U)}scrollPages(O){this.scrollLines(O*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(O){let F=O-this._bufferService.buffer.ydisp;F!==0&&this.scrollLines(F)}registerEscHandler(O,F){return this._inputHandler.registerEscHandler(O,F)}registerDcsHandler(O,F){return this._inputHandler.registerDcsHandler(O,F)}registerCsiHandler(O,F){return this._inputHandler.registerCsiHandler(O,F)}registerOscHandler(O,F){return this._inputHandler.registerOscHandler(O,F)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let O=!1,F=this.optionsService.rawOptions.windowsPty;F&&F.buildNumber!==void 0&&F.buildNumber!==void 0?O=F.backend==="conpty"&&F.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(O=!0),O?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let O=[];O.push(this.onLineFeed(k.updateWindowsModeWrappedState.bind(null,this._bufferService))),O.push(this.registerCsiHandler({final:"H"},()=>((0,k.updateWindowsModeWrappedState)(this._bufferService),!1))),this._windowsWrappingHeuristics.value=(0,m.toDisposable)(()=>{for(let F of O)F.dispose()})}}}r.CoreTerminal=N},460:(o,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.runAndSubscribe=r.forwardEvent=r.EventEmitter=void 0,r.EventEmitter=class{constructor(){this._listeners=[],this._disposed=!1}get event(){return this._event||(this._event=a=>(this._listeners.push(a),{dispose:()=>{if(!this._disposed){for(let p=0;p<this._listeners.length;p++)if(this._listeners[p]===a)return void this._listeners.splice(p,1)}}})),this._event}fire(a,m){let p=[];for(let h=0;h<this._listeners.length;h++)p.push(this._listeners[h]);for(let h=0;h<p.length;h++)p[h].call(void 0,a,m)}dispose(){this.clearListeners(),this._disposed=!0}clearListeners(){this._listeners&&(this._listeners.length=0)}},r.forwardEvent=function(a,m){return a(p=>m.fire(p))},r.runAndSubscribe=function(a,m){return m(void 0),a(p=>m(p))}},435:function(o,r,a){var m=this&&this.__decorate||function(Z,S,$,T){var I,z=arguments.length,Y=z<3?S:T===null?T=Object.getOwnPropertyDescriptor(S,$):T;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")Y=Reflect.decorate(Z,S,$,T);else for(var oe=Z.length-1;oe>=0;oe--)(I=Z[oe])&&(Y=(z<3?I(Y):z>3?I(S,$,Y):I(S,$))||Y);return z>3&&Y&&Object.defineProperty(S,$,Y),Y},p=this&&this.__param||function(Z,S){return function($,T){S($,T,Z)}};Object.defineProperty(r,"__esModule",{value:!0}),r.InputHandler=r.WindowsOptionsReportType=void 0;let h=a(584),v=a(116),f=a(15),w=a(844),x=a(482),l=a(437),g=a(460),y=a(643),b=a(511),k=a(734),E=a(585),A=a(480),B=a(242),L=a(351),N=a(941),he={"(":0,")":1,"*":2,"+":3,"-":1,".":2},O=131072;function F(Z,S){if(Z>24)return S.setWinLines||!1;switch(Z){case 1:return!!S.restoreWin;case 2:return!!S.minimizeWin;case 3:return!!S.setWinPosition;case 4:return!!S.setWinSizePixels;case 5:return!!S.raiseWin;case 6:return!!S.lowerWin;case 7:return!!S.refreshWin;case 8:return!!S.setWinSizeChars;case 9:return!!S.maximizeWin;case 10:return!!S.fullscreenWin;case 11:return!!S.getWinState;case 13:return!!S.getWinPosition;case 14:return!!S.getWinSizePixels;case 15:return!!S.getScreenSizePixels;case 16:return!!S.getCellSizePixels;case 18:return!!S.getWinSizeChars;case 19:return!!S.getScreenSizeChars;case 20:return!!S.getIconTitle;case 21:return!!S.getWinTitle;case 22:return!!S.pushTitle;case 23:return!!S.popTitle;case 24:return!!S.setWinLines}return!1}var U;(function(Z){Z[Z.GET_WIN_SIZE_PIXELS=0]="GET_WIN_SIZE_PIXELS",Z[Z.GET_CELL_SIZE_PIXELS=1]="GET_CELL_SIZE_PIXELS"})(U||(r.WindowsOptionsReportType=U={}));let rt=0;class Xe extends w.Disposable{getAttrData(){return this._curAttrData}constructor(S,$,T,I,z,Y,oe,de,Je=new f.EscapeSequenceParser){super(),this._bufferService=S,this._charsetService=$,this._coreService=T,this._logService=I,this._optionsService=z,this._oscLinkService=Y,this._coreMouseService=oe,this._unicodeService=de,this._parser=Je,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new x.StringToUtf32,this._utf8Decoder=new x.Utf8ToUtf32,this._workCell=new b.CellData,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=l.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=l.DEFAULT_ATTR_DATA.clone(),this._onRequestBell=this.register(new g.EventEmitter),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this.register(new g.EventEmitter),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this.register(new g.EventEmitter),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this.register(new g.EventEmitter),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this.register(new g.EventEmitter),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this.register(new g.EventEmitter),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this.register(new g.EventEmitter),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this.register(new g.EventEmitter),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this.register(new g.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this.register(new g.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onScroll=this.register(new g.EventEmitter),this.onScroll=this._onScroll.event,this._onTitleChange=this.register(new g.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onColor=this.register(new g.EventEmitter),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this.register(this._parser),this._dirtyRowTracker=new re(this._bufferService),this._activeBuffer=this._bufferService.buffer,this.register(this._bufferService.buffers.onBufferActivate(M=>this._activeBuffer=M.activeBuffer)),this._parser.setCsiHandlerFallback((M,ne)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(M),params:ne.toArray()})}),this._parser.setEscHandlerFallback(M=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(M)})}),this._parser.setExecuteHandlerFallback(M=>{this._logService.debug("Unknown EXECUTE code: ",{code:M})}),this._parser.setOscHandlerFallback((M,ne,V)=>{this._logService.debug("Unknown OSC code: ",{identifier:M,action:ne,data:V})}),this._parser.setDcsHandlerFallback((M,ne,V)=>{ne==="HOOK"&&(V=V.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(M),action:ne,payload:V})}),this._parser.setPrintHandler((M,ne,V)=>this.print(M,ne,V)),this._parser.registerCsiHandler({final:"@"},M=>this.insertChars(M)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},M=>this.scrollLeft(M)),this._parser.registerCsiHandler({final:"A"},M=>this.cursorUp(M)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},M=>this.scrollRight(M)),this._parser.registerCsiHandler({final:"B"},M=>this.cursorDown(M)),this._parser.registerCsiHandler({final:"C"},M=>this.cursorForward(M)),this._parser.registerCsiHandler({final:"D"},M=>this.cursorBackward(M)),this._parser.registerCsiHandler({final:"E"},M=>this.cursorNextLine(M)),this._parser.registerCsiHandler({final:"F"},M=>this.cursorPrecedingLine(M)),this._parser.registerCsiHandler({final:"G"},M=>this.cursorCharAbsolute(M)),this._parser.registerCsiHandler({final:"H"},M=>this.cursorPosition(M)),this._parser.registerCsiHandler({final:"I"},M=>this.cursorForwardTab(M)),this._parser.registerCsiHandler({final:"J"},M=>this.eraseInDisplay(M,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},M=>this.eraseInDisplay(M,!0)),this._parser.registerCsiHandler({final:"K"},M=>this.eraseInLine(M,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},M=>this.eraseInLine(M,!0)),this._parser.registerCsiHandler({final:"L"},M=>this.insertLines(M)),this._parser.registerCsiHandler({final:"M"},M=>this.deleteLines(M)),this._parser.registerCsiHandler({final:"P"},M=>this.deleteChars(M)),this._parser.registerCsiHandler({final:"S"},M=>this.scrollUp(M)),this._parser.registerCsiHandler({final:"T"},M=>this.scrollDown(M)),this._parser.registerCsiHandler({final:"X"},M=>this.eraseChars(M)),this._parser.registerCsiHandler({final:"Z"},M=>this.cursorBackwardTab(M)),this._parser.registerCsiHandler({final:"`"},M=>this.charPosAbsolute(M)),this._parser.registerCsiHandler({final:"a"},M=>this.hPositionRelative(M)),this._parser.registerCsiHandler({final:"b"},M=>this.repeatPrecedingCharacter(M)),this._parser.registerCsiHandler({final:"c"},M=>this.sendDeviceAttributesPrimary(M)),this._parser.registerCsiHandler({prefix:">",final:"c"},M=>this.sendDeviceAttributesSecondary(M)),this._parser.registerCsiHandler({final:"d"},M=>this.linePosAbsolute(M)),this._parser.registerCsiHandler({final:"e"},M=>this.vPositionRelative(M)),this._parser.registerCsiHandler({final:"f"},M=>this.hVPosition(M)),this._parser.registerCsiHandler({final:"g"},M=>this.tabClear(M)),this._parser.registerCsiHandler({final:"h"},M=>this.setMode(M)),this._parser.registerCsiHandler({prefix:"?",final:"h"},M=>this.setModePrivate(M)),this._parser.registerCsiHandler({final:"l"},M=>this.resetMode(M)),this._parser.registerCsiHandler({prefix:"?",final:"l"},M=>this.resetModePrivate(M)),this._parser.registerCsiHandler({final:"m"},M=>this.charAttributes(M)),this._parser.registerCsiHandler({final:"n"},M=>this.deviceStatus(M)),this._parser.registerCsiHandler({prefix:"?",final:"n"},M=>this.deviceStatusPrivate(M)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},M=>this.softReset(M)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},M=>this.setCursorStyle(M)),this._parser.registerCsiHandler({final:"r"},M=>this.setScrollRegion(M)),this._parser.registerCsiHandler({final:"s"},M=>this.saveCursor(M)),this._parser.registerCsiHandler({final:"t"},M=>this.windowOptions(M)),this._parser.registerCsiHandler({final:"u"},M=>this.restoreCursor(M)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},M=>this.insertColumns(M)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},M=>this.deleteColumns(M)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},M=>this.selectProtected(M)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},M=>this.requestMode(M,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},M=>this.requestMode(M,!1)),this._parser.setExecuteHandler(h.C0.BEL,()=>this.bell()),this._parser.setExecuteHandler(h.C0.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(h.C0.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(h.C0.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(h.C0.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(h.C0.BS,()=>this.backspace()),this._parser.setExecuteHandler(h.C0.HT,()=>this.tab()),this._parser.setExecuteHandler(h.C0.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(h.C0.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(h.C1.IND,()=>this.index()),this._parser.setExecuteHandler(h.C1.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(h.C1.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new B.OscHandler(M=>(this.setTitle(M),this.setIconName(M),!0))),this._parser.registerOscHandler(1,new B.OscHandler(M=>this.setIconName(M))),this._parser.registerOscHandler(2,new B.OscHandler(M=>this.setTitle(M))),this._parser.registerOscHandler(4,new B.OscHandler(M=>this.setOrReportIndexedColor(M))),this._parser.registerOscHandler(8,new B.OscHandler(M=>this.setHyperlink(M))),this._parser.registerOscHandler(10,new B.OscHandler(M=>this.setOrReportFgColor(M))),this._parser.registerOscHandler(11,new B.OscHandler(M=>this.setOrReportBgColor(M))),this._parser.registerOscHandler(12,new B.OscHandler(M=>this.setOrReportCursorColor(M))),this._parser.registerOscHandler(104,new B.OscHandler(M=>this.restoreIndexedColor(M))),this._parser.registerOscHandler(110,new B.OscHandler(M=>this.restoreFgColor(M))),this._parser.registerOscHandler(111,new B.OscHandler(M=>this.restoreBgColor(M))),this._parser.registerOscHandler(112,new B.OscHandler(M=>this.restoreCursorColor(M))),this._parser.registerEscHandler({final:"7"},()=>this.saveCursor()),this._parser.registerEscHandler({final:"8"},()=>this.restoreCursor()),this._parser.registerEscHandler({final:"D"},()=>this.index()),this._parser.registerEscHandler({final:"E"},()=>this.nextLine()),this._parser.registerEscHandler({final:"H"},()=>this.tabSet()),this._parser.registerEscHandler({final:"M"},()=>this.reverseIndex()),this._parser.registerEscHandler({final:"="},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:">"},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:"c"},()=>this.fullReset()),this._parser.registerEscHandler({final:"n"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"o"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"|"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"}"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"~"},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:"%",final:"@"},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:"%",final:"G"},()=>this.selectDefaultCharset());for(let M in v.CHARSETS)this._parser.registerEscHandler({intermediates:"(",final:M},()=>this.selectCharset("("+M)),this._parser.registerEscHandler({intermediates:")",final:M},()=>this.selectCharset(")"+M)),this._parser.registerEscHandler({intermediates:"*",final:M},()=>this.selectCharset("*"+M)),this._parser.registerEscHandler({intermediates:"+",final:M},()=>this.selectCharset("+"+M)),this._parser.registerEscHandler({intermediates:"-",final:M},()=>this.selectCharset("-"+M)),this._parser.registerEscHandler({intermediates:".",final:M},()=>this.selectCharset("."+M)),this._parser.registerEscHandler({intermediates:"/",final:M},()=>this.selectCharset("/"+M));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(M=>(this._logService.error("Parsing error: ",M),M)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new L.DcsHandler((M,ne)=>this.requestStatusString(M,ne)))}_preserveStack(S,$,T,I){this._parseStack.paused=!0,this._parseStack.cursorStartX=S,this._parseStack.cursorStartY=$,this._parseStack.decodedLength=T,this._parseStack.position=I}_logSlowResolvingAsync(S){this._logService.logLevel<=E.LogLevelEnum.WARN&&Promise.race([S,new Promise(($,T)=>setTimeout(()=>T("#SLOW_TIMEOUT"),5e3))]).catch($=>{if($!=="#SLOW_TIMEOUT")throw $;console.warn("async parser handler taking longer than 5000 ms")})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(S,$){let T,I=this._activeBuffer.x,z=this._activeBuffer.y,Y=0,oe=this._parseStack.paused;if(oe){if(T=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,$))return this._logSlowResolvingAsync(T),T;I=this._parseStack.cursorStartX,z=this._parseStack.cursorStartY,this._parseStack.paused=!1,S.length>O&&(Y=this._parseStack.position+O)}if(this._logService.logLevel<=E.LogLevelEnum.DEBUG&&this._logService.debug("parsing data"+(typeof S=="string"?` "${S}"`:` "${Array.prototype.map.call(S,M=>String.fromCharCode(M)).join("")}"`),typeof S=="string"?S.split("").map(M=>M.charCodeAt(0)):S),this._parseBuffer.length<S.length&&this._parseBuffer.length<O&&(this._parseBuffer=new Uint32Array(Math.min(S.length,O))),oe||this._dirtyRowTracker.clearRange(),S.length>O)for(let M=Y;M<S.length;M+=O){let ne=M+O<S.length?M+O:S.length,V=typeof S=="string"?this._stringDecoder.decode(S.substring(M,ne),this._parseBuffer):this._utf8Decoder.decode(S.subarray(M,ne),this._parseBuffer);if(T=this._parser.parse(this._parseBuffer,V))return this._preserveStack(I,z,V,M),this._logSlowResolvingAsync(T),T}else if(!oe){let M=typeof S=="string"?this._stringDecoder.decode(S,this._parseBuffer):this._utf8Decoder.decode(S,this._parseBuffer);if(T=this._parser.parse(this._parseBuffer,M))return this._preserveStack(I,z,M,0),this._logSlowResolvingAsync(T),T}this._activeBuffer.x===I&&this._activeBuffer.y===z||this._onCursorMove.fire();let de=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),Je=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);Je<this._bufferService.rows&&this._onRequestRefreshRows.fire(Math.min(Je,this._bufferService.rows-1),Math.min(de,this._bufferService.rows-1))}print(S,$,T){let I,z,Y=this._charsetService.charset,oe=this._optionsService.rawOptions.screenReaderMode,de=this._bufferService.cols,Je=this._coreService.decPrivateModes.wraparound,M=this._coreService.modes.insertMode,ne=this._curAttrData,V=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&T-$>0&&V.getWidth(this._activeBuffer.x-1)===2&&V.setCellFromCodepoint(this._activeBuffer.x-1,0,1,ne);let ee=this._parser.precedingJoinState;for(let oi=$;oi<T;++oi){if(I=S[oi],I<127&&Y){let Ot=Y[String.fromCharCode(I)];Ot&&(I=Ot.charCodeAt(0))}let ai=this._unicodeService.charProperties(I,ee);z=A.UnicodeService.extractWidth(ai);let ji=A.UnicodeService.extractShouldJoin(ai),Ft=ji?A.UnicodeService.extractWidth(ee):0;if(ee=ai,oe&&this._onA11yChar.fire((0,x.stringFromCodePoint)(I)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+z-Ft>de){if(Je){let Ot=V,Ci=this._activeBuffer.x-Ft;for(this._activeBuffer.x=Ft,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),V=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),Ft>0&&V instanceof l.BufferLine&&V.copyCellsFrom(Ot,Ci,0,Ft,!1);Ci<de;)Ot.setCellFromCodepoint(Ci++,0,1,ne)}else if(this._activeBuffer.x=de-1,z===2)continue}if(ji&&this._activeBuffer.x){let Ot=V.getWidth(this._activeBuffer.x-1)?1:2;V.addCodepointToCell(this._activeBuffer.x-Ot,I,z);for(let Ci=z-Ft;--Ci>=0;)V.setCellFromCodepoint(this._activeBuffer.x++,0,0,ne)}else if(M&&(V.insertCells(this._activeBuffer.x,z-Ft,this._activeBuffer.getNullCell(ne)),V.getWidth(de-1)===2&&V.setCellFromCodepoint(de-1,y.NULL_CELL_CODE,y.NULL_CELL_WIDTH,ne)),V.setCellFromCodepoint(this._activeBuffer.x++,I,z,ne),z>0)for(;--z;)V.setCellFromCodepoint(this._activeBuffer.x++,0,0,ne)}this._parser.precedingJoinState=ee,this._activeBuffer.x<de&&T-$>0&&V.getWidth(this._activeBuffer.x)===0&&!V.hasContent(this._activeBuffer.x)&&V.setCellFromCodepoint(this._activeBuffer.x,0,1,ne),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(S,$){return S.final!=="t"||S.prefix||S.intermediates?this._parser.registerCsiHandler(S,$):this._parser.registerCsiHandler(S,T=>!F(T.params[0],this._optionsService.rawOptions.windowOptions)||$(T))}registerDcsHandler(S,$){return this._parser.registerDcsHandler(S,new L.DcsHandler($))}registerEscHandler(S,$){return this._parser.registerEscHandler(S,$)}registerOscHandler(S,$){return this._parser.registerOscHandler(S,new B.OscHandler($))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let S=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);S.hasWidth(this._activeBuffer.x)&&!S.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let S=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-S),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(S=this._bufferService.cols-1){this._activeBuffer.x=Math.min(S,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(S,$){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=S,this._activeBuffer.y=this._activeBuffer.scrollTop+$):(this._activeBuffer.x=S,this._activeBuffer.y=$),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(S,$){this._restrictCursor(),this._setCursor(this._activeBuffer.x+S,this._activeBuffer.y+$)}cursorUp(S){let $=this._activeBuffer.y-this._activeBuffer.scrollTop;return $>=0?this._moveCursor(0,-Math.min($,S.params[0]||1)):this._moveCursor(0,-(S.params[0]||1)),!0}cursorDown(S){let $=this._activeBuffer.scrollBottom-this.