teapot-coding-agent 0.37.172 → 0.37.174

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,29 +1,29 @@
1
1
  const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/astro-BZ97kZFP.js","assets/json-B88Oqtu5.js","assets/javascript-BzbQS41l.js","assets/typescript-j_1H8WHN.js","assets/css-BGIxQoYs.js","assets/postcss-D_Wz94rJ.js","assets/tsx-BOvsFOI6.js","assets/c-Cz4nF6n_.js","assets/c-SSSlmE39.js","assets/cpp-B6pWdJV2.js","assets/cpp-ZGiJKGk8.js","assets/glsl-CaPTrB3a.js","assets/css-DgaLhXQH.js","assets/elixir-raGDl1oO.js","assets/html-DSw1lh5G.js","assets/erlang-D0CaQ5Pl.js","assets/markdown-CboqBxpY.js","assets/fsharp-PZeu-6rm.js","assets/graphql-BZEhxNwM.js","assets/graphql-DEIChqxY.js","assets/jsx-D3KKoC5L.js","assets/html-BCy9P6D2.js","assets/java-_ATy9zCa.js","assets/java-BtIQNnN0.js","assets/javascript-CpIGwZ_Y.js","assets/json-C3WlssX3.js","assets/jsx-C4yDKi0A.js","assets/julia-DCfl8sf8.js","assets/python-CzFU0dpx.js","assets/r-DWzjseEo.js","assets/sql-CNu3Or2W.js","assets/justfile-CKP9W7x6.js","assets/shellscript-CqHdAlCp.js","assets/perl-XQDPZEjP.js","assets/xml-WY0zc4PG.js","assets/ruby-DV2UBOs2.js","assets/lua-DjuecEsk.js","assets/yaml-DijMHRDA.js","assets/lua-fPRBWD-V.js","assets/markdown-CjQmuOi1.js","assets/nim-VAaFSKwL.js","assets/perl-BTdIRyOQ.js","assets/php-DPoYWQt_.js","assets/postcss-DkKB82OS.js","assets/python-C5TF47hQ.js","assets/r-BXEss897.js","assets/ruby-BdDtUACQ.js","assets/scss-8bKmll0B.js","assets/shellscript-CVTB3cr6.js","assets/sql-CfM2IJm3.js","assets/svelte-CdeT-Ich.js","assets/tsx-CGosfAUg.js","assets/typescript-Bb1J8qyy.js","assets/vue-BqdMUtqy.js","assets/xml-DuKfbPI6.js","assets/yaml-DDA_XMNu.js"])))=>i.map(i=>d[i]);
2
- var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n||e(r,Symbol.toStringTag,{value:`Module`}),r};(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var n={context:void 0,registry:void 0,effects:void 0,done:!1,getContextId(){return r(this.context.count)},getNextContextId(){return r(this.context.count++)}};function r(e){let t=String(e),r=t.length-1;return n.context.id+(r?String.fromCharCode(96+r):``)+t}function i(e){n.context=e}var a=(e,t)=>e===t,o=Symbol(`solid-track`),s={equals:a},c=null,l=ue,u=1,d=2,f={owned:null,cleanups:null,context:null,owner:null},p=null,m=null,h=null,g=null,_=null,v=0;function ee(e,t){let n=h,r=p,i=e.length===0,a=t===void 0?r:t,o=i?f:{owned:null,cleanups:null,context:a?a.context:null,owner:a},s=i?e:()=>e(()=>C(()=>k(o)));p=o,h=null;try{return ce(s,!0)}finally{h=n,p=r}}function y(e,t){t=t?Object.assign({},s,t):s;let n={value:e,observers:null,observerSlots:null,comparator:t.equals||void 0};return[re.bind(n),e=>(typeof e==`function`&&(e=m&&m.running&&m.sources.has(n)?e(n.tValue):e(n.value)),ie(n,e))]}function b(e,t,n){O(oe(e,t,!1,u))}function x(e,t,n){l=de;let r=oe(e,t,!1,u),i=ne&&D(ne);i&&(r.suspense=i),(!n||!n.render)&&(r.user=!0),_?_.push(r):O(r)}function S(e,t,n){n=n?Object.assign({},s,n):s;let r=oe(e,t,!0,0);return r.observers=null,r.observerSlots=null,r.comparator=n.equals||void 0,O(r),re.bind(r)}function C(e){if(h===null)return e();let t=h;h=null;try{return e()}finally{h=t}}function w(e){x(()=>C(e))}function T(e){return p===null||(p.cleanups===null?p.cleanups=[e]:p.cleanups.push(e)),e}var[te,E]=y(!1);function D(e){let t;return p&&p.context&&(t=p.context[e.id])!==void 0?t:e.defaultValue}var ne;function re(){let e=m&&m.running;if(this.sources&&(e?this.tState:this.state)){if((e?this.tState:this.state)===u)O(this);else{let e=g;g=null,ce(()=>fe(this),!1),g=e}}if(h){let e=this.observers;if(!e||e[e.length-1]!==h){let t=e?e.length:0;h.sources?(h.sources.push(this),h.sourceSlots.push(t)):(h.sources=[this],h.sourceSlots=[t]),e?(e.push(h),this.observerSlots.push(h.sources.length-1)):(this.observers=[h],this.observerSlots=[h.sources.length-1])}}return e&&m.sources.has(this)?this.tValue:this.value}function ie(e,t,n){let r=m&&m.running&&m.sources.has(e)?e.tValue:e.value;if(!e.comparator||!e.comparator(r,t)){if(m){let r=m.running;(r||!n&&m.sources.has(e))&&(m.sources.add(e),e.tValue=t),r||(e.value=t)}else e.value=t;e.observers&&e.observers.length&&ce(()=>{for(let t=0;t<e.observers.length;t+=1){let n=e.observers[t],r=m&&m.running;r&&m.disposed.has(n)||((r?!n.tState:!n.state)&&(n.pure?g.push(n):_.push(n),n.observers&&pe(n)),r?n.tState=u:n.state=u)}if(g.length>1e6)throw g=[],Error()},!1)}return t}function O(e){if(!e.fn)return;k(e);let t=v;ae(e,m&&m.running&&m.sources.has(e)?e.tValue:e.value,t),m&&!m.running&&m.sources.has(e)&&queueMicrotask(()=>{ce(()=>{m&&(m.running=!0),h=p=e,ae(e,e.tValue,t),h=p=null},!1)})}function ae(e,t,n){let r,i=p,a=h;h=p=e;try{r=e.fn(t)}catch(t){return e.pure&&(m&&m.running?(e.tState=u,e.tOwned&&e.tOwned.forEach(k),e.tOwned=void 0):(e.state=u,e.owned&&e.owned.forEach(k),e.owned=null)),e.updatedAt=n+1,_e(t)}finally{h=a,p=i}(!e.updatedAt||e.updatedAt<=n)&&(e.updatedAt!=null&&`observers`in e?ie(e,r,!0):m&&m.running&&e.pure?(m.sources.has(e)||(e.value=r),m.sources.add(e),e.tValue=r):e.value=r,e.updatedAt=n)}function oe(e,t,n,r=u,i){let a={fn:e,state:r,updatedAt:null,owned:null,sources:null,sourceSlots:null,cleanups:null,value:t,owner:p,context:p?p.context:null,pure:n};return m&&m.running&&(a.state=0,a.tState=r),p===null||p!==f&&(m&&m.running&&p.pure?p.tOwned?p.tOwned.push(a):p.tOwned=[a]:p.owned?p.owned.push(a):p.owned=[a]),a}function se(e){let t=m&&m.running;if((t?e.tState:e.state)===0)return;if((t?e.tState:e.state)===d)return fe(e);if(e.suspense&&C(e.suspense.inFallback))return e.suspense.effects.push(e);let n=[e];for(;(e=e.owner)&&(!e.updatedAt||e.updatedAt<v);){if(t&&m.disposed.has(e))return;(t?e.tState:e.state)&&n.push(e)}for(let r=n.length-1;r>=0;r--){if(e=n[r],t){let t=e,i=n[r+1];for(;(t=t.owner)&&t!==i;)if(m.disposed.has(t))return}if((t?e.tState:e.state)===u)O(e);else if((t?e.tState:e.state)===d){let t=g;g=null,ce(()=>fe(e,n[0]),!1),g=t}}}function ce(e,t){if(g)return e();let n=!1;t||(g=[]),_?n=!0:_=[],v++;try{let t=e();return le(n),t}catch(e){n||(_=null),g=null,_e(e)}}function le(e){if(g&&=(ue(g),null),e)return;let t;if(m){if(!m.promises.size&&!m.queue.size){let e=m.sources,n=m.disposed;_.push.apply(_,m.effects),t=m.resolve;for(let e of _)`tState`in e&&(e.state=e.tState),delete e.tState;m=null,ce(()=>{for(let e of n)k(e);for(let t of e){if(t.value=t.tValue,t.owned)for(let e=0,n=t.owned.length;e<n;e++)k(t.owned[e]);t.tOwned&&(t.owned=t.tOwned),delete t.tValue,delete t.tOwned,t.tState=0}E(!1)},!1)}else if(m.running){m.running=!1,m.effects.push.apply(m.effects,_),_=null,E(!0);return}}let n=_;_=null,n.length&&ce(()=>l(n),!1),t&&t()}function ue(e){for(let t=0;t<e.length;t++)se(e[t])}function de(e){let t,r=0;for(t=0;t<e.length;t++){let n=e[t];n.user?e[r++]=n:se(n)}if(n.context){if(n.count){n.effects||=[],n.effects.push(...e.slice(0,r));return}i()}for(n.effects&&(n.done||!n.count)&&(e=[...n.effects,...e],r+=n.effects.length,delete n.effects),t=0;t<r;t++)se(e[t])}function fe(e,t){let n=m&&m.running;n?e.tState=0:e.state=0;for(let r=0;r<e.sources.length;r+=1){let i=e.sources[r];if(i.sources){let e=n?i.tState:i.state;e===u?i!==t&&(!i.updatedAt||i.updatedAt<v)&&se(i):e===d&&fe(i,t)}}}function pe(e){let t=m&&m.running;for(let n=0;n<e.observers.length;n+=1){let r=e.observers[n];(t?!r.tState:!r.state)&&(t?r.tState=d:r.state=d,r.pure?g.push(r):_.push(r),r.observers&&pe(r))}}function k(e){let t;if(e.sources)for(;e.sources.length;){let t=e.sources.pop(),n=e.sourceSlots.pop(),r=t.observers;if(r&&r.length){let e=r.pop(),i=t.observerSlots.pop();n<r.length&&(e.sourceSlots[i]=n,r[n]=e,t.observerSlots[n]=i)}}if(e.tOwned){for(t=e.tOwned.length-1;t>=0;t--)k(e.tOwned[t]);delete e.tOwned}if(m&&m.running&&e.pure)me(e,!0);else if(e.owned){for(t=e.owned.length-1;t>=0;t--)k(e.owned[t]);e.owned=null}if(e.cleanups){for(t=e.cleanups.length-1;t>=0;t--)e.cleanups[t]();e.cleanups=null}m&&m.running?e.tState=0:e.state=0}function me(e,t){if(t||(e.tState=0,m.disposed.add(e)),e.owned)for(let t=0;t<e.owned.length;t++)me(e.owned[t])}function he(e){return e instanceof Error?e:Error(typeof e==`string`?e:`Unknown error`,{cause:e})}function ge(e,t,n){try{for(let n of t)n(e)}catch(e){_e(e,n&&n.owner||null)}}function _e(e,t=p){let n=c&&t&&t.context&&t.context[c],r=he(e);if(!n)throw r;_?_.push({fn(){ge(r,n,t)},state:u}):ge(r,n,t)}var ve=Symbol(`fallback`);function ye(e){for(let t=0;t<e.length;t++)e[t]()}function be(e,t,n={}){let r=[],i=[],a=[],s=0,c=t.length>1?[]:null;return T(()=>ye(a)),()=>{let l=e()||[],u=l.length,d,f;return l[o],C(()=>{let e,t,o,m,h,g,_,v,y;if(u===0)s!==0&&(ye(a),a=[],r=[],i=[],s=0,c&&=[]),n.fallback&&(r=[ve],i[0]=ee(e=>(a[0]=e,n.fallback())),s=1);else if(s===0){for(i=Array(u),f=0;f<u;f++)r[f]=l[f],i[f]=ee(p);s=u}else{for(o=Array(u),m=Array(u),c&&(h=Array(u)),g=0,_=Math.min(s,u);g<_&&r[g]===l[g];g++);for(_=s-1,v=u-1;_>=g&&v>=g&&r[_]===l[v];_--,v--)o[v]=i[_],m[v]=a[_],c&&(h[v]=c[_]);for(e=new Map,t=Array(v+1),f=v;f>=g;f--)y=l[f],d=e.get(y),t[f]=d===void 0?-1:d,e.set(y,f);for(d=g;d<=_;d++)y=r[d],f=e.get(y),f!==void 0&&f!==-1?(o[f]=i[d],m[f]=a[d],c&&(h[f]=c[d]),f=t[f],e.set(y,f)):a[d]();for(f=g;f<u;f++)f in o?(i[f]=o[f],a[f]=m[f],c&&(c[f]=h[f],c[f](f))):i[f]=ee(p);i=i.slice(0,s=u),r=l.slice(0)}return i});function p(e){if(a[f]=e,c){let[e,n]=y(f);return c[f]=n,t(l[f],e)}return t(l[f])}}}function xe(e,t,n={}){let r=[],i=[],a=[],s=[],c=0,l;return T(()=>ye(a)),()=>{let u=e()||[],d=u.length;return u[o],C(()=>{if(d===0)return c!==0&&(ye(a),a=[],r=[],i=[],c=0,s=[]),n.fallback&&(r=[ve],i[0]=ee(e=>(a[0]=e,n.fallback())),c=1),i;for(r[0]===ve&&(a[0](),a=[],r=[],i=[],c=0),l=0;l<d;l++)l<r.length&&r[l]!==u[l]?s[l](()=>u[l]):l>=r.length&&(i[l]=ee(f));for(;l<r.length;l++)a[l]();return c=s.length=a.length=d,r=u.slice(0),i=i.slice(0,c)});function f(e){a[l]=e;let[n,r]=y(u[l]);return s[l]=r,t(n,l)}}}function A(e,t){return C(()=>e(t||{}))}var Se=e=>`Stale read from <${e}>.`;function j(e){let t=`fallback`in e&&{fallback:()=>e.fallback};return S(be(()=>e.each,e.children,t||void 0))}function Ce(e){let t=`fallback`in e&&{fallback:()=>e.fallback};return S(xe(()=>e.each,e.children,t||void 0))}function M(e){let t=e.keyed,n=S(()=>e.when,void 0,void 0),r=t?n:S(n,void 0,{equals:(e,t)=>!e==!t});return S(()=>{let i=r();if(i){let a=e.children;return typeof a==`function`&&a.length>0?C(()=>a(t?i:()=>{if(!C(r))throw Se(`Show`);return n()})):a}return e.fallback},void 0,void 0)}var N=e=>S(()=>e());function we(e,t,n){let r=n.length,i=t.length,a=r,o=0,s=0,c=t[i-1].nextSibling,l=null;for(;o<i||s<a;)if(t[o]===n[s])o++,s++;else{for(;t[i-1]===n[a-1];)i--,a--;if(i===o){let t=a<r?s?n[s-1].nextSibling:n[a-s]:c;for(;s<a;)e.insertBefore(n[s++],t)}else if(a===s)for(;o<i;)(!l||!l.has(t[o]))&&t[o].remove(),o++;else if(t[o]===n[a-1]&&n[s]===t[i-1]){let r=t[--i].nextSibling;e.insertBefore(n[s++],t[o++].nextSibling),e.insertBefore(n[--a],r),t[i]=n[a]}else{if(!l){l=new Map;let e=s;for(;e<a;)l.set(n[e],e++)}let r=l.get(t[o]);if(r!=null){if(s<r&&r<a){let c=o,u=1,d;for(;++c<i&&c<a&&(d=l.get(t[c]))!=null&&d===r+u;)u++;if(u>r-s){let i=t[o];for(;s<r;)e.insertBefore(n[s++],i)}else e.replaceChild(n[s++],t[o++])}else o++}else t[o++].remove()}}}var Te=`_$DX_DELEGATE`;function Ee(e,t,n,r={}){let i;return ee(r=>{i=r,t===document?e():L(t,e(),!n&&t.firstChild?null:void 0,n)},r.owner),()=>{i(),t.textContent=``}}function P(e,t,n,r){let i,a=()=>{let t=r?document.createElementNS(`http://www.w3.org/1998/Math/MathML`,`template`):document.createElement(`template`);return t.innerHTML=e,n?t.content.firstChild.firstChild:r?t.firstChild:t.content.firstChild},o=t?()=>C(()=>document.importNode(i||=a(),!0)):()=>(i||=a()).cloneNode(!0);return o.cloneNode=o,o}function De(e,t=window.document){let n=t[Te]||(t[Te]=new Set);for(let r=0,i=e.length;r<i;r++){let i=e[r];n.has(i)||(n.add(i),t.addEventListener(i,Ne))}}function F(e,t,n){Me(e)||(n==null?e.removeAttribute(t):e.setAttribute(t,n))}function I(e,t){Me(e)||(t==null?e.removeAttribute(`class`):e.className=t)}function Oe(e,t,n,r){if(r)Array.isArray(n)?(e[`$$${t}`]=n[0],e[`$$${t}Data`]=n[1]):e[`$$${t}`]=n;else if(Array.isArray(n)){let r=n[0];e.addEventListener(t,n[0]=t=>r.call(e,n[1],t))}else e.addEventListener(t,n,typeof n!=`function`&&n)}function ke(e,t,n){if(!t)return n?F(e,`style`):t;let r=e.style;if(typeof t==`string`)return r.cssText=t;typeof n==`string`&&(r.cssText=n=void 0),n||={},t||={};let i,a;for(a in n)t[a]??r.removeProperty(a),delete n[a];for(a in t)i=t[a],i!==n[a]&&(r.setProperty(a,i),n[a]=i);return n}function Ae(e,t,n){n==null?e.style.removeProperty(t):e.style.setProperty(t,n)}function je(e,t,n){return C(()=>e(t,n))}function L(e,t,n,r){if(n!==void 0&&!r&&(r=[]),typeof t!=`function`)return Pe(e,t,r,n);b(r=>Pe(e,t(),r,n),r)}function Me(e){return!!n.context&&!n.done&&(!e||e.isConnected)}function Ne(e){if(n.registry&&n.events&&n.events.find(([t,n])=>n===e))return;let t=e.target,r=`$$${e.type}`,i=e.target,a=e.currentTarget,o=t=>Object.defineProperty(e,"target",{configurable:!0,value:t}),s=()=>{let n=t[r];if(n&&!t.disabled){let i=t[`${r}Data`];if(i===void 0?n.call(t,e):n.call(t,i,e),e.cancelBubble)return}return t.host&&typeof t.host!=`string`&&!t.host._$host&&t.contains(e.target)&&o(t.host),!0},c=()=>{for(;s()&&(t=t._$host||t.parentNode||t.host););};Object.defineProperty(e,"currentTarget",{configurable:!0,get(){return t||document}}),n.registry&&!n.done&&(n.done=_$HY.done=!0);try{if(e.composedPath){let n=e.composedPath();o(n[0]);for(let e=0;e<n.length-2&&(t=n[e],s());e++){if(t._$host){t=t._$host,c();break}if(t.parentNode===a)break}}else c();o(i)}finally{e=t=null}}function Pe(e,t,n,r,i){let a=Me(e);if(a){!n&&(n=[...e.childNodes]);let t=[];for(let e=0;e<n.length;e++){let r=n[e];r.nodeType===8&&r.data.slice(0,2)===`!$`?r.remove():t.push(r)}n=t}for(;typeof n==`function`;)n=n();if(t===n)return n;let o=typeof t,s=r!==void 0;if(e=s&&n[0]&&n[0].parentNode||e,o===`string`||o===`number`){if(a||o===`number`&&(t=t.toString(),t===n))return n;if(s){let i=n[0];i&&i.nodeType===3?i.data!==t&&(i.data=t):i=document.createTextNode(t),n=Le(e,n,r,i)}else n=n!==``&&typeof n==`string`?e.firstChild.data=t:e.textContent=t}else if(t==null||o===`boolean`){if(a)return n;n=Le(e,n,r)}else if(o===`function`)return b(()=>{let i=t();for(;typeof i==`function`;)i=i();n=Pe(e,i,n,r)}),()=>n;else if(Array.isArray(t)){let o=[],c=n&&Array.isArray(n);if(Fe(o,t,n,i))return b(()=>n=Pe(e,o,n,r,!0)),()=>n;if(a){if(!o.length)return n;if(r===void 0)return n=[...e.childNodes];let t=o[0];if(t.parentNode!==e)return n;let i=[t];for(;(t=t.nextSibling)!==r;)i.push(t);return n=i}if(o.length===0){if(n=Le(e,n,r),s)return n}else c?n.length===0?Ie(e,o,r):we(e,n,o):(n&&Le(e),Ie(e,o));n=o}else if(t.nodeType){if(a&&t.parentNode)return n=s?[t]:t;if(Array.isArray(n)){if(s)return n=Le(e,n,r,t);Le(e,n,null,t)}else n==null||n===``||!e.firstChild?e.appendChild(t):e.replaceChild(t,e.firstChild);n=t}return n}function Fe(e,t,n,r){let i=!1;for(let a=0,o=t.length;a<o;a++){let o=t[a],s=n&&n[e.length],c;if(o!=null&&o!==!0&&o!==!1){if((c=typeof o)==`object`&&o.nodeType)e.push(o);else if(Array.isArray(o))i=Fe(e,o,s)||i;else if(c===`function`){if(r){for(;typeof o==`function`;)o=o();i=Fe(e,Array.isArray(o)?o:[o],Array.isArray(s)?s:[s])||i}else e.push(o),i=!0}else{let t=String(o);s&&s.nodeType===3&&s.data===t?e.push(s):e.push(document.createTextNode(t))}}}return i}function Ie(e,t,n=null){for(let r=0,i=t.length;r<i;r++)e.insertBefore(t[r],n)}function Le(e,t,n,r){if(n===void 0)return e.textContent=``;let i=r||document.createTextNode(``);if(t.length){let r=!1;for(let a=t.length-1;a>=0;a--){let o=t[a];if(i!==o){let t=o.parentNode===e;!r&&!a?t?e.replaceChild(i,o):e.insertBefore(i,n):t&&o.remove()}else r=!0}}else e.insertBefore(i,n);return[i]}var Re=/^(\s*)([-*+]|\d+[.)])\s+(.*)$/;function ze(e){return Be(Ue(e.replace(/\r\n/g,`
2
+ var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n||e(r,Symbol.toStringTag,{value:`Module`}),r};(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var n={context:void 0,registry:void 0,effects:void 0,done:!1,getContextId(){return r(this.context.count)},getNextContextId(){return r(this.context.count++)}};function r(e){let t=String(e),r=t.length-1;return n.context.id+(r?String.fromCharCode(96+r):``)+t}function i(e){n.context=e}var a=(e,t)=>e===t,o=Symbol(`solid-track`),s={equals:a},c=null,l=le,u=1,d=2,f={owned:null,cleanups:null,context:null,owner:null},p=null,m=null,h=null,g=null,_=null,v=0;function ee(e,t){let n=h,r=p,i=e.length===0,a=t===void 0?r:t,o=i?f:{owned:null,cleanups:null,context:a?a.context:null,owner:a},s=i?e:()=>e(()=>C(()=>A(o)));p=o,h=null;try{return se(s,!0)}finally{h=n,p=r}}function y(e,t){t=t?Object.assign({},s,t):s;let n={value:e,observers:null,observerSlots:null,comparator:t.equals||void 0};return[ne.bind(n),e=>(typeof e==`function`&&(e=m&&m.running&&m.sources.has(n)?e(n.tValue):e(n.value)),re(n,e))]}function b(e,t,n){k(ae(e,t,!1,u))}function x(e,t,n){l=ue;let r=ae(e,t,!1,u),i=te&&O(te);i&&(r.suspense=i),(!n||!n.render)&&(r.user=!0),_?_.push(r):k(r)}function S(e,t,n){n=n?Object.assign({},s,n):s;let r=ae(e,t,!0,0);return r.observers=null,r.observerSlots=null,r.comparator=n.equals||void 0,k(r),ne.bind(r)}function C(e){if(h===null)return e();let t=h;h=null;try{return e()}finally{h=t}}function w(e){x(()=>C(e))}function T(e){return p===null||(p.cleanups===null?p.cleanups=[e]:p.cleanups.push(e)),e}var[E,D]=y(!1);function O(e){let t;return p&&p.context&&(t=p.context[e.id])!==void 0?t:e.defaultValue}var te;function ne(){let e=m&&m.running;if(this.sources&&(e?this.tState:this.state)){if((e?this.tState:this.state)===u)k(this);else{let e=g;g=null,se(()=>de(this),!1),g=e}}if(h){let e=this.observers;if(!e||e[e.length-1]!==h){let t=e?e.length:0;h.sources?(h.sources.push(this),h.sourceSlots.push(t)):(h.sources=[this],h.sourceSlots=[t]),e?(e.push(h),this.observerSlots.push(h.sources.length-1)):(this.observers=[h],this.observerSlots=[h.sources.length-1])}}return e&&m.sources.has(this)?this.tValue:this.value}function re(e,t,n){let r=m&&m.running&&m.sources.has(e)?e.tValue:e.value;if(!e.comparator||!e.comparator(r,t)){if(m){let r=m.running;(r||!n&&m.sources.has(e))&&(m.sources.add(e),e.tValue=t),r||(e.value=t)}else e.value=t;e.observers&&e.observers.length&&se(()=>{for(let t=0;t<e.observers.length;t+=1){let n=e.observers[t],r=m&&m.running;r&&m.disposed.has(n)||((r?!n.tState:!n.state)&&(n.pure?g.push(n):_.push(n),n.observers&&fe(n)),r?n.tState=u:n.state=u)}if(g.length>1e6)throw g=[],Error()},!1)}return t}function k(e){if(!e.fn)return;A(e);let t=v;ie(e,m&&m.running&&m.sources.has(e)?e.tValue:e.value,t),m&&!m.running&&m.sources.has(e)&&queueMicrotask(()=>{se(()=>{m&&(m.running=!0),h=p=e,ie(e,e.tValue,t),h=p=null},!1)})}function ie(e,t,n){let r,i=p,a=h;h=p=e;try{r=e.fn(t)}catch(t){return e.pure&&(m&&m.running?(e.tState=u,e.tOwned&&e.tOwned.forEach(A),e.tOwned=void 0):(e.state=u,e.owned&&e.owned.forEach(A),e.owned=null)),e.updatedAt=n+1,ge(t)}finally{h=a,p=i}(!e.updatedAt||e.updatedAt<=n)&&(e.updatedAt!=null&&`observers`in e?re(e,r,!0):m&&m.running&&e.pure?(m.sources.has(e)||(e.value=r),m.sources.add(e),e.tValue=r):e.value=r,e.updatedAt=n)}function ae(e,t,n,r=u,i){let a={fn:e,state:r,updatedAt:null,owned:null,sources:null,sourceSlots:null,cleanups:null,value:t,owner:p,context:p?p.context:null,pure:n};return m&&m.running&&(a.state=0,a.tState=r),p===null||p!==f&&(m&&m.running&&p.pure?p.tOwned?p.tOwned.push(a):p.tOwned=[a]:p.owned?p.owned.push(a):p.owned=[a]),a}function oe(e){let t=m&&m.running;if((t?e.tState:e.state)===0)return;if((t?e.tState:e.state)===d)return de(e);if(e.suspense&&C(e.suspense.inFallback))return e.suspense.effects.push(e);let n=[e];for(;(e=e.owner)&&(!e.updatedAt||e.updatedAt<v);){if(t&&m.disposed.has(e))return;(t?e.tState:e.state)&&n.push(e)}for(let r=n.length-1;r>=0;r--){if(e=n[r],t){let t=e,i=n[r+1];for(;(t=t.owner)&&t!==i;)if(m.disposed.has(t))return}if((t?e.tState:e.state)===u)k(e);else if((t?e.tState:e.state)===d){let t=g;g=null,se(()=>de(e,n[0]),!1),g=t}}}function se(e,t){if(g)return e();let n=!1;t||(g=[]),_?n=!0:_=[],v++;try{let t=e();return ce(n),t}catch(e){n||(_=null),g=null,ge(e)}}function ce(e){if(g&&=(le(g),null),e)return;let t;if(m){if(!m.promises.size&&!m.queue.size){let e=m.sources,n=m.disposed;_.push.apply(_,m.effects),t=m.resolve;for(let e of _)`tState`in e&&(e.state=e.tState),delete e.tState;m=null,se(()=>{for(let e of n)A(e);for(let t of e){if(t.value=t.tValue,t.owned)for(let e=0,n=t.owned.length;e<n;e++)A(t.owned[e]);t.tOwned&&(t.owned=t.tOwned),delete t.tValue,delete t.tOwned,t.tState=0}D(!1)},!1)}else if(m.running){m.running=!1,m.effects.push.apply(m.effects,_),_=null,D(!0);return}}let n=_;_=null,n.length&&se(()=>l(n),!1),t&&t()}function le(e){for(let t=0;t<e.length;t++)oe(e[t])}function ue(e){let t,r=0;for(t=0;t<e.length;t++){let n=e[t];n.user?e[r++]=n:oe(n)}if(n.context){if(n.count){n.effects||=[],n.effects.push(...e.slice(0,r));return}i()}for(n.effects&&(n.done||!n.count)&&(e=[...n.effects,...e],r+=n.effects.length,delete n.effects),t=0;t<r;t++)oe(e[t])}function de(e,t){let n=m&&m.running;n?e.tState=0:e.state=0;for(let r=0;r<e.sources.length;r+=1){let i=e.sources[r];if(i.sources){let e=n?i.tState:i.state;e===u?i!==t&&(!i.updatedAt||i.updatedAt<v)&&oe(i):e===d&&de(i,t)}}}function fe(e){let t=m&&m.running;for(let n=0;n<e.observers.length;n+=1){let r=e.observers[n];(t?!r.tState:!r.state)&&(t?r.tState=d:r.state=d,r.pure?g.push(r):_.push(r),r.observers&&fe(r))}}function A(e){let t;if(e.sources)for(;e.sources.length;){let t=e.sources.pop(),n=e.sourceSlots.pop(),r=t.observers;if(r&&r.length){let e=r.pop(),i=t.observerSlots.pop();n<r.length&&(e.sourceSlots[i]=n,r[n]=e,t.observerSlots[n]=i)}}if(e.tOwned){for(t=e.tOwned.length-1;t>=0;t--)A(e.tOwned[t]);delete e.tOwned}if(m&&m.running&&e.pure)pe(e,!0);else if(e.owned){for(t=e.owned.length-1;t>=0;t--)A(e.owned[t]);e.owned=null}if(e.cleanups){for(t=e.cleanups.length-1;t>=0;t--)e.cleanups[t]();e.cleanups=null}m&&m.running?e.tState=0:e.state=0}function pe(e,t){if(t||(e.tState=0,m.disposed.add(e)),e.owned)for(let t=0;t<e.owned.length;t++)pe(e.owned[t])}function me(e){return e instanceof Error?e:Error(typeof e==`string`?e:`Unknown error`,{cause:e})}function he(e,t,n){try{for(let n of t)n(e)}catch(e){ge(e,n&&n.owner||null)}}function ge(e,t=p){let n=c&&t&&t.context&&t.context[c],r=me(e);if(!n)throw r;_?_.push({fn(){he(r,n,t)},state:u}):he(r,n,t)}var _e=Symbol(`fallback`);function ve(e){for(let t=0;t<e.length;t++)e[t]()}function ye(e,t,n={}){let r=[],i=[],a=[],s=0,c=t.length>1?[]:null;return T(()=>ve(a)),()=>{let l=e()||[],u=l.length,d,f;return l[o],C(()=>{let e,t,o,m,h,g,_,v,y;if(u===0)s!==0&&(ve(a),a=[],r=[],i=[],s=0,c&&=[]),n.fallback&&(r=[_e],i[0]=ee(e=>(a[0]=e,n.fallback())),s=1);else if(s===0){for(i=Array(u),f=0;f<u;f++)r[f]=l[f],i[f]=ee(p);s=u}else{for(o=Array(u),m=Array(u),c&&(h=Array(u)),g=0,_=Math.min(s,u);g<_&&r[g]===l[g];g++);for(_=s-1,v=u-1;_>=g&&v>=g&&r[_]===l[v];_--,v--)o[v]=i[_],m[v]=a[_],c&&(h[v]=c[_]);for(e=new Map,t=Array(v+1),f=v;f>=g;f--)y=l[f],d=e.get(y),t[f]=d===void 0?-1:d,e.set(y,f);for(d=g;d<=_;d++)y=r[d],f=e.get(y),f!==void 0&&f!==-1?(o[f]=i[d],m[f]=a[d],c&&(h[f]=c[d]),f=t[f],e.set(y,f)):a[d]();for(f=g;f<u;f++)f in o?(i[f]=o[f],a[f]=m[f],c&&(c[f]=h[f],c[f](f))):i[f]=ee(p);i=i.slice(0,s=u),r=l.slice(0)}return i});function p(e){if(a[f]=e,c){let[e,n]=y(f);return c[f]=n,t(l[f],e)}return t(l[f])}}}function be(e,t,n={}){let r=[],i=[],a=[],s=[],c=0,l;return T(()=>ve(a)),()=>{let u=e()||[],d=u.length;return u[o],C(()=>{if(d===0)return c!==0&&(ve(a),a=[],r=[],i=[],c=0,s=[]),n.fallback&&(r=[_e],i[0]=ee(e=>(a[0]=e,n.fallback())),c=1),i;for(r[0]===_e&&(a[0](),a=[],r=[],i=[],c=0),l=0;l<d;l++)l<r.length&&r[l]!==u[l]?s[l](()=>u[l]):l>=r.length&&(i[l]=ee(f));for(;l<r.length;l++)a[l]();return c=s.length=a.length=d,r=u.slice(0),i=i.slice(0,c)});function f(e){a[l]=e;let[n,r]=y(u[l]);return s[l]=r,t(n,l)}}}function j(e,t){return C(()=>e(t||{}))}var xe=e=>`Stale read from <${e}>.`;function M(e){let t=`fallback`in e&&{fallback:()=>e.fallback};return S(ye(()=>e.each,e.children,t||void 0))}function Se(e){let t=`fallback`in e&&{fallback:()=>e.fallback};return S(be(()=>e.each,e.children,t||void 0))}function N(e){let t=e.keyed,n=S(()=>e.when,void 0,void 0),r=t?n:S(n,void 0,{equals:(e,t)=>!e==!t});return S(()=>{let i=r();if(i){let a=e.children;return typeof a==`function`&&a.length>0?C(()=>a(t?i:()=>{if(!C(r))throw xe(`Show`);return n()})):a}return e.fallback},void 0,void 0)}var P=e=>S(()=>e());function Ce(e,t,n){let r=n.length,i=t.length,a=r,o=0,s=0,c=t[i-1].nextSibling,l=null;for(;o<i||s<a;)if(t[o]===n[s])o++,s++;else{for(;t[i-1]===n[a-1];)i--,a--;if(i===o){let t=a<r?s?n[s-1].nextSibling:n[a-s]:c;for(;s<a;)e.insertBefore(n[s++],t)}else if(a===s)for(;o<i;)(!l||!l.has(t[o]))&&t[o].remove(),o++;else if(t[o]===n[a-1]&&n[s]===t[i-1]){let r=t[--i].nextSibling;e.insertBefore(n[s++],t[o++].nextSibling),e.insertBefore(n[--a],r),t[i]=n[a]}else{if(!l){l=new Map;let e=s;for(;e<a;)l.set(n[e],e++)}let r=l.get(t[o]);if(r!=null){if(s<r&&r<a){let c=o,u=1,d;for(;++c<i&&c<a&&(d=l.get(t[c]))!=null&&d===r+u;)u++;if(u>r-s){let i=t[o];for(;s<r;)e.insertBefore(n[s++],i)}else e.replaceChild(n[s++],t[o++])}else o++}else t[o++].remove()}}}var we=`_$DX_DELEGATE`;function Te(e,t,n,r={}){let i;return ee(r=>{i=r,t===document?e():R(t,e(),!n&&t.firstChild?null:void 0,n)},r.owner),()=>{i(),t.textContent=``}}function F(e,t,n,r){let i,a=()=>{let t=r?document.createElementNS(`http://www.w3.org/1998/Math/MathML`,`template`):document.createElement(`template`);return t.innerHTML=e,n?t.content.firstChild.firstChild:r?t.firstChild:t.content.firstChild},o=t?()=>C(()=>document.importNode(i||=a(),!0)):()=>(i||=a()).cloneNode(!0);return o.cloneNode=o,o}function Ee(e,t=window.document){let n=t[we]||(t[we]=new Set);for(let r=0,i=e.length;r<i;r++){let i=e[r];n.has(i)||(n.add(i),t.addEventListener(i,Me))}}function I(e,t,n){je(e)||(n==null?e.removeAttribute(t):e.setAttribute(t,n))}function L(e,t){je(e)||(t==null?e.removeAttribute(`class`):e.className=t)}function De(e,t,n,r){if(r)Array.isArray(n)?(e[`$$${t}`]=n[0],e[`$$${t}Data`]=n[1]):e[`$$${t}`]=n;else if(Array.isArray(n)){let r=n[0];e.addEventListener(t,n[0]=t=>r.call(e,n[1],t))}else e.addEventListener(t,n,typeof n!=`function`&&n)}function Oe(e,t,n){if(!t)return n?I(e,`style`):t;let r=e.style;if(typeof t==`string`)return r.cssText=t;typeof n==`string`&&(r.cssText=n=void 0),n||={},t||={};let i,a;for(a in n)t[a]??r.removeProperty(a),delete n[a];for(a in t)i=t[a],i!==n[a]&&(r.setProperty(a,i),n[a]=i);return n}function ke(e,t,n){n==null?e.style.removeProperty(t):e.style.setProperty(t,n)}function Ae(e,t,n){return C(()=>e(t,n))}function R(e,t,n,r){if(n!==void 0&&!r&&(r=[]),typeof t!=`function`)return Ne(e,t,r,n);b(r=>Ne(e,t(),r,n),r)}function je(e){return!!n.context&&!n.done&&(!e||e.isConnected)}function Me(e){if(n.registry&&n.events&&n.events.find(([t,n])=>n===e))return;let t=e.target,r=`$$${e.type}`,i=e.target,a=e.currentTarget,o=t=>Object.defineProperty(e,"target",{configurable:!0,value:t}),s=()=>{let n=t[r];if(n&&!t.disabled){let i=t[`${r}Data`];if(i===void 0?n.call(t,e):n.call(t,i,e),e.cancelBubble)return}return t.host&&typeof t.host!=`string`&&!t.host._$host&&t.contains(e.target)&&o(t.host),!0},c=()=>{for(;s()&&(t=t._$host||t.parentNode||t.host););};Object.defineProperty(e,"currentTarget",{configurable:!0,get(){return t||document}}),n.registry&&!n.done&&(n.done=_$HY.done=!0);try{if(e.composedPath){let n=e.composedPath();o(n[0]);for(let e=0;e<n.length-2&&(t=n[e],s());e++){if(t._$host){t=t._$host,c();break}if(t.parentNode===a)break}}else c();o(i)}finally{e=t=null}}function Ne(e,t,n,r,i){let a=je(e);if(a){!n&&(n=[...e.childNodes]);let t=[];for(let e=0;e<n.length;e++){let r=n[e];r.nodeType===8&&r.data.slice(0,2)===`!$`?r.remove():t.push(r)}n=t}for(;typeof n==`function`;)n=n();if(t===n)return n;let o=typeof t,s=r!==void 0;if(e=s&&n[0]&&n[0].parentNode||e,o===`string`||o===`number`){if(a||o===`number`&&(t=t.toString(),t===n))return n;if(s){let i=n[0];i&&i.nodeType===3?i.data!==t&&(i.data=t):i=document.createTextNode(t),n=Ie(e,n,r,i)}else n=n!==``&&typeof n==`string`?e.firstChild.data=t:e.textContent=t}else if(t==null||o===`boolean`){if(a)return n;n=Ie(e,n,r)}else if(o===`function`)return b(()=>{let i=t();for(;typeof i==`function`;)i=i();n=Ne(e,i,n,r)}),()=>n;else if(Array.isArray(t)){let o=[],c=n&&Array.isArray(n);if(Pe(o,t,n,i))return b(()=>n=Ne(e,o,n,r,!0)),()=>n;if(a){if(!o.length)return n;if(r===void 0)return n=[...e.childNodes];let t=o[0];if(t.parentNode!==e)return n;let i=[t];for(;(t=t.nextSibling)!==r;)i.push(t);return n=i}if(o.length===0){if(n=Ie(e,n,r),s)return n}else c?n.length===0?Fe(e,o,r):Ce(e,n,o):(n&&Ie(e),Fe(e,o));n=o}else if(t.nodeType){if(a&&t.parentNode)return n=s?[t]:t;if(Array.isArray(n)){if(s)return n=Ie(e,n,r,t);Ie(e,n,null,t)}else n==null||n===``||!e.firstChild?e.appendChild(t):e.replaceChild(t,e.firstChild);n=t}return n}function Pe(e,t,n,r){let i=!1;for(let a=0,o=t.length;a<o;a++){let o=t[a],s=n&&n[e.length],c;if(o!=null&&o!==!0&&o!==!1){if((c=typeof o)==`object`&&o.nodeType)e.push(o);else if(Array.isArray(o))i=Pe(e,o,s)||i;else if(c===`function`){if(r){for(;typeof o==`function`;)o=o();i=Pe(e,Array.isArray(o)?o:[o],Array.isArray(s)?s:[s])||i}else e.push(o),i=!0}else{let t=String(o);s&&s.nodeType===3&&s.data===t?e.push(s):e.push(document.createTextNode(t))}}}return i}function Fe(e,t,n=null){for(let r=0,i=t.length;r<i;r++)e.insertBefore(t[r],n)}function Ie(e,t,n,r){if(n===void 0)return e.textContent=``;let i=r||document.createTextNode(``);if(t.length){let r=!1;for(let a=t.length-1;a>=0;a--){let o=t[a];if(i!==o){let t=o.parentNode===e;!r&&!a?t?e.replaceChild(i,o):e.insertBefore(i,n):t&&o.remove()}else r=!0}}else e.insertBefore(i,n);return[i]}var Le=/^(\s*)([-*+]|\d+[.)])\s+(.*)$/;function Re(e){return ze(He(e.replace(/\r\n/g,`
3
3
  `)).split(`
4
- `))}function Be(e){let t=[],n=0;for(;n<e.length;){let o=e[n],s=o.match(/^(`{3,})([^\n]*)$/);if(s&&!/^```.+\`\`\`/.test(o)){let r=s[1].length,i=s[2].trim().split(/\s+/)[0]??``,a=[];n++;let o=RegExp("^`{"+r+`,}\\s*$`);for(;n<e.length&&!o.test(e[n]);)a.push(e[n++]);n++;let c=i?i.split(/\s+/)[0]:``,l=c?c.split(`/`).pop().split(`.`).pop().replace(/[^\w+#-]/g,``):``,u=l?` class="language-${l}"`:``;t.push(`<pre><code${u}>${a.join(`
5
- `)}</code></pre>`);continue}if(/^ {0,3}(?:-{3,}|\*{3,}|_{3,})\s*$/.test(o)){t.push(`<hr>`),n++;continue}let c=o.match(/^(#{1,6})\s+(.*)$/);if(c){t.push(`<h${c[1].length}>${a(c[2])}</h${c[1].length}>`),n++;continue}if(/^\s*&gt;/.test(o)){let r=[];for(;n<e.length&&/^\s*&gt;/.test(e[n]);)r.push(e[n++].replace(/^\s*&gt;\s?/,``));t.push(`<blockquote>${Be(r)}</blockquote>`);continue}if(o.includes(`|`)&&n+1<e.length&&He(e[n+1])){let r=Ve(e[n+1]).map(e=>e.startsWith(`:`)&&e.endsWith(`:`)?`center`:e.endsWith(`:`)?`right`:`left`),i=Ve(o);n+=2;let s=[];for(;n<e.length&&/\S/.test(e[n])&&e[n].includes(`|`);)s.push(Ve(e[n])),n++;let c=(e,t,n)=>{let i=r[t];return`<${n}${i&&i!==`left`?` style="text-align:${i}"`:``}>${a(e)}</${n}>`},l=i.some(e=>e!==``);t.push(`<div class="tbl"><table>`+(l?`<thead><tr>${i.map((e,t)=>c(e,t,`th`)).join(``)}</tr></thead>`:``)+`<tbody>${s.map(e=>`<tr>${e.map((e,t)=>c(e,t,`td`)).join(``)}</tr>`).join(``)}</tbody></table></div>`);continue}if(Re.test(o)){t.push(i(r(o.match(Re)[1])));continue}if(/^\s*$/.test(o)){n++;continue}let l=n,u=[];for(;n<e.length&&!/^\s*$/.test(e[n])&&!/^#{1,6}\s/.test(e[n])&&!e[n].startsWith("```")&&!/^ {0,3}(?:-{3,}|\*{3,}|_{3,})\s*$/.test(e[n])&&!/^\s*&gt;/.test(e[n])&&!Re.test(e[n])&&!(e[n].includes(`|`)&&n+1<e.length&&He(e[n+1]));)u.push(e[n++]);n===l&&u.push(e[n++]),t.push(`<p>${u.map(a).join(`<br>`)}</p>`)}return t.join(`
6
- `);function r(e){return e.replace(/\t/g,` `).length}function i(t){let o=null,s=1,c=[];for(;n<e.length;){let l=e[n].match(Re);if(!l)break;let u=r(l[1]);if(u<t)break;let d=/^\d/.test(l[2]);if(o===null)o=d;else if(d!==o)break;if(o&&c.length===0){let e=Number.parseInt(l[2],10);Number.isFinite(e)&&(s=e)}n++;let f=l[3];for(;n<e.length&&/\S/.test(e[n])&&!Re.test(e[n])&&!/^#{1,6}\s/.test(e[n])&&!e[n].startsWith("```")&&!/^\s*&gt;/.test(e[n])&&!/^ {0,3}(?:-{3,}|\*{3,}|_{3,})\s*$/.test(e[n])&&!/^ {0,3}={3,}\s*$/.test(e[n])&&!(e[n].includes(`|`)&&n+1<e.length&&He(e[n+1]));)f+=` `+e[n].trim(),n++;let p=``,m=e[n]?.match(Re);m&&r(m[1])>u&&(p=i(r(m[1])));let h=f.match(/^\[( |x|X)\]\s+(.*)$/),g=h?`<input type="checkbox" disabled${h[1].toLowerCase()===`x`?` checked`:``}> `:``;c.push(`<li>${g}${a(h?h[2]:f)}${p}</li>`);let _=n;for(;_<e.length&&!/\S/.test(e[_]);)_++;let v=e[_]?.match(Re);_>n&&v&&r(v[1])===u&&/^\d/.test(v[2])===o&&(n=_)}return o?s===1?`<ol>${c.join(``)}</ol>`:`<ol start="${s}">${c.join(``)}</ol>`:`<ul>${c.join(``)}</ul>`}function a(e){let t=[];return e=e.replace(/\u0000/g,``),e=e.replace(/`([^`]+)`/g,(e,n)=>(t.push(`<code>${n}</code>`),`\ue000${t.length-1}\uE001`)),e=e.replace(/!\[([^\]]*)\]\((https?:\/\/[^)\s]+)(?:\s+&quot;[^)]*&quot;)?\)/g,(e,n,r)=>(t.push(`<img src="${r}" alt="${n}" loading="lazy">`),`\ue000${t.length-1}\uE001`)),e=e.replace(/\[([^\]]+)\]\((https?:\/\/[^)\s]+)(?:\s+&quot;[^)]*&quot;)?\)/g,(e,n,r)=>(t.push(`<a href="${r}" rel="noopener noreferrer" target="_blank">${n}</a>`),`\ue000${t.length-1}\uE001`)),e=e.replace(/(?<!["'=\w])(https?:\/\/[^\s<>"')\]]*[^\s<>"')\].,;:!?"')\]])/g,`<a href="$1">$1</a>`),e=e.replace(/\*\*\*([\s\S]+?)\*\*\*/g,`<strong><em>$1</em></strong>`),e=e.replace(/\*\*([\s\S]+?)\*\*/g,`<strong>$1</strong>`),e=e.replace(/(^|[^\w])__(?=\S)([\s\S]*?\S)__(?!\w)/g,`$1<strong>$2</strong>`),e=e.replace(/(^|[^\w*])\*(?!\s)([^*\n]+?)\*(?![\w*])/g,`$1<em>$2</em>`),e=e.replace(/(^|[^\w])_(?!\s)([^_\n]+?)_(?!\w)/g,`$1<em>$2</em>`),e=e.replace(/~~([\s\S]+?)~~/g,`<del>$1</del>`),e.replace(/\ue000(\d+)\ue001/g,(e,n)=>t[+n]??``)}}function Ve(e){let t=e.trim();t.startsWith(`|`)&&(t=t.slice(1));let n=[],r=``;for(let e=0;e<t.length;e++){let i=t[e];if(i===`\\`&&t[e+1]===`|`)r+=`|`,e++;else if(i==="`"){let n=t.indexOf("`",e+1);if(n!==-1){r+=t.slice(e,n+1).replace(/\\\|/g,`|`),e=n;continue}r+=i}else{if(i===`|`&&e===t.length-1)break;i===`|`?(n.push(r.trim()),r=``):r+=i}}return n.push(r.trim()),n.filter((e,r)=>!(e===``&&r===n.length-1&&t.endsWith(`|`)))}function He(e){let t=e.trim();if(!t.includes(`|`)||!t.includes(`-`))return!1;let n=Ve(t);return n.every(e=>/^:?-+:?$/.test(e))&&n.some(e=>e!==``)}function Ue(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`)}function We(e){return Math.max(0,e.height-e.viewport)}function Ge(e){return e?Math.max(0,e.height-e.top-e.viewport):1/0}function Ke(e,t=24){return e?Ge(e)<=t:!1}function qe(e,t,n,r){if(r!==void 0&&Math.abs(e.viewport-r)>.5||n!==void 0&&Math.abs(e.height-n)>.5)return`layout`;if(t){let n=Math.min(t.top,We(e));if(Math.abs(e.top-n)<=.5)return`programmatic`}return`reader`}function Je(e,t){return e?Ge(t)<=64:!1}function Ye(e,t,n,r){return t===`reader`?r!==void 0&&n.top<r-.5?!1:Ke(n):e||Ke(n)}function Xe(e,t,n=.5){return e?Ge(t)>n:!1}var Ze=Ge;function Qe(e,t,n=200){return!t||e-t>=n}function $e(e,t){let n=String(e??``).trim();return!n||!t||n===t}var[et,tt]=y(null),nt=et;function rt(e){e&&tt(e)}function it(){tt(null)}function at(e,t){let n=0,r=()=>{let t=0;for(let n of e.values())t+=n.bytes;return t};for(;e.size>t.maxEntries||r()>t.maxBytes;){let t,r=1/0;for(let[n,i]of e)i.at<r&&(r=i.at,t=n);if(t===void 0||(e.delete(t),n++,e.size===0))break}return n}function ot(e,t=0){if(t>8)return 8;if(e==null)return 4;switch(typeof e){case`string`:return 16+e.length*2;case`number`:case`boolean`:return 8;case`object`:{if(Array.isArray(e)){let n=16;for(let r of e)n+=ot(r,t+1);return n}let n=16;for(let[r,i]of Object.entries(e))n+=8+r.length*2+ot(i,t+1);return n}default:return 8}}var st=new Map,ct=0,lt=500,ut=4194304;function dt(e){let t=st.get(e);if(t!==void 0)return t;let n=ze(e);for(st.set(e,n),ct+=(e.length+n.length)*2;(st.size>lt||ct>ut)&&st.size;){let e=st.keys().next().value;if(e===void 0)break;let t=st.get(e)??``;ct-=(e.length+t.length)*2,st.delete(e)}return n}function ft(e){if(e==null||!Number.isFinite(e))return`?`;let t=Math.max(0,e);if(t<1e3)return`${Math.round(t)}ms`;if(t<6e4)return`${(Math.floor(t/100)/10).toFixed(1)}s`;let n=Math.round(t/1e3);if(n<3600){let e=Math.floor(n/60),t=n%60;return t?`${e}m ${t}s`:`${e}m`}let r=Math.round(n/60),i=Math.floor(r/60),a=r%60;return a?`${i}h ${a}m`:`${i}h`}function pt(e,t){return e.length>t?e.slice(0,t)+` …`:e}function mt(e){let t=new Date(e).getTime()-Date.now(),n=Math.abs(t),r=n<9e4?`${Math.round(n/1e3)}s`:n<54e5?`${Math.round(n/6e4)}m`:`${(n/36e5).toFixed(1)}h`;return t>=0?`in ${r}`:`${r} ago`}function ht(e,t,n,r=Date.now()){let i=new Map(e);return i.set(t,{text:n.text??``,reasoning:n.reasoning??``,at:r}),i}function gt(e,t){if(!e.has(t))return e;let n=new Map(e);return n.delete(t),n}function _t(e){let t=e;return t?.type===`state`&&t.data?.detail===`llm turn start`||t?.type===`question`}function vt(e){return e===`running`||e===`waiting`||e===`needs_operator`}function yt(e,t,n){let r=e.text.trim(),i=Ct(t),a=vt(n);return{textCovered:!r||i.has(r),reasoningStale:!e.reasoning.trim()||St(t).has(e.reasoning.trim())||a&&xt(t,e.at)}}function bt(e,t,n){let r=yt(e,t,n),i=r.textCovered?``:e.text,a=r.reasoningStale?``:e.reasoning,o=vt(n),s=!i.trim()&&!a.trim(),c=!!e.text.trim()||!!e.reasoning.trim();return{text:i,reasoning:a,live:o,empty:s&&(!o||c)}}function xt(e,t){return t?e.some(e=>{if(e.type!==`tool_call`)return!1;let n=Date.parse(String(e.ts??``));return Number.isFinite(n)&&n>t}):!1}function St(e){let t=new Set;for(let n of e){let e=String(n.data?.reasoning??``).trim();e&&t.add(e)}return t}function Ct(e){let t=new Set;for(let n of e)n.type===`message`&&n.data?.role===`assistant`&&t.add(String(n.data.content??``).trim());return t}function wt(e){if(!e)return!1;let t=e.data?.actor;return!(typeof t==`string`&&t.length>0)}var Tt=new Set([`stopped`,`error`]),Et=2e3;function Dt(e,t,n=Date.now()){let r=[];for(let[i,a]of e){let e=t(i);e!==void 0&&(!Tt.has(e)&&(vt(e)||n-Number(a?.at??0)<=Et)||r.push(i))}if(r.length===0)return e;let i=new Map(e);for(let e of r)i.delete(e);return i}function Ot(e,t,n){if(!e)return null;let r=bt(e,t,n);return r.empty?null:r.text===e.text&&r.reasoning===e.reasoning?e:{text:r.text,reasoning:r.reasoning,at:e.at}}function kt(e,t,n,r){if(!e)return 0;if(r)return e;if(!n)return 0;let i=t.find(e=>e.id===n);return i?.status===`running`||i?.status===`waiting`||i?.status===`needs_operator`?e:0}function At(e,t){if(!t.length)return[...e].sort((e,t)=>e.seq-t.seq);let n=e.reduce((e,t)=>Math.max(e,t.seq),0),r=t.map((e,t)=>e.seq>n?e:{...e,seq:n+1+t});return[...e,...r].sort((e,t)=>e.seq-t.seq)}function jt(e,t){if(t===void 0||t<=e.seq)return e;let n=Mt.get(e);n||(n=new Map,Mt.set(e,n));let r=n.get(t);if(r)return r;let i={...e,seq:t};return n.set(t,i),i}var Mt=new WeakMap;function Nt(e,t){return t===void 0?e.reduce((e,t)=>Math.max(e,t.seq),0)+1:t}var Pt=new Set([`report_progress`,`ask_operator`,`ask_user`,`record_decision`]);function Ft(e){let{events:t,consumed:n,feedTypes:r}=e;return t.filter(e=>{if(e.type===`sub`)return!0;if(!r.has(e.type))return!1;let t=e.type===`tool_call`||e.type===`tool_result`?String(e.data?.name??``):``;if(Pt.has(t))return!1;if(e.type===`tool_result`)return!n.has(e.id);if(e.type===`message`){let t=String(e.data?.content??``),n=String(e.data?.reasoning??``);return t.trim()===``&&n.trim()!==``&&e.data?._prevKind===`tool`||e.data?.progressEcho||!e.data?.final&&t.trim()===`(tool call)`?!1:t.trim()!==``||n.trim()!==``||!!e.data?.final}return!0})}function It(e){let t=[];for(let n of e){if(n.type!==`sub`){t.push(n);continue}let e=n.data,r=String(e?.type??`message`);r!==`state`&&t.push({...n,type:r,data:{...e?.data??{},actor:e?.sub}})}return t}var Lt=e=>String(e??``).replace(/\s+/g,` `).trim().toLowerCase();function Rt(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n];if(r.type===`message`&&r.data?.role===`assistant`){let e=t[t.length-1],n=e?.type;if(n===`progress`||n===`decision`||e?.data?.progressEcho){let t=Lt(r.data?.content),n=Lt(e?.data?.content);if(t&&t===n)continue}}t.push(r)}return t}function zt(e){let t=new Set,n=new Set,r=new Set,i=new Map,a=new Map;for(let o of e){let e=o.data?.promptId;e&&(o.type===`prompt`&&r.add(String(e)),o.type===`prompt`&&o.data?.source===`user`&&n.add(String(e)),o.type===`system_note`&&o.data?.event===`prompt-delivered`&&(t.add(String(e)),i.set(String(e),o.seq)),o.type===`system_note`&&o.data?.event===`prompt-cancelled`&&a.set(String(e),o.seq))}return{deliveredIds:t,loggedUserPrompts:n,loggedPromptIds:r,deliveredNotes:i,cancelledNotes:a}}var Bt=new WeakMap,Vt=2**53-1-1e5,Ht=new Set;function Ut(e,t){return e.map(e=>{if(e.type!==`prompt`||!(Number(e.data?.ahead??0)>0)||t.deliveredIds.has(String(e.data?.promptId??``))||t.cancelledNotes.has(String(e.data?.promptId??``))||e.data?.pending)return e;let n=Bt.get(e);if(n)return n;let r={...e,seq:Vt+e.seq,data:{...e.data,pending:!0,queued:!0}};return Bt.set(e,r),r})}function Wt(e,t,n){return e.filter(e=>{if(!t.renderedTypes.has(e.type))return e.type===`system_note`&&t.renderedNoteEvents.has(String(e.data?.event??``));if(e.type!==`prompt`)return!0;let r=String(e.data?.promptId??``);return r===``||!n.has(r)})}var Gt=new WeakMap;function Kt(e,t){let n=Gt.get(e);n||(n=new Map,Gt.set(e,n));let r=n.get(t);if(r)return r;let i={...e,data:{...e.data??{},cancelled:!0}};return n.set(t,i),i}function qt(e,t){let n=t=>Nt(e,t),r=[];for(let i of e){if(i.type!==`prompt`||i.data?.source!==`user`){r.push(i);continue}let e=String(i.data?.promptId??``),a=t.cancelledNotes.get(e),o=t.deliveredNotes.get(e)??0,s=Math.max(o,a??0)||void 0,c=a===void 0?i:Kt(i,a);if(s!==void 0){r.push(jt(c,s));continue}let l=n(c.seq);r.push(c.seq===l?c:{...c,seq:l})}return r}function Jt(e,t){return e.filter(e=>!e.promptId||!(t.deliveredIds.has(e.promptId)&&t.loggedUserPrompts.has(e.promptId)))}function Yt(e){let t=Rt(It(Ft(e))),n=zt(t),r=new Set;for(let t of e.pending)t.promptId&&!n.deliveredIds.has(t.promptId)&&r.add(t.promptId);for(let t of e.serverPendingIds??[])t&&!n.deliveredIds.has(t)&&e.pending.some(e=>e.promptId===t)&&r.add(t);let i=Ut(t,n),a=Jt(e.pending,n).filter(e=>!e.promptId||!n.loggedPromptIds.has(e.promptId)),o=At(qt(Wt(i,e,Ht),n),a.map(e.echo));return{rows:o,pendingCount:o.filter(e=>(e.data?.pending||e.data?.echo)&&e.data?.queued!==!1).length}}function Xt(e){let t=e.event;return t===`status`||t===`audit-started`||t===`audit`||t===`audit-failed`?t:`other`}function Zt(e){let t=e.trim().toLowerCase();return t===``||t===`(no detail)`||t===`no detail`||t===`(none)`||t===`(empty)`}function Qt(e,t){let n=String(e??``).trim();return Zt(n)?Zt(t)?``:t:n}function $t(e){switch(Xt(e)){case`audit-started`:return{label:`🔍️ completion audit started`,detail:String(e.verify??``).trim()||`checking the verification contract…`,tone:``,markdown:!1,hasCard:!0};case`audit`:{let t=!Zt(String(e.feedback??``));return e.verdict===`approved`?{label:`✅ audit: approved`,detail:Qt(e.feedback??``,``),tone:`ok`,markdown:!0,hasCard:t}:{label:`⚠ audit: changes required`,detail:Qt(e.feedback??``,``),tone:`warn`,markdown:!0,hasCard:t}}case`audit-failed`:return{label:`🔍️ audit unavailable — finish accepted`,detail:String(e.detail??``).trim()||`the auditor could not be reached`,tone:`err`,markdown:!1,hasCard:!0};case`status`:{let t=String(e.status??``).trim();return t?t===`done`?String(e.by??``).trim()===`operator`?{label:`🏁 goal marked done`,detail:`you marked this goal done — no audit runs for a manual completion`,tone:``,markdown:!1,hasCard:!0}:{label:`🏁 finish claimed — pending audit`,detail:`the agent called finish(goalComplete=true); the verification contract is now being audited`,tone:``,markdown:!1,hasCard:!0}:t===`active`?String(e.by??``).trim()===`auditor`?{label:`▶ goal reopened`,detail:`the audit rejected the finish — work continues on the same goal`,tone:`warn`,markdown:!1,hasCard:!0}:{label:`▶ goal resumed`,detail:`marked active again — auto-continue picks the goal up from the next turn`,tone:``,markdown:!1,hasCard:!0}:{label:`🎯 goal ${t||`updated`}`,detail:String(e.text??``).trim()||`the goal is now ${t}`,tone:``,markdown:!0,hasCard:!0}:{label:`🎯 goal status updated`,detail:String(e.text??``).trim()||`no status recorded`,tone:``,markdown:!0,hasCard:!0}}default:{let t=String(e.text??``).trim(),n=String(e.event??``).trim();return{label:n?`🎯 goal ${n}`:`🎯 goal updated`,detail:t||`the "${n||`goal`}" event carried no further detail`,tone:``,markdown:!0,hasCard:!0}}}}var en=P(`<span class="meta muted">`),tn=P(`<div class=ctitle>`),nn=P(`<div>`),rn=P(`<div class=cardbody>`);function an(e){let t=()=>{let t=e.tone;return[`card`,t?`card-${t}`:``,e.class??``].filter(Boolean).join(` `)},n=()=>e.markdown===!1?ze(`\`\`\`\n${e.body}\n\`\`\``):ze(e.body);return(()=>{var r=nn();return L(r,A(M,{get when(){return e.title},get children(){var t=tn();return L(t,()=>e.title,null),L(t,A(M,{get when(){return e.meta},get children(){var t=en();return L(t,()=>e.meta),t}}),null),t}}),null),L(r,()=>e.children??(()=>{var e=rn();return b(()=>e.innerHTML=n()),e})(),null),b(()=>I(r,t())),r})()}function on(e){let t=e.hideGhosts?e.agents.filter(e=>!e.workspaceMissing):e.agents,n=t.length?t:e.agents,r=e.urlId,i=r?e.ownerOf(r):void 0;return(i?n.find(e=>e.id===i):void 0)??n.find(t=>t.id===e.lastId)??n[0]}function sn(e,t){let n=new Map;for(let t of e)n.set(t.id,t);for(let e of t)n.set(e.id,e);return[...n.values()]}var cn=[320,640,1280,1920,2560,3840],ln=cn[0],un=/^\/api\/assets\/[a-f0-9]{32}\.(png|jpg|jpeg|gif|webp|avif)$/i;function dn(e,t){if(e)return un.test(e)?`${e}?w=${t}`:e}function fn(e){if(e)return cn.map(t=>`${dn(e,t)} ${t}w`).join(`, `)}function pn(e,t=ln){return dn(e,t)}function mn(e,t=new Set,n=!1,r=new Set){let i=n?e.filter(t=>{if(!t.workspaceMissing)return!0;let n=[t.id],r=new Set;for(;n.length;){let t=n.pop();if(!r.has(t)){r.add(t);for(let i of e)i.parent===t&&!r.has(i.id)&&n.push(i.id)}}for(let t of r){let n=e.find(e=>e.id===t);if(n&&!n.workspaceMissing)return!0}return!1}):e,a=new Map,o=[];for(let e of i)e.parent&&i.some(t=>t.id===e.parent)?(a.has(e.parent)||a.set(e.parent,[]),a.get(e.parent).unshift(e)):o.push(e);let s=[],c=(e,n)=>{for(let o of e){let e=n===0&&r.has(yn(i,o));if(s.push({a:o,depth:n}),e)continue;let l=a.get(o.id);l?.length&&!t.has(o.id)&&c(l,n+1)}},l=[],u=new Map;for(let e of o){if(e.parent)continue;let t=hn(i,e.id),n=u.get(t);n?n.push(e):(u.set(t,[e]),l.push(t))}for(let t of o){if(!t.parent)continue;let n=hn(e,t.id)||``,r=u.get(n);r?r.push(t):(u.set(n,[t]),l.push(n))}for(let e of l)c(u.get(e),0);return s}function hn(e,t,n=new Set){let r=e.find(e=>e.id===t);return r?!r.parent||n.has(t)?r.workspace||``:(n.add(t),hn(e,r.parent,n)||r.workspace||``):``}function gn(e){return e.isSub?e.hasChildren:e.collapsed||e.hasChildren}function _n(e,t=[]){let n=e.indexOf(`-sub`);if(n===-1)return null;let r=e.slice(n+4).replace(/^-+/,``);if(!r)return null;let i=r.split(`-`);return(t.includes(i[0]??``)?i.slice(1).join(`-`):r).replace(/_/g,` `).trim()||null}function vn(e,t,n=new Set){let r=[],i=new Set(n);for(let n of e)n.parent===t&&(i.has(n.id)||(i.add(n.id),r.push(n,...vn(e,n.id,i))));return r}function yn(e,t){let n=t.id,r=new Set;for(;;){let t=e.find(e=>e.id===n);if(!t?.parent||r.has(n))break;r.add(n),n=t.parent}return`chat:${n||t.id}`}function bn(e){let t=new Map;for(let n of e){if(n.parent)continue;let r=hn(e,n.id);r&&t.set(r,(t.get(r)??0)+1)}return t}function xn(e,t,n=new Set){let r=[],i=null;for(let a of t){let t=hn(e,a.a.id);t?(t!==i&&(i=t,r.push({a:a.a,depth:0,headerOnly:!0,wsHeader:t,wsCollapsedGroup:n.has(`ws:${t}`)})),!n.has(`ws:${t}`)&&(n.has(yn(e,a.a))?r.push({a:a.a,depth:a.depth,chatCollapsedGroup:!0}):r.push({a:a.a,depth:a.depth}))):r.push({a:a.a,depth:a.depth})}return r}function Sn(e,t=new Set){let n=new Set,r=-1,i=-1;for(let t of e)t.type===`question`?r=t.seq:t.type===`prompt`&&t.data?.source===`user`?i=t.seq:t.type===`system_note`&&t.data?.event===`prompt-delivered`&&(i=Math.max(i,t.seq));if(r>=0&&i>r)for(let t of e)t.type===`question`&&t.seq<=i&&n.add(String(t.data?.callId??``));for(let e of t)n.add(e);return n}var Cn=(e,t,n)=>{if(t>=e.length)return e;if(n?.length){let r=new Set(n),i=e.filter(e=>e.promptId&&r.has(e.promptId));if(i.length){let n=e.filter(e=>!e.promptId);return n.length?[...i,...n].slice(0,t):i}}return e.slice(0,t)};function wn(e,t){let n=new Set(e.map(e=>e.promptId??e.id).filter(e=>!!e)),r=e.filter(e=>!e.promptId).map(e=>e.text),i=[];for(let e of t){let t=typeof e.id==`string`?e.id:``;if(!t||n.has(t))continue;let a=r.indexOf(String(e.text??``));a===-1?i.push({id:`p${t}`,text:String(e.text??``),at:Number(e.at)||Date.now(),promptId:t,queued:!0,images:e.images?.map(e=>e.url),...e.source?{source:e.source}:{}}):r.splice(a,1)}return i.length?[...e,...i]:e}var Tn=(e=!1)=>e;function En(e,t,n){let r=e??[];return n&&r.includes(n)?n:t&&r.includes(t)||t&&r.length===0?t:r[0]??null}function Dn(e,t,n){return!t||n&&t===n?!0:typeof e==`string`&&e===t}function On(e,t,n){return!e||!t||e.agent!==t?!1:Dn(e.session,n,t)}function kn(e,t,n){return!e||!t||e.agentId!==t||!e.sessionId?!1:Dn(e.sessionId,n,t)}function An(e,t,n){return n?!e||!t||t===e.id||!e.session||e.session===t:!1}function jn(e,t){if(t>=1)return e;let n=/^#([0-9a-f]{6})$/i.exec(e.trim());if(n){let e=Number.parseInt(n[1],16);return`rgba(${e>>16&255}, ${e>>8&255}, ${e&255}, ${Math.max(0,Math.min(1,t))})`}let r=/^rgba?\(([^)]+)\)$/i.exec(e.trim());if(r){let[e,n,i]=r[1].split(`,`).map(e=>e.trim());return`rgba(${e}, ${n}, ${i}, ${Math.max(0,Math.min(1,t))})`}return e}function Mn(e=1){let t=``,n=``,r=``,i=``;try{let e=getComputedStyle(document.documentElement);t=e.getPropertyValue(`--term-bg`).trim(),n=e.getPropertyValue(`--term-fg`).trim(),r=e.getPropertyValue(`--term-cursor`).trim(),i=e.getPropertyValue(`--term-cursor-accent`).trim()}catch{}let a=t||`#0d0e12`,o=jn(a,e),s=n||`#dcdee4`;return{background:o,foreground:s,cursor:r||s,cursorAccent:i||a,selectionBackground:Pn(s),selectionForeground:s}}function Nn(e,t=1){let n=Mn(t),r=e.options.theme;r&&r.background===n.background&&r.foreground===n.foreground&&r.cursor===n.cursor&&r.cursorAccent===n.cursorAccent&&r.selectionBackground===n.selectionBackground||(e.options.theme=n)}function Pn(e){let t=e.trim(),n=/^#([0-9a-f]{6})$/i.exec(t);return n?`#${n[1]}47`:`rgba(128, 128, 128, 0.35)`}function Fn(e,t,n){return e?.provider||n||Object.keys(t??{})[0]||``}function In(e,t){return t?String(e?.[t]?.model??``).trim():``}function Ln(e,t,n){return In(e,t)||(n&&t===(n.provider??``)?n.model??``:``)}function Rn(e,t,n,r){return n?.model&&t===r?n.model:In(e,t)||n?.model||``}function zn(e){return!e}function Bn(e){return!e}function Vn(e,t){return e!==t}function Hn(e,t){return Math.max(1,Math.min(e,t))}function Un(e){return typeof e!=`number`||!Number.isFinite(e)?!1:e<0}function Wn(e){return e===`PageUp`||e===`ArrowUp`||e===`Home`}function Gn(e,t,n){if(!n)return null;let r=e.find(e=>e.top+e.height>t+.5);if(!r)return null;let i=Math.min(Math.max(0,Math.round(t-r.top)),Math.max(0,Math.round(r.height)));return{session:n,eid:r.eid,offset:i}}function Kn(e,t,n){if(!e)return null;let r=t.find(t=>t.eid===e.eid);if(!r)return null;let i=Math.max(0,Math.min(n,Math.round(r.top+e.offset)));return Number.isFinite(n)&&i>=n-1?null:i}var qn=`teapot.textareaH.`;function Jn(e){try{let t=Number(localStorage.getItem(qn+e)??``);return Number.isFinite(t)&&t>0?t:0}catch{return 0}}function Yn(e,t){try{localStorage.setItem(qn+e,String(Math.round(t)))}catch{}}function Xn(e,t,n){return!n||!Number.isFinite(e)||e<=0?!1:!Number.isFinite(t)||t<=0||Math.abs(e-t)>=1}function Zn(e,t){let n=Jn(t);n>0&&(e.style.height=`${n}px`);let r=!1,i=()=>{r=!0};e.addEventListener(`pointerdown`,i);let a=new ResizeObserver(()=>{let n=e.offsetHeight;Xn(n,Jn(t),r)&&Yn(t,n)});return a.observe(e),()=>{e.removeEventListener(`pointerdown`,i),a.disconnect()}}var Qn=e=>e?e.sessionTitle?.trim()||e.id:``,$n=(e,t)=>{if(!e)return``;let n=Qn(e),r=t?` — ${t}`:``;return n===e.id?`${n}${r}`:`${n} — ${e.id}${r}`},er=e=>(e.sameSession,e.echoCount),tr=[{key:`bgDarkest`,cssVar:`--bg-darkest`,label:`surface (deepest)`},{key:`bgDark`,cssVar:`--bg-dark`,label:`surface`},{key:`bgMid`,cssVar:`--bg-mid`,label:`surface (raised)`},{key:`bgLight`,cssVar:`--bg-light`,label:`surface (control)`},{key:`fg`,cssVar:`--fg`,label:`text`},{key:`dim`,cssVar:`--dim`,label:`text (muted)`},{key:`line`,cssVar:`--line`,label:`divider`},{key:`acc`,cssVar:`--acc`,label:`accent`},{key:`ok`,cssVar:`--ok`,label:`success`},{key:`warn`,cssVar:`--warn`,label:`warning`},{key:`err`,cssVar:`--err`,label:`error`},{key:`tool`,cssVar:`--tool`,label:`tool accent`},{key:`termBg`,cssVar:`--term-bg`,label:`terminal background`},{key:`termFg`,cssVar:`--term-fg`,label:`terminal text`}],nr=`teapot.customThemes`,rr={bgDarkest:`#1a1c22`,bgDark:`#232630`,bgMid:`#2b2e39`,bgLight:`#343845`,fg:`#dcdee4`,dim:`#9298a5`,line:`#1d2027`,acc:`#5865f2`,ok:`#3ba55d`,warn:`#faa81a`,err:`#ed4245`,tool:`#3ba0c9`,termBg:`#0d0e12`,termFg:`#dcdee4`},ir={dark:{bgDarkest:`#1a1c22`,bgDark:`#232630`,bgMid:`#2b2e39`,bgLight:`#343845`,fg:`#dcdee4`,dim:`#9298a5`,line:`#1d2027`,acc:`#5865f2`,ok:`#3ba55d`,warn:`#faa81a`,err:`#ed4245`,tool:`#3ba0c9`,termBg:`#0d0e12`,termFg:`#dcdee4`},midnight:{bgDarkest:`#0d0f18`,bgDark:`#12141f`,bgMid:`#1b1f31`,bgLight:`#252a42`,fg:`#dfe2f2`,dim:`#8a90ad`,line:`#0a0c14`,acc:`#8b7cf7`,ok:`#54c08a`,warn:`#e5b567`,err:`#ef6a6a`,tool:`#6aa9e9`,termBg:`#0a0c13`,termFg:`#dfe2f2`},tea:{bgDarkest:`#241c16`,bgDark:`#2e241c`,bgMid:`#3b2f24`,bgLight:`#493b2d`,fg:`#f0e4d2`,dim:`#b39d82`,line:`#1b140f`,acc:`#d98e32`,ok:`#7fa653`,warn:`#e0b058`,err:`#cf5b47`,tool:`#c9975f`,termBg:`#1d1712`,termFg:`#ecdcc3`},coffee:{bgDarkest:`#191410`,bgDark:`#211a14`,bgMid:`#30271e`,bgLight:`#403527`,fg:`#ede3d0`,dim:`#a89478`,line:`#120d07`,acc:`#c68a4b`,ok:`#8aa15c`,warn:`#d9a441`,err:`#c25450`,tool:`#a67c52`,termBg:`#15100c`,termFg:`#e8dcc5`},matcha:{bgDarkest:`#1b2217`,bgDark:`#232b1e`,bgMid:`#2f3a28`,bgLight:`#3c4a33`,fg:`#e8eeda`,dim:`#9aab84`,line:`#131a10`,acc:`#8db64e`,ok:`#6fae4e`,warn:`#d8b13c`,err:`#cd5c50`,tool:`#5da88f`,termBg:`#151b11`,termFg:`#dfe8cb`},matrix:{bgDarkest:`#060a06`,bgDark:`#0a0f0a`,bgMid:`#122116`,bgLight:`#18301d`,fg:`#c9f2cf`,dim:`#6fa075`,line:`#030603`,acc:`#2fd558`,ok:`#39c95f`,warn:`#b8d977`,err:`#ff6b6b`,tool:`#57c99b`,termBg:`#030503`,termFg:`#33ff77`},sunset:{bgDarkest:`#1c1422`,bgDark:`#241b2b`,bgMid:`#33253e`,bgLight:`#452f52`,fg:`#f2e6ea`,dim:`#ab93a8`,line:`#150e1b`,acc:`#f2784b`,ok:`#63b46f`,warn:`#eda63d`,err:`#e25563`,tool:`#b06ac9`,termBg:`#170f1d`,termFg:`#f0dfe4`},sakura:{bgDarkest:`#22131f`,bgDark:`#251322`,bgMid:`#311a2d`,bgLight:`#3f213a`,fg:`#f6eaf3`,dim:`#bba6bd`,line:`#402b43`,acc:`#f2558e`,ok:`#34bd73`,warn:`#f5b83d`,err:`#f43f5e`,tool:`#a77bff`,termBg:`#170b15`,termFg:`#f2e6f0`},light:{bgDarkest:`#eceef4`,bgDark:`#f6f7fa`,bgMid:`#e2e5ee`,bgLight:`#ffffff`,fg:`#24272f`,dim:`#5d6470`,line:`#d8dbe4`,acc:`#4757d8`,ok:`#2b8a4b`,warn:`#b97a0f`,err:`#d83c3f`,tool:`#2278a8`,termBg:`#ffffff`,termFg:`#24272f`},strawberry:{bgDarkest:`#fbe4ea`,bgDark:`#fdf0f3`,bgMid:`#f7d4de`,bgLight:`#fffafb`,fg:`#4a2733`,dim:`#96707e`,line:`#f0ccd6`,acc:`#e05575`,ok:`#4d9e63`,warn:`#c98a2d`,err:`#d43d51`,tool:`#b05687`,termBg:`#fff5f8`,termFg:`#4a2733`},ramune:{bgDarkest:`#ddeff7`,bgDark:`#ecf7fb`,bgMid:`#c9e7f4`,bgLight:`#fbfeff`,fg:`#173342`,dim:`#5b7d90`,line:`#c2e2ef`,acc:`#1d86ae`,ok:`#3a9e6e`,warn:`#cf9a2a`,err:`#d64f5c`,tool:`#3a9db8`,termBg:`#f4fbfd`,termFg:`#173342`}},ar=e=>typeof e==`string`&&e.length>0&&e.length<=64&&!/[;{}]/.test(e);function or(e){if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.id!=`string`||!/^[a-z0-9-]{1,40}$/i.test(t.id)||typeof t.label!=`string`||!t.label.trim()||t.mode!==`dark`&&t.mode!==`light`)return null;let n=t.palette;if(!n||typeof n!=`object`)return null;let r={};for(let{key:e}of tr){if(!ar(n[e]))return null;r[e]=n[e]}let i={id:t.id,label:t.label.slice(0,40),mode:t.mode,palette:r};if(typeof t.backgroundImage==`string`){let e=t.backgroundImage,n=/^\/api\/assets\/[a-f0-9]{32}\.(png|jpe?g|gif|webp|avif)$/i.test(e),r=/^data:image\//.test(e)&&e.length<=15e5,a=/^https?:\/\//.test(e);(n||r||a)&&(i.backgroundImage=e)}return typeof t.backgroundDim==`number`&&Number.isFinite(t.backgroundDim)&&(i.backgroundDim=Math.min(.9,Math.max(0,t.backgroundDim))),typeof t.backgroundImageBytes==`number`&&Number.isFinite(t.backgroundImageBytes)&&(i.backgroundImageBytes=Math.max(0,Math.round(t.backgroundImageBytes))),typeof t.surfaceAlpha==`number`&&Number.isFinite(t.surfaceAlpha)&&(i.surfaceAlpha=Math.min(1,Math.max(.35,t.surfaceAlpha))),i}function sr(){try{let e=localStorage.getItem(nr);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t.map(or).filter(e=>e!==null):[]}catch{return[]}}function cr(e){try{return localStorage.setItem(nr,JSON.stringify(e)),fetch(`/api/themes`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({themes:e})}).catch(()=>{}),{ok:!0}}catch(e){return{ok:!1,error:e.name===`QuotaExceededError`||/quota/i.test(String(e.message))?`storage is full — that background image is too large. Try a smaller one, or remove another theme.`:`could not save: ${e.message}`}}}async function lr(){try{let e=await fetch(`/api/themes`);if(!e.ok)return null;let t=await e.json();return Array.isArray(t.themes)?t.themes.map(or).filter(e=>e!==null):null}catch{return null}}function ur(e){for(let t=0;;t++){let n=`custom-${Date.now().toString(36)}${t?`-${t}`:``}`;if(!e.includes(n))return n}}function dr(e,t){let n=new Set([`--bg-darkest`,`--bg-dark`,`--bg-mid`,`--bg-light`]),r=!!t?.backgroundImage;for(let{key:i,cssVar:a}of tr){let o=t?t.palette[i]:``;r&&n.has(a)?e.style.getPropertyValue(a)&&e.style.removeProperty(a):e.style.getPropertyValue(a)!==o&&(o?e.style.setProperty(a,o):e.style.removeProperty(a))}let i=t?.backgroundImage?String(t.backgroundDim??.55):``,a=t?.backgroundImage?String(t.surfaceAlpha??.82):``;for(let[t,n]of[[`--bg-image-dim`,i],[`--surface-alpha`,a]])e.style.getPropertyValue(t)!==n&&(n?e.style.setProperty(t,n):e.style.removeProperty(t));if(t?.backgroundImage){e.dataset&&(e.dataset.bgImage=`on`);for(let[n,r]of[[`--bg-darkest-solid`,t.palette.bgDarkest],[`--bg-dark-solid`,t.palette.bgDark],[`--bg-mid-solid`,t.palette.bgMid],[`--bg-light-solid`,t.palette.bgLight]]){let t=fr(r);e.style.getPropertyValue(n)!==t&&e.style.setProperty(n,t)}}else{e.dataset&&delete e.dataset.bgImage;for(let t of[`--bg-darkest-solid`,`--bg-dark-solid`,`--bg-mid-solid`,`--bg-light-solid`])e.style.removeProperty(t)}}function fr(e){let t=/^#([0-9a-f]{6})[0-9a-f]{2}$/i.exec(e.trim());return t?`#${t[1]}`:e}function pr(e){let t=e.trim().toLowerCase(),n=/^#?([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/.exec(t);if(!n)return null;let r=n[1];return r.length===3?`#${r[0]}${r[0]}${r[1]}${r[1]}${r[2]}${r[2]}`:`#${r}`}function mr(e){if(e.customIds.includes(e.want)||e.presetIds.includes(e.want))return{active:e.want,repaired:!1};let t=e.fallback&&e.presetIds.includes(e.fallback)?e.fallback:`dark`;return{active:e.presetIds.includes(t)?t:e.presetIds[0]??`dark`,repaired:!0}}function hr(e,t,n){return e.find(e=>e.id===t)??e.find(e=>e.id===n)??e[0]}function gr(e){return e.preview?e.preview:e.auto?e.prefersLight?e.light:e.dark:e.fixed}var _r=Object.defineProperty,vr=Object.getOwnPropertyDescriptor,yr=(e,t)=>{for(var n in t)_r(e,n,{get:t[n],enumerable:!0})},R=(e,t,n,r)=>{for(var i=r>1?void 0:r?vr(t,n):t,a=e.length-1,o;a>=0;a--)(o=e[a])&&(i=(r?o(t,n,i):o(i))||i);return r&&i&&_r(t,n,i),i},z=(e,t)=>(n,r)=>t(n,r,e),br=`Terminal input`,xr={get:()=>br,set:e=>br=e},Sr=`Too much output to announce, navigate to rows manually to read`,Cr={get:()=>Sr,set:e=>Sr=e};function wr(e){return e.replace(/\r?\n/g,`\r`)}function Tr(e,t){return t?`\x1B[200~`+e+`\x1B[201~`:e}function B(e,t){e.clipboardData&&e.clipboardData.setData(`text/plain`,t.selectionText),e.preventDefault()}function Er(e,t,n,r){e.stopPropagation(),e.clipboardData&&Dr(e.clipboardData.getData(`text/plain`),t,n,r)}function Dr(e,t,n,r){e=wr(e),e=Tr(e,n.decPrivateModes.bracketedPasteMode&&r.rawOptions.ignoreBracketedPasteMode!==!0),n.triggerDataEvent(e,!0),t.value=``}function Or(e,t,n){let r=n.getBoundingClientRect(),i=e.clientX-r.left-10,a=e.clientY-r.top-10;t.style.width=`20px`,t.style.height=`20px`,t.style.left=`${i}px`,t.style.top=`${a}px`,t.style.zIndex=`1000`,t.focus()}function kr(e,t,n,r,i){Or(e,t,n),i&&r.rightClickSelect(e),t.value=r.selectionText,t.select()}function Ar(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function jr(e,t=0,n=e.length){let r=``;for(let i=t;i<n;++i){let t=e[i];t>65535?(t-=65536,r+=String.fromCharCode((t>>10)+55296)+String.fromCharCode(t%1024+56320)):r+=String.fromCharCode(t)}return r}var Mr=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let n=e.length;if(!n)return 0;let r=0,i=0;if(this._interim){let n=e.charCodeAt(i++);56320<=n&&n<=57343?t[r++]=(this._interim-55296)*1024+n-56320+65536:(t[r++]=this._interim,t[r++]=n),this._interim=0}for(let a=i;a<n;++a){let i=e.charCodeAt(a);if(55296<=i&&i<=56319){if(++a>=n)return this._interim=i,r;let o=e.charCodeAt(a);56320<=o&&o<=57343?t[r++]=(i-55296)*1024+o-56320+65536:(t[r++]=i,t[r++]=o)}else i!==65279&&(t[r++]=i)}return r}},Nr=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let n=e.length;if(!n)return 0;let r=0,i,a,o,s,c=0,l=0;if(this.interim[0]){let i=!1,a=this.interim[0];a&=(a&224)==192?31:(a&240)==224?15:7;let o=0,s;for(;(s=this.interim[++o]&63)&&o<4;)a<<=6,a|=s;let c=(this.interim[0]&224)==192?2:(this.interim[0]&240)==224?3:4,u=c-o;for(;l<u;){if(l>=n)return 0;if(s=e[l++],(s&192)!=128){l--,i=!0;break}this.interim[o++]=s,a<<=6,a|=s&63}i||(c===2?a<128?l--:t[r++]=a:c===3?a<2048||a>=55296&&a<=57343||a===65279||(t[r++]=a):a<65536||a>1114111||(t[r++]=a)),this.interim.fill(0)}let u=n-4,d=l;for(;d<n;){for(;d<u&&!((i=e[d])&128)&&!((a=e[d+1])&128)&&!((o=e[d+2])&128)&&!((s=e[d+3])&128);)t[r++]=i,t[r++]=a,t[r++]=o,t[r++]=s,d+=4;if(i=e[d++],i<128)t[r++]=i;else if((i&224)==192){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128||(c=(i&31)<<6|a&63,c<128)){d--;continue}t[r++]=c}else if((i&240)==224){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,r;if(o=e[d++],(o&192)!=128){d--;continue}if(c=(i&15)<<12|(a&63)<<6|o&63,c<2048||c>=55296&&c<=57343||c===65279)continue;t[r++]=c}else if((i&248)==240){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,r;if(o=e[d++],(o&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,this.interim[2]=o,r;if(s=e[d++],(s&192)!=128){d--;continue}if(c=(i&7)<<18|(a&63)<<12|(o&63)<<6|s&63,c<65536||c>1114111)continue;t[r++]=c}}return r}},Pr=``,Fr=` `,Ir=class e{constructor(){this.fg=0,this.bg=0,this.extended=new Lr}static toColorRGB(e){return[e>>>16&255,e>>>8&255,e&255]}static fromColorRGB(e){return(e[0]&255)<<16|(e[1]&255)<<8|e[2]&255}clone(){let t=new e;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)==50331648}isBgRGB(){return(this.bg&50331648)==50331648}isFgPalette(){return(this.fg&50331648)==16777216||(this.fg&50331648)==33554432}isBgPalette(){return(this.bg&50331648)==16777216||(this.bg&50331648)==33554432}isFgDefault(){return!(this.fg&50331648)}isBgDefault(){return!(this.bg&50331648)}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)==50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)==16777216||(this.extended.underlineColor&50331648)==33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?!(this.extended.underlineColor&50331648):this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},Lr=class e{constructor(e=0,t=0){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 urlId(){return this._urlId}set urlId(e){this._urlId=e}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}clone(){return new e(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},Rr=class e extends Ir{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new Lr,this.combinedData=``}static fromCharData(t){let n=new e;return n.setFromCharData(t),n}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?Ar(this.content&2097151):``}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(e){this.fg=e[0],this.bg=0;let t=!1;if(e[1].length>2)t=!0;else if(e[1].length===2){let n=e[1].charCodeAt(0);if(55296<=n&&n<=56319){let r=e[1].charCodeAt(1);56320<=r&&r<=57343?this.content=(n-55296)*1024+r-56320+65536|e[2]<<22:t=!0}else t=!0}else this.content=e[1].charCodeAt(0)|e[2]<<22;t&&(this.combinedData=e[1],this.content=2097152|e[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},zr=`di$target`,Br=`di$dependencies`,Vr=new Map;function Hr(e){return e[Br]||[]}function Ur(e){if(Vr.has(e))return Vr.get(e);let t=function(e,n,r){if(arguments.length!==3)throw Error(`@IServiceName-decorator can only be used to decorate a parameter`);Wr(t,e,r)};return t._id=e,Vr.set(e,t),t}function Wr(e,t,n){t[zr]===t?t[Br].push({id:e,index:n}):(t[Br]=[{id:e,index:n}],t[zr]=t)}var Gr=Ur(`BufferService`),Kr=Ur(`CoreMouseService`),qr=Ur(`CoreService`),Jr=Ur(`CharsetService`),Yr=Ur(`InstantiationService`),Xr=Ur(`LogService`),Zr=Ur(`OptionsService`),Qr=Ur(`OscLinkService`),$r=Ur(`UnicodeService`),ei=Ur(`DecorationService`),ti=class{constructor(e,t,n){this._bufferService=e,this._optionsService=t,this._oscLinkService=n}provideLinks(e,t){let n=this._bufferService.buffer.lines.get(e-1);if(!n){t(void 0);return}let r=[],i=this._optionsService.rawOptions.linkHandler,a=new Rr,o=n.getTrimmedLength(),s=-1,c=-1,l=!1;for(let t=0;t<o;t++)if(c!==-1||n.hasContent(t)){if(n.loadCell(t,a),a.hasExtendedAttrs()&&a.extended.urlId){if(c===-1){c=t,s=a.extended.urlId;continue}l=a.extended.urlId!==s}else c!==-1&&(l=!0);if(l||c!==-1&&t===o-1){let n=this._oscLinkService.getLinkData(s)?.uri;if(n){let a={start:{x:c+1,y:e},end:{x:t+ +(!l&&t===o-1),y:e}},s=!1;if(!i?.allowNonHttpProtocols)try{let e=new URL(n);[`http:`,`https:`].includes(e.protocol)||(s=!0)}catch{s=!0}s||r.push({text:n,range:a,activate:(e,t)=>i?i.activate(e,t,a):ni(e,t),hover:(e,t)=>i?.hover?.(e,t,a),leave:(e,t)=>i?.leave?.(e,t,a)})}l=!1,a.hasExtendedAttrs()&&a.extended.urlId?(c=t,s=a.extended.urlId):(c=-1,s=-1)}}t(r)}};ti=R([z(0,Gr),z(1,Zr),z(2,Qr)],ti);function ni(e,t){if(confirm(`Do you want to navigate to ${t}?
4
+ `))}function ze(e){let t=[],n=0;for(;n<e.length;){let o=e[n],s=o.match(/^(`{3,})([^\n]*)$/);if(s&&!/^```.+\`\`\`/.test(o)){let r=s[1].length,i=s[2].trim().split(/\s+/)[0]??``,a=[];n++;let o=RegExp("^`{"+r+`,}\\s*$`);for(;n<e.length&&!o.test(e[n]);)a.push(e[n++]);n++;let c=i?i.split(/\s+/)[0]:``,l=c?c.split(`/`).pop().split(`.`).pop().replace(/[^\w+#-]/g,``):``,u=l?` class="language-${l}"`:``;t.push(`<pre><code${u}>${a.join(`
5
+ `)}</code></pre>`);continue}if(/^ {0,3}(?:-{3,}|\*{3,}|_{3,})\s*$/.test(o)){t.push(`<hr>`),n++;continue}let c=o.match(/^(#{1,6})\s+(.*)$/);if(c){t.push(`<h${c[1].length}>${a(c[2])}</h${c[1].length}>`),n++;continue}if(/^\s*&gt;/.test(o)){let r=[];for(;n<e.length&&/^\s*&gt;/.test(e[n]);)r.push(e[n++].replace(/^\s*&gt;\s?/,``));t.push(`<blockquote>${ze(r)}</blockquote>`);continue}if(o.includes(`|`)&&n+1<e.length&&Ve(e[n+1])){let r=Be(e[n+1]).map(e=>e.startsWith(`:`)&&e.endsWith(`:`)?`center`:e.endsWith(`:`)?`right`:`left`),i=Be(o);n+=2;let s=[];for(;n<e.length&&/\S/.test(e[n])&&e[n].includes(`|`);)s.push(Be(e[n])),n++;let c=(e,t,n)=>{let i=r[t];return`<${n}${i&&i!==`left`?` style="text-align:${i}"`:``}>${a(e)}</${n}>`},l=i.some(e=>e!==``);t.push(`<div class="tbl"><table>`+(l?`<thead><tr>${i.map((e,t)=>c(e,t,`th`)).join(``)}</tr></thead>`:``)+`<tbody>${s.map(e=>`<tr>${e.map((e,t)=>c(e,t,`td`)).join(``)}</tr>`).join(``)}</tbody></table></div>`);continue}if(Le.test(o)){t.push(i(r(o.match(Le)[1])));continue}if(/^\s*$/.test(o)){n++;continue}let l=n,u=[];for(;n<e.length&&!/^\s*$/.test(e[n])&&!/^#{1,6}\s/.test(e[n])&&!e[n].startsWith("```")&&!/^ {0,3}(?:-{3,}|\*{3,}|_{3,})\s*$/.test(e[n])&&!/^\s*&gt;/.test(e[n])&&!Le.test(e[n])&&!(e[n].includes(`|`)&&n+1<e.length&&Ve(e[n+1]));)u.push(e[n++]);n===l&&u.push(e[n++]),t.push(`<p>${u.map(a).join(`<br>`)}</p>`)}return t.join(`
6
+ `);function r(e){return e.replace(/\t/g,` `).length}function i(t){let o=null,s=1,c=[];for(;n<e.length;){let l=e[n].match(Le);if(!l)break;let u=r(l[1]);if(u<t)break;let d=/^\d/.test(l[2]);if(o===null)o=d;else if(d!==o)break;if(o&&c.length===0){let e=Number.parseInt(l[2],10);Number.isFinite(e)&&(s=e)}n++;let f=l[3];for(;n<e.length&&/\S/.test(e[n])&&!Le.test(e[n])&&!/^#{1,6}\s/.test(e[n])&&!e[n].startsWith("```")&&!/^\s*&gt;/.test(e[n])&&!/^ {0,3}(?:-{3,}|\*{3,}|_{3,})\s*$/.test(e[n])&&!/^ {0,3}={3,}\s*$/.test(e[n])&&!(e[n].includes(`|`)&&n+1<e.length&&Ve(e[n+1]));)f+=` `+e[n].trim(),n++;let p=``,m=e[n]?.match(Le);m&&r(m[1])>u&&(p=i(r(m[1])));let h=f.match(/^\[( |x|X)\]\s+(.*)$/),g=h?`<input type="checkbox" disabled${h[1].toLowerCase()===`x`?` checked`:``}> `:``;c.push(`<li>${g}${a(h?h[2]:f)}${p}</li>`);let _=n;for(;_<e.length&&!/\S/.test(e[_]);)_++;let v=e[_]?.match(Le);_>n&&v&&r(v[1])===u&&/^\d/.test(v[2])===o&&(n=_)}return o?s===1?`<ol>${c.join(``)}</ol>`:`<ol start="${s}">${c.join(``)}</ol>`:`<ul>${c.join(``)}</ul>`}function a(e){let t=[];return e=e.replace(/\u0000/g,``),e=e.replace(/`([^`]+)`/g,(e,n)=>(t.push(`<code>${n}</code>`),`\ue000${t.length-1}\uE001`)),e=e.replace(/!\[([^\]]*)\]\((https?:\/\/[^)\s]+)(?:\s+&quot;[^)]*&quot;)?\)/g,(e,n,r)=>(t.push(`<img src="${r}" alt="${n}" loading="lazy">`),`\ue000${t.length-1}\uE001`)),e=e.replace(/\[([^\]]+)\]\((https?:\/\/[^)\s]+)(?:\s+&quot;[^)]*&quot;)?\)/g,(e,n,r)=>(t.push(`<a href="${r}" rel="noopener noreferrer" target="_blank">${n}</a>`),`\ue000${t.length-1}\uE001`)),e=e.replace(/(?<!["'=\w])(https?:\/\/[^\s<>"')\]]*[^\s<>"')\].,;:!?"')\]])/g,`<a href="$1">$1</a>`),e=e.replace(/\*\*\*([\s\S]+?)\*\*\*/g,`<strong><em>$1</em></strong>`),e=e.replace(/\*\*([\s\S]+?)\*\*/g,`<strong>$1</strong>`),e=e.replace(/(^|[^\w])__(?=\S)([\s\S]*?\S)__(?!\w)/g,`$1<strong>$2</strong>`),e=e.replace(/(^|[^\w*])\*(?!\s)([^*\n]+?)\*(?![\w*])/g,`$1<em>$2</em>`),e=e.replace(/(^|[^\w])_(?!\s)([^_\n]+?)_(?!\w)/g,`$1<em>$2</em>`),e=e.replace(/~~([\s\S]+?)~~/g,`<del>$1</del>`),e.replace(/\ue000(\d+)\ue001/g,(e,n)=>t[+n]??``)}}function Be(e){let t=e.trim();t.startsWith(`|`)&&(t=t.slice(1));let n=[],r=``;for(let e=0;e<t.length;e++){let i=t[e];if(i===`\\`&&t[e+1]===`|`)r+=`|`,e++;else if(i==="`"){let n=t.indexOf("`",e+1);if(n!==-1){r+=t.slice(e,n+1).replace(/\\\|/g,`|`),e=n;continue}r+=i}else{if(i===`|`&&e===t.length-1)break;i===`|`?(n.push(r.trim()),r=``):r+=i}}return n.push(r.trim()),n.filter((e,r)=>!(e===``&&r===n.length-1&&t.endsWith(`|`)))}function Ve(e){let t=e.trim();if(!t.includes(`|`)||!t.includes(`-`))return!1;let n=Be(t);return n.every(e=>/^:?-+:?$/.test(e))&&n.some(e=>e!==``)}function He(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`)}function Ue(e){return Math.max(0,e.height-e.viewport)}function We(e){return e?Math.max(0,e.height-e.top-e.viewport):1/0}function Ge(e,t=24){return e?We(e)<=t:!1}function Ke(e,t,n,r){if(r!==void 0&&Math.abs(e.viewport-r)>.5||n!==void 0&&Math.abs(e.height-n)>.5)return`layout`;if(t){let n=Math.min(t.top,Ue(e));if(Math.abs(e.top-n)<=.5)return`programmatic`}return`reader`}function qe(e,t){return e?We(t)<=64:!1}function Je(e,t,n,r){return t===`reader`?r!==void 0&&n.top<r-.5?!1:Ge(n):e||Ge(n)}function Ye(e,t,n=.5){return e?We(t)>n:!1}var Xe=We;function Ze(e,t,n=200){return!t||e-t>=n}function Qe(e,t){let n=String(e??``).trim();return!n||!t||n===t}var[$e,et]=y(null),tt=$e;function nt(e){e&&et(e)}function rt(){et(null)}function it(e,t){let n=0,r=()=>{let t=0;for(let n of e.values())t+=n.bytes;return t};for(;e.size>t.maxEntries||r()>t.maxBytes;){let t,r=1/0;for(let[n,i]of e)i.at<r&&(r=i.at,t=n);if(t===void 0||(e.delete(t),n++,e.size===0))break}return n}function at(e,t=0){if(t>8)return 8;if(e==null)return 4;switch(typeof e){case`string`:return 16+e.length*2;case`number`:case`boolean`:return 8;case`object`:{if(Array.isArray(e)){let n=16;for(let r of e)n+=at(r,t+1);return n}let n=16;for(let[r,i]of Object.entries(e))n+=8+r.length*2+at(i,t+1);return n}default:return 8}}var ot=new Map,st=0,ct=500,lt=4194304;function ut(e){let t=ot.get(e);if(t!==void 0)return t;let n=Re(e);for(ot.set(e,n),st+=(e.length+n.length)*2;(ot.size>ct||st>lt)&&ot.size;){let e=ot.keys().next().value;if(e===void 0)break;let t=ot.get(e)??``;st-=(e.length+t.length)*2,ot.delete(e)}return n}function dt(e){if(e==null||!Number.isFinite(e))return`?`;let t=Math.max(0,e);if(t<1e3)return`${Math.round(t)}ms`;if(t<6e4)return`${(Math.floor(t/100)/10).toFixed(1)}s`;let n=Math.round(t/1e3);if(n<3600){let e=Math.floor(n/60),t=n%60;return t?`${e}m ${t}s`:`${e}m`}let r=Math.round(n/60),i=Math.floor(r/60),a=r%60;return a?`${i}h ${a}m`:`${i}h`}function ft(e,t){return e.length>t?e.slice(0,t)+` …`:e}function pt(e){let t=new Date(e).getTime()-Date.now(),n=Math.abs(t),r=n<9e4?`${Math.round(n/1e3)}s`:n<54e5?`${Math.round(n/6e4)}m`:`${(n/36e5).toFixed(1)}h`;return t>=0?`in ${r}`:`${r} ago`}function mt(e,t,n,r=Date.now()){let i=new Map(e);return i.set(t,{text:n.text??``,reasoning:n.reasoning??``,at:r}),i}function ht(e,t){if(!e.has(t))return e;let n=new Map(e);return n.delete(t),n}function gt(e){let t=e;return t?.type===`state`&&t.data?.detail===`llm turn start`||t?.type===`question`}function _t(e){return e===`running`||e===`waiting`||e===`needs_operator`}function vt(e,t,n){let r=e.text.trim(),i=St(t),a=_t(n);return{textCovered:!r||i.has(r),reasoningStale:!e.reasoning.trim()||xt(t).has(e.reasoning.trim())||a&&bt(t,e.at)}}function yt(e,t,n){let r=vt(e,t,n),i=r.textCovered?``:e.text,a=r.reasoningStale?``:e.reasoning,o=_t(n),s=!i.trim()&&!a.trim(),c=!!e.text.trim()||!!e.reasoning.trim();return{text:i,reasoning:a,live:o,empty:s&&(!o||c)}}function bt(e,t){return t?e.some(e=>{if(e.type!==`tool_call`)return!1;let n=Date.parse(String(e.ts??``));return Number.isFinite(n)&&n>t}):!1}function xt(e){let t=new Set;for(let n of e){let e=String(n.data?.reasoning??``).trim();e&&t.add(e)}return t}function St(e){let t=new Set;for(let n of e)n.type===`message`&&n.data?.role===`assistant`&&t.add(String(n.data.content??``).trim());return t}function Ct(e){if(!e)return!1;let t=e.data?.actor;return!(typeof t==`string`&&t.length>0)}var wt=new Set([`stopped`,`error`]),Tt=2e3;function Et(e,t,n=Date.now()){let r=[];for(let[i,a]of e){let e=t(i);e!==void 0&&(!wt.has(e)&&(_t(e)||n-Number(a?.at??0)<=Tt)||r.push(i))}if(r.length===0)return e;let i=new Map(e);for(let e of r)i.delete(e);return i}function Dt(e,t,n){if(!e)return null;let r=yt(e,t,n);return r.empty?null:r.text===e.text&&r.reasoning===e.reasoning?e:{text:r.text,reasoning:r.reasoning,at:e.at}}function Ot(e,t,n,r){if(!e)return 0;if(r)return e;if(!n)return 0;let i=t.find(e=>e.id===n);return i?.status===`running`||i?.status===`waiting`||i?.status===`needs_operator`?e:0}function kt(e,t){if(!t.length)return[...e].sort((e,t)=>e.seq-t.seq);let n=e.reduce((e,t)=>Math.max(e,t.seq),0),r=t.map((e,t)=>e.seq>n?e:{...e,seq:n+1+t});return[...e,...r].sort((e,t)=>e.seq-t.seq)}function At(e,t){if(t===void 0||t<=e.seq)return e;let n=jt.get(e);n||(n=new Map,jt.set(e,n));let r=n.get(t);if(r)return r;let i={...e,seq:t};return n.set(t,i),i}var jt=new WeakMap;function Mt(e,t){return t===void 0?e.reduce((e,t)=>Math.max(e,t.seq),0)+1:t}var Nt=new Set([`report_progress`,`ask_operator`,`ask_user`,`record_decision`]);function Pt(e){let{events:t,consumed:n,feedTypes:r}=e;return t.filter(e=>{if(e.type===`sub`)return!0;if(!r.has(e.type))return!1;let t=e.type===`tool_call`||e.type===`tool_result`?String(e.data?.name??``):``;if(Nt.has(t))return!1;if(e.type===`tool_result`)return!n.has(e.id);if(e.type===`message`){let t=String(e.data?.content??``),n=String(e.data?.reasoning??``);return t.trim()===``&&n.trim()!==``&&e.data?._prevKind===`tool`||e.data?.progressEcho||!e.data?.final&&t.trim()===`(tool call)`?!1:t.trim()!==``||n.trim()!==``||!!e.data?.final}return!0})}function Ft(e){let t=[];for(let n of e){if(n.type!==`sub`){t.push(n);continue}let e=n.data,r=String(e?.type??`message`);r!==`state`&&t.push({...n,type:r,data:{...e?.data??{},actor:e?.sub}})}return t}var It=e=>String(e??``).replace(/\s+/g,` `).trim().toLowerCase();function Lt(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n];if(r.type===`message`&&r.data?.role===`assistant`){let e=t[t.length-1],n=e?.type;if(n===`progress`||n===`decision`||e?.data?.progressEcho){let t=It(r.data?.content),n=It(e?.data?.content);if(t&&t===n)continue}}t.push(r)}return t}function Rt(e){let t=new Set,n=new Set,r=new Set,i=new Map,a=new Map;for(let o of e){let e=o.data?.promptId;e&&(o.type===`prompt`&&r.add(String(e)),o.type===`prompt`&&o.data?.source===`user`&&n.add(String(e)),o.type===`system_note`&&o.data?.event===`prompt-delivered`&&(t.add(String(e)),i.set(String(e),o.seq)),o.type===`system_note`&&o.data?.event===`prompt-cancelled`&&a.set(String(e),o.seq))}return{deliveredIds:t,loggedUserPrompts:n,loggedPromptIds:r,deliveredNotes:i,cancelledNotes:a}}var zt=new WeakMap,Bt=2**53-1-1e5,Vt=new Set;function Ht(e,t,n){return e.map(e=>{if(e.type!==`prompt`||!(Number(e.data?.ahead??0)>0))return e;let r=String(e.data?.promptId??``);if(t.deliveredIds.has(r)||t.cancelledNotes.has(r)||n&&n.size>0&&!n.has(r)||e.data?.pending)return e;let i=zt.get(e);if(i)return i;let a={...e,seq:Bt+e.seq,data:{...e.data,pending:!0,queued:!0}};return zt.set(e,a),a})}function Ut(e,t,n){return e.filter(e=>{if(!t.renderedTypes.has(e.type))return e.type===`system_note`&&t.renderedNoteEvents.has(String(e.data?.event??``));if(e.type!==`prompt`)return!0;let r=String(e.data?.promptId??``);return r===``||!n.has(r)})}var Wt=new WeakMap;function Gt(e,t){let n=Wt.get(e);n||(n=new Map,Wt.set(e,n));let r=n.get(t);if(r)return r;let i={...e,data:{...e.data??{},cancelled:!0}};return n.set(t,i),i}function Kt(e,t){let n=t=>Mt(e,t),r=[];for(let i of e){if(i.type!==`prompt`||i.data?.source!==`user`){r.push(i);continue}let e=String(i.data?.promptId??``),a=t.cancelledNotes.get(e),o=t.deliveredNotes.get(e)??0,s=Math.max(o,a??0)||void 0,c=a===void 0?i:Gt(i,a);if(s!==void 0){r.push(At(c,s));continue}let l=n(c.seq);r.push(c.seq===l?c:{...c,seq:l})}return r}function qt(e,t){return e.filter(e=>!e.promptId||!(t.deliveredIds.has(e.promptId)&&t.loggedUserPrompts.has(e.promptId)))}function Jt(e){let t=Lt(Ft(Pt(e))),n=Rt(t),r=new Set;for(let t of e.pending)t.promptId&&!n.deliveredIds.has(t.promptId)&&r.add(t.promptId);for(let t of e.serverPendingIds??[])t&&!n.deliveredIds.has(t)&&e.pending.some(e=>e.promptId===t)&&r.add(t);let i=Ht(t,n,new Set(e.serverPendingIds??[])),a=qt(e.pending,n).filter(e=>!e.promptId||!n.loggedPromptIds.has(e.promptId)),o=kt(Kt(Ut(i,e,Vt),n),a.map(e.echo));return{rows:o,pendingCount:o.filter(e=>(e.data?.pending||e.data?.echo)&&e.data?.queued!==!1).length}}function Yt(e){let t=e.event;return t===`status`||t===`audit-started`||t===`audit`||t===`audit-failed`?t:`other`}function Xt(e){let t=e.trim().toLowerCase();return t===``||t===`(no detail)`||t===`no detail`||t===`(none)`||t===`(empty)`}function Zt(e,t){let n=String(e??``).trim();return Xt(n)?Xt(t)?``:t:n}function Qt(e){switch(Yt(e)){case`audit-started`:return{label:`🔍️ completion audit started`,detail:String(e.verify??``).trim()||`checking the verification contract…`,tone:``,markdown:!1,hasCard:!0};case`audit`:{let t=!Xt(String(e.feedback??``));return e.verdict===`approved`?{label:`✅ audit: approved`,detail:Zt(e.feedback??``,``),tone:`ok`,markdown:!0,hasCard:t}:{label:`⚠ audit: changes required`,detail:Zt(e.feedback??``,``),tone:`warn`,markdown:!0,hasCard:t}}case`audit-failed`:return{label:`🔍️ audit unavailable — finish accepted`,detail:String(e.detail??``).trim()||`the auditor could not be reached`,tone:`err`,markdown:!1,hasCard:!0};case`status`:{let t=String(e.status??``).trim();return t?t===`done`?String(e.by??``).trim()===`operator`?{label:`🏁 goal marked done`,detail:`you marked this goal done — no audit runs for a manual completion`,tone:``,markdown:!1,hasCard:!0}:{label:`🏁 finish claimed — pending audit`,detail:`the agent called finish(goalComplete=true); the verification contract is now being audited`,tone:``,markdown:!1,hasCard:!0}:t===`active`?String(e.by??``).trim()===`auditor`?{label:`▶ goal reopened`,detail:`the audit rejected the finish — work continues on the same goal`,tone:`warn`,markdown:!1,hasCard:!0}:{label:`▶ goal resumed`,detail:`marked active again — auto-continue picks the goal up from the next turn`,tone:``,markdown:!1,hasCard:!0}:{label:`🎯 goal ${t||`updated`}`,detail:String(e.text??``).trim()||`the goal is now ${t}`,tone:``,markdown:!0,hasCard:!0}:{label:`🎯 goal status updated`,detail:String(e.text??``).trim()||`no status recorded`,tone:``,markdown:!0,hasCard:!0}}default:{let t=String(e.text??``).trim(),n=String(e.event??``).trim();return{label:n?`🎯 goal ${n}`:`🎯 goal updated`,detail:t||`the "${n||`goal`}" event carried no further detail`,tone:``,markdown:!0,hasCard:!0}}}}var $t=F(`<span class="meta muted">`),en=F(`<div class=ctitle>`),tn=F(`<div>`),nn=F(`<div class=cardbody>`);function rn(e){let t=()=>{let t=e.tone;return[`card`,t?`card-${t}`:``,e.class??``].filter(Boolean).join(` `)},n=()=>e.markdown===!1?Re(`\`\`\`\n${e.body}\n\`\`\``):Re(e.body);return(()=>{var r=tn();return R(r,j(N,{get when(){return e.title},get children(){var t=en();return R(t,()=>e.title,null),R(t,j(N,{get when(){return e.meta},get children(){var t=$t();return R(t,()=>e.meta),t}}),null),t}}),null),R(r,()=>e.children??(()=>{var e=nn();return b(()=>e.innerHTML=n()),e})(),null),b(()=>L(r,t())),r})()}function an(e){let t=e.hideGhosts?e.agents.filter(e=>!e.workspaceMissing):e.agents,n=t.length?t:e.agents,r=e.urlId,i=r?e.ownerOf(r):void 0;return(i?n.find(e=>e.id===i):void 0)??n.find(t=>t.id===e.lastId)??n[0]}function on(e,t){let n=new Map;for(let t of e)n.set(t.id,t);for(let e of t)n.set(e.id,e);return[...n.values()]}var sn=[320,640,1280,1920,2560,3840],cn=sn[0],ln=/^\/api\/assets\/[a-f0-9]{32}\.(png|jpg|jpeg|gif|webp|avif)$/i;function un(e,t){if(e)return ln.test(e)?`${e}?w=${t}`:e}function dn(e){if(e)return sn.map(t=>`${un(e,t)} ${t}w`).join(`, `)}function fn(e,t=cn){return un(e,t)}function pn(e,t=new Set,n=!1,r=new Set){let i=n?e.filter(t=>{if(!t.workspaceMissing)return!0;let n=[t.id],r=new Set;for(;n.length;){let t=n.pop();if(!r.has(t)){r.add(t);for(let i of e)i.parent===t&&!r.has(i.id)&&n.push(i.id)}}for(let t of r){let n=e.find(e=>e.id===t);if(n&&!n.workspaceMissing)return!0}return!1}):e,a=new Map,o=[];for(let e of i)e.parent&&i.some(t=>t.id===e.parent)?(a.has(e.parent)||a.set(e.parent,[]),a.get(e.parent).unshift(e)):o.push(e);let s=[],c=(e,n)=>{for(let o of e){let e=n===0&&r.has(vn(i,o));if(s.push({a:o,depth:n}),e)continue;let l=a.get(o.id);l?.length&&!t.has(o.id)&&c(l,n+1)}},l=[],u=new Map;for(let e of o){if(e.parent)continue;let t=mn(i,e.id),n=u.get(t);n?n.push(e):(u.set(t,[e]),l.push(t))}for(let t of o){if(!t.parent)continue;let n=mn(e,t.id)||``,r=u.get(n);r?r.push(t):(u.set(n,[t]),l.push(n))}for(let e of l)c(u.get(e),0);return s}function mn(e,t,n=new Set){let r=e.find(e=>e.id===t);return r?!r.parent||n.has(t)?r.workspace||``:(n.add(t),mn(e,r.parent,n)||r.workspace||``):``}function hn(e){return e.isSub?e.hasChildren:e.collapsed||e.hasChildren}function gn(e,t=[]){let n=e.indexOf(`-sub`);if(n===-1)return null;let r=e.slice(n+4).replace(/^-+/,``);if(!r)return null;let i=r.split(`-`);return(t.includes(i[0]??``)?i.slice(1).join(`-`):r).replace(/_/g,` `).trim()||null}function _n(e,t,n=new Set){let r=[],i=new Set(n);for(let n of e)n.parent===t&&(i.has(n.id)||(i.add(n.id),r.push(n,..._n(e,n.id,i))));return r}function vn(e,t){let n=t.id,r=new Set;for(;;){let t=e.find(e=>e.id===n);if(!t?.parent||r.has(n))break;r.add(n),n=t.parent}return`chat:${n||t.id}`}function yn(e){let t=new Map;for(let n of e){if(n.parent)continue;let r=mn(e,n.id);r&&t.set(r,(t.get(r)??0)+1)}return t}function bn(e,t,n=new Set){let r=[],i=null;for(let a of t){let t=mn(e,a.a.id);t?(t!==i&&(i=t,r.push({a:a.a,depth:0,headerOnly:!0,wsHeader:t,wsCollapsedGroup:n.has(`ws:${t}`)})),!n.has(`ws:${t}`)&&(n.has(vn(e,a.a))?r.push({a:a.a,depth:a.depth,chatCollapsedGroup:!0}):r.push({a:a.a,depth:a.depth}))):r.push({a:a.a,depth:a.depth})}return r}function xn(e,t=new Set){let n=new Set,r=-1,i=-1;for(let t of e)t.type===`question`?r=t.seq:t.type===`prompt`&&t.data?.source===`user`?i=t.seq:t.type===`system_note`&&t.data?.event===`prompt-delivered`&&(i=Math.max(i,t.seq));if(r>=0&&i>r)for(let t of e)t.type===`question`&&t.seq<=i&&n.add(String(t.data?.callId??``));for(let e of t)n.add(e);return n}var Sn=(e,t,n)=>{if(t>=e.length)return e;if(n?.length){let r=new Set(n),i=e.filter(e=>e.promptId&&r.has(e.promptId));if(i.length){let n=e.filter(e=>!e.promptId);return n.length?[...i,...n].slice(0,t):i}}return e.slice(0,t)};function Cn(e,t){let n=new Set(e.map(e=>e.promptId??e.id).filter(e=>!!e)),r=e.filter(e=>!e.promptId).map(e=>e.text),i=[];for(let e of t){let t=typeof e.id==`string`?e.id:``;if(!t||n.has(t))continue;let a=r.indexOf(String(e.text??``));a===-1?i.push({id:`p${t}`,text:String(e.text??``),at:Number(e.at)||Date.now(),promptId:t,queued:!0,images:e.images?.map(e=>e.url),...e.source?{source:e.source}:{}}):r.splice(a,1)}return i.length?[...e,...i]:e}var wn=(e=!1)=>e;function Tn(e,t,n){let r=e??[];return n&&r.includes(n)?n:t&&r.includes(t)||t&&r.length===0?t:r[0]??null}function En(e,t,n){return!t||n&&t===n?!0:typeof e==`string`&&e===t}function Dn(e,t,n){return!e||!t||e.agent!==t?!1:En(e.session,n,t)}function On(e,t,n){return!e||!t||e.agentId!==t||!e.sessionId?!1:En(e.sessionId,n,t)}function kn(e,t,n){return n?!e||!t||t===e.id||!e.session||e.session===t:!1}function An(e,t){if(t>=1)return e;let n=/^#([0-9a-f]{6})$/i.exec(e.trim());if(n){let e=Number.parseInt(n[1],16);return`rgba(${e>>16&255}, ${e>>8&255}, ${e&255}, ${Math.max(0,Math.min(1,t))})`}let r=/^rgba?\(([^)]+)\)$/i.exec(e.trim());if(r){let[e,n,i]=r[1].split(`,`).map(e=>e.trim());return`rgba(${e}, ${n}, ${i}, ${Math.max(0,Math.min(1,t))})`}return e}function jn(e=1){let t=``,n=``,r=``,i=``;try{let e=getComputedStyle(document.documentElement);t=e.getPropertyValue(`--term-bg`).trim(),n=e.getPropertyValue(`--term-fg`).trim(),r=e.getPropertyValue(`--term-cursor`).trim(),i=e.getPropertyValue(`--term-cursor-accent`).trim()}catch{}let a=t||`#0d0e12`,o=An(a,e),s=n||`#dcdee4`;return{background:o,foreground:s,cursor:r||s,cursorAccent:i||a,selectionBackground:Nn(s),selectionForeground:s}}function Mn(e,t=1){let n=jn(t),r=e.options.theme;r&&r.background===n.background&&r.foreground===n.foreground&&r.cursor===n.cursor&&r.cursorAccent===n.cursorAccent&&r.selectionBackground===n.selectionBackground||(e.options.theme=n)}function Nn(e){let t=e.trim(),n=/^#([0-9a-f]{6})$/i.exec(t);return n?`#${n[1]}47`:`rgba(128, 128, 128, 0.35)`}function Pn(e,t,n){return e?.provider||n||Object.keys(t??{})[0]||``}function Fn(e,t){return t?String(e?.[t]?.model??``).trim():``}function In(e,t,n){return Fn(e,t)||(n&&t===(n.provider??``)?n.model??``:``)}function Ln(e,t,n,r){return n?.model&&t===r?n.model:Fn(e,t)||n?.model||``}function Rn(e){return!e}function zn(e){return!e}function Bn(e,t){return e!==t}function Vn(e,t){return Math.max(1,Math.min(e,t))}function Hn(e){return typeof e!=`number`||!Number.isFinite(e)?!1:e<0}function Un(e){return e===`PageUp`||e===`ArrowUp`||e===`Home`}function Wn(e){return e.editable?!1:e.insideFeed||e.isBackground}function Gn(e,t,n){if(!n)return null;let r=e.find(e=>e.top+e.height>t+.5);if(!r)return null;let i=Math.min(Math.max(0,Math.round(t-r.top)),Math.max(0,Math.round(r.height)));return{session:n,eid:r.eid,offset:i}}function Kn(e,t,n){if(!e)return null;let r=t.find(t=>t.eid===e.eid);if(!r)return null;let i=Math.max(0,Math.min(n,Math.round(r.top+e.offset)));return Number.isFinite(n)&&i>=n-1?null:i}var qn=`teapot.textareaH.`;function Jn(e){try{let t=Number(localStorage.getItem(qn+e)??``);return Number.isFinite(t)&&t>0?t:0}catch{return 0}}function Yn(e,t){try{localStorage.setItem(qn+e,String(Math.round(t)))}catch{}}function Xn(e,t,n){return!n||!Number.isFinite(e)||e<=0?!1:!Number.isFinite(t)||t<=0||Math.abs(e-t)>=1}function Zn(e,t){let n=Jn(t);n>0&&(e.style.height=`${n}px`);let r=!1,i=()=>{r=!0};e.addEventListener(`pointerdown`,i);let a=new ResizeObserver(()=>{let n=e.offsetHeight;Xn(n,Jn(t),r)&&Yn(t,n)});return a.observe(e),()=>{e.removeEventListener(`pointerdown`,i),a.disconnect()}}var Qn=e=>e?e.sessionTitle?.trim()||e.id:``,$n=(e,t)=>{if(!e)return``;let n=Qn(e),r=t?` — ${t}`:``;return n===e.id?`${n}${r}`:`${n} — ${e.id}${r}`},er=e=>(e.sameSession,e.echoCount),tr=[{key:`bgDarkest`,cssVar:`--bg-darkest`,label:`surface (deepest)`},{key:`bgDark`,cssVar:`--bg-dark`,label:`surface`},{key:`bgMid`,cssVar:`--bg-mid`,label:`surface (raised)`},{key:`bgLight`,cssVar:`--bg-light`,label:`surface (control)`},{key:`fg`,cssVar:`--fg`,label:`text`},{key:`dim`,cssVar:`--dim`,label:`text (muted)`},{key:`line`,cssVar:`--line`,label:`divider`},{key:`acc`,cssVar:`--acc`,label:`accent`},{key:`ok`,cssVar:`--ok`,label:`success`},{key:`warn`,cssVar:`--warn`,label:`warning`},{key:`err`,cssVar:`--err`,label:`error`},{key:`tool`,cssVar:`--tool`,label:`tool accent`},{key:`termBg`,cssVar:`--term-bg`,label:`terminal background`},{key:`termFg`,cssVar:`--term-fg`,label:`terminal text`}],nr=`teapot.customThemes`,rr={bgDarkest:`#1a1c22`,bgDark:`#232630`,bgMid:`#2b2e39`,bgLight:`#343845`,fg:`#dcdee4`,dim:`#9298a5`,line:`#1d2027`,acc:`#5865f2`,ok:`#3ba55d`,warn:`#faa81a`,err:`#ed4245`,tool:`#3ba0c9`,termBg:`#0d0e12`,termFg:`#dcdee4`},ir={dark:{bgDarkest:`#1a1c22`,bgDark:`#232630`,bgMid:`#2b2e39`,bgLight:`#343845`,fg:`#dcdee4`,dim:`#9298a5`,line:`#1d2027`,acc:`#5865f2`,ok:`#3ba55d`,warn:`#faa81a`,err:`#ed4245`,tool:`#3ba0c9`,termBg:`#0d0e12`,termFg:`#dcdee4`},midnight:{bgDarkest:`#0d0f18`,bgDark:`#12141f`,bgMid:`#1b1f31`,bgLight:`#252a42`,fg:`#dfe2f2`,dim:`#8a90ad`,line:`#0a0c14`,acc:`#8b7cf7`,ok:`#54c08a`,warn:`#e5b567`,err:`#ef6a6a`,tool:`#6aa9e9`,termBg:`#0a0c13`,termFg:`#dfe2f2`},tea:{bgDarkest:`#241c16`,bgDark:`#2e241c`,bgMid:`#3b2f24`,bgLight:`#493b2d`,fg:`#f0e4d2`,dim:`#b39d82`,line:`#1b140f`,acc:`#d98e32`,ok:`#7fa653`,warn:`#e0b058`,err:`#cf5b47`,tool:`#c9975f`,termBg:`#1d1712`,termFg:`#ecdcc3`},coffee:{bgDarkest:`#191410`,bgDark:`#211a14`,bgMid:`#30271e`,bgLight:`#403527`,fg:`#ede3d0`,dim:`#a89478`,line:`#120d07`,acc:`#c68a4b`,ok:`#8aa15c`,warn:`#d9a441`,err:`#c25450`,tool:`#a67c52`,termBg:`#15100c`,termFg:`#e8dcc5`},matcha:{bgDarkest:`#1b2217`,bgDark:`#232b1e`,bgMid:`#2f3a28`,bgLight:`#3c4a33`,fg:`#e8eeda`,dim:`#9aab84`,line:`#131a10`,acc:`#8db64e`,ok:`#6fae4e`,warn:`#d8b13c`,err:`#cd5c50`,tool:`#5da88f`,termBg:`#151b11`,termFg:`#dfe8cb`},matrix:{bgDarkest:`#060a06`,bgDark:`#0a0f0a`,bgMid:`#122116`,bgLight:`#18301d`,fg:`#c9f2cf`,dim:`#6fa075`,line:`#030603`,acc:`#2fd558`,ok:`#39c95f`,warn:`#b8d977`,err:`#ff6b6b`,tool:`#57c99b`,termBg:`#030503`,termFg:`#33ff77`},sunset:{bgDarkest:`#1c1422`,bgDark:`#241b2b`,bgMid:`#33253e`,bgLight:`#452f52`,fg:`#f2e6ea`,dim:`#ab93a8`,line:`#150e1b`,acc:`#f2784b`,ok:`#63b46f`,warn:`#eda63d`,err:`#e25563`,tool:`#b06ac9`,termBg:`#170f1d`,termFg:`#f0dfe4`},sakura:{bgDarkest:`#22131f`,bgDark:`#251322`,bgMid:`#311a2d`,bgLight:`#3f213a`,fg:`#f6eaf3`,dim:`#bba6bd`,line:`#402b43`,acc:`#f2558e`,ok:`#34bd73`,warn:`#f5b83d`,err:`#f43f5e`,tool:`#a77bff`,termBg:`#170b15`,termFg:`#f2e6f0`},light:{bgDarkest:`#eceef4`,bgDark:`#f6f7fa`,bgMid:`#e2e5ee`,bgLight:`#ffffff`,fg:`#24272f`,dim:`#5d6470`,line:`#d8dbe4`,acc:`#4757d8`,ok:`#2b8a4b`,warn:`#b97a0f`,err:`#d83c3f`,tool:`#2278a8`,termBg:`#ffffff`,termFg:`#24272f`},strawberry:{bgDarkest:`#fbe4ea`,bgDark:`#fdf0f3`,bgMid:`#f7d4de`,bgLight:`#fffafb`,fg:`#4a2733`,dim:`#96707e`,line:`#f0ccd6`,acc:`#e05575`,ok:`#4d9e63`,warn:`#c98a2d`,err:`#d43d51`,tool:`#b05687`,termBg:`#fff5f8`,termFg:`#4a2733`},ramune:{bgDarkest:`#ddeff7`,bgDark:`#ecf7fb`,bgMid:`#c9e7f4`,bgLight:`#fbfeff`,fg:`#173342`,dim:`#5b7d90`,line:`#c2e2ef`,acc:`#1d86ae`,ok:`#3a9e6e`,warn:`#cf9a2a`,err:`#d64f5c`,tool:`#3a9db8`,termBg:`#f4fbfd`,termFg:`#173342`}},ar=e=>typeof e==`string`&&e.length>0&&e.length<=64&&!/[;{}]/.test(e);function or(e){if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.id!=`string`||!/^[a-z0-9-]{1,40}$/i.test(t.id)||typeof t.label!=`string`||!t.label.trim()||t.mode!==`dark`&&t.mode!==`light`)return null;let n=t.palette;if(!n||typeof n!=`object`)return null;let r={};for(let{key:e}of tr){if(!ar(n[e]))return null;r[e]=n[e]}let i={id:t.id,label:t.label.slice(0,40),mode:t.mode,palette:r};if(typeof t.backgroundImage==`string`){let e=t.backgroundImage,n=/^\/api\/assets\/[a-f0-9]{32}\.(png|jpe?g|gif|webp|avif)$/i.test(e),r=/^data:image\//.test(e)&&e.length<=15e5,a=/^https?:\/\//.test(e);(n||r||a)&&(i.backgroundImage=e)}return typeof t.backgroundDim==`number`&&Number.isFinite(t.backgroundDim)&&(i.backgroundDim=Math.min(.9,Math.max(0,t.backgroundDim))),typeof t.backgroundImageBytes==`number`&&Number.isFinite(t.backgroundImageBytes)&&(i.backgroundImageBytes=Math.max(0,Math.round(t.backgroundImageBytes))),typeof t.surfaceAlpha==`number`&&Number.isFinite(t.surfaceAlpha)&&(i.surfaceAlpha=Math.min(1,Math.max(.35,t.surfaceAlpha))),i}function sr(){try{let e=localStorage.getItem(nr);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t.map(or).filter(e=>e!==null):[]}catch{return[]}}function cr(e){try{return localStorage.setItem(nr,JSON.stringify(e)),fetch(`/api/themes`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({themes:e})}).catch(()=>{}),{ok:!0}}catch(e){return{ok:!1,error:e.name===`QuotaExceededError`||/quota/i.test(String(e.message))?`storage is full — that background image is too large. Try a smaller one, or remove another theme.`:`could not save: ${e.message}`}}}async function lr(){try{let e=await fetch(`/api/themes`);if(!e.ok)return null;let t=await e.json();return Array.isArray(t.themes)?t.themes.map(or).filter(e=>e!==null):null}catch{return null}}function ur(e){for(let t=0;;t++){let n=`custom-${Date.now().toString(36)}${t?`-${t}`:``}`;if(!e.includes(n))return n}}function dr(e,t){let n=new Set([`--bg-darkest`,`--bg-dark`,`--bg-mid`,`--bg-light`]),r=!!t?.backgroundImage;for(let{key:i,cssVar:a}of tr){let o=t?t.palette[i]:``;r&&n.has(a)?e.style.getPropertyValue(a)&&e.style.removeProperty(a):e.style.getPropertyValue(a)!==o&&(o?e.style.setProperty(a,o):e.style.removeProperty(a))}let i=t?.backgroundImage?String(t.backgroundDim??.55):``,a=t?.backgroundImage?String(t.surfaceAlpha??.82):``;for(let[t,n]of[[`--bg-image-dim`,i],[`--surface-alpha`,a]])e.style.getPropertyValue(t)!==n&&(n?e.style.setProperty(t,n):e.style.removeProperty(t));if(t?.backgroundImage){e.dataset&&(e.dataset.bgImage=`on`);for(let[n,r]of[[`--bg-darkest-solid`,t.palette.bgDarkest],[`--bg-dark-solid`,t.palette.bgDark],[`--bg-mid-solid`,t.palette.bgMid],[`--bg-light-solid`,t.palette.bgLight]]){let t=fr(r);e.style.getPropertyValue(n)!==t&&e.style.setProperty(n,t)}}else{e.dataset&&delete e.dataset.bgImage;for(let t of[`--bg-darkest-solid`,`--bg-dark-solid`,`--bg-mid-solid`,`--bg-light-solid`])e.style.removeProperty(t)}}function fr(e){let t=/^#([0-9a-f]{6})[0-9a-f]{2}$/i.exec(e.trim());return t?`#${t[1]}`:e}function pr(e){let t=e.trim().toLowerCase(),n=/^#?([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/.exec(t);if(!n)return null;let r=n[1];return r.length===3?`#${r[0]}${r[0]}${r[1]}${r[1]}${r[2]}${r[2]}`:`#${r}`}function mr(e){if(e.customIds.includes(e.want)||e.presetIds.includes(e.want))return{active:e.want,repaired:!1};let t=e.fallback&&e.presetIds.includes(e.fallback)?e.fallback:`dark`;return{active:e.presetIds.includes(t)?t:e.presetIds[0]??`dark`,repaired:!0}}function hr(e,t,n){return e.find(e=>e.id===t)??e.find(e=>e.id===n)??e[0]}function gr(e){return e.preview?e.preview:e.auto?e.prefersLight?e.light:e.dark:e.fixed}var _r=Object.defineProperty,vr=Object.getOwnPropertyDescriptor,yr=(e,t)=>{for(var n in t)_r(e,n,{get:t[n],enumerable:!0})},z=(e,t,n,r)=>{for(var i=r>1?void 0:r?vr(t,n):t,a=e.length-1,o;a>=0;a--)(o=e[a])&&(i=(r?o(t,n,i):o(i))||i);return r&&i&&_r(t,n,i),i},B=(e,t)=>(n,r)=>t(n,r,e),br=`Terminal input`,xr={get:()=>br,set:e=>br=e},Sr=`Too much output to announce, navigate to rows manually to read`,Cr={get:()=>Sr,set:e=>Sr=e};function wr(e){return e.replace(/\r?\n/g,`\r`)}function Tr(e,t){return t?`\x1B[200~`+e+`\x1B[201~`:e}function V(e,t){e.clipboardData&&e.clipboardData.setData(`text/plain`,t.selectionText),e.preventDefault()}function Er(e,t,n,r){e.stopPropagation(),e.clipboardData&&Dr(e.clipboardData.getData(`text/plain`),t,n,r)}function Dr(e,t,n,r){e=wr(e),e=Tr(e,n.decPrivateModes.bracketedPasteMode&&r.rawOptions.ignoreBracketedPasteMode!==!0),n.triggerDataEvent(e,!0),t.value=``}function Or(e,t,n){let r=n.getBoundingClientRect(),i=e.clientX-r.left-10,a=e.clientY-r.top-10;t.style.width=`20px`,t.style.height=`20px`,t.style.left=`${i}px`,t.style.top=`${a}px`,t.style.zIndex=`1000`,t.focus()}function kr(e,t,n,r,i){Or(e,t,n),i&&r.rightClickSelect(e),t.value=r.selectionText,t.select()}function Ar(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function jr(e,t=0,n=e.length){let r=``;for(let i=t;i<n;++i){let t=e[i];t>65535?(t-=65536,r+=String.fromCharCode((t>>10)+55296)+String.fromCharCode(t%1024+56320)):r+=String.fromCharCode(t)}return r}var Mr=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let n=e.length;if(!n)return 0;let r=0,i=0;if(this._interim){let n=e.charCodeAt(i++);56320<=n&&n<=57343?t[r++]=(this._interim-55296)*1024+n-56320+65536:(t[r++]=this._interim,t[r++]=n),this._interim=0}for(let a=i;a<n;++a){let i=e.charCodeAt(a);if(55296<=i&&i<=56319){if(++a>=n)return this._interim=i,r;let o=e.charCodeAt(a);56320<=o&&o<=57343?t[r++]=(i-55296)*1024+o-56320+65536:(t[r++]=i,t[r++]=o)}else i!==65279&&(t[r++]=i)}return r}},Nr=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let n=e.length;if(!n)return 0;let r=0,i,a,o,s,c=0,l=0;if(this.interim[0]){let i=!1,a=this.interim[0];a&=(a&224)==192?31:(a&240)==224?15:7;let o=0,s;for(;(s=this.interim[++o]&63)&&o<4;)a<<=6,a|=s;let c=(this.interim[0]&224)==192?2:(this.interim[0]&240)==224?3:4,u=c-o;for(;l<u;){if(l>=n)return 0;if(s=e[l++],(s&192)!=128){l--,i=!0;break}this.interim[o++]=s,a<<=6,a|=s&63}i||(c===2?a<128?l--:t[r++]=a:c===3?a<2048||a>=55296&&a<=57343||a===65279||(t[r++]=a):a<65536||a>1114111||(t[r++]=a)),this.interim.fill(0)}let u=n-4,d=l;for(;d<n;){for(;d<u&&!((i=e[d])&128)&&!((a=e[d+1])&128)&&!((o=e[d+2])&128)&&!((s=e[d+3])&128);)t[r++]=i,t[r++]=a,t[r++]=o,t[r++]=s,d+=4;if(i=e[d++],i<128)t[r++]=i;else if((i&224)==192){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128||(c=(i&31)<<6|a&63,c<128)){d--;continue}t[r++]=c}else if((i&240)==224){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,r;if(o=e[d++],(o&192)!=128){d--;continue}if(c=(i&15)<<12|(a&63)<<6|o&63,c<2048||c>=55296&&c<=57343||c===65279)continue;t[r++]=c}else if((i&248)==240){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,r;if(o=e[d++],(o&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,this.interim[2]=o,r;if(s=e[d++],(s&192)!=128){d--;continue}if(c=(i&7)<<18|(a&63)<<12|(o&63)<<6|s&63,c<65536||c>1114111)continue;t[r++]=c}}return r}},Pr=``,Fr=` `,Ir=class e{constructor(){this.fg=0,this.bg=0,this.extended=new Lr}static toColorRGB(e){return[e>>>16&255,e>>>8&255,e&255]}static fromColorRGB(e){return(e[0]&255)<<16|(e[1]&255)<<8|e[2]&255}clone(){let t=new e;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)==50331648}isBgRGB(){return(this.bg&50331648)==50331648}isFgPalette(){return(this.fg&50331648)==16777216||(this.fg&50331648)==33554432}isBgPalette(){return(this.bg&50331648)==16777216||(this.bg&50331648)==33554432}isFgDefault(){return!(this.fg&50331648)}isBgDefault(){return!(this.bg&50331648)}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)==50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)==16777216||(this.extended.underlineColor&50331648)==33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?!(this.extended.underlineColor&50331648):this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},Lr=class e{constructor(e=0,t=0){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 urlId(){return this._urlId}set urlId(e){this._urlId=e}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}clone(){return new e(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},Rr=class e extends Ir{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new Lr,this.combinedData=``}static fromCharData(t){let n=new e;return n.setFromCharData(t),n}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?Ar(this.content&2097151):``}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(e){this.fg=e[0],this.bg=0;let t=!1;if(e[1].length>2)t=!0;else if(e[1].length===2){let n=e[1].charCodeAt(0);if(55296<=n&&n<=56319){let r=e[1].charCodeAt(1);56320<=r&&r<=57343?this.content=(n-55296)*1024+r-56320+65536|e[2]<<22:t=!0}else t=!0}else this.content=e[1].charCodeAt(0)|e[2]<<22;t&&(this.combinedData=e[1],this.content=2097152|e[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},zr=`di$target`,Br=`di$dependencies`,Vr=new Map;function Hr(e){return e[Br]||[]}function Ur(e){if(Vr.has(e))return Vr.get(e);let t=function(e,n,r){if(arguments.length!==3)throw Error(`@IServiceName-decorator can only be used to decorate a parameter`);Wr(t,e,r)};return t._id=e,Vr.set(e,t),t}function Wr(e,t,n){t[zr]===t?t[Br].push({id:e,index:n}):(t[Br]=[{id:e,index:n}],t[zr]=t)}var Gr=Ur(`BufferService`),Kr=Ur(`CoreMouseService`),qr=Ur(`CoreService`),Jr=Ur(`CharsetService`),Yr=Ur(`InstantiationService`),Xr=Ur(`LogService`),Zr=Ur(`OptionsService`),Qr=Ur(`OscLinkService`),$r=Ur(`UnicodeService`),ei=Ur(`DecorationService`),ti=class{constructor(e,t,n){this._bufferService=e,this._optionsService=t,this._oscLinkService=n}provideLinks(e,t){let n=this._bufferService.buffer.lines.get(e-1);if(!n){t(void 0);return}let r=[],i=this._optionsService.rawOptions.linkHandler,a=new Rr,o=n.getTrimmedLength(),s=-1,c=-1,l=!1;for(let t=0;t<o;t++)if(c!==-1||n.hasContent(t)){if(n.loadCell(t,a),a.hasExtendedAttrs()&&a.extended.urlId){if(c===-1){c=t,s=a.extended.urlId;continue}l=a.extended.urlId!==s}else c!==-1&&(l=!0);if(l||c!==-1&&t===o-1){let n=this._oscLinkService.getLinkData(s)?.uri;if(n){let a={start:{x:c+1,y:e},end:{x:t+ +(!l&&t===o-1),y:e}},s=!1;if(!i?.allowNonHttpProtocols)try{let e=new URL(n);[`http:`,`https:`].includes(e.protocol)||(s=!0)}catch{s=!0}s||r.push({text:n,range:a,activate:(e,t)=>i?i.activate(e,t,a):ni(e,t),hover:(e,t)=>i?.hover?.(e,t,a),leave:(e,t)=>i?.leave?.(e,t,a)})}l=!1,a.hasExtendedAttrs()&&a.extended.urlId?(c=t,s=a.extended.urlId):(c=-1,s=-1)}}t(r)}};ti=z([B(0,Gr),B(1,Zr),B(2,Qr)],ti);function ni(e,t){if(confirm(`Do you want to navigate to ${t}?
7
7
 
8
8
  WARNING: This link could potentially be dangerous`)){let e=window.open();if(e){try{e.opener=null}catch{}e.location.href=t}else console.warn(`Opening link blocked as opener could not be cleared`)}}var ri=Ur(`CharSizeService`),ii=Ur(`CoreBrowserService`),ai=Ur(`MouseService`),oi=Ur(`RenderService`),si=Ur(`SelectionService`),ci=Ur(`CharacterJoinerService`),li=Ur(`ThemeService`),ui=Ur(`LinkProviderService`),di=new class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?_i.isErrorNoTelemetry(e)?new _i(e.message+`
9
9
 
10
10
  `+e.stack):Error(e.message+`
11
11
 
12
- `+e.stack):e},0)}}addListener(e){return this.listeners.push(e),()=>{this._removeListener(e)}}emit(e){this.listeners.forEach(t=>{t(e)})}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}};function fi(e){mi(e)||di.onUnexpectedError(e)}var pi=`Canceled`;function mi(e){return e instanceof hi||e instanceof Error&&e.name===pi&&e.message===pi}var hi=class extends Error{constructor(){super(pi),this.name=this.message}};function gi(e){return Error(e?`Illegal argument: ${e}`:`Illegal argument`)}var _i=class e extends Error{constructor(e){super(e),this.name=`CodeExpectedError`}static fromError(t){if(t instanceof e)return t;let n=new e;return n.message=t.message,n.stack=t.stack,n}static isErrorNoTelemetry(e){return e.name===`CodeExpectedError`}},vi=class e extends Error{constructor(t){super(t||`An unexpected bug occurred.`),Object.setPrototypeOf(this,e.prototype)}};function yi(e,t=0){return e[e.length-(1+t)]}var bi;(e=>{function t(e){return e<0}e.isLessThan=t;function n(e){return e<=0}e.isLessThanOrEqual=n;function r(e){return e>0}e.isGreaterThan=r;function i(e){return e===0}e.isNeitherLessOrGreaterThan=i,e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0})(bi||={});var xi=class e{constructor(e){this.iterate=e}forEach(e){this.iterate(t=>(e(t),!0))}toArray(){let e=[];return this.iterate(t=>(e.push(t),!0)),e}filter(t){return new e(e=>this.iterate(n=>!t(n)||e(n)))}map(t){return new e(e=>this.iterate(n=>e(t(n))))}some(e){let t=!1;return this.iterate(n=>(t=e(n),!t)),t}findFirst(e){let t;return this.iterate(n=>!e(n)||(t=n,!1)),t}findLast(e){let t;return this.iterate(n=>(e(n)&&(t=n),!0)),t}findLastMaxBy(e){let t,n=!0;return this.iterate(r=>((n||bi.isGreaterThan(e(r,t)))&&(n=!1,t=r),!0)),t}};xi.empty=new xi(e=>{});function Si(e,t){let n=this,r=!1,i;return function(){if(r)return i;if(r=!0,t)try{i=e.apply(n,arguments)}finally{t()}else i=e.apply(n,arguments);return i}}var Ci;(e=>{function t(e){return e&&typeof e==`object`&&typeof e[Symbol.iterator]==`function`}e.is=t;let n=Object.freeze([]);function r(){return n}e.empty=r;function*i(e){yield e}e.single=i;function a(e){return t(e)?e:i(e)}e.wrap=a;function o(e){return e||n}e.from=o;function*s(e){for(let t=e.length-1;t>=0;t--)yield e[t]}e.reverse=s;function c(e){return!e||e[Symbol.iterator]().next().done===!0}e.isEmpty=c;function l(e){return e[Symbol.iterator]().next().value}e.first=l;function u(e,t){let n=0;for(let r of e)if(t(r,n++))return!0;return!1}e.some=u;function d(e,t){for(let n of e)if(t(n))return n}e.find=d;function*f(e,t){for(let n of e)t(n)&&(yield n)}e.filter=f;function*p(e,t){let n=0;for(let r of e)yield t(r,n++)}e.map=p;function*m(e,t){let n=0;for(let r of e)yield*t(r,n++)}e.flatMap=m;function*h(...e){for(let t of e)yield*t}e.concat=h;function g(e,t,n){let r=n;for(let n of e)r=t(r,n);return r}e.reduce=g;function*_(e,t,n=e.length){for(t<0&&(t+=e.length),n<0?n+=e.length:n>e.length&&(n=e.length);t<n;t++)yield e[t]}e.slice=_;function v(t,n=1/0){let r=[];if(n===0)return[r,t];let i=t[Symbol.iterator]();for(let t=0;t<n;t++){let t=i.next();if(t.done)return[r,e.empty()];r.push(t.value)}return[r,{[Symbol.iterator](){return i}}]}e.consume=v;async function ee(e){let t=[];for await(let n of e)t.push(n);return Promise.resolve(t)}e.asyncToArray=ee})(Ci||={});var wi=null;function Ti(e){return wi?.trackDisposable(e),e}function Ei(e){wi?.markAsDisposed(e)}function Di(e,t){wi?.setParent(e,t)}function Oi(e){return wi?.markAsSingleton(e),e}function ki(e){if(Ci.is(e)){let t=[];for(let n of e)if(n)try{n.dispose()}catch(e){t.push(e)}if(t.length===1)throw t[0];if(t.length>1)throw AggregateError(t,`Encountered errors while disposing of store`);return Array.isArray(e)?[]:e}if(e)return e.dispose(),e}function Ai(...e){return V(()=>ki(e))}function V(e){let t=Ti({dispose:Si(()=>{Ei(t),e()})});return t}var ji=class e{constructor(){this._toDispose=new Set,this._isDisposed=!1,Ti(this)}dispose(){this._isDisposed||(Ei(this),this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{ki(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw Error(`Cannot register a disposable on itself!`);return Di(t,this),this._isDisposed?e.DISABLE_DISPOSED_WARNING||console.warn(Error(`Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!`).stack):this._toDispose.add(t),t}delete(e){if(e){if(e===this)throw Error(`Cannot dispose a disposable on itself!`);this._toDispose.delete(e),e.dispose()}}deleteAndLeak(e){e&&this._toDispose.has(e)&&(this._toDispose.delete(e),Di(e,null))}};ji.DISABLE_DISPOSED_WARNING=!1;var Mi=ji,H=class{constructor(){this._store=new Mi,Ti(this),Di(this._store,this)}dispose(){Ei(this),this._store.dispose()}_register(e){if(e===this)throw Error(`Cannot register a disposable on itself!`);return this._store.add(e)}};H.None=Object.freeze({dispose(){}});var Ni=class{constructor(){this._isDisposed=!1,Ti(this)}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),e&&Di(e,this),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,Ei(this),this._value?.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e&&Di(e,null),e}},Pi=typeof window==`object`?window:globalThis,Fi=class e{constructor(t){this.element=t,this.next=e.Undefined,this.prev=e.Undefined}};Fi.Undefined=new Fi(void 0);var Ii=Fi,Li=class{constructor(){this._first=Ii.Undefined,this._last=Ii.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===Ii.Undefined}clear(){let e=this._first;for(;e!==Ii.Undefined;){let t=e.next;e.prev=Ii.Undefined,e.next=Ii.Undefined,e=t}this._first=Ii.Undefined,this._last=Ii.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let n=new Ii(e);if(this._first===Ii.Undefined)this._first=n,this._last=n;else if(t){let e=this._last;this._last=n,n.prev=e,e.next=n}else{let e=this._first;this._first=n,n.next=e,e.prev=n}this._size+=1;let r=!1;return()=>{r||(r=!0,this._remove(n))}}shift(){if(this._first!==Ii.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==Ii.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==Ii.Undefined&&e.next!==Ii.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===Ii.Undefined&&e.next===Ii.Undefined?(this._first=Ii.Undefined,this._last=Ii.Undefined):e.next===Ii.Undefined?(this._last=this._last.prev,this._last.next=Ii.Undefined):e.prev===Ii.Undefined&&(this._first=this._first.next,this._first.prev=Ii.Undefined);--this._size}*[Symbol.iterator](){let e=this._first;for(;e!==Ii.Undefined;)yield e.element,e=e.next}},Ri=globalThis.performance&&typeof globalThis.performance.now==`function`,zi=class e{static create(t){return new e(t)}constructor(e){this._now=Ri&&e===!1?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime===-1?this._now()-this._startTime:this._stopTime-this._startTime}},Bi;(e=>{e.None=()=>H.None;function t(e,t){return d(e,()=>{},0,void 0,!0,void 0,t)}e.defer=t;function n(e){return(t,n=null,r)=>{let i=!1,a;return a=e(e=>{if(!i)return a?a.dispose():i=!0,t.call(n,e)},null,r),i&&a.dispose(),a}}e.once=n;function r(e,t,n){return l((n,r=null,i)=>e(e=>n.call(r,t(e)),null,i),n)}e.map=r;function i(e,t,n){return l((n,r=null,i)=>e(e=>{t(e),n.call(r,e)},null,i),n)}e.forEach=i;function a(e,t,n){return l((n,r=null,i)=>e(e=>t(e)&&n.call(r,e),null,i),n)}e.filter=a;function o(e){return e}e.signal=o;function s(...e){return(t,n=null,r)=>u(Ai(...e.map(e=>e(e=>t.call(n,e)))),r)}e.any=s;function c(e,t,n,i){let a=n;return r(e,e=>(a=t(a,e),a),i)}e.reduce=c;function l(e,t){let n,r=new U({onWillAddFirstListener(){n=e(r.fire,r)},onDidRemoveLastListener(){n?.dispose()}});return t?.add(r),r.event}function u(e,t){return t instanceof Array?t.push(e):t&&t.add(e),e}function d(e,t,n=100,r=!1,i=!1,a,o){let s,c,l,u=0,d,f=new U({leakWarningThreshold:a,onWillAddFirstListener(){s=e(e=>{u++,c=t(c,e),r&&!l&&(f.fire(c),c=void 0),d=()=>{let e=c;c=void 0,l=void 0,(!r||u>1)&&f.fire(e),u=0},typeof n==`number`?(clearTimeout(l),l=setTimeout(d,n)):l===void 0&&(l=0,queueMicrotask(d))})},onWillRemoveListener(){i&&u>0&&d?.()},onDidRemoveLastListener(){d=void 0,s.dispose()}});return o?.add(f),f.event}e.debounce=d;function f(t,n=0,r){return e.debounce(t,(e,t)=>e?(e.push(t),e):[t],n,void 0,!0,void 0,r)}e.accumulate=f;function p(e,t=(e,t)=>e===t,n){let r=!0,i;return a(e,e=>{let n=r||!t(e,i);return r=!1,i=e,n},n)}e.latch=p;function m(t,n,r){return[e.filter(t,n,r),e.filter(t,e=>!n(e),r)]}e.split=m;function h(e,t=!1,n=[],r){let i=n.slice(),a=e(e=>{i?i.push(e):s.fire(e)});r&&r.add(a);let o=()=>{i?.forEach(e=>s.fire(e)),i=null},s=new U({onWillAddFirstListener(){a||(a=e(e=>s.fire(e)),r&&r.add(a))},onDidAddFirstListener(){i&&(t?setTimeout(o):o())},onDidRemoveLastListener(){a&&a.dispose(),a=null}});return r&&r.add(s),s.event}e.buffer=h;function g(e,t){return(n,r,i)=>{let a=t(new v);return e(function(e){let t=a.evaluate(e);t!==_&&n.call(r,t)},void 0,i)}}e.chain=g;let _=Symbol(`HaltChainable`);class v{constructor(){this.steps=[]}map(e){return this.steps.push(e),this}forEach(e){return this.steps.push(t=>(e(t),t)),this}filter(e){return this.steps.push(t=>e(t)?t:_),this}reduce(e,t){let n=t;return this.steps.push(t=>(n=e(n,t),n)),this}latch(e=(e,t)=>e===t){let t=!0,n;return this.steps.push(r=>{let i=t||!e(r,n);return t=!1,n=r,i?r:_}),this}evaluate(e){for(let t of this.steps)if(e=t(e),e===_)break;return e}}function ee(e,t,n=e=>e){let r=(...e)=>i.fire(n(...e)),i=new U({onWillAddFirstListener:()=>e.on(t,r),onDidRemoveLastListener:()=>e.removeListener(t,r)});return i.event}e.fromNodeEventEmitter=ee;function y(e,t,n=e=>e){let r=(...e)=>i.fire(n(...e)),i=new U({onWillAddFirstListener:()=>e.addEventListener(t,r),onDidRemoveLastListener:()=>e.removeEventListener(t,r)});return i.event}e.fromDOMEventEmitter=y;function b(e){return new Promise(t=>n(e)(t))}e.toPromise=b;function x(e){let t=new U;return e.then(e=>{t.fire(e)},()=>{t.fire(void 0)}).finally(()=>{t.dispose()}),t.event}e.fromPromise=x;function S(e,t){return e(e=>t.fire(e))}e.forward=S;function C(e,t,n){return t(n),e(e=>t(e))}e.runAndSubscribe=C;class w{constructor(e,t){this._observable=e,this._counter=0,this._hasChanged=!1;let n={onWillAddFirstListener:()=>{e.addObserver(this)},onDidRemoveLastListener:()=>{e.removeObserver(this)}};this.emitter=new U(n),t&&t.add(this.emitter)}beginUpdate(e){this._counter++}handlePossibleChange(e){}handleChange(e,t){this._hasChanged=!0}endUpdate(e){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function T(e,t){return new w(e,t).emitter.event}e.fromObservable=T;function te(e){return(t,n,r)=>{let i=0,a=!1,o={beginUpdate(){i++},endUpdate(){i--,i===0&&(e.reportChanges(),a&&(a=!1,t.call(n)))},handlePossibleChange(){},handleChange(){a=!0}};e.addObserver(o),e.reportChanges();let s={dispose(){e.removeObserver(o)}};return r instanceof Mi?r.add(s):Array.isArray(r)&&r.push(s),s}}e.fromObservableLight=te})(Bi||={});var Vi=class e{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${e._idPool++}`,e.all.add(this)}start(e){this._stopWatch=new zi,this.listenerCount=e}stop(){if(this._stopWatch){let e=this._stopWatch.elapsed();this.durations.push(e),this.elapsedOverall+=e,this.invocationCount+=1,this._stopWatch=void 0}}};Vi.all=new Set,Vi._idPool=0;var Hi=Vi,Ui=-1,Wi=class e{constructor(t,n,r=(e._idPool++).toString(16).padStart(3,`0`)){this._errorHandler=t,this.threshold=n,this.name=r,this._warnCountdown=0}dispose(){this._stacks?.clear()}check(e,t){let n=this.threshold;if(n<=0||t<n)return;this._stacks||=new Map;let r=this._stacks.get(e.value)||0;if(this._stacks.set(e.value,r+1),--this._warnCountdown,this._warnCountdown<=0){this._warnCountdown=n*.5;let[e,r]=this.getMostFrequentStack(),i=`[${this.name}] potential listener LEAK detected, having ${t} listeners already. MOST frequent listener (${r}):`;console.warn(i),console.warn(e);let a=new qi(i,e);this._errorHandler(a)}return()=>{let t=this._stacks.get(e.value)||0;this._stacks.set(e.value,t-1)}}getMostFrequentStack(){if(!this._stacks)return;let e,t=0;for(let[n,r]of this._stacks)(!e||t<r)&&(e=[n,r],t=r);return e}};Wi._idPool=1;var Gi=Wi,Ki=class e{constructor(e){this.value=e}static create(){return new e(Error().stack??``)}print(){console.warn(this.value.split(`
12
+ `+e.stack):e},0)}}addListener(e){return this.listeners.push(e),()=>{this._removeListener(e)}}emit(e){this.listeners.forEach(t=>{t(e)})}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}};function fi(e){mi(e)||di.onUnexpectedError(e)}var pi=`Canceled`;function mi(e){return e instanceof hi||e instanceof Error&&e.name===pi&&e.message===pi}var hi=class extends Error{constructor(){super(pi),this.name=this.message}};function gi(e){return Error(e?`Illegal argument: ${e}`:`Illegal argument`)}var _i=class e extends Error{constructor(e){super(e),this.name=`CodeExpectedError`}static fromError(t){if(t instanceof e)return t;let n=new e;return n.message=t.message,n.stack=t.stack,n}static isErrorNoTelemetry(e){return e.name===`CodeExpectedError`}},vi=class e extends Error{constructor(t){super(t||`An unexpected bug occurred.`),Object.setPrototypeOf(this,e.prototype)}};function yi(e,t=0){return e[e.length-(1+t)]}var bi;(e=>{function t(e){return e<0}e.isLessThan=t;function n(e){return e<=0}e.isLessThanOrEqual=n;function r(e){return e>0}e.isGreaterThan=r;function i(e){return e===0}e.isNeitherLessOrGreaterThan=i,e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0})(bi||={});var xi=class e{constructor(e){this.iterate=e}forEach(e){this.iterate(t=>(e(t),!0))}toArray(){let e=[];return this.iterate(t=>(e.push(t),!0)),e}filter(t){return new e(e=>this.iterate(n=>!t(n)||e(n)))}map(t){return new e(e=>this.iterate(n=>e(t(n))))}some(e){let t=!1;return this.iterate(n=>(t=e(n),!t)),t}findFirst(e){let t;return this.iterate(n=>!e(n)||(t=n,!1)),t}findLast(e){let t;return this.iterate(n=>(e(n)&&(t=n),!0)),t}findLastMaxBy(e){let t,n=!0;return this.iterate(r=>((n||bi.isGreaterThan(e(r,t)))&&(n=!1,t=r),!0)),t}};xi.empty=new xi(e=>{});function Si(e,t){let n=this,r=!1,i;return function(){if(r)return i;if(r=!0,t)try{i=e.apply(n,arguments)}finally{t()}else i=e.apply(n,arguments);return i}}var Ci;(e=>{function t(e){return e&&typeof e==`object`&&typeof e[Symbol.iterator]==`function`}e.is=t;let n=Object.freeze([]);function r(){return n}e.empty=r;function*i(e){yield e}e.single=i;function a(e){return t(e)?e:i(e)}e.wrap=a;function o(e){return e||n}e.from=o;function*s(e){for(let t=e.length-1;t>=0;t--)yield e[t]}e.reverse=s;function c(e){return!e||e[Symbol.iterator]().next().done===!0}e.isEmpty=c;function l(e){return e[Symbol.iterator]().next().value}e.first=l;function u(e,t){let n=0;for(let r of e)if(t(r,n++))return!0;return!1}e.some=u;function d(e,t){for(let n of e)if(t(n))return n}e.find=d;function*f(e,t){for(let n of e)t(n)&&(yield n)}e.filter=f;function*p(e,t){let n=0;for(let r of e)yield t(r,n++)}e.map=p;function*m(e,t){let n=0;for(let r of e)yield*t(r,n++)}e.flatMap=m;function*h(...e){for(let t of e)yield*t}e.concat=h;function g(e,t,n){let r=n;for(let n of e)r=t(r,n);return r}e.reduce=g;function*_(e,t,n=e.length){for(t<0&&(t+=e.length),n<0?n+=e.length:n>e.length&&(n=e.length);t<n;t++)yield e[t]}e.slice=_;function v(t,n=1/0){let r=[];if(n===0)return[r,t];let i=t[Symbol.iterator]();for(let t=0;t<n;t++){let t=i.next();if(t.done)return[r,e.empty()];r.push(t.value)}return[r,{[Symbol.iterator](){return i}}]}e.consume=v;async function ee(e){let t=[];for await(let n of e)t.push(n);return Promise.resolve(t)}e.asyncToArray=ee})(Ci||={});var wi=null;function Ti(e){return wi?.trackDisposable(e),e}function Ei(e){wi?.markAsDisposed(e)}function Di(e,t){wi?.setParent(e,t)}function Oi(e){return wi?.markAsSingleton(e),e}function ki(e){if(Ci.is(e)){let t=[];for(let n of e)if(n)try{n.dispose()}catch(e){t.push(e)}if(t.length===1)throw t[0];if(t.length>1)throw AggregateError(t,`Encountered errors while disposing of store`);return Array.isArray(e)?[]:e}if(e)return e.dispose(),e}function Ai(...e){return H(()=>ki(e))}function H(e){let t=Ti({dispose:Si(()=>{Ei(t),e()})});return t}var ji=class e{constructor(){this._toDispose=new Set,this._isDisposed=!1,Ti(this)}dispose(){this._isDisposed||(Ei(this),this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{ki(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw Error(`Cannot register a disposable on itself!`);return Di(t,this),this._isDisposed?e.DISABLE_DISPOSED_WARNING||console.warn(Error(`Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!`).stack):this._toDispose.add(t),t}delete(e){if(e){if(e===this)throw Error(`Cannot dispose a disposable on itself!`);this._toDispose.delete(e),e.dispose()}}deleteAndLeak(e){e&&this._toDispose.has(e)&&(this._toDispose.delete(e),Di(e,null))}};ji.DISABLE_DISPOSED_WARNING=!1;var Mi=ji,U=class{constructor(){this._store=new Mi,Ti(this),Di(this._store,this)}dispose(){Ei(this),this._store.dispose()}_register(e){if(e===this)throw Error(`Cannot register a disposable on itself!`);return this._store.add(e)}};U.None=Object.freeze({dispose(){}});var Ni=class{constructor(){this._isDisposed=!1,Ti(this)}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),e&&Di(e,this),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,Ei(this),this._value?.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e&&Di(e,null),e}},Pi=typeof window==`object`?window:globalThis,Fi=class e{constructor(t){this.element=t,this.next=e.Undefined,this.prev=e.Undefined}};Fi.Undefined=new Fi(void 0);var Ii=Fi,Li=class{constructor(){this._first=Ii.Undefined,this._last=Ii.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===Ii.Undefined}clear(){let e=this._first;for(;e!==Ii.Undefined;){let t=e.next;e.prev=Ii.Undefined,e.next=Ii.Undefined,e=t}this._first=Ii.Undefined,this._last=Ii.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let n=new Ii(e);if(this._first===Ii.Undefined)this._first=n,this._last=n;else if(t){let e=this._last;this._last=n,n.prev=e,e.next=n}else{let e=this._first;this._first=n,n.next=e,e.prev=n}this._size+=1;let r=!1;return()=>{r||(r=!0,this._remove(n))}}shift(){if(this._first!==Ii.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==Ii.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==Ii.Undefined&&e.next!==Ii.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===Ii.Undefined&&e.next===Ii.Undefined?(this._first=Ii.Undefined,this._last=Ii.Undefined):e.next===Ii.Undefined?(this._last=this._last.prev,this._last.next=Ii.Undefined):e.prev===Ii.Undefined&&(this._first=this._first.next,this._first.prev=Ii.Undefined);--this._size}*[Symbol.iterator](){let e=this._first;for(;e!==Ii.Undefined;)yield e.element,e=e.next}},Ri=globalThis.performance&&typeof globalThis.performance.now==`function`,zi=class e{static create(t){return new e(t)}constructor(e){this._now=Ri&&e===!1?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime===-1?this._now()-this._startTime:this._stopTime-this._startTime}},Bi;(e=>{e.None=()=>U.None;function t(e,t){return d(e,()=>{},0,void 0,!0,void 0,t)}e.defer=t;function n(e){return(t,n=null,r)=>{let i=!1,a;return a=e(e=>{if(!i)return a?a.dispose():i=!0,t.call(n,e)},null,r),i&&a.dispose(),a}}e.once=n;function r(e,t,n){return l((n,r=null,i)=>e(e=>n.call(r,t(e)),null,i),n)}e.map=r;function i(e,t,n){return l((n,r=null,i)=>e(e=>{t(e),n.call(r,e)},null,i),n)}e.forEach=i;function a(e,t,n){return l((n,r=null,i)=>e(e=>t(e)&&n.call(r,e),null,i),n)}e.filter=a;function o(e){return e}e.signal=o;function s(...e){return(t,n=null,r)=>u(Ai(...e.map(e=>e(e=>t.call(n,e)))),r)}e.any=s;function c(e,t,n,i){let a=n;return r(e,e=>(a=t(a,e),a),i)}e.reduce=c;function l(e,t){let n,r=new W({onWillAddFirstListener(){n=e(r.fire,r)},onDidRemoveLastListener(){n?.dispose()}});return t?.add(r),r.event}function u(e,t){return t instanceof Array?t.push(e):t&&t.add(e),e}function d(e,t,n=100,r=!1,i=!1,a,o){let s,c,l,u=0,d,f=new W({leakWarningThreshold:a,onWillAddFirstListener(){s=e(e=>{u++,c=t(c,e),r&&!l&&(f.fire(c),c=void 0),d=()=>{let e=c;c=void 0,l=void 0,(!r||u>1)&&f.fire(e),u=0},typeof n==`number`?(clearTimeout(l),l=setTimeout(d,n)):l===void 0&&(l=0,queueMicrotask(d))})},onWillRemoveListener(){i&&u>0&&d?.()},onDidRemoveLastListener(){d=void 0,s.dispose()}});return o?.add(f),f.event}e.debounce=d;function f(t,n=0,r){return e.debounce(t,(e,t)=>e?(e.push(t),e):[t],n,void 0,!0,void 0,r)}e.accumulate=f;function p(e,t=(e,t)=>e===t,n){let r=!0,i;return a(e,e=>{let n=r||!t(e,i);return r=!1,i=e,n},n)}e.latch=p;function m(t,n,r){return[e.filter(t,n,r),e.filter(t,e=>!n(e),r)]}e.split=m;function h(e,t=!1,n=[],r){let i=n.slice(),a=e(e=>{i?i.push(e):s.fire(e)});r&&r.add(a);let o=()=>{i?.forEach(e=>s.fire(e)),i=null},s=new W({onWillAddFirstListener(){a||(a=e(e=>s.fire(e)),r&&r.add(a))},onDidAddFirstListener(){i&&(t?setTimeout(o):o())},onDidRemoveLastListener(){a&&a.dispose(),a=null}});return r&&r.add(s),s.event}e.buffer=h;function g(e,t){return(n,r,i)=>{let a=t(new v);return e(function(e){let t=a.evaluate(e);t!==_&&n.call(r,t)},void 0,i)}}e.chain=g;let _=Symbol(`HaltChainable`);class v{constructor(){this.steps=[]}map(e){return this.steps.push(e),this}forEach(e){return this.steps.push(t=>(e(t),t)),this}filter(e){return this.steps.push(t=>e(t)?t:_),this}reduce(e,t){let n=t;return this.steps.push(t=>(n=e(n,t),n)),this}latch(e=(e,t)=>e===t){let t=!0,n;return this.steps.push(r=>{let i=t||!e(r,n);return t=!1,n=r,i?r:_}),this}evaluate(e){for(let t of this.steps)if(e=t(e),e===_)break;return e}}function ee(e,t,n=e=>e){let r=(...e)=>i.fire(n(...e)),i=new W({onWillAddFirstListener:()=>e.on(t,r),onDidRemoveLastListener:()=>e.removeListener(t,r)});return i.event}e.fromNodeEventEmitter=ee;function y(e,t,n=e=>e){let r=(...e)=>i.fire(n(...e)),i=new W({onWillAddFirstListener:()=>e.addEventListener(t,r),onDidRemoveLastListener:()=>e.removeEventListener(t,r)});return i.event}e.fromDOMEventEmitter=y;function b(e){return new Promise(t=>n(e)(t))}e.toPromise=b;function x(e){let t=new W;return e.then(e=>{t.fire(e)},()=>{t.fire(void 0)}).finally(()=>{t.dispose()}),t.event}e.fromPromise=x;function S(e,t){return e(e=>t.fire(e))}e.forward=S;function C(e,t,n){return t(n),e(e=>t(e))}e.runAndSubscribe=C;class w{constructor(e,t){this._observable=e,this._counter=0,this._hasChanged=!1;let n={onWillAddFirstListener:()=>{e.addObserver(this)},onDidRemoveLastListener:()=>{e.removeObserver(this)}};this.emitter=new W(n),t&&t.add(this.emitter)}beginUpdate(e){this._counter++}handlePossibleChange(e){}handleChange(e,t){this._hasChanged=!0}endUpdate(e){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function T(e,t){return new w(e,t).emitter.event}e.fromObservable=T;function E(e){return(t,n,r)=>{let i=0,a=!1,o={beginUpdate(){i++},endUpdate(){i--,i===0&&(e.reportChanges(),a&&(a=!1,t.call(n)))},handlePossibleChange(){},handleChange(){a=!0}};e.addObserver(o),e.reportChanges();let s={dispose(){e.removeObserver(o)}};return r instanceof Mi?r.add(s):Array.isArray(r)&&r.push(s),s}}e.fromObservableLight=E})(Bi||={});var Vi=class e{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${e._idPool++}`,e.all.add(this)}start(e){this._stopWatch=new zi,this.listenerCount=e}stop(){if(this._stopWatch){let e=this._stopWatch.elapsed();this.durations.push(e),this.elapsedOverall+=e,this.invocationCount+=1,this._stopWatch=void 0}}};Vi.all=new Set,Vi._idPool=0;var Hi=Vi,Ui=-1,Wi=class e{constructor(t,n,r=(e._idPool++).toString(16).padStart(3,`0`)){this._errorHandler=t,this.threshold=n,this.name=r,this._warnCountdown=0}dispose(){this._stacks?.clear()}check(e,t){let n=this.threshold;if(n<=0||t<n)return;this._stacks||=new Map;let r=this._stacks.get(e.value)||0;if(this._stacks.set(e.value,r+1),--this._warnCountdown,this._warnCountdown<=0){this._warnCountdown=n*.5;let[e,r]=this.getMostFrequentStack(),i=`[${this.name}] potential listener LEAK detected, having ${t} listeners already. MOST frequent listener (${r}):`;console.warn(i),console.warn(e);let a=new qi(i,e);this._errorHandler(a)}return()=>{let t=this._stacks.get(e.value)||0;this._stacks.set(e.value,t-1)}}getMostFrequentStack(){if(!this._stacks)return;let e,t=0;for(let[n,r]of this._stacks)(!e||t<r)&&(e=[n,r],t=r);return e}};Wi._idPool=1;var Gi=Wi,Ki=class e{constructor(e){this.value=e}static create(){return new e(Error().stack??``)}print(){console.warn(this.value.split(`
13
13
  `).slice(2).join(`
14
- `))}},qi=class extends Error{constructor(e,t){super(e),this.name=`ListenerLeakError`,this.stack=t}},Ji=class extends Error{constructor(e,t){super(e),this.name=`ListenerRefusalError`,this.stack=t}},Yi=0,Xi=class{constructor(e){this.value=e,this.id=Yi++}},Zi=2,U=class{constructor(e){this._size=0,this._options=e,this._leakageMon=Ui>0||this._options?.leakWarningThreshold?new Gi(e?.onListenerError??fi,this._options?.leakWarningThreshold??Ui):void 0,this._perfMon=this._options?._profName?new Hi(this._options._profName):void 0,this._deliveryQueue=this._options?.deliveryQueue}dispose(){this._disposed||(this._disposed=!0,this._deliveryQueue?.current===this&&this._deliveryQueue.reset(),this._listeners&&(this._listeners=void 0,this._size=0),this._options?.onDidRemoveLastListener?.(),this._leakageMon?.dispose())}get event(){return this._event??=(e,t,n)=>{if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let e=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(e);let t=this._leakageMon.getMostFrequentStack()??[`UNKNOWN stack`,-1],n=new Ji(`${e}. HINT: Stack shows most frequent listener (${t[1]}-times)`,t[0]);return(this._options?.onListenerError||fi)(n),H.None}if(this._disposed)return H.None;t&&(e=e.bind(t));let r=new Xi(e),i;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(r.stack=Ki.create(),i=this._leakageMon.check(r.stack,this._size+1)),this._listeners?this._listeners instanceof Xi?(this._deliveryQueue??=new Qi,this._listeners=[this._listeners,r]):this._listeners.push(r):(this._options?.onWillAddFirstListener?.(this),this._listeners=r,this._options?.onDidAddFirstListener?.(this)),this._size++;let a=V(()=>{i?.(),this._removeListener(r)});return n instanceof Mi?n.add(a):Array.isArray(n)&&n.push(a),a},this._event}_removeListener(e){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(this._size===1){this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),this._size=0;return}let t=this._listeners,n=t.indexOf(e);if(n===-1)throw console.log(`disposed?`,this._disposed),console.log(`size?`,this._size),console.log(`arr?`,JSON.stringify(this._listeners)),Error(`Attempted to dispose unknown listener`);this._size--,t[n]=void 0;let r=this._deliveryQueue.current===this;if(this._size*Zi<=t.length){let e=0;for(let n=0;n<t.length;n++)t[n]?t[e++]=t[n]:r&&(this._deliveryQueue.end--,e<this._deliveryQueue.i&&this._deliveryQueue.i--);t.length=e}}_deliver(e,t){if(!e)return;let n=this._options?.onListenerError||fi;if(!n)e.value(t);else try{e.value(t)}catch(e){n(e)}}_deliverQueue(e){let t=e.current._listeners;for(;e.i<e.end;)this._deliver(t[e.i++],e.value);e.reset()}fire(e){if(this._deliveryQueue?.current&&(this._deliverQueue(this._deliveryQueue),this._perfMon?.stop()),this._perfMon?.start(this._size),this._listeners){if(this._listeners instanceof Xi)this._deliver(this._listeners,e);else{let t=this._deliveryQueue;t.enqueue(this,e,this._listeners.length),this._deliverQueue(t)}}this._perfMon?.stop()}hasListeners(){return this._size>0}},Qi=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,n){this.i=0,this.end=n,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},$i=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new U,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new U,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(e){return this.mapWindowIdToZoomLevel.get(this.getWindowId(e))??0}setZoomLevel(e,t){if(this.getZoomLevel(t)===e)return;let n=this.getWindowId(t);this.mapWindowIdToZoomLevel.set(n,e),this._onDidChangeZoomLevel.fire(n)}getZoomFactor(e){return this.mapWindowIdToZoomFactor.get(this.getWindowId(e))??1}setZoomFactor(e,t){this.mapWindowIdToZoomFactor.set(this.getWindowId(t),e)}setFullscreen(e,t){if(this.isFullscreen(t)===e)return;let n=this.getWindowId(t);this.mapWindowIdToFullScreen.set(n,e),this._onDidChangeFullscreen.fire(n)}isFullscreen(e){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(e))}getWindowId(e){return e.vscodeWindowId}};$i.INSTANCE=new $i;var ea=$i;function ta(e,t,n){typeof t==`string`&&(t=e.matchMedia(t)),t.addEventListener(`change`,n)}ea.INSTANCE.onDidChangeZoomLevel;function na(e){return ea.INSTANCE.getZoomFactor(e)}ea.INSTANCE.onDidChangeFullscreen;var ra=typeof navigator==`object`?navigator.userAgent:``,ia=ra.indexOf(`Firefox`)>=0,aa=ra.indexOf(`AppleWebKit`)>=0,oa=ra.indexOf(`Chrome`)>=0,sa=!oa&&ra.indexOf(`Safari`)>=0;ra.indexOf(`Electron/`),ra.indexOf(`Android`);var ca=!1;if(typeof Pi.matchMedia==`function`){let e=Pi.matchMedia(`(display-mode: standalone) or (display-mode: window-controls-overlay)`),t=Pi.matchMedia(`(display-mode: fullscreen)`);ca=e.matches,ta(Pi,e,({matches:e})=>{ca&&t.matches||(ca=e)})}function la(){return ca}var ua=`en`,da=!1,fa=!1,pa=!1,ma=!1,ha=!1,ga=ua,_a,va=globalThis,ya;typeof va.vscode<`u`&&typeof va.vscode.process<`u`?ya=va.vscode.process:typeof process<`u`&&typeof process?.versions?.node==`string`&&(ya=process);var ba=typeof ya?.versions?.electron==`string`&&ya?.type===`renderer`;if(typeof ya==`object`){da=ya.platform===`win32`,fa=ya.platform===`darwin`,pa=ya.platform===`linux`,pa&&ya.env.SNAP&&ya.env.SNAP_REVISION,ya.env.CI||ya.env.BUILD_ARTIFACTSTAGINGDIRECTORY,ga=ua;let e=ya.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);t.userLocale,t.osLocale,ga=t.resolvedLanguage||ua,t.languagePack?.translationsConfigFile}catch{}ma=!0}else typeof navigator==`object`&&!ba?(_a=navigator.userAgent,da=_a.indexOf(`Windows`)>=0,fa=_a.indexOf(`Macintosh`)>=0,(_a.indexOf(`Macintosh`)>=0||_a.indexOf(`iPad`)>=0||_a.indexOf(`iPhone`)>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints,pa=_a.indexOf(`Linux`)>=0,_a?.indexOf(`Mobi`),ha=!0,ga=globalThis._VSCODE_NLS_LANGUAGE||ua,navigator.language.toLowerCase()):console.error(`Unable to resolve platform.`);var xa=da,Sa=fa,Ca=pa,wa=ma;ha&&typeof va.importScripts==`function`&&va.origin;var Ta=_a,Ea=ga,Da;(e=>{function t(){return Ea}e.value=t;function n(){return Ea.length===2?Ea===`en`:Ea.length>=3&&Ea[0]===`e`&&Ea[1]===`n`&&Ea[2]===`-`}e.isDefaultVariant=n;function r(){return Ea===`en`}e.isDefault=r})(Da||={});var Oa=typeof va.postMessage==`function`&&!va.importScripts;(()=>{if(Oa){let e=[];va.addEventListener(`message`,t=>{if(t.data&&t.data.vscodeScheduleAsyncWork)for(let n=0,r=e.length;n<r;n++){let r=e[n];if(r.id===t.data.vscodeScheduleAsyncWork){e.splice(n,1),r.callback();return}}});let t=0;return n=>{let r=++t;e.push({id:r,callback:n}),va.postMessage({vscodeScheduleAsyncWork:r},`*`)}}return e=>setTimeout(e)})();var ka=!!(Ta&&Ta.indexOf(`Chrome`)>=0);Ta&&Ta.indexOf(`Firefox`),!ka&&Ta&&Ta.indexOf(`Safari`),Ta&&Ta.indexOf(`Edg/`),Ta&&Ta.indexOf(`Android`);var Aa=typeof navigator==`object`?navigator:{};wa||document.queryCommandSupported&&document.queryCommandSupported(`copy`)||Aa&&Aa.clipboard&&Aa.clipboard.writeText,wa||Aa&&Aa.clipboard&&Aa.clipboard.readText,wa||la()||Aa.keyboard,`ontouchstart`in Pi||Aa.maxTouchPoints,Pi.PointerEvent&&(`ontouchstart`in Pi||navigator.maxTouchPoints);var ja=class{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e}keyCodeToStr(e){return this._keyCodeToStr[e]}strToKeyCode(e){return this._strToKeyCode[e.toLowerCase()]||0}},Ma=new ja,Na=new ja,Pa=new ja,Fa=Array(230),Ia;(e=>{function t(e){return Ma.keyCodeToStr(e)}e.toString=t;function n(e){return Ma.strToKeyCode(e)}e.fromString=n;function r(e){return Na.keyCodeToStr(e)}e.toUserSettingsUS=r;function i(e){return Pa.keyCodeToStr(e)}e.toUserSettingsGeneral=i;function a(e){return Na.strToKeyCode(e)||Pa.strToKeyCode(e)}e.fromUserSettings=a;function o(e){if(e>=98&&e<=113)return null;switch(e){case 16:return`Up`;case 18:return`Down`;case 15:return`Left`;case 17:return`Right`}return Ma.keyCodeToStr(e)}e.toElectronAccelerator=o})(Ia||={});var La=class e{constructor(e,t,n,r,i){this.ctrlKey=e,this.shiftKey=t,this.altKey=n,this.metaKey=r,this.keyCode=i}equals(t){return t instanceof e&&this.ctrlKey===t.ctrlKey&&this.shiftKey===t.shiftKey&&this.altKey===t.altKey&&this.metaKey===t.metaKey&&this.keyCode===t.keyCode}getHashCode(){return`K${this.ctrlKey?`1`:`0`}${this.shiftKey?`1`:`0`}${this.altKey?`1`:`0`}${this.metaKey?`1`:`0`}${this.keyCode}`}isModifierKey(){return this.keyCode===0||this.keyCode===5||this.keyCode===57||this.keyCode===6||this.keyCode===4}toKeybinding(){return new Ra([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},Ra=class{constructor(e){if(e.length===0)throw gi(`chords`);this.chords=e}getHashCode(){let e=``;for(let t=0,n=this.chords.length;t<n;t++)t!==0&&(e+=`;`),e+=this.chords[t].getHashCode();return e}equals(e){if(e===null||this.chords.length!==e.chords.length)return!1;for(let t=0;t<this.chords.length;t++)if(!this.chords[t].equals(e.chords[t]))return!1;return!0}};function za(e){if(e.charCode){let t=String.fromCharCode(e.charCode).toUpperCase();return Ia.fromString(t)}let t=e.keyCode;if(t===3)return 7;if(ia)switch(t){case 59:return 85;case 60:if(Ca)return 97;break;case 61:return 86;case 107:return 109;case 109:return 111;case 173:return 88;case 224:if(Sa)return 57}else if(aa&&(Sa&&t===93||!Sa&&t===92))return 57;return Fa[t]||0}var Ba=Sa?256:2048,Va=512,Ha=1024,Ua=Sa?2048:256,Wa=class{constructor(e){this._standardKeyboardEventBrand=!0;let t=e;this.browserEvent=t,this.target=t.target,this.ctrlKey=t.ctrlKey,this.shiftKey=t.shiftKey,this.altKey=t.altKey,this.metaKey=t.metaKey,this.altGraphKey=t.getModifierState?.(`AltGraph`),this.keyCode=za(t),this.code=t.code,this.ctrlKey=this.ctrlKey||this.keyCode===5,this.altKey=this.altKey||this.keyCode===6,this.shiftKey=this.shiftKey||this.keyCode===4,this.metaKey=this.metaKey||this.keyCode===57,this._asKeybinding=this._computeKeybinding(),this._asKeyCodeChord=this._computeKeyCodeChord()}preventDefault(){this.browserEvent&&this.browserEvent.preventDefault&&this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent&&this.browserEvent.stopPropagation&&this.browserEvent.stopPropagation()}toKeyCodeChord(){return this._asKeyCodeChord}equals(e){return this._asKeybinding===e}_computeKeybinding(){let e=0;this.keyCode!==5&&this.keyCode!==4&&this.keyCode!==6&&this.keyCode!==57&&(e=this.keyCode);let t=0;return this.ctrlKey&&(t|=Ba),this.altKey&&(t|=Va),this.shiftKey&&(t|=Ha),this.metaKey&&(t|=Ua),t|=e,t}_computeKeyCodeChord(){let e=0;return this.keyCode!==5&&this.keyCode!==4&&this.keyCode!==6&&this.keyCode!==57&&(e=this.keyCode),new La(this.ctrlKey,this.shiftKey,this.altKey,this.metaKey,e)}},Ga=new WeakMap;function Ka(e){if(!e.parent||e.parent===e)return null;try{let t=e.location,n=e.parent.location;if(t.origin!==`null`&&n.origin!==`null`&&t.origin!==n.origin)return null}catch{return null}return e.parent}var qa=class{static getSameOriginWindowChain(e){let t=Ga.get(e);if(!t){t=[],Ga.set(e,t);let n=e,r;do r=Ka(n),r?t.push({window:new WeakRef(n),iframeElement:n.frameElement||null}):t.push({window:new WeakRef(n),iframeElement:null}),n=r;while(n)}return t.slice(0)}static getPositionOfChildWindowRelativeToAncestorWindow(e,t){if(!t||e===t)return{top:0,left:0};let n=0,r=0,i=this.getSameOriginWindowChain(e);for(let e of i){let i=e.window.deref();if(n+=i?.scrollY??0,r+=i?.scrollX??0,i===t||!e.iframeElement)break;let a=e.iframeElement.getBoundingClientRect();n+=a.top,r+=a.left}return{top:n,left:r}}},Ja=class{constructor(e,t){this.timestamp=Date.now(),this.browserEvent=t,this.leftButton=t.button===0,this.middleButton=t.button===1,this.rightButton=t.button===2,this.buttons=t.buttons,this.target=t.target,this.detail=t.detail||1,t.type===`dblclick`&&(this.detail=2),this.ctrlKey=t.ctrlKey,this.shiftKey=t.shiftKey,this.altKey=t.altKey,this.metaKey=t.metaKey,typeof t.pageX==`number`?(this.posx=t.pageX,this.posy=t.pageY):(this.posx=t.clientX+this.target.ownerDocument.body.scrollLeft+this.target.ownerDocument.documentElement.scrollLeft,this.posy=t.clientY+this.target.ownerDocument.body.scrollTop+this.target.ownerDocument.documentElement.scrollTop);let n=qa.getPositionOfChildWindowRelativeToAncestorWindow(e,t.view);this.posx-=n.left,this.posy-=n.top}preventDefault(){this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent.stopPropagation()}},Ya=class{constructor(e,t=0,n=0){this.browserEvent=e||null,this.target=e?e.target||e.targetNode||e.srcElement:null,this.deltaY=n,this.deltaX=t;let r=!1;if(oa){let e=navigator.userAgent.match(/Chrome\/(\d+)/);r=(e?parseInt(e[1]):123)<=122}if(e){let t=e,n=e,i=e.view?.devicePixelRatio||1;if(typeof t.wheelDeltaY<`u`)this.deltaY=r?t.wheelDeltaY/(120*i):t.wheelDeltaY/120;else if(typeof n.VERTICAL_AXIS<`u`&&n.axis===n.VERTICAL_AXIS)this.deltaY=-n.detail/3;else if(e.type===`wheel`){let t=e;this.deltaY=t.deltaMode===t.DOM_DELTA_LINE?ia&&!Sa?-e.deltaY/3:-e.deltaY:-e.deltaY/40}if(typeof t.wheelDeltaX<`u`)this.deltaX=sa&&xa?-(t.wheelDeltaX/120):r?t.wheelDeltaX/(120*i):t.wheelDeltaX/120;else if(typeof n.HORIZONTAL_AXIS<`u`&&n.axis===n.HORIZONTAL_AXIS)this.deltaX=-e.detail/3;else if(e.type===`wheel`){let t=e;this.deltaX=t.deltaMode===t.DOM_DELTA_LINE?ia&&!Sa?-e.deltaX/3:-e.deltaX:-e.deltaX/40}this.deltaY===0&&this.deltaX===0&&e.wheelDelta&&(this.deltaY=r?e.wheelDelta/(120*i):e.wheelDelta/120)}}preventDefault(){this.browserEvent?.preventDefault()}stopPropagation(){this.browserEvent?.stopPropagation()}},Xa=Object.freeze(function(e,t){let n=setTimeout(e.bind(t),0);return{dispose(){clearTimeout(n)}}}),Za;(e=>{function t(t){return t===e.None||t===e.Cancelled||t instanceof Qa?!0:!t||typeof t!=`object`?!1:typeof t.isCancellationRequested==`boolean`&&typeof t.onCancellationRequested==`function`}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:Bi.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:Xa})})(Za||={});var Qa=class{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?Xa:(this._emitter||=new U,this._emitter.event)}dispose(){this._emitter&&=(this._emitter.dispose(),null)}},$a=class{constructor(e,t){this._isDisposed=!1,this._token=-1,typeof e==`function`&&typeof t==`number`&&this.setIfNotSet(e,t)}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._token!==-1&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(e,t){if(this._isDisposed)throw new vi(`Calling 'cancelAndSet' on a disposed TimeoutTimer`);this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new vi(`Calling 'setIfNotSet' on a disposed TimeoutTimer`);this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},eo=class{constructor(){this.disposable=void 0,this.isDisposed=!1}cancel(){this.disposable?.dispose(),this.disposable=void 0}cancelAndSet(e,t,n=globalThis){if(this.isDisposed)throw new vi(`Calling 'cancelAndSet' on a disposed IntervalTimer`);this.cancel();let r=n.setInterval(()=>{e()},t);this.disposable=V(()=>{n.clearInterval(r),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}};(function(){typeof globalThis.requestIdleCallback!=`function`||globalThis.cancelIdleCallback})();var to;(e=>{async function t(e){let t,n=await Promise.all(e.map(e=>e.then(e=>e,e=>{t||=e})));if(typeof t<`u`)throw t;return n}e.settled=t;function n(e){return new Promise(async(t,n)=>{try{await e(t,n)}catch(e){n(e)}})}e.withAsyncBody=n})(to||={});var no=class e{static fromArray(t){return new e(e=>{e.emitMany(t)})}static fromPromise(t){return new e(async e=>{e.emitMany(await t)})}static fromPromises(t){return new e(async e=>{await Promise.all(t.map(async t=>e.emitOne(await t)))})}static merge(t){return new e(async e=>{await Promise.all(t.map(async t=>{for await(let n of t)e.emitOne(n)}))})}constructor(e,t){this._state=0,this._results=[],this._error=null,this._onReturn=t,this._onStateChanged=new U,queueMicrotask(async()=>{let t={emitOne:e=>this.emitOne(e),emitMany:e=>this.emitMany(e),reject:e=>this.reject(e)};try{await Promise.resolve(e(t)),this.resolve()}catch(e){this.reject(e)}finally{t.emitOne=void 0,t.emitMany=void 0,t.reject=void 0}})}[Symbol.asyncIterator](){let e=0;return{next:async()=>{do{if(this._state===2)throw this._error;if(e<this._results.length)return{done:!1,value:this._results[e++]};if(this._state===1)return{done:!0,value:void 0};await Bi.toPromise(this._onStateChanged.event)}while(1)},return:async()=>(this._onReturn?.(),{done:!0,value:void 0})}}static map(t,n){return new e(async e=>{for await(let r of t)e.emitOne(n(r))})}map(t){return e.map(this,t)}static filter(t,n){return new e(async e=>{for await(let r of t)n(r)&&e.emitOne(r)})}filter(t){return e.filter(this,t)}static coalesce(t){return e.filter(t,e=>!!e)}coalesce(){return e.coalesce(this)}static async toPromise(e){let t=[];for await(let n of e)t.push(n);return t}toPromise(){return e.toPromise(this)}emitOne(e){this._state===0&&(this._results.push(e),this._onStateChanged.fire())}emitMany(e){this._state===0&&(this._results=this._results.concat(e),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(e){this._state===0&&(this._state=2,this._error=e,this._onStateChanged.fire())}};no.EMPTY=no.fromArray([]);function ro(e){return io(e,0)}function io(e,t){switch(typeof e){case`object`:return e===null?ao(349,t):Array.isArray(e)?co(e,t):lo(e,t);case`string`:return so(e,t);case`boolean`:return oo(e,t);case`number`:return ao(e,t);case`undefined`:return ao(937,t);default:return ao(617,t)}}function ao(e,t){return(t<<5)-t+e|0}function oo(e,t){return ao(e?433:863,t)}function so(e,t){t=ao(149417,t);for(let n=0,r=e.length;n<r;n++)t=ao(e.charCodeAt(n),t);return t}function co(e,t){return t=ao(104579,t),e.reduce((e,t)=>io(t,e),t)}function lo(e,t){return t=ao(181387,t),Object.keys(e).sort().reduce((t,n)=>(t=so(n,t),io(e[n],t)),t)}var{registerWindow:uo,getWindow:fo,getDocument:po,getWindows:mo,getWindowsCount:ho,getWindowId:go,getWindowById:_o,hasWindow:vo,onDidRegisterWindow:yo,onWillUnregisterWindow:bo,onDidUnregisterWindow:xo}=function(){let e=new Map,t={window:Pi,disposables:new Mi};e.set(Pi.vscodeWindowId,t);let n=new U,r=new U,i=new U;function a(n,r){return(typeof n==`number`?e.get(n):void 0)??(r?t:void 0)}return{onDidRegisterWindow:n.event,onWillUnregisterWindow:i.event,onDidUnregisterWindow:r.event,registerWindow(t){if(e.has(t.vscodeWindowId))return H.None;let a=new Mi,o={window:t,disposables:a.add(new Mi)};return e.set(t.vscodeWindowId,o),a.add(V(()=>{e.delete(t.vscodeWindowId),r.fire(t)})),a.add(W(t,jo.BEFORE_UNLOAD,()=>{i.fire(t)})),n.fire(o),a},getWindows(){return e.values()},getWindowsCount(){return e.size},getWindowId(e){return e.vscodeWindowId},hasWindow(t){return e.has(t)},getWindowById:a,getWindow(e){let t=e;if(t?.ownerDocument?.defaultView)return t.ownerDocument.defaultView.window;let n=e;return n?.view?n.view.window:Pi},getDocument(e){return fo(e).document}}}(),So=class{constructor(e,t,n,r){this._node=e,this._type=t,this._handler=n,this._options=r||!1,this._node.addEventListener(this._type,this._handler,this._options)}dispose(){this._handler&&=(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,null)}};function W(e,t,n,r){return new So(e,t,n,r)}function Co(e,t){return function(n){return t(new Ja(e,n))}}function wo(e){return function(t){return e(new Wa(t))}}var To=function(e,t,n,r){let i=n;return t===`click`||t===`mousedown`||t===`contextmenu`?i=Co(fo(e),n):(t===`keydown`||t===`keypress`||t===`keyup`)&&(i=wo(n)),W(e,t,i,r)},Eo,Do=class extends eo{constructor(e){super(),this.defaultTarget=e&&fo(e)}cancelAndSet(e,t,n){return super.cancelAndSet(e,t,n??this.defaultTarget)}},Oo=class{constructor(e,t=0){this._runner=e,this.priority=t,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(e){fi(e)}}static sort(e,t){return t.priority-e.priority}};(function(){let e=new Map,t=new Map,n=new Map,r=new Map,i=i=>{n.set(i,!1);let a=e.get(i)??[];for(t.set(i,a),e.set(i,[]),r.set(i,!0);a.length>0;)a.sort(Oo.sort),a.shift().execute();r.set(i,!1)};Eo=(t,r,a=0)=>{let o=go(t),s=new Oo(r,a),c=e.get(o);return c||(c=[],e.set(o,c)),c.push(s),n.get(o)||(n.set(o,!0),t.requestAnimationFrame(()=>i(o))),s}})();var ko=class e{constructor(e,t){this.width=e,this.height=t}with(t=this.width,n=this.height){return t!==this.width||n!==this.height?new e(t,n):this}static is(e){return typeof e==`object`&&typeof e.height==`number`&&typeof e.width==`number`}static lift(t){return t instanceof e?t:new e(t.width,t.height)}static equals(e,t){return e===t?!0:!e||!t?!1:e.width===t.width&&e.height===t.height}};ko.None=new ko(0,0);function Ao(e){let t=e.getBoundingClientRect(),n=fo(e);return{left:t.left+n.scrollX,top:t.top+n.scrollY,width:t.width,height:t.height}}new class{constructor(){this.mutationObservers=new Map}observe(e,t,n){let r=this.mutationObservers.get(e);r||(r=new Map,this.mutationObservers.set(e,r));let i=ro(n),a=r.get(i);if(a)a.users+=1;else{let o=new U,s=new MutationObserver(e=>o.fire(e));s.observe(e,n);let c=a={users:1,observer:s,onDidMutate:o.event};t.add(V(()=>{--c.users,c.users===0&&(o.dispose(),s.disconnect(),r?.delete(i),r?.size===0&&this.mutationObservers.delete(e))})),r.set(i,a)}return a.onDidMutate}};var jo={CLICK:`click`,AUXCLICK:`auxclick`,DBLCLICK:`dblclick`,MOUSE_UP:`mouseup`,MOUSE_DOWN:`mousedown`,MOUSE_OVER:`mouseover`,MOUSE_MOVE:`mousemove`,MOUSE_OUT:`mouseout`,MOUSE_ENTER:`mouseenter`,MOUSE_LEAVE:`mouseleave`,MOUSE_WHEEL:`wheel`,POINTER_UP:`pointerup`,POINTER_DOWN:`pointerdown`,POINTER_MOVE:`pointermove`,POINTER_LEAVE:`pointerleave`,CONTEXT_MENU:`contextmenu`,WHEEL:`wheel`,KEY_DOWN:`keydown`,KEY_PRESS:`keypress`,KEY_UP:`keyup`,LOAD:`load`,BEFORE_UNLOAD:`beforeunload`,UNLOAD:`unload`,PAGE_SHOW:`pageshow`,PAGE_HIDE:`pagehide`,PASTE:`paste`,ABORT:`abort`,ERROR:`error`,RESIZE:`resize`,SCROLL:`scroll`,FULLSCREEN_CHANGE:`fullscreenchange`,WK_FULLSCREEN_CHANGE:`webkitfullscreenchange`,SELECT:`select`,CHANGE:`change`,SUBMIT:`submit`,RESET:`reset`,FOCUS:`focus`,FOCUS_IN:`focusin`,FOCUS_OUT:`focusout`,BLUR:`blur`,INPUT:`input`,STORAGE:`storage`,DRAG_START:`dragstart`,DRAG:`drag`,DRAG_ENTER:`dragenter`,DRAG_LEAVE:`dragleave`,DRAG_OVER:`dragover`,DROP:`drop`,DRAG_END:`dragend`,ANIMATION_START:aa?`webkitAnimationStart`:`animationstart`,ANIMATION_END:aa?`webkitAnimationEnd`:`animationend`,ANIMATION_ITERATION:aa?`webkitAnimationIteration`:`animationiteration`},Mo=class{constructor(e){this.domNode=e,this._maxWidth=``,this._width=``,this._height=``,this._top=``,this._left=``,this._bottom=``,this._right=``,this._paddingTop=``,this._paddingLeft=``,this._paddingBottom=``,this._paddingRight=``,this._fontFamily=``,this._fontWeight=``,this._fontSize=``,this._fontStyle=``,this._fontFeatureSettings=``,this._fontVariationSettings=``,this._textDecoration=``,this._lineHeight=``,this._letterSpacing=``,this._className=``,this._display=``,this._position=``,this._visibility=``,this._color=``,this._backgroundColor=``,this._layerHint=!1,this._contain=`none`,this._boxShadow=``}setMaxWidth(e){let t=No(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=No(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=No(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=No(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=No(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=No(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=No(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=No(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=No(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=No(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=No(e);this._paddingRight!==t&&(this._paddingRight=t,this.domNode.style.paddingRight=this._paddingRight)}setFontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.domNode.style.fontFamily=this._fontFamily)}setFontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.domNode.style.fontWeight=this._fontWeight)}setFontSize(e){let t=No(e);this._fontSize!==t&&(this._fontSize=t,this.domNode.style.fontSize=this._fontSize)}setFontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this.domNode.style.fontStyle=this._fontStyle)}setFontFeatureSettings(e){this._fontFeatureSettings!==e&&(this._fontFeatureSettings=e,this.domNode.style.fontFeatureSettings=this._fontFeatureSettings)}setFontVariationSettings(e){this._fontVariationSettings!==e&&(this._fontVariationSettings=e,this.domNode.style.fontVariationSettings=this._fontVariationSettings)}setTextDecoration(e){this._textDecoration!==e&&(this._textDecoration=e,this.domNode.style.textDecoration=this._textDecoration)}setLineHeight(e){let t=No(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=No(e);this._letterSpacing!==t&&(this._letterSpacing=t,this.domNode.style.letterSpacing=this._letterSpacing)}setClassName(e){this._className!==e&&(this._className=e,this.domNode.className=this._className)}toggleClassName(e,t){this.domNode.classList.toggle(e,t),this._className=this.domNode.className}setDisplay(e){this._display!==e&&(this._display=e,this.domNode.style.display=this._display)}setPosition(e){this._position!==e&&(this._position=e,this.domNode.style.position=this._position)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this.domNode.style.visibility=this._visibility)}setColor(e){this._color!==e&&(this._color=e,this.domNode.style.color=this._color)}setBackgroundColor(e){this._backgroundColor!==e&&(this._backgroundColor=e,this.domNode.style.backgroundColor=this._backgroundColor)}setLayerHinting(e){this._layerHint!==e&&(this._layerHint=e,this.domNode.style.transform=this._layerHint?`translate3d(0px, 0px, 0px)`:``)}setBoxShadow(e){this._boxShadow!==e&&(this._boxShadow=e,this.domNode.style.boxShadow=e)}setContain(e){this._contain!==e&&(this._contain=e,this.domNode.style.contain=this._contain)}setAttribute(e,t){this.domNode.setAttribute(e,t)}removeAttribute(e){this.domNode.removeAttribute(e)}appendChild(e){this.domNode.appendChild(e.domNode)}removeChild(e){this.domNode.removeChild(e.domNode)}};function No(e){return typeof e==`number`?`${e}px`:e}function Po(e){return new Mo(e)}var Fo=class{constructor(){this._hooks=new Mi,this._pointerMoveCallback=null,this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(e,t){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;let n=this._onStopCallback;this._onStopCallback=null,e&&n&&n(t)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(e,t,n,r,i){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=r,this._onStopCallback=i;let a=e;try{e.setPointerCapture(t),this._hooks.add(V(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{a=fo(e)}this._hooks.add(W(a,jo.POINTER_MOVE,e=>{e.buttons===n?(e.preventDefault(),this._pointerMoveCallback(e)):this.stopMonitoring(!0)})),this._hooks.add(W(a,jo.POINTER_UP,e=>this.stopMonitoring(!0)))}};function Io(e,t,n){let r=null,i=null;if(typeof n.value==`function`?(r=`value`,i=n.value,i.length!==0&&console.warn(`Memoize should only be used in functions with zero parameters`)):typeof n.get==`function`&&(r=`get`,i=n.get),!i)throw Error(`not supported`);let a=`$memoize$${t}`;n[r]=function(...e){return this.hasOwnProperty(a)||Object.defineProperty(this,a,{configurable:!1,enumerable:!1,writable:!1,value:i.apply(this,e)}),this[a]}}var Lo;(e=>(e.Tap=`-xterm-gesturetap`,e.Change=`-xterm-gesturechange`,e.Start=`-xterm-gesturestart`,e.End=`-xterm-gesturesend`,e.Contextmenu=`-xterm-gesturecontextmenu`))(Lo||={});var Ro=class e extends H{constructor(){super(),this.dispatched=!1,this.targets=new Li,this.ignoreTargets=new Li,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(Bi.runAndSubscribe(yo,({window:e,disposables:t})=>{t.add(W(e.document,`touchstart`,e=>this.onTouchStart(e),{passive:!1})),t.add(W(e.document,`touchend`,t=>this.onTouchEnd(e,t))),t.add(W(e.document,`touchmove`,e=>this.onTouchMove(e),{passive:!1}))},{window:Pi,disposables:this._store}))}static addTarget(t){return e.isTouchDevice()?(e.INSTANCE||=Oi(new e),V(e.INSTANCE.targets.push(t))):H.None}static ignoreTarget(t){return e.isTouchDevice()?(e.INSTANCE||=Oi(new e),V(e.INSTANCE.ignoreTargets.push(t))):H.None}static isTouchDevice(){return`ontouchstart`in Pi||navigator.maxTouchPoints>0}dispose(){this.handle&&=(this.handle.dispose(),null),super.dispose()}onTouchStart(e){let t=Date.now();this.handle&&=(this.handle.dispose(),null);for(let n=0,r=e.targetTouches.length;n<r;n++){let r=e.targetTouches.item(n);this.activeTouches[r.identifier]={id:r.identifier,initialTarget:r.target,initialTimeStamp:t,initialPageX:r.pageX,initialPageY:r.pageY,rollingTimestamps:[t],rollingPageX:[r.pageX],rollingPageY:[r.pageY]};let i=this.newGestureEvent(Lo.Start,r.target);i.pageX=r.pageX,i.pageY=r.pageY,this.dispatchEvent(i)}this.dispatched&&=(e.preventDefault(),e.stopPropagation(),!1)}onTouchEnd(t,n){let r=Date.now(),i=Object.keys(this.activeTouches).length;for(let a=0,o=n.changedTouches.length;a<o;a++){let o=n.changedTouches.item(a);if(!this.activeTouches.hasOwnProperty(String(o.identifier))){console.warn(`move of an UNKNOWN touch`,o);continue}let s=this.activeTouches[o.identifier],c=Date.now()-s.initialTimeStamp;if(c<e.HOLD_DELAY&&Math.abs(s.initialPageX-yi(s.rollingPageX))<30&&Math.abs(s.initialPageY-yi(s.rollingPageY))<30){let e=this.newGestureEvent(Lo.Tap,s.initialTarget);e.pageX=yi(s.rollingPageX),e.pageY=yi(s.rollingPageY),this.dispatchEvent(e)}else if(c>=e.HOLD_DELAY&&Math.abs(s.initialPageX-yi(s.rollingPageX))<30&&Math.abs(s.initialPageY-yi(s.rollingPageY))<30){let e=this.newGestureEvent(Lo.Contextmenu,s.initialTarget);e.pageX=yi(s.rollingPageX),e.pageY=yi(s.rollingPageY),this.dispatchEvent(e)}else if(i===1){let e=yi(s.rollingPageX),n=yi(s.rollingPageY),i=yi(s.rollingTimestamps)-s.rollingTimestamps[0],a=e-s.rollingPageX[0],o=n-s.rollingPageY[0],c=[...this.targets].filter(e=>s.initialTarget instanceof Node&&e.contains(s.initialTarget));this.inertia(t,c,r,Math.abs(a)/i,a>0?1:-1,e,Math.abs(o)/i,o>0?1:-1,n)}this.dispatchEvent(this.newGestureEvent(Lo.End,s.initialTarget)),delete this.activeTouches[o.identifier]}this.dispatched&&=(n.preventDefault(),n.stopPropagation(),!1)}newGestureEvent(e,t){let n=document.createEvent(`CustomEvent`);return n.initEvent(e,!1,!0),n.initialTarget=t,n.tapCount=0,n}dispatchEvent(t){if(t.type===Lo.Tap){let n=new Date().getTime(),r=0;r=n-this._lastSetTapCountTime>e.CLEAR_TAP_COUNT_TIME?1:2,this._lastSetTapCountTime=n,t.tapCount=r}else(t.type===Lo.Change||t.type===Lo.Contextmenu)&&(this._lastSetTapCountTime=0);if(t.initialTarget instanceof Node){for(let e of this.ignoreTargets)if(e.contains(t.initialTarget))return;let e=[];for(let n of this.targets)if(n.contains(t.initialTarget)){let r=0,i=t.initialTarget;for(;i&&i!==n;)r++,i=i.parentElement;e.push([r,n])}e.sort((e,t)=>e[0]-t[0]);for(let[n,r]of e)r.dispatchEvent(t),this.dispatched=!0}}inertia(t,n,r,i,a,o,s,c,l){this.handle=Eo(t,()=>{let u=Date.now(),d=u-r,f=0,p=0,m=!0;i+=e.SCROLL_FRICTION*d,s+=e.SCROLL_FRICTION*d,i>0&&(m=!1,f=a*i*d),s>0&&(m=!1,p=c*s*d);let h=this.newGestureEvent(Lo.Change);h.translationX=f,h.translationY=p,n.forEach(e=>e.dispatchEvent(h)),m||this.inertia(t,n,u,i,a,o+f,s,c,l+p)})}onTouchMove(e){let t=Date.now();for(let n=0,r=e.changedTouches.length;n<r;n++){let r=e.changedTouches.item(n);if(!this.activeTouches.hasOwnProperty(String(r.identifier))){console.warn(`end of an UNKNOWN touch`,r);continue}let i=this.activeTouches[r.identifier],a=this.newGestureEvent(Lo.Change,i.initialTarget);a.translationX=r.pageX-yi(i.rollingPageX),a.translationY=r.pageY-yi(i.rollingPageY),a.pageX=r.pageX,a.pageY=r.pageY,this.dispatchEvent(a),i.rollingPageX.length>3&&(i.rollingPageX.shift(),i.rollingPageY.shift(),i.rollingTimestamps.shift()),i.rollingPageX.push(r.pageX),i.rollingPageY.push(r.pageY),i.rollingTimestamps.push(t)}this.dispatched&&=(e.preventDefault(),e.stopPropagation(),!1)}};Ro.SCROLL_FRICTION=-.005,Ro.HOLD_DELAY=700,Ro.CLEAR_TAP_COUNT_TIME=400,R([Io],Ro,`isTouchDevice`,1);var zo=Ro,Bo=class extends H{onclick(e,t){this._register(W(e,jo.CLICK,n=>t(new Ja(fo(e),n))))}onmousedown(e,t){this._register(W(e,jo.MOUSE_DOWN,n=>t(new Ja(fo(e),n))))}onmouseover(e,t){this._register(W(e,jo.MOUSE_OVER,n=>t(new Ja(fo(e),n))))}onmouseleave(e,t){this._register(W(e,jo.MOUSE_LEAVE,n=>t(new Ja(fo(e),n))))}onkeydown(e,t){this._register(W(e,jo.KEY_DOWN,e=>t(new Wa(e))))}onkeyup(e,t){this._register(W(e,jo.KEY_UP,e=>t(new Wa(e))))}oninput(e,t){this._register(W(e,jo.INPUT,t))}onblur(e,t){this._register(W(e,jo.BLUR,t))}onfocus(e,t){this._register(W(e,jo.FOCUS,t))}onchange(e,t){this._register(W(e,jo.CHANGE,t))}ignoreGesture(e){return zo.ignoreTarget(e)}},Vo=11,Ho=class extends Bo{constructor(e){super(),this._onActivate=e.onActivate,this.bgDomNode=document.createElement(`div`),this.bgDomNode.className=`arrow-background`,this.bgDomNode.style.position=`absolute`,this.bgDomNode.style.width=e.bgWidth+`px`,this.bgDomNode.style.height=e.bgHeight+`px`,typeof e.top<`u`&&(this.bgDomNode.style.top=`0px`),typeof e.left<`u`&&(this.bgDomNode.style.left=`0px`),typeof e.bottom<`u`&&(this.bgDomNode.style.bottom=`0px`),typeof e.right<`u`&&(this.bgDomNode.style.right=`0px`),this.domNode=document.createElement(`div`),this.domNode.className=e.className,this.domNode.style.position=`absolute`,this.domNode.style.width=Vo+`px`,this.domNode.style.height=Vo+`px`,typeof e.top<`u`&&(this.domNode.style.top=e.top+`px`),typeof e.left<`u`&&(this.domNode.style.left=e.left+`px`),typeof e.bottom<`u`&&(this.domNode.style.bottom=e.bottom+`px`),typeof e.right<`u`&&(this.domNode.style.right=e.right+`px`),this._pointerMoveMonitor=this._register(new Fo),this._register(To(this.bgDomNode,jo.POINTER_DOWN,e=>this._arrowPointerDown(e))),this._register(To(this.domNode,jo.POINTER_DOWN,e=>this._arrowPointerDown(e))),this._pointerdownRepeatTimer=this._register(new Do),this._pointerdownScheduleRepeatTimer=this._register(new $a)}_arrowPointerDown(e){e.target&&e.target instanceof Element&&(this._onActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet(()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,fo(e))},200),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,e=>{},()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()}),e.preventDefault())}},Uo=class e{constructor(e,t,n,r,i,a,o){this._forceIntegerValues=e,this._scrollStateBrand=void 0,this._forceIntegerValues&&(t|=0,n|=0,r|=0,i|=0,a|=0,o|=0),this.rawScrollLeft=r,this.rawScrollTop=o,t<0&&(t=0),r+t>n&&(r=n-t),r<0&&(r=0),i<0&&(i=0),o+i>a&&(o=a-i),o<0&&(o=0),this.width=t,this.scrollWidth=n,this.scrollLeft=r,this.height=i,this.scrollHeight=a,this.scrollTop=o}equals(e){return this.rawScrollLeft===e.rawScrollLeft&&this.rawScrollTop===e.rawScrollTop&&this.width===e.width&&this.scrollWidth===e.scrollWidth&&this.scrollLeft===e.scrollLeft&&this.height===e.height&&this.scrollHeight===e.scrollHeight&&this.scrollTop===e.scrollTop}withScrollDimensions(t,n){return new e(this._forceIntegerValues,typeof t.width<`u`?t.width:this.width,typeof t.scrollWidth<`u`?t.scrollWidth:this.scrollWidth,n?this.rawScrollLeft:this.scrollLeft,typeof t.height<`u`?t.height:this.height,typeof t.scrollHeight<`u`?t.scrollHeight:this.scrollHeight,n?this.rawScrollTop:this.scrollTop)}withScrollPosition(t){return new e(this._forceIntegerValues,this.width,this.scrollWidth,typeof t.scrollLeft<`u`?t.scrollLeft:this.rawScrollLeft,this.height,this.scrollHeight,typeof t.scrollTop<`u`?t.scrollTop:this.rawScrollTop)}createScrollEvent(e,t){let n=this.width!==e.width,r=this.scrollWidth!==e.scrollWidth,i=this.scrollLeft!==e.scrollLeft,a=this.height!==e.height,o=this.scrollHeight!==e.scrollHeight,s=this.scrollTop!==e.scrollTop;return{inSmoothScrolling:t,oldWidth:e.width,oldScrollWidth:e.scrollWidth,oldScrollLeft:e.scrollLeft,width:this.width,scrollWidth:this.scrollWidth,scrollLeft:this.scrollLeft,oldHeight:e.height,oldScrollHeight:e.scrollHeight,oldScrollTop:e.scrollTop,height:this.height,scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,widthChanged:n,scrollWidthChanged:r,scrollLeftChanged:i,heightChanged:a,scrollHeightChanged:o,scrollTopChanged:s}}},Wo=class extends H{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new U),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new Uo(e.forceIntegerValues,0,0,0,0,0,0),this._smoothScrolling=null}dispose(){this._smoothScrolling&&=(this._smoothScrolling.dispose(),null),super.dispose()}setSmoothScrollDuration(e){this._smoothScrollDuration=e}validateScrollPosition(e){return this._state.withScrollPosition(e)}getScrollDimensions(){return this._state}setScrollDimensions(e,t){let n=this._state.withScrollDimensions(e,t);this._setState(n,!!this._smoothScrolling),this._smoothScrolling?.acceptScrollDimensions(this._state)}getFutureScrollPosition(){return this._smoothScrolling?this._smoothScrolling.to:this._state}getCurrentScrollPosition(){return this._state}setScrollPositionNow(e){let t=this._state.withScrollPosition(e);this._smoothScrolling&&=(this._smoothScrolling.dispose(),null),this._setState(t,!1)}setScrollPositionSmooth(e,t){if(this._smoothScrollDuration===0)return this.setScrollPositionNow(e);if(this._smoothScrolling){e={scrollLeft:typeof e.scrollLeft>`u`?this._smoothScrolling.to.scrollLeft:e.scrollLeft,scrollTop:typeof e.scrollTop>`u`?this._smoothScrolling.to.scrollTop:e.scrollTop};let n=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===n.scrollLeft&&this._smoothScrolling.to.scrollTop===n.scrollTop)return;let r;r=t?new Jo(this._smoothScrolling.from,n,this._smoothScrolling.startTime,this._smoothScrolling.duration):this._smoothScrolling.combine(this._state,n,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=r}else{let t=this._state.withScrollPosition(e);this._smoothScrolling=Jo.start(this._state,t,this._smoothScrollDuration)}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}hasPendingScrollAnimation(){return!!this._smoothScrolling}_performSmoothScrolling(){if(!this._smoothScrolling)return;let e=this._smoothScrolling.tick(),t=this._state.withScrollPosition(e);if(this._setState(t,!0),this._smoothScrolling){if(e.isDone){this._smoothScrolling.dispose(),this._smoothScrolling=null;return}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}}_setState(e,t){let n=this._state;n.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(n,t)))}},Go=class{constructor(e,t,n){this.scrollLeft=e,this.scrollTop=t,this.isDone=n}};function Ko(e,t){let n=t-e;return function(t){return e+n*Xo(t)}}function qo(e,t,n){return function(r){return r<n?e(r/n):t((r-n)/(1-n))}}var Jo=class e{constructor(e,t,n,r){this.from=e,this.to=t,this.duration=r,this.startTime=n,this.animationFrameDisposable=null,this._initAnimations()}_initAnimations(){this.scrollLeft=this._initAnimation(this.from.scrollLeft,this.to.scrollLeft,this.to.width),this.scrollTop=this._initAnimation(this.from.scrollTop,this.to.scrollTop,this.to.height)}_initAnimation(e,t,n){if(Math.abs(e-t)>2.5*n){let r,i;return e<t?(r=e+.75*n,i=t-.75*n):(r=e-.75*n,i=t+.75*n),qo(Ko(e,r),Ko(i,t),.33)}return Ko(e,t)}dispose(){this.animationFrameDisposable!==null&&(this.animationFrameDisposable.dispose(),this.animationFrameDisposable=null)}acceptScrollDimensions(e){this.to=e.withScrollPosition(this.to),this._initAnimations()}tick(){return this._tick(Date.now())}_tick(e){let t=(e-this.startTime)/this.duration;return t<1?new Go(this.scrollLeft(t),this.scrollTop(t),!1):new Go(this.to.scrollLeft,this.to.scrollTop,!0)}combine(t,n,r){return e.start(t,n,r)}static start(t,n,r){r+=10;let i=Date.now()-10;return new e(t,n,i,r)}};function Yo(e){return e**3}function Xo(e){return 1-Yo(1-e)}var Zo=class extends H{constructor(e,t,n){super(),this._visibility=e,this._visibleClassName=t,this._invisibleClassName=n,this._domNode=null,this._isVisible=!1,this._isNeeded=!1,this._rawShouldBeVisible=!1,this._shouldBeVisible=!1,this._revealTimer=this._register(new $a)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this._updateShouldBeVisible())}setShouldBeVisible(e){this._rawShouldBeVisible=e,this._updateShouldBeVisible()}_applyVisibilitySetting(){return this._visibility===2?!1:this._visibility===3||this._rawShouldBeVisible}_updateShouldBeVisible(){let e=this._applyVisibilitySetting();this._shouldBeVisible!==e&&(this._shouldBeVisible=e,this.ensureVisibility())}setIsNeeded(e){this._isNeeded!==e&&(this._isNeeded=e,this.ensureVisibility())}setDomNode(e){this._domNode=e,this._domNode.setClassName(this._invisibleClassName),this.setShouldBeVisible(!1)}ensureVisibility(){this._isNeeded?this._shouldBeVisible?this._reveal():this._hide(!0):this._hide(!1)}_reveal(){this._isVisible||(this._isVisible=!0,this._revealTimer.setIfNotSet(()=>{this._domNode?.setClassName(this._visibleClassName)},0))}_hide(e){this._revealTimer.cancel(),this._isVisible&&(this._isVisible=!1,this._domNode?.setClassName(this._invisibleClassName+(e?` fade`:``)))}},Qo=140,$o=class extends Bo{constructor(e){super(),this._lazyRender=e.lazyRender,this._host=e.host,this._scrollable=e.scrollable,this._scrollByPage=e.scrollByPage,this._scrollbarState=e.scrollbarState,this._visibilityController=this._register(new Zo(e.visibility,`visible scrollbar `+e.extraScrollbarClassName,`invisible scrollbar `+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new Fo),this._shouldRender=!0,this.domNode=Po(document.createElement(`div`)),this.domNode.setAttribute(`role`,`presentation`),this.domNode.setAttribute(`aria-hidden`,`true`),this._visibilityController.setDomNode(this.domNode),this.domNode.setPosition(`absolute`),this._register(W(this.domNode.domNode,jo.POINTER_DOWN,e=>this._domNodePointerDown(e)))}_createArrow(e){let t=this._register(new Ho(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,n,r){this.slider=Po(document.createElement(`div`)),this.slider.setClassName(`slider`),this.slider.setPosition(`absolute`),this.slider.setTop(e),this.slider.setLeft(t),typeof n==`number`&&this.slider.setWidth(n),typeof r==`number`&&this.slider.setHeight(r),this.slider.setLayerHinting(!0),this.slider.setContain(`strict`),this.domNode.domNode.appendChild(this.slider.domNode),this._register(W(this.slider.domNode,jo.POINTER_DOWN,e=>{e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))})),this.onclick(this.slider.domNode,e=>{e.leftButton&&e.stopPropagation()})}_onElementSize(e){return this._scrollbarState.setVisibleSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollSize(e){return this._scrollbarState.setScrollSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollPosition(e){return this._scrollbarState.setScrollPosition(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}beginReveal(){this._visibilityController.setShouldBeVisible(!0)}beginHide(){this._visibilityController.setShouldBeVisible(!1)}render(){this._shouldRender&&(this._shouldRender=!1,this._renderDomNode(this._scrollbarState.getRectangleLargeSize(),this._scrollbarState.getRectangleSmallSize()),this._updateSlider(this._scrollbarState.getSliderSize(),this._scrollbarState.getArrowSize()+this._scrollbarState.getSliderPosition()))}_domNodePointerDown(e){e.target===this.domNode.domNode&&this._onPointerDown(e)}delegatePointerDown(e){let t=this.domNode.domNode.getClientRects()[0].top,n=t+this._scrollbarState.getSliderPosition(),r=t+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),i=this._sliderPointerPosition(e);n<=i&&i<=r?e.button===0&&(e.preventDefault(),this._sliderPointerDown(e)):this._onPointerDown(e)}_onPointerDown(e){let t,n;if(e.target===this.domNode.domNode&&typeof e.offsetX==`number`&&typeof e.offsetY==`number`)t=e.offsetX,n=e.offsetY;else{let r=Ao(this.domNode.domNode);t=e.pageX-r.left,n=e.pageY-r.top}let r=this._pointerDownRelativePosition(t,n);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(r):this._scrollbarState.getDesiredScrollPositionFromOffset(r)),e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))}_sliderPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=this._sliderPointerPosition(e),n=this._sliderOrthogonalPointerPosition(e),r=this._scrollbarState.clone();this.slider.toggleClassName(`active`,!0),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,e=>{let i=this._sliderOrthogonalPointerPosition(e),a=Math.abs(i-n);if(xa&&a>Qo){this._setDesiredScrollPositionNow(r.getScrollPosition());return}let o=this._sliderPointerPosition(e)-t;this._setDesiredScrollPositionNow(r.getDesiredScrollPositionFromDelta(o))},()=>{this.slider.toggleClassName(`active`,!1),this._host.onDragEnd()}),this._host.onDragStart()}_setDesiredScrollPositionNow(e){let t={};this.writeScrollPosition(t,e),this._scrollable.setScrollPositionNow(t)}updateScrollbarSize(e){this._updateScrollbarSize(e),this._scrollbarState.setScrollbarSize(e),this._shouldRender=!0,this._lazyRender||this.render()}isNeeded(){return this._scrollbarState.isNeeded()}},es=class e{constructor(e,t,n,r,i,a){this._scrollbarSize=Math.round(t),this._oppositeScrollbarSize=Math.round(n),this._arrowSize=Math.round(e),this._visibleSize=r,this._scrollSize=i,this._scrollPosition=a,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new e(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(e){let t=Math.round(e);return this._visibleSize!==t&&(this._visibleSize=t,this._refreshComputedValues(),!0)}setScrollSize(e){let t=Math.round(e);return this._scrollSize!==t&&(this._scrollSize=t,this._refreshComputedValues(),!0)}setScrollPosition(e){let t=Math.round(e);return this._scrollPosition!==t&&(this._scrollPosition=t,this._refreshComputedValues(),!0)}setScrollbarSize(e){this._scrollbarSize=Math.round(e)}setOppositeScrollbarSize(e){this._oppositeScrollbarSize=Math.round(e)}static _computeValues(e,t,n,r,i){let a=Math.max(0,n-e),o=Math.max(0,a-2*t),s=r>0&&r>n;if(!s)return{computedAvailableSize:Math.round(a),computedIsNeeded:s,computedSliderSize:Math.round(o),computedSliderRatio:0,computedSliderPosition:0};let c=Math.round(Math.max(20,Math.floor(n*o/r))),l=(o-c)/(r-n),u=i*l;return{computedAvailableSize:Math.round(a),computedIsNeeded:s,computedSliderSize:Math.round(c),computedSliderRatio:l,computedSliderPosition:Math.round(u)}}_refreshComputedValues(){let t=e._computeValues(this._oppositeScrollbarSize,this._arrowSize,this._visibleSize,this._scrollSize,this._scrollPosition);this._computedAvailableSize=t.computedAvailableSize,this._computedIsNeeded=t.computedIsNeeded,this._computedSliderSize=t.computedSliderSize,this._computedSliderRatio=t.computedSliderRatio,this._computedSliderPosition=t.computedSliderPosition}getArrowSize(){return this._arrowSize}getScrollPosition(){return this._scrollPosition}getRectangleLargeSize(){return this._computedAvailableSize}getRectangleSmallSize(){return this._scrollbarSize}isNeeded(){return this._computedIsNeeded}getSliderSize(){return this._computedSliderSize}getSliderPosition(){return this._computedSliderPosition}getDesiredScrollPositionFromOffset(e){if(!this._computedIsNeeded)return 0;let t=e-this._arrowSize-this._computedSliderSize/2;return Math.round(t/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(e){if(!this._computedIsNeeded)return 0;let t=e-this._arrowSize,n=this._scrollPosition;return t<this._computedSliderPosition?n-=this._visibleSize:n+=this._visibleSize,n}getDesiredScrollPositionFromDelta(e){if(!this._computedIsNeeded)return 0;let t=this._computedSliderPosition+e;return Math.round(t/this._computedSliderRatio)}},ts=class extends $o{constructor(e,t,n){let r=e.getScrollDimensions(),i=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:n,scrollbarState:new es(t.horizontalHasArrows?t.arrowSize:0,t.horizontal===2?0:t.horizontalScrollbarSize,t.vertical===2?0:t.verticalScrollbarSize,r.width,r.scrollWidth,i.scrollLeft),visibility:t.horizontal,extraScrollbarClassName:`horizontal`,scrollable:e,scrollByPage:t.scrollByPage}),t.horizontalHasArrows)throw Error(`horizontalHasArrows is not supported in xterm.js`);this._createSlider(Math.floor((t.horizontalScrollbarSize-t.horizontalSliderSize)/2),0,void 0,t.horizontalSliderSize)}_updateSlider(e,t){this.slider.setWidth(e),this.slider.setLeft(t)}_renderDomNode(e,t){this.domNode.setWidth(e),this.domNode.setHeight(t),this.domNode.setLeft(0),this.domNode.setBottom(0)}onDidScroll(e){return this._shouldRender=this._onElementScrollSize(e.scrollWidth)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(e.scrollLeft)||this._shouldRender,this._shouldRender=this._onElementSize(e.width)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(e,t){return e}_sliderPointerPosition(e){return e.pageX}_sliderOrthogonalPointerPosition(e){return e.pageY}_updateScrollbarSize(e){this.slider.setHeight(e)}writeScrollPosition(e,t){e.scrollLeft=t}updateOptions(e){this.updateScrollbarSize(e.horizontal===2?0:e.horizontalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(e.vertical===2?0:e.verticalScrollbarSize),this._visibilityController.setVisibility(e.horizontal),this._scrollByPage=e.scrollByPage}},ns=class extends $o{constructor(e,t,n){let r=e.getScrollDimensions(),i=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:n,scrollbarState:new es(t.verticalHasArrows?t.arrowSize:0,t.vertical===2?0:t.verticalScrollbarSize,0,r.height,r.scrollHeight,i.scrollTop),visibility:t.vertical,extraScrollbarClassName:`vertical`,scrollable:e,scrollByPage:t.scrollByPage}),t.verticalHasArrows)throw Error(`horizontalHasArrows is not supported in xterm.js`);this._createSlider(0,Math.floor((t.verticalScrollbarSize-t.verticalSliderSize)/2),t.verticalSliderSize,void 0)}_updateSlider(e,t){this.slider.setHeight(e),this.slider.setTop(t)}_renderDomNode(e,t){this.domNode.setWidth(t),this.domNode.setHeight(e),this.domNode.setRight(0),this.domNode.setTop(0)}onDidScroll(e){return this._shouldRender=this._onElementScrollSize(e.scrollHeight)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(e.scrollTop)||this._shouldRender,this._shouldRender=this._onElementSize(e.height)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(e,t){return t}_sliderPointerPosition(e){return e.pageY}_sliderOrthogonalPointerPosition(e){return e.pageX}_updateScrollbarSize(e){this.slider.setWidth(e)}writeScrollPosition(e,t){e.scrollTop=t}updateOptions(e){this.updateScrollbarSize(e.vertical===2?0:e.verticalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(0),this._visibilityController.setVisibility(e.vertical),this._scrollByPage=e.scrollByPage}},rs=500,is=50,as=!0,os=class{constructor(e,t,n){this.timestamp=e,this.deltaX=t,this.deltaY=n,this.score=0}},ss=class{constructor(){this._capacity=5,this._memory=[],this._front=-1,this._rear=-1}isPhysicalMouseWheel(){if(this._front===-1&&this._rear===-1)return!1;let e=1,t=0,n=1,r=this._rear;do{let i=r===this._front?e:2**-n;if(e-=i,t+=this._memory[r].score*i,r===this._front)break;r=(this._capacity+r-1)%this._capacity,n++}while(1);return t<=.5}acceptStandardWheelEvent(e){if(oa){let t=na(fo(e.browserEvent));this.accept(Date.now(),e.deltaX*t,e.deltaY*t)}else this.accept(Date.now(),e.deltaX,e.deltaY)}accept(e,t,n){let r=null,i=new os(e,t,n);this._front===-1&&this._rear===-1?(this._memory[0]=i,this._front=0,this._rear=0):(r=this._memory[this._rear],this._rear=(this._rear+1)%this._capacity,this._rear===this._front&&(this._front=(this._front+1)%this._capacity),this._memory[this._rear]=i),i.score=this._computeScore(i,r)}_computeScore(e,t){if(Math.abs(e.deltaX)>0&&Math.abs(e.deltaY)>0)return 1;let n=.5;if((!this._isAlmostInt(e.deltaX)||!this._isAlmostInt(e.deltaY))&&(n+=.25),t){let r=Math.abs(e.deltaX),i=Math.abs(e.deltaY),a=Math.abs(t.deltaX),o=Math.abs(t.deltaY),s=Math.max(Math.min(r,a),1),c=Math.max(Math.min(i,o),1),l=Math.max(r,a),u=Math.max(i,o);l%s===0&&u%c===0&&(n-=.5)}return Math.min(Math.max(n,0),1)}_isAlmostInt(e){return Math.abs(Math.round(e)-e)<.01}};ss.INSTANCE=new ss;var cs=ss,ls=class extends Bo{constructor(e,t,n){super(),this._onScroll=this._register(new U),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new U),this.onWillScroll=this._onWillScroll.event,this._options=ds(t),this._scrollable=n,this._register(this._scrollable.onScroll(e=>{this._onWillScroll.fire(e),this._onDidScroll(e),this._onScroll.fire(e)}));let r={onMouseWheel:e=>this._onMouseWheel(e),onDragStart:()=>this._onDragStart(),onDragEnd:()=>this._onDragEnd()};this._verticalScrollbar=this._register(new ns(this._scrollable,this._options,r)),this._horizontalScrollbar=this._register(new ts(this._scrollable,this._options,r)),this._domNode=document.createElement(`div`),this._domNode.className=`xterm-scrollable-element `+this._options.className,this._domNode.setAttribute(`role`,`presentation`),this._domNode.style.position=`relative`,this._domNode.appendChild(e),this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode),this._domNode.appendChild(this._verticalScrollbar.domNode.domNode),this._options.useShadows?(this._leftShadowDomNode=Po(document.createElement(`div`)),this._leftShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=Po(document.createElement(`div`)),this._topShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=Po(document.createElement(`div`)),this._topLeftShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._topLeftShadowDomNode.domNode)):(this._leftShadowDomNode=null,this._topShadowDomNode=null,this._topLeftShadowDomNode=null),this._listenOnDomNode=this._options.listenOnDomNode||this._domNode,this._mouseWheelToDispose=[],this._setListeningToMouseWheel(this._options.handleMouseWheel),this.onmouseover(this._listenOnDomNode,e=>this._onMouseOver(e)),this.onmouseleave(this._listenOnDomNode,e=>this._onMouseLeave(e)),this._hideTimeout=this._register(new $a),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=ki(this._mouseWheelToDispose),super.dispose()}getDomNode(){return this._domNode}getOverviewRulerLayoutInfo(){return{parent:this._domNode,insertBefore:this._verticalScrollbar.domNode.domNode}}delegateVerticalScrollbarPointerDown(e){this._verticalScrollbar.delegatePointerDown(e)}getScrollDimensions(){return this._scrollable.getScrollDimensions()}setScrollDimensions(e){this._scrollable.setScrollDimensions(e,!1)}updateClassName(e){this._options.className=e,Sa&&(this._options.className+=` mac`),this._domNode.className=`xterm-scrollable-element `+this._options.className}updateOptions(e){typeof e.handleMouseWheel<`u`&&(this._options.handleMouseWheel=e.handleMouseWheel,this._setListeningToMouseWheel(this._options.handleMouseWheel)),typeof e.mouseWheelScrollSensitivity<`u`&&(this._options.mouseWheelScrollSensitivity=e.mouseWheelScrollSensitivity),typeof e.fastScrollSensitivity<`u`&&(this._options.fastScrollSensitivity=e.fastScrollSensitivity),typeof e.scrollPredominantAxis<`u`&&(this._options.scrollPredominantAxis=e.scrollPredominantAxis),typeof e.horizontal<`u`&&(this._options.horizontal=e.horizontal),typeof e.vertical<`u`&&(this._options.vertical=e.vertical),typeof e.horizontalScrollbarSize<`u`&&(this._options.horizontalScrollbarSize=e.horizontalScrollbarSize),typeof e.verticalScrollbarSize<`u`&&(this._options.verticalScrollbarSize=e.verticalScrollbarSize),typeof e.scrollByPage<`u`&&(this._options.scrollByPage=e.scrollByPage),this._horizontalScrollbar.updateOptions(this._options),this._verticalScrollbar.updateOptions(this._options),this._options.lazyRender||this._render()}setRevealOnScroll(e){this._revealOnScroll=e}delegateScrollFromMouseWheelEvent(e){this._onMouseWheel(new Ya(e))}_setListeningToMouseWheel(e){this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=ki(this._mouseWheelToDispose),e)&&this._mouseWheelToDispose.push(W(this._listenOnDomNode,jo.MOUSE_WHEEL,e=>{this._onMouseWheel(new Ya(e))},{passive:!1}))}_onMouseWheel(e){if(e.browserEvent?.defaultPrevented)return;let t=cs.INSTANCE;as&&t.acceptStandardWheelEvent(e);let n=!1;if(e.deltaY||e.deltaX){let r=e.deltaY*this._options.mouseWheelScrollSensitivity,i=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&i+r===0?i=r=0:Math.abs(r)>=Math.abs(i)?i=0:r=0),this._options.flipAxes&&([r,i]=[i,r]);let a=!Sa&&e.browserEvent&&e.browserEvent.shiftKey;(this._options.scrollYToX||a)&&!i&&(i=r,r=0),e.browserEvent&&e.browserEvent.altKey&&(i*=this._options.fastScrollSensitivity,r*=this._options.fastScrollSensitivity);let o=this._scrollable.getFutureScrollPosition(),s={};if(r){let e=is*r,t=o.scrollTop-(e<0?Math.floor(e):Math.ceil(e));this._verticalScrollbar.writeScrollPosition(s,t)}if(i){let e=is*i,t=o.scrollLeft-(e<0?Math.floor(e):Math.ceil(e));this._horizontalScrollbar.writeScrollPosition(s,t)}s=this._scrollable.validateScrollPosition(s),(o.scrollLeft!==s.scrollLeft||o.scrollTop!==s.scrollTop)&&(as&&this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(s):this._scrollable.setScrollPositionNow(s),n=!0)}let r=n;!r&&this._options.alwaysConsumeMouseWheel&&(r=!0),!r&&this._options.consumeMouseWheelIfScrollbarIsNeeded&&(this._verticalScrollbar.isNeeded()||this._horizontalScrollbar.isNeeded())&&(r=!0),r&&(e.preventDefault(),e.stopPropagation())}_onDidScroll(e){this._shouldRender=this._horizontalScrollbar.onDidScroll(e)||this._shouldRender,this._shouldRender=this._verticalScrollbar.onDidScroll(e)||this._shouldRender,this._options.useShadows&&(this._shouldRender=!0),this._revealOnScroll&&this._reveal(),this._options.lazyRender||this._render()}renderNow(){if(!this._options.lazyRender)throw Error("Please use `lazyRender` together with `renderNow`!");this._render()}_render(){if(this._shouldRender&&(this._shouldRender=!1,this._horizontalScrollbar.render(),this._verticalScrollbar.render(),this._options.useShadows)){let e=this._scrollable.getCurrentScrollPosition(),t=e.scrollTop>0,n=e.scrollLeft>0,r=n?` left`:``,i=t?` top`:``,a=n||t?` top-left-corner`:``;this._leftShadowDomNode.setClassName(`shadow${r}`),this._topShadowDomNode.setClassName(`shadow${i}`),this._topLeftShadowDomNode.setClassName(`shadow${a}${i}${r}`)}}_onDragStart(){this._isDragging=!0,this._reveal()}_onDragEnd(){this._isDragging=!1,this._hide()}_onMouseLeave(e){this._mouseIsOver=!1,this._hide()}_onMouseOver(e){this._mouseIsOver=!0,this._reveal()}_reveal(){this._verticalScrollbar.beginReveal(),this._horizontalScrollbar.beginReveal(),this._scheduleHide()}_hide(){!this._mouseIsOver&&!this._isDragging&&(this._verticalScrollbar.beginHide(),this._horizontalScrollbar.beginHide())}_scheduleHide(){!this._mouseIsOver&&!this._isDragging&&this._hideTimeout.cancelAndSet(()=>this._hide(),rs)}},us=class extends ls{constructor(e,t,n){super(e,t,n)}setScrollPosition(e){e.reuseAnimation?this._scrollable.setScrollPositionSmooth(e,e.reuseAnimation):this._scrollable.setScrollPositionNow(e)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}};function ds(e){let t={lazyRender:typeof e.lazyRender<`u`&&e.lazyRender,className:typeof e.className<`u`?e.className:``,useShadows:typeof e.useShadows<`u`?e.useShadows:!0,handleMouseWheel:typeof e.handleMouseWheel<`u`?e.handleMouseWheel:!0,flipAxes:typeof e.flipAxes<`u`&&e.flipAxes,consumeMouseWheelIfScrollbarIsNeeded:typeof e.consumeMouseWheelIfScrollbarIsNeeded<`u`&&e.consumeMouseWheelIfScrollbarIsNeeded,alwaysConsumeMouseWheel:typeof e.alwaysConsumeMouseWheel<`u`&&e.alwaysConsumeMouseWheel,scrollYToX:typeof e.scrollYToX<`u`&&e.scrollYToX,mouseWheelScrollSensitivity:typeof e.mouseWheelScrollSensitivity<`u`?e.mouseWheelScrollSensitivity:1,fastScrollSensitivity:typeof e.fastScrollSensitivity<`u`?e.fastScrollSensitivity:5,scrollPredominantAxis:typeof e.scrollPredominantAxis<`u`?e.scrollPredominantAxis:!0,mouseWheelSmoothScroll:typeof e.mouseWheelSmoothScroll<`u`?e.mouseWheelSmoothScroll:!0,arrowSize:typeof e.arrowSize<`u`?e.arrowSize:11,listenOnDomNode:typeof e.listenOnDomNode<`u`?e.listenOnDomNode:null,horizontal:typeof e.horizontal<`u`?e.horizontal:1,horizontalScrollbarSize:typeof e.horizontalScrollbarSize<`u`?e.horizontalScrollbarSize:10,horizontalSliderSize:typeof e.horizontalSliderSize<`u`?e.horizontalSliderSize:0,horizontalHasArrows:typeof e.horizontalHasArrows<`u`&&e.horizontalHasArrows,vertical:typeof e.vertical<`u`?e.vertical:1,verticalScrollbarSize:typeof e.verticalScrollbarSize<`u`?e.verticalScrollbarSize:10,verticalHasArrows:typeof e.verticalHasArrows<`u`&&e.verticalHasArrows,verticalSliderSize:typeof e.verticalSliderSize<`u`?e.verticalSliderSize:0,scrollByPage:typeof e.scrollByPage<`u`&&e.scrollByPage};return t.horizontalSliderSize=typeof e.horizontalSliderSize<`u`?e.horizontalSliderSize:t.horizontalScrollbarSize,t.verticalSliderSize=typeof e.verticalSliderSize<`u`?e.verticalSliderSize:t.verticalScrollbarSize,Sa&&(t.className+=` mac`),t}var fs=class extends H{constructor(e,t,n,r,i,a,o,s){super(),this._bufferService=n,this._optionsService=o,this._renderService=s,this._onRequestScrollLines=this._register(new U),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let c=this._register(new Wo({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:e=>Eo(r.window,e)}));this._register(this._optionsService.onSpecificOptionChange(`smoothScrollDuration`,()=>{c.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new us(t,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,...this._getChangeOptions()},c)),this._register(this._optionsService.onMultipleOptionChange([`scrollSensitivity`,`fastScrollSensitivity`,`overviewRuler`],()=>this._scrollableElement.updateOptions(this._getChangeOptions()))),this._register(i.onProtocolChange(e=>{this._scrollableElement.updateOptions({handleMouseWheel:!(e&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(Bi.runAndSubscribe(a.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=a.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(V(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=r.mainDocument.createElement(`style`),t.appendChild(this._styleElement),this._register(V(()=>this._styleElement.remove())),this._register(Bi.runAndSubscribe(a.onChangeColors,()=>{this._styleElement.textContent=[`.xterm .xterm-scrollable-element > .scrollbar > .slider {`,` background: ${a.colors.scrollbarSliderBackground.css};`,`}`,`.xterm .xterm-scrollable-element > .scrollbar > .slider:hover {`,` background: ${a.colors.scrollbarSliderHoverBackground.css};`,`}`,`.xterm .xterm-scrollable-element > .scrollbar > .slider.active {`,` background: ${a.colors.scrollbarSliderActiveBackground.css};`,`}`].join(`
15
- `)})),this._register(this._bufferService.onResize(()=>this.queueSync())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._latestYDisp=void 0,this.queueSync()})),this._register(this._bufferService.onScroll(()=>this._sync())),this._register(this._scrollableElement.onScroll(e=>this._handleScroll(e)))}scrollLines(e){let t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:t.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,t){t&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!t,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:this._optionsService.rawOptions.overviewRuler?.width||14}}queueSync(e){e!==void 0&&(this._latestYDisp=e),this._queuedAnimationFrame===void 0&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback(()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)}))}_sync(e=this._bufferService.buffer.ydisp){!this._renderService||this._isSyncing||(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),n=t-this._bufferService.buffer.ydisp;n!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(n)),this._isHandlingScroll=!1}};fs=R([z(2,Gr),z(3,ii),z(4,Kr),z(5,li),z(6,Zr),z(7,oi)],fs);var ps=class extends H{constructor(e,t,n,r,i){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=n,this._decorationService=r,this._renderService=i,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement(`div`),this._container.classList.add(`xterm-decoration-container`),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this._register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this._register(this._decorationService.onDecorationRemoved(e=>this._removeDecoration(e))),this._register(V(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(let e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){let t=this._coreBrowserService.mainDocument.createElement(`div`);t.classList.add(`xterm-decoration`),t.classList.toggle(`xterm-decoration-top-layer`,e?.options?.layer===`top`),t.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,t.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,t.style.top=`${(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height}px`,t.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let n=e.options.x??0;return n&&n>this._bufferService.cols&&(t.style.display=`none`),this._refreshXPosition(e,t),t}_refreshStyle(e){let t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display=`none`,e.onRenderEmitter.fire(e.element));else{let n=this._decorationElements.get(e);n||(n=this._createElement(e),e.element=n,this._decorationElements.set(e,n),this._container.appendChild(n),e.onDispose(()=>{this._decorationElements.delete(e),n.remove()})),n.style.display=this._altBufferIsActive?`none`:`block`,this._altBufferIsActive||(n.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,n.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,n.style.top=`${t*this._renderService.dimensions.css.cell.height}px`,n.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),e.onRenderEmitter.fire(n)}}_refreshXPosition(e,t=e.element){if(!t)return;let n=e.options.x??0;(e.options.anchor||`left`)===`right`?t.style.right=n?`${n*this._renderService.dimensions.css.cell.width}px`:``:t.style.left=n?`${n*this._renderService.dimensions.css.cell.width}px`:``}_removeDecoration(e){this._decorationElements.get(e)?.remove(),this._decorationElements.delete(e),e.dispose()}};ps=R([z(1,Gr),z(2,ii),z(3,ei),z(4,oi)],ps);var ms=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(e){if(e.options.overviewRulerOptions){for(let t of this._zones)if(t.color===e.options.overviewRulerOptions.color&&t.position===e.options.overviewRulerOptions.position){if(this._lineIntersectsZone(t,e.marker.line))return;if(this._lineAdjacentToZone(t,e.marker.line,e.options.overviewRulerOptions.position)){this._addLineToZone(t,e.marker.line);return}}if(this._zonePoolIndex<this._zonePool.length){this._zonePool[this._zonePoolIndex].color=e.options.overviewRulerOptions.color,this._zonePool[this._zonePoolIndex].position=e.options.overviewRulerOptions.position,this._zonePool[this._zonePoolIndex].startBufferLine=e.marker.line,this._zonePool[this._zonePoolIndex].endBufferLine=e.marker.line,this._zones.push(this._zonePool[this._zonePoolIndex++]);return}this._zones.push({color:e.options.overviewRulerOptions.color,position:e.options.overviewRulerOptions.position,startBufferLine:e.marker.line,endBufferLine:e.marker.line}),this._zonePool.push(this._zones[this._zones.length-1]),this._zonePoolIndex++}}setPadding(e){this._linePadding=e}_lineIntersectsZone(e,t){return t>=e.startBufferLine&&t<=e.endBufferLine}_lineAdjacentToZone(e,t,n){return t>=e.startBufferLine-this._linePadding[n||`full`]&&t<=e.endBufferLine+this._linePadding[n||`full`]}_addLineToZone(e,t){e.startBufferLine=Math.min(e.startBufferLine,t),e.endBufferLine=Math.max(e.endBufferLine,t)}},hs={full:0,left:0,center:0,right:0},gs={full:0,left:0,center:0,right:0},_s={full:0,left:0,center:0,right:0},vs=class extends H{constructor(e,t,n,r,i,a,o,s){super(),this._viewportElement=e,this._screenElement=t,this._bufferService=n,this._decorationService=r,this._renderService=i,this._optionsService=a,this._themeService=o,this._coreBrowserService=s,this._colorZoneStore=new ms,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=this._coreBrowserService.mainDocument.createElement(`canvas`),this._canvas.classList.add(`xterm-decoration-overview-ruler`),this._refreshCanvasDimensions(),this._viewportElement.parentElement?.insertBefore(this._canvas,this._viewportElement),this._register(V(()=>this._canvas?.remove()));let c=this._canvas.getContext(`2d`);if(c)this._ctx=c;else throw Error(`Ctx cannot be null`);this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this._register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0))),this._register(this._renderService.onRenderedViewportChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?`none`:`block`})),this._register(this._bufferService.onScroll(()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})),this._register(this._renderService.onRender(()=>{(!this._containerHeight||this._containerHeight!==this._screenElement.clientHeight)&&(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh(!0))),this._register(this._optionsService.onSpecificOptionChange(`overviewRuler`,()=>this._queueRefresh(!0))),this._register(this._themeService.onChangeColors(()=>this._queueRefresh())),this._queueRefresh(!0)}get _width(){return this._optionsService.options.overviewRuler?.width||0}_refreshDrawConstants(){let e=Math.floor((this._canvas.width-1)/3),t=Math.ceil((this._canvas.width-1)/3);gs.full=this._canvas.width,gs.left=e,gs.center=t,gs.right=e,this._refreshDrawHeightConstants(),_s.full=1,_s.left=1,_s.center=1+gs.left,_s.right=1+gs.left+gs.center}_refreshDrawHeightConstants(){hs.full=Math.round(2*this._coreBrowserService.dpr);let e=this._canvas.height/this._bufferService.buffer.lines.length,t=Math.round(Math.max(Math.min(e,12),6)*this._coreBrowserService.dpr);hs.left=t,hs.center=t,hs.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*hs.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*hs.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*hs.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*hs.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(let e of this._decorationService.decorations)this._colorZoneStore.addDecoration(e);this._ctx.lineWidth=1,this._renderRulerOutline();let e=this._colorZoneStore.zones;for(let t of e)t.position!==`full`&&this._renderColorZone(t);for(let t of e)t.position===`full`&&this._renderColorZone(t);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderRulerOutline(){this._ctx.fillStyle=this._themeService.colors.overviewRulerBorder.css,this._ctx.fillRect(0,0,1,this._canvas.height),this._optionsService.rawOptions.overviewRuler.showTopBorder&&this._ctx.fillRect(1,0,this._canvas.width-1,1),this._optionsService.rawOptions.overviewRuler.showBottomBorder&&this._ctx.fillRect(1,this._canvas.height-1,this._canvas.width-1,this._canvas.height)}_renderColorZone(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(_s[e.position||`full`],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-hs[e.position||`full`]/2),gs[e.position||`full`],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+hs[e.position||`full`]))}_queueRefresh(e,t){this._shouldUpdateDimensions=e||this._shouldUpdateDimensions,this._shouldUpdateAnchor=t||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};vs=R([z(2,Gr),z(3,ei),z(4,oi),z(5,Zr),z(6,li),z(7,ii)],vs);var G;(e=>(e.NUL=`\0`,e.SOH=``,e.STX=``,e.ETX=``,e.EOT=``,e.ENQ=``,e.ACK=``,e.BEL=`\x07`,e.BS=`\b`,e.HT=` `,e.LF=`
16
- `,e.VT=`\v`,e.FF=`\f`,e.CR=`\r`,e.SO=``,e.SI=``,e.DLE=``,e.DC1=``,e.DC2=``,e.DC3=``,e.DC4=``,e.NAK=``,e.SYN=``,e.ETB=``,e.CAN=``,e.EM=``,e.SUB=``,e.ESC=`\x1B`,e.FS=``,e.GS=``,e.RS=``,e.US=``,e.SP=` `,e.DEL=``))(G||={});var ys;(e=>(e.PAD=`€`,e.HOP=``,e.BPH=`‚`,e.NBH=`ƒ`,e.IND=`„`,e.NEL=`…`,e.SSA=`†`,e.ESA=`‡`,e.HTS=`ˆ`,e.HTJ=`‰`,e.VTS=`Š`,e.PLD=`‹`,e.PLU=`Œ`,e.RI=``,e.SS2=`Ž`,e.SS3=``,e.DCS=``,e.PU1=`‘`,e.PU2=`’`,e.STS=`“`,e.CCH=`”`,e.MW=`•`,e.SPA=`–`,e.EPA=`—`,e.SOS=`˜`,e.SGCI=`™`,e.SCI=`š`,e.CSI=`›`,e.ST=`œ`,e.OSC=``,e.PM=`ž`,e.APC=`Ÿ`))(ys||={});var bs;(e=>e.ST=`${G.ESC}\\`)(bs||={});var xs=class{constructor(e,t,n,r,i,a){this._textarea=e,this._compositionView=t,this._bufferService=n,this._optionsService=r,this._coreService=i,this._renderService=a,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=``}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent=``,this._dataAlreadySent=``,this._compositionView.classList.add(`active`)}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(e.keyCode===20||e.keyCode===229||e.keyCode===16||e.keyCode===17||e.keyCode===18)return!1;this._finalizeComposition(!1)}return e.keyCode!==229||(this._handleAnyTextareaChanges(),!1)}_finalizeComposition(e){if(this._compositionView.classList.remove(`active`),this._isComposing=!1,e){let e={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=!1;let t;e.start+=this._dataAlreadySent.length,t=this._isComposing?this._textarea.value.substring(e.start,this._compositionPosition.start):this._textarea.value.substring(e.start),t.length>0&&this._coreService.triggerDataEvent(t,!0)}},0)}else{this._isSendingComposition=!1;let e=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(e,!0)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,n=t.replace(e,``);this._dataAlreadySent=n,t.length>e.length?this._coreService.triggerDataEvent(n,!0):t.length<e.length?this._coreService.triggerDataEvent(`${G.DEL}`,!0):t.length===e.length&&t!==e&&this._coreService.triggerDataEvent(t,!0)}},0)}updateCompositionElements(e){if(this._isComposing){if(this._bufferService.buffer.isCursorInViewport){let e=Math.min(this._bufferService.buffer.x,this._bufferService.cols-1),t=this._renderService.dimensions.css.cell.height,n=this._bufferService.buffer.y*this._renderService.dimensions.css.cell.height,r=e*this._renderService.dimensions.css.cell.width;this._compositionView.style.left=r+`px`,this._compositionView.style.top=n+`px`,this._compositionView.style.height=t+`px`,this._compositionView.style.lineHeight=t+`px`,this._compositionView.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._compositionView.style.fontSize=this._optionsService.rawOptions.fontSize+`px`;let i=this._compositionView.getBoundingClientRect();this._textarea.style.left=r+`px`,this._textarea.style.top=n+`px`,this._textarea.style.width=Math.max(i.width,1)+`px`,this._textarea.style.height=Math.max(i.height,1)+`px`,this._textarea.style.lineHeight=i.height+`px`}e||setTimeout(()=>this.updateCompositionElements(!0),0)}}};xs=R([z(2,Gr),z(3,Zr),z(4,qr),z(5,oi)],xs);var Ss=0,Cs=0,ws=0,Ts=0,Es={css:`#00000000`,rgba:0},Ds;(e=>{function t(e,t,n,r){return r===void 0?`#${Ms(e)}${Ms(t)}${Ms(n)}`:`#${Ms(e)}${Ms(t)}${Ms(n)}${Ms(r)}`}e.toCss=t;function n(e,t,n,r=255){return(e<<24|t<<16|n<<8|r)>>>0}e.toRgba=n;function r(t,n,r,i){return{css:e.toCss(t,n,r,i),rgba:e.toRgba(t,n,r,i)}}e.toColor=r})(Ds||={});var Os;(e=>{function t(e,t){if(Ts=(t.rgba&255)/255,Ts===1)return{css:t.css,rgba:t.rgba};let n=t.rgba>>24&255,r=t.rgba>>16&255,i=t.rgba>>8&255,a=e.rgba>>24&255,o=e.rgba>>16&255,s=e.rgba>>8&255;return Ss=a+Math.round((n-a)*Ts),Cs=o+Math.round((r-o)*Ts),ws=s+Math.round((i-s)*Ts),{css:Ds.toCss(Ss,Cs,ws),rgba:Ds.toRgba(Ss,Cs,ws)}}e.blend=t;function n(e){return(e.rgba&255)==255}e.isOpaque=n;function r(e,t,n){let r=js.ensureContrastRatio(e.rgba,t.rgba,n);if(r)return Ds.toColor(r>>24&255,r>>16&255,r>>8&255)}e.ensureContrastRatio=r;function i(e){let t=(e.rgba|255)>>>0;return[Ss,Cs,ws]=js.toChannels(t),{css:Ds.toCss(Ss,Cs,ws),rgba:t}}e.opaque=i;function a(e,t){return Ts=Math.round(t*255),[Ss,Cs,ws]=js.toChannels(e.rgba),{css:Ds.toCss(Ss,Cs,ws,Ts),rgba:Ds.toRgba(Ss,Cs,ws,Ts)}}e.opacity=a;function o(e,t){return Ts=e.rgba&255,a(e,Ts*t/255)}e.multiplyOpacity=o;function s(e){return[e.rgba>>24&255,e.rgba>>16&255,e.rgba>>8&255]}e.toColorRGB=s})(Os||={});var ks;(e=>{let t,n;try{let e=document.createElement(`canvas`);e.width=1,e.height=1;let r=e.getContext(`2d`,{willReadFrequently:!0});r&&(t=r,t.globalCompositeOperation=`copy`,n=t.createLinearGradient(0,0,1,1))}catch{}function r(e){if(e.match(/#[\da-f]{3,8}/i))switch(e.length){case 4:return Ss=parseInt(e.slice(1,2).repeat(2),16),Cs=parseInt(e.slice(2,3).repeat(2),16),ws=parseInt(e.slice(3,4).repeat(2),16),Ds.toColor(Ss,Cs,ws);case 5:return Ss=parseInt(e.slice(1,2).repeat(2),16),Cs=parseInt(e.slice(2,3).repeat(2),16),ws=parseInt(e.slice(3,4).repeat(2),16),Ts=parseInt(e.slice(4,5).repeat(2),16),Ds.toColor(Ss,Cs,ws,Ts);case 7:return{css:e,rgba:(parseInt(e.slice(1),16)<<8|255)>>>0};case 9:return{css:e,rgba:parseInt(e.slice(1),16)>>>0}}let r=e.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(r)return Ss=parseInt(r[1]),Cs=parseInt(r[2]),ws=parseInt(r[3]),Ts=Math.round((r[5]===void 0?1:parseFloat(r[5]))*255),Ds.toColor(Ss,Cs,ws,Ts);if(!t||!n||(t.fillStyle=n,t.fillStyle=e,typeof t.fillStyle!=`string`)||(t.fillRect(0,0,1,1),[Ss,Cs,ws,Ts]=t.getImageData(0,0,1,1).data,Ts!==255))throw Error(`css.toColor: Unsupported css format`);return{rgba:Ds.toRgba(Ss,Cs,ws,Ts),css:e}}e.toColor=r})(ks||={});var As;(e=>{function t(e){return n(e>>16&255,e>>8&255,e&255)}e.relativeLuminance=t;function n(e,t,n){let r=e/255,i=t/255,a=n/255,o=r<=.03928?r/12.92:((r+.055)/1.055)**2.4,s=i<=.03928?i/12.92:((i+.055)/1.055)**2.4,c=a<=.03928?a/12.92:((a+.055)/1.055)**2.4;return o*.2126+s*.7152+c*.0722}e.relativeLuminance2=n})(As||={});var js;(e=>{function t(e,t){if(Ts=(t&255)/255,Ts===1)return t;let n=t>>24&255,r=t>>16&255,i=t>>8&255,a=e>>24&255,o=e>>16&255,s=e>>8&255;return Ss=a+Math.round((n-a)*Ts),Cs=o+Math.round((r-o)*Ts),ws=s+Math.round((i-s)*Ts),Ds.toRgba(Ss,Cs,ws)}e.blend=t;function n(e,t,n){let a=As.relativeLuminance(e>>8),o=As.relativeLuminance(t>>8);if(Ns(a,o)<n){if(o<a){let o=r(e,t,n),s=Ns(a,As.relativeLuminance(o>>8));if(s<n){let r=i(e,t,n);return s>Ns(a,As.relativeLuminance(r>>8))?o:r}return o}let s=i(e,t,n),c=Ns(a,As.relativeLuminance(s>>8));if(c<n){let i=r(e,t,n);return c>Ns(a,As.relativeLuminance(i>>8))?s:i}return s}}e.ensureContrastRatio=n;function r(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,l=Ns(As.relativeLuminance2(o,s,c),As.relativeLuminance2(r,i,a));for(;l<n&&(o>0||s>0||c>0);)o-=Math.max(0,Math.ceil(o*.1)),s-=Math.max(0,Math.ceil(s*.1)),c-=Math.max(0,Math.ceil(c*.1)),l=Ns(As.relativeLuminance2(o,s,c),As.relativeLuminance2(r,i,a));return(o<<24|s<<16|c<<8|255)>>>0}e.reduceLuminance=r;function i(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,l=Ns(As.relativeLuminance2(o,s,c),As.relativeLuminance2(r,i,a));for(;l<n&&(o<255||s<255||c<255);)o=Math.min(255,o+Math.ceil((255-o)*.1)),s=Math.min(255,s+Math.ceil((255-s)*.1)),c=Math.min(255,c+Math.ceil((255-c)*.1)),l=Ns(As.relativeLuminance2(o,s,c),As.relativeLuminance2(r,i,a));return(o<<24|s<<16|c<<8|255)>>>0}e.increaseLuminance=i;function a(e){return[e>>24&255,e>>16&255,e>>8&255,e&255]}e.toChannels=a})(js||={});function Ms(e){let t=e.toString(16);return t.length<2?`0`+t:t}function Ns(e,t){return e<t?(t+.05)/(e+.05):(e+.05)/(t+.05)}var Ps=class extends Ir{constructor(e,t,n){super(),this.content=0,this.combinedData=``,this.fg=e.fg,this.bg=e.bg,this.combinedData=t,this._width=n}isCombined(){return 2097152}getWidth(){return this._width}getChars(){return this.combinedData}getCode(){return 2097151}setFromCharData(e){throw Error(`not implemented`)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},Fs=class{constructor(e){this._bufferService=e,this._characterJoiners=[],this._nextCharacterJoinerId=0,this._workCell=new Rr}register(e){let t={id:this._nextCharacterJoinerId++,handler:e};return this._characterJoiners.push(t),t.id}deregister(e){for(let t=0;t<this._characterJoiners.length;t++)if(this._characterJoiners[t].id===e)return this._characterJoiners.splice(t,1),!0;return!1}getJoinedCharacters(e){if(this._characterJoiners.length===0)return[];let t=this._bufferService.buffer.lines.get(e);if(!t||t.length===0)return[];let n=[],r=t.translateToString(!0),i=0,a=0,o=0,s=t.getFg(0),c=t.getBg(0);for(let e=0;e<t.getTrimmedLength();e++)if(t.loadCell(e,this._workCell),this._workCell.getWidth()!==0){if(this._workCell.fg!==s||this._workCell.bg!==c){if(e-i>1){let e=this._getJoinedRanges(r,o,a,t,i);for(let t=0;t<e.length;t++)n.push(e[t])}i=e,o=a,s=this._workCell.fg,c=this._workCell.bg}a+=this._workCell.getChars().length||Fr.length}if(this._bufferService.cols-i>1){let e=this._getJoinedRanges(r,o,a,t,i);for(let t=0;t<e.length;t++)n.push(e[t])}return n}_getJoinedRanges(e,t,n,r,i){let a=e.substring(t,n),o=[];try{o=this._characterJoiners[0].handler(a)}catch(e){console.error(e)}for(let e=1;e<this._characterJoiners.length;e++)try{let t=this._characterJoiners[e].handler(a);for(let e=0;e<t.length;e++)Fs._mergeRanges(o,t[e])}catch(e){console.error(e)}return this._stringRangesToCellRanges(o,r,i),o}_stringRangesToCellRanges(e,t,n){let r=0,i=!1,a=0,o=e[r];if(o){for(let s=n;s<this._bufferService.cols;s++){let n=t.getWidth(s),c=t.getString(s).length||Fr.length;if(n!==0){if(!i&&o[0]<=a&&(o[0]=s,i=!0),o[1]<=a){if(o[1]=s,o=e[++r],!o)break;o[0]<=a?(o[0]=s,i=!0):i=!1}a+=c}}o&&(o[1]=this._bufferService.cols)}}static _mergeRanges(e,t){let n=!1;for(let r=0;r<e.length;r++){let i=e[r];if(n){if(t[1]<=i[0])return e[r-1][1]=t[1],e;if(t[1]<=i[1])return e[r-1][1]=Math.max(t[1],i[1]),e.splice(r,1),e;e.splice(r,1),r--}else{if(t[1]<=i[0])return e.splice(r,0,t),e;if(t[1]<=i[1])return i[0]=Math.min(t[0],i[0]),e;t[0]<i[1]&&(i[0]=Math.min(t[0],i[0]),n=!0);continue}}return n?e[e.length-1][1]=t[1]:e.push(t),e}};Fs=R([z(0,Gr)],Fs);function Is(e){return 57508<=e&&e<=57558}function Ls(e){return 9472<=e&&e<=9631}function Rs(e){return Is(e)||Ls(e)}function zs(){return{css:{canvas:Bs(),cell:Bs()},device:{canvas:Bs(),cell:Bs(),char:{width:0,height:0,left:0,top:0}}}}function Bs(){return{width:0,height:0}}var Vs=class{constructor(e,t,n,r,i,a,o){this._document=e,this._characterJoinerService=t,this._optionsService=n,this._coreBrowserService=r,this._coreService=i,this._decorationService=a,this._themeService=o,this._workCell=new Rr,this._columnSelectMode=!1,this.defaultSpacing=0}handleSelectionChanged(e,t,n){this._selectionStart=e,this._selectionEnd=t,this._columnSelectMode=n}createRow(e,t,n,r,i,a,o,s,c,l,u){let d=[],f=this._characterJoinerService.getJoinedCharacters(t),p=this._themeService.colors,m=e.getNoBgTrimmedLength();n&&m<a+1&&(m=a+1);let h,g=0,_=``,v=0,ee=0,y=0,b=0,x=!1,S=0,C=!1,w=0,T=0,te=[],E=l!==-1&&u!==-1;for(let D=0;D<m;D++){e.loadCell(D,this._workCell);let m=this._workCell.getWidth();if(m===0)continue;let ne=!1,re=D>=T,ie=D,O=this._workCell;if(f.length>0&&D===f[0][0]&&re){let r=f.shift(),i=this._isCellInSelection(r[0],t);for(v=r[0]+1;v<r[1];v++)re&&=i===this._isCellInSelection(v,t);re&&=!n||a<r[0]||a>=r[1],re?(ne=!0,O=new Ps(this._workCell,e.translateToString(!0,r[0],r[1]),r[1]-r[0]),ie=r[1]-1,m=O.getWidth()):T=r[1]}let ae=this._isCellInSelection(D,t),oe=n&&D===a,se=E&&D>=l&&D<=u,ce=!1;this._decorationService.forEachDecorationAtCell(D,t,void 0,e=>{ce=!0});let le=O.getChars()||Fr;if(le===` `&&(O.isUnderline()||O.isOverline())&&(le=`\xA0`),w=m*s-c.get(le,O.isBold(),O.isItalic()),!h)h=this._document.createElement(`span`);else if(g&&(ae&&C||!ae&&!C&&O.bg===ee)&&(ae&&C&&p.selectionForeground||O.fg===y)&&O.extended.ext===b&&se===x&&w===S&&!oe&&!ne&&!ce&&re){O.isInvisible()?_+=Fr:_+=le,g++;continue}else g&&(h.textContent=_),h=this._document.createElement(`span`),g=0,_=``;if(ee=O.bg,y=O.fg,b=O.extended.ext,x=se,S=w,C=ae,ne&&a>=D&&a<=ie&&(a=D),!this._coreService.isCursorHidden&&oe&&this._coreService.isCursorInitialized){if(te.push(`xterm-cursor`),this._coreBrowserService.isFocused)o&&te.push(`xterm-cursor-blink`),te.push(r===`bar`?`xterm-cursor-bar`:r===`underline`?`xterm-cursor-underline`:`xterm-cursor-block`);else if(i)switch(i){case`outline`:te.push(`xterm-cursor-outline`);break;case`block`:te.push(`xterm-cursor-block`);break;case`bar`:te.push(`xterm-cursor-bar`);break;case`underline`:te.push(`xterm-cursor-underline`)}}if(O.isBold()&&te.push(`xterm-bold`),O.isItalic()&&te.push(`xterm-italic`),O.isDim()&&te.push(`xterm-dim`),_=O.isInvisible()?Fr:O.getChars()||Fr,O.isUnderline()&&(te.push(`xterm-underline-${O.extended.underlineStyle}`),_===` `&&(_=`\xA0`),!O.isUnderlineColorDefault())){if(O.isUnderlineColorRGB())h.style.textDecorationColor=`rgb(${Ir.toColorRGB(O.getUnderlineColor()).join(`,`)})`;else{let e=O.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&O.isBold()&&e<8&&(e+=8),h.style.textDecorationColor=p.ansi[e].css}}O.isOverline()&&(te.push(`xterm-overline`),_===` `&&(_=`\xA0`)),O.isStrikethrough()&&te.push(`xterm-strikethrough`),se&&(h.style.textDecoration=`underline`);let ue=O.getFgColor(),de=O.getFgColorMode(),fe=O.getBgColor(),pe=O.getBgColorMode(),k=!!O.isInverse();if(k){let e=ue;ue=fe,fe=e;let t=de;de=pe,pe=t}let me,he,ge=!1;this._decorationService.forEachDecorationAtCell(D,t,void 0,e=>{e.options.layer!==`top`&&ge||(e.backgroundColorRGB&&(pe=50331648,fe=e.backgroundColorRGB.rgba>>8&16777215,me=e.backgroundColorRGB),e.foregroundColorRGB&&(de=50331648,ue=e.foregroundColorRGB.rgba>>8&16777215,he=e.foregroundColorRGB),ge=e.options.layer===`top`)}),!ge&&ae&&(me=this._coreBrowserService.isFocused?p.selectionBackgroundOpaque:p.selectionInactiveBackgroundOpaque,fe=me.rgba>>8&16777215,pe=50331648,ge=!0,p.selectionForeground&&(de=50331648,ue=p.selectionForeground.rgba>>8&16777215,he=p.selectionForeground)),ge&&te.push(`xterm-decoration-top`);let _e;switch(pe){case 16777216:case 33554432:_e=p.ansi[fe],te.push(`xterm-bg-${fe}`);break;case 50331648:_e=Ds.toColor(fe>>16,fe>>8&255,fe&255),this._addStyle(h,`background-color:#${Hs((fe>>>0).toString(16),`0`,6)}`);break;default:k?(_e=p.foreground,te.push(`xterm-bg-257`)):_e=p.background}switch(me||O.isDim()&&(me=Os.multiplyOpacity(_e,.5)),de){case 16777216:case 33554432:O.isBold()&&ue<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(ue+=8),this._applyMinimumContrast(h,_e,p.ansi[ue],O,me,void 0)||te.push(`xterm-fg-${ue}`);break;case 50331648:let e=Ds.toColor(ue>>16&255,ue>>8&255,ue&255);this._applyMinimumContrast(h,_e,e,O,me,he)||this._addStyle(h,`color:#${Hs(ue.toString(16),`0`,6)}`);break;default:this._applyMinimumContrast(h,_e,p.foreground,O,me,he)||k&&te.push(`xterm-fg-257`)}te.length&&=(h.className=te.join(` `),0),!oe&&!ne&&!ce&&re?g++:h.textContent=_,w!==this.defaultSpacing&&(h.style.letterSpacing=`${w}px`),d.push(h),D=ie}return h&&g&&(h.textContent=_),d}_applyMinimumContrast(e,t,n,r,i,a){if(this._optionsService.rawOptions.minimumContrastRatio===1||Rs(r.getCode()))return!1;let o=this._getContrastCache(r),s;if(!i&&!a&&(s=o.getColor(t.rgba,n.rgba)),s===void 0){let e=this._optionsService.rawOptions.minimumContrastRatio/(r.isDim()?2:1);s=Os.ensureContrastRatio(i||t,a||n,e),o.setColor((i||t).rgba,(a||n).rgba,s??null)}return s?(this._addStyle(e,`color:${s.css}`),!0):!1}_getContrastCache(e){return e.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(e,t){e.setAttribute(`style`,`${e.getAttribute(`style`)||``}${t};`)}_isCellInSelection(e,t){let n=this._selectionStart,r=this._selectionEnd;return!n||!r?!1:this._columnSelectMode?n[0]<=r[0]?e>=n[0]&&t>=n[1]&&e<r[0]&&t<=r[1]:e<n[0]&&t>=n[1]&&e>=r[0]&&t<=r[1]:t>n[1]&&t<r[1]||n[1]===r[1]&&t===n[1]&&e>=n[0]&&e<r[0]||n[1]<r[1]&&t===r[1]&&e<r[0]||n[1]<r[1]&&t===n[1]&&e>=n[0]}};Vs=R([z(1,ci),z(2,Zr),z(3,ii),z(4,qr),z(5,ei),z(6,li)],Vs);function Hs(e,t,n){for(;e.length<n;)e=t+e;return e}var Us=class{constructor(e,t){this._flat=new Float32Array(256),this._font=``,this._fontSize=0,this._weight=`normal`,this._weightBold=`bold`,this._measureElements=[],this._container=e.createElement(`div`),this._container.classList.add(`xterm-width-cache-measure-container`),this._container.setAttribute(`aria-hidden`,`true`),this._container.style.whiteSpace=`pre`,this._container.style.fontKerning=`none`;let n=e.createElement(`span`);n.classList.add(`xterm-char-measure-element`);let r=e.createElement(`span`);r.classList.add(`xterm-char-measure-element`),r.style.fontWeight=`bold`;let i=e.createElement(`span`);i.classList.add(`xterm-char-measure-element`),i.style.fontStyle=`italic`;let a=e.createElement(`span`);a.classList.add(`xterm-char-measure-element`),a.style.fontWeight=`bold`,a.style.fontStyle=`italic`,this._measureElements=[n,r,i,a],this._container.appendChild(n),this._container.appendChild(r),this._container.appendChild(i),this._container.appendChild(a),t.appendChild(this._container),this.clear()}dispose(){this._container.remove(),this._measureElements.length=0,this._holey=void 0}clear(){this._flat.fill(-9999),this._holey=new Map}setFont(e,t,n,r){e===this._font&&t===this._fontSize&&n===this._weight&&r===this._weightBold||(this._font=e,this._fontSize=t,this._weight=n,this._weightBold=r,this._container.style.fontFamily=this._font,this._container.style.fontSize=`${this._fontSize}px`,this._measureElements[0].style.fontWeight=`${n}`,this._measureElements[1].style.fontWeight=`${r}`,this._measureElements[2].style.fontWeight=`${n}`,this._measureElements[3].style.fontWeight=`${r}`,this.clear())}get(e,t,n){let r=0;if(!t&&!n&&e.length===1&&(r=e.charCodeAt(0))<256){if(this._flat[r]!==-9999)return this._flat[r];let t=this._measure(e,0);return t>0&&(this._flat[r]=t),t}let i=e;t&&(i+=`B`),n&&(i+=`I`);let a=this._holey.get(i);if(a===void 0){let r=0;t&&(r|=1),n&&(r|=2),a=this._measure(e,r),a>0&&this._holey.set(i,a)}return a}_measure(e,t){let n=this._measureElements[t];return n.textContent=e.repeat(32),n.offsetWidth/32}},Ws=class{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(e,t,n,r=!1){if(this.selectionStart=t,this.selectionEnd=n,!t||!n||t[0]===n[0]&&t[1]===n[1]){this.clear();return}let i=e.buffers.active.ydisp,a=t[1]-i,o=n[1]-i,s=Math.max(a,0),c=Math.min(o,e.rows-1);s>=e.rows||c<0?this.clear():(this.hasSelection=!0,this.columnSelectMode=r,this.viewportStartRow=a,this.viewportEndRow=o,this.viewportCappedStartRow=s,this.viewportCappedEndRow=c,this.startCol=t[0],this.endCol=n[0])}isCellSelected(e,t,n){return this.hasSelection?(n-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&n>=this.viewportCappedStartRow&&t<this.endCol&&n<=this.viewportCappedEndRow:t<this.startCol&&n>=this.viewportCappedStartRow&&t>=this.endCol&&n<=this.viewportCappedEndRow:n>this.viewportStartRow&&n<this.viewportEndRow||this.viewportStartRow===this.viewportEndRow&&n===this.viewportStartRow&&t>=this.startCol&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&n===this.viewportEndRow&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&n===this.viewportStartRow&&t>=this.startCol):!1}};function Gs(){return new Ws}var Ks=`xterm-dom-renderer-owner-`,qs=`xterm-rows`,Js=`xterm-fg-`,Ys=`xterm-bg-`,Xs=`xterm-focus`,Zs=`xterm-selection`,Qs=1,$s=class extends H{constructor(e,t,n,r,i,a,o,s,c,l,u,d,f,p){super(),this._terminal=e,this._document=t,this._element=n,this._screenElement=r,this._viewportElement=i,this._helperContainer=a,this._linkifier2=o,this._charSizeService=c,this._optionsService=l,this._bufferService=u,this._coreService=d,this._coreBrowserService=f,this._themeService=p,this._terminalClass=Qs++,this._rowElements=[],this._selectionRenderModel=Gs(),this.onRequestRedraw=this._register(new U).event,this._rowContainer=this._document.createElement(`div`),this._rowContainer.classList.add(qs),this._rowContainer.style.lineHeight=`normal`,this._rowContainer.setAttribute(`aria-hidden`,`true`),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement(`div`),this._selectionContainer.classList.add(Zs),this._selectionContainer.setAttribute(`aria-hidden`,`true`),this.dimensions=zs(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(e=>this._injectCss(e))),this._injectCss(this._themeService.colors),this._rowFactory=s.createInstance(Vs,document),this._element.classList.add(Ks+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(e=>this._handleLinkHover(e))),this._register(this._linkifier2.onHideLinkUnderline(e=>this._handleLinkLeave(e))),this._register(V(()=>{this._element.classList.remove(Ks+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new Us(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){let e=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*e,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*e),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/e),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/e),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(let e of this._rowElements)e.style.width=`${this.dimensions.css.canvas.width}px`,e.style.height=`${this.dimensions.css.cell.height}px`,e.style.lineHeight=`${this.dimensions.css.cell.height}px`,e.style.overflow=`hidden`;this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement(`style`),this._screenElement.appendChild(this._dimensionsStyleElement));let t=`${this._terminalSelector} .${qs} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=t,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(e){this._themeStyleElement||(this._themeStyleElement=this._document.createElement(`style`),this._screenElement.appendChild(this._themeStyleElement));let t=`${this._terminalSelector} .${qs} { pointer-events: none; color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;t+=`${this._terminalSelector} .${qs} .xterm-dim { color: ${Os.multiplyOpacity(e.foreground,.5).css};}`,t+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;let n=`blink_underline_${this._terminalClass}`,r=`blink_bar_${this._terminalClass}`,i=`blink_block_${this._terminalClass}`;t+=`@keyframes ${n} { 50% { border-bottom-style: hidden; }}`,t+=`@keyframes ${r} { 50% { box-shadow: none; }}`,t+=`@keyframes ${i} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${qs}.${Xs} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${n} 1s step-end infinite;}${this._terminalSelector} .${qs}.${Xs} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${r} 1s step-end infinite;}${this._terminalSelector} .${qs}.${Xs} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${qs} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${qs} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${qs} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${qs} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${qs} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${Zs} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${Zs} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${Zs} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[n,r]of e.ansi.entries())t+=`${this._terminalSelector} .${Js}${n} { color: ${r.css}; }${this._terminalSelector} .${Js}${n}.xterm-dim { color: ${Os.multiplyOpacity(r,.5).css}; }${this._terminalSelector} .${Ys}${n} { background-color: ${r.css}; }`;t+=`${this._terminalSelector} .${Js}257 { color: ${Os.opaque(e.background).css}; }${this._terminalSelector} .${Js}257.xterm-dim { color: ${Os.multiplyOpacity(Os.opaque(e.background),.5).css}; }${this._terminalSelector} .${Ys}257 { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=t}_setDefaultSpacing(){let e=this.dimensions.css.cell.width-this._widthCache.get(`W`,!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,t){for(let e=this._rowElements.length;e<=t;e++){let e=this._document.createElement(`div`);this._rowContainer.appendChild(e),this._rowElements.push(e)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,t){this._refreshRowElements(e,t),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(Xs),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(Xs),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,n){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,n),this.renderRows(0,this._bufferService.rows-1),!e||!t||(this._selectionRenderModel.update(this._terminal,e,t,n),!this._selectionRenderModel.hasSelection))return;let r=this._selectionRenderModel.viewportStartRow,i=this._selectionRenderModel.viewportEndRow,a=this._selectionRenderModel.viewportCappedStartRow,o=this._selectionRenderModel.viewportCappedEndRow,s=this._document.createDocumentFragment();if(n){let n=e[0]>t[0];s.appendChild(this._createSelectionElement(a,n?t[0]:e[0],n?e[0]:t[0],o-a+1))}else{let n=r===a?e[0]:0,c=a===i?t[0]:this._bufferService.cols;s.appendChild(this._createSelectionElement(a,n,c));let l=o-a-1;if(s.appendChild(this._createSelectionElement(a+1,0,this._bufferService.cols,l)),a!==o){let e=i===o?t[0]:this._bufferService.cols;s.appendChild(this._createSelectionElement(o,0,e))}}this._selectionContainer.appendChild(s)}_createSelectionElement(e,t,n,r=1){let i=this._document.createElement(`div`),a=t*this.dimensions.css.cell.width,o=this.dimensions.css.cell.width*(n-t);return a+o>this.dimensions.css.canvas.width&&(o=this.dimensions.css.canvas.width-a),i.style.height=`${r*this.dimensions.css.cell.height}px`,i.style.top=`${e*this.dimensions.css.cell.height}px`,i.style.left=`${a}px`,i.style.width=`${o}px`,i}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(let e of this._rowElements)e.replaceChildren()}renderRows(e,t){let n=this._bufferService.buffer,r=n.ybase+n.y,i=Math.min(n.x,this._bufferService.cols-1),a=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,o=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,s=this._optionsService.rawOptions.cursorInactiveStyle;for(let c=e;c<=t;c++){let e=c+n.ydisp,t=this._rowElements[c],l=n.lines.get(e);if(!t||!l)break;t.replaceChildren(...this._rowFactory.createRow(l,e,e===r,o,s,i,a,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${Ks}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,t,n,r,i,a){n<0&&(e=0),r<0&&(t=0);let o=this._bufferService.rows-1;n=Math.max(Math.min(n,o),0),r=Math.max(Math.min(r,o),0),i=Math.min(i,this._bufferService.cols);let s=this._bufferService.buffer,c=s.ybase+s.y,l=Math.min(s.x,i-1),u=this._optionsService.rawOptions.cursorBlink,d=this._optionsService.rawOptions.cursorStyle,f=this._optionsService.rawOptions.cursorInactiveStyle;for(let o=n;o<=r;++o){let p=o+s.ydisp,m=this._rowElements[o],h=s.lines.get(p);if(!m||!h)break;m.replaceChildren(...this._rowFactory.createRow(h,p,p===c,d,f,l,u,this.dimensions.css.cell.width,this._widthCache,a?o===n?e:0:-1,a?(o===r?t:i)-1:-1))}}};$s=R([z(7,Yr),z(8,ri),z(9,Zr),z(10,Gr),z(11,qr),z(12,ii),z(13,li)],$s);var ec=class extends H{constructor(e,t,n){super(),this._optionsService=n,this.width=0,this.height=0,this._onCharSizeChange=this._register(new U),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new rc(this._optionsService))}catch{this._measureStrategy=this._register(new nc(e,t,this._optionsService))}this._register(this._optionsService.onMultipleOptionChange([`fontFamily`,`fontSize`],()=>this.measure()))}get hasValidSize(){return this.width>0&&this.height>0}measure(){let e=this._measureStrategy.measure();(e.width!==this.width||e.height!==this.height)&&(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};ec=R([z(2,Zr)],ec);var tc=class extends H{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(e,t){e!==void 0&&e>0&&t!==void 0&&t>0&&(this._result.width=e,this._result.height=t)}},nc=class extends tc{constructor(e,t,n){super(),this._document=e,this._parentElement=t,this._optionsService=n,this._measureElement=this._document.createElement(`span`),this._measureElement.classList.add(`xterm-char-measure-element`),this._measureElement.textContent=`W`.repeat(32),this._measureElement.setAttribute(`aria-hidden`,`true`),this._measureElement.style.whiteSpace=`pre`,this._measureElement.style.fontKerning=`none`,this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}},rc=class extends tc{constructor(e){super(),this._optionsService=e,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext(`2d`);let t=this._ctx.measureText(`W`);if(!(`width`in t&&`fontBoundingBoxAscent`in t&&`fontBoundingBoxDescent`in t))throw Error(`Required font metrics not supported`)}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;let e=this._ctx.measureText(`W`);return this._validateAndSet(e.width,e.fontBoundingBoxAscent+e.fontBoundingBoxDescent),this._result}},ic=class extends H{constructor(e,t,n){super(),this._textarea=e,this._window=t,this.mainDocument=n,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=this._register(new ac(this._window)),this._onDprChange=this._register(new U),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new U),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(e=>this._screenDprMonitor.setWindow(e))),this._register(Bi.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(W(this._textarea,`focus`,()=>this._isFocused=!0)),this._register(W(this._textarea,`blur`,()=>this._isFocused=!1))}get window(){return this._window}set window(e){this._window!==e&&(this._window=e,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return this._cachedIsFocused===void 0&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask(()=>this._cachedIsFocused=void 0)),this._cachedIsFocused}},ac=class extends H{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new Ni),this._onDprChange=this._register(new U),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register(V(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=W(this._parentWindow,`resize`,()=>this._setDprAndFireIfDiffers())}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){this._outerListener&&(this._resolutionMediaMatchList?.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){!this._resolutionMediaMatchList||!this._outerListener||(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}},oc=class extends H{constructor(){super(),this.linkProviders=[],this._register(V(()=>this.linkProviders.length=0))}registerLinkProvider(e){return this.linkProviders.push(e),{dispose:()=>{let t=this.linkProviders.indexOf(e);t!==-1&&this.linkProviders.splice(t,1)}}}};function sc(e,t,n){let r=n.getBoundingClientRect(),i=e.getComputedStyle(n),a=parseInt(i.getPropertyValue(`padding-left`)),o=parseInt(i.getPropertyValue(`padding-top`));return[t.clientX-r.left-a,t.clientY-r.top-o]}function cc(e,t,n,r,i,a,o,s,c){if(!a)return;let l=sc(e,t,n);if(l)return l[0]=Math.ceil((l[0]+(c?o/2:0))/o),l[1]=Math.ceil(l[1]/s),l[0]=Math.min(Math.max(l[0],1),r+ +!!c),l[1]=Math.min(Math.max(l[1],1),i),l}var lc=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,n,r,i){return cc(window,e,t,n,r,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,i)}getMouseReportCoords(e,t){let n=sc(window,e,t);if(this._charSizeService.hasValidSize)return n[0]=Math.min(Math.max(n[0],0),this._renderService.dimensions.css.canvas.width-1),n[1]=Math.min(Math.max(n[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(n[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(n[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(n[0]),y:Math.floor(n[1])}}};lc=R([z(0,oi),z(1,ri)],lc);var uc=class{constructor(e,t){this._renderCallback=e,this._coreBrowserService=t,this._refreshCallbacks=[]}dispose(){this._animationFrame&&=(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),void 0)}addRefreshCallback(e){return this._refreshCallbacks.push(e),this._animationFrame||=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()),this._animationFrame}refresh(e,t,n){this._rowCount=n,e=e===void 0?0:e,t=t===void 0?this._rowCount-1:t,this._rowStart=this._rowStart===void 0?e:Math.min(this._rowStart,e),this._rowEnd=this._rowEnd===void 0?t:Math.max(this._rowEnd,t),!this._animationFrame&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0){this._runRefreshCallbacks();return}let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(let e of this._refreshCallbacks)e(0);this._refreshCallbacks=[]}},dc={};yr(dc,{getSafariVersion:()=>vc,isChromeOS:()=>wc,isFirefox:()=>hc,isIpad:()=>bc,isIphone:()=>xc,isLegacyEdge:()=>gc,isLinux:()=>Cc,isMac:()=>yc,isNode:()=>fc,isSafari:()=>_c,isWindows:()=>Sc});var fc=typeof process<`u`&&`title`in process,pc=fc?`node`:navigator.userAgent,mc=fc?`node`:navigator.platform,hc=pc.includes(`Firefox`),gc=pc.includes(`Edge`),_c=/^((?!chrome|android).)*safari/i.test(pc);function vc(){if(!_c)return 0;let e=pc.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var yc=[`Macintosh`,`MacIntel`,`MacPPC`,`Mac68K`].includes(mc),bc=mc===`iPad`,xc=mc===`iPhone`,Sc=[`Windows`,`Win16`,`Win32`,`WinCE`].includes(mc),Cc=mc.indexOf(`Linux`)>=0,wc=/\bCrOS\b/.test(pc),Tc=class{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._i<this._tasks.length;)this._tasks[this._i]()||this._i++;this.clear()}clear(){this._idleCallback&&=(this._cancelCallback(this._idleCallback),void 0),this._i=0,this._tasks.length=0}_start(){this._idleCallback||=this._requestCallback(this._process.bind(this))}_process(e){this._idleCallback=void 0;let t=0,n=0,r=e.timeRemaining(),i=0;for(;this._i<this._tasks.length;){if(t=performance.now(),this._tasks[this._i]()||this._i++,t=Math.max(1,performance.now()-t),n=Math.max(t,n),i=e.timeRemaining(),n*1.5>i){r-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(r-t))}ms`),this._start();return}r=i}this.clear()}},Ec=class extends Tc{_requestCallback(e){return setTimeout(()=>e(this._createDeadline(16)))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=performance.now()+e;return{timeRemaining:()=>Math.max(0,t-performance.now())}}},Dc=class extends Tc{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},Oc=!fc&&`requestIdleCallback`in window?Dc:Ec,kc=class{constructor(){this._queue=new Oc}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},Ac=class extends H{constructor(e,t,n,r,i,a,o,s,c){super(),this._rowCount=e,this._optionsService=n,this._charSizeService=r,this._coreService=i,this._coreBrowserService=s,this._renderer=this._register(new Ni),this._pausedResizeTask=new kc,this._observerDisposable=this._register(new Ni),this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this._register(new U),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new U),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new U),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new U),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new uc((e,t)=>this._renderRows(e,t),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new jc(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(V(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(o.onResize(()=>this._fullRefresh())),this._register(o.buffers.onBufferActivate(()=>this._renderer.value?.clear())),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this._register(a.onDecorationRegistered(()=>this._fullRefresh())),this._register(a.onDecorationRemoved(()=>this._fullRefresh())),this._register(this._optionsService.onMultipleOptionChange([`customGlyphs`,`drawBoldTextInBrightColors`,`letterSpacing`,`lineHeight`,`fontFamily`,`fontSize`,`fontWeight`,`fontWeightBold`,`minimumContrastRatio`,`rescaleOverlappingGlyphs`],()=>{this.clear(),this.handleResize(o.cols,o.rows),this._fullRefresh()})),this._register(this._optionsService.onMultipleOptionChange([`cursorBlink`,`cursorStyle`],()=>this.refreshRows(o.buffer.y,o.buffer.y,!0))),this._register(c.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(this._coreBrowserService.window,t),this._register(this._coreBrowserService.onWindowChange(e=>this._registerIntersectionObserver(e,t)))}get dimensions(){return this._renderer.value.dimensions}_registerIntersectionObserver(e,t){if(`IntersectionObserver`in e){let n=new e.IntersectionObserver(e=>this._handleIntersectionChange(e[e.length-1]),{threshold:0});n.observe(t),this._observerDisposable.value=V(()=>n.disconnect())}}_handleIntersectionChange(e){this._isPaused=e.isIntersecting===void 0?e.intersectionRatio===0:!e.isIntersecting,!this._isPaused&&!this._charSizeService.hasValidSize&&this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,t,n=!1){if(this._isPaused){this._needsFullRefresh=!0;return}if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}let r=this._syncOutputHandler.flush();r&&(e=Math.min(e,r.start),t=Math.max(t,r.end)),n||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,t,this._rowCount)}_renderRows(e,t){if(this._renderer.value){if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}e=Math.min(e,this._rowCount-1),t=Math.min(t,this._rowCount-1),this._renderer.value.renderRows(e,t),this._needsSelectionRefresh&&=(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:t}),this._onRender.fire({start:e,end:t}),this._isNextRenderRedrawOnly=!0}}resize(e,t){this._rowCount=t,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw(e=>this.refreshRows(e.start,e.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){this._renderer.value&&(this._renderer.value.clearTextureAtlas?.(),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,t){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>this._renderer.value?.handleResize(e,t)):this._renderer.value.handleResize(e,t),this._fullRefresh())}handleCharSizeChanged(){this._renderer.value?.handleCharSizeChanged()}handleBlur(){this._renderer.value?.handleBlur()}handleFocus(){this._renderer.value?.handleFocus()}handleSelectionChanged(e,t,n){this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=n,this._renderer.value?.handleSelectionChanged(e,t,n)}handleCursorMove(){this._renderer.value?.handleCursorMove()}clear(){this._renderer.value?.clear()}};Ac=R([z(2,Zr),z(3,ri),z(4,qr),z(5,ei),z(6,Gr),z(7,ii),z(8,li)],Ac);var jc=class{constructor(e,t,n){this._coreBrowserService=e,this._coreService=t,this._onTimeout=n,this._start=0,this._end=0,this._isBuffering=!1}bufferRows(e,t){this._isBuffering?(this._start=Math.min(this._start,e),this._end=Math.max(this._end,t)):(this._start=e,this._end=t,this._isBuffering=!0),this._timeout===void 0&&(this._timeout=this._coreBrowserService.window.setTimeout(()=>{this._timeout=void 0,this._coreService.decPrivateModes.synchronizedOutput=!1,this._onTimeout()},1e3))}flush(){if(this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0),!this._isBuffering)return;let e={start:this._start,end:this._end};return this._isBuffering=!1,e}dispose(){this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0)}};function Mc(e,t,n,r){let i=n.buffer.x,a=n.buffer.y;if(!n.buffer.hasScrollback)return Fc(i,a,e,t,n,r)+Ic(a,t,n,r)+Lc(i,a,e,t,n,r);let o;if(a===t)return o=i>e?`D`:`C`,Wc(Math.abs(i-e),Uc(o,r));o=a>t?`D`:`C`;let s=Math.abs(a-t);return Wc(Pc(a>t?e:i,n)+(s-1)*n.cols+1+Nc(a>t?i:e,n),Uc(o,r))}function Nc(e,t){return e-1}function Pc(e,t){return t.cols-e}function Fc(e,t,n,r,i,a){return Ic(t,r,i,a).length===0?``:Wc(Hc(e,t,e,t-zc(t,i),!1,i).length,Uc(`D`,a))}function Ic(e,t,n,r){let i=e-zc(e,n),a=t-zc(t,n);return Wc(Math.abs(i-a)-Rc(e,t,n),Uc(Vc(e,t),r))}function Lc(e,t,n,r,i,a){let o;o=Ic(t,r,i,a).length>0?r-zc(r,i):t;let s=r,c=Bc(e,t,n,r,i,a);return Wc(Hc(e,o,n,s,c===`C`,i).length,Uc(c,a))}function Rc(e,t,n){let r=0,i=e-zc(e,n),a=t-zc(t,n);for(let o=0;o<Math.abs(i-a);o++){let a=Vc(e,t)===`A`?-1:1;n.buffer.lines.get(i+a*o)?.isWrapped&&r++}return r}function zc(e,t){let n=0,r=t.buffer.lines.get(e),i=r?.isWrapped;for(;i&&e>=0&&e<t.rows;)n++,r=t.buffer.lines.get(--e),i=r?.isWrapped;return n}function Bc(e,t,n,r,i,a){let o;return o=Ic(n,r,i,a).length>0?r-zc(r,i):t,e<n&&o<=r||e>=n&&o<r?`C`:`D`}function Vc(e,t){return e>t?`A`:`B`}function Hc(e,t,n,r,i,a){let o=e,s=t,c=``;for(;(o!==n||s!==r)&&s>=0&&s<a.buffer.lines.length;)o+=i?1:-1,i&&o>a.cols-1?(c+=a.buffer.translateBufferLineToString(s,!1,e,o),o=0,e=0,s++):!i&&o<0&&(c+=a.buffer.translateBufferLineToString(s,!1,0,e+1),o=a.cols-1,e=o,s--);return c+a.buffer.translateBufferLineToString(s,!1,e,o)}function Uc(e,t){let n=t?`O`:`[`;return G.ESC+n+e}function Wc(e,t){e=Math.floor(e);let n=``;for(let r=0;r<e;r++)n+=t;return n}var Gc=class{constructor(e){this._bufferService=e,this.isSelectAllActive=!1,this.selectionStartLength=0}clearSelection(){this.selectionStart=void 0,this.selectionEnd=void 0,this.isSelectAllActive=!1,this.selectionStartLength=0}get finalSelectionStart(){return this.isSelectAllActive?[0,0]:!this.selectionEnd||!this.selectionStart?this.selectionStart:this.areSelectionValuesReversed()?this.selectionEnd:this.selectionStart}get finalSelectionEnd(){if(this.isSelectAllActive)return[this._bufferService.cols,this._bufferService.buffer.ybase+this._bufferService.rows-1];if(this.selectionStart){if(!this.selectionEnd||this.areSelectionValuesReversed()){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?e%this._bufferService.cols===0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)-1]:[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[Math.max(e,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){let e=this.selectionStart,t=this.selectionEnd;return!e||!t?!1:e[1]>t[1]||e[1]===t[1]&&e[0]>t[0]}handleTrim(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}};function Kc(e,t){if(e.start.y>e.end.y)throw Error(`Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`);return t*(e.end.y-e.start.y)+(e.end.x-e.start.x+1)}var qc=50,Jc=15,Yc=50,Xc=500,Zc=RegExp(`\xA0`,`g`),Qc=class extends H{constructor(e,t,n,r,i,a,o,s,c){super(),this._element=e,this._screenElement=t,this._linkifier=n,this._bufferService=r,this._coreService=i,this._mouseService=a,this._optionsService=o,this._renderService=s,this._coreBrowserService=c,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new Rr,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new U),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new U),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new U),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new U),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=e=>this._handleMouseMove(e),this._mouseUpListener=e=>this._handleMouseUp(e),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(e=>this._handleTrim(e)),this._register(this._bufferService.buffers.onBufferActivate(e=>this._handleBufferActivate(e))),this.enable(),this._model=new Gc(this._bufferService),this._activeSelectionMode=0,this._register(V(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(e=>{e.rowsChanged&&this.clearSelection()}))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!e||!t?!1:e[0]!==t[0]||e[1]!==t[1]}get selectionText(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return``;let n=this._bufferService.buffer,r=[];if(this._activeSelectionMode===3){if(e[0]===t[0])return``;let i=e[0]<t[0]?e[0]:t[0],a=e[0]<t[0]?t[0]:e[0];for(let o=e[1];o<=t[1];o++){let e=n.translateBufferLineToString(o,!0,i,a);r.push(e)}}else{let i=e[1]===t[1]?t[0]:void 0;r.push(n.translateBufferLineToString(e[1],!0,e[0],i));for(let i=e[1]+1;i<=t[1]-1;i++){let e=n.lines.get(i),t=n.translateBufferLineToString(i,!0);e?.isWrapped?r[r.length-1]+=t:r.push(t)}if(e[1]!==t[1]){let e=n.lines.get(t[1]),i=n.translateBufferLineToString(t[1],!0,0,t[0]);e&&e.isWrapped?r[r.length-1]+=i:r.push(i)}}return r.map(e=>e.replace(Zc,` `)).join(Sc?`\r
14
+ `))}},qi=class extends Error{constructor(e,t){super(e),this.name=`ListenerLeakError`,this.stack=t}},Ji=class extends Error{constructor(e,t){super(e),this.name=`ListenerRefusalError`,this.stack=t}},Yi=0,Xi=class{constructor(e){this.value=e,this.id=Yi++}},Zi=2,W=class{constructor(e){this._size=0,this._options=e,this._leakageMon=Ui>0||this._options?.leakWarningThreshold?new Gi(e?.onListenerError??fi,this._options?.leakWarningThreshold??Ui):void 0,this._perfMon=this._options?._profName?new Hi(this._options._profName):void 0,this._deliveryQueue=this._options?.deliveryQueue}dispose(){this._disposed||(this._disposed=!0,this._deliveryQueue?.current===this&&this._deliveryQueue.reset(),this._listeners&&(this._listeners=void 0,this._size=0),this._options?.onDidRemoveLastListener?.(),this._leakageMon?.dispose())}get event(){return this._event??=(e,t,n)=>{if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let e=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(e);let t=this._leakageMon.getMostFrequentStack()??[`UNKNOWN stack`,-1],n=new Ji(`${e}. HINT: Stack shows most frequent listener (${t[1]}-times)`,t[0]);return(this._options?.onListenerError||fi)(n),U.None}if(this._disposed)return U.None;t&&(e=e.bind(t));let r=new Xi(e),i;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(r.stack=Ki.create(),i=this._leakageMon.check(r.stack,this._size+1)),this._listeners?this._listeners instanceof Xi?(this._deliveryQueue??=new Qi,this._listeners=[this._listeners,r]):this._listeners.push(r):(this._options?.onWillAddFirstListener?.(this),this._listeners=r,this._options?.onDidAddFirstListener?.(this)),this._size++;let a=H(()=>{i?.(),this._removeListener(r)});return n instanceof Mi?n.add(a):Array.isArray(n)&&n.push(a),a},this._event}_removeListener(e){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(this._size===1){this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),this._size=0;return}let t=this._listeners,n=t.indexOf(e);if(n===-1)throw console.log(`disposed?`,this._disposed),console.log(`size?`,this._size),console.log(`arr?`,JSON.stringify(this._listeners)),Error(`Attempted to dispose unknown listener`);this._size--,t[n]=void 0;let r=this._deliveryQueue.current===this;if(this._size*Zi<=t.length){let e=0;for(let n=0;n<t.length;n++)t[n]?t[e++]=t[n]:r&&(this._deliveryQueue.end--,e<this._deliveryQueue.i&&this._deliveryQueue.i--);t.length=e}}_deliver(e,t){if(!e)return;let n=this._options?.onListenerError||fi;if(!n)e.value(t);else try{e.value(t)}catch(e){n(e)}}_deliverQueue(e){let t=e.current._listeners;for(;e.i<e.end;)this._deliver(t[e.i++],e.value);e.reset()}fire(e){if(this._deliveryQueue?.current&&(this._deliverQueue(this._deliveryQueue),this._perfMon?.stop()),this._perfMon?.start(this._size),this._listeners){if(this._listeners instanceof Xi)this._deliver(this._listeners,e);else{let t=this._deliveryQueue;t.enqueue(this,e,this._listeners.length),this._deliverQueue(t)}}this._perfMon?.stop()}hasListeners(){return this._size>0}},Qi=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,n){this.i=0,this.end=n,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},$i=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new W,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new W,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(e){return this.mapWindowIdToZoomLevel.get(this.getWindowId(e))??0}setZoomLevel(e,t){if(this.getZoomLevel(t)===e)return;let n=this.getWindowId(t);this.mapWindowIdToZoomLevel.set(n,e),this._onDidChangeZoomLevel.fire(n)}getZoomFactor(e){return this.mapWindowIdToZoomFactor.get(this.getWindowId(e))??1}setZoomFactor(e,t){this.mapWindowIdToZoomFactor.set(this.getWindowId(t),e)}setFullscreen(e,t){if(this.isFullscreen(t)===e)return;let n=this.getWindowId(t);this.mapWindowIdToFullScreen.set(n,e),this._onDidChangeFullscreen.fire(n)}isFullscreen(e){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(e))}getWindowId(e){return e.vscodeWindowId}};$i.INSTANCE=new $i;var ea=$i;function ta(e,t,n){typeof t==`string`&&(t=e.matchMedia(t)),t.addEventListener(`change`,n)}ea.INSTANCE.onDidChangeZoomLevel;function na(e){return ea.INSTANCE.getZoomFactor(e)}ea.INSTANCE.onDidChangeFullscreen;var ra=typeof navigator==`object`?navigator.userAgent:``,ia=ra.indexOf(`Firefox`)>=0,aa=ra.indexOf(`AppleWebKit`)>=0,oa=ra.indexOf(`Chrome`)>=0,sa=!oa&&ra.indexOf(`Safari`)>=0;ra.indexOf(`Electron/`),ra.indexOf(`Android`);var ca=!1;if(typeof Pi.matchMedia==`function`){let e=Pi.matchMedia(`(display-mode: standalone) or (display-mode: window-controls-overlay)`),t=Pi.matchMedia(`(display-mode: fullscreen)`);ca=e.matches,ta(Pi,e,({matches:e})=>{ca&&t.matches||(ca=e)})}function la(){return ca}var ua=`en`,da=!1,fa=!1,pa=!1,ma=!1,ha=!1,ga=ua,_a,va=globalThis,ya;typeof va.vscode<`u`&&typeof va.vscode.process<`u`?ya=va.vscode.process:typeof process<`u`&&typeof process?.versions?.node==`string`&&(ya=process);var ba=typeof ya?.versions?.electron==`string`&&ya?.type===`renderer`;if(typeof ya==`object`){da=ya.platform===`win32`,fa=ya.platform===`darwin`,pa=ya.platform===`linux`,pa&&ya.env.SNAP&&ya.env.SNAP_REVISION,ya.env.CI||ya.env.BUILD_ARTIFACTSTAGINGDIRECTORY,ga=ua;let e=ya.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);t.userLocale,t.osLocale,ga=t.resolvedLanguage||ua,t.languagePack?.translationsConfigFile}catch{}ma=!0}else typeof navigator==`object`&&!ba?(_a=navigator.userAgent,da=_a.indexOf(`Windows`)>=0,fa=_a.indexOf(`Macintosh`)>=0,(_a.indexOf(`Macintosh`)>=0||_a.indexOf(`iPad`)>=0||_a.indexOf(`iPhone`)>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints,pa=_a.indexOf(`Linux`)>=0,_a?.indexOf(`Mobi`),ha=!0,ga=globalThis._VSCODE_NLS_LANGUAGE||ua,navigator.language.toLowerCase()):console.error(`Unable to resolve platform.`);var xa=da,Sa=fa,Ca=pa,wa=ma;ha&&typeof va.importScripts==`function`&&va.origin;var Ta=_a,Ea=ga,Da;(e=>{function t(){return Ea}e.value=t;function n(){return Ea.length===2?Ea===`en`:Ea.length>=3&&Ea[0]===`e`&&Ea[1]===`n`&&Ea[2]===`-`}e.isDefaultVariant=n;function r(){return Ea===`en`}e.isDefault=r})(Da||={});var Oa=typeof va.postMessage==`function`&&!va.importScripts;(()=>{if(Oa){let e=[];va.addEventListener(`message`,t=>{if(t.data&&t.data.vscodeScheduleAsyncWork)for(let n=0,r=e.length;n<r;n++){let r=e[n];if(r.id===t.data.vscodeScheduleAsyncWork){e.splice(n,1),r.callback();return}}});let t=0;return n=>{let r=++t;e.push({id:r,callback:n}),va.postMessage({vscodeScheduleAsyncWork:r},`*`)}}return e=>setTimeout(e)})();var ka=!!(Ta&&Ta.indexOf(`Chrome`)>=0);Ta&&Ta.indexOf(`Firefox`),!ka&&Ta&&Ta.indexOf(`Safari`),Ta&&Ta.indexOf(`Edg/`),Ta&&Ta.indexOf(`Android`);var Aa=typeof navigator==`object`?navigator:{};wa||document.queryCommandSupported&&document.queryCommandSupported(`copy`)||Aa&&Aa.clipboard&&Aa.clipboard.writeText,wa||Aa&&Aa.clipboard&&Aa.clipboard.readText,wa||la()||Aa.keyboard,`ontouchstart`in Pi||Aa.maxTouchPoints,Pi.PointerEvent&&(`ontouchstart`in Pi||navigator.maxTouchPoints);var ja=class{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e}keyCodeToStr(e){return this._keyCodeToStr[e]}strToKeyCode(e){return this._strToKeyCode[e.toLowerCase()]||0}},Ma=new ja,Na=new ja,Pa=new ja,Fa=Array(230),Ia;(e=>{function t(e){return Ma.keyCodeToStr(e)}e.toString=t;function n(e){return Ma.strToKeyCode(e)}e.fromString=n;function r(e){return Na.keyCodeToStr(e)}e.toUserSettingsUS=r;function i(e){return Pa.keyCodeToStr(e)}e.toUserSettingsGeneral=i;function a(e){return Na.strToKeyCode(e)||Pa.strToKeyCode(e)}e.fromUserSettings=a;function o(e){if(e>=98&&e<=113)return null;switch(e){case 16:return`Up`;case 18:return`Down`;case 15:return`Left`;case 17:return`Right`}return Ma.keyCodeToStr(e)}e.toElectronAccelerator=o})(Ia||={});var La=class e{constructor(e,t,n,r,i){this.ctrlKey=e,this.shiftKey=t,this.altKey=n,this.metaKey=r,this.keyCode=i}equals(t){return t instanceof e&&this.ctrlKey===t.ctrlKey&&this.shiftKey===t.shiftKey&&this.altKey===t.altKey&&this.metaKey===t.metaKey&&this.keyCode===t.keyCode}getHashCode(){return`K${this.ctrlKey?`1`:`0`}${this.shiftKey?`1`:`0`}${this.altKey?`1`:`0`}${this.metaKey?`1`:`0`}${this.keyCode}`}isModifierKey(){return this.keyCode===0||this.keyCode===5||this.keyCode===57||this.keyCode===6||this.keyCode===4}toKeybinding(){return new Ra([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},Ra=class{constructor(e){if(e.length===0)throw gi(`chords`);this.chords=e}getHashCode(){let e=``;for(let t=0,n=this.chords.length;t<n;t++)t!==0&&(e+=`;`),e+=this.chords[t].getHashCode();return e}equals(e){if(e===null||this.chords.length!==e.chords.length)return!1;for(let t=0;t<this.chords.length;t++)if(!this.chords[t].equals(e.chords[t]))return!1;return!0}};function za(e){if(e.charCode){let t=String.fromCharCode(e.charCode).toUpperCase();return Ia.fromString(t)}let t=e.keyCode;if(t===3)return 7;if(ia)switch(t){case 59:return 85;case 60:if(Ca)return 97;break;case 61:return 86;case 107:return 109;case 109:return 111;case 173:return 88;case 224:if(Sa)return 57}else if(aa&&(Sa&&t===93||!Sa&&t===92))return 57;return Fa[t]||0}var Ba=Sa?256:2048,Va=512,Ha=1024,Ua=Sa?2048:256,Wa=class{constructor(e){this._standardKeyboardEventBrand=!0;let t=e;this.browserEvent=t,this.target=t.target,this.ctrlKey=t.ctrlKey,this.shiftKey=t.shiftKey,this.altKey=t.altKey,this.metaKey=t.metaKey,this.altGraphKey=t.getModifierState?.(`AltGraph`),this.keyCode=za(t),this.code=t.code,this.ctrlKey=this.ctrlKey||this.keyCode===5,this.altKey=this.altKey||this.keyCode===6,this.shiftKey=this.shiftKey||this.keyCode===4,this.metaKey=this.metaKey||this.keyCode===57,this._asKeybinding=this._computeKeybinding(),this._asKeyCodeChord=this._computeKeyCodeChord()}preventDefault(){this.browserEvent&&this.browserEvent.preventDefault&&this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent&&this.browserEvent.stopPropagation&&this.browserEvent.stopPropagation()}toKeyCodeChord(){return this._asKeyCodeChord}equals(e){return this._asKeybinding===e}_computeKeybinding(){let e=0;this.keyCode!==5&&this.keyCode!==4&&this.keyCode!==6&&this.keyCode!==57&&(e=this.keyCode);let t=0;return this.ctrlKey&&(t|=Ba),this.altKey&&(t|=Va),this.shiftKey&&(t|=Ha),this.metaKey&&(t|=Ua),t|=e,t}_computeKeyCodeChord(){let e=0;return this.keyCode!==5&&this.keyCode!==4&&this.keyCode!==6&&this.keyCode!==57&&(e=this.keyCode),new La(this.ctrlKey,this.shiftKey,this.altKey,this.metaKey,e)}},Ga=new WeakMap;function Ka(e){if(!e.parent||e.parent===e)return null;try{let t=e.location,n=e.parent.location;if(t.origin!==`null`&&n.origin!==`null`&&t.origin!==n.origin)return null}catch{return null}return e.parent}var qa=class{static getSameOriginWindowChain(e){let t=Ga.get(e);if(!t){t=[],Ga.set(e,t);let n=e,r;do r=Ka(n),r?t.push({window:new WeakRef(n),iframeElement:n.frameElement||null}):t.push({window:new WeakRef(n),iframeElement:null}),n=r;while(n)}return t.slice(0)}static getPositionOfChildWindowRelativeToAncestorWindow(e,t){if(!t||e===t)return{top:0,left:0};let n=0,r=0,i=this.getSameOriginWindowChain(e);for(let e of i){let i=e.window.deref();if(n+=i?.scrollY??0,r+=i?.scrollX??0,i===t||!e.iframeElement)break;let a=e.iframeElement.getBoundingClientRect();n+=a.top,r+=a.left}return{top:n,left:r}}},Ja=class{constructor(e,t){this.timestamp=Date.now(),this.browserEvent=t,this.leftButton=t.button===0,this.middleButton=t.button===1,this.rightButton=t.button===2,this.buttons=t.buttons,this.target=t.target,this.detail=t.detail||1,t.type===`dblclick`&&(this.detail=2),this.ctrlKey=t.ctrlKey,this.shiftKey=t.shiftKey,this.altKey=t.altKey,this.metaKey=t.metaKey,typeof t.pageX==`number`?(this.posx=t.pageX,this.posy=t.pageY):(this.posx=t.clientX+this.target.ownerDocument.body.scrollLeft+this.target.ownerDocument.documentElement.scrollLeft,this.posy=t.clientY+this.target.ownerDocument.body.scrollTop+this.target.ownerDocument.documentElement.scrollTop);let n=qa.getPositionOfChildWindowRelativeToAncestorWindow(e,t.view);this.posx-=n.left,this.posy-=n.top}preventDefault(){this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent.stopPropagation()}},Ya=class{constructor(e,t=0,n=0){this.browserEvent=e||null,this.target=e?e.target||e.targetNode||e.srcElement:null,this.deltaY=n,this.deltaX=t;let r=!1;if(oa){let e=navigator.userAgent.match(/Chrome\/(\d+)/);r=(e?parseInt(e[1]):123)<=122}if(e){let t=e,n=e,i=e.view?.devicePixelRatio||1;if(typeof t.wheelDeltaY<`u`)this.deltaY=r?t.wheelDeltaY/(120*i):t.wheelDeltaY/120;else if(typeof n.VERTICAL_AXIS<`u`&&n.axis===n.VERTICAL_AXIS)this.deltaY=-n.detail/3;else if(e.type===`wheel`){let t=e;this.deltaY=t.deltaMode===t.DOM_DELTA_LINE?ia&&!Sa?-e.deltaY/3:-e.deltaY:-e.deltaY/40}if(typeof t.wheelDeltaX<`u`)this.deltaX=sa&&xa?-(t.wheelDeltaX/120):r?t.wheelDeltaX/(120*i):t.wheelDeltaX/120;else if(typeof n.HORIZONTAL_AXIS<`u`&&n.axis===n.HORIZONTAL_AXIS)this.deltaX=-e.detail/3;else if(e.type===`wheel`){let t=e;this.deltaX=t.deltaMode===t.DOM_DELTA_LINE?ia&&!Sa?-e.deltaX/3:-e.deltaX:-e.deltaX/40}this.deltaY===0&&this.deltaX===0&&e.wheelDelta&&(this.deltaY=r?e.wheelDelta/(120*i):e.wheelDelta/120)}}preventDefault(){this.browserEvent?.preventDefault()}stopPropagation(){this.browserEvent?.stopPropagation()}},Xa=Object.freeze(function(e,t){let n=setTimeout(e.bind(t),0);return{dispose(){clearTimeout(n)}}}),Za;(e=>{function t(t){return t===e.None||t===e.Cancelled||t instanceof Qa?!0:!t||typeof t!=`object`?!1:typeof t.isCancellationRequested==`boolean`&&typeof t.onCancellationRequested==`function`}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:Bi.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:Xa})})(Za||={});var Qa=class{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?Xa:(this._emitter||=new W,this._emitter.event)}dispose(){this._emitter&&=(this._emitter.dispose(),null)}},$a=class{constructor(e,t){this._isDisposed=!1,this._token=-1,typeof e==`function`&&typeof t==`number`&&this.setIfNotSet(e,t)}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._token!==-1&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(e,t){if(this._isDisposed)throw new vi(`Calling 'cancelAndSet' on a disposed TimeoutTimer`);this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new vi(`Calling 'setIfNotSet' on a disposed TimeoutTimer`);this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},eo=class{constructor(){this.disposable=void 0,this.isDisposed=!1}cancel(){this.disposable?.dispose(),this.disposable=void 0}cancelAndSet(e,t,n=globalThis){if(this.isDisposed)throw new vi(`Calling 'cancelAndSet' on a disposed IntervalTimer`);this.cancel();let r=n.setInterval(()=>{e()},t);this.disposable=H(()=>{n.clearInterval(r),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}};(function(){typeof globalThis.requestIdleCallback!=`function`||globalThis.cancelIdleCallback})();var to;(e=>{async function t(e){let t,n=await Promise.all(e.map(e=>e.then(e=>e,e=>{t||=e})));if(typeof t<`u`)throw t;return n}e.settled=t;function n(e){return new Promise(async(t,n)=>{try{await e(t,n)}catch(e){n(e)}})}e.withAsyncBody=n})(to||={});var no=class e{static fromArray(t){return new e(e=>{e.emitMany(t)})}static fromPromise(t){return new e(async e=>{e.emitMany(await t)})}static fromPromises(t){return new e(async e=>{await Promise.all(t.map(async t=>e.emitOne(await t)))})}static merge(t){return new e(async e=>{await Promise.all(t.map(async t=>{for await(let n of t)e.emitOne(n)}))})}constructor(e,t){this._state=0,this._results=[],this._error=null,this._onReturn=t,this._onStateChanged=new W,queueMicrotask(async()=>{let t={emitOne:e=>this.emitOne(e),emitMany:e=>this.emitMany(e),reject:e=>this.reject(e)};try{await Promise.resolve(e(t)),this.resolve()}catch(e){this.reject(e)}finally{t.emitOne=void 0,t.emitMany=void 0,t.reject=void 0}})}[Symbol.asyncIterator](){let e=0;return{next:async()=>{do{if(this._state===2)throw this._error;if(e<this._results.length)return{done:!1,value:this._results[e++]};if(this._state===1)return{done:!0,value:void 0};await Bi.toPromise(this._onStateChanged.event)}while(1)},return:async()=>(this._onReturn?.(),{done:!0,value:void 0})}}static map(t,n){return new e(async e=>{for await(let r of t)e.emitOne(n(r))})}map(t){return e.map(this,t)}static filter(t,n){return new e(async e=>{for await(let r of t)n(r)&&e.emitOne(r)})}filter(t){return e.filter(this,t)}static coalesce(t){return e.filter(t,e=>!!e)}coalesce(){return e.coalesce(this)}static async toPromise(e){let t=[];for await(let n of e)t.push(n);return t}toPromise(){return e.toPromise(this)}emitOne(e){this._state===0&&(this._results.push(e),this._onStateChanged.fire())}emitMany(e){this._state===0&&(this._results=this._results.concat(e),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(e){this._state===0&&(this._state=2,this._error=e,this._onStateChanged.fire())}};no.EMPTY=no.fromArray([]);function ro(e){return io(e,0)}function io(e,t){switch(typeof e){case`object`:return e===null?ao(349,t):Array.isArray(e)?co(e,t):lo(e,t);case`string`:return so(e,t);case`boolean`:return oo(e,t);case`number`:return ao(e,t);case`undefined`:return ao(937,t);default:return ao(617,t)}}function ao(e,t){return(t<<5)-t+e|0}function oo(e,t){return ao(e?433:863,t)}function so(e,t){t=ao(149417,t);for(let n=0,r=e.length;n<r;n++)t=ao(e.charCodeAt(n),t);return t}function co(e,t){return t=ao(104579,t),e.reduce((e,t)=>io(t,e),t)}function lo(e,t){return t=ao(181387,t),Object.keys(e).sort().reduce((t,n)=>(t=so(n,t),io(e[n],t)),t)}var{registerWindow:uo,getWindow:fo,getDocument:po,getWindows:mo,getWindowsCount:ho,getWindowId:go,getWindowById:_o,hasWindow:vo,onDidRegisterWindow:yo,onWillUnregisterWindow:bo,onDidUnregisterWindow:xo}=function(){let e=new Map,t={window:Pi,disposables:new Mi};e.set(Pi.vscodeWindowId,t);let n=new W,r=new W,i=new W;function a(n,r){return(typeof n==`number`?e.get(n):void 0)??(r?t:void 0)}return{onDidRegisterWindow:n.event,onWillUnregisterWindow:i.event,onDidUnregisterWindow:r.event,registerWindow(t){if(e.has(t.vscodeWindowId))return U.None;let a=new Mi,o={window:t,disposables:a.add(new Mi)};return e.set(t.vscodeWindowId,o),a.add(H(()=>{e.delete(t.vscodeWindowId),r.fire(t)})),a.add(G(t,jo.BEFORE_UNLOAD,()=>{i.fire(t)})),n.fire(o),a},getWindows(){return e.values()},getWindowsCount(){return e.size},getWindowId(e){return e.vscodeWindowId},hasWindow(t){return e.has(t)},getWindowById:a,getWindow(e){let t=e;if(t?.ownerDocument?.defaultView)return t.ownerDocument.defaultView.window;let n=e;return n?.view?n.view.window:Pi},getDocument(e){return fo(e).document}}}(),So=class{constructor(e,t,n,r){this._node=e,this._type=t,this._handler=n,this._options=r||!1,this._node.addEventListener(this._type,this._handler,this._options)}dispose(){this._handler&&=(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,null)}};function G(e,t,n,r){return new So(e,t,n,r)}function Co(e,t){return function(n){return t(new Ja(e,n))}}function wo(e){return function(t){return e(new Wa(t))}}var To=function(e,t,n,r){let i=n;return t===`click`||t===`mousedown`||t===`contextmenu`?i=Co(fo(e),n):(t===`keydown`||t===`keypress`||t===`keyup`)&&(i=wo(n)),G(e,t,i,r)},Eo,Do=class extends eo{constructor(e){super(),this.defaultTarget=e&&fo(e)}cancelAndSet(e,t,n){return super.cancelAndSet(e,t,n??this.defaultTarget)}},Oo=class{constructor(e,t=0){this._runner=e,this.priority=t,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(e){fi(e)}}static sort(e,t){return t.priority-e.priority}};(function(){let e=new Map,t=new Map,n=new Map,r=new Map,i=i=>{n.set(i,!1);let a=e.get(i)??[];for(t.set(i,a),e.set(i,[]),r.set(i,!0);a.length>0;)a.sort(Oo.sort),a.shift().execute();r.set(i,!1)};Eo=(t,r,a=0)=>{let o=go(t),s=new Oo(r,a),c=e.get(o);return c||(c=[],e.set(o,c)),c.push(s),n.get(o)||(n.set(o,!0),t.requestAnimationFrame(()=>i(o))),s}})();var ko=class e{constructor(e,t){this.width=e,this.height=t}with(t=this.width,n=this.height){return t!==this.width||n!==this.height?new e(t,n):this}static is(e){return typeof e==`object`&&typeof e.height==`number`&&typeof e.width==`number`}static lift(t){return t instanceof e?t:new e(t.width,t.height)}static equals(e,t){return e===t?!0:!e||!t?!1:e.width===t.width&&e.height===t.height}};ko.None=new ko(0,0);function Ao(e){let t=e.getBoundingClientRect(),n=fo(e);return{left:t.left+n.scrollX,top:t.top+n.scrollY,width:t.width,height:t.height}}new class{constructor(){this.mutationObservers=new Map}observe(e,t,n){let r=this.mutationObservers.get(e);r||(r=new Map,this.mutationObservers.set(e,r));let i=ro(n),a=r.get(i);if(a)a.users+=1;else{let o=new W,s=new MutationObserver(e=>o.fire(e));s.observe(e,n);let c=a={users:1,observer:s,onDidMutate:o.event};t.add(H(()=>{--c.users,c.users===0&&(o.dispose(),s.disconnect(),r?.delete(i),r?.size===0&&this.mutationObservers.delete(e))})),r.set(i,a)}return a.onDidMutate}};var jo={CLICK:`click`,AUXCLICK:`auxclick`,DBLCLICK:`dblclick`,MOUSE_UP:`mouseup`,MOUSE_DOWN:`mousedown`,MOUSE_OVER:`mouseover`,MOUSE_MOVE:`mousemove`,MOUSE_OUT:`mouseout`,MOUSE_ENTER:`mouseenter`,MOUSE_LEAVE:`mouseleave`,MOUSE_WHEEL:`wheel`,POINTER_UP:`pointerup`,POINTER_DOWN:`pointerdown`,POINTER_MOVE:`pointermove`,POINTER_LEAVE:`pointerleave`,CONTEXT_MENU:`contextmenu`,WHEEL:`wheel`,KEY_DOWN:`keydown`,KEY_PRESS:`keypress`,KEY_UP:`keyup`,LOAD:`load`,BEFORE_UNLOAD:`beforeunload`,UNLOAD:`unload`,PAGE_SHOW:`pageshow`,PAGE_HIDE:`pagehide`,PASTE:`paste`,ABORT:`abort`,ERROR:`error`,RESIZE:`resize`,SCROLL:`scroll`,FULLSCREEN_CHANGE:`fullscreenchange`,WK_FULLSCREEN_CHANGE:`webkitfullscreenchange`,SELECT:`select`,CHANGE:`change`,SUBMIT:`submit`,RESET:`reset`,FOCUS:`focus`,FOCUS_IN:`focusin`,FOCUS_OUT:`focusout`,BLUR:`blur`,INPUT:`input`,STORAGE:`storage`,DRAG_START:`dragstart`,DRAG:`drag`,DRAG_ENTER:`dragenter`,DRAG_LEAVE:`dragleave`,DRAG_OVER:`dragover`,DROP:`drop`,DRAG_END:`dragend`,ANIMATION_START:aa?`webkitAnimationStart`:`animationstart`,ANIMATION_END:aa?`webkitAnimationEnd`:`animationend`,ANIMATION_ITERATION:aa?`webkitAnimationIteration`:`animationiteration`},Mo=class{constructor(e){this.domNode=e,this._maxWidth=``,this._width=``,this._height=``,this._top=``,this._left=``,this._bottom=``,this._right=``,this._paddingTop=``,this._paddingLeft=``,this._paddingBottom=``,this._paddingRight=``,this._fontFamily=``,this._fontWeight=``,this._fontSize=``,this._fontStyle=``,this._fontFeatureSettings=``,this._fontVariationSettings=``,this._textDecoration=``,this._lineHeight=``,this._letterSpacing=``,this._className=``,this._display=``,this._position=``,this._visibility=``,this._color=``,this._backgroundColor=``,this._layerHint=!1,this._contain=`none`,this._boxShadow=``}setMaxWidth(e){let t=No(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=No(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=No(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=No(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=No(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=No(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=No(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=No(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=No(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=No(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=No(e);this._paddingRight!==t&&(this._paddingRight=t,this.domNode.style.paddingRight=this._paddingRight)}setFontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.domNode.style.fontFamily=this._fontFamily)}setFontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.domNode.style.fontWeight=this._fontWeight)}setFontSize(e){let t=No(e);this._fontSize!==t&&(this._fontSize=t,this.domNode.style.fontSize=this._fontSize)}setFontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this.domNode.style.fontStyle=this._fontStyle)}setFontFeatureSettings(e){this._fontFeatureSettings!==e&&(this._fontFeatureSettings=e,this.domNode.style.fontFeatureSettings=this._fontFeatureSettings)}setFontVariationSettings(e){this._fontVariationSettings!==e&&(this._fontVariationSettings=e,this.domNode.style.fontVariationSettings=this._fontVariationSettings)}setTextDecoration(e){this._textDecoration!==e&&(this._textDecoration=e,this.domNode.style.textDecoration=this._textDecoration)}setLineHeight(e){let t=No(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=No(e);this._letterSpacing!==t&&(this._letterSpacing=t,this.domNode.style.letterSpacing=this._letterSpacing)}setClassName(e){this._className!==e&&(this._className=e,this.domNode.className=this._className)}toggleClassName(e,t){this.domNode.classList.toggle(e,t),this._className=this.domNode.className}setDisplay(e){this._display!==e&&(this._display=e,this.domNode.style.display=this._display)}setPosition(e){this._position!==e&&(this._position=e,this.domNode.style.position=this._position)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this.domNode.style.visibility=this._visibility)}setColor(e){this._color!==e&&(this._color=e,this.domNode.style.color=this._color)}setBackgroundColor(e){this._backgroundColor!==e&&(this._backgroundColor=e,this.domNode.style.backgroundColor=this._backgroundColor)}setLayerHinting(e){this._layerHint!==e&&(this._layerHint=e,this.domNode.style.transform=this._layerHint?`translate3d(0px, 0px, 0px)`:``)}setBoxShadow(e){this._boxShadow!==e&&(this._boxShadow=e,this.domNode.style.boxShadow=e)}setContain(e){this._contain!==e&&(this._contain=e,this.domNode.style.contain=this._contain)}setAttribute(e,t){this.domNode.setAttribute(e,t)}removeAttribute(e){this.domNode.removeAttribute(e)}appendChild(e){this.domNode.appendChild(e.domNode)}removeChild(e){this.domNode.removeChild(e.domNode)}};function No(e){return typeof e==`number`?`${e}px`:e}function Po(e){return new Mo(e)}var Fo=class{constructor(){this._hooks=new Mi,this._pointerMoveCallback=null,this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(e,t){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;let n=this._onStopCallback;this._onStopCallback=null,e&&n&&n(t)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(e,t,n,r,i){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=r,this._onStopCallback=i;let a=e;try{e.setPointerCapture(t),this._hooks.add(H(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{a=fo(e)}this._hooks.add(G(a,jo.POINTER_MOVE,e=>{e.buttons===n?(e.preventDefault(),this._pointerMoveCallback(e)):this.stopMonitoring(!0)})),this._hooks.add(G(a,jo.POINTER_UP,e=>this.stopMonitoring(!0)))}};function Io(e,t,n){let r=null,i=null;if(typeof n.value==`function`?(r=`value`,i=n.value,i.length!==0&&console.warn(`Memoize should only be used in functions with zero parameters`)):typeof n.get==`function`&&(r=`get`,i=n.get),!i)throw Error(`not supported`);let a=`$memoize$${t}`;n[r]=function(...e){return this.hasOwnProperty(a)||Object.defineProperty(this,a,{configurable:!1,enumerable:!1,writable:!1,value:i.apply(this,e)}),this[a]}}var Lo;(e=>(e.Tap=`-xterm-gesturetap`,e.Change=`-xterm-gesturechange`,e.Start=`-xterm-gesturestart`,e.End=`-xterm-gesturesend`,e.Contextmenu=`-xterm-gesturecontextmenu`))(Lo||={});var Ro=class e extends U{constructor(){super(),this.dispatched=!1,this.targets=new Li,this.ignoreTargets=new Li,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(Bi.runAndSubscribe(yo,({window:e,disposables:t})=>{t.add(G(e.document,`touchstart`,e=>this.onTouchStart(e),{passive:!1})),t.add(G(e.document,`touchend`,t=>this.onTouchEnd(e,t))),t.add(G(e.document,`touchmove`,e=>this.onTouchMove(e),{passive:!1}))},{window:Pi,disposables:this._store}))}static addTarget(t){return e.isTouchDevice()?(e.INSTANCE||=Oi(new e),H(e.INSTANCE.targets.push(t))):U.None}static ignoreTarget(t){return e.isTouchDevice()?(e.INSTANCE||=Oi(new e),H(e.INSTANCE.ignoreTargets.push(t))):U.None}static isTouchDevice(){return`ontouchstart`in Pi||navigator.maxTouchPoints>0}dispose(){this.handle&&=(this.handle.dispose(),null),super.dispose()}onTouchStart(e){let t=Date.now();this.handle&&=(this.handle.dispose(),null);for(let n=0,r=e.targetTouches.length;n<r;n++){let r=e.targetTouches.item(n);this.activeTouches[r.identifier]={id:r.identifier,initialTarget:r.target,initialTimeStamp:t,initialPageX:r.pageX,initialPageY:r.pageY,rollingTimestamps:[t],rollingPageX:[r.pageX],rollingPageY:[r.pageY]};let i=this.newGestureEvent(Lo.Start,r.target);i.pageX=r.pageX,i.pageY=r.pageY,this.dispatchEvent(i)}this.dispatched&&=(e.preventDefault(),e.stopPropagation(),!1)}onTouchEnd(t,n){let r=Date.now(),i=Object.keys(this.activeTouches).length;for(let a=0,o=n.changedTouches.length;a<o;a++){let o=n.changedTouches.item(a);if(!this.activeTouches.hasOwnProperty(String(o.identifier))){console.warn(`move of an UNKNOWN touch`,o);continue}let s=this.activeTouches[o.identifier],c=Date.now()-s.initialTimeStamp;if(c<e.HOLD_DELAY&&Math.abs(s.initialPageX-yi(s.rollingPageX))<30&&Math.abs(s.initialPageY-yi(s.rollingPageY))<30){let e=this.newGestureEvent(Lo.Tap,s.initialTarget);e.pageX=yi(s.rollingPageX),e.pageY=yi(s.rollingPageY),this.dispatchEvent(e)}else if(c>=e.HOLD_DELAY&&Math.abs(s.initialPageX-yi(s.rollingPageX))<30&&Math.abs(s.initialPageY-yi(s.rollingPageY))<30){let e=this.newGestureEvent(Lo.Contextmenu,s.initialTarget);e.pageX=yi(s.rollingPageX),e.pageY=yi(s.rollingPageY),this.dispatchEvent(e)}else if(i===1){let e=yi(s.rollingPageX),n=yi(s.rollingPageY),i=yi(s.rollingTimestamps)-s.rollingTimestamps[0],a=e-s.rollingPageX[0],o=n-s.rollingPageY[0],c=[...this.targets].filter(e=>s.initialTarget instanceof Node&&e.contains(s.initialTarget));this.inertia(t,c,r,Math.abs(a)/i,a>0?1:-1,e,Math.abs(o)/i,o>0?1:-1,n)}this.dispatchEvent(this.newGestureEvent(Lo.End,s.initialTarget)),delete this.activeTouches[o.identifier]}this.dispatched&&=(n.preventDefault(),n.stopPropagation(),!1)}newGestureEvent(e,t){let n=document.createEvent(`CustomEvent`);return n.initEvent(e,!1,!0),n.initialTarget=t,n.tapCount=0,n}dispatchEvent(t){if(t.type===Lo.Tap){let n=new Date().getTime(),r=0;r=n-this._lastSetTapCountTime>e.CLEAR_TAP_COUNT_TIME?1:2,this._lastSetTapCountTime=n,t.tapCount=r}else(t.type===Lo.Change||t.type===Lo.Contextmenu)&&(this._lastSetTapCountTime=0);if(t.initialTarget instanceof Node){for(let e of this.ignoreTargets)if(e.contains(t.initialTarget))return;let e=[];for(let n of this.targets)if(n.contains(t.initialTarget)){let r=0,i=t.initialTarget;for(;i&&i!==n;)r++,i=i.parentElement;e.push([r,n])}e.sort((e,t)=>e[0]-t[0]);for(let[n,r]of e)r.dispatchEvent(t),this.dispatched=!0}}inertia(t,n,r,i,a,o,s,c,l){this.handle=Eo(t,()=>{let u=Date.now(),d=u-r,f=0,p=0,m=!0;i+=e.SCROLL_FRICTION*d,s+=e.SCROLL_FRICTION*d,i>0&&(m=!1,f=a*i*d),s>0&&(m=!1,p=c*s*d);let h=this.newGestureEvent(Lo.Change);h.translationX=f,h.translationY=p,n.forEach(e=>e.dispatchEvent(h)),m||this.inertia(t,n,u,i,a,o+f,s,c,l+p)})}onTouchMove(e){let t=Date.now();for(let n=0,r=e.changedTouches.length;n<r;n++){let r=e.changedTouches.item(n);if(!this.activeTouches.hasOwnProperty(String(r.identifier))){console.warn(`end of an UNKNOWN touch`,r);continue}let i=this.activeTouches[r.identifier],a=this.newGestureEvent(Lo.Change,i.initialTarget);a.translationX=r.pageX-yi(i.rollingPageX),a.translationY=r.pageY-yi(i.rollingPageY),a.pageX=r.pageX,a.pageY=r.pageY,this.dispatchEvent(a),i.rollingPageX.length>3&&(i.rollingPageX.shift(),i.rollingPageY.shift(),i.rollingTimestamps.shift()),i.rollingPageX.push(r.pageX),i.rollingPageY.push(r.pageY),i.rollingTimestamps.push(t)}this.dispatched&&=(e.preventDefault(),e.stopPropagation(),!1)}};Ro.SCROLL_FRICTION=-.005,Ro.HOLD_DELAY=700,Ro.CLEAR_TAP_COUNT_TIME=400,z([Io],Ro,`isTouchDevice`,1);var zo=Ro,Bo=class extends U{onclick(e,t){this._register(G(e,jo.CLICK,n=>t(new Ja(fo(e),n))))}onmousedown(e,t){this._register(G(e,jo.MOUSE_DOWN,n=>t(new Ja(fo(e),n))))}onmouseover(e,t){this._register(G(e,jo.MOUSE_OVER,n=>t(new Ja(fo(e),n))))}onmouseleave(e,t){this._register(G(e,jo.MOUSE_LEAVE,n=>t(new Ja(fo(e),n))))}onkeydown(e,t){this._register(G(e,jo.KEY_DOWN,e=>t(new Wa(e))))}onkeyup(e,t){this._register(G(e,jo.KEY_UP,e=>t(new Wa(e))))}oninput(e,t){this._register(G(e,jo.INPUT,t))}onblur(e,t){this._register(G(e,jo.BLUR,t))}onfocus(e,t){this._register(G(e,jo.FOCUS,t))}onchange(e,t){this._register(G(e,jo.CHANGE,t))}ignoreGesture(e){return zo.ignoreTarget(e)}},Vo=11,Ho=class extends Bo{constructor(e){super(),this._onActivate=e.onActivate,this.bgDomNode=document.createElement(`div`),this.bgDomNode.className=`arrow-background`,this.bgDomNode.style.position=`absolute`,this.bgDomNode.style.width=e.bgWidth+`px`,this.bgDomNode.style.height=e.bgHeight+`px`,typeof e.top<`u`&&(this.bgDomNode.style.top=`0px`),typeof e.left<`u`&&(this.bgDomNode.style.left=`0px`),typeof e.bottom<`u`&&(this.bgDomNode.style.bottom=`0px`),typeof e.right<`u`&&(this.bgDomNode.style.right=`0px`),this.domNode=document.createElement(`div`),this.domNode.className=e.className,this.domNode.style.position=`absolute`,this.domNode.style.width=Vo+`px`,this.domNode.style.height=Vo+`px`,typeof e.top<`u`&&(this.domNode.style.top=e.top+`px`),typeof e.left<`u`&&(this.domNode.style.left=e.left+`px`),typeof e.bottom<`u`&&(this.domNode.style.bottom=e.bottom+`px`),typeof e.right<`u`&&(this.domNode.style.right=e.right+`px`),this._pointerMoveMonitor=this._register(new Fo),this._register(To(this.bgDomNode,jo.POINTER_DOWN,e=>this._arrowPointerDown(e))),this._register(To(this.domNode,jo.POINTER_DOWN,e=>this._arrowPointerDown(e))),this._pointerdownRepeatTimer=this._register(new Do),this._pointerdownScheduleRepeatTimer=this._register(new $a)}_arrowPointerDown(e){e.target&&e.target instanceof Element&&(this._onActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet(()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,fo(e))},200),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,e=>{},()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()}),e.preventDefault())}},Uo=class e{constructor(e,t,n,r,i,a,o){this._forceIntegerValues=e,this._scrollStateBrand=void 0,this._forceIntegerValues&&(t|=0,n|=0,r|=0,i|=0,a|=0,o|=0),this.rawScrollLeft=r,this.rawScrollTop=o,t<0&&(t=0),r+t>n&&(r=n-t),r<0&&(r=0),i<0&&(i=0),o+i>a&&(o=a-i),o<0&&(o=0),this.width=t,this.scrollWidth=n,this.scrollLeft=r,this.height=i,this.scrollHeight=a,this.scrollTop=o}equals(e){return this.rawScrollLeft===e.rawScrollLeft&&this.rawScrollTop===e.rawScrollTop&&this.width===e.width&&this.scrollWidth===e.scrollWidth&&this.scrollLeft===e.scrollLeft&&this.height===e.height&&this.scrollHeight===e.scrollHeight&&this.scrollTop===e.scrollTop}withScrollDimensions(t,n){return new e(this._forceIntegerValues,typeof t.width<`u`?t.width:this.width,typeof t.scrollWidth<`u`?t.scrollWidth:this.scrollWidth,n?this.rawScrollLeft:this.scrollLeft,typeof t.height<`u`?t.height:this.height,typeof t.scrollHeight<`u`?t.scrollHeight:this.scrollHeight,n?this.rawScrollTop:this.scrollTop)}withScrollPosition(t){return new e(this._forceIntegerValues,this.width,this.scrollWidth,typeof t.scrollLeft<`u`?t.scrollLeft:this.rawScrollLeft,this.height,this.scrollHeight,typeof t.scrollTop<`u`?t.scrollTop:this.rawScrollTop)}createScrollEvent(e,t){let n=this.width!==e.width,r=this.scrollWidth!==e.scrollWidth,i=this.scrollLeft!==e.scrollLeft,a=this.height!==e.height,o=this.scrollHeight!==e.scrollHeight,s=this.scrollTop!==e.scrollTop;return{inSmoothScrolling:t,oldWidth:e.width,oldScrollWidth:e.scrollWidth,oldScrollLeft:e.scrollLeft,width:this.width,scrollWidth:this.scrollWidth,scrollLeft:this.scrollLeft,oldHeight:e.height,oldScrollHeight:e.scrollHeight,oldScrollTop:e.scrollTop,height:this.height,scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,widthChanged:n,scrollWidthChanged:r,scrollLeftChanged:i,heightChanged:a,scrollHeightChanged:o,scrollTopChanged:s}}},Wo=class extends U{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new W),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new Uo(e.forceIntegerValues,0,0,0,0,0,0),this._smoothScrolling=null}dispose(){this._smoothScrolling&&=(this._smoothScrolling.dispose(),null),super.dispose()}setSmoothScrollDuration(e){this._smoothScrollDuration=e}validateScrollPosition(e){return this._state.withScrollPosition(e)}getScrollDimensions(){return this._state}setScrollDimensions(e,t){let n=this._state.withScrollDimensions(e,t);this._setState(n,!!this._smoothScrolling),this._smoothScrolling?.acceptScrollDimensions(this._state)}getFutureScrollPosition(){return this._smoothScrolling?this._smoothScrolling.to:this._state}getCurrentScrollPosition(){return this._state}setScrollPositionNow(e){let t=this._state.withScrollPosition(e);this._smoothScrolling&&=(this._smoothScrolling.dispose(),null),this._setState(t,!1)}setScrollPositionSmooth(e,t){if(this._smoothScrollDuration===0)return this.setScrollPositionNow(e);if(this._smoothScrolling){e={scrollLeft:typeof e.scrollLeft>`u`?this._smoothScrolling.to.scrollLeft:e.scrollLeft,scrollTop:typeof e.scrollTop>`u`?this._smoothScrolling.to.scrollTop:e.scrollTop};let n=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===n.scrollLeft&&this._smoothScrolling.to.scrollTop===n.scrollTop)return;let r;r=t?new Jo(this._smoothScrolling.from,n,this._smoothScrolling.startTime,this._smoothScrolling.duration):this._smoothScrolling.combine(this._state,n,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=r}else{let t=this._state.withScrollPosition(e);this._smoothScrolling=Jo.start(this._state,t,this._smoothScrollDuration)}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}hasPendingScrollAnimation(){return!!this._smoothScrolling}_performSmoothScrolling(){if(!this._smoothScrolling)return;let e=this._smoothScrolling.tick(),t=this._state.withScrollPosition(e);if(this._setState(t,!0),this._smoothScrolling){if(e.isDone){this._smoothScrolling.dispose(),this._smoothScrolling=null;return}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}}_setState(e,t){let n=this._state;n.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(n,t)))}},Go=class{constructor(e,t,n){this.scrollLeft=e,this.scrollTop=t,this.isDone=n}};function Ko(e,t){let n=t-e;return function(t){return e+n*Xo(t)}}function qo(e,t,n){return function(r){return r<n?e(r/n):t((r-n)/(1-n))}}var Jo=class e{constructor(e,t,n,r){this.from=e,this.to=t,this.duration=r,this.startTime=n,this.animationFrameDisposable=null,this._initAnimations()}_initAnimations(){this.scrollLeft=this._initAnimation(this.from.scrollLeft,this.to.scrollLeft,this.to.width),this.scrollTop=this._initAnimation(this.from.scrollTop,this.to.scrollTop,this.to.height)}_initAnimation(e,t,n){if(Math.abs(e-t)>2.5*n){let r,i;return e<t?(r=e+.75*n,i=t-.75*n):(r=e-.75*n,i=t+.75*n),qo(Ko(e,r),Ko(i,t),.33)}return Ko(e,t)}dispose(){this.animationFrameDisposable!==null&&(this.animationFrameDisposable.dispose(),this.animationFrameDisposable=null)}acceptScrollDimensions(e){this.to=e.withScrollPosition(this.to),this._initAnimations()}tick(){return this._tick(Date.now())}_tick(e){let t=(e-this.startTime)/this.duration;return t<1?new Go(this.scrollLeft(t),this.scrollTop(t),!1):new Go(this.to.scrollLeft,this.to.scrollTop,!0)}combine(t,n,r){return e.start(t,n,r)}static start(t,n,r){r+=10;let i=Date.now()-10;return new e(t,n,i,r)}};function Yo(e){return e**3}function Xo(e){return 1-Yo(1-e)}var Zo=class extends U{constructor(e,t,n){super(),this._visibility=e,this._visibleClassName=t,this._invisibleClassName=n,this._domNode=null,this._isVisible=!1,this._isNeeded=!1,this._rawShouldBeVisible=!1,this._shouldBeVisible=!1,this._revealTimer=this._register(new $a)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this._updateShouldBeVisible())}setShouldBeVisible(e){this._rawShouldBeVisible=e,this._updateShouldBeVisible()}_applyVisibilitySetting(){return this._visibility===2?!1:this._visibility===3||this._rawShouldBeVisible}_updateShouldBeVisible(){let e=this._applyVisibilitySetting();this._shouldBeVisible!==e&&(this._shouldBeVisible=e,this.ensureVisibility())}setIsNeeded(e){this._isNeeded!==e&&(this._isNeeded=e,this.ensureVisibility())}setDomNode(e){this._domNode=e,this._domNode.setClassName(this._invisibleClassName),this.setShouldBeVisible(!1)}ensureVisibility(){this._isNeeded?this._shouldBeVisible?this._reveal():this._hide(!0):this._hide(!1)}_reveal(){this._isVisible||(this._isVisible=!0,this._revealTimer.setIfNotSet(()=>{this._domNode?.setClassName(this._visibleClassName)},0))}_hide(e){this._revealTimer.cancel(),this._isVisible&&(this._isVisible=!1,this._domNode?.setClassName(this._invisibleClassName+(e?` fade`:``)))}},Qo=140,$o=class extends Bo{constructor(e){super(),this._lazyRender=e.lazyRender,this._host=e.host,this._scrollable=e.scrollable,this._scrollByPage=e.scrollByPage,this._scrollbarState=e.scrollbarState,this._visibilityController=this._register(new Zo(e.visibility,`visible scrollbar `+e.extraScrollbarClassName,`invisible scrollbar `+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new Fo),this._shouldRender=!0,this.domNode=Po(document.createElement(`div`)),this.domNode.setAttribute(`role`,`presentation`),this.domNode.setAttribute(`aria-hidden`,`true`),this._visibilityController.setDomNode(this.domNode),this.domNode.setPosition(`absolute`),this._register(G(this.domNode.domNode,jo.POINTER_DOWN,e=>this._domNodePointerDown(e)))}_createArrow(e){let t=this._register(new Ho(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,n,r){this.slider=Po(document.createElement(`div`)),this.slider.setClassName(`slider`),this.slider.setPosition(`absolute`),this.slider.setTop(e),this.slider.setLeft(t),typeof n==`number`&&this.slider.setWidth(n),typeof r==`number`&&this.slider.setHeight(r),this.slider.setLayerHinting(!0),this.slider.setContain(`strict`),this.domNode.domNode.appendChild(this.slider.domNode),this._register(G(this.slider.domNode,jo.POINTER_DOWN,e=>{e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))})),this.onclick(this.slider.domNode,e=>{e.leftButton&&e.stopPropagation()})}_onElementSize(e){return this._scrollbarState.setVisibleSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollSize(e){return this._scrollbarState.setScrollSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollPosition(e){return this._scrollbarState.setScrollPosition(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}beginReveal(){this._visibilityController.setShouldBeVisible(!0)}beginHide(){this._visibilityController.setShouldBeVisible(!1)}render(){this._shouldRender&&(this._shouldRender=!1,this._renderDomNode(this._scrollbarState.getRectangleLargeSize(),this._scrollbarState.getRectangleSmallSize()),this._updateSlider(this._scrollbarState.getSliderSize(),this._scrollbarState.getArrowSize()+this._scrollbarState.getSliderPosition()))}_domNodePointerDown(e){e.target===this.domNode.domNode&&this._onPointerDown(e)}delegatePointerDown(e){let t=this.domNode.domNode.getClientRects()[0].top,n=t+this._scrollbarState.getSliderPosition(),r=t+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),i=this._sliderPointerPosition(e);n<=i&&i<=r?e.button===0&&(e.preventDefault(),this._sliderPointerDown(e)):this._onPointerDown(e)}_onPointerDown(e){let t,n;if(e.target===this.domNode.domNode&&typeof e.offsetX==`number`&&typeof e.offsetY==`number`)t=e.offsetX,n=e.offsetY;else{let r=Ao(this.domNode.domNode);t=e.pageX-r.left,n=e.pageY-r.top}let r=this._pointerDownRelativePosition(t,n);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(r):this._scrollbarState.getDesiredScrollPositionFromOffset(r)),e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))}_sliderPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=this._sliderPointerPosition(e),n=this._sliderOrthogonalPointerPosition(e),r=this._scrollbarState.clone();this.slider.toggleClassName(`active`,!0),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,e=>{let i=this._sliderOrthogonalPointerPosition(e),a=Math.abs(i-n);if(xa&&a>Qo){this._setDesiredScrollPositionNow(r.getScrollPosition());return}let o=this._sliderPointerPosition(e)-t;this._setDesiredScrollPositionNow(r.getDesiredScrollPositionFromDelta(o))},()=>{this.slider.toggleClassName(`active`,!1),this._host.onDragEnd()}),this._host.onDragStart()}_setDesiredScrollPositionNow(e){let t={};this.writeScrollPosition(t,e),this._scrollable.setScrollPositionNow(t)}updateScrollbarSize(e){this._updateScrollbarSize(e),this._scrollbarState.setScrollbarSize(e),this._shouldRender=!0,this._lazyRender||this.render()}isNeeded(){return this._scrollbarState.isNeeded()}},es=class e{constructor(e,t,n,r,i,a){this._scrollbarSize=Math.round(t),this._oppositeScrollbarSize=Math.round(n),this._arrowSize=Math.round(e),this._visibleSize=r,this._scrollSize=i,this._scrollPosition=a,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new e(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(e){let t=Math.round(e);return this._visibleSize!==t&&(this._visibleSize=t,this._refreshComputedValues(),!0)}setScrollSize(e){let t=Math.round(e);return this._scrollSize!==t&&(this._scrollSize=t,this._refreshComputedValues(),!0)}setScrollPosition(e){let t=Math.round(e);return this._scrollPosition!==t&&(this._scrollPosition=t,this._refreshComputedValues(),!0)}setScrollbarSize(e){this._scrollbarSize=Math.round(e)}setOppositeScrollbarSize(e){this._oppositeScrollbarSize=Math.round(e)}static _computeValues(e,t,n,r,i){let a=Math.max(0,n-e),o=Math.max(0,a-2*t),s=r>0&&r>n;if(!s)return{computedAvailableSize:Math.round(a),computedIsNeeded:s,computedSliderSize:Math.round(o),computedSliderRatio:0,computedSliderPosition:0};let c=Math.round(Math.max(20,Math.floor(n*o/r))),l=(o-c)/(r-n),u=i*l;return{computedAvailableSize:Math.round(a),computedIsNeeded:s,computedSliderSize:Math.round(c),computedSliderRatio:l,computedSliderPosition:Math.round(u)}}_refreshComputedValues(){let t=e._computeValues(this._oppositeScrollbarSize,this._arrowSize,this._visibleSize,this._scrollSize,this._scrollPosition);this._computedAvailableSize=t.computedAvailableSize,this._computedIsNeeded=t.computedIsNeeded,this._computedSliderSize=t.computedSliderSize,this._computedSliderRatio=t.computedSliderRatio,this._computedSliderPosition=t.computedSliderPosition}getArrowSize(){return this._arrowSize}getScrollPosition(){return this._scrollPosition}getRectangleLargeSize(){return this._computedAvailableSize}getRectangleSmallSize(){return this._scrollbarSize}isNeeded(){return this._computedIsNeeded}getSliderSize(){return this._computedSliderSize}getSliderPosition(){return this._computedSliderPosition}getDesiredScrollPositionFromOffset(e){if(!this._computedIsNeeded)return 0;let t=e-this._arrowSize-this._computedSliderSize/2;return Math.round(t/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(e){if(!this._computedIsNeeded)return 0;let t=e-this._arrowSize,n=this._scrollPosition;return t<this._computedSliderPosition?n-=this._visibleSize:n+=this._visibleSize,n}getDesiredScrollPositionFromDelta(e){if(!this._computedIsNeeded)return 0;let t=this._computedSliderPosition+e;return Math.round(t/this._computedSliderRatio)}},ts=class extends $o{constructor(e,t,n){let r=e.getScrollDimensions(),i=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:n,scrollbarState:new es(t.horizontalHasArrows?t.arrowSize:0,t.horizontal===2?0:t.horizontalScrollbarSize,t.vertical===2?0:t.verticalScrollbarSize,r.width,r.scrollWidth,i.scrollLeft),visibility:t.horizontal,extraScrollbarClassName:`horizontal`,scrollable:e,scrollByPage:t.scrollByPage}),t.horizontalHasArrows)throw Error(`horizontalHasArrows is not supported in xterm.js`);this._createSlider(Math.floor((t.horizontalScrollbarSize-t.horizontalSliderSize)/2),0,void 0,t.horizontalSliderSize)}_updateSlider(e,t){this.slider.setWidth(e),this.slider.setLeft(t)}_renderDomNode(e,t){this.domNode.setWidth(e),this.domNode.setHeight(t),this.domNode.setLeft(0),this.domNode.setBottom(0)}onDidScroll(e){return this._shouldRender=this._onElementScrollSize(e.scrollWidth)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(e.scrollLeft)||this._shouldRender,this._shouldRender=this._onElementSize(e.width)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(e,t){return e}_sliderPointerPosition(e){return e.pageX}_sliderOrthogonalPointerPosition(e){return e.pageY}_updateScrollbarSize(e){this.slider.setHeight(e)}writeScrollPosition(e,t){e.scrollLeft=t}updateOptions(e){this.updateScrollbarSize(e.horizontal===2?0:e.horizontalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(e.vertical===2?0:e.verticalScrollbarSize),this._visibilityController.setVisibility(e.horizontal),this._scrollByPage=e.scrollByPage}},ns=class extends $o{constructor(e,t,n){let r=e.getScrollDimensions(),i=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:n,scrollbarState:new es(t.verticalHasArrows?t.arrowSize:0,t.vertical===2?0:t.verticalScrollbarSize,0,r.height,r.scrollHeight,i.scrollTop),visibility:t.vertical,extraScrollbarClassName:`vertical`,scrollable:e,scrollByPage:t.scrollByPage}),t.verticalHasArrows)throw Error(`horizontalHasArrows is not supported in xterm.js`);this._createSlider(0,Math.floor((t.verticalScrollbarSize-t.verticalSliderSize)/2),t.verticalSliderSize,void 0)}_updateSlider(e,t){this.slider.setHeight(e),this.slider.setTop(t)}_renderDomNode(e,t){this.domNode.setWidth(t),this.domNode.setHeight(e),this.domNode.setRight(0),this.domNode.setTop(0)}onDidScroll(e){return this._shouldRender=this._onElementScrollSize(e.scrollHeight)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(e.scrollTop)||this._shouldRender,this._shouldRender=this._onElementSize(e.height)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(e,t){return t}_sliderPointerPosition(e){return e.pageY}_sliderOrthogonalPointerPosition(e){return e.pageX}_updateScrollbarSize(e){this.slider.setWidth(e)}writeScrollPosition(e,t){e.scrollTop=t}updateOptions(e){this.updateScrollbarSize(e.vertical===2?0:e.verticalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(0),this._visibilityController.setVisibility(e.vertical),this._scrollByPage=e.scrollByPage}},rs=500,is=50,as=!0,os=class{constructor(e,t,n){this.timestamp=e,this.deltaX=t,this.deltaY=n,this.score=0}},ss=class{constructor(){this._capacity=5,this._memory=[],this._front=-1,this._rear=-1}isPhysicalMouseWheel(){if(this._front===-1&&this._rear===-1)return!1;let e=1,t=0,n=1,r=this._rear;do{let i=r===this._front?e:2**-n;if(e-=i,t+=this._memory[r].score*i,r===this._front)break;r=(this._capacity+r-1)%this._capacity,n++}while(1);return t<=.5}acceptStandardWheelEvent(e){if(oa){let t=na(fo(e.browserEvent));this.accept(Date.now(),e.deltaX*t,e.deltaY*t)}else this.accept(Date.now(),e.deltaX,e.deltaY)}accept(e,t,n){let r=null,i=new os(e,t,n);this._front===-1&&this._rear===-1?(this._memory[0]=i,this._front=0,this._rear=0):(r=this._memory[this._rear],this._rear=(this._rear+1)%this._capacity,this._rear===this._front&&(this._front=(this._front+1)%this._capacity),this._memory[this._rear]=i),i.score=this._computeScore(i,r)}_computeScore(e,t){if(Math.abs(e.deltaX)>0&&Math.abs(e.deltaY)>0)return 1;let n=.5;if((!this._isAlmostInt(e.deltaX)||!this._isAlmostInt(e.deltaY))&&(n+=.25),t){let r=Math.abs(e.deltaX),i=Math.abs(e.deltaY),a=Math.abs(t.deltaX),o=Math.abs(t.deltaY),s=Math.max(Math.min(r,a),1),c=Math.max(Math.min(i,o),1),l=Math.max(r,a),u=Math.max(i,o);l%s===0&&u%c===0&&(n-=.5)}return Math.min(Math.max(n,0),1)}_isAlmostInt(e){return Math.abs(Math.round(e)-e)<.01}};ss.INSTANCE=new ss;var cs=ss,ls=class extends Bo{constructor(e,t,n){super(),this._onScroll=this._register(new W),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new W),this.onWillScroll=this._onWillScroll.event,this._options=ds(t),this._scrollable=n,this._register(this._scrollable.onScroll(e=>{this._onWillScroll.fire(e),this._onDidScroll(e),this._onScroll.fire(e)}));let r={onMouseWheel:e=>this._onMouseWheel(e),onDragStart:()=>this._onDragStart(),onDragEnd:()=>this._onDragEnd()};this._verticalScrollbar=this._register(new ns(this._scrollable,this._options,r)),this._horizontalScrollbar=this._register(new ts(this._scrollable,this._options,r)),this._domNode=document.createElement(`div`),this._domNode.className=`xterm-scrollable-element `+this._options.className,this._domNode.setAttribute(`role`,`presentation`),this._domNode.style.position=`relative`,this._domNode.appendChild(e),this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode),this._domNode.appendChild(this._verticalScrollbar.domNode.domNode),this._options.useShadows?(this._leftShadowDomNode=Po(document.createElement(`div`)),this._leftShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=Po(document.createElement(`div`)),this._topShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=Po(document.createElement(`div`)),this._topLeftShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._topLeftShadowDomNode.domNode)):(this._leftShadowDomNode=null,this._topShadowDomNode=null,this._topLeftShadowDomNode=null),this._listenOnDomNode=this._options.listenOnDomNode||this._domNode,this._mouseWheelToDispose=[],this._setListeningToMouseWheel(this._options.handleMouseWheel),this.onmouseover(this._listenOnDomNode,e=>this._onMouseOver(e)),this.onmouseleave(this._listenOnDomNode,e=>this._onMouseLeave(e)),this._hideTimeout=this._register(new $a),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=ki(this._mouseWheelToDispose),super.dispose()}getDomNode(){return this._domNode}getOverviewRulerLayoutInfo(){return{parent:this._domNode,insertBefore:this._verticalScrollbar.domNode.domNode}}delegateVerticalScrollbarPointerDown(e){this._verticalScrollbar.delegatePointerDown(e)}getScrollDimensions(){return this._scrollable.getScrollDimensions()}setScrollDimensions(e){this._scrollable.setScrollDimensions(e,!1)}updateClassName(e){this._options.className=e,Sa&&(this._options.className+=` mac`),this._domNode.className=`xterm-scrollable-element `+this._options.className}updateOptions(e){typeof e.handleMouseWheel<`u`&&(this._options.handleMouseWheel=e.handleMouseWheel,this._setListeningToMouseWheel(this._options.handleMouseWheel)),typeof e.mouseWheelScrollSensitivity<`u`&&(this._options.mouseWheelScrollSensitivity=e.mouseWheelScrollSensitivity),typeof e.fastScrollSensitivity<`u`&&(this._options.fastScrollSensitivity=e.fastScrollSensitivity),typeof e.scrollPredominantAxis<`u`&&(this._options.scrollPredominantAxis=e.scrollPredominantAxis),typeof e.horizontal<`u`&&(this._options.horizontal=e.horizontal),typeof e.vertical<`u`&&(this._options.vertical=e.vertical),typeof e.horizontalScrollbarSize<`u`&&(this._options.horizontalScrollbarSize=e.horizontalScrollbarSize),typeof e.verticalScrollbarSize<`u`&&(this._options.verticalScrollbarSize=e.verticalScrollbarSize),typeof e.scrollByPage<`u`&&(this._options.scrollByPage=e.scrollByPage),this._horizontalScrollbar.updateOptions(this._options),this._verticalScrollbar.updateOptions(this._options),this._options.lazyRender||this._render()}setRevealOnScroll(e){this._revealOnScroll=e}delegateScrollFromMouseWheelEvent(e){this._onMouseWheel(new Ya(e))}_setListeningToMouseWheel(e){this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=ki(this._mouseWheelToDispose),e)&&this._mouseWheelToDispose.push(G(this._listenOnDomNode,jo.MOUSE_WHEEL,e=>{this._onMouseWheel(new Ya(e))},{passive:!1}))}_onMouseWheel(e){if(e.browserEvent?.defaultPrevented)return;let t=cs.INSTANCE;as&&t.acceptStandardWheelEvent(e);let n=!1;if(e.deltaY||e.deltaX){let r=e.deltaY*this._options.mouseWheelScrollSensitivity,i=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&i+r===0?i=r=0:Math.abs(r)>=Math.abs(i)?i=0:r=0),this._options.flipAxes&&([r,i]=[i,r]);let a=!Sa&&e.browserEvent&&e.browserEvent.shiftKey;(this._options.scrollYToX||a)&&!i&&(i=r,r=0),e.browserEvent&&e.browserEvent.altKey&&(i*=this._options.fastScrollSensitivity,r*=this._options.fastScrollSensitivity);let o=this._scrollable.getFutureScrollPosition(),s={};if(r){let e=is*r,t=o.scrollTop-(e<0?Math.floor(e):Math.ceil(e));this._verticalScrollbar.writeScrollPosition(s,t)}if(i){let e=is*i,t=o.scrollLeft-(e<0?Math.floor(e):Math.ceil(e));this._horizontalScrollbar.writeScrollPosition(s,t)}s=this._scrollable.validateScrollPosition(s),(o.scrollLeft!==s.scrollLeft||o.scrollTop!==s.scrollTop)&&(as&&this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(s):this._scrollable.setScrollPositionNow(s),n=!0)}let r=n;!r&&this._options.alwaysConsumeMouseWheel&&(r=!0),!r&&this._options.consumeMouseWheelIfScrollbarIsNeeded&&(this._verticalScrollbar.isNeeded()||this._horizontalScrollbar.isNeeded())&&(r=!0),r&&(e.preventDefault(),e.stopPropagation())}_onDidScroll(e){this._shouldRender=this._horizontalScrollbar.onDidScroll(e)||this._shouldRender,this._shouldRender=this._verticalScrollbar.onDidScroll(e)||this._shouldRender,this._options.useShadows&&(this._shouldRender=!0),this._revealOnScroll&&this._reveal(),this._options.lazyRender||this._render()}renderNow(){if(!this._options.lazyRender)throw Error("Please use `lazyRender` together with `renderNow`!");this._render()}_render(){if(this._shouldRender&&(this._shouldRender=!1,this._horizontalScrollbar.render(),this._verticalScrollbar.render(),this._options.useShadows)){let e=this._scrollable.getCurrentScrollPosition(),t=e.scrollTop>0,n=e.scrollLeft>0,r=n?` left`:``,i=t?` top`:``,a=n||t?` top-left-corner`:``;this._leftShadowDomNode.setClassName(`shadow${r}`),this._topShadowDomNode.setClassName(`shadow${i}`),this._topLeftShadowDomNode.setClassName(`shadow${a}${i}${r}`)}}_onDragStart(){this._isDragging=!0,this._reveal()}_onDragEnd(){this._isDragging=!1,this._hide()}_onMouseLeave(e){this._mouseIsOver=!1,this._hide()}_onMouseOver(e){this._mouseIsOver=!0,this._reveal()}_reveal(){this._verticalScrollbar.beginReveal(),this._horizontalScrollbar.beginReveal(),this._scheduleHide()}_hide(){!this._mouseIsOver&&!this._isDragging&&(this._verticalScrollbar.beginHide(),this._horizontalScrollbar.beginHide())}_scheduleHide(){!this._mouseIsOver&&!this._isDragging&&this._hideTimeout.cancelAndSet(()=>this._hide(),rs)}},us=class extends ls{constructor(e,t,n){super(e,t,n)}setScrollPosition(e){e.reuseAnimation?this._scrollable.setScrollPositionSmooth(e,e.reuseAnimation):this._scrollable.setScrollPositionNow(e)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}};function ds(e){let t={lazyRender:typeof e.lazyRender<`u`&&e.lazyRender,className:typeof e.className<`u`?e.className:``,useShadows:typeof e.useShadows<`u`?e.useShadows:!0,handleMouseWheel:typeof e.handleMouseWheel<`u`?e.handleMouseWheel:!0,flipAxes:typeof e.flipAxes<`u`&&e.flipAxes,consumeMouseWheelIfScrollbarIsNeeded:typeof e.consumeMouseWheelIfScrollbarIsNeeded<`u`&&e.consumeMouseWheelIfScrollbarIsNeeded,alwaysConsumeMouseWheel:typeof e.alwaysConsumeMouseWheel<`u`&&e.alwaysConsumeMouseWheel,scrollYToX:typeof e.scrollYToX<`u`&&e.scrollYToX,mouseWheelScrollSensitivity:typeof e.mouseWheelScrollSensitivity<`u`?e.mouseWheelScrollSensitivity:1,fastScrollSensitivity:typeof e.fastScrollSensitivity<`u`?e.fastScrollSensitivity:5,scrollPredominantAxis:typeof e.scrollPredominantAxis<`u`?e.scrollPredominantAxis:!0,mouseWheelSmoothScroll:typeof e.mouseWheelSmoothScroll<`u`?e.mouseWheelSmoothScroll:!0,arrowSize:typeof e.arrowSize<`u`?e.arrowSize:11,listenOnDomNode:typeof e.listenOnDomNode<`u`?e.listenOnDomNode:null,horizontal:typeof e.horizontal<`u`?e.horizontal:1,horizontalScrollbarSize:typeof e.horizontalScrollbarSize<`u`?e.horizontalScrollbarSize:10,horizontalSliderSize:typeof e.horizontalSliderSize<`u`?e.horizontalSliderSize:0,horizontalHasArrows:typeof e.horizontalHasArrows<`u`&&e.horizontalHasArrows,vertical:typeof e.vertical<`u`?e.vertical:1,verticalScrollbarSize:typeof e.verticalScrollbarSize<`u`?e.verticalScrollbarSize:10,verticalHasArrows:typeof e.verticalHasArrows<`u`&&e.verticalHasArrows,verticalSliderSize:typeof e.verticalSliderSize<`u`?e.verticalSliderSize:0,scrollByPage:typeof e.scrollByPage<`u`&&e.scrollByPage};return t.horizontalSliderSize=typeof e.horizontalSliderSize<`u`?e.horizontalSliderSize:t.horizontalScrollbarSize,t.verticalSliderSize=typeof e.verticalSliderSize<`u`?e.verticalSliderSize:t.verticalScrollbarSize,Sa&&(t.className+=` mac`),t}var fs=class extends U{constructor(e,t,n,r,i,a,o,s){super(),this._bufferService=n,this._optionsService=o,this._renderService=s,this._onRequestScrollLines=this._register(new W),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let c=this._register(new Wo({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:e=>Eo(r.window,e)}));this._register(this._optionsService.onSpecificOptionChange(`smoothScrollDuration`,()=>{c.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new us(t,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,...this._getChangeOptions()},c)),this._register(this._optionsService.onMultipleOptionChange([`scrollSensitivity`,`fastScrollSensitivity`,`overviewRuler`],()=>this._scrollableElement.updateOptions(this._getChangeOptions()))),this._register(i.onProtocolChange(e=>{this._scrollableElement.updateOptions({handleMouseWheel:!(e&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(Bi.runAndSubscribe(a.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=a.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(H(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=r.mainDocument.createElement(`style`),t.appendChild(this._styleElement),this._register(H(()=>this._styleElement.remove())),this._register(Bi.runAndSubscribe(a.onChangeColors,()=>{this._styleElement.textContent=[`.xterm .xterm-scrollable-element > .scrollbar > .slider {`,` background: ${a.colors.scrollbarSliderBackground.css};`,`}`,`.xterm .xterm-scrollable-element > .scrollbar > .slider:hover {`,` background: ${a.colors.scrollbarSliderHoverBackground.css};`,`}`,`.xterm .xterm-scrollable-element > .scrollbar > .slider.active {`,` background: ${a.colors.scrollbarSliderActiveBackground.css};`,`}`].join(`
15
+ `)})),this._register(this._bufferService.onResize(()=>this.queueSync())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._latestYDisp=void 0,this.queueSync()})),this._register(this._bufferService.onScroll(()=>this._sync())),this._register(this._scrollableElement.onScroll(e=>this._handleScroll(e)))}scrollLines(e){let t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:t.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,t){t&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!t,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:this._optionsService.rawOptions.overviewRuler?.width||14}}queueSync(e){e!==void 0&&(this._latestYDisp=e),this._queuedAnimationFrame===void 0&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback(()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)}))}_sync(e=this._bufferService.buffer.ydisp){!this._renderService||this._isSyncing||(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),n=t-this._bufferService.buffer.ydisp;n!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(n)),this._isHandlingScroll=!1}};fs=z([B(2,Gr),B(3,ii),B(4,Kr),B(5,li),B(6,Zr),B(7,oi)],fs);var ps=class extends U{constructor(e,t,n,r,i){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=n,this._decorationService=r,this._renderService=i,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement(`div`),this._container.classList.add(`xterm-decoration-container`),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this._register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this._register(this._decorationService.onDecorationRemoved(e=>this._removeDecoration(e))),this._register(H(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(let e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){let t=this._coreBrowserService.mainDocument.createElement(`div`);t.classList.add(`xterm-decoration`),t.classList.toggle(`xterm-decoration-top-layer`,e?.options?.layer===`top`),t.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,t.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,t.style.top=`${(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height}px`,t.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let n=e.options.x??0;return n&&n>this._bufferService.cols&&(t.style.display=`none`),this._refreshXPosition(e,t),t}_refreshStyle(e){let t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display=`none`,e.onRenderEmitter.fire(e.element));else{let n=this._decorationElements.get(e);n||(n=this._createElement(e),e.element=n,this._decorationElements.set(e,n),this._container.appendChild(n),e.onDispose(()=>{this._decorationElements.delete(e),n.remove()})),n.style.display=this._altBufferIsActive?`none`:`block`,this._altBufferIsActive||(n.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,n.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,n.style.top=`${t*this._renderService.dimensions.css.cell.height}px`,n.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),e.onRenderEmitter.fire(n)}}_refreshXPosition(e,t=e.element){if(!t)return;let n=e.options.x??0;(e.options.anchor||`left`)===`right`?t.style.right=n?`${n*this._renderService.dimensions.css.cell.width}px`:``:t.style.left=n?`${n*this._renderService.dimensions.css.cell.width}px`:``}_removeDecoration(e){this._decorationElements.get(e)?.remove(),this._decorationElements.delete(e),e.dispose()}};ps=z([B(1,Gr),B(2,ii),B(3,ei),B(4,oi)],ps);var ms=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(e){if(e.options.overviewRulerOptions){for(let t of this._zones)if(t.color===e.options.overviewRulerOptions.color&&t.position===e.options.overviewRulerOptions.position){if(this._lineIntersectsZone(t,e.marker.line))return;if(this._lineAdjacentToZone(t,e.marker.line,e.options.overviewRulerOptions.position)){this._addLineToZone(t,e.marker.line);return}}if(this._zonePoolIndex<this._zonePool.length){this._zonePool[this._zonePoolIndex].color=e.options.overviewRulerOptions.color,this._zonePool[this._zonePoolIndex].position=e.options.overviewRulerOptions.position,this._zonePool[this._zonePoolIndex].startBufferLine=e.marker.line,this._zonePool[this._zonePoolIndex].endBufferLine=e.marker.line,this._zones.push(this._zonePool[this._zonePoolIndex++]);return}this._zones.push({color:e.options.overviewRulerOptions.color,position:e.options.overviewRulerOptions.position,startBufferLine:e.marker.line,endBufferLine:e.marker.line}),this._zonePool.push(this._zones[this._zones.length-1]),this._zonePoolIndex++}}setPadding(e){this._linePadding=e}_lineIntersectsZone(e,t){return t>=e.startBufferLine&&t<=e.endBufferLine}_lineAdjacentToZone(e,t,n){return t>=e.startBufferLine-this._linePadding[n||`full`]&&t<=e.endBufferLine+this._linePadding[n||`full`]}_addLineToZone(e,t){e.startBufferLine=Math.min(e.startBufferLine,t),e.endBufferLine=Math.max(e.endBufferLine,t)}},hs={full:0,left:0,center:0,right:0},gs={full:0,left:0,center:0,right:0},_s={full:0,left:0,center:0,right:0},vs=class extends U{constructor(e,t,n,r,i,a,o,s){super(),this._viewportElement=e,this._screenElement=t,this._bufferService=n,this._decorationService=r,this._renderService=i,this._optionsService=a,this._themeService=o,this._coreBrowserService=s,this._colorZoneStore=new ms,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=this._coreBrowserService.mainDocument.createElement(`canvas`),this._canvas.classList.add(`xterm-decoration-overview-ruler`),this._refreshCanvasDimensions(),this._viewportElement.parentElement?.insertBefore(this._canvas,this._viewportElement),this._register(H(()=>this._canvas?.remove()));let c=this._canvas.getContext(`2d`);if(c)this._ctx=c;else throw Error(`Ctx cannot be null`);this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this._register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0))),this._register(this._renderService.onRenderedViewportChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?`none`:`block`})),this._register(this._bufferService.onScroll(()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})),this._register(this._renderService.onRender(()=>{(!this._containerHeight||this._containerHeight!==this._screenElement.clientHeight)&&(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh(!0))),this._register(this._optionsService.onSpecificOptionChange(`overviewRuler`,()=>this._queueRefresh(!0))),this._register(this._themeService.onChangeColors(()=>this._queueRefresh())),this._queueRefresh(!0)}get _width(){return this._optionsService.options.overviewRuler?.width||0}_refreshDrawConstants(){let e=Math.floor((this._canvas.width-1)/3),t=Math.ceil((this._canvas.width-1)/3);gs.full=this._canvas.width,gs.left=e,gs.center=t,gs.right=e,this._refreshDrawHeightConstants(),_s.full=1,_s.left=1,_s.center=1+gs.left,_s.right=1+gs.left+gs.center}_refreshDrawHeightConstants(){hs.full=Math.round(2*this._coreBrowserService.dpr);let e=this._canvas.height/this._bufferService.buffer.lines.length,t=Math.round(Math.max(Math.min(e,12),6)*this._coreBrowserService.dpr);hs.left=t,hs.center=t,hs.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*hs.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*hs.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*hs.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*hs.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(let e of this._decorationService.decorations)this._colorZoneStore.addDecoration(e);this._ctx.lineWidth=1,this._renderRulerOutline();let e=this._colorZoneStore.zones;for(let t of e)t.position!==`full`&&this._renderColorZone(t);for(let t of e)t.position===`full`&&this._renderColorZone(t);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderRulerOutline(){this._ctx.fillStyle=this._themeService.colors.overviewRulerBorder.css,this._ctx.fillRect(0,0,1,this._canvas.height),this._optionsService.rawOptions.overviewRuler.showTopBorder&&this._ctx.fillRect(1,0,this._canvas.width-1,1),this._optionsService.rawOptions.overviewRuler.showBottomBorder&&this._ctx.fillRect(1,this._canvas.height-1,this._canvas.width-1,this._canvas.height)}_renderColorZone(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(_s[e.position||`full`],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-hs[e.position||`full`]/2),gs[e.position||`full`],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+hs[e.position||`full`]))}_queueRefresh(e,t){this._shouldUpdateDimensions=e||this._shouldUpdateDimensions,this._shouldUpdateAnchor=t||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};vs=z([B(2,Gr),B(3,ei),B(4,oi),B(5,Zr),B(6,li),B(7,ii)],vs);var K;(e=>(e.NUL=`\0`,e.SOH=``,e.STX=``,e.ETX=``,e.EOT=``,e.ENQ=``,e.ACK=``,e.BEL=`\x07`,e.BS=`\b`,e.HT=` `,e.LF=`
16
+ `,e.VT=`\v`,e.FF=`\f`,e.CR=`\r`,e.SO=``,e.SI=``,e.DLE=``,e.DC1=``,e.DC2=``,e.DC3=``,e.DC4=``,e.NAK=``,e.SYN=``,e.ETB=``,e.CAN=``,e.EM=``,e.SUB=``,e.ESC=`\x1B`,e.FS=``,e.GS=``,e.RS=``,e.US=``,e.SP=` `,e.DEL=``))(K||={});var ys;(e=>(e.PAD=`€`,e.HOP=``,e.BPH=`‚`,e.NBH=`ƒ`,e.IND=`„`,e.NEL=`…`,e.SSA=`†`,e.ESA=`‡`,e.HTS=`ˆ`,e.HTJ=`‰`,e.VTS=`Š`,e.PLD=`‹`,e.PLU=`Œ`,e.RI=``,e.SS2=`Ž`,e.SS3=``,e.DCS=``,e.PU1=`‘`,e.PU2=`’`,e.STS=`“`,e.CCH=`”`,e.MW=`•`,e.SPA=`–`,e.EPA=`—`,e.SOS=`˜`,e.SGCI=`™`,e.SCI=`š`,e.CSI=`›`,e.ST=`œ`,e.OSC=``,e.PM=`ž`,e.APC=`Ÿ`))(ys||={});var bs;(e=>e.ST=`${K.ESC}\\`)(bs||={});var xs=class{constructor(e,t,n,r,i,a){this._textarea=e,this._compositionView=t,this._bufferService=n,this._optionsService=r,this._coreService=i,this._renderService=a,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=``}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent=``,this._dataAlreadySent=``,this._compositionView.classList.add(`active`)}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(e.keyCode===20||e.keyCode===229||e.keyCode===16||e.keyCode===17||e.keyCode===18)return!1;this._finalizeComposition(!1)}return e.keyCode!==229||(this._handleAnyTextareaChanges(),!1)}_finalizeComposition(e){if(this._compositionView.classList.remove(`active`),this._isComposing=!1,e){let e={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=!1;let t;e.start+=this._dataAlreadySent.length,t=this._isComposing?this._textarea.value.substring(e.start,this._compositionPosition.start):this._textarea.value.substring(e.start),t.length>0&&this._coreService.triggerDataEvent(t,!0)}},0)}else{this._isSendingComposition=!1;let e=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(e,!0)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,n=t.replace(e,``);this._dataAlreadySent=n,t.length>e.length?this._coreService.triggerDataEvent(n,!0):t.length<e.length?this._coreService.triggerDataEvent(`${K.DEL}`,!0):t.length===e.length&&t!==e&&this._coreService.triggerDataEvent(t,!0)}},0)}updateCompositionElements(e){if(this._isComposing){if(this._bufferService.buffer.isCursorInViewport){let e=Math.min(this._bufferService.buffer.x,this._bufferService.cols-1),t=this._renderService.dimensions.css.cell.height,n=this._bufferService.buffer.y*this._renderService.dimensions.css.cell.height,r=e*this._renderService.dimensions.css.cell.width;this._compositionView.style.left=r+`px`,this._compositionView.style.top=n+`px`,this._compositionView.style.height=t+`px`,this._compositionView.style.lineHeight=t+`px`,this._compositionView.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._compositionView.style.fontSize=this._optionsService.rawOptions.fontSize+`px`;let i=this._compositionView.getBoundingClientRect();this._textarea.style.left=r+`px`,this._textarea.style.top=n+`px`,this._textarea.style.width=Math.max(i.width,1)+`px`,this._textarea.style.height=Math.max(i.height,1)+`px`,this._textarea.style.lineHeight=i.height+`px`}e||setTimeout(()=>this.updateCompositionElements(!0),0)}}};xs=z([B(2,Gr),B(3,Zr),B(4,qr),B(5,oi)],xs);var Ss=0,Cs=0,ws=0,Ts=0,Es={css:`#00000000`,rgba:0},Ds;(e=>{function t(e,t,n,r){return r===void 0?`#${Ms(e)}${Ms(t)}${Ms(n)}`:`#${Ms(e)}${Ms(t)}${Ms(n)}${Ms(r)}`}e.toCss=t;function n(e,t,n,r=255){return(e<<24|t<<16|n<<8|r)>>>0}e.toRgba=n;function r(t,n,r,i){return{css:e.toCss(t,n,r,i),rgba:e.toRgba(t,n,r,i)}}e.toColor=r})(Ds||={});var Os;(e=>{function t(e,t){if(Ts=(t.rgba&255)/255,Ts===1)return{css:t.css,rgba:t.rgba};let n=t.rgba>>24&255,r=t.rgba>>16&255,i=t.rgba>>8&255,a=e.rgba>>24&255,o=e.rgba>>16&255,s=e.rgba>>8&255;return Ss=a+Math.round((n-a)*Ts),Cs=o+Math.round((r-o)*Ts),ws=s+Math.round((i-s)*Ts),{css:Ds.toCss(Ss,Cs,ws),rgba:Ds.toRgba(Ss,Cs,ws)}}e.blend=t;function n(e){return(e.rgba&255)==255}e.isOpaque=n;function r(e,t,n){let r=js.ensureContrastRatio(e.rgba,t.rgba,n);if(r)return Ds.toColor(r>>24&255,r>>16&255,r>>8&255)}e.ensureContrastRatio=r;function i(e){let t=(e.rgba|255)>>>0;return[Ss,Cs,ws]=js.toChannels(t),{css:Ds.toCss(Ss,Cs,ws),rgba:t}}e.opaque=i;function a(e,t){return Ts=Math.round(t*255),[Ss,Cs,ws]=js.toChannels(e.rgba),{css:Ds.toCss(Ss,Cs,ws,Ts),rgba:Ds.toRgba(Ss,Cs,ws,Ts)}}e.opacity=a;function o(e,t){return Ts=e.rgba&255,a(e,Ts*t/255)}e.multiplyOpacity=o;function s(e){return[e.rgba>>24&255,e.rgba>>16&255,e.rgba>>8&255]}e.toColorRGB=s})(Os||={});var ks;(e=>{let t,n;try{let e=document.createElement(`canvas`);e.width=1,e.height=1;let r=e.getContext(`2d`,{willReadFrequently:!0});r&&(t=r,t.globalCompositeOperation=`copy`,n=t.createLinearGradient(0,0,1,1))}catch{}function r(e){if(e.match(/#[\da-f]{3,8}/i))switch(e.length){case 4:return Ss=parseInt(e.slice(1,2).repeat(2),16),Cs=parseInt(e.slice(2,3).repeat(2),16),ws=parseInt(e.slice(3,4).repeat(2),16),Ds.toColor(Ss,Cs,ws);case 5:return Ss=parseInt(e.slice(1,2).repeat(2),16),Cs=parseInt(e.slice(2,3).repeat(2),16),ws=parseInt(e.slice(3,4).repeat(2),16),Ts=parseInt(e.slice(4,5).repeat(2),16),Ds.toColor(Ss,Cs,ws,Ts);case 7:return{css:e,rgba:(parseInt(e.slice(1),16)<<8|255)>>>0};case 9:return{css:e,rgba:parseInt(e.slice(1),16)>>>0}}let r=e.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(r)return Ss=parseInt(r[1]),Cs=parseInt(r[2]),ws=parseInt(r[3]),Ts=Math.round((r[5]===void 0?1:parseFloat(r[5]))*255),Ds.toColor(Ss,Cs,ws,Ts);if(!t||!n||(t.fillStyle=n,t.fillStyle=e,typeof t.fillStyle!=`string`)||(t.fillRect(0,0,1,1),[Ss,Cs,ws,Ts]=t.getImageData(0,0,1,1).data,Ts!==255))throw Error(`css.toColor: Unsupported css format`);return{rgba:Ds.toRgba(Ss,Cs,ws,Ts),css:e}}e.toColor=r})(ks||={});var As;(e=>{function t(e){return n(e>>16&255,e>>8&255,e&255)}e.relativeLuminance=t;function n(e,t,n){let r=e/255,i=t/255,a=n/255,o=r<=.03928?r/12.92:((r+.055)/1.055)**2.4,s=i<=.03928?i/12.92:((i+.055)/1.055)**2.4,c=a<=.03928?a/12.92:((a+.055)/1.055)**2.4;return o*.2126+s*.7152+c*.0722}e.relativeLuminance2=n})(As||={});var js;(e=>{function t(e,t){if(Ts=(t&255)/255,Ts===1)return t;let n=t>>24&255,r=t>>16&255,i=t>>8&255,a=e>>24&255,o=e>>16&255,s=e>>8&255;return Ss=a+Math.round((n-a)*Ts),Cs=o+Math.round((r-o)*Ts),ws=s+Math.round((i-s)*Ts),Ds.toRgba(Ss,Cs,ws)}e.blend=t;function n(e,t,n){let a=As.relativeLuminance(e>>8),o=As.relativeLuminance(t>>8);if(Ns(a,o)<n){if(o<a){let o=r(e,t,n),s=Ns(a,As.relativeLuminance(o>>8));if(s<n){let r=i(e,t,n);return s>Ns(a,As.relativeLuminance(r>>8))?o:r}return o}let s=i(e,t,n),c=Ns(a,As.relativeLuminance(s>>8));if(c<n){let i=r(e,t,n);return c>Ns(a,As.relativeLuminance(i>>8))?s:i}return s}}e.ensureContrastRatio=n;function r(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,l=Ns(As.relativeLuminance2(o,s,c),As.relativeLuminance2(r,i,a));for(;l<n&&(o>0||s>0||c>0);)o-=Math.max(0,Math.ceil(o*.1)),s-=Math.max(0,Math.ceil(s*.1)),c-=Math.max(0,Math.ceil(c*.1)),l=Ns(As.relativeLuminance2(o,s,c),As.relativeLuminance2(r,i,a));return(o<<24|s<<16|c<<8|255)>>>0}e.reduceLuminance=r;function i(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,l=Ns(As.relativeLuminance2(o,s,c),As.relativeLuminance2(r,i,a));for(;l<n&&(o<255||s<255||c<255);)o=Math.min(255,o+Math.ceil((255-o)*.1)),s=Math.min(255,s+Math.ceil((255-s)*.1)),c=Math.min(255,c+Math.ceil((255-c)*.1)),l=Ns(As.relativeLuminance2(o,s,c),As.relativeLuminance2(r,i,a));return(o<<24|s<<16|c<<8|255)>>>0}e.increaseLuminance=i;function a(e){return[e>>24&255,e>>16&255,e>>8&255,e&255]}e.toChannels=a})(js||={});function Ms(e){let t=e.toString(16);return t.length<2?`0`+t:t}function Ns(e,t){return e<t?(t+.05)/(e+.05):(e+.05)/(t+.05)}var Ps=class extends Ir{constructor(e,t,n){super(),this.content=0,this.combinedData=``,this.fg=e.fg,this.bg=e.bg,this.combinedData=t,this._width=n}isCombined(){return 2097152}getWidth(){return this._width}getChars(){return this.combinedData}getCode(){return 2097151}setFromCharData(e){throw Error(`not implemented`)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},Fs=class{constructor(e){this._bufferService=e,this._characterJoiners=[],this._nextCharacterJoinerId=0,this._workCell=new Rr}register(e){let t={id:this._nextCharacterJoinerId++,handler:e};return this._characterJoiners.push(t),t.id}deregister(e){for(let t=0;t<this._characterJoiners.length;t++)if(this._characterJoiners[t].id===e)return this._characterJoiners.splice(t,1),!0;return!1}getJoinedCharacters(e){if(this._characterJoiners.length===0)return[];let t=this._bufferService.buffer.lines.get(e);if(!t||t.length===0)return[];let n=[],r=t.translateToString(!0),i=0,a=0,o=0,s=t.getFg(0),c=t.getBg(0);for(let e=0;e<t.getTrimmedLength();e++)if(t.loadCell(e,this._workCell),this._workCell.getWidth()!==0){if(this._workCell.fg!==s||this._workCell.bg!==c){if(e-i>1){let e=this._getJoinedRanges(r,o,a,t,i);for(let t=0;t<e.length;t++)n.push(e[t])}i=e,o=a,s=this._workCell.fg,c=this._workCell.bg}a+=this._workCell.getChars().length||Fr.length}if(this._bufferService.cols-i>1){let e=this._getJoinedRanges(r,o,a,t,i);for(let t=0;t<e.length;t++)n.push(e[t])}return n}_getJoinedRanges(e,t,n,r,i){let a=e.substring(t,n),o=[];try{o=this._characterJoiners[0].handler(a)}catch(e){console.error(e)}for(let e=1;e<this._characterJoiners.length;e++)try{let t=this._characterJoiners[e].handler(a);for(let e=0;e<t.length;e++)Fs._mergeRanges(o,t[e])}catch(e){console.error(e)}return this._stringRangesToCellRanges(o,r,i),o}_stringRangesToCellRanges(e,t,n){let r=0,i=!1,a=0,o=e[r];if(o){for(let s=n;s<this._bufferService.cols;s++){let n=t.getWidth(s),c=t.getString(s).length||Fr.length;if(n!==0){if(!i&&o[0]<=a&&(o[0]=s,i=!0),o[1]<=a){if(o[1]=s,o=e[++r],!o)break;o[0]<=a?(o[0]=s,i=!0):i=!1}a+=c}}o&&(o[1]=this._bufferService.cols)}}static _mergeRanges(e,t){let n=!1;for(let r=0;r<e.length;r++){let i=e[r];if(n){if(t[1]<=i[0])return e[r-1][1]=t[1],e;if(t[1]<=i[1])return e[r-1][1]=Math.max(t[1],i[1]),e.splice(r,1),e;e.splice(r,1),r--}else{if(t[1]<=i[0])return e.splice(r,0,t),e;if(t[1]<=i[1])return i[0]=Math.min(t[0],i[0]),e;t[0]<i[1]&&(i[0]=Math.min(t[0],i[0]),n=!0);continue}}return n?e[e.length-1][1]=t[1]:e.push(t),e}};Fs=z([B(0,Gr)],Fs);function Is(e){return 57508<=e&&e<=57558}function Ls(e){return 9472<=e&&e<=9631}function Rs(e){return Is(e)||Ls(e)}function zs(){return{css:{canvas:Bs(),cell:Bs()},device:{canvas:Bs(),cell:Bs(),char:{width:0,height:0,left:0,top:0}}}}function Bs(){return{width:0,height:0}}var Vs=class{constructor(e,t,n,r,i,a,o){this._document=e,this._characterJoinerService=t,this._optionsService=n,this._coreBrowserService=r,this._coreService=i,this._decorationService=a,this._themeService=o,this._workCell=new Rr,this._columnSelectMode=!1,this.defaultSpacing=0}handleSelectionChanged(e,t,n){this._selectionStart=e,this._selectionEnd=t,this._columnSelectMode=n}createRow(e,t,n,r,i,a,o,s,c,l,u){let d=[],f=this._characterJoinerService.getJoinedCharacters(t),p=this._themeService.colors,m=e.getNoBgTrimmedLength();n&&m<a+1&&(m=a+1);let h,g=0,_=``,v=0,ee=0,y=0,b=0,x=!1,S=0,C=!1,w=0,T=0,E=[],D=l!==-1&&u!==-1;for(let O=0;O<m;O++){e.loadCell(O,this._workCell);let m=this._workCell.getWidth();if(m===0)continue;let te=!1,ne=O>=T,re=O,k=this._workCell;if(f.length>0&&O===f[0][0]&&ne){let r=f.shift(),i=this._isCellInSelection(r[0],t);for(v=r[0]+1;v<r[1];v++)ne&&=i===this._isCellInSelection(v,t);ne&&=!n||a<r[0]||a>=r[1],ne?(te=!0,k=new Ps(this._workCell,e.translateToString(!0,r[0],r[1]),r[1]-r[0]),re=r[1]-1,m=k.getWidth()):T=r[1]}let ie=this._isCellInSelection(O,t),ae=n&&O===a,oe=D&&O>=l&&O<=u,se=!1;this._decorationService.forEachDecorationAtCell(O,t,void 0,e=>{se=!0});let ce=k.getChars()||Fr;if(ce===` `&&(k.isUnderline()||k.isOverline())&&(ce=`\xA0`),w=m*s-c.get(ce,k.isBold(),k.isItalic()),!h)h=this._document.createElement(`span`);else if(g&&(ie&&C||!ie&&!C&&k.bg===ee)&&(ie&&C&&p.selectionForeground||k.fg===y)&&k.extended.ext===b&&oe===x&&w===S&&!ae&&!te&&!se&&ne){k.isInvisible()?_+=Fr:_+=ce,g++;continue}else g&&(h.textContent=_),h=this._document.createElement(`span`),g=0,_=``;if(ee=k.bg,y=k.fg,b=k.extended.ext,x=oe,S=w,C=ie,te&&a>=O&&a<=re&&(a=O),!this._coreService.isCursorHidden&&ae&&this._coreService.isCursorInitialized){if(E.push(`xterm-cursor`),this._coreBrowserService.isFocused)o&&E.push(`xterm-cursor-blink`),E.push(r===`bar`?`xterm-cursor-bar`:r===`underline`?`xterm-cursor-underline`:`xterm-cursor-block`);else if(i)switch(i){case`outline`:E.push(`xterm-cursor-outline`);break;case`block`:E.push(`xterm-cursor-block`);break;case`bar`:E.push(`xterm-cursor-bar`);break;case`underline`:E.push(`xterm-cursor-underline`)}}if(k.isBold()&&E.push(`xterm-bold`),k.isItalic()&&E.push(`xterm-italic`),k.isDim()&&E.push(`xterm-dim`),_=k.isInvisible()?Fr:k.getChars()||Fr,k.isUnderline()&&(E.push(`xterm-underline-${k.extended.underlineStyle}`),_===` `&&(_=`\xA0`),!k.isUnderlineColorDefault())){if(k.isUnderlineColorRGB())h.style.textDecorationColor=`rgb(${Ir.toColorRGB(k.getUnderlineColor()).join(`,`)})`;else{let e=k.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&k.isBold()&&e<8&&(e+=8),h.style.textDecorationColor=p.ansi[e].css}}k.isOverline()&&(E.push(`xterm-overline`),_===` `&&(_=`\xA0`)),k.isStrikethrough()&&E.push(`xterm-strikethrough`),oe&&(h.style.textDecoration=`underline`);let le=k.getFgColor(),ue=k.getFgColorMode(),de=k.getBgColor(),fe=k.getBgColorMode(),A=!!k.isInverse();if(A){let e=le;le=de,de=e;let t=ue;ue=fe,fe=t}let pe,me,he=!1;this._decorationService.forEachDecorationAtCell(O,t,void 0,e=>{e.options.layer!==`top`&&he||(e.backgroundColorRGB&&(fe=50331648,de=e.backgroundColorRGB.rgba>>8&16777215,pe=e.backgroundColorRGB),e.foregroundColorRGB&&(ue=50331648,le=e.foregroundColorRGB.rgba>>8&16777215,me=e.foregroundColorRGB),he=e.options.layer===`top`)}),!he&&ie&&(pe=this._coreBrowserService.isFocused?p.selectionBackgroundOpaque:p.selectionInactiveBackgroundOpaque,de=pe.rgba>>8&16777215,fe=50331648,he=!0,p.selectionForeground&&(ue=50331648,le=p.selectionForeground.rgba>>8&16777215,me=p.selectionForeground)),he&&E.push(`xterm-decoration-top`);let ge;switch(fe){case 16777216:case 33554432:ge=p.ansi[de],E.push(`xterm-bg-${de}`);break;case 50331648:ge=Ds.toColor(de>>16,de>>8&255,de&255),this._addStyle(h,`background-color:#${Hs((de>>>0).toString(16),`0`,6)}`);break;default:A?(ge=p.foreground,E.push(`xterm-bg-257`)):ge=p.background}switch(pe||k.isDim()&&(pe=Os.multiplyOpacity(ge,.5)),ue){case 16777216:case 33554432:k.isBold()&&le<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(le+=8),this._applyMinimumContrast(h,ge,p.ansi[le],k,pe,void 0)||E.push(`xterm-fg-${le}`);break;case 50331648:let e=Ds.toColor(le>>16&255,le>>8&255,le&255);this._applyMinimumContrast(h,ge,e,k,pe,me)||this._addStyle(h,`color:#${Hs(le.toString(16),`0`,6)}`);break;default:this._applyMinimumContrast(h,ge,p.foreground,k,pe,me)||A&&E.push(`xterm-fg-257`)}E.length&&=(h.className=E.join(` `),0),!ae&&!te&&!se&&ne?g++:h.textContent=_,w!==this.defaultSpacing&&(h.style.letterSpacing=`${w}px`),d.push(h),O=re}return h&&g&&(h.textContent=_),d}_applyMinimumContrast(e,t,n,r,i,a){if(this._optionsService.rawOptions.minimumContrastRatio===1||Rs(r.getCode()))return!1;let o=this._getContrastCache(r),s;if(!i&&!a&&(s=o.getColor(t.rgba,n.rgba)),s===void 0){let e=this._optionsService.rawOptions.minimumContrastRatio/(r.isDim()?2:1);s=Os.ensureContrastRatio(i||t,a||n,e),o.setColor((i||t).rgba,(a||n).rgba,s??null)}return s?(this._addStyle(e,`color:${s.css}`),!0):!1}_getContrastCache(e){return e.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(e,t){e.setAttribute(`style`,`${e.getAttribute(`style`)||``}${t};`)}_isCellInSelection(e,t){let n=this._selectionStart,r=this._selectionEnd;return!n||!r?!1:this._columnSelectMode?n[0]<=r[0]?e>=n[0]&&t>=n[1]&&e<r[0]&&t<=r[1]:e<n[0]&&t>=n[1]&&e>=r[0]&&t<=r[1]:t>n[1]&&t<r[1]||n[1]===r[1]&&t===n[1]&&e>=n[0]&&e<r[0]||n[1]<r[1]&&t===r[1]&&e<r[0]||n[1]<r[1]&&t===n[1]&&e>=n[0]}};Vs=z([B(1,ci),B(2,Zr),B(3,ii),B(4,qr),B(5,ei),B(6,li)],Vs);function Hs(e,t,n){for(;e.length<n;)e=t+e;return e}var Us=class{constructor(e,t){this._flat=new Float32Array(256),this._font=``,this._fontSize=0,this._weight=`normal`,this._weightBold=`bold`,this._measureElements=[],this._container=e.createElement(`div`),this._container.classList.add(`xterm-width-cache-measure-container`),this._container.setAttribute(`aria-hidden`,`true`),this._container.style.whiteSpace=`pre`,this._container.style.fontKerning=`none`;let n=e.createElement(`span`);n.classList.add(`xterm-char-measure-element`);let r=e.createElement(`span`);r.classList.add(`xterm-char-measure-element`),r.style.fontWeight=`bold`;let i=e.createElement(`span`);i.classList.add(`xterm-char-measure-element`),i.style.fontStyle=`italic`;let a=e.createElement(`span`);a.classList.add(`xterm-char-measure-element`),a.style.fontWeight=`bold`,a.style.fontStyle=`italic`,this._measureElements=[n,r,i,a],this._container.appendChild(n),this._container.appendChild(r),this._container.appendChild(i),this._container.appendChild(a),t.appendChild(this._container),this.clear()}dispose(){this._container.remove(),this._measureElements.length=0,this._holey=void 0}clear(){this._flat.fill(-9999),this._holey=new Map}setFont(e,t,n,r){e===this._font&&t===this._fontSize&&n===this._weight&&r===this._weightBold||(this._font=e,this._fontSize=t,this._weight=n,this._weightBold=r,this._container.style.fontFamily=this._font,this._container.style.fontSize=`${this._fontSize}px`,this._measureElements[0].style.fontWeight=`${n}`,this._measureElements[1].style.fontWeight=`${r}`,this._measureElements[2].style.fontWeight=`${n}`,this._measureElements[3].style.fontWeight=`${r}`,this.clear())}get(e,t,n){let r=0;if(!t&&!n&&e.length===1&&(r=e.charCodeAt(0))<256){if(this._flat[r]!==-9999)return this._flat[r];let t=this._measure(e,0);return t>0&&(this._flat[r]=t),t}let i=e;t&&(i+=`B`),n&&(i+=`I`);let a=this._holey.get(i);if(a===void 0){let r=0;t&&(r|=1),n&&(r|=2),a=this._measure(e,r),a>0&&this._holey.set(i,a)}return a}_measure(e,t){let n=this._measureElements[t];return n.textContent=e.repeat(32),n.offsetWidth/32}},Ws=class{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(e,t,n,r=!1){if(this.selectionStart=t,this.selectionEnd=n,!t||!n||t[0]===n[0]&&t[1]===n[1]){this.clear();return}let i=e.buffers.active.ydisp,a=t[1]-i,o=n[1]-i,s=Math.max(a,0),c=Math.min(o,e.rows-1);s>=e.rows||c<0?this.clear():(this.hasSelection=!0,this.columnSelectMode=r,this.viewportStartRow=a,this.viewportEndRow=o,this.viewportCappedStartRow=s,this.viewportCappedEndRow=c,this.startCol=t[0],this.endCol=n[0])}isCellSelected(e,t,n){return this.hasSelection?(n-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&n>=this.viewportCappedStartRow&&t<this.endCol&&n<=this.viewportCappedEndRow:t<this.startCol&&n>=this.viewportCappedStartRow&&t>=this.endCol&&n<=this.viewportCappedEndRow:n>this.viewportStartRow&&n<this.viewportEndRow||this.viewportStartRow===this.viewportEndRow&&n===this.viewportStartRow&&t>=this.startCol&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&n===this.viewportEndRow&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&n===this.viewportStartRow&&t>=this.startCol):!1}};function Gs(){return new Ws}var Ks=`xterm-dom-renderer-owner-`,qs=`xterm-rows`,Js=`xterm-fg-`,Ys=`xterm-bg-`,Xs=`xterm-focus`,Zs=`xterm-selection`,Qs=1,$s=class extends U{constructor(e,t,n,r,i,a,o,s,c,l,u,d,f,p){super(),this._terminal=e,this._document=t,this._element=n,this._screenElement=r,this._viewportElement=i,this._helperContainer=a,this._linkifier2=o,this._charSizeService=c,this._optionsService=l,this._bufferService=u,this._coreService=d,this._coreBrowserService=f,this._themeService=p,this._terminalClass=Qs++,this._rowElements=[],this._selectionRenderModel=Gs(),this.onRequestRedraw=this._register(new W).event,this._rowContainer=this._document.createElement(`div`),this._rowContainer.classList.add(qs),this._rowContainer.style.lineHeight=`normal`,this._rowContainer.setAttribute(`aria-hidden`,`true`),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement(`div`),this._selectionContainer.classList.add(Zs),this._selectionContainer.setAttribute(`aria-hidden`,`true`),this.dimensions=zs(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(e=>this._injectCss(e))),this._injectCss(this._themeService.colors),this._rowFactory=s.createInstance(Vs,document),this._element.classList.add(Ks+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(e=>this._handleLinkHover(e))),this._register(this._linkifier2.onHideLinkUnderline(e=>this._handleLinkLeave(e))),this._register(H(()=>{this._element.classList.remove(Ks+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new Us(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){let e=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*e,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*e),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/e),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/e),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(let e of this._rowElements)e.style.width=`${this.dimensions.css.canvas.width}px`,e.style.height=`${this.dimensions.css.cell.height}px`,e.style.lineHeight=`${this.dimensions.css.cell.height}px`,e.style.overflow=`hidden`;this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement(`style`),this._screenElement.appendChild(this._dimensionsStyleElement));let t=`${this._terminalSelector} .${qs} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=t,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(e){this._themeStyleElement||(this._themeStyleElement=this._document.createElement(`style`),this._screenElement.appendChild(this._themeStyleElement));let t=`${this._terminalSelector} .${qs} { pointer-events: none; color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;t+=`${this._terminalSelector} .${qs} .xterm-dim { color: ${Os.multiplyOpacity(e.foreground,.5).css};}`,t+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;let n=`blink_underline_${this._terminalClass}`,r=`blink_bar_${this._terminalClass}`,i=`blink_block_${this._terminalClass}`;t+=`@keyframes ${n} { 50% { border-bottom-style: hidden; }}`,t+=`@keyframes ${r} { 50% { box-shadow: none; }}`,t+=`@keyframes ${i} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${qs}.${Xs} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${n} 1s step-end infinite;}${this._terminalSelector} .${qs}.${Xs} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${r} 1s step-end infinite;}${this._terminalSelector} .${qs}.${Xs} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${qs} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${qs} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${qs} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${qs} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${qs} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${Zs} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${Zs} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${Zs} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[n,r]of e.ansi.entries())t+=`${this._terminalSelector} .${Js}${n} { color: ${r.css}; }${this._terminalSelector} .${Js}${n}.xterm-dim { color: ${Os.multiplyOpacity(r,.5).css}; }${this._terminalSelector} .${Ys}${n} { background-color: ${r.css}; }`;t+=`${this._terminalSelector} .${Js}257 { color: ${Os.opaque(e.background).css}; }${this._terminalSelector} .${Js}257.xterm-dim { color: ${Os.multiplyOpacity(Os.opaque(e.background),.5).css}; }${this._terminalSelector} .${Ys}257 { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=t}_setDefaultSpacing(){let e=this.dimensions.css.cell.width-this._widthCache.get(`W`,!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,t){for(let e=this._rowElements.length;e<=t;e++){let e=this._document.createElement(`div`);this._rowContainer.appendChild(e),this._rowElements.push(e)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,t){this._refreshRowElements(e,t),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(Xs),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(Xs),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,n){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,n),this.renderRows(0,this._bufferService.rows-1),!e||!t||(this._selectionRenderModel.update(this._terminal,e,t,n),!this._selectionRenderModel.hasSelection))return;let r=this._selectionRenderModel.viewportStartRow,i=this._selectionRenderModel.viewportEndRow,a=this._selectionRenderModel.viewportCappedStartRow,o=this._selectionRenderModel.viewportCappedEndRow,s=this._document.createDocumentFragment();if(n){let n=e[0]>t[0];s.appendChild(this._createSelectionElement(a,n?t[0]:e[0],n?e[0]:t[0],o-a+1))}else{let n=r===a?e[0]:0,c=a===i?t[0]:this._bufferService.cols;s.appendChild(this._createSelectionElement(a,n,c));let l=o-a-1;if(s.appendChild(this._createSelectionElement(a+1,0,this._bufferService.cols,l)),a!==o){let e=i===o?t[0]:this._bufferService.cols;s.appendChild(this._createSelectionElement(o,0,e))}}this._selectionContainer.appendChild(s)}_createSelectionElement(e,t,n,r=1){let i=this._document.createElement(`div`),a=t*this.dimensions.css.cell.width,o=this.dimensions.css.cell.width*(n-t);return a+o>this.dimensions.css.canvas.width&&(o=this.dimensions.css.canvas.width-a),i.style.height=`${r*this.dimensions.css.cell.height}px`,i.style.top=`${e*this.dimensions.css.cell.height}px`,i.style.left=`${a}px`,i.style.width=`${o}px`,i}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(let e of this._rowElements)e.replaceChildren()}renderRows(e,t){let n=this._bufferService.buffer,r=n.ybase+n.y,i=Math.min(n.x,this._bufferService.cols-1),a=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,o=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,s=this._optionsService.rawOptions.cursorInactiveStyle;for(let c=e;c<=t;c++){let e=c+n.ydisp,t=this._rowElements[c],l=n.lines.get(e);if(!t||!l)break;t.replaceChildren(...this._rowFactory.createRow(l,e,e===r,o,s,i,a,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${Ks}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,t,n,r,i,a){n<0&&(e=0),r<0&&(t=0);let o=this._bufferService.rows-1;n=Math.max(Math.min(n,o),0),r=Math.max(Math.min(r,o),0),i=Math.min(i,this._bufferService.cols);let s=this._bufferService.buffer,c=s.ybase+s.y,l=Math.min(s.x,i-1),u=this._optionsService.rawOptions.cursorBlink,d=this._optionsService.rawOptions.cursorStyle,f=this._optionsService.rawOptions.cursorInactiveStyle;for(let o=n;o<=r;++o){let p=o+s.ydisp,m=this._rowElements[o],h=s.lines.get(p);if(!m||!h)break;m.replaceChildren(...this._rowFactory.createRow(h,p,p===c,d,f,l,u,this.dimensions.css.cell.width,this._widthCache,a?o===n?e:0:-1,a?(o===r?t:i)-1:-1))}}};$s=z([B(7,Yr),B(8,ri),B(9,Zr),B(10,Gr),B(11,qr),B(12,ii),B(13,li)],$s);var ec=class extends U{constructor(e,t,n){super(),this._optionsService=n,this.width=0,this.height=0,this._onCharSizeChange=this._register(new W),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new rc(this._optionsService))}catch{this._measureStrategy=this._register(new nc(e,t,this._optionsService))}this._register(this._optionsService.onMultipleOptionChange([`fontFamily`,`fontSize`],()=>this.measure()))}get hasValidSize(){return this.width>0&&this.height>0}measure(){let e=this._measureStrategy.measure();(e.width!==this.width||e.height!==this.height)&&(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};ec=z([B(2,Zr)],ec);var tc=class extends U{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(e,t){e!==void 0&&e>0&&t!==void 0&&t>0&&(this._result.width=e,this._result.height=t)}},nc=class extends tc{constructor(e,t,n){super(),this._document=e,this._parentElement=t,this._optionsService=n,this._measureElement=this._document.createElement(`span`),this._measureElement.classList.add(`xterm-char-measure-element`),this._measureElement.textContent=`W`.repeat(32),this._measureElement.setAttribute(`aria-hidden`,`true`),this._measureElement.style.whiteSpace=`pre`,this._measureElement.style.fontKerning=`none`,this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}},rc=class extends tc{constructor(e){super(),this._optionsService=e,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext(`2d`);let t=this._ctx.measureText(`W`);if(!(`width`in t&&`fontBoundingBoxAscent`in t&&`fontBoundingBoxDescent`in t))throw Error(`Required font metrics not supported`)}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;let e=this._ctx.measureText(`W`);return this._validateAndSet(e.width,e.fontBoundingBoxAscent+e.fontBoundingBoxDescent),this._result}},ic=class extends U{constructor(e,t,n){super(),this._textarea=e,this._window=t,this.mainDocument=n,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=this._register(new ac(this._window)),this._onDprChange=this._register(new W),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new W),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(e=>this._screenDprMonitor.setWindow(e))),this._register(Bi.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(G(this._textarea,`focus`,()=>this._isFocused=!0)),this._register(G(this._textarea,`blur`,()=>this._isFocused=!1))}get window(){return this._window}set window(e){this._window!==e&&(this._window=e,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return this._cachedIsFocused===void 0&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask(()=>this._cachedIsFocused=void 0)),this._cachedIsFocused}},ac=class extends U{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new Ni),this._onDprChange=this._register(new W),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register(H(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=G(this._parentWindow,`resize`,()=>this._setDprAndFireIfDiffers())}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){this._outerListener&&(this._resolutionMediaMatchList?.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){!this._resolutionMediaMatchList||!this._outerListener||(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}},oc=class extends U{constructor(){super(),this.linkProviders=[],this._register(H(()=>this.linkProviders.length=0))}registerLinkProvider(e){return this.linkProviders.push(e),{dispose:()=>{let t=this.linkProviders.indexOf(e);t!==-1&&this.linkProviders.splice(t,1)}}}};function sc(e,t,n){let r=n.getBoundingClientRect(),i=e.getComputedStyle(n),a=parseInt(i.getPropertyValue(`padding-left`)),o=parseInt(i.getPropertyValue(`padding-top`));return[t.clientX-r.left-a,t.clientY-r.top-o]}function cc(e,t,n,r,i,a,o,s,c){if(!a)return;let l=sc(e,t,n);if(l)return l[0]=Math.ceil((l[0]+(c?o/2:0))/o),l[1]=Math.ceil(l[1]/s),l[0]=Math.min(Math.max(l[0],1),r+ +!!c),l[1]=Math.min(Math.max(l[1],1),i),l}var lc=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,n,r,i){return cc(window,e,t,n,r,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,i)}getMouseReportCoords(e,t){let n=sc(window,e,t);if(this._charSizeService.hasValidSize)return n[0]=Math.min(Math.max(n[0],0),this._renderService.dimensions.css.canvas.width-1),n[1]=Math.min(Math.max(n[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(n[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(n[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(n[0]),y:Math.floor(n[1])}}};lc=z([B(0,oi),B(1,ri)],lc);var uc=class{constructor(e,t){this._renderCallback=e,this._coreBrowserService=t,this._refreshCallbacks=[]}dispose(){this._animationFrame&&=(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),void 0)}addRefreshCallback(e){return this._refreshCallbacks.push(e),this._animationFrame||=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()),this._animationFrame}refresh(e,t,n){this._rowCount=n,e=e===void 0?0:e,t=t===void 0?this._rowCount-1:t,this._rowStart=this._rowStart===void 0?e:Math.min(this._rowStart,e),this._rowEnd=this._rowEnd===void 0?t:Math.max(this._rowEnd,t),!this._animationFrame&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0){this._runRefreshCallbacks();return}let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(let e of this._refreshCallbacks)e(0);this._refreshCallbacks=[]}},dc={};yr(dc,{getSafariVersion:()=>vc,isChromeOS:()=>wc,isFirefox:()=>hc,isIpad:()=>bc,isIphone:()=>xc,isLegacyEdge:()=>gc,isLinux:()=>Cc,isMac:()=>yc,isNode:()=>fc,isSafari:()=>_c,isWindows:()=>Sc});var fc=typeof process<`u`&&`title`in process,pc=fc?`node`:navigator.userAgent,mc=fc?`node`:navigator.platform,hc=pc.includes(`Firefox`),gc=pc.includes(`Edge`),_c=/^((?!chrome|android).)*safari/i.test(pc);function vc(){if(!_c)return 0;let e=pc.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var yc=[`Macintosh`,`MacIntel`,`MacPPC`,`Mac68K`].includes(mc),bc=mc===`iPad`,xc=mc===`iPhone`,Sc=[`Windows`,`Win16`,`Win32`,`WinCE`].includes(mc),Cc=mc.indexOf(`Linux`)>=0,wc=/\bCrOS\b/.test(pc),Tc=class{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._i<this._tasks.length;)this._tasks[this._i]()||this._i++;this.clear()}clear(){this._idleCallback&&=(this._cancelCallback(this._idleCallback),void 0),this._i=0,this._tasks.length=0}_start(){this._idleCallback||=this._requestCallback(this._process.bind(this))}_process(e){this._idleCallback=void 0;let t=0,n=0,r=e.timeRemaining(),i=0;for(;this._i<this._tasks.length;){if(t=performance.now(),this._tasks[this._i]()||this._i++,t=Math.max(1,performance.now()-t),n=Math.max(t,n),i=e.timeRemaining(),n*1.5>i){r-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(r-t))}ms`),this._start();return}r=i}this.clear()}},Ec=class extends Tc{_requestCallback(e){return setTimeout(()=>e(this._createDeadline(16)))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=performance.now()+e;return{timeRemaining:()=>Math.max(0,t-performance.now())}}},Dc=class extends Tc{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},Oc=!fc&&`requestIdleCallback`in window?Dc:Ec,kc=class{constructor(){this._queue=new Oc}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},Ac=class extends U{constructor(e,t,n,r,i,a,o,s,c){super(),this._rowCount=e,this._optionsService=n,this._charSizeService=r,this._coreService=i,this._coreBrowserService=s,this._renderer=this._register(new Ni),this._pausedResizeTask=new kc,this._observerDisposable=this._register(new Ni),this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this._register(new W),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new W),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new W),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new W),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new uc((e,t)=>this._renderRows(e,t),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new jc(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(H(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(o.onResize(()=>this._fullRefresh())),this._register(o.buffers.onBufferActivate(()=>this._renderer.value?.clear())),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this._register(a.onDecorationRegistered(()=>this._fullRefresh())),this._register(a.onDecorationRemoved(()=>this._fullRefresh())),this._register(this._optionsService.onMultipleOptionChange([`customGlyphs`,`drawBoldTextInBrightColors`,`letterSpacing`,`lineHeight`,`fontFamily`,`fontSize`,`fontWeight`,`fontWeightBold`,`minimumContrastRatio`,`rescaleOverlappingGlyphs`],()=>{this.clear(),this.handleResize(o.cols,o.rows),this._fullRefresh()})),this._register(this._optionsService.onMultipleOptionChange([`cursorBlink`,`cursorStyle`],()=>this.refreshRows(o.buffer.y,o.buffer.y,!0))),this._register(c.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(this._coreBrowserService.window,t),this._register(this._coreBrowserService.onWindowChange(e=>this._registerIntersectionObserver(e,t)))}get dimensions(){return this._renderer.value.dimensions}_registerIntersectionObserver(e,t){if(`IntersectionObserver`in e){let n=new e.IntersectionObserver(e=>this._handleIntersectionChange(e[e.length-1]),{threshold:0});n.observe(t),this._observerDisposable.value=H(()=>n.disconnect())}}_handleIntersectionChange(e){this._isPaused=e.isIntersecting===void 0?e.intersectionRatio===0:!e.isIntersecting,!this._isPaused&&!this._charSizeService.hasValidSize&&this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,t,n=!1){if(this._isPaused){this._needsFullRefresh=!0;return}if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}let r=this._syncOutputHandler.flush();r&&(e=Math.min(e,r.start),t=Math.max(t,r.end)),n||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,t,this._rowCount)}_renderRows(e,t){if(this._renderer.value){if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}e=Math.min(e,this._rowCount-1),t=Math.min(t,this._rowCount-1),this._renderer.value.renderRows(e,t),this._needsSelectionRefresh&&=(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:t}),this._onRender.fire({start:e,end:t}),this._isNextRenderRedrawOnly=!0}}resize(e,t){this._rowCount=t,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw(e=>this.refreshRows(e.start,e.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){this._renderer.value&&(this._renderer.value.clearTextureAtlas?.(),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,t){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>this._renderer.value?.handleResize(e,t)):this._renderer.value.handleResize(e,t),this._fullRefresh())}handleCharSizeChanged(){this._renderer.value?.handleCharSizeChanged()}handleBlur(){this._renderer.value?.handleBlur()}handleFocus(){this._renderer.value?.handleFocus()}handleSelectionChanged(e,t,n){this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=n,this._renderer.value?.handleSelectionChanged(e,t,n)}handleCursorMove(){this._renderer.value?.handleCursorMove()}clear(){this._renderer.value?.clear()}};Ac=z([B(2,Zr),B(3,ri),B(4,qr),B(5,ei),B(6,Gr),B(7,ii),B(8,li)],Ac);var jc=class{constructor(e,t,n){this._coreBrowserService=e,this._coreService=t,this._onTimeout=n,this._start=0,this._end=0,this._isBuffering=!1}bufferRows(e,t){this._isBuffering?(this._start=Math.min(this._start,e),this._end=Math.max(this._end,t)):(this._start=e,this._end=t,this._isBuffering=!0),this._timeout===void 0&&(this._timeout=this._coreBrowserService.window.setTimeout(()=>{this._timeout=void 0,this._coreService.decPrivateModes.synchronizedOutput=!1,this._onTimeout()},1e3))}flush(){if(this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0),!this._isBuffering)return;let e={start:this._start,end:this._end};return this._isBuffering=!1,e}dispose(){this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0)}};function Mc(e,t,n,r){let i=n.buffer.x,a=n.buffer.y;if(!n.buffer.hasScrollback)return Fc(i,a,e,t,n,r)+Ic(a,t,n,r)+Lc(i,a,e,t,n,r);let o;if(a===t)return o=i>e?`D`:`C`,Wc(Math.abs(i-e),Uc(o,r));o=a>t?`D`:`C`;let s=Math.abs(a-t);return Wc(Pc(a>t?e:i,n)+(s-1)*n.cols+1+Nc(a>t?i:e,n),Uc(o,r))}function Nc(e,t){return e-1}function Pc(e,t){return t.cols-e}function Fc(e,t,n,r,i,a){return Ic(t,r,i,a).length===0?``:Wc(Hc(e,t,e,t-zc(t,i),!1,i).length,Uc(`D`,a))}function Ic(e,t,n,r){let i=e-zc(e,n),a=t-zc(t,n);return Wc(Math.abs(i-a)-Rc(e,t,n),Uc(Vc(e,t),r))}function Lc(e,t,n,r,i,a){let o;o=Ic(t,r,i,a).length>0?r-zc(r,i):t;let s=r,c=Bc(e,t,n,r,i,a);return Wc(Hc(e,o,n,s,c===`C`,i).length,Uc(c,a))}function Rc(e,t,n){let r=0,i=e-zc(e,n),a=t-zc(t,n);for(let o=0;o<Math.abs(i-a);o++){let a=Vc(e,t)===`A`?-1:1;n.buffer.lines.get(i+a*o)?.isWrapped&&r++}return r}function zc(e,t){let n=0,r=t.buffer.lines.get(e),i=r?.isWrapped;for(;i&&e>=0&&e<t.rows;)n++,r=t.buffer.lines.get(--e),i=r?.isWrapped;return n}function Bc(e,t,n,r,i,a){let o;return o=Ic(n,r,i,a).length>0?r-zc(r,i):t,e<n&&o<=r||e>=n&&o<r?`C`:`D`}function Vc(e,t){return e>t?`A`:`B`}function Hc(e,t,n,r,i,a){let o=e,s=t,c=``;for(;(o!==n||s!==r)&&s>=0&&s<a.buffer.lines.length;)o+=i?1:-1,i&&o>a.cols-1?(c+=a.buffer.translateBufferLineToString(s,!1,e,o),o=0,e=0,s++):!i&&o<0&&(c+=a.buffer.translateBufferLineToString(s,!1,0,e+1),o=a.cols-1,e=o,s--);return c+a.buffer.translateBufferLineToString(s,!1,e,o)}function Uc(e,t){let n=t?`O`:`[`;return K.ESC+n+e}function Wc(e,t){e=Math.floor(e);let n=``;for(let r=0;r<e;r++)n+=t;return n}var Gc=class{constructor(e){this._bufferService=e,this.isSelectAllActive=!1,this.selectionStartLength=0}clearSelection(){this.selectionStart=void 0,this.selectionEnd=void 0,this.isSelectAllActive=!1,this.selectionStartLength=0}get finalSelectionStart(){return this.isSelectAllActive?[0,0]:!this.selectionEnd||!this.selectionStart?this.selectionStart:this.areSelectionValuesReversed()?this.selectionEnd:this.selectionStart}get finalSelectionEnd(){if(this.isSelectAllActive)return[this._bufferService.cols,this._bufferService.buffer.ybase+this._bufferService.rows-1];if(this.selectionStart){if(!this.selectionEnd||this.areSelectionValuesReversed()){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?e%this._bufferService.cols===0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)-1]:[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[Math.max(e,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){let e=this.selectionStart,t=this.selectionEnd;return!e||!t?!1:e[1]>t[1]||e[1]===t[1]&&e[0]>t[0]}handleTrim(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}};function Kc(e,t){if(e.start.y>e.end.y)throw Error(`Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`);return t*(e.end.y-e.start.y)+(e.end.x-e.start.x+1)}var qc=50,Jc=15,Yc=50,Xc=500,Zc=RegExp(`\xA0`,`g`),Qc=class extends U{constructor(e,t,n,r,i,a,o,s,c){super(),this._element=e,this._screenElement=t,this._linkifier=n,this._bufferService=r,this._coreService=i,this._mouseService=a,this._optionsService=o,this._renderService=s,this._coreBrowserService=c,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new Rr,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new W),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new W),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new W),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new W),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=e=>this._handleMouseMove(e),this._mouseUpListener=e=>this._handleMouseUp(e),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(e=>this._handleTrim(e)),this._register(this._bufferService.buffers.onBufferActivate(e=>this._handleBufferActivate(e))),this.enable(),this._model=new Gc(this._bufferService),this._activeSelectionMode=0,this._register(H(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(e=>{e.rowsChanged&&this.clearSelection()}))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!e||!t?!1:e[0]!==t[0]||e[1]!==t[1]}get selectionText(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return``;let n=this._bufferService.buffer,r=[];if(this._activeSelectionMode===3){if(e[0]===t[0])return``;let i=e[0]<t[0]?e[0]:t[0],a=e[0]<t[0]?t[0]:e[0];for(let o=e[1];o<=t[1];o++){let e=n.translateBufferLineToString(o,!0,i,a);r.push(e)}}else{let i=e[1]===t[1]?t[0]:void 0;r.push(n.translateBufferLineToString(e[1],!0,e[0],i));for(let i=e[1]+1;i<=t[1]-1;i++){let e=n.lines.get(i),t=n.translateBufferLineToString(i,!0);e?.isWrapped?r[r.length-1]+=t:r.push(t)}if(e[1]!==t[1]){let e=n.lines.get(t[1]),i=n.translateBufferLineToString(t[1],!0,0,t[0]);e&&e.isWrapped?r[r.length-1]+=i:r.push(i)}}return r.map(e=>e.replace(Zc,` `)).join(Sc?`\r
17
17
  `:`
18
- `)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh()),Cc&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r||!t?!1:this._areCoordsInSelection(t,n,r)}isCellInSelection(e,t){let n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r?!1:this._areCoordsInSelection([e,t],n,r)}_areCoordsInSelection(e,t,n){return e[1]>t[1]&&e[1]<n[1]||t[1]===n[1]&&e[1]===t[1]&&e[0]>=t[0]&&e[0]<n[0]||t[1]<n[1]&&e[1]===n[1]&&e[0]<n[0]||t[1]<n[1]&&e[1]===t[1]&&e[0]>=t[0]}_selectWordAtCursor(e,t){let n=this._linkifier.currentLink?.link?.range;if(n)return this._model.selectionStart=[n.start.x-1,n.start.y-1],this._model.selectionStartLength=Kc(n,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let r=this._getMouseBufferCoords(e);return r?(this._selectWordAt(r,t),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=sc(this._coreBrowserService.window,e,this._screenElement)[1],n=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=n?0:(t>n&&(t-=n),t=Math.min(Math.max(t,-qc),qc),t/=qc,t/Math.abs(t)+Math.round(t*(Jc-1)))}shouldForceSelection(e){return yc?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(e.button===2&&this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener(`mousemove`,this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener(`mouseup`,this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),Yc)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener(`mousemove`,this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener(`mouseup`,this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&t.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(yc&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]<this._model.selectionStart[1]?this._model.selectionEnd[0]=0:this._model.selectionEnd[0]=this._bufferService.cols:this._activeSelectionMode===1&&this._selectToWordAt(this._model.selectionEnd),this._dragScrollAmount=this._getMouseEventScrollAmount(e),this._activeSelectionMode!==3&&(this._dragScrollAmount>0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let n=this._bufferService.buffer;if(this._model.selectionEnd[1]<n.lines.length){let e=n.lines.get(this._model.selectionEnd[1]);e&&e.hasWidth(this._model.selectionEnd[0])===0&&this._model.selectionEnd[0]<this._bufferService.cols&&this._model.selectionEnd[0]++}(!t||t[0]!==this._model.selectionEnd[0]||t[1]!==this._model.selectionEnd[1])&&this.refresh(!0)}_dragScroll(){if(this._model.selectionEnd&&this._model.selectionStart&&this._dragScrollAmount){this._onRequestScrollLines.fire({amount:this._dragScrollAmount,suppressScrollEvent:!1});let e=this._bufferService.buffer;this._dragScrollAmount>0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&t<Xc&&e.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){let t=this._mouseService.getCoords(e,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(t&&t[0]!==void 0&&t[1]!==void 0){let e=Mc(t[0]-1,t[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(e,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd,n=!!e&&!!t&&(e[0]!==t[0]||e[1]!==t[1]);n?!e||!t||(!this._oldSelectionStart||!this._oldSelectionEnd||e[0]!==this._oldSelectionStart[0]||e[1]!==this._oldSelectionStart[1]||t[0]!==this._oldSelectionEnd[0]||t[1]!==this._oldSelectionEnd[1])&&this._fireOnSelectionChange(e,t,n):this._oldHasSelection&&this._fireOnSelectionChange(e,t,n)}_fireOnSelectionChange(e,t,n){this._oldSelectionStart=e,this._oldSelectionEnd=t,this._oldHasSelection=n,this._onSelectionChange.fire()}_handleBufferActivate(e){this.clearSelection(),this._trimListener.dispose(),this._trimListener=e.activeBuffer.lines.onTrim(e=>this._handleTrim(e))}_convertViewportColToCharacterIndex(e,t){let n=t;for(let r=0;t>=r;r++){let i=e.loadCell(r,this._workCell).getChars().length;this._workCell.getWidth()===0?n--:i>1&&t!==r&&(n+=i-1)}return n}setSelection(e,t,n){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=n,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,n=!0,r=!0){if(e[0]>=this._bufferService.cols)return;let i=this._bufferService.buffer,a=i.lines.get(e[1]);if(!a)return;let o=i.translateBufferLineToString(e[1],!1),s=this._convertViewportColToCharacterIndex(a,e[0]),c=s,l=e[0]-s,u=0,d=0,f=0,p=0;if(o.charAt(s)===` `){for(;s>0&&o.charAt(s-1)===` `;)s--;for(;c<o.length&&o.charAt(c+1)===` `;)c++}else{let t=e[0],n=e[0];a.getWidth(t)===0&&(u++,t--),a.getWidth(n)===2&&(d++,n++);let r=a.getString(n).length;for(r>1&&(p+=r-1,c+=r-1);t>0&&s>0&&!this._isCharWordSeparator(a.loadCell(t-1,this._workCell));){a.loadCell(t-1,this._workCell);let e=this._workCell.getChars().length;this._workCell.getWidth()===0?(u++,t--):e>1&&(f+=e-1,s-=e-1),s--,t--}for(;n<a.length&&c+1<o.length&&!this._isCharWordSeparator(a.loadCell(n+1,this._workCell));){a.loadCell(n+1,this._workCell);let e=this._workCell.getChars().length;this._workCell.getWidth()===2?(d++,n++):e>1&&(p+=e-1,c+=e-1),c++,n++}}c++;let m=s+l-u+f,h=Math.min(this._bufferService.cols,c-s+u+d-f-p);if(t||o.slice(s,c).trim()!==``){if(n&&m===0&&a.getCodePoint(0)!==32){let t=i.lines.get(e[1]-1);if(t&&a.isWrapped&&t.getCodePoint(this._bufferService.cols-1)!==32){let t=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(t){let e=this._bufferService.cols-t.start;m-=e,h+=e}}}if(r&&m+h===this._bufferService.cols&&a.getCodePoint(this._bufferService.cols-1)!==32){let t=i.lines.get(e[1]+1);if(t?.isWrapped&&t.getCodePoint(0)!==32){let t=this._getWordAt([0,e[1]+1],!1,!1,!0);t&&(h+=t.length)}}return{start:m,length:h}}}_selectWordAt(e,t){let n=this._getWordAt(e,t);if(n){for(;n.start<0;)n.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[n.start,e[1]],this._model.selectionStartLength=n.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let n=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,n--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,n++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,n]}}_isCharWordSeparator(e){return e.getWidth()!==0&&this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),n={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=Kc(n,this._bufferService.cols)}};Qc=R([z(3,Gr),z(4,qr),z(5,ai),z(6,Zr),z(7,oi),z(8,ii)],Qc);var $c=class{constructor(){this._data={}}set(e,t,n){this._data[e]||(this._data[e]={}),this._data[e][t]=n}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},el=class{constructor(){this._color=new $c,this._css=new $c}setCss(e,t,n){this._css.set(e,t,n)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,n){this._color.set(e,t,n)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}},tl=Object.freeze((()=>{let e=[ks.toColor(`#2e3436`),ks.toColor(`#cc0000`),ks.toColor(`#4e9a06`),ks.toColor(`#c4a000`),ks.toColor(`#3465a4`),ks.toColor(`#75507b`),ks.toColor(`#06989a`),ks.toColor(`#d3d7cf`),ks.toColor(`#555753`),ks.toColor(`#ef2929`),ks.toColor(`#8ae234`),ks.toColor(`#fce94f`),ks.toColor(`#729fcf`),ks.toColor(`#ad7fa8`),ks.toColor(`#34e2e2`),ks.toColor(`#eeeeec`)],t=[0,95,135,175,215,255];for(let n=0;n<216;n++){let r=t[n/36%6|0],i=t[n/6%6|0],a=t[n%6];e.push({css:Ds.toCss(r,i,a),rgba:Ds.toRgba(r,i,a)})}for(let t=0;t<24;t++){let n=8+t*10;e.push({css:Ds.toCss(n,n,n),rgba:Ds.toRgba(n,n,n)})}return e})()),nl=ks.toColor(`#ffffff`),rl=ks.toColor(`#000000`),il=ks.toColor(`#ffffff`),al=rl,ol={css:`rgba(255, 255, 255, 0.3)`,rgba:4294967117},sl=nl,cl=class extends H{constructor(e){super(),this._optionsService=e,this._contrastCache=new el,this._halfContrastCache=new el,this._onChangeColors=this._register(new U),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:nl,background:rl,cursor:il,cursorAccent:al,selectionForeground:void 0,selectionBackgroundTransparent:ol,selectionBackgroundOpaque:Os.blend(rl,ol),selectionInactiveBackgroundTransparent:ol,selectionInactiveBackgroundOpaque:Os.blend(rl,ol),scrollbarSliderBackground:Os.opacity(nl,.2),scrollbarSliderHoverBackground:Os.opacity(nl,.4),scrollbarSliderActiveBackground:Os.opacity(nl,.5),overviewRulerBorder:nl,ansi:tl.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange(`minimumContrastRatio`,()=>this._contrastCache.clear())),this._register(this._optionsService.onSpecificOptionChange(`theme`,()=>this._setTheme(this._optionsService.rawOptions.theme)))}get colors(){return this._colors}_setTheme(e={}){let t=this._colors;if(t.foreground=K(e.foreground,nl),t.background=K(e.background,rl),t.cursor=Os.blend(t.background,K(e.cursor,il)),t.cursorAccent=Os.blend(t.background,K(e.cursorAccent,al)),t.selectionBackgroundTransparent=K(e.selectionBackground,ol),t.selectionBackgroundOpaque=Os.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=K(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=Os.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?K(e.selectionForeground,Es):void 0,t.selectionForeground===Es&&(t.selectionForeground=void 0),Os.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=Os.opacity(t.selectionBackgroundTransparent,.3)),Os.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=Os.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=K(e.scrollbarSliderBackground,Os.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=K(e.scrollbarSliderHoverBackground,Os.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=K(e.scrollbarSliderActiveBackground,Os.opacity(t.foreground,.5)),t.overviewRulerBorder=K(e.overviewRulerBorder,sl),t.ansi=tl.slice(),t.ansi[0]=K(e.black,tl[0]),t.ansi[1]=K(e.red,tl[1]),t.ansi[2]=K(e.green,tl[2]),t.ansi[3]=K(e.yellow,tl[3]),t.ansi[4]=K(e.blue,tl[4]),t.ansi[5]=K(e.magenta,tl[5]),t.ansi[6]=K(e.cyan,tl[6]),t.ansi[7]=K(e.white,tl[7]),t.ansi[8]=K(e.brightBlack,tl[8]),t.ansi[9]=K(e.brightRed,tl[9]),t.ansi[10]=K(e.brightGreen,tl[10]),t.ansi[11]=K(e.brightYellow,tl[11]),t.ansi[12]=K(e.brightBlue,tl[12]),t.ansi[13]=K(e.brightMagenta,tl[13]),t.ansi[14]=K(e.brightCyan,tl[14]),t.ansi[15]=K(e.brightWhite,tl[15]),e.extendedAnsi){let n=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let r=0;r<n;r++)t.ansi[r+16]=K(e.extendedAnsi[r],tl[r+16])}this._contrastCache.clear(),this._halfContrastCache.clear(),this._updateRestoreColors(),this._onChangeColors.fire(this.colors)}restoreColor(e){this._restoreColor(e),this._onChangeColors.fire(this.colors)}_restoreColor(e){if(e===void 0)for(let e=0;e<this._restoreColors.ansi.length;++e)this._colors.ansi[e]=this._restoreColors.ansi[e];else switch(e){case 256:this._colors.foreground=this._restoreColors.foreground;break;case 257:this._colors.background=this._restoreColors.background;break;case 258:this._colors.cursor=this._restoreColors.cursor;break;default:this._colors.ansi[e]=this._restoreColors.ansi[e]}}modifyColors(e){e(this._colors),this._onChangeColors.fire(this.colors)}_updateRestoreColors(){this._restoreColors={foreground:this._colors.foreground,background:this._colors.background,cursor:this._colors.cursor,ansi:this._colors.ansi.slice()}}};cl=R([z(0,Zr)],cl);function K(e,t){if(e!==void 0)try{return ks.toColor(e)}catch{}return t}var ll=class{constructor(...e){this._entries=new Map;for(let[t,n]of e)this.set(t,n)}set(e,t){let n=this._entries.get(e);return this._entries.set(e,t),n}forEach(e){for(let[t,n]of this._entries.entries())e(t,n)}has(e){return this._entries.has(e)}get(e){return this._entries.get(e)}},ul=class{constructor(){this._services=new ll,this._services.set(Yr,this)}setService(e,t){this._services.set(e,t)}getService(e){return this._services.get(e)}createInstance(e,...t){let n=Hr(e).sort((e,t)=>e.index-t.index),r=[];for(let t of n){let n=this._services.get(t.id);if(!n)throw Error(`[createInstance] ${e.name} depends on UNKNOWN service ${t.id._id}.`);r.push(n)}let i=n.length>0?n[0].index:t.length;if(t.length!==i)throw Error(`[createInstance] First service dependency of ${e.name} at position ${i+1} conflicts with ${t.length} static arguments`);return new e(...t,...r)}},dl={trace:0,debug:1,info:2,warn:3,error:4,off:5},fl=`xterm.js: `,pl=class extends H{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange(`logLevel`,()=>this._updateLogLevel())),ml=this}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=dl[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;t<e.length;t++)typeof e[t]==`function`&&(e[t]=e[t]())}_log(e,t,n){this._evalLazyOptionalParams(n),e.call(console,(this._optionsService.options.logger?``:fl)+t,...n)}trace(e,...t){this._logLevel<=0&&this._log(this._optionsService.options.logger?.trace.bind(this._optionsService.options.logger)??console.log,e,t)}debug(e,...t){this._logLevel<=1&&this._log(this._optionsService.options.logger?.debug.bind(this._optionsService.options.logger)??console.log,e,t)}info(e,...t){this._logLevel<=2&&this._log(this._optionsService.options.logger?.info.bind(this._optionsService.options.logger)??console.info,e,t)}warn(e,...t){this._logLevel<=3&&this._log(this._optionsService.options.logger?.warn.bind(this._optionsService.options.logger)??console.warn,e,t)}error(e,...t){this._logLevel<=4&&this._log(this._optionsService.options.logger?.error.bind(this._optionsService.options.logger)??console.error,e,t)}};pl=R([z(0,Zr)],pl);var ml,hl=class extends H{constructor(e){super(),this._maxLength=e,this.onDeleteEmitter=this._register(new U),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this._register(new U),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this._register(new U),this.onTrim=this.onTrimEmitter.event,this._array=Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(e){if(this._maxLength===e)return;let t=Array(e);for(let n=0;n<Math.min(e,this.length);n++)t[n]=this._array[this._getCyclicIndex(n)];this._array=t,this._maxLength=e,this._startIndex=0}get length(){return this._length}set length(e){if(e>this._length)for(let t=this._length;t<e;t++)this._array[t]=void 0;this._length=e}get(e){return this._array[this._getCyclicIndex(e)]}set(e,t){this._array[this._getCyclicIndex(e)]=t}push(e){this._array[this._getCyclicIndex(this._length)]=e,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++}recycle(){if(this._length!==this._maxLength)throw 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(e,t,...n){if(t){for(let n=e;n<this._length-t;n++)this._array[this._getCyclicIndex(n)]=this._array[this._getCyclicIndex(n+t)];this._length-=t,this.onDeleteEmitter.fire({index:e,amount:t})}for(let t=this._length-1;t>=e;t--)this._array[this._getCyclicIndex(t+n.length)]=this._array[this._getCyclicIndex(t)];for(let t=0;t<n.length;t++)this._array[this._getCyclicIndex(e+t)]=n[t];if(n.length&&this.onInsertEmitter.fire({index:e,amount:n.length}),this._length+n.length>this._maxLength){let e=this._length+n.length-this._maxLength;this._startIndex+=e,this._length=this._maxLength,this.onTrimEmitter.fire(e)}else this._length+=n.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,n){if(!(t<=0)){if(e<0||e>=this._length)throw Error(`start argument out of range`);if(e+n<0)throw Error(`Cannot shift elements in list beyond index 0`);if(n>0){for(let r=t-1;r>=0;r--)this.set(e+r+n,this.get(e+r));let r=e+t+n-this._length;if(r>0)for(this._length+=r;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let r=0;r<t;r++)this.set(e+r+n,this.get(e+r))}}_getCyclicIndex(e){return(this._startIndex+e)%this._maxLength}},q=3,gl=Object.freeze(new Ir),_l=0,vl=2,yl=class e{constructor(e,t,n=!1){this.isWrapped=n,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(e*q);let r=t||Rr.fromCharData([0,Pr,1,0]);for(let t=0;t<e;++t)this.setCell(t,r);this.length=e}get(e){let t=this._data[e*q+0],n=t&2097151;return[this._data[e*q+1],t&2097152?this._combined[e]:n?Ar(n):``,t>>22,t&2097152?this._combined[e].charCodeAt(this._combined[e].length-1):n]}set(e,t){this._data[e*q+1]=t[0],t[1].length>1?(this._combined[e]=t[1],this._data[e*q+0]=e|2097152|t[2]<<22):this._data[e*q+0]=t[1].charCodeAt(0)|t[2]<<22}getWidth(e){return this._data[e*q+0]>>22}hasWidth(e){return this._data[e*q+0]&12582912}getFg(e){return this._data[e*q+1]}getBg(e){return this._data[e*q+2]}hasContent(e){return this._data[e*q+0]&4194303}getCodePoint(e){let t=this._data[e*q+0];return t&2097152?this._combined[e].charCodeAt(this._combined[e].length-1):t&2097151}isCombined(e){return this._data[e*q+0]&2097152}getString(e){let t=this._data[e*q+0];return t&2097152?this._combined[e]:t&2097151?Ar(t&2097151):``}isProtected(e){return this._data[e*q+2]&536870912}loadCell(e,t){return _l=e*q,t.content=this._data[_l+0],t.fg=this._data[_l+1],t.bg=this._data[_l+2],t.content&2097152&&(t.combinedData=this._combined[e]),t.bg&268435456&&(t.extended=this._extendedAttrs[e]),t}setCell(e,t){t.content&2097152&&(this._combined[e]=t.combinedData),t.bg&268435456&&(this._extendedAttrs[e]=t.extended),this._data[e*q+0]=t.content,this._data[e*q+1]=t.fg,this._data[e*q+2]=t.bg}setCellFromCodepoint(e,t,n,r){r.bg&268435456&&(this._extendedAttrs[e]=r.extended),this._data[e*q+0]=t|n<<22,this._data[e*q+1]=r.fg,this._data[e*q+2]=r.bg}addCodepointToCell(e,t,n){let r=this._data[e*q+0];r&2097152?this._combined[e]+=Ar(t):r&2097151?(this._combined[e]=Ar(r&2097151)+Ar(t),r&=-2097152,r|=2097152):r=t|1<<22,n&&(r&=-12582913,r|=n<<22),this._data[e*q+0]=r}insertCells(e,t,n){if(e%=this.length,e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length-e){let r=new Rr;for(let n=this.length-e-t-1;n>=0;--n)this.setCell(e+t+n,this.loadCell(e+n,r));for(let r=0;r<t;++r)this.setCell(e+r,n)}else for(let t=e;t<this.length;++t)this.setCell(t,n);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,n)}deleteCells(e,t,n){if(e%=this.length,t<this.length-e){let r=new Rr;for(let n=0;n<this.length-e-t;++n)this.setCell(e+n,this.loadCell(e+t+n,r));for(let e=this.length-t;e<this.length;++e)this.setCell(e,n)}else for(let t=e;t<this.length;++t)this.setCell(t,n);e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),this.getWidth(e)===0&&!this.hasContent(e)&&this.setCellFromCodepoint(e,0,1,n)}replaceCells(e,t,n,r=!1){if(r)for(e&&this.getWidth(e-1)===2&&!this.isProtected(e-1)&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length&&this.getWidth(t-1)===2&&!this.isProtected(t)&&this.setCellFromCodepoint(t,0,1,n);e<t&&e<this.length;)this.isProtected(e)||this.setCell(e,n),e++;else for(e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t,0,1,n);e<t&&e<this.length;)this.setCell(e++,n)}resize(e,t){if(e===this.length)return this._data.length*4*vl<this._data.buffer.byteLength;let n=e*q;if(e>this.length){if(this._data.buffer.byteLength>=n*4)this._data=new Uint32Array(this._data.buffer,0,n);else{let e=new Uint32Array(n);e.set(this._data),this._data=e}for(let n=this.length;n<e;++n)this.setCell(n,t)}else{this._data=this._data.subarray(0,n);let t=Object.keys(this._combined);for(let n=0;n<t.length;n++){let r=parseInt(t[n],10);r>=e&&delete this._combined[r]}let r=Object.keys(this._extendedAttrs);for(let t=0;t<r.length;t++){let n=parseInt(r[t],10);n>=e&&delete this._extendedAttrs[n]}}return this.length=e,n*4*vl<this._data.buffer.byteLength}cleanupMemory(){if(this._data.length*4*vl<this._data.buffer.byteLength){let e=new Uint32Array(this._data.length);return e.set(this._data),this._data=e,1}return 0}fill(e,t=!1){if(t)for(let t=0;t<this.length;++t)this.isProtected(t)||this.setCell(t,e);else{this._combined={},this._extendedAttrs={};for(let t=0;t<this.length;++t)this.setCell(t,e)}}copyFrom(e){this.length===e.length?this._data.set(e._data):this._data=new Uint32Array(e._data),this.length=e.length,this._combined={};for(let t in e._combined)this._combined[t]=e._combined[t];this._extendedAttrs={};for(let t in e._extendedAttrs)this._extendedAttrs[t]=e._extendedAttrs[t];this.isWrapped=e.isWrapped}clone(){let t=new e(0);t._data=new Uint32Array(this._data),t.length=this.length;for(let e in this._combined)t._combined[e]=this._combined[e];for(let e in this._extendedAttrs)t._extendedAttrs[e]=this._extendedAttrs[e];return t.isWrapped=this.isWrapped,t}getTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(this._data[e*q+0]&4194303)return e+(this._data[e*q+0]>>22);return 0}getNoBgTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(this._data[e*q+0]&4194303||this._data[e*q+2]&50331648)return e+(this._data[e*q+0]>>22);return 0}copyCellsFrom(e,t,n,r,i){let a=e._data;if(i)for(let i=r-1;i>=0;i--){for(let e=0;e<q;e++)this._data[(n+i)*q+e]=a[(t+i)*q+e];a[(t+i)*q+2]&268435456&&(this._extendedAttrs[n+i]=e._extendedAttrs[t+i])}else for(let i=0;i<r;i++){for(let e=0;e<q;e++)this._data[(n+i)*q+e]=a[(t+i)*q+e];a[(t+i)*q+2]&268435456&&(this._extendedAttrs[n+i]=e._extendedAttrs[t+i])}let o=Object.keys(e._combined);for(let r=0;r<o.length;r++){let i=parseInt(o[r],10);i>=t&&(this._combined[i-t+n]=e._combined[i])}}translateToString(e,t,n,r){t??=0,n??=this.length,e&&(n=Math.min(n,this.getTrimmedLength())),r&&(r.length=0);let i=``;for(;t<n;){let e=this._data[t*q+0],n=e&2097151,a=e&2097152?this._combined[t]:n?Ar(n):Fr;if(i+=a,r)for(let e=0;e<a.length;++e)r.push(t);t+=e>>22||1}return r&&r.push(t),i}};function bl(e,t,n,r,i,a){let o=[];for(let s=0;s<e.length-1;s++){let c=s,l=e.get(++c);if(!l.isWrapped)continue;let u=[e.get(s)];for(;c<e.length&&l.isWrapped;)u.push(l),l=e.get(++c);if(!a&&r>=s&&r<c){s+=u.length-1;continue}let d=0,f=wl(u,d,t),p=1,m=0;for(;p<u.length;){let e=wl(u,p,t),r=e-m,a=n-f,o=Math.min(r,a);u[d].copyCellsFrom(u[p],m,f,o,!1),f+=o,f===n&&(d++,f=0),m+=o,m===e&&(p++,m=0),f===0&&d!==0&&u[d-1].getWidth(n-1)===2&&(u[d].copyCellsFrom(u[d-1],n-1,f++,1,!1),u[d-1].setCell(n-1,i))}u[d].replaceCells(f,n,i);let h=0;for(let e=u.length-1;e>0&&(e>d||u[e].getTrimmedLength()===0);e--)h++;h>0&&(o.push(s+u.length-h),o.push(h)),s+=u.length-1}return o}function xl(e,t){let n=[],r=0,i=t[r],a=0;for(let o=0;o<e.length;o++)if(i===o){let n=t[++r];e.onDeleteEmitter.fire({index:o-a,amount:n}),o+=n-1,a+=n,i=t[++r]}else n.push(o);return{layout:n,countRemoved:a}}function Sl(e,t){let n=[];for(let r=0;r<t.length;r++)n.push(e.get(t[r]));for(let t=0;t<n.length;t++)e.set(t,n[t]);e.length=t.length}function Cl(e,t,n){let r=[],i=e.map((n,r)=>wl(e,r,t)).reduce((e,t)=>e+t),a=0,o=0,s=0;for(;s<i;){if(i-s<n){r.push(i-s);break}a+=n;let c=wl(e,o,t);a>c&&(a-=c,o++);let l=e[o].getWidth(a-1)===2;l&&a--;let u=l?n-1:n;r.push(u),s+=u}return r}function wl(e,t,n){if(t===e.length-1)return e[t].getTrimmedLength();let r=!e[t].hasContent(n-1)&&e[t].getWidth(n-1)===1,i=e[t+1].getWidth(0)===2;return r&&i?n-1:n}var Tl=class e{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=e._nextId++,this._onDispose=this.register(new U),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),ki(this._disposables),this._disposables.length=0)}register(e){return this._disposables.push(e),e}};Tl._nextId=1;var El=Tl,Dl={},Ol=Dl.B;Dl[0]={"`":`◆`,a:`▒`,b:`␉`,c:`␌`,d:`␍`,e:`␊`,f:`°`,g:`±`,h:`␤`,i:`␋`,j:`┘`,k:`┐`,l:`┌`,m:`└`,n:`┼`,o:`⎺`,p:`⎻`,q:`─`,r:`⎼`,s:`⎽`,t:`├`,u:`┤`,v:`┴`,w:`┬`,x:`│`,y:`≤`,z:`≥`,"{":`π`,"|":`≠`,"}":`£`,"~":`·`},Dl.A={"#":`£`},Dl.B=void 0,Dl[4]={"#":`£`,"@":`¾`,"[":`ij`,"\\":`½`,"]":`|`,"{":`¨`,"|":`f`,"}":`¼`,"~":`´`},Dl.C=Dl[5]={"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},Dl.R={"#":`£`,"@":`à`,"[":`°`,"\\":`ç`,"]":`§`,"{":`é`,"|":`ù`,"}":`è`,"~":`¨`},Dl.Q={"@":`à`,"[":`â`,"\\":`ç`,"]":`ê`,"^":`î`,"`":`ô`,"{":`é`,"|":`ù`,"}":`è`,"~":`û`},Dl.K={"@":`§`,"[":`Ä`,"\\":`Ö`,"]":`Ü`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`ß`},Dl.Y={"#":`£`,"@":`§`,"[":`°`,"\\":`ç`,"]":`é`,"`":`ù`,"{":`à`,"|":`ò`,"}":`è`,"~":`ì`},Dl.E=Dl[6]={"@":`Ä`,"[":`Æ`,"\\":`Ø`,"]":`Å`,"^":`Ü`,"`":`ä`,"{":`æ`,"|":`ø`,"}":`å`,"~":`ü`},Dl.Z={"#":`£`,"@":`§`,"[":`¡`,"\\":`Ñ`,"]":`¿`,"{":`°`,"|":`ñ`,"}":`ç`},Dl.H=Dl[7]={"@":`É`,"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},Dl[`=`]={"#":`ù`,"@":`à`,"[":`é`,"\\":`ç`,"]":`ê`,"^":`î`,_:`è`,"`":`ô`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`û`};var kl=4294967295,Al=class{constructor(e,t,n){this._hasScrollback=e,this._optionsService=t,this._bufferService=n,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=gl.clone(),this.savedCharset=Ol,this.markers=[],this._nullCell=Rr.fromCharData([0,Pr,1,0]),this._whitespaceCell=Rr.fromCharData([0,Fr,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new Oc,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new hl(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new Lr),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new Lr),this._whitespaceCell}getBlankLine(e,t){return new yl(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&e<this._rows}_getCorrectBufferLength(e){if(!this._hasScrollback)return e;let t=e+this._optionsService.rawOptions.scrollback;return t>kl?kl:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=gl);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new hl(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let n=this.getNullCell(gl),r=0,i=this._getCorrectBufferLength(t);if(i>this.lines.maxLength&&(this.lines.maxLength=i),this.lines.length>0){if(this._cols<e)for(let t=0;t<this.lines.length;t++)r+=+this.lines.get(t).resize(e,n);let a=0;if(this._rows<t)for(let r=this._rows;r<t;r++)this.lines.length<t+this.ybase&&(this._optionsService.rawOptions.windowsMode||this._optionsService.rawOptions.windowsPty.backend!==void 0||this._optionsService.rawOptions.windowsPty.buildNumber!==void 0?this.lines.push(new yl(e,n)):this.ybase>0&&this.lines.length<=this.ybase+this.y+a+1?(this.ybase--,a++,this.ydisp>0&&this.ydisp--):this.lines.push(new yl(e,n)));else for(let e=this._rows;e>t;e--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(i<this.lines.maxLength){let e=this.lines.length-i;e>0&&(this.lines.trimStart(e),this.ybase=Math.max(this.ybase-e,0),this.ydisp=Math.max(this.ydisp-e,0),this.savedY=Math.max(this.savedY-e,0)),this.lines.maxLength=i}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),a&&(this.y+=a),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let t=0;t<this.lines.length;t++)r+=+this.lines.get(t).resize(e,n);this._cols=e,this._rows=t,this._memoryCleanupQueue.clear(),r>.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition<this.lines.length;)if(t+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),t>100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&e.backend===`conpty`&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let n=this._optionsService.rawOptions.reflowCursorLine,r=bl(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(gl),n);if(r.length>0){let n=xl(this.lines,r);Sl(this.lines,n.layout),this._reflowLargerAdjustViewport(e,t,n.countRemoved)}}_reflowLargerAdjustViewport(e,t,n){let r=this.getNullCell(gl),i=n;for(;i-->0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<t&&this.lines.push(new yl(e,r))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-n,0)}_reflowSmaller(e,t){let n=this._optionsService.rawOptions.reflowCursorLine,r=this.getNullCell(gl),i=[],a=0;for(let o=this.lines.length-1;o>=0;o--){let s=this.lines.get(o);if(!s||!s.isWrapped&&s.getTrimmedLength()<=e)continue;let c=[s];for(;s.isWrapped&&o>0;)s=this.lines.get(--o),c.unshift(s);if(!n){let e=this.ybase+this.y;if(e>=o&&e<o+c.length)continue}let l=c[c.length-1].getTrimmedLength(),u=Cl(c,this._cols,e),d=u.length-c.length,f;f=this.ybase===0&&this.y!==this.lines.length-1?Math.max(0,this.y-this.lines.maxLength+d):Math.max(0,this.lines.length-this.lines.maxLength+d);let p=[];for(let e=0;e<d;e++){let e=this.getBlankLine(gl,!0);p.push(e)}p.length>0&&(i.push({start:o+c.length+a,newLines:p}),a+=p.length),c.push(...p);let m=u.length-1,h=u[m];h===0&&(m--,h=u[m]);let g=c.length-d-1,_=l;for(;g>=0;){let e=Math.min(_,h);if(c[m]===void 0)break;c[m].copyCellsFrom(c[g],_-e,h-e,e,!0),h-=e,h===0&&(m--,h=u[m]),_-=e,_===0&&(g--,_=wl(c,Math.max(g,0),this._cols))}for(let t=0;t<c.length;t++)u[t]<e&&c[t].setCell(u[t],r);let v=d-f;for(;v-->0;)this.ybase===0?this.y<t-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+a)-t&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+d,this.ybase+t-1)}if(i.length>0){let e=[],t=[];for(let e=0;e<this.lines.length;e++)t.push(this.lines.get(e));let n=this.lines.length,r=n-1,o=0,s=i[o];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+a);let c=0;for(let l=Math.min(this.lines.maxLength-1,n+a-1);l>=0;l--)if(s&&s.start>r+c){for(let e=s.newLines.length-1;e>=0;e--)this.lines.set(l--,s.newLines[e]);l++,e.push({index:r+1,amount:s.newLines.length}),c+=s.newLines.length,s=i[++o]}else this.lines.set(l,t[r--]);let l=0;for(let t=e.length-1;t>=0;t--)e[t].index+=l,this.lines.onInsertEmitter.fire(e[t]),l+=e[t].amount;let u=Math.max(0,n+a-this.lines.maxLength);u>0&&this.lines.onTrimEmitter.fire(u)}}translateBufferLineToString(e,t,n=0,r){let i=this.lines.get(e);return i?i.translateToString(t,n,r):``}getWrappedRangeForLine(e){let t=e,n=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;n+1<this.lines.length&&this.lines.get(n+1).isWrapped;)n++;return{first:t,last:n}}setupTabStops(e){for(e==null?(this.tabs={},e=0):this.tabs[e]||(e=this.prevStop(e));e<this._cols;e+=this._optionsService.rawOptions.tabStopWidth)this.tabs[e]=!0}prevStop(e){for(e??=this.x;!this.tabs[--e]&&e>0;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e??=this.x;!this.tabs[++e]&&e<this._cols;);return e>=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t<this.markers.length;t++)this.markers[t].line===e&&(this.markers[t].dispose(),this.markers.splice(t--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let e=0;e<this.markers.length;e++)this.markers[e].dispose();this.markers.length=0,this._isClearing=!1}addMarker(e){let t=new El(e);return this.markers.push(t),t.register(this.lines.onTrim(e=>{t.line-=e,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(e=>{t.line>=e.index&&(t.line+=e.amount)})),t.register(this.lines.onDelete(e=>{t.line>=e.index&&t.line<e.index+e.amount&&t.dispose(),t.line>e.index&&(t.line-=e.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},jl=class extends H{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new U),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this._register(this._optionsService.onSpecificOptionChange(`scrollback`,()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this._register(this._optionsService.onSpecificOptionChange(`tabStopWidth`,()=>this.setupTabStops()))}reset(){this._normal=new Al(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new Al(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}},Ml=2,Nl=1,Pl=class extends H{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new U),this.onResize=this._onResize.event,this._onScroll=this._register(new U),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,Ml),this.rows=Math.max(e.rawOptions.rows||0,Nl),this.buffers=this._register(new jl(e,this)),this._register(this.buffers.onBufferActivate(e=>{this._onScroll.fire(e.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let n=this.cols!==e,r=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:n,rowsChanged:r})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let n=this.buffer,r;r=this._cachedBlankLine,(!r||r.length!==this.cols||r.getFg(0)!==e.fg||r.getBg(0)!==e.bg)&&(r=n.getBlankLine(e,t),this._cachedBlankLine=r),r.isWrapped=t;let i=n.ybase+n.scrollTop,a=n.ybase+n.scrollBottom;if(n.scrollTop===0){let e=n.lines.isFull;a===n.lines.length-1?e?n.lines.recycle().copyFrom(r):n.lines.push(r.clone()):n.lines.splice(a+1,0,r.clone()),e?this.isUserScrolling&&(n.ydisp=Math.max(n.ydisp-1,0)):(n.ybase++,this.isUserScrolling||n.ydisp++)}else{let e=a-i+1;n.lines.shiftElements(i+1,e-1,-1),n.lines.set(a,r.clone())}this.isUserScrolling||(n.ydisp=n.ybase),this._onScroll.fire(n.ydisp)}scrollLines(e,t){let n=this.buffer;if(e<0){if(n.ydisp===0)return;this.isUserScrolling=!0}else e+n.ydisp>=n.ybase&&(this.isUserScrolling=!1);let r=n.ydisp;n.ydisp=Math.max(Math.min(n.ydisp+e,n.ybase),0),r!==n.ydisp&&(t||this._onScroll.fire(n.ydisp))}};Pl=R([z(0,Zr)],Pl);var Fl={cols:80,rows:24,cursorBlink:!1,cursorStyle:`block`,cursorWidth:1,cursorInactiveStyle:`outline`,customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:`alt`,fastScrollSensitivity:5,fontFamily:`monospace`,fontSize:15,fontWeight:`normal`,fontWeightBold:`bold`,ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:`info`,logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:yc,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:` ()[]{}',"\``,altClickMovesCursor:!0,convertEol:!1,termName:`xterm`,cancelEvents:!1,overviewRuler:{}},Il=[`normal`,`bold`,`100`,`200`,`300`,`400`,`500`,`600`,`700`,`800`,`900`],Ll=class extends H{constructor(e){super(),this._onOptionChange=this._register(new U),this.onOptionChange=this._onOptionChange.event;let t={...Fl};for(let n in e)if(n in t)try{let r=e[n];t[n]=this._sanitizeAndValidateOption(n,r)}catch(e){console.error(e)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register(V(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(n=>{n===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(n=>{e.indexOf(n)!==-1&&t()})}_setupOptions(){let e=e=>{if(!(e in Fl))throw Error(`No option with key "${e}"`);return this.rawOptions[e]},t=(e,t)=>{if(!(e in Fl))throw Error(`No option with key "${e}"`);t=this._sanitizeAndValidateOption(e,t),this.rawOptions[e]!==t&&(this.rawOptions[e]=t,this._onOptionChange.fire(e))};for(let n in this.rawOptions){let r={get:e.bind(this,n),set:t.bind(this,n)};Object.defineProperty(this.options,n,r)}}_sanitizeAndValidateOption(e,t){switch(e){case`cursorStyle`:if(t||=Fl[e],!Rl(t))throw Error(`"${t}" is not a valid value for ${e}`);break;case`wordSeparator`:t||=Fl[e];break;case`fontWeight`:case`fontWeightBold`:if(typeof t==`number`&&1<=t&&t<=1e3)break;t=Il.includes(t)?t:Fl[e];break;case`cursorWidth`:t=Math.floor(t);case`lineHeight`:case`tabStopWidth`:if(t<1)throw Error(`${e} cannot be less than 1, value: ${t}`);break;case`minimumContrastRatio`:t=Math.max(1,Math.min(21,Math.round(t*10)/10));break;case`scrollback`:if(t=Math.min(t,4294967295),t<0)throw Error(`${e} cannot be less than 0, value: ${t}`);break;case`fastScrollSensitivity`:case`scrollSensitivity`:if(t<=0)throw Error(`${e} cannot be less than or equal to 0, value: ${t}`);break;case`rows`:case`cols`:if(!t&&t!==0)throw Error(`${e} must be numeric, value: ${t}`);break;case`windowsPty`:t??={}}return t}};function Rl(e){return e===`block`||e===`underline`||e===`bar`}function zl(e,t=5){if(typeof e!=`object`)return e;let n=Array.isArray(e)?[]:{};for(let r in e)n[r]=t<=1?e[r]:e[r]&&zl(e[r],t-1);return n}var Bl=Object.freeze({insertMode:!1}),Vl=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),Hl=class extends H{constructor(e,t,n){super(),this._bufferService=e,this._logService=t,this._optionsService=n,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new U),this.onData=this._onData.event,this._onUserInput=this._register(new U),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new U),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new U),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=zl(Bl),this.decPrivateModes=zl(Vl)}reset(){this.modes=zl(Bl),this.decPrivateModes=zl(Vl)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let n=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&n.ybase!==n.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace(`sending data (codes)`,()=>e.split(``).map(e=>e.charCodeAt(0))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`),this._logService.trace(`sending binary (codes)`,()=>e.split(``).map(e=>e.charCodeAt(0))),this._onBinary.fire(e))}};Hl=R([z(0,Gr),z(1,Xr),z(2,Zr)],Hl);var Ul={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>e.button===4||e.action!==1?!1:(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>e.action!==32},DRAG:{events:23,restrict:e=>e.action!==32||e.button!==3},ANY:{events:31,restrict:e=>!0}};function Wl(e,t){let n=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(n|=64,n|=e.action):(n|=e.button&3,e.button&4&&(n|=64),e.button&8&&(n|=128),e.action===32?n|=32:e.action===0&&!t&&(n|=3)),n}var Gl=String.fromCharCode,Kl={DEFAULT:e=>{let t=[Wl(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?``:`\x1B[M${Gl(t[0])}${Gl(t[1])}${Gl(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`\x1B[<${Wl(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`\x1B[<${Wl(e,!0)};${e.x};${e.y}${t}`}},ql=class extends H{constructor(e,t,n){super(),this._bufferService=e,this._coreService=t,this._optionsService=n,this._protocols={},this._encodings={},this._activeProtocol=``,this._activeEncoding=``,this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new U),this.onProtocolChange=this._onProtocolChange.event;for(let e of Object.keys(Ul))this.addProtocol(e,Ul[e]);for(let e of Object.keys(Kl))this.addEncoding(e,Kl[e]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e){if(!this._protocols[e])throw Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol=`NONE`,this.activeEncoding=`DEFAULT`,this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,t,n){if(e.deltaY===0||e.shiftKey||t===void 0||n===void 0)return 0;let r=t/n,i=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(i/=r+0,Math.abs(e.deltaY)<50&&(i*=.3),this._wheelPartialScroll+=i,i=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(i*=this._bufferService.rows),i}_applyScrollModifier(e,t){return t.altKey||t.ctrlKey||t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding===`SGR_PIXELS`))||!this._protocols[this._activeProtocol].restrict(e))return!1;let t=this._encodings[this._activeEncoding](e);return t&&(this._activeEncoding===`DEFAULT`?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(e&1),up:!!(e&2),drag:!!(e&4),move:!!(e&8),wheel:!!(e&16)}}_equalEvents(e,t,n){if(n){if(e.x!==t.x||e.y!==t.y)return!1}else if(e.col!==t.col||e.row!==t.row)return!1;return e.button===t.button&&e.action===t.action&&e.ctrl===t.ctrl&&e.alt===t.alt&&e.shift===t.shift}};ql=R([z(0,Gr),z(1,qr),z(2,Zr)],ql);var Jl=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],Yl=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],Xl;function Zl(e,t){let n=0,r=t.length-1,i;if(e<t[0][0]||e>t[r][1])return!1;for(;r>=n;)if(i=n+r>>1,e>t[i][1])n=i+1;else if(e<t[i][0])r=i-1;else return!0;return!1}var Ql=class{constructor(){if(this.version=`6`,!Xl){Xl=new Uint8Array(65536),Xl.fill(1),Xl[0]=0,Xl.fill(0,1,32),Xl.fill(0,127,160),Xl.fill(2,4352,4448),Xl[9001]=2,Xl[9002]=2,Xl.fill(2,11904,42192),Xl[12351]=1,Xl.fill(2,44032,55204),Xl.fill(2,63744,64256),Xl.fill(2,65040,65050),Xl.fill(2,65072,65136),Xl.fill(2,65280,65377),Xl.fill(2,65504,65511);for(let e=0;e<Jl.length;++e)Xl.fill(0,Jl[e][0],Jl[e][1]+1)}}wcwidth(e){return e<32?0:e<127?1:e<65536?Xl[e]:Zl(e,Yl)?0:e>=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let n=this.wcwidth(e),r=n===0&&t!==0;if(r){let e=$l.extractWidth(t);e===0?r=!1:e>n&&(n=e)}return $l.createPropertyValue(0,n,r)}},$l=class e{constructor(){this._providers=Object.create(null),this._active=``,this._onChange=new U,this.onChange=this._onChange.event;let e=new Ql;this.register(e),this._active=e.version,this._activeProvider=e}static extractShouldJoin(e){return!!(e&1)}static extractWidth(e){return e>>1&3}static extractCharKind(e){return e>>3}static createPropertyValue(e,t,n=!1){return(e&16777215)<<3|(t&3)<<1|!!n}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(e){if(!this._providers[e])throw Error(`unknown Unicode version "${e}"`);this._active=e,this._activeProvider=this._providers[e],this._onChange.fire(e)}register(e){this._providers[e.version]=e}wcwidth(e){return this._activeProvider.wcwidth(e)}getStringCellWidth(t){let n=0,r=0,i=t.length;for(let a=0;a<i;++a){let o=t.charCodeAt(a);if(55296<=o&&o<=56319){if(++a>=i)return n+this.wcwidth(o);let e=t.charCodeAt(a);56320<=e&&e<=57343?o=(o-55296)*1024+e-56320+65536:n+=this.wcwidth(e)}let s=this.charProperties(o,r),c=e.extractWidth(s);e.extractShouldJoin(s)&&(c-=e.extractWidth(r)),n+=c,r=s}return n}charProperties(e,t){return this._activeProvider.charProperties(e,t)}},eu=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}};function tu(e){let t=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1)?.get(e.cols-1),n=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);n&&t&&(n.isWrapped=t[3]!==0&&t[3]!==32)}var nu=2147483647,ru=256,iu=class e{constructor(e=32,t=32){if(this.maxLength=e,this.maxSubParamsLength=t,t>ru)throw Error(`maxSubParamsLength must not be greater than 256`);this.params=new Int32Array(e),this.length=0,this._subParams=new Int32Array(t),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(e),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let n=new e;if(!t.length)return n;for(let e=+!!Array.isArray(t[0]);e<t.length;++e){let r=t[e];if(Array.isArray(r))for(let e=0;e<r.length;++e)n.addSubParam(r[e]);else n.addParam(r)}return n}clone(){let t=new e(this.maxLength,this.maxSubParamsLength);return t.params.set(this.params),t.length=this.length,t._subParams.set(this._subParams),t._subParamsLength=this._subParamsLength,t._subParamsIdx.set(this._subParamsIdx),t._rejectDigits=this._rejectDigits,t._rejectSubDigits=this._rejectSubDigits,t._digitIsSub=this._digitIsSub,t}toArray(){let e=[];for(let t=0;t<this.length;++t){e.push(this.params[t]);let n=this._subParamsIdx[t]>>8,r=this._subParamsIdx[t]&255;r-n>0&&e.push(Array.prototype.slice.call(this._subParams,n,r))}return e}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(e){if(this._digitIsSub=!1,this.length>=this.maxLength)this._rejectDigits=!0;else{if(e<-1)throw Error(`values lesser than -1 are not allowed`);this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=e>nu?nu:e}}addSubParam(e){if(this._digitIsSub=!0,this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength){this._rejectSubDigits=!0;return}if(e<-1)throw Error(`values lesser than -1 are not allowed`);this._subParams[this._subParamsLength++]=e>nu?nu:e,this._subParamsIdx[this.length-1]++}}hasSubParams(e){return(this._subParamsIdx[e]&255)-(this._subParamsIdx[e]>>8)>0}getSubParams(e){let t=this._subParamsIdx[e]>>8,n=this._subParamsIdx[e]&255;return n-t>0?this._subParams.subarray(t,n):null}getSubParamsAll(){let e={};for(let t=0;t<this.length;++t){let n=this._subParamsIdx[t]>>8,r=this._subParamsIdx[t]&255;r-n>0&&(e[t]=this._subParams.slice(n,r))}return e}addDigit(e){let t;if(this._rejectDigits||!(t=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let n=this._digitIsSub?this._subParams:this.params,r=n[t-1];n[t-1]=~r?Math.min(r*10+e,nu):e}},au=[],ou=class{constructor(){this._state=0,this._active=au,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=au}reset(){if(this._state===2)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=au,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||au,!this._active.length)this._handlerFb(this._id,`START`);else for(let e=this._active.length-1;e>=0;e--)this._active[e].start()}_put(e,t,n){if(!this._active.length)this._handlerFb(this._id,`PUT`,jr(e,t,n));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n)}start(){this.reset(),this._state=1}put(e,t,n){if(this._state!==3){if(this._state===1)for(;t<n;){let n=e[t++];if(n===59){this._state=2,this._start();break}if(n<48||57<n){this._state=3;return}this._id===-1&&(this._id=0),this._id=this._id*10+n-48}this._state===2&&n-t>0&&this._put(e,t,n)}}end(e,t=!0){if(this._state!==0){if(this._state!==3){if(this._state===1&&this._start(),!this._active.length)this._handlerFb(this._id,`END`,e);else{let n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&n===!1){for(;r>=0&&(n=this._active[r].end(e),n!==!0);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].end(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}}this._active=au,this._id=-1,this._state=0}}},su=class{constructor(e){this._handler=e,this._data=``,this._hitLimit=!1}start(){this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=jr(e,t,n),this._data.length>1e7&&(this._data=``,this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then(e=>(this._data=``,this._hitLimit=!1,e));return this._data=``,this._hitLimit=!1,t}},cu=[],lu=class{constructor(){this._handlers=Object.create(null),this._active=cu,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=cu}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=cu,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||cu,!this._active.length)this._handlerFb(this._ident,`HOOK`,t);else for(let e=this._active.length-1;e>=0;e--)this._active[e].hook(t)}put(e,t,n){if(!this._active.length)this._handlerFb(this._ident,`PUT`,jr(e,t,n));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n)}unhook(e,t=!0){if(!this._active.length)this._handlerFb(this._ident,`UNHOOK`,e);else{let n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&n===!1){for(;r>=0&&(n=this._active[r].unhook(e),n!==!0);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].unhook(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}this._active=cu,this._ident=0}},uu=new iu;uu.addParam(0);var du=class{constructor(e){this._handler=e,this._data=``,this._params=uu,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():uu,this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=jr(e,t,n),this._data.length>1e7&&(this._data=``,this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then(e=>(this._params=uu,this._data=``,this._hitLimit=!1,e));return this._params=uu,this._data=``,this._hitLimit=!1,t}},fu=class{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,n,r){this.table[t<<8|e]=n<<4|r}addMany(e,t,n,r){for(let i=0;i<e.length;i++)this.table[t<<8|e[i]]=n<<4|r}},pu=160,mu=function(){let e=new fu(4095),t=Array.apply(null,Array(256)).map((e,t)=>t),n=(e,n)=>t.slice(e,n),r=n(32,127),i=n(0,24);i.push(25),i.push.apply(i,n(28,32));let a=n(0,14),o;for(o in e.setDefault(1,0),e.addMany(r,0,2,0),a)e.addMany([24,26,153,154],o,3,0),e.addMany(n(128,144),o,3,0),e.addMany(n(144,152),o,3,0),e.add(156,o,0,0),e.add(27,o,11,1),e.add(157,o,4,8),e.addMany([152,158,159],o,0,7),e.add(155,o,11,3),e.add(144,o,11,9);return e.addMany(i,0,3,0),e.addMany(i,1,3,1),e.add(127,1,0,1),e.addMany(i,8,0,8),e.addMany(i,3,3,3),e.add(127,3,0,3),e.addMany(i,4,3,4),e.add(127,4,0,4),e.addMany(i,6,3,6),e.addMany(i,5,3,5),e.add(127,5,0,5),e.addMany(i,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(r,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(n(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(r,7,0,7),e.addMany(i,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(n(64,127),3,7,0),e.addMany(n(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(n(48,60),4,8,4),e.addMany(n(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(n(32,64),6,0,6),e.add(127,6,0,6),e.addMany(n(64,127),6,0,0),e.addMany(n(32,48),3,9,5),e.addMany(n(32,48),5,9,5),e.addMany(n(48,64),5,0,6),e.addMany(n(64,127),5,7,0),e.addMany(n(32,48),4,9,5),e.addMany(n(32,48),1,9,2),e.addMany(n(32,48),2,9,2),e.addMany(n(48,127),2,10,0),e.addMany(n(48,80),1,10,0),e.addMany(n(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(n(96,127),1,10,0),e.add(80,1,11,9),e.addMany(i,9,0,9),e.add(127,9,0,9),e.addMany(n(28,32),9,0,9),e.addMany(n(32,48),9,9,12),e.addMany(n(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(i,11,0,11),e.addMany(n(32,128),11,0,11),e.addMany(n(28,32),11,0,11),e.addMany(i,10,0,10),e.add(127,10,0,10),e.addMany(n(28,32),10,0,10),e.addMany(n(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(n(32,48),10,9,12),e.addMany(i,12,0,12),e.add(127,12,0,12),e.addMany(n(28,32),12,0,12),e.addMany(n(32,48),12,9,12),e.addMany(n(48,64),12,0,11),e.addMany(n(64,127),12,12,13),e.addMany(n(64,127),10,12,13),e.addMany(n(64,127),9,12,13),e.addMany(i,13,13,13),e.addMany(r,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(pu,0,2,0),e.add(pu,8,5,8),e.add(pu,6,0,6),e.add(pu,11,0,11),e.add(pu,13,13,13),e}(),hu=class extends H{constructor(e=mu){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new iu,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(e,t,n)=>{},this._executeHandlerFb=e=>{},this._csiHandlerFb=(e,t)=>{},this._escHandlerFb=e=>{},this._errorHandlerFb=e=>e,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register(V(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new ou),this._dcsParser=this._register(new lu),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:`\\`},()=>!0)}_identifier(e,t=[64,126]){let n=0;if(e.prefix){if(e.prefix.length>1)throw Error(`only one byte as prefix supported`);if(n=e.prefix.charCodeAt(0),n&&60>n||n>63)throw Error(`prefix must be in range 0x3c .. 0x3f`)}if(e.intermediates){if(e.intermediates.length>2)throw Error(`only two bytes as intermediates are supported`);for(let t=0;t<e.intermediates.length;++t){let r=e.intermediates.charCodeAt(t);if(32>r||r>47)throw Error(`intermediate must be in range 0x20 .. 0x2f`);n<<=8,n|=r}}if(e.final.length!==1)throw Error(`final must be a single byte`);let r=e.final.charCodeAt(0);if(t[0]>r||r>t[1])throw Error(`final must be in range ${t[0]} .. ${t[1]}`);return n<<=8,n|=r,n}identToString(e){let t=[];for(;e;)t.push(String.fromCharCode(e&255)),e>>=8;return t.reverse().join(``)}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){let n=this._identifier(e,[48,126]);this._escHandlers[n]===void 0&&(this._escHandlers[n]=[]);let r=this._escHandlers[n];return r.push(t),{dispose:()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){let n=this._identifier(e);this._csiHandlers[n]===void 0&&(this._csiHandlers[n]=[]);let r=this._csiHandlers[n];return r.push(t),{dispose:()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,t,n,r,i){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=n,this._parseStack.transition=r,this._parseStack.chunkPos=i}parse(e,t,n){let r=0,i=0,a=0,o;if(this._parseStack.state){if(this._parseStack.state===2)this._parseStack.state=0,a=this._parseStack.chunkPos+1;else{if(n===void 0||this._parseStack.state===1)throw this._parseStack.state=1,Error(`improper continuation due to previous async handler, giving up parsing`);let t=this._parseStack.handlers,i=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(n===!1&&i>-1){for(;i>=0&&(o=t[i](this._params),o!==!0);i--)if(o instanceof Promise)return this._parseStack.handlerPos=i,o}this._parseStack.handlers=[];break;case 4:if(n===!1&&i>-1){for(;i>=0&&(o=t[i](),o!==!0);i--)if(o instanceof Promise)return this._parseStack.handlerPos=i,o}this._parseStack.handlers=[];break;case 6:if(r=e[this._parseStack.chunkPos],o=this._dcsParser.unhook(r!==24&&r!==26,n),o)return o;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(r=e[this._parseStack.chunkPos],o=this._oscParser.end(r!==24&&r!==26,n),o)return o;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,a=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}}for(let n=a;n<t;++n){switch(r=e[n],i=this._transitions.table[this.currentState<<8|(r<160?r:pu)],i>>4){case 2:for(let i=n+1;;++i)if(i>=t||(r=e[i])<32||r>126&&r<pu||++i>=t||(r=e[i])<32||r>126&&r<pu||++i>=t||(r=e[i])<32||r>126&&r<pu||++i>=t||(r=e[i])<32||r>126&&r<pu){this._printHandler(e,n,i),n=i-1;break}break;case 3:this._executeHandlers[r]?this._executeHandlers[r]():this._executeHandlerFb(r),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:n,code:r,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:let a=this._csiHandlers[this._collect<<8|r],s=a?a.length-1:-1;for(;s>=0&&(o=a[s](this._params),o!==!0);s--)if(o instanceof Promise)return this._preserveStack(3,a,s,i,n),o;s<0&&this._csiHandlerFb(this._collect<<8|r,this._params),this.precedingJoinState=0;break;case 8:do switch(r){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(r-48)}while(++n<t&&(r=e[n])>47&&r<60);n--;break;case 9:this._collect<<=8,this._collect|=r;break;case 10:let c=this._escHandlers[this._collect<<8|r],l=c?c.length-1:-1;for(;l>=0&&(o=c[l](),o!==!0);l--)if(o instanceof Promise)return this._preserveStack(4,c,l,i,n),o;l<0&&this._escHandlerFb(this._collect<<8|r),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|r,this._params);break;case 13:for(let i=n+1;;++i)if(i>=t||(r=e[i])===24||r===26||r===27||r>127&&r<pu){this._dcsParser.put(e,n,i),n=i-1;break}break;case 14:if(o=this._dcsParser.unhook(r!==24&&r!==26),o)return this._preserveStack(6,[],0,i,n),o;r===27&&(i|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break;case 4:this._oscParser.start();break;case 5:for(let i=n+1;;i++)if(i>=t||(r=e[i])<32||r>127&&r<pu){this._oscParser.put(e,n,i),n=i-1;break}break;case 6:if(o=this._oscParser.end(r!==24&&r!==26),o)return this._preserveStack(5,[],0,i,n),o;r===27&&(i|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0}this.currentState=i&15}}},gu=/^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/,_u=/^[\da-f]+$/;function vu(e){if(!e)return;let t=e.toLowerCase();if(t.indexOf(`rgb:`)===0){t=t.slice(4);let e=gu.exec(t);if(e){let t=e[1]?15:e[4]?255:e[7]?4095:65535;return[Math.round(parseInt(e[1]||e[4]||e[7]||e[10],16)/t*255),Math.round(parseInt(e[2]||e[5]||e[8]||e[11],16)/t*255),Math.round(parseInt(e[3]||e[6]||e[9]||e[12],16)/t*255)]}}else if(t.indexOf(`#`)===0&&(t=t.slice(1),_u.exec(t)&&[3,6,9,12].includes(t.length))){let e=t.length/3,n=[0,0,0];for(let r=0;r<3;++r){let i=parseInt(t.slice(e*r,e*r+e),16);n[r]=e===1?i<<4:e===2?i:e===3?i>>4:i>>8}return n}}function yu(e,t){let n=e.toString(16),r=n.length<2?`0`+n:n;switch(t){case 4:return n[0];case 8:return r;case 12:return(r+r).slice(0,3);default:return r+r}}function bu(e,t=16){let[n,r,i]=e;return`rgb:${yu(n,t)}/${yu(r,t)}/${yu(i,t)}`}var xu={"(":0,")":1,"*":2,"+":3,"-":1,".":2},Su=131072,Cu=10;function wu(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var Tu=5e3,Eu=0,Du=class extends H{constructor(e,t,n,r,i,a,o,s,c=new hu){super(),this._bufferService=e,this._charsetService=t,this._coreService=n,this._logService=r,this._optionsService=i,this._oscLinkService=a,this._coreMouseService=o,this._unicodeService=s,this._parser=c,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new Mr,this._utf8Decoder=new Nr,this._windowTitle=``,this._iconName=``,this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=gl.clone(),this._eraseAttrDataInternal=gl.clone(),this._onRequestBell=this._register(new U),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new U),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new U),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new U),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new U),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new U),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new U),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new U),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new U),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new U),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new U),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new U),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new U),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 Ou(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(e=>this._activeBuffer=e.activeBuffer)),this._parser.setCsiHandlerFallback((e,t)=>{this._logService.debug(`Unknown CSI code: `,{identifier:this._parser.identToString(e),params:t.toArray()})}),this._parser.setEscHandlerFallback(e=>{this._logService.debug(`Unknown ESC code: `,{identifier:this._parser.identToString(e)})}),this._parser.setExecuteHandlerFallback(e=>{this._logService.debug(`Unknown EXECUTE code: `,{code:e})}),this._parser.setOscHandlerFallback((e,t,n)=>{this._logService.debug(`Unknown OSC code: `,{identifier:e,action:t,data:n})}),this._parser.setDcsHandlerFallback((e,t,n)=>{t===`HOOK`&&(n=n.toArray()),this._logService.debug(`Unknown DCS code: `,{identifier:this._parser.identToString(e),action:t,payload:n})}),this._parser.setPrintHandler((e,t,n)=>this.print(e,t,n)),this._parser.registerCsiHandler({final:`@`},e=>this.insertChars(e)),this._parser.registerCsiHandler({intermediates:` `,final:`@`},e=>this.scrollLeft(e)),this._parser.registerCsiHandler({final:`A`},e=>this.cursorUp(e)),this._parser.registerCsiHandler({intermediates:` `,final:`A`},e=>this.scrollRight(e)),this._parser.registerCsiHandler({final:`B`},e=>this.cursorDown(e)),this._parser.registerCsiHandler({final:`C`},e=>this.cursorForward(e)),this._parser.registerCsiHandler({final:`D`},e=>this.cursorBackward(e)),this._parser.registerCsiHandler({final:`E`},e=>this.cursorNextLine(e)),this._parser.registerCsiHandler({final:`F`},e=>this.cursorPrecedingLine(e)),this._parser.registerCsiHandler({final:`G`},e=>this.cursorCharAbsolute(e)),this._parser.registerCsiHandler({final:`H`},e=>this.cursorPosition(e)),this._parser.registerCsiHandler({final:`I`},e=>this.cursorForwardTab(e)),this._parser.registerCsiHandler({final:`J`},e=>this.eraseInDisplay(e,!1)),this._parser.registerCsiHandler({prefix:`?`,final:`J`},e=>this.eraseInDisplay(e,!0)),this._parser.registerCsiHandler({final:`K`},e=>this.eraseInLine(e,!1)),this._parser.registerCsiHandler({prefix:`?`,final:`K`},e=>this.eraseInLine(e,!0)),this._parser.registerCsiHandler({final:`L`},e=>this.insertLines(e)),this._parser.registerCsiHandler({final:`M`},e=>this.deleteLines(e)),this._parser.registerCsiHandler({final:`P`},e=>this.deleteChars(e)),this._parser.registerCsiHandler({final:`S`},e=>this.scrollUp(e)),this._parser.registerCsiHandler({final:`T`},e=>this.scrollDown(e)),this._parser.registerCsiHandler({final:`X`},e=>this.eraseChars(e)),this._parser.registerCsiHandler({final:`Z`},e=>this.cursorBackwardTab(e)),this._parser.registerCsiHandler({final:"`"},e=>this.charPosAbsolute(e)),this._parser.registerCsiHandler({final:`a`},e=>this.hPositionRelative(e)),this._parser.registerCsiHandler({final:`b`},e=>this.repeatPrecedingCharacter(e)),this._parser.registerCsiHandler({final:`c`},e=>this.sendDeviceAttributesPrimary(e)),this._parser.registerCsiHandler({prefix:`>`,final:`c`},e=>this.sendDeviceAttributesSecondary(e)),this._parser.registerCsiHandler({final:`d`},e=>this.linePosAbsolute(e)),this._parser.registerCsiHandler({final:`e`},e=>this.vPositionRelative(e)),this._parser.registerCsiHandler({final:`f`},e=>this.hVPosition(e)),this._parser.registerCsiHandler({final:`g`},e=>this.tabClear(e)),this._parser.registerCsiHandler({final:`h`},e=>this.setMode(e)),this._parser.registerCsiHandler({prefix:`?`,final:`h`},e=>this.setModePrivate(e)),this._parser.registerCsiHandler({final:`l`},e=>this.resetMode(e)),this._parser.registerCsiHandler({prefix:`?`,final:`l`},e=>this.resetModePrivate(e)),this._parser.registerCsiHandler({final:`m`},e=>this.charAttributes(e)),this._parser.registerCsiHandler({final:`n`},e=>this.deviceStatus(e)),this._parser.registerCsiHandler({prefix:`?`,final:`n`},e=>this.deviceStatusPrivate(e)),this._parser.registerCsiHandler({intermediates:`!`,final:`p`},e=>this.softReset(e)),this._parser.registerCsiHandler({intermediates:` `,final:`q`},e=>this.setCursorStyle(e)),this._parser.registerCsiHandler({final:`r`},e=>this.setScrollRegion(e)),this._parser.registerCsiHandler({final:`s`},e=>this.saveCursor(e)),this._parser.registerCsiHandler({final:`t`},e=>this.windowOptions(e)),this._parser.registerCsiHandler({final:`u`},e=>this.restoreCursor(e)),this._parser.registerCsiHandler({intermediates:`'`,final:`}`},e=>this.insertColumns(e)),this._parser.registerCsiHandler({intermediates:`'`,final:`~`},e=>this.deleteColumns(e)),this._parser.registerCsiHandler({intermediates:`"`,final:`q`},e=>this.selectProtected(e)),this._parser.registerCsiHandler({intermediates:`$`,final:`p`},e=>this.requestMode(e,!0)),this._parser.registerCsiHandler({prefix:`?`,intermediates:`$`,final:`p`},e=>this.requestMode(e,!1)),this._parser.setExecuteHandler(G.BEL,()=>this.bell()),this._parser.setExecuteHandler(G.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(G.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(G.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(G.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(G.BS,()=>this.backspace()),this._parser.setExecuteHandler(G.HT,()=>this.tab()),this._parser.setExecuteHandler(G.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(G.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(ys.IND,()=>this.index()),this._parser.setExecuteHandler(ys.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(ys.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new su(e=>(this.setTitle(e),this.setIconName(e),!0))),this._parser.registerOscHandler(1,new su(e=>this.setIconName(e))),this._parser.registerOscHandler(2,new su(e=>this.setTitle(e))),this._parser.registerOscHandler(4,new su(e=>this.setOrReportIndexedColor(e))),this._parser.registerOscHandler(8,new su(e=>this.setHyperlink(e))),this._parser.registerOscHandler(10,new su(e=>this.setOrReportFgColor(e))),this._parser.registerOscHandler(11,new su(e=>this.setOrReportBgColor(e))),this._parser.registerOscHandler(12,new su(e=>this.setOrReportCursorColor(e))),this._parser.registerOscHandler(104,new su(e=>this.restoreIndexedColor(e))),this._parser.registerOscHandler(110,new su(e=>this.restoreFgColor(e))),this._parser.registerOscHandler(111,new su(e=>this.restoreBgColor(e))),this._parser.registerOscHandler(112,new su(e=>this.restoreCursorColor(e))),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 e in Dl)this._parser.registerEscHandler({intermediates:`(`,final:e},()=>this.selectCharset(`(`+e)),this._parser.registerEscHandler({intermediates:`)`,final:e},()=>this.selectCharset(`)`+e)),this._parser.registerEscHandler({intermediates:`*`,final:e},()=>this.selectCharset(`*`+e)),this._parser.registerEscHandler({intermediates:`+`,final:e},()=>this.selectCharset(`+`+e)),this._parser.registerEscHandler({intermediates:`-`,final:e},()=>this.selectCharset(`-`+e)),this._parser.registerEscHandler({intermediates:`.`,final:e},()=>this.selectCharset(`.`+e)),this._parser.registerEscHandler({intermediates:`/`,final:e},()=>this.selectCharset(`/`+e));this._parser.registerEscHandler({intermediates:`#`,final:`8`},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(e=>(this._logService.error(`Parsing error: `,e),e)),this._parser.registerDcsHandler({intermediates:`$`,final:`q`},new du((e,t)=>this.requestStatusString(e,t)))}getAttrData(){return this._curAttrData}_preserveStack(e,t,n,r){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=n,this._parseStack.position=r}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((e,t)=>setTimeout(()=>t(`#SLOW_TIMEOUT`),Tu))]).catch(e=>{if(e!==`#SLOW_TIMEOUT`)throw e;console.warn(`async parser handler taking longer than ${Tu} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let n,r=this._activeBuffer.x,i=this._activeBuffer.y,a=0,o=this._parseStack.paused;if(o){if(n=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(n),n;r=this._parseStack.cursorStartX,i=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>Su&&(a=this._parseStack.position+Su)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e==`string`?` "${e}"`:` "${Array.prototype.map.call(e,e=>String.fromCharCode(e)).join(``)}"`}`),this._logService.logLevel===0&&this._logService.trace(`parsing data (codes)`,typeof e==`string`?e.split(``).map(e=>e.charCodeAt(0)):e),this._parseBuffer.length<e.length&&this._parseBuffer.length<Su&&(this._parseBuffer=new Uint32Array(Math.min(e.length,Su))),o||this._dirtyRowTracker.clearRange(),e.length>Su)for(let t=a;t<e.length;t+=Su){let a=t+Su<e.length?t+Su:e.length,o=typeof e==`string`?this._stringDecoder.decode(e.substring(t,a),this._parseBuffer):this._utf8Decoder.decode(e.subarray(t,a),this._parseBuffer);if(n=this._parser.parse(this._parseBuffer,o))return this._preserveStack(r,i,o,t),this._logSlowResolvingAsync(n),n}else if(!o){let t=typeof e==`string`?this._stringDecoder.decode(e,this._parseBuffer):this._utf8Decoder.decode(e,this._parseBuffer);if(n=this._parser.parse(this._parseBuffer,t))return this._preserveStack(r,i,t,0),this._logSlowResolvingAsync(n),n}(this._activeBuffer.x!==r||this._activeBuffer.y!==i)&&this._onCursorMove.fire();let s=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),c=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);c<this._bufferService.rows&&this._onRequestRefreshRows.fire({start:Math.min(c,this._bufferService.rows-1),end:Math.min(s,this._bufferService.rows-1)})}print(e,t,n){let r,i,a=this._charsetService.charset,o=this._optionsService.rawOptions.screenReaderMode,s=this._bufferService.cols,c=this._coreService.decPrivateModes.wraparound,l=this._coreService.modes.insertMode,u=this._curAttrData,d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&n-t>0&&d.getWidth(this._activeBuffer.x-1)===2&&d.setCellFromCodepoint(this._activeBuffer.x-1,0,1,u);let f=this._parser.precedingJoinState;for(let p=t;p<n;++p){if(r=e[p],r<127&&a){let e=a[String.fromCharCode(r)];e&&(r=e.charCodeAt(0))}let t=this._unicodeService.charProperties(r,f);i=$l.extractWidth(t);let n=$l.extractShouldJoin(t),m=n?$l.extractWidth(f):0;if(f=t,o&&this._onA11yChar.fire(Ar(r)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+i-m>s){if(c){let e=d,t=this._activeBuffer.x-m;for(this._activeBuffer.x=m,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),d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),m>0&&d instanceof yl&&d.copyCellsFrom(e,t,0,m,!1);t<s;)e.setCellFromCodepoint(t++,0,1,u)}else if(this._activeBuffer.x=s-1,i===2)continue}if(n&&this._activeBuffer.x){let e=d.getWidth(this._activeBuffer.x-1)?1:2;d.addCodepointToCell(this._activeBuffer.x-e,r,i);for(let e=i-m;--e>=0;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,u)}else if(l&&(d.insertCells(this._activeBuffer.x,i-m,this._activeBuffer.getNullCell(u)),d.getWidth(s-1)===2&&d.setCellFromCodepoint(s-1,0,1,u)),d.setCellFromCodepoint(this._activeBuffer.x++,r,i,u),i>0)for(;--i;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,u)}this._parser.precedingJoinState=f,this._activeBuffer.x<s&&n-t>0&&d.getWidth(this._activeBuffer.x)===0&&!d.hasContent(this._activeBuffer.x)&&d.setCellFromCodepoint(this._activeBuffer.x,0,1,u),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final===`t`&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,e=>!wu(e.params[0],this._optionsService.rawOptions.windowOptions)||t(e)):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new du(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new su(t))}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 e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);e.hasWidth(this._activeBuffer.x)&&!e.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,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(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return t===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return t===1&&(this._curAttrData.bg|=536870912),(t===2||t===0)&&(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,n,r=!1,i=!1){let a=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);a.replaceCells(t,n,this._activeBuffer.getNullCell(this._eraseAttrData()),i),r&&(a.isWrapped=!1)}_resetBufferLine(e,t=!1){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n&&(n.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),n.isWrapped=!1)}eraseInDisplay(e,t=!1){this._restrictCursor(this._bufferService.cols);let n;switch(e.params[0]){case 0:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);n<this._bufferService.rows;n++)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(n);break;case 1:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n,0,this._activeBuffer.x+1,!0,t),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(n+1).isWrapped=!1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(n=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,n-1);n--&&!this._activeBuffer.lines.get(this._activeBuffer.ybase+n)?.getTrimmedLength(););for(;n>=0;n--)this._bufferService.scroll(this._eraseAttrData())}else{for(n=this._bufferService.rows,this._dirtyRowTracker.markDirty(n-1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let e=this._activeBuffer.lines.length-this._bufferService.rows;e>0&&(this._activeBuffer.lines.trimStart(e),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-e,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-e,0),this._onScroll.fire(0))}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=this._activeBuffer.ybase+this._activeBuffer.y,r=this._bufferService.rows-1-this._activeBuffer.scrollBottom,i=this._bufferService.rows-1+this._activeBuffer.ybase-r+1;for(;t--;)this._activeBuffer.lines.splice(i-1,1),this._activeBuffer.lines.splice(n,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=this._activeBuffer.ybase+this._activeBuffer.y,r;for(r=this._bufferService.rows-1-this._activeBuffer.scrollBottom,r=this._bufferService.rows-1+this._activeBuffer.ybase-r;t--;)this._activeBuffer.lines.splice(n,1),this._activeBuffer.lines.splice(r,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.insertCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.deleteCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollDown(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,0,this._activeBuffer.getBlankLine(gl));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.deleteCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.insertCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.insertCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.deleteCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(e.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(e){let t=this._parser.precedingJoinState;if(!t)return!0;let n=e.params[0]||1,r=$l.extractWidth(t),i=this._activeBuffer.x-r,a=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(i),o=new Uint32Array(a.length*n),s=0;for(let e=0;e<a.length;){let t=a.codePointAt(e)||0;o[s++]=t,e+=t>65535?2:1}let c=s;for(let e=1;e<n;++e)o.copyWithin(c,0,s),c+=s;return this.print(o,0,c),!0}sendDeviceAttributesPrimary(e){return e.params[0]>0||(this._is(`xterm`)||this._is(`rxvt-unicode`)||this._is(`screen`)?this._coreService.triggerDataEvent(G.ESC+`[?1;2c`):this._is(`linux`)&&this._coreService.triggerDataEvent(G.ESC+`[?6c`)),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is(`xterm`)?this._coreService.triggerDataEvent(G.ESC+`[>0;276;0c`):this._is(`rxvt-unicode`)?this._coreService.triggerDataEvent(G.ESC+`[>85;95;0c`):this._is(`linux`)?this._coreService.triggerDataEvent(e.params[0]+`c`):this._is(`screen`)&&this._coreService.triggerDataEvent(G.ESC+`[>83;40003;0c`)),!0}_is(e){return(this._optionsService.rawOptions.termName+``).indexOf(e)===0}setMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0}return!0}setModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,Ol),this._charsetService.setgCharset(1,Ol),this._charsetService.setgCharset(2,Ol),this._charsetService.setgCharset(3,Ol);break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(132,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!0,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!0;break;case 12:this._optionsService.options.cursorBlink=!0;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!0;break;case 66:this._logService.debug(`Serial port requested application keypad.`),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire();break;case 9:this._coreMouseService.activeProtocol=`X10`;break;case 1e3:this._coreMouseService.activeProtocol=`VT200`;break;case 1002:this._coreMouseService.activeProtocol=`DRAG`;break;case 1003:this._coreMouseService.activeProtocol=`ANY`;break;case 1004:this._coreService.decPrivateModes.sendFocus=!0,this._onRequestSendFocus.fire();break;case 1005:this._logService.debug(`DECSET 1005 not supported (see #2507)`);break;case 1006:this._coreMouseService.activeEncoding=`SGR`;break;case 1015:this._logService.debug(`DECSET 1015 not supported (see #2507)`);break;case 1016:this._coreMouseService.activeEncoding=`SGR_PIXELS`;break;case 25:this._coreService.isCursorHidden=!1;break;case 1048:this.saveCursor();break;case 1049:this.saveCursor();case 47:case 1047:this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!0;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!0}return!0}resetMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1}return!0}resetModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!1;break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(80,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!1,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!1;break;case 12:this._optionsService.options.cursorBlink=!1;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!1;break;case 66:this._logService.debug(`Switching back to normal keypad.`),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire();break;case 9:case 1e3:case 1002:case 1003:this._coreMouseService.activeProtocol=`NONE`;break;case 1004:this._coreService.decPrivateModes.sendFocus=!1;break;case 1005:this._logService.debug(`DECRST 1005 not supported (see #2507)`);break;case 1006:this._coreMouseService.activeEncoding=`DEFAULT`;break;case 1015:this._logService.debug(`DECRST 1015 not supported (see #2507)`);break;case 1016:this._coreMouseService.activeEncoding=`DEFAULT`;break;case 25:this._coreService.isCursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),e.params[t]===1049&&this.restoreCursor(),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!1;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!1,this._onRequestRefreshRows.fire(void 0)}return!0}requestMode(e,t){let n;(e=>(e[e.NOT_RECOGNIZED=0]=`NOT_RECOGNIZED`,e[e.SET=1]=`SET`,e[e.RESET=2]=`RESET`,e[e.PERMANENTLY_SET=3]=`PERMANENTLY_SET`,e[e.PERMANENTLY_RESET=4]=`PERMANENTLY_RESET`))(n||={});let r=this._coreService.decPrivateModes,{activeProtocol:i,activeEncoding:a}=this._coreMouseService,o=this._coreService,{buffers:s,cols:c}=this._bufferService,{active:l,alt:u}=s,d=this._optionsService.rawOptions,f=(e,n)=>(o.triggerDataEvent(`${G.ESC}[${t?``:`?`}${e};${n}$y`),!0),p=e=>e?1:2,m=e.params[0];return t?m===2?f(m,4):m===4?f(m,p(o.modes.insertMode)):m===12?f(m,3):m===20?f(m,p(d.convertEol)):f(m,0):m===1?f(m,p(r.applicationCursorKeys)):m===3?f(m,d.windowOptions.setWinLines?c===80?2:+(c===132):0):m===6?f(m,p(r.origin)):m===7?f(m,p(r.wraparound)):m===8?f(m,3):m===9?f(m,p(i===`X10`)):m===12?f(m,p(d.cursorBlink)):m===25?f(m,p(!o.isCursorHidden)):m===45?f(m,p(r.reverseWraparound)):m===66?f(m,p(r.applicationKeypad)):m===67?f(m,4):m===1e3?f(m,p(i===`VT200`)):m===1002?f(m,p(i===`DRAG`)):m===1003?f(m,p(i===`ANY`)):m===1004?f(m,p(r.sendFocus)):m===1005?f(m,4):m===1006?f(m,p(a===`SGR`)):m===1015?f(m,4):m===1016?f(m,p(a===`SGR_PIXELS`)):m===1048?f(m,1):m===47||m===1047||m===1049?f(m,p(l===u)):m===2004?f(m,p(r.bracketedPasteMode)):m===2026?f(m,p(r.synchronizedOutput)):f(m,0)}_updateAttrColor(e,t,n,r,i){return t===2?(e|=50331648,e&=-16777216,e|=Ir.fromColorRGB([n,r,i])):t===5&&(e&=-50331904,e|=33554432|n&255),e}_extractColor(e,t,n){let r=[0,0,-1,0,0,0],i=0,a=0;do{if(r[a+i]=e.params[t+a],e.hasSubParams(t+a)){let n=e.getSubParams(t+a),o=0;do r[1]===5&&(i=1),r[a+o+1+i]=n[o];while(++o<n.length&&o+a+1+i<r.length);break}if(r[1]===5&&a+i>=2||r[1]===2&&a+i>=5)break;r[1]&&(i=1)}while(++a+t<e.length&&a+i<r.length);for(let e=2;e<r.length;++e)r[e]===-1&&(r[e]=0);switch(r[0]){case 38:n.fg=this._updateAttrColor(n.fg,r[1],r[3],r[4],r[5]);break;case 48:n.bg=this._updateAttrColor(n.bg,r[1],r[3],r[4],r[5]);break;case 58:n.extended=n.extended.clone(),n.extended.underlineColor=this._updateAttrColor(n.extended.underlineColor,r[1],r[3],r[4],r[5])}return a}_processUnderline(e,t){t.extended=t.extended.clone(),(!~e||e>5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=gl.fg,e.bg=gl.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t=e.length,n,r=this._curAttrData;for(let i=0;i<t;i++)n=e.params[i],n>=30&&n<=37?(r.fg&=-50331904,r.fg|=16777216|n-30):n>=40&&n<=47?(r.bg&=-50331904,r.bg|=16777216|n-40):n>=90&&n<=97?(r.fg&=-50331904,r.fg|=n-90|16777224):n>=100&&n<=107?(r.bg&=-50331904,r.bg|=n-100|16777224):n===0?this._processSGR0(r):n===1?r.fg|=134217728:n===3?r.bg|=67108864:n===4?(r.fg|=268435456,this._processUnderline(e.hasSubParams(i)?e.getSubParams(i)[0]:1,r)):n===5?r.fg|=536870912:n===7?r.fg|=67108864:n===8?r.fg|=1073741824:n===9?r.fg|=2147483648:n===2?r.bg|=134217728:n===21?this._processUnderline(2,r):n===22?(r.fg&=-134217729,r.bg&=-134217729):n===23?r.bg&=-67108865:n===24?(r.fg&=-268435457,this._processUnderline(0,r)):n===25?r.fg&=-536870913:n===27?r.fg&=-67108865:n===28?r.fg&=-1073741825:n===29?r.fg&=2147483647:n===39?(r.fg&=-67108864,r.fg|=gl.fg&16777215):n===49?(r.bg&=-67108864,r.bg|=gl.bg&16777215):n===38||n===48||n===58?i+=this._extractColor(e,i,r):n===53?r.bg|=1073741824:n===55?r.bg&=-1073741825:n===59?(r.extended=r.extended.clone(),r.extended.underlineColor=-1,r.updateExtended()):n===100?(r.fg&=-67108864,r.fg|=gl.fg&16777215,r.bg&=-67108864,r.bg|=gl.bg&16777215):this._logService.debug(`Unknown SGR attribute: %d.`,n);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${G.ESC}[0n`);break;case 6:let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${G.ESC}[${e};${t}R`)}return!0}deviceStatusPrivate(e){if(e.params[0]===6){let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${G.ESC}[?${e};${t}R`)}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=gl.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=e.length===0?1:e.params[0];if(t===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(t){case 1:case 2:this._coreService.decPrivateModes.cursorStyle=`block`;break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle=`underline`;break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle=`bar`}let e=t%2==1;this._coreService.decPrivateModes.cursorBlink=e}return!0}setScrollRegion(e){let t=e.params[0]||1,n;return(e.length<2||(n=e.params[1])>this._bufferService.rows||n===0)&&(n=this._bufferService.rows),n>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=n-1,this._setCursor(0,0)),!0}windowOptions(e){if(!wu(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:t!==2&&this._onRequestWindowsOptionsReport.fire(0);break;case 16:this._onRequestWindowsOptionsReport.fire(1);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${G.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>Cu&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>Cu&&this._iconNameStack.shift());break;case 23:(t===0||t===2)&&this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),(t===0||t===1)&&this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],n=e.split(`;`);for(;n.length>1;){let e=n.shift(),r=n.shift();if(/^\d+$/.exec(e)){let n=parseInt(e);if(ku(n)){if(r===`?`)t.push({type:0,index:n});else{let e=vu(r);e&&t.push({type:1,index:n,color:e})}}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(`;`);if(t===-1)return!0;let n=e.slice(0,t).trim(),r=e.slice(t+1);return r?this._createHyperlink(n,r):!n.trim()&&this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let n=e.split(`:`),r,i=n.findIndex(e=>e.startsWith(`id=`));return i!==-1&&(r=n[i].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:r,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let n=e.split(`;`);for(let e=0;e<n.length&&!(t>=this._specialColors.length);++e,++t)if(n[e]===`?`)this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let r=vu(n[e]);r&&this._onColor.fire([{type:1,index:this._specialColors[t],color:r}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],n=e.split(`;`);for(let e=0;e<n.length;++e)if(/^\d+$/.exec(n[e])){let r=parseInt(n[e]);ku(r)&&t.push({type:2,index:r})}return t.length&&this._onColor.fire(t),!0}restoreFgColor(e){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(e){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(e){return this._onColor.fire([{type:2,index:258}]),!0}nextLine(){return this._activeBuffer.x=0,this.index(),!0}keypadApplicationMode(){return this._logService.debug(`Serial port requested application keypad.`),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire(),!0}keypadNumericMode(){return this._logService.debug(`Switching back to normal keypad.`),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire(),!0}selectDefaultCharset(){return this._charsetService.setgLevel(0),this._charsetService.setgCharset(0,Ol),!0}selectCharset(e){return e.length===2?(e[0]===`/`||this._charsetService.setgCharset(xu[e[0]],Dl[e[1]]||Ol),!0):(this.selectDefaultCharset(),!0)}index(){return this._restrictCursor(),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._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=gl.clone(),this._eraseAttrDataInternal=gl.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=this._curAttrData.bg&67108863,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new Rr;e.content=4194373,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t<this._bufferService.rows;++t){let n=this._activeBuffer.ybase+this._activeBuffer.y+t,r=this._activeBuffer.lines.get(n);r&&(r.fill(e),r.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(e,t){let n=e=>(this._coreService.triggerDataEvent(`${G.ESC}${e}${G.ESC}\\`),!0),r=this._bufferService.buffer,i=this._optionsService.rawOptions;return n(e===`"q`?`P1$r${+!!this._curAttrData.isProtected()}"q`:e===`"p`?`P1$r61;1"p`:e===`r`?`P1$r${r.scrollTop+1};${r.scrollBottom+1}r`:e===`m`?`P1$r0m`:e===` q`?`P1$r${{block:2,underline:4,bar:6}[i.cursorStyle]-+!!i.cursorBlink} q`:`P0$r`)}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},Ou=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){e<this.start?this.start=e:e>this.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(Eu=e,e=t,t=Eu),e<this.start&&(this.start=e),t>this.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};Ou=R([z(0,Gr)],Ou);function ku(e){return 0<=e&&e<256}var Au=5e7,ju=12,Mu=50,Nu=class extends H{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new U),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(t!==void 0&&this._syncCalls>t){this._syncCalls=0;return}if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;this._isSyncWriting=!0;let n;for(;n=this._writeBuffer.shift();){this._action(n);let e=this._callbacks.shift();e&&e()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>Au)throw Error(`write data discarded, use flow control to avoid losing data`);if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput){this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),this._innerWrite();return}setTimeout(()=>this._innerWrite())}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){let n=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let e=this._writeBuffer[this._bufferOffset],r=this._action(e,t);if(r){r.catch(e=>(queueMicrotask(()=>{throw e}),Promise.resolve(!1))).then(e=>performance.now()-n>=ju?setTimeout(()=>this._innerWrite(0,e)):this._innerWrite(n,e));return}let i=this._callbacks[this._bufferOffset];if(i&&i(),this._bufferOffset++,this._pendingData-=e.length,performance.now()-n>=ju)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>Mu&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}},Pu=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){let t=this._bufferService.buffer;if(e.id===void 0){let n=t.addMarker(t.ybase+t.y),r={data:e,id:this._nextId++,lines:[n]};return n.onDispose(()=>this._removeMarkerFromLink(r,n)),this._dataByLinkId.set(r.id,r),r.id}let n=e,r=this._getEntryIdKey(n),i=this._entriesWithId.get(r);if(i)return this.addLineToLink(i.id,t.ybase+t.y),i.id;let a=t.addMarker(t.ybase+t.y),o={id:this._nextId++,key:this._getEntryIdKey(n),data:n,lines:[a]};return a.onDispose(()=>this._removeMarkerFromLink(o,a)),this._entriesWithId.set(o.key,o),this._dataByLinkId.set(o.id,o),o.id}addLineToLink(e,t){let n=this._dataByLinkId.get(e);if(n&&n.lines.every(e=>e.line!==t)){let e=this._bufferService.buffer.addMarker(t);n.lines.push(e),e.onDispose(()=>this._removeMarkerFromLink(n,e))}}getLinkData(e){return this._dataByLinkId.get(e)?.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let n=e.lines.indexOf(t);n!==-1&&(e.lines.splice(n,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};Pu=R([z(0,Gr)],Pu);var Fu=!1,Iu=class extends H{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new Ni),this._onBinary=this._register(new U),this.onBinary=this._onBinary.event,this._onData=this._register(new U),this.onData=this._onData.event,this._onLineFeed=this._register(new U),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new U),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new U),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new U),this._instantiationService=new ul,this.optionsService=this._register(new Ll(e)),this._instantiationService.setService(Zr,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(Pl)),this._instantiationService.setService(Gr,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(pl)),this._instantiationService.setService(Xr,this._logService),this.coreService=this._register(this._instantiationService.createInstance(Hl)),this._instantiationService.setService(qr,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(ql)),this._instantiationService.setService(Kr,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance($l)),this._instantiationService.setService($r,this.unicodeService),this._charsetService=this._instantiationService.createInstance(eu),this._instantiationService.setService(Jr,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(Pu),this._instantiationService.setService(Qr,this._oscLinkService),this._inputHandler=this._register(new Du(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(Bi.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(Bi.forward(this._bufferService.onResize,this._onResize)),this._register(Bi.forward(this.coreService.onData,this._onData)),this._register(Bi.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom(!0))),this._register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this._register(this.optionsService.onMultipleOptionChange([`windowsMode`,`windowsPty`],()=>this._handleWindowsPtyOptionChange())),this._register(this._bufferService.onScroll(()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this._register(new Nu((e,t)=>this._inputHandler.parse(e,t))),this._register(Bi.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new U),this._onScroll.event(e=>{this._onScrollApi?.fire(e.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(e){for(let t in e)this.optionsService.options[t]=e[t]}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=3&&!Fu&&(this._logService.warn(`writeSync is unreliable and will be removed soon.`),Fu=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,Ml),t=Math.max(t,Nl),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t){this._bufferService.scrollLines(e,t)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,t=this.optionsService.rawOptions.windowsPty;t&&t.buildNumber!==void 0&&t.buildNumber!==void 0?e=t.backend===`conpty`&&t.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(tu.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:`H`},()=>(tu(this._bufferService),!1))),this._windowsWrappingHeuristics.value=V(()=>{for(let t of e)t.dispose()})}}},Lu={48:[`0`,`)`],49:[`1`,`!`],50:[`2`,`@`],51:[`3`,`#`],52:[`4`,`$`],53:[`5`,`%`],54:[`6`,`^`],55:[`7`,`&`],56:[`8`,`*`],57:[`9`,`(`],186:[`;`,`:`],187:[`=`,`+`],188:[`,`,`<`],189:[`-`,`_`],190:[`.`,`>`],191:[`/`,`?`],192:["`",`~`],219:[`[`,`{`],220:[`\\`,`|`],221:[`]`,`}`],222:[`'`,`"`]};function Ru(e,t,n,r){let i={type:0,cancel:!1,key:void 0},a=+!!e.shiftKey|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:e.key===`UIKeyInputUpArrow`?i.key=t?G.ESC+`OA`:G.ESC+`[A`:e.key===`UIKeyInputLeftArrow`?i.key=t?G.ESC+`OD`:G.ESC+`[D`:e.key===`UIKeyInputRightArrow`?i.key=t?G.ESC+`OC`:G.ESC+`[C`:e.key===`UIKeyInputDownArrow`&&(i.key=t?G.ESC+`OB`:G.ESC+`[B`);break;case 8:i.key=e.ctrlKey?`\b`:G.DEL,e.altKey&&(i.key=G.ESC+i.key);break;case 9:if(e.shiftKey){i.key=G.ESC+`[Z`;break}i.key=G.HT,i.cancel=!0;break;case 13:i.key=e.altKey?G.ESC+G.CR:G.CR,i.cancel=!0;break;case 27:i.key=G.ESC,e.altKey&&(i.key=G.ESC+G.ESC),i.cancel=!0;break;case 37:if(e.metaKey)break;i.key=a?G.ESC+`[1;`+(a+1)+`D`:t?G.ESC+`OD`:G.ESC+`[D`;break;case 39:if(e.metaKey)break;i.key=a?G.ESC+`[1;`+(a+1)+`C`:t?G.ESC+`OC`:G.ESC+`[C`;break;case 38:if(e.metaKey)break;i.key=a?G.ESC+`[1;`+(a+1)+`A`:t?G.ESC+`OA`:G.ESC+`[A`;break;case 40:if(e.metaKey)break;i.key=a?G.ESC+`[1;`+(a+1)+`B`:t?G.ESC+`OB`:G.ESC+`[B`;break;case 45:!e.shiftKey&&!e.ctrlKey&&(i.key=G.ESC+`[2~`);break;case 46:i.key=a?G.ESC+`[3;`+(a+1)+`~`:G.ESC+`[3~`;break;case 36:i.key=a?G.ESC+`[1;`+(a+1)+`H`:t?G.ESC+`OH`:G.ESC+`[H`;break;case 35:i.key=a?G.ESC+`[1;`+(a+1)+`F`:t?G.ESC+`OF`:G.ESC+`[F`;break;case 33:e.shiftKey?i.type=2:i.key=e.ctrlKey?G.ESC+`[5;`+(a+1)+`~`:G.ESC+`[5~`;break;case 34:e.shiftKey?i.type=3:i.key=e.ctrlKey?G.ESC+`[6;`+(a+1)+`~`:G.ESC+`[6~`;break;case 112:i.key=a?G.ESC+`[1;`+(a+1)+`P`:G.ESC+`OP`;break;case 113:i.key=a?G.ESC+`[1;`+(a+1)+`Q`:G.ESC+`OQ`;break;case 114:i.key=a?G.ESC+`[1;`+(a+1)+`R`:G.ESC+`OR`;break;case 115:i.key=a?G.ESC+`[1;`+(a+1)+`S`:G.ESC+`OS`;break;case 116:i.key=a?G.ESC+`[15;`+(a+1)+`~`:G.ESC+`[15~`;break;case 117:i.key=a?G.ESC+`[17;`+(a+1)+`~`:G.ESC+`[17~`;break;case 118:i.key=a?G.ESC+`[18;`+(a+1)+`~`:G.ESC+`[18~`;break;case 119:i.key=a?G.ESC+`[19;`+(a+1)+`~`:G.ESC+`[19~`;break;case 120:i.key=a?G.ESC+`[20;`+(a+1)+`~`:G.ESC+`[20~`;break;case 121:i.key=a?G.ESC+`[21;`+(a+1)+`~`:G.ESC+`[21~`;break;case 122:i.key=a?G.ESC+`[23;`+(a+1)+`~`:G.ESC+`[23~`;break;case 123:i.key=a?G.ESC+`[24;`+(a+1)+`~`:G.ESC+`[24~`;break;default:if(e.ctrlKey&&!e.shiftKey&&!e.altKey&&!e.metaKey)e.keyCode>=65&&e.keyCode<=90?i.key=String.fromCharCode(e.keyCode-64):e.keyCode===32?i.key=G.NUL:e.keyCode>=51&&e.keyCode<=55?i.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?i.key=G.DEL:e.keyCode===219?i.key=G.ESC:e.keyCode===220?i.key=G.FS:e.keyCode===221&&(i.key=G.GS);else if((!n||r)&&e.altKey&&!e.metaKey){let t=Lu[e.keyCode]?.[+!!e.shiftKey];if(t)i.key=G.ESC+t;else if(e.keyCode>=65&&e.keyCode<=90){let t=e.ctrlKey?e.keyCode-64:e.keyCode+32,n=String.fromCharCode(t);e.shiftKey&&(n=n.toUpperCase()),i.key=G.ESC+n}else if(e.keyCode===32)i.key=G.ESC+(e.ctrlKey?G.NUL:` `);else if(e.key===`Dead`&&e.code.startsWith(`Key`)){let t=e.code.slice(3,4);e.shiftKey||(t=t.toLowerCase()),i.key=G.ESC+t,i.cancel=!0}}else n&&!e.altKey&&!e.ctrlKey&&!e.shiftKey&&e.metaKey?e.keyCode===65&&(i.type=1):e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&e.key.length===1?i.key=e.key:e.key&&e.ctrlKey&&(e.key===`_`&&(i.key=G.US),e.key===`@`&&(i.key=G.NUL))}return i}var zu=0,Bu=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new Oc,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new Oc,this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(e){this._flushCleanupDeleted(),this._insertedValues.length===0&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(e)}_flushInserted(){let e=this._insertedValues.sort((e,t)=>this._getKey(e)-this._getKey(t)),t=0,n=0,r=Array(this._array.length+this._insertedValues.length);for(let i=0;i<r.length;i++)n>=this._array.length||this._getKey(e[t])<=this._getKey(this._array[n])?(r[i]=e[t],t++):r[i]=this._array[n++];this._array=r,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(e){if(this._flushCleanupInserted(),this._array.length===0)return!1;let t=this._getKey(e);if(t===void 0||(zu=this._search(t),zu===-1)||this._getKey(this._array[zu])!==t)return!1;do if(this._array[zu]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(zu),!0;while(++zu<this._array.length&&this._getKey(this._array[zu])===t);return!1}_flushDeleted(){this._isFlushingDeleted=!0;let e=this._deletedIndices.sort((e,t)=>e-t),t=0,n=Array(this._array.length-e.length),r=0;for(let i=0;i<this._array.length;i++)e[t]===i?t++:n[r++]=this._array[i];this._array=n,this._deletedIndices.length=0,this._isFlushingDeleted=!1}_flushCleanupDeleted(){!this._isFlushingDeleted&&this._deletedIndices.length>0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(zu=this._search(e),!(zu<0||zu>=this._array.length)&&this._getKey(this._array[zu])===e))do yield this._array[zu];while(++zu<this._array.length&&this._getKey(this._array[zu])===e)}forEachByKey(e,t){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(zu=this._search(e),!(zu<0||zu>=this._array.length)&&this._getKey(this._array[zu])===e))do t(this._array[zu]);while(++zu<this._array.length&&this._getKey(this._array[zu])===e)}values(){return this._flushCleanupInserted(),this._flushCleanupDeleted(),[...this._array].values()}_search(e){let t=0,n=this._array.length-1;for(;n>=t;){let r=t+n>>1,i=this._getKey(this._array[r]);if(i>e)n=r-1;else if(i<e)t=r+1;else{for(;r>0&&this._getKey(this._array[r-1])===e;)r--;return r}}return t}},Vu=0,Hu=0,Uu=class extends H{constructor(){super(),this._decorations=new Bu(e=>e?.marker.line),this._onDecorationRegistered=this._register(new U),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new U),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(V(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new Wu(e);if(t){let e=t.marker.onDispose(()=>t.dispose()),n=t.onDispose(()=>{n.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),e.dispose())});this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,n){let r=0,i=0;for(let a of this._decorations.getKeyIterator(t))r=a.options.x??0,i=r+(a.options.width??1),e>=r&&e<i&&(!n||(a.options.layer??`bottom`)===n)&&(yield a)}forEachDecorationAtCell(e,t,n,r){this._decorations.forEachByKey(t,t=>{Vu=t.options.x??0,Hu=Vu+(t.options.width??1),e>=Vu&&e<Hu&&(!n||(t.options.layer??`bottom`)===n)&&r(t)})}},Wu=class extends Mi{constructor(e){super(),this.options=e,this.onRenderEmitter=this.add(new U),this.onRender=this.onRenderEmitter.event,this._onDispose=this.add(new U),this.onDispose=this._onDispose.event,this._cachedBg=null,this._cachedFg=null,this.marker=e.marker,this.options.overviewRulerOptions&&!this.options.overviewRulerOptions.position&&(this.options.overviewRulerOptions.position=`full`)}get backgroundColorRGB(){return this._cachedBg===null&&(this._cachedBg=this.options.backgroundColor?ks.toColor(this.options.backgroundColor):void 0),this._cachedBg}get foregroundColorRGB(){return this._cachedFg===null&&(this._cachedFg=this.options.foregroundColor?ks.toColor(this.options.foregroundColor):void 0),this._cachedFg}dispose(){this._onDispose.fire(),super.dispose()}},Gu=1e3,Ku=class{constructor(e,t=Gu){this._renderCallback=e,this._debounceThresholdMS=t,this._lastRefreshMs=0,this._additionalRefreshRequested=!1}dispose(){this._refreshTimeoutID&&clearTimeout(this._refreshTimeoutID)}refresh(e,t,n){this._rowCount=n,e=e===void 0?0:e,t=t===void 0?this._rowCount-1:t,this._rowStart=this._rowStart===void 0?e:Math.min(this._rowStart,e),this._rowEnd=this._rowEnd===void 0?t:Math.max(this._rowEnd,t);let r=performance.now();if(r-this._lastRefreshMs>=this._debounceThresholdMS)this._lastRefreshMs=r,this._innerRefresh();else if(!this._additionalRefreshRequested){let e=r-this._lastRefreshMs,t=this._debounceThresholdMS-e;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},t)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t)}},qu=20,Ju=class extends H{constructor(e,t,n,r){super(),this._terminal=e,this._coreBrowserService=n,this._renderService=r,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce=``;let i=this._coreBrowserService.mainDocument;this._accessibilityContainer=i.createElement(`div`),this._accessibilityContainer.classList.add(`xterm-accessibility`),this._rowContainer=i.createElement(`div`),this._rowContainer.setAttribute(`role`,`list`),this._rowContainer.classList.add(`xterm-accessibility-tree`),this._rowElements=[];for(let e=0;e<this._terminal.rows;e++)this._rowElements[e]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[e]);if(this._topBoundaryFocusListener=e=>this._handleBoundaryFocus(e,0),this._bottomBoundaryFocusListener=e=>this._handleBoundaryFocus(e,1),this._rowElements[0].addEventListener(`focus`,this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=i.createElement(`div`),this._liveRegion.classList.add(`live-region`),this._liveRegion.setAttribute(`aria-live`,`assertive`),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new Ku(this._renderRows.bind(this))),!this._terminal.element)throw Error(`Cannot enable accessibility before Terminal.open`);this._terminal.element.insertAdjacentElement(`afterbegin`,this._accessibilityContainer),this._register(this._terminal.onResize(e=>this._handleResize(e.rows))),this._register(this._terminal.onRender(e=>this._refreshRows(e.start,e.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(e=>this._handleChar(e))),this._register(this._terminal.onLineFeed(()=>this._handleChar(`
19
- `))),this._register(this._terminal.onA11yTab(e=>this._handleTab(e))),this._register(this._terminal.onKey(e=>this._handleKey(e.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(W(i,`selectionchange`,()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(V(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t<e;t++)this._handleChar(` `)}_handleChar(e){this._liveRegionLineCount<qu+1&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===`
20
- `&&(this._liveRegionLineCount++,this._liveRegionLineCount===qu+1&&(this._liveRegion.textContent+=Cr.get())))}_clearLiveRegion(){this._liveRegion.textContent=``,this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),/\p{Control}/u.test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let n=this._terminal.buffer,r=n.lines.length.toString();for(let i=e;i<=t;i++){let e=n.lines.get(n.ydisp+i),t=[],a=e?.translateToString(!0,void 0,void 0,t)||``,o=(n.ydisp+i+1).toString(),s=this._rowElements[i];s&&(a.length===0?(s.textContent=`\xA0`,this._rowColumns.set(s,[0,1])):(s.textContent=a,this._rowColumns.set(s,t)),s.setAttribute(`aria-posinset`,o),s.setAttribute(`aria-setsize`,r),this._alignRowWidth(s))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce=``)}_handleBoundaryFocus(e,t){let n=e.target,r=this._rowElements[t===0?1:this._rowElements.length-2];if(n.getAttribute(`aria-posinset`)===(t===0?`1`:`${this._terminal.buffer.lines.length}`)||e.relatedTarget!==r)return;let i,a;if(t===0?(i=n,a=this._rowElements.pop(),this._rowContainer.removeChild(a)):(i=this._rowElements.shift(),a=n,this._rowContainer.removeChild(i)),i.removeEventListener(`focus`,this._topBoundaryFocusListener),a.removeEventListener(`focus`,this._bottomBoundaryFocusListener),t===0){let e=this._createAccessibilityTreeNode();this._rowElements.unshift(e),this._rowContainer.insertAdjacentElement(`afterbegin`,e)}else{let e=this._createAccessibilityTreeNode();this._rowElements.push(e),this._rowContainer.appendChild(e)}this._rowElements[0].addEventListener(`focus`,this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error(`anchorNode and/or focusNode are null`);return}let t={node:e.anchorNode,offset:e.anchorOffset},n={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(n.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===n.node&&t.offset>n.offset)&&([t,n]=[n,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let r=this._rowElements.slice(-1)[0];if(n.node.compareDocumentPosition(r)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(n={node:r,offset:r.textContent?.length??0}),!this._rowContainer.contains(n.node))return;let i=({node:e,offset:t})=>{let n=e instanceof Text?e.parentNode:e,r=parseInt(n?.getAttribute(`aria-posinset`),10)-1;if(isNaN(r))return console.warn(`row is invalid. Race condition?`),null;let i=this._rowColumns.get(n);if(!i)return console.warn(`columns is null. Race condition?`),null;let a=t<i.length?i[t]:i.slice(-1)[0]+1;return a>=this._terminal.cols&&(++r,a=0),{row:r,column:a}},a=i(t),o=i(n);if(a&&o){if(a.row>o.row||a.row===o.row&&a.column>=o.column)throw Error(`invalid range`);this._terminal.select(a.column,a.row,(o.row-a.row)*this._terminal.cols-a.column+o.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener(`focus`,this._bottomBoundaryFocusListener);for(let e=this._rowContainer.children.length;e<this._terminal.rows;e++)this._rowElements[e]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[e]);for(;this._rowElements.length>e;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement(`div`);return e.setAttribute(`role`,`listitem`),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e<this._terminal.rows;e++)this._refreshRowDimensions(this._rowElements[e]),this._alignRowWidth(this._rowElements[e])}}_refreshRowDimensions(e){e.style.height=`${this._renderService.dimensions.css.cell.height}px`}_alignRowWidth(e){e.style.transform=``;let t=e.getBoundingClientRect().width,n=this._rowColumns.get(e)?.slice(-1)?.[0];if(!n)return;let r=n*this._renderService.dimensions.css.cell.width;e.style.transform=`scaleX(${r/t})`}};Ju=R([z(1,Yr),z(2,ii),z(3,oi)],Ju);var Yu=class extends H{constructor(e,t,n,r,i){super(),this._element=e,this._mouseService=t,this._renderService=n,this._bufferService=r,this._linkProviderService=i,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this._register(new U),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this._register(new U),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this._register(V(()=>{ki(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,this._activeProviderReplies?.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(W(this._element,`mouseleave`,()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(W(this._element,`mousemove`,this._handleMouseMove.bind(this))),this._register(W(this._element,`mousedown`,this._handleMouseDown.bind(this))),this._register(W(this._element,`mouseup`,this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(e){this._lastMouseEvent=e;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;let n=e.composedPath();for(let e=0;e<n.length;e++){let t=n[e];if(t.classList.contains(`xterm`))break;if(t.classList.contains(`xterm-hover`))return}(!this._lastBufferCell||t.x!==this._lastBufferCell.x||t.y!==this._lastBufferCell.y)&&(this._handleHover(t),this._lastBufferCell=t)}_handleHover(e){this._activeLine!==e.y||this._wasResized?(this._clearCurrentLink(),this._askForLink(e,!1),this._wasResized=!1):this._currentLink&&this._linkAtPosition(this._currentLink.link,e)||(this._clearCurrentLink(),this._askForLink(e,!0))}_askForLink(e,t){(!this._activeProviderReplies||!t)&&(this._activeProviderReplies?.forEach(e=>{e?.forEach(e=>{e.link.dispose&&e.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let n=!1;for(let[r,i]of this._linkProviderService.linkProviders.entries())t?this._activeProviderReplies?.get(r)&&(n=this._checkLinkProviderResult(r,e,n)):i.provideLinks(e.y,t=>{if(this._isMouseOut)return;let i=t?.map(e=>({link:e}));this._activeProviderReplies?.set(r,i),n=this._checkLinkProviderResult(r,e,n),this._activeProviderReplies?.size===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let n=new Set;for(let r=0;r<t.size;r++){let i=t.get(r);if(i)for(let t=0;t<i.length;t++){let r=i[t],a=r.link.range.start.y<e?0:r.link.range.start.x,o=r.link.range.end.y>e?this._bufferService.cols:r.link.range.end.x;for(let e=a;e<=o;e++){if(n.has(e)){i.splice(t--,1);break}n.add(e)}}}}_checkLinkProviderResult(e,t,n){if(!this._activeProviderReplies)return n;let r=this._activeProviderReplies.get(e),i=!1;for(let t=0;t<e;t++)(!this._activeProviderReplies.has(t)||this._activeProviderReplies.get(t))&&(i=!0);if(!i&&r){let e=r.find(e=>this._linkAtPosition(e.link,t));e&&(n=!0,this._handleNewLink(e))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!n)for(let e=0;e<this._activeProviderReplies.size;e++){let r=this._activeProviderReplies.get(e)?.find(e=>this._linkAtPosition(e.link,t));if(r){n=!0,this._handleNewLink(r);break}}return n}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink&&Xu(this._mouseDownLink.link,this._currentLink.link)&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){!this._currentLink||!this._lastMouseEvent||(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,ki(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:e.link.decorations===void 0||e.link.decorations.underline,pointerCursor:e.link.decorations===void 0||e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>this._currentLink?.state?.decorations.pointerCursor,set:e=>{this._currentLink?.state&&this._currentLink.state.decorations.pointerCursor!==e&&(this._currentLink.state.decorations.pointerCursor=e,this._currentLink.state.isHovered&&this._element.classList.toggle(`xterm-cursor-pointer`,e))}},underline:{get:()=>this._currentLink?.state?.decorations.underline,set:t=>{this._currentLink?.state&&this._currentLink?.state?.decorations.underline!==t&&(this._currentLink.state.decorations.underline=t,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,t))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(e=>{if(!this._currentLink)return;let t=e.start===0?0:e.start+1+this._bufferService.buffer.ydisp,n=this._bufferService.buffer.ydisp+1+e.end;if(this._currentLink.link.range.start.y>=t&&this._currentLink.link.range.end.y<=n&&(this._clearCurrentLink(t,n),this._lastMouseEvent)){let e=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);e&&this._askForLink(e,!1)}})))}_linkHover(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add(`xterm-cursor-pointer`)),t.hover&&t.hover(n,t.text)}_fireUnderlineEvent(e,t){let n=e.range,r=this._bufferService.buffer.ydisp,i=this._createLinkUnderlineEvent(n.start.x-1,n.start.y-r-1,n.end.x,n.end.y-r-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(i)}_linkLeave(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove(`xterm-cursor-pointer`)),t.leave&&t.leave(n,t.text)}_linkAtPosition(e,t){let n=e.range.start.y*this._bufferService.cols+e.range.start.x,r=e.range.end.y*this._bufferService.cols+e.range.end.x,i=t.y*this._bufferService.cols+t.x;return n<=i&&i<=r}_positionFromMouseEvent(e,t,n){let r=n.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(r)return{x:r[0],y:r[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,n,r,i){return{x1:e,y1:t,x2:n,y2:r,cols:this._bufferService.cols,fg:i}}};Yu=R([z(1,ai),z(2,oi),z(3,Gr),z(4,ui)],Yu);function Xu(e,t){return e.text===t.text&&e.range.start.x===t.range.start.x&&e.range.start.y===t.range.start.y&&e.range.end.x===t.range.end.x&&e.range.end.y===t.range.end.y}var Zu=class extends Iu{constructor(e={}){super(e),this._linkifier=this._register(new Ni),this.browser=dc,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new Ni),this._onCursorMove=this._register(new U),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new U),this.onKey=this._onKey.event,this._onRender=this._register(new U),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new U),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new U),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new U),this.onBell=this._onBell.event,this._onFocus=this._register(new U),this._onBlur=this._register(new U),this._onA11yCharEmitter=this._register(new U),this._onA11yTabEmitter=this._register(new U),this._onWillOpen=this._register(new U),this._setup(),this._decorationService=this._instantiationService.createInstance(Uu),this._instantiationService.setService(ei,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(oc),this._instantiationService.setService(ui,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(ti)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(e=>this.refresh(e?.start??0,e?.end??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(e=>this._reportWindowsOptions(e))),this._register(this._inputHandler.onColor(e=>this._handleColorEvent(e))),this._register(Bi.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(Bi.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(Bi.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(Bi.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(e=>this._afterResize(e.cols,e.rows))),this._register(V(()=>{this._customKeyEventHandler=void 0,this.element?.parentNode?.removeChild(this.element)}))}get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}_handleColorEvent(e){if(this._themeService)for(let t of e){let e,n=``;switch(t.index){case 256:e=`foreground`,n=`10`;break;case 257:e=`background`,n=`11`;break;case 258:e=`cursor`,n=`12`;break;default:e=`ansi`,n=`4;`+t.index}switch(t.type){case 0:let r=Os.toColorRGB(e===`ansi`?this._themeService.colors.ansi[t.index]:this._themeService.colors[e]);this.coreService.triggerDataEvent(`${G.ESC}]${n};${bu(r)}${bs.ST}`);break;case 1:if(e===`ansi`)this._themeService.modifyColors(e=>e.ansi[t.index]=Ds.toColor(...t.color));else{let n=e;this._themeService.modifyColors(e=>e[n]=Ds.toColor(...t.color))}break;case 2:this._themeService.restoreColor(t.index)}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(Ju,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(G.ESC+`[I`),this.element.classList.add(`focus`),this._showCursor(),this._onFocus.fire()}blur(){return this.textarea?.blur()}_handleTextAreaBlur(){this.textarea.value=``,this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(G.ESC+`[O`),this.element.classList.remove(`focus`),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;let n=Math.min(this.buffer.x,this.cols-1),r=this._renderService.dimensions.css.cell.height,i=t.getWidth(n),a=this._renderService.dimensions.css.cell.width*i,o=this.buffer.y*this._renderService.dimensions.css.cell.height,s=n*this._renderService.dimensions.css.cell.width;this.textarea.style.left=s+`px`,this.textarea.style.top=o+`px`,this.textarea.style.width=a+`px`,this.textarea.style.height=r+`px`,this.textarea.style.lineHeight=r+`px`,this.textarea.style.zIndex=`-5`}_initGlobal(){this._bindKeys(),this._register(W(this.element,`copy`,e=>{this.hasSelection()&&B(e,this._selectionService)}));let e=e=>Er(e,this.textarea,this.coreService,this.optionsService);this._register(W(this.textarea,`paste`,e)),this._register(W(this.element,`paste`,e)),hc?this._register(W(this.element,`mousedown`,e=>{e.button===2&&kr(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(W(this.element,`contextmenu`,e=>{kr(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),Cc&&this._register(W(this.element,`auxclick`,e=>{e.button===1&&Or(e,this.textarea,this.screenElement)}))}_bindKeys(){this._register(W(this.textarea,`keyup`,e=>this._keyUp(e),!0)),this._register(W(this.textarea,`keydown`,e=>this._keyDown(e),!0)),this._register(W(this.textarea,`keypress`,e=>this._keyPress(e),!0)),this._register(W(this.textarea,`compositionstart`,()=>this._compositionHelper.compositionstart())),this._register(W(this.textarea,`compositionupdate`,e=>this._compositionHelper.compositionupdate(e))),this._register(W(this.textarea,`compositionend`,()=>this._compositionHelper.compositionend())),this._register(W(this.textarea,`input`,e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){if(!e)throw Error(`Terminal requires a parent element.`);if(e.isConnected||this._logService.debug(`Terminal.open was called on an element that was not attached to the DOM`),this.element?.ownerDocument.defaultView&&this._coreBrowserService){this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView);return}this._document=e.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement(`div`),this.element.dir=`ltr`,this.element.classList.add(`terminal`),this.element.classList.add(`xterm`),e.appendChild(this.element);let t=this._document.createDocumentFragment();this._viewportElement=this._document.createElement(`div`),this._viewportElement.classList.add(`xterm-viewport`),t.appendChild(this._viewportElement),this.screenElement=this._document.createElement(`div`),this.screenElement.classList.add(`xterm-screen`),this._register(W(this.screenElement,`mousemove`,e=>this.updateCursorStyle(e))),this._helperContainer=this._document.createElement(`div`),this._helperContainer.classList.add(`xterm-helpers`),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);let n=this.textarea=this._document.createElement(`textarea`);this.textarea.classList.add(`xterm-helper-textarea`),this.textarea.setAttribute(`aria-label`,xr.get()),wc||this.textarea.setAttribute(`aria-multiline`,`false`),this.textarea.setAttribute(`autocorrect`,`off`),this.textarea.setAttribute(`autocapitalize`,`off`),this.textarea.setAttribute(`spellcheck`,`false`),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange(`disableStdin`,()=>n.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(ic,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<`u`?window.document:null)),this._instantiationService.setService(ii,this._coreBrowserService),this._register(W(this.textarea,`focus`,e=>this._handleTextAreaFocus(e))),this._register(W(this.textarea,`blur`,()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(ec,this._document,this._helperContainer),this._instantiationService.setService(ri,this._charSizeService),this._themeService=this._instantiationService.createInstance(cl),this._instantiationService.setService(li,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(Fs),this._instantiationService.setService(ci,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(Ac,this.rows,this.screenElement)),this._instantiationService.setService(oi,this._renderService),this._register(this._renderService.onRenderedViewportChange(e=>this._onRender.fire(e))),this.onResize(e=>this._renderService.resize(e.cols,e.rows)),this._compositionView=this._document.createElement(`div`),this._compositionView.classList.add(`composition-view`),this._compositionHelper=this._instantiationService.createInstance(xs,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(lc),this._instantiationService.setService(ai,this._mouseService);let r=this._linkifier.value=this._register(this._instantiationService.createInstance(Yu,this.screenElement));this.element.appendChild(t);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this._register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this._register(this.onBlur(()=>this._renderService.handleBlur())),this._register(this.onFocus(()=>this._renderService.handleFocus())),this._viewport=this._register(this._instantiationService.createInstance(fs,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(e=>{super.scrollLines(e,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(Qc,this.element,this.screenElement,r)),this._instantiationService.setService(si,this._selectionService),this._register(this._selectionService.onRequestScrollLines(e=>this.scrollLines(e.amount,e.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(e=>this._renderService.handleSelectionChanged(e.start,e.end,e.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(e=>{this.textarea.value=e,this.textarea.focus(),this.textarea.select()})),this._register(Bi.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{this._selectionService.refresh(),this._viewport?.queueSync()})),this._register(this._instantiationService.createInstance(ps,this.screenElement)),this._register(W(this.element,`mousedown`,e=>this._selectionService.handleMouseDown(e))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add(`enable-mouse-events`)):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(Ju,this)),this._register(this.optionsService.onSpecificOptionChange(`screenReaderMode`,e=>this._handleScreenReaderModeOptionChange(e))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(vs,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange(`overviewRuler`,e=>{!this._overviewRulerRenderer&&e&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(vs,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance($s,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function n(t){let n=e._mouseService.getMouseReportCoords(t,e.screenElement);if(!n)return!1;let r,i;switch(t.overrideType||t.type){case`mousemove`:i=32,t.buttons===void 0?(r=3,t.button!==void 0&&(r=t.button<3?t.button:3)):r=t.buttons&1?0:t.buttons&4?1:t.buttons&2?2:3;break;case`mouseup`:i=0,r=t.button<3?t.button:3;break;case`mousedown`:i=1,r=t.button<3?t.button:3;break;case`wheel`:if(e._customWheelEventHandler&&e._customWheelEventHandler(t)===!1)return!1;let n=t.deltaY;if(n===0||e.coreMouseService.consumeWheelEvent(t,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return!1;i=n<0?0:1,r=4;break;default:return!1}return i===void 0||r===void 0||r>4?!1:e.coreMouseService.triggerMouseEvent({col:n.col,row:n.row,x:n.x,y:n.y,button:r,action:i,ctrl:t.ctrlKey,alt:t.altKey,shift:t.shiftKey})}let r={mouseup:null,wheel:null,mousedrag:null,mousemove:null},i={mouseup:e=>(n(e),e.buttons||(this._document.removeEventListener(`mouseup`,r.mouseup),r.mousedrag&&this._document.removeEventListener(`mousemove`,r.mousedrag)),this.cancel(e)),wheel:e=>(n(e),this.cancel(e,!0)),mousedrag:e=>{e.buttons&&n(e)},mousemove:e=>{e.buttons||n(e)}};this._register(this.coreMouseService.onProtocolChange(e=>{e?(this.optionsService.rawOptions.logLevel===`debug`&&this._logService.debug(`Binding to mouse events:`,this.coreMouseService.explainEvents(e)),this.element.classList.add(`enable-mouse-events`),this._selectionService.disable()):(this._logService.debug(`Unbinding from mouse events.`),this.element.classList.remove(`enable-mouse-events`),this._selectionService.enable()),e&8?r.mousemove||=(t.addEventListener(`mousemove`,i.mousemove),i.mousemove):(t.removeEventListener(`mousemove`,r.mousemove),r.mousemove=null),e&16?r.wheel||=(t.addEventListener(`wheel`,i.wheel,{passive:!1}),i.wheel):(t.removeEventListener(`wheel`,r.wheel),r.wheel=null),e&2?r.mouseup||=i.mouseup:(this._document.removeEventListener(`mouseup`,r.mouseup),r.mouseup=null),e&4?r.mousedrag||=i.mousedrag:(this._document.removeEventListener(`mousemove`,r.mousedrag),r.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(W(t,`mousedown`,e=>{if(e.preventDefault(),this.focus(),this.coreMouseService.areMouseEventsActive&&!this._selectionService.shouldForceSelection(e))return n(e),r.mouseup&&this._document.addEventListener(`mouseup`,r.mouseup),r.mousedrag&&this._document.addEventListener(`mousemove`,r.mousedrag),this.cancel(e)})),this._register(W(t,`wheel`,t=>{if(!r.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(t)===!1)return!1;if(!this.buffer.hasScrollback){if(t.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(t,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return this.cancel(t,!0);let n=G.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?`O`:`[`)+(t.deltaY<0?`A`:`B`);return this.coreService.triggerDataEvent(n,!0),this.cancel(t,!0)}}},{passive:!1}))}refresh(e,t){this._renderService?.refreshRows(e,t)}updateCursorStyle(e){this._selectionService?.shouldColumnSelect(e)?this.element.classList.add(`column-select`):this.element.classList.remove(`column-select`)}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,t){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,t),this.refresh(0,this.rows-1)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){e&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}paste(e){Dr(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}attachCustomWheelEventHandler(e){this._customWheelEventHandler=e}registerLinkProvider(e){return this._linkProviderService.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw Error(`Terminal must be opened first`);let t=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),t}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw Error(`Terminal must be opened first`);this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return this._selectionService?this._selectionService.hasSelection:!1}select(e,t,n){this._selectionService.setSelection(e,t,n)}getSelection(){return this._selectionService?this._selectionService.selectionText:``}getSelectionPosition(){if(this._selectionService&&this._selectionService.hasSelection)return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){this._selectionService?.clearSelection()}selectAll(){this._selectionService?.selectAll()}selectLines(e,t){this._selectionService?.selectLines(e,t)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;let t=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!t&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;!t&&(e.key===`Dead`||e.key===`AltGraph`)&&(this._unprocessedDeadKey=!0);let n=Ru(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),n.type===3||n.type===2){let t=this.rows-1;return this.scrollLines(n.type===2?-t:t),this.cancel(e,!0)}if(n.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,e)||(n.cancel&&this.cancel(e,!0),!n.key)||e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.key.length===1&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)return!0;if(this._unprocessedDeadKey)return this._unprocessedDeadKey=!1,!0;if((n.key===G.ETX||n.key===G.CR)&&(this.textarea.value=``),this._onKey.fire({key:n.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(n.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)return this.cancel(e,!0);this._keyDownHandled=!0}_isThirdLevelShift(e,t){let n=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey||e.isWindows&&t.getModifierState(`AltGraph`);return t.type===`keypress`?n:n&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)&&(Qu(e)||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let t;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;if(this.cancel(e),e.charCode)t=e.charCode;else if(e.which===null||e.which===void 0)t=e.keyCode;else if(e.which!==0&&e.charCode!==0)t=e.which;else return!1;return!t||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e)?!1:(t=String.fromCharCode(t),this._onKey.fire({key:t,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(t,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,!0)}_inputEvent(e){if(e.data&&e.inputType===`insertText`&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;let t=e.data;return this.coreService.triggerDataEvent(t,!0),this.cancel(e),!0}return!1}resize(e,t){e===this.cols&&t===this.rows?this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure():super.resize(e,t)}_afterResize(e,t){this._charSizeService?.measure()}clear(){if(this.buffer.ybase!==0||this.buffer.y!==0){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e<this.rows;e++)this.buffer.lines.push(this.buffer.getBlankLine(gl));this._onScroll.fire({position:this.buffer.ydisp}),this.refresh(0,this.rows-1)}}reset(){this.options.rows=this.rows,this.options.cols=this.cols;let e=this._customKeyEventHandler;this._setup(),super.reset(),this._selectionService?.reset(),this._decorationService.reset(),this._customKeyEventHandler=e,this.refresh(0,this.rows-1)}clearTextureAtlas(){this._renderService?.clearTextureAtlas()}_reportFocus(){this.element?.classList.contains(`focus`)?this.coreService.triggerDataEvent(G.ESC+`[I`):this.coreService.triggerDataEvent(G.ESC+`[O`)}_reportWindowsOptions(e){if(this._renderService)switch(e){case 0:let e=this._renderService.dimensions.css.canvas.width.toFixed(0),t=this._renderService.dimensions.css.canvas.height.toFixed(0);this.coreService.triggerDataEvent(`${G.ESC}[4;${t};${e}t`);break;case 1:let n=this._renderService.dimensions.css.cell.width.toFixed(0),r=this._renderService.dimensions.css.cell.height.toFixed(0);this.coreService.triggerDataEvent(`${G.ESC}[6;${r};${n}t`)}}cancel(e,t){if(this.options.cancelEvents||t)return e.preventDefault(),e.stopPropagation(),!1}};function Qu(e){return e.keyCode===16||e.keyCode===17||e.keyCode===18}var $u=class{constructor(){this._addons=[]}dispose(){for(let e=this._addons.length-1;e>=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let n={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(n),t.dispose=()=>this._wrappedAddonDispose(n),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let n=0;n<this._addons.length;n++)if(this._addons[n]===e){t=n;break}if(t===-1)throw Error(`Could not dispose an addon that has not been loaded`);e.isDisposed=!0,e.dispose.apply(e.instance),this._addons.splice(t,1)}},ed=class{constructor(e){this._line=e}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(e,t){if(!(e<0||e>=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new Rr)}translateToString(e,t,n){return this._line.translateToString(e,t,n)}},td=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){let t=this._buffer.lines.get(e);if(t)return new ed(t)}getNullCell(){return new Rr}},nd=class extends H{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new U),this.onBufferChange=this._onBufferChange.event,this._normal=new td(this._core.buffers.normal,`normal`),this._alternate=new td(this._core.buffers.alt,`alternate`),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw Error(`Active buffer is neither normal nor alternate`)}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}},rd=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,e=>t(e.toArray()))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,(e,n)=>t(e,n.toArray()))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}},id=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}},ad=[`cols`,`rows`],od=0,sd=class extends H{constructor(e){super(),this._core=this._register(new Zu(e)),this._addonManager=this._register(new $u),this._publicOptions={...this._core.options};let t=e=>this._core.options[e],n=(e,t)=>{this._checkReadonlyOptions(e),this._core.options[e]=t};for(let e in this._core.options){let r={get:t.bind(this,e),set:n.bind(this,e)};Object.defineProperty(this._publicOptions,e,r)}}_checkReadonlyOptions(e){if(ad.includes(e))throw Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw Error(`You must set the allowProposedApi option to true to use proposed API`)}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||=new rd(this._core),this._parser}get unicode(){return this._checkProposedApi(),new id(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||=this._register(new nd(this._core)),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,t=`none`;switch(this._core.coreMouseService.activeProtocol){case`X10`:t=`x10`;break;case`VT200`:t=`vt200`;break;case`DRAG`:t=`drag`;break;case`ANY`:t=`any`}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,synchronizedOutputMode:e.synchronizedOutput,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,n){this._verifyIntegers(e,t,n),this._core.select(e,t,n)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write(`\r
21
- `,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return xr.get()},set promptLabel(e){xr.set(e)},get tooMuchOutput(){return Cr.get()},set tooMuchOutput(e){Cr.set(e)}}}_verifyIntegers(...e){for(od of e)if(od===1/0||isNaN(od)||od%1!=0)throw Error(`This API only accepts integers`)}_verifyPositiveIntegers(...e){for(od of e)if(od&&(od===1/0||isNaN(od)||od%1!=0||od<0))throw Error(`This API only accepts positive integers`)}},cd=2,ld=1,ud=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:this._terminal.options.overviewRuler?.width||14,n=window.getComputedStyle(this._terminal.element.parentElement),r=parseInt(n.getPropertyValue(`height`)),i=Math.max(0,parseInt(n.getPropertyValue(`width`))),a=window.getComputedStyle(this._terminal.element),o={top:parseInt(a.getPropertyValue(`padding-top`)),bottom:parseInt(a.getPropertyValue(`padding-bottom`)),right:parseInt(a.getPropertyValue(`padding-right`)),left:parseInt(a.getPropertyValue(`padding-left`))},s=o.top+o.bottom,c=o.right+o.left,l=r-s,u=i-c-t;return{cols:Math.max(cd,Math.floor(u/e.css.cell.width)),rows:Math.max(ld,Math.floor(l/e.css.cell.height))}}};function dd(e){return e.length}function fd(e,t){return t<=0||e<0?-1:Math.min(e,t-1)}function pd(e,t,n){return fd(e===t?t:e>t?e-1:e,n)}function md(e,t){return Array.from({length:t},(e,t)=>t).find(t=>t!==e)??-1}function hd(e,t){let n=e.filter(e=>!t.has(e.id));return n.find(e=>!e.workspaceMissing)??n[0]??null}function gd(e){return!(e.key!==`Enter`||e.shiftKey||e.composing||e.maximized)}function _d(e){return e}async function vd(e,t={}){if(!e)return`unsupported`;let n=t.clipboard===void 0?typeof navigator<`u`?navigator.clipboard??null:null:t.clipboard,r=t.execCommand??(typeof document<`u`?document.execCommand.bind(document):void 0),i=t.makeTextarea??(()=>{let e=document.createElement(`textarea`);return document.body.appendChild(e),{set value(t){e.value=t},get value(){return e.value},style:{get position(){return e.style.position},set position(t){e.style.position=t},get opacity(){return e.style.opacity},set opacity(t){e.style.opacity=t}},select:()=>e.select(),remove:()=>e.remove()}}),a=n?.writeText;if(typeof a==`function`)try{return await a.call(n,e),`copied`}catch{}let o=null;try{let t=i();return o=t,t.value=e,t.style.position=`fixed`,t.style.opacity=`0`,t.select(),r&&r(`copy`)?`copied`:`failed`}catch{return`failed`}finally{o?.remove()}}var yd=P(`<button type=button><span class=iconbtn-glyph>`),bd=P(`<button class=copybtn>`),xd=P(`<div class=overlay><div class=modal><div class=modal-head><b></b><button class=iconbtn>✕`);function Sd(e){return(()=>{var t=yd(),n=t.firstChild;return Oe(t,`click`,e.onClick,!0),L(n,()=>e.icon),b(n=>{var r=`iconbtn`+(e.active?` active`:``)+(e.class?` `+e.class:``),i=e.title,a=e.style;return r!==n.e&&I(t,n.e=r),i!==n.t&&F(t,`title`,n.t=i),n.a=ke(t,a,n.a),n},{e:void 0,t:void 0,a:void 0}),t})()}function Cd(e){let[t,n]=y(!1),[r,i]=y(!1),a=t=>{t.preventDefault(),t.stopPropagation(),vd(e.text??``).then(e=>{e===`unsupported`||e===`failed`?(i(!0),setTimeout(()=>i(!1),1200)):(n(!0),setTimeout(()=>n(!1),900))})};return(()=>{var n=bd();return n.$$click=a,L(n,(()=>{var n=N(()=>!!t());return()=>n()?`✓`:N(()=>!!r())()?`✗`:e.label??`⧉`})()),b(()=>F(n,`title`,e.title??`copy to clipboard`)),n})()}function wd(e){return(()=>{var t=xd(),n=t.firstChild,r=n.firstChild.firstChild,i=r.nextSibling;return t.$$click=t=>t.target===t.currentTarget&&e.onClose(),L(r,()=>e.title),Oe(i,`click`,e.onClose,!0),L(n,()=>e.children,null),t})()}De([`click`]);var Td={fg:void 0,bg:void 0,bold:!1,dim:!1,italic:!1,underline:!1,inverse:!1},Ed=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`];function Dd(e){let t=[];return e.fg&&t.push(`ansi-fg-${e.fg}`),e.bg&&t.push(`ansi-bg-${e.bg}`),e.bold&&t.push(`ansi-bold`),e.dim&&t.push(`ansi-dim`),e.italic&&t.push(`ansi-italic`),e.underline&&t.push(`ansi-underline`),e.inverse&&t.push(`ansi-inverse`),t}function Od(e,t){let n={...e};t.length===0&&(t=[0]);for(let e=0;e<t.length;e++){let r=t[e];if(r===0)n.fg=void 0,n.bg=void 0,n.bold=!1,n.dim=!1,n.italic=!1,n.underline=!1,n.inverse=!1;else if(r===1)n.bold=!0;else if(r===2)n.dim=!0;else if(r===3)n.italic=!0;else if(r===4)n.underline=!0;else if(r===7)n.inverse=!0;else if(r===21||r===22)n.bold=!1,n.dim=!1;else if(r===23)n.italic=!1;else if(r===24)n.underline=!1;else if(r===27)n.inverse=!1;else if(r>=30&&r<=37)n.fg=Ed[r-30];else if(r>=90&&r<=97)n.fg=`bright-${Ed[r-90]}`;else if(r===39)n.fg=void 0;else if(r>=40&&r<=47)n.bg=Ed[r-40];else if(r>=100&&r<=107)n.bg=`bright-${Ed[r-100]}`;else if(r===49)n.bg=void 0;else if(r===38||r===48){let i=t[e+1],a=r===38?`fg`:`bg`;i===5&&t[e+2]!==void 0?(n[a]=`ext`,e+=2):i===2&&t[e+4]!==void 0?(n[a]=`ext`,e+=4):(n[a]=`ext`,e+=1)}}return n}var kd=/\x1b\[([0-9;]*)m/;function Ad(e){if(!e)return[];let t=[],n={...Td},r=``,i=()=>{if(!r)return;let e=Dd(n),i=t[t.length-1];i&&i.classes.join(` `)===e.join(` `)?i.text+=r:t.push({text:r,classes:e}),r=``};for(let t=0;t<e.length;t++){let a=e[t];if(a===`\x1B`){let r=e.slice(t),a=kd.exec(r);if(a){i();let e=(a[1]??``).split(`;`).filter(e=>e!==``).map(e=>Number(e)).filter(e=>Number.isFinite(e));n=Od(n,e),t+=a[0].length-1;continue}let o=/^\x1b\[[0-9;?]*[A-Za-z]/.exec(r);if(o){t+=o[0].length-1;continue}let s=/^\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/.exec(r);if(s){t+=s[0].length-1;continue}}else if(a===`\r`){if(e[t+1]===`
18
+ `)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh()),Cc&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r||!t?!1:this._areCoordsInSelection(t,n,r)}isCellInSelection(e,t){let n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r?!1:this._areCoordsInSelection([e,t],n,r)}_areCoordsInSelection(e,t,n){return e[1]>t[1]&&e[1]<n[1]||t[1]===n[1]&&e[1]===t[1]&&e[0]>=t[0]&&e[0]<n[0]||t[1]<n[1]&&e[1]===n[1]&&e[0]<n[0]||t[1]<n[1]&&e[1]===t[1]&&e[0]>=t[0]}_selectWordAtCursor(e,t){let n=this._linkifier.currentLink?.link?.range;if(n)return this._model.selectionStart=[n.start.x-1,n.start.y-1],this._model.selectionStartLength=Kc(n,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let r=this._getMouseBufferCoords(e);return r?(this._selectWordAt(r,t),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=sc(this._coreBrowserService.window,e,this._screenElement)[1],n=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=n?0:(t>n&&(t-=n),t=Math.min(Math.max(t,-qc),qc),t/=qc,t/Math.abs(t)+Math.round(t*(Jc-1)))}shouldForceSelection(e){return yc?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(e.button===2&&this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener(`mousemove`,this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener(`mouseup`,this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),Yc)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener(`mousemove`,this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener(`mouseup`,this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&t.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(yc&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]<this._model.selectionStart[1]?this._model.selectionEnd[0]=0:this._model.selectionEnd[0]=this._bufferService.cols:this._activeSelectionMode===1&&this._selectToWordAt(this._model.selectionEnd),this._dragScrollAmount=this._getMouseEventScrollAmount(e),this._activeSelectionMode!==3&&(this._dragScrollAmount>0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let n=this._bufferService.buffer;if(this._model.selectionEnd[1]<n.lines.length){let e=n.lines.get(this._model.selectionEnd[1]);e&&e.hasWidth(this._model.selectionEnd[0])===0&&this._model.selectionEnd[0]<this._bufferService.cols&&this._model.selectionEnd[0]++}(!t||t[0]!==this._model.selectionEnd[0]||t[1]!==this._model.selectionEnd[1])&&this.refresh(!0)}_dragScroll(){if(this._model.selectionEnd&&this._model.selectionStart&&this._dragScrollAmount){this._onRequestScrollLines.fire({amount:this._dragScrollAmount,suppressScrollEvent:!1});let e=this._bufferService.buffer;this._dragScrollAmount>0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&t<Xc&&e.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){let t=this._mouseService.getCoords(e,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(t&&t[0]!==void 0&&t[1]!==void 0){let e=Mc(t[0]-1,t[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(e,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd,n=!!e&&!!t&&(e[0]!==t[0]||e[1]!==t[1]);n?!e||!t||(!this._oldSelectionStart||!this._oldSelectionEnd||e[0]!==this._oldSelectionStart[0]||e[1]!==this._oldSelectionStart[1]||t[0]!==this._oldSelectionEnd[0]||t[1]!==this._oldSelectionEnd[1])&&this._fireOnSelectionChange(e,t,n):this._oldHasSelection&&this._fireOnSelectionChange(e,t,n)}_fireOnSelectionChange(e,t,n){this._oldSelectionStart=e,this._oldSelectionEnd=t,this._oldHasSelection=n,this._onSelectionChange.fire()}_handleBufferActivate(e){this.clearSelection(),this._trimListener.dispose(),this._trimListener=e.activeBuffer.lines.onTrim(e=>this._handleTrim(e))}_convertViewportColToCharacterIndex(e,t){let n=t;for(let r=0;t>=r;r++){let i=e.loadCell(r,this._workCell).getChars().length;this._workCell.getWidth()===0?n--:i>1&&t!==r&&(n+=i-1)}return n}setSelection(e,t,n){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=n,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,n=!0,r=!0){if(e[0]>=this._bufferService.cols)return;let i=this._bufferService.buffer,a=i.lines.get(e[1]);if(!a)return;let o=i.translateBufferLineToString(e[1],!1),s=this._convertViewportColToCharacterIndex(a,e[0]),c=s,l=e[0]-s,u=0,d=0,f=0,p=0;if(o.charAt(s)===` `){for(;s>0&&o.charAt(s-1)===` `;)s--;for(;c<o.length&&o.charAt(c+1)===` `;)c++}else{let t=e[0],n=e[0];a.getWidth(t)===0&&(u++,t--),a.getWidth(n)===2&&(d++,n++);let r=a.getString(n).length;for(r>1&&(p+=r-1,c+=r-1);t>0&&s>0&&!this._isCharWordSeparator(a.loadCell(t-1,this._workCell));){a.loadCell(t-1,this._workCell);let e=this._workCell.getChars().length;this._workCell.getWidth()===0?(u++,t--):e>1&&(f+=e-1,s-=e-1),s--,t--}for(;n<a.length&&c+1<o.length&&!this._isCharWordSeparator(a.loadCell(n+1,this._workCell));){a.loadCell(n+1,this._workCell);let e=this._workCell.getChars().length;this._workCell.getWidth()===2?(d++,n++):e>1&&(p+=e-1,c+=e-1),c++,n++}}c++;let m=s+l-u+f,h=Math.min(this._bufferService.cols,c-s+u+d-f-p);if(t||o.slice(s,c).trim()!==``){if(n&&m===0&&a.getCodePoint(0)!==32){let t=i.lines.get(e[1]-1);if(t&&a.isWrapped&&t.getCodePoint(this._bufferService.cols-1)!==32){let t=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(t){let e=this._bufferService.cols-t.start;m-=e,h+=e}}}if(r&&m+h===this._bufferService.cols&&a.getCodePoint(this._bufferService.cols-1)!==32){let t=i.lines.get(e[1]+1);if(t?.isWrapped&&t.getCodePoint(0)!==32){let t=this._getWordAt([0,e[1]+1],!1,!1,!0);t&&(h+=t.length)}}return{start:m,length:h}}}_selectWordAt(e,t){let n=this._getWordAt(e,t);if(n){for(;n.start<0;)n.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[n.start,e[1]],this._model.selectionStartLength=n.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let n=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,n--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,n++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,n]}}_isCharWordSeparator(e){return e.getWidth()!==0&&this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),n={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=Kc(n,this._bufferService.cols)}};Qc=z([B(3,Gr),B(4,qr),B(5,ai),B(6,Zr),B(7,oi),B(8,ii)],Qc);var $c=class{constructor(){this._data={}}set(e,t,n){this._data[e]||(this._data[e]={}),this._data[e][t]=n}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},el=class{constructor(){this._color=new $c,this._css=new $c}setCss(e,t,n){this._css.set(e,t,n)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,n){this._color.set(e,t,n)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}},tl=Object.freeze((()=>{let e=[ks.toColor(`#2e3436`),ks.toColor(`#cc0000`),ks.toColor(`#4e9a06`),ks.toColor(`#c4a000`),ks.toColor(`#3465a4`),ks.toColor(`#75507b`),ks.toColor(`#06989a`),ks.toColor(`#d3d7cf`),ks.toColor(`#555753`),ks.toColor(`#ef2929`),ks.toColor(`#8ae234`),ks.toColor(`#fce94f`),ks.toColor(`#729fcf`),ks.toColor(`#ad7fa8`),ks.toColor(`#34e2e2`),ks.toColor(`#eeeeec`)],t=[0,95,135,175,215,255];for(let n=0;n<216;n++){let r=t[n/36%6|0],i=t[n/6%6|0],a=t[n%6];e.push({css:Ds.toCss(r,i,a),rgba:Ds.toRgba(r,i,a)})}for(let t=0;t<24;t++){let n=8+t*10;e.push({css:Ds.toCss(n,n,n),rgba:Ds.toRgba(n,n,n)})}return e})()),nl=ks.toColor(`#ffffff`),rl=ks.toColor(`#000000`),il=ks.toColor(`#ffffff`),al=rl,ol={css:`rgba(255, 255, 255, 0.3)`,rgba:4294967117},sl=nl,cl=class extends U{constructor(e){super(),this._optionsService=e,this._contrastCache=new el,this._halfContrastCache=new el,this._onChangeColors=this._register(new W),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:nl,background:rl,cursor:il,cursorAccent:al,selectionForeground:void 0,selectionBackgroundTransparent:ol,selectionBackgroundOpaque:Os.blend(rl,ol),selectionInactiveBackgroundTransparent:ol,selectionInactiveBackgroundOpaque:Os.blend(rl,ol),scrollbarSliderBackground:Os.opacity(nl,.2),scrollbarSliderHoverBackground:Os.opacity(nl,.4),scrollbarSliderActiveBackground:Os.opacity(nl,.5),overviewRulerBorder:nl,ansi:tl.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange(`minimumContrastRatio`,()=>this._contrastCache.clear())),this._register(this._optionsService.onSpecificOptionChange(`theme`,()=>this._setTheme(this._optionsService.rawOptions.theme)))}get colors(){return this._colors}_setTheme(e={}){let t=this._colors;if(t.foreground=q(e.foreground,nl),t.background=q(e.background,rl),t.cursor=Os.blend(t.background,q(e.cursor,il)),t.cursorAccent=Os.blend(t.background,q(e.cursorAccent,al)),t.selectionBackgroundTransparent=q(e.selectionBackground,ol),t.selectionBackgroundOpaque=Os.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=q(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=Os.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?q(e.selectionForeground,Es):void 0,t.selectionForeground===Es&&(t.selectionForeground=void 0),Os.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=Os.opacity(t.selectionBackgroundTransparent,.3)),Os.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=Os.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=q(e.scrollbarSliderBackground,Os.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=q(e.scrollbarSliderHoverBackground,Os.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=q(e.scrollbarSliderActiveBackground,Os.opacity(t.foreground,.5)),t.overviewRulerBorder=q(e.overviewRulerBorder,sl),t.ansi=tl.slice(),t.ansi[0]=q(e.black,tl[0]),t.ansi[1]=q(e.red,tl[1]),t.ansi[2]=q(e.green,tl[2]),t.ansi[3]=q(e.yellow,tl[3]),t.ansi[4]=q(e.blue,tl[4]),t.ansi[5]=q(e.magenta,tl[5]),t.ansi[6]=q(e.cyan,tl[6]),t.ansi[7]=q(e.white,tl[7]),t.ansi[8]=q(e.brightBlack,tl[8]),t.ansi[9]=q(e.brightRed,tl[9]),t.ansi[10]=q(e.brightGreen,tl[10]),t.ansi[11]=q(e.brightYellow,tl[11]),t.ansi[12]=q(e.brightBlue,tl[12]),t.ansi[13]=q(e.brightMagenta,tl[13]),t.ansi[14]=q(e.brightCyan,tl[14]),t.ansi[15]=q(e.brightWhite,tl[15]),e.extendedAnsi){let n=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let r=0;r<n;r++)t.ansi[r+16]=q(e.extendedAnsi[r],tl[r+16])}this._contrastCache.clear(),this._halfContrastCache.clear(),this._updateRestoreColors(),this._onChangeColors.fire(this.colors)}restoreColor(e){this._restoreColor(e),this._onChangeColors.fire(this.colors)}_restoreColor(e){if(e===void 0)for(let e=0;e<this._restoreColors.ansi.length;++e)this._colors.ansi[e]=this._restoreColors.ansi[e];else switch(e){case 256:this._colors.foreground=this._restoreColors.foreground;break;case 257:this._colors.background=this._restoreColors.background;break;case 258:this._colors.cursor=this._restoreColors.cursor;break;default:this._colors.ansi[e]=this._restoreColors.ansi[e]}}modifyColors(e){e(this._colors),this._onChangeColors.fire(this.colors)}_updateRestoreColors(){this._restoreColors={foreground:this._colors.foreground,background:this._colors.background,cursor:this._colors.cursor,ansi:this._colors.ansi.slice()}}};cl=z([B(0,Zr)],cl);function q(e,t){if(e!==void 0)try{return ks.toColor(e)}catch{}return t}var ll=class{constructor(...e){this._entries=new Map;for(let[t,n]of e)this.set(t,n)}set(e,t){let n=this._entries.get(e);return this._entries.set(e,t),n}forEach(e){for(let[t,n]of this._entries.entries())e(t,n)}has(e){return this._entries.has(e)}get(e){return this._entries.get(e)}},ul=class{constructor(){this._services=new ll,this._services.set(Yr,this)}setService(e,t){this._services.set(e,t)}getService(e){return this._services.get(e)}createInstance(e,...t){let n=Hr(e).sort((e,t)=>e.index-t.index),r=[];for(let t of n){let n=this._services.get(t.id);if(!n)throw Error(`[createInstance] ${e.name} depends on UNKNOWN service ${t.id._id}.`);r.push(n)}let i=n.length>0?n[0].index:t.length;if(t.length!==i)throw Error(`[createInstance] First service dependency of ${e.name} at position ${i+1} conflicts with ${t.length} static arguments`);return new e(...t,...r)}},dl={trace:0,debug:1,info:2,warn:3,error:4,off:5},fl=`xterm.js: `,pl=class extends U{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange(`logLevel`,()=>this._updateLogLevel())),ml=this}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=dl[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;t<e.length;t++)typeof e[t]==`function`&&(e[t]=e[t]())}_log(e,t,n){this._evalLazyOptionalParams(n),e.call(console,(this._optionsService.options.logger?``:fl)+t,...n)}trace(e,...t){this._logLevel<=0&&this._log(this._optionsService.options.logger?.trace.bind(this._optionsService.options.logger)??console.log,e,t)}debug(e,...t){this._logLevel<=1&&this._log(this._optionsService.options.logger?.debug.bind(this._optionsService.options.logger)??console.log,e,t)}info(e,...t){this._logLevel<=2&&this._log(this._optionsService.options.logger?.info.bind(this._optionsService.options.logger)??console.info,e,t)}warn(e,...t){this._logLevel<=3&&this._log(this._optionsService.options.logger?.warn.bind(this._optionsService.options.logger)??console.warn,e,t)}error(e,...t){this._logLevel<=4&&this._log(this._optionsService.options.logger?.error.bind(this._optionsService.options.logger)??console.error,e,t)}};pl=z([B(0,Zr)],pl);var ml,hl=class extends U{constructor(e){super(),this._maxLength=e,this.onDeleteEmitter=this._register(new W),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this._register(new W),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this._register(new W),this.onTrim=this.onTrimEmitter.event,this._array=Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(e){if(this._maxLength===e)return;let t=Array(e);for(let n=0;n<Math.min(e,this.length);n++)t[n]=this._array[this._getCyclicIndex(n)];this._array=t,this._maxLength=e,this._startIndex=0}get length(){return this._length}set length(e){if(e>this._length)for(let t=this._length;t<e;t++)this._array[t]=void 0;this._length=e}get(e){return this._array[this._getCyclicIndex(e)]}set(e,t){this._array[this._getCyclicIndex(e)]=t}push(e){this._array[this._getCyclicIndex(this._length)]=e,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++}recycle(){if(this._length!==this._maxLength)throw 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(e,t,...n){if(t){for(let n=e;n<this._length-t;n++)this._array[this._getCyclicIndex(n)]=this._array[this._getCyclicIndex(n+t)];this._length-=t,this.onDeleteEmitter.fire({index:e,amount:t})}for(let t=this._length-1;t>=e;t--)this._array[this._getCyclicIndex(t+n.length)]=this._array[this._getCyclicIndex(t)];for(let t=0;t<n.length;t++)this._array[this._getCyclicIndex(e+t)]=n[t];if(n.length&&this.onInsertEmitter.fire({index:e,amount:n.length}),this._length+n.length>this._maxLength){let e=this._length+n.length-this._maxLength;this._startIndex+=e,this._length=this._maxLength,this.onTrimEmitter.fire(e)}else this._length+=n.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,n){if(!(t<=0)){if(e<0||e>=this._length)throw Error(`start argument out of range`);if(e+n<0)throw Error(`Cannot shift elements in list beyond index 0`);if(n>0){for(let r=t-1;r>=0;r--)this.set(e+r+n,this.get(e+r));let r=e+t+n-this._length;if(r>0)for(this._length+=r;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let r=0;r<t;r++)this.set(e+r+n,this.get(e+r))}}_getCyclicIndex(e){return(this._startIndex+e)%this._maxLength}},J=3,gl=Object.freeze(new Ir),_l=0,vl=2,yl=class e{constructor(e,t,n=!1){this.isWrapped=n,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(e*J);let r=t||Rr.fromCharData([0,Pr,1,0]);for(let t=0;t<e;++t)this.setCell(t,r);this.length=e}get(e){let t=this._data[e*J+0],n=t&2097151;return[this._data[e*J+1],t&2097152?this._combined[e]:n?Ar(n):``,t>>22,t&2097152?this._combined[e].charCodeAt(this._combined[e].length-1):n]}set(e,t){this._data[e*J+1]=t[0],t[1].length>1?(this._combined[e]=t[1],this._data[e*J+0]=e|2097152|t[2]<<22):this._data[e*J+0]=t[1].charCodeAt(0)|t[2]<<22}getWidth(e){return this._data[e*J+0]>>22}hasWidth(e){return this._data[e*J+0]&12582912}getFg(e){return this._data[e*J+1]}getBg(e){return this._data[e*J+2]}hasContent(e){return this._data[e*J+0]&4194303}getCodePoint(e){let t=this._data[e*J+0];return t&2097152?this._combined[e].charCodeAt(this._combined[e].length-1):t&2097151}isCombined(e){return this._data[e*J+0]&2097152}getString(e){let t=this._data[e*J+0];return t&2097152?this._combined[e]:t&2097151?Ar(t&2097151):``}isProtected(e){return this._data[e*J+2]&536870912}loadCell(e,t){return _l=e*J,t.content=this._data[_l+0],t.fg=this._data[_l+1],t.bg=this._data[_l+2],t.content&2097152&&(t.combinedData=this._combined[e]),t.bg&268435456&&(t.extended=this._extendedAttrs[e]),t}setCell(e,t){t.content&2097152&&(this._combined[e]=t.combinedData),t.bg&268435456&&(this._extendedAttrs[e]=t.extended),this._data[e*J+0]=t.content,this._data[e*J+1]=t.fg,this._data[e*J+2]=t.bg}setCellFromCodepoint(e,t,n,r){r.bg&268435456&&(this._extendedAttrs[e]=r.extended),this._data[e*J+0]=t|n<<22,this._data[e*J+1]=r.fg,this._data[e*J+2]=r.bg}addCodepointToCell(e,t,n){let r=this._data[e*J+0];r&2097152?this._combined[e]+=Ar(t):r&2097151?(this._combined[e]=Ar(r&2097151)+Ar(t),r&=-2097152,r|=2097152):r=t|1<<22,n&&(r&=-12582913,r|=n<<22),this._data[e*J+0]=r}insertCells(e,t,n){if(e%=this.length,e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length-e){let r=new Rr;for(let n=this.length-e-t-1;n>=0;--n)this.setCell(e+t+n,this.loadCell(e+n,r));for(let r=0;r<t;++r)this.setCell(e+r,n)}else for(let t=e;t<this.length;++t)this.setCell(t,n);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,n)}deleteCells(e,t,n){if(e%=this.length,t<this.length-e){let r=new Rr;for(let n=0;n<this.length-e-t;++n)this.setCell(e+n,this.loadCell(e+t+n,r));for(let e=this.length-t;e<this.length;++e)this.setCell(e,n)}else for(let t=e;t<this.length;++t)this.setCell(t,n);e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),this.getWidth(e)===0&&!this.hasContent(e)&&this.setCellFromCodepoint(e,0,1,n)}replaceCells(e,t,n,r=!1){if(r)for(e&&this.getWidth(e-1)===2&&!this.isProtected(e-1)&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length&&this.getWidth(t-1)===2&&!this.isProtected(t)&&this.setCellFromCodepoint(t,0,1,n);e<t&&e<this.length;)this.isProtected(e)||this.setCell(e,n),e++;else for(e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t,0,1,n);e<t&&e<this.length;)this.setCell(e++,n)}resize(e,t){if(e===this.length)return this._data.length*4*vl<this._data.buffer.byteLength;let n=e*J;if(e>this.length){if(this._data.buffer.byteLength>=n*4)this._data=new Uint32Array(this._data.buffer,0,n);else{let e=new Uint32Array(n);e.set(this._data),this._data=e}for(let n=this.length;n<e;++n)this.setCell(n,t)}else{this._data=this._data.subarray(0,n);let t=Object.keys(this._combined);for(let n=0;n<t.length;n++){let r=parseInt(t[n],10);r>=e&&delete this._combined[r]}let r=Object.keys(this._extendedAttrs);for(let t=0;t<r.length;t++){let n=parseInt(r[t],10);n>=e&&delete this._extendedAttrs[n]}}return this.length=e,n*4*vl<this._data.buffer.byteLength}cleanupMemory(){if(this._data.length*4*vl<this._data.buffer.byteLength){let e=new Uint32Array(this._data.length);return e.set(this._data),this._data=e,1}return 0}fill(e,t=!1){if(t)for(let t=0;t<this.length;++t)this.isProtected(t)||this.setCell(t,e);else{this._combined={},this._extendedAttrs={};for(let t=0;t<this.length;++t)this.setCell(t,e)}}copyFrom(e){this.length===e.length?this._data.set(e._data):this._data=new Uint32Array(e._data),this.length=e.length,this._combined={};for(let t in e._combined)this._combined[t]=e._combined[t];this._extendedAttrs={};for(let t in e._extendedAttrs)this._extendedAttrs[t]=e._extendedAttrs[t];this.isWrapped=e.isWrapped}clone(){let t=new e(0);t._data=new Uint32Array(this._data),t.length=this.length;for(let e in this._combined)t._combined[e]=this._combined[e];for(let e in this._extendedAttrs)t._extendedAttrs[e]=this._extendedAttrs[e];return t.isWrapped=this.isWrapped,t}getTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(this._data[e*J+0]&4194303)return e+(this._data[e*J+0]>>22);return 0}getNoBgTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(this._data[e*J+0]&4194303||this._data[e*J+2]&50331648)return e+(this._data[e*J+0]>>22);return 0}copyCellsFrom(e,t,n,r,i){let a=e._data;if(i)for(let i=r-1;i>=0;i--){for(let e=0;e<J;e++)this._data[(n+i)*J+e]=a[(t+i)*J+e];a[(t+i)*J+2]&268435456&&(this._extendedAttrs[n+i]=e._extendedAttrs[t+i])}else for(let i=0;i<r;i++){for(let e=0;e<J;e++)this._data[(n+i)*J+e]=a[(t+i)*J+e];a[(t+i)*J+2]&268435456&&(this._extendedAttrs[n+i]=e._extendedAttrs[t+i])}let o=Object.keys(e._combined);for(let r=0;r<o.length;r++){let i=parseInt(o[r],10);i>=t&&(this._combined[i-t+n]=e._combined[i])}}translateToString(e,t,n,r){t??=0,n??=this.length,e&&(n=Math.min(n,this.getTrimmedLength())),r&&(r.length=0);let i=``;for(;t<n;){let e=this._data[t*J+0],n=e&2097151,a=e&2097152?this._combined[t]:n?Ar(n):Fr;if(i+=a,r)for(let e=0;e<a.length;++e)r.push(t);t+=e>>22||1}return r&&r.push(t),i}};function bl(e,t,n,r,i,a){let o=[];for(let s=0;s<e.length-1;s++){let c=s,l=e.get(++c);if(!l.isWrapped)continue;let u=[e.get(s)];for(;c<e.length&&l.isWrapped;)u.push(l),l=e.get(++c);if(!a&&r>=s&&r<c){s+=u.length-1;continue}let d=0,f=wl(u,d,t),p=1,m=0;for(;p<u.length;){let e=wl(u,p,t),r=e-m,a=n-f,o=Math.min(r,a);u[d].copyCellsFrom(u[p],m,f,o,!1),f+=o,f===n&&(d++,f=0),m+=o,m===e&&(p++,m=0),f===0&&d!==0&&u[d-1].getWidth(n-1)===2&&(u[d].copyCellsFrom(u[d-1],n-1,f++,1,!1),u[d-1].setCell(n-1,i))}u[d].replaceCells(f,n,i);let h=0;for(let e=u.length-1;e>0&&(e>d||u[e].getTrimmedLength()===0);e--)h++;h>0&&(o.push(s+u.length-h),o.push(h)),s+=u.length-1}return o}function xl(e,t){let n=[],r=0,i=t[r],a=0;for(let o=0;o<e.length;o++)if(i===o){let n=t[++r];e.onDeleteEmitter.fire({index:o-a,amount:n}),o+=n-1,a+=n,i=t[++r]}else n.push(o);return{layout:n,countRemoved:a}}function Sl(e,t){let n=[];for(let r=0;r<t.length;r++)n.push(e.get(t[r]));for(let t=0;t<n.length;t++)e.set(t,n[t]);e.length=t.length}function Cl(e,t,n){let r=[],i=e.map((n,r)=>wl(e,r,t)).reduce((e,t)=>e+t),a=0,o=0,s=0;for(;s<i;){if(i-s<n){r.push(i-s);break}a+=n;let c=wl(e,o,t);a>c&&(a-=c,o++);let l=e[o].getWidth(a-1)===2;l&&a--;let u=l?n-1:n;r.push(u),s+=u}return r}function wl(e,t,n){if(t===e.length-1)return e[t].getTrimmedLength();let r=!e[t].hasContent(n-1)&&e[t].getWidth(n-1)===1,i=e[t+1].getWidth(0)===2;return r&&i?n-1:n}var Tl=class e{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=e._nextId++,this._onDispose=this.register(new W),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),ki(this._disposables),this._disposables.length=0)}register(e){return this._disposables.push(e),e}};Tl._nextId=1;var El=Tl,Dl={},Ol=Dl.B;Dl[0]={"`":`◆`,a:`▒`,b:`␉`,c:`␌`,d:`␍`,e:`␊`,f:`°`,g:`±`,h:`␤`,i:`␋`,j:`┘`,k:`┐`,l:`┌`,m:`└`,n:`┼`,o:`⎺`,p:`⎻`,q:`─`,r:`⎼`,s:`⎽`,t:`├`,u:`┤`,v:`┴`,w:`┬`,x:`│`,y:`≤`,z:`≥`,"{":`π`,"|":`≠`,"}":`£`,"~":`·`},Dl.A={"#":`£`},Dl.B=void 0,Dl[4]={"#":`£`,"@":`¾`,"[":`ij`,"\\":`½`,"]":`|`,"{":`¨`,"|":`f`,"}":`¼`,"~":`´`},Dl.C=Dl[5]={"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},Dl.R={"#":`£`,"@":`à`,"[":`°`,"\\":`ç`,"]":`§`,"{":`é`,"|":`ù`,"}":`è`,"~":`¨`},Dl.Q={"@":`à`,"[":`â`,"\\":`ç`,"]":`ê`,"^":`î`,"`":`ô`,"{":`é`,"|":`ù`,"}":`è`,"~":`û`},Dl.K={"@":`§`,"[":`Ä`,"\\":`Ö`,"]":`Ü`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`ß`},Dl.Y={"#":`£`,"@":`§`,"[":`°`,"\\":`ç`,"]":`é`,"`":`ù`,"{":`à`,"|":`ò`,"}":`è`,"~":`ì`},Dl.E=Dl[6]={"@":`Ä`,"[":`Æ`,"\\":`Ø`,"]":`Å`,"^":`Ü`,"`":`ä`,"{":`æ`,"|":`ø`,"}":`å`,"~":`ü`},Dl.Z={"#":`£`,"@":`§`,"[":`¡`,"\\":`Ñ`,"]":`¿`,"{":`°`,"|":`ñ`,"}":`ç`},Dl.H=Dl[7]={"@":`É`,"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},Dl[`=`]={"#":`ù`,"@":`à`,"[":`é`,"\\":`ç`,"]":`ê`,"^":`î`,_:`è`,"`":`ô`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`û`};var kl=4294967295,Al=class{constructor(e,t,n){this._hasScrollback=e,this._optionsService=t,this._bufferService=n,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=gl.clone(),this.savedCharset=Ol,this.markers=[],this._nullCell=Rr.fromCharData([0,Pr,1,0]),this._whitespaceCell=Rr.fromCharData([0,Fr,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new Oc,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new hl(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new Lr),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new Lr),this._whitespaceCell}getBlankLine(e,t){return new yl(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&e<this._rows}_getCorrectBufferLength(e){if(!this._hasScrollback)return e;let t=e+this._optionsService.rawOptions.scrollback;return t>kl?kl:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=gl);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new hl(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let n=this.getNullCell(gl),r=0,i=this._getCorrectBufferLength(t);if(i>this.lines.maxLength&&(this.lines.maxLength=i),this.lines.length>0){if(this._cols<e)for(let t=0;t<this.lines.length;t++)r+=+this.lines.get(t).resize(e,n);let a=0;if(this._rows<t)for(let r=this._rows;r<t;r++)this.lines.length<t+this.ybase&&(this._optionsService.rawOptions.windowsMode||this._optionsService.rawOptions.windowsPty.backend!==void 0||this._optionsService.rawOptions.windowsPty.buildNumber!==void 0?this.lines.push(new yl(e,n)):this.ybase>0&&this.lines.length<=this.ybase+this.y+a+1?(this.ybase--,a++,this.ydisp>0&&this.ydisp--):this.lines.push(new yl(e,n)));else for(let e=this._rows;e>t;e--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(i<this.lines.maxLength){let e=this.lines.length-i;e>0&&(this.lines.trimStart(e),this.ybase=Math.max(this.ybase-e,0),this.ydisp=Math.max(this.ydisp-e,0),this.savedY=Math.max(this.savedY-e,0)),this.lines.maxLength=i}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),a&&(this.y+=a),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let t=0;t<this.lines.length;t++)r+=+this.lines.get(t).resize(e,n);this._cols=e,this._rows=t,this._memoryCleanupQueue.clear(),r>.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition<this.lines.length;)if(t+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),t>100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&e.backend===`conpty`&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let n=this._optionsService.rawOptions.reflowCursorLine,r=bl(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(gl),n);if(r.length>0){let n=xl(this.lines,r);Sl(this.lines,n.layout),this._reflowLargerAdjustViewport(e,t,n.countRemoved)}}_reflowLargerAdjustViewport(e,t,n){let r=this.getNullCell(gl),i=n;for(;i-->0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<t&&this.lines.push(new yl(e,r))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-n,0)}_reflowSmaller(e,t){let n=this._optionsService.rawOptions.reflowCursorLine,r=this.getNullCell(gl),i=[],a=0;for(let o=this.lines.length-1;o>=0;o--){let s=this.lines.get(o);if(!s||!s.isWrapped&&s.getTrimmedLength()<=e)continue;let c=[s];for(;s.isWrapped&&o>0;)s=this.lines.get(--o),c.unshift(s);if(!n){let e=this.ybase+this.y;if(e>=o&&e<o+c.length)continue}let l=c[c.length-1].getTrimmedLength(),u=Cl(c,this._cols,e),d=u.length-c.length,f;f=this.ybase===0&&this.y!==this.lines.length-1?Math.max(0,this.y-this.lines.maxLength+d):Math.max(0,this.lines.length-this.lines.maxLength+d);let p=[];for(let e=0;e<d;e++){let e=this.getBlankLine(gl,!0);p.push(e)}p.length>0&&(i.push({start:o+c.length+a,newLines:p}),a+=p.length),c.push(...p);let m=u.length-1,h=u[m];h===0&&(m--,h=u[m]);let g=c.length-d-1,_=l;for(;g>=0;){let e=Math.min(_,h);if(c[m]===void 0)break;c[m].copyCellsFrom(c[g],_-e,h-e,e,!0),h-=e,h===0&&(m--,h=u[m]),_-=e,_===0&&(g--,_=wl(c,Math.max(g,0),this._cols))}for(let t=0;t<c.length;t++)u[t]<e&&c[t].setCell(u[t],r);let v=d-f;for(;v-->0;)this.ybase===0?this.y<t-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+a)-t&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+d,this.ybase+t-1)}if(i.length>0){let e=[],t=[];for(let e=0;e<this.lines.length;e++)t.push(this.lines.get(e));let n=this.lines.length,r=n-1,o=0,s=i[o];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+a);let c=0;for(let l=Math.min(this.lines.maxLength-1,n+a-1);l>=0;l--)if(s&&s.start>r+c){for(let e=s.newLines.length-1;e>=0;e--)this.lines.set(l--,s.newLines[e]);l++,e.push({index:r+1,amount:s.newLines.length}),c+=s.newLines.length,s=i[++o]}else this.lines.set(l,t[r--]);let l=0;for(let t=e.length-1;t>=0;t--)e[t].index+=l,this.lines.onInsertEmitter.fire(e[t]),l+=e[t].amount;let u=Math.max(0,n+a-this.lines.maxLength);u>0&&this.lines.onTrimEmitter.fire(u)}}translateBufferLineToString(e,t,n=0,r){let i=this.lines.get(e);return i?i.translateToString(t,n,r):``}getWrappedRangeForLine(e){let t=e,n=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;n+1<this.lines.length&&this.lines.get(n+1).isWrapped;)n++;return{first:t,last:n}}setupTabStops(e){for(e==null?(this.tabs={},e=0):this.tabs[e]||(e=this.prevStop(e));e<this._cols;e+=this._optionsService.rawOptions.tabStopWidth)this.tabs[e]=!0}prevStop(e){for(e??=this.x;!this.tabs[--e]&&e>0;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e??=this.x;!this.tabs[++e]&&e<this._cols;);return e>=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t<this.markers.length;t++)this.markers[t].line===e&&(this.markers[t].dispose(),this.markers.splice(t--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let e=0;e<this.markers.length;e++)this.markers[e].dispose();this.markers.length=0,this._isClearing=!1}addMarker(e){let t=new El(e);return this.markers.push(t),t.register(this.lines.onTrim(e=>{t.line-=e,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(e=>{t.line>=e.index&&(t.line+=e.amount)})),t.register(this.lines.onDelete(e=>{t.line>=e.index&&t.line<e.index+e.amount&&t.dispose(),t.line>e.index&&(t.line-=e.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},jl=class extends U{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new W),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this._register(this._optionsService.onSpecificOptionChange(`scrollback`,()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this._register(this._optionsService.onSpecificOptionChange(`tabStopWidth`,()=>this.setupTabStops()))}reset(){this._normal=new Al(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new Al(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}},Ml=2,Nl=1,Pl=class extends U{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new W),this.onResize=this._onResize.event,this._onScroll=this._register(new W),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,Ml),this.rows=Math.max(e.rawOptions.rows||0,Nl),this.buffers=this._register(new jl(e,this)),this._register(this.buffers.onBufferActivate(e=>{this._onScroll.fire(e.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let n=this.cols!==e,r=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:n,rowsChanged:r})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let n=this.buffer,r;r=this._cachedBlankLine,(!r||r.length!==this.cols||r.getFg(0)!==e.fg||r.getBg(0)!==e.bg)&&(r=n.getBlankLine(e,t),this._cachedBlankLine=r),r.isWrapped=t;let i=n.ybase+n.scrollTop,a=n.ybase+n.scrollBottom;if(n.scrollTop===0){let e=n.lines.isFull;a===n.lines.length-1?e?n.lines.recycle().copyFrom(r):n.lines.push(r.clone()):n.lines.splice(a+1,0,r.clone()),e?this.isUserScrolling&&(n.ydisp=Math.max(n.ydisp-1,0)):(n.ybase++,this.isUserScrolling||n.ydisp++)}else{let e=a-i+1;n.lines.shiftElements(i+1,e-1,-1),n.lines.set(a,r.clone())}this.isUserScrolling||(n.ydisp=n.ybase),this._onScroll.fire(n.ydisp)}scrollLines(e,t){let n=this.buffer;if(e<0){if(n.ydisp===0)return;this.isUserScrolling=!0}else e+n.ydisp>=n.ybase&&(this.isUserScrolling=!1);let r=n.ydisp;n.ydisp=Math.max(Math.min(n.ydisp+e,n.ybase),0),r!==n.ydisp&&(t||this._onScroll.fire(n.ydisp))}};Pl=z([B(0,Zr)],Pl);var Fl={cols:80,rows:24,cursorBlink:!1,cursorStyle:`block`,cursorWidth:1,cursorInactiveStyle:`outline`,customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:`alt`,fastScrollSensitivity:5,fontFamily:`monospace`,fontSize:15,fontWeight:`normal`,fontWeightBold:`bold`,ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:`info`,logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:yc,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:` ()[]{}',"\``,altClickMovesCursor:!0,convertEol:!1,termName:`xterm`,cancelEvents:!1,overviewRuler:{}},Il=[`normal`,`bold`,`100`,`200`,`300`,`400`,`500`,`600`,`700`,`800`,`900`],Ll=class extends U{constructor(e){super(),this._onOptionChange=this._register(new W),this.onOptionChange=this._onOptionChange.event;let t={...Fl};for(let n in e)if(n in t)try{let r=e[n];t[n]=this._sanitizeAndValidateOption(n,r)}catch(e){console.error(e)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register(H(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(n=>{n===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(n=>{e.indexOf(n)!==-1&&t()})}_setupOptions(){let e=e=>{if(!(e in Fl))throw Error(`No option with key "${e}"`);return this.rawOptions[e]},t=(e,t)=>{if(!(e in Fl))throw Error(`No option with key "${e}"`);t=this._sanitizeAndValidateOption(e,t),this.rawOptions[e]!==t&&(this.rawOptions[e]=t,this._onOptionChange.fire(e))};for(let n in this.rawOptions){let r={get:e.bind(this,n),set:t.bind(this,n)};Object.defineProperty(this.options,n,r)}}_sanitizeAndValidateOption(e,t){switch(e){case`cursorStyle`:if(t||=Fl[e],!Rl(t))throw Error(`"${t}" is not a valid value for ${e}`);break;case`wordSeparator`:t||=Fl[e];break;case`fontWeight`:case`fontWeightBold`:if(typeof t==`number`&&1<=t&&t<=1e3)break;t=Il.includes(t)?t:Fl[e];break;case`cursorWidth`:t=Math.floor(t);case`lineHeight`:case`tabStopWidth`:if(t<1)throw Error(`${e} cannot be less than 1, value: ${t}`);break;case`minimumContrastRatio`:t=Math.max(1,Math.min(21,Math.round(t*10)/10));break;case`scrollback`:if(t=Math.min(t,4294967295),t<0)throw Error(`${e} cannot be less than 0, value: ${t}`);break;case`fastScrollSensitivity`:case`scrollSensitivity`:if(t<=0)throw Error(`${e} cannot be less than or equal to 0, value: ${t}`);break;case`rows`:case`cols`:if(!t&&t!==0)throw Error(`${e} must be numeric, value: ${t}`);break;case`windowsPty`:t??={}}return t}};function Rl(e){return e===`block`||e===`underline`||e===`bar`}function zl(e,t=5){if(typeof e!=`object`)return e;let n=Array.isArray(e)?[]:{};for(let r in e)n[r]=t<=1?e[r]:e[r]&&zl(e[r],t-1);return n}var Bl=Object.freeze({insertMode:!1}),Vl=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),Hl=class extends U{constructor(e,t,n){super(),this._bufferService=e,this._logService=t,this._optionsService=n,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new W),this.onData=this._onData.event,this._onUserInput=this._register(new W),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new W),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new W),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=zl(Bl),this.decPrivateModes=zl(Vl)}reset(){this.modes=zl(Bl),this.decPrivateModes=zl(Vl)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let n=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&n.ybase!==n.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace(`sending data (codes)`,()=>e.split(``).map(e=>e.charCodeAt(0))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`),this._logService.trace(`sending binary (codes)`,()=>e.split(``).map(e=>e.charCodeAt(0))),this._onBinary.fire(e))}};Hl=z([B(0,Gr),B(1,Xr),B(2,Zr)],Hl);var Ul={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>e.button===4||e.action!==1?!1:(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>e.action!==32},DRAG:{events:23,restrict:e=>e.action!==32||e.button!==3},ANY:{events:31,restrict:e=>!0}};function Wl(e,t){let n=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(n|=64,n|=e.action):(n|=e.button&3,e.button&4&&(n|=64),e.button&8&&(n|=128),e.action===32?n|=32:e.action===0&&!t&&(n|=3)),n}var Gl=String.fromCharCode,Kl={DEFAULT:e=>{let t=[Wl(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?``:`\x1B[M${Gl(t[0])}${Gl(t[1])}${Gl(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`\x1B[<${Wl(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`\x1B[<${Wl(e,!0)};${e.x};${e.y}${t}`}},ql=class extends U{constructor(e,t,n){super(),this._bufferService=e,this._coreService=t,this._optionsService=n,this._protocols={},this._encodings={},this._activeProtocol=``,this._activeEncoding=``,this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new W),this.onProtocolChange=this._onProtocolChange.event;for(let e of Object.keys(Ul))this.addProtocol(e,Ul[e]);for(let e of Object.keys(Kl))this.addEncoding(e,Kl[e]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e){if(!this._protocols[e])throw Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol=`NONE`,this.activeEncoding=`DEFAULT`,this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,t,n){if(e.deltaY===0||e.shiftKey||t===void 0||n===void 0)return 0;let r=t/n,i=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(i/=r+0,Math.abs(e.deltaY)<50&&(i*=.3),this._wheelPartialScroll+=i,i=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(i*=this._bufferService.rows),i}_applyScrollModifier(e,t){return t.altKey||t.ctrlKey||t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding===`SGR_PIXELS`))||!this._protocols[this._activeProtocol].restrict(e))return!1;let t=this._encodings[this._activeEncoding](e);return t&&(this._activeEncoding===`DEFAULT`?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(e&1),up:!!(e&2),drag:!!(e&4),move:!!(e&8),wheel:!!(e&16)}}_equalEvents(e,t,n){if(n){if(e.x!==t.x||e.y!==t.y)return!1}else if(e.col!==t.col||e.row!==t.row)return!1;return e.button===t.button&&e.action===t.action&&e.ctrl===t.ctrl&&e.alt===t.alt&&e.shift===t.shift}};ql=z([B(0,Gr),B(1,qr),B(2,Zr)],ql);var Jl=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],Yl=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],Xl;function Zl(e,t){let n=0,r=t.length-1,i;if(e<t[0][0]||e>t[r][1])return!1;for(;r>=n;)if(i=n+r>>1,e>t[i][1])n=i+1;else if(e<t[i][0])r=i-1;else return!0;return!1}var Ql=class{constructor(){if(this.version=`6`,!Xl){Xl=new Uint8Array(65536),Xl.fill(1),Xl[0]=0,Xl.fill(0,1,32),Xl.fill(0,127,160),Xl.fill(2,4352,4448),Xl[9001]=2,Xl[9002]=2,Xl.fill(2,11904,42192),Xl[12351]=1,Xl.fill(2,44032,55204),Xl.fill(2,63744,64256),Xl.fill(2,65040,65050),Xl.fill(2,65072,65136),Xl.fill(2,65280,65377),Xl.fill(2,65504,65511);for(let e=0;e<Jl.length;++e)Xl.fill(0,Jl[e][0],Jl[e][1]+1)}}wcwidth(e){return e<32?0:e<127?1:e<65536?Xl[e]:Zl(e,Yl)?0:e>=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let n=this.wcwidth(e),r=n===0&&t!==0;if(r){let e=$l.extractWidth(t);e===0?r=!1:e>n&&(n=e)}return $l.createPropertyValue(0,n,r)}},$l=class e{constructor(){this._providers=Object.create(null),this._active=``,this._onChange=new W,this.onChange=this._onChange.event;let e=new Ql;this.register(e),this._active=e.version,this._activeProvider=e}static extractShouldJoin(e){return!!(e&1)}static extractWidth(e){return e>>1&3}static extractCharKind(e){return e>>3}static createPropertyValue(e,t,n=!1){return(e&16777215)<<3|(t&3)<<1|!!n}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(e){if(!this._providers[e])throw Error(`unknown Unicode version "${e}"`);this._active=e,this._activeProvider=this._providers[e],this._onChange.fire(e)}register(e){this._providers[e.version]=e}wcwidth(e){return this._activeProvider.wcwidth(e)}getStringCellWidth(t){let n=0,r=0,i=t.length;for(let a=0;a<i;++a){let o=t.charCodeAt(a);if(55296<=o&&o<=56319){if(++a>=i)return n+this.wcwidth(o);let e=t.charCodeAt(a);56320<=e&&e<=57343?o=(o-55296)*1024+e-56320+65536:n+=this.wcwidth(e)}let s=this.charProperties(o,r),c=e.extractWidth(s);e.extractShouldJoin(s)&&(c-=e.extractWidth(r)),n+=c,r=s}return n}charProperties(e,t){return this._activeProvider.charProperties(e,t)}},eu=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}};function tu(e){let t=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1)?.get(e.cols-1),n=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);n&&t&&(n.isWrapped=t[3]!==0&&t[3]!==32)}var nu=2147483647,ru=256,iu=class e{constructor(e=32,t=32){if(this.maxLength=e,this.maxSubParamsLength=t,t>ru)throw Error(`maxSubParamsLength must not be greater than 256`);this.params=new Int32Array(e),this.length=0,this._subParams=new Int32Array(t),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(e),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let n=new e;if(!t.length)return n;for(let e=+!!Array.isArray(t[0]);e<t.length;++e){let r=t[e];if(Array.isArray(r))for(let e=0;e<r.length;++e)n.addSubParam(r[e]);else n.addParam(r)}return n}clone(){let t=new e(this.maxLength,this.maxSubParamsLength);return t.params.set(this.params),t.length=this.length,t._subParams.set(this._subParams),t._subParamsLength=this._subParamsLength,t._subParamsIdx.set(this._subParamsIdx),t._rejectDigits=this._rejectDigits,t._rejectSubDigits=this._rejectSubDigits,t._digitIsSub=this._digitIsSub,t}toArray(){let e=[];for(let t=0;t<this.length;++t){e.push(this.params[t]);let n=this._subParamsIdx[t]>>8,r=this._subParamsIdx[t]&255;r-n>0&&e.push(Array.prototype.slice.call(this._subParams,n,r))}return e}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(e){if(this._digitIsSub=!1,this.length>=this.maxLength)this._rejectDigits=!0;else{if(e<-1)throw Error(`values lesser than -1 are not allowed`);this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=e>nu?nu:e}}addSubParam(e){if(this._digitIsSub=!0,this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength){this._rejectSubDigits=!0;return}if(e<-1)throw Error(`values lesser than -1 are not allowed`);this._subParams[this._subParamsLength++]=e>nu?nu:e,this._subParamsIdx[this.length-1]++}}hasSubParams(e){return(this._subParamsIdx[e]&255)-(this._subParamsIdx[e]>>8)>0}getSubParams(e){let t=this._subParamsIdx[e]>>8,n=this._subParamsIdx[e]&255;return n-t>0?this._subParams.subarray(t,n):null}getSubParamsAll(){let e={};for(let t=0;t<this.length;++t){let n=this._subParamsIdx[t]>>8,r=this._subParamsIdx[t]&255;r-n>0&&(e[t]=this._subParams.slice(n,r))}return e}addDigit(e){let t;if(this._rejectDigits||!(t=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let n=this._digitIsSub?this._subParams:this.params,r=n[t-1];n[t-1]=~r?Math.min(r*10+e,nu):e}},au=[],ou=class{constructor(){this._state=0,this._active=au,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=au}reset(){if(this._state===2)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=au,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||au,!this._active.length)this._handlerFb(this._id,`START`);else for(let e=this._active.length-1;e>=0;e--)this._active[e].start()}_put(e,t,n){if(!this._active.length)this._handlerFb(this._id,`PUT`,jr(e,t,n));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n)}start(){this.reset(),this._state=1}put(e,t,n){if(this._state!==3){if(this._state===1)for(;t<n;){let n=e[t++];if(n===59){this._state=2,this._start();break}if(n<48||57<n){this._state=3;return}this._id===-1&&(this._id=0),this._id=this._id*10+n-48}this._state===2&&n-t>0&&this._put(e,t,n)}}end(e,t=!0){if(this._state!==0){if(this._state!==3){if(this._state===1&&this._start(),!this._active.length)this._handlerFb(this._id,`END`,e);else{let n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&n===!1){for(;r>=0&&(n=this._active[r].end(e),n!==!0);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].end(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}}this._active=au,this._id=-1,this._state=0}}},su=class{constructor(e){this._handler=e,this._data=``,this._hitLimit=!1}start(){this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=jr(e,t,n),this._data.length>1e7&&(this._data=``,this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then(e=>(this._data=``,this._hitLimit=!1,e));return this._data=``,this._hitLimit=!1,t}},cu=[],lu=class{constructor(){this._handlers=Object.create(null),this._active=cu,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=cu}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=cu,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||cu,!this._active.length)this._handlerFb(this._ident,`HOOK`,t);else for(let e=this._active.length-1;e>=0;e--)this._active[e].hook(t)}put(e,t,n){if(!this._active.length)this._handlerFb(this._ident,`PUT`,jr(e,t,n));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n)}unhook(e,t=!0){if(!this._active.length)this._handlerFb(this._ident,`UNHOOK`,e);else{let n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&n===!1){for(;r>=0&&(n=this._active[r].unhook(e),n!==!0);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].unhook(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}this._active=cu,this._ident=0}},uu=new iu;uu.addParam(0);var du=class{constructor(e){this._handler=e,this._data=``,this._params=uu,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():uu,this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=jr(e,t,n),this._data.length>1e7&&(this._data=``,this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then(e=>(this._params=uu,this._data=``,this._hitLimit=!1,e));return this._params=uu,this._data=``,this._hitLimit=!1,t}},fu=class{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,n,r){this.table[t<<8|e]=n<<4|r}addMany(e,t,n,r){for(let i=0;i<e.length;i++)this.table[t<<8|e[i]]=n<<4|r}},pu=160,mu=function(){let e=new fu(4095),t=Array.apply(null,Array(256)).map((e,t)=>t),n=(e,n)=>t.slice(e,n),r=n(32,127),i=n(0,24);i.push(25),i.push.apply(i,n(28,32));let a=n(0,14),o;for(o in e.setDefault(1,0),e.addMany(r,0,2,0),a)e.addMany([24,26,153,154],o,3,0),e.addMany(n(128,144),o,3,0),e.addMany(n(144,152),o,3,0),e.add(156,o,0,0),e.add(27,o,11,1),e.add(157,o,4,8),e.addMany([152,158,159],o,0,7),e.add(155,o,11,3),e.add(144,o,11,9);return e.addMany(i,0,3,0),e.addMany(i,1,3,1),e.add(127,1,0,1),e.addMany(i,8,0,8),e.addMany(i,3,3,3),e.add(127,3,0,3),e.addMany(i,4,3,4),e.add(127,4,0,4),e.addMany(i,6,3,6),e.addMany(i,5,3,5),e.add(127,5,0,5),e.addMany(i,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(r,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(n(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(r,7,0,7),e.addMany(i,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(n(64,127),3,7,0),e.addMany(n(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(n(48,60),4,8,4),e.addMany(n(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(n(32,64),6,0,6),e.add(127,6,0,6),e.addMany(n(64,127),6,0,0),e.addMany(n(32,48),3,9,5),e.addMany(n(32,48),5,9,5),e.addMany(n(48,64),5,0,6),e.addMany(n(64,127),5,7,0),e.addMany(n(32,48),4,9,5),e.addMany(n(32,48),1,9,2),e.addMany(n(32,48),2,9,2),e.addMany(n(48,127),2,10,0),e.addMany(n(48,80),1,10,0),e.addMany(n(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(n(96,127),1,10,0),e.add(80,1,11,9),e.addMany(i,9,0,9),e.add(127,9,0,9),e.addMany(n(28,32),9,0,9),e.addMany(n(32,48),9,9,12),e.addMany(n(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(i,11,0,11),e.addMany(n(32,128),11,0,11),e.addMany(n(28,32),11,0,11),e.addMany(i,10,0,10),e.add(127,10,0,10),e.addMany(n(28,32),10,0,10),e.addMany(n(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(n(32,48),10,9,12),e.addMany(i,12,0,12),e.add(127,12,0,12),e.addMany(n(28,32),12,0,12),e.addMany(n(32,48),12,9,12),e.addMany(n(48,64),12,0,11),e.addMany(n(64,127),12,12,13),e.addMany(n(64,127),10,12,13),e.addMany(n(64,127),9,12,13),e.addMany(i,13,13,13),e.addMany(r,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(pu,0,2,0),e.add(pu,8,5,8),e.add(pu,6,0,6),e.add(pu,11,0,11),e.add(pu,13,13,13),e}(),hu=class extends U{constructor(e=mu){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new iu,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(e,t,n)=>{},this._executeHandlerFb=e=>{},this._csiHandlerFb=(e,t)=>{},this._escHandlerFb=e=>{},this._errorHandlerFb=e=>e,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register(H(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new ou),this._dcsParser=this._register(new lu),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:`\\`},()=>!0)}_identifier(e,t=[64,126]){let n=0;if(e.prefix){if(e.prefix.length>1)throw Error(`only one byte as prefix supported`);if(n=e.prefix.charCodeAt(0),n&&60>n||n>63)throw Error(`prefix must be in range 0x3c .. 0x3f`)}if(e.intermediates){if(e.intermediates.length>2)throw Error(`only two bytes as intermediates are supported`);for(let t=0;t<e.intermediates.length;++t){let r=e.intermediates.charCodeAt(t);if(32>r||r>47)throw Error(`intermediate must be in range 0x20 .. 0x2f`);n<<=8,n|=r}}if(e.final.length!==1)throw Error(`final must be a single byte`);let r=e.final.charCodeAt(0);if(t[0]>r||r>t[1])throw Error(`final must be in range ${t[0]} .. ${t[1]}`);return n<<=8,n|=r,n}identToString(e){let t=[];for(;e;)t.push(String.fromCharCode(e&255)),e>>=8;return t.reverse().join(``)}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){let n=this._identifier(e,[48,126]);this._escHandlers[n]===void 0&&(this._escHandlers[n]=[]);let r=this._escHandlers[n];return r.push(t),{dispose:()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){let n=this._identifier(e);this._csiHandlers[n]===void 0&&(this._csiHandlers[n]=[]);let r=this._csiHandlers[n];return r.push(t),{dispose:()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,t,n,r,i){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=n,this._parseStack.transition=r,this._parseStack.chunkPos=i}parse(e,t,n){let r=0,i=0,a=0,o;if(this._parseStack.state){if(this._parseStack.state===2)this._parseStack.state=0,a=this._parseStack.chunkPos+1;else{if(n===void 0||this._parseStack.state===1)throw this._parseStack.state=1,Error(`improper continuation due to previous async handler, giving up parsing`);let t=this._parseStack.handlers,i=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(n===!1&&i>-1){for(;i>=0&&(o=t[i](this._params),o!==!0);i--)if(o instanceof Promise)return this._parseStack.handlerPos=i,o}this._parseStack.handlers=[];break;case 4:if(n===!1&&i>-1){for(;i>=0&&(o=t[i](),o!==!0);i--)if(o instanceof Promise)return this._parseStack.handlerPos=i,o}this._parseStack.handlers=[];break;case 6:if(r=e[this._parseStack.chunkPos],o=this._dcsParser.unhook(r!==24&&r!==26,n),o)return o;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(r=e[this._parseStack.chunkPos],o=this._oscParser.end(r!==24&&r!==26,n),o)return o;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,a=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}}for(let n=a;n<t;++n){switch(r=e[n],i=this._transitions.table[this.currentState<<8|(r<160?r:pu)],i>>4){case 2:for(let i=n+1;;++i)if(i>=t||(r=e[i])<32||r>126&&r<pu||++i>=t||(r=e[i])<32||r>126&&r<pu||++i>=t||(r=e[i])<32||r>126&&r<pu||++i>=t||(r=e[i])<32||r>126&&r<pu){this._printHandler(e,n,i),n=i-1;break}break;case 3:this._executeHandlers[r]?this._executeHandlers[r]():this._executeHandlerFb(r),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:n,code:r,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:let a=this._csiHandlers[this._collect<<8|r],s=a?a.length-1:-1;for(;s>=0&&(o=a[s](this._params),o!==!0);s--)if(o instanceof Promise)return this._preserveStack(3,a,s,i,n),o;s<0&&this._csiHandlerFb(this._collect<<8|r,this._params),this.precedingJoinState=0;break;case 8:do switch(r){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(r-48)}while(++n<t&&(r=e[n])>47&&r<60);n--;break;case 9:this._collect<<=8,this._collect|=r;break;case 10:let c=this._escHandlers[this._collect<<8|r],l=c?c.length-1:-1;for(;l>=0&&(o=c[l](),o!==!0);l--)if(o instanceof Promise)return this._preserveStack(4,c,l,i,n),o;l<0&&this._escHandlerFb(this._collect<<8|r),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|r,this._params);break;case 13:for(let i=n+1;;++i)if(i>=t||(r=e[i])===24||r===26||r===27||r>127&&r<pu){this._dcsParser.put(e,n,i),n=i-1;break}break;case 14:if(o=this._dcsParser.unhook(r!==24&&r!==26),o)return this._preserveStack(6,[],0,i,n),o;r===27&&(i|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break;case 4:this._oscParser.start();break;case 5:for(let i=n+1;;i++)if(i>=t||(r=e[i])<32||r>127&&r<pu){this._oscParser.put(e,n,i),n=i-1;break}break;case 6:if(o=this._oscParser.end(r!==24&&r!==26),o)return this._preserveStack(5,[],0,i,n),o;r===27&&(i|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0}this.currentState=i&15}}},gu=/^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/,_u=/^[\da-f]+$/;function vu(e){if(!e)return;let t=e.toLowerCase();if(t.indexOf(`rgb:`)===0){t=t.slice(4);let e=gu.exec(t);if(e){let t=e[1]?15:e[4]?255:e[7]?4095:65535;return[Math.round(parseInt(e[1]||e[4]||e[7]||e[10],16)/t*255),Math.round(parseInt(e[2]||e[5]||e[8]||e[11],16)/t*255),Math.round(parseInt(e[3]||e[6]||e[9]||e[12],16)/t*255)]}}else if(t.indexOf(`#`)===0&&(t=t.slice(1),_u.exec(t)&&[3,6,9,12].includes(t.length))){let e=t.length/3,n=[0,0,0];for(let r=0;r<3;++r){let i=parseInt(t.slice(e*r,e*r+e),16);n[r]=e===1?i<<4:e===2?i:e===3?i>>4:i>>8}return n}}function yu(e,t){let n=e.toString(16),r=n.length<2?`0`+n:n;switch(t){case 4:return n[0];case 8:return r;case 12:return(r+r).slice(0,3);default:return r+r}}function bu(e,t=16){let[n,r,i]=e;return`rgb:${yu(n,t)}/${yu(r,t)}/${yu(i,t)}`}var xu={"(":0,")":1,"*":2,"+":3,"-":1,".":2},Su=131072,Cu=10;function wu(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var Tu=5e3,Eu=0,Du=class extends U{constructor(e,t,n,r,i,a,o,s,c=new hu){super(),this._bufferService=e,this._charsetService=t,this._coreService=n,this._logService=r,this._optionsService=i,this._oscLinkService=a,this._coreMouseService=o,this._unicodeService=s,this._parser=c,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new Mr,this._utf8Decoder=new Nr,this._windowTitle=``,this._iconName=``,this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=gl.clone(),this._eraseAttrDataInternal=gl.clone(),this._onRequestBell=this._register(new W),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new W),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new W),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new W),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new W),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new W),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new W),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new W),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new W),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new W),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new W),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new W),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new W),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 Ou(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(e=>this._activeBuffer=e.activeBuffer)),this._parser.setCsiHandlerFallback((e,t)=>{this._logService.debug(`Unknown CSI code: `,{identifier:this._parser.identToString(e),params:t.toArray()})}),this._parser.setEscHandlerFallback(e=>{this._logService.debug(`Unknown ESC code: `,{identifier:this._parser.identToString(e)})}),this._parser.setExecuteHandlerFallback(e=>{this._logService.debug(`Unknown EXECUTE code: `,{code:e})}),this._parser.setOscHandlerFallback((e,t,n)=>{this._logService.debug(`Unknown OSC code: `,{identifier:e,action:t,data:n})}),this._parser.setDcsHandlerFallback((e,t,n)=>{t===`HOOK`&&(n=n.toArray()),this._logService.debug(`Unknown DCS code: `,{identifier:this._parser.identToString(e),action:t,payload:n})}),this._parser.setPrintHandler((e,t,n)=>this.print(e,t,n)),this._parser.registerCsiHandler({final:`@`},e=>this.insertChars(e)),this._parser.registerCsiHandler({intermediates:` `,final:`@`},e=>this.scrollLeft(e)),this._parser.registerCsiHandler({final:`A`},e=>this.cursorUp(e)),this._parser.registerCsiHandler({intermediates:` `,final:`A`},e=>this.scrollRight(e)),this._parser.registerCsiHandler({final:`B`},e=>this.cursorDown(e)),this._parser.registerCsiHandler({final:`C`},e=>this.cursorForward(e)),this._parser.registerCsiHandler({final:`D`},e=>this.cursorBackward(e)),this._parser.registerCsiHandler({final:`E`},e=>this.cursorNextLine(e)),this._parser.registerCsiHandler({final:`F`},e=>this.cursorPrecedingLine(e)),this._parser.registerCsiHandler({final:`G`},e=>this.cursorCharAbsolute(e)),this._parser.registerCsiHandler({final:`H`},e=>this.cursorPosition(e)),this._parser.registerCsiHandler({final:`I`},e=>this.cursorForwardTab(e)),this._parser.registerCsiHandler({final:`J`},e=>this.eraseInDisplay(e,!1)),this._parser.registerCsiHandler({prefix:`?`,final:`J`},e=>this.eraseInDisplay(e,!0)),this._parser.registerCsiHandler({final:`K`},e=>this.eraseInLine(e,!1)),this._parser.registerCsiHandler({prefix:`?`,final:`K`},e=>this.eraseInLine(e,!0)),this._parser.registerCsiHandler({final:`L`},e=>this.insertLines(e)),this._parser.registerCsiHandler({final:`M`},e=>this.deleteLines(e)),this._parser.registerCsiHandler({final:`P`},e=>this.deleteChars(e)),this._parser.registerCsiHandler({final:`S`},e=>this.scrollUp(e)),this._parser.registerCsiHandler({final:`T`},e=>this.scrollDown(e)),this._parser.registerCsiHandler({final:`X`},e=>this.eraseChars(e)),this._parser.registerCsiHandler({final:`Z`},e=>this.cursorBackwardTab(e)),this._parser.registerCsiHandler({final:"`"},e=>this.charPosAbsolute(e)),this._parser.registerCsiHandler({final:`a`},e=>this.hPositionRelative(e)),this._parser.registerCsiHandler({final:`b`},e=>this.repeatPrecedingCharacter(e)),this._parser.registerCsiHandler({final:`c`},e=>this.sendDeviceAttributesPrimary(e)),this._parser.registerCsiHandler({prefix:`>`,final:`c`},e=>this.sendDeviceAttributesSecondary(e)),this._parser.registerCsiHandler({final:`d`},e=>this.linePosAbsolute(e)),this._parser.registerCsiHandler({final:`e`},e=>this.vPositionRelative(e)),this._parser.registerCsiHandler({final:`f`},e=>this.hVPosition(e)),this._parser.registerCsiHandler({final:`g`},e=>this.tabClear(e)),this._parser.registerCsiHandler({final:`h`},e=>this.setMode(e)),this._parser.registerCsiHandler({prefix:`?`,final:`h`},e=>this.setModePrivate(e)),this._parser.registerCsiHandler({final:`l`},e=>this.resetMode(e)),this._parser.registerCsiHandler({prefix:`?`,final:`l`},e=>this.resetModePrivate(e)),this._parser.registerCsiHandler({final:`m`},e=>this.charAttributes(e)),this._parser.registerCsiHandler({final:`n`},e=>this.deviceStatus(e)),this._parser.registerCsiHandler({prefix:`?`,final:`n`},e=>this.deviceStatusPrivate(e)),this._parser.registerCsiHandler({intermediates:`!`,final:`p`},e=>this.softReset(e)),this._parser.registerCsiHandler({intermediates:` `,final:`q`},e=>this.setCursorStyle(e)),this._parser.registerCsiHandler({final:`r`},e=>this.setScrollRegion(e)),this._parser.registerCsiHandler({final:`s`},e=>this.saveCursor(e)),this._parser.registerCsiHandler({final:`t`},e=>this.windowOptions(e)),this._parser.registerCsiHandler({final:`u`},e=>this.restoreCursor(e)),this._parser.registerCsiHandler({intermediates:`'`,final:`}`},e=>this.insertColumns(e)),this._parser.registerCsiHandler({intermediates:`'`,final:`~`},e=>this.deleteColumns(e)),this._parser.registerCsiHandler({intermediates:`"`,final:`q`},e=>this.selectProtected(e)),this._parser.registerCsiHandler({intermediates:`$`,final:`p`},e=>this.requestMode(e,!0)),this._parser.registerCsiHandler({prefix:`?`,intermediates:`$`,final:`p`},e=>this.requestMode(e,!1)),this._parser.setExecuteHandler(K.BEL,()=>this.bell()),this._parser.setExecuteHandler(K.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(K.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(K.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(K.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(K.BS,()=>this.backspace()),this._parser.setExecuteHandler(K.HT,()=>this.tab()),this._parser.setExecuteHandler(K.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(K.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(ys.IND,()=>this.index()),this._parser.setExecuteHandler(ys.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(ys.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new su(e=>(this.setTitle(e),this.setIconName(e),!0))),this._parser.registerOscHandler(1,new su(e=>this.setIconName(e))),this._parser.registerOscHandler(2,new su(e=>this.setTitle(e))),this._parser.registerOscHandler(4,new su(e=>this.setOrReportIndexedColor(e))),this._parser.registerOscHandler(8,new su(e=>this.setHyperlink(e))),this._parser.registerOscHandler(10,new su(e=>this.setOrReportFgColor(e))),this._parser.registerOscHandler(11,new su(e=>this.setOrReportBgColor(e))),this._parser.registerOscHandler(12,new su(e=>this.setOrReportCursorColor(e))),this._parser.registerOscHandler(104,new su(e=>this.restoreIndexedColor(e))),this._parser.registerOscHandler(110,new su(e=>this.restoreFgColor(e))),this._parser.registerOscHandler(111,new su(e=>this.restoreBgColor(e))),this._parser.registerOscHandler(112,new su(e=>this.restoreCursorColor(e))),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 e in Dl)this._parser.registerEscHandler({intermediates:`(`,final:e},()=>this.selectCharset(`(`+e)),this._parser.registerEscHandler({intermediates:`)`,final:e},()=>this.selectCharset(`)`+e)),this._parser.registerEscHandler({intermediates:`*`,final:e},()=>this.selectCharset(`*`+e)),this._parser.registerEscHandler({intermediates:`+`,final:e},()=>this.selectCharset(`+`+e)),this._parser.registerEscHandler({intermediates:`-`,final:e},()=>this.selectCharset(`-`+e)),this._parser.registerEscHandler({intermediates:`.`,final:e},()=>this.selectCharset(`.`+e)),this._parser.registerEscHandler({intermediates:`/`,final:e},()=>this.selectCharset(`/`+e));this._parser.registerEscHandler({intermediates:`#`,final:`8`},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(e=>(this._logService.error(`Parsing error: `,e),e)),this._parser.registerDcsHandler({intermediates:`$`,final:`q`},new du((e,t)=>this.requestStatusString(e,t)))}getAttrData(){return this._curAttrData}_preserveStack(e,t,n,r){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=n,this._parseStack.position=r}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((e,t)=>setTimeout(()=>t(`#SLOW_TIMEOUT`),Tu))]).catch(e=>{if(e!==`#SLOW_TIMEOUT`)throw e;console.warn(`async parser handler taking longer than ${Tu} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let n,r=this._activeBuffer.x,i=this._activeBuffer.y,a=0,o=this._parseStack.paused;if(o){if(n=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(n),n;r=this._parseStack.cursorStartX,i=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>Su&&(a=this._parseStack.position+Su)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e==`string`?` "${e}"`:` "${Array.prototype.map.call(e,e=>String.fromCharCode(e)).join(``)}"`}`),this._logService.logLevel===0&&this._logService.trace(`parsing data (codes)`,typeof e==`string`?e.split(``).map(e=>e.charCodeAt(0)):e),this._parseBuffer.length<e.length&&this._parseBuffer.length<Su&&(this._parseBuffer=new Uint32Array(Math.min(e.length,Su))),o||this._dirtyRowTracker.clearRange(),e.length>Su)for(let t=a;t<e.length;t+=Su){let a=t+Su<e.length?t+Su:e.length,o=typeof e==`string`?this._stringDecoder.decode(e.substring(t,a),this._parseBuffer):this._utf8Decoder.decode(e.subarray(t,a),this._parseBuffer);if(n=this._parser.parse(this._parseBuffer,o))return this._preserveStack(r,i,o,t),this._logSlowResolvingAsync(n),n}else if(!o){let t=typeof e==`string`?this._stringDecoder.decode(e,this._parseBuffer):this._utf8Decoder.decode(e,this._parseBuffer);if(n=this._parser.parse(this._parseBuffer,t))return this._preserveStack(r,i,t,0),this._logSlowResolvingAsync(n),n}(this._activeBuffer.x!==r||this._activeBuffer.y!==i)&&this._onCursorMove.fire();let s=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),c=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);c<this._bufferService.rows&&this._onRequestRefreshRows.fire({start:Math.min(c,this._bufferService.rows-1),end:Math.min(s,this._bufferService.rows-1)})}print(e,t,n){let r,i,a=this._charsetService.charset,o=this._optionsService.rawOptions.screenReaderMode,s=this._bufferService.cols,c=this._coreService.decPrivateModes.wraparound,l=this._coreService.modes.insertMode,u=this._curAttrData,d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&n-t>0&&d.getWidth(this._activeBuffer.x-1)===2&&d.setCellFromCodepoint(this._activeBuffer.x-1,0,1,u);let f=this._parser.precedingJoinState;for(let p=t;p<n;++p){if(r=e[p],r<127&&a){let e=a[String.fromCharCode(r)];e&&(r=e.charCodeAt(0))}let t=this._unicodeService.charProperties(r,f);i=$l.extractWidth(t);let n=$l.extractShouldJoin(t),m=n?$l.extractWidth(f):0;if(f=t,o&&this._onA11yChar.fire(Ar(r)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+i-m>s){if(c){let e=d,t=this._activeBuffer.x-m;for(this._activeBuffer.x=m,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),d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),m>0&&d instanceof yl&&d.copyCellsFrom(e,t,0,m,!1);t<s;)e.setCellFromCodepoint(t++,0,1,u)}else if(this._activeBuffer.x=s-1,i===2)continue}if(n&&this._activeBuffer.x){let e=d.getWidth(this._activeBuffer.x-1)?1:2;d.addCodepointToCell(this._activeBuffer.x-e,r,i);for(let e=i-m;--e>=0;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,u)}else if(l&&(d.insertCells(this._activeBuffer.x,i-m,this._activeBuffer.getNullCell(u)),d.getWidth(s-1)===2&&d.setCellFromCodepoint(s-1,0,1,u)),d.setCellFromCodepoint(this._activeBuffer.x++,r,i,u),i>0)for(;--i;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,u)}this._parser.precedingJoinState=f,this._activeBuffer.x<s&&n-t>0&&d.getWidth(this._activeBuffer.x)===0&&!d.hasContent(this._activeBuffer.x)&&d.setCellFromCodepoint(this._activeBuffer.x,0,1,u),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final===`t`&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,e=>!wu(e.params[0],this._optionsService.rawOptions.windowOptions)||t(e)):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new du(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new su(t))}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 e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);e.hasWidth(this._activeBuffer.x)&&!e.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,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(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return t===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return t===1&&(this._curAttrData.bg|=536870912),(t===2||t===0)&&(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,n,r=!1,i=!1){let a=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);a.replaceCells(t,n,this._activeBuffer.getNullCell(this._eraseAttrData()),i),r&&(a.isWrapped=!1)}_resetBufferLine(e,t=!1){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n&&(n.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),n.isWrapped=!1)}eraseInDisplay(e,t=!1){this._restrictCursor(this._bufferService.cols);let n;switch(e.params[0]){case 0:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);n<this._bufferService.rows;n++)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(n);break;case 1:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n,0,this._activeBuffer.x+1,!0,t),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(n+1).isWrapped=!1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(n=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,n-1);n--&&!this._activeBuffer.lines.get(this._activeBuffer.ybase+n)?.getTrimmedLength(););for(;n>=0;n--)this._bufferService.scroll(this._eraseAttrData())}else{for(n=this._bufferService.rows,this._dirtyRowTracker.markDirty(n-1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let e=this._activeBuffer.lines.length-this._bufferService.rows;e>0&&(this._activeBuffer.lines.trimStart(e),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-e,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-e,0),this._onScroll.fire(0))}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=this._activeBuffer.ybase+this._activeBuffer.y,r=this._bufferService.rows-1-this._activeBuffer.scrollBottom,i=this._bufferService.rows-1+this._activeBuffer.ybase-r+1;for(;t--;)this._activeBuffer.lines.splice(i-1,1),this._activeBuffer.lines.splice(n,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=this._activeBuffer.ybase+this._activeBuffer.y,r;for(r=this._bufferService.rows-1-this._activeBuffer.scrollBottom,r=this._bufferService.rows-1+this._activeBuffer.ybase-r;t--;)this._activeBuffer.lines.splice(n,1),this._activeBuffer.lines.splice(r,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.insertCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.deleteCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollDown(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,0,this._activeBuffer.getBlankLine(gl));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.deleteCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.insertCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.insertCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.deleteCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(e.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(e){let t=this._parser.precedingJoinState;if(!t)return!0;let n=e.params[0]||1,r=$l.extractWidth(t),i=this._activeBuffer.x-r,a=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(i),o=new Uint32Array(a.length*n),s=0;for(let e=0;e<a.length;){let t=a.codePointAt(e)||0;o[s++]=t,e+=t>65535?2:1}let c=s;for(let e=1;e<n;++e)o.copyWithin(c,0,s),c+=s;return this.print(o,0,c),!0}sendDeviceAttributesPrimary(e){return e.params[0]>0||(this._is(`xterm`)||this._is(`rxvt-unicode`)||this._is(`screen`)?this._coreService.triggerDataEvent(K.ESC+`[?1;2c`):this._is(`linux`)&&this._coreService.triggerDataEvent(K.ESC+`[?6c`)),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is(`xterm`)?this._coreService.triggerDataEvent(K.ESC+`[>0;276;0c`):this._is(`rxvt-unicode`)?this._coreService.triggerDataEvent(K.ESC+`[>85;95;0c`):this._is(`linux`)?this._coreService.triggerDataEvent(e.params[0]+`c`):this._is(`screen`)&&this._coreService.triggerDataEvent(K.ESC+`[>83;40003;0c`)),!0}_is(e){return(this._optionsService.rawOptions.termName+``).indexOf(e)===0}setMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0}return!0}setModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,Ol),this._charsetService.setgCharset(1,Ol),this._charsetService.setgCharset(2,Ol),this._charsetService.setgCharset(3,Ol);break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(132,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!0,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!0;break;case 12:this._optionsService.options.cursorBlink=!0;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!0;break;case 66:this._logService.debug(`Serial port requested application keypad.`),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire();break;case 9:this._coreMouseService.activeProtocol=`X10`;break;case 1e3:this._coreMouseService.activeProtocol=`VT200`;break;case 1002:this._coreMouseService.activeProtocol=`DRAG`;break;case 1003:this._coreMouseService.activeProtocol=`ANY`;break;case 1004:this._coreService.decPrivateModes.sendFocus=!0,this._onRequestSendFocus.fire();break;case 1005:this._logService.debug(`DECSET 1005 not supported (see #2507)`);break;case 1006:this._coreMouseService.activeEncoding=`SGR`;break;case 1015:this._logService.debug(`DECSET 1015 not supported (see #2507)`);break;case 1016:this._coreMouseService.activeEncoding=`SGR_PIXELS`;break;case 25:this._coreService.isCursorHidden=!1;break;case 1048:this.saveCursor();break;case 1049:this.saveCursor();case 47:case 1047:this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!0;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!0}return!0}resetMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1}return!0}resetModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!1;break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(80,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!1,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!1;break;case 12:this._optionsService.options.cursorBlink=!1;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!1;break;case 66:this._logService.debug(`Switching back to normal keypad.`),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire();break;case 9:case 1e3:case 1002:case 1003:this._coreMouseService.activeProtocol=`NONE`;break;case 1004:this._coreService.decPrivateModes.sendFocus=!1;break;case 1005:this._logService.debug(`DECRST 1005 not supported (see #2507)`);break;case 1006:this._coreMouseService.activeEncoding=`DEFAULT`;break;case 1015:this._logService.debug(`DECRST 1015 not supported (see #2507)`);break;case 1016:this._coreMouseService.activeEncoding=`DEFAULT`;break;case 25:this._coreService.isCursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),e.params[t]===1049&&this.restoreCursor(),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!1;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!1,this._onRequestRefreshRows.fire(void 0)}return!0}requestMode(e,t){let n;(e=>(e[e.NOT_RECOGNIZED=0]=`NOT_RECOGNIZED`,e[e.SET=1]=`SET`,e[e.RESET=2]=`RESET`,e[e.PERMANENTLY_SET=3]=`PERMANENTLY_SET`,e[e.PERMANENTLY_RESET=4]=`PERMANENTLY_RESET`))(n||={});let r=this._coreService.decPrivateModes,{activeProtocol:i,activeEncoding:a}=this._coreMouseService,o=this._coreService,{buffers:s,cols:c}=this._bufferService,{active:l,alt:u}=s,d=this._optionsService.rawOptions,f=(e,n)=>(o.triggerDataEvent(`${K.ESC}[${t?``:`?`}${e};${n}$y`),!0),p=e=>e?1:2,m=e.params[0];return t?m===2?f(m,4):m===4?f(m,p(o.modes.insertMode)):m===12?f(m,3):m===20?f(m,p(d.convertEol)):f(m,0):m===1?f(m,p(r.applicationCursorKeys)):m===3?f(m,d.windowOptions.setWinLines?c===80?2:+(c===132):0):m===6?f(m,p(r.origin)):m===7?f(m,p(r.wraparound)):m===8?f(m,3):m===9?f(m,p(i===`X10`)):m===12?f(m,p(d.cursorBlink)):m===25?f(m,p(!o.isCursorHidden)):m===45?f(m,p(r.reverseWraparound)):m===66?f(m,p(r.applicationKeypad)):m===67?f(m,4):m===1e3?f(m,p(i===`VT200`)):m===1002?f(m,p(i===`DRAG`)):m===1003?f(m,p(i===`ANY`)):m===1004?f(m,p(r.sendFocus)):m===1005?f(m,4):m===1006?f(m,p(a===`SGR`)):m===1015?f(m,4):m===1016?f(m,p(a===`SGR_PIXELS`)):m===1048?f(m,1):m===47||m===1047||m===1049?f(m,p(l===u)):m===2004?f(m,p(r.bracketedPasteMode)):m===2026?f(m,p(r.synchronizedOutput)):f(m,0)}_updateAttrColor(e,t,n,r,i){return t===2?(e|=50331648,e&=-16777216,e|=Ir.fromColorRGB([n,r,i])):t===5&&(e&=-50331904,e|=33554432|n&255),e}_extractColor(e,t,n){let r=[0,0,-1,0,0,0],i=0,a=0;do{if(r[a+i]=e.params[t+a],e.hasSubParams(t+a)){let n=e.getSubParams(t+a),o=0;do r[1]===5&&(i=1),r[a+o+1+i]=n[o];while(++o<n.length&&o+a+1+i<r.length);break}if(r[1]===5&&a+i>=2||r[1]===2&&a+i>=5)break;r[1]&&(i=1)}while(++a+t<e.length&&a+i<r.length);for(let e=2;e<r.length;++e)r[e]===-1&&(r[e]=0);switch(r[0]){case 38:n.fg=this._updateAttrColor(n.fg,r[1],r[3],r[4],r[5]);break;case 48:n.bg=this._updateAttrColor(n.bg,r[1],r[3],r[4],r[5]);break;case 58:n.extended=n.extended.clone(),n.extended.underlineColor=this._updateAttrColor(n.extended.underlineColor,r[1],r[3],r[4],r[5])}return a}_processUnderline(e,t){t.extended=t.extended.clone(),(!~e||e>5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=gl.fg,e.bg=gl.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t=e.length,n,r=this._curAttrData;for(let i=0;i<t;i++)n=e.params[i],n>=30&&n<=37?(r.fg&=-50331904,r.fg|=16777216|n-30):n>=40&&n<=47?(r.bg&=-50331904,r.bg|=16777216|n-40):n>=90&&n<=97?(r.fg&=-50331904,r.fg|=n-90|16777224):n>=100&&n<=107?(r.bg&=-50331904,r.bg|=n-100|16777224):n===0?this._processSGR0(r):n===1?r.fg|=134217728:n===3?r.bg|=67108864:n===4?(r.fg|=268435456,this._processUnderline(e.hasSubParams(i)?e.getSubParams(i)[0]:1,r)):n===5?r.fg|=536870912:n===7?r.fg|=67108864:n===8?r.fg|=1073741824:n===9?r.fg|=2147483648:n===2?r.bg|=134217728:n===21?this._processUnderline(2,r):n===22?(r.fg&=-134217729,r.bg&=-134217729):n===23?r.bg&=-67108865:n===24?(r.fg&=-268435457,this._processUnderline(0,r)):n===25?r.fg&=-536870913:n===27?r.fg&=-67108865:n===28?r.fg&=-1073741825:n===29?r.fg&=2147483647:n===39?(r.fg&=-67108864,r.fg|=gl.fg&16777215):n===49?(r.bg&=-67108864,r.bg|=gl.bg&16777215):n===38||n===48||n===58?i+=this._extractColor(e,i,r):n===53?r.bg|=1073741824:n===55?r.bg&=-1073741825:n===59?(r.extended=r.extended.clone(),r.extended.underlineColor=-1,r.updateExtended()):n===100?(r.fg&=-67108864,r.fg|=gl.fg&16777215,r.bg&=-67108864,r.bg|=gl.bg&16777215):this._logService.debug(`Unknown SGR attribute: %d.`,n);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${K.ESC}[0n`);break;case 6:let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${K.ESC}[${e};${t}R`)}return!0}deviceStatusPrivate(e){if(e.params[0]===6){let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${K.ESC}[?${e};${t}R`)}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=gl.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=e.length===0?1:e.params[0];if(t===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(t){case 1:case 2:this._coreService.decPrivateModes.cursorStyle=`block`;break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle=`underline`;break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle=`bar`}let e=t%2==1;this._coreService.decPrivateModes.cursorBlink=e}return!0}setScrollRegion(e){let t=e.params[0]||1,n;return(e.length<2||(n=e.params[1])>this._bufferService.rows||n===0)&&(n=this._bufferService.rows),n>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=n-1,this._setCursor(0,0)),!0}windowOptions(e){if(!wu(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:t!==2&&this._onRequestWindowsOptionsReport.fire(0);break;case 16:this._onRequestWindowsOptionsReport.fire(1);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${K.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>Cu&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>Cu&&this._iconNameStack.shift());break;case 23:(t===0||t===2)&&this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),(t===0||t===1)&&this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],n=e.split(`;`);for(;n.length>1;){let e=n.shift(),r=n.shift();if(/^\d+$/.exec(e)){let n=parseInt(e);if(ku(n)){if(r===`?`)t.push({type:0,index:n});else{let e=vu(r);e&&t.push({type:1,index:n,color:e})}}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(`;`);if(t===-1)return!0;let n=e.slice(0,t).trim(),r=e.slice(t+1);return r?this._createHyperlink(n,r):!n.trim()&&this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let n=e.split(`:`),r,i=n.findIndex(e=>e.startsWith(`id=`));return i!==-1&&(r=n[i].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:r,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let n=e.split(`;`);for(let e=0;e<n.length&&!(t>=this._specialColors.length);++e,++t)if(n[e]===`?`)this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let r=vu(n[e]);r&&this._onColor.fire([{type:1,index:this._specialColors[t],color:r}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],n=e.split(`;`);for(let e=0;e<n.length;++e)if(/^\d+$/.exec(n[e])){let r=parseInt(n[e]);ku(r)&&t.push({type:2,index:r})}return t.length&&this._onColor.fire(t),!0}restoreFgColor(e){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(e){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(e){return this._onColor.fire([{type:2,index:258}]),!0}nextLine(){return this._activeBuffer.x=0,this.index(),!0}keypadApplicationMode(){return this._logService.debug(`Serial port requested application keypad.`),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire(),!0}keypadNumericMode(){return this._logService.debug(`Switching back to normal keypad.`),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire(),!0}selectDefaultCharset(){return this._charsetService.setgLevel(0),this._charsetService.setgCharset(0,Ol),!0}selectCharset(e){return e.length===2?(e[0]===`/`||this._charsetService.setgCharset(xu[e[0]],Dl[e[1]]||Ol),!0):(this.selectDefaultCharset(),!0)}index(){return this._restrictCursor(),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._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=gl.clone(),this._eraseAttrDataInternal=gl.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=this._curAttrData.bg&67108863,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new Rr;e.content=4194373,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t<this._bufferService.rows;++t){let n=this._activeBuffer.ybase+this._activeBuffer.y+t,r=this._activeBuffer.lines.get(n);r&&(r.fill(e),r.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(e,t){let n=e=>(this._coreService.triggerDataEvent(`${K.ESC}${e}${K.ESC}\\`),!0),r=this._bufferService.buffer,i=this._optionsService.rawOptions;return n(e===`"q`?`P1$r${+!!this._curAttrData.isProtected()}"q`:e===`"p`?`P1$r61;1"p`:e===`r`?`P1$r${r.scrollTop+1};${r.scrollBottom+1}r`:e===`m`?`P1$r0m`:e===` q`?`P1$r${{block:2,underline:4,bar:6}[i.cursorStyle]-+!!i.cursorBlink} q`:`P0$r`)}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},Ou=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){e<this.start?this.start=e:e>this.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(Eu=e,e=t,t=Eu),e<this.start&&(this.start=e),t>this.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};Ou=z([B(0,Gr)],Ou);function ku(e){return 0<=e&&e<256}var Au=5e7,ju=12,Mu=50,Nu=class extends U{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new W),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(t!==void 0&&this._syncCalls>t){this._syncCalls=0;return}if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;this._isSyncWriting=!0;let n;for(;n=this._writeBuffer.shift();){this._action(n);let e=this._callbacks.shift();e&&e()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>Au)throw Error(`write data discarded, use flow control to avoid losing data`);if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput){this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),this._innerWrite();return}setTimeout(()=>this._innerWrite())}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){let n=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let e=this._writeBuffer[this._bufferOffset],r=this._action(e,t);if(r){r.catch(e=>(queueMicrotask(()=>{throw e}),Promise.resolve(!1))).then(e=>performance.now()-n>=ju?setTimeout(()=>this._innerWrite(0,e)):this._innerWrite(n,e));return}let i=this._callbacks[this._bufferOffset];if(i&&i(),this._bufferOffset++,this._pendingData-=e.length,performance.now()-n>=ju)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>Mu&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}},Pu=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){let t=this._bufferService.buffer;if(e.id===void 0){let n=t.addMarker(t.ybase+t.y),r={data:e,id:this._nextId++,lines:[n]};return n.onDispose(()=>this._removeMarkerFromLink(r,n)),this._dataByLinkId.set(r.id,r),r.id}let n=e,r=this._getEntryIdKey(n),i=this._entriesWithId.get(r);if(i)return this.addLineToLink(i.id,t.ybase+t.y),i.id;let a=t.addMarker(t.ybase+t.y),o={id:this._nextId++,key:this._getEntryIdKey(n),data:n,lines:[a]};return a.onDispose(()=>this._removeMarkerFromLink(o,a)),this._entriesWithId.set(o.key,o),this._dataByLinkId.set(o.id,o),o.id}addLineToLink(e,t){let n=this._dataByLinkId.get(e);if(n&&n.lines.every(e=>e.line!==t)){let e=this._bufferService.buffer.addMarker(t);n.lines.push(e),e.onDispose(()=>this._removeMarkerFromLink(n,e))}}getLinkData(e){return this._dataByLinkId.get(e)?.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let n=e.lines.indexOf(t);n!==-1&&(e.lines.splice(n,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};Pu=z([B(0,Gr)],Pu);var Fu=!1,Iu=class extends U{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new Ni),this._onBinary=this._register(new W),this.onBinary=this._onBinary.event,this._onData=this._register(new W),this.onData=this._onData.event,this._onLineFeed=this._register(new W),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new W),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new W),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new W),this._instantiationService=new ul,this.optionsService=this._register(new Ll(e)),this._instantiationService.setService(Zr,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(Pl)),this._instantiationService.setService(Gr,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(pl)),this._instantiationService.setService(Xr,this._logService),this.coreService=this._register(this._instantiationService.createInstance(Hl)),this._instantiationService.setService(qr,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(ql)),this._instantiationService.setService(Kr,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance($l)),this._instantiationService.setService($r,this.unicodeService),this._charsetService=this._instantiationService.createInstance(eu),this._instantiationService.setService(Jr,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(Pu),this._instantiationService.setService(Qr,this._oscLinkService),this._inputHandler=this._register(new Du(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(Bi.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(Bi.forward(this._bufferService.onResize,this._onResize)),this._register(Bi.forward(this.coreService.onData,this._onData)),this._register(Bi.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom(!0))),this._register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this._register(this.optionsService.onMultipleOptionChange([`windowsMode`,`windowsPty`],()=>this._handleWindowsPtyOptionChange())),this._register(this._bufferService.onScroll(()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this._register(new Nu((e,t)=>this._inputHandler.parse(e,t))),this._register(Bi.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new W),this._onScroll.event(e=>{this._onScrollApi?.fire(e.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(e){for(let t in e)this.optionsService.options[t]=e[t]}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=3&&!Fu&&(this._logService.warn(`writeSync is unreliable and will be removed soon.`),Fu=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,Ml),t=Math.max(t,Nl),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t){this._bufferService.scrollLines(e,t)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,t=this.optionsService.rawOptions.windowsPty;t&&t.buildNumber!==void 0&&t.buildNumber!==void 0?e=t.backend===`conpty`&&t.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(tu.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:`H`},()=>(tu(this._bufferService),!1))),this._windowsWrappingHeuristics.value=H(()=>{for(let t of e)t.dispose()})}}},Lu={48:[`0`,`)`],49:[`1`,`!`],50:[`2`,`@`],51:[`3`,`#`],52:[`4`,`$`],53:[`5`,`%`],54:[`6`,`^`],55:[`7`,`&`],56:[`8`,`*`],57:[`9`,`(`],186:[`;`,`:`],187:[`=`,`+`],188:[`,`,`<`],189:[`-`,`_`],190:[`.`,`>`],191:[`/`,`?`],192:["`",`~`],219:[`[`,`{`],220:[`\\`,`|`],221:[`]`,`}`],222:[`'`,`"`]};function Ru(e,t,n,r){let i={type:0,cancel:!1,key:void 0},a=+!!e.shiftKey|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:e.key===`UIKeyInputUpArrow`?i.key=t?K.ESC+`OA`:K.ESC+`[A`:e.key===`UIKeyInputLeftArrow`?i.key=t?K.ESC+`OD`:K.ESC+`[D`:e.key===`UIKeyInputRightArrow`?i.key=t?K.ESC+`OC`:K.ESC+`[C`:e.key===`UIKeyInputDownArrow`&&(i.key=t?K.ESC+`OB`:K.ESC+`[B`);break;case 8:i.key=e.ctrlKey?`\b`:K.DEL,e.altKey&&(i.key=K.ESC+i.key);break;case 9:if(e.shiftKey){i.key=K.ESC+`[Z`;break}i.key=K.HT,i.cancel=!0;break;case 13:i.key=e.altKey?K.ESC+K.CR:K.CR,i.cancel=!0;break;case 27:i.key=K.ESC,e.altKey&&(i.key=K.ESC+K.ESC),i.cancel=!0;break;case 37:if(e.metaKey)break;i.key=a?K.ESC+`[1;`+(a+1)+`D`:t?K.ESC+`OD`:K.ESC+`[D`;break;case 39:if(e.metaKey)break;i.key=a?K.ESC+`[1;`+(a+1)+`C`:t?K.ESC+`OC`:K.ESC+`[C`;break;case 38:if(e.metaKey)break;i.key=a?K.ESC+`[1;`+(a+1)+`A`:t?K.ESC+`OA`:K.ESC+`[A`;break;case 40:if(e.metaKey)break;i.key=a?K.ESC+`[1;`+(a+1)+`B`:t?K.ESC+`OB`:K.ESC+`[B`;break;case 45:!e.shiftKey&&!e.ctrlKey&&(i.key=K.ESC+`[2~`);break;case 46:i.key=a?K.ESC+`[3;`+(a+1)+`~`:K.ESC+`[3~`;break;case 36:i.key=a?K.ESC+`[1;`+(a+1)+`H`:t?K.ESC+`OH`:K.ESC+`[H`;break;case 35:i.key=a?K.ESC+`[1;`+(a+1)+`F`:t?K.ESC+`OF`:K.ESC+`[F`;break;case 33:e.shiftKey?i.type=2:i.key=e.ctrlKey?K.ESC+`[5;`+(a+1)+`~`:K.ESC+`[5~`;break;case 34:e.shiftKey?i.type=3:i.key=e.ctrlKey?K.ESC+`[6;`+(a+1)+`~`:K.ESC+`[6~`;break;case 112:i.key=a?K.ESC+`[1;`+(a+1)+`P`:K.ESC+`OP`;break;case 113:i.key=a?K.ESC+`[1;`+(a+1)+`Q`:K.ESC+`OQ`;break;case 114:i.key=a?K.ESC+`[1;`+(a+1)+`R`:K.ESC+`OR`;break;case 115:i.key=a?K.ESC+`[1;`+(a+1)+`S`:K.ESC+`OS`;break;case 116:i.key=a?K.ESC+`[15;`+(a+1)+`~`:K.ESC+`[15~`;break;case 117:i.key=a?K.ESC+`[17;`+(a+1)+`~`:K.ESC+`[17~`;break;case 118:i.key=a?K.ESC+`[18;`+(a+1)+`~`:K.ESC+`[18~`;break;case 119:i.key=a?K.ESC+`[19;`+(a+1)+`~`:K.ESC+`[19~`;break;case 120:i.key=a?K.ESC+`[20;`+(a+1)+`~`:K.ESC+`[20~`;break;case 121:i.key=a?K.ESC+`[21;`+(a+1)+`~`:K.ESC+`[21~`;break;case 122:i.key=a?K.ESC+`[23;`+(a+1)+`~`:K.ESC+`[23~`;break;case 123:i.key=a?K.ESC+`[24;`+(a+1)+`~`:K.ESC+`[24~`;break;default:if(e.ctrlKey&&!e.shiftKey&&!e.altKey&&!e.metaKey)e.keyCode>=65&&e.keyCode<=90?i.key=String.fromCharCode(e.keyCode-64):e.keyCode===32?i.key=K.NUL:e.keyCode>=51&&e.keyCode<=55?i.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?i.key=K.DEL:e.keyCode===219?i.key=K.ESC:e.keyCode===220?i.key=K.FS:e.keyCode===221&&(i.key=K.GS);else if((!n||r)&&e.altKey&&!e.metaKey){let t=Lu[e.keyCode]?.[+!!e.shiftKey];if(t)i.key=K.ESC+t;else if(e.keyCode>=65&&e.keyCode<=90){let t=e.ctrlKey?e.keyCode-64:e.keyCode+32,n=String.fromCharCode(t);e.shiftKey&&(n=n.toUpperCase()),i.key=K.ESC+n}else if(e.keyCode===32)i.key=K.ESC+(e.ctrlKey?K.NUL:` `);else if(e.key===`Dead`&&e.code.startsWith(`Key`)){let t=e.code.slice(3,4);e.shiftKey||(t=t.toLowerCase()),i.key=K.ESC+t,i.cancel=!0}}else n&&!e.altKey&&!e.ctrlKey&&!e.shiftKey&&e.metaKey?e.keyCode===65&&(i.type=1):e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&e.key.length===1?i.key=e.key:e.key&&e.ctrlKey&&(e.key===`_`&&(i.key=K.US),e.key===`@`&&(i.key=K.NUL))}return i}var zu=0,Bu=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new Oc,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new Oc,this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(e){this._flushCleanupDeleted(),this._insertedValues.length===0&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(e)}_flushInserted(){let e=this._insertedValues.sort((e,t)=>this._getKey(e)-this._getKey(t)),t=0,n=0,r=Array(this._array.length+this._insertedValues.length);for(let i=0;i<r.length;i++)n>=this._array.length||this._getKey(e[t])<=this._getKey(this._array[n])?(r[i]=e[t],t++):r[i]=this._array[n++];this._array=r,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(e){if(this._flushCleanupInserted(),this._array.length===0)return!1;let t=this._getKey(e);if(t===void 0||(zu=this._search(t),zu===-1)||this._getKey(this._array[zu])!==t)return!1;do if(this._array[zu]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(zu),!0;while(++zu<this._array.length&&this._getKey(this._array[zu])===t);return!1}_flushDeleted(){this._isFlushingDeleted=!0;let e=this._deletedIndices.sort((e,t)=>e-t),t=0,n=Array(this._array.length-e.length),r=0;for(let i=0;i<this._array.length;i++)e[t]===i?t++:n[r++]=this._array[i];this._array=n,this._deletedIndices.length=0,this._isFlushingDeleted=!1}_flushCleanupDeleted(){!this._isFlushingDeleted&&this._deletedIndices.length>0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(zu=this._search(e),!(zu<0||zu>=this._array.length)&&this._getKey(this._array[zu])===e))do yield this._array[zu];while(++zu<this._array.length&&this._getKey(this._array[zu])===e)}forEachByKey(e,t){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(zu=this._search(e),!(zu<0||zu>=this._array.length)&&this._getKey(this._array[zu])===e))do t(this._array[zu]);while(++zu<this._array.length&&this._getKey(this._array[zu])===e)}values(){return this._flushCleanupInserted(),this._flushCleanupDeleted(),[...this._array].values()}_search(e){let t=0,n=this._array.length-1;for(;n>=t;){let r=t+n>>1,i=this._getKey(this._array[r]);if(i>e)n=r-1;else if(i<e)t=r+1;else{for(;r>0&&this._getKey(this._array[r-1])===e;)r--;return r}}return t}},Vu=0,Hu=0,Uu=class extends U{constructor(){super(),this._decorations=new Bu(e=>e?.marker.line),this._onDecorationRegistered=this._register(new W),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new W),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(H(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new Wu(e);if(t){let e=t.marker.onDispose(()=>t.dispose()),n=t.onDispose(()=>{n.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),e.dispose())});this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,n){let r=0,i=0;for(let a of this._decorations.getKeyIterator(t))r=a.options.x??0,i=r+(a.options.width??1),e>=r&&e<i&&(!n||(a.options.layer??`bottom`)===n)&&(yield a)}forEachDecorationAtCell(e,t,n,r){this._decorations.forEachByKey(t,t=>{Vu=t.options.x??0,Hu=Vu+(t.options.width??1),e>=Vu&&e<Hu&&(!n||(t.options.layer??`bottom`)===n)&&r(t)})}},Wu=class extends Mi{constructor(e){super(),this.options=e,this.onRenderEmitter=this.add(new W),this.onRender=this.onRenderEmitter.event,this._onDispose=this.add(new W),this.onDispose=this._onDispose.event,this._cachedBg=null,this._cachedFg=null,this.marker=e.marker,this.options.overviewRulerOptions&&!this.options.overviewRulerOptions.position&&(this.options.overviewRulerOptions.position=`full`)}get backgroundColorRGB(){return this._cachedBg===null&&(this._cachedBg=this.options.backgroundColor?ks.toColor(this.options.backgroundColor):void 0),this._cachedBg}get foregroundColorRGB(){return this._cachedFg===null&&(this._cachedFg=this.options.foregroundColor?ks.toColor(this.options.foregroundColor):void 0),this._cachedFg}dispose(){this._onDispose.fire(),super.dispose()}},Gu=1e3,Ku=class{constructor(e,t=Gu){this._renderCallback=e,this._debounceThresholdMS=t,this._lastRefreshMs=0,this._additionalRefreshRequested=!1}dispose(){this._refreshTimeoutID&&clearTimeout(this._refreshTimeoutID)}refresh(e,t,n){this._rowCount=n,e=e===void 0?0:e,t=t===void 0?this._rowCount-1:t,this._rowStart=this._rowStart===void 0?e:Math.min(this._rowStart,e),this._rowEnd=this._rowEnd===void 0?t:Math.max(this._rowEnd,t);let r=performance.now();if(r-this._lastRefreshMs>=this._debounceThresholdMS)this._lastRefreshMs=r,this._innerRefresh();else if(!this._additionalRefreshRequested){let e=r-this._lastRefreshMs,t=this._debounceThresholdMS-e;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},t)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t)}},qu=20,Ju=class extends U{constructor(e,t,n,r){super(),this._terminal=e,this._coreBrowserService=n,this._renderService=r,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce=``;let i=this._coreBrowserService.mainDocument;this._accessibilityContainer=i.createElement(`div`),this._accessibilityContainer.classList.add(`xterm-accessibility`),this._rowContainer=i.createElement(`div`),this._rowContainer.setAttribute(`role`,`list`),this._rowContainer.classList.add(`xterm-accessibility-tree`),this._rowElements=[];for(let e=0;e<this._terminal.rows;e++)this._rowElements[e]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[e]);if(this._topBoundaryFocusListener=e=>this._handleBoundaryFocus(e,0),this._bottomBoundaryFocusListener=e=>this._handleBoundaryFocus(e,1),this._rowElements[0].addEventListener(`focus`,this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=i.createElement(`div`),this._liveRegion.classList.add(`live-region`),this._liveRegion.setAttribute(`aria-live`,`assertive`),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new Ku(this._renderRows.bind(this))),!this._terminal.element)throw Error(`Cannot enable accessibility before Terminal.open`);this._terminal.element.insertAdjacentElement(`afterbegin`,this._accessibilityContainer),this._register(this._terminal.onResize(e=>this._handleResize(e.rows))),this._register(this._terminal.onRender(e=>this._refreshRows(e.start,e.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(e=>this._handleChar(e))),this._register(this._terminal.onLineFeed(()=>this._handleChar(`
19
+ `))),this._register(this._terminal.onA11yTab(e=>this._handleTab(e))),this._register(this._terminal.onKey(e=>this._handleKey(e.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(G(i,`selectionchange`,()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(H(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t<e;t++)this._handleChar(` `)}_handleChar(e){this._liveRegionLineCount<qu+1&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===`
20
+ `&&(this._liveRegionLineCount++,this._liveRegionLineCount===qu+1&&(this._liveRegion.textContent+=Cr.get())))}_clearLiveRegion(){this._liveRegion.textContent=``,this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),/\p{Control}/u.test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let n=this._terminal.buffer,r=n.lines.length.toString();for(let i=e;i<=t;i++){let e=n.lines.get(n.ydisp+i),t=[],a=e?.translateToString(!0,void 0,void 0,t)||``,o=(n.ydisp+i+1).toString(),s=this._rowElements[i];s&&(a.length===0?(s.textContent=`\xA0`,this._rowColumns.set(s,[0,1])):(s.textContent=a,this._rowColumns.set(s,t)),s.setAttribute(`aria-posinset`,o),s.setAttribute(`aria-setsize`,r),this._alignRowWidth(s))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce=``)}_handleBoundaryFocus(e,t){let n=e.target,r=this._rowElements[t===0?1:this._rowElements.length-2];if(n.getAttribute(`aria-posinset`)===(t===0?`1`:`${this._terminal.buffer.lines.length}`)||e.relatedTarget!==r)return;let i,a;if(t===0?(i=n,a=this._rowElements.pop(),this._rowContainer.removeChild(a)):(i=this._rowElements.shift(),a=n,this._rowContainer.removeChild(i)),i.removeEventListener(`focus`,this._topBoundaryFocusListener),a.removeEventListener(`focus`,this._bottomBoundaryFocusListener),t===0){let e=this._createAccessibilityTreeNode();this._rowElements.unshift(e),this._rowContainer.insertAdjacentElement(`afterbegin`,e)}else{let e=this._createAccessibilityTreeNode();this._rowElements.push(e),this._rowContainer.appendChild(e)}this._rowElements[0].addEventListener(`focus`,this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error(`anchorNode and/or focusNode are null`);return}let t={node:e.anchorNode,offset:e.anchorOffset},n={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(n.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===n.node&&t.offset>n.offset)&&([t,n]=[n,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let r=this._rowElements.slice(-1)[0];if(n.node.compareDocumentPosition(r)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(n={node:r,offset:r.textContent?.length??0}),!this._rowContainer.contains(n.node))return;let i=({node:e,offset:t})=>{let n=e instanceof Text?e.parentNode:e,r=parseInt(n?.getAttribute(`aria-posinset`),10)-1;if(isNaN(r))return console.warn(`row is invalid. Race condition?`),null;let i=this._rowColumns.get(n);if(!i)return console.warn(`columns is null. Race condition?`),null;let a=t<i.length?i[t]:i.slice(-1)[0]+1;return a>=this._terminal.cols&&(++r,a=0),{row:r,column:a}},a=i(t),o=i(n);if(a&&o){if(a.row>o.row||a.row===o.row&&a.column>=o.column)throw Error(`invalid range`);this._terminal.select(a.column,a.row,(o.row-a.row)*this._terminal.cols-a.column+o.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener(`focus`,this._bottomBoundaryFocusListener);for(let e=this._rowContainer.children.length;e<this._terminal.rows;e++)this._rowElements[e]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[e]);for(;this._rowElements.length>e;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement(`div`);return e.setAttribute(`role`,`listitem`),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e<this._terminal.rows;e++)this._refreshRowDimensions(this._rowElements[e]),this._alignRowWidth(this._rowElements[e])}}_refreshRowDimensions(e){e.style.height=`${this._renderService.dimensions.css.cell.height}px`}_alignRowWidth(e){e.style.transform=``;let t=e.getBoundingClientRect().width,n=this._rowColumns.get(e)?.slice(-1)?.[0];if(!n)return;let r=n*this._renderService.dimensions.css.cell.width;e.style.transform=`scaleX(${r/t})`}};Ju=z([B(1,Yr),B(2,ii),B(3,oi)],Ju);var Yu=class extends U{constructor(e,t,n,r,i){super(),this._element=e,this._mouseService=t,this._renderService=n,this._bufferService=r,this._linkProviderService=i,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this._register(new W),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this._register(new W),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this._register(H(()=>{ki(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,this._activeProviderReplies?.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(G(this._element,`mouseleave`,()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(G(this._element,`mousemove`,this._handleMouseMove.bind(this))),this._register(G(this._element,`mousedown`,this._handleMouseDown.bind(this))),this._register(G(this._element,`mouseup`,this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(e){this._lastMouseEvent=e;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;let n=e.composedPath();for(let e=0;e<n.length;e++){let t=n[e];if(t.classList.contains(`xterm`))break;if(t.classList.contains(`xterm-hover`))return}(!this._lastBufferCell||t.x!==this._lastBufferCell.x||t.y!==this._lastBufferCell.y)&&(this._handleHover(t),this._lastBufferCell=t)}_handleHover(e){this._activeLine!==e.y||this._wasResized?(this._clearCurrentLink(),this._askForLink(e,!1),this._wasResized=!1):this._currentLink&&this._linkAtPosition(this._currentLink.link,e)||(this._clearCurrentLink(),this._askForLink(e,!0))}_askForLink(e,t){(!this._activeProviderReplies||!t)&&(this._activeProviderReplies?.forEach(e=>{e?.forEach(e=>{e.link.dispose&&e.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let n=!1;for(let[r,i]of this._linkProviderService.linkProviders.entries())t?this._activeProviderReplies?.get(r)&&(n=this._checkLinkProviderResult(r,e,n)):i.provideLinks(e.y,t=>{if(this._isMouseOut)return;let i=t?.map(e=>({link:e}));this._activeProviderReplies?.set(r,i),n=this._checkLinkProviderResult(r,e,n),this._activeProviderReplies?.size===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let n=new Set;for(let r=0;r<t.size;r++){let i=t.get(r);if(i)for(let t=0;t<i.length;t++){let r=i[t],a=r.link.range.start.y<e?0:r.link.range.start.x,o=r.link.range.end.y>e?this._bufferService.cols:r.link.range.end.x;for(let e=a;e<=o;e++){if(n.has(e)){i.splice(t--,1);break}n.add(e)}}}}_checkLinkProviderResult(e,t,n){if(!this._activeProviderReplies)return n;let r=this._activeProviderReplies.get(e),i=!1;for(let t=0;t<e;t++)(!this._activeProviderReplies.has(t)||this._activeProviderReplies.get(t))&&(i=!0);if(!i&&r){let e=r.find(e=>this._linkAtPosition(e.link,t));e&&(n=!0,this._handleNewLink(e))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!n)for(let e=0;e<this._activeProviderReplies.size;e++){let r=this._activeProviderReplies.get(e)?.find(e=>this._linkAtPosition(e.link,t));if(r){n=!0,this._handleNewLink(r);break}}return n}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink&&Xu(this._mouseDownLink.link,this._currentLink.link)&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){!this._currentLink||!this._lastMouseEvent||(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,ki(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:e.link.decorations===void 0||e.link.decorations.underline,pointerCursor:e.link.decorations===void 0||e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>this._currentLink?.state?.decorations.pointerCursor,set:e=>{this._currentLink?.state&&this._currentLink.state.decorations.pointerCursor!==e&&(this._currentLink.state.decorations.pointerCursor=e,this._currentLink.state.isHovered&&this._element.classList.toggle(`xterm-cursor-pointer`,e))}},underline:{get:()=>this._currentLink?.state?.decorations.underline,set:t=>{this._currentLink?.state&&this._currentLink?.state?.decorations.underline!==t&&(this._currentLink.state.decorations.underline=t,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,t))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(e=>{if(!this._currentLink)return;let t=e.start===0?0:e.start+1+this._bufferService.buffer.ydisp,n=this._bufferService.buffer.ydisp+1+e.end;if(this._currentLink.link.range.start.y>=t&&this._currentLink.link.range.end.y<=n&&(this._clearCurrentLink(t,n),this._lastMouseEvent)){let e=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);e&&this._askForLink(e,!1)}})))}_linkHover(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add(`xterm-cursor-pointer`)),t.hover&&t.hover(n,t.text)}_fireUnderlineEvent(e,t){let n=e.range,r=this._bufferService.buffer.ydisp,i=this._createLinkUnderlineEvent(n.start.x-1,n.start.y-r-1,n.end.x,n.end.y-r-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(i)}_linkLeave(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove(`xterm-cursor-pointer`)),t.leave&&t.leave(n,t.text)}_linkAtPosition(e,t){let n=e.range.start.y*this._bufferService.cols+e.range.start.x,r=e.range.end.y*this._bufferService.cols+e.range.end.x,i=t.y*this._bufferService.cols+t.x;return n<=i&&i<=r}_positionFromMouseEvent(e,t,n){let r=n.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(r)return{x:r[0],y:r[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,n,r,i){return{x1:e,y1:t,x2:n,y2:r,cols:this._bufferService.cols,fg:i}}};Yu=z([B(1,ai),B(2,oi),B(3,Gr),B(4,ui)],Yu);function Xu(e,t){return e.text===t.text&&e.range.start.x===t.range.start.x&&e.range.start.y===t.range.start.y&&e.range.end.x===t.range.end.x&&e.range.end.y===t.range.end.y}var Zu=class extends Iu{constructor(e={}){super(e),this._linkifier=this._register(new Ni),this.browser=dc,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new Ni),this._onCursorMove=this._register(new W),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new W),this.onKey=this._onKey.event,this._onRender=this._register(new W),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new W),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new W),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new W),this.onBell=this._onBell.event,this._onFocus=this._register(new W),this._onBlur=this._register(new W),this._onA11yCharEmitter=this._register(new W),this._onA11yTabEmitter=this._register(new W),this._onWillOpen=this._register(new W),this._setup(),this._decorationService=this._instantiationService.createInstance(Uu),this._instantiationService.setService(ei,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(oc),this._instantiationService.setService(ui,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(ti)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(e=>this.refresh(e?.start??0,e?.end??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(e=>this._reportWindowsOptions(e))),this._register(this._inputHandler.onColor(e=>this._handleColorEvent(e))),this._register(Bi.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(Bi.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(Bi.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(Bi.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(e=>this._afterResize(e.cols,e.rows))),this._register(H(()=>{this._customKeyEventHandler=void 0,this.element?.parentNode?.removeChild(this.element)}))}get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}_handleColorEvent(e){if(this._themeService)for(let t of e){let e,n=``;switch(t.index){case 256:e=`foreground`,n=`10`;break;case 257:e=`background`,n=`11`;break;case 258:e=`cursor`,n=`12`;break;default:e=`ansi`,n=`4;`+t.index}switch(t.type){case 0:let r=Os.toColorRGB(e===`ansi`?this._themeService.colors.ansi[t.index]:this._themeService.colors[e]);this.coreService.triggerDataEvent(`${K.ESC}]${n};${bu(r)}${bs.ST}`);break;case 1:if(e===`ansi`)this._themeService.modifyColors(e=>e.ansi[t.index]=Ds.toColor(...t.color));else{let n=e;this._themeService.modifyColors(e=>e[n]=Ds.toColor(...t.color))}break;case 2:this._themeService.restoreColor(t.index)}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(Ju,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(K.ESC+`[I`),this.element.classList.add(`focus`),this._showCursor(),this._onFocus.fire()}blur(){return this.textarea?.blur()}_handleTextAreaBlur(){this.textarea.value=``,this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(K.ESC+`[O`),this.element.classList.remove(`focus`),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;let n=Math.min(this.buffer.x,this.cols-1),r=this._renderService.dimensions.css.cell.height,i=t.getWidth(n),a=this._renderService.dimensions.css.cell.width*i,o=this.buffer.y*this._renderService.dimensions.css.cell.height,s=n*this._renderService.dimensions.css.cell.width;this.textarea.style.left=s+`px`,this.textarea.style.top=o+`px`,this.textarea.style.width=a+`px`,this.textarea.style.height=r+`px`,this.textarea.style.lineHeight=r+`px`,this.textarea.style.zIndex=`-5`}_initGlobal(){this._bindKeys(),this._register(G(this.element,`copy`,e=>{this.hasSelection()&&V(e,this._selectionService)}));let e=e=>Er(e,this.textarea,this.coreService,this.optionsService);this._register(G(this.textarea,`paste`,e)),this._register(G(this.element,`paste`,e)),hc?this._register(G(this.element,`mousedown`,e=>{e.button===2&&kr(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(G(this.element,`contextmenu`,e=>{kr(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),Cc&&this._register(G(this.element,`auxclick`,e=>{e.button===1&&Or(e,this.textarea,this.screenElement)}))}_bindKeys(){this._register(G(this.textarea,`keyup`,e=>this._keyUp(e),!0)),this._register(G(this.textarea,`keydown`,e=>this._keyDown(e),!0)),this._register(G(this.textarea,`keypress`,e=>this._keyPress(e),!0)),this._register(G(this.textarea,`compositionstart`,()=>this._compositionHelper.compositionstart())),this._register(G(this.textarea,`compositionupdate`,e=>this._compositionHelper.compositionupdate(e))),this._register(G(this.textarea,`compositionend`,()=>this._compositionHelper.compositionend())),this._register(G(this.textarea,`input`,e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){if(!e)throw Error(`Terminal requires a parent element.`);if(e.isConnected||this._logService.debug(`Terminal.open was called on an element that was not attached to the DOM`),this.element?.ownerDocument.defaultView&&this._coreBrowserService){this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView);return}this._document=e.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement(`div`),this.element.dir=`ltr`,this.element.classList.add(`terminal`),this.element.classList.add(`xterm`),e.appendChild(this.element);let t=this._document.createDocumentFragment();this._viewportElement=this._document.createElement(`div`),this._viewportElement.classList.add(`xterm-viewport`),t.appendChild(this._viewportElement),this.screenElement=this._document.createElement(`div`),this.screenElement.classList.add(`xterm-screen`),this._register(G(this.screenElement,`mousemove`,e=>this.updateCursorStyle(e))),this._helperContainer=this._document.createElement(`div`),this._helperContainer.classList.add(`xterm-helpers`),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);let n=this.textarea=this._document.createElement(`textarea`);this.textarea.classList.add(`xterm-helper-textarea`),this.textarea.setAttribute(`aria-label`,xr.get()),wc||this.textarea.setAttribute(`aria-multiline`,`false`),this.textarea.setAttribute(`autocorrect`,`off`),this.textarea.setAttribute(`autocapitalize`,`off`),this.textarea.setAttribute(`spellcheck`,`false`),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange(`disableStdin`,()=>n.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(ic,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<`u`?window.document:null)),this._instantiationService.setService(ii,this._coreBrowserService),this._register(G(this.textarea,`focus`,e=>this._handleTextAreaFocus(e))),this._register(G(this.textarea,`blur`,()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(ec,this._document,this._helperContainer),this._instantiationService.setService(ri,this._charSizeService),this._themeService=this._instantiationService.createInstance(cl),this._instantiationService.setService(li,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(Fs),this._instantiationService.setService(ci,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(Ac,this.rows,this.screenElement)),this._instantiationService.setService(oi,this._renderService),this._register(this._renderService.onRenderedViewportChange(e=>this._onRender.fire(e))),this.onResize(e=>this._renderService.resize(e.cols,e.rows)),this._compositionView=this._document.createElement(`div`),this._compositionView.classList.add(`composition-view`),this._compositionHelper=this._instantiationService.createInstance(xs,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(lc),this._instantiationService.setService(ai,this._mouseService);let r=this._linkifier.value=this._register(this._instantiationService.createInstance(Yu,this.screenElement));this.element.appendChild(t);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this._register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this._register(this.onBlur(()=>this._renderService.handleBlur())),this._register(this.onFocus(()=>this._renderService.handleFocus())),this._viewport=this._register(this._instantiationService.createInstance(fs,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(e=>{super.scrollLines(e,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(Qc,this.element,this.screenElement,r)),this._instantiationService.setService(si,this._selectionService),this._register(this._selectionService.onRequestScrollLines(e=>this.scrollLines(e.amount,e.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(e=>this._renderService.handleSelectionChanged(e.start,e.end,e.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(e=>{this.textarea.value=e,this.textarea.focus(),this.textarea.select()})),this._register(Bi.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{this._selectionService.refresh(),this._viewport?.queueSync()})),this._register(this._instantiationService.createInstance(ps,this.screenElement)),this._register(G(this.element,`mousedown`,e=>this._selectionService.handleMouseDown(e))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add(`enable-mouse-events`)):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(Ju,this)),this._register(this.optionsService.onSpecificOptionChange(`screenReaderMode`,e=>this._handleScreenReaderModeOptionChange(e))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(vs,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange(`overviewRuler`,e=>{!this._overviewRulerRenderer&&e&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(vs,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance($s,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function n(t){let n=e._mouseService.getMouseReportCoords(t,e.screenElement);if(!n)return!1;let r,i;switch(t.overrideType||t.type){case`mousemove`:i=32,t.buttons===void 0?(r=3,t.button!==void 0&&(r=t.button<3?t.button:3)):r=t.buttons&1?0:t.buttons&4?1:t.buttons&2?2:3;break;case`mouseup`:i=0,r=t.button<3?t.button:3;break;case`mousedown`:i=1,r=t.button<3?t.button:3;break;case`wheel`:if(e._customWheelEventHandler&&e._customWheelEventHandler(t)===!1)return!1;let n=t.deltaY;if(n===0||e.coreMouseService.consumeWheelEvent(t,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return!1;i=n<0?0:1,r=4;break;default:return!1}return i===void 0||r===void 0||r>4?!1:e.coreMouseService.triggerMouseEvent({col:n.col,row:n.row,x:n.x,y:n.y,button:r,action:i,ctrl:t.ctrlKey,alt:t.altKey,shift:t.shiftKey})}let r={mouseup:null,wheel:null,mousedrag:null,mousemove:null},i={mouseup:e=>(n(e),e.buttons||(this._document.removeEventListener(`mouseup`,r.mouseup),r.mousedrag&&this._document.removeEventListener(`mousemove`,r.mousedrag)),this.cancel(e)),wheel:e=>(n(e),this.cancel(e,!0)),mousedrag:e=>{e.buttons&&n(e)},mousemove:e=>{e.buttons||n(e)}};this._register(this.coreMouseService.onProtocolChange(e=>{e?(this.optionsService.rawOptions.logLevel===`debug`&&this._logService.debug(`Binding to mouse events:`,this.coreMouseService.explainEvents(e)),this.element.classList.add(`enable-mouse-events`),this._selectionService.disable()):(this._logService.debug(`Unbinding from mouse events.`),this.element.classList.remove(`enable-mouse-events`),this._selectionService.enable()),e&8?r.mousemove||=(t.addEventListener(`mousemove`,i.mousemove),i.mousemove):(t.removeEventListener(`mousemove`,r.mousemove),r.mousemove=null),e&16?r.wheel||=(t.addEventListener(`wheel`,i.wheel,{passive:!1}),i.wheel):(t.removeEventListener(`wheel`,r.wheel),r.wheel=null),e&2?r.mouseup||=i.mouseup:(this._document.removeEventListener(`mouseup`,r.mouseup),r.mouseup=null),e&4?r.mousedrag||=i.mousedrag:(this._document.removeEventListener(`mousemove`,r.mousedrag),r.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(G(t,`mousedown`,e=>{if(e.preventDefault(),this.focus(),this.coreMouseService.areMouseEventsActive&&!this._selectionService.shouldForceSelection(e))return n(e),r.mouseup&&this._document.addEventListener(`mouseup`,r.mouseup),r.mousedrag&&this._document.addEventListener(`mousemove`,r.mousedrag),this.cancel(e)})),this._register(G(t,`wheel`,t=>{if(!r.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(t)===!1)return!1;if(!this.buffer.hasScrollback){if(t.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(t,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return this.cancel(t,!0);let n=K.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?`O`:`[`)+(t.deltaY<0?`A`:`B`);return this.coreService.triggerDataEvent(n,!0),this.cancel(t,!0)}}},{passive:!1}))}refresh(e,t){this._renderService?.refreshRows(e,t)}updateCursorStyle(e){this._selectionService?.shouldColumnSelect(e)?this.element.classList.add(`column-select`):this.element.classList.remove(`column-select`)}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,t){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,t),this.refresh(0,this.rows-1)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){e&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}paste(e){Dr(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}attachCustomWheelEventHandler(e){this._customWheelEventHandler=e}registerLinkProvider(e){return this._linkProviderService.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw Error(`Terminal must be opened first`);let t=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),t}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw Error(`Terminal must be opened first`);this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return this._selectionService?this._selectionService.hasSelection:!1}select(e,t,n){this._selectionService.setSelection(e,t,n)}getSelection(){return this._selectionService?this._selectionService.selectionText:``}getSelectionPosition(){if(this._selectionService&&this._selectionService.hasSelection)return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){this._selectionService?.clearSelection()}selectAll(){this._selectionService?.selectAll()}selectLines(e,t){this._selectionService?.selectLines(e,t)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;let t=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!t&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;!t&&(e.key===`Dead`||e.key===`AltGraph`)&&(this._unprocessedDeadKey=!0);let n=Ru(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),n.type===3||n.type===2){let t=this.rows-1;return this.scrollLines(n.type===2?-t:t),this.cancel(e,!0)}if(n.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,e)||(n.cancel&&this.cancel(e,!0),!n.key)||e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.key.length===1&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)return!0;if(this._unprocessedDeadKey)return this._unprocessedDeadKey=!1,!0;if((n.key===K.ETX||n.key===K.CR)&&(this.textarea.value=``),this._onKey.fire({key:n.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(n.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)return this.cancel(e,!0);this._keyDownHandled=!0}_isThirdLevelShift(e,t){let n=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey||e.isWindows&&t.getModifierState(`AltGraph`);return t.type===`keypress`?n:n&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)&&(Qu(e)||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let t;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;if(this.cancel(e),e.charCode)t=e.charCode;else if(e.which===null||e.which===void 0)t=e.keyCode;else if(e.which!==0&&e.charCode!==0)t=e.which;else return!1;return!t||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e)?!1:(t=String.fromCharCode(t),this._onKey.fire({key:t,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(t,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,!0)}_inputEvent(e){if(e.data&&e.inputType===`insertText`&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;let t=e.data;return this.coreService.triggerDataEvent(t,!0),this.cancel(e),!0}return!1}resize(e,t){e===this.cols&&t===this.rows?this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure():super.resize(e,t)}_afterResize(e,t){this._charSizeService?.measure()}clear(){if(this.buffer.ybase!==0||this.buffer.y!==0){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e<this.rows;e++)this.buffer.lines.push(this.buffer.getBlankLine(gl));this._onScroll.fire({position:this.buffer.ydisp}),this.refresh(0,this.rows-1)}}reset(){this.options.rows=this.rows,this.options.cols=this.cols;let e=this._customKeyEventHandler;this._setup(),super.reset(),this._selectionService?.reset(),this._decorationService.reset(),this._customKeyEventHandler=e,this.refresh(0,this.rows-1)}clearTextureAtlas(){this._renderService?.clearTextureAtlas()}_reportFocus(){this.element?.classList.contains(`focus`)?this.coreService.triggerDataEvent(K.ESC+`[I`):this.coreService.triggerDataEvent(K.ESC+`[O`)}_reportWindowsOptions(e){if(this._renderService)switch(e){case 0:let e=this._renderService.dimensions.css.canvas.width.toFixed(0),t=this._renderService.dimensions.css.canvas.height.toFixed(0);this.coreService.triggerDataEvent(`${K.ESC}[4;${t};${e}t`);break;case 1:let n=this._renderService.dimensions.css.cell.width.toFixed(0),r=this._renderService.dimensions.css.cell.height.toFixed(0);this.coreService.triggerDataEvent(`${K.ESC}[6;${r};${n}t`)}}cancel(e,t){if(this.options.cancelEvents||t)return e.preventDefault(),e.stopPropagation(),!1}};function Qu(e){return e.keyCode===16||e.keyCode===17||e.keyCode===18}var $u=class{constructor(){this._addons=[]}dispose(){for(let e=this._addons.length-1;e>=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let n={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(n),t.dispose=()=>this._wrappedAddonDispose(n),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let n=0;n<this._addons.length;n++)if(this._addons[n]===e){t=n;break}if(t===-1)throw Error(`Could not dispose an addon that has not been loaded`);e.isDisposed=!0,e.dispose.apply(e.instance),this._addons.splice(t,1)}},ed=class{constructor(e){this._line=e}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(e,t){if(!(e<0||e>=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new Rr)}translateToString(e,t,n){return this._line.translateToString(e,t,n)}},td=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){let t=this._buffer.lines.get(e);if(t)return new ed(t)}getNullCell(){return new Rr}},nd=class extends U{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new W),this.onBufferChange=this._onBufferChange.event,this._normal=new td(this._core.buffers.normal,`normal`),this._alternate=new td(this._core.buffers.alt,`alternate`),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw Error(`Active buffer is neither normal nor alternate`)}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}},rd=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,e=>t(e.toArray()))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,(e,n)=>t(e,n.toArray()))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}},id=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}},ad=[`cols`,`rows`],od=0,sd=class extends U{constructor(e){super(),this._core=this._register(new Zu(e)),this._addonManager=this._register(new $u),this._publicOptions={...this._core.options};let t=e=>this._core.options[e],n=(e,t)=>{this._checkReadonlyOptions(e),this._core.options[e]=t};for(let e in this._core.options){let r={get:t.bind(this,e),set:n.bind(this,e)};Object.defineProperty(this._publicOptions,e,r)}}_checkReadonlyOptions(e){if(ad.includes(e))throw Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw Error(`You must set the allowProposedApi option to true to use proposed API`)}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||=new rd(this._core),this._parser}get unicode(){return this._checkProposedApi(),new id(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||=this._register(new nd(this._core)),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,t=`none`;switch(this._core.coreMouseService.activeProtocol){case`X10`:t=`x10`;break;case`VT200`:t=`vt200`;break;case`DRAG`:t=`drag`;break;case`ANY`:t=`any`}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,synchronizedOutputMode:e.synchronizedOutput,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,n){this._verifyIntegers(e,t,n),this._core.select(e,t,n)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write(`\r
21
+ `,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return xr.get()},set promptLabel(e){xr.set(e)},get tooMuchOutput(){return Cr.get()},set tooMuchOutput(e){Cr.set(e)}}}_verifyIntegers(...e){for(od of e)if(od===1/0||isNaN(od)||od%1!=0)throw Error(`This API only accepts integers`)}_verifyPositiveIntegers(...e){for(od of e)if(od&&(od===1/0||isNaN(od)||od%1!=0||od<0))throw Error(`This API only accepts positive integers`)}},cd=2,ld=1,ud=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:this._terminal.options.overviewRuler?.width||14,n=window.getComputedStyle(this._terminal.element.parentElement),r=parseInt(n.getPropertyValue(`height`)),i=Math.max(0,parseInt(n.getPropertyValue(`width`))),a=window.getComputedStyle(this._terminal.element),o={top:parseInt(a.getPropertyValue(`padding-top`)),bottom:parseInt(a.getPropertyValue(`padding-bottom`)),right:parseInt(a.getPropertyValue(`padding-right`)),left:parseInt(a.getPropertyValue(`padding-left`))},s=o.top+o.bottom,c=o.right+o.left,l=r-s,u=i-c-t;return{cols:Math.max(cd,Math.floor(u/e.css.cell.width)),rows:Math.max(ld,Math.floor(l/e.css.cell.height))}}};function dd(e){return e.length}function fd(e,t){return t<=0||e<0?-1:Math.min(e,t-1)}function pd(e,t,n){return fd(e===t?t:e>t?e-1:e,n)}function md(e,t){return Array.from({length:t},(e,t)=>t).find(t=>t!==e)??-1}function hd(e,t){let n=e.filter(e=>!t.has(e.id));return n.find(e=>!e.workspaceMissing)??n[0]??null}function gd(e){return!(e.key!==`Enter`||e.shiftKey||e.composing||e.maximized)}function _d(e){return e}async function vd(e,t={}){if(!e)return`unsupported`;let n=t.clipboard===void 0?typeof navigator<`u`?navigator.clipboard??null:null:t.clipboard,r=t.execCommand??(typeof document<`u`?document.execCommand.bind(document):void 0),i=t.makeTextarea??(()=>{let e=document.createElement(`textarea`);return document.body.appendChild(e),{set value(t){e.value=t},get value(){return e.value},style:{get position(){return e.style.position},set position(t){e.style.position=t},get opacity(){return e.style.opacity},set opacity(t){e.style.opacity=t}},select:()=>e.select(),remove:()=>e.remove()}}),a=n?.writeText;if(typeof a==`function`)try{return await a.call(n,e),`copied`}catch{}let o=null;try{let t=i();return o=t,t.value=e,t.style.position=`fixed`,t.style.opacity=`0`,t.select(),r&&r(`copy`)?`copied`:`failed`}catch{return`failed`}finally{o?.remove()}}var yd=F(`<button type=button><span class=iconbtn-glyph>`),bd=F(`<button class=copybtn>`),xd=F(`<div class=overlay><div class=modal><div class=modal-head><b></b><button class=iconbtn>✕`);function Sd(e){return(()=>{var t=yd(),n=t.firstChild;return De(t,`click`,e.onClick,!0),R(n,()=>e.icon),b(n=>{var r=`iconbtn`+(e.active?` active`:``)+(e.class?` `+e.class:``),i=e.title,a=e.style;return r!==n.e&&L(t,n.e=r),i!==n.t&&I(t,`title`,n.t=i),n.a=Oe(t,a,n.a),n},{e:void 0,t:void 0,a:void 0}),t})()}function Cd(e){let[t,n]=y(!1),[r,i]=y(!1),a=t=>{t.preventDefault(),t.stopPropagation(),vd(e.text??``).then(e=>{e===`unsupported`||e===`failed`?(i(!0),setTimeout(()=>i(!1),1200)):(n(!0),setTimeout(()=>n(!1),900))})};return(()=>{var n=bd();return n.$$click=a,R(n,(()=>{var n=P(()=>!!t());return()=>n()?`✓`:P(()=>!!r())()?`✗`:e.label??`⧉`})()),b(()=>I(n,`title`,e.title??`copy to clipboard`)),n})()}function wd(e){return(()=>{var t=xd(),n=t.firstChild,r=n.firstChild.firstChild,i=r.nextSibling;return t.$$click=t=>t.target===t.currentTarget&&e.onClose(),R(r,()=>e.title),De(i,`click`,e.onClose,!0),R(n,()=>e.children,null),t})()}Ee([`click`]);var Td={fg:void 0,bg:void 0,bold:!1,dim:!1,italic:!1,underline:!1,inverse:!1},Ed=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`];function Dd(e){let t=[];return e.fg&&t.push(`ansi-fg-${e.fg}`),e.bg&&t.push(`ansi-bg-${e.bg}`),e.bold&&t.push(`ansi-bold`),e.dim&&t.push(`ansi-dim`),e.italic&&t.push(`ansi-italic`),e.underline&&t.push(`ansi-underline`),e.inverse&&t.push(`ansi-inverse`),t}function Od(e,t){let n={...e};t.length===0&&(t=[0]);for(let e=0;e<t.length;e++){let r=t[e];if(r===0)n.fg=void 0,n.bg=void 0,n.bold=!1,n.dim=!1,n.italic=!1,n.underline=!1,n.inverse=!1;else if(r===1)n.bold=!0;else if(r===2)n.dim=!0;else if(r===3)n.italic=!0;else if(r===4)n.underline=!0;else if(r===7)n.inverse=!0;else if(r===21||r===22)n.bold=!1,n.dim=!1;else if(r===23)n.italic=!1;else if(r===24)n.underline=!1;else if(r===27)n.inverse=!1;else if(r>=30&&r<=37)n.fg=Ed[r-30];else if(r>=90&&r<=97)n.fg=`bright-${Ed[r-90]}`;else if(r===39)n.fg=void 0;else if(r>=40&&r<=47)n.bg=Ed[r-40];else if(r>=100&&r<=107)n.bg=`bright-${Ed[r-100]}`;else if(r===49)n.bg=void 0;else if(r===38||r===48){let i=t[e+1],a=r===38?`fg`:`bg`;i===5&&t[e+2]!==void 0?(n[a]=`ext`,e+=2):i===2&&t[e+4]!==void 0?(n[a]=`ext`,e+=4):(n[a]=`ext`,e+=1)}}return n}var kd=/\x1b\[([0-9;]*)m/;function Ad(e){if(!e)return[];let t=[],n={...Td},r=``,i=()=>{if(!r)return;let e=Dd(n),i=t[t.length-1];i&&i.classes.join(` `)===e.join(` `)?i.text+=r:t.push({text:r,classes:e}),r=``};for(let t=0;t<e.length;t++){let a=e[t];if(a===`\x1B`){let r=e.slice(t),a=kd.exec(r);if(a){i();let e=(a[1]??``).split(`;`).filter(e=>e!==``).map(e=>Number(e)).filter(e=>Number.isFinite(e));n=Od(n,e),t+=a[0].length-1;continue}let o=/^\x1b\[[0-9;?]*[A-Za-z]/.exec(r);if(o){t+=o[0].length-1;continue}let s=/^\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/.exec(r);if(s){t+=s[0].length-1;continue}}else if(a===`\r`){if(e[t+1]===`
22
22
  `){r+=`
23
- `,t++;continue}r=``}else r+=a}return i(),t}function jd(e){return Ad(e).map(e=>e.text).join(``)}function Md(e){return e.includes(`\x1B`)}var Nd=400,Pd=new Map;function Fd(e){return Pd.get(e)}function Id(e,t){if(Pd.size>=Nd){let e=Pd.keys().next();e.done||Pd.delete(e.value)}Pd.set(e,t)}var Ld=`modulepreload`,Rd=function(e){return`/`+e},zd={},Bd=function(e){return e.pathname.endsWith(`.css`)},Vd=function(e,t,n){if(t in e)return e[t];let r=n();if(!r){e[t]=void 0;return}let i=r.then(()=>{e[t]=void 0},n=>{throw e[t]=void 0,n});return e[t]=i,i},J=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e,i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?new URL(import.meta.resolve(e)):new URL(e,import.meta.url)}r=o(t.map(t=>{t=Rd(t,n);let r=s(t),i=Bd(r);return Vd(zd,r.href,()=>{if(e===void 0){e={all:new Set,styles:new Set};let t=document.getElementsByTagName(`link`);for(let n=t.length-1;n>=0;n--){let r=t[n];e.all.add(r.href),r.rel===`stylesheet`&&e.styles.add(r.href)}}if((i?e.styles:e.all).has(r.href))return;let t=document.createElement(`link`);if(t.rel=i?`stylesheet`:Ld,i||(t.as=`script`),t.crossOrigin=``,t.href=r.href,a&&t.setAttribute(`nonce`,a),document.head.appendChild(t),i)return new Promise((e,n)=>{t.addEventListener(`load`,e),t.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${r}`)))})})}).filter(e=>e!==void 0))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},Hd=P(`<span class=bashelapsed>running… `),Ud=P(`<span class=bashelapsed> elapsed`),Wd=P(`<span class=thinktimer>`),Gd=P(`<pre class="mono toolbody ansi">`),Kd=P(`<pre class="mono toolbody">`),qd=P(`<span>`),Jd=P(`<div class="toolbody shiki">`);function Yd(e){let t=new Date(e.startedAt).getTime(),[n,r]=y(Date.now());w(()=>{let e=setInterval(()=>r(Date.now()),500);T(()=>clearInterval(e))});let i=()=>ft(Math.max(0,n()-t));return e.inline?(()=>{var t=Hd();return t.firstChild,L(t,i,null),L(t,(()=>{var t=N(()=>!!e.timeoutMs);return()=>t()?` · timeout ${Math.round(e.timeoutMs/1e3)}s`:``})(),null),t})():(()=>{var e=Ud(),t=e.firstChild;return L(e,i,t),e})()}function Xd(e){let[t,n]=y(Date.now());w(()=>{let e=setInterval(()=>n(Date.now()),500);T(()=>clearInterval(e))});let r=()=>{if(!e.startedAt)return null;let n=Math.max(0,t()-e.startedAt);return n>864e5?null:ft(n)};return A(M,{get when(){return r()!==null},fallback:null,get children(){var e=Wd();return L(e,r),e}})}function Zd(e){let t=S(()=>Md(e.text)?Ad(e.text):null);return A(M,{get when(){return t()},get fallback(){return(()=>{var t=Kd();return L(t,()=>e.text),t})()},get children(){var e=Gd();return L(e,A(j,{get each(){return t()},children:e=>e.classes.length?(()=>{var t=qd();return L(t,()=>e.text),b(()=>I(t,e.classes.join(` `))),t})():e.text})),e}})}function Qd(e){let t=()=>e.lang?`${e.lang}::${e.text.length}::${e.text}`:``,[n,r]=y((e.lang?Fd(t()):void 0)??``);return x(()=>{let n=t(),i=e.text,a=e.lang;if(!a||!i.trim()){r(``);return}let o=Fd(n);o===void 0?(async()=>{try{let{highlightLangChunks:e}=await J(async()=>{let{highlightLangChunks:e}=await Promise.resolve().then(()=>_x);return{highlightLangChunks:e}},void 0),o=``;for await(let t of e(a,i))o+=t;if(!o)return;Id(n,o),t()===n&&r(o)}catch{}})():r(o)}),A(M,{get when(){return!!n()},get fallback(){return(()=>{var t=Kd();return L(t,()=>e.text),t})()},get children(){var e=Jd();return b(()=>e.innerHTML=n()),e}})}var $d=[{key:`dark`,label:`Dark`,mode:`dark`,sw:[`#1a1c22`,`#2b2e39`,`#5865f2`]},{key:`midnight`,label:`Midnight`,mode:`dark`,sw:[`#0d0f18`,`#252a42`,`#8b7cf7`]},{key:`tea`,label:`Milk Tea`,mode:`dark`,sw:[`#241c16`,`#493b2d`,`#d98e32`]},{key:`coffee`,label:`Coffee`,mode:`dark`,sw:[`#191410`,`#403527`,`#c68a4b`]},{key:`matcha`,label:`Matcha`,mode:`dark`,sw:[`#1b2217`,`#3c4a33`,`#8db64e`]},{key:`matrix`,label:`Matrix`,mode:`dark`,sw:[`#060a06`,`#18301d`,`#2fd558`]},{key:`sunset`,label:`Sunset`,mode:`dark`,sw:[`#1c1422`,`#452f52`,`#f2784b`]},{key:`sakura`,label:`Sakura`,mode:`dark`,sw:[`#22131f`,`#3f213a`,`#f2558e`]},{key:`light`,label:`Light`,mode:`light`,sw:[`#eceef4`,`#ffffff`,`#4757d8`]},{key:`strawberry`,label:`Strawberry`,mode:`light`,sw:[`#fbe4ea`,`#fffafb`,`#e05575`]},{key:`ramune`,label:`Ramune`,mode:`light`,sw:[`#ddeff7`,`#fbfeff`,`#1d86ae`]}];async function Y(e,t){let n=localStorage.getItem(`teapot.token`),r=new Headers(t?.headers);n&&!r.has(`authorization`)&&r.set(`authorization`,`Bearer ${n}`);let i=await fetch(e,{...t,headers:r});if(!i.ok){i.status===401&&window.dispatchEvent(new CustomEvent(`teapot:unauthorized`));let t=null;try{t=await i.json()}catch{}let n=(t&&typeof t==`object`&&`error`in t?String(t.error):``)||`${e}: HTTP ${i.status}`;throw Object.assign(Error(n),{payload:t})}return i.json()}var ef=.82,tf=.9,nf=e=>{if(Number.isFinite(e))return e<0?0:e>1?1:e};function rf(e,t){let n=nf(e??ef)??ef;return{dim:nf(t??tf)??tf,panel:Math.max(0,Math.min(1,n-.05)),raised:Math.max(0,Math.min(1,n+.06))}}function af(e,t){return`color-mix(in srgb, ${e} ${Math.round((nf(t)??tf)*100)}%, transparent)`}function of(e,t){let n=e?.trim();if(n)return`url("${(t?dn(n,t)??n:n).replace(/"/g,`%22`)}")`}var sf=P(`<div class="content mdpreview todopane">`),cf=P(`<textarea id=todo-input class="mono todopane-edit"rows=5 placeholder="- [ ] task one
24
- - [ ] task two"title="shared with the agent \\u2014 it may check items off via set_todo; your unsaved edits win until you save">`),lf=P(`<div class="filepreview shikiwrap">`),uf=P(`<div class=muted style=padding-top:6px;font-size:11.5px>… truncated (first 100 KB)`),df=P(`<div class=muted style=padding:8px;font-size:12px>✨ highlighting <!>…`),ff=P(`<pre class=mono style=max-height:62vh;overflow:auto;white-space:pre-wrap;margin:0>`),pf=P(`<label><input type=number min=0>`),mf=P(`<span class=tprev-bg>`),hf=P(`<span class=tprev-veil>`),gf=P(`<span class=tprev><span class=tprev-nav></span><span class=tprev-head></span><span class=tprev-panel></span><span class=tprev-line style=left:32%;top:38%;width:34%;opacity:0.85></span><span class=tprev-line style=left:32%;top:50%;width:22%></span><span class=tprev-line style=left:32%;top:62%;width:40%></span><span class=tprev-dot style=left:6%;top:20%></span><span class=tprev-dot style=left:6%;top:40%></span><span class=tprev-dot style=left:6%;top:60%></span><span class=tprev-dot style=left:70%;top:12%></span><span class=tprev-dot style=left:84%;top:12%>`);function _f(e){let t=Number(localStorage.getItem(`teapot.todoH`)??``),[n,r]=y(Number.isFinite(t)&&t>0?t:0),i=()=>n()>0?{height:`${n()}px`}:void 0,a=e=>{let t=new ResizeObserver(()=>{let t=e.offsetHeight;t<=0||r(e=>Math.abs(e-t)<1?e:(localStorage.setItem(`teapot.todoH`,String(t)),t))});t.observe(e),T(()=>t.disconnect())};return A(M,{get when(){return e.preview},get fallback(){return(()=>{var t=cf();return t.$$input=t=>e.onDraft(t.currentTarget.value),je(a,t),b(e=>ke(t,i(),e)),b(()=>t.value=e.draft),t})()},get children(){var t=sf();return je(a,t),b(n=>{var r=i(),a=dt(e.draft);return n.e=ke(t,r,n.e),a!==n.t&&(t.innerHTML=n.t=a),n},{e:void 0,t:void 0}),t}})}function vf(e){return[A(M,{get when(){return e.html},get fallback(){return N(()=>!!e.pending)()?(()=>{var t=df(),n=t.firstChild.nextSibling;return n.nextSibling,L(t,()=>e.path.split(`/`).pop(),n),t})():(()=>{var t=ff();return L(t,()=>e.content),t})()},get children(){var t=lf();return b(()=>t.innerHTML=e.html),t}}),A(M,{get when(){return e.truncated},get children(){return uf()}})]}function yf(e){return(()=>{var t=pf(),n=t.firstChild;return L(t,()=>e.label,n),n.$$input=t=>e.onValue(Number(t.currentTarget.value)),b(()=>F(t,`title`,e.hint)),b(()=>n.value=e.value),t})()}function bf(e){let t=()=>e.palette,n=()=>rf(e.surfaceAlpha,e.backgroundDim);return(()=>{var r=gf(),i=r.firstChild,a=i.nextSibling,o=a.nextSibling,s=o.nextSibling,c=s.nextSibling,l=c.nextSibling,u=l.nextSibling,d=u.nextSibling,f=d.nextSibling,p=f.nextSibling,m=p.nextSibling;return L(r,A(M,{get when(){return e.backgroundImage},get children(){return[(()=>{var t=mf();return b(n=>Ae(t,`background-image`,of(e.backgroundImage,ln))),t})(),(()=>{var e=hf();return b(r=>Ae(e,`background`,af(t().bgDark,n().dim))),e})()]}}),i),b(h=>{var g=t().bgDark,_=t().bgDarkest,v=e.backgroundImage?String(n().panel):`1`,ee=t().bgDarkest,y=e.backgroundImage?String(n().panel):`1`,b=t().bgMid,x=e.backgroundImage?String(n().raised):`1`,S=t().fg,C=t().acc,w=t().dim,T=t().acc,te=t().dim,E=t().ok,D=t().warn,ne=t().err;return g!==h.e&&Ae(r,`background`,h.e=g),_!==h.t&&Ae(i,`background`,h.t=_),v!==h.a&&Ae(i,`opacity`,h.a=v),ee!==h.o&&Ae(a,`background`,h.o=ee),y!==h.i&&Ae(a,`opacity`,h.i=y),b!==h.n&&Ae(o,`background`,h.n=b),x!==h.s&&Ae(o,`opacity`,h.s=x),S!==h.h&&Ae(s,`background`,h.h=S),C!==h.r&&Ae(c,`background`,h.r=C),w!==h.d&&Ae(l,`background`,h.d=w),T!==h.l&&Ae(u,`background`,h.l=T),te!==h.u&&Ae(d,`background`,h.u=te),E!==h.c&&Ae(f,`background`,h.c=E),D!==h.w&&Ae(p,`background`,h.w=D),ne!==h.m&&Ae(m,`background`,h.m=ne),h},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0,r:void 0,d:void 0,l:void 0,u:void 0,c:void 0,w:void 0,m:void 0}),r})()}De([`input`]);var[xf,Sf]=y(``),Cf,wf=e=>{Sf(e),clearTimeout(Cf),Cf=setTimeout(()=>Sf(``),3200)};function Tf(e,t){if(!t.startsWith(`blobs/`)||!e)return t;let n=t.slice(6);return`/api/agents/${encodeURIComponent(e)}/blobs/${encodeURIComponent(n)}`}var Ef=class extends Error{constructor(e){super(e),this.name=`ShikiError`}};function Df(e){return Of(e)}function Of(e){return Array.isArray(e)?kf(e):e instanceof RegExp?e:typeof e==`object`?Af(e):e}function kf(e){let t=[];for(let n=0,r=e.length;n<r;n++)t[n]=Of(e[n]);return t}function Af(e){let t={};for(let n in e)t[n]=Of(e[n]);return t}function jf(e,...t){return t.forEach(t=>{for(let n in t)e[n]=t[n]}),e}function Mf(e){let t=~e.lastIndexOf(`/`)||~e.lastIndexOf(`\\`);return t===0?e:~t===e.length-1?Mf(e.substring(0,e.length-1)):e.substr(~t+1)}var Nf=/\$(\d+)|\${(\d+):\/(downcase|upcase)}/g,Pf=class{static hasCaptures(e){return e!==null&&(Nf.lastIndex=0,Nf.test(e))}static replaceCaptures(e,t,n){return e.replace(Nf,(e,r,i,a)=>{let o=n[parseInt(r||i,10)];if(o){let e=t.substring(o.start,o.end);for(;e[0]===`.`;)e=e.substring(1);switch(a){case`downcase`:return e.toLowerCase();case`upcase`:return e.toUpperCase();default:return e}}else return e})}};function Ff(e,t){return e<t?-1:+(e>t)}function If(e,t){if(e===null&&t===null)return 0;if(!e)return-1;if(!t)return 1;let n=e.length,r=t.length;if(n===r){for(let r=0;r<n;r++){let n=Ff(e[r],t[r]);if(n!==0)return n}return 0}return n-r}function Lf(e){return!!(/^#[0-9a-f]{6}$/i.test(e)||/^#[0-9a-f]{8}$/i.test(e)||/^#[0-9a-f]{3}$/i.test(e)||/^#[0-9a-f]{4}$/i.test(e))}function Rf(e){return e.replace(/[\-\\\{\}\*\+\?\|\^\$\.\,\[\]\(\)\#\s]/g,`\\$&`)}var zf=class{constructor(e){this.fn=e}cache=new Map;get(e){if(this.cache.has(e))return this.cache.get(e);let t=this.fn(e);return this.cache.set(e,t),t}},Bf=class{constructor(e,t,n){this._colorMap=e,this._defaults=t,this._root=n}static createFromRawTheme(e,t){return this.createFromParsedTheme(Gf(e),t)}static createFromParsedTheme(e,t){return Jf(e,t)}_cachedMatchRoot=new zf(e=>this._root.match(e));getColorMap(){return this._colorMap.getColorMap()}getDefaults(){return this._defaults}match(e){if(e===null)return this._defaults;let t=e.scopeName,n=this._cachedMatchRoot.get(t).find(t=>Hf(e.parent,t.parentScopes));return n?new Wf(n.fontStyle,n.foreground,n.background):null}},Vf=class e{constructor(e,t){this.parent=e,this.scopeName=t}static push(t,n){for(let r of n)t=new e(t,r);return t}static from(...t){let n=null;for(let r=0;r<t.length;r++)n=new e(n,t[r]);return n}push(t){return new e(this,t)}getSegments(){let e=this,t=[];for(;e;)t.push(e.scopeName),e=e.parent;return t.reverse(),t}toString(){return this.getSegments().join(` `)}extends(e){return this===e||this.parent!==null&&this.parent.extends(e)}getExtensionIfDefined(e){let t=[],n=this;for(;n&&n!==e;)t.push(n.scopeName),n=n.parent;return n===e?t.reverse():void 0}};function Hf(e,t){if(t.length===0)return!0;for(let n=0;n<t.length;n++){let r=t[n],i=!1;if(r===`>`){if(n===t.length-1)return!1;r=t[++n],i=!0}for(;e&&!Uf(e.scopeName,r);){if(i)return!1;e=e.parent}if(!e)return!1;e=e.parent}return!0}function Uf(e,t){return t===e||e.startsWith(t)&&e[t.length]===`.`}var Wf=class{constructor(e,t,n){this.fontStyle=e,this.foregroundId=t,this.backgroundId=n}};function Gf(e){if(!e||!e.settings||!Array.isArray(e.settings))return[];let t=e.settings,n=[],r=0;for(let e=0,i=t.length;e<i;e++){let i=t[e];if(!i.settings)continue;let a;if(typeof i.scope==`string`){let e=i.scope;e=e.replace(/^[,]+/,``),e=e.replace(/[,]+$/,``),a=e.split(`,`)}else a=Array.isArray(i.scope)?i.scope:[``];let o=-1;if(typeof i.settings.fontStyle==`string`){o=0;let e=i.settings.fontStyle.split(` `);for(let t=0,n=e.length;t<n;t++)switch(e[t]){case`italic`:o|=1;break;case`bold`:o|=2;break;case`underline`:o|=4;break;case`strikethrough`:o|=8}}let s=null;typeof i.settings.foreground==`string`&&Lf(i.settings.foreground)&&(s=i.settings.foreground);let c=null;typeof i.settings.background==`string`&&Lf(i.settings.background)&&(c=i.settings.background);for(let t=0,i=a.length;t<i;t++){let i=a[t].trim().split(` `),l=i[i.length-1],u=null;i.length>1&&(u=i.slice(0,i.length-1),u.reverse()),n[r++]=new Kf(l,u,e,o,s,c)}}return n}var Kf=class{constructor(e,t,n,r,i,a){this.scope=e,this.parentScopes=t,this.index=n,this.fontStyle=r,this.foreground=i,this.background=a}},qf=(e=>(e[e.NotSet=-1]=`NotSet`,e[e.None=0]=`None`,e[e.Italic=1]=`Italic`,e[e.Bold=2]=`Bold`,e[e.Underline=4]=`Underline`,e[e.Strikethrough=8]=`Strikethrough`,e))(qf||{});function Jf(e,t){e.sort((e,t)=>{let n=Ff(e.scope,t.scope);return n!==0||(n=If(e.parentScopes,t.parentScopes),n!==0)?n:e.index-t.index});let n=0,r=`#000000`,i=`#ffffff`;for(;e.length>=1&&e[0].scope===``;){let t=e.shift();t.fontStyle!==-1&&(n=t.fontStyle),t.foreground!==null&&(r=t.foreground),t.background!==null&&(i=t.background)}let a=new Yf(t),o=new Wf(n,a.getId(r),a.getId(i)),s=new Qf(new Zf(0,null,-1,0,0),[]);for(let t=0,n=e.length;t<n;t++){let n=e[t];s.insert(0,n.scope,n.parentScopes,n.fontStyle,a.getId(n.foreground),a.getId(n.background))}return new Bf(a,o,s)}var Yf=class{_isFrozen;_lastColorId;_id2color;_color2id;constructor(e){if(this._lastColorId=0,this._id2color=[],this._color2id=Object.create(null),Array.isArray(e)){this._isFrozen=!0;for(let t=0,n=e.length;t<n;t++)this._color2id[e[t]]=t,this._id2color[t]=e[t]}else this._isFrozen=!1}getId(e){if(e===null)return 0;e=e.toUpperCase();let t=this._color2id[e];if(t)return t;if(this._isFrozen)throw Error(`Missing color in color map - ${e}`);return t=++this._lastColorId,this._color2id[e]=t,this._id2color[t]=e,t}getColorMap(){return this._id2color.slice(0)}},Xf=Object.freeze([]),Zf=class e{scopeDepth;parentScopes;fontStyle;foreground;background;constructor(e,t,n,r,i){this.scopeDepth=e,this.parentScopes=t||Xf,this.fontStyle=n,this.foreground=r,this.background=i}clone(){return new e(this.scopeDepth,this.parentScopes,this.fontStyle,this.foreground,this.background)}static cloneArr(e){let t=[];for(let n=0,r=e.length;n<r;n++)t[n]=e[n].clone();return t}acceptOverwrite(e,t,n,r){this.scopeDepth>e?console.log(`how did this happen?`):this.scopeDepth=e,t!==-1&&(this.fontStyle=t),n!==0&&(this.foreground=n),r!==0&&(this.background=r)}},Qf=class e{constructor(e,t=[],n={}){this._mainRule=e,this._children=n,this._rulesWithParentScopes=t}_rulesWithParentScopes;static _cmpBySpecificity(e,t){if(e.scopeDepth!==t.scopeDepth)return t.scopeDepth-e.scopeDepth;let n=0,r=0;for(;e.parentScopes[n]===`>`&&n++,t.parentScopes[r]===`>`&&r++,!(n>=e.parentScopes.length||r>=t.parentScopes.length);){let i=t.parentScopes[r].length-e.parentScopes[n].length;if(i!==0)return i;n++,r++}return t.parentScopes.length-e.parentScopes.length}match(t){if(t!==``){let e=t.indexOf(`.`),n,r;if(e===-1?(n=t,r=``):(n=t.substring(0,e),r=t.substring(e+1)),this._children.hasOwnProperty(n))return this._children[n].match(r)}let n=this._rulesWithParentScopes.concat(this._mainRule);return n.sort(e._cmpBySpecificity),n}insert(t,n,r,i,a,o){if(n===``){this._doInsertHere(t,r,i,a,o);return}let s=n.indexOf(`.`),c,l;s===-1?(c=n,l=``):(c=n.substring(0,s),l=n.substring(s+1));let u;this._children.hasOwnProperty(c)?u=this._children[c]:(u=new e(this._mainRule.clone(),Zf.cloneArr(this._rulesWithParentScopes)),this._children[c]=u),u.insert(t+1,l,r,i,a,o)}_doInsertHere(e,t,n,r,i){if(t===null)this._mainRule.acceptOverwrite(e,n,r,i);else{for(let a=0,o=this._rulesWithParentScopes.length;a<o;a++){let o=this._rulesWithParentScopes[a];if(If(o.parentScopes,t)===0){o.acceptOverwrite(e,n,r,i);return}}n===-1&&(n=this._mainRule.fontStyle),r===0&&(r=this._mainRule.foreground),i===0&&(i=this._mainRule.background),this._rulesWithParentScopes.push(new Zf(e,t,n,r,i))}}},$f=class e{static toBinaryStr(e){return e.toString(2).padStart(32,`0`)}static print(t){let n=e.getLanguageId(t),r=e.getTokenType(t),i=e.getFontStyle(t),a=e.getForeground(t),o=e.getBackground(t);console.log({languageId:n,tokenType:r,fontStyle:i,foreground:a,background:o})}static getLanguageId(e){return(e&255)>>>0}static getTokenType(e){return(e&768)>>>8}static containsBalancedBrackets(e){return!!(e&1024)}static getFontStyle(e){return(e&30720)>>>11}static getForeground(e){return(e&16744448)>>>15}static getBackground(e){return(e&4278190080)>>>24}static set(t,n,r,i,a,o,s){let c=e.getLanguageId(t),l=e.getTokenType(t),u=+!!e.containsBalancedBrackets(t),d=e.getFontStyle(t),f=e.getForeground(t),p=e.getBackground(t);return n!==0&&(c=n),r!==8&&(l=tp(r)),i!==null&&(u=+!!i),a!==-1&&(d=a),o!==0&&(f=o),s!==0&&(p=s),(c|0|l<<8|u<<10|d<<11|f<<15|p<<24)>>>0}};function ep(e){return e}function tp(e){return e}function np(e,t){let n=[],r=ip(e),i=r.next();for(;i!==null;){let e=0;if(i.length===2&&i.charAt(1)===`:`){switch(i.charAt(0)){case`R`:e=1;break;case`L`:e=-1;break;default:console.log(`Unknown priority ${i} in scope selector`)}i=r.next()}let t=o();if(n.push({matcher:t,priority:e}),i!==`,`)break;i=r.next()}return n;function a(){if(i===`-`){i=r.next();let e=a();return t=>!!e&&!e(t)}if(i===`(`){i=r.next();let e=s();return i===`)`&&(i=r.next()),e}if(rp(i)){let e=[];do e.push(i),i=r.next();while(rp(i));return n=>t(e,n)}return null}function o(){let e=[],t=a();for(;t;)e.push(t),t=a();return t=>e.every(e=>e(t))}function s(){let e=[],t=o();for(;t&&(e.push(t),i===`|`||i===`,`);){do i=r.next();while(i===`|`||i===`,`);t=o()}return t=>e.some(e=>e(t))}}function rp(e){return!!e&&!!e.match(/[\w\.:]+/)}function ip(e){let t=/([LR]:|[\w\.:][\w\.:\-]*|[\,\|\-\(\)])/g,n=t.exec(e);return{next:()=>{if(!n)return null;let r=n[0];return n=t.exec(e),r}}}function ap(e){typeof e.dispose==`function`&&e.dispose()}var op=class{constructor(e){this.scopeName=e}toKey(){return this.scopeName}},sp=class{constructor(e,t){this.scopeName=e,this.ruleName=t}toKey(){return`${this.scopeName}#${this.ruleName}`}},cp=class{_references=[];_seenReferenceKeys=new Set;get references(){return this._references}visitedRule=new Set;add(e){let t=e.toKey();this._seenReferenceKeys.has(t)||(this._seenReferenceKeys.add(t),this._references.push(e))}},lp=class{constructor(e,t){this.repo=e,this.initialScopeName=t,this.seenFullScopeRequests.add(this.initialScopeName),this.Q=[new op(this.initialScopeName)]}seenFullScopeRequests=new Set;seenPartialScopeRequests=new Set;Q;processQueue(){let e=this.Q;this.Q=[];let t=new cp;for(let n of e)up(n,this.initialScopeName,this.repo,t);for(let e of t.references)if(e instanceof op){if(this.seenFullScopeRequests.has(e.scopeName))continue;this.seenFullScopeRequests.add(e.scopeName),this.Q.push(e)}else{if(this.seenFullScopeRequests.has(e.scopeName)||this.seenPartialScopeRequests.has(e.toKey()))continue;this.seenPartialScopeRequests.add(e.toKey()),this.Q.push(e)}}};function up(e,t,n,r){let i=n.lookup(e.scopeName);if(!i){if(e.scopeName===t)throw Error(`No grammar provided for <${t}>`);return}let a=n.lookup(t);e instanceof op?fp({baseGrammar:a,selfGrammar:i},r):dp(e.ruleName,{baseGrammar:a,selfGrammar:i,repository:i.repository},r);let o=n.injections(e.scopeName);if(o)for(let e of o)r.add(new op(e))}function dp(e,t,n){if(t.repository&&t.repository[e]){let r=t.repository[e];pp([r],t,n)}}function fp(e,t){e.selfGrammar.patterns&&Array.isArray(e.selfGrammar.patterns)&&pp(e.selfGrammar.patterns,{...e,repository:e.selfGrammar.repository},t),e.selfGrammar.injections&&pp(Object.values(e.selfGrammar.injections),{...e,repository:e.selfGrammar.repository},t)}function pp(e,t,n){for(let r of e){if(n.visitedRule.has(r))continue;n.visitedRule.add(r);let e=r.repository?jf({},t.repository,r.repository):t.repository;Array.isArray(r.patterns)&&pp(r.patterns,{...t,repository:e},n);let i=r.include;if(!i)continue;let a=yp(i);switch(a.kind){case 0:fp({...t,selfGrammar:t.baseGrammar},n);break;case 1:fp(t,n);break;case 2:dp(a.ruleName,{...t,repository:e},n);break;case 3:case 4:let r=a.scopeName===t.selfGrammar.scopeName?t.selfGrammar:a.scopeName===t.baseGrammar.scopeName?t.baseGrammar:void 0;if(r){let i={baseGrammar:t.baseGrammar,selfGrammar:r,repository:e};a.kind===4?dp(a.ruleName,i,n):fp(i,n)}else a.kind===4?n.add(new sp(a.scopeName,a.ruleName)):n.add(new op(a.scopeName))}}}var mp=class{kind=0},hp=class{kind=1},gp=class{constructor(e){this.ruleName=e}kind=2},_p=class{constructor(e){this.scopeName=e}kind=3},vp=class{constructor(e,t){this.scopeName=e,this.ruleName=t}kind=4};function yp(e){if(e===`$base`)return new mp;if(e===`$self`)return new hp;let t=e.indexOf(`#`);return t===-1?new _p(e):t===0?new gp(e.substring(1)):new vp(e.substring(0,t),e.substring(t+1))}var bp=/\\(\d+)/,xp=/\\(\d+)/g,Sp=-1,Cp=-2;function wp(e){return e}function Tp(e){return e}var Ep=class{$location;id;_nameIsCapturing;_name;_contentNameIsCapturing;_contentName;constructor(e,t,n,r){this.$location=e,this.id=t,this._name=n||null,this._nameIsCapturing=Pf.hasCaptures(this._name),this._contentName=r||null,this._contentNameIsCapturing=Pf.hasCaptures(this._contentName)}get debugName(){let e=this.$location?`${Mf(this.$location.filename)}:${this.$location.line}`:`unknown`;return`${this.constructor.name}#${this.id} @ ${e}`}getName(e,t){return!this._nameIsCapturing||this._name===null||e===null||t===null?this._name:Pf.replaceCaptures(this._name,e,t)}getContentName(e,t){return!this._contentNameIsCapturing||this._contentName===null?this._contentName:Pf.replaceCaptures(this._contentName,e,t)}},Dp=class extends Ep{retokenizeCapturedWithRuleId;constructor(e,t,n,r,i){super(e,t,n,r),this.retokenizeCapturedWithRuleId=i}dispose(){}collectPatterns(e,t){throw Error(`Not supported!`)}compile(e,t){throw Error(`Not supported!`)}compileAG(e,t,n,r){throw Error(`Not supported!`)}},Op=class extends Ep{_match;captures;_cachedCompiledPatterns;constructor(e,t,n,r,i){super(e,t,n,null),this._match=new Np(r,this.id),this.captures=i,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&=(this._cachedCompiledPatterns.dispose(),null)}get debugMatchRegExp(){return`${this._match.source}`}collectPatterns(e,t){t.push(this._match)}compile(e,t){return this._getCachedCompiledPatterns(e).compile(e)}compileAG(e,t,n,r){return this._getCachedCompiledPatterns(e).compileAG(e,n,r)}_getCachedCompiledPatterns(e){return this._cachedCompiledPatterns||(this._cachedCompiledPatterns=new Pp,this.collectPatterns(e,this._cachedCompiledPatterns)),this._cachedCompiledPatterns}},kp=class extends Ep{hasMissingPatterns;patterns;_cachedCompiledPatterns;constructor(e,t,n,r,i){super(e,t,n,r),this.patterns=i.patterns,this.hasMissingPatterns=i.hasMissingPatterns,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&=(this._cachedCompiledPatterns.dispose(),null)}collectPatterns(e,t){for(let n of this.patterns)e.getRule(n).collectPatterns(e,t)}compile(e,t){return this._getCachedCompiledPatterns(e).compile(e)}compileAG(e,t,n,r){return this._getCachedCompiledPatterns(e).compileAG(e,n,r)}_getCachedCompiledPatterns(e){return this._cachedCompiledPatterns||(this._cachedCompiledPatterns=new Pp,this.collectPatterns(e,this._cachedCompiledPatterns)),this._cachedCompiledPatterns}},Ap=class extends Ep{_begin;beginCaptures;_end;endHasBackReferences;endCaptures;applyEndPatternLast;hasMissingPatterns;patterns;_cachedCompiledPatterns;constructor(e,t,n,r,i,a,o,s,c,l){super(e,t,n,r),this._begin=new Np(i,this.id),this.beginCaptures=a,this._end=new Np(o||`￿`,-1),this.endHasBackReferences=this._end.hasBackReferences,this.endCaptures=s,this.applyEndPatternLast=c||!1,this.patterns=l.patterns,this.hasMissingPatterns=l.hasMissingPatterns,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&=(this._cachedCompiledPatterns.dispose(),null)}get debugBeginRegExp(){return`${this._begin.source}`}get debugEndRegExp(){return`${this._end.source}`}getEndWithResolvedBackReferences(e,t){return this._end.resolveBackReferences(e,t)}collectPatterns(e,t){t.push(this._begin)}compile(e,t){return this._getCachedCompiledPatterns(e,t).compile(e)}compileAG(e,t,n,r){return this._getCachedCompiledPatterns(e,t).compileAG(e,n,r)}_getCachedCompiledPatterns(e,t){if(!this._cachedCompiledPatterns){this._cachedCompiledPatterns=new Pp;for(let t of this.patterns)e.getRule(t).collectPatterns(e,this._cachedCompiledPatterns);this.applyEndPatternLast?this._cachedCompiledPatterns.push(this._end.hasBackReferences?this._end.clone():this._end):this._cachedCompiledPatterns.unshift(this._end.hasBackReferences?this._end.clone():this._end)}return this._end.hasBackReferences&&(this.applyEndPatternLast?this._cachedCompiledPatterns.setSource(this._cachedCompiledPatterns.length()-1,t):this._cachedCompiledPatterns.setSource(0,t)),this._cachedCompiledPatterns}},jp=class extends Ep{_begin;beginCaptures;whileCaptures;_while;whileHasBackReferences;hasMissingPatterns;patterns;_cachedCompiledPatterns;_cachedCompiledWhilePatterns;constructor(e,t,n,r,i,a,o,s,c){super(e,t,n,r),this._begin=new Np(i,this.id),this.beginCaptures=a,this.whileCaptures=s,this._while=new Np(o,Cp),this.whileHasBackReferences=this._while.hasBackReferences,this.patterns=c.patterns,this.hasMissingPatterns=c.hasMissingPatterns,this._cachedCompiledPatterns=null,this._cachedCompiledWhilePatterns=null}dispose(){this._cachedCompiledPatterns&&=(this._cachedCompiledPatterns.dispose(),null),this._cachedCompiledWhilePatterns&&=(this._cachedCompiledWhilePatterns.dispose(),null)}get debugBeginRegExp(){return`${this._begin.source}`}get debugWhileRegExp(){return`${this._while.source}`}getWhileWithResolvedBackReferences(e,t){return this._while.resolveBackReferences(e,t)}collectPatterns(e,t){t.push(this._begin)}compile(e,t){return this._getCachedCompiledPatterns(e).compile(e)}compileAG(e,t,n,r){return this._getCachedCompiledPatterns(e).compileAG(e,n,r)}_getCachedCompiledPatterns(e){if(!this._cachedCompiledPatterns){this._cachedCompiledPatterns=new Pp;for(let t of this.patterns)e.getRule(t).collectPatterns(e,this._cachedCompiledPatterns)}return this._cachedCompiledPatterns}compileWhile(e,t){return this._getCachedCompiledWhilePatterns(e,t).compile(e)}compileWhileAG(e,t,n,r){return this._getCachedCompiledWhilePatterns(e,t).compileAG(e,n,r)}_getCachedCompiledWhilePatterns(e,t){return this._cachedCompiledWhilePatterns||(this._cachedCompiledWhilePatterns=new Pp,this._cachedCompiledWhilePatterns.push(this._while.hasBackReferences?this._while.clone():this._while)),this._while.hasBackReferences&&this._cachedCompiledWhilePatterns.setSource(0,t||`￿`),this._cachedCompiledWhilePatterns}},Mp=class e{static createCaptureRule(e,t,n,r,i){return e.registerRule(e=>new Dp(t,e,n,r,i))}static getCompiledRuleId(t,n,r){return t.id||n.registerRule(i=>{if(t.id=i,t.match)return new Op(t.$vscodeTextmateLocation,t.id,t.name,t.match,e._compileCaptures(t.captures,n,r));if(t.begin===void 0){t.repository&&(r=jf({},r,t.repository));let i=t.patterns;return i===void 0&&t.include&&(i=[{include:t.include}]),new kp(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,e._compilePatterns(i,n,r))}return t.while?new jp(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,t.begin,e._compileCaptures(t.beginCaptures||t.captures,n,r),t.while,e._compileCaptures(t.whileCaptures||t.captures,n,r),e._compilePatterns(t.patterns,n,r)):new Ap(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,t.begin,e._compileCaptures(t.beginCaptures||t.captures,n,r),t.end,e._compileCaptures(t.endCaptures||t.captures,n,r),t.applyEndPatternLast,e._compilePatterns(t.patterns,n,r))}),t.id}static _compileCaptures(t,n,r){let i=[];if(t){let a=0;for(let e in t){if(e===`$vscodeTextmateLocation`)continue;let t=parseInt(e,10);t>a&&(a=t)}for(let e=0;e<=a;e++)i[e]=null;for(let a in t){if(a===`$vscodeTextmateLocation`)continue;let o=parseInt(a,10),s=0;t[a].patterns&&(s=e.getCompiledRuleId(t[a],n,r)),i[o]=e.createCaptureRule(n,t[a].$vscodeTextmateLocation,t[a].name,t[a].contentName,s)}}return i}static _compilePatterns(t,n,r){let i=[];if(t)for(let a=0,o=t.length;a<o;a++){let o=t[a],s=-1;if(o.include){let t=yp(o.include);switch(t.kind){case 0:case 1:s=e.getCompiledRuleId(r[o.include],n,r);break;case 2:let i=r[t.ruleName];i&&(s=e.getCompiledRuleId(i,n,r));break;case 3:case 4:let a=t.scopeName,c=t.kind===4?t.ruleName:null,l=n.getExternalGrammar(a,r);if(l){if(c){let t=l.repository[c];t&&(s=e.getCompiledRuleId(t,n,l.repository))}else s=e.getCompiledRuleId(l.repository.$self,n,l.repository)}}}else s=e.getCompiledRuleId(o,n,r);if(s!==-1){let e=n.getRule(s),t=!1;if((e instanceof kp||e instanceof Ap||e instanceof jp)&&e.hasMissingPatterns&&e.patterns.length===0&&(t=!0),t)continue;i.push(s)}}return{patterns:i,hasMissingPatterns:(t?t.length:0)!==i.length}}},Np=class e{source;ruleId;hasAnchor;hasBackReferences;_anchorCache;constructor(e,t){if(e&&typeof e==`string`){let t=e.length,n=0,r=[],i=!1;for(let a=0;a<t;a++)if(e.charAt(a)===`\\`&&a+1<t){let t=e.charAt(a+1);t===`z`?(r.push(e.substring(n,a)),r.push(`$(?!\\n)(?<!\\n)`),n=a+2):(t===`A`||t===`G`)&&(i=!0),a++}this.hasAnchor=i,n===0?this.source=e:(r.push(e.substring(n,t)),this.source=r.join(``))}else this.hasAnchor=!1,this.source=e;this._anchorCache=this.hasAnchor?this._buildAnchorCache():null,this.ruleId=t,this.hasBackReferences=typeof this.source==`string`&&bp.test(this.source)}clone(){return new e(this.source,this.ruleId)}setSource(e){this.source!==e&&(this.source=e,this.hasAnchor&&(this._anchorCache=this._buildAnchorCache()))}resolveBackReferences(e,t){if(typeof this.source!=`string`)throw Error(`This method should only be called if the source is a string`);let n=t.map(t=>e.substring(t.start,t.end));return xp.lastIndex=0,this.source.replace(xp,(e,t)=>Rf(n[parseInt(t,10)]||``))}_buildAnchorCache(){if(typeof this.source!=`string`)throw Error(`This method should only be called if the source is a string`);let e=[],t=[],n=[],r=[],i,a,o,s;for(i=0,a=this.source.length;i<a;i++)o=this.source.charAt(i),e[i]=o,t[i]=o,n[i]=o,r[i]=o,o===`\\`&&i+1<a&&(s=this.source.charAt(i+1),s===`A`?(e[i+1]=`￿`,t[i+1]=`￿`,n[i+1]=`A`,r[i+1]=`A`):s===`G`?(e[i+1]=`￿`,t[i+1]=`G`,n[i+1]=`￿`,r[i+1]=`G`):(e[i+1]=s,t[i+1]=s,n[i+1]=s,r[i+1]=s),i++);return{A0_G0:e.join(``),A0_G1:t.join(``),A1_G0:n.join(``),A1_G1:r.join(``)}}resolveAnchors(e,t){return!this.hasAnchor||!this._anchorCache||typeof this.source!=`string`?this.source:e?t?this._anchorCache.A1_G1:this._anchorCache.A1_G0:t?this._anchorCache.A0_G1:this._anchorCache.A0_G0}},Pp=class{_items;_hasAnchors;_cached;_anchorCache;constructor(){this._items=[],this._hasAnchors=!1,this._cached=null,this._anchorCache={A0_G0:null,A0_G1:null,A1_G0:null,A1_G1:null}}dispose(){this._disposeCaches()}_disposeCaches(){this._cached&&=(this._cached.dispose(),null),this._anchorCache.A0_G0&&(this._anchorCache.A0_G0.dispose(),this._anchorCache.A0_G0=null),this._anchorCache.A0_G1&&(this._anchorCache.A0_G1.dispose(),this._anchorCache.A0_G1=null),this._anchorCache.A1_G0&&(this._anchorCache.A1_G0.dispose(),this._anchorCache.A1_G0=null),this._anchorCache.A1_G1&&(this._anchorCache.A1_G1.dispose(),this._anchorCache.A1_G1=null)}push(e){this._items.push(e),this._hasAnchors=this._hasAnchors||e.hasAnchor}unshift(e){this._items.unshift(e),this._hasAnchors=this._hasAnchors||e.hasAnchor}length(){return this._items.length}setSource(e,t){this._items[e].source!==t&&(this._disposeCaches(),this._items[e].setSource(t))}compile(e){if(!this._cached){let t=this._items.map(e=>e.source);this._cached=new Fp(e,t,this._items.map(e=>e.ruleId))}return this._cached}compileAG(e,t,n){return this._hasAnchors?t?n?(this._anchorCache.A1_G1||(this._anchorCache.A1_G1=this._resolveAnchors(e,t,n)),this._anchorCache.A1_G1):(this._anchorCache.A1_G0||(this._anchorCache.A1_G0=this._resolveAnchors(e,t,n)),this._anchorCache.A1_G0):n?(this._anchorCache.A0_G1||(this._anchorCache.A0_G1=this._resolveAnchors(e,t,n)),this._anchorCache.A0_G1):(this._anchorCache.A0_G0||(this._anchorCache.A0_G0=this._resolveAnchors(e,t,n)),this._anchorCache.A0_G0):this.compile(e)}_resolveAnchors(e,t,n){return new Fp(e,this._items.map(e=>e.resolveAnchors(t,n)),this._items.map(e=>e.ruleId))}},Fp=class{constructor(e,t,n){this.regExps=t,this.rules=n,this.scanner=e.createOnigScanner(t)}scanner;dispose(){typeof this.scanner.dispose==`function`&&this.scanner.dispose()}toString(){let e=[];for(let t=0,n=this.rules.length;t<n;t++)e.push(` - `+this.rules[t]+`: `+this.regExps[t]);return e.join(`
23
+ `,t++;continue}r=``}else r+=a}return i(),t}function jd(e){return Ad(e).map(e=>e.text).join(``)}function Md(e){return e.includes(`\x1B`)}var Nd=400,Pd=new Map;function Fd(e){return Pd.get(e)}function Id(e,t){if(Pd.size>=Nd){let e=Pd.keys().next();e.done||Pd.delete(e.value)}Pd.set(e,t)}var Ld=`modulepreload`,Rd=function(e){return`/`+e},zd={},Bd=function(e){return e.pathname.endsWith(`.css`)},Vd=function(e,t,n){if(t in e)return e[t];let r=n();if(!r){e[t]=void 0;return}let i=r.then(()=>{e[t]=void 0},n=>{throw e[t]=void 0,n});return e[t]=i,i},Y=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e,i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?new URL(import.meta.resolve(e)):new URL(e,import.meta.url)}r=o(t.map(t=>{t=Rd(t,n);let r=s(t),i=Bd(r);return Vd(zd,r.href,()=>{if(e===void 0){e={all:new Set,styles:new Set};let t=document.getElementsByTagName(`link`);for(let n=t.length-1;n>=0;n--){let r=t[n];e.all.add(r.href),r.rel===`stylesheet`&&e.styles.add(r.href)}}if((i?e.styles:e.all).has(r.href))return;let t=document.createElement(`link`);if(t.rel=i?`stylesheet`:Ld,i||(t.as=`script`),t.crossOrigin=``,t.href=r.href,a&&t.setAttribute(`nonce`,a),document.head.appendChild(t),i)return new Promise((e,n)=>{t.addEventListener(`load`,e),t.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${r}`)))})})}).filter(e=>e!==void 0))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},Hd=F(`<span class=bashelapsed>running… `),Ud=F(`<span class=bashelapsed> elapsed`),Wd=F(`<span class=thinktimer>`),Gd=F(`<pre class="mono toolbody ansi">`),Kd=F(`<pre class="mono toolbody">`),qd=F(`<span>`),Jd=F(`<div class="toolbody shiki">`);function Yd(e){let t=new Date(e.startedAt).getTime(),[n,r]=y(Date.now());w(()=>{let e=setInterval(()=>r(Date.now()),500);T(()=>clearInterval(e))});let i=()=>dt(Math.max(0,n()-t));return e.inline?(()=>{var t=Hd();return t.firstChild,R(t,i,null),R(t,(()=>{var t=P(()=>!!e.timeoutMs);return()=>t()?` · timeout ${Math.round(e.timeoutMs/1e3)}s`:``})(),null),t})():(()=>{var e=Ud(),t=e.firstChild;return R(e,i,t),e})()}function Xd(e){let[t,n]=y(Date.now());w(()=>{let e=setInterval(()=>n(Date.now()),500);T(()=>clearInterval(e))});let r=()=>{if(!e.startedAt)return null;let n=Math.max(0,t()-e.startedAt);return n>864e5?null:dt(n)};return j(N,{get when(){return r()!==null},fallback:null,get children(){var e=Wd();return R(e,r),e}})}function Zd(e){let t=S(()=>Md(e.text)?Ad(e.text):null);return j(N,{get when(){return t()},get fallback(){return(()=>{var t=Kd();return R(t,()=>e.text),t})()},get children(){var e=Gd();return R(e,j(M,{get each(){return t()},children:e=>e.classes.length?(()=>{var t=qd();return R(t,()=>e.text),b(()=>L(t,e.classes.join(` `))),t})():e.text})),e}})}function Qd(e){let t=()=>e.lang?`${e.lang}::${e.text.length}::${e.text}`:``,[n,r]=y((e.lang?Fd(t()):void 0)??``);return x(()=>{let n=t(),i=e.text,a=e.lang;if(!a||!i.trim()){r(``);return}let o=Fd(n);o===void 0?(async()=>{try{let{highlightLangChunks:e}=await Y(async()=>{let{highlightLangChunks:e}=await Promise.resolve().then(()=>vx);return{highlightLangChunks:e}},void 0),o=``;for await(let t of e(a,i))o+=t;if(!o)return;Id(n,o),t()===n&&r(o)}catch{}})():r(o)}),j(N,{get when(){return!!n()},get fallback(){return(()=>{var t=Kd();return R(t,()=>e.text),t})()},get children(){var e=Jd();return b(()=>e.innerHTML=n()),e}})}var $d=[{key:`dark`,label:`Dark`,mode:`dark`,sw:[`#1a1c22`,`#2b2e39`,`#5865f2`]},{key:`midnight`,label:`Midnight`,mode:`dark`,sw:[`#0d0f18`,`#252a42`,`#8b7cf7`]},{key:`tea`,label:`Milk Tea`,mode:`dark`,sw:[`#241c16`,`#493b2d`,`#d98e32`]},{key:`coffee`,label:`Coffee`,mode:`dark`,sw:[`#191410`,`#403527`,`#c68a4b`]},{key:`matcha`,label:`Matcha`,mode:`dark`,sw:[`#1b2217`,`#3c4a33`,`#8db64e`]},{key:`matrix`,label:`Matrix`,mode:`dark`,sw:[`#060a06`,`#18301d`,`#2fd558`]},{key:`sunset`,label:`Sunset`,mode:`dark`,sw:[`#1c1422`,`#452f52`,`#f2784b`]},{key:`sakura`,label:`Sakura`,mode:`dark`,sw:[`#22131f`,`#3f213a`,`#f2558e`]},{key:`light`,label:`Light`,mode:`light`,sw:[`#eceef4`,`#ffffff`,`#4757d8`]},{key:`strawberry`,label:`Strawberry`,mode:`light`,sw:[`#fbe4ea`,`#fffafb`,`#e05575`]},{key:`ramune`,label:`Ramune`,mode:`light`,sw:[`#ddeff7`,`#fbfeff`,`#1d86ae`]}];async function X(e,t){let n=localStorage.getItem(`teapot.token`),r=new Headers(t?.headers);n&&!r.has(`authorization`)&&r.set(`authorization`,`Bearer ${n}`);let i=await fetch(e,{...t,headers:r});if(!i.ok){i.status===401&&window.dispatchEvent(new CustomEvent(`teapot:unauthorized`));let t=null;try{t=await i.json()}catch{}let n=(t&&typeof t==`object`&&`error`in t?String(t.error):``)||`${e}: HTTP ${i.status}`;throw Object.assign(Error(n),{payload:t})}return i.json()}var ef=.82,tf=.9,nf=e=>{if(Number.isFinite(e))return e<0?0:e>1?1:e};function rf(e,t){let n=nf(e??ef)??ef;return{dim:nf(t??tf)??tf,panel:Math.max(0,Math.min(1,n-.05)),raised:Math.max(0,Math.min(1,n+.06))}}function af(e,t){return`color-mix(in srgb, ${e} ${Math.round((nf(t)??tf)*100)}%, transparent)`}function of(e,t){let n=e?.trim();if(n)return`url("${(t?un(n,t)??n:n).replace(/"/g,`%22`)}")`}var sf=F(`<div class="content mdpreview todopane">`),cf=F(`<textarea id=todo-input class="mono todopane-edit"rows=5 placeholder="- [ ] task one
24
+ - [ ] task two"title="shared with the agent \\u2014 it may check items off via set_todo; your unsaved edits win until you save">`),lf=F(`<div class="filepreview shikiwrap">`),uf=F(`<div class=muted style=padding-top:6px;font-size:11.5px>… truncated (first 100 KB)`),df=F(`<div class=muted style=padding:8px;font-size:12px>✨ highlighting <!>…`),ff=F(`<pre class=mono style=max-height:62vh;overflow:auto;white-space:pre-wrap;margin:0>`),pf=F(`<label><input type=number min=0>`),mf=F(`<span class=tprev-bg>`),hf=F(`<span class=tprev-veil>`),gf=F(`<span class=tprev><span class=tprev-nav></span><span class=tprev-head></span><span class=tprev-panel></span><span class=tprev-line style=left:32%;top:38%;width:34%;opacity:0.85></span><span class=tprev-line style=left:32%;top:50%;width:22%></span><span class=tprev-line style=left:32%;top:62%;width:40%></span><span class=tprev-dot style=left:6%;top:20%></span><span class=tprev-dot style=left:6%;top:40%></span><span class=tprev-dot style=left:6%;top:60%></span><span class=tprev-dot style=left:70%;top:12%></span><span class=tprev-dot style=left:84%;top:12%>`);function _f(e){let t=Number(localStorage.getItem(`teapot.todoH`)??``),[n,r]=y(Number.isFinite(t)&&t>0?t:0),i=()=>n()>0?{height:`${n()}px`}:void 0,a=e=>{let t=new ResizeObserver(()=>{let t=e.offsetHeight;t<=0||r(e=>Math.abs(e-t)<1?e:(localStorage.setItem(`teapot.todoH`,String(t)),t))});t.observe(e),T(()=>t.disconnect())};return j(N,{get when(){return e.preview},get fallback(){return(()=>{var t=cf();return t.$$input=t=>e.onDraft(t.currentTarget.value),Ae(a,t),b(e=>Oe(t,i(),e)),b(()=>t.value=e.draft),t})()},get children(){var t=sf();return Ae(a,t),b(n=>{var r=i(),a=ut(e.draft);return n.e=Oe(t,r,n.e),a!==n.t&&(t.innerHTML=n.t=a),n},{e:void 0,t:void 0}),t}})}function vf(e){return[j(N,{get when(){return e.html},get fallback(){return P(()=>!!e.pending)()?(()=>{var t=df(),n=t.firstChild.nextSibling;return n.nextSibling,R(t,()=>e.path.split(`/`).pop(),n),t})():(()=>{var t=ff();return R(t,()=>e.content),t})()},get children(){var t=lf();return b(()=>t.innerHTML=e.html),t}}),j(N,{get when(){return e.truncated},get children(){return uf()}})]}function yf(e){return(()=>{var t=pf(),n=t.firstChild;return R(t,()=>e.label,n),n.$$input=t=>e.onValue(Number(t.currentTarget.value)),b(()=>I(t,`title`,e.hint)),b(()=>n.value=e.value),t})()}function bf(e){let t=()=>e.palette,n=()=>rf(e.surfaceAlpha,e.backgroundDim);return(()=>{var r=gf(),i=r.firstChild,a=i.nextSibling,o=a.nextSibling,s=o.nextSibling,c=s.nextSibling,l=c.nextSibling,u=l.nextSibling,d=u.nextSibling,f=d.nextSibling,p=f.nextSibling,m=p.nextSibling;return R(r,j(N,{get when(){return e.backgroundImage},get children(){return[(()=>{var t=mf();return b(n=>ke(t,`background-image`,of(e.backgroundImage,cn))),t})(),(()=>{var e=hf();return b(r=>ke(e,`background`,af(t().bgDark,n().dim))),e})()]}}),i),b(h=>{var g=t().bgDark,_=t().bgDarkest,v=e.backgroundImage?String(n().panel):`1`,ee=t().bgDarkest,y=e.backgroundImage?String(n().panel):`1`,b=t().bgMid,x=e.backgroundImage?String(n().raised):`1`,S=t().fg,C=t().acc,w=t().dim,T=t().acc,E=t().dim,D=t().ok,O=t().warn,te=t().err;return g!==h.e&&ke(r,`background`,h.e=g),_!==h.t&&ke(i,`background`,h.t=_),v!==h.a&&ke(i,`opacity`,h.a=v),ee!==h.o&&ke(a,`background`,h.o=ee),y!==h.i&&ke(a,`opacity`,h.i=y),b!==h.n&&ke(o,`background`,h.n=b),x!==h.s&&ke(o,`opacity`,h.s=x),S!==h.h&&ke(s,`background`,h.h=S),C!==h.r&&ke(c,`background`,h.r=C),w!==h.d&&ke(l,`background`,h.d=w),T!==h.l&&ke(u,`background`,h.l=T),E!==h.u&&ke(d,`background`,h.u=E),D!==h.c&&ke(f,`background`,h.c=D),O!==h.w&&ke(p,`background`,h.w=O),te!==h.m&&ke(m,`background`,h.m=te),h},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0,r:void 0,d:void 0,l:void 0,u:void 0,c:void 0,w:void 0,m:void 0}),r})()}Ee([`input`]);var[xf,Sf]=y(``),Cf,wf=e=>{Sf(e),clearTimeout(Cf),Cf=setTimeout(()=>Sf(``),3200)};function Tf(e,t){if(!t.startsWith(`blobs/`)||!e)return t;let n=t.slice(6);return`/api/agents/${encodeURIComponent(e)}/blobs/${encodeURIComponent(n)}`}var Ef=class extends Error{constructor(e){super(e),this.name=`ShikiError`}};function Df(e){return Of(e)}function Of(e){return Array.isArray(e)?kf(e):e instanceof RegExp?e:typeof e==`object`?Af(e):e}function kf(e){let t=[];for(let n=0,r=e.length;n<r;n++)t[n]=Of(e[n]);return t}function Af(e){let t={};for(let n in e)t[n]=Of(e[n]);return t}function jf(e,...t){return t.forEach(t=>{for(let n in t)e[n]=t[n]}),e}function Mf(e){let t=~e.lastIndexOf(`/`)||~e.lastIndexOf(`\\`);return t===0?e:~t===e.length-1?Mf(e.substring(0,e.length-1)):e.substr(~t+1)}var Nf=/\$(\d+)|\${(\d+):\/(downcase|upcase)}/g,Pf=class{static hasCaptures(e){return e!==null&&(Nf.lastIndex=0,Nf.test(e))}static replaceCaptures(e,t,n){return e.replace(Nf,(e,r,i,a)=>{let o=n[parseInt(r||i,10)];if(o){let e=t.substring(o.start,o.end);for(;e[0]===`.`;)e=e.substring(1);switch(a){case`downcase`:return e.toLowerCase();case`upcase`:return e.toUpperCase();default:return e}}else return e})}};function Ff(e,t){return e<t?-1:+(e>t)}function If(e,t){if(e===null&&t===null)return 0;if(!e)return-1;if(!t)return 1;let n=e.length,r=t.length;if(n===r){for(let r=0;r<n;r++){let n=Ff(e[r],t[r]);if(n!==0)return n}return 0}return n-r}function Lf(e){return!!(/^#[0-9a-f]{6}$/i.test(e)||/^#[0-9a-f]{8}$/i.test(e)||/^#[0-9a-f]{3}$/i.test(e)||/^#[0-9a-f]{4}$/i.test(e))}function Rf(e){return e.replace(/[\-\\\{\}\*\+\?\|\^\$\.\,\[\]\(\)\#\s]/g,`\\$&`)}var zf=class{constructor(e){this.fn=e}cache=new Map;get(e){if(this.cache.has(e))return this.cache.get(e);let t=this.fn(e);return this.cache.set(e,t),t}},Bf=class{constructor(e,t,n){this._colorMap=e,this._defaults=t,this._root=n}static createFromRawTheme(e,t){return this.createFromParsedTheme(Gf(e),t)}static createFromParsedTheme(e,t){return Jf(e,t)}_cachedMatchRoot=new zf(e=>this._root.match(e));getColorMap(){return this._colorMap.getColorMap()}getDefaults(){return this._defaults}match(e){if(e===null)return this._defaults;let t=e.scopeName,n=this._cachedMatchRoot.get(t).find(t=>Hf(e.parent,t.parentScopes));return n?new Wf(n.fontStyle,n.foreground,n.background):null}},Vf=class e{constructor(e,t){this.parent=e,this.scopeName=t}static push(t,n){for(let r of n)t=new e(t,r);return t}static from(...t){let n=null;for(let r=0;r<t.length;r++)n=new e(n,t[r]);return n}push(t){return new e(this,t)}getSegments(){let e=this,t=[];for(;e;)t.push(e.scopeName),e=e.parent;return t.reverse(),t}toString(){return this.getSegments().join(` `)}extends(e){return this===e||this.parent!==null&&this.parent.extends(e)}getExtensionIfDefined(e){let t=[],n=this;for(;n&&n!==e;)t.push(n.scopeName),n=n.parent;return n===e?t.reverse():void 0}};function Hf(e,t){if(t.length===0)return!0;for(let n=0;n<t.length;n++){let r=t[n],i=!1;if(r===`>`){if(n===t.length-1)return!1;r=t[++n],i=!0}for(;e&&!Uf(e.scopeName,r);){if(i)return!1;e=e.parent}if(!e)return!1;e=e.parent}return!0}function Uf(e,t){return t===e||e.startsWith(t)&&e[t.length]===`.`}var Wf=class{constructor(e,t,n){this.fontStyle=e,this.foregroundId=t,this.backgroundId=n}};function Gf(e){if(!e||!e.settings||!Array.isArray(e.settings))return[];let t=e.settings,n=[],r=0;for(let e=0,i=t.length;e<i;e++){let i=t[e];if(!i.settings)continue;let a;if(typeof i.scope==`string`){let e=i.scope;e=e.replace(/^[,]+/,``),e=e.replace(/[,]+$/,``),a=e.split(`,`)}else a=Array.isArray(i.scope)?i.scope:[``];let o=-1;if(typeof i.settings.fontStyle==`string`){o=0;let e=i.settings.fontStyle.split(` `);for(let t=0,n=e.length;t<n;t++)switch(e[t]){case`italic`:o|=1;break;case`bold`:o|=2;break;case`underline`:o|=4;break;case`strikethrough`:o|=8}}let s=null;typeof i.settings.foreground==`string`&&Lf(i.settings.foreground)&&(s=i.settings.foreground);let c=null;typeof i.settings.background==`string`&&Lf(i.settings.background)&&(c=i.settings.background);for(let t=0,i=a.length;t<i;t++){let i=a[t].trim().split(` `),l=i[i.length-1],u=null;i.length>1&&(u=i.slice(0,i.length-1),u.reverse()),n[r++]=new Kf(l,u,e,o,s,c)}}return n}var Kf=class{constructor(e,t,n,r,i,a){this.scope=e,this.parentScopes=t,this.index=n,this.fontStyle=r,this.foreground=i,this.background=a}},qf=(e=>(e[e.NotSet=-1]=`NotSet`,e[e.None=0]=`None`,e[e.Italic=1]=`Italic`,e[e.Bold=2]=`Bold`,e[e.Underline=4]=`Underline`,e[e.Strikethrough=8]=`Strikethrough`,e))(qf||{});function Jf(e,t){e.sort((e,t)=>{let n=Ff(e.scope,t.scope);return n!==0||(n=If(e.parentScopes,t.parentScopes),n!==0)?n:e.index-t.index});let n=0,r=`#000000`,i=`#ffffff`;for(;e.length>=1&&e[0].scope===``;){let t=e.shift();t.fontStyle!==-1&&(n=t.fontStyle),t.foreground!==null&&(r=t.foreground),t.background!==null&&(i=t.background)}let a=new Yf(t),o=new Wf(n,a.getId(r),a.getId(i)),s=new Qf(new Zf(0,null,-1,0,0),[]);for(let t=0,n=e.length;t<n;t++){let n=e[t];s.insert(0,n.scope,n.parentScopes,n.fontStyle,a.getId(n.foreground),a.getId(n.background))}return new Bf(a,o,s)}var Yf=class{_isFrozen;_lastColorId;_id2color;_color2id;constructor(e){if(this._lastColorId=0,this._id2color=[],this._color2id=Object.create(null),Array.isArray(e)){this._isFrozen=!0;for(let t=0,n=e.length;t<n;t++)this._color2id[e[t]]=t,this._id2color[t]=e[t]}else this._isFrozen=!1}getId(e){if(e===null)return 0;e=e.toUpperCase();let t=this._color2id[e];if(t)return t;if(this._isFrozen)throw Error(`Missing color in color map - ${e}`);return t=++this._lastColorId,this._color2id[e]=t,this._id2color[t]=e,t}getColorMap(){return this._id2color.slice(0)}},Xf=Object.freeze([]),Zf=class e{scopeDepth;parentScopes;fontStyle;foreground;background;constructor(e,t,n,r,i){this.scopeDepth=e,this.parentScopes=t||Xf,this.fontStyle=n,this.foreground=r,this.background=i}clone(){return new e(this.scopeDepth,this.parentScopes,this.fontStyle,this.foreground,this.background)}static cloneArr(e){let t=[];for(let n=0,r=e.length;n<r;n++)t[n]=e[n].clone();return t}acceptOverwrite(e,t,n,r){this.scopeDepth>e?console.log(`how did this happen?`):this.scopeDepth=e,t!==-1&&(this.fontStyle=t),n!==0&&(this.foreground=n),r!==0&&(this.background=r)}},Qf=class e{constructor(e,t=[],n={}){this._mainRule=e,this._children=n,this._rulesWithParentScopes=t}_rulesWithParentScopes;static _cmpBySpecificity(e,t){if(e.scopeDepth!==t.scopeDepth)return t.scopeDepth-e.scopeDepth;let n=0,r=0;for(;e.parentScopes[n]===`>`&&n++,t.parentScopes[r]===`>`&&r++,!(n>=e.parentScopes.length||r>=t.parentScopes.length);){let i=t.parentScopes[r].length-e.parentScopes[n].length;if(i!==0)return i;n++,r++}return t.parentScopes.length-e.parentScopes.length}match(t){if(t!==``){let e=t.indexOf(`.`),n,r;if(e===-1?(n=t,r=``):(n=t.substring(0,e),r=t.substring(e+1)),this._children.hasOwnProperty(n))return this._children[n].match(r)}let n=this._rulesWithParentScopes.concat(this._mainRule);return n.sort(e._cmpBySpecificity),n}insert(t,n,r,i,a,o){if(n===``){this._doInsertHere(t,r,i,a,o);return}let s=n.indexOf(`.`),c,l;s===-1?(c=n,l=``):(c=n.substring(0,s),l=n.substring(s+1));let u;this._children.hasOwnProperty(c)?u=this._children[c]:(u=new e(this._mainRule.clone(),Zf.cloneArr(this._rulesWithParentScopes)),this._children[c]=u),u.insert(t+1,l,r,i,a,o)}_doInsertHere(e,t,n,r,i){if(t===null)this._mainRule.acceptOverwrite(e,n,r,i);else{for(let a=0,o=this._rulesWithParentScopes.length;a<o;a++){let o=this._rulesWithParentScopes[a];if(If(o.parentScopes,t)===0){o.acceptOverwrite(e,n,r,i);return}}n===-1&&(n=this._mainRule.fontStyle),r===0&&(r=this._mainRule.foreground),i===0&&(i=this._mainRule.background),this._rulesWithParentScopes.push(new Zf(e,t,n,r,i))}}},$f=class e{static toBinaryStr(e){return e.toString(2).padStart(32,`0`)}static print(t){let n=e.getLanguageId(t),r=e.getTokenType(t),i=e.getFontStyle(t),a=e.getForeground(t),o=e.getBackground(t);console.log({languageId:n,tokenType:r,fontStyle:i,foreground:a,background:o})}static getLanguageId(e){return(e&255)>>>0}static getTokenType(e){return(e&768)>>>8}static containsBalancedBrackets(e){return!!(e&1024)}static getFontStyle(e){return(e&30720)>>>11}static getForeground(e){return(e&16744448)>>>15}static getBackground(e){return(e&4278190080)>>>24}static set(t,n,r,i,a,o,s){let c=e.getLanguageId(t),l=e.getTokenType(t),u=+!!e.containsBalancedBrackets(t),d=e.getFontStyle(t),f=e.getForeground(t),p=e.getBackground(t);return n!==0&&(c=n),r!==8&&(l=tp(r)),i!==null&&(u=+!!i),a!==-1&&(d=a),o!==0&&(f=o),s!==0&&(p=s),(c|0|l<<8|u<<10|d<<11|f<<15|p<<24)>>>0}};function ep(e){return e}function tp(e){return e}function np(e,t){let n=[],r=ip(e),i=r.next();for(;i!==null;){let e=0;if(i.length===2&&i.charAt(1)===`:`){switch(i.charAt(0)){case`R`:e=1;break;case`L`:e=-1;break;default:console.log(`Unknown priority ${i} in scope selector`)}i=r.next()}let t=o();if(n.push({matcher:t,priority:e}),i!==`,`)break;i=r.next()}return n;function a(){if(i===`-`){i=r.next();let e=a();return t=>!!e&&!e(t)}if(i===`(`){i=r.next();let e=s();return i===`)`&&(i=r.next()),e}if(rp(i)){let e=[];do e.push(i),i=r.next();while(rp(i));return n=>t(e,n)}return null}function o(){let e=[],t=a();for(;t;)e.push(t),t=a();return t=>e.every(e=>e(t))}function s(){let e=[],t=o();for(;t&&(e.push(t),i===`|`||i===`,`);){do i=r.next();while(i===`|`||i===`,`);t=o()}return t=>e.some(e=>e(t))}}function rp(e){return!!e&&!!e.match(/[\w\.:]+/)}function ip(e){let t=/([LR]:|[\w\.:][\w\.:\-]*|[\,\|\-\(\)])/g,n=t.exec(e);return{next:()=>{if(!n)return null;let r=n[0];return n=t.exec(e),r}}}function ap(e){typeof e.dispose==`function`&&e.dispose()}var op=class{constructor(e){this.scopeName=e}toKey(){return this.scopeName}},sp=class{constructor(e,t){this.scopeName=e,this.ruleName=t}toKey(){return`${this.scopeName}#${this.ruleName}`}},cp=class{_references=[];_seenReferenceKeys=new Set;get references(){return this._references}visitedRule=new Set;add(e){let t=e.toKey();this._seenReferenceKeys.has(t)||(this._seenReferenceKeys.add(t),this._references.push(e))}},lp=class{constructor(e,t){this.repo=e,this.initialScopeName=t,this.seenFullScopeRequests.add(this.initialScopeName),this.Q=[new op(this.initialScopeName)]}seenFullScopeRequests=new Set;seenPartialScopeRequests=new Set;Q;processQueue(){let e=this.Q;this.Q=[];let t=new cp;for(let n of e)up(n,this.initialScopeName,this.repo,t);for(let e of t.references)if(e instanceof op){if(this.seenFullScopeRequests.has(e.scopeName))continue;this.seenFullScopeRequests.add(e.scopeName),this.Q.push(e)}else{if(this.seenFullScopeRequests.has(e.scopeName)||this.seenPartialScopeRequests.has(e.toKey()))continue;this.seenPartialScopeRequests.add(e.toKey()),this.Q.push(e)}}};function up(e,t,n,r){let i=n.lookup(e.scopeName);if(!i){if(e.scopeName===t)throw Error(`No grammar provided for <${t}>`);return}let a=n.lookup(t);e instanceof op?fp({baseGrammar:a,selfGrammar:i},r):dp(e.ruleName,{baseGrammar:a,selfGrammar:i,repository:i.repository},r);let o=n.injections(e.scopeName);if(o)for(let e of o)r.add(new op(e))}function dp(e,t,n){if(t.repository&&t.repository[e]){let r=t.repository[e];pp([r],t,n)}}function fp(e,t){e.selfGrammar.patterns&&Array.isArray(e.selfGrammar.patterns)&&pp(e.selfGrammar.patterns,{...e,repository:e.selfGrammar.repository},t),e.selfGrammar.injections&&pp(Object.values(e.selfGrammar.injections),{...e,repository:e.selfGrammar.repository},t)}function pp(e,t,n){for(let r of e){if(n.visitedRule.has(r))continue;n.visitedRule.add(r);let e=r.repository?jf({},t.repository,r.repository):t.repository;Array.isArray(r.patterns)&&pp(r.patterns,{...t,repository:e},n);let i=r.include;if(!i)continue;let a=yp(i);switch(a.kind){case 0:fp({...t,selfGrammar:t.baseGrammar},n);break;case 1:fp(t,n);break;case 2:dp(a.ruleName,{...t,repository:e},n);break;case 3:case 4:let r=a.scopeName===t.selfGrammar.scopeName?t.selfGrammar:a.scopeName===t.baseGrammar.scopeName?t.baseGrammar:void 0;if(r){let i={baseGrammar:t.baseGrammar,selfGrammar:r,repository:e};a.kind===4?dp(a.ruleName,i,n):fp(i,n)}else a.kind===4?n.add(new sp(a.scopeName,a.ruleName)):n.add(new op(a.scopeName))}}}var mp=class{kind=0},hp=class{kind=1},gp=class{constructor(e){this.ruleName=e}kind=2},_p=class{constructor(e){this.scopeName=e}kind=3},vp=class{constructor(e,t){this.scopeName=e,this.ruleName=t}kind=4};function yp(e){if(e===`$base`)return new mp;if(e===`$self`)return new hp;let t=e.indexOf(`#`);return t===-1?new _p(e):t===0?new gp(e.substring(1)):new vp(e.substring(0,t),e.substring(t+1))}var bp=/\\(\d+)/,xp=/\\(\d+)/g,Sp=-1,Cp=-2;function wp(e){return e}function Tp(e){return e}var Ep=class{$location;id;_nameIsCapturing;_name;_contentNameIsCapturing;_contentName;constructor(e,t,n,r){this.$location=e,this.id=t,this._name=n||null,this._nameIsCapturing=Pf.hasCaptures(this._name),this._contentName=r||null,this._contentNameIsCapturing=Pf.hasCaptures(this._contentName)}get debugName(){let e=this.$location?`${Mf(this.$location.filename)}:${this.$location.line}`:`unknown`;return`${this.constructor.name}#${this.id} @ ${e}`}getName(e,t){return!this._nameIsCapturing||this._name===null||e===null||t===null?this._name:Pf.replaceCaptures(this._name,e,t)}getContentName(e,t){return!this._contentNameIsCapturing||this._contentName===null?this._contentName:Pf.replaceCaptures(this._contentName,e,t)}},Dp=class extends Ep{retokenizeCapturedWithRuleId;constructor(e,t,n,r,i){super(e,t,n,r),this.retokenizeCapturedWithRuleId=i}dispose(){}collectPatterns(e,t){throw Error(`Not supported!`)}compile(e,t){throw Error(`Not supported!`)}compileAG(e,t,n,r){throw Error(`Not supported!`)}},Op=class extends Ep{_match;captures;_cachedCompiledPatterns;constructor(e,t,n,r,i){super(e,t,n,null),this._match=new Np(r,this.id),this.captures=i,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&=(this._cachedCompiledPatterns.dispose(),null)}get debugMatchRegExp(){return`${this._match.source}`}collectPatterns(e,t){t.push(this._match)}compile(e,t){return this._getCachedCompiledPatterns(e).compile(e)}compileAG(e,t,n,r){return this._getCachedCompiledPatterns(e).compileAG(e,n,r)}_getCachedCompiledPatterns(e){return this._cachedCompiledPatterns||(this._cachedCompiledPatterns=new Pp,this.collectPatterns(e,this._cachedCompiledPatterns)),this._cachedCompiledPatterns}},kp=class extends Ep{hasMissingPatterns;patterns;_cachedCompiledPatterns;constructor(e,t,n,r,i){super(e,t,n,r),this.patterns=i.patterns,this.hasMissingPatterns=i.hasMissingPatterns,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&=(this._cachedCompiledPatterns.dispose(),null)}collectPatterns(e,t){for(let n of this.patterns)e.getRule(n).collectPatterns(e,t)}compile(e,t){return this._getCachedCompiledPatterns(e).compile(e)}compileAG(e,t,n,r){return this._getCachedCompiledPatterns(e).compileAG(e,n,r)}_getCachedCompiledPatterns(e){return this._cachedCompiledPatterns||(this._cachedCompiledPatterns=new Pp,this.collectPatterns(e,this._cachedCompiledPatterns)),this._cachedCompiledPatterns}},Ap=class extends Ep{_begin;beginCaptures;_end;endHasBackReferences;endCaptures;applyEndPatternLast;hasMissingPatterns;patterns;_cachedCompiledPatterns;constructor(e,t,n,r,i,a,o,s,c,l){super(e,t,n,r),this._begin=new Np(i,this.id),this.beginCaptures=a,this._end=new Np(o||`￿`,-1),this.endHasBackReferences=this._end.hasBackReferences,this.endCaptures=s,this.applyEndPatternLast=c||!1,this.patterns=l.patterns,this.hasMissingPatterns=l.hasMissingPatterns,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&=(this._cachedCompiledPatterns.dispose(),null)}get debugBeginRegExp(){return`${this._begin.source}`}get debugEndRegExp(){return`${this._end.source}`}getEndWithResolvedBackReferences(e,t){return this._end.resolveBackReferences(e,t)}collectPatterns(e,t){t.push(this._begin)}compile(e,t){return this._getCachedCompiledPatterns(e,t).compile(e)}compileAG(e,t,n,r){return this._getCachedCompiledPatterns(e,t).compileAG(e,n,r)}_getCachedCompiledPatterns(e,t){if(!this._cachedCompiledPatterns){this._cachedCompiledPatterns=new Pp;for(let t of this.patterns)e.getRule(t).collectPatterns(e,this._cachedCompiledPatterns);this.applyEndPatternLast?this._cachedCompiledPatterns.push(this._end.hasBackReferences?this._end.clone():this._end):this._cachedCompiledPatterns.unshift(this._end.hasBackReferences?this._end.clone():this._end)}return this._end.hasBackReferences&&(this.applyEndPatternLast?this._cachedCompiledPatterns.setSource(this._cachedCompiledPatterns.length()-1,t):this._cachedCompiledPatterns.setSource(0,t)),this._cachedCompiledPatterns}},jp=class extends Ep{_begin;beginCaptures;whileCaptures;_while;whileHasBackReferences;hasMissingPatterns;patterns;_cachedCompiledPatterns;_cachedCompiledWhilePatterns;constructor(e,t,n,r,i,a,o,s,c){super(e,t,n,r),this._begin=new Np(i,this.id),this.beginCaptures=a,this.whileCaptures=s,this._while=new Np(o,Cp),this.whileHasBackReferences=this._while.hasBackReferences,this.patterns=c.patterns,this.hasMissingPatterns=c.hasMissingPatterns,this._cachedCompiledPatterns=null,this._cachedCompiledWhilePatterns=null}dispose(){this._cachedCompiledPatterns&&=(this._cachedCompiledPatterns.dispose(),null),this._cachedCompiledWhilePatterns&&=(this._cachedCompiledWhilePatterns.dispose(),null)}get debugBeginRegExp(){return`${this._begin.source}`}get debugWhileRegExp(){return`${this._while.source}`}getWhileWithResolvedBackReferences(e,t){return this._while.resolveBackReferences(e,t)}collectPatterns(e,t){t.push(this._begin)}compile(e,t){return this._getCachedCompiledPatterns(e).compile(e)}compileAG(e,t,n,r){return this._getCachedCompiledPatterns(e).compileAG(e,n,r)}_getCachedCompiledPatterns(e){if(!this._cachedCompiledPatterns){this._cachedCompiledPatterns=new Pp;for(let t of this.patterns)e.getRule(t).collectPatterns(e,this._cachedCompiledPatterns)}return this._cachedCompiledPatterns}compileWhile(e,t){return this._getCachedCompiledWhilePatterns(e,t).compile(e)}compileWhileAG(e,t,n,r){return this._getCachedCompiledWhilePatterns(e,t).compileAG(e,n,r)}_getCachedCompiledWhilePatterns(e,t){return this._cachedCompiledWhilePatterns||(this._cachedCompiledWhilePatterns=new Pp,this._cachedCompiledWhilePatterns.push(this._while.hasBackReferences?this._while.clone():this._while)),this._while.hasBackReferences&&this._cachedCompiledWhilePatterns.setSource(0,t||`￿`),this._cachedCompiledWhilePatterns}},Mp=class e{static createCaptureRule(e,t,n,r,i){return e.registerRule(e=>new Dp(t,e,n,r,i))}static getCompiledRuleId(t,n,r){return t.id||n.registerRule(i=>{if(t.id=i,t.match)return new Op(t.$vscodeTextmateLocation,t.id,t.name,t.match,e._compileCaptures(t.captures,n,r));if(t.begin===void 0){t.repository&&(r=jf({},r,t.repository));let i=t.patterns;return i===void 0&&t.include&&(i=[{include:t.include}]),new kp(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,e._compilePatterns(i,n,r))}return t.while?new jp(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,t.begin,e._compileCaptures(t.beginCaptures||t.captures,n,r),t.while,e._compileCaptures(t.whileCaptures||t.captures,n,r),e._compilePatterns(t.patterns,n,r)):new Ap(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,t.begin,e._compileCaptures(t.beginCaptures||t.captures,n,r),t.end,e._compileCaptures(t.endCaptures||t.captures,n,r),t.applyEndPatternLast,e._compilePatterns(t.patterns,n,r))}),t.id}static _compileCaptures(t,n,r){let i=[];if(t){let a=0;for(let e in t){if(e===`$vscodeTextmateLocation`)continue;let t=parseInt(e,10);t>a&&(a=t)}for(let e=0;e<=a;e++)i[e]=null;for(let a in t){if(a===`$vscodeTextmateLocation`)continue;let o=parseInt(a,10),s=0;t[a].patterns&&(s=e.getCompiledRuleId(t[a],n,r)),i[o]=e.createCaptureRule(n,t[a].$vscodeTextmateLocation,t[a].name,t[a].contentName,s)}}return i}static _compilePatterns(t,n,r){let i=[];if(t)for(let a=0,o=t.length;a<o;a++){let o=t[a],s=-1;if(o.include){let t=yp(o.include);switch(t.kind){case 0:case 1:s=e.getCompiledRuleId(r[o.include],n,r);break;case 2:let i=r[t.ruleName];i&&(s=e.getCompiledRuleId(i,n,r));break;case 3:case 4:let a=t.scopeName,c=t.kind===4?t.ruleName:null,l=n.getExternalGrammar(a,r);if(l){if(c){let t=l.repository[c];t&&(s=e.getCompiledRuleId(t,n,l.repository))}else s=e.getCompiledRuleId(l.repository.$self,n,l.repository)}}}else s=e.getCompiledRuleId(o,n,r);if(s!==-1){let e=n.getRule(s),t=!1;if((e instanceof kp||e instanceof Ap||e instanceof jp)&&e.hasMissingPatterns&&e.patterns.length===0&&(t=!0),t)continue;i.push(s)}}return{patterns:i,hasMissingPatterns:(t?t.length:0)!==i.length}}},Np=class e{source;ruleId;hasAnchor;hasBackReferences;_anchorCache;constructor(e,t){if(e&&typeof e==`string`){let t=e.length,n=0,r=[],i=!1;for(let a=0;a<t;a++)if(e.charAt(a)===`\\`&&a+1<t){let t=e.charAt(a+1);t===`z`?(r.push(e.substring(n,a)),r.push(`$(?!\\n)(?<!\\n)`),n=a+2):(t===`A`||t===`G`)&&(i=!0),a++}this.hasAnchor=i,n===0?this.source=e:(r.push(e.substring(n,t)),this.source=r.join(``))}else this.hasAnchor=!1,this.source=e;this._anchorCache=this.hasAnchor?this._buildAnchorCache():null,this.ruleId=t,this.hasBackReferences=typeof this.source==`string`&&bp.test(this.source)}clone(){return new e(this.source,this.ruleId)}setSource(e){this.source!==e&&(this.source=e,this.hasAnchor&&(this._anchorCache=this._buildAnchorCache()))}resolveBackReferences(e,t){if(typeof this.source!=`string`)throw Error(`This method should only be called if the source is a string`);let n=t.map(t=>e.substring(t.start,t.end));return xp.lastIndex=0,this.source.replace(xp,(e,t)=>Rf(n[parseInt(t,10)]||``))}_buildAnchorCache(){if(typeof this.source!=`string`)throw Error(`This method should only be called if the source is a string`);let e=[],t=[],n=[],r=[],i,a,o,s;for(i=0,a=this.source.length;i<a;i++)o=this.source.charAt(i),e[i]=o,t[i]=o,n[i]=o,r[i]=o,o===`\\`&&i+1<a&&(s=this.source.charAt(i+1),s===`A`?(e[i+1]=`￿`,t[i+1]=`￿`,n[i+1]=`A`,r[i+1]=`A`):s===`G`?(e[i+1]=`￿`,t[i+1]=`G`,n[i+1]=`￿`,r[i+1]=`G`):(e[i+1]=s,t[i+1]=s,n[i+1]=s,r[i+1]=s),i++);return{A0_G0:e.join(``),A0_G1:t.join(``),A1_G0:n.join(``),A1_G1:r.join(``)}}resolveAnchors(e,t){return!this.hasAnchor||!this._anchorCache||typeof this.source!=`string`?this.source:e?t?this._anchorCache.A1_G1:this._anchorCache.A1_G0:t?this._anchorCache.A0_G1:this._anchorCache.A0_G0}},Pp=class{_items;_hasAnchors;_cached;_anchorCache;constructor(){this._items=[],this._hasAnchors=!1,this._cached=null,this._anchorCache={A0_G0:null,A0_G1:null,A1_G0:null,A1_G1:null}}dispose(){this._disposeCaches()}_disposeCaches(){this._cached&&=(this._cached.dispose(),null),this._anchorCache.A0_G0&&(this._anchorCache.A0_G0.dispose(),this._anchorCache.A0_G0=null),this._anchorCache.A0_G1&&(this._anchorCache.A0_G1.dispose(),this._anchorCache.A0_G1=null),this._anchorCache.A1_G0&&(this._anchorCache.A1_G0.dispose(),this._anchorCache.A1_G0=null),this._anchorCache.A1_G1&&(this._anchorCache.A1_G1.dispose(),this._anchorCache.A1_G1=null)}push(e){this._items.push(e),this._hasAnchors=this._hasAnchors||e.hasAnchor}unshift(e){this._items.unshift(e),this._hasAnchors=this._hasAnchors||e.hasAnchor}length(){return this._items.length}setSource(e,t){this._items[e].source!==t&&(this._disposeCaches(),this._items[e].setSource(t))}compile(e){if(!this._cached){let t=this._items.map(e=>e.source);this._cached=new Fp(e,t,this._items.map(e=>e.ruleId))}return this._cached}compileAG(e,t,n){return this._hasAnchors?t?n?(this._anchorCache.A1_G1||(this._anchorCache.A1_G1=this._resolveAnchors(e,t,n)),this._anchorCache.A1_G1):(this._anchorCache.A1_G0||(this._anchorCache.A1_G0=this._resolveAnchors(e,t,n)),this._anchorCache.A1_G0):n?(this._anchorCache.A0_G1||(this._anchorCache.A0_G1=this._resolveAnchors(e,t,n)),this._anchorCache.A0_G1):(this._anchorCache.A0_G0||(this._anchorCache.A0_G0=this._resolveAnchors(e,t,n)),this._anchorCache.A0_G0):this.compile(e)}_resolveAnchors(e,t,n){return new Fp(e,this._items.map(e=>e.resolveAnchors(t,n)),this._items.map(e=>e.ruleId))}},Fp=class{constructor(e,t,n){this.regExps=t,this.rules=n,this.scanner=e.createOnigScanner(t)}scanner;dispose(){typeof this.scanner.dispose==`function`&&this.scanner.dispose()}toString(){let e=[];for(let t=0,n=this.rules.length;t<n;t++)e.push(` - `+this.rules[t]+`: `+this.regExps[t]);return e.join(`
25
25
  `)}findNextMatchSync(e,t,n){let r=this.scanner.findNextMatchSync(e,t,n);return r?{ruleId:this.rules[r.index],captureIndices:r.captureIndices}:null}},Ip=class{constructor(e,t){this.languageId=e,this.tokenType=t}},Lp=class e{_defaultAttributes;_embeddedLanguagesMatcher;constructor(e,t){this._defaultAttributes=new Ip(e,8),this._embeddedLanguagesMatcher=new Rp(Object.entries(t||{}))}getDefaultAttributes(){return this._defaultAttributes}getBasicScopeAttributes(t){return t===null?e._NULL_SCOPE_METADATA:this._getBasicScopeAttributes.get(t)}static _NULL_SCOPE_METADATA=new Ip(0,0);_getBasicScopeAttributes=new zf(e=>new Ip(this._scopeToLanguage(e),this._toStandardTokenType(e)));_scopeToLanguage(e){return this._embeddedLanguagesMatcher.match(e)||0}_toStandardTokenType(t){let n=t.match(e.STANDARD_TOKEN_TYPE_REGEXP);if(!n)return 8;switch(n[1]){case`comment`:return 1;case`string`:return 2;case`regex`:return 3;case`meta.embedded`:return 0}throw Error(`Unexpected match for standard token type!`)}static STANDARD_TOKEN_TYPE_REGEXP=/\b(comment|string|regex|meta\.embedded)\b/},Rp=class{values;scopesRegExp;constructor(e){if(e.length===0)this.values=null,this.scopesRegExp=null;else{this.values=new Map(e);let t=e.map(([e,t])=>Rf(e));t.sort(),t.reverse(),this.scopesRegExp=RegExp(`^((${t.join(`)|(`)}))($|\\.)`,``)}}match(e){if(!this.scopesRegExp)return;let t=e.match(this.scopesRegExp);if(t)return this.values.get(t[1])}};typeof process<`u`&&{}.VSCODE_TEXTMATE_DEBUG;var zp=class{constructor(e,t){this.stack=e,this.stoppedEarly=t}};function Bp(e,t,n,r,i,a,o,s){let c=t.content.length,l=!1,u=-1;if(o){let o=Vp(e,t,n,r,i,a);i=o.stack,r=o.linePos,n=o.isFirstLine,u=o.anchorPosition}let d=Date.now();for(;!l;){if(s!==0&&Date.now()-d>s)return new zp(i,!0);f()}return new zp(i,!1);function f(){let o=Hp(e,t,n,r,i,u);if(!o){a.produce(i,c),l=!0;return}let s=o.captureIndices,d=o.matchedRuleId,f=s&&s.length>0?s[0].end>r:!1;if(d===Sp){let o=i.getRule(e);a.produce(i,s[0].start),i=i.withContentNameScopesList(i.nameScopesList),qp(e,t,n,i,a,o.endCaptures,s),a.produce(i,s[0].end);let d=i;if(i=i.parent,u=d.getAnchorPos(),!f&&d.getEnterPos()===r){i=d,a.produce(i,c),l=!0;return}}else{let o=e.getRule(d);a.produce(i,s[0].start);let p=i,m=o.getName(t.content,s),h=i.contentNameScopesList.pushAttributed(m,e);if(i=i.push(d,r,u,s[0].end===c,null,h,h),o instanceof Ap){let r=o;qp(e,t,n,i,a,r.beginCaptures,s),a.produce(i,s[0].end),u=s[0].end;let d=r.getContentName(t.content,s),m=h.pushAttributed(d,e);if(i=i.withContentNameScopesList(m),r.endHasBackReferences&&(i=i.withEndRule(r.getEndWithResolvedBackReferences(t.content,s))),!f&&p.hasSameRuleAs(i)){i=i.pop(),a.produce(i,c),l=!0;return}}else if(o instanceof jp){let r=o;qp(e,t,n,i,a,r.beginCaptures,s),a.produce(i,s[0].end),u=s[0].end;let d=r.getContentName(t.content,s),m=h.pushAttributed(d,e);if(i=i.withContentNameScopesList(m),r.whileHasBackReferences&&(i=i.withEndRule(r.getWhileWithResolvedBackReferences(t.content,s))),!f&&p.hasSameRuleAs(i)){i=i.pop(),a.produce(i,c),l=!0;return}}else if(qp(e,t,n,i,a,o.captures,s),a.produce(i,s[0].end),i=i.pop(),!f){i=i.safePop(),a.produce(i,c),l=!0;return}}s[0].end>r&&(r=s[0].end,n=!1)}}function Vp(e,t,n,r,i,a){let o=i.beginRuleCapturedEOL?0:-1,s=[];for(let t=i;t;t=t.pop()){let n=t.getRule(e);n instanceof jp&&s.push({rule:n,stack:t})}for(let c=s.pop();c;c=s.pop()){let{ruleScanner:s,findOptions:l}=Kp(c.rule,e,c.stack.endRule,n,r===o),u=s.findNextMatchSync(t,r,l);if(u){if(u.ruleId!==Cp){i=c.stack.pop();break}u.captureIndices&&u.captureIndices.length&&(a.produce(c.stack,u.captureIndices[0].start),qp(e,t,n,c.stack,a,c.rule.whileCaptures,u.captureIndices),a.produce(c.stack,u.captureIndices[0].end),o=u.captureIndices[0].end,u.captureIndices[0].end>r&&(r=u.captureIndices[0].end,n=!1))}else{i=c.stack.pop();break}}return{stack:i,linePos:r,anchorPosition:o,isFirstLine:n}}function Hp(e,t,n,r,i,a){let o=Up(e,t,n,r,i,a),s=e.getInjections();if(s.length===0)return o;let c=Wp(s,e,t,n,r,i,a);if(!c)return o;if(!o)return c;let l=o.captureIndices[0].start,u=c.captureIndices[0].start;return u<l||c.priorityMatch&&u===l?c:o}function Up(e,t,n,r,i,a){let{ruleScanner:o,findOptions:s}=Gp(i.getRule(e),e,i.endRule,n,r===a),c=o.findNextMatchSync(t,r,s);return c?{captureIndices:c.captureIndices,matchedRuleId:c.ruleId}:null}function Wp(e,t,n,r,i,a,o){let s=Number.MAX_VALUE,c=null,l,u=0,d=a.contentNameScopesList.getScopeNames();for(let a=0,f=e.length;a<f;a++){let f=e[a];if(!f.matcher(d))continue;let{ruleScanner:p,findOptions:m}=Gp(t.getRule(f.ruleId),t,null,r,i===o),h=p.findNextMatchSync(n,i,m);if(!h)continue;let g=h.captureIndices[0].start;if(!(g>=s)&&(s=g,c=h.captureIndices,l=h.ruleId,u=f.priority,s===i))break}return c?{priorityMatch:u===-1,captureIndices:c,matchedRuleId:l}:null}function Gp(e,t,n,r,i){return{ruleScanner:e.compileAG(t,n,r,i),findOptions:0}}function Kp(e,t,n,r,i){return{ruleScanner:e.compileWhileAG(t,n,r,i),findOptions:0}}function qp(e,t,n,r,i,a,o){if(a.length===0)return;let s=t.content,c=Math.min(a.length,o.length),l=[],u=o[0].end;for(let t=0;t<c;t++){let c=a[t];if(c===null)continue;let d=o[t];if(d.length===0)continue;if(d.start>u)break;for(;l.length>0&&l[l.length-1].endPos<=d.start;)i.produceFromScopes(l[l.length-1].scopes,l[l.length-1].endPos),l.pop();if(l.length>0?i.produceFromScopes(l[l.length-1].scopes,d.start):i.produce(r,d.start),c.retokenizeCapturedWithRuleId){let t=c.getName(s,o),a=r.contentNameScopesList.pushAttributed(t,e),l=c.getContentName(s,o),u=a.pushAttributed(l,e),f=r.push(c.retokenizeCapturedWithRuleId,d.start,-1,!1,null,a,u),p=e.createOnigString(s.substring(0,d.end));Bp(e,p,n&&d.start===0,d.start,f,i,!1,0),ap(p);continue}let f=c.getName(s,o);if(f!==null){let t=(l.length>0?l[l.length-1].scopes:r.contentNameScopesList).pushAttributed(f,e);l.push(new Jp(t,d.end))}}for(;l.length>0;)i.produceFromScopes(l[l.length-1].scopes,l[l.length-1].endPos),l.pop()}var Jp=class{scopes;endPos;constructor(e,t){this.scopes=e,this.endPos=t}};function Yp(e,t,n,r,i,a,o,s){return new $p(e,t,n,r,i,a,o,s)}function Xp(e,t,n,r,i){let a=np(t,Zp),o=Mp.getCompiledRuleId(n,r,i.repository);for(let n of a)e.push({debugSelector:t,matcher:n.matcher,ruleId:o,grammar:i,priority:n.priority})}function Zp(e,t){if(t.length<e.length)return!1;let n=0;return e.every(e=>{for(let r=n;r<t.length;r++)if(Qp(t[r],e))return n=r+1,!0;return!1})}function Qp(e,t){if(!e)return!1;if(e===t)return!0;let n=t.length;return e.length>n&&e.substr(0,n)===t&&e[n]===`.`}var $p=class{constructor(e,t,n,r,i,a,o,s){if(this._rootScopeName=e,this.balancedBracketSelectors=a,this._onigLib=s,this._basicScopeAttributesProvider=new Lp(n,r),this._rootId=-1,this._lastRuleId=0,this._ruleId2desc=[null],this._includedGrammars={},this._grammarRepository=o,this._grammar=em(t,null),this._injections=null,this._tokenTypeMatchers=[],i)for(let e of Object.keys(i)){let t=np(e,Zp);for(let n of t)this._tokenTypeMatchers.push({matcher:n.matcher,type:i[e]})}}_rootId;_lastRuleId;_ruleId2desc;_includedGrammars;_grammarRepository;_grammar;_injections;_basicScopeAttributesProvider;_tokenTypeMatchers;get themeProvider(){return this._grammarRepository}dispose(){for(let e of this._ruleId2desc)e&&e.dispose()}createOnigScanner(e){return this._onigLib.createOnigScanner(e)}createOnigString(e){return this._onigLib.createOnigString(e)}getMetadataForScope(e){return this._basicScopeAttributesProvider.getBasicScopeAttributes(e)}_collectInjections(){let e={lookup:e=>e===this._rootScopeName?this._grammar:this.getExternalGrammar(e),injections:e=>this._grammarRepository.injections(e)},t=[],n=this._rootScopeName,r=e.lookup(n);if(r){let e=r.injections;if(e)for(let n in e)Xp(t,n,e[n],this,r);let i=this._grammarRepository.injections(n);i&&i.forEach(e=>{let n=this.getExternalGrammar(e);if(n){let e=n.injectionSelector;e&&Xp(t,e,n,this,n)}})}return t.sort((e,t)=>e.priority-t.priority),t}getInjections(){return this._injections===null&&(this._injections=this._collectInjections()),this._injections}registerRule(e){let t=++this._lastRuleId,n=e(wp(t));return this._ruleId2desc[t]=n,n}getRule(e){return this._ruleId2desc[Tp(e)]}getExternalGrammar(e,t){if(this._includedGrammars[e])return this._includedGrammars[e];if(this._grammarRepository){let n=this._grammarRepository.lookup(e);if(n)return this._includedGrammars[e]=em(n,t&&t.$base),this._includedGrammars[e]}}tokenizeLine(e,t,n=0){let r=this._tokenize(e,t,!1,n);return{tokens:r.lineTokens.getResult(r.ruleStack,r.lineLength),ruleStack:r.ruleStack,stoppedEarly:r.stoppedEarly}}tokenizeLine2(e,t,n=0){let r=this._tokenize(e,t,!0,n);return{tokens:r.lineTokens.getBinaryResult(r.ruleStack,r.lineLength),ruleStack:r.ruleStack,stoppedEarly:r.stoppedEarly}}_tokenize(e,t,n,r){this._rootId===-1&&(this._rootId=Mp.getCompiledRuleId(this._grammar.repository.$self,this,this._grammar.repository),this.getInjections());let i;if(!t||t===nm.NULL){i=!0;let e=this._basicScopeAttributesProvider.getDefaultAttributes(),n=this.themeProvider.getDefaults(),r=$f.set(0,e.languageId,e.tokenType,null,n.fontStyle,n.foregroundId,n.backgroundId),a=this.getRule(this._rootId).getName(null,null),o;o=a?tm.createRootAndLookUpScopeName(a,r,this):tm.createRoot(`unknown`,r),t=new nm(null,this._rootId,-1,-1,!1,null,o,o)}else i=!1,t.reset();e+=`
26
- `;let a=this.createOnigString(e),o=a.content.length,s=new im(n,e,this._tokenTypeMatchers,this.balancedBracketSelectors),c=Bp(this,a,i,0,t,s,!0,r);return ap(a),{lineLength:o,lineTokens:s,ruleStack:c.stack,stoppedEarly:c.stoppedEarly}}};function em(e,t){return e=Df(e),e.repository=e.repository||{},e.repository.$self={$vscodeTextmateLocation:e.$vscodeTextmateLocation,patterns:e.patterns,name:e.scopeName},e.repository.$base=t||e.repository.$self,e}var tm=class e{constructor(e,t,n){this.parent=e,this.scopePath=t,this.tokenAttributes=n}static fromExtension(t,n){let r=t,i=t?.scopePath??null;for(let t of n)i=Vf.push(i,t.scopeNames),r=new e(r,i,t.encodedTokenAttributes);return r}static createRoot(t,n){return new e(null,new Vf(null,t),n)}static createRootAndLookUpScopeName(t,n,r){let i=r.getMetadataForScope(t),a=new Vf(null,t),o=r.themeProvider.themeMatch(a),s=e.mergeAttributes(n,i,o);return new e(null,a,s)}get scopeName(){return this.scopePath.scopeName}toString(){return this.getScopeNames().join(` `)}equals(t){return e.equals(this,t)}static equals(e,t){do{if(e===t||!e&&!t)return!0;if(!e||!t||e.scopeName!==t.scopeName||e.tokenAttributes!==t.tokenAttributes)return!1;e=e.parent,t=t.parent}while(1)}static mergeAttributes(e,t,n){let r=-1,i=0,a=0;return n!==null&&(r=n.fontStyle,i=n.foregroundId,a=n.backgroundId),$f.set(e,t.languageId,t.tokenType,null,r,i,a)}pushAttributed(t,n){if(t===null)return this;if(t.indexOf(` `)===-1)return e._pushAttributed(this,t,n);let r=t.split(/ /g),i=this;for(let t of r)i=e._pushAttributed(i,t,n);return i}static _pushAttributed(t,n,r){let i=r.getMetadataForScope(n),a=t.scopePath.push(n),o=r.themeProvider.themeMatch(a),s=e.mergeAttributes(t.tokenAttributes,i,o);return new e(t,a,s)}getScopeNames(){return this.scopePath.getSegments()}getExtensionIfDefined(e){let t=[],n=this;for(;n&&n!==e;)t.push({encodedTokenAttributes:n.tokenAttributes,scopeNames:n.scopePath.getExtensionIfDefined(n.parent?.scopePath??null)}),n=n.parent;return n===e?t.reverse():void 0}},nm=class e{constructor(e,t,n,r,i,a,o,s){this.parent=e,this.ruleId=t,this.beginRuleCapturedEOL=i,this.endRule=a,this.nameScopesList=o,this.contentNameScopesList=s,this.depth=this.parent?this.parent.depth+1:1,this._enterPos=n,this._anchorPos=r}_stackElementBrand=void 0;static NULL=new e(null,0,0,0,!1,null,null,null);_enterPos;_anchorPos;depth;equals(t){return t!==null&&e._equals(this,t)}static _equals(e,t){return e===t?!0:this._structuralEquals(e,t)?tm.equals(e.contentNameScopesList,t.contentNameScopesList):!1}static _structuralEquals(e,t){do{if(e===t||!e&&!t)return!0;if(!e||!t||e.depth!==t.depth||e.ruleId!==t.ruleId||e.endRule!==t.endRule)return!1;e=e.parent,t=t.parent}while(1)}clone(){return this}static _reset(e){for(;e;)e._enterPos=-1,e._anchorPos=-1,e=e.parent}reset(){e._reset(this)}pop(){return this.parent}safePop(){return this.parent?this.parent:this}push(t,n,r,i,a,o,s){return new e(this,t,n,r,i,a,o,s)}getEnterPos(){return this._enterPos}getAnchorPos(){return this._anchorPos}getRule(e){return e.getRule(this.ruleId)}toString(){let e=[];return this._writeString(e,0),`[`+e.join(`,`)+`]`}_writeString(e,t){return this.parent&&(t=this.parent._writeString(e,t)),e[t++]=`(${this.ruleId}, ${this.nameScopesList?.toString()}, ${this.contentNameScopesList?.toString()})`,t}withContentNameScopesList(e){return this.contentNameScopesList===e?this:this.parent.push(this.ruleId,this._enterPos,this._anchorPos,this.beginRuleCapturedEOL,this.endRule,this.nameScopesList,e)}withEndRule(t){return this.endRule===t?this:new e(this.parent,this.ruleId,this._enterPos,this._anchorPos,this.beginRuleCapturedEOL,t,this.nameScopesList,this.contentNameScopesList)}hasSameRuleAs(e){let t=this;for(;t&&t._enterPos===e._enterPos;){if(t.ruleId===e.ruleId)return!0;t=t.parent}return!1}toStateStackFrame(){return{ruleId:Tp(this.ruleId),beginRuleCapturedEOL:this.beginRuleCapturedEOL,endRule:this.endRule,nameScopesList:this.nameScopesList?.getExtensionIfDefined(this.parent?.nameScopesList??null)??[],contentNameScopesList:this.contentNameScopesList?.getExtensionIfDefined(this.nameScopesList)??[]}}static pushFrame(t,n){let r=tm.fromExtension(t?.nameScopesList??null,n.nameScopesList);return new e(t,wp(n.ruleId),n.enterPos??-1,n.anchorPos??-1,n.beginRuleCapturedEOL,n.endRule,r,tm.fromExtension(r,n.contentNameScopesList))}},rm=class{balancedBracketScopes;unbalancedBracketScopes;allowAny=!1;constructor(e,t){this.balancedBracketScopes=e.flatMap(e=>e===`*`?(this.allowAny=!0,[]):np(e,Zp).map(e=>e.matcher)),this.unbalancedBracketScopes=t.flatMap(e=>np(e,Zp).map(e=>e.matcher))}get matchesAlways(){return this.allowAny&&this.unbalancedBracketScopes.length===0}get matchesNever(){return this.balancedBracketScopes.length===0&&!this.allowAny}match(e){for(let t of this.unbalancedBracketScopes)if(t(e))return!1;for(let t of this.balancedBracketScopes)if(t(e))return!0;return this.allowAny}},im=class{constructor(e,t,n,r){this.balancedBracketSelectors=r,this._emitBinaryTokens=e,this._tokenTypeOverrides=n,this._lineText=null,this._tokens=[],this._binaryTokens=[],this._lastTokenEndIndex=0}_emitBinaryTokens;_lineText;_tokens;_binaryTokens;_lastTokenEndIndex;_tokenTypeOverrides;produce(e,t){this.produceFromScopes(e.contentNameScopesList,t)}produceFromScopes(e,t){if(this._lastTokenEndIndex>=t)return;if(this._emitBinaryTokens){let n=e?.tokenAttributes??0,r=!1;if(this.balancedBracketSelectors?.matchesAlways&&(r=!0),this._tokenTypeOverrides.length>0||this.balancedBracketSelectors&&!this.balancedBracketSelectors.matchesAlways&&!this.balancedBracketSelectors.matchesNever){let t=e?.getScopeNames()??[];for(let e of this._tokenTypeOverrides)e.matcher(t)&&(n=$f.set(n,0,ep(e.type),null,-1,0,0));this.balancedBracketSelectors&&(r=this.balancedBracketSelectors.match(t))}if(r&&(n=$f.set(n,0,8,r,-1,0,0)),this._binaryTokens.length>0&&this._binaryTokens[this._binaryTokens.length-1]===n){this._lastTokenEndIndex=t;return}this._binaryTokens.push(this._lastTokenEndIndex),this._binaryTokens.push(n),this._lastTokenEndIndex=t;return}let n=e?.getScopeNames()??[];this._tokens.push({startIndex:this._lastTokenEndIndex,endIndex:t,scopes:n}),this._lastTokenEndIndex=t}getResult(e,t){return this._tokens.length>0&&this._tokens[this._tokens.length-1].startIndex===t-1&&this._tokens.pop(),this._tokens.length===0&&(this._lastTokenEndIndex=-1,this.produce(e,t),this._tokens[this._tokens.length-1].startIndex=0),this._tokens}getBinaryResult(e,t){this._binaryTokens.length>0&&this._binaryTokens[this._binaryTokens.length-2]===t-1&&(this._binaryTokens.pop(),this._binaryTokens.pop()),this._binaryTokens.length===0&&(this._lastTokenEndIndex=-1,this.produce(e,t),this._binaryTokens[this._binaryTokens.length-2]=0);let n=new Uint32Array(this._binaryTokens.length);for(let e=0,t=this._binaryTokens.length;e<t;e++)n[e]=this._binaryTokens[e];return n}},am=class{constructor(e,t){this._onigLib=t,this._theme=e}_grammars=new Map;_rawGrammars=new Map;_injectionGrammars=new Map;_theme;dispose(){for(let e of this._grammars.values())e.dispose()}setTheme(e){this._theme=e}getColorMap(){return this._theme.getColorMap()}addGrammar(e,t){this._rawGrammars.set(e.scopeName,e),t&&this._injectionGrammars.set(e.scopeName,t)}lookup(e){return this._rawGrammars.get(e)}injections(e){return this._injectionGrammars.get(e)}getDefaults(){return this._theme.getDefaults()}themeMatch(e){return this._theme.match(e)}grammarForScopeName(e,t,n,r,i){if(!this._grammars.has(e)){let a=this._rawGrammars.get(e);if(!a)return null;this._grammars.set(e,Yp(e,a,t,n,r,i,this,this._onigLib))}return this._grammars.get(e)}},om=class{_options;_syncRegistry;_ensureGrammarCache;constructor(e){this._options=e,this._syncRegistry=new am(Bf.createFromRawTheme(e.theme,e.colorMap),e.onigLib),this._ensureGrammarCache=new Map}dispose(){this._syncRegistry.dispose()}setTheme(e,t){this._syncRegistry.setTheme(Bf.createFromRawTheme(e,t))}getColorMap(){return this._syncRegistry.getColorMap()}loadGrammarWithEmbeddedLanguages(e,t,n){return this.loadGrammarWithConfiguration(e,t,{embeddedLanguages:n})}loadGrammarWithConfiguration(e,t,n){return this._loadGrammar(e,t,n.embeddedLanguages,n.tokenTypes,new rm(n.balancedBracketSelectors||[],n.unbalancedBracketSelectors||[]))}loadGrammar(e){return this._loadGrammar(e,0,null,null,null)}_loadGrammar(e,t,n,r,i){let a=new lp(this._syncRegistry,e);for(;a.Q.length>0;)a.Q.map(e=>this._loadSingleGrammar(e.scopeName)),a.processQueue();return this._grammarForScopeName(e,t,n,r,i)}_loadSingleGrammar(e){this._ensureGrammarCache.has(e)||(this._doLoadSingleGrammar(e),this._ensureGrammarCache.set(e,!0))}_doLoadSingleGrammar(e){let t=this._options.loadGrammar(e);if(t){let n=typeof this._options.getInjections==`function`?this._options.getInjections(e):void 0;this._syncRegistry.addGrammar(t,n)}}addGrammar(e,t=[],n=0,r=null){return this._syncRegistry.addGrammar(e,t),this._grammarForScopeName(e.scopeName,n,r)}_grammarForScopeName(e,t=0,n=null,r=null,i=null){return this._syncRegistry.grammarForScopeName(e,t,n,r,i)}},sm=nm.NULL;function cm(e,t){let n=typeof e==`string`?{}:{...e.colorReplacements},r=typeof e==`string`?e:e.name;for(let[e,i]of Object.entries(t?.colorReplacements||{}))typeof i==`string`?n[e]=i:e===r&&Object.assign(n,i);return n}function lm(e,t){return e&&(t?.[e?.toLowerCase()]||e)}function um(e){return Array.isArray(e)?e:[e]}async function dm(e){return Promise.resolve(typeof e==`function`?e():e).then(e=>e.default||e)}function fm(e){return!e||[`plaintext`,`txt`,`text`,`plain`].includes(e)}function pm(e){return e===`ansi`||fm(e)}function mm(e){return e===`none`}function hm(e){return mm(e)}var gm=/(\r?\n)/g;function _m(e,t=!1){if(e.length===0)return[[``,0]];let n=e.split(gm),r=0,i=[];for(let e=0;e<n.length;e+=2){let a=t?n[e]+(n[e+1]||``):n[e];i.push([a,r]),r+=n[e].length,r+=n[e+1]?.length||0}return i}var vm={light:`#333333`,dark:`#bbbbbb`},ym={light:`#fffffe`,dark:`#1e1e1e`},bm=`__shiki_resolved`;function xm(e){if(e?.[bm])return e;let t={...e};t.tokenColors&&!t.settings&&(t.settings=t.tokenColors,delete t.tokenColors),t.type||=`dark`,t.colorReplacements={...t.colorReplacements},t.settings||=[];let{bg:n,fg:r}=t;if(!n||!r){let e=t.settings?t.settings.find(e=>!e.name&&!e.scope):void 0;e?.settings?.foreground&&(r=e.settings.foreground),e?.settings?.background&&(n=e.settings.background),!r&&t?.colors?.[`editor.foreground`]&&(r=t.colors[`editor.foreground`]),!n&&t?.colors?.[`editor.background`]&&(n=t.colors[`editor.background`]),r||=t.type===`light`?vm.light:vm.dark,n||=t.type===`light`?ym.light:ym.dark,t.fg=r,t.bg=n}t.settings[0]&&t.settings[0].settings&&!t.settings[0].scope||t.settings.unshift({settings:{foreground:t.fg,background:t.bg}});let i=0,a=new Map;function o(e){if(a.has(e))return a.get(e);i+=1;let n=`#${i.toString(16).padStart(8,`0`).toLowerCase()}`;return t.colorReplacements?.[`#${n}`]?o(e):(a.set(e,n),n)}t.settings=t.settings.map(e=>{let n=e.settings?.foreground&&!e.settings.foreground.startsWith(`#`),r=e.settings?.background&&!e.settings.background.startsWith(`#`);if(!n&&!r)return e;let i={...e,settings:{...e.settings}};if(n){let n=o(e.settings.foreground);t.colorReplacements[n]=e.settings.foreground,i.settings.foreground=n}if(r){let n=o(e.settings.background);t.colorReplacements[n]=e.settings.background,i.settings.background=n}return i});for(let e of Object.keys(t.colors||{}))if((e===`editor.foreground`||e===`editor.background`||e.startsWith(`terminal.ansi`))&&!t.colors[e]?.startsWith(`#`)){let n=o(t.colors[e]);t.colorReplacements[n]=t.colors[e],t.colors[e]=n}return Object.defineProperty(t,bm,{enumerable:!1,writable:!1,value:!0}),t}async function Sm(e){return[...new Set((await Promise.all(e.filter(e=>!pm(e)).map(async e=>await dm(e).then(e=>Array.isArray(e)?e:[e])))).flat())]}async function Cm(e){return(await Promise.all(e.map(async e=>hm(e)?null:xm(await dm(e))))).filter(e=>!!e)}function wm(e,t){if(!t)return e;if(t[e]){let n=new Set([e]);for(;t[e];){if(e=t[e],n.has(e))throw new Ef(`Circular alias \`${[...n].join(` -> `)} -> ${e}\``);n.add(e)}}return e}var Tm=class extends om{_resolver;_themes;_langs;_alias;_resolvedThemes=new Map;_resolvedGrammars=new Map;_langMap=new Map;_langGraph=new Map;_textmateThemeCache=new WeakMap;_loadedThemesCache=null;_loadedLanguagesCache=null;constructor(e,t,n,r={}){super(e),this._resolver=e,this._themes=t,this._langs=n,this._alias=r,this._themes.map(e=>this.loadTheme(e)),this.loadLanguages(this._langs)}getTheme(e){return typeof e==`string`?this._resolvedThemes.get(e):this.loadTheme(e)}loadTheme(e){let t=xm(e);return t.name&&(this._resolvedThemes.set(t.name,t),this._loadedThemesCache=null),t}getLoadedThemes(){return this._loadedThemesCache||=[...this._resolvedThemes.keys()],this._loadedThemesCache}setTheme(e){let t=this._textmateThemeCache.get(e);t||(t=Bf.createFromRawTheme(e),this._textmateThemeCache.set(e,t)),this._syncRegistry.setTheme(t)}getGrammar(e){return e=wm(e,this._alias),this._resolvedGrammars.get(e)}loadLanguage(e){if(this.getGrammar(e.name))return;let t=new Set([...this._langMap.values()].filter(t=>t.embeddedLangsLazy?.includes(e.name)));this._resolver.addLanguage(e);let n={balancedBracketSelectors:e.balancedBracketSelectors||[`*`],unbalancedBracketSelectors:e.unbalancedBracketSelectors||[]};this._syncRegistry._rawGrammars.set(e.scopeName,e);let r=this.loadGrammarWithConfiguration(e.scopeName,1,n);if(r.name=e.name,this._resolvedGrammars.set(e.name,r),e.aliases&&e.aliases.forEach(t=>{this._alias[t]=e.name}),this._loadedLanguagesCache=null,t.size)for(let e of t)this._syncRegistry?._grammars?.get(e.scopeName)?.dispose(),this._resolvedGrammars.delete(e.name),this._loadedLanguagesCache=null,this._syncRegistry?._injectionGrammars?.delete(e.scopeName),this._syncRegistry?._grammars?.delete(e.scopeName),this.loadLanguage(this._langMap.get(e.name))}dispose(){super.dispose(),this._resolvedThemes.clear(),this._resolvedGrammars.clear(),this._langMap.clear(),this._langGraph.clear(),this._loadedThemesCache=null}loadLanguages(e){for(let t of e)this.resolveEmbeddedLanguages(t);let t=[...this._langGraph.entries()],n=t.filter(([e,t])=>!t);if(n.length){let e=t.filter(([e,t])=>t?(t.embeddedLanguages||t.embeddedLangs)?.some(e=>n.map(([e])=>e).includes(e)):!1).filter(e=>!n.includes(e));throw new Ef(`Missing languages ${n.map(([e])=>`\`${e}\``).join(`, `)}, required by ${e.map(([e])=>`\`${e}\``).join(`, `)}`)}for(let[e,n]of t)this._resolver.addLanguage(n);for(let[e,n]of t)this.loadLanguage(n)}getLoadedLanguages(){return this._loadedLanguagesCache||=[...new Set([...this._resolvedGrammars.keys(),...Object.keys(this._alias)])],this._loadedLanguagesCache}resolveEmbeddedLanguages(e){this._langMap.set(e.name,e),this._langGraph.set(e.name,e);let t=e.embeddedLanguages??e.embeddedLangs;if(t)for(let e of t)this._langGraph.set(e,this._langMap.get(e))}},Em=class{_langs=new Map;_scopeToLang=new Map;_injections=new Map;_onigLib;constructor(e,t){this._onigLib={createOnigScanner:t=>e.createScanner(t),createOnigString:t=>e.createString(t)},t.forEach(e=>this.addLanguage(e))}get onigLib(){return this._onigLib}getLangRegistration(e){return this._langs.get(e)}loadGrammar(e){return this._scopeToLang.get(e)}addLanguage(e){this._langs.set(e.name,e),e.aliases&&e.aliases.forEach(t=>{this._langs.set(t,e)}),this._scopeToLang.set(e.scopeName,e),e.injectTo&&e.injectTo.forEach(t=>{this._injections.get(t)||this._injections.set(t,[]),this._injections.get(t).includes(e.scopeName)||this._injections.get(t).push(e.scopeName)})}getInjections(e){let t=e.split(`.`),n=[];for(let e=1;e<=t.length;e++){let r=t.slice(0,e).join(`.`);n=[...n,...this._injections.get(r)||[]]}return n}},Dm=0;function Om(e){Dm+=1,e.warnings!==!1&&Dm>=10&&Dm%10==0&&console.warn(`[Shiki] ${Dm} instances have been created. Shiki is supposed to be used as a singleton, consider refactoring your code to cache your highlighter instance; Or call \`highlighter.dispose()\` to release unused instances.`);let t=!1;if(!e.engine)throw new Ef("`engine` option is required for synchronous mode");let n=(e.langs||[]).flat(1),r=(e.themes||[]).flat(1).map(xm),i=new Tm(new Em(e.engine,n),r,n,e.langAlias),a;function o(t){return wm(t,e.langAlias)}function s(e){g();let t=i.getGrammar(typeof e==`string`?e:e.name);if(!t)throw new Ef(`Language \`${e}\` not found, you may need to load it first`);return t}function c(e){if(e===`none`)return{bg:``,fg:``,name:`none`,settings:[],type:`dark`};g();let t=i.getTheme(e);if(!t)throw new Ef(`Theme \`${e}\` not found, you may need to load it first`);return t}function l(e){g();let t=c(e);return a!==e&&(i.setTheme(t),a=e),{theme:t,colorMap:i.getColorMap()}}function u(){return g(),i.getLoadedThemes()}function d(){return g(),i.getLoadedLanguages()}function f(...e){g(),i.loadLanguages(e.flat(1))}async function p(...e){return f(await Sm(e))}function m(...e){g();for(let t of e.flat(1))i.loadTheme(t)}async function h(...e){return g(),m(await Cm(e))}function g(){if(t)throw new Ef(`Shiki instance has been disposed`)}function _(){t||(t=!0,i.dispose(),--Dm)}return{setTheme:l,getTheme:c,getLanguage:s,getLoadedThemes:u,getLoadedLanguages:d,resolveLangAlias:o,loadLanguage:p,loadLanguageSync:f,loadTheme:h,loadThemeSync:m,dispose:_,[Symbol.dispose]:_}}async function km(e){e.engine||console.warn("`engine` option is required. Use `createOnigurumaEngine` or `createJavaScriptRegexEngine` to create an engine.");let[t,n,r]=await Promise.all([Cm(e.themes||[]),Sm(e.langs||[]),e.engine]);return Om({...e,themes:t,langs:n,engine:r})}var Am=new WeakMap;function jm(e,t){Am.set(e,t)}function Mm(e){return Am.get(e)}var Nm=class e{_stacks={};lang;get themes(){return Object.keys(this._stacks)}get theme(){return this.themes[0]}get _stack(){return this._stacks[this.theme]}static initial(t,n){return new e(Object.fromEntries(um(n).map(e=>[e,sm])),t)}constructor(...e){if(e.length===2){let[t,n]=e;this.lang=n,this._stacks=t}else{let[t,n,r]=e;this.lang=n,this._stacks={[r]:t}}}getInternalStack(e=this.theme){return this._stacks[e]}getScopes(e=this.theme){return Pm(this._stacks[e])}toJSON(){return{lang:this.lang,theme:this.theme,themes:this.themes,scopes:this.getScopes()}}};function Pm(e){let t=[],n=new Set;function r(e){if(n.has(e))return;n.add(e);let i=e?.nameScopesList?.scopeName;i&&t.push(i),e.parent&&r(e.parent)}return r(e),t}function Fm(e,t){if(!(e instanceof Nm))throw new Ef(`Invalid grammar state`);return e.getInternalStack(t)}var Im=/,/,Lm=/ /;function Rm(e,t,n={}){let{theme:r=e.getLoadedThemes()[0]}=n;if(fm(e.resolveLangAlias(n.lang||`text`))||mm(r))return _m(t).map(e=>[{content:e[0],offset:e[1]}]);let{theme:i,colorMap:a}=e.setTheme(r),o=e.getLanguage(n.lang||`text`);if(n.grammarState){if(n.grammarState.lang!==o.name)throw new Ef(`Grammar state language "${n.grammarState.lang}" does not match highlight language "${o.name}"`);if(!n.grammarState.themes.includes(i.name))throw new Ef(`Grammar state themes "${n.grammarState.themes}" do not contain highlight theme "${i.name}"`)}return Bm(t,o,i,a,n)}function zm(...e){if(e.length===2)return Mm(e[1]);let[t,n,r={}]=e,{lang:i=`text`,theme:a=t.getLoadedThemes()[0]}=r;if(fm(i)||mm(a))throw new Ef(`Plain language does not have grammar state`);if(i===`ansi`)throw new Ef(`ANSI language does not have grammar state`);let{theme:o,colorMap:s}=t.setTheme(a),c=t.getLanguage(i);return new Nm(Vm(n,c,o,s,r).stateStack,c.name,o.name)}function Bm(e,t,n,r,i){let a=Vm(e,t,n,r,i),o=new Nm(a.stateStack,t.name,n.name);return jm(a.tokens,o),a.tokens}function Vm(e,t,n,r,i){let a=cm(n,i),{tokenizeMaxLineLength:o=0,tokenizeTimeLimit:s=500,includeExplanation:c=!1}=i,l=_m(e),u=i.grammarState?Fm(i.grammarState,n.name)??sm:i.grammarContextCode==null?sm:Vm(i.grammarContextCode,t,n,r,{...i,grammarState:void 0,grammarContextCode:void 0}).stateStack,d=[],f=[];for(let e=0,i=l.length;e<i;e++){let[i,p]=l[e];if(i===``){d=[],f.push([]);continue}if(o>0&&i.length>=o){d=[],f.push([{content:i,offset:p,color:``,fontStyle:0}]);continue}let m,h,g;c&&c!==`tokenType`&&(m=t.tokenizeLine(i,u,s),h=m.tokens,g=0);let _=t.tokenizeLine2(i,u,s),v=_.tokens.length/2;for(let e=0;e<v;e++){let t=_.tokens[2*e],o=e+1<v?_.tokens[2*e+2]:i.length;if(t===o)continue;let s=_.tokens[2*e+1],l=lm(r[$f.getForeground(s)],a),u=$f.getFontStyle(s),f={content:i.substring(t,o),offset:p+t,color:l,fontStyle:u};if(c===`tokenType`)f.type=$f.getTokenType(s);else if(c){let e=[];if(c!==`scopeName`)for(let t of n.settings){let n;switch(typeof t.scope){case`string`:n=t.scope.split(Im).map(e=>e.trim());break;case`object`:n=t.scope;break;default:continue}e.push({settings:t,selectors:n.map(e=>e.split(Lm))})}f.explanation=[];let r=0;for(;t+r<o;){let t=h[g],n=i.substring(t.startIndex,t.endIndex);r+=n.length,f.explanation.push({content:n,scopes:c===`scopeName`?Hm(t.scopes):Um(e,t.scopes)}),g+=1}}d.push(f)}f.push(d),d=[],u=_.ruleStack}return{tokens:f,stateStack:u}}function Hm(e){return e.map(e=>({scopeName:e}))}function Um(e,t){let n=[];for(let r=0,i=t.length;r<i;r++){let i=t[r];n[r]={scopeName:i,themeMatches:Km(e,i,t.slice(0,r))}}return n}function Wm(e,t){return e===t||t.substring(0,e.length)===e&&t[e.length]===`.`}function Gm(e,t,n){if(!Wm(e.at(-1),t))return!1;let r=e.length-2,i=n.length-1;for(;r>=0&&i>=0;)Wm(e[r],n[i])&&--r,--i;return r===-1}function Km(e,t,n){let r=[];for(let{selectors:i,settings:a}of e)for(let e of i)if(Gm(e,t,n)){r.push(a);break}return r}function qm(e,t,n,r=Rm){let i=Object.entries(n.themes).filter(e=>e[1]).map(e=>({color:e[0],theme:e[1]})),a=i.map(i=>{let a=r(e,t,{...n,theme:i.theme});return{tokens:a,state:Mm(a),theme:typeof i.theme==`string`?i.theme:i.theme.name}}),o=Jm(...a.map(e=>e.tokens)),s=o[0].map((e,t)=>e.map((e,r)=>{let a={content:e.content,variants:{},offset:e.offset};return`includeExplanation`in n&&n.includeExplanation&&(a.explanation=e.explanation),o.forEach((e,n)=>{let{content:o,explanation:s,offset:c,...l}=e[t][r];a.variants[i[n].color]=l}),a})),c=a[0].state?new Nm(Object.fromEntries(a.map(e=>[e.theme,e.state?.getInternalStack(e.theme)])),a[0].state.lang):void 0;return c&&jm(s,c),s}function Jm(...e){let t=e.map(()=>[]),n=e.length;for(let r=0;r<e[0].length;r++){let i=e.map(e=>e[r]),a=t.map(()=>[]);t.forEach((e,t)=>e.push(a[t]));let o=i.map(()=>0),s=i.map(e=>e[0]);for(;s.every(e=>e);){let e=Math.min(...s.map(e=>e.content.length));for(let t=0;t<n;t++){let n=s[t];n.content.length===e?(a[t].push(n),o[t]+=1,s[t]=i[t][o[t]]):(a[t].push({...n,content:n.content.slice(0,e)}),s[t]={...n,content:n.content.slice(e),offset:n.offset+e})}}}return t}var Ym=[`area`,`base`,`basefont`,`bgsound`,`br`,`col`,`command`,`embed`,`frame`,`hr`,`image`,`img`,`input`,`keygen`,`link`,`meta`,`param`,`source`,`track`,`wbr`],Xm=class{constructor(e,t,n){this.normal=t,this.property=e,n&&(this.space=n)}};Xm.prototype.normal={},Xm.prototype.property={},Xm.prototype.space=void 0;function Zm(e,t){let n={},r={};for(let t of e)Object.assign(n,t.property),Object.assign(r,t.normal);return new Xm(n,r,t)}function Qm(e){return e.toLowerCase()}var $m=class{constructor(e,t){this.attribute=t,this.property=e}};$m.prototype.attribute=``,$m.prototype.booleanish=!1,$m.prototype.boolean=!1,$m.prototype.commaOrSpaceSeparated=!1,$m.prototype.commaSeparated=!1,$m.prototype.defined=!1,$m.prototype.mustUseProperty=!1,$m.prototype.number=!1,$m.prototype.overloadedBoolean=!1,$m.prototype.property=``,$m.prototype.spaceSeparated=!1,$m.prototype.space=void 0;var eh=t({boolean:()=>X,booleanish:()=>nh,commaOrSpaceSeparated:()=>ah,commaSeparated:()=>ih,number:()=>Z,overloadedBoolean:()=>rh,spaceSeparated:()=>Q}),th=0,X=oh(),nh=oh(),rh=oh(),Z=oh(),Q=oh(),ih=oh(),ah=oh();function oh(){return 2**++th}var sh=Object.keys(eh),ch=class extends $m{constructor(e,t,n,r){let i=-1;if(super(e,t),lh(this,`space`,r),typeof n==`number`)for(;++i<sh.length;){let e=sh[i];lh(this,sh[i],(n&eh[e])===eh[e])}}};ch.prototype.defined=!0;function lh(e,t,n){n&&(e[t]=n)}function uh(e){let t={},n={};for(let[r,i]of Object.entries(e.properties)){let a=new ch(r,e.transform(e.attributes||{},r),i,e.space);e.mustUseProperty&&e.mustUseProperty.includes(r)&&(a.mustUseProperty=!0),t[r]=a,n[Qm(r)]=r,n[Qm(a.attribute)]=r}return new Xm(t,n,e.space)}var dh=uh({properties:{ariaActiveDescendant:null,ariaAtomic:nh,ariaAutoComplete:null,ariaBusy:nh,ariaChecked:nh,ariaColCount:Z,ariaColIndex:Z,ariaColSpan:Z,ariaControls:Q,ariaCurrent:null,ariaDescribedBy:Q,ariaDetails:null,ariaDisabled:nh,ariaDropEffect:Q,ariaErrorMessage:null,ariaExpanded:nh,ariaFlowTo:Q,ariaGrabbed:nh,ariaHasPopup:null,ariaHidden:nh,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:Q,ariaLevel:Z,ariaLive:null,ariaModal:nh,ariaMultiLine:nh,ariaMultiSelectable:nh,ariaOrientation:null,ariaOwns:Q,ariaPlaceholder:null,ariaPosInSet:Z,ariaPressed:nh,ariaReadOnly:nh,ariaRelevant:null,ariaRequired:nh,ariaRoleDescription:Q,ariaRowCount:Z,ariaRowIndex:Z,ariaRowSpan:Z,ariaSelected:nh,ariaSetSize:Z,ariaSort:null,ariaValueMax:Z,ariaValueMin:Z,ariaValueNow:Z,ariaValueText:null,role:null},transform(e,t){return t===`role`?t:`aria-`+t.slice(4).toLowerCase()}});function fh(e,t){return t in e?e[t]:t}function ph(e,t){return fh(e,t.toLowerCase())}var mh=uh({attributes:{acceptcharset:`accept-charset`,classname:`class`,htmlfor:`for`,httpequiv:`http-equiv`},mustUseProperty:[`checked`,`multiple`,`muted`,`selected`],properties:{abbr:null,accept:ih,acceptCharset:Q,accessKey:Q,action:null,allow:null,allowFullScreen:X,allowPaymentRequest:X,allowUserMedia:X,alpha:X,alt:null,as:null,async:X,autoCapitalize:null,autoComplete:Q,autoFocus:X,autoPlay:X,blocking:Q,capture:null,charSet:null,checked:X,cite:null,className:Q,closedBy:null,colorSpace:null,cols:Z,colSpan:Z,command:null,commandFor:null,content:null,contentEditable:nh,controls:X,controlsList:Q,coords:Z|ih,crossOrigin:null,data:null,dateTime:null,decoding:null,default:X,defer:X,dir:null,dirName:null,disabled:X,download:rh,draggable:nh,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:X,formTarget:null,headers:Q,height:Z,hidden:rh,high:Z,href:null,hrefLang:null,htmlFor:Q,httpEquiv:Q,id:null,imageSizes:null,imageSrcSet:null,inert:X,inputMode:null,integrity:null,is:null,isMap:X,itemId:null,itemProp:Q,itemRef:Q,itemScope:X,itemType:Q,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:X,low:Z,manifest:null,max:null,maxLength:Z,media:null,method:null,min:null,minLength:Z,multiple:X,muted:X,name:null,nonce:null,noModule:X,noValidate:X,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:X,optimum:Z,pattern:null,ping:Q,placeholder:null,playsInline:X,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:X,referrerPolicy:null,rel:Q,required:X,reversed:X,rows:Z,rowSpan:Z,sandbox:Q,scope:null,scoped:X,seamless:X,selected:X,shadowRootClonable:X,shadowRootCustomElementRegistry:X,shadowRootDelegatesFocus:X,shadowRootMode:null,shadowRootSerializable:X,shape:null,size:Z,sizes:null,slot:null,span:Z,spellCheck:nh,src:null,srcDoc:null,srcLang:null,srcSet:null,start:Z,step:null,style:null,tabIndex:Z,target:null,title:null,translate:null,type:null,typeMustMatch:X,useMap:null,value:nh,width:Z,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:Q,axis:null,background:null,bgColor:null,border:Z,borderColor:null,bottomMargin:Z,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:X,declare:X,event:null,face:null,frame:null,frameBorder:null,hSpace:Z,leftMargin:Z,link:null,longDesc:null,lowSrc:null,marginHeight:Z,marginWidth:Z,noResize:X,noHref:X,noShade:X,noWrap:X,object:null,profile:null,prompt:null,rev:null,rightMargin:Z,rules:null,scheme:null,scrolling:nh,standby:null,summary:null,text:null,topMargin:Z,valueType:null,version:null,vAlign:null,vLink:null,vSpace:Z,allowTransparency:null,autoCorrect:null,autoSave:null,credentialless:X,disablePictureInPicture:X,disableRemotePlayback:X,exportParts:ih,part:Q,prefix:null,property:null,results:Z,security:null,unselectable:null},space:`html`,transform:ph}),hh=uh({attributes:{accentHeight:`accent-height`,alignmentBaseline:`alignment-baseline`,arabicForm:`arabic-form`,baselineShift:`baseline-shift`,capHeight:`cap-height`,className:`class`,clipPath:`clip-path`,clipRule:`clip-rule`,colorInterpolation:`color-interpolation`,colorInterpolationFilters:`color-interpolation-filters`,colorProfile:`color-profile`,colorRendering:`color-rendering`,crossOrigin:`crossorigin`,dataType:`datatype`,dominantBaseline:`dominant-baseline`,enableBackground:`enable-background`,fillOpacity:`fill-opacity`,fillRule:`fill-rule`,floodColor:`flood-color`,floodOpacity:`flood-opacity`,fontFamily:`font-family`,fontSize:`font-size`,fontSizeAdjust:`font-size-adjust`,fontStretch:`font-stretch`,fontStyle:`font-style`,fontVariant:`font-variant`,fontWeight:`font-weight`,glyphName:`glyph-name`,glyphOrientationHorizontal:`glyph-orientation-horizontal`,glyphOrientationVertical:`glyph-orientation-vertical`,hrefLang:`hreflang`,horizAdvX:`horiz-adv-x`,horizOriginX:`horiz-origin-x`,horizOriginY:`horiz-origin-y`,imageRendering:`image-rendering`,letterSpacing:`letter-spacing`,lightingColor:`lighting-color`,markerEnd:`marker-end`,markerMid:`marker-mid`,markerStart:`marker-start`,maskType:`mask-type`,navDown:`nav-down`,navDownLeft:`nav-down-left`,navDownRight:`nav-down-right`,navLeft:`nav-left`,navNext:`nav-next`,navPrev:`nav-prev`,navRight:`nav-right`,navUp:`nav-up`,navUpLeft:`nav-up-left`,navUpRight:`nav-up-right`,onAbort:`onabort`,onActivate:`onactivate`,onAfterPrint:`onafterprint`,onBeforePrint:`onbeforeprint`,onBegin:`onbegin`,onCancel:`oncancel`,onCanPlay:`oncanplay`,onCanPlayThrough:`oncanplaythrough`,onChange:`onchange`,onClick:`onclick`,onClose:`onclose`,onCopy:`oncopy`,onCueChange:`oncuechange`,onCut:`oncut`,onDblClick:`ondblclick`,onDrag:`ondrag`,onDragEnd:`ondragend`,onDragEnter:`ondragenter`,onDragExit:`ondragexit`,onDragLeave:`ondragleave`,onDragOver:`ondragover`,onDragStart:`ondragstart`,onDrop:`ondrop`,onDurationChange:`ondurationchange`,onEmptied:`onemptied`,onEnd:`onend`,onEnded:`onended`,onError:`onerror`,onFocus:`onfocus`,onFocusIn:`onfocusin`,onFocusOut:`onfocusout`,onHashChange:`onhashchange`,onInput:`oninput`,onInvalid:`oninvalid`,onKeyDown:`onkeydown`,onKeyPress:`onkeypress`,onKeyUp:`onkeyup`,onLoad:`onload`,onLoadedData:`onloadeddata`,onLoadedMetadata:`onloadedmetadata`,onLoadStart:`onloadstart`,onMessage:`onmessage`,onMouseDown:`onmousedown`,onMouseEnter:`onmouseenter`,onMouseLeave:`onmouseleave`,onMouseMove:`onmousemove`,onMouseOut:`onmouseout`,onMouseOver:`onmouseover`,onMouseUp:`onmouseup`,onMouseWheel:`onmousewheel`,onOffline:`onoffline`,onOnline:`ononline`,onPageHide:`onpagehide`,onPageShow:`onpageshow`,onPaste:`onpaste`,onPause:`onpause`,onPlay:`onplay`,onPlaying:`onplaying`,onPopState:`onpopstate`,onProgress:`onprogress`,onRateChange:`onratechange`,onRepeat:`onrepeat`,onReset:`onreset`,onResize:`onresize`,onScroll:`onscroll`,onSeeked:`onseeked`,onSeeking:`onseeking`,onSelect:`onselect`,onShow:`onshow`,onStalled:`onstalled`,onStorage:`onstorage`,onSubmit:`onsubmit`,onSuspend:`onsuspend`,onTimeUpdate:`ontimeupdate`,onToggle:`ontoggle`,onUnload:`onunload`,onVolumeChange:`onvolumechange`,onWaiting:`onwaiting`,onZoom:`onzoom`,overlinePosition:`overline-position`,overlineThickness:`overline-thickness`,paintOrder:`paint-order`,panose1:`panose-1`,pointerEvents:`pointer-events`,referrerPolicy:`referrerpolicy`,renderingIntent:`rendering-intent`,shapeRendering:`shape-rendering`,stopColor:`stop-color`,stopOpacity:`stop-opacity`,strikethroughPosition:`strikethrough-position`,strikethroughThickness:`strikethrough-thickness`,strokeDashArray:`stroke-dasharray`,strokeDashOffset:`stroke-dashoffset`,strokeLineCap:`stroke-linecap`,strokeLineJoin:`stroke-linejoin`,strokeMiterLimit:`stroke-miterlimit`,strokeOpacity:`stroke-opacity`,strokeWidth:`stroke-width`,tabIndex:`tabindex`,textAnchor:`text-anchor`,textDecoration:`text-decoration`,textRendering:`text-rendering`,transformOrigin:`transform-origin`,typeOf:`typeof`,underlinePosition:`underline-position`,underlineThickness:`underline-thickness`,unicodeBidi:`unicode-bidi`,unicodeRange:`unicode-range`,unitsPerEm:`units-per-em`,vAlphabetic:`v-alphabetic`,vHanging:`v-hanging`,vIdeographic:`v-ideographic`,vMathematical:`v-mathematical`,vectorEffect:`vector-effect`,vertAdvY:`vert-adv-y`,vertOriginX:`vert-origin-x`,vertOriginY:`vert-origin-y`,wordSpacing:`word-spacing`,writingMode:`writing-mode`,xHeight:`x-height`,playbackOrder:`playbackorder`,timelineBegin:`timelinebegin`},properties:{about:ah,accentHeight:Z,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:Z,amplitude:Z,arabicForm:null,ascent:Z,attributeName:null,attributeType:null,azimuth:Z,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:Z,by:null,calcMode:null,capHeight:Z,className:Q,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:Z,diffuseConstant:Z,direction:null,display:null,dur:null,divisor:Z,dominantBaseline:null,download:X,dx:null,dy:null,edgeMode:null,editable:null,elevation:Z,enableBackground:null,end:null,event:null,exponent:Z,externalResourcesRequired:null,fill:null,fillOpacity:Z,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:ih,g2:ih,glyphName:ih,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:Z,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:Z,horizOriginX:Z,horizOriginY:Z,id:null,ideographic:Z,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:Z,k:Z,k1:Z,k2:Z,k3:Z,k4:Z,kernelMatrix:ah,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:Z,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskType:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:Z,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:Z,overlineThickness:Z,paintOrder:null,panose1:null,path:null,pathLength:Z,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:Q,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:Z,pointsAtY:Z,pointsAtZ:Z,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:ah,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:ah,rev:ah,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:ah,requiredFeatures:ah,requiredFonts:ah,requiredFormats:ah,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:Z,specularExponent:Z,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:Z,strikethroughThickness:Z,string:null,stroke:null,strokeDashArray:ah,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:Z,strokeOpacity:Z,strokeWidth:null,style:null,surfaceScale:Z,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:ah,tabIndex:Z,tableValues:null,target:null,targetX:Z,targetY:Z,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:ah,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:Z,underlineThickness:Z,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:Z,values:null,vAlphabetic:Z,vMathematical:Z,vectorEffect:null,vHanging:Z,vIdeographic:Z,version:null,vertAdvY:Z,vertOriginX:Z,vertOriginY:Z,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:Z,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:`svg`,transform:fh}),gh=uh({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:`xlink`,transform(e,t){return`xlink:`+t.slice(5).toLowerCase()}}),_h=uh({attributes:{xmlnsxlink:`xmlns:xlink`},properties:{xmlnsXLink:null,xmlns:null},space:`xmlns`,transform:ph}),vh=uh({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:`xml`,transform(e,t){return`xml:`+t.slice(3).toLowerCase()}}),yh=/[A-Z]/g,bh=/-[a-z]/g,xh=/^data[-\w.:]+$/i;function Sh(e,t){let n=Qm(t),r=t,i=$m;if(n in e.normal)return e.property[e.normal[n]];if(n.length>4&&n.slice(0,4)===`data`&&xh.test(t)){if(t.charAt(4)===`-`){let e=t.slice(5).replace(bh,wh);r=`data`+e.charAt(0).toUpperCase()+e.slice(1)}else{let e=t.slice(4);if(!bh.test(e)){let n=e.replace(yh,Ch);n.charAt(0)!==`-`&&(n=`-`+n),t=`data`+n}}i=ch}return new i(r,t)}function Ch(e){return`-`+e.toLowerCase()}function wh(e){return e.charAt(1).toUpperCase()}var Th=Zm([dh,mh,gh,_h,vh],`html`),Eh=Zm([dh,hh,gh,_h,vh],`svg`),Dh={}.hasOwnProperty;function Oh(e,t){let n=t||{};function r(t,...n){let i=r.invalid,a=r.handlers;if(t&&Dh.call(t,e)){let n=String(t[e]);i=Dh.call(a,n)?a[n]:r.unknown}if(i)return i.call(this,t,...n)}return r.handlers=n.handlers||{},r.invalid=n.invalid,r.unknown=n.unknown,r}var kh=/["&'<>`]/g,Ah=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,jh=/[\x01-\t\v\f\x0E-\x1F\x7F\x81\x8D\x8F\x90\x9D\xA0-\uFFFF]/g,Mh=/[|\\{}()[\]^$+*?.]/g,Nh=new WeakMap;function Ph(e,t){return e=e.replace(t.subset?Fh(t.subset):kh,r),t.subset||t.escapeOnly?e:e.replace(Ah,n).replace(jh,r);function n(e,n,r){return t.format((e.charCodeAt(0)-55296)*1024+e.charCodeAt(1)-56320+65536,r.charCodeAt(n+2),t)}function r(e,n,r){return t.format(e.charCodeAt(0),r.charCodeAt(n+1),t)}}function Fh(e){let t=Nh.get(e);return t||(t=Ih(e),Nh.set(e,t)),t}function Ih(e){let t=[],n=-1;for(;++n<e.length;)t.push(e[n].replace(Mh,`\\$&`));return RegExp(`(?:`+t.join(`|`)+`)`,`g`)}var Lh=/[\dA-Fa-f]/;function Rh(e,t,n){let r=`&#x`+e.toString(16).toUpperCase();return n&&t&&!Lh.test(String.fromCharCode(t))?r:r+`;`}var zh=/\d/;function Bh(e,t,n){let r=`&#`+String(e);return n&&t&&!zh.test(String.fromCharCode(t))?r:r+`;`}var Vh=`AElig.AMP.Aacute.Acirc.Agrave.Aring.Atilde.Auml.COPY.Ccedil.ETH.Eacute.Ecirc.Egrave.Euml.GT.Iacute.Icirc.Igrave.Iuml.LT.Ntilde.Oacute.Ocirc.Ograve.Oslash.Otilde.Ouml.QUOT.REG.THORN.Uacute.Ucirc.Ugrave.Uuml.Yacute.aacute.acirc.acute.aelig.agrave.amp.aring.atilde.auml.brvbar.ccedil.cedil.cent.copy.curren.deg.divide.eacute.ecirc.egrave.eth.euml.frac12.frac14.frac34.gt.iacute.icirc.iexcl.igrave.iquest.iuml.laquo.lt.macr.micro.middot.nbsp.not.ntilde.oacute.ocirc.ograve.ordf.ordm.oslash.otilde.ouml.para.plusmn.pound.quot.raquo.reg.sect.shy.sup1.sup2.sup3.szlig.thorn.times.uacute.ucirc.ugrave.uml.uuml.yacute.yen.yuml`.split(`.`),Hh={nbsp:`\xA0`,iexcl:`¡`,cent:`¢`,pound:`£`,curren:`¤`,yen:`¥`,brvbar:`¦`,sect:`§`,uml:`¨`,copy:`©`,ordf:`ª`,laquo:`«`,not:`¬`,shy:`­`,reg:`®`,macr:`¯`,deg:`°`,plusmn:`±`,sup2:`²`,sup3:`³`,acute:`´`,micro:`µ`,para:`¶`,middot:`·`,cedil:`¸`,sup1:`¹`,ordm:`º`,raquo:`»`,frac14:`¼`,frac12:`½`,frac34:`¾`,iquest:`¿`,Agrave:`À`,Aacute:`Á`,Acirc:`Â`,Atilde:`Ã`,Auml:`Ä`,Aring:`Å`,AElig:`Æ`,Ccedil:`Ç`,Egrave:`È`,Eacute:`É`,Ecirc:`Ê`,Euml:`Ë`,Igrave:`Ì`,Iacute:`Í`,Icirc:`Î`,Iuml:`Ï`,ETH:`Ð`,Ntilde:`Ñ`,Ograve:`Ò`,Oacute:`Ó`,Ocirc:`Ô`,Otilde:`Õ`,Ouml:`Ö`,times:`×`,Oslash:`Ø`,Ugrave:`Ù`,Uacute:`Ú`,Ucirc:`Û`,Uuml:`Ü`,Yacute:`Ý`,THORN:`Þ`,szlig:`ß`,agrave:`à`,aacute:`á`,acirc:`â`,atilde:`ã`,auml:`ä`,aring:`å`,aelig:`æ`,ccedil:`ç`,egrave:`è`,eacute:`é`,ecirc:`ê`,euml:`ë`,igrave:`ì`,iacute:`í`,icirc:`î`,iuml:`ï`,eth:`ð`,ntilde:`ñ`,ograve:`ò`,oacute:`ó`,ocirc:`ô`,otilde:`õ`,ouml:`ö`,divide:`÷`,oslash:`ø`,ugrave:`ù`,uacute:`ú`,ucirc:`û`,uuml:`ü`,yacute:`ý`,thorn:`þ`,yuml:`ÿ`,fnof:`ƒ`,Alpha:`Α`,Beta:`Β`,Gamma:`Γ`,Delta:`Δ`,Epsilon:`Ε`,Zeta:`Ζ`,Eta:`Η`,Theta:`Θ`,Iota:`Ι`,Kappa:`Κ`,Lambda:`Λ`,Mu:`Μ`,Nu:`Ν`,Xi:`Ξ`,Omicron:`Ο`,Pi:`Π`,Rho:`Ρ`,Sigma:`Σ`,Tau:`Τ`,Upsilon:`Υ`,Phi:`Φ`,Chi:`Χ`,Psi:`Ψ`,Omega:`Ω`,alpha:`α`,beta:`β`,gamma:`γ`,delta:`δ`,epsilon:`ε`,zeta:`ζ`,eta:`η`,theta:`θ`,iota:`ι`,kappa:`κ`,lambda:`λ`,mu:`μ`,nu:`ν`,xi:`ξ`,omicron:`ο`,pi:`π`,rho:`ρ`,sigmaf:`ς`,sigma:`σ`,tau:`τ`,upsilon:`υ`,phi:`φ`,chi:`χ`,psi:`ψ`,omega:`ω`,thetasym:`ϑ`,upsih:`ϒ`,piv:`ϖ`,bull:`•`,hellip:`…`,prime:`′`,Prime:`″`,oline:`‾`,frasl:`⁄`,weierp:`℘`,image:`ℑ`,real:`ℜ`,trade:`™`,alefsym:`ℵ`,larr:`←`,uarr:`↑`,rarr:`→`,darr:`↓`,harr:`↔`,crarr:`↵`,lArr:`⇐`,uArr:`⇑`,rArr:`⇒`,dArr:`⇓`,hArr:`⇔`,forall:`∀`,part:`∂`,exist:`∃`,empty:`∅`,nabla:`∇`,isin:`∈`,notin:`∉`,ni:`∋`,prod:`∏`,sum:`∑`,minus:`−`,lowast:`∗`,radic:`√`,prop:`∝`,infin:`∞`,ang:`∠`,and:`∧`,or:`∨`,cap:`∩`,cup:`∪`,int:`∫`,there4:`∴`,sim:`∼`,cong:`≅`,asymp:`≈`,ne:`≠`,equiv:`≡`,le:`≤`,ge:`≥`,sub:`⊂`,sup:`⊃`,nsub:`⊄`,sube:`⊆`,supe:`⊇`,oplus:`⊕`,otimes:`⊗`,perp:`⊥`,sdot:`⋅`,lceil:`⌈`,rceil:`⌉`,lfloor:`⌊`,rfloor:`⌋`,lang:`〈`,rang:`〉`,loz:`◊`,spades:`♠`,clubs:`♣`,hearts:`♥`,diams:`♦`,quot:`"`,amp:`&`,lt:`<`,gt:`>`,OElig:`Œ`,oelig:`œ`,Scaron:`Š`,scaron:`š`,Yuml:`Ÿ`,circ:`ˆ`,tilde:`˜`,ensp:` `,emsp:` `,thinsp:` `,zwnj:`‌`,zwj:`‍`,lrm:`‎`,rlm:`‏`,ndash:`–`,mdash:`—`,lsquo:`‘`,rsquo:`’`,sbquo:`‚`,ldquo:`“`,rdquo:`”`,bdquo:`„`,dagger:`†`,Dagger:`‡`,permil:`‰`,lsaquo:`‹`,rsaquo:`›`,euro:`€`},Uh=[`cent`,`copy`,`divide`,`gt`,`lt`,`not`,`para`,`times`],Wh={}.hasOwnProperty,Gh={},Kh;for(Kh in Hh)Wh.call(Hh,Kh)&&(Gh[Hh[Kh]]=Kh);var qh=/[^\dA-Za-z]/;function Jh(e,t,n,r){let i=String.fromCharCode(e);if(Wh.call(Gh,i)){let e=Gh[i],a=`&`+e;return n&&Vh.includes(e)&&!Uh.includes(e)&&(!r||t&&t!==61&&qh.test(String.fromCharCode(t)))?a:a+`;`}return``}function Yh(e,t,n){let r=Rh(e,t,n.omitOptionalSemicolons),i;if((n.useNamedReferences||n.useShortestReferences)&&(i=Jh(e,t,n.omitOptionalSemicolons,n.attribute)),(n.useShortestReferences||!i)&&n.useShortestReferences){let i=Bh(e,t,n.omitOptionalSemicolons);i.length<r.length&&(r=i)}return i&&(!n.useShortestReferences||i.length<r.length)?i:r}function Xh(e,t){return Ph(e,Object.assign({format:Yh},t))}var Zh=/^>|^->|<!--|-->|--!>|<!-$/g,Qh=[`>`],$h=[`<`,`>`];function eg(e,t,n,r){return r.settings.bogusComments?`<?`+Xh(e.value,Object.assign({},r.settings.characterReferences,{subset:Qh}))+`>`:`<!--`+e.value.replace(Zh,i)+`-->`;function i(e){return Xh(e,Object.assign({},r.settings.characterReferences,{subset:$h}))}}function tg(e,t,n,r){return`<!`+(r.settings.upperDoctype?`DOCTYPE`:`doctype`)+(r.settings.tightDoctype?``:` `)+`html>`}function ng(e,t){let n=String(e);if(typeof t!=`string`)throw TypeError(`Expected character`);let r=0,i=n.indexOf(t);for(;i!==-1;)r++,i=n.indexOf(t,i+t.length);return r}function rg(e,t){let n=t||{};return(e[e.length-1]===``?[...e,``]:e).join((n.padRight?` `:``)+`,`+(n.padLeft===!1?``:` `)).trim()}function ig(e){return e.join(` `).trim()}var ag=/[ \t\n\f\r]/g;function og(e){return typeof e==`object`?e.type===`text`&&sg(e.value):sg(e)}function sg(e){return e.replace(ag,``)===``}var cg=dg(1),lg=dg(-1),ug=[];function dg(e){return t;function t(t,n,r){let i=t?t.children:ug,a=(n||0)+e,o=i[a];if(!r)for(;o&&og(o);)a+=e,o=i[a];return o}}var fg={}.hasOwnProperty;function pg(e){return t;function t(t,n,r){return fg.call(e,t.tagName)&&e[t.tagName](t,n,r)}}var mg=pg({body:_g,caption:hg,colgroup:hg,dd:xg,dt:bg,head:hg,html:gg,li:yg,optgroup:Cg,option:wg,p:vg,rp:Sg,rt:Sg,tbody:Eg,td:kg,tfoot:Dg,th:kg,thead:Tg,tr:Og});function hg(e,t,n){let r=cg(n,t,!0);return!r||r.type!==`comment`&&!(r.type===`text`&&og(r.value.charAt(0)))}function gg(e,t,n){let r=cg(n,t);return!r||r.type!==`comment`}function _g(e,t,n){let r=cg(n,t);return!r||r.type!==`comment`}function vg(e,t,n){let r=cg(n,t);return r?r.type===`element`&&(r.tagName===`address`||r.tagName===`article`||r.tagName===`aside`||r.tagName===`blockquote`||r.tagName===`details`||r.tagName===`div`||r.tagName===`dl`||r.tagName===`fieldset`||r.tagName===`figcaption`||r.tagName===`figure`||r.tagName===`footer`||r.tagName===`form`||r.tagName===`h1`||r.tagName===`h2`||r.tagName===`h3`||r.tagName===`h4`||r.tagName===`h5`||r.tagName===`h6`||r.tagName===`header`||r.tagName===`hgroup`||r.tagName===`hr`||r.tagName===`main`||r.tagName===`menu`||r.tagName===`nav`||r.tagName===`ol`||r.tagName===`p`||r.tagName===`pre`||r.tagName===`section`||r.tagName===`table`||r.tagName===`ul`):!n||n.type!==`element`||n.tagName!==`a`&&n.tagName!==`audio`&&n.tagName!==`del`&&n.tagName!==`ins`&&n.tagName!==`map`&&n.tagName!==`noscript`&&n.tagName!==`video`}function yg(e,t,n){let r=cg(n,t);return!r||r.type===`element`&&r.tagName===`li`}function bg(e,t,n){let r=cg(n,t);return!(!r||r.type!==`element`||r.tagName!==`dt`&&r.tagName!==`dd`)}function xg(e,t,n){let r=cg(n,t);return!r||r.type===`element`&&(r.tagName===`dt`||r.tagName===`dd`)}function Sg(e,t,n){let r=cg(n,t);return!r||r.type===`element`&&(r.tagName===`rp`||r.tagName===`rt`)}function Cg(e,t,n){let r=cg(n,t);return!r||r.type===`element`&&r.tagName===`optgroup`}function wg(e,t,n){let r=cg(n,t);return!r||r.type===`element`&&(r.tagName===`option`||r.tagName===`optgroup`)}function Tg(e,t,n){let r=cg(n,t);return!(!r||r.type!==`element`||r.tagName!==`tbody`&&r.tagName!==`tfoot`)}function Eg(e,t,n){let r=cg(n,t);return!r||r.type===`element`&&(r.tagName===`tbody`||r.tagName===`tfoot`)}function Dg(e,t,n){return!cg(n,t)}function Og(e,t,n){let r=cg(n,t);return!r||r.type===`element`&&r.tagName===`tr`}function kg(e,t,n){let r=cg(n,t);return!r||r.type===`element`&&(r.tagName===`td`||r.tagName===`th`)}var Ag=pg({body:Ng,colgroup:Pg,head:Mg,html:jg,tbody:Fg});function jg(e){let t=cg(e,-1);return!t||t.type!==`comment`}function Mg(e){let t=new Set;for(let n of e.children)if(n.type===`element`&&(n.tagName===`base`||n.tagName===`title`)){if(t.has(n.tagName))return!1;t.add(n.tagName)}let n=e.children[0];return!n||n.type===`element`}function Ng(e){let t=cg(e,-1,!0);return!t||t.type!==`comment`&&!(t.type===`text`&&og(t.value.charAt(0)))&&(t.type!==`element`||t.tagName!==`meta`&&t.tagName!==`link`&&t.tagName!==`script`&&t.tagName!==`style`&&t.tagName!==`template`)}function Pg(e,t,n){let r=lg(n,t),i=cg(e,-1,!0);return n&&r&&r.type===`element`&&r.tagName===`colgroup`&&mg(r,n.children.indexOf(r),n)?!1:!!(i&&i.type===`element`&&i.tagName===`col`)}function Fg(e,t,n){let r=lg(n,t),i=cg(e,-1);return n&&r&&r.type===`element`&&(r.tagName===`thead`||r.tagName===`tbody`)&&mg(r,n.children.indexOf(r),n)?!1:!!(i&&i.type===`element`&&i.tagName===`tr`)}var Ig={name:[[`
26
+ `;let a=this.createOnigString(e),o=a.content.length,s=new im(n,e,this._tokenTypeMatchers,this.balancedBracketSelectors),c=Bp(this,a,i,0,t,s,!0,r);return ap(a),{lineLength:o,lineTokens:s,ruleStack:c.stack,stoppedEarly:c.stoppedEarly}}};function em(e,t){return e=Df(e),e.repository=e.repository||{},e.repository.$self={$vscodeTextmateLocation:e.$vscodeTextmateLocation,patterns:e.patterns,name:e.scopeName},e.repository.$base=t||e.repository.$self,e}var tm=class e{constructor(e,t,n){this.parent=e,this.scopePath=t,this.tokenAttributes=n}static fromExtension(t,n){let r=t,i=t?.scopePath??null;for(let t of n)i=Vf.push(i,t.scopeNames),r=new e(r,i,t.encodedTokenAttributes);return r}static createRoot(t,n){return new e(null,new Vf(null,t),n)}static createRootAndLookUpScopeName(t,n,r){let i=r.getMetadataForScope(t),a=new Vf(null,t),o=r.themeProvider.themeMatch(a),s=e.mergeAttributes(n,i,o);return new e(null,a,s)}get scopeName(){return this.scopePath.scopeName}toString(){return this.getScopeNames().join(` `)}equals(t){return e.equals(this,t)}static equals(e,t){do{if(e===t||!e&&!t)return!0;if(!e||!t||e.scopeName!==t.scopeName||e.tokenAttributes!==t.tokenAttributes)return!1;e=e.parent,t=t.parent}while(1)}static mergeAttributes(e,t,n){let r=-1,i=0,a=0;return n!==null&&(r=n.fontStyle,i=n.foregroundId,a=n.backgroundId),$f.set(e,t.languageId,t.tokenType,null,r,i,a)}pushAttributed(t,n){if(t===null)return this;if(t.indexOf(` `)===-1)return e._pushAttributed(this,t,n);let r=t.split(/ /g),i=this;for(let t of r)i=e._pushAttributed(i,t,n);return i}static _pushAttributed(t,n,r){let i=r.getMetadataForScope(n),a=t.scopePath.push(n),o=r.themeProvider.themeMatch(a),s=e.mergeAttributes(t.tokenAttributes,i,o);return new e(t,a,s)}getScopeNames(){return this.scopePath.getSegments()}getExtensionIfDefined(e){let t=[],n=this;for(;n&&n!==e;)t.push({encodedTokenAttributes:n.tokenAttributes,scopeNames:n.scopePath.getExtensionIfDefined(n.parent?.scopePath??null)}),n=n.parent;return n===e?t.reverse():void 0}},nm=class e{constructor(e,t,n,r,i,a,o,s){this.parent=e,this.ruleId=t,this.beginRuleCapturedEOL=i,this.endRule=a,this.nameScopesList=o,this.contentNameScopesList=s,this.depth=this.parent?this.parent.depth+1:1,this._enterPos=n,this._anchorPos=r}_stackElementBrand=void 0;static NULL=new e(null,0,0,0,!1,null,null,null);_enterPos;_anchorPos;depth;equals(t){return t!==null&&e._equals(this,t)}static _equals(e,t){return e===t?!0:this._structuralEquals(e,t)?tm.equals(e.contentNameScopesList,t.contentNameScopesList):!1}static _structuralEquals(e,t){do{if(e===t||!e&&!t)return!0;if(!e||!t||e.depth!==t.depth||e.ruleId!==t.ruleId||e.endRule!==t.endRule)return!1;e=e.parent,t=t.parent}while(1)}clone(){return this}static _reset(e){for(;e;)e._enterPos=-1,e._anchorPos=-1,e=e.parent}reset(){e._reset(this)}pop(){return this.parent}safePop(){return this.parent?this.parent:this}push(t,n,r,i,a,o,s){return new e(this,t,n,r,i,a,o,s)}getEnterPos(){return this._enterPos}getAnchorPos(){return this._anchorPos}getRule(e){return e.getRule(this.ruleId)}toString(){let e=[];return this._writeString(e,0),`[`+e.join(`,`)+`]`}_writeString(e,t){return this.parent&&(t=this.parent._writeString(e,t)),e[t++]=`(${this.ruleId}, ${this.nameScopesList?.toString()}, ${this.contentNameScopesList?.toString()})`,t}withContentNameScopesList(e){return this.contentNameScopesList===e?this:this.parent.push(this.ruleId,this._enterPos,this._anchorPos,this.beginRuleCapturedEOL,this.endRule,this.nameScopesList,e)}withEndRule(t){return this.endRule===t?this:new e(this.parent,this.ruleId,this._enterPos,this._anchorPos,this.beginRuleCapturedEOL,t,this.nameScopesList,this.contentNameScopesList)}hasSameRuleAs(e){let t=this;for(;t&&t._enterPos===e._enterPos;){if(t.ruleId===e.ruleId)return!0;t=t.parent}return!1}toStateStackFrame(){return{ruleId:Tp(this.ruleId),beginRuleCapturedEOL:this.beginRuleCapturedEOL,endRule:this.endRule,nameScopesList:this.nameScopesList?.getExtensionIfDefined(this.parent?.nameScopesList??null)??[],contentNameScopesList:this.contentNameScopesList?.getExtensionIfDefined(this.nameScopesList)??[]}}static pushFrame(t,n){let r=tm.fromExtension(t?.nameScopesList??null,n.nameScopesList);return new e(t,wp(n.ruleId),n.enterPos??-1,n.anchorPos??-1,n.beginRuleCapturedEOL,n.endRule,r,tm.fromExtension(r,n.contentNameScopesList))}},rm=class{balancedBracketScopes;unbalancedBracketScopes;allowAny=!1;constructor(e,t){this.balancedBracketScopes=e.flatMap(e=>e===`*`?(this.allowAny=!0,[]):np(e,Zp).map(e=>e.matcher)),this.unbalancedBracketScopes=t.flatMap(e=>np(e,Zp).map(e=>e.matcher))}get matchesAlways(){return this.allowAny&&this.unbalancedBracketScopes.length===0}get matchesNever(){return this.balancedBracketScopes.length===0&&!this.allowAny}match(e){for(let t of this.unbalancedBracketScopes)if(t(e))return!1;for(let t of this.balancedBracketScopes)if(t(e))return!0;return this.allowAny}},im=class{constructor(e,t,n,r){this.balancedBracketSelectors=r,this._emitBinaryTokens=e,this._tokenTypeOverrides=n,this._lineText=null,this._tokens=[],this._binaryTokens=[],this._lastTokenEndIndex=0}_emitBinaryTokens;_lineText;_tokens;_binaryTokens;_lastTokenEndIndex;_tokenTypeOverrides;produce(e,t){this.produceFromScopes(e.contentNameScopesList,t)}produceFromScopes(e,t){if(this._lastTokenEndIndex>=t)return;if(this._emitBinaryTokens){let n=e?.tokenAttributes??0,r=!1;if(this.balancedBracketSelectors?.matchesAlways&&(r=!0),this._tokenTypeOverrides.length>0||this.balancedBracketSelectors&&!this.balancedBracketSelectors.matchesAlways&&!this.balancedBracketSelectors.matchesNever){let t=e?.getScopeNames()??[];for(let e of this._tokenTypeOverrides)e.matcher(t)&&(n=$f.set(n,0,ep(e.type),null,-1,0,0));this.balancedBracketSelectors&&(r=this.balancedBracketSelectors.match(t))}if(r&&(n=$f.set(n,0,8,r,-1,0,0)),this._binaryTokens.length>0&&this._binaryTokens[this._binaryTokens.length-1]===n){this._lastTokenEndIndex=t;return}this._binaryTokens.push(this._lastTokenEndIndex),this._binaryTokens.push(n),this._lastTokenEndIndex=t;return}let n=e?.getScopeNames()??[];this._tokens.push({startIndex:this._lastTokenEndIndex,endIndex:t,scopes:n}),this._lastTokenEndIndex=t}getResult(e,t){return this._tokens.length>0&&this._tokens[this._tokens.length-1].startIndex===t-1&&this._tokens.pop(),this._tokens.length===0&&(this._lastTokenEndIndex=-1,this.produce(e,t),this._tokens[this._tokens.length-1].startIndex=0),this._tokens}getBinaryResult(e,t){this._binaryTokens.length>0&&this._binaryTokens[this._binaryTokens.length-2]===t-1&&(this._binaryTokens.pop(),this._binaryTokens.pop()),this._binaryTokens.length===0&&(this._lastTokenEndIndex=-1,this.produce(e,t),this._binaryTokens[this._binaryTokens.length-2]=0);let n=new Uint32Array(this._binaryTokens.length);for(let e=0,t=this._binaryTokens.length;e<t;e++)n[e]=this._binaryTokens[e];return n}},am=class{constructor(e,t){this._onigLib=t,this._theme=e}_grammars=new Map;_rawGrammars=new Map;_injectionGrammars=new Map;_theme;dispose(){for(let e of this._grammars.values())e.dispose()}setTheme(e){this._theme=e}getColorMap(){return this._theme.getColorMap()}addGrammar(e,t){this._rawGrammars.set(e.scopeName,e),t&&this._injectionGrammars.set(e.scopeName,t)}lookup(e){return this._rawGrammars.get(e)}injections(e){return this._injectionGrammars.get(e)}getDefaults(){return this._theme.getDefaults()}themeMatch(e){return this._theme.match(e)}grammarForScopeName(e,t,n,r,i){if(!this._grammars.has(e)){let a=this._rawGrammars.get(e);if(!a)return null;this._grammars.set(e,Yp(e,a,t,n,r,i,this,this._onigLib))}return this._grammars.get(e)}},om=class{_options;_syncRegistry;_ensureGrammarCache;constructor(e){this._options=e,this._syncRegistry=new am(Bf.createFromRawTheme(e.theme,e.colorMap),e.onigLib),this._ensureGrammarCache=new Map}dispose(){this._syncRegistry.dispose()}setTheme(e,t){this._syncRegistry.setTheme(Bf.createFromRawTheme(e,t))}getColorMap(){return this._syncRegistry.getColorMap()}loadGrammarWithEmbeddedLanguages(e,t,n){return this.loadGrammarWithConfiguration(e,t,{embeddedLanguages:n})}loadGrammarWithConfiguration(e,t,n){return this._loadGrammar(e,t,n.embeddedLanguages,n.tokenTypes,new rm(n.balancedBracketSelectors||[],n.unbalancedBracketSelectors||[]))}loadGrammar(e){return this._loadGrammar(e,0,null,null,null)}_loadGrammar(e,t,n,r,i){let a=new lp(this._syncRegistry,e);for(;a.Q.length>0;)a.Q.map(e=>this._loadSingleGrammar(e.scopeName)),a.processQueue();return this._grammarForScopeName(e,t,n,r,i)}_loadSingleGrammar(e){this._ensureGrammarCache.has(e)||(this._doLoadSingleGrammar(e),this._ensureGrammarCache.set(e,!0))}_doLoadSingleGrammar(e){let t=this._options.loadGrammar(e);if(t){let n=typeof this._options.getInjections==`function`?this._options.getInjections(e):void 0;this._syncRegistry.addGrammar(t,n)}}addGrammar(e,t=[],n=0,r=null){return this._syncRegistry.addGrammar(e,t),this._grammarForScopeName(e.scopeName,n,r)}_grammarForScopeName(e,t=0,n=null,r=null,i=null){return this._syncRegistry.grammarForScopeName(e,t,n,r,i)}},sm=nm.NULL;function cm(e,t){let n=typeof e==`string`?{}:{...e.colorReplacements},r=typeof e==`string`?e:e.name;for(let[e,i]of Object.entries(t?.colorReplacements||{}))typeof i==`string`?n[e]=i:e===r&&Object.assign(n,i);return n}function lm(e,t){return e&&(t?.[e?.toLowerCase()]||e)}function um(e){return Array.isArray(e)?e:[e]}async function dm(e){return Promise.resolve(typeof e==`function`?e():e).then(e=>e.default||e)}function fm(e){return!e||[`plaintext`,`txt`,`text`,`plain`].includes(e)}function pm(e){return e===`ansi`||fm(e)}function mm(e){return e===`none`}function hm(e){return mm(e)}var gm=/(\r?\n)/g;function _m(e,t=!1){if(e.length===0)return[[``,0]];let n=e.split(gm),r=0,i=[];for(let e=0;e<n.length;e+=2){let a=t?n[e]+(n[e+1]||``):n[e];i.push([a,r]),r+=n[e].length,r+=n[e+1]?.length||0}return i}var vm={light:`#333333`,dark:`#bbbbbb`},ym={light:`#fffffe`,dark:`#1e1e1e`},bm=`__shiki_resolved`;function xm(e){if(e?.[bm])return e;let t={...e};t.tokenColors&&!t.settings&&(t.settings=t.tokenColors,delete t.tokenColors),t.type||=`dark`,t.colorReplacements={...t.colorReplacements},t.settings||=[];let{bg:n,fg:r}=t;if(!n||!r){let e=t.settings?t.settings.find(e=>!e.name&&!e.scope):void 0;e?.settings?.foreground&&(r=e.settings.foreground),e?.settings?.background&&(n=e.settings.background),!r&&t?.colors?.[`editor.foreground`]&&(r=t.colors[`editor.foreground`]),!n&&t?.colors?.[`editor.background`]&&(n=t.colors[`editor.background`]),r||=t.type===`light`?vm.light:vm.dark,n||=t.type===`light`?ym.light:ym.dark,t.fg=r,t.bg=n}t.settings[0]&&t.settings[0].settings&&!t.settings[0].scope||t.settings.unshift({settings:{foreground:t.fg,background:t.bg}});let i=0,a=new Map;function o(e){if(a.has(e))return a.get(e);i+=1;let n=`#${i.toString(16).padStart(8,`0`).toLowerCase()}`;return t.colorReplacements?.[`#${n}`]?o(e):(a.set(e,n),n)}t.settings=t.settings.map(e=>{let n=e.settings?.foreground&&!e.settings.foreground.startsWith(`#`),r=e.settings?.background&&!e.settings.background.startsWith(`#`);if(!n&&!r)return e;let i={...e,settings:{...e.settings}};if(n){let n=o(e.settings.foreground);t.colorReplacements[n]=e.settings.foreground,i.settings.foreground=n}if(r){let n=o(e.settings.background);t.colorReplacements[n]=e.settings.background,i.settings.background=n}return i});for(let e of Object.keys(t.colors||{}))if((e===`editor.foreground`||e===`editor.background`||e.startsWith(`terminal.ansi`))&&!t.colors[e]?.startsWith(`#`)){let n=o(t.colors[e]);t.colorReplacements[n]=t.colors[e],t.colors[e]=n}return Object.defineProperty(t,bm,{enumerable:!1,writable:!1,value:!0}),t}async function Sm(e){return[...new Set((await Promise.all(e.filter(e=>!pm(e)).map(async e=>await dm(e).then(e=>Array.isArray(e)?e:[e])))).flat())]}async function Cm(e){return(await Promise.all(e.map(async e=>hm(e)?null:xm(await dm(e))))).filter(e=>!!e)}function wm(e,t){if(!t)return e;if(t[e]){let n=new Set([e]);for(;t[e];){if(e=t[e],n.has(e))throw new Ef(`Circular alias \`${[...n].join(` -> `)} -> ${e}\``);n.add(e)}}return e}var Tm=class extends om{_resolver;_themes;_langs;_alias;_resolvedThemes=new Map;_resolvedGrammars=new Map;_langMap=new Map;_langGraph=new Map;_textmateThemeCache=new WeakMap;_loadedThemesCache=null;_loadedLanguagesCache=null;constructor(e,t,n,r={}){super(e),this._resolver=e,this._themes=t,this._langs=n,this._alias=r,this._themes.map(e=>this.loadTheme(e)),this.loadLanguages(this._langs)}getTheme(e){return typeof e==`string`?this._resolvedThemes.get(e):this.loadTheme(e)}loadTheme(e){let t=xm(e);return t.name&&(this._resolvedThemes.set(t.name,t),this._loadedThemesCache=null),t}getLoadedThemes(){return this._loadedThemesCache||=[...this._resolvedThemes.keys()],this._loadedThemesCache}setTheme(e){let t=this._textmateThemeCache.get(e);t||(t=Bf.createFromRawTheme(e),this._textmateThemeCache.set(e,t)),this._syncRegistry.setTheme(t)}getGrammar(e){return e=wm(e,this._alias),this._resolvedGrammars.get(e)}loadLanguage(e){if(this.getGrammar(e.name))return;let t=new Set([...this._langMap.values()].filter(t=>t.embeddedLangsLazy?.includes(e.name)));this._resolver.addLanguage(e);let n={balancedBracketSelectors:e.balancedBracketSelectors||[`*`],unbalancedBracketSelectors:e.unbalancedBracketSelectors||[]};this._syncRegistry._rawGrammars.set(e.scopeName,e);let r=this.loadGrammarWithConfiguration(e.scopeName,1,n);if(r.name=e.name,this._resolvedGrammars.set(e.name,r),e.aliases&&e.aliases.forEach(t=>{this._alias[t]=e.name}),this._loadedLanguagesCache=null,t.size)for(let e of t)this._syncRegistry?._grammars?.get(e.scopeName)?.dispose(),this._resolvedGrammars.delete(e.name),this._loadedLanguagesCache=null,this._syncRegistry?._injectionGrammars?.delete(e.scopeName),this._syncRegistry?._grammars?.delete(e.scopeName),this.loadLanguage(this._langMap.get(e.name))}dispose(){super.dispose(),this._resolvedThemes.clear(),this._resolvedGrammars.clear(),this._langMap.clear(),this._langGraph.clear(),this._loadedThemesCache=null}loadLanguages(e){for(let t of e)this.resolveEmbeddedLanguages(t);let t=[...this._langGraph.entries()],n=t.filter(([e,t])=>!t);if(n.length){let e=t.filter(([e,t])=>t?(t.embeddedLanguages||t.embeddedLangs)?.some(e=>n.map(([e])=>e).includes(e)):!1).filter(e=>!n.includes(e));throw new Ef(`Missing languages ${n.map(([e])=>`\`${e}\``).join(`, `)}, required by ${e.map(([e])=>`\`${e}\``).join(`, `)}`)}for(let[e,n]of t)this._resolver.addLanguage(n);for(let[e,n]of t)this.loadLanguage(n)}getLoadedLanguages(){return this._loadedLanguagesCache||=[...new Set([...this._resolvedGrammars.keys(),...Object.keys(this._alias)])],this._loadedLanguagesCache}resolveEmbeddedLanguages(e){this._langMap.set(e.name,e),this._langGraph.set(e.name,e);let t=e.embeddedLanguages??e.embeddedLangs;if(t)for(let e of t)this._langGraph.set(e,this._langMap.get(e))}},Em=class{_langs=new Map;_scopeToLang=new Map;_injections=new Map;_onigLib;constructor(e,t){this._onigLib={createOnigScanner:t=>e.createScanner(t),createOnigString:t=>e.createString(t)},t.forEach(e=>this.addLanguage(e))}get onigLib(){return this._onigLib}getLangRegistration(e){return this._langs.get(e)}loadGrammar(e){return this._scopeToLang.get(e)}addLanguage(e){this._langs.set(e.name,e),e.aliases&&e.aliases.forEach(t=>{this._langs.set(t,e)}),this._scopeToLang.set(e.scopeName,e),e.injectTo&&e.injectTo.forEach(t=>{this._injections.get(t)||this._injections.set(t,[]),this._injections.get(t).includes(e.scopeName)||this._injections.get(t).push(e.scopeName)})}getInjections(e){let t=e.split(`.`),n=[];for(let e=1;e<=t.length;e++){let r=t.slice(0,e).join(`.`);n=[...n,...this._injections.get(r)||[]]}return n}},Dm=0;function Om(e){Dm+=1,e.warnings!==!1&&Dm>=10&&Dm%10==0&&console.warn(`[Shiki] ${Dm} instances have been created. Shiki is supposed to be used as a singleton, consider refactoring your code to cache your highlighter instance; Or call \`highlighter.dispose()\` to release unused instances.`);let t=!1;if(!e.engine)throw new Ef("`engine` option is required for synchronous mode");let n=(e.langs||[]).flat(1),r=(e.themes||[]).flat(1).map(xm),i=new Tm(new Em(e.engine,n),r,n,e.langAlias),a;function o(t){return wm(t,e.langAlias)}function s(e){g();let t=i.getGrammar(typeof e==`string`?e:e.name);if(!t)throw new Ef(`Language \`${e}\` not found, you may need to load it first`);return t}function c(e){if(e===`none`)return{bg:``,fg:``,name:`none`,settings:[],type:`dark`};g();let t=i.getTheme(e);if(!t)throw new Ef(`Theme \`${e}\` not found, you may need to load it first`);return t}function l(e){g();let t=c(e);return a!==e&&(i.setTheme(t),a=e),{theme:t,colorMap:i.getColorMap()}}function u(){return g(),i.getLoadedThemes()}function d(){return g(),i.getLoadedLanguages()}function f(...e){g(),i.loadLanguages(e.flat(1))}async function p(...e){return f(await Sm(e))}function m(...e){g();for(let t of e.flat(1))i.loadTheme(t)}async function h(...e){return g(),m(await Cm(e))}function g(){if(t)throw new Ef(`Shiki instance has been disposed`)}function _(){t||(t=!0,i.dispose(),--Dm)}return{setTheme:l,getTheme:c,getLanguage:s,getLoadedThemes:u,getLoadedLanguages:d,resolveLangAlias:o,loadLanguage:p,loadLanguageSync:f,loadTheme:h,loadThemeSync:m,dispose:_,[Symbol.dispose]:_}}async function km(e){e.engine||console.warn("`engine` option is required. Use `createOnigurumaEngine` or `createJavaScriptRegexEngine` to create an engine.");let[t,n,r]=await Promise.all([Cm(e.themes||[]),Sm(e.langs||[]),e.engine]);return Om({...e,themes:t,langs:n,engine:r})}var Am=new WeakMap;function jm(e,t){Am.set(e,t)}function Mm(e){return Am.get(e)}var Nm=class e{_stacks={};lang;get themes(){return Object.keys(this._stacks)}get theme(){return this.themes[0]}get _stack(){return this._stacks[this.theme]}static initial(t,n){return new e(Object.fromEntries(um(n).map(e=>[e,sm])),t)}constructor(...e){if(e.length===2){let[t,n]=e;this.lang=n,this._stacks=t}else{let[t,n,r]=e;this.lang=n,this._stacks={[r]:t}}}getInternalStack(e=this.theme){return this._stacks[e]}getScopes(e=this.theme){return Pm(this._stacks[e])}toJSON(){return{lang:this.lang,theme:this.theme,themes:this.themes,scopes:this.getScopes()}}};function Pm(e){let t=[],n=new Set;function r(e){if(n.has(e))return;n.add(e);let i=e?.nameScopesList?.scopeName;i&&t.push(i),e.parent&&r(e.parent)}return r(e),t}function Fm(e,t){if(!(e instanceof Nm))throw new Ef(`Invalid grammar state`);return e.getInternalStack(t)}var Im=/,/,Lm=/ /;function Rm(e,t,n={}){let{theme:r=e.getLoadedThemes()[0]}=n;if(fm(e.resolveLangAlias(n.lang||`text`))||mm(r))return _m(t).map(e=>[{content:e[0],offset:e[1]}]);let{theme:i,colorMap:a}=e.setTheme(r),o=e.getLanguage(n.lang||`text`);if(n.grammarState){if(n.grammarState.lang!==o.name)throw new Ef(`Grammar state language "${n.grammarState.lang}" does not match highlight language "${o.name}"`);if(!n.grammarState.themes.includes(i.name))throw new Ef(`Grammar state themes "${n.grammarState.themes}" do not contain highlight theme "${i.name}"`)}return Bm(t,o,i,a,n)}function zm(...e){if(e.length===2)return Mm(e[1]);let[t,n,r={}]=e,{lang:i=`text`,theme:a=t.getLoadedThemes()[0]}=r;if(fm(i)||mm(a))throw new Ef(`Plain language does not have grammar state`);if(i===`ansi`)throw new Ef(`ANSI language does not have grammar state`);let{theme:o,colorMap:s}=t.setTheme(a),c=t.getLanguage(i);return new Nm(Vm(n,c,o,s,r).stateStack,c.name,o.name)}function Bm(e,t,n,r,i){let a=Vm(e,t,n,r,i),o=new Nm(a.stateStack,t.name,n.name);return jm(a.tokens,o),a.tokens}function Vm(e,t,n,r,i){let a=cm(n,i),{tokenizeMaxLineLength:o=0,tokenizeTimeLimit:s=500,includeExplanation:c=!1}=i,l=_m(e),u=i.grammarState?Fm(i.grammarState,n.name)??sm:i.grammarContextCode==null?sm:Vm(i.grammarContextCode,t,n,r,{...i,grammarState:void 0,grammarContextCode:void 0}).stateStack,d=[],f=[];for(let e=0,i=l.length;e<i;e++){let[i,p]=l[e];if(i===``){d=[],f.push([]);continue}if(o>0&&i.length>=o){d=[],f.push([{content:i,offset:p,color:``,fontStyle:0}]);continue}let m,h,g;c&&c!==`tokenType`&&(m=t.tokenizeLine(i,u,s),h=m.tokens,g=0);let _=t.tokenizeLine2(i,u,s),v=_.tokens.length/2;for(let e=0;e<v;e++){let t=_.tokens[2*e],o=e+1<v?_.tokens[2*e+2]:i.length;if(t===o)continue;let s=_.tokens[2*e+1],l=lm(r[$f.getForeground(s)],a),u=$f.getFontStyle(s),f={content:i.substring(t,o),offset:p+t,color:l,fontStyle:u};if(c===`tokenType`)f.type=$f.getTokenType(s);else if(c){let e=[];if(c!==`scopeName`)for(let t of n.settings){let n;switch(typeof t.scope){case`string`:n=t.scope.split(Im).map(e=>e.trim());break;case`object`:n=t.scope;break;default:continue}e.push({settings:t,selectors:n.map(e=>e.split(Lm))})}f.explanation=[];let r=0;for(;t+r<o;){let t=h[g],n=i.substring(t.startIndex,t.endIndex);r+=n.length,f.explanation.push({content:n,scopes:c===`scopeName`?Hm(t.scopes):Um(e,t.scopes)}),g+=1}}d.push(f)}f.push(d),d=[],u=_.ruleStack}return{tokens:f,stateStack:u}}function Hm(e){return e.map(e=>({scopeName:e}))}function Um(e,t){let n=[];for(let r=0,i=t.length;r<i;r++){let i=t[r];n[r]={scopeName:i,themeMatches:Km(e,i,t.slice(0,r))}}return n}function Wm(e,t){return e===t||t.substring(0,e.length)===e&&t[e.length]===`.`}function Gm(e,t,n){if(!Wm(e.at(-1),t))return!1;let r=e.length-2,i=n.length-1;for(;r>=0&&i>=0;)Wm(e[r],n[i])&&--r,--i;return r===-1}function Km(e,t,n){let r=[];for(let{selectors:i,settings:a}of e)for(let e of i)if(Gm(e,t,n)){r.push(a);break}return r}function qm(e,t,n,r=Rm){let i=Object.entries(n.themes).filter(e=>e[1]).map(e=>({color:e[0],theme:e[1]})),a=i.map(i=>{let a=r(e,t,{...n,theme:i.theme});return{tokens:a,state:Mm(a),theme:typeof i.theme==`string`?i.theme:i.theme.name}}),o=Jm(...a.map(e=>e.tokens)),s=o[0].map((e,t)=>e.map((e,r)=>{let a={content:e.content,variants:{},offset:e.offset};return`includeExplanation`in n&&n.includeExplanation&&(a.explanation=e.explanation),o.forEach((e,n)=>{let{content:o,explanation:s,offset:c,...l}=e[t][r];a.variants[i[n].color]=l}),a})),c=a[0].state?new Nm(Object.fromEntries(a.map(e=>[e.theme,e.state?.getInternalStack(e.theme)])),a[0].state.lang):void 0;return c&&jm(s,c),s}function Jm(...e){let t=e.map(()=>[]),n=e.length;for(let r=0;r<e[0].length;r++){let i=e.map(e=>e[r]),a=t.map(()=>[]);t.forEach((e,t)=>e.push(a[t]));let o=i.map(()=>0),s=i.map(e=>e[0]);for(;s.every(e=>e);){let e=Math.min(...s.map(e=>e.content.length));for(let t=0;t<n;t++){let n=s[t];n.content.length===e?(a[t].push(n),o[t]+=1,s[t]=i[t][o[t]]):(a[t].push({...n,content:n.content.slice(0,e)}),s[t]={...n,content:n.content.slice(e),offset:n.offset+e})}}}return t}var Ym=[`area`,`base`,`basefont`,`bgsound`,`br`,`col`,`command`,`embed`,`frame`,`hr`,`image`,`img`,`input`,`keygen`,`link`,`meta`,`param`,`source`,`track`,`wbr`],Xm=class{constructor(e,t,n){this.normal=t,this.property=e,n&&(this.space=n)}};Xm.prototype.normal={},Xm.prototype.property={},Xm.prototype.space=void 0;function Zm(e,t){let n={},r={};for(let t of e)Object.assign(n,t.property),Object.assign(r,t.normal);return new Xm(n,r,t)}function Qm(e){return e.toLowerCase()}var $m=class{constructor(e,t){this.attribute=t,this.property=e}};$m.prototype.attribute=``,$m.prototype.booleanish=!1,$m.prototype.boolean=!1,$m.prototype.commaOrSpaceSeparated=!1,$m.prototype.commaSeparated=!1,$m.prototype.defined=!1,$m.prototype.mustUseProperty=!1,$m.prototype.number=!1,$m.prototype.overloadedBoolean=!1,$m.prototype.property=``,$m.prototype.spaceSeparated=!1,$m.prototype.space=void 0;var eh=t({boolean:()=>Z,booleanish:()=>nh,commaOrSpaceSeparated:()=>oh,commaSeparated:()=>ah,number:()=>Q,overloadedBoolean:()=>rh,spaceSeparated:()=>ih}),th=0,Z=sh(),nh=sh(),rh=sh(),Q=sh(),ih=sh(),ah=sh(),oh=sh();function sh(){return 2**++th}var ch=Object.keys(eh),lh=class extends $m{constructor(e,t,n,r){let i=-1;if(super(e,t),uh(this,`space`,r),typeof n==`number`)for(;++i<ch.length;){let e=ch[i];uh(this,ch[i],(n&eh[e])===eh[e])}}};lh.prototype.defined=!0;function uh(e,t,n){n&&(e[t]=n)}function dh(e){let t={},n={};for(let[r,i]of Object.entries(e.properties)){let a=new lh(r,e.transform(e.attributes||{},r),i,e.space);e.mustUseProperty&&e.mustUseProperty.includes(r)&&(a.mustUseProperty=!0),t[r]=a,n[Qm(r)]=r,n[Qm(a.attribute)]=r}return new Xm(t,n,e.space)}var fh=dh({properties:{ariaActiveDescendant:null,ariaAtomic:nh,ariaAutoComplete:null,ariaBusy:nh,ariaChecked:nh,ariaColCount:Q,ariaColIndex:Q,ariaColSpan:Q,ariaControls:ih,ariaCurrent:null,ariaDescribedBy:ih,ariaDetails:null,ariaDisabled:nh,ariaDropEffect:ih,ariaErrorMessage:null,ariaExpanded:nh,ariaFlowTo:ih,ariaGrabbed:nh,ariaHasPopup:null,ariaHidden:nh,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:ih,ariaLevel:Q,ariaLive:null,ariaModal:nh,ariaMultiLine:nh,ariaMultiSelectable:nh,ariaOrientation:null,ariaOwns:ih,ariaPlaceholder:null,ariaPosInSet:Q,ariaPressed:nh,ariaReadOnly:nh,ariaRelevant:null,ariaRequired:nh,ariaRoleDescription:ih,ariaRowCount:Q,ariaRowIndex:Q,ariaRowSpan:Q,ariaSelected:nh,ariaSetSize:Q,ariaSort:null,ariaValueMax:Q,ariaValueMin:Q,ariaValueNow:Q,ariaValueText:null,role:null},transform(e,t){return t===`role`?t:`aria-`+t.slice(4).toLowerCase()}});function ph(e,t){return t in e?e[t]:t}function mh(e,t){return ph(e,t.toLowerCase())}var hh=dh({attributes:{acceptcharset:`accept-charset`,classname:`class`,htmlfor:`for`,httpequiv:`http-equiv`},mustUseProperty:[`checked`,`multiple`,`muted`,`selected`],properties:{abbr:null,accept:ah,acceptCharset:ih,accessKey:ih,action:null,allow:null,allowFullScreen:Z,allowPaymentRequest:Z,allowUserMedia:Z,alpha:Z,alt:null,as:null,async:Z,autoCapitalize:null,autoComplete:ih,autoFocus:Z,autoPlay:Z,blocking:ih,capture:null,charSet:null,checked:Z,cite:null,className:ih,closedBy:null,colorSpace:null,cols:Q,colSpan:Q,command:null,commandFor:null,content:null,contentEditable:nh,controls:Z,controlsList:ih,coords:Q|ah,crossOrigin:null,data:null,dateTime:null,decoding:null,default:Z,defer:Z,dir:null,dirName:null,disabled:Z,download:rh,draggable:nh,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:Z,formTarget:null,headers:ih,height:Q,hidden:rh,high:Q,href:null,hrefLang:null,htmlFor:ih,httpEquiv:ih,id:null,imageSizes:null,imageSrcSet:null,inert:Z,inputMode:null,integrity:null,is:null,isMap:Z,itemId:null,itemProp:ih,itemRef:ih,itemScope:Z,itemType:ih,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:Z,low:Q,manifest:null,max:null,maxLength:Q,media:null,method:null,min:null,minLength:Q,multiple:Z,muted:Z,name:null,nonce:null,noModule:Z,noValidate:Z,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:Z,optimum:Q,pattern:null,ping:ih,placeholder:null,playsInline:Z,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:Z,referrerPolicy:null,rel:ih,required:Z,reversed:Z,rows:Q,rowSpan:Q,sandbox:ih,scope:null,scoped:Z,seamless:Z,selected:Z,shadowRootClonable:Z,shadowRootCustomElementRegistry:Z,shadowRootDelegatesFocus:Z,shadowRootMode:null,shadowRootSerializable:Z,shape:null,size:Q,sizes:null,slot:null,span:Q,spellCheck:nh,src:null,srcDoc:null,srcLang:null,srcSet:null,start:Q,step:null,style:null,tabIndex:Q,target:null,title:null,translate:null,type:null,typeMustMatch:Z,useMap:null,value:nh,width:Q,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:ih,axis:null,background:null,bgColor:null,border:Q,borderColor:null,bottomMargin:Q,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:Z,declare:Z,event:null,face:null,frame:null,frameBorder:null,hSpace:Q,leftMargin:Q,link:null,longDesc:null,lowSrc:null,marginHeight:Q,marginWidth:Q,noResize:Z,noHref:Z,noShade:Z,noWrap:Z,object:null,profile:null,prompt:null,rev:null,rightMargin:Q,rules:null,scheme:null,scrolling:nh,standby:null,summary:null,text:null,topMargin:Q,valueType:null,version:null,vAlign:null,vLink:null,vSpace:Q,allowTransparency:null,autoCorrect:null,autoSave:null,credentialless:Z,disablePictureInPicture:Z,disableRemotePlayback:Z,exportParts:ah,part:ih,prefix:null,property:null,results:Q,security:null,unselectable:null},space:`html`,transform:mh}),gh=dh({attributes:{accentHeight:`accent-height`,alignmentBaseline:`alignment-baseline`,arabicForm:`arabic-form`,baselineShift:`baseline-shift`,capHeight:`cap-height`,className:`class`,clipPath:`clip-path`,clipRule:`clip-rule`,colorInterpolation:`color-interpolation`,colorInterpolationFilters:`color-interpolation-filters`,colorProfile:`color-profile`,colorRendering:`color-rendering`,crossOrigin:`crossorigin`,dataType:`datatype`,dominantBaseline:`dominant-baseline`,enableBackground:`enable-background`,fillOpacity:`fill-opacity`,fillRule:`fill-rule`,floodColor:`flood-color`,floodOpacity:`flood-opacity`,fontFamily:`font-family`,fontSize:`font-size`,fontSizeAdjust:`font-size-adjust`,fontStretch:`font-stretch`,fontStyle:`font-style`,fontVariant:`font-variant`,fontWeight:`font-weight`,glyphName:`glyph-name`,glyphOrientationHorizontal:`glyph-orientation-horizontal`,glyphOrientationVertical:`glyph-orientation-vertical`,hrefLang:`hreflang`,horizAdvX:`horiz-adv-x`,horizOriginX:`horiz-origin-x`,horizOriginY:`horiz-origin-y`,imageRendering:`image-rendering`,letterSpacing:`letter-spacing`,lightingColor:`lighting-color`,markerEnd:`marker-end`,markerMid:`marker-mid`,markerStart:`marker-start`,maskType:`mask-type`,navDown:`nav-down`,navDownLeft:`nav-down-left`,navDownRight:`nav-down-right`,navLeft:`nav-left`,navNext:`nav-next`,navPrev:`nav-prev`,navRight:`nav-right`,navUp:`nav-up`,navUpLeft:`nav-up-left`,navUpRight:`nav-up-right`,onAbort:`onabort`,onActivate:`onactivate`,onAfterPrint:`onafterprint`,onBeforePrint:`onbeforeprint`,onBegin:`onbegin`,onCancel:`oncancel`,onCanPlay:`oncanplay`,onCanPlayThrough:`oncanplaythrough`,onChange:`onchange`,onClick:`onclick`,onClose:`onclose`,onCopy:`oncopy`,onCueChange:`oncuechange`,onCut:`oncut`,onDblClick:`ondblclick`,onDrag:`ondrag`,onDragEnd:`ondragend`,onDragEnter:`ondragenter`,onDragExit:`ondragexit`,onDragLeave:`ondragleave`,onDragOver:`ondragover`,onDragStart:`ondragstart`,onDrop:`ondrop`,onDurationChange:`ondurationchange`,onEmptied:`onemptied`,onEnd:`onend`,onEnded:`onended`,onError:`onerror`,onFocus:`onfocus`,onFocusIn:`onfocusin`,onFocusOut:`onfocusout`,onHashChange:`onhashchange`,onInput:`oninput`,onInvalid:`oninvalid`,onKeyDown:`onkeydown`,onKeyPress:`onkeypress`,onKeyUp:`onkeyup`,onLoad:`onload`,onLoadedData:`onloadeddata`,onLoadedMetadata:`onloadedmetadata`,onLoadStart:`onloadstart`,onMessage:`onmessage`,onMouseDown:`onmousedown`,onMouseEnter:`onmouseenter`,onMouseLeave:`onmouseleave`,onMouseMove:`onmousemove`,onMouseOut:`onmouseout`,onMouseOver:`onmouseover`,onMouseUp:`onmouseup`,onMouseWheel:`onmousewheel`,onOffline:`onoffline`,onOnline:`ononline`,onPageHide:`onpagehide`,onPageShow:`onpageshow`,onPaste:`onpaste`,onPause:`onpause`,onPlay:`onplay`,onPlaying:`onplaying`,onPopState:`onpopstate`,onProgress:`onprogress`,onRateChange:`onratechange`,onRepeat:`onrepeat`,onReset:`onreset`,onResize:`onresize`,onScroll:`onscroll`,onSeeked:`onseeked`,onSeeking:`onseeking`,onSelect:`onselect`,onShow:`onshow`,onStalled:`onstalled`,onStorage:`onstorage`,onSubmit:`onsubmit`,onSuspend:`onsuspend`,onTimeUpdate:`ontimeupdate`,onToggle:`ontoggle`,onUnload:`onunload`,onVolumeChange:`onvolumechange`,onWaiting:`onwaiting`,onZoom:`onzoom`,overlinePosition:`overline-position`,overlineThickness:`overline-thickness`,paintOrder:`paint-order`,panose1:`panose-1`,pointerEvents:`pointer-events`,referrerPolicy:`referrerpolicy`,renderingIntent:`rendering-intent`,shapeRendering:`shape-rendering`,stopColor:`stop-color`,stopOpacity:`stop-opacity`,strikethroughPosition:`strikethrough-position`,strikethroughThickness:`strikethrough-thickness`,strokeDashArray:`stroke-dasharray`,strokeDashOffset:`stroke-dashoffset`,strokeLineCap:`stroke-linecap`,strokeLineJoin:`stroke-linejoin`,strokeMiterLimit:`stroke-miterlimit`,strokeOpacity:`stroke-opacity`,strokeWidth:`stroke-width`,tabIndex:`tabindex`,textAnchor:`text-anchor`,textDecoration:`text-decoration`,textRendering:`text-rendering`,transformOrigin:`transform-origin`,typeOf:`typeof`,underlinePosition:`underline-position`,underlineThickness:`underline-thickness`,unicodeBidi:`unicode-bidi`,unicodeRange:`unicode-range`,unitsPerEm:`units-per-em`,vAlphabetic:`v-alphabetic`,vHanging:`v-hanging`,vIdeographic:`v-ideographic`,vMathematical:`v-mathematical`,vectorEffect:`vector-effect`,vertAdvY:`vert-adv-y`,vertOriginX:`vert-origin-x`,vertOriginY:`vert-origin-y`,wordSpacing:`word-spacing`,writingMode:`writing-mode`,xHeight:`x-height`,playbackOrder:`playbackorder`,timelineBegin:`timelinebegin`},properties:{about:oh,accentHeight:Q,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:Q,amplitude:Q,arabicForm:null,ascent:Q,attributeName:null,attributeType:null,azimuth:Q,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:Q,by:null,calcMode:null,capHeight:Q,className:ih,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:Q,diffuseConstant:Q,direction:null,display:null,dur:null,divisor:Q,dominantBaseline:null,download:Z,dx:null,dy:null,edgeMode:null,editable:null,elevation:Q,enableBackground:null,end:null,event:null,exponent:Q,externalResourcesRequired:null,fill:null,fillOpacity:Q,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:ah,g2:ah,glyphName:ah,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:Q,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:Q,horizOriginX:Q,horizOriginY:Q,id:null,ideographic:Q,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:Q,k:Q,k1:Q,k2:Q,k3:Q,k4:Q,kernelMatrix:oh,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:Q,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskType:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:Q,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:Q,overlineThickness:Q,paintOrder:null,panose1:null,path:null,pathLength:Q,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:ih,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:Q,pointsAtY:Q,pointsAtZ:Q,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:oh,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:oh,rev:oh,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:oh,requiredFeatures:oh,requiredFonts:oh,requiredFormats:oh,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:Q,specularExponent:Q,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:Q,strikethroughThickness:Q,string:null,stroke:null,strokeDashArray:oh,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:Q,strokeOpacity:Q,strokeWidth:null,style:null,surfaceScale:Q,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:oh,tabIndex:Q,tableValues:null,target:null,targetX:Q,targetY:Q,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:oh,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:Q,underlineThickness:Q,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:Q,values:null,vAlphabetic:Q,vMathematical:Q,vectorEffect:null,vHanging:Q,vIdeographic:Q,version:null,vertAdvY:Q,vertOriginX:Q,vertOriginY:Q,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:Q,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:`svg`,transform:ph}),_h=dh({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:`xlink`,transform(e,t){return`xlink:`+t.slice(5).toLowerCase()}}),vh=dh({attributes:{xmlnsxlink:`xmlns:xlink`},properties:{xmlnsXLink:null,xmlns:null},space:`xmlns`,transform:mh}),yh=dh({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:`xml`,transform(e,t){return`xml:`+t.slice(3).toLowerCase()}}),bh=/[A-Z]/g,xh=/-[a-z]/g,Sh=/^data[-\w.:]+$/i;function Ch(e,t){let n=Qm(t),r=t,i=$m;if(n in e.normal)return e.property[e.normal[n]];if(n.length>4&&n.slice(0,4)===`data`&&Sh.test(t)){if(t.charAt(4)===`-`){let e=t.slice(5).replace(xh,Th);r=`data`+e.charAt(0).toUpperCase()+e.slice(1)}else{let e=t.slice(4);if(!xh.test(e)){let n=e.replace(bh,wh);n.charAt(0)!==`-`&&(n=`-`+n),t=`data`+n}}i=lh}return new i(r,t)}function wh(e){return`-`+e.toLowerCase()}function Th(e){return e.charAt(1).toUpperCase()}var Eh=Zm([fh,hh,_h,vh,yh],`html`),Dh=Zm([fh,gh,_h,vh,yh],`svg`),Oh={}.hasOwnProperty;function kh(e,t){let n=t||{};function r(t,...n){let i=r.invalid,a=r.handlers;if(t&&Oh.call(t,e)){let n=String(t[e]);i=Oh.call(a,n)?a[n]:r.unknown}if(i)return i.call(this,t,...n)}return r.handlers=n.handlers||{},r.invalid=n.invalid,r.unknown=n.unknown,r}var Ah=/["&'<>`]/g,jh=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,Mh=/[\x01-\t\v\f\x0E-\x1F\x7F\x81\x8D\x8F\x90\x9D\xA0-\uFFFF]/g,Nh=/[|\\{}()[\]^$+*?.]/g,Ph=new WeakMap;function Fh(e,t){return e=e.replace(t.subset?Ih(t.subset):Ah,r),t.subset||t.escapeOnly?e:e.replace(jh,n).replace(Mh,r);function n(e,n,r){return t.format((e.charCodeAt(0)-55296)*1024+e.charCodeAt(1)-56320+65536,r.charCodeAt(n+2),t)}function r(e,n,r){return t.format(e.charCodeAt(0),r.charCodeAt(n+1),t)}}function Ih(e){let t=Ph.get(e);return t||(t=Lh(e),Ph.set(e,t)),t}function Lh(e){let t=[],n=-1;for(;++n<e.length;)t.push(e[n].replace(Nh,`\\$&`));return RegExp(`(?:`+t.join(`|`)+`)`,`g`)}var Rh=/[\dA-Fa-f]/;function zh(e,t,n){let r=`&#x`+e.toString(16).toUpperCase();return n&&t&&!Rh.test(String.fromCharCode(t))?r:r+`;`}var Bh=/\d/;function Vh(e,t,n){let r=`&#`+String(e);return n&&t&&!Bh.test(String.fromCharCode(t))?r:r+`;`}var Hh=`AElig.AMP.Aacute.Acirc.Agrave.Aring.Atilde.Auml.COPY.Ccedil.ETH.Eacute.Ecirc.Egrave.Euml.GT.Iacute.Icirc.Igrave.Iuml.LT.Ntilde.Oacute.Ocirc.Ograve.Oslash.Otilde.Ouml.QUOT.REG.THORN.Uacute.Ucirc.Ugrave.Uuml.Yacute.aacute.acirc.acute.aelig.agrave.amp.aring.atilde.auml.brvbar.ccedil.cedil.cent.copy.curren.deg.divide.eacute.ecirc.egrave.eth.euml.frac12.frac14.frac34.gt.iacute.icirc.iexcl.igrave.iquest.iuml.laquo.lt.macr.micro.middot.nbsp.not.ntilde.oacute.ocirc.ograve.ordf.ordm.oslash.otilde.ouml.para.plusmn.pound.quot.raquo.reg.sect.shy.sup1.sup2.sup3.szlig.thorn.times.uacute.ucirc.ugrave.uml.uuml.yacute.yen.yuml`.split(`.`),Uh={nbsp:`\xA0`,iexcl:`¡`,cent:`¢`,pound:`£`,curren:`¤`,yen:`¥`,brvbar:`¦`,sect:`§`,uml:`¨`,copy:`©`,ordf:`ª`,laquo:`«`,not:`¬`,shy:`­`,reg:`®`,macr:`¯`,deg:`°`,plusmn:`±`,sup2:`²`,sup3:`³`,acute:`´`,micro:`µ`,para:`¶`,middot:`·`,cedil:`¸`,sup1:`¹`,ordm:`º`,raquo:`»`,frac14:`¼`,frac12:`½`,frac34:`¾`,iquest:`¿`,Agrave:`À`,Aacute:`Á`,Acirc:`Â`,Atilde:`Ã`,Auml:`Ä`,Aring:`Å`,AElig:`Æ`,Ccedil:`Ç`,Egrave:`È`,Eacute:`É`,Ecirc:`Ê`,Euml:`Ë`,Igrave:`Ì`,Iacute:`Í`,Icirc:`Î`,Iuml:`Ï`,ETH:`Ð`,Ntilde:`Ñ`,Ograve:`Ò`,Oacute:`Ó`,Ocirc:`Ô`,Otilde:`Õ`,Ouml:`Ö`,times:`×`,Oslash:`Ø`,Ugrave:`Ù`,Uacute:`Ú`,Ucirc:`Û`,Uuml:`Ü`,Yacute:`Ý`,THORN:`Þ`,szlig:`ß`,agrave:`à`,aacute:`á`,acirc:`â`,atilde:`ã`,auml:`ä`,aring:`å`,aelig:`æ`,ccedil:`ç`,egrave:`è`,eacute:`é`,ecirc:`ê`,euml:`ë`,igrave:`ì`,iacute:`í`,icirc:`î`,iuml:`ï`,eth:`ð`,ntilde:`ñ`,ograve:`ò`,oacute:`ó`,ocirc:`ô`,otilde:`õ`,ouml:`ö`,divide:`÷`,oslash:`ø`,ugrave:`ù`,uacute:`ú`,ucirc:`û`,uuml:`ü`,yacute:`ý`,thorn:`þ`,yuml:`ÿ`,fnof:`ƒ`,Alpha:`Α`,Beta:`Β`,Gamma:`Γ`,Delta:`Δ`,Epsilon:`Ε`,Zeta:`Ζ`,Eta:`Η`,Theta:`Θ`,Iota:`Ι`,Kappa:`Κ`,Lambda:`Λ`,Mu:`Μ`,Nu:`Ν`,Xi:`Ξ`,Omicron:`Ο`,Pi:`Π`,Rho:`Ρ`,Sigma:`Σ`,Tau:`Τ`,Upsilon:`Υ`,Phi:`Φ`,Chi:`Χ`,Psi:`Ψ`,Omega:`Ω`,alpha:`α`,beta:`β`,gamma:`γ`,delta:`δ`,epsilon:`ε`,zeta:`ζ`,eta:`η`,theta:`θ`,iota:`ι`,kappa:`κ`,lambda:`λ`,mu:`μ`,nu:`ν`,xi:`ξ`,omicron:`ο`,pi:`π`,rho:`ρ`,sigmaf:`ς`,sigma:`σ`,tau:`τ`,upsilon:`υ`,phi:`φ`,chi:`χ`,psi:`ψ`,omega:`ω`,thetasym:`ϑ`,upsih:`ϒ`,piv:`ϖ`,bull:`•`,hellip:`…`,prime:`′`,Prime:`″`,oline:`‾`,frasl:`⁄`,weierp:`℘`,image:`ℑ`,real:`ℜ`,trade:`™`,alefsym:`ℵ`,larr:`←`,uarr:`↑`,rarr:`→`,darr:`↓`,harr:`↔`,crarr:`↵`,lArr:`⇐`,uArr:`⇑`,rArr:`⇒`,dArr:`⇓`,hArr:`⇔`,forall:`∀`,part:`∂`,exist:`∃`,empty:`∅`,nabla:`∇`,isin:`∈`,notin:`∉`,ni:`∋`,prod:`∏`,sum:`∑`,minus:`−`,lowast:`∗`,radic:`√`,prop:`∝`,infin:`∞`,ang:`∠`,and:`∧`,or:`∨`,cap:`∩`,cup:`∪`,int:`∫`,there4:`∴`,sim:`∼`,cong:`≅`,asymp:`≈`,ne:`≠`,equiv:`≡`,le:`≤`,ge:`≥`,sub:`⊂`,sup:`⊃`,nsub:`⊄`,sube:`⊆`,supe:`⊇`,oplus:`⊕`,otimes:`⊗`,perp:`⊥`,sdot:`⋅`,lceil:`⌈`,rceil:`⌉`,lfloor:`⌊`,rfloor:`⌋`,lang:`〈`,rang:`〉`,loz:`◊`,spades:`♠`,clubs:`♣`,hearts:`♥`,diams:`♦`,quot:`"`,amp:`&`,lt:`<`,gt:`>`,OElig:`Œ`,oelig:`œ`,Scaron:`Š`,scaron:`š`,Yuml:`Ÿ`,circ:`ˆ`,tilde:`˜`,ensp:` `,emsp:` `,thinsp:` `,zwnj:`‌`,zwj:`‍`,lrm:`‎`,rlm:`‏`,ndash:`–`,mdash:`—`,lsquo:`‘`,rsquo:`’`,sbquo:`‚`,ldquo:`“`,rdquo:`”`,bdquo:`„`,dagger:`†`,Dagger:`‡`,permil:`‰`,lsaquo:`‹`,rsaquo:`›`,euro:`€`},Wh=[`cent`,`copy`,`divide`,`gt`,`lt`,`not`,`para`,`times`],Gh={}.hasOwnProperty,Kh={},qh;for(qh in Uh)Gh.call(Uh,qh)&&(Kh[Uh[qh]]=qh);var Jh=/[^\dA-Za-z]/;function Yh(e,t,n,r){let i=String.fromCharCode(e);if(Gh.call(Kh,i)){let e=Kh[i],a=`&`+e;return n&&Hh.includes(e)&&!Wh.includes(e)&&(!r||t&&t!==61&&Jh.test(String.fromCharCode(t)))?a:a+`;`}return``}function Xh(e,t,n){let r=zh(e,t,n.omitOptionalSemicolons),i;if((n.useNamedReferences||n.useShortestReferences)&&(i=Yh(e,t,n.omitOptionalSemicolons,n.attribute)),(n.useShortestReferences||!i)&&n.useShortestReferences){let i=Vh(e,t,n.omitOptionalSemicolons);i.length<r.length&&(r=i)}return i&&(!n.useShortestReferences||i.length<r.length)?i:r}function Zh(e,t){return Fh(e,Object.assign({format:Xh},t))}var Qh=/^>|^->|<!--|-->|--!>|<!-$/g,$h=[`>`],eg=[`<`,`>`];function tg(e,t,n,r){return r.settings.bogusComments?`<?`+Zh(e.value,Object.assign({},r.settings.characterReferences,{subset:$h}))+`>`:`<!--`+e.value.replace(Qh,i)+`-->`;function i(e){return Zh(e,Object.assign({},r.settings.characterReferences,{subset:eg}))}}function ng(e,t,n,r){return`<!`+(r.settings.upperDoctype?`DOCTYPE`:`doctype`)+(r.settings.tightDoctype?``:` `)+`html>`}function rg(e,t){let n=String(e);if(typeof t!=`string`)throw TypeError(`Expected character`);let r=0,i=n.indexOf(t);for(;i!==-1;)r++,i=n.indexOf(t,i+t.length);return r}function ig(e,t){let n=t||{};return(e[e.length-1]===``?[...e,``]:e).join((n.padRight?` `:``)+`,`+(n.padLeft===!1?``:` `)).trim()}function ag(e){return e.join(` `).trim()}var og=/[ \t\n\f\r]/g;function sg(e){return typeof e==`object`?e.type===`text`&&cg(e.value):cg(e)}function cg(e){return e.replace(og,``)===``}var lg=fg(1),ug=fg(-1),dg=[];function fg(e){return t;function t(t,n,r){let i=t?t.children:dg,a=(n||0)+e,o=i[a];if(!r)for(;o&&sg(o);)a+=e,o=i[a];return o}}var pg={}.hasOwnProperty;function mg(e){return t;function t(t,n,r){return pg.call(e,t.tagName)&&e[t.tagName](t,n,r)}}var hg=mg({body:vg,caption:gg,colgroup:gg,dd:Sg,dt:xg,head:gg,html:_g,li:bg,optgroup:wg,option:Tg,p:yg,rp:Cg,rt:Cg,tbody:Dg,td:Ag,tfoot:Og,th:Ag,thead:Eg,tr:kg});function gg(e,t,n){let r=lg(n,t,!0);return!r||r.type!==`comment`&&!(r.type===`text`&&sg(r.value.charAt(0)))}function _g(e,t,n){let r=lg(n,t);return!r||r.type!==`comment`}function vg(e,t,n){let r=lg(n,t);return!r||r.type!==`comment`}function yg(e,t,n){let r=lg(n,t);return r?r.type===`element`&&(r.tagName===`address`||r.tagName===`article`||r.tagName===`aside`||r.tagName===`blockquote`||r.tagName===`details`||r.tagName===`div`||r.tagName===`dl`||r.tagName===`fieldset`||r.tagName===`figcaption`||r.tagName===`figure`||r.tagName===`footer`||r.tagName===`form`||r.tagName===`h1`||r.tagName===`h2`||r.tagName===`h3`||r.tagName===`h4`||r.tagName===`h5`||r.tagName===`h6`||r.tagName===`header`||r.tagName===`hgroup`||r.tagName===`hr`||r.tagName===`main`||r.tagName===`menu`||r.tagName===`nav`||r.tagName===`ol`||r.tagName===`p`||r.tagName===`pre`||r.tagName===`section`||r.tagName===`table`||r.tagName===`ul`):!n||n.type!==`element`||n.tagName!==`a`&&n.tagName!==`audio`&&n.tagName!==`del`&&n.tagName!==`ins`&&n.tagName!==`map`&&n.tagName!==`noscript`&&n.tagName!==`video`}function bg(e,t,n){let r=lg(n,t);return!r||r.type===`element`&&r.tagName===`li`}function xg(e,t,n){let r=lg(n,t);return!(!r||r.type!==`element`||r.tagName!==`dt`&&r.tagName!==`dd`)}function Sg(e,t,n){let r=lg(n,t);return!r||r.type===`element`&&(r.tagName===`dt`||r.tagName===`dd`)}function Cg(e,t,n){let r=lg(n,t);return!r||r.type===`element`&&(r.tagName===`rp`||r.tagName===`rt`)}function wg(e,t,n){let r=lg(n,t);return!r||r.type===`element`&&r.tagName===`optgroup`}function Tg(e,t,n){let r=lg(n,t);return!r||r.type===`element`&&(r.tagName===`option`||r.tagName===`optgroup`)}function Eg(e,t,n){let r=lg(n,t);return!(!r||r.type!==`element`||r.tagName!==`tbody`&&r.tagName!==`tfoot`)}function Dg(e,t,n){let r=lg(n,t);return!r||r.type===`element`&&(r.tagName===`tbody`||r.tagName===`tfoot`)}function Og(e,t,n){return!lg(n,t)}function kg(e,t,n){let r=lg(n,t);return!r||r.type===`element`&&r.tagName===`tr`}function Ag(e,t,n){let r=lg(n,t);return!r||r.type===`element`&&(r.tagName===`td`||r.tagName===`th`)}var jg=mg({body:Pg,colgroup:Fg,head:Ng,html:Mg,tbody:Ig});function Mg(e){let t=lg(e,-1);return!t||t.type!==`comment`}function Ng(e){let t=new Set;for(let n of e.children)if(n.type===`element`&&(n.tagName===`base`||n.tagName===`title`)){if(t.has(n.tagName))return!1;t.add(n.tagName)}let n=e.children[0];return!n||n.type===`element`}function Pg(e){let t=lg(e,-1,!0);return!t||t.type!==`comment`&&!(t.type===`text`&&sg(t.value.charAt(0)))&&(t.type!==`element`||t.tagName!==`meta`&&t.tagName!==`link`&&t.tagName!==`script`&&t.tagName!==`style`&&t.tagName!==`template`)}function Fg(e,t,n){let r=ug(n,t),i=lg(e,-1,!0);return n&&r&&r.type===`element`&&r.tagName===`colgroup`&&hg(r,n.children.indexOf(r),n)?!1:!!(i&&i.type===`element`&&i.tagName===`col`)}function Ig(e,t,n){let r=ug(n,t),i=lg(e,-1);return n&&r&&r.type===`element`&&(r.tagName===`thead`||r.tagName===`tbody`)&&hg(r,n.children.indexOf(r),n)?!1:!!(i&&i.type===`element`&&i.tagName===`tr`)}var Lg={name:[[`
27
27
  \f\r &/=>`.split(``),`
28
28
  \f\r "&'/=>\``.split(``)],[`\0
29
29
  \f\r "&'/<=>`.split(``),`\0
@@ -31,10 +31,10 @@ WARNING: This link could potentially be dangerous`)){let e=window.open();if(e){t
31
31
  \f\r &>`.split(``),`\0
32
32
  \f\r "&'<=>\``.split(``)],[`\0
33
33
  \f\r "&'<=>\``.split(``),`\0
34
- \f\r "&'<=>\``.split(``)]],single:[[`&'`.split(``),`"&'\``.split(``)],[`\0&'`.split(``),`\0"&'\``.split(``)]],double:[[`"&`.split(``),`"&'\``.split(``)],[`\0"&`.split(``),`\0"&'\``.split(``)]]};function Lg(e,t,n,r){let i=r.schema,a=i.space!==`svg`&&r.settings.omitOptionalTags,o=i.space===`svg`?r.settings.closeEmptyElements:r.settings.voids.includes(e.tagName.toLowerCase()),s=[],c;i.space===`html`&&e.tagName===`svg`&&(r.schema=Eh);let l=Rg(r,e.properties),u=r.all(i.space===`html`&&e.tagName===`template`?e.content:e);return r.schema=i,u&&(o=!1),(l||!a||!Ag(e,t,n))&&(s.push(`<`,e.tagName,l?` `+l:``),o&&(i.space===`svg`||r.settings.closeSelfClosing)&&(c=l.charAt(l.length-1),(!r.settings.tightSelfClosing||c===`/`||c&&c!==`"`&&c!==`'`)&&s.push(` `),s.push(`/`)),s.push(`>`)),s.push(u),!o&&(!a||!mg(e,t,n))&&s.push(`</`+e.tagName+`>`),s.join(``)}function Rg(e,t){let n=[],r=-1,i;if(t){for(i in t)if(t[i]!==null&&t[i]!==void 0){let r=zg(e,i,t[i]);r&&n.push(r)}}for(;++r<n.length;){let t=e.settings.tightAttributes?n[r].charAt(n[r].length-1):void 0;r!==n.length-1&&t!==`"`&&t!==`'`&&(n[r]+=` `)}return n.join(``)}function zg(e,t,n){let r=Sh(e.schema,t),i=e.settings.allowParseErrors&&e.schema.space===`html`?0:1,a=+!e.settings.allowDangerousCharacters,o=e.quote,s;if(r.overloadedBoolean&&(n===r.attribute||n===``)?n=!0:(r.boolean||r.overloadedBoolean)&&(typeof n!=`string`||n===r.attribute||n===``)&&(n=!!n),n==null||n===!1||typeof n==`number`&&Number.isNaN(n))return``;let c=Xh(r.attribute,Object.assign({},e.settings.characterReferences,{subset:Ig.name[i][a]}));return n===!0||(n=Array.isArray(n)?(r.commaSeparated?rg:ig)(n,{padLeft:!e.settings.tightCommaSeparatedLists}):String(n),e.settings.collapseEmptyAttributes&&!n)?c:(e.settings.preferUnquoted&&(s=Xh(n,Object.assign({},e.settings.characterReferences,{attribute:!0,subset:Ig.unquoted[i][a]}))),s!==n&&(e.settings.quoteSmart&&ng(n,o)>ng(n,e.alternative)&&(o=e.alternative),s=o+Xh(n,Object.assign({},e.settings.characterReferences,{subset:(o===`'`?Ig.single:Ig.double)[i][a],attribute:!0}))+o),c+(s&&`=`+s))}var Bg=[`<`,`&`];function Vg(e,t,n,r){return n&&n.type===`element`&&(n.tagName===`script`||n.tagName===`style`)?e.value:Xh(e.value,Object.assign({},r.settings.characterReferences,{subset:Bg}))}function Hg(e,t,n,r){return r.settings.allowDangerousHtml?e.value:Vg(e,t,n,r)}function Ug(e,t,n,r){return r.all(e)}var Wg=Oh(`type`,{invalid:Gg,unknown:Kg,handlers:{comment:eg,doctype:tg,element:Lg,raw:Hg,root:Ug,text:Vg}});function Gg(e){throw Error("Expected node, not `"+e+"`")}function Kg(e){throw Error("Cannot compile unknown node `"+e.type+"`")}var qg={},Jg={},Yg=[];function Xg(e,t){let n=t||qg,r=n.quote||`"`,i=r===`"`?`'`:`"`;if(r!==`"`&&r!==`'`)throw Error("Invalid quote `"+r+"`, expected `'` or `\"`");return{one:Zg,all:Qg,settings:{omitOptionalTags:n.omitOptionalTags||!1,allowParseErrors:n.allowParseErrors||!1,allowDangerousCharacters:n.allowDangerousCharacters||!1,quoteSmart:n.quoteSmart||!1,preferUnquoted:n.preferUnquoted||!1,tightAttributes:n.tightAttributes||!1,upperDoctype:n.upperDoctype||!1,tightDoctype:n.tightDoctype||!1,bogusComments:n.bogusComments||!1,tightCommaSeparatedLists:n.tightCommaSeparatedLists||!1,tightSelfClosing:n.tightSelfClosing||!1,collapseEmptyAttributes:n.collapseEmptyAttributes||!1,allowDangerousHtml:n.allowDangerousHtml||!1,voids:n.voids||Ym,characterReferences:n.characterReferences||Jg,closeSelfClosing:n.closeSelfClosing||!1,closeEmptyElements:n.closeEmptyElements||!1},schema:n.space===`svg`?Eh:Th,quote:r,alternative:i}.one(Array.isArray(e)?{type:`root`,children:e}:e,void 0,void 0)}function Zg(e,t,n){return Wg(e,t,n,this)}function Qg(e){let t=[],n=e&&e.children||Yg,r=-1;for(;++r<n.length;)t[r]=this.one(n[r],r,e);return t.join(``)}var $g=/\s+/g;function e_(e,t){if(!t)return e;e.properties||={},e.properties.class||=[],typeof e.properties.class==`string`&&(e.properties.class=e.properties.class.split($g)),Array.isArray(e.properties.class)||(e.properties.class=[]);let n=Array.isArray(t)?t:t.split($g);for(let t of n)t&&!e.properties.class.includes(t)&&e.properties.class.push(t);return e}function t_(e){let t=_m(e,!0).map(([e])=>e);function n(n){if(n===e.length)return{line:t.length-1,character:t.at(-1).length};let r=n,i=0;for(let e of t){if(r<e.length)break;r-=e.length,i++}return{line:i,character:r}}function r(e,n){let r=0;for(let n=0;n<e;n++)r+=t[n].length;return r+=n,r}return{lines:t,indexToPos:n,posToIndex:r}}var n_=[`color`,`background-color`];function r_(e,t){let n=0,r=[];for(let i of t)i>n&&r.push({...e,content:e.content.slice(n,i),offset:e.offset+n}),n=i;return n<e.content.length&&r.push({...e,content:e.content.slice(n),offset:e.offset+n}),r}function i_(e,t){let n=0,r=e.length;for(;n<r;){let i=n+(r-n>>1);e[i]<=t?n=i+1:r=i}return n}function a_(e,t){let n=[...t instanceof Set?t:new Set(t)].sort((e,t)=>e-t);return n.length?e.map(e=>e.flatMap(e=>{let t=e.offset+e.content.length,r=i_(n,e.offset),i=r;for(;i<n.length&&n[i]<t;)i++;if(r===i)return e;let a=n.slice(r,i);for(let t=0;t<a.length;t++)a[t]-=e.offset;return r_(e,a)})):e}function o_(e,t,n,r,i=`css-vars`){let a={content:e.content,explanation:e.explanation,offset:e.offset},o=t.map(t=>s_(e.variants[t])),s=new Set(o.flatMap(e=>Object.keys(e))),c={},l=(e,r)=>{let i=r===`color`?``:r===`background-color`?`-bg`:`-${r}`;return n+t[e]+(r===`color`?``:i)};return o.forEach((e,n)=>{for(let a of s){let s=e[a]||`inherit`;if(n===0&&r&&n_.includes(a)){if(r===`light-dark()`&&o.length>1){let e=t.findIndex(e=>e===`light`),r=t.findIndex(e=>e===`dark`);if(e===-1||r===-1)throw new Ef('When using `defaultColor: "light-dark()"`, you must provide both `light` and `dark` themes');let u=o[e][a]||`inherit`,d=o[r][a]||`inherit`;c[a]=`light-dark(${u}, ${d})`,i===`css-vars`&&(c[l(n,a)]=s)}else c[a]=s}else i===`css-vars`&&(c[l(n,a)]=s)}}),a.htmlStyle=c,a}function s_(e){let t={};if(e.color&&(t.color=e.color),e.bgColor&&(t[`background-color`]=e.bgColor),e.fontStyle){e.fontStyle&qf.Italic&&(t[`font-style`]=`italic`),e.fontStyle&qf.Bold&&(t[`font-weight`]=`bold`);let n=[];e.fontStyle&qf.Underline&&n.push(`underline`),e.fontStyle&qf.Strikethrough&&n.push(`line-through`),n.length&&(t[`text-decoration`]=n.join(` `))}return t}function c_(e){return typeof e==`string`?e:Object.entries(e).map(([e,t])=>`${e}:${t}`).join(`;`)}function l_(){let e=new WeakMap;function t(t){if(!e.has(t.meta)){let n=t_(t.source);function r(e){if(typeof e==`number`){if(e<0||e>t.source.length)throw new Ef(`Invalid decoration offset: ${e}. Code length: ${t.source.length}`);return{...n.indexToPos(e),offset:e}}{let t=n.lines[e.line];if(t===void 0)throw new Ef(`Invalid decoration position ${JSON.stringify(e)}. Lines length: ${n.lines.length}`);let r=e.character;if(r<0&&(r=t.length+r),r<0||r>t.length)throw new Ef(`Invalid decoration position ${JSON.stringify(e)}. Line ${e.line} length: ${t.length}`);return{...e,character:r,offset:n.posToIndex(e.line,r)}}}let i=(t.options.decorations||[]).map(e=>({...e,start:r(e.start),end:r(e.end)}));u_(i),e.set(t.meta,{decorations:i,converter:n,source:t.source})}return e.get(t.meta)}return{name:`shiki:decorations`,tokens(e){if(this.options.decorations?.length)return a_(e,t(this).decorations.flatMap(e=>[e.start.offset,e.end.offset]))},code(e){if(!this.options.decorations?.length)return;let n=t(this),r=[...e.children].filter(e=>e.type===`element`&&e.tagName===`span`);if(r.length!==n.converter.lines.length)throw new Ef(`Number of lines in code element (${r.length}) does not match the number of lines in the source (${n.converter.lines.length}). Failed to apply decorations.`);function i(e,t,n,i){let a=r[e],s=``,c=-1,l=-1;if(t===0&&(c=0),n===0&&(l=0),n===1/0&&(l=a.children.length),c===-1||l===-1)for(let e=0;e<a.children.length;e++)s+=d_(a.children[e]),c===-1&&s.length===t&&(c=e+1),l===-1&&s.length===n&&(l=e+1);if(c===-1)throw new Ef(`Failed to find start index for decoration ${JSON.stringify(i.start)}`);if(l===-1)throw new Ef(`Failed to find end index for decoration ${JSON.stringify(i.end)}`);let u=a.children.slice(c,l);if(!i.alwaysWrap&&u.length===a.children.length)o(a,i,`line`);else if(!i.alwaysWrap&&u.length===1&&u[0].type===`element`)o(u[0],i,`token`);else{let e={type:`element`,tagName:`span`,properties:{},children:u};o(e,i,`wrapper`),a.children.splice(c,u.length,e)}}function a(e,t){r[e]=o(r[e],t,`line`)}function o(e,t,n){let r=t.properties||{},i=t.transform||(e=>e);return e.tagName=t.tagName||`span`,e.properties={...e.properties,...r,class:e.properties.class},t.properties?.class&&e_(e,t.properties.class),e=i(e,n)||e,e}let s=[],c=n.decorations.sort((e,t)=>t.start.offset-e.start.offset||e.end.offset-t.end.offset);for(let e of c){let{start:t,end:n}=e;if(t.line===n.line)i(t.line,t.character,n.character,e);else if(t.line<n.line){i(t.line,t.character,1/0,e);for(let r=t.line+1;r<n.line;r++)s.unshift(()=>a(r,e));i(n.line,0,n.character,e)}}s.forEach(e=>e())}}}function u_(e){for(let t=0;t<e.length;t++){let n=e[t];if(n.start.offset>n.end.offset)throw new Ef(`Invalid decoration range: ${JSON.stringify(n.start)} - ${JSON.stringify(n.end)}`);for(let r=t+1;r<e.length;r++){let t=e[r],i=n.start.offset<=t.start.offset&&t.start.offset<n.end.offset,a=n.start.offset<t.end.offset&&t.end.offset<=n.end.offset,o=t.start.offset<=n.start.offset&&n.start.offset<t.end.offset,s=t.start.offset<n.end.offset&&n.end.offset<=t.end.offset;if(i||a||o||s){if(i&&a||o&&s||o&&n.start.offset===n.end.offset||a&&t.start.offset===t.end.offset)continue;throw new Ef(`Decorations ${JSON.stringify(n.start)} and ${JSON.stringify(t.start)} intersect.`)}}}}function d_(e){return e.type===`text`?e.value:e.type===`element`?e.children.map(d_).join(``):``}var f_=[l_()];function p_(e){let t=m_(e.transformers||[]);return[...t.pre,...t.normal,...t.post,...f_]}function m_(e){let t=[],n=[],r=[];for(let i of e)switch(i.enforce){case`pre`:t.push(i);break;case`post`:n.push(i);break;default:r.push(i)}return{pre:t,post:n,normal:r}}var h_=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`brightBlack`,`brightRed`,`brightGreen`,`brightYellow`,`brightBlue`,`brightMagenta`,`brightCyan`,`brightWhite`],g_={1:`bold`,2:`dim`,3:`italic`,4:`underline`,7:`reverse`,8:`hidden`,9:`strikethrough`};function __(e,t){let n=e.indexOf(`\x1B`,t);if(n!==-1&&e[n+1]===`[`){let t=e.indexOf(`m`,n);if(t!==-1)return{sequence:e.substring(n+2,t).split(`;`),startPosition:n,position:t+1}}return{position:e.length}}function v_(e){let t=e.shift();if(t===`2`){let t=e.splice(0,3).map(e=>Number.parseInt(e));return t.length!==3||t.some(e=>Number.isNaN(e))?void 0:{type:`rgb`,rgb:t}}if(t===`5`){let t=e.shift();if(t)return{type:`table`,index:Number(t)}}}function y_(e){let t=[];for(;e.length>0;){let n=e.shift();if(!n)continue;let r=Number.parseInt(n);if(!Number.isNaN(r)){if(r===0)t.push({type:`resetAll`});else if(r<=9)g_[r]&&t.push({type:`setDecoration`,value:g_[r]});else if(r<=29){let e=g_[r-20];e&&(t.push({type:`resetDecoration`,value:e}),e===`dim`&&t.push({type:`resetDecoration`,value:`bold`}))}else if(r<=37)t.push({type:`setForegroundColor`,value:{type:`named`,name:h_[r-30]}});else if(r===38){let n=v_(e);n&&t.push({type:`setForegroundColor`,value:n})}else if(r===39)t.push({type:`resetForegroundColor`});else if(r<=47)t.push({type:`setBackgroundColor`,value:{type:`named`,name:h_[r-40]}});else if(r===48){let n=v_(e);n&&t.push({type:`setBackgroundColor`,value:n})}else r===49?t.push({type:`resetBackgroundColor`}):r===53?t.push({type:`setDecoration`,value:`overline`}):r===55?t.push({type:`resetDecoration`,value:`overline`}):r>=90&&r<=97?t.push({type:`setForegroundColor`,value:{type:`named`,name:h_[r-90+8]}}):r>=100&&r<=107&&t.push({type:`setBackgroundColor`,value:{type:`named`,name:h_[r-100+8]}})}}return t}function b_(){let e=null,t=null,n=new Set;return{parse(r){let i=[],a=0;do{let o=__(r,a),s=o.sequence?r.substring(a,o.startPosition):r.substring(a);if(s.length>0&&i.push({value:s,foreground:e,background:t,decorations:new Set(n)}),o.sequence){let r=y_(o.sequence);for(let i of r)i.type===`resetAll`?(e=null,t=null,n.clear()):i.type===`resetForegroundColor`?e=null:i.type===`resetBackgroundColor`?t=null:i.type===`resetDecoration`&&n.delete(i.value);for(let i of r)i.type===`setForegroundColor`?e=i.value:i.type===`setBackgroundColor`?t=i.value:i.type===`setDecoration`&&n.add(i.value)}a=o.position}while(a<r.length);return i}}}var x_={black:`#000000`,red:`#bb0000`,green:`#00bb00`,yellow:`#bbbb00`,blue:`#0000bb`,magenta:`#ff00ff`,cyan:`#00bbbb`,white:`#eeeeee`,brightBlack:`#555555`,brightRed:`#ff5555`,brightGreen:`#00ff00`,brightYellow:`#ffff55`,brightBlue:`#5555ff`,brightMagenta:`#ff55ff`,brightCyan:`#55ffff`,brightWhite:`#ffffff`};function S_(e=x_){function t(t){return e[t]}function n(e){return`#${e.map(e=>Math.max(0,Math.min(e,255)).toString(16).padStart(2,`0`)).join(``)}`}let r;function i(){if(r)return r;r=[];for(let e=0;e<h_.length;e++)r.push(t(h_[e]));let 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++)r.push(n([e[t],e[i],e[a]]));let i=8;for(let e=0;e<24;e++,i+=10)r.push(n([i,i,i]));return r}function a(e){return i()[e]}function o(e){switch(e.type){case`named`:return t(e.name);case`rgb`:return n(e.rgb);case`table`:return a(e.index)}}return{value:o}}var C_=/#([0-9a-f]{3,8})/i,w_=/var\((--[\w-]+-ansi-[\w-]+)\)/,T_={black:`#000000`,red:`#cd3131`,green:`#0DBC79`,yellow:`#E5E510`,blue:`#2472C8`,magenta:`#BC3FBC`,cyan:`#11A8CD`,white:`#E5E5E5`,brightBlack:`#666666`,brightRed:`#F14C4C`,brightGreen:`#23D18B`,brightYellow:`#F5F543`,brightBlue:`#3B8EEA`,brightMagenta:`#D670D6`,brightCyan:`#29B8DB`,brightWhite:`#FFFFFF`};function E_(e,t,n){let r=cm(e,n),i=_m(t),a=S_(Object.fromEntries(h_.map(t=>{let n=`terminal.ansi${t[0].toUpperCase()}${t.substring(1)}`;return[t,e.colors?.[n]||T_[t]]}))),o=b_();return i.map(t=>o.parse(t[0]).map(n=>{let i,o;n.decorations.has(`reverse`)?(i=n.background?a.value(n.background):e.bg,o=n.foreground?a.value(n.foreground):e.fg):(i=n.foreground?a.value(n.foreground):e.fg,o=n.background?a.value(n.background):void 0),i=lm(i,r),o=lm(o,r),n.decorations.has(`dim`)&&(i=D_(i));let s=qf.None;return n.decorations.has(`bold`)&&(s|=qf.Bold),n.decorations.has(`italic`)&&(s|=qf.Italic),n.decorations.has(`underline`)&&(s|=qf.Underline),n.decorations.has(`strikethrough`)&&(s|=qf.Strikethrough),{content:n.value,offset:t[1],color:i,bgColor:o,fontStyle:s}}))}function D_(e){let t=e.match(C_);if(t){let e=t[1];if(e.length===8){let t=Math.round(Number.parseInt(e.slice(6,8),16)/2).toString(16).padStart(2,`0`);return`#${e.slice(0,6)}${t}`}if(e.length===6)return`#${e}80`;if(e.length===4){let t=e[0],n=e[1],r=e[2],i=e[3];return`#${t}${t}${n}${n}${r}${r}${Math.round(Number.parseInt(`${i}${i}`,16)/2).toString(16).padStart(2,`0`)}`}if(e.length===3){let t=e[0],n=e[1],r=e[2];return`#${t}${t}${n}${n}${r}${r}80`}}let n=e.match(w_);return n?`var(${n[1]}-dim)`:e}function O_(e,t,n={}){let r=e.resolveLangAlias(n.lang||`text`),{theme:i=e.getLoadedThemes()[0]}=n;if(!fm(r)&&!mm(i)&&r===`ansi`){let{theme:r}=e.setTheme(i);return E_(r,t,n)}return Rm(e,t,n)}function k_(e,t,n){let r,i,a,o,s,c;if(`themes`in n){let{defaultColor:l=`light`,cssVariablePrefix:u=`--shiki-`,colorsRendering:d=`css-vars`}=n,f=Object.entries(n.themes).filter(e=>e[1]).map(e=>({color:e[0],theme:e[1]})).sort((e,t)=>e.color===l?-1:+(t.color===l));if(f.length===0)throw new Ef("`themes` option must not be empty");let p=qm(e,t,n,O_);if(c=Mm(p),l&&l!==`light-dark()`&&!f.some(e=>e.color===l))throw new Ef(`\`themes\` option must contain the defaultColor key \`${l}\``);let m=f.map(t=>e.getTheme(t.theme)),h=f.map(e=>e.color);a=p.map(e=>e.map(e=>o_(e,h,u,l,d))),c&&jm(a,c);let g=f.map(e=>cm(e.theme,n));i=A_(f,m,g,u,l,`fg`,d),r=A_(f,m,g,u,l,`bg`,d),o=`shiki-themes ${m.map(e=>e.name).join(` `)}`,s=l?void 0:[i,r].join(`;`)}else if(`theme`in n){let s=cm(n.theme,n);a=O_(e,t,n);let l=e.getTheme(n.theme);r=lm(l.bg,s),i=lm(l.fg,s),o=l.name,c=Mm(a)}else throw new Ef("Invalid options, either `theme` or `themes` must be provided");return{tokens:a,fg:i,bg:r,themeName:o,rootStyle:s,grammarState:c}}function A_(e,t,n,r,i,a,o){return e.map((s,c)=>{let l=lm(t[c][a],n[c])||`inherit`,u=`${r+s.color}${a===`bg`?`-bg`:``}:${l}`;if(c===0&&i){if(i===`light-dark()`&&e.length>1){let r=e.findIndex(e=>e.color===`light`),i=e.findIndex(e=>e.color===`dark`);if(r===-1||i===-1)throw new Ef('When using `defaultColor: "light-dark()"`, you must provide both `light` and `dark` themes');return`light-dark(${lm(t[r][a],n[r])||`inherit`}, ${lm(t[i][a],n[i])||`inherit`});${u}`}return l}return o===`css-vars`?u:null}).filter(e=>!!e).join(`;`)}var j_=/^\s+$/,M_=/^(\s*)(.*?)(\s*)$/;function N_(e,t,n,r={meta:{},options:n,codeToHast:(t,n)=>N_(e,t,n),codeToTokens:(t,n)=>k_(e,t,n)}){let i=t;for(let e of p_(n))i=e.preprocess?.call(r,i,n)||i;let{tokens:a,fg:o,bg:s,themeName:c,rootStyle:l,grammarState:u}=k_(e,i,n),{mergeWhitespaces:d=!0,mergeSameStyleTokens:f=!1}=n;d===!0?a=F_(a):d===`never`&&(a=I_(a)),f&&(a=L_(a));let p={...r,get source(){return i}};for(let e of p_(n))a=e.tokens?.call(p,a)||a;return P_(a,{...n,fg:o,bg:s,themeName:c,rootStyle:n.rootStyle===!1?!1:n.rootStyle??l},p,u)}function P_(e,t,n,r=Mm(e)){let i=p_(t),a=[],o={type:`root`,children:[]},{structure:s=`classic`,tabindex:c=`0`}=t,l={class:`shiki ${t.themeName||``}`};t.rootStyle!==!1&&(l.style=t.rootStyle==null?`background-color:${t.bg};color:${t.fg}`:t.rootStyle),c!==!1&&c!=null&&(l.tabindex=c.toString());for(let[e,n]of Object.entries(t.meta||{}))e.startsWith(`_`)||(l[e]=n);let u={type:`element`,tagName:`pre`,properties:l,children:[],data:t.data},d={type:`element`,tagName:`code`,properties:{},children:a},f=[],p={...n,structure:s,addClassToHast:e_,get source(){return n.source},get tokens(){return e},get options(){return t},get root(){return o},get pre(){return u},get code(){return d},get lines(){return f}};if(e.forEach((e,t)=>{t&&(s===`inline`?o.children.push({type:`element`,tagName:`br`,properties:{},children:[]}):s===`classic`&&a.push({type:`text`,value:`
35
- `}));let n={type:`element`,tagName:`span`,properties:{class:`line`},children:[]},r=0;for(let a of e){let e={type:`element`,tagName:`span`,properties:{...a.htmlAttrs},children:[{type:`text`,value:a.content}]},c=c_(a.htmlStyle||s_(a));c&&(e.properties.style=c);for(let o of i)e=o?.span?.call(p,e,t+1,r,n,a)||e;s===`inline`?o.children.push(e):s===`classic`&&n.children.push(e),r+=a.content.length}if(s===`classic`){for(let e of i)n=e?.line?.call(p,n,t+1)||n;f.push(n),a.push(n)}else s===`inline`&&f.push(n)}),s===`classic`){for(let e of i)d=e?.code?.call(p,d)||d;u.children.push(d);for(let e of i)u=e?.pre?.call(p,u)||u;o.children.push(u)}else if(s===`inline`){let e=[],t={type:`element`,tagName:`span`,properties:{class:`line`},children:[]};for(let n of o.children)n.type===`element`&&n.tagName===`br`?(e.push(t),t={type:`element`,tagName:`span`,properties:{class:`line`},children:[]}):(n.type===`element`||n.type===`text`)&&t.children.push(n);e.push(t);let n={type:`element`,tagName:`code`,properties:{},children:e};for(let e of i)n=e?.code?.call(p,n)||n;o.children=[];for(let e=0;e<n.children.length;e++){e>0&&o.children.push({type:`element`,tagName:`br`,properties:{},children:[]});let t=n.children[e];t.type===`element`&&o.children.push(...t.children)}}let m=o;for(let e of i)m=e?.root?.call(p,m)||m;return r&&jm(m,r),m}function F_(e){return e.map(e=>{let t=[],n=``,r;return e.forEach((i,a)=>{let o=!(i.fontStyle&&(i.fontStyle&qf.Underline||i.fontStyle&qf.Strikethrough));o&&j_.test(i.content)&&e[a+1]?(r===void 0&&(r=i.offset),n+=i.content):n?(o?t.push({...i,offset:r,content:n+i.content}):t.push({content:n,offset:r},i),r=void 0,n=``):t.push(i)}),t})}function I_(e){return e.map(e=>e.flatMap(e=>{if(j_.test(e.content))return e;let t=e.content.match(M_);if(!t)return e;let[,n,r,i]=t;if(!n&&!i)return e;let a=[{...e,offset:e.offset+n.length,content:r}];return n&&a.unshift({content:n,offset:e.offset}),i&&a.push({content:i,offset:e.offset+n.length+r.length}),a}))}function L_(e){return e.map(e=>{let t=[];for(let n of e){if(t.length===0){t.push({...n});continue}let e=t.at(-1),r=c_(e.htmlStyle||s_(e)),i=c_(n.htmlStyle||s_(n)),a=e.fontStyle&&(e.fontStyle&qf.Underline||e.fontStyle&qf.Strikethrough),o=n.fontStyle&&(n.fontStyle&qf.Underline||n.fontStyle&qf.Strikethrough);!a&&!o&&r===i?e.content+=n.content:t.push({...n})}return t})}var R_=Xg;function z_(e,t,n){let r={meta:{},options:n,codeToHast:(t,n)=>N_(e,t,n),codeToTokens:(t,n)=>k_(e,t,n)},i=R_(N_(e,t,n,r));for(let e of p_(n))i=e.postprocess?.call(r,i,n)||i;return i}async function B_(e){let t=await km(e);return{getLastGrammarState:(...e)=>zm(t,...e),codeToTokensBase:(e,n)=>O_(t,e,n),codeToTokensWithThemes:(e,n)=>qm(t,e,n),codeToTokens:(e,n)=>k_(t,e,n),codeToHast:(e,n)=>N_(t,e,n),codeToHtml:(e,n)=>z_(t,e,n),getBundledLanguages:()=>({}),getBundledThemes:()=>({}),...t,getInternalContext:()=>t}}var V_=4294967295;function H_(e){return!e.sticky&&!e.rawOptions?.strategy}function U_(e,t){return{index:e,captureIndices:t.map(e=>e==null?{start:V_,end:V_,length:0}:{start:e[0],end:e[1],length:e[1]-e[0]})}}var W_=class{patterns;options;regexps;lastSearches;constructor(e,t={}){this.patterns=e,this.options=t;let{forgiving:n=!1,cache:r,regexConstructor:i}=t;if(!i)throw Error("Option `regexConstructor` is not provided");this.regexps=e.map(e=>{if(typeof e!=`string`)return e;let t=r?.get(e);if(t){if(t instanceof RegExp)return t;if(n)return null;throw t}try{let t=i(e);return r?.set(e,t),t}catch(t){if(r?.set(e,t),n)return null;throw t}}),this.lastSearches=this.regexps.map(e=>e&&H_(e)?{strId:0,searchedFrom:0,matchIndex:-1,indices:null}:null)}findNextMatchSync(e,t,n){let r=typeof e==`string`?e:e.content,i=typeof e==`string`?0:e.id||0,a=-1,o=0,s=null;for(let e=0;e<this.regexps.length;e++){let n=this.regexps[e];if(n)try{let c=i?this.lastSearches[e]:null,l,u;if(c&&c.strId===i&&c.searchedFrom<=t&&(c.matchIndex===-1||c.matchIndex>=t))l=c.matchIndex,u=c.indices;else{n.lastIndex=t;let e=n.exec(r);l=e?e.index:-1,u=e?e.indices:null,c&&(c.strId=i,c.searchedFrom=t,c.matchIndex=l,c.indices=u)}if(l===-1)continue;if(l===t)return U_(e,u);(a===-1||l<o)&&(a=e,o=l,s=u)}catch(e){if(this.options.forgiving)continue;throw e}}return a===-1?null:U_(a,s)}},G_=0;function K_(e){return{content:e,id:++G_}}function q_(e){if([...e].length!==1)throw Error(`Expected "${e}" to be a single code point`);return e.codePointAt(0)}function J_(e,t,n){return e.has(t)||e.set(t,n),e.get(t)}var Y_=new Set([`alnum`,`alpha`,`ascii`,`blank`,`cntrl`,`digit`,`graph`,`lower`,`print`,`punct`,`space`,`upper`,`word`,`xdigit`]),X_=String.raw;function Z_(e,t){if(e==null)throw Error(t??`Value expected`);return e}var Q_=X_`\[\^?`,$_=`c.? | C(?:-.?)?|${X_`[pP]\{(?:\^?[-\x20_]*[A-Za-z][-\x20\w]*\})?`}|${X_`x[89A-Fa-f]\p{AHex}(?:\\x[89A-Fa-f]\p{AHex})*`}|${X_`u(?:\p{AHex}{4})? | x\{[^\}]*\}? | x\p{AHex}{0,2}`}|${X_`o\{[^\}]*\}?`}|${X_`\d{1,3}`}`,ev=/[?*+][?+]?|\{(?:\d+(?:,\d*)?|,\d+)\}\??/,tv=new RegExp(X_`
34
+ \f\r "&'<=>\``.split(``)]],single:[[`&'`.split(``),`"&'\``.split(``)],[`\0&'`.split(``),`\0"&'\``.split(``)]],double:[[`"&`.split(``),`"&'\``.split(``)],[`\0"&`.split(``),`\0"&'\``.split(``)]]};function Rg(e,t,n,r){let i=r.schema,a=i.space!==`svg`&&r.settings.omitOptionalTags,o=i.space===`svg`?r.settings.closeEmptyElements:r.settings.voids.includes(e.tagName.toLowerCase()),s=[],c;i.space===`html`&&e.tagName===`svg`&&(r.schema=Dh);let l=zg(r,e.properties),u=r.all(i.space===`html`&&e.tagName===`template`?e.content:e);return r.schema=i,u&&(o=!1),(l||!a||!jg(e,t,n))&&(s.push(`<`,e.tagName,l?` `+l:``),o&&(i.space===`svg`||r.settings.closeSelfClosing)&&(c=l.charAt(l.length-1),(!r.settings.tightSelfClosing||c===`/`||c&&c!==`"`&&c!==`'`)&&s.push(` `),s.push(`/`)),s.push(`>`)),s.push(u),!o&&(!a||!hg(e,t,n))&&s.push(`</`+e.tagName+`>`),s.join(``)}function zg(e,t){let n=[],r=-1,i;if(t){for(i in t)if(t[i]!==null&&t[i]!==void 0){let r=Bg(e,i,t[i]);r&&n.push(r)}}for(;++r<n.length;){let t=e.settings.tightAttributes?n[r].charAt(n[r].length-1):void 0;r!==n.length-1&&t!==`"`&&t!==`'`&&(n[r]+=` `)}return n.join(``)}function Bg(e,t,n){let r=Ch(e.schema,t),i=e.settings.allowParseErrors&&e.schema.space===`html`?0:1,a=+!e.settings.allowDangerousCharacters,o=e.quote,s;if(r.overloadedBoolean&&(n===r.attribute||n===``)?n=!0:(r.boolean||r.overloadedBoolean)&&(typeof n!=`string`||n===r.attribute||n===``)&&(n=!!n),n==null||n===!1||typeof n==`number`&&Number.isNaN(n))return``;let c=Zh(r.attribute,Object.assign({},e.settings.characterReferences,{subset:Lg.name[i][a]}));return n===!0||(n=Array.isArray(n)?(r.commaSeparated?ig:ag)(n,{padLeft:!e.settings.tightCommaSeparatedLists}):String(n),e.settings.collapseEmptyAttributes&&!n)?c:(e.settings.preferUnquoted&&(s=Zh(n,Object.assign({},e.settings.characterReferences,{attribute:!0,subset:Lg.unquoted[i][a]}))),s!==n&&(e.settings.quoteSmart&&rg(n,o)>rg(n,e.alternative)&&(o=e.alternative),s=o+Zh(n,Object.assign({},e.settings.characterReferences,{subset:(o===`'`?Lg.single:Lg.double)[i][a],attribute:!0}))+o),c+(s&&`=`+s))}var Vg=[`<`,`&`];function Hg(e,t,n,r){return n&&n.type===`element`&&(n.tagName===`script`||n.tagName===`style`)?e.value:Zh(e.value,Object.assign({},r.settings.characterReferences,{subset:Vg}))}function Ug(e,t,n,r){return r.settings.allowDangerousHtml?e.value:Hg(e,t,n,r)}function Wg(e,t,n,r){return r.all(e)}var Gg=kh(`type`,{invalid:Kg,unknown:qg,handlers:{comment:tg,doctype:ng,element:Rg,raw:Ug,root:Wg,text:Hg}});function Kg(e){throw Error("Expected node, not `"+e+"`")}function qg(e){throw Error("Cannot compile unknown node `"+e.type+"`")}var Jg={},Yg={},Xg=[];function Zg(e,t){let n=t||Jg,r=n.quote||`"`,i=r===`"`?`'`:`"`;if(r!==`"`&&r!==`'`)throw Error("Invalid quote `"+r+"`, expected `'` or `\"`");return{one:Qg,all:$g,settings:{omitOptionalTags:n.omitOptionalTags||!1,allowParseErrors:n.allowParseErrors||!1,allowDangerousCharacters:n.allowDangerousCharacters||!1,quoteSmart:n.quoteSmart||!1,preferUnquoted:n.preferUnquoted||!1,tightAttributes:n.tightAttributes||!1,upperDoctype:n.upperDoctype||!1,tightDoctype:n.tightDoctype||!1,bogusComments:n.bogusComments||!1,tightCommaSeparatedLists:n.tightCommaSeparatedLists||!1,tightSelfClosing:n.tightSelfClosing||!1,collapseEmptyAttributes:n.collapseEmptyAttributes||!1,allowDangerousHtml:n.allowDangerousHtml||!1,voids:n.voids||Ym,characterReferences:n.characterReferences||Yg,closeSelfClosing:n.closeSelfClosing||!1,closeEmptyElements:n.closeEmptyElements||!1},schema:n.space===`svg`?Dh:Eh,quote:r,alternative:i}.one(Array.isArray(e)?{type:`root`,children:e}:e,void 0,void 0)}function Qg(e,t,n){return Gg(e,t,n,this)}function $g(e){let t=[],n=e&&e.children||Xg,r=-1;for(;++r<n.length;)t[r]=this.one(n[r],r,e);return t.join(``)}var e_=/\s+/g;function t_(e,t){if(!t)return e;e.properties||={},e.properties.class||=[],typeof e.properties.class==`string`&&(e.properties.class=e.properties.class.split(e_)),Array.isArray(e.properties.class)||(e.properties.class=[]);let n=Array.isArray(t)?t:t.split(e_);for(let t of n)t&&!e.properties.class.includes(t)&&e.properties.class.push(t);return e}function n_(e){let t=_m(e,!0).map(([e])=>e);function n(n){if(n===e.length)return{line:t.length-1,character:t.at(-1).length};let r=n,i=0;for(let e of t){if(r<e.length)break;r-=e.length,i++}return{line:i,character:r}}function r(e,n){let r=0;for(let n=0;n<e;n++)r+=t[n].length;return r+=n,r}return{lines:t,indexToPos:n,posToIndex:r}}var r_=[`color`,`background-color`];function i_(e,t){let n=0,r=[];for(let i of t)i>n&&r.push({...e,content:e.content.slice(n,i),offset:e.offset+n}),n=i;return n<e.content.length&&r.push({...e,content:e.content.slice(n),offset:e.offset+n}),r}function a_(e,t){let n=0,r=e.length;for(;n<r;){let i=n+(r-n>>1);e[i]<=t?n=i+1:r=i}return n}function o_(e,t){let n=[...t instanceof Set?t:new Set(t)].sort((e,t)=>e-t);return n.length?e.map(e=>e.flatMap(e=>{let t=e.offset+e.content.length,r=a_(n,e.offset),i=r;for(;i<n.length&&n[i]<t;)i++;if(r===i)return e;let a=n.slice(r,i);for(let t=0;t<a.length;t++)a[t]-=e.offset;return i_(e,a)})):e}function s_(e,t,n,r,i=`css-vars`){let a={content:e.content,explanation:e.explanation,offset:e.offset},o=t.map(t=>c_(e.variants[t])),s=new Set(o.flatMap(e=>Object.keys(e))),c={},l=(e,r)=>{let i=r===`color`?``:r===`background-color`?`-bg`:`-${r}`;return n+t[e]+(r===`color`?``:i)};return o.forEach((e,n)=>{for(let a of s){let s=e[a]||`inherit`;if(n===0&&r&&r_.includes(a)){if(r===`light-dark()`&&o.length>1){let e=t.findIndex(e=>e===`light`),r=t.findIndex(e=>e===`dark`);if(e===-1||r===-1)throw new Ef('When using `defaultColor: "light-dark()"`, you must provide both `light` and `dark` themes');let u=o[e][a]||`inherit`,d=o[r][a]||`inherit`;c[a]=`light-dark(${u}, ${d})`,i===`css-vars`&&(c[l(n,a)]=s)}else c[a]=s}else i===`css-vars`&&(c[l(n,a)]=s)}}),a.htmlStyle=c,a}function c_(e){let t={};if(e.color&&(t.color=e.color),e.bgColor&&(t[`background-color`]=e.bgColor),e.fontStyle){e.fontStyle&qf.Italic&&(t[`font-style`]=`italic`),e.fontStyle&qf.Bold&&(t[`font-weight`]=`bold`);let n=[];e.fontStyle&qf.Underline&&n.push(`underline`),e.fontStyle&qf.Strikethrough&&n.push(`line-through`),n.length&&(t[`text-decoration`]=n.join(` `))}return t}function l_(e){return typeof e==`string`?e:Object.entries(e).map(([e,t])=>`${e}:${t}`).join(`;`)}function u_(){let e=new WeakMap;function t(t){if(!e.has(t.meta)){let n=n_(t.source);function r(e){if(typeof e==`number`){if(e<0||e>t.source.length)throw new Ef(`Invalid decoration offset: ${e}. Code length: ${t.source.length}`);return{...n.indexToPos(e),offset:e}}{let t=n.lines[e.line];if(t===void 0)throw new Ef(`Invalid decoration position ${JSON.stringify(e)}. Lines length: ${n.lines.length}`);let r=e.character;if(r<0&&(r=t.length+r),r<0||r>t.length)throw new Ef(`Invalid decoration position ${JSON.stringify(e)}. Line ${e.line} length: ${t.length}`);return{...e,character:r,offset:n.posToIndex(e.line,r)}}}let i=(t.options.decorations||[]).map(e=>({...e,start:r(e.start),end:r(e.end)}));d_(i),e.set(t.meta,{decorations:i,converter:n,source:t.source})}return e.get(t.meta)}return{name:`shiki:decorations`,tokens(e){if(this.options.decorations?.length)return o_(e,t(this).decorations.flatMap(e=>[e.start.offset,e.end.offset]))},code(e){if(!this.options.decorations?.length)return;let n=t(this),r=[...e.children].filter(e=>e.type===`element`&&e.tagName===`span`);if(r.length!==n.converter.lines.length)throw new Ef(`Number of lines in code element (${r.length}) does not match the number of lines in the source (${n.converter.lines.length}). Failed to apply decorations.`);function i(e,t,n,i){let a=r[e],s=``,c=-1,l=-1;if(t===0&&(c=0),n===0&&(l=0),n===1/0&&(l=a.children.length),c===-1||l===-1)for(let e=0;e<a.children.length;e++)s+=f_(a.children[e]),c===-1&&s.length===t&&(c=e+1),l===-1&&s.length===n&&(l=e+1);if(c===-1)throw new Ef(`Failed to find start index for decoration ${JSON.stringify(i.start)}`);if(l===-1)throw new Ef(`Failed to find end index for decoration ${JSON.stringify(i.end)}`);let u=a.children.slice(c,l);if(!i.alwaysWrap&&u.length===a.children.length)o(a,i,`line`);else if(!i.alwaysWrap&&u.length===1&&u[0].type===`element`)o(u[0],i,`token`);else{let e={type:`element`,tagName:`span`,properties:{},children:u};o(e,i,`wrapper`),a.children.splice(c,u.length,e)}}function a(e,t){r[e]=o(r[e],t,`line`)}function o(e,t,n){let r=t.properties||{},i=t.transform||(e=>e);return e.tagName=t.tagName||`span`,e.properties={...e.properties,...r,class:e.properties.class},t.properties?.class&&t_(e,t.properties.class),e=i(e,n)||e,e}let s=[],c=n.decorations.sort((e,t)=>t.start.offset-e.start.offset||e.end.offset-t.end.offset);for(let e of c){let{start:t,end:n}=e;if(t.line===n.line)i(t.line,t.character,n.character,e);else if(t.line<n.line){i(t.line,t.character,1/0,e);for(let r=t.line+1;r<n.line;r++)s.unshift(()=>a(r,e));i(n.line,0,n.character,e)}}s.forEach(e=>e())}}}function d_(e){for(let t=0;t<e.length;t++){let n=e[t];if(n.start.offset>n.end.offset)throw new Ef(`Invalid decoration range: ${JSON.stringify(n.start)} - ${JSON.stringify(n.end)}`);for(let r=t+1;r<e.length;r++){let t=e[r],i=n.start.offset<=t.start.offset&&t.start.offset<n.end.offset,a=n.start.offset<t.end.offset&&t.end.offset<=n.end.offset,o=t.start.offset<=n.start.offset&&n.start.offset<t.end.offset,s=t.start.offset<n.end.offset&&n.end.offset<=t.end.offset;if(i||a||o||s){if(i&&a||o&&s||o&&n.start.offset===n.end.offset||a&&t.start.offset===t.end.offset)continue;throw new Ef(`Decorations ${JSON.stringify(n.start)} and ${JSON.stringify(t.start)} intersect.`)}}}}function f_(e){return e.type===`text`?e.value:e.type===`element`?e.children.map(f_).join(``):``}var p_=[u_()];function m_(e){let t=h_(e.transformers||[]);return[...t.pre,...t.normal,...t.post,...p_]}function h_(e){let t=[],n=[],r=[];for(let i of e)switch(i.enforce){case`pre`:t.push(i);break;case`post`:n.push(i);break;default:r.push(i)}return{pre:t,post:n,normal:r}}var g_=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`brightBlack`,`brightRed`,`brightGreen`,`brightYellow`,`brightBlue`,`brightMagenta`,`brightCyan`,`brightWhite`],__={1:`bold`,2:`dim`,3:`italic`,4:`underline`,7:`reverse`,8:`hidden`,9:`strikethrough`};function v_(e,t){let n=e.indexOf(`\x1B`,t);if(n!==-1&&e[n+1]===`[`){let t=e.indexOf(`m`,n);if(t!==-1)return{sequence:e.substring(n+2,t).split(`;`),startPosition:n,position:t+1}}return{position:e.length}}function y_(e){let t=e.shift();if(t===`2`){let t=e.splice(0,3).map(e=>Number.parseInt(e));return t.length!==3||t.some(e=>Number.isNaN(e))?void 0:{type:`rgb`,rgb:t}}if(t===`5`){let t=e.shift();if(t)return{type:`table`,index:Number(t)}}}function b_(e){let t=[];for(;e.length>0;){let n=e.shift();if(!n)continue;let r=Number.parseInt(n);if(!Number.isNaN(r)){if(r===0)t.push({type:`resetAll`});else if(r<=9)__[r]&&t.push({type:`setDecoration`,value:__[r]});else if(r<=29){let e=__[r-20];e&&(t.push({type:`resetDecoration`,value:e}),e===`dim`&&t.push({type:`resetDecoration`,value:`bold`}))}else if(r<=37)t.push({type:`setForegroundColor`,value:{type:`named`,name:g_[r-30]}});else if(r===38){let n=y_(e);n&&t.push({type:`setForegroundColor`,value:n})}else if(r===39)t.push({type:`resetForegroundColor`});else if(r<=47)t.push({type:`setBackgroundColor`,value:{type:`named`,name:g_[r-40]}});else if(r===48){let n=y_(e);n&&t.push({type:`setBackgroundColor`,value:n})}else r===49?t.push({type:`resetBackgroundColor`}):r===53?t.push({type:`setDecoration`,value:`overline`}):r===55?t.push({type:`resetDecoration`,value:`overline`}):r>=90&&r<=97?t.push({type:`setForegroundColor`,value:{type:`named`,name:g_[r-90+8]}}):r>=100&&r<=107&&t.push({type:`setBackgroundColor`,value:{type:`named`,name:g_[r-100+8]}})}}return t}function x_(){let e=null,t=null,n=new Set;return{parse(r){let i=[],a=0;do{let o=v_(r,a),s=o.sequence?r.substring(a,o.startPosition):r.substring(a);if(s.length>0&&i.push({value:s,foreground:e,background:t,decorations:new Set(n)}),o.sequence){let r=b_(o.sequence);for(let i of r)i.type===`resetAll`?(e=null,t=null,n.clear()):i.type===`resetForegroundColor`?e=null:i.type===`resetBackgroundColor`?t=null:i.type===`resetDecoration`&&n.delete(i.value);for(let i of r)i.type===`setForegroundColor`?e=i.value:i.type===`setBackgroundColor`?t=i.value:i.type===`setDecoration`&&n.add(i.value)}a=o.position}while(a<r.length);return i}}}var S_={black:`#000000`,red:`#bb0000`,green:`#00bb00`,yellow:`#bbbb00`,blue:`#0000bb`,magenta:`#ff00ff`,cyan:`#00bbbb`,white:`#eeeeee`,brightBlack:`#555555`,brightRed:`#ff5555`,brightGreen:`#00ff00`,brightYellow:`#ffff55`,brightBlue:`#5555ff`,brightMagenta:`#ff55ff`,brightCyan:`#55ffff`,brightWhite:`#ffffff`};function C_(e=S_){function t(t){return e[t]}function n(e){return`#${e.map(e=>Math.max(0,Math.min(e,255)).toString(16).padStart(2,`0`)).join(``)}`}let r;function i(){if(r)return r;r=[];for(let e=0;e<g_.length;e++)r.push(t(g_[e]));let 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++)r.push(n([e[t],e[i],e[a]]));let i=8;for(let e=0;e<24;e++,i+=10)r.push(n([i,i,i]));return r}function a(e){return i()[e]}function o(e){switch(e.type){case`named`:return t(e.name);case`rgb`:return n(e.rgb);case`table`:return a(e.index)}}return{value:o}}var w_=/#([0-9a-f]{3,8})/i,T_=/var\((--[\w-]+-ansi-[\w-]+)\)/,E_={black:`#000000`,red:`#cd3131`,green:`#0DBC79`,yellow:`#E5E510`,blue:`#2472C8`,magenta:`#BC3FBC`,cyan:`#11A8CD`,white:`#E5E5E5`,brightBlack:`#666666`,brightRed:`#F14C4C`,brightGreen:`#23D18B`,brightYellow:`#F5F543`,brightBlue:`#3B8EEA`,brightMagenta:`#D670D6`,brightCyan:`#29B8DB`,brightWhite:`#FFFFFF`};function D_(e,t,n){let r=cm(e,n),i=_m(t),a=C_(Object.fromEntries(g_.map(t=>{let n=`terminal.ansi${t[0].toUpperCase()}${t.substring(1)}`;return[t,e.colors?.[n]||E_[t]]}))),o=x_();return i.map(t=>o.parse(t[0]).map(n=>{let i,o;n.decorations.has(`reverse`)?(i=n.background?a.value(n.background):e.bg,o=n.foreground?a.value(n.foreground):e.fg):(i=n.foreground?a.value(n.foreground):e.fg,o=n.background?a.value(n.background):void 0),i=lm(i,r),o=lm(o,r),n.decorations.has(`dim`)&&(i=O_(i));let s=qf.None;return n.decorations.has(`bold`)&&(s|=qf.Bold),n.decorations.has(`italic`)&&(s|=qf.Italic),n.decorations.has(`underline`)&&(s|=qf.Underline),n.decorations.has(`strikethrough`)&&(s|=qf.Strikethrough),{content:n.value,offset:t[1],color:i,bgColor:o,fontStyle:s}}))}function O_(e){let t=e.match(w_);if(t){let e=t[1];if(e.length===8){let t=Math.round(Number.parseInt(e.slice(6,8),16)/2).toString(16).padStart(2,`0`);return`#${e.slice(0,6)}${t}`}if(e.length===6)return`#${e}80`;if(e.length===4){let t=e[0],n=e[1],r=e[2],i=e[3];return`#${t}${t}${n}${n}${r}${r}${Math.round(Number.parseInt(`${i}${i}`,16)/2).toString(16).padStart(2,`0`)}`}if(e.length===3){let t=e[0],n=e[1],r=e[2];return`#${t}${t}${n}${n}${r}${r}80`}}let n=e.match(T_);return n?`var(${n[1]}-dim)`:e}function k_(e,t,n={}){let r=e.resolveLangAlias(n.lang||`text`),{theme:i=e.getLoadedThemes()[0]}=n;if(!fm(r)&&!mm(i)&&r===`ansi`){let{theme:r}=e.setTheme(i);return D_(r,t,n)}return Rm(e,t,n)}function A_(e,t,n){let r,i,a,o,s,c;if(`themes`in n){let{defaultColor:l=`light`,cssVariablePrefix:u=`--shiki-`,colorsRendering:d=`css-vars`}=n,f=Object.entries(n.themes).filter(e=>e[1]).map(e=>({color:e[0],theme:e[1]})).sort((e,t)=>e.color===l?-1:+(t.color===l));if(f.length===0)throw new Ef("`themes` option must not be empty");let p=qm(e,t,n,k_);if(c=Mm(p),l&&l!==`light-dark()`&&!f.some(e=>e.color===l))throw new Ef(`\`themes\` option must contain the defaultColor key \`${l}\``);let m=f.map(t=>e.getTheme(t.theme)),h=f.map(e=>e.color);a=p.map(e=>e.map(e=>s_(e,h,u,l,d))),c&&jm(a,c);let g=f.map(e=>cm(e.theme,n));i=j_(f,m,g,u,l,`fg`,d),r=j_(f,m,g,u,l,`bg`,d),o=`shiki-themes ${m.map(e=>e.name).join(` `)}`,s=l?void 0:[i,r].join(`;`)}else if(`theme`in n){let s=cm(n.theme,n);a=k_(e,t,n);let l=e.getTheme(n.theme);r=lm(l.bg,s),i=lm(l.fg,s),o=l.name,c=Mm(a)}else throw new Ef("Invalid options, either `theme` or `themes` must be provided");return{tokens:a,fg:i,bg:r,themeName:o,rootStyle:s,grammarState:c}}function j_(e,t,n,r,i,a,o){return e.map((s,c)=>{let l=lm(t[c][a],n[c])||`inherit`,u=`${r+s.color}${a===`bg`?`-bg`:``}:${l}`;if(c===0&&i){if(i===`light-dark()`&&e.length>1){let r=e.findIndex(e=>e.color===`light`),i=e.findIndex(e=>e.color===`dark`);if(r===-1||i===-1)throw new Ef('When using `defaultColor: "light-dark()"`, you must provide both `light` and `dark` themes');return`light-dark(${lm(t[r][a],n[r])||`inherit`}, ${lm(t[i][a],n[i])||`inherit`});${u}`}return l}return o===`css-vars`?u:null}).filter(e=>!!e).join(`;`)}var M_=/^\s+$/,N_=/^(\s*)(.*?)(\s*)$/;function P_(e,t,n,r={meta:{},options:n,codeToHast:(t,n)=>P_(e,t,n),codeToTokens:(t,n)=>A_(e,t,n)}){let i=t;for(let e of m_(n))i=e.preprocess?.call(r,i,n)||i;let{tokens:a,fg:o,bg:s,themeName:c,rootStyle:l,grammarState:u}=A_(e,i,n),{mergeWhitespaces:d=!0,mergeSameStyleTokens:f=!1}=n;d===!0?a=I_(a):d===`never`&&(a=L_(a)),f&&(a=R_(a));let p={...r,get source(){return i}};for(let e of m_(n))a=e.tokens?.call(p,a)||a;return F_(a,{...n,fg:o,bg:s,themeName:c,rootStyle:n.rootStyle===!1?!1:n.rootStyle??l},p,u)}function F_(e,t,n,r=Mm(e)){let i=m_(t),a=[],o={type:`root`,children:[]},{structure:s=`classic`,tabindex:c=`0`}=t,l={class:`shiki ${t.themeName||``}`};t.rootStyle!==!1&&(l.style=t.rootStyle==null?`background-color:${t.bg};color:${t.fg}`:t.rootStyle),c!==!1&&c!=null&&(l.tabindex=c.toString());for(let[e,n]of Object.entries(t.meta||{}))e.startsWith(`_`)||(l[e]=n);let u={type:`element`,tagName:`pre`,properties:l,children:[],data:t.data},d={type:`element`,tagName:`code`,properties:{},children:a},f=[],p={...n,structure:s,addClassToHast:t_,get source(){return n.source},get tokens(){return e},get options(){return t},get root(){return o},get pre(){return u},get code(){return d},get lines(){return f}};if(e.forEach((e,t)=>{t&&(s===`inline`?o.children.push({type:`element`,tagName:`br`,properties:{},children:[]}):s===`classic`&&a.push({type:`text`,value:`
35
+ `}));let n={type:`element`,tagName:`span`,properties:{class:`line`},children:[]},r=0;for(let a of e){let e={type:`element`,tagName:`span`,properties:{...a.htmlAttrs},children:[{type:`text`,value:a.content}]},c=l_(a.htmlStyle||c_(a));c&&(e.properties.style=c);for(let o of i)e=o?.span?.call(p,e,t+1,r,n,a)||e;s===`inline`?o.children.push(e):s===`classic`&&n.children.push(e),r+=a.content.length}if(s===`classic`){for(let e of i)n=e?.line?.call(p,n,t+1)||n;f.push(n),a.push(n)}else s===`inline`&&f.push(n)}),s===`classic`){for(let e of i)d=e?.code?.call(p,d)||d;u.children.push(d);for(let e of i)u=e?.pre?.call(p,u)||u;o.children.push(u)}else if(s===`inline`){let e=[],t={type:`element`,tagName:`span`,properties:{class:`line`},children:[]};for(let n of o.children)n.type===`element`&&n.tagName===`br`?(e.push(t),t={type:`element`,tagName:`span`,properties:{class:`line`},children:[]}):(n.type===`element`||n.type===`text`)&&t.children.push(n);e.push(t);let n={type:`element`,tagName:`code`,properties:{},children:e};for(let e of i)n=e?.code?.call(p,n)||n;o.children=[];for(let e=0;e<n.children.length;e++){e>0&&o.children.push({type:`element`,tagName:`br`,properties:{},children:[]});let t=n.children[e];t.type===`element`&&o.children.push(...t.children)}}let m=o;for(let e of i)m=e?.root?.call(p,m)||m;return r&&jm(m,r),m}function I_(e){return e.map(e=>{let t=[],n=``,r;return e.forEach((i,a)=>{let o=!(i.fontStyle&&(i.fontStyle&qf.Underline||i.fontStyle&qf.Strikethrough));o&&M_.test(i.content)&&e[a+1]?(r===void 0&&(r=i.offset),n+=i.content):n?(o?t.push({...i,offset:r,content:n+i.content}):t.push({content:n,offset:r},i),r=void 0,n=``):t.push(i)}),t})}function L_(e){return e.map(e=>e.flatMap(e=>{if(M_.test(e.content))return e;let t=e.content.match(N_);if(!t)return e;let[,n,r,i]=t;if(!n&&!i)return e;let a=[{...e,offset:e.offset+n.length,content:r}];return n&&a.unshift({content:n,offset:e.offset}),i&&a.push({content:i,offset:e.offset+n.length+r.length}),a}))}function R_(e){return e.map(e=>{let t=[];for(let n of e){if(t.length===0){t.push({...n});continue}let e=t.at(-1),r=l_(e.htmlStyle||c_(e)),i=l_(n.htmlStyle||c_(n)),a=e.fontStyle&&(e.fontStyle&qf.Underline||e.fontStyle&qf.Strikethrough),o=n.fontStyle&&(n.fontStyle&qf.Underline||n.fontStyle&qf.Strikethrough);!a&&!o&&r===i?e.content+=n.content:t.push({...n})}return t})}var z_=Zg;function B_(e,t,n){let r={meta:{},options:n,codeToHast:(t,n)=>P_(e,t,n),codeToTokens:(t,n)=>A_(e,t,n)},i=z_(P_(e,t,n,r));for(let e of m_(n))i=e.postprocess?.call(r,i,n)||i;return i}async function V_(e){let t=await km(e);return{getLastGrammarState:(...e)=>zm(t,...e),codeToTokensBase:(e,n)=>k_(t,e,n),codeToTokensWithThemes:(e,n)=>qm(t,e,n),codeToTokens:(e,n)=>A_(t,e,n),codeToHast:(e,n)=>P_(t,e,n),codeToHtml:(e,n)=>B_(t,e,n),getBundledLanguages:()=>({}),getBundledThemes:()=>({}),...t,getInternalContext:()=>t}}var H_=4294967295;function U_(e){return!e.sticky&&!e.rawOptions?.strategy}function W_(e,t){return{index:e,captureIndices:t.map(e=>e==null?{start:H_,end:H_,length:0}:{start:e[0],end:e[1],length:e[1]-e[0]})}}var G_=class{patterns;options;regexps;lastSearches;constructor(e,t={}){this.patterns=e,this.options=t;let{forgiving:n=!1,cache:r,regexConstructor:i}=t;if(!i)throw Error("Option `regexConstructor` is not provided");this.regexps=e.map(e=>{if(typeof e!=`string`)return e;let t=r?.get(e);if(t){if(t instanceof RegExp)return t;if(n)return null;throw t}try{let t=i(e);return r?.set(e,t),t}catch(t){if(r?.set(e,t),n)return null;throw t}}),this.lastSearches=this.regexps.map(e=>e&&U_(e)?{strId:0,searchedFrom:0,matchIndex:-1,indices:null}:null)}findNextMatchSync(e,t,n){let r=typeof e==`string`?e:e.content,i=typeof e==`string`?0:e.id||0,a=-1,o=0,s=null;for(let e=0;e<this.regexps.length;e++){let n=this.regexps[e];if(n)try{let c=i?this.lastSearches[e]:null,l,u;if(c&&c.strId===i&&c.searchedFrom<=t&&(c.matchIndex===-1||c.matchIndex>=t))l=c.matchIndex,u=c.indices;else{n.lastIndex=t;let e=n.exec(r);l=e?e.index:-1,u=e?e.indices:null,c&&(c.strId=i,c.searchedFrom=t,c.matchIndex=l,c.indices=u)}if(l===-1)continue;if(l===t)return W_(e,u);(a===-1||l<o)&&(a=e,o=l,s=u)}catch(e){if(this.options.forgiving)continue;throw e}}return a===-1?null:W_(a,s)}},K_=0;function q_(e){return{content:e,id:++K_}}function J_(e){if([...e].length!==1)throw Error(`Expected "${e}" to be a single code point`);return e.codePointAt(0)}function Y_(e,t,n){return e.has(t)||e.set(t,n),e.get(t)}var X_=new Set([`alnum`,`alpha`,`ascii`,`blank`,`cntrl`,`digit`,`graph`,`lower`,`print`,`punct`,`space`,`upper`,`word`,`xdigit`]),Z_=String.raw;function Q_(e,t){if(e==null)throw Error(t??`Value expected`);return e}var $_=Z_`\[\^?`,ev=`c.? | C(?:-.?)?|${Z_`[pP]\{(?:\^?[-\x20_]*[A-Za-z][-\x20\w]*\})?`}|${Z_`x[89A-Fa-f]\p{AHex}(?:\\x[89A-Fa-f]\p{AHex})*`}|${Z_`u(?:\p{AHex}{4})? | x\{[^\}]*\}? | x\p{AHex}{0,2}`}|${Z_`o\{[^\}]*\}?`}|${Z_`\d{1,3}`}`,tv=/[?*+][?+]?|\{(?:\d+(?:,\d*)?|,\d+)\}\??/,nv=new RegExp(Z_`
36
36
  \\ (?:
37
- ${$_}
37
+ ${ev}
38
38
  | [gk]<[^>]*>?
39
39
  | [gk]'[^']*'?
40
40
  | .
@@ -51,20 +51,20 @@ WARNING: This link could potentially be dangerous`)){let e=window.open();if(e){t
51
51
  )?
52
52
  | \*[^\)]*\)?
53
53
  )?
54
- | (?:${ev.source})+
55
- | ${Q_}
54
+ | (?:${tv.source})+
55
+ | ${$_}
56
56
  | .
57
- `.replace(/\s+/g,``),`gsu`),nv=new RegExp(X_`
57
+ `.replace(/\s+/g,``),`gsu`),rv=new RegExp(Z_`
58
58
  \\ (?:
59
- ${$_}
59
+ ${ev}
60
60
  | .
61
61
  )
62
62
  | \[:(?:\^?\p{Alpha}+|\^):\]
63
- | ${Q_}
63
+ | ${$_}
64
64
  | &&
65
65
  | .
66
- `.replace(/\s+/g,``),`gsu`);function rv(e,t={}){let n={flags:``,...t,rules:{captureGroup:!1,singleline:!1,...t.rules}};if(typeof e!=`string`)throw Error(`String expected as pattern`);let r=Nv(n.flags),i=[r.extended],a={captureGroup:n.rules.captureGroup,getCurrentModX(){return i.at(-1)},numOpenGroups:0,popModX(){i.pop()},pushModX(e){i.push(e)},replaceCurrentModX(e){i[i.length-1]=e},singleline:n.rules.singleline},o=[],s;for(tv.lastIndex=0;s=tv.exec(e);){let t=iv(a,e,s[0],tv.lastIndex);t.tokens?o.push(...t.tokens):t.token&&o.push(t.token),t.lastIndex!==void 0&&(tv.lastIndex=t.lastIndex)}let c=[],l=0;o.filter(e=>e.type===`GroupOpen`).forEach(e=>{e.kind===`capturing`?e.number=++l:e.raw===`(`&&c.push(e)}),l||c.forEach((e,t)=>{e.kind=`capturing`,e.number=t+1});let u=l||c.length;return{tokens:o.map(e=>e.type===`EscapedNumber`?Fv(e,u):e).flat(),flags:r}}function iv(e,t,n,r){let[i,a]=n;if(n===`[`||n===`[^`){let e=av(t,n,r);return{tokens:e.tokens,lastIndex:e.lastIndex}}if(i===`\\`){if(`AbBGyYzZ`.includes(a))return{token:lv(n,n)};if(/^\\g[<']/.test(n)){if(!/^\\g(?:<[^>]+>|'[^']+')$/.test(n))throw Error(`Invalid group name "${n}"`);return{token:Cv(n)}}if(/^\\k[<']/.test(n)){if(!/^\\k(?:<[^>]+>|'[^']+')$/.test(n))throw Error(`Invalid group name "${n}"`);return{token:uv(n)}}if(a===`K`)return{token:_v(`keep`,n)};if(a===`N`||a===`R`)return{token:gv(`newline`,n,{negate:a===`N`})};if(a===`O`)return{token:gv(`any`,n)};if(a===`X`)return{token:gv(`text_segment`,n)};let e=sv(n,{inCharClass:!1});return Array.isArray(e)?{tokens:e}:{token:e}}if(i===`(`){if(a===`*`)return{token:Ov(n)};if(n===`(?{`)throw Error(`Unsupported callout "${n}"`);if(n.startsWith(`(?#`)){if(t[r]!==`)`)throw Error(`Unclosed comment group "(?#"`);return{lastIndex:r+1}}if(/^\(\?[-imx]+[:)]$/.test(n))return{token:Dv(n,e)};if(e.pushModX(e.getCurrentModX()),e.numOpenGroups++,n===`(`&&!e.captureGroup||n===`(?:`)return{token:bv(`group`,n)};if(n===`(?>`)return{token:bv(`atomic`,n)};if(n===`(?=`||n===`(?!`||n===`(?<=`||n===`(?<!`)return{token:bv(n[2]===`<`?`lookbehind`:`lookahead`,n,{negate:n.endsWith(`!`)})};if(n===`(`&&e.captureGroup||n.startsWith(`(?<`)&&n.endsWith(`>`)||n.startsWith(`(?'`)&&n.endsWith(`'`))return{token:bv(`capturing`,n,{...n!==`(`&&{name:n.slice(3,-1)}})};if(n.startsWith(`(?~`)){if(n===`(?~|`)throw Error(`Unsupported absence function kind "${n}"`);return{token:bv(`absence_repeater`,n)}}throw Error(n===`(?(`?`Unsupported conditional "${n}"`:`Invalid or unsupported group option "${n}"`)}if(n===`)`){if(e.popModX(),e.numOpenGroups--,e.numOpenGroups<0)throw Error(`Unmatched ")"`);return{token:yv(n)}}if(e.getCurrentModX()){if(n===`#`){let e=t.indexOf(`
67
- `,r);return{lastIndex:e===-1?t.length:e}}if(/^\s$/.test(n)){let e=/\s+/y;return e.lastIndex=r,{lastIndex:e.exec(t)?e.lastIndex:r}}}return n===`.`?{token:gv(`dot`,n)}:n===`^`||n===`$`?{token:lv(e.singleline?{"^":X_`\A`,$:X_`\Z`}[n]:n,n)}:n===`|`?{token:cv(n)}:ev.test(n)?{tokens:Iv(n)}:{token:dv(q_(n),n)}}function av(e,t,n){let r=[hv(t[1]===`^`,t)],i=1,a;for(nv.lastIndex=n;a=nv.exec(e);){let e=a[0];if(e[0]===`[`&&e[1]!==`:`)i++,r.push(hv(e[1]===`^`,e));else if(e===`]`){if(r.at(-1).type===`CharacterClassOpen`)r.push(dv(93,e));else if(i--,r.push(fv(e)),!i)break}else{let t=ov(e);Array.isArray(t)?r.push(...t):r.push(t)}}return{tokens:r,lastIndex:nv.lastIndex||e.length}}function ov(e){if(e[0]===`\\`)return sv(e,{inCharClass:!0});if(e[0]===`[`){let t=/\[:(?<negate>\^?)(?<name>[a-z]+):\]/.exec(e);if(!t||!Y_.has(t.groups.name))throw Error(`Invalid POSIX class "${e}"`);return gv(`posix`,e,{value:t.groups.name,negate:!!t.groups.negate})}return e===`-`?pv(e):e===`&&`?mv(e):dv(q_(e),e)}function sv(e,{inCharClass:t}){let n=e[1];if(n===`c`||n===`C`)return Ev(e);if(`dDhHsSwW`.includes(n))return Av(e);if(e.startsWith(X_`\o{`))throw Error(`Incomplete, invalid, or unsupported octal code point "${e}"`);if(/^\\[pP]\{/.test(e)){if(e.length===3)throw Error(`Incomplete or invalid Unicode property "${e}"`);return jv(e)}if(/^\\x[89A-Fa-f]\p{AHex}/u.test(e))try{let t=e.split(/\\x/).slice(1).map(e=>parseInt(e,16)),n=new TextDecoder(`utf-8`,{ignoreBOM:!0,fatal:!0}).decode(new Uint8Array(t)),r=new TextEncoder;return[...n].map(e=>{let t=[...r.encode(e)].map(e=>`\\x${e.toString(16)}`).join(``);return dv(q_(e),t)})}catch{throw Error(`Multibyte code "${e}" incomplete or invalid in Oniguruma`)}if(n===`u`||n===`x`)return dv(Pv(e),e);if(Tv.has(n))return dv(Tv.get(n),e);if(/\d/.test(n))return vv(t,e);if(e===`\\`)throw Error(X_`Incomplete escape "\"`);if(n===`M`)throw Error(`Unsupported meta "${e}"`);if([...e].length===2)return dv(e.codePointAt(1),e);throw Error(`Unexpected escape "${e}"`)}function cv(e){return{type:`Alternator`,raw:e}}function lv(e,t){return{type:`Assertion`,kind:e,raw:t}}function uv(e){return{type:`Backreference`,raw:e}}function dv(e,t){return{type:`Character`,value:e,raw:t}}function fv(e){return{type:`CharacterClassClose`,raw:e}}function pv(e){return{type:`CharacterClassHyphen`,raw:e}}function mv(e){return{type:`CharacterClassIntersector`,raw:e}}function hv(e,t){return{type:`CharacterClassOpen`,negate:e,raw:t}}function gv(e,t,n={}){return{type:`CharacterSet`,kind:e,...n,raw:t}}function _v(e,t,n={}){return e===`keep`?{type:`Directive`,kind:e,raw:t}:{type:`Directive`,kind:e,flags:Z_(n.flags),raw:t}}function vv(e,t){return{type:`EscapedNumber`,inCharClass:e,raw:t}}function yv(e){return{type:`GroupClose`,raw:e}}function bv(e,t,n={}){return{type:`GroupOpen`,kind:e,...n,raw:t}}function xv(e,t,n,r){return{type:`NamedCallout`,kind:e,tag:t,arguments:n,raw:r}}function Sv(e,t,n,r){return{type:`Quantifier`,kind:e,min:t,max:n,raw:r}}function Cv(e){return{type:`Subroutine`,raw:e}}var wv=new Set([`COUNT`,`CMP`,`ERROR`,`FAIL`,`MAX`,`MISMATCH`,`SKIP`,`TOTAL_COUNT`]),Tv=new Map([[`a`,7],[`b`,8],[`e`,27],[`f`,12],[`n`,10],[`r`,13],[`t`,9],[`v`,11]]);function Ev(e){let t=e[1]===`c`?e[2]:e[3];if(!t||!/[A-Za-z]/.test(t))throw Error(`Unsupported control character "${e}"`);return dv(q_(t.toUpperCase())-64,e)}function Dv(e,t){let{on:n,off:r}=/^\(\?(?<on>[imx]*)(?:-(?<off>[-imx]*))?/.exec(e).groups;r??=``;let i=(t.getCurrentModX()||n.includes(`x`))&&!r.includes(`x`),a=Mv(n),o=Mv(r),s={};if(a&&(s.enable=a),o&&(s.disable=o),e.endsWith(`)`))return t.replaceCurrentModX(i),_v(`flags`,e,{flags:s});if(e.endsWith(`:`))return t.pushModX(i),t.numOpenGroups++,bv(`group`,e,{...(a||o)&&{flags:s}});throw Error(`Unexpected flag modifier "${e}"`)}function Ov(e){let t=/\(\*(?<name>[A-Za-z_]\w*)?(?:\[(?<tag>(?:[A-Za-z_]\w*)?)\])?(?:\{(?<args>[^}]*)\})?\)/.exec(e);if(!t)throw Error(`Incomplete or invalid named callout "${e}"`);let{name:n,tag:r,args:i}=t.groups;if(!n)throw Error(`Invalid named callout "${e}"`);if(r===``)throw Error(`Named callout tag with empty value not allowed "${e}"`);let a=i?i.split(`,`).filter(e=>e!==``).map(e=>/^[+-]?\d+$/.test(e)?+e:e):[],[o,s,c]=a,l=wv.has(n)?n.toLowerCase():`custom`;switch(l){case`fail`:case`mismatch`:case`skip`:if(a.length>0)throw Error(`Named callout arguments not allowed "${a}"`);break;case`error`:if(a.length>1)throw Error(`Named callout allows only one argument "${a}"`);if(typeof o==`string`)throw Error(`Named callout argument must be a number "${o}"`);break;case`max`:if(!a.length||a.length>2)throw Error(`Named callout must have one or two arguments "${a}"`);if(typeof o==`string`&&!/^[A-Za-z_]\w*$/.test(o))throw Error(`Named callout argument one must be a tag or number "${o}"`);if(a.length===2&&(typeof s==`number`||!/^[<>X]$/.test(s)))throw Error(`Named callout optional argument two must be '<', '>', or 'X' "${s}"`);break;case`count`:case`total_count`:if(a.length>1)throw Error(`Named callout allows only one argument "${a}"`);if(a.length===1&&(typeof o==`number`||!/^[<>X]$/.test(o)))throw Error(`Named callout optional argument must be '<', '>', or 'X' "${o}"`);break;case`cmp`:if(a.length!==3)throw Error(`Named callout must have three arguments "${a}"`);if(typeof o==`string`&&!/^[A-Za-z_]\w*$/.test(o))throw Error(`Named callout argument one must be a tag or number "${o}"`);if(typeof s==`number`||!/^(?:[<>!=]=|[<>])$/.test(s))throw Error(`Named callout argument two must be '==', '!=', '>', '<', '>=', or '<=' "${s}"`);if(typeof c==`string`&&!/^[A-Za-z_]\w*$/.test(c))throw Error(`Named callout argument three must be a tag or number "${c}"`);break;case`custom`:throw Error(`Undefined callout name "${n}"`);default:throw Error(`Unexpected named callout kind "${l}"`)}return xv(l,r??null,i?.split(`,`)??null,e)}function kv(e){let t=null,n,r;if(e[0]===`{`){let{minStr:i,maxStr:a}=/^\{(?<minStr>\d*)(?:,(?<maxStr>\d*))?/.exec(e).groups,o=1e5;if(+i>o||a&&+a>o)throw Error(`Quantifier value unsupported in Oniguruma`);if(n=+i,r=a===void 0?+i:a===``?1/0:+a,n>r&&(t=`possessive`,[n,r]=[r,n]),e.endsWith(`?`)){if(t===`possessive`)throw Error(`Unsupported possessive interval quantifier chain with "?"`);t=`lazy`}else t||=`greedy`}else n=+(e[0]===`+`),r=e[0]===`?`?1:1/0,t=e[1]===`+`?`possessive`:e[1]===`?`?`lazy`:`greedy`;return Sv(t,n,r,e)}function Av(e){let t=e[1].toLowerCase();return gv({d:`digit`,h:`hex`,s:`space`,w:`word`}[t],e,{negate:e[1]!==t})}function jv(e){let{p:t,neg:n,value:r}=/^\\(?<p>[pP])\{(?<neg>\^?)(?<value>[^}]+)/.exec(e).groups;return gv(`property`,e,{value:r,negate:t===`P`&&!n||t===`p`&&!!n})}function Mv(e){let t={};return e.includes(`i`)&&(t.ignoreCase=!0),e.includes(`m`)&&(t.dotAll=!0),e.includes(`x`)&&(t.extended=!0),Object.keys(t).length?t:null}function Nv(e){let t={ignoreCase:!1,dotAll:!1,extended:!1,digitIsAscii:!1,posixIsAscii:!1,spaceIsAscii:!1,wordIsAscii:!1,textSegmentMode:null};for(let n=0;n<e.length;n++){let r=e[n];if(!`imxDPSWy`.includes(r))throw Error(`Invalid flag "${r}"`);if(r===`y`){if(!/^y{[gw]}/.test(e.slice(n)))throw Error(`Invalid or unspecified flag "y" mode`);t.textSegmentMode=e[n+2]===`g`?`grapheme`:`word`,n+=3}else t[{i:`ignoreCase`,m:`dotAll`,x:`extended`,D:`digitIsAscii`,P:`posixIsAscii`,S:`spaceIsAscii`,W:`wordIsAscii`}[r]]=!0}return t}function Pv(e){if(/^(?:\\u(?!\p{AHex}{4})|\\x(?!\p{AHex}{1,2}|\{\p{AHex}{1,8}\}))/u.test(e))throw Error(`Incomplete or invalid escape "${e}"`);let t=e[2]===`{`?/^\\x\{\s*(?<hex>\p{AHex}+)/u.exec(e).groups.hex:e.slice(2);return parseInt(t,16)}function Fv(e,t){let{raw:n,inCharClass:r}=e,i=n.slice(1);if(!r&&(i!==`0`&&i.length===1||i[0]!==`0`&&+i<=t))return[uv(n)];let a=[],o=i.match(/^[0-7]+|\d/g);for(let e=0;e<o.length;e++){let t=o[e],r;if(e===0&&t!==`8`&&t!==`9`){if(r=parseInt(t,8),r>127)throw Error(X_`Octal encoded byte above 177 unsupported "${n}"`)}else r=q_(t);a.push(dv(r,(e===0?`\\`:``)+t))}return a}function Iv(e){let t=[],n=new RegExp(ev,`gy`),r;for(;r=n.exec(e);){let e=r[0];if(e[0]===`{`){let r=/^\{(?<min>\d+),(?<max>\d+)\}\??$/.exec(e);if(r){let{min:i,max:a}=r.groups;if(+i>+a&&e.endsWith(`?`)){n.lastIndex--,t.push(kv(e.slice(0,-1)));continue}}}t.push(kv(e))}return t}function Lv(e,t){if(!Array.isArray(e.body))throw Error(`Expected node with body array`);if(e.body.length!==1)return!1;let n=e.body[0];return!t||Object.keys(t).every(e=>t[e]===n[e])}function Rv(e){return zv.has(e.type)}var zv=new Set([`AbsenceFunction`,`Backreference`,`CapturingGroup`,`Character`,`CharacterClass`,`CharacterSet`,`Group`,`Quantifier`,`Subroutine`]);function Bv(e,t={}){let n={flags:``,normalizeUnknownPropertyNames:!1,skipBackrefValidation:!1,skipLookbehindValidation:!1,skipPropertyNameValidation:!1,unicodePropertyMap:null,...t,rules:{captureGroup:!1,singleline:!1,...t.rules}},r=rv(e,{flags:n.flags,rules:{captureGroup:n.rules.captureGroup,singleline:n.rules.singleline}}),i=(e,t)=>{let n=r.tokens[a.nextIndex];switch(a.parent=e,a.nextIndex++,n.type){case`Alternator`:return Xv();case`Assertion`:return Vv(n);case`Backreference`:return Hv(n,a);case`Character`:return ey(n.value,{useLastValid:!!t.isCheckingRangeEnd});case`CharacterClassHyphen`:return Uv(n,a,t);case`CharacterClassOpen`:return Wv(n,a,t);case`CharacterSet`:return Gv(n,a);case`Directive`:return iy(n.kind,{flags:n.flags});case`GroupOpen`:return Kv(n,a,t);case`NamedCallout`:return cy(n.kind,n.tag,n.arguments);case`Quantifier`:return qv(n,a);case`Subroutine`:return Jv(n,a);default:throw Error(`Unexpected token type "${n.type}"`)}},a={capturingGroups:[],hasNumberedRef:!1,namedGroupsByName:new Map,nextIndex:0,normalizeUnknownPropertyNames:n.normalizeUnknownPropertyNames,parent:null,skipBackrefValidation:n.skipBackrefValidation,skipLookbehindValidation:n.skipLookbehindValidation,skipPropertyNameValidation:n.skipPropertyNameValidation,subroutines:[],tokens:r.tokens,unicodePropertyMap:n.unicodePropertyMap,walk:i},o=dy(ay(r.flags)),s=o.body[0];for(;a.nextIndex<r.tokens.length;){let e=i(s,{});e.type===`Alternative`?(o.body.push(e),s=e):s.body.push(e)}let{capturingGroups:c,hasNumberedRef:l,namedGroupsByName:u,subroutines:d}=a;if(l&&u.size&&!n.rules.captureGroup)throw Error(`Numbered backref/subroutine not allowed when using named capture`);for(let{ref:e}of d)if(typeof e==`number`){if(e>c.length)throw Error(`Subroutine uses a group number that's not defined`);e&&(c[e-1].isSubroutined=!0)}else if(u.has(e)){if(u.get(e).length>1)throw Error(X_`Subroutine uses a duplicate group name "\g<${e}>"`);u.get(e)[0].isSubroutined=!0}else throw Error(X_`Subroutine uses a group name that's not defined "\g<${e}>"`);return o}function Vv({kind:e}){return Zv(Z_({"^":`line_start`,$:`line_end`,"\\A":`string_start`,"\\b":`word_boundary`,"\\B":`word_boundary`,"\\G":`search_start`,"\\y":`text_segment_boundary`,"\\Y":`text_segment_boundary`,"\\z":`string_end`,"\\Z":`string_end_newline`}[e],`Unexpected assertion kind "${e}"`),{negate:e===X_`\B`||e===X_`\Y`})}function Hv({raw:e},t){let n=/^\\k[<']/.test(e),r=n?e.slice(3,-1):e.slice(1),i=(n,r=!1)=>{let i=t.capturingGroups.length,a=!1;if(n>i){if(t.skipBackrefValidation)a=!0;else throw Error(`Not enough capturing groups defined to the left "${e}"`)}return t.hasNumberedRef=!0,Qv(r?i+1-n:n,{orphan:a})};if(n){let n=/^(?<sign>-?)0*(?<num>[1-9]\d*)$/.exec(r);if(n)return i(+n.groups.num,!!n.groups.sign);if(/[-+]/.test(r))throw Error(`Invalid backref name "${e}"`);if(!t.namedGroupsByName.has(r))throw Error(`Group name not defined to the left "${e}"`);return Qv(r)}return i(+r)}function Uv(e,t,n){let{tokens:r,walk:i}=t,a=t.parent,o=a.body.at(-1),s=r[t.nextIndex];if(!n.isCheckingRangeEnd&&o&&o.type!==`CharacterClass`&&o.type!==`CharacterClassRange`&&s&&s.type!==`CharacterClassOpen`&&s.type!==`CharacterClassClose`&&s.type!==`CharacterClassIntersector`){let e=i(a,{...n,isCheckingRangeEnd:!0});if(o.type===`Character`&&e.type===`Character`)return a.body.pop(),ny(o,e);throw Error(`Invalid character class range`)}return ey(q_(`-`))}function Wv({negate:e},t,n){let{tokens:r,walk:i}=t,a=[ty()],o=r[t.nextIndex],s=Sy(o);for(;s.type!==`CharacterClassClose`;){if(s.type===`CharacterClassIntersector`)a.push(ty()),t.nextIndex++;else{let e=a.at(-1);e.body.push(i(e,n))}s=Sy(r[t.nextIndex],o)}let c=ty({negate:e});return a.length===1?c.body=a[0].body:(c.kind=`intersection`,c.body=a.map(e=>e.body.length===1?e.body[0]:e)),t.nextIndex++,c}function Gv({kind:e,negate:t,value:n},r){let{normalizeUnknownPropertyNames:i,skipPropertyNameValidation:a,unicodePropertyMap:o}=r;if(e===`property`){let r=xy(n);if(Y_.has(r)&&!o?.has(r))e=`posix`,n=r;else return py(n,{negate:t,normalizeUnknownPropertyNames:i,skipPropertyNameValidation:a,unicodePropertyMap:o})}return e===`posix`?ly(n,{negate:t}):ry(e,{negate:t})}function Kv(e,t,n){let{tokens:r,capturingGroups:i,namedGroupsByName:a,skipLookbehindValidation:o,walk:s}=t,c=my(e),l=c.type===`AbsenceFunction`,u=vy(c),d=u&&c.negate;if(c.type===`CapturingGroup`&&(i.push(c),c.name&&J_(a,c.name,[]).push(c)),l&&n.isInAbsenceFunction)throw Error(`Nested absence function not supported by Oniguruma`);let f=Cy(r[t.nextIndex]);for(;f.type!==`GroupClose`;){if(f.type===`Alternator`)c.body.push(Xv()),t.nextIndex++;else{let e=c.body.at(-1),t=s(e,{...n,isInAbsenceFunction:n.isInAbsenceFunction||l,isInLookbehind:n.isInLookbehind||u,isInNegLookbehind:n.isInNegLookbehind||d});if(e.body.push(t),(u||n.isInLookbehind)&&!o){let e=`Lookbehind includes a pattern not allowed by Oniguruma`;if(d||n.isInNegLookbehind){if(_y(t)||t.type===`CapturingGroup`)throw Error(e)}else if(_y(t)||vy(t)&&t.negate)throw Error(e)}}f=Cy(r[t.nextIndex])}return t.nextIndex++,c}function qv({kind:e,min:t,max:n},r){let i=r.parent,a=i.body.at(-1);if(!a||!Rv(a))throw Error(`Quantifier requires a repeatable token`);let o=uy(e,t,n,a);return i.body.pop(),o}function Jv({raw:e},t){let{capturingGroups:n,subroutines:r}=t,i=e.slice(3,-1),a=/^(?<sign>[-+]?)0*(?<num>[1-9]\d*)$/.exec(i);if(a){let e=+a.groups.num,r=n.length;if(t.hasNumberedRef=!0,i={"":e,"+":r+e,"-":r+1-e}[a.groups.sign],i<1)throw Error(`Invalid subroutine number`)}else i===`0`&&(i=0);let o=fy(i);return r.push(o),o}function Yv(e,t){if(e!==`repeater`)throw Error(`Unexpected absence function kind "${e}"`);return{type:`AbsenceFunction`,kind:e,body:hy(t?.body)}}function Xv(e){return{type:`Alternative`,body:gy(e?.body)}}function Zv(e,t){let n={type:`Assertion`,kind:e};return(e===`word_boundary`||e===`text_segment_boundary`)&&(n.negate=!!t?.negate),n}function Qv(e,t){let n=!!t?.orphan;return{type:`Backreference`,ref:e,...n&&{orphan:n}}}function $v(e,t){let n={name:void 0,isSubroutined:!1,...t};if(n.name!==void 0&&!yy(n.name))throw Error(`Group name "${n.name}" invalid in Oniguruma`);return{type:`CapturingGroup`,number:e,...n.name&&{name:n.name},...n.isSubroutined&&{isSubroutined:n.isSubroutined},body:hy(t?.body)}}function ey(e,t){let n={useLastValid:!1,...t};if(e>1114111){let t=e.toString(16);if(n.useLastValid)e=1114111;else throw Error(e>1310719?`Invalid code point out of range "\\x{${t}}"`:`Invalid code point out of range in JS "\\x{${t}}"`)}return{type:`Character`,value:e}}function ty(e){let t={kind:`union`,negate:!1,...e};return{type:`CharacterClass`,kind:t.kind,negate:t.negate,body:gy(e?.body)}}function ny(e,t){if(t.value<e.value)throw Error(`Character class range out of order`);return{type:`CharacterClassRange`,min:e,max:t}}function ry(e,t){let n=!!t?.negate,r={type:`CharacterSet`,kind:e};return(e===`digit`||e===`hex`||e===`newline`||e===`space`||e===`word`)&&(r.negate=n),(e===`text_segment`||e===`newline`&&!n)&&(r.variableLength=!0),r}function iy(e,t={}){if(e===`keep`)return{type:`Directive`,kind:e};if(e===`flags`)return{type:`Directive`,kind:e,flags:Z_(t.flags)};throw Error(`Unexpected directive kind "${e}"`)}function ay(e){return{type:`Flags`,...e}}function oy(e){let t=e?.atomic,n=e?.flags;if(t&&n)throw Error(`Atomic group cannot have flags`);return{type:`Group`,...t&&{atomic:t},...n&&{flags:n},body:hy(e?.body)}}function sy(e){let t={behind:!1,negate:!1,...e};return{type:`LookaroundAssertion`,kind:t.behind?`lookbehind`:`lookahead`,negate:t.negate,body:hy(e?.body)}}function cy(e,t,n){return{type:`NamedCallout`,kind:e,tag:t,arguments:n}}function ly(e,t){let n=!!t?.negate;if(!Y_.has(e))throw Error(`Invalid POSIX class "${e}"`);return{type:`CharacterSet`,kind:`posix`,value:e,negate:n}}function uy(e,t,n,r){if(t>n)throw Error(`Invalid reversed quantifier range`);return{type:`Quantifier`,kind:e,min:t,max:n,body:r}}function dy(e,t){return{type:`Regex`,body:hy(t?.body),flags:e}}function fy(e){return{type:`Subroutine`,ref:e}}function py(e,t){let n={negate:!1,normalizeUnknownPropertyNames:!1,skipPropertyNameValidation:!1,unicodePropertyMap:null,...t},r=n.unicodePropertyMap?.get(xy(e));if(!r){if(n.normalizeUnknownPropertyNames)r=by(e);else if(n.unicodePropertyMap&&!n.skipPropertyNameValidation)throw Error(X_`Invalid Unicode property "\p{${e}}"`)}return{type:`CharacterSet`,kind:`property`,value:r??e,negate:n.negate}}function my({flags:e,kind:t,name:n,negate:r,number:i}){switch(t){case`absence_repeater`:return Yv(`repeater`);case`atomic`:return oy({atomic:!0});case`capturing`:return $v(i,{name:n});case`group`:return oy({flags:e});case`lookahead`:case`lookbehind`:return sy({behind:t===`lookbehind`,negate:r});default:throw Error(`Unexpected group kind "${t}"`)}}function hy(e){if(e===void 0)e=[Xv()];else if(!Array.isArray(e)||!e.length||!e.every(e=>e.type===`Alternative`))throw Error(`Invalid body; expected array of one or more Alternative nodes`);return e}function gy(e){if(e===void 0)e=[];else if(!Array.isArray(e)||!e.every(e=>!!e.type))throw Error(`Invalid body; expected array of nodes`);return e}function _y(e){return e.type===`LookaroundAssertion`&&e.kind===`lookahead`}function vy(e){return e.type===`LookaroundAssertion`&&e.kind===`lookbehind`}function yy(e){return/^[\p{Alpha}\p{Pc}][^)]*$/u.test(e)}function by(e){return e.trim().replace(/[- _]+/g,`_`).replace(/[A-Z][a-z]+(?=[A-Z])/g,`$&_`).replace(/[A-Za-z]+/g,e=>e[0].toUpperCase()+e.slice(1).toLowerCase())}function xy(e){return e.replace(/[- _]+/g,``).toLowerCase()}function Sy(e,t){let n=t;return Z_(e,`Unclosed character class${n?.type===`Character`&&n.value===93&&n.raw===`]`?` (started with "]")`:``}`)}function Cy(e){return Z_(e,`Unclosed group`)}function wy(e,t,n=null){function r(e,t){for(let n=0;n<e.length;n++){let r=i(e[n],t,n,e);n=Math.max(-1,n+r)}}function i(a,o=null,s=null,c=null){let l=0,u=!1,d={node:a,parent:o,key:s,container:c,root:e,remove(){Ty(c).splice(Math.max(0,Ey(s)+l),1),l--,u=!0},removeAllNextSiblings(){return Ty(c).splice(Ey(s)+1)},removeAllPrevSiblings(){let e=Ey(s)+l;return l-=e,Ty(c).splice(0,Math.max(0,e))},replaceWith(e,t={}){let n=!!t.traverse;c?c[Math.max(0,Ey(s)+l)]=e:Z_(o,`Can't replace root node`)[s]=e,n&&i(e,o,s,c),u=!0},replaceWithMultiple(e,t={}){let n=!!t.traverse;if(Ty(c).splice(Math.max(0,Ey(s)+l),1,...e),l+=e.length-1,n){let t=0;for(let n=0;n<e.length;n++)t+=i(e[n],o,Ey(s)+n+t,c)}u=!0},skip(){u=!0}},{type:f}=a,p=t[`*`],m=t[f],h=typeof p==`function`?p:p?.enter,g=typeof m==`function`?m:m?.enter;if(h?.(d,n),g?.(d,n),!u)switch(f){case`AbsenceFunction`:case`Alternative`:case`CapturingGroup`:case`CharacterClass`:case`Group`:case`LookaroundAssertion`:r(a.body,a);break;case`Assertion`:case`Backreference`:case`Character`:case`CharacterSet`:case`Directive`:case`Flags`:case`NamedCallout`:case`Subroutine`:break;case`CharacterClassRange`:i(a.min,a,`min`),i(a.max,a,`max`);break;case`Quantifier`:i(a.body,a,`body`);break;case`Regex`:r(a.body,a),i(a.flags,a,`flags`);break;default:throw Error(`Unexpected node type "${f}"`)}return m?.exit?.(d,n),p?.exit?.(d,n),l}return i(e),e}function Ty(e){if(!Array.isArray(e))throw Error(`Container expected`);return e}function Ey(e){if(typeof e!=`number`)throw Error(`Numeric key expected`);return e}var Dy=String.raw`\(\?(?:[:=!>A-Za-z\-]|<[=!]|\(DEFINE\))`;function Oy(e,t){for(let n=0;n<e.length;n++)e[n]>=t&&e[n]++}function ky(e,t,n,r){return e.slice(0,t)+r+e.slice(t+n.length)}var Ay=Object.freeze({DEFAULT:`DEFAULT`,CHAR_CLASS:`CHAR_CLASS`});function jy(e,t,n,r){let i=new RegExp(String.raw`${t}|(?<$skip>\[\^?|\\?.)`,`gsu`),a=[!1],o=0,s=``;for(let t of e.matchAll(i)){let{0:e,groups:{$skip:i}}=t;!i&&(!r||r===Ay.DEFAULT==!o)?n instanceof Function?s+=n(t,{context:o?Ay.CHAR_CLASS:Ay.DEFAULT,negated:a[a.length-1]}):s+=n:(e[0]===`[`?(o++,a.push(e[1]===`^`)):e===`]`&&o&&(o--,a.pop()),s+=e)}return s}function My(e,t,n,r){jy(e,t,n,r)}function Ny(e,t,n=0,r){if(!new RegExp(t,`su`).test(e))return null;let i=RegExp(`${t}|(?<$skip>\\\\?.)`,`gsu`);i.lastIndex=n;let a=0,o;for(;o=i.exec(e);){let{0:e,groups:{$skip:t}}=o;if(!t&&(!r||r===Ay.DEFAULT==!a))return o;e===`[`?a++:e===`]`&&a&&a--,i.lastIndex==o.index&&i.lastIndex++}return null}function Py(e,t,n){return!!Ny(e,t,0,n)}function Fy(e,t){let n=/\\?./gsu;n.lastIndex=t;let r=e.length,i=0,a=1,o;for(;o=n.exec(e);){let[e]=o;if(e===`[`)i++;else if(i)e===`]`&&i--;else if(e===`(`)a++;else if(e===`)`&&(a--,!a)){r=o.index;break}}return e.slice(t,r)}var Iy=new RegExp(String.raw`(?<noncapturingStart>${Dy})|(?<capturingStart>\((?:\?<[^>]+>)?)|\\?.`,`gsu`);function Ly(e,t){let n=t?.hiddenCaptures??[],r=t?.captureTransfers??new Map;if(!/\(\?>/.test(e))return{pattern:e,captureTransfers:r,hiddenCaptures:n};let i=[0],a=[],o=0,s=0,c=NaN,l;do{l=!1;let t=0,u=0,d=!1,f;for(Iy.lastIndex=Number.isNaN(c)?0:c+7;f=Iy.exec(e);){let{0:p,index:m,groups:{capturingStart:h,noncapturingStart:g}}=f;if(p===`[`)t++;else if(t)p===`]`&&t--;else if(p===`(?>`&&!d)c=m,d=!0;else if(d&&g)u++;else if(h)d?u++:(o++,i.push(o+s));else if(p===`)`&&d){if(!u){s++;let t=o+s;if(e=`${e.slice(0,c)}(?:(?=(${e.slice(c+3,m)}))<$$${t}>)${e.slice(m+1)}`,l=!0,a.push(t),Oy(n,t),r.size){let e=new Map;r.forEach((n,r)=>{e.set(r>=t?r+1:r,n.map(e=>e>=t?e+1:e))}),r=e}break}u--}}}while(l);return n.push(...a),e=jy(e,String.raw`\\(?<backrefNum>[1-9]\d*)|<\$\$(?<wrappedBackrefNum>\d+)>`,({0:e,groups:{backrefNum:t,wrappedBackrefNum:n}})=>{if(t){let n=+t;if(n>i.length-1)throw Error(`Backref "${e}" greater than number of captures`);return`\\${i[n]}`}return`\\${n}`},Ay.DEFAULT),{pattern:e,captureTransfers:r,hiddenCaptures:n}}var Ry=String.raw`(?:[?*+]|\{\d+(?:,\d*)?\})`,zy=new RegExp(String.raw`
66
+ `.replace(/\s+/g,``),`gsu`);function iv(e,t={}){let n={flags:``,...t,rules:{captureGroup:!1,singleline:!1,...t.rules}};if(typeof e!=`string`)throw Error(`String expected as pattern`);let r=Pv(n.flags),i=[r.extended],a={captureGroup:n.rules.captureGroup,getCurrentModX(){return i.at(-1)},numOpenGroups:0,popModX(){i.pop()},pushModX(e){i.push(e)},replaceCurrentModX(e){i[i.length-1]=e},singleline:n.rules.singleline},o=[],s;for(nv.lastIndex=0;s=nv.exec(e);){let t=av(a,e,s[0],nv.lastIndex);t.tokens?o.push(...t.tokens):t.token&&o.push(t.token),t.lastIndex!==void 0&&(nv.lastIndex=t.lastIndex)}let c=[],l=0;o.filter(e=>e.type===`GroupOpen`).forEach(e=>{e.kind===`capturing`?e.number=++l:e.raw===`(`&&c.push(e)}),l||c.forEach((e,t)=>{e.kind=`capturing`,e.number=t+1});let u=l||c.length;return{tokens:o.map(e=>e.type===`EscapedNumber`?Iv(e,u):e).flat(),flags:r}}function av(e,t,n,r){let[i,a]=n;if(n===`[`||n===`[^`){let e=ov(t,n,r);return{tokens:e.tokens,lastIndex:e.lastIndex}}if(i===`\\`){if(`AbBGyYzZ`.includes(a))return{token:uv(n,n)};if(/^\\g[<']/.test(n)){if(!/^\\g(?:<[^>]+>|'[^']+')$/.test(n))throw Error(`Invalid group name "${n}"`);return{token:wv(n)}}if(/^\\k[<']/.test(n)){if(!/^\\k(?:<[^>]+>|'[^']+')$/.test(n))throw Error(`Invalid group name "${n}"`);return{token:dv(n)}}if(a===`K`)return{token:vv(`keep`,n)};if(a===`N`||a===`R`)return{token:_v(`newline`,n,{negate:a===`N`})};if(a===`O`)return{token:_v(`any`,n)};if(a===`X`)return{token:_v(`text_segment`,n)};let e=cv(n,{inCharClass:!1});return Array.isArray(e)?{tokens:e}:{token:e}}if(i===`(`){if(a===`*`)return{token:kv(n)};if(n===`(?{`)throw Error(`Unsupported callout "${n}"`);if(n.startsWith(`(?#`)){if(t[r]!==`)`)throw Error(`Unclosed comment group "(?#"`);return{lastIndex:r+1}}if(/^\(\?[-imx]+[:)]$/.test(n))return{token:Ov(n,e)};if(e.pushModX(e.getCurrentModX()),e.numOpenGroups++,n===`(`&&!e.captureGroup||n===`(?:`)return{token:xv(`group`,n)};if(n===`(?>`)return{token:xv(`atomic`,n)};if(n===`(?=`||n===`(?!`||n===`(?<=`||n===`(?<!`)return{token:xv(n[2]===`<`?`lookbehind`:`lookahead`,n,{negate:n.endsWith(`!`)})};if(n===`(`&&e.captureGroup||n.startsWith(`(?<`)&&n.endsWith(`>`)||n.startsWith(`(?'`)&&n.endsWith(`'`))return{token:xv(`capturing`,n,{...n!==`(`&&{name:n.slice(3,-1)}})};if(n.startsWith(`(?~`)){if(n===`(?~|`)throw Error(`Unsupported absence function kind "${n}"`);return{token:xv(`absence_repeater`,n)}}throw Error(n===`(?(`?`Unsupported conditional "${n}"`:`Invalid or unsupported group option "${n}"`)}if(n===`)`){if(e.popModX(),e.numOpenGroups--,e.numOpenGroups<0)throw Error(`Unmatched ")"`);return{token:bv(n)}}if(e.getCurrentModX()){if(n===`#`){let e=t.indexOf(`
67
+ `,r);return{lastIndex:e===-1?t.length:e}}if(/^\s$/.test(n)){let e=/\s+/y;return e.lastIndex=r,{lastIndex:e.exec(t)?e.lastIndex:r}}}return n===`.`?{token:_v(`dot`,n)}:n===`^`||n===`$`?{token:uv(e.singleline?{"^":Z_`\A`,$:Z_`\Z`}[n]:n,n)}:n===`|`?{token:lv(n)}:tv.test(n)?{tokens:Lv(n)}:{token:fv(J_(n),n)}}function ov(e,t,n){let r=[gv(t[1]===`^`,t)],i=1,a;for(rv.lastIndex=n;a=rv.exec(e);){let e=a[0];if(e[0]===`[`&&e[1]!==`:`)i++,r.push(gv(e[1]===`^`,e));else if(e===`]`){if(r.at(-1).type===`CharacterClassOpen`)r.push(fv(93,e));else if(i--,r.push(pv(e)),!i)break}else{let t=sv(e);Array.isArray(t)?r.push(...t):r.push(t)}}return{tokens:r,lastIndex:rv.lastIndex||e.length}}function sv(e){if(e[0]===`\\`)return cv(e,{inCharClass:!0});if(e[0]===`[`){let t=/\[:(?<negate>\^?)(?<name>[a-z]+):\]/.exec(e);if(!t||!X_.has(t.groups.name))throw Error(`Invalid POSIX class "${e}"`);return _v(`posix`,e,{value:t.groups.name,negate:!!t.groups.negate})}return e===`-`?mv(e):e===`&&`?hv(e):fv(J_(e),e)}function cv(e,{inCharClass:t}){let n=e[1];if(n===`c`||n===`C`)return Dv(e);if(`dDhHsSwW`.includes(n))return jv(e);if(e.startsWith(Z_`\o{`))throw Error(`Incomplete, invalid, or unsupported octal code point "${e}"`);if(/^\\[pP]\{/.test(e)){if(e.length===3)throw Error(`Incomplete or invalid Unicode property "${e}"`);return Mv(e)}if(/^\\x[89A-Fa-f]\p{AHex}/u.test(e))try{let t=e.split(/\\x/).slice(1).map(e=>parseInt(e,16)),n=new TextDecoder(`utf-8`,{ignoreBOM:!0,fatal:!0}).decode(new Uint8Array(t)),r=new TextEncoder;return[...n].map(e=>{let t=[...r.encode(e)].map(e=>`\\x${e.toString(16)}`).join(``);return fv(J_(e),t)})}catch{throw Error(`Multibyte code "${e}" incomplete or invalid in Oniguruma`)}if(n===`u`||n===`x`)return fv(Fv(e),e);if(Ev.has(n))return fv(Ev.get(n),e);if(/\d/.test(n))return yv(t,e);if(e===`\\`)throw Error(Z_`Incomplete escape "\"`);if(n===`M`)throw Error(`Unsupported meta "${e}"`);if([...e].length===2)return fv(e.codePointAt(1),e);throw Error(`Unexpected escape "${e}"`)}function lv(e){return{type:`Alternator`,raw:e}}function uv(e,t){return{type:`Assertion`,kind:e,raw:t}}function dv(e){return{type:`Backreference`,raw:e}}function fv(e,t){return{type:`Character`,value:e,raw:t}}function pv(e){return{type:`CharacterClassClose`,raw:e}}function mv(e){return{type:`CharacterClassHyphen`,raw:e}}function hv(e){return{type:`CharacterClassIntersector`,raw:e}}function gv(e,t){return{type:`CharacterClassOpen`,negate:e,raw:t}}function _v(e,t,n={}){return{type:`CharacterSet`,kind:e,...n,raw:t}}function vv(e,t,n={}){return e===`keep`?{type:`Directive`,kind:e,raw:t}:{type:`Directive`,kind:e,flags:Q_(n.flags),raw:t}}function yv(e,t){return{type:`EscapedNumber`,inCharClass:e,raw:t}}function bv(e){return{type:`GroupClose`,raw:e}}function xv(e,t,n={}){return{type:`GroupOpen`,kind:e,...n,raw:t}}function Sv(e,t,n,r){return{type:`NamedCallout`,kind:e,tag:t,arguments:n,raw:r}}function Cv(e,t,n,r){return{type:`Quantifier`,kind:e,min:t,max:n,raw:r}}function wv(e){return{type:`Subroutine`,raw:e}}var Tv=new Set([`COUNT`,`CMP`,`ERROR`,`FAIL`,`MAX`,`MISMATCH`,`SKIP`,`TOTAL_COUNT`]),Ev=new Map([[`a`,7],[`b`,8],[`e`,27],[`f`,12],[`n`,10],[`r`,13],[`t`,9],[`v`,11]]);function Dv(e){let t=e[1]===`c`?e[2]:e[3];if(!t||!/[A-Za-z]/.test(t))throw Error(`Unsupported control character "${e}"`);return fv(J_(t.toUpperCase())-64,e)}function Ov(e,t){let{on:n,off:r}=/^\(\?(?<on>[imx]*)(?:-(?<off>[-imx]*))?/.exec(e).groups;r??=``;let i=(t.getCurrentModX()||n.includes(`x`))&&!r.includes(`x`),a=Nv(n),o=Nv(r),s={};if(a&&(s.enable=a),o&&(s.disable=o),e.endsWith(`)`))return t.replaceCurrentModX(i),vv(`flags`,e,{flags:s});if(e.endsWith(`:`))return t.pushModX(i),t.numOpenGroups++,xv(`group`,e,{...(a||o)&&{flags:s}});throw Error(`Unexpected flag modifier "${e}"`)}function kv(e){let t=/\(\*(?<name>[A-Za-z_]\w*)?(?:\[(?<tag>(?:[A-Za-z_]\w*)?)\])?(?:\{(?<args>[^}]*)\})?\)/.exec(e);if(!t)throw Error(`Incomplete or invalid named callout "${e}"`);let{name:n,tag:r,args:i}=t.groups;if(!n)throw Error(`Invalid named callout "${e}"`);if(r===``)throw Error(`Named callout tag with empty value not allowed "${e}"`);let a=i?i.split(`,`).filter(e=>e!==``).map(e=>/^[+-]?\d+$/.test(e)?+e:e):[],[o,s,c]=a,l=Tv.has(n)?n.toLowerCase():`custom`;switch(l){case`fail`:case`mismatch`:case`skip`:if(a.length>0)throw Error(`Named callout arguments not allowed "${a}"`);break;case`error`:if(a.length>1)throw Error(`Named callout allows only one argument "${a}"`);if(typeof o==`string`)throw Error(`Named callout argument must be a number "${o}"`);break;case`max`:if(!a.length||a.length>2)throw Error(`Named callout must have one or two arguments "${a}"`);if(typeof o==`string`&&!/^[A-Za-z_]\w*$/.test(o))throw Error(`Named callout argument one must be a tag or number "${o}"`);if(a.length===2&&(typeof s==`number`||!/^[<>X]$/.test(s)))throw Error(`Named callout optional argument two must be '<', '>', or 'X' "${s}"`);break;case`count`:case`total_count`:if(a.length>1)throw Error(`Named callout allows only one argument "${a}"`);if(a.length===1&&(typeof o==`number`||!/^[<>X]$/.test(o)))throw Error(`Named callout optional argument must be '<', '>', or 'X' "${o}"`);break;case`cmp`:if(a.length!==3)throw Error(`Named callout must have three arguments "${a}"`);if(typeof o==`string`&&!/^[A-Za-z_]\w*$/.test(o))throw Error(`Named callout argument one must be a tag or number "${o}"`);if(typeof s==`number`||!/^(?:[<>!=]=|[<>])$/.test(s))throw Error(`Named callout argument two must be '==', '!=', '>', '<', '>=', or '<=' "${s}"`);if(typeof c==`string`&&!/^[A-Za-z_]\w*$/.test(c))throw Error(`Named callout argument three must be a tag or number "${c}"`);break;case`custom`:throw Error(`Undefined callout name "${n}"`);default:throw Error(`Unexpected named callout kind "${l}"`)}return Sv(l,r??null,i?.split(`,`)??null,e)}function Av(e){let t=null,n,r;if(e[0]===`{`){let{minStr:i,maxStr:a}=/^\{(?<minStr>\d*)(?:,(?<maxStr>\d*))?/.exec(e).groups,o=1e5;if(+i>o||a&&+a>o)throw Error(`Quantifier value unsupported in Oniguruma`);if(n=+i,r=a===void 0?+i:a===``?1/0:+a,n>r&&(t=`possessive`,[n,r]=[r,n]),e.endsWith(`?`)){if(t===`possessive`)throw Error(`Unsupported possessive interval quantifier chain with "?"`);t=`lazy`}else t||=`greedy`}else n=+(e[0]===`+`),r=e[0]===`?`?1:1/0,t=e[1]===`+`?`possessive`:e[1]===`?`?`lazy`:`greedy`;return Cv(t,n,r,e)}function jv(e){let t=e[1].toLowerCase();return _v({d:`digit`,h:`hex`,s:`space`,w:`word`}[t],e,{negate:e[1]!==t})}function Mv(e){let{p:t,neg:n,value:r}=/^\\(?<p>[pP])\{(?<neg>\^?)(?<value>[^}]+)/.exec(e).groups;return _v(`property`,e,{value:r,negate:t===`P`&&!n||t===`p`&&!!n})}function Nv(e){let t={};return e.includes(`i`)&&(t.ignoreCase=!0),e.includes(`m`)&&(t.dotAll=!0),e.includes(`x`)&&(t.extended=!0),Object.keys(t).length?t:null}function Pv(e){let t={ignoreCase:!1,dotAll:!1,extended:!1,digitIsAscii:!1,posixIsAscii:!1,spaceIsAscii:!1,wordIsAscii:!1,textSegmentMode:null};for(let n=0;n<e.length;n++){let r=e[n];if(!`imxDPSWy`.includes(r))throw Error(`Invalid flag "${r}"`);if(r===`y`){if(!/^y{[gw]}/.test(e.slice(n)))throw Error(`Invalid or unspecified flag "y" mode`);t.textSegmentMode=e[n+2]===`g`?`grapheme`:`word`,n+=3}else t[{i:`ignoreCase`,m:`dotAll`,x:`extended`,D:`digitIsAscii`,P:`posixIsAscii`,S:`spaceIsAscii`,W:`wordIsAscii`}[r]]=!0}return t}function Fv(e){if(/^(?:\\u(?!\p{AHex}{4})|\\x(?!\p{AHex}{1,2}|\{\p{AHex}{1,8}\}))/u.test(e))throw Error(`Incomplete or invalid escape "${e}"`);let t=e[2]===`{`?/^\\x\{\s*(?<hex>\p{AHex}+)/u.exec(e).groups.hex:e.slice(2);return parseInt(t,16)}function Iv(e,t){let{raw:n,inCharClass:r}=e,i=n.slice(1);if(!r&&(i!==`0`&&i.length===1||i[0]!==`0`&&+i<=t))return[dv(n)];let a=[],o=i.match(/^[0-7]+|\d/g);for(let e=0;e<o.length;e++){let t=o[e],r;if(e===0&&t!==`8`&&t!==`9`){if(r=parseInt(t,8),r>127)throw Error(Z_`Octal encoded byte above 177 unsupported "${n}"`)}else r=J_(t);a.push(fv(r,(e===0?`\\`:``)+t))}return a}function Lv(e){let t=[],n=new RegExp(tv,`gy`),r;for(;r=n.exec(e);){let e=r[0];if(e[0]===`{`){let r=/^\{(?<min>\d+),(?<max>\d+)\}\??$/.exec(e);if(r){let{min:i,max:a}=r.groups;if(+i>+a&&e.endsWith(`?`)){n.lastIndex--,t.push(Av(e.slice(0,-1)));continue}}}t.push(Av(e))}return t}function Rv(e,t){if(!Array.isArray(e.body))throw Error(`Expected node with body array`);if(e.body.length!==1)return!1;let n=e.body[0];return!t||Object.keys(t).every(e=>t[e]===n[e])}function zv(e){return Bv.has(e.type)}var Bv=new Set([`AbsenceFunction`,`Backreference`,`CapturingGroup`,`Character`,`CharacterClass`,`CharacterSet`,`Group`,`Quantifier`,`Subroutine`]);function Vv(e,t={}){let n={flags:``,normalizeUnknownPropertyNames:!1,skipBackrefValidation:!1,skipLookbehindValidation:!1,skipPropertyNameValidation:!1,unicodePropertyMap:null,...t,rules:{captureGroup:!1,singleline:!1,...t.rules}},r=iv(e,{flags:n.flags,rules:{captureGroup:n.rules.captureGroup,singleline:n.rules.singleline}}),i=(e,t)=>{let n=r.tokens[a.nextIndex];switch(a.parent=e,a.nextIndex++,n.type){case`Alternator`:return Zv();case`Assertion`:return Hv(n);case`Backreference`:return Uv(n,a);case`Character`:return ty(n.value,{useLastValid:!!t.isCheckingRangeEnd});case`CharacterClassHyphen`:return Wv(n,a,t);case`CharacterClassOpen`:return Gv(n,a,t);case`CharacterSet`:return Kv(n,a);case`Directive`:return ay(n.kind,{flags:n.flags});case`GroupOpen`:return qv(n,a,t);case`NamedCallout`:return ly(n.kind,n.tag,n.arguments);case`Quantifier`:return Jv(n,a);case`Subroutine`:return Yv(n,a);default:throw Error(`Unexpected token type "${n.type}"`)}},a={capturingGroups:[],hasNumberedRef:!1,namedGroupsByName:new Map,nextIndex:0,normalizeUnknownPropertyNames:n.normalizeUnknownPropertyNames,parent:null,skipBackrefValidation:n.skipBackrefValidation,skipLookbehindValidation:n.skipLookbehindValidation,skipPropertyNameValidation:n.skipPropertyNameValidation,subroutines:[],tokens:r.tokens,unicodePropertyMap:n.unicodePropertyMap,walk:i},o=fy(oy(r.flags)),s=o.body[0];for(;a.nextIndex<r.tokens.length;){let e=i(s,{});e.type===`Alternative`?(o.body.push(e),s=e):s.body.push(e)}let{capturingGroups:c,hasNumberedRef:l,namedGroupsByName:u,subroutines:d}=a;if(l&&u.size&&!n.rules.captureGroup)throw Error(`Numbered backref/subroutine not allowed when using named capture`);for(let{ref:e}of d)if(typeof e==`number`){if(e>c.length)throw Error(`Subroutine uses a group number that's not defined`);e&&(c[e-1].isSubroutined=!0)}else if(u.has(e)){if(u.get(e).length>1)throw Error(Z_`Subroutine uses a duplicate group name "\g<${e}>"`);u.get(e)[0].isSubroutined=!0}else throw Error(Z_`Subroutine uses a group name that's not defined "\g<${e}>"`);return o}function Hv({kind:e}){return Qv(Q_({"^":`line_start`,$:`line_end`,"\\A":`string_start`,"\\b":`word_boundary`,"\\B":`word_boundary`,"\\G":`search_start`,"\\y":`text_segment_boundary`,"\\Y":`text_segment_boundary`,"\\z":`string_end`,"\\Z":`string_end_newline`}[e],`Unexpected assertion kind "${e}"`),{negate:e===Z_`\B`||e===Z_`\Y`})}function Uv({raw:e},t){let n=/^\\k[<']/.test(e),r=n?e.slice(3,-1):e.slice(1),i=(n,r=!1)=>{let i=t.capturingGroups.length,a=!1;if(n>i){if(t.skipBackrefValidation)a=!0;else throw Error(`Not enough capturing groups defined to the left "${e}"`)}return t.hasNumberedRef=!0,$v(r?i+1-n:n,{orphan:a})};if(n){let n=/^(?<sign>-?)0*(?<num>[1-9]\d*)$/.exec(r);if(n)return i(+n.groups.num,!!n.groups.sign);if(/[-+]/.test(r))throw Error(`Invalid backref name "${e}"`);if(!t.namedGroupsByName.has(r))throw Error(`Group name not defined to the left "${e}"`);return $v(r)}return i(+r)}function Wv(e,t,n){let{tokens:r,walk:i}=t,a=t.parent,o=a.body.at(-1),s=r[t.nextIndex];if(!n.isCheckingRangeEnd&&o&&o.type!==`CharacterClass`&&o.type!==`CharacterClassRange`&&s&&s.type!==`CharacterClassOpen`&&s.type!==`CharacterClassClose`&&s.type!==`CharacterClassIntersector`){let e=i(a,{...n,isCheckingRangeEnd:!0});if(o.type===`Character`&&e.type===`Character`)return a.body.pop(),ry(o,e);throw Error(`Invalid character class range`)}return ty(J_(`-`))}function Gv({negate:e},t,n){let{tokens:r,walk:i}=t,a=[ny()],o=r[t.nextIndex],s=Cy(o);for(;s.type!==`CharacterClassClose`;){if(s.type===`CharacterClassIntersector`)a.push(ny()),t.nextIndex++;else{let e=a.at(-1);e.body.push(i(e,n))}s=Cy(r[t.nextIndex],o)}let c=ny({negate:e});return a.length===1?c.body=a[0].body:(c.kind=`intersection`,c.body=a.map(e=>e.body.length===1?e.body[0]:e)),t.nextIndex++,c}function Kv({kind:e,negate:t,value:n},r){let{normalizeUnknownPropertyNames:i,skipPropertyNameValidation:a,unicodePropertyMap:o}=r;if(e===`property`){let r=Sy(n);if(X_.has(r)&&!o?.has(r))e=`posix`,n=r;else return my(n,{negate:t,normalizeUnknownPropertyNames:i,skipPropertyNameValidation:a,unicodePropertyMap:o})}return e===`posix`?uy(n,{negate:t}):iy(e,{negate:t})}function qv(e,t,n){let{tokens:r,capturingGroups:i,namedGroupsByName:a,skipLookbehindValidation:o,walk:s}=t,c=hy(e),l=c.type===`AbsenceFunction`,u=yy(c),d=u&&c.negate;if(c.type===`CapturingGroup`&&(i.push(c),c.name&&Y_(a,c.name,[]).push(c)),l&&n.isInAbsenceFunction)throw Error(`Nested absence function not supported by Oniguruma`);let f=wy(r[t.nextIndex]);for(;f.type!==`GroupClose`;){if(f.type===`Alternator`)c.body.push(Zv()),t.nextIndex++;else{let e=c.body.at(-1),t=s(e,{...n,isInAbsenceFunction:n.isInAbsenceFunction||l,isInLookbehind:n.isInLookbehind||u,isInNegLookbehind:n.isInNegLookbehind||d});if(e.body.push(t),(u||n.isInLookbehind)&&!o){let e=`Lookbehind includes a pattern not allowed by Oniguruma`;if(d||n.isInNegLookbehind){if(vy(t)||t.type===`CapturingGroup`)throw Error(e)}else if(vy(t)||yy(t)&&t.negate)throw Error(e)}}f=wy(r[t.nextIndex])}return t.nextIndex++,c}function Jv({kind:e,min:t,max:n},r){let i=r.parent,a=i.body.at(-1);if(!a||!zv(a))throw Error(`Quantifier requires a repeatable token`);let o=dy(e,t,n,a);return i.body.pop(),o}function Yv({raw:e},t){let{capturingGroups:n,subroutines:r}=t,i=e.slice(3,-1),a=/^(?<sign>[-+]?)0*(?<num>[1-9]\d*)$/.exec(i);if(a){let e=+a.groups.num,r=n.length;if(t.hasNumberedRef=!0,i={"":e,"+":r+e,"-":r+1-e}[a.groups.sign],i<1)throw Error(`Invalid subroutine number`)}else i===`0`&&(i=0);let o=py(i);return r.push(o),o}function Xv(e,t){if(e!==`repeater`)throw Error(`Unexpected absence function kind "${e}"`);return{type:`AbsenceFunction`,kind:e,body:gy(t?.body)}}function Zv(e){return{type:`Alternative`,body:_y(e?.body)}}function Qv(e,t){let n={type:`Assertion`,kind:e};return(e===`word_boundary`||e===`text_segment_boundary`)&&(n.negate=!!t?.negate),n}function $v(e,t){let n=!!t?.orphan;return{type:`Backreference`,ref:e,...n&&{orphan:n}}}function ey(e,t){let n={name:void 0,isSubroutined:!1,...t};if(n.name!==void 0&&!by(n.name))throw Error(`Group name "${n.name}" invalid in Oniguruma`);return{type:`CapturingGroup`,number:e,...n.name&&{name:n.name},...n.isSubroutined&&{isSubroutined:n.isSubroutined},body:gy(t?.body)}}function ty(e,t){let n={useLastValid:!1,...t};if(e>1114111){let t=e.toString(16);if(n.useLastValid)e=1114111;else throw Error(e>1310719?`Invalid code point out of range "\\x{${t}}"`:`Invalid code point out of range in JS "\\x{${t}}"`)}return{type:`Character`,value:e}}function ny(e){let t={kind:`union`,negate:!1,...e};return{type:`CharacterClass`,kind:t.kind,negate:t.negate,body:_y(e?.body)}}function ry(e,t){if(t.value<e.value)throw Error(`Character class range out of order`);return{type:`CharacterClassRange`,min:e,max:t}}function iy(e,t){let n=!!t?.negate,r={type:`CharacterSet`,kind:e};return(e===`digit`||e===`hex`||e===`newline`||e===`space`||e===`word`)&&(r.negate=n),(e===`text_segment`||e===`newline`&&!n)&&(r.variableLength=!0),r}function ay(e,t={}){if(e===`keep`)return{type:`Directive`,kind:e};if(e===`flags`)return{type:`Directive`,kind:e,flags:Q_(t.flags)};throw Error(`Unexpected directive kind "${e}"`)}function oy(e){return{type:`Flags`,...e}}function sy(e){let t=e?.atomic,n=e?.flags;if(t&&n)throw Error(`Atomic group cannot have flags`);return{type:`Group`,...t&&{atomic:t},...n&&{flags:n},body:gy(e?.body)}}function cy(e){let t={behind:!1,negate:!1,...e};return{type:`LookaroundAssertion`,kind:t.behind?`lookbehind`:`lookahead`,negate:t.negate,body:gy(e?.body)}}function ly(e,t,n){return{type:`NamedCallout`,kind:e,tag:t,arguments:n}}function uy(e,t){let n=!!t?.negate;if(!X_.has(e))throw Error(`Invalid POSIX class "${e}"`);return{type:`CharacterSet`,kind:`posix`,value:e,negate:n}}function dy(e,t,n,r){if(t>n)throw Error(`Invalid reversed quantifier range`);return{type:`Quantifier`,kind:e,min:t,max:n,body:r}}function fy(e,t){return{type:`Regex`,body:gy(t?.body),flags:e}}function py(e){return{type:`Subroutine`,ref:e}}function my(e,t){let n={negate:!1,normalizeUnknownPropertyNames:!1,skipPropertyNameValidation:!1,unicodePropertyMap:null,...t},r=n.unicodePropertyMap?.get(Sy(e));if(!r){if(n.normalizeUnknownPropertyNames)r=xy(e);else if(n.unicodePropertyMap&&!n.skipPropertyNameValidation)throw Error(Z_`Invalid Unicode property "\p{${e}}"`)}return{type:`CharacterSet`,kind:`property`,value:r??e,negate:n.negate}}function hy({flags:e,kind:t,name:n,negate:r,number:i}){switch(t){case`absence_repeater`:return Xv(`repeater`);case`atomic`:return sy({atomic:!0});case`capturing`:return ey(i,{name:n});case`group`:return sy({flags:e});case`lookahead`:case`lookbehind`:return cy({behind:t===`lookbehind`,negate:r});default:throw Error(`Unexpected group kind "${t}"`)}}function gy(e){if(e===void 0)e=[Zv()];else if(!Array.isArray(e)||!e.length||!e.every(e=>e.type===`Alternative`))throw Error(`Invalid body; expected array of one or more Alternative nodes`);return e}function _y(e){if(e===void 0)e=[];else if(!Array.isArray(e)||!e.every(e=>!!e.type))throw Error(`Invalid body; expected array of nodes`);return e}function vy(e){return e.type===`LookaroundAssertion`&&e.kind===`lookahead`}function yy(e){return e.type===`LookaroundAssertion`&&e.kind===`lookbehind`}function by(e){return/^[\p{Alpha}\p{Pc}][^)]*$/u.test(e)}function xy(e){return e.trim().replace(/[- _]+/g,`_`).replace(/[A-Z][a-z]+(?=[A-Z])/g,`$&_`).replace(/[A-Za-z]+/g,e=>e[0].toUpperCase()+e.slice(1).toLowerCase())}function Sy(e){return e.replace(/[- _]+/g,``).toLowerCase()}function Cy(e,t){let n=t;return Q_(e,`Unclosed character class${n?.type===`Character`&&n.value===93&&n.raw===`]`?` (started with "]")`:``}`)}function wy(e){return Q_(e,`Unclosed group`)}function Ty(e,t,n=null){function r(e,t){for(let n=0;n<e.length;n++){let r=i(e[n],t,n,e);n=Math.max(-1,n+r)}}function i(a,o=null,s=null,c=null){let l=0,u=!1,d={node:a,parent:o,key:s,container:c,root:e,remove(){Ey(c).splice(Math.max(0,Dy(s)+l),1),l--,u=!0},removeAllNextSiblings(){return Ey(c).splice(Dy(s)+1)},removeAllPrevSiblings(){let e=Dy(s)+l;return l-=e,Ey(c).splice(0,Math.max(0,e))},replaceWith(e,t={}){let n=!!t.traverse;c?c[Math.max(0,Dy(s)+l)]=e:Q_(o,`Can't replace root node`)[s]=e,n&&i(e,o,s,c),u=!0},replaceWithMultiple(e,t={}){let n=!!t.traverse;if(Ey(c).splice(Math.max(0,Dy(s)+l),1,...e),l+=e.length-1,n){let t=0;for(let n=0;n<e.length;n++)t+=i(e[n],o,Dy(s)+n+t,c)}u=!0},skip(){u=!0}},{type:f}=a,p=t[`*`],m=t[f],h=typeof p==`function`?p:p?.enter,g=typeof m==`function`?m:m?.enter;if(h?.(d,n),g?.(d,n),!u)switch(f){case`AbsenceFunction`:case`Alternative`:case`CapturingGroup`:case`CharacterClass`:case`Group`:case`LookaroundAssertion`:r(a.body,a);break;case`Assertion`:case`Backreference`:case`Character`:case`CharacterSet`:case`Directive`:case`Flags`:case`NamedCallout`:case`Subroutine`:break;case`CharacterClassRange`:i(a.min,a,`min`),i(a.max,a,`max`);break;case`Quantifier`:i(a.body,a,`body`);break;case`Regex`:r(a.body,a),i(a.flags,a,`flags`);break;default:throw Error(`Unexpected node type "${f}"`)}return m?.exit?.(d,n),p?.exit?.(d,n),l}return i(e),e}function Ey(e){if(!Array.isArray(e))throw Error(`Container expected`);return e}function Dy(e){if(typeof e!=`number`)throw Error(`Numeric key expected`);return e}var Oy=String.raw`\(\?(?:[:=!>A-Za-z\-]|<[=!]|\(DEFINE\))`;function ky(e,t){for(let n=0;n<e.length;n++)e[n]>=t&&e[n]++}function Ay(e,t,n,r){return e.slice(0,t)+r+e.slice(t+n.length)}var jy=Object.freeze({DEFAULT:`DEFAULT`,CHAR_CLASS:`CHAR_CLASS`});function My(e,t,n,r){let i=new RegExp(String.raw`${t}|(?<$skip>\[\^?|\\?.)`,`gsu`),a=[!1],o=0,s=``;for(let t of e.matchAll(i)){let{0:e,groups:{$skip:i}}=t;!i&&(!r||r===jy.DEFAULT==!o)?n instanceof Function?s+=n(t,{context:o?jy.CHAR_CLASS:jy.DEFAULT,negated:a[a.length-1]}):s+=n:(e[0]===`[`?(o++,a.push(e[1]===`^`)):e===`]`&&o&&(o--,a.pop()),s+=e)}return s}function Ny(e,t,n,r){My(e,t,n,r)}function Py(e,t,n=0,r){if(!new RegExp(t,`su`).test(e))return null;let i=RegExp(`${t}|(?<$skip>\\\\?.)`,`gsu`);i.lastIndex=n;let a=0,o;for(;o=i.exec(e);){let{0:e,groups:{$skip:t}}=o;if(!t&&(!r||r===jy.DEFAULT==!a))return o;e===`[`?a++:e===`]`&&a&&a--,i.lastIndex==o.index&&i.lastIndex++}return null}function Fy(e,t,n){return!!Py(e,t,0,n)}function Iy(e,t){let n=/\\?./gsu;n.lastIndex=t;let r=e.length,i=0,a=1,o;for(;o=n.exec(e);){let[e]=o;if(e===`[`)i++;else if(i)e===`]`&&i--;else if(e===`(`)a++;else if(e===`)`&&(a--,!a)){r=o.index;break}}return e.slice(t,r)}var Ly=new RegExp(String.raw`(?<noncapturingStart>${Oy})|(?<capturingStart>\((?:\?<[^>]+>)?)|\\?.`,`gsu`);function Ry(e,t){let n=t?.hiddenCaptures??[],r=t?.captureTransfers??new Map;if(!/\(\?>/.test(e))return{pattern:e,captureTransfers:r,hiddenCaptures:n};let i=[0],a=[],o=0,s=0,c=NaN,l;do{l=!1;let t=0,u=0,d=!1,f;for(Ly.lastIndex=Number.isNaN(c)?0:c+7;f=Ly.exec(e);){let{0:p,index:m,groups:{capturingStart:h,noncapturingStart:g}}=f;if(p===`[`)t++;else if(t)p===`]`&&t--;else if(p===`(?>`&&!d)c=m,d=!0;else if(d&&g)u++;else if(h)d?u++:(o++,i.push(o+s));else if(p===`)`&&d){if(!u){s++;let t=o+s;if(e=`${e.slice(0,c)}(?:(?=(${e.slice(c+3,m)}))<$$${t}>)${e.slice(m+1)}`,l=!0,a.push(t),ky(n,t),r.size){let e=new Map;r.forEach((n,r)=>{e.set(r>=t?r+1:r,n.map(e=>e>=t?e+1:e))}),r=e}break}u--}}}while(l);return n.push(...a),e=My(e,String.raw`\\(?<backrefNum>[1-9]\d*)|<\$\$(?<wrappedBackrefNum>\d+)>`,({0:e,groups:{backrefNum:t,wrappedBackrefNum:n}})=>{if(t){let n=+t;if(n>i.length-1)throw Error(`Backref "${e}" greater than number of captures`);return`\\${i[n]}`}return`\\${n}`},jy.DEFAULT),{pattern:e,captureTransfers:r,hiddenCaptures:n}}var zy=String.raw`(?:[?*+]|\{\d+(?:,\d*)?\})`,By=new RegExp(String.raw`
68
68
  \\(?: \d+
69
69
  | c[A-Za-z]
70
70
  | [gk]<[^>]+>
@@ -77,9 +77,9 @@ WARNING: This link could potentially be dangerous`)){let e=window.open();if(e){t
77
77
  | [A-Za-z\-]+:
78
78
  | \(DEFINE\)
79
79
  ))?
80
- | (?<qBase>${Ry})(?<qMod>[?+]?)(?<invalidQ>[?*+\{]?)
80
+ | (?<qBase>${zy})(?<qMod>[?+]?)(?<invalidQ>[?*+\{]?)
81
81
  | \\?.
82
- `.replace(/\s+/g,``),`gsu`);function By(e){if(!RegExp(`${Ry}\\+`).test(e))return{pattern:e};let t=[],n=null,r=null,i=``,a=0,o;for(zy.lastIndex=0;o=zy.exec(e);){let{0:s,index:c,groups:{qBase:l,qMod:u,invalidQ:d}}=o;if(s===`[`)a||(r=c),a++;else if(s===`]`)a?a--:r=null;else if(!a){if(u===`+`&&i&&!i.startsWith(`(`)){if(d)throw Error(`Invalid quantifier "${s}"`);let t=-1;if(/^\{\d+\}$/.test(l))e=ky(e,c+l.length,u,``);else{if(i===`)`||i===`]`){let t=i===`)`?n:r;if(t===null)throw Error(`Invalid unmatched "${i}"`);e=`${e.slice(0,t)}(?>${e.slice(t,c)}${l})${e.slice(c+s.length)}`}else e=`${e.slice(0,c-i.length)}(?>${i}${l})${e.slice(c+s.length)}`;t+=4}zy.lastIndex+=t}else s[0]===`(`?t.push(c):s===`)`&&(n=t.length?t.pop():null)}i=s}return{pattern:e}}var Vy=String.raw,Hy=Vy`\(\?R=(?<rDepth>[^\)]+)\)|${Vy`\\g<(?<gRNameOrNum>[^>&]+)&R=(?<gRDepth>[^>]+)>`}`,Uy=Vy`\(\?<(?![=!])(?<captureName>[^>]+)>`,Wy=Vy`${Uy}|(?<unnamed>\()(?!\?)`,Gy=new RegExp(Vy`${Uy}|${Hy}|\(\?|\\?.`,`gsu`),Ky=`Cannot use multiple overlapping recursions`;function qy(e,t){let{hiddenCaptures:n,mode:r}={hiddenCaptures:[],mode:`plugin`,...t},i=t?.captureTransfers??new Map;if(!new RegExp(Hy,`su`).test(e))return{pattern:e,captureTransfers:i,hiddenCaptures:n};if(r===`plugin`&&Py(e,Vy`\(\?\(DEFINE\)`,Ay.DEFAULT))throw Error(`DEFINE groups cannot be used with recursion`);let a=[],o=Py(e,Vy`\\[1-9]`,Ay.DEFAULT),s=new Map,c=[],l=!1,u=0,d=0,f;for(Gy.lastIndex=0;f=Gy.exec(e);){let{0:t,groups:{captureName:p,rDepth:m,gRNameOrNum:h,gRDepth:g}}=f;if(t===`[`)u++;else if(u)t===`]`&&u--;else{if(m){if(Jy(m),l)throw Error(Ky);if(o)throw Error(`${r===`external`?`Backrefs`:`Numbered backrefs`} cannot be used with global recursion`);let t=e.slice(0,f.index),s=e.slice(Gy.lastIndex);if(Py(s,Hy,Ay.DEFAULT))throw Error(Ky);let c=m-1;e=Yy(t,s,c,!1,n,a,d),i=Qy(i,t,c,a.length,0,d);break}if(h){Jy(g);let u=!1;for(let e of c)if(e.name===h||e.num===+h){if(u=!0,e.hasRecursedWithin)throw Error(Ky);break}if(!u)throw Error(Vy`Recursive \g cannot be used outside the referenced group "${r===`external`?h:Vy`\g<${h}&R=${g}>`}"`);let p=s.get(h),m=Fy(e,p);if(o&&Py(m,Vy`${Uy}|\((?!\?)`,Ay.DEFAULT))throw Error(`${r===`external`?`Backrefs`:`Numbered backrefs`} cannot be used with recursion of capturing groups`);let _=e.slice(p,f.index),v=m.slice(_.length+t.length),ee=a.length,y=g-1,b=Yy(_,v,y,!0,n,a,d);i=Qy(i,_,y,a.length-ee,ee,d),e=`${e.slice(0,p)}${b}${e.slice(p+m.length)}`,Gy.lastIndex+=b.length-t.length-_.length-v.length,c.forEach(e=>e.hasRecursedWithin=!0),l=!0}else if(p)d++,s.set(String(d),Gy.lastIndex),s.set(p,Gy.lastIndex),c.push({num:d,name:p});else if(t[0]===`(`){let e=t===`(`;e&&(d++,s.set(String(d),Gy.lastIndex)),c.push(e?{num:d}:{})}else t===`)`&&c.pop()}}return n.push(...a),{pattern:e,captureTransfers:i,hiddenCaptures:n}}function Jy(e){let t=`Max depth must be integer between 2 and 100; used ${e}`;if(!/^[1-9]\d*$/.test(e)||(e=+e,e<2||e>100))throw Error(t)}function Yy(e,t,n,r,i,a,o){let s=new Set;r&&My(e+t,Uy,({groups:{captureName:e}})=>{s.add(e)},Ay.DEFAULT);let c=[n,r?s:null,i,a,o];return`${e}${Xy(`(?:${e}`,`forward`,...c)}(?:)${Xy(`${t})`,`backward`,...c)}${t}`}function Xy(e,t,n,r,i,a,o){let s=e=>t===`forward`?e+2:n-e+2-1,c=``;for(let t=0;t<n;t++){let n=s(t);c+=jy(e,Vy`${Wy}|\\k<(?<backref>[^>]+)>`,({0:e,groups:{captureName:t,unnamed:s,backref:c}})=>{if(c&&r&&!r.has(c))return e;let l=`_$${n}`;if(s||t){let n=o+a.length+1;return a.push(n),Zy(i,n),s?e:`(?<${t}${l}>`}return Vy`\k<${c}${l}>`},Ay.DEFAULT)}return c}function Zy(e,t){for(let n=0;n<e.length;n++)e[n]>=t&&e[n]++}function Qy(e,t,n,r,i,a){if(e.size&&r){let o=0;My(t,Wy,()=>o++,Ay.DEFAULT);let s=a-o+i,c=new Map;return e.forEach((e,t)=>{let i=(r-o*n)/n,a=o*n,l=t>s+o?t+r:t,u=[];for(let t of e)if(t<=s)u.push(t);else if(t>s+o+i)u.push(t+r);else if(t<=s+o)for(let e=0;e<=n;e++)u.push(t+o*e);else for(let e=0;e<=n;e++)u.push(t+a+i*e);c.set(l,u)}),c}return e}var $y=String.fromCodePoint,$=String.raw,eb={},tb=globalThis.RegExp;eb.flagGroups=(()=>{try{new tb(`(?i:)`)}catch{return!1}return!0})(),eb.unicodeSets=(()=>{try{new tb(`[[]]`,`v`)}catch{return!1}return!0})(),eb.bugFlagVLiteralHyphenIsRange=eb.unicodeSets?(()=>{try{new tb($`[\d\-a]`,`v`)}catch{return!0}return!1})():!1,eb.bugNestedClassIgnoresNegation=eb.unicodeSets&&new tb(`[[^a]]`,`v`).test(`a`);function nb(e,{enable:t,disable:n}){return{dotAll:!n?.dotAll&&!!(t?.dotAll||e.dotAll),ignoreCase:!n?.ignoreCase&&!!(t?.ignoreCase||e.ignoreCase)}}function rb(e,t,n){return e.has(t)||e.set(t,n),e.get(t)}function ib(e,t){return ob[e]>=ob[t]}function ab(e,t){if(e==null)throw Error(t??`Value expected`);return e}var ob={ES2025:2025,ES2024:2024,ES2018:2018},sb={auto:`auto`,ES2025:`ES2025`,ES2024:`ES2024`,ES2018:`ES2018`};function cb(e={}){if({}.toString.call(e)!==`[object Object]`)throw Error(`Unexpected options`);if(e.target!==void 0&&!sb[e.target])throw Error(`Unexpected target "${e.target}"`);let t={accuracy:`default`,avoidSubclass:!1,flags:``,global:!1,hasIndices:!1,lazyCompileLength:1/0,target:`auto`,verbose:!1,...e,rules:{allowOrphanBackrefs:!1,asciiWordBoundaries:!1,captureGroup:!1,recursionLimit:20,singleline:!1,...e.rules}};return t.target===`auto`&&(t.target=eb.flagGroups?`ES2025`:eb.unicodeSets?`ES2024`:`ES2018`),t}var lb=`[ -\r ]`,ub=new Set([$y(304),$y(305)]),db=$`[\p{L}\p{M}\p{N}\p{Pc}]`;function fb(e){if(ub.has(e))return[e];let t=new Set,n=e.toLowerCase(),r=n.toUpperCase(),i=gb.get(n),a=mb.get(n),o=hb.get(n);return[...r].length===1&&t.add(r),o&&t.add(o),i&&t.add(i),t.add(n),a&&t.add(a),[...t]}var pb=new Map(`C Other
82
+ `.replace(/\s+/g,``),`gsu`);function Vy(e){if(!RegExp(`${zy}\\+`).test(e))return{pattern:e};let t=[],n=null,r=null,i=``,a=0,o;for(By.lastIndex=0;o=By.exec(e);){let{0:s,index:c,groups:{qBase:l,qMod:u,invalidQ:d}}=o;if(s===`[`)a||(r=c),a++;else if(s===`]`)a?a--:r=null;else if(!a){if(u===`+`&&i&&!i.startsWith(`(`)){if(d)throw Error(`Invalid quantifier "${s}"`);let t=-1;if(/^\{\d+\}$/.test(l))e=Ay(e,c+l.length,u,``);else{if(i===`)`||i===`]`){let t=i===`)`?n:r;if(t===null)throw Error(`Invalid unmatched "${i}"`);e=`${e.slice(0,t)}(?>${e.slice(t,c)}${l})${e.slice(c+s.length)}`}else e=`${e.slice(0,c-i.length)}(?>${i}${l})${e.slice(c+s.length)}`;t+=4}By.lastIndex+=t}else s[0]===`(`?t.push(c):s===`)`&&(n=t.length?t.pop():null)}i=s}return{pattern:e}}var Hy=String.raw,Uy=Hy`\(\?R=(?<rDepth>[^\)]+)\)|${Hy`\\g<(?<gRNameOrNum>[^>&]+)&R=(?<gRDepth>[^>]+)>`}`,Wy=Hy`\(\?<(?![=!])(?<captureName>[^>]+)>`,Gy=Hy`${Wy}|(?<unnamed>\()(?!\?)`,Ky=new RegExp(Hy`${Wy}|${Uy}|\(\?|\\?.`,`gsu`),qy=`Cannot use multiple overlapping recursions`;function Jy(e,t){let{hiddenCaptures:n,mode:r}={hiddenCaptures:[],mode:`plugin`,...t},i=t?.captureTransfers??new Map;if(!new RegExp(Uy,`su`).test(e))return{pattern:e,captureTransfers:i,hiddenCaptures:n};if(r===`plugin`&&Fy(e,Hy`\(\?\(DEFINE\)`,jy.DEFAULT))throw Error(`DEFINE groups cannot be used with recursion`);let a=[],o=Fy(e,Hy`\\[1-9]`,jy.DEFAULT),s=new Map,c=[],l=!1,u=0,d=0,f;for(Ky.lastIndex=0;f=Ky.exec(e);){let{0:t,groups:{captureName:p,rDepth:m,gRNameOrNum:h,gRDepth:g}}=f;if(t===`[`)u++;else if(u)t===`]`&&u--;else{if(m){if(Yy(m),l)throw Error(qy);if(o)throw Error(`${r===`external`?`Backrefs`:`Numbered backrefs`} cannot be used with global recursion`);let t=e.slice(0,f.index),s=e.slice(Ky.lastIndex);if(Fy(s,Uy,jy.DEFAULT))throw Error(qy);let c=m-1;e=Xy(t,s,c,!1,n,a,d),i=$y(i,t,c,a.length,0,d);break}if(h){Yy(g);let u=!1;for(let e of c)if(e.name===h||e.num===+h){if(u=!0,e.hasRecursedWithin)throw Error(qy);break}if(!u)throw Error(Hy`Recursive \g cannot be used outside the referenced group "${r===`external`?h:Hy`\g<${h}&R=${g}>`}"`);let p=s.get(h),m=Iy(e,p);if(o&&Fy(m,Hy`${Wy}|\((?!\?)`,jy.DEFAULT))throw Error(`${r===`external`?`Backrefs`:`Numbered backrefs`} cannot be used with recursion of capturing groups`);let _=e.slice(p,f.index),v=m.slice(_.length+t.length),ee=a.length,y=g-1,b=Xy(_,v,y,!0,n,a,d);i=$y(i,_,y,a.length-ee,ee,d),e=`${e.slice(0,p)}${b}${e.slice(p+m.length)}`,Ky.lastIndex+=b.length-t.length-_.length-v.length,c.forEach(e=>e.hasRecursedWithin=!0),l=!0}else if(p)d++,s.set(String(d),Ky.lastIndex),s.set(p,Ky.lastIndex),c.push({num:d,name:p});else if(t[0]===`(`){let e=t===`(`;e&&(d++,s.set(String(d),Ky.lastIndex)),c.push(e?{num:d}:{})}else t===`)`&&c.pop()}}return n.push(...a),{pattern:e,captureTransfers:i,hiddenCaptures:n}}function Yy(e){let t=`Max depth must be integer between 2 and 100; used ${e}`;if(!/^[1-9]\d*$/.test(e)||(e=+e,e<2||e>100))throw Error(t)}function Xy(e,t,n,r,i,a,o){let s=new Set;r&&Ny(e+t,Wy,({groups:{captureName:e}})=>{s.add(e)},jy.DEFAULT);let c=[n,r?s:null,i,a,o];return`${e}${Zy(`(?:${e}`,`forward`,...c)}(?:)${Zy(`${t})`,`backward`,...c)}${t}`}function Zy(e,t,n,r,i,a,o){let s=e=>t===`forward`?e+2:n-e+2-1,c=``;for(let t=0;t<n;t++){let n=s(t);c+=My(e,Hy`${Gy}|\\k<(?<backref>[^>]+)>`,({0:e,groups:{captureName:t,unnamed:s,backref:c}})=>{if(c&&r&&!r.has(c))return e;let l=`_$${n}`;if(s||t){let n=o+a.length+1;return a.push(n),Qy(i,n),s?e:`(?<${t}${l}>`}return Hy`\k<${c}${l}>`},jy.DEFAULT)}return c}function Qy(e,t){for(let n=0;n<e.length;n++)e[n]>=t&&e[n]++}function $y(e,t,n,r,i,a){if(e.size&&r){let o=0;Ny(t,Gy,()=>o++,jy.DEFAULT);let s=a-o+i,c=new Map;return e.forEach((e,t)=>{let i=(r-o*n)/n,a=o*n,l=t>s+o?t+r:t,u=[];for(let t of e)if(t<=s)u.push(t);else if(t>s+o+i)u.push(t+r);else if(t<=s+o)for(let e=0;e<=n;e++)u.push(t+o*e);else for(let e=0;e<=n;e++)u.push(t+a+i*e);c.set(l,u)}),c}return e}var eb=String.fromCodePoint,$=String.raw,tb={},nb=globalThis.RegExp;tb.flagGroups=(()=>{try{new nb(`(?i:)`)}catch{return!1}return!0})(),tb.unicodeSets=(()=>{try{new nb(`[[]]`,`v`)}catch{return!1}return!0})(),tb.bugFlagVLiteralHyphenIsRange=tb.unicodeSets?(()=>{try{new nb($`[\d\-a]`,`v`)}catch{return!0}return!1})():!1,tb.bugNestedClassIgnoresNegation=tb.unicodeSets&&new nb(`[[^a]]`,`v`).test(`a`);function rb(e,{enable:t,disable:n}){return{dotAll:!n?.dotAll&&!!(t?.dotAll||e.dotAll),ignoreCase:!n?.ignoreCase&&!!(t?.ignoreCase||e.ignoreCase)}}function ib(e,t,n){return e.has(t)||e.set(t,n),e.get(t)}function ab(e,t){return sb[e]>=sb[t]}function ob(e,t){if(e==null)throw Error(t??`Value expected`);return e}var sb={ES2025:2025,ES2024:2024,ES2018:2018},cb={auto:`auto`,ES2025:`ES2025`,ES2024:`ES2024`,ES2018:`ES2018`};function lb(e={}){if({}.toString.call(e)!==`[object Object]`)throw Error(`Unexpected options`);if(e.target!==void 0&&!cb[e.target])throw Error(`Unexpected target "${e.target}"`);let t={accuracy:`default`,avoidSubclass:!1,flags:``,global:!1,hasIndices:!1,lazyCompileLength:1/0,target:`auto`,verbose:!1,...e,rules:{allowOrphanBackrefs:!1,asciiWordBoundaries:!1,captureGroup:!1,recursionLimit:20,singleline:!1,...e.rules}};return t.target===`auto`&&(t.target=tb.flagGroups?`ES2025`:tb.unicodeSets?`ES2024`:`ES2018`),t}var ub=`[ -\r ]`,db=new Set([eb(304),eb(305)]),fb=$`[\p{L}\p{M}\p{N}\p{Pc}]`;function pb(e){if(db.has(e))return[e];let t=new Set,n=e.toLowerCase(),r=n.toUpperCase(),i=_b.get(n),a=hb.get(n),o=gb.get(n);return[...r].length===1&&t.add(r),o&&t.add(o),i&&t.add(i),t.add(n),a&&t.add(a),[...t]}var mb=new Map(`C Other
83
83
  Cc Control cntrl
84
84
  Cf Format
85
85
  Cn Unassigned
@@ -169,22 +169,22 @@ Uppercase Upper
169
169
  Variation_Selector VS
170
170
  White_Space space
171
171
  XID_Continue XIDC
172
- XID_Start XIDS`.split(/\s/).map(e=>[xy(e),e])),mb=new Map([[`s`,$y(383)],[$y(383),`s`]]),hb=new Map([[$y(223),$y(7838)],[$y(107),$y(8490)],[$y(229),$y(8491)],[$y(969),$y(8486)]]),gb=new Map([yb(453),yb(456),yb(459),yb(498),...bb(8072,8079),...bb(8088,8095),...bb(8104,8111),yb(8124),yb(8140),yb(8188)]),_b=new Map([[`alnum`,$`[\p{Alpha}\p{Nd}]`],[`alpha`,$`\p{Alpha}`],[`ascii`,$`\p{ASCII}`],[`blank`,$`[\p{Zs}\t]`],[`cntrl`,$`\p{Cc}`],[`digit`,$`\p{Nd}`],[`graph`,$`[\P{space}&&\P{Cc}&&\P{Cn}&&\P{Cs}]`],[`lower`,$`\p{Lower}`],[`print`,$`[[\P{space}&&\P{Cc}&&\P{Cn}&&\P{Cs}]\p{Zs}]`],[`punct`,$`[\p{P}\p{S}]`],[`space`,$`\p{space}`],[`upper`,$`\p{Upper}`],[`word`,$`[\p{Alpha}\p{M}\p{Nd}\p{Pc}]`],[`xdigit`,$`\p{AHex}`]]);function vb(e,t){let n=[];for(let r=e;r<=t;r++)n.push(r);return n}function yb(e){let t=$y(e);return[t.toLowerCase(),t]}function bb(e,t){return vb(e,t).map(e=>yb(e))}var xb=new Set([`Lower`,`Lowercase`,`Upper`,`Uppercase`,`Ll`,`Lowercase_Letter`,`Lt`,`Titlecase_Letter`,`Lu`,`Uppercase_Letter`]);function Sb(e,t){let n={accuracy:`default`,asciiWordBoundaries:!1,avoidSubclass:!1,bestEffortTarget:`ES2025`,...t};Eb(e);let r={accuracy:n.accuracy,asciiWordBoundaries:n.asciiWordBoundaries,avoidSubclass:n.avoidSubclass,flagDirectivesByAlt:new Map,jsGroupNameMap:new Map,minTargetEs2024:ib(n.bestEffortTarget,`ES2024`),passedLookbehind:!1,strategy:null,subroutineRefMap:new Map,supportedGNodes:new Set,digitIsAscii:e.flags.digitIsAscii,spaceIsAscii:e.flags.spaceIsAscii,wordIsAscii:e.flags.wordIsAscii};wy(e,Cb,r);let i={dotAll:e.flags.dotAll,ignoreCase:e.flags.ignoreCase},a={currentFlags:i,prevFlags:null,globalFlags:i,groupOriginByCopy:new Map,groupsByName:new Map,multiplexCapturesToLeftByRef:new Map,openRefs:new Map,reffedNodesByReferencer:new Map,subroutineRefMap:r.subroutineRefMap};return wy(e,wb,a),wy(e,Tb,{groupsByName:a.groupsByName,highestOrphanBackref:0,numCapturesToLeft:0,reffedNodesByReferencer:a.reffedNodesByReferencer}),e._originMap=a.groupOriginByCopy,e._strategy=r.strategy,e}var Cb={AbsenceFunction({node:e,parent:t,replaceWith:n}){let{body:r,kind:i}=e;if(i===`repeater`){let e=oy();e.body[0].body.push(sy({negate:!0,body:r}),py(`Any`));let i=oy();i.body[0].body.push(uy(`greedy`,0,1/0,e)),n(Gb(i,t),{traverse:!0})}else throw Error(`Unsupported absence function "(?~|"`)},Alternative:{enter({node:e,parent:t,key:n},{flagDirectivesByAlt:r}){let i=e.body.filter(e=>e.kind===`flags`);for(let e=n+1;e<t.body.length;e++){let n=t.body[e];rb(r,n,[]).push(...i)}},exit({node:e},{flagDirectivesByAlt:t}){if(t.get(e)?.length){let n=Nb(t.get(e));if(n){let t=oy({flags:n});t.body[0].body=e.body,e.body=[Gb(t,e)]}}}},Assertion({node:e,parent:t,key:n,container:r,root:i,remove:a,replaceWith:o},s){let{kind:c,negate:l}=e,{asciiWordBoundaries:u,avoidSubclass:d,supportedGNodes:f,wordIsAscii:p}=s;if(c===`text_segment_boundary`)throw Error(`Unsupported text segment boundary "\\${l?`Y`:`y`}"`);if(c===`line_end`)o(Gb(sy({body:[Xv({body:[Zv(`string_end`)]}),Xv({body:[ey(10)]})]}),t));else if(c===`line_start`)o(Gb(Hb($`(?<=\A|\n(?!\z))`,{skipLookbehindValidation:!0}),t));else if(c===`search_start`){if(f.has(e))i.flags.sticky=!0,a();else{let e=r[n-1];if(e&&zb(e))o(Gb(sy({negate:!0}),t));else if(d)throw Error($`Uses "\G" in a way that requires a subclass`);else o(Wb(Zv(`string_start`),t)),s.strategy=`clip_search`}}else if(c!==`string_end`&&c!==`string_start`){if(c===`string_end_newline`)o(Gb(Hb($`(?=\n?\z)`),t));else if(c===`word_boundary`){if(!p&&!u){let e=`(?:(?<=${db})(?!${db})|(?<!${db})(?=${db}))`,n=`(?:(?<=${db})(?=${db})|(?<!${db})(?!${db}))`;o(Gb(Hb(l?n:e),t))}}else throw Error(`Unexpected assertion kind "${c}"`)}},Backreference({node:e},{jsGroupNameMap:t}){let{ref:n}=e;typeof n==`string`&&!Vb(n)&&(n=Mb(n,t),e.ref=n)},CapturingGroup({node:e},{jsGroupNameMap:t,subroutineRefMap:n}){let{name:r}=e;r&&!Vb(r)&&(r=Mb(r,t),e.name=r),n.set(e.number,e),r&&n.set(r,e)},CharacterClassRange({node:e,parent:t,replaceWith:n}){t.kind===`intersection`&&n(Gb(ty({body:[e]}),t),{traverse:!0})},CharacterSet({node:e,parent:t,replaceWith:n},{accuracy:r,minTargetEs2024:i,digitIsAscii:a,spaceIsAscii:o,wordIsAscii:s}){let{kind:c,negate:l,value:u}=e;if(a&&(c===`digit`||u===`digit`))n(Wb(ry(`digit`,{negate:l}),t));else if(o&&(c===`space`||u===`space`))n(Gb(Ub(Hb(lb),l),t));else if(s&&(c===`word`||u===`word`))n(Wb(ry(`word`,{negate:l}),t));else if(c===`any`)n(Wb(py(`Any`),t));else if(c===`digit`)n(Wb(py(`Nd`,{negate:l}),t));else if(c!==`dot`){if(c===`text_segment`){if(r===`strict`)throw Error($`Use of "\X" requires non-strict accuracy`);let e=`\\p{Emoji}(?:\\p{EMod}|\\uFE0F\\u20E3?|[\\x{E0020}-\\x{E007E}]+\\x{E007F})?`,a=$`\p{RI}{2}|${e}(?:\u200D${e})*`;n(Gb(Hb($`(?>\r\n|${i?$`\p{RGI_Emoji}`:a}|\P{M}\p{M}*)`,{skipPropertyNameValidation:!0}),t))}else if(c===`hex`)n(Wb(py(`AHex`,{negate:l}),t));else if(c===`newline`)n(Gb(Hb(l?`[^
172
+ XID_Start XIDS`.split(/\s/).map(e=>[Sy(e),e])),hb=new Map([[`s`,eb(383)],[eb(383),`s`]]),gb=new Map([[eb(223),eb(7838)],[eb(107),eb(8490)],[eb(229),eb(8491)],[eb(969),eb(8486)]]),_b=new Map([bb(453),bb(456),bb(459),bb(498),...xb(8072,8079),...xb(8088,8095),...xb(8104,8111),bb(8124),bb(8140),bb(8188)]),vb=new Map([[`alnum`,$`[\p{Alpha}\p{Nd}]`],[`alpha`,$`\p{Alpha}`],[`ascii`,$`\p{ASCII}`],[`blank`,$`[\p{Zs}\t]`],[`cntrl`,$`\p{Cc}`],[`digit`,$`\p{Nd}`],[`graph`,$`[\P{space}&&\P{Cc}&&\P{Cn}&&\P{Cs}]`],[`lower`,$`\p{Lower}`],[`print`,$`[[\P{space}&&\P{Cc}&&\P{Cn}&&\P{Cs}]\p{Zs}]`],[`punct`,$`[\p{P}\p{S}]`],[`space`,$`\p{space}`],[`upper`,$`\p{Upper}`],[`word`,$`[\p{Alpha}\p{M}\p{Nd}\p{Pc}]`],[`xdigit`,$`\p{AHex}`]]);function yb(e,t){let n=[];for(let r=e;r<=t;r++)n.push(r);return n}function bb(e){let t=eb(e);return[t.toLowerCase(),t]}function xb(e,t){return yb(e,t).map(e=>bb(e))}var Sb=new Set([`Lower`,`Lowercase`,`Upper`,`Uppercase`,`Ll`,`Lowercase_Letter`,`Lt`,`Titlecase_Letter`,`Lu`,`Uppercase_Letter`]);function Cb(e,t){let n={accuracy:`default`,asciiWordBoundaries:!1,avoidSubclass:!1,bestEffortTarget:`ES2025`,...t};Db(e);let r={accuracy:n.accuracy,asciiWordBoundaries:n.asciiWordBoundaries,avoidSubclass:n.avoidSubclass,flagDirectivesByAlt:new Map,jsGroupNameMap:new Map,minTargetEs2024:ab(n.bestEffortTarget,`ES2024`),passedLookbehind:!1,strategy:null,subroutineRefMap:new Map,supportedGNodes:new Set,digitIsAscii:e.flags.digitIsAscii,spaceIsAscii:e.flags.spaceIsAscii,wordIsAscii:e.flags.wordIsAscii};Ty(e,wb,r);let i={dotAll:e.flags.dotAll,ignoreCase:e.flags.ignoreCase},a={currentFlags:i,prevFlags:null,globalFlags:i,groupOriginByCopy:new Map,groupsByName:new Map,multiplexCapturesToLeftByRef:new Map,openRefs:new Map,reffedNodesByReferencer:new Map,subroutineRefMap:r.subroutineRefMap};return Ty(e,Tb,a),Ty(e,Eb,{groupsByName:a.groupsByName,highestOrphanBackref:0,numCapturesToLeft:0,reffedNodesByReferencer:a.reffedNodesByReferencer}),e._originMap=a.groupOriginByCopy,e._strategy=r.strategy,e}var wb={AbsenceFunction({node:e,parent:t,replaceWith:n}){let{body:r,kind:i}=e;if(i===`repeater`){let e=sy();e.body[0].body.push(cy({negate:!0,body:r}),my(`Any`));let i=sy();i.body[0].body.push(dy(`greedy`,0,1/0,e)),n(Kb(i,t),{traverse:!0})}else throw Error(`Unsupported absence function "(?~|"`)},Alternative:{enter({node:e,parent:t,key:n},{flagDirectivesByAlt:r}){let i=e.body.filter(e=>e.kind===`flags`);for(let e=n+1;e<t.body.length;e++){let n=t.body[e];ib(r,n,[]).push(...i)}},exit({node:e},{flagDirectivesByAlt:t}){if(t.get(e)?.length){let n=Pb(t.get(e));if(n){let t=sy({flags:n});t.body[0].body=e.body,e.body=[Kb(t,e)]}}}},Assertion({node:e,parent:t,key:n,container:r,root:i,remove:a,replaceWith:o},s){let{kind:c,negate:l}=e,{asciiWordBoundaries:u,avoidSubclass:d,supportedGNodes:f,wordIsAscii:p}=s;if(c===`text_segment_boundary`)throw Error(`Unsupported text segment boundary "\\${l?`Y`:`y`}"`);if(c===`line_end`)o(Kb(cy({body:[Zv({body:[Qv(`string_end`)]}),Zv({body:[ty(10)]})]}),t));else if(c===`line_start`)o(Kb(Ub($`(?<=\A|\n(?!\z))`,{skipLookbehindValidation:!0}),t));else if(c===`search_start`){if(f.has(e))i.flags.sticky=!0,a();else{let e=r[n-1];if(e&&Bb(e))o(Kb(cy({negate:!0}),t));else if(d)throw Error($`Uses "\G" in a way that requires a subclass`);else o(Gb(Qv(`string_start`),t)),s.strategy=`clip_search`}}else if(c!==`string_end`&&c!==`string_start`){if(c===`string_end_newline`)o(Kb(Ub($`(?=\n?\z)`),t));else if(c===`word_boundary`){if(!p&&!u){let e=`(?:(?<=${fb})(?!${fb})|(?<!${fb})(?=${fb}))`,n=`(?:(?<=${fb})(?=${fb})|(?<!${fb})(?!${fb}))`;o(Kb(Ub(l?n:e),t))}}else throw Error(`Unexpected assertion kind "${c}"`)}},Backreference({node:e},{jsGroupNameMap:t}){let{ref:n}=e;typeof n==`string`&&!Hb(n)&&(n=Nb(n,t),e.ref=n)},CapturingGroup({node:e},{jsGroupNameMap:t,subroutineRefMap:n}){let{name:r}=e;r&&!Hb(r)&&(r=Nb(r,t),e.name=r),n.set(e.number,e),r&&n.set(r,e)},CharacterClassRange({node:e,parent:t,replaceWith:n}){t.kind===`intersection`&&n(Kb(ny({body:[e]}),t),{traverse:!0})},CharacterSet({node:e,parent:t,replaceWith:n},{accuracy:r,minTargetEs2024:i,digitIsAscii:a,spaceIsAscii:o,wordIsAscii:s}){let{kind:c,negate:l,value:u}=e;if(a&&(c===`digit`||u===`digit`))n(Gb(iy(`digit`,{negate:l}),t));else if(o&&(c===`space`||u===`space`))n(Kb(Wb(Ub(ub),l),t));else if(s&&(c===`word`||u===`word`))n(Gb(iy(`word`,{negate:l}),t));else if(c===`any`)n(Gb(my(`Any`),t));else if(c===`digit`)n(Gb(my(`Nd`,{negate:l}),t));else if(c!==`dot`){if(c===`text_segment`){if(r===`strict`)throw Error($`Use of "\X" requires non-strict accuracy`);let e=`\\p{Emoji}(?:\\p{EMod}|\\uFE0F\\u20E3?|[\\x{E0020}-\\x{E007E}]+\\x{E007F})?`,a=$`\p{RI}{2}|${e}(?:\u200D${e})*`;n(Kb(Ub($`(?>\r\n|${i?$`\p{RGI_Emoji}`:a}|\P{M}\p{M}*)`,{skipPropertyNameValidation:!0}),t))}else if(c===`hex`)n(Gb(my(`AHex`,{negate:l}),t));else if(c===`newline`)n(Kb(Ub(l?`[^
173
173
  ]`:`(?>\r
174
174
  ?|[
175
- \v\f…\u2028\u2029])`),t));else if(c===`posix`){if(!i&&(u===`graph`||u===`print`)){if(r===`strict`)throw Error(`POSIX class "${u}" requires min target ES2024 or non-strict accuracy`);let e={graph:`!-~`,print:` -~`}[u];l&&(e=`\0-${$y(e.codePointAt(0)-1)}${$y(e.codePointAt(2)+1)}-\u{10FFFF}`),n(Gb(Hb(`[${e}]`),t))}else n(Gb(Ub(Hb(_b.get(u)),l),t))}else if(c===`property`)pb.has(xy(u))||(e.key=`sc`);else if(c===`space`)n(Wb(py(`space`,{negate:l}),t));else if(c===`word`)n(Gb(Ub(Hb(db),l),t));else throw Error(`Unexpected character set kind "${c}"`)}},Directive({node:e,parent:t,root:n,remove:r,replaceWith:i,removeAllPrevSiblings:a,removeAllNextSiblings:o}){let{kind:s,flags:c}=e;if(s===`flags`){if(!c.enable&&!c.disable)r();else{let e=oy({flags:c});e.body[0].body=o(),i(Gb(e,t),{traverse:!0})}}else if(s===`keep`){let e=n.body[0],r=n.body.length===1&&Lv(e,{type:`Group`})&&e.body[0].body.length===1?e.body[0]:n;if(t.parent!==r||r.body.length>1)throw Error($`Uses "\K" in a way that's unsupported`);let o=sy({behind:!0});o.body[0].body=a(),i(Gb(o,t))}else throw Error(`Unexpected directive kind "${s}"`)},Flags({node:e,parent:t}){if(e.posixIsAscii)throw Error(`Unsupported flag "P"`);if(e.textSegmentMode===`word`)throw Error(`Unsupported flag "y{w}"`);[`digitIsAscii`,`extended`,`posixIsAscii`,`spaceIsAscii`,`wordIsAscii`,`textSegmentMode`].forEach(t=>delete e[t]),Object.assign(e,{global:!1,hasIndices:!1,multiline:!1,sticky:e.sticky??!1}),t.options={disable:{x:!0,n:!0},force:{v:!0}}},Group({node:e}){if(!e.flags)return;let{enable:t,disable:n}=e.flags;t?.extended&&delete t.extended,n?.extended&&delete n.extended,t?.dotAll&&n?.dotAll&&delete t.dotAll,t?.ignoreCase&&n?.ignoreCase&&delete t.ignoreCase,t&&!Object.keys(t).length&&delete e.flags.enable,n&&!Object.keys(n).length&&delete e.flags.disable,!e.flags.enable&&!e.flags.disable&&delete e.flags},LookaroundAssertion({node:e},t){let{kind:n}=e;n===`lookbehind`&&(t.passedLookbehind=!0)},NamedCallout({node:e,parent:t,replaceWith:n}){let{kind:r}=e;if(r===`fail`)n(Gb(sy({negate:!0}),t));else throw Error(`Unsupported named callout "(*${r.toUpperCase()}"`)},Quantifier({node:e}){if(e.body.type===`Quantifier`){let t=oy();t.body[0].body.push(e.body),e.body=Gb(t,e)}},Regex:{enter({node:e},{supportedGNodes:t}){let n=[],r=!1,i=!1;for(let t of e.body)if(t.body.length===1&&t.body[0].kind===`search_start`)t.body.pop();else{let e=Ib(t.body);e?(r=!0,Array.isArray(e)?n.push(...e):n.push(e)):i=!0}r&&!i&&n.forEach(e=>t.add(e))},exit(e,{accuracy:t,passedLookbehind:n,strategy:r}){if(t===`strict`&&n&&r)throw Error($`Uses "\G" in a way that requires non-strict accuracy`)}},Subroutine({node:e},{jsGroupNameMap:t}){let{ref:n}=e;typeof n==`string`&&!Vb(n)&&(n=Mb(n,t),e.ref=n)}},wb={Backreference({node:e},{multiplexCapturesToLeftByRef:t,reffedNodesByReferencer:n}){let{orphan:r,ref:i}=e;r||n.set(e,[...t.get(i).map(({node:e})=>e)])},CapturingGroup:{enter({node:e,parent:t,replaceWith:n,skip:r},{groupOriginByCopy:i,groupsByName:a,multiplexCapturesToLeftByRef:o,openRefs:s,reffedNodesByReferencer:c}){let l=i.get(e);if(l&&s.has(e.number)){let r=Wb(Ab(e.number),t);c.set(r,s.get(e.number)),n(r);return}s.set(e.number,e),o.set(e.number,[]),e.name&&rb(o,e.name,[]);let u=o.get(e.name??e.number);for(let t=0;t<u.length;t++){let n=u[t];if(l===n.node||l&&l===n.origin||e===n.origin){u.splice(t,1);break}}if(o.get(e.number).push({node:e,origin:l}),e.name&&o.get(e.name).push({node:e,origin:l}),e.name){let t=rb(a,e.name,new Map),n=!1;if(l)n=!0;else for(let e of t.values())if(!e.hasDuplicateNameToRemove){n=!0;break}a.get(e.name).set(e,{node:e,hasDuplicateNameToRemove:n})}},exit({node:e},{openRefs:t}){t.get(e.number)===e&&t.delete(e.number)}},Group:{enter({node:e},t){t.prevFlags=t.currentFlags,e.flags&&(t.currentFlags=nb(t.currentFlags,e.flags))},exit(e,t){t.currentFlags=t.prevFlags}},Subroutine({node:e,parent:t,replaceWith:n},r){let{isRecursive:i,ref:a}=e;if(i){let n=t;for(;(n=n.parent)&&(n.type!==`CapturingGroup`||n.name!==a&&n.number!==a););r.reffedNodesByReferencer.set(e,n);return}let o=r.subroutineRefMap.get(a),s=a===0,c=s?Ab(0):kb(o,r.groupOriginByCopy,null),l=c;if(!s){let e=Nb(jb(o,e=>e.type===`Group`&&!!e.flags)),t=e?nb(r.globalFlags,e):r.globalFlags;Db(t,r.currentFlags)||(l=oy({flags:Pb(t)}),l.body[0].body.push(c))}n(Gb(l,t),{traverse:!s})}},Tb={Backreference({node:e,parent:t,replaceWith:n},r){if(e.orphan){r.highestOrphanBackref=Math.max(r.highestOrphanBackref,e.ref);return}let i=r.reffedNodesByReferencer.get(e).filter(t=>Ob(t,e));i.length?i.length>1?n(Gb(oy({atomic:!0,body:i.reverse().map(e=>Xv({body:[Qv(e.number)]}))}),t)):e.ref=i[0].number:n(Gb(sy({negate:!0}),t))},CapturingGroup({node:e},t){e.number=++t.numCapturesToLeft,e.name&&t.groupsByName.get(e.name).get(e).hasDuplicateNameToRemove&&delete e.name},Regex:{exit({node:e},t){let n=Math.max(t.highestOrphanBackref-t.numCapturesToLeft,0);for(let t=0;t<n;t++){let t=$v();e.body.at(-1).body.push(t)}}},Subroutine({node:e},t){e.isRecursive&&e.ref!==0&&(e.ref=t.reffedNodesByReferencer.get(e).number)}};function Eb(e){wy(e,{"*"({node:e,parent:t}){e.parent=t}})}function Db(e,t){return e.dotAll===t.dotAll&&e.ignoreCase===t.ignoreCase}function Ob(e,t){let n=t;do{if(n.type===`Regex`)return!1;if(n.type===`Alternative`)continue;if(n===e)return!1;let t=Fb(n.parent);for(let r of t){if(r===n)break;if(r===e||Lb(r,e))return!0}}while(n=n.parent);throw Error(`Unexpected path`)}function kb(e,t,n,r){let i=Array.isArray(e)?[]:{};for(let[a,o]of Object.entries(e))a===`parent`?i.parent=Array.isArray(n)?r:n:o&&typeof o==`object`?i[a]=kb(o,t,i,n):(a===`type`&&o===`CapturingGroup`&&t.set(i,t.get(e)??e),i[a]=o);return i}function Ab(e){let t=fy(e);return t.isRecursive=!0,t}function jb(e,t){let n=[];for(;e=e.parent;)(!t||t(e))&&n.push(e);return n}function Mb(e,t){if(t.has(e))return t.get(e);let n=`$${t.size}_${e.replace(/^[^$_\p{IDS}]|[^$\u200C\u200D\p{IDC}]/gu,`_`)}`;return t.set(e,n),n}function Nb(e){let t=[`dotAll`,`ignoreCase`],n={enable:{},disable:{}};return e.forEach(({flags:e})=>{t.forEach(t=>{e.enable?.[t]&&(delete n.disable[t],n.enable[t]=!0),e.disable?.[t]&&(n.disable[t]=!0)})}),Object.keys(n.enable).length||delete n.enable,Object.keys(n.disable).length||delete n.disable,n.enable||n.disable?n:null}function Pb({dotAll:e,ignoreCase:t}){let n={};return(e||t)&&(n.enable={},e&&(n.enable.dotAll=!0),t&&(n.enable.ignoreCase=!0)),(!e||!t)&&(n.disable={},!e&&(n.disable.dotAll=!0),!t&&(n.disable.ignoreCase=!0)),n}function Fb(e){if(!e)throw Error(`Node expected`);let{body:t}=e;return Array.isArray(t)?t:t?[t]:null}function Ib(e){let t=e.find(e=>e.kind===`search_start`||Bb(e,{negate:!1})||!Rb(e));if(!t)return null;if(t.kind===`search_start`)return t;if(t.type===`LookaroundAssertion`)return t.body[0].body[0];if(t.type===`CapturingGroup`||t.type===`Group`){let e=[];for(let n of t.body){let t=Ib(n.body);if(!t)return null;Array.isArray(t)?e.push(...t):e.push(t)}return e}return null}function Lb(e,t){let n=Fb(e)??[];for(let e of n)if(e===t||Lb(e,t))return!0;return!1}function Rb({type:e}){return e===`Assertion`||e===`Directive`||e===`LookaroundAssertion`}function zb(e){let t=[`Character`,`CharacterClass`,`CharacterSet`];return t.includes(e.type)||e.type===`Quantifier`&&e.min&&t.includes(e.body.type)}function Bb(e,t){let n={negate:null,...t};return e.type===`LookaroundAssertion`&&(n.negate===null||e.negate===n.negate)&&e.body.length===1&&Lv(e.body[0],{type:`Assertion`,kind:`search_start`})}function Vb(e){return/^[$_\p{IDS}][$\u200C\u200D\p{IDC}]*$/u.test(e)}function Hb(e,t){let n=Bv(e,{...t,unicodePropertyMap:pb}).body;return n.length>1||n[0].body.length>1?oy({body:n}):n[0].body[0]}function Ub(e,t){return e.negate=t,e}function Wb(e,t){return e.parent=t,e}function Gb(e,t){return Eb(e),e.parent=t,e}function Kb(e,t){let n=cb(t),r=ib(n.target,`ES2024`),i=ib(n.target,`ES2025`),a=n.rules.recursionLimit;if(!Number.isInteger(a)||a<2||a>20)throw Error(`Invalid recursionLimit; use 2-20`);let o=null,s=null;if(!i){let t=[e.flags.ignoreCase];wy(e,qb,{getCurrentModI:()=>t.at(-1),popModI(){t.pop()},pushModI(e){t.push(e)},setHasCasedChar(){t.at(-1)?o=!0:s=!0}})}let c={dotAll:e.flags.dotAll,ignoreCase:!(!e.flags.ignoreCase&&!o||s)},l=e,u={accuracy:n.accuracy,appliedGlobalFlags:c,captureMap:new Map,currentFlags:{dotAll:e.flags.dotAll,ignoreCase:e.flags.ignoreCase},inCharClass:!1,lastNode:l,originMap:e._originMap,recursionLimit:a,useAppliedIgnoreCase:!!(!i&&o&&s),useFlagMods:i,useFlagV:r,verbose:n.verbose};function d(e){return u.lastNode=l,l=e,ab(Jb[e.type],`Unexpected node type "${e.type}"`)(e,u,d)}let f={pattern:e.body.map(d).join(`|`),flags:d(e.flags),options:{...e.options}};return r||(delete f.options.force.v,f.options.disable.v=!0,f.options.unicodeSetsPlugin=null),f._captureTransfers=new Map,f._hiddenCaptures=[],u.captureMap.forEach((e,t)=>{e.hidden&&f._hiddenCaptures.push(t),e.transferTo&&rb(f._captureTransfers,e.transferTo,[]).push(t)}),f}var qb={"*":{enter({node:e},t){if(ox(e)){let n=t.getCurrentModI();t.pushModI(e.flags?nb({ignoreCase:n},e.flags).ignoreCase:n)}},exit({node:e},t){ox(e)&&t.popModI()}},Backreference(e,t){t.setHasCasedChar()},Character({node:e},t){ex($y(e.value))&&t.setHasCasedChar()},CharacterClassRange({node:e,skip:t},n){t(),tx(e,{firstOnly:!0}).length&&n.setHasCasedChar()},CharacterSet({node:e},t){e.kind===`property`&&xb.has(e.value)&&t.setHasCasedChar()}},Jb={Alternative({body:e},t,n){return e.map(n).join(``)},Assertion({kind:e,negate:t}){if(e===`string_end`)return`$`;if(e===`string_start`)return`^`;if(e===`word_boundary`)return t?$`\B`:$`\b`;throw Error(`Unexpected assertion kind "${e}"`)},Backreference({ref:e},t){if(typeof e!=`number`)throw Error(`Unexpected named backref in transformed AST`);if(!t.useFlagMods&&t.accuracy===`strict`&&t.currentFlags.ignoreCase&&!t.captureMap.get(e).ignoreCase)throw Error(`Use of case-insensitive backref to case-sensitive group requires target ES2025 or non-strict accuracy`);return`\\`+e},CapturingGroup(e,t,n){let{body:r,name:i,number:a}=e,o={ignoreCase:t.currentFlags.ignoreCase},s=t.originMap.get(e);return s&&(o.hidden=!0,a>s.number&&(o.transferTo=s.number)),t.captureMap.set(a,o),`(${i?`?<${i}>`:``}${r.map(n).join(`|`)})`},Character({value:e},t){let n=$y(e),r=nx(e,{escDigit:t.lastNode.type===`Backreference`,inCharClass:t.inCharClass,useFlagV:t.useFlagV});if(r!==n)return r;if(t.useAppliedIgnoreCase&&t.currentFlags.ignoreCase&&ex(n)){let e=fb(n);return t.inCharClass?e.join(``):e.length>1?`[${e.join(``)}]`:e[0]}return n},CharacterClass(e,t,n){let{kind:r,negate:i,parent:a}=e,{body:o}=e;if(r===`intersection`&&!t.useFlagV)throw Error(`Use of character class intersection requires min target ES2024`);eb.bugFlagVLiteralHyphenIsRange&&t.useFlagV&&o.some(cx)&&(o=[ey(45),...o.filter(e=>!cx(e))]);let s=()=>`[${i?`^`:``}${o.map(n).join(r===`intersection`?`&&`:``)}]`;if(!t.inCharClass){if((!t.useFlagV||eb.bugNestedClassIgnoresNegation)&&!i){let t=o.filter(e=>e.type===`CharacterClass`&&e.kind===`union`&&e.negate);if(t.length){let r=oy(),i=r.body[0];return r.parent=a,i.parent=r,o=o.filter(e=>!t.includes(e)),e.body=o,o.length?(e.parent=i,i.body.push(e)):r.body.pop(),t.forEach(e=>{let t=Xv({body:[e]});e.parent=t,t.parent=r,r.body.push(t)}),n(r)}}t.inCharClass=!0;let r=s();return t.inCharClass=!1,r}let c=o[0];if(r===`union`&&!i&&c&&((!t.useFlagV||!t.verbose)&&a.kind===`union`&&!(eb.bugFlagVLiteralHyphenIsRange&&t.useFlagV)||!t.verbose&&a.kind===`intersection`&&o.length===1&&c.type!==`CharacterClassRange`))return o.map(n).join(``);if(!t.useFlagV&&a.type===`CharacterClass`)throw Error(`Uses nested character class in a way that requires min target ES2024`);return s()},CharacterClassRange(e,t){let n=e.min.value,r=e.max.value,i={escDigit:!1,inCharClass:!0,useFlagV:t.useFlagV},a=nx(n,i),o=nx(r,i),s=new Set;return t.useAppliedIgnoreCase&&t.currentFlags.ignoreCase&&rx(tx(e)).forEach(e=>{s.add(Array.isArray(e)?`${nx(e[0],i)}-${nx(e[1],i)}`:nx(e,i))}),`${a}-${o}${[...s].join(``)}`},CharacterSet({kind:e,negate:t,value:n,key:r},i){if(e===`dot`)return i.currentFlags.dotAll?i.appliedGlobalFlags.dotAll||i.useFlagMods?`.`:`[^]`:$`[^\n]`;if(e===`digit`)return t?$`\D`:$`\d`;if(e===`property`){if(i.useAppliedIgnoreCase&&i.currentFlags.ignoreCase&&xb.has(n))throw Error(`Unicode property "${n}" can't be case-insensitive when other chars have specific case`);return`${t?$`\P`:$`\p`}{${r?`${r}=`:``}${n}}`}if(e===`word`)return t?$`\W`:$`\w`;throw Error(`Unexpected character set kind "${e}"`)},Flags(e,t){return(t.appliedGlobalFlags.ignoreCase?`i`:``)+(e.dotAll?`s`:``)+(e.sticky?`y`:``)},Group({atomic:e,body:t,flags:n,parent:r},i,a){let o=i.currentFlags;n&&(i.currentFlags=nb(o,n));let s=t.map(a).join(`|`),c=!i.verbose&&t.length===1&&r.type!==`Quantifier`&&!e&&(!i.useFlagMods||!n)?s:`(?${ix(e,n,i.useFlagMods)}${s})`;return i.currentFlags=o,c},LookaroundAssertion({body:e,kind:t,negate:n},r,i){return`(?${`${t===`lookahead`?``:`<`}${n?`!`:`=`}`}${e.map(i).join(`|`)})`},Quantifier(e,t,n){return n(e.body)+ax(e)},Subroutine({isRecursive:e,ref:t},n){if(!e)throw Error(`Unexpected non-recursive subroutine in transformed AST`);let r=n.recursionLimit;return t===0?`(?R=${r})`:$`\g<${t}&R=${r}>`}},Yb=new Set([`$`,`(`,`)`,`*`,`+`,`.`,`?`,`[`,`\\`,`]`,`^`,`{`,`|`,`}`]),Xb=new Set([`-`,`\\`,`]`,`^`,`[`]),Zb=new Set("()-/[\\]^{|}!#$%&*+,.:;<=>?@`~".split(``)),Qb=new Map([[9,$`\t`],[10,$`\n`],[11,$`\v`],[12,$`\f`],[13,$`\r`],[8232,$`\u2028`],[8233,$`\u2029`],[65279,$`\uFEFF`]]),$b=/^\p{Cased}$/u;function ex(e){return $b.test(e)}function tx(e,t){let n=!!t?.firstOnly,r=e.min.value,i=e.max.value,a=[];if(r<65&&(i===65535||i>=131071)||r===65536&&i>=131071)return a;for(let e=r;e<=i;e++){let t=$y(e);if(!ex(t))continue;let o=fb(t).filter(e=>{let t=e.codePointAt(0);return t<r||t>i});if(o.length&&(a.push(...o),n))break}return a}function nx(e,{escDigit:t,inCharClass:n,useFlagV:r}){if(Qb.has(e))return Qb.get(e);if(e<32||e>126&&e<160||e>262143||t&&sx(e))return e>255?`\\u{${e.toString(16).toUpperCase()}}`:`\\x${e.toString(16).toUpperCase().padStart(2,`0`)}`;let i=n?r?Zb:Xb:Yb,a=$y(e);return(i.has(a)?`\\`:``)+a}function rx(e){let t=e.map(e=>e.codePointAt(0)).sort((e,t)=>e-t),n=[],r=null;for(let e=0;e<t.length;e++)t[e+1]===t[e]+1?r??=t[e]:r===null?n.push(t[e]):(n.push([r,t[e]]),r=null);return n}function ix(e,t,n){if(e)return`>`;let r=``;if(t&&n){let{enable:e,disable:n}=t;r=(e?.ignoreCase?`i`:``)+(e?.dotAll?`s`:``)+(n?`-`:``)+(n?.ignoreCase?`i`:``)+(n?.dotAll?`s`:``)}return`${r}:`}function ax({kind:e,max:t,min:n}){let r;return r=!n&&t===1?`?`:!n&&t===1/0?`*`:n===1&&t===1/0?`+`:n===t?`{${n}}`:`{${n},${t===1/0?``:t}}`,r+{greedy:``,lazy:`?`,possessive:`+`}[e]}function ox({type:e}){return e===`CapturingGroup`||e===`Group`||e===`LookaroundAssertion`}function sx(e){return e>47&&e<58}function cx({type:e,value:t}){return e===`Character`&&t===45}var lx=class e extends RegExp{#e=new Map;#t=null;#n;#r=null;#i=null;rawOptions={};get source(){return this.#n||`(?:)`}constructor(t,n,r){let i=!!r?.lazyCompile;if(t instanceof RegExp){if(r)throw Error(`Cannot provide options when copying a regexp`);let i=t;super(i,n),this.#n=i.source,i instanceof e&&(this.#e=i.#e,this.#r=i.#r,this.#i=i.#i,this.rawOptions=i.rawOptions)}else{let e={hiddenCaptures:[],strategy:null,transfers:[],...r};super(i?``:t,n),this.#n=t,this.#e=dx(e.hiddenCaptures,e.transfers),this.#i=e.strategy,this.rawOptions=r??{}}i||(this.#t=this)}exec(t){if(!this.#t){let{lazyCompile:t,...n}=this.rawOptions;this.#t=new e(this.#n,this.flags,n)}let n=this.global||this.sticky,r=this.lastIndex;if(this.#i===`clip_search`&&n&&r){this.lastIndex=0;let e=this.#a(t.slice(r));return e&&(ux(e,r,t,this.hasIndices),this.lastIndex+=r),e}return this.#a(t)}#a(e){this.#t.lastIndex=this.lastIndex;let t=super.exec.call(this.#t,e);if(this.lastIndex=this.#t.lastIndex,!t||!this.#e.size)return t;let n=[...t];t.length=1;let r;this.hasIndices&&(r=[...t.indices],t.indices.length=1);let i=[0];for(let e=1;e<n.length;e++){let{hidden:a,transferTo:o}=this.#e.get(e)??{};if(a?i.push(null):(i.push(t.length),t.push(n[e]),this.hasIndices&&t.indices.push(r[e])),o&&n[e]!==void 0){let a=i[o];if(!a)throw Error(`Invalid capture transfer to "${a}"`);if(t[a]=n[e],this.hasIndices&&(t.indices[a]=r[e]),t.groups){this.#r||=fx(this.source);let i=this.#r.get(o);i&&(t.groups[i]=n[e],this.hasIndices&&(t.indices.groups[i]=r[e]))}}}return t}};function ux(e,t,n,r){if(e.index+=t,e.input=n,r){let n=e.indices;for(let e=0;e<n.length;e++){let r=n[e];r&&(n[e]=[r[0]+t,r[1]+t])}let r=n.groups;r&&Object.keys(r).forEach(e=>{let n=r[e];n&&(r[e]=[n[0]+t,n[1]+t])})}}function dx(e,t){let n=new Map;for(let t of e)n.set(t,{hidden:!0});for(let[e,r]of t)for(let t of r)rb(n,t,{}).transferTo=e;return n}function fx(e){let t=/(?<capture>\((?:\?<(?![=!])(?<name>[^>]+)>|(?!\?)))|\\?./gsu,n=new Map,r=0,i=0,a;for(;a=t.exec(e);){let{0:e,groups:{capture:t,name:o}}=a;e===`[`?r++:r?e===`]`&&r--:t&&(i++,o&&n.set(i,o))}return n}function px(e,t){let n=mx(e,t);return n.options?new lx(n.pattern,n.flags,n.options):new RegExp(n.pattern,n.flags)}function mx(e,t){let n=cb(t),r=Sb(Bv(e,{flags:n.flags,normalizeUnknownPropertyNames:!0,rules:{captureGroup:n.rules.captureGroup,singleline:n.rules.singleline},skipBackrefValidation:n.rules.allowOrphanBackrefs,unicodePropertyMap:pb}),{accuracy:n.accuracy,asciiWordBoundaries:n.rules.asciiWordBoundaries,avoidSubclass:n.avoidSubclass,bestEffortTarget:n.target}),i=Kb(r,n),a=qy(i.pattern,{captureTransfers:i._captureTransfers,hiddenCaptures:i._hiddenCaptures,mode:`external`}),o=Ly(By(a.pattern).pattern,{captureTransfers:a.captureTransfers,hiddenCaptures:a.hiddenCaptures}),s={pattern:o.pattern,flags:`${n.hasIndices?`d`:``}${n.global?`g`:``}${i.flags}${i.options.disable.v?`u`:`v`}`};if(n.avoidSubclass){if(n.lazyCompileLength!==1/0)throw Error(`Lazy compilation requires subclass`)}else{let e=o.hiddenCaptures.sort((e,t)=>e-t),t=Array.from(o.captureTransfers),i=r._strategy,a=s.pattern.length>=n.lazyCompileLength;(e.length||t.length||i||a)&&(s.options={...e.length&&{hiddenCaptures:e},...t.length&&{transfers:t},...i&&{strategy:i},...a&&{lazyCompile:a}})}return s}function hx(e,t){return px(e,{global:!0,hasIndices:!0,lazyCompileLength:3e3,rules:{allowOrphanBackrefs:!0,asciiWordBoundaries:!0,captureGroup:!0,recursionLimit:5,singleline:!0},...t})}function gx(e={}){let t={target:`auto`,cache:new Map,...e};return t.regexConstructor||=e=>hx(e,{target:t.target}),{createScanner(e){return new W_(e,t)},createString:K_}}var _x=t({highlightChunks:()=>Ox,highlightLangChunks:()=>kx,langForPath:()=>Dx}),vx={light:`github-light`,dark:`github-dark`},yx=400,bx={ts:`typescript`,mts:`typescript`,cts:`typescript`,js:`javascript`,mjs:`javascript`,cjs:`javascript`,jsx:`jsx`,tsx:`tsx`,json:`json`,jsonc:`jsonc`,json5:`json5`,map:`json`,md:`markdown`,mdx:`mdx`,markdown:`markdown`,css:`css`,pcss:`css`,postcss:`css`,sass:`sass`,scss:`scss`,less:`less`,styl:`stylus`,html:`html`,htm:`html`,vue:`vue`,svelte:`svelte`,astro:`astro`,py:`python`,pyi:`python`,rb:`ruby`,rake:`ruby`,rs:`rust`,go:`go`,java:`java`,kt:`kotlin`,kts:`kotlin`,c:`c`,h:`c`,cpp:`cpp`,cc:`cpp`,cxx:`cpp`,hpp:`cpp`,hh:`cpp`,cs:`csharp`,fs:`fsharp`,swift:`swift`,m:`objective-c`,php:`php`,scala:`scala`,groovy:`groovy`,dart:`dart`,sh:`shellscript`,bash:`shellscript`,zsh:`shellscript`,fish:`fish`,ps1:`powershell`,bat:`bat`,cmd:`bat`,yml:`yaml`,yaml:`yaml`,toml:`toml`,xml:`xml`,svg:`xml`,sql:`sql`,graphql:`graphql`,gql:`graphql`,prisma:`prisma`,lua:`lua`,pl:`perl`,pm:`perl`,r:`r`,jl:`julia`,ex:`elixir`,exs:`elixir`,erl:`erlang`,hs:`haskell`,clj:`clojure`,cljs:`clojure`,edn:`clojure`,vim:`vim`,zig:`zig`,nim:`nim`,sol:`solidity`,tf:`terraform`,tfvars:`terraform`,hcl:`hcl`,diff:`diff`,patch:`diff`,lock:`yaml`},xx={dockerfile:`dockerfile`,makefile:`makefile`,".gitignore":`ini`,".gitattributes":`ini`,".editorconfig":`ini`,".npmrc":`ini`,".nvmrc":`ini`,".env":`ini`,justfile:`justfile`,"cmakelists.txt":`cmake`},Sx={astro:()=>J(()=>import(`./astro-BZ97kZFP.js`),__vite__mapDeps([0,1,2,3,4,5,6])),bat:()=>J(()=>import(`./bat-qdxAdBWQ.js`),[]),c:()=>J(()=>import(`./c-Cz4nF6n_.js`),__vite__mapDeps([7,8])),clojure:()=>J(()=>import(`./clojure-DqKBuwfJ.js`),[]),cmake:()=>J(()=>import(`./cmake-Bj61d0ZC.js`),[]),cpp:()=>J(()=>import(`./cpp-B6pWdJV2.js`),__vite__mapDeps([9,10,11,8])),csharp:()=>J(()=>import(`./csharp-dmMxLVLW.js`),[]),css:()=>J(()=>import(`./css-DgaLhXQH.js`),__vite__mapDeps([12,4])),dart:()=>J(()=>import(`./dart-CHZY9Xhz.js`),[]),diff:()=>J(()=>import(`./diff-woXpYk--.js`),[]),dockerfile:()=>J(()=>import(`./dockerfile-IyjqRm3v.js`),[]),elixir:()=>J(()=>import(`./elixir-raGDl1oO.js`),__vite__mapDeps([13,14,2,4])),erlang:()=>J(()=>import(`./erlang-D0CaQ5Pl.js`),__vite__mapDeps([15,16])),fish:()=>J(()=>import(`./fish-BJitypiv.js`),[]),fsharp:()=>J(()=>import(`./fsharp-PZeu-6rm.js`),__vite__mapDeps([17,16])),graphql:()=>J(()=>import(`./graphql-BZEhxNwM.js`),__vite__mapDeps([18,19,2,3,6,20])),groovy:()=>J(()=>import(`./groovy-CacY0gHj.js`),[]),hcl:()=>J(()=>import(`./hcl-Dh228itO.js`),[]),haskell:()=>J(()=>import(`./haskell-D8IpX4py.js`),[]),html:()=>J(()=>import(`./html-BCy9P6D2.js`),__vite__mapDeps([21,14,2,4])),ini:()=>J(()=>import(`./ini-B5eOa1yu.js`),[]),java:()=>J(()=>import(`./java-_ATy9zCa.js`),__vite__mapDeps([22,23])),javascript:()=>J(()=>import(`./javascript-CpIGwZ_Y.js`),__vite__mapDeps([24,2])),json:()=>J(()=>import(`./json-C3WlssX3.js`),__vite__mapDeps([25,1])),json5:()=>J(()=>import(`./json5-BR5RXkoi.js`),[]),jsonc:()=>J(()=>import(`./jsonc-CYpm1nAK.js`),[]),jsx:()=>J(()=>import(`./jsx-C4yDKi0A.js`),__vite__mapDeps([26,20])),julia:()=>J(()=>import(`./julia-DCfl8sf8.js`),__vite__mapDeps([27,2,10,11,8,28,29,30])),justfile:()=>J(()=>import(`./justfile-CKP9W7x6.js`),__vite__mapDeps([31,2,3,28,32,33,4,14,30,34,23,35,8,10,11,19,6,20,36,37])),kotlin:()=>J(()=>import(`./kotlin-DhhofPvG.js`),[]),less:()=>J(()=>import(`./less-DVTAwKKz.js`),[]),lua:()=>J(()=>import(`./lua-fPRBWD-V.js`),__vite__mapDeps([38,36,8])),makefile:()=>J(()=>import(`./makefile-Dixweg8N.js`),[]),markdown:()=>J(()=>import(`./markdown-CjQmuOi1.js`),__vite__mapDeps([39,16])),mdx:()=>J(()=>import(`./mdx-DQZ5AkYe.js`),[]),nim:()=>J(()=>import(`./nim-VAaFSKwL.js`),__vite__mapDeps([40,2,4,8,11,14,16,34,23])),"objective-c":()=>J(()=>import(`./objective-c-D1A_Heim.js`),[]),perl:()=>J(()=>import(`./perl-BTdIRyOQ.js`),__vite__mapDeps([41,33,2,4,14,30,34,23])),php:()=>J(()=>import(`./php-DPoYWQt_.js`),__vite__mapDeps([42,1,2,4,14,30,34,23])),postcss:()=>J(()=>import(`./postcss-DkKB82OS.js`),__vite__mapDeps([43,5])),powershell:()=>J(()=>import(`./powershell-QtSnmXcu.js`),[]),prisma:()=>J(()=>import(`./prisma-DMgNhnYS.js`),[]),python:()=>J(()=>import(`./python-C5TF47hQ.js`),__vite__mapDeps([44,28])),r:()=>J(()=>import(`./r-BXEss897.js`),__vite__mapDeps([45,29])),ruby:()=>J(()=>import(`./ruby-BdDtUACQ.js`),__vite__mapDeps([46,35,2,4,8,10,11,14,19,3,6,20,30,32,34,23,36,37])),rust:()=>J(()=>import(`./rust-DpiIf5JO.js`),[]),sass:()=>J(()=>import(`./sass-DXrisJhu.js`),[]),scala:()=>J(()=>import(`./scala-BiFt_7mu.js`),[]),scss:()=>J(()=>import(`./scss-8bKmll0B.js`),__vite__mapDeps([47,4])),shellscript:()=>J(()=>import(`./shellscript-CVTB3cr6.js`),__vite__mapDeps([48,32])),solidity:()=>J(()=>import(`./solidity-Bj7E1mRn.js`),[]),sql:()=>J(()=>import(`./sql-CfM2IJm3.js`),__vite__mapDeps([49,30])),svelte:()=>J(()=>import(`./svelte-CdeT-Ich.js`),__vite__mapDeps([50,2,3,4,5])),swift:()=>J(()=>import(`./swift-CyEgAFGc.js`),[]),terraform:()=>J(()=>import(`./terraform-DswuEJGm.js`),[]),toml:()=>J(()=>import(`./toml-CcmNWLt0.js`),[]),tsx:()=>J(()=>import(`./tsx-CGosfAUg.js`),__vite__mapDeps([51,6])),typescript:()=>J(()=>import(`./typescript-Bb1J8qyy.js`),__vite__mapDeps([52,3])),vim:()=>J(()=>import(`./viml-DvXPmvsu.js`),[]),vue:()=>J(()=>import(`./vue-BqdMUtqy.js`),__vite__mapDeps([53,1,2,3,4,14])),xml:()=>J(()=>import(`./xml-DuKfbPI6.js`),__vite__mapDeps([54,34,23])),yaml:()=>J(()=>import(`./yaml-DDA_XMNu.js`),__vite__mapDeps([55,37])),stylus:()=>J(()=>import(`./stylus-B6D30XZt.js`),[]),zig:()=>J(()=>import(`./zig-CMLA9XwU.js`),[])},Cx=null;function wx(){return Cx??=B_({themes:[J(()=>import(`./github-light-EUqPIrTm.js`),[]),J(()=>import(`./github-dark-C-LZuMrd.js`),[])],langs:[],engine:gx({forgiving:!0})}),Cx}var Tx=new Map;function Ex(e,t){let n=Tx.get(t);if(!n){let r=Sx[t];n=r?r().then(t=>e.loadLanguage(t)).then(()=>void 0):Promise.reject(Error(`no grammar loader for ${t}`)),n.catch(()=>Tx.delete(t)),Tx.set(t,n)}return n}function Dx(e){let t=(e.split(`/`).pop()??e).toLowerCase();return xx[t]?xx[t]:bx[t.includes(`.`)?t.slice(t.lastIndexOf(`.`)+1):``]??null}async function*Ox(e,t){let n=Dx(e);n&&t.trim()&&Sx[n]&&(yield*kx(n,t))}async function*kx(e,t){if(!e||!t.trim()||!Sx[e])return;let n=await wx();await Ex(n,e);let r=t.split(`
176
- `),i;for(let t=0;t<r.length;t+=yx){let a=r.slice(t,t+yx).join(`
177
- `),o=n.codeToHast(a,{lang:e,themes:vx,defaultColor:!1,...i?{grammarState:i}:{}});i=n.getLastGrammarState(o)??void 0,yield R_(o)}}var Ax=/(?:^|\s)language-([\w+#.-]+)/,jx=`hl`;function Mx(e){if(e)for(let t of e.querySelectorAll(`pre`)){if(t.dataset[jx])continue;let e=t.querySelector(`code`);if(!e){t.dataset[jx]=`skip`;continue}let n=Ax.exec(e.className)?.[1],r=n?Dx(`x.${n}`)??n:void 0,i=e.textContent??``;if(!r||!i.trim()){t.dataset[jx]=`skip`;continue}let a=`${r}::${i.length}::${i}`;t.dataset[jx]=`pending`;let o=Fd(a);o===void 0?(async()=>{try{let{highlightLangChunks:e}=await J(async()=>{let{highlightLangChunks:e}=await Promise.resolve().then(()=>_x);return{highlightLangChunks:e}},void 0),n=``;for await(let t of e(r,i))n+=t;if(!n){t.dataset[jx]=`skip`;return}Id(a,n),t.isConnected&&Nx(t,n)}catch{t.dataset[jx]=`skip`}})():Nx(t,o)}}function Nx(e,t){let n=document.createElement(`div`);n.className=`shikiwrap`;let r=document.createElement(`div`);r.className=`shiki`,r.innerHTML=t,n.appendChild(r),e.replaceWith(n)}function Px(e){let t=String(e??``).trim();if(!t)return null;if(t.startsWith(`[`)){let e=(()=>{try{return JSON.parse(t)}catch{try{return JSON.parse(t.replace(/'/g,`"`))}catch{return}}})();if(Array.isArray(e)&&e.length>=2)return`${String(e[0])}/${String(e[1])}`}for(let e of[`__`,`/`,`::`]){let n=t.lastIndexOf(e);if(!(n<=0))return`${t.slice(0,n).replace(/^mcp__/,``)}/${t.slice(n+e.length)}`}return t}var Fx={prompt:{name:`you`,icon:`🟧`,color:`#faa81a`},user:{name:`you`,icon:`🟧`,color:`#faa81a`},message:{name:`agent`,icon:`🫖`,color:`#5865f2`},progress:{name:`progress`,icon:`📈`,color:`#3ba55d`},question:{name:`agent`,icon:`❓️`,color:`#5865f2`}},Ix={name:`harness`,icon:`📣`,color:`#3ba55d`},Lx={"#faa81a":`you`,"#5865f2":`agent`,"#3ba55d":`progress`,"#3ba0c9":`tool`},Rx=e=>Lx[e]??`agent`,zx=e=>{if(e.data?.actor)return{name:`@${String(e.data.actor)}`,icon:`🧩`,color:`#3ba0c9`};if(e.type===`tool_call`||e.type===`tool_result`){let t=String(e.data?.name??`tool`);if(t===`run_tool`){let t=Px(e.data?.args?.tool_id);if(t)return{name:t,icon:`⚙️`,color:`#3ba0c9`}}let n=/^mcp__([^_]+(?:_[^_]+)*)__(.+)$/.exec(t);return n?{name:`${n[1]}/${n[2]}`,icon:`⚙️`,color:`#3ba0c9`}:{name:t,icon:`⚙️`,color:`#3ba0c9`}}if(e.type===`prompt`){let t=String(e.data?.source??`user`);return t===`user`?Fx.prompt:t.startsWith(`scheduler:`)?{name:t.slice(10),icon:`📣`,color:`#3ba55d`}:Ix}return Fx[e.type]??{name:e.type,icon:`•`,color:`#9298a5`}},Bx=e=>{let t=new Date(e);return`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}`};function Vx(e){let t=e.data??{};return e.type===`prompt`?String(t.text??``):e.type===`message`?`${typeof t.reasoning==`string`&&t.reasoning.trim()?`<reasoning>\n${t.reasoning}\n</reasoning>\n\n`:``}${String(t.content??``)}`:(e.type,``)}function Hx(e){return e>=1e9?`${+(e/1e9).toFixed(1)}b`:e>=1e6?`${+(e/1e6).toFixed(1)}m`:e>=1e4?`${Math.round(e/1e3)}k`:e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e)}function Ux(e,t){return pt(e.replace(/\s+/g,` `).trim(),t)}function Wx(e){return e.type===`prompt`&&e.data?.source===`user`?`you`:e.type===`message`?`agent`:`harness`}function Gx(e){let t=e.data??{};if(e.data?.actor)return`sub:${String(e.data.actor)}`;if(e.type===`tool_call`||e.type===`tool_result`){let e=typeof t.name==`string`?t.name:``;return e===`load_skill`?`agent-skill`:`tool:${e}`}return e.type===`prompt`?`src:${String(t.source??`user`)}`:`type:${e.type}`}function Kx(e,t){return!(!e||t.data?.pending||e.data?.pending||t.data?.cancelled||Gx(e)!==Gx(t)||Wx(e)!==Wx(t)||t.session!==e.session||t.branch!==e.branch)}function qx(e,t){let n=String(t??``);return/^TIMEOUT after\b/.test(n)?`timeout`:/^ABORTED\b/.test(n)?`aborted`:/^exit=\d+/.test(n)||e===!1?`exit`:n.trim()?`ok`:`empty`}function Jx(e){switch(e){case`timeout`:return` · TIMED OUT`;case`aborted`:return` · ABORTED`;case`exit`:return` · FAILED`;default:return``}}function Yx(e){let t=[];e.outcome!==`empty`&&t.push(e.fmtDur(e.durationMs)),e.timeoutMs&&t.push(`timeout ${Math.round(e.timeoutMs/1e3)}s`);let n=Jx(e.outcome).replace(/^\s*·\s*/,``);return n&&t.push(n),t.join(` · `)}function Xx(e){let t=e.trim();if(!t)return;let n=t[0];if(n===`{`||n===`[`||n===`"`)try{let e=JSON.parse(t);return typeof e==`object`&&e?`json`:void 0}catch{return}}function Zx(e){if(Xx(e)!==`json`)return e;try{let t=JSON.parse(e.trim()),n=JSON.stringify(t,null,1);return e.trim().split(`
178
- `).length>1?e:n}catch{return e}}var Qx=12e4,$x=6e5,eS=e=>{let t=Number(e);return Math.min(Number.isFinite(t)&&t>0?t:Qx,$x)},tS=P(`<div class=qfree><input type=text><button>reply`),nS=P(`<div class=meta>`),rS=P(`<div class=meta>waiting for output…`),iS=P(`<div class="meta bgjob-note">runs in background — poll with <b>bash_output(job_id=&quot;<!>&quot;)`),aS=P(`<b>action="kill"`),oS=P(`<div class=meta>writing…`),sS=P(`<pre class="mono toolbody del">`),cS=P(`<pre class="mono toolbody add">`),lS=P(`<div class=meta> · `),uS=P(`<div class=meta>applying…`),dS=P(`<pre class="mono toolbody patch">`),fS=P(`<div>`),pS=P(`<div class=meta>validating…`),mS=P(`<a target=_blank rel="noopener noreferrer"referrerpolicy=no-referrer>open ↗`),hS=P(`<span class=muted>`),gS=P(`<div class=content>`),_S=P(`<div class=meta>loading…`),vS=P(`<div class=meta>bundled: `),yS=P(`<div class=meta>saving…`),bS=P(`<div class=meta>found: `),xS=P(`<div class=meta>no matches`),SS=P(`<span class=actor>@`),CS=P(`<details><summary><b></b><span class=meta></span><span class=toolcopy>`),wS=P(`<div class=divider-msg>⑂ forked from <!> → `),TS=P(`<div><div class=goalline-label>`),ES=P(`<div class="embed auditstep"><span class=meta>`),DS=P(`<span class="meta muted">`),OS=P(`<pre class="mono toolbody">`),kS=P(`<details class="embed auditstep"><summary><span class=meta>`),AS=P(`<div class=divider-msg>✅ tasks updated (<!>)`),jS=P(`<div> → `),MS=P(`<div class="embed fail"><div class=mono>🛑 runaway: <!> tool failures in a row (limit <!>)</div><div class=meta>last: <!> — `),NS=P(`<div class="embed warn-embed"title="a round-fatal API error occurred; auto-retry is waiting, then a fresh round starts (onError: retry)"><div class=mono>↻ API error — retrying (attempt <!>) in <!>s…`),PS=P(`<div class=divider-msg>🗜 compacted: <!> → <!> tok (<!>)`),FS=P(`<div class=divider-msg title="compaction is rewriting older history — the agent is not stuck">🗜 compacting: summarizing <!> earlier messages from <!> tok (<!>)…`),IS=P(`<span class=ts>`),LS=P(`<button class=editbtn title="withdraw this message — it has not reached the model yet; the text goes back to the input box">✕ cancel`),RS=P(`<button class=editbtn title="edit this prompt — forks the conversation here (later events are dropped or summarized)">✎ edit`),zS=P(`<div class=msg-head><span></span><span class=ts>`),BS=P(`<div><div></div><div class=msg-body>`),VS=P(`<span class=grouptime>`),HS=P(`<div class=promptimgs>`),US=P(`<img class=promptimg alt="tool image"loading=lazy title="click to enlarge">`,!0,!1,!1),WS=P(`<img class=promptimg alt=attachment title="click to enlarge">`),GS=P(`<details class=reasoning><summary>💭 thinking</summary><div class=mono>`),KS=P(`<div class=interrupted>⚠ interrupted — partial output kept`),qS=P(`<div class=msgfoot><span>copy summary`),JS=P(`<div class=meta>its call is no longer in the loaded events — the run itself finished`),YS=P(`<details><summary><span class=meta></span></summary><div class=mono></div><div class=meta>`),XS=P(`<div class="content muted">Rejected: `),ZS=P(`<details class="embed decision"><summary><b>📌 <span class="content inline-md"></span></b><span class=meta>decision logged`),QS=P(`<div class="meta answerdone">✓ answered — continuing below`),$S=P(`<div class=qopts>`),eC=P(`<div><div>❓️ <div class="content inline-md">`),tC=P(`<button class=qopt>`),nC=P(`<div class=progrow><b>goal</b><span>`),rC=P(`<div class=progrow><b>recent</b><span class="content inline-md">`),iC=P(`<div class="progrow warn"><b>⚠ problems</b><span class="content inline-md">`),aC=P(`<div class=progrow><b>next</b><span class="content inline-md">`),oC=P(`<div class="embed progembed"><div>📈 <div class="content inline-md">`),sC=P(`<div class="embed fail"><div class=mono>⚠ `),cC=P(`<div class="muted compactnote">the summary pass produced nothing, so the oldest messages were dropped instead — the session continues with the recent tail intact`),lC=P(`<div class="embed compaction"><b>🗜 context compacted</b><span class=meta> · <!> → <!> tok · `),uC=P(`<div class="vtitle compactkept">what the agent kept`),dC=P(`<details class="embed compaction"><summary><b>🗜 context compacted</b><span class=meta> · <!> → <!> tok · `),fC=P(`<div class="content muted">`);function pC(e){let[t,n]=y(``),r=()=>{let r=t().trim();r&&!e.answered&&(n(``),e.onOption?.(r))};return(()=>{var i=tS(),a=i.firstChild,o=a.nextSibling;return a.$$keydown=e=>{e.key===`Enter`&&!e.isComposing&&(e.preventDefault(),r())},a.$$input=e=>n(e.currentTarget.value),o.$$click=r,b(n=>{var r=e.answered?`answered`:`or type your own answer…`,i=e.answered,s=e.answered||!t().trim();return r!==n.e&&F(a,`placeholder`,n.e=r),i!==n.t&&(a.disabled=n.t=i),s!==n.a&&(o.disabled=n.a=s),n},{e:void 0,t:void 0,a:void 0}),b(()=>a.value=t()),i})()}function mC(e){let t=e.e,n=Kx(e.prev,t),r=S(()=>e.res?.(),void 0,{equals:(e,t)=>e?.id===t?.id}),i=()=>r(),a=()=>!e.agentActive&&!i(),o=t.data??{},s=String(o.name??`tool`),c=()=>String(i()?.data?.result??``),l=e=>String(o.args?.[e]??``),u=()=>s===`bash`?l(`command`):l(`path`)||JSON.stringify(o.args??{},null,1),d=()=>s===`bash`?eS(l(`timeout_ms`)):s===`wait_children`?Number(l(`timeout_ms`))||3e5:Number(l(`timeout_ms`))||void 0,f=(e,t,n)=>A(Qd,{text:e,lang:n}),p=e=>A(Qd,{get text(){return JSON.stringify(e??o.args??{},null,1)},lang:`json`}),m=()=>(()=>{let t=i();return t?[N(()=>N(()=>!!Md(c()))()?A(Zd,{get text(){return c()}}):A(Qd,{get text(){return Zx(c())},get lang(){return Xx(c())}})),(()=>{var e=nS();return L(e,()=>ft(t.data?.durationMs),null),L(e,()=>s===`bash`?Jx(qx(t.data?.ok,String(t.data?.result??``))):t.data?.ok===!1?` · FAILED`:``,null),L(e,A(Cd,{get text(){return N(()=>!!Md(c()))()?jd(c()):Zx(c())}}),null),e})(),A(_C,{get data(){return t.data},get agentId(){return e.agentId}})]:rS()})(),h=S(()=>{i();let e=s,t=``,n=p(),r=(r,a,o)=>{let s=o??{},c=Object.keys(s);e=c.length?Ux(JSON.stringify(s),120):`(no arguments)`,t=i()?ft(i().data?.durationMs):null,n=[N(()=>N(()=>!!c.length)()?p(s):null),N(m)]};try{switch(s){case`bash`:{let r=l(`command`),a=o.args?.background===!0,s=a?String(c()).match(/job (bg\d+)/)?.[1]??``:``;e=(a?`⏳ `:`$ `)+Ux(r,96);let u=l(`timeout_ms`)?Number(l(`timeout_ms`)):void 0,d=i(),f=qx(d?.data?.ok,d?String(d.data?.result??``):``);t=d?a?`background job${s?` ${s}`:``}${u?` · timeout ${Math.round(u/1e3)}s`:``}`:Yx({outcome:f,durationMs:d.data?.durationMs,timeoutMs:u,fmtDur:ft}):null,n=[a?(()=>{var e=iS(),t=e.firstChild.nextSibling,n=t.firstChild.nextSibling;return n.nextSibling,L(t,s||`?`,n),L(e,s?[` · kill with `,aS()]:null,null),e})():null,A(Qd,{text:r,lang:`shellscript`}),N(m)];break}case`read_file`:{let r=Array.isArray(o.args?.paths)?o.args.paths.map(String):[];e=l(`path`)||(r.length?r.length===1?r[0]:`${r[0]} +${r.length-1} more`:`(no path)`);let i=[];l(`pattern`)&&i.push(`grep /${Ux(l(`pattern`),40)}/`),Number(o.args?.offset)<0?i.push(`last ${-Number(o.args.offset)} lines`):o.args?.offset&&i.push(`from L${o.args.offset}`),o.args?.limit&&i.push(`≤${o.args.limit} lines`),t=i.join(` · `),n=m();break}case`write_file`:{let r=String(o.args?.content??``),a=l(`path`);e=a||`(no path)`,t=`${Hx(r.length)} bytes`,n=[N(()=>f(r,void 0,Dx(a)??void 0)),N(()=>N(()=>!!i())()?(()=>{var e=nS();return L(e,()=>Ux(c(),160)),e})():oS())];break}case`edit_file`:e=l(`path`)||`(no path)`,t=o.args?.replace_all===!0?`replace all`:`unique spot`,n=[(()=>{var e=sS();return L(e,()=>`- `+l(`old_text`)),e})(),(()=>{var e=cS();return L(e,()=>`+ `+l(`new_text`)),e})(),N(()=>N(()=>!!i())()?(()=>{var e=lS(),t=e.firstChild;return L(e,()=>Ux(c(),120),t),L(e,()=>ft(i().data?.durationMs),null),e})():uS())];break;case`apply_patch`:{let t=l(`patch`).split(`
179
- `).filter(e=>e&&!/^---$/.test(e.trim())),r=t.map(e=>e.match(/^\*\*\* (?:Add|Update|Delete) File: (.+)$/)?.[1]).filter(Boolean);e=r.length?`${r.length} file${r.length>1?`s`:``}: ${Ux(r.join(`, `),80)}`:`patch`,n=[(()=>{var e=dS();return L(e,()=>t.map(e=>{let t=e.startsWith(`+`)?` add`:e.startsWith(`-`)?` del`:/^\*\*\*|^@@/.test(e)?` meta`:``;return(()=>{var n=fS();return I(n,`pline`+t),L(n,e),n})()})),e})(),N(()=>N(()=>!!i())()?(()=>{var e=nS();return L(e,()=>Ux(c().split(`
180
- `)[0]??``,140),null),L(e,()=>i().data?.ok===!1?` · FAILED`:``,null),e})():pS())];break}case`list_dir`:e=l(`path`)||`.`,n=m();break;case`read_url`:{let r=l(`url`);try{let e=new URL(r);r=e.host+e.pathname}catch{}e=Ux(r,70),t=`web`,n=[(()=>{var e=nS();return L(e,A(M,{get when(){return/^https?:/i.test(l(`url`))},get fallback(){return(()=>{var e=hS();return L(e,()=>Ux(l(`url`),80)),e})()},get children(){var e=mS();return b(()=>F(e,`href`,l(`url`))),e}})),e})(),N(m)];break}case`bash_output`:{let r=l(`action`)||`read`;e=`bash_output ${l(`job_id`)||`(?)`}`,t=r,n=m();break}case`load_skill`:{e=`skill: ${l(`name`)}`;let t=c().replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/,``);n=i()?[(()=>{var e=gS();return b(()=>e.innerHTML=ze(t)),e})(),(()=>{var e=nS();return L(e,()=>ft(i().data?.durationMs)),e})()]:_S();break}case`save_skill`:{e=`skill: ${l(`name`)}`,t=Ux(l(`description`),60);let r=Array.isArray(o.args?.files)?o.args.files.map(e=>e?.name).filter(Boolean):[];n=[N(()=>N(()=>!!r.length)()?(()=>{var e=vS();return e.firstChild,L(e,()=>r.join(`, `),null),e})():null),N(()=>N(()=>!!i())()?(()=>{var e=lS(),t=e.firstChild;return L(e,()=>Ux(c(),160),t),L(e,()=>ft(i().data?.durationMs),null),e})():yS())];break}case`search_tools`:{e=`🔎 ${Ux(l(`query`)||`(browse)`,60)}`;let r=(()=>{try{let e=JSON.parse(c());return{names:(e.tools??[]).map(e=>`${e.server??`?`}/${e.name??`?`}`),total:e.totalMatches??0}}catch{return{names:[],total:0}}})();t=i()?`${r.total} match${r.total===1?``:`es`}`:null,n=[N(p),N(()=>N(()=>!!i())()?N(()=>!!r.names.length)()?(()=>{var e=bS();return e.firstChild,L(e,()=>r.names.join(`, `),null),e})():xS():null),N(m)];break}case`run_tool`:{let a=Px(l(`tool_id`)),s=a?.indexOf(`/`)??-1;a&&s>0?r(a.slice(0,s),a.slice(s+1),o.args?.arguments):(e=a||`(no tool_id)`,t=i()?ft(i().data?.durationMs):null,n=[N(p),N(m)]);break}default:{let a=/^mcp__([^_]+(?:_[^_]+)*)__(.+)$/.exec(s);if(a){r(a[1],a[2],o.args);break}e=s,t=i()?ft(i().data?.durationMs):null,n=[N(p),N(m)];break}}}catch{}return{label:e,hint:t,body:n,key:`${i()?.id??`none`}|${e}|${t??``}`}},void 0,{equals:(e,t)=>e.key===t.key});return(()=>{var r=CS(),o=r.firstChild,l=o.firstChild,f=l.nextSibling,p=f.nextSibling;return r.addEventListener(`toggle`,t=>{t.target.open&&e.onResize?.()}),L(l,()=>h().label),L(o,A(M,{get when(){return t.data?.actor},get children(){var e=SS();return e.firstChild,L(e,()=>String(t.data.actor),null),e}}),f),L(f,(()=>{var e=N(()=>!!i());return()=>e()?h().hint||``:N(()=>!!a())()?`(result missed)`:N(()=>!!(s===`bash`||d()))()?A(Yd,{get startedAt(){return t.ts},inline:!0,get timeoutMs(){return d()}}):`running…`})()),L(p,A(Cd,{get text(){return u()},label:`⧉ cmd`,title:`copy the ${s} arguments`}),null),L(p,A(M,{get when(){return i()},get children(){return A(Cd,{get text(){return N(()=>!!Md(c()))()?jd(c()):c()},label:`⧉ out`,title:`copy this tool's full output (escapes removed)`})}}),null),L(r,()=>h().body,null),b(e=>{var t=`embed`+(n?` grouped`:``)+(i()?i().data?.ok===!1?` fail`:` done`:a()?` done`:` running`),o=`${s}${h().hint?` — `+h().hint:``}`;return t!==e.e&&I(r,e.e=t),o!==e.t&&F(r,`title`,e.t=o),e},{e:void 0,t:void 0}),r})()}function hC(e){let t;return x(()=>{e.html,queueMicrotask(()=>Mx(t))}),(()=>{var n=gS(),r=t;return typeof r==`function`?je(r,n):t=n,b(()=>n.innerHTML=e.html),n})()}function gC(e){let t=e.e,n=zx(t),r=()=>Kx(e.prev?.(),t),i=()=>{let n=e.next?.();return!!n&&Kx(t,n)};if(t.type===`fork`){let e=t.data??{};return(()=>{var n=wS(),r=n.firstChild.nextSibling;return r.nextSibling,L(n,()=>String(e.fromBranch??`?`),r),L(n,()=>String(e.newBranch??t.branch),null),n})()}if(t.type===`goal`){let e=$t(t.data??{});return(()=>{var t=TS(),n=t.firstChild;return L(n,()=>e.label),L(t,A(M,{get when(){return e.hasCard},get children(){return A(an,{get tone(){return N(()=>e.tone===`ok`)()?`ok`:e.tone===`warn`?`warn`:`tool`},get markdown(){return e.markdown},get body(){return e.detail}})}}),null),b(()=>I(t,`goalline `+(e.tone===`err`?`err`:e.tone===`warn`?`warn`:``))),t})()}if(t.type===`audit_step`){let e=String(t.data?.step??``),n=String(t.data?.name??``),r=e===`started`?`🔍️ auditor started`:e===`tool`?`🔍️ auditor → ${n}`:e===`tool_done`?`🔍️ auditor ← ${n} ${t.data?.ok===!1?`failed`:`${String(t.data?.chars??0)} chars`}`:e===`reply`?`🔍️ auditor replied`:`🔍️ auditor`;return e===`reply`&&t.data?.text||e===`tool`&&t.data?.args?(()=>{var n=kS(),i=n.firstChild,a=i.firstChild;return L(a,r),L(i,A(M,{get when(){return e===`tool`&&t.data?.args},get children(){var e=DS();return L(e,()=>pt(String(t.data?.args??``),120)),e}}),null),L(n,A(M,{get when(){return e===`reply`&&t.data?.text},get children(){var e=OS();return L(e,()=>String(t.data?.text??``)),e}}),null),L(n,A(M,{get when(){return e===`tool`&&t.data?.args},get children(){var e=OS();return L(e,()=>String(t.data?.args??``)),e}}),null),n})():(()=>{var e=ES(),t=e.firstChild;return L(t,r),e})()}if(t.type===`todo`){let e=String(t.data?.by??`operator`);return(()=>{var t=AS(),n=t.firstChild.nextSibling;return n.nextSibling,L(t,e===`human`?`operator`:e,n),t})()}if(t.type===`state`)return t.data.from===t.data.to?null:(()=>{var e=jS(),n=e.firstChild;return L(e,()=>t.data.from,n),L(e,()=>t.data.to,null),L(e,(()=>{var e=N(()=>!!t.data.reason);return()=>e()?` — ${t.data.reason}`:``})(),null),b(()=>I(e,`divider-msg`+(t.data.to===`error`?` err`:``))),e})();if(t.type===`system_note`){let e=String(t.data?.event??``);if(e===`runaway-detected`)return(()=>{var e=MS(),n=e.firstChild,r=n.firstChild.nextSibling,i=r.nextSibling.nextSibling;i.nextSibling;var a=n.nextSibling,o=a.firstChild.nextSibling;return o.nextSibling,L(n,()=>String(t.data?.failures),r),L(n,()=>String(t.data?.limit),i),L(a,()=>String(t.data?.lastTool),o),L(a,()=>String(t.data?.lastError??``).slice(0,200),null),b(()=>F(e,`title`,`${t.data?.failures} consecutive tool failures hit the configured limit (${t.data?.limit})`)),e})();if(e===`error-retry`)return(()=>{var e=NS(),n=e.firstChild,r=n.firstChild.nextSibling,i=r.nextSibling.nextSibling;return i.nextSibling,L(n,()=>String(t.data?.attempt),r),L(n,()=>Math.round(Number(t.data?.waitMs)/1e3),i),e})();if(e===`background-exit`){let e=t.data?.failed===!0,n=Math.round(Number(t.data?.durationMs??0)/1e3);return(()=>{var r=fS();return I(r,`divider-msg`+(e?` err`:``)),L(r,()=>(e?`⚠ background job `:`✓ background job `)+String(t.data?.jobId??`?`)+` `+(e?`FAILED (exit ${String(t.data?.code??`?`)})`:`finished (${n}s)`)),b(()=>F(r,`title`,String(t.data?.cmd??``))),r})()}return e===`context-compacted`?(()=>{var e=PS(),n=e.firstChild.nextSibling,r=n.nextSibling.nextSibling,i=r.nextSibling.nextSibling;return i.nextSibling,L(e,()=>String(t.data?.tokensBefore??`?`),n),L(e,()=>String(t.data?.tokensAfter??`?`),r),L(e,()=>String(t.data?.mode??``),i),e})():e===`context-compaction-started`?(()=>{var e=FS(),n=e.firstChild.nextSibling,r=n.nextSibling.nextSibling,i=r.nextSibling.nextSibling;return i.nextSibling,L(e,()=>String(t.data?.messages??`?`),n),L(e,()=>String(t.data?.tokensBefore??`?`),r),L(e,()=>String(t.data?.reason??`auto`),i),e})():null}return(()=>{var a=BS(),o=a.firstChild,s=o.nextSibling;return L(o,(()=>{var e=N(()=>!!r());return()=>e()?``:n.icon})()),L(s,(()=>{var e=N(()=>!!r());return()=>e()&&(()=>{var e=VS();return b(()=>F(e,`title`,`${Bx(t.ts)} · ${t.branch}`)),e})()})(),null),L(s,A(M,{get when(){return!r()},get children(){var r=zS(),i=r.firstChild,a=i.nextSibling;return L(i,()=>n.name),L(r,A(M,{get when(){return t.data?.actor},get children(){var e=SS();return e.firstChild,L(e,()=>String(t.data.actor),null),e}}),a),L(a,(()=>{var e=N(()=>!(!t.data?.pending||t.data?.queued===!1||t.data?.sent));return()=>e()?`queued…`:N(()=>!!t.data?.cancelled)()?`withdrawn`:Bx(t.ts)})()),L(r,A(M,{get when(){return e.showBranch},get children(){var e=IS();return L(e,()=>t.branch),e}}),null),L(r,A(M,{get when(){return e.onCancel},get children(){var t=LS();return t.$$click=t=>{t.stopPropagation(),e.onCancel()},t}}),null),L(r,A(M,{get when(){return t.type!==`tool_call`},get children(){return A(Cd,{get text(){return Vx(t)},label:`⧉ copy`,title:`copy the RAW text of this message (no markdown rendering)`})}}),null),L(r,A(M,{get when(){return e.onEdit},get children(){var t=RS();return t.$$click=t=>{t.stopPropagation(),e.onEdit()},t}}),null),b(()=>I(i,`author tone-${Rx(n.color)}`)),r}}),null),L(s,A(vC,{e:t,get prev(){return e.prev?.()},get res(){return e.res},get orphan(){return e.orphan},get onOption(){return e.onOption},get answeredIds(){return e.answeredIds},get onAnswered(){return e.onAnswered},get agentActive(){return e.agentActive},get onResize(){return e.onResize},get agentId(){return e.agentId}}),null),b(e=>{var s=`msg`+(r()?` grouped`:``)+(i()?` next-grouped`:``)+(t.data?.pending?` pending`:``)+(t.data?.cancelled?` withdrawn`:``)+` tone-${Rx(n.color)}`,c=t.id,l=String(t.session??``),u=`avatar avghost tone-${Rx(n.color)}`+(r()?` ghosted`:``),d=r()?`${Bx(t.ts)} · ${t.branch}`:void 0;return s!==e.e&&I(a,e.e=s),c!==e.t&&F(a,`data-eid`,e.t=c),l!==e.a&&F(a,`data-session`,e.a=l),u!==e.o&&I(o,e.o=u),d!==e.i&&F(o,`title`,e.i=d),e},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),a})()}function _C(e){let t=()=>(Array.isArray(e.data?.images)?e.data.images:[]).map(e=>typeof e==`string`?e:e?.url).filter(e=>typeof e==`string`&&e.length>0).map(t=>Tf(e.agentId,t));return A(M,{get when(){return t().length},get children(){var e=HS();return L(e,A(j,{get each(){return t()},children:e=>(()=>{var t=US();return t.$$click=()=>rt(e),F(t,`src`,e),t})()})),e}})}function vC(e){let t=e.e;switch(t.type){case`prompt`:{let n=(t.data?.images??[]).map(e=>typeof e==`string`?e:e?.url).filter(e=>typeof e==`string`&&e.length>0).map(t=>Tf(e.agentId,t));return[A(hC,{get html(){return dt(String(t.data.text??``))}}),A(M,{get when(){return n.length},get children(){var e=HS();return L(e,A(j,{each:n,children:e=>(()=>{var t=WS();return t.$$click=()=>rt(e),F(t,`src`,e),t})()})),e}})]}case`message`:return[A(M,{get when(){return N(()=>typeof t.data.reasoning==`string`)()&&t.data.reasoning.trim()},get children(){var e=GS(),n=e.firstChild.nextSibling;return L(n,()=>String(t.data.reasoning)),e}}),A(hC,{get html(){return dt(String(t.data.content??``))}}),A(M,{get when(){return t.data.interrupted},get children(){return KS()}}),A(M,{get when(){return t.data.final},get children(){var e=qS(),n=e.firstChild;return L(e,A(Cd,{get text(){return String(t.data.content??``)}}),n),e}})];case`tool_call`:return A(mC,{e:t,get prev(){return e.prev},get res(){return e.res},get orphan(){return e.orphan},get agentActive(){return e.agentActive},get onResize(){return e.onResize},get agentId(){return e.agentId}});case`tool_result`:{let n=String(t.data.result??``),r=String(t.data.name??`tool`),i=t.data.ok!==!1;return(()=>{var a=YS(),o=a.firstChild,s=o.firstChild,c=o.nextSibling,l=c.nextSibling;return I(a,`embed `+(i?``:`fail`)),L(s,r===`bash`?`$ (bash, call evicted)`:r),L(o,A(Cd,{text:n}),null),L(c,n),L(l,()=>ft(t.data.durationMs),null),L(l,()=>r===`bash`?Jx(qx(t.data.ok,n)):i?``:` · FAILED`,null),L(a,A(M,{get when(){return e.orphan},get children(){return JS()}}),null),b(()=>a.open=e.orphan),a})()}case`decision`:{let e=Array.isArray(t.data?.alternatives)?t.data.alternatives:[];return(()=>{var n=ZS(),r=n.firstChild.firstChild.firstChild.nextSibling;return L(n,A(hC,{get html(){return dt(String(t.data?.rationale??``))}}),null),L(n,A(M,{get when(){return e.length},get children(){var t=XS();return t.firstChild,L(t,()=>e.join(` / `),null),t}}),null),b(()=>r.innerHTML=dt(String(t.data?.decision??``))),n})()}case`question`:{let n=Array.isArray(t.data?.options)?t.data.options:[],r=t.data?.callId?String(t.data.callId):``,i=()=>e.answeredIds?.().has(r)??!1;return(()=>{var a=eC(),o=a.firstChild.firstChild.nextSibling;return L(a,A(M,{get when(){return i()},get children(){return QS()}}),null),L(a,A(M,{get when(){return n.length>0},get children(){var a=$S();return L(a,A(j,{each:n,children:n=>(()=>{var a=tC();return a.$$click=()=>{e.onAnswered?.(r);let i=t.data?.actor;i?Y(`/api/agents/${encodeURIComponent(String(i))}/prompt`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({text:n,start:!0})}).then(()=>wf(`→ answered @${String(t.data.actor)}`)).catch(()=>wf(`answer failed`)):e.onOption?.(n)},L(a,n),b(()=>a.disabled=i()),a})()})),a}}),null),L(a,A(pC,{get answered(){return i()},get onOption(){return e.onOption}}),null),b(e=>{var n=`embed question`+(i()?` answered`:``),r=dt(String(t.data?.question??``));return n!==e.e&&I(a,e.e=n),r!==e.t&&(o.innerHTML=e.t=r),e},{e:void 0,t:void 0}),a})()}case`progress`:return(()=>{var e=oC(),n=e.firstChild.firstChild.nextSibling;return L(e,A(M,{get when(){return t.data.goalStatus},get children(){var e=nC(),n=e.firstChild.nextSibling;return L(n,()=>String(t.data.goalStatus)),e}}),null),L(e,A(M,{get when(){return t.data.recent},get children(){var e=rC(),n=e.firstChild.nextSibling;return b(()=>n.innerHTML=dt(String(t.data.recent))),e}}),null),L(e,A(M,{get when(){return t.data.problems},get children(){var e=iC(),n=e.firstChild.nextSibling;return b(()=>n.innerHTML=dt(String(t.data.problems))),e}}),null),L(e,A(M,{get when(){return t.data.next},get children(){var e=aC(),n=e.firstChild.nextSibling;return b(()=>n.innerHTML=dt(String(t.data.next))),e}}),null),b(()=>n.innerHTML=dt(String(t.data.doing??``))),e})();case`error`:return(()=>{var e=sC(),n=e.firstChild;return n.firstChild,L(n,()=>String(t.data.message??``),null),e})();case`compaction`:return t.data.summary?(()=>{var e=dC(),n=e.firstChild.firstChild.nextSibling,r=n.firstChild,i=r.nextSibling,a=i.nextSibling.nextSibling;return a.nextSibling,L(n,()=>String(t.data.mode??``),r),L(n,()=>Hx(Number(t.data.tokensBefore??0)),i),L(n,()=>Hx(Number(t.data.tokensAfter??0)),a),L(n,(()=>{var e=N(()=>!!t.data.summarized);return()=>e()?`${t.data.summarized} summarized`:`${t.data.dropped} dropped`})(),null),L(e,A(M,{get when(){return t.data.summary},get children(){return[uC(),A(hC,{get html(){return dt(String(t.data.summary))}})]}}),null),e})():(()=>{var e=lC(),n=e.firstChild.nextSibling,r=n.firstChild,i=r.nextSibling,a=i.nextSibling.nextSibling;return a.nextSibling,L(n,()=>String(t.data.mode??``),r),L(n,()=>Hx(Number(t.data.tokensBefore??0)),i),L(n,()=>Hx(Number(t.data.tokensAfter??0)),a),L(n,(()=>{var e=N(()=>!!t.data.summarized);return()=>e()?`${t.data.summarized} summarized`:`${t.data.dropped} dropped`})(),null),L(n,()=>String(t.data.mode??``)===`truncate`?` · older history dropped`:``,null),L(e,A(M,{get when(){return String(t.data.mode??``)===`truncate`},get children(){return cC()}}),null),e})();default:return(()=>{var e=fC();return L(e,()=>pt(JSON.stringify(t.data),200)),e})()}}De([`input`,`keydown`,`click`]);var yC=(e,t)=>{let n=String(t??``).trim();return!n||/^\d+$/.test(n)?null:e?.[n]??null},bC=[{key:`openrouter`,label:`OpenRouter`,url:`https://openrouter.ai/api/v1`,model:``,hint:`400+ models behind one key — teapot sends app-attribution headers automatically`},{key:`orcarouter`,label:`OrcaRouter`,url:`https://api.orcarouter.ai/v1`,model:``,hint:`zero-markup routing gateway — 'orcarouter/auto' grades each prompt and picks the model`},{key:`openai`,label:`OpenAI`,url:`https://api.openai.com/v1`,model:``,hint:`your account's models — pick from the list once the endpoint answers`},{key:`opencode-go`,label:`OpenCode Go`,url:`https://opencode.ai/zen/go/v1`,model:``,hint:`OpenCode's open-model subscription — teapot sends the required x-opencode-session header; choose a chat/completions model`},{key:`llamacpp`,label:`llama.cpp server`,url:`http://localhost:8080/v1`,model:``,hint:`free & local — start it with: llama-server -m ./model.gguf (any model name works)`}];function xC(e,t){return e?t===`dark`?{slot:`dark`,key:`teapot.theme.dark`}:{slot:`light`,key:`teapot.theme.light`}:{slot:`fixed`,key:`teapot.theme`}}var SC=P(`<div class=themeeditor><h4 class=cfgsub>your themes</h4><div class=btnrow><button type=button title="copy the theme you are using into a new editable one — presets themselves are never modified">+ duplicate current`),CC=P(`<div class=muted style="margin:6px 0">`),wC=P(`<b>+ duplicate current`),TC=P(`<div class=cfggrid style=margin-top:8px><label class=trow>name<input type=text maxlength=40 placeholder="theme name"></label><label class=trow>appearance<select><option value=dark>dark</option><option value=light>light`),EC=P(`<div class=paletterows>`),DC=P(`<div class=btnrow><button type=button title="put every colour back to the palette this theme was created from">↺ reset palette</button><button type=button title="delete this custom theme">🗑 delete`),OC=P(`<h4 class=cfgsub>background image`),kC=P(`<img sizes=260px alt="current background"decoding=async loading=lazy>`,!0,!1,!1),AC=P(`<span class=bgpick-hint>🖼 replace…`),jC=P(`<div class=bgpreview><span class=muted title="this image is served from the server; the theme stores only its URL">✓ image set</span><div class=btnrow><label class=trow title="how much the image is dimmed so text stays readable">dim<input type=range min=0 max=0.9 step=0.01><span class="muted mono">%</span></label><label title="how much of the background shows through code blocks and tool cards — lower is more transparent">surfaces<input type=range min=0.35 max=1 step=0.01><span class="muted mono">%</span></label><button type=button>✕ remove`),MC=P(`<div class=cfggrid><button type=button></button><input type=file accept=image/* style=display:none>`),NC=P(`<div class=muted style=margin-top:6px;font-size:var(--text-xs)>the image is uploaded to the server and sits behind the panels, dimmed so text stays readable. No size limit — it is a file now, not browser storage.`),PC=P(`<label class=paletterow><input type=color><span class=paletterow-label></span><input class="mono paletterow-hex">`),FC=P(`<span class=bgpick-empty>🖼 choose a background image…`),IC=P(`<div class=muted style=font-size:11.5px;margin-top:4px>⚠ configured default provider <code></code> has no provider row here<!> Add a provider named <code></code> or pick a default below; otherwise agents fall back to the first provider.`),LC=P(`<div class=cfggrid style=margin-top:8px><label class=trow>dark theme →<select class=w100></select></label><label class=trow>light theme →<select class=w100>`),RC=P(`<div class=skilllist>`),zC=P(`<span style=color:var(--err);font-size:13px>`),BC=P(`<form style=display:flex;flex-direction:column;gap:12px;min-height:0><div class=cfgbody><nav class=cfgmenu aria-label="settings sections"></nav><div class=cfgpanel><fieldset><legend>providers</legend><button type=button>+ add custom</button><div style=display:flex;gap:6px;flex-wrap:wrap;margin-top:6px><span class=muted style=font-size:11.5px>quick-add:</span></div><div><label title="agents without an explicit provider use this one"style=display:flex;align-items:center;gap:6px;margin-top:6px>default provider<select><option value>(none — first provider wins)</option></select></label></div></fieldset><fieldset><legend>appearance</legend><div class=cfggrid><label class=trow>follow the system<input type=checkbox></label></div><h4 class=cfgsub>themes</h4></fieldset><fieldset><legend>agent runtime</legend><div class=cfgrow><label style=flex:1>API password<input type=password class=w100></label><span class=muted style=font-size:11.5px;max-width:34ch>bearer token for /api. empty = loopback only.</span></div><div class=cfggrid><label title="auto-compact threshold in k tokens. Leave EMPTY to derive per model (75% of its context window) — recommended, since models differ wildly in window size. Set only to force an absolute cap across all models.">compact budget (k tok)<input type=number min=0 placeholder="(derive: 75% of window)"></label></div><label class=cfgtoggle title="prune old tool output early (at 60% of the budget) instead of waiting for the window to fill. Meant for small-window models — on a large window it throws away context you had room for."><input type=checkbox>short-context mode</label></fieldset><fieldset><legend>MCP servers — external tools, shared by every agent</legend><div class=muted style=font-size:11.5px;margin-bottom:8px>each tool becomes <code class=mono>mcp__server__tool</code> for every agent. saving connects them; the status shown here is live.</div><button type=button>+ add MCP server</button></fieldset><fieldset><legend>scheduled tasks</legend><button type=button>+ add task</button></fieldset><fieldset><legend>archived agents — restore, or delete for good</legend></fieldset><fieldset><legend>agents (read-only — edit config file or use +)</legend></fieldset><fieldset><legend>live update</legend><div class=cfgrow><span class=muted>current version: </span><button type=button class=primarybtn>update & restart</button><span class=muted style=margin-left:8px;font-size:12px>gracefully stops all agents, spawns new process, then reloads this page</span></div></fieldset><fieldset><legend>skills</legend></fieldset><fieldset><legend>help</legend><div class=helpsec><h4 class=cfgsub>this host</h4><div class=featgrid><div class=featrow><b>image downscaling</b><span class=muted></span></div><div class=featrow><b>terminal pty</b><span class=muted></span></div></div></div><div class=helpsec><h4 class=cfgsub>keyboard</h4><div class=helprow><kbd>enter</kbd><span>send (shift+enter for a newline)</span></div><div class=helprow><span class=kbdgroup><kbd>↑</kbd><kbd>↓</kbd></span><span>move between sessions</span></div><div class=helprow><kbd>/</kbd><span>command palette — commands and focus</span></div><div class=helprow><kbd>t</kbd><span>open the terminal panel</span></div><div class=helprow><kbd>d</kbd><span>toggle the details panel</span></div><div class=helprow><kbd>esc</kbd><span>interrupt the running turn</span></div></div><div class=helpsec><h4 class=cfgsub>what the toggles do</h4><div class=helprow><b>auto-continue</b><span>fires after a round only when all hold: the toggle is on, a goal is set and its status is <code>active</code>, and the round ended cleanly (not an error, not stopped). It stops when the goal is marked done, or when you press ■ stop. Sending any prompt starts an idle agent regardless.</span></div><div class=helprow><b>auto-compact</b><span>when the live context passes the budget shown under 📊 runtime, older turns are summarized into notes and the recent stretch is kept verbatim, so work continues without losing the thread. Off means you compact by hand (<code>/compact</code>).</span></div><div class=helprow><b>messages while it works</b><span>anything you send queues up and is handed to the model at its next turn boundary — the timeline shows it as "pending (queued)…" until then. Withdraw it with ✕ cancel while it is still queued.</span></div><div class=helprow><b>👻 ghost sessions</b><span>a session whose workspace directory no longer exists on disk. The session log is intact — recreate the directory and it stops being a ghost.</span></div></div></fieldset></div></div><div class=cfgfoot><button type=submit class=cfgsave>`),VC=P(`<button type=button><span class=cfgmenu-label>`),HC=P(`<div class=cfgrow><input class=cfgname placeholder=name><input placeholder=https://…/v1><input placeholder="default model"><button type=button class=danger title="remove provider">✕</button><div class=cfgkeys><button type=button title="add another key for this provider — they are rotated round-robin, and a rate-limited key is skipped for a minute">+ key`),UC=P(`<button type=button title="remove this key">−`),WC=P(`<div class=cfgkeyrow><input type=password>`),GC=P(`<button type=button>+ `),KC=P(`<option>`),qC=P(`<div class=cfgsub style=margin-bottom:var(--space-1)>`),JC=P(`<div class=themepick>`),YC=P(`<button type=button><span class=themecard-preview></span><span class=themecard-label> ★`),XC=P(`<button type=button><span class=themecard-preview></span><span class=themecard-label>`),ZC=P(`<div class=muted style=font-size:12.5px>no MCP servers. add one below — a remote url, or a local command for stdio.`),QC=P(`<input placeholder="command (e.g. npx)">`),$C=P(`<input placeholder="args, space separated">`),ew=P(`<input type=password placeholder="paste the token"title="sent as Authorization: Bearer <token>"style=flex:1>`),tw=P(`<input placeholder="header name"style="flex:0 1 150px">`),nw=P(`<input type=password placeholder=value style=flex:1>`),rw=P(`<div class=cfgrow><textarea class=mono rows=2 placeholder="{&quot;Authorization&quot;: &quot;Bearer …&quot;, &quot;X-Team&quot;: &quot;infra&quot;}"title="static headers for every request. Use the bearer option unless the server needs something unusual."style=flex:1>`),iw=P(`<button type=button class=mcpauthorize title="start the OAuth flow: a browser tab opens, and the tools appear when you finish">🔑 authorize`),aw=P(`<span class="mcpstate connected"title="an OAuth access token is usable — disconnect it under the server's details">🔑 authorized`),ow=P(`<span>`),sw=P(`<div class=muted style=font-size:11px;color:var(--warn)>`),cw=P(`<div class="cfgcol mcpcard"><div class=cfgrow><input class=cfgname placeholder=name title="the name that appears inside mcp__<name>__ in tool names"><input placeholder="https://example.com/mcp (or leave empty for a stdio command)"><label style=display:flex;gap:3px;align-items:center;white-space:nowrap;color:var(--dim);font-size:11px><input type=checkbox>on</label><button type=button class=danger>✕</button></div><div class=cfgrow><input placeholder="what this server is for — e.g. reverse engineering: decompile, disassemble"title="shown to the model when the MCP catalog is too large to send, so it can search for the right tool instead of guessing keywords"></div><div class=cfgrow><select title="streamable HTTP is the current spec; legacy SSE is the 2024-11-05 handshake; stdio spawns a local process"><option value=http>streamable http</option><option value=sse>legacy http+sse</option><option value=stdio>stdio (local command)</option></select></div><div class=cfgrow><select title="how this server authenticates"><option value=none>no auth</option><option value=bearer>bearer token</option><option value=header>custom header</option><option value=json>headers as JSON (advanced)</option></select></div><div class=cfgrow><button type=button title="connect now and list the tools — nothing is saved">test`),lw=P(`<option value=oauth selected>`),uw=P(`<span class=muted> · needs a grant (🔑 authorize)`),dw=P(`<details class=mcptools-wrap><summary>show <!> tool</summary><ul class=mcptools>`),fw=P(`<div class=mcpdanger><span class=muted>OAuth grant</span><button type=button class=mcpdisconnect title="forget the stored grant (the refresh token is deleted, so authorizing again needs a browser)">disconnect`),pw=P(`<div><div class=mcpresult-head><b>`),mw=P(`<span class=mcptool-desc>`),hw=P(`<li><code class=mono>`),gw=P(`<div class=cfgcol><div class=cfgrow><input placeholder=id><input placeholder="agent id"><input placeholder="every 30m / cron"><label style=display:flex;gap:3px;align-items:center;white-space:nowrap;color:var(--dim);font-size:11px><input type=checkbox>fork</label><button type=button class=danger>✕</button></div><textarea rows=2 placeholder="prompt to send">`),_w=P(`<div class=muted style=font-size:12.5px>nothing archived. 🗄 archive in the controls panel puts an agent away without losing its history.`),vw=P(`<div class="cfgrow archrow"><div class=archmain><b></b><span class=muted> session</span><span class="muted mono ellip"></span></div><button type=button class=archrestore title="bring it back and start it again — its history was never touched">↩ restore</button><button type=button class=danger title="erase the config entry AND every session directory — irreversible">🗑 delete`),yw=P(`<span class=muted>🧩 sub of @`),bw=P(`<div class=cfgrow><b></b><span class=muted>`),xw=P(`<div class=muted>`),Sw=P(`<div class=skillbody>`),Cw=P(`<div class=skillrow><button type=button class=skillhead title="show the playbook"><span class=skillcaret></span><b class=mono></b><span class=muted>`),ww=P(`<div class="muted skillbody">`);function Tw(e){let[t,n]=y(e.themes().some(t=>t.id===e.paintedId)?e.paintedId:e.themes()[0]?.id??``),r=()=>hr(e.themes(),e.paintedId,t()),[i,a]=y({}),o,s=t=>{let n=r()?.id;if(!n)return;let i=e.themes().map(e=>e.id===n?t(e):e);e.onChange(i)},c=(e,t)=>{let n=pr(t);n&&s(t=>({...t,palette:{...t.palette,[e]:n}}))},l=()=>{let t=e.themes().find(t=>t.id===e.paintedId),r=$d.find(t=>t.key===e.paintedId),i=t??r??$d[0],a=getComputedStyle(document.documentElement),o={...rr};for(let{key:e,cssVar:t}of tr){let n=pr(a.getPropertyValue(t));n&&(o[e]=n)}let s=ur(e.themes().map(e=>e.id).concat($d.map(e=>e.key))),c={id:s,label:`${i.label}${t?``:` copy`}`.slice(0,40),mode:i.mode,palette:o,...t?.backgroundImage?{backgroundImage:t.backgroundImage,backgroundDim:t.backgroundDim,surfaceAlpha:t.surfaceAlpha}:{}};e.onChange([...e.themes(),c]),n(s),e.onPick(s)},u=async t=>{if(t){if(!/^image\//.test(t.type))wf(`that file is ${JSON.stringify(t.type||`unknown`)} — pick an image`);else{wf(`uploading ${t.name} (${Math.round(t.size/1024)}KB)…`);try{let n=await fetch(`/api/assets`,{method:`POST`,headers:{"content-type":t.type},body:t}).then(async e=>({ok:e.ok,body:await e.json().catch(()=>null)}));if(!n.ok||!n.body?.url){wf(n.body?.error??`upload failed`);return}s(e=>({...e,backgroundImage:n.body.url,backgroundImageBytes:n.body.bytes}));let i=r()?.id;i&&e.onPick(i),wf(`background image set`)}catch(e){wf(`upload failed: ${e.message}`)}}}};return(()=>{var t=SC(),d=t.firstChild.nextSibling.firstChild;return d.$$click=l,L(t,A(M,{get when(){return N(()=>!!(r()&&e.themes().some(t=>t.id===e.paintedId)))()?r():null},get fallback(){return(()=>{var t=CC();return L(t,(()=>{var t=N(()=>e.themes().length===0);return()=>t()?[`no custom themes yet — press `,wC(),` to start from the palette you are using.`]:[`the editor shows when one of your themes is the one on screen — pick one under "your themes" above (or press `,wC(),`).`]})()),t})()},children:t=>[(()=>{var e=TC(),t=e.firstChild,n=t.firstChild.nextSibling,i=t.nextSibling.firstChild.nextSibling;return n.$$input=e=>s(t=>({...t,label:e.currentTarget.value})),i.addEventListener(`change`,e=>s(t=>({...t,mode:e.currentTarget.value}))),b(()=>n.value=r().label),b(()=>i.value=r().mode),e})(),(()=>{var e=EC();return L(e,A(j,{each:tr,children:e=>(()=>{var t=PC(),n=t.firstChild,o=n.nextSibling,s=o.nextSibling;return n.$$input=t=>c(e.key,t.currentTarget.value),L(o,()=>e.label),s.addEventListener(`blur`,()=>a(t=>{let n={...t};return delete n[e.key],n})),s.$$input=t=>{let n=t.currentTarget.value;a(t=>({...t,[e.key]:n})),c(e.key,n)},F(s,`spellcheck`,!1),b(()=>F(t,`title`,e.cssVar)),b(()=>n.value=pr(r().palette[e.key])??`#000000`),b(()=>s.value=i()[e.key]??r().palette[e.key]),t})()})),e})(),(()=>{var t=DC(),i=t.firstChild,a=i.nextSibling;return i.$$click=()=>s(e=>({...e,palette:{...rr}})),a.$$click=()=>{let t=r()?.id;t&&(e.onChange(e.themes().filter(e=>e.id!==t)),n(e.themes().find(e=>e.id!==t)?.id??``))},t})(),OC(),(()=>{var e=MC(),t=e.firstChild,n=t.nextSibling;t.$$click=()=>o?.click(),L(t,A(M,{get when(){return r().backgroundImage},get fallback(){return FC()},get children(){return[(()=>{var e=kC();return b(t=>{var n=pn(r().backgroundImage),i=fn(r().backgroundImage);return n!==t.e&&F(e,`src`,t.e=n),i!==t.t&&F(e,`srcset`,t.t=i),t},{e:void 0,t:void 0}),e})(),AC()]}})),n.addEventListener(`change`,e=>{e.stopPropagation(),u(e.currentTarget.files?.[0]),e.currentTarget.value=``}),n.$$input=e=>e.stopPropagation();var i=o;return typeof i==`function`?je(i,n):o=n,L(e,A(M,{get when(){return r().backgroundImage},get children(){var e=jC(),t=e.firstChild;t.firstChild;var n=t.nextSibling.firstChild,i=n.firstChild.nextSibling,a=i.nextSibling,o=a.firstChild,c=n.nextSibling,l=c.firstChild.nextSibling,u=l.nextSibling,d=u.firstChild,f=c.nextSibling;return L(t,()=>{let e=r()?.backgroundImageBytes;return e?` — ${Math.max(1,Math.round(e/1024))} KB`:``},null),i.$$input=e=>s(t=>({...t,backgroundDim:Number(e.currentTarget.value)})),L(a,()=>Math.round((r().backgroundDim??.55)*100),o),l.$$input=e=>s(t=>({...t,surfaceAlpha:Number(e.currentTarget.value)})),L(u,()=>Math.round((r().surfaceAlpha??.82)*100),d),f.$$click=()=>s(e=>({...e,backgroundImage:void 0})),b(()=>i.value=r().backgroundDim??.55),b(()=>l.value=r().surfaceAlpha??.82),e}}),null),b(e=>{var n=`bgpick`+(r().backgroundImage?` has`:``),i=r().backgroundImage?`click to replace this background image (PNG/JPG/WebP)`:`choose a background image (PNG/JPG/WebP)`;return n!==e.e&&I(t,e.e=n),i!==e.t&&F(t,`title`,e.t=i),e},{e:void 0,t:void 0}),e})(),NC()]}),null),t})()}function Ew(e){let t=(e,t)=>{let n=Array.isArray(t?.apiKeys)&&t.apiKeys.length?t.apiKeys.filter(e=>typeof e==`string`&&e.trim()):t?.apiKey?[String(t.apiKey)]:[``];return{name:e,baseUrl:t?.baseUrl??``,apiKeys:n.length?n:[``],model:t?.model??``}},[n,r]=y(Object.entries(e.cfg.providers??{}).map(([e,n])=>t(e,n))),[i,a]=y(e.cfg.defaultProvider??``),o=()=>e.cfg.defaultProvider??``,s=()=>{let e=[...new Set(n().map(e=>e.name.trim()).filter(Boolean))],t=i();return t&&!e.includes(t)&&e.push(t),e},c=()=>{let e=i();return e?n().some(t=>t.name.trim()===e)?``:e:``},[l,u]=y(Math.round((e.cfg.progressIntervalMs??6e5)/6e4)),[d,f]=y(e.cfg.progressMinChars??4e3),[p,m]=y(e.cfg.contextTokenBudget==null?null:Math.round(e.cfg.contextTokenBudget/1e3)),[h,g]=y(e.cfg.contextWindowTokens?Math.round(e.cfg.contextWindowTokens/1e3):0),[_,v]=y(e.cfg.maxSpawnDepth??3),[ee,S]=y(!!e.cfg.shortContext),[C,w]=y(``),[T,te]=y(!1),[E,D]=y((e.cfg.tasks??[]).map(e=>({...e}))),[ne,re]=y((e.cfg.mcpServers??[]).map(e=>({...e}))),[ie,O]=y(Object.fromEntries((e.cfg.mcpServers??[]).map((e,t)=>[t,e.headers?JSON.stringify(e.headers):``]))),[ae,oe]=y({}),[se,ce]=y(Object.fromEntries((e.cfg.mcpServers??[]).map((e,t)=>{let n=e.headers??{},r=Object.keys(n);if(!r.length)return[t,`none`];let i=r.length===1?r[0]:``;return i===`Authorization`&&/^Bearer /i.test(n[i]??``)?[t,`bearer`]:[t,r.length===1?`header`:`json`]}))),[le,ue]=y(Object.fromEntries((e.cfg.mcpServers??[]).map((e,t)=>{let n=e.headers??{},r=Object.keys(n);if(r.length!==1)return[t,``];let i=r[0];return[t,i===`Authorization`?(n[i]??``).replace(/^Bearer /i,``):n[i]??``]}))),[de,fe]=y(Object.fromEntries((e.cfg.mcpServers??[]).map((e,t)=>{let n=Object.keys(e.headers??{}),r=n.length===1?n[0]:``;return[t,r&&r!==`Authorization`?r:``]}))),[pe,k]=y({}),me={},he=async(e,t)=>{if(!ne()[e])return;let n=await Y(`/api/mcp/test`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(t)}).catch(()=>null);ne()[e]&&n&&k(t=>({...t,[e]:n.ok?{kind:`ok`,text:`${n.tools?.length??0} tools`}:{kind:`err`,text:n.needsOAuth?`needs authorization — press 🔑`:n.error??`no response`,...n.needsOAuth?{needsOAuth:!0}:{}}}))},[ge,_e]=y({}),[ve,ye]=y({}),be=e=>{let t=yC(ve(),e);return t&&(t.required||t.authorized)?t:null},xe=async()=>{let e=await Y(`/api/mcp`).catch(()=>null);_e(Object.fromEntries((e?.states??[]).map(e=>[e.name,e])))},Se=async e=>{let t=String(e??``).trim();if(!t)return;let n=await Y(`/api/mcp/oauth/status?name=${encodeURIComponent(t)}`).catch(()=>null);n&&!n.error&&ye(e=>({...e,[t]:n}))},we=async(t,n)=>{if(!n.name){k(e=>({...e,[t]:{kind:`err`,text:`give it a name first`}}));return}k(e=>({...e,[t]:{kind:`testing`,text:`discovering the authorization server…`}}));let r=await Y(`/api/mcp/oauth/start`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({name:n.name,url:n.url})}).catch(()=>null);if(r?.alreadyAuthorized){k(e=>({...e,[t]:{kind:`ok`,text:`already authorized`}})),await Se(n.name),await xe();return}if(!r?.ok||!r.url){k(e=>({...e,[t]:{kind:`err`,text:r?.error??`no response`}})),await Se(n.name);return}window.open(r.url,`_blank`,`noopener`),k(e=>({...e,[t]:{kind:`testing`,text:`waiting for you to finish in the browser…`}}));let i=Date.now()+3e5;for(;Date.now()<i;){await new Promise(e=>setTimeout(e,1e3));let r=await Y(`/api/mcp/oauth/status?name=${encodeURIComponent(n.name)}`).catch(()=>null);if(r&&!r.error){if(ye(e=>({...e,[n.name]:r})),r.authorized){k(e=>({...e,[t]:{kind:`ok`,text:`authorized — the tools are available now`}})),await xe(),e.onSaved();return}if(r.flow?.phase===`error`){k(e=>({...e,[t]:{kind:`err`,text:r.flow.message??r.lastError??`authorization failed`}}));return}}}k(e=>({...e,[t]:{kind:`err`,text:`authorization timed out`}}))};x(()=>{P()===`mcp`&&(xe(),ne().forEach((e,t)=>{e.name&&Se(e.name)}))});let[Te,Ee]=y(``),[P,De]=y(`providers`),Oe=(t,n)=>{let{slot:r}=xC(e.theme.auto(),n);r===`dark`?Ke(t):r===`light`?Je(t):He(t)},ke=t=>e.theme.auto()?t===e.theme.dark()||t===e.theme.light():t===e.theme.activeId(),[Ae,je]=y([]),Me=async()=>{let e=await Y(`/api/archived`).catch(()=>null);je(e?.agents??[])},Ne=()=>Ae().filter(e=>!e.parent);x(()=>{P()===`archive`&&Me()});let Pe=[{key:`providers`,label:`🧦 providers`,hint:`endpoints, API keys, default models`},{key:`appearance`,label:`🎨 appearance`,hint:`theme, custom palettes, background image`},{key:`runtime`,label:`⚙️ runtime`,hint:`context budget, retries, spawn depth`},{key:`tasks`,label:`⏰ scheduled tasks`,hint:`cron prompts run against an agent`},{key:`mcp`,label:`🔌 MCP servers`,hint:`external tool servers exposed to every agent`},{key:`archive`,label:`🗄 archive`,hint:`agents you put away — restore or delete for good`},{key:`agents`,label:`👥 agents`,hint:`what exists (read-only)`},{key:`update`,label:`⬆️ live update`,hint:`restart onto a newer build`},{key:`skills`,label:`🧠 skills`,hint:`reusable playbooks available to the selected session`},{key:`help`,label:`❔️ help`,hint:`keyboard shortcuts and what each toggle does`}],Fe=()=>(e.cfg.agents??[]).map(e=>e.id),Ie=()=>e.theme.themes(),Le=()=>e.theme.activeId(),Re={auto:localStorage.getItem(`teapot.theme.auto`)===`1`,dark:localStorage.getItem(`teapot.theme.dark`)??`dark`,light:localStorage.getItem(`teapot.theme.light`)??`light`,fixed:localStorage.getItem(`teapot.theme`)??`dark`},ze=y(Re),Be=ze[0],Ve=t=>{let n={...Be(),...t};ze[1](n),e.theme.setAuto(n.auto),e.theme.setDark(n.dark),e.theme.setLight(n.light),e.theme.setActive(n.fixed);let r=t.dark??t.light??t.fixed;r&&e.theme.preview(r)},He=e=>Ve({fixed:e}),Ue=()=>Be().auto,We=e=>Ve({auto:e}),Ge=()=>Be().dark,Ke=e=>Ve({dark:e}),qe=()=>Be().light,Je=e=>Ve({light:e}),Ye=t=>e.theme.setThemes(t),Xe=()=>{let t=Re;e.theme.setAuto(t.auto),e.theme.setDark(t.dark),e.theme.setLight(t.light),e.theme.setActive(t.fixed),e.theme.preview(null)},Ze=e=>ir[e]??rr,Qe=()=>{let e={};for(let t of n()){if(!t.name.trim())return Ee(`provider name is required`),null;if(t.baseUrl&&!/^https?:\/\//.test(t.baseUrl))return Ee(`provider ${t.name}: baseUrl must start with http(s)://`),null;let n=t.apiKeys.map(e=>e.trim()).filter(Boolean);e[t.name.trim()]={baseUrl:t.baseUrl,...n.length?{apiKeys:n,apiKey:n[0]}:{},...t.model?{model:t.model}:{}}}return e},[$e,et]=y(`idle`),tt=e=>{Ee(e),et(e=>e===`saving`?`idle`:e)},nt=async t=>{t.preventDefault(),Ee(``),et(`saving`);let n=Qe();if(!n)return et(`idle`);let r=E().filter(e=>e.id?.trim()||e.prompt?.trim()).map((e,t)=>({id:e.id?.trim()||`task-${t+1}`,agent:e.agent,schedule:e.schedule,prompt:e.prompt,...e.forked?{forked:!0}:{}}));for(let e of r){if(!e.agent)return tt(`task "${e.id}": agent is required`);if(!e.schedule?.trim())return tt(`task "${e.id}": schedule is required`)}let a=[],o=new Set;for(let e of ne()){let t=String(e.name??``).trim(),n=String(e.url??``).trim(),r=e.transport??`http`,i=String(e.command??``).trim();if(t||n||i){if(!t)return tt(`MCP: a server needs a name`);if(o.has(t))return tt(`MCP: two servers are named "${t}"`);if(o.add(t),r===`stdio`?!i:!n)return tt(`MCP "${t}": ${r===`stdio`?`a command is`:`a url is`} required`);a.push({name:t,transport:r,enabled:e.enabled!==!1,...String(e.description??``).trim()?{description:String(e.description).trim()}:{},...n?{url:n}:{},...r===`stdio`?{command:i,...e.args?.length?{args:e.args}:{}}:{},...e.headers&&Object.keys(e.headers).length?{headers:e.headers}:{}})}}try{await Y(`/api/config`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({providers:n,defaultProvider:i()||void 0,progressIntervalMs:Math.max(1,l())*6e4,progressMinChars:Math.max(100,d()),...p()==null?{}:{contextTokenBudget:Math.max(1,p())*1e3},...h()>0?{contextWindowTokens:h()*1e3}:{},maxSpawnDepth:Math.max(0,_()),shortContext:ee(),...T()?{password:C()}:{},tasks:r,mcpServers:a})}),await xe(),await Promise.all(a.map((e,t)=>e.name?Se(e.name):Promise.resolve())),setTimeout(()=>{xe(),a.forEach((e,t)=>{e.name&&Se(e.name)})},1200),e.onSaved();let t=new Set(a.map(e=>e.name).filter(Boolean)),o=ne().filter(e=>{let n=String(e.name??``).trim();return t.has(n)&&ve()[n]?.required&&!ve()[n]?.authorized}).filter(t=>!e.announcedOAuth.has(String(t.name??``)));if(o.length>0){for(let t of o)e.announcedOAuth.add(String(t.name??``));wf(`${o.map(e=>String(e.name??``).trim()).filter(Boolean).join(`, `)||`a saved MCP server`} needs authorization — 🔑 authorize in MCP servers`)}e.theme.commitAppearance(Be()),e.theme.preview(null),et(`saved`),Object.assign(Re,Be()),setTimeout(()=>{et(`idle`),e.onClose()},400)}catch(e){Ee(e.message),et(`error`),setTimeout(()=>et(`idle`),1600)}};return A(wd,{title:`settings`,onClose:()=>{Xe(),e.onClose()},get children(){var t=BC(),x=t.firstChild,T=x.firstChild,_e=T.nextSibling.firstChild,ye=_e.firstChild.nextSibling,xe=ye.nextSibling;xe.firstChild;var Ae=xe.nextSibling.firstChild.firstChild.nextSibling;Ae.firstChild;var je=_e.nextSibling,Re=je.firstChild.nextSibling,ze=Re.firstChild.firstChild.nextSibling,Be=Re.nextSibling,Ve=je.nextSibling,Xe=Ve.firstChild.nextSibling,Qe=Xe.firstChild.firstChild.nextSibling,et=Xe.nextSibling,tt=et.firstChild,rt=tt.firstChild.nextSibling,it=et.nextSibling.firstChild,at=Ve.nextSibling,ot=at.firstChild.nextSibling.nextSibling,st=at.nextSibling,ct=st.firstChild.nextSibling,lt=st.nextSibling;lt.firstChild;var ut=lt.nextSibling;ut.firstChild;var ft=ut.nextSibling,pt=ft.firstChild.nextSibling.firstChild;pt.firstChild;var ht=pt.nextSibling,gt=ft.nextSibling;gt.firstChild;var _t=gt.nextSibling,vt=_t.firstChild.nextSibling.firstChild.nextSibling.firstChild,yt=vt.firstChild.nextSibling,bt=vt.nextSibling.firstChild.nextSibling,xt=x.nextSibling,St=xt.firstChild;return t.addEventListener(`submit`,nt),L(T,A(j,{each:Pe,children:e=>(()=>{var t=VC(),n=t.firstChild;return t.$$click=()=>De(e.key),L(n,()=>e.label),b(n=>{var r=`cfgmenu-item`+(P()===e.key?` on`:``),i=e.hint,a=P()===e.key?`page`:void 0;return r!==n.e&&I(t,n.e=r),i!==n.t&&F(t,`title`,n.t=i),a!==n.a&&F(t,`aria-current`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()})),L(_e,A(Ce,{get each(){return n()},children:(e,t)=>(()=>{var i=HC(),a=i.firstChild,o=a.nextSibling,s=o.nextSibling,c=s.nextSibling,l=c.nextSibling,u=l.firstChild;return a.$$input=e=>r(n().map((n,r)=>r===t?{...n,name:e.currentTarget.value}:n)),o.$$input=e=>r(n().map((n,r)=>r===t?{...n,baseUrl:e.currentTarget.value}:n)),s.$$input=e=>r(n().map((n,r)=>r===t?{...n,model:e.currentTarget.value}:n)),c.$$click=()=>r(n().filter((e,n)=>n!==t)),L(l,A(j,{get each(){return e().apiKeys},children:(i,a)=>(()=>{var o=WC(),s=o.firstChild;return s.$$input=e=>r(n().map((n,r)=>r===t?{...n,apiKeys:n.apiKeys.map((t,n)=>n===a()?e.currentTarget.value:t)}:n)),s.value=i,L(o,A(M,{get when(){return e().apiKeys.length>1},get children(){var e=UC();return e.$$click=()=>r(n().map((e,n)=>n===t?{...e,apiKeys:e.apiKeys.filter((e,t)=>t!==a())}:e)),e}}),null),b(()=>F(s,`placeholder`,a()===0?`api key`:`api key (backup)`)),o})()}),u),u.$$click=()=>r(n().map((e,n)=>n===t?{...e,apiKeys:[...e.apiKeys,``]}:e)),b(()=>a.value=e().name),b(()=>o.value=e().baseUrl),b(()=>s.value=e().model),i})()}),ye),ye.$$click=()=>r([...n(),{name:``,baseUrl:``,apiKeys:[``],model:``}]),L(xe,A(j,{each:bC,children:e=>(()=>{var t=GC();return t.firstChild,t.$$click=()=>{let t=n().filter(t=>t.name!==e.key);r([...t,{name:e.key,baseUrl:e.url,apiKeys:[``],model:e.model}]),i()||a(e.key)},L(t,()=>e.label,null),b(()=>F(t,`title`,`fill a ${e.label} row — ${e.url}${e.model?` (model: ${e.model})`:``}`)),t})()}),null),Ae.addEventListener(`change`,e=>a(e.currentTarget.value)),L(Ae,A(j,{get each(){return s()},children:e=>(()=>{var t=KC();return t.value=e,L(t,e),t})()}),null),L(_e,A(M,{get when(){return c()},get children(){var e=IC(),t=e.firstChild.nextSibling,n=t.nextSibling.nextSibling,r=n.nextSibling.nextSibling;return L(t,c),L(e,()=>c()===o()?` — the dropdown above cannot show it.`:` — it was replaced by your selection.`,n),L(r,c),e}}),null),ze.addEventListener(`change`,e=>{We(e.currentTarget.checked)}),L(je,A(M,{get when(){return Ue()},get children(){var e=LC(),t=e.firstChild,n=t.firstChild.nextSibling,r=t.nextSibling.firstChild.nextSibling;return n.addEventListener(`change`,e=>{Ke(e.currentTarget.value)}),L(n,A(j,{get each(){return Ie().filter(e=>e.mode===`dark`).map(e=>({key:e.id,label:`${e.label} (custom)`})).concat($d.filter(e=>e.mode===`dark`))},children:e=>(()=>{var t=KC();return L(t,()=>e.label),b(()=>t.value=e.key),t})()})),r.addEventListener(`change`,e=>{Je(e.currentTarget.value)}),L(r,A(j,{get each(){return Ie().filter(e=>e.mode===`light`).map(e=>({key:e.id,label:`${e.label} (custom)`})).concat($d.filter(e=>e.mode===`light`))},children:e=>(()=>{var t=KC();return L(t,()=>e.label),b(()=>t.value=e.key),t})()})),b(()=>n.value=Ge()),b(()=>r.value=qe()),e}}),Be),L(je,A(j,{each:[{mode:`dark`,title:`dark themes`},{mode:`light`,title:`light themes`}],children:e=>A(M,{get when(){return[...Ie(),...$d].some(t=>t.mode===e.mode)},get children(){return[(()=>{var t=qC();return L(t,()=>e.title),t})(),(()=>{var t=JC();return L(t,A(j,{get each(){return Ie().filter(t=>t.mode===e.mode)},children:e=>(()=>{var t=YC(),n=t.firstChild,r=n.nextSibling,i=r.firstChild;return t.$$click=()=>Oe(e.id,e.mode),L(n,A(bf,{get palette(){return e.palette},get backgroundImage(){return e.backgroundImage},get surfaceAlpha(){return e.surfaceAlpha},get backgroundDim(){return e.backgroundDim}})),L(r,()=>e.label,i),b(n=>{var r=`themecard`+(ke(e.id)?` on`:``),i=`${e.label} (custom)${e.backgroundImage?` · with a background image`:``}`,a=ke(e.id);return r!==n.e&&I(t,n.e=r),i!==n.t&&F(t,`title`,n.t=i),a!==n.a&&F(t,`aria-pressed`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()}),null),L(t,A(j,{get each(){return $d.filter(t=>t.mode===e.mode)},children:e=>(()=>{var t=XC(),n=t.firstChild,r=n.nextSibling;return t.$$click=()=>Oe(e.key,e.mode),L(n,A(bf,{get palette(){return Ze(e.key)}})),L(r,()=>e.label),b(n=>{var r=`themecard`+(ke(e.key)?` on`:``),i=`${e.label} (${e.mode})`,a=ke(e.key);return r!==n.e&&I(t,n.e=r),i!==n.t&&F(t,`title`,n.t=i),a!==n.a&&F(t,`aria-pressed`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()}),null),t})()]}})}),null),L(je,A(Tw,{themes:Ie,get paintedId(){return e.theme.paintedId()},onChange:e=>{let t=cr(e),n=e;if(!t.ok){let t=e.map(e=>e.backgroundImage?{...e,backgroundImage:void 0,backgroundDim:void 0,surfaceAlpha:void 0,backgroundImageBytes:void 0}:e),r=cr(t);if(r.ok)n=t,wf(`storage was full — saved without the background image(s)`);else{wf(r.error??`could not save theme`);return}}Ye(n);let r=e=>n.some(t=>t.id===e)||$d.some(t=>t.key===e);r(Le())||(He(`dark`),localStorage.setItem(`teapot.theme`,`dark`)),r(Ge())||(Ke(`dark`),localStorage.setItem(`teapot.theme.dark`,`dark`)),r(qe())||(Je(`light`),localStorage.setItem(`teapot.theme.light`,`light`))},onPick:e=>{let t=Ie().find(t=>t.id===e)?.mode??$d.find(t=>t.key===e)?.mode??`dark`,n=xC(Ue(),t);n.slot===`dark`?Ke(e):n.slot===`light`?Je(e):He(e)}}),null),Qe.$$input=e=>{w(e.currentTarget.value),te(!0)},L(et,A(yf,{label:`progress interval (min)`,get value(){return l()},onValue:e=>u(e),hint:`how often the harness asks for a progress report`}),tt),L(et,A(yf,{label:`progress min chars`,get value(){return d()},onValue:e=>f(e),hint:`progress prompts wait for this much real output`}),tt),rt.$$input=e=>m(e.currentTarget.value===``?null:Number(e.currentTarget.value)),L(et,A(yf,{label:`context window (k tok)`,get value(){return h()},onValue:e=>g(e),hint:`model's real window — 0/blank hides the % gauge`}),null),L(et,A(yf,{label:`max spawn depth`,get value(){return _()},onValue:e=>v(e),hint:`sub-agent nesting limit (0 = no spawning)`}),null),it.addEventListener(`change`,e=>S(e.currentTarget.checked)),L(at,A(M,{get when(){return ne().length>0},get fallback(){return ZC()},get children(){return A(Ce,{get each(){return ne()},children:(e,t)=>{let n=()=>ge()[e().name],r=e=>re(ne().map((n,r)=>r===t?{...n,...e}:n));return(()=>{var i=cw(),a=i.firstChild,o=a.firstChild,s=o.nextSibling,c=s.nextSibling,l=c.firstChild,u=c.nextSibling,d=a.nextSibling,f=d.firstChild,p=d.nextSibling,m=p.firstChild,h=p.nextSibling,g=h.firstChild,_=g.firstChild,v=h.nextSibling,ee=v.firstChild;return o.$$input=e=>r({name:e.currentTarget.value}),s.$$input=e=>{r({url:e.currentTarget.value});let n=e.currentTarget.value.trim();clearTimeout(me[t]),/^https?:\/\//.test(n)&&(me[t]=setTimeout(()=>{he(t,{...ne()[t],url:n})},700))},l.addEventListener(`change`,e=>r({enabled:e.currentTarget.checked})),u.$$click=()=>re(ne().filter((e,n)=>n!==t)),f.$$input=e=>r({description:e.currentTarget.value}),m.addEventListener(`change`,e=>r({transport:e.currentTarget.value})),L(p,A(M,{get when(){return e().transport===`stdio`},get children(){return[(()=>{var t=QC();return t.$$input=e=>r({command:e.currentTarget.value}),b(()=>t.value=e().command??``),t})(),(()=>{var t=$C();return t.$$input=e=>r({args:e.currentTarget.value.split(` `).filter(Boolean)}),b(()=>t.value=(e().args??[]).join(` `)),t})()]}}),null),g.addEventListener(`change`,e=>{let n=e.currentTarget.value;if(ce(e=>({...e,[t]:n})),n===`none`)r({headers:void 0});else if(n===`bearer`){let e=le()[t]??``;r({headers:e?{Authorization:`Bearer ${e}`}:void 0})}else if(n===`header`){let e=de()[t]??``,n=le()[t]??``;r({headers:e&&n?{[e]:n}:void 0})}}),L(g,A(M,{get when(){return be(String(e().name??``))},children:e=>(()=>{var t=lw();return L(t,()=>e().authorized?`OAuth — authorized`:`OAuth — authorization needed`),t})()}),_),L(h,A(M,{get when(){return se()[t]===`bearer`},get children(){var e=ew();return e.$$input=e=>{let n=e.currentTarget.value;ue(e=>({...e,[t]:n})),r({headers:n?{Authorization:`Bearer ${n}`}:void 0})},b(()=>e.value=le()[t]??``),e}}),null),L(h,A(M,{get when(){return se()[t]===`header`},get children(){return[(()=>{var e=tw();return e.$$input=e=>{let n=e.currentTarget.value;fe(e=>({...e,[t]:n}));let i=le()[t]??``;r({headers:n&&i?{[n]:i}:void 0})},b(()=>e.value=de()[t]??``),e})(),(()=>{var e=nw();return e.$$input=e=>{let n=e.currentTarget.value;ue(e=>({...e,[t]:n}));let i=de()[t]??``;r({headers:i&&n?{[i]:n}:void 0})},b(()=>e.value=le()[t]??``),e})()]}}),null),L(i,A(M,{get when(){return se()[t]===`json`},get children(){var e=rw(),n=e.firstChild;return n.$$input=e=>{let n=e.currentTarget.value;if(O(e=>({...e,[t]:n})),!n.trim())r({headers:void 0});else try{let e=JSON.parse(n);if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`not an object`);r({headers:e}),oe(e=>({...e,[t]:``}))}catch{oe(e=>({...e,[t]:`must be a JSON object — not applied`}))}},b(()=>n.value=ie()[t]??``),e}}),v),ee.$$click=async()=>{let e=ne()[t];if(!e.name){k(e=>({...e,[t]:{kind:`err`,text:`give it a name first`}}));return}k(e=>({...e,[t]:{kind:`testing`,text:`connecting…`}}));let n=await Y(`/api/mcp/test`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e)}).catch(()=>null);k(e=>({...e,[t]:n?.ok?{kind:`ok`,text:`${n.tools?.length??0} tool${n.tools?.length===1?``:`s`}`,tools:n.tools??[]}:{kind:`err`,text:n?.error??`no response`,...n?.needsOAuth?{needsOAuth:!0}:{}}})),n?.ok||await Se(e.name)},L(v,A(M,{get when(){return N(()=>!!yC(ve(),String(e().name??``))?.required)()&&!yC(ve(),String(e().name??``))?.authorized},get children(){var n=iw();return n.$$click=()=>void we(t,e()),n}}),null),L(v,A(M,{get when(){return yC(ve(),String(e().name??``))?.authorized},get children(){return aw()}}),null),L(v,A(M,{get when(){return n()},get children(){var e=ow();return L(e,(()=>{var e=N(()=>n()?.status===`connected`);return()=>e()?`● ${n()?.tools} tools`:N(()=>n()?.status===`error`)()?`● error`:n()?.status===`disabled`?`● off`:`● idle`})()),b(t=>{var r=`mcpstate `+(n()?.status??``),i=n()?.lastError??``;return r!==t.e&&I(e,t.e=r),i!==t.t&&F(e,`title`,t.t=i),t},{e:void 0,t:void 0}),e}}),null),L(i,A(M,{get when(){return ae()[t]},get children(){var e=sw();return L(e,()=>ae()[t]),e}}),null),L(i,A(M,{get when(){return pe()[t]},children:n=>(()=>{var r=pw(),i=r.firstChild,a=i.firstChild;return L(a,()=>n().text),L(i,A(M,{get when(){return n().needsOAuth},get children(){return uw()}}),null),L(r,A(M,{get when(){return(n().tools?.length??0)>0},get children(){var e=dw(),t=e.firstChild,r=t.firstChild.nextSibling;r.nextSibling;var i=t.nextSibling;return L(t,()=>n().tools?.length,r),L(t,()=>n().tools?.length===1?``:`s`,null),L(i,A(j,{get each(){return n().tools??[]},children:e=>(()=>{var t=hw(),n=t.firstChild;return L(n,()=>e.name),L(t,A(M,{get when(){return e.description},get children(){var t=mw();return L(t,()=>e.description),t}}),null),b(()=>F(t,`title`,e.description??``)),t})()})),e}}),null),L(r,A(M,{get when(){return yC(ve(),String(e().name??``))?.authorized},get children(){var n=fw(),r=n.firstChild.nextSibling;return r.$$click=async()=>{confirm(`Disconnect ${e().name}?\n\nThe stored OAuth grant is deleted and you will have to authorize again in a browser.`)&&(await Y(`/api/mcp/oauth/disconnect`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({name:e().name})}).catch(()=>{}),await Se(e().name),k(e=>({...e,[t]:{kind:`ok`,text:`disconnected`}})))},n}}),null),b(()=>I(r,`mcpresult `+(n().kind===`err`?`err`:`ok`))),r})()}),null),b(()=>o.value=e().name),b(()=>s.value=e().url??``),b(()=>l.checked=e().enabled!==!1),b(()=>f.value=e().description??``),b(()=>m.value=e().transport??`http`),b(()=>g.value=be(String(e().name??``))?`oauth`:se()[t]??`none`),i})()}})}}),ot),ot.$$click=()=>re([...ne(),{name:``,url:``,transport:`http`,enabled:!0}]),L(st,A(M,{get when(){return E().length>0},get children(){return A(Ce,{get each(){return E()},children:(e,t)=>(()=>{var n=gw(),r=n.firstChild,i=r.firstChild,a=i.nextSibling,o=a.nextSibling,s=o.nextSibling,c=s.firstChild,l=s.nextSibling,u=r.nextSibling;return i.$$input=e=>D(E().map((n,r)=>r===t?{...n,id:e.currentTarget.value}:n)),a.$$input=e=>D(E().map((n,r)=>r===t?{...n,agent:e.currentTarget.value}:n)),o.$$input=e=>D(E().map((n,r)=>r===t?{...n,schedule:e.currentTarget.value}:n)),c.addEventListener(`change`,e=>D(E().map((n,r)=>r===t?{...n,forked:e.currentTarget.checked}:n))),l.$$click=()=>D(E().filter((e,n)=>n!==t)),u.$$input=e=>D(E().map((n,r)=>r===t?{...n,prompt:e.currentTarget.value}:n)),b(()=>i.value=e().id),b(()=>a.value=e().agent),b(()=>o.value=e().schedule),b(()=>c.checked=!!e().forked),b(()=>u.value=e().prompt),n})()})}}),ct),ct.$$click=()=>D([...E(),{id:``,agent:Fe()[0]??``,schedule:`every 30m`,prompt:``}]),L(lt,A(M,{get when(){return Ne().length>0},get fallback(){return _w()},get children(){return A(j,{get each(){return Ne()},children:t=>(()=>{var n=vw(),r=n.firstChild,i=r.firstChild,a=i.nextSibling,o=a.firstChild,s=a.nextSibling,c=r.nextSibling,l=c.nextSibling;return L(i,()=>t.id),L(a,()=>t.sessions,o),L(a,()=>t.sessions===1?``:`s`,null),L(a,(()=>{var e=N(()=>(t.subs??0)>0);return()=>e()?` · +${t.subs} sub-agent${t.subs===1?``:`s`} (restored together)`:``})(),null),L(a,(()=>{var e=N(()=>!!t.archivedAt);return()=>e()?` · archived ${mt(new Date(t.archivedAt).toISOString())}`:``})(),null),L(s,()=>t.workspace),c.$$click=async()=>{let n=await Y(`/api/agents/${t.id}/restore`,{method:`POST`}).catch(()=>null);await Me(),e.onSaved();let r=(n?.ids?.length??1)-1;wf((n?.live===!1?`restored ${t.id} — it could not be started (check its provider)`:`restored ${t.id}`)+(r>0?` + ${r} sub-agent${r===1?``:`s`}`:``))},l.$$click=async()=>{confirm(`PERMANENTLY DELETE ${t.id}?\n\n${t.sessions} session${t.sessions===1?``:`s`} of history will be erased from disk along with the config entry. This cannot be undone — archiving was the reversible option.`)&&(await Y(`/api/agents/${t.id}/purge`,{method:`DELETE`}).catch(()=>{}),await Me(),e.onSaved(),wf(`deleted ${t.id} for good`))},b(()=>F(s,`title`,t.workspace)),n})()})}}),null),L(ut,A(j,{get each(){return e.cfg.agents??[]},children:e=>(()=>{var t=bw(),n=t.firstChild,r=n.nextSibling;return L(n,()=>e.id),L(r,()=>e.workspace),L(t,A(M,{get when(){return e.parent},get children(){var t=yw();return t.firstChild,L(t,()=>e.parent,null),t}}),null),t})()}),null),L(pt,()=>e.cfg.version??`unknown`,null),ht.$$click=async e=>{try{Ee(``);let t=e.currentTarget;t.disabled=!0,t.textContent=`updating…`;let n=await Y(`/api/update/restart`,{method:`POST`});if(!n.ok)throw Error((await n.json()).error??`restart failed`);t.textContent=`restarting…`;let r=null,i=!1;for(let e=0;e<120&&!i;e++){await new Promise(e=>setTimeout(e,1e3));try{let e=await Y(`/api/version`);if(!e.version)continue;r===null&&(r=e.uptimeSeconds??null),(e.version!==`0.37.172`||typeof e.uptimeSeconds==`number`&&r!==null&&e.uptimeSeconds<r)&&(i=!0,window.location.reload())}catch{}}if(!i)throw Error(`restart timeout — new server did not come up`)}catch(e){Ee(e.message)}finally{e.currentTarget.disabled=!1,e.currentTarget.textContent=`update & restart`}},L(gt,A(M,{get when(){return e.skills.length>0},get fallback(){return(()=>{var t=xw();return L(t,()=>e.hasSelection?`this session has no skills yet — the agent saves them with save_skill once a procedure proves itself`:`select a session to see the skills available to it`),t})()},get children(){var t=RC();return L(t,A(j,{get each(){return e.skills},children:t=>{let[n,r]=y(!1),[i,a]=y(null),[o,s]=y(``),c=async()=>{if(n())return r(!1);if(r(!0),i()===null&&e.agentId)try{let n=await Y(`/api/agents/${e.agentId}/skills/${encodeURIComponent(t.name)}`);a(String(n.text??``))}catch(e){s(e.message)}};return(()=>{var e=Cw(),r=e.firstChild,a=r.firstChild,s=a.nextSibling,l=s.nextSibling;return r.$$click=c,L(a,()=>n()?`▾`:`▸`),L(s,()=>t.name),L(l,()=>t.description),L(e,A(M,{get when(){return n()},get children(){return A(M,{get when(){return i()!==null},get fallback(){return(()=>{var e=ww();return L(e,()=>o()||`loading…`),e})()},get children(){var e=Sw();return b(()=>e.innerHTML=dt(String(i()??``))),e}})}}),null),b(()=>e.classList.toggle(`open`,!!n())),e})()}})),t}}),null),L(yt,(()=>{var t=N(()=>!!e.features);return()=>t()?N(()=>!!e.features.imageResize.available)()?`on — ${e.features.imageResize.tool}, long edge ≤ ${e.features.imageResize.maxEdge}px`:`off — no ffmpeg / ImageMagick found; uploads are served as-is`:`checking…`})()),L(bt,(()=>{var t=N(()=>!!e.features);return()=>t()?N(()=>!!e.features.pty.available)()?`on — ${e.features.pty.provider}`:`off — no pty provider; terminals run on plain pipes (no resize)`:`checking…`})()),L(xt,A(M,{get when(){return Te()},get children(){var e=zC();return L(e,Te),e}}),St),L(St,(()=>{var e=N(()=>$e()===`saving`);return()=>e()?`saving…`:N(()=>$e()===`saved`)()?`✓ saved`:$e()===`error`?`✕ failed`:`save settings`})()),b(t=>{var n=P()!==`providers`,r=P()!==`appearance`,i=P()!==`runtime`,a=e.cfg.hasPassword?`(unchanged — type to replace)`:`(none — loopback only)`,o=P()!==`mcp`,s=P()!==`tasks`,c=P()!==`archive`,l=P()!==`agents`,u=P()!==`update`,d=P()!==`skills`,f=P()!==`help`,p=$e()===`saved`,m=$e()===`error`,h=$e()===`saving`;return n!==t.e&&_e.classList.toggle(`hide`,t.e=n),r!==t.t&&je.classList.toggle(`hide`,t.t=r),i!==t.a&&Ve.classList.toggle(`hide`,t.a=i),a!==t.o&&F(Qe,`placeholder`,t.o=a),o!==t.i&&at.classList.toggle(`hide`,t.i=o),s!==t.n&&st.classList.toggle(`hide`,t.n=s),c!==t.s&&lt.classList.toggle(`hide`,t.s=c),l!==t.h&&ut.classList.toggle(`hide`,t.h=l),u!==t.r&&ft.classList.toggle(`hide`,t.r=u),d!==t.d&&gt.classList.toggle(`hide`,t.d=d),f!==t.l&&_t.classList.toggle(`hide`,t.l=f),p!==t.u&&St.classList.toggle(`saved`,t.u=p),m!==t.c&&St.classList.toggle(`error`,t.c=m),h!==t.w&&(St.disabled=t.w=h),t},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0,r:void 0,d:void 0,l:void 0,u:void 0,c:void 0,w:void 0}),b(()=>Ae.value=i()),b(()=>ze.checked=Ue()),b(()=>Qe.value=C()),b(()=>rt.value=p()??``),b(()=>it.checked=ee()),t}})}De([`click`,`input`]);var Dw=new Set([`png`,`jpg`,`jpeg`,`gif`,`webp`,`svg`,`bmp`,`ico`,`avif`]),Ow=new Set([`mp4`,`webm`,`mov`,`mkv`,`avi`,`m4v`]),kw=new Set([`mp3`,`wav`,`ogg`,`m4a`,`flac`,`aac`,`opus`]);function Aw(e){let t=e.split(`.`).pop()?.toLowerCase()??``,n=jw(e);return n===`image`?`🖼`:n===`video`?`🎬️`:n===`audio`?`🎵`:[`ts`,`tsx`,`mts`,`cts`].includes(t)?`🟦`:[`js`,`mjs`,`cjs`,`jsx`].includes(t)?`🟨`:t===`json`||t===`jsonc`?`🧾`:t===`md`||t===`mdx`||t===`markdown`?`📝`:t===`css`||t===`scss`||t===`less`?`🎨`:t===`html`||t===`htm`||t===`svg`?`🌐️`:[`py`,`pyi`].includes(t)?`🐍`:t===`rs`?`🦀`:t===`go`?`🐹`:t===`java`||t===`kt`||t===`kts`?`☕️`:t===`rb`?`💎`:t===`php`?`🐘`:t===`c`||t===`h`||t===`cpp`||t===`hpp`||t===`cc`?`🧩`:t===`sh`||t===`bash`||t===`zsh`||t===`fish`?`🐚`:t===`sql`?`🗄`:t===`yml`||t===`yaml`||t===`toml`||t===`ini`||t===`conf`?`⚙️`:t===`lock`?`🔒️`:e===`Dockerfile`||t===`dockerfile`?`🐳`:t===`zip`||t===`gz`||t===`tar`||t===`tgz`||t===`bz2`?`📦`:t===`pdf`?`📕`:t===`txt`||t===`log`?`📄`:`·`}function jw(e){let t=e.split(`.`).pop()?.toLowerCase()??``;return Dw.has(t)?`image`:Ow.has(t)?`video`:kw.has(t)?`audio`:null}var Mw=new Map,Nw=e=>{let t=Mw.get(e);return t||(t={expanded:new Set,preview:null,media:null,viewMode:`code`},Mw.set(e,t)),t},Pw=P(`<span class=fsize>`),Fw=P(`<div><span class=ficon></span><span class=fname>`),Iw=P(`<h3 title="the agent's workspace — lazy-loaded, dotfiles hidden; click a folder to expand, a file to preview"style=display:flex;align-items:center;gap:6px>🗂 files <span class=muted style=text-transform:none;letter-spacing:0>· `),Lw=P(`<div class=filebox>`),Rw=P(`<div class=muted style=padding:6px>`),zw=P(`<img>`),Bw=P(`<div class=mediapreview><div class="meta muted"> preview`),Vw=P(`<button title="rendered markdown">👁 preview`),Hw=P(`<button title="edit and save back to the workspace">✎ edit`),Uw=P(`<div class=filetoolbar><button title="syntax-highlighted source">&lt;/> code`),Ww=P(`<div class=fileeditor><textarea class=mono></textarea><div class=filerow-actions><span class=muted> bytes</span><button class=savebtn>`),Gw=P(`<div class=mono style=margin:0;color:var(--dim)>(binary file — inspect it from the terminal)`),Kw=P(`<div class="content mdpreview shikiwrap">`),qw=P(`<video controls>`),Jw=P(`<audio controls>`);function Yw(e){let t=Nw(e.agentId),[n,r]=y(new Map),[i,a]=y(t.expanded),[o,s]=y(t.preview),c=e=>{t.preview=e,s(e)},l=e=>{t.expanded=e,a(e)},[u,d]=y(t.media),f=e=>{t.media=e,d(e)},[p,m]=y(t.viewMode),h=e=>{t.viewMode=e,m(e)},[g,_]=y(``),[v,ee]=y(localStorage.getItem(`teapot.ignoreMode`)??`dim`),S=()=>{let e=[`dim`,`hide`,`show`],t=e[(e.indexOf(v())+1)%3];ee(t),localStorage.setItem(`teapot.ignoreMode`,t)},C=e=>v()!==`hide`||!e.ignored,[w,te]=y(localStorage.getItem(`teapot.showHidden`)===`1`),E=()=>{let e=!w(),t=[``,...i()];Promise.all(t.map(async t=>({p:t,rows:await re(t,e)}))).then(t=>{te(e),localStorage.setItem(`teapot.showHidden`,e?`1`:`0`);for(let{p:e,rows:n}of t)n&&ie(e,n)})},D=(e,t)=>t.map(t=>({name:String(t.name),path:e?`${e}/${t.name}`:String(t.name),dir:!!t.dir,...typeof t.size==`number`?{size:t.size}:{},...t.ignored?{ignored:!0}:{}}));async function ne(e){return re(e,w())}async function re(t,n){try{let r=new URLSearchParams;t&&r.set(`path`,t),n&&r.set(`hidden`,`1`);let i=await Y(`/api/agents/${e.agentId}/tree?${r.toString()}`);return D(t,i.entries??[])}catch(e){return _(e.message),null}}let ie=(e,n)=>r(r=>{let i=r.get(e);if(!i)return new Map(r).set(e,n);let a=new Map(i.map(e=>[e.path,e])),o=n.map(e=>{let t=a.get(e.path);return t&&t.dir===e.dir&&t.size===e.size&&t.ignored===e.ignored&&t.name===e.name?t:e}).filter(e=>n.some(t=>t.path===e.path)||t.preview?.path===e.path),s=new Map(r);return s.set(e,o),s}),O=``;x(()=>{let t=e.agentId;t!==O&&(O=t,l(new Set),c(null),f(null),r(new Map),ne(``).then(e=>{e&&O===t&&r(new Map([[``,e]]))}))});let ae=async e=>{let t=new Set(i());if(t.has(e.path))t.delete(e.path),l(t);else if(t.add(e.path),l(t),!n().has(e.path)){let t=await ne(e.path);t&&ie(e.path,t)}},[oe,se]=y(``),[ce,le]=y(!1),[ue,de]=y(``),[fe,pe]=y(!1),k=e=>/\.(md|markdown|mdx)$/i.test(e),me=0,he=async e=>{let t=++me;se(``),le(!0);try{let{highlightChunks:n}=await J(async()=>{let{highlightChunks:e}=await Promise.resolve().then(()=>_x);return{highlightChunks:e}},void 0);for await(let r of n(e.path,e.content)){if(me!==t)return;se(e=>e+r)}}catch{me===t&&se(``)}finally{me===t&&le(!1)}};T(()=>{me++});let ge=async(t,n)=>{let r=jw(t.path);if(r)c({path:t.path,content:``,binary:!0}),f({path:t.path,kind:r}),h(`media`);else try{let r=await Y(`/api/agents/${e.agentId}/file?path=${encodeURIComponent(t.path)}`);f(null),c({path:t.path,content:r.content??``,binary:r.binary,truncated:r.truncated}),de(r.content??``),h(r.binary?`code`:n),!r.binary&&n!==`md`&&he({path:t.path,content:r.content??``,truncated:r.truncated})}catch(e){wf(`open failed: ${e.message}`)}},_e=async()=>{let t=o();if(t&&!fe()){pe(!0);try{await Y(`/api/agents/${e.agentId}/file?path=${encodeURIComponent(t.path)}`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({content:ue(),baseContent:t.content})}),c({...t,content:ue()}),wf(`saved ${t.path}`)}catch(e){let n=e.payload,r=n&&typeof n==`object`&&n.error===`file changed on disk`?n:null;r?.current===void 0?wf(`save failed: ${e.message}`):confirm(`This file changed on disk since you opened it.
175
+ \v\f…\u2028\u2029])`),t));else if(c===`posix`){if(!i&&(u===`graph`||u===`print`)){if(r===`strict`)throw Error(`POSIX class "${u}" requires min target ES2024 or non-strict accuracy`);let e={graph:`!-~`,print:` -~`}[u];l&&(e=`\0-${eb(e.codePointAt(0)-1)}${eb(e.codePointAt(2)+1)}-\u{10FFFF}`),n(Kb(Ub(`[${e}]`),t))}else n(Kb(Wb(Ub(vb.get(u)),l),t))}else if(c===`property`)mb.has(Sy(u))||(e.key=`sc`);else if(c===`space`)n(Gb(my(`space`,{negate:l}),t));else if(c===`word`)n(Kb(Wb(Ub(fb),l),t));else throw Error(`Unexpected character set kind "${c}"`)}},Directive({node:e,parent:t,root:n,remove:r,replaceWith:i,removeAllPrevSiblings:a,removeAllNextSiblings:o}){let{kind:s,flags:c}=e;if(s===`flags`){if(!c.enable&&!c.disable)r();else{let e=sy({flags:c});e.body[0].body=o(),i(Kb(e,t),{traverse:!0})}}else if(s===`keep`){let e=n.body[0],r=n.body.length===1&&Rv(e,{type:`Group`})&&e.body[0].body.length===1?e.body[0]:n;if(t.parent!==r||r.body.length>1)throw Error($`Uses "\K" in a way that's unsupported`);let o=cy({behind:!0});o.body[0].body=a(),i(Kb(o,t))}else throw Error(`Unexpected directive kind "${s}"`)},Flags({node:e,parent:t}){if(e.posixIsAscii)throw Error(`Unsupported flag "P"`);if(e.textSegmentMode===`word`)throw Error(`Unsupported flag "y{w}"`);[`digitIsAscii`,`extended`,`posixIsAscii`,`spaceIsAscii`,`wordIsAscii`,`textSegmentMode`].forEach(t=>delete e[t]),Object.assign(e,{global:!1,hasIndices:!1,multiline:!1,sticky:e.sticky??!1}),t.options={disable:{x:!0,n:!0},force:{v:!0}}},Group({node:e}){if(!e.flags)return;let{enable:t,disable:n}=e.flags;t?.extended&&delete t.extended,n?.extended&&delete n.extended,t?.dotAll&&n?.dotAll&&delete t.dotAll,t?.ignoreCase&&n?.ignoreCase&&delete t.ignoreCase,t&&!Object.keys(t).length&&delete e.flags.enable,n&&!Object.keys(n).length&&delete e.flags.disable,!e.flags.enable&&!e.flags.disable&&delete e.flags},LookaroundAssertion({node:e},t){let{kind:n}=e;n===`lookbehind`&&(t.passedLookbehind=!0)},NamedCallout({node:e,parent:t,replaceWith:n}){let{kind:r}=e;if(r===`fail`)n(Kb(cy({negate:!0}),t));else throw Error(`Unsupported named callout "(*${r.toUpperCase()}"`)},Quantifier({node:e}){if(e.body.type===`Quantifier`){let t=sy();t.body[0].body.push(e.body),e.body=Kb(t,e)}},Regex:{enter({node:e},{supportedGNodes:t}){let n=[],r=!1,i=!1;for(let t of e.body)if(t.body.length===1&&t.body[0].kind===`search_start`)t.body.pop();else{let e=Lb(t.body);e?(r=!0,Array.isArray(e)?n.push(...e):n.push(e)):i=!0}r&&!i&&n.forEach(e=>t.add(e))},exit(e,{accuracy:t,passedLookbehind:n,strategy:r}){if(t===`strict`&&n&&r)throw Error($`Uses "\G" in a way that requires non-strict accuracy`)}},Subroutine({node:e},{jsGroupNameMap:t}){let{ref:n}=e;typeof n==`string`&&!Hb(n)&&(n=Nb(n,t),e.ref=n)}},Tb={Backreference({node:e},{multiplexCapturesToLeftByRef:t,reffedNodesByReferencer:n}){let{orphan:r,ref:i}=e;r||n.set(e,[...t.get(i).map(({node:e})=>e)])},CapturingGroup:{enter({node:e,parent:t,replaceWith:n,skip:r},{groupOriginByCopy:i,groupsByName:a,multiplexCapturesToLeftByRef:o,openRefs:s,reffedNodesByReferencer:c}){let l=i.get(e);if(l&&s.has(e.number)){let r=Gb(jb(e.number),t);c.set(r,s.get(e.number)),n(r);return}s.set(e.number,e),o.set(e.number,[]),e.name&&ib(o,e.name,[]);let u=o.get(e.name??e.number);for(let t=0;t<u.length;t++){let n=u[t];if(l===n.node||l&&l===n.origin||e===n.origin){u.splice(t,1);break}}if(o.get(e.number).push({node:e,origin:l}),e.name&&o.get(e.name).push({node:e,origin:l}),e.name){let t=ib(a,e.name,new Map),n=!1;if(l)n=!0;else for(let e of t.values())if(!e.hasDuplicateNameToRemove){n=!0;break}a.get(e.name).set(e,{node:e,hasDuplicateNameToRemove:n})}},exit({node:e},{openRefs:t}){t.get(e.number)===e&&t.delete(e.number)}},Group:{enter({node:e},t){t.prevFlags=t.currentFlags,e.flags&&(t.currentFlags=rb(t.currentFlags,e.flags))},exit(e,t){t.currentFlags=t.prevFlags}},Subroutine({node:e,parent:t,replaceWith:n},r){let{isRecursive:i,ref:a}=e;if(i){let n=t;for(;(n=n.parent)&&(n.type!==`CapturingGroup`||n.name!==a&&n.number!==a););r.reffedNodesByReferencer.set(e,n);return}let o=r.subroutineRefMap.get(a),s=a===0,c=s?jb(0):Ab(o,r.groupOriginByCopy,null),l=c;if(!s){let e=Pb(Mb(o,e=>e.type===`Group`&&!!e.flags)),t=e?rb(r.globalFlags,e):r.globalFlags;Ob(t,r.currentFlags)||(l=sy({flags:Fb(t)}),l.body[0].body.push(c))}n(Kb(l,t),{traverse:!s})}},Eb={Backreference({node:e,parent:t,replaceWith:n},r){if(e.orphan){r.highestOrphanBackref=Math.max(r.highestOrphanBackref,e.ref);return}let i=r.reffedNodesByReferencer.get(e).filter(t=>kb(t,e));i.length?i.length>1?n(Kb(sy({atomic:!0,body:i.reverse().map(e=>Zv({body:[$v(e.number)]}))}),t)):e.ref=i[0].number:n(Kb(cy({negate:!0}),t))},CapturingGroup({node:e},t){e.number=++t.numCapturesToLeft,e.name&&t.groupsByName.get(e.name).get(e).hasDuplicateNameToRemove&&delete e.name},Regex:{exit({node:e},t){let n=Math.max(t.highestOrphanBackref-t.numCapturesToLeft,0);for(let t=0;t<n;t++){let t=ey();e.body.at(-1).body.push(t)}}},Subroutine({node:e},t){e.isRecursive&&e.ref!==0&&(e.ref=t.reffedNodesByReferencer.get(e).number)}};function Db(e){Ty(e,{"*"({node:e,parent:t}){e.parent=t}})}function Ob(e,t){return e.dotAll===t.dotAll&&e.ignoreCase===t.ignoreCase}function kb(e,t){let n=t;do{if(n.type===`Regex`)return!1;if(n.type===`Alternative`)continue;if(n===e)return!1;let t=Ib(n.parent);for(let r of t){if(r===n)break;if(r===e||Rb(r,e))return!0}}while(n=n.parent);throw Error(`Unexpected path`)}function Ab(e,t,n,r){let i=Array.isArray(e)?[]:{};for(let[a,o]of Object.entries(e))a===`parent`?i.parent=Array.isArray(n)?r:n:o&&typeof o==`object`?i[a]=Ab(o,t,i,n):(a===`type`&&o===`CapturingGroup`&&t.set(i,t.get(e)??e),i[a]=o);return i}function jb(e){let t=py(e);return t.isRecursive=!0,t}function Mb(e,t){let n=[];for(;e=e.parent;)(!t||t(e))&&n.push(e);return n}function Nb(e,t){if(t.has(e))return t.get(e);let n=`$${t.size}_${e.replace(/^[^$_\p{IDS}]|[^$\u200C\u200D\p{IDC}]/gu,`_`)}`;return t.set(e,n),n}function Pb(e){let t=[`dotAll`,`ignoreCase`],n={enable:{},disable:{}};return e.forEach(({flags:e})=>{t.forEach(t=>{e.enable?.[t]&&(delete n.disable[t],n.enable[t]=!0),e.disable?.[t]&&(n.disable[t]=!0)})}),Object.keys(n.enable).length||delete n.enable,Object.keys(n.disable).length||delete n.disable,n.enable||n.disable?n:null}function Fb({dotAll:e,ignoreCase:t}){let n={};return(e||t)&&(n.enable={},e&&(n.enable.dotAll=!0),t&&(n.enable.ignoreCase=!0)),(!e||!t)&&(n.disable={},!e&&(n.disable.dotAll=!0),!t&&(n.disable.ignoreCase=!0)),n}function Ib(e){if(!e)throw Error(`Node expected`);let{body:t}=e;return Array.isArray(t)?t:t?[t]:null}function Lb(e){let t=e.find(e=>e.kind===`search_start`||Vb(e,{negate:!1})||!zb(e));if(!t)return null;if(t.kind===`search_start`)return t;if(t.type===`LookaroundAssertion`)return t.body[0].body[0];if(t.type===`CapturingGroup`||t.type===`Group`){let e=[];for(let n of t.body){let t=Lb(n.body);if(!t)return null;Array.isArray(t)?e.push(...t):e.push(t)}return e}return null}function Rb(e,t){let n=Ib(e)??[];for(let e of n)if(e===t||Rb(e,t))return!0;return!1}function zb({type:e}){return e===`Assertion`||e===`Directive`||e===`LookaroundAssertion`}function Bb(e){let t=[`Character`,`CharacterClass`,`CharacterSet`];return t.includes(e.type)||e.type===`Quantifier`&&e.min&&t.includes(e.body.type)}function Vb(e,t){let n={negate:null,...t};return e.type===`LookaroundAssertion`&&(n.negate===null||e.negate===n.negate)&&e.body.length===1&&Rv(e.body[0],{type:`Assertion`,kind:`search_start`})}function Hb(e){return/^[$_\p{IDS}][$\u200C\u200D\p{IDC}]*$/u.test(e)}function Ub(e,t){let n=Vv(e,{...t,unicodePropertyMap:mb}).body;return n.length>1||n[0].body.length>1?sy({body:n}):n[0].body[0]}function Wb(e,t){return e.negate=t,e}function Gb(e,t){return e.parent=t,e}function Kb(e,t){return Db(e),e.parent=t,e}function qb(e,t){let n=lb(t),r=ab(n.target,`ES2024`),i=ab(n.target,`ES2025`),a=n.rules.recursionLimit;if(!Number.isInteger(a)||a<2||a>20)throw Error(`Invalid recursionLimit; use 2-20`);let o=null,s=null;if(!i){let t=[e.flags.ignoreCase];Ty(e,Jb,{getCurrentModI:()=>t.at(-1),popModI(){t.pop()},pushModI(e){t.push(e)},setHasCasedChar(){t.at(-1)?o=!0:s=!0}})}let c={dotAll:e.flags.dotAll,ignoreCase:!(!e.flags.ignoreCase&&!o||s)},l=e,u={accuracy:n.accuracy,appliedGlobalFlags:c,captureMap:new Map,currentFlags:{dotAll:e.flags.dotAll,ignoreCase:e.flags.ignoreCase},inCharClass:!1,lastNode:l,originMap:e._originMap,recursionLimit:a,useAppliedIgnoreCase:!!(!i&&o&&s),useFlagMods:i,useFlagV:r,verbose:n.verbose};function d(e){return u.lastNode=l,l=e,ob(Yb[e.type],`Unexpected node type "${e.type}"`)(e,u,d)}let f={pattern:e.body.map(d).join(`|`),flags:d(e.flags),options:{...e.options}};return r||(delete f.options.force.v,f.options.disable.v=!0,f.options.unicodeSetsPlugin=null),f._captureTransfers=new Map,f._hiddenCaptures=[],u.captureMap.forEach((e,t)=>{e.hidden&&f._hiddenCaptures.push(t),e.transferTo&&ib(f._captureTransfers,e.transferTo,[]).push(t)}),f}var Jb={"*":{enter({node:e},t){if(sx(e)){let n=t.getCurrentModI();t.pushModI(e.flags?rb({ignoreCase:n},e.flags).ignoreCase:n)}},exit({node:e},t){sx(e)&&t.popModI()}},Backreference(e,t){t.setHasCasedChar()},Character({node:e},t){tx(eb(e.value))&&t.setHasCasedChar()},CharacterClassRange({node:e,skip:t},n){t(),nx(e,{firstOnly:!0}).length&&n.setHasCasedChar()},CharacterSet({node:e},t){e.kind===`property`&&Sb.has(e.value)&&t.setHasCasedChar()}},Yb={Alternative({body:e},t,n){return e.map(n).join(``)},Assertion({kind:e,negate:t}){if(e===`string_end`)return`$`;if(e===`string_start`)return`^`;if(e===`word_boundary`)return t?$`\B`:$`\b`;throw Error(`Unexpected assertion kind "${e}"`)},Backreference({ref:e},t){if(typeof e!=`number`)throw Error(`Unexpected named backref in transformed AST`);if(!t.useFlagMods&&t.accuracy===`strict`&&t.currentFlags.ignoreCase&&!t.captureMap.get(e).ignoreCase)throw Error(`Use of case-insensitive backref to case-sensitive group requires target ES2025 or non-strict accuracy`);return`\\`+e},CapturingGroup(e,t,n){let{body:r,name:i,number:a}=e,o={ignoreCase:t.currentFlags.ignoreCase},s=t.originMap.get(e);return s&&(o.hidden=!0,a>s.number&&(o.transferTo=s.number)),t.captureMap.set(a,o),`(${i?`?<${i}>`:``}${r.map(n).join(`|`)})`},Character({value:e},t){let n=eb(e),r=rx(e,{escDigit:t.lastNode.type===`Backreference`,inCharClass:t.inCharClass,useFlagV:t.useFlagV});if(r!==n)return r;if(t.useAppliedIgnoreCase&&t.currentFlags.ignoreCase&&tx(n)){let e=pb(n);return t.inCharClass?e.join(``):e.length>1?`[${e.join(``)}]`:e[0]}return n},CharacterClass(e,t,n){let{kind:r,negate:i,parent:a}=e,{body:o}=e;if(r===`intersection`&&!t.useFlagV)throw Error(`Use of character class intersection requires min target ES2024`);tb.bugFlagVLiteralHyphenIsRange&&t.useFlagV&&o.some(lx)&&(o=[ty(45),...o.filter(e=>!lx(e))]);let s=()=>`[${i?`^`:``}${o.map(n).join(r===`intersection`?`&&`:``)}]`;if(!t.inCharClass){if((!t.useFlagV||tb.bugNestedClassIgnoresNegation)&&!i){let t=o.filter(e=>e.type===`CharacterClass`&&e.kind===`union`&&e.negate);if(t.length){let r=sy(),i=r.body[0];return r.parent=a,i.parent=r,o=o.filter(e=>!t.includes(e)),e.body=o,o.length?(e.parent=i,i.body.push(e)):r.body.pop(),t.forEach(e=>{let t=Zv({body:[e]});e.parent=t,t.parent=r,r.body.push(t)}),n(r)}}t.inCharClass=!0;let r=s();return t.inCharClass=!1,r}let c=o[0];if(r===`union`&&!i&&c&&((!t.useFlagV||!t.verbose)&&a.kind===`union`&&!(tb.bugFlagVLiteralHyphenIsRange&&t.useFlagV)||!t.verbose&&a.kind===`intersection`&&o.length===1&&c.type!==`CharacterClassRange`))return o.map(n).join(``);if(!t.useFlagV&&a.type===`CharacterClass`)throw Error(`Uses nested character class in a way that requires min target ES2024`);return s()},CharacterClassRange(e,t){let n=e.min.value,r=e.max.value,i={escDigit:!1,inCharClass:!0,useFlagV:t.useFlagV},a=rx(n,i),o=rx(r,i),s=new Set;return t.useAppliedIgnoreCase&&t.currentFlags.ignoreCase&&ix(nx(e)).forEach(e=>{s.add(Array.isArray(e)?`${rx(e[0],i)}-${rx(e[1],i)}`:rx(e,i))}),`${a}-${o}${[...s].join(``)}`},CharacterSet({kind:e,negate:t,value:n,key:r},i){if(e===`dot`)return i.currentFlags.dotAll?i.appliedGlobalFlags.dotAll||i.useFlagMods?`.`:`[^]`:$`[^\n]`;if(e===`digit`)return t?$`\D`:$`\d`;if(e===`property`){if(i.useAppliedIgnoreCase&&i.currentFlags.ignoreCase&&Sb.has(n))throw Error(`Unicode property "${n}" can't be case-insensitive when other chars have specific case`);return`${t?$`\P`:$`\p`}{${r?`${r}=`:``}${n}}`}if(e===`word`)return t?$`\W`:$`\w`;throw Error(`Unexpected character set kind "${e}"`)},Flags(e,t){return(t.appliedGlobalFlags.ignoreCase?`i`:``)+(e.dotAll?`s`:``)+(e.sticky?`y`:``)},Group({atomic:e,body:t,flags:n,parent:r},i,a){let o=i.currentFlags;n&&(i.currentFlags=rb(o,n));let s=t.map(a).join(`|`),c=!i.verbose&&t.length===1&&r.type!==`Quantifier`&&!e&&(!i.useFlagMods||!n)?s:`(?${ax(e,n,i.useFlagMods)}${s})`;return i.currentFlags=o,c},LookaroundAssertion({body:e,kind:t,negate:n},r,i){return`(?${`${t===`lookahead`?``:`<`}${n?`!`:`=`}`}${e.map(i).join(`|`)})`},Quantifier(e,t,n){return n(e.body)+ox(e)},Subroutine({isRecursive:e,ref:t},n){if(!e)throw Error(`Unexpected non-recursive subroutine in transformed AST`);let r=n.recursionLimit;return t===0?`(?R=${r})`:$`\g<${t}&R=${r}>`}},Xb=new Set([`$`,`(`,`)`,`*`,`+`,`.`,`?`,`[`,`\\`,`]`,`^`,`{`,`|`,`}`]),Zb=new Set([`-`,`\\`,`]`,`^`,`[`]),Qb=new Set("()-/[\\]^{|}!#$%&*+,.:;<=>?@`~".split(``)),$b=new Map([[9,$`\t`],[10,$`\n`],[11,$`\v`],[12,$`\f`],[13,$`\r`],[8232,$`\u2028`],[8233,$`\u2029`],[65279,$`\uFEFF`]]),ex=/^\p{Cased}$/u;function tx(e){return ex.test(e)}function nx(e,t){let n=!!t?.firstOnly,r=e.min.value,i=e.max.value,a=[];if(r<65&&(i===65535||i>=131071)||r===65536&&i>=131071)return a;for(let e=r;e<=i;e++){let t=eb(e);if(!tx(t))continue;let o=pb(t).filter(e=>{let t=e.codePointAt(0);return t<r||t>i});if(o.length&&(a.push(...o),n))break}return a}function rx(e,{escDigit:t,inCharClass:n,useFlagV:r}){if($b.has(e))return $b.get(e);if(e<32||e>126&&e<160||e>262143||t&&cx(e))return e>255?`\\u{${e.toString(16).toUpperCase()}}`:`\\x${e.toString(16).toUpperCase().padStart(2,`0`)}`;let i=n?r?Qb:Zb:Xb,a=eb(e);return(i.has(a)?`\\`:``)+a}function ix(e){let t=e.map(e=>e.codePointAt(0)).sort((e,t)=>e-t),n=[],r=null;for(let e=0;e<t.length;e++)t[e+1]===t[e]+1?r??=t[e]:r===null?n.push(t[e]):(n.push([r,t[e]]),r=null);return n}function ax(e,t,n){if(e)return`>`;let r=``;if(t&&n){let{enable:e,disable:n}=t;r=(e?.ignoreCase?`i`:``)+(e?.dotAll?`s`:``)+(n?`-`:``)+(n?.ignoreCase?`i`:``)+(n?.dotAll?`s`:``)}return`${r}:`}function ox({kind:e,max:t,min:n}){let r;return r=!n&&t===1?`?`:!n&&t===1/0?`*`:n===1&&t===1/0?`+`:n===t?`{${n}}`:`{${n},${t===1/0?``:t}}`,r+{greedy:``,lazy:`?`,possessive:`+`}[e]}function sx({type:e}){return e===`CapturingGroup`||e===`Group`||e===`LookaroundAssertion`}function cx(e){return e>47&&e<58}function lx({type:e,value:t}){return e===`Character`&&t===45}var ux=class e extends RegExp{#e=new Map;#t=null;#n;#r=null;#i=null;rawOptions={};get source(){return this.#n||`(?:)`}constructor(t,n,r){let i=!!r?.lazyCompile;if(t instanceof RegExp){if(r)throw Error(`Cannot provide options when copying a regexp`);let i=t;super(i,n),this.#n=i.source,i instanceof e&&(this.#e=i.#e,this.#r=i.#r,this.#i=i.#i,this.rawOptions=i.rawOptions)}else{let e={hiddenCaptures:[],strategy:null,transfers:[],...r};super(i?``:t,n),this.#n=t,this.#e=fx(e.hiddenCaptures,e.transfers),this.#i=e.strategy,this.rawOptions=r??{}}i||(this.#t=this)}exec(t){if(!this.#t){let{lazyCompile:t,...n}=this.rawOptions;this.#t=new e(this.#n,this.flags,n)}let n=this.global||this.sticky,r=this.lastIndex;if(this.#i===`clip_search`&&n&&r){this.lastIndex=0;let e=this.#a(t.slice(r));return e&&(dx(e,r,t,this.hasIndices),this.lastIndex+=r),e}return this.#a(t)}#a(e){this.#t.lastIndex=this.lastIndex;let t=super.exec.call(this.#t,e);if(this.lastIndex=this.#t.lastIndex,!t||!this.#e.size)return t;let n=[...t];t.length=1;let r;this.hasIndices&&(r=[...t.indices],t.indices.length=1);let i=[0];for(let e=1;e<n.length;e++){let{hidden:a,transferTo:o}=this.#e.get(e)??{};if(a?i.push(null):(i.push(t.length),t.push(n[e]),this.hasIndices&&t.indices.push(r[e])),o&&n[e]!==void 0){let a=i[o];if(!a)throw Error(`Invalid capture transfer to "${a}"`);if(t[a]=n[e],this.hasIndices&&(t.indices[a]=r[e]),t.groups){this.#r||=px(this.source);let i=this.#r.get(o);i&&(t.groups[i]=n[e],this.hasIndices&&(t.indices.groups[i]=r[e]))}}}return t}};function dx(e,t,n,r){if(e.index+=t,e.input=n,r){let n=e.indices;for(let e=0;e<n.length;e++){let r=n[e];r&&(n[e]=[r[0]+t,r[1]+t])}let r=n.groups;r&&Object.keys(r).forEach(e=>{let n=r[e];n&&(r[e]=[n[0]+t,n[1]+t])})}}function fx(e,t){let n=new Map;for(let t of e)n.set(t,{hidden:!0});for(let[e,r]of t)for(let t of r)ib(n,t,{}).transferTo=e;return n}function px(e){let t=/(?<capture>\((?:\?<(?![=!])(?<name>[^>]+)>|(?!\?)))|\\?./gsu,n=new Map,r=0,i=0,a;for(;a=t.exec(e);){let{0:e,groups:{capture:t,name:o}}=a;e===`[`?r++:r?e===`]`&&r--:t&&(i++,o&&n.set(i,o))}return n}function mx(e,t){let n=hx(e,t);return n.options?new ux(n.pattern,n.flags,n.options):new RegExp(n.pattern,n.flags)}function hx(e,t){let n=lb(t),r=Cb(Vv(e,{flags:n.flags,normalizeUnknownPropertyNames:!0,rules:{captureGroup:n.rules.captureGroup,singleline:n.rules.singleline},skipBackrefValidation:n.rules.allowOrphanBackrefs,unicodePropertyMap:mb}),{accuracy:n.accuracy,asciiWordBoundaries:n.rules.asciiWordBoundaries,avoidSubclass:n.avoidSubclass,bestEffortTarget:n.target}),i=qb(r,n),a=Jy(i.pattern,{captureTransfers:i._captureTransfers,hiddenCaptures:i._hiddenCaptures,mode:`external`}),o=Ry(Vy(a.pattern).pattern,{captureTransfers:a.captureTransfers,hiddenCaptures:a.hiddenCaptures}),s={pattern:o.pattern,flags:`${n.hasIndices?`d`:``}${n.global?`g`:``}${i.flags}${i.options.disable.v?`u`:`v`}`};if(n.avoidSubclass){if(n.lazyCompileLength!==1/0)throw Error(`Lazy compilation requires subclass`)}else{let e=o.hiddenCaptures.sort((e,t)=>e-t),t=Array.from(o.captureTransfers),i=r._strategy,a=s.pattern.length>=n.lazyCompileLength;(e.length||t.length||i||a)&&(s.options={...e.length&&{hiddenCaptures:e},...t.length&&{transfers:t},...i&&{strategy:i},...a&&{lazyCompile:a}})}return s}function gx(e,t){return mx(e,{global:!0,hasIndices:!0,lazyCompileLength:3e3,rules:{allowOrphanBackrefs:!0,asciiWordBoundaries:!0,captureGroup:!0,recursionLimit:5,singleline:!0},...t})}function _x(e={}){let t={target:`auto`,cache:new Map,...e};return t.regexConstructor||=e=>gx(e,{target:t.target}),{createScanner(e){return new G_(e,t)},createString:q_}}var vx=t({highlightChunks:()=>kx,highlightLangChunks:()=>Ax,langForPath:()=>Ox}),yx={light:`github-light`,dark:`github-dark`},bx=400,xx={ts:`typescript`,mts:`typescript`,cts:`typescript`,js:`javascript`,mjs:`javascript`,cjs:`javascript`,jsx:`jsx`,tsx:`tsx`,json:`json`,jsonc:`jsonc`,json5:`json5`,map:`json`,md:`markdown`,mdx:`mdx`,markdown:`markdown`,css:`css`,pcss:`css`,postcss:`css`,sass:`sass`,scss:`scss`,less:`less`,styl:`stylus`,html:`html`,htm:`html`,vue:`vue`,svelte:`svelte`,astro:`astro`,py:`python`,pyi:`python`,rb:`ruby`,rake:`ruby`,rs:`rust`,go:`go`,java:`java`,kt:`kotlin`,kts:`kotlin`,c:`c`,h:`c`,cpp:`cpp`,cc:`cpp`,cxx:`cpp`,hpp:`cpp`,hh:`cpp`,cs:`csharp`,fs:`fsharp`,swift:`swift`,m:`objective-c`,php:`php`,scala:`scala`,groovy:`groovy`,dart:`dart`,sh:`shellscript`,bash:`shellscript`,zsh:`shellscript`,fish:`fish`,ps1:`powershell`,bat:`bat`,cmd:`bat`,yml:`yaml`,yaml:`yaml`,toml:`toml`,xml:`xml`,svg:`xml`,sql:`sql`,graphql:`graphql`,gql:`graphql`,prisma:`prisma`,lua:`lua`,pl:`perl`,pm:`perl`,r:`r`,jl:`julia`,ex:`elixir`,exs:`elixir`,erl:`erlang`,hs:`haskell`,clj:`clojure`,cljs:`clojure`,edn:`clojure`,vim:`vim`,zig:`zig`,nim:`nim`,sol:`solidity`,tf:`terraform`,tfvars:`terraform`,hcl:`hcl`,diff:`diff`,patch:`diff`,lock:`yaml`},Sx={dockerfile:`dockerfile`,makefile:`makefile`,".gitignore":`ini`,".gitattributes":`ini`,".editorconfig":`ini`,".npmrc":`ini`,".nvmrc":`ini`,".env":`ini`,justfile:`justfile`,"cmakelists.txt":`cmake`},Cx={astro:()=>Y(()=>import(`./astro-BZ97kZFP.js`),__vite__mapDeps([0,1,2,3,4,5,6])),bat:()=>Y(()=>import(`./bat-qdxAdBWQ.js`),[]),c:()=>Y(()=>import(`./c-Cz4nF6n_.js`),__vite__mapDeps([7,8])),clojure:()=>Y(()=>import(`./clojure-DqKBuwfJ.js`),[]),cmake:()=>Y(()=>import(`./cmake-Bj61d0ZC.js`),[]),cpp:()=>Y(()=>import(`./cpp-B6pWdJV2.js`),__vite__mapDeps([9,10,11,8])),csharp:()=>Y(()=>import(`./csharp-dmMxLVLW.js`),[]),css:()=>Y(()=>import(`./css-DgaLhXQH.js`),__vite__mapDeps([12,4])),dart:()=>Y(()=>import(`./dart-CHZY9Xhz.js`),[]),diff:()=>Y(()=>import(`./diff-woXpYk--.js`),[]),dockerfile:()=>Y(()=>import(`./dockerfile-IyjqRm3v.js`),[]),elixir:()=>Y(()=>import(`./elixir-raGDl1oO.js`),__vite__mapDeps([13,14,2,4])),erlang:()=>Y(()=>import(`./erlang-D0CaQ5Pl.js`),__vite__mapDeps([15,16])),fish:()=>Y(()=>import(`./fish-BJitypiv.js`),[]),fsharp:()=>Y(()=>import(`./fsharp-PZeu-6rm.js`),__vite__mapDeps([17,16])),graphql:()=>Y(()=>import(`./graphql-BZEhxNwM.js`),__vite__mapDeps([18,19,2,3,6,20])),groovy:()=>Y(()=>import(`./groovy-CacY0gHj.js`),[]),hcl:()=>Y(()=>import(`./hcl-Dh228itO.js`),[]),haskell:()=>Y(()=>import(`./haskell-D8IpX4py.js`),[]),html:()=>Y(()=>import(`./html-BCy9P6D2.js`),__vite__mapDeps([21,14,2,4])),ini:()=>Y(()=>import(`./ini-B5eOa1yu.js`),[]),java:()=>Y(()=>import(`./java-_ATy9zCa.js`),__vite__mapDeps([22,23])),javascript:()=>Y(()=>import(`./javascript-CpIGwZ_Y.js`),__vite__mapDeps([24,2])),json:()=>Y(()=>import(`./json-C3WlssX3.js`),__vite__mapDeps([25,1])),json5:()=>Y(()=>import(`./json5-BR5RXkoi.js`),[]),jsonc:()=>Y(()=>import(`./jsonc-CYpm1nAK.js`),[]),jsx:()=>Y(()=>import(`./jsx-C4yDKi0A.js`),__vite__mapDeps([26,20])),julia:()=>Y(()=>import(`./julia-DCfl8sf8.js`),__vite__mapDeps([27,2,10,11,8,28,29,30])),justfile:()=>Y(()=>import(`./justfile-CKP9W7x6.js`),__vite__mapDeps([31,2,3,28,32,33,4,14,30,34,23,35,8,10,11,19,6,20,36,37])),kotlin:()=>Y(()=>import(`./kotlin-DhhofPvG.js`),[]),less:()=>Y(()=>import(`./less-DVTAwKKz.js`),[]),lua:()=>Y(()=>import(`./lua-fPRBWD-V.js`),__vite__mapDeps([38,36,8])),makefile:()=>Y(()=>import(`./makefile-Dixweg8N.js`),[]),markdown:()=>Y(()=>import(`./markdown-CjQmuOi1.js`),__vite__mapDeps([39,16])),mdx:()=>Y(()=>import(`./mdx-DQZ5AkYe.js`),[]),nim:()=>Y(()=>import(`./nim-VAaFSKwL.js`),__vite__mapDeps([40,2,4,8,11,14,16,34,23])),"objective-c":()=>Y(()=>import(`./objective-c-D1A_Heim.js`),[]),perl:()=>Y(()=>import(`./perl-BTdIRyOQ.js`),__vite__mapDeps([41,33,2,4,14,30,34,23])),php:()=>Y(()=>import(`./php-DPoYWQt_.js`),__vite__mapDeps([42,1,2,4,14,30,34,23])),postcss:()=>Y(()=>import(`./postcss-DkKB82OS.js`),__vite__mapDeps([43,5])),powershell:()=>Y(()=>import(`./powershell-QtSnmXcu.js`),[]),prisma:()=>Y(()=>import(`./prisma-DMgNhnYS.js`),[]),python:()=>Y(()=>import(`./python-C5TF47hQ.js`),__vite__mapDeps([44,28])),r:()=>Y(()=>import(`./r-BXEss897.js`),__vite__mapDeps([45,29])),ruby:()=>Y(()=>import(`./ruby-BdDtUACQ.js`),__vite__mapDeps([46,35,2,4,8,10,11,14,19,3,6,20,30,32,34,23,36,37])),rust:()=>Y(()=>import(`./rust-DpiIf5JO.js`),[]),sass:()=>Y(()=>import(`./sass-DXrisJhu.js`),[]),scala:()=>Y(()=>import(`./scala-BiFt_7mu.js`),[]),scss:()=>Y(()=>import(`./scss-8bKmll0B.js`),__vite__mapDeps([47,4])),shellscript:()=>Y(()=>import(`./shellscript-CVTB3cr6.js`),__vite__mapDeps([48,32])),solidity:()=>Y(()=>import(`./solidity-Bj7E1mRn.js`),[]),sql:()=>Y(()=>import(`./sql-CfM2IJm3.js`),__vite__mapDeps([49,30])),svelte:()=>Y(()=>import(`./svelte-CdeT-Ich.js`),__vite__mapDeps([50,2,3,4,5])),swift:()=>Y(()=>import(`./swift-CyEgAFGc.js`),[]),terraform:()=>Y(()=>import(`./terraform-DswuEJGm.js`),[]),toml:()=>Y(()=>import(`./toml-CcmNWLt0.js`),[]),tsx:()=>Y(()=>import(`./tsx-CGosfAUg.js`),__vite__mapDeps([51,6])),typescript:()=>Y(()=>import(`./typescript-Bb1J8qyy.js`),__vite__mapDeps([52,3])),vim:()=>Y(()=>import(`./viml-DvXPmvsu.js`),[]),vue:()=>Y(()=>import(`./vue-BqdMUtqy.js`),__vite__mapDeps([53,1,2,3,4,14])),xml:()=>Y(()=>import(`./xml-DuKfbPI6.js`),__vite__mapDeps([54,34,23])),yaml:()=>Y(()=>import(`./yaml-DDA_XMNu.js`),__vite__mapDeps([55,37])),stylus:()=>Y(()=>import(`./stylus-B6D30XZt.js`),[]),zig:()=>Y(()=>import(`./zig-CMLA9XwU.js`),[])},wx=null;function Tx(){return wx??=V_({themes:[Y(()=>import(`./github-light-EUqPIrTm.js`),[]),Y(()=>import(`./github-dark-C-LZuMrd.js`),[])],langs:[],engine:_x({forgiving:!0})}),wx}var Ex=new Map;function Dx(e,t){let n=Ex.get(t);if(!n){let r=Cx[t];n=r?r().then(t=>e.loadLanguage(t)).then(()=>void 0):Promise.reject(Error(`no grammar loader for ${t}`)),n.catch(()=>Ex.delete(t)),Ex.set(t,n)}return n}function Ox(e){let t=(e.split(`/`).pop()??e).toLowerCase();return Sx[t]?Sx[t]:xx[t.includes(`.`)?t.slice(t.lastIndexOf(`.`)+1):``]??null}async function*kx(e,t){let n=Ox(e);n&&t.trim()&&Cx[n]&&(yield*Ax(n,t))}async function*Ax(e,t){if(!e||!t.trim()||!Cx[e])return;let n=await Tx();await Dx(n,e);let r=t.split(`
176
+ `),i;for(let t=0;t<r.length;t+=bx){let a=r.slice(t,t+bx).join(`
177
+ `),o=n.codeToHast(a,{lang:e,themes:yx,defaultColor:!1,...i?{grammarState:i}:{}});i=n.getLastGrammarState(o)??void 0,yield z_(o)}}var jx=/(?:^|\s)language-([\w+#.-]+)/,Mx=`hl`;function Nx(e){if(e)for(let t of e.querySelectorAll(`pre`)){if(t.dataset[Mx])continue;let e=t.querySelector(`code`);if(!e){t.dataset[Mx]=`skip`;continue}let n=jx.exec(e.className)?.[1],r=n?Ox(`x.${n}`)??n:void 0,i=e.textContent??``;if(!r||!i.trim()){t.dataset[Mx]=`skip`;continue}let a=`${r}::${i.length}::${i}`;t.dataset[Mx]=`pending`;let o=Fd(a);o===void 0?(async()=>{try{let{highlightLangChunks:e}=await Y(async()=>{let{highlightLangChunks:e}=await Promise.resolve().then(()=>vx);return{highlightLangChunks:e}},void 0),n=``;for await(let t of e(r,i))n+=t;if(!n){t.dataset[Mx]=`skip`;return}Id(a,n),t.isConnected&&Px(t,n)}catch{t.dataset[Mx]=`skip`}})():Px(t,o)}}function Px(e,t){let n=document.createElement(`div`);n.className=`shikiwrap`;let r=document.createElement(`div`);r.className=`shiki`,r.innerHTML=t,n.appendChild(r),e.replaceWith(n)}function Fx(e){let t=String(e??``).trim();if(!t)return null;if(t.startsWith(`[`)){let e=(()=>{try{return JSON.parse(t)}catch{try{return JSON.parse(t.replace(/'/g,`"`))}catch{return}}})();if(Array.isArray(e)&&e.length>=2)return`${String(e[0])}/${String(e[1])}`}for(let e of[`__`,`/`,`::`]){let n=t.lastIndexOf(e);if(!(n<=0))return`${t.slice(0,n).replace(/^mcp__/,``)}/${t.slice(n+e.length)}`}return t}var Ix={prompt:{name:`you`,icon:`🟧`,color:`#faa81a`},user:{name:`you`,icon:`🟧`,color:`#faa81a`},message:{name:`agent`,icon:`🫖`,color:`#5865f2`},progress:{name:`progress`,icon:`📈`,color:`#3ba55d`},question:{name:`agent`,icon:`❓️`,color:`#5865f2`}},Lx={name:`harness`,icon:`📣`,color:`#3ba55d`},Rx={"#faa81a":`you`,"#5865f2":`agent`,"#3ba55d":`progress`,"#3ba0c9":`tool`},zx=e=>Rx[e]??`agent`,Bx=e=>{if(e.data?.actor)return{name:`@${String(e.data.actor)}`,icon:`🧩`,color:`#3ba0c9`};if(e.type===`tool_call`||e.type===`tool_result`){let t=String(e.data?.name??`tool`);if(t===`run_tool`){let t=Fx(e.data?.args?.tool_id);if(t)return{name:t,icon:`⚙️`,color:`#3ba0c9`}}let n=/^mcp__([^_]+(?:_[^_]+)*)__(.+)$/.exec(t);return n?{name:`${n[1]}/${n[2]}`,icon:`⚙️`,color:`#3ba0c9`}:{name:t,icon:`⚙️`,color:`#3ba0c9`}}if(e.type===`prompt`){let t=String(e.data?.source??`user`);return t===`user`?Ix.prompt:t.startsWith(`scheduler:`)?{name:t.slice(10),icon:`📣`,color:`#3ba55d`}:Lx}return Ix[e.type]??{name:e.type,icon:`•`,color:`#9298a5`}},Vx=e=>{let t=new Date(e);return`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}`};function Hx(e){let t=e.data??{};return e.type===`prompt`?String(t.text??``):e.type===`message`?`${typeof t.reasoning==`string`&&t.reasoning.trim()?`<reasoning>\n${t.reasoning}\n</reasoning>\n\n`:``}${String(t.content??``)}`:(e.type,``)}function Ux(e){return e>=1e9?`${+(e/1e9).toFixed(1)}b`:e>=1e6?`${+(e/1e6).toFixed(1)}m`:e>=1e4?`${Math.round(e/1e3)}k`:e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e)}function Wx(e,t){return ft(e.replace(/\s+/g,` `).trim(),t)}function Gx(e){return e.type===`prompt`&&e.data?.source===`user`?`you`:e.type===`message`?`agent`:`harness`}function Kx(e){let t=e.data??{};if(e.data?.actor)return`sub:${String(e.data.actor)}`;if(e.type===`tool_call`||e.type===`tool_result`){let e=typeof t.name==`string`?t.name:``;return e===`load_skill`?`agent-skill`:`tool:${e}`}return e.type===`prompt`?`src:${String(t.source??`user`)}`:`type:${e.type}`}function qx(e,t){return!(!e||t.data?.pending||e.data?.pending||t.data?.cancelled||Kx(e)!==Kx(t)||Gx(e)!==Gx(t)||t.session!==e.session||t.branch!==e.branch)}function Jx(e,t){let n=String(t??``);return/^TIMEOUT after\b/.test(n)?`timeout`:/^ABORTED\b/.test(n)?`aborted`:/^exit=\d+/.test(n)||e===!1?`exit`:n.trim()?`ok`:`empty`}function Yx(e){switch(e){case`timeout`:return` · TIMED OUT`;case`aborted`:return` · ABORTED`;case`exit`:return` · FAILED`;default:return``}}function Xx(e){let t=[];e.outcome!==`empty`&&t.push(e.fmtDur(e.durationMs)),e.timeoutMs&&t.push(`timeout ${Math.round(e.timeoutMs/1e3)}s`);let n=Yx(e.outcome).replace(/^\s*·\s*/,``);return n&&t.push(n),t.join(` · `)}function Zx(e){let t=e.trim();if(!t)return;let n=t[0];if(n===`{`||n===`[`||n===`"`)try{let e=JSON.parse(t);return typeof e==`object`&&e?`json`:void 0}catch{return}}function Qx(e){if(Zx(e)!==`json`)return e;try{let t=JSON.parse(e.trim()),n=JSON.stringify(t,null,1);return e.trim().split(`
178
+ `).length>1?e:n}catch{return e}}var $x=12e4,eS=6e5,tS=e=>{let t=Number(e);return Math.min(Number.isFinite(t)&&t>0?t:$x,eS)},nS=F(`<div class=qfree><input type=text><button>reply`),rS=F(`<div class=meta>`),iS=F(`<div class=meta>waiting for output…`),aS=F(`<div class="meta bgjob-note">runs in background — poll with <b>bash_output(job_id=&quot;<!>&quot;)`),oS=F(`<b>action="kill"`),sS=F(`<div class=meta>writing…`),cS=F(`<pre class="mono toolbody del">`),lS=F(`<pre class="mono toolbody add">`),uS=F(`<div class=meta> · `),dS=F(`<div class=meta>applying…`),fS=F(`<pre class="mono toolbody patch">`),pS=F(`<div>`),mS=F(`<div class=meta>validating…`),hS=F(`<a target=_blank rel="noopener noreferrer"referrerpolicy=no-referrer>open ↗`),gS=F(`<span class=muted>`),_S=F(`<div class=content>`),vS=F(`<div class=meta>loading…`),yS=F(`<div class=meta>bundled: `),bS=F(`<div class=meta>saving…`),xS=F(`<div class=meta>found: `),SS=F(`<div class=meta>no matches`),CS=F(`<span class=actor>@`),wS=F(`<details><summary><b></b><span class=meta></span><span class=toolcopy>`),TS=F(`<div class=divider-msg>⑂ forked from <!> → `),ES=F(`<div><div class=goalline-label>`),DS=F(`<div class="embed auditstep"><span class=meta>`),OS=F(`<span class="meta muted">`),kS=F(`<pre class="mono toolbody">`),AS=F(`<details class="embed auditstep"><summary><span class=meta>`),jS=F(`<div class=divider-msg>✅ tasks updated (<!>)`),MS=F(`<div> → `),NS=F(`<div class="embed fail"><div class=mono>🛑 runaway: <!> tool failures in a row (limit <!>)</div><div class=meta>last: <!> — `),PS=F(`<div class="embed warn-embed"title="a round-fatal API error occurred; auto-retry is waiting, then a fresh round starts (onError: retry)"><div class=mono>↻ API error — retrying (attempt <!>) in <!>s…`),FS=F(`<div class=divider-msg>🗜 compacted: <!> → <!> tok (<!>)`),IS=F(`<div class=divider-msg title="compaction is rewriting older history — the agent is not stuck">🗜 compacting: summarizing <!> earlier messages from <!> tok (<!>)…`),LS=F(`<span class=ts>`),RS=F(`<button class=editbtn title="withdraw this message — it has not reached the model yet; the text goes back to the input box">✕ cancel`),zS=F(`<button class=editbtn title="edit this prompt — forks the conversation here (later events are dropped or summarized)">✎ edit`),BS=F(`<div class=msg-head><span></span><span class=ts>`),VS=F(`<div><div></div><div class=msg-body>`),HS=F(`<span class=grouptime>`),US=F(`<div class=promptimgs>`),WS=F(`<img class=promptimg alt="tool image"loading=lazy title="click to enlarge">`,!0,!1,!1),GS=F(`<img class=promptimg alt=attachment title="click to enlarge">`),KS=F(`<details class=reasoning><summary>💭 thinking</summary><div class=mono>`),qS=F(`<div class=interrupted>⚠ interrupted — partial output kept`),JS=F(`<div class=msgfoot><span>copy summary`),YS=F(`<div class=meta>its call is no longer in the loaded events — the run itself finished`),XS=F(`<details><summary><span class=meta></span></summary><div class=mono></div><div class=meta>`),ZS=F(`<div class="content muted">Rejected: `),QS=F(`<details class="embed decision"><summary><b>📌 <span class="content inline-md"></span></b><span class=meta>decision logged`),$S=F(`<div class="meta answerdone">✓ answered — continuing below`),eC=F(`<div class=qopts>`),tC=F(`<div><div>❓️ <div class="content inline-md">`),nC=F(`<button class=qopt>`),rC=F(`<div class=progrow><b>goal</b><span>`),iC=F(`<div class=progrow><b>recent</b><span class="content inline-md">`),aC=F(`<div class="progrow warn"><b>⚠ problems</b><span class="content inline-md">`),oC=F(`<div class=progrow><b>next</b><span class="content inline-md">`),sC=F(`<div class="embed progembed"><div>📈 <div class="content inline-md">`),cC=F(`<div class="embed fail"><div class=mono>⚠ `),lC=F(`<div class="muted compactnote">the summary pass produced nothing, so the oldest messages were dropped instead — the session continues with the recent tail intact`),uC=F(`<div class="embed compaction"><b>🗜 context compacted</b><span class=meta> · <!> → <!> tok · `),dC=F(`<div class="vtitle compactkept">what the agent kept`),fC=F(`<details class="embed compaction"><summary><b>🗜 context compacted</b><span class=meta> · <!> → <!> tok · `),pC=F(`<div class="content muted">`);function mC(e){let[t,n]=y(``),r=()=>{let r=t().trim();r&&!e.answered&&(n(``),e.onOption?.(r))};return(()=>{var i=nS(),a=i.firstChild,o=a.nextSibling;return a.$$keydown=e=>{e.key===`Enter`&&!e.isComposing&&(e.preventDefault(),r())},a.$$input=e=>n(e.currentTarget.value),o.$$click=r,b(n=>{var r=e.answered?`answered`:`or type your own answer…`,i=e.answered,s=e.answered||!t().trim();return r!==n.e&&I(a,`placeholder`,n.e=r),i!==n.t&&(a.disabled=n.t=i),s!==n.a&&(o.disabled=n.a=s),n},{e:void 0,t:void 0,a:void 0}),b(()=>a.value=t()),i})()}function hC(e){let t=e.e,n=qx(e.prev,t),r=S(()=>e.res?.(),void 0,{equals:(e,t)=>e?.id===t?.id}),i=()=>r(),a=()=>!e.agentActive&&!i(),o=t.data??{},s=String(o.name??`tool`),c=()=>String(i()?.data?.result??``),l=e=>String(o.args?.[e]??``),u=()=>s===`bash`?l(`command`):l(`path`)||JSON.stringify(o.args??{},null,1),d=()=>s===`bash`?tS(l(`timeout_ms`)):s===`wait_children`?Number(l(`timeout_ms`))||3e5:Number(l(`timeout_ms`))||void 0,f=(e,t,n)=>j(Qd,{text:e,lang:n}),p=e=>j(Qd,{get text(){return JSON.stringify(e??o.args??{},null,1)},lang:`json`}),m=()=>(()=>{let t=i();return t?[P(()=>P(()=>!!Md(c()))()?j(Zd,{get text(){return c()}}):j(Qd,{get text(){return Qx(c())},get lang(){return Zx(c())}})),(()=>{var e=rS();return R(e,()=>dt(t.data?.durationMs),null),R(e,()=>s===`bash`?Yx(Jx(t.data?.ok,String(t.data?.result??``))):t.data?.ok===!1?` · FAILED`:``,null),R(e,j(Cd,{get text(){return P(()=>!!Md(c()))()?jd(c()):Qx(c())}}),null),e})(),j(vC,{get data(){return t.data},get agentId(){return e.agentId}})]:iS()})(),h=S(()=>{i();let e=s,t=``,n=p(),r=(r,a,o)=>{let s=o??{},c=Object.keys(s);e=c.length?Wx(JSON.stringify(s),120):`(no arguments)`,t=i()?dt(i().data?.durationMs):null,n=[P(()=>P(()=>!!c.length)()?p(s):null),P(m)]};try{switch(s){case`bash`:{let r=l(`command`),a=o.args?.background===!0,s=a?String(c()).match(/job (bg\d+)/)?.[1]??``:``;e=(a?`⏳ `:`$ `)+Wx(r,96);let u=l(`timeout_ms`)?Number(l(`timeout_ms`)):void 0,d=i(),f=Jx(d?.data?.ok,d?String(d.data?.result??``):``);t=d?a?`background job${s?` ${s}`:``}${u?` · timeout ${Math.round(u/1e3)}s`:``}`:Xx({outcome:f,durationMs:d.data?.durationMs,timeoutMs:u,fmtDur:dt}):null,n=[a?(()=>{var e=aS(),t=e.firstChild.nextSibling,n=t.firstChild.nextSibling;return n.nextSibling,R(t,s||`?`,n),R(e,s?[` · kill with `,oS()]:null,null),e})():null,j(Qd,{text:r,lang:`shellscript`}),P(m)];break}case`read_file`:{let r=Array.isArray(o.args?.paths)?o.args.paths.map(String):[];e=l(`path`)||(r.length?r.length===1?r[0]:`${r[0]} +${r.length-1} more`:`(no path)`);let i=[];l(`pattern`)&&i.push(`grep /${Wx(l(`pattern`),40)}/`),Number(o.args?.offset)<0?i.push(`last ${-Number(o.args.offset)} lines`):o.args?.offset&&i.push(`from L${o.args.offset}`),o.args?.limit&&i.push(`≤${o.args.limit} lines`),t=i.join(` · `),n=m();break}case`write_file`:{let r=String(o.args?.content??``),a=l(`path`);e=a||`(no path)`,t=`${Ux(r.length)} bytes`,n=[P(()=>f(r,void 0,Ox(a)??void 0)),P(()=>P(()=>!!i())()?(()=>{var e=rS();return R(e,()=>Wx(c(),160)),e})():sS())];break}case`edit_file`:e=l(`path`)||`(no path)`,t=o.args?.replace_all===!0?`replace all`:`unique spot`,n=[(()=>{var e=cS();return R(e,()=>`- `+l(`old_text`)),e})(),(()=>{var e=lS();return R(e,()=>`+ `+l(`new_text`)),e})(),P(()=>P(()=>!!i())()?(()=>{var e=uS(),t=e.firstChild;return R(e,()=>Wx(c(),120),t),R(e,()=>dt(i().data?.durationMs),null),e})():dS())];break;case`apply_patch`:{let t=l(`patch`).split(`
179
+ `).filter(e=>e&&!/^---$/.test(e.trim())),r=t.map(e=>e.match(/^\*\*\* (?:Add|Update|Delete) File: (.+)$/)?.[1]).filter(Boolean);e=r.length?`${r.length} file${r.length>1?`s`:``}: ${Wx(r.join(`, `),80)}`:`patch`,n=[(()=>{var e=fS();return R(e,()=>t.map(e=>{let t=e.startsWith(`+`)?` add`:e.startsWith(`-`)?` del`:/^\*\*\*|^@@/.test(e)?` meta`:``;return(()=>{var n=pS();return L(n,`pline`+t),R(n,e),n})()})),e})(),P(()=>P(()=>!!i())()?(()=>{var e=rS();return R(e,()=>Wx(c().split(`
180
+ `)[0]??``,140),null),R(e,()=>i().data?.ok===!1?` · FAILED`:``,null),e})():mS())];break}case`list_dir`:e=l(`path`)||`.`,n=m();break;case`read_url`:{let r=l(`url`);try{let e=new URL(r);r=e.host+e.pathname}catch{}e=Wx(r,70),t=`web`,n=[(()=>{var e=rS();return R(e,j(N,{get when(){return/^https?:/i.test(l(`url`))},get fallback(){return(()=>{var e=gS();return R(e,()=>Wx(l(`url`),80)),e})()},get children(){var e=hS();return b(()=>I(e,`href`,l(`url`))),e}})),e})(),P(m)];break}case`bash_output`:{let r=l(`action`)||`read`;e=`bash_output ${l(`job_id`)||`(?)`}`,t=r,n=m();break}case`load_skill`:{e=`skill: ${l(`name`)}`;let t=c().replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/,``);n=i()?[(()=>{var e=_S();return b(()=>e.innerHTML=Re(t)),e})(),(()=>{var e=rS();return R(e,()=>dt(i().data?.durationMs)),e})()]:vS();break}case`save_skill`:{e=`skill: ${l(`name`)}`,t=Wx(l(`description`),60);let r=Array.isArray(o.args?.files)?o.args.files.map(e=>e?.name).filter(Boolean):[];n=[P(()=>P(()=>!!r.length)()?(()=>{var e=yS();return e.firstChild,R(e,()=>r.join(`, `),null),e})():null),P(()=>P(()=>!!i())()?(()=>{var e=uS(),t=e.firstChild;return R(e,()=>Wx(c(),160),t),R(e,()=>dt(i().data?.durationMs),null),e})():bS())];break}case`search_tools`:{e=`🔎 ${Wx(l(`query`)||`(browse)`,60)}`;let r=(()=>{try{let e=JSON.parse(c());return{names:(e.tools??[]).map(e=>`${e.server??`?`}/${e.name??`?`}`),total:e.totalMatches??0}}catch{return{names:[],total:0}}})();t=i()?`${r.total} match${r.total===1?``:`es`}`:null,n=[P(p),P(()=>P(()=>!!i())()?P(()=>!!r.names.length)()?(()=>{var e=xS();return e.firstChild,R(e,()=>r.names.join(`, `),null),e})():SS():null),P(m)];break}case`run_tool`:{let a=Fx(l(`tool_id`)),s=a?.indexOf(`/`)??-1;a&&s>0?r(a.slice(0,s),a.slice(s+1),o.args?.arguments):(e=a||`(no tool_id)`,t=i()?dt(i().data?.durationMs):null,n=[P(p),P(m)]);break}default:{let a=/^mcp__([^_]+(?:_[^_]+)*)__(.+)$/.exec(s);if(a){r(a[1],a[2],o.args);break}e=s,t=i()?dt(i().data?.durationMs):null,n=[P(p),P(m)];break}}}catch{}return{label:e,hint:t,body:n,key:`${i()?.id??`none`}|${e}|${t??``}`}},void 0,{equals:(e,t)=>e.key===t.key});return(()=>{var r=wS(),o=r.firstChild,l=o.firstChild,f=l.nextSibling,p=f.nextSibling;return r.addEventListener(`toggle`,t=>{t.target.open&&e.onResize?.()}),R(l,()=>h().label),R(o,j(N,{get when(){return t.data?.actor},get children(){var e=CS();return e.firstChild,R(e,()=>String(t.data.actor),null),e}}),f),R(f,(()=>{var e=P(()=>!!i());return()=>e()?h().hint||``:P(()=>!!a())()?`(result missed)`:P(()=>!!(s===`bash`||d()))()?j(Yd,{get startedAt(){return t.ts},inline:!0,get timeoutMs(){return d()}}):`running…`})()),R(p,j(Cd,{get text(){return u()},label:`⧉ cmd`,title:`copy the ${s} arguments`}),null),R(p,j(N,{get when(){return i()},get children(){return j(Cd,{get text(){return P(()=>!!Md(c()))()?jd(c()):c()},label:`⧉ out`,title:`copy this tool's full output (escapes removed)`})}}),null),R(r,()=>h().body,null),b(e=>{var t=`embed`+(n?` grouped`:``)+(i()?i().data?.ok===!1?` fail`:` done`:a()?` done`:` running`),o=`${s}${h().hint?` — `+h().hint:``}`;return t!==e.e&&L(r,e.e=t),o!==e.t&&I(r,`title`,e.t=o),e},{e:void 0,t:void 0}),r})()}function gC(e){let t;return x(()=>{e.html,queueMicrotask(()=>Nx(t))}),(()=>{var n=_S(),r=t;return typeof r==`function`?Ae(r,n):t=n,b(()=>n.innerHTML=e.html),n})()}function _C(e){let t=e.e,n=Bx(t),r=()=>qx(e.prev?.(),t),i=()=>{let n=e.next?.();return!!n&&qx(t,n)};if(t.type===`fork`){let e=t.data??{};return(()=>{var n=TS(),r=n.firstChild.nextSibling;return r.nextSibling,R(n,()=>String(e.fromBranch??`?`),r),R(n,()=>String(e.newBranch??t.branch),null),n})()}if(t.type===`goal`){let e=Qt(t.data??{});return(()=>{var t=ES(),n=t.firstChild;return R(n,()=>e.label),R(t,j(N,{get when(){return e.hasCard},get children(){return j(rn,{get tone(){return P(()=>e.tone===`ok`)()?`ok`:e.tone===`warn`?`warn`:`tool`},get markdown(){return e.markdown},get body(){return e.detail}})}}),null),b(()=>L(t,`goalline `+(e.tone===`err`?`err`:e.tone===`warn`?`warn`:``))),t})()}if(t.type===`audit_step`){let e=String(t.data?.step??``),n=String(t.data?.name??``),r=e===`started`?`🔍️ auditor started`:e===`tool`?`🔍️ auditor → ${n}`:e===`tool_done`?`🔍️ auditor ← ${n} ${t.data?.ok===!1?`failed`:`${String(t.data?.chars??0)} chars`}`:e===`reply`?`🔍️ auditor replied`:`🔍️ auditor`;return e===`reply`&&t.data?.text||e===`tool`&&t.data?.args?(()=>{var n=AS(),i=n.firstChild,a=i.firstChild;return R(a,r),R(i,j(N,{get when(){return e===`tool`&&t.data?.args},get children(){var e=OS();return R(e,()=>ft(String(t.data?.args??``),120)),e}}),null),R(n,j(N,{get when(){return e===`reply`&&t.data?.text},get children(){var e=kS();return R(e,()=>String(t.data?.text??``)),e}}),null),R(n,j(N,{get when(){return e===`tool`&&t.data?.args},get children(){var e=kS();return R(e,()=>String(t.data?.args??``)),e}}),null),n})():(()=>{var e=DS(),t=e.firstChild;return R(t,r),e})()}if(t.type===`todo`){let e=String(t.data?.by??`operator`);return(()=>{var t=jS(),n=t.firstChild.nextSibling;return n.nextSibling,R(t,e===`human`?`operator`:e,n),t})()}if(t.type===`state`)return t.data.from===t.data.to?null:(()=>{var e=MS(),n=e.firstChild;return R(e,()=>t.data.from,n),R(e,()=>t.data.to,null),R(e,(()=>{var e=P(()=>!!t.data.reason);return()=>e()?` — ${t.data.reason}`:``})(),null),b(()=>L(e,`divider-msg`+(t.data.to===`error`?` err`:``))),e})();if(t.type===`system_note`){let e=String(t.data?.event??``);if(e===`runaway-detected`)return(()=>{var e=NS(),n=e.firstChild,r=n.firstChild.nextSibling,i=r.nextSibling.nextSibling;i.nextSibling;var a=n.nextSibling,o=a.firstChild.nextSibling;return o.nextSibling,R(n,()=>String(t.data?.failures),r),R(n,()=>String(t.data?.limit),i),R(a,()=>String(t.data?.lastTool),o),R(a,()=>String(t.data?.lastError??``).slice(0,200),null),b(()=>I(e,`title`,`${t.data?.failures} consecutive tool failures hit the configured limit (${t.data?.limit})`)),e})();if(e===`error-retry`)return(()=>{var e=PS(),n=e.firstChild,r=n.firstChild.nextSibling,i=r.nextSibling.nextSibling;return i.nextSibling,R(n,()=>String(t.data?.attempt),r),R(n,()=>Math.round(Number(t.data?.waitMs)/1e3),i),e})();if(e===`background-exit`){let e=t.data?.failed===!0,n=Math.round(Number(t.data?.durationMs??0)/1e3);return(()=>{var r=pS();return L(r,`divider-msg`+(e?` err`:``)),R(r,()=>(e?`⚠ background job `:`✓ background job `)+String(t.data?.jobId??`?`)+` `+(e?`FAILED (exit ${String(t.data?.code??`?`)})`:`finished (${n}s)`)),b(()=>I(r,`title`,String(t.data?.cmd??``))),r})()}return e===`context-compacted`?(()=>{var e=FS(),n=e.firstChild.nextSibling,r=n.nextSibling.nextSibling,i=r.nextSibling.nextSibling;return i.nextSibling,R(e,()=>String(t.data?.tokensBefore??`?`),n),R(e,()=>String(t.data?.tokensAfter??`?`),r),R(e,()=>String(t.data?.mode??``),i),e})():e===`context-compaction-started`?(()=>{var e=IS(),n=e.firstChild.nextSibling,r=n.nextSibling.nextSibling,i=r.nextSibling.nextSibling;return i.nextSibling,R(e,()=>String(t.data?.messages??`?`),n),R(e,()=>String(t.data?.tokensBefore??`?`),r),R(e,()=>String(t.data?.reason??`auto`),i),e})():null}return(()=>{var a=VS(),o=a.firstChild,s=o.nextSibling;return R(o,(()=>{var e=P(()=>!!r());return()=>e()?``:n.icon})()),R(s,(()=>{var e=P(()=>!!r());return()=>e()&&(()=>{var e=HS();return b(()=>I(e,`title`,`${Vx(t.ts)} · ${t.branch}`)),e})()})(),null),R(s,j(N,{get when(){return!r()},get children(){var r=BS(),i=r.firstChild,a=i.nextSibling;return R(i,()=>n.name),R(r,j(N,{get when(){return t.data?.actor},get children(){var e=CS();return e.firstChild,R(e,()=>String(t.data.actor),null),e}}),a),R(a,(()=>{var e=P(()=>!(!t.data?.pending||t.data?.queued===!1||t.data?.sent));return()=>e()?`queued…`:P(()=>!!t.data?.cancelled)()?`withdrawn`:Vx(t.ts)})()),R(r,j(N,{get when(){return e.showBranch},get children(){var e=LS();return R(e,()=>t.branch),e}}),null),R(r,j(N,{get when(){return e.onCancel},get children(){var t=RS();return t.$$click=t=>{t.stopPropagation(),e.onCancel()},t}}),null),R(r,j(N,{get when(){return t.type!==`tool_call`},get children(){return j(Cd,{get text(){return Hx(t)},label:`⧉ copy`,title:`copy the RAW text of this message (no markdown rendering)`})}}),null),R(r,j(N,{get when(){return e.onEdit},get children(){var t=zS();return t.$$click=t=>{t.stopPropagation(),e.onEdit()},t}}),null),b(()=>L(i,`author tone-${zx(n.color)}`)),r}}),null),R(s,j(yC,{e:t,get prev(){return e.prev?.()},get res(){return e.res},get orphan(){return e.orphan},get onOption(){return e.onOption},get answeredIds(){return e.answeredIds},get onAnswered(){return e.onAnswered},get agentActive(){return e.agentActive},get onResize(){return e.onResize},get agentId(){return e.agentId}}),null),b(e=>{var s=`msg`+(r()?` grouped`:``)+(i()?` next-grouped`:``)+(t.data?.pending?` pending`:``)+(t.data?.cancelled?` withdrawn`:``)+` tone-${zx(n.color)}`,c=t.id,l=String(t.session??``),u=`avatar avghost tone-${zx(n.color)}`+(r()?` ghosted`:``),d=r()?`${Vx(t.ts)} · ${t.branch}`:void 0;return s!==e.e&&L(a,e.e=s),c!==e.t&&I(a,`data-eid`,e.t=c),l!==e.a&&I(a,`data-session`,e.a=l),u!==e.o&&L(o,e.o=u),d!==e.i&&I(o,`title`,e.i=d),e},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),a})()}function vC(e){let t=()=>(Array.isArray(e.data?.images)?e.data.images:[]).map(e=>typeof e==`string`?e:e?.url).filter(e=>typeof e==`string`&&e.length>0).map(t=>Tf(e.agentId,t));return j(N,{get when(){return t().length},get children(){var e=US();return R(e,j(M,{get each(){return t()},children:e=>(()=>{var t=WS();return t.$$click=()=>nt(e),I(t,`src`,e),t})()})),e}})}function yC(e){let t=e.e;switch(t.type){case`prompt`:{let n=(t.data?.images??[]).map(e=>typeof e==`string`?e:e?.url).filter(e=>typeof e==`string`&&e.length>0).map(t=>Tf(e.agentId,t));return[j(gC,{get html(){return ut(String(t.data.text??``))}}),j(N,{get when(){return n.length},get children(){var e=US();return R(e,j(M,{each:n,children:e=>(()=>{var t=GS();return t.$$click=()=>nt(e),I(t,`src`,e),t})()})),e}})]}case`message`:return[j(N,{get when(){return P(()=>typeof t.data.reasoning==`string`)()&&t.data.reasoning.trim()},get children(){var e=KS(),n=e.firstChild.nextSibling;return R(n,()=>String(t.data.reasoning)),e}}),j(gC,{get html(){return ut(String(t.data.content??``))}}),j(N,{get when(){return t.data.interrupted},get children(){return qS()}}),j(N,{get when(){return t.data.final},get children(){var e=JS(),n=e.firstChild;return R(e,j(Cd,{get text(){return String(t.data.content??``)}}),n),e}})];case`tool_call`:return j(hC,{e:t,get prev(){return e.prev},get res(){return e.res},get orphan(){return e.orphan},get agentActive(){return e.agentActive},get onResize(){return e.onResize},get agentId(){return e.agentId}});case`tool_result`:{let n=String(t.data.result??``),r=String(t.data.name??`tool`),i=t.data.ok!==!1;return(()=>{var a=XS(),o=a.firstChild,s=o.firstChild,c=o.nextSibling,l=c.nextSibling;return L(a,`embed `+(i?``:`fail`)),R(s,r===`bash`?`$ (bash, call evicted)`:r),R(o,j(Cd,{text:n}),null),R(c,n),R(l,()=>dt(t.data.durationMs),null),R(l,()=>r===`bash`?Yx(Jx(t.data.ok,n)):i?``:` · FAILED`,null),R(a,j(N,{get when(){return e.orphan},get children(){return YS()}}),null),b(()=>a.open=e.orphan),a})()}case`decision`:{let e=Array.isArray(t.data?.alternatives)?t.data.alternatives:[];return(()=>{var n=QS(),r=n.firstChild.firstChild.firstChild.nextSibling;return R(n,j(gC,{get html(){return ut(String(t.data?.rationale??``))}}),null),R(n,j(N,{get when(){return e.length},get children(){var t=ZS();return t.firstChild,R(t,()=>e.join(` / `),null),t}}),null),b(()=>r.innerHTML=ut(String(t.data?.decision??``))),n})()}case`question`:{let n=Array.isArray(t.data?.options)?t.data.options:[],r=t.data?.callId?String(t.data.callId):``,i=()=>e.answeredIds?.().has(r)??!1;return(()=>{var a=tC(),o=a.firstChild.firstChild.nextSibling;return R(a,j(N,{get when(){return i()},get children(){return $S()}}),null),R(a,j(N,{get when(){return n.length>0},get children(){var a=eC();return R(a,j(M,{each:n,children:n=>(()=>{var a=nC();return a.$$click=()=>{e.onAnswered?.(r);let i=t.data?.actor;i?X(`/api/agents/${encodeURIComponent(String(i))}/prompt`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({text:n,start:!0})}).then(()=>wf(`→ answered @${String(t.data.actor)}`)).catch(()=>wf(`answer failed`)):e.onOption?.(n)},R(a,n),b(()=>a.disabled=i()),a})()})),a}}),null),R(a,j(mC,{get answered(){return i()},get onOption(){return e.onOption}}),null),b(e=>{var n=`embed question`+(i()?` answered`:``),r=ut(String(t.data?.question??``));return n!==e.e&&L(a,e.e=n),r!==e.t&&(o.innerHTML=e.t=r),e},{e:void 0,t:void 0}),a})()}case`progress`:return(()=>{var e=sC(),n=e.firstChild.firstChild.nextSibling;return R(e,j(N,{get when(){return t.data.goalStatus},get children(){var e=rC(),n=e.firstChild.nextSibling;return R(n,()=>String(t.data.goalStatus)),e}}),null),R(e,j(N,{get when(){return t.data.recent},get children(){var e=iC(),n=e.firstChild.nextSibling;return b(()=>n.innerHTML=ut(String(t.data.recent))),e}}),null),R(e,j(N,{get when(){return t.data.problems},get children(){var e=aC(),n=e.firstChild.nextSibling;return b(()=>n.innerHTML=ut(String(t.data.problems))),e}}),null),R(e,j(N,{get when(){return t.data.next},get children(){var e=oC(),n=e.firstChild.nextSibling;return b(()=>n.innerHTML=ut(String(t.data.next))),e}}),null),b(()=>n.innerHTML=ut(String(t.data.doing??``))),e})();case`error`:return(()=>{var e=cC(),n=e.firstChild;return n.firstChild,R(n,()=>String(t.data.message??``),null),e})();case`compaction`:return t.data.summary?(()=>{var e=fC(),n=e.firstChild.firstChild.nextSibling,r=n.firstChild,i=r.nextSibling,a=i.nextSibling.nextSibling;return a.nextSibling,R(n,()=>String(t.data.mode??``),r),R(n,()=>Ux(Number(t.data.tokensBefore??0)),i),R(n,()=>Ux(Number(t.data.tokensAfter??0)),a),R(n,(()=>{var e=P(()=>!!t.data.summarized);return()=>e()?`${t.data.summarized} summarized`:`${t.data.dropped} dropped`})(),null),R(e,j(N,{get when(){return t.data.summary},get children(){return[dC(),j(gC,{get html(){return ut(String(t.data.summary))}})]}}),null),e})():(()=>{var e=uC(),n=e.firstChild.nextSibling,r=n.firstChild,i=r.nextSibling,a=i.nextSibling.nextSibling;return a.nextSibling,R(n,()=>String(t.data.mode??``),r),R(n,()=>Ux(Number(t.data.tokensBefore??0)),i),R(n,()=>Ux(Number(t.data.tokensAfter??0)),a),R(n,(()=>{var e=P(()=>!!t.data.summarized);return()=>e()?`${t.data.summarized} summarized`:`${t.data.dropped} dropped`})(),null),R(n,()=>String(t.data.mode??``)===`truncate`?` · older history dropped`:``,null),R(e,j(N,{get when(){return String(t.data.mode??``)===`truncate`},get children(){return lC()}}),null),e})();default:return(()=>{var e=pC();return R(e,()=>ft(JSON.stringify(t.data),200)),e})()}}Ee([`input`,`keydown`,`click`]);var bC=(e,t)=>{let n=String(t??``).trim();return!n||/^\d+$/.test(n)?null:e?.[n]??null},xC=[{key:`openrouter`,label:`OpenRouter`,url:`https://openrouter.ai/api/v1`,model:``,hint:`400+ models behind one key — teapot sends app-attribution headers automatically`},{key:`orcarouter`,label:`OrcaRouter`,url:`https://api.orcarouter.ai/v1`,model:``,hint:`zero-markup routing gateway — 'orcarouter/auto' grades each prompt and picks the model`},{key:`openai`,label:`OpenAI`,url:`https://api.openai.com/v1`,model:``,hint:`your account's models — pick from the list once the endpoint answers`},{key:`opencode-go`,label:`OpenCode Go`,url:`https://opencode.ai/zen/go/v1`,model:``,hint:`OpenCode's open-model subscription — teapot sends the required x-opencode-session header; choose a chat/completions model`},{key:`llamacpp`,label:`llama.cpp server`,url:`http://localhost:8080/v1`,model:``,hint:`free & local — start it with: llama-server -m ./model.gguf (any model name works)`}];function SC(e,t){return e?t===`dark`?{slot:`dark`,key:`teapot.theme.dark`}:{slot:`light`,key:`teapot.theme.light`}:{slot:`fixed`,key:`teapot.theme`}}var CC=F(`<div class=themeeditor><h4 class=cfgsub>your themes</h4><div class=btnrow><button type=button title="copy the theme you are using into a new editable one — presets themselves are never modified">+ duplicate current`),wC=F(`<div class=muted style="margin:6px 0">`),TC=F(`<b>+ duplicate current`),EC=F(`<div class=cfggrid style=margin-top:8px><label class=trow>name<input type=text maxlength=40 placeholder="theme name"></label><label class=trow>appearance<select><option value=dark>dark</option><option value=light>light`),DC=F(`<div class=paletterows>`),OC=F(`<div class=btnrow><button type=button title="put every colour back to the palette this theme was created from">↺ reset palette</button><button type=button title="delete this custom theme">🗑 delete`),kC=F(`<h4 class=cfgsub>background image`),AC=F(`<img sizes=260px alt="current background"decoding=async loading=lazy>`,!0,!1,!1),jC=F(`<span class=bgpick-hint>🖼 replace…`),MC=F(`<div class=bgpreview><span class=muted title="this image is served from the server; the theme stores only its URL">✓ image set</span><div class=btnrow><label class=trow title="how much the image is dimmed so text stays readable">dim<input type=range min=0 max=0.9 step=0.01><span class="muted mono">%</span></label><label title="how much of the background shows through code blocks and tool cards — lower is more transparent">surfaces<input type=range min=0.35 max=1 step=0.01><span class="muted mono">%</span></label><button type=button>✕ remove`),NC=F(`<div class=cfggrid><button type=button></button><input type=file accept=image/* style=display:none>`),PC=F(`<div class=muted style=margin-top:6px;font-size:var(--text-xs)>the image is uploaded to the server and sits behind the panels, dimmed so text stays readable. No size limit — it is a file now, not browser storage.`),FC=F(`<label class=paletterow><input type=color><span class=paletterow-label></span><input class="mono paletterow-hex">`),IC=F(`<span class=bgpick-empty>🖼 choose a background image…`),LC=F(`<div class=muted style=font-size:11.5px;margin-top:4px>⚠ configured default provider <code></code> has no provider row here<!> Add a provider named <code></code> or pick a default below; otherwise agents fall back to the first provider.`),RC=F(`<div class=cfggrid style=margin-top:8px><label class=trow>dark theme →<select class=w100></select></label><label class=trow>light theme →<select class=w100>`),zC=F(`<div class=skilllist>`),BC=F(`<span style=color:var(--err);font-size:13px>`),VC=F(`<form style=display:flex;flex-direction:column;gap:12px;min-height:0><div class=cfgbody><nav class=cfgmenu aria-label="settings sections"></nav><div class=cfgpanel><fieldset><legend>providers</legend><button type=button>+ add custom</button><div style=display:flex;gap:6px;flex-wrap:wrap;margin-top:6px><span class=muted style=font-size:11.5px>quick-add:</span></div><div><label title="agents without an explicit provider use this one"style=display:flex;align-items:center;gap:6px;margin-top:6px>default provider<select><option value>(none — first provider wins)</option></select></label></div></fieldset><fieldset><legend>appearance</legend><div class=cfggrid><label class=trow>follow the system<input type=checkbox></label></div><h4 class=cfgsub>themes</h4></fieldset><fieldset><legend>agent runtime</legend><div class=cfgrow><label style=flex:1>API password<input type=password class=w100></label><span class=muted style=font-size:11.5px;max-width:34ch>bearer token for /api. empty = loopback only.</span></div><div class=cfggrid><label title="auto-compact threshold in k tokens. Leave EMPTY to derive per model (75% of its context window) — recommended, since models differ wildly in window size. Set only to force an absolute cap across all models.">compact budget (k tok)<input type=number min=0 placeholder="(derive: 75% of window)"></label></div><label class=cfgtoggle title="prune old tool output early (at 60% of the budget) instead of waiting for the window to fill. Meant for small-window models — on a large window it throws away context you had room for."><input type=checkbox>short-context mode</label></fieldset><fieldset><legend>MCP servers — external tools, shared by every agent</legend><div class=muted style=font-size:11.5px;margin-bottom:8px>each tool becomes <code class=mono>mcp__server__tool</code> for every agent. saving connects them; the status shown here is live.</div><button type=button>+ add MCP server</button></fieldset><fieldset><legend>scheduled tasks</legend><button type=button>+ add task</button></fieldset><fieldset><legend>archived agents — restore, or delete for good</legend></fieldset><fieldset><legend>agents (read-only — edit config file or use +)</legend></fieldset><fieldset><legend>live update</legend><div class=cfgrow><span class=muted>current version: </span><button type=button class=primarybtn>update & restart</button><span class=muted style=margin-left:8px;font-size:12px>gracefully stops all agents, spawns new process, then reloads this page</span></div></fieldset><fieldset><legend>skills</legend></fieldset><fieldset><legend>help</legend><div class=helpsec><h4 class=cfgsub>this host</h4><div class=featgrid><div class=featrow><b>image downscaling</b><span class=muted></span></div><div class=featrow><b>terminal pty</b><span class=muted></span></div></div></div><div class=helpsec><h4 class=cfgsub>keyboard</h4><div class=helprow><kbd>enter</kbd><span>send (shift+enter for a newline)</span></div><div class=helprow><span class=kbdgroup><kbd>↑</kbd><kbd>↓</kbd></span><span>move between sessions</span></div><div class=helprow><kbd>/</kbd><span>command palette — commands and focus</span></div><div class=helprow><kbd>t</kbd><span>open the terminal panel</span></div><div class=helprow><kbd>d</kbd><span>toggle the details panel</span></div><div class=helprow><kbd>esc</kbd><span>interrupt the running turn</span></div></div><div class=helpsec><h4 class=cfgsub>what the toggles do</h4><div class=helprow><b>auto-continue</b><span>fires after a round only when all hold: the toggle is on, a goal is set and its status is <code>active</code>, and the round ended cleanly (not an error, not stopped). It stops when the goal is marked done, or when you press ■ stop. Sending any prompt starts an idle agent regardless.</span></div><div class=helprow><b>auto-compact</b><span>when the live context passes the budget shown under 📊 runtime, older turns are summarized into notes and the recent stretch is kept verbatim, so work continues without losing the thread. Off means you compact by hand (<code>/compact</code>).</span></div><div class=helprow><b>messages while it works</b><span>anything you send queues up and is handed to the model at its next turn boundary — the timeline shows it as "pending (queued)…" until then. Withdraw it with ✕ cancel while it is still queued.</span></div><div class=helprow><b>👻 ghost sessions</b><span>a session whose workspace directory no longer exists on disk. The session log is intact — recreate the directory and it stops being a ghost.</span></div></div></fieldset></div></div><div class=cfgfoot><button type=submit class=cfgsave>`),HC=F(`<button type=button><span class=cfgmenu-label>`),UC=F(`<div class=cfgrow><input class=cfgname placeholder=name><input placeholder=https://…/v1><input placeholder="default model"><button type=button class=danger title="remove provider">✕</button><div class=cfgkeys><button type=button title="add another key for this provider — they are rotated round-robin, and a rate-limited key is skipped for a minute">+ key`),WC=F(`<button type=button title="remove this key">−`),GC=F(`<div class=cfgkeyrow><input type=password>`),KC=F(`<button type=button>+ `),qC=F(`<option>`),JC=F(`<div class=cfgsub style=margin-bottom:var(--space-1)>`),YC=F(`<div class=themepick>`),XC=F(`<button type=button><span class=themecard-preview></span><span class=themecard-label> ★`),ZC=F(`<button type=button><span class=themecard-preview></span><span class=themecard-label>`),QC=F(`<div class=muted style=font-size:12.5px>no MCP servers. add one below — a remote url, or a local command for stdio.`),$C=F(`<input placeholder="command (e.g. npx)">`),ew=F(`<input placeholder="args, space separated">`),tw=F(`<input type=password placeholder="paste the token"title="sent as Authorization: Bearer <token>"style=flex:1>`),nw=F(`<input placeholder="header name"style="flex:0 1 150px">`),rw=F(`<input type=password placeholder=value style=flex:1>`),iw=F(`<div class=cfgrow><textarea class=mono rows=2 placeholder="{&quot;Authorization&quot;: &quot;Bearer …&quot;, &quot;X-Team&quot;: &quot;infra&quot;}"title="static headers for every request. Use the bearer option unless the server needs something unusual."style=flex:1>`),aw=F(`<button type=button class=mcpauthorize title="start the OAuth flow: a browser tab opens, and the tools appear when you finish">🔑 authorize`),ow=F(`<span class="mcpstate connected"title="an OAuth access token is usable — disconnect it under the server's details">🔑 authorized`),sw=F(`<span>`),cw=F(`<div class=muted style=font-size:11px;color:var(--warn)>`),lw=F(`<div class="cfgcol mcpcard"><div class=cfgrow><input class=cfgname placeholder=name title="the name that appears inside mcp__<name>__ in tool names"><input placeholder="https://example.com/mcp (or leave empty for a stdio command)"><label style=display:flex;gap:3px;align-items:center;white-space:nowrap;color:var(--dim);font-size:11px><input type=checkbox>on</label><button type=button class=danger>✕</button></div><div class=cfgrow><input placeholder="what this server is for — e.g. reverse engineering: decompile, disassemble"title="shown to the model when the MCP catalog is too large to send, so it can search for the right tool instead of guessing keywords"></div><div class=cfgrow><select title="streamable HTTP is the current spec; legacy SSE is the 2024-11-05 handshake; stdio spawns a local process"><option value=http>streamable http</option><option value=sse>legacy http+sse</option><option value=stdio>stdio (local command)</option></select></div><div class=cfgrow><select title="how this server authenticates"><option value=none>no auth</option><option value=bearer>bearer token</option><option value=header>custom header</option><option value=json>headers as JSON (advanced)</option></select></div><div class=cfgrow><button type=button title="connect now and list the tools — nothing is saved">test`),uw=F(`<option value=oauth selected>`),dw=F(`<span class=muted> · needs a grant (🔑 authorize)`),fw=F(`<details class=mcptools-wrap><summary>show <!> tool</summary><ul class=mcptools>`),pw=F(`<div class=mcpdanger><span class=muted>OAuth grant</span><button type=button class=mcpdisconnect title="forget the stored grant (the refresh token is deleted, so authorizing again needs a browser)">disconnect`),mw=F(`<div><div class=mcpresult-head><b>`),hw=F(`<span class=mcptool-desc>`),gw=F(`<li><code class=mono>`),_w=F(`<div class=cfgcol><div class=cfgrow><input placeholder=id><input placeholder="agent id"><input placeholder="every 30m / cron"><label style=display:flex;gap:3px;align-items:center;white-space:nowrap;color:var(--dim);font-size:11px><input type=checkbox>fork</label><button type=button class=danger>✕</button></div><textarea rows=2 placeholder="prompt to send">`),vw=F(`<div class=muted style=font-size:12.5px>nothing archived. 🗄 archive in the controls panel puts an agent away without losing its history.`),yw=F(`<div class="cfgrow archrow"><div class=archmain><b></b><span class=muted> session</span><span class="muted mono ellip"></span></div><button type=button class=archrestore title="bring it back and start it again — its history was never touched">↩ restore</button><button type=button class=danger title="erase the config entry AND every session directory — irreversible">🗑 delete`),bw=F(`<span class=muted>🧩 sub of @`),xw=F(`<div class=cfgrow><b></b><span class=muted>`),Sw=F(`<div class=muted>`),Cw=F(`<div class=skillbody>`),ww=F(`<div class=skillrow><button type=button class=skillhead title="show the playbook"><span class=skillcaret></span><b class=mono></b><span class=muted>`),Tw=F(`<div class="muted skillbody">`);function Ew(e){let[t,n]=y(e.themes().some(t=>t.id===e.paintedId)?e.paintedId:e.themes()[0]?.id??``),r=()=>hr(e.themes(),e.paintedId,t()),[i,a]=y({}),o,s=t=>{let n=r()?.id;if(!n)return;let i=e.themes().map(e=>e.id===n?t(e):e);e.onChange(i)},c=(e,t)=>{let n=pr(t);n&&s(t=>({...t,palette:{...t.palette,[e]:n}}))},l=()=>{let t=e.themes().find(t=>t.id===e.paintedId),r=$d.find(t=>t.key===e.paintedId),i=t??r??$d[0],a=getComputedStyle(document.documentElement),o={...rr};for(let{key:e,cssVar:t}of tr){let n=pr(a.getPropertyValue(t));n&&(o[e]=n)}let s=ur(e.themes().map(e=>e.id).concat($d.map(e=>e.key))),c={id:s,label:`${i.label}${t?``:` copy`}`.slice(0,40),mode:i.mode,palette:o,...t?.backgroundImage?{backgroundImage:t.backgroundImage,backgroundDim:t.backgroundDim,surfaceAlpha:t.surfaceAlpha}:{}};e.onChange([...e.themes(),c]),n(s),e.onPick(s)},u=async t=>{if(t){if(!/^image\//.test(t.type))wf(`that file is ${JSON.stringify(t.type||`unknown`)} — pick an image`);else{wf(`uploading ${t.name} (${Math.round(t.size/1024)}KB)…`);try{let n=await fetch(`/api/assets`,{method:`POST`,headers:{"content-type":t.type},body:t}).then(async e=>({ok:e.ok,body:await e.json().catch(()=>null)}));if(!n.ok||!n.body?.url){wf(n.body?.error??`upload failed`);return}s(e=>({...e,backgroundImage:n.body.url,backgroundImageBytes:n.body.bytes}));let i=r()?.id;i&&e.onPick(i),wf(`background image set`)}catch(e){wf(`upload failed: ${e.message}`)}}}};return(()=>{var t=CC(),d=t.firstChild.nextSibling.firstChild;return d.$$click=l,R(t,j(N,{get when(){return P(()=>!!(r()&&e.themes().some(t=>t.id===e.paintedId)))()?r():null},get fallback(){return(()=>{var t=wC();return R(t,(()=>{var t=P(()=>e.themes().length===0);return()=>t()?[`no custom themes yet — press `,TC(),` to start from the palette you are using.`]:[`the editor shows when one of your themes is the one on screen — pick one under "your themes" above (or press `,TC(),`).`]})()),t})()},children:t=>[(()=>{var e=EC(),t=e.firstChild,n=t.firstChild.nextSibling,i=t.nextSibling.firstChild.nextSibling;return n.$$input=e=>s(t=>({...t,label:e.currentTarget.value})),i.addEventListener(`change`,e=>s(t=>({...t,mode:e.currentTarget.value}))),b(()=>n.value=r().label),b(()=>i.value=r().mode),e})(),(()=>{var e=DC();return R(e,j(M,{each:tr,children:e=>(()=>{var t=FC(),n=t.firstChild,o=n.nextSibling,s=o.nextSibling;return n.$$input=t=>c(e.key,t.currentTarget.value),R(o,()=>e.label),s.addEventListener(`blur`,()=>a(t=>{let n={...t};return delete n[e.key],n})),s.$$input=t=>{let n=t.currentTarget.value;a(t=>({...t,[e.key]:n})),c(e.key,n)},I(s,`spellcheck`,!1),b(()=>I(t,`title`,e.cssVar)),b(()=>n.value=pr(r().palette[e.key])??`#000000`),b(()=>s.value=i()[e.key]??r().palette[e.key]),t})()})),e})(),(()=>{var t=OC(),i=t.firstChild,a=i.nextSibling;return i.$$click=()=>s(e=>({...e,palette:{...rr}})),a.$$click=()=>{let t=r()?.id;t&&(e.onChange(e.themes().filter(e=>e.id!==t)),n(e.themes().find(e=>e.id!==t)?.id??``))},t})(),kC(),(()=>{var e=NC(),t=e.firstChild,n=t.nextSibling;t.$$click=()=>o?.click(),R(t,j(N,{get when(){return r().backgroundImage},get fallback(){return IC()},get children(){return[(()=>{var e=AC();return b(t=>{var n=fn(r().backgroundImage),i=dn(r().backgroundImage);return n!==t.e&&I(e,`src`,t.e=n),i!==t.t&&I(e,`srcset`,t.t=i),t},{e:void 0,t:void 0}),e})(),jC()]}})),n.addEventListener(`change`,e=>{e.stopPropagation(),u(e.currentTarget.files?.[0]),e.currentTarget.value=``}),n.$$input=e=>e.stopPropagation();var i=o;return typeof i==`function`?Ae(i,n):o=n,R(e,j(N,{get when(){return r().backgroundImage},get children(){var e=MC(),t=e.firstChild;t.firstChild;var n=t.nextSibling.firstChild,i=n.firstChild.nextSibling,a=i.nextSibling,o=a.firstChild,c=n.nextSibling,l=c.firstChild.nextSibling,u=l.nextSibling,d=u.firstChild,f=c.nextSibling;return R(t,()=>{let e=r()?.backgroundImageBytes;return e?` — ${Math.max(1,Math.round(e/1024))} KB`:``},null),i.$$input=e=>s(t=>({...t,backgroundDim:Number(e.currentTarget.value)})),R(a,()=>Math.round((r().backgroundDim??.55)*100),o),l.$$input=e=>s(t=>({...t,surfaceAlpha:Number(e.currentTarget.value)})),R(u,()=>Math.round((r().surfaceAlpha??.82)*100),d),f.$$click=()=>s(e=>({...e,backgroundImage:void 0})),b(()=>i.value=r().backgroundDim??.55),b(()=>l.value=r().surfaceAlpha??.82),e}}),null),b(e=>{var n=`bgpick`+(r().backgroundImage?` has`:``),i=r().backgroundImage?`click to replace this background image (PNG/JPG/WebP)`:`choose a background image (PNG/JPG/WebP)`;return n!==e.e&&L(t,e.e=n),i!==e.t&&I(t,`title`,e.t=i),e},{e:void 0,t:void 0}),e})(),PC()]}),null),t})()}function Dw(e){let t=(e,t)=>{let n=Array.isArray(t?.apiKeys)&&t.apiKeys.length?t.apiKeys.filter(e=>typeof e==`string`&&e.trim()):t?.apiKey?[String(t.apiKey)]:[``];return{name:e,baseUrl:t?.baseUrl??``,apiKeys:n.length?n:[``],model:t?.model??``}},[n,r]=y(Object.entries(e.cfg.providers??{}).map(([e,n])=>t(e,n))),[i,a]=y(e.cfg.defaultProvider??``),o=()=>e.cfg.defaultProvider??``,s=()=>{let e=[...new Set(n().map(e=>e.name.trim()).filter(Boolean))],t=i();return t&&!e.includes(t)&&e.push(t),e},c=()=>{let e=i();return e?n().some(t=>t.name.trim()===e)?``:e:``},[l,u]=y(Math.round((e.cfg.progressIntervalMs??6e5)/6e4)),[d,f]=y(e.cfg.progressMinChars??4e3),[p,m]=y(e.cfg.contextTokenBudget==null?null:Math.round(e.cfg.contextTokenBudget/1e3)),[h,g]=y(e.cfg.contextWindowTokens?Math.round(e.cfg.contextWindowTokens/1e3):0),[_,v]=y(e.cfg.maxSpawnDepth??3),[ee,S]=y(!!e.cfg.shortContext),[C,w]=y(``),[T,E]=y(!1),[D,O]=y((e.cfg.tasks??[]).map(e=>({...e}))),[te,ne]=y((e.cfg.mcpServers??[]).map(e=>({...e}))),[re,k]=y(Object.fromEntries((e.cfg.mcpServers??[]).map((e,t)=>[t,e.headers?JSON.stringify(e.headers):``]))),[ie,ae]=y({}),[oe,se]=y(Object.fromEntries((e.cfg.mcpServers??[]).map((e,t)=>{let n=e.headers??{},r=Object.keys(n);if(!r.length)return[t,`none`];let i=r.length===1?r[0]:``;return i===`Authorization`&&/^Bearer /i.test(n[i]??``)?[t,`bearer`]:[t,r.length===1?`header`:`json`]}))),[ce,le]=y(Object.fromEntries((e.cfg.mcpServers??[]).map((e,t)=>{let n=e.headers??{},r=Object.keys(n);if(r.length!==1)return[t,``];let i=r[0];return[t,i===`Authorization`?(n[i]??``).replace(/^Bearer /i,``):n[i]??``]}))),[ue,de]=y(Object.fromEntries((e.cfg.mcpServers??[]).map((e,t)=>{let n=Object.keys(e.headers??{}),r=n.length===1?n[0]:``;return[t,r&&r!==`Authorization`?r:``]}))),[fe,A]=y({}),pe={},me=async(e,t)=>{if(!te()[e])return;let n=await X(`/api/mcp/test`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(t)}).catch(()=>null);te()[e]&&n&&A(t=>({...t,[e]:n.ok?{kind:`ok`,text:`${n.tools?.length??0} tools`}:{kind:`err`,text:n.needsOAuth?`needs authorization — press 🔑`:n.error??`no response`,...n.needsOAuth?{needsOAuth:!0}:{}}}))},[he,ge]=y({}),[_e,ve]=y({}),ye=e=>{let t=bC(_e(),e);return t&&(t.required||t.authorized)?t:null},be=async()=>{let e=await X(`/api/mcp`).catch(()=>null);ge(Object.fromEntries((e?.states??[]).map(e=>[e.name,e])))},xe=async e=>{let t=String(e??``).trim();if(!t)return;let n=await X(`/api/mcp/oauth/status?name=${encodeURIComponent(t)}`).catch(()=>null);n&&!n.error&&ve(e=>({...e,[t]:n}))},Ce=async(t,n)=>{if(!n.name){A(e=>({...e,[t]:{kind:`err`,text:`give it a name first`}}));return}A(e=>({...e,[t]:{kind:`testing`,text:`discovering the authorization server…`}}));let r=await X(`/api/mcp/oauth/start`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({name:n.name,url:n.url})}).catch(()=>null);if(r?.alreadyAuthorized){A(e=>({...e,[t]:{kind:`ok`,text:`already authorized`}})),await xe(n.name),await be();return}if(!r?.ok||!r.url){A(e=>({...e,[t]:{kind:`err`,text:r?.error??`no response`}})),await xe(n.name);return}window.open(r.url,`_blank`,`noopener`),A(e=>({...e,[t]:{kind:`testing`,text:`waiting for you to finish in the browser…`}}));let i=Date.now()+3e5;for(;Date.now()<i;){await new Promise(e=>setTimeout(e,1e3));let r=await X(`/api/mcp/oauth/status?name=${encodeURIComponent(n.name)}`).catch(()=>null);if(r&&!r.error){if(ve(e=>({...e,[n.name]:r})),r.authorized){A(e=>({...e,[t]:{kind:`ok`,text:`authorized — the tools are available now`}})),await be(),e.onSaved();return}if(r.flow?.phase===`error`){A(e=>({...e,[t]:{kind:`err`,text:r.flow.message??r.lastError??`authorization failed`}}));return}}}A(e=>({...e,[t]:{kind:`err`,text:`authorization timed out`}}))};x(()=>{F()===`mcp`&&(be(),te().forEach((e,t)=>{e.name&&xe(e.name)}))});let[we,Te]=y(``),[F,Ee]=y(`providers`),De=(t,n)=>{let{slot:r}=SC(e.theme.auto(),n);r===`dark`?Ge(t):r===`light`?qe(t):Ve(t)},Oe=t=>e.theme.auto()?t===e.theme.dark()||t===e.theme.light():t===e.theme.activeId(),[ke,Ae]=y([]),je=async()=>{let e=await X(`/api/archived`).catch(()=>null);Ae(e?.agents??[])},Me=()=>ke().filter(e=>!e.parent);x(()=>{F()===`archive`&&je()});let Ne=[{key:`providers`,label:`🧦 providers`,hint:`endpoints, API keys, default models`},{key:`appearance`,label:`🎨 appearance`,hint:`theme, custom palettes, background image`},{key:`runtime`,label:`⚙️ runtime`,hint:`context budget, retries, spawn depth`},{key:`tasks`,label:`⏰ scheduled tasks`,hint:`cron prompts run against an agent`},{key:`mcp`,label:`🔌 MCP servers`,hint:`external tool servers exposed to every agent`},{key:`archive`,label:`🗄 archive`,hint:`agents you put away — restore or delete for good`},{key:`agents`,label:`👥 agents`,hint:`what exists (read-only)`},{key:`update`,label:`⬆️ live update`,hint:`restart onto a newer build`},{key:`skills`,label:`🧠 skills`,hint:`reusable playbooks available to the selected session`},{key:`help`,label:`❔️ help`,hint:`keyboard shortcuts and what each toggle does`}],Pe=()=>(e.cfg.agents??[]).map(e=>e.id),Fe=()=>e.theme.themes(),Ie=()=>e.theme.activeId(),Le={auto:localStorage.getItem(`teapot.theme.auto`)===`1`,dark:localStorage.getItem(`teapot.theme.dark`)??`dark`,light:localStorage.getItem(`teapot.theme.light`)??`light`,fixed:localStorage.getItem(`teapot.theme`)??`dark`},Re=y(Le),ze=Re[0],Be=t=>{let n={...ze(),...t};Re[1](n),e.theme.setAuto(n.auto),e.theme.setDark(n.dark),e.theme.setLight(n.light),e.theme.setActive(n.fixed);let r=t.dark??t.light??t.fixed;r&&e.theme.preview(r)},Ve=e=>Be({fixed:e}),He=()=>ze().auto,Ue=e=>Be({auto:e}),We=()=>ze().dark,Ge=e=>Be({dark:e}),Ke=()=>ze().light,qe=e=>Be({light:e}),Je=t=>e.theme.setThemes(t),Ye=()=>{let t=Le;e.theme.setAuto(t.auto),e.theme.setDark(t.dark),e.theme.setLight(t.light),e.theme.setActive(t.fixed),e.theme.preview(null)},Xe=e=>ir[e]??rr,Ze=()=>{let e={};for(let t of n()){if(!t.name.trim())return Te(`provider name is required`),null;if(t.baseUrl&&!/^https?:\/\//.test(t.baseUrl))return Te(`provider ${t.name}: baseUrl must start with http(s)://`),null;let n=t.apiKeys.map(e=>e.trim()).filter(Boolean);e[t.name.trim()]={baseUrl:t.baseUrl,...n.length?{apiKeys:n,apiKey:n[0]}:{},...t.model?{model:t.model}:{}}}return e},[Qe,$e]=y(`idle`),et=e=>{Te(e),$e(e=>e===`saving`?`idle`:e)},tt=async t=>{t.preventDefault(),Te(``),$e(`saving`);let n=Ze();if(!n)return $e(`idle`);let r=D().filter(e=>e.id?.trim()||e.prompt?.trim()).map((e,t)=>({id:e.id?.trim()||`task-${t+1}`,agent:e.agent,schedule:e.schedule,prompt:e.prompt,...e.forked?{forked:!0}:{}}));for(let e of r){if(!e.agent)return et(`task "${e.id}": agent is required`);if(!e.schedule?.trim())return et(`task "${e.id}": schedule is required`)}let a=[],o=new Set;for(let e of te()){let t=String(e.name??``).trim(),n=String(e.url??``).trim(),r=e.transport??`http`,i=String(e.command??``).trim();if(t||n||i){if(!t)return et(`MCP: a server needs a name`);if(o.has(t))return et(`MCP: two servers are named "${t}"`);if(o.add(t),r===`stdio`?!i:!n)return et(`MCP "${t}": ${r===`stdio`?`a command is`:`a url is`} required`);a.push({name:t,transport:r,enabled:e.enabled!==!1,...String(e.description??``).trim()?{description:String(e.description).trim()}:{},...n?{url:n}:{},...r===`stdio`?{command:i,...e.args?.length?{args:e.args}:{}}:{},...e.headers&&Object.keys(e.headers).length?{headers:e.headers}:{}})}}try{await X(`/api/config`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({providers:n,defaultProvider:i()||void 0,progressIntervalMs:Math.max(1,l())*6e4,progressMinChars:Math.max(100,d()),...p()==null?{}:{contextTokenBudget:Math.max(1,p())*1e3},...h()>0?{contextWindowTokens:h()*1e3}:{},maxSpawnDepth:Math.max(0,_()),shortContext:ee(),...T()?{password:C()}:{},tasks:r,mcpServers:a})}),await be(),await Promise.all(a.map((e,t)=>e.name?xe(e.name):Promise.resolve())),setTimeout(()=>{be(),a.forEach((e,t)=>{e.name&&xe(e.name)})},1200),e.onSaved();let t=new Set(a.map(e=>e.name).filter(Boolean)),o=te().filter(e=>{let n=String(e.name??``).trim();return t.has(n)&&_e()[n]?.required&&!_e()[n]?.authorized}).filter(t=>!e.announcedOAuth.has(String(t.name??``)));if(o.length>0){for(let t of o)e.announcedOAuth.add(String(t.name??``));wf(`${o.map(e=>String(e.name??``).trim()).filter(Boolean).join(`, `)||`a saved MCP server`} needs authorization — 🔑 authorize in MCP servers`)}e.theme.commitAppearance(ze()),e.theme.preview(null),$e(`saved`),Object.assign(Le,ze()),setTimeout(()=>{$e(`idle`),e.onClose()},400)}catch(e){Te(e.message),$e(`error`),setTimeout(()=>$e(`idle`),1600)}};return j(wd,{title:`settings`,onClose:()=>{Ye(),e.onClose()},get children(){var t=VC(),x=t.firstChild,T=x.firstChild,ge=T.nextSibling.firstChild,ve=ge.firstChild.nextSibling,be=ve.nextSibling;be.firstChild;var ke=be.nextSibling.firstChild.firstChild.nextSibling;ke.firstChild;var Ae=ge.nextSibling,Le=Ae.firstChild.nextSibling,Re=Le.firstChild.firstChild.nextSibling,ze=Le.nextSibling,Be=Ae.nextSibling,Ye=Be.firstChild.nextSibling,Ze=Ye.firstChild.firstChild.nextSibling,$e=Ye.nextSibling,et=$e.firstChild,nt=et.firstChild.nextSibling,rt=$e.nextSibling.firstChild,it=Be.nextSibling,at=it.firstChild.nextSibling.nextSibling,ot=it.nextSibling,st=ot.firstChild.nextSibling,ct=ot.nextSibling;ct.firstChild;var lt=ct.nextSibling;lt.firstChild;var dt=lt.nextSibling,ft=dt.firstChild.nextSibling.firstChild;ft.firstChild;var mt=ft.nextSibling,ht=dt.nextSibling;ht.firstChild;var gt=ht.nextSibling,_t=gt.firstChild.nextSibling.firstChild.nextSibling.firstChild,vt=_t.firstChild.nextSibling,yt=_t.nextSibling.firstChild.nextSibling,bt=x.nextSibling,xt=bt.firstChild;return t.addEventListener(`submit`,tt),R(T,j(M,{each:Ne,children:e=>(()=>{var t=HC(),n=t.firstChild;return t.$$click=()=>Ee(e.key),R(n,()=>e.label),b(n=>{var r=`cfgmenu-item`+(F()===e.key?` on`:``),i=e.hint,a=F()===e.key?`page`:void 0;return r!==n.e&&L(t,n.e=r),i!==n.t&&I(t,`title`,n.t=i),a!==n.a&&I(t,`aria-current`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()})),R(ge,j(Se,{get each(){return n()},children:(e,t)=>(()=>{var i=UC(),a=i.firstChild,o=a.nextSibling,s=o.nextSibling,c=s.nextSibling,l=c.nextSibling,u=l.firstChild;return a.$$input=e=>r(n().map((n,r)=>r===t?{...n,name:e.currentTarget.value}:n)),o.$$input=e=>r(n().map((n,r)=>r===t?{...n,baseUrl:e.currentTarget.value}:n)),s.$$input=e=>r(n().map((n,r)=>r===t?{...n,model:e.currentTarget.value}:n)),c.$$click=()=>r(n().filter((e,n)=>n!==t)),R(l,j(M,{get each(){return e().apiKeys},children:(i,a)=>(()=>{var o=GC(),s=o.firstChild;return s.$$input=e=>r(n().map((n,r)=>r===t?{...n,apiKeys:n.apiKeys.map((t,n)=>n===a()?e.currentTarget.value:t)}:n)),s.value=i,R(o,j(N,{get when(){return e().apiKeys.length>1},get children(){var e=WC();return e.$$click=()=>r(n().map((e,n)=>n===t?{...e,apiKeys:e.apiKeys.filter((e,t)=>t!==a())}:e)),e}}),null),b(()=>I(s,`placeholder`,a()===0?`api key`:`api key (backup)`)),o})()}),u),u.$$click=()=>r(n().map((e,n)=>n===t?{...e,apiKeys:[...e.apiKeys,``]}:e)),b(()=>a.value=e().name),b(()=>o.value=e().baseUrl),b(()=>s.value=e().model),i})()}),ve),ve.$$click=()=>r([...n(),{name:``,baseUrl:``,apiKeys:[``],model:``}]),R(be,j(M,{each:xC,children:e=>(()=>{var t=KC();return t.firstChild,t.$$click=()=>{let t=n().filter(t=>t.name!==e.key);r([...t,{name:e.key,baseUrl:e.url,apiKeys:[``],model:e.model}]),i()||a(e.key)},R(t,()=>e.label,null),b(()=>I(t,`title`,`fill a ${e.label} row — ${e.url}${e.model?` (model: ${e.model})`:``}`)),t})()}),null),ke.addEventListener(`change`,e=>a(e.currentTarget.value)),R(ke,j(M,{get each(){return s()},children:e=>(()=>{var t=qC();return t.value=e,R(t,e),t})()}),null),R(ge,j(N,{get when(){return c()},get children(){var e=LC(),t=e.firstChild.nextSibling,n=t.nextSibling.nextSibling,r=n.nextSibling.nextSibling;return R(t,c),R(e,()=>c()===o()?` — the dropdown above cannot show it.`:` — it was replaced by your selection.`,n),R(r,c),e}}),null),Re.addEventListener(`change`,e=>{Ue(e.currentTarget.checked)}),R(Ae,j(N,{get when(){return He()},get children(){var e=RC(),t=e.firstChild,n=t.firstChild.nextSibling,r=t.nextSibling.firstChild.nextSibling;return n.addEventListener(`change`,e=>{Ge(e.currentTarget.value)}),R(n,j(M,{get each(){return Fe().filter(e=>e.mode===`dark`).map(e=>({key:e.id,label:`${e.label} (custom)`})).concat($d.filter(e=>e.mode===`dark`))},children:e=>(()=>{var t=qC();return R(t,()=>e.label),b(()=>t.value=e.key),t})()})),r.addEventListener(`change`,e=>{qe(e.currentTarget.value)}),R(r,j(M,{get each(){return Fe().filter(e=>e.mode===`light`).map(e=>({key:e.id,label:`${e.label} (custom)`})).concat($d.filter(e=>e.mode===`light`))},children:e=>(()=>{var t=qC();return R(t,()=>e.label),b(()=>t.value=e.key),t})()})),b(()=>n.value=We()),b(()=>r.value=Ke()),e}}),ze),R(Ae,j(M,{each:[{mode:`dark`,title:`dark themes`},{mode:`light`,title:`light themes`}],children:e=>j(N,{get when(){return[...Fe(),...$d].some(t=>t.mode===e.mode)},get children(){return[(()=>{var t=JC();return R(t,()=>e.title),t})(),(()=>{var t=YC();return R(t,j(M,{get each(){return Fe().filter(t=>t.mode===e.mode)},children:e=>(()=>{var t=XC(),n=t.firstChild,r=n.nextSibling,i=r.firstChild;return t.$$click=()=>De(e.id,e.mode),R(n,j(bf,{get palette(){return e.palette},get backgroundImage(){return e.backgroundImage},get surfaceAlpha(){return e.surfaceAlpha},get backgroundDim(){return e.backgroundDim}})),R(r,()=>e.label,i),b(n=>{var r=`themecard`+(Oe(e.id)?` on`:``),i=`${e.label} (custom)${e.backgroundImage?` · with a background image`:``}`,a=Oe(e.id);return r!==n.e&&L(t,n.e=r),i!==n.t&&I(t,`title`,n.t=i),a!==n.a&&I(t,`aria-pressed`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()}),null),R(t,j(M,{get each(){return $d.filter(t=>t.mode===e.mode)},children:e=>(()=>{var t=ZC(),n=t.firstChild,r=n.nextSibling;return t.$$click=()=>De(e.key,e.mode),R(n,j(bf,{get palette(){return Xe(e.key)}})),R(r,()=>e.label),b(n=>{var r=`themecard`+(Oe(e.key)?` on`:``),i=`${e.label} (${e.mode})`,a=Oe(e.key);return r!==n.e&&L(t,n.e=r),i!==n.t&&I(t,`title`,n.t=i),a!==n.a&&I(t,`aria-pressed`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()}),null),t})()]}})}),null),R(Ae,j(Ew,{themes:Fe,get paintedId(){return e.theme.paintedId()},onChange:e=>{let t=cr(e),n=e;if(!t.ok){let t=e.map(e=>e.backgroundImage?{...e,backgroundImage:void 0,backgroundDim:void 0,surfaceAlpha:void 0,backgroundImageBytes:void 0}:e),r=cr(t);if(r.ok)n=t,wf(`storage was full — saved without the background image(s)`);else{wf(r.error??`could not save theme`);return}}Je(n);let r=e=>n.some(t=>t.id===e)||$d.some(t=>t.key===e);r(Ie())||(Ve(`dark`),localStorage.setItem(`teapot.theme`,`dark`)),r(We())||(Ge(`dark`),localStorage.setItem(`teapot.theme.dark`,`dark`)),r(Ke())||(qe(`light`),localStorage.setItem(`teapot.theme.light`,`light`))},onPick:e=>{let t=Fe().find(t=>t.id===e)?.mode??$d.find(t=>t.key===e)?.mode??`dark`,n=SC(He(),t);n.slot===`dark`?Ge(e):n.slot===`light`?qe(e):Ve(e)}}),null),Ze.$$input=e=>{w(e.currentTarget.value),E(!0)},R($e,j(yf,{label:`progress interval (min)`,get value(){return l()},onValue:e=>u(e),hint:`how often the harness asks for a progress report`}),et),R($e,j(yf,{label:`progress min chars`,get value(){return d()},onValue:e=>f(e),hint:`progress prompts wait for this much real output`}),et),nt.$$input=e=>m(e.currentTarget.value===``?null:Number(e.currentTarget.value)),R($e,j(yf,{label:`context window (k tok)`,get value(){return h()},onValue:e=>g(e),hint:`model's real window — 0/blank hides the % gauge`}),null),R($e,j(yf,{label:`max spawn depth`,get value(){return _()},onValue:e=>v(e),hint:`sub-agent nesting limit (0 = no spawning)`}),null),rt.addEventListener(`change`,e=>S(e.currentTarget.checked)),R(it,j(N,{get when(){return te().length>0},get fallback(){return QC()},get children(){return j(Se,{get each(){return te()},children:(e,t)=>{let n=()=>he()[e().name],r=e=>ne(te().map((n,r)=>r===t?{...n,...e}:n));return(()=>{var i=lw(),a=i.firstChild,o=a.firstChild,s=o.nextSibling,c=s.nextSibling,l=c.firstChild,u=c.nextSibling,d=a.nextSibling,f=d.firstChild,p=d.nextSibling,m=p.firstChild,h=p.nextSibling,g=h.firstChild,_=g.firstChild,v=h.nextSibling,ee=v.firstChild;return o.$$input=e=>r({name:e.currentTarget.value}),s.$$input=e=>{r({url:e.currentTarget.value});let n=e.currentTarget.value.trim();clearTimeout(pe[t]),/^https?:\/\//.test(n)&&(pe[t]=setTimeout(()=>{me(t,{...te()[t],url:n})},700))},l.addEventListener(`change`,e=>r({enabled:e.currentTarget.checked})),u.$$click=()=>ne(te().filter((e,n)=>n!==t)),f.$$input=e=>r({description:e.currentTarget.value}),m.addEventListener(`change`,e=>r({transport:e.currentTarget.value})),R(p,j(N,{get when(){return e().transport===`stdio`},get children(){return[(()=>{var t=$C();return t.$$input=e=>r({command:e.currentTarget.value}),b(()=>t.value=e().command??``),t})(),(()=>{var t=ew();return t.$$input=e=>r({args:e.currentTarget.value.split(` `).filter(Boolean)}),b(()=>t.value=(e().args??[]).join(` `)),t})()]}}),null),g.addEventListener(`change`,e=>{let n=e.currentTarget.value;if(se(e=>({...e,[t]:n})),n===`none`)r({headers:void 0});else if(n===`bearer`){let e=ce()[t]??``;r({headers:e?{Authorization:`Bearer ${e}`}:void 0})}else if(n===`header`){let e=ue()[t]??``,n=ce()[t]??``;r({headers:e&&n?{[e]:n}:void 0})}}),R(g,j(N,{get when(){return ye(String(e().name??``))},children:e=>(()=>{var t=uw();return R(t,()=>e().authorized?`OAuth — authorized`:`OAuth — authorization needed`),t})()}),_),R(h,j(N,{get when(){return oe()[t]===`bearer`},get children(){var e=tw();return e.$$input=e=>{let n=e.currentTarget.value;le(e=>({...e,[t]:n})),r({headers:n?{Authorization:`Bearer ${n}`}:void 0})},b(()=>e.value=ce()[t]??``),e}}),null),R(h,j(N,{get when(){return oe()[t]===`header`},get children(){return[(()=>{var e=nw();return e.$$input=e=>{let n=e.currentTarget.value;de(e=>({...e,[t]:n}));let i=ce()[t]??``;r({headers:n&&i?{[n]:i}:void 0})},b(()=>e.value=ue()[t]??``),e})(),(()=>{var e=rw();return e.$$input=e=>{let n=e.currentTarget.value;le(e=>({...e,[t]:n}));let i=ue()[t]??``;r({headers:i&&n?{[i]:n}:void 0})},b(()=>e.value=ce()[t]??``),e})()]}}),null),R(i,j(N,{get when(){return oe()[t]===`json`},get children(){var e=iw(),n=e.firstChild;return n.$$input=e=>{let n=e.currentTarget.value;if(k(e=>({...e,[t]:n})),!n.trim())r({headers:void 0});else try{let e=JSON.parse(n);if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`not an object`);r({headers:e}),ae(e=>({...e,[t]:``}))}catch{ae(e=>({...e,[t]:`must be a JSON object — not applied`}))}},b(()=>n.value=re()[t]??``),e}}),v),ee.$$click=async()=>{let e=te()[t];if(!e.name){A(e=>({...e,[t]:{kind:`err`,text:`give it a name first`}}));return}A(e=>({...e,[t]:{kind:`testing`,text:`connecting…`}}));let n=await X(`/api/mcp/test`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e)}).catch(()=>null);A(e=>({...e,[t]:n?.ok?{kind:`ok`,text:`${n.tools?.length??0} tool${n.tools?.length===1?``:`s`}`,tools:n.tools??[]}:{kind:`err`,text:n?.error??`no response`,...n?.needsOAuth?{needsOAuth:!0}:{}}})),n?.ok||await xe(e.name)},R(v,j(N,{get when(){return P(()=>!!bC(_e(),String(e().name??``))?.required)()&&!bC(_e(),String(e().name??``))?.authorized},get children(){var n=aw();return n.$$click=()=>void Ce(t,e()),n}}),null),R(v,j(N,{get when(){return bC(_e(),String(e().name??``))?.authorized},get children(){return ow()}}),null),R(v,j(N,{get when(){return n()},get children(){var e=sw();return R(e,(()=>{var e=P(()=>n()?.status===`connected`);return()=>e()?`● ${n()?.tools} tools`:P(()=>n()?.status===`error`)()?`● error`:n()?.status===`disabled`?`● off`:`● idle`})()),b(t=>{var r=`mcpstate `+(n()?.status??``),i=n()?.lastError??``;return r!==t.e&&L(e,t.e=r),i!==t.t&&I(e,`title`,t.t=i),t},{e:void 0,t:void 0}),e}}),null),R(i,j(N,{get when(){return ie()[t]},get children(){var e=cw();return R(e,()=>ie()[t]),e}}),null),R(i,j(N,{get when(){return fe()[t]},children:n=>(()=>{var r=mw(),i=r.firstChild,a=i.firstChild;return R(a,()=>n().text),R(i,j(N,{get when(){return n().needsOAuth},get children(){return dw()}}),null),R(r,j(N,{get when(){return(n().tools?.length??0)>0},get children(){var e=fw(),t=e.firstChild,r=t.firstChild.nextSibling;r.nextSibling;var i=t.nextSibling;return R(t,()=>n().tools?.length,r),R(t,()=>n().tools?.length===1?``:`s`,null),R(i,j(M,{get each(){return n().tools??[]},children:e=>(()=>{var t=gw(),n=t.firstChild;return R(n,()=>e.name),R(t,j(N,{get when(){return e.description},get children(){var t=hw();return R(t,()=>e.description),t}}),null),b(()=>I(t,`title`,e.description??``)),t})()})),e}}),null),R(r,j(N,{get when(){return bC(_e(),String(e().name??``))?.authorized},get children(){var n=pw(),r=n.firstChild.nextSibling;return r.$$click=async()=>{confirm(`Disconnect ${e().name}?\n\nThe stored OAuth grant is deleted and you will have to authorize again in a browser.`)&&(await X(`/api/mcp/oauth/disconnect`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({name:e().name})}).catch(()=>{}),await xe(e().name),A(e=>({...e,[t]:{kind:`ok`,text:`disconnected`}})))},n}}),null),b(()=>L(r,`mcpresult `+(n().kind===`err`?`err`:`ok`))),r})()}),null),b(()=>o.value=e().name),b(()=>s.value=e().url??``),b(()=>l.checked=e().enabled!==!1),b(()=>f.value=e().description??``),b(()=>m.value=e().transport??`http`),b(()=>g.value=ye(String(e().name??``))?`oauth`:oe()[t]??`none`),i})()}})}}),at),at.$$click=()=>ne([...te(),{name:``,url:``,transport:`http`,enabled:!0}]),R(ot,j(N,{get when(){return D().length>0},get children(){return j(Se,{get each(){return D()},children:(e,t)=>(()=>{var n=_w(),r=n.firstChild,i=r.firstChild,a=i.nextSibling,o=a.nextSibling,s=o.nextSibling,c=s.firstChild,l=s.nextSibling,u=r.nextSibling;return i.$$input=e=>O(D().map((n,r)=>r===t?{...n,id:e.currentTarget.value}:n)),a.$$input=e=>O(D().map((n,r)=>r===t?{...n,agent:e.currentTarget.value}:n)),o.$$input=e=>O(D().map((n,r)=>r===t?{...n,schedule:e.currentTarget.value}:n)),c.addEventListener(`change`,e=>O(D().map((n,r)=>r===t?{...n,forked:e.currentTarget.checked}:n))),l.$$click=()=>O(D().filter((e,n)=>n!==t)),u.$$input=e=>O(D().map((n,r)=>r===t?{...n,prompt:e.currentTarget.value}:n)),b(()=>i.value=e().id),b(()=>a.value=e().agent),b(()=>o.value=e().schedule),b(()=>c.checked=!!e().forked),b(()=>u.value=e().prompt),n})()})}}),st),st.$$click=()=>O([...D(),{id:``,agent:Pe()[0]??``,schedule:`every 30m`,prompt:``}]),R(ct,j(N,{get when(){return Me().length>0},get fallback(){return vw()},get children(){return j(M,{get each(){return Me()},children:t=>(()=>{var n=yw(),r=n.firstChild,i=r.firstChild,a=i.nextSibling,o=a.firstChild,s=a.nextSibling,c=r.nextSibling,l=c.nextSibling;return R(i,()=>t.id),R(a,()=>t.sessions,o),R(a,()=>t.sessions===1?``:`s`,null),R(a,(()=>{var e=P(()=>(t.subs??0)>0);return()=>e()?` · +${t.subs} sub-agent${t.subs===1?``:`s`} (restored together)`:``})(),null),R(a,(()=>{var e=P(()=>!!t.archivedAt);return()=>e()?` · archived ${pt(new Date(t.archivedAt).toISOString())}`:``})(),null),R(s,()=>t.workspace),c.$$click=async()=>{let n=await X(`/api/agents/${t.id}/restore`,{method:`POST`}).catch(()=>null);await je(),e.onSaved();let r=(n?.ids?.length??1)-1;wf((n?.live===!1?`restored ${t.id} — it could not be started (check its provider)`:`restored ${t.id}`)+(r>0?` + ${r} sub-agent${r===1?``:`s`}`:``))},l.$$click=async()=>{confirm(`PERMANENTLY DELETE ${t.id}?\n\n${t.sessions} session${t.sessions===1?``:`s`} of history will be erased from disk along with the config entry. This cannot be undone — archiving was the reversible option.`)&&(await X(`/api/agents/${t.id}/purge`,{method:`DELETE`}).catch(()=>{}),await je(),e.onSaved(),wf(`deleted ${t.id} for good`))},b(()=>I(s,`title`,t.workspace)),n})()})}}),null),R(lt,j(M,{get each(){return e.cfg.agents??[]},children:e=>(()=>{var t=xw(),n=t.firstChild,r=n.nextSibling;return R(n,()=>e.id),R(r,()=>e.workspace),R(t,j(N,{get when(){return e.parent},get children(){var t=bw();return t.firstChild,R(t,()=>e.parent,null),t}}),null),t})()}),null),R(ft,()=>e.cfg.version??`unknown`,null),mt.$$click=async e=>{try{Te(``);let t=e.currentTarget;t.disabled=!0,t.textContent=`updating…`;let n=await X(`/api/update/restart`,{method:`POST`});if(!n.ok)throw Error((await n.json()).error??`restart failed`);t.textContent=`restarting…`;let r=null,i=!1;for(let e=0;e<120&&!i;e++){await new Promise(e=>setTimeout(e,1e3));try{let e=await X(`/api/version`);if(!e.version)continue;r===null&&(r=e.uptimeSeconds??null),(e.version!==`0.37.174`||typeof e.uptimeSeconds==`number`&&r!==null&&e.uptimeSeconds<r)&&(i=!0,window.location.reload())}catch{}}if(!i)throw Error(`restart timeout — new server did not come up`)}catch(e){Te(e.message)}finally{e.currentTarget.disabled=!1,e.currentTarget.textContent=`update & restart`}},R(ht,j(N,{get when(){return e.skills.length>0},get fallback(){return(()=>{var t=Sw();return R(t,()=>e.hasSelection?`this session has no skills yet — the agent saves them with save_skill once a procedure proves itself`:`select a session to see the skills available to it`),t})()},get children(){var t=zC();return R(t,j(M,{get each(){return e.skills},children:t=>{let[n,r]=y(!1),[i,a]=y(null),[o,s]=y(``),c=async()=>{if(n())return r(!1);if(r(!0),i()===null&&e.agentId)try{let n=await X(`/api/agents/${e.agentId}/skills/${encodeURIComponent(t.name)}`);a(String(n.text??``))}catch(e){s(e.message)}};return(()=>{var e=ww(),r=e.firstChild,a=r.firstChild,s=a.nextSibling,l=s.nextSibling;return r.$$click=c,R(a,()=>n()?`▾`:`▸`),R(s,()=>t.name),R(l,()=>t.description),R(e,j(N,{get when(){return n()},get children(){return j(N,{get when(){return i()!==null},get fallback(){return(()=>{var e=Tw();return R(e,()=>o()||`loading…`),e})()},get children(){var e=Cw();return b(()=>e.innerHTML=ut(String(i()??``))),e}})}}),null),b(()=>e.classList.toggle(`open`,!!n())),e})()}})),t}}),null),R(vt,(()=>{var t=P(()=>!!e.features);return()=>t()?P(()=>!!e.features.imageResize.available)()?`on — ${e.features.imageResize.tool}, long edge ≤ ${e.features.imageResize.maxEdge}px`:`off — no ffmpeg / ImageMagick found; uploads are served as-is`:`checking…`})()),R(yt,(()=>{var t=P(()=>!!e.features);return()=>t()?P(()=>!!e.features.pty.available)()?`on — ${e.features.pty.provider}`:`off — no pty provider; terminals run on plain pipes (no resize)`:`checking…`})()),R(bt,j(N,{get when(){return we()},get children(){var e=BC();return R(e,we),e}}),xt),R(xt,(()=>{var e=P(()=>Qe()===`saving`);return()=>e()?`saving…`:P(()=>Qe()===`saved`)()?`✓ saved`:Qe()===`error`?`✕ failed`:`save settings`})()),b(t=>{var n=F()!==`providers`,r=F()!==`appearance`,i=F()!==`runtime`,a=e.cfg.hasPassword?`(unchanged — type to replace)`:`(none — loopback only)`,o=F()!==`mcp`,s=F()!==`tasks`,c=F()!==`archive`,l=F()!==`agents`,u=F()!==`update`,d=F()!==`skills`,f=F()!==`help`,p=Qe()===`saved`,m=Qe()===`error`,h=Qe()===`saving`;return n!==t.e&&ge.classList.toggle(`hide`,t.e=n),r!==t.t&&Ae.classList.toggle(`hide`,t.t=r),i!==t.a&&Be.classList.toggle(`hide`,t.a=i),a!==t.o&&I(Ze,`placeholder`,t.o=a),o!==t.i&&it.classList.toggle(`hide`,t.i=o),s!==t.n&&ot.classList.toggle(`hide`,t.n=s),c!==t.s&&ct.classList.toggle(`hide`,t.s=c),l!==t.h&&lt.classList.toggle(`hide`,t.h=l),u!==t.r&&dt.classList.toggle(`hide`,t.r=u),d!==t.d&&ht.classList.toggle(`hide`,t.d=d),f!==t.l&&gt.classList.toggle(`hide`,t.l=f),p!==t.u&&xt.classList.toggle(`saved`,t.u=p),m!==t.c&&xt.classList.toggle(`error`,t.c=m),h!==t.w&&(xt.disabled=t.w=h),t},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0,r:void 0,d:void 0,l:void 0,u:void 0,c:void 0,w:void 0}),b(()=>ke.value=i()),b(()=>Re.checked=He()),b(()=>Ze.value=C()),b(()=>nt.value=p()??``),b(()=>rt.checked=ee()),t}})}Ee([`click`,`input`]);var Ow=new Set([`png`,`jpg`,`jpeg`,`gif`,`webp`,`svg`,`bmp`,`ico`,`avif`]),kw=new Set([`mp4`,`webm`,`mov`,`mkv`,`avi`,`m4v`]),Aw=new Set([`mp3`,`wav`,`ogg`,`m4a`,`flac`,`aac`,`opus`]);function jw(e){let t=e.split(`.`).pop()?.toLowerCase()??``,n=Mw(e);return n===`image`?`🖼`:n===`video`?`🎬️`:n===`audio`?`🎵`:[`ts`,`tsx`,`mts`,`cts`].includes(t)?`🟦`:[`js`,`mjs`,`cjs`,`jsx`].includes(t)?`🟨`:t===`json`||t===`jsonc`?`🧾`:t===`md`||t===`mdx`||t===`markdown`?`📝`:t===`css`||t===`scss`||t===`less`?`🎨`:t===`html`||t===`htm`||t===`svg`?`🌐️`:[`py`,`pyi`].includes(t)?`🐍`:t===`rs`?`🦀`:t===`go`?`🐹`:t===`java`||t===`kt`||t===`kts`?`☕️`:t===`rb`?`💎`:t===`php`?`🐘`:t===`c`||t===`h`||t===`cpp`||t===`hpp`||t===`cc`?`🧩`:t===`sh`||t===`bash`||t===`zsh`||t===`fish`?`🐚`:t===`sql`?`🗄`:t===`yml`||t===`yaml`||t===`toml`||t===`ini`||t===`conf`?`⚙️`:t===`lock`?`🔒️`:e===`Dockerfile`||t===`dockerfile`?`🐳`:t===`zip`||t===`gz`||t===`tar`||t===`tgz`||t===`bz2`?`📦`:t===`pdf`?`📕`:t===`txt`||t===`log`?`📄`:`·`}function Mw(e){let t=e.split(`.`).pop()?.toLowerCase()??``;return Ow.has(t)?`image`:kw.has(t)?`video`:Aw.has(t)?`audio`:null}var Nw=new Map,Pw=e=>{let t=Nw.get(e);return t||(t={expanded:new Set,preview:null,media:null,viewMode:`code`},Nw.set(e,t)),t},Fw=F(`<span class=fsize>`),Iw=F(`<div><span class=ficon></span><span class=fname>`),Lw=F(`<h3 title="the agent's workspace — lazy-loaded, dotfiles hidden; click a folder to expand, a file to preview"style=display:flex;align-items:center;gap:6px>🗂 files <span class=muted style=text-transform:none;letter-spacing:0>· `),Rw=F(`<div class=filebox>`),zw=F(`<div class=muted style=padding:6px>`),Bw=F(`<img>`),Vw=F(`<div class=mediapreview><div class="meta muted"> preview`),Hw=F(`<button title="rendered markdown">👁 preview`),Uw=F(`<button title="edit and save back to the workspace">✎ edit`),Ww=F(`<div class=filetoolbar><button title="syntax-highlighted source">&lt;/> code`),Gw=F(`<div class=fileeditor><textarea class=mono></textarea><div class=filerow-actions><span class=muted> bytes</span><button class=savebtn>`),Kw=F(`<div class=mono style=margin:0;color:var(--dim)>(binary file — inspect it from the terminal)`),qw=F(`<div class="content mdpreview shikiwrap">`),Jw=F(`<video controls>`),Yw=F(`<audio controls>`);function Xw(e){let t=Pw(e.agentId),[n,r]=y(new Map),[i,a]=y(t.expanded),[o,s]=y(t.preview),c=e=>{t.preview=e,s(e)},l=e=>{t.expanded=e,a(e)},[u,d]=y(t.media),f=e=>{t.media=e,d(e)},[p,m]=y(t.viewMode),h=e=>{t.viewMode=e,m(e)},[g,_]=y(``),[v,ee]=y(localStorage.getItem(`teapot.ignoreMode`)??`dim`),S=()=>{let e=[`dim`,`hide`,`show`],t=e[(e.indexOf(v())+1)%3];ee(t),localStorage.setItem(`teapot.ignoreMode`,t)},C=e=>v()!==`hide`||!e.ignored,[w,E]=y(localStorage.getItem(`teapot.showHidden`)===`1`),D=()=>{let e=!w(),t=[``,...i()];Promise.all(t.map(async t=>({p:t,rows:await ne(t,e)}))).then(t=>{E(e),localStorage.setItem(`teapot.showHidden`,e?`1`:`0`);for(let{p:e,rows:n}of t)n&&re(e,n)})},O=(e,t)=>t.map(t=>({name:String(t.name),path:e?`${e}/${t.name}`:String(t.name),dir:!!t.dir,...typeof t.size==`number`?{size:t.size}:{},...t.ignored?{ignored:!0}:{}}));async function te(e){return ne(e,w())}async function ne(t,n){try{let r=new URLSearchParams;t&&r.set(`path`,t),n&&r.set(`hidden`,`1`);let i=await X(`/api/agents/${e.agentId}/tree?${r.toString()}`);return O(t,i.entries??[])}catch(e){return _(e.message),null}}let re=(e,n)=>r(r=>{let i=r.get(e);if(!i)return new Map(r).set(e,n);let a=new Map(i.map(e=>[e.path,e])),o=n.map(e=>{let t=a.get(e.path);return t&&t.dir===e.dir&&t.size===e.size&&t.ignored===e.ignored&&t.name===e.name?t:e}).filter(e=>n.some(t=>t.path===e.path)||t.preview?.path===e.path),s=new Map(r);return s.set(e,o),s}),k=``;x(()=>{let t=e.agentId;t!==k&&(k=t,l(new Set),c(null),f(null),r(new Map),te(``).then(e=>{e&&k===t&&r(new Map([[``,e]]))}))});let ie=async e=>{let t=new Set(i());if(t.has(e.path))t.delete(e.path),l(t);else if(t.add(e.path),l(t),!n().has(e.path)){let t=await te(e.path);t&&re(e.path,t)}},[ae,oe]=y(``),[se,ce]=y(!1),[le,ue]=y(``),[de,fe]=y(!1),A=e=>/\.(md|markdown|mdx)$/i.test(e),pe=0,me=async e=>{let t=++pe;oe(``),ce(!0);try{let{highlightChunks:n}=await Y(async()=>{let{highlightChunks:e}=await Promise.resolve().then(()=>vx);return{highlightChunks:e}},void 0);for await(let r of n(e.path,e.content)){if(pe!==t)return;oe(e=>e+r)}}catch{pe===t&&oe(``)}finally{pe===t&&ce(!1)}};T(()=>{pe++});let he=async(t,n)=>{let r=Mw(t.path);if(r)c({path:t.path,content:``,binary:!0}),f({path:t.path,kind:r}),h(`media`);else try{let r=await X(`/api/agents/${e.agentId}/file?path=${encodeURIComponent(t.path)}`);f(null),c({path:t.path,content:r.content??``,binary:r.binary,truncated:r.truncated}),ue(r.content??``),h(r.binary?`code`:n),!r.binary&&n!==`md`&&me({path:t.path,content:r.content??``,truncated:r.truncated})}catch(e){wf(`open failed: ${e.message}`)}},ge=async()=>{let t=o();if(t&&!de()){fe(!0);try{await X(`/api/agents/${e.agentId}/file?path=${encodeURIComponent(t.path)}`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({content:le(),baseContent:t.content})}),c({...t,content:le()}),wf(`saved ${t.path}`)}catch(e){let n=e.payload,r=n&&typeof n==`object`&&n.error===`file changed on disk`?n:null;r?.current===void 0?wf(`save failed: ${e.message}`):confirm(`This file changed on disk since you opened it.
181
181
  OK = load the disk version into the editor (your edits are discarded)
182
- Cancel = keep editing your copy`)?(de(r.current),c({...t,content:r.current}),wf(`loaded the current file from disk`)):wf(`kept your edits — use Save As via bash to force-write`)}finally{pe(!1)}}},ve=e=>!e.binary&&!e.truncated,ye=(e,t)=>[(()=>{var n=Fw(),r=n.firstChild,a=r.nextSibling;return n.$$click=()=>e.dir?void ae(e):void ge(e,`code`),L(r,(()=>{var t=N(()=>!!e.dir);return()=>t()?i().has(e.path)?`▾`:`▸`:Aw(e.name)})()),L(a,()=>e.name),L(n,A(M,{get when(){return N(()=>!e.dir)()&&e.size!==void 0},get children(){var t=Pw();return L(t,()=>Hx(e.size)),t}}),null),b(r=>{var i=`filerow`+(e.dir?` isdir`:``)+(e.ignored&&v()===`dim`?` gitignored`:``),a=`padding-left:${t*13+8}px`,o=e.dir?`browse ${e.path}`:`preview ${e.path}`;return i!==r.e&&I(n,r.e=i),r.t=ke(n,a,r.t),o!==r.a&&F(n,`title`,r.a=o),r},{e:void 0,t:void 0,a:void 0}),n})(),A(M,{get when(){return N(()=>!!e.dir)()&&i().has(e.path)},get children(){return A(j,{get each(){return(n().get(e.path)??[]).filter(C)},children:e=>ye(e,t+1)})}})],be=()=>e.workspace.split(`/`).filter(Boolean).pop()??e.workspace,[xe,Se]=y(!1),Ce=async()=>{if(!xe()){Se(!0);try{let e=[``,...i()],t=await Promise.all(e.map(async e=>({p:e,rows:await re(e,w())})));for(let{p:e,rows:n}of t)n&&ie(e,n)}finally{Se(!1)}}};return[(()=>{var e=Iw(),t=e.firstChild.nextSibling;return t.firstChild,L(t,be,null),L(e,A(Sd,{class:`filetoggle`,get icon(){return xe()?`…`:`⟳`},title:`refresh the tree (root + expanded folders) — open popups are kept`,onClick:()=>void Ce()}),null),L(e,A(Sd,{class:`filetoggle`,style:`margin-left:auto`,get icon(){return N(()=>v()===`hide`)()?`🙈`:v()===`dim`?`👁`:`✨`},get title(){return`gitignored files: ${v()} — click to cycle (dim → hidden → shown)`},onClick:S}),null),L(e,A(Sd,{class:`filetoggle`,get icon(){return w()?`◉.`:`○.`},get title(){return w()?`dotfiles shown — click to hide`:`dotfiles hidden — click to show`},onClick:E}),null),e})(),(()=>{var e=Lw();return L(e,A(M,{get when(){return(n().get(``)??[]).length>0},get fallback(){return(()=>{var e=Rw();return L(e,()=>g()||`empty workspace`),e})()},get children(){return A(j,{get each(){return(n().get(``)??[]).filter(C)},children:e=>ye(e,0)})}})),e})(),A(M,{get when(){return o()},children:t=>A(wd,{get title(){return`🗂 ${t().path}`},onClose:()=>{me++,c(null),f(null)},get children(){return A(M,{get when(){return u()},get fallback(){return[(()=>{var e=Uw(),n=e.firstChild;return L(e,A(M,{get when(){return N(()=>!!k(t().path))()&&!t().binary},get children(){var e=Vw();return e.$$click=()=>h(`md`),b(()=>I(e,p()===`md`?`on`:``)),e}}),n),n.$$click=()=>{h(`code`),oe()||he({path:t().path,content:t().content,truncated:t().truncated})},L(e,A(M,{get when(){return ve(t())},get children(){var e=Hw();return e.$$click=()=>h(`edit`),b(()=>I(e,p()===`edit`?`on`:``)),e}}),null),b(()=>I(n,p()===`code`?`on`:``)),e})(),A(M,{get when(){return!t().binary},get fallback(){return Gw()},get children(){return A(M,{get when(){return p()===`edit`},get fallback(){return A(M,{get when(){return N(()=>p()===`md`)()&&k(t().path)},get fallback(){return A(vf,{get path(){return t().path},get content(){return t().content},get html(){return oe()},get pending(){return ce()},get truncated(){return!!t().truncated}})},get children(){var e=Kw();return b(()=>e.innerHTML=ze(t().content)),e}})},get children(){var e=Ww(),n=e.firstChild,r=n.nextSibling.firstChild,i=r.firstChild,a=r.nextSibling;return n.$$input=e=>de(e.currentTarget.value),F(n,`spellcheck`,!1),L(r,()=>Hx(ue().length),i),a.$$click=()=>void _e(),L(a,()=>fe()?`saving…`:`💾 save`),b(()=>a.disabled=fe()||ue()===t().content),b(()=>n.value=ue()),e}})}})]},get children(){var t=Bw(),n=t.firstChild,r=n.firstChild;return L(t,A(M,{get when(){return u().kind===`image`},get fallback(){return A(M,{get when(){return u().kind===`video`},get fallback(){return(()=>{var t=Jw();return b(()=>F(t,`src`,`/api/agents/${e.agentId}/raw?path=${encodeURIComponent(u().path)}`)),t})()},get children(){var t=qw();return b(()=>F(t,`src`,`/api/agents/${e.agentId}/raw?path=${encodeURIComponent(u().path)}`)),t}})},get children(){var t=zw();return b(n=>{var r=`/api/agents/${e.agentId}/raw?path=${encodeURIComponent(u().path)}`,i=u().path.split(`/`).pop();return r!==n.e&&F(t,`src`,n.e=r),i!==n.t&&F(t,`alt`,n.t=i),n},{e:void 0,t:void 0}),t}}),n),L(n,()=>u().kind,r),t}})}})})]}De([`click`,`input`]);var Xw=P(`<div class=overlay><div class=modal style=max-width:360px><div class=modal-head><b>🔒️ sign in</b><span></span></div><form style=display:flex;flex-direction:column;gap:10px><input id=pw-input type=password placeholder=password autofocus><button type=submit class=primarybtn>unlock</button><span class=muted style=font-size:11px>the token is stored locally and sent as Bearer to this server only`),Zw=P(`<div class=leftbarbackdrop>`),Qw=P(`<div class=sidehead><b>agents</b><button class=iconbtn title="close the agent list">✕`),$w=P(`<i class=notifdot>`),eT=P(`<br>`),tT=P(`<button class="iconbtn ham"title="agent list">☰`),nT=P(`<input class="title titleedit">`),rT=P(`<span class="badge queued">⏳ <!> <!> queued`),iT=P(`<button type=button class="badge bgjobs">⚙️ `),aT=P(`<span class="badge cron">⏰ `),oT=P(`<div class=bgjobs-pop role=dialog aria-label="background shells"><div class=bgjobs-head><span>background shells</span><button type=button class=iconbtn title=close>✕`),sT=P(`<header class=chan-head><span class=hash title="rename this chat">#</span><span></span><span class=sub> · <!>/<!> · <!>↻ <!>⚙️</span><span class=head-actions><button></button><span class=head-sep aria-hidden=true>`),cT=P(`<div class=divider-msg>── beginning of log ──`),lT=P(`<div class=divider-msg>loading older events…`),uT=P(`<div class=feedloading><span class=spinner aria-hidden=true></span> loading timeline…`),dT=P(`<div class=feedloading><span class=spinner aria-hidden=true></span> loading newer events…`),fT=P(`<details class=reasoning open><summary>💭 thinking </summary><div class="mono thinkscroll">`),pT=P(`<div class=muted style=font-size:11.5px;margin-bottom:4px>🗜 summarizing older context…`),mT=P(`<div class=content>`),hT=P(`<div class="msg live"><div class=avatar style="background:#5865f233;border:1px solid #5865f266">🫖</div><div class=msg-body><div class=msg-head><span class=author style=color:var(--acc)>agent</span><span class=ts>streaming…`),gT=P(`<div class=feed>`),_T=P(`<div class="termempty muted">no shell here — + opens one, tabs fill the focused pane`),vT=P(`<div class=termsplit>`),yT=P(`<div class="termempty muted">no shell here — click a tab or + to add`),bT=P(`<div class=termpane>`),xT=P(`<div class=termdrawer><div class=termgrip title="drag to resize · double-click to reset"></div><div class=termbar><div class=termtabs></div><div style=display:flex;gap:4px;align-items:center><span class="muted mono"style=flex:1;text-align:center;overflow:hidden;text-overflow:ellipsis;white-space:nowrap></span></div></div><div class=termbody><div class=termpane>`),ST=P(`<button class=jump>↓ `),CT=P(`<div class=cmds>`),wT=P(`<div class=attachrow><button type=button class=attachclear title="remove every attachment">clear`),TT=P(`<label class=forkchip title="inherit the conversation prefix byte-exactly — the sub-agent's provider prefix cache starts warm"><input type=checkbox>fork ctx`),ET=P(`<div class="hint flashhint">`),DT=P(`<div><form><textarea rows=1></textarea><button type=button class="iconbtn maxbtn"></button><button type=submit>send</button><input id=composer-file type=file accept=image/* multiple style=display:none>`),OT=P(`<div class=rightbarbackdrop>`),kT=P(`<div><nav><div class=agent-list></div><div class=sidebar-footer><div class=footer-row style=justify-content:flex-end><button>🔔️</button></div><div class=brand-row><div class=brand>🫖 teapot <span class=version>v</span><span></span></div></div><div class=metrics></div></div></nav><section class=channel></section><aside><div class=rightbarhead><span class=muted>details`),AT=P(`<div class=notifbackdrop>`),jT=P(`<button class=editbtn>clear all`),MT=P(`<div class=notiflist>`),NT=P(`<div class=notifpanel><div class=notifhead>notifications<span style=display:flex;gap:8px;align-items:center><button class=iconbtn title="close notifications">✕`),PT=P(`<div class=bgphoto aria-hidden=true><img sizes=100vw alt decoding=async><span class=bgphoto-veil>`),FT=P(`<span class=wscount>`),IT=P(`<div class=wsheader><span class=wscaret></span><span class=wsname>`),LT=P(`<span class=notifbadge>🔔️`),RT=P(`<span class=subtag>🧩`),zT=P(`<span class=mini-cron>⏰`),BT=P(`<span class=goaldone title="goal done">✓`),VT=P(`<div><span></span><span>`),HT=P(`<span class=caret-spacer>`),UT=P(`<span class=caret>`),WT=P(`<span class=ghosttag title="workspace missing">👻`),GT=P(`<span>🧩 `),KT=P(`<div class=muted style=display:grid;place-items:center;height:100%>select an agent`),qT=P(`<span class=title>`),JT=P(`<div class="muted bgjobs-empty">no background jobs for this agent`),YT=P(`<pre class="mono bgjob-tail">`),XT=P(`<div class=bgjob><div class=bgjob-line><span></span><code class="mono bgjob-cmd"></code><span class="muted bgjob-meta"></span><button type=button class=bgjob-kill>`),ZT=P(`<div class="muted bgjob-detached">this job outlived a harness restart, so its output is no longer captured here. it is still running as pid <!> — read its own log, or stop it yourself.`),QT=P(`<div class="divider-msg compacting"title="the harness is compressing old turns into notes so work can continue within the context window">🗜 `),$T=P(`<div class=muted style=display:grid;place-items:center;height:100%><span><span class=spinner aria-hidden=true></span> loading timeline…`),eE=P(`<div class=muted style=display:grid;place-items:center;height:100%>no events yet — say something or press ▶ start`),tE=P(`<div class="content muted">thinking…`),nE=P(`<div class=lightbox role=dialog aria-modal=true aria-label="enlarged image"title="click to close"><img alt>`),rE=P(`<span>⌨ <button class=tabx title="close this shell">✕`),iE=P(`<div><b class=mono></b><span class=muted>`),aE=P(`<div class=cmdrow><b>@</b><span class=muted>`),oE=P(`<span class=imgchip><img title="click to enlarge"><button type=button class=imgx title=remove>✕`),sE=P(`<span class=muted style=text-transform:none;letter-spacing:0>· <!> models`),cE=P(`<h3 title="switch provider/model live — applies from the agent's next turn">🧦 model`),lE=P(`<div style=display:flex;gap:6px;align-items:center;margin-top:6px><label class=muted style=font-size:11.5px;white-space:nowrap>effort</label><select style=flex:1;min-width:0><option value>provider default`),uE=P(`<div class=meta style=color:var(--fg)>`),dE=P(`<div class=modelbox><select title="provider (OpenAI-compatible endpoint)"></select><div style=display:flex;gap:4px><input type=text list=model-list style=flex:1;min-width:0><datalist id=model-list></datalist></div><div style=display:flex;gap:6px;align-items:center;margin-top:6px><button title="apply the provider, model and effort above to this session — takes effect from the agent's next turn"style=flex:1>apply</button></div><div class=meta>current: `),fE=P(`<span>`),pE=P(`<h3 title="what the agent is working toward. Stored with the session; the agent reads it via get_goal(). Auto-continue keeps looping while the status is 'active' and stops when marked done.">🎯 goal`),mE=P(`<div class=statrow style=margin-bottom:6px><span class=k>status`),hE=P(`<div class="card goalcard"><div class=content>`),gE=P(`<form style=display:flex;flex-direction:column;gap:6px;margin-top:8px;margin-bottom:6px><textarea id=goal-input rows=3 placeholder="set new goal…"title="drag the bottom edge to make this taller — the height is remembered"style="background:var(--bg-darkest);border:none;border-radius:6px;padding:6px 8px;color:var(--fg);font:inherit;width:100%;resize:vertical"></textarea><textarea id=goal-verify-input rows=2 placeholder="verification contract (optional) — e.g. 'npm test passes; endpoint documented'. finish(goalComplete=true) is then audited against this."title="pi-goal-x-style verification contract — an independent reviewer checks the agent's finish against these requirements"style="background:var(--bg-darkest);border:1px solid var(--bg-light);border-radius:6px;padding:6px 8px;color:var(--fg);font:inherit;font-size:12.5px;width:100%;resize:vertical"></textarea><div style=display:flex;justify-content:flex-end;align-items:center;gap:10px><label class=muted title="auto-continue acts on the GOAL above: it fires after a round ONLY when all hold — ① this toggle is on ② a goal is set and its status is 'active' ③ the round ended cleanly (no error / not stopped). It stops when the goal is marked done, or if you press ■ stop."style=display:flex;align-items:center;gap:4px;font-size:11.5px;white-space:nowrap;cursor:pointer><input type=checkbox>auto-continue</label><label class=muted title="queue a harness prompt telling the agent about the new goal at its next turn boundary"style=display:flex;align-items:center;gap:4px;font-size:11.5px;white-space:nowrap;cursor:pointer><input id=goal-notify type=checkbox> notify agent</label><button type=submit class=primarybtn>✓ save goal`),_E=P(`<span class=badge>/<!> done`),vE=P(`<h3 title="todo.md — a shared checklist in the session dir. Write tasks like '- [ ] fix login'; the agent ticks them off via set_todo, you edit here. With notify on, it's told at its next turn boundary.">✅ tasks`),yE=P(`<div class=bartrack style=margin-bottom:6px><div>`),bE=P(`<div style=display:flex;justify-content:flex-end;align-items:center;gap:10px;margin-top:4px><label class=muted title="queue a harness prompt telling the agent the task list changed"style=display:flex;align-items:center;gap:4px;font-size:11.5px;white-space:nowrap;cursor:pointer><input id=todo-notify type=checkbox checked> notify agent</label><button class=okbtn>✓ save tasks`),xE=P(`<h3 title="latest report_progress snapshot. The harness asks for one after real activity (time AND output gates); errors show under ⚠ problems">📈 progress`),SE=P(`<h3 title="context is how much of the model's window the live conversation occupies. Past the threshold, the oldest turns are summarized into notes so work can continue.">📊 runtime`),CE=P(`<div class=rtcell><span>cost</span><b>$`),wE=P(`<div class=rtcell><span>cached</span><b>%`),TE=P(`<div class="card runcard"><div class=rtgrid><div class=rtcell title="prompt tokens billed this session"><span>tokens in</span><b></b></div><div class=rtcell title="completion tokens billed this session"><span>tokens out</span><b></b></div><div class=rtcell title="assistant turns this session"><span>turns</span><b></b></div><div class=rtcell title="tool calls this session"><span>tools</span><b></b></div><div class=rtcell><span>compacted</span><b>`),EE=P(`<div class=muted style=font-size:11px;text-transform:none;letter-spacing:0>showing <b></b> and the history it inherited before forking`),DE=P(`<h3>🌿 branches <span class=muted style=text-transform:none;letter-spacing:0>· click to filter the feed`),OE=P(`<span class=muted style=text-transform:none;letter-spacing:0>· <!> · all agents`),kE=P(`<h3 title="cron tasks, all agents — click a row to open that agent. Edit them in ⚙️ settings → scheduled tasks.">⏰ schedule`),AE=P(`<option>`),jE=P(`<span class=badge title="no goal set yet">no goal`),ME=P(`<button>`),NE=P(`<div class="card muted">no goal yet — write one below and press ✓ save. Then ▶ start (or any message) sets it in motion.`),PE=P(`<div class=muted>none yet`),FE=P(`<div class=progrow><b>recent</b><span class="content inline-md">`),IE=P(`<div class="progrow warn"><b>⚠ problems</b><span class="content inline-md">`),LE=P(`<div class=progrow><b>next</b><span class="content inline-md">`),RE=P(`<div class=progrow><b>goal</b><span>`),zE=P(`<div class="card prog"><div class=progrow><b>doing</b><span class="content inline-md"></span></div><div class="meta muted">`),BE=P(`<div class=statrow><span class=k>context</span><span class=muted>no window known for this model yet`),VE=P(`<span>% of `),HE=P(`<div class=bartrack><div>`),UE=P(`<div class=statrow title="a compaction pass is running right now — the summarizer's output streams in the timeline"><span class=k>🗜</span><b>compacting…</b><span class=muted style=font-size:11px;color:var(--acc)>`),WE=P(`<div class=ctxblock title="estimated live context vs the model's real window. Past the window, old turns are summarized into notes (compaction); the compact line below shows where that starts."><div class=statrow><span class=k>context</span><b>~<!> tok</b></div><div class=statrow style=margin-top:4px><span class=k>compact at</span><b> tok</b><span class=muted style=color:var(--dim)></span></div><div class=ctrlrow style=margin-top:6px><label title="when on, older turns are automatically summarized when context exceeds the budget"><input type=checkbox>auto-compact`),GE=P(`<div><span></span><span> events`),KE=P(`<div class=muted>no scheduled tasks — add them in ⚙️ settings ("scheduled tasks")`),qE=P(`<span title="runs on a forked branch so chatter stays off the main line">⑂`),JE=P(`<div><div class=sched-top><b></b><span class=muted>@</span></div><div class=sched-meta> → next </div><div class="sched-prompt muted">`),YE=P(`<div class=muted style=padding:10px>nothing yet — progress, finishes, questions and errors will land here`),XE=P(`<div class=nbody>`),ZE=P(`<div><div class=nhead><span class=nicon></span><span class=ntitle></span><span class="meta muted"></span><button class="iconbtn nreadbtn">`),QE=P(`<div style=font-size:12.5px;color:var(--dim)> event(s) came after this prompt and will be discarded — the new branch starts from your edited text.`),$E=P(`<form style=display:flex;flex-direction:column;gap:10px><textarea id=edit-text class="mono w100"rows=6></textarea><div style=display:flex;justify-content:flex-end;gap:8px><button type=button>cancel</button><button type=submit class=primarybtn>⑂ fork & resend`),eD=P(`<span style=color:var(--err);font-size:13px>`),tD=P(`<form style=display:flex;flex-direction:column;gap:10px><label>workspace directory<div style=display:flex;gap:6px><input type=text class="w100 mono"><button type=button>go</button><button type=button title="parent directory">↑</button></div></label><div class=dirlist></div><div style=display:flex;gap:10px><label style=flex:1>agent name <input type=text placeholder="(directory name)"></label><label style="flex:0 1 auto;min-width:0">provider<select></select></label><label style=flex:1>model <input type=text placeholder="(provider default)"></label></div><button type=submit style=align-self:flex-end>create`),nD=P(`<div class=direntry>📁 `),rD=[`minimal`,`low`,`medium`,`high`],iD=1100,[aD,oD]=y(``),sD,cD=e=>{oD(e),clearTimeout(sD),sD=setTimeout(()=>oD(``),3200)},lD=!1,uD=new Set([`user`,`message`,`prompt`,`tool_call`,`tool_result`,`progress`,`state`,`error`,`fork`,`goal`,`todo`,`question`,`decision`,`compaction`,`audit_step`,`system_note`]),dD=new Set([`system_note`]),fD=new Set([`user`,`message`,`prompt`,`tool_call`,`tool_result`,`progress`,`error`,`fork`,`goal`,`todo`,`question`,`decision`,`compaction`,`audit_step`]),pD=new Set([`runaway-detected`,`error-retry`,`background-exit`,`context-compacted`,`context-compaction-started`]),mD=location.hash.match(/[#&]token=([^&]+)/);mD&&(localStorage.setItem(`teapot.token`,decodeURIComponent(mD[1])),history.replaceState(null,``,location.pathname+location.search));var hD=()=>{let e=localStorage.getItem(`teapot.token`);return e?`?token=${encodeURIComponent(e)}`:``};function gD(){let[e,t]=y([]),[n,r]=y(null),[i,a]=y(``),[o,s]=y(new Map),[c,l]=y(new Map),[u,d]=y(new Map),f=!1,p=null;async function m(e=!1){if(p)return p;if(f&&!e)return;let t=(async()=>{try{let e=await Y(`/api/sessions`),t=new Map,n=new Map,r=new Map;for(let i of e.sessions??[]){t.set(i.id,i.agentId),typeof i.title==`string`&&i.title&&r.set(i.id,i.title);let e=n.get(i.agentId)??[];e.push(i.id),n.set(i.agentId,e)}s(t),l(n),d(r),f=!0}catch{}})();p=t;try{await t}finally{p===t&&(p=null)}}let[h,g]=y([]),[_,v]=y(0),[ee,te]=y([]),[E,D]=y(null),ne=new Map,[re,ie]=y(ne.get(n()??``)??``),O=e=>{ie(e);let t=n();t&&(e?ne.set(t,e):ne.delete(t))},[ae,oe]=y({providers:{}}),[se,ce]=y(!1),le=()=>mr({want:gr({preview:zt(),auto:Ft(),prefersLight:Kt(),dark:Ut(),light:Lt(),fixed:Nt()}),customIds:Vt().map(e=>e.id),presetIds:$d.map(e=>e.key),fallback:`dark`}),ue=()=>le().active,de=()=>Vt().find(e=>e.id===ue())?.backgroundImage??``,[fe,pe]=y(!1),k=!1;x(()=>{!k&&ae()?.needsSetup&&(k=!0,requestAnimationFrame(()=>{fi(),pe(!0)}))}),x(()=>{fe()&&!Bo()&&Y(`/api/features`).then(e=>Vo(e)).catch(()=>Vo(null))});let me=new Set,he=()=>window.innerWidth<=iD,[ge,_e]=y(he());w(()=>{let e=()=>{let e=he();e!==ge()&&(_e(e),(localStorage.getItem(yt(e))!==null||!e)&&St(bt(e)))};window.addEventListener(`resize`,e),T(()=>window.removeEventListener(`resize`,e)),e()});let ve=0,ye=null,be=0,xe,Se,Ce=0,we=0,Te=0,Ee=()=>{if(performance.now()<Ie){if(performance.now()<Te)return;let e=ma();e&&Ue(e);return}if(qn()||!ye)return;let e=ma();if(!e)return;if(!Qe(performance.now(),we)||e.scrollHeight===$o){ye=vt(e),be=performance.now();return}if(!P(e))return;let t=e.scrollHeight;tt(e,ye,ts),$o=e.scrollHeight,t!==$o&&(Qo={top:e.scrollTop,height:e.scrollHeight})},P=e=>{if(!ye)return!1;let t=vt(e);return t?t.sel===ye.sel||(ye=t,be=performance.now(),!1):!1},De=()=>{Ce||=requestAnimationFrame(()=>{Ce=0,Ee()})},Me,Ne,Pe=0,Fe=``,Ie=0,Le=!0,Re=e=>{Le=e,qn()!==e&&Jn(e)},Be=0,Ve=()=>{if(Be=0,performance.now()>=Ie)return;if(performance.now()<Te){Be=requestAnimationFrame(Ve);return}let e=ma();e&&Ge({top:e.scrollTop,height:e.scrollHeight,viewport:e.clientHeight})>1&&Ue(e),Be=requestAnimationFrame(Ve)},He=(e=1500)=>{Ie=performance.now()+e,Be||=requestAnimationFrame(Ve)},Ue=e=>{e.scrollTop=e.scrollHeight,Qo={top:e.scrollTop,height:e.scrollHeight},Jn(!0),tr(0),ye=vt(e),be=performance.now()},We=0,et=()=>{Pe=0;let e=ma();if(!e)return;let t=e.scrollHeight!==$o;$o=e.scrollHeight,ns=e.clientHeight;let n=e.clientWidth!==We;We=e.clientWidth,!n&&(qn()||performance.now()<Ie)?_a():n&&(Le||performance.now()<Ie)?(_a(),ir(ha())):n?((Le||performance.now()<Ie)&&_a(),ir(ha())):t?Qe(performance.now(),we)?(P(e)&&tt(e,ye,es),ir(ha())):(ye=vt(e),be=performance.now(),ir(ha())):(ye||(ye=vt(e),be=performance.now()),ir(ha()))};function tt(e,t,n=es){if(!t)return;let r=e.querySelector(t.sel);if(!r)return;let i=r.getBoundingClientRect().top-t.top;Math.abs(i)<1||Math.abs(i)>n||(e.scrollTop+=i,Qo={top:e.scrollTop,height:e.scrollHeight})}let st=()=>{Pe||=requestAnimationFrame(et)},ct=null,lt=e=>{ct?.();let t=e=>{Un(e.deltaY)&&(Te=performance.now()+400,Re(!1))},n=()=>{Te=performance.now()+400,Re(!1)},r=t=>{let r=t.target;if(r&&typeof r.closest==`function`&&r.closest(`textarea, input, select, [contenteditable=''], [contenteditable='true']`))return;let i=!!r&&typeof e.contains==`function`&&e.contains(r),a=!r||r===document.body||r===document.documentElement;(i||a)&&Wn(t.key)&&n()};e.addEventListener(`wheel`,t,{passive:!0}),e.addEventListener(`touchmove`,n,{passive:!0}),window.addEventListener(`keydown`,r,{capture:!0}),ct=()=>{e.removeEventListener(`wheel`,t),e.removeEventListener(`touchmove`,n),window.removeEventListener(`keydown`,r,{capture:!0}),ct=null}},ut=e=>{e&&(lt(e),e!==Ne&&(Me??=new ResizeObserver(e=>{let t=e[0]?.contentRect,n=t?`${Math.round(t.width)}x${Math.round(t.height)}`:``;n!==Fe&&(Fe=n,st())}),Ne&&Me.unobserve(Ne),Ne=e,Fe=``,Me.observe(e),typeof MutationObserver<`u`&&(xe??=new MutationObserver(De),Se&&Se!==e&&Se.removeEventListener(`load`,De,!0),Se=e,xe.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),e.addEventListener(`load`,De,!0))))};w(()=>{window.addEventListener(`resize`,st),T(()=>{window.removeEventListener(`resize`,st),Me?.disconnect(),Me=void 0,Ne=void 0,xe?.disconnect(),xe=void 0,Se&&Se.removeEventListener(`load`,De,!0),Se=void 0,Ce&&cancelAnimationFrame(Ce),Pe&&cancelAnimationFrame(Pe)})});let pt=e=>`[data-eid="${globalThis.CSS?.escape?.(e)??e.replace(/["\\]/g,`\\$&`)}"]`;function vt(e){let t=e.querySelectorAll(`[data-eid]`);if(!t.length)return null;let n=e.getBoundingClientRect().top,r=e=>t[e].getBoundingClientRect(),i=0,a=t.length-1,o=-1;for(;i<=a;){let e=i+a>>1;r(e).bottom>n?(o=e,a=e-1):i=e+1}if(o<0)return null;let s=t[o].dataset.eid??``;return s?{sel:pt(s),top:r(o).top}:null}let yt=e=>e?`teapot.panel.narrow`:`teapot.panel`,bt=e=>{let t=localStorage.getItem(yt(e));return t===null?!e:t===`1`},[xt,St]=y(bt(he())),Ct=e=>{St(e),localStorage.setItem(yt(ge()),e?`1`:`0`)},Tt=()=>Ct(!xt()),Et=()=>{xt()&&Ct(!1)},[At,jt]=y(!1),Mt=()=>jt(!1),[Nt,Pt]=y(localStorage.getItem(`teapot.theme`)??`dark`),[Ft,It]=y(localStorage.getItem(`teapot.theme.auto`)===`1`),[Lt,Rt]=y(localStorage.getItem(`teapot.theme.light`)??`light`),[zt,Bt]=y(null),[Vt,Ht]=y(sr());w(()=>{lr().then(e=>{if(e===null)return;let t=sn(Vt(),e);Ht(t),cr(t)})});let[Ut,Wt]=y(localStorage.getItem(`teapot.theme.dark`)??`dark`),Gt=typeof window.matchMedia==`function`?window.matchMedia(`(prefers-color-scheme: light)`):null,[Kt,qt]=y(Gt?.matches??!1);w(()=>{let e=e=>qt(e.matches);Gt?.addEventListener(`change`,e);let t=()=>{if(document.visibilityState!==`visible`)return;let e=Gt?.matches??!1;e!==Kt()&&qt(e)};document.addEventListener(`visibilitychange`,t),T(()=>{Gt?.removeEventListener(`change`,e),document.removeEventListener(`visibilitychange`,t)})}),x(()=>{let{active:e,repaired:t}=le(),n=Vt().find(t=>t.id===e)??null;t&&(Ft()?localStorage.setItem(Kt()?`teapot.theme.light`:`teapot.theme.dark`,e):localStorage.setItem(`teapot.theme`,e)),document.documentElement.dataset.theme=e,dr(document.documentElement,n),document.documentElement.dataset.appearance=n?.mode??$d.find(t=>t.key===e)?.mode??`dark`});let[Jt,Xt]=y(``),[Qt,$t]=y(``),[en,tn]=y(``);x(()=>{let t=n();tn(C(()=>e().find(e=>e.id===t)?.reasoningEffort??``))});let[nn,rn]=y([]),ln=()=>Object.keys(ae().providers??{});async function un(e){if(e)try{let t=await Y(`/api/models?provider=${encodeURIComponent(e)}`);rn(t.models??[])}catch{rn([])}}let dn=e=>{let t={text:`📄`,image:`🖼️`,audio:`🔊`,video:`🎬️`,file:`📎`},n=e=>(e??[`text`]).map(e=>t[e]??e).join(``);return e?.modalities?`${n(e.modalities.input)} → ${n(e.modalities.output)}`:``},hn=()=>{let e=Qt().trim()||B()?.model||``;if(!e)return``;let t=nn().find(t=>t.id===e);if(!t)return``;let n=[],r=dn(t);r&&r!==`📄 → 📄`&&n.push(r),t.contextLength&&n.push(`ctx ${Hx(t.contextLength)} tok`);let i=e=>e===void 0?``:`${e*1e6>=10?Math.round(e*1e6):+(e*1e6).toFixed(1)}/M`;if(t.pricing){let e=i(t.pricing.prompt),r=i(t.pricing.completion);e&&r?n.push(`${e} in · ${r} out`):(e||r)&&n.push(i(t.pricing.prompt??t.pricing.completion))}return n.join(` · `)},Dn=null,jn=!1;x(()=>{let t=n();if(!t)return;let r=e().find(e=>e.id===t),i=r?.provider||ae().defaultProvider||ln()[0]||``;if(r){if(t!==Dn)Dn=t,jn=!1,C(()=>Jt())!==i&&(Xt(i),un(i)),C(()=>Qt())&&$t(``);else{let e=C(()=>Jt());!C(()=>Qt())&&e!==i&&zn(jn)&&(Xt(i),un(i))}}});let[Pn,In]=y(!1),[qn,Jn]=y(!0),Yn,[Xn,tr]=y(0),[nr,rr]=y(-1),ir=e=>rr(e?Ze(e):-1),[ar,or]=y(null),ur=()=>R().startsWith(`[compact] `),fr=()=>{let e=ur()?R().slice(10):R();return e.length>1200?`…`+e.slice(-1200):e};x(()=>{ar()||vr(e=>e?.text.startsWith(`[compact] `)?null:e)}),x(()=>{h().length,_(),ar(),oi().length,ta(),$i(),U();let e=ma();if(!e)return;let t=e.scrollHeight;t!==ve&&(ve=t,requestAnimationFrame(()=>requestAnimationFrame(()=>{qn()&&(_a(),requestAnimationFrame(()=>{if(!qn())return;let t=e.scrollHeight;t!==ve&&(ve=t,_a())}))})))});let[pr,hr]=y(new Map),_r=()=>{let e=n();return e?pr().get(e)??null:null},vr=e=>{let t=n();t&&hr(n=>{let r=new Map(n),i=typeof e==`function`?e(n.get(t)??null):e;return i?r.set(t,{...i,at:Date.now()}):r.delete(t),r})},yr=()=>{let e=_r();if(!e)return;let t=Ot(e,h(),B()?.status);t?(t.text!==e.text||t.reasoning!==e.reasoning)&&vr(t):vr(null)},[R,z]=y(``),[br,xr]=y(0),Sr=()=>br(),[Cr,wr]=y(``),Tr;x(()=>{_r()?Tr||=setTimeout(()=>{Tr=void 0,z(_r()?.text??``),wr(_r()?.reasoning??``)},(_r()?.text.length??0)>2e4?250:(_r()?.text.length??0)>6e3?120:60):(clearTimeout(Tr),Tr=void 0,z(``),wr(``))}),T(()=>clearTimeout(Tr)),x(()=>{let t=e();hr(e=>Dt(e,e=>t.find(t=>t.id===e)?.status)),xr(e=>kt(e,t,n(),_r()))}),x(()=>{let e=R(),t=_r()?.reasoning??``;(e||t)&&requestAnimationFrame(()=>{qn()&&_a()})}),x(()=>{let e=B()?.pendingPrompts??0,t=B()?.pendingPromptIds,n=Ir(),r=Lr(n),i=Cn(r,e,t);i!==r&&Rr(n,i)}),x(()=>{let e=B()?.pendingPromptQueue;if(!e?.length)return;let t=B()?.session||Ir();if(xa.size){let t=new Set(e.map(e=>String(e.id??``)));for(let e of[...xa])t.has(e)||xa.delete(e)}let n=wn(Lr(t),e.filter(e=>!xa.has(String(e.id??``))));n!==Lr(t)&&Rr(t,n)}),x(()=>{if(!n())return;let e=()=>{document.visibilityState===`visible`&&requestAnimationFrame(()=>{ga()&&(Jn(!0),tr(0),va(!0),qr())})};document.addEventListener(`visibilitychange`,e),T(()=>document.removeEventListener(`visibilitychange`,e))});let B=S(()=>e().find(e=>e.id===n()));x(()=>{let e=B()?.pendingQuestionId;e&&(h().some(t=>t.id===e)||(Dr.has(e)||(Dr.add(e),pa(n(),i())),!(ta()||U())&&(async()=>{for(let t=0;t<8;t++){if(h().some(t=>t.id===e)||ta())return;if(U()){await new Promise(e=>setTimeout(e,50));continue}let t=h().length;if(await sa(),h().length===t)return}})()))});let Er=``,Dr=new Set;x(()=>{let e=B()?.pendingQuestionId;e&&e!==Er&&h().some(t=>t.id===e)&&(Er=e,Qr(e,0))});let Or=()=>er({sameSession:!(B()?.session!==Ir()&&B()?.session),echoCount:si()}),kr=()=>{let e=B();return e?e.live??(e.status===`running`||e.status===`waiting`||e.status===`needs_operator`):!1},Ar=()=>An(B(),i(),kr()),[jr,Mr]=y(null);S(()=>{let e=new Set;for(let t of h())t.type===`tool_result`&&(t.data?.name===`ask_operator`||t.data?.name===`ask_user`)&&e.add(String(t.data.callId));return e});let Nr=new Map,[Pr,Fr]=y([]),Ir=()=>i()||n()||`?`,Lr=e=>Nr.get(e)??[],Rr=(e,t)=>{let n=new Set,r=[];for(let e=t.length-1;e>=0;e--){let i=t[e],a=i.promptId;a?n.has(a)||(n.add(a),r.push(i)):r.push(i)}r.reverse(),r.length===0?Nr.delete(e):Nr.set(e,r),Ir()===e&&Fr(r)},[zr,Br]=y([]),[Vr,Hr]=y(localStorage.getItem(`teapot.hideGhosts`)===`1`),[Ur,Wr]=y(!1),Gr=()=>zr().filter(e=>!e.read).length,Kr=e=>{Br(t=>{let n=!1,r=t.map(t=>t.read||t.agentId!==e?t:(n=!0,{...t,read:!0}));return n?r:t})},qr=()=>{let e=n();e&&zr().some(t=>!t.read&&t.agentId===e)&&Kr(e)},Jr=t=>{let n=zr().filter(e=>!e.read&&e.agentId===t).length;for(let r of e())r.parent===t&&(n+=Jr(r.id));return n},Yr=0,Xr=e=>{Br(t=>[{...e,id:`n${++Yr}`,at:Date.now(),read:!1},...t].slice(0,50))},Zr=(t,n)=>{if(n.type===`system_note`&&n.data?.event===`background-exit`){let r=e().find(e=>e.id===t)?.id??t,i=n.data.failed===!0,a=Math.round(Number(n.data.durationMs??0)/1e3);Xr({agentId:t,kind:i?`error`:`progress`,title:`${r}: ${i?`⚠`:`✓`} background job ${String(n.data.jobId??`?`)} `+(i?`FAILED (exit ${String(n.data.code??`?`)})`:`finished (${a}s)`),body:String(n.data.cmd??``).slice(0,200)});return}let r=e().find(e=>e.id===t)?.id??t,i=typeof n.id==`string`?n.id:void 0;n.type===`message`&&n.data?.final===!0?Xr({agentId:t,kind:`finish`,title:`${r} finished`,body:String(n.data.content??``).slice(0,300),eventId:i}):n.type===`question`?Xr({agentId:t,kind:`question`,title:`${r} asks a question`,body:String(n.data.question??``).slice(0,300),eventId:i}):n.type===`error`?Xr({agentId:t,kind:`error`,title:`${r} hit an error`,body:String(n.data.message??``).slice(0,300),eventId:i}):n.type===`progress`&&Xr({agentId:t,kind:`progress`,title:`${r}: ${String(n.data.doing??`progress`)}`.slice(0,120),body:[n.data.recent&&`recent: ${n.data.recent}`,n.data.next&&`next: ${n.data.next}`].filter(Boolean).join(` · `).slice(0,300),eventId:i})},Qr=(e,t=0)=>{let n=i(),r=document.querySelector(pt(e)),a=!!r&&$e(r.dataset.session,n);r&&a?(r.scrollIntoView({behavior:`smooth`,block:`center`}),r.classList.add(`flash-target`),setTimeout(()=>r.classList.remove(`flash-target`),1600)):t<30&&requestAnimationFrame(()=>Qr(e,t+1))},$r=S(()=>{let e=new Map,t=new Set,n=new Map,r=new Map;for(let i of h())if(uD.has(i.type)){if(i.type===`tool_call`){let e=n.get(i.data.callId)??[];e.push(i),n.set(i.data.callId,e)}else if(i.type===`tool_result`){let a=n.get(i.data.callId)?.shift();a?(e.set(a.id,i),t.add(i.id)):r.set(i.id,i)}}return{resFor:e,consumed:t,orphanCalls:r}}),[ei,ti]=y(new Set),ni=e=>{e&&ti(t=>{if(t.has(e))return t;let n=new Set(t);return n.add(e),n})},ri=()=>ti(new Set),ii=S(()=>Sn(h(),ei())),ai=S(()=>Yt({events:h(),consumed:$r().consumed,pending:Pr().map(e=>({...e,promptId:e.promptId??e.id})),serverPendingIds:B()?.pendingPromptIds??[],echo:di,feedTypes:uD,renderedTypes:fD,renderedNoteEvents:pD})),oi=()=>ai().rows,si=()=>ai().pendingCount,ci=S(()=>{let e=new WeakMap;return oi().forEach((t,n)=>e.set(t,n)),e}),li=(e,t)=>{let n=ci().get(e);if(n!==void 0)return oi()[n+t]},ui=new Map;function di(e){let t=`${e.id}:${e.sent?`s`:`p`}:${e.promptId??``}`,n=ui.get(t);if(n)return n;ui.size>64&&ui.clear();let r={id:e.id,seq:2**53-1,ts:new Date(e.at).toISOString(),session:B()?.session??``,branch:B()?.branch??`br0`,parent:null,type:`prompt`,data:{source:e.source??`user`,text:e.text,pending:!e.sent,queued:!e.sent&&e.queued===!0,...e.images?.length?{images:e.images}:{},...e.promptId?{promptId:e.promptId}:{}}};return ui.set(t,r),r}let fi=()=>Y(`/api/config`).then(oe).catch(()=>{}),[pi,mi]=y(!1);w(()=>{let e=()=>mi(!0);window.addEventListener(`teapot:unauthorized`,e),T(()=>window.removeEventListener(`teapot:unauthorized`,e))});let[hi,gi]=y(``),[_i,vi]=y(!0),[yi,bi]=y(!1),xi=``;x(()=>{let t=n(),r=e().find(e=>e.id===t)?.todo??``;t&&t!==xi?(xi=t,bi(!1),gi(r)):t&&!yi()&&gi(r)});let Si=async()=>{let e=document.getElementById(`todo-notify`)?.checked??!0;if(n())try{await Y(`/api/agents/${n()}/todo`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({text:hi(),notify:e})}),bi(!1),vi(!0),cD(`tasks saved${e&&hi().trim()?` & notification queued`:``}`),Ti()}catch(e){cD(`save failed: ${e.message}`)}},Ci=S(()=>{let e=0,t=0;for(let n of hi().split(`
183
- `)){let r=n.match(/^\s*[-*+] \[([ xX])\]/);r&&(e++,r[1].toLowerCase()===`x`&&t++)}return{total:e,done:t}});function wi(e,t){let n=new Map(e.map(e=>[e.id,e]));return t.map(e=>{let t=n.get(e.id);return t&&JSON.stringify(t)===JSON.stringify(e)?t:e})}let Ti=()=>Y(`/api/agents`).then(e=>{let n=!1;t(t=>(t.length!==(e.agents??[]).length&&(n=!0),(e.agents??[]).some(e=>!t.some(t=>t.id===e.id))&&(n=!0),wi(t,e.agents??[]))),n&&m()}).catch(()=>{}),Ei=()=>Y(`/api/metrics`).then(D).catch(()=>{}),[Di,Oi]=y([]),ki=()=>Y(`/api/tasks`).then(e=>Oi(e.tasks)).catch(()=>{}),Ai=e=>Di().filter(t=>t.agent===e),[V,ji]=y((()=>{try{let e=JSON.parse(localStorage.getItem(`teapot.expandedSubs`)??`[]`);return new Set(e.filter(e=>typeof e==`string`))}catch{return new Set}})()),[Mi,H]=y((()=>{try{let e=JSON.parse(localStorage.getItem(`teapot.collapsed`)??`[]`);return new Set(e.filter(e=>typeof e==`string`&&!e.startsWith(`chat:`)))}catch{return new Set}})()),Ni=e=>Mi().has(e)||!V().has(e),Pi=e=>{let t=new Set(V());if(t.has(e)?t.delete(e):t.add(e),ji(t),localStorage.setItem(`teapot.expandedSubs`,JSON.stringify([...t])),t.has(e)&&Mi().has(e)){let t=new Set(Mi());t.delete(e),H(t),localStorage.setItem(`teapot.collapsed`,JSON.stringify([...t]))}},Fi=t=>yn(e(),t),[Ii,Li]=y((()=>{try{let e=JSON.parse(localStorage.getItem(`teapot.wsCollapsed`)??`[]`),t=Array.isArray(e)?e.filter(e=>typeof e==`string`):[];if(Number(localStorage.getItem(`teapot.wsCollapsed.v`)??`0`)<2){let e=t.filter(e=>!e.startsWith(`chat:`));return t.length-e.length>0&&localStorage.setItem(`teapot.wsCollapsed`,JSON.stringify(e)),localStorage.setItem(`teapot.wsCollapsed.v`,`2`),new Set(e)}return new Set(t)}catch{return new Set}})()),Ri=S(()=>{let e=new Set;for(let t of Ii())t.startsWith(`chat:`)&&e.add(t);return e}),zi=S(()=>mn(e(),new Set(e().filter(e=>Ni(e.id)).map(e=>e.id)),Vr(),Ri())),Bi=(t,r,i,a)=>{let o=new Set(Ii());if(i)o.delete(t),a&&o.delete(a);else{o.add(t),a&&o.delete(a);let i=n();i&&(t===`chat:${i}`||Fi(e().find(e=>e.id===i))===t)&&cD(`hid ${r} — click the header to show it`)}Li(o);try{localStorage.setItem(`teapot.wsCollapsed`,JSON.stringify([...o]))}catch{}},Vi=e=>e.replace(/\/+$/,``).split(/[/\\]/).pop()||e,Hi=e=>{let t=Ui().get(e)??0;return`${t} chat${t===1?``:`s`}`},Ui=S(()=>bn(e())),Wi=S(()=>xn(e(),zi(),Ii())),[Gi,Ki]=y(null),qi=new Map,Ji=()=>{g([]),qi.clear(),Yi=0},Yi=0;function Xi(e){return`${i()||(n()??`?`)}:${e.id}`}function Zi(e){let t=Array.from({length:e.length});for(let n=0;n<e.length;n++){let r=e[n],i=Xi(r),a=qi.get(i);if(t[n]=a??r,!a)for(qi.set(i,r),Yi+=wa(r);qi.size>4e3||Yi>8388608;){let e=qi.keys().next().value;if(e===void 0)break;let t=qi.get(e);t&&(Yi-=wa(t)),qi.delete(e)}}return t}let[U,Qi]=y(!1),[$i,ea]=y(!1),[ta,na]=y(!1),ra=0,ia=-1;function aa(e){let t=Zi(e);g(e=>{if(t.length>0&&e.length>0){let n=e[e.length-1],r=t.every(e=>e.seq>n.seq),i=new Set(e.map(e=>e.id));if(r&&t.every(e=>!i.has(e.id)))return[...e,...t]}let n=new Map;for(let t of e)n.set(t.id,t);let r=!1;for(let e of t)n.has(e.id)||(n.set(e.id,e),r=!0);return r?[...n.values()].sort((e,t)=>e.seq-t.seq):e})}async function oa(){let e=n();if(!e||ta()||U()||qn())return;if(h().length>=_()){na(!0);return}let t=()=>{let e=ma();return e&&e.clientHeight>0?e:null},r=0;for(;r++<20&&!ta()&&n()===e;){let r=t();if(r&&r.scrollHeight>r.clientHeight+40)return;if(h().length>=_()){na(!0);return}let i=h().length;if(await sa(),h().length===i)return;Ke(ha())&&n()===e&&va(!0)}}async function sa(){let e=n(),t=h()[0];if(e&&t&&!U()&&!ta()){Qi(!0);try{let r=ma(),a=r?.scrollHeight??0,o=r?.scrollTop??0,s=Gi(),c=i(),l=(await Y(la(e,{before:t.id},c,s))).events??[];if(l.length===0){na(!0);return}if(n()!==e||h()[0]?.id!==t.id)return;aa(l),requestAnimationFrame(()=>{if(n()===e){let e=ma();e&&(e.scrollTop=o+(e.scrollHeight-a))}})}catch{}finally{Qi(!1)}}}function ca(e,t){return t&&o().has(t)?`&session=${encodeURIComponent(t)}`:``}function la(e,t,n,r){let i=[`/api/agents/${encodeURIComponent(e)}/events?limit=2000`];t.before&&i.push(`&before=${encodeURIComponent(t.before)}`),t.after&&i.push(`&after=${encodeURIComponent(t.after)}`);let a=ca(e,n);return a&&i.push(a),r&&i.push(`&branch=${encodeURIComponent(r)}&lineage=true`),i.join(``)}let ua=!1,[da,fa]=y(!1);async function pa(e,t){let r=ra,a=t??i()??``;try{let t=Gi(),i=r!==ia||!ee().length;h().length||ea(!0),Y(`/api/agents/${e}/skills`).then(t=>{r===ra&&n()===e&&zo(t.skills??[])}).catch(()=>{});let[o,s]=await Promise.all([Y(la(e,{},a,t)),i?Y(`/api/agents/${e}/branches`):Promise.resolve({branches:ee()})]);if(i&&(ia=r),r!==ra||n()!==e)return;if(ua){ua=!1,qi.clear(),g(Zi(o.events)),fa(!1);let t=ma();t&&((ba.get(a)??ba.get(e))||(t.scrollTop=t.scrollHeight))}else g(e=>{let t=new Map;for(let n of e)t.set(n.id,n);for(let e of Zi(o.events))t.set(e.id,e);return[...t.values()].sort((e,t)=>e.seq-t.seq)});v(o.total??o.events.length),te(s.branches)}catch{ua&&(ua=!1,fa(!1),Ji())}finally{ea(!1)}}function ma(){return document.querySelector(`.feed`)}function ha(){let e=ma();return e?{top:e.scrollTop,height:e.scrollHeight,viewport:e.clientHeight}:null}function ga(){return Ke(ha())}function _a(){let e=ma();if(!e)return;let t=()=>e.isConnected?(e.scrollTop=e.scrollHeight,Qo={top:e.scrollTop,height:e.scrollHeight},!0):!1;if(!t())return;tr(0);let n=r=>{e.isConnected&&qn()&&(Xe(qn(),{top:e.scrollTop,height:e.scrollHeight,viewport:e.clientHeight})&&t(),r>0&&requestAnimationFrame(()=>n(r-1)))};requestAnimationFrame(()=>n(2)),Yn&&clearTimeout(Yn),Yn=setTimeout(()=>n(0),250)}function va(e=!1){(e||qn())&&_a()}let ya=new Map,ba=new Map,xa=new Set,Sa=(e,t=0,n=!1)=>{let r=n?e.getBoundingClientRect().top:-1/0,i=[];for(let a of e.querySelectorAll(`[data-eid]`)){let e=a.getBoundingClientRect();if(i.push({eid:a.dataset.eid??``,session:a.dataset.session??``,top:e.top+t,height:e.height}),n&&e.top>r+4)break}return i},Ca=8388608,wa=e=>ot(e),Ta=(t,n)=>En(c().get(t),e().find(e=>e.id===t)?.session,n);async function Ea(e,t=!0,s){let l=n(),u=i(),d=h(),f=_();ra++,c().size||m();let p=Ta(e,s),ee=s&&o().has(s)?s:null,y=p??ee??``;if(l!==e||y!==u){if(u&&d.length){let e=d.reduce((e,t)=>e+wa(t),0);e<=Ca&&ya.set(u,{events:d,total:f,at:Date.now(),bytes:e}),at(ya,{maxEntries:6,maxBytes:Ca})}{let e=ma();if(fa(!0),e){let t=Sa(e,0,!0),n=t.filter(e=>!e.eid.startsWith(`@p`)),r=u||t.find(e=>e.session)?.session||``,i={top:e.scrollTop,height:e.scrollHeight,viewport:e.clientHeight},a=r?Gn(n.length?n:t,e.getBoundingClientRect().top,r):null;a&&Ge(i)>1?ba.set(r,a):r&&ba.delete(r)}}ri(),ua=!0,ya.get(y)?.events.length||Ji(),fa(!0),or(null),tr(0),Jn(!0),Zo=void 0}r(e),a(y),O(ne.get(e)??``),Ki(null),na(!1),Qi(!1),Rr(u||l||`?`,Pr()),Fr(Lr(y||e)),localStorage.setItem(`teapot.session`,e),Ra(y,t);let b=ya.get(y);if(b?.events.length&&(g(Zi(b.events)),v(b.total),ea(!0),requestAnimationFrame(()=>{n()===e&&va(!0)})),Y(`/api/agents/${e}/load`,{method:`POST`}).then(Ti).catch(()=>{}),await pa(e,y),n()!==e)return;hr(t=>{let n=t.get(e)??null,r=Ot(n,h(),B()?.status);if(r===n)return t;let i=new Map(t);return r?i.set(e,r):i.delete(e),i}),or(B()?.ctx?.compacting?{phase:String(B().ctx.compacting)}:null),Jn(!0);let x=ra;He(3e3);let S=performance.now()+3e3,C=()=>{if(n()!==e||x!==ra||performance.now()<Te)return;let t=ma();t&&Ue(t),performance.now()<S&&requestAnimationFrame(C)},w=()=>{let t=ba.get(y)??ba.get(e);if(!t)return`give-up`;let r=ma();if(!r)return`wait`;let i=Sa(r,r.scrollTop);if(!i.length)return`wait`;let a=Kn(t,i,r.scrollHeight-r.clientHeight);if(a===null)return ba.delete(y),ba.delete(e),`give-up`;r.scrollTop=a,Jn(!1),Te=performance.now()+400,Ie=0,ba.delete(y),ba.delete(e);let o=()=>{let e=ma();if(!e)return null;for(let n of e.querySelectorAll(`[data-eid]`))if(n.dataset.eid===t.eid&&n.dataset.session===t.session)return n;return null},s=r=>{if(n()!==e)return;let i=ma();if(!i)return;let a=o();if(!a)return;let c=i.getBoundingClientRect().top-t.offset,l=a.getBoundingClientRect().top-c;Math.abs(l)<2||r<=0||(i.scrollTop+=l,requestAnimationFrame(()=>s(r-1)))};return requestAnimationFrame(()=>s(6)),`applied`};(async()=>{if(await oa(),n()!==e||x!==ra)return;let t=performance.now()+1500,r=()=>{if(n()!==e||x!==ra)return;let i=w();i!==`applied`&&(i===`wait`&&performance.now()<t?requestAnimationFrame(r):requestAnimationFrame(C))};requestAnimationFrame(r)})()}let[Da,Oa]=y(!1),ka=null,Aa=null;T(()=>ka?.close());let ja=!1,Ma=null;document.addEventListener(`visibilitychange`,()=>Ma?.()),T(()=>{Ma=null});let Na=!0,Pa=null;async function Fa(){let e=n(),t=h().at(-1)?.id,r=i(),a=document.visibilityState===`hidden`;if(!e||!t)ja=!0,a||Pa?.();else try{let n=Gi(),i=await Y(la(e,{after:t},r,n)),o=i.events??[];i.gap?(g(Zi(o)),v(o.length)):o.length&&(aa(o),v(e=>e+o.length)),await Ti(),o.length&&!a&&Ei()}catch{ja=!0}}function Ia(){Na=!0;let r=location.protocol===`https:`?`wss://`:`ws://`,a=new WebSocket(`${r}${location.host}/api/ws${hD()}`);ka=a,a.onopen=()=>{Oa(!0),Na?Na=!1:Fa()},a.onclose=()=>{Oa(!1),setTimeout(Ia,1500)},a.onerror=()=>a.close();let o=new Set([`state`,`usage`,`session_start`]);a.onmessage=r=>{let s=JSON.parse(r.data);if(s.kind===`ping`)try{a.send(JSON.stringify({kind:`pong`}))}catch{}else if(s.kind!==`pong`){if(s.kind===`hello`&&Array.isArray(s.agents)){t(e=>wi(e,s.agents));let n=e();hr(e=>Dt(e,e=>n.find(t=>t.id===e)?.status))}else if(s.kind===`event`&&_t(s.event)&&hr(e=>gt(e,s.agentId)),s.kind===`llm-delta`){if(!kn(s,n(),i()))return;if(hr(e=>ht(e,s.agentId,s)),s.agentId===n()){let e=String(s.reasoning??``),t=String(s.text??``);e&&!t?br()||xr(Date.now()):t&&xr(0)}}else if(s.kind===`terminal-closed`&&s.terminalId)to(e=>{let t=e.findIndex(e=>e.key===s.terminalId);return t<0?e:(cD(s.reason===`idle`?`a terminal was closed after being idle — open a new shell with +`:`a terminal exited`),e.filter((e,n)=>n!==t))});else if(s.kind===`compaction-progress`){if(s.agentId!==n())return;s.phase===`done`?or(null):or({phase:s.phase,summarized:s.summarized})}else if(s.kind===`agent-update`&&s.snapshot)t(e=>{let t=e.findIndex(e=>e.id===s.snapshot.id),n=s.snapshot;return t===-1?[...e,n]:wi(e,e.map((e,n)=>n===t?s.snapshot:e))});else if(s.kind===`metrics`&&s.metrics)D(s.metrics);else if(s.kind===`tasks`&&Array.isArray(s.tasks))Oi(s.tasks);else{if(s.kind===`event`){let e=s.event?.type,t=s.event?.data??{};if(e===`system_note`&&(t.event===`prompt-delivered`||t.event===`prompt-cancelled`)){let e=String(t.promptId??``);if(e){let t=String(s.event?.session??``),n=new Set;t&&n.add(t),n.add(Ir());for(let[t,r]of Nr)r.some(t=>t.promptId===e)&&n.add(t);for(let t of n){let n=Lr(t);n.some(t=>t.promptId===e)&&Rr(t,n.filter(t=>t.promptId!==e))}}}if(o.has(e)&&!dD.has(e)||(Zr(s.agentId,s.event),!On(s.event,n(),i()))||(aa([s.event]),s.event&&yr(),ja=!0,document.visibilityState!==`visible`))return;c()}document.visibilityState===`hidden`?ja=!0:c()}}};let s=0;function c(){s||=requestAnimationFrame(()=>{s=0,Aa&&=(clearTimeout(Aa),null),l()})}ja=!1;let l=async()=>{if(Aa=null,n()){let e=h().at(-1)?.id,t=h().length,r=_r();r&&!Ot(r,h(),B()?.status)&&vr(null),h().at(-1)?.id!==e&&(qn()?(_a(),Kr(n())):(tr(e=>e+Math.max(0,h().length-t)),ir(ha())))}};Pa=l,Ma=()=>{document.visibilityState===`visible`&&(Ei(),ki(),n()&&(ja?(ja=!1,l()):h().at(-1)?.id?Fa():(ja=!0,l())))}}let La=()=>decodeURIComponent(location.pathname.split(`/`)[2]??``);function Ra(e,t=!0){if(!e)return;let n=`/session/${encodeURIComponent(e)}`;t?history.pushState(null,``,n):history.replaceState(null,``,n)}window.addEventListener(`popstate`,()=>{let e=La(),t=o().get(e);t&&(t!==n()||e!==i())&&Ea(t,!1,e||null)}),x(()=>{let e=B(),t=e?`${kr()?`▶ `:e.status===`error`?`⚠ `:``}${Qn(e)} · teapot`:`teapot`;document.title=Gr()>0?`(${Gr()}) ${t}`:t});let za=()=>se()||fe()||jr()!==null||he()&&xt();window.addEventListener(`keydown`,e=>{let t=e.target;if(t&&(t.tagName===`INPUT`||t.tagName===`TEXTAREA`||t.isContentEditable))e.key===`Escape`&&t.blur();else if(e.key===`Escape`){if(se()){ce(!1);return}if(fe()){pe(!1);return}if(jr()){Mr(null);return}if(he()&&xt()){Et();return}let e=B();if(e&&kr()){Y(`/api/agents/${e.id}/stop`,{method:`POST`}).then(Ti);return}}else if(!za()){if(e.key===`/`)e.preventDefault(),document.querySelector(`.composer textarea`)?.focus();else if(e.key===`d`)Tt();else if(e.key===`t`)$a();else if(e.key===`ArrowDown`||e.key===`ArrowUp`){let t=zi().map(e=>e.a);if(t.length===0)return;e.preventDefault();let r=t.findIndex(e=>e.id===n()),i=e.key===`ArrowDown`?Math.min(r+1,t.length-1):Math.max(r-1,0);i!==r&&Ea(t[i].id)}}});let[Ba,Va]=y(localStorage.getItem(`teapot.term`)===`1`),[Ha,Ua]=y([]),[Wa,Ga]=y(!1),Ka=async()=>{let e=n();if(!e)return;let t=await Y(`/api/agents/${encodeURIComponent(e)}/bg-jobs`).catch(()=>null);t?.jobs&&Ua(t.jobs)};x(()=>{n(),Ka()}),x(()=>{if(!Wa())return;let e=setInterval(()=>void Ka(),2e3);T(()=>clearInterval(e))});let[qa,Ja]=y(!1),[Ya,Xa]=y(``),Za=()=>{let e=B();e&&(Xa(Qn(e)),Ja(!0))},Qa=async()=>{if(!qa())return;let e=B();Ja(!1);let t=Ya().replace(/\s+/g,` `).trim();if(!e||!t||t===Qn(e))return;let n=await Y(`/api/agents/${encodeURIComponent(e.id)}/session-title?session=${encodeURIComponent(e.session)}`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({title:t})}).catch(e=>({error:String(e)}));n?.error?cD(`rename failed: ${n.error}`):(d(n=>new Map(n).set(e.session,t)),Ti())},$a=()=>{let e=Le||qn(),t=!Ba();Va(t),localStorage.setItem(`teapot.term`,t?`1`:`0`),e&&He(900)},[eo,to]=y([]),no=e=>{let t=(e.cwd??``).replace(/[\\/]+$/,``).split(/[\\/]/).pop();return t&&t.length<=24?t:e.title},ro=async()=>{let e=(await Y(`/api/terminals`).catch(()=>null))?.terminals??[];e.length&&to(t=>t.map(t=>{let n=e.find(e=>e.id===t.key);return n?{...t,title:n.title,cwd:n.cwd}:t}))},[io,ao]=y(0),[oo,so]=y(-1),[co,lo]=y(!1),[uo,fo]=y(0),[po,mo]=y(Number(localStorage.getItem(`teapot.termH`))||Math.max(220,Math.round(window.innerHeight*.35))),ho=new Map,go=[null,null],_o=()=>eo()[uo()===0?io():oo()]??null;function vo(e){if(!eo()[e])return;let t=uo(),n=t===0?io():oo(),r=t===0?oo():io(),i=e=>t===0?ao(e):so(e);r===e?((e=>t===0?so(e):ao(e))(n),i(e)):n!==e&&i(e)}let yo=()=>bo();async function bo(e){let t=e??n();if(t){if(eo().filter(e=>e.agentId===t).length>=10)cD(`max 10 shells per agent (${t}) — that's already a lot`);else try{let e=(await Y(`/api/terminals`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({agentId:t})})).terminal;if(!e){cD(`could not open a shell`);return}let n=dd(eo());to(t=>[...t,{key:e.id,agentId:e.agentId,title:e.title,cwd:e.cwd}]),uo()===0?ao(n):so(n)}catch(e){cD(`could not open a shell: ${e.message}`)}}}function xo(e){let t=eo()[e];if(!t)return;Y(`/api/terminals/${encodeURIComponent(t.key)}`,{method:`DELETE`}).catch(()=>{});let n=ho.get(t.key);if(n){n.ro?.disconnect();try{n.ws.close()}catch{}n.term.dispose(),ho.delete(t.key)}let r=eo().filter((t,n)=>n!==e);to(r),ao(t=>pd(t,e,r.length)),so(t=>t===-1?-1:pd(t,e,r.length))}let So=()=>+!de();x(()=>{Ft(),Nt(),Kt(),Lt(),Ut(),de();let e=So();for(let[,t]of ho)Nn(t.term,e)});function W(){for(let[,e]of ho){e.ro?.disconnect();try{e.ws.close()}catch{}e.term.dispose()}ho.clear()}function Co(e,t){let n=ho.get(e.key);if(n&&Nn(n.term,So()),n)n.el.parentElement!==t&&(t.appendChild(n.el),setTimeout(()=>{try{n.fit()}catch{}},30));else{let r=document.createElement(`div`);r.className=`termsession`,t.appendChild(r);let i=new sd({cursorBlink:!0,fontSize:12.5,scrollSensitivity:3,fontFamily:`ui-monospace, Menlo, Consolas, monospace`,allowTransparency:!0,theme:Mn(So())});i.attachCustomKeyEventHandler(e=>{if(e.type!==`keydown`||!(e.ctrlKey&&e.shiftKey)||e.altKey||e.key!==`C`&&e.key!==`c`)return!0;let t=i.getSelection();return t&&navigator.clipboard?.writeText(t).catch(()=>{}),e.preventDefault(),!1});let a=new ud;i.loadAddon(a),i.open(r);let o=location.protocol===`https:`?`wss://`:`ws://`,s=()=>`${o}${location.host}/api/agents/${encodeURIComponent(e.agentId)}/term?terminal=${encodeURIComponent(e.key)}${hD()}`,c=new WebSocket(s()),l,u=!1,d=t=>{t.onmessage=t=>{let n=JSON.parse(t.data);n.kind===`data`?i.write(n.data):n.kind===`ping`||(n.kind===`exit`?(u=!0,i.write(`\r\n\x1b[2m[terminal exited ${n.code??``}]\x1b[0m\r\n`),to(t=>t.filter(t=>t.key!==e.key)),ho.get(e.key)?.term.dispose(),ho.delete(e.key)):n.kind===`attach`&&n.error&&(u=!0,i.write(`\r\n\x1b[2m[${n.error}]\x1b[0m\r\n`)))},t.onclose=()=>{!u&&ho.has(e.key)&&(l||=(i.write(`\r
182
+ Cancel = keep editing your copy`)?(ue(r.current),c({...t,content:r.current}),wf(`loaded the current file from disk`)):wf(`kept your edits — use Save As via bash to force-write`)}finally{fe(!1)}}},_e=e=>!e.binary&&!e.truncated,ve=(e,t)=>[(()=>{var n=Iw(),r=n.firstChild,a=r.nextSibling;return n.$$click=()=>e.dir?void ie(e):void he(e,`code`),R(r,(()=>{var t=P(()=>!!e.dir);return()=>t()?i().has(e.path)?`▾`:`▸`:jw(e.name)})()),R(a,()=>e.name),R(n,j(N,{get when(){return P(()=>!e.dir)()&&e.size!==void 0},get children(){var t=Fw();return R(t,()=>Ux(e.size)),t}}),null),b(r=>{var i=`filerow`+(e.dir?` isdir`:``)+(e.ignored&&v()===`dim`?` gitignored`:``),a=`padding-left:${t*13+8}px`,o=e.dir?`browse ${e.path}`:`preview ${e.path}`;return i!==r.e&&L(n,r.e=i),r.t=Oe(n,a,r.t),o!==r.a&&I(n,`title`,r.a=o),r},{e:void 0,t:void 0,a:void 0}),n})(),j(N,{get when(){return P(()=>!!e.dir)()&&i().has(e.path)},get children(){return j(M,{get each(){return(n().get(e.path)??[]).filter(C)},children:e=>ve(e,t+1)})}})],ye=()=>e.workspace.split(`/`).filter(Boolean).pop()??e.workspace,[be,xe]=y(!1),Se=async()=>{if(!be()){xe(!0);try{let e=[``,...i()],t=await Promise.all(e.map(async e=>({p:e,rows:await ne(e,w())})));for(let{p:e,rows:n}of t)n&&re(e,n)}finally{xe(!1)}}};return[(()=>{var e=Lw(),t=e.firstChild.nextSibling;return t.firstChild,R(t,ye,null),R(e,j(Sd,{class:`filetoggle`,get icon(){return be()?`…`:`⟳`},title:`refresh the tree (root + expanded folders) — open popups are kept`,onClick:()=>void Se()}),null),R(e,j(Sd,{class:`filetoggle`,style:`margin-left:auto`,get icon(){return P(()=>v()===`hide`)()?`🙈`:v()===`dim`?`👁`:`✨`},get title(){return`gitignored files: ${v()} — click to cycle (dim → hidden → shown)`},onClick:S}),null),R(e,j(Sd,{class:`filetoggle`,get icon(){return w()?`◉.`:`○.`},get title(){return w()?`dotfiles shown — click to hide`:`dotfiles hidden — click to show`},onClick:D}),null),e})(),(()=>{var e=Rw();return R(e,j(N,{get when(){return(n().get(``)??[]).length>0},get fallback(){return(()=>{var e=zw();return R(e,()=>g()||`empty workspace`),e})()},get children(){return j(M,{get each(){return(n().get(``)??[]).filter(C)},children:e=>ve(e,0)})}})),e})(),j(N,{get when(){return o()},children:t=>j(wd,{get title(){return`🗂 ${t().path}`},onClose:()=>{pe++,c(null),f(null)},get children(){return j(N,{get when(){return u()},get fallback(){return[(()=>{var e=Ww(),n=e.firstChild;return R(e,j(N,{get when(){return P(()=>!!A(t().path))()&&!t().binary},get children(){var e=Hw();return e.$$click=()=>h(`md`),b(()=>L(e,p()===`md`?`on`:``)),e}}),n),n.$$click=()=>{h(`code`),ae()||me({path:t().path,content:t().content,truncated:t().truncated})},R(e,j(N,{get when(){return _e(t())},get children(){var e=Uw();return e.$$click=()=>h(`edit`),b(()=>L(e,p()===`edit`?`on`:``)),e}}),null),b(()=>L(n,p()===`code`?`on`:``)),e})(),j(N,{get when(){return!t().binary},get fallback(){return Kw()},get children(){return j(N,{get when(){return p()===`edit`},get fallback(){return j(N,{get when(){return P(()=>p()===`md`)()&&A(t().path)},get fallback(){return j(vf,{get path(){return t().path},get content(){return t().content},get html(){return ae()},get pending(){return se()},get truncated(){return!!t().truncated}})},get children(){var e=qw();return b(()=>e.innerHTML=Re(t().content)),e}})},get children(){var e=Gw(),n=e.firstChild,r=n.nextSibling.firstChild,i=r.firstChild,a=r.nextSibling;return n.$$input=e=>ue(e.currentTarget.value),I(n,`spellcheck`,!1),R(r,()=>Ux(le().length),i),a.$$click=()=>void ge(),R(a,()=>de()?`saving…`:`💾 save`),b(()=>a.disabled=de()||le()===t().content),b(()=>n.value=le()),e}})}})]},get children(){var t=Vw(),n=t.firstChild,r=n.firstChild;return R(t,j(N,{get when(){return u().kind===`image`},get fallback(){return j(N,{get when(){return u().kind===`video`},get fallback(){return(()=>{var t=Yw();return b(()=>I(t,`src`,`/api/agents/${e.agentId}/raw?path=${encodeURIComponent(u().path)}`)),t})()},get children(){var t=Jw();return b(()=>I(t,`src`,`/api/agents/${e.agentId}/raw?path=${encodeURIComponent(u().path)}`)),t}})},get children(){var t=Bw();return b(n=>{var r=`/api/agents/${e.agentId}/raw?path=${encodeURIComponent(u().path)}`,i=u().path.split(`/`).pop();return r!==n.e&&I(t,`src`,n.e=r),i!==n.t&&I(t,`alt`,n.t=i),n},{e:void 0,t:void 0}),t}}),n),R(n,()=>u().kind,r),t}})}})})]}Ee([`click`,`input`]);var Zw=F(`<div class=overlay><div class=modal style=max-width:360px><div class=modal-head><b>🔒️ sign in</b><span></span></div><form style=display:flex;flex-direction:column;gap:10px><input id=pw-input type=password placeholder=password autofocus><button type=submit class=primarybtn>unlock</button><span class=muted style=font-size:11px>the token is stored locally and sent as Bearer to this server only`),Qw=F(`<div class=leftbarbackdrop>`),$w=F(`<div class=sidehead><b>agents</b><button class=iconbtn title="close the agent list">✕`),eT=F(`<i class=notifdot>`),tT=F(`<br>`),nT=F(`<button class="iconbtn ham"title="agent list">☰`),rT=F(`<input class="title titleedit">`),iT=F(`<span class="badge queued">⏳ <!> <!> queued`),aT=F(`<button type=button class="badge bgjobs">⚙️ `),oT=F(`<span class="badge cron">⏰ `),sT=F(`<div class=bgjobs-pop role=dialog aria-label="background shells"><div class=bgjobs-head><span>background shells</span><button type=button class=iconbtn title=close>✕`),cT=F(`<header class=chan-head><span class=hash title="rename this chat">#</span><span></span><span class=sub> · <!>/<!> · <!>↻ <!>⚙️</span><span class=head-actions><button></button><span class=head-sep aria-hidden=true>`),lT=F(`<div class=divider-msg>── beginning of log ──`),uT=F(`<div class=divider-msg>loading older events…`),dT=F(`<div class=feedloading><span class=spinner aria-hidden=true></span> loading timeline…`),fT=F(`<div class=feedloading><span class=spinner aria-hidden=true></span> loading newer events…`),pT=F(`<details class=reasoning open><summary>💭 thinking </summary><div class="mono thinkscroll">`),mT=F(`<div class=muted style=font-size:11.5px;margin-bottom:4px>🗜 summarizing older context…`),hT=F(`<div class=content>`),gT=F(`<div class="msg live"><div class=avatar style="background:#5865f233;border:1px solid #5865f266">🫖</div><div class=msg-body><div class=msg-head><span class=author style=color:var(--acc)>agent</span><span class=ts>streaming…`),_T=F(`<div class=feed>`),vT=F(`<div class="termempty muted">no shell here — + opens one, tabs fill the focused pane`),yT=F(`<div class=termsplit>`),bT=F(`<div class="termempty muted">no shell here — click a tab or + to add`),xT=F(`<div class=termpane>`),ST=F(`<div class=termdrawer><div class=termgrip title="drag to resize · double-click to reset"></div><div class=termbar><div class=termtabs></div><div style=display:flex;gap:4px;align-items:center><span class="muted mono"style=flex:1;text-align:center;overflow:hidden;text-overflow:ellipsis;white-space:nowrap></span></div></div><div class=termbody><div class=termpane>`),CT=F(`<button class=jump>↓ `),wT=F(`<div class=cmds>`),TT=F(`<div class=attachrow><button type=button class=attachclear title="remove every attachment">clear`),ET=F(`<label class=forkchip title="inherit the conversation prefix byte-exactly — the sub-agent's provider prefix cache starts warm"><input type=checkbox>fork ctx`),DT=F(`<div class="hint flashhint">`),OT=F(`<div><form><textarea rows=1></textarea><button type=button class="iconbtn maxbtn"></button><button type=submit>send</button><input id=composer-file type=file accept=image/* multiple style=display:none>`),kT=F(`<div class=rightbarbackdrop>`),AT=F(`<div><nav><div class=agent-list></div><div class=sidebar-footer><div class=footer-row style=justify-content:flex-end><button>🔔️</button></div><div class=brand-row><div class=brand>🫖 teapot <span class=version>v</span><span></span></div></div><div class=metrics></div></div></nav><section class=channel></section><aside><div class=rightbarhead><span class=muted>details`),jT=F(`<div class=notifbackdrop>`),MT=F(`<button class=editbtn>clear all`),NT=F(`<div class=notiflist>`),PT=F(`<div class=notifpanel><div class=notifhead>notifications<span style=display:flex;gap:8px;align-items:center><button class=iconbtn title="close notifications">✕`),FT=F(`<div class=bgphoto aria-hidden=true><img sizes=100vw alt decoding=async><span class=bgphoto-veil>`),IT=F(`<span class=wscount>`),LT=F(`<div class=wsheader><span class=wscaret></span><span class=wsname>`),RT=F(`<span class=notifbadge>🔔️`),zT=F(`<span class=subtag>🧩`),BT=F(`<span class=mini-cron>⏰`),VT=F(`<span class=goaldone title="goal done">✓`),HT=F(`<div><span></span><span>`),UT=F(`<span class=caret-spacer>`),WT=F(`<span class=caret>`),GT=F(`<span class=ghosttag title="workspace missing">👻`),KT=F(`<span>🧩 `),qT=F(`<div class=muted style=display:grid;place-items:center;height:100%>select an agent`),JT=F(`<span class=title>`),YT=F(`<div class="muted bgjobs-empty">no background jobs for this agent`),XT=F(`<pre class="mono bgjob-tail">`),ZT=F(`<div class=bgjob><div class=bgjob-line><span></span><code class="mono bgjob-cmd"></code><span class="muted bgjob-meta"></span><button type=button class=bgjob-kill>`),QT=F(`<div class="muted bgjob-detached">this job outlived a harness restart, so its output is no longer captured here. it is still running as pid <!> — read its own log, or stop it yourself.`),$T=F(`<div class="divider-msg compacting"title="the harness is compressing old turns into notes so work can continue within the context window">🗜 `),eE=F(`<div class=muted style=display:grid;place-items:center;height:100%><span><span class=spinner aria-hidden=true></span> loading timeline…`),tE=F(`<div class=muted style=display:grid;place-items:center;height:100%>no events yet — say something or press ▶ start`),nE=F(`<div class="content muted">thinking…`),rE=F(`<div class=lightbox role=dialog aria-modal=true aria-label="enlarged image"title="click to close"><img alt>`),iE=F(`<span>⌨ <button class=tabx title="close this shell">✕`),aE=F(`<div><b class=mono></b><span class=muted>`),oE=F(`<div class=cmdrow><b>@</b><span class=muted>`),sE=F(`<span class=imgchip><img title="click to enlarge"><button type=button class=imgx title=remove>✕`),cE=F(`<span class=muted style=text-transform:none;letter-spacing:0>· <!> models`),lE=F(`<h3 title="switch provider/model live — applies from the agent's next turn">🧦 model`),uE=F(`<div style=display:flex;gap:6px;align-items:center;margin-top:6px><label class=muted style=font-size:11.5px;white-space:nowrap>effort</label><select style=flex:1;min-width:0><option value>provider default`),dE=F(`<div class=meta style=color:var(--fg)>`),fE=F(`<div class=modelbox><select title="provider (OpenAI-compatible endpoint)"></select><div style=display:flex;gap:4px><input type=text list=model-list style=flex:1;min-width:0><datalist id=model-list></datalist></div><div style=display:flex;gap:6px;align-items:center;margin-top:6px><button title="apply the provider, model and effort above to this session — takes effect from the agent's next turn"style=flex:1>apply</button></div><div class=meta>current: `),pE=F(`<span>`),mE=F(`<h3 title="what the agent is working toward. Stored with the session; the agent reads it via get_goal(). Auto-continue keeps looping while the status is 'active' and stops when marked done.">🎯 goal`),hE=F(`<div class=statrow style=margin-bottom:6px><span class=k>status`),gE=F(`<div class="card goalcard"><div class=content>`),_E=F(`<form style=display:flex;flex-direction:column;gap:6px;margin-top:8px;margin-bottom:6px><textarea id=goal-input rows=3 placeholder="set new goal…"title="drag the bottom edge to make this taller — the height is remembered"style="background:var(--bg-darkest);border:none;border-radius:6px;padding:6px 8px;color:var(--fg);font:inherit;width:100%;resize:vertical"></textarea><textarea id=goal-verify-input rows=2 placeholder="verification contract (optional) — e.g. 'npm test passes; endpoint documented'. finish(goalComplete=true) is then audited against this."title="pi-goal-x-style verification contract — an independent reviewer checks the agent's finish against these requirements"style="background:var(--bg-darkest);border:1px solid var(--bg-light);border-radius:6px;padding:6px 8px;color:var(--fg);font:inherit;font-size:12.5px;width:100%;resize:vertical"></textarea><div style=display:flex;justify-content:flex-end;align-items:center;gap:10px><label class=muted title="auto-continue acts on the GOAL above: it fires after a round ONLY when all hold — ① this toggle is on ② a goal is set and its status is 'active' ③ the round ended cleanly (no error / not stopped). It stops when the goal is marked done, or if you press ■ stop."style=display:flex;align-items:center;gap:4px;font-size:11.5px;white-space:nowrap;cursor:pointer><input type=checkbox>auto-continue</label><label class=muted title="queue a harness prompt telling the agent about the new goal at its next turn boundary"style=display:flex;align-items:center;gap:4px;font-size:11.5px;white-space:nowrap;cursor:pointer><input id=goal-notify type=checkbox> notify agent</label><button type=submit class=primarybtn>✓ save goal`),vE=F(`<span class=badge>/<!> done`),yE=F(`<h3 title="todo.md — a shared checklist in the session dir. Write tasks like '- [ ] fix login'; the agent ticks them off via set_todo, you edit here. With notify on, it's told at its next turn boundary.">✅ tasks`),bE=F(`<div class=bartrack style=margin-bottom:6px><div>`),xE=F(`<div style=display:flex;justify-content:flex-end;align-items:center;gap:10px;margin-top:4px><label class=muted title="queue a harness prompt telling the agent the task list changed"style=display:flex;align-items:center;gap:4px;font-size:11.5px;white-space:nowrap;cursor:pointer><input id=todo-notify type=checkbox checked> notify agent</label><button class=okbtn>✓ save tasks`),SE=F(`<h3 title="latest report_progress snapshot. The harness asks for one after real activity (time AND output gates); errors show under ⚠ problems">📈 progress`),CE=F(`<h3 title="context is how much of the model's window the live conversation occupies. Past the threshold, the oldest turns are summarized into notes so work can continue.">📊 runtime`),wE=F(`<div class=rtcell><span>cost</span><b>$`),TE=F(`<div class=rtcell><span>cached</span><b>%`),EE=F(`<div class="card runcard"><div class=rtgrid><div class=rtcell title="prompt tokens billed this session"><span>tokens in</span><b></b></div><div class=rtcell title="completion tokens billed this session"><span>tokens out</span><b></b></div><div class=rtcell title="assistant turns this session"><span>turns</span><b></b></div><div class=rtcell title="tool calls this session"><span>tools</span><b></b></div><div class=rtcell><span>compacted</span><b>`),DE=F(`<div class=muted style=font-size:11px;text-transform:none;letter-spacing:0>showing <b></b> and the history it inherited before forking`),OE=F(`<h3>🌿 branches <span class=muted style=text-transform:none;letter-spacing:0>· click to filter the feed`),kE=F(`<span class=muted style=text-transform:none;letter-spacing:0>· <!> · all agents`),AE=F(`<h3 title="cron tasks, all agents — click a row to open that agent. Edit them in ⚙️ settings → scheduled tasks.">⏰ schedule`),jE=F(`<option>`),ME=F(`<span class=badge title="no goal set yet">no goal`),NE=F(`<button>`),PE=F(`<div class="card muted">no goal yet — write one below and press ✓ save. Then ▶ start (or any message) sets it in motion.`),FE=F(`<div class=muted>none yet`),IE=F(`<div class=progrow><b>recent</b><span class="content inline-md">`),LE=F(`<div class="progrow warn"><b>⚠ problems</b><span class="content inline-md">`),RE=F(`<div class=progrow><b>next</b><span class="content inline-md">`),zE=F(`<div class=progrow><b>goal</b><span>`),BE=F(`<div class="card prog"><div class=progrow><b>doing</b><span class="content inline-md"></span></div><div class="meta muted">`),VE=F(`<div class=statrow><span class=k>context</span><span class=muted>no window known for this model yet`),HE=F(`<span>% of `),UE=F(`<div class=bartrack><div>`),WE=F(`<div class=statrow title="a compaction pass is running right now — the summarizer's output streams in the timeline"><span class=k>🗜</span><b>compacting…</b><span class=muted style=font-size:11px;color:var(--acc)>`),GE=F(`<div class=ctxblock title="estimated live context vs the model's real window. Past the window, old turns are summarized into notes (compaction); the compact line below shows where that starts."><div class=statrow><span class=k>context</span><b>~<!> tok</b></div><div class=statrow style=margin-top:4px><span class=k>compact at</span><b> tok</b><span class=muted style=color:var(--dim)></span></div><div class=ctrlrow style=margin-top:6px><label title="when on, older turns are automatically summarized when context exceeds the budget"><input type=checkbox>auto-compact`),KE=F(`<div><span></span><span> events`),qE=F(`<div class=muted>no scheduled tasks — add them in ⚙️ settings ("scheduled tasks")`),JE=F(`<span title="runs on a forked branch so chatter stays off the main line">⑂`),YE=F(`<div><div class=sched-top><b></b><span class=muted>@</span></div><div class=sched-meta> → next </div><div class="sched-prompt muted">`),XE=F(`<div class=muted style=padding:10px>nothing yet — progress, finishes, questions and errors will land here`),ZE=F(`<div class=nbody>`),QE=F(`<div><div class=nhead><span class=nicon></span><span class=ntitle></span><span class="meta muted"></span><button class="iconbtn nreadbtn">`),$E=F(`<div style=font-size:12.5px;color:var(--dim)> event(s) came after this prompt and will be discarded — the new branch starts from your edited text.`),eD=F(`<form style=display:flex;flex-direction:column;gap:10px><textarea id=edit-text class="mono w100"rows=6></textarea><div style=display:flex;justify-content:flex-end;gap:8px><button type=button>cancel</button><button type=submit class=primarybtn>⑂ fork & resend`),tD=F(`<span style=color:var(--err);font-size:13px>`),nD=F(`<form style=display:flex;flex-direction:column;gap:10px><label>workspace directory<div style=display:flex;gap:6px><input type=text class="w100 mono"><button type=button>go</button><button type=button title="parent directory">↑</button></div></label><div class=dirlist></div><div style=display:flex;gap:10px><label style=flex:1>agent name <input type=text placeholder="(directory name)"></label><label style="flex:0 1 auto;min-width:0">provider<select></select></label><label style=flex:1>model <input type=text placeholder="(provider default)"></label></div><button type=submit style=align-self:flex-end>create`),rD=F(`<div class=direntry>📁 `),iD=[`minimal`,`low`,`medium`,`high`],aD=1100,[oD,sD]=y(``),cD,lD=e=>{sD(e),clearTimeout(cD),cD=setTimeout(()=>sD(``),3200)},uD=!1,dD=new Set([`user`,`message`,`prompt`,`tool_call`,`tool_result`,`progress`,`state`,`error`,`fork`,`goal`,`todo`,`question`,`decision`,`compaction`,`audit_step`,`system_note`]),fD=new Set([`system_note`]),pD=new Set([`user`,`message`,`prompt`,`tool_call`,`tool_result`,`progress`,`error`,`fork`,`goal`,`todo`,`question`,`decision`,`compaction`,`audit_step`]),mD=new Set([`runaway-detected`,`error-retry`,`background-exit`,`context-compacted`,`context-compaction-started`]),hD=location.hash.match(/[#&]token=([^&]+)/);hD&&(localStorage.setItem(`teapot.token`,decodeURIComponent(hD[1])),history.replaceState(null,``,location.pathname+location.search));var gD=()=>{let e=localStorage.getItem(`teapot.token`);return e?`?token=${encodeURIComponent(e)}`:``};function _D(){let[e,t]=y([]),[n,r]=y(null),[i,a]=y(``),[o,s]=y(new Map),[c,l]=y(new Map),[u,d]=y(new Map),f=!1,p=null;async function m(e=!1){if(p)return p;if(f&&!e)return;let t=(async()=>{try{let e=await X(`/api/sessions`),t=new Map,n=new Map,r=new Map;for(let i of e.sessions??[]){t.set(i.id,i.agentId),typeof i.title==`string`&&i.title&&r.set(i.id,i.title);let e=n.get(i.agentId)??[];e.push(i.id),n.set(i.agentId,e)}s(t),l(n),d(r),f=!0}catch{}})();p=t;try{await t}finally{p===t&&(p=null)}}let[h,g]=y([]),[_,v]=y(0),[ee,E]=y([]),[D,O]=y(null),te=new Map,[ne,re]=y(te.get(n()??``)??``),k=e=>{re(e);let t=n();t&&(e?te.set(t,e):te.delete(t))},[ie,ae]=y({providers:{}}),[oe,se]=y(!1),ce=()=>mr({want:gr({preview:Rt(),auto:Pt(),prefersLight:Gt(),dark:Ht(),light:It(),fixed:Mt()}),customIds:Bt().map(e=>e.id),presetIds:$d.map(e=>e.key),fallback:`dark`}),le=()=>ce().active,ue=()=>Bt().find(e=>e.id===le())?.backgroundImage??``,[de,fe]=y(!1),A=!1;x(()=>{!A&&ie()?.needsSetup&&(A=!0,requestAnimationFrame(()=>{fi(),fe(!0)}))}),x(()=>{de()&&!Bo()&&X(`/api/features`).then(e=>Vo(e)).catch(()=>Vo(null))});let pe=new Set,me=()=>window.innerWidth<=aD,[he,ge]=y(me());w(()=>{let e=()=>{let e=me();e!==he()&&(ge(e),(localStorage.getItem(vt(e))!==null||!e)&&xt(yt(e)))};window.addEventListener(`resize`,e),T(()=>window.removeEventListener(`resize`,e)),e()});let _e=0,ve=null,ye=0,be,xe,Se=0,Ce=0,we=0,Te=()=>{if(performance.now()<Fe){if(performance.now()<we)return;let e=ma();e&&He(e);return}if(qn()||!ve)return;let e=ma();if(!e)return;if(!Ze(performance.now(),Ce)||e.scrollHeight===$o){ve=_t(e),ye=performance.now();return}if(!F(e))return;let t=e.scrollHeight;et(e,ve,ts),$o=e.scrollHeight,t!==$o&&(Qo={top:e.scrollTop,height:e.scrollHeight})},F=e=>{if(!ve)return!1;let t=_t(e);return t?t.sel===ve.sel||(ve=t,ye=performance.now(),!1):!1},Ee=()=>{Se||=requestAnimationFrame(()=>{Se=0,Te()})},je,Me,Ne=0,Pe=``,Fe=0,Ie=!0,Le=e=>{Ie=e,qn()!==e&&Jn(e)},ze=0,Be=()=>{if(ze=0,performance.now()>=Fe)return;if(performance.now()<we){ze=requestAnimationFrame(Be);return}let e=ma();e&&We({top:e.scrollTop,height:e.scrollHeight,viewport:e.clientHeight})>1&&He(e),ze=requestAnimationFrame(Be)},Ve=(e=1500)=>{Fe=performance.now()+e,ze||=requestAnimationFrame(Be)},He=e=>{e.scrollTop=e.scrollHeight,Qo={top:e.scrollTop,height:e.scrollHeight},Jn(!0),tr(0),ve=_t(e),ye=performance.now()},Ue=0,$e=()=>{Ne=0;let e=ma();if(!e)return;let t=e.scrollHeight!==$o;$o=e.scrollHeight,ns=e.clientHeight;let n=e.clientWidth!==Ue;Ue=e.clientWidth,!n&&(qn()||performance.now()<Fe)?_a():n&&(Ie||performance.now()<Fe)?(_a(),ir(ha())):n?((Ie||performance.now()<Fe)&&_a(),ir(ha())):t?Ze(performance.now(),Ce)?(F(e)&&et(e,ve,es),ir(ha())):(ve=_t(e),ye=performance.now(),ir(ha())):(ve||(ve=_t(e),ye=performance.now()),ir(ha()))};function et(e,t,n=es){if(!t)return;let r=e.querySelector(t.sel);if(!r)return;let i=r.getBoundingClientRect().top-t.top;Math.abs(i)<1||Math.abs(i)>n||(e.scrollTop+=i,Qo={top:e.scrollTop,height:e.scrollHeight})}let ot=()=>{Ne||=requestAnimationFrame($e)},st=null,ct=e=>{st?.();let t=e=>{Hn(e.deltaY)&&(we=performance.now()+400,Le(!1))},n=()=>{we=performance.now()+400,Le(!1)},r=t=>{let r=t.target;r&&typeof r.closest==`function`&&r.closest(`textarea, input, select, [contenteditable=''], [contenteditable='true']`)||!Wn({target:r,insideFeed:!!r&&typeof e.contains==`function`&&e.contains(r),isBackground:!r||r===document.body||r===document.documentElement,editable:!1})||Un(t.key)&&n()};e.addEventListener(`wheel`,t,{passive:!0}),e.addEventListener(`touchmove`,n,{passive:!0}),window.addEventListener(`keydown`,r,{capture:!0}),st=()=>{e.removeEventListener(`wheel`,t),e.removeEventListener(`touchmove`,n),window.removeEventListener(`keydown`,r,{capture:!0}),st=null}},lt=e=>{e&&(ct(e),e!==Me&&(je??=new ResizeObserver(e=>{let t=e[0]?.contentRect,n=t?`${Math.round(t.width)}x${Math.round(t.height)}`:``;n!==Pe&&(Pe=n,ot())}),Me&&je.unobserve(Me),Me=e,Pe=``,je.observe(e),typeof MutationObserver<`u`&&(be??=new MutationObserver(Ee),xe&&xe!==e&&xe.removeEventListener(`load`,Ee,!0),xe=e,be.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),e.addEventListener(`load`,Ee,!0))))};w(()=>{window.addEventListener(`resize`,ot),T(()=>{window.removeEventListener(`resize`,ot),je?.disconnect(),je=void 0,Me=void 0,be?.disconnect(),be=void 0,xe&&xe.removeEventListener(`load`,Ee,!0),xe=void 0,Se&&cancelAnimationFrame(Se),Ne&&cancelAnimationFrame(Ne)})});let ft=e=>`[data-eid="${globalThis.CSS?.escape?.(e)??e.replace(/["\\]/g,`\\$&`)}"]`;function _t(e){let t=e.querySelectorAll(`[data-eid]`);if(!t.length)return null;let n=e.getBoundingClientRect().top,r=e=>t[e].getBoundingClientRect(),i=0,a=t.length-1,o=-1;for(;i<=a;){let e=i+a>>1;r(e).bottom>n?(o=e,a=e-1):i=e+1}if(o<0)return null;let s=t[o].dataset.eid??``;return s?{sel:ft(s),top:r(o).top}:null}let vt=e=>e?`teapot.panel.narrow`:`teapot.panel`,yt=e=>{let t=localStorage.getItem(vt(e));return t===null?!e:t===`1`},[bt,xt]=y(yt(me())),St=e=>{xt(e),localStorage.setItem(vt(he()),e?`1`:`0`)},wt=()=>St(!bt()),Tt=()=>{bt()&&St(!1)},[kt,At]=y(!1),jt=()=>At(!1),[Mt,Nt]=y(localStorage.getItem(`teapot.theme`)??`dark`),[Pt,Ft]=y(localStorage.getItem(`teapot.theme.auto`)===`1`),[It,Lt]=y(localStorage.getItem(`teapot.theme.light`)??`light`),[Rt,zt]=y(null),[Bt,Vt]=y(sr());w(()=>{lr().then(e=>{if(e===null)return;let t=on(Bt(),e);Vt(t),cr(t)})});let[Ht,Ut]=y(localStorage.getItem(`teapot.theme.dark`)??`dark`),Wt=typeof window.matchMedia==`function`?window.matchMedia(`(prefers-color-scheme: light)`):null,[Gt,Kt]=y(Wt?.matches??!1);w(()=>{let e=e=>Kt(e.matches);Wt?.addEventListener(`change`,e);let t=()=>{if(document.visibilityState!==`visible`)return;let e=Wt?.matches??!1;e!==Gt()&&Kt(e)};document.addEventListener(`visibilitychange`,t),T(()=>{Wt?.removeEventListener(`change`,e),document.removeEventListener(`visibilitychange`,t)})}),x(()=>{let{active:e,repaired:t}=ce(),n=Bt().find(t=>t.id===e)??null;t&&(Pt()?localStorage.setItem(Gt()?`teapot.theme.light`:`teapot.theme.dark`,e):localStorage.setItem(`teapot.theme`,e)),document.documentElement.dataset.theme=e,dr(document.documentElement,n),document.documentElement.dataset.appearance=n?.mode??$d.find(t=>t.key===e)?.mode??`dark`});let[qt,Yt]=y(``),[Zt,Qt]=y(``),[$t,en]=y(``);x(()=>{let t=n();en(C(()=>e().find(e=>e.id===t)?.reasoningEffort??``))});let[tn,nn]=y([]),cn=()=>Object.keys(ie().providers??{});async function ln(e){if(e)try{let t=await X(`/api/models?provider=${encodeURIComponent(e)}`);nn(t.models??[])}catch{nn([])}}let un=e=>{let t={text:`📄`,image:`🖼️`,audio:`🔊`,video:`🎬️`,file:`📎`},n=e=>(e??[`text`]).map(e=>t[e]??e).join(``);return e?.modalities?`${n(e.modalities.input)} → ${n(e.modalities.output)}`:``},mn=()=>{let e=Zt().trim()||V()?.model||``;if(!e)return``;let t=tn().find(t=>t.id===e);if(!t)return``;let n=[],r=un(t);r&&r!==`📄 → 📄`&&n.push(r),t.contextLength&&n.push(`ctx ${Ux(t.contextLength)} tok`);let i=e=>e===void 0?``:`${e*1e6>=10?Math.round(e*1e6):+(e*1e6).toFixed(1)}/M`;if(t.pricing){let e=i(t.pricing.prompt),r=i(t.pricing.completion);e&&r?n.push(`${e} in · ${r} out`):(e||r)&&n.push(i(t.pricing.prompt??t.pricing.completion))}return n.join(` · `)},En=null,An=!1;x(()=>{let t=n();if(!t)return;let r=e().find(e=>e.id===t),i=r?.provider||ie().defaultProvider||cn()[0]||``;if(r){if(t!==En)En=t,An=!1,C(()=>qt())!==i&&(Yt(i),ln(i)),C(()=>Zt())&&Qt(``);else{let e=C(()=>qt());!C(()=>Zt())&&e!==i&&Rn(An)&&(Yt(i),ln(i))}}});let[Nn,Fn]=y(!1),[qn,Jn]=y(!0),Yn,[Xn,tr]=y(0),[nr,rr]=y(-1),ir=e=>rr(e?Xe(e):-1),[ar,or]=y(null),ur=()=>z().startsWith(`[compact] `),fr=()=>{let e=ur()?z().slice(10):z();return e.length>1200?`…`+e.slice(-1200):e};x(()=>{ar()||vr(e=>e?.text.startsWith(`[compact] `)?null:e)}),x(()=>{h().length,_(),ar(),oi().length,ta(),$i(),W();let e=ma();if(!e)return;let t=e.scrollHeight;t!==_e&&(_e=t,requestAnimationFrame(()=>requestAnimationFrame(()=>{qn()&&(_a(),requestAnimationFrame(()=>{if(!qn())return;let t=e.scrollHeight;t!==_e&&(_e=t,_a())}))})))});let[pr,hr]=y(new Map),_r=()=>{let e=n();return e?pr().get(e)??null:null},vr=e=>{let t=n();t&&hr(n=>{let r=new Map(n),i=typeof e==`function`?e(n.get(t)??null):e;return i?r.set(t,{...i,at:Date.now()}):r.delete(t),r})},yr=()=>{let e=_r();if(!e)return;let t=Dt(e,h(),V()?.status);t?(t.text!==e.text||t.reasoning!==e.reasoning)&&vr(t):vr(null)},[z,B]=y(``),[br,xr]=y(0),Sr=()=>br(),[Cr,wr]=y(``),Tr;x(()=>{_r()?Tr||=setTimeout(()=>{Tr=void 0,B(_r()?.text??``),wr(_r()?.reasoning??``)},(_r()?.text.length??0)>2e4?250:(_r()?.text.length??0)>6e3?120:60):(clearTimeout(Tr),Tr=void 0,B(``),wr(``))}),T(()=>clearTimeout(Tr)),x(()=>{let t=e();hr(e=>Et(e,e=>t.find(t=>t.id===e)?.status)),xr(e=>Ot(e,t,n(),_r()))}),x(()=>{let e=z(),t=_r()?.reasoning??``;(e||t)&&requestAnimationFrame(()=>{qn()&&_a()})}),x(()=>{let e=V()?.pendingPrompts??0,t=V()?.pendingPromptIds,n=Ir(),r=Lr(n),i=Sn(r,e,t);i!==r&&Rr(n,i)}),x(()=>{let e=V()?.pendingPromptQueue;if(!e?.length)return;let t=V()?.session||Ir();if(xa.size){let t=new Set(e.map(e=>String(e.id??``)));for(let e of[...xa])t.has(e)||xa.delete(e)}let n=Cn(Lr(t),e.filter(e=>!xa.has(String(e.id??``))));n!==Lr(t)&&Rr(t,n)}),x(()=>{if(!n())return;let e=()=>{document.visibilityState===`visible`&&requestAnimationFrame(()=>{ga()&&(Jn(!0),tr(0),va(!0),qr())})};document.addEventListener(`visibilitychange`,e),T(()=>document.removeEventListener(`visibilitychange`,e))});let V=S(()=>e().find(e=>e.id===n()));x(()=>{let e=V()?.pendingQuestionId;e&&(h().some(t=>t.id===e)||(Dr.has(e)||(Dr.add(e),pa(n(),i())),!(ta()||W())&&(async()=>{for(let t=0;t<8;t++){if(h().some(t=>t.id===e)||ta())return;if(W()){await new Promise(e=>setTimeout(e,50));continue}let t=h().length;if(await sa(),h().length===t)return}})()))});let Er=``,Dr=new Set;x(()=>{let e=V()?.pendingQuestionId;e&&e!==Er&&h().some(t=>t.id===e)&&(Er=e,Qr(e,0))});let Or=()=>er({sameSession:!(V()?.session!==Ir()&&V()?.session),echoCount:si()}),kr=()=>{let e=V();return e?e.live??(e.status===`running`||e.status===`waiting`||e.status===`needs_operator`):!1},Ar=()=>kn(V(),i(),kr()),[jr,Mr]=y(null);S(()=>{let e=new Set;for(let t of h())t.type===`tool_result`&&(t.data?.name===`ask_operator`||t.data?.name===`ask_user`)&&e.add(String(t.data.callId));return e});let Nr=new Map,[Pr,Fr]=y([]),Ir=()=>i()||n()||`?`,Lr=e=>Nr.get(e)??[],Rr=(e,t)=>{let n=new Set,r=[];for(let e=t.length-1;e>=0;e--){let i=t[e],a=i.promptId;a?n.has(a)||(n.add(a),r.push(i)):r.push(i)}r.reverse(),r.length===0?Nr.delete(e):Nr.set(e,r),Ir()===e&&Fr(r)},[zr,Br]=y([]),[Vr,Hr]=y(localStorage.getItem(`teapot.hideGhosts`)===`1`),[Ur,Wr]=y(!1),Gr=()=>zr().filter(e=>!e.read).length,Kr=e=>{Br(t=>{let n=!1,r=t.map(t=>t.read||t.agentId!==e?t:(n=!0,{...t,read:!0}));return n?r:t})},qr=()=>{let e=n();e&&zr().some(t=>!t.read&&t.agentId===e)&&Kr(e)},Jr=t=>{let n=zr().filter(e=>!e.read&&e.agentId===t).length;for(let r of e())r.parent===t&&(n+=Jr(r.id));return n},Yr=0,Xr=e=>{Br(t=>[{...e,id:`n${++Yr}`,at:Date.now(),read:!1},...t].slice(0,50))},Zr=(t,n)=>{if(n.type===`system_note`&&n.data?.event===`background-exit`){let r=e().find(e=>e.id===t)?.id??t,i=n.data.failed===!0,a=Math.round(Number(n.data.durationMs??0)/1e3);Xr({agentId:t,kind:i?`error`:`progress`,title:`${r}: ${i?`⚠`:`✓`} background job ${String(n.data.jobId??`?`)} `+(i?`FAILED (exit ${String(n.data.code??`?`)})`:`finished (${a}s)`),body:String(n.data.cmd??``).slice(0,200)});return}let r=e().find(e=>e.id===t)?.id??t,i=typeof n.id==`string`?n.id:void 0;n.type===`message`&&n.data?.final===!0?Xr({agentId:t,kind:`finish`,title:`${r} finished`,body:String(n.data.content??``).slice(0,300),eventId:i}):n.type===`question`?Xr({agentId:t,kind:`question`,title:`${r} asks a question`,body:String(n.data.question??``).slice(0,300),eventId:i}):n.type===`error`?Xr({agentId:t,kind:`error`,title:`${r} hit an error`,body:String(n.data.message??``).slice(0,300),eventId:i}):n.type===`progress`&&Xr({agentId:t,kind:`progress`,title:`${r}: ${String(n.data.doing??`progress`)}`.slice(0,120),body:[n.data.recent&&`recent: ${n.data.recent}`,n.data.next&&`next: ${n.data.next}`].filter(Boolean).join(` · `).slice(0,300),eventId:i})},Qr=(e,t=0)=>{let n=i(),r=document.querySelector(ft(e)),a=!!r&&Qe(r.dataset.session,n);r&&a?(r.scrollIntoView({behavior:`smooth`,block:`center`}),r.classList.add(`flash-target`),setTimeout(()=>r.classList.remove(`flash-target`),1600)):t<30&&requestAnimationFrame(()=>Qr(e,t+1))},$r=S(()=>{let e=new Map,t=new Set,n=new Map,r=new Map;for(let i of h())if(dD.has(i.type)){if(i.type===`tool_call`){let e=n.get(i.data.callId)??[];e.push(i),n.set(i.data.callId,e)}else if(i.type===`tool_result`){let a=n.get(i.data.callId)?.shift();a?(e.set(a.id,i),t.add(i.id)):r.set(i.id,i)}}return{resFor:e,consumed:t,orphanCalls:r}}),[ei,ti]=y(new Set),ni=e=>{e&&ti(t=>{if(t.has(e))return t;let n=new Set(t);return n.add(e),n})},ri=()=>ti(new Set),ii=S(()=>xn(h(),ei())),ai=S(()=>Jt({events:h(),consumed:$r().consumed,pending:Pr().map(e=>({...e,promptId:e.promptId??e.id})),serverPendingIds:V()?.pendingPromptIds??[],echo:di,feedTypes:dD,renderedTypes:pD,renderedNoteEvents:mD})),oi=()=>ai().rows,si=()=>ai().pendingCount,ci=S(()=>{let e=new WeakMap;return oi().forEach((t,n)=>e.set(t,n)),e}),li=(e,t)=>{let n=ci().get(e);if(n!==void 0)return oi()[n+t]},ui=new Map;function di(e){let t=`${e.id}:${e.sent?`s`:`p`}:${e.promptId??``}`,n=ui.get(t);if(n)return n;ui.size>64&&ui.clear();let r={id:e.id,seq:2**53-1,ts:new Date(e.at).toISOString(),session:V()?.session??``,branch:V()?.branch??`br0`,parent:null,type:`prompt`,data:{source:e.source??`user`,text:e.text,pending:!e.sent,queued:!e.sent&&e.queued===!0,...e.images?.length?{images:e.images}:{},...e.promptId?{promptId:e.promptId}:{}}};return ui.set(t,r),r}let fi=()=>X(`/api/config`).then(ae).catch(()=>{}),[pi,mi]=y(!1);w(()=>{let e=()=>mi(!0);window.addEventListener(`teapot:unauthorized`,e),T(()=>window.removeEventListener(`teapot:unauthorized`,e))});let[hi,gi]=y(``),[_i,vi]=y(!0),[yi,bi]=y(!1),xi=``;x(()=>{let t=n(),r=e().find(e=>e.id===t)?.todo??``;t&&t!==xi?(xi=t,bi(!1),gi(r)):t&&!yi()&&gi(r)});let Si=async()=>{let e=document.getElementById(`todo-notify`)?.checked??!0;if(n())try{await X(`/api/agents/${n()}/todo`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({text:hi(),notify:e})}),bi(!1),vi(!0),lD(`tasks saved${e&&hi().trim()?` & notification queued`:``}`),Ti()}catch(e){lD(`save failed: ${e.message}`)}},Ci=S(()=>{let e=0,t=0;for(let n of hi().split(`
183
+ `)){let r=n.match(/^\s*[-*+] \[([ xX])\]/);r&&(e++,r[1].toLowerCase()===`x`&&t++)}return{total:e,done:t}});function wi(e,t){let n=new Map(e.map(e=>[e.id,e]));return t.map(e=>{let t=n.get(e.id);return t&&JSON.stringify(t)===JSON.stringify(e)?t:e})}let Ti=()=>X(`/api/agents`).then(e=>{let n=!1;t(t=>(t.length!==(e.agents??[]).length&&(n=!0),(e.agents??[]).some(e=>!t.some(t=>t.id===e.id))&&(n=!0),wi(t,e.agents??[]))),n&&m()}).catch(()=>{}),Ei=()=>X(`/api/metrics`).then(O).catch(()=>{}),[Di,Oi]=y([]),ki=()=>X(`/api/tasks`).then(e=>Oi(e.tasks)).catch(()=>{}),Ai=e=>Di().filter(t=>t.agent===e),[H,ji]=y((()=>{try{let e=JSON.parse(localStorage.getItem(`teapot.expandedSubs`)??`[]`);return new Set(e.filter(e=>typeof e==`string`))}catch{return new Set}})()),[Mi,U]=y((()=>{try{let e=JSON.parse(localStorage.getItem(`teapot.collapsed`)??`[]`);return new Set(e.filter(e=>typeof e==`string`&&!e.startsWith(`chat:`)))}catch{return new Set}})()),Ni=e=>Mi().has(e)||!H().has(e),Pi=e=>{let t=new Set(H());if(t.has(e)?t.delete(e):t.add(e),ji(t),localStorage.setItem(`teapot.expandedSubs`,JSON.stringify([...t])),t.has(e)&&Mi().has(e)){let t=new Set(Mi());t.delete(e),U(t),localStorage.setItem(`teapot.collapsed`,JSON.stringify([...t]))}},Fi=t=>vn(e(),t),[Ii,Li]=y((()=>{try{let e=JSON.parse(localStorage.getItem(`teapot.wsCollapsed`)??`[]`),t=Array.isArray(e)?e.filter(e=>typeof e==`string`):[];if(Number(localStorage.getItem(`teapot.wsCollapsed.v`)??`0`)<2){let e=t.filter(e=>!e.startsWith(`chat:`));return t.length-e.length>0&&localStorage.setItem(`teapot.wsCollapsed`,JSON.stringify(e)),localStorage.setItem(`teapot.wsCollapsed.v`,`2`),new Set(e)}return new Set(t)}catch{return new Set}})()),Ri=S(()=>{let e=new Set;for(let t of Ii())t.startsWith(`chat:`)&&e.add(t);return e}),zi=S(()=>pn(e(),new Set(e().filter(e=>Ni(e.id)).map(e=>e.id)),Vr(),Ri())),Bi=(t,r,i,a)=>{let o=new Set(Ii());if(i)o.delete(t),a&&o.delete(a);else{o.add(t),a&&o.delete(a);let i=n();i&&(t===`chat:${i}`||Fi(e().find(e=>e.id===i))===t)&&lD(`hid ${r} — click the header to show it`)}Li(o);try{localStorage.setItem(`teapot.wsCollapsed`,JSON.stringify([...o]))}catch{}},Vi=e=>e.replace(/\/+$/,``).split(/[/\\]/).pop()||e,Hi=e=>{let t=Ui().get(e)??0;return`${t} chat${t===1?``:`s`}`},Ui=S(()=>yn(e())),Wi=S(()=>bn(e(),zi(),Ii())),[Gi,Ki]=y(null),qi=new Map,Ji=()=>{g([]),qi.clear(),Yi=0},Yi=0;function Xi(e){return`${i()||(n()??`?`)}:${e.id}`}function Zi(e){let t=Array.from({length:e.length});for(let n=0;n<e.length;n++){let r=e[n],i=Xi(r),a=qi.get(i);if(t[n]=a??r,!a)for(qi.set(i,r),Yi+=wa(r);qi.size>4e3||Yi>8388608;){let e=qi.keys().next().value;if(e===void 0)break;let t=qi.get(e);t&&(Yi-=wa(t)),qi.delete(e)}}return t}let[W,Qi]=y(!1),[$i,ea]=y(!1),[ta,na]=y(!1),ra=0,ia=-1;function aa(e){let t=Zi(e);g(e=>{if(t.length>0&&e.length>0){let n=e[e.length-1],r=t.every(e=>e.seq>n.seq),i=new Set(e.map(e=>e.id));if(r&&t.every(e=>!i.has(e.id)))return[...e,...t]}let n=new Map;for(let t of e)n.set(t.id,t);let r=!1;for(let e of t)n.has(e.id)||(n.set(e.id,e),r=!0);return r?[...n.values()].sort((e,t)=>e.seq-t.seq):e})}async function oa(){let e=n();if(!e||ta()||W()||qn())return;if(h().length>=_()){na(!0);return}let t=()=>{let e=ma();return e&&e.clientHeight>0?e:null},r=0;for(;r++<20&&!ta()&&n()===e;){let r=t();if(r&&r.scrollHeight>r.clientHeight+40)return;if(h().length>=_()){na(!0);return}let i=h().length;if(await sa(),h().length===i)return;Ge(ha())&&n()===e&&va(!0)}}async function sa(){let e=n(),t=h()[0];if(e&&t&&!W()&&!ta()){Qi(!0);try{let r=ma(),a=r?.scrollHeight??0,o=r?.scrollTop??0,s=Gi(),c=i(),l=(await X(la(e,{before:t.id},c,s))).events??[];if(l.length===0){na(!0);return}if(n()!==e||h()[0]?.id!==t.id)return;aa(l),requestAnimationFrame(()=>{if(n()===e){let e=ma();e&&(e.scrollTop=o+(e.scrollHeight-a))}})}catch{}finally{Qi(!1)}}}function ca(e,t){return t&&o().has(t)?`&session=${encodeURIComponent(t)}`:``}function la(e,t,n,r){let i=[`/api/agents/${encodeURIComponent(e)}/events?limit=2000`];t.before&&i.push(`&before=${encodeURIComponent(t.before)}`),t.after&&i.push(`&after=${encodeURIComponent(t.after)}`);let a=ca(e,n);return a&&i.push(a),r&&i.push(`&branch=${encodeURIComponent(r)}&lineage=true`),i.join(``)}let ua=!1,[da,fa]=y(!1);async function pa(e,t){let r=ra,a=t??i()??``;try{let t=Gi(),i=r!==ia||!ee().length;h().length||ea(!0),X(`/api/agents/${e}/skills`).then(t=>{r===ra&&n()===e&&zo(t.skills??[])}).catch(()=>{});let[o,s]=await Promise.all([X(la(e,{},a,t)),i?X(`/api/agents/${e}/branches`):Promise.resolve({branches:ee()})]);if(i&&(ia=r),r!==ra||n()!==e)return;if(ua){ua=!1,qi.clear(),g(Zi(o.events)),fa(!1);let t=ma();t&&((ba.get(a)??ba.get(e))||(t.scrollTop=t.scrollHeight))}else g(e=>{let t=new Map;for(let n of e)t.set(n.id,n);for(let e of Zi(o.events))t.set(e.id,e);return[...t.values()].sort((e,t)=>e.seq-t.seq)});v(o.total??o.events.length),E(s.branches)}catch{ua&&(ua=!1,fa(!1),Ji())}finally{ea(!1)}}function ma(){return document.querySelector(`.feed`)}function ha(){let e=ma();return e?{top:e.scrollTop,height:e.scrollHeight,viewport:e.clientHeight}:null}function ga(){return Ge(ha())}function _a(){let e=ma();if(!e)return;let t=()=>e.isConnected?(e.scrollTop=e.scrollHeight,Qo={top:e.scrollTop,height:e.scrollHeight},!0):!1;if(!t())return;tr(0);let n=r=>{e.isConnected&&qn()&&(Ye(qn(),{top:e.scrollTop,height:e.scrollHeight,viewport:e.clientHeight})&&t(),r>0&&requestAnimationFrame(()=>n(r-1)))};requestAnimationFrame(()=>n(2)),Yn&&clearTimeout(Yn),Yn=setTimeout(()=>n(0),250)}function va(e=!1){(e||qn())&&_a()}let ya=new Map,ba=new Map,xa=new Set,Sa=(e,t=0,n=!1)=>{let r=n?e.getBoundingClientRect().top:-1/0,i=[];for(let a of e.querySelectorAll(`[data-eid]`)){let e=a.getBoundingClientRect();if(i.push({eid:a.dataset.eid??``,session:a.dataset.session??``,top:e.top+t,height:e.height}),n&&e.top>r+4)break}return i},Ca=8388608,wa=e=>at(e),Ta=(t,n)=>Tn(c().get(t),e().find(e=>e.id===t)?.session,n);async function Ea(e,t=!0,s){let l=n(),u=i(),d=h(),f=_();ra++,c().size||m();let p=Ta(e,s),ee=s&&o().has(s)?s:null,y=p??ee??``;if(l!==e||y!==u){if(u&&d.length){let e=d.reduce((e,t)=>e+wa(t),0);e<=Ca&&ya.set(u,{events:d,total:f,at:Date.now(),bytes:e}),it(ya,{maxEntries:6,maxBytes:Ca})}{let e=ma();if(fa(!0),e){let t=Sa(e,0,!0),n=t.filter(e=>!e.eid.startsWith(`@p`)),r=u||t.find(e=>e.session)?.session||``,i={top:e.scrollTop,height:e.scrollHeight,viewport:e.clientHeight},a=r?Gn(n.length?n:t,e.getBoundingClientRect().top,r):null;a&&We(i)>1?ba.set(r,a):r&&ba.delete(r)}}ri(),ua=!0,ya.get(y)?.events.length||Ji(),fa(!0),or(null),tr(0),Jn(!0),Zo=void 0}r(e),a(y),k(te.get(e)??``),Ki(null),na(!1),Qi(!1),Rr(u||l||`?`,Pr()),Fr(Lr(y||e)),localStorage.setItem(`teapot.session`,e),Ra(y,t);let b=ya.get(y);if(b?.events.length&&(g(Zi(b.events)),v(b.total),ea(!0),requestAnimationFrame(()=>{n()===e&&va(!0)})),X(`/api/agents/${e}/load`,{method:`POST`}).then(Ti).catch(()=>{}),await pa(e,y),n()!==e)return;hr(t=>{let n=t.get(e)??null,r=Dt(n,h(),V()?.status);if(r===n)return t;let i=new Map(t);return r?i.set(e,r):i.delete(e),i}),or(V()?.ctx?.compacting?{phase:String(V().ctx.compacting)}:null),Jn(!0);let x=ra;Ve(3e3);let S=performance.now()+3e3,C=()=>{if(n()!==e||x!==ra||performance.now()<we)return;let t=ma();t&&He(t),performance.now()<S&&requestAnimationFrame(C)},w=()=>{let t=ba.get(y)??ba.get(e);if(!t)return`give-up`;let r=ma();if(!r)return`wait`;let i=Sa(r,r.scrollTop);if(!i.length)return`wait`;let a=Kn(t,i,r.scrollHeight-r.clientHeight);if(a===null)return ba.delete(y),ba.delete(e),`give-up`;r.scrollTop=a,Jn(!1),we=performance.now()+400,Fe=0,ba.delete(y),ba.delete(e);let o=()=>{let e=ma();if(!e)return null;for(let n of e.querySelectorAll(`[data-eid]`))if(n.dataset.eid===t.eid&&n.dataset.session===t.session)return n;return null},s=r=>{if(n()!==e)return;let i=ma();if(!i)return;let a=o();if(!a)return;let c=i.getBoundingClientRect().top-t.offset,l=a.getBoundingClientRect().top-c;Math.abs(l)<2||r<=0||(i.scrollTop+=l,requestAnimationFrame(()=>s(r-1)))};return requestAnimationFrame(()=>s(6)),`applied`};(async()=>{if(await oa(),n()!==e||x!==ra)return;let t=performance.now()+1500,r=()=>{if(n()!==e||x!==ra)return;let i=w();i!==`applied`&&(i===`wait`&&performance.now()<t?requestAnimationFrame(r):requestAnimationFrame(C))};requestAnimationFrame(r)})()}let[Da,Oa]=y(!1),ka=null,Aa=null;T(()=>ka?.close());let ja=!1,Ma=null;document.addEventListener(`visibilitychange`,()=>Ma?.()),T(()=>{Ma=null});let Na=!0,Pa=null;async function Fa(){let e=n(),t=h().at(-1)?.id,r=i(),a=document.visibilityState===`hidden`;if(!e||!t)ja=!0,a||Pa?.();else try{let n=Gi(),i=await X(la(e,{after:t},r,n)),o=i.events??[];i.gap?(g(Zi(o)),v(o.length)):o.length&&(aa(o),v(e=>e+o.length)),await Ti(),o.length&&!a&&Ei()}catch{ja=!0}}function Ia(){Na=!0;let r=location.protocol===`https:`?`wss://`:`ws://`,a=new WebSocket(`${r}${location.host}/api/ws${gD()}`);ka=a,a.onopen=()=>{Oa(!0),Na?Na=!1:Fa()},a.onclose=()=>{Oa(!1),setTimeout(Ia,1500)},a.onerror=()=>a.close();let o=new Set([`state`,`usage`,`session_start`]);a.onmessage=r=>{let s=JSON.parse(r.data);if(s.kind===`ping`)try{a.send(JSON.stringify({kind:`pong`}))}catch{}else if(s.kind!==`pong`){if(s.kind===`hello`&&Array.isArray(s.agents)){t(e=>wi(e,s.agents));let n=e();hr(e=>Et(e,e=>n.find(t=>t.id===e)?.status))}else if(s.kind===`event`&&gt(s.event)&&hr(e=>ht(e,s.agentId)),s.kind===`llm-delta`){if(!On(s,n(),i()))return;if(hr(e=>mt(e,s.agentId,s)),s.agentId===n()){let e=String(s.reasoning??``),t=String(s.text??``);e&&!t?br()||xr(Date.now()):t&&xr(0)}}else if(s.kind===`terminal-closed`&&s.terminalId)to(e=>{let t=e.findIndex(e=>e.key===s.terminalId);return t<0?e:(lD(s.reason===`idle`?`a terminal was closed after being idle — open a new shell with +`:`a terminal exited`),e.filter((e,n)=>n!==t))});else if(s.kind===`compaction-progress`){if(s.agentId!==n())return;s.phase===`done`?or(null):or({phase:s.phase,summarized:s.summarized})}else if(s.kind===`agent-update`&&s.snapshot)t(e=>{let t=e.findIndex(e=>e.id===s.snapshot.id),n=s.snapshot;return t===-1?[...e,n]:wi(e,e.map((e,n)=>n===t?s.snapshot:e))});else if(s.kind===`metrics`&&s.metrics)O(s.metrics);else if(s.kind===`tasks`&&Array.isArray(s.tasks))Oi(s.tasks);else{if(s.kind===`event`){let e=s.event?.type,t=s.event?.data??{};if(e===`system_note`&&(t.event===`prompt-delivered`||t.event===`prompt-cancelled`)){let e=String(t.promptId??``);if(e){let t=String(s.event?.session??``),n=new Set;t&&n.add(t),n.add(Ir());for(let[t,r]of Nr)r.some(t=>t.promptId===e)&&n.add(t);for(let t of n){let n=Lr(t);n.some(t=>t.promptId===e)&&Rr(t,n.filter(t=>t.promptId!==e))}}}if(o.has(e)&&!fD.has(e)||(Zr(s.agentId,s.event),!Dn(s.event,n(),i()))||(aa([s.event]),s.event&&yr(),ja=!0,document.visibilityState!==`visible`))return;c()}document.visibilityState===`hidden`?ja=!0:c()}}};let s=0;function c(){s||=requestAnimationFrame(()=>{s=0,Aa&&=(clearTimeout(Aa),null),l()})}ja=!1;let l=async()=>{if(Aa=null,n()){let e=h().at(-1)?.id,t=h().length,r=_r();r&&!Dt(r,h(),V()?.status)&&vr(null),h().at(-1)?.id!==e&&(qn()?(_a(),Kr(n())):(tr(e=>e+Math.max(0,h().length-t)),ir(ha())))}};Pa=l,Ma=()=>{document.visibilityState===`visible`&&(Ei(),ki(),n()&&(ja?(ja=!1,l()):h().at(-1)?.id?Fa():(ja=!0,l())))}}let La=()=>decodeURIComponent(location.pathname.split(`/`)[2]??``);function Ra(e,t=!0){if(!e)return;let n=`/session/${encodeURIComponent(e)}`;t?history.pushState(null,``,n):history.replaceState(null,``,n)}window.addEventListener(`popstate`,()=>{let e=La(),t=o().get(e);t&&(t!==n()||e!==i())&&Ea(t,!1,e||null)}),x(()=>{let e=V(),t=e?`${kr()?`▶ `:e.status===`error`?`⚠ `:``}${Qn(e)} · teapot`:`teapot`;document.title=Gr()>0?`(${Gr()}) ${t}`:t});let za=()=>oe()||de()||jr()!==null||me()&&bt();window.addEventListener(`keydown`,e=>{let t=e.target;if(t&&(t.tagName===`INPUT`||t.tagName===`TEXTAREA`||t.isContentEditable))e.key===`Escape`&&t.blur();else if(e.key===`Escape`){if(oe()){se(!1);return}if(de()){fe(!1);return}if(jr()){Mr(null);return}if(me()&&bt()){Tt();return}let e=V();if(e&&kr()){X(`/api/agents/${e.id}/stop`,{method:`POST`}).then(Ti);return}}else if(!za()){if(e.key===`/`)e.preventDefault(),document.querySelector(`.composer textarea`)?.focus();else if(e.key===`d`)wt();else if(e.key===`t`)$a();else if(e.key===`ArrowDown`||e.key===`ArrowUp`){let t=zi().map(e=>e.a);if(t.length===0)return;e.preventDefault();let r=t.findIndex(e=>e.id===n()),i=e.key===`ArrowDown`?Math.min(r+1,t.length-1):Math.max(r-1,0);i!==r&&Ea(t[i].id)}}});let[Ba,Va]=y(localStorage.getItem(`teapot.term`)===`1`),[Ha,Ua]=y([]),[Wa,Ga]=y(!1),Ka=async()=>{let e=n();if(!e)return;let t=await X(`/api/agents/${encodeURIComponent(e)}/bg-jobs`).catch(()=>null);t?.jobs&&Ua(t.jobs)};x(()=>{n(),Ka()}),x(()=>{if(!Wa())return;let e=setInterval(()=>void Ka(),2e3);T(()=>clearInterval(e))});let[qa,Ja]=y(!1),[Ya,Xa]=y(``),Za=()=>{let e=V();e&&(Xa(Qn(e)),Ja(!0))},Qa=async()=>{if(!qa())return;let e=V();Ja(!1);let t=Ya().replace(/\s+/g,` `).trim();if(!e||!t||t===Qn(e))return;let n=await X(`/api/agents/${encodeURIComponent(e.id)}/session-title?session=${encodeURIComponent(e.session)}`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({title:t})}).catch(e=>({error:String(e)}));n?.error?lD(`rename failed: ${n.error}`):(d(n=>new Map(n).set(e.session,t)),Ti())},$a=()=>{let e=Ie||qn(),t=!Ba();Va(t),localStorage.setItem(`teapot.term`,t?`1`:`0`),e&&Ve(900)},[eo,to]=y([]),no=e=>{let t=(e.cwd??``).replace(/[\\/]+$/,``).split(/[\\/]/).pop();return t&&t.length<=24?t:e.title},ro=async()=>{let e=(await X(`/api/terminals`).catch(()=>null))?.terminals??[];e.length&&to(t=>t.map(t=>{let n=e.find(e=>e.id===t.key);return n?{...t,title:n.title,cwd:n.cwd}:t}))},[io,ao]=y(0),[oo,so]=y(-1),[co,lo]=y(!1),[uo,fo]=y(0),[po,mo]=y(Number(localStorage.getItem(`teapot.termH`))||Math.max(220,Math.round(window.innerHeight*.35))),ho=new Map,go=[null,null],_o=()=>eo()[uo()===0?io():oo()]??null;function vo(e){if(!eo()[e])return;let t=uo(),n=t===0?io():oo(),r=t===0?oo():io(),i=e=>t===0?ao(e):so(e);r===e?((e=>t===0?so(e):ao(e))(n),i(e)):n!==e&&i(e)}let yo=()=>bo();async function bo(e){let t=e??n();if(t){if(eo().filter(e=>e.agentId===t).length>=10)lD(`max 10 shells per agent (${t}) — that's already a lot`);else try{let e=(await X(`/api/terminals`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({agentId:t})})).terminal;if(!e){lD(`could not open a shell`);return}let n=dd(eo());to(t=>[...t,{key:e.id,agentId:e.agentId,title:e.title,cwd:e.cwd}]),uo()===0?ao(n):so(n)}catch(e){lD(`could not open a shell: ${e.message}`)}}}function xo(e){let t=eo()[e];if(!t)return;X(`/api/terminals/${encodeURIComponent(t.key)}`,{method:`DELETE`}).catch(()=>{});let n=ho.get(t.key);if(n){n.ro?.disconnect();try{n.ws.close()}catch{}n.term.dispose(),ho.delete(t.key)}let r=eo().filter((t,n)=>n!==e);to(r),ao(t=>pd(t,e,r.length)),so(t=>t===-1?-1:pd(t,e,r.length))}let So=()=>+!ue();x(()=>{Pt(),Mt(),Gt(),It(),Ht(),ue();let e=So();for(let[,t]of ho)Mn(t.term,e)});function G(){for(let[,e]of ho){e.ro?.disconnect();try{e.ws.close()}catch{}e.term.dispose()}ho.clear()}function Co(e,t){let n=ho.get(e.key);if(n&&Mn(n.term,So()),n)n.el.parentElement!==t&&(t.appendChild(n.el),setTimeout(()=>{try{n.fit()}catch{}},30));else{let r=document.createElement(`div`);r.className=`termsession`,t.appendChild(r);let i=new sd({cursorBlink:!0,fontSize:12.5,scrollSensitivity:3,fontFamily:`ui-monospace, Menlo, Consolas, monospace`,allowTransparency:!0,theme:jn(So())});i.attachCustomKeyEventHandler(e=>{if(e.type!==`keydown`||!(e.ctrlKey&&e.shiftKey)||e.altKey||e.key!==`C`&&e.key!==`c`)return!0;let t=i.getSelection();return t&&navigator.clipboard?.writeText(t).catch(()=>{}),e.preventDefault(),!1});let a=new ud;i.loadAddon(a),i.open(r);let o=location.protocol===`https:`?`wss://`:`ws://`,s=()=>`${o}${location.host}/api/agents/${encodeURIComponent(e.agentId)}/term?terminal=${encodeURIComponent(e.key)}${gD()}`,c=new WebSocket(s()),l,u=!1,d=t=>{t.onmessage=t=>{let n=JSON.parse(t.data);n.kind===`data`?i.write(n.data):n.kind===`ping`||(n.kind===`exit`?(u=!0,i.write(`\r\n\x1b[2m[terminal exited ${n.code??``}]\x1b[0m\r\n`),to(t=>t.filter(t=>t.key!==e.key)),ho.get(e.key)?.term.dispose(),ho.delete(e.key)):n.kind===`attach`&&n.error&&(u=!0,i.write(`\r\n\x1b[2m[${n.error}]\x1b[0m\r\n`)))},t.onclose=()=>{!u&&ho.has(e.key)&&(l||=(i.write(`\r
184
184
  \x1B[2m[connection lost — reconnecting…]\x1B[0m\r
185
- `),setTimeout(function(){if(l=void 0,!ho.has(e.key))return;let t=new WebSocket(s());c=t,d(t),t.addEventListener(`open`,()=>h())},1500)))}};d(c),i.onData(e=>{c.readyState===WebSocket.OPEN&&c.send(JSON.stringify({kind:`input`,data:e}))});let f={cols:0,rows:0},p,m=[],h=()=>{try{a.fit()}catch{}c.readyState===WebSocket.OPEN?(i.cols!==f.cols||i.rows!==f.rows)&&(f={cols:i.cols,rows:i.rows},c.send(JSON.stringify({kind:`resize`,cols:i.cols,rows:i.rows}))):g()};function g(){p||=setInterval(()=>{ho.has(e.key)?c.readyState===WebSocket.OPEN&&(clearInterval(p),p=void 0,h()):(clearInterval(p),p=void 0)},400)}c.addEventListener(`open`,()=>h());let _=r.parentElement??r,v=new ResizeObserver(()=>{m[0]&&clearTimeout(m[0]),m[0]=setTimeout(h,250)});v.observe(_),_!==r&&v.observe(r),setTimeout(h,60),n={el:r,term:i,fit:a,ws:c,ro:v},ho.set(e.key,n)}return n}function wo(e){let t=go[e];if(!t)return;let n=eo()[e===0?io():oo()];if(!n){[...ho.values()].some(e=>e.el.parentElement===t)&&t.replaceChildren();return}let r=Co(n,t);for(let[e,r]of ho)e!==n.key&&r.el.parentElement===t&&r.el.remove();requestAnimationFrame(()=>{r.el.parentElement!==t&&t.appendChild(r.el);try{r.fit()}catch{}if(uo()===(e===0?0:1))try{r.term.focus()}catch{}})}x(()=>{eo(),co(),io(),oo(),po(),requestAnimationFrame(()=>{wo(0),co()&&wo(1)})});let To=null;x(()=>{if(!Ba())return;let e=n();if(!e||e===To)return;To=e;let t=eo().map((e,t)=>({t:e,i:t})).filter(t=>t.t.agentId===e);t.length&&vo(t[t.length-1].i)}),x(()=>{let e=eo().length,t=fd(io(),e);if(t!==io()&&ao(t),co()){let t=fd(oo(),e);t!==oo()&&so(t)}});let Eo=e=>{e.preventDefault();let t=e.clientY,n=po(),r=e=>{let r=Math.min(Math.max(n-(e.clientY-t),140),Math.round(window.innerHeight*.85));mo(r)},i=()=>{window.removeEventListener(`pointermove`,r),window.removeEventListener(`pointerup`,i),localStorage.setItem(`teapot.termH`,String(po())),requestAnimationFrame(()=>{wo(0),co()&&wo(1)})};window.addEventListener(`pointermove`,r),window.addEventListener(`pointerup`,i)},Do=()=>{let e=!co();lo(e),e&&(oo()<0||oo()===io()||oo()>=eo().length)&&so(md(io(),eo().length)),requestAnimationFrame(()=>{wo(0),co()&&wo(1)})};T(W);let Oo=e=>t=>{go[e]=t,t&&requestAnimationFrame(()=>{wo(e),co()&&wo(1),setTimeout(()=>wo(e),200)})};w(()=>{let t=e=>{e.key===`Escape`&&nt()&&it()};window.addEventListener(`keydown`,t),T(()=>window.removeEventListener(`keydown`,t)),fi(),Ti().then(async()=>{await m();let t=La(),n=on({agents:e(),urlId:t,ownerOf:e=>o().get(e),lastId:localStorage.getItem(`teapot.session`),hideGhosts:Vr()});n&&Ea(n.id,!1,t||null)}),Ei(),ki(),Mo(),Ia(),Y(`/api/terminals`).then(e=>{let t=e.terminals??[];t.length&&(to(t.map(e=>({key:e.id,agentId:e.agentId,title:e.title,cwd:e.cwd}))),Ba()&&(ao(0),so(-1)))}).catch(()=>{}),T(()=>{})});let ko=[{cmd:`/start`,desc:`start working toward the goal`},{cmd:`/stop`,desc:`interrupt the running agent`},{cmd:`/fork`,desc:`branch the conversation here`},{cmd:`/goal`,desc:`/goal <text> — set goal & notify the agent`},{cmd:`/compact`,desc:`force a context compaction now`},{cmd:`/skill`,desc:`/skill <name> — force-load a skill and follow it`}],[Ao,jo]=y([]),Mo=()=>Y(`/api/personas`).then(e=>jo(e.personas)).catch(()=>{}),[No,Po]=y(!1),Fo=()=>{let e=re().match(/^@([A-Za-z0-9._-]*)$/);return e?e[1].toLowerCase():null},Io=()=>{let t=Fo();return t===null?[]:[...Ao().map(e=>({key:e.key,label:`${e.label} — spawns a sub-agent`,kind:`persona`})),...e().filter(e=>e.id!==n()).map(e=>({key:e.id,label:`${e.status} — send directly`,kind:`agent`}))].filter(e=>e.key.toLowerCase().startsWith(t))},Lo=new Set([`start`,`stop`,`fork`,`compact`]),[Ro,zo]=y([]),[Bo,Vo]=y(null),[Ho,Uo]=y(-1),Wo=()=>{let e=re();if(!e.startsWith(`/`)||e.includes(`
185
+ `),setTimeout(function(){if(l=void 0,!ho.has(e.key))return;let t=new WebSocket(s());c=t,d(t),t.addEventListener(`open`,()=>h())},1500)))}};d(c),i.onData(e=>{c.readyState===WebSocket.OPEN&&c.send(JSON.stringify({kind:`input`,data:e}))});let f={cols:0,rows:0},p,m=[],h=()=>{try{a.fit()}catch{}c.readyState===WebSocket.OPEN?(i.cols!==f.cols||i.rows!==f.rows)&&(f={cols:i.cols,rows:i.rows},c.send(JSON.stringify({kind:`resize`,cols:i.cols,rows:i.rows}))):g()};function g(){p||=setInterval(()=>{ho.has(e.key)?c.readyState===WebSocket.OPEN&&(clearInterval(p),p=void 0,h()):(clearInterval(p),p=void 0)},400)}c.addEventListener(`open`,()=>h());let _=r.parentElement??r,v=new ResizeObserver(()=>{m[0]&&clearTimeout(m[0]),m[0]=setTimeout(h,250)});v.observe(_),_!==r&&v.observe(r),setTimeout(h,60),n={el:r,term:i,fit:a,ws:c,ro:v},ho.set(e.key,n)}return n}function wo(e){let t=go[e];if(!t)return;let n=eo()[e===0?io():oo()];if(!n){[...ho.values()].some(e=>e.el.parentElement===t)&&t.replaceChildren();return}let r=Co(n,t);for(let[e,r]of ho)e!==n.key&&r.el.parentElement===t&&r.el.remove();requestAnimationFrame(()=>{r.el.parentElement!==t&&t.appendChild(r.el);try{r.fit()}catch{}if(uo()===(e===0?0:1))try{r.term.focus()}catch{}})}x(()=>{eo(),co(),io(),oo(),po(),requestAnimationFrame(()=>{wo(0),co()&&wo(1)})});let To=null;x(()=>{if(!Ba())return;let e=n();if(!e||e===To)return;To=e;let t=eo().map((e,t)=>({t:e,i:t})).filter(t=>t.t.agentId===e);t.length&&vo(t[t.length-1].i)}),x(()=>{let e=eo().length,t=fd(io(),e);if(t!==io()&&ao(t),co()){let t=fd(oo(),e);t!==oo()&&so(t)}});let Eo=e=>{e.preventDefault();let t=e.clientY,n=po(),r=e=>{let r=Math.min(Math.max(n-(e.clientY-t),140),Math.round(window.innerHeight*.85));mo(r)},i=()=>{window.removeEventListener(`pointermove`,r),window.removeEventListener(`pointerup`,i),localStorage.setItem(`teapot.termH`,String(po())),requestAnimationFrame(()=>{wo(0),co()&&wo(1)})};window.addEventListener(`pointermove`,r),window.addEventListener(`pointerup`,i)},Do=()=>{let e=!co();lo(e),e&&(oo()<0||oo()===io()||oo()>=eo().length)&&so(md(io(),eo().length)),requestAnimationFrame(()=>{wo(0),co()&&wo(1)})};T(G);let Oo=e=>t=>{go[e]=t,t&&requestAnimationFrame(()=>{wo(e),co()&&wo(1),setTimeout(()=>wo(e),200)})};w(()=>{let t=e=>{e.key===`Escape`&&tt()&&rt()};window.addEventListener(`keydown`,t),T(()=>window.removeEventListener(`keydown`,t)),fi(),Ti().then(async()=>{await m();let t=La(),n=an({agents:e(),urlId:t,ownerOf:e=>o().get(e),lastId:localStorage.getItem(`teapot.session`),hideGhosts:Vr()});n&&Ea(n.id,!1,t||null)}),Ei(),ki(),Mo(),Ia(),X(`/api/terminals`).then(e=>{let t=e.terminals??[];t.length&&(to(t.map(e=>({key:e.id,agentId:e.agentId,title:e.title,cwd:e.cwd}))),Ba()&&(ao(0),so(-1)))}).catch(()=>{}),T(()=>{})});let ko=[{cmd:`/start`,desc:`start working toward the goal`},{cmd:`/stop`,desc:`interrupt the running agent`},{cmd:`/fork`,desc:`branch the conversation here`},{cmd:`/goal`,desc:`/goal <text> — set goal & notify the agent`},{cmd:`/compact`,desc:`force a context compaction now`},{cmd:`/skill`,desc:`/skill <name> — force-load a skill and follow it`}],[Ao,jo]=y([]),Mo=()=>X(`/api/personas`).then(e=>jo(e.personas)).catch(()=>{}),[No,Po]=y(!1),Fo=()=>{let e=ne().match(/^@([A-Za-z0-9._-]*)$/);return e?e[1].toLowerCase():null},Io=()=>{let t=Fo();return t===null?[]:[...Ao().map(e=>({key:e.key,label:`${e.label} — spawns a sub-agent`,kind:`persona`})),...e().filter(e=>e.id!==n()).map(e=>({key:e.id,label:`${e.status} — send directly`,kind:`agent`}))].filter(e=>e.key.toLowerCase().startsWith(t))},Lo=new Set([`start`,`stop`,`fork`,`compact`]),[Ro,zo]=y([]),[Bo,Vo]=y(null),[Ho,Uo]=y(-1),Wo=()=>{let e=ne();if(!e.startsWith(`/`)||e.includes(`
186
186
  `))return[];let t=e.match(/^\/([a-z]*)(?:\s+(.*))?$/i);if(!t)return[];let n=t[1].toLowerCase(),r=(t[2]??``).trim();if(!r&&n!==`skill`){let e=ko.filter(e=>e.cmd.slice(1).startsWith(n));return e.find(e=>e.cmd.slice(1)===n)&&Lo.has(n)?[]:e.map(e=>({insert:e.cmd+` `,title:e.desc}))}if(n===`skill`){let e=Ro().filter(e=>e.name.toLowerCase().startsWith(r.toLowerCase()));return e.length===1&&e[0].name.toLowerCase()===r.toLowerCase()?[]:e.map(e=>({insert:`/skill ${e.name} `,title:e.description||`(bundled skill)`}))}return[]},Go,Ko,qo,Jo=!1;function Yo(e){if(!Ko){Ko=document.createElement(`div`),Ko.setAttribute(`aria-hidden`,`true`);let e=Ko.style;e.position=`absolute`,e.visibility=`hidden`,e.pointerEvents=`none`,e.top=`0`,e.left=`-9999px`,e.whiteSpace=`pre-wrap`,e.overflowWrap=`anywhere`,e.wordBreak=`break-word`,Ko.dataset.mirror=``}let t=getComputedStyle(e);for(let e of[`font-family`,`font-size`,`font-weight`,`line-height`,`letter-spacing`,`padding-top`,`padding-bottom`,`padding-left`,`padding-right`,`border-top-width`,`border-bottom-width`,`box-sizing`])Ko.style.setProperty(e,t.getPropertyValue(e));if(Ko.style.width=`${e.clientWidth}px`,Ko.setAttribute(`data-mirror-text`,e.value.endsWith(`
187
- `)?`${e.value} `:e.value),qo||(qo=document.createElement(`div`),qo.setAttribute(`aria-hidden`,`true`),qo.style.cssText=`position:absolute;left:-9999px;top:0;pointer-events:none`,document.body.appendChild(qo)),Ko.parentElement!==qo&&qo.appendChild(Ko),!Jo){let e=document.createElement(`style`);e.textContent=`[data-mirror]::after{content:attr(data-mirror-text);white-space:pre-wrap;display:block}`,document.head.appendChild(e),Jo=!0}return Ko.scrollHeight}let Xo=()=>{if(!Go)return;let e=Pn();if(!Go.value&&!e){Go.style.height=``;return}let t=Yo(Go),n=e?-1:Hn(t,360);Go.style.height=n===-1?``:`${n}px`},Zo,Qo=null,$o,es=240,ts=1200,ns;x(()=>{let e=re();Go&&Bn(lD)&&(Vn(Go.value,e)&&(Go.value=e),Xo())}),w(()=>{let e=0,t=()=>{e||=requestAnimationFrame(()=>{e=0,Xo()})};window.addEventListener(`resize`,t),T(()=>{window.removeEventListener(`resize`,t),e&&cancelAnimationFrame(e)})});let[rs,is]=y([]),as=e=>{let t=Array.from(e).filter(e=>e.type.startsWith(`image/`));for(let e of t){if(e.size>8e6){cD(`"${e.name}" is over 8 MB — skipped`);continue}let t=new FileReader;t.onload=()=>{is(n=>[...n,{url:String(t.result),name:e.name}].slice(0,4))},t.readAsDataURL(e)}},os=async(t,r)=>{let i=r??n();if(!i)return;let a=rs(),o=e().find(e=>e.id===i)?.session||i,s=qn(),c=Tn((B()?.status??``)===`running`),l=`@p${Date.now()}${Math.random().toString(36).slice(2,6)}`;Rr(o,[...Lr(o),{id:l,text:t,at:Date.now(),...c?{queued:!0}:{},...a.length?{images:a.map(e=>e.url)}:{}}]);try{let e=await Y(`/api/agents/${i}/prompt`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({text:t,start:!0,clientId:l,...a.length?{images:a}:{}})}),n=e.promptId,r=e.ahead;(n||typeof r==`number`)&&Rr(o,Lr(o).map(e=>e.id===l?{...e,...n?{promptId:n}:{},...typeof r==`number`?{queued:r>0}:{}}:e)),is([]),_d(Pn())&&In(!1),Xo(),s&&(Jn(!0),tr(0),Te=0,He(700))}catch(e){Rr(o,Lr(o).filter(e=>e.id!==l)),O(t),console.error(`send failed:`,e)}},ss=async t=>{t.preventDefault();let r=n(),i=re().trim();if(r&&i){if(i.startsWith(`@`)){let t=i.indexOf(` `),r=(t===-1?i.slice(1):i.slice(1,t)).toLowerCase(),a=t===-1?``:i.slice(t+1).trim(),o=Ao().some(e=>e.key.toLowerCase()===r),s=e().some(e=>e.id.toLowerCase()===r);try{if(o){if(!a){cD(`usage: @${r} <task>`);return}cD(`🧩 spawned ${(await Y(`/api/agents/${n()}/spawn`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({persona:r,task:a,context:No()?`fork`:`none`})})).id}${No()?` (forked context)`:``}`),Ti(),O(``)}else if(s){if(!a){cD(`usage: @${r} <message>`);return}await Y(`/api/agents/${encodeURIComponent(r)}/prompt`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({text:a,start:!0})}),cD(`→ delivered to @${r}`),O(``)}else{cD(`unknown @${r} — personas: ${Ao().map(e=>e.key).join(`, `)||`(none)`}`);return}}catch(e){cD(`@${r} failed: ${e.message}`)}}else if(i.startsWith(`/`)){let e=i.indexOf(` `),t=(e===-1?i.slice(1):i.slice(1,e)).toLowerCase(),n=e===-1?``:i.slice(e+1).trim();if(t===`goal`&&!n){O(`/goal `);return}if(t===`skill`&&!n){O(`/skill `);return}O(``);try{await cs(t,n)}catch(e){throw O(re()?`${i}\n${re()}`:i),e}}else O(``),await os(i)}},cs=async(e,t)=>{let r=n();if(!r)return;let i=(e,t)=>Y(`/api/agents/${r}${e}`,{method:`POST`,headers:{"content-type":`application/json`},...t===void 0?{}:{body:JSON.stringify(t)}}).then(Ti);try{if(e===`start`)await i(`/start`);else if(e===`stop`)await i(`/stop`);else if(e===`fork`)await i(`/fork`,{}),await Ea(r);else if(e===`compact`)cD((await i(`/compact`))?.ran?`context compacted`:`nothing to compact yet`);else if(e===`goal`){if(!t){cD(`usage: /goal <text>`);return}await i(`/goal`,{text:t,notify:!0}),cD(`goal saved & notification queued`)}else if(e===`skill`){if(!t){cD(`usage: /skill <name>`);return}await i(`/skill`,{name:t}),cD(`skill "${t}" dispatched`)}else cD(`unknown command "${e}" — /start /stop /fork /goal /skill /compact`)}catch(t){cD(`/${e} failed: ${t.message}`)}},ls,us=0;x(()=>{e(),requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!ls)return;let e=Math.min(us,ls.scrollHeight);Math.abs(ls.scrollTop-e)>1&&(ls.scrollTop=e)})})});let ds=e=>()=>n()&&Y(`/api/agents/${n()}${e}`,{method:`POST`}).then(Ti),fs=async()=>{let i=n();if(!i)return;let a=new Set([i,...vn(e(),i).map(e=>e.id)]),o=a.size-1;if(!confirm(`archive agent ${i}?\n\n`+(o>0?`Its ${o} sub-agent${o===1?``:`s`} will be archived too.\n\n`:``)+`They stop running and leave the list, but the config and full session history are KEPT — restore any of them from ⚙️ settings → archive.`))return;await Y(`/api/agents/${i}/archive`,{method:`POST`}).catch(()=>{}),t(e().filter(e=>!a.has(e.id))),m(!0);let s=hd(e(),a);s?Ea(s.id):(r(null),Ji())},ps=async()=>{n()&&(cD(`stopped: ${((await Y(`/api/agents/${n()}/stop-children`,{method:`POST`})).stopped??[]).join(`, `)||`(none)`}`),Ti())},ms=()=>Y(`/api/agents/${B().id}/fork`,{method:`POST`,headers:{"content-type":`application/json`},body:`{}`}).then(async()=>{await m(!0),await Ea(B().id)}),[hs,gs]=y(``),_s=()=>({"max-height":`none`,"overflow-y":`auto`,resize:`vertical`}),vs=e=>{T(Zn(e,`goalPreview`))},G=e=>{T(Zn(e,`goal`))},[ys,bs]=y(``),[xs,Ss]=y(!1),[Cs,ws]=y(!0),Ts=``;x(()=>{let e=n();e&&(B()?.goal,e!==Ts&&(Ts=e,Ss(!1),gs(``),bs(``)))});let Es=async e=>{if(e.preventDefault(),n()&&hs().trim())try{await Y(`/api/agents/${n()}/goal`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({text:hs(),notify:Cs(),...ys().trim()?{verify:ys()}:{}})}),gs(``),bs(``),Ss(!1),Ti()}catch(e){cD(`goal save failed: ${e.message}`)}};return[A(M,{get when(){return pi()},get children(){var e=Xw();return e.firstChild.firstChild.nextSibling.addEventListener(`submit`,e=>{e.preventDefault();let t=document.getElementById(`pw-input`);localStorage.setItem(`teapot.token`,t.value),location.reload()}),e}}),A(M,{get when(){return de()},children:e=>(()=>{var t=PT(),n=t.firstChild;return b(t=>{var r=pn(e(),cn[cn.length-1]),i=fn(e());return r!==t.e&&F(n,`src`,t.e=r),i!==t.t&&F(n,`srcset`,t.t=i),t},{e:void 0,t:void 0}),t})()}),(()=>{var t=kT(),r=t.firstChild,i=r.firstChild,a=i.nextSibling.firstChild,o=a.firstChild;o.firstChild;var s=a.nextSibling,c=s.firstChild.firstChild.nextSibling;c.firstChild;var l=c.nextSibling,d=s.nextSibling,f=r.nextSibling,p=f.nextSibling,m=p.firstChild;m.firstChild,L(t,A(M,{get when(){return N(()=>!!ge())()&&At()},get children(){var e=Zw();return e.$$click=Mt,e}}),r),L(r,A(M,{get when(){return ge()},get children(){var e=Qw(),t=e.firstChild.nextSibling;return t.$$click=Mt,e}}),i),L(i,A(j,{get each(){return Wi()},children:t=>[A(M,{get when(){return N(()=>t.wsHeader!==void 0)()&&t.wsHeader!==``},get children(){var e=IT(),n=e.firstChild,r=n.nextSibling;return e.$$click=()=>Bi(`ws:${t.wsHeader}`,Vi(t.wsHeader),t.wsCollapsedGroup===!0,t.collapsedVia),L(n,()=>t.wsCollapsedGroup?`▸`:`▾`),L(r,()=>Vi(t.wsHeader)),L(e,A(M,{get when(){return t.wsCollapsedGroup},get children(){var e=FT();return L(e,()=>Ui().get(t.wsHeader)??0),e}}),null),b(n=>{var i=t.wsCollapsedGroup?`${t.wsHeader} — collapsed (${Hi(t.wsHeader)} hidden). Click to show.`:(Ui().get(t.wsHeader)??0)>1?`${t.wsHeader} — ${Hi(t.wsHeader)} in this directory`:t.wsHeader||``,a=t.wsHeader;return i!==n.e&&F(e,`title`,n.e=i),a!==n.t&&F(r,`title`,n.t=a),n},{e:void 0,t:void 0}),e}}),A(M,{get when(){return N(()=>!t.headerOnly)()&&!t.wsCollapsedGroup},get children(){var r=VT(),i=r.firstChild,a=i.nextSibling;return r.$$click=()=>Ea(t.a.id),L(r,A(M,{get when(){return gn({isSub:!!t.a.parent,collapsed:t.chatCollapsedGroup===!0,hasChildren:e().some(e=>e.parent===t.a.id)})},get fallback(){return HT()},get children(){return(()=>{let e=!t.a.parent,n=e&&Ri().has(`chat:${t.a.id}`)||Ni(t.a.id);return(()=>{var r=UT();return r.$$click=r=>{if(r.stopPropagation(),e){if(n){if(!V().has(t.a.id)){let e=new Set(V());e.add(t.a.id),ji(e),localStorage.setItem(`teapot.expandedSubs`,JSON.stringify([...e]))}if(Mi().has(t.a.id)){let e=new Set(Mi());e.delete(t.a.id),H(e),localStorage.setItem(`teapot.collapsed`,JSON.stringify([...e]))}}else if(V().has(t.a.id)){let e=new Set(V());e.delete(t.a.id),ji(e),localStorage.setItem(`teapot.expandedSubs`,JSON.stringify([...e]))}Bi(`chat:${t.a.id}`,t.a.id,n)}else Pi(t.a.id)},L(r,n?`▸`:`▾`),b(()=>F(r,`title`,e?n?`show ${t.a.id}`:`hide ${t.a.id} and its sub-agents`:n?`expand sub-agents`:`collapse sub-agents`)),r})()})()}}),i),L(a,()=>Qn({id:t.a.id,sessionTitle:t.a.sessionTitle??u().get(t.a.session??``)})),L(r,(()=>{var e=N(()=>!!t.a.workspaceMissing);return()=>e()?WT():null})(),null),L(r,A(M,{get when(){return Jr(t.a.id)>0},get children(){var e=LT();return e.firstChild,L(e,()=>Jr(t.a.id),null),b(()=>F(e,`title`,`${Jr(t.a.id)} unread notification${Jr(t.a.id)>1?`s`:``} (including sub-agents)`)),e}}),null),L(r,A(M,{get when(){return Ni(t.a.id)||t.chatCollapsedGroup===!0&&Ri().has(`chat:${t.a.id}`)},get children(){return(()=>{let n=vn(e(),t.a.id),r=n.filter(e=>e.live??(e.status===`running`||e.status===`waiting`||e.status===`needs_operator`)).length;return n.length>0?(()=>{var e=GT();return e.firstChild,I(e,`subcount`+(r>0?` live`:``)),L(e,()=>n.length,null),L(e,r>0?` · ▶${r}`:``,null),b(()=>F(e,`title`,`${n.length} sub-agent${n.length>1?`s`:``} (${r} active)`)),e})():null})()}}),null),L(r,A(M,{get when(){return t.a.parent},get children(){return RT()}}),null),L(r,A(M,{get when(){return Ai(t.a.id).length>0},get children(){var e=zT();return b(()=>F(e,`title`,Ai(t.a.id).map(e=>`${e.id}: ${e.schedule}`).join(`
188
- `))),e}}),null),L(r,A(M,{get when(){return t.a.goal.status===`done`},get children(){return BT()}}),null),b(e=>{var o=`agent-item`+(t.a.id===n()?` sel`:``)+(t.depth>0?` sub-row`:``)+(t.chatCollapsedGroup?` collapsed`:``),s=t.depth>0?`padding-left:${10+t.depth*14}px`:``,c=t.a.parent?(()=>{let e=_n(t.a.id,Ao().map(e=>e.key));return e?`sub-agent of @${t.a.parent} — "${e}"`:`sub-agent of @${t.a.parent}`})():void 0,l=`dot ${t.a.status}`,d=t.a.status===`needs_operator`?`waiting for your answer`:t.a.status===`waiting`?`waiting on its own work — resumes by itself`:t.a.status,f=t.a.workspaceMissing?` ghost`:``,p=t.a.workspaceMissing?`workspace not found on disk (${t.a.workspace}) — it will be created when this session runs`:$n({id:t.a.id,sessionTitle:t.a.sessionTitle??u().get(t.a.session??``)});return o!==e.e&&I(r,e.e=o),e.t=ke(r,s,e.t),c!==e.a&&F(r,`title`,e.a=c),l!==e.o&&I(i,e.o=l),d!==e.i&&F(i,`title`,e.i=d),f!==e.n&&I(a,e.n=f),p!==e.s&&F(a,`title`,e.s=p),e},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0}),r}})]})),o.$$click=e=>{e.stopPropagation(),Wr(!Ur()),Ur()||Br(e=>e.map(e=>({...e,read:!0})))},L(o,A(M,{get when(){return Gr()>0},get children(){var e=$w();return L(e,Gr),e}}),null),L(a,A(Sd,{icon:`👻`,get active(){return Vr()},get title(){return Vr()?`show ghost sessions again (👻 workspace missing on disk)`:`hide ghost sessions (👻 — their workspace directory no longer exists)`},onClick:t=>{t.stopPropagation();let r=!Vr();if(Hr(r),localStorage.setItem(`teapot.hideGhosts`,r?`1`:`0`),r&&n()&&B()?.workspaceMissing){let t=e().find(e=>!e.workspaceMissing);t&&Ea(t.id)}}}),null),L(a,A(Sd,{icon:`+`,title:`new agent`,onClick:()=>{fi(),ce(!0)}}),null),L(a,A(Sd,{icon:`⚙️`,title:`settings`,onClick:()=>{fi(),pe(!0)}}),null),L(c,`0.37.172`,null),L(d,A(M,{get when(){return E()},get children(){return[`master rss `,N(()=>E().rssMb),`MB · heap `,N(()=>E().heapUsedMb),`MB`,A(M,{get when(){return E().heapTotalMb!==void 0},get children(){return[` · total `,N(()=>E().heapTotalMb),`MB`]}}),A(M,{get when(){return E().externalMb!==void 0},get children(){return[` · ext `,N(()=>E().externalMb),`MB`]}}),A(M,{get when(){return E().arrayBuffersMb!==void 0},get children(){return[` · buf `,N(()=>E().arrayBuffersMb),`MB`]}}),eT(),A(M,{get when(){return E().messagesInMemory!==void 0},get children(){return[`msgs `,N(()=>E().messagesInMemory),` in `,N(()=>E().loadedSessions),` loaded session(s)`,eT()]}}),`load1 `,N(()=>E().loadavg1),` · up `,N(()=>Math.floor(E().uptimeSec/60)),`m`]}})),L(f,A(M,{get when(){return B()?.id},get fallback(){return KT()},get children(){return[(()=>{var t=sT(),r=t.firstChild,i=r.nextSibling,a=i.nextSibling,o=a.firstChild,s=o.nextSibling,c=s.nextSibling.nextSibling,l=c.nextSibling.nextSibling,u=l.nextSibling.nextSibling;u.nextSibling;var d=a.nextSibling,f=d.firstChild,p=f.nextSibling;return L(t,A(M,{get when(){return ge()},get children(){var e=tT();return e.$$click=()=>jt(!At()),b(()=>F(e,`aria-expanded`,At())),e}}),r),r.$$click=()=>Za(),L(t,A(M,{get when(){return qa()},get fallback(){return(()=>{var e=qT();return e.$$click=()=>Za(),L(e,()=>Qn(B())),b(()=>F(e,`title`,`${$n(B(),B().session)} — click to rename`)),e})()},get children(){var e=nT();return e.addEventListener(`blur`,()=>void Qa()),e.$$keydown=e=>{e.key===`Enter`?(e.preventDefault(),Qa()):e.key===`Escape`&&(e.preventDefault(),Ja(!1))},e.$$input=e=>Xa(e.currentTarget.value),je(e=>{requestAnimationFrame(()=>{e.focus(),e.select()})},e),F(e,`spellcheck`,!1),b(()=>e.value=Ya()),e}}),i),L(i,()=>B().status),L(t,A(M,{get when(){return Or()>0},get children(){var e=rT(),t=e.firstChild.nextSibling,n=t.nextSibling.nextSibling;return n.nextSibling,L(e,Or,t),L(e,()=>Or()===1?`message`:`messages`,n),L(e,()=>B().status===`stopped`?` (stopped)`:``,null),b(()=>F(e,`title`,(()=>{let e=B().pendingPromptQueue??[],t=e.length||B().pendingPromptIds?.length||B().pendingPrompts||0,n=e.length?e.filter(e=>(e.source??`user`)===`user`).length:t,r=t-n;return`${`${t} message${t>1?`s`:``} queued${r?` — ${n} from you, ${r} from the harness`:` from you`}`}. ${B().status===`stopped`?`This agent is STOPPED, so nothing will run until you press start (or it is resumed).`:`They are handed to the model at its next turn boundary — the timeline shows them as queued… until then.`}`+(n?` Yours can be withdrawn with ✕ cancel while still queued.`:``)})())),e}}),a),L(t,A(M,{get when(){return(B()?.bgRunning??0)>0},get children(){var e=iT();return e.firstChild,e.$$click=()=>{Ga(!Wa()),Wa()&&Ka()},L(e,()=>B().bgRunning,null),b(t=>{var n=Wa(),r=`${B().bgRunning} background shell(s) running — click to inspect`;return n!==t.e&&F(e,`aria-expanded`,t.e=n),r!==t.t&&F(e,`title`,t.t=r),t},{e:void 0,t:void 0}),e}}),a),L(t,A(M,{get when(){return Ai(B().id).length>0},get children(){var e=aT();return e.firstChild,L(e,()=>Ai(B().id).length,null),b(()=>F(e,`title`,`scheduled tasks:\n${Ai(B().id).map(e=>`${e.schedule} · ${e.id}${e.forked?` (forked)`:``}`).join(`
189
- `)}`)),e}}),a),L(a,()=>B().model,o),L(a,()=>B().session,s),L(a,()=>B().branch,c),L(a,()=>B().stats.turns,l),L(a,()=>B().stats.toolCalls,u),f.$$click=()=>(kr()?ds(`/stop`):ds(`/start`))(),L(f,()=>kr()?`■ stop`:`▶ start`),L(d,A(M,{get when(){return e().some(e=>e.parent===n())},get children(){return A(Sd,{icon:`⏹`,title:`stop every sub-agent this agent spawned (descendants included)`,onClick:ps})}}),p),L(d,A(Sd,{icon:`🗄`,title:`archive this agent — reversible: it leaves the list but keeps its config and history (restore in ⚙️ settings → archive)`,onClick:fs}),null),L(d,A(Sd,{icon:`⑂`,title:`fork: branch off the conversation here — try things without disturbing the main line`,onClick:ms}),null),L(d,A(Sd,{icon:`⌨`,title:`terminal (t)`,onClick:$a}),null),L(d,A(Sd,{icon:`▤`,title:`toggle details panel (d)`,get active(){return xt()},onClick:Tt}),null),L(t,A(M,{get when(){return Wa()},get children(){var e=oT(),t=e.firstChild.firstChild.nextSibling;return t.$$click=()=>Ga(!1),L(e,A(M,{get when(){return Ha().length>0},get fallback(){return JT()},get children(){return A(j,{get each(){return Ha()},children:e=>(()=>{var t=XT(),n=t.firstChild.firstChild,r=n.nextSibling,i=r.nextSibling,a=i.nextSibling;return L(r,()=>Ux(e.cmd,80)),L(i,(()=>{var t=N(()=>!!e.detached);return()=>t()?`detached · pid ${e.pid??`?`}`:N(()=>!!e.running)()?ft(Date.now()-e.startedAt):`exit ${e.code??`?`}`})(),null),L(i,()=>e.truncated?` · truncated`:``,null),a.$$click=async()=>{await Y(`/api/agents/${encodeURIComponent(B().id)}/bg-jobs/${encodeURIComponent(e.id)}`,{method:`DELETE`}).catch(()=>{}),await Ka()},L(a,(()=>{var t=N(()=>!!e.detached);return()=>t()?`forget`:e.running?`kill`:`clear`})()),L(t,A(M,{get when(){return e.tail.trim()},get fallback(){return A(M,{get when(){return e.detached},get children(){var t=ZT(),n=t.firstChild.nextSibling;return n.nextSibling,L(t,()=>e.pid??`?`,n),t}})},get children(){var t=YT();return L(t,()=>e.tail),t}}),null),b(t=>{var i=`bgjob-dot `+(e.running?`running`:`done`),o=e.running?`running`:`finished`,s=e.cmd,c=e.detached?`this job survived a harness restart (pid ${e.pid??`?`}) — its output can no longer be read here; stop it yourself if needed`:e.running?`kill this job (whole process group)`:`forget this finished job`;return i!==t.e&&I(n,t.e=i),o!==t.t&&F(n,`title`,t.t=o),s!==t.a&&F(r,`title`,t.a=s),c!==t.o&&F(a,`title`,t.o=c),t},{e:void 0,t:void 0,a:void 0,o:void 0}),t})()})}}),null),e}}),null),b(e=>{var t=`badge ${B().status}`,n=B().statusReason&&!/^(round complete|prompt|api start|goal set|created via web|start)$/.test(B().statusReason)?`${B().status} — ${B().statusReason}`:void 0,r=`${B().model} · ${B().session}/${B().branch} · turns ${B().stats.turns} · tools ${B().stats.toolCalls}`,o=`runbtn`+(kr()?` danger`:``),s=kr()?`interrupt: aborts the current LLM call; the running tool finishes first`:`run toward the goal (starts the loop)`;return t!==e.e&&I(i,e.e=t),n!==e.t&&F(i,`title`,e.t=n),r!==e.a&&F(a,`title`,e.a=r),o!==e.o&&I(f,e.o=o),s!==e.i&&F(f,`title`,e.i=s),e},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),t})(),(()=>{var e=gT();return e.addEventListener(`scroll`,e=>{let t=e.currentTarget,r={top:t.scrollTop,height:t.scrollHeight,viewport:t.clientHeight},i=qe(r,Qo,$o,ns);Qo=null,we=performance.now();let a=Zo?.top,o=Zo?.height;$o=r.height,ns=r.viewport,Zo=r,ir(r);let s=qn(),c=performance.now();c-be>100&&(be=c,ye=vt(t));let l=o!==void 0&&Math.abs(r.height-o)>.5,u=a!==void 0&&r.top<a-.5&&!l;u&&(Te=performance.now()+400);let d=u?!1:Ke(r)?!0:performance.now()<Te?!1:Ye(s,i,r,a);d===s?Le=d:Re(d),d&&i!==`reader`?(Xn()&&tr(0),qr(),Je(d,r)&&Ge(r)>0&&_a()):d&&Ke(r)&&(Xn()&&tr(0),qr()),r.top<=4&&n()&&!U()&&!ta()&&h().length>0&&sa()}),je(e=>ut(e),e),L(e,A(M,{get when(){return ar()},children:e=>(()=>{var t=QT();return t.firstChild,L(t,(()=>{var t=N(()=>e().phase===`harvesting`);return()=>t()?`saving durable lessons…`:`summarizing ${e().summarized?Hx(e().summarized)+` `:``}older messages…`})(),null),t})()}),null),L(e,A(M,{get when(){return N(()=>!!ta())()&&oi().length>0},get children(){return cT()}}),null),L(e,A(M,{get when(){return U()},get children(){return lT()}}),null),L(e,A(M,{get when(){return oi().length>0},get fallback(){return N(()=>!!($i()||da()))()?$T():eE()},get children(){return[A(j,{get each(){return oi()},children:e=>A(gC,{e,prev:()=>li(e,-1),next:()=>li(e,1),get showBranch(){return ee().length>1},res:()=>$r().resFor.get(e.id),get orphan(){return $r().orphanCalls.has(e.id)},onOption:e=>void os(e),answeredIds:ii,onAnswered:ni,get agentActive(){return N(()=>!!Ar())()&&wt(e)},onResize:()=>{qn()&&_a()},get agentId(){return n()??void 0},get onCancel(){return e.data?.source===`user`&&e.data?.pending&&e.data?.sent!==!0?()=>{let t=Lr(Ir()).find(t=>t.id===e.id),r=String(t?.promptId??e.data?.promptId??``);if(!r){cD(`still being sent — try again in a moment`);return}let i=qn();Y(`/api/agents/${n()}/prompt/cancel`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({promptId:r})}).then(e=>{let t=String(e.text??``);O(re()?`${t}\n\n${re()}`:t),xa.add(r),Rr(Ir(),Pr().filter(e=>e.promptId!==r));let n=ma();i?He(400):n&&(ye=vt(n),be=performance.now()),cD(`message withdrawn — draft restored`)}).catch(()=>cD(`withdraw failed — it may have already been sent`))}:void 0},get onEdit(){return e.type===`prompt`&&e.data?.source===`user`&&!(e.data?.pending&&e.data?.sent!==!0)&&!e.data?.cancelled?async()=>{kr()&&(await Y(`/api/agents/${n()}/stop`,{method:`POST`}).catch(()=>{}),await Ti()),Mr({eventId:e.id,text:String(e.data?.text??``)})}:void 0}})}),A(M,{get when(){return da()},get children(){return uT()}}),A(M,{get when(){return N(()=>!!$i())()&&!da()},get children(){return dT()}}),A(M,{get when(){return N(()=>!!Ar())()&&_r()},get children(){var e=hT(),t=e.firstChild.nextSibling;return t.firstChild,L(t,A(M,{get when(){return Cr().trim()!==``},get children(){var e=fT(),t=e.firstChild;t.firstChild;var n=t.nextSibling;return L(t,A(Xd,{get startedAt(){return Sr()}}),null),je(e=>{let t=!0;e.addEventListener(`scroll`,()=>{t=e.scrollHeight-e.scrollTop-e.clientHeight<24}),x(()=>{Cr(),t&&(e.scrollTop=e.scrollHeight)})},n),L(n,Cr),e}}),null),L(t,A(M,{get when(){return R()},get fallback(){return tE()},get children(){return A(M,{get when(){return ur()},get fallback(){return(()=>{var e=mT();return b(()=>e.innerHTML=ze(R()+`▍`)),e})()},get children(){return[pT(),(()=>{var e=mT();return b(()=>e.innerHTML=ze(fr()+`▍`)),e})()]}})}}),null),e}})]}}),null),e})(),A(M,{get when(){return nt()},children:e=>(()=>{var t=nE(),n=t.firstChild;return Oe(t,`click`,it,!0),n.$$click=e=>e.stopPropagation(),b(()=>F(n,`src`,e())),t})()}),A(M,{get when(){return Ba()},get children(){var t=xT(),n=t.firstChild,r=n.nextSibling,i=r.firstChild,a=i.nextSibling,o=a.firstChild,s=r.nextSibling,c=s.firstChild;n.$$dblclick=()=>{mo(Math.max(220,Math.round(window.innerHeight*.35))),localStorage.setItem(`teapot.termH`,String(po()))},n.$$pointerdown=Eo,L(i,A(j,{get each(){return eo()},children:(e,t)=>(()=>{var n=rE(),r=n.firstChild.nextSibling;return n.$$click=()=>{vo(t()),ro()},L(n,()=>no(e),r),r.$$click=e=>{e.stopPropagation(),xo(t())},b(r=>{var i=`termtab`+(uo()===0&&io()===t()?` active`:``)+(co()&&uo()===1&&oo()===t()?` active`:``),a=`${e.cwd?`${e.cwd}\n`:``}${e.title} — click to show in focused pane`;return i!==r.e&&I(n,r.e=i),a!==r.t&&F(n,`title`,r.t=a),r},{e:void 0,t:void 0}),n})()}),null),L(i,A(Sd,{icon:`+`,title:`new shell in this workspace`,onClick:yo}),null),L(o,(()=>{var t=N(()=>!!_o());return()=>t()?e().find(e=>e.id===_o().agentId)?.workspace.split(`/`).filter(Boolean).pop():B()?.workspace})()),L(a,A(Sd,{icon:`◫`,get title(){return co()?`single pane`:`split panes (50/50)`},onClick:Do}),null),L(a,A(Sd,{icon:`▾`,title:`hide the terminal (shells keep running; reopen with t) — close individual shells with their ✕ tab buttons`,onClick:$a}),null);var l=Oo(0);return typeof l==`function`&&je(l,c),c.$$pointerdown=()=>fo(0),L(c,A(M,{get when(){return io()<0||io()>=eo().length},get children(){return _T()}})),L(s,A(M,{get when(){return co()},get children(){return[vT(),(()=>{var e=bT(),t=Oo(1);return typeof t==`function`&&je(t,e),e.$$pointerdown=()=>fo(1),L(e,A(M,{get when(){return oo()<0||oo()>=eo().length},get children(){return yT()}})),b(()=>e.classList.toggle(`focused`,uo()===1)),e})()]}}),null),b(e=>{var n={height:`${po()}px`},r=!!co(),i=uo()===0;return e.e=ke(t,n,e.e),r!==e.t&&s.classList.toggle(`split`,e.t=r),i!==e.a&&c.classList.toggle(`focused`,e.a=i),e},{e:void 0,t:void 0,a:void 0}),t}}),(()=>{var e=DT(),t=e.firstChild,n=t.firstChild,r=n.nextSibling,i=r.nextSibling,a=i.nextSibling;return L(e,A(M,{get when(){return N(()=>nr()>32)()&&!qn()},get children(){var e=ST();return e.firstChild,e.$$click=()=>{va(!0),qr()},L(e,(()=>{var e=N(()=>Xn()>0);return()=>e()?`${Xn()} new message${Xn()>1?`s`:``}`:`jump to present`})(),null),e}}),t),L(e,A(M,{get when(){return Wo().length>0},get children(){var e=CT();return L(e,A(j,{get each(){return Wo()},children:(e,t)=>(()=>{var n=iE(),r=n.firstChild,i=r.nextSibling;return n.$$click=()=>{O(e.insert),Uo(-1)},L(r,()=>e.insert.trim()),L(i,()=>e.title),b(r=>{var i=`cmdrow`+(t()===Ho()?` active`:``),a=e.title;return i!==r.e&&I(n,r.e=i),a!==r.t&&F(n,`title`,r.t=a),r},{e:void 0,t:void 0}),n})()})),e}}),t),L(e,A(M,{get when(){return Io().length>0},get children(){var e=CT();return L(e,A(j,{get each(){return Io()},children:e=>(()=>{var t=aE(),n=t.firstChild;n.firstChild;var r=n.nextSibling;return t.$$click=()=>{O(`@${e.key} `),Uo(-1)},L(n,()=>e.key,null),L(r,()=>e.label),b(()=>F(t,`title`,e.label)),t})()})),e}}),t),L(e,A(M,{get when(){return rs().length>0},get children(){var e=wT(),t=e.firstChild;return L(e,A(j,{get each(){return rs()},children:(e,t)=>(()=>{var n=oE(),r=n.firstChild,i=r.nextSibling;return r.$$click=()=>rt(e.url),i.$$click=()=>is(e=>e.filter((e,n)=>n!==t())),b(t=>{var i=e.name,a=e.url,o=e.name;return i!==t.e&&F(n,`title`,t.e=i),a!==t.t&&F(r,`src`,t.t=a),o!==t.a&&F(r,`alt`,t.a=o),t},{e:void 0,t:void 0,a:void 0}),n})()}),t),t.$$click=()=>is([]),e}}),t),t.addEventListener(`submit`,ss),n.$$keydown=e=>{let t=Wo();t.length>0&&e.key===`ArrowDown`?(e.preventDefault(),Uo(e=>Math.min(e+1,t.length-1))):t.length>0&&e.key===`ArrowUp`?(e.preventDefault(),Uo(e=>Math.max(e-1,0))):t.length>0&&(e.key===`Tab`||e.key===`Enter`)&&!e.shiftKey&&Ho()>=0&&!lD?(e.preventDefault(),O(t[Ho()].insert),Uo(-1)):e.key===`Escape`&&t.length>0?Uo(-1):gd({key:e.key,shiftKey:e.shiftKey,composing:lD,maximized:Pn()})&&(e.preventDefault(),ss(e))},n.$$input=e=>{O(e.currentTarget.value),Uo(0),Xo()},n.addEventListener(`paste`,e=>{let t=Array.from(e.clipboardData?.files??[]).filter(e=>e.type.startsWith(`image/`));t.length&&(e.preventDefault(),as(t))}),n.addEventListener(`compositionend`,()=>{requestAnimationFrame(()=>{lD=!1}),O(Go?.value??``)}),n.addEventListener(`compositionstart`,()=>{lD=!0}),je(e=>{Go=e,e.value=re()},n),L(t,A(M,{get when(){return N(()=>!!re().startsWith(`@`))()&&re().includes(` `)},get children(){var e=TT(),t=e.firstChild;return t.addEventListener(`change`,e=>Po(e.currentTarget.checked)),b(()=>t.checked=No()),e}}),r),r.$$click=()=>{let e=Le||qn(),t=!Pn();In(t),e&&He(900),requestAnimationFrame(()=>Xo())},L(r,()=>Pn()?`⤡`:`⤢`),L(t,A(Sd,{icon:`📎`,title:`attach images (or paste them straight into the box)`,onClick:()=>document.getElementById(`composer-file`)?.click()}),i),a.addEventListener(`change`,e=>{e.currentTarget.files?.length&&as(e.currentTarget.files),e.currentTarget.value=``}),L(e,A(M,{get when(){return aD()},get children(){var e=ET();return L(e,aD),e}}),null),b(t=>{var i=`composer`+(Pn()?` maximized`:``),a=`message #${B().id} — / for commands · paste or 📎 to attach images`,o=Pn()?`restore composer (hide timeline)`:`maximize composer — hide the timeline and fill the main column`;return i!==t.e&&I(e,t.e=i),a!==t.t&&F(n,`placeholder`,t.t=a),o!==t.a&&F(r,`title`,t.a=o),t},{e:void 0,t:void 0,a:void 0}),e})()]}})),L(t,A(M,{get when(){return N(()=>!!ge())()&&xt()},get children(){var e=OT();return e.$$click=()=>Ct(!1),e}}),p),p.addEventListener(`scroll`,e=>{us=e.currentTarget.scrollTop});var g=ls;return typeof g==`function`?je(g,p):ls=p,L(m,A(Sd,{icon:`✕`,title:`close details panel (esc)`,onClick:Et}),null),L(p,A(M,{get when(){return B()?.id},keyed:!0,fallback:null,children:t=>[A(M,{get when(){return B().id},keyed:!0,fallback:null,children:e=>A(Yw,{agentId:e,get workspace(){return B().workspace}})}),(()=>{var e=cE();return e.firstChild,L(e,A(M,{get when(){return nn().length},get children(){var e=sE(),t=e.firstChild.nextSibling;return t.nextSibling,L(e,()=>nn().length,t),e}}),null),e})(),(()=>{var t=dE(),r=t.firstChild,i=r.nextSibling,a=i.firstChild,o=a.nextSibling,s=i.nextSibling,c=s.firstChild,l=s.nextSibling;return l.firstChild,r.addEventListener(`change`,t=>{let r=t.currentTarget.value;jn=!0,Xt(r),$t(Ln(ae().providers,r,e().find(e=>e.id===n()))),un(r)}),L(r,A(j,{get each(){return ln()},children:e=>(()=>{var t=AE();return t.value=e,L(t,e,null),L(t,()=>e===ae().defaultProvider?` ★`:``,null),t})()})),a.$$input=e=>$t(e.currentTarget.value),L(o,A(j,{get each(){return nn()},children:e=>(()=>{var t=AE();return b(()=>t.value=e.id),t})()})),L(t,A(M,{get when(){return B().effortSupported},get children(){var e=lE(),t=e.firstChild.nextSibling;return t.firstChild,t.addEventListener(`change`,e=>tn(e.currentTarget.value)),L(t,A(j,{get each(){return N(()=>!!B().effortOptions?.length)()?B().effortOptions:rD},children:e=>(()=>{var t=AE();return t.value=e,L(t,e),t})()}),null),b(()=>t.value=en()),e}}),s),c.$$click=async e=>{if(!n())return;let t=e.currentTarget;t.disabled=!0;try{await Y(`/api/agents/${n()}/model`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({provider:Jt(),model:Qt().trim()||void 0,contextWindowTokens:nn().find(e=>e.id===(Qt().trim()||void 0))?.contextLength,...B().effortSupported?{reasoningEffort:en()}:{}})}),t.textContent=`✓ applied`,Ti()}catch(e){alert(`apply failed: ${e.message}`)}finally{setTimeout(()=>{t.textContent=`apply`,t.disabled=!1},1200)}},L(l,()=>B().model,null),L(t,A(M,{get when(){return hn()},get children(){var e=uE();return L(e,hn),e}}),null),b(()=>F(a,`placeholder`,Rn(ae().providers,Jt(),B(),Fn(B(),ae().providers,ae().defaultProvider)))),b(()=>r.value=Jt()),b(()=>a.value=Qt()),t})(),(()=>{var e=pE();return e.firstChild,L(e,A(M,{get when(){return!!B().goal.text.trim()},get fallback(){return jE()},get children(){var e=fE();return L(e,()=>B().goal.status),b(()=>I(e,`badge ${B().goal.status===`active`?`running`:B().goal.status}`)),e}}),null),e})(),(()=>{var e=mE();return e.firstChild,L(e,A(j,{each:[`active`,`done`,`paused`],children:e=>(()=>{var t=ME();return t.$$click=()=>{n()&&Y(`/api/agents/${n()}/goal`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({status:e})}).then(Ti)},F(t,`title`,e===`active`?`agent keeps working toward the goal (with auto-continue)`:e===`done`?`mark achieved — auto-continue stops`:`parked on purpose — resume by setting active again`),L(t,e===`active`?`▶ working`:e===`done`?`✓ done`:`⏸ paused`),b(n=>{var r=`goalstate`+(B().goal.text.trim()&&B().goal.status===e?` on ${e}`:``),i=!!B().goal.text.trim()&&B().goal.status===e;return r!==n.e&&I(t,n.e=r),i!==n.t&&(t.disabled=n.t=i),n},{e:void 0,t:void 0}),t})()}),null),e})(),A(M,{get when(){return B().goal.text},get fallback(){return NE()},get children(){return[(()=>{var e=hE(),t=e.firstChild;return je(vs,e),b(n=>{var r=_s(),i=ze(String(B().goal.text));return n.e=ke(e,r,n.e),i!==n.t&&(t.innerHTML=n.t=i),n},{e:void 0,t:void 0}),e})(),A(M,{get when(){return B().goal.verify},get children(){return A(an,{title:`🔍️ verification contract`,tone:`tool`,get body(){return String(B().goal.verify)}})}}),A(M,{get when(){return B().goal.audit},children:e=>A(an,{get title(){return e().verdict===`approved`?`✅ audit: approved`:`⚠ audit: changes required`},get meta(){return mt(e().at)},get tone(){return e().verdict===`approved`?`ok`:`warn`},get body(){return N(()=>!!Zt(e().feedback))()?`_the auditor returned a verdict with no detail_`:e().feedback}})})]}}),(()=>{var e=gE(),t=e.firstChild,r=t.nextSibling,i=r.nextSibling.firstChild,a=i.firstChild,o=i.nextSibling.firstChild;return e.addEventListener(`submit`,Es),t.$$input=e=>{gs(e.currentTarget.value),Ss(!0)},je(G,t),r.$$input=e=>{bs(e.currentTarget.value),Ss(!0)},a.addEventListener(`change`,e=>{n()&&Y(`/api/agents/${n()}/auto-continue`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({value:e.currentTarget.checked})}).then(Ti)}),o.addEventListener(`change`,e=>ws(e.currentTarget.checked)),b(()=>t.value=hs()),b(()=>r.value=ys()),b(()=>a.checked=B().autoContinue??!0),b(()=>o.checked=Cs()),e})(),(()=>{var e=vE();return e.firstChild,L(e,A(M,{get when(){return Ci().total>0},get children(){var e=_E(),t=e.firstChild,n=t.nextSibling;return n.nextSibling,L(e,()=>Ci().done,t),L(e,()=>Ci().total,n),b(t=>ke(e,Ci().done===Ci().total?`color:var(--ok)`:`color:var(--warn)`,t)),e}}),null),e})(),A(M,{get when(){return Ci().total>0},get children(){var e=yE(),t=e.firstChild;return b(e=>{var n=`barfill `+(Ci().done===Ci().total?``:`warn`),r=`${Math.round(Ci().done/Ci().total*100)}%`;return n!==e.e&&I(t,e.e=n),r!==e.t&&Ae(t,`width`,e.t=r),e},{e:void 0,t:void 0}),e}}),A(_f,{get draft(){return hi()},get preview(){return _i()},onDraft:e=>{gi(e),bi(!0)}}),(()=>{var e=bE(),t=e.firstChild,n=t.nextSibling;return L(e,A(Sd,{get icon(){return _i()?`✎`:`👁`},get title(){return _i()?`edit markdown`:`rendered checklist`},onClick:()=>vi(!_i())}),t),n.$$click=Si,e})(),xE(),A(M,{get when(){return B().latestProgress},get fallback(){return PE()},children:e=>(()=>{var t=zE(),n=t.firstChild,r=n.firstChild.nextSibling,i=n.nextSibling;return L(t,A(M,{get when(){return e().recent},get children(){var t=FE(),n=t.firstChild.nextSibling;return b(()=>n.innerHTML=dt(e().recent)),t}}),i),L(t,A(M,{get when(){return e().problems},get children(){var t=IE(),n=t.firstChild.nextSibling;return b(()=>n.innerHTML=dt(e().problems)),t}}),i),L(t,A(M,{get when(){return e().next},get children(){var t=LE(),n=t.firstChild.nextSibling;return b(()=>n.innerHTML=dt(e().next)),t}}),i),L(t,A(M,{get when(){return e().goalStatus},get children(){var t=RE(),n=t.firstChild.nextSibling;return L(n,()=>e().goalStatus),t}}),i),L(i,()=>mt(e().ts)),b(()=>r.innerHTML=dt(e().doing)),t})()}),SE(),(()=>{var e=TE(),t=e.firstChild,r=t.firstChild,i=r.firstChild.nextSibling,a=r.nextSibling,o=a.firstChild.nextSibling,s=a.nextSibling,c=s.firstChild.nextSibling,l=s.nextSibling,u=l.firstChild.nextSibling,d=l.nextSibling,f=d.firstChild.nextSibling;return L(e,A(M,{get when(){return B().ctx},keyed:!0,get fallback(){return BE()},children:e=>{let t=S(()=>{let t=e,n=nn().find(e=>e.id===B().model),r=t.window||n?.contextLength||0,i=r?Math.min(999,t.usedTokens/r*100):0;return{usedTokens:t.usedTokens,compactAt:t.compactAt,compacting:t.compacting,window:t.window,effectiveWindow:r,pct:i,cls:r?i>=85?`crit`:i>=70?`warn`:`ok`:``,derivedBudget:r?Math.round(r*.75):0,usingDerived:t.compactAtIsManual!==!0}}),r=()=>t(),i=e=>{let t=Math.round(e*10)/10;return Number.isInteger(t)?String(t):t.toFixed(1)};return(()=>{var e=WE(),t=e.firstChild,a=t.firstChild.nextSibling,o=a.firstChild.nextSibling;o.nextSibling;var s=t.nextSibling,c=s.firstChild.nextSibling,l=c.firstChild,u=c.nextSibling,d=s.nextSibling,f=d.firstChild.firstChild;return L(a,()=>Hx(r().usedTokens),o),L(t,A(M,{get when(){return r().effectiveWindow},get children(){var e=VE(),t=e.firstChild;return L(e,()=>i(r().pct),t),L(e,()=>Hx(r().effectiveWindow),null),b(()=>I(e,`pill ${r().cls}`)),e}}),null),L(e,A(M,{get when(){return r().effectiveWindow},get children(){var e=HE(),t=e.firstChild;return b(e=>{var n=`barfill ${r().cls}`,i=`${Math.min(100,r().pct)}%`;return n!==e.e&&I(t,e.e=n),i!==e.t&&Ae(t,`width`,e.t=i),e},{e:void 0,t:void 0}),e}}),s),L(c,()=>Hx(r().usingDerived?r().derivedBudget:r().compactAt),l),L(u,()=>r().usingDerived?`75% of window`:`manual`),L(e,A(M,{get when(){return ar()||r().compacting},get children(){var e=UE(),t=e.firstChild.nextSibling.nextSibling;return L(t,()=>ar()?.phase??String(r().compacting)),e}}),d),f.addEventListener(`change`,e=>{n()&&Y(`/api/agents/${n()}/auto-compact`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({value:e.currentTarget.checked})}).then(Ti)}),b(()=>f.checked=B().autoCompact!==!1),e})()}}),t),L(i,()=>Hx(B().stats.inputTokens)),L(o,()=>Hx(B().stats.outputTokens)),L(c,()=>B().stats.turns),L(u,()=>B().stats.toolCalls),L(f,()=>B().stats.compactions??0),L(t,A(M,{get when(){return(B().stats.costUsd??0)>0},get children(){var e=CE(),t=e.firstChild.nextSibling;return t.firstChild,L(t,()=>vD(B().stats.costUsd??0),null),b(()=>F(e,`title`,`≈ ${(B().stats.costUsd??0).toFixed(4)} this session, from the model's per-token pricing and per-turn usage. Cached input is estimated at ~10% of the prompt rate; treat as an approximation, not an invoice.`)),e}}),null),L(t,A(M,{get when(){return(B().stats.cachedInputTokens??0)>0},get children(){var e=wE(),t=e.firstChild.nextSibling,n=t.firstChild;return L(t,()=>Math.round(B().stats.cachedInputTokens/Math.max(1,B().stats.inputTokens)*100),n),b(()=>F(e,`title`,`${Hx(B().stats.cachedInputTokens)} input tokens were served from the provider's prompt cache — billed far cheaper than fresh input`)),e}}),null),b(()=>F(d,`title`,`how many times old turns were summarized into notes to make room. ${B().stats.compactions?`Each one keeps the recent stretch verbatim.`:`Not yet — the context has fit so far.`}`)),e})(),(()=>{var e=DE();return e.firstChild.nextSibling,L(e,A(M,{get when(){return Gi()},get children(){var e=EE(),t=e.firstChild.nextSibling;return L(t,Gi),e}}),null),e})(),A(j,{get each(){return ee()},children:e=>(()=>{var t=GE(),r=t.firstChild,i=r.nextSibling,a=i.firstChild;return t.$$click=()=>{let t=Gi()===e.branch?null:e.branch,r=t!==Gi();Ki(t),n()&&(r&&(ra++,Ji(),v(0),na(!1)),pa(n()))},L(r,()=>e.branch,null),L(r,()=>e.branch===B().branch?` (current)`:``,null),L(i,()=>e.events,a),b(n=>{var r=`branch-row`+(e.branch===B().branch||e.branch===Gi()?` cur`:``),i=e.branch===Gi()?`click to show all branches again`:`show only ${e.branch}`;return r!==n.e&&I(t,n.e=r),i!==n.t&&F(t,`title`,n.t=i),n},{e:void 0,t:void 0}),t})()}),(()=>{var e=kE();return e.firstChild,L(e,A(M,{get when(){return Di().length>0},get children(){var e=OE(),t=e.firstChild.nextSibling;return t.nextSibling,L(e,()=>Di().length,t),e}}),null),e})(),A(M,{get when(){return Di().length>0},get fallback(){return KE()},get children(){return A(j,{get each(){return Di()},children:e=>(()=>{var t=JE(),r=t.firstChild,i=r.firstChild,a=i.nextSibling;a.firstChild;var o=r.nextSibling,s=o.firstChild,c=o.nextSibling;return t.$$click=()=>Ea(e.agent),L(i,()=>e.id),L(a,()=>e.agent,null),L(r,A(M,{get when(){return e.forked},get children(){return qE()}}),null),L(o,()=>e.schedule,s),L(o,(()=>{var t=N(()=>!!e.next);return()=>t()?mt(e.next):`—`})(),null),L(o,(()=>{var t=N(()=>!!e.last);return()=>t()?` · last ${mt(e.last)}`:` · never ran`})(),null),L(c,()=>Ux(e.prompt,90)),b(r=>{var i=`sched-row`+(e.agent===n()?` cur`:``),a=`${Ux(e.prompt,200)}\nclick to open #${e.agent}`;return i!==r.e&&I(t,r.e=i),a!==r.t&&F(t,`title`,r.t=a),r},{e:void 0,t:void 0}),t})()})}})]}),null),b(e=>{var n=`layout`+(xt()?``:` right-hidden`)+(At()?` left-open`:``),i=`sidebar`+(At()?` open`:``),a=`iconbtn notifbtn`+(Gr()>0?` has-unread`:``),s=Gr()>0?`${Gr()} unread notifications`:`notifications`,c=`conn`+(Da()?` ok`:``),u=Da()?`live (websocket)`:`reconnecting…`,d={"--termh":`${po()}px`},m=`rightbar`+(xt()?` open`:``);return n!==e.e&&I(t,e.e=n),i!==e.t&&I(r,e.t=i),a!==e.a&&I(o,e.a=a),s!==e.o&&F(o,`title`,e.o=s),c!==e.i&&I(l,e.i=c),u!==e.n&&F(l,`title`,e.n=u),e.s=ke(f,d,e.s),m!==e.h&&I(p,e.h=m),e},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0}),t})(),A(M,{get when(){return Ur()},get children(){return[(()=>{var e=AT();return e.$$click=()=>Wr(!1),e})(),(()=>{var t=NT(),r=t.firstChild.firstChild.nextSibling,i=r.firstChild;return L(r,A(M,{get when(){return zr().length>0},get children(){var e=jT();return e.$$click=()=>Br([]),e}}),i),i.$$click=()=>Wr(!1),L(t,A(M,{get when(){return zr().length>0},get fallback(){return YE()},get children(){var t=MT();return L(t,A(j,{get each(){return zr()},children:t=>(()=>{var r=ZE(),i=r.firstChild.firstChild,a=i.nextSibling,o=a.nextSibling,s=o.nextSibling;return r.$$click=()=>{Br(e=>e.map(e=>e.id===t.id?{...e,read:!0}:e)),n()!==t.agentId&&e().some(e=>e.id===t.agentId)&&Ea(t.agentId),Wr(!1),t.eventId&&Qr(t.eventId)},L(i,(()=>{var e=N(()=>t.kind===`finish`);return()=>e()?`✅`:N(()=>t.kind===`question`)()?`❓️`:t.kind===`error`?`⚠️`:`📈`})()),L(a,()=>t.title),L(o,()=>mt(new Date(t.at).toISOString())),s.$$click=e=>{e.stopPropagation(),Br(e=>e.map(e=>e.id===t.id?{...e,read:!0}:e))},L(s,()=>t.read?`✓`:`○`),L(r,A(M,{get when(){return t.body},get children(){var e=XE();return L(e,()=>_D(t.body,160)),e}}),null),b(e=>{var n=`notifitem `+t.kind+(t.read?` read`:``),i=`from ${t.agentId}`,a=t.read?`already read`:`mark as read`;return n!==e.e&&I(r,e.e=n),i!==e.t&&F(r,`title`,e.t=i),a!==e.a&&F(s,`title`,e.a=a),e},{e:void 0,t:void 0,a:void 0}),r})()})),t}}),null),t})()]}}),A(M,{get when(){return se()},get children(){return A(yD,{get providers(){return Object.keys(ae().providers??{})},onClose:()=>ce(!1),onCreated:e=>{ce(!1),t(t=>wi(t,[e])),Ea(e.id)}})}}),A(M,{get when(){return fe()},get children(){return A(Ew,{get cfg(){return ae()},onClose:()=>pe(!1),announcedOAuth:me,get skills(){return Ro()},get hasSelection(){return!!n()},get agentId(){return n()},get features(){return Bo()},onSaved:()=>{fi(),ki()},theme:{themes:Vt,activeId:Nt,paintedId:ue,auto:Ft,setAuto:e=>{It(e),localStorage.setItem(`teapot.theme.auto`,e?`1`:`0`)},dark:Ut,setDark:Wt,light:Lt,setLight:Rt,setThemes:Ht,setActive:Pt,preview:e=>Bt(e),commitAppearance:e=>{localStorage.setItem(`teapot.theme.auto`,e.auto?`1`:`0`),localStorage.setItem(`teapot.theme.dark`,e.dark),localStorage.setItem(`teapot.theme.light`,e.light),localStorage.setItem(`teapot.theme`,e.fixed)}}})}}),A(M,{get when(){return jr()},fallback:null,children:e=>{let t=()=>h().findIndex(t=>t.id===e().eventId),r=()=>Math.max(0,h().length-t()-1);return A(wd,{title:`edit prompt — forks the conversation`,onClose:()=>Mr(null),get children(){var t=$E(),i=t.firstChild,a=i.nextSibling,o=a.firstChild;return t.addEventListener(`submit`,async t=>{t.preventDefault();let r=document.getElementById(`edit-text`);try{await Y(`/api/agents/${n()}/edit-prompt`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({eventId:e().eventId,text:r.value})}),Mr(null),Ti();let t=n();t&&await Ea(t)}catch(e){alert(`edit failed: ${e.message}`)}}),L(t,A(M,{get when(){return r()>0},get children(){var e=QE(),t=e.firstChild;return L(e,r,t),e}}),a),o.$$click=()=>Mr(null),b(()=>i.value=e().text),t}})}})]}function _D(e,t){return e.length>t?e.slice(0,t)+` …`:e}function vD(e){return e>=100?Math.round(e).toLocaleString():e>=10?e.toFixed(1):e>=1?e.toFixed(2):e>=.01?e.toFixed(3):e.toFixed(4)}function yD(e){let[t,n]=y(`~`),[r,i]=y([]),[a,o]=y(``),[s,c]=y(e.providers[0]??``),[l,u]=y(``),[d,f]=y(``);async function p(e){let r=await Y(`/api/fs?path=${encodeURIComponent(e??t())}`);n(r.path),h(r.parent??``),i(r.entries??[])}w(()=>p(t()));let[m,h]=y(``),g=async n=>{n.preventDefault(),f(``);try{let n=await Y(`/api/agents`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({workspace:t(),id:a(),provider:s()||void 0,model:l()||void 0,start:!1})});e.onCreated(n.agent)}catch(e){f(String(e.message))}};return A(wd,{title:`new agent`,get onClose(){return e.onClose},get children(){var i=tD(),f=i.firstChild,h=f.firstChild.nextSibling.firstChild,_=h.nextSibling,v=_.nextSibling,ee=f.nextSibling,y=ee.nextSibling,x=y.firstChild,S=x.firstChild.nextSibling,C=x.nextSibling,w=C.firstChild.nextSibling,T=C.nextSibling.firstChild.nextSibling,te=y.nextSibling;return i.addEventListener(`submit`,g),h.$$input=e=>n(e.currentTarget.value),_.$$click=()=>p(t()),v.$$click=()=>m()?p(m()):p(`..`),L(ee,A(j,{get each(){return r()},children:e=>(()=>{var n=nD();return n.firstChild,n.$$click=()=>p(`${t()}/${e}`.replace(/\/+/g,`/`)),L(n,e,null),n})()})),S.$$input=e=>o(e.currentTarget.value),w.addEventListener(`change`,e=>c(e.currentTarget.value)),L(w,A(j,{get each(){return e.providers},children:e=>(()=>{var t=AE();return L(t,e),t})()})),T.$$input=e=>u(e.currentTarget.value),L(i,A(M,{get when(){return d()},get children(){var e=eD();return L(e,d),e}}),te),b(()=>h.value=t()),b(()=>S.value=a()),b(()=>w.value=s()),b(()=>T.value=l()),i}})}De([`click`,`input`,`keydown`,`pointerdown`,`dblclick`]),Ee(()=>A(gD,{}),document.getElementById(`root`));
190
- //# sourceMappingURL=index-BOCS3KYE.js.map
187
+ `)?`${e.value} `:e.value),qo||(qo=document.createElement(`div`),qo.setAttribute(`aria-hidden`,`true`),qo.style.cssText=`position:absolute;left:-9999px;top:0;pointer-events:none`,document.body.appendChild(qo)),Ko.parentElement!==qo&&qo.appendChild(Ko),!Jo){let e=document.createElement(`style`);e.textContent=`[data-mirror]::after{content:attr(data-mirror-text);white-space:pre-wrap;display:block}`,document.head.appendChild(e),Jo=!0}return Ko.scrollHeight}let Xo=()=>{if(!Go)return;let e=Nn();if(!Go.value&&!e){Go.style.height=``;return}let t=Yo(Go),n=e?-1:Vn(t,360);Go.style.height=n===-1?``:`${n}px`},Zo,Qo=null,$o,es=240,ts=1200,ns;x(()=>{let e=ne();Go&&zn(uD)&&(Bn(Go.value,e)&&(Go.value=e),Xo())}),w(()=>{let e=0,t=()=>{e||=requestAnimationFrame(()=>{e=0,Xo()})};window.addEventListener(`resize`,t),T(()=>{window.removeEventListener(`resize`,t),e&&cancelAnimationFrame(e)})});let[rs,is]=y([]),as=e=>{let t=Array.from(e).filter(e=>e.type.startsWith(`image/`));for(let e of t){if(e.size>8e6){lD(`"${e.name}" is over 8 MB — skipped`);continue}let t=new FileReader;t.onload=()=>{is(n=>[...n,{url:String(t.result),name:e.name}].slice(0,4))},t.readAsDataURL(e)}},os=async(t,r)=>{let i=r??n();if(!i)return;let a=rs(),o=e().find(e=>e.id===i)?.session||i,s=qn(),c=wn((V()?.status??``)===`running`),l=`@p${Date.now()}${Math.random().toString(36).slice(2,6)}`;Rr(o,[...Lr(o),{id:l,text:t,at:Date.now(),...c?{queued:!0}:{},...a.length?{images:a.map(e=>e.url)}:{}}]);try{let e=await X(`/api/agents/${i}/prompt`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({text:t,start:!0,clientId:l,...a.length?{images:a}:{}})}),n=e.promptId,r=e.ahead;(n||typeof r==`number`)&&Rr(o,Lr(o).map(e=>e.id===l?{...e,...n?{promptId:n}:{},...typeof r==`number`?{queued:r>0}:{}}:e)),is([]),_d(Nn())&&Fn(!1),Xo(),s&&(Jn(!0),tr(0),we=0,Ve(700))}catch(e){Rr(o,Lr(o).filter(e=>e.id!==l)),k(t),console.error(`send failed:`,e)}},ss=async t=>{t.preventDefault();let r=n(),i=ne().trim();if(r&&i){if(i.startsWith(`@`)){let t=i.indexOf(` `),r=(t===-1?i.slice(1):i.slice(1,t)).toLowerCase(),a=t===-1?``:i.slice(t+1).trim(),o=Ao().some(e=>e.key.toLowerCase()===r),s=e().some(e=>e.id.toLowerCase()===r);try{if(o){if(!a){lD(`usage: @${r} <task>`);return}lD(`🧩 spawned ${(await X(`/api/agents/${n()}/spawn`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({persona:r,task:a,context:No()?`fork`:`none`})})).id}${No()?` (forked context)`:``}`),Ti(),k(``)}else if(s){if(!a){lD(`usage: @${r} <message>`);return}await X(`/api/agents/${encodeURIComponent(r)}/prompt`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({text:a,start:!0})}),lD(`→ delivered to @${r}`),k(``)}else{lD(`unknown @${r} — personas: ${Ao().map(e=>e.key).join(`, `)||`(none)`}`);return}}catch(e){lD(`@${r} failed: ${e.message}`)}}else if(i.startsWith(`/`)){let e=i.indexOf(` `),t=(e===-1?i.slice(1):i.slice(1,e)).toLowerCase(),n=e===-1?``:i.slice(e+1).trim();if(t===`goal`&&!n){k(`/goal `);return}if(t===`skill`&&!n){k(`/skill `);return}k(``);try{await cs(t,n)}catch(e){throw k(ne()?`${i}\n${ne()}`:i),e}}else k(``),await os(i)}},cs=async(e,t)=>{let r=n();if(!r)return;let i=(e,t)=>X(`/api/agents/${r}${e}`,{method:`POST`,headers:{"content-type":`application/json`},...t===void 0?{}:{body:JSON.stringify(t)}}).then(Ti);try{if(e===`start`)await i(`/start`);else if(e===`stop`)await i(`/stop`);else if(e===`fork`)await i(`/fork`,{}),await Ea(r);else if(e===`compact`)lD((await i(`/compact`))?.ran?`context compacted`:`nothing to compact yet`);else if(e===`goal`){if(!t){lD(`usage: /goal <text>`);return}await i(`/goal`,{text:t,notify:!0}),lD(`goal saved & notification queued`)}else if(e===`skill`){if(!t){lD(`usage: /skill <name>`);return}await i(`/skill`,{name:t}),lD(`skill "${t}" dispatched`)}else lD(`unknown command "${e}" — /start /stop /fork /goal /skill /compact`)}catch(t){lD(`/${e} failed: ${t.message}`)}},ls,us=0;x(()=>{e(),requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!ls)return;let e=Math.min(us,ls.scrollHeight);Math.abs(ls.scrollTop-e)>1&&(ls.scrollTop=e)})})});let ds=e=>()=>n()&&X(`/api/agents/${n()}${e}`,{method:`POST`}).then(Ti),fs=async()=>{let i=n();if(!i)return;let a=new Set([i,..._n(e(),i).map(e=>e.id)]),o=a.size-1;if(!confirm(`archive agent ${i}?\n\n`+(o>0?`Its ${o} sub-agent${o===1?``:`s`} will be archived too.\n\n`:``)+`They stop running and leave the list, but the config and full session history are KEPT — restore any of them from ⚙️ settings → archive.`))return;await X(`/api/agents/${i}/archive`,{method:`POST`}).catch(()=>{}),t(e().filter(e=>!a.has(e.id))),m(!0);let s=hd(e(),a);s?Ea(s.id):(r(null),Ji())},ps=async()=>{n()&&(lD(`stopped: ${((await X(`/api/agents/${n()}/stop-children`,{method:`POST`})).stopped??[]).join(`, `)||`(none)`}`),Ti())},ms=()=>X(`/api/agents/${V().id}/fork`,{method:`POST`,headers:{"content-type":`application/json`},body:`{}`}).then(async()=>{await m(!0),await Ea(V().id)}),[hs,gs]=y(``),_s=()=>({"max-height":`none`,"overflow-y":`auto`,resize:`vertical`}),vs=e=>{T(Zn(e,`goalPreview`))},K=e=>{T(Zn(e,`goal`))},[ys,bs]=y(``),[xs,Ss]=y(!1),[Cs,ws]=y(!0),Ts=``;x(()=>{let e=n();e&&(V()?.goal,e!==Ts&&(Ts=e,Ss(!1),gs(``),bs(``)))});let Es=async e=>{if(e.preventDefault(),n()&&hs().trim())try{await X(`/api/agents/${n()}/goal`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({text:hs(),notify:Cs(),...ys().trim()?{verify:ys()}:{}})}),gs(``),bs(``),Ss(!1),Ti()}catch(e){lD(`goal save failed: ${e.message}`)}};return[j(N,{get when(){return pi()},get children(){var e=Zw();return e.firstChild.firstChild.nextSibling.addEventListener(`submit`,e=>{e.preventDefault();let t=document.getElementById(`pw-input`);localStorage.setItem(`teapot.token`,t.value),location.reload()}),e}}),j(N,{get when(){return ue()},children:e=>(()=>{var t=FT(),n=t.firstChild;return b(t=>{var r=fn(e(),sn[sn.length-1]),i=dn(e());return r!==t.e&&I(n,`src`,t.e=r),i!==t.t&&I(n,`srcset`,t.t=i),t},{e:void 0,t:void 0}),t})()}),(()=>{var t=AT(),r=t.firstChild,i=r.firstChild,a=i.nextSibling.firstChild,o=a.firstChild;o.firstChild;var s=a.nextSibling,c=s.firstChild.firstChild.nextSibling;c.firstChild;var l=c.nextSibling,d=s.nextSibling,f=r.nextSibling,p=f.nextSibling,m=p.firstChild;m.firstChild,R(t,j(N,{get when(){return P(()=>!!he())()&&kt()},get children(){var e=Qw();return e.$$click=jt,e}}),r),R(r,j(N,{get when(){return he()},get children(){var e=$w(),t=e.firstChild.nextSibling;return t.$$click=jt,e}}),i),R(i,j(M,{get each(){return Wi()},children:t=>[j(N,{get when(){return P(()=>t.wsHeader!==void 0)()&&t.wsHeader!==``},get children(){var e=LT(),n=e.firstChild,r=n.nextSibling;return e.$$click=()=>Bi(`ws:${t.wsHeader}`,Vi(t.wsHeader),t.wsCollapsedGroup===!0,t.collapsedVia),R(n,()=>t.wsCollapsedGroup?`▸`:`▾`),R(r,()=>Vi(t.wsHeader)),R(e,j(N,{get when(){return t.wsCollapsedGroup},get children(){var e=IT();return R(e,()=>Ui().get(t.wsHeader)??0),e}}),null),b(n=>{var i=t.wsCollapsedGroup?`${t.wsHeader} — collapsed (${Hi(t.wsHeader)} hidden). Click to show.`:(Ui().get(t.wsHeader)??0)>1?`${t.wsHeader} — ${Hi(t.wsHeader)} in this directory`:t.wsHeader||``,a=t.wsHeader;return i!==n.e&&I(e,`title`,n.e=i),a!==n.t&&I(r,`title`,n.t=a),n},{e:void 0,t:void 0}),e}}),j(N,{get when(){return P(()=>!t.headerOnly)()&&!t.wsCollapsedGroup},get children(){var r=HT(),i=r.firstChild,a=i.nextSibling;return r.$$click=()=>Ea(t.a.id),R(r,j(N,{get when(){return hn({isSub:!!t.a.parent,collapsed:t.chatCollapsedGroup===!0,hasChildren:e().some(e=>e.parent===t.a.id)})},get fallback(){return UT()},get children(){return(()=>{let e=!t.a.parent,n=e&&Ri().has(`chat:${t.a.id}`)||Ni(t.a.id);return(()=>{var r=WT();return r.$$click=r=>{if(r.stopPropagation(),e){if(n){if(!H().has(t.a.id)){let e=new Set(H());e.add(t.a.id),ji(e),localStorage.setItem(`teapot.expandedSubs`,JSON.stringify([...e]))}if(Mi().has(t.a.id)){let e=new Set(Mi());e.delete(t.a.id),U(e),localStorage.setItem(`teapot.collapsed`,JSON.stringify([...e]))}}else if(H().has(t.a.id)){let e=new Set(H());e.delete(t.a.id),ji(e),localStorage.setItem(`teapot.expandedSubs`,JSON.stringify([...e]))}Bi(`chat:${t.a.id}`,t.a.id,n)}else Pi(t.a.id)},R(r,n?`▸`:`▾`),b(()=>I(r,`title`,e?n?`show ${t.a.id}`:`hide ${t.a.id} and its sub-agents`:n?`expand sub-agents`:`collapse sub-agents`)),r})()})()}}),i),R(a,()=>Qn({id:t.a.id,sessionTitle:t.a.sessionTitle??u().get(t.a.session??``)})),R(r,(()=>{var e=P(()=>!!t.a.workspaceMissing);return()=>e()?GT():null})(),null),R(r,j(N,{get when(){return Jr(t.a.id)>0},get children(){var e=RT();return e.firstChild,R(e,()=>Jr(t.a.id),null),b(()=>I(e,`title`,`${Jr(t.a.id)} unread notification${Jr(t.a.id)>1?`s`:``} (including sub-agents)`)),e}}),null),R(r,j(N,{get when(){return Ni(t.a.id)||t.chatCollapsedGroup===!0&&Ri().has(`chat:${t.a.id}`)},get children(){return(()=>{let n=_n(e(),t.a.id),r=n.filter(e=>e.live??(e.status===`running`||e.status===`waiting`||e.status===`needs_operator`)).length;return n.length>0?(()=>{var e=KT();return e.firstChild,L(e,`subcount`+(r>0?` live`:``)),R(e,()=>n.length,null),R(e,r>0?` · ▶${r}`:``,null),b(()=>I(e,`title`,`${n.length} sub-agent${n.length>1?`s`:``} (${r} active)`)),e})():null})()}}),null),R(r,j(N,{get when(){return t.a.parent},get children(){return zT()}}),null),R(r,j(N,{get when(){return Ai(t.a.id).length>0},get children(){var e=BT();return b(()=>I(e,`title`,Ai(t.a.id).map(e=>`${e.id}: ${e.schedule}`).join(`
188
+ `))),e}}),null),R(r,j(N,{get when(){return t.a.goal.status===`done`},get children(){return VT()}}),null),b(e=>{var o=`agent-item`+(t.a.id===n()?` sel`:``)+(t.depth>0?` sub-row`:``)+(t.chatCollapsedGroup?` collapsed`:``),s=t.depth>0?`padding-left:${10+t.depth*14}px`:``,c=t.a.parent?(()=>{let e=gn(t.a.id,Ao().map(e=>e.key));return e?`sub-agent of @${t.a.parent} — "${e}"`:`sub-agent of @${t.a.parent}`})():void 0,l=`dot ${t.a.status}`,d=t.a.status===`needs_operator`?`waiting for your answer`:t.a.status===`waiting`?`waiting on its own work — resumes by itself`:t.a.status,f=t.a.workspaceMissing?` ghost`:``,p=t.a.workspaceMissing?`workspace not found on disk (${t.a.workspace}) — it will be created when this session runs`:$n({id:t.a.id,sessionTitle:t.a.sessionTitle??u().get(t.a.session??``)});return o!==e.e&&L(r,e.e=o),e.t=Oe(r,s,e.t),c!==e.a&&I(r,`title`,e.a=c),l!==e.o&&L(i,e.o=l),d!==e.i&&I(i,`title`,e.i=d),f!==e.n&&L(a,e.n=f),p!==e.s&&I(a,`title`,e.s=p),e},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0}),r}})]})),o.$$click=e=>{e.stopPropagation(),Wr(!Ur()),Ur()||Br(e=>e.map(e=>({...e,read:!0})))},R(o,j(N,{get when(){return Gr()>0},get children(){var e=eT();return R(e,Gr),e}}),null),R(a,j(Sd,{icon:`👻`,get active(){return Vr()},get title(){return Vr()?`show ghost sessions again (👻 workspace missing on disk)`:`hide ghost sessions (👻 — their workspace directory no longer exists)`},onClick:t=>{t.stopPropagation();let r=!Vr();if(Hr(r),localStorage.setItem(`teapot.hideGhosts`,r?`1`:`0`),r&&n()&&V()?.workspaceMissing){let t=e().find(e=>!e.workspaceMissing);t&&Ea(t.id)}}}),null),R(a,j(Sd,{icon:`+`,title:`new agent`,onClick:()=>{fi(),se(!0)}}),null),R(a,j(Sd,{icon:`⚙️`,title:`settings`,onClick:()=>{fi(),fe(!0)}}),null),R(c,`0.37.174`,null),R(d,j(N,{get when(){return D()},get children(){return[`master rss `,P(()=>D().rssMb),`MB · heap `,P(()=>D().heapUsedMb),`MB`,j(N,{get when(){return D().heapTotalMb!==void 0},get children(){return[` · total `,P(()=>D().heapTotalMb),`MB`]}}),j(N,{get when(){return D().externalMb!==void 0},get children(){return[` · ext `,P(()=>D().externalMb),`MB`]}}),j(N,{get when(){return D().arrayBuffersMb!==void 0},get children(){return[` · buf `,P(()=>D().arrayBuffersMb),`MB`]}}),tT(),j(N,{get when(){return D().messagesInMemory!==void 0},get children(){return[`msgs `,P(()=>D().messagesInMemory),` in `,P(()=>D().loadedSessions),` loaded session(s)`,tT()]}}),`load1 `,P(()=>D().loadavg1),` · up `,P(()=>Math.floor(D().uptimeSec/60)),`m`]}})),R(f,j(N,{get when(){return V()?.id},get fallback(){return qT()},get children(){return[(()=>{var t=cT(),r=t.firstChild,i=r.nextSibling,a=i.nextSibling,o=a.firstChild,s=o.nextSibling,c=s.nextSibling.nextSibling,l=c.nextSibling.nextSibling,u=l.nextSibling.nextSibling;u.nextSibling;var d=a.nextSibling,f=d.firstChild,p=f.nextSibling;return R(t,j(N,{get when(){return he()},get children(){var e=nT();return e.$$click=()=>At(!kt()),b(()=>I(e,`aria-expanded`,kt())),e}}),r),r.$$click=()=>Za(),R(t,j(N,{get when(){return qa()},get fallback(){return(()=>{var e=JT();return e.$$click=()=>Za(),R(e,()=>Qn(V())),b(()=>I(e,`title`,`${$n(V(),V().session)} — click to rename`)),e})()},get children(){var e=rT();return e.addEventListener(`blur`,()=>void Qa()),e.$$keydown=e=>{e.key===`Enter`?(e.preventDefault(),Qa()):e.key===`Escape`&&(e.preventDefault(),Ja(!1))},e.$$input=e=>Xa(e.currentTarget.value),Ae(e=>{requestAnimationFrame(()=>{e.focus(),e.select()})},e),I(e,`spellcheck`,!1),b(()=>e.value=Ya()),e}}),i),R(i,()=>V().status),R(t,j(N,{get when(){return Or()>0},get children(){var e=iT(),t=e.firstChild.nextSibling,n=t.nextSibling.nextSibling;return n.nextSibling,R(e,Or,t),R(e,()=>Or()===1?`message`:`messages`,n),R(e,()=>V().status===`stopped`?` (stopped)`:``,null),b(()=>I(e,`title`,(()=>{let e=V().pendingPromptQueue??[],t=e.length||V().pendingPromptIds?.length||V().pendingPrompts||0,n=e.length?e.filter(e=>(e.source??`user`)===`user`).length:t,r=t-n;return`${`${t} message${t>1?`s`:``} queued${r?` — ${n} from you, ${r} from the harness`:` from you`}`}. ${V().status===`stopped`?`This agent is STOPPED, so nothing will run until you press start (or it is resumed).`:`They are handed to the model at its next turn boundary — the timeline shows them as queued… until then.`}`+(n?` Yours can be withdrawn with ✕ cancel while still queued.`:``)})())),e}}),a),R(t,j(N,{get when(){return(V()?.bgRunning??0)>0},get children(){var e=aT();return e.firstChild,e.$$click=()=>{Ga(!Wa()),Wa()&&Ka()},R(e,()=>V().bgRunning,null),b(t=>{var n=Wa(),r=`${V().bgRunning} background shell(s) running — click to inspect`;return n!==t.e&&I(e,`aria-expanded`,t.e=n),r!==t.t&&I(e,`title`,t.t=r),t},{e:void 0,t:void 0}),e}}),a),R(t,j(N,{get when(){return Ai(V().id).length>0},get children(){var e=oT();return e.firstChild,R(e,()=>Ai(V().id).length,null),b(()=>I(e,`title`,`scheduled tasks:\n${Ai(V().id).map(e=>`${e.schedule} · ${e.id}${e.forked?` (forked)`:``}`).join(`
189
+ `)}`)),e}}),a),R(a,()=>V().model,o),R(a,()=>V().session,s),R(a,()=>V().branch,c),R(a,()=>V().stats.turns,l),R(a,()=>V().stats.toolCalls,u),f.$$click=()=>(kr()?ds(`/stop`):ds(`/start`))(),R(f,()=>kr()?`■ stop`:`▶ start`),R(d,j(N,{get when(){return e().some(e=>e.parent===n())},get children(){return j(Sd,{icon:`⏹`,title:`stop every sub-agent this agent spawned (descendants included)`,onClick:ps})}}),p),R(d,j(Sd,{icon:`🗄`,title:`archive this agent — reversible: it leaves the list but keeps its config and history (restore in ⚙️ settings → archive)`,onClick:fs}),null),R(d,j(Sd,{icon:`⑂`,title:`fork: branch off the conversation here — try things without disturbing the main line`,onClick:ms}),null),R(d,j(Sd,{icon:`⌨`,title:`terminal (t)`,onClick:$a}),null),R(d,j(Sd,{icon:`▤`,title:`toggle details panel (d)`,get active(){return bt()},onClick:wt}),null),R(t,j(N,{get when(){return Wa()},get children(){var e=sT(),t=e.firstChild.firstChild.nextSibling;return t.$$click=()=>Ga(!1),R(e,j(N,{get when(){return Ha().length>0},get fallback(){return YT()},get children(){return j(M,{get each(){return Ha()},children:e=>(()=>{var t=ZT(),n=t.firstChild.firstChild,r=n.nextSibling,i=r.nextSibling,a=i.nextSibling;return R(r,()=>Wx(e.cmd,80)),R(i,(()=>{var t=P(()=>!!e.detached);return()=>t()?`detached · pid ${e.pid??`?`}`:P(()=>!!e.running)()?dt(Date.now()-e.startedAt):`exit ${e.code??`?`}`})(),null),R(i,()=>e.truncated?` · truncated`:``,null),a.$$click=async()=>{await X(`/api/agents/${encodeURIComponent(V().id)}/bg-jobs/${encodeURIComponent(e.id)}`,{method:`DELETE`}).catch(()=>{}),await Ka()},R(a,(()=>{var t=P(()=>!!e.detached);return()=>t()?`forget`:e.running?`kill`:`clear`})()),R(t,j(N,{get when(){return e.tail.trim()},get fallback(){return j(N,{get when(){return e.detached},get children(){var t=QT(),n=t.firstChild.nextSibling;return n.nextSibling,R(t,()=>e.pid??`?`,n),t}})},get children(){var t=XT();return R(t,()=>e.tail),t}}),null),b(t=>{var i=`bgjob-dot `+(e.running?`running`:`done`),o=e.running?`running`:`finished`,s=e.cmd,c=e.detached?`this job survived a harness restart (pid ${e.pid??`?`}) — its output can no longer be read here; stop it yourself if needed`:e.running?`kill this job (whole process group)`:`forget this finished job`;return i!==t.e&&L(n,t.e=i),o!==t.t&&I(n,`title`,t.t=o),s!==t.a&&I(r,`title`,t.a=s),c!==t.o&&I(a,`title`,t.o=c),t},{e:void 0,t:void 0,a:void 0,o:void 0}),t})()})}}),null),e}}),null),b(e=>{var t=`badge ${V().status}`,n=V().statusReason&&!/^(round complete|prompt|api start|goal set|created via web|start)$/.test(V().statusReason)?`${V().status} — ${V().statusReason}`:void 0,r=`${V().model} · ${V().session}/${V().branch} · turns ${V().stats.turns} · tools ${V().stats.toolCalls}`,o=`runbtn`+(kr()?` danger`:``),s=kr()?`interrupt: aborts the current LLM call; the running tool finishes first`:`run toward the goal (starts the loop)`;return t!==e.e&&L(i,e.e=t),n!==e.t&&I(i,`title`,e.t=n),r!==e.a&&I(a,`title`,e.a=r),o!==e.o&&L(f,e.o=o),s!==e.i&&I(f,`title`,e.i=s),e},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),t})(),(()=>{var e=_T();return e.addEventListener(`scroll`,e=>{let t=e.currentTarget,r={top:t.scrollTop,height:t.scrollHeight,viewport:t.clientHeight},i=Ke(r,Qo,$o,ns);Qo=null,Ce=performance.now();let a=Zo?.top,o=Zo?.height;$o=r.height,ns=r.viewport,Zo=r,ir(r);let s=qn(),c=performance.now();c-ye>100&&(ye=c,ve=_t(t));let l=o!==void 0&&Math.abs(r.height-o)>.5,u=a!==void 0&&r.top<a-.5&&!l;u&&(we=performance.now()+400);let d=u?!1:Ge(r)?!0:performance.now()<we?!1:Je(s,i,r,a);d===s?Ie=d:Le(d),d&&i!==`reader`?(Xn()&&tr(0),qr(),qe(d,r)&&We(r)>0&&_a()):d&&Ge(r)&&(Xn()&&tr(0),qr()),r.top<=4&&n()&&!W()&&!ta()&&h().length>0&&sa()}),Ae(e=>lt(e),e),R(e,j(N,{get when(){return ar()},children:e=>(()=>{var t=$T();return t.firstChild,R(t,(()=>{var t=P(()=>e().phase===`harvesting`);return()=>t()?`saving durable lessons…`:`summarizing ${e().summarized?Ux(e().summarized)+` `:``}older messages…`})(),null),t})()}),null),R(e,j(N,{get when(){return P(()=>!!ta())()&&oi().length>0},get children(){return lT()}}),null),R(e,j(N,{get when(){return W()},get children(){return uT()}}),null),R(e,j(N,{get when(){return oi().length>0},get fallback(){return P(()=>!!($i()||da()))()?eE():tE()},get children(){return[j(M,{get each(){return oi()},children:e=>j(_C,{e,prev:()=>li(e,-1),next:()=>li(e,1),get showBranch(){return ee().length>1},res:()=>$r().resFor.get(e.id),get orphan(){return $r().orphanCalls.has(e.id)},onOption:e=>void os(e),answeredIds:ii,onAnswered:ni,get agentActive(){return P(()=>!!Ar())()&&Ct(e)},onResize:()=>{qn()&&_a()},get agentId(){return n()??void 0},get onCancel(){return e.data?.source===`user`&&e.data?.pending&&e.data?.sent!==!0?()=>{let t=Lr(Ir()).find(t=>t.id===e.id),r=String(t?.promptId??e.data?.promptId??``);if(!r){lD(`still being sent — try again in a moment`);return}let i=qn();X(`/api/agents/${n()}/prompt/cancel`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({promptId:r})}).then(e=>{let t=String(e.text??``);k(ne()?`${t}\n\n${ne()}`:t),xa.add(r),Rr(Ir(),Pr().filter(e=>e.promptId!==r));let n=ma();i?Ve(400):n&&(ve=_t(n),ye=performance.now()),lD(`message withdrawn — draft restored`)}).catch(()=>lD(`withdraw failed — it may have already been sent`))}:void 0},get onEdit(){return e.type===`prompt`&&e.data?.source===`user`&&!(e.data?.pending&&e.data?.sent!==!0)&&!e.data?.cancelled?async()=>{kr()&&(await X(`/api/agents/${n()}/stop`,{method:`POST`}).catch(()=>{}),await Ti()),Mr({eventId:e.id,text:String(e.data?.text??``)})}:void 0}})}),j(N,{get when(){return da()},get children(){return dT()}}),j(N,{get when(){return P(()=>!!$i())()&&!da()},get children(){return fT()}}),j(N,{get when(){return P(()=>!!Ar())()&&_r()},get children(){var e=gT(),t=e.firstChild.nextSibling;return t.firstChild,R(t,j(N,{get when(){return Cr().trim()!==``},get children(){var e=pT(),t=e.firstChild;t.firstChild;var n=t.nextSibling;return R(t,j(Xd,{get startedAt(){return Sr()}}),null),Ae(e=>{let t=!0;e.addEventListener(`scroll`,()=>{t=e.scrollHeight-e.scrollTop-e.clientHeight<24}),x(()=>{Cr(),t&&(e.scrollTop=e.scrollHeight)})},n),R(n,Cr),e}}),null),R(t,j(N,{get when(){return z()},get fallback(){return nE()},get children(){return j(N,{get when(){return ur()},get fallback(){return(()=>{var e=hT();return b(()=>e.innerHTML=Re(z()+`▍`)),e})()},get children(){return[mT(),(()=>{var e=hT();return b(()=>e.innerHTML=Re(fr()+`▍`)),e})()]}})}}),null),e}})]}}),null),e})(),j(N,{get when(){return tt()},children:e=>(()=>{var t=rE(),n=t.firstChild;return De(t,`click`,rt,!0),n.$$click=e=>e.stopPropagation(),b(()=>I(n,`src`,e())),t})()}),j(N,{get when(){return Ba()},get children(){var t=ST(),n=t.firstChild,r=n.nextSibling,i=r.firstChild,a=i.nextSibling,o=a.firstChild,s=r.nextSibling,c=s.firstChild;n.$$dblclick=()=>{mo(Math.max(220,Math.round(window.innerHeight*.35))),localStorage.setItem(`teapot.termH`,String(po()))},n.$$pointerdown=Eo,R(i,j(M,{get each(){return eo()},children:(e,t)=>(()=>{var n=iE(),r=n.firstChild.nextSibling;return n.$$click=()=>{vo(t()),ro()},R(n,()=>no(e),r),r.$$click=e=>{e.stopPropagation(),xo(t())},b(r=>{var i=`termtab`+(uo()===0&&io()===t()?` active`:``)+(co()&&uo()===1&&oo()===t()?` active`:``),a=`${e.cwd?`${e.cwd}\n`:``}${e.title} — click to show in focused pane`;return i!==r.e&&L(n,r.e=i),a!==r.t&&I(n,`title`,r.t=a),r},{e:void 0,t:void 0}),n})()}),null),R(i,j(Sd,{icon:`+`,title:`new shell in this workspace`,onClick:yo}),null),R(o,(()=>{var t=P(()=>!!_o());return()=>t()?e().find(e=>e.id===_o().agentId)?.workspace.split(`/`).filter(Boolean).pop():V()?.workspace})()),R(a,j(Sd,{icon:`◫`,get title(){return co()?`single pane`:`split panes (50/50)`},onClick:Do}),null),R(a,j(Sd,{icon:`▾`,title:`hide the terminal (shells keep running; reopen with t) — close individual shells with their ✕ tab buttons`,onClick:$a}),null);var l=Oo(0);return typeof l==`function`&&Ae(l,c),c.$$pointerdown=()=>fo(0),R(c,j(N,{get when(){return io()<0||io()>=eo().length},get children(){return vT()}})),R(s,j(N,{get when(){return co()},get children(){return[yT(),(()=>{var e=xT(),t=Oo(1);return typeof t==`function`&&Ae(t,e),e.$$pointerdown=()=>fo(1),R(e,j(N,{get when(){return oo()<0||oo()>=eo().length},get children(){return bT()}})),b(()=>e.classList.toggle(`focused`,uo()===1)),e})()]}}),null),b(e=>{var n={height:`${po()}px`},r=!!co(),i=uo()===0;return e.e=Oe(t,n,e.e),r!==e.t&&s.classList.toggle(`split`,e.t=r),i!==e.a&&c.classList.toggle(`focused`,e.a=i),e},{e:void 0,t:void 0,a:void 0}),t}}),(()=>{var e=OT(),t=e.firstChild,n=t.firstChild,r=n.nextSibling,i=r.nextSibling,a=i.nextSibling;return R(e,j(N,{get when(){return P(()=>nr()>32)()&&!qn()},get children(){var e=CT();return e.firstChild,e.$$click=()=>{va(!0),qr()},R(e,(()=>{var e=P(()=>Xn()>0);return()=>e()?`${Xn()} new message${Xn()>1?`s`:``}`:`jump to present`})(),null),e}}),t),R(e,j(N,{get when(){return Wo().length>0},get children(){var e=wT();return R(e,j(M,{get each(){return Wo()},children:(e,t)=>(()=>{var n=aE(),r=n.firstChild,i=r.nextSibling;return n.$$click=()=>{k(e.insert),Uo(-1)},R(r,()=>e.insert.trim()),R(i,()=>e.title),b(r=>{var i=`cmdrow`+(t()===Ho()?` active`:``),a=e.title;return i!==r.e&&L(n,r.e=i),a!==r.t&&I(n,`title`,r.t=a),r},{e:void 0,t:void 0}),n})()})),e}}),t),R(e,j(N,{get when(){return Io().length>0},get children(){var e=wT();return R(e,j(M,{get each(){return Io()},children:e=>(()=>{var t=oE(),n=t.firstChild;n.firstChild;var r=n.nextSibling;return t.$$click=()=>{k(`@${e.key} `),Uo(-1)},R(n,()=>e.key,null),R(r,()=>e.label),b(()=>I(t,`title`,e.label)),t})()})),e}}),t),R(e,j(N,{get when(){return rs().length>0},get children(){var e=TT(),t=e.firstChild;return R(e,j(M,{get each(){return rs()},children:(e,t)=>(()=>{var n=sE(),r=n.firstChild,i=r.nextSibling;return r.$$click=()=>nt(e.url),i.$$click=()=>is(e=>e.filter((e,n)=>n!==t())),b(t=>{var i=e.name,a=e.url,o=e.name;return i!==t.e&&I(n,`title`,t.e=i),a!==t.t&&I(r,`src`,t.t=a),o!==t.a&&I(r,`alt`,t.a=o),t},{e:void 0,t:void 0,a:void 0}),n})()}),t),t.$$click=()=>is([]),e}}),t),t.addEventListener(`submit`,ss),n.$$keydown=e=>{let t=Wo();t.length>0&&e.key===`ArrowDown`?(e.preventDefault(),Uo(e=>Math.min(e+1,t.length-1))):t.length>0&&e.key===`ArrowUp`?(e.preventDefault(),Uo(e=>Math.max(e-1,0))):t.length>0&&(e.key===`Tab`||e.key===`Enter`)&&!e.shiftKey&&Ho()>=0&&!uD?(e.preventDefault(),k(t[Ho()].insert),Uo(-1)):e.key===`Escape`&&t.length>0?Uo(-1):gd({key:e.key,shiftKey:e.shiftKey,composing:uD,maximized:Nn()})&&(e.preventDefault(),ss(e))},n.$$input=e=>{k(e.currentTarget.value),Uo(0),Xo()},n.addEventListener(`paste`,e=>{let t=Array.from(e.clipboardData?.files??[]).filter(e=>e.type.startsWith(`image/`));t.length&&(e.preventDefault(),as(t))}),n.addEventListener(`compositionend`,()=>{requestAnimationFrame(()=>{uD=!1}),k(Go?.value??``)}),n.addEventListener(`compositionstart`,()=>{uD=!0}),Ae(e=>{Go=e,e.value=ne()},n),R(t,j(N,{get when(){return P(()=>!!ne().startsWith(`@`))()&&ne().includes(` `)},get children(){var e=ET(),t=e.firstChild;return t.addEventListener(`change`,e=>Po(e.currentTarget.checked)),b(()=>t.checked=No()),e}}),r),r.$$click=()=>{let e=Ie||qn(),t=!Nn();Fn(t),e&&Ve(900),requestAnimationFrame(()=>Xo())},R(r,()=>Nn()?`⤡`:`⤢`),R(t,j(Sd,{icon:`📎`,title:`attach images (or paste them straight into the box)`,onClick:()=>document.getElementById(`composer-file`)?.click()}),i),a.addEventListener(`change`,e=>{e.currentTarget.files?.length&&as(e.currentTarget.files),e.currentTarget.value=``}),R(e,j(N,{get when(){return oD()},get children(){var e=DT();return R(e,oD),e}}),null),b(t=>{var i=`composer`+(Nn()?` maximized`:``),a=`message #${V().id} — / for commands · paste or 📎 to attach images`,o=Nn()?`restore composer (hide timeline)`:`maximize composer — hide the timeline and fill the main column`;return i!==t.e&&L(e,t.e=i),a!==t.t&&I(n,`placeholder`,t.t=a),o!==t.a&&I(r,`title`,t.a=o),t},{e:void 0,t:void 0,a:void 0}),e})()]}})),R(t,j(N,{get when(){return P(()=>!!he())()&&bt()},get children(){var e=kT();return e.$$click=()=>St(!1),e}}),p),p.addEventListener(`scroll`,e=>{us=e.currentTarget.scrollTop});var g=ls;return typeof g==`function`?Ae(g,p):ls=p,R(m,j(Sd,{icon:`✕`,title:`close details panel (esc)`,onClick:Tt}),null),R(p,j(N,{get when(){return V()?.id},keyed:!0,fallback:null,children:t=>[j(N,{get when(){return V().id},keyed:!0,fallback:null,children:e=>j(Xw,{agentId:e,get workspace(){return V().workspace}})}),(()=>{var e=lE();return e.firstChild,R(e,j(N,{get when(){return tn().length},get children(){var e=cE(),t=e.firstChild.nextSibling;return t.nextSibling,R(e,()=>tn().length,t),e}}),null),e})(),(()=>{var t=fE(),r=t.firstChild,i=r.nextSibling,a=i.firstChild,o=a.nextSibling,s=i.nextSibling,c=s.firstChild,l=s.nextSibling;return l.firstChild,r.addEventListener(`change`,t=>{let r=t.currentTarget.value;An=!0,Yt(r),Qt(In(ie().providers,r,e().find(e=>e.id===n()))),ln(r)}),R(r,j(M,{get each(){return cn()},children:e=>(()=>{var t=jE();return t.value=e,R(t,e,null),R(t,()=>e===ie().defaultProvider?` ★`:``,null),t})()})),a.$$input=e=>Qt(e.currentTarget.value),R(o,j(M,{get each(){return tn()},children:e=>(()=>{var t=jE();return b(()=>t.value=e.id),t})()})),R(t,j(N,{get when(){return V().effortSupported},get children(){var e=uE(),t=e.firstChild.nextSibling;return t.firstChild,t.addEventListener(`change`,e=>en(e.currentTarget.value)),R(t,j(M,{get each(){return P(()=>!!V().effortOptions?.length)()?V().effortOptions:iD},children:e=>(()=>{var t=jE();return t.value=e,R(t,e),t})()}),null),b(()=>t.value=$t()),e}}),s),c.$$click=async e=>{if(!n())return;let t=e.currentTarget;t.disabled=!0;try{await X(`/api/agents/${n()}/model`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({provider:qt(),model:Zt().trim()||void 0,contextWindowTokens:tn().find(e=>e.id===(Zt().trim()||void 0))?.contextLength,...V().effortSupported?{reasoningEffort:$t()}:{}})}),t.textContent=`✓ applied`,Ti()}catch(e){alert(`apply failed: ${e.message}`)}finally{setTimeout(()=>{t.textContent=`apply`,t.disabled=!1},1200)}},R(l,()=>V().model,null),R(t,j(N,{get when(){return mn()},get children(){var e=dE();return R(e,mn),e}}),null),b(()=>I(a,`placeholder`,Ln(ie().providers,qt(),V(),Pn(V(),ie().providers,ie().defaultProvider)))),b(()=>r.value=qt()),b(()=>a.value=Zt()),t})(),(()=>{var e=mE();return e.firstChild,R(e,j(N,{get when(){return!!V().goal.text.trim()},get fallback(){return ME()},get children(){var e=pE();return R(e,()=>V().goal.status),b(()=>L(e,`badge ${V().goal.status===`active`?`running`:V().goal.status}`)),e}}),null),e})(),(()=>{var e=hE();return e.firstChild,R(e,j(M,{each:[`active`,`done`,`paused`],children:e=>(()=>{var t=NE();return t.$$click=()=>{n()&&X(`/api/agents/${n()}/goal`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({status:e})}).then(Ti)},I(t,`title`,e===`active`?`agent keeps working toward the goal (with auto-continue)`:e===`done`?`mark achieved — auto-continue stops`:`parked on purpose — resume by setting active again`),R(t,e===`active`?`▶ working`:e===`done`?`✓ done`:`⏸ paused`),b(n=>{var r=`goalstate`+(V().goal.text.trim()&&V().goal.status===e?` on ${e}`:``),i=!!V().goal.text.trim()&&V().goal.status===e;return r!==n.e&&L(t,n.e=r),i!==n.t&&(t.disabled=n.t=i),n},{e:void 0,t:void 0}),t})()}),null),e})(),j(N,{get when(){return V().goal.text},get fallback(){return PE()},get children(){return[(()=>{var e=gE(),t=e.firstChild;return Ae(vs,e),b(n=>{var r=_s(),i=Re(String(V().goal.text));return n.e=Oe(e,r,n.e),i!==n.t&&(t.innerHTML=n.t=i),n},{e:void 0,t:void 0}),e})(),j(N,{get when(){return V().goal.verify},get children(){return j(rn,{title:`🔍️ verification contract`,tone:`tool`,get body(){return String(V().goal.verify)}})}}),j(N,{get when(){return V().goal.audit},children:e=>j(rn,{get title(){return e().verdict===`approved`?`✅ audit: approved`:`⚠ audit: changes required`},get meta(){return pt(e().at)},get tone(){return e().verdict===`approved`?`ok`:`warn`},get body(){return P(()=>!!Xt(e().feedback))()?`_the auditor returned a verdict with no detail_`:e().feedback}})})]}}),(()=>{var e=_E(),t=e.firstChild,r=t.nextSibling,i=r.nextSibling.firstChild,a=i.firstChild,o=i.nextSibling.firstChild;return e.addEventListener(`submit`,Es),t.$$input=e=>{gs(e.currentTarget.value),Ss(!0)},Ae(K,t),r.$$input=e=>{bs(e.currentTarget.value),Ss(!0)},a.addEventListener(`change`,e=>{n()&&X(`/api/agents/${n()}/auto-continue`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({value:e.currentTarget.checked})}).then(Ti)}),o.addEventListener(`change`,e=>ws(e.currentTarget.checked)),b(()=>t.value=hs()),b(()=>r.value=ys()),b(()=>a.checked=V().autoContinue??!0),b(()=>o.checked=Cs()),e})(),(()=>{var e=yE();return e.firstChild,R(e,j(N,{get when(){return Ci().total>0},get children(){var e=vE(),t=e.firstChild,n=t.nextSibling;return n.nextSibling,R(e,()=>Ci().done,t),R(e,()=>Ci().total,n),b(t=>Oe(e,Ci().done===Ci().total?`color:var(--ok)`:`color:var(--warn)`,t)),e}}),null),e})(),j(N,{get when(){return Ci().total>0},get children(){var e=bE(),t=e.firstChild;return b(e=>{var n=`barfill `+(Ci().done===Ci().total?``:`warn`),r=`${Math.round(Ci().done/Ci().total*100)}%`;return n!==e.e&&L(t,e.e=n),r!==e.t&&ke(t,`width`,e.t=r),e},{e:void 0,t:void 0}),e}}),j(_f,{get draft(){return hi()},get preview(){return _i()},onDraft:e=>{gi(e),bi(!0)}}),(()=>{var e=xE(),t=e.firstChild,n=t.nextSibling;return R(e,j(Sd,{get icon(){return _i()?`✎`:`👁`},get title(){return _i()?`edit markdown`:`rendered checklist`},onClick:()=>vi(!_i())}),t),n.$$click=Si,e})(),SE(),j(N,{get when(){return V().latestProgress},get fallback(){return FE()},children:e=>(()=>{var t=BE(),n=t.firstChild,r=n.firstChild.nextSibling,i=n.nextSibling;return R(t,j(N,{get when(){return e().recent},get children(){var t=IE(),n=t.firstChild.nextSibling;return b(()=>n.innerHTML=ut(e().recent)),t}}),i),R(t,j(N,{get when(){return e().problems},get children(){var t=LE(),n=t.firstChild.nextSibling;return b(()=>n.innerHTML=ut(e().problems)),t}}),i),R(t,j(N,{get when(){return e().next},get children(){var t=RE(),n=t.firstChild.nextSibling;return b(()=>n.innerHTML=ut(e().next)),t}}),i),R(t,j(N,{get when(){return e().goalStatus},get children(){var t=zE(),n=t.firstChild.nextSibling;return R(n,()=>e().goalStatus),t}}),i),R(i,()=>pt(e().ts)),b(()=>r.innerHTML=ut(e().doing)),t})()}),CE(),(()=>{var e=EE(),t=e.firstChild,r=t.firstChild,i=r.firstChild.nextSibling,a=r.nextSibling,o=a.firstChild.nextSibling,s=a.nextSibling,c=s.firstChild.nextSibling,l=s.nextSibling,u=l.firstChild.nextSibling,d=l.nextSibling,f=d.firstChild.nextSibling;return R(e,j(N,{get when(){return V().ctx},keyed:!0,get fallback(){return VE()},children:e=>{let t=S(()=>{let t=e,n=tn().find(e=>e.id===V().model),r=t.window||n?.contextLength||0,i=r?Math.min(999,t.usedTokens/r*100):0;return{usedTokens:t.usedTokens,compactAt:t.compactAt,compacting:t.compacting,window:t.window,effectiveWindow:r,pct:i,cls:r?i>=85?`crit`:i>=70?`warn`:`ok`:``,derivedBudget:r?Math.round(r*.75):0,usingDerived:t.compactAtIsManual!==!0}}),r=()=>t(),i=e=>{let t=Math.round(e*10)/10;return Number.isInteger(t)?String(t):t.toFixed(1)};return(()=>{var e=GE(),t=e.firstChild,a=t.firstChild.nextSibling,o=a.firstChild.nextSibling;o.nextSibling;var s=t.nextSibling,c=s.firstChild.nextSibling,l=c.firstChild,u=c.nextSibling,d=s.nextSibling,f=d.firstChild.firstChild;return R(a,()=>Ux(r().usedTokens),o),R(t,j(N,{get when(){return r().effectiveWindow},get children(){var e=HE(),t=e.firstChild;return R(e,()=>i(r().pct),t),R(e,()=>Ux(r().effectiveWindow),null),b(()=>L(e,`pill ${r().cls}`)),e}}),null),R(e,j(N,{get when(){return r().effectiveWindow},get children(){var e=UE(),t=e.firstChild;return b(e=>{var n=`barfill ${r().cls}`,i=`${Math.min(100,r().pct)}%`;return n!==e.e&&L(t,e.e=n),i!==e.t&&ke(t,`width`,e.t=i),e},{e:void 0,t:void 0}),e}}),s),R(c,()=>Ux(r().usingDerived?r().derivedBudget:r().compactAt),l),R(u,()=>r().usingDerived?`75% of window`:`manual`),R(e,j(N,{get when(){return ar()||r().compacting},get children(){var e=WE(),t=e.firstChild.nextSibling.nextSibling;return R(t,()=>ar()?.phase??String(r().compacting)),e}}),d),f.addEventListener(`change`,e=>{n()&&X(`/api/agents/${n()}/auto-compact`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({value:e.currentTarget.checked})}).then(Ti)}),b(()=>f.checked=V().autoCompact!==!1),e})()}}),t),R(i,()=>Ux(V().stats.inputTokens)),R(o,()=>Ux(V().stats.outputTokens)),R(c,()=>V().stats.turns),R(u,()=>V().stats.toolCalls),R(f,()=>V().stats.compactions??0),R(t,j(N,{get when(){return(V().stats.costUsd??0)>0},get children(){var e=wE(),t=e.firstChild.nextSibling;return t.firstChild,R(t,()=>yD(V().stats.costUsd??0),null),b(()=>I(e,`title`,`≈ ${(V().stats.costUsd??0).toFixed(4)} this session, from the model's per-token pricing and per-turn usage. Cached input is estimated at ~10% of the prompt rate; treat as an approximation, not an invoice.`)),e}}),null),R(t,j(N,{get when(){return(V().stats.cachedInputTokens??0)>0},get children(){var e=TE(),t=e.firstChild.nextSibling,n=t.firstChild;return R(t,()=>Math.round(V().stats.cachedInputTokens/Math.max(1,V().stats.inputTokens)*100),n),b(()=>I(e,`title`,`${Ux(V().stats.cachedInputTokens)} input tokens were served from the provider's prompt cache — billed far cheaper than fresh input`)),e}}),null),b(()=>I(d,`title`,`how many times old turns were summarized into notes to make room. ${V().stats.compactions?`Each one keeps the recent stretch verbatim.`:`Not yet — the context has fit so far.`}`)),e})(),(()=>{var e=OE();return e.firstChild.nextSibling,R(e,j(N,{get when(){return Gi()},get children(){var e=DE(),t=e.firstChild.nextSibling;return R(t,Gi),e}}),null),e})(),j(M,{get each(){return ee()},children:e=>(()=>{var t=KE(),r=t.firstChild,i=r.nextSibling,a=i.firstChild;return t.$$click=()=>{let t=Gi()===e.branch?null:e.branch,r=t!==Gi();Ki(t),n()&&(r&&(ra++,Ji(),v(0),na(!1)),pa(n()))},R(r,()=>e.branch,null),R(r,()=>e.branch===V().branch?` (current)`:``,null),R(i,()=>e.events,a),b(n=>{var r=`branch-row`+(e.branch===V().branch||e.branch===Gi()?` cur`:``),i=e.branch===Gi()?`click to show all branches again`:`show only ${e.branch}`;return r!==n.e&&L(t,n.e=r),i!==n.t&&I(t,`title`,n.t=i),n},{e:void 0,t:void 0}),t})()}),(()=>{var e=AE();return e.firstChild,R(e,j(N,{get when(){return Di().length>0},get children(){var e=kE(),t=e.firstChild.nextSibling;return t.nextSibling,R(e,()=>Di().length,t),e}}),null),e})(),j(N,{get when(){return Di().length>0},get fallback(){return qE()},get children(){return j(M,{get each(){return Di()},children:e=>(()=>{var t=YE(),r=t.firstChild,i=r.firstChild,a=i.nextSibling;a.firstChild;var o=r.nextSibling,s=o.firstChild,c=o.nextSibling;return t.$$click=()=>Ea(e.agent),R(i,()=>e.id),R(a,()=>e.agent,null),R(r,j(N,{get when(){return e.forked},get children(){return JE()}}),null),R(o,()=>e.schedule,s),R(o,(()=>{var t=P(()=>!!e.next);return()=>t()?pt(e.next):`—`})(),null),R(o,(()=>{var t=P(()=>!!e.last);return()=>t()?` · last ${pt(e.last)}`:` · never ran`})(),null),R(c,()=>Wx(e.prompt,90)),b(r=>{var i=`sched-row`+(e.agent===n()?` cur`:``),a=`${Wx(e.prompt,200)}\nclick to open #${e.agent}`;return i!==r.e&&L(t,r.e=i),a!==r.t&&I(t,`title`,r.t=a),r},{e:void 0,t:void 0}),t})()})}})]}),null),b(e=>{var n=`layout`+(bt()?``:` right-hidden`)+(kt()?` left-open`:``),i=`sidebar`+(kt()?` open`:``),a=`iconbtn notifbtn`+(Gr()>0?` has-unread`:``),s=Gr()>0?`${Gr()} unread notifications`:`notifications`,c=`conn`+(Da()?` ok`:``),u=Da()?`live (websocket)`:`reconnecting…`,d={"--termh":`${po()}px`},m=`rightbar`+(bt()?` open`:``);return n!==e.e&&L(t,e.e=n),i!==e.t&&L(r,e.t=i),a!==e.a&&L(o,e.a=a),s!==e.o&&I(o,`title`,e.o=s),c!==e.i&&L(l,e.i=c),u!==e.n&&I(l,`title`,e.n=u),e.s=Oe(f,d,e.s),m!==e.h&&L(p,e.h=m),e},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0}),t})(),j(N,{get when(){return Ur()},get children(){return[(()=>{var e=jT();return e.$$click=()=>Wr(!1),e})(),(()=>{var t=PT(),r=t.firstChild.firstChild.nextSibling,i=r.firstChild;return R(r,j(N,{get when(){return zr().length>0},get children(){var e=MT();return e.$$click=()=>Br([]),e}}),i),i.$$click=()=>Wr(!1),R(t,j(N,{get when(){return zr().length>0},get fallback(){return XE()},get children(){var t=NT();return R(t,j(M,{get each(){return zr()},children:t=>(()=>{var r=QE(),i=r.firstChild.firstChild,a=i.nextSibling,o=a.nextSibling,s=o.nextSibling;return r.$$click=()=>{Br(e=>e.map(e=>e.id===t.id?{...e,read:!0}:e)),n()!==t.agentId&&e().some(e=>e.id===t.agentId)&&Ea(t.agentId),Wr(!1),t.eventId&&Qr(t.eventId)},R(i,(()=>{var e=P(()=>t.kind===`finish`);return()=>e()?`✅`:P(()=>t.kind===`question`)()?`❓️`:t.kind===`error`?`⚠️`:`📈`})()),R(a,()=>t.title),R(o,()=>pt(new Date(t.at).toISOString())),s.$$click=e=>{e.stopPropagation(),Br(e=>e.map(e=>e.id===t.id?{...e,read:!0}:e))},R(s,()=>t.read?`✓`:`○`),R(r,j(N,{get when(){return t.body},get children(){var e=ZE();return R(e,()=>vD(t.body,160)),e}}),null),b(e=>{var n=`notifitem `+t.kind+(t.read?` read`:``),i=`from ${t.agentId}`,a=t.read?`already read`:`mark as read`;return n!==e.e&&L(r,e.e=n),i!==e.t&&I(r,`title`,e.t=i),a!==e.a&&I(s,`title`,e.a=a),e},{e:void 0,t:void 0,a:void 0}),r})()})),t}}),null),t})()]}}),j(N,{get when(){return oe()},get children(){return j(bD,{get providers(){return Object.keys(ie().providers??{})},onClose:()=>se(!1),onCreated:e=>{se(!1),t(t=>wi(t,[e])),Ea(e.id)}})}}),j(N,{get when(){return de()},get children(){return j(Dw,{get cfg(){return ie()},onClose:()=>fe(!1),announcedOAuth:pe,get skills(){return Ro()},get hasSelection(){return!!n()},get agentId(){return n()},get features(){return Bo()},onSaved:()=>{fi(),ki()},theme:{themes:Bt,activeId:Mt,paintedId:le,auto:Pt,setAuto:e=>{Ft(e),localStorage.setItem(`teapot.theme.auto`,e?`1`:`0`)},dark:Ht,setDark:Ut,light:It,setLight:Lt,setThemes:Vt,setActive:Nt,preview:e=>zt(e),commitAppearance:e=>{localStorage.setItem(`teapot.theme.auto`,e.auto?`1`:`0`),localStorage.setItem(`teapot.theme.dark`,e.dark),localStorage.setItem(`teapot.theme.light`,e.light),localStorage.setItem(`teapot.theme`,e.fixed)}}})}}),j(N,{get when(){return jr()},fallback:null,children:e=>{let t=()=>h().findIndex(t=>t.id===e().eventId),r=()=>Math.max(0,h().length-t()-1);return j(wd,{title:`edit prompt — forks the conversation`,onClose:()=>Mr(null),get children(){var t=eD(),i=t.firstChild,a=i.nextSibling,o=a.firstChild;return t.addEventListener(`submit`,async t=>{t.preventDefault();let r=document.getElementById(`edit-text`);try{await X(`/api/agents/${n()}/edit-prompt`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({eventId:e().eventId,text:r.value})}),Mr(null),Ti();let t=n();t&&await Ea(t)}catch(e){alert(`edit failed: ${e.message}`)}}),R(t,j(N,{get when(){return r()>0},get children(){var e=$E(),t=e.firstChild;return R(e,r,t),e}}),a),o.$$click=()=>Mr(null),b(()=>i.value=e().text),t}})}})]}function vD(e,t){return e.length>t?e.slice(0,t)+` …`:e}function yD(e){return e>=100?Math.round(e).toLocaleString():e>=10?e.toFixed(1):e>=1?e.toFixed(2):e>=.01?e.toFixed(3):e.toFixed(4)}function bD(e){let[t,n]=y(`~`),[r,i]=y([]),[a,o]=y(``),[s,c]=y(e.providers[0]??``),[l,u]=y(``),[d,f]=y(``);async function p(e){let r=await X(`/api/fs?path=${encodeURIComponent(e??t())}`);n(r.path),h(r.parent??``),i(r.entries??[])}w(()=>p(t()));let[m,h]=y(``),g=async n=>{n.preventDefault(),f(``);try{let n=await X(`/api/agents`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({workspace:t(),id:a(),provider:s()||void 0,model:l()||void 0,start:!1})});e.onCreated(n.agent)}catch(e){f(String(e.message))}};return j(wd,{title:`new agent`,get onClose(){return e.onClose},get children(){var i=nD(),f=i.firstChild,h=f.firstChild.nextSibling.firstChild,_=h.nextSibling,v=_.nextSibling,ee=f.nextSibling,y=ee.nextSibling,x=y.firstChild,S=x.firstChild.nextSibling,C=x.nextSibling,w=C.firstChild.nextSibling,T=C.nextSibling.firstChild.nextSibling,E=y.nextSibling;return i.addEventListener(`submit`,g),h.$$input=e=>n(e.currentTarget.value),_.$$click=()=>p(t()),v.$$click=()=>m()?p(m()):p(`..`),R(ee,j(M,{get each(){return r()},children:e=>(()=>{var n=rD();return n.firstChild,n.$$click=()=>p(`${t()}/${e}`.replace(/\/+/g,`/`)),R(n,e,null),n})()})),S.$$input=e=>o(e.currentTarget.value),w.addEventListener(`change`,e=>c(e.currentTarget.value)),R(w,j(M,{get each(){return e.providers},children:e=>(()=>{var t=jE();return R(t,e),t})()})),T.$$input=e=>u(e.currentTarget.value),R(i,j(N,{get when(){return d()},get children(){var e=tD();return R(e,d),e}}),E),b(()=>h.value=t()),b(()=>S.value=a()),b(()=>w.value=s()),b(()=>T.value=l()),i}})}Ee([`click`,`input`,`keydown`,`pointerdown`,`dblclick`]),Te(()=>j(_D,{}),document.getElementById(`root`));
190
+ //# sourceMappingURL=index-C5VXBX4X.js.map