@kecan0406/ttheme 1.0.31 → 1.0.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/ttheme.js CHANGED
@@ -1,61 +1,114 @@
1
1
  #!/usr/bin/env node
2
- import{createRequire as Hf}from"node:module";var Ef=Object.create;var{getPrototypeOf:vf,defineProperty:ko,getOwnPropertyNames:Ff}=Object;var yf=Object.prototype.hasOwnProperty;function If(n){return this[n]}var Sf,Nf,Te=(n,r,e)=>{var t=n!=null&&typeof n==="object";if(t){var i=r?Sf??=new WeakMap:Nf??=new WeakMap,o=i.get(n);if(o)return o}e=n!=null?Ef(vf(n)):{};let s=r||!n||!n.__esModule?ko(e,"default",{value:n,enumerable:!0}):e;for(let u of Ff(n))if(!yf.call(s,u))ko(s,u,{get:If.bind(n,u),enumerable:!0});if(t)i.set(n,s);return s};var pn=(n,r)=>()=>(r||n((r={exports:{}}).exports,r),r.exports);var Rn=Hf(import.meta.url);var Lo=pn((I0,Ce)=>{var Go=Go||function(n){return Buffer.from(n).toString("base64")};function Kf(n){var r=this,e=Math.round,t=Math.floor,i=Array(64),o=Array(64),s=Array(64),u=Array(64),c,h,f,l,g=Array(65535),d=Array(65535),w=Array(64),m=Array(64),b=[],F=0,S=7,k=Array(64),y=Array(64),p=Array(64),R=Array(256),M=Array(2048),j,H=[0,1,5,6,14,15,27,28,2,4,7,13,16,26,29,42,3,8,12,17,25,30,41,43,9,11,18,24,31,40,44,53,10,19,23,32,39,45,52,54,20,22,33,38,46,51,55,60,21,34,37,47,50,56,59,61,35,36,48,49,57,58,62,63],J=[0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0],G=[0,1,2,3,4,5,6,7,8,9,10,11],z=[0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,125],U=[1,2,3,0,4,17,5,18,33,49,65,6,19,81,97,7,34,113,20,50,129,145,161,8,35,66,177,193,21,82,209,240,36,51,98,114,130,9,10,22,23,24,25,26,37,38,39,40,41,42,52,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,225,226,227,228,229,230,231,232,233,234,241,242,243,244,245,246,247,248,249,250],Sn=[0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0],Q=[0,1,2,3,4,5,6,7,8,9,10,11],B=[0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,119],En=[0,1,2,3,17,4,5,33,49,6,18,65,81,7,97,113,19,34,50,129,8,20,66,145,161,177,193,9,35,51,82,240,21,98,114,209,10,22,36,52,225,37,241,23,24,25,26,38,39,40,41,42,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,130,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,226,227,228,229,230,231,232,233,234,242,243,244,245,246,247,248,249,250];function mn(a){var L=[16,11,10,16,24,40,51,61,12,12,14,19,26,58,60,55,14,13,16,24,40,57,69,56,14,17,22,29,51,87,80,62,18,22,37,56,68,109,103,77,24,35,55,64,81,104,113,92,49,64,78,87,103,121,120,101,72,92,95,98,112,100,103,99];for(var W=0;W<64;W++){var P=t((L[W]*a+50)/100);if(P<1)P=1;else if(P>255)P=255;i[H[W]]=P}var X=[17,18,24,47,99,99,99,99,18,21,26,66,99,99,99,99,24,26,56,99,99,99,99,99,47,66,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99];for(var T=0;T<64;T++){var tn=t((X[T]*a+50)/100);if(tn<1)tn=1;else if(tn>255)tn=255;o[H[T]]=tn}var on=[1,1.387039845,1.306562965,1.175875602,1,0.785694958,0.5411961,0.275899379],In=0;for(var wn=0;wn<8;wn++)for(var v=0;v<8;v++)s[In]=1/(i[H[In]]*on[wn]*on[v]*8),u[In]=1/(o[H[In]]*on[wn]*on[v]*8),In++}function x(a,L){var W=0,P=0,X=[];for(var T=1;T<=16;T++){for(var tn=1;tn<=a[T];tn++)X[L[P]]=[],X[L[P]][0]=W,X[L[P]][1]=T,P++,W++;W*=2}return X}function Nn(){c=x(J,G),h=x(Sn,Q),f=x(z,U),l=x(B,En)}function sn(){var a=1,L=2;for(var W=1;W<=15;W++){for(var P=a;P<L;P++)d[32767+P]=W,g[32767+P]=[],g[32767+P][1]=W,g[32767+P][0]=P;for(var X=-(L-1);X<=-a;X++)d[32767+X]=W,g[32767+X]=[],g[32767+X][1]=W,g[32767+X][0]=L-1+X;a<<=1,L<<=1}}function nn(){for(var a=0;a<256;a++)M[a]=19595*a,M[a+256>>0]=38470*a,M[a+512>>0]=7471*a+32768,M[a+768>>0]=-11059*a,M[a+1024>>0]=-21709*a,M[a+1280>>0]=32768*a+8421375,M[a+1536>>0]=-27439*a,M[a+1792>>0]=-5329*a}function Y(a){var L=a[0],W=a[1]-1;while(W>=0){if(L&1<<W)F|=1<<S;if(W--,S--,S<0){if(F==255)$(255),$(0);else $(F);S=7,F=0}}}function $(a){b.push(a)}function K(a){$(a>>8&255),$(a&255)}function gn(a,L){var W,P,X,T,tn,on,In,wn,v=0,O,A=8,vn=64;for(O=0;O<A;++O){W=a[v],P=a[v+1],X=a[v+2],T=a[v+3],tn=a[v+4],on=a[v+5],In=a[v+6],wn=a[v+7];var V=W+wn,D=W-wn,an=P+In,Z=P-In,un=X+on,jn=X-on,kn=T+tn,Xn=T-tn,nr=V+kn,Fr=V-kn,Jr=an+un,Kr=an-un;a[v]=nr+Jr,a[v+4]=nr-Jr;var oe=(Kr+Fr)*0.707106781;a[v+2]=Fr+oe,a[v+6]=Fr-oe,nr=Xn+jn,Jr=jn+Z,Kr=Z+D;var se=(nr-Kr)*0.382683433,Ze=0.5411961*nr+se,ue=1.306562965*Kr+se,ce=Jr*0.707106781,he=D+ce,fe=D-ce;a[v+5]=fe+Ze,a[v+3]=fe-Ze,a[v+1]=he+ue,a[v+7]=he-ue,v+=8}v=0;for(O=0;O<A;++O){W=a[v],P=a[v+8],X=a[v+16],T=a[v+24],tn=a[v+32],on=a[v+40],In=a[v+48],wn=a[v+56];var so=W+wn,jt=W-wn,uo=P+In,co=P-In,ho=X+on,fo=X-on,go=T+tn,Mf=T-tn,ge=so+go,Rt=so-go,qe=uo+ho,Ae=uo-ho;a[v]=ge+qe,a[v+32]=ge-qe;var lo=(Ae+Rt)*0.707106781;a[v+16]=Rt+lo,a[v+48]=Rt-lo,ge=Mf+fo,qe=fo+co,Ae=co+jt;var ao=(ge-Ae)*0.382683433,mo=0.5411961*ge+ao,$o=1.306562965*Ae+ao,wo=qe*0.707106781,po=jt+wo,bo=jt-wo;a[v+40]=bo+mo,a[v+24]=bo-mo,a[v+8]=po+$o,a[v+56]=po-$o,v++}var Xe;for(O=0;O<vn;++O)Xe=a[O]*L[O],w[O]=Xe>0?Xe+0.5|0:Xe-0.5|0;return w}function ln(){K(65504),K(16),$(74),$(70),$(73),$(70),$(0),$(1),$(1),$(0),K(1),K(1),$(0),$(0)}function rn(a){if(!a)return;if(K(65505),a[0]===69&&a[1]===120&&a[2]===105&&a[3]===102)K(a.length+2);else K(a.length+5+2),$(69),$(120),$(105),$(102),$(0);for(var L=0;L<a.length;L++)$(a[L])}function en(a,L){K(65472),K(17),$(8),K(L),K(a),$(3),$(1),$(17),$(0),$(2),$(17),$(1),$(3),$(17),$(1)}function C(){K(65499),K(132),$(0);for(var a=0;a<64;a++)$(i[a]);$(1);for(var L=0;L<64;L++)$(o[L])}function N(){K(65476),K(418),$(0);for(var a=0;a<16;a++)$(J[a+1]);for(var L=0;L<=11;L++)$(G[L]);$(16);for(var W=0;W<16;W++)$(z[W+1]);for(var P=0;P<=161;P++)$(U[P]);$(1);for(var X=0;X<16;X++)$(Sn[X+1]);for(var T=0;T<=11;T++)$(Q[T]);$(17);for(var tn=0;tn<16;tn++)$(B[tn+1]);for(var on=0;on<=161;on++)$(En[on])}function I(a){if(typeof a>"u"||a.constructor!==Array)return;a.forEach((L)=>{if(typeof L!=="string")return;K(65534);var W=L.length;K(W+2);var P;for(P=0;P<W;P++)$(L.charCodeAt(P))})}function $n(){K(65498),K(12),$(3),$(1),$(0),$(2),$(17),$(3),$(17),$(0),$(63),$(0)}function q(a,L,W,P,X){var T=X[0],tn=X[240],on,In=16,wn=63,v=64,O=gn(a,L);for(var A=0;A<v;++A)m[H[A]]=O[A];var vn=m[0]-W;if(W=m[0],vn==0)Y(P[0]);else on=32767+vn,Y(P[d[on]]),Y(g[on]);var V=63;for(;V>0&&m[V]==0;V--);if(V==0)return Y(T),W;var D=1,an;while(D<=V){var Z=D;for(;m[D]==0&&D<=V;++D);var un=D-Z;if(un>=In){an=un>>4;for(var jn=1;jn<=an;++jn)Y(tn);un=un&15}on=32767+m[D],Y(X[(un<<4)+d[on]]),Y(g[on]),D++}if(V!=wn)Y(T);return W}function _(){var a=String.fromCharCode;for(var L=0;L<256;L++)R[L]=a(L)}this.encode=function(a,L){var W=new Date().getTime();if(L)An(L);b=[],F=0,S=7,K(65496),ln(),I(a.comments),rn(a.exifBuffer),C(),en(a.width,a.height),N(),$n();var P=0,X=0,T=0;F=0,S=7,this.encode.displayName="_encode_";var{data:tn,width:on,height:In}=a,wn=on*4,v=on*3,O,A=0,vn,V,D,an,Z,un,jn,kn;while(A<In){O=0;while(O<wn){an=wn*A+O,Z=an,un=-1,jn=0;for(kn=0;kn<64;kn++){if(jn=kn>>3,un=(kn&7)*4,Z=an+jn*wn+un,A+jn>=In)Z-=wn*(A+1+jn-In);if(O+un>=wn)Z-=O+un-wn+4;vn=tn[Z++],V=tn[Z++],D=tn[Z++],k[kn]=(M[vn]+M[V+256>>0]+M[D+512>>0]>>16)-128,y[kn]=(M[vn+768>>0]+M[V+1024>>0]+M[D+1280>>0]>>16)-128,p[kn]=(M[vn+1280>>0]+M[V+1536>>0]+M[D+1792>>0]>>16)-128}P=q(k,s,P,c,f),X=q(y,u,X,h,l),T=q(p,u,T,h,l),O+=32}A+=8}if(S>=0){var Xn=[];Xn[1]=S+1,Xn[0]=(1<<S+1)-1,Y(Xn)}if(K(65497),typeof Ce>"u")return new Uint8Array(b);return Buffer.from(b);var nr,Fr};function An(a){if(a<=0)a=1;if(a>100)a=100;if(j==a)return;var L=0;if(a<50)L=Math.floor(5000/a);else L=Math.floor(200-a*2);mn(L),j=a}function Cn(){var a=new Date().getTime();if(!n)n=50;_(),Nn(),sn(),nn(),An(n);var L=new Date().getTime()-a}Cn()}if(typeof Ce<"u")Ce.exports=Ro;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].encode=Ro;function Ro(n,r){if(typeof r>"u")r=50;var e=new Kf(r),t=e.encode(n,r);return{data:t,width:n.width,height:n.height}}});var Ko=pn((S0,Pt)=>{var Kt=function(){var r=new Int32Array([0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5,12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28,35,42,49,56,57,50,43,36,29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54,47,55,62,63]),e=4017,t=799,i=3406,o=2276,s=1567,u=3784,c=5793,h=2896;function f(){}function l(S,k){var y=0,p=[],R,M,j=16;while(j>0&&!S[j-1])j--;p.push({children:[],index:0});var H=p[0],J;for(R=0;R<j;R++){for(M=0;M<S[R];M++){H=p.pop(),H.children[H.index]=k[y];while(H.index>0){if(p.length===0)throw Error("Could not recreate Huffman Table");H=p.pop()}H.index++,p.push(H);while(p.length<=R)p.push(J={children:[],index:0}),H.children[H.index]=J.children,H=J;y++}if(R+1<j)p.push(J={children:[],index:0}),H.children[H.index]=J.children,H=J}return p[0].children}function g(S,k,y,p,R,M,j,H,J,G){var{precision:z,samplesPerLine:U,scanLines:Sn,mcusPerLine:Q,progressive:B,maxH:En,maxV:mn}=y,x=k,Nn=0,sn=0;function nn(){if(sn>0)return sn--,Nn>>sn&1;if(Nn=S[k++],Nn==255){var v=S[k++];if(v)throw Error("unexpected marker: "+(Nn<<8|v).toString(16))}return sn=7,Nn>>>7}function Y(v){var O=v,A;while((A=nn())!==null){if(O=O[A],typeof O==="number")return O;if(typeof O!=="object")throw Error("invalid huffman sequence")}return null}function $(v){var O=0;while(v>0){var A=nn();if(A===null)return;O=O<<1|A,v--}return O}function K(v){var O=$(v);if(O>=1<<v-1)return O;return O+(-1<<v)+1}function gn(v,O){var A=Y(v.huffmanTableDC),vn=A===0?0:K(A);O[0]=v.pred+=vn;var V=1;while(V<64){var D=Y(v.huffmanTableAC),an=D&15,Z=D>>4;if(an===0){if(Z<15)break;V+=16;continue}V+=Z;var un=r[V];O[un]=K(an),V++}}function ln(v,O){var A=Y(v.huffmanTableDC),vn=A===0?0:K(A)<<J;O[0]=v.pred+=vn}function rn(v,O){O[0]|=nn()<<J}var en=0;function C(v,O){if(en>0){en--;return}var A=M,vn=j;while(A<=vn){var V=Y(v.huffmanTableAC),D=V&15,an=V>>4;if(D===0){if(an<15){en=$(an)+(1<<an)-1;break}A+=16;continue}A+=an;var Z=r[A];O[Z]=K(D)*(1<<J),A++}}var N=0,I;function $n(v,O){var A=M,vn=j,V=0;while(A<=vn){var D=r[A],an=O[D]<0?-1:1;switch(N){case 0:var Z=Y(v.huffmanTableAC),un=Z&15,V=Z>>4;if(un===0)if(V<15)en=$(V)+(1<<V),N=4;else V=16,N=1;else{if(un!==1)throw Error("invalid ACn encoding");I=K(un),N=V?2:3}continue;case 1:case 2:if(O[D])O[D]+=(nn()<<J)*an;else if(V--,V===0)N=N==2?3:0;break;case 3:if(O[D])O[D]+=(nn()<<J)*an;else O[D]=I<<J,N=0;break;case 4:if(O[D])O[D]+=(nn()<<J)*an;break}A++}if(N===4){if(en--,en===0)N=0}}function q(v,O,A,vn,V){var D=A/Q|0,an=A%Q,Z=D*v.v+vn,un=an*v.h+V;if(v.blocks[Z]===void 0&&G.tolerantDecoding)return;O(v,v.blocks[Z][un])}function _(v,O,A){var vn=A/v.blocksPerLine|0,V=A%v.blocksPerLine;if(v.blocks[vn]===void 0&&G.tolerantDecoding)return;O(v,v.blocks[vn][V])}var An=p.length,Cn,a,L,W,P,X;if(B)if(M===0)X=H===0?ln:rn;else X=H===0?C:$n;else X=gn;var T=0,tn,on;if(An==1)on=p[0].blocksPerLine*p[0].blocksPerColumn;else on=Q*y.mcusPerColumn;if(!R)R=on;var In,wn;while(T<on){for(a=0;a<An;a++)p[a].pred=0;if(en=0,An==1){Cn=p[0];for(P=0;P<R;P++)_(Cn,X,T),T++}else for(P=0;P<R;P++){for(a=0;a<An;a++){Cn=p[a],In=Cn.h,wn=Cn.v;for(L=0;L<wn;L++)for(W=0;W<In;W++)q(Cn,X,T,L,W)}if(T++,T===on)break}if(T===on)do{if(S[k]===255){if(S[k+1]!==0)break}k+=1}while(k<S.length-2);if(sn=0,tn=S[k]<<8|S[k+1],tn<65280)throw Error("marker was not found");if(tn>=65488&&tn<=65495)k+=2;else break}return k-x}function d(S,k){var y=[],p=k.blocksPerLine,R=k.blocksPerColumn,M=p<<3,j=new Int32Array(64),H=new Uint8Array(64);function J(x,Nn,sn){var nn=k.quantizationTable,Y,$,K,gn,ln,rn,en,C,N,I=sn,$n;for($n=0;$n<64;$n++)I[$n]=x[$n]*nn[$n];for($n=0;$n<8;++$n){var q=8*$n;if(I[1+q]==0&&I[2+q]==0&&I[3+q]==0&&I[4+q]==0&&I[5+q]==0&&I[6+q]==0&&I[7+q]==0){N=c*I[0+q]+512>>10,I[0+q]=N,I[1+q]=N,I[2+q]=N,I[3+q]=N,I[4+q]=N,I[5+q]=N,I[6+q]=N,I[7+q]=N;continue}Y=c*I[0+q]+128>>8,$=c*I[4+q]+128>>8,K=I[2+q],gn=I[6+q],ln=h*(I[1+q]-I[7+q])+128>>8,C=h*(I[1+q]+I[7+q])+128>>8,rn=I[3+q]<<4,en=I[5+q]<<4,N=Y-$+1>>1,Y=Y+$+1>>1,$=N,N=K*u+gn*s+128>>8,K=K*s-gn*u+128>>8,gn=N,N=ln-en+1>>1,ln=ln+en+1>>1,en=N,N=C+rn+1>>1,rn=C-rn+1>>1,C=N,N=Y-gn+1>>1,Y=Y+gn+1>>1,gn=N,N=$-K+1>>1,$=$+K+1>>1,K=N,N=ln*o+C*i+2048>>12,ln=ln*i-C*o+2048>>12,C=N,N=rn*t+en*e+2048>>12,rn=rn*e-en*t+2048>>12,en=N,I[0+q]=Y+C,I[7+q]=Y-C,I[1+q]=$+en,I[6+q]=$-en,I[2+q]=K+rn,I[5+q]=K-rn,I[3+q]=gn+ln,I[4+q]=gn-ln}for($n=0;$n<8;++$n){var _=$n;if(I[8+_]==0&&I[16+_]==0&&I[24+_]==0&&I[32+_]==0&&I[40+_]==0&&I[48+_]==0&&I[56+_]==0){N=c*sn[$n+0]+8192>>14,I[0+_]=N,I[8+_]=N,I[16+_]=N,I[24+_]=N,I[32+_]=N,I[40+_]=N,I[48+_]=N,I[56+_]=N;continue}Y=c*I[0+_]+2048>>12,$=c*I[32+_]+2048>>12,K=I[16+_],gn=I[48+_],ln=h*(I[8+_]-I[56+_])+2048>>12,C=h*(I[8+_]+I[56+_])+2048>>12,rn=I[24+_],en=I[40+_],N=Y-$+1>>1,Y=Y+$+1>>1,$=N,N=K*u+gn*s+2048>>12,K=K*s-gn*u+2048>>12,gn=N,N=ln-en+1>>1,ln=ln+en+1>>1,en=N,N=C+rn+1>>1,rn=C-rn+1>>1,C=N,N=Y-gn+1>>1,Y=Y+gn+1>>1,gn=N,N=$-K+1>>1,$=$+K+1>>1,K=N,N=ln*o+C*i+2048>>12,ln=ln*i-C*o+2048>>12,C=N,N=rn*t+en*e+2048>>12,rn=rn*e-en*t+2048>>12,en=N,I[0+_]=Y+C,I[56+_]=Y-C,I[8+_]=$+en,I[48+_]=$-en,I[16+_]=K+rn,I[40+_]=K-rn,I[24+_]=gn+ln,I[32+_]=gn-ln}for($n=0;$n<64;++$n){var An=128+(I[$n]+8>>4);Nn[$n]=An<0?0:An>255?255:An}}F(M*R*8);var G,z;for(var U=0;U<R;U++){var Sn=U<<3;for(G=0;G<8;G++)y.push(new Uint8Array(M));for(var Q=0;Q<p;Q++){J(k.blocks[U][Q],H,j);var B=0,En=Q<<3;for(z=0;z<8;z++){var mn=y[Sn+z];for(G=0;G<8;G++)mn[En+G]=H[B++]}}}return y}function w(S){return S<0?0:S>255?255:S}f.prototype={load:function(k){var y=new XMLHttpRequest;y.open("GET",k,!0),y.responseType="arraybuffer",y.onload=function(){var p=new Uint8Array(y.response||y.mozResponseArrayBuffer);if(this.parse(p),this.onload)this.onload()}.bind(this),y.send(null)},parse:function(k){var y=this.opts.maxResolutionInMP*1000*1000,p=0,R=k.length;function M(){var Z=k[p]<<8|k[p+1];return p+=2,Z}function j(){var Z=M(),un=k.subarray(p,p+Z-2);return p+=un.length,un}function H(Z){var un=1,jn=1,kn,Xn;for(Xn in Z.components)if(Z.components.hasOwnProperty(Xn)){if(kn=Z.components[Xn],un<kn.h)un=kn.h;if(jn<kn.v)jn=kn.v}var nr=Math.ceil(Z.samplesPerLine/8/un),Fr=Math.ceil(Z.scanLines/8/jn);for(Xn in Z.components)if(Z.components.hasOwnProperty(Xn)){kn=Z.components[Xn];var Jr=Math.ceil(Math.ceil(Z.samplesPerLine/8)*kn.h/un),Kr=Math.ceil(Math.ceil(Z.scanLines/8)*kn.v/jn),oe=nr*kn.h,se=Fr*kn.v,Ze=se*oe,ue=[];F(Ze*256);for(var ce=0;ce<se;ce++){var he=[];for(var fe=0;fe<oe;fe++)he.push(new Int32Array(64));ue.push(he)}kn.blocksPerLine=Jr,kn.blocksPerColumn=Kr,kn.blocks=ue}Z.maxH=un,Z.maxV=jn,Z.mcusPerLine=nr,Z.mcusPerColumn=Fr}var J=null,G=null,z=null,U,Sn,Q=[],B=[],En=[],mn=[],x=M(),Nn=-1;if(this.comments=[],x!=65496)throw Error("SOI not found");x=M();while(x!=65497){var sn,nn,Y;switch(x){case 65280:break;case 65504:case 65505:case 65506:case 65507:case 65508:case 65509:case 65510:case 65511:case 65512:case 65513:case 65514:case 65515:case 65516:case 65517:case 65518:case 65519:case 65534:var $=j();if(x===65534){var K=String.fromCharCode.apply(null,$);this.comments.push(K)}if(x===65504){if($[0]===74&&$[1]===70&&$[2]===73&&$[3]===70&&$[4]===0)J={version:{major:$[5],minor:$[6]},densityUnits:$[7],xDensity:$[8]<<8|$[9],yDensity:$[10]<<8|$[11],thumbWidth:$[12],thumbHeight:$[13],thumbData:$.subarray(14,14+3*$[12]*$[13])}}if(x===65505){if($[0]===69&&$[1]===120&&$[2]===105&&$[3]===102&&$[4]===0)this.exifBuffer=$.subarray(5,$.length)}if(x===65518){if($[0]===65&&$[1]===100&&$[2]===111&&$[3]===98&&$[4]===101&&$[5]===0)G={version:$[6],flags0:$[7]<<8|$[8],flags1:$[9]<<8|$[10],transformCode:$[11]}}break;case 65499:var gn=M(),ln=gn+p-2;while(p<ln){var rn=k[p++];F(256);var en=new Int32Array(64);if(rn>>4===0)for(nn=0;nn<64;nn++){var C=r[nn];en[C]=k[p++]}else if(rn>>4===1)for(nn=0;nn<64;nn++){var C=r[nn];en[C]=M()}else throw Error("DQT: invalid table spec");Q[rn&15]=en}break;case 65472:case 65473:case 65474:M(),U={},U.extended=x===65473,U.progressive=x===65474,U.precision=k[p++],U.scanLines=M(),U.samplesPerLine=M(),U.components={},U.componentsOrder=[];var N=U.scanLines*U.samplesPerLine;if(N>y){var I=Math.ceil((N-y)/1e6);throw Error(`maxResolutionInMP limit exceeded by ${I}MP`)}var $n=k[p++],q,_=0,An=0;for(sn=0;sn<$n;sn++){q=k[p];var Cn=k[p+1]>>4,a=k[p+1]&15,L=k[p+2];if(Cn<=0||a<=0)throw Error("Invalid sampling factor, expected values above 0");U.componentsOrder.push(q),U.components[q]={h:Cn,v:a,quantizationIdx:L},p+=3}H(U),B.push(U);break;case 65476:var W=M();for(sn=2;sn<W;){var P=k[p++],X=new Uint8Array(16),T=0;for(nn=0;nn<16;nn++,p++)T+=X[nn]=k[p];F(16+T);var tn=new Uint8Array(T);for(nn=0;nn<T;nn++,p++)tn[nn]=k[p];sn+=17+T,(P>>4===0?mn:En)[P&15]=l(X,tn)}break;case 65501:M(),Sn=M();break;case 65500:M(),M();break;case 65498:var on=M(),In=k[p++],wn=[],v;for(sn=0;sn<In;sn++){v=U.components[k[p++]];var O=k[p++];v.huffmanTableDC=mn[O>>4],v.huffmanTableAC=En[O&15],wn.push(v)}var A=k[p++],vn=k[p++],V=k[p++],D=g(k,p,U,wn,Sn,A,vn,V>>4,V&15,this.opts);p+=D;break;case 65535:if(k[p]!==255)p--;break;default:if(k[p-3]==255&&k[p-2]>=192&&k[p-2]<=254){p-=3;break}else if(x===224||x==225){if(Nn!==-1)throw Error(`first unknown JPEG marker at offset ${Nn.toString(16)}, second unknown JPEG marker ${x.toString(16)} at offset ${(p-1).toString(16)}`);Nn=p-1;let Z=M();if(k[p+Z-2]===255){p+=Z-2;break}}throw Error("unknown JPEG marker "+x.toString(16))}x=M()}if(B.length!=1)throw Error("only single frame JPEGs supported");for(var sn=0;sn<B.length;sn++){var an=B[sn].components;for(var nn in an)an[nn].quantizationTable=Q[an[nn].quantizationIdx],delete an[nn].quantizationIdx}this.width=U.samplesPerLine,this.height=U.scanLines,this.jfif=J,this.adobe=G,this.components=[];for(var sn=0;sn<U.componentsOrder.length;sn++){var v=U.components[U.componentsOrder[sn]];this.components.push({lines:d(U,v),scaleX:v.h/U.maxH,scaleY:v.v/U.maxV})}},getData:function(k,y){var p=this.width/k,R=this.height/y,M,j,H,J,G,z,U,Sn,Q,B,En=0,mn,x,Nn,sn,nn,Y,$,K,gn,ln,rn,en=k*y*this.components.length;F(en);var C=new Uint8Array(en);switch(this.components.length){case 1:M=this.components[0];for(B=0;B<y;B++){G=M.lines[0|B*M.scaleY*R];for(Q=0;Q<k;Q++)mn=G[0|Q*M.scaleX*p],C[En++]=mn}break;case 2:M=this.components[0],j=this.components[1];for(B=0;B<y;B++){G=M.lines[0|B*M.scaleY*R],z=j.lines[0|B*j.scaleY*R];for(Q=0;Q<k;Q++)mn=G[0|Q*M.scaleX*p],C[En++]=mn,mn=z[0|Q*j.scaleX*p],C[En++]=mn}break;case 3:if(rn=!0,this.adobe&&this.adobe.transformCode)rn=!0;else if(typeof this.opts.colorTransform<"u")rn=!!this.opts.colorTransform;M=this.components[0],j=this.components[1],H=this.components[2];for(B=0;B<y;B++){G=M.lines[0|B*M.scaleY*R],z=j.lines[0|B*j.scaleY*R],U=H.lines[0|B*H.scaleY*R];for(Q=0;Q<k;Q++){if(!rn)K=G[0|Q*M.scaleX*p],gn=z[0|Q*j.scaleX*p],ln=U[0|Q*H.scaleX*p];else mn=G[0|Q*M.scaleX*p],x=z[0|Q*j.scaleX*p],Nn=U[0|Q*H.scaleX*p],K=w(mn+1.402*(Nn-128)),gn=w(mn-0.3441363*(x-128)-0.71413636*(Nn-128)),ln=w(mn+1.772*(x-128));C[En++]=K,C[En++]=gn,C[En++]=ln}}break;case 4:if(!this.adobe)throw Error("Unsupported color mode (4 components)");if(rn=!1,this.adobe&&this.adobe.transformCode)rn=!0;else if(typeof this.opts.colorTransform<"u")rn=!!this.opts.colorTransform;M=this.components[0],j=this.components[1],H=this.components[2],J=this.components[3];for(B=0;B<y;B++){G=M.lines[0|B*M.scaleY*R],z=j.lines[0|B*j.scaleY*R],U=H.lines[0|B*H.scaleY*R],Sn=J.lines[0|B*J.scaleY*R];for(Q=0;Q<k;Q++){if(!rn)nn=G[0|Q*M.scaleX*p],Y=z[0|Q*j.scaleX*p],$=U[0|Q*H.scaleX*p],sn=Sn[0|Q*J.scaleX*p];else mn=G[0|Q*M.scaleX*p],x=z[0|Q*j.scaleX*p],Nn=U[0|Q*H.scaleX*p],sn=Sn[0|Q*J.scaleX*p],nn=255-w(mn+1.402*(Nn-128)),Y=255-w(mn-0.3441363*(x-128)-0.71413636*(Nn-128)),$=255-w(mn+1.772*(x-128));C[En++]=255-nn,C[En++]=255-Y,C[En++]=255-$,C[En++]=255-sn}}break;default:throw Error("Unsupported color mode")}return C},copyToImageData:function(k,y){var{width:p,height:R,data:M}=k,j=this.getData(p,R),H=0,J=0,G,z,U,Sn,Q,B,En,mn,x;switch(this.components.length){case 1:for(z=0;z<R;z++)for(G=0;G<p;G++)if(U=j[H++],M[J++]=U,M[J++]=U,M[J++]=U,y)M[J++]=255;break;case 3:for(z=0;z<R;z++)for(G=0;G<p;G++)if(En=j[H++],mn=j[H++],x=j[H++],M[J++]=En,M[J++]=mn,M[J++]=x,y)M[J++]=255;break;case 4:for(z=0;z<R;z++)for(G=0;G<p;G++)if(Q=j[H++],B=j[H++],U=j[H++],Sn=j[H++],En=255-w(Q*(1-Sn/255)+Sn),mn=255-w(B*(1-Sn/255)+Sn),x=255-w(U*(1-Sn/255)+Sn),M[J++]=En,M[J++]=mn,M[J++]=x,y)M[J++]=255;break;default:throw Error("Unsupported color mode")}}};var m=0,b=0;function F(S=0){var k=m+S;if(k>b){var y=Math.ceil((k-b)/1024/1024);throw Error(`maxMemoryUsageInMB limit exceeded by at least ${y}MB`)}m=k}return f.resetMaxMemoryUsage=function(S){m=0,b=S},f.getBytesAllocated=function(){return m},f.requestMemoryAllocation=F,f}();if(typeof Pt<"u")Pt.exports=Jo;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].decode=Jo;function Jo(n,r={}){var e={colorTransform:void 0,useTArray:!1,formatAsRGBA:!0,tolerantDecoding:!0,maxResolutionInMP:100,maxMemoryUsageInMB:512},t={...e,...r},i=new Uint8Array(n),o=new Kt;o.opts=t,Kt.resetMaxMemoryUsage(t.maxMemoryUsageInMB*1024*1024),o.parse(i);var s=t.formatAsRGBA?4:3,u=o.width*o.height*s;try{Kt.requestMemoryAllocation(u);var c={width:o.width,height:o.height,exifBuffer:o.exifBuffer,data:t.useTArray?new Uint8Array(u):Buffer.alloc(u)};if(o.comments.length>0)c.comments=o.comments}catch(h){if(h instanceof RangeError)throw Error("Could not allocate enough memory for the image. Required: "+u);if(h instanceof ReferenceError){if(h.message==="Buffer is not defined")throw Error("Buffer is not globally defined in this environment. Consider setting useTArray to true")}throw h}return o.copyToImageData(c,t.formatAsRGBA),c}});var Uo=pn((N0,Po)=>{var Pf=Lo(),Uf=Ko();Po.exports={encode:Pf,decode:Uf}});var Ut=pn((H0,Wo)=>{var Qf=Rn("util"),Qo=Rn("stream"),Bn=Wo.exports=function(){Qo.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};Qf.inherits(Bn,Qo);Bn.prototype.read=function(n,r){this._reads.push({length:Math.abs(n),allowLess:n<0,func:r}),process.nextTick(function(){if(this._process(),this._paused&&this._reads&&this._reads.length>0)this._paused=!1,this.emit("drain")}.bind(this))};Bn.prototype.write=function(n,r){if(!this.writable)return this.emit("error",Error("Stream not writable")),!1;let e;if(Buffer.isBuffer(n))e=n;else e=Buffer.from(n,r||this._encoding);if(this._buffers.push(e),this._buffered+=e.length,this._process(),this._reads&&this._reads.length===0)this._paused=!0;return this.writable&&!this._paused};Bn.prototype.end=function(n,r){if(n)this.write(n,r);if(this.writable=!1,!this._buffers)return;if(this._buffers.length===0)this._end();else this._buffers.push(null),this._process()};Bn.prototype.destroySoon=Bn.prototype.end;Bn.prototype._end=function(){if(this._reads.length>0)this.emit("error",Error("Unexpected end of input"));this.destroy()};Bn.prototype.destroy=function(){if(!this._buffers)return;this.writable=!1,this._reads=null,this._buffers=null,this.emit("close")};Bn.prototype._processReadAllowingLess=function(n){this._reads.shift();let r=this._buffers[0];if(r.length>n.length)this._buffered-=n.length,this._buffers[0]=r.slice(n.length),n.func.call(this,r.slice(0,n.length));else this._buffered-=r.length,this._buffers.shift(),n.func.call(this,r)};Bn.prototype._processRead=function(n){this._reads.shift();let r=0,e=0,t=Buffer.alloc(n.length);while(r<n.length){let i=this._buffers[e++],o=Math.min(i.length,n.length-r);if(i.copy(t,r,0,o),r+=o,o!==i.length)this._buffers[--e]=i.slice(o)}if(e>0)this._buffers.splice(0,e);this._buffered-=n.length,n.func.call(this,t)};Bn.prototype._process=function(){try{while(this._buffered>0&&this._reads&&this._reads.length>0){let n=this._reads[0];if(n.allowLess)this._processReadAllowingLess(n);else if(this._buffered>=n.length)this._processRead(n);else break}if(this._buffers&&!this.writable)this._end()}catch(n){this.emit("error",n)}}});var Qt=pn((Wf)=>{var wr=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];Wf.getImagePasses=function(n,r){let e=[],t=n%8,i=r%8,o=(n-t)/8,s=(r-i)/8;for(let u=0;u<wr.length;u++){let c=wr[u],h=o*c.x.length,f=s*c.y.length;for(let l=0;l<c.x.length;l++)if(c.x[l]<t)h++;else break;for(let l=0;l<c.y.length;l++)if(c.y[l]<i)f++;else break;if(h>0&&f>0)e.push({width:h,height:f,index:u})}return e};Wf.getInterlaceIterator=function(n){return function(r,e,t){let i=r%wr[t].x.length,o=(r-i)/wr[t].x.length*8+wr[t].x[i],s=e%wr[t].y.length,u=(e-s)/wr[t].y.length*8+wr[t].y[s];return o*4+u*n*4}}});var Wt=pn((j0,Zo)=>{Zo.exports=function(r,e,t){let i=r+e-t,o=Math.abs(i-r),s=Math.abs(i-e),u=Math.abs(i-t);if(o<=s&&o<=u)return r;if(s<=u)return e;return t}});var Zt=pn((R0,Ao)=>{var Af=Qt(),Xf=Wt();function qo(n,r,e){let t=n*r;if(e!==8)t=Math.ceil(t/(8/e));return t}var Ur=Ao.exports=function(n,r){let{width:e,height:t,interlace:i,bpp:o,depth:s}=n;if(this.read=r.read,this.write=r.write,this.complete=r.complete,this._imageIndex=0,this._images=[],i){let u=Af.getImagePasses(e,t);for(let c=0;c<u.length;c++)this._images.push({byteWidth:qo(u[c].width,o,s),height:u[c].height,lineIndex:0})}else this._images.push({byteWidth:qo(e,o,s),height:t,lineIndex:0});if(s===8)this._xComparison=o;else if(s===16)this._xComparison=o*2;else this._xComparison=1};Ur.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Ur.prototype._unFilterType1=function(n,r,e){let t=this._xComparison,i=t-1;for(let o=0;o<e;o++){let s=n[1+o],u=o>i?r[o-t]:0;r[o]=s+u}};Ur.prototype._unFilterType2=function(n,r,e){let t=this._lastLine;for(let i=0;i<e;i++){let o=n[1+i],s=t?t[i]:0;r[i]=o+s}};Ur.prototype._unFilterType3=function(n,r,e){let t=this._xComparison,i=t-1,o=this._lastLine;for(let s=0;s<e;s++){let u=n[1+s],c=o?o[s]:0,h=s>i?r[s-t]:0,f=Math.floor((h+c)/2);r[s]=u+f}};Ur.prototype._unFilterType4=function(n,r,e){let t=this._xComparison,i=t-1,o=this._lastLine;for(let s=0;s<e;s++){let u=n[1+s],c=o?o[s]:0,h=s>i?r[s-t]:0,f=s>i&&o?o[s-t]:0,l=Xf(h,c,f);r[s]=u+l}};Ur.prototype._reverseFilterLine=function(n){let r=n[0],e,t=this._images[this._imageIndex],i=t.byteWidth;if(r===0)e=n.slice(1,i+1);else switch(e=Buffer.alloc(i),r){case 1:this._unFilterType1(n,e,i);break;case 2:this._unFilterType2(n,e,i);break;case 3:this._unFilterType3(n,e,i);break;case 4:this._unFilterType4(n,e,i);break;default:throw Error("Unrecognised filter type - "+r)}if(this.write(e),t.lineIndex++,t.lineIndex>=t.height)this._lastLine=null,this._imageIndex++,t=this._images[this._imageIndex];else this._lastLine=e;if(t)this.read(t.byteWidth+1,this._reverseFilterLine.bind(this));else this._lastLine=null,this.complete()}});var Vo=pn((G0,To)=>{var Tf=Rn("util"),Xo=Ut(),Vf=Zt(),zf=To.exports=function(n){Xo.call(this);let r=[],e=this;this._filter=new Vf(n,{read:this.read.bind(this),write:function(t){r.push(t)},complete:function(){e.emit("complete",Buffer.concat(r))}}),this._filter.start()};Tf.inherits(zf,Xo)});var Qr=pn((L0,zo)=>{zo.exports={PNG_SIGNATURE:[137,80,78,71,13,10,26,10],TYPE_IHDR:1229472850,TYPE_IEND:1229278788,TYPE_IDAT:1229209940,TYPE_PLTE:1347179589,TYPE_tRNS:1951551059,TYPE_gAMA:1732332865,COLORTYPE_GRAYSCALE:0,COLORTYPE_PALETTE:1,COLORTYPE_COLOR:2,COLORTYPE_ALPHA:4,COLORTYPE_PALETTE_COLOR:3,COLORTYPE_COLOR_ALPHA:6,COLORTYPE_TO_BPP_MAP:{0:1,2:3,3:1,4:2,6:4},GAMMA_DIVISION:1e5}});var Xt=pn((J0,Yo)=>{var qt=[];(function(){for(let n=0;n<256;n++){let r=n;for(let e=0;e<8;e++)if(r&1)r=3988292384^r>>>1;else r=r>>>1;qt[n]=r}})();var At=Yo.exports=function(){this._crc=-1};At.prototype.write=function(n){for(let r=0;r<n.length;r++)this._crc=qt[(this._crc^n[r])&255]^this._crc>>>8;return!0};At.prototype.crc32=function(){return this._crc^-1};At.crc32=function(n){let r=-1;for(let e=0;e<n.length;e++)r=qt[(r^n[e])&255]^r>>>8;return r^-1}});var Tt=pn((K0,Co)=>{var Hn=Qr(),Yf=Xt(),On=Co.exports=function(n,r){this._options=n,n.checkCRC=n.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[Hn.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[Hn.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[Hn.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[Hn.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[Hn.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[Hn.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=r.read,this.error=r.error,this.metadata=r.metadata,this.gamma=r.gamma,this.transColor=r.transColor,this.palette=r.palette,this.parsed=r.parsed,this.inflateData=r.inflateData,this.finished=r.finished,this.simpleTransparency=r.simpleTransparency,this.headersFinished=r.headersFinished||function(){}};On.prototype.start=function(){this.read(Hn.PNG_SIGNATURE.length,this._parseSignature.bind(this))};On.prototype._parseSignature=function(n){let r=Hn.PNG_SIGNATURE;for(let e=0;e<r.length;e++)if(n[e]!==r[e]){this.error(Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};On.prototype._parseChunkBegin=function(n){let r=n.readUInt32BE(0),e=n.readUInt32BE(4),t="";for(let o=4;o<8;o++)t+=String.fromCharCode(n[o]);let i=Boolean(n[4]&32);if(!this._hasIHDR&&e!==Hn.TYPE_IHDR){this.error(Error("Expected IHDR on beggining"));return}if(this._crc=new Yf,this._crc.write(Buffer.from(t)),this._chunks[e])return this._chunks[e](r);if(!i){this.error(Error("Unsupported critical chunk type "+t));return}this.read(r+4,this._skipChunk.bind(this))};On.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};On.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};On.prototype._parseChunkEnd=function(n){let r=n.readInt32BE(0),e=this._crc.crc32();if(this._options.checkCRC&&e!==r){this.error(Error("Crc error - "+r+" - "+e));return}if(!this._hasIEND)this.read(8,this._parseChunkBegin.bind(this))};On.prototype._handleIHDR=function(n){this.read(n,this._parseIHDR.bind(this))};On.prototype._parseIHDR=function(n){this._crc.write(n);let r=n.readUInt32BE(0),e=n.readUInt32BE(4),t=n[8],i=n[9],o=n[10],s=n[11],u=n[12];if(t!==8&&t!==4&&t!==2&&t!==1&&t!==16){this.error(Error("Unsupported bit depth "+t));return}if(!(i in Hn.COLORTYPE_TO_BPP_MAP)){this.error(Error("Unsupported color type"));return}if(o!==0){this.error(Error("Unsupported compression method"));return}if(s!==0){this.error(Error("Unsupported filter method"));return}if(u!==0&&u!==1){this.error(Error("Unsupported interlace method"));return}this._colorType=i;let c=Hn.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:r,height:e,depth:t,interlace:Boolean(u),palette:Boolean(i&Hn.COLORTYPE_PALETTE),color:Boolean(i&Hn.COLORTYPE_COLOR),alpha:Boolean(i&Hn.COLORTYPE_ALPHA),bpp:c,colorType:i}),this._handleChunkEnd()};On.prototype._handlePLTE=function(n){this.read(n,this._parsePLTE.bind(this))};On.prototype._parsePLTE=function(n){this._crc.write(n);let r=Math.floor(n.length/3);for(let e=0;e<r;e++)this._palette.push([n[e*3],n[e*3+1],n[e*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};On.prototype._handleTRNS=function(n){this.simpleTransparency(),this.read(n,this._parseTRNS.bind(this))};On.prototype._parseTRNS=function(n){if(this._crc.write(n),this._colorType===Hn.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(Error("Transparency chunk must be after palette"));return}if(n.length>this._palette.length){this.error(Error("More transparent colors than palette size"));return}for(let r=0;r<n.length;r++)this._palette[r][3]=n[r];this.palette(this._palette)}if(this._colorType===Hn.COLORTYPE_GRAYSCALE)this.transColor([n.readUInt16BE(0)]);if(this._colorType===Hn.COLORTYPE_COLOR)this.transColor([n.readUInt16BE(0),n.readUInt16BE(2),n.readUInt16BE(4)]);this._handleChunkEnd()};On.prototype._handleGAMA=function(n){this.read(n,this._parseGAMA.bind(this))};On.prototype._parseGAMA=function(n){this._crc.write(n),this.gamma(n.readUInt32BE(0)/Hn.GAMMA_DIVISION),this._handleChunkEnd()};On.prototype._handleIDAT=function(n){if(!this._emittedHeadersFinished)this._emittedHeadersFinished=!0,this.headersFinished();this.read(-n,this._parseIDAT.bind(this,n))};On.prototype._parseIDAT=function(n,r){if(this._crc.write(r),this._colorType===Hn.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw Error("Expected palette not found");this.inflateData(r);let e=n-r.length;if(e>0)this._handleIDAT(e);else this._handleChunkEnd()};On.prototype._handleIEND=function(n){this.read(n,this._parseIEND.bind(this))};On.prototype._parseIEND=function(n){if(this._crc.write(n),this._hasIEND=!0,this._handleChunkEnd(),this.finished)this.finished()}});var Vt=pn((ng)=>{var _o=Qt(),Cf=[function(){},function(n,r,e,t){if(t===r.length)throw Error("Ran out of data");let i=r[t];n[e]=i,n[e+1]=i,n[e+2]=i,n[e+3]=255},function(n,r,e,t){if(t+1>=r.length)throw Error("Ran out of data");let i=r[t];n[e]=i,n[e+1]=i,n[e+2]=i,n[e+3]=r[t+1]},function(n,r,e,t){if(t+2>=r.length)throw Error("Ran out of data");n[e]=r[t],n[e+1]=r[t+1],n[e+2]=r[t+2],n[e+3]=255},function(n,r,e,t){if(t+3>=r.length)throw Error("Ran out of data");n[e]=r[t],n[e+1]=r[t+1],n[e+2]=r[t+2],n[e+3]=r[t+3]}],_f=[function(){},function(n,r,e,t){let i=r[0];n[e]=i,n[e+1]=i,n[e+2]=i,n[e+3]=t},function(n,r,e){let t=r[0];n[e]=t,n[e+1]=t,n[e+2]=t,n[e+3]=r[1]},function(n,r,e,t){n[e]=r[0],n[e+1]=r[1],n[e+2]=r[2],n[e+3]=t},function(n,r,e){n[e]=r[0],n[e+1]=r[1],n[e+2]=r[2],n[e+3]=r[3]}];function Bf(n,r){let e=[],t=0;function i(){if(t===n.length)throw Error("Ran out of data");let o=n[t];t++;let s,u,c,h,f,l,g,d;switch(r){default:throw Error("unrecognised depth");case 16:g=n[t],t++,e.push((o<<8)+g);break;case 4:g=o&15,d=o>>4,e.push(d,g);break;case 2:f=o&3,l=o>>2&3,g=o>>4&3,d=o>>6&3,e.push(d,g,l,f);break;case 1:s=o&1,u=o>>1&1,c=o>>2&1,h=o>>3&1,f=o>>4&1,l=o>>5&1,g=o>>6&1,d=o>>7&1,e.push(d,g,l,f,h,c,u,s);break}}return{get:function(o){while(e.length<o)i();let s=e.slice(0,o);return e=e.slice(o),s},resetAfterLine:function(){e.length=0},end:function(){if(t!==n.length)throw Error("extra data found")}}}function xf(n,r,e,t,i,o){let{width:s,height:u,index:c}=n;for(let h=0;h<u;h++)for(let f=0;f<s;f++){let l=e(f,h,c);Cf[t](r,i,l,o),o+=t}return o}function Df(n,r,e,t,i,o){let{width:s,height:u,index:c}=n;for(let h=0;h<u;h++){for(let f=0;f<s;f++){let l=i.get(t),g=e(f,h,c);_f[t](r,l,g,o)}i.resetAfterLine()}}ng.dataToBitMap=function(n,r){let{width:e,height:t,depth:i,bpp:o,interlace:s}=r,u;if(i!==8)u=Bf(n,i);let c;if(i<=8)c=Buffer.alloc(e*t*4);else c=new Uint16Array(e*t*4);let h=Math.pow(2,i)-1,f=0,l,g;if(s)l=_o.getImagePasses(e,t),g=_o.getInterlaceIterator(e,t);else{let d=0;g=function(){let w=d;return d+=4,w},l=[{width:e,height:t}]}for(let d=0;d<l.length;d++)if(i===8)f=xf(l[d],c,g,o,n,f);else Df(l[d],c,g,o,u,h);if(i===8){if(f!==n.length)throw Error("extra data found")}else u.end();return c}});var zt=pn((U0,Bo)=>{function eg(n,r,e,t,i){let o=0;for(let s=0;s<t;s++)for(let u=0;u<e;u++){let c=i[n[o]];if(!c)throw Error("index "+n[o]+" not in palette");for(let h=0;h<4;h++)r[o+h]=c[h];o+=4}}function tg(n,r,e,t,i){let o=0;for(let s=0;s<t;s++)for(let u=0;u<e;u++){let c=!1;if(i.length===1){if(i[0]===n[o])c=!0}else if(i[0]===n[o]&&i[1]===n[o+1]&&i[2]===n[o+2])c=!0;if(c)for(let h=0;h<4;h++)r[o+h]=0;o+=4}}function ig(n,r,e,t,i){let o=255,s=Math.pow(2,i)-1,u=0;for(let c=0;c<t;c++)for(let h=0;h<e;h++){for(let f=0;f<4;f++)r[u+f]=Math.floor(n[u+f]*o/s+0.5);u+=4}}Bo.exports=function(n,r,e=!1){let{depth:t,width:i,height:o,colorType:s,transColor:u,palette:c}=r,h=n;if(s===3)eg(n,h,i,o,c);else{if(u)tg(n,h,i,o,u);if(t!==8&&!e){if(t===16)h=Buffer.alloc(i*o*4);ig(n,h,i,o,t)}}return h}});var ns=pn((Q0,Do)=>{var og=Rn("util"),Yt=Rn("zlib"),xo=Ut(),sg=Vo(),ug=Tt(),cg=Vt(),hg=zt(),er=Do.exports=function(n){xo.call(this),this._parser=new ug(n,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,"gamma"),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=n,this.writable=!0,this._parser.start()};og.inherits(er,xo);er.prototype._handleError=function(n){if(this.emit("error",n),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy)this._inflate.destroy();if(this._filter)this._filter.destroy(),this._filter.on("error",function(){});this.errord=!0};er.prototype._inflateData=function(n){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=Yt.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let e=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,t=Math.max(e,Yt.Z_MIN_CHUNK);this._inflate=Yt.createInflate({chunkSize:t});let i=e,o=this.emit.bind(this,"error");this._inflate.on("error",function(u){if(!i)return;o(u)}),this._filter.on("complete",this._complete.bind(this));let s=this._filter.write.bind(this._filter);this._inflate.on("data",function(u){if(!i)return;if(u.length>i)u=u.slice(0,i);i-=u.length,s(u)}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(n)};er.prototype._handleMetaData=function(n){this._metaData=n,this._bitmapInfo=Object.create(n),this._filter=new sg(this._bitmapInfo)};er.prototype._handleTransColor=function(n){this._bitmapInfo.transColor=n};er.prototype._handlePalette=function(n){this._bitmapInfo.palette=n};er.prototype._simpleTransparency=function(){this._metaData.alpha=!0};er.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};er.prototype._finished=function(){if(this.errord)return;if(!this._inflate)this.emit("error","No Inflate block");else this._inflate.end()};er.prototype._complete=function(n){if(this.errord)return;let r;try{let e=cg.dataToBitMap(n,this._bitmapInfo);r=hg(e,this._bitmapInfo,this._options.skipRescale),e=null}catch(e){this._handleError(e);return}this.emit("parsed",r)}});var es=pn((W0,rs)=>{var Tn=Qr();rs.exports=function(n,r,e,t){let i=[Tn.COLORTYPE_COLOR_ALPHA,Tn.COLORTYPE_ALPHA].indexOf(t.colorType)!==-1;if(t.colorType===t.inputColorType){let w=function(){let m=new ArrayBuffer(2);return new DataView(m).setInt16(0,256,!0),new Int16Array(m)[0]!==256}();if(t.bitDepth===8||t.bitDepth===16&&w)return n}let o=t.bitDepth!==16?n:new Uint16Array(n.buffer),s=255,u=Tn.COLORTYPE_TO_BPP_MAP[t.inputColorType];if(u===4&&!t.inputHasAlpha)u=3;let c=Tn.COLORTYPE_TO_BPP_MAP[t.colorType];if(t.bitDepth===16)s=65535,c*=2;let h=Buffer.alloc(r*e*c),f=0,l=0,g=t.bgColor||{};if(g.red===void 0)g.red=s;if(g.green===void 0)g.green=s;if(g.blue===void 0)g.blue=s;function d(){let w,m,b,F=s;switch(t.inputColorType){case Tn.COLORTYPE_COLOR_ALPHA:F=o[f+3],w=o[f],m=o[f+1],b=o[f+2];break;case Tn.COLORTYPE_COLOR:w=o[f],m=o[f+1],b=o[f+2];break;case Tn.COLORTYPE_ALPHA:F=o[f+1],w=o[f],m=w,b=w;break;case Tn.COLORTYPE_GRAYSCALE:w=o[f],m=w,b=w;break;default:throw Error("input color type:"+t.inputColorType+" is not supported at present")}if(t.inputHasAlpha){if(!i)F/=s,w=Math.min(Math.max(Math.round((1-F)*g.red+F*w),0),s),m=Math.min(Math.max(Math.round((1-F)*g.green+F*m),0),s),b=Math.min(Math.max(Math.round((1-F)*g.blue+F*b),0),s)}return{red:w,green:m,blue:b,alpha:F}}for(let w=0;w<e;w++)for(let m=0;m<r;m++){let b=d(o,f);switch(t.colorType){case Tn.COLORTYPE_COLOR_ALPHA:case Tn.COLORTYPE_COLOR:if(t.bitDepth===8){if(h[l]=b.red,h[l+1]=b.green,h[l+2]=b.blue,i)h[l+3]=b.alpha}else if(h.writeUInt16BE(b.red,l),h.writeUInt16BE(b.green,l+2),h.writeUInt16BE(b.blue,l+4),i)h.writeUInt16BE(b.alpha,l+6);break;case Tn.COLORTYPE_ALPHA:case Tn.COLORTYPE_GRAYSCALE:{let F=(b.red+b.green+b.blue)/3;if(t.bitDepth===8){if(h[l]=F,i)h[l+1]=b.alpha}else if(h.writeUInt16BE(F,l),i)h.writeUInt16BE(b.alpha,l+2);break}default:throw Error("unrecognised color Type "+t.colorType)}f+=u,l+=c}return h}});var os=pn((Z0,is)=>{var ts=Wt();function fg(n,r,e,t,i){for(let o=0;o<e;o++)t[i+o]=n[r+o]}function gg(n,r,e){let t=0,i=r+e;for(let o=r;o<i;o++)t+=Math.abs(n[o]);return t}function lg(n,r,e,t,i,o){for(let s=0;s<e;s++){let u=s>=o?n[r+s-o]:0,c=n[r+s]-u;t[i+s]=c}}function ag(n,r,e,t){let i=0;for(let o=0;o<e;o++){let s=o>=t?n[r+o-t]:0,u=n[r+o]-s;i+=Math.abs(u)}return i}function dg(n,r,e,t,i){for(let o=0;o<e;o++){let s=r>0?n[r+o-e]:0,u=n[r+o]-s;t[i+o]=u}}function mg(n,r,e){let t=0,i=r+e;for(let o=r;o<i;o++){let s=r>0?n[o-e]:0,u=n[o]-s;t+=Math.abs(u)}return t}function $g(n,r,e,t,i,o){for(let s=0;s<e;s++){let u=s>=o?n[r+s-o]:0,c=r>0?n[r+s-e]:0,h=n[r+s]-(u+c>>1);t[i+s]=h}}function wg(n,r,e,t){let i=0;for(let o=0;o<e;o++){let s=o>=t?n[r+o-t]:0,u=r>0?n[r+o-e]:0,c=n[r+o]-(s+u>>1);i+=Math.abs(c)}return i}function pg(n,r,e,t,i,o){for(let s=0;s<e;s++){let u=s>=o?n[r+s-o]:0,c=r>0?n[r+s-e]:0,h=r>0&&s>=o?n[r+s-(e+o)]:0,f=n[r+s]-ts(u,c,h);t[i+s]=f}}function bg(n,r,e,t){let i=0;for(let o=0;o<e;o++){let s=o>=t?n[r+o-t]:0,u=r>0?n[r+o-e]:0,c=r>0&&o>=t?n[r+o-(e+t)]:0,h=n[r+o]-ts(s,u,c);i+=Math.abs(h)}return i}var kg={0:fg,1:lg,2:dg,3:$g,4:pg},Mg={0:gg,1:ag,2:mg,3:wg,4:bg};is.exports=function(n,r,e,t,i){let o;if(!("filterType"in t)||t.filterType===-1)o=[0,1,2,3,4];else if(typeof t.filterType==="number")o=[t.filterType];else throw Error("unrecognised filter types");if(t.bitDepth===16)i*=2;let s=r*i,u=0,c=0,h=Buffer.alloc((s+1)*e),f=o[0];for(let l=0;l<e;l++){if(o.length>1){let g=1/0;for(let d=0;d<o.length;d++){let w=Mg[o[d]](n,c,s,i);if(w<g)f=o[d],g=w}}h[u]=f,u++,kg[f](n,c,s,h,u,i),u+=s,c+=s}return h}});var Ct=pn((q0,ss)=>{var Ln=Qr(),Eg=Xt(),vg=es(),Fg=os(),yg=Rn("zlib"),pr=ss.exports=function(n){if(this._options=n,n.deflateChunkSize=n.deflateChunkSize||32768,n.deflateLevel=n.deflateLevel!=null?n.deflateLevel:9,n.deflateStrategy=n.deflateStrategy!=null?n.deflateStrategy:3,n.inputHasAlpha=n.inputHasAlpha!=null?n.inputHasAlpha:!0,n.deflateFactory=n.deflateFactory||yg.createDeflate,n.bitDepth=n.bitDepth||8,n.colorType=typeof n.colorType==="number"?n.colorType:Ln.COLORTYPE_COLOR_ALPHA,n.inputColorType=typeof n.inputColorType==="number"?n.inputColorType:Ln.COLORTYPE_COLOR_ALPHA,[Ln.COLORTYPE_GRAYSCALE,Ln.COLORTYPE_COLOR,Ln.COLORTYPE_COLOR_ALPHA,Ln.COLORTYPE_ALPHA].indexOf(n.colorType)===-1)throw Error("option color type:"+n.colorType+" is not supported at present");if([Ln.COLORTYPE_GRAYSCALE,Ln.COLORTYPE_COLOR,Ln.COLORTYPE_COLOR_ALPHA,Ln.COLORTYPE_ALPHA].indexOf(n.inputColorType)===-1)throw Error("option input color type:"+n.inputColorType+" is not supported at present");if(n.bitDepth!==8&&n.bitDepth!==16)throw Error("option bit depth:"+n.bitDepth+" is not supported at present")};pr.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};pr.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};pr.prototype.filterData=function(n,r,e){let t=vg(n,r,e,this._options),i=Ln.COLORTYPE_TO_BPP_MAP[this._options.colorType];return Fg(t,r,e,this._options,i)};pr.prototype._packChunk=function(n,r){let e=r?r.length:0,t=Buffer.alloc(e+12);if(t.writeUInt32BE(e,0),t.writeUInt32BE(n,4),r)r.copy(t,8);return t.writeInt32BE(Eg.crc32(t.slice(4,t.length-4)),t.length-4),t};pr.prototype.packGAMA=function(n){let r=Buffer.alloc(4);return r.writeUInt32BE(Math.floor(n*Ln.GAMMA_DIVISION),0),this._packChunk(Ln.TYPE_gAMA,r)};pr.prototype.packIHDR=function(n,r){let e=Buffer.alloc(13);return e.writeUInt32BE(n,0),e.writeUInt32BE(r,4),e[8]=this._options.bitDepth,e[9]=this._options.colorType,e[10]=0,e[11]=0,e[12]=0,this._packChunk(Ln.TYPE_IHDR,e)};pr.prototype.packIDAT=function(n){return this._packChunk(Ln.TYPE_IDAT,n)};pr.prototype.packIEND=function(){return this._packChunk(Ln.TYPE_IEND,null)}});var fs=pn((A0,hs)=>{var Ig=Rn("util"),us=Rn("stream"),Sg=Qr(),Ng=Ct(),cs=hs.exports=function(n){us.call(this);let r=n||{};this._packer=new Ng(r),this._deflate=this._packer.createDeflate(),this.readable=!0};Ig.inherits(cs,us);cs.prototype.pack=function(n,r,e,t){if(this.emit("data",Buffer.from(Sg.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(r,e)),t)this.emit("data",this._packer.packGAMA(t));let i=this._packer.filterData(n,r,e);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(o){this.emit("data",this._packer.packIDAT(o))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(i)}});var $s=pn((we,ms)=>{var gs=Rn("assert").ok,Wr=Rn("zlib"),Hg=Rn("util"),ls=Rn("buffer").kMaxLength;function yr(n){if(!(this instanceof yr))return new yr(n);if(n&&n.chunkSize<Wr.Z_MIN_CHUNK)n.chunkSize=Wr.Z_MIN_CHUNK;if(Wr.Inflate.call(this,n),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,n&&n.maxLength!=null)this._maxLength=n.maxLength}function Og(n){return new yr(n)}function as(n,r){if(r)process.nextTick(r);if(!n._handle)return;n._handle.close(),n._handle=null}yr.prototype._processChunk=function(n,r,e){if(typeof e==="function")return Wr.Inflate._processChunk.call(this,n,r,e);let t=this,i=n&&n.length,o=this._chunkSize-this._offset,s=this._maxLength,u=0,c=[],h=0,f;this.on("error",function(w){f=w});function l(w,m){if(t._hadError)return;let b=o-m;if(gs(b>=0,"have should not go down"),b>0){let F=t._buffer.slice(t._offset,t._offset+b);if(t._offset+=b,F.length>s)F=F.slice(0,s);if(c.push(F),h+=F.length,s-=F.length,s===0)return!1}if(m===0||t._offset>=t._chunkSize)o=t._chunkSize,t._offset=0,t._buffer=Buffer.allocUnsafe(t._chunkSize);if(m===0)return u+=i-w,i=w,!0;return!1}gs(this._handle,"zlib binding closed");let g;do g=this._handle.writeSync(r,n,u,i,this._buffer,this._offset,o),g=g||this._writeState;while(!this._hadError&&l(g[0],g[1]));if(this._hadError)throw f;if(h>=ls)throw as(this),RangeError("Cannot create final Buffer. It would be larger than 0x"+ls.toString(16)+" bytes");let d=Buffer.concat(c,h);return as(this),d};Hg.inherits(yr,Wr.Inflate);function jg(n,r){if(typeof r==="string")r=Buffer.from(r);if(!(r instanceof Buffer))throw TypeError("Not a string or buffer");let e=n._finishFlushFlag;if(e==null)e=Wr.Z_FINISH;return n._processChunk(r,e)}function ds(n,r){return jg(new yr(r),n)}ms.exports=we=ds;we.Inflate=yr;we.createInflate=Og;we.inflateSync=ds});var _t=pn((X0,ps)=>{var ws=ps.exports=function(n){this._buffer=n,this._reads=[]};ws.prototype.read=function(n,r){this._reads.push({length:Math.abs(n),allowLess:n<0,func:r})};ws.prototype.process=function(){while(this._reads.length>0&&this._buffer.length){let n=this._reads[0];if(this._buffer.length&&(this._buffer.length>=n.length||n.allowLess)){this._reads.shift();let r=this._buffer;this._buffer=r.slice(n.length),n.func.call(this,r.slice(0,n.length))}else break}if(this._reads.length>0)throw Error("There are some read requests waitng on finished stream");if(this._buffer.length>0)throw Error("unrecognised content at end of stream")}});var bs=pn((Lg)=>{var Rg=_t(),Gg=Zt();Lg.process=function(n,r){let e=[],t=new Rg(n);return new Gg(r,{read:t.read.bind(t),write:function(o){e.push(o)},complete:function(){}}).start(),t.process(),Buffer.concat(e)}});var vs=pn((V0,Es)=>{var ks=!0,Ms=Rn("zlib"),Kg=$s();if(!Ms.deflateSync)ks=!1;var Pg=_t(),Ug=bs(),Qg=Tt(),Wg=Vt(),Zg=zt();Es.exports=function(n,r){if(!ks)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let e;function t(y){e=y}let i;function o(y){i=y}function s(y){i.transColor=y}function u(y){i.palette=y}function c(){i.alpha=!0}let h;function f(y){h=y}let l=[];function g(y){l.push(y)}let d=new Pg(n);if(new Qg(r,{read:d.read.bind(d),error:t,metadata:o,gamma:f,palette:u,transColor:s,inflateData:g,simpleTransparency:c}).start(),d.process(),e)throw e;let m=Buffer.concat(l);l.length=0;let b;if(i.interlace)b=Ms.inflateSync(m);else{let p=((i.width*i.bpp*i.depth+7>>3)+1)*i.height;b=Kg(m,{chunkSize:p,maxLength:p})}if(m=null,!b||!b.length)throw Error("bad png - invalid inflate data response");let F=Ug.process(b,i);m=null;let S=Wg.dataToBitMap(F,i);F=null;let k=Zg(S,i,r.skipRescale);return i.data=k,i.gamma=h||0,i}});var Ss=pn((z0,Is)=>{var Fs=!0,ys=Rn("zlib");if(!ys.deflateSync)Fs=!1;var qg=Qr(),Ag=Ct();Is.exports=function(n,r){if(!Fs)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let t=new Ag(r||{}),i=[];if(i.push(Buffer.from(qg.PNG_SIGNATURE)),i.push(t.packIHDR(n.width,n.height)),n.gamma)i.push(t.packGAMA(n.gamma));let o=t.filterData(n.data,n.width,n.height),s=ys.deflateSync(o,t.getDeflateOptions());if(o=null,!s||!s.length)throw Error("bad png - invalid compressed data response");return i.push(t.packIDAT(s)),i.push(t.packIEND()),Buffer.concat(i)}});var Ns=pn((Vg)=>{var Xg=vs(),Tg=Ss();Vg.read=function(n,r){return Xg(n,r||{})};Vg.write=function(n,r){return Tg(n,r)}});var Os=pn((Dg)=>{var Cg=Rn("util"),Hs=Rn("stream"),_g=ns(),Bg=fs(),xg=Ns(),Jn=Dg.PNG=function(n){if(Hs.call(this),n=n||{},this.width=n.width|0,this.height=n.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,n.fill&&this.data)this.data.fill(0);this.gamma=0,this.readable=this.writable=!0,this._parser=new _g(n),this._parser.on("error",this.emit.bind(this,"error")),this._parser.on("close",this._handleClose.bind(this)),this._parser.on("metadata",this._metadata.bind(this)),this._parser.on("gamma",this._gamma.bind(this)),this._parser.on("parsed",function(r){this.data=r,this.emit("parsed",r)}.bind(this)),this._packer=new Bg(n),this._packer.on("data",this.emit.bind(this,"data")),this._packer.on("end",this.emit.bind(this,"end")),this._parser.on("close",this._handleClose.bind(this)),this._packer.on("error",this.emit.bind(this,"error"))};Cg.inherits(Jn,Hs);Jn.sync=xg;Jn.prototype.pack=function(){if(!this.data||!this.data.length)return this.emit("error","No data provided"),this;return process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this};Jn.prototype.parse=function(n,r){if(r){let e,t;e=function(i){this.removeListener("error",t),this.data=i,r(null,this)}.bind(this),t=function(i){this.removeListener("parsed",e),r(i,null)}.bind(this),this.once("parsed",e),this.once("error",t)}return this.end(n),this};Jn.prototype.write=function(n){return this._parser.write(n),!0};Jn.prototype.end=function(n){this._parser.end(n)};Jn.prototype._metadata=function(n){this.width=n.width,this.height=n.height,this.emit("metadata",n)};Jn.prototype._gamma=function(n){this.gamma=n};Jn.prototype._handleClose=function(){if(!this._parser.writable&&!this._packer.readable)this.emit("close")};Jn.bitblt=function(n,r,e,t,i,o,s,u){if(e|=0,t|=0,i|=0,o|=0,s|=0,u|=0,e>n.width||t>n.height||e+i>n.width||t+o>n.height)throw Error("bitblt reading outside image");if(s>r.width||u>r.height||s+i>r.width||u+o>r.height)throw Error("bitblt writing outside image");for(let c=0;c<o;c++)n.data.copy(r.data,(u+c)*r.width+s<<2,(t+c)*n.width+e<<2,(t+c)*n.width+e+i<<2)};Jn.prototype.bitblt=function(n,r,e,t,i,o,s){return Jn.bitblt(this,n,r,e,t,i,o,s),this};Jn.adjustGamma=function(n){if(n.gamma){for(let r=0;r<n.height;r++)for(let e=0;e<n.width;e++){let t=n.width*r+e<<2;for(let i=0;i<3;i++){let o=n.data[t+i]/255;o=Math.pow(o,0.45454545454545453/n.gamma),n.data[t+i]=Math.round(o*255)}}n.gamma=0}};Jn.prototype.adjustGamma=function(){Jn.adjustGamma(this)}});var Wi=pn((op,kh)=>{var Qi={to(n,r){if(!r)return`\x1B[${n+1}G`;return`\x1B[${r+1};${n+1}H`},move(n,r){let e="";if(n<0)e+=`\x1B[${-n}D`;else if(n>0)e+=`\x1B[${n}C`;if(r<0)e+=`\x1B[${-r}A`;else if(r>0)e+=`\x1B[${r}B`;return e},up:(n=1)=>`\x1B[${n}A`,down:(n=1)=>`\x1B[${n}B`,forward:(n=1)=>`\x1B[${n}C`,backward:(n=1)=>`\x1B[${n}D`,nextLine:(n=1)=>"\x1B[E".repeat(n),prevLine:(n=1)=>"\x1B[F".repeat(n),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},tm={up:(n=1)=>"\x1B[S".repeat(n),down:(n=1)=>"\x1B[T".repeat(n)},im={screen:"\x1B[2J",up:(n=1)=>"\x1B[1J".repeat(n),down:(n=1)=>"\x1B[J".repeat(n),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(n){let r="";for(let e=0;e<n;e++)r+=this.line+(e<n-1?Qi.up():"");if(n)r+=Qi.left;return r}};kh.exports={cursor:Qi,scroll:tm,erase:im,beep:"\x07"}});import{isMainThread as h0}from"node:worker_threads";import{parseArgs as s0}from"node:util";var rr={name:"@kecan0406/ttheme",version:"1.0.31",type:"module",bin:{ttheme:"bin/ttheme.js"},files:["bin","dist/manifest.json","dist/ghostty/ttheme.conf","shell","!shell/check.zsh","ghostty/shaders"],description:"Character terminal palettes for ghostty, kitty, alacritty, wezterm and iTerm2",license:"MIT",author:"kecan0406",repository:{type:"git",url:"git+https://github.com/kecan0406/ttheme.git"},homepage:"https://github.com/kecan0406/ttheme#readme",bugs:"https://github.com/kecan0406/ttheme/issues",keywords:["terminal","theme","ghostty","kitty","alacritty","wezterm","iterm2"],devDependencies:{"@biomejs/biome":"^2.3.0","@clack/core":"^1.4.3","@clack/prompts":"^1.7.0","@material/material-color-utilities":"^0.4.0","@types/bun":"^1.3.0","@types/pngjs":"6.0.5","jpeg-js":"^0.4.4",pngjs:"7.0.0",typescript:"^5.8.2"},engines:{bun:">=1.3",node:">=20.11"}};import{rmSync as nc}from"node:fs";import{basename as da,join as Oe}from"node:path";var jf=/^#[0-9a-f]{6}$/;function Mo(n){return jf.test(n)}function Gn(n){let r=Number.parseInt(n.slice(1),16);return[r>>16&255,r>>8&255,r&255]}function _n(n){let[r,e,t]=Gn(n).map((i)=>{let o=i/255;return o<=0.03928?o/12.92:((o+0.055)/1.055)**2.4});return 0.2126*r+0.7152*e+0.0722*t}function ur(n,r){let e=_n(n),t=_n(r);return(Math.max(e,t)+0.05)/(Math.min(e,t)+0.05)}function Ve(n,r){return Math.round(ur(n,r)*100)/100}var mr=7,Eo=3,Gt=0.15,vo=1.6,Fo=[1,2,3,4,5,6,9,10,11,12,13,14],yo=[7,15];function le(n,r){let e=n.ansi[r];if(e===void 0)throw Error(`${n.name}: missing ANSI ${r}`);return e}function Lt(n,r,e){let t=n.background;return r.flatMap((i)=>{let o=le(n,i);return ur(o,t)<e?[`ANSI ${i} ${o} on ${t} is ${Ve(o,t)}:1, needs ${e}:1`]:[]})}function Io(n,r){return Math.min(...r.map((e)=>ur(le(n,e),n.background)))}var ze=[{rule:"foreground",label:"foreground on background",unit:"ratio",min:mr,measure:({foreground:n,background:r})=>ur(n,r),check:({foreground:n,background:r})=>ur(n,r)<mr?[`foreground ${n} on ${r} is ${Ve(n,r)}:1, needs ${mr}:1`]:[]},{rule:"accents",label:"weakest accent on background",unit:"ratio",min:Eo,measure:(n)=>Io(n,Fo),check:(n)=>Lt(n,Fo,Eo)},{rule:"ansi0-dark",label:"ansi0 luminance",unit:"luminance",max:Gt,measure:(n)=>_n(le(n,0)),check:(n)=>{let r=le(n,0);return _n(r)>Gt?[`ANSI 0 ${r} has luminance ${_n(r).toFixed(3)}, needs <= ${Gt}`]:[]}},{rule:"light-ansi",label:"ansi7 and ansi15 on background",unit:"ratio",min:mr,measure:(n)=>Io(n,yo),check:(n)=>Lt(n,yo,mr)},{rule:"ansi8-visible",label:"ansi8 on background",unit:"ratio",min:vo,measure:(n)=>ur(le(n,8),n.background),check:(n)=>Lt(n,[8],vo)},{rule:"selection",label:"foreground on selection",unit:"ratio",min:mr,measure:({foreground:n,selectionBackground:r})=>r===void 0?Number.NaN:ur(n,r),check:({foreground:n,selectionBackground:r})=>r!==void 0&&ur(n,r)<mr?[`foreground ${n} on selection ${r} is ${Ve(n,r)}:1, needs ${mr}:1`]:[]}],m0=ze.map((n)=>n.rule),Ye=ze.map(({rule:n,label:r,unit:e,min:t,max:i})=>({rule:n,label:r,unit:e,...t===void 0?{}:{min:t},...i===void 0?{}:{max:i}}));function So(n){return ze.map((r)=>Math.round(r.measure(n)*1000)/1000)}function Jt(n){return ze.filter((r)=>!n.waive.includes(r.rule)).flatMap((r)=>r.check(n).map((e)=>({theme:n.name,rule:r.rule,detail:e})))}function No(n){return n.flatMap(Jt)}var Rf=["black","red","green","yellow","blue","magenta","cyan","white"];function Ho(n,r){return[n,...Rf.map((e,t)=>`${e} = '${r[t]}'`),""].join(`
3
- `)}var ae={id:"alacritty",limits:"no shaders, no runtime color API (OSC only)",emit(n){let r=[...Pr(n),"","[colors.primary]",`background = '${n.background}'`,`foreground = '${n.foreground}'`,"","[colors.cursor]",`cursor = '${n.cursor}'`,`text = '${n.background}'`,"","[colors.selection]",`background = '${n.selectionBackground}'`,`text = '${n.foreground}'`,"",Ho("[colors.normal]",n.ansi.slice(0,8)),Ho("[colors.bright]",n.ansi.slice(8,16))].join(`
4
- `),e=[`# ${n.name} — font settings.`,`# Pair with the palette: import = ["~/.config/alacritty/themes/${n.name}.toml"]`,"","[font]",`size = ${n.font.size}`,"","[font.normal]",`family = '${n.font.family}'`,""].join(`
5
- `);return[{path:`alacritty/themes/${n.name}.toml`,content:r},{path:`alacritty/config/${n.name}.toml`,content:e}]}};import{isDeepStrictEqual as Gf}from"node:util";var de={id:"ghostty",emit(n){let r=[...Pr(n),`background = ${n.background}`,`foreground = ${n.foreground}`,`cursor-color = ${n.cursor}`,`selection-background = ${n.selectionBackground}`,`selection-foreground = ${n.foreground}`,...n.ansi.map((e,t)=>`palette = ${t}=${e}`),"palette-generate = true","","macos-icon = custom-style",`macos-icon-ghost-color = ${n.ghostty.iconGhost}`,`macos-icon-screen-color = ${n.ghostty.iconScreen.join(",")}`,"macos-icon-frame = chrome",""].join(`
6
- `);return[{path:`ghostty/themes/${n.name}`,content:r}]},emitShared(n){let[r]=n;if(!r)return[];for(let t of n)if(!Gf(t.font,r.font)||t.ghostty.shader!==r.ghostty.shader)throw Error(`${t.name}: per-theme font/shader overrides cannot be expressed in the shared ghostty/ttheme.conf`);return[{path:"ghostty/ttheme.conf",content:["# ttheme — shared font and shader, identical for every palette.","# Pick colors with: theme = <palette>",`font-family = ${r.font.family}`,`font-size = ${r.font.size}`,...r.font.codepointMap.map((t)=>`font-codepoint-map = ${t.range}=${t.family}`),...r.ghostty.shader?["",`custom-shader = ~/.config/ghostty/shaders/${r.ghostty.shader}`,"custom-shader-animation = true"]:[],""].join(`
7
- `)}]}};function $r(n){let[r,e,t]=Gn(n);return{"Alpha Component":1,"Blue Component":t/255,"Color Space":"P3","Green Component":e/255,"Red Component":r/255}}function Oo(n){return{...Object.fromEntries(n.ansi.map((r,e)=>[`Ansi ${e} Color`,$r(r)])),"Background Color":$r(n.background),"Bold Color":$r(n.foreground),"Cursor Color":$r(n.cursor),"Cursor Text Color":$r(n.background),"Foreground Color":$r(n.foreground),"Selected Text Color":$r(n.foreground),"Selection Color":$r(n.selectionBackground)}}function Lf(n){return n?{"Background Image Location":n.image,"Background Image Mode":n.cover?2:3,Blend:n.opacity}:{"Background Image Location":""}}function jo(n,r,e,t){let i=(s,u)=>({Name:`ttheme · ${u}`,Guid:`ttheme-${u}`,...t?{"Dynamic Profile Parent GUID":t}:{},"Use Separate Colors for Light and Dark Mode":!1,"Harmonize 256 Colors":!0,...Lf(r.get(s.name)),...Oo(s)}),o=[...e?[i(e,"default")]:[],...n.map((s)=>i(s,s.name))];return`${JSON.stringify({Profiles:o},null,2)}
8
- `}function Jf(n,r){return[` <key>${n}</key>`,"\t<dict>",...Object.entries(r).flatMap(([e,t])=>[` <key>${e}</key>`,typeof t==="string"?` <string>${t}</string>`:` <real>${t}</real>`]),"\t</dict>"].join(`
9
- `)}var me={id:"iterm2",limits:"colors only — font lives in the profile; colors are Display P3, the space iTerm2 reads OSC colors in",emit(n){let r=['<?xml version="1.0" encoding="UTF-8"?>','<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">','<plist version="1.0">',"<dict>",...Object.entries(Oo(n)).map(([e,t])=>Jf(e,t)),"</dict>","</plist>",""].join(`
10
- `);return[{path:`iterm2/${n.name}.itermcolors`,content:r}]}};var $e={id:"kitty",limits:"no GLSL shaders, no per-codepoint font mapping",emit(n){let r=[...Pr(n),`background ${n.background}`,`foreground ${n.foreground}`,`cursor ${n.cursor}`,`cursor_text_color ${n.background}`,`selection_background ${n.selectionBackground}`,`selection_foreground ${n.foreground}`,...n.ansi.map((t,i)=>`color${i} ${t}`),""].join(`
11
- `),e=[`# ${n.name} — font settings.`,`# Pair with the palette: include themes/${n.name}.conf`,`font_family ${n.font.family}`,`font_size ${n.font.size}`,""].join(`
12
- `);return[{path:`kitty/themes/${n.name}.conf`,content:r},{path:`kitty/config/${n.name}.conf`,content:e}]}};import{createHash as el}from"node:crypto";import{mkdirSync as qs,readdirSync as Ir,readFileSync as As,renameSync as Xs,rmSync as qr,statSync as tl,utimesSync as il,writeFileSync as xe}from"node:fs";import{isAbsolute as ol,join as Fn}from"node:path";var Gs=Te(Uo(),1),_e=Te(Os(),1),js=[137,80,78,71,13,10,26,10],Ls=13;function Js(n){return n.length>=js.length&&js.every((r,e)=>n[e]===r)}function nl(n){let r=_e.PNG.sync.read(Buffer.from(n));return{width:r.width,height:r.height,data:new Uint8Array(r.data)}}function Ks(n,r){if(Js(n)){let e=Bt(n);if(e&&e.width*e.height>r)throw Error(`${e.width}×${e.height} is over ${r/1e6} megapixels`);return nl(n)}if(n[0]===255&&n[1]===216){let e=Gs.decode(n,{useTArray:!0,formatAsRGBA:!0,maxResolutionInMP:r/1e6,maxMemoryUsageInMB:1024});return{width:e.width,height:e.height,data:e.data}}throw Error("not a PNG or JPEG image")}function Zr(n){let r=new _e.PNG({width:n.width,height:n.height});return r.data=Buffer.from(n.data),_e.PNG.sync.write(r)}function Rs(n,r){for(let e=0;e+r.length<=n.length;e++){let t=!0;for(let i=0;i<r.length&&t;i++)t=n[e+i]===r.charCodeAt(i);if(t)return e}return-1}function Bt(n){if(n.length<33||!Js(n))return null;let r=new DataView(n.buffer,n.byteOffset,n.byteLength),e=r.getUint32(16),t=r.getUint32(20);if(n[25]===4||n[25]===6)return{width:e,height:t,alpha:!0};let i=Rs(n,"IDAT");return{width:e,height:t,alpha:Rs(i===-1?n:n.subarray(0,i),"tRNS")!==-1}}function Ps(n,r=Ls){let{width:e,height:t}=n,i=-1,o=-1;for(let s=0;s<n.height;s++)for(let u=0;u<n.width;u++)if((n.data[(s*n.width+u)*4+3]??0)>=r)e=Math.min(e,u),i=Math.max(i,u),t=Math.min(t,s),o=Math.max(o,s);return i<0?null:{x:e,y:t,w:i-e+1,h:o-t+1}}function pe(n,r={x:0,y:0,w:n.width,h:n.height}){let e=0;for(let t=r.y;t<r.y+r.h;t++)for(let i=r.x;i<r.x+r.w;i++)if((n.data[(t*n.width+i)*4+3]??0)<Ls)e++;return Math.round(e*100/(r.w*r.h))}function rl(n,r){if(r<=1)return n;let e=Math.max(1,Math.floor(n.width/r)),t=Math.max(1,Math.floor(n.height/r)),i=new Uint8Array(e*t*4),o=n.data;for(let s=0;s<t;s++)for(let u=0;u<e;u++){let c=0,h=0,f=0,l=0;for(let d=0;d<r;d++)for(let w=0;w<r;w++){let m=((s*r+d)*n.width+u*r+w)*4,b=o[m+3]??0;c+=(o[m]??0)*b,h+=(o[m+1]??0)*b,f+=(o[m+2]??0)*b,l+=b}let g=(s*e+u)*4;if(l>0)i[g]=Math.round(c/l),i[g+1]=Math.round(h/l),i[g+2]=Math.round(f/l);i[g+3]=Math.round(l/(r*r))}return{width:e,height:t,data:i}}function Us(n,r,e){let t=Math.min(r/n.width,e/n.height),i=Math.max(1,Math.round(n.width*t)),o=Math.max(1,Math.round(n.height*t)),s=Be(n,{x:0,y:0,w:n.width,h:n.height},i,o),u=new Uint8Array(r*e*4),c=Math.floor((r-i)/2),h=Math.floor((e-o)/2);for(let f=0;f<o;f++)u.set(s.data.subarray(f*i*4,(f+1)*i*4),((h+f)*r+c)*4);return{width:r,height:e,data:u}}function Be(n,r,e,t){let i=Math.max(1,Math.floor(Math.min(r.w/e,r.h/t))),o=rl(n,i),s=o.data,u=new Uint8Array(e*t*4);for(let c=0;c<t;c++){let h=Math.min(o.height-1,Math.max(0,r.y/i+(c+0.5)*r.h/i/t-0.5)),f=Math.floor(h),l=Math.min(o.height-1,f+1),g=h-f;for(let d=0;d<e;d++){let w=Math.min(o.width-1,Math.max(0,r.x/i+(d+0.5)*r.w/i/e-0.5)),m=Math.floor(w),b=Math.min(o.width-1,m+1),F=w-m,S=(f*o.width+m)*4,k=(f*o.width+b)*4,y=(l*o.width+m)*4,p=(l*o.width+b)*4,R=(s[S+3]??0)*(1-F)*(1-g),M=(s[k+3]??0)*F*(1-g),j=(s[y+3]??0)*(1-F)*g,H=(s[p+3]??0)*F*g,J=R+M+j+H,G=(c*e+d)*4;if(J>0)for(let z=0;z<3;z++){let U=(s[S+z]??0)*R+(s[k+z]??0)*M+(s[y+z]??0)*j+(s[p+z]??0)*H;u[G+z]=Math.round(U/J)}u[G+3]=Math.round(J)}}return{width:e,height:t,data:u}}var Qs={width:2560,height:1550},sl=2560,ul=0.1,cr={tall:1.15,reach:0.4,widest:0.95,headroom:0.04,margin:0.03,stands:12},cl=_n(xt("#19161e","#9b86c8",0.2)),hl="shelf";function xt(n,r,e){let t=Gn(n),i=Gn(r);return`#${t.map((o,s)=>Math.round(o+((i[s]??0)-o)*e).toString(16).padStart(2,"0")).join("")}`}function fl(n,r){if(r==="background"||r==="foreground"||r==="cursor")return n[r];if(r==="selection"&&n.selection)return n.selection;let e=/^ansi(\d|1[0-5])$/.exec(r),t=e?n.ansi[Number(e[1])]:void 0;if(!t)throw Error(`${n.name} has no slot ${r}`);return t}function Ws(n){if(n(1))return 1;let r=0,e=1;for(let t=0;t<40;t++){let i=(r+e)/2;if(n(i))r=i;else e=i}return r}function Zs(n,r){let e=fl(n,r),i=Ws((h)=>Jt({name:n.name,background:xt(n.background,e,h),foreground:n.foreground,ansi:n.ansi,waive:n.waived??[]}).length===0),o=Ws((h)=>_n(xt(n.background,e,h))<=cl),s=Math.floor(Math.min(i,o)*1000)/1000,u=Gn(n.background),c=Math.hypot(...Gn(e).map((h,f)=>(h-(u[f]??0))*s));return{slot:r,color:e,cap:i,matched:o,opacity:s,reach:c}}function De(n,r){let e=Zs(n,"cursor");if(e.opacity>=ul)return e;return r.filter((t)=>t!=="cursor"&&t!=="background").map((t)=>Zs(n,t)).reduce((t,i)=>i.reach>t.reach?i:t,e)}function Dt(n,r,e){let t=Gn(r),i=Gn(e),o=n.data;for(let s=0;s<o.length;s+=4){let u=(0.299*(o[s]??0)+0.587*(o[s+1]??0)+0.114*(o[s+2]??0))/255;for(let c=0;c<3;c++)o[s+c]=Math.round((t[c]??0)+((i[c]??0)-(t[c]??0))*u)}return n}function gl(n,r,e){let t=Gn(r),i=n.data,o=new Uint8Array(i.length);for(let s=0;s<i.length;s+=4){let u=(i[s+3]??0)/255*e;for(let c=0;c<3;c++)o[s+c]=Math.round((t[c]??0)*(1-u)+(i[s+c]??0)*u);o[s+3]=255}return{width:n.width,height:n.height,data:o}}function Ts(n){return Ps(n)??{x:0,y:0,w:n.width,h:n.height}}function ll(n,r){if(n<=0||r<=0)return Qs;let e=Math.min(1,Qs.width/Math.max(n,r));return{width:Math.round(n*e),height:Math.round(r*e)}}function al(n,r){let e=Math.min(1,sl/Math.max(r.w,r.h));return Be(n,r,Math.round(r.w*e),Math.round(r.h*e))}function Vs(n,r,e,t){if(t<cr.stands){let c=n.w*e>n.h*r?{x:n.x+(n.w-n.h*r/e)/2,y:n.y,w:n.h*r/e,h:n.h}:{x:n.x,y:n.y,w:n.w,h:n.w*e/r};return{crop:c,at:{x:0,y:0,w:r,h:e},focus:(c.y-n.y+c.h/2)/n.h}}let i=Math.max(cr.tall*e,cr.reach*r*n.h/n.w),o=i*n.w/n.h;if(o>cr.widest*r)o=cr.widest*r,i=o*n.h/n.w;let s=cr.headroom*e,u=Math.min(1,(e-s)/i);return{crop:{x:n.x,y:n.y,w:n.w,h:n.h*u},at:{x:r*(1-cr.margin)-o,y:s,w:o,h:i*u},focus:Math.min(1,(e/2-s)/i)}}function zs(n,r,e,t){let i=Math.max(1,Math.round(r.at.w)),o=Math.max(1,Math.round(r.at.h)),s=Be(n,r.crop,i,o),u=new Uint8Array(e*t*4),c=Math.round(r.at.x),h=Math.round(r.at.y);for(let f=0;f<o;f++){let l=h+f,g=Math.max(0,-c),d=Math.min(i,e-c);if(l<0||l>=t||d<=g)continue;u.set(s.data.subarray((f*i+g)*4,(f*i+d)*4),(l*e+c+g)*4)}return{width:e,height:t,data:u}}function Ys(n,r,e,t,i){let o=Ts(n),s=zs(n,Vs(o,t,i,pe(n,o)),t,i);return gl(Dt(s,r.background,e.color),r.background,e.opacity)}function Sr(n){return Fn(n,"ttheme","backgrounds")}function dl(n,r,e,t,i){return[...t?[`# from ${t}`]:[],...i?[`# image ${i}`]:[],`background-image = ${r}`,"background-image-fit = cover","background-image-position = top-right",`background-image-opacity = ${e}`,`config-file = ?${n}.tune.conf`,`config-file = ?${n}.off.conf`,""].join(`
13
- `)}function Cs(n,r,e){let t=new Map;for(let s of[`${r}.conf`,`${r}.tune.conf`,`${r}.off.conf`]){let u;try{u=As(Fn(n,s),"utf8")}catch{if(s===`${r}.conf`)return;continue}for(let c of u.split(`
14
- `)){let h=/^(background-image(?:-fit|-opacity)?)\s*=\s*(.*?)\s*$/.exec(c);if(h)t.set(h[1],h[2])}}let i=t.get("background-image")??"";if(i==="")return;let o=Number(t.get("background-image-opacity")??1);return{image:i.startsWith("~/")?Fn(e,i.slice(2)):ol(i)?i:Fn(n,i),opacity:Number.isFinite(o)?o:1,cover:t.get("background-image-fit")==="cover"}}function ml(n,r){for(let e of Ir(n))if(ni(e,r))qr(Fn(n,e))}function $l(n){return`${n.site}_${n.id}`}function nt(n,r){return Fn(n,hl,r)}function ni(n,r){let e=n.slice(r.length);return n.startsWith(r)&&(e===".conf"||e===".tune.conf"||e===".off.conf"||/^(\.[0-9a-f]{8})?(@[a-z0-9-]+)?\.png$/.test(e))}function be(n,r){try{return/^# image (\S+)$/m.exec(As(Fn(n,`${r}.conf`),"utf8"))?.[1]}catch{return}}function wl(n,r){try{return Ir(nt(n,r))}catch{return[]}}function _s(n,r){let e=be(n,r);return[...e?[e]:[],...wl(n,r)].sort()}function Bs(n,r){let e=be(n,r);if(!e)return;let t=Fn(nt(n,r),e);qr(t,{recursive:!0,force:!0}),qs(t,{recursive:!0});for(let i of Ir(n))if(ni(i,r))Xs(Fn(n,i),Fn(t,i.slice(r.length)))}function xs(n,r,e){let t=Fn(nt(n,r),e);for(let i of Ir(t))Xs(Fn(t,i),Fn(n,`${r}${i}`));qr(t,{recursive:!0})}function Ds(n,r,e){try{return Ir(Fn(n,"originals")).find((t)=>t.startsWith(`${r}-${e}.`))}catch{return}}function nu(n,r,e){let t=Ds(n,r,e);if(t){let i=new Date;il(Fn(n,"originals",t),i,i)}}function ru(n,r,e){let t=Sr(n),i=_s(t,r),o=be(t,r);if(!o||i.length<2)throw Error(`${r} has no other image`);let s=(i.indexOf(o)+e+i.length)%i.length,u=i[s];return Bs(t,r),xs(t,r,u),nu(t,r,u),{key:u,at:s+1,of:i.length}}function eu(n,r){let e=Sr(n),t=Ir(e).filter((h)=>ni(h,r));if(t.length===0)throw Error(`${r} has no image`);let i=_s(e,r),o=be(e,r),s=o&&Ds(e,r,o);if(s)qr(Fn(e,"originals",s));for(let h of t)qr(Fn(e,h));let u=i.filter((h)=>h!==o),c=u[(o?i.indexOf(o):0)%u.length];if(c)xs(e,r,c),nu(e,r,c);return{key:o,left:u.length}}function pl(n,r,e){if(be(n,r)!==e)Bs(n,r);if(e)qr(Fn(nt(n,r),e),{recursive:!0,force:!0});ml(n,r)}function tu(n,r,e,t,i,o){let s=Sr(n),u=r.name,c=$l(i);qs(Fn(s,"originals"),{recursive:!0}),pl(s,u,c);let h=Ts(t),{width:f,height:l}=ll(o.width,o.height),g=Vs(h,f,l,pe(t,h)),d=Zr(Dt(al(t,h),r.background,e.color)),w=Zr(Dt(zs(t,g,f,l),r.background,e.color)),m=Fn(s,`${u}.${el("sha1").update(d).update(w).digest("hex").slice(0,8)}`),b=`${m}.png`,F=`${m}@fill-${Math.round(g.focus*100)}.png`,S=Fn(s,`${u}.conf`),k=Fn(s,"originals",`${u}-${i.site}_${i.id}.${i.ext}`);return xe(b,d),xe(F,w),xe(S,dl(u,F,e.opacity,i.from,c)),xe(k,i.bytes),[b,F,S,k]}function iu(n){let r=Fn(Sr(n),"originals"),e=new Map,t;try{t=Ir(r)}catch{return new Map}for(let i of t){let o=/^(.+)-([a-z.]+)_(\d+)\.[a-z]+$/.exec(i),[,s,u,c]=o??[];if(!s||!u||!c)continue;let h=tl(Fn(r,i)).mtimeMs,f=e.get(s);if(!f||h>f.at)e.set(s,{site:u,id:Number(c),at:h})}return new Map([...e].map(([i,{site:o,id:s}])=>[i,{site:o,id:s}]))}function ri(n){let{slot:r,color:e,opacity:t}=De({name:n.name,background:n.background,foreground:n.foreground,cursor:n.cursor,selection:n.selectionBackground,ansi:n.ansi,waived:n.waive},n.signatureSlots);return{name:n.name,group:n.group,...n.native?{native:n.native}:{},...n.lead?{lead:!0}:{},order:n.order,ansiSource:n.ansiSource,...n.booru?{booru:n.booru}:{},...n.booruSites?{booruSites:n.booruSites}:{},...n.role==="default"?{default:!0}:{},background:n.background,foreground:n.foreground,cursor:n.cursor,selection:n.selectionBackground,signature:n.signature,signatureSlots:n.signatureSlots,ansi:n.ansi,gate:So(n),...n.waive.length>0?{waived:n.waive}:{},backdrop:{slot:r,color:e,opacity:t}}}function Ar(n){return n.filter((r)=>r.default!==!0)}function bl(n){let[r]=n;if(!r)throw Error("manifest needs at least one theme");return{version:rr.version,gate:Ye,placement:cr,font:r.font,...r.ghostty.shader?{shader:r.ghostty.shader}:{},palettes:n.map(ri)}}var ei={id:"meta",emitShared(n){return[{path:"manifest.json",content:`${JSON.stringify(bl(n),null,2)}
15
- `}]}};import{readdirSync as xl,readFileSync as ci}from"node:fs";import{basename as Dl,join as hi}from"node:path";import{readdirSync as kl,rmSync as Ml,statSync as El}from"node:fs";import{setDefaultAutoSelectFamilyAttemptTimeout as vl}from"node:net";import{homedir as Fl}from"node:os";import{join as Me}from"node:path";import{setTimeout as yl}from"node:timers/promises";var Nr=100,ii=25000000,Il=536870912,Ee=["safe","questionable","explicit"],Hr=["nudity","underwear"],Sl={nudity:new Set(["nude","naked","topless","bottomless","nipples","naked_towel","undressing"]),underwear:new Set(["underwear","panties","pantsu","bra","lingerie","pantyshot"])},ke={safe:"s",questionable:"q",explicit:"e"},Nl=8191,Hl=20000,Ol=5000,ou=3000,su=8,jl=3000,fu=60000,uu=3,Rl=`ttheme/${rr.version} (+${rr.homepage})`,Gl=["orig","tile","thumb","cut"],gu=new Map,Ll=Xl(process.env.TTHEME_FIND_HOSTS),Jl=Al(process.env.TTHEME_FIND_CUTOUTS);vl(jl);function cu(n){try{return kl(n)}catch{return[]}}function rt(n){return n.startsWith("//")?`https:${n}`:n}function ve(n){return(/\.([a-z0-9]+)(?:\?.*)?$/i.exec(n)?.[1]??"").toLowerCase()}function Fe(n){let r=n.trim();if(!r)return[];let e=JSON.parse(r);if(Array.isArray(e))return e;let t=e.posts;return Array.isArray(t)?t:[]}function Kl(n){let r=n.trim(),t=(r?JSON.parse(r):{}).tags??{};return new Map(Object.entries(t).map(([i,o])=>[i,String(o)]))}function ti(n,r,e){let t=rt(String(n??""));return{file:t,width:Number(r)||0,height:Number(e)||0,ext:ve(t)}}function lu(n,r){let e=rt(String(r.preview??""));if(!r.file||!e||!Number(n.id))return[];let t=Number(n.width??n.image_width)||0,i=Number(n.height??n.image_height)||0;return[{id:Number(n.id),width:t,height:i,file:r.file,preview:e,ext:r.ext,owner:String(r.owner??""),artist:r.artist,score:Number(n.score)||0,rating:String(n.rating??""),md5:String(r.md5??""),source:String(n.source??""),tags:r.tags.split(/\s+/).filter(Boolean),solo:r.solo,family:Number(n.parent_id)||(n.has_children===!0?Number(n.id):0),smaller:r.versions.filter((o)=>o.file&&o.width>0&&o.height>0&&o.width*o.height<t*i)}]}function Pl(n){let r=Kl(n);return Fe(n).flatMap((e)=>{let t=rt(String(e.file_url??"")),i=String(e.tags??"");return lu(e,{preview:e.preview_url,file:t,ext:String(e.file_ext||ve(t)).toLowerCase(),owner:e.author,artist:i.split(/\s+/).find((o)=>r.get(o)==="artist")??"",md5:e.md5,tags:i,solo:void 0,versions:[ti(e.jpeg_url,e.jpeg_width,e.jpeg_height),ti(e.sample_url,e.sample_width,e.sample_height)]})})}function Ul(n){return Fe(n).flatMap((r)=>{let e=rt(String(r.file_url??"")),t=String(r.tag_string??""),i=r.media_asset??{};return lu(r,{preview:i.variants?.find((o)=>o.type==="360x360")?.url??r.preview_file_url,file:e,ext:String(r.file_ext||ve(e)).toLowerCase(),owner:"",artist:String(r.tag_string_artist??"").split(/\s+/)[0]??"",md5:r.md5,tags:t,solo:t.split(/\s+/).includes("solo"),versions:(i.variants??[]).map((o)=>ti(o.url,o.width,o.height)).filter((o)=>o.ext==="jpg"||o.ext==="png").sort((o,s)=>s.width*s.height-o.width*o.height)})})}function Ql(n){return Fe(n).flatMap((r)=>{let e=String(r.value??"");return e?[{value:e,count:Number(r.post_count)||0}]:[]})}function Wl(n){return Fe(n).flatMap((r)=>{let e=String(r.name??"");return e?[{value:e,count:Number(r.count)||0}]:[]})}function Zl(n){return Number(/count="(\d+)"/.exec(n)?.[1]??0)}function ql(n){let r=n.trim()?JSON.parse(n):{};return Number(r.counts?.posts)||0}function Al(n){let r=new Map;for(let e of(n??"").split(/\s+/).filter(Boolean)){let t=e.indexOf("=");if(t>0)r.set(e.slice(0,t),e.slice(t+1).split(",").filter(Boolean))}return r}function Xl(n){let r=new Map;for(let e of(n??"").split(/[\s,]+/).filter(Boolean)){let t=e.indexOf("="),i=e.slice(0,t);try{let o=new URL(e.slice(t+1));if(i&&o.protocol==="https:")r.set(i,o.origin)}catch{}}return r}function au(n,r,e,t){let i=(n??"").split(/\s+/);if(t!==void 0&&i.includes(t))return[];let o=r.filter((s)=>i.includes(s));return o.length>0?o:[...e]}function et(n){return au(n,Ee,["safe"])}function tt(n){return au(n,Hr,Hr,"none")}function du(n,r,e){return{safe:new Set(n),questionable:new Set(r),explicit:new Set(e)}}function mu(n){let r=Ll.get(n.key),e=Jl.get(n.key);return{...n,origin:r??n.origin,moved:r!==void 0&&r!==n.origin,cutouts:e??n.cutouts,vouched:n.vouched&&e===void 0}}function $u(n){return n.length<2?n.join(""):n.map((r)=>`~${r}`).join(" ")}function hu(n){let r=mu(n),e=(t)=>new URLSearchParams({api_version:"2",include_tags:"1",...t});return{...r,cutouts:$u(r.cutouts),ratings:du([ke.safe],[ke.questionable],[ke.explicit]),rate:(t)=>{let[i]=t;if(t.length===1&&i)return`rating:${ke[i]}`;let o=Ee.filter((u)=>!t.includes(u)),[s]=o;return o.length===1&&s?`-rating:${ke[s]}`:""},best:"order:score",tagBudget:Number.POSITIVE_INFINITY,postsUrl:(t,i)=>`${r.origin}/post.json?${e({limit:String(Nr),page:String(i+1),tags:t})}`,countUrl:(t)=>`${r.origin}/post.xml?${new URLSearchParams({limit:"1",tags:t})}`,postUrl:(t)=>`${r.origin}/post.json?${e({tags:`id:${t}`})}`,pageUrl:(t)=>`${r.origin}/post/show/${t}`,parse:Pl,count:Zl}}function Tl(n){let r=mu(n),e=du(["g"],["s","q"],["e"]);return{...r,cutouts:$u(r.cutouts),ratings:e,rate:(t)=>t.length===Ee.length?"":`rating:${t.flatMap((i)=>[...e[i]]).join(",")}`,best:"order:score",tagBudget:2,postsUrl:(t,i)=>`${r.origin}/posts.json?${new URLSearchParams({limit:String(Nr),page:String(i+1),tags:t})}`,countUrl:(t)=>`${r.origin}/counts/posts.json?${new URLSearchParams({tags:t})}`,postUrl:(t)=>`${r.origin}/posts.json?${new URLSearchParams({limit:"1",tags:`id:${t}`})}`,pageUrl:(t)=>`${r.origin}/posts/${t}`,parse:Ul,count:ql}}function Vl(n){return Mn.find((r)=>r.key===n||r.name===n||new URL(r.origin).host===n)}function oi(n){return n.split(/\s+/).filter((r)=>r&&!r.startsWith("rating:")).length}function wu(n,r){let e=n.trim();if(/^\d+$/.test(e))return{site:r,id:Number(e)};let t=/^([\w.]+):(\d+)$/.exec(e);if(t){let u=Mn.find((c)=>c.key===t[1]||c.name===t[1]);return u&&{site:u,id:Number(t[2])}}let i;try{i=new URL(e)}catch{return}let o=Vl(i.host),s=Number(i.searchParams.get("id")??i.pathname.split("/").filter(Boolean).at(-1));return o&&s>0?{site:o,id:s}:void 0}var Mn=[Tl({key:"danbooru",name:"danbooru",origin:"https://danbooru.donmai.us",cutouts:["transparent_background"],vouched:!1,tunneled:!0,ansi:2}),hu({key:"konachan",name:"konachan",origin:"https://konachan.net",cutouts:["transparent","vector"],vouched:!1,tunneled:!1,ansi:6}),hu({key:"yande",name:"yande.re",origin:"https://yande.re",cutouts:["transparent_png"],vouched:!0,tunneled:!1,ansi:5})],Or=134217728;function tr(n,r){return Mn.indexOf(n)*Or+r}function si(n){let r;try{r=new URL(n).hostname}catch{return""}return r.split(".").slice(-2).join(".")}function pu(){return Mn.filter((n)=>!n.tunneled).map((n)=>si(n.origin)).flatMap((n)=>[n,`.${n}`]).join(",")}function bu(n,r=Hr){return n.tags.filter((e)=>r.some((t)=>Sl[t].has(e)))}function ku(n,r,e=["safe"]){return e.some((t)=>n.ratings[t].has(r.rating))}function ye(n){return[n,...n.smaller].find((r)=>r.width*r.height<=ii)}function Mu(n){let r=new Map;for(let[e,t]of[...n].sort(([i],[o])=>i<o?-1:1)){if(t==="")continue;r.set(t,[...r.get(t)??[],e])}return r}function Eu(){return Me(process.env.XDG_CACHE_HOME??Me(Fl(),".cache"),"ttheme")}function Mr(n){return Me(Eu(),n.key)}function vu(n=Il,r=Eu()){let e=[],t=0;for(let i of cu(r))for(let o of Gl){let s=Me(r,i,o);for(let u of cu(s)){let c=Me(s,u);try{let{size:h,mtimeMs:f}=El(c);e.push({path:c,size:h,at:f}),t+=h}catch{}}}e.sort((i,o)=>i.at-o.at);for(let i of e){if(t<=n)return;try{Ml(i.path,{force:!0}),t-=i.size}catch{}}}function zl(n,r){if(n!==null&&/^\s*\d+\s*$/.test(n))return Number(n)*1000;let e=n===null?Number.NaN:Date.parse(n);return Number.isNaN(e)?fu:Math.max(0,e-r)}function br(n){return gu.get(n.key)??0}function Yl(n){for(let r=n;r instanceof Error;r=r.cause)if(r.code==="ECONNRESET")return!0;return!1}function Cl(n){return(n.headers.get("server")??"").startsWith("cloudflare")&&n.headers.get("cf-mitigated")==="challenge"}async function kr(n,r,e,t={},i=Hl){for(let o=1;;o++){let s=br(n)-Date.now();if(s>0)await yl(s,void 0,{signal:e});let u;try{u=await fetch(r,{headers:{"User-Agent":Rl,Referer:`${n.origin}/`,...t},signal:i?AbortSignal.any([e,AbortSignal.timeout(i)]):e})}catch(c){if(o<uu&&!e.aborted&&Yl(c))continue;throw c}if(u.status===429&&o<uu){await u.body?.cancel();let c=zl(u.headers.get("retry-after"),Date.now());if(c>fu)throw Error(`${n.name} asks to wait ${Math.ceil(c/1000)}s`);gu.set(n.key,Math.max(br(n),Date.now()+c));continue}if(!u.ok)throw await u.body?.cancel(),Error(Cl(u)?`${n.name} is behind a Cloudflare challenge`:`${n.name} answered ${u.status}`);return u}}async function Fu(n,r,e,t){return n.parse(await(await kr(n,n.postsUrl(r,e),t)).text())}async function yu(n,r,e){return n.count(await(await kr(n,n.countUrl(r),e)).text())}async function ui(n,r,e){let[t]=n.parse(await(await kr(n,n.postUrl(r),e)).text());return t}function _l(n){let r=Mn.find((t)=>t.key==="danbooru"),e=new URLSearchParams({limit:String(2*Nr),only:"md5,tag_string",tags:`md5:${n.join(",")}`});return`${r.origin}/posts.json?${e}`}function Bl(n){return new Map(Fe(n).flatMap((r)=>{let e=String(r.md5??"");return e?[[e,String(r.tag_string??"").split(/\s+/).filter(Boolean)]]:[]}))}function Iu(n,r){for(let e of n){let t=r.get(e.md5);if(t)e.tags=[...new Set([...e.tags,...t])],e.solo=t.includes("solo")}}async function Su(n,r){let e=Mn.find((i)=>i.key==="danbooru"),t=new Map;if(br(e)>Date.now())return t;for(let i=0;i<n.length;i+=Nr){let o=await(await kr(e,_l(n.slice(i,i+Nr)),r,{},Ol)).text();for(let[s,u]of Bl(o))t.set(s,u)}return t}async function Nu(n,r){let e=Mn.find((o)=>o.key==="danbooru");if(br(e)<=Date.now())try{let o=new URLSearchParams({"search[query]":n,"search[type]":"tag_query",limit:String(su)}),s=`${e.origin}/autocomplete.json?${o}`;return Ql(await(await kr(e,s,r,{},ou)).text())}catch(o){if(r.aborted)throw o}let t=Mn.find((o)=>o.key==="yande"),i=new URLSearchParams({name:n,order:"count",limit:String(su)});return Wl(await(await kr(t,`${t.origin}/tag.json?${i}`,r,{},ou)).text())}async function Hu(n,r,e){let t=await kr(n,r,e,{Range:`bytes=0-${Nl}`});return Bt(new Uint8Array(await t.arrayBuffer()))}async function Ou(n,r,e,t){let i=await kr(n,r,e,{},0),o=Number(i.headers.get("content-length"))||0,s=i.body?.getReader();if(!s)return new Uint8Array(await i.arrayBuffer());let u=[],c=0;for(;;){let{done:l,value:g}=await s.read();if(l)break;u.push(g),c+=g.length,t?.(c,o)}let h=new Uint8Array(c),f=0;for(let l of u)h.set(l,f),f+=l.length;return h}var na="_defaults.toml",hr="_groups.toml",ju=3,Ru=["background","foreground","cursor","selection"],ra=new Set(["next","help","preview","pin","unpin","config"]);function yn(n,r){throw Error(`${n}: ${r}`)}function jr(n,r,e){if(typeof e!=="string"||!Mo(e))yn(n,`${r} must be "#rrggbb" (lowercase), got ${JSON.stringify(e)}`);return e}function Vn(n,r,e){if(typeof e!=="string"||e.length===0)yn(n,`${r} must be a non-empty string`);return e}function fr(n){return n&&typeof n==="object"?n:{}}function ea(n,r,e){let t={...fr(e),...fr(r)},i=t.codepoint_map??[];if(!Array.isArray(i))yn(n,"font.codepoint_map must be an array");return{family:Vn(n,"font.family",t.family),size:Number(t.size),codepointMap:i.map((o)=>{let s=fr(o);return{range:Vn(n,"font.codepoint_map[].range",s.range),family:Vn(n,"font.codepoint_map[].family",s.family)}})}}function ta(n,r,e){if(r===void 0)return[e.cursor,e.selectionBackground,e.background];let t=Array.isArray(r)?r:[r];if(t.length===0)yn(n,"ghostty.icon_screen must not be empty");return t.map((i,o)=>jr(n,`ghostty.icon_screen[${o}]`,i))}function ia(n,r,e,t){let i={...fr(e),...fr(r)};return{shader:i.shader===void 0?void 0:Vn(n,"ghostty.shader",i.shader),iconGhost:i.icon_ghost===void 0?t.cursor:jr(n,"ghostty.icon_ghost",i.icon_ghost),iconScreen:ta(n,i.icon_screen,t)}}function oa(n){return new Map([...Ru.map((r)=>[r,n[r]]),...n.ansi.map((r,e)=>[`ansi${e}`,r])])}function sa(n,r,e){if(!Array.isArray(r)||r.length!==ju)yn(n,`meta.signature must name exactly ${ju} palette slots`);let t=oa(e),i=[],o=[];for(let[s,u]of r.entries()){let c=`meta.signature[${s}]`,h=Vn(n,c,u),f=t.get(h);if(f===void 0)yn(n,`${c} ${JSON.stringify(u)} is not a palette slot — use ${Ru.join(", ")} or ansi0-ansi15`);i.push(h),o.push(f)}if(new Set(o).size!==o.length)yn(n,"meta.signature slots must resolve to three different colors");return{names:i,colors:o}}function ua(n,r,e){if(r===void 0)return;if(!e)yn(n,"meta.booru_sites renames meta.booru per site, so it needs meta.booru");if(!r||typeof r!=="object"||Array.isArray(r))yn(n,'meta.booru_sites must be a table of site = "tag" or site = ["tag", ...]');let t={};for(let[i,o]of Object.entries(r)){let s=Mn.find((c)=>c.key===i);if(!s)yn(n,`meta.booru_sites.${i} is not a find site — use ${Mn.map((c)=>c.key).join(", ")}`);let u=typeof o==="string"?[o]:Array.isArray(o)?o:void 0;if(!u||u.some((c)=>typeof c!=="string"||c===""||/\s/.test(c)))yn(n,`meta.booru_sites.${i} must be one tag or a list of tags, got ${JSON.stringify(o)}`);if(u.length>1&&Number.isFinite(s.tagBudget))yn(n,`meta.booru_sites.${i} takes one tag — ${s.name} searches ${s.tagBudget} tags at a time`);t[i]=u}return t}function ca(n){let e=Bun.TOML.parse(ci(hi(n,hr),"utf8")).group;if(!Array.isArray(e)||e.length===0)yn(hr,"needs at least one [[group]] table");return e.map((t)=>{let i=fr(t);return{name:Vn(hr,"group.name",i.name),native:i.native===void 0?void 0:Vn(hr,"group.native",i.native),lead:Vn(hr,"group.lead",i.lead)}})}function ha(n,r,e,t){let i=Bun.TOML.parse(r),o=fr(i.meta),s=fr(i.colors),u=fr(i.contrast),c=s.ansi;if(!Array.isArray(c)||c.length!==16)yn(n,`colors.ansi must hold exactly 16 colors, got ${Array.isArray(c)?c.length:typeof c}`);let h=Vn(n,"meta.name",o.name);if(h!==Dl(n,".toml"))yn(n,`meta.name "${h}" does not match the filename`);if(ra.has(h))yn(n,`meta.name "${h}" collides with a ttheme subcommand`);if(h.startsWith("-"))yn(n,`meta.name "${h}" would be read as a flag by the ttheme CLI`);let f=o.role;if(f!==void 0&&f!=="default")yn(n,`meta.role must be "default", got ${JSON.stringify(f)}`);let l=Vn(n,"meta.group",o.group),g=t.get(l);if(!g)yn(n,`meta.group "${l}" has no [[group]] table in ${hr}`);let d=jr(n,"colors.background",s.background),w=jr(n,"colors.foreground",s.foreground),m=jr(n,"colors.cursor",s.cursor),b=jr(n,"colors.selection_background",s.selection_background),F=c.map((R,M)=>jr(n,`colors.ansi[${M}]`,R)),S=sa(n,o.signature,{background:d,foreground:w,cursor:m,selection:b,ansi:F}),k=o.booru===void 0?void 0:Vn(n,"meta.booru",o.booru);if(k!==void 0&&/\s/.test(k))yn(n,`meta.booru must be a single booru tag, got ${JSON.stringify(k)}`);let y=ua(n,o.booru_sites,k),p=Array.isArray(u.waive)?u.waive.map(String):[];if(p.length>0&&typeof u.reason!=="string")yn(n,"contrast.waive needs a contrast.reason explaining why");return{name:h,group:l,native:g.native,lead:g.lead===h,order:Number(o.order),role:f,ansiSource:Vn(n,"meta.ansi_source",o.ansi_source),...k?{booru:k}:{},...y?{booruSites:y}:{},background:d,foreground:w,cursor:m,selectionBackground:b,ansi:F,signature:S.colors,signatureSlots:S.names,font:ea(n,i.font,e.font),ghostty:ia(n,i.ghostty,e.ghostty,{background:d,cursor:m,selectionBackground:b}),waive:p,waiveReason:typeof u.reason==="string"?u.reason:void 0}}function Gu(n){let r=Bun.TOML.parse(ci(hi(n,na),"utf8")),e=ca(n),t=new Map(e.map((s)=>[s.name,s]));if(t.size!==e.length)yn(hr,"group.name must be unique");let i=xl(n).filter((s)=>s.endsWith(".toml")&&!s.startsWith("_")).map((s)=>ha(s,ci(hi(n,s),"utf8"),r,t)).sort((s,u)=>s.order-u.order);if(new Set(i.map((s)=>s.order)).size!==i.length)throw Error("themes: meta.order must be unique across all themes");for(let s of e){let u=i.filter((c)=>c.group===s.name);if(u.length===0)yn(hr,`group "${s.name}" has no themes`);if(!u.some((c)=>c.name===s.lead))yn(hr,`group "${s.name}" lead "${s.lead}" is not one of its themes`)}return i}function Lu(n){return n.filter((r)=>r.role===void 0)}function Ie(n){let r=(e,t)=>e<t?-1:e>t?1:0;return[...n].sort((e,t)=>r(e.group.toLowerCase(),t.group.toLowerCase())||r(e.name,t.name))}var it=["ghostty","kitty","alacritty","wezterm","iterm2","windows-terminal","warp"];var Ju=/# ttheme begin\n[\s\S]*?# ttheme end\n?/;function ot(n,r){let e=`# ttheme begin
16
- ${r}
2
+ import{createRequire as fa}from"node:module";var ra=Object.create;var{getPrototypeOf:ia,defineProperty:Ko,getOwnPropertyNames:oa}=Object;var sa=Object.prototype.hasOwnProperty;function ca(t){return this[t]}var ua,ha,nr=(t,n,e)=>{var r=t!=null&&typeof t==="object";if(r){var i=n?ua??=new WeakMap:ha??=new WeakMap,o=i.get(t);if(o)return o}e=t!=null?ra(ia(t)):{};let s=n||!t||!t.__esModule?Ko(e,"default",{value:t,enumerable:!0}):e;for(let c of oa(t))if(!sa.call(s,c))Ko(s,c,{get:ca.bind(t,c),enumerable:!0});if(r)i.set(t,s);return s};var $t=(t,n)=>()=>(n||t((n={exports:{}}).exports,n),n.exports);var jt=fa(import.meta.url);var xo=$t((j0,or)=>{var Vo=Vo||function(t){return Buffer.from(t).toString("base64")};function wa(t){var n=this,e=Math.round,r=Math.floor,i=Array(64),o=Array(64),s=Array(64),c=Array(64),u,h,f,a,g=Array(65535),d=Array(65535),p=Array(64),l=Array(64),k=[],v=0,I=7,E=Array(64),y=Array(64),$=Array(64),H=Array(256),b=Array(2048),R,O=[0,1,5,6,14,15,27,28,2,4,7,13,16,26,29,42,3,8,12,17,25,30,41,43,9,11,18,24,31,40,44,53,10,19,23,32,39,45,52,54,20,22,33,38,46,51,55,60,21,34,37,47,50,56,59,61,35,36,48,49,57,58,62,63],P=[0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0],G=[0,1,2,3,4,5,6,7,8,9,10,11],C=[0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,125],A=[1,2,3,0,4,17,5,18,33,49,65,6,19,81,97,7,34,113,20,50,129,145,161,8,35,66,177,193,21,82,209,240,36,51,98,114,130,9,10,22,23,24,25,26,37,38,39,40,41,42,52,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,225,226,227,228,229,230,231,232,233,234,241,242,243,244,245,246,247,248,249,250],Ft=[0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0],U=[0,1,2,3,4,5,6,7,8,9,10,11],x=[0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,119],kt=[0,1,2,3,17,4,5,33,49,6,18,65,81,7,97,113,19,34,50,129,8,20,66,145,161,177,193,9,35,51,82,240,21,98,114,209,10,22,36,52,225,37,241,23,24,25,26,38,39,40,41,42,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,130,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,226,227,228,229,230,231,232,233,234,242,243,244,245,246,247,248,249,250];function dt(m){var L=[16,11,10,16,24,40,51,61,12,12,14,19,26,58,60,55,14,13,16,24,40,57,69,56,14,17,22,29,51,87,80,62,18,22,37,56,68,109,103,77,24,35,55,64,81,104,113,92,49,64,78,87,103,121,120,101,72,92,95,98,112,100,103,99];for(var T=0;T<64;T++){var J=r((L[T]*m+50)/100);if(J<1)J=1;else if(J>255)J=255;i[O[T]]=J}var q=[17,18,24,47,99,99,99,99,18,21,26,66,99,99,99,99,24,26,56,99,99,99,99,99,47,66,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99];for(var X=0;X<64;X++){var rt=r((q[X]*m+50)/100);if(rt<1)rt=1;else if(rt>255)rt=255;o[O[X]]=rt}var it=[1,1.387039845,1.306562965,1.175875602,1,0.785694958,0.5411961,0.275899379],St=0;for(var wt=0;wt<8;wt++)for(var M=0;M<8;M++)s[St]=1/(i[O[St]]*it[wt]*it[M]*8),c[St]=1/(o[O[St]]*it[wt]*it[M]*8),St++}function B(m,L){var T=0,J=0,q=[];for(var X=1;X<=16;X++){for(var rt=1;rt<=m[X];rt++)q[L[J]]=[],q[L[J]][0]=T,q[L[J]][1]=X,J++,T++;T*=2}return q}function It(){u=B(P,G),h=B(Ft,U),f=B(C,A),a=B(x,kt)}function ot(){var m=1,L=2;for(var T=1;T<=15;T++){for(var J=m;J<L;J++)d[32767+J]=T,g[32767+J]=[],g[32767+J][1]=T,g[32767+J][0]=J;for(var q=-(L-1);q<=-m;q++)d[32767+q]=T,g[32767+q]=[],g[32767+q][1]=T,g[32767+q][0]=L-1+q;m<<=1,L<<=1}}function tt(){for(var m=0;m<256;m++)b[m]=19595*m,b[m+256>>0]=38470*m,b[m+512>>0]=7471*m+32768,b[m+768>>0]=-11059*m,b[m+1024>>0]=-21709*m,b[m+1280>>0]=32768*m+8421375,b[m+1536>>0]=-27439*m,b[m+1792>>0]=-5329*m}function z(m){var L=m[0],T=m[1]-1;while(T>=0){if(L&1<<T)v|=1<<I;if(T--,I--,I<0){if(v==255)w(255),w(0);else w(v);I=7,v=0}}}function w(m){k.push(m)}function K(m){w(m>>8&255),w(m&255)}function ht(m,L){var T,J,q,X,rt,it,St,wt,M=0,j,Z=8,Et=64;for(j=0;j<Z;++j){T=m[M],J=m[M+1],q=m[M+2],X=m[M+3],rt=m[M+4],it=m[M+5],St=m[M+6],wt=m[M+7];var _=T+wt,D=T-wt,at=J+St,W=J-St,st=q+it,Ht=q-it,bt=X+rt,qt=X-rt,nn=_+bt,In=_-bt,Kn=at+st,Jn=at-st;m[M]=nn+Kn,m[M+4]=nn-Kn;var ce=(Jn+In)*0.707106781;m[M+2]=In+ce,m[M+6]=In-ce,nn=qt+Ht,Kn=Ht+W,Jn=W+D;var ue=(nn-Jn)*0.382683433,xe=0.5411961*nn+ue,he=1.306562965*Jn+ue,fe=Kn*0.707106781,ae=D+fe,ge=D-fe;m[M+5]=ge+xe,m[M+3]=ge-xe,m[M+1]=ae+he,m[M+7]=ae-he,M+=8}M=0;for(j=0;j<Z;++j){T=m[M],J=m[M+8],q=m[M+16],X=m[M+24],rt=m[M+32],it=m[M+40],St=m[M+48],wt=m[M+56];var vo=T+wt,zr=T-wt,yo=J+St,So=J-St,Fo=q+it,Io=q-it,No=X+rt,ea=X-rt,le=vo+No,Yr=vo-No,Be=yo+Fo,De=yo-Fo;m[M]=le+Be,m[M+32]=le-Be;var Oo=(De+Yr)*0.707106781;m[M+16]=Yr+Oo,m[M+48]=Yr-Oo,le=ea+Io,Be=Io+So,De=So+zr;var Ho=(le-De)*0.382683433,jo=0.5411961*le+Ho,Ro=1.306562965*De+Ho,Go=Be*0.707106781,Lo=zr+Go,Po=zr-Go;m[M+40]=Po+jo,m[M+24]=Po-jo,m[M+8]=Lo+Ro,m[M+56]=Lo-Ro,M++}var tr;for(j=0;j<Et;++j)tr=m[j]*L[j],p[j]=tr>0?tr+0.5|0:tr-0.5|0;return p}function ft(){K(65504),K(16),w(74),w(70),w(73),w(70),w(0),w(1),w(1),w(0),K(1),K(1),w(0),w(0)}function nt(m){if(!m)return;if(K(65505),m[0]===69&&m[1]===120&&m[2]===105&&m[3]===102)K(m.length+2);else K(m.length+5+2),w(69),w(120),w(105),w(102),w(0);for(var L=0;L<m.length;L++)w(m[L])}function et(m,L){K(65472),K(17),w(8),K(L),K(m),w(3),w(1),w(17),w(0),w(2),w(17),w(1),w(3),w(17),w(1)}function Y(){K(65499),K(132),w(0);for(var m=0;m<64;m++)w(i[m]);w(1);for(var L=0;L<64;L++)w(o[L])}function N(){K(65476),K(418),w(0);for(var m=0;m<16;m++)w(P[m+1]);for(var L=0;L<=11;L++)w(G[L]);w(16);for(var T=0;T<16;T++)w(C[T+1]);for(var J=0;J<=161;J++)w(A[J]);w(1);for(var q=0;q<16;q++)w(Ft[q+1]);for(var X=0;X<=11;X++)w(U[X]);w(17);for(var rt=0;rt<16;rt++)w(x[rt+1]);for(var it=0;it<=161;it++)w(kt[it])}function F(m){if(typeof m>"u"||m.constructor!==Array)return;m.forEach((L)=>{if(typeof L!=="string")return;K(65534);var T=L.length;K(T+2);var J;for(J=0;J<T;J++)w(L.charCodeAt(J))})}function pt(){K(65498),K(12),w(3),w(1),w(0),w(2),w(17),w(3),w(17),w(0),w(63),w(0)}function Q(m,L,T,J,q){var X=q[0],rt=q[240],it,St=16,wt=63,M=64,j=ht(m,L);for(var Z=0;Z<M;++Z)l[O[Z]]=j[Z];var Et=l[0]-T;if(T=l[0],Et==0)z(J[0]);else it=32767+Et,z(J[d[it]]),z(g[it]);var _=63;for(;_>0&&l[_]==0;_--);if(_==0)return z(X),T;var D=1,at;while(D<=_){var W=D;for(;l[D]==0&&D<=_;++D);var st=D-W;if(st>=St){at=st>>4;for(var Ht=1;Ht<=at;++Ht)z(rt);st=st&15}it=32767+l[D],z(q[(st<<4)+d[it]]),z(g[it]),D++}if(_!=wt)z(X);return T}function V(){var m=String.fromCharCode;for(var L=0;L<256;L++)H[L]=m(L)}this.encode=function(m,L){var T=new Date().getTime();if(L)Zt(L);k=[],v=0,I=7,K(65496),ft(),F(m.comments),nt(m.exifBuffer),Y(),et(m.width,m.height),N(),pt();var J=0,q=0,X=0;v=0,I=7,this.encode.displayName="_encode_";var{data:rt,width:it,height:St}=m,wt=it*4,M=it*3,j,Z=0,Et,_,D,at,W,st,Ht,bt;while(Z<St){j=0;while(j<wt){at=wt*Z+j,W=at,st=-1,Ht=0;for(bt=0;bt<64;bt++){if(Ht=bt>>3,st=(bt&7)*4,W=at+Ht*wt+st,Z+Ht>=St)W-=wt*(Z+1+Ht-St);if(j+st>=wt)W-=j+st-wt+4;Et=rt[W++],_=rt[W++],D=rt[W++],E[bt]=(b[Et]+b[_+256>>0]+b[D+512>>0]>>16)-128,y[bt]=(b[Et+768>>0]+b[_+1024>>0]+b[D+1280>>0]>>16)-128,$[bt]=(b[Et+1280>>0]+b[_+1536>>0]+b[D+1792>>0]>>16)-128}J=Q(E,s,J,u,f),q=Q(y,c,q,h,a),X=Q($,c,X,h,a),j+=32}Z+=8}if(I>=0){var qt=[];qt[1]=I+1,qt[0]=(1<<I+1)-1,z(qt)}if(K(65497),typeof or>"u")return new Uint8Array(k);return Buffer.from(k);var nn,In};function Zt(m){if(m<=0)m=1;if(m>100)m=100;if(R==m)return;var L=0;if(m<50)L=Math.floor(5000/m);else L=Math.floor(200-m*2);dt(L),R=m}function xt(){var m=new Date().getTime();if(!t)t=50;V(),It(),ot(),tt(),Zt(t);var L=new Date().getTime()-m}xt()}if(typeof or<"u")or.exports=Yo;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].encode=Yo;function Yo(t,n){if(typeof n>"u")n=50;var e=new wa(n),r=e.encode(t,n);return{data:r,width:t.width,height:t.height}}});var Do=$t((R0,ti)=>{var Dr=function(){var n=new Int32Array([0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5,12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28,35,42,49,56,57,50,43,36,29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54,47,55,62,63]),e=4017,r=799,i=3406,o=2276,s=1567,c=3784,u=5793,h=2896;function f(){}function a(I,E){var y=0,$=[],H,b,R=16;while(R>0&&!I[R-1])R--;$.push({children:[],index:0});var O=$[0],P;for(H=0;H<R;H++){for(b=0;b<I[H];b++){O=$.pop(),O.children[O.index]=E[y];while(O.index>0){if($.length===0)throw Error("Could not recreate Huffman Table");O=$.pop()}O.index++,$.push(O);while($.length<=H)$.push(P={children:[],index:0}),O.children[O.index]=P.children,O=P;y++}if(H+1<R)$.push(P={children:[],index:0}),O.children[O.index]=P.children,O=P}return $[0].children}function g(I,E,y,$,H,b,R,O,P,G){var{precision:C,samplesPerLine:A,scanLines:Ft,mcusPerLine:U,progressive:x,maxH:kt,maxV:dt}=y,B=E,It=0,ot=0;function tt(){if(ot>0)return ot--,It>>ot&1;if(It=I[E++],It==255){var M=I[E++];if(M)throw Error("unexpected marker: "+(It<<8|M).toString(16))}return ot=7,It>>>7}function z(M){var j=M,Z;while((Z=tt())!==null){if(j=j[Z],typeof j==="number")return j;if(typeof j!=="object")throw Error("invalid huffman sequence")}return null}function w(M){var j=0;while(M>0){var Z=tt();if(Z===null)return;j=j<<1|Z,M--}return j}function K(M){var j=w(M);if(j>=1<<M-1)return j;return j+(-1<<M)+1}function ht(M,j){var Z=z(M.huffmanTableDC),Et=Z===0?0:K(Z);j[0]=M.pred+=Et;var _=1;while(_<64){var D=z(M.huffmanTableAC),at=D&15,W=D>>4;if(at===0){if(W<15)break;_+=16;continue}_+=W;var st=n[_];j[st]=K(at),_++}}function ft(M,j){var Z=z(M.huffmanTableDC),Et=Z===0?0:K(Z)<<P;j[0]=M.pred+=Et}function nt(M,j){j[0]|=tt()<<P}var et=0;function Y(M,j){if(et>0){et--;return}var Z=b,Et=R;while(Z<=Et){var _=z(M.huffmanTableAC),D=_&15,at=_>>4;if(D===0){if(at<15){et=w(at)+(1<<at)-1;break}Z+=16;continue}Z+=at;var W=n[Z];j[W]=K(D)*(1<<P),Z++}}var N=0,F;function pt(M,j){var Z=b,Et=R,_=0;while(Z<=Et){var D=n[Z],at=j[D]<0?-1:1;switch(N){case 0:var W=z(M.huffmanTableAC),st=W&15,_=W>>4;if(st===0)if(_<15)et=w(_)+(1<<_),N=4;else _=16,N=1;else{if(st!==1)throw Error("invalid ACn encoding");F=K(st),N=_?2:3}continue;case 1:case 2:if(j[D])j[D]+=(tt()<<P)*at;else if(_--,_===0)N=N==2?3:0;break;case 3:if(j[D])j[D]+=(tt()<<P)*at;else j[D]=F<<P,N=0;break;case 4:if(j[D])j[D]+=(tt()<<P)*at;break}Z++}if(N===4){if(et--,et===0)N=0}}function Q(M,j,Z,Et,_){var D=Z/U|0,at=Z%U,W=D*M.v+Et,st=at*M.h+_;if(M.blocks[W]===void 0&&G.tolerantDecoding)return;j(M,M.blocks[W][st])}function V(M,j,Z){var Et=Z/M.blocksPerLine|0,_=Z%M.blocksPerLine;if(M.blocks[Et]===void 0&&G.tolerantDecoding)return;j(M,M.blocks[Et][_])}var Zt=$.length,xt,m,L,T,J,q;if(x)if(b===0)q=O===0?ft:nt;else q=O===0?Y:pt;else q=ht;var X=0,rt,it;if(Zt==1)it=$[0].blocksPerLine*$[0].blocksPerColumn;else it=U*y.mcusPerColumn;if(!H)H=it;var St,wt;while(X<it){for(m=0;m<Zt;m++)$[m].pred=0;if(et=0,Zt==1){xt=$[0];for(J=0;J<H;J++)V(xt,q,X),X++}else for(J=0;J<H;J++){for(m=0;m<Zt;m++){xt=$[m],St=xt.h,wt=xt.v;for(L=0;L<wt;L++)for(T=0;T<St;T++)Q(xt,q,X,L,T)}if(X++,X===it)break}if(X===it)do{if(I[E]===255){if(I[E+1]!==0)break}E+=1}while(E<I.length-2);if(ot=0,rt=I[E]<<8|I[E+1],rt<65280)throw Error("marker was not found");if(rt>=65488&&rt<=65495)E+=2;else break}return E-B}function d(I,E){var y=[],$=E.blocksPerLine,H=E.blocksPerColumn,b=$<<3,R=new Int32Array(64),O=new Uint8Array(64);function P(B,It,ot){var tt=E.quantizationTable,z,w,K,ht,ft,nt,et,Y,N,F=ot,pt;for(pt=0;pt<64;pt++)F[pt]=B[pt]*tt[pt];for(pt=0;pt<8;++pt){var Q=8*pt;if(F[1+Q]==0&&F[2+Q]==0&&F[3+Q]==0&&F[4+Q]==0&&F[5+Q]==0&&F[6+Q]==0&&F[7+Q]==0){N=u*F[0+Q]+512>>10,F[0+Q]=N,F[1+Q]=N,F[2+Q]=N,F[3+Q]=N,F[4+Q]=N,F[5+Q]=N,F[6+Q]=N,F[7+Q]=N;continue}z=u*F[0+Q]+128>>8,w=u*F[4+Q]+128>>8,K=F[2+Q],ht=F[6+Q],ft=h*(F[1+Q]-F[7+Q])+128>>8,Y=h*(F[1+Q]+F[7+Q])+128>>8,nt=F[3+Q]<<4,et=F[5+Q]<<4,N=z-w+1>>1,z=z+w+1>>1,w=N,N=K*c+ht*s+128>>8,K=K*s-ht*c+128>>8,ht=N,N=ft-et+1>>1,ft=ft+et+1>>1,et=N,N=Y+nt+1>>1,nt=Y-nt+1>>1,Y=N,N=z-ht+1>>1,z=z+ht+1>>1,ht=N,N=w-K+1>>1,w=w+K+1>>1,K=N,N=ft*o+Y*i+2048>>12,ft=ft*i-Y*o+2048>>12,Y=N,N=nt*r+et*e+2048>>12,nt=nt*e-et*r+2048>>12,et=N,F[0+Q]=z+Y,F[7+Q]=z-Y,F[1+Q]=w+et,F[6+Q]=w-et,F[2+Q]=K+nt,F[5+Q]=K-nt,F[3+Q]=ht+ft,F[4+Q]=ht-ft}for(pt=0;pt<8;++pt){var V=pt;if(F[8+V]==0&&F[16+V]==0&&F[24+V]==0&&F[32+V]==0&&F[40+V]==0&&F[48+V]==0&&F[56+V]==0){N=u*ot[pt+0]+8192>>14,F[0+V]=N,F[8+V]=N,F[16+V]=N,F[24+V]=N,F[32+V]=N,F[40+V]=N,F[48+V]=N,F[56+V]=N;continue}z=u*F[0+V]+2048>>12,w=u*F[32+V]+2048>>12,K=F[16+V],ht=F[48+V],ft=h*(F[8+V]-F[56+V])+2048>>12,Y=h*(F[8+V]+F[56+V])+2048>>12,nt=F[24+V],et=F[40+V],N=z-w+1>>1,z=z+w+1>>1,w=N,N=K*c+ht*s+2048>>12,K=K*s-ht*c+2048>>12,ht=N,N=ft-et+1>>1,ft=ft+et+1>>1,et=N,N=Y+nt+1>>1,nt=Y-nt+1>>1,Y=N,N=z-ht+1>>1,z=z+ht+1>>1,ht=N,N=w-K+1>>1,w=w+K+1>>1,K=N,N=ft*o+Y*i+2048>>12,ft=ft*i-Y*o+2048>>12,Y=N,N=nt*r+et*e+2048>>12,nt=nt*e-et*r+2048>>12,et=N,F[0+V]=z+Y,F[56+V]=z-Y,F[8+V]=w+et,F[48+V]=w-et,F[16+V]=K+nt,F[40+V]=K-nt,F[24+V]=ht+ft,F[32+V]=ht-ft}for(pt=0;pt<64;++pt){var Zt=128+(F[pt]+8>>4);It[pt]=Zt<0?0:Zt>255?255:Zt}}v(b*H*8);var G,C;for(var A=0;A<H;A++){var Ft=A<<3;for(G=0;G<8;G++)y.push(new Uint8Array(b));for(var U=0;U<$;U++){P(E.blocks[A][U],O,R);var x=0,kt=U<<3;for(C=0;C<8;C++){var dt=y[Ft+C];for(G=0;G<8;G++)dt[kt+G]=O[x++]}}}return y}function p(I){return I<0?0:I>255?255:I}f.prototype={load:function(E){var y=new XMLHttpRequest;y.open("GET",E,!0),y.responseType="arraybuffer",y.onload=function(){var $=new Uint8Array(y.response||y.mozResponseArrayBuffer);if(this.parse($),this.onload)this.onload()}.bind(this),y.send(null)},parse:function(E){var y=this.opts.maxResolutionInMP*1000*1000,$=0,H=E.length;function b(){var W=E[$]<<8|E[$+1];return $+=2,W}function R(){var W=b(),st=E.subarray($,$+W-2);return $+=st.length,st}function O(W){var st=1,Ht=1,bt,qt;for(qt in W.components)if(W.components.hasOwnProperty(qt)){if(bt=W.components[qt],st<bt.h)st=bt.h;if(Ht<bt.v)Ht=bt.v}var nn=Math.ceil(W.samplesPerLine/8/st),In=Math.ceil(W.scanLines/8/Ht);for(qt in W.components)if(W.components.hasOwnProperty(qt)){bt=W.components[qt];var Kn=Math.ceil(Math.ceil(W.samplesPerLine/8)*bt.h/st),Jn=Math.ceil(Math.ceil(W.scanLines/8)*bt.v/Ht),ce=nn*bt.h,ue=In*bt.v,xe=ue*ce,he=[];v(xe*256);for(var fe=0;fe<ue;fe++){var ae=[];for(var ge=0;ge<ce;ge++)ae.push(new Int32Array(64));he.push(ae)}bt.blocksPerLine=Kn,bt.blocksPerColumn=Jn,bt.blocks=he}W.maxH=st,W.maxV=Ht,W.mcusPerLine=nn,W.mcusPerColumn=In}var P=null,G=null,C=null,A,Ft,U=[],x=[],kt=[],dt=[],B=b(),It=-1;if(this.comments=[],B!=65496)throw Error("SOI not found");B=b();while(B!=65497){var ot,tt,z;switch(B){case 65280:break;case 65504:case 65505:case 65506:case 65507:case 65508:case 65509:case 65510:case 65511:case 65512:case 65513:case 65514:case 65515:case 65516:case 65517:case 65518:case 65519:case 65534:var w=R();if(B===65534){var K=String.fromCharCode.apply(null,w);this.comments.push(K)}if(B===65504){if(w[0]===74&&w[1]===70&&w[2]===73&&w[3]===70&&w[4]===0)P={version:{major:w[5],minor:w[6]},densityUnits:w[7],xDensity:w[8]<<8|w[9],yDensity:w[10]<<8|w[11],thumbWidth:w[12],thumbHeight:w[13],thumbData:w.subarray(14,14+3*w[12]*w[13])}}if(B===65505){if(w[0]===69&&w[1]===120&&w[2]===105&&w[3]===102&&w[4]===0)this.exifBuffer=w.subarray(5,w.length)}if(B===65518){if(w[0]===65&&w[1]===100&&w[2]===111&&w[3]===98&&w[4]===101&&w[5]===0)G={version:w[6],flags0:w[7]<<8|w[8],flags1:w[9]<<8|w[10],transformCode:w[11]}}break;case 65499:var ht=b(),ft=ht+$-2;while($<ft){var nt=E[$++];v(256);var et=new Int32Array(64);if(nt>>4===0)for(tt=0;tt<64;tt++){var Y=n[tt];et[Y]=E[$++]}else if(nt>>4===1)for(tt=0;tt<64;tt++){var Y=n[tt];et[Y]=b()}else throw Error("DQT: invalid table spec");U[nt&15]=et}break;case 65472:case 65473:case 65474:b(),A={},A.extended=B===65473,A.progressive=B===65474,A.precision=E[$++],A.scanLines=b(),A.samplesPerLine=b(),A.components={},A.componentsOrder=[];var N=A.scanLines*A.samplesPerLine;if(N>y){var F=Math.ceil((N-y)/1e6);throw Error(`maxResolutionInMP limit exceeded by ${F}MP`)}var pt=E[$++],Q,V=0,Zt=0;for(ot=0;ot<pt;ot++){Q=E[$];var xt=E[$+1]>>4,m=E[$+1]&15,L=E[$+2];if(xt<=0||m<=0)throw Error("Invalid sampling factor, expected values above 0");A.componentsOrder.push(Q),A.components[Q]={h:xt,v:m,quantizationIdx:L},$+=3}O(A),x.push(A);break;case 65476:var T=b();for(ot=2;ot<T;){var J=E[$++],q=new Uint8Array(16),X=0;for(tt=0;tt<16;tt++,$++)X+=q[tt]=E[$];v(16+X);var rt=new Uint8Array(X);for(tt=0;tt<X;tt++,$++)rt[tt]=E[$];ot+=17+X,(J>>4===0?dt:kt)[J&15]=a(q,rt)}break;case 65501:b(),Ft=b();break;case 65500:b(),b();break;case 65498:var it=b(),St=E[$++],wt=[],M;for(ot=0;ot<St;ot++){M=A.components[E[$++]];var j=E[$++];M.huffmanTableDC=dt[j>>4],M.huffmanTableAC=kt[j&15],wt.push(M)}var Z=E[$++],Et=E[$++],_=E[$++],D=g(E,$,A,wt,Ft,Z,Et,_>>4,_&15,this.opts);$+=D;break;case 65535:if(E[$]!==255)$--;break;default:if(E[$-3]==255&&E[$-2]>=192&&E[$-2]<=254){$-=3;break}else if(B===224||B==225){if(It!==-1)throw Error(`first unknown JPEG marker at offset ${It.toString(16)}, second unknown JPEG marker ${B.toString(16)} at offset ${($-1).toString(16)}`);It=$-1;let W=b();if(E[$+W-2]===255){$+=W-2;break}}throw Error("unknown JPEG marker "+B.toString(16))}B=b()}if(x.length!=1)throw Error("only single frame JPEGs supported");for(var ot=0;ot<x.length;ot++){var at=x[ot].components;for(var tt in at)at[tt].quantizationTable=U[at[tt].quantizationIdx],delete at[tt].quantizationIdx}this.width=A.samplesPerLine,this.height=A.scanLines,this.jfif=P,this.adobe=G,this.components=[];for(var ot=0;ot<A.componentsOrder.length;ot++){var M=A.components[A.componentsOrder[ot]];this.components.push({lines:d(A,M),scaleX:M.h/A.maxH,scaleY:M.v/A.maxV})}},getData:function(E,y){var $=this.width/E,H=this.height/y,b,R,O,P,G,C,A,Ft,U,x,kt=0,dt,B,It,ot,tt,z,w,K,ht,ft,nt,et=E*y*this.components.length;v(et);var Y=new Uint8Array(et);switch(this.components.length){case 1:b=this.components[0];for(x=0;x<y;x++){G=b.lines[0|x*b.scaleY*H];for(U=0;U<E;U++)dt=G[0|U*b.scaleX*$],Y[kt++]=dt}break;case 2:b=this.components[0],R=this.components[1];for(x=0;x<y;x++){G=b.lines[0|x*b.scaleY*H],C=R.lines[0|x*R.scaleY*H];for(U=0;U<E;U++)dt=G[0|U*b.scaleX*$],Y[kt++]=dt,dt=C[0|U*R.scaleX*$],Y[kt++]=dt}break;case 3:if(nt=!0,this.adobe&&this.adobe.transformCode)nt=!0;else if(typeof this.opts.colorTransform<"u")nt=!!this.opts.colorTransform;b=this.components[0],R=this.components[1],O=this.components[2];for(x=0;x<y;x++){G=b.lines[0|x*b.scaleY*H],C=R.lines[0|x*R.scaleY*H],A=O.lines[0|x*O.scaleY*H];for(U=0;U<E;U++){if(!nt)K=G[0|U*b.scaleX*$],ht=C[0|U*R.scaleX*$],ft=A[0|U*O.scaleX*$];else dt=G[0|U*b.scaleX*$],B=C[0|U*R.scaleX*$],It=A[0|U*O.scaleX*$],K=p(dt+1.402*(It-128)),ht=p(dt-0.3441363*(B-128)-0.71413636*(It-128)),ft=p(dt+1.772*(B-128));Y[kt++]=K,Y[kt++]=ht,Y[kt++]=ft}}break;case 4:if(!this.adobe)throw Error("Unsupported color mode (4 components)");if(nt=!1,this.adobe&&this.adobe.transformCode)nt=!0;else if(typeof this.opts.colorTransform<"u")nt=!!this.opts.colorTransform;b=this.components[0],R=this.components[1],O=this.components[2],P=this.components[3];for(x=0;x<y;x++){G=b.lines[0|x*b.scaleY*H],C=R.lines[0|x*R.scaleY*H],A=O.lines[0|x*O.scaleY*H],Ft=P.lines[0|x*P.scaleY*H];for(U=0;U<E;U++){if(!nt)tt=G[0|U*b.scaleX*$],z=C[0|U*R.scaleX*$],w=A[0|U*O.scaleX*$],ot=Ft[0|U*P.scaleX*$];else dt=G[0|U*b.scaleX*$],B=C[0|U*R.scaleX*$],It=A[0|U*O.scaleX*$],ot=Ft[0|U*P.scaleX*$],tt=255-p(dt+1.402*(It-128)),z=255-p(dt-0.3441363*(B-128)-0.71413636*(It-128)),w=255-p(dt+1.772*(B-128));Y[kt++]=255-tt,Y[kt++]=255-z,Y[kt++]=255-w,Y[kt++]=255-ot}}break;default:throw Error("Unsupported color mode")}return Y},copyToImageData:function(E,y){var{width:$,height:H,data:b}=E,R=this.getData($,H),O=0,P=0,G,C,A,Ft,U,x,kt,dt,B;switch(this.components.length){case 1:for(C=0;C<H;C++)for(G=0;G<$;G++)if(A=R[O++],b[P++]=A,b[P++]=A,b[P++]=A,y)b[P++]=255;break;case 3:for(C=0;C<H;C++)for(G=0;G<$;G++)if(kt=R[O++],dt=R[O++],B=R[O++],b[P++]=kt,b[P++]=dt,b[P++]=B,y)b[P++]=255;break;case 4:for(C=0;C<H;C++)for(G=0;G<$;G++)if(U=R[O++],x=R[O++],A=R[O++],Ft=R[O++],kt=255-p(U*(1-Ft/255)+Ft),dt=255-p(x*(1-Ft/255)+Ft),B=255-p(A*(1-Ft/255)+Ft),b[P++]=kt,b[P++]=dt,b[P++]=B,y)b[P++]=255;break;default:throw Error("Unsupported color mode")}}};var l=0,k=0;function v(I=0){var E=l+I;if(E>k){var y=Math.ceil((E-k)/1024/1024);throw Error(`maxMemoryUsageInMB limit exceeded by at least ${y}MB`)}l=E}return f.resetMaxMemoryUsage=function(I){l=0,k=I},f.getBytesAllocated=function(){return l},f.requestMemoryAllocation=v,f}();if(typeof ti<"u")ti.exports=Bo;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].decode=Bo;function Bo(t,n={}){var e={colorTransform:void 0,useTArray:!1,formatAsRGBA:!0,tolerantDecoding:!0,maxResolutionInMP:100,maxMemoryUsageInMB:512},r={...e,...n},i=new Uint8Array(t),o=new Dr;o.opts=r,Dr.resetMaxMemoryUsage(r.maxMemoryUsageInMB*1024*1024),o.parse(i);var s=r.formatAsRGBA?4:3,c=o.width*o.height*s;try{Dr.requestMemoryAllocation(c);var u={width:o.width,height:o.height,exifBuffer:o.exifBuffer,data:r.useTArray?new Uint8Array(c):Buffer.alloc(c)};if(o.comments.length>0)u.comments=o.comments}catch(h){if(h instanceof RangeError)throw Error("Could not allocate enough memory for the image. Required: "+c);if(h instanceof ReferenceError){if(h.message==="Buffer is not defined")throw Error("Buffer is not globally defined in this environment. Consider setting useTArray to true")}throw h}return o.copyToImageData(u,r.formatAsRGBA),u}});var ns=$t((G0,ts)=>{var $a=xo(),ba=Do();ts.exports={encode:$a,decode:ba}});var ni=$t((L0,rs)=>{var ka=jt("util"),es=jt("stream"),Dt=rs.exports=function(){es.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};ka.inherits(Dt,es);Dt.prototype.read=function(t,n){this._reads.push({length:Math.abs(t),allowLess:t<0,func:n}),process.nextTick(function(){if(this._process(),this._paused&&this._reads&&this._reads.length>0)this._paused=!1,this.emit("drain")}.bind(this))};Dt.prototype.write=function(t,n){if(!this.writable)return this.emit("error",Error("Stream not writable")),!1;let e;if(Buffer.isBuffer(t))e=t;else e=Buffer.from(t,n||this._encoding);if(this._buffers.push(e),this._buffered+=e.length,this._process(),this._reads&&this._reads.length===0)this._paused=!0;return this.writable&&!this._paused};Dt.prototype.end=function(t,n){if(t)this.write(t,n);if(this.writable=!1,!this._buffers)return;if(this._buffers.length===0)this._end();else this._buffers.push(null),this._process()};Dt.prototype.destroySoon=Dt.prototype.end;Dt.prototype._end=function(){if(this._reads.length>0)this.emit("error",Error("Unexpected end of input"));this.destroy()};Dt.prototype.destroy=function(){if(!this._buffers)return;this.writable=!1,this._reads=null,this._buffers=null,this.emit("close")};Dt.prototype._processReadAllowingLess=function(t){this._reads.shift();let n=this._buffers[0];if(n.length>t.length)this._buffered-=t.length,this._buffers[0]=n.slice(t.length),t.func.call(this,n.slice(0,t.length));else this._buffered-=n.length,this._buffers.shift(),t.func.call(this,n)};Dt.prototype._processRead=function(t){this._reads.shift();let n=0,e=0,r=Buffer.alloc(t.length);while(n<t.length){let i=this._buffers[e++],o=Math.min(i.length,t.length-n);if(i.copy(r,n,0,o),n+=o,o!==i.length)this._buffers[--e]=i.slice(o)}if(e>0)this._buffers.splice(0,e);this._buffered-=t.length,t.func.call(this,r)};Dt.prototype._process=function(){try{while(this._buffered>0&&this._reads&&this._reads.length>0){let t=this._reads[0];if(t.allowLess)this._processReadAllowingLess(t);else if(this._buffered>=t.length)this._processRead(t);else break}if(this._buffers&&!this.writable)this._end()}catch(t){this.emit("error",t)}}});var ei=$t((Ea)=>{var bn=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];Ea.getImagePasses=function(t,n){let e=[],r=t%8,i=n%8,o=(t-r)/8,s=(n-i)/8;for(let c=0;c<bn.length;c++){let u=bn[c],h=o*u.x.length,f=s*u.y.length;for(let a=0;a<u.x.length;a++)if(u.x[a]<r)h++;else break;for(let a=0;a<u.y.length;a++)if(u.y[a]<i)f++;else break;if(h>0&&f>0)e.push({width:h,height:f,index:c})}return e};Ea.getInterlaceIterator=function(t){return function(n,e,r){let i=n%bn[r].x.length,o=(n-i)/bn[r].x.length*8+bn[r].x[i],s=e%bn[r].y.length,c=(e-s)/bn[r].y.length*8+bn[r].y[s];return o*4+c*t*4}}});var ri=$t((K0,is)=>{is.exports=function(n,e,r){let i=n+e-r,o=Math.abs(i-n),s=Math.abs(i-e),c=Math.abs(i-r);if(o<=s&&o<=c)return n;if(s<=c)return e;return r}});var ii=$t((J0,ss)=>{var ya=ei(),Sa=ri();function os(t,n,e){let r=t*n;if(e!==8)r=Math.ceil(r/(8/e));return r}var Un=ss.exports=function(t,n){let{width:e,height:r,interlace:i,bpp:o,depth:s}=t;if(this.read=n.read,this.write=n.write,this.complete=n.complete,this._imageIndex=0,this._images=[],i){let c=ya.getImagePasses(e,r);for(let u=0;u<c.length;u++)this._images.push({byteWidth:os(c[u].width,o,s),height:c[u].height,lineIndex:0})}else this._images.push({byteWidth:os(e,o,s),height:r,lineIndex:0});if(s===8)this._xComparison=o;else if(s===16)this._xComparison=o*2;else this._xComparison=1};Un.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Un.prototype._unFilterType1=function(t,n,e){let r=this._xComparison,i=r-1;for(let o=0;o<e;o++){let s=t[1+o],c=o>i?n[o-r]:0;n[o]=s+c}};Un.prototype._unFilterType2=function(t,n,e){let r=this._lastLine;for(let i=0;i<e;i++){let o=t[1+i],s=r?r[i]:0;n[i]=o+s}};Un.prototype._unFilterType3=function(t,n,e){let r=this._xComparison,i=r-1,o=this._lastLine;for(let s=0;s<e;s++){let c=t[1+s],u=o?o[s]:0,h=s>i?n[s-r]:0,f=Math.floor((h+u)/2);n[s]=c+f}};Un.prototype._unFilterType4=function(t,n,e){let r=this._xComparison,i=r-1,o=this._lastLine;for(let s=0;s<e;s++){let c=t[1+s],u=o?o[s]:0,h=s>i?n[s-r]:0,f=s>i&&o?o[s-r]:0,a=Sa(h,u,f);n[s]=c+a}};Un.prototype._reverseFilterLine=function(t){let n=t[0],e,r=this._images[this._imageIndex],i=r.byteWidth;if(n===0)e=t.slice(1,i+1);else switch(e=Buffer.alloc(i),n){case 1:this._unFilterType1(t,e,i);break;case 2:this._unFilterType2(t,e,i);break;case 3:this._unFilterType3(t,e,i);break;case 4:this._unFilterType4(t,e,i);break;default:throw Error("Unrecognised filter type - "+n)}if(this.write(e),r.lineIndex++,r.lineIndex>=r.height)this._lastLine=null,this._imageIndex++,r=this._images[this._imageIndex];else this._lastLine=e;if(r)this.read(r.byteWidth+1,this._reverseFilterLine.bind(this));else this._lastLine=null,this.complete()}});var hs=$t((A0,us)=>{var Fa=jt("util"),cs=ni(),Ia=ii(),Na=us.exports=function(t){cs.call(this);let n=[],e=this;this._filter=new Ia(t,{read:this.read.bind(this),write:function(r){n.push(r)},complete:function(){e.emit("complete",Buffer.concat(n))}}),this._filter.start()};Fa.inherits(Na,cs)});var Tn=$t((U0,fs)=>{fs.exports={PNG_SIGNATURE:[137,80,78,71,13,10,26,10],TYPE_IHDR:1229472850,TYPE_IEND:1229278788,TYPE_IDAT:1229209940,TYPE_PLTE:1347179589,TYPE_tRNS:1951551059,TYPE_gAMA:1732332865,COLORTYPE_GRAYSCALE:0,COLORTYPE_PALETTE:1,COLORTYPE_COLOR:2,COLORTYPE_ALPHA:4,COLORTYPE_PALETTE_COLOR:3,COLORTYPE_COLOR_ALPHA:6,COLORTYPE_TO_BPP_MAP:{0:1,2:3,3:1,4:2,6:4},GAMMA_DIVISION:1e5}});var ci=$t((T0,as)=>{var oi=[];(function(){for(let t=0;t<256;t++){let n=t;for(let e=0;e<8;e++)if(n&1)n=3988292384^n>>>1;else n=n>>>1;oi[t]=n}})();var si=as.exports=function(){this._crc=-1};si.prototype.write=function(t){for(let n=0;n<t.length;n++)this._crc=oi[(this._crc^t[n])&255]^this._crc>>>8;return!0};si.prototype.crc32=function(){return this._crc^-1};si.crc32=function(t){let n=-1;for(let e=0;e<t.length;e++)n=oi[(n^t[e])&255]^n>>>8;return n^-1}});var ui=$t((W0,gs)=>{var Nt=Tn(),Oa=ci(),Ot=gs.exports=function(t,n){this._options=t,t.checkCRC=t.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[Nt.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[Nt.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[Nt.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[Nt.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[Nt.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[Nt.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=n.read,this.error=n.error,this.metadata=n.metadata,this.gamma=n.gamma,this.transColor=n.transColor,this.palette=n.palette,this.parsed=n.parsed,this.inflateData=n.inflateData,this.finished=n.finished,this.simpleTransparency=n.simpleTransparency,this.headersFinished=n.headersFinished||function(){}};Ot.prototype.start=function(){this.read(Nt.PNG_SIGNATURE.length,this._parseSignature.bind(this))};Ot.prototype._parseSignature=function(t){let n=Nt.PNG_SIGNATURE;for(let e=0;e<n.length;e++)if(t[e]!==n[e]){this.error(Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};Ot.prototype._parseChunkBegin=function(t){let n=t.readUInt32BE(0),e=t.readUInt32BE(4),r="";for(let o=4;o<8;o++)r+=String.fromCharCode(t[o]);let i=Boolean(t[4]&32);if(!this._hasIHDR&&e!==Nt.TYPE_IHDR){this.error(Error("Expected IHDR on beggining"));return}if(this._crc=new Oa,this._crc.write(Buffer.from(r)),this._chunks[e])return this._chunks[e](n);if(!i){this.error(Error("Unsupported critical chunk type "+r));return}this.read(n+4,this._skipChunk.bind(this))};Ot.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};Ot.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};Ot.prototype._parseChunkEnd=function(t){let n=t.readInt32BE(0),e=this._crc.crc32();if(this._options.checkCRC&&e!==n){this.error(Error("Crc error - "+n+" - "+e));return}if(!this._hasIEND)this.read(8,this._parseChunkBegin.bind(this))};Ot.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};Ot.prototype._parseIHDR=function(t){this._crc.write(t);let n=t.readUInt32BE(0),e=t.readUInt32BE(4),r=t[8],i=t[9],o=t[10],s=t[11],c=t[12];if(r!==8&&r!==4&&r!==2&&r!==1&&r!==16){this.error(Error("Unsupported bit depth "+r));return}if(!(i in Nt.COLORTYPE_TO_BPP_MAP)){this.error(Error("Unsupported color type"));return}if(o!==0){this.error(Error("Unsupported compression method"));return}if(s!==0){this.error(Error("Unsupported filter method"));return}if(c!==0&&c!==1){this.error(Error("Unsupported interlace method"));return}this._colorType=i;let u=Nt.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:n,height:e,depth:r,interlace:Boolean(c),palette:Boolean(i&Nt.COLORTYPE_PALETTE),color:Boolean(i&Nt.COLORTYPE_COLOR),alpha:Boolean(i&Nt.COLORTYPE_ALPHA),bpp:u,colorType:i}),this._handleChunkEnd()};Ot.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};Ot.prototype._parsePLTE=function(t){this._crc.write(t);let n=Math.floor(t.length/3);for(let e=0;e<n;e++)this._palette.push([t[e*3],t[e*3+1],t[e*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};Ot.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};Ot.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===Nt.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(Error("Transparency chunk must be after palette"));return}if(t.length>this._palette.length){this.error(Error("More transparent colors than palette size"));return}for(let n=0;n<t.length;n++)this._palette[n][3]=t[n];this.palette(this._palette)}if(this._colorType===Nt.COLORTYPE_GRAYSCALE)this.transColor([t.readUInt16BE(0)]);if(this._colorType===Nt.COLORTYPE_COLOR)this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]);this._handleChunkEnd()};Ot.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};Ot.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/Nt.GAMMA_DIVISION),this._handleChunkEnd()};Ot.prototype._handleIDAT=function(t){if(!this._emittedHeadersFinished)this._emittedHeadersFinished=!0,this.headersFinished();this.read(-t,this._parseIDAT.bind(this,t))};Ot.prototype._parseIDAT=function(t,n){if(this._crc.write(n),this._colorType===Nt.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw Error("Expected palette not found");this.inflateData(n);let e=t-n.length;if(e>0)this._handleIDAT(e);else this._handleChunkEnd()};Ot.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};Ot.prototype._parseIEND=function(t){if(this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished)this.finished()}});var hi=$t((Pa)=>{var ls=ei(),Ha=[function(){},function(t,n,e,r){if(r===n.length)throw Error("Ran out of data");let i=n[r];t[e]=i,t[e+1]=i,t[e+2]=i,t[e+3]=255},function(t,n,e,r){if(r+1>=n.length)throw Error("Ran out of data");let i=n[r];t[e]=i,t[e+1]=i,t[e+2]=i,t[e+3]=n[r+1]},function(t,n,e,r){if(r+2>=n.length)throw Error("Ran out of data");t[e]=n[r],t[e+1]=n[r+1],t[e+2]=n[r+2],t[e+3]=255},function(t,n,e,r){if(r+3>=n.length)throw Error("Ran out of data");t[e]=n[r],t[e+1]=n[r+1],t[e+2]=n[r+2],t[e+3]=n[r+3]}],ja=[function(){},function(t,n,e,r){let i=n[0];t[e]=i,t[e+1]=i,t[e+2]=i,t[e+3]=r},function(t,n,e){let r=n[0];t[e]=r,t[e+1]=r,t[e+2]=r,t[e+3]=n[1]},function(t,n,e,r){t[e]=n[0],t[e+1]=n[1],t[e+2]=n[2],t[e+3]=r},function(t,n,e){t[e]=n[0],t[e+1]=n[1],t[e+2]=n[2],t[e+3]=n[3]}];function Ra(t,n){let e=[],r=0;function i(){if(r===t.length)throw Error("Ran out of data");let o=t[r];r++;let s,c,u,h,f,a,g,d;switch(n){default:throw Error("unrecognised depth");case 16:g=t[r],r++,e.push((o<<8)+g);break;case 4:g=o&15,d=o>>4,e.push(d,g);break;case 2:f=o&3,a=o>>2&3,g=o>>4&3,d=o>>6&3,e.push(d,g,a,f);break;case 1:s=o&1,c=o>>1&1,u=o>>2&1,h=o>>3&1,f=o>>4&1,a=o>>5&1,g=o>>6&1,d=o>>7&1,e.push(d,g,a,f,h,u,c,s);break}}return{get:function(o){while(e.length<o)i();let s=e.slice(0,o);return e=e.slice(o),s},resetAfterLine:function(){e.length=0},end:function(){if(r!==t.length)throw Error("extra data found")}}}function Ga(t,n,e,r,i,o){let{width:s,height:c,index:u}=t;for(let h=0;h<c;h++)for(let f=0;f<s;f++){let a=e(f,h,u);Ha[r](n,i,a,o),o+=r}return o}function La(t,n,e,r,i,o){let{width:s,height:c,index:u}=t;for(let h=0;h<c;h++){for(let f=0;f<s;f++){let a=i.get(r),g=e(f,h,u);ja[r](n,a,g,o)}i.resetAfterLine()}}Pa.dataToBitMap=function(t,n){let{width:e,height:r,depth:i,bpp:o,interlace:s}=n,c;if(i!==8)c=Ra(t,i);let u;if(i<=8)u=Buffer.alloc(e*r*4);else u=new Uint16Array(e*r*4);let h=Math.pow(2,i)-1,f=0,a,g;if(s)a=ls.getImagePasses(e,r),g=ls.getInterlaceIterator(e,r);else{let d=0;g=function(){let p=d;return d+=4,p},a=[{width:e,height:r}]}for(let d=0;d<a.length;d++)if(i===8)f=Ga(a[d],u,g,o,t,f);else La(a[d],u,g,o,c,h);if(i===8){if(f!==t.length)throw Error("extra data found")}else c.end();return u}});var fi=$t((Z0,ds)=>{function Ja(t,n,e,r,i){let o=0;for(let s=0;s<r;s++)for(let c=0;c<e;c++){let u=i[t[o]];if(!u)throw Error("index "+t[o]+" not in palette");for(let h=0;h<4;h++)n[o+h]=u[h];o+=4}}function Aa(t,n,e,r,i){let o=0;for(let s=0;s<r;s++)for(let c=0;c<e;c++){let u=!1;if(i.length===1){if(i[0]===t[o])u=!0}else if(i[0]===t[o]&&i[1]===t[o+1]&&i[2]===t[o+2])u=!0;if(u)for(let h=0;h<4;h++)n[o+h]=0;o+=4}}function Ua(t,n,e,r,i){let o=255,s=Math.pow(2,i)-1,c=0;for(let u=0;u<r;u++)for(let h=0;h<e;h++){for(let f=0;f<4;f++)n[c+f]=Math.floor(t[c+f]*o/s+0.5);c+=4}}ds.exports=function(t,n,e=!1){let{depth:r,width:i,height:o,colorType:s,transColor:c,palette:u}=n,h=t;if(s===3)Ja(t,h,i,o,u);else{if(c)Aa(t,h,i,o,c);if(r!==8&&!e){if(r===16)h=Buffer.alloc(i*o*4);Ua(t,h,i,o,r)}}return h}});var ws=$t((q0,ps)=>{var Ta=jt("util"),ai=jt("zlib"),ms=ni(),Wa=hs(),Qa=ui(),Za=hi(),qa=fi(),rn=ps.exports=function(t){ms.call(this),this._parser=new Qa(t,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,"gamma"),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=t,this.writable=!0,this._parser.start()};Ta.inherits(rn,ms);rn.prototype._handleError=function(t){if(this.emit("error",t),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy)this._inflate.destroy();if(this._filter)this._filter.destroy(),this._filter.on("error",function(){});this.errord=!0};rn.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=ai.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let e=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,r=Math.max(e,ai.Z_MIN_CHUNK);this._inflate=ai.createInflate({chunkSize:r});let i=e,o=this.emit.bind(this,"error");this._inflate.on("error",function(c){if(!i)return;o(c)}),this._filter.on("complete",this._complete.bind(this));let s=this._filter.write.bind(this._filter);this._inflate.on("data",function(c){if(!i)return;if(c.length>i)c=c.slice(0,i);i-=c.length,s(c)}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};rn.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new Wa(this._bitmapInfo)};rn.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};rn.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};rn.prototype._simpleTransparency=function(){this._metaData.alpha=!0};rn.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};rn.prototype._finished=function(){if(this.errord)return;if(!this._inflate)this.emit("error","No Inflate block");else this._inflate.end()};rn.prototype._complete=function(t){if(this.errord)return;let n;try{let e=Za.dataToBitMap(t,this._bitmapInfo);n=qa(e,this._bitmapInfo,this._options.skipRescale),e=null}catch(e){this._handleError(e);return}this.emit("parsed",n)}});var bs=$t((X0,$s)=>{var Xt=Tn();$s.exports=function(t,n,e,r){let i=[Xt.COLORTYPE_COLOR_ALPHA,Xt.COLORTYPE_ALPHA].indexOf(r.colorType)!==-1;if(r.colorType===r.inputColorType){let p=function(){let l=new ArrayBuffer(2);return new DataView(l).setInt16(0,256,!0),new Int16Array(l)[0]!==256}();if(r.bitDepth===8||r.bitDepth===16&&p)return t}let o=r.bitDepth!==16?t:new Uint16Array(t.buffer),s=255,c=Xt.COLORTYPE_TO_BPP_MAP[r.inputColorType];if(c===4&&!r.inputHasAlpha)c=3;let u=Xt.COLORTYPE_TO_BPP_MAP[r.colorType];if(r.bitDepth===16)s=65535,u*=2;let h=Buffer.alloc(n*e*u),f=0,a=0,g=r.bgColor||{};if(g.red===void 0)g.red=s;if(g.green===void 0)g.green=s;if(g.blue===void 0)g.blue=s;function d(){let p,l,k,v=s;switch(r.inputColorType){case Xt.COLORTYPE_COLOR_ALPHA:v=o[f+3],p=o[f],l=o[f+1],k=o[f+2];break;case Xt.COLORTYPE_COLOR:p=o[f],l=o[f+1],k=o[f+2];break;case Xt.COLORTYPE_ALPHA:v=o[f+1],p=o[f],l=p,k=p;break;case Xt.COLORTYPE_GRAYSCALE:p=o[f],l=p,k=p;break;default:throw Error("input color type:"+r.inputColorType+" is not supported at present")}if(r.inputHasAlpha){if(!i)v/=s,p=Math.min(Math.max(Math.round((1-v)*g.red+v*p),0),s),l=Math.min(Math.max(Math.round((1-v)*g.green+v*l),0),s),k=Math.min(Math.max(Math.round((1-v)*g.blue+v*k),0),s)}return{red:p,green:l,blue:k,alpha:v}}for(let p=0;p<e;p++)for(let l=0;l<n;l++){let k=d(o,f);switch(r.colorType){case Xt.COLORTYPE_COLOR_ALPHA:case Xt.COLORTYPE_COLOR:if(r.bitDepth===8){if(h[a]=k.red,h[a+1]=k.green,h[a+2]=k.blue,i)h[a+3]=k.alpha}else if(h.writeUInt16BE(k.red,a),h.writeUInt16BE(k.green,a+2),h.writeUInt16BE(k.blue,a+4),i)h.writeUInt16BE(k.alpha,a+6);break;case Xt.COLORTYPE_ALPHA:case Xt.COLORTYPE_GRAYSCALE:{let v=(k.red+k.green+k.blue)/3;if(r.bitDepth===8){if(h[a]=v,i)h[a+1]=k.alpha}else if(h.writeUInt16BE(v,a),i)h.writeUInt16BE(k.alpha,a+2);break}default:throw Error("unrecognised color Type "+r.colorType)}f+=c,a+=u}return h}});var Ms=$t((_0,Es)=>{var ks=ri();function Xa(t,n,e,r,i){for(let o=0;o<e;o++)r[i+o]=t[n+o]}function _a(t,n,e){let r=0,i=n+e;for(let o=n;o<i;o++)r+=Math.abs(t[o]);return r}function Ca(t,n,e,r,i,o){for(let s=0;s<e;s++){let c=s>=o?t[n+s-o]:0,u=t[n+s]-c;r[i+s]=u}}function za(t,n,e,r){let i=0;for(let o=0;o<e;o++){let s=o>=r?t[n+o-r]:0,c=t[n+o]-s;i+=Math.abs(c)}return i}function Ya(t,n,e,r,i){for(let o=0;o<e;o++){let s=n>0?t[n+o-e]:0,c=t[n+o]-s;r[i+o]=c}}function Va(t,n,e){let r=0,i=n+e;for(let o=n;o<i;o++){let s=n>0?t[o-e]:0,c=t[o]-s;r+=Math.abs(c)}return r}function xa(t,n,e,r,i,o){for(let s=0;s<e;s++){let c=s>=o?t[n+s-o]:0,u=n>0?t[n+s-e]:0,h=t[n+s]-(c+u>>1);r[i+s]=h}}function Ba(t,n,e,r){let i=0;for(let o=0;o<e;o++){let s=o>=r?t[n+o-r]:0,c=n>0?t[n+o-e]:0,u=t[n+o]-(s+c>>1);i+=Math.abs(u)}return i}function Da(t,n,e,r,i,o){for(let s=0;s<e;s++){let c=s>=o?t[n+s-o]:0,u=n>0?t[n+s-e]:0,h=n>0&&s>=o?t[n+s-(e+o)]:0,f=t[n+s]-ks(c,u,h);r[i+s]=f}}function tg(t,n,e,r){let i=0;for(let o=0;o<e;o++){let s=o>=r?t[n+o-r]:0,c=n>0?t[n+o-e]:0,u=n>0&&o>=r?t[n+o-(e+r)]:0,h=t[n+o]-ks(s,c,u);i+=Math.abs(h)}return i}var ng={0:Xa,1:Ca,2:Ya,3:xa,4:Da},eg={0:_a,1:za,2:Va,3:Ba,4:tg};Es.exports=function(t,n,e,r,i){let o;if(!("filterType"in r)||r.filterType===-1)o=[0,1,2,3,4];else if(typeof r.filterType==="number")o=[r.filterType];else throw Error("unrecognised filter types");if(r.bitDepth===16)i*=2;let s=n*i,c=0,u=0,h=Buffer.alloc((s+1)*e),f=o[0];for(let a=0;a<e;a++){if(o.length>1){let g=1/0;for(let d=0;d<o.length;d++){let p=eg[o[d]](t,u,s,i);if(p<g)f=o[d],g=p}}h[c]=f,c++,ng[f](t,u,s,h,c,i),c+=s,u+=s}return h}});var gi=$t((C0,vs)=>{var Gt=Tn(),rg=ci(),ig=bs(),og=Ms(),sg=jt("zlib"),kn=vs.exports=function(t){if(this._options=t,t.deflateChunkSize=t.deflateChunkSize||32768,t.deflateLevel=t.deflateLevel!=null?t.deflateLevel:9,t.deflateStrategy=t.deflateStrategy!=null?t.deflateStrategy:3,t.inputHasAlpha=t.inputHasAlpha!=null?t.inputHasAlpha:!0,t.deflateFactory=t.deflateFactory||sg.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType==="number"?t.colorType:Gt.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType==="number"?t.inputColorType:Gt.COLORTYPE_COLOR_ALPHA,[Gt.COLORTYPE_GRAYSCALE,Gt.COLORTYPE_COLOR,Gt.COLORTYPE_COLOR_ALPHA,Gt.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw Error("option color type:"+t.colorType+" is not supported at present");if([Gt.COLORTYPE_GRAYSCALE,Gt.COLORTYPE_COLOR,Gt.COLORTYPE_COLOR_ALPHA,Gt.COLORTYPE_ALPHA].indexOf(t.inputColorType)===-1)throw Error("option input color type:"+t.inputColorType+" is not supported at present");if(t.bitDepth!==8&&t.bitDepth!==16)throw Error("option bit depth:"+t.bitDepth+" is not supported at present")};kn.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};kn.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};kn.prototype.filterData=function(t,n,e){let r=ig(t,n,e,this._options),i=Gt.COLORTYPE_TO_BPP_MAP[this._options.colorType];return og(r,n,e,this._options,i)};kn.prototype._packChunk=function(t,n){let e=n?n.length:0,r=Buffer.alloc(e+12);if(r.writeUInt32BE(e,0),r.writeUInt32BE(t,4),n)n.copy(r,8);return r.writeInt32BE(rg.crc32(r.slice(4,r.length-4)),r.length-4),r};kn.prototype.packGAMA=function(t){let n=Buffer.alloc(4);return n.writeUInt32BE(Math.floor(t*Gt.GAMMA_DIVISION),0),this._packChunk(Gt.TYPE_gAMA,n)};kn.prototype.packIHDR=function(t,n){let e=Buffer.alloc(13);return e.writeUInt32BE(t,0),e.writeUInt32BE(n,4),e[8]=this._options.bitDepth,e[9]=this._options.colorType,e[10]=0,e[11]=0,e[12]=0,this._packChunk(Gt.TYPE_IHDR,e)};kn.prototype.packIDAT=function(t){return this._packChunk(Gt.TYPE_IDAT,t)};kn.prototype.packIEND=function(){return this._packChunk(Gt.TYPE_IEND,null)}});var Is=$t((z0,Fs)=>{var cg=jt("util"),ys=jt("stream"),ug=Tn(),hg=gi(),Ss=Fs.exports=function(t){ys.call(this);let n=t||{};this._packer=new hg(n),this._deflate=this._packer.createDeflate(),this.readable=!0};cg.inherits(Ss,ys);Ss.prototype.pack=function(t,n,e,r){if(this.emit("data",Buffer.from(ug.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(n,e)),r)this.emit("data",this._packer.packGAMA(r));let i=this._packer.filterData(t,n,e);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(o){this.emit("data",this._packer.packIDAT(o))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(i)}});var Gs=$t((be,Rs)=>{var Ns=jt("assert").ok,Wn=jt("zlib"),fg=jt("util"),Os=jt("buffer").kMaxLength;function Nn(t){if(!(this instanceof Nn))return new Nn(t);if(t&&t.chunkSize<Wn.Z_MIN_CHUNK)t.chunkSize=Wn.Z_MIN_CHUNK;if(Wn.Inflate.call(this,t),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,t&&t.maxLength!=null)this._maxLength=t.maxLength}function ag(t){return new Nn(t)}function Hs(t,n){if(n)process.nextTick(n);if(!t._handle)return;t._handle.close(),t._handle=null}Nn.prototype._processChunk=function(t,n,e){if(typeof e==="function")return Wn.Inflate._processChunk.call(this,t,n,e);let r=this,i=t&&t.length,o=this._chunkSize-this._offset,s=this._maxLength,c=0,u=[],h=0,f;this.on("error",function(p){f=p});function a(p,l){if(r._hadError)return;let k=o-l;if(Ns(k>=0,"have should not go down"),k>0){let v=r._buffer.slice(r._offset,r._offset+k);if(r._offset+=k,v.length>s)v=v.slice(0,s);if(u.push(v),h+=v.length,s-=v.length,s===0)return!1}if(l===0||r._offset>=r._chunkSize)o=r._chunkSize,r._offset=0,r._buffer=Buffer.allocUnsafe(r._chunkSize);if(l===0)return c+=i-p,i=p,!0;return!1}Ns(this._handle,"zlib binding closed");let g;do g=this._handle.writeSync(n,t,c,i,this._buffer,this._offset,o),g=g||this._writeState;while(!this._hadError&&a(g[0],g[1]));if(this._hadError)throw f;if(h>=Os)throw Hs(this),RangeError("Cannot create final Buffer. It would be larger than 0x"+Os.toString(16)+" bytes");let d=Buffer.concat(u,h);return Hs(this),d};fg.inherits(Nn,Wn.Inflate);function gg(t,n){if(typeof n==="string")n=Buffer.from(n);if(!(n instanceof Buffer))throw TypeError("Not a string or buffer");let e=t._finishFlushFlag;if(e==null)e=Wn.Z_FINISH;return t._processChunk(n,e)}function js(t,n){return gg(new Nn(n),t)}Rs.exports=be=js;be.Inflate=Nn;be.createInflate=ag;be.inflateSync=js});var li=$t((Y0,Ps)=>{var Ls=Ps.exports=function(t){this._buffer=t,this._reads=[]};Ls.prototype.read=function(t,n){this._reads.push({length:Math.abs(t),allowLess:t<0,func:n})};Ls.prototype.process=function(){while(this._reads.length>0&&this._buffer.length){let t=this._reads[0];if(this._buffer.length&&(this._buffer.length>=t.length||t.allowLess)){this._reads.shift();let n=this._buffer;this._buffer=n.slice(t.length),t.func.call(this,n.slice(0,t.length))}else break}if(this._reads.length>0)throw Error("There are some read requests waitng on finished stream");if(this._buffer.length>0)throw Error("unrecognised content at end of stream")}});var Ks=$t((mg)=>{var lg=li(),dg=ii();mg.process=function(t,n){let e=[],r=new lg(t);return new dg(n,{read:r.read.bind(r),write:function(o){e.push(o)},complete:function(){}}).start(),r.process(),Buffer.concat(e)}});var Ts=$t((x0,Us)=>{var Js=!0,As=jt("zlib"),wg=Gs();if(!As.deflateSync)Js=!1;var $g=li(),bg=Ks(),kg=ui(),Eg=hi(),Mg=fi();Us.exports=function(t,n){if(!Js)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let e;function r(y){e=y}let i;function o(y){i=y}function s(y){i.transColor=y}function c(y){i.palette=y}function u(){i.alpha=!0}let h;function f(y){h=y}let a=[];function g(y){a.push(y)}let d=new $g(t);if(new kg(n,{read:d.read.bind(d),error:r,metadata:o,gamma:f,palette:c,transColor:s,inflateData:g,simpleTransparency:u}).start(),d.process(),e)throw e;let l=Buffer.concat(a);a.length=0;let k;if(i.interlace)k=As.inflateSync(l);else{let $=((i.width*i.bpp*i.depth+7>>3)+1)*i.height;k=wg(l,{chunkSize:$,maxLength:$})}if(l=null,!k||!k.length)throw Error("bad png - invalid inflate data response");let v=bg.process(k,i);l=null;let I=Eg.dataToBitMap(v,i);v=null;let E=Mg(I,i,n.skipRescale);return i.data=E,i.gamma=h||0,i}});var qs=$t((B0,Zs)=>{var Ws=!0,Qs=jt("zlib");if(!Qs.deflateSync)Ws=!1;var vg=Tn(),yg=gi();Zs.exports=function(t,n){if(!Ws)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let r=new yg(n||{}),i=[];if(i.push(Buffer.from(vg.PNG_SIGNATURE)),i.push(r.packIHDR(t.width,t.height)),t.gamma)i.push(r.packGAMA(t.gamma));let o=r.filterData(t.data,t.width,t.height),s=Qs.deflateSync(o,r.getDeflateOptions());if(o=null,!s||!s.length)throw Error("bad png - invalid compressed data response");return i.push(r.packIDAT(s)),i.push(r.packIEND()),Buffer.concat(i)}});var Xs=$t((Ig)=>{var Sg=Ts(),Fg=qs();Ig.read=function(t,n){return Sg(t,n||{})};Ig.write=function(t,n){return Fg(t,n)}});var Cs=$t((Lg)=>{var Hg=jt("util"),_s=jt("stream"),jg=ws(),Rg=Is(),Gg=Xs(),Lt=Lg.PNG=function(t){if(_s.call(this),t=t||{},this.width=t.width|0,this.height=t.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,t.fill&&this.data)this.data.fill(0);this.gamma=0,this.readable=this.writable=!0,this._parser=new jg(t),this._parser.on("error",this.emit.bind(this,"error")),this._parser.on("close",this._handleClose.bind(this)),this._parser.on("metadata",this._metadata.bind(this)),this._parser.on("gamma",this._gamma.bind(this)),this._parser.on("parsed",function(n){this.data=n,this.emit("parsed",n)}.bind(this)),this._packer=new Rg(t),this._packer.on("data",this.emit.bind(this,"data")),this._packer.on("end",this.emit.bind(this,"end")),this._parser.on("close",this._handleClose.bind(this)),this._packer.on("error",this.emit.bind(this,"error"))};Hg.inherits(Lt,_s);Lt.sync=Gg;Lt.prototype.pack=function(){if(!this.data||!this.data.length)return this.emit("error","No data provided"),this;return process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this};Lt.prototype.parse=function(t,n){if(n){let e,r;e=function(i){this.removeListener("error",r),this.data=i,n(null,this)}.bind(this),r=function(i){this.removeListener("parsed",e),n(i,null)}.bind(this),this.once("parsed",e),this.once("error",r)}return this.end(t),this};Lt.prototype.write=function(t){return this._parser.write(t),!0};Lt.prototype.end=function(t){this._parser.end(t)};Lt.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};Lt.prototype._gamma=function(t){this.gamma=t};Lt.prototype._handleClose=function(){if(!this._parser.writable&&!this._packer.readable)this.emit("close")};Lt.bitblt=function(t,n,e,r,i,o,s,c){if(e|=0,r|=0,i|=0,o|=0,s|=0,c|=0,e>t.width||r>t.height||e+i>t.width||r+o>t.height)throw Error("bitblt reading outside image");if(s>n.width||c>n.height||s+i>n.width||c+o>n.height)throw Error("bitblt writing outside image");for(let u=0;u<o;u++)t.data.copy(n.data,(c+u)*n.width+s<<2,(r+u)*t.width+e<<2,(r+u)*t.width+e+i<<2)};Lt.prototype.bitblt=function(t,n,e,r,i,o,s){return Lt.bitblt(this,t,n,e,r,i,o,s),this};Lt.adjustGamma=function(t){if(t.gamma){for(let n=0;n<t.height;n++)for(let e=0;e<t.width;e++){let r=t.width*n+e<<2;for(let i=0;i<3;i++){let o=t.data[r+i]/255;o=Math.pow(o,0.45454545454545453/t.gamma),t.data[r+i]=Math.round(o*255)}}t.gamma=0}};Lt.prototype.adjustGamma=function(){Lt.adjustGamma(this)}});var oo=$t((vb,Dh)=>{var io={to(t,n){if(!n)return`\x1B[${t+1}G`;return`\x1B[${n+1};${t+1}H`},move(t,n){let e="";if(t<0)e+=`\x1B[${-t}D`;else if(t>0)e+=`\x1B[${t}C`;if(n<0)e+=`\x1B[${-n}A`;else if(n>0)e+=`\x1B[${n}B`;return e},up:(t=1)=>`\x1B[${t}A`,down:(t=1)=>`\x1B[${t}B`,forward:(t=1)=>`\x1B[${t}C`,backward:(t=1)=>`\x1B[${t}D`,nextLine:(t=1)=>"\x1B[E".repeat(t),prevLine:(t=1)=>"\x1B[F".repeat(t),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},up={up:(t=1)=>"\x1B[S".repeat(t),down:(t=1)=>"\x1B[T".repeat(t)},hp={screen:"\x1B[2J",up:(t=1)=>"\x1B[1J".repeat(t),down:(t=1)=>"\x1B[J".repeat(t),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(t){let n="";for(let e=0;e<t;e++)n+=this.line+(e<t-1?io.up():"");if(t)n+=io.left;return n}};Dh.exports={cursor:io,scroll:up,erase:hp,beep:"\x07"}});import{isMainThread as d0}from"node:worker_threads";import{parseArgs as a0}from"node:util";var en={name:"@kecan0406/ttheme",version:"1.0.33",type:"module",bin:{ttheme:"bin/ttheme.js"},files:["bin","dist/manifest.json","dist/ghostty/ttheme.conf","shell","!shell/check.zsh","ghostty/shaders"],description:"Character terminal palettes for ghostty, kitty, alacritty, wezterm and iTerm2",license:"MIT",author:"kecan0406",repository:{type:"git",url:"git+https://github.com/kecan0406/ttheme.git"},homepage:"https://github.com/kecan0406/ttheme#readme",bugs:"https://github.com/kecan0406/ttheme/issues",keywords:["terminal","theme","ghostty","kitty","alacritty","wezterm","iterm2"],devDependencies:{"@biomejs/biome":"^2.3.0","@clack/core":"^1.4.3","@clack/prompts":"^1.7.0","@material/material-color-utilities":"^0.4.0","@types/bun":"^1.3.0","@types/pngjs":"6.0.5","jpeg-js":"^0.4.4",pngjs:"7.0.0",typescript:"^5.8.2"},engines:{bun:">=1.3",node:">=20.11"}};import{rmSync as pu}from"node:fs";import{basename as xl,join as Pe}from"node:path";var ga=/^#[0-9a-f]{6}$/;function Jo(t){return ga.test(t)}function Rt(t){let n=Number.parseInt(t.slice(1),16);return[n>>16&255,n>>8&255,n&255]}function Bt(t){let[n,e,r]=Rt(t).map((i)=>{let o=i/255;return o<=0.03928?o/12.92:((o+0.055)/1.055)**2.4});return 0.2126*n+0.7152*e+0.0722*r}function an(t,n){let e=Bt(t),r=Bt(n);return(Math.max(e,r)+0.05)/(Math.min(e,r)+0.05)}function er(t,n){return Math.round(an(t,n)*100)/100}var wn=7,Ao=3,Vr=0.15,Uo=1.6,To=[1,2,3,4,5,6,9,10,11,12,13,14],Wo=[7,15];function de(t,n){let e=t.ansi[n];if(e===void 0)throw Error(`${t.name}: missing ANSI ${n}`);return e}function xr(t,n,e){let r=t.background;return n.flatMap((i)=>{let o=de(t,i);return an(o,r)<e?[`ANSI ${i} ${o} on ${r} is ${er(o,r)}:1, needs ${e}:1`]:[]})}function Qo(t,n){return Math.min(...n.map((e)=>an(de(t,e),t.background)))}var rr=[{rule:"foreground",label:"foreground on background",unit:"ratio",min:wn,measure:({foreground:t,background:n})=>an(t,n),check:({foreground:t,background:n})=>an(t,n)<wn?[`foreground ${t} on ${n} is ${er(t,n)}:1, needs ${wn}:1`]:[]},{rule:"accents",label:"weakest accent on background",unit:"ratio",min:Ao,measure:(t)=>Qo(t,To),check:(t)=>xr(t,To,Ao)},{rule:"ansi0-dark",label:"ansi0 luminance",unit:"luminance",max:Vr,measure:(t)=>Bt(de(t,0)),check:(t)=>{let n=de(t,0);return Bt(n)>Vr?[`ANSI 0 ${n} has luminance ${Bt(n).toFixed(3)}, needs <= ${Vr}`]:[]}},{rule:"light-ansi",label:"ansi7 and ansi15 on background",unit:"ratio",min:wn,measure:(t)=>Qo(t,Wo),check:(t)=>xr(t,Wo,wn)},{rule:"ansi8-visible",label:"ansi8 on background",unit:"ratio",min:Uo,measure:(t)=>an(de(t,8),t.background),check:(t)=>xr(t,[8],Uo)},{rule:"selection",label:"foreground on selection",unit:"ratio",min:wn,measure:({foreground:t,selectionBackground:n})=>n===void 0?Number.NaN:an(t,n),check:({foreground:t,selectionBackground:n})=>n!==void 0&&an(t,n)<wn?[`foreground ${t} on selection ${n} is ${er(t,n)}:1, needs ${wn}:1`]:[]}],k0=rr.map((t)=>t.rule),ir=rr.map(({rule:t,label:n,unit:e,min:r,max:i})=>({rule:t,label:n,unit:e,...r===void 0?{}:{min:r},...i===void 0?{}:{max:i}}));function Zo(t){return rr.map((n)=>Math.round(n.measure(t)*1000)/1000)}function Br(t){return rr.filter((n)=>!t.waive.includes(n.rule)).flatMap((n)=>n.check(t).map((e)=>({theme:t.name,rule:n.rule,detail:e})))}function qo(t){return t.flatMap(Br)}var la=["black","red","green","yellow","blue","magenta","cyan","white"];function Xo(t,n){return[t,...la.map((e,r)=>`${e} = '${n[r]}'`),""].join(`
3
+ `)}var me={id:"alacritty",limits:"no shaders, no runtime color API (OSC only)",emit(t){let n=[...An(t),"","[colors.primary]",`background = '${t.background}'`,`foreground = '${t.foreground}'`,"","[colors.cursor]",`cursor = '${t.cursor}'`,`text = '${t.background}'`,"","[colors.selection]",`background = '${t.selectionBackground}'`,`text = '${t.foreground}'`,"",Xo("[colors.normal]",t.ansi.slice(0,8)),Xo("[colors.bright]",t.ansi.slice(8,16))].join(`
4
+ `),e=[`# ${t.name} — font settings.`,`# Pair with the palette: import = ["~/.config/alacritty/themes/${t.name}.toml"]`,"","[font]",`size = ${t.font.size}`,"","[font.normal]",`family = '${t.font.family}'`,""].join(`
5
+ `);return[{path:`alacritty/themes/${t.name}.toml`,content:n},{path:`alacritty/config/${t.name}.toml`,content:e}]}};import{isDeepStrictEqual as da}from"node:util";var pe={id:"ghostty",emit(t){let n=[...An(t),`background = ${t.background}`,`foreground = ${t.foreground}`,`cursor-color = ${t.cursor}`,`selection-background = ${t.selectionBackground}`,`selection-foreground = ${t.foreground}`,...t.ansi.map((e,r)=>`palette = ${r}=${e}`),"palette-generate = true","","macos-icon = custom-style",`macos-icon-ghost-color = ${t.ghostty.iconGhost}`,`macos-icon-screen-color = ${t.ghostty.iconScreen.join(",")}`,"macos-icon-frame = chrome",""].join(`
6
+ `);return[{path:`ghostty/themes/${t.name}`,content:n}]},emitShared(t){let[n]=t;if(!n)return[];for(let r of t)if(!da(r.font,n.font)||r.ghostty.shader!==n.ghostty.shader)throw Error(`${r.name}: per-theme font/shader overrides cannot be expressed in the shared ghostty/ttheme.conf`);return[{path:"ghostty/ttheme.conf",content:["# ttheme — shared font and shader, identical for every palette.","# Pick colors with: theme = <palette>",`font-family = ${n.font.family}`,`font-size = ${n.font.size}`,...n.font.codepointMap.map((r)=>`font-codepoint-map = ${r.range}=${r.family}`),...n.ghostty.shader?["",`custom-shader = ~/.config/ghostty/shaders/${n.ghostty.shader}`,"custom-shader-animation = true"]:[],""].join(`
7
+ `)}]}};function $n(t){let[n,e,r]=Rt(t);return{"Alpha Component":1,"Blue Component":r/255,"Color Space":"P3","Green Component":e/255,"Red Component":n/255}}function _o(t){return{...Object.fromEntries(t.ansi.map((n,e)=>[`Ansi ${e} Color`,$n(n)])),"Background Color":$n(t.background),"Bold Color":$n(t.foreground),"Cursor Color":$n(t.cursor),"Cursor Text Color":$n(t.background),"Foreground Color":$n(t.foreground),"Selected Text Color":$n(t.foreground),"Selection Color":$n(t.selectionBackground)}}function ma(t){return t?{"Background Image Location":t.image,"Background Image Mode":t.cover?2:3,Blend:t.opacity}:{"Background Image Location":""}}function Co(t,n,e,r){let i=(s,c)=>({Name:`ttheme · ${c}`,Guid:`ttheme-${c}`,...r?{"Dynamic Profile Parent GUID":r}:{},"Use Separate Colors for Light and Dark Mode":!1,"Harmonize 256 Colors":!0,...ma(n.get(s.name)),..._o(s)}),o=[...e?[i(e,"default")]:[],...t.map((s)=>i(s,s.name))];return`${JSON.stringify({Profiles:o},null,2)}
8
+ `}function pa(t,n){return[` <key>${t}</key>`,"\t<dict>",...Object.entries(n).flatMap(([e,r])=>[` <key>${e}</key>`,typeof r==="string"?` <string>${r}</string>`:` <real>${r}</real>`]),"\t</dict>"].join(`
9
+ `)}var we={id:"iterm2",limits:"colors only — font lives in the profile; colors are Display P3, the space iTerm2 reads OSC colors in",emit(t){let n=['<?xml version="1.0" encoding="UTF-8"?>','<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">','<plist version="1.0">',"<dict>",...Object.entries(_o(t)).map(([e,r])=>pa(e,r)),"</dict>","</plist>",""].join(`
10
+ `);return[{path:`iterm2/${t.name}.itermcolors`,content:n}]}};var $e={id:"kitty",limits:"no GLSL shaders, no per-codepoint font mapping",emit(t){let n=[...An(t),`background ${t.background}`,`foreground ${t.foreground}`,`cursor ${t.cursor}`,`cursor_text_color ${t.background}`,`selection_background ${t.selectionBackground}`,`selection_foreground ${t.foreground}`,...t.ansi.map((r,i)=>`color${i} ${r}`),""].join(`
11
+ `),e=[`# ${t.name} — font settings.`,`# Pair with the palette: include themes/${t.name}.conf`,`font_family ${t.font.family}`,`font_size ${t.font.size}`,""].join(`
12
+ `);return[{path:`kitty/themes/${t.name}.conf`,content:n},{path:`kitty/config/${t.name}.conf`,content:e}]}};function zo(t){return["# Generated by ttheme — rewritten on every add, remove and default; do not edit.","import os","",`THEMES = ${JSON.stringify(t.themes)}`,`BACKGROUNDS = ${JSON.stringify(t.backgrounds)}`,"PLACES = {"," 'top-left': 'top-left', 'top-center': 'top', 'top-right': 'top-right',"," 'center-left': 'left', 'center': 'center', 'center-center': 'center', 'center-right': 'right',"," 'bottom-left': 'bottom-left', 'bottom-center': 'bottom', 'bottom-right': 'bottom-right',","}","","shown = {}","faded = {}","worn = {}","","","def locate(path):"," if path.startswith('~/'):"," return os.path.expanduser(path)"," return path if os.path.isabs(path) else os.path.join(BACKGROUNDS, path)","","","def read(path, into):"," try:"," with open(path, encoding='utf-8') as f:"," lines = f.read().splitlines()"," except OSError:"," return False"," for line in lines:"," key, sep, value = line.partition('=')"," key, value = key.strip(), value.strip()"," if not sep or not key or key.startswith('#'):"," continue"," if key == 'config-file':"," read(locate(value.lstrip('?')), into)"," else:"," into[key] = value"," return True","","","def logo(palette):"," c = {}"," if not palette or not read(os.path.join(BACKGROUNDS, palette + '.conf'), c):"," return None"," image = c.get('background-image', '')"," try:"," opacity = min(float(c.get('background-image-opacity', '1')), 1.0)"," except ValueError:"," opacity = 1.0"," if not image or opacity <= 0:"," return None"," return locate(image), PLACES.get(c.get('background-image-position', 'center'), 'center'), opacity","","","def fade(path, opacity):"," key = f'{path}#{opacity}'"," if key not in faded:"," from kitty.fast_data_types import load_png_data, png_from_32bit_rgba_data"," with open(path, 'rb') as f:"," rgba, width, height = load_png_data(f.read())"," data = bytearray(rgba)"," data[3::4] = data[3::4].translate(bytes(round(a * opacity) for a in range(256)))"," if len(faded) > 8:"," faded.clear()"," faded[key] = png_from_32bit_rgba_data(bytes(data), width, height)"," return key, faded[key]","","","def show(window):"," want = logo(window.user_vars.get('ttheme_shown') or '')"," if window.id in shown and shown[window.id] == want:"," return"," shown[window.id] = want"," try:"," if want is None:"," window.set_logo('')"," elif want[2] < 1:"," key, png = fade(want[0], want[2])"," window.set_logo(key, want[1], 1, png)"," else:"," window.set_logo(want[0], want[1], 1)"," except Exception:"," shown.pop(window.id, None)","","","def theme(palette):"," path = os.path.join(THEMES, palette + '.conf')"," if not palette or not os.path.exists(path):"," return None"," from kitty.colors import parse_colors"," return parse_colors([path])","","","def wear(palette):"," colors = theme(palette) if worn.get('startup') != palette else None"," if colors is None:"," return"," from kitty.colors import patch_colors"," patch_colors(colors[0], colors[1], True, ())"," worn['startup'] = palette","","","def rewear(boss):"," from kitty.colors import patch_colors"," for window in tuple(boss.all_windows):"," colors = theme(window.user_vars.get('ttheme_worn') or '')"," if colors is not None:"," patch_colors(colors[0], colors[1], False, (window,))","","","def on_load(boss, data):"," if getattr(boss, 'ttheme_rewears', False):"," return"," load = boss.load_config_file",""," def reload(*args, **kwargs):"," load(*args, **kwargs)"," worn.pop('startup', None)"," rewear(boss)",""," boss.load_config_file = reload"," boss.ttheme_rewears = True","","","def on_set_user_var(boss, window, data):"," if data['key'] == 'ttheme_shown':"," show(window)"," elif data['key'] == 'ttheme_startup':"," wear(data['value'] or '')","","","def on_focus_change(boss, window, data):"," if data['focused']:"," show(window)","","","def on_close(boss, window, data):"," shown.pop(window.id, None)",""].join(`
13
+ `)}import{createHash as Jg}from"node:crypto";import{mkdirSync as ic,readdirSync as On,readFileSync as oc,renameSync as sc,rmSync as Zn,statSync as Ag,utimesSync as Ug,writeFileSync as ur}from"node:fs";import{isAbsolute as Tg,join as Mt}from"node:path";var Vs=nr(ns(),1),sr=nr(Cs(),1),zs=[137,80,78,71,13,10,26,10],xs=13;function ke(t){return t.length>=zs.length&&zs.every((n,e)=>t[e]===n)}function Pg(t){let n=sr.PNG.sync.read(Buffer.from(t));return{width:n.width,height:n.height,data:new Uint8Array(n.data)}}function Bs(t,n){if(ke(t)){let e=Ee(t);if(e&&e.width*e.height>n)throw Error(`${e.width}×${e.height} is over ${n/1e6} megapixels`);return Pg(t)}if(t[0]===255&&t[1]===216){let e=Vs.decode(t,{useTArray:!0,formatAsRGBA:!0,maxResolutionInMP:n/1e6,maxMemoryUsageInMB:1024});return{width:e.width,height:e.height,data:e.data}}throw Error("not a PNG or JPEG image")}function Qn(t){let n=new sr.PNG({width:t.width,height:t.height});return n.data=Buffer.from(t.data),sr.PNG.sync.write(n)}function Ys(t,n){for(let e=0;e+n.length<=t.length;e++){let r=!0;for(let i=0;i<n.length&&r;i++)r=t[e+i]===n.charCodeAt(i);if(r)return e}return-1}function Ee(t){if(t.length<33||!ke(t))return null;let n=new DataView(t.buffer,t.byteOffset,t.byteLength),e=n.getUint32(16),r=n.getUint32(20);if(t[25]===4||t[25]===6)return{width:e,height:r,alpha:!0};let i=Ys(t,"IDAT");return{width:e,height:r,alpha:Ys(i===-1?t:t.subarray(0,i),"tRNS")!==-1}}function Ds(t,n=xs){let{width:e,height:r}=t,i=-1,o=-1;for(let s=0;s<t.height;s++)for(let c=0;c<t.width;c++)if((t.data[(s*t.width+c)*4+3]??0)>=n)e=Math.min(e,c),i=Math.max(i,c),r=Math.min(r,s),o=Math.max(o,s);return i<0?null:{x:e,y:r,w:i-e+1,h:o-r+1}}function Me(t,n={x:0,y:0,w:t.width,h:t.height}){let e=0;for(let r=n.y;r<n.y+n.h;r++)for(let i=n.x;i<n.x+n.w;i++)if((t.data[(r*t.width+i)*4+3]??0)<xs)e++;return Math.round(e*100/(n.w*n.h))}function Kg(t,n){if(n<=1)return t;let e=Math.max(1,Math.floor(t.width/n)),r=Math.max(1,Math.floor(t.height/n)),i=new Uint8Array(e*r*4),o=t.data;for(let s=0;s<r;s++)for(let c=0;c<e;c++){let u=0,h=0,f=0,a=0;for(let d=0;d<n;d++)for(let p=0;p<n;p++){let l=((s*n+d)*t.width+c*n+p)*4,k=o[l+3]??0;u+=(o[l]??0)*k,h+=(o[l+1]??0)*k,f+=(o[l+2]??0)*k,a+=k}let g=(s*e+c)*4;if(a>0)i[g]=Math.round(u/a),i[g+1]=Math.round(h/a),i[g+2]=Math.round(f/a);i[g+3]=Math.round(a/(n*n))}return{width:e,height:r,data:i}}function tc(t,n,e){let r=Math.min(n/t.width,e/t.height),i=Math.max(1,Math.round(t.width*r)),o=Math.max(1,Math.round(t.height*r)),s=cr(t,{x:0,y:0,w:t.width,h:t.height},i,o),c=new Uint8Array(n*e*4),u=Math.floor((n-i)/2),h=Math.floor((e-o)/2);for(let f=0;f<o;f++)c.set(s.data.subarray(f*i*4,(f+1)*i*4),((h+f)*n+u)*4);return{width:n,height:e,data:c}}function cr(t,n,e,r){let i=Math.max(1,Math.floor(Math.min(n.w/e,n.h/r))),o=Kg(t,i),s=o.data,c=new Uint8Array(e*r*4);for(let u=0;u<r;u++){let h=Math.min(o.height-1,Math.max(0,n.y/i+(u+0.5)*n.h/i/r-0.5)),f=Math.floor(h),a=Math.min(o.height-1,f+1),g=h-f;for(let d=0;d<e;d++){let p=Math.min(o.width-1,Math.max(0,n.x/i+(d+0.5)*n.w/i/e-0.5)),l=Math.floor(p),k=Math.min(o.width-1,l+1),v=p-l,I=(f*o.width+l)*4,E=(f*o.width+k)*4,y=(a*o.width+l)*4,$=(a*o.width+k)*4,H=(s[I+3]??0)*(1-v)*(1-g),b=(s[E+3]??0)*v*(1-g),R=(s[y+3]??0)*(1-v)*g,O=(s[$+3]??0)*v*g,P=H+b+R+O,G=(u*e+d)*4;if(P>0)for(let C=0;C<3;C++){let A=(s[I+C]??0)*H+(s[E+C]??0)*b+(s[y+C]??0)*R+(s[$+C]??0)*O;c[G+C]=Math.round(A/P)}c[G+3]=Math.round(P)}}return{width:e,height:r,data:c}}var nc={width:2560,height:1550},Wg=2560,Qg=0.1,gn={tall:1.15,reach:0.4,widest:0.95,headroom:0.04,margin:0.03,stands:12},Zg=Bt(di("#19161e","#9b86c8",0.2)),qg="shelf";function di(t,n,e){let r=Rt(t),i=Rt(n);return`#${r.map((o,s)=>Math.round(o+((i[s]??0)-o)*e).toString(16).padStart(2,"0")).join("")}`}function Xg(t,n){if(n==="background"||n==="foreground"||n==="cursor")return t[n];if(n==="selection"&&t.selection)return t.selection;let e=/^ansi(\d|1[0-5])$/.exec(n),r=e?t.ansi[Number(e[1])]:void 0;if(!r)throw Error(`${t.name} has no slot ${n}`);return r}function ec(t){if(t(1))return 1;let n=0,e=1;for(let r=0;r<40;r++){let i=(n+e)/2;if(t(i))n=i;else e=i}return n}function rc(t,n){let e=Xg(t,n),i=ec((h)=>Br({name:t.name,background:di(t.background,e,h),foreground:t.foreground,ansi:t.ansi,waive:t.waived??[]}).length===0),o=ec((h)=>Bt(di(t.background,e,h))<=Zg),s=Math.floor(Math.min(i,o)*1000)/1000,c=Rt(t.background),u=Math.hypot(...Rt(e).map((h,f)=>(h-(c[f]??0))*s));return{slot:n,color:e,cap:i,matched:o,opacity:s,reach:u}}function hr(t,n){let e=rc(t,"cursor");if(e.opacity>=Qg)return e;return n.filter((r)=>r!=="cursor"&&r!=="background").map((r)=>rc(t,r)).reduce((r,i)=>i.reach>r.reach?i:r,e)}function mi(t,n,e){let r=Rt(n),i=Rt(e),o=t.data;for(let s=0;s<o.length;s+=4){let c=(0.299*(o[s]??0)+0.587*(o[s+1]??0)+0.114*(o[s+2]??0))/255;for(let u=0;u<3;u++)o[s+u]=Math.round((r[u]??0)+((i[u]??0)-(r[u]??0))*c)}return t}function _g(t,n,e){let r=Rt(n),i=t.data,o=new Uint8Array(i.length);for(let s=0;s<i.length;s+=4){let c=(i[s+3]??0)/255*e;for(let u=0;u<3;u++)o[s+u]=Math.round((r[u]??0)*(1-c)+(i[s+u]??0)*c);o[s+3]=255}return{width:t.width,height:t.height,data:o}}function cc(t){return Ds(t)??{x:0,y:0,w:t.width,h:t.height}}function Cg(t,n){if(t<=0||n<=0)return nc;let e=Math.min(1,nc.width/Math.max(t,n));return{width:Math.round(t*e),height:Math.round(n*e)}}function zg(t,n){let e=Math.min(1,Wg/Math.max(n.w,n.h));return cr(t,n,Math.round(n.w*e),Math.round(n.h*e))}function uc(t,n,e,r){if(r<gn.stands){let u=t.w*e>t.h*n?{x:t.x+(t.w-t.h*n/e)/2,y:t.y,w:t.h*n/e,h:t.h}:{x:t.x,y:t.y,w:t.w,h:t.w*e/n};return{crop:u,at:{x:0,y:0,w:n,h:e},focus:(u.y-t.y+u.h/2)/t.h}}let i=Math.max(gn.tall*e,gn.reach*n*t.h/t.w),o=i*t.w/t.h;if(o>gn.widest*n)o=gn.widest*n,i=o*t.h/t.w;let s=gn.headroom*e,c=Math.min(1,(e-s)/i);return{crop:{x:t.x,y:t.y,w:t.w,h:t.h*c},at:{x:n*(1-gn.margin)-o,y:s,w:o,h:i*c},focus:Math.min(1,(e/2-s)/i)}}function hc(t,n,e,r){let i=Math.max(1,Math.round(n.at.w)),o=Math.max(1,Math.round(n.at.h)),s=cr(t,n.crop,i,o),c=new Uint8Array(e*r*4),u=Math.round(n.at.x),h=Math.round(n.at.y);for(let f=0;f<o;f++){let a=h+f,g=Math.max(0,-u),d=Math.min(i,e-u);if(a<0||a>=r||d<=g)continue;c.set(s.data.subarray((f*i+g)*4,(f*i+d)*4),(a*e+u+g)*4)}return{width:e,height:r,data:c}}function fc(t,n,e,r,i){let o=cc(t),s=hc(t,uc(o,r,i,Me(t,o)),r,i);return _g(mi(s,n.background,e.color),n.background,e.opacity)}function En(t){return Mt(t,"ttheme","backgrounds")}function Yg(t,n,e,r,i){return[...r?[`# from ${r}`]:[],...i?[`# image ${i}`]:[],`background-image = ${n}`,"background-image-fit = cover","background-image-position = top-right",`background-image-opacity = ${e}`,`config-file = ?${t}.tune.conf`,`config-file = ?${t}.off.conf`,""].join(`
14
+ `)}function ac(t,n,e){let r=new Map;for(let s of[`${n}.conf`,`${n}.tune.conf`,`${n}.off.conf`]){let c;try{c=oc(Mt(t,s),"utf8")}catch{if(s===`${n}.conf`)return;continue}for(let u of c.split(`
15
+ `)){let h=/^(background-image(?:-fit|-opacity)?)\s*=\s*(.*?)\s*$/.exec(u);if(h)r.set(h[1],h[2])}}let i=r.get("background-image")??"";if(i==="")return;let o=Number(r.get("background-image-opacity")??1);return{image:i.startsWith("~/")?Mt(e,i.slice(2)):Tg(i)?i:Mt(t,i),opacity:Number.isFinite(o)?o:1,cover:r.get("background-image-fit")==="cover"}}function Vg(t,n){for(let e of On(t))if(pi(e,n))Zn(Mt(t,e))}function xg(t){return`${t.site}_${t.id}`}function fr(t,n){return Mt(t,qg,n)}function pi(t,n){let e=t.slice(n.length);return t.startsWith(n)&&(e===".conf"||e===".tune.conf"||e===".off.conf"||/^(\.[0-9a-f]{8})?(@[a-z0-9-]+)?\.png$/.test(e))}function ve(t,n){try{return/^# image (\S+)$/m.exec(oc(Mt(t,`${n}.conf`),"utf8"))?.[1]}catch{return}}function Bg(t,n){try{return On(fr(t,n))}catch{return[]}}function gc(t,n){let e=ve(t,n);return[...e?[e]:[],...Bg(t,n)].sort()}function lc(t,n){let e=ve(t,n);if(!e)return;let r=Mt(fr(t,n),e);Zn(r,{recursive:!0,force:!0}),ic(r,{recursive:!0});for(let i of On(t))if(pi(i,n))sc(Mt(t,i),Mt(r,i.slice(n.length)))}function dc(t,n,e){let r=Mt(fr(t,n),e);for(let i of On(r))sc(Mt(r,i),Mt(t,`${n}${i}`));Zn(r,{recursive:!0})}function mc(t,n,e){try{return On(Mt(t,"originals")).find((r)=>r.startsWith(`${n}-${e}.`))}catch{return}}function pc(t,n,e){let r=mc(t,n,e);if(r){let i=new Date;Ug(Mt(t,"originals",r),i,i)}}function wc(t,n,e){let r=En(t),i=gc(r,n),o=ve(r,n);if(!o||i.length<2)throw Error(`${n} has no other image`);let s=(i.indexOf(o)+e+i.length)%i.length,c=i[s];return lc(r,n),dc(r,n,c),pc(r,n,c),{key:c,at:s+1,of:i.length}}function $c(t,n){let e=En(t),r=On(e).filter((h)=>pi(h,n));if(r.length===0)throw Error(`${n} has no image`);let i=gc(e,n),o=ve(e,n),s=o&&mc(e,n,o);if(s)Zn(Mt(e,"originals",s));for(let h of r)Zn(Mt(e,h));let c=i.filter((h)=>h!==o),u=c[(o?i.indexOf(o):0)%c.length];if(u)dc(e,n,u),pc(e,n,u);return{key:o,left:c.length}}function Dg(t,n,e){if(ve(t,n)!==e)lc(t,n);if(e)Zn(Mt(fr(t,n),e),{recursive:!0,force:!0});Vg(t,n)}function bc(t,n,e,r,i,o){let s=En(t),c=n.name,u=xg(i);ic(Mt(s,"originals"),{recursive:!0}),Dg(s,c,u);let h=cc(r),{width:f,height:a}=Cg(o.width,o.height),g=uc(h,f,a,Me(r,h)),d=Qn(mi(zg(r,h),n.background,e.color)),p=Qn(mi(hc(r,g,f,a),n.background,e.color)),l=Mt(s,`${c}.${Jg("sha1").update(d).update(p).digest("hex").slice(0,8)}`),k=`${l}.png`,v=`${l}@fill-${Math.round(g.focus*100)}.png`,I=Mt(s,`${c}.conf`),E=Mt(s,"originals",`${c}-${i.site}_${i.id}.${i.ext}`);return ur(k,d),ur(v,p),ur(I,Yg(c,v,e.opacity,i.from,u)),ur(E,i.bytes),[k,v,I,E]}function kc(t){let n=Mt(En(t),"originals"),e=new Map,r;try{r=On(n)}catch{return new Map}for(let i of r){let o=/^(.+)-([a-z.]+)_(\d+)\.[a-z]+$/.exec(i),[,s,c,u]=o??[];if(!s||!c||!u)continue;let h=Ag(Mt(n,i)).mtimeMs,f=e.get(s);if(!f||h>f.at)e.set(s,{site:c,id:Number(u),at:h})}return new Map([...e].map(([i,{site:o,id:s}])=>[i,{site:o,id:s}]))}function wi(t){let{slot:n,color:e,opacity:r}=hr({name:t.name,background:t.background,foreground:t.foreground,cursor:t.cursor,selection:t.selectionBackground,ansi:t.ansi,waived:t.waive},t.signatureSlots);return{name:t.name,group:t.group,...t.native?{native:t.native}:{},...t.lead?{lead:!0}:{},order:t.order,ansiSource:t.ansiSource,...t.booru?{booru:t.booru}:{},...t.booruSites?{booruSites:t.booruSites}:{},...t.role==="default"?{default:!0}:{},background:t.background,foreground:t.foreground,cursor:t.cursor,selection:t.selectionBackground,signature:t.signature,signatureSlots:t.signatureSlots,ansi:t.ansi,gate:Zo(t),...t.waive.length>0?{waived:t.waive}:{},backdrop:{slot:n,color:e,opacity:r}}}function qn(t){return t.filter((n)=>n.default!==!0)}function tl(t){let[n]=t;if(!n)throw Error("manifest needs at least one theme");return{version:en.version,gate:ir,placement:gn,font:n.font,...n.ghostty.shader?{shader:n.ghostty.shader}:{},palettes:t.map(wi)}}var $i={id:"meta",emitShared(t){return[{path:"manifest.json",content:`${JSON.stringify(tl(t),null,2)}
16
+ `}]}};import{readdirSync as Rl,readFileSync as yi}from"node:fs";import{basename as Gl,join as Si}from"node:path";import{readdirSync as nl,rmSync as el,statSync as rl}from"node:fs";import{setDefaultAutoSelectFamilyAttemptTimeout as il}from"node:net";import{homedir as ol}from"node:os";import{join as Se}from"node:path";import{setTimeout as sl}from"node:timers/promises";var Hn=100,Rn=25000000,cl=536870912,Fe=["safe","questionable","explicit"],jn=["nudity","underwear"],ul={nudity:new Set(["nude","naked","topless","bottomless","nipples","naked_towel","undressing"]),underwear:new Set(["underwear","panties","pantsu","bra","lingerie","pantyshot"])},ye={safe:"s",questionable:"q",explicit:"e"},hl=8191,fl=20000,al=5000,Ec=3000,Mc=8,gl=3000,Fc=60000,vc=3,ki=`ttheme/${en.version} (+${en.homepage})`,ll=["orig","tile","thumb","cut"],Ic=new Map,dl=yl(process.env.TTHEME_FIND_HOSTS),ml=vl(process.env.TTHEME_FIND_CUTOUTS);il(gl);function yc(t){try{return nl(t)}catch{return[]}}function ar(t){return t.startsWith("//")?`https:${t}`:t}function Ie(t){return(/\.([a-z0-9]+)(?:\?.*)?$/i.exec(t)?.[1]??"").toLowerCase()}function Ne(t){let n=t.trim();if(!n)return[];let e=JSON.parse(n);if(Array.isArray(e))return e;let r=e.posts;return Array.isArray(r)?r:[]}function pl(t){let n=t.trim(),r=(n?JSON.parse(n):{}).tags??{};return new Map(Object.entries(r).map(([i,o])=>[i,String(o)]))}function bi(t,n,e){let r=ar(String(t??""));return{file:r,width:Number(n)||0,height:Number(e)||0,ext:Ie(r)}}function Nc(t,n){let e=ar(String(n.preview??""));if(!n.file||!e||!Number(t.id))return[];let r=Number(t.width??t.image_width)||0,i=Number(t.height??t.image_height)||0;return[{id:Number(t.id),width:r,height:i,file:n.file,preview:e,ext:n.ext,owner:String(n.owner??""),artist:n.artist,score:Number(t.score)||0,rating:String(t.rating??""),md5:String(n.md5??""),source:String(t.source??""),tags:n.tags.split(/\s+/).filter(Boolean),solo:n.solo,family:Number(t.parent_id)||(t.has_children===!0?Number(t.id):0),smaller:n.versions.filter((o)=>o.file&&o.width>0&&o.height>0&&o.width*o.height<r*i)}]}function wl(t){let n=pl(t);return Ne(t).flatMap((e)=>{let r=ar(String(e.file_url??"")),i=String(e.tags??"");return Nc(e,{preview:e.preview_url,file:r,ext:String(e.file_ext||Ie(r)).toLowerCase(),owner:e.author,artist:i.split(/\s+/).find((o)=>n.get(o)==="artist")??"",md5:e.md5,tags:i,solo:void 0,versions:[bi(e.jpeg_url,e.jpeg_width,e.jpeg_height),bi(e.sample_url,e.sample_width,e.sample_height)]})})}function $l(t){return Ne(t).flatMap((n)=>{let e=ar(String(n.file_url??"")),r=String(n.tag_string??""),i=n.media_asset??{};return Nc(n,{preview:i.variants?.find((o)=>o.type==="360x360")?.url??n.preview_file_url,file:e,ext:String(n.file_ext||Ie(e)).toLowerCase(),owner:"",artist:String(n.tag_string_artist??"").split(/\s+/)[0]??"",md5:n.md5,tags:r,solo:r.split(/\s+/).includes("solo"),versions:(i.variants??[]).map((o)=>bi(o.url,o.width,o.height)).filter((o)=>o.ext==="jpg"||o.ext==="png").sort((o,s)=>s.width*s.height-o.width*o.height)})})}function bl(t){return Ne(t).flatMap((n)=>{let e=String(n.value??"");return e?[{value:e,count:Number(n.post_count)||0}]:[]})}function kl(t){return Ne(t).flatMap((n)=>{let e=String(n.name??"");return e?[{value:e,count:Number(n.count)||0}]:[]})}function El(t){return Number(/count="(\d+)"/.exec(t)?.[1]??0)}function Ml(t){let n=t.trim()?JSON.parse(t):{};return Number(n.counts?.posts)||0}function vl(t){let n=new Map;for(let e of(t??"").split(/\s+/).filter(Boolean)){let r=e.indexOf("=");if(r>0)n.set(e.slice(0,r),e.slice(r+1).split(",").filter(Boolean))}return n}function yl(t){let n=new Map;for(let e of(t??"").split(/[\s,]+/).filter(Boolean)){let r=e.indexOf("="),i=e.slice(0,r);try{let o=new URL(e.slice(r+1));if(i&&o.protocol==="https:")n.set(i,o.origin)}catch{}}return n}function Oc(t,n,e,r){let i=(t??"").split(/\s+/);if(r!==void 0&&i.includes(r))return[];let o=n.filter((s)=>i.includes(s));return o.length>0?o:[...e]}function gr(t){return Oc(t,Fe,["safe"])}function lr(t){return Oc(t,jn,jn,"none")}function Hc(t,n,e){return{safe:new Set(t),questionable:new Set(n),explicit:new Set(e)}}function jc(t){let n=dl.get(t.key),e=ml.get(t.key);return{...t,origin:n??t.origin,moved:n!==void 0&&n!==t.origin,cutouts:e??t.cutouts,vouched:t.vouched&&e===void 0}}function Rc(t){return t.length<2?t.join(""):t.map((n)=>`~${n}`).join(" ")}function Sc(t){let n=jc(t),e=(r)=>new URLSearchParams({api_version:"2",include_tags:"1",...r});return{...n,cutouts:Rc(n.cutouts),ratings:Hc([ye.safe],[ye.questionable],[ye.explicit]),rate:(r)=>{let[i]=r;if(r.length===1&&i)return`rating:${ye[i]}`;let o=Fe.filter((c)=>!r.includes(c)),[s]=o;return o.length===1&&s?`-rating:${ye[s]}`:""},best:"order:score",tagBudget:Number.POSITIVE_INFINITY,postsUrl:(r,i)=>`${n.origin}/post.json?${e({limit:String(Hn),page:String(i+1),tags:r})}`,countUrl:(r)=>`${n.origin}/post.xml?${new URLSearchParams({limit:"1",tags:r})}`,postUrl:(r)=>`${n.origin}/post.json?${e({tags:`id:${r}`})}`,pageUrl:(r)=>`${n.origin}/post/show/${r}`,parse:wl,count:El}}function Sl(t){let n=jc(t),e=Hc(["g"],["s","q"],["e"]);return{...n,cutouts:Rc(n.cutouts),ratings:e,rate:(r)=>r.length===Fe.length?"":`rating:${r.flatMap((i)=>[...e[i]]).join(",")}`,best:"order:score",tagBudget:2,postsUrl:(r,i)=>`${n.origin}/posts.json?${new URLSearchParams({limit:String(Hn),page:String(i+1),tags:r})}`,countUrl:(r)=>`${n.origin}/counts/posts.json?${new URLSearchParams({tags:r})}`,postUrl:(r)=>`${n.origin}/posts.json?${new URLSearchParams({limit:"1",tags:`id:${r}`})}`,pageUrl:(r)=>`${n.origin}/posts/${r}`,parse:$l,count:Ml}}function Fl(t){return gt.find((n)=>n.key===t||n.name===t||new URL(n.origin).host===t)}function Ei(t){return t.split(/\s+/).filter((n)=>n&&!n.startsWith("rating:")).length}function dr(t,n){let e=t.trim();if(/^\d+$/.test(e))return{site:n,id:Number(e)};let r=/^([\w.]+):(\d+)$/.exec(e);if(r){let c=gt.find((u)=>u.key===r[1]||u.name===r[1]);return c&&{site:c,id:Number(r[2])}}let i;try{i=new URL(e)}catch{return}let o=Fl(i.host),s=Number(i.searchParams.get("id")??i.pathname.split("/").filter(Boolean).at(-1));return o&&s>0?{site:o,id:s}:void 0}var gt=[Sl({key:"danbooru",name:"danbooru",origin:"https://danbooru.donmai.us",cutouts:["transparent_background"],vouched:!1,tunneled:!0,ansi:2}),Sc({key:"konachan",name:"konachan",origin:"https://konachan.net",cutouts:["transparent","vector"],vouched:!1,tunneled:!1,ansi:6}),Sc({key:"yande",name:"yande.re",origin:"https://yande.re",cutouts:["transparent_png"],vouched:!0,tunneled:!1,ansi:5})],ln=134217728;function on(t,n){let e=gt.indexOf(t);return(e===-1?gt.length:e)*ln+n}function Mi(t){let n;try{n=new URL(t).hostname}catch{return""}return n.split(".").slice(-2).join(".")}function Gc(){return gt.filter((t)=>!t.tunneled).map((t)=>Mi(t.origin)).flatMap((t)=>[t,`.${t}`]).join(",")}function Lc(t,n=jn){return t.tags.filter((e)=>n.some((r)=>ul[r].has(e)))}function Pc(t,n,e=["safe"]){return e.some((r)=>t.ratings[r].has(n.rating))}function Oe(t){return[t,...t.smaller].find((n)=>n.width*n.height<=Rn)}function Kc(t){let n=new Map;for(let[e,r]of[...t].sort(([i],[o])=>i<o?-1:1)){if(r==="")continue;n.set(r,[...n.get(r)??[],e])}return n}function Jc(){return Se(process.env.XDG_CACHE_HOME??Se(ol(),".cache"),"ttheme")}function yn(t){return Se(Jc(),t.key)}function Ac(t=cl,n=Jc()){let e=[],r=0;for(let i of yc(n))for(let o of ll){let s=Se(n,i,o);for(let c of yc(s)){let u=Se(s,c);try{let{size:h,mtimeMs:f}=rl(u);e.push({path:u,size:h,at:f}),r+=h}catch{}}}e.sort((i,o)=>i.at-o.at);for(let i of e){if(r<=t)return;try{el(i.path,{force:!0}),r-=i.size}catch{}}}function Il(t,n){if(t!==null&&/^\s*\d+\s*$/.test(t))return Number(t)*1000;let e=t===null?Number.NaN:Date.parse(t);return Number.isNaN(e)?Fc:Math.max(0,e-n)}function Mn(t){return Ic.get(t.key)??0}function Nl(t){for(let n=t;n instanceof Error;n=n.cause)if(n.code==="ECONNRESET")return!0;return!1}function Ol(t){return(t.headers.get("server")??"").startsWith("cloudflare")&&t.headers.get("cf-mitigated")==="challenge"}async function vn(t,n,e,r={},i=fl){for(let o=1;;o++){let s=Mn(t)-Date.now();if(s>0)await sl(s,void 0,{signal:e});let c;try{c=await fetch(n,{headers:{"User-Agent":ki,Referer:`${t.origin}/`,...r},signal:i?AbortSignal.any([e,AbortSignal.timeout(i)]):e})}catch(u){if(o<vc&&!e.aborted&&Nl(u))continue;throw u}if(c.status===429&&o<vc){await c.body?.cancel();let u=Il(c.headers.get("retry-after"),Date.now());if(u>Fc)throw Error(`${t.name} asks to wait ${Math.ceil(u/1000)}s`);Ic.set(t.key,Math.max(Mn(t),Date.now()+u));continue}if(!c.ok)throw await c.body?.cancel(),Error(Ol(c)?`${t.name} is behind a Cloudflare challenge`:`${t.name} answered ${c.status}`);return c}}async function Uc(t,n,e,r){return t.parse(await(await vn(t,t.postsUrl(n,e),r)).text())}async function Tc(t,n,e){return t.count(await(await vn(t,t.countUrl(n),e)).text())}async function vi(t,n,e){let[r]=t.parse(await(await vn(t,t.postUrl(n),e)).text());return r}function Hl(t){let n=gt.find((r)=>r.key==="danbooru"),e=new URLSearchParams({limit:String(2*Hn),only:"md5,tag_string",tags:`md5:${t.join(",")}`});return`${n.origin}/posts.json?${e}`}function jl(t){return new Map(Ne(t).flatMap((n)=>{let e=String(n.md5??"");return e?[[e,String(n.tag_string??"").split(/\s+/).filter(Boolean)]]:[]}))}function Wc(t,n){for(let e of t){let r=n.get(e.md5);if(r)e.tags=[...new Set([...e.tags,...r])],e.solo=r.includes("solo")}}async function Qc(t,n){let e=gt.find((i)=>i.key==="danbooru"),r=new Map;if(Mn(e)>Date.now())return r;for(let i=0;i<t.length;i+=Hn){let o=await(await vn(e,Hl(t.slice(i,i+Hn)),n,{},al)).text();for(let[s,c]of jl(o))r.set(s,c)}return r}async function Zc(t,n){let e=gt.find((o)=>o.key==="danbooru");if(Mn(e)<=Date.now())try{let o=new URLSearchParams({"search[query]":t,"search[type]":"tag_query",limit:String(Mc)}),s=`${e.origin}/autocomplete.json?${o}`;return bl(await(await vn(e,s,n,{},Ec)).text())}catch(o){if(n.aborted)throw o}let r=gt.find((o)=>o.key==="yande"),i=new URLSearchParams({name:t,order:"count",limit:String(Mc)});return kl(await(await vn(r,`${r.origin}/tag.json?${i}`,n,{},Ec)).text())}async function qc(t,n,e){let r=await vn(t,n,e,{Range:`bytes=0-${hl}`});return Ee(new Uint8Array(await r.arrayBuffer()))}async function Xc(t,n,e,r){let i=await vn(t,n,e,{},0),o=Number(i.headers.get("content-length"))||0,s=i.body?.getReader();if(!s)return new Uint8Array(await i.arrayBuffer());let c=[],u=0;for(;;){let{done:a,value:g}=await s.read();if(a)break;c.push(g),u+=g.length,r?.(u,o)}let h=new Uint8Array(u),f=0;for(let a of c)h.set(a,f),f+=a.length;return h}var Ll="_defaults.toml",dn="_groups.toml",_c=3,Cc=["background","foreground","cursor","selection"],Pl=new Set(["next","help","preview","pin","unpin","config"]);function vt(t,n){throw Error(`${t}: ${n}`)}function Gn(t,n,e){if(typeof e!=="string"||!Jo(e))vt(t,`${n} must be "#rrggbb" (lowercase), got ${JSON.stringify(e)}`);return e}function _t(t,n,e){if(typeof e!=="string"||e.length===0)vt(t,`${n} must be a non-empty string`);return e}function mn(t){return t&&typeof t==="object"?t:{}}function Kl(t,n,e){let r={...mn(e),...mn(n)},i=r.codepoint_map??[];if(!Array.isArray(i))vt(t,"font.codepoint_map must be an array");return{family:_t(t,"font.family",r.family),size:Number(r.size),codepointMap:i.map((o)=>{let s=mn(o);return{range:_t(t,"font.codepoint_map[].range",s.range),family:_t(t,"font.codepoint_map[].family",s.family)}})}}function Jl(t,n,e){if(n===void 0)return[e.cursor,e.selectionBackground,e.background];let r=Array.isArray(n)?n:[n];if(r.length===0)vt(t,"ghostty.icon_screen must not be empty");return r.map((i,o)=>Gn(t,`ghostty.icon_screen[${o}]`,i))}function Al(t,n,e,r){let i={...mn(e),...mn(n)};return{shader:i.shader===void 0?void 0:_t(t,"ghostty.shader",i.shader),iconGhost:i.icon_ghost===void 0?r.cursor:Gn(t,"ghostty.icon_ghost",i.icon_ghost),iconScreen:Jl(t,i.icon_screen,r)}}function Ul(t){return new Map([...Cc.map((n)=>[n,t[n]]),...t.ansi.map((n,e)=>[`ansi${e}`,n])])}function Tl(t,n,e){if(!Array.isArray(n)||n.length!==_c)vt(t,`meta.signature must name exactly ${_c} palette slots`);let r=Ul(e),i=[],o=[];for(let[s,c]of n.entries()){let u=`meta.signature[${s}]`,h=_t(t,u,c),f=r.get(h);if(f===void 0)vt(t,`${u} ${JSON.stringify(c)} is not a palette slot — use ${Cc.join(", ")} or ansi0-ansi15`);i.push(h),o.push(f)}if(new Set(o).size!==o.length)vt(t,"meta.signature slots must resolve to three different colors");return{names:i,colors:o}}function Wl(t,n,e){if(n===void 0)return;if(!e)vt(t,"meta.booru_sites renames meta.booru per site, so it needs meta.booru");if(!n||typeof n!=="object"||Array.isArray(n))vt(t,'meta.booru_sites must be a table of site = "tag" or site = ["tag", ...]');let r={};for(let[i,o]of Object.entries(n)){let s=gt.find((u)=>u.key===i);if(!s)vt(t,`meta.booru_sites.${i} is not a find site — use ${gt.map((u)=>u.key).join(", ")}`);let c=typeof o==="string"?[o]:Array.isArray(o)?o:void 0;if(!c||c.some((u)=>typeof u!=="string"||u===""||/\s/.test(u)))vt(t,`meta.booru_sites.${i} must be one tag or a list of tags, got ${JSON.stringify(o)}`);if(c.length>1&&Number.isFinite(s.tagBudget))vt(t,`meta.booru_sites.${i} takes one tag — ${s.name} searches ${s.tagBudget} tags at a time`);r[i]=c}return r}function Ql(t){let e=Bun.TOML.parse(yi(Si(t,dn),"utf8")).group;if(!Array.isArray(e)||e.length===0)vt(dn,"needs at least one [[group]] table");return e.map((r)=>{let i=mn(r);return{name:_t(dn,"group.name",i.name),native:i.native===void 0?void 0:_t(dn,"group.native",i.native),lead:_t(dn,"group.lead",i.lead)}})}function Zl(t,n,e,r){let i=Bun.TOML.parse(n),o=mn(i.meta),s=mn(i.colors),c=mn(i.contrast),u=s.ansi;if(!Array.isArray(u)||u.length!==16)vt(t,`colors.ansi must hold exactly 16 colors, got ${Array.isArray(u)?u.length:typeof u}`);let h=_t(t,"meta.name",o.name);if(h!==Gl(t,".toml"))vt(t,`meta.name "${h}" does not match the filename`);if(Pl.has(h))vt(t,`meta.name "${h}" collides with a ttheme subcommand`);if(h.startsWith("-"))vt(t,`meta.name "${h}" would be read as a flag by the ttheme CLI`);let f=o.role;if(f!==void 0&&f!=="default")vt(t,`meta.role must be "default", got ${JSON.stringify(f)}`);let a=_t(t,"meta.group",o.group),g=r.get(a);if(!g)vt(t,`meta.group "${a}" has no [[group]] table in ${dn}`);let d=Gn(t,"colors.background",s.background),p=Gn(t,"colors.foreground",s.foreground),l=Gn(t,"colors.cursor",s.cursor),k=Gn(t,"colors.selection_background",s.selection_background),v=u.map((H,b)=>Gn(t,`colors.ansi[${b}]`,H)),I=Tl(t,o.signature,{background:d,foreground:p,cursor:l,selection:k,ansi:v}),E=o.booru===void 0?void 0:_t(t,"meta.booru",o.booru);if(E!==void 0&&/\s/.test(E))vt(t,`meta.booru must be a single booru tag, got ${JSON.stringify(E)}`);let y=Wl(t,o.booru_sites,E),$=Array.isArray(c.waive)?c.waive.map(String):[];if($.length>0&&typeof c.reason!=="string")vt(t,"contrast.waive needs a contrast.reason explaining why");return{name:h,group:a,native:g.native,lead:g.lead===h,order:Number(o.order),role:f,ansiSource:_t(t,"meta.ansi_source",o.ansi_source),...E?{booru:E}:{},...y?{booruSites:y}:{},background:d,foreground:p,cursor:l,selectionBackground:k,ansi:v,signature:I.colors,signatureSlots:I.names,font:Kl(t,i.font,e.font),ghostty:Al(t,i.ghostty,e.ghostty,{background:d,cursor:l,selectionBackground:k}),waive:$,waiveReason:typeof c.reason==="string"?c.reason:void 0}}function zc(t){let n=Bun.TOML.parse(yi(Si(t,Ll),"utf8")),e=Ql(t),r=new Map(e.map((s)=>[s.name,s]));if(r.size!==e.length)vt(dn,"group.name must be unique");let i=Rl(t).filter((s)=>s.endsWith(".toml")&&!s.startsWith("_")).map((s)=>Zl(s,yi(Si(t,s),"utf8"),n,r)).sort((s,c)=>s.order-c.order);if(new Set(i.map((s)=>s.order)).size!==i.length)throw Error("themes: meta.order must be unique across all themes");for(let s of e){let c=i.filter((u)=>u.group===s.name);if(c.length===0)vt(dn,`group "${s.name}" has no themes`);if(!c.some((u)=>u.name===s.lead))vt(dn,`group "${s.name}" lead "${s.lead}" is not one of its themes`)}return i}function Yc(t){return t.filter((n)=>n.role===void 0)}function He(t){let n=(e,r)=>e<r?-1:e>r?1:0;return[...t].sort((e,r)=>n(e.group.toLowerCase(),r.group.toLowerCase())||n(e.name,r.name))}var mr=["ghostty","kitty","alacritty","wezterm","iterm2","windows-terminal","warp"];var Fi=/# ttheme begin\n[\s\S]*?# ttheme end\n?/;function je(t,n){let e=`# ttheme begin
17
+ ${n}
17
18
  # ttheme end
18
- `;if(Ju.test(n))return n.replace(Ju,e);if(n==="")return e;return`${n.replace(/\n*$/,`
19
+ `;if(Fi.test(t))return t.replace(Fi,e);if(t==="")return e;return`${t.replace(/\n*$/,`
19
20
  `)}
20
- ${e}`}function fi(n){if(n.TERM_PROGRAM==="WarpTerminal")return"warp";if(n.GHOSTTY_RESOURCES_DIR||n.TERM_PROGRAM==="ghostty")return"ghostty";if(n.KITTY_WINDOW_ID)return"kitty";if(n.WEZTERM_PANE)return"wezterm";if(n.ALACRITTY_WINDOW_ID)return"alacritty";if(n.ITERM_SESSION_ID||n.TERM_PROGRAM==="iTerm.app")return"iterm2";if(n.TERM_PROGRAM==="Apple_Terminal")return"terminal-app";if(n.WT_SESSION&&!n.TERM_PROGRAM)return"windows-terminal";if(n.TERM?.startsWith("foot"))return"foot";return"unknown"}function Pu(n,r){let e=[`command = ${n}/launch-tab.zsh`,"shell-integration = zsh"];if(r)e.push(`theme = ${r}`);return e.push(`config-file = ${n}/ttheme.conf`,`config-file = ?${n}/backgrounds/shown.conf`),e.join(`
21
- `)}function Uu(n){return`source ${n}/ttheme.zsh`}var fa="# ttheme settings — uncomment a line to change it; exported variables win over this file",st={TTHEME_TAB_PALETTE:{doc:"# new tabs: off keeps the configured terminal theme, seq rotates through the palettes (default off)",default:"off"},TTHEME_ANNOUNCE:{doc:'# the palette notice under "Last login:": 1 shows it, 0 silences it (default 1)',default:"1"},TTHEME_FX:{doc:"# search hint animation: typewriter, decode or glitch (default typewriter)",default:"typewriter"},TTHEME_SORT:{doc:"# series and palettes in ttheme and preview: abc sorts them by name, series keeps the order they were added (default abc)",default:"abc"},TTHEME_FIND_RATING:{doc:"# the ratings find lists, any of safe, questionable and explicit, each booru read in its own rating vocabulary (default safe)",default:"safe"},TTHEME_FIND_BLOCK:{doc:'# the posts find drops by tag: nudity, underwear, both, or none to keep them all (default "nudity underwear")',default:"nudity underwear"},TTHEME_FIND_POSTS:{doc:"# what find lists first: all is every post of the character, cutouts are the transparent ones (default all)",default:"all"},TTHEME_FIND_SOLO:{doc:"# on keeps the danbooru posts tagged solo, the character alone; off lists every post (default on)",default:"on"},TTHEME_FIND_CUTOUTS:{doc:'# the tags find calls a transparent cutout, per site as key=tag,tag pairs — e.g. "konachan=transparent,vector yande=transparent_png" (default the built-in tags)',default:""},TTHEME_FIND_ORDER:{doc:"# the order find lists posts in: fit ranks each page by how well it makes a backdrop, newest or score (default fit)",default:"fit"},TTHEME_FIND_SETS:{doc:"# runs of the same picture at the same size from one uploader: fold shows them as one tile, show lists each (default fold)",default:"fold"},TTHEME_FIND_REMOVE_BG:{doc:"# an opaque picture tried on in find: on cuts the character out with macOS Vision, off leaves it as it is (default on)",default:"on"},TTHEME_FIND_UNBLOCK:{doc:"# when a network blocks a booru by name, 1 sends find through a local proxy that splits the TLS handshake — find offers to turn it on (default 0)",default:"0"},TTHEME_FIND_HOSTS:{doc:'# send a find site somewhere else, as key=https://host pairs — e.g. "danbooru=https://safebooru.donmai.us" (default none)',default:""}};function gi(n,r){let e=`: \${${n}:=${r}}`;return st[n]?.default===r?`# ${e}`:e}function Qu(n){return new RegExp(String.raw`^#? ?: \$\{${n}[^\n]*$`,"m")}function ga(n,r){if(Qu(r).test(n))return n;let e=st[r];return`${n.replace(/\n*$/,`
21
+ ${e}`}function pr(t){if(t.TERM_PROGRAM==="WarpTerminal")return"warp";if(t.GHOSTTY_RESOURCES_DIR||t.TERM_PROGRAM==="ghostty")return"ghostty";if(t.KITTY_WINDOW_ID)return"kitty";if(t.WEZTERM_PANE)return"wezterm";if(t.ALACRITTY_WINDOW_ID)return"alacritty";if(t.ITERM_SESSION_ID||t.TERM_PROGRAM==="iTerm.app")return"iterm2";if(t.TERM_PROGRAM==="Apple_Terminal")return"terminal-app";if(t.WT_SESSION&&!t.TERM_PROGRAM)return"windows-terminal";if(t.TERM?.startsWith("foot"))return"foot";return"unknown"}function Dc(t,n){let e=[`command = ${t}/launch-tab.zsh`,"shell-integration = zsh"];if(n)e.push(`theme = ${n}`);return e.push(`config-file = ${t}/ttheme.conf`,`config-file = ?${t}/backgrounds/shown.conf`),e.join(`
22
+ `)}function tu(t){return`source ${t}/ttheme.zsh`}var ql="# ttheme settings — uncomment a line to change it; exported variables win over this file",wr={TTHEME_TAB_PALETTE:{doc:"# new tabs: off keeps the configured terminal theme, seq rotates through the palettes (default off)",default:"off"},TTHEME_ANNOUNCE:{doc:'# the palette notice under "Last login:": 1 shows it, 0 silences it (default 1)',default:"1"},TTHEME_FX:{doc:"# search hint animation: typewriter, decode or glitch (default typewriter)",default:"typewriter"},TTHEME_SORT:{doc:"# series and palettes in ttheme and preview: abc sorts them by name, series keeps the order they were added (default abc)",default:"abc"},TTHEME_FIND_RATING:{doc:"# the ratings find lists, any of safe, questionable and explicit, each booru read in its own rating vocabulary (default safe)",default:"safe"},TTHEME_FIND_BLOCK:{doc:'# the posts find drops by tag: nudity, underwear, both, or none to keep them all (default "nudity underwear")',default:"nudity underwear"},TTHEME_FIND_POSTS:{doc:"# what find lists first: all is every post of the character, cutouts are the transparent ones (default all)",default:"all"},TTHEME_FIND_SOLO:{doc:"# on keeps the danbooru posts tagged solo, the character alone; off lists every post (default on)",default:"on"},TTHEME_FIND_CUTOUTS:{doc:'# the tags find calls a transparent cutout, per site as key=tag,tag pairs — e.g. "konachan=transparent,vector yande=transparent_png" (default the built-in tags)',default:""},TTHEME_FIND_ORDER:{doc:"# the order find lists posts in: fit ranks each page by how well it makes a backdrop, newest or score (default fit)",default:"fit"},TTHEME_FIND_SETS:{doc:"# runs of the same picture at the same size from one uploader: fold shows them as one tile, show lists each (default fold)",default:"fold"},TTHEME_FIND_REMOVE_BG:{doc:"# an opaque picture tried on in find: on cuts the character out with macOS Vision, off leaves it as it is (default on)",default:"on"},TTHEME_FIND_UNBLOCK:{doc:"# when a network blocks a booru by name, 1 sends find through a local proxy that splits the TLS handshake — find offers to turn it on (default 0)",default:"0"},TTHEME_FIND_HOSTS:{doc:'# send a find site somewhere else, as key=https://host pairs — e.g. "danbooru=https://safebooru.donmai.us" (default none)',default:""}};function Ii(t,n){let e=`: \${${t}:=${n}}`;return wr[t]?.default===n?`# ${e}`:e}function nu(t){return new RegExp(String.raw`^#? ?: \$\{${t}[^\n]*$`,"m")}function Xl(t,n){if(nu(n).test(t))return t;let e=wr[n];return`${t.replace(/\n*$/,`
22
23
  `)}
23
24
  ${e.doc}
24
- ${gi(r,e.default)}
25
- `}function li(){let n=Object.entries(st).map(([r,e])=>`${e.doc}
26
- ${gi(r,e.default)}`);return`${[fa,...n].join(`
25
+ ${Ii(n,e.default)}
26
+ `}function Ni(){let t=Object.entries(wr).map(([n,e])=>`${e.doc}
27
+ ${Ii(n,e.default)}`);return`${[ql,...t].join(`
27
28
 
28
29
  `)}
29
- `}function ut(n,r,e){let t=gi(r,e),i=Qu(r);if(i.test(n))return n.replace(i,t);return`${n.replace(/\n*$/,`
30
+ `}function eu(t,n,e){let r=Ii(n,e),i=nu(n);if(i.test(t))return t.replace(i,r);return`${t.replace(/\n*$/,`
30
31
  `)}
31
- ${t}
32
- `}function Wu(n){if(n==="")return li();return Object.keys(st).reduce(ga,n)}function Zu(n){return n?`include themes/${n}.conf`:""}function qu(n){return n?`[general]
33
- import = ["${n}"]`:""}var Ku=/-- ttheme begin\n[\s\S]*?-- ttheme end\n?/,la=/^return config[ \t]*$/gm;function Au(n){return`dofile(${JSON.stringify(n)})(config)`}function ct(n,r){let e=`-- ttheme begin
34
32
  ${r}
33
+ `}function ru(t){if(t==="")return Ni();return Object.keys(wr).reduce(Xl,t)}function iu(t,n){return[...t?[`include themes/${t}.conf`]:[],`watcher ${n}`,"window_logo_scale 100","window_logo_alpha 1"].join(`
34
+ `)}var _l=/^[ \t]*\[general\][ \t]*(?:#.*)?$/m,Vc=/^[ \t]*\[/m,xc=/^[ \t]*import[ \t]*=/m,Cl=/^[ \t]*general[ \t]*[.=]/m;function zl(t){return t?`[general]
35
+ import = ["${t}"]`:""}function $r(t,n){let e=t.replace(Fi,""),r=_l.exec(e);if(!r){let u=e.search(Vc),h=u<0?e:e.slice(0,u);if(Cl.test(e)||xc.test(h))return;return je(t,zl(n))}let i=r.index+r[0].length,o=e.slice(i),s=o.search(Vc);if(xc.test(s<0?o:o.slice(0,s)))return;let c=n?`import = ["${n}"]
36
+ `:"";return`${e.slice(0,i)}
37
+ # ttheme begin
38
+ ${c}# ttheme end${o}`}var Bc=/-- ttheme begin\n[\s\S]*?-- ttheme end\n?/,Yl=/^return config[ \t]*$/gm;function ou(t){return`dofile(${JSON.stringify(t)})(config)`}function br(t,n){let e=`-- ttheme begin
39
+ ${n}
35
40
  -- ttheme end
36
- `;if(Ku.test(n))return n.replace(Ku,e);if(n==="")return`local wezterm = require 'wezterm'
41
+ `;if(Bc.test(t))return t.replace(Bc,e);if(t==="")return`local wezterm = require 'wezterm'
37
42
  local config = wezterm.config_builder()
38
43
 
39
44
  ${e}
40
45
  return config
41
- `;let t=[...n.matchAll(la)].at(-1);if(t?.index===void 0)return;return`${n.slice(0,t.index)}${e}
42
- ${n.slice(t.index)}`}var Xu="[appearance.themes]";function Tu(n){let r=n.findIndex((t)=>t.trim()===Xu);if(r<0)return;let e=n.findIndex((t,i)=>i>r&&t.trimStart().startsWith("["));return[r,e<0?n.length:e]}function Vu(n){let r=n.split(`
43
- `),e=Tu(r);if(!e)return;return r.slice(e[0]+1,e[1]).find((i)=>/^theme\s*=/.test(i))?.replace(/^theme\s*=\s*/,"").trim()}function zu(n){return`{ custom = { name = "${n}", path = "ttheme-${n}.yaml" } }`}function Yu(n,r){let e=n.split(`
44
- `),t=Tu(e);if(!t)return r===void 0?n:`${n.replace(/\n*$/,`
46
+ `;let r=[...t.matchAll(Yl)].at(-1);if(r?.index===void 0)return;return`${t.slice(0,r.index)}${e}
47
+ ${t.slice(r.index)}`}var su="[appearance.themes]";function cu(t){let n=t.findIndex((r)=>r.trim()===su);if(n<0)return;let e=t.findIndex((r,i)=>i>n&&r.trimStart().startsWith("["));return[n,e<0?t.length:e]}function uu(t){let n=t.split(`
48
+ `),e=cu(n);if(!e)return;return n.slice(e[0]+1,e[1]).find((i)=>/^theme\s*=/.test(i))?.replace(/^theme\s*=\s*/,"").trim()}function hu(t){return`{ custom = { name = "${t}", path = "ttheme-${t}.yaml" } }`}function fu(t,n){let e=t.split(`
49
+ `),r=cu(e);if(!r)return n===void 0?t:`${t.replace(/\n*$/,`
45
50
  `)}
46
- ${Xu}
47
- theme = ${r}
48
- `;let i=e.findIndex((o,s)=>s>t[0]&&s<t[1]&&/^theme\s*=/.test(o));if(i>=0)e.splice(i,1,...r===void 0?[]:[`theme = ${r}`]);else if(r!==void 0)e.splice(t[0]+1,0,`theme = ${r}`);return e.join(`
49
- `)}function ai(n,r,e=[]){for(let u of n)for(let c of[u.name,u.group,u.native??"",u.ansiSource])if(/["$`\\]/.test(c))throw Error(`${u.name}: "${c}" contains a character that breaks zsh quoting`);let t=Math.max(0,...n.map((u)=>u.name.length)),i=(u,c)=>` ${u.name.padEnd(t)} "${c}"`,o=(u)=>u.map((c)=>c.name).join(" "),s=Ar(n);return["# Generated by `mise run build` — do not edit.","# Source of truth: themes/*.toml in the ttheme repo.","",`typeset -g TTHEME_VERSION=${rr.version}`,"",'# the palette new tabs open with, which the iTerm2 "ttheme · default" profile wears',`typeset -g TTHEME_STARTUP=${r??""}`,"","# the terminals ttheme is wired into: a picture change reaches every one of them, from whichever runs the shell",`typeset -ga TTHEME_TERMINALS=(${e.join(" ")})`,"","# seed for `ttheme config` when no config.zsh exists yet",`typeset -g TTHEME_CONFIG_TEMPLATE='${li().trimEnd().replaceAll("'","'\\''")}'`,"","typeset -gA TTHEME_PALETTE=(",...n.map((u)=>i(u,[u.background,u.foreground,u.cursor,u.selection,...u.ansi].join(" "))),")","","# series order: new tabs cycle through it and TTHEME_SORT=series lists it — the default role stays applyable but unlisted",`typeset -ga TTHEME_ORDER=(${o(s)})`,"","# the same palettes by series name, then palette name: TTHEME_SORT=abc lists them this way",`typeset -ga TTHEME_ABC=(${o(Ie(s))})`,"","typeset -gA TTHEME_GROUP=(",...n.map((u)=>i(u,u.group)),")","","# original-language title, rendered dim next to the group","typeset -gA TTHEME_NATIVE=(",...n.filter((u)=>u.native).map((u)=>i(u,u.native??"")),")","","# where each palette's 16 ANSI colors came from","typeset -gA TTHEME_SRC=(",...n.map((u)=>i(u,u.ansiSource)),")",""].join(`
50
- `)}var di={id:"shell",emitShared(n){return[{path:"shell/palettes.zsh",content:ai(n.map(ri))}]}};var aa=["black","red","green","yellow","blue","magenta","cyan","white"];function Cu(n,r){return[` ${n}:`,...aa.map((e,t)=>` ${e}: "${r[t]}"`)]}var Se={id:"warp",limits:"colors only — no selection color, and Warp paints one theme app-wide",emit(n){let r=[`name: "${n.name}"`,`background: "${n.background}"`,`foreground: "${n.foreground}"`,`accent: "${n.cursor}"`,`cursor: "${n.cursor}"`,`details: ${_n(n.background)<0.18?"darker":"lighter"}`,"terminal_colors:",...Cu("normal",n.ansi.slice(0,8)),...Cu("bright",n.ansi.slice(8,16)),""].join(`
51
- `);return[{path:`warp/themes/ttheme-${n.name}.yaml`,content:r}]}};var _u=(n)=>`[${n.map((r)=>`"${r}"`).join(", ")}]`,Ne={id:"wezterm",limits:"no shaders; OSC repaints per pane, pictures show per window",emit(n){let r=["[metadata]",`name = "${n.name}"`,`origin_url = "${n.ansiSource}"`,"","[colors]",`foreground = "${n.foreground}"`,`background = "${n.background}"`,`cursor_bg = "${n.cursor}"`,`cursor_border = "${n.cursor}"`,`cursor_fg = "${n.background}"`,`selection_bg = "${n.selectionBackground}"`,`selection_fg = "${n.foreground}"`,"",`ansi = ${_u(n.ansi.slice(0,8))}`,`brights = ${_u(n.ansi.slice(8,16))}`,""].join(`
52
- `),e=[`-- ${n.name} — font settings.`,"-- Merge into your wezterm.lua config table:",`-- local t = require("ttheme.${n.name}")`,`-- config.color_scheme = "${n.name}"`,"-- config.font = t.font","-- config.font_size = t.font_size","return {",` font = require("wezterm").font("${n.font.family}"),`,` font_size = ${n.font.size},`,"}",""].join(`
53
- `);return[{path:`wezterm/colors/${n.name}.toml`,content:r},{path:`wezterm/config/${n.name}.lua`,content:e}]}},Xr=(n)=>JSON.stringify(n);function Bu(n){return["-- Generated by ttheme — rewritten on every add, remove and default; do not edit.","local wezterm = require 'wezterm'","",`local MODULE = ${Xr(n.path)}`,`local COLORS = ${Xr(n.colors)}`,`local BACKGROUNDS = ${Xr(n.backgrounds)}`,`local STARTUP = ${n.startup?Xr(n.startup):"nil"}`,"local PALETTES = {",...n.palettes.map((r)=>` [${Xr(r.name)}] = ${Xr(r.background)},`),"}","","local X = { left = 'Left', center = 'Center', right = 'Right' }","local Y = { top = 'Top', center = 'Middle', bottom = 'Bottom' }","local SIZE = { cover = 'Cover', contain = 'Contain', stretch = '100%' }","","local function locate(path)"," if path:sub(1, 2) == '~/' then"," return os.getenv('HOME') .. path:sub(2)"," elseif path:sub(1, 1) == '/' or path:match('^%a:[/\\\\]') then"," return path"," end"," return BACKGROUNDS .. '/' .. path","end","","local function read(path, into)"," local f = io.open(path, 'r')"," if not f then"," return false"," end"," for line in f:lines() do"," local key, value = line:match('^%s*([%w%-]+)%s*=%s*(.-)%s*$')"," if key == 'config-file' then"," read(locate((value:gsub('^%?', ''))), into)"," elseif key then"," into[key] = value"," end"," end"," f:close()"," return true","end","","local function layers(palette)"," local color = PALETTES[palette]"," local c = {}"," if not color or not read(BACKGROUNDS .. '/' .. palette .. '.conf', c) then"," return nil, 'none'"," end"," local image = c['background-image'] or ''"," local opacity = tonumber(c['background-image-opacity'] or '1') or 1"," if image == '' or opacity <= 0 then"," return nil, 'none'"," end"," local fit = c['background-image-fit'] or 'contain'"," local position = c['background-image-position'] or 'center'"," local y, x = position:match('^(%a+)-(%a+)$')"," local rep = c['background-image-repeat'] == 'true' and 'Repeat' or 'NoRepeat'"," return {"," { source = { Color = color }, width = '100%', height = '100%' },"," {"," source = { File = locate(image) },"," opacity = opacity,"," width = SIZE[fit],"," height = SIZE[fit],"," horizontal_align = X[x or 'center'],"," vertical_align = Y[y or 'center'],"," repeat_x = rep,"," repeat_y = rep,"," },"," }, table.concat({ color, image, opacity, fit, position, rep }, '|')","end","","local shown = {}","","local function show(window, pane)"," local want = pane:get_user_vars().ttheme_shown"," if not want or want == '' then"," return"," end"," local background, key = layers(want)"," local id = window:window_id()"," if shown[id] == key then"," return"," end"," shown[id] = key"," local overrides = window:get_config_overrides() or {}"," overrides.background = background"," window:set_config_overrides(overrides)","end","","wezterm.on('user-var-changed', function(window, pane, name)"," if name == 'ttheme_shown' then"," show(window, pane)"," end","end)","wezterm.on('update-status', show)","","return function(config)"," local dirs = config.color_scheme_dirs or {}"," table.insert(dirs, COLORS)"," config.color_scheme_dirs = dirs"," if STARTUP then"," config.color_scheme = STARTUP"," end"," wezterm.add_to_config_reload_watch_list(MODULE)","end",""].join(`
54
- `)}var xu=["black","red","green","yellow","blue","purple","cyan","white"];function Du(n){return{name:n.name,background:n.background,foreground:n.foreground,cursorColor:n.cursor,selectionBackground:n.selectionBackground,...Object.fromEntries(xu.map((r,e)=>[r,n.ansi[e]])),...Object.fromEntries(xu.map((r,e)=>[`bright${r[0]?.toUpperCase()}${r.slice(1)}`,n.ansi[e+8]]))}}function mi(n,r,e){let t={...r&&e?{profiles:[{updates:r,colorScheme:e}]}:{},schemes:n.map(Du)};return`${JSON.stringify(t,null,2)}
55
- `}var He={id:"windows-terminal",limits:"colors only — no kitty graphics, so no pictures; OSC repaints per pane",emit(n){return[{path:`windows-terminal/schemes/${n.name}.json`,content:`${JSON.stringify(Du(n),null,2)}
56
- `}]},emitShared(n){return[{path:"windows-terminal/ttheme.json",content:mi(n)}]}};function Pr(n){return[`# ${n.name} — ${n.group}${n.native?` (${n.native})`:""}`,`# ANSI: ${n.ansiSource}`]}var rc=Oe(import.meta.dirname,".."),ma=Oe(rc,"themes"),$i=Oe(rc,"dist"),ht=[de,$e,ae,Ne,me,He,Se],$a=[di,ei],ec=ht.map((n)=>n.id);async function ft({only:n}={}){if(typeof Bun>"u")throw Error("ttheme build needs bun — run it from a checkout: bun src/bin.ts build");let r=n&&n.length>0?ht.filter((o)=>n.includes(o.id)):ht,e=Gu(ma),t=No(e);if(t.length>0){for(let o of t)console.error(` ✗ ${o.theme} [${o.rule}] ${o.detail}`);throw Error(`${t.length} contrast violation(s). Fix the palette, or waive the rule in its [contrast] section with a reason.`)}if(r.length===ht.length)nc($i,{recursive:!0,force:!0});else for(let o of r)nc(Oe($i,o.id),{recursive:!0,force:!0});let i=0;for(let o of[...r,...$a]){let s=e.flatMap((h)=>o.emit?.(h)??[]),u=o.emitShared?.(e)??[];for(let h of[...s,...u])await Bun.write(Oe($i,h.path),h.content),i++;let c=s.length>0?`${e.length} themes${o.limits?` (${o.limits})`:""}`:u.map((h)=>da(h.path)).join(" ");console.log(` ${o.id.padEnd(16)} ${c}`)}console.log(`
57
- ${e.length} themes (${Lu(e).length} in the new-tab rotation) -> ${i} files in dist/`)}import{spawn as nh}from"node:child_process";import{createHash as Nd}from"node:crypto";import{existsSync as xr,mkdirSync as Li,mkdtempSync as Hd,readFileSync as rh,rmSync as Hi,statSync as Od,writeFileSync as Ji}from"node:fs";import{tmpdir as jd}from"node:os";import{dirname as Vc,join as ar}from"node:path";import{existsSync as wa,mkdirSync as pa,readFileSync as ba,writeFileSync as ka}from"node:fs";import{dirname as Ma,join as Ea}from"node:path";var tc="https://kecan0406.github.io/ttheme/manifest.json",va=20000;function gt(n){return Ea(n,"ttheme","catalog.json")}function lt(n,r){let e=gt(n);pa(Ma(e),{recursive:!0}),ka(e,`${JSON.stringify(r,null,2)}
58
- `)}function Qn(n){let r=gt(n);if(!wa(r))throw Error(`no catalog at ${r} — run \`ttheme init\` first`);return ic(ba(r,"utf8"))}function ic(n){let r;try{r=JSON.parse(n)}catch{throw Error("catalog is not valid JSON")}let e=r;if(typeof e?.version!=="string"||!Array.isArray(e.palettes))throw Error("catalog has no version or palettes");for(let t of e.palettes)if(typeof t?.name!=="string"||!Array.isArray(t.ansi)||t.ansi.length!==16)throw Error(`catalog entry ${JSON.stringify(t?.name)} is missing name or its 16 ANSI colors`);return e}async function oc(n){let r;try{r=await fetch(n,{signal:AbortSignal.timeout(va)})}catch(e){throw Error(`cannot reach the registry at ${n} — ${e instanceof Error?e.message:String(e)}`)}if(!r.ok)throw Error(`registry at ${n} answered ${r.status}`);return ic(await r.text())}function sc(n){let r=new Set(n.waived??[]);return Ye.flatMap((e,t)=>{let i=n.gate?.[t];if(r.has(e.rule)||typeof i!=="number")return[];if(e.min!==void 0&&i<e.min)return[`${e.label} ${i} < ${e.min}`];if(e.max!==void 0&&i>e.max)return[`${e.label} ${i} > ${e.max}`];return[]})}function at(n,r){let e=n.find((t)=>t.name===r);if(!e)throw Error(`no palette named ${r} in the catalog — \`ttheme list\` shows what is there`);return e}function uc(n,r){let e=r.toLowerCase();return n.filter((t)=>[t.name,t.group,t.native??"",t.ansiSource].some((i)=>i.toLowerCase().includes(e)))}function cc(n,r,e){let t=e.toLowerCase(),i=(o)=>o.name===r.name?0:o.group===r.group?1:2;return n.filter((o)=>o.booru?.toLowerCase().includes(t)).map((o,s)=>({p:o,at:s})).sort((o,s)=>i(o.p)-i(s.p)||o.at-s.at).map(({p:o})=>o)}function hc(n,r){return n.booruSites?.[r]??(n.booru?[n.booru]:[])}import{spawn as Fa}from"node:child_process";var ya=30000,Ia=3,Sa=97,Na=`ObjC.import('Vision')
51
+ ${su}
52
+ theme = ${n}
53
+ `;let i=e.findIndex((o,s)=>s>r[0]&&s<r[1]&&/^theme\s*=/.test(o));if(i>=0)e.splice(i,1,...n===void 0?[]:[`theme = ${n}`]);else if(n!==void 0)e.splice(r[0]+1,0,`theme = ${n}`);return e.join(`
54
+ `)}function Oi(t,n,e=[]){for(let c of t)for(let u of[c.name,c.group,c.native??"",c.ansiSource])if(/["$`\\]/.test(u))throw Error(`${c.name}: "${u}" contains a character that breaks zsh quoting`);let r=Math.max(0,...t.map((c)=>c.name.length)),i=(c,u)=>` ${c.name.padEnd(r)} "${u}"`,o=(c)=>c.map((u)=>u.name).join(" "),s=qn(t);return["# Generated by `mise run build` — do not edit.","# Source of truth: themes/*.toml in the ttheme repo.","",`typeset -g TTHEME_VERSION=${en.version}`,"",'# the palette new tabs open with, which the iTerm2 "ttheme · default" profile wears',`typeset -g TTHEME_STARTUP=${n??""}`,"","# the terminals ttheme is wired into: a picture change reaches every one of them, from whichever runs the shell",`typeset -ga TTHEME_TERMINALS=(${e.join(" ")})`,"","# seed for `ttheme config` when no config.zsh exists yet",`typeset -g TTHEME_CONFIG_TEMPLATE='${Ni().trimEnd().replaceAll("'","'\\''")}'`,"","typeset -gA TTHEME_PALETTE=(",...t.map((c)=>i(c,[c.background,c.foreground,c.cursor,c.selection,...c.ansi].join(" "))),")","","# series order: new tabs cycle through it and TTHEME_SORT=series lists it — the default role stays applyable but unlisted",`typeset -ga TTHEME_ORDER=(${o(s)})`,"","# the same palettes by series name, then palette name: TTHEME_SORT=abc lists them this way",`typeset -ga TTHEME_ABC=(${o(He(s))})`,"","typeset -gA TTHEME_GROUP=(",...t.map((c)=>i(c,c.group)),")","","# original-language title, rendered dim next to the group","typeset -gA TTHEME_NATIVE=(",...t.filter((c)=>c.native).map((c)=>i(c,c.native??"")),")","","# where each palette's 16 ANSI colors came from","typeset -gA TTHEME_SRC=(",...t.map((c)=>i(c,c.ansiSource)),")",""].join(`
55
+ `)}var Hi={id:"shell",emitShared(t){return[{path:"shell/palettes.zsh",content:Oi(t.map(wi))}]}};var Vl=["black","red","green","yellow","blue","magenta","cyan","white"];function au(t,n){return[` ${t}:`,...Vl.map((e,r)=>` ${e}: "${n[r]}"`)]}var Re={id:"warp",limits:"colors only — no selection color, and Warp paints one theme app-wide",emit(t){let n=[`name: "${t.name}"`,`background: "${t.background}"`,`foreground: "${t.foreground}"`,`accent: "${t.cursor}"`,`cursor: "${t.cursor}"`,`details: ${Bt(t.background)<0.18?"darker":"lighter"}`,"terminal_colors:",...au("normal",t.ansi.slice(0,8)),...au("bright",t.ansi.slice(8,16)),""].join(`
56
+ `);return[{path:`warp/themes/ttheme-${t.name}.yaml`,content:n}]}};var gu=(t)=>`[${t.map((n)=>`"${n}"`).join(", ")}]`,Ge={id:"wezterm",limits:"no shaders; OSC repaints per pane, pictures show per window",emit(t){let n=["[metadata]",`name = "${t.name}"`,`origin_url = "${t.ansiSource}"`,"","[colors]",`foreground = "${t.foreground}"`,`background = "${t.background}"`,`cursor_bg = "${t.cursor}"`,`cursor_border = "${t.cursor}"`,`cursor_fg = "${t.background}"`,`selection_bg = "${t.selectionBackground}"`,`selection_fg = "${t.foreground}"`,"",`ansi = ${gu(t.ansi.slice(0,8))}`,`brights = ${gu(t.ansi.slice(8,16))}`,""].join(`
57
+ `),e=[`-- ${t.name} — font settings.`,"-- Merge into your wezterm.lua config table:",`-- local t = require("ttheme.${t.name}")`,`-- config.color_scheme = "${t.name}"`,"-- config.font = t.font","-- config.font_size = t.font_size","return {",` font = require("wezterm").font("${t.font.family}"),`,` font_size = ${t.font.size},`,"}",""].join(`
58
+ `);return[{path:`wezterm/colors/${t.name}.toml`,content:n},{path:`wezterm/config/${t.name}.lua`,content:e}]}},Xn=(t)=>JSON.stringify(t);function lu(t){return["-- Generated by ttheme — rewritten on every add, remove and default; do not edit.","local wezterm = require 'wezterm'","",`local MODULE = ${Xn(t.path)}`,`local COLORS = ${Xn(t.colors)}`,`local BACKGROUNDS = ${Xn(t.backgrounds)}`,`local STARTUP = ${t.startup?Xn(t.startup):"nil"}`,"local PALETTES = {",...t.palettes.map((n)=>` [${Xn(n.name)}] = ${Xn(n.background)},`),"}","","local X = { left = 'Left', center = 'Center', right = 'Right' }","local Y = { top = 'Top', center = 'Middle', bottom = 'Bottom' }","local SIZE = { cover = 'Cover', contain = 'Contain', stretch = '100%' }","","local function locate(path)"," if path:sub(1, 2) == '~/' then"," return os.getenv('HOME') .. path:sub(2)"," elseif path:sub(1, 1) == '/' or path:match('^%a:[/\\\\]') then"," return path"," end"," return BACKGROUNDS .. '/' .. path","end","","local function read(path, into)"," local f = io.open(path, 'r')"," if not f then"," return false"," end"," for line in f:lines() do"," local key, value = line:match('^%s*([%w%-]+)%s*=%s*(.-)%s*$')"," if key == 'config-file' then"," read(locate((value:gsub('^%?', ''))), into)"," elseif key then"," into[key] = value"," end"," end"," f:close()"," return true","end","","local function layers(palette)"," local color = PALETTES[palette]"," local c = {}"," if not color or not read(BACKGROUNDS .. '/' .. palette .. '.conf', c) then"," return nil, 'none'"," end"," local image = c['background-image'] or ''"," local opacity = tonumber(c['background-image-opacity'] or '1') or 1"," if image == '' or opacity <= 0 then"," return nil, 'none'"," end"," local fit = c['background-image-fit'] or 'contain'"," local position = c['background-image-position'] or 'center'"," local y, x = position:match('^(%a+)-(%a+)$')"," local rep = c['background-image-repeat'] == 'true' and 'Repeat' or 'NoRepeat'"," return {"," { source = { Color = color }, width = '100%', height = '100%' },"," {"," source = { File = locate(image) },"," opacity = opacity,"," width = SIZE[fit],"," height = SIZE[fit],"," horizontal_align = X[x or 'center'],"," vertical_align = Y[y or 'center'],"," repeat_x = rep,"," repeat_y = rep,"," },"," }, table.concat({ color, image, opacity, fit, position, rep }, '|')","end","","local shown = {}","","local function show(window, pane)"," local want = pane:get_user_vars().ttheme_shown"," if not want or want == '' then"," return"," end"," local background, key = layers(want)"," local id = window:window_id()"," if shown[id] == key then"," return"," end"," shown[id] = key"," local overrides = window:get_config_overrides() or {}"," overrides.background = background"," window:set_config_overrides(overrides)","end","","wezterm.on('user-var-changed', function(window, pane, name)"," if name == 'ttheme_shown' then"," show(window, pane)"," end","end)","wezterm.on('update-status', show)","","return function(config)"," local dirs = config.color_scheme_dirs or {}"," table.insert(dirs, COLORS)"," config.color_scheme_dirs = dirs"," if STARTUP then"," config.color_scheme = STARTUP"," end"," wezterm.add_to_config_reload_watch_list(MODULE)","end",""].join(`
59
+ `)}var du=["black","red","green","yellow","blue","purple","cyan","white"];function mu(t){return{name:t.name,background:t.background,foreground:t.foreground,cursorColor:t.cursor,selectionBackground:t.selectionBackground,...Object.fromEntries(du.map((n,e)=>[n,t.ansi[e]])),...Object.fromEntries(du.map((n,e)=>[`bright${n[0]?.toUpperCase()}${n.slice(1)}`,t.ansi[e+8]]))}}function ji(t,n,e){let r={...n&&e?{profiles:[{updates:n,colorScheme:e}]}:{},schemes:t.map(mu)};return`${JSON.stringify(r,null,2)}
60
+ `}var Le={id:"windows-terminal",limits:"colors only — no kitty graphics, so no pictures; OSC repaints per pane",emit(t){return[{path:`windows-terminal/schemes/${t.name}.json`,content:`${JSON.stringify(mu(t),null,2)}
61
+ `}]},emitShared(t){return[{path:"windows-terminal/ttheme.json",content:ji(t)}]}};function An(t){return[`# ${t.name} — ${t.group}${t.native?` (${t.native})`:""}`,`# ANSI: ${t.ansiSource}`]}var wu=Pe(import.meta.dirname,".."),Bl=Pe(wu,"themes"),Ri=Pe(wu,"dist"),kr=[pe,$e,me,Ge,we,Le,Re],Dl=[Hi,$i],$u=kr.map((t)=>t.id);async function Er({only:t}={}){if(typeof Bun>"u")throw Error("ttheme build needs bun — run it from a checkout: bun src/bin.ts build");let n=t&&t.length>0?kr.filter((o)=>t.includes(o.id)):kr,e=zc(Bl),r=qo(e);if(r.length>0){for(let o of r)console.error(` ✗ ${o.theme} [${o.rule}] ${o.detail}`);throw Error(`${r.length} contrast violation(s). Fix the palette, or waive the rule in its [contrast] section with a reason.`)}if(n.length===kr.length)pu(Ri,{recursive:!0,force:!0});else for(let o of n)pu(Pe(Ri,o.id),{recursive:!0,force:!0});let i=0;for(let o of[...n,...Dl]){let s=e.flatMap((h)=>o.emit?.(h)??[]),c=o.emitShared?.(e)??[];for(let h of[...s,...c])await Bun.write(Pe(Ri,h.path),h.content),i++;let u=s.length>0?`${e.length} themes${o.limits?` (${o.limits})`:""}`:c.map((h)=>xl(h.path)).join(" ");console.log(` ${o.id.padEnd(16)} ${u}`)}console.log(`
62
+ ${e.length} themes (${Yc(e).length} in the new-tab rotation) -> ${i} files in dist/`)}import{spawn as Rh}from"node:child_process";import{createHash as Gh}from"node:crypto";import{existsSync as xn,mkdirSync as _e,mkdtempSync as Hm,readFileSync as Lh,rmSync as xi,statSync as jm,writeFileSync as Ce}from"node:fs";import{tmpdir as Rm}from"node:os";import{dirname as Jr,join as fn}from"node:path";import{pathToFileURL as Gm}from"node:url";import{execFile as td}from"node:child_process";import{createHash as Mu}from"node:crypto";import{existsSync as nd,mkdtempSync as ed,readFileSync as Sr,rmSync as rd,statSync as vu,writeFileSync as yu}from"node:fs";import{homedir as id,tmpdir as od}from"node:os";import{join as Mr}from"node:path";import{fileURLToPath as sd}from"node:url";import{promisify as cd}from"node:util";var sn=cd(td),vr=67108864,ud=4096,Pi=["image/png","image/jpeg","image/webp","image/gif","image/tiff","image/heic"],hd=["text/uri-list","text/plain;charset=utf-8","text/plain"],Gi=[...Pi,"text/uri-list","text/plain"];function fd(t){try{return vu(t).isFile()}catch{return!1}}function ad(t){let n=[],e="",r="",i=!1;for(let o=0;o<t.length;o++){let s=t[o];if(r==="'")if(s==="'")r="";else e+=s;else if(r==='"')if(s==='"')r="";else if(s==="\\"&&'"\\$`'.includes(t[o+1]??""))e+=t[++o];else e+=s;else if(s==="\\"&&o+1<t.length)e+=t[++o],i=!0;else if(s==="'"||s==='"')r=s,i=!0;else if(/\s/.test(s)){if(i)n.push(e);e="",i=!1}else e+=s,i=!0}if(i)n.push(e);return n}function bu(t){if(/^file:\/\//i.test(t))try{return sd(t)}catch{return}if(t.startsWith("~/"))return Mr(id(),t.slice(2));return t.startsWith("/")?t:void 0}function Fr(t,n=fd){let e=[];for(let r of t.replace(/\r\n?/g,`
63
+ `).split(`
64
+ `)){let i=bu(r.trim());if(i&&n(i)){e.push(i);continue}for(let o of ad(r)){if(/^https?:\/\/\S+$/i.test(o)){e.push(o);continue}let s=bu(o);if(s&&n(s))e.push(s)}}return e}function gd(t){if(t[0]!==255||t[1]!==216)return null;let n=2;while(n+9<t.length){if(t[n]!==255){n++;continue}let e=t[n+1];if(e===255){n++;continue}let r=t[n+2]<<8|t[n+3];if(e>=192&&e<=207&&e!==196&&e!==200&&e!==204)return{height:t[n+5]<<8|t[n+6],width:t[n+7]<<8|t[n+8]};n+=2+r}return null}function ku(t){let n=ke(t)?Ee(t):gd(t);if(!n)return;return{ext:ke(t)?"png":"jpg",width:n.width,height:n.height}}async function yr(t,n){let e=ku(t);if(e&&e.width*e.height<=Rn)return{bytes:t,...e,source:n};if(process.platform!=="darwin")throw Error(e?`${e.width}×${e.height} is over ${Rn/1e6} megapixels`:"only PNG and JPEG pictures work here");let r=ed(Mr(od(),"ttheme-attach-"));try{let i=Mr(r,"in"),o=Mr(r,"out.png");yu(i,t);let s=!e||e.width*e.height>Rn?["--resampleHeightWidthMax",String(ud)]:[];await sn("sips",["-s","format","png",...s,i,"--out",o]).catch(()=>{throw Error("that is not a picture macOS can read")});let c=new Uint8Array(Sr(o)),u=ku(c);if(!u)throw Error("that is not a picture macOS can read");return{bytes:c,...u,source:n}}finally{rd(r,{recursive:!0,force:!0})}}async function Ki(t,n){if(/^https?:\/\//i.test(t)){let e=await fetch(t,{headers:{"User-Agent":ki},signal:n});if(!e.ok)throw Error(`${new URL(t).host} answered ${e.status}`);if(Number(e.headers.get("content-length")??0)>vr)throw Error("that picture is over 64 MB");let r=new Uint8Array(await e.arrayBuffer());if(/^text\/html/i.test(e.headers.get("content-type")??""))throw Error(`${new URL(t).host} sent a web page, not a picture — copy the image address instead`);return yr(r,t)}if(vu(t).size>vr)throw Error("that picture is over 64 MB");return yr(new Uint8Array(Sr(t)),t)}var Su=new Map,Ir={key:"local",name:"local",origin:"file://",moved:!1,cutouts:"",best:"",tagBudget:0,vouched:!0,tunneled:!1,ansi:7,ratings:{safe:new Set,questionable:new Set,explicit:new Set},rate:()=>"",postsUrl:()=>"",countUrl:()=>"",postUrl:()=>"",pageUrl:(t)=>Su.get(t)??"",parse:()=>[],count:()=>0};function Fu(t){if(/^https?:\/\//i.test(t))return"";return t.split("/").pop()??t}function Iu(t,n){Su.set(t,n)}function Nu(t){return Number.parseInt(Mu("sha1").update(t).digest("hex").slice(0,8),16)%ln}var ld=`ObjC.import('AppKit')
65
+ function run(argv) {
66
+ const pb = $.NSPasteboard.generalPasteboard
67
+ const files = pb.readObjectsForClassesOptions($([$.NSURL]), $({ NSPasteboardURLReadingFileURLsOnlyKey: true }))
68
+ if (files && files.count > 0) {
69
+ const out = []
70
+ for (let i = 0; i < files.count; i++) out.push(files.objectAtIndex(i).path.js)
71
+ return out.join('\\n')
72
+ }
73
+ for (const type of ['public.png', 'public.tiff', 'public.jpeg', 'public.heic']) {
74
+ const data = pb.dataForType(type)
75
+ if (!data || data.isNil()) continue
76
+ if (type === 'public.png') {
77
+ data.writeToFileAtomically(argv[0], true)
78
+ return argv[0]
79
+ }
80
+ const rep = $.NSBitmapImageRep.imageRepWithData(data)
81
+ if (rep.isNil()) continue
82
+ rep.representationUsingTypeProperties($.NSBitmapImageFileTypePNG, $({})).writeToFileAtomically(argv[0], true)
83
+ return argv[0]
84
+ }
85
+ const web = pb.readObjectsForClassesOptions($([$.NSURL]), $({}))
86
+ if (web && web.count > 0) return web.objectAtIndex(0).absoluteString.js
87
+ const text = pb.stringForType('public.utf8-plain-text')
88
+ return text && !text.isNil() ? text.js : ''
89
+ }`,dd=`Add-Type -AssemblyName System.Windows.Forms,System.Drawing
90
+ $c = [Windows.Forms.Clipboard]
91
+ $f = $c::GetFileDropList(); if ($f.Count) { $f; exit }
92
+ $p = Join-Path $env:TEMP 'ttheme-clipboard.png'
93
+ $s = $c::GetData('PNG'); if ($s -is [IO.MemoryStream]) { [IO.File]::WriteAllBytes($p, $s.ToArray()); $p; exit }
94
+ $i = $c::GetImage(); if ($i) { $i.Save($p, [Drawing.Imaging.ImageFormat]::Png); $p; exit }
95
+ $c::GetText()`;function Ou(){if(process.platform!=="linux")return!1;try{return/microsoft/i.test(Sr("/proc/version","utf8"))}catch{return!1}}async function md(t){let n=Boolean(process.env.WAYLAND_DISPLAY),e=n?["wl-paste",["--list-types"]]:["xclip",["-selection","clipboard","-t","TARGETS","-o"]],r=(await sn(e[0],e[1])).stdout.split(`
96
+ `).map((s)=>s.trim()),i=(s)=>n?sn("wl-paste",["--no-newline","--type",s],{encoding:"buffer",maxBuffer:vr}):sn("xclip",["-selection","clipboard","-t",s,"-o"],{encoding:"buffer",maxBuffer:vr});if(r.includes("text/uri-list"))return{text:(await i("text/uri-list")).stdout.toString("utf8")};let o=Pi.find((s)=>r.includes(s));if(o)return yu(t,(await i(o)).stdout),{image:t};return{text:r.some((s)=>s.startsWith("text/plain")||s==="UTF8_STRING")?(await i(r.includes("text/plain")?"text/plain":"UTF8_STRING")).stdout.toString("utf8"):""}}function Ji(){return Boolean(process.env.SSH_CONNECTION||process.env.SSH_TTY)}async function Hu(t){if(process.platform==="darwin"){let n=(await sn("osascript",["-l","JavaScript","-e",ld,t])).stdout.trim();return n===t?{image:t}:{text:n}}if(Ou()){let n=(await sn("powershell.exe",["-NoProfile","-STA","-Command",dd])).stdout.replace(/\r/g,"").trim(),e=await Promise.all(n.split(`
97
+ `).map(async(r)=>/^[A-Za-z]:\\/.test(r)?(await sn("wslpath",["-u",r])).stdout.trim():r));return e.length===1&&/ttheme-clipboard\.png$/.test(e[0]??"")?{image:e[0]}:{text:e.join(`
98
+ `)}}if(process.platform==="linux")return md(t);throw Error(`reading the clipboard is not supported on ${process.platform}`)}var pd=`ObjC.import('AppKit')
99
+ function run() {
100
+ const pb = $.NSPasteboard.generalPasteboard
101
+ const files = pb.readObjectsForClassesOptions($([$.NSURL]), $({ NSPasteboardURLReadingFileURLsOnlyKey: true }))
102
+ let picture = false
103
+ if (files && files.count > 0) {
104
+ for (let i = 0; i < files.count; i++) picture ||= /\\.(png|jpe?g|gif|webp|heic|tiff?|bmp)$/i.test(files.objectAtIndex(i).path.js)
105
+ } else {
106
+ const types = pb.types.js.map((t) => t.js)
107
+ picture = ['public.png', 'public.tiff', 'public.jpeg', 'public.heic'].some((t) => types.includes(t))
108
+ }
109
+ return pb.changeCount + '\\t' + (picture ? 'picture' : '')
110
+ }`;async function ju(){if(Ji())return;if(process.platform==="darwin"){let[t="",n=""]=(await sn("osascript",["-l","JavaScript","-e",pd])).stdout.trim().split("\t");return{stamp:t,picture:n==="picture"}}if(process.platform==="linux"&&!Ou()){let n=Boolean(process.env.WAYLAND_DISPLAY)?(await sn("wl-paste",["--list-types"])).stdout:(await sn("xclip",["-selection","clipboard","-t","TARGETS","-o"])).stdout;return{stamp:n,picture:/^image\//m.test(n)}}return}function Ru(t){let n=[],e="",r=0;while(r<t.length){if(t[r]!=="\x1B"){e+=t[r],r++;continue}if(t.startsWith("\x1B[200~",r)){let o=t.indexOf("\x1B[201~",r+6);if(o===-1)return{events:n,keys:e,pending:t.slice(r)};n.push({kind:"paste",text:t.slice(r+6,o)}),r=o+6;continue}if(t.startsWith("\x1B]5522;",r)||t.startsWith("\x1B]72;",r)){let o=[t.indexOf("\x1B\\",r),t.indexOf("\x07",r)].filter((a)=>a!==-1);if(o.length===0)return{events:n,keys:e,pending:t.slice(r)};let s=Math.min(...o),c=t.slice(r+2,s),[u="",h="",...f]=c.split(";");n.push({kind:"osc",code:u,meta:wd(h),payload:f.join(";")}),r=s+(t[s]==="\x07"?1:2);continue}let i=/^\[\?([\d;]*)(\$y|c)/.exec(t.slice(r+1,r+64));if(i){if(i[2]==="c")n.push({kind:"attributes"});else{let[o="0",s="0"]=(i[1]??"").split(";");n.push({kind:"mode",mode:Number(o),value:Number(s)})}r+=1+i[0].length;continue}if(/^(?:\[(?:\?[\d;$]*|2|20|200|201)?|\](?:5|55|552|5522|7|72)?)$/.test(t.slice(r+1)))return{events:n,keys:e,pending:t.slice(r)};e+=t[r],r++}return{events:n,keys:e,pending:""}}function wd(t){let n={};for(let e of t.split(":")){let r=e.indexOf("=");if(r>0)n[e.slice(0,r)]=e.slice(r+1)}return n}var Ke=(t)=>Buffer.from(t).toString("base64"),Li=(t)=>Buffer.from(t,"base64");function Eu(t,n){return n.find((e)=>t.includes(e))}class Ai{clipboard=!1;drops=!1;reading;offered=[];dropping;pw=Ke(Mu("sha1").update(`${process.pid}:${Date.now()}`).digest("hex"));send;deliver;constructor(t,n){this.send=t,this.deliver=n}start(){let t="\x1B[?2004h";if(this.clipboard)t+="\x1B[?5522h";if(this.drops)t+=`\x1B]72;t=a;${Gi.join(" ")}\x1B\\`;this.send(t)}stop(){this.send(`\x1B[?2004l${this.clipboard?"\x1B[?5522l":""}${this.drops?"\x1B]72;t=A\x1B\\":""}`)}ask(){this.reading={mime:".",chunks:[],pw:"",listing:!0},this.send(`\x1B]5522;type=read:name=${Ke("ttheme")}:pw=${this.pw};${Ke(".")}\x1B\\`)}take(t){if(t.code==="5522")this.clip(t.meta,t.payload);else if(t.code==="72")this.drop(t.meta,t.payload)}clip(t,n){if(t.type!=="read")return;let e=t.status??"";if(e==="OK"){if(this.reading??={mime:".",chunks:[],pw:t.pw??"",listing:!0},t.pw)this.reading.pw=t.pw;return}let r=this.reading;if(!r)return;if(e==="DATA"){if(r.mime=t.mime?Li(t.mime).toString("utf8"):r.mime,n)r.chunks.push(Li(n));return}if(this.reading=void 0,e!=="DONE"){this.deliver({kind:"error",message:e==="EPERM"?"the clipboard read was not allowed":`the terminal answered ${e}`});return}let i=Buffer.concat(r.chunks);if(r.listing){let o=i.toString("utf8").split(/\s+/).filter(Boolean),s=Eu(o,[...Pi,...hd]);if(!s){this.deliver({kind:"text",text:""});return}let c=r.pw||this.pw,u=r.pw?"Paste event":"ttheme";this.reading={mime:s,chunks:[],pw:c,listing:!1},this.send(`\x1B]5522;type=read:name=${Ke(u)}:pw=${c};${Ke(s)}\x1B\\`);return}this.deliver(r.mime.startsWith("image/")?{kind:"bytes",bytes:new Uint8Array(i),source:"clipboard"}:{kind:"text",text:i.toString("utf8")})}drop(t,n){let e=t.t??"";if(e==="m"){if(t.x==="-1"){this.offered=[];return}if(n){this.offered=n.split(" ").filter(Boolean);let c=Gi.filter((u)=>this.offered.includes(u));this.send(`\x1B]72;t=m:o=${c.length>0?1:0};${c.join(" ")}\x1B\\`)}return}if(e==="M"){let c=n?n.split(" ").filter(Boolean):this.offered,u=Eu(c,Gi);if(!u){this.send("\x1B]72;t=r:o=0\x1B\\");return}this.dropping={mimes:c,index:c.indexOf(u)+1,chunks:[]},this.send(`\x1B]72;t=r:x=${this.dropping.index}\x1B\\`);return}let r=this.dropping;if(!r)return;if(e==="R"){this.dropping=void 0,this.send("\x1B]72;t=r:o=0\x1B\\"),this.deliver({kind:"error",message:`the drop failed: ${n.split(":")[0]||"unknown error"}`});return}if(e!=="r"&&e!=="")return;if(n)r.chunks.push(Li(n));if(t.m==="1"||n)return;this.dropping=void 0;let i=Buffer.concat(r.chunks),o=r.mimes[r.index-1]??"",s;if(o.startsWith("image/"))s={kind:"bytes",bytes:new Uint8Array(i),source:"drop"};else{let c=i.toString("utf8"),u=o==="text/uri-list"?Fr(c).find((h)=>nd(h)):void 0;s=u?{kind:"bytes",bytes:new Uint8Array(Sr(u)),source:u}:{kind:"text",text:c}}this.send("\x1B]72;t=r:o=1\x1B\\"),this.deliver(s)}}import{existsSync as $d,mkdirSync as bd,readFileSync as kd,writeFileSync as Ed}from"node:fs";import{dirname as Md,join as vd}from"node:path";var Gu="https://kecan0406.github.io/ttheme/manifest.json",yd=20000;function Nr(t){return vd(t,"ttheme","catalog.json")}function Or(t,n){let e=Nr(t);bd(Md(e),{recursive:!0}),Ed(e,`${JSON.stringify(n,null,2)}
111
+ `)}function Pt(t){let n=Nr(t);if(!$d(n))throw Error(`no catalog at ${n} — run \`ttheme init\` first`);return Lu(kd(n,"utf8"))}function Lu(t){let n;try{n=JSON.parse(t)}catch{throw Error("catalog is not valid JSON")}let e=n;if(typeof e?.version!=="string"||!Array.isArray(e.palettes))throw Error("catalog has no version or palettes");for(let r of e.palettes)if(typeof r?.name!=="string"||!Array.isArray(r.ansi)||r.ansi.length!==16)throw Error(`catalog entry ${JSON.stringify(r?.name)} is missing name or its 16 ANSI colors`);return e}async function Pu(t){let n;try{n=await fetch(t,{signal:AbortSignal.timeout(yd)})}catch(e){throw Error(`cannot reach the registry at ${t} — ${e instanceof Error?e.message:String(e)}`)}if(!n.ok)throw Error(`registry at ${t} answered ${n.status}`);return Lu(await n.text())}function Ku(t){let n=new Set(t.waived??[]);return ir.flatMap((e,r)=>{let i=t.gate?.[r];if(n.has(e.rule)||typeof i!=="number")return[];if(e.min!==void 0&&i<e.min)return[`${e.label} ${i} < ${e.min}`];if(e.max!==void 0&&i>e.max)return[`${e.label} ${i} > ${e.max}`];return[]})}function Hr(t,n){let e=t.find((r)=>r.name===n);if(!e)throw Error(`no palette named ${n} in the catalog — \`ttheme list\` shows what is there`);return e}function Ju(t,n){let e=n.toLowerCase();return t.filter((r)=>[r.name,r.group,r.native??"",r.ansiSource].some((i)=>i.toLowerCase().includes(e)))}function Au(t,n,e){let r=e.toLowerCase(),i=(o)=>o.name===n.name?0:o.group===n.group?1:2;return t.filter((o)=>o.booru?.toLowerCase().includes(r)).map((o,s)=>({p:o,at:s})).sort((o,s)=>i(o.p)-i(s.p)||o.at-s.at).map(({p:o})=>o)}function Uu(t,n){return t.booruSites?.[n]??(t.booru?[t.booru]:[])}import{spawn as Sd}from"node:child_process";var Fd=30000,Id=3,Nd=97,Od=`ObjC.import('Vision')
59
112
  ObjC.import('CoreImage')
60
113
  ObjC.import('CoreGraphics')
61
114
  function run(argv) {
@@ -74,104 +127,94 @@ function run(argv) {
74
127
  $.CIImage.imageWithCVPixelBuffer(buffer), $.NSURL.fileURLWithPath(argv[1]), $.kCIFormatRGBA8,
75
128
  $.CGColorSpaceCreateWithName($.kCGColorSpaceSRGB), $({}), error)
76
129
  if (!written) throw new Error('write failed')
77
- }`;function wi(){return process.platform==="darwin"}function fc(n){return n>=Ia&&n<=Sa}function gc(n,r,e){return new Promise((t,i)=>{let o=Fa("osascript",["-l","JavaScript","-e",Na,n,r],{stdio:["ignore","ignore","pipe"],signal:AbortSignal.any([e,AbortSignal.timeout(ya)])}),s="";o.stderr.on("data",(u)=>{s+=u}),o.on("error",i),o.on("close",(u)=>{if(u===0){t();return}i(Error(s.trim().split(`
78
- `).at(-1)||`osascript exited ${u}`))})})}var Un={pitch:25,cols:22,rows:9,height:13},Rr={cols:25,rows:16},Ha=2147483648,Oa=-1073741826,ja=1600,Ra="\x1B[0m",ir="\x1B[1m",cn="\x1B[2m",je="\x1B[31m",gr="\x1B[32m",Wn="\x1B[33m",dt="\x1B[1;34m",Ga="\x1B[35m",La={A:"up",B:"down",C:"right",D:"left",H:"home",F:"end","1~":"home","7~":"home","4~":"end","8~":"end","5~":"pgup","6~":"pgdn"};function dc(n){let r=[],e=0;while(e<n.length){let t=n[e]??"";if(t==="\x1B"){let i=/^(?:\[([0-9;]*)([A-Za-z~])|O([A-Za-z]))/.exec(n.slice(e+1));if(i){r.push(La[`${i[1]??""}${i[2]??i[3]??""}`]??"nop"),e+=1+i[0].length;continue}r.push("esc"),e++;continue}r.push(t==="\r"||t===`
79
- `?"enter":t==="\t"?"tab":t==="\x03"?"ctrl-c":t===""||t==="\b"?"backspace":t),e++}return r}var mc="\x1B]1337;ReportCellSize\x07\x1B[16t",lc="\x1B]1337;ReportCellSize=";function ki(n){let r=n.indexOf(lc);if(r!==-1){let i=n.slice(r+lc.length),o=[i.indexOf("\x07"),i.indexOf("\x1B\\")].filter((c)=>c!==-1),s=o.length>0?Math.min(...o):-1,u=s===-1?null:/^([\d.]+);([\d.]+);([\d.]+)$/.exec(i.slice(0,s));if(u){let c=Number(u[3]);return{cell:{h:Math.round(Number(u[1])*c),w:Math.round(Number(u[2])*c)},rest:n.slice(0,r)+i.slice(s+(i[s]==="\x07"?1:2))}}}let e=n.indexOf("\x1B[6;"),t=e===-1?null:/^\[6;(\d+);(\d+)t/.exec(n.slice(e+1));if(!t)return null;return{cell:{h:Number(t[1]),w:Number(t[2])},rest:n.slice(0,e)+n.slice(e+1+t[0].length)}}function Tr(n,r){return{perRow:Math.max(1,Math.floor((n+1)/Un.pitch)),rowsVis:Math.max(1,Math.floor((r-4)/Un.height))}}function $c(n){return`\x1B_Ga=t,t=f,f=100,i=${n.id},q=2;${Buffer.from(n.path).toString("base64")}\x1B\\`}function wc(n){return`\x1B[${n.row+1};${n.col+1}H\x1B_Ga=p,i=${n.id},p=${n.id},c=${n.cols},r=${n.rows},C=1,z=${n.z},q=2\x1B\\`}function pc(n){return`\x1B_Ga=d,d=I,i=${n},q=2\x1B\\`}function bc(n){return`\x1B[38;2;${Gn(n).join(";")}m`}function pi(n){return`\x1B[48;2;${Gn(n).join(";")}m`}function zn(n){return Array.from(n).length}class mt{parts=[];cols;constructor(n){this.cols=n}put(n,r,e=""){return this.parts.push({col:n,text:r,sgr:e}),n+zn(r)}run(n,r){let e=n;for(let[t,i]of r)e=this.put(e,t,i);return e}right(n,r){this.run(n-r.reduce((e,[t])=>e+zn(t),0),r)}render(){let n="";for(let{col:r,text:e,sgr:t}of this.parts){if(r>=this.cols||r<0)continue;let i=Array.from(e).slice(0,this.cols-r).join("");n+=`\x1B[${r+1}G${t}${i}${t?Ra:""}`}return n}}function kc(n){return n>=1e6?`${(n/1e6).toFixed(1)} MB`:`${Math.max(1,Math.round(n/1000))} KB`}function Ja(n,r){if(!r)return kc(n);return r>=1e6?`${(n/1e6).toFixed(1)}/${(r/1e6).toFixed(1)} MB`:`${Math.round(n/1000)}/${Math.round(r/1000)} KB`}function Mc(n){return n.replace(/_\([^)]*\)?$/,"")}function Ec(n){return[`${n.reduced?"↓":""}${n.width}×${n.height}`,Math.max(n.width,n.height)<ja?Wn:cn]}function Re(n,r,e,t){let i=[...t.keys??[]],o=t.lead,s=t.right,u=()=>{let f=[...o?[zn(o[0])]:[],...i.map(([g,d])=>zn(g)+1+zn(d))];return(t.badge?zn(t.badge)+4:0)+f.reduce((g,d)=>g+d,0)+3*Math.max(0,f.length-1)+(s?3+zn(s[0])+1+zn(s[1]):0)};while(u()>r)if(i.length>2)i.splice(-2,1);else if(s)s=void 0;else if(i.length>1)i.splice(-2,1);else break;if(o&&u()>r){let f=Math.max(0,zn(o[0])-(u()-r)-1);o=[`${Array.from(o[0]).slice(0,f).join("")}…`,o[1]]}let c=0;if(t.badge)c=n.put(0,` ${t.badge} `,`\x1B[7;1m${e}`)+2;if([...o?[[o]]:[],...i.map(([f,l])=>[[f,ir],[` ${l}`,cn]])].forEach((f,l)=>{c=n.run(c+(l?3:0),f)}),s)n.right(r,[[s[0],ir],[` ${s[1]}`,cn]])}function Ka(n,r,e,t,i,o){let{ansi:s,selection:u,cursor:c}=o.colors,h=t<44?3:4;if(t>=56)h=Math.min(7,Math.floor((t+1)/8)-1);let f=e;for(let w=0;w<8;w++)f=(n[r]?.put(f,"▀".repeat(h),bc(s[w]??c)+pi(s[w+8]??c))??f)+1;let l=["❯ ",gr],g=[[["~/code/demo",dt],[" on ",cn],["main",Ga],[" +2",gr],[" ~1",Wn]]];if(g.push([l,["git status -sb",""]]),t>=44)g.push([["## ",""],["main",gr],["...",""],["origin/main",je],[" [ahead 1]",Wn]]);if(g.push([[" M",je],[" src/main.rs",""]]),g.push([["??",je],[" notes.md",""]]),g.push([]),t>=44)g.push([l,["ls",""]]),g.push([["docs",dt],[" ",""],["src",dt],[" ",""],["tests",dt],[" Cargo.toml README.md",""]]),g.push([]);g.push([l,["cargo test",""]]),g.push([[" ✓",gr],[" parses config",""]]);let d=[[" ✗",je],[" renders frame",""]];if(t>=44)d.push([" expected ",cn],["3",gr],[", received ",cn],["2",je]);g.push(d),g.push([]),g.push([l,["echo ",""],["selected text",pi(u)],[" ",""],[" ",pi(c)]]),g.forEach((w,m)=>{let b=r+2+m;if(b<=i)n[b]?.run(e,w)})}function Pa(n,r,e,t,i,o){n[r]?.put(e,`╭${"─".repeat(i-2)}╮`,o);for(let s=r+1;s<r+t-1;s++)n[s]?.put(e,"│",o),n[s]?.put(e+i-1,"│",o);n[r+t-1]?.put(e,`╰${"─".repeat(i-2)}╯`,o)}function bi(n,r=n.site,e=n.siteAnsi){return[` ${r} `,`\x1B[7;${30+e}m`]}function Ua(n){return`${Mn[Math.floor(n/Or)]?.name??""} ${n%Or}`}function Qa(n,r,e){let t=[{name:"all",moved:!1},...Mn].flatMap((s,u)=>{let c=`${s.name}${s.moved?"*":""}`,h=s.name===e.site?bi(e,c):[` ${c} `,cn];return u?[[" ",""],h]:[h]}),i=t.reduce((s,[u])=>s+zn(u),0)<=r,o=n.run(0,i?t:[bi(e)]);if(e.asking!==void 0)n.run(o,[[` ${e.asking} was cut off — this network may block it. turn on the unblock proxy? `,Wn],["y",ir],[" turn on ",cn],["n",ir],[" not now",cn]])}function Wa(n,r,e,t){if(e.editing!==void 0){let u=n.run(0,[["⌕ ",t],[e.editing,""],["█",t]]),c=e.suggest?.length?" ↑↓ pick enter searches":" enter searches";n.put(u,e.editing?c:` a tag, a post url or an id — ${e.tag||"esc leaves"}`,cn);return}let i=n.run(0,[["⌕ ",t],[e.tag||"nothing yet — / searches",e.tag?"":cn]]),o=Hr.filter((u)=>!e.block.includes(u)),s=[e.preset,...e.solo?["solo"]:[],e.order,...e.rating.join("+")==="safe"?[]:[e.rating.join("+")],...o.length>0?[`allows ${o.join("+")}`]:[],...e.unblocked?["unblock"]:[]];if(n.put(i,` ${s.join(" ")}`,cn),e.total>0||!e.searching){let u=[[`${e.tiles.length}/${e.checked}`,""]];if(e.checked<e.total)u.push([` of ${e.total}`,cn]);n.right(r,u)}}function Za(n){if(n.cut==="on")return[[`cut out · ${n.clear}% transparent`,gr]];if(n.cut==="off")return[["opaque · x cuts out",Wn]];if(n.cut==="failed")return[["opaque · no cut-out",Wn]];return[n.clear>0?[`${n.clear}% transparent`,gr]:["opaque",Wn]]}function ac(n){return n.site==="all"?"any site":n.site}function vc(n){if(n.installing!==void 0)return[`installing ${n.palette} ← ${Ua(n.installing)}`,Wn];if(n.error)return[n.error,Wn];if(n.waiting!==void 0)return[`${n.slow??n.site} asked to slow down · ${n.waiting}s`,Wn];if(n.fetching)return[`fetching ${n.fetching.id%Or} · ${Ja(n.fetching.got,n.fetching.size)}`,Wn];if(n.cutting!==void 0)return[`cutting out ${n.cutting%Or}`,Wn];if(n.preparing!==void 0)return[`preparing ${n.preparing%Or}`,Wn];if(n.saved)return[n.saved,gr];if(n.note)return[n.note,cn];return}function qa(n,r,e,t,i,o){let{perRow:s,rowsVis:u}=Tr(e,t);Wa(n[0],e,i,o),Qa(n[1],e,i);for(let d=0;d<s*u;d++){let w=i.top*s+d,m=i.tiles[w];if(!m)break;let b=2+Math.floor(d/s)*Un.height,F=d%s*Un.pitch,S=w===i.focus;if(S)Pa(n,b,F,Un.height,Un.pitch-1,o);if(m.thumb)r.push({id:m.key,path:m.thumb,row:b+1,col:F+1,cols:Un.cols,rows:Un.rows,z:-1});if(n[b+10]?.run(F+1,[...i.installed.includes(m.key)?[["✓ ",gr]]:[],...i.site==="all"?[["● ",`\x1B[${30+m.siteAnsi}m`]]:[],[String(m.id),S?ir:""],[" ",""],Ec(m)]),m.mates.length>0)n[b+10]?.put(F+Un.cols,"≈",o);let k=m.artist?Mc(m.artist):m.owner&&`@${m.owner}`;if(k)n[b+11]?.put(F+1,k.slice(0,Un.cols-8),cn);let y=[];if(m.score>0)y.push([`★${m.score}`,cn]);if(m.variants>1)y.push([` ×${m.variants}`,o]);if(y.length>0)n[b+11]?.right(F+Un.cols+1,y)}let c=i.top*s,h=i.tiles.length-(i.top+u)*s,f=[...c>0?[`↑ ${c} above`]:[],...h>0?[`↓ ${h} more`]:[]];if(f.length>0)n[t-2]?.put(0,f.join(" "),cn);if(!i.searching&&i.tiles.length===0&&!i.error)n[3]?.put(0,i.preset==="cutouts"?`no transparent cutouts of ${i.tag} on ${ac(i)} — c searches every post, tab tries ${i.nextSite}`:`no posts of ${i.tag} on ${ac(i)} — tab tries ${i.nextSite}`,cn);let l=n[t-1],g=vc(i);if(i.searching&&i.tiles.length===0&&!g){Re(l,e,o,{badge:"FIND",lead:[i.preset==="cutouts"?"checking png headers":"fetching posts",cn],right:["esc","back"]});return}Re(l,e,o,{badge:"FIND",lead:g,keys:i.asking!==void 0?[]:[["←↑↓→","move"],["enter","try on"],["tab","site"],["s","settings"],["/","search"],["?","keys"]],right:i.asking!==void 0?void 0:["esc","back"]})}function Aa(n,r,e,t,i,o){let s=i.tiles[i.focus];if(!s)return;let u=i.shown?.id===s.key?i.shown:void 0,c=[bi(i,s.site,s.siteAnsi),[" ",""],[String(s.id),ir],[" ",""],Ec(s)];if(s.artist)c.push([` · ${Mc(s.artist)}`,""]);if(s.score>0)c.push([` · ★${s.score}`,cn]);if(u)c.push([` · ${kc(u.bytes)}`,cn]);if(c.push([` · ${s.owner}`,cn]),s.origin)c.push([` · ${s.origin}`,cn]);if(u)c.push([" ",""],...Za(u));if(n[0]?.run(0,c),s.mates.length>0)n[0]?.right(e,[["≈ ",o],[s.mates.join(" "),cn]]);if(Ka(n,3,2,e-4,t-2,i),i.shown)r.push({id:Ha+i.shown.id,path:i.shown.path,row:0,col:0,cols:e,rows:t,z:Oa});let h=vc(i);Re(n[t-1],e,o,{badge:"TRY",lead:h,keys:i.installing===void 0?[["←→","browse"],["enter","install"],...i.shown?.cut==="on"||i.shown?.cut==="off"?[["x","cut out"]]:[],["?","keys"]]:[],right:i.installing===void 0?["esc","grid"]:void 0})}var Xa={grid:[["move","←↑↓→ home end pgup pgdn"],["try on","enter"],["site",`tab all, ${Mn.map((n)=>n.name).join(", ")}`],["posts","c cutouts or every post"],["search","/ a tag, a post url or an id"],["unfold","space a set of ×N"],["open","o the post page in a browser"],["settings","s rating, block, posts, solo, order, sets, remove bg"],["back","esc returns to preview"],["close","? esc"]],try:[["browse","←→"],["install","enter"],["cut out","x the background off or on, on an opaque picture"],["open","o the post page in a browser"],["grid","esc"],["close","? esc"]]};function Ta(n,r,e,t,i){let o=t.panel??0,s=Math.max(...t.settings.map((g)=>g.label.length)),u=Math.max(...t.settings.map((g)=>g.choices.reduce((d,w)=>d+w.length+(g.multi?6:3),0))),c=Math.min(r-2,Math.max(28,s+u+8)),h=t.settings.length+4,f=Math.floor((r-c)/2),l=Math.max(2,Math.floor((e-h)/2));n[l]?.put(f,`╭─ settings ${"─".repeat(Math.max(0,c-13))}╮`);for(let g=l+1;g<l+h-1;g++)n[g]?.put(f,`│${" ".repeat(c-2)}│`);t.settings.forEach((g,d)=>{let w=n[l+2+d];w.put(f+3,g.label,d===o?ir:cn);let m=f+5+s,b=g.value.split(" ");g.choices.forEach((F,S)=>{let k=b.includes(F),y=g.multi&&d===o&&S===g.cursor?"4;":"",p=g.multi?` ${k?"[x]":"[ ]"} ${F} `:` ${F} `;m=w.put(m,p,k?`\x1B[${y}7;${30+t.siteAnsi}m`:y?`\x1B[4m${cn}`:cn)+1})}),n[l+h-1]?.put(f,`╰${"─".repeat(c-2)}╯`),Re(n[e-1],r,i,{badge:"SET",keys:[["↑↓","setting"],["←→","value"],["space","toggle"],["enter","save"]],right:["esc","undo"]})}function Va(n,r,e,t,i){let o=Xa[t.mode],s=Math.min(r-2,50),u=o.length+4,c=Math.floor((r-s)/2),h=Math.max(2,Math.floor((e-u)/2));n[h]?.put(c,`╭─ keys ${"─".repeat(s-9)}╮`);for(let f=h+1;f<h+u-1;f++)n[f]?.put(c,`│${" ".repeat(s-2)}│`);o.forEach(([f,l],g)=>{n[h+2+g]?.put(c+3,f,ir),n[h+2+g]?.put(c+13,l.slice(0,s-16))}),n[h+u-1]?.put(c,`╰${"─".repeat(s-2)}╯`),Re(n[e-1],r,i,{badge:"KEYS",right:["? esc","close"]})}function za(n,r,e){let t=r.suggest??[],i=t.map((u)=>u.count>0?String(u.count):u.palette??"0"),o=Math.max(...t.map((u)=>zn(u.value))),s=Math.max(7,...i.map(zn));t.forEach((u,c)=>{let h=c===r.pick,f=n[1+c];f?.run(0,[[h?"▸ ":" ",e],[u.value,h?ir+e:""]]),f?.right(2+o+2+s,[[i[c],cn]])})}function Fc(n,r,e){let t=Array.from({length:e},()=>new mt(r)),i=[],o=bc(n.colors.cursor);if(r<Rr.cols||e<Rr.rows)return t[0]?.put(0,"ttheme find",ir+o),t[1]?.put(0,`needs ${Rr.cols}×${Rr.rows} — now ${r}×${e}`),t[2]?.put(0,"esc quits",cn),{lines:t.map((s)=>s.render()),images:i};if(n.mode==="try")Aa(t,i,r,e,n,o);else qa(t,i,r,e,n,o);if(n.mode==="grid"&&n.editing!==void 0&&n.suggest?.length){for(let s=1;s<e-1;s++)t[s]=new mt(r);return za(t,n,o),{lines:t.map((s)=>s.render()),images:[]}}if(n.help||n.panel!==void 0){let s=n.mode==="try"?i:[];for(let u=0;u<e;u++)t[u]=new mt(r);if(n.help)Va(t,r,e,n,o);else Ta(t,r,e,n,o);return{lines:t.map((u)=>u.render()),images:s}}return{lines:t.map((s)=>s.render()),images:i}}var Ya=new Set(["comic","4koma","monochrome","greyscale","sketch","lineart","speech_bubble"]),Ca=new Set(["scenery","landscape","scenic","no_humans","wide_shot","very_wide_shot"]),_a=0.04,Ba=0.1,xa=0.05,Da=4096;function nd(n){return new Set(n.cutouts.split(/\s+/).map((r)=>r.replace(/^~/,"")).filter(Boolean))}function rd(n,r,e,t=0){let{site:i,post:o}=n,s=new Set(o.tags),u=[...nd(i)].some((f)=>s.has(f)),c=Math.min(o.width,o.height),h=o.width>0&&o.height>0?o.width/o.height/(r.w/r.h):1;return(o.solo?2:0)+([...Ya].some((f)=>s.has(f))?-3:0)+([...Ca].some((f)=>s.has(f))?-1.5:0)+2*Math.min(1,c/r.h)+(u?1.5:-Math.min(1.5,Math.abs(Math.log(h))))+(e>0?1.5*Math.log1p(Math.max(0,o.score))/Math.log1p(e):0)+2*t}function $t(n,r,e=new Map){let t=new Map;for(let{site:i,post:o}of n)t.set(i,Math.max(t.get(i)??0,o.score));return n.map((i,o)=>({pick:i,at:o,score:rd(i,r,t.get(i.site)??0,e.get(i.post))})).sort((i,o)=>o.score-i.score||i.at-o.at).map(({pick:i})=>i)}function Ic(n){let r=new Map;for(let t of n)r.set(t.site,[...r.get(t.site)??[],t]);let e=[];for(let t=0;e.length<n.length;t++)for(let i of r.values()){let o=i[t];if(o)e.push(o)}return e}function Mi(n){let r=n/255;return r<=0.04045?r/12.92:((r+0.055)/1.055)**2.4}function yc(n,r,e){let[t,i,o]=[Mi(n),Mi(r),Mi(e)],s=Math.cbrt(0.4122214708*t+0.5363325363*i+0.0514459929*o),u=Math.cbrt(0.2119034982*t+0.6806995451*i+0.1073969566*o),c=Math.cbrt(0.0883024619*t+0.2817188376*i+0.6299787005*o);return[0.2104542553*s+0.793617785*u-0.0040720468*c,1.9779984951*s-2.428592205*u+0.4505937099*c,0.0259040371*s+0.7827717662*u-0.808675766*c]}function Sc(n,r){let e=r.map((s)=>yc(...Gn(s))).filter(([,s,u])=>Math.hypot(s,u)>=_a);if(e.length===0)return 0;let t=Math.max(1,Math.floor(Math.sqrt(n.width*n.height/Da))),i=e.map(()=>0),o=0;for(let s=0;s<n.height;s+=t)for(let u=0;u<n.width;u+=t){let c=(s*n.width+u)*4;if(n.data[c+3]<128)continue;o++;let[h,f,l]=yc(n.data[c],n.data[c+1],n.data[c+2]);e.forEach(([g,d,w],m)=>{if(Math.hypot(h-g,f-d,l-w)<Ba)i[m]=i[m]+1})}if(o===0)return 0;return i.reduce((s,u)=>s+Math.min(1,u/o/xa),0)/e.length}import{execFileSync as ed,spawn as td}from"node:child_process";import{existsSync as or,mkdirSync as Le,readFileSync as Vr,rmSync as vi,utimesSync as id,writeFileSync as zr}from"node:fs";import{homedir as wt}from"node:os";import{dirname as Je,join as bn}from"node:path";var od={ghostty:de,kitty:$e,alacritty:ae,wezterm:Ne,iterm2:me,"windows-terminal":He,warp:Se},Nc="ttheme-default";function Yr(n=process.env.TTHEME_ITERM_SUITE??"com.googlecode.iterm2"){let r=(e,t)=>ed(e,t,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();return{read:()=>{try{return process.platform==="darwin"?r("defaults",["read",n,"Default Bookmark Guid"])||void 0:void 0}catch{return}},write:(e)=>{if(process.platform==="darwin")r("defaults",["write",n,"Default Bookmark Guid","-string",e])},running:()=>{try{return r("pgrep",["-x","iTerm2"])!==""}catch{return!1}}}}function Cr(n){return n.keepTheme?void 0:_r(n)}function Ke(n,r){if(!n.terminals.includes("iterm2"))return n;let e=r.read();return e&&!e.startsWith("ttheme-")?{...n,itermBase:e}:n}function Pe(n,r){if(!n.terminals.includes("iterm2"))return!1;let e=r.read(),t=Cr(n)?Nc:e===Nc?n.itermBase:void 0;if(!t||t===e)return!1;return r.write(t),!0}function xn(){return process.env.XDG_CONFIG_HOME??bn(wt(),".config")}function Hc(n){return bn(n,"Library","Application Support","iTerm2","DynamicProfiles","ttheme.json")}function Oc(n){return bn(n,"ttheme","installed.json")}function lr(n){let r=Oc(n);if(!or(r))throw Error(`nothing installed yet at ${r} — run \`ttheme init\` first`);let e=JSON.parse(Vr(r,"utf8"));if(!Array.isArray(e?.palettes)||!Array.isArray(e.terminals))throw Error(`${r} has no palettes or terminals`);return{terminals:e.terminals.filter((t)=>it.includes(t)),...e.startup?{startup:e.startup}:{},...e.keepTheme?{keepTheme:!0}:{},...e.itermBase?{itermBase:e.itermBase}:{},...e.wtHome?{wtHome:e.wtHome}:{},...e.wtProfile?{wtProfile:e.wtProfile}:{},palettes:e.palettes}}function Ue(n,r){let e=Oc(n);Le(Je(e),{recursive:!0}),zr(e,`${JSON.stringify(r,null,2)}
80
- `)}function Ge(n,r){return{name:n.name,group:n.group,...n.native?{native:n.native}:{},lead:n.lead===!0,order:n.order,...n.default?{role:"default"}:{},ansiSource:n.ansiSource,...n.booru?{booru:n.booru}:{},...n.booruSites?{booruSites:n.booruSites}:{},background:n.background,foreground:n.foreground,cursor:n.cursor,selectionBackground:n.selection,ansi:n.ansi,signature:n.signature,signatureSlots:n.signatureSlots,font:r.font,ghostty:{...r.shader?{shader:r.shader}:{},iconGhost:n.cursor,iconScreen:[n.cursor,n.selection,n.background]},waive:n.waived??[]}}function jc(n,r){let e=new Map(n.palettes.map((o)=>[o.name,o])),t=r.filter((o)=>!e.has(o));if(t.length>0)throw Error(`not in the catalog: ${t.join(", ")} — \`ttheme list\` shows what is there`);let i=r.flatMap((o)=>{let s=sc(e.get(o));return s.length>0?[`${o}: ${s.join(", ")}`]:[]});if(i.length>0)throw Error(`these palettes fail the contrast gate:
130
+ }`;function Ui(){return process.platform==="darwin"}function Tu(t){return t>=Id&&t<=Nd}function Wu(t,n,e){return new Promise((r,i)=>{let o=Sd("osascript",["-l","JavaScript","-e",Od,t,n],{stdio:["ignore","ignore","pipe"],signal:AbortSignal.any([e,AbortSignal.timeout(Fd)])}),s="";o.stderr.on("data",(c)=>{s+=c}),o.on("error",i),o.on("close",(c)=>{if(c===0){r();return}i(Error(s.trim().split(`
131
+ `).at(-1)||`osascript exited ${c}`))})})}var Jt={pitch:25,cols:22,rows:9,height:13},Ln={cols:25,rows:16},Hd=2147483648,jd=-1073741826,Rd=1600,Gd="\x1B[0m",un="\x1B[1m",ut="\x1B[2m",Je="\x1B[31m",cn="\x1B[32m",Ut="\x1B[33m",jr="\x1B[1;34m",Ld="\x1B[35m",Pd={A:"up",B:"down",C:"right",D:"left",H:"home",F:"end","1~":"home","7~":"home","4~":"end","8~":"end","5~":"pgup","6~":"pgdn",I:"focus-in",O:"focus-out"};function qu(t){let n=[],e=0;while(e<t.length){let r=t[e]??"";if(r==="\x1B"){let i=/^(?:\[([0-9;]*)([A-Za-z~])|O([A-Za-z]))/.exec(t.slice(e+1));if(i){n.push(Pd[`${i[1]??""}${i[2]??i[3]??""}`]??"nop"),e+=1+i[0].length;continue}let o=t[e+1]??"";if(/^[a-z]$/.test(o)){n.push(`alt-${o}`),e+=2;continue}n.push("esc"),e++;continue}n.push(r==="\r"||r===`
132
+ `?"enter":r==="\t"?"tab":r==="\x03"?"ctrl-c":r==="\x16"?"ctrl-v":r===""||r==="\b"?"backspace":r),e++}return n}var Xu="\x1B]1337;ReportCellSize\x07\x1B[16t",Qu="\x1B]1337;ReportCellSize=";function Qi(t){let n=t.indexOf(Qu);if(n!==-1){let i=t.slice(n+Qu.length),o=[i.indexOf("\x07"),i.indexOf("\x1B\\")].filter((u)=>u!==-1),s=o.length>0?Math.min(...o):-1,c=s===-1?null:/^([\d.]+);([\d.]+);([\d.]+)$/.exec(i.slice(0,s));if(c){let u=Number(c[3]);return{cell:{h:Math.round(Number(c[1])*u),w:Math.round(Number(c[2])*u)},rest:t.slice(0,n)+i.slice(s+(i[s]==="\x07"?1:2))}}}let e=t.indexOf("\x1B[6;"),r=e===-1?null:/^\[6;(\d+);(\d+)t/.exec(t.slice(e+1));if(!r)return null;return{cell:{h:Number(r[1]),w:Number(r[2])},rest:t.slice(0,e)+t.slice(e+1+r[0].length)}}function _n(t,n){return{perRow:Math.max(1,Math.floor((t+1)/Jt.pitch)),rowsVis:Math.max(1,Math.floor((n-4)/Jt.height))}}function _u(t){return`\x1B_Ga=t,t=f,f=100,i=${t.id},q=2;${Buffer.from(t.path).toString("base64")}\x1B\\`}function Cu(t){return`\x1B[${t.row+1};${t.col+1}H\x1B_Ga=p,i=${t.id},p=${t.id},c=${t.cols},r=${t.rows},C=1,z=${t.z},q=2\x1B\\`}function zu(t){return`\x1B_Ga=d,d=I,i=${t},q=2\x1B\\`}function Yu(t){return`\x1B[38;2;${Rt(t).join(";")}m`}function Ti(t){return`\x1B[48;2;${Rt(t).join(";")}m`}function Ct(t){return Array.from(t).length}class Rr{parts=[];cols;constructor(t){this.cols=t}put(t,n,e=""){return this.parts.push({col:t,text:n,sgr:e}),t+Ct(n)}run(t,n){let e=t;for(let[r,i]of n)e=this.put(e,r,i);return e}right(t,n){this.run(t-n.reduce((e,[r])=>e+Ct(r),0),n)}render(){let t="";for(let{col:n,text:e,sgr:r}of this.parts){if(n>=this.cols||n<0)continue;let i=Array.from(e).slice(0,this.cols-n).join("");t+=`\x1B[${n+1}G${r}${i}${r?Gd:""}`}return t}}function Vu(t){return t>=1e6?`${(t/1e6).toFixed(1)} MB`:`${Math.max(1,Math.round(t/1000))} KB`}function Kd(t,n){if(!n)return Vu(t);return n>=1e6?`${(t/1e6).toFixed(1)}/${(n/1e6).toFixed(1)} MB`:`${Math.round(t/1000)}/${Math.round(n/1000)} KB`}function xu(t){return t.replace(/_\([^)]*\)?$/,"")}function Bu(t){return[`${t.reduced?"↓":""}${t.width}×${t.height}`,Math.max(t.width,t.height)<Rd?Ut:ut]}function Ae(t,n,e,r){let i=[...r.keys??[]],o=r.lead,s=r.right,c=()=>{let f=[...o?[Ct(o[0])]:[],...i.map(([g,d])=>Ct(g)+1+Ct(d))];return(r.badge?Ct(r.badge)+4:0)+f.reduce((g,d)=>g+d,0)+3*Math.max(0,f.length-1)+(s?3+Ct(s[0])+1+Ct(s[1]):0)};while(c()>n)if(i.length>2)i.splice(-2,1);else if(s)s=void 0;else if(i.length>1)i.splice(-2,1);else break;if(o&&c()>n){let f=Math.max(0,Ct(o[0])-(c()-n)-1);o=[`${Array.from(o[0]).slice(0,f).join("")}…`,o[1]]}let u=0;if(r.badge)u=t.put(0,` ${r.badge} `,`\x1B[7;1m${e}`)+2;if([...o?[[o]]:[],...i.map(([f,a])=>[[f,un],[` ${a}`,ut]])].forEach((f,a)=>{u=t.run(u+(a?3:0),f)}),s)t.right(n,[[s[0],un],[` ${s[1]}`,ut]])}function Jd(t,n,e,r,i,o){let{ansi:s,selection:c,cursor:u}=o.colors,h=r<44?3:4;if(r>=56)h=Math.min(7,Math.floor((r+1)/8)-1);let f=e;for(let p=0;p<8;p++)f=(t[n]?.put(f,"▀".repeat(h),Yu(s[p]??u)+Ti(s[p+8]??u))??f)+1;let a=["❯ ",cn],g=[[["~/code/demo",jr],[" on ",ut],["main",Ld],[" +2",cn],[" ~1",Ut]]];if(g.push([a,["git status -sb",""]]),r>=44)g.push([["## ",""],["main",cn],["...",""],["origin/main",Je],[" [ahead 1]",Ut]]);if(g.push([[" M",Je],[" src/main.rs",""]]),g.push([["??",Je],[" notes.md",""]]),g.push([]),r>=44)g.push([a,["ls",""]]),g.push([["docs",jr],[" ",""],["src",jr],[" ",""],["tests",jr],[" Cargo.toml README.md",""]]),g.push([]);g.push([a,["cargo test",""]]),g.push([[" ✓",cn],[" parses config",""]]);let d=[[" ✗",Je],[" renders frame",""]];if(r>=44)d.push([" expected ",ut],["3",cn],[", received ",ut],["2",Je]);g.push(d),g.push([]),g.push([a,["echo ",""],["selected text",Ti(c)],[" ",""],[" ",Ti(u)]]),g.forEach((p,l)=>{let k=n+2+l;if(k<=i)t[k]?.run(e,p)})}function Ad(t,n,e,r,i,o){t[n]?.put(e,`╭${"─".repeat(i-2)}╮`,o);for(let s=n+1;s<n+r-1;s++)t[s]?.put(e,"│",o),t[s]?.put(e+i-1,"│",o);t[n+r-1]?.put(e,`╰${"─".repeat(i-2)}╯`,o)}function Wi(t,n=t.site,e=t.siteAnsi){return[` ${n} `,`\x1B[7;${30+e}m`]}function Ud(t){return`${gt[Math.floor(t/ln)]?.name??"local"} ${t%ln}`}function Td(t,n,e){let r=[{name:"all",moved:!1},...gt].flatMap((s,c)=>{let u=`${s.name}${s.moved?"*":""}`,h=s.name===e.site?Wi(e,u):[` ${u} `,ut];return c?[[" ",""],h]:[h]}),i=r.reduce((s,[c])=>s+Ct(c),0)<=n,o=t.run(0,i?r:[Wi(e)]);if(e.asking!==void 0)t.run(o,[[` ${e.asking} was cut off — this network may block it. turn on the unblock proxy? `,Ut],["y",un],[" turn on ",ut],["n",un],[" not now",ut]])}function Wd(t,n,e,r){if(e.editing!==void 0){let c=t.run(0,[["⌕ ",r],[e.editing,""],["█",r]]),u=e.suggest?.length?" ↑↓ pick enter searches":" enter searches";t.put(c,e.editing?u:` a tag, a post url or an id, or drop a picture or ctrl+v — ${e.tag||"esc leaves"}`,ut);return}let i=t.run(0,[["⌕ ",r],[e.tag||"nothing yet — / searches, ctrl+v pastes a picture",e.tag?"":ut]]),o=jn.filter((c)=>!e.block.includes(c)),s=[e.preset,...e.solo?["solo"]:[],e.order,...e.rating.join("+")==="safe"?[]:[e.rating.join("+")],...o.length>0?[`allows ${o.join("+")}`]:[],...e.unblocked?["unblock"]:[]];if(t.put(i,` ${s.join(" ")}`,ut),e.total>0||!e.searching){let c=[[`${e.tiles.length}/${e.checked}`,""]];if(e.checked<e.total)c.push([` of ${e.total}`,ut]);t.right(n,c)}}function Qd(t){if(t.cut==="on")return[[`cut out · ${t.clear}% transparent`,cn]];if(t.cut==="off")return[["opaque · x cuts out",Ut]];if(t.cut==="failed")return[["opaque · no cut-out",Ut]];return[t.clear>0?[`${t.clear}% transparent`,cn]:["opaque",Ut]]}function Zu(t){return t.site==="all"?"any site":t.site}function Du(t){if(t.installing!==void 0)return[`installing ${t.palette} ← ${Ud(t.installing)}`,Ut];if(t.hint)return[t.hint,cn];if(t.error)return[t.error,Ut];if(t.waiting!==void 0)return[`${t.slow??t.site} asked to slow down · ${t.waiting}s`,Ut];if(t.fetching)return[`fetching ${t.fetching.id%ln} · ${Kd(t.fetching.got,t.fetching.size)}`,Ut];if(t.cutting!==void 0)return[`cutting out ${t.cutting%ln}`,Ut];if(t.preparing!==void 0)return[`preparing ${t.preparing%ln}`,Ut];if(t.saved)return[t.saved,cn];if(t.note)return[t.note,ut];return}function Zd(t,n,e,r,i,o){let{perRow:s,rowsVis:c}=_n(e,r);Wd(t[0],e,i,o),Td(t[1],e,i);for(let d=0;d<s*c;d++){let p=i.top*s+d,l=i.tiles[p];if(!l)break;let k=2+Math.floor(d/s)*Jt.height,v=d%s*Jt.pitch,I=p===i.focus;if(I)Ad(t,k,v,Jt.height,Jt.pitch-1,o);if(l.thumb)n.push({id:l.key,path:l.thumb,row:k+1,col:v+1,cols:Jt.cols,rows:Jt.rows,z:-1});if(t[k+10]?.run(v+1,[...i.installed.includes(l.key)?[["✓ ",cn]]:[],...i.site==="all"?[["● ",`\x1B[${30+l.siteAnsi}m`]]:[],[String(l.id),I?un:""],[" ",""],Bu(l)]),l.mates.length>0)t[k+10]?.put(v+Jt.cols,"≈",o);let E=l.artist?xu(l.artist):l.owner&&`@${l.owner}`;if(E)t[k+11]?.put(v+1,E.slice(0,Jt.cols-8),ut);let y=[];if(l.score>0)y.push([`★${l.score}`,ut]);if(l.variants>1)y.push([` ×${l.variants}`,o]);if(y.length>0)t[k+11]?.right(v+Jt.cols+1,y)}let u=i.top*s,h=i.tiles.length-(i.top+c)*s,f=[...u>0?[`↑ ${u} above`]:[],...h>0?[`↓ ${h} more`]:[]];if(f.length>0)t[r-2]?.put(0,f.join(" "),ut);if(!i.searching&&i.tiles.length===0&&!i.error)t[3]?.put(0,i.preset==="cutouts"?`no transparent cutouts of ${i.tag} on ${Zu(i)} — c searches every post, tab tries ${i.nextSite}`:`no posts of ${i.tag} on ${Zu(i)} — tab tries ${i.nextSite}`,ut);let a=t[r-1],g=Du(i);if(i.searching&&i.tiles.length===0&&!g){Ae(a,e,o,{badge:"FIND",lead:[i.preset==="cutouts"?"checking png headers":"fetching posts",ut],right:["esc","back"]});return}Ae(a,e,o,{badge:"FIND",lead:g,keys:i.asking!==void 0?[]:[["←↑↓→","move"],["enter","try on"],["tab","site"],["ctrl+v","picture"],["s","settings"],["/","search"],["?","keys"]],right:i.asking!==void 0?void 0:["esc","back"]})}function qd(t,n,e,r,i,o){let s=i.tiles[i.focus];if(!s)return;let c=i.shown?.id===s.key?i.shown:void 0,u=[Wi(i,s.site,s.siteAnsi),[" ",""],[String(s.id),un],[" ",""],Bu(s)];if(s.artist)u.push([` · ${xu(s.artist)}`,""]);if(s.score>0)u.push([` · ★${s.score}`,ut]);if(c)u.push([` · ${Vu(c.bytes)}`,ut]);if(s.owner)u.push([` · ${s.owner}`,ut]);if(s.origin)u.push([` · ${s.origin}`,ut]);if(c)u.push([" ",""],...Qd(c));if(t[0]?.run(0,u),s.mates.length>0)t[0]?.right(e,[["≈ ",o],[s.mates.join(" "),ut]]);if(Jd(t,3,2,e-4,r-2,i),i.shown)n.push({id:Hd+i.shown.id,path:i.shown.path,row:0,col:0,cols:e,rows:r,z:jd});let h=Du(i);Ae(t[r-1],e,o,{badge:"TRY",lead:h,keys:i.installing===void 0?[["←→","browse"],["enter","install"],...i.shown?.cut==="on"||i.shown?.cut==="off"?[["x","cut out"]]:[],["?","keys"]]:[],right:i.installing===void 0?["esc","grid"]:void 0})}var Xd={grid:[["move","←↑↓→ home end pgup pgdn"],["try on","enter"],["site",`tab all, ${gt.map((t)=>t.name).join(", ")}`],["posts","c cutouts or every post"],["search","/ a tag, a post url or an id"],["your own","ctrl+v or v a picture from the clipboard · drop one on the window or paste its link"],["unfold","space a set of ×N"],["open","o the post page in a browser"],["settings","s rating, block, posts, solo, order, sets, remove bg"],["back","esc returns to preview"],["close","? esc"]],try:[["browse","←→"],["install","enter"],["cut out","x the background off or on, on an opaque picture"],["open","o the post page in a browser"],["your own","ctrl+v or v a picture from the clipboard · drop one on the window"],["grid","esc"],["close","? esc"]]};function _d(t,n,e,r,i){let o=r.panel??0,s=Math.max(...r.settings.map((g)=>g.label.length)),c=Math.max(...r.settings.map((g)=>g.choices.reduce((d,p)=>d+p.length+(g.multi?6:3),0))),u=Math.min(n-2,Math.max(28,s+c+8)),h=r.settings.length+4,f=Math.floor((n-u)/2),a=Math.max(2,Math.floor((e-h)/2));t[a]?.put(f,`╭─ settings ${"─".repeat(Math.max(0,u-13))}╮`);for(let g=a+1;g<a+h-1;g++)t[g]?.put(f,`│${" ".repeat(u-2)}│`);r.settings.forEach((g,d)=>{let p=t[a+2+d];p.put(f+3,g.label,d===o?un:ut);let l=f+5+s,k=g.value.split(" ");g.choices.forEach((v,I)=>{let E=k.includes(v),y=g.multi&&d===o&&I===g.cursor?"4;":"",$=g.multi?` ${E?"[x]":"[ ]"} ${v} `:` ${v} `;l=p.put(l,$,E?`\x1B[${y}7;${30+r.siteAnsi}m`:y?`\x1B[4m${ut}`:ut)+1})}),t[a+h-1]?.put(f,`╰${"─".repeat(u-2)}╯`),Ae(t[e-1],n,i,{badge:"SET",keys:[["↑↓","setting"],["←→","value"],["space","toggle"],["enter","save"]],right:["esc","undo"]})}function Cd(t,n,e,r,i){let o=Xd[r.mode],s=Math.min(n-2,50),c=o.length+4,u=Math.floor((n-s)/2),h=Math.max(2,Math.floor((e-c)/2));t[h]?.put(u,`╭─ keys ${"─".repeat(s-9)}╮`);for(let f=h+1;f<h+c-1;f++)t[f]?.put(u,`│${" ".repeat(s-2)}│`);o.forEach(([f,a],g)=>{t[h+2+g]?.put(u+3,f,un),t[h+2+g]?.put(u+13,a.slice(0,s-16))}),t[h+c-1]?.put(u,`╰${"─".repeat(s-2)}╯`),Ae(t[e-1],n,i,{badge:"KEYS",right:["? esc","close"]})}function zd(t,n,e){let r=n.suggest??[],i=r.map((c)=>c.count>0?String(c.count):c.palette??"0"),o=Math.max(...r.map((c)=>Ct(c.value))),s=Math.max(7,...i.map(Ct));r.forEach((c,u)=>{let h=u===n.pick,f=t[1+u];f?.run(0,[[h?"▸ ":" ",e],[c.value,h?un+e:""]]),f?.right(2+o+2+s,[[i[u],ut]])})}function th(t,n,e){let r=Array.from({length:e},()=>new Rr(n)),i=[],o=Yu(t.colors.cursor);if(n<Ln.cols||e<Ln.rows)return r[0]?.put(0,"ttheme find",un+o),r[1]?.put(0,`needs ${Ln.cols}×${Ln.rows} — now ${n}×${e}`),r[2]?.put(0,"esc quits",ut),{lines:r.map((s)=>s.render()),images:i};if(t.mode==="try")qd(r,i,n,e,t,o);else Zd(r,i,n,e,t,o);if(t.mode==="grid"&&t.editing!==void 0&&t.suggest?.length){for(let s=1;s<e-1;s++)r[s]=new Rr(n);return zd(r,t,o),{lines:r.map((s)=>s.render()),images:[]}}if(t.help||t.panel!==void 0){let s=t.mode==="try"?i:[];for(let c=0;c<e;c++)r[c]=new Rr(n);if(t.help)Cd(r,n,e,t,o);else _d(r,n,e,t,o);return{lines:r.map((c)=>c.render()),images:s}}return{lines:r.map((s)=>s.render()),images:i}}var Yd=new Set(["comic","4koma","monochrome","greyscale","sketch","lineart","speech_bubble"]),Vd=new Set(["scenery","landscape","scenic","no_humans","wide_shot","very_wide_shot"]),xd=0.04,Bd=0.1,Dd=0.05,tm=4096;function nm(t){return new Set(t.cutouts.split(/\s+/).map((n)=>n.replace(/^~/,"")).filter(Boolean))}function em(t,n,e,r=0){let{site:i,post:o}=t,s=new Set(o.tags),c=[...nm(i)].some((f)=>s.has(f)),u=Math.min(o.width,o.height),h=o.width>0&&o.height>0?o.width/o.height/(n.w/n.h):1;return(o.solo?2:0)+([...Yd].some((f)=>s.has(f))?-3:0)+([...Vd].some((f)=>s.has(f))?-1.5:0)+2*Math.min(1,u/n.h)+(c?1.5:-Math.min(1.5,Math.abs(Math.log(h))))+(e>0?1.5*Math.log1p(Math.max(0,o.score))/Math.log1p(e):0)+2*r}function Gr(t,n,e=new Map){let r=new Map;for(let{site:i,post:o}of t)r.set(i,Math.max(r.get(i)??0,o.score));return t.map((i,o)=>({pick:i,at:o,score:em(i,n,r.get(i.site)??0,e.get(i.post))})).sort((i,o)=>o.score-i.score||i.at-o.at).map(({pick:i})=>i)}function eh(t){let n=new Map;for(let r of t)n.set(r.site,[...n.get(r.site)??[],r]);let e=[];for(let r=0;e.length<t.length;r++)for(let i of n.values()){let o=i[r];if(o)e.push(o)}return e}function Zi(t){let n=t/255;return n<=0.04045?n/12.92:((n+0.055)/1.055)**2.4}function nh(t,n,e){let[r,i,o]=[Zi(t),Zi(n),Zi(e)],s=Math.cbrt(0.4122214708*r+0.5363325363*i+0.0514459929*o),c=Math.cbrt(0.2119034982*r+0.6806995451*i+0.1073969566*o),u=Math.cbrt(0.0883024619*r+0.2817188376*i+0.6299787005*o);return[0.2104542553*s+0.793617785*c-0.0040720468*u,1.9779984951*s-2.428592205*c+0.4505937099*u,0.0259040371*s+0.7827717662*c-0.808675766*u]}function rh(t,n){let e=n.map((s)=>nh(...Rt(s))).filter(([,s,c])=>Math.hypot(s,c)>=xd);if(e.length===0)return 0;let r=Math.max(1,Math.floor(Math.sqrt(t.width*t.height/tm))),i=e.map(()=>0),o=0;for(let s=0;s<t.height;s+=r)for(let c=0;c<t.width;c+=r){let u=(s*t.width+c)*4;if(t.data[u+3]<128)continue;o++;let[h,f,a]=nh(t.data[u],t.data[u+1],t.data[u+2]);e.forEach(([g,d,p],l)=>{if(Math.hypot(h-g,f-d,a-p)<Bd)i[l]=i[l]+1})}if(o===0)return 0;return i.reduce((s,c)=>s+Math.min(1,c/o/Dd),0)/e.length}import{execFileSync as rm,spawn as im}from"node:child_process";import{existsSync as zt,mkdirSync as Te,readFileSync as Sn,rmSync as qi,utimesSync as om,writeFileSync as Cn}from"node:fs";import{homedir as Pr}from"node:os";import{dirname as We,join as mt}from"node:path";var sm={ghostty:pe,kitty:$e,alacritty:me,wezterm:Ge,iterm2:we,"windows-terminal":Le,warp:Re},ih="ttheme-default";function zn(t=process.env.TTHEME_ITERM_SUITE??"com.googlecode.iterm2"){let n=(e,r)=>rm(e,r,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();return{read:()=>{try{return process.platform==="darwin"?n("defaults",["read",t,"Default Bookmark Guid"])||void 0:void 0}catch{return}},write:(e)=>{if(process.platform==="darwin")n("defaults",["write",t,"Default Bookmark Guid","-string",e])},running:()=>{try{return n("pgrep",["-x","iTerm2"])!==""}catch{return!1}}}}function hn(t){return t.off?void 0:Yn(t)}function Qe(t,n){if(!t.terminals.includes("iterm2"))return t;let e=n.read();return e&&!e.startsWith("ttheme-")?{...t,itermBase:e}:t}function Ze(t,n){if(!t.terminals.includes("iterm2"))return!1;let e=n.read(),r=hn(t)?ih:e===ih?t.itermBase:void 0;if(!r||r===e)return!1;return n.write(r),!0}function Tt(){return process.env.XDG_CONFIG_HOME??mt(Pr(),".config")}function oh(t){return mt(t,"Library","Application Support","iTerm2","DynamicProfiles","ttheme.json")}function sh(t){return mt(t,"ttheme","installed.json")}function Yt(t){let n=sh(t);if(!zt(n))throw Error(`nothing installed yet at ${n} — run \`ttheme init\` first`);let e=JSON.parse(Sn(n,"utf8"));if(!Array.isArray(e?.palettes)||!Array.isArray(e.terminals))throw Error(`${n} has no palettes or terminals`);return{terminals:e.terminals.filter((r)=>mr.includes(r)),...e.startup?{startup:e.startup}:{},...e.off?{off:!0}:{},...e.itermBase?{itermBase:e.itermBase}:{},...e.wtHome?{wtHome:e.wtHome}:{},...e.wtProfile?{wtProfile:e.wtProfile}:{},palettes:e.palettes}}function qe(t,n){let e=sh(t);Te(We(e),{recursive:!0}),Cn(e,`${JSON.stringify(n,null,2)}
133
+ `)}function Ue(t,n){return{name:t.name,group:t.group,...t.native?{native:t.native}:{},lead:t.lead===!0,order:t.order,...t.default?{role:"default"}:{},ansiSource:t.ansiSource,...t.booru?{booru:t.booru}:{},...t.booruSites?{booruSites:t.booruSites}:{},background:t.background,foreground:t.foreground,cursor:t.cursor,selectionBackground:t.selection,ansi:t.ansi,signature:t.signature,signatureSlots:t.signatureSlots,font:n.font,ghostty:{...n.shader?{shader:n.shader}:{},iconGhost:t.cursor,iconScreen:[t.cursor,t.selection,t.background]},waive:t.waived??[]}}function ch(t,n){let e=new Map(t.palettes.map((o)=>[o.name,o])),r=n.filter((o)=>!e.has(o));if(r.length>0)throw Error(`not in the catalog: ${r.join(", ")} — \`ttheme list\` shows what is there`);let i=n.flatMap((o)=>{let s=Ku(e.get(o));return s.length>0?[`${o}: ${s.join(", ")}`]:[]});if(i.length>0)throw Error(`these palettes fail the contrast gate:
81
134
  ${i.join(`
82
- `)}`);return n.palettes.filter((o)=>r.includes(o.name))}function Rc(n,r){let e=n==="wezterm"?"colors":"themes";return(od[n].emit?.(r)??[]).flatMap((t)=>{let[,i,o]=t.path.split("/");return i===e&&o!==void 0?[{file:o,content:t.content}]:[]})}function pt(n){return process.platform==="darwin"?bn(n,".warp","themes"):bn(process.env.XDG_DATA_HOME??bn(n,".local","share"),"warp-terminal","themes")}function Ei(n,r,e){if(n==="warp")return pt(e);return bn(r,n,n==="wezterm"?"colors":"themes")}function sd(n,r){return process.platform==="darwin"?bn(n,".warp","settings.toml"):bn(r,"warp-terminal","settings.toml")}var ud='"dark"',cd="setTimeout(() => { const fs = require('node:fs'); const [file, next, seen] = process.argv.slice(-3); if (fs.readFileSync(file, 'utf8') === seen) fs.writeFileSync(file, next) }, 1500)";function hd(n,r,e,t){let i=sd(r,n);if(!or(i))return;let o=bn(n,"ttheme","warp.base"),s=Vr(i,"utf8"),u=Vu(s),c=u?.includes('path = "ttheme-')===!0,h;if(e){if(!c&&!or(o))Le(Je(o),{recursive:!0}),zr(o,u??"");h=zu(e)}else{if(!c)return;h=or(o)&&Vr(o,"utf8")||ud,vi(o,{force:!0})}let f=Yu(s,h);if(f===s)return;if(t)td(process.execPath,["-e",cd,i,f,s],{detached:!0,stdio:"ignore"}).unref();else zr(i,f);return i}function Fi(n,r){let e=bn(r,".wezterm.lua");return or(e)?e:bn(n,"wezterm","wezterm.lua")}function fd(n){return bn(n,"Microsoft","Windows Terminal","Fragments","ttheme","ttheme.json")}function gd(n){return[bn(n,"Packages","Microsoft.WindowsTerminal_8wekyb3d8bbwe","LocalState","settings.json"),bn(n,"Packages","Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe","LocalState","settings.json"),bn(n,"Microsoft","Windows Terminal","settings.json")].filter((r)=>or(r))}function ld(n){for(let r of n){let e=/"defaultProfile"\s*:\s*"(\{[0-9a-fA-F-]+\})"/.exec(Vr(r,"utf8"))?.[1];if(e)return e}return}function _r(n){return n.startup&&n.palettes.includes(n.startup)?n.startup:n.palettes[0]}function ad(n,r,e){let t=bn(r,"ttheme");if(n==="ghostty")return{file:bn(r,"ghostty","config"),body:Pu(t,e)};if(n==="kitty")return{file:bn(r,"kitty","kitty.conf"),body:Zu(e)};let i=e?bn(r,"alacritty","themes",`${e}.toml`):void 0;return{file:bn(r,"alacritty","alacritty.toml"),body:qu(i)}}function Gc(n,r,e,t,i){let o=Sr(n),s=e.map((h)=>Ge(h,r)),u=new Map;for(let h of s){let f=Cs(o,h.name,i);if(f)u.set(h.name,f)}let c=new Set(Ar(e).map((h)=>h.name));return jo(s.filter((h)=>c.has(h.name)),u,s.find((h)=>h.name===Cr(t)),t.itermBase)}function Br(n,r=wt()){let e=lr(n);if(!e.terminals.includes("iterm2"))return;let t=Qn(n),i=Hc(r);Le(Je(i),{recursive:!0}),zr(i,Gc(n,t,jc(t,e.palettes),e,r))}function Qe(n,r,e,t=wt()){let i=jc(r,e.palettes),o=[],s=(h,f)=>{Le(Je(h),{recursive:!0}),zr(h,f),o.push(h)},u=Cr(e);for(let h of e.terminals){if(h==="iterm2"){s(Hc(t),Gc(n,r,i,e,t));continue}if(h==="windows-terminal"){if(e.wtHome){let m=gd(e.wtHome),b=i.map((S)=>Ge(S,r));s(fd(e.wtHome),mi(b,e.wtProfile??ld(m),u));let F=new Date;for(let S of m)id(S,F,F)}continue}let f=u!==void 0&&h==="warp"&&!or(bn(pt(t),`ttheme-${u}.yaml`)),l=h==="warp"?hd(n,t,u,f):void 0;for(let m of i)for(let{file:b,content:F}of Rc(h,Ge(m,r)))s(bn(Ei(h,n,t),b),F);if(h==="warp"){if(l)o.push(l);continue}if(h==="wezterm"){let m=bn(n,"ttheme","wezterm.lua");s(m,Bu({path:m,colors:Ei("wezterm",n,t),backgrounds:Sr(n),...u?{startup:u}:{},palettes:i.map((S)=>Ge(S,r))}));let b=Fi(n,t),F=ct(or(b)?Vr(b,"utf8"):"",Au(m));if(F!==void 0)s(b,F);continue}let{file:g,body:d}=ad(h,n,u),w=or(g)?Vr(g,"utf8"):"";if(h==="alacritty"&&w!==""&&!w.includes("# ttheme begin"))continue;Le(Je(g),{recursive:!0}),zr(g,ot(w,d)),o.push(g)}let c=bn(n,"ttheme","palettes.zsh");return s(c,ai(i,u,e.terminals)),vi(`${c}.zwc`,{force:!0}),o}function yi(n,r,e,t,i=wt()){let o=[];for(let s of e)for(let u of r.palettes.filter((c)=>t.includes(c.name)))for(let{file:c}of Rc(s,Ge(u,r))){let h=bn(Ei(s,n,i),c);if(or(h))vi(h,{force:!0}),o.push(h)}return o}import{mkdirSync as Uc,readFileSync as Qc,writeFileSync as Wc}from"node:fs";import{dirname as Zc}from"node:path";import{isMainThread as wd,parentPort as qc,Worker as pd}from"node:worker_threads";var dd=/(?:^|[^0-9a-f])([0-9a-f]{32})(?:[^0-9a-f]|$)/i,md=[[/yande\.re\/post\/show\/(\d+)/,"yande"],[/konachan\.(?:com|net)\/post\/show\/(\d+)/,"konachan"],[/danbooru\.donmai\.us\/(?:posts|post\/show)\/(\d+)/,"danbooru"]];function Ii(n){let r=/(\d+)_p(\d+)/.exec(n.source);return[...n.md5?[`md5:${n.md5}`]:[],...r&&n.source.includes("pximg")?[`pixiv:${r[1]}_p${r[2]}`]:[]]}function Lc(n,r){let e=dd.exec(r.source)?.[1]?.toLowerCase();return[`post:${n.key}:${r.id}`,...r.md5?[`md5:${r.md5}`]:[],...e&&e!==r.md5?[`md5:${e}`]:[],...md.flatMap(([t,i])=>{let o=t.exec(r.source)?.[1];return o?[`post:${i}:${Number(o)}`]:[]}),...r.family?[`family:${n.key}:${r.family}`]:[]]}function Jc(n,r){let e=n.owner||n.artist;return e!==""&&e===(r.owner||r.artist)&&n.width===r.width&&n.height===r.height}function Kc(n){let t=[];for(let o=0;o<8;o++){let s=Math.floor(o*n.height/8),u=Math.max(s+1,Math.floor((o+1)*n.height/8));for(let c=0;c<9;c++){let h=Math.floor(c*n.width/9),f=Math.max(h+1,Math.floor((c+1)*n.width/9)),l=0;for(let g=s;g<u;g++)for(let d=h;d<f;d++){let w=(g*n.width+d)*4,m=n.data[w+3]/255,b=0.299*n.data[w]+0.587*n.data[w+1]+0.114*n.data[w+2];l+=b*m+255*(1-m)}t.push(l/((f-h)*(u-s)))}}let i=0n;for(let o=0;o<8;o++)for(let s=0;s<8;s++)i=i<<1n|(t[o*9+s]>t[o*9+s+1]?1n:0n);return i.toString(16).padStart(16,"0")}function $d(n,r){let e=BigInt(`0x${n}`)^BigInt(`0x${r}`),t=0;while(e>0n)t+=Number(e&1n),e>>=1n;return t}function Pc(n,r){if(n.width<=0||n.height<=0||r.width<=0||r.height<=0)return!1;return Math.abs(Math.log(n.width/n.height/(r.width/r.height)))<0.01&&$d(n.hash,r.hash)<=2}var bd={thumb:"tile",match:"tile",show:"view",backdrop:"view"};function kd(n){let r=Ks(new Uint8Array(Qc(n.from)),ii);if(n.job==="backdrop")return tu(n.home,n.colors,n.tone,r,{...n.origin,bytes:new Uint8Array(Qc(n.source))},n),0;if(n.job==="match")return{match:Sc(r,n.colors),hash:Kc(r)};if(n.job==="thumb")return Uc(Zc(n.to),{recursive:!0}),Wc(n.to,Zr(Us(r,n.width,n.height))),0;let e=pe(r);return Uc(Zc(n.to),{recursive:!0}),Wc(n.to,Zr(Ys(r,n.colors,n.tone,n.width,n.height))),e}function Md(n){n.on("message",(r)=>{try{n.postMessage({id:r.id,value:kd(r)})}catch(e){n.postMessage({id:r.id,error:e instanceof Error?e.message:String(e)})}})}class Ac{worker;next=1;waiting=new Map;send(n){let r=this.next++;return new Promise((e,t)=>{let i=this.open();this.waiting.set(r,{ok:e,no:t}),i.ref(),i.postMessage({...n,id:r})})}close(){this.worker?.terminate(),this.worker=void 0,this.drop(Error("renderer closed"))}open(){if(this.worker)return this.worker;let n=new pd(import.meta.filename);n.unref(),n.on("message",({id:e,value:t,error:i})=>{let o=this.waiting.get(e);if(this.waiting.delete(e),this.waiting.size===0)n.unref();if(i!==void 0)o?.no(Error(i));else o?.ok(t)});let r=(e)=>{if(this.worker===n)this.worker=void 0;this.drop(e instanceof Error?e:Error("renderer stopped"))};return n.on("error",r),n.on("exit",()=>r(void 0)),this.worker=n,n}drop(n){for(let r of this.waiting.values())r.no(n);this.waiting.clear()}}class Si{lines=new Map;run(n){let r=bd[n.job],e=this.lines.get(r);if(!e)e=new Ac,this.lines.set(r,e);return e.send(n)}close(){for(let n of this.lines.values())n.close();this.lines.clear()}}if(!wd&&qc)Md(qc);import{connect as Ed,createServer as vd}from"node:net";var Fd=20,Xc=22;function Ni(n){let r=new Uint8Array(n.reduce((t,i)=>t+i.length,0)),e=0;for(let t of n)r.set(t,e),e+=t.length;return r}function yd(n,r=Fd){let e=n.subarray(5);if(n[0]!==Xc||e.length<2)return[n];let t=Math.max(1,Math.min(r,e.length-1)),i=(o)=>Ni([Uint8Array.from([n[0],n[1],n[2],o.length>>8,o.length&255]),o]);return[i(e.subarray(0,t)),i(e.subarray(t))]}function Id(n,r,e,t){let i=Ed(e,r,()=>{i.setNoDelay(!0),n.write(`HTTP/1.1 200 Connection Established\r
135
+ `)}`);return t.palettes.filter((o)=>n.includes(o.name))}function uh(t,n){let e=t==="wezterm"?"colors":"themes";return(sm[t].emit?.(n)??[]).flatMap((r)=>{let[,i,o]=r.path.split("/");return i===e&&o!==void 0?[{file:o,content:r.content}]:[]})}function Kr(t){return process.platform==="darwin"?mt(t,".warp","themes"):mt(process.env.XDG_DATA_HOME??mt(t,".local","share"),"warp-terminal","themes")}function Lr(t,n,e){if(t==="warp")return Kr(e);return mt(n,t,t==="wezterm"?"colors":"themes")}function cm(t,n){return process.platform==="darwin"?mt(t,".warp","settings.toml"):mt(n,"warp-terminal","settings.toml")}var um='"dark"',hm="setTimeout(() => { const fs = require('node:fs'); const [file, next, seen] = process.argv.slice(-3); if (fs.readFileSync(file, 'utf8') === seen) fs.writeFileSync(file, next) }, 1500)";function fm(t,n,e,r){let i=cm(n,t);if(!zt(i))return;let o=mt(t,"ttheme","warp.base"),s=Sn(i,"utf8"),c=uu(s),u=c?.includes('path = "ttheme-')===!0,h;if(e){if(!u&&!zt(o))Te(We(o),{recursive:!0}),Cn(o,c??"");h=hu(e)}else{if(!u)return;h=zt(o)&&Sn(o,"utf8")||um,qi(o,{force:!0})}let f=fu(s,h);if(f===s)return;if(r)im(process.execPath,["-e",hm,i,f,s],{detached:!0,stdio:"ignore"}).unref();else Cn(i,f);return i}function hh(t){return mt(t,"ttheme","kitty.py")}function Xi(t,n){let e=mt(n,".wezterm.lua");return zt(e)?e:mt(t,"wezterm","wezterm.lua")}function am(t){return mt(t,"Microsoft","Windows Terminal","Fragments","ttheme","ttheme.json")}function gm(t){return[mt(t,"Packages","Microsoft.WindowsTerminal_8wekyb3d8bbwe","LocalState","settings.json"),mt(t,"Packages","Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe","LocalState","settings.json"),mt(t,"Microsoft","Windows Terminal","settings.json")].filter((n)=>zt(n))}function lm(t){for(let n of t){let e=/"defaultProfile"\s*:\s*"(\{[0-9a-fA-F-]+\})"/.exec(Sn(n,"utf8"))?.[1];if(e)return e}return}function Yn(t){return t.startup&&t.palettes.includes(t.startup)?t.startup:t.palettes[0]}function dm(t,n,e){if(t==="ghostty")return{file:mt(n,"ghostty","config"),body:Dc(mt(n,"ttheme"),e)};return{file:mt(n,"kitty","kitty.conf"),body:iu(e,hh(n))}}function _i(t){return mt(t,"alacritty","alacritty.toml")}function mm(t,n){return n?mt(t,"alacritty","themes",`${n}.toml`):void 0}function fh(t,n,e,r,i){let o=En(t),s=e.map((h)=>Ue(h,n)),c=new Map;for(let h of s){let f=ac(o,h.name,i);if(f)c.set(h.name,f)}let u=new Set(qn(e).map((h)=>h.name));return Co(s.filter((h)=>u.has(h.name)),c,s.find((h)=>h.name===hn(r)),r.itermBase)}function Vn(t,n=Pr()){let e=Yt(t);if(!e.terminals.includes("iterm2"))return;let r=Pt(t),i=oh(n);Te(We(i),{recursive:!0}),Cn(i,fh(t,r,ch(r,e.palettes),e,n))}function Xe(t,n,e,r=Pr()){let i=ch(n,e.palettes),o=[],s=(h,f)=>{if(o.push(h),zt(h)&&Sn(h,"utf8")===f)return!1;return Te(We(h),{recursive:!0}),Cn(h,f),!0},c=hn(e);for(let h of e.terminals){if(h==="iterm2"){s(oh(r),fh(t,n,i,e,r));continue}if(h==="windows-terminal"){if(e.wtHome){let p=gm(e.wtHome),l=i.map((v)=>Ue(v,n)),k=ji(l,e.wtProfile??lm(p),c);if(s(am(e.wtHome),k)){let v=new Date;for(let I of p)om(I,v,v)}}continue}let f=c!==void 0&&h==="warp"&&!zt(mt(Kr(r),`ttheme-${c}.yaml`)),a=h==="warp"?fm(t,r,c,f):void 0;for(let p of i)for(let{file:l,content:k}of uh(h,Ue(p,n)))s(mt(Lr(h,t,r),l),k);if(h==="warp"){if(a)o.push(a);continue}if(h==="wezterm"){let p=mt(t,"ttheme","wezterm.lua");s(p,lu({path:p,colors:Lr("wezterm",t,r),backgrounds:En(t),...c?{startup:c}:{},palettes:i.map((v)=>Ue(v,n))}));let l=Xi(t,r),k=br(zt(l)?Sn(l,"utf8"):"",ou(p));if(k!==void 0)s(l,k);continue}if(h==="alacritty"){let p=_i(t),l=$r(zt(p)?Sn(p,"utf8"):"",mm(t,c));if(l!==void 0)s(p,l);continue}if(h==="kitty")s(hh(t),zo({themes:Lr("kitty",t,r),backgrounds:En(t)}));let{file:g,body:d}=dm(h,t,c);s(g,je(zt(g)?Sn(g,"utf8"):"",d))}let u=mt(t,"ttheme","palettes.zsh");return Te(We(u),{recursive:!0}),Cn(u,Oi(i,c,e.terminals)),o.push(u),qi(`${u}.zwc`,{force:!0}),o}function Ci(t,n,e,r,i=Pr()){let o=[];for(let s of e)for(let c of n.palettes.filter((u)=>r.includes(u.name)))for(let{file:u}of uh(s,Ue(c,n))){let h=mt(Lr(s,t,i),u);if(zt(h))qi(h,{force:!0}),o.push(h)}return o}import{mkdirSync as mh,readFileSync as ph,writeFileSync as wh}from"node:fs";import{dirname as $h}from"node:path";import{isMainThread as bm,parentPort as bh,Worker as km}from"node:worker_threads";var pm=/(?:^|[^0-9a-f])([0-9a-f]{32})(?:[^0-9a-f]|$)/i,wm=[[/yande\.re\/post\/show\/(\d+)/,"yande"],[/konachan\.(?:com|net)\/post\/show\/(\d+)/,"konachan"],[/danbooru\.donmai\.us\/(?:posts|post\/show)\/(\d+)/,"danbooru"]];function zi(t){let n=/(\d+)_p(\d+)/.exec(t.source);return[...t.md5?[`md5:${t.md5}`]:[],...n&&t.source.includes("pximg")?[`pixiv:${n[1]}_p${n[2]}`]:[]]}function ah(t,n){let e=pm.exec(n.source)?.[1]?.toLowerCase();return[`post:${t.key}:${n.id}`,...n.md5?[`md5:${n.md5}`]:[],...e&&e!==n.md5?[`md5:${e}`]:[],...wm.flatMap(([r,i])=>{let o=r.exec(n.source)?.[1];return o?[`post:${i}:${Number(o)}`]:[]}),...n.family?[`family:${t.key}:${n.family}`]:[]]}function gh(t,n){let e=t.owner||t.artist;return e!==""&&e===(n.owner||n.artist)&&t.width===n.width&&t.height===n.height}function lh(t){let r=[];for(let o=0;o<8;o++){let s=Math.floor(o*t.height/8),c=Math.max(s+1,Math.floor((o+1)*t.height/8));for(let u=0;u<9;u++){let h=Math.floor(u*t.width/9),f=Math.max(h+1,Math.floor((u+1)*t.width/9)),a=0;for(let g=s;g<c;g++)for(let d=h;d<f;d++){let p=(g*t.width+d)*4,l=t.data[p+3]/255,k=0.299*t.data[p]+0.587*t.data[p+1]+0.114*t.data[p+2];a+=k*l+255*(1-l)}r.push(a/((f-h)*(c-s)))}}let i=0n;for(let o=0;o<8;o++)for(let s=0;s<8;s++)i=i<<1n|(r[o*9+s]>r[o*9+s+1]?1n:0n);return i.toString(16).padStart(16,"0")}function $m(t,n){let e=BigInt(`0x${t}`)^BigInt(`0x${n}`),r=0;while(e>0n)r+=Number(e&1n),e>>=1n;return r}function dh(t,n){if(t.width<=0||t.height<=0||n.width<=0||n.height<=0)return!1;return Math.abs(Math.log(t.width/t.height/(n.width/n.height)))<0.01&&$m(t.hash,n.hash)<=2}var Em={thumb:"tile",match:"tile",show:"view",backdrop:"view"};function Mm(t){let n=Bs(new Uint8Array(ph(t.from)),Rn);if(t.job==="backdrop")return bc(t.home,t.colors,t.tone,n,{...t.origin,bytes:new Uint8Array(ph(t.source))},t),0;if(t.job==="match")return{match:rh(n,t.colors),hash:lh(n)};if(t.job==="thumb")return mh($h(t.to),{recursive:!0}),wh(t.to,Qn(tc(n,t.width,t.height))),0;let e=Me(n);return mh($h(t.to),{recursive:!0}),wh(t.to,Qn(fc(n,t.colors,t.tone,t.width,t.height))),e}function vm(t){t.on("message",(n)=>{try{t.postMessage({id:n.id,value:Mm(n)})}catch(e){t.postMessage({id:n.id,error:e instanceof Error?e.message:String(e)})}})}class kh{worker;next=1;waiting=new Map;send(t){let n=this.next++;return new Promise((e,r)=>{let i=this.open();this.waiting.set(n,{ok:e,no:r}),i.ref(),i.postMessage({...t,id:n})})}close(){this.worker?.terminate(),this.worker=void 0,this.drop(Error("renderer closed"))}open(){if(this.worker)return this.worker;let t=new km(import.meta.filename);t.unref(),t.on("message",({id:e,value:r,error:i})=>{let o=this.waiting.get(e);if(this.waiting.delete(e),this.waiting.size===0)t.unref();if(i!==void 0)o?.no(Error(i));else o?.ok(r)});let n=(e)=>{if(this.worker===t)this.worker=void 0;this.drop(e instanceof Error?e:Error("renderer stopped"))};return t.on("error",n),t.on("exit",()=>n(void 0)),this.worker=t,t}drop(t){for(let n of this.waiting.values())n.no(t);this.waiting.clear()}}class Yi{lines=new Map;run(t){let n=Em[t.job],e=this.lines.get(n);if(!e)e=new kh,this.lines.set(n,e);return e.send(t)}close(){for(let t of this.lines.values())t.close();this.lines.clear()}}if(!bm&&bh)vm(bh);import{connect as ym,createServer as Sm}from"node:net";var Fm=20,Eh=22;function Vi(t){let n=new Uint8Array(t.reduce((r,i)=>r+i.length,0)),e=0;for(let r of t)n.set(r,e),e+=r.length;return n}function Im(t,n=Fm){let e=t.subarray(5);if(t[0]!==Eh||e.length<2)return[t];let r=Math.max(1,Math.min(n,e.length-1)),i=(o)=>Vi([Uint8Array.from([t[0],t[1],t[2],o.length>>8,o.length&255]),o]);return[i(e.subarray(0,r)),i(e.subarray(r))]}function Nm(t,n,e,r){let i=ym(e,n,()=>{i.setNoDelay(!0),t.write(`HTTP/1.1 200 Connection Established\r
83
136
  \r
84
- `);let o=t,s=!1,u=(c)=>{if(s){i.write(c);return}if(o=Ni([o,c]),o.length<5)return;let h=o[3]*256+o[4];if(o[0]!==Xc){s=!0,i.write(o);return}if(o.length<5+h)return;s=!0;let[f,l]=yd(o.subarray(0,5+h));i.write(f),setTimeout(()=>{if(l)i.write(l);i.write(o.subarray(5+h))},10)};if(n.on("data",u),o.length>0){let c=o;o=new Uint8Array(0),u(c)}i.pipe(n)});i.on("error",()=>n.destroy()),i.on("close",()=>n.destroy()),n.on("error",()=>i.destroy()),n.on("close",()=>i.destroy())}function Sd(n){n.setNoDelay(!0);let r=new Uint8Array(0),e=(t)=>{r=Ni([r,t]);let i=Buffer.from(r).toString("latin1"),o=i.indexOf(`\r
137
+ `);let o=r,s=!1,c=(u)=>{if(s){i.write(u);return}if(o=Vi([o,u]),o.length<5)return;let h=o[3]*256+o[4];if(o[0]!==Eh){s=!0,i.write(o);return}if(o.length<5+h)return;s=!0;let[f,a]=Im(o.subarray(0,5+h));i.write(f),setTimeout(()=>{if(a)i.write(a);i.write(o.subarray(5+h))},10)};if(t.on("data",c),o.length>0){let u=o;o=new Uint8Array(0),c(u)}i.pipe(t)});i.on("error",()=>t.destroy()),i.on("close",()=>t.destroy()),t.on("error",()=>i.destroy()),t.on("close",()=>i.destroy())}function Om(t){t.setNoDelay(!0);let n=new Uint8Array(0),e=(r)=>{n=Vi([n,r]);let i=Buffer.from(n).toString("latin1"),o=i.indexOf(`\r
85
138
  \r
86
- `);if(o===-1)return;n.off("data",e);let s=/^CONNECT ([^ :]+):(\d+)/.exec(i);if(!s){n.end(`HTTP/1.1 405 Method Not Allowed\r
139
+ `);if(o===-1)return;t.off("data",e);let s=/^CONNECT ([^ :]+):(\d+)/.exec(i);if(!s){t.end(`HTTP/1.1 405 Method Not Allowed\r
87
140
  \r
88
- `);return}Id(n,s[1],Number(s[2]),r.subarray(o+4))};n.on("data",e),n.on("error",()=>n.destroy())}function Tc(){let n=vd(Sd);return new Promise((r,e)=>{n.once("error",e),n.listen(0,"127.0.0.1",()=>{r({port:n.address().port,close:()=>{n.close(),n.unref()}})})})}var Dr=[{name:"TTHEME_FIND_RATING",label:"rating",choices:Ee,multi:{read:et}},{name:"TTHEME_FIND_BLOCK",label:"block",choices:Hr,multi:{read:tt,none:"none"}},{name:"TTHEME_FIND_POSTS",label:"posts",choices:["all","cutouts"]},{name:"TTHEME_FIND_SOLO",label:"solo",choices:["on","off"]},{name:"TTHEME_FIND_ORDER",label:"order",choices:["fit","newest","score"]},{name:"TTHEME_FIND_SETS",label:"sets",choices:["fold","show"]},...wi()?[{name:"TTHEME_FIND_REMOVE_BG",label:"remove bg",choices:["on","off"]}]:[]];function Rd(n,r){if(n.multi)return n.multi.read(r).join(" ")||n.multi.none;return n.choices.find((e)=>e===r)??n.choices[0]}var Gd=["fit","newest","score"];function zc(n){return Gd.find((r)=>r===n)??"fit"}function Ld(n){return n.length>=2&&!/^\d+$/.test(n)&&!n.includes("://")&&!/^[\w.]+:\d+$/.test(n)}var Yc=12,Jd=4,Kd=150,Cc=12,Pd=2,Ud=150,Qd=30,Wd=1280,_c=2,Zd=3,qd=8;function Oi(n,r){return{key:n,groups:[],sources:[],queue:[],rounds:0,roundOf:new Map,last:new Map,kin:new Map,kindred:new Map,shapes:[],seen:new Set,same:new Map,checked:0,total:0,focus:0,top:0,searching:r}}function bt(n){if(!(n instanceof Error))return String(n);if(n instanceof AggregateError&&n.errors[0])return bt(n.errors[0]);if(n.cause)return bt(n.cause);let r=n.code;if(typeof r==="string")return r;let e=(n.message||n.name).split(".")[0]??"";return e.length>56?`${e.slice(0,55)}…`:e}function ji(n,r){return`${n}: ${bt(r)}`}function Bc(n){return n.width*n.height}function xc(n){return`${n.id}-${Nd("sha1").update(n.preview).digest("hex").slice(0,8)}`}function Ad(n){let r=n.lastIndexOf("\x1B");return r!==-1&&/^\[?[0-9;]*$/.test(n.slice(r+1))}function Ri(n,r){try{return JSON.parse(rh(ar(Mr(n),r),"utf8"))}catch{return{}}}function Gi(n,r,e){Li(Mr(n),{recursive:!0}),Ji(ar(Mr(n),r),`${JSON.stringify(e)}
89
- `)}class eh{view;tone;session=new AbortController;cell={w:0,h:0};cols=process.stdout.columns||80;rows=process.stdout.rows||24;gen=0;pumping=0;boards=new Map;board;posts=new Map;thumbPath=new Map;looking=new Map;looked=new Map;matched=new Map;aheading=!1;pages=new Map;tab=0;values=new Map(Dr.map((n)=>[n.name,Rd(n,process.env[n.name])]));direction=1;prefetching=0;inflight=new Map;owners=new Map;probed=new Map;unsaved=new Set;thumbQueue=[];thumbing=0;clarity=new Map;renders=new Si;sent=new Map;placed=new Map;current;fetch;settle;partial;suggestTimer;suggesting;input="";probeWait;done;dirty=!1;unblock=!1;scratch=Hd(ar(jd(),"ttheme-find-"));home;catalog;entry;constructor(n,r,e,t){this.home=n,this.catalog=r,this.entry=e,this.tone=De(e,e.signatureSlots),this.view={palette:e.name,tag:t,site:this.tabName,siteAnsi:this.tabAnsi,nextSite:this.nextTabName,preset:this.setting("TTHEME_FIND_POSTS")==="all"?"all":"cutouts",order:zc(this.setting("TTHEME_FIND_ORDER")),solo:this.setting("TTHEME_FIND_SOLO")==="on",rating:et(this.setting("TTHEME_FIND_RATING")),block:tt(this.setting("TTHEME_FIND_BLOCK")),sets:this.setting("TTHEME_FIND_SETS")==="show"?"show":"fold",unblocked:process.env.TTHEME_FIND_PROXY!==void 0,settings:Dr.map((i)=>({label:i.label,choices:[...i.choices],value:this.setting(i.name),multi:i.multi&&{none:i.multi.none},cursor:0})),colors:{cursor:e.cursor,selection:e.selection,ansi:e.ansi},tiles:[],installed:[],checked:0,total:0,searching:t!=="",focus:0,top:0,mode:"grid",help:!1,editing:t===""?"":void 0},this.board=Oi(this.boardKey,t!==""),this.boards.set(this.board.key,this.board)}get signal(){return this.session.signal}get site(){return this.tab===0?void 0:Mn[this.tab-1]}get sites(){return this.site?[this.site]:Mn}get tabName(){return this.site?.name??"all"}get tabAnsi(){return this.site?.ansi??Jd}get nextTabName(){let n=(this.tab+1)%(Mn.length+1);return n===0?"all":Mn[n-1].name}frame(){return{w:this.cols*(this.cell.w||10),h:this.rows*(this.cell.h||20)}}setting(n){return this.values.get(n)}get boardKey(){return`${this.site?.key??"all"}|${this.view.preset}|${this.view.order}`}origPath(n,r,e){return ar(Mr(n),"orig",`${r}.${e}`)}previewPath(n){return ar(Mr(n.site),"thumb",`${xc(n.post)}.${ve(n.post.preview)}`)}tileOf(n,r){let{site:e,post:t}=n,i=tr(e,t.id),o=ye(t)??t;return{id:t.id,key:i,site:e.name,siteAnsi:e.ansi,width:o.width,height:o.height,reduced:o!==t,owner:t.owner,artist:t.artist,score:t.score,variants:r,origin:si(t.source),mates:this.owners.get(e.key)?.get(t.owner)??[],thumb:this.thumbPath.get(i)}}show(){let n=this.view,r=this.board;n.tiles=r.groups.flatMap((e)=>e.open?e.posts.map((t)=>this.tileOf(t,0)):[this.tileOf(e.posts[0],e.posts.length)]),n.checked=r.checked,n.total=r.total,n.searching=r.searching,n.note=r.note,n.focus=Math.max(0,Math.min(r.focus,n.tiles.length-1)),n.top=r.top}syncSite(){let n=this.view;n.site=this.tabName,n.siteAnsi=this.tabAnsi,n.nextSite=this.nextTabName}async run(){let{stdin:n,stdout:r}=process;n.setRawMode(!0),n.resume(),n.on("data",this.onData),r.on("resize",this.onResize),this.write("\x1B[?25l\x1B[?7l\x1B[H\x1B[K\x1B[2H\x1B[J\x1B[H");let e=new Promise((s)=>{this.done=s}),t=setInterval(this.onClock,250),i=await this.probe();if(i){if(this.cell=i,this.view.tag)this.search()}else this.view.searching=!1,this.view.error="this terminal does not report its cell size — find needs kitty graphics";this.draw();let o=await e;return this.session.abort(),this.fetch?.abort(),clearTimeout(this.settle),clearTimeout(this.partial),this.quietSuggest(),clearInterval(t),n.off("data",this.onData),r.off("resize",this.onResize),this.write("\x1B_Ga=d,d=A,q=2\x1B\\\x1B[H\x1B[K\x1B[2H\x1B[J\x1B[H"),n.setRawMode(!1),n.pause(),this.saveProbes(),this.renders.close(),Hi(this.scratch,{recursive:!0,force:!0}),vu(),o}write(n){process.stdout.write(n)}get saved(){return this.view.saved}finish(n){this.done?.(n===2&&this.saved?0:n)}probe(){return new Promise((n)=>{let r=setTimeout(()=>{this.probeWait=void 0,n(null)},1000);this.probeWait=(e)=>{clearTimeout(r),this.probeWait=void 0,n(e)},this.write(mc)})}onData=(n)=>{this.input+=n.toString("utf8");for(let r=ki(this.input);r;r=ki(this.input))this.input=r.rest,this.probeWait?.(r.cell);if(this.probeWait)return;if(clearTimeout(this.partial),Ad(this.input)){this.partial=setTimeout(this.flushKeys,Qd);return}this.flushKeys()};flushKeys=()=>{let n=dc(this.input);this.input="";for(let r of n)this.key(r)};onClock=()=>{let n=this.sites.reduce((t,i)=>br(i)>br(t)?i:t),r=Math.ceil((br(n)-Date.now())/1000),e=r>0?r:void 0;if(e!==this.view.waiting)this.view.waiting=e,this.view.slow=n.name,this.draw()};onResize=()=>{if(this.cols=process.stdout.columns||this.cols,this.rows=process.stdout.rows||this.rows,this.scroll(),this.view.mode==="try"&&this.current)this.reveal();this.pump(),this.draw()};key(n){let r=this.view;if(n==="ctrl-c"){this.finish(2);return}if(r.installing!==void 0)return;if(r.asking!==void 0){this.askKey(n);return}if(r.editing!==void 0){this.editKey(n);return}if(r.panel!==void 0){this.panelKey(n);return}if(r.help){if(n==="?"||n==="esc")r.help=!1,this.draw();return}if(this.cols<Rr.cols||this.rows<Rr.rows){if(n==="esc")this.finish(2);return}if(n==="?"){r.help=!0,this.draw();return}if(r.mode==="try"){this.tryKey(n);return}this.gridKey(n)}gridKey(n){let r=this.view,{perRow:e,rowsVis:t}=Tr(this.cols,this.rows),o={left:-1,right:1,up:-e,down:e,pgup:-e*t,pgdn:e*t,home:-r.focus,end:r.tiles.length}[n];if(o!==void 0){this.focus(r.focus+o);return}if(n==="enter"&&r.tiles[r.focus]){r.mode="try",r.error=void 0,this.select();return}if(n==="c"){r.preset=r.preset==="cutouts"?"all":"cutouts",this.turn();return}if(n==="tab"){this.tab=(this.tab+1)%(Mn.length+1),this.syncSite(),this.turn();return}if(n==="/"){r.editing="",this.draw();return}if(n===" "){this.unfold();return}if(n==="o"){this.openPage();return}if(n==="s"){r.panel=0,this.draw();return}if(n==="esc")this.finish(2)}panelKey(n){let r=this.view,e=r.panel??0,t=r.settings[e];if(n==="up"||n==="down"){r.panel=Math.max(0,Math.min(r.settings.length-1,e+(n==="up"?-1:1))),this.draw();return}if((n==="left"||n==="right")&&t){let i=n==="left"?-1:1;if(t.multi)t.cursor=(t.cursor+i+t.choices.length)%t.choices.length;else{let o=t.choices.indexOf(t.value);t.value=t.choices[(o+i+t.choices.length)%t.choices.length]}this.draw();return}if(n===" "&&t?.multi){let i=t.value.split(" "),o=t.choices.filter((u,c)=>c===t.cursor?!i.includes(u):i.includes(u)),s=t.multi.none;if(o.length>0||s!==void 0)t.value=o.length>0?o.join(" "):s,this.draw();return}if(n==="esc"){r.settings.forEach((i,o)=>{i.value=this.setting(Dr[o]?.name??"")}),r.panel=void 0,this.draw();return}if(n==="enter"||n==="alt-c")r.panel=void 0,this.adopt()}adopt(){let n=this.view,r=Dr.map((t)=>this.setting(t.name));n.settings.forEach((t,i)=>{let o=Dr[i];if(o)this.values.set(o.name,t.value)});let e=Dr.filter((t,i)=>this.setting(t.name)!==r[i]);if(e.length===0){this.draw();return}this.save(e),n.rating=et(this.setting("TTHEME_FIND_RATING")),n.block=tt(this.setting("TTHEME_FIND_BLOCK")),n.sets=this.setting("TTHEME_FIND_SETS")==="show"?"show":"fold",n.preset=this.setting("TTHEME_FIND_POSTS")==="all"?"all":"cutouts",n.order=zc(this.setting("TTHEME_FIND_ORDER")),n.solo=this.setting("TTHEME_FIND_SOLO")==="on",this.boards.clear(),this.current=void 0,n.shown=void 0,n.mode="grid",this.search()}save(n){this.store(n.map((r)=>[r.name,this.setting(r.name)]))}store(n){let r=ar(this.home,"ttheme","config.zsh");try{let e=xr(r)?rh(r,"utf8"):"";return Ji(r,n.reduce((t,[i,o])=>ut(t,i,o),e)),!0}catch(e){return this.view.error=e instanceof Error?e.message:String(e),!1}}askKey(n){let r=this.view;if(n==="y"){if(r.asking=void 0,this.store([["TTHEME_FIND_UNBLOCK","1"]])){this.unblock=!0,this.finish(0);return}this.draw();return}if(n==="n"||n==="esc")r.asking=void 0,this.draw()}editKey(n){let r=this.view,e=r.editing??"",t=r.suggest??[];if((n==="up"||n==="down")&&t.length>0){let i=r.pick??-1,o=n==="down"?Math.min(t.length-1,i+1):i-1;r.pick=o<0?void 0:o,this.draw();return}if(n==="esc"||n==="enter")this.quietSuggest();if(n==="esc"){if(r.editing=void 0,r.tag===""){this.finish(2);return}this.draw();return}if(n==="enter"){let i=r.pick===void 0?void 0:t[r.pick],o=i?e.replace(/\S*$/,i.value):e;if(r.editing=void 0,r.suggest=void 0,r.pick=void 0,o.trim()){this.commit(o.trim());return}if(r.tag===""){this.finish(2);return}this.draw();return}if(n==="backspace"){r.editing=e.slice(0,-1),this.suggest(),this.draw();return}if(n.length===1&&n>=" ")r.editing=e+n,this.suggest(),this.draw()}quietSuggest(){clearTimeout(this.suggestTimer),this.suggesting?.abort(),this.suggesting=void 0}suggest(){this.quietSuggest();let n=this.view;n.pick=void 0;let r=/\S*$/.exec(n.editing??"")?.[0]??"";if(!Ld(r)){n.suggest=void 0;return}let e=[...new Map(cc(this.catalog.palettes,this.entry,r).map((i)=>[i.booru,{value:i.booru,count:0,palette:i.name}])).values()].slice(0,Zd);n.suggest=e.length>0?e:void 0;let t=new AbortController;this.suggesting=t,this.suggestTimer=setTimeout(async()=>{try{let i=await Nu(r,AbortSignal.any([this.signal,t.signal]));if(this.suggesting===t&&n.editing!==void 0){let o=new Map(i.map((u)=>[u.value,u.count])),s=new Set(e.map((u)=>u.value));n.suggest=[...e.map((u)=>({...u,count:o.get(u.value)??0})),...i.filter((u)=>!s.has(u.value))].slice(0,qd),n.pick=n.pick!==void 0&&n.pick<e.length?n.pick:void 0,this.draw()}}catch{}},Kd)}async commit(n){let r=wu(n,this.site??Mn[0]);if(r){await this.jump(r.site,r.id);return}this.view.tag=n,this.boards.clear(),await this.search()}async jump(n,r){let e=++this.gen;this.tab=Mn.indexOf(n)+1,this.syncSite(),this.current=void 0,this.view.shown=void 0,this.view.error=void 0;let t=Oi(`${n.key}|post:${r}`,!0);this.board=t,this.boards.set(t.key,t),this.show(),this.draw();try{let i=await ui(n,r,this.signal);if(e!==this.gen)return;if(t.searching=!1,!i)t.error=`${n.name} has no post ${r}`,this.view.error=t.error;else{let o={site:n,post:i};this.posts.set(tr(n,i.id),o),t.groups=[{posts:[o],open:!1}],t.checked=1,t.total=1,this.thumbQueue.push(o),this.thumbs(),this.view.mode="try"}if(this.show(),i)this.select();this.draw()}catch(i){this.fail(e,i,n)}}async turn(){this.fetch?.abort(),this.current=void 0,this.view.shown=void 0;let n=this.boards.get(this.boardKey);if(!n){await this.search();return}this.gen++,this.board=n,this.view.error=n.error,this.show(),this.draw(),await this.pump()}unfold(){let n=this.view,r=0;for(let e of this.board.groups){let t=e.open?e.posts.length:1;if(n.focus<r+t){if(e.posts.length<2)return;e.open=!e.open,this.board.focus=r;for(let i of e.posts)if(!this.thumbPath.has(tr(i.site,i.post.id)))this.thumbQueue.push(i);this.thumbs(),this.show(),this.scroll(),this.draw();return}r+=t}}openPage(){let n=this.view.tiles[this.view.focus],r=n&&this.posts.get(n.key);if(!r)return;let e=process.platform==="darwin"?"open":"xdg-open";try{nh(e,[r.site.pageUrl(r.post.id)],{stdio:"ignore",detached:!0}).unref()}catch{}}tryKey(n){let r=this.view;if(n==="left"||n==="right"){this.direction=n==="left"?-1:1,this.focus(r.focus+this.direction);return}if(n==="o"){this.openPage();return}if(n==="x"){this.swap();return}if(n==="enter"){this.install();return}if(n==="esc")this.fetch?.abort(),clearTimeout(this.settle),r.fetching=void 0,r.mode="grid",r.error=void 0,this.draw()}focus(n){let r=this.view;if(r.tiles.length===0)return;let e=Math.max(0,Math.min(r.tiles.length-1,n));if(e===r.focus)return;if(r.focus=e,this.board.focus=e,this.scroll(),this.pump(),r.mode==="try")this.select();this.draw()}scroll(){let n=this.view,{perRow:r,rowsVis:e}=Tr(this.cols,this.rows),t=Math.floor(n.focus/r);if(t<n.top)n.top=t;if(t>n.top+e-1)n.top=t-e+1;this.board.top=n.top}query(n){let r=this.view,e=r.tag===this.entry.booru?hc(this.entry,n.key):[r.tag];if(e.length===0)return;let t=e.length>1,i=r.preset==="cutouts"?n.cutouts:"",o=t&&i.includes("~"),s=[t?e.map((h)=>`~${h}`).join(" "):e[0],n.rate(this.view.rating),o?"":i,r.order==="score"?n.best:""].filter(Boolean),u=[],c=[];for(let h of s)if(oi([...u,h].join(" "))<=n.tagBudget)u.push(h);else c.push(h);return{tags:u.join(" "),notes:[...c.length>0?[`${n.name} takes ${n.tagBudget} tags — ${c.join(" ")} left out`]:[],...o?[`${n.name} ORs the names, so cutouts are told by the file`]:[]]}}async search(){let n=++this.gen,r=Oi(this.boardKey,!0);this.board=r,this.boards.set(r.key,r),this.view.error=void 0;let e=this.sites.flatMap((o)=>{let s=this.query(o);return s?[{site:o,...s}]:[]}),t=this.sites.filter((o)=>!e.some((s)=>s.site===o)),i=[...e.flatMap(({notes:o})=>o),...t.length>0?[`${this.entry.name} has no tag on ${t.map((o)=>o.name).join(", ")}`]:[]];if(r.note=i.length>0?i.join(" · "):void 0,e.length===0)r.searching=!1;this.show(),this.draw(),this.tally(n,r,e);try{let o=await Promise.all(e.map(async(s)=>({plan:s,owners:await this.mateOwners(s.site)})));if(n!==this.gen)return;r.sources=o.flatMap(({plan:{site:s,tags:u},owners:c})=>[...oi(u)+1<=s.tagBudget?[...c.keys()].map((h)=>({site:s,tags:`${u} user:${h}`,page:0,done:!1})):[],{site:s,tags:u,page:0,done:!1}]),this.show(),this.draw(),await this.pump()}catch(o){this.fail(n,o)}}async tally(n,r,e){let t=await Promise.allSettled(e.map(({site:i,tags:o})=>yu(i,o,this.signal)));if(n===this.gen)r.total=t.reduce((i,o)=>i+(o.status==="fulfilled"?o.value:0),0),this.show(),this.draw()}fail(n,r,e=this.site){if(n!==this.gen||this.signal.aborted)return;this.board.error=ji(e?.name??this.tabName,r),this.board.searching=!1,this.view.error=this.board.error,this.offer(e,r),this.show(),this.draw()}offer(n,r){if(n&&!this.view.unblocked&&th()&&bt(r)==="ECONNRESET")this.view.asking=n.name}drop(n,r,e){for(let t of n.sources)if(t.site===r)t.done=!0;n.note=[n.note,ji(r.name,e)].filter(Boolean).join(" · "),this.offer(r,e)}wants(){let{perRow:n,rowsVis:r}=Tr(this.cols,this.rows);return this.view.tiles.length<(this.board.top+r+_c)*n}need(){let{perRow:n,rowsVis:r}=Tr(this.cols,this.rows);return(r+_c)*n}live(n){return this.boards.get(n.key)===n}page(n,r,e){let t=`${n.key}|${r}|${e}`,i=this.pages.get(t);if(!i)i=Fu(n,r,e,this.signal).then((o)=>this.borrow(o)),this.pages.set(t,i),i.catch(()=>this.pages.delete(t));return i}async borrow(n){let r=n.filter((e)=>e.solo===void 0&&e.md5!=="");if(r.length>0)try{Iu(r,await Su(r.map((e)=>e.md5),this.signal))}catch{}return n}async round(n){let r=Mn.flatMap((u)=>{let c=n.sources.find((h)=>h.site===u&&!h.done);return c?[c]:[]}),e=await Promise.all(r.map(async(u)=>{try{return{source:u,posts:await this.page(u.site,u.tags,u.page)}}catch(c){if(n.sources.every((h)=>h.site===u.site)||this.signal.aborted)throw c;return this.drop(n,u.site,c),{source:u,posts:void 0}}}));if(!this.live(n))return;let t=[];for(let{source:u,posts:c}of e){if(!c)continue;u.page++,u.done=c.length<Nr;let h=n.last.get(u);for(let f of c){let l=h&&Jc(h.post,f)?h.set:`set:${u.site.key}:${f.id}`;h={post:f,set:l};let g=tr(u.site,f.id);if(n.seen.has(g))continue;n.seen.add(g);let d={site:u.site,post:f};if(this.eligible(d))n.kin.set(d,[l,...Lc(u.site,f)]),t.push(d);else n.checked++}if(h)n.last.set(u,h)}let i=this.dedupe(n,t),o=++n.rounds,s;if(this.view.order!=="fit")s=r.length>1?Ic(i):i;else{let u=$t(i,this.frame(),this.matched),c=u.slice(0,this.need());if(await this.looks(c),!this.live(n))return;s=[...$t(c,this.frame(),this.matched),...u.slice(c.length)]}for(let u of s)n.roundOf.set(u,o);n.queue.push(...s),this.ahead(n)}ahead(n){if(this.aheading||this.view.order!=="fit"||!this.live(n))return;let r=n.queue.slice(0,this.need()).filter((e)=>!this.looking.has(tr(e.site,e.post.id)));if(r.length===0)return;this.aheading=!0,this.looks(r).then(()=>{this.aheading=!1;for(let e of new Set(r.map((t)=>n.roundOf.get(t)??0)))this.resort(n,e);this.ahead(n)})}resort(n,r){let e=n.queue.flatMap((i,o)=>n.roundOf.get(i)===r?[o]:[]),t=$t(e.map((i)=>n.queue[i]),this.frame(),this.matched);e.forEach((i,o)=>{n.queue[i]=t[o]})}dedupe(n,r){let e=[];for(let t of r){let i=Ii(t.post),o=i.map((u)=>n.same.get(u)).find(Boolean);if(!o){for(let u of i)n.same.set(u,t);e.push(t);continue}if(n.checked++,Bc(t.post)<=Bc(o.post))continue;for(let u of[...i,...Ii(o.post)])n.same.set(u,t);let s=e.indexOf(o);if(s>=0){e[s]=t;continue}this.replace(n,o,t)}return e}replace(n,r,e){n.roundOf.set(e,n.roundOf.get(r)??0);let t=n.queue.indexOf(r);if(t>=0){n.queue[t]=e;return}for(let i of n.groups){let o=i.posts.indexOf(r);if(o>=0){i.posts[o]=e,this.posts.set(tr(e.site,e.post.id),e),this.thumbQueue.push(e),this.thumbs();return}}}async looks(n){let r=0;await Promise.all(Array.from({length:Cc},async()=>{while(r<n.length)await this.look(n[r++])}))}look(n){let r=tr(n.site,n.post.id),e=this.looking.get(r);if(!e)e=(async()=>{let t=this.previewPath(n);await this.cached(n.site,t,n.post.preview);let i=await this.renders.run({job:"match",from:t,colors:this.entry.signature});return this.looked.set(r,i),this.matched.set(n.post,i.match),i})().catch(()=>{return}),this.looking.set(r,e);return e}async pump(){let n=this.gen,r=this.board;if(this.pumping===n||r.sources.length===0)return;this.pumping=n;let e=[],t;try{r.searching=!0;while(n===this.gen){while(e.length<Yc&&r.queue.length>0&&this.wants()){let s=r.queue.shift();e.push({pick:s,passed:this.vet(s)})}if(this.ahead(r),!t&&r.queue.length<Yc&&r.sources.some((s)=>!s.done)&&this.wants()){let s=this.round(r).then(()=>{if(t===s)t=void 0});s.catch(()=>{}),t=s}let i=e.shift();if(!i){if(!t)break;await t,this.show(),this.draw();continue}let o=await i.passed;if(n!==this.gen)return;if(r.checked++,o)this.admit(i.pick);this.show(),this.draw()}if(n===this.gen)r.searching=!1,this.show(),this.draw()}catch(i){this.fail(n,i)}finally{if(this.saveProbes(),this.pumping===n)this.pumping=0}}eligible({site:n,post:r}){let e=ye(r);if(!ku(n,r,this.view.rating)||bu(r,this.view.block).length>0||!e)return!1;if(this.view.solo&&r.solo===!1)return!1;return this.view.preset==="all"?["png","jpg","jpeg"].includes(e.ext):r.ext==="png"}async vet(n){let[r]=await Promise.all([this.passes(n),this.look(n)]);return r}async passes({site:n,post:r}){return this.view.preset==="all"||n.vouched||this.transparent(n,r)}probes(n){let r=this.probed.get(n.key);if(!r)r=Ri(n,"probes.json"),this.probed.set(n.key,r);return r}async transparent(n,r){let e=this.probes(n),t=e[r.id];if(t!==void 0)return t;try{let i=(await Hu(n,r.file,this.signal))?.alpha===!0;return e[r.id]=i,this.unsaved.add(n.key),i}catch{return!1}}saveProbes(){for(let n of this.unsaved){let r=Mn.find((e)=>e.key===n);if(r)Gi(r,"probes.json",this.probes(r))}this.unsaved.clear()}admit(n){let{site:r,post:e}=n,t=this.board,i=tr(r,e.id);this.posts.set(i,n);let o=t.kin.get(n)??[],s=this.looked.get(i),u=s&&{hash:s.hash,width:e.width,height:e.height},c=this.view.sets==="fold"?this.kindred(t,o,u):void 0;if(c){if(c.posts.push(n),this.register(t,c,o,u),c.open)this.thumbQueue.push(n),this.thumbs();return}let h={posts:[n],open:!1};t.groups.push(h),this.register(t,h,o,u),this.thumbQueue.push(n),this.thumbs()}kindred(n,r,e){for(let t of r){let i=n.kindred.get(t);if(i)return i}return e&&n.shapes.find((t)=>Pc(t.shape,e))?.group}register(n,r,e,t){for(let i of e)if(!n.kindred.has(i))n.kindred.set(i,r);if(t)n.shapes.push({shape:t,group:r})}async mateOwners(n){let r=this.owners.get(n.key);if(r)return r;let e=iu(this.home),t=Ri(n,"owners.json"),i=this.catalog.palettes.flatMap((c)=>{let h=e.get(c.name);return c.group===this.entry.group&&c.name!==this.entry.name&&h?.site===n.key?[{name:c.name,id:h.id}]:[]}),o=await Promise.all(i.map(async(c)=>{let h=t[c.id];if(h!==void 0)return{...c,owner:h};try{return{...c,owner:(await ui(n,c.id,this.signal))?.owner??""}}catch{return}})),s=new Map;for(let c of o)if(c)t[c.id]=c.owner,s.set(c.name,c.owner);Gi(n,"owners.json",t);let u=Mu(s);return this.owners.set(n.key,u),u}async cached(n,r,e,t){if(xr(r))return Od(r).size;let i=this.inflight.get(r);if(i)return i;let o=(async()=>{let s=await Ou(n,e,this.signal,t);return Li(Vc(r),{recursive:!0}),Ji(r,s),s.length})();this.inflight.set(r,o);try{return await o}finally{this.inflight.delete(r)}}thumbs(){while(this.thumbing<Cc&&this.thumbQueue.length>0){let n=this.thumbQueue.shift();this.thumbing++,this.thumb(n).catch(()=>{}).finally(()=>{this.thumbing--,this.thumbs()})}}async thumb(n){let{site:r,post:e}=n,t=Un.cols*this.cell.w,i=Un.rows*this.cell.h,o=ar(Mr(r),"tile",`${xc(e)}-${t}x${i}.png`);if(!xr(o)){let s=this.previewPath(n);await this.cached(r,s,e.preview),await this.renders.run({job:"thumb",from:s,to:o,width:t,height:i})}this.thumbPath.set(tr(r,e.id),o),this.show(),this.draw()}select(){let n=this.view,r=n.tiles[n.focus];if(this.fetch?.abort(),clearTimeout(this.settle),n.fetching=void 0,!r)return;if(this.current?.key===r.key){this.reveal();return}this.settle=setTimeout(()=>void this.load(r),Ud),this.draw()}async load(n){let r=this.view,e=this.posts.get(n.key),t=e&&ye(e.post);if(!e||!t)return;let{site:i}=e,o=this.board,s=new AbortController;this.fetch=s;try{let u=this.origPath(i,n.id,t.ext);if(!xr(u))r.fetching={id:n.key,got:0,size:0},this.draw();let c=await this.cached(i,u,t.file,(l,g)=>{if(r.fetching?.id===n.key)r.fetching={id:n.key,got:l,size:g},this.draw()});if(s.signal.aborted)return;if(r.fetching=void 0,o!==this.board)return;let h={site:i,id:n.id,key:n.key,path:u,ext:t.ext,size:c,using:"plain",failed:!1};r.preparing=n.key,this.flush();let f=await this.render(h,"plain");if(s.signal.aborted||o!==this.board)return;if(f.clear===0&&wi()&&this.setting("TTHEME_FIND_REMOVE_BG")!=="off"){if(r.preparing=void 0,r.cutting=n.key,this.flush(),h.cut=await this.cutOut(i,n.id,u,s.signal),s.signal.aborted||o!==this.board)return;if(r.cutting=void 0,h.cut){r.preparing=n.key,this.flush();let l=await this.render(h,"cut").catch(()=>{return});if(s.signal.aborted||o!==this.board)return;if(l&&fc(l.clear))h.using="cut";else Hi(h.cut,{force:!0}),h.cut=void 0,h.failed=!0}else h.failed=!0}if(this.current=h,r.tiles[r.focus]?.key===n.key)await this.present();this.preload()}catch(u){if(!s.signal.aborted&&!this.signal.aborted)r.error=ji(i.name,u)}finally{if(r.fetching?.id===n.key)r.fetching=void 0;if(r.preparing===n.key)r.preparing=void 0;if(r.cutting===n.key)r.cutting=void 0;this.draw()}}async cutOut(n,r,e,t){let i=ar(Mr(n),"cut",`${r}.png`);if(xr(i))return i;try{return Li(Vc(i),{recursive:!0}),await gc(e,i,t),i}catch{Hi(i,{force:!0});return}}swap(){let n=this.current;if(!n?.cut||this.view.shown?.id!==n.key)return;n.using=n.using==="cut"?"plain":"cut",this.reveal()}preload(){let n=this.view;if(n.mode!=="try")return;for(let r of[n.focus+this.direction,n.focus-this.direction]){if(this.prefetching>=Pd)return;let e=n.tiles[r],t=e&&this.posts.get(e.key),i=t&&ye(t.post);if(!t||!i)continue;let{site:o,post:s}=t,u=this.origPath(o,s.id,i.ext);this.prefetching++,this.cached(o,u,i.file).then(()=>this.render({site:o,id:s.id,key:e.key,path:u,ext:i.ext,size:0,using:"plain",failed:!1},"plain")).catch(()=>{}).finally(()=>{this.prefetching--})}}async render(n,r){let e=this.cols*this.cell.w,t=this.rows*this.cell.h,i=Math.min(e,Wd),o=Math.max(1,Math.round(t*i/e)),s=ar(this.scratch,`${n.site.key}-${n.id}${r==="cut"?"c":""}-${i}x${o}.png`),u=`${n.site.key}:${n.id}:${r}`,c=this.clarity.get(u);if(c!==void 0&&xr(s))return{clear:c,path:s};let h=await this.renders.run({job:"show",from:r==="cut"?n.cut:n.path,to:s,width:i,height:o,colors:this.entry,tone:this.tone});return this.clarity.set(u,h),{clear:h,path:s}}async present(){let n=this.current;if(!n)return;let r=n.using,{clear:e,path:t}=await this.render(n,r);if(this.current!==n||n.using!==r)return;this.view.shown={id:n.key,clear:e,bytes:n.size,path:t,cut:n.cut?r==="cut"?"on":"off":n.failed?"failed":"none"}}reveal(){let n=this.view;n.preparing=this.current?.key,this.flush(),this.present().catch((r)=>{n.error=r instanceof Error?r.message:String(r)}).finally(()=>{if(n.preparing===this.current?.key)n.preparing=void 0;this.draw()})}async install(){let n=this.view,r=n.tiles[n.focus],e=this.current;if(!r||e?.key!==r.key||n.preparing!==void 0||n.shown?.id!==r.key)return;n.installing=r.key,n.error=void 0,this.flush();try{await this.renders.run({job:"backdrop",from:e.using==="cut"?e.cut:e.path,source:e.path,home:this.home,colors:this.entry,tone:this.tone,origin:{site:e.site.key,id:e.id,ext:e.ext,from:`${e.site.name} ${e.id} ${e.site.pageUrl(e.id)}`},width:this.cols*this.cell.w,height:this.rows*this.cell.h});let t=Ri(e.site,"owners.json");t[e.id]=this.posts.get(e.key)?.post.owner??"",Gi(e.site,"owners.json",t),Br(this.home),n.saved=`background · ${this.entry.name} ← ${e.site.name} ${e.id}`,n.installed.push(r.key),this.fetch?.abort(),clearTimeout(this.settle),n.fetching=void 0,n.mode="grid"}catch(t){n.error=t instanceof Error?t.message:String(t)}n.installing=void 0,this.draw()}draw(){if(this.dirty)return;this.dirty=!0,setImmediate(()=>{this.dirty=!1,this.flush()})}flush(){let n=Fc(this.view,this.cols,this.rows),r="\x1B[?2026h";n.lines.forEach((t,i)=>{r+=`\x1B[${i+1};1H\x1B[K${t}`});let e=new Set;for(let t of n.images){if(e.add(t.id),this.sent.get(t.id)!==t.path)r+=$c(t),this.sent.set(t.id,t.path),this.placed.delete(t.id);let i=`${t.row};${t.col};${t.cols};${t.rows};${t.z}`;if(this.placed.get(t.id)!==i)r+=wc(t),this.placed.set(t.id,i)}for(let t of this.sent.keys())if(!e.has(t))r+=pc(t),this.sent.delete(t),this.placed.delete(t);this.write(`${r}\x1B[?2026l`)}}function th(){if(process.versions.bun)return!0;let[n=0,r=0]=process.versions.node.split(".").map(Number);return n>22||n===22&&r>=21}async function Dc(){if(!th())return process.stderr.write(`unblock needs node 22.21 or newer — this is ${process.versions.node}
90
- `),1;let n=await Tc(),r=nh(process.execPath,process.argv.slice(1),{stdio:"inherit",env:{...process.env,NODE_USE_ENV_PROXY:"1",NODE_NO_WARNINGS:"1",HTTPS_PROXY:`http://127.0.0.1:${n.port}`,NO_PROXY:[process.env.NO_PROXY,pu()].filter(Boolean).join(","),TTHEME_FIND_PROXY:String(n.port)}}),e=await new Promise((t)=>r.on("exit",(i)=>t(i??1)));return n.close(),e}async function ih(n){if(process.env.TTHEME_FIND_UNBLOCK==="1"&&!process.env.TTHEME_FIND_PROXY)return Dc();let r=xn(),e=Qn(r),t=at(e.palettes,n);if(!process.stdin.isTTY||!process.stdout.isTTY)throw Error("ttheme find needs a terminal");let i=new eh(r,e,t,t.booru??""),o=await i.run(),s=i.unblock?await Dc():o;if(i.saved&&s!==0)return process.stderr.write(`${i.saved}
91
- `),0;return s}function oh(n,r){let e=xn();if(at(Qn(e).palettes,n),r==="next"||r==="prev"){let{key:t,at:i,of:o}=ru(e,n,r==="next"?1:-1);return Br(e),process.stderr.write(`background · ${n} ${i}/${o} ${t}
92
- `),0}if(r==="drop"){let{key:t,left:i}=eu(e,n);return Br(e),process.stderr.write(`background · ${n} removed ${t??"the picture"} · ${i} left
93
- `),0}if(r==="tuned")return Br(e),0;throw Error(`unknown image action ${r} — next, prev, drop or tuned`)}import{execFileSync as Xm}from"node:child_process";import{chmodSync as Tm,copyFileSync as Vm,existsSync as qn,mkdirSync as to,readdirSync as zm,readFileSync as ie,rmSync as sf,writeFileSync as uf}from"node:fs";import{homedir as Ym}from"node:os";import{dirname as te,join as fn}from"node:path";import{styleText as qi}from"node:util";import{stdout as vh,stdin as om}from"node:process";import sm from"node:readline";var sh=(()=>{let n=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(r)=>{let e=0;n.lastIndex=0;while(n.test(r))e+=1;return r.length-e}})(),uh=(n)=>{return n===12288||n>=65281&&n<=65376||n>=65504&&n<=65510},ch=(n)=>{return n===8987||n===9001||n>=12272&&n<=12287||n>=12289&&n<=12350||n>=12441&&n<=12543||n>=12549&&n<=12591||n>=12593&&n<=12686||n>=12688&&n<=12771||n>=12783&&n<=12830||n>=12832&&n<=12871||n>=12880&&n<=19903||n>=65040&&n<=65049||n>=65072&&n<=65106||n>=65108&&n<=65126||n>=65128&&n<=65131||n>=127488&&n<=127490||n>=127504&&n<=127547||n>=127552&&n<=127560||n>=131072&&n<=196605||n>=196608&&n<=262141};var Xd=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,Td=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,hh=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,Vd=/\t{1,1000}/y,fh=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu,zd=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Yd=/\p{M}+/gu,Cd={limit:1/0,ellipsis:""},gh=(n,r={},e={})=>{let t=r.limit??1/0,i=r.ellipsis??"",o=r?.ellipsisWidth??(i?gh(i,Cd,e).width:0),s=0,u=e.controlWidth??0,c=e.tabWidth??8,h=e.emojiWidth??2,f=2,l=e.regularWidth??1,g=e.wideWidth??2,d=[[zd,l],[Xd,0],[Td,u],[Vd,c],[fh,h],[hh,g]],w=0,m=0,b=n.length,F=0,S=!1,k=b,y=Math.max(0,t-o),p=0,R=0,M=0,j=0;n:while(!0){if(R>p||m>=b&&m>w){let H=n.slice(p,R)||n.slice(w,m);F=0;for(let J of H.replaceAll(Yd,"")){let G=J.codePointAt(0)||0;if(uh(G))j=2;else if(ch(G))j=g;else j=l;if(M+j>y)k=Math.min(k,Math.max(p,w)+F);if(M+j>t){S=!0;break n}F+=J.length,M+=j}p=R=0}if(m>=b)break n;for(let H=0,J=d.length;H<J;H++){let[G,z]=d[H];if(G.lastIndex=m,G.test(n)){if(F=G===hh?sh(n.slice(m,G.lastIndex)):G===fh?1:G.lastIndex-m,j=F*z,M+j>y)k=Math.min(k,m+Math.floor((y-M)/z));if(M+j>t){S=!0;break n}M+=j,p=w,R=m,m=w=G.lastIndex;continue n}}m+=1}return{width:S?y:M,index:S?k:b,truncated:S,ellipsed:S&&t>=o}},lh=gh;var _d={limit:1/0,ellipsis:"",ellipsisWidth:0},Bd=(n,r={})=>{return lh(n,_d,r).width},Kn=Bd;var kt="\x1B",wh="›",xd=39,Pi="\x07",ph="[",Dd="]",bh="m",Ui=`${Dd}8;;`,ah=new RegExp(`(?:\\${ph}(?<code>\\d+)m|\\${Ui}(?<uri>.*)${Pi})`,"y"),dh=(n)=>{if(n>=30&&n<=37)return 39;if(n>=90&&n<=97)return 39;if(n>=40&&n<=47)return 49;if(n>=100&&n<=107)return 49;if(n===1||n===2)return 22;if(n===3)return 23;if(n===4)return 24;if(n===7)return 27;if(n===8)return 28;if(n===9)return 29;if(n===0)return 0;return},mh=(n)=>`${kt}${ph}${n}${bh}`,$h=(n)=>`${kt}${Ui}${n}${Pi}`,Ki=(n,r,e)=>{let t=r[Symbol.iterator](),i=!1,o=!1,s=n.at(-1),u=s===void 0?0:Kn(s),c=t.next(),h=t.next(),f=0;while(!c.done){let l=c.value,g=Kn(l);if(u+g<=e)n[n.length-1]+=l;else n.push(l),u=0;if(l===kt||l===wh)i=!0,o=r.startsWith(Ui,f+1);if(i){if(o){if(l===Pi)i=!1,o=!1}else if(l===bh)i=!1}else if(u+=g,u===e&&!h.done)n.push(""),u=0;c=h,h=t.next(),f+=l.length}if(s=n.at(-1),!u&&s!==void 0&&s.length&&n.length>1)n[n.length-2]+=n.pop()},nm=(n)=>{let r=n.split(" "),e=r.length;while(e){if(Kn(r[e-1]))break;e--}if(e===r.length)return n;return r.slice(0,e).join(" ")+r.slice(e).join("")},rm=(n,r,e={})=>{if(e.trim!==!1&&n.trim()==="")return"";let t="",i,o,s=n.split(" "),u=[""],c=0;for(let l=0;l<s.length;l++){let g=s[l];if(e.trim!==!1){let w=u.at(-1)??"",m=w.trimStart();if(w.length!==m.length)u[u.length-1]=m,c=Kn(m)}if(l!==0){if(c>=r&&(e.wordWrap===!1||e.trim===!1))u.push(""),c=0;if(c||e.trim===!1)u[u.length-1]+=" ",c++}let d=Kn(g);if(e.hard&&d>r){let w=r-c,m=1+Math.floor((d-w-1)/r);if(Math.floor((d-1)/r)<m)u.push("");Ki(u,g,r),c=Kn(u.at(-1)??"");continue}if(c+d>r&&c&&d){if(e.wordWrap===!1&&c<r){Ki(u,g,r),c=Kn(u.at(-1)??"");continue}u.push(""),c=0}if(c+d>r&&e.wordWrap===!1){Ki(u,g,r),c=Kn(u.at(-1)??"");continue}u[u.length-1]+=g,c+=d}if(e.trim!==!1)u=u.map((l)=>nm(l));let h=u.join(`
94
- `),f=!1;for(let l=0;l<h.length;l++){let g=h[l];if(t+=g,!f){if(f=g>="\uD800"&&g<="\uDBFF",f)continue}else f=!1;if(g===kt||g===wh){ah.lastIndex=l+1;let w=ah.exec(h)?.groups;if(w?.code!==void 0){let m=Number.parseFloat(w.code);i=m===xd?void 0:m}else if(w?.uri!==void 0)o=w.uri.length===0?void 0:w.uri}if(h[l+1]===`
95
- `){if(o)t+=$h("");let d=i?dh(i):void 0;if(i&&d)t+=mh(d)}else if(g===`
96
- `){if(i&&dh(i))t+=mh(i);if(o)t+=$h(o)}}return t},em=/\r?\n/;function Er(n,r,e){return String(n).normalize().split(em).map((t)=>rm(t,r,e)).join(`
97
- `)}var Zn=Te(Wi(),1);function dr(n,r,e){if(!e.some((s)=>!s.disabled))return n;let t=n+r,i=Math.max(e.length-1,0),o=t<0?i:t>i?0:t;return e[o]?.disabled?dr(o,r<0?-1:1,e):o}function Mt(n,r,e,t){let i=t.split(`
98
- `),o=0,s=n;for(let c of i){if(s<=c.length)break;s-=c.length+1,o++}for(o=Math.max(0,Math.min(i.length-1,o+e)),s=Math.min(s,i[o].length)+r;s<0&&o>0;)o--,s+=i[o].length+1;for(;s>i[o].length&&o<i.length-1;)s-=i[o].length+1,o++;s=Math.max(0,Math.min(i[o].length,s));let u=0;for(let c=0;c<o;c++)u+=i[c].length+1;return u+s}var um=["up","down","left","right","space","enter","cancel"],cm=["January","February","March","April","May","June","July","August","September","October","November","December"],Pn={actions:new Set(um),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0,date:{monthNames:[...cm],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(n,r)=>`There are only ${n} days in ${r}`,afterMin:(n)=>`Date must be on or after ${n.toISOString().slice(0,10)}`,beforeMax:(n)=>`Date must be on or before ${n.toISOString().slice(0,10)}`}}};function Fh(n,r){if(typeof n=="string")return Pn.aliases.get(n)===r;for(let e of n)if(e!==void 0&&Fh(e,r))return!0;return!1}function hm(n,r){if(n===r)return;let e=n.split(`
99
- `),t=r.split(`
100
- `),i=Math.max(e.length,t.length),o=[];for(let s=0;s<i;s++)e[s]!==t[s]&&o.push(s);return{lines:o,numLinesBefore:e.length,numLinesAfter:t.length,numLines:i}}var fp=globalThis.process.platform.startsWith("win"),Ai=Symbol("clack:cancel");function ne(n){return n===Ai}function Et(n,r){let e=n;e.isTTY&&e.setRawMode(r)}var Ft=(n)=>("columns"in n)&&typeof n.columns=="number"?n.columns:80,Ti=(n)=>("rows"in n)&&typeof n.rows=="number"?n.rows:20;function vr(n,r,e,t=e,i=e,o){let s=Ft(n??vh);return Er(r,s-e.length,{hard:!0,trim:!1}).split(`
101
- `).map((u,c,h)=>{let f=o?o(u,c):u;return c===0?`${t}${f}`:c===h.length-1?`${i}${f}`:`${e}${f}`}).join(`
102
- `)}function yh(n,r){if("~standard"in n){let e=n["~standard"].validate(r);if(e instanceof Promise)throw TypeError("Schema validation must be synchronous. Update `validate()` and remove any asynchronous logic.");return e.issues?.at(0)?.message}return n(r)}class sr{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(n,r=!0){let{input:e=om,output:t=vh,render:i,signal:o,...s}=n;this.opts=s,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=i.bind(this),this._track=r,this._abortSignal=o,this.input=e,this.output=t}unsubscribe(){this._subscribers.clear()}setSubscriber(n,r){let e=this._subscribers.get(n)??[];e.push(r),this._subscribers.set(n,e)}on(n,r){this.setSubscriber(n,{cb:r})}once(n,r){this.setSubscriber(n,{cb:r,once:!0})}emit(n,...r){let e=this._subscribers.get(n)??[],t=[];for(let i of e)i.cb(...r),i.once&&t.push(()=>e.splice(e.indexOf(i),1));for(let i of t)i()}prompt(){return new Promise((n)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),n(Ai);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=sm.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on("keypress",this.onKeypress),Et(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(Zn.cursor.show),this.output.off("resize",this.render),Et(this.input,!1),n(this.value)}),this.once("cancel",()=>{this.output.write(Zn.cursor.show),this.output.off("resize",this.render),Et(this.input,!1),n(Ai)})})}_isActionKey(n,r){return n==="\t"}_shouldSubmit(n,r){return!0}_setValue(n){this.value=n,this.emit("value",this.value)}_setUserInput(n,r){this.userInput=n??"",this.emit("userInput",this.userInput),r&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}onKeypress(n,r){if(this._track&&r.name!=="return"&&(r.name&&this._isActionKey(n,r)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),r?.name&&(!this._track&&Pn.aliases.has(r.name)&&this.emit("cursor",Pn.aliases.get(r.name)),Pn.actions.has(r.name)&&this.emit("cursor",r.name)),n&&(n.toLowerCase()==="y"||n.toLowerCase()==="n")&&this.emit("confirm",n.toLowerCase()==="y"),this.emit("key",n,r),r?.name==="return"&&this._shouldSubmit(n,r)){if(this.opts.validate){let e=yh(this.opts.validate,this.value);e&&(this.error=e instanceof Error?e.message:e,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}Fh([n,r?.name,r?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
103
- `),Et(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let n=Er(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
104
- `).length-1;this.output.write(Zn.cursor.move(-999,n*-1))}render(){let n=Er(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(n!==this._prevFrame){if(this.state==="initial")this.output.write(Zn.cursor.hide);else{let r=hm(this._prevFrame,n),e=Ti(this.output);if(this.restoreCursor(),r){let t=Math.max(0,r.numLinesAfter-e),i=Math.max(0,r.numLinesBefore-e),o=r.lines.find((s)=>s>=t);if(o===void 0){this._prevFrame=n;return}if(r.lines.length===1){this.output.write(Zn.cursor.move(0,o-i)),this.output.write(Zn.erase.lines(1));let s=n.split(`
105
- `);this.output.write(s[o]),this._prevFrame=n,this.output.write(Zn.cursor.move(0,s.length-o-1));return}else if(r.lines.length>1){if(t<i)o=t;else{let u=o-i;u>0&&this.output.write(Zn.cursor.move(0,u))}this.output.write(Zn.erase.down());let s=n.split(`
141
+ `);return}Nm(t,s[1],Number(s[2]),n.subarray(o+4))};t.on("data",e),t.on("error",()=>t.destroy())}function Mh(){let t=Sm(Om);return new Promise((n,e)=>{t.once("error",e),t.listen(0,"127.0.0.1",()=>{n({port:t.address().port,close:()=>{t.close(),t.unref()}})})})}var Bn=[{name:"TTHEME_FIND_RATING",label:"rating",choices:Fe,multi:{read:gr}},{name:"TTHEME_FIND_BLOCK",label:"block",choices:jn,multi:{read:lr,none:"none"}},{name:"TTHEME_FIND_POSTS",label:"posts",choices:["all","cutouts"]},{name:"TTHEME_FIND_SOLO",label:"solo",choices:["on","off"]},{name:"TTHEME_FIND_ORDER",label:"order",choices:["fit","newest","score"]},{name:"TTHEME_FIND_SETS",label:"sets",choices:["fold","show"]},...Ui()?[{name:"TTHEME_FIND_REMOVE_BG",label:"remove bg",choices:["on","off"]}]:[]];function Lm(t,n){if(t.multi)return t.multi.read(n).join(" ")||t.multi.none;return t.choices.find((e)=>e===n)??t.choices[0]}var Pm=["fit","newest","score"];function vh(t){return Pm.find((n)=>n===t)??"fit"}function Km(t){return t.length>=2&&!/^\d+$/.test(t)&&!t.includes("://")&&!/^[\w.]+:\d+$/.test(t)}var yh=12,Jm=4,Am=150,Sh=12,Um=2,Tm=150,Wm=30,Qm=4000,Zm=8000,Fh=/\.(png|jpe?g|gif|webp|heic|tiff?|bmp)$/i,qm=process.platform==="win32"?"alt+v":"ctrl+v",Ih=process.platform==="darwin"?"ctrl+shift+cmd+4 copies a screenshot":"copy a picture first",Xm=1280,Nh=2,_m=3,Cm=8;function Ar(t,n){return{key:t,groups:[],sources:[],queue:[],rounds:0,roundOf:new Map,last:new Map,kin:new Map,kindred:new Map,shapes:[],seen:new Set,same:new Map,checked:0,total:0,focus:0,top:0,searching:n}}function Dn(t){if(!(t instanceof Error))return String(t);if(t instanceof AggregateError&&t.errors[0])return Dn(t.errors[0]);if(t.cause)return Dn(t.cause);let n=t.code;if(typeof n==="string")return n;let e=(t.message||t.name).split(".")[0]??"";return e.length>56?`${e.slice(0,55)}…`:e}function Bi(t,n){return`${t}: ${Dn(n)}`}function Oh(t){return t.width*t.height}function Hh(t){return`${t.id}-${Gh("sha1").update(t.preview).digest("hex").slice(0,8)}`}function zm(t){let n=t.lastIndexOf("\x1B");return n!==-1&&/^\[?[0-9;]*$/.test(t.slice(n+1))}function Di(t,n){try{return JSON.parse(Lh(fn(yn(t),n),"utf8"))}catch{return{}}}function to(t,n,e){_e(yn(t),{recursive:!0}),Ce(fn(yn(t),n),`${JSON.stringify(e)}
142
+ `)}class Ph{view;tone;session=new AbortController;cell={w:0,h:0};cols=process.stdout.columns||80;rows=process.stdout.rows||24;gen=0;pumping=0;boards=new Map;board;posts=new Map;thumbPath=new Map;looking=new Map;looked=new Map;matched=new Map;aheading=!1;pages=new Map;tab=0;values=new Map(Bn.map((t)=>[t.name,Lm(t,process.env[t.name])]));direction=1;prefetching=0;inflight=new Map;owners=new Map;probed=new Map;unsaved=new Set;thumbQueue=[];thumbing=0;clarity=new Map;renders=new Yi;sent=new Map;placed=new Map;current;fetch;settle;partial;suggestTimer;suggesting;input="";typed="";grabber=new Ai((t)=>this.write(t),(t)=>void this.got(t));featureWait;noticeTimer;peekTimer;peeked;attaching;probeWait;done;dirty=!1;unblock=!1;scratch=Hm(fn(Rm(),"ttheme-find-"));home;catalog;entry;constructor(t,n,e,r){this.home=t,this.catalog=n,this.entry=e,this.tone=hr(e,e.signatureSlots),this.view={palette:e.name,tag:r,site:this.tabName,siteAnsi:this.tabAnsi,nextSite:this.nextTabName,preset:this.setting("TTHEME_FIND_POSTS")==="all"?"all":"cutouts",order:vh(this.setting("TTHEME_FIND_ORDER")),solo:this.setting("TTHEME_FIND_SOLO")==="on",rating:gr(this.setting("TTHEME_FIND_RATING")),block:lr(this.setting("TTHEME_FIND_BLOCK")),sets:this.setting("TTHEME_FIND_SETS")==="show"?"show":"fold",unblocked:process.env.TTHEME_FIND_PROXY!==void 0,settings:Bn.map((i)=>({label:i.label,choices:[...i.choices],value:this.setting(i.name),multi:i.multi&&{none:i.multi.none},cursor:0})),colors:{cursor:e.cursor,selection:e.selection,ansi:e.ansi},tiles:[],installed:[],checked:0,total:0,searching:r!=="",focus:0,top:0,mode:"grid",help:!1,editing:r===""?"":void 0},this.board=Ar(this.boardKey,r!==""),this.boards.set(this.board.key,this.board)}get signal(){return this.session.signal}get site(){return this.tab===0?void 0:gt[this.tab-1]}get sites(){return this.site?[this.site]:gt}get tabName(){return this.site?.name??"all"}get tabAnsi(){return this.site?.ansi??Jm}get nextTabName(){let t=(this.tab+1)%(gt.length+1);return t===0?"all":gt[t-1].name}frame(){return{w:this.cols*(this.cell.w||10),h:this.rows*(this.cell.h||20)}}setting(t){return this.values.get(t)}get boardKey(){return`${this.site?.key??"all"}|${this.view.preset}|${this.view.order}`}origPath(t,n,e){return fn(yn(t),"orig",`${n}.${e}`)}previewPath(t){return fn(yn(t.site),"thumb",`${Hh(t.post)}.${Ie(t.post.preview)}`)}tileOf(t,n){let{site:e,post:r}=t,i=on(e,r.id),o=Oe(r)??r;return{id:r.id,key:i,site:e.name,siteAnsi:e.ansi,width:o.width,height:o.height,reduced:o!==r,owner:r.owner,artist:e===Ir?Fu(r.source):r.artist,score:r.score,variants:n,origin:Mi(r.source),mates:this.owners.get(e.key)?.get(r.owner)??[],thumb:this.thumbPath.get(i)}}show(){let t=this.view,n=this.board;t.tiles=n.groups.flatMap((e)=>e.open?e.posts.map((r)=>this.tileOf(r,0)):[this.tileOf(e.posts[0],e.posts.length)]),t.checked=n.checked,t.total=n.total,t.searching=n.searching,t.note=n.note,t.focus=Math.max(0,Math.min(n.focus,t.tiles.length-1)),t.top=n.top}syncSite(){let t=this.view;t.site=this.tabName,t.siteAnsi=this.tabAnsi,t.nextSite=this.nextTabName}async run(){let{stdin:t,stdout:n}=process;t.setRawMode(!0),t.resume(),t.on("data",this.onData),n.on("resize",this.onResize),this.write("\x1B[?25l\x1B[?7l\x1B[H\x1B[K\x1B[2H\x1B[J\x1B[H");let e=new Promise((s)=>{this.done=s}),r=setInterval(this.onClock,250),i=await this.probe();if(i){if(this.cell=i,this.view.tag)this.search()}else this.view.searching=!1,this.view.error="this terminal does not report its cell size — find needs kitty graphics";await this.features(),this.grabber.start(),this.write("\x1B[?1004h"),this.peek(),this.draw();let o=await e;return this.grabber.stop(),this.write("\x1B[?1004l"),this.attaching?.abort(),clearTimeout(this.noticeTimer),clearTimeout(this.peekTimer),this.session.abort(),this.fetch?.abort(),clearTimeout(this.settle),clearTimeout(this.partial),this.quietSuggest(),clearInterval(r),t.off("data",this.onData),n.off("resize",this.onResize),this.write("\x1B_Ga=d,d=A,q=2\x1B\\\x1B[H\x1B[K\x1B[2H\x1B[J\x1B[H"),t.setRawMode(!1),t.pause(),this.saveProbes(),this.renders.close(),xi(this.scratch,{recursive:!0,force:!0}),Ac(),o}write(t){process.stdout.write(t)}get saved(){return this.view.saved}finish(t){this.done?.(t===2&&this.saved?0:t)}probe(){return new Promise((t)=>{let n=setTimeout(()=>{this.probeWait=void 0,t(null)},1000);this.probeWait=(e)=>{clearTimeout(n),this.probeWait=void 0,t(e)},this.write(Xu)})}onData=(t)=>{this.input+=t.toString("utf8");for(let e=Qi(this.input);e;e=Qi(this.input))this.input=e.rest,this.probeWait?.(e.cell);if(this.probeWait)return;let n=Ru(this.input);if(this.input=n.pending,this.view.editing===void 0&&n.keys.length>8&&/^(?:\/|~\/|file:|https?:)/.test(n.keys))this.pasted(n.keys),n.keys="";this.typed+=n.keys;for(let e of n.events)this.inbound(e);if(clearTimeout(this.partial),zm(this.typed)){this.partial=setTimeout(this.flushKeys,Wm);return}this.flushKeys()};flushKeys=()=>{let t=qu(this.typed);this.typed="";for(let n of t)this.key(n)};features(){if(process.env.TMUX)return Promise.resolve();return new Promise((t)=>{let n=setTimeout(()=>{this.featureWait=void 0,t()},500);this.featureWait=()=>{clearTimeout(n),this.featureWait=void 0,t()},this.write("\x1B[?5522$p\x1B]72;t=q\x1B\\\x1B[c")})}inbound(t){if(t.kind==="mode"){if(t.mode===5522)this.grabber.clipboard=t.value!==0&&t.value!==4;return}if(t.kind==="attributes"){this.featureWait?.();return}if(t.kind==="osc"){if(t.code==="72"&&t.meta.t==="q"){this.grabber.drops=!0;return}this.grabber.take(t);return}this.pasted(t.text)}pasted(t){let n=this.view;if(n.editing!==void 0&&t.trim()!==""&&!this.picture(t)){n.editing+=t.replace(/[\r\n]+/g," "),this.suggest(),this.draw();return}if(n.installing!==void 0||n.asking!==void 0||n.panel!==void 0||n.help)return;if(t.trim()===""){this.fromClipboard();return}this.attach(t)}picture(t){let n=t.trim();if(/^https?:\/\/\S+$/i.test(n))return!dr(n,this.site??gt[0]);return Fr(n).length>0}async got(t){if(t.kind==="error"){this.notice(t.message);return}if(t.kind==="text"){if(t.text.trim()===""){this.notice(`no picture on the clipboard — ${Ih}`);return}this.pasted(t.text);return}await this.bring(()=>yr(t.bytes,t.source))}notice(t,n=Qm){let e=this.view;e.error=t,clearTimeout(this.noticeTimer),this.noticeTimer=setTimeout(()=>{if(e.error===t)e.error=void 0,this.draw()},n),this.draw()}async peek(){let t=this.view,n;try{n=await ju()}catch{return}if(!n||n.stamp===this.peeked)return;if(this.peeked=n.stamp,!n.picture||t.installing!==void 0||t.asking!==void 0)return;t.hint=`picture on the clipboard · ${qm} uses it`,clearTimeout(this.peekTimer),this.peekTimer=setTimeout(()=>{t.hint=void 0,this.draw()},Zm),this.draw()}async fromClipboard(){let t=this.view;if(Ji()){if(this.grabber.clipboard){this.grabber.ask();return}this.notice("over ssh the clipboard is not here — drop the file");return}let n;try{n=await Hu(fn(this.scratch,`clipboard-${Date.now()}.png`))}catch(r){this.notice(`could not read the clipboard: ${Dn(r)}`);return}if(clearTimeout(this.peekTimer),t.hint=void 0,"image"in n){await this.bring(async(r)=>({...await Ki(n.image,r),source:"clipboard"}));return}let e=n.text.trim();if(!e){this.notice(`no picture on the clipboard — ${Ih}`);return}if(this.picture(e)){await this.attach(e);return}if(t.editing===void 0)t.editing="";this.pasted(e)}async attach(t){let n=t.trim();if(/^https?:\/\//i.test(n)){let i=dr(n,this.site??gt[0]);if(i){await this.jump(i.site,i.id);return}}let[e,...r]=Fr(n).sort((i,o)=>Number(!Fh.test(i))-Number(!Fh.test(o)));if(!e){this.notice("nothing to use in that — drop a picture, or paste one or its link");return}await this.bring((i)=>Ki(e,i),r.length)}async bring(t,n=0){let e=this.view;this.attaching?.abort();let r=new AbortController;this.attaching=r,e.error=void 0,e.saved=void 0,e.note="reading the picture…",this.draw();let i;try{i=await t(AbortSignal.any([r.signal,this.signal]))}catch(g){if(!r.signal.aborted)e.note=void 0,this.notice(Dn(g),8000);return}if(r.signal.aborted)return;e.note=n>0?`the first picture of ${n+1} — drop one at a time to try the others`:void 0,this.quietSuggest(),e.editing=void 0,e.suggest=void 0,e.pick=void 0;let o=Nu(i.bytes);Iu(o,i.source);let s=this.origPath(Ir,o,i.ext);_e(Jr(s),{recursive:!0}),Ce(s,i.bytes);let c=Gm(s).href,u={id:o,file:c,width:i.width,height:i.height,ext:i.ext,preview:c,owner:"",artist:"",score:0,rating:"s",md5:Gh("md5").update(i.bytes).digest("hex"),source:i.source,tags:[],solo:void 0,family:0,smaller:[]},h={site:Ir,post:u},f=this.previewPath(h);_e(Jr(f),{recursive:!0}),Ce(f,i.bytes),++this.gen,this.current=void 0,e.shown=void 0;let a=Ar(`local|post:${o}`,!1);this.board=a,this.boards.set(a.key,a),this.single(a,h)}single(t,n){t.searching=!1,this.posts.set(on(n.site,n.post.id),n),t.groups=[{posts:[n],open:!1}],t.checked=1,t.total=1,this.thumbQueue.push(n),this.thumbs(),this.view.mode="try",this.show(),this.select(),this.draw()}onClock=()=>{let t=this.sites.reduce((r,i)=>Mn(i)>Mn(r)?i:r),n=Math.ceil((Mn(t)-Date.now())/1000),e=n>0?n:void 0;if(e!==this.view.waiting)this.view.waiting=e,this.view.slow=t.name,this.draw()};onResize=()=>{if(this.cols=process.stdout.columns||this.cols,this.rows=process.stdout.rows||this.rows,this.scroll(),this.view.mode==="try"&&this.current)this.reveal();this.pump(),this.draw()};key(t){let n=this.view;if(t==="ctrl-c"){this.finish(2);return}if(n.installing!==void 0)return;if(n.asking!==void 0){this.askKey(t);return}if(t==="focus-in"){this.peek();return}if(t==="focus-out"||t==="nop")return;if((t==="ctrl-v"||t==="alt-v")&&n.panel===void 0){this.fromClipboard();return}if(n.editing!==void 0){this.editKey(t);return}if(n.panel!==void 0){this.panelKey(t);return}if(n.help){if(t==="?"||t==="esc")n.help=!1,this.draw();return}if(this.cols<Ln.cols||this.rows<Ln.rows){if(t==="esc")this.finish(2);return}if(t==="?"){n.help=!0,this.draw();return}if(n.mode==="try"){this.tryKey(t);return}this.gridKey(t)}gridKey(t){let n=this.view,{perRow:e,rowsVis:r}=_n(this.cols,this.rows),o={left:-1,right:1,up:-e,down:e,pgup:-e*r,pgdn:e*r,home:-n.focus,end:n.tiles.length}[t];if(o!==void 0){this.focus(n.focus+o);return}if(t==="enter"&&n.tiles[n.focus]){n.mode="try",n.error=void 0,this.select();return}if(t==="v"){this.fromClipboard();return}if(t==="c"){n.preset=n.preset==="cutouts"?"all":"cutouts",this.turn();return}if(t==="tab"){this.tab=(this.tab+1)%(gt.length+1),this.syncSite(),this.turn();return}if(t==="/"){n.editing="",this.draw();return}if(t===" "){this.unfold();return}if(t==="o"){this.openPage();return}if(t==="s"){n.panel=0,this.draw();return}if(t==="esc")this.finish(2)}panelKey(t){let n=this.view,e=n.panel??0,r=n.settings[e];if(t==="up"||t==="down"){n.panel=Math.max(0,Math.min(n.settings.length-1,e+(t==="up"?-1:1))),this.draw();return}if((t==="left"||t==="right")&&r){let i=t==="left"?-1:1;if(r.multi)r.cursor=(r.cursor+i+r.choices.length)%r.choices.length;else{let o=r.choices.indexOf(r.value);r.value=r.choices[(o+i+r.choices.length)%r.choices.length]}this.draw();return}if(t===" "&&r?.multi){let i=r.value.split(" "),o=r.choices.filter((c,u)=>u===r.cursor?!i.includes(c):i.includes(c)),s=r.multi.none;if(o.length>0||s!==void 0)r.value=o.length>0?o.join(" "):s,this.draw();return}if(t==="esc"){n.settings.forEach((i,o)=>{i.value=this.setting(Bn[o]?.name??"")}),n.panel=void 0,this.draw();return}if(t==="enter"||t==="alt-c")n.panel=void 0,this.adopt()}adopt(){let t=this.view,n=Bn.map((r)=>this.setting(r.name));t.settings.forEach((r,i)=>{let o=Bn[i];if(o)this.values.set(o.name,r.value)});let e=Bn.filter((r,i)=>this.setting(r.name)!==n[i]);if(e.length===0){this.draw();return}this.save(e),t.rating=gr(this.setting("TTHEME_FIND_RATING")),t.block=lr(this.setting("TTHEME_FIND_BLOCK")),t.sets=this.setting("TTHEME_FIND_SETS")==="show"?"show":"fold",t.preset=this.setting("TTHEME_FIND_POSTS")==="all"?"all":"cutouts",t.order=vh(this.setting("TTHEME_FIND_ORDER")),t.solo=this.setting("TTHEME_FIND_SOLO")==="on",this.boards.clear(),this.current=void 0,t.shown=void 0,t.mode="grid",this.search()}save(t){this.store(t.map((n)=>[n.name,this.setting(n.name)]))}store(t){let n=fn(this.home,"ttheme","config.zsh");try{let e=xn(n)?Lh(n,"utf8"):"";return Ce(n,t.reduce((r,[i,o])=>eu(r,i,o),e)),!0}catch(e){return this.view.error=e instanceof Error?e.message:String(e),!1}}askKey(t){let n=this.view;if(t==="y"){if(n.asking=void 0,this.store([["TTHEME_FIND_UNBLOCK","1"]])){this.unblock=!0,this.finish(0);return}this.draw();return}if(t==="n"||t==="esc")n.asking=void 0,this.draw()}editKey(t){let n=this.view,e=n.editing??"",r=n.suggest??[];if((t==="up"||t==="down")&&r.length>0){let i=n.pick??-1,o=t==="down"?Math.min(r.length-1,i+1):i-1;n.pick=o<0?void 0:o,this.draw();return}if(t==="esc"||t==="enter")this.quietSuggest();if(t==="esc"){if(n.editing=void 0,n.tag===""){this.finish(2);return}this.draw();return}if(t==="enter"){let i=n.pick===void 0?void 0:r[n.pick],o=i?e.replace(/\S*$/,i.value):e;if(n.editing=void 0,n.suggest=void 0,n.pick=void 0,o.trim()){this.commit(o.trim());return}if(n.tag===""){this.finish(2);return}this.draw();return}if(t==="backspace"){n.editing=e.slice(0,-1),this.suggest(),this.draw();return}if(t.length===1&&t>=" ")n.editing=e+t,this.suggest(),this.draw()}quietSuggest(){clearTimeout(this.suggestTimer),this.suggesting?.abort(),this.suggesting=void 0}suggest(){this.quietSuggest();let t=this.view;t.pick=void 0;let n=/\S*$/.exec(t.editing??"")?.[0]??"";if(!Km(n)){t.suggest=void 0;return}let e=[...new Map(Au(this.catalog.palettes,this.entry,n).map((i)=>[i.booru,{value:i.booru,count:0,palette:i.name}])).values()].slice(0,_m);t.suggest=e.length>0?e:void 0;let r=new AbortController;this.suggesting=r,this.suggestTimer=setTimeout(async()=>{try{let i=await Zc(n,AbortSignal.any([this.signal,r.signal]));if(this.suggesting===r&&t.editing!==void 0){let o=new Map(i.map((c)=>[c.value,c.count])),s=new Set(e.map((c)=>c.value));t.suggest=[...e.map((c)=>({...c,count:o.get(c.value)??0})),...i.filter((c)=>!s.has(c.value))].slice(0,Cm),t.pick=t.pick!==void 0&&t.pick<e.length?t.pick:void 0,this.draw()}}catch{}},Am)}async commit(t){let n=dr(t,this.site??gt[0]);if(n){await this.jump(n.site,n.id);return}if(this.picture(t)){await this.attach(t);return}this.view.tag=t,this.boards.clear(),await this.search()}async jump(t,n){let e=++this.gen;this.tab=gt.indexOf(t)+1,this.syncSite(),this.current=void 0,this.view.shown=void 0,this.view.error=void 0;let r=Ar(`${t.key}|post:${n}`,!0);this.board=r,this.boards.set(r.key,r),this.show(),this.draw();try{let i=await vi(t,n,this.signal);if(e!==this.gen)return;if(!i){r.searching=!1,r.error=`${t.name} has no post ${n}`,this.view.error=r.error,this.show(),this.draw();return}this.single(r,{site:t,post:i})}catch(i){this.fail(e,i,t)}}async turn(){this.fetch?.abort(),this.current=void 0,this.view.shown=void 0;let t=this.boards.get(this.boardKey);if(!t){await this.search();return}this.gen++,this.board=t,this.view.error=t.error,this.show(),this.draw(),await this.pump()}unfold(){let t=this.view,n=0;for(let e of this.board.groups){let r=e.open?e.posts.length:1;if(t.focus<n+r){if(e.posts.length<2)return;e.open=!e.open,this.board.focus=n;for(let i of e.posts)if(!this.thumbPath.has(on(i.site,i.post.id)))this.thumbQueue.push(i);this.thumbs(),this.show(),this.scroll(),this.draw();return}n+=r}}openPage(){let t=this.view.tiles[this.view.focus],n=t&&this.posts.get(t.key);if(!n)return;let e=process.platform==="darwin"?"open":"xdg-open";try{Rh(e,[n.site.pageUrl(n.post.id)],{stdio:"ignore",detached:!0}).unref()}catch{}}tryKey(t){let n=this.view;if(t==="left"||t==="right"){this.direction=t==="left"?-1:1,this.focus(n.focus+this.direction);return}if(t==="o"){this.openPage();return}if(t==="x"){this.swap();return}if(t==="v"){this.fromClipboard();return}if(t==="enter"){this.install();return}if(t==="esc")this.fetch?.abort(),clearTimeout(this.settle),n.fetching=void 0,n.mode="grid",n.error=void 0,this.draw()}focus(t){let n=this.view;if(n.tiles.length===0)return;let e=Math.max(0,Math.min(n.tiles.length-1,t));if(e===n.focus)return;if(n.focus=e,this.board.focus=e,this.scroll(),this.pump(),n.mode==="try")this.select();this.draw()}scroll(){let t=this.view,{perRow:n,rowsVis:e}=_n(this.cols,this.rows),r=Math.floor(t.focus/n);if(r<t.top)t.top=r;if(r>t.top+e-1)t.top=r-e+1;this.board.top=t.top}query(t){let n=this.view,e=n.tag===this.entry.booru?Uu(this.entry,t.key):[n.tag];if(e.length===0)return;let r=e.length>1,i=n.preset==="cutouts"?t.cutouts:"",o=r&&i.includes("~"),s=[r?e.map((h)=>`~${h}`).join(" "):e[0],t.rate(this.view.rating),o?"":i,n.order==="score"?t.best:""].filter(Boolean),c=[],u=[];for(let h of s)if(Ei([...c,h].join(" "))<=t.tagBudget)c.push(h);else u.push(h);return{tags:c.join(" "),notes:[...u.length>0?[`${t.name} takes ${t.tagBudget} tags — ${u.join(" ")} left out`]:[],...o?[`${t.name} ORs the names, so cutouts are told by the file`]:[]]}}async search(){let t=++this.gen,n=Ar(this.boardKey,!0);this.board=n,this.boards.set(n.key,n),this.view.error=void 0;let e=this.sites.flatMap((o)=>{let s=this.query(o);return s?[{site:o,...s}]:[]}),r=this.sites.filter((o)=>!e.some((s)=>s.site===o)),i=[...e.flatMap(({notes:o})=>o),...r.length>0?[`${this.entry.name} has no tag on ${r.map((o)=>o.name).join(", ")}`]:[]];if(n.note=i.length>0?i.join(" · "):void 0,e.length===0)n.searching=!1;this.show(),this.draw(),this.tally(t,n,e);try{let o=await Promise.all(e.map(async(s)=>({plan:s,owners:await this.mateOwners(s.site)})));if(t!==this.gen)return;n.sources=o.flatMap(({plan:{site:s,tags:c},owners:u})=>[...Ei(c)+1<=s.tagBudget?[...u.keys()].map((h)=>({site:s,tags:`${c} user:${h}`,page:0,done:!1})):[],{site:s,tags:c,page:0,done:!1}]),this.show(),this.draw(),await this.pump()}catch(o){this.fail(t,o)}}async tally(t,n,e){let r=await Promise.allSettled(e.map(({site:i,tags:o})=>Tc(i,o,this.signal)));if(t===this.gen)n.total=r.reduce((i,o)=>i+(o.status==="fulfilled"?o.value:0),0),this.show(),this.draw()}fail(t,n,e=this.site){if(t!==this.gen||this.signal.aborted)return;this.board.error=Bi(e?.name??this.tabName,n),this.board.searching=!1,this.view.error=this.board.error,this.offer(e,n),this.show(),this.draw()}offer(t,n){if(t&&!this.view.unblocked&&Kh()&&Dn(n)==="ECONNRESET")this.view.asking=t.name}drop(t,n,e){for(let r of t.sources)if(r.site===n)r.done=!0;t.note=[t.note,Bi(n.name,e)].filter(Boolean).join(" · "),this.offer(n,e)}wants(){let{perRow:t,rowsVis:n}=_n(this.cols,this.rows);return this.view.tiles.length<(this.board.top+n+Nh)*t}need(){let{perRow:t,rowsVis:n}=_n(this.cols,this.rows);return(n+Nh)*t}live(t){return this.boards.get(t.key)===t}page(t,n,e){let r=`${t.key}|${n}|${e}`,i=this.pages.get(r);if(!i)i=Uc(t,n,e,this.signal).then((o)=>this.borrow(o)),this.pages.set(r,i),i.catch(()=>this.pages.delete(r));return i}async borrow(t){let n=t.filter((e)=>e.solo===void 0&&e.md5!=="");if(n.length>0)try{Wc(n,await Qc(n.map((e)=>e.md5),this.signal))}catch{}return t}async round(t){let n=gt.flatMap((c)=>{let u=t.sources.find((h)=>h.site===c&&!h.done);return u?[u]:[]}),e=await Promise.all(n.map(async(c)=>{try{return{source:c,posts:await this.page(c.site,c.tags,c.page)}}catch(u){if(t.sources.every((h)=>h.site===c.site)||this.signal.aborted)throw u;return this.drop(t,c.site,u),{source:c,posts:void 0}}}));if(!this.live(t))return;let r=[];for(let{source:c,posts:u}of e){if(!u)continue;c.page++,c.done=u.length<Hn;let h=t.last.get(c);for(let f of u){let a=h&&gh(h.post,f)?h.set:`set:${c.site.key}:${f.id}`;h={post:f,set:a};let g=on(c.site,f.id);if(t.seen.has(g))continue;t.seen.add(g);let d={site:c.site,post:f};if(this.eligible(d))t.kin.set(d,[a,...ah(c.site,f)]),r.push(d);else t.checked++}if(h)t.last.set(c,h)}let i=this.dedupe(t,r),o=++t.rounds,s;if(this.view.order!=="fit")s=n.length>1?eh(i):i;else{let c=Gr(i,this.frame(),this.matched),u=c.slice(0,this.need());if(await this.looks(u),!this.live(t))return;s=[...Gr(u,this.frame(),this.matched),...c.slice(u.length)]}for(let c of s)t.roundOf.set(c,o);t.queue.push(...s),this.ahead(t)}ahead(t){if(this.aheading||this.view.order!=="fit"||!this.live(t))return;let n=t.queue.slice(0,this.need()).filter((e)=>!this.looking.has(on(e.site,e.post.id)));if(n.length===0)return;this.aheading=!0,this.looks(n).then(()=>{this.aheading=!1;for(let e of new Set(n.map((r)=>t.roundOf.get(r)??0)))this.resort(t,e);this.ahead(t)})}resort(t,n){let e=t.queue.flatMap((i,o)=>t.roundOf.get(i)===n?[o]:[]),r=Gr(e.map((i)=>t.queue[i]),this.frame(),this.matched);e.forEach((i,o)=>{t.queue[i]=r[o]})}dedupe(t,n){let e=[];for(let r of n){let i=zi(r.post),o=i.map((c)=>t.same.get(c)).find(Boolean);if(!o){for(let c of i)t.same.set(c,r);e.push(r);continue}if(t.checked++,Oh(r.post)<=Oh(o.post))continue;for(let c of[...i,...zi(o.post)])t.same.set(c,r);let s=e.indexOf(o);if(s>=0){e[s]=r;continue}this.replace(t,o,r)}return e}replace(t,n,e){t.roundOf.set(e,t.roundOf.get(n)??0);let r=t.queue.indexOf(n);if(r>=0){t.queue[r]=e;return}for(let i of t.groups){let o=i.posts.indexOf(n);if(o>=0){i.posts[o]=e,this.posts.set(on(e.site,e.post.id),e),this.thumbQueue.push(e),this.thumbs();return}}}async looks(t){let n=0;await Promise.all(Array.from({length:Sh},async()=>{while(n<t.length)await this.look(t[n++])}))}look(t){let n=on(t.site,t.post.id),e=this.looking.get(n);if(!e)e=(async()=>{let r=this.previewPath(t);await this.cached(t.site,r,t.post.preview);let i=await this.renders.run({job:"match",from:r,colors:this.entry.signature});return this.looked.set(n,i),this.matched.set(t.post,i.match),i})().catch(()=>{return}),this.looking.set(n,e);return e}async pump(){let t=this.gen,n=this.board;if(this.pumping===t||n.sources.length===0)return;this.pumping=t;let e=[],r;try{n.searching=!0;while(t===this.gen){while(e.length<yh&&n.queue.length>0&&this.wants()){let s=n.queue.shift();e.push({pick:s,passed:this.vet(s)})}if(this.ahead(n),!r&&n.queue.length<yh&&n.sources.some((s)=>!s.done)&&this.wants()){let s=this.round(n).then(()=>{if(r===s)r=void 0});s.catch(()=>{}),r=s}let i=e.shift();if(!i){if(!r)break;await r,this.show(),this.draw();continue}let o=await i.passed;if(t!==this.gen)return;if(n.checked++,o)this.admit(i.pick);this.show(),this.draw()}if(t===this.gen)n.searching=!1,this.show(),this.draw()}catch(i){this.fail(t,i)}finally{if(this.saveProbes(),this.pumping===t)this.pumping=0}}eligible({site:t,post:n}){let e=Oe(n);if(!Pc(t,n,this.view.rating)||Lc(n,this.view.block).length>0||!e)return!1;if(this.view.solo&&n.solo===!1)return!1;return this.view.preset==="all"?["png","jpg","jpeg"].includes(e.ext):n.ext==="png"}async vet(t){let[n]=await Promise.all([this.passes(t),this.look(t)]);return n}async passes({site:t,post:n}){return this.view.preset==="all"||t.vouched||this.transparent(t,n)}probes(t){let n=this.probed.get(t.key);if(!n)n=Di(t,"probes.json"),this.probed.set(t.key,n);return n}async transparent(t,n){let e=this.probes(t),r=e[n.id];if(r!==void 0)return r;try{let i=(await qc(t,n.file,this.signal))?.alpha===!0;return e[n.id]=i,this.unsaved.add(t.key),i}catch{return!1}}saveProbes(){for(let t of this.unsaved){let n=gt.find((e)=>e.key===t);if(n)to(n,"probes.json",this.probes(n))}this.unsaved.clear()}admit(t){let{site:n,post:e}=t,r=this.board,i=on(n,e.id);this.posts.set(i,t);let o=r.kin.get(t)??[],s=this.looked.get(i),c=s&&{hash:s.hash,width:e.width,height:e.height},u=this.view.sets==="fold"?this.kindred(r,o,c):void 0;if(u){if(u.posts.push(t),this.register(r,u,o,c),u.open)this.thumbQueue.push(t),this.thumbs();return}let h={posts:[t],open:!1};r.groups.push(h),this.register(r,h,o,c),this.thumbQueue.push(t),this.thumbs()}kindred(t,n,e){for(let r of n){let i=t.kindred.get(r);if(i)return i}return e&&t.shapes.find((r)=>dh(r.shape,e))?.group}register(t,n,e,r){for(let i of e)if(!t.kindred.has(i))t.kindred.set(i,n);if(r)t.shapes.push({shape:r,group:n})}async mateOwners(t){let n=this.owners.get(t.key);if(n)return n;let e=kc(this.home),r=Di(t,"owners.json"),i=this.catalog.palettes.flatMap((u)=>{let h=e.get(u.name);return u.group===this.entry.group&&u.name!==this.entry.name&&h?.site===t.key?[{name:u.name,id:h.id}]:[]}),o=await Promise.all(i.map(async(u)=>{let h=r[u.id];if(h!==void 0)return{...u,owner:h};try{return{...u,owner:(await vi(t,u.id,this.signal))?.owner??""}}catch{return}})),s=new Map;for(let u of o)if(u)r[u.id]=u.owner,s.set(u.name,u.owner);to(t,"owners.json",r);let c=Kc(s);return this.owners.set(t.key,c),c}async cached(t,n,e,r){if(xn(n))return jm(n).size;let i=this.inflight.get(n);if(i)return i;let o=(async()=>{let s=await Xc(t,e,this.signal,r);return _e(Jr(n),{recursive:!0}),Ce(n,s),s.length})();this.inflight.set(n,o);try{return await o}finally{this.inflight.delete(n)}}thumbs(){while(this.thumbing<Sh&&this.thumbQueue.length>0){let t=this.thumbQueue.shift();this.thumbing++,this.thumb(t).catch(()=>{}).finally(()=>{this.thumbing--,this.thumbs()})}}async thumb(t){let{site:n,post:e}=t,r=Jt.cols*this.cell.w,i=Jt.rows*this.cell.h,o=fn(yn(n),"tile",`${Hh(e)}-${r}x${i}.png`);if(!xn(o)){let s=this.previewPath(t);await this.cached(n,s,e.preview),await this.renders.run({job:"thumb",from:s,to:o,width:r,height:i})}this.thumbPath.set(on(n,e.id),o),this.show(),this.draw()}select(){let t=this.view,n=t.tiles[t.focus];if(this.fetch?.abort(),clearTimeout(this.settle),t.fetching=void 0,!n)return;if(this.current?.key===n.key){this.reveal();return}this.settle=setTimeout(()=>void this.load(n),Tm),this.draw()}async load(t){let n=this.view,e=this.posts.get(t.key),r=e&&Oe(e.post);if(!e||!r)return;let{site:i}=e,o=this.board,s=new AbortController;this.fetch=s;try{let c=this.origPath(i,t.id,r.ext);if(!xn(c))n.fetching={id:t.key,got:0,size:0},this.draw();let u=await this.cached(i,c,r.file,(a,g)=>{if(n.fetching?.id===t.key)n.fetching={id:t.key,got:a,size:g},this.draw()});if(s.signal.aborted)return;if(n.fetching=void 0,o!==this.board)return;let h={site:i,id:t.id,key:t.key,path:c,ext:r.ext,size:u,using:"plain",failed:!1};n.preparing=t.key,this.flush();let f=await this.render(h,"plain");if(s.signal.aborted||o!==this.board)return;if(f.clear===0&&Ui()&&this.setting("TTHEME_FIND_REMOVE_BG")!=="off"){if(n.preparing=void 0,n.cutting=t.key,this.flush(),h.cut=await this.cutOut(i,t.id,c,s.signal),s.signal.aborted||o!==this.board)return;if(n.cutting=void 0,h.cut){n.preparing=t.key,this.flush();let a=await this.render(h,"cut").catch(()=>{return});if(s.signal.aborted||o!==this.board)return;if(a&&Tu(a.clear))h.using="cut";else xi(h.cut,{force:!0}),h.cut=void 0,h.failed=!0}else h.failed=!0}if(this.current=h,n.tiles[n.focus]?.key===t.key)await this.present();this.preload()}catch(c){if(!s.signal.aborted&&!this.signal.aborted)n.error=Bi(i.name,c)}finally{if(n.fetching?.id===t.key)n.fetching=void 0;if(n.preparing===t.key)n.preparing=void 0;if(n.cutting===t.key)n.cutting=void 0;this.draw()}}async cutOut(t,n,e,r){let i=fn(yn(t),"cut",`${n}.png`);if(xn(i))return i;try{return _e(Jr(i),{recursive:!0}),await Wu(e,i,r),i}catch{xi(i,{force:!0});return}}swap(){let t=this.current;if(!t?.cut||this.view.shown?.id!==t.key)return;t.using=t.using==="cut"?"plain":"cut",this.reveal()}preload(){let t=this.view;if(t.mode!=="try")return;for(let n of[t.focus+this.direction,t.focus-this.direction]){if(this.prefetching>=Um)return;let e=t.tiles[n],r=e&&this.posts.get(e.key),i=r&&Oe(r.post);if(!r||!i)continue;let{site:o,post:s}=r,c=this.origPath(o,s.id,i.ext);this.prefetching++,this.cached(o,c,i.file).then(()=>this.render({site:o,id:s.id,key:e.key,path:c,ext:i.ext,size:0,using:"plain",failed:!1},"plain")).catch(()=>{}).finally(()=>{this.prefetching--})}}async render(t,n){let e=this.cols*this.cell.w,r=this.rows*this.cell.h,i=Math.min(e,Xm),o=Math.max(1,Math.round(r*i/e)),s=fn(this.scratch,`${t.site.key}-${t.id}${n==="cut"?"c":""}-${i}x${o}.png`),c=`${t.site.key}:${t.id}:${n}`,u=this.clarity.get(c);if(u!==void 0&&xn(s))return{clear:u,path:s};let h=await this.renders.run({job:"show",from:n==="cut"?t.cut:t.path,to:s,width:i,height:o,colors:this.entry,tone:this.tone});return this.clarity.set(c,h),{clear:h,path:s}}async present(){let t=this.current;if(!t)return;let n=t.using,{clear:e,path:r}=await this.render(t,n);if(this.current!==t||t.using!==n)return;this.view.shown={id:t.key,clear:e,bytes:t.size,path:r,cut:t.cut?n==="cut"?"on":"off":t.failed?"failed":"none"}}reveal(){let t=this.view;t.preparing=this.current?.key,this.flush(),this.present().catch((n)=>{t.error=n instanceof Error?n.message:String(n)}).finally(()=>{if(t.preparing===this.current?.key)t.preparing=void 0;this.draw()})}async install(){let t=this.view,n=t.tiles[t.focus],e=this.current;if(!n||e?.key!==n.key||t.preparing!==void 0||t.shown?.id!==n.key)return;t.installing=n.key,t.error=void 0,this.flush();try{await this.renders.run({job:"backdrop",from:e.using==="cut"?e.cut:e.path,source:e.path,home:this.home,colors:this.entry,tone:this.tone,origin:{site:e.site.key,id:e.id,ext:e.ext,from:`${e.site.name} ${e.id} ${e.site.pageUrl(e.id)}`},width:this.cols*this.cell.w,height:this.rows*this.cell.h});let r=Di(e.site,"owners.json");r[e.id]=this.posts.get(e.key)?.post.owner??"",to(e.site,"owners.json",r),Vn(this.home),t.saved=`background · ${this.entry.name} ← ${e.site.name} ${e.id}`,t.installed.push(n.key),this.fetch?.abort(),clearTimeout(this.settle),t.fetching=void 0,t.mode="grid"}catch(r){t.error=r instanceof Error?r.message:String(r)}t.installing=void 0,this.draw()}draw(){if(this.dirty)return;this.dirty=!0,setImmediate(()=>{this.dirty=!1,this.flush()})}flush(){let t=th(this.view,this.cols,this.rows),n="\x1B[?2026h";t.lines.forEach((r,i)=>{n+=`\x1B[${i+1};1H\x1B[K${r}`});let e=new Set;for(let r of t.images){if(e.add(r.id),this.sent.get(r.id)!==r.path)n+=_u(r),this.sent.set(r.id,r.path),this.placed.delete(r.id);let i=`${r.row};${r.col};${r.cols};${r.rows};${r.z}`;if(this.placed.get(r.id)!==i)n+=Cu(r),this.placed.set(r.id,i)}for(let r of this.sent.keys())if(!e.has(r))n+=zu(r),this.sent.delete(r),this.placed.delete(r);this.write(`${n}\x1B[?2026l`)}}function Kh(){if(process.versions.bun)return!0;let[t=0,n=0]=process.versions.node.split(".").map(Number);return t>22||t===22&&n>=21}async function jh(){if(!Kh())return process.stderr.write(`unblock needs node 22.21 or newer — this is ${process.versions.node}
143
+ `),1;let t=await Mh(),n=Rh(process.execPath,process.argv.slice(1),{stdio:"inherit",env:{...process.env,NODE_USE_ENV_PROXY:"1",NODE_NO_WARNINGS:"1",HTTPS_PROXY:`http://127.0.0.1:${t.port}`,NO_PROXY:[process.env.NO_PROXY,Gc()].filter(Boolean).join(","),TTHEME_FIND_PROXY:String(t.port)}}),e=await new Promise((r)=>n.on("exit",(i)=>r(i??1)));return t.close(),e}async function Jh(t){if(process.env.TTHEME_FIND_UNBLOCK==="1"&&!process.env.TTHEME_FIND_PROXY)return jh();let n=Tt(),e=Pt(n),r=Hr(e.palettes,t);if(!process.stdin.isTTY||!process.stdout.isTTY)throw Error("ttheme find needs a terminal");let i=new Ph(n,e,r,r.booru??""),o=await i.run(),s=i.unblock?await jh():o;if(i.saved&&s!==0)return process.stderr.write(`${i.saved}
144
+ `),0;return s}function Ah(t,n){let e=Tt();if(Hr(Pt(e).palettes,t),n==="next"||n==="prev"){let{key:r,at:i,of:o}=wc(e,t,n==="next"?1:-1);return Vn(e),process.stderr.write(`background · ${t} ${i}/${o} ${r}
145
+ `),0}if(n==="drop"){let{key:r,left:i}=$c(e,t);return Vn(e),process.stderr.write(`background · ${t} removed ${r??"the picture"} · ${i} left
146
+ `),0}if(n==="tuned")return Vn(e),0;throw Error(`unknown image action ${n} — next, prev, drop or tuned`)}import{execFileSync as Yp,spawnSync as Vp}from"node:child_process";import{chmodSync as xp,copyFileSync as Bp,existsSync as Qt,mkdirSync as ko,readdirSync as Dp,readFileSync as se,rmSync as Wf,writeFileSync as Qf}from"node:fs";import{homedir as t0}from"node:os";import{dirname as oe,join as ct}from"node:path";import{styleText as co}from"node:util";import{stdout as ef,stdin as fp}from"node:process";import ap from"node:readline";var Uh=(()=>{let t=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(n)=>{let e=0;t.lastIndex=0;while(t.test(n))e+=1;return n.length-e}})(),Th=(t)=>{return t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510},Wh=(t)=>{return t===8987||t===9001||t>=12272&&t<=12287||t>=12289&&t<=12350||t>=12441&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12783&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=65040&&t<=65049||t>=65072&&t<=65106||t>=65108&&t<=65126||t>=65128&&t<=65131||t>=127488&&t<=127490||t>=127504&&t<=127547||t>=127552&&t<=127560||t>=131072&&t<=196605||t>=196608&&t<=262141};var Ym=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,Vm=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Qh=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,xm=/\t{1,1000}/y,Zh=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu,Bm=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Dm=/\p{M}+/gu,tp={limit:1/0,ellipsis:""},qh=(t,n={},e={})=>{let r=n.limit??1/0,i=n.ellipsis??"",o=n?.ellipsisWidth??(i?qh(i,tp,e).width:0),s=0,c=e.controlWidth??0,u=e.tabWidth??8,h=e.emojiWidth??2,f=2,a=e.regularWidth??1,g=e.wideWidth??2,d=[[Bm,a],[Ym,0],[Vm,c],[xm,u],[Zh,h],[Qh,g]],p=0,l=0,k=t.length,v=0,I=!1,E=k,y=Math.max(0,r-o),$=0,H=0,b=0,R=0;t:while(!0){if(H>$||l>=k&&l>p){let O=t.slice($,H)||t.slice(p,l);v=0;for(let P of O.replaceAll(Dm,"")){let G=P.codePointAt(0)||0;if(Th(G))R=2;else if(Wh(G))R=g;else R=a;if(b+R>y)E=Math.min(E,Math.max($,p)+v);if(b+R>r){I=!0;break t}v+=P.length,b+=R}$=H=0}if(l>=k)break t;for(let O=0,P=d.length;O<P;O++){let[G,C]=d[O];if(G.lastIndex=l,G.test(t)){if(v=G===Qh?Uh(t.slice(l,G.lastIndex)):G===Zh?1:G.lastIndex-l,R=v*C,b+R>y)E=Math.min(E,l+Math.floor((y-b)/C));if(b+R>r){I=!0;break t}b+=R,$=p,H=l,l=p=G.lastIndex;continue t}}l+=1}return{width:I?y:b,index:I?E:k,truncated:I,ellipsed:I&&r>=o}},Xh=qh;var np={limit:1/0,ellipsis:"",ellipsisWidth:0},ep=(t,n={})=>{return Xh(t,np,n).width},Kt=ep;var Ur="\x1B",Vh="›",rp=39,eo="\x07",xh="[",ip="]",Bh="m",ro=`${ip}8;;`,_h=new RegExp(`(?:\\${xh}(?<code>\\d+)m|\\${ro}(?<uri>.*)${eo})`,"y"),Ch=(t)=>{if(t>=30&&t<=37)return 39;if(t>=90&&t<=97)return 39;if(t>=40&&t<=47)return 49;if(t>=100&&t<=107)return 49;if(t===1||t===2)return 22;if(t===3)return 23;if(t===4)return 24;if(t===7)return 27;if(t===8)return 28;if(t===9)return 29;if(t===0)return 0;return},zh=(t)=>`${Ur}${xh}${t}${Bh}`,Yh=(t)=>`${Ur}${ro}${t}${eo}`,no=(t,n,e)=>{let r=n[Symbol.iterator](),i=!1,o=!1,s=t.at(-1),c=s===void 0?0:Kt(s),u=r.next(),h=r.next(),f=0;while(!u.done){let a=u.value,g=Kt(a);if(c+g<=e)t[t.length-1]+=a;else t.push(a),c=0;if(a===Ur||a===Vh)i=!0,o=n.startsWith(ro,f+1);if(i){if(o){if(a===eo)i=!1,o=!1}else if(a===Bh)i=!1}else if(c+=g,c===e&&!h.done)t.push(""),c=0;u=h,h=r.next(),f+=a.length}if(s=t.at(-1),!c&&s!==void 0&&s.length&&t.length>1)t[t.length-2]+=t.pop()},op=(t)=>{let n=t.split(" "),e=n.length;while(e){if(Kt(n[e-1]))break;e--}if(e===n.length)return t;return n.slice(0,e).join(" ")+n.slice(e).join("")},sp=(t,n,e={})=>{if(e.trim!==!1&&t.trim()==="")return"";let r="",i,o,s=t.split(" "),c=[""],u=0;for(let a=0;a<s.length;a++){let g=s[a];if(e.trim!==!1){let p=c.at(-1)??"",l=p.trimStart();if(p.length!==l.length)c[c.length-1]=l,u=Kt(l)}if(a!==0){if(u>=n&&(e.wordWrap===!1||e.trim===!1))c.push(""),u=0;if(u||e.trim===!1)c[c.length-1]+=" ",u++}let d=Kt(g);if(e.hard&&d>n){let p=n-u,l=1+Math.floor((d-p-1)/n);if(Math.floor((d-1)/n)<l)c.push("");no(c,g,n),u=Kt(c.at(-1)??"");continue}if(u+d>n&&u&&d){if(e.wordWrap===!1&&u<n){no(c,g,n),u=Kt(c.at(-1)??"");continue}c.push(""),u=0}if(u+d>n&&e.wordWrap===!1){no(c,g,n),u=Kt(c.at(-1)??"");continue}c[c.length-1]+=g,u+=d}if(e.trim!==!1)c=c.map((a)=>op(a));let h=c.join(`
147
+ `),f=!1;for(let a=0;a<h.length;a++){let g=h[a];if(r+=g,!f){if(f=g>="\uD800"&&g<="\uDBFF",f)continue}else f=!1;if(g===Ur||g===Vh){_h.lastIndex=a+1;let p=_h.exec(h)?.groups;if(p?.code!==void 0){let l=Number.parseFloat(p.code);i=l===rp?void 0:l}else if(p?.uri!==void 0)o=p.uri.length===0?void 0:p.uri}if(h[a+1]===`
148
+ `){if(o)r+=Yh("");let d=i?Ch(i):void 0;if(i&&d)r+=zh(d)}else if(g===`
149
+ `){if(i&&Ch(i))r+=zh(i);if(o)r+=Yh(o)}}return r},cp=/\r?\n/;function Fn(t,n,e){return String(t).normalize().split(cp).map((r)=>sp(r,n,e)).join(`
150
+ `)}var Wt=nr(oo(),1);function te(t,n,e){if(!e.some((s)=>!s.disabled))return t;let r=t+n,i=Math.max(e.length-1,0),o=r<0?i:r>i?0:r;return e[o]?.disabled?te(o,n<0?-1:1,e):o}function Tr(t,n,e,r){let i=r.split(`
151
+ `),o=0,s=t;for(let u of i){if(s<=u.length)break;s-=u.length+1,o++}for(o=Math.max(0,Math.min(i.length-1,o+e)),s=Math.min(s,i[o].length)+n;s<0&&o>0;)o--,s+=i[o].length+1;for(;s>i[o].length&&o<i.length-1;)s-=i[o].length+1,o++;s=Math.max(0,Math.min(i[o].length,s));let c=0;for(let u=0;u<o;u++)c+=i[u].length+1;return c+s}var gp=["up","down","left","right","space","enter","cancel"],lp=["January","February","March","April","May","June","July","August","September","October","November","December"],At={actions:new Set(gp),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0,date:{monthNames:[...lp],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(t,n)=>`There are only ${t} days in ${n}`,afterMin:(t)=>`Date must be on or after ${t.toISOString().slice(0,10)}`,beforeMax:(t)=>`Date must be on or before ${t.toISOString().slice(0,10)}`}}};function rf(t,n){if(typeof t=="string")return At.aliases.get(t)===n;for(let e of t)if(e!==void 0&&rf(e,n))return!0;return!1}function dp(t,n){if(t===n)return;let e=t.split(`
152
+ `),r=n.split(`
153
+ `),i=Math.max(e.length,r.length),o=[];for(let s=0;s<i;s++)e[s]!==r[s]&&o.push(s);return{lines:o,numLinesBefore:e.length,numLinesAfter:r.length,numLines:i}}var Nb=globalThis.process.platform.startsWith("win"),uo=Symbol("clack:cancel");function ne(t){return t===uo}function Wr(t,n){let e=t;e.isTTY&&e.setRawMode(n)}var Zr=(t)=>("columns"in t)&&typeof t.columns=="number"?t.columns:80,fo=(t)=>("rows"in t)&&typeof t.rows=="number"?t.rows:20;function ze(t,n,e,r=e,i=e,o){let s=Zr(t??ef);return Fn(n,s-e.length,{hard:!0,trim:!1}).split(`
154
+ `).map((c,u,h)=>{let f=o?o(c,u):c;return u===0?`${r}${f}`:u===h.length-1?`${i}${f}`:`${e}${f}`}).join(`
155
+ `)}function of(t,n){if("~standard"in t){let e=t["~standard"].validate(n);if(e instanceof Promise)throw TypeError("Schema validation must be synchronous. Update `validate()` and remove any asynchronous logic.");return e.issues?.at(0)?.message}return t(n)}class pn{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(t,n=!0){let{input:e=fp,output:r=ef,render:i,signal:o,...s}=t;this.opts=s,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=i.bind(this),this._track=n,this._abortSignal=o,this.input=e,this.output=r}unsubscribe(){this._subscribers.clear()}setSubscriber(t,n){let e=this._subscribers.get(t)??[];e.push(n),this._subscribers.set(t,e)}on(t,n){this.setSubscriber(t,{cb:n})}once(t,n){this.setSubscriber(t,{cb:n,once:!0})}emit(t,...n){let e=this._subscribers.get(t)??[],r=[];for(let i of e)i.cb(...n),i.once&&r.push(()=>e.splice(e.indexOf(i),1));for(let i of r)i()}prompt(){return new Promise((t)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),t(uo);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=ap.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on("keypress",this.onKeypress),Wr(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(Wt.cursor.show),this.output.off("resize",this.render),Wr(this.input,!1),t(this.value)}),this.once("cancel",()=>{this.output.write(Wt.cursor.show),this.output.off("resize",this.render),Wr(this.input,!1),t(uo)})})}_isActionKey(t,n){return t==="\t"}_shouldSubmit(t,n){return!0}_setValue(t){this.value=t,this.emit("value",this.value)}_setUserInput(t,n){this.userInput=t??"",this.emit("userInput",this.userInput),n&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}onKeypress(t,n){if(this._track&&n.name!=="return"&&(n.name&&this._isActionKey(t,n)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),n?.name&&(!this._track&&At.aliases.has(n.name)&&this.emit("cursor",At.aliases.get(n.name)),At.actions.has(n.name)&&this.emit("cursor",n.name)),t&&(t.toLowerCase()==="y"||t.toLowerCase()==="n")&&this.emit("confirm",t.toLowerCase()==="y"),this.emit("key",t,n),n?.name==="return"&&this._shouldSubmit(t,n)){if(this.opts.validate){let e=of(this.opts.validate,this.value);e&&(this.error=e instanceof Error?e.message:e,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}rf([t,n?.name,n?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
156
+ `),Wr(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let t=Fn(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
157
+ `).length-1;this.output.write(Wt.cursor.move(-999,t*-1))}render(){let t=Fn(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(t!==this._prevFrame){if(this.state==="initial")this.output.write(Wt.cursor.hide);else{let n=dp(this._prevFrame,t),e=fo(this.output);if(this.restoreCursor(),n){let r=Math.max(0,n.numLinesAfter-e),i=Math.max(0,n.numLinesBefore-e),o=n.lines.find((s)=>s>=r);if(o===void 0){this._prevFrame=t;return}if(n.lines.length===1){this.output.write(Wt.cursor.move(0,o-i)),this.output.write(Wt.erase.lines(1));let s=t.split(`
158
+ `);this.output.write(s[o]),this._prevFrame=t,this.output.write(Wt.cursor.move(0,s.length-o-1));return}else if(n.lines.length>1){if(r<i)o=r;else{let c=o-i;c>0&&this.output.write(Wt.cursor.move(0,c))}this.output.write(Wt.erase.down());let s=t.split(`
106
159
  `).slice(o);this.output.write(s.join(`
107
- `)),this._prevFrame=n;return}}this.output.write(Zn.erase.down())}this.output.write(n),this.state==="initial"&&(this.state="active"),this._prevFrame=n}}}function fm(n,r){if(n===void 0||r.length===0)return 0;let e=r.findIndex((t)=>t.value===n);return e!==-1?e:0}function gm(n,r){return(r.label??String(r.value)).toLowerCase().includes(n.toLowerCase())}function lm(n,r){if(r)return n?r:r[0]}var am=class extends sr{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#r=0;#i="";#n;#o;#u;get cursor(){return this.#r}get userInputWithCursor(){if(!this.userInput)return qi(["inverse","hidden"],"_");if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let r=this.userInput.slice(0,this.cursor),e=this.userInput.slice(this.cursor,this.cursor+1),t=this.userInput.slice(this.cursor+1);return`${r}${qi("inverse",e)}${t}`}get options(){return typeof this.#o=="function"?this.#o():this.#o}constructor(r){super(r),this.#o=r.options,this.#u=r.placeholder;let e=this.options;this.filteredOptions=[...e],this.multiple=r.multiple===!0,this.#n=typeof r.options=="function"?r.filter:r.filter??gm;let t;if(r.initialValue&&Array.isArray(r.initialValue)?this.multiple?t=r.initialValue:t=r.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(t=[this.options[0]?.value]),t)for(let i of t){let o=e.findIndex((s)=>s.value===i);o!==-1&&(this.toggleSelected(i),this.#r=o)}this.focusedValue=this.options[this.#r]?.value,this.on("key",(i,o)=>this.#e(i,o)),this.on("userInput",(i)=>this.#t(i))}_isActionKey(r,e){return r==="\t"||this.multiple&&this.isNavigating&&e.name==="space"&&r!==void 0&&r!==""}#e(r,e){let t=e.name==="up",i=e.name==="down",o=e.name==="return",s=this.userInput===""||this.userInput==="\t",u=this.#u,c=this.options,h=u!==void 0&&u!==""&&c.some((f)=>!f.disabled&&(this.#n?this.#n(u,f):!0));if(e.name==="tab"&&s&&h){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(u,!0),this.isNavigating=!1;return}t||i?(this.#r=dr(this.#r,t?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#r]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):o?this.value=lm(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(e.name==="tab"||this.isNavigating&&e.name==="space")?this.toggleSelected(this.focusedValue):this.isNavigating=!1:(this.focusedValue&&(this.selectedValues=[this.focusedValue]),this.isNavigating=!1)}deselectAll(){this.selectedValues=[]}toggleSelected(r){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(r)?this.selectedValues=this.selectedValues.filter((e)=>e!==r):this.selectedValues=[...this.selectedValues,r]:this.selectedValues=[r])}#t(r){if(r!==this.#i){this.#i=r;let e=this.options;r&&this.#n?this.filteredOptions=e.filter((o)=>this.#n?.(r,o)):this.filteredOptions=[...e];let t=fm(this.focusedValue,this.filteredOptions);this.#r=dr(t,0,this.filteredOptions);let i=this.filteredOptions[this.#r];i&&!i.disabled?this.focusedValue=i.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}};class Vi extends sr{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(n){super(n,!1),this.value=!!n.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(r)=>{this.output.write(Zn.cursor.move(0,-1)),this.value=r,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var dm={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function Mh(n){return[...n].map((r)=>dm[r])}function mm(n){let r=new Intl.DateTimeFormat(n,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2000,0,15)),e=[],t="/";for(let i of r)i.type==="literal"?t=i.value.trim()||i.value:(i.type==="year"||i.type==="month"||i.type==="day")&&e.push({type:i.type,len:i.type==="year"?4:2});return{segments:e,separator:t}}function Zi(n){return Number.parseInt((n||"0").replace(/_/g,"0"),10)||0}function vt(n){return{year:Zi(n.year),month:Zi(n.month),day:Zi(n.day)}}function Xi(n,r){return new Date(n||2001,r||1,0).getDate()}function Ih(n){let{year:r,month:e,day:t}=vt(n);if(!r||r<0||r>9999||!e||e<1||e>12||!t||t<1)return;let i=new Date(Date.UTC(r,e-1,t));if(!(i.getUTCFullYear()!==r||i.getUTCMonth()!==e-1||i.getUTCDate()!==t))return{year:r,month:e,day:t}}function Eh(n){let r=Ih(n);return r?new Date(Date.UTC(r.year,r.month-1,r.day)):void 0}function $m(n,r,e,t){let i=e?{year:e.getUTCFullYear(),month:e.getUTCMonth()+1,day:e.getUTCDate()}:null,o=t?{year:t.getUTCFullYear(),month:t.getUTCMonth()+1,day:t.getUTCDate()}:null;return n==="year"?{min:i?.year??1,max:o?.year??9999}:n==="month"?{min:i&&r.year===i.year?i.month:1,max:o&&r.year===o.year?o.month:12}:{min:i&&r.year===i.year&&r.month===i.month?i.day:1,max:o&&r.year===o.year&&r.month===o.month?o.day:Xi(r.year,r.month)}}class Sh extends sr{#r;#i;#n;#o;#u;#e={segmentIndex:0,positionInSegment:0};#t=!0;#s=null;inlineError="";get segmentCursor(){return{...this.#e}}get segmentValues(){return{...this.#n}}get segments(){return this.#r}get separator(){return this.#i}get formattedValue(){return this.#g(this.#n)}#g(n){return this.#r.map((r)=>n[r.type]).join(this.#i)}#c(){this._setUserInput(this.#g(this.#n)),this._setValue(Eh(this.#n)??void 0)}constructor(n){let r=n.format?{segments:Mh(n.format),separator:n.separator??"/"}:mm(n.locale),e=n.separator??r.separator,t=n.format?Mh(n.format):r.segments,i=n.initialValue??n.defaultValue,o=i?{year:String(i.getUTCFullYear()).padStart(4,"0"),month:String(i.getUTCMonth()+1).padStart(2,"0"),day:String(i.getUTCDate()).padStart(2,"0")}:{year:"____",month:"__",day:"__"},s=t.map((u)=>o[u.type]).join(e);super({...n,initialUserInput:s},!1),this.#r=t,this.#i=e,this.#n=o,this.#o=n.minDate,this.#u=n.maxDate,this.#c(),this.on("cursor",(u)=>this.#d(u)),this.on("key",(u,c)=>this.#m(u,c)),this.on("finalize",()=>this.#$(n))}#h(){let n=Math.max(0,Math.min(this.#e.segmentIndex,this.#r.length-1)),r=this.#r[n];if(r)return this.#e.positionInSegment=Math.max(0,Math.min(this.#e.positionInSegment,r.len-1)),{segment:r,index:n}}#f(n){this.inlineError="",this.#s=null;let r=this.#h();r&&(this.#e.segmentIndex=Math.max(0,Math.min(this.#r.length-1,r.index+n)),this.#e.positionInSegment=0,this.#t=!0)}#l(n){let r=this.#h();if(!r)return;let{segment:e}=r,t=this.#n[e.type],i=!t||t.replace(/_/g,"")==="",o=Number.parseInt((t||"0").replace(/_/g,"0"),10)||0,s=$m(e.type,vt(this.#n),this.#o,this.#u),u;i?u=n===1?s.min:s.max:u=Math.max(Math.min(s.max,o+n),s.min),this.#n={...this.#n,[e.type]:u.toString().padStart(e.len,"0")},this.#t=!0,this.#s=null,this.#c()}#d(n){if(n)switch(n){case"right":return this.#f(1);case"left":return this.#f(-1);case"up":return this.#l(1);case"down":return this.#l(-1)}}#m(n,r){if(r?.name==="backspace"||r?.sequence===""||r?.sequence==="\b"||n===""||n==="\b"){this.inlineError="";let e=this.#h();if(!e)return;if(!this.#n[e.segment.type].replace(/_/g,"")){this.#f(-1);return}this.#n[e.segment.type]="_".repeat(e.segment.len),this.#t=!0,this.#e.positionInSegment=0,this.#c();return}if(r?.name==="tab"){this.inlineError="";let e=this.#h();if(!e)return;let t=r.shift?-1:1,i=e.index+t;i>=0&&i<this.#r.length&&(this.#e.segmentIndex=i,this.#e.positionInSegment=0,this.#t=!0);return}if(n&&/^[0-9]$/.test(n)){let e=this.#h();if(!e)return;let{segment:t}=e,i=!this.#n[t.type].replace(/_/g,"");if(this.#t&&this.#s!==null&&!i){let g=this.#s+n,d={...this.#n,[t.type]:g},w=this.#a(d,t);if(w){this.inlineError=w,this.#s=null,this.#t=!1;return}this.inlineError="",this.#n[t.type]=g,this.#s=null,this.#t=!1,this.#c(),e.index<this.#r.length-1&&(this.#e.segmentIndex=e.index+1,this.#e.positionInSegment=0,this.#t=!0);return}this.#t&&!i&&(this.#n[t.type]="_".repeat(t.len),this.#e.positionInSegment=0),this.#t=!1,this.#s=null;let o=this.#n[t.type],s=o.indexOf("_"),u=s>=0?s:Math.min(this.#e.positionInSegment,t.len-1);if(u<0||u>=t.len)return;let c=o.slice(0,u)+n+o.slice(u+1),h=!1;if(u===0&&o==="__"&&(t.type==="month"||t.type==="day")){let g=Number.parseInt(n,10);c=`0${n}`,h=g<=(t.type==="month"?1:2)}if(t.type==="year"&&(c=(o.replace(/_/g,"")+n).padStart(t.len,"_")),!c.includes("_")){let g={...this.#n,[t.type]:c},d=this.#a(g,t);if(d){this.inlineError=d;return}}this.inlineError="",this.#n[t.type]=c;let f=c.includes("_")?void 0:Ih(this.#n);if(f){let{year:g,month:d}=f,w=Xi(g,d);this.#n={year:String(Math.max(0,Math.min(9999,g))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,d))).padStart(2,"0"),day:String(Math.max(1,Math.min(w,f.day))).padStart(2,"0")}}this.#c();let l=c.indexOf("_");h?(this.#t=!0,this.#s=n):l>=0?this.#e.positionInSegment=l:s>=0&&e.index<this.#r.length-1?(this.#e.segmentIndex=e.index+1,this.#e.positionInSegment=0,this.#t=!0):this.#e.positionInSegment=Math.min(u+1,t.len-1)}}#a(n,r){let{month:e,day:t}=vt(n);if(r.type==="month"&&(e<0||e>12))return Pn.date.messages.invalidMonth;if(r.type==="day"&&(t<0||t>31))return Pn.date.messages.invalidDay(31,"any month")}#$(n){let{year:r,month:e,day:t}=vt(this.#n);if(r&&e&&t){let i=Xi(r,e);this.#n={...this.#n,day:String(Math.min(t,i)).padStart(2,"0")}}this.value=Eh(this.#n)??n.defaultValue??void 0}}var wm=class extends sr{options;cursor=0;#r;getGroupItems(r){return this.options.filter((e)=>e.group===r)}isGroupSelected(r){let e=this.getGroupItems(r),t=this.value;return t===void 0?!1:e.every((i)=>t.includes(i.value))}toggleValue(){let r=this.options[this.cursor];if(r!==void 0)if(this.value===void 0&&(this.value=[]),r.group===!0){let e=r.value,t=this.getGroupItems(e);this.isGroupSelected(e)?this.value=this.value.filter((i)=>t.findIndex((o)=>o.value===i)===-1):this.value=[...this.value,...t.map((i)=>i.value)],this.value=Array.from(new Set(this.value))}else{let e=this.value.includes(r.value);this.value=e?this.value.filter((t)=>t!==r.value):[...this.value,r.value]}}constructor(r){super(r,!1);let{options:e}=r;this.#r=r.selectableGroups!==!1,this.options=Object.entries(e).flatMap(([t,i])=>[{value:t,group:!0,label:t},...i.map((o)=>({...o,group:t}))]),this.value=[...r.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:t})=>t===r.cursorAt),this.#r?0:1),this.on("cursor",(t)=>{switch(t){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let i=this.options[this.cursor]?.group===!0;!this.#r&&i&&(this.cursor=this.cursor===0?this.options.length-1:this.cursor-1);break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let i=this.options[this.cursor]?.group===!0;!this.#r&&i&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},pm=new Set(["up","down","left","right"]);class Nh extends sr{#r=!1;#i;focused="editor";get userInputWithCursor(){if(this.state==="submit")return this.userInput;let n=this.userInput;if(this.cursor>=n.length)return`${n}█`;let r=n.slice(0,this.cursor),e=n.slice(this.cursor,this.cursor+1),t=n.slice(this.cursor+1);return e===`
108
- `?`${r}█
109
- ${t}`:`${r}${qi("inverse",e)}${t}`}get cursor(){return this._cursor}#n(n){if(this.userInput.length===0){this._setUserInput(n);return}this._setUserInput(this.userInput.slice(0,this.cursor)+n+this.userInput.slice(this.cursor))}#o(n){let r=this.value??"";switch(n){case"up":this._cursor=Mt(this._cursor,0,-1,r);return;case"down":this._cursor=Mt(this._cursor,0,1,r);return;case"left":this._cursor=Mt(this._cursor,-1,0,r);return;case"right":this._cursor=Mt(this._cursor,1,0,r);return}}_shouldSubmit(n,r){if(this.#i)return this.focused==="submit"?!0:(this.#n(`
110
- `),this._cursor++,!1);let e=this.#r;return this.#r=!0,e&&this.cursor===this.userInput.length?(this.userInput[this.cursor-1]===`
111
- `&&(this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--),!0):(this.#n(`
112
- `),this._cursor++,!1)}constructor(n){let r=n.initialUserInput??n.initialValue;super({...n,initialUserInput:r},!1),r!==void 0&&(this._cursor=r.length),this.#i=n.showSubmit??!1,this.on("key",(e,t)=>{if(t?.name&&pm.has(t.name)){this.#r=!1,this.#o(t.name);return}if(e==="\t"&&this.#i){this.focused=this.focused==="editor"?"submit":"editor";return}if(t?.name!=="return"){if(this.#r=!1,t?.name==="backspace"&&this.cursor>0){this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--;return}if(t?.name==="delete"&&this.cursor<this.userInput.length){this._setUserInput(this.userInput.slice(0,this.cursor)+this.userInput.slice(this.cursor+1));return}e&&(this.#i&&this.focused==="submit"&&(this.focused="editor"),this.#n(e??""),this._cursor++)}}),this.on("userInput",(e)=>{this._setValue(e)}),this.on("finalize",()=>{this.value||(this.value=n.defaultValue),this.value===void 0&&(this.value="")})}}class zi extends sr{options;cursor=0;get _value(){return this.options[this.cursor]?.value}get _enabledOptions(){return this.options.filter((n)=>n.disabled!==!0)}toggleAll(){let n=this._enabledOptions,r=this.value!==void 0&&this.value.length===n.length;this.value=r?[]:n.map((e)=>e.value)}toggleInvert(){let n=this.value;if(!n)return;let r=this._enabledOptions.filter((e)=>!n.includes(e.value));this.value=r.map((e)=>e.value)}toggleValue(){this.value===void 0&&(this.value=[]);let n=this.value.includes(this._value);this.value=n?this.value.filter((r)=>r!==this._value):[...this.value,this._value]}constructor(n){super(n,!1),this.options=n.options,this.value=[...n.initialValues??[]];let r=Math.max(this.options.findIndex(({value:e})=>e===n.cursorAt),0);this.cursor=this.options[r]?.disabled?dr(r,1,this.options):r,this.on("key",(e,t)=>{t.name==="a"&&this.toggleAll(),t.name==="i"&&this.toggleInvert()}),this.on("cursor",(e)=>{switch(e){case"left":case"up":this.cursor=dr(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=dr(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}var Hh=class extends sr{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){let r=this._selectedValue;this.value=r===void 0?void 0:r.value}constructor(r){super(r,!1),this.options=r.options;let e=this.options.findIndex(({value:i})=>i===r.initialValue),t=e===-1?0:e;this.cursor=this.options[t]?.disabled?dr(t,1,this.options):t,this.changeValue(),this.on("cursor",(i)=>{switch(i){case"left":case"up":this.cursor=dr(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=dr(this.cursor,1,this.options);break}this.changeValue()})}};import{styleText as E,stripVTControlCharacters as bp}from"node:util";import Yn from"node:process";var Lh=Te(Wi(),1);function bm(){if(Yn.platform!=="win32")return Yn.env.TERM!=="linux";return Boolean(Yn.env.CI)||Boolean(Yn.env.WT_SESSION)||Boolean(Yn.env.TERMINUS_SUBLIME)||Yn.env.ConEmuTask==="{cmd::Cmder}"||Yn.env.TERM_PROGRAM==="Terminus-Sublime"||Yn.env.TERM_PROGRAM==="vscode"||Yn.env.TERM==="xterm-256color"||Yn.env.TERM==="alacritty"||Yn.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var km=bm();var dn=(n,r)=>km?n:r,Mm=dn("◆","*"),Em=dn("■","x"),vm=dn("▲","x"),Jh=dn("◇","o"),Fm=dn("┌","T"),hn=dn("│","|"),Gr=dn("└","—"),vp=dn("┐","T"),Fp=dn("┘","—"),Yi=dn("●",">"),It=dn("○"," "),ym=dn("◻","[•]"),Oh=dn("◼","[+]"),jh=dn("◻","[ ]"),yp=dn("▪","•"),Rh=dn("─","-"),Im=dn("╮","+"),Sm=dn("├","+"),Nm=dn("╯","+"),Hm=dn("╰","+"),Ip=dn("╭","+"),Sp=dn("●","•"),Np=dn("◆","*"),Hp=dn("▲","!"),Op=dn("■","x"),_i=(n)=>{switch(n){case"initial":case"active":return E("cyan",Mm);case"cancel":return E("red",Em);case"error":return E("yellow",vm);case"submit":return E("green",Jh)}},Kh=(n)=>{switch(n){case"initial":case"active":return E("cyan",hn);case"cancel":return E("red",hn);case"error":return E("yellow",hn);case"submit":return E("green",hn)}};function Ph(n,r){let e=[`${r?`${E("cyan",hn)} `:""}${n.join(" • ")}`];return r&&e.push(E("cyan",Gr)),e}var Gh=(n,r,e,t,i,o=!1)=>{let s=r,u=0;if(o)for(let c=t-1;c>=e;c--){let h=n[c];if(h&&(s-=h.length),u++,s<=i)break}else for(let c=e;c<t;c++){let h=n[c];if(h&&(s-=h.length),u++,s<=i)break}return{lineCount:s,removals:u}},Ci=({cursor:n,options:r,style:e,output:t=process.stdout,maxItems:i=Number.POSITIVE_INFINITY,columnPadding:o=0,rowPadding:s=4})=>{let u=Ft(t)-o,c=Ti(t),h=E("dim","..."),f=Math.max(c-s,0),l=Math.max(Math.min(i,f),5),g=0;n>=l-3&&(g=Math.max(Math.min(n-l+3,r.length-l),0));let d=l<r.length&&g>0,w=l<r.length&&g+l<r.length,m=Math.min(g+l,r.length),b=[],F=0;d&&F++,w&&F++;let S=g+(d?1:0),k=m-(w?1:0);for(let p=S;p<k;p++){let R=r[p],M=R?e(R,p===n):"",j=Er(M,u,{hard:!0,trim:!1}).split(`
113
- `);b.push(j),F+=j.length}if(F>f){let p=0,R=0,M=F,j=n-S,H=f,J=()=>Gh(b,M,0,j,H),G=()=>Gh(b,M,j+1,b.length,H,!0);d?({lineCount:M,removals:p}=J(),M>H&&(w||(H-=1),{lineCount:M,removals:R}=G())):(w||(H-=1),{lineCount:M,removals:R}=G(),M>H&&(H-=1,{lineCount:M,removals:p}=J())),p>0&&(d=!0,b.splice(0,p)),R>0&&(w=!0,b.splice(b.length-R,R))}let y=[];d&&y.push(h);for(let p of b)for(let R of p)y.push(R);return w&&y.push(h),y};var Uh=(n)=>{let r=n.active??"Yes",e=n.inactive??"No";return new Vi({active:r,inactive:e,signal:n.signal,input:n.input,output:n.output,initialValue:n.initialValue??!0,render(){let t=n.withGuide??Pn.withGuide,i=`${_i(this.state)} `,o=t?`${E("gray",hn)} `:"",s=vr(n.output,n.message,o,i),u=`${t?`${E("gray",hn)}
160
+ `)),this._prevFrame=t;return}}this.output.write(Wt.erase.down())}this.output.write(t),this.state==="initial"&&(this.state="active"),this._prevFrame=t}}}function mp(t,n){if(t===void 0||n.length===0)return 0;let e=n.findIndex((r)=>r.value===t);return e!==-1?e:0}function pp(t,n){return(n.label??String(n.value)).toLowerCase().includes(t.toLowerCase())}function wp(t,n){if(n)return t?n:n[0]}var $p=class extends pn{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#n=0;#i="";#t;#o;#c;get cursor(){return this.#n}get userInputWithCursor(){if(!this.userInput)return co(["inverse","hidden"],"_");if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let n=this.userInput.slice(0,this.cursor),e=this.userInput.slice(this.cursor,this.cursor+1),r=this.userInput.slice(this.cursor+1);return`${n}${co("inverse",e)}${r}`}get options(){return typeof this.#o=="function"?this.#o():this.#o}constructor(n){super(n),this.#o=n.options,this.#c=n.placeholder;let e=this.options;this.filteredOptions=[...e],this.multiple=n.multiple===!0,this.#t=typeof n.options=="function"?n.filter:n.filter??pp;let r;if(n.initialValue&&Array.isArray(n.initialValue)?this.multiple?r=n.initialValue:r=n.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(r=[this.options[0]?.value]),r)for(let i of r){let o=e.findIndex((s)=>s.value===i);o!==-1&&(this.toggleSelected(i),this.#n=o)}this.focusedValue=this.options[this.#n]?.value,this.on("key",(i,o)=>this.#e(i,o)),this.on("userInput",(i)=>this.#r(i))}_isActionKey(n,e){return n==="\t"||this.multiple&&this.isNavigating&&e.name==="space"&&n!==void 0&&n!==""}#e(n,e){let r=e.name==="up",i=e.name==="down",o=e.name==="return",s=this.userInput===""||this.userInput==="\t",c=this.#c,u=this.options,h=c!==void 0&&c!==""&&u.some((f)=>!f.disabled&&(this.#t?this.#t(c,f):!0));if(e.name==="tab"&&s&&h){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(c,!0),this.isNavigating=!1;return}r||i?(this.#n=te(this.#n,r?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#n]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):o?this.value=wp(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(e.name==="tab"||this.isNavigating&&e.name==="space")?this.toggleSelected(this.focusedValue):this.isNavigating=!1:(this.focusedValue&&(this.selectedValues=[this.focusedValue]),this.isNavigating=!1)}deselectAll(){this.selectedValues=[]}toggleSelected(n){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(n)?this.selectedValues=this.selectedValues.filter((e)=>e!==n):this.selectedValues=[...this.selectedValues,n]:this.selectedValues=[n])}#r(n){if(n!==this.#i){this.#i=n;let e=this.options;n&&this.#t?this.filteredOptions=e.filter((o)=>this.#t?.(n,o)):this.filteredOptions=[...e];let r=mp(this.focusedValue,this.filteredOptions);this.#n=te(r,0,this.filteredOptions);let i=this.filteredOptions[this.#n];i&&!i.disabled?this.focusedValue=i.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}};class ao extends pn{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(t){super(t,!1),this.value=!!t.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(n)=>{this.output.write(Wt.cursor.move(0,-1)),this.value=n,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var bp={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function tf(t){return[...t].map((n)=>bp[n])}function kp(t){let n=new Intl.DateTimeFormat(t,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2000,0,15)),e=[],r="/";for(let i of n)i.type==="literal"?r=i.value.trim()||i.value:(i.type==="year"||i.type==="month"||i.type==="day")&&e.push({type:i.type,len:i.type==="year"?4:2});return{segments:e,separator:r}}function so(t){return Number.parseInt((t||"0").replace(/_/g,"0"),10)||0}function Qr(t){return{year:so(t.year),month:so(t.month),day:so(t.day)}}function ho(t,n){return new Date(t||2001,n||1,0).getDate()}function sf(t){let{year:n,month:e,day:r}=Qr(t);if(!n||n<0||n>9999||!e||e<1||e>12||!r||r<1)return;let i=new Date(Date.UTC(n,e-1,r));if(!(i.getUTCFullYear()!==n||i.getUTCMonth()!==e-1||i.getUTCDate()!==r))return{year:n,month:e,day:r}}function nf(t){let n=sf(t);return n?new Date(Date.UTC(n.year,n.month-1,n.day)):void 0}function Ep(t,n,e,r){let i=e?{year:e.getUTCFullYear(),month:e.getUTCMonth()+1,day:e.getUTCDate()}:null,o=r?{year:r.getUTCFullYear(),month:r.getUTCMonth()+1,day:r.getUTCDate()}:null;return t==="year"?{min:i?.year??1,max:o?.year??9999}:t==="month"?{min:i&&n.year===i.year?i.month:1,max:o&&n.year===o.year?o.month:12}:{min:i&&n.year===i.year&&n.month===i.month?i.day:1,max:o&&n.year===o.year&&n.month===o.month?o.day:ho(n.year,n.month)}}class cf extends pn{#n;#i;#t;#o;#c;#e={segmentIndex:0,positionInSegment:0};#r=!0;#s=null;inlineError="";get segmentCursor(){return{...this.#e}}get segmentValues(){return{...this.#t}}get segments(){return this.#n}get separator(){return this.#i}get formattedValue(){return this.#a(this.#t)}#a(t){return this.#n.map((n)=>t[n.type]).join(this.#i)}#u(){this._setUserInput(this.#a(this.#t)),this._setValue(nf(this.#t)??void 0)}constructor(t){let n=t.format?{segments:tf(t.format),separator:t.separator??"/"}:kp(t.locale),e=t.separator??n.separator,r=t.format?tf(t.format):n.segments,i=t.initialValue??t.defaultValue,o=i?{year:String(i.getUTCFullYear()).padStart(4,"0"),month:String(i.getUTCMonth()+1).padStart(2,"0"),day:String(i.getUTCDate()).padStart(2,"0")}:{year:"____",month:"__",day:"__"},s=r.map((c)=>o[c.type]).join(e);super({...t,initialUserInput:s},!1),this.#n=r,this.#i=e,this.#t=o,this.#o=t.minDate,this.#c=t.maxDate,this.#u(),this.on("cursor",(c)=>this.#d(c)),this.on("key",(c,u)=>this.#m(c,u)),this.on("finalize",()=>this.#p(t))}#h(){let t=Math.max(0,Math.min(this.#e.segmentIndex,this.#n.length-1)),n=this.#n[t];if(n)return this.#e.positionInSegment=Math.max(0,Math.min(this.#e.positionInSegment,n.len-1)),{segment:n,index:t}}#f(t){this.inlineError="",this.#s=null;let n=this.#h();n&&(this.#e.segmentIndex=Math.max(0,Math.min(this.#n.length-1,n.index+t)),this.#e.positionInSegment=0,this.#r=!0)}#g(t){let n=this.#h();if(!n)return;let{segment:e}=n,r=this.#t[e.type],i=!r||r.replace(/_/g,"")==="",o=Number.parseInt((r||"0").replace(/_/g,"0"),10)||0,s=Ep(e.type,Qr(this.#t),this.#o,this.#c),c;i?c=t===1?s.min:s.max:c=Math.max(Math.min(s.max,o+t),s.min),this.#t={...this.#t,[e.type]:c.toString().padStart(e.len,"0")},this.#r=!0,this.#s=null,this.#u()}#d(t){if(t)switch(t){case"right":return this.#f(1);case"left":return this.#f(-1);case"up":return this.#g(1);case"down":return this.#g(-1)}}#m(t,n){if(n?.name==="backspace"||n?.sequence===""||n?.sequence==="\b"||t===""||t==="\b"){this.inlineError="";let e=this.#h();if(!e)return;if(!this.#t[e.segment.type].replace(/_/g,"")){this.#f(-1);return}this.#t[e.segment.type]="_".repeat(e.segment.len),this.#r=!0,this.#e.positionInSegment=0,this.#u();return}if(n?.name==="tab"){this.inlineError="";let e=this.#h();if(!e)return;let r=n.shift?-1:1,i=e.index+r;i>=0&&i<this.#n.length&&(this.#e.segmentIndex=i,this.#e.positionInSegment=0,this.#r=!0);return}if(t&&/^[0-9]$/.test(t)){let e=this.#h();if(!e)return;let{segment:r}=e,i=!this.#t[r.type].replace(/_/g,"");if(this.#r&&this.#s!==null&&!i){let g=this.#s+t,d={...this.#t,[r.type]:g},p=this.#l(d,r);if(p){this.inlineError=p,this.#s=null,this.#r=!1;return}this.inlineError="",this.#t[r.type]=g,this.#s=null,this.#r=!1,this.#u(),e.index<this.#n.length-1&&(this.#e.segmentIndex=e.index+1,this.#e.positionInSegment=0,this.#r=!0);return}this.#r&&!i&&(this.#t[r.type]="_".repeat(r.len),this.#e.positionInSegment=0),this.#r=!1,this.#s=null;let o=this.#t[r.type],s=o.indexOf("_"),c=s>=0?s:Math.min(this.#e.positionInSegment,r.len-1);if(c<0||c>=r.len)return;let u=o.slice(0,c)+t+o.slice(c+1),h=!1;if(c===0&&o==="__"&&(r.type==="month"||r.type==="day")){let g=Number.parseInt(t,10);u=`0${t}`,h=g<=(r.type==="month"?1:2)}if(r.type==="year"&&(u=(o.replace(/_/g,"")+t).padStart(r.len,"_")),!u.includes("_")){let g={...this.#t,[r.type]:u},d=this.#l(g,r);if(d){this.inlineError=d;return}}this.inlineError="",this.#t[r.type]=u;let f=u.includes("_")?void 0:sf(this.#t);if(f){let{year:g,month:d}=f,p=ho(g,d);this.#t={year:String(Math.max(0,Math.min(9999,g))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,d))).padStart(2,"0"),day:String(Math.max(1,Math.min(p,f.day))).padStart(2,"0")}}this.#u();let a=u.indexOf("_");h?(this.#r=!0,this.#s=t):a>=0?this.#e.positionInSegment=a:s>=0&&e.index<this.#n.length-1?(this.#e.segmentIndex=e.index+1,this.#e.positionInSegment=0,this.#r=!0):this.#e.positionInSegment=Math.min(c+1,r.len-1)}}#l(t,n){let{month:e,day:r}=Qr(t);if(n.type==="month"&&(e<0||e>12))return At.date.messages.invalidMonth;if(n.type==="day"&&(r<0||r>31))return At.date.messages.invalidDay(31,"any month")}#p(t){let{year:n,month:e,day:r}=Qr(this.#t);if(n&&e&&r){let i=ho(n,e);this.#t={...this.#t,day:String(Math.min(r,i)).padStart(2,"0")}}this.value=nf(this.#t)??t.defaultValue??void 0}}var Mp=class extends pn{options;cursor=0;#n;getGroupItems(n){return this.options.filter((e)=>e.group===n)}isGroupSelected(n){let e=this.getGroupItems(n),r=this.value;return r===void 0?!1:e.every((i)=>r.includes(i.value))}toggleValue(){let n=this.options[this.cursor];if(n!==void 0)if(this.value===void 0&&(this.value=[]),n.group===!0){let e=n.value,r=this.getGroupItems(e);this.isGroupSelected(e)?this.value=this.value.filter((i)=>r.findIndex((o)=>o.value===i)===-1):this.value=[...this.value,...r.map((i)=>i.value)],this.value=Array.from(new Set(this.value))}else{let e=this.value.includes(n.value);this.value=e?this.value.filter((r)=>r!==n.value):[...this.value,n.value]}}constructor(n){super(n,!1);let{options:e}=n;this.#n=n.selectableGroups!==!1,this.options=Object.entries(e).flatMap(([r,i])=>[{value:r,group:!0,label:r},...i.map((o)=>({...o,group:r}))]),this.value=[...n.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:r})=>r===n.cursorAt),this.#n?0:1),this.on("cursor",(r)=>{switch(r){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let i=this.options[this.cursor]?.group===!0;!this.#n&&i&&(this.cursor=this.cursor===0?this.options.length-1:this.cursor-1);break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let i=this.options[this.cursor]?.group===!0;!this.#n&&i&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},vp=new Set(["up","down","left","right"]);class uf extends pn{#n=!1;#i;focused="editor";get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t=this.userInput;if(this.cursor>=t.length)return`${t}█`;let n=t.slice(0,this.cursor),e=t.slice(this.cursor,this.cursor+1),r=t.slice(this.cursor+1);return e===`
161
+ `?`${n}█
162
+ ${r}`:`${n}${co("inverse",e)}${r}`}get cursor(){return this._cursor}#t(t){if(this.userInput.length===0){this._setUserInput(t);return}this._setUserInput(this.userInput.slice(0,this.cursor)+t+this.userInput.slice(this.cursor))}#o(t){let n=this.value??"";switch(t){case"up":this._cursor=Tr(this._cursor,0,-1,n);return;case"down":this._cursor=Tr(this._cursor,0,1,n);return;case"left":this._cursor=Tr(this._cursor,-1,0,n);return;case"right":this._cursor=Tr(this._cursor,1,0,n);return}}_shouldSubmit(t,n){if(this.#i)return this.focused==="submit"?!0:(this.#t(`
163
+ `),this._cursor++,!1);let e=this.#n;return this.#n=!0,e&&this.cursor===this.userInput.length?(this.userInput[this.cursor-1]===`
164
+ `&&(this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--),!0):(this.#t(`
165
+ `),this._cursor++,!1)}constructor(t){let n=t.initialUserInput??t.initialValue;super({...t,initialUserInput:n},!1),n!==void 0&&(this._cursor=n.length),this.#i=t.showSubmit??!1,this.on("key",(e,r)=>{if(r?.name&&vp.has(r.name)){this.#n=!1,this.#o(r.name);return}if(e==="\t"&&this.#i){this.focused=this.focused==="editor"?"submit":"editor";return}if(r?.name!=="return"){if(this.#n=!1,r?.name==="backspace"&&this.cursor>0){this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--;return}if(r?.name==="delete"&&this.cursor<this.userInput.length){this._setUserInput(this.userInput.slice(0,this.cursor)+this.userInput.slice(this.cursor+1));return}e&&(this.#i&&this.focused==="submit"&&(this.focused="editor"),this.#t(e??""),this._cursor++)}}),this.on("userInput",(e)=>{this._setValue(e)}),this.on("finalize",()=>{this.value||(this.value=t.defaultValue),this.value===void 0&&(this.value="")})}}class go extends pn{options;cursor=0;get _value(){return this.options[this.cursor]?.value}get _enabledOptions(){return this.options.filter((t)=>t.disabled!==!0)}toggleAll(){let t=this._enabledOptions,n=this.value!==void 0&&this.value.length===t.length;this.value=n?[]:t.map((e)=>e.value)}toggleInvert(){let t=this.value;if(!t)return;let n=this._enabledOptions.filter((e)=>!t.includes(e.value));this.value=n.map((e)=>e.value)}toggleValue(){this.value===void 0&&(this.value=[]);let t=this.value.includes(this._value);this.value=t?this.value.filter((n)=>n!==this._value):[...this.value,this._value]}constructor(t){super(t,!1),this.options=t.options,this.value=[...t.initialValues??[]];let n=Math.max(this.options.findIndex(({value:e})=>e===t.cursorAt),0);this.cursor=this.options[n]?.disabled?te(n,1,this.options):n,this.on("key",(e,r)=>{r.name==="a"&&this.toggleAll(),r.name==="i"&&this.toggleInvert()}),this.on("cursor",(e)=>{switch(e){case"left":case"up":this.cursor=te(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=te(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}import{styleText as S,stripVTControlCharacters as Ab}from"node:util";import Vt from"node:process";var pf=nr(oo(),1);function yp(){if(Vt.platform!=="win32")return Vt.env.TERM!=="linux";return Boolean(Vt.env.CI)||Boolean(Vt.env.WT_SESSION)||Boolean(Vt.env.TERMINUS_SUBLIME)||Vt.env.ConEmuTask==="{cmd::Cmder}"||Vt.env.TERM_PROGRAM==="Terminus-Sublime"||Vt.env.TERM_PROGRAM==="vscode"||Vt.env.TERM==="xterm-256color"||Vt.env.TERM==="alacritty"||Vt.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var Sp=yp();var lt=(t,n)=>Sp?t:n,Fp=lt("◆","*"),Ip=lt("■","x"),Np=lt("▲","x"),wf=lt("◇","o"),Op=lt("┌","T"),yt=lt("│","|"),ee=lt("└","—"),Qb=lt("┐","T"),Zb=lt("┘","—"),hf=lt("●",">"),ff=lt("○"," "),Hp=lt("◻","[•]"),af=lt("◼","[+]"),gf=lt("◻","[ ]"),qb=lt("▪","•"),lf=lt("─","-"),jp=lt("╮","+"),Rp=lt("├","+"),Gp=lt("╯","+"),Lp=lt("╰","+"),Xb=lt("╭","+"),_b=lt("●","•"),Cb=lt("◆","*"),zb=lt("▲","!"),Yb=lt("■","x"),$f=(t)=>{switch(t){case"initial":case"active":return S("cyan",Fp);case"cancel":return S("red",Ip);case"error":return S("yellow",Np);case"submit":return S("green",wf)}},Pp=(t)=>{switch(t){case"initial":case"active":return S("cyan",yt);case"cancel":return S("red",yt);case"error":return S("yellow",yt);case"submit":return S("green",yt)}};function Kp(t,n){let e=[`${n?`${S("cyan",yt)} `:""}${t.join(" • ")}`];return n&&e.push(S("cyan",ee)),e}var df=(t,n,e,r,i,o=!1)=>{let s=n,c=0;if(o)for(let u=r-1;u>=e;u--){let h=t[u];if(h&&(s-=h.length),c++,s<=i)break}else for(let u=e;u<r;u++){let h=t[u];if(h&&(s-=h.length),c++,s<=i)break}return{lineCount:s,removals:c}},mf=({cursor:t,options:n,style:e,output:r=process.stdout,maxItems:i=Number.POSITIVE_INFINITY,columnPadding:o=0,rowPadding:s=4})=>{let c=Zr(r)-o,u=fo(r),h=S("dim","..."),f=Math.max(u-s,0),a=Math.max(Math.min(i,f),5),g=0;t>=a-3&&(g=Math.max(Math.min(t-a+3,n.length-a),0));let d=a<n.length&&g>0,p=a<n.length&&g+a<n.length,l=Math.min(g+a,n.length),k=[],v=0;d&&v++,p&&v++;let I=g+(d?1:0),E=l-(p?1:0);for(let $=I;$<E;$++){let H=n[$],b=H?e(H,$===t):"",R=Fn(b,c,{hard:!0,trim:!1}).split(`
166
+ `);k.push(R),v+=R.length}if(v>f){let $=0,H=0,b=v,R=t-I,O=f,P=()=>df(k,b,0,R,O),G=()=>df(k,b,R+1,k.length,O,!0);d?({lineCount:b,removals:$}=P(),b>O&&(p||(O-=1),{lineCount:b,removals:H}=G())):(p||(O-=1),{lineCount:b,removals:H}=G(),b>O&&(O-=1,{lineCount:b,removals:$}=P())),$>0&&(d=!0,k.splice(0,$)),H>0&&(p=!0,k.splice(k.length-H,H))}let y=[];d&&y.push(h);for(let $ of k)for(let H of $)y.push(H);return p&&y.push(h),y};var lo=(t)=>{let n=t.active??"Yes",e=t.inactive??"No";return new ao({active:n,inactive:e,signal:t.signal,input:t.input,output:t.output,initialValue:t.initialValue??!0,render(){let r=t.withGuide??At.withGuide,i=`${$f(this.state)} `,o=r?`${S("gray",yt)} `:"",s=ze(t.output,t.message,o,i),c=`${r?`${S("gray",yt)}
114
167
  `:""}${s}
115
- `,c=this.value?r:e;switch(this.state){case"submit":{let h=t?`${E("gray",hn)} `:"";return`${u}${h}${E("dim",c)}`}case"cancel":{let h=t?`${E("gray",hn)} `:"";return`${u}${h}${E(["strikethrough","dim"],c)}${t?`
116
- ${E("gray",hn)}`:""}`}default:{let h=t?`${E("cyan",hn)} `:"",f=t?E("cyan",Gr):"";return`${u}${h}${this.value?`${E("green",Yi)} ${r}`:`${E("dim",It)} ${E("dim",r)}`}${n.vertical?t?`
117
- ${E("cyan",hn)} `:`
118
- `:` ${E("dim","/")} `}${this.value?`${E("dim",It)} ${E("dim",e)}`:`${E("green",Yi)} ${e}`}
168
+ `,u=this.value?n:e;switch(this.state){case"submit":{let h=r?`${S("gray",yt)} `:"";return`${c}${h}${S("dim",u)}`}case"cancel":{let h=r?`${S("gray",yt)} `:"";return`${c}${h}${S(["strikethrough","dim"],u)}${r?`
169
+ ${S("gray",yt)}`:""}`}default:{let h=r?`${S("cyan",yt)} `:"",f=r?S("cyan",ee):"";return`${c}${h}${this.value?`${S("green",hf)} ${n}`:`${S("dim",ff)} ${S("dim",n)}`}${t.vertical?r?`
170
+ ${S("cyan",yt)} `:`
171
+ `:` ${S("dim","/")} `}${this.value?`${S("dim",ff)} ${S("dim",e)}`:`${S("green",hf)} ${e}`}
119
172
  ${f}
120
- `}}}}).prompt()};var Om=[`${E("dim","↑/↓")} to navigate`,`${E("dim","Space:")} select`,`${E("dim","Enter:")} confirm`],We=(n,r)=>n.split(`
121
- `).map((e)=>r(e)).join(`
122
- `),Qh=(n)=>{let r=(i,o)=>{let s=i.label??String(i.value);return o==="disabled"?`${E("gray",jh)} ${We(s,(u)=>E(["strikethrough","gray"],u))}${i.hint?` ${E("dim",`(${i.hint??"disabled"})`)}`:""}`:o==="active"?`${E("cyan",ym)} ${s}${i.hint?` ${E("dim",`(${i.hint})`)}`:""}`:o==="selected"?`${E("green",Oh)} ${We(s,(u)=>E("dim",u))}${i.hint?` ${E("dim",`(${i.hint})`)}`:""}`:o==="cancelled"?`${We(s,(u)=>E(["strikethrough","dim"],u))}`:o==="active-selected"?`${E("green",Oh)} ${s}${i.hint?` ${E("dim",`(${i.hint})`)}`:""}`:o==="submitted"?`${We(s,(u)=>E("dim",u))}`:`${E("dim",jh)} ${We(s,(u)=>E("dim",u))}`},e=n.required??!0,t=n.showInstructions??!0;return new zi({options:n.options,signal:n.signal,input:n.input,output:n.output,initialValues:n.initialValues,required:e,cursorAt:n.cursorAt,validate(i){if(e&&(i===void 0||i.length===0))return`Please select at least one option.
123
- ${E("reset",E("dim",`Press ${E(["gray","bgWhite","inverse"]," space ")} to select, ${E("gray",E("bgWhite",E("inverse"," enter ")))} to submit`))}`},render(){let i=n.withGuide??Pn.withGuide,o=vr(n.output,n.message,i?`${Kh(this.state)} `:"",`${_i(this.state)} `),s=`${i?`${E("gray",hn)}
173
+ `}}}}).prompt()};var Jp=[`${S("dim","↑/↓")} to navigate`,`${S("dim","Space:")} select`,`${S("dim","Enter:")} confirm`],Ye=(t,n)=>t.split(`
174
+ `).map((e)=>n(e)).join(`
175
+ `),bf=(t)=>{let n=(i,o)=>{let s=i.label??String(i.value);return o==="disabled"?`${S("gray",gf)} ${Ye(s,(c)=>S(["strikethrough","gray"],c))}${i.hint?` ${S("dim",`(${i.hint??"disabled"})`)}`:""}`:o==="active"?`${S("cyan",Hp)} ${s}${i.hint?` ${S("dim",`(${i.hint})`)}`:""}`:o==="selected"?`${S("green",af)} ${Ye(s,(c)=>S("dim",c))}${i.hint?` ${S("dim",`(${i.hint})`)}`:""}`:o==="cancelled"?`${Ye(s,(c)=>S(["strikethrough","dim"],c))}`:o==="active-selected"?`${S("green",af)} ${s}${i.hint?` ${S("dim",`(${i.hint})`)}`:""}`:o==="submitted"?`${Ye(s,(c)=>S("dim",c))}`:`${S("dim",gf)} ${Ye(s,(c)=>S("dim",c))}`},e=t.required??!0,r=t.showInstructions??!0;return new go({options:t.options,signal:t.signal,input:t.input,output:t.output,initialValues:t.initialValues,required:e,cursorAt:t.cursorAt,validate(i){if(e&&(i===void 0||i.length===0))return`Please select at least one option.
176
+ ${S("reset",S("dim",`Press ${S(["gray","bgWhite","inverse"]," space ")} to select, ${S("gray",S("bgWhite",S("inverse"," enter ")))} to submit`))}`},render(){let i=t.withGuide??At.withGuide,o=ze(t.output,t.message,i?`${Pp(this.state)} `:"",`${$f(this.state)} `),s=`${i?`${S("gray",yt)}
124
177
  `:""}${o}
125
- `,u=this.value??[],c=(h,f)=>{if(h.disabled)return r(h,"disabled");let l=u.includes(h.value);return f&&l?r(h,"active-selected"):l?r(h,"selected"):r(h,f?"active":"inactive")};switch(this.state){case"submit":{let h=this.options.filter(({value:l})=>u.includes(l)).map((l)=>r(l,"submitted")).join(E("dim",", "))||E("dim","none"),f=vr(n.output,h,i?`${E("gray",hn)} `:"");return`${s}${f}`}case"cancel":{let h=this.options.filter(({value:l})=>u.includes(l)).map((l)=>r(l,"cancelled")).join(E("dim",", "));if(h.trim()==="")return`${s}${E("gray",hn)}`;let f=vr(n.output,h,i?`${E("gray",hn)} `:"");return`${s}${f}${i?`
126
- ${E("gray",hn)}`:""}`}case"error":{let h=i?`${E("yellow",hn)} `:"",f=this.error.split(`
127
- `).map((d,w)=>w===0?`${i?`${E("yellow",Gr)} `:""}${E("yellow",d)}`:` ${d}`).join(`
128
- `),l=s.split(`
178
+ `,c=this.value??[],u=(h,f)=>{if(h.disabled)return n(h,"disabled");let a=c.includes(h.value);return f&&a?n(h,"active-selected"):a?n(h,"selected"):n(h,f?"active":"inactive")};switch(this.state){case"submit":{let h=this.options.filter(({value:a})=>c.includes(a)).map((a)=>n(a,"submitted")).join(S("dim",", "))||S("dim","none"),f=ze(t.output,h,i?`${S("gray",yt)} `:"");return`${s}${f}`}case"cancel":{let h=this.options.filter(({value:a})=>c.includes(a)).map((a)=>n(a,"cancelled")).join(S("dim",", "));if(h.trim()==="")return`${s}${S("gray",yt)}`;let f=ze(t.output,h,i?`${S("gray",yt)} `:"");return`${s}${f}${i?`
179
+ ${S("gray",yt)}`:""}`}case"error":{let h=i?`${S("yellow",yt)} `:"",f=this.error.split(`
180
+ `).map((d,p)=>p===0?`${i?`${S("yellow",ee)} `:""}${S("yellow",d)}`:` ${d}`).join(`
181
+ `),a=s.split(`
129
182
  `).length,g=f.split(`
130
- `).length+1;return`${s}${h}${Ci({output:n.output,options:this.options,cursor:this.cursor,maxItems:n.maxItems,columnPadding:h.length,rowPadding:l+g,style:c}).join(`
183
+ `).length+1;return`${s}${h}${mf({output:t.output,options:this.options,cursor:this.cursor,maxItems:t.maxItems,columnPadding:h.length,rowPadding:a+g,style:u}).join(`
131
184
  ${h}`)}
132
185
  ${f}
133
- `}default:{let h=i?`${E("cyan",hn)} `:"",f=s.split(`
134
- `).length,l=t?Ph(Om,i):i?[E("cyan",Gr)]:[],g=l.join(`
135
- `),d=l.length+1;return`${s}${h}${Ci({output:n.output,options:this.options,cursor:this.cursor,maxItems:n.maxItems,columnPadding:h.length,rowPadding:f+d,style:c}).join(`
186
+ `}default:{let h=i?`${S("cyan",yt)} `:"",f=s.split(`
187
+ `).length,a=r?Kp(Jp,i):i?[S("cyan",ee)]:[],g=a.join(`
188
+ `),d=a.length+1;return`${s}${h}${mf({output:t.output,options:this.options,cursor:this.cursor,maxItems:t.maxItems,columnPadding:h.length,rowPadding:f+d,style:u}).join(`
136
189
  ${h}`)}
137
190
  ${g}
138
- `}}}}).prompt()};var St=(n="",r)=>{let e=r?.output??process.stdout,t=r?.withGuide??Pn.withGuide?`${E("gray",Gr)} `:"";e.write(`${t}${E("red",n)}
191
+ `}}}}).prompt()};var qr=(t="",n)=>{let e=n?.output??process.stdout,r=n?.withGuide??At.withGuide?`${S("gray",ee)} `:"";e.write(`${r}${S("red",t)}
139
192
 
140
- `)},Wh=(n="",r)=>{let e=r?.output??process.stdout,t=r?.withGuide??Pn.withGuide?`${E("gray",Fm)} `:"";e.write(`${t}${n}
141
- `)},Zh=(n="",r)=>{let e=r?.output??process.stdout,t=r?.withGuide??Pn.withGuide?`${E("gray",hn)}
142
- ${E("gray",Gr)} `:"";e.write(`${t}${n}
193
+ `)},kf=(t="",n)=>{let e=n?.output??process.stdout,r=n?.withGuide??At.withGuide?`${S("gray",Op)} `:"";e.write(`${r}${t}
194
+ `)},Ef=(t="",n)=>{let e=n?.output??process.stdout,r=n?.withGuide??At.withGuide?`${S("gray",yt)}
195
+ ${S("gray",ee)} `:"";e.write(`${r}${t}
143
196
 
144
- `)};var jm=(n)=>n,Rm=(n,r,e)=>{let t={hard:!0,trim:!1},i=Er(n,r,t).split(`
145
- `),o=i.reduce((c,h)=>Math.max(Kn(h),c),0),s=i.map(e).reduce((c,h)=>Math.max(Kn(h),c),0),u=r-(s-o);return Er(n,u,t)},Nt=(n="",r="",e)=>{let t=e?.output??Yn.stdout,i=e?.withGuide??Pn.withGuide,o=e?.format??jm,s=["",...Rm(n,Ft(t)-6,o).split(`
146
- `).map(o),""],u=Kn(r),c=Math.max(s.reduce((g,d)=>{let w=Kn(d);return w>g?w:g},0),u)+2,h=s.map((g)=>`${E("gray",hn)} ${g}${" ".repeat(c-Kn(g))}${E("gray",hn)}`).join(`
147
- `),f=i?`${E("gray",hn)}
148
- `:"",l=i?Sm:Hm;t.write(`${f}${E("green",Jh)} ${E("reset",r)} ${E("gray",Rh.repeat(Math.max(c-u-1,1))+Im)}
197
+ `)};var Ap=(t)=>t,Up=(t,n,e)=>{let r={hard:!0,trim:!1},i=Fn(t,n,r).split(`
198
+ `),o=i.reduce((u,h)=>Math.max(Kt(h),u),0),s=i.map(e).reduce((u,h)=>Math.max(Kt(h),u),0),c=n-(s-o);return Fn(t,c,r)},Xr=(t="",n="",e)=>{let r=e?.output??Vt.stdout,i=e?.withGuide??At.withGuide,o=e?.format??Ap,s=["",...Up(t,Zr(r)-6,o).split(`
199
+ `).map(o),""],c=Kt(n),u=Math.max(s.reduce((g,d)=>{let p=Kt(d);return p>g?p:g},0),c)+2,h=s.map((g)=>`${S("gray",yt)} ${g}${" ".repeat(u-Kt(g))}${S("gray",yt)}`).join(`
200
+ `),f=i?`${S("gray",yt)}
201
+ `:"",a=i?Rp:Lp;r.write(`${f}${S("green",wf)} ${S("reset",n)} ${S("gray",lf.repeat(Math.max(u-c-1,1))+jp)}
149
202
  ${h}
150
- ${E("gray",l+Rh.repeat(c+2)+Nm)}
151
- `)};var jp={light:dn("─","-"),heavy:dn("━","="),block:dn("█","#")};var Gm=[`${E("dim","↑/↓")} to navigate`,`${E("dim","Enter:")} confirm`],yt=(n,r)=>n.includes(`
152
- `)?n.split(`
153
- `).map((e)=>r(e)).join(`
154
- `):r(n),qh=(n)=>{let r=(t,i)=>{if(t===void 0)return"";let o=t.label??String(t.value);switch(i){case"disabled":return`${E("gray",It)} ${yt(o,(s)=>E("gray",s))}${t.hint?` ${E("dim",`(${t.hint??"disabled"})`)}`:""}`;case"selected":return`${yt(o,(s)=>E("dim",s))}`;case"active":return`${E("green",Yi)} ${o}${t.hint?` ${E("dim",`(${t.hint})`)}`:""}`;case"cancelled":return`${yt(o,(s)=>E(["strikethrough","dim"],s))}`;default:return`${E("dim",It)} ${yt(o,(s)=>E("dim",s))}`}},e=n.showInstructions??!0;return new Hh({options:n.options,signal:n.signal,input:n.input,output:n.output,initialValue:n.initialValue,render(){let t=n.withGuide??Pn.withGuide,i=`${_i(this.state)} `,o=`${Kh(this.state)} `,s=vr(n.output,n.message,o,i),u=`${t?`${E("gray",hn)}
155
- `:""}${s}
156
- `;switch(this.state){case"submit":{let c=t?`${E("gray",hn)} `:"",h=vr(n.output,r(this.options[this.cursor],"selected"),c);return`${u}${h}`}case"cancel":{let c=t?`${E("gray",hn)} `:"",h=vr(n.output,r(this.options[this.cursor],"cancelled"),c);return`${u}${h}${t?`
157
- ${E("gray",hn)}`:""}`}default:{let c=t?`${E("cyan",hn)} `:"",h=u.split(`
158
- `).length,f=e?Ph(Gm,t):t?[E("cyan",Gr)]:[],l=f.join(`
159
- `),g=f.length+1;return`${u}${c}${Ci({output:n.output,cursor:this.cursor,options:this.options,maxItems:n.maxItems,columnPadding:c.length,rowPadding:h+g,style:(d,w)=>r(d,d.disabled?"disabled":w?"active":"inactive")}).join(`
160
- ${c}`)}
161
- ${l}
162
- `}}}}).prompt()};var Rp=`${E("gray",hn)} `;import{existsSync as qm}from"node:fs";import{openSync as Lm,writeSync as Jm}from"node:fs";import{ReadStream as Km}from"node:tty";var Xh=["10","11","12","17",...Array.from({length:16},(n,r)=>`4;${r}`)];function Ht(n){let r=n.ansi.map((e,t)=>`;${t};${e}`).join("");return[`\x1B]11;${n.background}\x1B\\`,`\x1B]10;${n.foreground}\x1B\\`,`\x1B]12;${n.cursor}\x1B\\`,`\x1B]17;${n.selection}\x1B\\`,`\x1B]4${r}\x1B\\`].join("")}function Th(n){let r=new Map;for(let e of n.split("\x1B")){let t=e.match(/^\](\d+(?:;\d+)?);(rgba?:[0-9a-fA-F/]+)/),[,i,o]=t??[];if(i&&o)r.set(i,o)}return r}function Vh(n){return[...n].map(([r,e])=>`\x1B]${r};${e}\x1B\\`).join("")}async function zh(){let n,r;try{n=Lm("/dev/tty","r+"),r=new Km(n),r.setRawMode(!0)}catch{return new Map}try{Jm(n,Xh.map((t)=>`\x1B]${t};?\x1B\\`).join(""));let e="";return await new Promise((t)=>{let i=setTimeout(t,120);r.on("data",(o)=>{if(e+=o.toString(),Th(e).size>=Xh.length)clearTimeout(i),t()})}),Th(e)}finally{r.setRawMode(!1),r.destroy()}}function re(n){let r=n.replace("#","");return[r.slice(0,2),r.slice(2,4),r.slice(4,6)].map((e)=>Number.parseInt(e,16)).join(";")}function Yh(n,r){return`\x1B[48;2;${re(r)}m ${n} \x1B[0m`}function Bi(n,r){return`\x1B[48;2;${re(n)};38;2;${re(r)}m ● \x1B[0m`}function Ch(n){return`\x1B[38;2;${re(n)}m`}function xi(n,r){return`\x1B[48;2;${re(r)}m${n.map((e)=>`\x1B[38;2;${re(e)}m▄`).join("")} \x1B[0m`}function Ot(n,r){let e=r.toLowerCase();return[n.name,n.group,n.native??""].some((t)=>t.toLowerCase().includes(e))}function Bh(n,r,e){let t=e.trim(),i=[],o=new Set;for(let s of n){if(s.default||o.has(s.group))continue;o.add(s.group);let u=n.filter((f)=>!f.default&&f.group===s.group),c=t?u.filter((f)=>Ot(f,t)):u;if(t&&c.length===0)continue;let h=t.length>0||r.has(s.group);if(i.push({kind:"group",name:s.group,native:s.native,lead:u.find((f)=>f.lead)??s,expanded:h,count:c.length}),h)i.push(...c.map((f)=>({kind:"palette",entry:f})))}return i}function Pm(n,r){let e=r.trim(),t=new Set(n.filter((i)=>!i.default&&(e===""||Ot(i,e))).map((i)=>i.group));return Bh(n,new Set,"").filter((i)=>i.kind==="group"&&t.has(i.name))}function Um(n){let r=n.findIndex((e)=>e.kind==="palette");return r===-1?0:r}var Dn="\x1B[0m",ee="\x1B[2m",Qm="\x1B[1m",_h="\x1B[1;7m",Wm="\x1B[36m",Zm="\x1B[33m";function xh(n){return n==="decode"||n==="glitch"?n:"typewriter"}class Di extends sr{picked;scope;entries;named;series;seriesPad;expanded=new Set;rows=[];cursor=0;top=0;maxItems;color;lastInput="";lastFocused="";onFocus;example="";fx;fxStep=0;fxSeed=0;fxTimer;constructor(n){super({render:()=>this.draw(),input:n.input,output:n.output,validate:n.required?()=>this.picked.size===0?`pick at least one ${this.scope}`:void 0:void 0},!0);this.entries=n.entries,this.scope=n.scope??"palette",this.picked=new Set(n.installed??[]),this.named=n.entries.filter((e)=>!e.default),this.series=[...new Set(this.named.map((e)=>e.group))],this.seriesPad=Math.max(0,...this.series.map((e)=>e.length)),this.maxItems=n.maxItems??12,this.color=n.color??!0,this.fx=n.fx??"typewriter",this.onFocus=n.onFocus,this.rollExample();let r=setInterval(()=>{this.rollExample(),this.fxStep=8,this.output.emit("resize")},3000);r.unref?.(),this.once("finalize",()=>{clearInterval(r),clearTimeout(this.fxTimer)}),this.rebuild("first"),this.on("cursor",(e)=>{if(e==="up")this.move(-1);else if(e==="down")this.move(1);else if(e==="left")this.fold(!1);else if(e==="right")this.fold(!0)}),this.on("userInput",(e)=>{if(e!==this.lastInput)this.lastInput=e,this.rebuild("keep")}),this.on("key",(e,t)=>{if(t?.name==="space")this.pick(this.rows[this.cursor])})}_isActionKey(n){return n==="\t"||n===" "}members(n){let r=this.scope==="palette"?this.userInput.trim():"";return this.named.filter((e)=>e.group===n&&(r===""||Ot(e,r)))}everyone(n){return n.flatMap((r)=>r.kind==="group"?this.members(r.name):[])}pick(n){let r=n?.kind==="palette"?[n.entry.name]:n?.kind==="group"?this.members(n.name).map((t)=>t.name):n?.kind==="all"?this.everyone(this.rows).map((t)=>t.name):[];if(r.length===0)return;let e=r.some((t)=>!this.picked.has(t));for(let t of r)if(e)this.picked.add(t);else this.picked.delete(t)}pickedIn(n){return this.members(n).filter((r)=>this.picked.has(r.name)).length}pickedCount(){if(this.scope==="palette")return this.picked.size;return this.series.filter((n)=>this.members(n).every((r)=>this.picked.has(r.name))).length}rollExample(){let n=this.named[Math.floor(Math.random()*this.named.length)],r=this.series[Math.floor(Math.random()*this.series.length)];if(!n||!r){this.example="";return}let e=`${n.name} | ${r}`;this.example=e.length>30?`${e.slice(0,29)}…`:e,this.fxSeed=Math.floor(Math.random()*997)}animatedExample(){if(this.fxStep===0)return this.example;if(!this.fxTimer)this.fxTimer=setTimeout(()=>{this.fxTimer=void 0,this.fxStep-=1,this.output.emit("resize")},60),this.fxTimer.unref?.();let n=Math.floor(this.example.length*(8-this.fxStep)/8);if(this.fx==="typewriter")return`${this.example.slice(0,n)}▏`;let r=this.fx==="decode"?"abcdefghijklmnopqrstuvwxyz":"▓▒░#*+=<>?/-_",e=this.fx==="decode"?(t)=>!/[a-z0-9]/i.test(t):(t)=>t===" ";return[...this.example].map((t,i)=>i+(i*7+this.fxSeed)%3<n||e(t)?t:r[Math.floor(Math.random()*r.length)]??t).join("")}sync(){let n=this.rows[this.cursor],r=n?.kind==="palette"?n.entry:n?.kind==="group"&&this.scope==="series"?n.lead:void 0;if(r&&r.name!==this.lastFocused)this.lastFocused=r.name,this.onFocus?.(r)}rebuild(n){let r=this.rows[this.cursor],e=this.scope==="series"?Pm(this.entries,this.userInput):Bh(this.entries,this.expanded,this.userInput),t=e.length>0?Um(e)+1:0;if(this.rows=e.length>0?[{kind:"all",count:this.allCount(e)},...e]:[],n==="first")this.cursor=t;else if(n==="keep"){let i=r?.kind==="palette"?r.entry.name:"",o=i?this.rows.findIndex((s)=>s.kind==="palette"&&s.entry.name===i):-1;this.cursor=o===-1?t:o}else if(this.cursor>=this.rows.length)this.cursor=Math.max(0,this.rows.length-1);this.sync()}allCount(n){return this.scope==="series"?n.length:this.everyone(n).length}move(n){let r=this.cursor+n;if(r>=0&&r<this.rows.length)this.cursor=r;this.sync()}toggle(n){if(this.expanded.has(n))this.expanded.delete(n);else this.expanded.add(n);this.rebuild("clamp")}fold(n){if(this.userInput||this.scope==="series")return;let r=this.rows[this.cursor];if(r?.kind==="group"){if(n!==r.expanded)this.toggle(r.name)}else if(r?.kind==="palette"&&!n&&!r.entry.default){let e=r.entry.group;if(this.expanded.delete(e),this.rebuild("clamp"),this.cursor=this.rows.findIndex((t)=>t.kind==="group"&&t.name===e),this.cursor===-1)this.cursor=0;this.sync()}}renderRow(n,r){let e=r?"▶ ":" ";if(n.kind==="all"){let o=this.everyone(this.rows).every((u)=>this.picked.has(u.name))?"● ":"○ ",s=`(${n.count})`;return`${e}${o}select all ${this.color?`${ee}${s}${Dn}`:s}`}if(n.kind==="group"&&this.scope==="series"){let o=this.pickedIn(n.name)===n.count?"● ":"○ ",s=n.name.padEnd(this.seriesPad),u=`(${n.count})${n.native?` ${n.native}`:""}`;if(!this.color)return`${e}${o}${s} ${u}`;let c=n.lead;return`${e}${o}${s} ${Bi(c.background,c.cursor)}${xi(c.ansi.slice(1,7),c.background)} ${ee}${u}${Dn}`}if(n.kind==="group"){let o=n.expanded?"▾":"▸",s=this.rows[this.cursor],u=s?.kind==="palette"&&s.entry.group===n.name?s.entry:void 0,c=this.color?r?`${_h} ${n.name} ${Dn}`:u?`${_h}${Ch(u.cursor)} ${n.name} ${Dn}`:` ${Qm}${n.name}${Dn} `:r?`[${n.name}]`:` ${n.name}`,h=this.color?Yh("●",n.lead.selection):"",f=`${this.pickedIn(n.name)}/${n.count}`,l=this.color?` ${ee}(${f})${Dn}`:` (${f})`,g=n.native?this.color?` ${ee}${n.native}${Dn}`:` ${n.native}`:"";return`${o}${c}${h}${l}${g}`}let t=n.entry,i=this.picked.has(t.name)?"● ":"○ ";if(!this.color)return` ${e}${i}${t.name.padEnd(13)} ● · ${t.ansiSource}`;return` ${e}${i}${t.name.padEnd(13)} ${Bi(t.background,t.cursor)}${xi(t.ansi.slice(1,7),t.background)} ${ee}${t.ansiSource}${Dn}`}draw(){let n=(m)=>this.color?`${ee}${m}${Dn}`:m,r=(m)=>this.color?`${Wm}${m}${Dn}`:m,e=this.scope==="series"?"series":"catalog";if(this.state==="submit")return`${n("◇")} ${e} ${n(`· ${this.pickedCount()} picked`)}`;if(this.state==="cancel")return`${n(`◇ ${e} · cancelled`)}`;let t=this.userInput.trim(),i=this.scope==="series"?this.series.length:this.named.length,o=this.scope==="series"?this.rows.filter((m)=>m.kind==="group").length:t?this.named.filter((m)=>Ot(m,t)).length:i,s=`${r("◆")} ${e} ${n(`(${o}/${i} · ${this.pickedCount()} picked)`)}`,u=`${r("│")} ${this.userInput?`⌕ ${this.userInput}_`:n(`⌕ search…${this.example?` e.g. ${this.animatedExample()}`:""}`)}`;if(this.cursor<this.top)this.top=this.cursor;if(this.cursor>=this.top+this.maxItems)this.top=this.cursor-this.maxItems+1;this.top=Math.min(this.top,Math.max(0,this.rows.length-this.maxItems));let c=this.rows.slice(this.top,this.top+this.maxItems),h=c.length>0?c.map((m,b)=>`${r("│")} ${this.renderRow(m,this.top+b===this.cursor)}`):[`${r("│")} ${n(`no ${this.scope==="series"?"series":"palettes"} match '${this.userInput}'`)}`];while(h.length<this.maxItems)h.push(r("│"));let f=this.rows.length-this.top-c.length,l=f>0?`${r("│")} ${n(`↓ ${f} more`)}`:r("│"),g=this.scope==="series"?"":" · ←→ fold",d=this.scope==="series"?"continue":"install",w=this.state==="error"?`${r("└")} ${this.color?`${Zm}${this.error}${Dn}`:this.error}`:`${r("└")} ${n(`↑↓ move${g} · space pick · type to filter · enter ${d} · esc cancel`)}`;return[s,u,...h,l,w].join(`
163
- `)}}function no(n,r,e,t){let i=Yr(),o=Boolean(Cr(e))!==Boolean(Cr(t)),s=o?Ke(t,i):t;if(Qe(n,r,s),Ue(n,s),o)Pe(s,i)}function ro(n){console.log(`
164
- ${n} palettes installed — open a new tab, or reload your terminal config`)}function Dh(n){let r=xn(),e=Qn(r),t=lr(r),i=n.filter((u)=>t.palettes.includes(u)),o=n.filter((u)=>!t.palettes.includes(u));if(o.length===0){console.log(`already installed: ${i.join(", ")}`);return}let s={...t,palettes:[...t.palettes,...o]};no(r,e,t,s);for(let u of o)console.log(` + ${u}`);ro(s.palettes.length)}function nf(n){let r=xn(),e=Qn(r),t=lr(r),i=n.filter((s)=>t.palettes.includes(s));if(i.length===0){console.log(`not installed: ${n.join(", ")}`);return}let o={...t,palettes:t.palettes.filter((s)=>!i.includes(s))};no(r,e,t,o),yi(r,e,t.terminals,i);for(let s of i)console.log(` - ${s}`);ro(o.palettes.length)}function rf(n){let r=xn(),e=Qn(r),t=lr(r);if(!t.palettes.includes(n))throw Error(`${n} is not installed — \`ttheme add ${n}\` first`);let{keepTheme:i,...o}=t,s=Yr(),u=Ke({...o,startup:n},s);Qe(r,e,u),Ue(r,u);let c=Pe(u,s);console.log(Am(n,u.terminals,c&&s.running()).join(`
165
- `))}function Am(n,r,e){let t=r.filter((o)=>o!=="iterm2"),i=t.length>0?[`default ${n} · ${t.join(", ")} open new tabs with it once their config reloads`]:[];if(r.includes("iterm2"))i.push(e?'iterm2 new tabs open with it once iTerm2 restarts — "ttheme · default" is now its default profile':'iterm2 new tabs open with it — "ttheme · default" is its default profile');return i.length>0?i:[`default ${n} · no terminal is wired to open with it — \`ttheme init\` wires one`]}function ef(n){let r=xn(),e=Qn(r),t=new Set(lr(r).palettes),i=Ar(e.palettes),o=Ie(n?uc(i,n):i),s=Math.max(...o.map((c)=>c.name.length),0);for(let c of o)console.log(` ${t.has(c.name)?"●":"○"} ${c.name.padEnd(s)} ${c.group}`);let u=n?`${o.length} of ${i.length}`:`${i.length}`;console.log(`
166
- ${u} palettes — ${o.filter((c)=>t.has(c.name)).length} installed`)}async function tf(){let n=xn(),r=qm(gt(n))?Qn(n).palettes.length:0,e=await oc(tc);lt(n,e);let t=e.palettes.length-r;console.log(`catalog ${e.version} — ${e.palettes.length} palettes${t>0?` (+${t})`:""}`)}async function eo(n,r,e,t=!1){let i=process.env.TTHEME_SORT==="series"?n.palettes:Ie(n.palettes),o=process.stdout.isTTY===!0&&!process.env.NO_COLOR,s=o?await zh():new Map,u=new Di({entries:i,scope:e,installed:r,required:t,color:!process.env.NO_COLOR,fx:xh(process.env.TTHEME_FX),onFocus:o?(h)=>process.stdout.write(Ht(h)):void 0}),c=await u.prompt();if(process.stdout.write(Vh(s)),ne(c))return;return n.palettes.filter((h)=>u.picked.has(h.name)).map((h)=>h.name)}async function of(){let n=xn(),r=Qn(n),e=lr(n),t=await eo(r,e.palettes,"palette");if(!t){console.log("nothing changed");return}let i=e.palettes.filter((u)=>!t.includes(u)),o=t.filter((u)=>!e.palettes.includes(u));if(o.length===0&&i.length===0){console.log("nothing changed");return}let s={...e,palettes:t};no(n,r,e,s),yi(n,r,e.terminals,i);for(let u of o)console.log(` + ${u}`);for(let u of i)console.log(` - ${u}`);ro(s.palettes.length)}function cf(n,r,e){for(let t of zm(r))n.push({from:fn(r,t),to:fn(e,t)})}function lf(n){return JSON.parse(ie(fn(n,"dist","manifest.json"),"utf8"))}function hf(n,r){let e=fn(r.root,"dist"),t=fn(r.configHome,"ttheme"),i=[{from:fn(r.root,"bin","ttheme.js"),to:fn(t,"ttheme.js")},{from:fn(r.root,"shell","ttheme.zsh"),to:fn(t,"ttheme.zsh")},{from:fn(r.root,"shell","launch-tab.zsh"),to:fn(t,"launch-tab.zsh"),executable:!0},{from:fn(e,"ghostty","ttheme.conf"),to:fn(t,"ttheme.conf")}];cf(i,fn(r.root,"shell","adapters"),fn(t,"adapters"));let o=[{file:fn(r.zdotdir,".zshrc"),block:Uu(t)}],s=fn(t,"config.zsh"),u=Wu(qn(s)?ie(s,"utf8"):""),c={file:s,content:n.wear?ut(u,"TTHEME_TAB_PALETTE",n.wear==="rotate"?"seq":"off"):u},h=[];if(n.terminals.includes("ghostty"))cf(i,fn(r.root,"ghostty","shaders"),fn(r.configHome,"ghostty","shaders"));if(n.terminals.includes("alacritty")){let g=fn(r.configHome,"alacritty","alacritty.toml");if(qn(g)&&!ie(g,"utf8").includes("# ttheme begin"))h.push("alacritty.toml already exists — ttheme left it alone; add its themes/ import yourself")}if(n.terminals.includes("wezterm")){let g=Fi(r.configHome,r.home);if(qn(g)&&ct(ie(g,"utf8"),"")===void 0)h.push(`${g} has no \`return config\` line — ttheme left it alone; call \`dofile("${fn(t,"wezterm.lua")}")(config)\` from it yourself`)}let f=n.terminals.includes("windows-terminal");if(f&&!r.wtHome)h.push("windows terminal: %LOCALAPPDATA% was not found — drop the release fragment into its Fragments folder yourself");if(n.terminals.includes("warp"))h.push("warp: wears the default palette app-wide through its settings.toml — the shell layer stays off in it, since Warp paints no tab background of its own");let l={terminals:n.terminals,palettes:n.palettes,...n.wear==="keep"?{keepTheme:!0}:{},...f&&r.wtHome?{wtHome:r.wtHome}:{},...f&&r.wtProfile?{wtProfile:r.wtProfile}:{}};return{home:r.home,copies:i,edits:o,settings:c,catalog:lf(r.root),installed:l,notes:h}}function Cm(n){try{return lr(n).itermBase}catch{return}}function ff(n,r=Yr()){for(let o of n.copies)if(to(te(o.to),{recursive:!0}),sf(o.to,{force:!0}),sf(`${o.to}.zwc`,{force:!0}),Vm(o.from,o.to),o.executable)Tm(o.to,493);to(te(n.settings.file),{recursive:!0}),uf(n.settings.file,n.settings.content);let e=te(te(n.settings.file)),t=Cm(e),i=Ke(t?{...n.installed,itermBase:t}:n.installed,r);lt(e,n.catalog),Ue(e,i),Qe(e,n.catalog,i,n.home);for(let o of n.edits){to(te(o.file),{recursive:!0});let s=qn(o.file)?ie(o.file,"utf8"):"";uf(o.file,ot(s,o.block))}return Pe(i,r)}function io(n){if(ne(n))St("nothing changed"),process.exit(1);return n}function af(n){return it.filter((r)=>{if(r==="iterm2")return process.platform==="darwin";if(r==="windows-terminal")return n.wtHome!==void 0;return r!=="warp"||process.platform!=="win32"})}function _m(n,r){if(n==="iterm2")return qn(fn(r.home,"Library","Application Support","iTerm2"));if(n==="windows-terminal")return r.wtHome!==void 0;if(n==="warp")return qn(te(pt(r.home)));if(n==="wezterm")return qn(fn(r.configHome,"wezterm"))||qn(fn(r.home,".wezterm.lua"));return qn(fn(r.configHome,n))}function Bm(){if(process.platform==="win32")return process.env.LOCALAPPDATA;if(!process.env.WSL_DISTRO_NAME)return;let n=(r,e)=>Xm(r,e,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();try{return n("wslpath",["-u",n("cmd.exe",["/d","/c","echo %LOCALAPPDATA%"])])||void 0}catch{return}}async function xm(n,r,e){return io(await Qh({message:"wire which terminals?",options:af(e).map((t)=>({value:t,hint:t===n?"detected":void 0})),initialValues:r,required:!0}))}function Dm(n,r){if(n==="keep")return"leave the terminal colors as they are";return n==="rotate"?`paint every new tab with the next palette, this tab with ${r} now`:`paint every tab with ${r}, this one now`}async function n0(n){return io(await qh({message:"how should the terminal wear them?",options:[{value:"default",label:"default",hint:`every tab wears ${n}`},{value:"rotate",label:"rotate",hint:"every new tab wears the next palette"},{value:"keep",label:"keep",hint:"leave my terminal colors alone"}],initialValue:"default"}))}function gf(n){let r=[...n.copies.filter((e)=>!qn(e.to)).map((e)=>e.to),...qn(n.settings.file)?[]:[n.settings.file],...n.edits.filter((e)=>!ie(e.file,"utf8").includes("# ttheme begin")).map((e)=>e.file)];if(r.length>0)throw Error(`init left gaps:
167
- ${r.join(`
168
- `)}`)}function df(n,r){return[...new Set(n.palettes.filter((e)=>r.includes(e.name)).map((e)=>e.group))]}function r0(n,r){let e=n.palettes.find((i)=>i.name===_r(r)),t=process.stdout.isTTY===!0&&!process.env.NO_COLOR&&!process.env.TMUX&&fi(process.env)!=="warp";if(!e||!t)return!1;return process.stdout.write(Ht(e)),!0}function e0(n,r,e){if(n==="keep")return["terminal colors left alone — paint a tab with `ttheme <palette>`"," `ttheme default <palette>` sets the terminal default"];return[`default ${r}${e?" — this tab wears it already":""}`,n==="rotate"?"new tabs rotate through the palettes — change with `ttheme config`":`new tabs all wear ${r} — change with \`ttheme config\``]}function t0(n,r,e,t,i){let o=df(n.catalog,r.palettes);Nt([`${o.join(", ")} (${r.palettes.length})`,...e0(e,_r(n.installed),t)].join(`
169
- `),`installed ${r.palettes.length} palettes`);let s=["exec zsh the ttheme command in this tab"];if(r.terminals.includes("ghostty"))s.push("restart ghostty new tabs pick up its config");if(r.terminals.includes("kitty"))s.push("new kitty window picks up its config");if(r.terminals.includes("wezterm"))s.push("wezterm reloads its config by itself");if(r.terminals.includes("windows-terminal"))s.push("windows terminal reloads its settings by itself");if(r.terminals.includes("iterm2"))s.push(...i0(e==="default"?_r(n.installed):void 0,i));Nt([...s,...n.notes].join(`
170
- `),"next"),Zh("done")}function i0(n,r){let e=['iterm2 profiles a "ttheme · <palette>" per palette in Settings › Profiles'];if(n)e.push(r?`restart iterm2 new tabs open on "ttheme · default", which wears ${n}`:`iterm2 default "ttheme · default" wears ${n} and follows \`ttheme default\``);return e}function o0(n,r){let e=[`placed ${n.copies.length} files`,`settings in ${n.settings.file} — edit later with \`ttheme config\``,...n.edits.map((t)=>`wired ${t.file}`)];if(r.terminals.includes("ghostty"))e.push("restart ghostty to pick up its config");if(r.terminals.includes("kitty"))e.push("open a new kitty window to pick up its config");if(r.terminals.includes("wezterm")||r.terminals.includes("windows-terminal"))e.push("wezterm and windows terminal reload their config by themselves");if(r.terminals.includes("iterm2"))e.push('iterm2 gets a "ttheme · <palette>" profile per palette under Settings › Profiles');e.push(...n.notes),e.push("no palettes yet — open a new shell (`exec zsh`), then `ttheme browse` picks them from the catalog"),console.log(e.join(`
171
- `))}async function mf(n={}){let r=fn(import.meta.dirname,"..");if(!qn(fn(r,"bin","ttheme.js")))throw Error("bin/ttheme.js is missing — run `mise run bin:build` first");if(!qn(fn(r,"dist"))){if(typeof Bun>"u")throw Error("this package is missing dist/ — reinstall @kecan0406/ttheme");await ft()}let e=Ym(),t=process.env.XDG_CONFIG_HOME??fn(e,".config"),i=process.env.ZDOTDIR??e,o=Bm(),s=process.env.WT_PROFILE_ID,u={root:r,home:e,configHome:t,zdotdir:i,...o?{wtHome:o}:{},...s?{wtProfile:s}:{}},c=fi(process.env),h=af(u).filter((k)=>k===c||_m(k,u));if(!(!n.yes&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0)){if(h.length===0)throw Error("no supported terminal detected — run this inside ghostty, kitty, alacritty, wezterm, iterm2, windows terminal or warp");let k={terminals:h,palettes:[]},y=hf(k,u);ff(y),gf(y),o0(y,k);return}Wh("ttheme init");let l=await xm(c,h,u),g=await eo(lf(r),[],"series",!0);if(!g)St("nothing changed"),process.exit(1);let d=_r({terminals:l,palettes:g}),w=await n0(d),m={terminals:l,palettes:g,wear:w},b=hf(m,u);if(Nt([`install ${g.length} palettes — ${df(b.catalog,g).join(", ")}`,`copy ${b.copies.length} files under ${t}`,`write ${b.settings.file}`,...b.edits.map((k)=>`edit ${k.file}`),Dm(w,d),...l.includes("iterm2")&&w!=="keep"?['make "ttheme · default" the iTerm2 default profile']:[]].join(`
172
- `),`wiring ${l.join(", ")}`),!io(await Uh({message:"apply these changes?"})))St("nothing changed"),process.exit(1);let F=Yr(),S=ff(b,F);gf(b),t0(b,m,w,w!=="keep"&&r0(b.catalog,b.installed),S&&F.running())}var bf=[{name:"build",args:[],about:"emit dist/ for every terminal, plus the zsh palette table",flags:{only:{type:"string",multiple:!0,value:"<terminal>",choices:ec,about:"rebuild just this terminal — repeat it for more"}},run:(n,{only:r})=>ft({only:r})},{name:"init",args:[],about:"install the palettes and wire your terminal configs",flags:{yes:{type:"boolean",about:"accept every default without prompting"}},run:(n,{yes:r})=>mf({yes:r})},{name:"browse",args:[],about:"pick palettes from the catalog in a live picker",run:()=>of()},{name:"list",args:["[query]"],about:"show the catalog, marking what is installed",run:([n])=>ef(n)},{name:"add",args:["<palette...>"],about:"install palettes from the catalog",run:(n)=>Dh(n)},{name:"remove",args:["<palette...>"],about:"uninstall palettes",run:(n)=>nf(n)},{name:"default",args:["<palette>"],about:"make an installed palette the one new tabs open with",run:([n])=>rf(n)},{name:"find",args:["<palette>"],about:"pick a booru background for a palette — preview opens this on tab",hidden:!0,run:([n])=>ih(n)},{name:"image",args:["<palette>","<action>"],about:"switch a palette between its saved backgrounds, remove the one shown, or pass on tuning — preview calls this",hidden:!0,run:([n,r])=>oh(n,r)},{name:"update",args:[],about:"refresh the catalog from the registry",run:()=>tf()}];class Lr extends Error{verb;constructor(n,r){super(n);this.verb=r}}function $f(n){let r=bf.find((e)=>e.name===n);if(!r)throw new Lr(n.startsWith("-")?`unknown option '${n}'`:`unknown command '${n}'`);return r}function u0(n,r){let e={help:{type:"boolean",short:"h"}};for(let[t,{type:i,multiple:o}]of Object.entries(n.flags??{}))e[t]={type:i,multiple:o===!0};try{return s0({args:r,options:e,allowPositionals:!0})}catch(t){let[i=""]=(t instanceof Error?t.message:String(t)).split(". ");throw new Lr(`${i.charAt(0).toLowerCase()}${i.slice(1)}`,n)}}function c0(n){let[r,...e]=n;if(r===void 0)return{kind:"help",code:1};if(r==="-h"||r==="--help")return{kind:"help",code:0};if(r==="-V"||r==="--version")return{kind:"version"};if(r==="help")return e[0]===void 0?{kind:"help",code:0}:{kind:"help",verb:$f(e[0]),code:0};let t=$f(r),i=u0(t,e);if(i.values.help)return{kind:"help",verb:t,code:0};for(let[f,{choices:l}]of Object.entries(t.flags??{}))for(let g of[i.values[f]??[]].flat())if(l&&!l.includes(String(g)))throw new Lr(`--${f} takes ${l.join(", ")} — not ${g}`,t);let o=i.positionals,s=t.args.filter((f)=>f.startsWith("<")).length,u=t.args.some((f)=>f.includes("..."))?Number.POSITIVE_INFINITY:t.args.length;if(o.length<s)throw new Lr(`missing ${t.args[o.length]}`,t);if(o.length>u)throw new Lr(`too many arguments: ${o.slice(u).join(" ")}`,t);let{help:c,...h}=i.values;return{kind:"run",verb:t,args:o,flags:h}}function wf(n){let r=Object.entries(n.flags??{}).map(([e,{value:t}])=>`[--${e}${t?` ${t}`:""}]`);return[n.name,...r,...n.args].join(" ")}function pf(n){let r=Math.max(...n.map(([e])=>e.length));return n.map(([e,t])=>` ${e.padEnd(r)} ${t}`)}function oo(n){if(n){let r=Object.entries(n.flags??{}).map(([e,{value:t,about:i}])=>[`--${e}${t?` ${t}`:""}`,i]);return[`Usage: ttheme ${wf(n)}`,"",n.about,...r.length>0?["","Options:",...pf(r)]:[]].join(`
173
- `)}return["Usage: ttheme <command>","",rr.description,"","Commands:",...pf(bf.filter((r)=>!r.hidden).map((r)=>[wf(r),r.about])),"","ttheme <command> --help describes one command · ttheme --version prints the version"].join(`
174
- `)}async function kf(n){try{let r=c0(n);if(r.kind==="version")return console.log(rr.version),0;if(r.kind==="help"){if(r.code===0)console.log(oo(r.verb));else console.error(oo(r.verb));return r.code}let e=await r.verb.run(r.args,r.flags);return typeof e==="number"?e:0}catch(r){if(r instanceof Lr)return console.error(`ttheme${r.verb?` ${r.verb.name}`:""}: ${r.message}
203
+ ${S("gray",a+lf.repeat(u+2)+Gp)}
204
+ `)};var Vb={light:lt("─","-"),heavy:lt("━","="),block:lt("█","#")};var xb=[`${S("dim","↑/↓")} to navigate`,`${S("dim","Enter:")} confirm`];var Bb=`${S("gray",yt)} `;import{existsSync as zp}from"node:fs";import{openSync as Tp,writeSync as Wp}from"node:fs";import{ReadStream as Qp}from"node:tty";var vf=["10","11","12","17",...Array.from({length:16},(t,n)=>`4;${n}`)];function _r(t){return[`\x1B]11;${t.background}\x1B\\`,`\x1B]10;${t.foreground}\x1B\\`,`\x1B]12;${t.cursor}\x1B\\`,`\x1B]17;${t.selection}\x1B\\`,...t.ansi.map((n,e)=>`\x1B]4;${e};${n}\x1B\\`)].join("")}function yf(t){let n=new Map;for(let e of t.split("\x1B")){let r=e.match(/^\](\d+(?:;\d+)?);(rgba?:[0-9a-fA-F/]+)/),[,i,o]=r??[];if(i&&o)n.set(i,o)}return n}function Sf(t){return[...t].map(([n,e])=>`\x1B]${n};${e}\x1B\\`).join("")}async function Ff(){let t,n;try{t=Tp("/dev/tty","r+"),n=new Qp(t),n.setRawMode(!0)}catch{return new Map}try{Wp(t,vf.map((r)=>`\x1B]${r};?\x1B\\`).join(""));let e="";return await new Promise((r)=>{let i=setTimeout(r,120);n.on("data",(o)=>{if(e+=o.toString(),yf(e).size>=vf.length)clearTimeout(i),r()})}),yf(e)}finally{n.setRawMode(!1),n.destroy()}}function re(t){let n=t.replace("#","");return[n.slice(0,2),n.slice(2,4),n.slice(4,6)].map((e)=>Number.parseInt(e,16)).join(";")}function If(t,n){return`\x1B[48;2;${re(n)}m ${t} \x1B[0m`}function mo(t,n){return`\x1B[48;2;${re(t)};38;2;${re(n)}m ● \x1B[0m`}function Nf(t){return`\x1B[38;2;${re(t)}m`}function po(t,n){return`\x1B[48;2;${re(n)}m${t.map((e)=>`\x1B[38;2;${re(e)}m▄`).join("")} \x1B[0m`}function Cr(t,n){let e=n.toLowerCase();return[t.name,t.group,t.native??""].some((r)=>r.toLowerCase().includes(e))}function Hf(t,n,e){let r=e.trim(),i=[],o=new Set;for(let s of t){if(s.default||o.has(s.group))continue;o.add(s.group);let c=t.filter((f)=>!f.default&&f.group===s.group),u=r?c.filter((f)=>Cr(f,r)):c;if(r&&u.length===0)continue;let h=r.length>0||n.has(s.group);if(i.push({kind:"group",name:s.group,native:s.native,lead:c.find((f)=>f.lead)??s,expanded:h,count:u.length}),h)i.push(...u.map((f)=>({kind:"palette",entry:f})))}return i}function Zp(t,n){let e=n.trim(),r=new Set(t.filter((i)=>!i.default&&(e===""||Cr(i,e))).map((i)=>i.group));return Hf(t,new Set,"").filter((i)=>i.kind==="group"&&r.has(i.name))}function qp(t){let n=t.findIndex((e)=>e.kind==="palette");return n===-1?0:n}var tn="\x1B[0m",ie="\x1B[2m",Xp="\x1B[1m",Of="\x1B[1;7m",_p="\x1B[36m",Cp="\x1B[33m";function jf(t){return t==="decode"||t==="glitch"?t:"typewriter"}class wo extends pn{picked;scope;entries;named;series;seriesPad;expanded=new Set;rows=[];cursor=0;top=0;maxItems;color;lastInput="";lastFocused="";onFocus;example="";fx;fxStep=0;fxSeed=0;fxTimer;constructor(t){super({render:()=>this.draw(),input:t.input,output:t.output,validate:t.required?()=>this.picked.size===0?`pick at least one ${this.scope}`:void 0:void 0},!0);this.entries=t.entries,this.scope=t.scope??"palette",this.picked=new Set(t.installed??[]),this.named=t.entries.filter((e)=>!e.default),this.series=[...new Set(this.named.map((e)=>e.group))],this.seriesPad=Math.max(0,...this.series.map((e)=>e.length)),this.maxItems=t.maxItems??12,this.color=t.color??!0,this.fx=t.fx??"typewriter",this.onFocus=t.onFocus,this.rollExample();let n=setInterval(()=>{this.rollExample(),this.fxStep=8,this.output.emit("resize")},3000);n.unref?.(),this.once("finalize",()=>{clearInterval(n),clearTimeout(this.fxTimer)}),this.rebuild("first"),this.on("cursor",(e)=>{if(e==="up")this.move(-1);else if(e==="down")this.move(1);else if(e==="left")this.fold(!1);else if(e==="right")this.fold(!0)}),this.on("userInput",(e)=>{if(e!==this.lastInput)this.lastInput=e,this.rebuild("keep")}),this.on("key",(e,r)=>{if(r?.name==="space")this.pick(this.rows[this.cursor])})}_isActionKey(t){return t==="\t"||t===" "}members(t){let n=this.scope==="palette"?this.userInput.trim():"";return this.named.filter((e)=>e.group===t&&(n===""||Cr(e,n)))}everyone(t){return t.flatMap((n)=>n.kind==="group"?this.members(n.name):[])}pick(t){let n=t?.kind==="palette"?[t.entry.name]:t?.kind==="group"?this.members(t.name).map((r)=>r.name):t?.kind==="all"?this.everyone(this.rows).map((r)=>r.name):[];if(n.length===0)return;let e=n.some((r)=>!this.picked.has(r));for(let r of n)if(e)this.picked.add(r);else this.picked.delete(r)}pickedIn(t){return this.members(t).filter((n)=>this.picked.has(n.name)).length}pickedCount(){if(this.scope==="palette")return this.picked.size;return this.series.filter((t)=>this.members(t).every((n)=>this.picked.has(n.name))).length}rollExample(){let t=this.named[Math.floor(Math.random()*this.named.length)],n=this.series[Math.floor(Math.random()*this.series.length)];if(!t||!n){this.example="";return}let e=`${t.name} | ${n}`;this.example=e.length>30?`${e.slice(0,29)}…`:e,this.fxSeed=Math.floor(Math.random()*997)}animatedExample(){if(this.fxStep===0)return this.example;if(!this.fxTimer)this.fxTimer=setTimeout(()=>{this.fxTimer=void 0,this.fxStep-=1,this.output.emit("resize")},60),this.fxTimer.unref?.();let t=Math.floor(this.example.length*(8-this.fxStep)/8);if(this.fx==="typewriter")return`${this.example.slice(0,t)}▏`;let n=this.fx==="decode"?"abcdefghijklmnopqrstuvwxyz":"▓▒░#*+=<>?/-_",e=this.fx==="decode"?(r)=>!/[a-z0-9]/i.test(r):(r)=>r===" ";return[...this.example].map((r,i)=>i+(i*7+this.fxSeed)%3<t||e(r)?r:n[Math.floor(Math.random()*n.length)]??r).join("")}sync(){let t=this.rows[this.cursor],n=t?.kind==="palette"?t.entry:t?.kind==="group"&&this.scope==="series"?t.lead:void 0;if(n&&n.name!==this.lastFocused)this.lastFocused=n.name,this.onFocus?.(n)}rebuild(t){let n=this.rows[this.cursor],e=this.scope==="series"?Zp(this.entries,this.userInput):Hf(this.entries,this.expanded,this.userInput),r=e.length>0?qp(e)+1:0;if(this.rows=e.length>0?[{kind:"all",count:this.allCount(e)},...e]:[],t==="first")this.cursor=r;else if(t==="keep"){let i=n?.kind==="palette"?n.entry.name:"",o=i?this.rows.findIndex((s)=>s.kind==="palette"&&s.entry.name===i):-1;this.cursor=o===-1?r:o}else if(this.cursor>=this.rows.length)this.cursor=Math.max(0,this.rows.length-1);this.sync()}allCount(t){return this.scope==="series"?t.length:this.everyone(t).length}move(t){let n=this.cursor+t;if(n>=0&&n<this.rows.length)this.cursor=n;this.sync()}toggle(t){if(this.expanded.has(t))this.expanded.delete(t);else this.expanded.add(t);this.rebuild("clamp")}fold(t){if(this.userInput||this.scope==="series")return;let n=this.rows[this.cursor];if(n?.kind==="group"){if(t!==n.expanded)this.toggle(n.name)}else if(n?.kind==="palette"&&!t&&!n.entry.default){let e=n.entry.group;if(this.expanded.delete(e),this.rebuild("clamp"),this.cursor=this.rows.findIndex((r)=>r.kind==="group"&&r.name===e),this.cursor===-1)this.cursor=0;this.sync()}}renderRow(t,n){let e=n?"▶ ":" ";if(t.kind==="all"){let o=this.everyone(this.rows).every((c)=>this.picked.has(c.name))?"● ":"○ ",s=`(${t.count})`;return`${e}${o}select all ${this.color?`${ie}${s}${tn}`:s}`}if(t.kind==="group"&&this.scope==="series"){let o=this.pickedIn(t.name)===t.count?"● ":"○ ",s=t.name.padEnd(this.seriesPad),c=`(${t.count})${t.native?` ${t.native}`:""}`;if(!this.color)return`${e}${o}${s} ${c}`;let u=t.lead;return`${e}${o}${s} ${mo(u.background,u.cursor)}${po(u.ansi.slice(1,7),u.background)} ${ie}${c}${tn}`}if(t.kind==="group"){let o=t.expanded?"▾":"▸",s=this.rows[this.cursor],c=s?.kind==="palette"&&s.entry.group===t.name?s.entry:void 0,u=this.color?n?`${Of} ${t.name} ${tn}`:c?`${Of}${Nf(c.cursor)} ${t.name} ${tn}`:` ${Xp}${t.name}${tn} `:n?`[${t.name}]`:` ${t.name}`,h=this.color?If("●",t.lead.selection):"",f=`${this.pickedIn(t.name)}/${t.count}`,a=this.color?` ${ie}(${f})${tn}`:` (${f})`,g=t.native?this.color?` ${ie}${t.native}${tn}`:` ${t.native}`:"";return`${o}${u}${h}${a}${g}`}let r=t.entry,i=this.picked.has(r.name)?"● ":"○ ";if(!this.color)return` ${e}${i}${r.name.padEnd(13)} ● · ${r.ansiSource}`;return` ${e}${i}${r.name.padEnd(13)} ${mo(r.background,r.cursor)}${po(r.ansi.slice(1,7),r.background)} ${ie}${r.ansiSource}${tn}`}draw(){let t=(l)=>this.color?`${ie}${l}${tn}`:l,n=(l)=>this.color?`${_p}${l}${tn}`:l,e=this.scope==="series"?"series":"catalog";if(this.state==="submit")return`${t("◇")} ${e} ${t(`· ${this.pickedCount()} picked`)}`;if(this.state==="cancel")return`${t(`◇ ${e} · cancelled`)}`;let r=this.userInput.trim(),i=this.scope==="series"?this.series.length:this.named.length,o=this.scope==="series"?this.rows.filter((l)=>l.kind==="group").length:r?this.named.filter((l)=>Cr(l,r)).length:i,s=`${n("◆")} ${e} ${t(`(${o}/${i} · ${this.pickedCount()} picked)`)}`,c=`${n("│")} ${this.userInput?`⌕ ${this.userInput}_`:t(`⌕ search…${this.example?` e.g. ${this.animatedExample()}`:""}`)}`;if(this.cursor<this.top)this.top=this.cursor;if(this.cursor>=this.top+this.maxItems)this.top=this.cursor-this.maxItems+1;this.top=Math.min(this.top,Math.max(0,this.rows.length-this.maxItems));let u=this.rows.slice(this.top,this.top+this.maxItems),h=u.length>0?u.map((l,k)=>`${n("│")} ${this.renderRow(l,this.top+k===this.cursor)}`):[`${n("│")} ${t(`no ${this.scope==="series"?"series":"palettes"} match '${this.userInput}'`)}`];while(h.length<this.maxItems)h.push(n("│"));let f=this.rows.length-this.top-u.length,a=f>0?`${n("│")} ${t(`↓ ${f} more`)}`:n("│"),g=this.scope==="series"?"":" · ←→ fold",d=this.scope==="series"?"continue":"install",p=this.state==="error"?`${n("└")} ${this.color?`${Cp}${this.error}${tn}`:this.error}`:`${n("└")} ${t(`↑↓ move${g} · space pick · type to filter · enter ${d} · esc cancel`)}`;return[s,c,...h,a,p].join(`
205
+ `)}}function Ve(t,n,e,r){let i=zn(),o=Boolean(hn(e))!==Boolean(hn(r)),s=o?Qe(r,i):r;return Xe(t,n,s),qe(t,s),o&&Ze(s,i)&&i.running()}function $o(t){console.log(`
206
+ ${t} palettes installed — open a new tab, or reload your terminal config`)}function Rf(t){let n=Tt(),e=Pt(n),r=Yt(n),i=t.filter((c)=>r.palettes.includes(c)),o=t.filter((c)=>!r.palettes.includes(c));if(o.length===0){console.log(`already installed: ${i.join(", ")}`);return}let s={...r,palettes:[...r.palettes,...o]};Ve(n,e,r,s);for(let c of o)console.log(` + ${c}`);$o(s.palettes.length)}function Gf(t){let n=Tt(),e=Pt(n),r=Yt(n),i=t.filter((s)=>r.palettes.includes(s));if(i.length===0){console.log(`not installed: ${t.join(", ")}`);return}let o={...r,palettes:r.palettes.filter((s)=>!i.includes(s))};Ve(n,e,r,o),Ci(n,e,r.terminals,i);for(let s of i)console.log(` - ${s}`);$o(o.palettes.length)}function Lf(t){let n=Tt(),e=Pt(n),r=Yt(n);if(!r.palettes.includes(t))throw Error(`${t} is not installed — \`ttheme add ${t}\` first`);let{off:i,...o}=r,s=zn(),c=Qe({...o,startup:t},s);Xe(n,e,c),qe(n,c);let u=Ze(c,s);console.log(Jf(t,c.terminals,u&&s.running()).join(`
207
+ `))}function Pf(){let t=Tt(),n=Yt(t),e=Yn(n);if(!e)throw Error("no palettes installed — `ttheme browse` picks some");if(!n.off){console.log(`already on · ${e}`);return}let{off:r,...i}=n,o=Ve(t,Pt(t),n,i);console.log(Jf(e,i.terminals,o).join(`
208
+ `))}function Kf(){let t=Tt(),n=Yt(t);if(n.off){console.log("already off");return}let e=Ve(t,Pt(t),n,{...n,off:!0}),r=Yn(n);if(console.log(`off · new tabs open in the terminal's own colors${r?` — \`ttheme on\` wears ${r} again`:""}`),e)console.log("iterm2 new tabs open on your own profile once iTerm2 restarts")}function Jf(t,n,e){let r=n.filter((o)=>o!=="iterm2"),i=r.length>0?[`default ${t} · ${r.join(", ")} open new tabs with it once their config reloads`]:[];if(n.includes("iterm2"))i.push(e?'iterm2 new tabs open with it once iTerm2 restarts — "ttheme · default" is now its default profile':'iterm2 new tabs open with it — "ttheme · default" is its default profile');return i.length>0?i:[`default ${t} · no terminal is wired to open with it — \`ttheme init\` wires one`]}function Af(t){let n=Tt(),e=Pt(n),r=new Set(Yt(n).palettes),i=qn(e.palettes),o=He(t?Ju(i,t):i),s=Math.max(...o.map((u)=>u.name.length),0);for(let u of o)console.log(` ${r.has(u.name)?"●":"○"} ${u.name.padEnd(s)} ${u.group}`);let c=t?`${o.length} of ${i.length}`:`${i.length}`;console.log(`
209
+ ${c} palettes — ${o.filter((u)=>r.has(u.name)).length} installed`)}async function Uf(){let t=Tt(),n=zp(Nr(t))?Pt(t).palettes.length:0,e=await Pu(Gu);Or(t,e);let r=e.palettes.length-n;console.log(`catalog ${e.version} — ${e.palettes.length} palettes${r>0?` (+${r})`:""}`)}async function bo(t,n,e,r=!1){let i=process.env.TTHEME_SORT==="series"?t.palettes:He(t.palettes),o=process.stdout.isTTY===!0&&!process.env.NO_COLOR,s=o?await Ff():new Map,c=new wo({entries:i,scope:e,installed:n,required:r,color:!process.env.NO_COLOR,fx:jf(process.env.TTHEME_FX),onFocus:o?(h)=>process.stdout.write(_r(h)):void 0}),u=await c.prompt();if(process.stdout.write(Sf(s)),ne(u))return;return t.palettes.filter((h)=>c.picked.has(h.name)).map((h)=>h.name)}async function Tf(){let t=Tt(),n=Pt(t),e=Yt(t),r=await bo(n,e.palettes,"palette");if(!r){console.log("nothing changed");return}let i=e.palettes.filter((c)=>!r.includes(c)),o=r.filter((c)=>!e.palettes.includes(c));if(o.length===0&&i.length===0){console.log("nothing changed");return}let s={...e,palettes:r};Ve(t,n,e,s),Ci(t,n,e.terminals,i);for(let c of o)console.log(` + ${c}`);for(let c of i)console.log(` - ${c}`);$o(s.palettes.length)}function Zf(t,n,e){for(let r of Dp(n))t.push({from:ct(n,r),to:ct(e,r)})}function Cf(t){return JSON.parse(se(ct(t,"dist","manifest.json"),"utf8"))}function qf(t,n){let e=ct(n.root,"dist"),r=ct(n.configHome,"ttheme"),i=[{from:ct(n.root,"bin","ttheme.js"),to:ct(r,"ttheme.js")},{from:ct(n.root,"shell","ttheme.zsh"),to:ct(r,"ttheme.zsh")},{from:ct(n.root,"shell","launch-tab.zsh"),to:ct(r,"launch-tab.zsh"),executable:!0},{from:ct(e,"ghostty","ttheme.conf"),to:ct(r,"ttheme.conf")}];Zf(i,ct(n.root,"shell","adapters"),ct(r,"adapters"));let o=[{file:ct(n.zdotdir,".zshrc"),block:tu(r)}],s=ct(r,"config.zsh"),c=ru(Qt(s)?se(s,"utf8"):""),u={file:s,content:c},h=[];if(t.terminals.includes("ghostty"))Zf(i,ct(n.root,"ghostty","shaders"),ct(n.configHome,"ghostty","shaders"));if(t.terminals.includes("alacritty")){let g=_i(n.configHome);if(Qt(g)&&$r(se(g,"utf8"),void 0)===void 0)h.push(`${g} already imports files under [general] — ttheme left it alone; add ${ct(n.configHome,"alacritty","themes")}/<palette>.toml to that import list yourself`)}if(t.terminals.includes("wezterm")){let g=Xi(n.configHome,n.home);if(Qt(g)&&br(se(g,"utf8"),"")===void 0)h.push(`${g} has no \`return config\` line — ttheme left it alone; call \`dofile("${ct(r,"wezterm.lua")}")(config)\` from it yourself`)}let f=t.terminals.includes("windows-terminal");if(f&&!n.wtHome)h.push("windows terminal: %LOCALAPPDATA% was not found — drop the release fragment into its Fragments folder yourself");if(t.terminals.includes("warp"))h.push("warp: wears the default palette app-wide through its settings.toml — the shell layer stays off in it, since Warp paints no tab background of its own");let a={terminals:t.terminals,palettes:t.palettes,...f&&n.wtHome?{wtHome:n.wtHome}:{},...f&&n.wtProfile?{wtProfile:n.wtProfile}:{},...t.off?{off:!0}:{}};return{home:n.home,copies:i,edits:o,settings:u,catalog:Cf(n.root),installed:a,notes:h}}function n0(t){try{return Yt(t).itermBase}catch{return}}function Xf(t,n=zn()){for(let o of t.copies)if(ko(oe(o.to),{recursive:!0}),Wf(o.to,{force:!0}),Wf(`${o.to}.zwc`,{force:!0}),Bp(o.from,o.to),o.executable)xp(o.to,493);ko(oe(t.settings.file),{recursive:!0}),Qf(t.settings.file,t.settings.content);let e=oe(oe(t.settings.file)),r=n0(e),i=Qe(r?{...t.installed,itermBase:r}:t.installed,n);Or(e,t.catalog),qe(e,i),Xe(e,t.catalog,i,t.home);for(let o of t.edits){ko(oe(o.file),{recursive:!0});let s=Qt(o.file)?se(o.file,"utf8"):"";Qf(o.file,je(s,o.block))}return Ze(i,n)}function Eo(t){if(ne(t))qr("nothing changed"),process.exit(1);return t}function zf(t){return mr.filter((n)=>{if(n==="iterm2")return process.platform==="darwin";if(n==="windows-terminal")return t.wtHome!==void 0;return n!=="warp"||process.platform!=="win32"})}function e0(t,n){if(t==="iterm2")return Qt(ct(n.home,"Library","Application Support","iTerm2"));if(t==="windows-terminal")return n.wtHome!==void 0;if(t==="warp")return Qt(oe(Kr(n.home)));if(t==="wezterm")return Qt(ct(n.configHome,"wezterm"))||Qt(ct(n.home,".wezterm.lua"));return Qt(ct(n.configHome,t))}function r0(){if(process.platform==="win32")return process.env.LOCALAPPDATA;if(!process.env.WSL_DISTRO_NAME)return;let t=(n,e)=>Yp(n,e,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();try{return t("wslpath",["-u",t("cmd.exe",["/d","/c","echo %LOCALAPPDATA%"])])||void 0}catch{return}}async function i0(t,n,e){return Eo(await bf({message:"wire which terminals?",options:zf(e).map((r)=>({value:r,hint:r===t?"detected":void 0})),initialValues:n,required:!0}))}function _f(t){let n=[...t.copies.filter((e)=>!Qt(e.to)).map((e)=>e.to),...Qt(t.settings.file)?[]:[t.settings.file],...t.edits.filter((e)=>!se(e.file,"utf8").includes("# ttheme begin")).map((e)=>e.file)];if(n.length>0)throw Error(`init left gaps:
210
+ ${n.join(`
211
+ `)}`)}function Yf(t,n){return[...new Set(t.palettes.filter((e)=>n.includes(e.name)).map((e)=>e.group))]}function o0(t,n){let e=t.palettes.find((i)=>i.name===hn(n)),r=process.stdout.isTTY===!0&&!process.env.NO_COLOR&&!process.env.TMUX&&pr(process.env)!=="warp";if(!e||!r)return!1;return process.stdout.write(_r(e)),!0}function s0(t,n){let e=hn(t);if(!e)return["default none — new tabs keep the terminal colors",`turn on \`ttheme on\` wears ${Yn(t)}`];return[`default ${e}${n?" — this tab wears it already":""}`,"change it `ttheme preview`, enter on a palette, then default"]}function c0(t){Vp("zsh",["-c",'source "$1" && __tt_preview init',"zsh",ct(t,"ttheme","ttheme.zsh")],{stdio:"inherit"})}function u0(t,n,e,r){let i=Yf(t.catalog,n.palettes);Xr([`${i.join(", ")} (${n.palettes.length})`,...s0(t.installed,e)].join(`
212
+ `),`installed ${n.palettes.length} palettes`);let o=["exec zsh the ttheme command in this tab"];if(n.terminals.includes("ghostty"))o.push("restart ghostty new tabs pick up its config");if(n.terminals.includes("kitty"))o.push("new kitty window pictures follow it — kitty reloads its colors by itself");if(n.terminals.includes("alacritty"))o.push("alacritty reloads its config by itself");if(n.terminals.includes("wezterm"))o.push("wezterm reloads its config by itself");if(n.terminals.includes("windows-terminal"))o.push("windows terminal reloads its settings by itself");if(n.terminals.includes("iterm2"))o.push(...h0(hn(t.installed),r));Xr([...o,...t.notes].join(`
213
+ `),"next"),Ef("done")}function h0(t,n){let e=['iterm2 profiles a "ttheme · <palette>" per palette in Settings › Profiles'];if(t)e.push(n?`restart iterm2 new tabs open on "ttheme · default", which wears ${t}`:`iterm2 default "ttheme · default" wears ${t} and follows \`ttheme default\``);return e}function f0(t,n){let e=[`placed ${t.copies.length} files`,`settings in ${t.settings.file} — edit later with \`ttheme config\``,...t.edits.map((r)=>`wired ${r.file}`)];if(n.terminals.includes("ghostty"))e.push("restart ghostty to pick up its config");if(n.terminals.includes("kitty"))e.push("kitty reloads its colors by itself; pictures show in kitty windows opened from now on");if(n.terminals.includes("alacritty"))e.push("alacritty reloads its config by itself");if(n.terminals.includes("wezterm")||n.terminals.includes("windows-terminal"))e.push("wezterm and windows terminal reload their config by themselves");if(n.terminals.includes("iterm2"))e.push('iterm2 gets a "ttheme · <palette>" profile per palette under Settings › Profiles');e.push(...t.notes),e.push("no palettes yet — open a new shell (`exec zsh`), then `ttheme browse` picks them from the catalog"),console.log(e.join(`
214
+ `))}async function Vf(t={}){let n=ct(import.meta.dirname,"..");if(!Qt(ct(n,"bin","ttheme.js")))throw Error("bin/ttheme.js is missing — run `mise run bin:build` first");if(!Qt(ct(n,"dist"))){if(typeof Bun>"u")throw Error("this package is missing dist/ — reinstall @kecan0406/ttheme");await Er()}let e=t0(),r=process.env.XDG_CONFIG_HOME??ct(e,".config"),i=process.env.ZDOTDIR??e,o=r0(),s=process.env.WT_PROFILE_ID,c={root:n,home:e,configHome:r,zdotdir:i,...o?{wtHome:o}:{},...s?{wtProfile:s}:{}},u=pr(process.env),h=zf(c).filter((H)=>H===u||e0(H,c));if(!(!t.yes&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0)){if(h.length===0)throw Error("no supported terminal detected — run this inside ghostty, kitty, alacritty, wezterm, iterm2, windows terminal or warp");let H={terminals:h,palettes:[]},b=qf(H,c);Xf(b),_f(b),f0(b,H);return}kf("ttheme init");let a=await i0(u,h,c),g=Cf(n),d=await bo(g,[],"series",!0);if(!d)qr("nothing changed"),process.exit(1);let p=d[0],l=d.length>1&&pr(process.env)!=="warp",k=Eo(await lo({message:l?"pick a default palette in ttheme preview once installed?":`wear ${p} in every tab?`})),v={terminals:a,palettes:d,off:!k},I=qf(v,c);if(Xr([`install ${d.length} palettes — ${Yf(I.catalog,d).join(", ")}`,`copy ${I.copies.length} files under ${r}`,`write ${I.settings.file}`,...I.edits.map((H)=>`edit ${H.file}`),k?l?`open ttheme preview — every tab wears the palette picked there, ${p} until then`:`paint every tab with ${p}, this one now`:"leave the terminal colors as they are — `ttheme on` wears a palette later",...a.includes("iterm2")&&k?['make "ttheme · default" the iTerm2 default profile']:[]].join(`
215
+ `),`wiring ${a.join(", ")}`),!Eo(await lo({message:"apply these changes?"})))qr("nothing changed"),process.exit(1);let E=zn(),y=Xf(I,E);if(_f(I),k&&l)c0(r);let $=Yt(r);u0({...I,installed:$},v,o0(I.catalog,$),y&&E.running())}var ta=[{name:"build",args:[],about:"emit dist/ for every terminal, plus the zsh palette table",flags:{only:{type:"string",multiple:!0,value:"<terminal>",choices:$u,about:"rebuild just this terminal — repeat it for more"}},run:(t,{only:n})=>Er({only:n})},{name:"init",args:[],about:"install the palettes and wire your terminal configs",flags:{yes:{type:"boolean",about:"accept every default without prompting"}},run:(t,{yes:n})=>Vf({yes:n})},{name:"browse",args:[],about:"pick palettes from the catalog in a live picker",run:()=>Tf()},{name:"list",args:["[query]"],about:"show the catalog, marking what is installed",run:([t])=>Af(t)},{name:"add",args:["<palette...>"],about:"install palettes from the catalog",run:(t)=>Rf(t)},{name:"remove",args:["<palette...>"],about:"uninstall palettes",run:(t)=>Gf(t)},{name:"default",args:["<palette>"],about:"make an installed palette the one new tabs open with",run:([t])=>Lf(t)},{name:"on",args:[],about:"wear the default palette in new tabs again",run:()=>Pf()},{name:"off",args:[],about:"open new tabs in the terminal's own colors until `ttheme on`",run:()=>Kf()},{name:"find",args:["<palette>"],about:"pick a booru background for a palette — preview opens this on tab",hidden:!0,run:([t])=>Jh(t)},{name:"image",args:["<palette>","<action>"],about:"switch a palette between its saved backgrounds, remove the one shown, or pass on tuning — preview calls this",hidden:!0,run:([t,n])=>Ah(t,n)},{name:"update",args:[],about:"refresh the catalog from the registry",run:()=>Uf()}];class Pn extends Error{verb;constructor(t,n){super(t);this.verb=n}}function xf(t){let n=ta.find((e)=>e.name===t);if(!n)throw new Pn(t.startsWith("-")?`unknown option '${t}'`:`unknown command '${t}'`);return n}function g0(t,n){let e={help:{type:"boolean",short:"h"}};for(let[r,{type:i,multiple:o}]of Object.entries(t.flags??{}))e[r]={type:i,multiple:o===!0};try{return a0({args:n,options:e,allowPositionals:!0})}catch(r){let[i=""]=(r instanceof Error?r.message:String(r)).split(". ");throw new Pn(`${i.charAt(0).toLowerCase()}${i.slice(1)}`,t)}}function l0(t){let[n,...e]=t;if(n===void 0)return{kind:"help",code:1};if(n==="-h"||n==="--help")return{kind:"help",code:0};if(n==="-V"||n==="--version")return{kind:"version"};if(n==="help")return e[0]===void 0?{kind:"help",code:0}:{kind:"help",verb:xf(e[0]),code:0};let r=xf(n),i=g0(r,e);if(i.values.help)return{kind:"help",verb:r,code:0};for(let[f,{choices:a}]of Object.entries(r.flags??{}))for(let g of[i.values[f]??[]].flat())if(a&&!a.includes(String(g)))throw new Pn(`--${f} takes ${a.join(", ")} — not ${g}`,r);let o=i.positionals,s=r.args.filter((f)=>f.startsWith("<")).length,c=r.args.some((f)=>f.includes("..."))?Number.POSITIVE_INFINITY:r.args.length;if(o.length<s)throw new Pn(`missing ${r.args[o.length]}`,r);if(o.length>c)throw new Pn(`too many arguments: ${o.slice(c).join(" ")}`,r);let{help:u,...h}=i.values;return{kind:"run",verb:r,args:o,flags:h}}function Bf(t){let n=Object.entries(t.flags??{}).map(([e,{value:r}])=>`[--${e}${r?` ${r}`:""}]`);return[t.name,...n,...t.args].join(" ")}function Df(t){let n=Math.max(...t.map(([e])=>e.length));return t.map(([e,r])=>` ${e.padEnd(n)} ${r}`)}function Mo(t){if(t){let n=Object.entries(t.flags??{}).map(([e,{value:r,about:i}])=>[`--${e}${r?` ${r}`:""}`,i]);return[`Usage: ttheme ${Bf(t)}`,"",t.about,...n.length>0?["","Options:",...Df(n)]:[]].join(`
216
+ `)}return["Usage: ttheme <command>","",en.description,"","Commands:",...Df(ta.filter((n)=>!n.hidden).map((n)=>[Bf(n),n.about])),"","ttheme <command> --help describes one command · ttheme --version prints the version"].join(`
217
+ `)}async function na(t){try{let n=l0(t);if(n.kind==="version")return console.log(en.version),0;if(n.kind==="help"){if(n.code===0)console.log(Mo(n.verb));else console.error(Mo(n.verb));return n.code}let e=await n.verb.run(n.args,n.flags);return typeof e==="number"?e:0}catch(n){if(n instanceof Pn)return console.error(`ttheme${n.verb?` ${n.verb.name}`:""}: ${n.message}
175
218
 
176
- ${oo(r.verb)}`),1;return console.error(`
177
- ${r instanceof Error?r.message:String(r)}`),1}}if(h0)process.exitCode=await kf(process.argv.slice(2));
219
+ ${Mo(n.verb)}`),1;return console.error(`
220
+ ${n instanceof Error?n.message:String(n)}`),1}}if(d0)process.exitCode=await na(process.argv.slice(2));