@kecan0406/ttheme 1.0.0 → 1.0.1

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,40 +1,41 @@
1
1
  #!/usr/bin/env node
2
- import{createRequire as Nh}from"node:module";var wh=Object.create;var{getPrototypeOf:Eh,defineProperty:Te,getOwnPropertyNames:kh}=Object;var Mh=Object.prototype.hasOwnProperty;function Fh(n){return this[n]}var vh,Ih,Nt=(n,r,t)=>{var i=n!=null&&typeof n==="object";if(i){var e=r?vh??=new WeakMap:Ih??=new WeakMap,o=e.get(n);if(o)return o}t=n!=null?wh(Eh(n)):{};let s=r||!n||!n.__esModule?Te(t,"default",{value:n,enumerable:!0}):t;for(let u of kh(n))if(!Mh.call(s,u))Te(s,u,{get:Fh.bind(n,u),enumerable:!0});if(i)e.set(n,s);return s};var an=(n,r)=>()=>(r||n((r={exports:{}}).exports,r),r.exports);var Gn=Nh(import.meta.url);var Ho=an((Ed,Rt)=>{var No=No||function(n){return Buffer.from(n).toString("base64")};function Ch(n){var r=this,t=Math.round,i=Math.floor,e=Array(64),o=Array(64),s=Array(64),u=Array(64),c,h,f,g,l=Array(65535),$=Array(65535),a=Array(64),w=Array(64),F=[],H=0,J=7,M=Array(64),I=Array(64),b=Array(64),K=Array(256),E=Array(2048),G,j=[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],Q=[0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0],R=[0,1,2,3,4,5,6,7,8,9,10,11],A=[0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,125],L=[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],In=[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],B=[0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,119],kn=[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(m){var O=[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 q=0;q<64;q++){var Z=i((O[q]*m+50)/100);if(Z<1)Z=1;else if(Z>255)Z=255;e[j[q]]=Z}var Y=[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 z=0;z<64;z++){var en=i((Y[z]*m+50)/100);if(en<1)en=1;else if(en>255)en=255;o[j[z]]=en}var on=[1,1.387039845,1.306562965,1.175875602,1,0.785694958,0.5411961,0.275899379],Fn=0;for(var $n=0;$n<8;$n++)for(var v=0;v<8;v++)s[Fn]=1/(e[j[Fn]]*on[$n]*on[v]*8),u[Fn]=1/(o[j[Fn]]*on[$n]*on[v]*8),Fn++}function x(m,O){var q=0,Z=0,Y=[];for(var z=1;z<=16;z++){for(var en=1;en<=m[z];en++)Y[O[Z]]=[],Y[O[Z]][0]=q,Y[O[Z]][1]=z,Z++,q++;q*=2}return Y}function Nn(){c=x(Q,R),h=x(In,U),f=x(A,L),g=x(B,kn)}function sn(){var m=1,O=2;for(var q=1;q<=15;q++){for(var Z=m;Z<O;Z++)$[32767+Z]=q,l[32767+Z]=[],l[32767+Z][1]=q,l[32767+Z][0]=Z;for(var Y=-(O-1);Y<=-m;Y++)$[32767+Y]=q,l[32767+Y]=[],l[32767+Y][1]=q,l[32767+Y][0]=O-1+Y;m<<=1,O<<=1}}function nn(){for(var m=0;m<256;m++)E[m]=19595*m,E[m+256>>0]=38470*m,E[m+512>>0]=7471*m+32768,E[m+768>>0]=-11059*m,E[m+1024>>0]=-21709*m,E[m+1280>>0]=32768*m+8421375,E[m+1536>>0]=-27439*m,E[m+1792>>0]=-5329*m}function C(m){var O=m[0],q=m[1]-1;while(q>=0){if(O&1<<q)H|=1<<J;if(q--,J--,J<0){if(H==255)d(255),d(0);else d(H);J=7,H=0}}}function d(m){F.push(m)}function y(m){d(m>>8&255),d(m&255)}function hn(m,O){var q,Z,Y,z,en,on,Fn,$n,v=0,p,V=8,Mn=64;for(p=0;p<V;++p){q=m[v],Z=m[v+1],Y=m[v+2],z=m[v+3],en=m[v+4],on=m[v+5],Fn=m[v+6],$n=m[v+7];var P=q+$n,D=q-$n,gn=Z+Fn,W=Z-Fn,un=Y+on,pn=Y-on,En=z+en,Un=z-en,xn=P+En,$r=P-En,jr=gn+un,pr=gn-un;m[v]=xn+jr,m[v+4]=xn-jr;var Pr=(pr+$r)*0.707106781;m[v+2]=$r+Pr,m[v+6]=$r-Pr,xn=Un+pn,jr=pn+W,pr=W+D;var Ar=(xn-pr)*0.382683433,Mt=0.5411961*xn+Ar,Cr=1.306562965*pr+Ar,Tr=jr*0.707106781,_r=D+Tr,Br=D-Tr;m[v+5]=Br+Mt,m[v+3]=Br-Mt,m[v+1]=_r+Cr,m[v+7]=_r-Cr,v+=8}v=0;for(p=0;p<V;++p){q=m[v],Z=m[v+8],Y=m[v+16],z=m[v+24],en=m[v+32],on=m[v+40],Fn=m[v+48],$n=m[v+56];var ye=q+$n,oi=q-$n,Ze=Z+Fn,Le=Z-Fn,Ue=Y+on,qe=Y-on,We=z+en,bh=z-en,xr=ye+We,si=ye-We,Ft=Ze+Ue,vt=Ze-Ue;m[v]=xr+Ft,m[v+32]=xr-Ft;var Xe=(vt+si)*0.707106781;m[v+16]=si+Xe,m[v+48]=si-Xe,xr=bh+qe,Ft=qe+Le,vt=Le+oi;var Ve=(xr-vt)*0.382683433,Ye=0.5411961*xr+Ve,ze=1.306562965*vt+Ve,Pe=Ft*0.707106781,Ae=oi+Pe,Ce=oi-Pe;m[v+40]=Ce+Ye,m[v+24]=Ce-Ye,m[v+8]=Ae+ze,m[v+56]=Ae-ze,v++}var It;for(p=0;p<Mn;++p)It=m[p]*O[p],a[p]=It>0?It+0.5|0:It-0.5|0;return a}function fn(){y(65504),y(16),d(74),d(70),d(73),d(70),d(0),d(1),d(1),d(0),y(1),y(1),d(0),d(0)}function rn(m){if(!m)return;if(y(65505),m[0]===69&&m[1]===120&&m[2]===105&&m[3]===102)y(m.length+2);else y(m.length+5+2),d(69),d(120),d(105),d(102),d(0);for(var O=0;O<m.length;O++)d(m[O])}function tn(m,O){y(65472),y(17),d(8),y(O),y(m),d(3),d(1),d(17),d(0),d(2),d(17),d(1),d(3),d(17),d(1)}function T(){y(65499),y(132),d(0);for(var m=0;m<64;m++)d(e[m]);d(1);for(var O=0;O<64;O++)d(o[O])}function S(){y(65476),y(418),d(0);for(var m=0;m<16;m++)d(Q[m+1]);for(var O=0;O<=11;O++)d(R[O]);d(16);for(var q=0;q<16;q++)d(A[q+1]);for(var Z=0;Z<=161;Z++)d(L[Z]);d(1);for(var Y=0;Y<16;Y++)d(In[Y+1]);for(var z=0;z<=11;z++)d(U[z]);d(17);for(var en=0;en<16;en++)d(B[en+1]);for(var on=0;on<=161;on++)d(kn[on])}function N(m){if(typeof m>"u"||m.constructor!==Array)return;m.forEach((O)=>{if(typeof O!=="string")return;y(65534);var q=O.length;y(q+2);var Z;for(Z=0;Z<q;Z++)d(O.charCodeAt(Z))})}function dn(){y(65498),y(12),d(3),d(1),d(0),d(2),d(17),d(3),d(17),d(0),d(63),d(0)}function X(m,O,q,Z,Y){var z=Y[0],en=Y[240],on,Fn=16,$n=63,v=64,p=hn(m,O);for(var V=0;V<v;++V)w[j[V]]=p[V];var Mn=w[0]-q;if(q=w[0],Mn==0)C(Z[0]);else on=32767+Mn,C(Z[$[on]]),C(l[on]);var P=63;for(;P>0&&w[P]==0;P--);if(P==0)return C(z),q;var D=1,gn;while(D<=P){var W=D;for(;w[D]==0&&D<=P;++D);var un=D-W;if(un>=Fn){gn=un>>4;for(var pn=1;pn<=gn;++pn)C(en);un=un&15}on=32767+w[D],C(Y[(un<<4)+$[on]]),C(l[on]),D++}if(P!=$n)C(z);return q}function _(){var m=String.fromCharCode;for(var O=0;O<256;O++)K[O]=m(O)}this.encode=function(m,O){var q=new Date().getTime();if(O)Ln(O);F=[],H=0,J=7,y(65496),fn(),N(m.comments),rn(m.exifBuffer),T(),tn(m.width,m.height),S(),dn();var Z=0,Y=0,z=0;H=0,J=7,this.encode.displayName="_encode_";var{data:en,width:on,height:Fn}=m,$n=on*4,v=on*3,p,V=0,Mn,P,D,gn,W,un,pn,En;while(V<Fn){p=0;while(p<$n){gn=$n*V+p,W=gn,un=-1,pn=0;for(En=0;En<64;En++){if(pn=En>>3,un=(En&7)*4,W=gn+pn*$n+un,V+pn>=Fn)W-=$n*(V+1+pn-Fn);if(p+un>=$n)W-=p+un-$n+4;Mn=en[W++],P=en[W++],D=en[W++],M[En]=(E[Mn]+E[P+256>>0]+E[D+512>>0]>>16)-128,I[En]=(E[Mn+768>>0]+E[P+1024>>0]+E[D+1280>>0]>>16)-128,b[En]=(E[Mn+1280>>0]+E[P+1536>>0]+E[D+1792>>0]>>16)-128}Z=X(M,s,Z,c,f),Y=X(I,u,Y,h,g),z=X(b,u,z,h,g),p+=32}V+=8}if(J>=0){var Un=[];Un[1]=J+1,Un[0]=(1<<J+1)-1,C(Un)}if(y(65497),typeof Rt>"u")return new Uint8Array(F);return Buffer.from(F);var xn,$r};function Ln(m){if(m<=0)m=1;if(m>100)m=100;if(G==m)return;var O=0;if(m<50)O=Math.floor(5000/m);else O=Math.floor(200-m*2);mn(O),G=m}function Pn(){var m=new Date().getTime();if(!n)n=50;_(),Nn(),sn(),nn(),Ln(n);var O=new Date().getTime()-m}Pn()}if(typeof Rt<"u")Rt.exports=Io;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].encode=Io;function Io(n,r){if(typeof r>"u")r=50;var t=new Ch(r),i=t.encode(n,r);return{data:i,width:n.width,height:n.height}}});var jo=an((kd,vi)=>{var Fi=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]),t=4017,i=799,e=3406,o=2276,s=1567,u=3784,c=5793,h=2896;function f(){}function g(J,M){var I=0,b=[],K,E,G=16;while(G>0&&!J[G-1])G--;b.push({children:[],index:0});var j=b[0],Q;for(K=0;K<G;K++){for(E=0;E<J[K];E++){j=b.pop(),j.children[j.index]=M[I];while(j.index>0){if(b.length===0)throw Error("Could not recreate Huffman Table");j=b.pop()}j.index++,b.push(j);while(b.length<=K)b.push(Q={children:[],index:0}),j.children[j.index]=Q.children,j=Q;I++}if(K+1<G)b.push(Q={children:[],index:0}),j.children[j.index]=Q.children,j=Q}return b[0].children}function l(J,M,I,b,K,E,G,j,Q,R){var{precision:A,samplesPerLine:L,scanLines:In,mcusPerLine:U,progressive:B,maxH:kn,maxV:mn}=I,x=M,Nn=0,sn=0;function nn(){if(sn>0)return sn--,Nn>>sn&1;if(Nn=J[M++],Nn==255){var v=J[M++];if(v)throw Error("unexpected marker: "+(Nn<<8|v).toString(16))}return sn=7,Nn>>>7}function C(v){var p=v,V;while((V=nn())!==null){if(p=p[V],typeof p==="number")return p;if(typeof p!=="object")throw Error("invalid huffman sequence")}return null}function d(v){var p=0;while(v>0){var V=nn();if(V===null)return;p=p<<1|V,v--}return p}function y(v){var p=d(v);if(p>=1<<v-1)return p;return p+(-1<<v)+1}function hn(v,p){var V=C(v.huffmanTableDC),Mn=V===0?0:y(V);p[0]=v.pred+=Mn;var P=1;while(P<64){var D=C(v.huffmanTableAC),gn=D&15,W=D>>4;if(gn===0){if(W<15)break;P+=16;continue}P+=W;var un=r[P];p[un]=y(gn),P++}}function fn(v,p){var V=C(v.huffmanTableDC),Mn=V===0?0:y(V)<<Q;p[0]=v.pred+=Mn}function rn(v,p){p[0]|=nn()<<Q}var tn=0;function T(v,p){if(tn>0){tn--;return}var V=E,Mn=G;while(V<=Mn){var P=C(v.huffmanTableAC),D=P&15,gn=P>>4;if(D===0){if(gn<15){tn=d(gn)+(1<<gn)-1;break}V+=16;continue}V+=gn;var W=r[V];p[W]=y(D)*(1<<Q),V++}}var S=0,N;function dn(v,p){var V=E,Mn=G,P=0;while(V<=Mn){var D=r[V],gn=p[D]<0?-1:1;switch(S){case 0:var W=C(v.huffmanTableAC),un=W&15,P=W>>4;if(un===0)if(P<15)tn=d(P)+(1<<P),S=4;else P=16,S=1;else{if(un!==1)throw Error("invalid ACn encoding");N=y(un),S=P?2:3}continue;case 1:case 2:if(p[D])p[D]+=(nn()<<Q)*gn;else if(P--,P===0)S=S==2?3:0;break;case 3:if(p[D])p[D]+=(nn()<<Q)*gn;else p[D]=N<<Q,S=0;break;case 4:if(p[D])p[D]+=(nn()<<Q)*gn;break}V++}if(S===4){if(tn--,tn===0)S=0}}function X(v,p,V,Mn,P){var D=V/U|0,gn=V%U,W=D*v.v+Mn,un=gn*v.h+P;if(v.blocks[W]===void 0&&R.tolerantDecoding)return;p(v,v.blocks[W][un])}function _(v,p,V){var Mn=V/v.blocksPerLine|0,P=V%v.blocksPerLine;if(v.blocks[Mn]===void 0&&R.tolerantDecoding)return;p(v,v.blocks[Mn][P])}var Ln=b.length,Pn,m,O,q,Z,Y;if(B)if(E===0)Y=j===0?fn:rn;else Y=j===0?T:dn;else Y=hn;var z=0,en,on;if(Ln==1)on=b[0].blocksPerLine*b[0].blocksPerColumn;else on=U*I.mcusPerColumn;if(!K)K=on;var Fn,$n;while(z<on){for(m=0;m<Ln;m++)b[m].pred=0;if(tn=0,Ln==1){Pn=b[0];for(Z=0;Z<K;Z++)_(Pn,Y,z),z++}else for(Z=0;Z<K;Z++){for(m=0;m<Ln;m++){Pn=b[m],Fn=Pn.h,$n=Pn.v;for(O=0;O<$n;O++)for(q=0;q<Fn;q++)X(Pn,Y,z,O,q)}if(z++,z===on)break}if(z===on)do{if(J[M]===255){if(J[M+1]!==0)break}M+=1}while(M<J.length-2);if(sn=0,en=J[M]<<8|J[M+1],en<65280)throw Error("marker was not found");if(en>=65488&&en<=65495)M+=2;else break}return M-x}function $(J,M){var I=[],b=M.blocksPerLine,K=M.blocksPerColumn,E=b<<3,G=new Int32Array(64),j=new Uint8Array(64);function Q(x,Nn,sn){var nn=M.quantizationTable,C,d,y,hn,fn,rn,tn,T,S,N=sn,dn;for(dn=0;dn<64;dn++)N[dn]=x[dn]*nn[dn];for(dn=0;dn<8;++dn){var X=8*dn;if(N[1+X]==0&&N[2+X]==0&&N[3+X]==0&&N[4+X]==0&&N[5+X]==0&&N[6+X]==0&&N[7+X]==0){S=c*N[0+X]+512>>10,N[0+X]=S,N[1+X]=S,N[2+X]=S,N[3+X]=S,N[4+X]=S,N[5+X]=S,N[6+X]=S,N[7+X]=S;continue}C=c*N[0+X]+128>>8,d=c*N[4+X]+128>>8,y=N[2+X],hn=N[6+X],fn=h*(N[1+X]-N[7+X])+128>>8,T=h*(N[1+X]+N[7+X])+128>>8,rn=N[3+X]<<4,tn=N[5+X]<<4,S=C-d+1>>1,C=C+d+1>>1,d=S,S=y*u+hn*s+128>>8,y=y*s-hn*u+128>>8,hn=S,S=fn-tn+1>>1,fn=fn+tn+1>>1,tn=S,S=T+rn+1>>1,rn=T-rn+1>>1,T=S,S=C-hn+1>>1,C=C+hn+1>>1,hn=S,S=d-y+1>>1,d=d+y+1>>1,y=S,S=fn*o+T*e+2048>>12,fn=fn*e-T*o+2048>>12,T=S,S=rn*i+tn*t+2048>>12,rn=rn*t-tn*i+2048>>12,tn=S,N[0+X]=C+T,N[7+X]=C-T,N[1+X]=d+tn,N[6+X]=d-tn,N[2+X]=y+rn,N[5+X]=y-rn,N[3+X]=hn+fn,N[4+X]=hn-fn}for(dn=0;dn<8;++dn){var _=dn;if(N[8+_]==0&&N[16+_]==0&&N[24+_]==0&&N[32+_]==0&&N[40+_]==0&&N[48+_]==0&&N[56+_]==0){S=c*sn[dn+0]+8192>>14,N[0+_]=S,N[8+_]=S,N[16+_]=S,N[24+_]=S,N[32+_]=S,N[40+_]=S,N[48+_]=S,N[56+_]=S;continue}C=c*N[0+_]+2048>>12,d=c*N[32+_]+2048>>12,y=N[16+_],hn=N[48+_],fn=h*(N[8+_]-N[56+_])+2048>>12,T=h*(N[8+_]+N[56+_])+2048>>12,rn=N[24+_],tn=N[40+_],S=C-d+1>>1,C=C+d+1>>1,d=S,S=y*u+hn*s+2048>>12,y=y*s-hn*u+2048>>12,hn=S,S=fn-tn+1>>1,fn=fn+tn+1>>1,tn=S,S=T+rn+1>>1,rn=T-rn+1>>1,T=S,S=C-hn+1>>1,C=C+hn+1>>1,hn=S,S=d-y+1>>1,d=d+y+1>>1,y=S,S=fn*o+T*e+2048>>12,fn=fn*e-T*o+2048>>12,T=S,S=rn*i+tn*t+2048>>12,rn=rn*t-tn*i+2048>>12,tn=S,N[0+_]=C+T,N[56+_]=C-T,N[8+_]=d+tn,N[48+_]=d-tn,N[16+_]=y+rn,N[40+_]=y-rn,N[24+_]=hn+fn,N[32+_]=hn-fn}for(dn=0;dn<64;++dn){var Ln=128+(N[dn]+8>>4);Nn[dn]=Ln<0?0:Ln>255?255:Ln}}H(E*K*8);var R,A;for(var L=0;L<K;L++){var In=L<<3;for(R=0;R<8;R++)I.push(new Uint8Array(E));for(var U=0;U<b;U++){Q(M.blocks[L][U],j,G);var B=0,kn=U<<3;for(A=0;A<8;A++){var mn=I[In+A];for(R=0;R<8;R++)mn[kn+R]=j[B++]}}}return I}function a(J){return J<0?0:J>255?255:J}f.prototype={load:function(M){var I=new XMLHttpRequest;I.open("GET",M,!0),I.responseType="arraybuffer",I.onload=function(){var b=new Uint8Array(I.response||I.mozResponseArrayBuffer);if(this.parse(b),this.onload)this.onload()}.bind(this),I.send(null)},parse:function(M){var I=this.opts.maxResolutionInMP*1000*1000,b=0,K=M.length;function E(){var W=M[b]<<8|M[b+1];return b+=2,W}function G(){var W=E(),un=M.subarray(b,b+W-2);return b+=un.length,un}function j(W){var un=1,pn=1,En,Un;for(Un in W.components)if(W.components.hasOwnProperty(Un)){if(En=W.components[Un],un<En.h)un=En.h;if(pn<En.v)pn=En.v}var xn=Math.ceil(W.samplesPerLine/8/un),$r=Math.ceil(W.scanLines/8/pn);for(Un in W.components)if(W.components.hasOwnProperty(Un)){En=W.components[Un];var jr=Math.ceil(Math.ceil(W.samplesPerLine/8)*En.h/un),pr=Math.ceil(Math.ceil(W.scanLines/8)*En.v/pn),Pr=xn*En.h,Ar=$r*En.v,Mt=Ar*Pr,Cr=[];H(Mt*256);for(var Tr=0;Tr<Ar;Tr++){var _r=[];for(var Br=0;Br<Pr;Br++)_r.push(new Int32Array(64));Cr.push(_r)}En.blocksPerLine=jr,En.blocksPerColumn=pr,En.blocks=Cr}W.maxH=un,W.maxV=pn,W.mcusPerLine=xn,W.mcusPerColumn=$r}var Q=null,R=null,A=null,L,In,U=[],B=[],kn=[],mn=[],x=E(),Nn=-1;if(this.comments=[],x!=65496)throw Error("SOI not found");x=E();while(x!=65497){var sn,nn,C;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 d=G();if(x===65534){var y=String.fromCharCode.apply(null,d);this.comments.push(y)}if(x===65504){if(d[0]===74&&d[1]===70&&d[2]===73&&d[3]===70&&d[4]===0)Q={version:{major:d[5],minor:d[6]},densityUnits:d[7],xDensity:d[8]<<8|d[9],yDensity:d[10]<<8|d[11],thumbWidth:d[12],thumbHeight:d[13],thumbData:d.subarray(14,14+3*d[12]*d[13])}}if(x===65505){if(d[0]===69&&d[1]===120&&d[2]===105&&d[3]===102&&d[4]===0)this.exifBuffer=d.subarray(5,d.length)}if(x===65518){if(d[0]===65&&d[1]===100&&d[2]===111&&d[3]===98&&d[4]===101&&d[5]===0)R={version:d[6],flags0:d[7]<<8|d[8],flags1:d[9]<<8|d[10],transformCode:d[11]}}break;case 65499:var hn=E(),fn=hn+b-2;while(b<fn){var rn=M[b++];H(256);var tn=new Int32Array(64);if(rn>>4===0)for(nn=0;nn<64;nn++){var T=r[nn];tn[T]=M[b++]}else if(rn>>4===1)for(nn=0;nn<64;nn++){var T=r[nn];tn[T]=E()}else throw Error("DQT: invalid table spec");U[rn&15]=tn}break;case 65472:case 65473:case 65474:E(),L={},L.extended=x===65473,L.progressive=x===65474,L.precision=M[b++],L.scanLines=E(),L.samplesPerLine=E(),L.components={},L.componentsOrder=[];var S=L.scanLines*L.samplesPerLine;if(S>I){var N=Math.ceil((S-I)/1e6);throw Error(`maxResolutionInMP limit exceeded by ${N}MP`)}var dn=M[b++],X,_=0,Ln=0;for(sn=0;sn<dn;sn++){X=M[b];var Pn=M[b+1]>>4,m=M[b+1]&15,O=M[b+2];if(Pn<=0||m<=0)throw Error("Invalid sampling factor, expected values above 0");L.componentsOrder.push(X),L.components[X]={h:Pn,v:m,quantizationIdx:O},b+=3}j(L),B.push(L);break;case 65476:var q=E();for(sn=2;sn<q;){var Z=M[b++],Y=new Uint8Array(16),z=0;for(nn=0;nn<16;nn++,b++)z+=Y[nn]=M[b];H(16+z);var en=new Uint8Array(z);for(nn=0;nn<z;nn++,b++)en[nn]=M[b];sn+=17+z,(Z>>4===0?mn:kn)[Z&15]=g(Y,en)}break;case 65501:E(),In=E();break;case 65500:E(),E();break;case 65498:var on=E(),Fn=M[b++],$n=[],v;for(sn=0;sn<Fn;sn++){v=L.components[M[b++]];var p=M[b++];v.huffmanTableDC=mn[p>>4],v.huffmanTableAC=kn[p&15],$n.push(v)}var V=M[b++],Mn=M[b++],P=M[b++],D=l(M,b,L,$n,In,V,Mn,P>>4,P&15,this.opts);b+=D;break;case 65535:if(M[b]!==255)b--;break;default:if(M[b-3]==255&&M[b-2]>=192&&M[b-2]<=254){b-=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 ${(b-1).toString(16)}`);Nn=b-1;let W=E();if(M[b+W-2]===255){b+=W-2;break}}throw Error("unknown JPEG marker "+x.toString(16))}x=E()}if(B.length!=1)throw Error("only single frame JPEGs supported");for(var sn=0;sn<B.length;sn++){var gn=B[sn].components;for(var nn in gn)gn[nn].quantizationTable=U[gn[nn].quantizationIdx],delete gn[nn].quantizationIdx}this.width=L.samplesPerLine,this.height=L.scanLines,this.jfif=Q,this.adobe=R,this.components=[];for(var sn=0;sn<L.componentsOrder.length;sn++){var v=L.components[L.componentsOrder[sn]];this.components.push({lines:$(L,v),scaleX:v.h/L.maxH,scaleY:v.v/L.maxV})}},getData:function(M,I){var b=this.width/M,K=this.height/I,E,G,j,Q,R,A,L,In,U,B,kn=0,mn,x,Nn,sn,nn,C,d,y,hn,fn,rn,tn=M*I*this.components.length;H(tn);var T=new Uint8Array(tn);switch(this.components.length){case 1:E=this.components[0];for(B=0;B<I;B++){R=E.lines[0|B*E.scaleY*K];for(U=0;U<M;U++)mn=R[0|U*E.scaleX*b],T[kn++]=mn}break;case 2:E=this.components[0],G=this.components[1];for(B=0;B<I;B++){R=E.lines[0|B*E.scaleY*K],A=G.lines[0|B*G.scaleY*K];for(U=0;U<M;U++)mn=R[0|U*E.scaleX*b],T[kn++]=mn,mn=A[0|U*G.scaleX*b],T[kn++]=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;E=this.components[0],G=this.components[1],j=this.components[2];for(B=0;B<I;B++){R=E.lines[0|B*E.scaleY*K],A=G.lines[0|B*G.scaleY*K],L=j.lines[0|B*j.scaleY*K];for(U=0;U<M;U++){if(!rn)y=R[0|U*E.scaleX*b],hn=A[0|U*G.scaleX*b],fn=L[0|U*j.scaleX*b];else mn=R[0|U*E.scaleX*b],x=A[0|U*G.scaleX*b],Nn=L[0|U*j.scaleX*b],y=a(mn+1.402*(Nn-128)),hn=a(mn-0.3441363*(x-128)-0.71413636*(Nn-128)),fn=a(mn+1.772*(x-128));T[kn++]=y,T[kn++]=hn,T[kn++]=fn}}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;E=this.components[0],G=this.components[1],j=this.components[2],Q=this.components[3];for(B=0;B<I;B++){R=E.lines[0|B*E.scaleY*K],A=G.lines[0|B*G.scaleY*K],L=j.lines[0|B*j.scaleY*K],In=Q.lines[0|B*Q.scaleY*K];for(U=0;U<M;U++){if(!rn)nn=R[0|U*E.scaleX*b],C=A[0|U*G.scaleX*b],d=L[0|U*j.scaleX*b],sn=In[0|U*Q.scaleX*b];else mn=R[0|U*E.scaleX*b],x=A[0|U*G.scaleX*b],Nn=L[0|U*j.scaleX*b],sn=In[0|U*Q.scaleX*b],nn=255-a(mn+1.402*(Nn-128)),C=255-a(mn-0.3441363*(x-128)-0.71413636*(Nn-128)),d=255-a(mn+1.772*(x-128));T[kn++]=255-nn,T[kn++]=255-C,T[kn++]=255-d,T[kn++]=255-sn}}break;default:throw Error("Unsupported color mode")}return T},copyToImageData:function(M,I){var{width:b,height:K,data:E}=M,G=this.getData(b,K),j=0,Q=0,R,A,L,In,U,B,kn,mn,x;switch(this.components.length){case 1:for(A=0;A<K;A++)for(R=0;R<b;R++)if(L=G[j++],E[Q++]=L,E[Q++]=L,E[Q++]=L,I)E[Q++]=255;break;case 3:for(A=0;A<K;A++)for(R=0;R<b;R++)if(kn=G[j++],mn=G[j++],x=G[j++],E[Q++]=kn,E[Q++]=mn,E[Q++]=x,I)E[Q++]=255;break;case 4:for(A=0;A<K;A++)for(R=0;R<b;R++)if(U=G[j++],B=G[j++],L=G[j++],In=G[j++],kn=255-a(U*(1-In/255)+In),mn=255-a(B*(1-In/255)+In),x=255-a(L*(1-In/255)+In),E[Q++]=kn,E[Q++]=mn,E[Q++]=x,I)E[Q++]=255;break;default:throw Error("Unsupported color mode")}}};var w=0,F=0;function H(J=0){var M=w+J;if(M>F){var I=Math.ceil((M-F)/1024/1024);throw Error(`maxMemoryUsageInMB limit exceeded by at least ${I}MB`)}w=M}return f.resetMaxMemoryUsage=function(J){w=0,F=J},f.getBytesAllocated=function(){return w},f.requestMemoryAllocation=H,f}();if(typeof vi<"u")vi.exports=So;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].decode=So;function So(n,r={}){var t={colorTransform:void 0,useTArray:!1,formatAsRGBA:!0,tolerantDecoding:!0,maxResolutionInMP:100,maxMemoryUsageInMB:512},i={...t,...r},e=new Uint8Array(n),o=new Fi;o.opts=i,Fi.resetMaxMemoryUsage(i.maxMemoryUsageInMB*1024*1024),o.parse(e);var s=i.formatAsRGBA?4:3,u=o.width*o.height*s;try{Fi.requestMemoryAllocation(u);var c={width:o.width,height:o.height,exifBuffer:o.exifBuffer,data:i.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,i.formatAsRGBA),c}});var Go=an((Md,po)=>{var Th=Ho(),_h=jo();po.exports={encode:Th,decode:_h}});var Ii=an((Fd,Ko)=>{var Bh=Gn("util"),Jo=Gn("stream"),An=Ko.exports=function(){Jo.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};Bh.inherits(An,Jo);An.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))};An.prototype.write=function(n,r){if(!this.writable)return this.emit("error",Error("Stream not writable")),!1;let t;if(Buffer.isBuffer(n))t=n;else t=Buffer.from(n,r||this._encoding);if(this._buffers.push(t),this._buffered+=t.length,this._process(),this._reads&&this._reads.length===0)this._paused=!0;return this.writable&&!this._paused};An.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()};An.prototype.destroySoon=An.prototype.end;An.prototype._end=function(){if(this._reads.length>0)this.emit("error",Error("Unexpected end of input"));this.destroy()};An.prototype.destroy=function(){if(!this._buffers)return;this.writable=!1,this._reads=null,this._buffers=null,this.emit("close")};An.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)};An.prototype._processRead=function(n){this._reads.shift();let r=0,t=0,i=Buffer.alloc(n.length);while(r<n.length){let e=this._buffers[t++],o=Math.min(e.length,n.length-r);if(e.copy(i,r,0,o),r+=o,o!==e.length)this._buffers[--t]=e.slice(o)}if(t>0)this._buffers.splice(0,t);this._buffered-=n.length,n.func.call(this,i)};An.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 Ni=an((xh)=>{var fr=[{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]}];xh.getImagePasses=function(n,r){let t=[],i=n%8,e=r%8,o=(n-i)/8,s=(r-e)/8;for(let u=0;u<fr.length;u++){let c=fr[u],h=o*c.x.length,f=s*c.y.length;for(let g=0;g<c.x.length;g++)if(c.x[g]<i)h++;else break;for(let g=0;g<c.y.length;g++)if(c.y[g]<e)f++;else break;if(h>0&&f>0)t.push({width:h,height:f,index:u})}return t};xh.getInterlaceIterator=function(n){return function(r,t,i){let e=r%fr[i].x.length,o=(r-e)/fr[i].x.length*8+fr[i].x[e],s=t%fr[i].y.length,u=(t-s)/fr[i].y.length*8+fr[i].y[s];return o*4+u*n*4}}});var Hi=an((Id,Ro)=>{Ro.exports=function(r,t,i){let e=r+t-i,o=Math.abs(e-r),s=Math.abs(e-t),u=Math.abs(e-i);if(o<=s&&o<=u)return r;if(s<=u)return t;return i}});var Si=an((Nd,Qo)=>{var rf=Ni(),tf=Hi();function Oo(n,r,t){let i=n*r;if(t!==8)i=Math.ceil(i/(8/t));return i}var Kr=Qo.exports=function(n,r){let{width:t,height:i,interlace:e,bpp:o,depth:s}=n;if(this.read=r.read,this.write=r.write,this.complete=r.complete,this._imageIndex=0,this._images=[],e){let u=rf.getImagePasses(t,i);for(let c=0;c<u.length;c++)this._images.push({byteWidth:Oo(u[c].width,o,s),height:u[c].height,lineIndex:0})}else this._images.push({byteWidth:Oo(t,o,s),height:i,lineIndex:0});if(s===8)this._xComparison=o;else if(s===16)this._xComparison=o*2;else this._xComparison=1};Kr.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Kr.prototype._unFilterType1=function(n,r,t){let i=this._xComparison,e=i-1;for(let o=0;o<t;o++){let s=n[1+o],u=o>e?r[o-i]:0;r[o]=s+u}};Kr.prototype._unFilterType2=function(n,r,t){let i=this._lastLine;for(let e=0;e<t;e++){let o=n[1+e],s=i?i[e]:0;r[e]=o+s}};Kr.prototype._unFilterType3=function(n,r,t){let i=this._xComparison,e=i-1,o=this._lastLine;for(let s=0;s<t;s++){let u=n[1+s],c=o?o[s]:0,h=s>e?r[s-i]:0,f=Math.floor((h+c)/2);r[s]=u+f}};Kr.prototype._unFilterType4=function(n,r,t){let i=this._xComparison,e=i-1,o=this._lastLine;for(let s=0;s<t;s++){let u=n[1+s],c=o?o[s]:0,h=s>e?r[s-i]:0,f=s>e&&o?o[s-i]:0,g=tf(h,c,f);r[s]=u+g}};Kr.prototype._reverseFilterLine=function(n){let r=n[0],t,i=this._images[this._imageIndex],e=i.byteWidth;if(r===0)t=n.slice(1,e+1);else switch(t=Buffer.alloc(e),r){case 1:this._unFilterType1(n,t,e);break;case 2:this._unFilterType2(n,t,e);break;case 3:this._unFilterType3(n,t,e);break;case 4:this._unFilterType4(n,t,e);break;default:throw Error("Unrecognised filter type - "+r)}if(this.write(t),i.lineIndex++,i.lineIndex>=i.height)this._lastLine=null,this._imageIndex++,i=this._images[this._imageIndex];else this._lastLine=t;if(i)this.read(i.byteWidth+1,this._reverseFilterLine.bind(this));else this._lastLine=null,this.complete()}});var Lo=an((Hd,Zo)=>{var ef=Gn("util"),yo=Ii(),of=Si(),sf=Zo.exports=function(n){yo.call(this);let r=[],t=this;this._filter=new of(n,{read:this.read.bind(this),write:function(i){r.push(i)},complete:function(){t.emit("complete",Buffer.concat(r))}}),this._filter.start()};ef.inherits(sf,yo)});var Rr=an((Sd,Uo)=>{Uo.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 Gi=an((jd,qo)=>{var ji=[];(function(){for(let n=0;n<256;n++){let r=n;for(let t=0;t<8;t++)if(r&1)r=3988292384^r>>>1;else r=r>>>1;ji[n]=r}})();var pi=qo.exports=function(){this._crc=-1};pi.prototype.write=function(n){for(let r=0;r<n.length;r++)this._crc=ji[(this._crc^n[r])&255]^this._crc>>>8;return!0};pi.prototype.crc32=function(){return this._crc^-1};pi.crc32=function(n){let r=-1;for(let t=0;t<n.length;t++)r=ji[(r^n[t])&255]^r>>>8;return r^-1}});var Ji=an((pd,Wo)=>{var Sn=Rr(),uf=Gi(),jn=Wo.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[Sn.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[Sn.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[Sn.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[Sn.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[Sn.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[Sn.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(){}};jn.prototype.start=function(){this.read(Sn.PNG_SIGNATURE.length,this._parseSignature.bind(this))};jn.prototype._parseSignature=function(n){let r=Sn.PNG_SIGNATURE;for(let t=0;t<r.length;t++)if(n[t]!==r[t]){this.error(Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};jn.prototype._parseChunkBegin=function(n){let r=n.readUInt32BE(0),t=n.readUInt32BE(4),i="";for(let o=4;o<8;o++)i+=String.fromCharCode(n[o]);let e=Boolean(n[4]&32);if(!this._hasIHDR&&t!==Sn.TYPE_IHDR){this.error(Error("Expected IHDR on beggining"));return}if(this._crc=new uf,this._crc.write(Buffer.from(i)),this._chunks[t])return this._chunks[t](r);if(!e){this.error(Error("Unsupported critical chunk type "+i));return}this.read(r+4,this._skipChunk.bind(this))};jn.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};jn.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};jn.prototype._parseChunkEnd=function(n){let r=n.readInt32BE(0),t=this._crc.crc32();if(this._options.checkCRC&&t!==r){this.error(Error("Crc error - "+r+" - "+t));return}if(!this._hasIEND)this.read(8,this._parseChunkBegin.bind(this))};jn.prototype._handleIHDR=function(n){this.read(n,this._parseIHDR.bind(this))};jn.prototype._parseIHDR=function(n){this._crc.write(n);let r=n.readUInt32BE(0),t=n.readUInt32BE(4),i=n[8],e=n[9],o=n[10],s=n[11],u=n[12];if(i!==8&&i!==4&&i!==2&&i!==1&&i!==16){this.error(Error("Unsupported bit depth "+i));return}if(!(e in Sn.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=e;let c=Sn.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:r,height:t,depth:i,interlace:Boolean(u),palette:Boolean(e&Sn.COLORTYPE_PALETTE),color:Boolean(e&Sn.COLORTYPE_COLOR),alpha:Boolean(e&Sn.COLORTYPE_ALPHA),bpp:c,colorType:e}),this._handleChunkEnd()};jn.prototype._handlePLTE=function(n){this.read(n,this._parsePLTE.bind(this))};jn.prototype._parsePLTE=function(n){this._crc.write(n);let r=Math.floor(n.length/3);for(let t=0;t<r;t++)this._palette.push([n[t*3],n[t*3+1],n[t*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};jn.prototype._handleTRNS=function(n){this.simpleTransparency(),this.read(n,this._parseTRNS.bind(this))};jn.prototype._parseTRNS=function(n){if(this._crc.write(n),this._colorType===Sn.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===Sn.COLORTYPE_GRAYSCALE)this.transColor([n.readUInt16BE(0)]);if(this._colorType===Sn.COLORTYPE_COLOR)this.transColor([n.readUInt16BE(0),n.readUInt16BE(2),n.readUInt16BE(4)]);this._handleChunkEnd()};jn.prototype._handleGAMA=function(n){this.read(n,this._parseGAMA.bind(this))};jn.prototype._parseGAMA=function(n){this._crc.write(n),this.gamma(n.readUInt32BE(0)/Sn.GAMMA_DIVISION),this._handleChunkEnd()};jn.prototype._handleIDAT=function(n){if(!this._emittedHeadersFinished)this._emittedHeadersFinished=!0,this.headersFinished();this.read(-n,this._parseIDAT.bind(this,n))};jn.prototype._parseIDAT=function(n,r){if(this._crc.write(r),this._colorType===Sn.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw Error("Expected palette not found");this.inflateData(r);let t=n-r.length;if(t>0)this._handleIDAT(t);else this._handleChunkEnd()};jn.prototype._handleIEND=function(n){this.read(n,this._parseIEND.bind(this))};jn.prototype._parseIEND=function(n){if(this._crc.write(n),this._hasIEND=!0,this._handleChunkEnd(),this.finished)this.finished()}});var Ki=an((mf)=>{var Xo=Ni(),cf=[function(){},function(n,r,t,i){if(i===r.length)throw Error("Ran out of data");let e=r[i];n[t]=e,n[t+1]=e,n[t+2]=e,n[t+3]=255},function(n,r,t,i){if(i+1>=r.length)throw Error("Ran out of data");let e=r[i];n[t]=e,n[t+1]=e,n[t+2]=e,n[t+3]=r[i+1]},function(n,r,t,i){if(i+2>=r.length)throw Error("Ran out of data");n[t]=r[i],n[t+1]=r[i+1],n[t+2]=r[i+2],n[t+3]=255},function(n,r,t,i){if(i+3>=r.length)throw Error("Ran out of data");n[t]=r[i],n[t+1]=r[i+1],n[t+2]=r[i+2],n[t+3]=r[i+3]}],hf=[function(){},function(n,r,t,i){let e=r[0];n[t]=e,n[t+1]=e,n[t+2]=e,n[t+3]=i},function(n,r,t){let i=r[0];n[t]=i,n[t+1]=i,n[t+2]=i,n[t+3]=r[1]},function(n,r,t,i){n[t]=r[0],n[t+1]=r[1],n[t+2]=r[2],n[t+3]=i},function(n,r,t){n[t]=r[0],n[t+1]=r[1],n[t+2]=r[2],n[t+3]=r[3]}];function ff(n,r){let t=[],i=0;function e(){if(i===n.length)throw Error("Ran out of data");let o=n[i];i++;let s,u,c,h,f,g,l,$;switch(r){default:throw Error("unrecognised depth");case 16:l=n[i],i++,t.push((o<<8)+l);break;case 4:l=o&15,$=o>>4,t.push($,l);break;case 2:f=o&3,g=o>>2&3,l=o>>4&3,$=o>>6&3,t.push($,l,g,f);break;case 1:s=o&1,u=o>>1&1,c=o>>2&1,h=o>>3&1,f=o>>4&1,g=o>>5&1,l=o>>6&1,$=o>>7&1,t.push($,l,g,f,h,c,u,s);break}}return{get:function(o){while(t.length<o)e();let s=t.slice(0,o);return t=t.slice(o),s},resetAfterLine:function(){t.length=0},end:function(){if(i!==n.length)throw Error("extra data found")}}}function gf(n,r,t,i,e,o){let{width:s,height:u,index:c}=n;for(let h=0;h<u;h++)for(let f=0;f<s;f++){let g=t(f,h,c);cf[i](r,e,g,o),o+=i}return o}function lf(n,r,t,i,e,o){let{width:s,height:u,index:c}=n;for(let h=0;h<u;h++){for(let f=0;f<s;f++){let g=e.get(i),l=t(f,h,c);hf[i](r,g,l,o)}e.resetAfterLine()}}mf.dataToBitMap=function(n,r){let{width:t,height:i,depth:e,bpp:o,interlace:s}=r,u;if(e!==8)u=ff(n,e);let c;if(e<=8)c=Buffer.alloc(t*i*4);else c=new Uint16Array(t*i*4);let h=Math.pow(2,e)-1,f=0,g,l;if(s)g=Xo.getImagePasses(t,i),l=Xo.getInterlaceIterator(t,i);else{let $=0;l=function(){let a=$;return $+=4,a},g=[{width:t,height:i}]}for(let $=0;$<g.length;$++)if(e===8)f=gf(g[$],c,l,o,n,f);else lf(g[$],c,l,o,u,h);if(e===8){if(f!==n.length)throw Error("extra data found")}else u.end();return c}});var Ri=an((Jd,Vo)=>{function $f(n,r,t,i,e){let o=0;for(let s=0;s<i;s++)for(let u=0;u<t;u++){let c=e[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 af(n,r,t,i,e){let o=0;for(let s=0;s<i;s++)for(let u=0;u<t;u++){let c=!1;if(e.length===1){if(e[0]===n[o])c=!0}else if(e[0]===n[o]&&e[1]===n[o+1]&&e[2]===n[o+2])c=!0;if(c)for(let h=0;h<4;h++)r[o+h]=0;o+=4}}function bf(n,r,t,i,e){let o=255,s=Math.pow(2,e)-1,u=0;for(let c=0;c<i;c++)for(let h=0;h<t;h++){for(let f=0;f<4;f++)r[u+f]=Math.floor(n[u+f]*o/s+0.5);u+=4}}Vo.exports=function(n,r,t=!1){let{depth:i,width:e,height:o,colorType:s,transColor:u,palette:c}=r,h=n;if(s===3)$f(n,h,e,o,c);else{if(u)af(n,h,e,o,u);if(i!==8&&!t){if(i===16)h=Buffer.alloc(e*o*4);bf(n,h,e,o,i)}}return h}});var Po=an((Kd,zo)=>{var wf=Gn("util"),Oi=Gn("zlib"),Yo=Ii(),Ef=Lo(),kf=Ji(),Mf=Ki(),Ff=Ri(),nr=zo.exports=function(n){Yo.call(this),this._parser=new kf(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()};wf.inherits(nr,Yo);nr.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};nr.prototype._inflateData=function(n){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=Oi.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 t=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,i=Math.max(t,Oi.Z_MIN_CHUNK);this._inflate=Oi.createInflate({chunkSize:i});let e=t,o=this.emit.bind(this,"error");this._inflate.on("error",function(u){if(!e)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(!e)return;if(u.length>e)u=u.slice(0,e);e-=u.length,s(u)}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(n)};nr.prototype._handleMetaData=function(n){this._metaData=n,this._bitmapInfo=Object.create(n),this._filter=new Ef(this._bitmapInfo)};nr.prototype._handleTransColor=function(n){this._bitmapInfo.transColor=n};nr.prototype._handlePalette=function(n){this._bitmapInfo.palette=n};nr.prototype._simpleTransparency=function(){this._metaData.alpha=!0};nr.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};nr.prototype._finished=function(){if(this.errord)return;if(!this._inflate)this.emit("error","No Inflate block");else this._inflate.end()};nr.prototype._complete=function(n){if(this.errord)return;let r;try{let t=Mf.dataToBitMap(n,this._bitmapInfo);r=Ff(t,this._bitmapInfo,this._options.skipRescale),t=null}catch(t){this._handleError(t);return}this.emit("parsed",r)}});var Co=an((Rd,Ao)=>{var Wn=Rr();Ao.exports=function(n,r,t,i){let e=[Wn.COLORTYPE_COLOR_ALPHA,Wn.COLORTYPE_ALPHA].indexOf(i.colorType)!==-1;if(i.colorType===i.inputColorType){let a=function(){let w=new ArrayBuffer(2);return new DataView(w).setInt16(0,256,!0),new Int16Array(w)[0]!==256}();if(i.bitDepth===8||i.bitDepth===16&&a)return n}let o=i.bitDepth!==16?n:new Uint16Array(n.buffer),s=255,u=Wn.COLORTYPE_TO_BPP_MAP[i.inputColorType];if(u===4&&!i.inputHasAlpha)u=3;let c=Wn.COLORTYPE_TO_BPP_MAP[i.colorType];if(i.bitDepth===16)s=65535,c*=2;let h=Buffer.alloc(r*t*c),f=0,g=0,l=i.bgColor||{};if(l.red===void 0)l.red=s;if(l.green===void 0)l.green=s;if(l.blue===void 0)l.blue=s;function $(){let a,w,F,H=s;switch(i.inputColorType){case Wn.COLORTYPE_COLOR_ALPHA:H=o[f+3],a=o[f],w=o[f+1],F=o[f+2];break;case Wn.COLORTYPE_COLOR:a=o[f],w=o[f+1],F=o[f+2];break;case Wn.COLORTYPE_ALPHA:H=o[f+1],a=o[f],w=a,F=a;break;case Wn.COLORTYPE_GRAYSCALE:a=o[f],w=a,F=a;break;default:throw Error("input color type:"+i.inputColorType+" is not supported at present")}if(i.inputHasAlpha){if(!e)H/=s,a=Math.min(Math.max(Math.round((1-H)*l.red+H*a),0),s),w=Math.min(Math.max(Math.round((1-H)*l.green+H*w),0),s),F=Math.min(Math.max(Math.round((1-H)*l.blue+H*F),0),s)}return{red:a,green:w,blue:F,alpha:H}}for(let a=0;a<t;a++)for(let w=0;w<r;w++){let F=$(o,f);switch(i.colorType){case Wn.COLORTYPE_COLOR_ALPHA:case Wn.COLORTYPE_COLOR:if(i.bitDepth===8){if(h[g]=F.red,h[g+1]=F.green,h[g+2]=F.blue,e)h[g+3]=F.alpha}else if(h.writeUInt16BE(F.red,g),h.writeUInt16BE(F.green,g+2),h.writeUInt16BE(F.blue,g+4),e)h.writeUInt16BE(F.alpha,g+6);break;case Wn.COLORTYPE_ALPHA:case Wn.COLORTYPE_GRAYSCALE:{let H=(F.red+F.green+F.blue)/3;if(i.bitDepth===8){if(h[g]=H,e)h[g+1]=F.alpha}else if(h.writeUInt16BE(H,g),e)h.writeUInt16BE(F.alpha,g+2);break}default:throw Error("unrecognised color Type "+i.colorType)}f+=u,g+=c}return h}});var Bo=an((Od,_o)=>{var To=Hi();function vf(n,r,t,i,e){for(let o=0;o<t;o++)i[e+o]=n[r+o]}function If(n,r,t){let i=0,e=r+t;for(let o=r;o<e;o++)i+=Math.abs(n[o]);return i}function Nf(n,r,t,i,e,o){for(let s=0;s<t;s++){let u=s>=o?n[r+s-o]:0,c=n[r+s]-u;i[e+s]=c}}function Hf(n,r,t,i){let e=0;for(let o=0;o<t;o++){let s=o>=i?n[r+o-i]:0,u=n[r+o]-s;e+=Math.abs(u)}return e}function Sf(n,r,t,i,e){for(let o=0;o<t;o++){let s=r>0?n[r+o-t]:0,u=n[r+o]-s;i[e+o]=u}}function jf(n,r,t){let i=0,e=r+t;for(let o=r;o<e;o++){let s=r>0?n[o-t]:0,u=n[o]-s;i+=Math.abs(u)}return i}function pf(n,r,t,i,e,o){for(let s=0;s<t;s++){let u=s>=o?n[r+s-o]:0,c=r>0?n[r+s-t]:0,h=n[r+s]-(u+c>>1);i[e+s]=h}}function Gf(n,r,t,i){let e=0;for(let o=0;o<t;o++){let s=o>=i?n[r+o-i]:0,u=r>0?n[r+o-t]:0,c=n[r+o]-(s+u>>1);e+=Math.abs(c)}return e}function Jf(n,r,t,i,e,o){for(let s=0;s<t;s++){let u=s>=o?n[r+s-o]:0,c=r>0?n[r+s-t]:0,h=r>0&&s>=o?n[r+s-(t+o)]:0,f=n[r+s]-To(u,c,h);i[e+s]=f}}function Kf(n,r,t,i){let e=0;for(let o=0;o<t;o++){let s=o>=i?n[r+o-i]:0,u=r>0?n[r+o-t]:0,c=r>0&&o>=i?n[r+o-(t+i)]:0,h=n[r+o]-To(s,u,c);e+=Math.abs(h)}return e}var Rf={0:vf,1:Nf,2:Sf,3:pf,4:Jf},Of={0:If,1:Hf,2:jf,3:Gf,4:Kf};_o.exports=function(n,r,t,i,e){let o;if(!("filterType"in i)||i.filterType===-1)o=[0,1,2,3,4];else if(typeof i.filterType==="number")o=[i.filterType];else throw Error("unrecognised filter types");if(i.bitDepth===16)e*=2;let s=r*e,u=0,c=0,h=Buffer.alloc((s+1)*t),f=o[0];for(let g=0;g<t;g++){if(o.length>1){let l=1/0;for(let $=0;$<o.length;$++){let a=Of[o[$]](n,c,s,e);if(a<l)f=o[$],l=a}}h[u]=f,u++,Rf[f](n,c,s,h,u,e),u+=s,c+=s}return h}});var Qi=an((Qd,xo)=>{var Jn=Rr(),Qf=Gi(),yf=Co(),Zf=Bo(),Lf=Gn("zlib"),gr=xo.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||Lf.createDeflate,n.bitDepth=n.bitDepth||8,n.colorType=typeof n.colorType==="number"?n.colorType:Jn.COLORTYPE_COLOR_ALPHA,n.inputColorType=typeof n.inputColorType==="number"?n.inputColorType:Jn.COLORTYPE_COLOR_ALPHA,[Jn.COLORTYPE_GRAYSCALE,Jn.COLORTYPE_COLOR,Jn.COLORTYPE_COLOR_ALPHA,Jn.COLORTYPE_ALPHA].indexOf(n.colorType)===-1)throw Error("option color type:"+n.colorType+" is not supported at present");if([Jn.COLORTYPE_GRAYSCALE,Jn.COLORTYPE_COLOR,Jn.COLORTYPE_COLOR_ALPHA,Jn.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")};gr.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};gr.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};gr.prototype.filterData=function(n,r,t){let i=yf(n,r,t,this._options),e=Jn.COLORTYPE_TO_BPP_MAP[this._options.colorType];return Zf(i,r,t,this._options,e)};gr.prototype._packChunk=function(n,r){let t=r?r.length:0,i=Buffer.alloc(t+12);if(i.writeUInt32BE(t,0),i.writeUInt32BE(n,4),r)r.copy(i,8);return i.writeInt32BE(Qf.crc32(i.slice(4,i.length-4)),i.length-4),i};gr.prototype.packGAMA=function(n){let r=Buffer.alloc(4);return r.writeUInt32BE(Math.floor(n*Jn.GAMMA_DIVISION),0),this._packChunk(Jn.TYPE_gAMA,r)};gr.prototype.packIHDR=function(n,r){let t=Buffer.alloc(13);return t.writeUInt32BE(n,0),t.writeUInt32BE(r,4),t[8]=this._options.bitDepth,t[9]=this._options.colorType,t[10]=0,t[11]=0,t[12]=0,this._packChunk(Jn.TYPE_IHDR,t)};gr.prototype.packIDAT=function(n){return this._packChunk(Jn.TYPE_IDAT,n)};gr.prototype.packIEND=function(){return this._packChunk(Jn.TYPE_IEND,null)}});var ts=an((yd,rs)=>{var Uf=Gn("util"),Do=Gn("stream"),qf=Rr(),Wf=Qi(),ns=rs.exports=function(n){Do.call(this);let r=n||{};this._packer=new Wf(r),this._deflate=this._packer.createDeflate(),this.readable=!0};Uf.inherits(ns,Do);ns.prototype.pack=function(n,r,t,i){if(this.emit("data",Buffer.from(qf.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(r,t)),i)this.emit("data",this._packer.packGAMA(i));let e=this._packer.filterData(n,r,t);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(e)}});var cs=an((ut,us)=>{var is=Gn("assert").ok,Or=Gn("zlib"),Xf=Gn("util"),es=Gn("buffer").kMaxLength;function wr(n){if(!(this instanceof wr))return new wr(n);if(n&&n.chunkSize<Or.Z_MIN_CHUNK)n.chunkSize=Or.Z_MIN_CHUNK;if(Or.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 Vf(n){return new wr(n)}function os(n,r){if(r)process.nextTick(r);if(!n._handle)return;n._handle.close(),n._handle=null}wr.prototype._processChunk=function(n,r,t){if(typeof t==="function")return Or.Inflate._processChunk.call(this,n,r,t);let i=this,e=n&&n.length,o=this._chunkSize-this._offset,s=this._maxLength,u=0,c=[],h=0,f;this.on("error",function(a){f=a});function g(a,w){if(i._hadError)return;let F=o-w;if(is(F>=0,"have should not go down"),F>0){let H=i._buffer.slice(i._offset,i._offset+F);if(i._offset+=F,H.length>s)H=H.slice(0,s);if(c.push(H),h+=H.length,s-=H.length,s===0)return!1}if(w===0||i._offset>=i._chunkSize)o=i._chunkSize,i._offset=0,i._buffer=Buffer.allocUnsafe(i._chunkSize);if(w===0)return u+=e-a,e=a,!0;return!1}is(this._handle,"zlib binding closed");let l;do l=this._handle.writeSync(r,n,u,e,this._buffer,this._offset,o),l=l||this._writeState;while(!this._hadError&&g(l[0],l[1]));if(this._hadError)throw f;if(h>=es)throw os(this),RangeError("Cannot create final Buffer. It would be larger than 0x"+es.toString(16)+" bytes");let $=Buffer.concat(c,h);return os(this),$};Xf.inherits(wr,Or.Inflate);function Yf(n,r){if(typeof r==="string")r=Buffer.from(r);if(!(r instanceof Buffer))throw TypeError("Not a string or buffer");let t=n._finishFlushFlag;if(t==null)t=Or.Z_FINISH;return n._processChunk(r,t)}function ss(n,r){return Yf(new wr(r),n)}us.exports=ut=ss;ut.Inflate=wr;ut.createInflate=Vf;ut.inflateSync=ss});var yi=an((Zd,fs)=>{var hs=fs.exports=function(n){this._buffer=n,this._reads=[]};hs.prototype.read=function(n,r){this._reads.push({length:Math.abs(n),allowLess:n<0,func:r})};hs.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 gs=an((Af)=>{var zf=yi(),Pf=Si();Af.process=function(n,r){let t=[],i=new zf(n);return new Pf(r,{read:i.read.bind(i),write:function(o){t.push(o)},complete:function(){}}).start(),i.process(),Buffer.concat(t)}});var $s=an((Ud,ds)=>{var ls=!0,ms=Gn("zlib"),Tf=cs();if(!ms.deflateSync)ls=!1;var _f=yi(),Bf=gs(),xf=Ji(),Df=Ki(),ng=Ri();ds.exports=function(n,r){if(!ls)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let t;function i(I){t=I}let e;function o(I){e=I}function s(I){e.transColor=I}function u(I){e.palette=I}function c(){e.alpha=!0}let h;function f(I){h=I}let g=[];function l(I){g.push(I)}let $=new _f(n);if(new xf(r,{read:$.read.bind($),error:i,metadata:o,gamma:f,palette:u,transColor:s,inflateData:l,simpleTransparency:c}).start(),$.process(),t)throw t;let w=Buffer.concat(g);g.length=0;let F;if(e.interlace)F=ms.inflateSync(w);else{let b=((e.width*e.bpp*e.depth+7>>3)+1)*e.height;F=Tf(w,{chunkSize:b,maxLength:b})}if(w=null,!F||!F.length)throw Error("bad png - invalid inflate data response");let H=Bf.process(F,e);w=null;let J=Df.dataToBitMap(H,e);H=null;let M=ng(J,e,r.skipRescale);return e.data=M,e.gamma=h||0,e}});var Es=an((qd,ws)=>{var as=!0,bs=Gn("zlib");if(!bs.deflateSync)as=!1;var rg=Rr(),tg=Qi();ws.exports=function(n,r){if(!as)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let i=new tg(r||{}),e=[];if(e.push(Buffer.from(rg.PNG_SIGNATURE)),e.push(i.packIHDR(n.width,n.height)),n.gamma)e.push(i.packGAMA(n.gamma));let o=i.filterData(n.data,n.width,n.height),s=bs.deflateSync(o,i.getDeflateOptions());if(o=null,!s||!s.length)throw Error("bad png - invalid compressed data response");return e.push(i.packIDAT(s)),e.push(i.packIEND()),Buffer.concat(e)}});var ks=an((og)=>{var ig=$s(),eg=Es();og.read=function(n,r){return ig(n,r||{})};og.write=function(n,r){return eg(n,r)}});var Fs=an((lg)=>{var cg=Gn("util"),Ms=Gn("stream"),hg=Po(),fg=ts(),gg=ks(),Kn=lg.PNG=function(n){if(Ms.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 hg(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 fg(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(Kn,Ms);Kn.sync=gg;Kn.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};Kn.prototype.parse=function(n,r){if(r){let t,i;t=function(e){this.removeListener("error",i),this.data=e,r(null,this)}.bind(this),i=function(e){this.removeListener("parsed",t),r(e,null)}.bind(this),this.once("parsed",t),this.once("error",i)}return this.end(n),this};Kn.prototype.write=function(n){return this._parser.write(n),!0};Kn.prototype.end=function(n){this._parser.end(n)};Kn.prototype._metadata=function(n){this.width=n.width,this.height=n.height,this.emit("metadata",n)};Kn.prototype._gamma=function(n){this.gamma=n};Kn.prototype._handleClose=function(){if(!this._parser.writable&&!this._packer.readable)this.emit("close")};Kn.bitblt=function(n,r,t,i,e,o,s,u){if(t|=0,i|=0,e|=0,o|=0,s|=0,u|=0,t>n.width||i>n.height||t+e>n.width||i+o>n.height)throw Error("bitblt reading outside image");if(s>r.width||u>r.height||s+e>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,(i+c)*n.width+t<<2,(i+c)*n.width+t+e<<2)};Kn.prototype.bitblt=function(n,r,t,i,e,o,s){return Kn.bitblt(this,n,r,t,i,e,o,s),this};Kn.adjustGamma=function(n){if(n.gamma){for(let r=0;r<n.height;r++)for(let t=0;t<n.width;t++){let i=n.width*r+t<<2;for(let e=0;e<3;e++){let o=n.data[i+e]/255;o=Math.pow(o,0.45454545454545453/n.gamma),n.data[i+e]=Math.round(o*255)}}n.gamma=0}};Kn.prototype.adjustGamma=function(){Kn.adjustGamma(this)}});var be=an((ea,bc)=>{var ae={to(n,r){if(!r)return`\x1B[${n+1}G`;return`\x1B[${r+1};${n+1}H`},move(n,r){let t="";if(n<0)t+=`\x1B[${-n}D`;else if(n>0)t+=`\x1B[${n}C`;if(r<0)t+=`\x1B[${-r}A`;else if(r>0)t+=`\x1B[${r}B`;return t},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"},N0={up:(n=1)=>"\x1B[S".repeat(n),down:(n=1)=>"\x1B[T".repeat(n)},H0={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 t=0;t<n;t++)r+=this.line+(t<n-1?ae.up():"");if(n)r+=ae.left;return r}};bc.exports={cursor:ae,scroll:N0,erase:H0,beep:"\x07"}});import{isMainThread as jm}from"node:worker_threads";import{parseArgs as Nm}from"node:util";var Dn={name:"@kecan0406/ttheme",version:"1.0.0",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 Mo}from"node:fs";import{basename as zh,join as st}from"node:path";var Sh=/^#[0-9a-f]{6}$/;function _e(n){return Sh.test(n)}function Qn(n){let r=Number.parseInt(n.slice(1),16);return[r>>16&255,r>>8&255,r&255]}function ir(n){let[r,t,i]=Qn(n).map((e)=>{let o=e/255;return o<=0.03928?o/12.92:((o+0.055)/1.055)**2.4});return 0.2126*r+0.7152*t+0.0722*i}function ar(n,r){let t=ir(n),i=ir(r);return(Math.max(t,i)+0.05)/(Math.min(t,i)+0.05)}function ui(n,r){return Math.round(ar(n,r)*100)/100}var Dr=7,Be=3,ci=0.15,xe=1.6,De=[1,2,3,4,5,6,9,10,11,12,13,14],no=[7,15];function nt(n,r){let t=n.ansi[r];if(t===void 0)throw Error(`${n.name}: missing ANSI ${r}`);return t}function hi(n,r,t){let i=n.background;return r.flatMap((e)=>{let o=nt(n,e);return ar(o,i)<t?[`ANSI ${e} ${o} on ${i} is ${ui(o,i)}:1, needs ${t}:1`]:[]})}function ro(n,r){return Math.min(...r.map((t)=>ar(nt(n,t),n.background)))}var Ht=[{rule:"foreground",label:"foreground on background",unit:"ratio",min:Dr,measure:({foreground:n,background:r})=>ar(n,r),check:({foreground:n,background:r})=>ar(n,r)<Dr?[`foreground ${n} on ${r} is ${ui(n,r)}:1, needs ${Dr}:1`]:[]},{rule:"accents",label:"weakest accent on background",unit:"ratio",min:Be,measure:(n)=>ro(n,De),check:(n)=>hi(n,De,Be)},{rule:"ansi0-dark",label:"ansi0 luminance",unit:"luminance",max:ci,measure:(n)=>ir(nt(n,0)),check:(n)=>{let r=nt(n,0);return ir(r)>ci?[`ANSI 0 ${r} has luminance ${ir(r).toFixed(3)}, needs <= ${ci}`]:[]}},{rule:"light-ansi",label:"ansi7 and ansi15 on background",unit:"ratio",min:Dr,measure:(n)=>ro(n,no),check:(n)=>hi(n,no,Dr)},{rule:"ansi8-visible",label:"ansi8 on background",unit:"ratio",min:xe,measure:(n)=>ar(nt(n,8),n.background),check:(n)=>hi(n,[8],xe)}],Om=Ht.map((n)=>n.rule),St=Ht.map(({rule:n,label:r,unit:t,min:i,max:e})=>({rule:n,label:r,unit:t,...i===void 0?{}:{min:i},...e===void 0?{}:{max:e}}));function to(n){return Ht.map((r)=>Math.round(r.measure(n)*1000)/1000)}function fi(n){return Ht.filter((r)=>!n.waive.includes(r.rule)).flatMap((r)=>r.check(n).map((t)=>({theme:n.name,rule:r.rule,detail:t})))}function io(n){return n.flatMap(fi)}var jh=["black","red","green","yellow","blue","magenta","cyan","white"];function eo(n,r){return[n,...jh.map((t,i)=>`${t} = '${r[i]}'`),""].join(`
3
- `)}var rt={id:"alacritty",limits:"no shaders, no runtime color API (OSC only)",emit(n){let r=[...Gr(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}'`,"",eo("[colors.normal]",n.ansi.slice(0,8)),eo("[colors.bright]",n.ansi.slice(8,16))].join(`
2
+ import{createRequire as qh}from"node:module";var Rh=Object.create;var{getPrototypeOf:yh,defineProperty:io,getOwnPropertyNames:Oh}=Object;var Lh=Object.prototype.hasOwnProperty;function Qh(n){return this[n]}var Zh,Uh,Jt=(n,r,t)=>{var e=n!=null&&typeof n==="object";if(e){var i=r?Zh??=new WeakMap:Uh??=new WeakMap,o=i.get(n);if(o)return o}t=n!=null?Rh(yh(n)):{};let s=r||!n||!n.__esModule?io(t,"default",{value:n,enumerable:!0}):t;for(let u of Oh(n))if(!Lh.call(s,u))io(s,u,{get:Qh.bind(n,u),enumerable:!0});if(e)i.set(n,s);return s};var an=(n,r)=>()=>(r||n((r={exports:{}}).exports,r),r.exports);var Gn=qh(import.meta.url);var Oo=an((L0,Ut)=>{var yo=yo||function(n){return Buffer.from(n).toString("base64")};function gf(n){var r=this,t=Math.round,e=Math.floor,i=Array(64),o=Array(64),s=Array(64),u=Array(64),c,h,f,g,l=Array(65535),$=Array(65535),a=Array(64),w=Array(64),F=[],v=0,j=7,M=Array(64),p=Array(64),b=Array(64),K=Array(256),E=Array(2048),J,S=[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],O=[0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0],R=[0,1,2,3,4,5,6,7,8,9,10,11],A=[0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,125],Z=[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],vn=[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],B=[0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,119],kn=[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(m){var y=[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 q=0;q<64;q++){var Q=e((y[q]*m+50)/100);if(Q<1)Q=1;else if(Q>255)Q=255;i[S[q]]=Q}var Y=[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 P=0;P<64;P++){var en=e((Y[P]*m+50)/100);if(en<1)en=1;else if(en>255)en=255;o[S[P]]=en}var on=[1,1.387039845,1.306562965,1.175875602,1,0.785694958,0.5411961,0.275899379],In=0;for(var $n=0;$n<8;$n++)for(var I=0;I<8;I++)s[In]=1/(i[S[In]]*on[$n]*on[I]*8),u[In]=1/(o[S[In]]*on[$n]*on[I]*8),In++}function x(m,y){var q=0,Q=0,Y=[];for(var P=1;P<=16;P++){for(var en=1;en<=m[P];en++)Y[y[Q]]=[],Y[y[Q]][0]=q,Y[y[Q]][1]=P,Q++,q++;q*=2}return Y}function pn(){c=x(O,R),h=x(vn,U),f=x(A,Z),g=x(B,kn)}function sn(){var m=1,y=2;for(var q=1;q<=15;q++){for(var Q=m;Q<y;Q++)$[32767+Q]=q,l[32767+Q]=[],l[32767+Q][1]=q,l[32767+Q][0]=Q;for(var Y=-(y-1);Y<=-m;Y++)$[32767+Y]=q,l[32767+Y]=[],l[32767+Y][1]=q,l[32767+Y][0]=y-1+Y;m<<=1,y<<=1}}function nn(){for(var m=0;m<256;m++)E[m]=19595*m,E[m+256>>0]=38470*m,E[m+512>>0]=7471*m+32768,E[m+768>>0]=-11059*m,E[m+1024>>0]=-21709*m,E[m+1280>>0]=32768*m+8421375,E[m+1536>>0]=-27439*m,E[m+1792>>0]=-5329*m}function C(m){var y=m[0],q=m[1]-1;while(q>=0){if(y&1<<q)v|=1<<j;if(q--,j--,j<0){if(v==255)d(255),d(0);else d(v);j=7,v=0}}}function d(m){F.push(m)}function L(m){d(m>>8&255),d(m&255)}function hn(m,y){var q,Q,Y,P,en,on,In,$n,I=0,G,V=8,Mn=64;for(G=0;G<V;++G){q=m[I],Q=m[I+1],Y=m[I+2],P=m[I+3],en=m[I+4],on=m[I+5],In=m[I+6],$n=m[I+7];var z=q+$n,D=q-$n,gn=Q+In,W=Q-In,un=Y+on,jn=Y-on,En=P+en,qn=P-en,xn=z+En,ar=z-En,Hr=gn+un,Sr=gn-un;m[I]=xn+Hr,m[I+4]=xn-Hr;var Cr=(Sr+ar)*0.707106781;m[I+2]=ar+Cr,m[I+6]=ar-Cr,xn=qn+jn,Hr=jn+W,Sr=W+D;var Tr=(xn-Sr)*0.382683433,Ht=0.5411961*xn+Tr,_r=1.306562965*Sr+Tr,Br=Hr*0.707106781,xr=D+Br,Dr=D-Br;m[I+5]=Dr+Ht,m[I+3]=Dr-Ht,m[I+1]=xr+_r,m[I+7]=xr-_r,I+=8}I=0;for(G=0;G<V;++G){q=m[I],Q=m[I+8],Y=m[I+16],P=m[I+24],en=m[I+32],on=m[I+40],In=m[I+48],$n=m[I+56];var Pi=q+$n,me=q-$n,zi=Q+In,Ai=Q-In,Ci=Y+on,Ti=Y-on,_i=P+en,Kh=P-en,nt=Pi+_i,de=Pi-_i,St=zi+Ci,jt=zi-Ci;m[I]=nt+St,m[I+32]=nt-St;var Bi=(jt+de)*0.707106781;m[I+16]=de+Bi,m[I+48]=de-Bi,nt=Kh+Ti,St=Ti+Ai,jt=Ai+me;var xi=(nt-jt)*0.382683433,Di=0.5411961*nt+xi,no=1.306562965*jt+xi,ro=St*0.707106781,to=me+ro,eo=me-ro;m[I+40]=eo+Di,m[I+24]=eo-Di,m[I+8]=to+no,m[I+56]=to-no,I++}var Gt;for(G=0;G<Mn;++G)Gt=m[G]*y[G],a[G]=Gt>0?Gt+0.5|0:Gt-0.5|0;return a}function fn(){L(65504),L(16),d(74),d(70),d(73),d(70),d(0),d(1),d(1),d(0),L(1),L(1),d(0),d(0)}function rn(m){if(!m)return;if(L(65505),m[0]===69&&m[1]===120&&m[2]===105&&m[3]===102)L(m.length+2);else L(m.length+5+2),d(69),d(120),d(105),d(102),d(0);for(var y=0;y<m.length;y++)d(m[y])}function tn(m,y){L(65472),L(17),d(8),L(y),L(m),d(3),d(1),d(17),d(0),d(2),d(17),d(1),d(3),d(17),d(1)}function T(){L(65499),L(132),d(0);for(var m=0;m<64;m++)d(i[m]);d(1);for(var y=0;y<64;y++)d(o[y])}function H(){L(65476),L(418),d(0);for(var m=0;m<16;m++)d(O[m+1]);for(var y=0;y<=11;y++)d(R[y]);d(16);for(var q=0;q<16;q++)d(A[q+1]);for(var Q=0;Q<=161;Q++)d(Z[Q]);d(1);for(var Y=0;Y<16;Y++)d(vn[Y+1]);for(var P=0;P<=11;P++)d(U[P]);d(17);for(var en=0;en<16;en++)d(B[en+1]);for(var on=0;on<=161;on++)d(kn[on])}function N(m){if(typeof m>"u"||m.constructor!==Array)return;m.forEach((y)=>{if(typeof y!=="string")return;L(65534);var q=y.length;L(q+2);var Q;for(Q=0;Q<q;Q++)d(y.charCodeAt(Q))})}function dn(){L(65498),L(12),d(3),d(1),d(0),d(2),d(17),d(3),d(17),d(0),d(63),d(0)}function X(m,y,q,Q,Y){var P=Y[0],en=Y[240],on,In=16,$n=63,I=64,G=hn(m,y);for(var V=0;V<I;++V)w[S[V]]=G[V];var Mn=w[0]-q;if(q=w[0],Mn==0)C(Q[0]);else on=32767+Mn,C(Q[$[on]]),C(l[on]);var z=63;for(;z>0&&w[z]==0;z--);if(z==0)return C(P),q;var D=1,gn;while(D<=z){var W=D;for(;w[D]==0&&D<=z;++D);var un=D-W;if(un>=In){gn=un>>4;for(var jn=1;jn<=gn;++jn)C(en);un=un&15}on=32767+w[D],C(Y[(un<<4)+$[on]]),C(l[on]),D++}if(z!=$n)C(P);return q}function _(){var m=String.fromCharCode;for(var y=0;y<256;y++)K[y]=m(y)}this.encode=function(m,y){var q=new Date().getTime();if(y)Un(y);F=[],v=0,j=7,L(65496),fn(),N(m.comments),rn(m.exifBuffer),T(),tn(m.width,m.height),H(),dn();var Q=0,Y=0,P=0;v=0,j=7,this.encode.displayName="_encode_";var{data:en,width:on,height:In}=m,$n=on*4,I=on*3,G,V=0,Mn,z,D,gn,W,un,jn,En;while(V<In){G=0;while(G<$n){gn=$n*V+G,W=gn,un=-1,jn=0;for(En=0;En<64;En++){if(jn=En>>3,un=(En&7)*4,W=gn+jn*$n+un,V+jn>=In)W-=$n*(V+1+jn-In);if(G+un>=$n)W-=G+un-$n+4;Mn=en[W++],z=en[W++],D=en[W++],M[En]=(E[Mn]+E[z+256>>0]+E[D+512>>0]>>16)-128,p[En]=(E[Mn+768>>0]+E[z+1024>>0]+E[D+1280>>0]>>16)-128,b[En]=(E[Mn+1280>>0]+E[z+1536>>0]+E[D+1792>>0]>>16)-128}Q=X(M,s,Q,c,f),Y=X(p,u,Y,h,g),P=X(b,u,P,h,g),G+=32}V+=8}if(j>=0){var qn=[];qn[1]=j+1,qn[0]=(1<<j+1)-1,C(qn)}if(L(65497),typeof Ut>"u")return new Uint8Array(F);return Buffer.from(F);var xn,ar};function Un(m){if(m<=0)m=1;if(m>100)m=100;if(J==m)return;var y=0;if(m<50)y=Math.floor(5000/m);else y=Math.floor(200-m*2);mn(y),J=m}function An(){var m=new Date().getTime();if(!n)n=50;_(),pn(),sn(),nn(),Un(n);var y=new Date().getTime()-m}An()}if(typeof Ut<"u")Ut.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 t=new gf(r),e=t.encode(n,r);return{data:e,width:n.width,height:n.height}}});var Qo=an((Q0,Je)=>{var Ge=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]),t=4017,e=799,i=3406,o=2276,s=1567,u=3784,c=5793,h=2896;function f(){}function g(j,M){var p=0,b=[],K,E,J=16;while(J>0&&!j[J-1])J--;b.push({children:[],index:0});var S=b[0],O;for(K=0;K<J;K++){for(E=0;E<j[K];E++){S=b.pop(),S.children[S.index]=M[p];while(S.index>0){if(b.length===0)throw Error("Could not recreate Huffman Table");S=b.pop()}S.index++,b.push(S);while(b.length<=K)b.push(O={children:[],index:0}),S.children[S.index]=O.children,S=O;p++}if(K+1<J)b.push(O={children:[],index:0}),S.children[S.index]=O.children,S=O}return b[0].children}function l(j,M,p,b,K,E,J,S,O,R){var{precision:A,samplesPerLine:Z,scanLines:vn,mcusPerLine:U,progressive:B,maxH:kn,maxV:mn}=p,x=M,pn=0,sn=0;function nn(){if(sn>0)return sn--,pn>>sn&1;if(pn=j[M++],pn==255){var I=j[M++];if(I)throw Error("unexpected marker: "+(pn<<8|I).toString(16))}return sn=7,pn>>>7}function C(I){var G=I,V;while((V=nn())!==null){if(G=G[V],typeof G==="number")return G;if(typeof G!=="object")throw Error("invalid huffman sequence")}return null}function d(I){var G=0;while(I>0){var V=nn();if(V===null)return;G=G<<1|V,I--}return G}function L(I){var G=d(I);if(G>=1<<I-1)return G;return G+(-1<<I)+1}function hn(I,G){var V=C(I.huffmanTableDC),Mn=V===0?0:L(V);G[0]=I.pred+=Mn;var z=1;while(z<64){var D=C(I.huffmanTableAC),gn=D&15,W=D>>4;if(gn===0){if(W<15)break;z+=16;continue}z+=W;var un=r[z];G[un]=L(gn),z++}}function fn(I,G){var V=C(I.huffmanTableDC),Mn=V===0?0:L(V)<<O;G[0]=I.pred+=Mn}function rn(I,G){G[0]|=nn()<<O}var tn=0;function T(I,G){if(tn>0){tn--;return}var V=E,Mn=J;while(V<=Mn){var z=C(I.huffmanTableAC),D=z&15,gn=z>>4;if(D===0){if(gn<15){tn=d(gn)+(1<<gn)-1;break}V+=16;continue}V+=gn;var W=r[V];G[W]=L(D)*(1<<O),V++}}var H=0,N;function dn(I,G){var V=E,Mn=J,z=0;while(V<=Mn){var D=r[V],gn=G[D]<0?-1:1;switch(H){case 0:var W=C(I.huffmanTableAC),un=W&15,z=W>>4;if(un===0)if(z<15)tn=d(z)+(1<<z),H=4;else z=16,H=1;else{if(un!==1)throw Error("invalid ACn encoding");N=L(un),H=z?2:3}continue;case 1:case 2:if(G[D])G[D]+=(nn()<<O)*gn;else if(z--,z===0)H=H==2?3:0;break;case 3:if(G[D])G[D]+=(nn()<<O)*gn;else G[D]=N<<O,H=0;break;case 4:if(G[D])G[D]+=(nn()<<O)*gn;break}V++}if(H===4){if(tn--,tn===0)H=0}}function X(I,G,V,Mn,z){var D=V/U|0,gn=V%U,W=D*I.v+Mn,un=gn*I.h+z;if(I.blocks[W]===void 0&&R.tolerantDecoding)return;G(I,I.blocks[W][un])}function _(I,G,V){var Mn=V/I.blocksPerLine|0,z=V%I.blocksPerLine;if(I.blocks[Mn]===void 0&&R.tolerantDecoding)return;G(I,I.blocks[Mn][z])}var Un=b.length,An,m,y,q,Q,Y;if(B)if(E===0)Y=S===0?fn:rn;else Y=S===0?T:dn;else Y=hn;var P=0,en,on;if(Un==1)on=b[0].blocksPerLine*b[0].blocksPerColumn;else on=U*p.mcusPerColumn;if(!K)K=on;var In,$n;while(P<on){for(m=0;m<Un;m++)b[m].pred=0;if(tn=0,Un==1){An=b[0];for(Q=0;Q<K;Q++)_(An,Y,P),P++}else for(Q=0;Q<K;Q++){for(m=0;m<Un;m++){An=b[m],In=An.h,$n=An.v;for(y=0;y<$n;y++)for(q=0;q<In;q++)X(An,Y,P,y,q)}if(P++,P===on)break}if(P===on)do{if(j[M]===255){if(j[M+1]!==0)break}M+=1}while(M<j.length-2);if(sn=0,en=j[M]<<8|j[M+1],en<65280)throw Error("marker was not found");if(en>=65488&&en<=65495)M+=2;else break}return M-x}function $(j,M){var p=[],b=M.blocksPerLine,K=M.blocksPerColumn,E=b<<3,J=new Int32Array(64),S=new Uint8Array(64);function O(x,pn,sn){var nn=M.quantizationTable,C,d,L,hn,fn,rn,tn,T,H,N=sn,dn;for(dn=0;dn<64;dn++)N[dn]=x[dn]*nn[dn];for(dn=0;dn<8;++dn){var X=8*dn;if(N[1+X]==0&&N[2+X]==0&&N[3+X]==0&&N[4+X]==0&&N[5+X]==0&&N[6+X]==0&&N[7+X]==0){H=c*N[0+X]+512>>10,N[0+X]=H,N[1+X]=H,N[2+X]=H,N[3+X]=H,N[4+X]=H,N[5+X]=H,N[6+X]=H,N[7+X]=H;continue}C=c*N[0+X]+128>>8,d=c*N[4+X]+128>>8,L=N[2+X],hn=N[6+X],fn=h*(N[1+X]-N[7+X])+128>>8,T=h*(N[1+X]+N[7+X])+128>>8,rn=N[3+X]<<4,tn=N[5+X]<<4,H=C-d+1>>1,C=C+d+1>>1,d=H,H=L*u+hn*s+128>>8,L=L*s-hn*u+128>>8,hn=H,H=fn-tn+1>>1,fn=fn+tn+1>>1,tn=H,H=T+rn+1>>1,rn=T-rn+1>>1,T=H,H=C-hn+1>>1,C=C+hn+1>>1,hn=H,H=d-L+1>>1,d=d+L+1>>1,L=H,H=fn*o+T*i+2048>>12,fn=fn*i-T*o+2048>>12,T=H,H=rn*e+tn*t+2048>>12,rn=rn*t-tn*e+2048>>12,tn=H,N[0+X]=C+T,N[7+X]=C-T,N[1+X]=d+tn,N[6+X]=d-tn,N[2+X]=L+rn,N[5+X]=L-rn,N[3+X]=hn+fn,N[4+X]=hn-fn}for(dn=0;dn<8;++dn){var _=dn;if(N[8+_]==0&&N[16+_]==0&&N[24+_]==0&&N[32+_]==0&&N[40+_]==0&&N[48+_]==0&&N[56+_]==0){H=c*sn[dn+0]+8192>>14,N[0+_]=H,N[8+_]=H,N[16+_]=H,N[24+_]=H,N[32+_]=H,N[40+_]=H,N[48+_]=H,N[56+_]=H;continue}C=c*N[0+_]+2048>>12,d=c*N[32+_]+2048>>12,L=N[16+_],hn=N[48+_],fn=h*(N[8+_]-N[56+_])+2048>>12,T=h*(N[8+_]+N[56+_])+2048>>12,rn=N[24+_],tn=N[40+_],H=C-d+1>>1,C=C+d+1>>1,d=H,H=L*u+hn*s+2048>>12,L=L*s-hn*u+2048>>12,hn=H,H=fn-tn+1>>1,fn=fn+tn+1>>1,tn=H,H=T+rn+1>>1,rn=T-rn+1>>1,T=H,H=C-hn+1>>1,C=C+hn+1>>1,hn=H,H=d-L+1>>1,d=d+L+1>>1,L=H,H=fn*o+T*i+2048>>12,fn=fn*i-T*o+2048>>12,T=H,H=rn*e+tn*t+2048>>12,rn=rn*t-tn*e+2048>>12,tn=H,N[0+_]=C+T,N[56+_]=C-T,N[8+_]=d+tn,N[48+_]=d-tn,N[16+_]=L+rn,N[40+_]=L-rn,N[24+_]=hn+fn,N[32+_]=hn-fn}for(dn=0;dn<64;++dn){var Un=128+(N[dn]+8>>4);pn[dn]=Un<0?0:Un>255?255:Un}}v(E*K*8);var R,A;for(var Z=0;Z<K;Z++){var vn=Z<<3;for(R=0;R<8;R++)p.push(new Uint8Array(E));for(var U=0;U<b;U++){O(M.blocks[Z][U],S,J);var B=0,kn=U<<3;for(A=0;A<8;A++){var mn=p[vn+A];for(R=0;R<8;R++)mn[kn+R]=S[B++]}}}return p}function a(j){return j<0?0:j>255?255:j}f.prototype={load:function(M){var p=new XMLHttpRequest;p.open("GET",M,!0),p.responseType="arraybuffer",p.onload=function(){var b=new Uint8Array(p.response||p.mozResponseArrayBuffer);if(this.parse(b),this.onload)this.onload()}.bind(this),p.send(null)},parse:function(M){var p=this.opts.maxResolutionInMP*1000*1000,b=0,K=M.length;function E(){var W=M[b]<<8|M[b+1];return b+=2,W}function J(){var W=E(),un=M.subarray(b,b+W-2);return b+=un.length,un}function S(W){var un=1,jn=1,En,qn;for(qn in W.components)if(W.components.hasOwnProperty(qn)){if(En=W.components[qn],un<En.h)un=En.h;if(jn<En.v)jn=En.v}var xn=Math.ceil(W.samplesPerLine/8/un),ar=Math.ceil(W.scanLines/8/jn);for(qn in W.components)if(W.components.hasOwnProperty(qn)){En=W.components[qn];var Hr=Math.ceil(Math.ceil(W.samplesPerLine/8)*En.h/un),Sr=Math.ceil(Math.ceil(W.scanLines/8)*En.v/jn),Cr=xn*En.h,Tr=ar*En.v,Ht=Tr*Cr,_r=[];v(Ht*256);for(var Br=0;Br<Tr;Br++){var xr=[];for(var Dr=0;Dr<Cr;Dr++)xr.push(new Int32Array(64));_r.push(xr)}En.blocksPerLine=Hr,En.blocksPerColumn=Sr,En.blocks=_r}W.maxH=un,W.maxV=jn,W.mcusPerLine=xn,W.mcusPerColumn=ar}var O=null,R=null,A=null,Z,vn,U=[],B=[],kn=[],mn=[],x=E(),pn=-1;if(this.comments=[],x!=65496)throw Error("SOI not found");x=E();while(x!=65497){var sn,nn,C;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 d=J();if(x===65534){var L=String.fromCharCode.apply(null,d);this.comments.push(L)}if(x===65504){if(d[0]===74&&d[1]===70&&d[2]===73&&d[3]===70&&d[4]===0)O={version:{major:d[5],minor:d[6]},densityUnits:d[7],xDensity:d[8]<<8|d[9],yDensity:d[10]<<8|d[11],thumbWidth:d[12],thumbHeight:d[13],thumbData:d.subarray(14,14+3*d[12]*d[13])}}if(x===65505){if(d[0]===69&&d[1]===120&&d[2]===105&&d[3]===102&&d[4]===0)this.exifBuffer=d.subarray(5,d.length)}if(x===65518){if(d[0]===65&&d[1]===100&&d[2]===111&&d[3]===98&&d[4]===101&&d[5]===0)R={version:d[6],flags0:d[7]<<8|d[8],flags1:d[9]<<8|d[10],transformCode:d[11]}}break;case 65499:var hn=E(),fn=hn+b-2;while(b<fn){var rn=M[b++];v(256);var tn=new Int32Array(64);if(rn>>4===0)for(nn=0;nn<64;nn++){var T=r[nn];tn[T]=M[b++]}else if(rn>>4===1)for(nn=0;nn<64;nn++){var T=r[nn];tn[T]=E()}else throw Error("DQT: invalid table spec");U[rn&15]=tn}break;case 65472:case 65473:case 65474:E(),Z={},Z.extended=x===65473,Z.progressive=x===65474,Z.precision=M[b++],Z.scanLines=E(),Z.samplesPerLine=E(),Z.components={},Z.componentsOrder=[];var H=Z.scanLines*Z.samplesPerLine;if(H>p){var N=Math.ceil((H-p)/1e6);throw Error(`maxResolutionInMP limit exceeded by ${N}MP`)}var dn=M[b++],X,_=0,Un=0;for(sn=0;sn<dn;sn++){X=M[b];var An=M[b+1]>>4,m=M[b+1]&15,y=M[b+2];if(An<=0||m<=0)throw Error("Invalid sampling factor, expected values above 0");Z.componentsOrder.push(X),Z.components[X]={h:An,v:m,quantizationIdx:y},b+=3}S(Z),B.push(Z);break;case 65476:var q=E();for(sn=2;sn<q;){var Q=M[b++],Y=new Uint8Array(16),P=0;for(nn=0;nn<16;nn++,b++)P+=Y[nn]=M[b];v(16+P);var en=new Uint8Array(P);for(nn=0;nn<P;nn++,b++)en[nn]=M[b];sn+=17+P,(Q>>4===0?mn:kn)[Q&15]=g(Y,en)}break;case 65501:E(),vn=E();break;case 65500:E(),E();break;case 65498:var on=E(),In=M[b++],$n=[],I;for(sn=0;sn<In;sn++){I=Z.components[M[b++]];var G=M[b++];I.huffmanTableDC=mn[G>>4],I.huffmanTableAC=kn[G&15],$n.push(I)}var V=M[b++],Mn=M[b++],z=M[b++],D=l(M,b,Z,$n,vn,V,Mn,z>>4,z&15,this.opts);b+=D;break;case 65535:if(M[b]!==255)b--;break;default:if(M[b-3]==255&&M[b-2]>=192&&M[b-2]<=254){b-=3;break}else if(x===224||x==225){if(pn!==-1)throw Error(`first unknown JPEG marker at offset ${pn.toString(16)}, second unknown JPEG marker ${x.toString(16)} at offset ${(b-1).toString(16)}`);pn=b-1;let W=E();if(M[b+W-2]===255){b+=W-2;break}}throw Error("unknown JPEG marker "+x.toString(16))}x=E()}if(B.length!=1)throw Error("only single frame JPEGs supported");for(var sn=0;sn<B.length;sn++){var gn=B[sn].components;for(var nn in gn)gn[nn].quantizationTable=U[gn[nn].quantizationIdx],delete gn[nn].quantizationIdx}this.width=Z.samplesPerLine,this.height=Z.scanLines,this.jfif=O,this.adobe=R,this.components=[];for(var sn=0;sn<Z.componentsOrder.length;sn++){var I=Z.components[Z.componentsOrder[sn]];this.components.push({lines:$(Z,I),scaleX:I.h/Z.maxH,scaleY:I.v/Z.maxV})}},getData:function(M,p){var b=this.width/M,K=this.height/p,E,J,S,O,R,A,Z,vn,U,B,kn=0,mn,x,pn,sn,nn,C,d,L,hn,fn,rn,tn=M*p*this.components.length;v(tn);var T=new Uint8Array(tn);switch(this.components.length){case 1:E=this.components[0];for(B=0;B<p;B++){R=E.lines[0|B*E.scaleY*K];for(U=0;U<M;U++)mn=R[0|U*E.scaleX*b],T[kn++]=mn}break;case 2:E=this.components[0],J=this.components[1];for(B=0;B<p;B++){R=E.lines[0|B*E.scaleY*K],A=J.lines[0|B*J.scaleY*K];for(U=0;U<M;U++)mn=R[0|U*E.scaleX*b],T[kn++]=mn,mn=A[0|U*J.scaleX*b],T[kn++]=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;E=this.components[0],J=this.components[1],S=this.components[2];for(B=0;B<p;B++){R=E.lines[0|B*E.scaleY*K],A=J.lines[0|B*J.scaleY*K],Z=S.lines[0|B*S.scaleY*K];for(U=0;U<M;U++){if(!rn)L=R[0|U*E.scaleX*b],hn=A[0|U*J.scaleX*b],fn=Z[0|U*S.scaleX*b];else mn=R[0|U*E.scaleX*b],x=A[0|U*J.scaleX*b],pn=Z[0|U*S.scaleX*b],L=a(mn+1.402*(pn-128)),hn=a(mn-0.3441363*(x-128)-0.71413636*(pn-128)),fn=a(mn+1.772*(x-128));T[kn++]=L,T[kn++]=hn,T[kn++]=fn}}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;E=this.components[0],J=this.components[1],S=this.components[2],O=this.components[3];for(B=0;B<p;B++){R=E.lines[0|B*E.scaleY*K],A=J.lines[0|B*J.scaleY*K],Z=S.lines[0|B*S.scaleY*K],vn=O.lines[0|B*O.scaleY*K];for(U=0;U<M;U++){if(!rn)nn=R[0|U*E.scaleX*b],C=A[0|U*J.scaleX*b],d=Z[0|U*S.scaleX*b],sn=vn[0|U*O.scaleX*b];else mn=R[0|U*E.scaleX*b],x=A[0|U*J.scaleX*b],pn=Z[0|U*S.scaleX*b],sn=vn[0|U*O.scaleX*b],nn=255-a(mn+1.402*(pn-128)),C=255-a(mn-0.3441363*(x-128)-0.71413636*(pn-128)),d=255-a(mn+1.772*(x-128));T[kn++]=255-nn,T[kn++]=255-C,T[kn++]=255-d,T[kn++]=255-sn}}break;default:throw Error("Unsupported color mode")}return T},copyToImageData:function(M,p){var{width:b,height:K,data:E}=M,J=this.getData(b,K),S=0,O=0,R,A,Z,vn,U,B,kn,mn,x;switch(this.components.length){case 1:for(A=0;A<K;A++)for(R=0;R<b;R++)if(Z=J[S++],E[O++]=Z,E[O++]=Z,E[O++]=Z,p)E[O++]=255;break;case 3:for(A=0;A<K;A++)for(R=0;R<b;R++)if(kn=J[S++],mn=J[S++],x=J[S++],E[O++]=kn,E[O++]=mn,E[O++]=x,p)E[O++]=255;break;case 4:for(A=0;A<K;A++)for(R=0;R<b;R++)if(U=J[S++],B=J[S++],Z=J[S++],vn=J[S++],kn=255-a(U*(1-vn/255)+vn),mn=255-a(B*(1-vn/255)+vn),x=255-a(Z*(1-vn/255)+vn),E[O++]=kn,E[O++]=mn,E[O++]=x,p)E[O++]=255;break;default:throw Error("Unsupported color mode")}}};var w=0,F=0;function v(j=0){var M=w+j;if(M>F){var p=Math.ceil((M-F)/1024/1024);throw Error(`maxMemoryUsageInMB limit exceeded by at least ${p}MB`)}w=M}return f.resetMaxMemoryUsage=function(j){w=0,F=j},f.getBytesAllocated=function(){return w},f.requestMemoryAllocation=v,f}();if(typeof Je<"u")Je.exports=Lo;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].decode=Lo;function Lo(n,r={}){var t={colorTransform:void 0,useTArray:!1,formatAsRGBA:!0,tolerantDecoding:!0,maxResolutionInMP:100,maxMemoryUsageInMB:512},e={...t,...r},i=new Uint8Array(n),o=new Ge;o.opts=e,Ge.resetMaxMemoryUsage(e.maxMemoryUsageInMB*1024*1024),o.parse(i);var s=e.formatAsRGBA?4:3,u=o.width*o.height*s;try{Ge.requestMemoryAllocation(u);var c={width:o.width,height:o.height,exifBuffer:o.exifBuffer,data:e.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,e.formatAsRGBA),c}});var Uo=an((Z0,Zo)=>{var lf=Oo(),mf=Qo();Zo.exports={encode:lf,decode:mf}});var Ke=an((U0,Wo)=>{var df=Gn("util"),qo=Gn("stream"),Cn=Wo.exports=function(){qo.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};df.inherits(Cn,qo);Cn.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))};Cn.prototype.write=function(n,r){if(!this.writable)return this.emit("error",Error("Stream not writable")),!1;let t;if(Buffer.isBuffer(n))t=n;else t=Buffer.from(n,r||this._encoding);if(this._buffers.push(t),this._buffered+=t.length,this._process(),this._reads&&this._reads.length===0)this._paused=!0;return this.writable&&!this._paused};Cn.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()};Cn.prototype.destroySoon=Cn.prototype.end;Cn.prototype._end=function(){if(this._reads.length>0)this.emit("error",Error("Unexpected end of input"));this.destroy()};Cn.prototype.destroy=function(){if(!this._buffers)return;this.writable=!1,this._reads=null,this._buffers=null,this.emit("close")};Cn.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)};Cn.prototype._processRead=function(n){this._reads.shift();let r=0,t=0,e=Buffer.alloc(n.length);while(r<n.length){let i=this._buffers[t++],o=Math.min(i.length,n.length-r);if(i.copy(e,r,0,o),r+=o,o!==i.length)this._buffers[--t]=i.slice(o)}if(t>0)this._buffers.splice(0,t);this._buffered-=n.length,n.func.call(this,e)};Cn.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 Re=an(($f)=>{var gr=[{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]}];$f.getImagePasses=function(n,r){let t=[],e=n%8,i=r%8,o=(n-e)/8,s=(r-i)/8;for(let u=0;u<gr.length;u++){let c=gr[u],h=o*c.x.length,f=s*c.y.length;for(let g=0;g<c.x.length;g++)if(c.x[g]<e)h++;else break;for(let g=0;g<c.y.length;g++)if(c.y[g]<i)f++;else break;if(h>0&&f>0)t.push({width:h,height:f,index:u})}return t};$f.getInterlaceIterator=function(n){return function(r,t,e){let i=r%gr[e].x.length,o=(r-i)/gr[e].x.length*8+gr[e].x[i],s=t%gr[e].y.length,u=(t-s)/gr[e].y.length*8+gr[e].y[s];return o*4+u*n*4}}});var ye=an((W0,Xo)=>{Xo.exports=function(r,t,e){let i=r+t-e,o=Math.abs(i-r),s=Math.abs(i-t),u=Math.abs(i-e);if(o<=s&&o<=u)return r;if(s<=u)return t;return e}});var Oe=an((X0,Yo)=>{var wf=Re(),Ef=ye();function Vo(n,r,t){let e=n*r;if(t!==8)e=Math.ceil(e/(8/t));return e}var Jr=Yo.exports=function(n,r){let{width:t,height:e,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=wf.getImagePasses(t,e);for(let c=0;c<u.length;c++)this._images.push({byteWidth:Vo(u[c].width,o,s),height:u[c].height,lineIndex:0})}else this._images.push({byteWidth:Vo(t,o,s),height:e,lineIndex:0});if(s===8)this._xComparison=o;else if(s===16)this._xComparison=o*2;else this._xComparison=1};Jr.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Jr.prototype._unFilterType1=function(n,r,t){let e=this._xComparison,i=e-1;for(let o=0;o<t;o++){let s=n[1+o],u=o>i?r[o-e]:0;r[o]=s+u}};Jr.prototype._unFilterType2=function(n,r,t){let e=this._lastLine;for(let i=0;i<t;i++){let o=n[1+i],s=e?e[i]:0;r[i]=o+s}};Jr.prototype._unFilterType3=function(n,r,t){let e=this._xComparison,i=e-1,o=this._lastLine;for(let s=0;s<t;s++){let u=n[1+s],c=o?o[s]:0,h=s>i?r[s-e]:0,f=Math.floor((h+c)/2);r[s]=u+f}};Jr.prototype._unFilterType4=function(n,r,t){let e=this._xComparison,i=e-1,o=this._lastLine;for(let s=0;s<t;s++){let u=n[1+s],c=o?o[s]:0,h=s>i?r[s-e]:0,f=s>i&&o?o[s-e]:0,g=Ef(h,c,f);r[s]=u+g}};Jr.prototype._reverseFilterLine=function(n){let r=n[0],t,e=this._images[this._imageIndex],i=e.byteWidth;if(r===0)t=n.slice(1,i+1);else switch(t=Buffer.alloc(i),r){case 1:this._unFilterType1(n,t,i);break;case 2:this._unFilterType2(n,t,i);break;case 3:this._unFilterType3(n,t,i);break;case 4:this._unFilterType4(n,t,i);break;default:throw Error("Unrecognised filter type - "+r)}if(this.write(t),e.lineIndex++,e.lineIndex>=e.height)this._lastLine=null,this._imageIndex++,e=this._images[this._imageIndex];else this._lastLine=t;if(e)this.read(e.byteWidth+1,this._reverseFilterLine.bind(this));else this._lastLine=null,this.complete()}});var Ao=an((V0,zo)=>{var kf=Gn("util"),Po=Ke(),Mf=Oe(),Ff=zo.exports=function(n){Po.call(this);let r=[],t=this;this._filter=new Mf(n,{read:this.read.bind(this),write:function(e){r.push(e)},complete:function(){t.emit("complete",Buffer.concat(r))}}),this._filter.start()};kf.inherits(Ff,Po)});var Kr=an((Y0,Co)=>{Co.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 Ze=an((P0,To)=>{var Le=[];(function(){for(let n=0;n<256;n++){let r=n;for(let t=0;t<8;t++)if(r&1)r=3988292384^r>>>1;else r=r>>>1;Le[n]=r}})();var Qe=To.exports=function(){this._crc=-1};Qe.prototype.write=function(n){for(let r=0;r<n.length;r++)this._crc=Le[(this._crc^n[r])&255]^this._crc>>>8;return!0};Qe.prototype.crc32=function(){return this._crc^-1};Qe.crc32=function(n){let r=-1;for(let t=0;t<n.length;t++)r=Le[(r^n[t])&255]^r>>>8;return r^-1}});var Ue=an((z0,_o)=>{var Hn=Kr(),If=Ze(),Sn=_o.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(){}};Sn.prototype.start=function(){this.read(Hn.PNG_SIGNATURE.length,this._parseSignature.bind(this))};Sn.prototype._parseSignature=function(n){let r=Hn.PNG_SIGNATURE;for(let t=0;t<r.length;t++)if(n[t]!==r[t]){this.error(Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};Sn.prototype._parseChunkBegin=function(n){let r=n.readUInt32BE(0),t=n.readUInt32BE(4),e="";for(let o=4;o<8;o++)e+=String.fromCharCode(n[o]);let i=Boolean(n[4]&32);if(!this._hasIHDR&&t!==Hn.TYPE_IHDR){this.error(Error("Expected IHDR on beggining"));return}if(this._crc=new If,this._crc.write(Buffer.from(e)),this._chunks[t])return this._chunks[t](r);if(!i){this.error(Error("Unsupported critical chunk type "+e));return}this.read(r+4,this._skipChunk.bind(this))};Sn.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};Sn.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};Sn.prototype._parseChunkEnd=function(n){let r=n.readInt32BE(0),t=this._crc.crc32();if(this._options.checkCRC&&t!==r){this.error(Error("Crc error - "+r+" - "+t));return}if(!this._hasIEND)this.read(8,this._parseChunkBegin.bind(this))};Sn.prototype._handleIHDR=function(n){this.read(n,this._parseIHDR.bind(this))};Sn.prototype._parseIHDR=function(n){this._crc.write(n);let r=n.readUInt32BE(0),t=n.readUInt32BE(4),e=n[8],i=n[9],o=n[10],s=n[11],u=n[12];if(e!==8&&e!==4&&e!==2&&e!==1&&e!==16){this.error(Error("Unsupported bit depth "+e));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:t,depth:e,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()};Sn.prototype._handlePLTE=function(n){this.read(n,this._parsePLTE.bind(this))};Sn.prototype._parsePLTE=function(n){this._crc.write(n);let r=Math.floor(n.length/3);for(let t=0;t<r;t++)this._palette.push([n[t*3],n[t*3+1],n[t*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};Sn.prototype._handleTRNS=function(n){this.simpleTransparency(),this.read(n,this._parseTRNS.bind(this))};Sn.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()};Sn.prototype._handleGAMA=function(n){this.read(n,this._parseGAMA.bind(this))};Sn.prototype._parseGAMA=function(n){this._crc.write(n),this.gamma(n.readUInt32BE(0)/Hn.GAMMA_DIVISION),this._handleChunkEnd()};Sn.prototype._handleIDAT=function(n){if(!this._emittedHeadersFinished)this._emittedHeadersFinished=!0,this.headersFinished();this.read(-n,this._parseIDAT.bind(this,n))};Sn.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 t=n-r.length;if(t>0)this._handleIDAT(t);else this._handleChunkEnd()};Sn.prototype._handleIEND=function(n){this.read(n,this._parseIEND.bind(this))};Sn.prototype._parseIEND=function(n){if(this._crc.write(n),this._hasIEND=!0,this._handleChunkEnd(),this.finished)this.finished()}});var qe=an((jf)=>{var Bo=Re(),vf=[function(){},function(n,r,t,e){if(e===r.length)throw Error("Ran out of data");let i=r[e];n[t]=i,n[t+1]=i,n[t+2]=i,n[t+3]=255},function(n,r,t,e){if(e+1>=r.length)throw Error("Ran out of data");let i=r[e];n[t]=i,n[t+1]=i,n[t+2]=i,n[t+3]=r[e+1]},function(n,r,t,e){if(e+2>=r.length)throw Error("Ran out of data");n[t]=r[e],n[t+1]=r[e+1],n[t+2]=r[e+2],n[t+3]=255},function(n,r,t,e){if(e+3>=r.length)throw Error("Ran out of data");n[t]=r[e],n[t+1]=r[e+1],n[t+2]=r[e+2],n[t+3]=r[e+3]}],pf=[function(){},function(n,r,t,e){let i=r[0];n[t]=i,n[t+1]=i,n[t+2]=i,n[t+3]=e},function(n,r,t){let e=r[0];n[t]=e,n[t+1]=e,n[t+2]=e,n[t+3]=r[1]},function(n,r,t,e){n[t]=r[0],n[t+1]=r[1],n[t+2]=r[2],n[t+3]=e},function(n,r,t){n[t]=r[0],n[t+1]=r[1],n[t+2]=r[2],n[t+3]=r[3]}];function Nf(n,r){let t=[],e=0;function i(){if(e===n.length)throw Error("Ran out of data");let o=n[e];e++;let s,u,c,h,f,g,l,$;switch(r){default:throw Error("unrecognised depth");case 16:l=n[e],e++,t.push((o<<8)+l);break;case 4:l=o&15,$=o>>4,t.push($,l);break;case 2:f=o&3,g=o>>2&3,l=o>>4&3,$=o>>6&3,t.push($,l,g,f);break;case 1:s=o&1,u=o>>1&1,c=o>>2&1,h=o>>3&1,f=o>>4&1,g=o>>5&1,l=o>>6&1,$=o>>7&1,t.push($,l,g,f,h,c,u,s);break}}return{get:function(o){while(t.length<o)i();let s=t.slice(0,o);return t=t.slice(o),s},resetAfterLine:function(){t.length=0},end:function(){if(e!==n.length)throw Error("extra data found")}}}function Hf(n,r,t,e,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 g=t(f,h,c);vf[e](r,i,g,o),o+=e}return o}function Sf(n,r,t,e,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 g=i.get(e),l=t(f,h,c);pf[e](r,g,l,o)}i.resetAfterLine()}}jf.dataToBitMap=function(n,r){let{width:t,height:e,depth:i,bpp:o,interlace:s}=r,u;if(i!==8)u=Nf(n,i);let c;if(i<=8)c=Buffer.alloc(t*e*4);else c=new Uint16Array(t*e*4);let h=Math.pow(2,i)-1,f=0,g,l;if(s)g=Bo.getImagePasses(t,e),l=Bo.getInterlaceIterator(t,e);else{let $=0;l=function(){let a=$;return $+=4,a},g=[{width:t,height:e}]}for(let $=0;$<g.length;$++)if(i===8)f=Hf(g[$],c,l,o,n,f);else Sf(g[$],c,l,o,u,h);if(i===8){if(f!==n.length)throw Error("extra data found")}else u.end();return c}});var We=an((C0,xo)=>{function Jf(n,r,t,e,i){let o=0;for(let s=0;s<e;s++)for(let u=0;u<t;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 Kf(n,r,t,e,i){let o=0;for(let s=0;s<e;s++)for(let u=0;u<t;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 Rf(n,r,t,e,i){let o=255,s=Math.pow(2,i)-1,u=0;for(let c=0;c<e;c++)for(let h=0;h<t;h++){for(let f=0;f<4;f++)r[u+f]=Math.floor(n[u+f]*o/s+0.5);u+=4}}xo.exports=function(n,r,t=!1){let{depth:e,width:i,height:o,colorType:s,transColor:u,palette:c}=r,h=n;if(s===3)Jf(n,h,i,o,c);else{if(u)Kf(n,h,i,o,u);if(e!==8&&!t){if(e===16)h=Buffer.alloc(i*o*4);Rf(n,h,i,o,e)}}return h}});var rs=an((T0,ns)=>{var yf=Gn("util"),Xe=Gn("zlib"),Do=Ke(),Of=Ao(),Lf=Ue(),Qf=qe(),Zf=We(),nr=ns.exports=function(n){Do.call(this),this._parser=new Lf(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()};yf.inherits(nr,Do);nr.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};nr.prototype._inflateData=function(n){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=Xe.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 t=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,e=Math.max(t,Xe.Z_MIN_CHUNK);this._inflate=Xe.createInflate({chunkSize:e});let i=t,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)};nr.prototype._handleMetaData=function(n){this._metaData=n,this._bitmapInfo=Object.create(n),this._filter=new Of(this._bitmapInfo)};nr.prototype._handleTransColor=function(n){this._bitmapInfo.transColor=n};nr.prototype._handlePalette=function(n){this._bitmapInfo.palette=n};nr.prototype._simpleTransparency=function(){this._metaData.alpha=!0};nr.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};nr.prototype._finished=function(){if(this.errord)return;if(!this._inflate)this.emit("error","No Inflate block");else this._inflate.end()};nr.prototype._complete=function(n){if(this.errord)return;let r;try{let t=Qf.dataToBitMap(n,this._bitmapInfo);r=Zf(t,this._bitmapInfo,this._options.skipRescale),t=null}catch(t){this._handleError(t);return}this.emit("parsed",r)}});var es=an((_0,ts)=>{var Xn=Kr();ts.exports=function(n,r,t,e){let i=[Xn.COLORTYPE_COLOR_ALPHA,Xn.COLORTYPE_ALPHA].indexOf(e.colorType)!==-1;if(e.colorType===e.inputColorType){let a=function(){let w=new ArrayBuffer(2);return new DataView(w).setInt16(0,256,!0),new Int16Array(w)[0]!==256}();if(e.bitDepth===8||e.bitDepth===16&&a)return n}let o=e.bitDepth!==16?n:new Uint16Array(n.buffer),s=255,u=Xn.COLORTYPE_TO_BPP_MAP[e.inputColorType];if(u===4&&!e.inputHasAlpha)u=3;let c=Xn.COLORTYPE_TO_BPP_MAP[e.colorType];if(e.bitDepth===16)s=65535,c*=2;let h=Buffer.alloc(r*t*c),f=0,g=0,l=e.bgColor||{};if(l.red===void 0)l.red=s;if(l.green===void 0)l.green=s;if(l.blue===void 0)l.blue=s;function $(){let a,w,F,v=s;switch(e.inputColorType){case Xn.COLORTYPE_COLOR_ALPHA:v=o[f+3],a=o[f],w=o[f+1],F=o[f+2];break;case Xn.COLORTYPE_COLOR:a=o[f],w=o[f+1],F=o[f+2];break;case Xn.COLORTYPE_ALPHA:v=o[f+1],a=o[f],w=a,F=a;break;case Xn.COLORTYPE_GRAYSCALE:a=o[f],w=a,F=a;break;default:throw Error("input color type:"+e.inputColorType+" is not supported at present")}if(e.inputHasAlpha){if(!i)v/=s,a=Math.min(Math.max(Math.round((1-v)*l.red+v*a),0),s),w=Math.min(Math.max(Math.round((1-v)*l.green+v*w),0),s),F=Math.min(Math.max(Math.round((1-v)*l.blue+v*F),0),s)}return{red:a,green:w,blue:F,alpha:v}}for(let a=0;a<t;a++)for(let w=0;w<r;w++){let F=$(o,f);switch(e.colorType){case Xn.COLORTYPE_COLOR_ALPHA:case Xn.COLORTYPE_COLOR:if(e.bitDepth===8){if(h[g]=F.red,h[g+1]=F.green,h[g+2]=F.blue,i)h[g+3]=F.alpha}else if(h.writeUInt16BE(F.red,g),h.writeUInt16BE(F.green,g+2),h.writeUInt16BE(F.blue,g+4),i)h.writeUInt16BE(F.alpha,g+6);break;case Xn.COLORTYPE_ALPHA:case Xn.COLORTYPE_GRAYSCALE:{let v=(F.red+F.green+F.blue)/3;if(e.bitDepth===8){if(h[g]=v,i)h[g+1]=F.alpha}else if(h.writeUInt16BE(v,g),i)h.writeUInt16BE(F.alpha,g+2);break}default:throw Error("unrecognised color Type "+e.colorType)}f+=u,g+=c}return h}});var ss=an((B0,os)=>{var is=ye();function Uf(n,r,t,e,i){for(let o=0;o<t;o++)e[i+o]=n[r+o]}function qf(n,r,t){let e=0,i=r+t;for(let o=r;o<i;o++)e+=Math.abs(n[o]);return e}function Wf(n,r,t,e,i,o){for(let s=0;s<t;s++){let u=s>=o?n[r+s-o]:0,c=n[r+s]-u;e[i+s]=c}}function Xf(n,r,t,e){let i=0;for(let o=0;o<t;o++){let s=o>=e?n[r+o-e]:0,u=n[r+o]-s;i+=Math.abs(u)}return i}function Vf(n,r,t,e,i){for(let o=0;o<t;o++){let s=r>0?n[r+o-t]:0,u=n[r+o]-s;e[i+o]=u}}function Yf(n,r,t){let e=0,i=r+t;for(let o=r;o<i;o++){let s=r>0?n[o-t]:0,u=n[o]-s;e+=Math.abs(u)}return e}function Pf(n,r,t,e,i,o){for(let s=0;s<t;s++){let u=s>=o?n[r+s-o]:0,c=r>0?n[r+s-t]:0,h=n[r+s]-(u+c>>1);e[i+s]=h}}function zf(n,r,t,e){let i=0;for(let o=0;o<t;o++){let s=o>=e?n[r+o-e]:0,u=r>0?n[r+o-t]:0,c=n[r+o]-(s+u>>1);i+=Math.abs(c)}return i}function Af(n,r,t,e,i,o){for(let s=0;s<t;s++){let u=s>=o?n[r+s-o]:0,c=r>0?n[r+s-t]:0,h=r>0&&s>=o?n[r+s-(t+o)]:0,f=n[r+s]-is(u,c,h);e[i+s]=f}}function Cf(n,r,t,e){let i=0;for(let o=0;o<t;o++){let s=o>=e?n[r+o-e]:0,u=r>0?n[r+o-t]:0,c=r>0&&o>=e?n[r+o-(t+e)]:0,h=n[r+o]-is(s,u,c);i+=Math.abs(h)}return i}var Tf={0:Uf,1:Wf,2:Vf,3:Pf,4:Af},_f={0:qf,1:Xf,2:Yf,3:zf,4:Cf};os.exports=function(n,r,t,e,i){let o;if(!("filterType"in e)||e.filterType===-1)o=[0,1,2,3,4];else if(typeof e.filterType==="number")o=[e.filterType];else throw Error("unrecognised filter types");if(e.bitDepth===16)i*=2;let s=r*i,u=0,c=0,h=Buffer.alloc((s+1)*t),f=o[0];for(let g=0;g<t;g++){if(o.length>1){let l=1/0;for(let $=0;$<o.length;$++){let a=_f[o[$]](n,c,s,i);if(a<l)f=o[$],l=a}}h[u]=f,u++,Tf[f](n,c,s,h,u,i),u+=s,c+=s}return h}});var Ve=an((x0,us)=>{var Jn=Kr(),Bf=Ze(),xf=es(),Df=ss(),ng=Gn("zlib"),lr=us.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||ng.createDeflate,n.bitDepth=n.bitDepth||8,n.colorType=typeof n.colorType==="number"?n.colorType:Jn.COLORTYPE_COLOR_ALPHA,n.inputColorType=typeof n.inputColorType==="number"?n.inputColorType:Jn.COLORTYPE_COLOR_ALPHA,[Jn.COLORTYPE_GRAYSCALE,Jn.COLORTYPE_COLOR,Jn.COLORTYPE_COLOR_ALPHA,Jn.COLORTYPE_ALPHA].indexOf(n.colorType)===-1)throw Error("option color type:"+n.colorType+" is not supported at present");if([Jn.COLORTYPE_GRAYSCALE,Jn.COLORTYPE_COLOR,Jn.COLORTYPE_COLOR_ALPHA,Jn.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")};lr.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};lr.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};lr.prototype.filterData=function(n,r,t){let e=xf(n,r,t,this._options),i=Jn.COLORTYPE_TO_BPP_MAP[this._options.colorType];return Df(e,r,t,this._options,i)};lr.prototype._packChunk=function(n,r){let t=r?r.length:0,e=Buffer.alloc(t+12);if(e.writeUInt32BE(t,0),e.writeUInt32BE(n,4),r)r.copy(e,8);return e.writeInt32BE(Bf.crc32(e.slice(4,e.length-4)),e.length-4),e};lr.prototype.packGAMA=function(n){let r=Buffer.alloc(4);return r.writeUInt32BE(Math.floor(n*Jn.GAMMA_DIVISION),0),this._packChunk(Jn.TYPE_gAMA,r)};lr.prototype.packIHDR=function(n,r){let t=Buffer.alloc(13);return t.writeUInt32BE(n,0),t.writeUInt32BE(r,4),t[8]=this._options.bitDepth,t[9]=this._options.colorType,t[10]=0,t[11]=0,t[12]=0,this._packChunk(Jn.TYPE_IHDR,t)};lr.prototype.packIDAT=function(n){return this._packChunk(Jn.TYPE_IDAT,n)};lr.prototype.packIEND=function(){return this._packChunk(Jn.TYPE_IEND,null)}});var gs=an((D0,fs)=>{var rg=Gn("util"),cs=Gn("stream"),tg=Kr(),eg=Ve(),hs=fs.exports=function(n){cs.call(this);let r=n||{};this._packer=new eg(r),this._deflate=this._packer.createDeflate(),this.readable=!0};rg.inherits(hs,cs);hs.prototype.pack=function(n,r,t,e){if(this.emit("data",Buffer.from(tg.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(r,t)),e)this.emit("data",this._packer.packGAMA(e));let i=this._packer.filterData(n,r,t);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 bs=an((ht,as)=>{var ls=Gn("assert").ok,Rr=Gn("zlib"),ig=Gn("util"),ms=Gn("buffer").kMaxLength;function Er(n){if(!(this instanceof Er))return new Er(n);if(n&&n.chunkSize<Rr.Z_MIN_CHUNK)n.chunkSize=Rr.Z_MIN_CHUNK;if(Rr.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 Er(n)}function ds(n,r){if(r)process.nextTick(r);if(!n._handle)return;n._handle.close(),n._handle=null}Er.prototype._processChunk=function(n,r,t){if(typeof t==="function")return Rr.Inflate._processChunk.call(this,n,r,t);let e=this,i=n&&n.length,o=this._chunkSize-this._offset,s=this._maxLength,u=0,c=[],h=0,f;this.on("error",function(a){f=a});function g(a,w){if(e._hadError)return;let F=o-w;if(ls(F>=0,"have should not go down"),F>0){let v=e._buffer.slice(e._offset,e._offset+F);if(e._offset+=F,v.length>s)v=v.slice(0,s);if(c.push(v),h+=v.length,s-=v.length,s===0)return!1}if(w===0||e._offset>=e._chunkSize)o=e._chunkSize,e._offset=0,e._buffer=Buffer.allocUnsafe(e._chunkSize);if(w===0)return u+=i-a,i=a,!0;return!1}ls(this._handle,"zlib binding closed");let l;do l=this._handle.writeSync(r,n,u,i,this._buffer,this._offset,o),l=l||this._writeState;while(!this._hadError&&g(l[0],l[1]));if(this._hadError)throw f;if(h>=ms)throw ds(this),RangeError("Cannot create final Buffer. It would be larger than 0x"+ms.toString(16)+" bytes");let $=Buffer.concat(c,h);return ds(this),$};ig.inherits(Er,Rr.Inflate);function sg(n,r){if(typeof r==="string")r=Buffer.from(r);if(!(r instanceof Buffer))throw TypeError("Not a string or buffer");let t=n._finishFlushFlag;if(t==null)t=Rr.Z_FINISH;return n._processChunk(r,t)}function $s(n,r){return sg(new Er(r),n)}as.exports=ht=$s;ht.Inflate=Er;ht.createInflate=og;ht.inflateSync=$s});var Ye=an((n$,Es)=>{var ws=Es.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 ks=an((hg)=>{var ug=Ye(),cg=Oe();hg.process=function(n,r){let t=[],e=new ug(n);return new cg(r,{read:e.read.bind(e),write:function(o){t.push(o)},complete:function(){}}).start(),e.process(),Buffer.concat(t)}});var vs=an((t$,Is)=>{var Ms=!0,Fs=Gn("zlib"),gg=bs();if(!Fs.deflateSync)Ms=!1;var lg=Ye(),mg=ks(),dg=Ue(),$g=qe(),ag=We();Is.exports=function(n,r){if(!Ms)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let t;function e(p){t=p}let i;function o(p){i=p}function s(p){i.transColor=p}function u(p){i.palette=p}function c(){i.alpha=!0}let h;function f(p){h=p}let g=[];function l(p){g.push(p)}let $=new lg(n);if(new dg(r,{read:$.read.bind($),error:e,metadata:o,gamma:f,palette:u,transColor:s,inflateData:l,simpleTransparency:c}).start(),$.process(),t)throw t;let w=Buffer.concat(g);g.length=0;let F;if(i.interlace)F=Fs.inflateSync(w);else{let b=((i.width*i.bpp*i.depth+7>>3)+1)*i.height;F=gg(w,{chunkSize:b,maxLength:b})}if(w=null,!F||!F.length)throw Error("bad png - invalid inflate data response");let v=mg.process(F,i);w=null;let j=$g.dataToBitMap(v,i);v=null;let M=ag(j,i,r.skipRescale);return i.data=M,i.gamma=h||0,i}});var Ss=an((e$,Hs)=>{var ps=!0,Ns=Gn("zlib");if(!Ns.deflateSync)ps=!1;var bg=Kr(),wg=Ve();Hs.exports=function(n,r){if(!ps)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let e=new wg(r||{}),i=[];if(i.push(Buffer.from(bg.PNG_SIGNATURE)),i.push(e.packIHDR(n.width,n.height)),n.gamma)i.push(e.packGAMA(n.gamma));let o=e.filterData(n.data,n.width,n.height),s=Ns.deflateSync(o,e.getDeflateOptions());if(o=null,!s||!s.length)throw Error("bad png - invalid compressed data response");return i.push(e.packIDAT(s)),i.push(e.packIEND()),Buffer.concat(i)}});var js=an((Mg)=>{var Eg=vs(),kg=Ss();Mg.read=function(n,r){return Eg(n,r||{})};Mg.write=function(n,r){return kg(n,r)}});var Js=an((Sg)=>{var vg=Gn("util"),Gs=Gn("stream"),pg=rs(),Ng=gs(),Hg=js(),Kn=Sg.PNG=function(n){if(Gs.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 pg(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 Ng(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"))};vg.inherits(Kn,Gs);Kn.sync=Hg;Kn.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};Kn.prototype.parse=function(n,r){if(r){let t,e;t=function(i){this.removeListener("error",e),this.data=i,r(null,this)}.bind(this),e=function(i){this.removeListener("parsed",t),r(i,null)}.bind(this),this.once("parsed",t),this.once("error",e)}return this.end(n),this};Kn.prototype.write=function(n){return this._parser.write(n),!0};Kn.prototype.end=function(n){this._parser.end(n)};Kn.prototype._metadata=function(n){this.width=n.width,this.height=n.height,this.emit("metadata",n)};Kn.prototype._gamma=function(n){this.gamma=n};Kn.prototype._handleClose=function(){if(!this._parser.writable&&!this._packer.readable)this.emit("close")};Kn.bitblt=function(n,r,t,e,i,o,s,u){if(t|=0,e|=0,i|=0,o|=0,s|=0,u|=0,t>n.width||e>n.height||t+i>n.width||e+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,(e+c)*n.width+t<<2,(e+c)*n.width+t+i<<2)};Kn.prototype.bitblt=function(n,r,t,e,i,o,s){return Kn.bitblt(this,n,r,t,e,i,o,s),this};Kn.adjustGamma=function(n){if(n.gamma){for(let r=0;r<n.height;r++)for(let t=0;t<n.width;t++){let e=n.width*r+t<<2;for(let i=0;i<3;i++){let o=n.data[e+i]/255;o=Math.pow(o,0.45454545454545453/n.gamma),n.data[e+i]=Math.round(o*255)}}n.gamma=0}};Kn.prototype.adjustGamma=function(){Kn.adjustGamma(this)}});var pi=an((va,Kc)=>{var vi={to(n,r){if(!r)return`\x1B[${n+1}G`;return`\x1B[${r+1};${n+1}H`},move(n,r){let t="";if(n<0)t+=`\x1B[${-n}D`;else if(n>0)t+=`\x1B[${n}C`;if(r<0)t+=`\x1B[${-r}A`;else if(r>0)t+=`\x1B[${r}B`;return t},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"},Wm={up:(n=1)=>"\x1B[S".repeat(n),down:(n=1)=>"\x1B[T".repeat(n)},Xm={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 t=0;t<n;t++)r+=this.line+(t<n-1?vi.up():"");if(n)r+=vi.left;return r}};Kc.exports={cursor:vi,scroll:Wm,erase:Xm,beep:"\x07"}});import{isMainThread as Pd}from"node:worker_threads";import{parseArgs as Xd}from"node:util";var Dn={name:"@kecan0406/ttheme",version:"1.0.1",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 Go}from"node:fs";import{basename as cf,join as ct}from"node:path";var Xh=/^#[0-9a-f]{6}$/;function oo(n){return Xh.test(n)}function On(n){let r=Number.parseInt(n.slice(1),16);return[r>>16&255,r>>8&255,r&255]}function er(n){let[r,t,e]=On(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*t+0.0722*e}function br(n,r){let t=er(n),e=er(r);return(Math.max(t,e)+0.05)/(Math.min(t,e)+0.05)}function $e(n,r){return Math.round(br(n,r)*100)/100}var rt=7,so=3,ae=0.15,uo=1.6,co=[1,2,3,4,5,6,9,10,11,12,13,14],ho=[7,15];function tt(n,r){let t=n.ansi[r];if(t===void 0)throw Error(`${n.name}: missing ANSI ${r}`);return t}function be(n,r,t){let e=n.background;return r.flatMap((i)=>{let o=tt(n,i);return br(o,e)<t?[`ANSI ${i} ${o} on ${e} is ${$e(o,e)}:1, needs ${t}:1`]:[]})}function fo(n,r){return Math.min(...r.map((t)=>br(tt(n,t),n.background)))}var Kt=[{rule:"foreground",label:"foreground on background",unit:"ratio",min:rt,measure:({foreground:n,background:r})=>br(n,r),check:({foreground:n,background:r})=>br(n,r)<rt?[`foreground ${n} on ${r} is ${$e(n,r)}:1, needs ${rt}:1`]:[]},{rule:"accents",label:"weakest accent on background",unit:"ratio",min:so,measure:(n)=>fo(n,co),check:(n)=>be(n,co,so)},{rule:"ansi0-dark",label:"ansi0 luminance",unit:"luminance",max:ae,measure:(n)=>er(tt(n,0)),check:(n)=>{let r=tt(n,0);return er(r)>ae?[`ANSI 0 ${r} has luminance ${er(r).toFixed(3)}, needs <= ${ae}`]:[]}},{rule:"light-ansi",label:"ansi7 and ansi15 on background",unit:"ratio",min:rt,measure:(n)=>fo(n,ho),check:(n)=>be(n,ho,rt)},{rule:"ansi8-visible",label:"ansi8 on background",unit:"ratio",min:uo,measure:(n)=>br(tt(n,8),n.background),check:(n)=>be(n,[8],uo)}],Bd=Kt.map((n)=>n.rule),Rt=Kt.map(({rule:n,label:r,unit:t,min:e,max:i})=>({rule:n,label:r,unit:t,...e===void 0?{}:{min:e},...i===void 0?{}:{max:i}}));function go(n){return Kt.map((r)=>Math.round(r.measure(n)*1000)/1000)}function we(n){return Kt.filter((r)=>!n.waive.includes(r.rule)).flatMap((r)=>r.check(n).map((t)=>({theme:n.name,rule:r.rule,detail:t})))}function lo(n){return n.flatMap(we)}var Vh=["black","red","green","yellow","blue","magenta","cyan","white"];function mo(n,r){return[n,...Vh.map((t,e)=>`${t} = '${r[e]}'`),""].join(`
3
+ `)}var et={id:"alacritty",limits:"no shaders, no runtime color API (OSC only)",emit(n){let r=[...jr(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}'`,"",mo("[colors.normal]",n.ansi.slice(0,8)),mo("[colors.bright]",n.ansi.slice(8,16))].join(`
4
4
  `),t=[`# ${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:t}]}};import{isDeepStrictEqual as ph}from"node:util";var tt={id:"ghostty",emit(n){let r=[...Gr(n),`background = ${n.background}`,`foreground = ${n.foreground}`,`cursor-color = ${n.cursor}`,`selection-background = ${n.selectionBackground}`,`selection-foreground = ${n.foreground}`,...n.ansi.map((t,i)=>`palette = ${i}=${t}`),"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 i of n)if(!ph(i.font,r.font)||i.ghostty.shader!==r.ghostty.shader)throw Error(`${i.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((i)=>`font-codepoint-map = ${i.range}=${i.family}`),...r.ghostty.shader?["",`custom-shader = ~/.config/ghostty/shaders/${r.ghostty.shader}`,"custom-shader-animation = true"]:[],""].join(`
7
- `)}]}};function hr(n){let[r,t,i]=Qn(n);return{"Alpha Component":1,"Blue Component":i/255,"Color Space":"P3","Green Component":t/255,"Red Component":r/255}}function oo(n){return{...Object.fromEntries(n.ansi.map((r,t)=>[`Ansi ${t} Color`,hr(r)])),"Background Color":hr(n.background),"Bold Color":hr(n.foreground),"Cursor Color":hr(n.cursor),"Cursor Text Color":hr(n.background),"Foreground Color":hr(n.foreground),"Selected Text Color":hr(n.foreground),"Selection Color":hr(n.selectionBackground)}}function so(n){let r=n.map((t)=>({Name:`ttheme · ${t.name}`,Guid:`ttheme-${t.name}`,"Use Separate Colors for Light and Dark Mode":!1,...oo(t)}));return`${JSON.stringify({Profiles:r},null,2)}
8
- `}function Gh(n,r){return[` <key>${n}</key>`,"\t<dict>",...Object.entries(r).flatMap(([t,i])=>[` <key>${t}</key>`,typeof i==="string"?` <string>${i}</string>`:` <real>${i}</real>`]),"\t</dict>"].join(`
9
- `)}var it={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(([t,i])=>Gh(t,i)),"</dict>","</plist>",""].join(`
10
- `);return[{path:`iterm2/${n.name}.itermcolors`,content:r}]}};var et={id:"kitty",limits:"no GLSL shaders, no per-codepoint font mapping",emit(n){let r=[...Gr(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((i,e)=>`color${e} ${i}`),""].join(`
5
+ `);return[{path:`alacritty/themes/${n.name}.toml`,content:r},{path:`alacritty/config/${n.name}.toml`,content:t}]}};import{isDeepStrictEqual as Yh}from"node:util";var it={id:"ghostty",emit(n){let r=[...jr(n),`background = ${n.background}`,`foreground = ${n.foreground}`,`cursor-color = ${n.cursor}`,`selection-background = ${n.selectionBackground}`,`selection-foreground = ${n.foreground}`,...n.ansi.map((t,e)=>`palette = ${e}=${t}`),"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 e of n)if(!Yh(e.font,r.font)||e.ghostty.shader!==r.ghostty.shader)throw Error(`${e.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((e)=>`font-codepoint-map = ${e.range}=${e.family}`),...r.ghostty.shader?["",`custom-shader = ~/.config/ghostty/shaders/${r.ghostty.shader}`,"custom-shader-animation = true"]:[],""].join(`
7
+ `)}]}};function fr(n){let[r,t,e]=On(n);return{"Alpha Component":1,"Blue Component":e/255,"Color Space":"P3","Green Component":t/255,"Red Component":r/255}}function $o(n){return{...Object.fromEntries(n.ansi.map((r,t)=>[`Ansi ${t} Color`,fr(r)])),"Background Color":fr(n.background),"Bold Color":fr(n.foreground),"Cursor Color":fr(n.cursor),"Cursor Text Color":fr(n.background),"Foreground Color":fr(n.foreground),"Selected Text Color":fr(n.foreground),"Selection Color":fr(n.selectionBackground)}}function Ph(n){return n?{"Background Image Location":n.image,"Background Image Mode":n.cover?2:3,Blend:n.opacity}:{"Background Image Location":""}}function ao(n,r,t,e){let i=(s,u)=>({Name:`ttheme · ${u}`,Guid:`ttheme-${u}`,...e?{"Dynamic Profile Parent GUID":e}:{},"Use Separate Colors for Light and Dark Mode":!1,"Harmonize 256 Colors":!0,...Ph(r.get(s.name)),...$o(s)}),o=[...t?[i(t,"default")]:[],...n.map((s)=>i(s,s.name))];return`${JSON.stringify({Profiles:o},null,2)}
8
+ `}function zh(n,r){return[` <key>${n}</key>`,"\t<dict>",...Object.entries(r).flatMap(([t,e])=>[` <key>${t}</key>`,typeof e==="string"?` <string>${e}</string>`:` <real>${e}</real>`]),"\t</dict>"].join(`
9
+ `)}var ot={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($o(n)).map(([t,e])=>zh(t,e)),"</dict>","</plist>",""].join(`
10
+ `);return[{path:`iterm2/${n.name}.itermcolors`,content:r}]}};var st={id:"kitty",limits:"no GLSL shaders, no per-codepoint font mapping",emit(n){let r=[...jr(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((e,i)=>`color${i} ${e}`),""].join(`
11
11
  `),t=[`# ${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:t}]}};function gi(n){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.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:to(n),...n.waive.length>0?{waived:n.waive}:{}}}function Jr(n){return n.filter((r)=>r.default!==!0)}function Jh(n){let[r]=n;if(!r)throw Error("manifest needs at least one theme");return{version:Dn.version,gate:St,font:r.font,...r.ghostty.shader?{shader:r.ghostty.shader}:{},palettes:n.map(gi)}}var li={id:"meta",emitShared(n){return[{path:"manifest.json",content:`${JSON.stringify(Jh(n),null,2)}
13
- `}]}};import{readdirSync as Kh,readFileSync as mi}from"node:fs";import{basename as Rh,join as di}from"node:path";var Oh="_defaults.toml",er="_groups.toml",uo=3,co=["background","foreground","cursor","selection"],Qh=new Set(["next","help","preview","pin","unpin","config"]);function Hn(n,r){throw Error(`${n}: ${r}`)}function br(n,r,t){if(typeof t!=="string"||!_e(t))Hn(n,`${r} must be "#rrggbb" (lowercase), got ${JSON.stringify(t)}`);return t}function qn(n,r,t){if(typeof t!=="string"||t.length===0)Hn(n,`${r} must be a non-empty string`);return t}function or(n){return n&&typeof n==="object"?n:{}}function yh(n,r,t){let i={...or(t),...or(r)},e=i.codepoint_map??[];if(!Array.isArray(e))Hn(n,"font.codepoint_map must be an array");return{family:qn(n,"font.family",i.family),size:Number(i.size),codepointMap:e.map((o)=>{let s=or(o);return{range:qn(n,"font.codepoint_map[].range",s.range),family:qn(n,"font.codepoint_map[].family",s.family)}})}}function Zh(n,r,t){if(r===void 0)return[t.cursor,t.selectionBackground,t.background];let i=Array.isArray(r)?r:[r];if(i.length===0)Hn(n,"ghostty.icon_screen must not be empty");return i.map((e,o)=>br(n,`ghostty.icon_screen[${o}]`,e))}function Lh(n,r,t,i){let e={...or(t),...or(r)};return{shader:e.shader===void 0?void 0:qn(n,"ghostty.shader",e.shader),iconGhost:e.icon_ghost===void 0?i.cursor:br(n,"ghostty.icon_ghost",e.icon_ghost),iconScreen:Zh(n,e.icon_screen,i)}}function Uh(n){return new Map([...co.map((r)=>[r,n[r]]),...n.ansi.map((r,t)=>[`ansi${t}`,r])])}function qh(n,r,t){if(!Array.isArray(r)||r.length!==uo)Hn(n,`meta.signature must name exactly ${uo} palette slots`);let i=Uh(t),e=[],o=[];for(let[s,u]of r.entries()){let c=`meta.signature[${s}]`,h=qn(n,c,u),f=i.get(h);if(f===void 0)Hn(n,`${c} ${JSON.stringify(u)} is not a palette slot — use ${co.join(", ")} or ansi0-ansi15`);e.push(h),o.push(f)}if(new Set(o).size!==o.length)Hn(n,"meta.signature slots must resolve to three different colors");return{names:e,colors:o}}function Wh(n){let t=Bun.TOML.parse(mi(di(n,er),"utf8")).group;if(!Array.isArray(t)||t.length===0)Hn(er,"needs at least one [[group]] table");return t.map((i)=>{let e=or(i);return{name:qn(er,"group.name",e.name),native:e.native===void 0?void 0:qn(er,"group.native",e.native),lead:qn(er,"group.lead",e.lead)}})}function Xh(n,r,t,i){let e=Bun.TOML.parse(r),o=or(e.meta),s=or(e.colors),u=or(e.contrast),c=s.ansi;if(!Array.isArray(c)||c.length!==16)Hn(n,`colors.ansi must hold exactly 16 colors, got ${Array.isArray(c)?c.length:typeof c}`);let h=qn(n,"meta.name",o.name);if(h!==Rh(n,".toml"))Hn(n,`meta.name "${h}" does not match the filename`);if(Qh.has(h))Hn(n,`meta.name "${h}" collides with a ttheme subcommand`);if(h.startsWith("-"))Hn(n,`meta.name "${h}" would be read as a flag by the ttheme CLI`);let f=o.role;if(f!==void 0&&f!=="default")Hn(n,`meta.role must be "default", got ${JSON.stringify(f)}`);let g=qn(n,"meta.group",o.group),l=i.get(g);if(!l)Hn(n,`meta.group "${g}" has no [[group]] table in ${er}`);let $=br(n,"colors.background",s.background),a=br(n,"colors.foreground",s.foreground),w=br(n,"colors.cursor",s.cursor),F=br(n,"colors.selection_background",s.selection_background),H=c.map((b,K)=>br(n,`colors.ansi[${K}]`,b)),J=qh(n,o.signature,{background:$,foreground:a,cursor:w,selection:F,ansi:H}),M=o.booru===void 0?void 0:qn(n,"meta.booru",o.booru);if(M!==void 0&&/\s/.test(M))Hn(n,`meta.booru must be a single booru tag, got ${JSON.stringify(M)}`);let I=Array.isArray(u.waive)?u.waive.map(String):[];if(I.length>0&&typeof u.reason!=="string")Hn(n,"contrast.waive needs a contrast.reason explaining why");return{name:h,group:g,native:l.native,lead:l.lead===h,order:Number(o.order),role:f,ansiSource:qn(n,"meta.ansi_source",o.ansi_source),...M?{booru:M}:{},background:$,foreground:a,cursor:w,selectionBackground:F,ansi:H,signature:J.colors,signatureSlots:J.names,font:yh(n,e.font,t.font),ghostty:Lh(n,e.ghostty,t.ghostty,{background:$,cursor:w,selectionBackground:F}),waive:I,waiveReason:typeof u.reason==="string"?u.reason:void 0}}function ho(n){let r=Bun.TOML.parse(mi(di(n,Oh),"utf8")),t=Wh(n),i=new Map(t.map((s)=>[s.name,s]));if(i.size!==t.length)Hn(er,"group.name must be unique");let e=Kh(n).filter((s)=>s.endsWith(".toml")&&!s.startsWith("_")).map((s)=>Xh(s,mi(di(n,s),"utf8"),r,i)).sort((s,u)=>s.order-u.order);if(new Set(e.map((s)=>s.order)).size!==e.length)throw Error("themes: meta.order must be unique across all themes");for(let s of t){let u=e.filter((c)=>c.group===s.name);if(u.length===0)Hn(er,`group "${s.name}" has no themes`);if(!u.some((c)=>c.name===s.lead))Hn(er,`group "${s.name}" lead "${s.lead}" is not one of its themes`)}return e}function fo(n){return n.filter((r)=>r.role===void 0)}function ot(n){let r=(t,i)=>t<i?-1:t>i?1:0;return[...n].sort((t,i)=>r(t.group.toLowerCase(),i.group.toLowerCase())||r(t.name,i.name))}var jt=["ghostty","kitty","alacritty","iterm2"];var go=/# ttheme begin\n[\s\S]*?# ttheme end\n?/;function pt(n,r){let t=`# ttheme begin
12
+ `);return[{path:`kitty/themes/${n.name}.conf`,content:r},{path:`kitty/config/${n.name}.conf`,content:t}]}};function Ee(n){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.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:go(n),...n.waive.length>0?{waived:n.waive}:{}}}function Gr(n){return n.filter((r)=>r.default!==!0)}function Ah(n){let[r]=n;if(!r)throw Error("manifest needs at least one theme");return{version:Dn.version,gate:Rt,font:r.font,...r.ghostty.shader?{shader:r.ghostty.shader}:{},palettes:n.map(Ee)}}var ke={id:"meta",emitShared(n){return[{path:"manifest.json",content:`${JSON.stringify(Ah(n),null,2)}
13
+ `}]}};import{readdirSync as Ch,readFileSync as Me}from"node:fs";import{basename as Th,join as Fe}from"node:path";var _h="_defaults.toml",ir="_groups.toml",bo=3,wo=["background","foreground","cursor","selection"],Bh=new Set(["next","help","preview","pin","unpin","config"]);function Nn(n,r){throw Error(`${n}: ${r}`)}function wr(n,r,t){if(typeof t!=="string"||!oo(t))Nn(n,`${r} must be "#rrggbb" (lowercase), got ${JSON.stringify(t)}`);return t}function Wn(n,r,t){if(typeof t!=="string"||t.length===0)Nn(n,`${r} must be a non-empty string`);return t}function or(n){return n&&typeof n==="object"?n:{}}function xh(n,r,t){let e={...or(t),...or(r)},i=e.codepoint_map??[];if(!Array.isArray(i))Nn(n,"font.codepoint_map must be an array");return{family:Wn(n,"font.family",e.family),size:Number(e.size),codepointMap:i.map((o)=>{let s=or(o);return{range:Wn(n,"font.codepoint_map[].range",s.range),family:Wn(n,"font.codepoint_map[].family",s.family)}})}}function Dh(n,r,t){if(r===void 0)return[t.cursor,t.selectionBackground,t.background];let e=Array.isArray(r)?r:[r];if(e.length===0)Nn(n,"ghostty.icon_screen must not be empty");return e.map((i,o)=>wr(n,`ghostty.icon_screen[${o}]`,i))}function nf(n,r,t,e){let i={...or(t),...or(r)};return{shader:i.shader===void 0?void 0:Wn(n,"ghostty.shader",i.shader),iconGhost:i.icon_ghost===void 0?e.cursor:wr(n,"ghostty.icon_ghost",i.icon_ghost),iconScreen:Dh(n,i.icon_screen,e)}}function rf(n){return new Map([...wo.map((r)=>[r,n[r]]),...n.ansi.map((r,t)=>[`ansi${t}`,r])])}function tf(n,r,t){if(!Array.isArray(r)||r.length!==bo)Nn(n,`meta.signature must name exactly ${bo} palette slots`);let e=rf(t),i=[],o=[];for(let[s,u]of r.entries()){let c=`meta.signature[${s}]`,h=Wn(n,c,u),f=e.get(h);if(f===void 0)Nn(n,`${c} ${JSON.stringify(u)} is not a palette slot — use ${wo.join(", ")} or ansi0-ansi15`);i.push(h),o.push(f)}if(new Set(o).size!==o.length)Nn(n,"meta.signature slots must resolve to three different colors");return{names:i,colors:o}}function ef(n){let t=Bun.TOML.parse(Me(Fe(n,ir),"utf8")).group;if(!Array.isArray(t)||t.length===0)Nn(ir,"needs at least one [[group]] table");return t.map((e)=>{let i=or(e);return{name:Wn(ir,"group.name",i.name),native:i.native===void 0?void 0:Wn(ir,"group.native",i.native),lead:Wn(ir,"group.lead",i.lead)}})}function of(n,r,t,e){let i=Bun.TOML.parse(r),o=or(i.meta),s=or(i.colors),u=or(i.contrast),c=s.ansi;if(!Array.isArray(c)||c.length!==16)Nn(n,`colors.ansi must hold exactly 16 colors, got ${Array.isArray(c)?c.length:typeof c}`);let h=Wn(n,"meta.name",o.name);if(h!==Th(n,".toml"))Nn(n,`meta.name "${h}" does not match the filename`);if(Bh.has(h))Nn(n,`meta.name "${h}" collides with a ttheme subcommand`);if(h.startsWith("-"))Nn(n,`meta.name "${h}" would be read as a flag by the ttheme CLI`);let f=o.role;if(f!==void 0&&f!=="default")Nn(n,`meta.role must be "default", got ${JSON.stringify(f)}`);let g=Wn(n,"meta.group",o.group),l=e.get(g);if(!l)Nn(n,`meta.group "${g}" has no [[group]] table in ${ir}`);let $=wr(n,"colors.background",s.background),a=wr(n,"colors.foreground",s.foreground),w=wr(n,"colors.cursor",s.cursor),F=wr(n,"colors.selection_background",s.selection_background),v=c.map((b,K)=>wr(n,`colors.ansi[${K}]`,b)),j=tf(n,o.signature,{background:$,foreground:a,cursor:w,selection:F,ansi:v}),M=o.booru===void 0?void 0:Wn(n,"meta.booru",o.booru);if(M!==void 0&&/\s/.test(M))Nn(n,`meta.booru must be a single booru tag, got ${JSON.stringify(M)}`);let p=Array.isArray(u.waive)?u.waive.map(String):[];if(p.length>0&&typeof u.reason!=="string")Nn(n,"contrast.waive needs a contrast.reason explaining why");return{name:h,group:g,native:l.native,lead:l.lead===h,order:Number(o.order),role:f,ansiSource:Wn(n,"meta.ansi_source",o.ansi_source),...M?{booru:M}:{},background:$,foreground:a,cursor:w,selectionBackground:F,ansi:v,signature:j.colors,signatureSlots:j.names,font:xh(n,i.font,t.font),ghostty:nf(n,i.ghostty,t.ghostty,{background:$,cursor:w,selectionBackground:F}),waive:p,waiveReason:typeof u.reason==="string"?u.reason:void 0}}function Eo(n){let r=Bun.TOML.parse(Me(Fe(n,_h),"utf8")),t=ef(n),e=new Map(t.map((s)=>[s.name,s]));if(e.size!==t.length)Nn(ir,"group.name must be unique");let i=Ch(n).filter((s)=>s.endsWith(".toml")&&!s.startsWith("_")).map((s)=>of(s,Me(Fe(n,s),"utf8"),r,e)).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 t){let u=i.filter((c)=>c.group===s.name);if(u.length===0)Nn(ir,`group "${s.name}" has no themes`);if(!u.some((c)=>c.name===s.lead))Nn(ir,`group "${s.name}" lead "${s.lead}" is not one of its themes`)}return i}function ko(n){return n.filter((r)=>r.role===void 0)}function ut(n){let r=(t,e)=>t<e?-1:t>e?1:0;return[...n].sort((t,e)=>r(t.group.toLowerCase(),e.group.toLowerCase())||r(t.name,e.name))}var yt=["ghostty","kitty","alacritty","iterm2"];var Mo=/# ttheme begin\n[\s\S]*?# ttheme end\n?/;function Ot(n,r){let t=`# ttheme begin
14
14
  ${r}
15
15
  # ttheme end
16
- `;if(go.test(n))return n.replace(go,t);if(n==="")return t;return`${n.replace(/\n*$/,`
16
+ `;if(Mo.test(n))return n.replace(Mo,t);if(n==="")return t;return`${n.replace(/\n*$/,`
17
17
  `)}
18
- ${t}`}function lo(n){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?.startsWith("foot"))return"foot";return"unknown"}function mo(n,r){let t=[`command = ${n}/launch-tab.zsh`,"shell-integration = zsh"];if(r)t.push(`theme = ${r}`);return t.push(`config-file = ${n}/ttheme.conf`,`config-file = ?${n}/backgrounds/shown.conf`),t.join(`
19
- `)}function $o(n){return`source ${n}/ttheme.zsh`}var Vh="# ttheme settings — exported variables win over this file",$i={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_CUTOUTS:{doc:'# the tags find calls a transparent cutout, per site as key=tag,tag pairs — e.g. "safebooru=transparent_background yande=transparent_png,vector" (default the built-in tags)',default:""},TTHEME_FIND_ORDER:{doc:"# the order find lists posts in: newest or score (default newest)",default:"newest"},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 (default 0)",default:"0"},TTHEME_FIND_HOSTS:{doc:'# send a find site somewhere else, as key=https://host pairs — e.g. "konachan=https://konachan.com danbooru=https://danbooru.donmai.us" (default none)',default:""}};function ai(n,r){return`: \${${n}:=${r}}`}function ao(n){return new RegExp(String.raw`^#? ?: \$\{${n}[^\n]*$`,"m")}function Yh(n,r){if(ao(r).test(n))return n;let t=$i[r];return`${n.replace(/\n*$/,`
18
+ ${t}`}function Fo(n){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?.startsWith("foot"))return"foot";return"unknown"}function Io(n,r){let t=[`command = ${n}/launch-tab.zsh`,"shell-integration = zsh"];if(r)t.push(`theme = ${r}`);return t.push(`config-file = ${n}/ttheme.conf`,`config-file = ?${n}/backgrounds/shown.conf`),t.join(`
19
+ `)}function vo(n){return`source ${n}/ttheme.zsh`}var sf="# ttheme settings — exported variables win over this file",Ie={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_CUTOUTS:{doc:'# the tags find calls a transparent cutout, per site as key=tag,tag pairs — e.g. "safebooru=transparent_background yande=transparent_png,vector" (default the built-in tags)',default:""},TTHEME_FIND_ORDER:{doc:"# the order find lists posts in: newest or score (default newest)",default:"newest"},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 (default 0)",default:"0"},TTHEME_FIND_HOSTS:{doc:'# send a find site somewhere else, as key=https://host pairs — e.g. "konachan=https://konachan.com danbooru=https://danbooru.donmai.us" (default none)',default:""}};function ve(n,r){return`: \${${n}:=${r}}`}function po(n){return new RegExp(String.raw`^#? ?: \$\{${n}[^\n]*$`,"m")}function uf(n,r){if(po(r).test(n))return n;let t=Ie[r];return`${n.replace(/\n*$/,`
20
20
  `)}
21
21
  ${t.doc}
22
- ${ai(r,t.default)}
23
- `}function bi(){let n=Object.entries($i).map(([r,t])=>`${t.doc}
24
- ${ai(r,t.default)}`);return`${[Vh,...n].join(`
22
+ ${ve(r,t.default)}
23
+ `}function pe(){let n=Object.entries(Ie).map(([r,t])=>`${t.doc}
24
+ ${ve(r,t.default)}`);return`${[sf,...n].join(`
25
25
 
26
26
  `)}
27
- `}function Gt(n,r,t){let i=ai(r,t),e=ao(r);if(e.test(n))return n.replace(e,i);return`${n.replace(/\n*$/,`
27
+ `}function Lt(n,r,t){let e=ve(r,t),i=po(r);if(i.test(n))return n.replace(i,e);return`${n.replace(/\n*$/,`
28
28
  `)}
29
- ${i}
30
- `}function bo(n){if(n==="")return bi();return Object.keys($i).reduce(Yh,n)}function wo(n){return n?`include themes/${n}.conf`:""}function Eo(n){return n?`[general]
31
- import = ["${n}"]`:""}function wi(n){for(let o of n)for(let s of[o.name,o.group,o.native??"",o.ansiSource])if(/["$`\\]/.test(s))throw Error(`${o.name}: "${s}" contains a character that breaks zsh quoting`);let r=Math.max(0,...n.map((o)=>o.name.length)),t=(o,s)=>` ${o.name.padEnd(r)} "${s}"`,i=(o)=>o.map((s)=>s.name).join(" "),e=Jr(n);return["# Generated by `mise run build` — do not edit.","# Source of truth: themes/*.toml in the ttheme repo.","",`typeset -g TTHEME_VERSION=${Dn.version}`,"","# seed for `ttheme config` when no config.zsh exists yet",`typeset -g TTHEME_CONFIG_TEMPLATE='${bi().trimEnd().replaceAll("'","'\\''")}'`,"","typeset -gA TTHEME_PALETTE=(",...n.map((o)=>t(o,[o.background,o.foreground,o.cursor,o.selection,...o.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=(${i(e)})`,"","# the same palettes by series name, then palette name: TTHEME_SORT=abc lists them this way",`typeset -ga TTHEME_ABC=(${i(ot(e))})`,"","typeset -gA TTHEME_GROUP=(",...n.map((o)=>t(o,o.group)),")","","# original-language title, rendered dim next to the group","typeset -gA TTHEME_NATIVE=(",...n.filter((o)=>o.native).map((o)=>t(o,o.native??"")),")","","# where each palette's 16 ANSI colors came from","typeset -gA TTHEME_SRC=(",...n.map((o)=>t(o,o.ansiSource)),")",""].join(`
32
- `)}var Ei={id:"shell",emitShared(n){return[{path:"shell/palettes.zsh",content:wi(n.map(gi))}]}};var ko=(n)=>`[${n.map((r)=>`"${r}"`).join(", ")}]`,ki={id:"wezterm",limits:"no shaders; runtime overrides are per-window, never per-pane",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 = ${ko(n.ansi.slice(0,8))}`,`brights = ${ko(n.ansi.slice(8,16))}`,""].join(`
29
+ ${e}
30
+ `}function No(n){if(n==="")return pe();return Object.keys(Ie).reduce(uf,n)}function Ho(n){return n?`include themes/${n}.conf`:""}function So(n){return n?`[general]
31
+ import = ["${n}"]`:""}function Ne(n,r,t=[]){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 e=Math.max(0,...n.map((u)=>u.name.length)),i=(u,c)=>` ${u.name.padEnd(e)} "${c}"`,o=(u)=>u.map((c)=>c.name).join(" "),s=Gr(n);return["# Generated by `mise run build` — do not edit.","# Source of truth: themes/*.toml in the ttheme repo.","",`typeset -g TTHEME_VERSION=${Dn.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=(${t.join(" ")})`,"","# seed for `ttheme config` when no config.zsh exists yet",`typeset -g TTHEME_CONFIG_TEMPLATE='${pe().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(ut(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(`
32
+ `)}var He={id:"shell",emitShared(n){return[{path:"shell/palettes.zsh",content:Ne(n.map(Ee))}]}};var jo=(n)=>`[${n.map((r)=>`"${r}"`).join(", ")}]`,Se={id:"wezterm",limits:"no shaders; runtime overrides are per-window, never per-pane",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 = ${jo(n.ansi.slice(0,8))}`,`brights = ${jo(n.ansi.slice(8,16))}`,""].join(`
33
33
  `),t=[`-- ${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(`
34
- `);return[{path:`wezterm/colors/${n.name}.toml`,content:r},{path:`wezterm/config/${n.name}.lua`,content:t}]}};function Gr(n){return[`# ${n.name} — ${n.group}${n.native?` (${n.native})`:""}`,`# ANSI: ${n.ansiSource}`]}var Fo=st(import.meta.dirname,".."),Ph=st(Fo,"themes"),Mi=st(Fo,"dist"),Jt=[tt,et,rt,ki,it],Ah=[Ei,li],vo=Jt.map((n)=>n.id);async function Kt({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?Jt.filter((o)=>n.includes(o.id)):Jt,t=ho(Ph),i=io(t);if(i.length>0){for(let o of i)console.error(` ✗ ${o.theme} [${o.rule}] ${o.detail}`);throw Error(`${i.length} contrast violation(s). Fix the palette, or waive the rule in its [contrast] section with a reason.`)}if(r.length===Jt.length)Mo(Mi,{recursive:!0,force:!0});else for(let o of r)Mo(st(Mi,o.id),{recursive:!0,force:!0});let e=0;for(let o of[...r,...Ah]){let s=t.flatMap((h)=>o.emit?.(h)??[]),u=o.emitShared?.(t)??[];for(let h of[...s,...u])await Bun.write(st(Mi,h.path),h.content),e++;let c=s.length>0?`${t.length} themes${o.limits?` (${o.limits})`:""}`:u.map((h)=>zh(h.path)).join(" ");console.log(` ${o.id.padEnd(10)} ${c}`)}console.log(`
35
- ${t.length} themes (${fo(t).length} in the new-tab rotation) -> ${e} files in dist/`)}import{spawn as xu}from"node:child_process";import{existsSync as Wr,mkdirSync as fe,mkdtempSync as Dl,readFileSync as Du,rmSync as se,statSync as n0,writeFileSync as ge}from"node:fs";import{tmpdir as r0}from"node:os";import{dirname as Tu,join as sr}from"node:path";import{mkdirSync as Os,readdirSync as Er,readFileSync as $g,renameSync as Qs,rmSync as Zr,statSync as ag,utimesSync as bg,writeFileSync as yt}from"node:fs";import{join as vn}from"node:path";var Ns=Nt(Go(),1),Ot=Nt(Fs(),1),vs=[137,80,78,71,13,10,26,10],Hs=13;function Ss(n){return n.length>=vs.length&&vs.every((r,t)=>n[t]===r)}function mg(n){let r=Ot.PNG.sync.read(Buffer.from(n));return{width:r.width,height:r.height,data:new Uint8Array(r.data)}}function js(n,r){if(Ss(n)){let t=Zi(n);if(t&&t.width*t.height>r)throw Error(`${t.width}×${t.height} is over ${r/1e6} megapixels`);return mg(n)}if(n[0]===255&&n[1]===216){let t=Ns.decode(n,{useTArray:!0,formatAsRGBA:!0,maxResolutionInMP:r/1e6,maxMemoryUsageInMB:1024});return{width:t.width,height:t.height,data:t.data}}throw Error("not a PNG or JPEG image")}function Qr(n){let r=new Ot.PNG({width:n.width,height:n.height});return r.data=Buffer.from(n.data),Ot.PNG.sync.write(r)}function Is(n,r){for(let t=0;t+r.length<=n.length;t++){let i=!0;for(let e=0;e<r.length&&i;e++)i=n[t+e]===r.charCodeAt(e);if(i)return t}return-1}function Zi(n){if(n.length<33||!Ss(n))return null;let r=new DataView(n.buffer,n.byteOffset,n.byteLength),t=r.getUint32(16),i=r.getUint32(20);if(n[25]===4||n[25]===6)return{width:t,height:i,alpha:!0};let e=Is(n,"IDAT");return{width:t,height:i,alpha:Is(e===-1?n:n.subarray(0,e),"tRNS")!==-1}}function ps(n,r=Hs){let{width:t,height:i}=n,e=-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)t=Math.min(t,u),e=Math.max(e,u),i=Math.min(i,s),o=Math.max(o,s);return e<0?null:{x:t,y:i,w:e-t+1,h:o-i+1}}function Qt(n){let r=0;for(let t=3;t<n.data.length;t+=4)if((n.data[t]??0)<Hs)r++;return Math.round(r*100/(n.width*n.height))}function dg(n,r){if(r<=1)return n;let t=Math.max(1,Math.floor(n.width/r)),i=Math.max(1,Math.floor(n.height/r)),e=new Uint8Array(t*i*4),o=n.data;for(let s=0;s<i;s++)for(let u=0;u<t;u++){let c=0,h=0,f=0,g=0;for(let $=0;$<r;$++)for(let a=0;a<r;a++){let w=((s*r+$)*n.width+u*r+a)*4,F=o[w+3]??0;c+=(o[w]??0)*F,h+=(o[w+1]??0)*F,f+=(o[w+2]??0)*F,g+=F}let l=(s*t+u)*4;if(g>0)e[l]=Math.round(c/g),e[l+1]=Math.round(h/g),e[l+2]=Math.round(f/g);e[l+3]=Math.round(g/(r*r))}return{width:t,height:i,data:e}}function Gs(n,r,t){let i=Math.min(r/n.width,t/n.height),e=Math.max(1,Math.round(n.width*i)),o=Math.max(1,Math.round(n.height*i)),s=yr(n,{x:0,y:0,w:n.width,h:n.height},e,o),u=new Uint8Array(r*t*4),c=Math.floor((r-e)/2),h=Math.floor((t-o)/2);for(let f=0;f<o;f++)u.set(s.data.subarray(f*e*4,(f+1)*e*4),((h+f)*r+c)*4);return{width:r,height:t,data:u}}function yr(n,r,t,i){let e=Math.max(1,Math.floor(Math.min(r.w/t,r.h/i))),o=dg(n,e),s=o.data,u=new Uint8Array(t*i*4);for(let c=0;c<i;c++){let h=Math.min(o.height-1,Math.max(0,r.y/e+(c+0.5)*r.h/e/i-0.5)),f=Math.floor(h),g=Math.min(o.height-1,f+1),l=h-f;for(let $=0;$<t;$++){let a=Math.min(o.width-1,Math.max(0,r.x/e+($+0.5)*r.w/e/t-0.5)),w=Math.floor(a),F=Math.min(o.width-1,w+1),H=a-w,J=(f*o.width+w)*4,M=(f*o.width+F)*4,I=(g*o.width+w)*4,b=(g*o.width+F)*4,K=(s[J+3]??0)*(1-H)*(1-l),E=(s[M+3]??0)*H*(1-l),G=(s[I+3]??0)*(1-H)*l,j=(s[b+3]??0)*H*l,Q=K+E+G+j,R=(c*t+$)*4;if(Q>0)for(let A=0;A<3;A++){let L=(s[J+A]??0)*K+(s[M+A]??0)*E+(s[I+A]??0)*G+(s[b+A]??0)*j;u[R+A]=Math.round(L/Q)}u[R+3]=Math.round(Q)}}return{width:t,height:i,data:u}}var Xn={width:2560,height:1550},wg=2560,Eg=0.1,ys=0.15,kg=0.55,Mg=0.65,Fg=3,vg=ir(Li("#19161e","#9b86c8",0.2)),Ig="shelf";function Li(n,r,t){let i=Qn(n),e=Qn(r);return`#${i.map((o,s)=>Math.round(o+((e[s]??0)-o)*t).toString(16).padStart(2,"0")).join("")}`}function Ng(n,r){if(r==="background"||r==="foreground"||r==="cursor")return n[r];if(r==="selection"&&n.selection)return n.selection;let t=/^ansi(\d|1[0-5])$/.exec(r),i=t?n.ansi[Number(t[1])]:void 0;if(!i)throw Error(`${n.name} has no slot ${r}`);return i}function Js(n){if(n(1))return 1;let r=0,t=1;for(let i=0;i<40;i++){let e=(r+t)/2;if(n(e))r=e;else t=e}return r}function Ks(n,r){let t=Ng(n,r),e=Js((h)=>fi({name:n.name,background:Li(n.background,t,h),foreground:n.foreground,ansi:n.ansi,waive:n.waived??[]}).length===0),o=Js((h)=>ir(Li(n.background,t,h))<=vg),s=Math.floor(Math.min(e,o)*1000)/1000,u=Qn(n.background),c=Math.hypot(...Qn(t).map((h,f)=>(h-(u[f]??0))*s));return{slot:r,color:t,cap:e,matched:o,opacity:s,reach:c}}function Zs(n,r){let t=Ks(n,"cursor");if(t.opacity>=Eg)return t;return r.filter((i)=>i!=="cursor"&&i!=="background").map((i)=>Ks(n,i)).reduce((i,e)=>e.reach>i.reach?e:i,t)}function Ui(n,r,t){let i=Qn(r),e=Qn(t),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((i[c]??0)+((e[c]??0)-(i[c]??0))*u)}return n}function Hg(n,r,t){let i=Qn(r),e=n.data,o=new Uint8Array(e.length);for(let s=0;s<e.length;s+=4){let u=(e[s+3]??0)/255*t;for(let c=0;c<3;c++)o[s+c]=Math.round((i[c]??0)*(1-u)+(e[s+c]??0)*u);o[s+3]=255}return{width:n.width,height:n.height,data:o}}function Ls(n){return ps(n)??{x:0,y:0,w:n.width,h:n.height}}function Us(n){return Math.min(0.5,(ys+0.5)*(n.w*Xn.height/Xn.width/n.h))}function qs(n,r,t){let i=Math.min(Math.max(0,t*n.h-r/2),n.h-r);return{x:n.x,y:n.y+i,w:n.w,h:r}}function Sg(n,r,t,i){let e=n.w*t/r;if(e<=n.h)return qs(n,e,i);let o=n.h*r/t;return{x:n.x+(n.w-o)/2,y:n.y,w:o,h:n.h}}function Rs(n,r,t){if(n.w*t>n.h*r){let e=n.h*r/t;return{x:n.x+(n.w-e)/2,y:n.y,w:e,h:n.h}}let i=n.w*t/r;return{x:n.x,y:n.y+(n.h-i)/2,w:n.w,h:i}}function jg(n,r){let t=Math.min(1,wg/Math.max(r.w,r.h));return yr(n,r,Math.round(r.w*t),Math.round(r.h*t))}function Ws(n,r,t,i,e){let o=kg*n.h,s=n.w*t/r;if(e<Fg||s>o)return{crop:Sg(n,r,t,i),at:{x:0,y:0,w:r,h:t},inset:!1};let u=1-s/o,c=t*(1-ys*u),h=n.w*c/o;return{crop:qs(n,o,i),at:{x:(r-h)*Mg,y:t-c,w:h,h:c},inset:!0}}function Xs(n,r,t,i){let e=Math.max(1,Math.round(r.at.w)),o=Math.max(1,Math.round(r.at.h)),s=yr(n,r.crop,e,o),u=new Uint8Array(t*i*4),c=Math.round(r.at.x),h=Math.round(r.at.y);for(let f=0;f<o;f++){let g=h+f,l=Math.max(0,-c),$=Math.min(e,t-c);if(g<0||g>=i||$<=l)continue;u.set(s.data.subarray((f*e+l)*4,(f*e+$)*4),(g*t+c+l)*4)}return{width:t,height:i,data:u}}function pg(n,r,t,i){let e=Ws(r,Xn.width,Xn.height,t,i);return e.inset?Xs(n,e,Xn.width,Xn.height):yr(n,e.crop,Xn.width,Xn.height)}function Vs(n,r,t,i,e,o){let s=Ls(n),u=Ws(s,Xn.width,Xn.height,Us(s),o),c;if(u.inset){let h=Rs({x:0,y:0,w:Xn.width,h:Xn.height},i,e),f=i/h.w;c=Xs(n,{...u,at:{x:(u.at.x-h.x)*f,y:(u.at.y-h.y)*f,w:u.at.w*f,h:u.at.h*f}},i,e)}else c=yr(n,Rs(u.crop,i,e),i,e);return Hg(Ui(c,r.background,t.color),r.background,t.opacity)}function Zt(n){return vn(n,"ttheme","backgrounds")}function Gg(n,r,t,i,e){return[...i?[`# from ${i}`]:[],...e?[`# image ${e}`]:[],`background-image = ${r}`,"background-image-fit = cover","background-image-position = center",`background-image-opacity = ${t}`,`config-file = ?${n}.tune.conf`,`config-file = ?${n}.off.conf`,""].join(`
36
- `)}function Jg(n,r){for(let t of Er(n))if(t.startsWith(`${r}@`)&&t.endsWith(".png")||t===`${r}.tune.conf`||t===`${r}.off.conf`)Zr(vn(n,t))}function Kg(n){return`${n.site}_${n.id}`}function Lt(n,r){return vn(n,Ig,r)}function Ys(n,r){let t=n.slice(r.length);return n.startsWith(r)&&(t===".png"||t===".conf"||t===".tune.conf"||t===".off.conf"||/^@[a-z0-9-]+\.png$/.test(t))}function ct(n,r){try{return/^# image (\S+)$/m.exec($g(vn(n,`${r}.conf`),"utf8"))?.[1]}catch{return}}function Rg(n,r){try{return Er(Lt(n,r))}catch{return[]}}function zs(n,r){let t=ct(n,r);return[...t?[t]:[],...Rg(n,r)].sort()}function Ps(n,r){let t=ct(n,r);if(!t)return;let i=vn(Lt(n,r),t);Zr(i,{recursive:!0,force:!0}),Os(i,{recursive:!0});for(let e of Er(n))if(Ys(e,r))Qs(vn(n,e),vn(i,e.slice(r.length)))}function As(n,r,t){let i=vn(Lt(n,r),t);for(let e of Er(i))Qs(vn(i,e),vn(n,`${r}${e}`));Zr(i,{recursive:!0})}function Cs(n,r,t){try{return Er(vn(n,"originals")).find((i)=>i.startsWith(`${r}-${t}.`))}catch{return}}function Ts(n,r,t){let i=Cs(n,r,t);if(i){let e=new Date;bg(vn(n,"originals",i),e,e)}}function _s(n,r,t){let i=Zt(n),e=zs(i,r),o=ct(i,r);if(!o||e.length<2)throw Error(`${r} has no other image`);let s=(e.indexOf(o)+t+e.length)%e.length,u=e[s];return Ps(i,r),As(i,r,u),Ts(i,r,u),{key:u,at:s+1,of:e.length}}function Bs(n,r){let t=Zt(n),i=Er(t).filter((h)=>Ys(h,r));if(i.length===0)throw Error(`${r} has no image`);let e=zs(t,r),o=ct(t,r),s=o&&Cs(t,r,o);if(s)Zr(vn(t,"originals",s));for(let h of i)Zr(vn(t,h));let u=e.filter((h)=>h!==o),c=u[(o?e.indexOf(o):0)%u.length];if(c)As(t,r,c),Ts(t,r,c);return{key:o,left:u.length}}function Og(n,r,t){if(ct(n,r)!==t)Ps(n,r);if(t)Zr(vn(Lt(n,r),t),{recursive:!0,force:!0});Jg(n,r)}function xs(n,r,t,i,e){let o=Zt(n),s=r.name,u=Kg(e);Os(vn(o,"originals"),{recursive:!0}),Og(o,s,u);let c=Ls(i),h=Us(c),f=Qt(i),g=vn(o,`${s}.png`),l=vn(o,`${s}@fill-${Math.round(h*100)}.png`),$=vn(o,`${s}.conf`),a=vn(o,"originals",`${s}-${e.site}_${e.id}.${e.ext}`);return yt(g,Qr(Ui(jg(i,c),r.background,t.color))),yt(l,Qr(Ui(pg(i,c,h,f),r.background,t.color))),yt($,Gg(s,l,t.opacity,e.from,u)),yt(a,e.bytes),[g,l,$,a]}function Ds(n){let r=vn(Zt(n),"originals"),t=new Map,i;try{i=Er(r)}catch{return new Map}for(let e of i){let o=/^(.+)-([a-z.]+)_(\d+)\.[a-z]+$/.exec(e),[,s,u,c]=o??[];if(!s||!u||!c)continue;let h=ag(vn(r,e)).mtimeMs,f=t.get(s);if(!f||h>f.at)t.set(s,{site:u,id:Number(c),at:h})}return new Map([...t].map(([e,{site:o,id:s}])=>[e,{site:o,id:s}]))}import{readdirSync as Qg,rmSync as yg,statSync as Zg}from"node:fs";import{setDefaultAutoSelectFamilyAttemptTimeout as Lg}from"node:net";import{homedir as Ug}from"node:os";import{join as ft}from"node:path";import{setTimeout as qg}from"node:timers/promises";var gt=100,qi=25000000,Wg=536870912,Wt=["safe","questionable","explicit"],kr=["nudity","underwear"],Xg={nudity:new Set(["nude","naked","topless","bottomless","nipples","naked_towel","undressing"]),underwear:new Set(["underwear","panties","pantsu","bra","lingerie","pantyshot"])},ht={safe:"s",questionable:"q",explicit:"e"},tu=new Set(["danbooru","gelbooru","konachan","yande.re","sankaku"]),Vg=8191,Yg=20000,zg=3000,iu=60000,Pg=3,Ag=`ttheme/${Dn.version} (+${Dn.homepage})`,Cg=["orig","tile","thumb","cut"],eu=new Map,Tg=il(process.env.TTHEME_FIND_HOSTS),_g=tl(process.env.TTHEME_FIND_CUTOUTS);Lg(zg);function nu(n){try{return Qg(n)}catch{return[]}}function lt(n){return n.startsWith("//")?`https:${n}`:n}function Lr(n){return(/\.([a-z0-9]+)(?:\?.*)?$/i.exec(n)?.[1]??"").toLowerCase()}function Wi(n){let r=n.trim();if(!r)return[];let t=JSON.parse(r);if(Array.isArray(t))return t;let i=t.posts;return Array.isArray(i)?i:[]}function Bg(n){let r=n.trim(),i=(r?JSON.parse(r):{}).tags??{};return new Map(Object.entries(i).map(([e,o])=>[e,String(o)]))}function Ut(n,r,t){let i=lt(String(n??""));return{file:i,width:Number(r)||0,height:Number(t)||0,ext:Lr(i)}}function Xi(n,r){let t=lt(String(r.preview??""));if(!r.file||!t||!Number(n.id))return[];let i=Number(n.width??n.image_width)||0,e=Number(n.height??n.image_height)||0;return[{id:Number(n.id),width:i,height:e,file:r.file,preview:t,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),smaller:r.versions.filter((o)=>o.file&&o.width>0&&o.height>0&&o.width*o.height<i*e)}]}function xg(n,r="https://safebooru.org"){return Wi(n).flatMap((t)=>{let i=t.directory&&t.image?`${r}/images/${t.directory}/${t.image}`:"",e=lt(String(t.file_url||i));return Xi(t,{preview:t.preview_url,file:e,ext:Lr(e),owner:t.owner,artist:"",md5:t.hash??t.md5,tags:String(t.tags??""),versions:[Ut(t.sample_url,t.sample_width,t.sample_height)]})})}function Dg(n){let r=Bg(n);return Wi(n).flatMap((t)=>{let i=lt(String(t.file_url??"")),e=String(t.tags??"");return Xi(t,{preview:t.preview_url,file:i,ext:String(t.file_ext||Lr(i)).toLowerCase(),owner:t.author,artist:e.split(/\s+/).find((o)=>r.get(o)==="artist")??"",md5:t.md5,tags:e,versions:[Ut(t.jpeg_url,t.jpeg_width,t.jpeg_height),Ut(t.sample_url,t.sample_width,t.sample_height)]})})}function nl(n){return Wi(n).flatMap((r)=>{let t=lt(String(r.file_url??"")),i=r.media_asset??{};return Xi(r,{preview:r.preview_file_url,file:t,ext:String(r.file_ext||Lr(t)).toLowerCase(),owner:"",artist:String(r.tag_string_artist??"").split(/\s+/)[0]??"",md5:r.md5,tags:String(r.tag_string??""),versions:(i.variants??[]).map((e)=>Ut(e.url,e.width,e.height)).filter((e)=>e.ext==="jpg"||e.ext==="png").sort((e,o)=>o.width*o.height-e.width*e.height)})})}function ou(n){return Number(/count="(\d+)"/.exec(n)?.[1]??0)}function rl(n){let r=n.trim()?JSON.parse(n):{};return Number(r.counts?.posts)||0}function tl(n){let r=new Map;for(let t of(n??"").split(/\s+/).filter(Boolean)){let i=t.indexOf("=");if(i>0)r.set(t.slice(0,i),t.slice(i+1).split(",").filter(Boolean))}return r}function il(n){let r=new Map;for(let t of(n??"").split(/[\s,]+/).filter(Boolean)){let i=t.indexOf("="),e=t.slice(0,i);try{let o=new URL(t.slice(i+1));if(e&&o.protocol==="https:")r.set(e,o.origin)}catch{}}return r}function su(n,r,t,i){let e=(n??"").split(/\s+/);if(i!==void 0&&e.includes(i))return[];let o=r.filter((s)=>e.includes(s));return o.length>0?o:[...t]}function Xt(n){return su(n,Wt,["safe"])}function Vt(n){return su(n,kr,kr,"none")}function Vi(n,r,t){return{safe:new Set(n),questionable:new Set(r),explicit:new Set(t)}}function Yi(n){let r=Tg.get(n.key),t=_g.get(n.key);return{...n,origin:r??n.origin,moved:r!==void 0&&r!==n.origin,cutouts:t??n.cutouts,vouched:n.vouched&&t===void 0}}function zi(n,r){if(n.length<2)return n.join("");return r?`( ${n.join(" ~ ")} )`:n.map((t)=>`~${t}`).join(" ")}function el(n){let r=Yi(n),t=(i)=>`${r.origin}/index.php?${new URLSearchParams({page:"dapi",s:"post",q:"index",...i})}`;return{...r,cutouts:zi(r.cutouts,!0),ratings:Vi(["safe","general"],["questionable"],["explicit"]),rate:()=>"",best:"sort:score:desc",tagBudget:Number.POSITIVE_INFINITY,postsUrl:(i,e)=>t({json:"1",limit:String(gt),pid:String(e),tags:i}),countUrl:(i)=>t({limit:"0",tags:i}),postUrl:(i)=>t({json:"1",id:String(i)}),pageUrl:(i)=>`${r.origin}/index.php?page=post&s=view&id=${i}`,parse:(i)=>xg(i,r.origin),count:ou}}function ru(n){let r=Yi(n),t=(i)=>new URLSearchParams({api_version:"2",include_tags:"1",...i});return{...r,cutouts:zi(r.cutouts,!1),ratings:Vi([ht.safe],[ht.questionable],[ht.explicit]),rate:(i)=>{let[e]=i;if(i.length===1&&e)return`rating:${ht[e]}`;let o=Wt.filter((u)=>!i.includes(u)),[s]=o;return o.length===1&&s?`-rating:${ht[s]}`:""},best:"order:score",tagBudget:Number.POSITIVE_INFINITY,postsUrl:(i,e)=>`${r.origin}/post.json?${t({limit:String(gt),page:String(e+1),tags:i})}`,countUrl:(i)=>`${r.origin}/post.xml?${new URLSearchParams({limit:"1",tags:i})}`,postUrl:(i)=>`${r.origin}/post.json?${t({tags:`id:${i}`})}`,pageUrl:(i)=>`${r.origin}/post/show/${i}`,parse:Dg,count:ou}}function ol(n){let r=Yi(n);return{...r,cutouts:zi(r.cutouts,!1),ratings:Vi(["g"],["s","q"],["e"]),rate:()=>"",best:"order:score",tagBudget:2,postsUrl:(t,i)=>`${r.origin}/posts.json?${new URLSearchParams({limit:String(gt),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:nl,count:rl}}function sl(n){return Vn.find((r)=>r.key===n||r.name===n||new URL(r.origin).host===n)}function Pi(n){return n.split(/\s+/).filter(Boolean).length}function uu(n,r){let t=n.trim();if(/^\d+$/.test(t))return{site:r,id:Number(t)};let i=/^([\w.]+):(\d+)$/.exec(t);if(i){let u=Vn.find((c)=>c.key===i[1]||c.name===i[1]);return u&&{site:u,id:Number(i[2])}}let e;try{e=new URL(t)}catch{return}let o=sl(e.host),s=Number(e.searchParams.get("id")??e.pathname.split("/").filter(Boolean).at(-1));return o&&s>0?{site:o,id:s}:void 0}var Vn=[el({key:"safebooru",name:"safebooru",origin:"https://safebooru.org",cutouts:["transparent_background","vector_trace"],vouched:!1,ansi:4}),ru({key:"yande",name:"yande.re",origin:"https://yande.re",cutouts:["transparent_png"],vouched:!0,ansi:5}),ru({key:"konachan",name:"konachan",origin:"https://konachan.net",cutouts:["transparent","vector"],vouched:!1,ansi:6}),ol({key:"danbooru",name:"danbooru",origin:"https://safebooru.donmai.us",cutouts:["transparent_background"],vouched:!1,ansi:2})];function cu(n){let r;try{r=new URL(n).hostname}catch{return""}return r.split(".").slice(-2).join(".")}function hu(n,r=kr){return n.tags.filter((t)=>r.some((i)=>Xg[i].has(t)))}function fu(n,r,t=["safe"]){return t.some((i)=>n.ratings[i].has(r.rating))}function mt(n){return[n,...n.smaller].find((r)=>r.width*r.height<=qi)}function gu(n){return tu.has(n)}function lu(n){let r=new Map;for(let[t,i]of[...n].sort(([e],[o])=>e<o?-1:1)){if(i===""||tu.has(i))continue;r.set(i,[...r.get(i)??[],t])}return r}function mu(){return ft(process.env.XDG_CACHE_HOME??ft(Ug(),".cache"),"ttheme")}function lr(n){return ft(mu(),n.key)}function du(n=Wg,r=mu()){let t=[],i=0;for(let e of nu(r))for(let o of Cg){let s=ft(r,e,o);for(let u of nu(s)){let c=ft(s,u);try{let{size:h,mtimeMs:f}=Zg(c);t.push({path:c,size:h,at:f}),i+=h}catch{}}}t.sort((e,o)=>e.at-o.at);for(let e of t){if(i<=n)return;try{yg(e.path,{force:!0}),i-=e.size}catch{}}}function ul(n,r){if(n!==null&&/^\s*\d+\s*$/.test(n))return Number(n)*1000;let t=n===null?Number.NaN:Date.parse(n);return Number.isNaN(t)?iu:Math.max(0,t-r)}function qt(n){return eu.get(n.key)??0}function cl(n){return(n.headers.get("server")??"").startsWith("cloudflare")&&n.headers.get("cf-mitigated")==="challenge"}async function dt(n,r,t,i={},e=Yg){for(let o=1;;o++){let s=qt(n)-Date.now();if(s>0)await qg(s,void 0,{signal:t});let u=await fetch(r,{headers:{"User-Agent":Ag,Referer:`${n.origin}/`,...i},signal:e?AbortSignal.any([t,AbortSignal.timeout(e)]):t});if(u.status===429&&o<Pg){await u.body?.cancel();let c=ul(u.headers.get("retry-after"),Date.now());if(c>iu)throw Error(`${n.name} asks to wait ${Math.ceil(c/1000)}s`);eu.set(n.key,Math.max(qt(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 $u(n,r,t,i){return n.parse(await(await dt(n,n.postsUrl(r,t),i)).text())}async function au(n,r,t){return n.count(await(await dt(n,n.countUrl(r),t)).text())}async function Ai(n,r,t){let[i]=n.parse(await(await dt(n,n.postUrl(r),t)).text());return i}async function bu(n,r,t){let i=await dt(n,r,t,{Range:`bytes=0-${Vg}`});return Zi(new Uint8Array(await i.arrayBuffer()))}async function wu(n,r,t,i){let e=await dt(n,r,t,{},0),o=Number(e.headers.get("content-length"))||0,s=e.body?.getReader();if(!s)return new Uint8Array(await e.arrayBuffer());let u=[],c=0;for(;;){let{done:g,value:l}=await s.read();if(g)break;u.push(l),c+=l.length,i?.(c,o)}let h=new Uint8Array(c),f=0;for(let g of u)h.set(g,f),f+=g.length;return h}import{existsSync as hl,mkdirSync as fl,readFileSync as gl,writeFileSync as ll}from"node:fs";import{dirname as ml,join as dl}from"node:path";var Eu="https://kecan0406.github.io/ttheme/manifest.json",$l=20000;function Yt(n){return dl(n,"ttheme","catalog.json")}function zt(n,r){let t=Yt(n);fl(ml(t),{recursive:!0}),ll(t,`${JSON.stringify(r,null,2)}
37
- `)}function Cn(n){let r=Yt(n);if(!hl(r))throw Error(`no catalog at ${r} — run \`ttheme init\` first`);return ku(gl(r,"utf8"))}function ku(n){let r;try{r=JSON.parse(n)}catch{throw Error("catalog is not valid JSON")}let t=r;if(typeof t?.version!=="string"||!Array.isArray(t.palettes))throw Error("catalog has no version or palettes");for(let i of t.palettes)if(typeof i?.name!=="string"||!Array.isArray(i.ansi)||i.ansi.length!==16)throw Error(`catalog entry ${JSON.stringify(i?.name)} is missing name or its 16 ANSI colors`);return t}async function Mu(n){let r;try{r=await fetch(n,{signal:AbortSignal.timeout($l)})}catch(t){throw Error(`cannot reach the registry at ${n} — ${t instanceof Error?t.message:String(t)}`)}if(!r.ok)throw Error(`registry at ${n} answered ${r.status}`);return ku(await r.text())}function Fu(n){let r=new Set(n.waived??[]);return St.flatMap((t,i)=>{let e=n.gate?.[i];if(r.has(t.rule)||typeof e!=="number")return[];if(t.min!==void 0&&e<t.min)return[`${t.label} ${e} < ${t.min}`];if(t.max!==void 0&&e>t.max)return[`${t.label} ${e} > ${t.max}`];return[]})}function Pt(n,r){let t=n.find((i)=>i.name===r);if(!t)throw Error(`no palette named ${r} in the catalog — \`ttheme list\` shows what is there`);return t}function vu(n,r){let t=r.toLowerCase();return n.filter((i)=>[i.name,i.group,i.native??"",i.ansiSource].some((e)=>e.toLowerCase().includes(t)))}import{spawn as al}from"node:child_process";var bl=30000,wl=3,El=97,kl=`ObjC.import('Vision')
34
+ `);return[{path:`wezterm/colors/${n.name}.toml`,content:r},{path:`wezterm/config/${n.name}.lua`,content:t}]}};function jr(n){return[`# ${n.name} — ${n.group}${n.native?` (${n.native})`:""}`,`# ANSI: ${n.ansiSource}`]}var Jo=ct(import.meta.dirname,".."),hf=ct(Jo,"themes"),je=ct(Jo,"dist"),Qt=[it,st,et,Se,ot],ff=[He,ke],Ko=Qt.map((n)=>n.id);async function Zt({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?Qt.filter((o)=>n.includes(o.id)):Qt,t=Eo(hf),e=lo(t);if(e.length>0){for(let o of e)console.error(` ✗ ${o.theme} [${o.rule}] ${o.detail}`);throw Error(`${e.length} contrast violation(s). Fix the palette, or waive the rule in its [contrast] section with a reason.`)}if(r.length===Qt.length)Go(je,{recursive:!0,force:!0});else for(let o of r)Go(ct(je,o.id),{recursive:!0,force:!0});let i=0;for(let o of[...r,...ff]){let s=t.flatMap((h)=>o.emit?.(h)??[]),u=o.emitShared?.(t)??[];for(let h of[...s,...u])await Bun.write(ct(je,h.path),h.content),i++;let c=s.length>0?`${t.length} themes${o.limits?` (${o.limits})`:""}`:u.map((h)=>cf(h.path)).join(" ");console.log(` ${o.id.padEnd(10)} ${c}`)}console.log(`
35
+ ${t.length} themes (${ko(t).length} in the new-tab rotation) -> ${i} files in dist/`)}import{spawn as mc}from"node:child_process";import{existsSync as Vr,mkdirSync as wi,mkdtempSync as $m,readFileSync as dc,rmSync as di,statSync as am,writeFileSync as Ei}from"node:fs";import{tmpdir as bm}from"node:os";import{dirname as fc,join as ur}from"node:path";import{createHash as Jg}from"node:crypto";import{mkdirSync as Vs,readdirSync as kr,readFileSync as Ys,renameSync as Ps,rmSync as Lr,statSync as Kg,utimesSync as Rg,writeFileSync as Xt}from"node:fs";import{isAbsolute as yg,join as Fn}from"node:path";var ys=Jt(Uo(),1),qt=Jt(Js(),1),Ks=[137,80,78,71,13,10,26,10],Os=13;function Ls(n){return n.length>=Ks.length&&Ks.every((r,t)=>n[t]===r)}function jg(n){let r=qt.PNG.sync.read(Buffer.from(n));return{width:r.width,height:r.height,data:new Uint8Array(r.data)}}function Qs(n,r){if(Ls(n)){let t=Pe(n);if(t&&t.width*t.height>r)throw Error(`${t.width}×${t.height} is over ${r/1e6} megapixels`);return jg(n)}if(n[0]===255&&n[1]===216){let t=ys.decode(n,{useTArray:!0,formatAsRGBA:!0,maxResolutionInMP:r/1e6,maxMemoryUsageInMB:1024});return{width:t.width,height:t.height,data:t.data}}throw Error("not a PNG or JPEG image")}function yr(n){let r=new qt.PNG({width:n.width,height:n.height});return r.data=Buffer.from(n.data),qt.PNG.sync.write(r)}function Rs(n,r){for(let t=0;t+r.length<=n.length;t++){let e=!0;for(let i=0;i<r.length&&e;i++)e=n[t+i]===r.charCodeAt(i);if(e)return t}return-1}function Pe(n){if(n.length<33||!Ls(n))return null;let r=new DataView(n.buffer,n.byteOffset,n.byteLength),t=r.getUint32(16),e=r.getUint32(20);if(n[25]===4||n[25]===6)return{width:t,height:e,alpha:!0};let i=Rs(n,"IDAT");return{width:t,height:e,alpha:Rs(i===-1?n:n.subarray(0,i),"tRNS")!==-1}}function Zs(n,r=Os){let{width:t,height:e}=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)t=Math.min(t,u),i=Math.max(i,u),e=Math.min(e,s),o=Math.max(o,s);return i<0?null:{x:t,y:e,w:i-t+1,h:o-e+1}}function Wt(n){let r=0;for(let t=3;t<n.data.length;t+=4)if((n.data[t]??0)<Os)r++;return Math.round(r*100/(n.width*n.height))}function Gg(n,r){if(r<=1)return n;let t=Math.max(1,Math.floor(n.width/r)),e=Math.max(1,Math.floor(n.height/r)),i=new Uint8Array(t*e*4),o=n.data;for(let s=0;s<e;s++)for(let u=0;u<t;u++){let c=0,h=0,f=0,g=0;for(let $=0;$<r;$++)for(let a=0;a<r;a++){let w=((s*r+$)*n.width+u*r+a)*4,F=o[w+3]??0;c+=(o[w]??0)*F,h+=(o[w+1]??0)*F,f+=(o[w+2]??0)*F,g+=F}let l=(s*t+u)*4;if(g>0)i[l]=Math.round(c/g),i[l+1]=Math.round(h/g),i[l+2]=Math.round(f/g);i[l+3]=Math.round(g/(r*r))}return{width:t,height:e,data:i}}function Us(n,r,t){let e=Math.min(r/n.width,t/n.height),i=Math.max(1,Math.round(n.width*e)),o=Math.max(1,Math.round(n.height*e)),s=Or(n,{x:0,y:0,w:n.width,h:n.height},i,o),u=new Uint8Array(r*t*4),c=Math.floor((r-i)/2),h=Math.floor((t-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:t,data:u}}function Or(n,r,t,e){let i=Math.max(1,Math.floor(Math.min(r.w/t,r.h/e))),o=Gg(n,i),s=o.data,u=new Uint8Array(t*e*4);for(let c=0;c<e;c++){let h=Math.min(o.height-1,Math.max(0,r.y/i+(c+0.5)*r.h/i/e-0.5)),f=Math.floor(h),g=Math.min(o.height-1,f+1),l=h-f;for(let $=0;$<t;$++){let a=Math.min(o.width-1,Math.max(0,r.x/i+($+0.5)*r.w/i/t-0.5)),w=Math.floor(a),F=Math.min(o.width-1,w+1),v=a-w,j=(f*o.width+w)*4,M=(f*o.width+F)*4,p=(g*o.width+w)*4,b=(g*o.width+F)*4,K=(s[j+3]??0)*(1-v)*(1-l),E=(s[M+3]??0)*v*(1-l),J=(s[p+3]??0)*(1-v)*l,S=(s[b+3]??0)*v*l,O=K+E+J+S,R=(c*t+$)*4;if(O>0)for(let A=0;A<3;A++){let Z=(s[j+A]??0)*K+(s[M+A]??0)*E+(s[p+A]??0)*J+(s[b+A]??0)*S;u[R+A]=Math.round(Z/O)}u[R+3]=Math.round(O)}}return{width:t,height:e,data:u}}var Vn={width:2560,height:1550},Og=2560,Lg=0.1,zs=0.15,Qg=0.55,Zg=0.65,Ug=3,qg=er(ze("#19161e","#9b86c8",0.2)),Wg="shelf";function ze(n,r,t){let e=On(n),i=On(r);return`#${e.map((o,s)=>Math.round(o+((i[s]??0)-o)*t).toString(16).padStart(2,"0")).join("")}`}function Xg(n,r){if(r==="background"||r==="foreground"||r==="cursor")return n[r];if(r==="selection"&&n.selection)return n.selection;let t=/^ansi(\d|1[0-5])$/.exec(r),e=t?n.ansi[Number(t[1])]:void 0;if(!e)throw Error(`${n.name} has no slot ${r}`);return e}function qs(n){if(n(1))return 1;let r=0,t=1;for(let e=0;e<40;e++){let i=(r+t)/2;if(n(i))r=i;else t=i}return r}function Ws(n,r){let t=Xg(n,r),i=qs((h)=>we({name:n.name,background:ze(n.background,t,h),foreground:n.foreground,ansi:n.ansi,waive:n.waived??[]}).length===0),o=qs((h)=>er(ze(n.background,t,h))<=qg),s=Math.floor(Math.min(i,o)*1000)/1000,u=On(n.background),c=Math.hypot(...On(t).map((h,f)=>(h-(u[f]??0))*s));return{slot:r,color:t,cap:i,matched:o,opacity:s,reach:c}}function As(n,r){let t=Ws(n,"cursor");if(t.opacity>=Lg)return t;return r.filter((e)=>e!=="cursor"&&e!=="background").map((e)=>Ws(n,e)).reduce((e,i)=>i.reach>e.reach?i:e,t)}function Ae(n,r,t){let e=On(r),i=On(t),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((e[c]??0)+((i[c]??0)-(e[c]??0))*u)}return n}function Vg(n,r,t){let e=On(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*t;for(let c=0;c<3;c++)o[s+c]=Math.round((e[c]??0)*(1-u)+(i[s+c]??0)*u);o[s+3]=255}return{width:n.width,height:n.height,data:o}}function Cs(n){return Zs(n)??{x:0,y:0,w:n.width,h:n.height}}function Ts(n){return Math.min(0.5,(zs+0.5)*(n.w*Vn.height/Vn.width/n.h))}function _s(n,r,t){let e=Math.min(Math.max(0,t*n.h-r/2),n.h-r);return{x:n.x,y:n.y+e,w:n.w,h:r}}function Yg(n,r,t,e){let i=n.w*t/r;if(i<=n.h)return _s(n,i,e);let o=n.h*r/t;return{x:n.x+(n.w-o)/2,y:n.y,w:o,h:n.h}}function Xs(n,r,t){if(n.w*t>n.h*r){let i=n.h*r/t;return{x:n.x+(n.w-i)/2,y:n.y,w:i,h:n.h}}let e=n.w*t/r;return{x:n.x,y:n.y+(n.h-e)/2,w:n.w,h:e}}function Pg(n,r){let t=Math.min(1,Og/Math.max(r.w,r.h));return Or(n,r,Math.round(r.w*t),Math.round(r.h*t))}function Bs(n,r,t,e,i){let o=Qg*n.h,s=n.w*t/r;if(i<Ug||s>o)return{crop:Yg(n,r,t,e),at:{x:0,y:0,w:r,h:t},inset:!1};let u=1-s/o,c=t*(1-zs*u),h=n.w*c/o;return{crop:_s(n,o,e),at:{x:(r-h)*Zg,y:t-c,w:h,h:c},inset:!0}}function xs(n,r,t,e){let i=Math.max(1,Math.round(r.at.w)),o=Math.max(1,Math.round(r.at.h)),s=Or(n,r.crop,i,o),u=new Uint8Array(t*e*4),c=Math.round(r.at.x),h=Math.round(r.at.y);for(let f=0;f<o;f++){let g=h+f,l=Math.max(0,-c),$=Math.min(i,t-c);if(g<0||g>=e||$<=l)continue;u.set(s.data.subarray((f*i+l)*4,(f*i+$)*4),(g*t+c+l)*4)}return{width:t,height:e,data:u}}function zg(n,r,t,e){let i=Bs(r,Vn.width,Vn.height,t,e);return i.inset?xs(n,i,Vn.width,Vn.height):Or(n,i.crop,Vn.width,Vn.height)}function Ds(n,r,t,e,i,o){let s=Cs(n),u=Bs(s,Vn.width,Vn.height,Ts(s),o),c;if(u.inset){let h=Xs({x:0,y:0,w:Vn.width,h:Vn.height},e,i),f=e/h.w;c=xs(n,{...u,at:{x:(u.at.x-h.x)*f,y:(u.at.y-h.y)*f,w:u.at.w*f,h:u.at.h*f}},e,i)}else c=Or(n,Xs(u.crop,e,i),e,i);return Vg(Ae(c,r.background,t.color),r.background,t.opacity)}function Qr(n){return Fn(n,"ttheme","backgrounds")}function Ag(n,r,t,e,i){return[...e?[`# from ${e}`]:[],...i?[`# image ${i}`]:[],`background-image = ${r}`,"background-image-fit = cover","background-image-position = center",`background-image-opacity = ${t}`,`config-file = ?${n}.tune.conf`,`config-file = ?${n}.off.conf`,""].join(`
36
+ `)}function nu(n,r,t){let e=new Map;for(let s of[`${r}.conf`,`${r}.tune.conf`,`${r}.off.conf`]){let u;try{u=Ys(Fn(n,s),"utf8")}catch{if(s===`${r}.conf`)return;continue}for(let c of u.split(`
37
+ `)){let h=/^(background-image(?:-fit|-opacity)?)\s*=\s*(.*?)\s*$/.exec(c);if(h)e.set(h[1],h[2])}}let i=e.get("background-image")??"";if(i==="")return;let o=Number(e.get("background-image-opacity")??1);return{image:i.startsWith("~/")?Fn(t,i.slice(2)):yg(i)?i:Fn(n,i),opacity:Number.isFinite(o)?o:1,cover:e.get("background-image-fit")==="cover"}}function Cg(n,r){for(let t of kr(n))if(Ce(t,r))Lr(Fn(n,t))}function Tg(n){return`${n.site}_${n.id}`}function Vt(n,r){return Fn(n,Wg,r)}function Ce(n,r){let t=n.slice(r.length);return n.startsWith(r)&&(t===".conf"||t===".tune.conf"||t===".off.conf"||/^(\.[0-9a-f]{8})?(@[a-z0-9-]+)?\.png$/.test(t))}function ft(n,r){try{return/^# image (\S+)$/m.exec(Ys(Fn(n,`${r}.conf`),"utf8"))?.[1]}catch{return}}function _g(n,r){try{return kr(Vt(n,r))}catch{return[]}}function ru(n,r){let t=ft(n,r);return[...t?[t]:[],..._g(n,r)].sort()}function tu(n,r){let t=ft(n,r);if(!t)return;let e=Fn(Vt(n,r),t);Lr(e,{recursive:!0,force:!0}),Vs(e,{recursive:!0});for(let i of kr(n))if(Ce(i,r))Ps(Fn(n,i),Fn(e,i.slice(r.length)))}function eu(n,r,t){let e=Fn(Vt(n,r),t);for(let i of kr(e))Ps(Fn(e,i),Fn(n,`${r}${i}`));Lr(e,{recursive:!0})}function iu(n,r,t){try{return kr(Fn(n,"originals")).find((e)=>e.startsWith(`${r}-${t}.`))}catch{return}}function ou(n,r,t){let e=iu(n,r,t);if(e){let i=new Date;Rg(Fn(n,"originals",e),i,i)}}function su(n,r,t){let e=Qr(n),i=ru(e,r),o=ft(e,r);if(!o||i.length<2)throw Error(`${r} has no other image`);let s=(i.indexOf(o)+t+i.length)%i.length,u=i[s];return tu(e,r),eu(e,r,u),ou(e,r,u),{key:u,at:s+1,of:i.length}}function uu(n,r){let t=Qr(n),e=kr(t).filter((h)=>Ce(h,r));if(e.length===0)throw Error(`${r} has no image`);let i=ru(t,r),o=ft(t,r),s=o&&iu(t,r,o);if(s)Lr(Fn(t,"originals",s));for(let h of e)Lr(Fn(t,h));let u=i.filter((h)=>h!==o),c=u[(o?i.indexOf(o):0)%u.length];if(c)eu(t,r,c),ou(t,r,c);return{key:o,left:u.length}}function Bg(n,r,t){if(ft(n,r)!==t)tu(n,r);if(t)Lr(Fn(Vt(n,r),t),{recursive:!0,force:!0});Cg(n,r)}function cu(n,r,t,e,i){let o=Qr(n),s=r.name,u=Tg(i);Vs(Fn(o,"originals"),{recursive:!0}),Bg(o,s,u);let c=Cs(e),h=Ts(c),f=Wt(e),g=yr(Ae(Pg(e,c),r.background,t.color)),l=yr(Ae(zg(e,c,h,f),r.background,t.color)),$=Fn(o,`${s}.${Jg("sha1").update(g).update(l).digest("hex").slice(0,8)}`),a=`${$}.png`,w=`${$}@fill-${Math.round(h*100)}.png`,F=Fn(o,`${s}.conf`),v=Fn(o,"originals",`${s}-${i.site}_${i.id}.${i.ext}`);return Xt(a,g),Xt(w,l),Xt(F,Ag(s,w,t.opacity,i.from,u)),Xt(v,i.bytes),[a,w,F,v]}function hu(n){let r=Fn(Qr(n),"originals"),t=new Map,e;try{e=kr(r)}catch{return new Map}for(let i of e){let o=/^(.+)-([a-z.]+)_(\d+)\.[a-z]+$/.exec(i),[,s,u,c]=o??[];if(!s||!u||!c)continue;let h=Kg(Fn(r,i)).mtimeMs,f=t.get(s);if(!f||h>f.at)t.set(s,{site:u,id:Number(c),at:h})}return new Map([...t].map(([i,{site:o,id:s}])=>[i,{site:o,id:s}]))}import{readdirSync as xg,rmSync as Dg,statSync as nl}from"node:fs";import{setDefaultAutoSelectFamilyAttemptTimeout as rl}from"node:net";import{homedir as tl}from"node:os";import{join as lt}from"node:path";import{setTimeout as el}from"node:timers/promises";var mt=100,Te=25000000,il=536870912,zt=["safe","questionable","explicit"],Mr=["nudity","underwear"],ol={nudity:new Set(["nude","naked","topless","bottomless","nipples","naked_towel","undressing"]),underwear:new Set(["underwear","panties","pantsu","bra","lingerie","pantyshot"])},gt={safe:"s",questionable:"q",explicit:"e"},lu=new Set(["danbooru","gelbooru","konachan","yande.re","sankaku"]),sl=8191,ul=20000,cl=3000,mu=60000,hl=3,fl=`ttheme/${Dn.version} (+${Dn.homepage})`,gl=["orig","tile","thumb","cut"],du=new Map,ll=kl(process.env.TTHEME_FIND_HOSTS),ml=El(process.env.TTHEME_FIND_CUTOUTS);rl(cl);function fu(n){try{return xg(n)}catch{return[]}}function dt(n){return n.startsWith("//")?`https:${n}`:n}function Zr(n){return(/\.([a-z0-9]+)(?:\?.*)?$/i.exec(n)?.[1]??"").toLowerCase()}function _e(n){let r=n.trim();if(!r)return[];let t=JSON.parse(r);if(Array.isArray(t))return t;let e=t.posts;return Array.isArray(e)?e:[]}function dl(n){let r=n.trim(),e=(r?JSON.parse(r):{}).tags??{};return new Map(Object.entries(e).map(([i,o])=>[i,String(o)]))}function Yt(n,r,t){let e=dt(String(n??""));return{file:e,width:Number(r)||0,height:Number(t)||0,ext:Zr(e)}}function Be(n,r){let t=dt(String(r.preview??""));if(!r.file||!t||!Number(n.id))return[];let e=Number(n.width??n.image_width)||0,i=Number(n.height??n.image_height)||0;return[{id:Number(n.id),width:e,height:i,file:r.file,preview:t,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),smaller:r.versions.filter((o)=>o.file&&o.width>0&&o.height>0&&o.width*o.height<e*i)}]}function $l(n,r="https://safebooru.org"){return _e(n).flatMap((t)=>{let e=t.directory&&t.image?`${r}/images/${t.directory}/${t.image}`:"",i=dt(String(t.file_url||e));return Be(t,{preview:t.preview_url,file:i,ext:Zr(i),owner:t.owner,artist:"",md5:t.hash??t.md5,tags:String(t.tags??""),versions:[Yt(t.sample_url,t.sample_width,t.sample_height)]})})}function al(n){let r=dl(n);return _e(n).flatMap((t)=>{let e=dt(String(t.file_url??"")),i=String(t.tags??"");return Be(t,{preview:t.preview_url,file:e,ext:String(t.file_ext||Zr(e)).toLowerCase(),owner:t.author,artist:i.split(/\s+/).find((o)=>r.get(o)==="artist")??"",md5:t.md5,tags:i,versions:[Yt(t.jpeg_url,t.jpeg_width,t.jpeg_height),Yt(t.sample_url,t.sample_width,t.sample_height)]})})}function bl(n){return _e(n).flatMap((r)=>{let t=dt(String(r.file_url??"")),e=r.media_asset??{};return Be(r,{preview:r.preview_file_url,file:t,ext:String(r.file_ext||Zr(t)).toLowerCase(),owner:"",artist:String(r.tag_string_artist??"").split(/\s+/)[0]??"",md5:r.md5,tags:String(r.tag_string??""),versions:(e.variants??[]).map((i)=>Yt(i.url,i.width,i.height)).filter((i)=>i.ext==="jpg"||i.ext==="png").sort((i,o)=>o.width*o.height-i.width*i.height)})})}function $u(n){return Number(/count="(\d+)"/.exec(n)?.[1]??0)}function wl(n){let r=n.trim()?JSON.parse(n):{};return Number(r.counts?.posts)||0}function El(n){let r=new Map;for(let t of(n??"").split(/\s+/).filter(Boolean)){let e=t.indexOf("=");if(e>0)r.set(t.slice(0,e),t.slice(e+1).split(",").filter(Boolean))}return r}function kl(n){let r=new Map;for(let t of(n??"").split(/[\s,]+/).filter(Boolean)){let e=t.indexOf("="),i=t.slice(0,e);try{let o=new URL(t.slice(e+1));if(i&&o.protocol==="https:")r.set(i,o.origin)}catch{}}return r}function au(n,r,t,e){let i=(n??"").split(/\s+/);if(e!==void 0&&i.includes(e))return[];let o=r.filter((s)=>i.includes(s));return o.length>0?o:[...t]}function At(n){return au(n,zt,["safe"])}function Ct(n){return au(n,Mr,Mr,"none")}function xe(n,r,t){return{safe:new Set(n),questionable:new Set(r),explicit:new Set(t)}}function De(n){let r=ll.get(n.key),t=ml.get(n.key);return{...n,origin:r??n.origin,moved:r!==void 0&&r!==n.origin,cutouts:t??n.cutouts,vouched:n.vouched&&t===void 0}}function ni(n,r){if(n.length<2)return n.join("");return r?`( ${n.join(" ~ ")} )`:n.map((t)=>`~${t}`).join(" ")}function Ml(n){let r=De(n),t=(e)=>`${r.origin}/index.php?${new URLSearchParams({page:"dapi",s:"post",q:"index",...e})}`;return{...r,cutouts:ni(r.cutouts,!0),ratings:xe(["safe","general"],["questionable"],["explicit"]),rate:()=>"",best:"sort:score:desc",tagBudget:Number.POSITIVE_INFINITY,postsUrl:(e,i)=>t({json:"1",limit:String(mt),pid:String(i),tags:e}),countUrl:(e)=>t({limit:"0",tags:e}),postUrl:(e)=>t({json:"1",id:String(e)}),pageUrl:(e)=>`${r.origin}/index.php?page=post&s=view&id=${e}`,parse:(e)=>$l(e,r.origin),count:$u}}function gu(n){let r=De(n),t=(e)=>new URLSearchParams({api_version:"2",include_tags:"1",...e});return{...r,cutouts:ni(r.cutouts,!1),ratings:xe([gt.safe],[gt.questionable],[gt.explicit]),rate:(e)=>{let[i]=e;if(e.length===1&&i)return`rating:${gt[i]}`;let o=zt.filter((u)=>!e.includes(u)),[s]=o;return o.length===1&&s?`-rating:${gt[s]}`:""},best:"order:score",tagBudget:Number.POSITIVE_INFINITY,postsUrl:(e,i)=>`${r.origin}/post.json?${t({limit:String(mt),page:String(i+1),tags:e})}`,countUrl:(e)=>`${r.origin}/post.xml?${new URLSearchParams({limit:"1",tags:e})}`,postUrl:(e)=>`${r.origin}/post.json?${t({tags:`id:${e}`})}`,pageUrl:(e)=>`${r.origin}/post/show/${e}`,parse:al,count:$u}}function Fl(n){let r=De(n);return{...r,cutouts:ni(r.cutouts,!1),ratings:xe(["g"],["s","q"],["e"]),rate:()=>"",best:"order:score",tagBudget:2,postsUrl:(t,e)=>`${r.origin}/posts.json?${new URLSearchParams({limit:String(mt),page:String(e+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:bl,count:wl}}function Il(n){return Yn.find((r)=>r.key===n||r.name===n||new URL(r.origin).host===n)}function ri(n){return n.split(/\s+/).filter(Boolean).length}function bu(n,r){let t=n.trim();if(/^\d+$/.test(t))return{site:r,id:Number(t)};let e=/^([\w.]+):(\d+)$/.exec(t);if(e){let u=Yn.find((c)=>c.key===e[1]||c.name===e[1]);return u&&{site:u,id:Number(e[2])}}let i;try{i=new URL(t)}catch{return}let o=Il(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 Yn=[Ml({key:"safebooru",name:"safebooru",origin:"https://safebooru.org",cutouts:["transparent_background","vector_trace"],vouched:!1,ansi:4}),gu({key:"yande",name:"yande.re",origin:"https://yande.re",cutouts:["transparent_png"],vouched:!0,ansi:5}),gu({key:"konachan",name:"konachan",origin:"https://konachan.net",cutouts:["transparent","vector"],vouched:!1,ansi:6}),Fl({key:"danbooru",name:"danbooru",origin:"https://safebooru.donmai.us",cutouts:["transparent_background"],vouched:!1,ansi:2})];function wu(n){let r;try{r=new URL(n).hostname}catch{return""}return r.split(".").slice(-2).join(".")}function Eu(n,r=Mr){return n.tags.filter((t)=>r.some((e)=>ol[e].has(t)))}function ku(n,r,t=["safe"]){return t.some((e)=>n.ratings[e].has(r.rating))}function $t(n){return[n,...n.smaller].find((r)=>r.width*r.height<=Te)}function Mu(n){return lu.has(n)}function Fu(n){let r=new Map;for(let[t,e]of[...n].sort(([i],[o])=>i<o?-1:1)){if(e===""||lu.has(e))continue;r.set(e,[...r.get(e)??[],t])}return r}function Iu(){return lt(process.env.XDG_CACHE_HOME??lt(tl(),".cache"),"ttheme")}function mr(n){return lt(Iu(),n.key)}function vu(n=il,r=Iu()){let t=[],e=0;for(let i of fu(r))for(let o of gl){let s=lt(r,i,o);for(let u of fu(s)){let c=lt(s,u);try{let{size:h,mtimeMs:f}=nl(c);t.push({path:c,size:h,at:f}),e+=h}catch{}}}t.sort((i,o)=>i.at-o.at);for(let i of t){if(e<=n)return;try{Dg(i.path,{force:!0}),e-=i.size}catch{}}}function vl(n,r){if(n!==null&&/^\s*\d+\s*$/.test(n))return Number(n)*1000;let t=n===null?Number.NaN:Date.parse(n);return Number.isNaN(t)?mu:Math.max(0,t-r)}function Pt(n){return du.get(n.key)??0}function pl(n){return(n.headers.get("server")??"").startsWith("cloudflare")&&n.headers.get("cf-mitigated")==="challenge"}async function at(n,r,t,e={},i=ul){for(let o=1;;o++){let s=Pt(n)-Date.now();if(s>0)await el(s,void 0,{signal:t});let u=await fetch(r,{headers:{"User-Agent":fl,Referer:`${n.origin}/`,...e},signal:i?AbortSignal.any([t,AbortSignal.timeout(i)]):t});if(u.status===429&&o<hl){await u.body?.cancel();let c=vl(u.headers.get("retry-after"),Date.now());if(c>mu)throw Error(`${n.name} asks to wait ${Math.ceil(c/1000)}s`);du.set(n.key,Math.max(Pt(n),Date.now()+c));continue}if(!u.ok)throw await u.body?.cancel(),Error(pl(u)?`${n.name} is behind a Cloudflare challenge`:`${n.name} answered ${u.status}`);return u}}async function pu(n,r,t,e){return n.parse(await(await at(n,n.postsUrl(r,t),e)).text())}async function Nu(n,r,t){return n.count(await(await at(n,n.countUrl(r),t)).text())}async function ti(n,r,t){let[e]=n.parse(await(await at(n,n.postUrl(r),t)).text());return e}async function Hu(n,r,t){let e=await at(n,r,t,{Range:`bytes=0-${sl}`});return Pe(new Uint8Array(await e.arrayBuffer()))}async function Su(n,r,t,e){let i=await at(n,r,t,{},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:g,value:l}=await s.read();if(g)break;u.push(l),c+=l.length,e?.(c,o)}let h=new Uint8Array(c),f=0;for(let g of u)h.set(g,f),f+=g.length;return h}import{existsSync as Nl,mkdirSync as Hl,readFileSync as Sl,writeFileSync as jl}from"node:fs";import{dirname as Gl,join as Jl}from"node:path";var ju="https://kecan0406.github.io/ttheme/manifest.json",Kl=20000;function Tt(n){return Jl(n,"ttheme","catalog.json")}function _t(n,r){let t=Tt(n);Hl(Gl(t),{recursive:!0}),jl(t,`${JSON.stringify(r,null,2)}
38
+ `)}function Qn(n){let r=Tt(n);if(!Nl(r))throw Error(`no catalog at ${r} — run \`ttheme init\` first`);return Gu(Sl(r,"utf8"))}function Gu(n){let r;try{r=JSON.parse(n)}catch{throw Error("catalog is not valid JSON")}let t=r;if(typeof t?.version!=="string"||!Array.isArray(t.palettes))throw Error("catalog has no version or palettes");for(let e of t.palettes)if(typeof e?.name!=="string"||!Array.isArray(e.ansi)||e.ansi.length!==16)throw Error(`catalog entry ${JSON.stringify(e?.name)} is missing name or its 16 ANSI colors`);return t}async function Ju(n){let r;try{r=await fetch(n,{signal:AbortSignal.timeout(Kl)})}catch(t){throw Error(`cannot reach the registry at ${n} — ${t instanceof Error?t.message:String(t)}`)}if(!r.ok)throw Error(`registry at ${n} answered ${r.status}`);return Gu(await r.text())}function Ku(n){let r=new Set(n.waived??[]);return Rt.flatMap((t,e)=>{let i=n.gate?.[e];if(r.has(t.rule)||typeof i!=="number")return[];if(t.min!==void 0&&i<t.min)return[`${t.label} ${i} < ${t.min}`];if(t.max!==void 0&&i>t.max)return[`${t.label} ${i} > ${t.max}`];return[]})}function Bt(n,r){let t=n.find((e)=>e.name===r);if(!t)throw Error(`no palette named ${r} in the catalog — \`ttheme list\` shows what is there`);return t}function Ru(n,r){let t=r.toLowerCase();return n.filter((e)=>[e.name,e.group,e.native??"",e.ansiSource].some((i)=>i.toLowerCase().includes(t)))}import{spawn as Rl}from"node:child_process";var yl=30000,Ol=3,Ll=97,Ql=`ObjC.import('Vision')
38
39
  ObjC.import('CoreImage')
39
40
  ObjC.import('CoreGraphics')
40
41
  function run(argv) {
@@ -53,104 +54,104 @@ function run(argv) {
53
54
  $.CIImage.imageWithCVPixelBuffer(buffer), $.NSURL.fileURLWithPath(argv[1]), $.kCIFormatRGBA8,
54
55
  $.CGColorSpaceCreateWithName($.kCGColorSpaceSRGB), $({}), error)
55
56
  if (!written) throw new Error('write failed')
56
- }`;function Ci(){return process.platform==="darwin"}function Iu(n){return n>=wl&&n<=El}function Nu(n,r,t){return new Promise((i,e)=>{let o=al("osascript",["-l","JavaScript","-e",kl,n,r],{stdio:["ignore","ignore","pipe"],signal:AbortSignal.any([t,AbortSignal.timeout(bl)])}),s="";o.stderr.on("data",(u)=>{s+=u}),o.on("error",e),o.on("close",(u)=>{if(u===0){i();return}e(Error(s.trim().split(`
57
- `).at(-1)||`osascript exited ${u}`))})})}var yn={pitch:25,cols:22,rows:9,height:13},Fr={cols:25,rows:16},Ml=2147483648,Fl=-1073741826,vl=1600,Il="\x1B[0m",vr="\x1B[1m",bn="\x1B[2m",$t="\x1B[31m",Mr="\x1B[32m",Yn="\x1B[33m",At="\x1B[1;34m",Nl="\x1B[35m",Hl={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 Hu(n){let r=[],t=0;while(t<n.length){let i=n[t]??"";if(i==="\x1B"){let e=/^(?:\[([0-9;]*)([A-Za-z~])|O([A-Za-z]))/.exec(n.slice(t+1));if(e){r.push(Hl[`${e[1]??""}${e[2]??e[3]??""}`]??"nop"),t+=1+e[0].length;continue}r.push("esc"),t++;continue}r.push(i==="\r"||i===`
58
- `?"enter":i==="\t"?"tab":i==="\x03"?"ctrl-c":i===""||i==="\b"?"backspace":i),t++}return r}function bt(n,r){return{perRow:Math.max(1,Math.floor((n+1)/yn.pitch)),rowsVis:Math.max(1,Math.floor((r-4)/yn.height))}}function Su(n){return`\x1B_Ga=t,t=f,f=100,i=${n.id},q=2;${Buffer.from(n.path).toString("base64")}\x1B\\`}function ju(n){return`\x1B[${n.row+1};${n.col+1}H\x1B_Ga=p,i=${n.id},p=1,c=${n.cols},r=${n.rows},C=1,z=${n.z},q=2\x1B\\`}function pu(n){return`\x1B_Ga=d,d=I,i=${n},q=2\x1B\\`}function Gu(n){return`\x1B[38;2;${Qn(n).join(";")}m`}function Ti(n){return`\x1B[48;2;${Qn(n).join(";")}m`}function rr(n){return Array.from(n).length}class _i{parts=[];cols;constructor(n){this.cols=n}put(n,r,t=""){return this.parts.push({col:n,text:r,sgr:t}),n+rr(r)}run(n,r){let t=n;for(let[i,e]of r)t=this.put(t,i,e);return t}right(n,r){this.run(n-r.reduce((t,[i])=>t+rr(i),0),r)}render(){let n="";for(let{col:r,text:t,sgr:i}of this.parts){if(r>=this.cols||r<0)continue;let e=Array.from(t).slice(0,this.cols-r).join("");n+=`\x1B[${r+1}G${i}${e}${i?Il:""}`}return n}}function Ju(n){return n>=1e6?`${(n/1e6).toFixed(1)} MB`:`${Math.max(1,Math.round(n/1000))} KB`}function Sl(n,r){if(!r)return Ju(n);return r>=1e6?`${(n/1e6).toFixed(1)}/${(r/1e6).toFixed(1)} MB`:`${Math.round(n/1000)}/${Math.round(r/1000)} KB`}function Ku(n){return n.replace(/_\([^)]*\)?$/,"")}function Ru(n){return[`${n.reduced?"↓":""}${n.width}×${n.height}`,Math.max(n.width,n.height)<vl?Yn:bn]}function at(n,r,t,i){let e=[...i.keys??[]],o=i.lead,s=i.right,u=()=>{let f=[...o?[rr(o[0])]:[],...e.map(([l,$])=>rr(l)+1+rr($))];return(i.badge?rr(i.badge)+4:0)+f.reduce((l,$)=>l+$,0)+3*Math.max(0,f.length-1)+(s?3+rr(s[0])+1+rr(s[1]):0)};while(u()>r)if(e.length>2)e.splice(-2,1);else if(s)s=void 0;else if(e.length>1)e.splice(-2,1);else break;if(o&&u()>r){let f=Math.max(0,rr(o[0])-(u()-r)-1);o=[`${Array.from(o[0]).slice(0,f).join("")}…`,o[1]]}let c=0;if(i.badge)c=n.put(0,` ${i.badge} `,`\x1B[7;1m${t}`)+2;if([...o?[[o]]:[],...e.map(([f,g])=>[[f,vr],[` ${g}`,bn]])].forEach((f,g)=>{c=n.run(c+(g?3:0),f)}),s)n.right(r,[[s[0],vr],[` ${s[1]}`,bn]])}function jl(n,r,t,i,e,o){let{ansi:s,selection:u,cursor:c}=o.colors,h=i<44?3:4;if(i>=56)h=Math.min(7,Math.floor((i+1)/8)-1);let f=t;for(let a=0;a<8;a++)f=(n[r]?.put(f,"▀".repeat(h),Gu(s[a]??c)+Ti(s[a+8]??c))??f)+1;let g=["❯ ",Mr],l=[[["~/code/demo",At],[" on ",bn],["main",Nl],[" +2",Mr],[" ~1",Yn]]];if(l.push([g,["git status -sb",""]]),i>=44)l.push([["## ",""],["main",Mr],["...",""],["origin/main",$t],[" [ahead 1]",Yn]]);if(l.push([[" M",$t],[" src/main.rs",""]]),l.push([["??",$t],[" notes.md",""]]),l.push([]),i>=44)l.push([g,["ls",""]]),l.push([["docs",At],[" ",""],["src",At],[" ",""],["tests",At],[" Cargo.toml README.md",""]]),l.push([]);l.push([g,["cargo test",""]]),l.push([[" ✓",Mr],[" parses config",""]]);let $=[[" ✗",$t],[" renders frame",""]];if(i>=44)$.push([" expected ",bn],["3",Mr],[", received ",bn],["2",$t]);l.push($),l.push([]),l.push([g,["echo ",""],["selected text",Ti(u)],[" ",""],[" ",Ti(c)]]),l.forEach((a,w)=>{let F=r+2+w;if(F<=e)n[F]?.run(t,a)})}function pl(n,r,t,i,e,o){n[r]?.put(t,`╭${"─".repeat(e-2)}╮`,o);for(let s=r+1;s<r+i-1;s++)n[s]?.put(t,"│",o),n[s]?.put(t+e-1,"│",o);n[r+i-1]?.put(t,`╰${"─".repeat(e-2)}╯`,o)}function Bi(n,r=n.site){return[` ${r} `,`\x1B[7;${30+n.siteAnsi}m`]}function Gl(n,r,t){let i=Vn.flatMap((o,s)=>{let u=`${o.name}${o.moved?"*":""}`,c=o.name===t.site?Bi(t,u):[` ${u} `,bn];return s?[[" ",""],c]:[c]}),e=i.reduce((o,[s])=>o+rr(s),0)<=r;n.run(0,e?i:[Bi(t)])}function Jl(n,r,t,i){if(t.editing!==void 0){let u=n.run(0,[["⌕ ",i],[t.editing,""],["█",i]]);n.put(u,t.editing?" enter searches":` a tag, a post url or an id — ${t.tag||"esc leaves"}`,bn);return}let e=n.run(0,[["⌕ ",i],[t.tag||"nothing yet — / searches",t.tag?"":bn]]),o=kr.filter((u)=>!t.block.includes(u)),s=[t.preset,t.order,...t.rating.join("+")==="safe"?[]:[t.rating.join("+")],...o.length>0?[`allows ${o.join("+")}`]:[],...t.unblocked?["unblock"]:[]];if(n.put(e,` ${s.join(" ")}`,bn),t.total>0||!t.searching){let u=[[`${t.tiles.length}/${t.checked}`,""]];if(t.checked<t.total)u.push([` of ${t.total}`,bn]);n.right(r,u)}}function Kl(n){if(n.cut==="on")return[[`cut out · ${n.clear}% transparent`,Mr]];if(n.cut==="off")return[["opaque · x cuts out",Yn]];if(n.cut==="failed")return[["opaque · no cut-out",Yn]];return[n.clear>0?[`${n.clear}% transparent`,Mr]:["opaque",Yn]]}function Ou(n){if(n.installing!==void 0)return[`installing ${n.palette} ← ${n.site} ${n.installing}`,Yn];if(n.error)return[n.error,Yn];if(n.waiting!==void 0)return[`${n.site} asked to slow down · ${n.waiting}s`,Yn];if(n.fetching)return[`fetching ${n.fetching.id} · ${Sl(n.fetching.got,n.fetching.size)}`,Yn];if(n.cutting!==void 0)return[`cutting out ${n.cutting}`,Yn];if(n.preparing!==void 0)return[`preparing ${n.preparing}`,Yn];if(n.note)return[n.note,bn];return}function Rl(n,r,t,i,e,o){let{perRow:s,rowsVis:u}=bt(t,i);Jl(n[0],t,e,o),Gl(n[1],t,e);for(let $=0;$<s*u;$++){let a=e.top*s+$,w=e.tiles[a];if(!w)break;let F=2+Math.floor($/s)*yn.height,H=$%s*yn.pitch,J=a===e.focus;if(J)pl(n,F,H,yn.height,yn.pitch-1,o);if(w.thumb)r.push({id:w.id,path:w.thumb,row:F+1,col:H+1,cols:yn.cols,rows:yn.rows,z:-1});if(n[F+10]?.run(H+1,[[String(w.id),J?vr:""],[" ",""],Ru(w)]),w.mates.length>0)n[F+10]?.put(H+yn.cols,"≈",o);let M=w.artist?Ku(w.artist):w.owner&&`@${w.owner}`;if(M)n[F+11]?.put(H+1,M.slice(0,yn.cols-8),bn);let I=[];if(w.score>0)I.push([`★${w.score}`,bn]);if(w.variants>1)I.push([` ×${w.variants}`,o]);if(I.length>0)n[F+11]?.right(H+yn.cols+1,I)}let c=e.top*s,h=e.tiles.length-(e.top+u)*s,f=[...c>0?[`↑ ${c} above`]:[],...h>0?[`↓ ${h} more`]:[]];if(f.length>0)n[i-2]?.put(0,f.join(" "),bn);if(!e.searching&&e.tiles.length===0&&!e.error)n[3]?.put(0,e.preset==="cutouts"?`no transparent cutouts of ${e.tag} on ${e.site} — c searches every post, tab tries ${e.nextSite}`:`no posts of ${e.tag} on ${e.site} — tab tries ${e.nextSite}`,bn);let g=n[i-1],l=Ou(e);if(e.searching&&e.tiles.length===0&&!l){at(g,t,o,{badge:"FIND",lead:[e.preset==="cutouts"?"checking png headers":"fetching posts",bn],right:["esc","back"]});return}at(g,t,o,{badge:"FIND",lead:l,keys:[["←↑↓→","move"],["enter","try on"],["tab","site"],["s","settings"],["/","search"],["?","keys"]],right:["esc","back"]})}function Ol(n,r,t,i,e,o){let s=e.tiles[e.focus];if(!s)return;let u=e.shown?.id===s.id?e.shown:void 0,c=[Bi(e),[" ",""],[String(s.id),vr],[" ",""],Ru(s)];if(s.artist)c.push([` · ${Ku(s.artist)}`,""]);if(s.score>0)c.push([` · ★${s.score}`,bn]);if(u)c.push([` · ${Ju(u.bytes)}`,bn]);if(c.push([` · ${s.owner}`,bn]),s.origin)c.push([` · ${s.origin}`,bn]);if(u)c.push([" ",""],...Kl(u));if(n[0]?.run(0,c),s.mates.length>0)n[0]?.right(t,[["≈ ",o],[s.mates.join(" "),bn]]);if(jl(n,3,2,t-4,i-2,e),e.shown)r.push({id:Ml+e.shown.id,path:e.shown.path,row:0,col:0,cols:t,rows:i,z:Fl});let h=Ou(e);at(n[i-1],t,o,{badge:"TRY",lead:h,keys:e.installing===void 0?[["←→","browse"],["enter","install"],...e.shown?.cut==="on"||e.shown?.cut==="off"?[["x","cut out"]]:[],["?","keys"]]:[],right:e.installing===void 0?["esc","grid"]:void 0})}var Ql={grid:[["move","←↑↓→ home end pgup pgdn"],["try on","enter"],["site",`tab ${Vn.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, 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 yl(n,r,t,i,e){let o=i.panel??0,s=Math.max(...i.settings.map((l)=>l.label.length)),u=Math.max(...i.settings.map((l)=>l.choices.reduce(($,a)=>$+a.length+(l.multi?6:3),0))),c=Math.min(r-2,Math.max(28,s+u+8)),h=i.settings.length+4,f=Math.floor((r-c)/2),g=Math.max(2,Math.floor((t-h)/2));n[g]?.put(f,`╭─ settings ${"─".repeat(Math.max(0,c-13))}╮`);for(let l=g+1;l<g+h-1;l++)n[l]?.put(f,`│${" ".repeat(c-2)}│`);i.settings.forEach((l,$)=>{let a=n[g+2+$];a.put(f+3,l.label,$===o?vr:bn);let w=f+5+s,F=l.value.split(" ");l.choices.forEach((H,J)=>{let M=F.includes(H),I=l.multi&&$===o&&J===l.cursor?"4;":"",b=l.multi?` ${M?"[x]":"[ ]"} ${H} `:` ${H} `;w=a.put(w,b,M?`\x1B[${I}7;${30+i.siteAnsi}m`:I?`\x1B[4m${bn}`:bn)+1})}),n[g+h-1]?.put(f,`╰${"─".repeat(c-2)}╯`),at(n[t-1],r,e,{badge:"SET",keys:[["↑↓","setting"],["←→","value"],["space","toggle"],["enter","save"]],right:["esc","undo"]})}function Zl(n,r,t,i,e){let o=Ql[i.mode],s=Math.min(r-2,50),u=o.length+4,c=Math.floor((r-s)/2),h=Math.max(2,Math.floor((t-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,g],l)=>{n[h+2+l]?.put(c+3,f,vr),n[h+2+l]?.put(c+13,g.slice(0,s-16))}),n[h+u-1]?.put(c,`╰${"─".repeat(s-2)}╯`),at(n[t-1],r,e,{badge:"KEYS",right:["? esc","close"]})}function Qu(n,r,t){let i=Array.from({length:t},()=>new _i(r)),e=[],o=Gu(n.colors.cursor);if(r<Fr.cols||t<Fr.rows)return i[0]?.put(0,"ttheme find",vr+o),i[1]?.put(0,`needs ${Fr.cols}×${Fr.rows} — now ${r}×${t}`),i[2]?.put(0,"esc quits",bn),{lines:i.map((s)=>s.render()),images:e};if(n.mode==="try")Ol(i,e,r,t,n,o);else Rl(i,e,r,t,n,o);if(n.help||n.panel!==void 0){let s=n.mode==="try"?e:[];for(let u=0;u<t;u++)i[u]=new _i(r);if(n.help)Zl(i,r,t,n,o);else yl(i,r,t,n,o);return{lines:i.map((u)=>u.render()),images:s}}return{lines:i.map((s)=>s.render()),images:e}}import{existsSync as te,mkdirSync as xi,readFileSync as yu,rmSync as Zu,writeFileSync as Di}from"node:fs";import{homedir as Lu}from"node:os";import{dirname as ne,join as Tn}from"node:path";var Ll={ghostty:tt,kitty:et,alacritty:rt,iterm2:it};function _n(){return process.env.XDG_CONFIG_HOME??Tn(Lu(),".config")}function Ul(n){return Tn(n,"Library","Application Support","iTerm2","DynamicProfiles","ttheme.json")}function Uu(n){return Tn(n,"ttheme","installed.json")}function Ur(n){let r=Uu(n);if(!te(r))throw Error(`nothing installed yet at ${r} — run \`ttheme init\` first`);let t=JSON.parse(yu(r,"utf8"));if(!Array.isArray(t?.palettes)||!Array.isArray(t.terminals))throw Error(`${r} has no palettes or terminals`);return{terminals:t.terminals.filter((i)=>jt.includes(i)),...t.startup?{startup:t.startup}:{},...t.keepTheme?{keepTheme:!0}:{},palettes:t.palettes}}function Ir(n,r){let t=Uu(n);xi(ne(t),{recursive:!0}),Di(t,`${JSON.stringify(r,null,2)}
59
- `)}function re(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}:{},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 ql(n,r){let t=new Map(n.palettes.map((o)=>[o.name,o])),i=r.filter((o)=>!t.has(o));if(i.length>0)throw Error(`not in the catalog: ${i.join(", ")} — \`ttheme list\` shows what is there`);let e=r.flatMap((o)=>{let s=Fu(t.get(o));return s.length>0?[`${o}: ${s.join(", ")}`]:[]});if(e.length>0)throw Error(`these palettes fail the contrast gate:
60
- ${e.join(`
61
- `)}`);return n.palettes.filter((o)=>r.includes(o.name))}function qu(n,r){return(Ll[n].emit?.(r)??[]).flatMap((t)=>{let[,i,e]=t.path.split("/");return i==="themes"&&e!==void 0?[{file:e,content:t.content}]:[]})}function qr(n){return n.startup&&n.palettes.includes(n.startup)?n.startup:n.palettes[0]}function Wl(n,r,t){let i=Tn(r,"ttheme");if(n==="ghostty")return{file:Tn(r,"ghostty","config"),body:mo(i,t)};if(n==="kitty")return{file:Tn(r,"kitty","kitty.conf"),body:wo(t)};let e=t?Tn(r,"alacritty","themes",`${t}.toml`):void 0;return{file:Tn(r,"alacritty","alacritty.toml"),body:Eo(e)}}function Nr(n,r,t,i=Lu()){let e=ql(r,t.palettes),o=[],s=(h,f)=>{xi(ne(h),{recursive:!0}),Di(h,f),o.push(h)},u=t.keepTheme?void 0:qr(t);for(let h of t.terminals){if(h==="iterm2"){s(Ul(i),so(Jr(e).map(($)=>re($,r))));continue}for(let $ of e)for(let{file:a,content:w}of qu(h,re($,r)))s(Tn(n,h,"themes",a),w);let{file:f,body:g}=Wl(h,n,u),l=te(f)?yu(f,"utf8"):"";if(h==="alacritty"&&l!==""&&!l.includes("# ttheme begin"))continue;xi(ne(f),{recursive:!0}),Di(f,pt(l,g)),o.push(f)}let c=Tn(n,"ttheme","palettes.zsh");return s(c,wi(e)),Zu(`${c}.zwc`,{force:!0}),o}function ie(n,r,t,i){let e=[];for(let o of t)for(let s of r.palettes.filter((u)=>i.includes(u.name)))for(let{file:u}of qu(o,re(s,r))){let c=Tn(n,o,"themes",u);if(te(c))Zu(c,{force:!0}),e.push(c)}return e}import{mkdirSync as Wu,readFileSync as Xu,writeFileSync as Vu}from"node:fs";import{dirname as Yu}from"node:path";import{isMainThread as Xl,parentPort as zu,Worker as Vl}from"node:worker_threads";var Yl={thumb:"tile",show:"view",backdrop:"view"};function zl(n){let r=js(new Uint8Array(Xu(n.from)),qi);if(n.job==="backdrop")return xs(n.home,n.colors,n.tone,r,{...n.origin,bytes:new Uint8Array(Xu(n.source))}),0;if(n.job==="thumb")return Wu(Yu(n.to),{recursive:!0}),Vu(n.to,Qr(Gs(r,n.width,n.height))),0;let t=Qt(r);return Wu(Yu(n.to),{recursive:!0}),Vu(n.to,Qr(Vs(r,n.colors,n.tone,n.width,n.height,t))),t}function Pl(n){n.on("message",(r)=>{try{n.postMessage({id:r.id,value:zl(r)})}catch(t){n.postMessage({id:r.id,error:t instanceof Error?t.message:String(t)})}})}class Pu{worker;next=1;waiting=new Map;send(n){let r=this.next++;return new Promise((t,i)=>{let e=this.open();this.waiting.set(r,{ok:t,no:i}),e.ref(),e.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 Vl(import.meta.filename);n.unref(),n.on("message",({id:t,value:i,error:e})=>{let o=this.waiting.get(t);if(this.waiting.delete(t),this.waiting.size===0)n.unref();if(e!==void 0)o?.no(Error(e));else o?.ok(i)});let r=(t)=>{if(this.worker===n)this.worker=void 0;this.drop(t instanceof Error?t: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 ee{lines=new Map;run(n){let r=Yl[n.job],t=this.lines.get(r);if(!t)t=new Pu,this.lines.set(r,t);return t.send(n)}close(){for(let n of this.lines.values())n.close();this.lines.clear()}}if(!Xl&&zu)Pl(zu);import{connect as Al,createServer as Cl}from"node:net";var Tl=20,Au=22;function oe(n){let r=new Uint8Array(n.reduce((i,e)=>i+e.length,0)),t=0;for(let i of n)r.set(i,t),t+=i.length;return r}function _l(n,r=Tl){let t=n.subarray(5);if(n[0]!==Au||t.length<2)return[n];let i=Math.max(1,Math.min(r,t.length-1)),e=(o)=>oe([Uint8Array.from([n[0],n[1],n[2],o.length>>8,o.length&255]),o]);return[e(t.subarray(0,i)),e(t.subarray(i))]}function Bl(n,r,t,i){let e=Al(t,r,()=>{e.setNoDelay(!0),n.write(`HTTP/1.1 200 Connection Established\r
57
+ }`;function ei(){return process.platform==="darwin"}function yu(n){return n>=Ol&&n<=Ll}function Ou(n,r,t){return new Promise((e,i)=>{let o=Rl("osascript",["-l","JavaScript","-e",Ql,n,r],{stdio:["ignore","ignore","pipe"],signal:AbortSignal.any([t,AbortSignal.timeout(yl)])}),s="";o.stderr.on("data",(u)=>{s+=u}),o.on("error",i),o.on("close",(u)=>{if(u===0){e();return}i(Error(s.trim().split(`
58
+ `).at(-1)||`osascript exited ${u}`))})})}var Ln={pitch:25,cols:22,rows:9,height:13},Ir={cols:25,rows:16},Zl=2147483648,Ul=-1073741826,ql=1600,Wl="\x1B[0m",vr="\x1B[1m",bn="\x1B[2m",bt="\x1B[31m",Fr="\x1B[32m",Pn="\x1B[33m",xt="\x1B[1;34m",Xl="\x1B[35m",Vl={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 Qu(n){let r=[],t=0;while(t<n.length){let e=n[t]??"";if(e==="\x1B"){let i=/^(?:\[([0-9;]*)([A-Za-z~])|O([A-Za-z]))/.exec(n.slice(t+1));if(i){r.push(Vl[`${i[1]??""}${i[2]??i[3]??""}`]??"nop"),t+=1+i[0].length;continue}r.push("esc"),t++;continue}r.push(e==="\r"||e===`
59
+ `?"enter":e==="\t"?"tab":e==="\x03"?"ctrl-c":e===""||e==="\b"?"backspace":e),t++}return r}var Zu="\x1B]1337;ReportCellSize\x07\x1B[16t",Lu="\x1B]1337;ReportCellSize=";function ui(n){let r=n.indexOf(Lu);if(r!==-1){let i=n.slice(r+Lu.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 t=n.indexOf("\x1B[6;"),e=t===-1?null:/^\[6;(\d+);(\d+)t/.exec(n.slice(t+1));if(!e)return null;return{cell:{h:Number(e[1]),w:Number(e[2])},rest:n.slice(0,t)+n.slice(t+1+e[0].length)}}function Et(n,r){return{perRow:Math.max(1,Math.floor((n+1)/Ln.pitch)),rowsVis:Math.max(1,Math.floor((r-4)/Ln.height))}}function Uu(n){return`\x1B_Ga=t,t=f,f=100,i=${n.id},q=2;${Buffer.from(n.path).toString("base64")}\x1B\\`}function qu(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 Wu(n){return`\x1B_Ga=d,d=I,i=${n},q=2\x1B\\`}function Xu(n){return`\x1B[38;2;${On(n).join(";")}m`}function ii(n){return`\x1B[48;2;${On(n).join(";")}m`}function rr(n){return Array.from(n).length}class oi{parts=[];cols;constructor(n){this.cols=n}put(n,r,t=""){return this.parts.push({col:n,text:r,sgr:t}),n+rr(r)}run(n,r){let t=n;for(let[e,i]of r)t=this.put(t,e,i);return t}right(n,r){this.run(n-r.reduce((t,[e])=>t+rr(e),0),r)}render(){let n="";for(let{col:r,text:t,sgr:e}of this.parts){if(r>=this.cols||r<0)continue;let i=Array.from(t).slice(0,this.cols-r).join("");n+=`\x1B[${r+1}G${e}${i}${e?Wl:""}`}return n}}function Vu(n){return n>=1e6?`${(n/1e6).toFixed(1)} MB`:`${Math.max(1,Math.round(n/1000))} KB`}function Yl(n,r){if(!r)return Vu(n);return r>=1e6?`${(n/1e6).toFixed(1)}/${(r/1e6).toFixed(1)} MB`:`${Math.round(n/1000)}/${Math.round(r/1000)} KB`}function Yu(n){return n.replace(/_\([^)]*\)?$/,"")}function Pu(n){return[`${n.reduced?"↓":""}${n.width}×${n.height}`,Math.max(n.width,n.height)<ql?Pn:bn]}function wt(n,r,t,e){let i=[...e.keys??[]],o=e.lead,s=e.right,u=()=>{let f=[...o?[rr(o[0])]:[],...i.map(([l,$])=>rr(l)+1+rr($))];return(e.badge?rr(e.badge)+4:0)+f.reduce((l,$)=>l+$,0)+3*Math.max(0,f.length-1)+(s?3+rr(s[0])+1+rr(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,rr(o[0])-(u()-r)-1);o=[`${Array.from(o[0]).slice(0,f).join("")}…`,o[1]]}let c=0;if(e.badge)c=n.put(0,` ${e.badge} `,`\x1B[7;1m${t}`)+2;if([...o?[[o]]:[],...i.map(([f,g])=>[[f,vr],[` ${g}`,bn]])].forEach((f,g)=>{c=n.run(c+(g?3:0),f)}),s)n.right(r,[[s[0],vr],[` ${s[1]}`,bn]])}function Pl(n,r,t,e,i,o){let{ansi:s,selection:u,cursor:c}=o.colors,h=e<44?3:4;if(e>=56)h=Math.min(7,Math.floor((e+1)/8)-1);let f=t;for(let a=0;a<8;a++)f=(n[r]?.put(f,"▀".repeat(h),Xu(s[a]??c)+ii(s[a+8]??c))??f)+1;let g=["❯ ",Fr],l=[[["~/code/demo",xt],[" on ",bn],["main",Xl],[" +2",Fr],[" ~1",Pn]]];if(l.push([g,["git status -sb",""]]),e>=44)l.push([["## ",""],["main",Fr],["...",""],["origin/main",bt],[" [ahead 1]",Pn]]);if(l.push([[" M",bt],[" src/main.rs",""]]),l.push([["??",bt],[" notes.md",""]]),l.push([]),e>=44)l.push([g,["ls",""]]),l.push([["docs",xt],[" ",""],["src",xt],[" ",""],["tests",xt],[" Cargo.toml README.md",""]]),l.push([]);l.push([g,["cargo test",""]]),l.push([[" ✓",Fr],[" parses config",""]]);let $=[[" ✗",bt],[" renders frame",""]];if(e>=44)$.push([" expected ",bn],["3",Fr],[", received ",bn],["2",bt]);l.push($),l.push([]),l.push([g,["echo ",""],["selected text",ii(u)],[" ",""],[" ",ii(c)]]),l.forEach((a,w)=>{let F=r+2+w;if(F<=i)n[F]?.run(t,a)})}function zl(n,r,t,e,i,o){n[r]?.put(t,`╭${"─".repeat(i-2)}╮`,o);for(let s=r+1;s<r+e-1;s++)n[s]?.put(t,"│",o),n[s]?.put(t+i-1,"│",o);n[r+e-1]?.put(t,`╰${"─".repeat(i-2)}╯`,o)}function si(n,r=n.site){return[` ${r} `,`\x1B[7;${30+n.siteAnsi}m`]}function Al(n,r,t){let e=Yn.flatMap((o,s)=>{let u=`${o.name}${o.moved?"*":""}`,c=o.name===t.site?si(t,u):[` ${u} `,bn];return s?[[" ",""],c]:[c]}),i=e.reduce((o,[s])=>o+rr(s),0)<=r;n.run(0,i?e:[si(t)])}function Cl(n,r,t,e){if(t.editing!==void 0){let u=n.run(0,[["⌕ ",e],[t.editing,""],["█",e]]);n.put(u,t.editing?" enter searches":` a tag, a post url or an id — ${t.tag||"esc leaves"}`,bn);return}let i=n.run(0,[["⌕ ",e],[t.tag||"nothing yet — / searches",t.tag?"":bn]]),o=Mr.filter((u)=>!t.block.includes(u)),s=[t.preset,t.order,...t.rating.join("+")==="safe"?[]:[t.rating.join("+")],...o.length>0?[`allows ${o.join("+")}`]:[],...t.unblocked?["unblock"]:[]];if(n.put(i,` ${s.join(" ")}`,bn),t.total>0||!t.searching){let u=[[`${t.tiles.length}/${t.checked}`,""]];if(t.checked<t.total)u.push([` of ${t.total}`,bn]);n.right(r,u)}}function Tl(n){if(n.cut==="on")return[[`cut out · ${n.clear}% transparent`,Fr]];if(n.cut==="off")return[["opaque · x cuts out",Pn]];if(n.cut==="failed")return[["opaque · no cut-out",Pn]];return[n.clear>0?[`${n.clear}% transparent`,Fr]:["opaque",Pn]]}function zu(n){if(n.installing!==void 0)return[`installing ${n.palette} ← ${n.site} ${n.installing}`,Pn];if(n.error)return[n.error,Pn];if(n.waiting!==void 0)return[`${n.site} asked to slow down · ${n.waiting}s`,Pn];if(n.fetching)return[`fetching ${n.fetching.id} · ${Yl(n.fetching.got,n.fetching.size)}`,Pn];if(n.cutting!==void 0)return[`cutting out ${n.cutting}`,Pn];if(n.preparing!==void 0)return[`preparing ${n.preparing}`,Pn];if(n.note)return[n.note,bn];return}function _l(n,r,t,e,i,o){let{perRow:s,rowsVis:u}=Et(t,e);Cl(n[0],t,i,o),Al(n[1],t,i);for(let $=0;$<s*u;$++){let a=i.top*s+$,w=i.tiles[a];if(!w)break;let F=2+Math.floor($/s)*Ln.height,v=$%s*Ln.pitch,j=a===i.focus;if(j)zl(n,F,v,Ln.height,Ln.pitch-1,o);if(w.thumb)r.push({id:w.id,path:w.thumb,row:F+1,col:v+1,cols:Ln.cols,rows:Ln.rows,z:-1});if(n[F+10]?.run(v+1,[[String(w.id),j?vr:""],[" ",""],Pu(w)]),w.mates.length>0)n[F+10]?.put(v+Ln.cols,"≈",o);let M=w.artist?Yu(w.artist):w.owner&&`@${w.owner}`;if(M)n[F+11]?.put(v+1,M.slice(0,Ln.cols-8),bn);let p=[];if(w.score>0)p.push([`★${w.score}`,bn]);if(w.variants>1)p.push([` ×${w.variants}`,o]);if(p.length>0)n[F+11]?.right(v+Ln.cols+1,p)}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[e-2]?.put(0,f.join(" "),bn);if(!i.searching&&i.tiles.length===0&&!i.error)n[3]?.put(0,i.preset==="cutouts"?`no transparent cutouts of ${i.tag} on ${i.site} — c searches every post, tab tries ${i.nextSite}`:`no posts of ${i.tag} on ${i.site} — tab tries ${i.nextSite}`,bn);let g=n[e-1],l=zu(i);if(i.searching&&i.tiles.length===0&&!l){wt(g,t,o,{badge:"FIND",lead:[i.preset==="cutouts"?"checking png headers":"fetching posts",bn],right:["esc","back"]});return}wt(g,t,o,{badge:"FIND",lead:l,keys:[["←↑↓→","move"],["enter","try on"],["tab","site"],["s","settings"],["/","search"],["?","keys"]],right:["esc","back"]})}function Bl(n,r,t,e,i,o){let s=i.tiles[i.focus];if(!s)return;let u=i.shown?.id===s.id?i.shown:void 0,c=[si(i),[" ",""],[String(s.id),vr],[" ",""],Pu(s)];if(s.artist)c.push([` · ${Yu(s.artist)}`,""]);if(s.score>0)c.push([` · ★${s.score}`,bn]);if(u)c.push([` · ${Vu(u.bytes)}`,bn]);if(c.push([` · ${s.owner}`,bn]),s.origin)c.push([` · ${s.origin}`,bn]);if(u)c.push([" ",""],...Tl(u));if(n[0]?.run(0,c),s.mates.length>0)n[0]?.right(t,[["≈ ",o],[s.mates.join(" "),bn]]);if(Pl(n,3,2,t-4,e-2,i),i.shown)r.push({id:Zl+i.shown.id,path:i.shown.path,row:0,col:0,cols:t,rows:e,z:Ul});let h=zu(i);wt(n[e-1],t,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 xl={grid:[["move","←↑↓→ home end pgup pgdn"],["try on","enter"],["site",`tab ${Yn.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, 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 Dl(n,r,t,e,i){let o=e.panel??0,s=Math.max(...e.settings.map((l)=>l.label.length)),u=Math.max(...e.settings.map((l)=>l.choices.reduce(($,a)=>$+a.length+(l.multi?6:3),0))),c=Math.min(r-2,Math.max(28,s+u+8)),h=e.settings.length+4,f=Math.floor((r-c)/2),g=Math.max(2,Math.floor((t-h)/2));n[g]?.put(f,`╭─ settings ${"─".repeat(Math.max(0,c-13))}╮`);for(let l=g+1;l<g+h-1;l++)n[l]?.put(f,`│${" ".repeat(c-2)}│`);e.settings.forEach((l,$)=>{let a=n[g+2+$];a.put(f+3,l.label,$===o?vr:bn);let w=f+5+s,F=l.value.split(" ");l.choices.forEach((v,j)=>{let M=F.includes(v),p=l.multi&&$===o&&j===l.cursor?"4;":"",b=l.multi?` ${M?"[x]":"[ ]"} ${v} `:` ${v} `;w=a.put(w,b,M?`\x1B[${p}7;${30+e.siteAnsi}m`:p?`\x1B[4m${bn}`:bn)+1})}),n[g+h-1]?.put(f,`╰${"─".repeat(c-2)}╯`),wt(n[t-1],r,i,{badge:"SET",keys:[["↑↓","setting"],["←→","value"],["space","toggle"],["enter","save"]],right:["esc","undo"]})}function nm(n,r,t,e,i){let o=xl[e.mode],s=Math.min(r-2,50),u=o.length+4,c=Math.floor((r-s)/2),h=Math.max(2,Math.floor((t-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,g],l)=>{n[h+2+l]?.put(c+3,f,vr),n[h+2+l]?.put(c+13,g.slice(0,s-16))}),n[h+u-1]?.put(c,`╰${"─".repeat(s-2)}╯`),wt(n[t-1],r,i,{badge:"KEYS",right:["? esc","close"]})}function Au(n,r,t){let e=Array.from({length:t},()=>new oi(r)),i=[],o=Xu(n.colors.cursor);if(r<Ir.cols||t<Ir.rows)return e[0]?.put(0,"ttheme find",vr+o),e[1]?.put(0,`needs ${Ir.cols}×${Ir.rows} — now ${r}×${t}`),e[2]?.put(0,"esc quits",bn),{lines:e.map((s)=>s.render()),images:i};if(n.mode==="try")Bl(e,i,r,t,n,o);else _l(e,i,r,t,n,o);if(n.help||n.panel!==void 0){let s=n.mode==="try"?i:[];for(let u=0;u<t;u++)e[u]=new oi(r);if(n.help)nm(e,r,t,n,o);else Dl(e,r,t,n,o);return{lines:e.map((u)=>u.render()),images:s}}return{lines:e.map((s)=>s.render()),images:i}}import{execFileSync as rm}from"node:child_process";import{existsSync as ci,mkdirSync as Dt,readFileSync as Tu,rmSync as _u,writeFileSync as ne}from"node:fs";import{homedir as hi}from"node:os";import{dirname as re,join as Tn}from"node:path";var tm={ghostty:it,kitty:st,alacritty:et,iterm2:ot},Cu="ttheme-default";function Ur(n=process.env.TTHEME_ITERM_SUITE??"com.googlecode.iterm2"){let r=(t,e)=>rm(t,e,{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:(t)=>{if(process.platform==="darwin")r("defaults",["write",n,"Default Bookmark Guid","-string",t])},running:()=>{try{return r("pgrep",["-x","iTerm2"])!==""}catch{return!1}}}}function qr(n){return n.keepTheme?void 0:Wr(n)}function kt(n,r){if(!n.terminals.includes("iterm2"))return n;let t=r.read();return t&&!t.startsWith("ttheme-")?{...n,itermBase:t}:n}function Mt(n,r){if(!n.terminals.includes("iterm2"))return!1;let t=r.read(),e=qr(n)?Cu:t===Cu?n.itermBase:void 0;if(!e||e===t)return!1;return r.write(e),!0}function _n(){return process.env.XDG_CONFIG_HOME??Tn(hi(),".config")}function Bu(n){return Tn(n,"Library","Application Support","iTerm2","DynamicProfiles","ttheme.json")}function xu(n){return Tn(n,"ttheme","installed.json")}function sr(n){let r=xu(n);if(!ci(r))throw Error(`nothing installed yet at ${r} — run \`ttheme init\` first`);let t=JSON.parse(Tu(r,"utf8"));if(!Array.isArray(t?.palettes)||!Array.isArray(t.terminals))throw Error(`${r} has no palettes or terminals`);return{terminals:t.terminals.filter((e)=>yt.includes(e)),...t.startup?{startup:t.startup}:{},...t.keepTheme?{keepTheme:!0}:{},...t.itermBase?{itermBase:t.itermBase}:{},palettes:t.palettes}}function Ft(n,r){let t=xu(n);Dt(re(t),{recursive:!0}),ne(t,`${JSON.stringify(r,null,2)}
60
+ `)}function fi(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}:{},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 Du(n,r){let t=new Map(n.palettes.map((o)=>[o.name,o])),e=r.filter((o)=>!t.has(o));if(e.length>0)throw Error(`not in the catalog: ${e.join(", ")} — \`ttheme list\` shows what is there`);let i=r.flatMap((o)=>{let s=Ku(t.get(o));return s.length>0?[`${o}: ${s.join(", ")}`]:[]});if(i.length>0)throw Error(`these palettes fail the contrast gate:
61
+ ${i.join(`
62
+ `)}`);return n.palettes.filter((o)=>r.includes(o.name))}function nc(n,r){return(tm[n].emit?.(r)??[]).flatMap((t)=>{let[,e,i]=t.path.split("/");return e==="themes"&&i!==void 0?[{file:i,content:t.content}]:[]})}function Wr(n){return n.startup&&n.palettes.includes(n.startup)?n.startup:n.palettes[0]}function em(n,r,t){let e=Tn(r,"ttheme");if(n==="ghostty")return{file:Tn(r,"ghostty","config"),body:Io(e,t)};if(n==="kitty")return{file:Tn(r,"kitty","kitty.conf"),body:Ho(t)};let i=t?Tn(r,"alacritty","themes",`${t}.toml`):void 0;return{file:Tn(r,"alacritty","alacritty.toml"),body:So(i)}}function rc(n,r,t,e,i){let o=Qr(n),s=t.map((h)=>fi(h,r)),u=new Map;for(let h of s){let f=nu(o,h.name,i);if(f)u.set(h.name,f)}let c=new Set(Gr(t).map((h)=>h.name));return ao(s.filter((h)=>c.has(h.name)),u,s.find((h)=>h.name===qr(e)),e.itermBase)}function Xr(n,r=hi()){let t=sr(n);if(!t.terminals.includes("iterm2"))return;let e=Qn(n),i=Bu(r);Dt(re(i),{recursive:!0}),ne(i,rc(n,e,Du(e,t.palettes),t,r))}function It(n,r,t,e=hi()){let i=Du(r,t.palettes),o=[],s=(h,f)=>{Dt(re(h),{recursive:!0}),ne(h,f),o.push(h)},u=qr(t);for(let h of t.terminals){if(h==="iterm2"){s(Bu(e),rc(n,r,i,t,e));continue}for(let $ of i)for(let{file:a,content:w}of nc(h,fi($,r)))s(Tn(n,h,"themes",a),w);let{file:f,body:g}=em(h,n,u),l=ci(f)?Tu(f,"utf8"):"";if(h==="alacritty"&&l!==""&&!l.includes("# ttheme begin"))continue;Dt(re(f),{recursive:!0}),ne(f,Ot(l,g)),o.push(f)}let c=Tn(n,"ttheme","palettes.zsh");return s(c,Ne(i,u,t.terminals)),_u(`${c}.zwc`,{force:!0}),o}function gi(n,r,t,e){let i=[];for(let o of t)for(let s of r.palettes.filter((u)=>e.includes(u.name)))for(let{file:u}of nc(o,fi(s,r))){let c=Tn(n,o,"themes",u);if(ci(c))_u(c,{force:!0}),i.push(c)}return i}import{mkdirSync as tc,readFileSync as ec,writeFileSync as ic}from"node:fs";import{dirname as oc}from"node:path";import{isMainThread as im,parentPort as sc,Worker as om}from"node:worker_threads";var sm={thumb:"tile",show:"view",backdrop:"view"};function um(n){let r=Qs(new Uint8Array(ec(n.from)),Te);if(n.job==="backdrop")return cu(n.home,n.colors,n.tone,r,{...n.origin,bytes:new Uint8Array(ec(n.source))}),0;if(n.job==="thumb")return tc(oc(n.to),{recursive:!0}),ic(n.to,yr(Us(r,n.width,n.height))),0;let t=Wt(r);return tc(oc(n.to),{recursive:!0}),ic(n.to,yr(Ds(r,n.colors,n.tone,n.width,n.height,t))),t}function cm(n){n.on("message",(r)=>{try{n.postMessage({id:r.id,value:um(r)})}catch(t){n.postMessage({id:r.id,error:t instanceof Error?t.message:String(t)})}})}class uc{worker;next=1;waiting=new Map;send(n){let r=this.next++;return new Promise((t,e)=>{let i=this.open();this.waiting.set(r,{ok:t,no:e}),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 om(import.meta.filename);n.unref(),n.on("message",({id:t,value:e,error:i})=>{let o=this.waiting.get(t);if(this.waiting.delete(t),this.waiting.size===0)n.unref();if(i!==void 0)o?.no(Error(i));else o?.ok(e)});let r=(t)=>{if(this.worker===n)this.worker=void 0;this.drop(t instanceof Error?t: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 li{lines=new Map;run(n){let r=sm[n.job],t=this.lines.get(r);if(!t)t=new uc,this.lines.set(r,t);return t.send(n)}close(){for(let n of this.lines.values())n.close();this.lines.clear()}}if(!im&&sc)cm(sc);import{connect as hm,createServer as fm}from"node:net";var gm=20,cc=22;function mi(n){let r=new Uint8Array(n.reduce((e,i)=>e+i.length,0)),t=0;for(let e of n)r.set(e,t),t+=e.length;return r}function lm(n,r=gm){let t=n.subarray(5);if(n[0]!==cc||t.length<2)return[n];let e=Math.max(1,Math.min(r,t.length-1)),i=(o)=>mi([Uint8Array.from([n[0],n[1],n[2],o.length>>8,o.length&255]),o]);return[i(t.subarray(0,e)),i(t.subarray(e))]}function mm(n,r,t,e){let i=hm(t,r,()=>{i.setNoDelay(!0),n.write(`HTTP/1.1 200 Connection Established\r
62
63
  \r
63
- `);let o=i,s=!1,u=(c)=>{if(s){e.write(c);return}if(o=oe([o,c]),o.length<5)return;let h=o[3]*256+o[4];if(o[0]!==Au){s=!0,e.write(o);return}if(o.length<5+h)return;s=!0;let[f,g]=_l(o.subarray(0,5+h));e.write(f),setTimeout(()=>{if(g)e.write(g);e.write(o.subarray(5+h))},10)};if(n.on("data",u),o.length>0){let c=o;o=new Uint8Array(0),u(c)}e.pipe(n)});e.on("error",()=>n.destroy()),n.on("error",()=>e.destroy())}function xl(n){n.setNoDelay(!0);let r=new Uint8Array(0),t=(i)=>{r=oe([r,i]);let e=Buffer.from(r).toString("latin1"),o=e.indexOf(`\r
64
+ `);let o=e,s=!1,u=(c)=>{if(s){i.write(c);return}if(o=mi([o,c]),o.length<5)return;let h=o[3]*256+o[4];if(o[0]!==cc){s=!0,i.write(o);return}if(o.length<5+h)return;s=!0;let[f,g]=lm(o.subarray(0,5+h));i.write(f),setTimeout(()=>{if(g)i.write(g);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()),n.on("error",()=>i.destroy())}function dm(n){n.setNoDelay(!0);let r=new Uint8Array(0),t=(e)=>{r=mi([r,e]);let i=Buffer.from(r).toString("latin1"),o=i.indexOf(`\r
64
65
  \r
65
- `);if(o===-1)return;n.off("data",t);let s=/^CONNECT ([^ :]+):(\d+)/.exec(e);if(!s){n.end(`HTTP/1.1 405 Method Not Allowed\r
66
+ `);if(o===-1)return;n.off("data",t);let s=/^CONNECT ([^ :]+):(\d+)/.exec(i);if(!s){n.end(`HTTP/1.1 405 Method Not Allowed\r
66
67
  \r
67
- `);return}Bl(n,s[1],Number(s[2]),r.subarray(o+4))};n.on("data",t),n.on("error",()=>n.destroy())}function Cu(){let n=Cl(xl);return new Promise((r,t)=>{n.once("error",t),n.listen(0,"127.0.0.1",()=>{r({port:n.address().port,close:()=>{n.close(),n.unref()}})})})}var Xr=[{name:"TTHEME_FIND_RATING",label:"rating",choices:Wt,multi:{read:Xt}},{name:"TTHEME_FIND_BLOCK",label:"block",choices:kr,multi:{read:Vt,none:"none"}},{name:"TTHEME_FIND_POSTS",label:"posts",choices:["all","cutouts"]},{name:"TTHEME_FIND_ORDER",label:"order",choices:["newest","score"]},{name:"TTHEME_FIND_SETS",label:"sets",choices:["fold","show"]},...Ci()?[{name:"TTHEME_FIND_REMOVE_BG",label:"remove bg",choices:["on","off"]}]:[]];function t0(n,r){if(n.multi)return n.multi.read(r).join(" ")||n.multi.none;return n.choices.find((t)=>t===r)??n.choices[0]}var _u=12,i0=12,e0=2,o0=150,s0=30,u0=1280,c0=2;function ue(n,r){return{key:n,groups:[],sources:[],queue:[],seen:new Set,checked:0,total:0,focus:0,top:0,searching:r}}function le(n){if(!(n instanceof Error))return String(n);if(n instanceof AggregateError&&n.errors[0])return le(n.errors[0]);if(n.cause)return le(n.cause);let r=n.code;if(typeof r==="string")return r;let t=(n.message||n.name).split(".")[0]??"";return t.length>56?`${t.slice(0,55)}…`:t}function Bu(n,r){return`${n.name}: ${le(r)}`}function h0(n){let r=n.lastIndexOf("\x1B");return r!==-1&&/^\[?[0-9;]*$/.test(n.slice(r+1))}function ce(n,r){try{return JSON.parse(Du(sr(lr(n),r),"utf8"))}catch{return{}}}function he(n,r,t){fe(lr(n),{recursive:!0}),ge(sr(lr(n),r),`${JSON.stringify(t)}
68
- `)}class nc{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;siteIndex=0;values=new Map(Xr.map((n)=>[n.name,t0(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 ee;sent=new Map;placed=new Map;current;fetch;settle;partial;input="";probeWait;done;dirty=!1;scratch=Dl(sr(r0(),"ttheme-find-"));home;catalog;entry;constructor(n,r,t,i){this.home=n,this.catalog=r,this.entry=t,this.tone=Zs(t,t.signatureSlots),this.view={palette:t.name,tag:i,site:this.site.name,siteAnsi:this.site.ansi,nextSite:this.nextSite.name,preset:this.setting("TTHEME_FIND_POSTS")==="all"?"all":"cutouts",order:this.setting("TTHEME_FIND_ORDER")==="score"?"score":"newest",rating:Xt(this.setting("TTHEME_FIND_RATING")),block:Vt(this.setting("TTHEME_FIND_BLOCK")),sets:this.setting("TTHEME_FIND_SETS")==="show"?"show":"fold",unblocked:process.env.TTHEME_FIND_PROXY!==void 0,settings:Xr.map((e)=>({label:e.label,choices:[...e.choices],value:this.setting(e.name),multi:e.multi&&{none:e.multi.none},cursor:0})),colors:{cursor:t.cursor,selection:t.selection,ansi:t.ansi},tiles:[],checked:0,total:0,searching:i!=="",focus:0,top:0,mode:"grid",help:!1,editing:i===""?"":void 0},this.board=ue(this.boardKey,i!==""),this.boards.set(this.board.key,this.board)}get signal(){return this.session.signal}get site(){return Vn[this.siteIndex]}get nextSite(){return Vn[(this.siteIndex+1)%Vn.length]}setting(n){return this.values.get(n)}get boardKey(){return`${this.site.key}|${this.view.preset}|${this.view.order}`}mark(n,r){return`${n.key}:${r}`}origPath(n,r,t){return sr(lr(n),"orig",`${r}.${t}`)}tileOf(n,r,t){let i=mt(r)??r;return{id:r.id,width:i.width,height:i.height,reduced:i!==r,owner:gu(r.owner)?"":r.owner,artist:r.artist,score:r.score,variants:t,origin:cu(r.source),mates:this.owners.get(n.key)?.get(r.owner)??[],thumb:this.thumbPath.get(this.mark(n,r.id))}}show(){let n=this.site,r=this.view,t=this.board;r.tiles=t.groups.flatMap((i)=>i.open?i.posts.map((e)=>this.tileOf(n,e,0)):[this.tileOf(n,i.posts[0],i.posts.length)]),r.checked=t.checked,r.total=t.total,r.searching=t.searching,r.note=t.note,r.focus=Math.max(0,Math.min(t.focus,r.tiles.length-1)),r.top=t.top}syncSite(){let n=this.view;n.site=this.site.name,n.siteAnsi=this.site.ansi,n.nextSite=this.nextSite.name}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[J");let t=new Promise((s)=>{this.done=s}),i=setInterval(this.onClock,250),e=await this.probe();if(e){if(this.cell=e,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 t;return this.session.abort(),this.fetch?.abort(),clearTimeout(this.settle),clearTimeout(this.partial),clearInterval(i),n.off("data",this.onData),r.off("resize",this.onResize),this.write("\x1B_Ga=d,d=A,q=2\x1B\\\x1B[H\x1B[J"),n.setRawMode(!1),n.pause(),this.saveProbes(),this.renders.close(),se(this.scratch,{recursive:!0,force:!0}),du(),o}write(n){process.stdout.write(n)}finish(n){this.done?.(n)}probe(){return new Promise((n)=>{let r=setTimeout(()=>{this.probeWait=void 0,n(null)},1000);this.probeWait=(t)=>{clearTimeout(r),this.probeWait=void 0,n(t)},this.write("\x1B[16t")})}onData=(n)=>{if(this.input+=n.toString("utf8"),this.probeWait){let r=this.input.indexOf("\x1B[6;"),t=r===-1?null:/^\[6;(\d+);(\d+)t/.exec(this.input.slice(r+1));if(!t)return;this.input=this.input.slice(0,r)+this.input.slice(r+1+t[0].length),this.probeWait({h:Number(t[1]),w:Number(t[2])})}if(clearTimeout(this.partial),h0(this.input)){this.partial=setTimeout(this.flushKeys,s0);return}this.flushKeys()};flushKeys=()=>{let n=Hu(this.input);this.input="";for(let r of n)this.key(r)};onClock=()=>{let n=Math.ceil((qt(this.site)-Date.now())/1000),r=n>0?n:void 0;if(r!==this.view.waiting)this.view.waiting=r,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.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<Fr.cols||this.rows<Fr.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:t,rowsVis:i}=bt(this.cols,this.rows),o={left:-1,right:1,up:-t,down:t,pgup:-t*i,pgdn:t*i,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.siteIndex=(this.siteIndex+1)%Vn.length,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,t=r.panel??0,i=r.settings[t];if(n==="up"||n==="down"){r.panel=Math.max(0,Math.min(r.settings.length-1,t+(n==="up"?-1:1))),this.draw();return}if((n==="left"||n==="right")&&i){let e=n==="left"?-1:1;if(i.multi)i.cursor=(i.cursor+e+i.choices.length)%i.choices.length;else{let o=i.choices.indexOf(i.value);i.value=i.choices[(o+e+i.choices.length)%i.choices.length]}this.draw();return}if(n===" "&&i?.multi){let e=i.value.split(" "),o=i.choices.filter((u,c)=>c===i.cursor?!e.includes(u):e.includes(u)),s=i.multi.none;if(o.length>0||s!==void 0)i.value=o.length>0?o.join(" "):s,this.draw();return}if(n==="esc"){r.settings.forEach((e,o)=>{e.value=this.setting(Xr[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=Xr.map((i)=>this.setting(i.name));n.settings.forEach((i,e)=>{let o=Xr[e];if(o)this.values.set(o.name,i.value)});let t=Xr.filter((i,e)=>this.setting(i.name)!==r[e]);if(t.length===0){this.draw();return}this.save(t),n.rating=Xt(this.setting("TTHEME_FIND_RATING")),n.block=Vt(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=this.setting("TTHEME_FIND_ORDER")==="score"?"score":"newest",this.boards.clear(),this.current=void 0,n.shown=void 0,n.mode="grid",this.search()}save(n){let r=sr(this.home,"ttheme","config.zsh");try{let t=Wr(r)?Du(r,"utf8"):"",i=n.reduce((e,o)=>Gt(e,o.name,this.setting(o.name)),t);ge(r,i)}catch(t){this.view.error=t instanceof Error?t.message:String(t)}}editKey(n){let r=this.view,t=r.editing??"";if(n==="esc"){if(r.editing=void 0,r.tag===""){this.finish(2);return}this.draw();return}if(n==="enter"){if(r.editing=void 0,t.trim()){this.commit(t.trim());return}if(r.tag===""){this.finish(2);return}this.draw();return}if(n==="backspace"){r.editing=t.slice(0,-1),this.draw();return}if(n.length===1&&n>=" ")r.editing=t+n,this.draw()}async commit(n){let r=uu(n,this.site);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 t=++this.gen;this.siteIndex=Vn.indexOf(n),this.syncSite(),this.current=void 0,this.view.shown=void 0,this.view.error=void 0;let i=ue(`${n.key}|post:${r}`,!0);this.board=i,this.boards.set(i.key,i),this.show(),this.draw();try{let e=await Ai(n,r,this.signal);if(t!==this.gen)return;if(i.searching=!1,!e)i.error=`${n.name} has no post ${r}`,this.view.error=i.error;else this.posts.set(this.mark(n,e.id),e),i.groups=[{posts:[e],open:!1}],i.checked=1,i.total=1,this.thumbQueue.push({site:n,post:e}),this.thumbs(),this.view.mode="try";if(this.show(),e)this.select();this.draw()}catch(e){this.fail(t,e)}}async turn(){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 t of this.board.groups){let i=t.open?t.posts.length:1;if(n.focus<r+i){if(t.posts.length<2)return;t.open=!t.open,this.board.focus=r;for(let e of t.posts)if(!this.thumbPath.has(this.mark(this.site,e.id)))this.thumbQueue.push({site:this.site,post:e});this.thumbs(),this.show(),this.scroll(),this.draw();return}r+=i}}openPage(){let n=this.view.tiles[this.view.focus];if(!n)return;let r=process.platform==="darwin"?"open":"xdg-open";try{xu(r,[this.site.pageUrl(n.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 t=Math.max(0,Math.min(r.tiles.length-1,n));if(t===r.focus)return;if(r.focus=t,this.board.focus=t,this.scroll(),this.pump(),r.mode==="try")this.select();this.draw()}scroll(){let n=this.view,{perRow:r,rowsVis:t}=bt(this.cols,this.rows),i=Math.floor(n.focus/r);if(i<n.top)n.top=i;if(i>n.top+t-1)n.top=i-t+1;this.board.top=n.top}query(n){let r=this.view,t=[r.tag,n.rate(this.view.rating),r.preset==="cutouts"?n.cutouts:"",r.order==="score"?n.best:""].filter(Boolean),i=[],e=[];for(let o of t)if(Pi([...i,o].join(" "))<=n.tagBudget)i.push(o);else e.push(o);return this.board.note=e.length>0?`${n.name} takes ${n.tagBudget} tags — ${e.join(" ")} left out`:void 0,i.join(" ")}async search(){let n=++this.gen,r=this.site,t=ue(this.boardKey,!0);this.board=t,this.boards.set(t.key,t),this.view.error=void 0,this.show(),this.draw();let i=this.query(r);this.tally(n,r,t,i);try{let e=await this.mateOwners(r);if(n!==this.gen)return;let o=Pi(i)+1<=r.tagBudget;t.sources=[...o?[...e.keys()].map((s)=>({tags:`${i} user:${s}`,page:0,done:!1})):[],{tags:i,page:0,done:!1}],this.show(),this.draw(),await this.pump()}catch(e){this.fail(n,e)}}async tally(n,r,t,i){try{let e=await au(r,i,this.signal);if(n===this.gen)t.total=e,this.show(),this.draw()}catch{}}fail(n,r){if(n!==this.gen||this.signal.aborted)return;this.board.error=Bu(this.site,r),this.board.searching=!1,this.view.error=this.board.error,this.show(),this.draw()}wants(){let{perRow:n,rowsVis:r}=bt(this.cols,this.rows);return this.view.tiles.length<(this.board.top+r+c0)*n}async nextPage(n,r,t){let i=r.sources.find((o)=>!o.done);if(!i)return;let e=await $u(n,i.tags,i.page,this.signal);if(t!==this.gen)return;i.page++,i.done=e.length<gt;for(let o of e)if(!r.seen.has(o.id))r.seen.add(o.id),r.queue.push(o)}async pump(){let n=this.gen,r=this.board;if(this.pumping===n||r.sources.length===0)return;this.pumping=n;let t=this.site,i=[],e;try{r.searching=!0;while(n===this.gen){while(i.length<_u&&r.queue.length>0&&this.wants()){let u=r.queue.shift();i.push({post:u,passed:this.passes(t,u)})}if(!e&&r.queue.length<_u&&r.sources.some((u)=>!u.done)&&this.wants()){let u=this.nextPage(t,r,n).then(()=>{if(e===u)e=void 0});u.catch(()=>{}),e=u}let o=i.shift();if(!o){if(!e)break;await e;continue}let s=await o.passed;if(n!==this.gen)return;if(r.checked++,s)this.admit(t,o.post);this.show(),this.draw()}if(n===this.gen)r.searching=!1,this.show(),this.draw()}catch(o){this.fail(n,o)}finally{if(this.saveProbes(),this.pumping===n)this.pumping=0}}async passes(n,r){let t=mt(r);if(!fu(n,r,this.view.rating)||hu(r,this.view.block).length>0||!t)return!1;if(this.view.preset==="all")return["png","jpg","jpeg"].includes(t.ext);if(r.ext!=="png")return!1;return n.vouched||this.transparent(n,r)}probes(n){let r=this.probed.get(n.key);if(!r)r=ce(n,"probes.json"),this.probed.set(n.key,r);return r}async transparent(n,r){let t=this.probes(n),i=t[r.id];if(i!==void 0)return i;try{let e=(await bu(n,r.file,this.signal))?.alpha===!0;return t[r.id]=e,this.unsaved.add(n.key),e}catch{return!1}}saveProbes(){for(let n of this.unsaved){let r=Vn.find((t)=>t.key===n);if(r)he(r,"probes.json",this.probes(r))}this.unsaved.clear()}admit(n,r){this.posts.set(this.mark(n,r.id),r);let t=this.view.sets==="fold"?this.board.groups.at(-1):void 0,i=t?.posts[0],e=r.owner||r.artist;if(t&&i&&e&&(i.owner||i.artist)===e&&i.width===r.width&&i.height===r.height){if(t.posts.push(r),t.open)this.thumbQueue.push({site:n,post:r}),this.thumbs();return}this.board.groups.push({posts:[r],open:!1}),this.thumbQueue.push({site:n,post:r}),this.thumbs()}async mateOwners(n){let r=this.owners.get(n.key);if(r)return r;let t=Ds(this.home),i=ce(n,"owners.json"),e=this.catalog.palettes.flatMap((c)=>{let h=t.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(e.map(async(c)=>{let h=i[c.id];if(h!==void 0)return{...c,owner:h};try{return{...c,owner:(await Ai(n,c.id,this.signal))?.owner??""}}catch{return}})),s=new Map;for(let c of o)if(c)i[c.id]=c.owner,s.set(c.name,c.owner);he(n,"owners.json",i);let u=lu(s);return this.owners.set(n.key,u),u}async cached(n,r,t,i){if(Wr(r))return n0(r).size;let e=this.inflight.get(r);if(e)return e;let o=(async()=>{let s=await wu(n,t,this.signal,i);return fe(Tu(r),{recursive:!0}),ge(r,s),s.length})();this.inflight.set(r,o);try{return await o}finally{this.inflight.delete(r)}}thumbs(){while(this.thumbing<i0&&this.thumbQueue.length>0){let{site:n,post:r}=this.thumbQueue.shift();this.thumbing++,this.thumb(n,r).catch(()=>{}).finally(()=>{this.thumbing--,this.thumbs()})}}async thumb(n,r){let t=yn.cols*this.cell.w,i=yn.rows*this.cell.h,e=sr(lr(n),"tile",`${r.id}-${t}x${i}.png`);if(!Wr(e)){let o=sr(lr(n),"thumb",`${r.id}.${Lr(r.preview)}`);await this.cached(n,o,r.preview),await this.renders.run({job:"thumb",from:o,to:e,width:t,height:i})}this.thumbPath.set(this.mark(n,r.id),e),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?.id===r.id){this.reveal();return}this.settle=setTimeout(()=>void this.load(r),o0),this.draw()}async load(n){let r=this.view,t=this.posts.get(this.mark(this.site,n.id)),i=t&&mt(t);if(!i)return;let e=this.site,o=new AbortController;this.fetch=o;try{let s=this.origPath(e,n.id,i.ext);if(!Wr(s))r.fetching={id:n.id,got:0,size:0},this.draw();let u=await this.cached(e,s,i.file,(f,g)=>{if(r.fetching?.id===n.id)r.fetching={id:n.id,got:f,size:g},this.draw()});if(o.signal.aborted)return;if(r.fetching=void 0,e!==this.site)return;let c={site:e,id:n.id,path:s,ext:i.ext,size:u,using:"plain",failed:!1};r.preparing=n.id,this.flush();let h=await this.render(c,"plain");if(o.signal.aborted||e!==this.site)return;if(h.clear===0&&Ci()&&this.setting("TTHEME_FIND_REMOVE_BG")!=="off"){if(r.preparing=void 0,r.cutting=n.id,this.flush(),c.cut=await this.cutOut(e,n.id,s,o.signal),o.signal.aborted||e!==this.site)return;if(r.cutting=void 0,c.cut){r.preparing=n.id,this.flush();let f=await this.render(c,"cut").catch(()=>{return});if(o.signal.aborted||e!==this.site)return;if(f&&Iu(f.clear))c.using="cut";else se(c.cut,{force:!0}),c.cut=void 0,c.failed=!0}else c.failed=!0}if(this.current=c,r.tiles[r.focus]?.id===n.id)await this.present();this.preload()}catch(s){if(!o.signal.aborted&&!this.signal.aborted)r.error=Bu(e,s)}finally{if(r.fetching?.id===n.id)r.fetching=void 0;if(r.preparing===n.id)r.preparing=void 0;if(r.cutting===n.id)r.cutting=void 0;this.draw()}}async cutOut(n,r,t,i){let e=sr(lr(n),"cut",`${r}.png`);if(Wr(e))return e;try{return fe(Tu(e),{recursive:!0}),await Nu(t,e,i),e}catch{se(e,{force:!0});return}}swap(){let n=this.current;if(!n?.cut||this.view.shown?.id!==n.id)return;n.using=n.using==="cut"?"plain":"cut",this.reveal()}preload(){let n=this.view;if(n.mode!=="try")return;let r=this.site;for(let t of[n.focus+this.direction,n.focus-this.direction]){if(this.prefetching>=e0)return;let i=n.tiles[t],e=i&&this.posts.get(this.mark(r,i.id)),o=e&&mt(e);if(!o)continue;let s=this.origPath(r,e.id,o.ext);this.prefetching++,this.cached(r,s,o.file).then(()=>this.render({site:r,id:e.id,path:s,ext:o.ext,size:0,using:"plain",failed:!1},"plain")).catch(()=>{}).finally(()=>{this.prefetching--})}}async render(n,r){let t=this.cols*this.cell.w,i=this.rows*this.cell.h,e=Math.min(t,u0),o=Math.max(1,Math.round(i*e/t)),s=sr(this.scratch,`${n.site.key}-${n.id}${r==="cut"?"c":""}-${e}x${o}.png`),u=`${n.site.key}:${n.id}:${r}`,c=this.clarity.get(u);if(c!==void 0&&Wr(s))return{clear:c,path:s};let h=await this.renders.run({job:"show",from:r==="cut"?n.cut:n.path,to:s,width:e,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:t,path:i}=await this.render(n,r);if(this.current!==n||n.using!==r)return;this.view.shown={id:n.id,clear:t,bytes:n.size,path:i,cut:n.cut?r==="cut"?"on":"off":n.failed?"failed":"none"}}reveal(){let n=this.view;n.preparing=this.current?.id,this.flush(),this.present().catch((r)=>{n.error=r instanceof Error?r.message:String(r)}).finally(()=>{if(n.preparing===this.current?.id)n.preparing=void 0;this.draw()})}async install(){let n=this.view,r=n.tiles[n.focus],t=this.current;if(!r||t?.id!==r.id||n.preparing!==void 0||n.shown?.id!==r.id)return;n.installing=r.id,n.error=void 0,this.flush();try{await this.renders.run({job:"backdrop",from:t.using==="cut"?t.cut:t.path,source:t.path,home:this.home,colors:this.entry,tone:this.tone,origin:{site:t.site.key,id:t.id,ext:t.ext,from:`${t.site.name} ${t.id} ${t.site.pageUrl(t.id)}`}});let i=ce(t.site,"owners.json");i[t.id]=this.posts.get(this.mark(t.site,t.id))?.owner??"",he(t.site,"owners.json",i),process.stderr.write(`background · ${this.entry.name} ← ${t.site.name} ${t.id}
69
- `),this.finish(0)}catch(i){n.installing=void 0,n.error=i instanceof Error?i.message:String(i),this.draw()}}draw(){if(this.dirty)return;this.dirty=!0,setImmediate(()=>{this.dirty=!1,this.flush()})}flush(){let n=Qu(this.view,this.cols,this.rows),r="\x1B[?2026h";n.lines.forEach((i,e)=>{r+=`\x1B[${e+1};1H\x1B[K${i}`});let t=new Set;for(let i of n.images){if(t.add(i.id),this.sent.get(i.id)!==i.path)r+=Su(i),this.sent.set(i.id,i.path),this.placed.delete(i.id);let e=`${i.row};${i.col};${i.cols};${i.rows};${i.z}`;if(this.placed.get(i.id)!==e)r+=ju(i),this.placed.set(i.id,e)}for(let i of this.sent.keys())if(!t.has(i))r+=pu(i),this.sent.delete(i),this.placed.delete(i);this.write(`${r}\x1B[?2026l`)}}function f0(){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 g0(){if(!f0())return process.stderr.write(`unblock needs node 22.21 or newer — this is ${process.versions.node}
70
- `),1;let n=await Cu(),r=xu(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}`,TTHEME_FIND_PROXY:String(n.port)}}),t=await new Promise((i)=>r.on("exit",(e)=>i(e??1)));return n.close(),t}async function rc(n){if(process.env.TTHEME_FIND_UNBLOCK==="1"&&!process.env.TTHEME_FIND_PROXY)return g0();let r=_n(),t=Cn(r),i=Pt(t.palettes,n);if(!process.stdin.isTTY||!process.stdout.isTTY)throw Error("ttheme find needs a terminal");return new nc(r,t,i,i.booru??"").run()}function tc(n,r){let t=_n();if(Pt(Cn(t).palettes,n),r==="next"||r==="prev"){let{key:i,at:e,of:o}=_s(t,n,r==="next"?1:-1);return process.stderr.write(`background · ${n} ${e}/${o} ${i}
71
- `),0}if(r==="drop"){let{key:i,left:e}=Bs(t,n);return process.stderr.write(`background · ${n} removed ${i??"the picture"} · ${e} left
72
- `),0}throw Error(`unknown image action ${r} — next, prev or drop`)}import{chmodSync as lm,copyFileSync as mm,existsSync as cr,mkdirSync as Re,readdirSync as dm,readFileSync as kt,rmSync as th,writeFileSync as ih}from"node:fs";import{homedir as $m}from"node:os";import{dirname as Et,join as wn}from"node:path";import{styleText as Ee}from"node:util";import{stdout as kc,stdin as S0}from"node:process";import j0 from"node:readline";var ic=(()=>{let n=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(r)=>{let t=0;n.lastIndex=0;while(n.test(r))t+=1;return r.length-t}})(),ec=(n)=>{return n===12288||n>=65281&&n<=65376||n>=65504&&n<=65510},oc=(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 l0=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,m0=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,sc=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,d0=/\t{1,1000}/y,uc=/[\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,$0=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,a0=/\p{M}+/gu,b0={limit:1/0,ellipsis:""},cc=(n,r={},t={})=>{let i=r.limit??1/0,e=r.ellipsis??"",o=r?.ellipsisWidth??(e?cc(e,b0,t).width:0),s=0,u=t.controlWidth??0,c=t.tabWidth??8,h=t.emojiWidth??2,f=2,g=t.regularWidth??1,l=t.wideWidth??2,$=[[$0,g],[l0,0],[m0,u],[d0,c],[uc,h],[sc,l]],a=0,w=0,F=n.length,H=0,J=!1,M=F,I=Math.max(0,i-o),b=0,K=0,E=0,G=0;n:while(!0){if(K>b||w>=F&&w>a){let j=n.slice(b,K)||n.slice(a,w);H=0;for(let Q of j.replaceAll(a0,"")){let R=Q.codePointAt(0)||0;if(ec(R))G=2;else if(oc(R))G=l;else G=g;if(E+G>I)M=Math.min(M,Math.max(b,a)+H);if(E+G>i){J=!0;break n}H+=Q.length,E+=G}b=K=0}if(w>=F)break n;for(let j=0,Q=$.length;j<Q;j++){let[R,A]=$[j];if(R.lastIndex=w,R.test(n)){if(H=R===sc?ic(n.slice(w,R.lastIndex)):R===uc?1:R.lastIndex-w,G=H*A,E+G>I)M=Math.min(M,w+Math.floor((I-E)/A));if(E+G>i){J=!0;break n}E+=G,b=a,K=w,w=a=R.lastIndex;continue n}}w+=1}return{width:J?I:E,index:J?M:F,truncated:J,ellipsed:J&&i>=o}},hc=cc;var w0={limit:1/0,ellipsis:"",ellipsisWidth:0},E0=(n,r={})=>{return hc(n,w0,r).width},Rn=E0;var Ct="\x1B",dc="›",k0=39,de="\x07",$c="[",M0="]",ac="m",$e=`${M0}8;;`,fc=new RegExp(`(?:\\${$c}(?<code>\\d+)m|\\${$e}(?<uri>.*)${de})`,"y"),gc=(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},lc=(n)=>`${Ct}${$c}${n}${ac}`,mc=(n)=>`${Ct}${$e}${n}${de}`,me=(n,r,t)=>{let i=r[Symbol.iterator](),e=!1,o=!1,s=n.at(-1),u=s===void 0?0:Rn(s),c=i.next(),h=i.next(),f=0;while(!c.done){let g=c.value,l=Rn(g);if(u+l<=t)n[n.length-1]+=g;else n.push(g),u=0;if(g===Ct||g===dc)e=!0,o=r.startsWith($e,f+1);if(e){if(o){if(g===de)e=!1,o=!1}else if(g===ac)e=!1}else if(u+=l,u===t&&!h.done)n.push(""),u=0;c=h,h=i.next(),f+=g.length}if(s=n.at(-1),!u&&s!==void 0&&s.length&&n.length>1)n[n.length-2]+=n.pop()},F0=(n)=>{let r=n.split(" "),t=r.length;while(t){if(Rn(r[t-1]))break;t--}if(t===r.length)return n;return r.slice(0,t).join(" ")+r.slice(t).join("")},v0=(n,r,t={})=>{if(t.trim!==!1&&n.trim()==="")return"";let i="",e,o,s=n.split(" "),u=[""],c=0;for(let g=0;g<s.length;g++){let l=s[g];if(t.trim!==!1){let a=u.at(-1)??"",w=a.trimStart();if(a.length!==w.length)u[u.length-1]=w,c=Rn(w)}if(g!==0){if(c>=r&&(t.wordWrap===!1||t.trim===!1))u.push(""),c=0;if(c||t.trim===!1)u[u.length-1]+=" ",c++}let $=Rn(l);if(t.hard&&$>r){let a=r-c,w=1+Math.floor(($-a-1)/r);if(Math.floor(($-1)/r)<w)u.push("");me(u,l,r),c=Rn(u.at(-1)??"");continue}if(c+$>r&&c&&$){if(t.wordWrap===!1&&c<r){me(u,l,r),c=Rn(u.at(-1)??"");continue}u.push(""),c=0}if(c+$>r&&t.wordWrap===!1){me(u,l,r),c=Rn(u.at(-1)??"");continue}u[u.length-1]+=l,c+=$}if(t.trim!==!1)u=u.map((g)=>F0(g));let h=u.join(`
73
- `),f=!1;for(let g=0;g<h.length;g++){let l=h[g];if(i+=l,!f){if(f=l>="\uD800"&&l<="\uDBFF",f)continue}else f=!1;if(l===Ct||l===dc){fc.lastIndex=g+1;let a=fc.exec(h)?.groups;if(a?.code!==void 0){let w=Number.parseFloat(a.code);e=w===k0?void 0:w}else if(a?.uri!==void 0)o=a.uri.length===0?void 0:a.uri}if(h[g+1]===`
74
- `){if(o)i+=mc("");let $=e?gc(e):void 0;if(e&&$)i+=lc($)}else if(l===`
75
- `){if(e&&gc(e))i+=lc(e);if(o)i+=mc(o)}}return i},I0=/\r?\n/;function mr(n,r,t){return String(n).normalize().split(I0).map((i)=>v0(i,r,t)).join(`
76
- `)}var Zn=Nt(be(),1);function ur(n,r,t){if(!t.some((s)=>!s.disabled))return n;let i=n+r,e=Math.max(t.length-1,0),o=i<0?e:i>e?0:i;return t[o]?.disabled?ur(o,r<0?-1:1,t):o}function Tt(n,r,t,i){let e=i.split(`
77
- `),o=0,s=n;for(let c of e){if(s<=c.length)break;s-=c.length+1,o++}for(o=Math.max(0,Math.min(e.length-1,o+t)),s=Math.min(s,e[o].length)+r;s<0&&o>0;)o--,s+=e[o].length+1;for(;s>e[o].length&&o<e.length-1;)s-=e[o].length+1,o++;s=Math.max(0,Math.min(e[o].length,s));let u=0;for(let c=0;c<o;c++)u+=e[c].length+1;return u+s}var p0=["up","down","left","right","space","enter","cancel"],G0=["January","February","March","April","May","June","July","August","September","October","November","December"],On={actions:new Set(p0),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:[...G0],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 Mc(n,r){if(typeof n=="string")return On.aliases.get(n)===r;for(let t of n)if(t!==void 0&&Mc(t,r))return!0;return!1}function J0(n,r){if(n===r)return;let t=n.split(`
78
- `),i=r.split(`
79
- `),e=Math.max(t.length,i.length),o=[];for(let s=0;s<e;s++)t[s]!==i[s]&&o.push(s);return{lines:o,numLinesBefore:t.length,numLinesAfter:i.length,numLines:e}}var ha=globalThis.process.platform.startsWith("win"),ke=Symbol("clack:cancel");function Vr(n){return n===ke}function _t(n,r){let t=n;t.isTTY&&t.setRawMode(r)}var xt=(n)=>("columns"in n)&&typeof n.columns=="number"?n.columns:80,Fe=(n)=>("rows"in n)&&typeof n.rows=="number"?n.rows:20;function dr(n,r,t,i=t,e=t,o){let s=xt(n??kc);return mr(r,s-t.length,{hard:!0,trim:!1}).split(`
80
- `).map((u,c,h)=>{let f=o?o(u,c):u;return c===0?`${i}${f}`:c===h.length-1?`${e}${f}`:`${t}${f}`}).join(`
81
- `)}function Fc(n,r){if("~standard"in n){let t=n["~standard"].validate(r);if(t instanceof Promise)throw TypeError("Schema validation must be synchronous. Update `validate()` and remove any asynchronous logic.");return t.issues?.at(0)?.message}return n(r)}class tr{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:t=S0,output:i=kc,render:e,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=e.bind(this),this._track=r,this._abortSignal=o,this.input=t,this.output=i}unsubscribe(){this._subscribers.clear()}setSubscriber(n,r){let t=this._subscribers.get(n)??[];t.push(r),this._subscribers.set(n,t)}on(n,r){this.setSubscriber(n,{cb:r})}once(n,r){this.setSubscriber(n,{cb:r,once:!0})}emit(n,...r){let t=this._subscribers.get(n)??[],i=[];for(let e of t)e.cb(...r),e.once&&i.push(()=>t.splice(t.indexOf(e),1));for(let e of i)e()}prompt(){return new Promise((n)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),n(ke);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=j0.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),_t(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),_t(this.input,!1),n(this.value)}),this.once("cancel",()=>{this.output.write(Zn.cursor.show),this.output.off("resize",this.render),_t(this.input,!1),n(ke)})})}_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&&On.aliases.has(r.name)&&this.emit("cursor",On.aliases.get(r.name)),On.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 t=Fc(this.opts.validate,this.value);t&&(this.error=t instanceof Error?t.message:t,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}Mc([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(`
82
- `),_t(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let n=mr(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
83
- `).length-1;this.output.write(Zn.cursor.move(-999,n*-1))}render(){let n=mr(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=J0(this._prevFrame,n),t=Fe(this.output);if(this.restoreCursor(),r){let i=Math.max(0,r.numLinesAfter-t),e=Math.max(0,r.numLinesBefore-t),o=r.lines.find((s)=>s>=i);if(o===void 0){this._prevFrame=n;return}if(r.lines.length===1){this.output.write(Zn.cursor.move(0,o-e)),this.output.write(Zn.erase.lines(1));let s=n.split(`
84
- `);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(i<e)o=i;else{let u=o-e;u>0&&this.output.write(Zn.cursor.move(0,u))}this.output.write(Zn.erase.down());let s=n.split(`
68
+ `);return}mm(n,s[1],Number(s[2]),r.subarray(o+4))};n.on("data",t),n.on("error",()=>n.destroy())}function hc(){let n=fm(dm);return new Promise((r,t)=>{n.once("error",t),n.listen(0,"127.0.0.1",()=>{r({port:n.address().port,close:()=>{n.close(),n.unref()}})})})}var Yr=[{name:"TTHEME_FIND_RATING",label:"rating",choices:zt,multi:{read:At}},{name:"TTHEME_FIND_BLOCK",label:"block",choices:Mr,multi:{read:Ct,none:"none"}},{name:"TTHEME_FIND_POSTS",label:"posts",choices:["all","cutouts"]},{name:"TTHEME_FIND_ORDER",label:"order",choices:["newest","score"]},{name:"TTHEME_FIND_SETS",label:"sets",choices:["fold","show"]},...ei()?[{name:"TTHEME_FIND_REMOVE_BG",label:"remove bg",choices:["on","off"]}]:[]];function wm(n,r){if(n.multi)return n.multi.read(r).join(" ")||n.multi.none;return n.choices.find((t)=>t===r)??n.choices[0]}var gc=12,Em=12,km=2,Mm=150,Fm=30,Im=1280,vm=2;function $i(n,r){return{key:n,groups:[],sources:[],queue:[],seen:new Set,checked:0,total:0,focus:0,top:0,searching:r}}function ki(n){if(!(n instanceof Error))return String(n);if(n instanceof AggregateError&&n.errors[0])return ki(n.errors[0]);if(n.cause)return ki(n.cause);let r=n.code;if(typeof r==="string")return r;let t=(n.message||n.name).split(".")[0]??"";return t.length>56?`${t.slice(0,55)}…`:t}function lc(n,r){return`${n.name}: ${ki(r)}`}function pm(n){let r=n.lastIndexOf("\x1B");return r!==-1&&/^\[?[0-9;]*$/.test(n.slice(r+1))}function ai(n,r){try{return JSON.parse(dc(ur(mr(n),r),"utf8"))}catch{return{}}}function bi(n,r,t){wi(mr(n),{recursive:!0}),Ei(ur(mr(n),r),`${JSON.stringify(t)}
69
+ `)}class $c{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;siteIndex=0;values=new Map(Yr.map((n)=>[n.name,wm(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 li;sent=new Map;placed=new Map;current;fetch;settle;partial;input="";probeWait;done;dirty=!1;scratch=$m(ur(bm(),"ttheme-find-"));home;catalog;entry;constructor(n,r,t,e){this.home=n,this.catalog=r,this.entry=t,this.tone=As(t,t.signatureSlots),this.view={palette:t.name,tag:e,site:this.site.name,siteAnsi:this.site.ansi,nextSite:this.nextSite.name,preset:this.setting("TTHEME_FIND_POSTS")==="all"?"all":"cutouts",order:this.setting("TTHEME_FIND_ORDER")==="score"?"score":"newest",rating:At(this.setting("TTHEME_FIND_RATING")),block:Ct(this.setting("TTHEME_FIND_BLOCK")),sets:this.setting("TTHEME_FIND_SETS")==="show"?"show":"fold",unblocked:process.env.TTHEME_FIND_PROXY!==void 0,settings:Yr.map((i)=>({label:i.label,choices:[...i.choices],value:this.setting(i.name),multi:i.multi&&{none:i.multi.none},cursor:0})),colors:{cursor:t.cursor,selection:t.selection,ansi:t.ansi},tiles:[],checked:0,total:0,searching:e!=="",focus:0,top:0,mode:"grid",help:!1,editing:e===""?"":void 0},this.board=$i(this.boardKey,e!==""),this.boards.set(this.board.key,this.board)}get signal(){return this.session.signal}get site(){return Yn[this.siteIndex]}get nextSite(){return Yn[(this.siteIndex+1)%Yn.length]}setting(n){return this.values.get(n)}get boardKey(){return`${this.site.key}|${this.view.preset}|${this.view.order}`}mark(n,r){return`${n.key}:${r}`}origPath(n,r,t){return ur(mr(n),"orig",`${r}.${t}`)}tileOf(n,r,t){let e=$t(r)??r;return{id:r.id,width:e.width,height:e.height,reduced:e!==r,owner:Mu(r.owner)?"":r.owner,artist:r.artist,score:r.score,variants:t,origin:wu(r.source),mates:this.owners.get(n.key)?.get(r.owner)??[],thumb:this.thumbPath.get(this.mark(n,r.id))}}show(){let n=this.site,r=this.view,t=this.board;r.tiles=t.groups.flatMap((e)=>e.open?e.posts.map((i)=>this.tileOf(n,i,0)):[this.tileOf(n,e.posts[0],e.posts.length)]),r.checked=t.checked,r.total=t.total,r.searching=t.searching,r.note=t.note,r.focus=Math.max(0,Math.min(t.focus,r.tiles.length-1)),r.top=t.top}syncSite(){let n=this.view;n.site=this.site.name,n.siteAnsi=this.site.ansi,n.nextSite=this.nextSite.name}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 t=new Promise((s)=>{this.done=s}),e=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 t;return this.session.abort(),this.fetch?.abort(),clearTimeout(this.settle),clearTimeout(this.partial),clearInterval(e),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(),di(this.scratch,{recursive:!0,force:!0}),vu(),o}write(n){process.stdout.write(n)}finish(n){this.done?.(n)}probe(){return new Promise((n)=>{let r=setTimeout(()=>{this.probeWait=void 0,n(null)},1000);this.probeWait=(t)=>{clearTimeout(r),this.probeWait=void 0,n(t)},this.write(Zu)})}onData=(n)=>{this.input+=n.toString("utf8");for(let r=ui(this.input);r;r=ui(this.input))this.input=r.rest,this.probeWait?.(r.cell);if(this.probeWait)return;if(clearTimeout(this.partial),pm(this.input)){this.partial=setTimeout(this.flushKeys,Fm);return}this.flushKeys()};flushKeys=()=>{let n=Qu(this.input);this.input="";for(let r of n)this.key(r)};onClock=()=>{let n=Math.ceil((Pt(this.site)-Date.now())/1000),r=n>0?n:void 0;if(r!==this.view.waiting)this.view.waiting=r,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.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<Ir.cols||this.rows<Ir.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:t,rowsVis:e}=Et(this.cols,this.rows),o={left:-1,right:1,up:-t,down:t,pgup:-t*e,pgdn:t*e,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.siteIndex=(this.siteIndex+1)%Yn.length,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,t=r.panel??0,e=r.settings[t];if(n==="up"||n==="down"){r.panel=Math.max(0,Math.min(r.settings.length-1,t+(n==="up"?-1:1))),this.draw();return}if((n==="left"||n==="right")&&e){let i=n==="left"?-1:1;if(e.multi)e.cursor=(e.cursor+i+e.choices.length)%e.choices.length;else{let o=e.choices.indexOf(e.value);e.value=e.choices[(o+i+e.choices.length)%e.choices.length]}this.draw();return}if(n===" "&&e?.multi){let i=e.value.split(" "),o=e.choices.filter((u,c)=>c===e.cursor?!i.includes(u):i.includes(u)),s=e.multi.none;if(o.length>0||s!==void 0)e.value=o.length>0?o.join(" "):s,this.draw();return}if(n==="esc"){r.settings.forEach((i,o)=>{i.value=this.setting(Yr[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=Yr.map((e)=>this.setting(e.name));n.settings.forEach((e,i)=>{let o=Yr[i];if(o)this.values.set(o.name,e.value)});let t=Yr.filter((e,i)=>this.setting(e.name)!==r[i]);if(t.length===0){this.draw();return}this.save(t),n.rating=At(this.setting("TTHEME_FIND_RATING")),n.block=Ct(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=this.setting("TTHEME_FIND_ORDER")==="score"?"score":"newest",this.boards.clear(),this.current=void 0,n.shown=void 0,n.mode="grid",this.search()}save(n){let r=ur(this.home,"ttheme","config.zsh");try{let t=Vr(r)?dc(r,"utf8"):"",e=n.reduce((i,o)=>Lt(i,o.name,this.setting(o.name)),t);Ei(r,e)}catch(t){this.view.error=t instanceof Error?t.message:String(t)}}editKey(n){let r=this.view,t=r.editing??"";if(n==="esc"){if(r.editing=void 0,r.tag===""){this.finish(2);return}this.draw();return}if(n==="enter"){if(r.editing=void 0,t.trim()){this.commit(t.trim());return}if(r.tag===""){this.finish(2);return}this.draw();return}if(n==="backspace"){r.editing=t.slice(0,-1),this.draw();return}if(n.length===1&&n>=" ")r.editing=t+n,this.draw()}async commit(n){let r=bu(n,this.site);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 t=++this.gen;this.siteIndex=Yn.indexOf(n),this.syncSite(),this.current=void 0,this.view.shown=void 0,this.view.error=void 0;let e=$i(`${n.key}|post:${r}`,!0);this.board=e,this.boards.set(e.key,e),this.show(),this.draw();try{let i=await ti(n,r,this.signal);if(t!==this.gen)return;if(e.searching=!1,!i)e.error=`${n.name} has no post ${r}`,this.view.error=e.error;else this.posts.set(this.mark(n,i.id),i),e.groups=[{posts:[i],open:!1}],e.checked=1,e.total=1,this.thumbQueue.push({site:n,post:i}),this.thumbs(),this.view.mode="try";if(this.show(),i)this.select();this.draw()}catch(i){this.fail(t,i)}}async turn(){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 t of this.board.groups){let e=t.open?t.posts.length:1;if(n.focus<r+e){if(t.posts.length<2)return;t.open=!t.open,this.board.focus=r;for(let i of t.posts)if(!this.thumbPath.has(this.mark(this.site,i.id)))this.thumbQueue.push({site:this.site,post:i});this.thumbs(),this.show(),this.scroll(),this.draw();return}r+=e}}openPage(){let n=this.view.tiles[this.view.focus];if(!n)return;let r=process.platform==="darwin"?"open":"xdg-open";try{mc(r,[this.site.pageUrl(n.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 t=Math.max(0,Math.min(r.tiles.length-1,n));if(t===r.focus)return;if(r.focus=t,this.board.focus=t,this.scroll(),this.pump(),r.mode==="try")this.select();this.draw()}scroll(){let n=this.view,{perRow:r,rowsVis:t}=Et(this.cols,this.rows),e=Math.floor(n.focus/r);if(e<n.top)n.top=e;if(e>n.top+t-1)n.top=e-t+1;this.board.top=n.top}query(n){let r=this.view,t=[r.tag,n.rate(this.view.rating),r.preset==="cutouts"?n.cutouts:"",r.order==="score"?n.best:""].filter(Boolean),e=[],i=[];for(let o of t)if(ri([...e,o].join(" "))<=n.tagBudget)e.push(o);else i.push(o);return this.board.note=i.length>0?`${n.name} takes ${n.tagBudget} tags — ${i.join(" ")} left out`:void 0,e.join(" ")}async search(){let n=++this.gen,r=this.site,t=$i(this.boardKey,!0);this.board=t,this.boards.set(t.key,t),this.view.error=void 0,this.show(),this.draw();let e=this.query(r);this.tally(n,r,t,e);try{let i=await this.mateOwners(r);if(n!==this.gen)return;let o=ri(e)+1<=r.tagBudget;t.sources=[...o?[...i.keys()].map((s)=>({tags:`${e} user:${s}`,page:0,done:!1})):[],{tags:e,page:0,done:!1}],this.show(),this.draw(),await this.pump()}catch(i){this.fail(n,i)}}async tally(n,r,t,e){try{let i=await Nu(r,e,this.signal);if(n===this.gen)t.total=i,this.show(),this.draw()}catch{}}fail(n,r){if(n!==this.gen||this.signal.aborted)return;this.board.error=lc(this.site,r),this.board.searching=!1,this.view.error=this.board.error,this.show(),this.draw()}wants(){let{perRow:n,rowsVis:r}=Et(this.cols,this.rows);return this.view.tiles.length<(this.board.top+r+vm)*n}async nextPage(n,r,t){let e=r.sources.find((o)=>!o.done);if(!e)return;let i=await pu(n,e.tags,e.page,this.signal);if(t!==this.gen)return;e.page++,e.done=i.length<mt;for(let o of i)if(!r.seen.has(o.id))r.seen.add(o.id),r.queue.push(o)}async pump(){let n=this.gen,r=this.board;if(this.pumping===n||r.sources.length===0)return;this.pumping=n;let t=this.site,e=[],i;try{r.searching=!0;while(n===this.gen){while(e.length<gc&&r.queue.length>0&&this.wants()){let u=r.queue.shift();e.push({post:u,passed:this.passes(t,u)})}if(!i&&r.queue.length<gc&&r.sources.some((u)=>!u.done)&&this.wants()){let u=this.nextPage(t,r,n).then(()=>{if(i===u)i=void 0});u.catch(()=>{}),i=u}let o=e.shift();if(!o){if(!i)break;await i;continue}let s=await o.passed;if(n!==this.gen)return;if(r.checked++,s)this.admit(t,o.post);this.show(),this.draw()}if(n===this.gen)r.searching=!1,this.show(),this.draw()}catch(o){this.fail(n,o)}finally{if(this.saveProbes(),this.pumping===n)this.pumping=0}}async passes(n,r){let t=$t(r);if(!ku(n,r,this.view.rating)||Eu(r,this.view.block).length>0||!t)return!1;if(this.view.preset==="all")return["png","jpg","jpeg"].includes(t.ext);if(r.ext!=="png")return!1;return n.vouched||this.transparent(n,r)}probes(n){let r=this.probed.get(n.key);if(!r)r=ai(n,"probes.json"),this.probed.set(n.key,r);return r}async transparent(n,r){let t=this.probes(n),e=t[r.id];if(e!==void 0)return e;try{let i=(await Hu(n,r.file,this.signal))?.alpha===!0;return t[r.id]=i,this.unsaved.add(n.key),i}catch{return!1}}saveProbes(){for(let n of this.unsaved){let r=Yn.find((t)=>t.key===n);if(r)bi(r,"probes.json",this.probes(r))}this.unsaved.clear()}admit(n,r){this.posts.set(this.mark(n,r.id),r);let t=this.view.sets==="fold"?this.board.groups.at(-1):void 0,e=t?.posts[0],i=r.owner||r.artist;if(t&&e&&i&&(e.owner||e.artist)===i&&e.width===r.width&&e.height===r.height){if(t.posts.push(r),t.open)this.thumbQueue.push({site:n,post:r}),this.thumbs();return}this.board.groups.push({posts:[r],open:!1}),this.thumbQueue.push({site:n,post:r}),this.thumbs()}async mateOwners(n){let r=this.owners.get(n.key);if(r)return r;let t=hu(this.home),e=ai(n,"owners.json"),i=this.catalog.palettes.flatMap((c)=>{let h=t.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=e[c.id];if(h!==void 0)return{...c,owner:h};try{return{...c,owner:(await ti(n,c.id,this.signal))?.owner??""}}catch{return}})),s=new Map;for(let c of o)if(c)e[c.id]=c.owner,s.set(c.name,c.owner);bi(n,"owners.json",e);let u=Fu(s);return this.owners.set(n.key,u),u}async cached(n,r,t,e){if(Vr(r))return am(r).size;let i=this.inflight.get(r);if(i)return i;let o=(async()=>{let s=await Su(n,t,this.signal,e);return wi(fc(r),{recursive:!0}),Ei(r,s),s.length})();this.inflight.set(r,o);try{return await o}finally{this.inflight.delete(r)}}thumbs(){while(this.thumbing<Em&&this.thumbQueue.length>0){let{site:n,post:r}=this.thumbQueue.shift();this.thumbing++,this.thumb(n,r).catch(()=>{}).finally(()=>{this.thumbing--,this.thumbs()})}}async thumb(n,r){let t=Ln.cols*this.cell.w,e=Ln.rows*this.cell.h,i=ur(mr(n),"tile",`${r.id}-${t}x${e}.png`);if(!Vr(i)){let o=ur(mr(n),"thumb",`${r.id}.${Zr(r.preview)}`);await this.cached(n,o,r.preview),await this.renders.run({job:"thumb",from:o,to:i,width:t,height:e})}this.thumbPath.set(this.mark(n,r.id),i),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?.id===r.id){this.reveal();return}this.settle=setTimeout(()=>void this.load(r),Mm),this.draw()}async load(n){let r=this.view,t=this.posts.get(this.mark(this.site,n.id)),e=t&&$t(t);if(!e)return;let i=this.site,o=new AbortController;this.fetch=o;try{let s=this.origPath(i,n.id,e.ext);if(!Vr(s))r.fetching={id:n.id,got:0,size:0},this.draw();let u=await this.cached(i,s,e.file,(f,g)=>{if(r.fetching?.id===n.id)r.fetching={id:n.id,got:f,size:g},this.draw()});if(o.signal.aborted)return;if(r.fetching=void 0,i!==this.site)return;let c={site:i,id:n.id,path:s,ext:e.ext,size:u,using:"plain",failed:!1};r.preparing=n.id,this.flush();let h=await this.render(c,"plain");if(o.signal.aborted||i!==this.site)return;if(h.clear===0&&ei()&&this.setting("TTHEME_FIND_REMOVE_BG")!=="off"){if(r.preparing=void 0,r.cutting=n.id,this.flush(),c.cut=await this.cutOut(i,n.id,s,o.signal),o.signal.aborted||i!==this.site)return;if(r.cutting=void 0,c.cut){r.preparing=n.id,this.flush();let f=await this.render(c,"cut").catch(()=>{return});if(o.signal.aborted||i!==this.site)return;if(f&&yu(f.clear))c.using="cut";else di(c.cut,{force:!0}),c.cut=void 0,c.failed=!0}else c.failed=!0}if(this.current=c,r.tiles[r.focus]?.id===n.id)await this.present();this.preload()}catch(s){if(!o.signal.aborted&&!this.signal.aborted)r.error=lc(i,s)}finally{if(r.fetching?.id===n.id)r.fetching=void 0;if(r.preparing===n.id)r.preparing=void 0;if(r.cutting===n.id)r.cutting=void 0;this.draw()}}async cutOut(n,r,t,e){let i=ur(mr(n),"cut",`${r}.png`);if(Vr(i))return i;try{return wi(fc(i),{recursive:!0}),await Ou(t,i,e),i}catch{di(i,{force:!0});return}}swap(){let n=this.current;if(!n?.cut||this.view.shown?.id!==n.id)return;n.using=n.using==="cut"?"plain":"cut",this.reveal()}preload(){let n=this.view;if(n.mode!=="try")return;let r=this.site;for(let t of[n.focus+this.direction,n.focus-this.direction]){if(this.prefetching>=km)return;let e=n.tiles[t],i=e&&this.posts.get(this.mark(r,e.id)),o=i&&$t(i);if(!o)continue;let s=this.origPath(r,i.id,o.ext);this.prefetching++,this.cached(r,s,o.file).then(()=>this.render({site:r,id:i.id,path:s,ext:o.ext,size:0,using:"plain",failed:!1},"plain")).catch(()=>{}).finally(()=>{this.prefetching--})}}async render(n,r){let t=this.cols*this.cell.w,e=this.rows*this.cell.h,i=Math.min(t,Im),o=Math.max(1,Math.round(e*i/t)),s=ur(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&&Vr(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:t,path:e}=await this.render(n,r);if(this.current!==n||n.using!==r)return;this.view.shown={id:n.id,clear:t,bytes:n.size,path:e,cut:n.cut?r==="cut"?"on":"off":n.failed?"failed":"none"}}reveal(){let n=this.view;n.preparing=this.current?.id,this.flush(),this.present().catch((r)=>{n.error=r instanceof Error?r.message:String(r)}).finally(()=>{if(n.preparing===this.current?.id)n.preparing=void 0;this.draw()})}async install(){let n=this.view,r=n.tiles[n.focus],t=this.current;if(!r||t?.id!==r.id||n.preparing!==void 0||n.shown?.id!==r.id)return;n.installing=r.id,n.error=void 0,this.flush();try{await this.renders.run({job:"backdrop",from:t.using==="cut"?t.cut:t.path,source:t.path,home:this.home,colors:this.entry,tone:this.tone,origin:{site:t.site.key,id:t.id,ext:t.ext,from:`${t.site.name} ${t.id} ${t.site.pageUrl(t.id)}`}});let e=ai(t.site,"owners.json");e[t.id]=this.posts.get(this.mark(t.site,t.id))?.owner??"",bi(t.site,"owners.json",e),Xr(this.home),process.stderr.write(`background · ${this.entry.name} ← ${t.site.name} ${t.id}
70
+ `),this.finish(0)}catch(e){n.installing=void 0,n.error=e instanceof Error?e.message:String(e),this.draw()}}draw(){if(this.dirty)return;this.dirty=!0,setImmediate(()=>{this.dirty=!1,this.flush()})}flush(){let n=Au(this.view,this.cols,this.rows),r="\x1B[?2026h";n.lines.forEach((e,i)=>{r+=`\x1B[${i+1};1H\x1B[K${e}`});let t=new Set;for(let e of n.images){if(t.add(e.id),this.sent.get(e.id)!==e.path)r+=Uu(e),this.sent.set(e.id,e.path),this.placed.delete(e.id);let i=`${e.row};${e.col};${e.cols};${e.rows};${e.z}`;if(this.placed.get(e.id)!==i)r+=qu(e),this.placed.set(e.id,i)}for(let e of this.sent.keys())if(!t.has(e))r+=Wu(e),this.sent.delete(e),this.placed.delete(e);this.write(`${r}\x1B[?2026l`)}}function Nm(){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 Hm(){if(!Nm())return process.stderr.write(`unblock needs node 22.21 or newer — this is ${process.versions.node}
71
+ `),1;let n=await hc(),r=mc(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}`,TTHEME_FIND_PROXY:String(n.port)}}),t=await new Promise((e)=>r.on("exit",(i)=>e(i??1)));return n.close(),t}async function ac(n){if(process.env.TTHEME_FIND_UNBLOCK==="1"&&!process.env.TTHEME_FIND_PROXY)return Hm();let r=_n(),t=Qn(r),e=Bt(t.palettes,n);if(!process.stdin.isTTY||!process.stdout.isTTY)throw Error("ttheme find needs a terminal");return new $c(r,t,e,e.booru??"").run()}function bc(n,r){let t=_n();if(Bt(Qn(t).palettes,n),r==="next"||r==="prev"){let{key:e,at:i,of:o}=su(t,n,r==="next"?1:-1);return Xr(t),process.stderr.write(`background · ${n} ${i}/${o} ${e}
72
+ `),0}if(r==="drop"){let{key:e,left:i}=uu(t,n);return Xr(t),process.stderr.write(`background · ${n} removed ${e??"the picture"} · ${i} left
73
+ `),0}if(r==="tuned")return Xr(t),0;throw Error(`unknown image action ${r} — next, prev, drop or tuned`)}import{chmodSync as Sd,copyFileSync as jd,existsSync as hr,mkdirSync as Xi,readdirSync as Gd,readFileSync as Nt,rmSync as bh,writeFileSync as wh}from"node:fs";import{homedir as Jd}from"node:os";import{dirname as pt,join as wn}from"node:path";import{styleText as Hi}from"node:util";import{stdout as Oc,stdin as Vm}from"node:process";import Ym from"node:readline";var wc=(()=>{let n=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(r)=>{let t=0;n.lastIndex=0;while(n.test(r))t+=1;return r.length-t}})(),Ec=(n)=>{return n===12288||n>=65281&&n<=65376||n>=65504&&n<=65510},kc=(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 Sm=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,jm=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Mc=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,Gm=/\t{1,1000}/y,Fc=/[\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,Jm=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Km=/\p{M}+/gu,Rm={limit:1/0,ellipsis:""},Ic=(n,r={},t={})=>{let e=r.limit??1/0,i=r.ellipsis??"",o=r?.ellipsisWidth??(i?Ic(i,Rm,t).width:0),s=0,u=t.controlWidth??0,c=t.tabWidth??8,h=t.emojiWidth??2,f=2,g=t.regularWidth??1,l=t.wideWidth??2,$=[[Jm,g],[Sm,0],[jm,u],[Gm,c],[Fc,h],[Mc,l]],a=0,w=0,F=n.length,v=0,j=!1,M=F,p=Math.max(0,e-o),b=0,K=0,E=0,J=0;n:while(!0){if(K>b||w>=F&&w>a){let S=n.slice(b,K)||n.slice(a,w);v=0;for(let O of S.replaceAll(Km,"")){let R=O.codePointAt(0)||0;if(Ec(R))J=2;else if(kc(R))J=l;else J=g;if(E+J>p)M=Math.min(M,Math.max(b,a)+v);if(E+J>e){j=!0;break n}v+=O.length,E+=J}b=K=0}if(w>=F)break n;for(let S=0,O=$.length;S<O;S++){let[R,A]=$[S];if(R.lastIndex=w,R.test(n)){if(v=R===Mc?wc(n.slice(w,R.lastIndex)):R===Fc?1:R.lastIndex-w,J=v*A,E+J>p)M=Math.min(M,w+Math.floor((p-E)/A));if(E+J>e){j=!0;break n}E+=J,b=a,K=w,w=a=R.lastIndex;continue n}}w+=1}return{width:j?p:E,index:j?M:F,truncated:j,ellipsed:j&&e>=o}},vc=Ic;var ym={limit:1/0,ellipsis:"",ellipsisWidth:0},Om=(n,r={})=>{return vc(n,ym,r).width},Rn=Om;var te="\x1B",jc="›",Lm=39,Fi="\x07",Gc="[",Qm="]",Jc="m",Ii=`${Qm}8;;`,pc=new RegExp(`(?:\\${Gc}(?<code>\\d+)m|\\${Ii}(?<uri>.*)${Fi})`,"y"),Nc=(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},Hc=(n)=>`${te}${Gc}${n}${Jc}`,Sc=(n)=>`${te}${Ii}${n}${Fi}`,Mi=(n,r,t)=>{let e=r[Symbol.iterator](),i=!1,o=!1,s=n.at(-1),u=s===void 0?0:Rn(s),c=e.next(),h=e.next(),f=0;while(!c.done){let g=c.value,l=Rn(g);if(u+l<=t)n[n.length-1]+=g;else n.push(g),u=0;if(g===te||g===jc)i=!0,o=r.startsWith(Ii,f+1);if(i){if(o){if(g===Fi)i=!1,o=!1}else if(g===Jc)i=!1}else if(u+=l,u===t&&!h.done)n.push(""),u=0;c=h,h=e.next(),f+=g.length}if(s=n.at(-1),!u&&s!==void 0&&s.length&&n.length>1)n[n.length-2]+=n.pop()},Zm=(n)=>{let r=n.split(" "),t=r.length;while(t){if(Rn(r[t-1]))break;t--}if(t===r.length)return n;return r.slice(0,t).join(" ")+r.slice(t).join("")},Um=(n,r,t={})=>{if(t.trim!==!1&&n.trim()==="")return"";let e="",i,o,s=n.split(" "),u=[""],c=0;for(let g=0;g<s.length;g++){let l=s[g];if(t.trim!==!1){let a=u.at(-1)??"",w=a.trimStart();if(a.length!==w.length)u[u.length-1]=w,c=Rn(w)}if(g!==0){if(c>=r&&(t.wordWrap===!1||t.trim===!1))u.push(""),c=0;if(c||t.trim===!1)u[u.length-1]+=" ",c++}let $=Rn(l);if(t.hard&&$>r){let a=r-c,w=1+Math.floor(($-a-1)/r);if(Math.floor(($-1)/r)<w)u.push("");Mi(u,l,r),c=Rn(u.at(-1)??"");continue}if(c+$>r&&c&&$){if(t.wordWrap===!1&&c<r){Mi(u,l,r),c=Rn(u.at(-1)??"");continue}u.push(""),c=0}if(c+$>r&&t.wordWrap===!1){Mi(u,l,r),c=Rn(u.at(-1)??"");continue}u[u.length-1]+=l,c+=$}if(t.trim!==!1)u=u.map((g)=>Zm(g));let h=u.join(`
74
+ `),f=!1;for(let g=0;g<h.length;g++){let l=h[g];if(e+=l,!f){if(f=l>="\uD800"&&l<="\uDBFF",f)continue}else f=!1;if(l===te||l===jc){pc.lastIndex=g+1;let a=pc.exec(h)?.groups;if(a?.code!==void 0){let w=Number.parseFloat(a.code);i=w===Lm?void 0:w}else if(a?.uri!==void 0)o=a.uri.length===0?void 0:a.uri}if(h[g+1]===`
75
+ `){if(o)e+=Sc("");let $=i?Nc(i):void 0;if(i&&$)e+=Hc($)}else if(l===`
76
+ `){if(i&&Nc(i))e+=Hc(i);if(o)e+=Sc(o)}}return e},qm=/\r?\n/;function dr(n,r,t){return String(n).normalize().split(qm).map((e)=>Um(e,r,t)).join(`
77
+ `)}var Zn=Jt(pi(),1);function cr(n,r,t){if(!t.some((s)=>!s.disabled))return n;let e=n+r,i=Math.max(t.length-1,0),o=e<0?i:e>i?0:e;return t[o]?.disabled?cr(o,r<0?-1:1,t):o}function ee(n,r,t,e){let i=e.split(`
78
+ `),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+t)),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 Pm=["up","down","left","right","space","enter","cancel"],zm=["January","February","March","April","May","June","July","August","September","October","November","December"],yn={actions:new Set(Pm),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:[...zm],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 Lc(n,r){if(typeof n=="string")return yn.aliases.get(n)===r;for(let t of n)if(t!==void 0&&Lc(t,r))return!0;return!1}function Am(n,r){if(n===r)return;let t=n.split(`
79
+ `),e=r.split(`
80
+ `),i=Math.max(t.length,e.length),o=[];for(let s=0;s<i;s++)t[s]!==e[s]&&o.push(s);return{lines:o,numLinesBefore:t.length,numLinesAfter:e.length,numLines:i}}var ja=globalThis.process.platform.startsWith("win"),Si=Symbol("clack:cancel");function Pr(n){return n===Si}function ie(n,r){let t=n;t.isTTY&&t.setRawMode(r)}var se=(n)=>("columns"in n)&&typeof n.columns=="number"?n.columns:80,Gi=(n)=>("rows"in n)&&typeof n.rows=="number"?n.rows:20;function $r(n,r,t,e=t,i=t,o){let s=se(n??Oc);return dr(r,s-t.length,{hard:!0,trim:!1}).split(`
81
+ `).map((u,c,h)=>{let f=o?o(u,c):u;return c===0?`${e}${f}`:c===h.length-1?`${i}${f}`:`${t}${f}`}).join(`
82
+ `)}function Qc(n,r){if("~standard"in n){let t=n["~standard"].validate(r);if(t instanceof Promise)throw TypeError("Schema validation must be synchronous. Update `validate()` and remove any asynchronous logic.");return t.issues?.at(0)?.message}return n(r)}class tr{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:t=Vm,output:e=Oc,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=t,this.output=e}unsubscribe(){this._subscribers.clear()}setSubscriber(n,r){let t=this._subscribers.get(n)??[];t.push(r),this._subscribers.set(n,t)}on(n,r){this.setSubscriber(n,{cb:r})}once(n,r){this.setSubscriber(n,{cb:r,once:!0})}emit(n,...r){let t=this._subscribers.get(n)??[],e=[];for(let i of t)i.cb(...r),i.once&&e.push(()=>t.splice(t.indexOf(i),1));for(let i of e)i()}prompt(){return new Promise((n)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),n(Si);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=Ym.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),ie(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),ie(this.input,!1),n(this.value)}),this.once("cancel",()=>{this.output.write(Zn.cursor.show),this.output.off("resize",this.render),ie(this.input,!1),n(Si)})})}_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&&yn.aliases.has(r.name)&&this.emit("cursor",yn.aliases.get(r.name)),yn.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 t=Qc(this.opts.validate,this.value);t&&(this.error=t instanceof Error?t.message:t,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}Lc([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(`
83
+ `),ie(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let n=dr(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
84
+ `).length-1;this.output.write(Zn.cursor.move(-999,n*-1))}render(){let n=dr(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=Am(this._prevFrame,n),t=Gi(this.output);if(this.restoreCursor(),r){let e=Math.max(0,r.numLinesAfter-t),i=Math.max(0,r.numLinesBefore-t),o=r.lines.find((s)=>s>=e);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(`
85
+ `);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(e<i)o=e;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(`
85
86
  `).slice(o);this.output.write(s.join(`
86
- `)),this._prevFrame=n;return}}this.output.write(Zn.erase.down())}this.output.write(n),this.state==="initial"&&(this.state="active"),this._prevFrame=n}}}function K0(n,r){if(n===void 0||r.length===0)return 0;let t=r.findIndex((i)=>i.value===n);return t!==-1?t:0}function R0(n,r){return(r.label??String(r.value)).toLowerCase().includes(n.toLowerCase())}function O0(n,r){if(r)return n?r:r[0]}var Q0=class extends tr{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#r=0;#e="";#n;#o;#u;get cursor(){return this.#r}get userInputWithCursor(){if(!this.userInput)return Ee(["inverse","hidden"],"_");if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let r=this.userInput.slice(0,this.cursor),t=this.userInput.slice(this.cursor,this.cursor+1),i=this.userInput.slice(this.cursor+1);return`${r}${Ee("inverse",t)}${i}`}get options(){return typeof this.#o=="function"?this.#o():this.#o}constructor(r){super(r),this.#o=r.options,this.#u=r.placeholder;let t=this.options;this.filteredOptions=[...t],this.multiple=r.multiple===!0,this.#n=typeof r.options=="function"?r.filter:r.filter??R0;let i;if(r.initialValue&&Array.isArray(r.initialValue)?this.multiple?i=r.initialValue:i=r.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(i=[this.options[0]?.value]),i)for(let e of i){let o=t.findIndex((s)=>s.value===e);o!==-1&&(this.toggleSelected(e),this.#r=o)}this.focusedValue=this.options[this.#r]?.value,this.on("key",(e,o)=>this.#t(e,o)),this.on("userInput",(e)=>this.#i(e))}_isActionKey(r,t){return r==="\t"||this.multiple&&this.isNavigating&&t.name==="space"&&r!==void 0&&r!==""}#t(r,t){let i=t.name==="up",e=t.name==="down",o=t.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(t.name==="tab"&&s&&h){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(u,!0),this.isNavigating=!1;return}i||e?(this.#r=ur(this.#r,i?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#r]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):o?this.value=O0(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(t.name==="tab"||this.isNavigating&&t.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((t)=>t!==r):this.selectedValues=[...this.selectedValues,r]:this.selectedValues=[r])}#i(r){if(r!==this.#e){this.#e=r;let t=this.options;r&&this.#n?this.filteredOptions=t.filter((o)=>this.#n?.(r,o)):this.filteredOptions=[...t];let i=K0(this.focusedValue,this.filteredOptions);this.#r=ur(i,0,this.filteredOptions);let e=this.filteredOptions[this.#r];e&&!e.disabled?this.focusedValue=e.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}};class ve extends tr{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 y0={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function wc(n){return[...n].map((r)=>y0[r])}function Z0(n){let r=new Intl.DateTimeFormat(n,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2000,0,15)),t=[],i="/";for(let e of r)e.type==="literal"?i=e.value.trim()||e.value:(e.type==="year"||e.type==="month"||e.type==="day")&&t.push({type:e.type,len:e.type==="year"?4:2});return{segments:t,separator:i}}function we(n){return Number.parseInt((n||"0").replace(/_/g,"0"),10)||0}function Bt(n){return{year:we(n.year),month:we(n.month),day:we(n.day)}}function Me(n,r){return new Date(n||2001,r||1,0).getDate()}function vc(n){let{year:r,month:t,day:i}=Bt(n);if(!r||r<0||r>9999||!t||t<1||t>12||!i||i<1)return;let e=new Date(Date.UTC(r,t-1,i));if(!(e.getUTCFullYear()!==r||e.getUTCMonth()!==t-1||e.getUTCDate()!==i))return{year:r,month:t,day:i}}function Ec(n){let r=vc(n);return r?new Date(Date.UTC(r.year,r.month-1,r.day)):void 0}function L0(n,r,t,i){let e=t?{year:t.getUTCFullYear(),month:t.getUTCMonth()+1,day:t.getUTCDate()}:null,o=i?{year:i.getUTCFullYear(),month:i.getUTCMonth()+1,day:i.getUTCDate()}:null;return n==="year"?{min:e?.year??1,max:o?.year??9999}:n==="month"?{min:e&&r.year===e.year?e.month:1,max:o&&r.year===o.year?o.month:12}:{min:e&&r.year===e.year&&r.month===e.month?e.day:1,max:o&&r.year===o.year&&r.month===o.month?o.day:Me(r.year,r.month)}}class Ic extends tr{#r;#e;#n;#o;#u;#t={segmentIndex:0,positionInSegment:0};#i=!0;#s=null;inlineError="";get segmentCursor(){return{...this.#t}}get segmentValues(){return{...this.#n}}get segments(){return this.#r}get separator(){return this.#e}get formattedValue(){return this.#g(this.#n)}#g(n){return this.#r.map((r)=>n[r.type]).join(this.#e)}#c(){this._setUserInput(this.#g(this.#n)),this._setValue(Ec(this.#n)??void 0)}constructor(n){let r=n.format?{segments:wc(n.format),separator:n.separator??"/"}:Z0(n.locale),t=n.separator??r.separator,i=n.format?wc(n.format):r.segments,e=n.initialValue??n.defaultValue,o=e?{year:String(e.getUTCFullYear()).padStart(4,"0"),month:String(e.getUTCMonth()+1).padStart(2,"0"),day:String(e.getUTCDate()).padStart(2,"0")}:{year:"____",month:"__",day:"__"},s=i.map((u)=>o[u.type]).join(t);super({...n,initialUserInput:s},!1),this.#r=i,this.#e=t,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.#$(u,c)),this.on("finalize",()=>this.#a(n))}#h(){let n=Math.max(0,Math.min(this.#t.segmentIndex,this.#r.length-1)),r=this.#r[n];if(r)return this.#t.positionInSegment=Math.max(0,Math.min(this.#t.positionInSegment,r.len-1)),{segment:r,index:n}}#f(n){this.inlineError="",this.#s=null;let r=this.#h();r&&(this.#t.segmentIndex=Math.max(0,Math.min(this.#r.length-1,r.index+n)),this.#t.positionInSegment=0,this.#i=!0)}#l(n){let r=this.#h();if(!r)return;let{segment:t}=r,i=this.#n[t.type],e=!i||i.replace(/_/g,"")==="",o=Number.parseInt((i||"0").replace(/_/g,"0"),10)||0,s=L0(t.type,Bt(this.#n),this.#o,this.#u),u;e?u=n===1?s.min:s.max:u=Math.max(Math.min(s.max,o+n),s.min),this.#n={...this.#n,[t.type]:u.toString().padStart(t.len,"0")},this.#i=!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)}}#$(n,r){if(r?.name==="backspace"||r?.sequence===""||r?.sequence==="\b"||n===""||n==="\b"){this.inlineError="";let t=this.#h();if(!t)return;if(!this.#n[t.segment.type].replace(/_/g,"")){this.#f(-1);return}this.#n[t.segment.type]="_".repeat(t.segment.len),this.#i=!0,this.#t.positionInSegment=0,this.#c();return}if(r?.name==="tab"){this.inlineError="";let t=this.#h();if(!t)return;let i=r.shift?-1:1,e=t.index+i;e>=0&&e<this.#r.length&&(this.#t.segmentIndex=e,this.#t.positionInSegment=0,this.#i=!0);return}if(n&&/^[0-9]$/.test(n)){let t=this.#h();if(!t)return;let{segment:i}=t,e=!this.#n[i.type].replace(/_/g,"");if(this.#i&&this.#s!==null&&!e){let l=this.#s+n,$={...this.#n,[i.type]:l},a=this.#m($,i);if(a){this.inlineError=a,this.#s=null,this.#i=!1;return}this.inlineError="",this.#n[i.type]=l,this.#s=null,this.#i=!1,this.#c(),t.index<this.#r.length-1&&(this.#t.segmentIndex=t.index+1,this.#t.positionInSegment=0,this.#i=!0);return}this.#i&&!e&&(this.#n[i.type]="_".repeat(i.len),this.#t.positionInSegment=0),this.#i=!1,this.#s=null;let o=this.#n[i.type],s=o.indexOf("_"),u=s>=0?s:Math.min(this.#t.positionInSegment,i.len-1);if(u<0||u>=i.len)return;let c=o.slice(0,u)+n+o.slice(u+1),h=!1;if(u===0&&o==="__"&&(i.type==="month"||i.type==="day")){let l=Number.parseInt(n,10);c=`0${n}`,h=l<=(i.type==="month"?1:2)}if(i.type==="year"&&(c=(o.replace(/_/g,"")+n).padStart(i.len,"_")),!c.includes("_")){let l={...this.#n,[i.type]:c},$=this.#m(l,i);if($){this.inlineError=$;return}}this.inlineError="",this.#n[i.type]=c;let f=c.includes("_")?void 0:vc(this.#n);if(f){let{year:l,month:$}=f,a=Me(l,$);this.#n={year:String(Math.max(0,Math.min(9999,l))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,$))).padStart(2,"0"),day:String(Math.max(1,Math.min(a,f.day))).padStart(2,"0")}}this.#c();let g=c.indexOf("_");h?(this.#i=!0,this.#s=n):g>=0?this.#t.positionInSegment=g:s>=0&&t.index<this.#r.length-1?(this.#t.segmentIndex=t.index+1,this.#t.positionInSegment=0,this.#i=!0):this.#t.positionInSegment=Math.min(u+1,i.len-1)}}#m(n,r){let{month:t,day:i}=Bt(n);if(r.type==="month"&&(t<0||t>12))return On.date.messages.invalidMonth;if(r.type==="day"&&(i<0||i>31))return On.date.messages.invalidDay(31,"any month")}#a(n){let{year:r,month:t,day:i}=Bt(this.#n);if(r&&t&&i){let e=Me(r,t);this.#n={...this.#n,day:String(Math.min(i,e)).padStart(2,"0")}}this.value=Ec(this.#n)??n.defaultValue??void 0}}var U0=class extends tr{options;cursor=0;#r;getGroupItems(r){return this.options.filter((t)=>t.group===r)}isGroupSelected(r){let t=this.getGroupItems(r),i=this.value;return i===void 0?!1:t.every((e)=>i.includes(e.value))}toggleValue(){let r=this.options[this.cursor];if(r!==void 0)if(this.value===void 0&&(this.value=[]),r.group===!0){let t=r.value,i=this.getGroupItems(t);this.isGroupSelected(t)?this.value=this.value.filter((e)=>i.findIndex((o)=>o.value===e)===-1):this.value=[...this.value,...i.map((e)=>e.value)],this.value=Array.from(new Set(this.value))}else{let t=this.value.includes(r.value);this.value=t?this.value.filter((i)=>i!==r.value):[...this.value,r.value]}}constructor(r){super(r,!1);let{options:t}=r;this.#r=r.selectableGroups!==!1,this.options=Object.entries(t).flatMap(([i,e])=>[{value:i,group:!0,label:i},...e.map((o)=>({...o,group:i}))]),this.value=[...r.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:i})=>i===r.cursorAt),this.#r?0:1),this.on("cursor",(i)=>{switch(i){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let e=this.options[this.cursor]?.group===!0;!this.#r&&e&&(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 e=this.options[this.cursor]?.group===!0;!this.#r&&e&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},q0=new Set(["up","down","left","right"]);class Nc extends tr{#r=!1;#e;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),t=n.slice(this.cursor,this.cursor+1),i=n.slice(this.cursor+1);return t===`
87
+ `)),this._prevFrame=n;return}}this.output.write(Zn.erase.down())}this.output.write(n),this.state==="initial"&&(this.state="active"),this._prevFrame=n}}}function Cm(n,r){if(n===void 0||r.length===0)return 0;let t=r.findIndex((e)=>e.value===n);return t!==-1?t:0}function Tm(n,r){return(r.label??String(r.value)).toLowerCase().includes(n.toLowerCase())}function _m(n,r){if(r)return n?r:r[0]}var Bm=class extends tr{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#r=0;#i="";#n;#o;#u;get cursor(){return this.#r}get userInputWithCursor(){if(!this.userInput)return Hi(["inverse","hidden"],"_");if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let r=this.userInput.slice(0,this.cursor),t=this.userInput.slice(this.cursor,this.cursor+1),e=this.userInput.slice(this.cursor+1);return`${r}${Hi("inverse",t)}${e}`}get options(){return typeof this.#o=="function"?this.#o():this.#o}constructor(r){super(r),this.#o=r.options,this.#u=r.placeholder;let t=this.options;this.filteredOptions=[...t],this.multiple=r.multiple===!0,this.#n=typeof r.options=="function"?r.filter:r.filter??Tm;let e;if(r.initialValue&&Array.isArray(r.initialValue)?this.multiple?e=r.initialValue:e=r.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(e=[this.options[0]?.value]),e)for(let i of e){let o=t.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.#t(i,o)),this.on("userInput",(i)=>this.#e(i))}_isActionKey(r,t){return r==="\t"||this.multiple&&this.isNavigating&&t.name==="space"&&r!==void 0&&r!==""}#t(r,t){let e=t.name==="up",i=t.name==="down",o=t.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(t.name==="tab"&&s&&h){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(u,!0),this.isNavigating=!1;return}e||i?(this.#r=cr(this.#r,e?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#r]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):o?this.value=_m(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(t.name==="tab"||this.isNavigating&&t.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((t)=>t!==r):this.selectedValues=[...this.selectedValues,r]:this.selectedValues=[r])}#e(r){if(r!==this.#i){this.#i=r;let t=this.options;r&&this.#n?this.filteredOptions=t.filter((o)=>this.#n?.(r,o)):this.filteredOptions=[...t];let e=Cm(this.focusedValue,this.filteredOptions);this.#r=cr(e,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 Ji extends tr{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 xm={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function Rc(n){return[...n].map((r)=>xm[r])}function Dm(n){let r=new Intl.DateTimeFormat(n,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2000,0,15)),t=[],e="/";for(let i of r)i.type==="literal"?e=i.value.trim()||i.value:(i.type==="year"||i.type==="month"||i.type==="day")&&t.push({type:i.type,len:i.type==="year"?4:2});return{segments:t,separator:e}}function Ni(n){return Number.parseInt((n||"0").replace(/_/g,"0"),10)||0}function oe(n){return{year:Ni(n.year),month:Ni(n.month),day:Ni(n.day)}}function ji(n,r){return new Date(n||2001,r||1,0).getDate()}function Zc(n){let{year:r,month:t,day:e}=oe(n);if(!r||r<0||r>9999||!t||t<1||t>12||!e||e<1)return;let i=new Date(Date.UTC(r,t-1,e));if(!(i.getUTCFullYear()!==r||i.getUTCMonth()!==t-1||i.getUTCDate()!==e))return{year:r,month:t,day:e}}function yc(n){let r=Zc(n);return r?new Date(Date.UTC(r.year,r.month-1,r.day)):void 0}function nd(n,r,t,e){let i=t?{year:t.getUTCFullYear(),month:t.getUTCMonth()+1,day:t.getUTCDate()}:null,o=e?{year:e.getUTCFullYear(),month:e.getUTCMonth()+1,day:e.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:ji(r.year,r.month)}}class Uc extends tr{#r;#i;#n;#o;#u;#t={segmentIndex:0,positionInSegment:0};#e=!0;#s=null;inlineError="";get segmentCursor(){return{...this.#t}}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(yc(this.#n)??void 0)}constructor(n){let r=n.format?{segments:Rc(n.format),separator:n.separator??"/"}:Dm(n.locale),t=n.separator??r.separator,e=n.format?Rc(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=e.map((u)=>o[u.type]).join(t);super({...n,initialUserInput:s},!1),this.#r=e,this.#i=t,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.#$(u,c)),this.on("finalize",()=>this.#a(n))}#h(){let n=Math.max(0,Math.min(this.#t.segmentIndex,this.#r.length-1)),r=this.#r[n];if(r)return this.#t.positionInSegment=Math.max(0,Math.min(this.#t.positionInSegment,r.len-1)),{segment:r,index:n}}#f(n){this.inlineError="",this.#s=null;let r=this.#h();r&&(this.#t.segmentIndex=Math.max(0,Math.min(this.#r.length-1,r.index+n)),this.#t.positionInSegment=0,this.#e=!0)}#l(n){let r=this.#h();if(!r)return;let{segment:t}=r,e=this.#n[t.type],i=!e||e.replace(/_/g,"")==="",o=Number.parseInt((e||"0").replace(/_/g,"0"),10)||0,s=nd(t.type,oe(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,[t.type]:u.toString().padStart(t.len,"0")},this.#e=!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)}}#$(n,r){if(r?.name==="backspace"||r?.sequence===""||r?.sequence==="\b"||n===""||n==="\b"){this.inlineError="";let t=this.#h();if(!t)return;if(!this.#n[t.segment.type].replace(/_/g,"")){this.#f(-1);return}this.#n[t.segment.type]="_".repeat(t.segment.len),this.#e=!0,this.#t.positionInSegment=0,this.#c();return}if(r?.name==="tab"){this.inlineError="";let t=this.#h();if(!t)return;let e=r.shift?-1:1,i=t.index+e;i>=0&&i<this.#r.length&&(this.#t.segmentIndex=i,this.#t.positionInSegment=0,this.#e=!0);return}if(n&&/^[0-9]$/.test(n)){let t=this.#h();if(!t)return;let{segment:e}=t,i=!this.#n[e.type].replace(/_/g,"");if(this.#e&&this.#s!==null&&!i){let l=this.#s+n,$={...this.#n,[e.type]:l},a=this.#m($,e);if(a){this.inlineError=a,this.#s=null,this.#e=!1;return}this.inlineError="",this.#n[e.type]=l,this.#s=null,this.#e=!1,this.#c(),t.index<this.#r.length-1&&(this.#t.segmentIndex=t.index+1,this.#t.positionInSegment=0,this.#e=!0);return}this.#e&&!i&&(this.#n[e.type]="_".repeat(e.len),this.#t.positionInSegment=0),this.#e=!1,this.#s=null;let o=this.#n[e.type],s=o.indexOf("_"),u=s>=0?s:Math.min(this.#t.positionInSegment,e.len-1);if(u<0||u>=e.len)return;let c=o.slice(0,u)+n+o.slice(u+1),h=!1;if(u===0&&o==="__"&&(e.type==="month"||e.type==="day")){let l=Number.parseInt(n,10);c=`0${n}`,h=l<=(e.type==="month"?1:2)}if(e.type==="year"&&(c=(o.replace(/_/g,"")+n).padStart(e.len,"_")),!c.includes("_")){let l={...this.#n,[e.type]:c},$=this.#m(l,e);if($){this.inlineError=$;return}}this.inlineError="",this.#n[e.type]=c;let f=c.includes("_")?void 0:Zc(this.#n);if(f){let{year:l,month:$}=f,a=ji(l,$);this.#n={year:String(Math.max(0,Math.min(9999,l))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,$))).padStart(2,"0"),day:String(Math.max(1,Math.min(a,f.day))).padStart(2,"0")}}this.#c();let g=c.indexOf("_");h?(this.#e=!0,this.#s=n):g>=0?this.#t.positionInSegment=g:s>=0&&t.index<this.#r.length-1?(this.#t.segmentIndex=t.index+1,this.#t.positionInSegment=0,this.#e=!0):this.#t.positionInSegment=Math.min(u+1,e.len-1)}}#m(n,r){let{month:t,day:e}=oe(n);if(r.type==="month"&&(t<0||t>12))return yn.date.messages.invalidMonth;if(r.type==="day"&&(e<0||e>31))return yn.date.messages.invalidDay(31,"any month")}#a(n){let{year:r,month:t,day:e}=oe(this.#n);if(r&&t&&e){let i=ji(r,t);this.#n={...this.#n,day:String(Math.min(e,i)).padStart(2,"0")}}this.value=yc(this.#n)??n.defaultValue??void 0}}var rd=class extends tr{options;cursor=0;#r;getGroupItems(r){return this.options.filter((t)=>t.group===r)}isGroupSelected(r){let t=this.getGroupItems(r),e=this.value;return e===void 0?!1:t.every((i)=>e.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 t=r.value,e=this.getGroupItems(t);this.isGroupSelected(t)?this.value=this.value.filter((i)=>e.findIndex((o)=>o.value===i)===-1):this.value=[...this.value,...e.map((i)=>i.value)],this.value=Array.from(new Set(this.value))}else{let t=this.value.includes(r.value);this.value=t?this.value.filter((e)=>e!==r.value):[...this.value,r.value]}}constructor(r){super(r,!1);let{options:t}=r;this.#r=r.selectableGroups!==!1,this.options=Object.entries(t).flatMap(([e,i])=>[{value:e,group:!0,label:e},...i.map((o)=>({...o,group:e}))]),this.value=[...r.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:e})=>e===r.cursorAt),this.#r?0:1),this.on("cursor",(e)=>{switch(e){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}})}},td=new Set(["up","down","left","right"]);class qc extends tr{#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),t=n.slice(this.cursor,this.cursor+1),e=n.slice(this.cursor+1);return t===`
87
88
  `?`${r}█
88
- ${i}`:`${r}${Ee("inverse",t)}${i}`}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=Tt(this._cursor,0,-1,r);return;case"down":this._cursor=Tt(this._cursor,0,1,r);return;case"left":this._cursor=Tt(this._cursor,-1,0,r);return;case"right":this._cursor=Tt(this._cursor,1,0,r);return}}_shouldSubmit(n,r){if(this.#e)return this.focused==="submit"?!0:(this.#n(`
89
+ ${e}`:`${r}${Hi("inverse",t)}${e}`}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=ee(this._cursor,0,-1,r);return;case"down":this._cursor=ee(this._cursor,0,1,r);return;case"left":this._cursor=ee(this._cursor,-1,0,r);return;case"right":this._cursor=ee(this._cursor,1,0,r);return}}_shouldSubmit(n,r){if(this.#i)return this.focused==="submit"?!0:(this.#n(`
89
90
  `),this._cursor++,!1);let t=this.#r;return this.#r=!0,t&&this.cursor===this.userInput.length?(this.userInput[this.cursor-1]===`
90
91
  `&&(this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--),!0):(this.#n(`
91
- `),this._cursor++,!1)}constructor(n){let r=n.initialUserInput??n.initialValue;super({...n,initialUserInput:r},!1),r!==void 0&&(this._cursor=r.length),this.#e=n.showSubmit??!1,this.on("key",(t,i)=>{if(i?.name&&q0.has(i.name)){this.#r=!1,this.#o(i.name);return}if(t==="\t"&&this.#e){this.focused=this.focused==="editor"?"submit":"editor";return}if(i?.name!=="return"){if(this.#r=!1,i?.name==="backspace"&&this.cursor>0){this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--;return}if(i?.name==="delete"&&this.cursor<this.userInput.length){this._setUserInput(this.userInput.slice(0,this.cursor)+this.userInput.slice(this.cursor+1));return}t&&(this.#e&&this.focused==="submit"&&(this.focused="editor"),this.#n(t??""),this._cursor++)}}),this.on("userInput",(t)=>{this._setValue(t)}),this.on("finalize",()=>{this.value||(this.value=n.defaultValue),this.value===void 0&&(this.value="")})}}class Ie extends tr{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((t)=>t.value)}toggleInvert(){let n=this.value;if(!n)return;let r=this._enabledOptions.filter((t)=>!n.includes(t.value));this.value=r.map((t)=>t.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:t})=>t===n.cursorAt),0);this.cursor=this.options[r]?.disabled?ur(r,1,this.options):r,this.on("key",(t,i)=>{i.name==="a"&&this.toggleAll(),i.name==="i"&&this.toggleInvert()}),this.on("cursor",(t)=>{switch(t){case"left":case"up":this.cursor=ur(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=ur(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}var Hc=class extends tr{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 t=this.options.findIndex(({value:e})=>e===r.initialValue),i=t===-1?0:t;this.cursor=this.options[i]?.disabled?ur(i,1,this.options):i,this.changeValue(),this.on("cursor",(e)=>{switch(e){case"left":case"up":this.cursor=ur(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=ur(this.cursor,1,this.options);break}this.changeValue()})}};import{styleText as k,stripVTControlCharacters as wa}from"node:util";import zn from"node:process";var Jc=Nt(be(),1);function W0(){if(zn.platform!=="win32")return zn.env.TERM!=="linux";return Boolean(zn.env.CI)||Boolean(zn.env.WT_SESSION)||Boolean(zn.env.TERMINUS_SUBLIME)||zn.env.ConEmuTask==="{cmd::Cmder}"||zn.env.TERM_PROGRAM==="Terminus-Sublime"||zn.env.TERM_PROGRAM==="vscode"||zn.env.TERM==="xterm-256color"||zn.env.TERM==="alacritty"||zn.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var X0=W0();var ln=(n,r)=>X0?n:r,V0=ln("◆","*"),Y0=ln("■","x"),z0=ln("▲","x"),Kc=ln("◇","o"),P0=ln("┌","T"),cn=ln("│","|"),Hr=ln("└","—"),Fa=ln("┐","T"),va=ln("┘","—"),Ne=ln("●",">"),ni=ln("○"," "),A0=ln("◻","[•]"),Sc=ln("◼","[+]"),jc=ln("◻","[ ]"),Ia=ln("▪","•"),pc=ln("─","-"),C0=ln("╮","+"),T0=ln("├","+"),_0=ln("╯","+"),B0=ln("╰","+"),Na=ln("╭","+"),Ha=ln("●","•"),Sa=ln("◆","*"),ja=ln("▲","!"),pa=ln("■","x"),Se=(n)=>{switch(n){case"initial":case"active":return k("cyan",V0);case"cancel":return k("red",Y0);case"error":return k("yellow",z0);case"submit":return k("green",Kc)}},Rc=(n)=>{switch(n){case"initial":case"active":return k("cyan",cn);case"cancel":return k("red",cn);case"error":return k("yellow",cn);case"submit":return k("green",cn)}};function Oc(n,r){let t=[`${r?`${k("cyan",cn)} `:""}${n.join(" • ")}`];return r&&t.push(k("cyan",Hr)),t}var Gc=(n,r,t,i,e,o=!1)=>{let s=r,u=0;if(o)for(let c=i-1;c>=t;c--){let h=n[c];if(h&&(s-=h.length),u++,s<=e)break}else for(let c=t;c<i;c++){let h=n[c];if(h&&(s-=h.length),u++,s<=e)break}return{lineCount:s,removals:u}},He=({cursor:n,options:r,style:t,output:i=process.stdout,maxItems:e=Number.POSITIVE_INFINITY,columnPadding:o=0,rowPadding:s=4})=>{let u=xt(i)-o,c=Fe(i),h=k("dim","..."),f=Math.max(c-s,0),g=Math.max(Math.min(e,f),5),l=0;n>=g-3&&(l=Math.max(Math.min(n-g+3,r.length-g),0));let $=g<r.length&&l>0,a=g<r.length&&l+g<r.length,w=Math.min(l+g,r.length),F=[],H=0;$&&H++,a&&H++;let J=l+($?1:0),M=w-(a?1:0);for(let b=J;b<M;b++){let K=r[b],E=K?t(K,b===n):"",G=mr(E,u,{hard:!0,trim:!1}).split(`
92
- `);F.push(G),H+=G.length}if(H>f){let b=0,K=0,E=H,G=n-J,j=f,Q=()=>Gc(F,E,0,G,j),R=()=>Gc(F,E,G+1,F.length,j,!0);$?({lineCount:E,removals:b}=Q(),E>j&&(a||(j-=1),{lineCount:E,removals:K}=R())):(a||(j-=1),{lineCount:E,removals:K}=R(),E>j&&(j-=1,{lineCount:E,removals:b}=Q())),b>0&&($=!0,F.splice(0,b)),K>0&&(a=!0,F.splice(F.length-K,K))}let I=[];$&&I.push(h);for(let b of F)for(let K of b)I.push(K);return a&&I.push(h),I};var Qc=(n)=>{let r=n.active??"Yes",t=n.inactive??"No";return new ve({active:r,inactive:t,signal:n.signal,input:n.input,output:n.output,initialValue:n.initialValue??!0,render(){let i=n.withGuide??On.withGuide,e=`${Se(this.state)} `,o=i?`${k("gray",cn)} `:"",s=dr(n.output,n.message,o,e),u=`${i?`${k("gray",cn)}
92
+ `),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",(t,e)=>{if(e?.name&&td.has(e.name)){this.#r=!1,this.#o(e.name);return}if(t==="\t"&&this.#i){this.focused=this.focused==="editor"?"submit":"editor";return}if(e?.name!=="return"){if(this.#r=!1,e?.name==="backspace"&&this.cursor>0){this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--;return}if(e?.name==="delete"&&this.cursor<this.userInput.length){this._setUserInput(this.userInput.slice(0,this.cursor)+this.userInput.slice(this.cursor+1));return}t&&(this.#i&&this.focused==="submit"&&(this.focused="editor"),this.#n(t??""),this._cursor++)}}),this.on("userInput",(t)=>{this._setValue(t)}),this.on("finalize",()=>{this.value||(this.value=n.defaultValue),this.value===void 0&&(this.value="")})}}class Ki extends tr{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((t)=>t.value)}toggleInvert(){let n=this.value;if(!n)return;let r=this._enabledOptions.filter((t)=>!n.includes(t.value));this.value=r.map((t)=>t.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:t})=>t===n.cursorAt),0);this.cursor=this.options[r]?.disabled?cr(r,1,this.options):r,this.on("key",(t,e)=>{e.name==="a"&&this.toggleAll(),e.name==="i"&&this.toggleInvert()}),this.on("cursor",(t)=>{switch(t){case"left":case"up":this.cursor=cr(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=cr(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}var Wc=class extends tr{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 t=this.options.findIndex(({value:i})=>i===r.initialValue),e=t===-1?0:t;this.cursor=this.options[e]?.disabled?cr(e,1,this.options):e,this.changeValue(),this.on("cursor",(i)=>{switch(i){case"left":case"up":this.cursor=cr(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=cr(this.cursor,1,this.options);break}this.changeValue()})}};import{styleText as k,stripVTControlCharacters as Za}from"node:util";import zn from"node:process";var zc=Jt(pi(),1);function ed(){if(zn.platform!=="win32")return zn.env.TERM!=="linux";return Boolean(zn.env.CI)||Boolean(zn.env.WT_SESSION)||Boolean(zn.env.TERMINUS_SUBLIME)||zn.env.ConEmuTask==="{cmd::Cmder}"||zn.env.TERM_PROGRAM==="Terminus-Sublime"||zn.env.TERM_PROGRAM==="vscode"||zn.env.TERM==="xterm-256color"||zn.env.TERM==="alacritty"||zn.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var id=ed();var ln=(n,r)=>id?n:r,od=ln("◆","*"),sd=ln("■","x"),ud=ln("▲","x"),Ac=ln("◇","o"),cd=ln("┌","T"),cn=ln("│","|"),pr=ln("└","—"),Xa=ln("┐","T"),Va=ln("┘","—"),Ri=ln("●",">"),ce=ln("○"," "),hd=ln("◻","[•]"),Xc=ln("◼","[+]"),Vc=ln("◻","[ ]"),Ya=ln("▪","•"),Yc=ln("─","-"),fd=ln("╮","+"),gd=ln("├","+"),ld=ln("╯","+"),md=ln("╰","+"),Pa=ln("╭","+"),za=ln("●","•"),Aa=ln("◆","*"),Ca=ln("▲","!"),Ta=ln("■","x"),Oi=(n)=>{switch(n){case"initial":case"active":return k("cyan",od);case"cancel":return k("red",sd);case"error":return k("yellow",ud);case"submit":return k("green",Ac)}},Cc=(n)=>{switch(n){case"initial":case"active":return k("cyan",cn);case"cancel":return k("red",cn);case"error":return k("yellow",cn);case"submit":return k("green",cn)}};function Tc(n,r){let t=[`${r?`${k("cyan",cn)} `:""}${n.join(" • ")}`];return r&&t.push(k("cyan",pr)),t}var Pc=(n,r,t,e,i,o=!1)=>{let s=r,u=0;if(o)for(let c=e-1;c>=t;c--){let h=n[c];if(h&&(s-=h.length),u++,s<=i)break}else for(let c=t;c<e;c++){let h=n[c];if(h&&(s-=h.length),u++,s<=i)break}return{lineCount:s,removals:u}},yi=({cursor:n,options:r,style:t,output:e=process.stdout,maxItems:i=Number.POSITIVE_INFINITY,columnPadding:o=0,rowPadding:s=4})=>{let u=se(e)-o,c=Gi(e),h=k("dim","..."),f=Math.max(c-s,0),g=Math.max(Math.min(i,f),5),l=0;n>=g-3&&(l=Math.max(Math.min(n-g+3,r.length-g),0));let $=g<r.length&&l>0,a=g<r.length&&l+g<r.length,w=Math.min(l+g,r.length),F=[],v=0;$&&v++,a&&v++;let j=l+($?1:0),M=w-(a?1:0);for(let b=j;b<M;b++){let K=r[b],E=K?t(K,b===n):"",J=dr(E,u,{hard:!0,trim:!1}).split(`
93
+ `);F.push(J),v+=J.length}if(v>f){let b=0,K=0,E=v,J=n-j,S=f,O=()=>Pc(F,E,0,J,S),R=()=>Pc(F,E,J+1,F.length,S,!0);$?({lineCount:E,removals:b}=O(),E>S&&(a||(S-=1),{lineCount:E,removals:K}=R())):(a||(S-=1),{lineCount:E,removals:K}=R(),E>S&&(S-=1,{lineCount:E,removals:b}=O())),b>0&&($=!0,F.splice(0,b)),K>0&&(a=!0,F.splice(F.length-K,K))}let p=[];$&&p.push(h);for(let b of F)for(let K of b)p.push(K);return a&&p.push(h),p};var _c=(n)=>{let r=n.active??"Yes",t=n.inactive??"No";return new Ji({active:r,inactive:t,signal:n.signal,input:n.input,output:n.output,initialValue:n.initialValue??!0,render(){let e=n.withGuide??yn.withGuide,i=`${Oi(this.state)} `,o=e?`${k("gray",cn)} `:"",s=$r(n.output,n.message,o,i),u=`${e?`${k("gray",cn)}
93
94
  `:""}${s}
94
- `,c=this.value?r:t;switch(this.state){case"submit":{let h=i?`${k("gray",cn)} `:"";return`${u}${h}${k("dim",c)}`}case"cancel":{let h=i?`${k("gray",cn)} `:"";return`${u}${h}${k(["strikethrough","dim"],c)}${i?`
95
- ${k("gray",cn)}`:""}`}default:{let h=i?`${k("cyan",cn)} `:"",f=i?k("cyan",Hr):"";return`${u}${h}${this.value?`${k("green",Ne)} ${r}`:`${k("dim",ni)} ${k("dim",r)}`}${n.vertical?i?`
95
+ `,c=this.value?r:t;switch(this.state){case"submit":{let h=e?`${k("gray",cn)} `:"";return`${u}${h}${k("dim",c)}`}case"cancel":{let h=e?`${k("gray",cn)} `:"";return`${u}${h}${k(["strikethrough","dim"],c)}${e?`
96
+ ${k("gray",cn)}`:""}`}default:{let h=e?`${k("cyan",cn)} `:"",f=e?k("cyan",pr):"";return`${u}${h}${this.value?`${k("green",Ri)} ${r}`:`${k("dim",ce)} ${k("dim",r)}`}${n.vertical?e?`
96
97
  ${k("cyan",cn)} `:`
97
- `:` ${k("dim","/")} `}${this.value?`${k("dim",ni)} ${k("dim",t)}`:`${k("green",Ne)} ${t}`}
98
+ `:` ${k("dim","/")} `}${this.value?`${k("dim",ce)} ${k("dim",t)}`:`${k("green",Ri)} ${t}`}
98
99
  ${f}
99
- `}}}}).prompt()};var x0=[`${k("dim","↑/↓")} to navigate`,`${k("dim","Space:")} select`,`${k("dim","Enter:")} confirm`],wt=(n,r)=>n.split(`
100
+ `}}}}).prompt()};var dd=[`${k("dim","↑/↓")} to navigate`,`${k("dim","Space:")} select`,`${k("dim","Enter:")} confirm`],vt=(n,r)=>n.split(`
100
101
  `).map((t)=>r(t)).join(`
101
- `),yc=(n)=>{let r=(e,o)=>{let s=e.label??String(e.value);return o==="disabled"?`${k("gray",jc)} ${wt(s,(u)=>k(["strikethrough","gray"],u))}${e.hint?` ${k("dim",`(${e.hint??"disabled"})`)}`:""}`:o==="active"?`${k("cyan",A0)} ${s}${e.hint?` ${k("dim",`(${e.hint})`)}`:""}`:o==="selected"?`${k("green",Sc)} ${wt(s,(u)=>k("dim",u))}${e.hint?` ${k("dim",`(${e.hint})`)}`:""}`:o==="cancelled"?`${wt(s,(u)=>k(["strikethrough","dim"],u))}`:o==="active-selected"?`${k("green",Sc)} ${s}${e.hint?` ${k("dim",`(${e.hint})`)}`:""}`:o==="submitted"?`${wt(s,(u)=>k("dim",u))}`:`${k("dim",jc)} ${wt(s,(u)=>k("dim",u))}`},t=n.required??!0,i=n.showInstructions??!0;return new Ie({options:n.options,signal:n.signal,input:n.input,output:n.output,initialValues:n.initialValues,required:t,cursorAt:n.cursorAt,validate(e){if(t&&(e===void 0||e.length===0))return`Please select at least one option.
102
- ${k("reset",k("dim",`Press ${k(["gray","bgWhite","inverse"]," space ")} to select, ${k("gray",k("bgWhite",k("inverse"," enter ")))} to submit`))}`},render(){let e=n.withGuide??On.withGuide,o=dr(n.output,n.message,e?`${Rc(this.state)} `:"",`${Se(this.state)} `),s=`${e?`${k("gray",cn)}
102
+ `),Bc=(n)=>{let r=(i,o)=>{let s=i.label??String(i.value);return o==="disabled"?`${k("gray",Vc)} ${vt(s,(u)=>k(["strikethrough","gray"],u))}${i.hint?` ${k("dim",`(${i.hint??"disabled"})`)}`:""}`:o==="active"?`${k("cyan",hd)} ${s}${i.hint?` ${k("dim",`(${i.hint})`)}`:""}`:o==="selected"?`${k("green",Xc)} ${vt(s,(u)=>k("dim",u))}${i.hint?` ${k("dim",`(${i.hint})`)}`:""}`:o==="cancelled"?`${vt(s,(u)=>k(["strikethrough","dim"],u))}`:o==="active-selected"?`${k("green",Xc)} ${s}${i.hint?` ${k("dim",`(${i.hint})`)}`:""}`:o==="submitted"?`${vt(s,(u)=>k("dim",u))}`:`${k("dim",Vc)} ${vt(s,(u)=>k("dim",u))}`},t=n.required??!0,e=n.showInstructions??!0;return new Ki({options:n.options,signal:n.signal,input:n.input,output:n.output,initialValues:n.initialValues,required:t,cursorAt:n.cursorAt,validate(i){if(t&&(i===void 0||i.length===0))return`Please select at least one option.
103
+ ${k("reset",k("dim",`Press ${k(["gray","bgWhite","inverse"]," space ")} to select, ${k("gray",k("bgWhite",k("inverse"," enter ")))} to submit`))}`},render(){let i=n.withGuide??yn.withGuide,o=$r(n.output,n.message,i?`${Cc(this.state)} `:"",`${Oi(this.state)} `),s=`${i?`${k("gray",cn)}
103
104
  `:""}${o}
104
- `,u=this.value??[],c=(h,f)=>{if(h.disabled)return r(h,"disabled");let g=u.includes(h.value);return f&&g?r(h,"active-selected"):g?r(h,"selected"):r(h,f?"active":"inactive")};switch(this.state){case"submit":{let h=this.options.filter(({value:g})=>u.includes(g)).map((g)=>r(g,"submitted")).join(k("dim",", "))||k("dim","none"),f=dr(n.output,h,e?`${k("gray",cn)} `:"");return`${s}${f}`}case"cancel":{let h=this.options.filter(({value:g})=>u.includes(g)).map((g)=>r(g,"cancelled")).join(k("dim",", "));if(h.trim()==="")return`${s}${k("gray",cn)}`;let f=dr(n.output,h,e?`${k("gray",cn)} `:"");return`${s}${f}${e?`
105
- ${k("gray",cn)}`:""}`}case"error":{let h=e?`${k("yellow",cn)} `:"",f=this.error.split(`
106
- `).map(($,a)=>a===0?`${e?`${k("yellow",Hr)} `:""}${k("yellow",$)}`:` ${$}`).join(`
105
+ `,u=this.value??[],c=(h,f)=>{if(h.disabled)return r(h,"disabled");let g=u.includes(h.value);return f&&g?r(h,"active-selected"):g?r(h,"selected"):r(h,f?"active":"inactive")};switch(this.state){case"submit":{let h=this.options.filter(({value:g})=>u.includes(g)).map((g)=>r(g,"submitted")).join(k("dim",", "))||k("dim","none"),f=$r(n.output,h,i?`${k("gray",cn)} `:"");return`${s}${f}`}case"cancel":{let h=this.options.filter(({value:g})=>u.includes(g)).map((g)=>r(g,"cancelled")).join(k("dim",", "));if(h.trim()==="")return`${s}${k("gray",cn)}`;let f=$r(n.output,h,i?`${k("gray",cn)} `:"");return`${s}${f}${i?`
106
+ ${k("gray",cn)}`:""}`}case"error":{let h=i?`${k("yellow",cn)} `:"",f=this.error.split(`
107
+ `).map(($,a)=>a===0?`${i?`${k("yellow",pr)} `:""}${k("yellow",$)}`:` ${$}`).join(`
107
108
  `),g=s.split(`
108
109
  `).length,l=f.split(`
109
- `).length+1;return`${s}${h}${He({output:n.output,options:this.options,cursor:this.cursor,maxItems:n.maxItems,columnPadding:h.length,rowPadding:g+l,style:c}).join(`
110
+ `).length+1;return`${s}${h}${yi({output:n.output,options:this.options,cursor:this.cursor,maxItems:n.maxItems,columnPadding:h.length,rowPadding:g+l,style:c}).join(`
110
111
  ${h}`)}
111
112
  ${f}
112
- `}default:{let h=e?`${k("cyan",cn)} `:"",f=s.split(`
113
- `).length,g=i?Oc(x0,e):e?[k("cyan",Hr)]:[],l=g.join(`
114
- `),$=g.length+1;return`${s}${h}${He({output:n.output,options:this.options,cursor:this.cursor,maxItems:n.maxItems,columnPadding:h.length,rowPadding:f+$,style:c}).join(`
113
+ `}default:{let h=i?`${k("cyan",cn)} `:"",f=s.split(`
114
+ `).length,g=e?Tc(dd,i):i?[k("cyan",pr)]:[],l=g.join(`
115
+ `),$=g.length+1;return`${s}${h}${yi({output:n.output,options:this.options,cursor:this.cursor,maxItems:n.maxItems,columnPadding:h.length,rowPadding:f+$,style:c}).join(`
115
116
  ${h}`)}
116
117
  ${l}
117
- `}}}}).prompt()};var ri=(n="",r)=>{let t=r?.output??process.stdout,i=r?.withGuide??On.withGuide?`${k("gray",Hr)} `:"";t.write(`${i}${k("red",n)}
118
+ `}}}}).prompt()};var he=(n="",r)=>{let t=r?.output??process.stdout,e=r?.withGuide??yn.withGuide?`${k("gray",pr)} `:"";t.write(`${e}${k("red",n)}
118
119
 
119
- `)},Zc=(n="",r)=>{let t=r?.output??process.stdout,i=r?.withGuide??On.withGuide?`${k("gray",P0)} `:"";t.write(`${i}${n}
120
- `)},Lc=(n="",r)=>{let t=r?.output??process.stdout,i=r?.withGuide??On.withGuide?`${k("gray",cn)}
121
- ${k("gray",Hr)} `:"";t.write(`${i}${n}
120
+ `)},xc=(n="",r)=>{let t=r?.output??process.stdout,e=r?.withGuide??yn.withGuide?`${k("gray",cd)} `:"";t.write(`${e}${n}
121
+ `)},Dc=(n="",r)=>{let t=r?.output??process.stdout,e=r?.withGuide??yn.withGuide?`${k("gray",cn)}
122
+ ${k("gray",pr)} `:"";t.write(`${e}${n}
122
123
 
123
- `)};var D0=(n)=>n,nm=(n,r,t)=>{let i={hard:!0,trim:!1},e=mr(n,r,i).split(`
124
- `),o=e.reduce((c,h)=>Math.max(Rn(h),c),0),s=e.map(t).reduce((c,h)=>Math.max(Rn(h),c),0),u=r-(s-o);return mr(n,u,i)},ti=(n="",r="",t)=>{let i=t?.output??zn.stdout,e=t?.withGuide??On.withGuide,o=t?.format??D0,s=["",...nm(n,xt(i)-6,o).split(`
124
+ `)};var $d=(n)=>n,ad=(n,r,t)=>{let e={hard:!0,trim:!1},i=dr(n,r,e).split(`
125
+ `),o=i.reduce((c,h)=>Math.max(Rn(h),c),0),s=i.map(t).reduce((c,h)=>Math.max(Rn(h),c),0),u=r-(s-o);return dr(n,u,e)},fe=(n="",r="",t)=>{let e=t?.output??zn.stdout,i=t?.withGuide??yn.withGuide,o=t?.format??$d,s=["",...ad(n,se(e)-6,o).split(`
125
126
  `).map(o),""],u=Rn(r),c=Math.max(s.reduce((l,$)=>{let a=Rn($);return a>l?a:l},0),u)+2,h=s.map((l)=>`${k("gray",cn)} ${l}${" ".repeat(c-Rn(l))}${k("gray",cn)}`).join(`
126
- `),f=e?`${k("gray",cn)}
127
- `:"",g=e?T0:B0;i.write(`${f}${k("green",Kc)} ${k("reset",r)} ${k("gray",pc.repeat(Math.max(c-u-1,1))+C0)}
127
+ `),f=i?`${k("gray",cn)}
128
+ `:"",g=i?gd:md;e.write(`${f}${k("green",Ac)} ${k("reset",r)} ${k("gray",Yc.repeat(Math.max(c-u-1,1))+fd)}
128
129
  ${h}
129
- ${k("gray",g+pc.repeat(c+2)+_0)}
130
- `)};var Ga={light:ln("─","-"),heavy:ln("━","="),block:ln("█","#")};var rm=[`${k("dim","↑/↓")} to navigate`,`${k("dim","Enter:")} confirm`],Dt=(n,r)=>n.includes(`
130
+ ${k("gray",g+Yc.repeat(c+2)+ld)}
131
+ `)};var _a={light:ln("─","-"),heavy:ln("━","="),block:ln("█","#")};var bd=[`${k("dim","↑/↓")} to navigate`,`${k("dim","Enter:")} confirm`],ue=(n,r)=>n.includes(`
131
132
  `)?n.split(`
132
133
  `).map((t)=>r(t)).join(`
133
- `):r(n),Uc=(n)=>{let r=(i,e)=>{if(i===void 0)return"";let o=i.label??String(i.value);switch(e){case"disabled":return`${k("gray",ni)} ${Dt(o,(s)=>k("gray",s))}${i.hint?` ${k("dim",`(${i.hint??"disabled"})`)}`:""}`;case"selected":return`${Dt(o,(s)=>k("dim",s))}`;case"active":return`${k("green",Ne)} ${o}${i.hint?` ${k("dim",`(${i.hint})`)}`:""}`;case"cancelled":return`${Dt(o,(s)=>k(["strikethrough","dim"],s))}`;default:return`${k("dim",ni)} ${Dt(o,(s)=>k("dim",s))}`}},t=n.showInstructions??!0;return new Hc({options:n.options,signal:n.signal,input:n.input,output:n.output,initialValue:n.initialValue,render(){let i=n.withGuide??On.withGuide,e=`${Se(this.state)} `,o=`${Rc(this.state)} `,s=dr(n.output,n.message,o,e),u=`${i?`${k("gray",cn)}
134
+ `):r(n),nh=(n)=>{let r=(e,i)=>{if(e===void 0)return"";let o=e.label??String(e.value);switch(i){case"disabled":return`${k("gray",ce)} ${ue(o,(s)=>k("gray",s))}${e.hint?` ${k("dim",`(${e.hint??"disabled"})`)}`:""}`;case"selected":return`${ue(o,(s)=>k("dim",s))}`;case"active":return`${k("green",Ri)} ${o}${e.hint?` ${k("dim",`(${e.hint})`)}`:""}`;case"cancelled":return`${ue(o,(s)=>k(["strikethrough","dim"],s))}`;default:return`${k("dim",ce)} ${ue(o,(s)=>k("dim",s))}`}},t=n.showInstructions??!0;return new Wc({options:n.options,signal:n.signal,input:n.input,output:n.output,initialValue:n.initialValue,render(){let e=n.withGuide??yn.withGuide,i=`${Oi(this.state)} `,o=`${Cc(this.state)} `,s=$r(n.output,n.message,o,i),u=`${e?`${k("gray",cn)}
134
135
  `:""}${s}
135
- `;switch(this.state){case"submit":{let c=i?`${k("gray",cn)} `:"",h=dr(n.output,r(this.options[this.cursor],"selected"),c);return`${u}${h}`}case"cancel":{let c=i?`${k("gray",cn)} `:"",h=dr(n.output,r(this.options[this.cursor],"cancelled"),c);return`${u}${h}${i?`
136
- ${k("gray",cn)}`:""}`}default:{let c=i?`${k("cyan",cn)} `:"",h=u.split(`
137
- `).length,f=t?Oc(rm,i):i?[k("cyan",Hr)]:[],g=f.join(`
138
- `),l=f.length+1;return`${u}${c}${He({output:n.output,cursor:this.cursor,options:this.options,maxItems:n.maxItems,columnPadding:c.length,rowPadding:h+l,style:($,a)=>r($,$.disabled?"disabled":a?"active":"inactive")}).join(`
136
+ `;switch(this.state){case"submit":{let c=e?`${k("gray",cn)} `:"",h=$r(n.output,r(this.options[this.cursor],"selected"),c);return`${u}${h}`}case"cancel":{let c=e?`${k("gray",cn)} `:"",h=$r(n.output,r(this.options[this.cursor],"cancelled"),c);return`${u}${h}${e?`
137
+ ${k("gray",cn)}`:""}`}default:{let c=e?`${k("cyan",cn)} `:"",h=u.split(`
138
+ `).length,f=t?Tc(bd,e):e?[k("cyan",pr)]:[],g=f.join(`
139
+ `),l=f.length+1;return`${u}${c}${yi({output:n.output,cursor:this.cursor,options:this.options,maxItems:n.maxItems,columnPadding:c.length,rowPadding:h+l,style:($,a)=>r($,$.disabled?"disabled":a?"active":"inactive")}).join(`
139
140
  ${c}`)}
140
141
  ${g}
141
- `}}}}).prompt()};var Ja=`${k("gray",cn)} `;import{existsSync as fm}from"node:fs";import{openSync as tm,writeSync as im}from"node:fs";import{ReadStream as em}from"node:tty";var Wc=["10","11","12","17",...Array.from({length:16},(n,r)=>`4;${r}`)];function ii(n){let r=n.ansi.map((t,i)=>`;${i};${t}`).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 Xc(n){let r=new Map;for(let t of n.split("\x1B")){let i=t.match(/^\](\d+(?:;\d+)?);(rgba?:[0-9a-fA-F/]+)/),[,e,o]=i??[];if(e&&o)r.set(e,o)}return r}function Vc(n){return[...n].map(([r,t])=>`\x1B]${r};${t}\x1B\\`).join("")}async function Yc(){let n,r;try{n=tm("/dev/tty","r+"),r=new em(n),r.setRawMode(!0)}catch{return new Map}try{im(n,Wc.map((i)=>`\x1B]${i};?\x1B\\`).join(""));let t="";return await new Promise((i)=>{let e=setTimeout(i,120);r.on("data",(o)=>{if(t+=o.toString(),Xc(t).size>=Wc.length)clearTimeout(e),i()})}),Xc(t)}finally{r.setRawMode(!1),r.destroy()}}function Yr(n){let r=n.replace("#","");return[r.slice(0,2),r.slice(2,4),r.slice(4,6)].map((t)=>Number.parseInt(t,16)).join(";")}function zc(n,r){return`\x1B[48;2;${Yr(r)}m ${n} \x1B[0m`}function je(n,r){return`\x1B[48;2;${Yr(n)};38;2;${Yr(r)}m ● \x1B[0m`}function Pc(n){return`\x1B[38;2;${Yr(n)}m`}function pe(n,r){return`\x1B[48;2;${Yr(r)}m${n.map((t)=>`\x1B[38;2;${Yr(t)}m▄`).join("")} \x1B[0m`}function ei(n,r){let t=r.toLowerCase();return[n.name,n.group,n.native??""].some((i)=>i.toLowerCase().includes(t))}function Cc(n,r,t){let i=t.trim(),e=[],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=i?u.filter((f)=>ei(f,i)):u;if(i&&c.length===0)continue;let h=i.length>0||r.has(s.group);if(e.push({kind:"group",name:s.group,native:s.native,lead:u.find((f)=>f.lead)??s,expanded:h,count:c.length}),h)e.push(...c.map((f)=>({kind:"palette",entry:f})))}return e}function om(n,r){let t=r.trim(),i=new Set(n.filter((e)=>!e.default&&(t===""||ei(e,t))).map((e)=>e.group));return Cc(n,new Set,"").filter((e)=>e.kind==="group"&&i.has(e.name))}function sm(n){let r=n.findIndex((t)=>t.kind==="palette");return r===-1?0:r}var Bn="\x1B[0m",zr="\x1B[2m",um="\x1B[1m",Ac="\x1B[1;7m",cm="\x1B[36m",hm="\x1B[33m";function Tc(n){return n==="decode"||n==="glitch"?n:"typewriter"}class Ge extends tr{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((t)=>!t.default),this.series=[...new Set(this.named.map((t)=>t.group))],this.seriesPad=Math.max(0,...this.series.map((t)=>t.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",(t)=>{if(t==="up")this.move(-1);else if(t==="down")this.move(1);else if(t==="left")this.fold(!1);else if(t==="right")this.fold(!0)}),this.on("userInput",(t)=>{if(t!==this.lastInput)this.lastInput=t,this.rebuild("keep")}),this.on("key",(t,i)=>{if(i?.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((t)=>t.group===n&&(r===""||ei(t,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((i)=>i.name):n?.kind==="all"?this.everyone(this.rows).map((i)=>i.name):[];if(r.length===0)return;let t=r.some((i)=>!this.picked.has(i));for(let i of r)if(t)this.picked.add(i);else this.picked.delete(i)}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 t=`${n.name} | ${r}`;this.example=t.length>30?`${t.slice(0,29)}…`:t,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":"▓▒░#*+=<>?/-_",t=this.fx==="decode"?(i)=>!/[a-z0-9]/i.test(i):(i)=>i===" ";return[...this.example].map((i,e)=>e+(e*7+this.fxSeed)%3<n||t(i)?i:r[Math.floor(Math.random()*r.length)]??i).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],t=this.scope==="series"?om(this.entries,this.userInput):Cc(this.entries,this.expanded,this.userInput),i=t.length>0?sm(t)+1:0;if(this.rows=t.length>0?[{kind:"all",count:this.allCount(t)},...t]:[],n==="first")this.cursor=i;else if(n==="keep"){let e=r?.kind==="palette"?r.entry.name:"",o=e?this.rows.findIndex((s)=>s.kind==="palette"&&s.entry.name===e):-1;this.cursor=o===-1?i: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 t=r.entry.group;if(this.expanded.delete(t),this.rebuild("clamp"),this.cursor=this.rows.findIndex((i)=>i.kind==="group"&&i.name===t),this.cursor===-1)this.cursor=0;this.sync()}}renderRow(n,r){let t=r?"▶ ":" ";if(n.kind==="all"){let o=this.everyone(this.rows).every((u)=>this.picked.has(u.name))?"● ":"○ ",s=`(${n.count})`;return`${t}${o}select all ${this.color?`${zr}${s}${Bn}`: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`${t}${o}${s} ${u}`;let c=n.lead;return`${t}${o}${s} ${je(c.background,c.cursor)}${pe(c.ansi.slice(1,7),c.background)} ${zr}${u}${Bn}`}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?`${Ac} ${n.name} ${Bn}`:u?`${Ac}${Pc(u.cursor)} ${n.name} ${Bn}`:` ${um}${n.name}${Bn} `:r?`[${n.name}]`:` ${n.name}`,h=this.color?zc("●",n.lead.selection):"",f=`${this.pickedIn(n.name)}/${n.count}`,g=this.color?` ${zr}(${f})${Bn}`:` (${f})`,l=n.native?this.color?` ${zr}${n.native}${Bn}`:` ${n.native}`:"";return`${o}${c}${h}${g}${l}`}let i=n.entry,e=this.picked.has(i.name)?"● ":"○ ";if(!this.color)return` ${t}${e}${i.name.padEnd(13)} ● · ${i.ansiSource}`;return` ${t}${e}${i.name.padEnd(13)} ${je(i.background,i.cursor)}${pe(i.ansi.slice(1,7),i.background)} ${zr}${i.ansiSource}${Bn}`}draw(){let n=(w)=>this.color?`${zr}${w}${Bn}`:w,r=(w)=>this.color?`${cm}${w}${Bn}`:w,t=this.scope==="series"?"series":"catalog";if(this.state==="submit")return`${n("◇")} ${t} ${n(`· ${this.pickedCount()} picked`)}`;if(this.state==="cancel")return`${n(`◇ ${t} · cancelled`)}`;let i=this.userInput.trim(),e=this.scope==="series"?this.series.length:this.named.length,o=this.scope==="series"?this.rows.filter((w)=>w.kind==="group").length:i?this.named.filter((w)=>ei(w,i)).length:e,s=`${r("◆")} ${t} ${n(`(${o}/${e} · ${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((w,F)=>`${r("│")} ${this.renderRow(w,this.top+F===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,g=f>0?`${r("│")} ${n(`↓ ${f} more`)}`:r("│"),l=this.scope==="series"?"":" · ←→ fold",$=this.scope==="series"?"continue":"install",a=this.state==="error"?`${r("└")} ${this.color?`${hm}${this.error}${Bn}`:this.error}`:`${r("└")} ${n(`↑↓ move${l} · space pick · type to filter · enter ${$} · esc cancel`)}`;return[s,u,...h,g,a].join(`
142
- `)}}function Je(n){console.log(`
143
- ${n} palettes installed — open a new tab, or reload your terminal config`)}function _c(n){let r=_n(),t=Cn(r),i=Ur(r),e=n.filter((u)=>i.palettes.includes(u)),o=n.filter((u)=>!i.palettes.includes(u));if(o.length===0){console.log(`already installed: ${e.join(", ")}`);return}let s={...i,palettes:[...i.palettes,...o]};Nr(r,t,s),Ir(r,s);for(let u of o)console.log(` + ${u}`);Je(s.palettes.length)}function Bc(n){let r=_n(),t=Cn(r),i=Ur(r),e=n.filter((s)=>i.palettes.includes(s));if(e.length===0){console.log(`not installed: ${n.join(", ")}`);return}let o={...i,palettes:i.palettes.filter((s)=>!e.includes(s))};Nr(r,t,o),ie(r,t,i.terminals,e),Ir(r,o);for(let s of e)console.log(` - ${s}`);Je(o.palettes.length)}function xc(n){let r=_n(),t=Cn(r),i=Ur(r);if(!i.palettes.includes(n))throw Error(`${n} is not installed — \`ttheme add ${n}\` first`);let{keepTheme:e,...o}=i,s={...o,startup:n};Nr(r,t,s),Ir(r,s),console.log(gm(n,s.terminals).join(`
144
- `))}function gm(n,r){let t=r.filter((e)=>e!=="iterm2"),i=t.length>0?[`default ${n} · ${t.join(", ")} open new tabs with it once their config reloads`]:[];if(r.includes("iterm2"))i.push(`iterm2 keeps its own default · Set as Default on "ttheme · ${n}" in Settings Profiles`);return i.length>0?i:[`default ${n} · no terminal is wired to open with it — \`ttheme init\` wires one`]}function Dc(n){let r=_n(),t=Cn(r),i=new Set(Ur(r).palettes),e=Jr(t.palettes),o=ot(n?vu(e,n):e),s=Math.max(...o.map((c)=>c.name.length),0);for(let c of o)console.log(` ${i.has(c.name)?"●":"○"} ${c.name.padEnd(s)} ${c.group}`);let u=n?`${o.length} of ${e.length}`:`${e.length}`;console.log(`
145
- ${u} palettes — ${o.filter((c)=>i.has(c.name)).length} installed`)}async function nh(){let n=_n(),r=fm(Yt(n))?Cn(n).palettes.length:0,t=await Mu(Eu);zt(n,t);let i=t.palettes.length-r;console.log(`catalog ${t.version} — ${t.palettes.length} palettes${i>0?` (+${i})`:""}`)}async function Ke(n,r,t,i=!1){let e=process.env.TTHEME_SORT==="series"?n.palettes:ot(n.palettes),o=process.stdout.isTTY===!0&&!process.env.NO_COLOR,s=o?await Yc():new Map,u=new Ge({entries:e,scope:t,installed:r,required:i,color:!process.env.NO_COLOR,fx:Tc(process.env.TTHEME_FX),onFocus:o?(h)=>process.stdout.write(ii(h)):void 0}),c=await u.prompt();if(process.stdout.write(Vc(s)),Vr(c))return;return n.palettes.filter((h)=>u.picked.has(h.name)).map((h)=>h.name)}async function rh(){let n=_n(),r=Cn(n),t=Ur(n),i=await Ke(r,t.palettes,"palette");if(!i){console.log("nothing changed");return}let e=t.palettes.filter((u)=>!i.includes(u)),o=i.filter((u)=>!t.palettes.includes(u));if(o.length===0&&e.length===0){console.log("nothing changed");return}let s={...t,palettes:i};Nr(n,r,s),ie(n,r,t.terminals,e),Ir(n,s);for(let u of o)console.log(` + ${u}`);for(let u of e)console.log(` - ${u}`);Je(s.palettes.length)}function eh(n,r,t){for(let i of dm(r))n.push({from:wn(r,i),to:wn(t,i)})}function ch(n){return JSON.parse(kt(wn(n,"dist","manifest.json"),"utf8"))}function oh(n,r){let t=wn(r.root,"dist"),i=wn(r.configHome,"ttheme"),e=[{from:wn(r.root,"bin","ttheme.js"),to:wn(i,"ttheme.js")},{from:wn(r.root,"shell","ttheme.zsh"),to:wn(i,"ttheme.zsh")},{from:wn(r.root,"shell","launch-tab.zsh"),to:wn(i,"launch-tab.zsh"),executable:!0},{from:wn(t,"ghostty","ttheme.conf"),to:wn(i,"ttheme.conf")}];eh(e,wn(r.root,"shell","adapters"),wn(i,"adapters"));let o=[{file:wn(r.zdotdir,".zshrc"),block:$o(i)}],s=wn(i,"config.zsh"),u=bo(cr(s)?kt(s,"utf8"):""),c={file:s,content:n.wear?Gt(u,"TTHEME_TAB_PALETTE",n.wear==="rotate"?"seq":"off"):u},h=[];if(n.terminals.includes("ghostty"))eh(e,wn(r.root,"ghostty","shaders"),wn(r.configHome,"ghostty","shaders"));if(n.terminals.includes("alacritty")){let g=wn(r.configHome,"alacritty","alacritty.toml");if(cr(g)&&!kt(g,"utf8").includes("# ttheme begin"))h.push("alacritty.toml already exists — ttheme left it alone; add its themes/ import yourself")}h.push("wezterm: import the palettes you install from the release archive");let f={terminals:n.terminals,palettes:n.palettes,...n.wear==="keep"?{keepTheme:!0}:{}};return{home:r.home,copies:e,edits:o,settings:c,catalog:ch(r.root),installed:f,notes:h}}function sh(n){for(let t of n.copies)if(Re(Et(t.to),{recursive:!0}),th(t.to,{force:!0}),th(`${t.to}.zwc`,{force:!0}),mm(t.from,t.to),t.executable)lm(t.to,493);Re(Et(n.settings.file),{recursive:!0}),ih(n.settings.file,n.settings.content);let r=Et(Et(n.settings.file));zt(r,n.catalog),Ir(r,n.installed),Nr(r,n.catalog,n.installed,n.home);for(let t of n.edits){Re(Et(t.file),{recursive:!0});let i=cr(t.file)?kt(t.file,"utf8"):"";ih(t.file,pt(i,t.block))}}function Oe(n){if(Vr(n))ri("nothing changed"),process.exit(1);return n}function hh(){return jt.filter((n)=>n!=="iterm2"||process.platform==="darwin")}function am(n,r){return n==="iterm2"?cr(wn(r.home,"Library","Application Support","iTerm2")):cr(wn(r.configHome,n))}async function bm(n,r){return Oe(await yc({message:"wire which terminals?",options:hh().map((t)=>({value:t,hint:t===n?"detected":void 0})),initialValues:r,required:!0}))}function wm(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 Em(n){return Oe(await Uc({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 uh(n){let r=[...n.copies.filter((t)=>!cr(t.to)).map((t)=>t.to),...cr(n.settings.file)?[]:[n.settings.file],...n.edits.filter((t)=>!kt(t.file,"utf8").includes("# ttheme begin")).map((t)=>t.file)];if(r.length>0)throw Error(`init left gaps:
142
+ `}}}}).prompt()};var Ba=`${k("gray",cn)} `;import{existsSync as Nd}from"node:fs";import{openSync as wd,writeSync as Ed}from"node:fs";import{ReadStream as kd}from"node:tty";var th=["10","11","12","17",...Array.from({length:16},(n,r)=>`4;${r}`)];function ge(n){let r=n.ansi.map((t,e)=>`;${e};${t}`).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 eh(n){let r=new Map;for(let t of n.split("\x1B")){let e=t.match(/^\](\d+(?:;\d+)?);(rgba?:[0-9a-fA-F/]+)/),[,i,o]=e??[];if(i&&o)r.set(i,o)}return r}function ih(n){return[...n].map(([r,t])=>`\x1B]${r};${t}\x1B\\`).join("")}async function oh(){let n,r;try{n=wd("/dev/tty","r+"),r=new kd(n),r.setRawMode(!0)}catch{return new Map}try{Ed(n,th.map((e)=>`\x1B]${e};?\x1B\\`).join(""));let t="";return await new Promise((e)=>{let i=setTimeout(e,120);r.on("data",(o)=>{if(t+=o.toString(),eh(t).size>=th.length)clearTimeout(i),e()})}),eh(t)}finally{r.setRawMode(!1),r.destroy()}}function zr(n){let r=n.replace("#","");return[r.slice(0,2),r.slice(2,4),r.slice(4,6)].map((t)=>Number.parseInt(t,16)).join(";")}function sh(n,r){return`\x1B[48;2;${zr(r)}m ${n} \x1B[0m`}function Li(n,r){return`\x1B[48;2;${zr(n)};38;2;${zr(r)}m ● \x1B[0m`}function uh(n){return`\x1B[38;2;${zr(n)}m`}function Qi(n,r){return`\x1B[48;2;${zr(r)}m${n.map((t)=>`\x1B[38;2;${zr(t)}m▄`).join("")} \x1B[0m`}function le(n,r){let t=r.toLowerCase();return[n.name,n.group,n.native??""].some((e)=>e.toLowerCase().includes(t))}function hh(n,r,t){let e=t.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=e?u.filter((f)=>le(f,e)):u;if(e&&c.length===0)continue;let h=e.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 Md(n,r){let t=r.trim(),e=new Set(n.filter((i)=>!i.default&&(t===""||le(i,t))).map((i)=>i.group));return hh(n,new Set,"").filter((i)=>i.kind==="group"&&e.has(i.name))}function Fd(n){let r=n.findIndex((t)=>t.kind==="palette");return r===-1?0:r}var Bn="\x1B[0m",Ar="\x1B[2m",Id="\x1B[1m",ch="\x1B[1;7m",vd="\x1B[36m",pd="\x1B[33m";function fh(n){return n==="decode"||n==="glitch"?n:"typewriter"}class Zi extends tr{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((t)=>!t.default),this.series=[...new Set(this.named.map((t)=>t.group))],this.seriesPad=Math.max(0,...this.series.map((t)=>t.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",(t)=>{if(t==="up")this.move(-1);else if(t==="down")this.move(1);else if(t==="left")this.fold(!1);else if(t==="right")this.fold(!0)}),this.on("userInput",(t)=>{if(t!==this.lastInput)this.lastInput=t,this.rebuild("keep")}),this.on("key",(t,e)=>{if(e?.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((t)=>t.group===n&&(r===""||le(t,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((e)=>e.name):n?.kind==="all"?this.everyone(this.rows).map((e)=>e.name):[];if(r.length===0)return;let t=r.some((e)=>!this.picked.has(e));for(let e of r)if(t)this.picked.add(e);else this.picked.delete(e)}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 t=`${n.name} | ${r}`;this.example=t.length>30?`${t.slice(0,29)}…`:t,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":"▓▒░#*+=<>?/-_",t=this.fx==="decode"?(e)=>!/[a-z0-9]/i.test(e):(e)=>e===" ";return[...this.example].map((e,i)=>i+(i*7+this.fxSeed)%3<n||t(e)?e:r[Math.floor(Math.random()*r.length)]??e).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],t=this.scope==="series"?Md(this.entries,this.userInput):hh(this.entries,this.expanded,this.userInput),e=t.length>0?Fd(t)+1:0;if(this.rows=t.length>0?[{kind:"all",count:this.allCount(t)},...t]:[],n==="first")this.cursor=e;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?e: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 t=r.entry.group;if(this.expanded.delete(t),this.rebuild("clamp"),this.cursor=this.rows.findIndex((e)=>e.kind==="group"&&e.name===t),this.cursor===-1)this.cursor=0;this.sync()}}renderRow(n,r){let t=r?"▶ ":" ";if(n.kind==="all"){let o=this.everyone(this.rows).every((u)=>this.picked.has(u.name))?"● ":"○ ",s=`(${n.count})`;return`${t}${o}select all ${this.color?`${Ar}${s}${Bn}`: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`${t}${o}${s} ${u}`;let c=n.lead;return`${t}${o}${s} ${Li(c.background,c.cursor)}${Qi(c.ansi.slice(1,7),c.background)} ${Ar}${u}${Bn}`}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?`${ch} ${n.name} ${Bn}`:u?`${ch}${uh(u.cursor)} ${n.name} ${Bn}`:` ${Id}${n.name}${Bn} `:r?`[${n.name}]`:` ${n.name}`,h=this.color?sh("●",n.lead.selection):"",f=`${this.pickedIn(n.name)}/${n.count}`,g=this.color?` ${Ar}(${f})${Bn}`:` (${f})`,l=n.native?this.color?` ${Ar}${n.native}${Bn}`:` ${n.native}`:"";return`${o}${c}${h}${g}${l}`}let e=n.entry,i=this.picked.has(e.name)?"● ":"○ ";if(!this.color)return` ${t}${i}${e.name.padEnd(13)} ● · ${e.ansiSource}`;return` ${t}${i}${e.name.padEnd(13)} ${Li(e.background,e.cursor)}${Qi(e.ansi.slice(1,7),e.background)} ${Ar}${e.ansiSource}${Bn}`}draw(){let n=(w)=>this.color?`${Ar}${w}${Bn}`:w,r=(w)=>this.color?`${vd}${w}${Bn}`:w,t=this.scope==="series"?"series":"catalog";if(this.state==="submit")return`${n("◇")} ${t} ${n(`· ${this.pickedCount()} picked`)}`;if(this.state==="cancel")return`${n(`◇ ${t} · cancelled`)}`;let e=this.userInput.trim(),i=this.scope==="series"?this.series.length:this.named.length,o=this.scope==="series"?this.rows.filter((w)=>w.kind==="group").length:e?this.named.filter((w)=>le(w,e)).length:i,s=`${r("◆")} ${t} ${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((w,F)=>`${r("│")} ${this.renderRow(w,this.top+F===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,g=f>0?`${r("│")} ${n(`↓ ${f} more`)}`:r("│"),l=this.scope==="series"?"":" · ←→ fold",$=this.scope==="series"?"continue":"install",a=this.state==="error"?`${r("└")} ${this.color?`${pd}${this.error}${Bn}`:this.error}`:`${r("└")} ${n(`↑↓ move${l} · space pick · type to filter · enter ${$} · esc cancel`)}`;return[s,u,...h,g,a].join(`
143
+ `)}}function Ui(n,r,t,e){let i=Ur(),o=Boolean(qr(t))!==Boolean(qr(e)),s=o?kt(e,i):e;if(It(n,r,s),Ft(n,s),o)Mt(s,i)}function qi(n){console.log(`
144
+ ${n} palettes installed — open a new tab, or reload your terminal config`)}function gh(n){let r=_n(),t=Qn(r),e=sr(r),i=n.filter((u)=>e.palettes.includes(u)),o=n.filter((u)=>!e.palettes.includes(u));if(o.length===0){console.log(`already installed: ${i.join(", ")}`);return}let s={...e,palettes:[...e.palettes,...o]};Ui(r,t,e,s);for(let u of o)console.log(` + ${u}`);qi(s.palettes.length)}function lh(n){let r=_n(),t=Qn(r),e=sr(r),i=n.filter((s)=>e.palettes.includes(s));if(i.length===0){console.log(`not installed: ${n.join(", ")}`);return}let o={...e,palettes:e.palettes.filter((s)=>!i.includes(s))};Ui(r,t,e,o),gi(r,t,e.terminals,i);for(let s of i)console.log(` - ${s}`);qi(o.palettes.length)}function mh(n){let r=_n(),t=Qn(r),e=sr(r);if(!e.palettes.includes(n))throw Error(`${n} is not installed — \`ttheme add ${n}\` first`);let{keepTheme:i,...o}=e,s=Ur(),u=kt({...o,startup:n},s);It(r,t,u),Ft(r,u);let c=Mt(u,s);console.log(Hd(n,u.terminals,c&&s.running()).join(`
145
+ `))}function Hd(n,r,t){let e=r.filter((o)=>o!=="iterm2"),i=e.length>0?[`default ${n} · ${e.join(", ")} open new tabs with it once their config reloads`]:[];if(r.includes("iterm2"))i.push(t?'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 dh(n){let r=_n(),t=Qn(r),e=new Set(sr(r).palettes),i=Gr(t.palettes),o=ut(n?Ru(i,n):i),s=Math.max(...o.map((c)=>c.name.length),0);for(let c of o)console.log(` ${e.has(c.name)?"●":"○"} ${c.name.padEnd(s)} ${c.group}`);let u=n?`${o.length} of ${i.length}`:`${i.length}`;console.log(`
146
+ ${u} palettes — ${o.filter((c)=>e.has(c.name)).length} installed`)}async function $h(){let n=_n(),r=Nd(Tt(n))?Qn(n).palettes.length:0,t=await Ju(ju);_t(n,t);let e=t.palettes.length-r;console.log(`catalog ${t.version} — ${t.palettes.length} palettes${e>0?` (+${e})`:""}`)}async function Wi(n,r,t,e=!1){let i=process.env.TTHEME_SORT==="series"?n.palettes:ut(n.palettes),o=process.stdout.isTTY===!0&&!process.env.NO_COLOR,s=o?await oh():new Map,u=new Zi({entries:i,scope:t,installed:r,required:e,color:!process.env.NO_COLOR,fx:fh(process.env.TTHEME_FX),onFocus:o?(h)=>process.stdout.write(ge(h)):void 0}),c=await u.prompt();if(process.stdout.write(ih(s)),Pr(c))return;return n.palettes.filter((h)=>u.picked.has(h.name)).map((h)=>h.name)}async function ah(){let n=_n(),r=Qn(n),t=sr(n),e=await Wi(r,t.palettes,"palette");if(!e){console.log("nothing changed");return}let i=t.palettes.filter((u)=>!e.includes(u)),o=e.filter((u)=>!t.palettes.includes(u));if(o.length===0&&i.length===0){console.log("nothing changed");return}let s={...t,palettes:e};Ui(n,r,t,s),gi(n,r,t.terminals,i);for(let u of o)console.log(` + ${u}`);for(let u of i)console.log(` - ${u}`);qi(s.palettes.length)}function Eh(n,r,t){for(let e of Gd(r))n.push({from:wn(r,e),to:wn(t,e)})}function Ih(n){return JSON.parse(Nt(wn(n,"dist","manifest.json"),"utf8"))}function kh(n,r){let t=wn(r.root,"dist"),e=wn(r.configHome,"ttheme"),i=[{from:wn(r.root,"bin","ttheme.js"),to:wn(e,"ttheme.js")},{from:wn(r.root,"shell","ttheme.zsh"),to:wn(e,"ttheme.zsh")},{from:wn(r.root,"shell","launch-tab.zsh"),to:wn(e,"launch-tab.zsh"),executable:!0},{from:wn(t,"ghostty","ttheme.conf"),to:wn(e,"ttheme.conf")}];Eh(i,wn(r.root,"shell","adapters"),wn(e,"adapters"));let o=[{file:wn(r.zdotdir,".zshrc"),block:vo(e)}],s=wn(e,"config.zsh"),u=No(hr(s)?Nt(s,"utf8"):""),c={file:s,content:n.wear?Lt(u,"TTHEME_TAB_PALETTE",n.wear==="rotate"?"seq":"off"):u},h=[];if(n.terminals.includes("ghostty"))Eh(i,wn(r.root,"ghostty","shaders"),wn(r.configHome,"ghostty","shaders"));if(n.terminals.includes("alacritty")){let g=wn(r.configHome,"alacritty","alacritty.toml");if(hr(g)&&!Nt(g,"utf8").includes("# ttheme begin"))h.push("alacritty.toml already exists — ttheme left it alone; add its themes/ import yourself")}h.push("wezterm: import the palettes you install from the release archive");let f={terminals:n.terminals,palettes:n.palettes,...n.wear==="keep"?{keepTheme:!0}:{}};return{home:r.home,copies:i,edits:o,settings:c,catalog:Ih(r.root),installed:f,notes:h}}function Kd(n){try{return sr(n).itermBase}catch{return}}function Mh(n,r=Ur()){for(let o of n.copies)if(Xi(pt(o.to),{recursive:!0}),bh(o.to,{force:!0}),bh(`${o.to}.zwc`,{force:!0}),jd(o.from,o.to),o.executable)Sd(o.to,493);Xi(pt(n.settings.file),{recursive:!0}),wh(n.settings.file,n.settings.content);let t=pt(pt(n.settings.file)),e=Kd(t),i=kt(e?{...n.installed,itermBase:e}:n.installed,r);_t(t,n.catalog),Ft(t,i),It(t,n.catalog,i,n.home);for(let o of n.edits){Xi(pt(o.file),{recursive:!0});let s=hr(o.file)?Nt(o.file,"utf8"):"";wh(o.file,Ot(s,o.block))}return Mt(i,r)}function Vi(n){if(Pr(n))he("nothing changed"),process.exit(1);return n}function vh(){return yt.filter((n)=>n!=="iterm2"||process.platform==="darwin")}function Rd(n,r){return n==="iterm2"?hr(wn(r.home,"Library","Application Support","iTerm2")):hr(wn(r.configHome,n))}async function yd(n,r){return Vi(await Bc({message:"wire which terminals?",options:vh().map((t)=>({value:t,hint:t===n?"detected":void 0})),initialValues:r,required:!0}))}function Od(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 Ld(n){return Vi(await nh({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 Fh(n){let r=[...n.copies.filter((t)=>!hr(t.to)).map((t)=>t.to),...hr(n.settings.file)?[]:[n.settings.file],...n.edits.filter((t)=>!Nt(t.file,"utf8").includes("# ttheme begin")).map((t)=>t.file)];if(r.length>0)throw Error(`init left gaps:
146
147
  ${r.join(`
147
- `)}`)}function fh(n,r){return[...new Set(n.palettes.filter((t)=>r.includes(t.name)).map((t)=>t.group))]}function km(n,r){let t=n.palettes.find((e)=>e.name===qr(r)),i=process.stdout.isTTY===!0&&!process.env.NO_COLOR&&!process.env.TMUX;if(!t||!i)return!1;return process.stdout.write(ii(t)),!0}function Mm(n,r,t){if(n==="keep")return["terminal colors left alone — paint a tab with `ttheme <palette>`"," `ttheme default <palette>` sets the terminal default"];return[`default ${r}${t?" — 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 Fm(n,r,t,i){let e=fh(n.catalog,r.palettes);ti([`${e.join(", ")} (${r.palettes.length})`,...Mm(t,qr(n.installed),i)].join(`
148
- `),`installed ${r.palettes.length} palettes`);let o=["exec zsh the ttheme command in this tab"];if(r.terminals.includes("ghostty"))o.push("restart ghostty new tabs pick up its config");if(r.terminals.includes("kitty"))o.push("new kitty window picks up its config");if(r.terminals.includes("iterm2"))o.push(...vm(t==="default"?qr(n.installed):void 0));ti([...o,...n.notes].join(`
149
- `),"next"),Lc("done")}function vm(n){let r=['iterm2 profiles a "ttheme · <palette>" per palette in Settings › Profiles'];if(n)r.push(` Set as Default on "ttheme · ${n}" and every new tab wears it`);return r}function Im(n,r){let t=[`placed ${n.copies.length} files`,`settings in ${n.settings.file} — edit later with \`ttheme config\``,...n.edits.map((i)=>`wired ${i.file}`)];if(r.terminals.includes("ghostty"))t.push("restart ghostty to pick up its config");if(r.terminals.includes("kitty"))t.push("open a new kitty window to pick up its config");if(r.terminals.includes("iterm2"))t.push('iterm2 gets a "ttheme · <palette>" profile per palette under Settings › Profiles');t.push(...n.notes),t.push("no palettes yet — open a new shell (`exec zsh`), then `ttheme browse` picks them from the catalog"),console.log(t.join(`
150
- `))}async function gh(n={}){let r=wn(import.meta.dirname,"..");if(!cr(wn(r,"bin","ttheme.js")))throw Error("bin/ttheme.js is missing — run `mise run bin:build` first");if(!cr(wn(r,"dist"))){if(typeof Bun>"u")throw Error("this package is missing dist/ — reinstall @kecan0406/ttheme");await Kt()}let t=$m(),i=process.env.XDG_CONFIG_HOME??wn(t,".config"),e=process.env.ZDOTDIR??t,o={root:r,home:t,configHome:i,zdotdir:e},s=lo(process.env),u=hh().filter((w)=>w===s||am(w,o));if(!(!n.yes&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0)){if(u.length===0)throw Error("no supported terminal detected — run this inside ghostty, kitty, alacritty or iterm2");let w={terminals:u,palettes:[]},F=oh(w,o);sh(F),uh(F),Im(F,w);return}Zc("ttheme init");let h=await bm(s,u),f=await Ke(ch(r),[],"series",!0);if(!f)ri("nothing changed"),process.exit(1);let g=qr({terminals:h,palettes:f}),l=await Em(g),$={terminals:h,palettes:f,wear:l},a=oh($,o);if(ti([`install ${f.length} palettes — ${fh(a.catalog,f).join(", ")}`,`copy ${a.copies.length} files under ${i}`,`write ${a.settings.file}`,...a.edits.map((w)=>`edit ${w.file}`),wm(l,g)].join(`
151
- `),`wiring ${h.join(", ")}`),!Oe(await Qc({message:"apply these changes?"})))ri("nothing changed"),process.exit(1);sh(a),uh(a),Fm(a,$,l,l!=="keep"&&km(a.catalog,a.installed))}var $h=[{name:"build",args:[],about:"emit dist/ for every terminal, plus the zsh palette table",flags:{only:{type:"string",multiple:!0,value:"<terminal>",choices:vo,about:"rebuild just this terminal — repeat it for more"}},run:(n,{only:r})=>Kt({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})=>gh({yes:r})},{name:"browse",args:[],about:"pick palettes from the catalog in a live picker",run:()=>rh()},{name:"list",args:["[query]"],about:"show the catalog, marking what is installed",run:([n])=>Dc(n)},{name:"add",args:["<palette...>"],about:"install palettes from the catalog",run:(n)=>_c(n)},{name:"remove",args:["<palette...>"],about:"uninstall palettes",run:(n)=>Bc(n)},{name:"default",args:["<palette>"],about:"make an installed palette the one new tabs open with",run:([n])=>xc(n)},{name:"find",args:["<palette>"],about:"pick a safebooru background for a palette — preview opens this on tab",hidden:!0,run:([n])=>rc(n)},{name:"image",args:["<palette>","<action>"],about:"switch a palette between its saved backgrounds, or remove the one shown — preview calls this",hidden:!0,run:([n,r])=>tc(n,r)},{name:"update",args:[],about:"refresh the catalog from the registry",run:()=>nh()}];class Sr extends Error{verb;constructor(n,r){super(n);this.verb=r}}function lh(n){let r=$h.find((t)=>t.name===n);if(!r)throw new Sr(n.startsWith("-")?`unknown option '${n}'`:`unknown command '${n}'`);return r}function Hm(n,r){let t={help:{type:"boolean",short:"h"}};for(let[i,{type:e,multiple:o}]of Object.entries(n.flags??{}))t[i]={type:e,multiple:o===!0};try{return Nm({args:r,options:t,allowPositionals:!0})}catch(i){let[e=""]=(i instanceof Error?i.message:String(i)).split(". ");throw new Sr(`${e.charAt(0).toLowerCase()}${e.slice(1)}`,n)}}function Sm(n){let[r,...t]=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 t[0]===void 0?{kind:"help",code:0}:{kind:"help",verb:lh(t[0]),code:0};let i=lh(r),e=Hm(i,t);if(e.values.help)return{kind:"help",verb:i,code:0};for(let[f,{choices:g}]of Object.entries(i.flags??{}))for(let l of[e.values[f]??[]].flat())if(g&&!g.includes(String(l)))throw new Sr(`--${f} takes ${g.join(", ")} — not ${l}`,i);let o=e.positionals,s=i.args.filter((f)=>f.startsWith("<")).length,u=i.args.some((f)=>f.includes("..."))?Number.POSITIVE_INFINITY:i.args.length;if(o.length<s)throw new Sr(`missing ${i.args[o.length]}`,i);if(o.length>u)throw new Sr(`too many arguments: ${o.slice(u).join(" ")}`,i);let{help:c,...h}=e.values;return{kind:"run",verb:i,args:o,flags:h}}function mh(n){let r=Object.entries(n.flags??{}).map(([t,{value:i}])=>`[--${t}${i?` ${i}`:""}]`);return[n.name,...r,...n.args].join(" ")}function dh(n){let r=Math.max(...n.map(([t])=>t.length));return n.map(([t,i])=>` ${t.padEnd(r)} ${i}`)}function Qe(n){if(n){let r=Object.entries(n.flags??{}).map(([t,{value:i,about:e}])=>[`--${t}${i?` ${i}`:""}`,e]);return[`Usage: ttheme ${mh(n)}`,"",n.about,...r.length>0?["","Options:",...dh(r)]:[]].join(`
152
- `)}return["Usage: ttheme <command>","",Dn.description,"","Commands:",...dh($h.filter((r)=>!r.hidden).map((r)=>[mh(r),r.about])),"","ttheme <command> --help describes one command · ttheme --version prints the version"].join(`
153
- `)}async function ah(n){try{let r=Sm(n);if(r.kind==="version")return console.log(Dn.version),0;if(r.kind==="help"){if(r.code===0)console.log(Qe(r.verb));else console.error(Qe(r.verb));return r.code}let t=await r.verb.run(r.args,r.flags);return typeof t==="number"?t:0}catch(r){if(r instanceof Sr)return console.error(`ttheme${r.verb?` ${r.verb.name}`:""}: ${r.message}
148
+ `)}`)}function ph(n,r){return[...new Set(n.palettes.filter((t)=>r.includes(t.name)).map((t)=>t.group))]}function Qd(n,r){let t=n.palettes.find((i)=>i.name===Wr(r)),e=process.stdout.isTTY===!0&&!process.env.NO_COLOR&&!process.env.TMUX;if(!t||!e)return!1;return process.stdout.write(ge(t)),!0}function Zd(n,r,t){if(n==="keep")return["terminal colors left alone — paint a tab with `ttheme <palette>`"," `ttheme default <palette>` sets the terminal default"];return[`default ${r}${t?" — 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 Ud(n,r,t,e,i){let o=ph(n.catalog,r.palettes);fe([`${o.join(", ")} (${r.palettes.length})`,...Zd(t,Wr(n.installed),e)].join(`
149
+ `),`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("iterm2"))s.push(...qd(t==="default"?Wr(n.installed):void 0,i));fe([...s,...n.notes].join(`
150
+ `),"next"),Dc("done")}function qd(n,r){let t=['iterm2 profiles a "ttheme · <palette>" per palette in Settings › Profiles'];if(n)t.push(r?`restart iterm2 new tabs open on "ttheme · default", which wears ${n}`:`iterm2 default "ttheme · default" wears ${n} and follows \`ttheme default\``);return t}function Wd(n,r){let t=[`placed ${n.copies.length} files`,`settings in ${n.settings.file} — edit later with \`ttheme config\``,...n.edits.map((e)=>`wired ${e.file}`)];if(r.terminals.includes("ghostty"))t.push("restart ghostty to pick up its config");if(r.terminals.includes("kitty"))t.push("open a new kitty window to pick up its config");if(r.terminals.includes("iterm2"))t.push('iterm2 gets a "ttheme · <palette>" profile per palette under Settings › Profiles');t.push(...n.notes),t.push("no palettes yet — open a new shell (`exec zsh`), then `ttheme browse` picks them from the catalog"),console.log(t.join(`
151
+ `))}async function Nh(n={}){let r=wn(import.meta.dirname,"..");if(!hr(wn(r,"bin","ttheme.js")))throw Error("bin/ttheme.js is missing — run `mise run bin:build` first");if(!hr(wn(r,"dist"))){if(typeof Bun>"u")throw Error("this package is missing dist/ — reinstall @kecan0406/ttheme");await Zt()}let t=Jd(),e=process.env.XDG_CONFIG_HOME??wn(t,".config"),i=process.env.ZDOTDIR??t,o={root:r,home:t,configHome:e,zdotdir:i},s=Fo(process.env),u=vh().filter((v)=>v===s||Rd(v,o));if(!(!n.yes&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0)){if(u.length===0)throw Error("no supported terminal detected — run this inside ghostty, kitty, alacritty or iterm2");let v={terminals:u,palettes:[]},j=kh(v,o);Mh(j),Fh(j),Wd(j,v);return}xc("ttheme init");let h=await yd(s,u),f=await Wi(Ih(r),[],"series",!0);if(!f)he("nothing changed"),process.exit(1);let g=Wr({terminals:h,palettes:f}),l=await Ld(g),$={terminals:h,palettes:f,wear:l},a=kh($,o);if(fe([`install ${f.length} palettes — ${ph(a.catalog,f).join(", ")}`,`copy ${a.copies.length} files under ${e}`,`write ${a.settings.file}`,...a.edits.map((v)=>`edit ${v.file}`),Od(l,g),...h.includes("iterm2")&&l!=="keep"?['make "ttheme · default" the iTerm2 default profile']:[]].join(`
152
+ `),`wiring ${h.join(", ")}`),!Vi(await _c({message:"apply these changes?"})))he("nothing changed"),process.exit(1);let w=Ur(),F=Mh(a,w);Fh(a),Ud(a,$,l,l!=="keep"&&Qd(a.catalog,a.installed),F&&w.running())}var Gh=[{name:"build",args:[],about:"emit dist/ for every terminal, plus the zsh palette table",flags:{only:{type:"string",multiple:!0,value:"<terminal>",choices:Ko,about:"rebuild just this terminal — repeat it for more"}},run:(n,{only:r})=>Zt({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})=>Nh({yes:r})},{name:"browse",args:[],about:"pick palettes from the catalog in a live picker",run:()=>ah()},{name:"list",args:["[query]"],about:"show the catalog, marking what is installed",run:([n])=>dh(n)},{name:"add",args:["<palette...>"],about:"install palettes from the catalog",run:(n)=>gh(n)},{name:"remove",args:["<palette...>"],about:"uninstall palettes",run:(n)=>lh(n)},{name:"default",args:["<palette>"],about:"make an installed palette the one new tabs open with",run:([n])=>mh(n)},{name:"find",args:["<palette>"],about:"pick a safebooru background for a palette — preview opens this on tab",hidden:!0,run:([n])=>ac(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])=>bc(n,r)},{name:"update",args:[],about:"refresh the catalog from the registry",run:()=>$h()}];class Nr extends Error{verb;constructor(n,r){super(n);this.verb=r}}function Hh(n){let r=Gh.find((t)=>t.name===n);if(!r)throw new Nr(n.startsWith("-")?`unknown option '${n}'`:`unknown command '${n}'`);return r}function Vd(n,r){let t={help:{type:"boolean",short:"h"}};for(let[e,{type:i,multiple:o}]of Object.entries(n.flags??{}))t[e]={type:i,multiple:o===!0};try{return Xd({args:r,options:t,allowPositionals:!0})}catch(e){let[i=""]=(e instanceof Error?e.message:String(e)).split(". ");throw new Nr(`${i.charAt(0).toLowerCase()}${i.slice(1)}`,n)}}function Yd(n){let[r,...t]=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 t[0]===void 0?{kind:"help",code:0}:{kind:"help",verb:Hh(t[0]),code:0};let e=Hh(r),i=Vd(e,t);if(i.values.help)return{kind:"help",verb:e,code:0};for(let[f,{choices:g}]of Object.entries(e.flags??{}))for(let l of[i.values[f]??[]].flat())if(g&&!g.includes(String(l)))throw new Nr(`--${f} takes ${g.join(", ")} — not ${l}`,e);let o=i.positionals,s=e.args.filter((f)=>f.startsWith("<")).length,u=e.args.some((f)=>f.includes("..."))?Number.POSITIVE_INFINITY:e.args.length;if(o.length<s)throw new Nr(`missing ${e.args[o.length]}`,e);if(o.length>u)throw new Nr(`too many arguments: ${o.slice(u).join(" ")}`,e);let{help:c,...h}=i.values;return{kind:"run",verb:e,args:o,flags:h}}function Sh(n){let r=Object.entries(n.flags??{}).map(([t,{value:e}])=>`[--${t}${e?` ${e}`:""}]`);return[n.name,...r,...n.args].join(" ")}function jh(n){let r=Math.max(...n.map(([t])=>t.length));return n.map(([t,e])=>` ${t.padEnd(r)} ${e}`)}function Yi(n){if(n){let r=Object.entries(n.flags??{}).map(([t,{value:e,about:i}])=>[`--${t}${e?` ${e}`:""}`,i]);return[`Usage: ttheme ${Sh(n)}`,"",n.about,...r.length>0?["","Options:",...jh(r)]:[]].join(`
153
+ `)}return["Usage: ttheme <command>","",Dn.description,"","Commands:",...jh(Gh.filter((r)=>!r.hidden).map((r)=>[Sh(r),r.about])),"","ttheme <command> --help describes one command · ttheme --version prints the version"].join(`
154
+ `)}async function Jh(n){try{let r=Yd(n);if(r.kind==="version")return console.log(Dn.version),0;if(r.kind==="help"){if(r.code===0)console.log(Yi(r.verb));else console.error(Yi(r.verb));return r.code}let t=await r.verb.run(r.args,r.flags);return typeof t==="number"?t:0}catch(r){if(r instanceof Nr)return console.error(`ttheme${r.verb?` ${r.verb.name}`:""}: ${r.message}
154
155
 
155
- ${Qe(r.verb)}`),1;return console.error(`
156
- ${r instanceof Error?r.message:String(r)}`),1}}if(jm)process.exitCode=await ah(process.argv.slice(2));
156
+ ${Yi(r.verb)}`),1;return console.error(`
157
+ ${r instanceof Error?r.message:String(r)}`),1}}if(Pd)process.exitCode=await Jh(process.argv.slice(2));