/**
 * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved.
 * @license MIT
 *
 * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
 * @license MIT
 *
 * Originally forked from (with the author's permission):
 *   Fabrice Bellard's javascript vt100 for jslinux:
 *   http://bellard.org/jslinux/
 *   Copyright (c) 2011 Fabrice Bellard
 */
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var it=Object.create;var Te=Object.defineProperty;var At=Object.getOwnPropertyDescriptor;var rt=Object.getOwnPropertyNames;var st=Object.getPrototypeOf,nt=Object.prototype.hasOwnProperty;var T=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports);var at=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let A of rt(e))!nt.call(s,A)&&A!==t&&Te(s,A,{get:()=>e[A],enumerable:!(i=At(e,A))||i.enumerable});return s};var x=(s,e,t)=>(t=s!=null?it(st(s)):{},at(e||!s||!s.__esModule?Te(t,"default",{value:s,enumerable:!0}):t,s));var z=T(m=>{"use strict";Object.defineProperty(m,"__esModule",{value:!0});m.DEFAULT_FOREGROUND=m.DEFAULT_BACKGROUND=m.PALETTE_ANSI_256=m.PALETTE_VT340_GREY=m.PALETTE_VT340_COLOR=m.normalizeHLS=m.normalizeRGB=m.nearestColorIndex=m.fromRGBA8888=m.toRGBA8888=m.alpha=m.blue=m.green=m.red=m.BIG_ENDIAN=void 0;m.BIG_ENDIAN=new Uint8Array(new Uint32Array([4278190080]).buffer)[0]===255;m.BIG_ENDIAN&&console.warn("BE platform detected. This version of node-sixel works only on LE properly.");function xe(s){return s&255}m.red=xe;function Me(s){return s>>>8&255}m.green=Me;function ve(s){return s>>>16&255}m.blue=ve;function ht(s){return s>>>24&255}m.alpha=ht;function B(s,e,t,i=255){return((i&255)<<24|(t&255)<<16|(e&255)<<8|s&255)>>>0}m.toRGBA8888=B;function dt(s){return[s&255,s>>8&255,s>>16&255,s>>>24]}m.fromRGBA8888=dt;function It(s,e){let t=xe(s),i=Me(s),A=ve(s),r=Number.MAX_SAFE_INTEGER,a=-1;for(let n=0;n<e.length;++n){let o=t-e[n][0],d=i-e[n][1],h=A-e[n][2],g=o*o+d*d+h*h;if(!g)return n;g<r&&(r=g,a=n)}return a}m.nearestColorIndex=It;function de(s,e,t){return Math.max(s,Math.min(t,e))}function Ie(s,e,t){return t<0&&(t+=1),t>1&&(t-=1),t*6<1?e+(s-e)*6*t:t*2<1?s:t*3<2?e+(s-e)*(4-t*6):e}function gt(s,e,t){if(!t){let r=Math.round(e*255);return B(r,r,r)}let i=e<.5?e*(1+t):e+t-e*t,A=2*e-i;return B(de(0,255,Math.round(Ie(i,A,s+1/3)*255)),de(0,255,Math.round(Ie(i,A,s)*255)),de(0,255,Math.round(Ie(i,A,s-1/3)*255)))}function c(s,e,t){return(4278190080|Math.round(t/100*255)<<16|Math.round(e/100*255)<<8|Math.round(s/100*255))>>>0}m.normalizeRGB=c;function lt(s,e,t){return gt((s+240%360)/360,e/100,t/100)}m.normalizeHLS=lt;m.PALETTE_VT340_COLOR=new Uint32Array([c(0,0,0),c(20,20,80),c(80,13,13),c(20,80,20),c(80,20,80),c(20,80,80),c(80,80,20),c(53,53,53),c(26,26,26),c(33,33,60),c(60,26,26),c(33,60,33),c(60,33,60),c(33,60,60),c(60,60,33),c(80,80,80)]);m.PALETTE_VT340_GREY=new Uint32Array([c(0,0,0),c(13,13,13),c(26,26,26),c(40,40,40),c(6,6,6),c(20,20,20),c(33,33,33),c(46,46,46),c(0,0,0),c(13,13,13),c(26,26,26),c(40,40,40),c(6,6,6),c(20,20,20),c(33,33,33),c(46,46,46)]);m.PALETTE_ANSI_256=(()=>{let s=[B(0,0,0),B(205,0,0),B(0,205,0),B(205,205,0),B(0,0,238),B(205,0,205),B(0,250,205),B(229,229,229),B(127,127,127),B(255,0,0),B(0,255,0),B(255,255,0),B(92,92,255),B(255,0,255),B(0,255,255),B(255,255,255)],e=[0,95,135,175,215,255];for(let t=0;t<6;++t)for(let i=0;i<6;++i)for(let A=0;A<6;++A)s.push(B(e[t],e[i],e[A]));for(let t=8;t<=238;t+=10)s.push(B(t,t,t));return new Uint32Array(s)})();m.DEFAULT_BACKGROUND=B(0,0,0,255);m.DEFAULT_FOREGROUND=B(255,255,255,255)});var ce=T(le=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.InWasm=Ct;var M=s=>{if(Uint8Array.fromBase64)return Uint8Array.fromBase64(s);if(typeof Buffer<"u")return Buffer.from(s,"base64");let e=atob(s),t=new Uint8Array(e.length);for(let i=0;i<t.length;++i)t[i]=e.charCodeAt(i);return t};function Ct(s){if(s.d){let{t:e,s:t,d:i}=s,A,r,a=WebAssembly;return e===0?t?n=>new a.Instance(r||(r=new a.Module(A||(A=M(i)))),n):n=>r?a.instantiate(r,n):a.instantiate(A||(A=M(i)),n).then(o=>(r=o.module)&&o.instance):e===1?t?()=>r||(r=new a.Module(A||(A=M(i)))):()=>r?Promise.resolve(r):a.compile(A||(A=M(i))).then(n=>r=n):t?()=>A||(A=M(i)):()=>Promise.resolve(A||(A=M(i)))}if(typeof _wasmCtx>"u")throw new Error('must run "inwasm"');_wasmCtx.add(s)}});var Ee=T(_e=>{"use strict";Object.defineProperty(_e,"__esModule",{value:!0});var pt=ce(),Bt=(0,pt.InWasm)({s:1,t:0,d:"AGFzbQEAAAABBQFgAAF/Ag8BA2VudgZtZW1vcnkCAAEDAwIAAAcNAgNkZWMAAANlbmQAAQqLBgKZBAEKf0GIKCgCAEGgKGohAUGEKCgCACIDQaAoaiEAQYAoKAIAQQFrQXxxIgRBoChqIQUgBEEQayADSgRAIARBkChqIQMDQCABIABBA2otAABBAnQoAoAgIABBAmotAABBAnQoAoAYIABBAWotAABBAnQoAoAQIAAtAABBAnQoAoAIcnJyIgY2AgAgAUEDaiAAQQdqLQAAQQJ0KAKAICAAQQZqLQAAQQJ0KAKAGCAAQQVqLQAAQQJ0KAKAECAAQQRqLQAAQQJ0KAKACHJyciIHNgIAIAFBBmogAEELai0AAEECdCgCgCAgAEEKai0AAEECdCgCgBggAEEJai0AAEECdCgCgBAgAEEIai0AAEECdCgCgAhycnIiCDYCACABQQlqIABBD2otAABBAnQoAoAgIABBDmotAABBAnQoAoAYIABBDWotAABBAnQoAoAQIABBDGotAABBAnQoAoAIcnJyIgk2AgAgAiAGciAHciAIciAJciECIAFBDGohASAAQRBqIgAgA0kNAAsLIAAgBUkEQANAIAEgAEEDai0AAEECdCgCgCAgAEECai0AAEECdCgCgBggAEEBai0AAEECdCgCgBAgAC0AAEECdCgCgAhycnIiAzYCACACIANyIQIgAUEDaiEBIABBBGoiACAFSQ0ACwtBfyEAIAJB////B00Ef0GEKCAENgIAQYgoIAFBoChrNgIAQQAFQX8LC+0BAQR/AkBBgCgoAgAiAUGEKCgCACIAa0EFTgRAQX8hAxAADQFBgCgoAgAhAUGEKCgCACEAC0F/IQMgASAAayIBQQJIDQAgAC0AoShBAnQoAoAQIAAtAKAoQQJ0KAKACHIhAgJ/IAFBBEYEQEEDQQQgAC0AoyhBPUYbIAAtAKIoQT1GayEBC0EBIAFBA0kNABogAC0AoihBAnQoAoAYIAJyIQJBAiABQQRHDQAaIAAtAKMoQQJ0KAKAICACciECQQMLIQEgAkH///8HSw0AQQAhA0GIKCgCACIAIAI2AKAoQYgoIAAgAWo2AgALIAML"}),S=new Uint8Array("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("").map(s=>s.charCodeAt(0))),v=new Uint32Array(1024);v.fill(4278190080);for(let s=0;s<S.length;++s)v[S[s]]=s<<2;for(let s=0;s<S.length;++s)v[256+S[s]]=s>>4|(s<<4&255)<<8;for(let s=0;s<S.length;++s)v[512+S[s]]=s>>2<<8|(s<<6&255)<<16;for(let s=0;s<S.length;++s)v[768+S[s]]=s<<16;var ft=new Uint8Array(0),me=class{constructor(e,t,i){if(this._inst=null,this._ended=!0,this._bytes=0,this.keepSize=e??1048576,this.maxBytes=t??4294901760,this._bytes=i??32768,this._bytes>this.maxBytes||this.maxBytes>4294901760)throw new Error("invalid byte settings")}get data8(){return this._inst?this._d.subarray(0,this._m32[1282]):ft}release(){this._inst&&(this._bytes>this.keepSize?this._inst=this._m32=this._d=this._mem=null:(this._m32[1280]=0,this._m32[1281]=0,this._m32[1282]=0))}init(e,t){if(this.maxBytes=e??this.maxBytes,this._bytes=t??Math.min(this._bytes,this.maxBytes),this._bytes>this.maxBytes||this.maxBytes>4294901760)throw Error("invalid byte settings");let i=this._m32,A=this._bytes+5152;this._inst?this._mem.buffer.byteLength<A&&(this._mem.grow(Math.ceil((A-this._mem.buffer.byteLength)/65536)),i=new Uint32Array(this._mem.buffer,0),this._d=new Uint8Array(this._mem.buffer,5152)):(this._mem=new WebAssembly.Memory({initial:Math.ceil(A/65536)}),this._inst=Bt({env:{memory:this._mem}}),i=new Uint32Array(this._mem.buffer,0),i.set(v,256),this._d=new Uint8Array(this._mem.buffer,5152)),i[1280]=0,i[1281]=0,i[1282]=0,this._m32=i,this._ended=!1}_realloc(e){let t=this._m32[1280]+e;if(this._bytes<t){if(t>this.maxBytes)return-3;let i=this._bytes;for(;(i*=2)<t;);if(i=Math.min(i,this.maxBytes),i<t)return-3;if(i+5152>this._mem.buffer.byteLength){let A=Math.ceil((i+5152-this._mem.buffer.byteLength)/65536);this._mem.grow(A),this._m32=new Uint32Array(this._mem.buffer,0),this._d=new Uint8Array(this._mem.buffer,5152)}this._bytes=i}return 0}put(e){if(!this._inst||this._ended)return-2;if(this._realloc(e.length))return-3;let t=this._m32;return this._d.set(e,t[1280]),t[1280]+=e.length,t[1280]-t[1281]>=131072?this._inst.exports.dec():0}end(){return this._ended=!0,this._inst?this._inst.exports.end():-2}get loadedBytes(){return this._inst?this._m32[1280]:0}get freeBytes(){return this._inst?this.maxBytes-this._m32[1280]:0}};_e.default=me});var Re=T(Ce=>{"use strict";Object.defineProperty(Ce,"__esModule",{value:!0});var Qt=ce(),Dt=(0,Qt.InWasm)({s:1,t:0,d:"AGFzbQEAAAABCgJgAABgA39/fwACDwEDZW52Bm1lbW9yeQIAAQMDAgABBwcBA2RlYwABCAEACu4EAgwAQQBBAEGAAvwLAAveBAEJf0EAQQBBgAL8CwAgAUEXTgRAIAAgAWpBCGshCkGACCEBIAJBAnRBgAhqIQsgAEEOaiEDQf8BIQZBACECA0AgA0EBaiEHIAMtAAAiCEE/cSEAAkACQCAIQcABcSIJRQRAIABBAnQiAC0AAyEGIAAtAAIhBCAALQABIQUgAC0AACECIAchAwwBCwJAIAhB/QFLDQAgCUHAAUcNACAFQQVsIAJBA2xqIARBB2xqIAZBC2xqQT9xQQJ0IgMgBDoAAiADIAU6AAEgAyACOgAAIANBA2ogBjoAAANAIAEgAjoAACABQQNqIAY6AAAgAUECaiAEOgAAIAFBAWogBToAACABQQRqIQEgAEUEQCAHIQMMBAsgAEEBayEAIAEgC0kNAAsgByEDDAILAn8CQAJAAkAgCEH+AWsOAgABAgsgAy0AAyEEIAMtAAIhBSADLQABIQIgA0EEagwCCyADKAIBIgJBGHYhBiACQRB2IQQgAkEIdiEFIANBBWoMAQsgCUGAAUcEQCAHIAlBwABHDQEaIAQgCEEDcWpBAmshBCACIABBBHZqQQJrIQIgBSAIQQJ2QQNxakECayEFIAcMAQsgBCAAQShrIgkgAy0AASIHQQ9xamohBCACIAdBBHYgCWpqIQIgACAFakEgayEFIANBAmoLIQMgBUEFbCACQQNsaiAEQQdsaiAGQQtsakE/cUECdCIAIAQ6AAIgACAFOgABIAAgAjoAACAAQQNqIAY6AAALIAEgBjoAAyABIAQ6AAIgASAFOgABIAEgAjoAACABQQRqIQELIAMgCkkNAAsLCw=="}),ue=class{constructor(e){this.keepSize=e,this.width=0,this.height=0}decode(e){this.width=e[4]<<24|e[5]<<16|e[6]<<8|e[7],this.height=e[8]<<24|e[9]<<16|e[10]<<8|e[11];let t=this.width*this.height,i=t*4,A=e.length,r=Math.max(i,A)+(Math.min(i,A)>>1)+4096;this._inst?this._mem.buffer.byteLength<r&&(this._mem.grow(Math.ceil((r-this._mem.buffer.byteLength)/65536)),this._d=null):(this._mem=new WebAssembly.Memory({initial:Math.ceil(r/65536)}),this._inst=Dt({env:{memory:this._mem}})),this._d||(this._d=new Uint8Array(this._mem.buffer));let a=this._mem.buffer.byteLength-A&-256;return this._d.set(e,a),this._inst.exports.dec(a,A,t),this._d.subarray(1024,1024+i)}release(){this._inst&&this._mem.buffer.byteLength>this.keepSize&&(this._inst=this._d=this._mem=null)}};Ce.default=ue});var Ke=T(ie=>{"use strict";Object.defineProperty(ie,"__esModule",{value:!0});ie.LIMITS=void 0;ie.LIMITS={CHUNK_SIZE:16384,PALETTE_SIZE:4096,MAX_WIDTH:16384,BYTES:"[encoded data, 14928 characters]"}});var We=T(b=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});b.decodeAsync=b.decode=b.Decoder=b.DecoderAsync=void 0;var U=z(),Q=Ke();function yt(s){if(typeof Buffer<"u")return Buffer.from(s,"base64");let e=atob(s),t=new Uint8Array(e.length);for(let i=0;i<t.length;++i)t[i]=e.charCodeAt(i);return t}var Ye=yt(Q.LIMITS.BYTES),O,Ae=new Uint32Array,ye=class{constructor(){this.bandHandler=e=>1,this.modeHandler=e=>1}handle_band(e){return this.bandHandler(e)}mode_parsed(e){return this.modeHandler(e)}},St={memoryLimit:2048*65536,sixelColor:U.DEFAULT_FOREGROUND,fillColor:U.DEFAULT_BACKGROUND,palette:U.PALETTE_VT340_COLOR,paletteLimit:Q.LIMITS.PALETTE_SIZE,truncate:!0};function qe(s){let e=new ye,t={env:{handle_band:e.handle_band.bind(e),mode_parsed:e.mode_parsed.bind(e)}};return WebAssembly.instantiate(O||Ye,t).then(i=>(O=O||i.module,new J(s,i.instance||i,e)))}b.DecoderAsync=qe;var J=class{constructor(e,t,i){if(this._PIXEL_OFFSET=Q.LIMITS.MAX_WIDTH+4,this._canvas=Ae,this._bandWidths=[],this._maxWidth=0,this._minWidth=Q.LIMITS.MAX_WIDTH,this._lastOffset=0,this._currentHeight=0,this._opts=Object.assign({},St,e),this._opts.paletteLimit>Q.LIMITS.PALETTE_SIZE)throw new Error(`DecoderOptions.paletteLimit must not exceed ${Q.LIMITS.PALETTE_SIZE}`);if(t)i.bandHandler=this._handle_band.bind(this),i.modeHandler=this._initCanvas.bind(this);else{let A=O||(O=new WebAssembly.Module(Ye));t=new WebAssembly.Instance(A,{env:{handle_band:this._handle_band.bind(this),mode_parsed:this._initCanvas.bind(this)}})}this._instance=t,this._wasm=this._instance.exports,this._chunk=new Uint8Array(this._wasm.memory.buffer,this._wasm.get_chunk_address(),Q.LIMITS.CHUNK_SIZE),this._states=new Uint32Array(this._wasm.memory.buffer,this._wasm.get_state_address(),12),this._palette=new Uint32Array(this._wasm.memory.buffer,this._wasm.get_palette_address(),Q.LIMITS.PALETTE_SIZE),this._palette.set(this._opts.palette),this._pSrc=new Uint32Array(this._wasm.memory.buffer,this._wasm.get_p0_address()),this._wasm.init(U.DEFAULT_FOREGROUND,0,this._opts.paletteLimit,0)}get _fillColor(){return this._states[0]}get _truncate(){return this._states[8]}get _rasterWidth(){return this._states[6]}get _rasterHeight(){return this._states[7]}get _width(){return this._states[2]?this._states[2]-4:0}get _height(){return this._states[3]}get _level(){return this._states[9]}get _mode(){return this._states[10]}get _paletteLimit(){return this._states[11]}_initCanvas(e){if(e===2){let t=this.width*this.height;if(t>this._canvas.length){if(this._opts.memoryLimit&&t*4>this._opts.memoryLimit)throw this.release(),new Error("image exceeds memory limit");this._canvas=new Uint32Array(t)}this._maxWidth=this._width}else if(e===1)if(this._level===2){let t=Math.min(this._rasterWidth,Q.LIMITS.MAX_WIDTH)*this._rasterHeight;if(t>this._canvas.length){if(this._opts.memoryLimit&&t*4>this._opts.memoryLimit)throw this.release(),new Error("image exceeds memory limit");this._canvas=new Uint32Array(t)}}else this._canvas.length<65536&&(this._canvas=new Uint32Array(65536));return 0}_realloc(e,t){let i=e+t;if(i>this._canvas.length){if(this._opts.memoryLimit&&i*4>this._opts.memoryLimit)throw this.release(),new Error("image exceeds memory limit");let A=new Uint32Array(Math.ceil(i/65536)*65536);A.set(this._canvas),this._canvas=A}}_handle_band(e){let t=this._PIXEL_OFFSET,i=this._lastOffset;if(this._mode===2){let A=this.height-this._currentHeight,r=0;for(;r<6&&A>0;)this._canvas.set(this._pSrc.subarray(t*r,t*r+e),i+e*r),r++,A--;this._lastOffset+=e*r,this._currentHeight+=r}else if(this._mode===1){this._realloc(i,e*6),this._maxWidth=Math.max(this._maxWidth,e),this._minWidth=Math.min(this._minWidth,e);for(let A=0;A<6;++A)this._canvas.set(this._pSrc.subarray(t*A,t*A+e),i+e*A);this._bandWidths.push(e),this._lastOffset+=e*6,this._currentHeight+=6}return 0}get width(){return this._mode!==1?this._width:Math.max(this._maxWidth,this._wasm.current_width())}get height(){return this._mode!==1?this._height:this._wasm.current_width()?this._bandWidths.length*6+this._wasm.current_height():this._bandWidths.length*6}get palette(){return this._palette.subarray(0,this._paletteLimit)}get memoryUsage(){return this._canvas.byteLength+this._wasm.memory.buffer.byteLength+8*this._bandWidths.length}get properties(){return{width:this.width,height:this.height,mode:this._mode,level:this._level,truncate:!!this._truncate,paletteLimit:this._paletteLimit,fillColor:this._fillColor,memUsage:this.memoryUsage,rasterAttributes:{numerator:this._states[4],denominator:this._states[5],width:this._rasterWidth,height:this._rasterHeight}}}init(e=this._opts.fillColor,t=this._opts.palette,i=this._opts.paletteLimit,A=this._opts.truncate){this._wasm.init(this._opts.sixelColor,e,i,A?1:0),t&&this._palette.set(t.subarray(0,Q.LIMITS.PALETTE_SIZE)),this._bandWidths.length=0,this._maxWidth=0,this._minWidth=Q.LIMITS.MAX_WIDTH,this._lastOffset=0,this._currentHeight=0}decode(e,t=0,i=e.length){let A=t;for(;A<i;){let r=Math.min(i-A,Q.LIMITS.CHUNK_SIZE);this._chunk.set(e.subarray(A,A+=r)),this._wasm.decode(0,r)}}decodeString(e,t=0,i=e.length){let A=t;for(;A<i;){let r=Math.min(i-A,Q.LIMITS.CHUNK_SIZE);for(let a=0,n=A;a<r;++a,++n)this._chunk[a]=e.charCodeAt(n);A+=r,this._wasm.decode(0,r)}}get data32(){if(this._mode===0||!this.width||!this.height)return Ae;let e=this._wasm.current_width();if(this._mode===2){let t=this.height-this._currentHeight;if(t>0){let i=this._PIXEL_OFFSET,A=this._lastOffset,r=0;for(;r<6&&t>0;)this._canvas.set(this._pSrc.subarray(i*r,i*r+e),A+e*r),r++,t--;t&&this._canvas.fill(this._fillColor,A+e*r)}return this._canvas.subarray(0,this.width*this.height)}if(this._mode===1){if(this._minWidth===this._maxWidth){let r=!1;if(e)if(e!==this._minWidth)r=!0;else{let a=this._PIXEL_OFFSET,n=this._lastOffset;this._realloc(n,e*6);for(let o=0;o<6;++o)this._canvas.set(this._pSrc.subarray(a*o,a*o+e),n+e*o)}if(!r)return this._canvas.subarray(0,this.width*this.height)}let t=new Uint32Array(this.width*this.height);t.fill(this._fillColor);let i=0,A=0;for(let r=0;r<this._bandWidths.length;++r){let a=this._bandWidths[r];for(let n=0;n<6;++n)t.set(this._canvas.subarray(A,A+=a),i),i+=this.width}if(e){let r=this._PIXEL_OFFSET,a=this._wasm.current_height();for(let n=0;n<a;++n)t.set(this._pSrc.subarray(r*n,r*n+e),i+this.width*n)}return t}return Ae}get data8(){return new Uint8ClampedArray(this.data32.buffer,0,this.width*this.height*4)}release(){this._canvas=Ae,this._bandWidths.length=0,this._maxWidth=0,this._minWidth=Q.LIMITS.MAX_WIDTH,this._wasm.init(U.DEFAULT_FOREGROUND,0,this._opts.paletteLimit,0)}};b.Decoder=J;function Lt(s,e){let t=new J(e);return t.init(),typeof s=="string"?t.decodeString(s):t.decode(s),{width:t.width,height:t.height,data32:t.data32,data8:t.data8}}b.decode=Lt;async function Tt(s,e){let t=await qe(e);return t.init(),typeof s=="string"?t.decodeString(s):t.decode(s),{width:t.width,height:t.height,data32:t.data32,data8:t.data8}}b.decodeAsync=Tt});function N(s){return{dispose:s}}var k=class{constructor(){this._disposables=new Set;this._isDisposed=!1}get isDisposed(){return this._isDisposed}add(e){return this._isDisposed?e.dispose():this._disposables.add(e),e}dispose(){if(!this._isDisposed){this._isDisposed=!0;for(let e of this._disposables)e.dispose();this._disposables.clear()}}clear(){for(let e of this._disposables)e.dispose();this._disposables.clear()}},R=class{constructor(){this._store=new k}dispose(){this._store.dispose()}_register(e){return this._store.add(e)}};R.None=Object.freeze({dispose(){}});var q=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,this._value?.dispose(),this._value=void 0}};var W=class{constructor(){this._listeners=[];this._disposed=!1}get event(){return this._event?this._event:(this._event=(e,t,i)=>{if(this._disposed)return N(()=>{});let A={fn:e,thisArgs:t};this._listeners.push(A);let r=N(()=>{let a=this._listeners.indexOf(A);a!==-1&&this._listeners.splice(a,1)});return i&&(Array.isArray(i)?i.push(r):i.add(r)),r},this._event)}fire(e){if(!this._disposed)switch(this._listeners.length){case 0:return;case 1:{let{fn:t,thisArgs:i}=this._listeners[0];t.call(i,e);return}default:{let t=this._listeners.slice();for(let{fn:i,thisArgs:A}of t)i.call(A,e)}}}dispose(){this._disposed||(this._disposed=!0,this._listeners.length=0)}},ot;(A=>{function s(r,a){return r(n=>a.fire(n))}A.forward=s;function e(r,a){return(n,o,d)=>r(h=>n.call(o,a(h)),void 0,d)}A.map=e;function t(...r){return(a,n,o)=>{let d=new k;for(let h of r)d.add(h(g=>a.call(n,g)));return o&&(Array.isArray(o)?o.push(d):o.add(d)),d}}A.any=t;function i(r,a,n){return a(n),r(o=>a(o))}A.runAndSubscribe=i})(ot||={});var ge=x(z());var D=class s extends R{constructor(t){super();this._terminal=t;this._layers=new Map;this._optionsRefresh=this._register(new q);this._oldOpen=this._terminal._core.open,this._terminal._core.open=i=>{this._oldOpen?.call(this._terminal._core,i),this._open()},this._terminal._core.screenElement&&this._open(),this._optionsRefresh.value=this._terminal._core.optionsService.onOptionChange(i=>{i==="fontSize"&&(this.rescaleCanvas(),this._renderService?.refreshRows(0,this._terminal.rows))}),this._register(N(()=>{this.removeLayerFromDom(),this.removeLayerFromDom("bottom"),this._terminal._core&&this._oldOpen&&(this._terminal._core.open=this._oldOpen,this._oldOpen=void 0),this._renderService&&this._oldSetRenderer&&(this._renderService.setRenderer=this._oldSetRenderer,this._oldSetRenderer=void 0),this._renderService=void 0,this._layers.clear(),this._placeholderBitmap?.close(),this._placeholderBitmap=void 0,this._placeholder=void 0}))}get canvas(){return this._layers.get("top")?.canvas}static createCanvas(t,i,A){let r=(t??document).createElement("canvas");return r.width=i|0,r.height=A|0,r}static createImageData(t,i,A,r){if(typeof ImageData!="function"){let a=t.createImageData(i,A);return r&&a.data.set(new Uint8ClampedArray(r,0,i*A*4)),a}return r?new ImageData(new Uint8ClampedArray(r,0,i*A*4),i,A):new ImageData(i,A)}static createImageBitmap(t){return typeof createImageBitmap!="function"?Promise.resolve(void 0):createImageBitmap(t)}showPlaceholder(t){t?!this._placeholder&&this.cellSize.height!==-1&&this._createPlaceHolder(Math.max(this.cellSize.height+1,24)):(this._placeholderBitmap?.close(),this._placeholderBitmap=void 0,this._placeholder=void 0),this._renderService?.refreshRows(0,this._terminal.rows)}get dimensions(){return this._terminal.dimensions}get cellSize(){return{width:this.dimensions?.css.cell.width||-1,height:this.dimensions?.css.cell.height||-1}}clearLines(t,i,A){let r=t*(this.dimensions?.css.cell.height||0),a=this.dimensions?.css.canvas.width||0,n=(i+1-t)*(this.dimensions?.css.cell.height||0);(!A||A==="top")&&this._layers.get("top")?.clearRect(0,r,a,n),(!A||A==="bottom")&&this._layers.get("bottom")?.clearRect(0,r,a,n)}clearAll(t){if(!t||t==="top"){let i=this._layers.get("top");i?.clearRect(0,0,i.canvas.width,i.canvas.height)}if(!t||t==="bottom"){let i=this._layers.get("bottom");i?.clearRect(0,0,i.canvas.width,i.canvas.height)}}draw(t,i,A,r,a=1){let n=this._layers.get(t.layer);if(!n)return;let{width:o,height:d}=this.cellSize;if(o===-1||d===-1)return;this._rescaleImage(t,o,d);let h=t.actual,g=Math.ceil(h.width/o),I=i%g*o,_=Math.floor(i/g)*d,l=A*o,C=r*d,u=a*o+I>h.width?h.width-I:a*o,E=_+d>h.height?h.height-_:d;n.drawImage(h,Math.floor(I),Math.floor(_),Math.ceil(u),Math.ceil(E),Math.floor(l),Math.floor(C),Math.ceil(u),Math.ceil(E))}extractTile(t,i){let{width:A,height:r}=this.cellSize;if(A===-1||r===-1)return;this._rescaleImage(t,A,r);let a=t.actual,n=Math.ceil(a.width/A),o=i%n*A,d=Math.floor(i/n)*r,h=A+o>a.width?a.width-o:A,g=d+r>a.height?a.height-d:r,I=s.createCanvas(this.document,h,g),_=I.getContext("2d");if(_)return _.drawImage(a,Math.floor(o),Math.floor(d),Math.floor(h),Math.floor(g),0,0,Math.floor(h),Math.floor(g)),I}drawPlaceholder(t,i,A=1){let r=this._layers.get("top");if(r){let{width:a,height:n}=this.cellSize;if(a===-1||n===-1||(this._placeholder?n>=this._placeholder.height&&this._createPlaceHolder(n+1):this._createPlaceHolder(Math.max(n+1,24)),!this._placeholder))return;r.drawImage(this._placeholderBitmap??this._placeholder,t*a,i*n%2?0:1,a*A,n,t*a,i*n,a*A,n)}}rescaleCanvas(){let t=this.dimensions?.css.canvas.width||0,i=this.dimensions?.css.canvas.height||0;for(let A of this._layers.values())(A.canvas.width!==t||A.canvas.height!==i)&&(A.canvas.width=t,A.canvas.height=i)}_rescaleImage(t,i,A){if(i===t.actualCellSize.width&&A===t.actualCellSize.height)return;let{width:r,height:a}=t.origCellSize;if(i===r&&A===a){t.actual=t.orig,t.actualCellSize.width=r,t.actualCellSize.height=a;return}let n=s.createCanvas(this.document,Math.ceil(t.orig.width*i/r),Math.ceil(t.orig.height*A/a)),o=n.getContext("2d");o&&(o.drawImage(t.orig,0,0,n.width,n.height),t.actual=n,t.actualCellSize.width=i,t.actualCellSize.height=A)}_open(){this._renderService=this._terminal._core._renderService,this._oldSetRenderer=this._renderService.setRenderer.bind(this._renderService),this._renderService.setRenderer=t=>{for(let i of[...this._layers.keys()])this.removeLayerFromDom(i);this._oldSetRenderer?.call(this._renderService,t)}}insertLayerToDom(t="top"){if(!this.document||!this._terminal._core.screenElement){console.warn("image addon: cannot insert output canvas to DOM, missing document or screenElement");return}if(this._layers.has(t))return;let i=s.createCanvas(this.document,this.dimensions?.css.canvas.width||0,this.dimensions?.css.canvas.height||0);i.classList.add(`xterm-image-layer-${t}`);let A=this._terminal._core.screenElement;A.style.isolation="isolate",t==="bottom"?(i.style.zIndex="-1",A.insertBefore(i,A.firstChild)):(i.style.zIndex="0",A.appendChild(i));let r=i.getContext("2d",{alpha:!0});if(!r){i.remove();return}this._layers.set(t,r),this.clearAll(t)}removeLayerFromDom(t="top"){let i=this._layers.get(t);i&&(i.canvas.remove(),this._layers.delete(t))}hasLayer(t){return this._layers.has(t)}_createPlaceHolder(t=24){this._placeholderBitmap?.close(),this._placeholderBitmap=void 0;let i=32,A=s.createCanvas(this.document,i,t),r=A.getContext("2d",{alpha:!1});if(!r)return;let a=s.createImageData(r,i,t),n=new Uint32Array(a.data.buffer),o=(0,ge.toRGBA8888)(0,0,0),d=(0,ge.toRGBA8888)(255,255,255);n.fill(o);for(let I=0;I<t;++I){let _=I%2,l=I*i;for(let C=0;C<i;C+=2)n[l+C+_]=d}r.putImageData(a,0,0);let h=screen.width+i-1&~(i-1)||4096;this._placeholder=s.createCanvas(this.document,h,t);let g=this._placeholder.getContext("2d",{alpha:!1});if(!g){this._placeholder=void 0;return}for(let I=0;I<h;I+=i)g.drawImage(A,I,0);s.createImageBitmap(this._placeholder).then(I=>this._placeholderBitmap=I)}get document(){return this._terminal._core._coreBrowserService?.window.document}};var w={width:7,height:14},H=class s{constructor(e=0,t=0,i=-1,A=-1){this.imageId=i;this.tileId=A;this._ext=0;this._urlId=0;this._ext=e,this._urlId=t}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(e){this._ext=e}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(e){this._ext&=-469762049,this._ext|=e<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(e){this._ext&=-67108864,this._ext|=e&67108863}get underlineVariantOffset(){let e=(this._ext&3758096384)>>29;return e<0?e^4294967288:e}set underlineVariantOffset(e){this._ext&=536870911,this._ext|=e<<29&3758096384}get urlId(){return this._urlId}set urlId(e){this._urlId=e}clone(){return new s(this._ext,this._urlId,this.imageId,this.tileId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0&&this.imageId===-1}},X=new H,Z=class{constructor(e,t,i){this._terminal=e;this._renderer=t;this._opts=i;this._images=new Map;this._lastId=0;this._lowestId=0;this._fullyCleared=!1;this._needsFullClear=!1;this._pixelLimit=25e5;try{this.setLimit(this._opts.storageLimit)}catch(A){A instanceof Error&&console.error(A.message),console.warn(`storageLimit is set to ${this.getLimit()} MB`)}this._viewportMetrics={cols:this._terminal.cols,rows:this._terminal.rows}}dispose(){this.reset()}reset(){for(let e of this._images.values())e.marker?.dispose();this._images.clear(),this._renderer.clearAll()}getLimit(){return this._pixelLimit*4/1e6}setLimit(e){if(e<.5||e>1e3)throw RangeError("invalid storageLimit, should be at least 0.5 MB and not exceed 1G");this._pixelLimit=e/4*1e6>>>0,this._evictOldest(0)}getUsage(){return this._getStoredPixels()*4/1e6}_getStoredPixels(){let e=0;for(let t of this._images.values())t.orig&&(e+=t.orig.width*t.orig.height,t.actual&&t.actual!==t.orig&&(e+=t.actual.width*t.actual.height));return e}_delImg(e){let t=this._images.get(e);t&&(this._images.delete(e),window.ImageBitmap&&t.orig instanceof ImageBitmap&&t.orig.close(),this.onImageDeleted?.(e))}wipeAlternate(){let e=[];for(let[t,i]of this._images.entries())i.bufferType==="alternate"&&(i.marker?.dispose(),e.push(t));for(let t of e)this._delImg(t);this._needsFullClear=!0,this._fullyCleared=!1}deleteImage(e){let t=this._images.get(e);t&&(t.marker?.dispose(),this._delImg(e))}addImage(e,t){this._evictOldest(e.width*e.height);let i=this._renderer.cellSize;(i.width===-1||i.height===-1)&&(i=w);let A=Math.ceil(e.width/i.width),r=Math.ceil(e.height/i.height),a=++this._lastId,n=this._terminal._core.buffer,o=this._terminal.cols,d=this._terminal.rows,h=n.x,g=n.y,I=h,_=0;t.scrolling||(n.x=0,n.y=0,I=0),this._terminal._core._inputHandler._dirtyRowTracker.markDirty(n.y);for(let E=0;E<r;++E){let p=n.lines.get(n.y+n.ybase);for(let f=0;f<A&&!(I+f>=o);++f)this._writeToCell(p,I+f,a,E*A+f),_++;if(t.scrolling)E<r-1&&this._terminal._core._inputHandler.lineFeed();else if(++n.y>=d)break;n.x=I}this._terminal._core._inputHandler._dirtyRowTracker.markDirty(n.y),t.scrolling?t.cursorPos==="iip"?n.x=Math.min(I+A,o):n.x=I:(n.x=h,n.y=g);let l=[];for(let[E,p]of this._images.entries())p.tileCount<1&&(p.marker?.dispose(),l.push(E));for(let E of l)this._delImg(E);let C=this._terminal.registerMarker(0);C?.onDispose(()=>{this._images.get(a)&&this._delImg(a)}),this._terminal.buffer.active.type==="alternate"&&this._evictOnAlternate();let u={orig:e,origCellSize:i,actual:e,actualCellSize:{...i},marker:C||void 0,tileCount:_,bufferType:this._terminal.buffer.active.type,layer:t.layer,zIndex:t.zIndex};return this._images.set(a,u),this.onImageAdded?.(),a}render(e){let t=!1,i=!1;for(let h of this._images.values())if(h.layer==="bottom"?i=!0:t=!0,t&&i)break;if(t&&!this._renderer.hasLayer("top")&&(this._renderer.insertLayerToDom("top"),!this._renderer.hasLayer("top")))return;if(i&&!this._renderer.hasLayer("bottom")&&this._renderer.insertLayerToDom("bottom"),this._renderer.rescaleCanvas(),!this._images.size){this._fullyCleared||(this._renderer.clearAll(),this._fullyCleared=!0,this._needsFullClear=!1),this._renderer.hasLayer("top")&&this._renderer.removeLayerFromDom("top"),this._renderer.hasLayer("bottom")&&this._renderer.removeLayerFromDom("bottom");return}!t&&this._renderer.hasLayer("top")&&(this._renderer.clearAll("top"),this._renderer.removeLayerFromDom("top")),!i&&this._renderer.hasLayer("bottom")&&(this._renderer.clearAll("bottom"),this._renderer.removeLayerFromDom("bottom")),this._needsFullClear&&(this._renderer.clearAll(),this._fullyCleared=!0,this._needsFullClear=!1);let{start:A,end:r}=e,a=this._terminal._core.buffer,n=this._terminal._core.cols;this._renderer.clearLines(A,r);let o=[],d=[];for(let h=A;h<=r;++h){let g=a.lines.get(h+a.ydisp);if(!g)return;for(let I=0;I<n;++I){let _;if(g.getBg(I)&268435456)_=g._extendedAttrs[I]??X;else{let u=g._extendedAttrs[I];if(!u||u.imageId===void 0||u.imageId===-1)continue;_=u}let l=_.imageId;if(l===void 0||l===-1)continue;let C=this._images.get(l);if(_.tileId!==-1){let u=_.tileId,E=I,p=1;for(;++I<n;){let f=g._extendedAttrs[I];if(!f||f.imageId!==l||f.tileId!==u+p)break;p++}I--,C?C.actual&&o.push({imgSpec:C,tileId:u,col:E,row:h,count:p}):this._opts.showPlaceholder&&d.push({col:E,row:h,count:p}),this._fullyCleared=!1}}}o.sort((h,g)=>h.imgSpec.zIndex-g.imgSpec.zIndex);for(let h of d)this._renderer.drawPlaceholder(h.col,h.row,h.count);for(let h of o)this._renderer.draw(h.imgSpec,h.tileId,h.col,h.row,h.count)}viewportResize(e){if(!this._images.size){this._viewportMetrics=e;return}if(this._viewportMetrics.cols>=e.cols){this._viewportMetrics=e;return}let t=this._terminal._core.buffer,i=t.lines.length,A=this._viewportMetrics.cols-1;for(let r=0;r<i;++r){let a=t.lines.get(r);if(a.getBg(A)&268435456){let n=a._extendedAttrs[A]??X,o=n.imageId;if(o===void 0||o===-1)continue;let d=this._images.get(o);if(!d)continue;let h=Math.ceil((d.actual?.width||0)/d.actualCellSize.width);if(n.tileId%h+1>=h)continue;let g=!1;for(let l=A+1;l>e.cols;++l)if(a._data[l*3+0]&4194303){g=!0;break}if(g)continue;let I=Math.min(e.cols,h-n.tileId%h+A),_=n.tileId;for(let l=A+1;l<I;++l)this._writeToCell(a,l,o,++_),d.tileCount++}}this._viewportMetrics=e}getImageAtBufferCell(e,t){let A=this._terminal._core.buffer.lines.get(t);if(A&&A.getBg(e)&268435456){let r=A._extendedAttrs[e]??X;if(r.imageId&&r.imageId!==-1){let a=this._images.get(r.imageId)?.orig;if(window.ImageBitmap&&a instanceof ImageBitmap){let n=D.createCanvas(window.document,a.width,a.height);return n.getContext("2d")?.drawImage(a,0,0,a.width,a.height),n}return a}}}extractTileAtBufferCell(e,t){let A=this._terminal._core.buffer.lines.get(t);if(A&&A.getBg(e)&268435456){let r=A._extendedAttrs[e]??X;if(r.imageId&&r.imageId!==-1&&r.tileId!==-1){let a=this._images.get(r.imageId);if(a)return this._renderer.extractTile(a,r.tileId)}}}_evictOldest(e){let t=this._getStoredPixels(),i=t;for(;this._pixelLimit<i+e&&this._images.size;){let A=this._images.get(++this._lowestId);A&&A.orig&&(i-=A.orig.width*A.orig.height,A.actual&&A.orig!==A.actual&&(i-=A.actual.width*A.actual.height),A.marker?.dispose(),this._delImg(this._lowestId))}return t-i}_writeToCell(e,t,i,A){if(e._data[t*3+2]&268435456){let r=e._extendedAttrs[t];if(r){if(r.imageId!==void 0){let a=this._images.get(r.imageId);a&&a.tileCount--,r.imageId=i,r.tileId=A;return}e._extendedAttrs[t]=new H(r.ext,r.urlId,i,A);return}}e._data[t*3+2]|=268435456,e._extendedAttrs[t]=new H(0,0,i,A)}_evictOnAlternate(){for(let i of this._images.values())i.bufferType==="alternate"&&(i.tileCount=0);let e=this._terminal._core.buffer;for(let i=0;i<this._terminal.rows;++i){let A=e.lines.get(i);if(A){for(let r=0;r<this._terminal.cols;++r)if(A._data[r*3+2]&268435456){let a=A._extendedAttrs[r]?.imageId;if(a){let n=this._images.get(a);n&&n.tileCount++}}}}let t=[];for(let[i,A]of this._images.entries())A.bufferType==="alternate"&&!A.tileCount&&(A.marker?.dispose(),t.push(i));for(let i of t)this._delImg(i)}};var Ue=x(Ee()),Oe=x(Re());function j(s){let e="";for(let t=0;t<s.length;++t)e+=String.fromCharCode(s[t]);return e}function pe(s){let e=0;for(let t=0;t<s.length;++t){if(s[t]<48||s[t]>57)throw new Error("illegal char");e=e*10+s[t]-48}return e}function ke(s){let e=j(s);if(!e.match(/^((auto)|(\d+?((px)|(%)){0,1}))$/))throw new Error("illegal size");return e}function wt(s){if(typeof Buffer<"u")return Buffer.from(j(s),"base64").toString();let e=atob(j(s)),t=new Uint8Array(e.length);for(let i=0;i<t.length;++i)t[i]=e.charCodeAt(i);return new TextDecoder().decode(t)}var Ne={inline:pe,size:pe,name:wt,width:ke,height:ke,preserveAspectRatio:pe},He=[70,105,108,101],Fe=[77,117,108,116,105,112,97,114,116,70,105,108,101],Be=[70,105,108,101,80,97,114,116],fe=[70,105,108,101,69,110,100],Qe=[82,101,112,111,114,116,67,101,108,108,83,105,122,101],De=1024,V=class{constructor(){this.state=0;this._buffer=new Uint32Array(De);this._position=0;this._key="";this.fields={}}reset(){this._buffer.fill(0),this.state=0,this._position=0,this.fields={},this._key=""}end(){if(this.state===0){if(this._position===fe.length){for(let e=0;e<fe.length;++e)if(this._buffer[e]!==fe[e])return this._a();return this.fields.type=4,this.state=4,0}if(this._position===Qe.length){for(let e=0;e<Qe.length;++e)if(this._buffer[e]!==Qe[e])return this._a();return this.fields.type=5,this.state=4,0}return this._a()}return this.state===4?0:this.state===3&&this.fields.type===2?this._storeValue(this._position)?(this.state=4,0):this._a():this._a()}parse(e,t,i){let A=this.state,r=this._position,a=this._buffer;if(A===1||A===4||A===0&&r>14)return-1;for(let n=t;n<i;++n){let o=e[n];switch(o){case 59:if(!this._storeValue(r))return this._a();A=2,r=0;break;case 61:if(A===0){if(a[0]===70){let d=0;for(;d<He.length;++d)if(a[d]!==He[d])return this._a();if(this.fields.type=1,r===Be.length){for(;d<Be.length;++d)if(a[d]!==Be[d])return this._a();return this.fields.type=3,this.state=4,n+1}}else if(a[0]===77){for(let d=0;d<Fe.length;++d)if(a[d]!==Fe[d])return this._a();this.fields.type=2}else return this._a();A=2,r=0}else if(A===2){if(!this._storeKey(r))return this._a();A=3,r=0}else if(A===3){if(r>=De)return this._a();a[r++]=o}break;case 58:return A===3&&!this._storeValue(r)?this._a():(this.state=4,n+1);default:if(r>=De)return this._a();a[r++]=o}}return this.state=A,this._position=r,-2}_a(){return this.fields.type=0,this.state=1,-1}_storeKey(e){let t=j(this._buffer.subarray(0,e));return t?(this._key=t,this.fields[t]=null,!0):!1}_storeValue(e){if(this._key){try{let t=this._buffer.slice(0,e);this.fields[this._key]=Ne[this._key]?Ne[this._key](t):t}catch{return!1}return!0}return!1}};var F={mime:"unsupported",width:0,height:0};function Ge(s){if(s.length<24)return F;let e=new Uint32Array(s.buffer,s.byteOffset,6);if(e[0]===1196314761&&e[1]===169478669&&e[3]===1380206665)return{mime:"image/png",width:s[16]<<24|s[17]<<16|s[18]<<8|s[19],height:s[20]<<24|s[21]<<16|s[22]<<8|s[23]};if(s[0]===255&&s[1]===216&&s[2]===255){let[t,i]=bt(s);return{mime:"image/jpeg",width:t,height:i}}return e[0]===944130375&&(s[4]===55||s[4]===57)&&s[5]===97?{mime:"image/gif",width:s[7]<<8|s[6],height:s[9]<<8|s[8]}:e[0]===1718185841?{mime:"image/qoi",width:s[4]<<24|s[5]<<16|s[6]<<8|s[7],height:s[8]<<24|s[9]<<16|s[10]<<8|s[11]}:F}function bt(s){let e=s.length,t=4,i=s[t]<<8|s[t+1];for(;;){if(t+=i,t>=e)return[0,0];if(s[t]!==255)return[0,0];if(s[t+1]===192||s[t+1]===194)return t+8<e?[s[t+7]<<8|s[t+8],s[t+5]<<8|s[t+6]]:[0,0];t+=2,i=s[t]<<8|s[t+1]}}var we={type:0,name:"Unnamed file",size:0,width:"auto",height:"auto",preserveAspectRatio:1,inline:0},$=class{constructor(e,t,i,A){this._opts=e;this._renderer=t;this._storage=i;this._coreTerminal=A;this._aborted=!1;this._hp=new V;this._header=we;this._metrics=F;this._isMultipart=!1;this._abortMulti=!1;let r=Math.ceil(this._opts.iipSizeLimit*4/3),a=Math.min(1048576,r);this._dec=new Ue.default(4194304,r,a),this._qoiDec=new Oe.default(4194304)}reset(){this._hp.reset(),this._dec.release(),this._qoiDec.release()}start(){this._aborted=!1,this._metrics=F,this._hp.reset()}put(e,t,i){if(!this._aborted)if(this._hp.state===4)this._dec.put(e.subarray(t,i))!==0&&(this._dec.release(),this._aborted=!0);else{let A=this._hp.parse(e,t,i);if(A===-1){this._aborted=!0;return}if(A>0){if(this._hp.fields.type===1){if(this._isMultipart&&(this._isMultipart=!1,this._abortMulti=!1,this._dec.release()),this._header=Object.assign({},we,this._hp.fields),!this._header.inline){this._aborted=!0;return}this._dec.init()}else if(this._abortMulti){this._aborted=!0;return}this._dec.put(e.subarray(A,i))!==0&&(this._dec.release(),this._aborted=!0,this._isMultipart&&(this._abortMulti=!0))}}}end(e){if(this._aborted||this._hp.state!==4&&this._hp.end())return!0;let t=this._hp.fields.type;if(t===3)return!0;if(t===5){let n=w.width,o=w.height;this._renderer.dimensions&&(n=this._renderer.dimensions.css.canvas.width/this._coreTerminal.cols,o=this._renderer.dimensions.css.canvas.height/this._coreTerminal.rows);let d=this._coreTerminal._core._coreBrowserService?.dpr??1,h=`\x1B]1337;ReportCellSize=${o.toFixed(3)};${n.toFixed(3)};${d.toFixed(3)}\x1B\\`;return this._coreTerminal.input(h,!1),!0}if(t===2)return this._header=Object.assign({},we,this._hp.fields),this._isMultipart=!0,this._abortMulti=!1,this._dec.release(),this._dec.init(),!0;if(t===4&&(!this._isMultipart||(this._isMultipart=!1,this._abortMulti||this._header.type!==2)))return!0;let i=0,A=0,r;if((r=e)&&(r=!this._dec.end())&&(this._metrics=Ge(this._dec.data8),(r=this._metrics.mime!=="unsupported")&&(i=this._metrics.width,A=this._metrics.height,(r=i&&A&&i*A<this._opts.pixelLimit)&&([i,A]=this._resize(i,A).map(Math.floor),r=i&&A&&i*A<this._opts.pixelLimit))),!r)return this._dec.release(),!0;let a;if(this._metrics.mime==="image/qoi"){let n=this._qoiDec.decode(this._dec.data8);if(a=new ImageData(new Uint8ClampedArray(n.buffer,n.byteOffset,n.byteLength),this._qoiDec.width,this._qoiDec.height),this._qoiDec.release(),i===this._qoiDec.width&&A===this._qoiDec.height){this._dec.release();let o=D.createCanvas(void 0,this._qoiDec.width,this._qoiDec.height);return o.getContext("2d")?.putImageData(a,0,0),this._storage.addImage(o),!0}}else a=new Blob([this._dec.data8],{type:this._metrics.mime});return this._dec.release(),createImageBitmap(a,{resizeWidth:i,resizeHeight:A}).then(n=>(this._storage.addImage(n),!0))}_resize(e,t){let i=this._renderer.dimensions?.css.cell.width||w.width,A=this._renderer.dimensions?.css.cell.height||w.height,r=this._renderer.dimensions?.css.canvas.width||i*this._coreTerminal.cols,a=this._renderer.dimensions?.css.canvas.height||A*this._coreTerminal.rows,n=this._dim(this._header.width,r,i),o=this._dim(this._header.height,a,A);if(!n&&!o){let d=r/e,h=(a-A)/t,g=Math.min(d,h);return g<1?[e*g,t*g]:[e,t]}return n?this._header.preserveAspectRatio||!n||!o?[n,t*n/e]:[n,o]:[e*o/t,o]}_dim(e,t,i){return e==="auto"?0:e.endsWith("%")?parseInt(e.slice(0,-1),10)*t/100:e.endsWith("px")?parseInt(e.slice(0,-2),10):parseInt(e,10)*i}};var Pe=x(Ee());function be(s){let e={},t=s.split(",");for(let i of t){let A=i.indexOf("=");if(A===-1)continue;let r=i.substring(0,A),a=i.substring(A+1);if(r==="a"){e.action=a;continue}if(r==="o"){e.compression=a;continue}if(r==="t"){e.transmission=a;continue}if(r==="d"){e.deleteSelector=a;continue}let n=parseInt(a,10);switch(r){case"f":e.format=n;break;case"i":e.id=n;break;case"I":e.imageNumber=n;break;case"s":e.width=n;break;case"v":e.height=n;break;case"x":e.x=n;break;case"y":e.y=n;break;case"w":e.sourceWidth=n;break;case"h":e.sourceHeight=n;break;case"X":e.xOffset=n;break;case"Y":e.yOffset=n;break;case"c":e.columns=n;break;case"r":e.rows=n;break;case"m":e.more=n;break;case"q":e.quiet=n;break;case"C":e.cursorMovement=n;break;case"z":e.zIndex=n;break;case"p":e.placementId=n;break}}return e}var Je=0,ee=class{constructor(e,t,i,A){this._opts=e;this._renderer=t;this._kittyStorage=i;this._coreTerminal=A;this._aborted=!1;this._decodeError=!1;this._activeDecoder=null;this._inControlData=!0;this._controlData=new Uint32Array(512);this._controlLength=0;this._encodedSizeLimit=0;this._totalEncodedSize=0;this._parsedCommand=null;this._pendingTransmissions=new Map;this._maxEncodedBytes=Math.ceil(this._opts.kittySizeLimit*4/3),this._initialEncodedBytes=Math.min(4194304,this._maxEncodedBytes)}reset(){this._cleanupAllPending(),this._activeDecoder&&(this._activeDecoder.release(),this._activeDecoder=null),this._kittyStorage.reset()}dispose(){this.reset()}_removePendingEntry(e){this._pendingTransmissions.delete(e),this._lastPendingKey===e&&(this._lastPendingKey=void 0)}_cleanupAllPending(){for(let e of this._pendingTransmissions.values())e.decoder.release();this._pendingTransmissions.clear(),this._lastPendingKey=void 0}start(){this._aborted=!1,this._decodeError=!1,this._inControlData=!0,this._controlLength=0,this._parsedCommand=null,this._encodedSizeLimit=this._maxEncodedBytes,this._totalEncodedSize=0,this._activeDecoder=null}put(e,t,i){if(!this._aborted)if(!this._inControlData)this._streamPayload(e,t,i);else{let A=i;for(let a=t;a<i;a++)if(e[a]===59){this._inControlData=!1,A=a;break}let r=A-t;if(this._controlLength+r>512){this._aborted=!0;return}if(this._controlData.set(e.subarray(t,A),this._controlLength),this._controlLength+=r,!this._inControlData){if(this._parsedCommand=be(this._parseControlDataString()),this._parsedCommand.id!==void 0&&this._parsedCommand.imageNumber!==void 0){this._sendResponse(this._parsedCommand.id,"EINVAL:cannot specify both i and I keys",this._parsedCommand.quiet??0),this._aborted=!0;return}if(this._parsedCommand.action==="d")return;let a=A+1;a<i&&this._streamPayload(e,a,i)}}}_streamPayload(e,t,i){if(this._aborted)return;let A=this._parsedCommand?.id??this._lastPendingKey??0,r=this._pendingTransmissions.get(A),a=r?.totalEncodedSize??0;if(this._totalEncodedSize+=i-t,a+this._totalEncodedSize>this._encodedSizeLimit){let o=this._activeDecoder??r?.decoder;o&&o.release(),this._activeDecoder=null,r&&this._removePendingEntry(A),this._aborted=!0;return}this._decodeError||(r?.decoder&&!this._activeDecoder&&(this._activeDecoder=r.decoder),this._activeDecoder||(this._activeDecoder=new Pe.default(4194304,this._maxEncodedBytes,this._initialEncodedBytes),this._activeDecoder.init()),this._activeDecoder.put(e.subarray(t,i))!==Je&&(this._activeDecoder.release(),this._activeDecoder=null,this._decodeError=!0,r&&this._removePendingEntry(A)))}end(e){if(this._aborted||!e)return this._activeDecoder&&(this._activeDecoder.release(),this._activeDecoder=null),!0;if(this._inControlData)return this._handleNoPayloadCommand();let t=this._parsedCommand;if(t.action==="d")return this._handleDelete(t);let i=t.id??this._lastPendingKey??0,A=t.more===1,r=this._pendingTransmissions.get(i);if(A)return this._activeDecoder&&(r?(r.totalEncodedSize+=this._totalEncodedSize,r.decodeError=r.decodeError||this._decodeError):this._pendingTransmissions.set(i,{cmd:{...t},decoder:this._activeDecoder,totalEncodedSize:this._totalEncodedSize,decodeError:this._decodeError}),this._lastPendingKey=i,this._activeDecoder=null),!0;r&&(this._lastPendingKey=void 0);let a=this._decodeError,n=t,o=this._activeDecoder;r&&(n=r.cmd,o=r.decoder,a=a||r.decodeError,this._pendingTransmissions.delete(i));let d=new Uint8Array(0);o&&(o.end()!==Je&&(a=!0),d=o.data8),this._activeDecoder=null;let h=this._handleCommandWithBytesAndCmd(n,d,a);return o&&o.release(),h}_parseControlDataString(){let e="";for(let t=0;t<this._controlLength;t++)e+=String.fromCodePoint(this._controlData[t]);return e}_handleNoPayloadCommand(){let e=be(this._parseControlDataString());if(e.id!==void 0&&e.imageNumber!==void 0)return this._sendResponse(e.id,"EINVAL:cannot specify both i and I keys",e.quiet??0),!0;switch(e.action??"t"){case"d":return this._handleDelete(e);case"q":return this._sendResponse(e.id??0,"OK",e.quiet??0),!0;case"p":return this._handlePlacement(e);default:return e.id!==void 0&&this._sendResponse(e.id,"EINVAL:unsupported action",e.quiet??0),!0}}_handleCommandWithBytesAndCmd(e,t,i){switch(e.action??"t"){case"t":{let r=this._handleTransmit(e,t,i);return(e.transmission??"d")==="d"&&e.id!==void 0&&(i?this._sendResponse(e.id,"EINVAL:invalid base64 data",e.quiet??0):t.length>0&&this._sendResponse(e.id,"OK",e.quiet??0)),r}case"T":return this._handleTransmitDisplay(e,t,i);case"q":return this._handleQuery(e,t,i);case"p":return this._handlePlacement(e);default:return e.id!==void 0&&this._sendResponse(e.id,"EINVAL:unsupported action",e.quiet??0),!0}}_handlePlacement(e){if(e.id===void 0)return!0;let t=e.id,i=this._kittyStorage.getImage(t);return i?this._displayImage(i,e).then(r=>(this._sendResponse(t,r?"OK":"EINVAL:image rendering failed",e.quiet??0,e.placementId),!0)):(this._sendResponse(t,"ENOENT:image not found",e.quiet??0,e.placementId),!0)}_handleTransmit(e,t,i){return(e.transmission??"d")!=="d"?(e.id!==void 0&&this._sendResponse(e.id,"EINVAL:unsupported transmission medium",e.quiet??0),!0):(i||t.length===0||this._kittyStorage.storeImage(e.id,{data:new Blob([t]),width:e.width??0,height:e.height??0,format:e.format??32,compression:e.compression??""}),!0)}_handleTransmitDisplay(e,t,i){if(i)return e.id!==void 0&&this._sendResponse(e.id,"EINVAL:invalid base64 data",e.quiet??0),!0;this._handleTransmit(e,t,i);let A=e.id??this._kittyStorage.lastImageId,r=this._kittyStorage.getImage(A);if(r){let a=this._displayImage(r,e);return e.id!==void 0?a.then(n=>(this._sendResponse(A,n?"OK":"EINVAL:image rendering failed",e.quiet??0),!0)):a.then(()=>!0)}return!0}_handleQuery(e,t,i){let A=e.id??0,r=e.quiet??0;if((e.transmission??"d")!=="d")return this._sendResponse(A,"EINVAL:unsupported transmission medium",r),!0;if(i)return this._sendResponse(A,"EINVAL:invalid base64 data",r),!0;if(t.length===0)return this._sendResponse(A,"OK",r),!0;let n=e.format??32;if(n===100)this._sendResponse(A,"OK",r);else{let o=e.width??0,d=e.height??0;if(!o||!d)return this._sendResponse(A,"EINVAL:width and height required for raw pixel data",r),!0;let h=n===32?4:3,g=o*d*h;if(t.length<g)return this._sendResponse(A,"EINVAL:insufficient pixel data",r),!0;this._sendResponse(A,"OK",r)}return!0}_handleDelete(e){switch(e.deleteSelector??"a"){case"a":case"A":this._cleanupAllPending(),this._kittyStorage.deleteAll();break;case"i":case"I":if(e.id!==void 0){let i=this._pendingTransmissions.get(e.id);i&&i.decoder.release(),this._removePendingEntry(e.id),this._kittyStorage.deleteById(e.id)}break;default:break}return!0}_sendResponse(e,t,i,A){let r=t==="OK";if(r&&i>=1||!r&&i>=2)return;let a=A?`,p=${A}`:"",n=`\x1B_Gi=${e}${a};${t}\x1B\\`;this._coreTerminal._core.coreService.triggerDataEvent(n)}_displayImage(e,t){return this._decodeAndDisplay(e,t).then(()=>!0).catch(()=>!1)}async _decodeAndDisplay(e,t){let i=await this._createBitmap(e);try{let A=Math.max(0,t.x??0),r=Math.max(0,t.y??0),a=t.sourceWidth||i.width-A,n=t.sourceHeight||i.height-r,o=Math.max(0,i.width-A),d=Math.max(0,i.height-r),h=Math.max(0,Math.min(a,o)),g=Math.max(0,Math.min(n,d));if(h===0||g===0)throw new Error("invalid source rectangle");if(A!==0||r!==0||h!==i.width||g!==i.height){let L=await createImageBitmap(i,A,r,h,g);i.close(),i=L}let I=this._renderer.dimensions?.css.cell.width||w.width,_=this._renderer.dimensions?.css.cell.height||w.height,l,C;t.columns!==void 0&&t.rows!==void 0?(l=t.columns,C=t.rows):t.columns!==void 0?(l=t.columns,C=Math.max(1,Math.ceil(i.height/i.width*(l*I)/_))):t.rows!==void 0?(C=t.rows,l=Math.max(1,Math.ceil(i.width/i.height*(C*_)/I))):(l=Math.ceil(i.width/I),C=Math.ceil(i.height/_));let u=i.width,E=i.height;if((t.columns!==void 0||t.rows!==void 0)&&(u=Math.round(l*I),E=Math.round(C*_)),u*E>this._opts.pixelLimit)throw new Error("image exceeds pixel limit");let p=this._coreTerminal._core.buffer,f=p.x,P=p.y,K=p.ybase,Ve=t.zIndex!==void 0&&t.zIndex<0?"bottom":"top";if(u!==i.width||E!==i.height){let L=await createImageBitmap(i,{resizeWidth:u,resizeHeight:E});i.close(),i=L}let oe=Math.min(Math.max(0,t.xOffset??0),I-1),he=Math.min(Math.max(0,t.yOffset??0),_-1);if(oe!==0||he!==0){let L=t.columns!==void 0?Math.round(l*I):i.width+oe,et=t.rows!==void 0?Math.round(C*_):i.height+he,Y=D.createCanvas(window.document,L,et),Le=Y.getContext("2d");if(!Le)throw new Error("Failed to create offset canvas context");Le.drawImage(i,oe,he);let tt=await createImageBitmap(Y);if(Y.width=Y.height=0,i.close(),i=tt,u=i.width,E=i.height,u*E>this._opts.pixelLimit)throw new Error("image exceeds pixel limit");t.columns===void 0&&(l=Math.ceil(i.width/I)),t.rows===void 0&&(C=Math.ceil(i.height/_))}let $e=t.zIndex??0;if(this._kittyStorage.addImage(e.id,i,!0,Ve,$e),i=void 0,t.cursorMovement===1){let L=p.ybase-K;p.x=f,p.y=Math.max(P-L,0)}else p.x=Math.min(f+l,this._coreTerminal.cols)}catch(A){throw i?.close(),A}}async _createBitmap(e){let t=new Uint8Array(await e.data.arrayBuffer());if(e.compression==="z"&&(t=await this._decompressZlib(t)),e.format===100){let u=new Blob([t],{type:"image/png"});if(!window.createImageBitmap){let E=URL.createObjectURL(u),p=new Image;return new Promise((f,P)=>{p.addEventListener("load",()=>{URL.revokeObjectURL(E);let K=D.createCanvas(window.document,p.width,p.height);K.getContext("2d")?.drawImage(p,0,0),createImageBitmap(K).then(f).catch(P)}),p.addEventListener("error",()=>{URL.revokeObjectURL(E),P(new Error("Failed to load image"))}),p.src=E})}return createImageBitmap(u)}let i=e.width,A=e.height;if(!i||!A)throw new Error("Width and height required for raw pixel data");let r=e.format===32?4:3,a=i*A*r;if(t.length<a)throw new Error("Insufficient pixel data");let n=i*A;if(e.format===32)return createImageBitmap(new ImageData(new Uint8ClampedArray(t.buffer,t.byteOffset,n*4),i,A));let o=new Uint8ClampedArray(n*4),d=new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4)),h=new Uint32Array(o.buffer),g=n&-4,I=0,_=0;for(let u=0;u<g;u+=4){let E=d[I++],p=d[I++],f=d[I++];h[_++]=4278190080|E,h[_++]=4278190080|E>>>24|p<<8,h[_++]=4278190080|p>>>16|f<<16,h[_++]=4278190080|f>>>8}let l=g*3,C=g*4;for(let u=g;u<n;u++)o[C]=t[l],o[C+1]=t[l+1],o[C+2]=t[l+2],o[C+3]=255,l+=3,C+=4;return createImageBitmap(new ImageData(o,i,A))}async _decompressZlib(e){try{return await this._decompress(e,"deflate")}catch{return await this._decompress(e,"deflate-raw")}}async _decompress(e,t){let i=new DecompressionStream(t),A=i.writable.getWriter();A.write(e),A.close();let r=[],a=i.readable.getReader();for(;;){let{done:h,value:g}=await a.read();if(h)break;r.push(g)}let n=r.reduce((h,g)=>h+g.length,0),o=new Uint8Array(n),d=0;for(let h of r)o.set(h,d),d+=h.length;return o}get images(){return this._kittyStorage.images}get _kittyIdToStorageId(){return this._kittyStorage.kittyIdToStorageId}get pendingTransmissions(){return this._pendingTransmissions}};var G=class G{constructor(e){this._storage=e;this._nextImageId=1;this._images=new Map;this._kittyIdToStorageId=new Map;this._storageIdToKittyId=new Map;this._handleStorageImageDeleted=e=>{let t=this._storageIdToKittyId.get(e);t!==void 0&&(this._kittyIdToStorageId.delete(t),this._storageIdToKittyId.delete(e),this._images.delete(t))};this._addImageOpts={scrolling:!0,layer:"top",zIndex:0,cursorPos:"iip"};this._previousOnImageDeleted=this._storage.onImageDeleted,this._wrappedOnImageDeleted=t=>{this._previousOnImageDeleted?.(t),this._handleStorageImageDeleted(t)},this._storage.onImageDeleted=this._wrappedOnImageDeleted}reset(){this._nextImageId=1,this._images.clear(),this._kittyIdToStorageId.clear(),this._storageIdToKittyId.clear()}dispose(){this.reset(),this._storage.onImageDeleted===this._wrappedOnImageDeleted&&(this._storage.onImageDeleted=this._previousOnImageDeleted)}storeImage(e,t){let i=e??this._nextImageId++,A=this._kittyIdToStorageId.get(i);return A!==void 0&&(this._storage.deleteImage(A),this._kittyIdToStorageId.delete(i),this._storageIdToKittyId.delete(A)),!this._images.has(i)&&this._images.size>=G._maxStoredImages&&this._evictUndisplayedImages(),this._images.set(i,{...t,id:i}),i}addImage(e,t,i,A,r){let a=this._kittyIdToStorageId.get(e);a!==void 0&&this._storageIdToKittyId.delete(a),this._addImageOpts.scrolling=i,this._addImageOpts.layer=A,this._addImageOpts.zIndex=r;let n=this._storage.addImage(t,this._addImageOpts);this._kittyIdToStorageId.set(e,n),this._storageIdToKittyId.set(n,e)}getImage(e){return this._images.get(e)}deleteById(e){this._images.delete(e);let t=this._kittyIdToStorageId.get(e);t!==void 0&&(this._storage.deleteImage(t),this._kittyIdToStorageId.delete(e),this._storageIdToKittyId.delete(t))}deleteAll(){this._images.clear();for(let e of this._kittyIdToStorageId.values())this._storage.deleteImage(e);this._kittyIdToStorageId.clear(),this._storageIdToKittyId.clear()}get images(){return this._images}get kittyIdToStorageId(){return this._kittyIdToStorageId}get lastImageId(){return this._nextImageId-1}_evictUndisplayedImages(){for(let[e]of this._images){if(this._images.size<=G._maxStoredImages/2)break;this._kittyIdToStorageId.has(e)||this._images.delete(e)}}};G._maxStoredImages=256;var te=G;var y=x(z());var ze=x(We());var xt=4194304,Se=y.PALETTE_ANSI_256;Se.set(y.PALETTE_VT340_COLOR);var se=class{constructor(e,t,i){this._opts=e;this._storage=t;this._coreTerminal=i;this._size=0;this._aborted=!1;(0,ze.DecoderAsync)({memoryLimit:this._opts.pixelLimit*4,palette:Se,paletteLimit:this._opts.sixelPaletteLimit}).then(A=>this._dec=A)}reset(){this._dec&&(this._dec.release(),this._dec._palette.fill(0),this._dec.init(0,Se,this._opts.sixelPaletteLimit))}hook(e){if(this._size=0,this._aborted=!1,this._dec){let t=e.params[1]===1?0:Mt(this._coreTerminal._core._inputHandler._curAttrData,this._coreTerminal._core._themeService?.colors);this._dec.init(t,null,this._opts.sixelPaletteLimit)}}put(e,t,i){if(!(this._aborted||!this._dec)){if(this._size+=i-t,this._size>this._opts.sixelSizeLimit){console.warn("SIXEL: too much data, aborting"),this._aborted=!0,this._dec.release();return}try{this._dec.decode(e,t,i)}catch(A){console.warn(`SIXEL: error while decoding image - ${A}`),this._aborted=!0,this._dec.release()}}}unhook(e){if(this._aborted||!e||!this._dec)return!0;let t=this._dec.width,i=this._dec.height;if(!t||!i)return i&&this._storage.advanceCursor(i),!0;let A=D.createCanvas(void 0,t,i);return A.getContext("2d")?.putImageData(new ImageData(this._dec.data8,t,i),0,0),this._dec.memoryUsage>xt&&this._dec.release(),this._storage.addImage(A),!0}};function Mt(s,e){let t=0;if(!e)return t;if(s.isInverse())if(s.isFgDefault())t=re(e.foreground.rgba);else if(s.isFgRGB()){let i=s.constructor.toColorRGB(s.getFgColor());t=(0,y.toRGBA8888)(...i)}else t=re(e.ansi[s.getFgColor()].rgba);else if(s.isBgDefault())t=re(e.background.rgba);else if(s.isBgRGB()){let i=s.constructor.toColorRGB(s.getBgColor());t=(0,y.toRGBA8888)(...i)}else t=re(e.ansi[s.getBgColor()].rgba);return t}function re(s){return y.BIG_ENDIAN?s:(s&255)<<24|(s>>>8&255)<<16|(s>>>16&255)<<8|s>>>24&255}var ne=class{constructor(e,t,i,A){this._storage=e;this._opts=t;this._renderer=i;this._terminal=A;this._addImageOpts={scrolling:!0,layer:"top",zIndex:0,cursorPos:"vt340"}}addImage(e){this._addImageOpts.scrolling=this._opts.sixelScrolling,this._storage.addImage(e,this._addImageOpts)}advanceCursor(e){if(this._opts.sixelScrolling){let t=this._renderer.cellSize;(t.width===-1||t.height===-1)&&(t=w);let i=Math.ceil(e/t.height);for(let A=1;A<i;++A)this._terminal._core._inputHandler.lineFeed()}}};var ae=class{constructor(e){this._storage=e;this._addImageOpts={scrolling:!0,layer:"top",zIndex:0,cursorPos:"iip"}}addImage(e){this._storage.addImage(e,this._addImageOpts)}};var Xe={enableSizeReports:!0,pixelLimit:16777216,sixelSupport:!0,sixelScrolling:!0,sixelPaletteLimit:4096,sixelSizeLimit:33554432,storageLimit:128,showPlaceholder:!0,iipSupport:!0,iipSizeLimit:33554432,kittySupport:!0,kittySizeLimit:33554432},Ze=4096;var je=class{constructor(e){this._disposables=[];this._handlers=new Map;this._onImageAdded=new W;this.onImageAdded=this._onImageAdded.event;this._opts=Object.assign({},Xe,e),this._defaultOpts=Object.assign({},Xe,e)}dispose(){for(let e of this._disposables)e.dispose();this._disposables.length=0,this._handlers.clear(),this._onImageAdded.dispose()}_disposeLater(...e){for(let t of e)this._disposables.push(t)}activate(e){if(this._terminal=e,this._renderer=new D(e),this._storage=new Z(e,this._renderer,this._opts),this._storage.onImageAdded=()=>this._onImageAdded.fire(),this._opts.enableSizeReports){let t=e.options.windowOptions??{};t.getWinSizePixels=!0,t.getCellSizePixels=!0,t.getWinSizeChars=!0,e.options.windowOptions=t}if(this._disposeLater(this._renderer,this._storage,e.parser.registerCsiHandler({prefix:"?",final:"h"},t=>this._decset(t)),e.parser.registerCsiHandler({prefix:"?",final:"l"},t=>this._decrst(t)),e.parser.registerCsiHandler({final:"c"},t=>this._da1(t)),e.parser.registerCsiHandler({prefix:"?",final:"S"},t=>this._xtermGraphicsAttributes(t)),e.onRender(t=>this._storage?.render(t)),e.parser.registerCsiHandler({intermediates:"!",final:"p"},()=>this.reset()),e.parser.registerEscHandler({final:"c"},()=>this.reset()),e._core._inputHandler.onRequestReset(()=>this.reset()),e.buffer.onBufferChange(()=>this._storage?.wipeAlternate()),e.onResize(t=>this._storage?.viewportResize(t))),this._opts.sixelSupport){let t=new ne(this._storage,this._opts,this._renderer,e),i=new se(this._opts,t,e);this._handlers.set("sixel",i),this._disposeLater(e._core._inputHandler._parser.registerDcsHandler({final:"q"},i))}if(this._opts.iipSupport){let t=new ae(this._storage),i=new $(this._opts,this._renderer,t,e);this._handlers.set("iip",i),this._disposeLater(e._core._inputHandler._parser.registerOscHandler(1337,i))}if(this._opts.kittySupport){let t=new te(this._storage),i=new ee(this._opts,this._renderer,t,e);this._handlers.set("kitty",i),this._disposeLater(t,i,e._core._inputHandler._parser.registerApcHandler({final:"G"},i))}}reset(){this._opts.sixelScrolling=this._defaultOpts.sixelScrolling,this._opts.sixelPaletteLimit=this._defaultOpts.sixelPaletteLimit,this._storage?.reset();for(let e of this._handlers.values())e.reset();return!1}get storageLimit(){return this._storage?.getLimit()||-1}set storageLimit(e){this._storage?.setLimit(e),this._opts.storageLimit=e}get storageUsage(){return this._storage?this._storage.getUsage():-1}get showPlaceholder(){return this._opts.showPlaceholder}set showPlaceholder(e){this._opts.showPlaceholder=e,this._renderer?.showPlaceholder(e)}getImageAtBufferCell(e,t){return this._storage?.getImageAtBufferCell(e,t)}extractTileAtBufferCell(e,t){return this._storage?.extractTileAtBufferCell(e,t)}_report(e){this._terminal?._core.input(e,!1)}_decset(e){for(let t=0;t<e.length;++t)e[t]===80&&(this._opts.sixelScrolling=!1);return!1}_decrst(e){for(let t=0;t<e.length;++t)e[t]===80&&(this._opts.sixelScrolling=!0);return!1}_da1(e){return e[0]?!0:this._opts.sixelSupport?(this._report("\x1B[?62;4;9;22c"),!0):!1}_xtermGraphicsAttributes(e){if(e.length<2)return!0;if(e[0]===1)switch(e[1]){case 1:return this._report(`\x1B[?${e[0]};0;${this._opts.sixelPaletteLimit}S`),!0;case 2:this._opts.sixelPaletteLimit=this._defaultOpts.sixelPaletteLimit,this._report(`\x1B[?${e[0]};0;${this._opts.sixelPaletteLimit}S`);for(let t of this._handlers.values())t.reset();return!0;case 3:return e.length>2&&!(e[2]instanceof Array)&&e[2]<=Ze?(this._opts.sixelPaletteLimit=e[2],this._report(`\x1B[?${e[0]};0;${this._opts.sixelPaletteLimit}S`)):this._report(`\x1B[?${e[0]};2S`),!0;case 4:return this._report(`\x1B[?${e[0]};0;${Ze}S`),!0;default:return this._report(`\x1B[?${e[0]};2S`),!0}if(e[0]===2)switch(e[1]){case 1:let t=this._renderer?.dimensions?.css.canvas.width,i=this._renderer?.dimensions?.css.canvas.height;if(!t||!i){let r=w;t=(this._terminal?.cols||80)*r.width,i=(this._terminal?.rows||24)*r.height}if(t*i<this._opts.pixelLimit)this._report(`\x1B[?${e[0]};0;${t.toFixed(0)};${i.toFixed(0)}S`);else{let r=Math.floor(Math.sqrt(this._opts.pixelLimit));this._report(`\x1B[?${e[0]};0;${r};${r}S`)}return!0;case 4:let A=Math.floor(Math.sqrt(this._opts.pixelLimit));return this._report(`\x1B[?${e[0]};0;${A};${A}S`),!0;default:return this._report(`\x1B[?${e[0]};2S`),!0}return this._report(`\x1B[?${e[0]};1S`),!0}};export{je as ImageAddon};
//# sourceMappingURL=addon-image.mjs.map
