@kecan0406/ttheme 1.0.30 → 1.0.31

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,41 +1,61 @@
1
1
  #!/usr/bin/env node
2
- import{createRequire as ff}from"node:module";var tf=Object.create;var{getPrototypeOf:ef,defineProperty:cs,getOwnPropertyNames:sf}=Object;var of=Object.prototype.hasOwnProperty;function uf(n){return this[n]}var cf,hf,Kt=(n,r,t)=>{var e=n!=null&&typeof n==="object";if(e){var i=r?cf??=new WeakMap:hf??=new WeakMap,s=i.get(n);if(s)return s}t=n!=null?tf(ef(n)):{};let o=r||!n||!n.__esModule?cs(t,"default",{value:n,enumerable:!0}):t;for(let u of sf(n))if(!of.call(o,u))cs(o,u,{get:uf.bind(n,u),enumerable:!0});if(e)i.set(n,o);return o};var bn=(n,r)=>()=>(r||n((r={exports:{}}).exports,r),r.exports);var Gn=ff(import.meta.url);var Es=bn((Tm,Zt)=>{var Ms=Ms||function(n){return Buffer.from(n).toString("base64")};function bf(n){var r=this,t=Math.round,e=Math.floor,i=Array(64),s=Array(64),o=Array(64),u=Array(64),c,h,f,g,l=Array(65535),a=Array(65535),m=Array(64),b=Array(64),E=[],F=0,H=7,p=Array(64),I=Array(64),w=Array(64),O=Array(256),k=Array(2048),G,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],K=[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],z=[0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,125],P=[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],Nn=[0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0],Z=[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],Mn=[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 an(d){var J=[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((J[q]*d+50)/100);if(Q<1)Q=1;else if(Q>255)Q=255;i[S[q]]=Q}var V=[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 Y=0;Y<64;Y++){var en=e((V[Y]*d+50)/100);if(en<1)en=1;else if(en>255)en=255;s[S[Y]]=en}var sn=[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 v=0;v<8;v++)o[In]=1/(i[S[In]]*sn[$n]*sn[v]*8),u[In]=1/(s[S[In]]*sn[$n]*sn[v]*8),In++}function x(d,J){var q=0,Q=0,V=[];for(var Y=1;Y<=16;Y++){for(var en=1;en<=d[Y];en++)V[J[Q]]=[],V[J[Q]][0]=q,V[J[Q]][1]=Y,Q++,q++;q*=2}return V}function yn(){c=x(K,R),h=x(Nn,Z),f=x(z,P),g=x(B,Mn)}function on(){var d=1,J=2;for(var q=1;q<=15;q++){for(var Q=d;Q<J;Q++)a[32767+Q]=q,l[32767+Q]=[],l[32767+Q][1]=q,l[32767+Q][0]=Q;for(var V=-(J-1);V<=-d;V++)a[32767+V]=q,l[32767+V]=[],l[32767+V][1]=q,l[32767+V][0]=J-1+V;d<<=1,J<<=1}}function nn(){for(var d=0;d<256;d++)k[d]=19595*d,k[d+256>>0]=38470*d,k[d+512>>0]=7471*d+32768,k[d+768>>0]=-11059*d,k[d+1024>>0]=-21709*d,k[d+1280>>0]=32768*d+8421375,k[d+1536>>0]=-27439*d,k[d+1792>>0]=-5329*d}function T(d){var J=d[0],q=d[1]-1;while(q>=0){if(J&1<<q)F|=1<<H;if(q--,H--,H<0){if(F==255)$(255),$(0);else $(F);H=7,F=0}}}function $(d){E.push(d)}function L(d){$(d>>8&255),$(d&255)}function fn(d,J){var q,Q,V,Y,en,sn,In,$n,v=0,j,X=8,En=64;for(j=0;j<X;++j){q=d[v],Q=d[v+1],V=d[v+2],Y=d[v+3],en=d[v+4],sn=d[v+5],In=d[v+6],$n=d[v+7];var A=q+$n,D=q-$n,ln=Q+In,U=Q-In,un=V+sn,jn=V-sn,kn=Y+en,Wn=Y-en,xn=A+kn,vr=A-kn,Rr=ln+un,Jr=ln-un;d[v]=xn+Rr,d[v+4]=xn-Rr;var Dr=(Jr+vr)*0.707106781;d[v+2]=vr+Dr,d[v+6]=vr-Dr,xn=Wn+jn,Rr=jn+U,Jr=U+D;var nt=(xn-Jr)*0.382683433,Gt=0.5411961*xn+nt,rt=1.306562965*Jr+nt,tt=Rr*0.707106781,et=D+tt,it=D-tt;d[v+5]=it+Gt,d[v+3]=it-Gt,d[v+1]=et+rt,d[v+7]=et-rt,v+=8}v=0;for(j=0;j<X;++j){q=d[v],Q=d[v+8],V=d[v+16],Y=d[v+24],en=d[v+32],sn=d[v+40],In=d[v+48],$n=d[v+56];var Ci=q+$n,Me=q-$n,_i=Q+In,Bi=Q-In,xi=V+sn,Di=V-sn,ns=Y+en,rf=Y-en,st=Ci+ns,Ee=Ci-ns,Ot=_i+xi,Rt=_i-xi;d[v]=st+Ot,d[v+32]=st-Ot;var rs=(Rt+Ee)*0.707106781;d[v+16]=Ee+rs,d[v+48]=Ee-rs,st=rf+Di,Ot=Di+Bi,Rt=Bi+Me;var ts=(st-Rt)*0.382683433,es=0.5411961*st+ts,is=1.306562965*Rt+ts,ss=Ot*0.707106781,os=Me+ss,us=Me-ss;d[v+40]=us+es,d[v+24]=us-es,d[v+8]=os+is,d[v+56]=os-is,v++}var Jt;for(j=0;j<En;++j)Jt=d[j]*J[j],m[j]=Jt>0?Jt+0.5|0:Jt-0.5|0;return m}function gn(){L(65504),L(16),$(74),$(70),$(73),$(70),$(0),$(1),$(1),$(0),L(1),L(1),$(0),$(0)}function rn(d){if(!d)return;if(L(65505),d[0]===69&&d[1]===120&&d[2]===105&&d[3]===102)L(d.length+2);else L(d.length+5+2),$(69),$(120),$(105),$(102),$(0);for(var J=0;J<d.length;J++)$(d[J])}function tn(d,J){L(65472),L(17),$(8),L(J),L(d),$(3),$(1),$(17),$(0),$(2),$(17),$(1),$(3),$(17),$(1)}function C(){L(65499),L(132),$(0);for(var d=0;d<64;d++)$(i[d]);$(1);for(var J=0;J<64;J++)$(s[J])}function y(){L(65476),L(418),$(0);for(var d=0;d<16;d++)$(K[d+1]);for(var J=0;J<=11;J++)$(R[J]);$(16);for(var q=0;q<16;q++)$(z[q+1]);for(var Q=0;Q<=161;Q++)$(P[Q]);$(1);for(var V=0;V<16;V++)$(Nn[V+1]);for(var Y=0;Y<=11;Y++)$(Z[Y]);$(17);for(var en=0;en<16;en++)$(B[en+1]);for(var sn=0;sn<=161;sn++)$(Mn[sn])}function N(d){if(typeof d>"u"||d.constructor!==Array)return;d.forEach((J)=>{if(typeof J!=="string")return;L(65534);var q=J.length;L(q+2);var Q;for(Q=0;Q<q;Q++)$(J.charCodeAt(Q))})}function mn(){L(65498),L(12),$(3),$(1),$(0),$(2),$(17),$(3),$(17),$(0),$(63),$(0)}function W(d,J,q,Q,V){var Y=V[0],en=V[240],sn,In=16,$n=63,v=64,j=fn(d,J);for(var X=0;X<v;++X)b[S[X]]=j[X];var En=b[0]-q;if(q=b[0],En==0)T(Q[0]);else sn=32767+En,T(Q[a[sn]]),T(l[sn]);var A=63;for(;A>0&&b[A]==0;A--);if(A==0)return T(Y),q;var D=1,ln;while(D<=A){var U=D;for(;b[D]==0&&D<=A;++D);var un=D-U;if(un>=In){ln=un>>4;for(var jn=1;jn<=ln;++jn)T(en);un=un&15}sn=32767+b[D],T(V[(un<<4)+a[sn]]),T(l[sn]),D++}if(A!=$n)T(Y);return q}function _(){var d=String.fromCharCode;for(var J=0;J<256;J++)O[J]=d(J)}this.encode=function(d,J){var q=new Date().getTime();if(J)Un(J);E=[],F=0,H=7,L(65496),gn(),N(d.comments),rn(d.exifBuffer),C(),tn(d.width,d.height),y(),mn();var Q=0,V=0,Y=0;F=0,H=7,this.encode.displayName="_encode_";var{data:en,width:sn,height:In}=d,$n=sn*4,v=sn*3,j,X=0,En,A,D,ln,U,un,jn,kn;while(X<In){j=0;while(j<$n){ln=$n*X+j,U=ln,un=-1,jn=0;for(kn=0;kn<64;kn++){if(jn=kn>>3,un=(kn&7)*4,U=ln+jn*$n+un,X+jn>=In)U-=$n*(X+1+jn-In);if(j+un>=$n)U-=j+un-$n+4;En=en[U++],A=en[U++],D=en[U++],p[kn]=(k[En]+k[A+256>>0]+k[D+512>>0]>>16)-128,I[kn]=(k[En+768>>0]+k[A+1024>>0]+k[D+1280>>0]>>16)-128,w[kn]=(k[En+1280>>0]+k[A+1536>>0]+k[D+1792>>0]>>16)-128}Q=W(p,o,Q,c,f),V=W(I,u,V,h,g),Y=W(w,u,Y,h,g),j+=32}X+=8}if(H>=0){var Wn=[];Wn[1]=H+1,Wn[0]=(1<<H+1)-1,T(Wn)}if(L(65497),typeof Zt>"u")return new Uint8Array(E);return Buffer.from(E);var xn,vr};function Un(d){if(d<=0)d=1;if(d>100)d=100;if(G==d)return;var J=0;if(d<50)J=Math.floor(5000/d);else J=Math.floor(200-d*2);an(J),G=d}function zn(){var d=new Date().getTime();if(!n)n=50;_(),yn(),on(),nn(),Un(n);var J=new Date().getTime()-d}zn()}if(typeof Zt<"u")Zt.exports=ps;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].encode=ps;function ps(n,r){if(typeof r>"u")r=50;var t=new bf(r),e=t.encode(n,r);return{data:e,width:n.width,height:n.height}}});var Fs=bn((Cm,ye)=>{var Ne=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,s=2276,o=1567,u=3784,c=5793,h=2896;function f(){}function g(H,p){var I=0,w=[],O,k,G=16;while(G>0&&!H[G-1])G--;w.push({children:[],index:0});var S=w[0],K;for(O=0;O<G;O++){for(k=0;k<H[O];k++){S=w.pop(),S.children[S.index]=p[I];while(S.index>0){if(w.length===0)throw Error("Could not recreate Huffman Table");S=w.pop()}S.index++,w.push(S);while(w.length<=O)w.push(K={children:[],index:0}),S.children[S.index]=K.children,S=K;I++}if(O+1<G)w.push(K={children:[],index:0}),S.children[S.index]=K.children,S=K}return w[0].children}function l(H,p,I,w,O,k,G,S,K,R){var{precision:z,samplesPerLine:P,scanLines:Nn,mcusPerLine:Z,progressive:B,maxH:Mn,maxV:an}=I,x=p,yn=0,on=0;function nn(){if(on>0)return on--,yn>>on&1;if(yn=H[p++],yn==255){var v=H[p++];if(v)throw Error("unexpected marker: "+(yn<<8|v).toString(16))}return on=7,yn>>>7}function T(v){var j=v,X;while((X=nn())!==null){if(j=j[X],typeof j==="number")return j;if(typeof j!=="object")throw Error("invalid huffman sequence")}return null}function $(v){var j=0;while(v>0){var X=nn();if(X===null)return;j=j<<1|X,v--}return j}function L(v){var j=$(v);if(j>=1<<v-1)return j;return j+(-1<<v)+1}function fn(v,j){var X=T(v.huffmanTableDC),En=X===0?0:L(X);j[0]=v.pred+=En;var A=1;while(A<64){var D=T(v.huffmanTableAC),ln=D&15,U=D>>4;if(ln===0){if(U<15)break;A+=16;continue}A+=U;var un=r[A];j[un]=L(ln),A++}}function gn(v,j){var X=T(v.huffmanTableDC),En=X===0?0:L(X)<<K;j[0]=v.pred+=En}function rn(v,j){j[0]|=nn()<<K}var tn=0;function C(v,j){if(tn>0){tn--;return}var X=k,En=G;while(X<=En){var A=T(v.huffmanTableAC),D=A&15,ln=A>>4;if(D===0){if(ln<15){tn=$(ln)+(1<<ln)-1;break}X+=16;continue}X+=ln;var U=r[X];j[U]=L(D)*(1<<K),X++}}var y=0,N;function mn(v,j){var X=k,En=G,A=0;while(X<=En){var D=r[X],ln=j[D]<0?-1:1;switch(y){case 0:var U=T(v.huffmanTableAC),un=U&15,A=U>>4;if(un===0)if(A<15)tn=$(A)+(1<<A),y=4;else A=16,y=1;else{if(un!==1)throw Error("invalid ACn encoding");N=L(un),y=A?2:3}continue;case 1:case 2:if(j[D])j[D]+=(nn()<<K)*ln;else if(A--,A===0)y=y==2?3:0;break;case 3:if(j[D])j[D]+=(nn()<<K)*ln;else j[D]=N<<K,y=0;break;case 4:if(j[D])j[D]+=(nn()<<K)*ln;break}X++}if(y===4){if(tn--,tn===0)y=0}}function W(v,j,X,En,A){var D=X/Z|0,ln=X%Z,U=D*v.v+En,un=ln*v.h+A;if(v.blocks[U]===void 0&&R.tolerantDecoding)return;j(v,v.blocks[U][un])}function _(v,j,X){var En=X/v.blocksPerLine|0,A=X%v.blocksPerLine;if(v.blocks[En]===void 0&&R.tolerantDecoding)return;j(v,v.blocks[En][A])}var Un=w.length,zn,d,J,q,Q,V;if(B)if(k===0)V=S===0?gn:rn;else V=S===0?C:mn;else V=fn;var Y=0,en,sn;if(Un==1)sn=w[0].blocksPerLine*w[0].blocksPerColumn;else sn=Z*I.mcusPerColumn;if(!O)O=sn;var In,$n;while(Y<sn){for(d=0;d<Un;d++)w[d].pred=0;if(tn=0,Un==1){zn=w[0];for(Q=0;Q<O;Q++)_(zn,V,Y),Y++}else for(Q=0;Q<O;Q++){for(d=0;d<Un;d++){zn=w[d],In=zn.h,$n=zn.v;for(J=0;J<$n;J++)for(q=0;q<In;q++)W(zn,V,Y,J,q)}if(Y++,Y===sn)break}if(Y===sn)do{if(H[p]===255){if(H[p+1]!==0)break}p+=1}while(p<H.length-2);if(on=0,en=H[p]<<8|H[p+1],en<65280)throw Error("marker was not found");if(en>=65488&&en<=65495)p+=2;else break}return p-x}function a(H,p){var I=[],w=p.blocksPerLine,O=p.blocksPerColumn,k=w<<3,G=new Int32Array(64),S=new Uint8Array(64);function K(x,yn,on){var nn=p.quantizationTable,T,$,L,fn,gn,rn,tn,C,y,N=on,mn;for(mn=0;mn<64;mn++)N[mn]=x[mn]*nn[mn];for(mn=0;mn<8;++mn){var W=8*mn;if(N[1+W]==0&&N[2+W]==0&&N[3+W]==0&&N[4+W]==0&&N[5+W]==0&&N[6+W]==0&&N[7+W]==0){y=c*N[0+W]+512>>10,N[0+W]=y,N[1+W]=y,N[2+W]=y,N[3+W]=y,N[4+W]=y,N[5+W]=y,N[6+W]=y,N[7+W]=y;continue}T=c*N[0+W]+128>>8,$=c*N[4+W]+128>>8,L=N[2+W],fn=N[6+W],gn=h*(N[1+W]-N[7+W])+128>>8,C=h*(N[1+W]+N[7+W])+128>>8,rn=N[3+W]<<4,tn=N[5+W]<<4,y=T-$+1>>1,T=T+$+1>>1,$=y,y=L*u+fn*o+128>>8,L=L*o-fn*u+128>>8,fn=y,y=gn-tn+1>>1,gn=gn+tn+1>>1,tn=y,y=C+rn+1>>1,rn=C-rn+1>>1,C=y,y=T-fn+1>>1,T=T+fn+1>>1,fn=y,y=$-L+1>>1,$=$+L+1>>1,L=y,y=gn*s+C*i+2048>>12,gn=gn*i-C*s+2048>>12,C=y,y=rn*e+tn*t+2048>>12,rn=rn*t-tn*e+2048>>12,tn=y,N[0+W]=T+C,N[7+W]=T-C,N[1+W]=$+tn,N[6+W]=$-tn,N[2+W]=L+rn,N[5+W]=L-rn,N[3+W]=fn+gn,N[4+W]=fn-gn}for(mn=0;mn<8;++mn){var _=mn;if(N[8+_]==0&&N[16+_]==0&&N[24+_]==0&&N[32+_]==0&&N[40+_]==0&&N[48+_]==0&&N[56+_]==0){y=c*on[mn+0]+8192>>14,N[0+_]=y,N[8+_]=y,N[16+_]=y,N[24+_]=y,N[32+_]=y,N[40+_]=y,N[48+_]=y,N[56+_]=y;continue}T=c*N[0+_]+2048>>12,$=c*N[32+_]+2048>>12,L=N[16+_],fn=N[48+_],gn=h*(N[8+_]-N[56+_])+2048>>12,C=h*(N[8+_]+N[56+_])+2048>>12,rn=N[24+_],tn=N[40+_],y=T-$+1>>1,T=T+$+1>>1,$=y,y=L*u+fn*o+2048>>12,L=L*o-fn*u+2048>>12,fn=y,y=gn-tn+1>>1,gn=gn+tn+1>>1,tn=y,y=C+rn+1>>1,rn=C-rn+1>>1,C=y,y=T-fn+1>>1,T=T+fn+1>>1,fn=y,y=$-L+1>>1,$=$+L+1>>1,L=y,y=gn*s+C*i+2048>>12,gn=gn*i-C*s+2048>>12,C=y,y=rn*e+tn*t+2048>>12,rn=rn*t-tn*e+2048>>12,tn=y,N[0+_]=T+C,N[56+_]=T-C,N[8+_]=$+tn,N[48+_]=$-tn,N[16+_]=L+rn,N[40+_]=L-rn,N[24+_]=fn+gn,N[32+_]=fn-gn}for(mn=0;mn<64;++mn){var Un=128+(N[mn]+8>>4);yn[mn]=Un<0?0:Un>255?255:Un}}F(k*O*8);var R,z;for(var P=0;P<O;P++){var Nn=P<<3;for(R=0;R<8;R++)I.push(new Uint8Array(k));for(var Z=0;Z<w;Z++){K(p.blocks[P][Z],S,G);var B=0,Mn=Z<<3;for(z=0;z<8;z++){var an=I[Nn+z];for(R=0;R<8;R++)an[Mn+R]=S[B++]}}}return I}function m(H){return H<0?0:H>255?255:H}f.prototype={load:function(p){var I=new XMLHttpRequest;I.open("GET",p,!0),I.responseType="arraybuffer",I.onload=function(){var w=new Uint8Array(I.response||I.mozResponseArrayBuffer);if(this.parse(w),this.onload)this.onload()}.bind(this),I.send(null)},parse:function(p){var I=this.opts.maxResolutionInMP*1000*1000,w=0,O=p.length;function k(){var U=p[w]<<8|p[w+1];return w+=2,U}function G(){var U=k(),un=p.subarray(w,w+U-2);return w+=un.length,un}function S(U){var un=1,jn=1,kn,Wn;for(Wn in U.components)if(U.components.hasOwnProperty(Wn)){if(kn=U.components[Wn],un<kn.h)un=kn.h;if(jn<kn.v)jn=kn.v}var xn=Math.ceil(U.samplesPerLine/8/un),vr=Math.ceil(U.scanLines/8/jn);for(Wn in U.components)if(U.components.hasOwnProperty(Wn)){kn=U.components[Wn];var Rr=Math.ceil(Math.ceil(U.samplesPerLine/8)*kn.h/un),Jr=Math.ceil(Math.ceil(U.scanLines/8)*kn.v/jn),Dr=xn*kn.h,nt=vr*kn.v,Gt=nt*Dr,rt=[];F(Gt*256);for(var tt=0;tt<nt;tt++){var et=[];for(var it=0;it<Dr;it++)et.push(new Int32Array(64));rt.push(et)}kn.blocksPerLine=Rr,kn.blocksPerColumn=Jr,kn.blocks=rt}U.maxH=un,U.maxV=jn,U.mcusPerLine=xn,U.mcusPerColumn=vr}var K=null,R=null,z=null,P,Nn,Z=[],B=[],Mn=[],an=[],x=k(),yn=-1;if(this.comments=[],x!=65496)throw Error("SOI not found");x=k();while(x!=65497){var on,nn,T;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 $=G();if(x===65534){var L=String.fromCharCode.apply(null,$);this.comments.push(L)}if(x===65504){if($[0]===74&&$[1]===70&&$[2]===73&&$[3]===70&&$[4]===0)K={version:{major:$[5],minor:$[6]},densityUnits:$[7],xDensity:$[8]<<8|$[9],yDensity:$[10]<<8|$[11],thumbWidth:$[12],thumbHeight:$[13],thumbData:$.subarray(14,14+3*$[12]*$[13])}}if(x===65505){if($[0]===69&&$[1]===120&&$[2]===105&&$[3]===102&&$[4]===0)this.exifBuffer=$.subarray(5,$.length)}if(x===65518){if($[0]===65&&$[1]===100&&$[2]===111&&$[3]===98&&$[4]===101&&$[5]===0)R={version:$[6],flags0:$[7]<<8|$[8],flags1:$[9]<<8|$[10],transformCode:$[11]}}break;case 65499:var fn=k(),gn=fn+w-2;while(w<gn){var rn=p[w++];F(256);var tn=new Int32Array(64);if(rn>>4===0)for(nn=0;nn<64;nn++){var C=r[nn];tn[C]=p[w++]}else if(rn>>4===1)for(nn=0;nn<64;nn++){var C=r[nn];tn[C]=k()}else throw Error("DQT: invalid table spec");Z[rn&15]=tn}break;case 65472:case 65473:case 65474:k(),P={},P.extended=x===65473,P.progressive=x===65474,P.precision=p[w++],P.scanLines=k(),P.samplesPerLine=k(),P.components={},P.componentsOrder=[];var y=P.scanLines*P.samplesPerLine;if(y>I){var N=Math.ceil((y-I)/1e6);throw Error(`maxResolutionInMP limit exceeded by ${N}MP`)}var mn=p[w++],W,_=0,Un=0;for(on=0;on<mn;on++){W=p[w];var zn=p[w+1]>>4,d=p[w+1]&15,J=p[w+2];if(zn<=0||d<=0)throw Error("Invalid sampling factor, expected values above 0");P.componentsOrder.push(W),P.components[W]={h:zn,v:d,quantizationIdx:J},w+=3}S(P),B.push(P);break;case 65476:var q=k();for(on=2;on<q;){var Q=p[w++],V=new Uint8Array(16),Y=0;for(nn=0;nn<16;nn++,w++)Y+=V[nn]=p[w];F(16+Y);var en=new Uint8Array(Y);for(nn=0;nn<Y;nn++,w++)en[nn]=p[w];on+=17+Y,(Q>>4===0?an:Mn)[Q&15]=g(V,en)}break;case 65501:k(),Nn=k();break;case 65500:k(),k();break;case 65498:var sn=k(),In=p[w++],$n=[],v;for(on=0;on<In;on++){v=P.components[p[w++]];var j=p[w++];v.huffmanTableDC=an[j>>4],v.huffmanTableAC=Mn[j&15],$n.push(v)}var X=p[w++],En=p[w++],A=p[w++],D=l(p,w,P,$n,Nn,X,En,A>>4,A&15,this.opts);w+=D;break;case 65535:if(p[w]!==255)w--;break;default:if(p[w-3]==255&&p[w-2]>=192&&p[w-2]<=254){w-=3;break}else if(x===224||x==225){if(yn!==-1)throw Error(`first unknown JPEG marker at offset ${yn.toString(16)}, second unknown JPEG marker ${x.toString(16)} at offset ${(w-1).toString(16)}`);yn=w-1;let U=k();if(p[w+U-2]===255){w+=U-2;break}}throw Error("unknown JPEG marker "+x.toString(16))}x=k()}if(B.length!=1)throw Error("only single frame JPEGs supported");for(var on=0;on<B.length;on++){var ln=B[on].components;for(var nn in ln)ln[nn].quantizationTable=Z[ln[nn].quantizationIdx],delete ln[nn].quantizationIdx}this.width=P.samplesPerLine,this.height=P.scanLines,this.jfif=K,this.adobe=R,this.components=[];for(var on=0;on<P.componentsOrder.length;on++){var v=P.components[P.componentsOrder[on]];this.components.push({lines:a(P,v),scaleX:v.h/P.maxH,scaleY:v.v/P.maxV})}},getData:function(p,I){var w=this.width/p,O=this.height/I,k,G,S,K,R,z,P,Nn,Z,B,Mn=0,an,x,yn,on,nn,T,$,L,fn,gn,rn,tn=p*I*this.components.length;F(tn);var C=new Uint8Array(tn);switch(this.components.length){case 1:k=this.components[0];for(B=0;B<I;B++){R=k.lines[0|B*k.scaleY*O];for(Z=0;Z<p;Z++)an=R[0|Z*k.scaleX*w],C[Mn++]=an}break;case 2:k=this.components[0],G=this.components[1];for(B=0;B<I;B++){R=k.lines[0|B*k.scaleY*O],z=G.lines[0|B*G.scaleY*O];for(Z=0;Z<p;Z++)an=R[0|Z*k.scaleX*w],C[Mn++]=an,an=z[0|Z*G.scaleX*w],C[Mn++]=an}break;case 3:if(rn=!0,this.adobe&&this.adobe.transformCode)rn=!0;else if(typeof this.opts.colorTransform<"u")rn=!!this.opts.colorTransform;k=this.components[0],G=this.components[1],S=this.components[2];for(B=0;B<I;B++){R=k.lines[0|B*k.scaleY*O],z=G.lines[0|B*G.scaleY*O],P=S.lines[0|B*S.scaleY*O];for(Z=0;Z<p;Z++){if(!rn)L=R[0|Z*k.scaleX*w],fn=z[0|Z*G.scaleX*w],gn=P[0|Z*S.scaleX*w];else an=R[0|Z*k.scaleX*w],x=z[0|Z*G.scaleX*w],yn=P[0|Z*S.scaleX*w],L=m(an+1.402*(yn-128)),fn=m(an-0.3441363*(x-128)-0.71413636*(yn-128)),gn=m(an+1.772*(x-128));C[Mn++]=L,C[Mn++]=fn,C[Mn++]=gn}}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;k=this.components[0],G=this.components[1],S=this.components[2],K=this.components[3];for(B=0;B<I;B++){R=k.lines[0|B*k.scaleY*O],z=G.lines[0|B*G.scaleY*O],P=S.lines[0|B*S.scaleY*O],Nn=K.lines[0|B*K.scaleY*O];for(Z=0;Z<p;Z++){if(!rn)nn=R[0|Z*k.scaleX*w],T=z[0|Z*G.scaleX*w],$=P[0|Z*S.scaleX*w],on=Nn[0|Z*K.scaleX*w];else an=R[0|Z*k.scaleX*w],x=z[0|Z*G.scaleX*w],yn=P[0|Z*S.scaleX*w],on=Nn[0|Z*K.scaleX*w],nn=255-m(an+1.402*(yn-128)),T=255-m(an-0.3441363*(x-128)-0.71413636*(yn-128)),$=255-m(an+1.772*(x-128));C[Mn++]=255-nn,C[Mn++]=255-T,C[Mn++]=255-$,C[Mn++]=255-on}}break;default:throw Error("Unsupported color mode")}return C},copyToImageData:function(p,I){var{width:w,height:O,data:k}=p,G=this.getData(w,O),S=0,K=0,R,z,P,Nn,Z,B,Mn,an,x;switch(this.components.length){case 1:for(z=0;z<O;z++)for(R=0;R<w;R++)if(P=G[S++],k[K++]=P,k[K++]=P,k[K++]=P,I)k[K++]=255;break;case 3:for(z=0;z<O;z++)for(R=0;R<w;R++)if(Mn=G[S++],an=G[S++],x=G[S++],k[K++]=Mn,k[K++]=an,k[K++]=x,I)k[K++]=255;break;case 4:for(z=0;z<O;z++)for(R=0;R<w;R++)if(Z=G[S++],B=G[S++],P=G[S++],Nn=G[S++],Mn=255-m(Z*(1-Nn/255)+Nn),an=255-m(B*(1-Nn/255)+Nn),x=255-m(P*(1-Nn/255)+Nn),k[K++]=Mn,k[K++]=an,k[K++]=x,I)k[K++]=255;break;default:throw Error("Unsupported color mode")}}};var b=0,E=0;function F(H=0){var p=b+H;if(p>E){var I=Math.ceil((p-E)/1024/1024);throw Error(`maxMemoryUsageInMB limit exceeded by at least ${I}MB`)}b=p}return f.resetMaxMemoryUsage=function(H){b=0,E=H},f.getBytesAllocated=function(){return b},f.requestMemoryAllocation=F,f}();if(typeof ye<"u")ye.exports=vs;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].decode=vs;function vs(n,r={}){var t={colorTransform:void 0,useTArray:!1,formatAsRGBA:!0,tolerantDecoding:!0,maxResolutionInMP:100,maxMemoryUsageInMB:512},e={...t,...r},i=new Uint8Array(n),s=new Ne;s.opts=e,Ne.resetMaxMemoryUsage(e.maxMemoryUsageInMB*1024*1024),s.parse(i);var o=e.formatAsRGBA?4:3,u=s.width*s.height*o;try{Ne.requestMemoryAllocation(u);var c={width:s.width,height:s.height,exifBuffer:s.exifBuffer,data:e.useTArray?new Uint8Array(u):Buffer.alloc(u)};if(s.comments.length>0)c.comments=s.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 s.copyToImageData(c,e.formatAsRGBA),c}});var Ns=bn((_m,Is)=>{var wf=Es(),kf=Fs();Is.exports={encode:wf,decode:kf}});var Se=bn((Bm,Ss)=>{var pf=Gn("util"),ys=Gn("stream"),Tn=Ss.exports=function(){ys.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};pf.inherits(Tn,ys);Tn.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))};Tn.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};Tn.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()};Tn.prototype.destroySoon=Tn.prototype.end;Tn.prototype._end=function(){if(this._reads.length>0)this.emit("error",Error("Unexpected end of input"));this.destroy()};Tn.prototype.destroy=function(){if(!this._buffers)return;this.writable=!1,this._reads=null,this._buffers=null,this.emit("close")};Tn.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)};Tn.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++],s=Math.min(i.length,n.length-r);if(i.copy(e,r,0,s),r+=s,s!==i.length)this._buffers[--t]=i.slice(s)}if(t>0)this._buffers.splice(0,t);this._buffered-=n.length,n.func.call(this,e)};Tn.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 He=bn((Mf)=>{var $r=[{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]}];Mf.getImagePasses=function(n,r){let t=[],e=n%8,i=r%8,s=(n-e)/8,o=(r-i)/8;for(let u=0;u<$r.length;u++){let c=$r[u],h=s*c.x.length,f=o*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};Mf.getInterlaceIterator=function(n){return function(r,t,e){let i=r%$r[e].x.length,s=(r-i)/$r[e].x.length*8+$r[e].x[i],o=t%$r[e].y.length,u=(t-o)/$r[e].y.length*8+$r[e].y[o];return s*4+u*n*4}}});var je=bn((Dm,Hs)=>{Hs.exports=function(r,t,e){let i=r+t-e,s=Math.abs(i-r),o=Math.abs(i-t),u=Math.abs(i-e);if(s<=o&&s<=u)return r;if(o<=u)return t;return e}});var Ge=bn((n0,Gs)=>{var Ff=He(),If=je();function js(n,r,t){let e=n*r;if(t!==8)e=Math.ceil(e/(8/t));return e}var Lr=Gs.exports=function(n,r){let{width:t,height:e,interlace:i,bpp:s,depth:o}=n;if(this.read=r.read,this.write=r.write,this.complete=r.complete,this._imageIndex=0,this._images=[],i){let u=Ff.getImagePasses(t,e);for(let c=0;c<u.length;c++)this._images.push({byteWidth:js(u[c].width,s,o),height:u[c].height,lineIndex:0})}else this._images.push({byteWidth:js(t,s,o),height:e,lineIndex:0});if(o===8)this._xComparison=s;else if(o===16)this._xComparison=s*2;else this._xComparison=1};Lr.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Lr.prototype._unFilterType1=function(n,r,t){let e=this._xComparison,i=e-1;for(let s=0;s<t;s++){let o=n[1+s],u=s>i?r[s-e]:0;r[s]=o+u}};Lr.prototype._unFilterType2=function(n,r,t){let e=this._lastLine;for(let i=0;i<t;i++){let s=n[1+i],o=e?e[i]:0;r[i]=s+o}};Lr.prototype._unFilterType3=function(n,r,t){let e=this._xComparison,i=e-1,s=this._lastLine;for(let o=0;o<t;o++){let u=n[1+o],c=s?s[o]:0,h=o>i?r[o-e]:0,f=Math.floor((h+c)/2);r[o]=u+f}};Lr.prototype._unFilterType4=function(n,r,t){let e=this._xComparison,i=e-1,s=this._lastLine;for(let o=0;o<t;o++){let u=n[1+o],c=s?s[o]:0,h=o>i?r[o-e]:0,f=o>i&&s?s[o-e]:0,g=If(h,c,f);r[o]=u+g}};Lr.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 Js=bn((r0,Rs)=>{var Nf=Gn("util"),Os=Se(),yf=Ge(),Sf=Rs.exports=function(n){Os.call(this);let r=[],t=this;this._filter=new yf(n,{read:this.read.bind(this),write:function(e){r.push(e)},complete:function(){t.emit("complete",Buffer.concat(r))}}),this._filter.start()};Nf.inherits(Sf,Os)});var Qr=bn((t0,Ks)=>{Ks.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 Je=bn((e0,Ls)=>{var Oe=[];(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;Oe[n]=r}})();var Re=Ls.exports=function(){this._crc=-1};Re.prototype.write=function(n){for(let r=0;r<n.length;r++)this._crc=Oe[(this._crc^n[r])&255]^this._crc>>>8;return!0};Re.prototype.crc32=function(){return this._crc^-1};Re.crc32=function(n){let r=-1;for(let t=0;t<n.length;t++)r=Oe[(r^n[t])&255]^r>>>8;return r^-1}});var Ke=bn((i0,Qs)=>{var Sn=Qr(),Hf=Je(),Hn=Qs.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(){}};Hn.prototype.start=function(){this.read(Sn.PNG_SIGNATURE.length,this._parseSignature.bind(this))};Hn.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))};Hn.prototype._parseChunkBegin=function(n){let r=n.readUInt32BE(0),t=n.readUInt32BE(4),e="";for(let s=4;s<8;s++)e+=String.fromCharCode(n[s]);let i=Boolean(n[4]&32);if(!this._hasIHDR&&t!==Sn.TYPE_IHDR){this.error(Error("Expected IHDR on beggining"));return}if(this._crc=new Hf,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))};Hn.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};Hn.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};Hn.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))};Hn.prototype._handleIHDR=function(n){this.read(n,this._parseIHDR.bind(this))};Hn.prototype._parseIHDR=function(n){this._crc.write(n);let r=n.readUInt32BE(0),t=n.readUInt32BE(4),e=n[8],i=n[9],s=n[10],o=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 Sn.COLORTYPE_TO_BPP_MAP)){this.error(Error("Unsupported color type"));return}if(s!==0){this.error(Error("Unsupported compression method"));return}if(o!==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=Sn.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:r,height:t,depth:e,interlace:Boolean(u),palette:Boolean(i&Sn.COLORTYPE_PALETTE),color:Boolean(i&Sn.COLORTYPE_COLOR),alpha:Boolean(i&Sn.COLORTYPE_ALPHA),bpp:c,colorType:i}),this._handleChunkEnd()};Hn.prototype._handlePLTE=function(n){this.read(n,this._parsePLTE.bind(this))};Hn.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()};Hn.prototype._handleTRNS=function(n){this.simpleTransparency(),this.read(n,this._parseTRNS.bind(this))};Hn.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()};Hn.prototype._handleGAMA=function(n){this.read(n,this._parseGAMA.bind(this))};Hn.prototype._parseGAMA=function(n){this._crc.write(n),this.gamma(n.readUInt32BE(0)/Sn.GAMMA_DIVISION),this._handleChunkEnd()};Hn.prototype._handleIDAT=function(n){if(!this._emittedHeadersFinished)this._emittedHeadersFinished=!0,this.headersFinished();this.read(-n,this._parseIDAT.bind(this,n))};Hn.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()};Hn.prototype._handleIEND=function(n){this.read(n,this._parseIEND.bind(this))};Hn.prototype._parseIEND=function(n){if(this._crc.write(n),this._hasIEND=!0,this._handleChunkEnd(),this.finished)this.finished()}});var Le=bn((Kf)=>{var Ps=He(),jf=[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]}],Gf=[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 Of(n,r){let t=[],e=0;function i(){if(e===n.length)throw Error("Ran out of data");let s=n[e];e++;let o,u,c,h,f,g,l,a;switch(r){default:throw Error("unrecognised depth");case 16:l=n[e],e++,t.push((s<<8)+l);break;case 4:l=s&15,a=s>>4,t.push(a,l);break;case 2:f=s&3,g=s>>2&3,l=s>>4&3,a=s>>6&3,t.push(a,l,g,f);break;case 1:o=s&1,u=s>>1&1,c=s>>2&1,h=s>>3&1,f=s>>4&1,g=s>>5&1,l=s>>6&1,a=s>>7&1,t.push(a,l,g,f,h,c,u,o);break}}return{get:function(s){while(t.length<s)i();let o=t.slice(0,s);return t=t.slice(s),o},resetAfterLine:function(){t.length=0},end:function(){if(e!==n.length)throw Error("extra data found")}}}function Rf(n,r,t,e,i,s){let{width:o,height:u,index:c}=n;for(let h=0;h<u;h++)for(let f=0;f<o;f++){let g=t(f,h,c);jf[e](r,i,g,s),s+=e}return s}function Jf(n,r,t,e,i,s){let{width:o,height:u,index:c}=n;for(let h=0;h<u;h++){for(let f=0;f<o;f++){let g=i.get(e),l=t(f,h,c);Gf[e](r,g,l,s)}i.resetAfterLine()}}Kf.dataToBitMap=function(n,r){let{width:t,height:e,depth:i,bpp:s,interlace:o}=r,u;if(i!==8)u=Of(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(o)g=Ps.getImagePasses(t,e),l=Ps.getInterlaceIterator(t,e);else{let a=0;l=function(){let m=a;return a+=4,m},g=[{width:t,height:e}]}for(let a=0;a<g.length;a++)if(i===8)f=Rf(g[a],c,l,s,n,f);else Jf(g[a],c,l,s,u,h);if(i===8){if(f!==n.length)throw Error("extra data found")}else u.end();return c}});var Qe=bn((o0,Zs)=>{function Qf(n,r,t,e,i){let s=0;for(let o=0;o<e;o++)for(let u=0;u<t;u++){let c=i[n[s]];if(!c)throw Error("index "+n[s]+" not in palette");for(let h=0;h<4;h++)r[s+h]=c[h];s+=4}}function Pf(n,r,t,e,i){let s=0;for(let o=0;o<e;o++)for(let u=0;u<t;u++){let c=!1;if(i.length===1){if(i[0]===n[s])c=!0}else if(i[0]===n[s]&&i[1]===n[s+1]&&i[2]===n[s+2])c=!0;if(c)for(let h=0;h<4;h++)r[s+h]=0;s+=4}}function Zf(n,r,t,e,i){let s=255,o=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]*s/o+0.5);u+=4}}Zs.exports=function(n,r,t=!1){let{depth:e,width:i,height:s,colorType:o,transColor:u,palette:c}=r,h=n;if(o===3)Qf(n,h,i,s,c);else{if(u)Pf(n,h,i,s,u);if(e!==8&&!t){if(e===16)h=Buffer.alloc(i*s*4);Zf(n,h,i,s,e)}}return h}});var Ws=bn((u0,Us)=>{var qf=Gn("util"),Pe=Gn("zlib"),qs=Se(),Uf=Js(),Wf=Ke(),Xf=Le(),Vf=Qe(),nr=Us.exports=function(n){qs.call(this),this._parser=new Wf(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()};qf.inherits(nr,qs);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=Pe.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,Pe.Z_MIN_CHUNK);this._inflate=Pe.createInflate({chunkSize:e});let i=t,s=this.emit.bind(this,"error");this._inflate.on("error",function(u){if(!i)return;s(u)}),this._filter.on("complete",this._complete.bind(this));let o=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,o(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 Uf(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=Xf.dataToBitMap(n,this._bitmapInfo);r=Vf(t,this._bitmapInfo,this._options.skipRescale),t=null}catch(t){this._handleError(t);return}this.emit("parsed",r)}});var Vs=bn((c0,Xs)=>{var Xn=Qr();Xs.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 m=function(){let b=new ArrayBuffer(2);return new DataView(b).setInt16(0,256,!0),new Int16Array(b)[0]!==256}();if(e.bitDepth===8||e.bitDepth===16&&m)return n}let s=e.bitDepth!==16?n:new Uint16Array(n.buffer),o=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)o=65535,c*=2;let h=Buffer.alloc(r*t*c),f=0,g=0,l=e.bgColor||{};if(l.red===void 0)l.red=o;if(l.green===void 0)l.green=o;if(l.blue===void 0)l.blue=o;function a(){let m,b,E,F=o;switch(e.inputColorType){case Xn.COLORTYPE_COLOR_ALPHA:F=s[f+3],m=s[f],b=s[f+1],E=s[f+2];break;case Xn.COLORTYPE_COLOR:m=s[f],b=s[f+1],E=s[f+2];break;case Xn.COLORTYPE_ALPHA:F=s[f+1],m=s[f],b=m,E=m;break;case Xn.COLORTYPE_GRAYSCALE:m=s[f],b=m,E=m;break;default:throw Error("input color type:"+e.inputColorType+" is not supported at present")}if(e.inputHasAlpha){if(!i)F/=o,m=Math.min(Math.max(Math.round((1-F)*l.red+F*m),0),o),b=Math.min(Math.max(Math.round((1-F)*l.green+F*b),0),o),E=Math.min(Math.max(Math.round((1-F)*l.blue+F*E),0),o)}return{red:m,green:b,blue:E,alpha:F}}for(let m=0;m<t;m++)for(let b=0;b<r;b++){let E=a(s,f);switch(e.colorType){case Xn.COLORTYPE_COLOR_ALPHA:case Xn.COLORTYPE_COLOR:if(e.bitDepth===8){if(h[g]=E.red,h[g+1]=E.green,h[g+2]=E.blue,i)h[g+3]=E.alpha}else if(h.writeUInt16BE(E.red,g),h.writeUInt16BE(E.green,g+2),h.writeUInt16BE(E.blue,g+4),i)h.writeUInt16BE(E.alpha,g+6);break;case Xn.COLORTYPE_ALPHA:case Xn.COLORTYPE_GRAYSCALE:{let F=(E.red+E.green+E.blue)/3;if(e.bitDepth===8){if(h[g]=F,i)h[g+1]=E.alpha}else if(h.writeUInt16BE(F,g),i)h.writeUInt16BE(E.alpha,g+2);break}default:throw Error("unrecognised color Type "+e.colorType)}f+=u,g+=c}return h}});var zs=bn((h0,As)=>{var Ys=je();function Yf(n,r,t,e,i){for(let s=0;s<t;s++)e[i+s]=n[r+s]}function Af(n,r,t){let e=0,i=r+t;for(let s=r;s<i;s++)e+=Math.abs(n[s]);return e}function zf(n,r,t,e,i,s){for(let o=0;o<t;o++){let u=o>=s?n[r+o-s]:0,c=n[r+o]-u;e[i+o]=c}}function Tf(n,r,t,e){let i=0;for(let s=0;s<t;s++){let o=s>=e?n[r+s-e]:0,u=n[r+s]-o;i+=Math.abs(u)}return i}function Cf(n,r,t,e,i){for(let s=0;s<t;s++){let o=r>0?n[r+s-t]:0,u=n[r+s]-o;e[i+s]=u}}function _f(n,r,t){let e=0,i=r+t;for(let s=r;s<i;s++){let o=r>0?n[s-t]:0,u=n[s]-o;e+=Math.abs(u)}return e}function Bf(n,r,t,e,i,s){for(let o=0;o<t;o++){let u=o>=s?n[r+o-s]:0,c=r>0?n[r+o-t]:0,h=n[r+o]-(u+c>>1);e[i+o]=h}}function xf(n,r,t,e){let i=0;for(let s=0;s<t;s++){let o=s>=e?n[r+s-e]:0,u=r>0?n[r+s-t]:0,c=n[r+s]-(o+u>>1);i+=Math.abs(c)}return i}function Df(n,r,t,e,i,s){for(let o=0;o<t;o++){let u=o>=s?n[r+o-s]:0,c=r>0?n[r+o-t]:0,h=r>0&&o>=s?n[r+o-(t+s)]:0,f=n[r+o]-Ys(u,c,h);e[i+o]=f}}function ng(n,r,t,e){let i=0;for(let s=0;s<t;s++){let o=s>=e?n[r+s-e]:0,u=r>0?n[r+s-t]:0,c=r>0&&s>=e?n[r+s-(t+e)]:0,h=n[r+s]-Ys(o,u,c);i+=Math.abs(h)}return i}var rg={0:Yf,1:zf,2:Cf,3:Bf,4:Df},tg={0:Af,1:Tf,2:_f,3:xf,4:ng};As.exports=function(n,r,t,e,i){let s;if(!("filterType"in e)||e.filterType===-1)s=[0,1,2,3,4];else if(typeof e.filterType==="number")s=[e.filterType];else throw Error("unrecognised filter types");if(e.bitDepth===16)i*=2;let o=r*i,u=0,c=0,h=Buffer.alloc((o+1)*t),f=s[0];for(let g=0;g<t;g++){if(s.length>1){let l=1/0;for(let a=0;a<s.length;a++){let m=tg[s[a]](n,c,o,i);if(m<l)f=s[a],l=m}}h[u]=f,u++,rg[f](n,c,o,h,u,i),u+=o,c+=o}return h}});var Ze=bn((f0,Ts)=>{var Rn=Qr(),eg=Je(),ig=Vs(),sg=zs(),og=Gn("zlib"),br=Ts.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||og.createDeflate,n.bitDepth=n.bitDepth||8,n.colorType=typeof n.colorType==="number"?n.colorType:Rn.COLORTYPE_COLOR_ALPHA,n.inputColorType=typeof n.inputColorType==="number"?n.inputColorType:Rn.COLORTYPE_COLOR_ALPHA,[Rn.COLORTYPE_GRAYSCALE,Rn.COLORTYPE_COLOR,Rn.COLORTYPE_COLOR_ALPHA,Rn.COLORTYPE_ALPHA].indexOf(n.colorType)===-1)throw Error("option color type:"+n.colorType+" is not supported at present");if([Rn.COLORTYPE_GRAYSCALE,Rn.COLORTYPE_COLOR,Rn.COLORTYPE_COLOR_ALPHA,Rn.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")};br.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};br.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};br.prototype.filterData=function(n,r,t){let e=ig(n,r,t,this._options),i=Rn.COLORTYPE_TO_BPP_MAP[this._options.colorType];return sg(e,r,t,this._options,i)};br.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(eg.crc32(e.slice(4,e.length-4)),e.length-4),e};br.prototype.packGAMA=function(n){let r=Buffer.alloc(4);return r.writeUInt32BE(Math.floor(n*Rn.GAMMA_DIVISION),0),this._packChunk(Rn.TYPE_gAMA,r)};br.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(Rn.TYPE_IHDR,t)};br.prototype.packIDAT=function(n){return this._packChunk(Rn.TYPE_IDAT,n)};br.prototype.packIEND=function(){return this._packChunk(Rn.TYPE_IEND,null)}});var xs=bn((g0,Bs)=>{var ug=Gn("util"),Cs=Gn("stream"),cg=Qr(),hg=Ze(),_s=Bs.exports=function(n){Cs.call(this);let r=n||{};this._packer=new hg(r),this._deflate=this._packer.createDeflate(),this.readable=!0};ug.inherits(_s,Cs);_s.prototype.pack=function(n,r,t,e){if(this.emit("data",Buffer.from(cg.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(s){this.emit("data",this._packer.packIDAT(s))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(i)}});var io=bn((gt,eo)=>{var Ds=Gn("assert").ok,Pr=Gn("zlib"),fg=Gn("util"),no=Gn("buffer").kMaxLength;function Fr(n){if(!(this instanceof Fr))return new Fr(n);if(n&&n.chunkSize<Pr.Z_MIN_CHUNK)n.chunkSize=Pr.Z_MIN_CHUNK;if(Pr.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 gg(n){return new Fr(n)}function ro(n,r){if(r)process.nextTick(r);if(!n._handle)return;n._handle.close(),n._handle=null}Fr.prototype._processChunk=function(n,r,t){if(typeof t==="function")return Pr.Inflate._processChunk.call(this,n,r,t);let e=this,i=n&&n.length,s=this._chunkSize-this._offset,o=this._maxLength,u=0,c=[],h=0,f;this.on("error",function(m){f=m});function g(m,b){if(e._hadError)return;let E=s-b;if(Ds(E>=0,"have should not go down"),E>0){let F=e._buffer.slice(e._offset,e._offset+E);if(e._offset+=E,F.length>o)F=F.slice(0,o);if(c.push(F),h+=F.length,o-=F.length,o===0)return!1}if(b===0||e._offset>=e._chunkSize)s=e._chunkSize,e._offset=0,e._buffer=Buffer.allocUnsafe(e._chunkSize);if(b===0)return u+=i-m,i=m,!0;return!1}Ds(this._handle,"zlib binding closed");let l;do l=this._handle.writeSync(r,n,u,i,this._buffer,this._offset,s),l=l||this._writeState;while(!this._hadError&&g(l[0],l[1]));if(this._hadError)throw f;if(h>=no)throw ro(this),RangeError("Cannot create final Buffer. It would be larger than 0x"+no.toString(16)+" bytes");let a=Buffer.concat(c,h);return ro(this),a};fg.inherits(Fr,Pr.Inflate);function lg(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=Pr.Z_FINISH;return n._processChunk(r,t)}function to(n,r){return lg(new Fr(r),n)}eo.exports=gt=to;gt.Inflate=Fr;gt.createInflate=gg;gt.inflateSync=to});var qe=bn((l0,oo)=>{var so=oo.exports=function(n){this._buffer=n,this._reads=[]};so.prototype.read=function(n,r){this._reads.push({length:Math.abs(n),allowLess:n<0,func:r})};so.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 uo=bn((mg)=>{var dg=qe(),ag=Ge();mg.process=function(n,r){let t=[],e=new dg(n);return new ag(r,{read:e.read.bind(e),write:function(s){t.push(s)},complete:function(){}}).start(),e.process(),Buffer.concat(t)}});var go=bn((a0,fo)=>{var co=!0,ho=Gn("zlib"),bg=io();if(!ho.deflateSync)co=!1;var wg=qe(),kg=uo(),pg=Ke(),Mg=Le(),Eg=Qe();fo.exports=function(n,r){if(!co)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(I){t=I}let i;function s(I){i=I}function o(I){i.transColor=I}function u(I){i.palette=I}function c(){i.alpha=!0}let h;function f(I){h=I}let g=[];function l(I){g.push(I)}let a=new wg(n);if(new pg(r,{read:a.read.bind(a),error:e,metadata:s,gamma:f,palette:u,transColor:o,inflateData:l,simpleTransparency:c}).start(),a.process(),t)throw t;let b=Buffer.concat(g);g.length=0;let E;if(i.interlace)E=ho.inflateSync(b);else{let w=((i.width*i.bpp*i.depth+7>>3)+1)*i.height;E=bg(b,{chunkSize:w,maxLength:w})}if(b=null,!E||!E.length)throw Error("bad png - invalid inflate data response");let F=kg.process(E,i);b=null;let H=Mg.dataToBitMap(F,i);F=null;let p=Eg(H,i,r.skipRescale);return i.data=p,i.gamma=h||0,i}});var $o=bn((m0,mo)=>{var lo=!0,ao=Gn("zlib");if(!ao.deflateSync)lo=!1;var vg=Qr(),Fg=Ze();mo.exports=function(n,r){if(!lo)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let e=new Fg(r||{}),i=[];if(i.push(Buffer.from(vg.PNG_SIGNATURE)),i.push(e.packIHDR(n.width,n.height)),n.gamma)i.push(e.packGAMA(n.gamma));let s=e.filterData(n.data,n.width,n.height),o=ao.deflateSync(s,e.getDeflateOptions());if(s=null,!o||!o.length)throw Error("bad png - invalid compressed data response");return i.push(e.packIDAT(o)),i.push(e.packIEND()),Buffer.concat(i)}});var bo=bn((yg)=>{var Ig=go(),Ng=$o();yg.read=function(n,r){return Ig(n,r||{})};yg.write=function(n,r){return Ng(n,r)}});var ko=bn((Jg)=>{var jg=Gn("util"),wo=Gn("stream"),Gg=Ws(),Og=xs(),Rg=bo(),Jn=Jg.PNG=function(n){if(wo.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 Gg(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 Og(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"))};jg.inherits(Jn,wo);Jn.sync=Rg;Jn.prototype.pack=function(){if(!this.data||!this.data.length)return this.emit("error","No data provided"),this;return process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this};Jn.prototype.parse=function(n,r){if(r){let 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};Jn.prototype.write=function(n){return this._parser.write(n),!0};Jn.prototype.end=function(n){this._parser.end(n)};Jn.prototype._metadata=function(n){this.width=n.width,this.height=n.height,this.emit("metadata",n)};Jn.prototype._gamma=function(n){this.gamma=n};Jn.prototype._handleClose=function(){if(!this._parser.writable&&!this._packer.readable)this.emit("close")};Jn.bitblt=function(n,r,t,e,i,s,o,u){if(t|=0,e|=0,i|=0,s|=0,o|=0,u|=0,t>n.width||e>n.height||t+i>n.width||e+s>n.height)throw Error("bitblt reading outside image");if(o>r.width||u>r.height||o+i>r.width||u+s>r.height)throw Error("bitblt writing outside image");for(let c=0;c<s;c++)n.data.copy(r.data,(u+c)*r.width+o<<2,(e+c)*n.width+t<<2,(e+c)*n.width+t+i<<2)};Jn.prototype.bitblt=function(n,r,t,e,i,s,o){return Jn.bitblt(this,n,r,t,e,i,s,o),this};Jn.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 s=n.data[e+i]/255;s=Math.pow(s,0.45454545454545453/n.gamma),n.data[e+i]=Math.round(s*255)}}n.gamma=0}};Jn.prototype.adjustGamma=function(){Jn.adjustGamma(this)}});var Hi=bn((p1,rh)=>{var Si={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"},ya={up:(n=1)=>"\x1B[S".repeat(n),down:(n=1)=>"\x1B[T".repeat(n)},Sa={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?Si.up():"");if(n)r+=Si.left;return r}};rh.exports={cursor:Si,scroll:ya,erase:Sa,beep:"\x07"}});import{isMainThread as Gm}from"node:worker_threads";import{parseArgs as Sm}from"node:util";var Dn={name:"@kecan0406/ttheme",version:"1.0.30",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 Ru}from"node:fs";import{basename as zl,join as Mt}from"node:path";var lf=/^#[0-9a-f]{6}$/;function hs(n){return lf.test(n)}function On(n){let r=Number.parseInt(n.slice(1),16);return[r>>16&255,r>>8&255,r&255]}function ir(n){let[r,t,e]=On(n).map((i)=>{let s=i/255;return s<=0.03928?s/12.92:((s+0.055)/1.055)**2.4});return 0.2126*r+0.7152*t+0.0722*e}function sr(n,r){let t=ir(n),e=ir(r);return(Math.max(t,e)+0.05)/(Math.min(t,e)+0.05)}function Lt(n,r){return Math.round(sr(n,r)*100)/100}var ar=7,fs=3,ve=0.15,gs=1.6,ls=[1,2,3,4,5,6,9,10,11,12,13,14],ds=[7,15];function ot(n,r){let t=n.ansi[r];if(t===void 0)throw Error(`${n.name}: missing ANSI ${r}`);return t}function Fe(n,r,t){let e=n.background;return r.flatMap((i)=>{let s=ot(n,i);return sr(s,e)<t?[`ANSI ${i} ${s} on ${e} is ${Lt(s,e)}:1, needs ${t}:1`]:[]})}function as(n,r){return Math.min(...r.map((t)=>sr(ot(n,t),n.background)))}var Qt=[{rule:"foreground",label:"foreground on background",unit:"ratio",min:ar,measure:({foreground:n,background:r})=>sr(n,r),check:({foreground:n,background:r})=>sr(n,r)<ar?[`foreground ${n} on ${r} is ${Lt(n,r)}:1, needs ${ar}:1`]:[]},{rule:"accents",label:"weakest accent on background",unit:"ratio",min:fs,measure:(n)=>as(n,ls),check:(n)=>Fe(n,ls,fs)},{rule:"ansi0-dark",label:"ansi0 luminance",unit:"luminance",max:ve,measure:(n)=>ir(ot(n,0)),check:(n)=>{let r=ot(n,0);return ir(r)>ve?[`ANSI 0 ${r} has luminance ${ir(r).toFixed(3)}, needs <= ${ve}`]:[]}},{rule:"light-ansi",label:"ansi7 and ansi15 on background",unit:"ratio",min:ar,measure:(n)=>as(n,ds),check:(n)=>Fe(n,ds,ar)},{rule:"ansi8-visible",label:"ansi8 on background",unit:"ratio",min:gs,measure:(n)=>sr(ot(n,8),n.background),check:(n)=>Fe(n,[8],gs)},{rule:"selection",label:"foreground on selection",unit:"ratio",min:ar,measure:({foreground:n,selectionBackground:r})=>r===void 0?Number.NaN:sr(n,r),check:({foreground:n,selectionBackground:r})=>r!==void 0&&sr(n,r)<ar?[`foreground ${n} on selection ${r} is ${Lt(n,r)}:1, needs ${ar}:1`]:[]}],Qm=Qt.map((n)=>n.rule),Pt=Qt.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 ms(n){return Qt.map((r)=>Math.round(r.measure(n)*1000)/1000)}function Ie(n){return Qt.filter((r)=>!n.waive.includes(r.rule)).flatMap((r)=>r.check(n).map((t)=>({theme:n.name,rule:r.rule,detail:t})))}function $s(n){return n.flatMap(Ie)}var df=["black","red","green","yellow","blue","magenta","cyan","white"];function bs(n,r){return[n,...df.map((t,e)=>`${t} = '${r[e]}'`),""].join(`
3
- `)}var ut={id:"alacritty",limits:"no shaders, no runtime color API (OSC only)",emit(n){let r=[...Kr(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}'`,"",bs("[colors.normal]",n.ansi.slice(0,8)),bs("[colors.bright]",n.ansi.slice(8,16))].join(`
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 af}from"node:util";var ct={id:"ghostty",emit(n){let r=[...Kr(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(!af(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 mr(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 ws(n){return{...Object.fromEntries(n.ansi.map((r,t)=>[`Ansi ${t} Color`,mr(r)])),"Background Color":mr(n.background),"Bold Color":mr(n.foreground),"Cursor Color":mr(n.cursor),"Cursor Text Color":mr(n.background),"Foreground Color":mr(n.foreground),"Selected Text Color":mr(n.foreground),"Selection Color":mr(n.selectionBackground)}}function mf(n){return n?{"Background Image Location":n.image,"Background Image Mode":n.cover?2:3,Blend:n.opacity}:{"Background Image Location":""}}function ks(n,r,t,e){let i=(o,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,...mf(r.get(o.name)),...ws(o)}),s=[...t?[i(t,"default")]:[],...n.map((o)=>i(o,o.name))];return`${JSON.stringify({Profiles:s},null,2)}
8
- `}function $f(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 ht={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(ws(n)).map(([t,e])=>$f(t,e)),"</dict>","</plist>",""].join(`
10
- `);return[{path:`iterm2/${n.name}.itermcolors`,content:r}]}};var ft={id:"kitty",limits:"no GLSL shaders, no per-codepoint font mapping",emit(n){let r=[...Kr(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
- `),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}]}};import{createHash as Qg}from"node:crypto";import{mkdirSync as Go,readdirSync as Ir,readFileSync as Oo,renameSync as Ro,rmSync as qr,statSync as Pg,utimesSync as Zg,writeFileSync as Wt}from"node:fs";import{isAbsolute as qg,join as vn}from"node:path";var Eo=Kt(Ns(),1),qt=Kt(ko(),1),po=[137,80,78,71,13,10,26,10],vo=13;function Fo(n){return n.length>=po.length&&po.every((r,t)=>n[t]===r)}function Kg(n){let r=qt.PNG.sync.read(Buffer.from(n));return{width:r.width,height:r.height,data:new Uint8Array(r.data)}}function Io(n,r){if(Fo(n)){let t=Ue(n);if(t&&t.width*t.height>r)throw Error(`${t.width}×${t.height} is over ${r/1e6} megapixels`);return Kg(n)}if(n[0]===255&&n[1]===216){let t=Eo.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 Zr(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 Mo(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 Ue(n){if(n.length<33||!Fo(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=Mo(n,"IDAT");return{width:t,height:e,alpha:Mo(i===-1?n:n.subarray(0,i),"tRNS")!==-1}}function No(n,r=vo){let{width:t,height:e}=n,i=-1,s=-1;for(let o=0;o<n.height;o++)for(let u=0;u<n.width;u++)if((n.data[(o*n.width+u)*4+3]??0)>=r)t=Math.min(t,u),i=Math.max(i,u),e=Math.min(e,o),s=Math.max(s,o);return i<0?null:{x:t,y:e,w:i-t+1,h:s-e+1}}function lt(n,r={x:0,y:0,w:n.width,h:n.height}){let t=0;for(let e=r.y;e<r.y+r.h;e++)for(let i=r.x;i<r.x+r.w;i++)if((n.data[(e*n.width+i)*4+3]??0)<vo)t++;return Math.round(t*100/(r.w*r.h))}function Lg(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),s=n.data;for(let o=0;o<e;o++)for(let u=0;u<t;u++){let c=0,h=0,f=0,g=0;for(let a=0;a<r;a++)for(let m=0;m<r;m++){let b=((o*r+a)*n.width+u*r+m)*4,E=s[b+3]??0;c+=(s[b]??0)*E,h+=(s[b+1]??0)*E,f+=(s[b+2]??0)*E,g+=E}let l=(o*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 yo(n,r,t){let e=Math.min(r/n.width,t/n.height),i=Math.max(1,Math.round(n.width*e)),s=Math.max(1,Math.round(n.height*e)),o=Ut(n,{x:0,y:0,w:n.width,h:n.height},i,s),u=new Uint8Array(r*t*4),c=Math.floor((r-i)/2),h=Math.floor((t-s)/2);for(let f=0;f<s;f++)u.set(o.data.subarray(f*i*4,(f+1)*i*4),((h+f)*r+c)*4);return{width:r,height:t,data:u}}function Ut(n,r,t,e){let i=Math.max(1,Math.floor(Math.min(r.w/t,r.h/e))),s=Lg(n,i),o=s.data,u=new Uint8Array(t*e*4);for(let c=0;c<e;c++){let h=Math.min(s.height-1,Math.max(0,r.y/i+(c+0.5)*r.h/i/e-0.5)),f=Math.floor(h),g=Math.min(s.height-1,f+1),l=h-f;for(let a=0;a<t;a++){let m=Math.min(s.width-1,Math.max(0,r.x/i+(a+0.5)*r.w/i/t-0.5)),b=Math.floor(m),E=Math.min(s.width-1,b+1),F=m-b,H=(f*s.width+b)*4,p=(f*s.width+E)*4,I=(g*s.width+b)*4,w=(g*s.width+E)*4,O=(o[H+3]??0)*(1-F)*(1-l),k=(o[p+3]??0)*F*(1-l),G=(o[I+3]??0)*(1-F)*l,S=(o[w+3]??0)*F*l,K=O+k+G+S,R=(c*t+a)*4;if(K>0)for(let z=0;z<3;z++){let P=(o[H+z]??0)*O+(o[p+z]??0)*k+(o[I+z]??0)*G+(o[w+z]??0)*S;u[R+z]=Math.round(P/K)}u[R+3]=Math.round(K)}}return{width:t,height:e,data:u}}var So={width:2560,height:1550},Ug=2560,Wg=0.1,or={tall:1.15,reach:0.4,widest:0.95,headroom:0.04,margin:0.03,stands:12},Xg=ir(We("#19161e","#9b86c8",0.2)),Vg="shelf";function We(n,r,t){let e=On(n),i=On(r);return`#${e.map((s,o)=>Math.round(s+((i[o]??0)-s)*t).toString(16).padStart(2,"0")).join("")}`}function Yg(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 Ho(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 jo(n,r){let t=Yg(n,r),i=Ho((h)=>Ie({name:n.name,background:We(n.background,t,h),foreground:n.foreground,ansi:n.ansi,waive:n.waived??[]}).length===0),s=Ho((h)=>ir(We(n.background,t,h))<=Xg),o=Math.floor(Math.min(i,s)*1000)/1000,u=On(n.background),c=Math.hypot(...On(t).map((h,f)=>(h-(u[f]??0))*o));return{slot:r,color:t,cap:i,matched:s,opacity:o,reach:c}}function Xt(n,r){let t=jo(n,"cursor");if(t.opacity>=Wg)return t;return r.filter((e)=>e!=="cursor"&&e!=="background").map((e)=>jo(n,e)).reduce((e,i)=>i.reach>e.reach?i:e,t)}function Xe(n,r,t){let e=On(r),i=On(t),s=n.data;for(let o=0;o<s.length;o+=4){let u=(0.299*(s[o]??0)+0.587*(s[o+1]??0)+0.114*(s[o+2]??0))/255;for(let c=0;c<3;c++)s[o+c]=Math.round((e[c]??0)+((i[c]??0)-(e[c]??0))*u)}return n}function Ag(n,r,t){let e=On(r),i=n.data,s=new Uint8Array(i.length);for(let o=0;o<i.length;o+=4){let u=(i[o+3]??0)/255*t;for(let c=0;c<3;c++)s[o+c]=Math.round((e[c]??0)*(1-u)+(i[o+c]??0)*u);s[o+3]=255}return{width:n.width,height:n.height,data:s}}function Jo(n){return No(n)??{x:0,y:0,w:n.width,h:n.height}}function zg(n,r){if(n<=0||r<=0)return So;let t=Math.min(1,So.width/Math.max(n,r));return{width:Math.round(n*t),height:Math.round(r*t)}}function Tg(n,r){let t=Math.min(1,Ug/Math.max(r.w,r.h));return Ut(n,r,Math.round(r.w*t),Math.round(r.h*t))}function Ko(n,r,t,e){if(e<or.stands){let c=n.w*t>n.h*r?{x:n.x+(n.w-n.h*r/t)/2,y:n.y,w:n.h*r/t,h:n.h}:{x:n.x,y:n.y,w:n.w,h:n.w*t/r};return{crop:c,at:{x:0,y:0,w:r,h:t},focus:(c.y-n.y+c.h/2)/n.h}}let i=Math.max(or.tall*t,or.reach*r*n.h/n.w),s=i*n.w/n.h;if(s>or.widest*r)s=or.widest*r,i=s*n.h/n.w;let o=or.headroom*t,u=Math.min(1,(t-o)/i);return{crop:{x:n.x,y:n.y,w:n.w,h:n.h*u},at:{x:r*(1-or.margin)-s,y:o,w:s,h:i*u},focus:Math.min(1,(t/2-o)/i)}}function Lo(n,r,t,e){let i=Math.max(1,Math.round(r.at.w)),s=Math.max(1,Math.round(r.at.h)),o=Ut(n,r.crop,i,s),u=new Uint8Array(t*e*4),c=Math.round(r.at.x),h=Math.round(r.at.y);for(let f=0;f<s;f++){let g=h+f,l=Math.max(0,-c),a=Math.min(i,t-c);if(g<0||g>=e||a<=l)continue;u.set(o.data.subarray((f*i+l)*4,(f*i+a)*4),(g*t+c+l)*4)}return{width:t,height:e,data:u}}function Qo(n,r,t,e,i){let s=Jo(n),o=Lo(n,Ko(s,e,i,lt(n,s)),e,i);return Ag(Xe(o,r.background,t.color),r.background,t.opacity)}function Ur(n){return vn(n,"ttheme","backgrounds")}function Cg(n,r,t,e,i){return[...e?[`# from ${e}`]:[],...i?[`# image ${i}`]:[],`background-image = ${r}`,"background-image-fit = cover","background-image-position = top-right",`background-image-opacity = ${t}`,`config-file = ?${n}.tune.conf`,`config-file = ?${n}.off.conf`,""].join(`
13
- `)}function Po(n,r,t){let e=new Map;for(let o of[`${r}.conf`,`${r}.tune.conf`,`${r}.off.conf`]){let u;try{u=Oo(vn(n,o),"utf8")}catch{if(o===`${r}.conf`)return;continue}for(let c of u.split(`
14
- `)){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 s=Number(e.get("background-image-opacity")??1);return{image:i.startsWith("~/")?vn(t,i.slice(2)):qg(i)?i:vn(n,i),opacity:Number.isFinite(s)?s:1,cover:e.get("background-image-fit")==="cover"}}function _g(n,r){for(let t of Ir(n))if(Ve(t,r))qr(vn(n,t))}function Bg(n){return`${n.site}_${n.id}`}function Vt(n,r){return vn(n,Vg,r)}function Ve(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 dt(n,r){try{return/^# image (\S+)$/m.exec(Oo(vn(n,`${r}.conf`),"utf8"))?.[1]}catch{return}}function xg(n,r){try{return Ir(Vt(n,r))}catch{return[]}}function Zo(n,r){let t=dt(n,r);return[...t?[t]:[],...xg(n,r)].sort()}function qo(n,r){let t=dt(n,r);if(!t)return;let e=vn(Vt(n,r),t);qr(e,{recursive:!0,force:!0}),Go(e,{recursive:!0});for(let i of Ir(n))if(Ve(i,r))Ro(vn(n,i),vn(e,i.slice(r.length)))}function Uo(n,r,t){let e=vn(Vt(n,r),t);for(let i of Ir(e))Ro(vn(e,i),vn(n,`${r}${i}`));qr(e,{recursive:!0})}function Wo(n,r,t){try{return Ir(vn(n,"originals")).find((e)=>e.startsWith(`${r}-${t}.`))}catch{return}}function Xo(n,r,t){let e=Wo(n,r,t);if(e){let i=new Date;Zg(vn(n,"originals",e),i,i)}}function Vo(n,r,t){let e=Ur(n),i=Zo(e,r),s=dt(e,r);if(!s||i.length<2)throw Error(`${r} has no other image`);let o=(i.indexOf(s)+t+i.length)%i.length,u=i[o];return qo(e,r),Uo(e,r,u),Xo(e,r,u),{key:u,at:o+1,of:i.length}}function Yo(n,r){let t=Ur(n),e=Ir(t).filter((h)=>Ve(h,r));if(e.length===0)throw Error(`${r} has no image`);let i=Zo(t,r),s=dt(t,r),o=s&&Wo(t,r,s);if(o)qr(vn(t,"originals",o));for(let h of e)qr(vn(t,h));let u=i.filter((h)=>h!==s),c=u[(s?i.indexOf(s):0)%u.length];if(c)Uo(t,r,c),Xo(t,r,c);return{key:s,left:u.length}}function Dg(n,r,t){if(dt(n,r)!==t)qo(n,r);if(t)qr(vn(Vt(n,r),t),{recursive:!0,force:!0});_g(n,r)}function Ao(n,r,t,e,i,s){let o=Ur(n),u=r.name,c=Bg(i);Go(vn(o,"originals"),{recursive:!0}),Dg(o,u,c);let h=Jo(e),{width:f,height:g}=zg(s.width,s.height),l=Ko(h,f,g,lt(e,h)),a=Zr(Xe(Tg(e,h),r.background,t.color)),m=Zr(Xe(Lo(e,l,f,g),r.background,t.color)),b=vn(o,`${u}.${Qg("sha1").update(a).update(m).digest("hex").slice(0,8)}`),E=`${b}.png`,F=`${b}@fill-${Math.round(l.focus*100)}.png`,H=vn(o,`${u}.conf`),p=vn(o,"originals",`${u}-${i.site}_${i.id}.${i.ext}`);return Wt(E,a),Wt(F,m),Wt(H,Cg(u,F,t.opacity,i.from,c)),Wt(p,i.bytes),[E,F,H,p]}function zo(n){let r=vn(Ur(n),"originals"),t=new Map,e;try{e=Ir(r)}catch{return new Map}for(let i of e){let s=/^(.+)-([a-z.]+)_(\d+)\.[a-z]+$/.exec(i),[,o,u,c]=s??[];if(!o||!u||!c)continue;let h=Pg(vn(r,i)).mtimeMs,f=t.get(o);if(!f||h>f.at)t.set(o,{site:u,id:Number(c),at:h})}return new Map([...t].map(([i,{site:s,id:o}])=>[i,{site:s,id:o}]))}function Ye(n){let{slot:r,color:t,opacity:e}=Xt({name:n.name,background:n.background,foreground:n.foreground,cursor:n.cursor,selection:n.selectionBackground,ansi:n.ansi,waived:n.waive},n.signatureSlots);return{name:n.name,group:n.group,...n.native?{native:n.native}:{},...n.lead?{lead:!0}:{},order:n.order,ansiSource:n.ansiSource,...n.booru?{booru:n.booru}:{},...n.booruSites?{booruSites:n.booruSites}:{},...n.role==="default"?{default:!0}:{},background:n.background,foreground:n.foreground,cursor:n.cursor,selection:n.selectionBackground,signature:n.signature,signatureSlots:n.signatureSlots,ansi:n.ansi,gate:ms(n),...n.waive.length>0?{waived:n.waive}:{},backdrop:{slot:r,color:t,opacity:e}}}function Wr(n){return n.filter((r)=>r.default!==!0)}function nl(n){let[r]=n;if(!r)throw Error("manifest needs at least one theme");return{version:Dn.version,gate:Pt,placement:or,font:r.font,...r.ghostty.shader?{shader:r.ghostty.shader}:{},palettes:n.map(Ye)}}var Ae={id:"meta",emitShared(n){return[{path:"manifest.json",content:`${JSON.stringify(nl(n),null,2)}
15
- `}]}};import{readdirSync as Rl,readFileSync as xe}from"node:fs";import{basename as Jl,join as De}from"node:path";import{readdirSync as rl,rmSync as tl,statSync as el}from"node:fs";import{setDefaultAutoSelectFamilyAttemptTimeout as il}from"node:net";import{homedir as sl}from"node:os";import{join as mt}from"node:path";import{setTimeout as ol}from"node:timers/promises";var Nr=100,Te=25000000,ul=536870912,$t=["safe","questionable","explicit"],yr=["nudity","underwear"],cl={nudity:new Set(["nude","naked","topless","bottomless","nipples","naked_towel","undressing"]),underwear:new Set(["underwear","panties","pantsu","bra","lingerie","pantyshot"])},at={safe:"s",questionable:"q",explicit:"e"},hl=8191,fl=20000,gl=5000,To=3000,Co=8,ll=3000,Do=60000,_o=3,dl=`ttheme/${Dn.version} (+${Dn.homepage})`,al=["orig","tile","thumb","cut"],nu=new Map,ml=Il(process.env.TTHEME_FIND_HOSTS),$l=Fl(process.env.TTHEME_FIND_CUTOUTS);il(ll);function Bo(n){try{return rl(n)}catch{return[]}}function Yt(n){return n.startsWith("//")?`https:${n}`:n}function bt(n){return(/\.([a-z0-9]+)(?:\?.*)?$/i.exec(n)?.[1]??"").toLowerCase()}function wt(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 bl(n){let r=n.trim(),e=(r?JSON.parse(r):{}).tags??{};return new Map(Object.entries(e).map(([i,s])=>[i,String(s)]))}function ze(n,r,t){let e=Yt(String(n??""));return{file:e,width:Number(r)||0,height:Number(t)||0,ext:bt(e)}}function ru(n,r){let t=Yt(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),solo:r.solo,family:Number(n.parent_id)||(n.has_children===!0?Number(n.id):0),smaller:r.versions.filter((s)=>s.file&&s.width>0&&s.height>0&&s.width*s.height<e*i)}]}function wl(n){let r=bl(n);return wt(n).flatMap((t)=>{let e=Yt(String(t.file_url??"")),i=String(t.tags??"");return ru(t,{preview:t.preview_url,file:e,ext:String(t.file_ext||bt(e)).toLowerCase(),owner:t.author,artist:i.split(/\s+/).find((s)=>r.get(s)==="artist")??"",md5:t.md5,tags:i,solo:void 0,versions:[ze(t.jpeg_url,t.jpeg_width,t.jpeg_height),ze(t.sample_url,t.sample_width,t.sample_height)]})})}function kl(n){return wt(n).flatMap((r)=>{let t=Yt(String(r.file_url??"")),e=String(r.tag_string??""),i=r.media_asset??{};return ru(r,{preview:i.variants?.find((s)=>s.type==="360x360")?.url??r.preview_file_url,file:t,ext:String(r.file_ext||bt(t)).toLowerCase(),owner:"",artist:String(r.tag_string_artist??"").split(/\s+/)[0]??"",md5:r.md5,tags:e,solo:e.split(/\s+/).includes("solo"),versions:(i.variants??[]).map((s)=>ze(s.url,s.width,s.height)).filter((s)=>s.ext==="jpg"||s.ext==="png").sort((s,o)=>o.width*o.height-s.width*s.height)})})}function pl(n){return wt(n).flatMap((r)=>{let t=String(r.value??"");return t?[{value:t,count:Number(r.post_count)||0}]:[]})}function Ml(n){return wt(n).flatMap((r)=>{let t=String(r.name??"");return t?[{value:t,count:Number(r.count)||0}]:[]})}function El(n){return Number(/count="(\d+)"/.exec(n)?.[1]??0)}function vl(n){let r=n.trim()?JSON.parse(n):{};return Number(r.counts?.posts)||0}function Fl(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 Il(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 s=new URL(t.slice(e+1));if(i&&s.protocol==="https:")r.set(i,s.origin)}catch{}}return r}function tu(n,r,t,e){let i=(n??"").split(/\s+/);if(e!==void 0&&i.includes(e))return[];let s=r.filter((o)=>i.includes(o));return s.length>0?s:[...t]}function At(n){return tu(n,$t,["safe"])}function zt(n){return tu(n,yr,yr,"none")}function eu(n,r,t){return{safe:new Set(n),questionable:new Set(r),explicit:new Set(t)}}function iu(n){let r=ml.get(n.key),t=$l.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 su(n){return n.length<2?n.join(""):n.map((r)=>`~${r}`).join(" ")}function xo(n){let r=iu(n),t=(e)=>new URLSearchParams({api_version:"2",include_tags:"1",...e});return{...r,cutouts:su(r.cutouts),ratings:eu([at.safe],[at.questionable],[at.explicit]),rate:(e)=>{let[i]=e;if(e.length===1&&i)return`rating:${at[i]}`;let s=$t.filter((u)=>!e.includes(u)),[o]=s;return s.length===1&&o?`-rating:${at[o]}`:""},best:"order:score",tagBudget:Number.POSITIVE_INFINITY,postsUrl:(e,i)=>`${r.origin}/post.json?${t({limit:String(Nr),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:wl,count:El}}function Nl(n){let r=iu(n),t=eu(["g"],["s","q"],["e"]);return{...r,cutouts:su(r.cutouts),ratings:t,rate:(e)=>e.length===$t.length?"":`rating:${e.flatMap((i)=>[...t[i]]).join(",")}`,best:"order:score",tagBudget:2,postsUrl:(e,i)=>`${r.origin}/posts.json?${new URLSearchParams({limit:String(Nr),page:String(i+1),tags:e})}`,countUrl:(e)=>`${r.origin}/counts/posts.json?${new URLSearchParams({tags:e})}`,postUrl:(e)=>`${r.origin}/posts.json?${new URLSearchParams({limit:"1",tags:`id:${e}`})}`,pageUrl:(e)=>`${r.origin}/posts/${e}`,parse:kl,count:vl}}function yl(n){return pn.find((r)=>r.key===n||r.name===n||new URL(r.origin).host===n)}function Ce(n){return n.split(/\s+/).filter((r)=>r&&!r.startsWith("rating:")).length}function ou(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=pn.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 s=yl(i.host),o=Number(i.searchParams.get("id")??i.pathname.split("/").filter(Boolean).at(-1));return s&&o>0?{site:s,id:o}:void 0}var pn=[Nl({key:"danbooru",name:"danbooru",origin:"https://danbooru.donmai.us",cutouts:["transparent_background"],vouched:!1,tunneled:!0,ansi:2}),xo({key:"konachan",name:"konachan",origin:"https://konachan.net",cutouts:["transparent","vector"],vouched:!1,tunneled:!1,ansi:6}),xo({key:"yande",name:"yande.re",origin:"https://yande.re",cutouts:["transparent_png"],vouched:!0,tunneled:!1,ansi:5})],Sr=134217728;function rr(n,r){return pn.indexOf(n)*Sr+r}function _e(n){let r;try{r=new URL(n).hostname}catch{return""}return r.split(".").slice(-2).join(".")}function uu(){return pn.filter((n)=>!n.tunneled).map((n)=>_e(n.origin)).flatMap((n)=>[n,`.${n}`]).join(",")}function cu(n,r=yr){return n.tags.filter((t)=>r.some((e)=>cl[e].has(t)))}function hu(n,r,t=["safe"]){return t.some((e)=>n.ratings[e].has(r.rating))}function kt(n){return[n,...n.smaller].find((r)=>r.width*r.height<=Te)}function fu(n){let r=new Map;for(let[t,e]of[...n].sort(([i],[s])=>i<s?-1:1)){if(e==="")continue;r.set(e,[...r.get(e)??[],t])}return r}function gu(){return mt(process.env.XDG_CACHE_HOME??mt(sl(),".cache"),"ttheme")}function pr(n){return mt(gu(),n.key)}function lu(n=ul,r=gu()){let t=[],e=0;for(let i of Bo(r))for(let s of al){let o=mt(r,i,s);for(let u of Bo(o)){let c=mt(o,u);try{let{size:h,mtimeMs:f}=el(c);t.push({path:c,size:h,at:f}),e+=h}catch{}}}t.sort((i,s)=>i.at-s.at);for(let i of t){if(e<=n)return;try{tl(i.path,{force:!0}),e-=i.size}catch{}}}function Sl(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)?Do:Math.max(0,t-r)}function wr(n){return nu.get(n.key)??0}function Hl(n){for(let r=n;r instanceof Error;r=r.cause)if(r.code==="ECONNRESET")return!0;return!1}function jl(n){return(n.headers.get("server")??"").startsWith("cloudflare")&&n.headers.get("cf-mitigated")==="challenge"}async function kr(n,r,t,e={},i=fl){for(let s=1;;s++){let o=wr(n)-Date.now();if(o>0)await ol(o,void 0,{signal:t});let u;try{u=await fetch(r,{headers:{"User-Agent":dl,Referer:`${n.origin}/`,...e},signal:i?AbortSignal.any([t,AbortSignal.timeout(i)]):t})}catch(c){if(s<_o&&!t.aborted&&Hl(c))continue;throw c}if(u.status===429&&s<_o){await u.body?.cancel();let c=Sl(u.headers.get("retry-after"),Date.now());if(c>Do)throw Error(`${n.name} asks to wait ${Math.ceil(c/1000)}s`);nu.set(n.key,Math.max(wr(n),Date.now()+c));continue}if(!u.ok)throw await u.body?.cancel(),Error(jl(u)?`${n.name} is behind a Cloudflare challenge`:`${n.name} answered ${u.status}`);return u}}async function du(n,r,t,e){return n.parse(await(await kr(n,n.postsUrl(r,t),e)).text())}async function au(n,r,t){return n.count(await(await kr(n,n.countUrl(r),t)).text())}async function Be(n,r,t){let[e]=n.parse(await(await kr(n,n.postUrl(r),t)).text());return e}function Gl(n){let r=pn.find((e)=>e.key==="danbooru"),t=new URLSearchParams({limit:String(2*Nr),only:"md5,tag_string",tags:`md5:${n.join(",")}`});return`${r.origin}/posts.json?${t}`}function Ol(n){return new Map(wt(n).flatMap((r)=>{let t=String(r.md5??"");return t?[[t,String(r.tag_string??"").split(/\s+/).filter(Boolean)]]:[]}))}function mu(n,r){for(let t of n){let e=r.get(t.md5);if(e)t.tags=[...new Set([...t.tags,...e])],t.solo=e.includes("solo")}}async function $u(n,r){let t=pn.find((i)=>i.key==="danbooru"),e=new Map;if(wr(t)>Date.now())return e;for(let i=0;i<n.length;i+=Nr){let s=await(await kr(t,Gl(n.slice(i,i+Nr)),r,{},gl)).text();for(let[o,u]of Ol(s))e.set(o,u)}return e}async function bu(n,r){let t=pn.find((s)=>s.key==="danbooru");if(wr(t)<=Date.now())try{let s=new URLSearchParams({"search[query]":n,"search[type]":"tag_query",limit:String(Co)}),o=`${t.origin}/autocomplete.json?${s}`;return pl(await(await kr(t,o,r,{},To)).text())}catch(s){if(r.aborted)throw s}let e=pn.find((s)=>s.key==="yande"),i=new URLSearchParams({name:n,order:"count",limit:String(Co)});return Ml(await(await kr(e,`${e.origin}/tag.json?${i}`,r,{},To)).text())}async function wu(n,r,t){let e=await kr(n,r,t,{Range:`bytes=0-${hl}`});return Ue(new Uint8Array(await e.arrayBuffer()))}async function ku(n,r,t,e){let i=await kr(n,r,t,{},0),s=Number(i.headers.get("content-length"))||0,o=i.body?.getReader();if(!o)return new Uint8Array(await i.arrayBuffer());let u=[],c=0;for(;;){let{done:g,value:l}=await o.read();if(g)break;u.push(l),c+=l.length,e?.(c,s)}let h=new Uint8Array(c),f=0;for(let g of u)h.set(g,f),f+=g.length;return h}var Kl="_defaults.toml",ur="_groups.toml",pu=3,Mu=["background","foreground","cursor","selection"],Ll=new Set(["next","help","preview","pin","unpin","config"]);function Fn(n,r){throw Error(`${n}: ${r}`)}function Hr(n,r,t){if(typeof t!=="string"||!hs(t))Fn(n,`${r} must be "#rrggbb" (lowercase), got ${JSON.stringify(t)}`);return t}function Vn(n,r,t){if(typeof t!=="string"||t.length===0)Fn(n,`${r} must be a non-empty string`);return t}function cr(n){return n&&typeof n==="object"?n:{}}function Ql(n,r,t){let e={...cr(t),...cr(r)},i=e.codepoint_map??[];if(!Array.isArray(i))Fn(n,"font.codepoint_map must be an array");return{family:Vn(n,"font.family",e.family),size:Number(e.size),codepointMap:i.map((s)=>{let o=cr(s);return{range:Vn(n,"font.codepoint_map[].range",o.range),family:Vn(n,"font.codepoint_map[].family",o.family)}})}}function Pl(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)Fn(n,"ghostty.icon_screen must not be empty");return e.map((i,s)=>Hr(n,`ghostty.icon_screen[${s}]`,i))}function Zl(n,r,t,e){let i={...cr(t),...cr(r)};return{shader:i.shader===void 0?void 0:Vn(n,"ghostty.shader",i.shader),iconGhost:i.icon_ghost===void 0?e.cursor:Hr(n,"ghostty.icon_ghost",i.icon_ghost),iconScreen:Pl(n,i.icon_screen,e)}}function ql(n){return new Map([...Mu.map((r)=>[r,n[r]]),...n.ansi.map((r,t)=>[`ansi${t}`,r])])}function Ul(n,r,t){if(!Array.isArray(r)||r.length!==pu)Fn(n,`meta.signature must name exactly ${pu} palette slots`);let e=ql(t),i=[],s=[];for(let[o,u]of r.entries()){let c=`meta.signature[${o}]`,h=Vn(n,c,u),f=e.get(h);if(f===void 0)Fn(n,`${c} ${JSON.stringify(u)} is not a palette slot — use ${Mu.join(", ")} or ansi0-ansi15`);i.push(h),s.push(f)}if(new Set(s).size!==s.length)Fn(n,"meta.signature slots must resolve to three different colors");return{names:i,colors:s}}function Wl(n,r,t){if(r===void 0)return;if(!t)Fn(n,"meta.booru_sites renames meta.booru per site, so it needs meta.booru");if(!r||typeof r!=="object"||Array.isArray(r))Fn(n,'meta.booru_sites must be a table of site = "tag" or site = ["tag", ...]');let e={};for(let[i,s]of Object.entries(r)){let o=pn.find((c)=>c.key===i);if(!o)Fn(n,`meta.booru_sites.${i} is not a find site — use ${pn.map((c)=>c.key).join(", ")}`);let u=typeof s==="string"?[s]:Array.isArray(s)?s:void 0;if(!u||u.some((c)=>typeof c!=="string"||c===""||/\s/.test(c)))Fn(n,`meta.booru_sites.${i} must be one tag or a list of tags, got ${JSON.stringify(s)}`);if(u.length>1&&Number.isFinite(o.tagBudget))Fn(n,`meta.booru_sites.${i} takes one tag — ${o.name} searches ${o.tagBudget} tags at a time`);e[i]=u}return e}function Xl(n){let t=Bun.TOML.parse(xe(De(n,ur),"utf8")).group;if(!Array.isArray(t)||t.length===0)Fn(ur,"needs at least one [[group]] table");return t.map((e)=>{let i=cr(e);return{name:Vn(ur,"group.name",i.name),native:i.native===void 0?void 0:Vn(ur,"group.native",i.native),lead:Vn(ur,"group.lead",i.lead)}})}function Vl(n,r,t,e){let i=Bun.TOML.parse(r),s=cr(i.meta),o=cr(i.colors),u=cr(i.contrast),c=o.ansi;if(!Array.isArray(c)||c.length!==16)Fn(n,`colors.ansi must hold exactly 16 colors, got ${Array.isArray(c)?c.length:typeof c}`);let h=Vn(n,"meta.name",s.name);if(h!==Jl(n,".toml"))Fn(n,`meta.name "${h}" does not match the filename`);if(Ll.has(h))Fn(n,`meta.name "${h}" collides with a ttheme subcommand`);if(h.startsWith("-"))Fn(n,`meta.name "${h}" would be read as a flag by the ttheme CLI`);let f=s.role;if(f!==void 0&&f!=="default")Fn(n,`meta.role must be "default", got ${JSON.stringify(f)}`);let g=Vn(n,"meta.group",s.group),l=e.get(g);if(!l)Fn(n,`meta.group "${g}" has no [[group]] table in ${ur}`);let a=Hr(n,"colors.background",o.background),m=Hr(n,"colors.foreground",o.foreground),b=Hr(n,"colors.cursor",o.cursor),E=Hr(n,"colors.selection_background",o.selection_background),F=c.map((O,k)=>Hr(n,`colors.ansi[${k}]`,O)),H=Ul(n,s.signature,{background:a,foreground:m,cursor:b,selection:E,ansi:F}),p=s.booru===void 0?void 0:Vn(n,"meta.booru",s.booru);if(p!==void 0&&/\s/.test(p))Fn(n,`meta.booru must be a single booru tag, got ${JSON.stringify(p)}`);let I=Wl(n,s.booru_sites,p),w=Array.isArray(u.waive)?u.waive.map(String):[];if(w.length>0&&typeof u.reason!=="string")Fn(n,"contrast.waive needs a contrast.reason explaining why");return{name:h,group:g,native:l.native,lead:l.lead===h,order:Number(s.order),role:f,ansiSource:Vn(n,"meta.ansi_source",s.ansi_source),...p?{booru:p}:{},...I?{booruSites:I}:{},background:a,foreground:m,cursor:b,selectionBackground:E,ansi:F,signature:H.colors,signatureSlots:H.names,font:Ql(n,i.font,t.font),ghostty:Zl(n,i.ghostty,t.ghostty,{background:a,cursor:b,selectionBackground:E}),waive:w,waiveReason:typeof u.reason==="string"?u.reason:void 0}}function Eu(n){let r=Bun.TOML.parse(xe(De(n,Kl),"utf8")),t=Xl(n),e=new Map(t.map((o)=>[o.name,o]));if(e.size!==t.length)Fn(ur,"group.name must be unique");let i=Rl(n).filter((o)=>o.endsWith(".toml")&&!o.startsWith("_")).map((o)=>Vl(o,xe(De(n,o),"utf8"),r,e)).sort((o,u)=>o.order-u.order);if(new Set(i.map((o)=>o.order)).size!==i.length)throw Error("themes: meta.order must be unique across all themes");for(let o of t){let u=i.filter((c)=>c.group===o.name);if(u.length===0)Fn(ur,`group "${o.name}" has no themes`);if(!u.some((c)=>c.name===o.lead))Fn(ur,`group "${o.name}" lead "${o.lead}" is not one of its themes`)}return i}function vu(n){return n.filter((r)=>r.role===void 0)}function pt(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 Tt=["ghostty","kitty","alacritty","iterm2"];var Fu=/# ttheme begin\n[\s\S]*?# ttheme end\n?/;function Ct(n,r){let t=`# ttheme begin
2
+ import{createRequire as Hf}from"node:module";var Ef=Object.create;var{getPrototypeOf:vf,defineProperty:ko,getOwnPropertyNames:Ff}=Object;var yf=Object.prototype.hasOwnProperty;function If(n){return this[n]}var Sf,Nf,Te=(n,r,e)=>{var t=n!=null&&typeof n==="object";if(t){var i=r?Sf??=new WeakMap:Nf??=new WeakMap,o=i.get(n);if(o)return o}e=n!=null?Ef(vf(n)):{};let s=r||!n||!n.__esModule?ko(e,"default",{value:n,enumerable:!0}):e;for(let u of Ff(n))if(!yf.call(s,u))ko(s,u,{get:If.bind(n,u),enumerable:!0});if(t)i.set(n,s);return s};var pn=(n,r)=>()=>(r||n((r={exports:{}}).exports,r),r.exports);var Rn=Hf(import.meta.url);var Lo=pn((I0,Ce)=>{var Go=Go||function(n){return Buffer.from(n).toString("base64")};function Kf(n){var r=this,e=Math.round,t=Math.floor,i=Array(64),o=Array(64),s=Array(64),u=Array(64),c,h,f,l,g=Array(65535),d=Array(65535),w=Array(64),m=Array(64),b=[],F=0,S=7,k=Array(64),y=Array(64),p=Array(64),R=Array(256),M=Array(2048),j,H=[0,1,5,6,14,15,27,28,2,4,7,13,16,26,29,42,3,8,12,17,25,30,41,43,9,11,18,24,31,40,44,53,10,19,23,32,39,45,52,54,20,22,33,38,46,51,55,60,21,34,37,47,50,56,59,61,35,36,48,49,57,58,62,63],J=[0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0],G=[0,1,2,3,4,5,6,7,8,9,10,11],z=[0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,125],U=[1,2,3,0,4,17,5,18,33,49,65,6,19,81,97,7,34,113,20,50,129,145,161,8,35,66,177,193,21,82,209,240,36,51,98,114,130,9,10,22,23,24,25,26,37,38,39,40,41,42,52,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,225,226,227,228,229,230,231,232,233,234,241,242,243,244,245,246,247,248,249,250],Sn=[0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0],Q=[0,1,2,3,4,5,6,7,8,9,10,11],B=[0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,119],En=[0,1,2,3,17,4,5,33,49,6,18,65,81,7,97,113,19,34,50,129,8,20,66,145,161,177,193,9,35,51,82,240,21,98,114,209,10,22,36,52,225,37,241,23,24,25,26,38,39,40,41,42,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,130,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,226,227,228,229,230,231,232,233,234,242,243,244,245,246,247,248,249,250];function mn(a){var L=[16,11,10,16,24,40,51,61,12,12,14,19,26,58,60,55,14,13,16,24,40,57,69,56,14,17,22,29,51,87,80,62,18,22,37,56,68,109,103,77,24,35,55,64,81,104,113,92,49,64,78,87,103,121,120,101,72,92,95,98,112,100,103,99];for(var W=0;W<64;W++){var P=t((L[W]*a+50)/100);if(P<1)P=1;else if(P>255)P=255;i[H[W]]=P}var X=[17,18,24,47,99,99,99,99,18,21,26,66,99,99,99,99,24,26,56,99,99,99,99,99,47,66,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99];for(var T=0;T<64;T++){var tn=t((X[T]*a+50)/100);if(tn<1)tn=1;else if(tn>255)tn=255;o[H[T]]=tn}var on=[1,1.387039845,1.306562965,1.175875602,1,0.785694958,0.5411961,0.275899379],In=0;for(var wn=0;wn<8;wn++)for(var v=0;v<8;v++)s[In]=1/(i[H[In]]*on[wn]*on[v]*8),u[In]=1/(o[H[In]]*on[wn]*on[v]*8),In++}function x(a,L){var W=0,P=0,X=[];for(var T=1;T<=16;T++){for(var tn=1;tn<=a[T];tn++)X[L[P]]=[],X[L[P]][0]=W,X[L[P]][1]=T,P++,W++;W*=2}return X}function Nn(){c=x(J,G),h=x(Sn,Q),f=x(z,U),l=x(B,En)}function sn(){var a=1,L=2;for(var W=1;W<=15;W++){for(var P=a;P<L;P++)d[32767+P]=W,g[32767+P]=[],g[32767+P][1]=W,g[32767+P][0]=P;for(var X=-(L-1);X<=-a;X++)d[32767+X]=W,g[32767+X]=[],g[32767+X][1]=W,g[32767+X][0]=L-1+X;a<<=1,L<<=1}}function nn(){for(var a=0;a<256;a++)M[a]=19595*a,M[a+256>>0]=38470*a,M[a+512>>0]=7471*a+32768,M[a+768>>0]=-11059*a,M[a+1024>>0]=-21709*a,M[a+1280>>0]=32768*a+8421375,M[a+1536>>0]=-27439*a,M[a+1792>>0]=-5329*a}function Y(a){var L=a[0],W=a[1]-1;while(W>=0){if(L&1<<W)F|=1<<S;if(W--,S--,S<0){if(F==255)$(255),$(0);else $(F);S=7,F=0}}}function $(a){b.push(a)}function K(a){$(a>>8&255),$(a&255)}function gn(a,L){var W,P,X,T,tn,on,In,wn,v=0,O,A=8,vn=64;for(O=0;O<A;++O){W=a[v],P=a[v+1],X=a[v+2],T=a[v+3],tn=a[v+4],on=a[v+5],In=a[v+6],wn=a[v+7];var V=W+wn,D=W-wn,an=P+In,Z=P-In,un=X+on,jn=X-on,kn=T+tn,Xn=T-tn,nr=V+kn,Fr=V-kn,Jr=an+un,Kr=an-un;a[v]=nr+Jr,a[v+4]=nr-Jr;var oe=(Kr+Fr)*0.707106781;a[v+2]=Fr+oe,a[v+6]=Fr-oe,nr=Xn+jn,Jr=jn+Z,Kr=Z+D;var se=(nr-Kr)*0.382683433,Ze=0.5411961*nr+se,ue=1.306562965*Kr+se,ce=Jr*0.707106781,he=D+ce,fe=D-ce;a[v+5]=fe+Ze,a[v+3]=fe-Ze,a[v+1]=he+ue,a[v+7]=he-ue,v+=8}v=0;for(O=0;O<A;++O){W=a[v],P=a[v+8],X=a[v+16],T=a[v+24],tn=a[v+32],on=a[v+40],In=a[v+48],wn=a[v+56];var so=W+wn,jt=W-wn,uo=P+In,co=P-In,ho=X+on,fo=X-on,go=T+tn,Mf=T-tn,ge=so+go,Rt=so-go,qe=uo+ho,Ae=uo-ho;a[v]=ge+qe,a[v+32]=ge-qe;var lo=(Ae+Rt)*0.707106781;a[v+16]=Rt+lo,a[v+48]=Rt-lo,ge=Mf+fo,qe=fo+co,Ae=co+jt;var ao=(ge-Ae)*0.382683433,mo=0.5411961*ge+ao,$o=1.306562965*Ae+ao,wo=qe*0.707106781,po=jt+wo,bo=jt-wo;a[v+40]=bo+mo,a[v+24]=bo-mo,a[v+8]=po+$o,a[v+56]=po-$o,v++}var Xe;for(O=0;O<vn;++O)Xe=a[O]*L[O],w[O]=Xe>0?Xe+0.5|0:Xe-0.5|0;return w}function ln(){K(65504),K(16),$(74),$(70),$(73),$(70),$(0),$(1),$(1),$(0),K(1),K(1),$(0),$(0)}function rn(a){if(!a)return;if(K(65505),a[0]===69&&a[1]===120&&a[2]===105&&a[3]===102)K(a.length+2);else K(a.length+5+2),$(69),$(120),$(105),$(102),$(0);for(var L=0;L<a.length;L++)$(a[L])}function en(a,L){K(65472),K(17),$(8),K(L),K(a),$(3),$(1),$(17),$(0),$(2),$(17),$(1),$(3),$(17),$(1)}function C(){K(65499),K(132),$(0);for(var a=0;a<64;a++)$(i[a]);$(1);for(var L=0;L<64;L++)$(o[L])}function N(){K(65476),K(418),$(0);for(var a=0;a<16;a++)$(J[a+1]);for(var L=0;L<=11;L++)$(G[L]);$(16);for(var W=0;W<16;W++)$(z[W+1]);for(var P=0;P<=161;P++)$(U[P]);$(1);for(var X=0;X<16;X++)$(Sn[X+1]);for(var T=0;T<=11;T++)$(Q[T]);$(17);for(var tn=0;tn<16;tn++)$(B[tn+1]);for(var on=0;on<=161;on++)$(En[on])}function I(a){if(typeof a>"u"||a.constructor!==Array)return;a.forEach((L)=>{if(typeof L!=="string")return;K(65534);var W=L.length;K(W+2);var P;for(P=0;P<W;P++)$(L.charCodeAt(P))})}function $n(){K(65498),K(12),$(3),$(1),$(0),$(2),$(17),$(3),$(17),$(0),$(63),$(0)}function q(a,L,W,P,X){var T=X[0],tn=X[240],on,In=16,wn=63,v=64,O=gn(a,L);for(var A=0;A<v;++A)m[H[A]]=O[A];var vn=m[0]-W;if(W=m[0],vn==0)Y(P[0]);else on=32767+vn,Y(P[d[on]]),Y(g[on]);var V=63;for(;V>0&&m[V]==0;V--);if(V==0)return Y(T),W;var D=1,an;while(D<=V){var Z=D;for(;m[D]==0&&D<=V;++D);var un=D-Z;if(un>=In){an=un>>4;for(var jn=1;jn<=an;++jn)Y(tn);un=un&15}on=32767+m[D],Y(X[(un<<4)+d[on]]),Y(g[on]),D++}if(V!=wn)Y(T);return W}function _(){var a=String.fromCharCode;for(var L=0;L<256;L++)R[L]=a(L)}this.encode=function(a,L){var W=new Date().getTime();if(L)An(L);b=[],F=0,S=7,K(65496),ln(),I(a.comments),rn(a.exifBuffer),C(),en(a.width,a.height),N(),$n();var P=0,X=0,T=0;F=0,S=7,this.encode.displayName="_encode_";var{data:tn,width:on,height:In}=a,wn=on*4,v=on*3,O,A=0,vn,V,D,an,Z,un,jn,kn;while(A<In){O=0;while(O<wn){an=wn*A+O,Z=an,un=-1,jn=0;for(kn=0;kn<64;kn++){if(jn=kn>>3,un=(kn&7)*4,Z=an+jn*wn+un,A+jn>=In)Z-=wn*(A+1+jn-In);if(O+un>=wn)Z-=O+un-wn+4;vn=tn[Z++],V=tn[Z++],D=tn[Z++],k[kn]=(M[vn]+M[V+256>>0]+M[D+512>>0]>>16)-128,y[kn]=(M[vn+768>>0]+M[V+1024>>0]+M[D+1280>>0]>>16)-128,p[kn]=(M[vn+1280>>0]+M[V+1536>>0]+M[D+1792>>0]>>16)-128}P=q(k,s,P,c,f),X=q(y,u,X,h,l),T=q(p,u,T,h,l),O+=32}A+=8}if(S>=0){var Xn=[];Xn[1]=S+1,Xn[0]=(1<<S+1)-1,Y(Xn)}if(K(65497),typeof Ce>"u")return new Uint8Array(b);return Buffer.from(b);var nr,Fr};function An(a){if(a<=0)a=1;if(a>100)a=100;if(j==a)return;var L=0;if(a<50)L=Math.floor(5000/a);else L=Math.floor(200-a*2);mn(L),j=a}function Cn(){var a=new Date().getTime();if(!n)n=50;_(),Nn(),sn(),nn(),An(n);var L=new Date().getTime()-a}Cn()}if(typeof Ce<"u")Ce.exports=Ro;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].encode=Ro;function Ro(n,r){if(typeof r>"u")r=50;var e=new Kf(r),t=e.encode(n,r);return{data:t,width:n.width,height:n.height}}});var Ko=pn((S0,Pt)=>{var Kt=function(){var r=new Int32Array([0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5,12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28,35,42,49,56,57,50,43,36,29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54,47,55,62,63]),e=4017,t=799,i=3406,o=2276,s=1567,u=3784,c=5793,h=2896;function f(){}function l(S,k){var y=0,p=[],R,M,j=16;while(j>0&&!S[j-1])j--;p.push({children:[],index:0});var H=p[0],J;for(R=0;R<j;R++){for(M=0;M<S[R];M++){H=p.pop(),H.children[H.index]=k[y];while(H.index>0){if(p.length===0)throw Error("Could not recreate Huffman Table");H=p.pop()}H.index++,p.push(H);while(p.length<=R)p.push(J={children:[],index:0}),H.children[H.index]=J.children,H=J;y++}if(R+1<j)p.push(J={children:[],index:0}),H.children[H.index]=J.children,H=J}return p[0].children}function g(S,k,y,p,R,M,j,H,J,G){var{precision:z,samplesPerLine:U,scanLines:Sn,mcusPerLine:Q,progressive:B,maxH:En,maxV:mn}=y,x=k,Nn=0,sn=0;function nn(){if(sn>0)return sn--,Nn>>sn&1;if(Nn=S[k++],Nn==255){var v=S[k++];if(v)throw Error("unexpected marker: "+(Nn<<8|v).toString(16))}return sn=7,Nn>>>7}function Y(v){var O=v,A;while((A=nn())!==null){if(O=O[A],typeof O==="number")return O;if(typeof O!=="object")throw Error("invalid huffman sequence")}return null}function $(v){var O=0;while(v>0){var A=nn();if(A===null)return;O=O<<1|A,v--}return O}function K(v){var O=$(v);if(O>=1<<v-1)return O;return O+(-1<<v)+1}function gn(v,O){var A=Y(v.huffmanTableDC),vn=A===0?0:K(A);O[0]=v.pred+=vn;var V=1;while(V<64){var D=Y(v.huffmanTableAC),an=D&15,Z=D>>4;if(an===0){if(Z<15)break;V+=16;continue}V+=Z;var un=r[V];O[un]=K(an),V++}}function ln(v,O){var A=Y(v.huffmanTableDC),vn=A===0?0:K(A)<<J;O[0]=v.pred+=vn}function rn(v,O){O[0]|=nn()<<J}var en=0;function C(v,O){if(en>0){en--;return}var A=M,vn=j;while(A<=vn){var V=Y(v.huffmanTableAC),D=V&15,an=V>>4;if(D===0){if(an<15){en=$(an)+(1<<an)-1;break}A+=16;continue}A+=an;var Z=r[A];O[Z]=K(D)*(1<<J),A++}}var N=0,I;function $n(v,O){var A=M,vn=j,V=0;while(A<=vn){var D=r[A],an=O[D]<0?-1:1;switch(N){case 0:var Z=Y(v.huffmanTableAC),un=Z&15,V=Z>>4;if(un===0)if(V<15)en=$(V)+(1<<V),N=4;else V=16,N=1;else{if(un!==1)throw Error("invalid ACn encoding");I=K(un),N=V?2:3}continue;case 1:case 2:if(O[D])O[D]+=(nn()<<J)*an;else if(V--,V===0)N=N==2?3:0;break;case 3:if(O[D])O[D]+=(nn()<<J)*an;else O[D]=I<<J,N=0;break;case 4:if(O[D])O[D]+=(nn()<<J)*an;break}A++}if(N===4){if(en--,en===0)N=0}}function q(v,O,A,vn,V){var D=A/Q|0,an=A%Q,Z=D*v.v+vn,un=an*v.h+V;if(v.blocks[Z]===void 0&&G.tolerantDecoding)return;O(v,v.blocks[Z][un])}function _(v,O,A){var vn=A/v.blocksPerLine|0,V=A%v.blocksPerLine;if(v.blocks[vn]===void 0&&G.tolerantDecoding)return;O(v,v.blocks[vn][V])}var An=p.length,Cn,a,L,W,P,X;if(B)if(M===0)X=H===0?ln:rn;else X=H===0?C:$n;else X=gn;var T=0,tn,on;if(An==1)on=p[0].blocksPerLine*p[0].blocksPerColumn;else on=Q*y.mcusPerColumn;if(!R)R=on;var In,wn;while(T<on){for(a=0;a<An;a++)p[a].pred=0;if(en=0,An==1){Cn=p[0];for(P=0;P<R;P++)_(Cn,X,T),T++}else for(P=0;P<R;P++){for(a=0;a<An;a++){Cn=p[a],In=Cn.h,wn=Cn.v;for(L=0;L<wn;L++)for(W=0;W<In;W++)q(Cn,X,T,L,W)}if(T++,T===on)break}if(T===on)do{if(S[k]===255){if(S[k+1]!==0)break}k+=1}while(k<S.length-2);if(sn=0,tn=S[k]<<8|S[k+1],tn<65280)throw Error("marker was not found");if(tn>=65488&&tn<=65495)k+=2;else break}return k-x}function d(S,k){var y=[],p=k.blocksPerLine,R=k.blocksPerColumn,M=p<<3,j=new Int32Array(64),H=new Uint8Array(64);function J(x,Nn,sn){var nn=k.quantizationTable,Y,$,K,gn,ln,rn,en,C,N,I=sn,$n;for($n=0;$n<64;$n++)I[$n]=x[$n]*nn[$n];for($n=0;$n<8;++$n){var q=8*$n;if(I[1+q]==0&&I[2+q]==0&&I[3+q]==0&&I[4+q]==0&&I[5+q]==0&&I[6+q]==0&&I[7+q]==0){N=c*I[0+q]+512>>10,I[0+q]=N,I[1+q]=N,I[2+q]=N,I[3+q]=N,I[4+q]=N,I[5+q]=N,I[6+q]=N,I[7+q]=N;continue}Y=c*I[0+q]+128>>8,$=c*I[4+q]+128>>8,K=I[2+q],gn=I[6+q],ln=h*(I[1+q]-I[7+q])+128>>8,C=h*(I[1+q]+I[7+q])+128>>8,rn=I[3+q]<<4,en=I[5+q]<<4,N=Y-$+1>>1,Y=Y+$+1>>1,$=N,N=K*u+gn*s+128>>8,K=K*s-gn*u+128>>8,gn=N,N=ln-en+1>>1,ln=ln+en+1>>1,en=N,N=C+rn+1>>1,rn=C-rn+1>>1,C=N,N=Y-gn+1>>1,Y=Y+gn+1>>1,gn=N,N=$-K+1>>1,$=$+K+1>>1,K=N,N=ln*o+C*i+2048>>12,ln=ln*i-C*o+2048>>12,C=N,N=rn*t+en*e+2048>>12,rn=rn*e-en*t+2048>>12,en=N,I[0+q]=Y+C,I[7+q]=Y-C,I[1+q]=$+en,I[6+q]=$-en,I[2+q]=K+rn,I[5+q]=K-rn,I[3+q]=gn+ln,I[4+q]=gn-ln}for($n=0;$n<8;++$n){var _=$n;if(I[8+_]==0&&I[16+_]==0&&I[24+_]==0&&I[32+_]==0&&I[40+_]==0&&I[48+_]==0&&I[56+_]==0){N=c*sn[$n+0]+8192>>14,I[0+_]=N,I[8+_]=N,I[16+_]=N,I[24+_]=N,I[32+_]=N,I[40+_]=N,I[48+_]=N,I[56+_]=N;continue}Y=c*I[0+_]+2048>>12,$=c*I[32+_]+2048>>12,K=I[16+_],gn=I[48+_],ln=h*(I[8+_]-I[56+_])+2048>>12,C=h*(I[8+_]+I[56+_])+2048>>12,rn=I[24+_],en=I[40+_],N=Y-$+1>>1,Y=Y+$+1>>1,$=N,N=K*u+gn*s+2048>>12,K=K*s-gn*u+2048>>12,gn=N,N=ln-en+1>>1,ln=ln+en+1>>1,en=N,N=C+rn+1>>1,rn=C-rn+1>>1,C=N,N=Y-gn+1>>1,Y=Y+gn+1>>1,gn=N,N=$-K+1>>1,$=$+K+1>>1,K=N,N=ln*o+C*i+2048>>12,ln=ln*i-C*o+2048>>12,C=N,N=rn*t+en*e+2048>>12,rn=rn*e-en*t+2048>>12,en=N,I[0+_]=Y+C,I[56+_]=Y-C,I[8+_]=$+en,I[48+_]=$-en,I[16+_]=K+rn,I[40+_]=K-rn,I[24+_]=gn+ln,I[32+_]=gn-ln}for($n=0;$n<64;++$n){var An=128+(I[$n]+8>>4);Nn[$n]=An<0?0:An>255?255:An}}F(M*R*8);var G,z;for(var U=0;U<R;U++){var Sn=U<<3;for(G=0;G<8;G++)y.push(new Uint8Array(M));for(var Q=0;Q<p;Q++){J(k.blocks[U][Q],H,j);var B=0,En=Q<<3;for(z=0;z<8;z++){var mn=y[Sn+z];for(G=0;G<8;G++)mn[En+G]=H[B++]}}}return y}function w(S){return S<0?0:S>255?255:S}f.prototype={load:function(k){var y=new XMLHttpRequest;y.open("GET",k,!0),y.responseType="arraybuffer",y.onload=function(){var p=new Uint8Array(y.response||y.mozResponseArrayBuffer);if(this.parse(p),this.onload)this.onload()}.bind(this),y.send(null)},parse:function(k){var y=this.opts.maxResolutionInMP*1000*1000,p=0,R=k.length;function M(){var Z=k[p]<<8|k[p+1];return p+=2,Z}function j(){var Z=M(),un=k.subarray(p,p+Z-2);return p+=un.length,un}function H(Z){var un=1,jn=1,kn,Xn;for(Xn in Z.components)if(Z.components.hasOwnProperty(Xn)){if(kn=Z.components[Xn],un<kn.h)un=kn.h;if(jn<kn.v)jn=kn.v}var nr=Math.ceil(Z.samplesPerLine/8/un),Fr=Math.ceil(Z.scanLines/8/jn);for(Xn in Z.components)if(Z.components.hasOwnProperty(Xn)){kn=Z.components[Xn];var Jr=Math.ceil(Math.ceil(Z.samplesPerLine/8)*kn.h/un),Kr=Math.ceil(Math.ceil(Z.scanLines/8)*kn.v/jn),oe=nr*kn.h,se=Fr*kn.v,Ze=se*oe,ue=[];F(Ze*256);for(var ce=0;ce<se;ce++){var he=[];for(var fe=0;fe<oe;fe++)he.push(new Int32Array(64));ue.push(he)}kn.blocksPerLine=Jr,kn.blocksPerColumn=Kr,kn.blocks=ue}Z.maxH=un,Z.maxV=jn,Z.mcusPerLine=nr,Z.mcusPerColumn=Fr}var J=null,G=null,z=null,U,Sn,Q=[],B=[],En=[],mn=[],x=M(),Nn=-1;if(this.comments=[],x!=65496)throw Error("SOI not found");x=M();while(x!=65497){var sn,nn,Y;switch(x){case 65280:break;case 65504:case 65505:case 65506:case 65507:case 65508:case 65509:case 65510:case 65511:case 65512:case 65513:case 65514:case 65515:case 65516:case 65517:case 65518:case 65519:case 65534:var $=j();if(x===65534){var K=String.fromCharCode.apply(null,$);this.comments.push(K)}if(x===65504){if($[0]===74&&$[1]===70&&$[2]===73&&$[3]===70&&$[4]===0)J={version:{major:$[5],minor:$[6]},densityUnits:$[7],xDensity:$[8]<<8|$[9],yDensity:$[10]<<8|$[11],thumbWidth:$[12],thumbHeight:$[13],thumbData:$.subarray(14,14+3*$[12]*$[13])}}if(x===65505){if($[0]===69&&$[1]===120&&$[2]===105&&$[3]===102&&$[4]===0)this.exifBuffer=$.subarray(5,$.length)}if(x===65518){if($[0]===65&&$[1]===100&&$[2]===111&&$[3]===98&&$[4]===101&&$[5]===0)G={version:$[6],flags0:$[7]<<8|$[8],flags1:$[9]<<8|$[10],transformCode:$[11]}}break;case 65499:var gn=M(),ln=gn+p-2;while(p<ln){var rn=k[p++];F(256);var en=new Int32Array(64);if(rn>>4===0)for(nn=0;nn<64;nn++){var C=r[nn];en[C]=k[p++]}else if(rn>>4===1)for(nn=0;nn<64;nn++){var C=r[nn];en[C]=M()}else throw Error("DQT: invalid table spec");Q[rn&15]=en}break;case 65472:case 65473:case 65474:M(),U={},U.extended=x===65473,U.progressive=x===65474,U.precision=k[p++],U.scanLines=M(),U.samplesPerLine=M(),U.components={},U.componentsOrder=[];var N=U.scanLines*U.samplesPerLine;if(N>y){var I=Math.ceil((N-y)/1e6);throw Error(`maxResolutionInMP limit exceeded by ${I}MP`)}var $n=k[p++],q,_=0,An=0;for(sn=0;sn<$n;sn++){q=k[p];var Cn=k[p+1]>>4,a=k[p+1]&15,L=k[p+2];if(Cn<=0||a<=0)throw Error("Invalid sampling factor, expected values above 0");U.componentsOrder.push(q),U.components[q]={h:Cn,v:a,quantizationIdx:L},p+=3}H(U),B.push(U);break;case 65476:var W=M();for(sn=2;sn<W;){var P=k[p++],X=new Uint8Array(16),T=0;for(nn=0;nn<16;nn++,p++)T+=X[nn]=k[p];F(16+T);var tn=new Uint8Array(T);for(nn=0;nn<T;nn++,p++)tn[nn]=k[p];sn+=17+T,(P>>4===0?mn:En)[P&15]=l(X,tn)}break;case 65501:M(),Sn=M();break;case 65500:M(),M();break;case 65498:var on=M(),In=k[p++],wn=[],v;for(sn=0;sn<In;sn++){v=U.components[k[p++]];var O=k[p++];v.huffmanTableDC=mn[O>>4],v.huffmanTableAC=En[O&15],wn.push(v)}var A=k[p++],vn=k[p++],V=k[p++],D=g(k,p,U,wn,Sn,A,vn,V>>4,V&15,this.opts);p+=D;break;case 65535:if(k[p]!==255)p--;break;default:if(k[p-3]==255&&k[p-2]>=192&&k[p-2]<=254){p-=3;break}else if(x===224||x==225){if(Nn!==-1)throw Error(`first unknown JPEG marker at offset ${Nn.toString(16)}, second unknown JPEG marker ${x.toString(16)} at offset ${(p-1).toString(16)}`);Nn=p-1;let Z=M();if(k[p+Z-2]===255){p+=Z-2;break}}throw Error("unknown JPEG marker "+x.toString(16))}x=M()}if(B.length!=1)throw Error("only single frame JPEGs supported");for(var sn=0;sn<B.length;sn++){var an=B[sn].components;for(var nn in an)an[nn].quantizationTable=Q[an[nn].quantizationIdx],delete an[nn].quantizationIdx}this.width=U.samplesPerLine,this.height=U.scanLines,this.jfif=J,this.adobe=G,this.components=[];for(var sn=0;sn<U.componentsOrder.length;sn++){var v=U.components[U.componentsOrder[sn]];this.components.push({lines:d(U,v),scaleX:v.h/U.maxH,scaleY:v.v/U.maxV})}},getData:function(k,y){var p=this.width/k,R=this.height/y,M,j,H,J,G,z,U,Sn,Q,B,En=0,mn,x,Nn,sn,nn,Y,$,K,gn,ln,rn,en=k*y*this.components.length;F(en);var C=new Uint8Array(en);switch(this.components.length){case 1:M=this.components[0];for(B=0;B<y;B++){G=M.lines[0|B*M.scaleY*R];for(Q=0;Q<k;Q++)mn=G[0|Q*M.scaleX*p],C[En++]=mn}break;case 2:M=this.components[0],j=this.components[1];for(B=0;B<y;B++){G=M.lines[0|B*M.scaleY*R],z=j.lines[0|B*j.scaleY*R];for(Q=0;Q<k;Q++)mn=G[0|Q*M.scaleX*p],C[En++]=mn,mn=z[0|Q*j.scaleX*p],C[En++]=mn}break;case 3:if(rn=!0,this.adobe&&this.adobe.transformCode)rn=!0;else if(typeof this.opts.colorTransform<"u")rn=!!this.opts.colorTransform;M=this.components[0],j=this.components[1],H=this.components[2];for(B=0;B<y;B++){G=M.lines[0|B*M.scaleY*R],z=j.lines[0|B*j.scaleY*R],U=H.lines[0|B*H.scaleY*R];for(Q=0;Q<k;Q++){if(!rn)K=G[0|Q*M.scaleX*p],gn=z[0|Q*j.scaleX*p],ln=U[0|Q*H.scaleX*p];else mn=G[0|Q*M.scaleX*p],x=z[0|Q*j.scaleX*p],Nn=U[0|Q*H.scaleX*p],K=w(mn+1.402*(Nn-128)),gn=w(mn-0.3441363*(x-128)-0.71413636*(Nn-128)),ln=w(mn+1.772*(x-128));C[En++]=K,C[En++]=gn,C[En++]=ln}}break;case 4:if(!this.adobe)throw Error("Unsupported color mode (4 components)");if(rn=!1,this.adobe&&this.adobe.transformCode)rn=!0;else if(typeof this.opts.colorTransform<"u")rn=!!this.opts.colorTransform;M=this.components[0],j=this.components[1],H=this.components[2],J=this.components[3];for(B=0;B<y;B++){G=M.lines[0|B*M.scaleY*R],z=j.lines[0|B*j.scaleY*R],U=H.lines[0|B*H.scaleY*R],Sn=J.lines[0|B*J.scaleY*R];for(Q=0;Q<k;Q++){if(!rn)nn=G[0|Q*M.scaleX*p],Y=z[0|Q*j.scaleX*p],$=U[0|Q*H.scaleX*p],sn=Sn[0|Q*J.scaleX*p];else mn=G[0|Q*M.scaleX*p],x=z[0|Q*j.scaleX*p],Nn=U[0|Q*H.scaleX*p],sn=Sn[0|Q*J.scaleX*p],nn=255-w(mn+1.402*(Nn-128)),Y=255-w(mn-0.3441363*(x-128)-0.71413636*(Nn-128)),$=255-w(mn+1.772*(x-128));C[En++]=255-nn,C[En++]=255-Y,C[En++]=255-$,C[En++]=255-sn}}break;default:throw Error("Unsupported color mode")}return C},copyToImageData:function(k,y){var{width:p,height:R,data:M}=k,j=this.getData(p,R),H=0,J=0,G,z,U,Sn,Q,B,En,mn,x;switch(this.components.length){case 1:for(z=0;z<R;z++)for(G=0;G<p;G++)if(U=j[H++],M[J++]=U,M[J++]=U,M[J++]=U,y)M[J++]=255;break;case 3:for(z=0;z<R;z++)for(G=0;G<p;G++)if(En=j[H++],mn=j[H++],x=j[H++],M[J++]=En,M[J++]=mn,M[J++]=x,y)M[J++]=255;break;case 4:for(z=0;z<R;z++)for(G=0;G<p;G++)if(Q=j[H++],B=j[H++],U=j[H++],Sn=j[H++],En=255-w(Q*(1-Sn/255)+Sn),mn=255-w(B*(1-Sn/255)+Sn),x=255-w(U*(1-Sn/255)+Sn),M[J++]=En,M[J++]=mn,M[J++]=x,y)M[J++]=255;break;default:throw Error("Unsupported color mode")}}};var m=0,b=0;function F(S=0){var k=m+S;if(k>b){var y=Math.ceil((k-b)/1024/1024);throw Error(`maxMemoryUsageInMB limit exceeded by at least ${y}MB`)}m=k}return f.resetMaxMemoryUsage=function(S){m=0,b=S},f.getBytesAllocated=function(){return m},f.requestMemoryAllocation=F,f}();if(typeof Pt<"u")Pt.exports=Jo;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].decode=Jo;function Jo(n,r={}){var e={colorTransform:void 0,useTArray:!1,formatAsRGBA:!0,tolerantDecoding:!0,maxResolutionInMP:100,maxMemoryUsageInMB:512},t={...e,...r},i=new Uint8Array(n),o=new Kt;o.opts=t,Kt.resetMaxMemoryUsage(t.maxMemoryUsageInMB*1024*1024),o.parse(i);var s=t.formatAsRGBA?4:3,u=o.width*o.height*s;try{Kt.requestMemoryAllocation(u);var c={width:o.width,height:o.height,exifBuffer:o.exifBuffer,data:t.useTArray?new Uint8Array(u):Buffer.alloc(u)};if(o.comments.length>0)c.comments=o.comments}catch(h){if(h instanceof RangeError)throw Error("Could not allocate enough memory for the image. Required: "+u);if(h instanceof ReferenceError){if(h.message==="Buffer is not defined")throw Error("Buffer is not globally defined in this environment. Consider setting useTArray to true")}throw h}return o.copyToImageData(c,t.formatAsRGBA),c}});var Uo=pn((N0,Po)=>{var Pf=Lo(),Uf=Ko();Po.exports={encode:Pf,decode:Uf}});var Ut=pn((H0,Wo)=>{var Qf=Rn("util"),Qo=Rn("stream"),Bn=Wo.exports=function(){Qo.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};Qf.inherits(Bn,Qo);Bn.prototype.read=function(n,r){this._reads.push({length:Math.abs(n),allowLess:n<0,func:r}),process.nextTick(function(){if(this._process(),this._paused&&this._reads&&this._reads.length>0)this._paused=!1,this.emit("drain")}.bind(this))};Bn.prototype.write=function(n,r){if(!this.writable)return this.emit("error",Error("Stream not writable")),!1;let e;if(Buffer.isBuffer(n))e=n;else e=Buffer.from(n,r||this._encoding);if(this._buffers.push(e),this._buffered+=e.length,this._process(),this._reads&&this._reads.length===0)this._paused=!0;return this.writable&&!this._paused};Bn.prototype.end=function(n,r){if(n)this.write(n,r);if(this.writable=!1,!this._buffers)return;if(this._buffers.length===0)this._end();else this._buffers.push(null),this._process()};Bn.prototype.destroySoon=Bn.prototype.end;Bn.prototype._end=function(){if(this._reads.length>0)this.emit("error",Error("Unexpected end of input"));this.destroy()};Bn.prototype.destroy=function(){if(!this._buffers)return;this.writable=!1,this._reads=null,this._buffers=null,this.emit("close")};Bn.prototype._processReadAllowingLess=function(n){this._reads.shift();let r=this._buffers[0];if(r.length>n.length)this._buffered-=n.length,this._buffers[0]=r.slice(n.length),n.func.call(this,r.slice(0,n.length));else this._buffered-=r.length,this._buffers.shift(),n.func.call(this,r)};Bn.prototype._processRead=function(n){this._reads.shift();let r=0,e=0,t=Buffer.alloc(n.length);while(r<n.length){let i=this._buffers[e++],o=Math.min(i.length,n.length-r);if(i.copy(t,r,0,o),r+=o,o!==i.length)this._buffers[--e]=i.slice(o)}if(e>0)this._buffers.splice(0,e);this._buffered-=n.length,n.func.call(this,t)};Bn.prototype._process=function(){try{while(this._buffered>0&&this._reads&&this._reads.length>0){let n=this._reads[0];if(n.allowLess)this._processReadAllowingLess(n);else if(this._buffered>=n.length)this._processRead(n);else break}if(this._buffers&&!this.writable)this._end()}catch(n){this.emit("error",n)}}});var Qt=pn((Wf)=>{var wr=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];Wf.getImagePasses=function(n,r){let e=[],t=n%8,i=r%8,o=(n-t)/8,s=(r-i)/8;for(let u=0;u<wr.length;u++){let c=wr[u],h=o*c.x.length,f=s*c.y.length;for(let l=0;l<c.x.length;l++)if(c.x[l]<t)h++;else break;for(let l=0;l<c.y.length;l++)if(c.y[l]<i)f++;else break;if(h>0&&f>0)e.push({width:h,height:f,index:u})}return e};Wf.getInterlaceIterator=function(n){return function(r,e,t){let i=r%wr[t].x.length,o=(r-i)/wr[t].x.length*8+wr[t].x[i],s=e%wr[t].y.length,u=(e-s)/wr[t].y.length*8+wr[t].y[s];return o*4+u*n*4}}});var Wt=pn((j0,Zo)=>{Zo.exports=function(r,e,t){let i=r+e-t,o=Math.abs(i-r),s=Math.abs(i-e),u=Math.abs(i-t);if(o<=s&&o<=u)return r;if(s<=u)return e;return t}});var Zt=pn((R0,Ao)=>{var Af=Qt(),Xf=Wt();function qo(n,r,e){let t=n*r;if(e!==8)t=Math.ceil(t/(8/e));return t}var Ur=Ao.exports=function(n,r){let{width:e,height:t,interlace:i,bpp:o,depth:s}=n;if(this.read=r.read,this.write=r.write,this.complete=r.complete,this._imageIndex=0,this._images=[],i){let u=Af.getImagePasses(e,t);for(let c=0;c<u.length;c++)this._images.push({byteWidth:qo(u[c].width,o,s),height:u[c].height,lineIndex:0})}else this._images.push({byteWidth:qo(e,o,s),height:t,lineIndex:0});if(s===8)this._xComparison=o;else if(s===16)this._xComparison=o*2;else this._xComparison=1};Ur.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Ur.prototype._unFilterType1=function(n,r,e){let t=this._xComparison,i=t-1;for(let o=0;o<e;o++){let s=n[1+o],u=o>i?r[o-t]:0;r[o]=s+u}};Ur.prototype._unFilterType2=function(n,r,e){let t=this._lastLine;for(let i=0;i<e;i++){let o=n[1+i],s=t?t[i]:0;r[i]=o+s}};Ur.prototype._unFilterType3=function(n,r,e){let t=this._xComparison,i=t-1,o=this._lastLine;for(let s=0;s<e;s++){let u=n[1+s],c=o?o[s]:0,h=s>i?r[s-t]:0,f=Math.floor((h+c)/2);r[s]=u+f}};Ur.prototype._unFilterType4=function(n,r,e){let t=this._xComparison,i=t-1,o=this._lastLine;for(let s=0;s<e;s++){let u=n[1+s],c=o?o[s]:0,h=s>i?r[s-t]:0,f=s>i&&o?o[s-t]:0,l=Xf(h,c,f);r[s]=u+l}};Ur.prototype._reverseFilterLine=function(n){let r=n[0],e,t=this._images[this._imageIndex],i=t.byteWidth;if(r===0)e=n.slice(1,i+1);else switch(e=Buffer.alloc(i),r){case 1:this._unFilterType1(n,e,i);break;case 2:this._unFilterType2(n,e,i);break;case 3:this._unFilterType3(n,e,i);break;case 4:this._unFilterType4(n,e,i);break;default:throw Error("Unrecognised filter type - "+r)}if(this.write(e),t.lineIndex++,t.lineIndex>=t.height)this._lastLine=null,this._imageIndex++,t=this._images[this._imageIndex];else this._lastLine=e;if(t)this.read(t.byteWidth+1,this._reverseFilterLine.bind(this));else this._lastLine=null,this.complete()}});var Vo=pn((G0,To)=>{var Tf=Rn("util"),Xo=Ut(),Vf=Zt(),zf=To.exports=function(n){Xo.call(this);let r=[],e=this;this._filter=new Vf(n,{read:this.read.bind(this),write:function(t){r.push(t)},complete:function(){e.emit("complete",Buffer.concat(r))}}),this._filter.start()};Tf.inherits(zf,Xo)});var Qr=pn((L0,zo)=>{zo.exports={PNG_SIGNATURE:[137,80,78,71,13,10,26,10],TYPE_IHDR:1229472850,TYPE_IEND:1229278788,TYPE_IDAT:1229209940,TYPE_PLTE:1347179589,TYPE_tRNS:1951551059,TYPE_gAMA:1732332865,COLORTYPE_GRAYSCALE:0,COLORTYPE_PALETTE:1,COLORTYPE_COLOR:2,COLORTYPE_ALPHA:4,COLORTYPE_PALETTE_COLOR:3,COLORTYPE_COLOR_ALPHA:6,COLORTYPE_TO_BPP_MAP:{0:1,2:3,3:1,4:2,6:4},GAMMA_DIVISION:1e5}});var Xt=pn((J0,Yo)=>{var qt=[];(function(){for(let n=0;n<256;n++){let r=n;for(let e=0;e<8;e++)if(r&1)r=3988292384^r>>>1;else r=r>>>1;qt[n]=r}})();var At=Yo.exports=function(){this._crc=-1};At.prototype.write=function(n){for(let r=0;r<n.length;r++)this._crc=qt[(this._crc^n[r])&255]^this._crc>>>8;return!0};At.prototype.crc32=function(){return this._crc^-1};At.crc32=function(n){let r=-1;for(let e=0;e<n.length;e++)r=qt[(r^n[e])&255]^r>>>8;return r^-1}});var Tt=pn((K0,Co)=>{var Hn=Qr(),Yf=Xt(),On=Co.exports=function(n,r){this._options=n,n.checkCRC=n.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[Hn.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[Hn.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[Hn.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[Hn.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[Hn.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[Hn.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=r.read,this.error=r.error,this.metadata=r.metadata,this.gamma=r.gamma,this.transColor=r.transColor,this.palette=r.palette,this.parsed=r.parsed,this.inflateData=r.inflateData,this.finished=r.finished,this.simpleTransparency=r.simpleTransparency,this.headersFinished=r.headersFinished||function(){}};On.prototype.start=function(){this.read(Hn.PNG_SIGNATURE.length,this._parseSignature.bind(this))};On.prototype._parseSignature=function(n){let r=Hn.PNG_SIGNATURE;for(let e=0;e<r.length;e++)if(n[e]!==r[e]){this.error(Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};On.prototype._parseChunkBegin=function(n){let r=n.readUInt32BE(0),e=n.readUInt32BE(4),t="";for(let o=4;o<8;o++)t+=String.fromCharCode(n[o]);let i=Boolean(n[4]&32);if(!this._hasIHDR&&e!==Hn.TYPE_IHDR){this.error(Error("Expected IHDR on beggining"));return}if(this._crc=new Yf,this._crc.write(Buffer.from(t)),this._chunks[e])return this._chunks[e](r);if(!i){this.error(Error("Unsupported critical chunk type "+t));return}this.read(r+4,this._skipChunk.bind(this))};On.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};On.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};On.prototype._parseChunkEnd=function(n){let r=n.readInt32BE(0),e=this._crc.crc32();if(this._options.checkCRC&&e!==r){this.error(Error("Crc error - "+r+" - "+e));return}if(!this._hasIEND)this.read(8,this._parseChunkBegin.bind(this))};On.prototype._handleIHDR=function(n){this.read(n,this._parseIHDR.bind(this))};On.prototype._parseIHDR=function(n){this._crc.write(n);let r=n.readUInt32BE(0),e=n.readUInt32BE(4),t=n[8],i=n[9],o=n[10],s=n[11],u=n[12];if(t!==8&&t!==4&&t!==2&&t!==1&&t!==16){this.error(Error("Unsupported bit depth "+t));return}if(!(i in Hn.COLORTYPE_TO_BPP_MAP)){this.error(Error("Unsupported color type"));return}if(o!==0){this.error(Error("Unsupported compression method"));return}if(s!==0){this.error(Error("Unsupported filter method"));return}if(u!==0&&u!==1){this.error(Error("Unsupported interlace method"));return}this._colorType=i;let c=Hn.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:r,height:e,depth:t,interlace:Boolean(u),palette:Boolean(i&Hn.COLORTYPE_PALETTE),color:Boolean(i&Hn.COLORTYPE_COLOR),alpha:Boolean(i&Hn.COLORTYPE_ALPHA),bpp:c,colorType:i}),this._handleChunkEnd()};On.prototype._handlePLTE=function(n){this.read(n,this._parsePLTE.bind(this))};On.prototype._parsePLTE=function(n){this._crc.write(n);let r=Math.floor(n.length/3);for(let e=0;e<r;e++)this._palette.push([n[e*3],n[e*3+1],n[e*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};On.prototype._handleTRNS=function(n){this.simpleTransparency(),this.read(n,this._parseTRNS.bind(this))};On.prototype._parseTRNS=function(n){if(this._crc.write(n),this._colorType===Hn.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(Error("Transparency chunk must be after palette"));return}if(n.length>this._palette.length){this.error(Error("More transparent colors than palette size"));return}for(let r=0;r<n.length;r++)this._palette[r][3]=n[r];this.palette(this._palette)}if(this._colorType===Hn.COLORTYPE_GRAYSCALE)this.transColor([n.readUInt16BE(0)]);if(this._colorType===Hn.COLORTYPE_COLOR)this.transColor([n.readUInt16BE(0),n.readUInt16BE(2),n.readUInt16BE(4)]);this._handleChunkEnd()};On.prototype._handleGAMA=function(n){this.read(n,this._parseGAMA.bind(this))};On.prototype._parseGAMA=function(n){this._crc.write(n),this.gamma(n.readUInt32BE(0)/Hn.GAMMA_DIVISION),this._handleChunkEnd()};On.prototype._handleIDAT=function(n){if(!this._emittedHeadersFinished)this._emittedHeadersFinished=!0,this.headersFinished();this.read(-n,this._parseIDAT.bind(this,n))};On.prototype._parseIDAT=function(n,r){if(this._crc.write(r),this._colorType===Hn.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw Error("Expected palette not found");this.inflateData(r);let e=n-r.length;if(e>0)this._handleIDAT(e);else this._handleChunkEnd()};On.prototype._handleIEND=function(n){this.read(n,this._parseIEND.bind(this))};On.prototype._parseIEND=function(n){if(this._crc.write(n),this._hasIEND=!0,this._handleChunkEnd(),this.finished)this.finished()}});var Vt=pn((ng)=>{var _o=Qt(),Cf=[function(){},function(n,r,e,t){if(t===r.length)throw Error("Ran out of data");let i=r[t];n[e]=i,n[e+1]=i,n[e+2]=i,n[e+3]=255},function(n,r,e,t){if(t+1>=r.length)throw Error("Ran out of data");let i=r[t];n[e]=i,n[e+1]=i,n[e+2]=i,n[e+3]=r[t+1]},function(n,r,e,t){if(t+2>=r.length)throw Error("Ran out of data");n[e]=r[t],n[e+1]=r[t+1],n[e+2]=r[t+2],n[e+3]=255},function(n,r,e,t){if(t+3>=r.length)throw Error("Ran out of data");n[e]=r[t],n[e+1]=r[t+1],n[e+2]=r[t+2],n[e+3]=r[t+3]}],_f=[function(){},function(n,r,e,t){let i=r[0];n[e]=i,n[e+1]=i,n[e+2]=i,n[e+3]=t},function(n,r,e){let t=r[0];n[e]=t,n[e+1]=t,n[e+2]=t,n[e+3]=r[1]},function(n,r,e,t){n[e]=r[0],n[e+1]=r[1],n[e+2]=r[2],n[e+3]=t},function(n,r,e){n[e]=r[0],n[e+1]=r[1],n[e+2]=r[2],n[e+3]=r[3]}];function Bf(n,r){let e=[],t=0;function i(){if(t===n.length)throw Error("Ran out of data");let o=n[t];t++;let s,u,c,h,f,l,g,d;switch(r){default:throw Error("unrecognised depth");case 16:g=n[t],t++,e.push((o<<8)+g);break;case 4:g=o&15,d=o>>4,e.push(d,g);break;case 2:f=o&3,l=o>>2&3,g=o>>4&3,d=o>>6&3,e.push(d,g,l,f);break;case 1:s=o&1,u=o>>1&1,c=o>>2&1,h=o>>3&1,f=o>>4&1,l=o>>5&1,g=o>>6&1,d=o>>7&1,e.push(d,g,l,f,h,c,u,s);break}}return{get:function(o){while(e.length<o)i();let s=e.slice(0,o);return e=e.slice(o),s},resetAfterLine:function(){e.length=0},end:function(){if(t!==n.length)throw Error("extra data found")}}}function xf(n,r,e,t,i,o){let{width:s,height:u,index:c}=n;for(let h=0;h<u;h++)for(let f=0;f<s;f++){let l=e(f,h,c);Cf[t](r,i,l,o),o+=t}return o}function Df(n,r,e,t,i,o){let{width:s,height:u,index:c}=n;for(let h=0;h<u;h++){for(let f=0;f<s;f++){let l=i.get(t),g=e(f,h,c);_f[t](r,l,g,o)}i.resetAfterLine()}}ng.dataToBitMap=function(n,r){let{width:e,height:t,depth:i,bpp:o,interlace:s}=r,u;if(i!==8)u=Bf(n,i);let c;if(i<=8)c=Buffer.alloc(e*t*4);else c=new Uint16Array(e*t*4);let h=Math.pow(2,i)-1,f=0,l,g;if(s)l=_o.getImagePasses(e,t),g=_o.getInterlaceIterator(e,t);else{let d=0;g=function(){let w=d;return d+=4,w},l=[{width:e,height:t}]}for(let d=0;d<l.length;d++)if(i===8)f=xf(l[d],c,g,o,n,f);else Df(l[d],c,g,o,u,h);if(i===8){if(f!==n.length)throw Error("extra data found")}else u.end();return c}});var zt=pn((U0,Bo)=>{function eg(n,r,e,t,i){let o=0;for(let s=0;s<t;s++)for(let u=0;u<e;u++){let c=i[n[o]];if(!c)throw Error("index "+n[o]+" not in palette");for(let h=0;h<4;h++)r[o+h]=c[h];o+=4}}function tg(n,r,e,t,i){let o=0;for(let s=0;s<t;s++)for(let u=0;u<e;u++){let c=!1;if(i.length===1){if(i[0]===n[o])c=!0}else if(i[0]===n[o]&&i[1]===n[o+1]&&i[2]===n[o+2])c=!0;if(c)for(let h=0;h<4;h++)r[o+h]=0;o+=4}}function ig(n,r,e,t,i){let o=255,s=Math.pow(2,i)-1,u=0;for(let c=0;c<t;c++)for(let h=0;h<e;h++){for(let f=0;f<4;f++)r[u+f]=Math.floor(n[u+f]*o/s+0.5);u+=4}}Bo.exports=function(n,r,e=!1){let{depth:t,width:i,height:o,colorType:s,transColor:u,palette:c}=r,h=n;if(s===3)eg(n,h,i,o,c);else{if(u)tg(n,h,i,o,u);if(t!==8&&!e){if(t===16)h=Buffer.alloc(i*o*4);ig(n,h,i,o,t)}}return h}});var ns=pn((Q0,Do)=>{var og=Rn("util"),Yt=Rn("zlib"),xo=Ut(),sg=Vo(),ug=Tt(),cg=Vt(),hg=zt(),er=Do.exports=function(n){xo.call(this),this._parser=new ug(n,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,"gamma"),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=n,this.writable=!0,this._parser.start()};og.inherits(er,xo);er.prototype._handleError=function(n){if(this.emit("error",n),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy)this._inflate.destroy();if(this._filter)this._filter.destroy(),this._filter.on("error",function(){});this.errord=!0};er.prototype._inflateData=function(n){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=Yt.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let e=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,t=Math.max(e,Yt.Z_MIN_CHUNK);this._inflate=Yt.createInflate({chunkSize:t});let i=e,o=this.emit.bind(this,"error");this._inflate.on("error",function(u){if(!i)return;o(u)}),this._filter.on("complete",this._complete.bind(this));let s=this._filter.write.bind(this._filter);this._inflate.on("data",function(u){if(!i)return;if(u.length>i)u=u.slice(0,i);i-=u.length,s(u)}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(n)};er.prototype._handleMetaData=function(n){this._metaData=n,this._bitmapInfo=Object.create(n),this._filter=new sg(this._bitmapInfo)};er.prototype._handleTransColor=function(n){this._bitmapInfo.transColor=n};er.prototype._handlePalette=function(n){this._bitmapInfo.palette=n};er.prototype._simpleTransparency=function(){this._metaData.alpha=!0};er.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};er.prototype._finished=function(){if(this.errord)return;if(!this._inflate)this.emit("error","No Inflate block");else this._inflate.end()};er.prototype._complete=function(n){if(this.errord)return;let r;try{let e=cg.dataToBitMap(n,this._bitmapInfo);r=hg(e,this._bitmapInfo,this._options.skipRescale),e=null}catch(e){this._handleError(e);return}this.emit("parsed",r)}});var es=pn((W0,rs)=>{var Tn=Qr();rs.exports=function(n,r,e,t){let i=[Tn.COLORTYPE_COLOR_ALPHA,Tn.COLORTYPE_ALPHA].indexOf(t.colorType)!==-1;if(t.colorType===t.inputColorType){let w=function(){let m=new ArrayBuffer(2);return new DataView(m).setInt16(0,256,!0),new Int16Array(m)[0]!==256}();if(t.bitDepth===8||t.bitDepth===16&&w)return n}let o=t.bitDepth!==16?n:new Uint16Array(n.buffer),s=255,u=Tn.COLORTYPE_TO_BPP_MAP[t.inputColorType];if(u===4&&!t.inputHasAlpha)u=3;let c=Tn.COLORTYPE_TO_BPP_MAP[t.colorType];if(t.bitDepth===16)s=65535,c*=2;let h=Buffer.alloc(r*e*c),f=0,l=0,g=t.bgColor||{};if(g.red===void 0)g.red=s;if(g.green===void 0)g.green=s;if(g.blue===void 0)g.blue=s;function d(){let w,m,b,F=s;switch(t.inputColorType){case Tn.COLORTYPE_COLOR_ALPHA:F=o[f+3],w=o[f],m=o[f+1],b=o[f+2];break;case Tn.COLORTYPE_COLOR:w=o[f],m=o[f+1],b=o[f+2];break;case Tn.COLORTYPE_ALPHA:F=o[f+1],w=o[f],m=w,b=w;break;case Tn.COLORTYPE_GRAYSCALE:w=o[f],m=w,b=w;break;default:throw Error("input color type:"+t.inputColorType+" is not supported at present")}if(t.inputHasAlpha){if(!i)F/=s,w=Math.min(Math.max(Math.round((1-F)*g.red+F*w),0),s),m=Math.min(Math.max(Math.round((1-F)*g.green+F*m),0),s),b=Math.min(Math.max(Math.round((1-F)*g.blue+F*b),0),s)}return{red:w,green:m,blue:b,alpha:F}}for(let w=0;w<e;w++)for(let m=0;m<r;m++){let b=d(o,f);switch(t.colorType){case Tn.COLORTYPE_COLOR_ALPHA:case Tn.COLORTYPE_COLOR:if(t.bitDepth===8){if(h[l]=b.red,h[l+1]=b.green,h[l+2]=b.blue,i)h[l+3]=b.alpha}else if(h.writeUInt16BE(b.red,l),h.writeUInt16BE(b.green,l+2),h.writeUInt16BE(b.blue,l+4),i)h.writeUInt16BE(b.alpha,l+6);break;case Tn.COLORTYPE_ALPHA:case Tn.COLORTYPE_GRAYSCALE:{let F=(b.red+b.green+b.blue)/3;if(t.bitDepth===8){if(h[l]=F,i)h[l+1]=b.alpha}else if(h.writeUInt16BE(F,l),i)h.writeUInt16BE(b.alpha,l+2);break}default:throw Error("unrecognised color Type "+t.colorType)}f+=u,l+=c}return h}});var os=pn((Z0,is)=>{var ts=Wt();function fg(n,r,e,t,i){for(let o=0;o<e;o++)t[i+o]=n[r+o]}function gg(n,r,e){let t=0,i=r+e;for(let o=r;o<i;o++)t+=Math.abs(n[o]);return t}function lg(n,r,e,t,i,o){for(let s=0;s<e;s++){let u=s>=o?n[r+s-o]:0,c=n[r+s]-u;t[i+s]=c}}function ag(n,r,e,t){let i=0;for(let o=0;o<e;o++){let s=o>=t?n[r+o-t]:0,u=n[r+o]-s;i+=Math.abs(u)}return i}function dg(n,r,e,t,i){for(let o=0;o<e;o++){let s=r>0?n[r+o-e]:0,u=n[r+o]-s;t[i+o]=u}}function mg(n,r,e){let t=0,i=r+e;for(let o=r;o<i;o++){let s=r>0?n[o-e]:0,u=n[o]-s;t+=Math.abs(u)}return t}function $g(n,r,e,t,i,o){for(let s=0;s<e;s++){let u=s>=o?n[r+s-o]:0,c=r>0?n[r+s-e]:0,h=n[r+s]-(u+c>>1);t[i+s]=h}}function wg(n,r,e,t){let i=0;for(let o=0;o<e;o++){let s=o>=t?n[r+o-t]:0,u=r>0?n[r+o-e]:0,c=n[r+o]-(s+u>>1);i+=Math.abs(c)}return i}function pg(n,r,e,t,i,o){for(let s=0;s<e;s++){let u=s>=o?n[r+s-o]:0,c=r>0?n[r+s-e]:0,h=r>0&&s>=o?n[r+s-(e+o)]:0,f=n[r+s]-ts(u,c,h);t[i+s]=f}}function bg(n,r,e,t){let i=0;for(let o=0;o<e;o++){let s=o>=t?n[r+o-t]:0,u=r>0?n[r+o-e]:0,c=r>0&&o>=t?n[r+o-(e+t)]:0,h=n[r+o]-ts(s,u,c);i+=Math.abs(h)}return i}var kg={0:fg,1:lg,2:dg,3:$g,4:pg},Mg={0:gg,1:ag,2:mg,3:wg,4:bg};is.exports=function(n,r,e,t,i){let o;if(!("filterType"in t)||t.filterType===-1)o=[0,1,2,3,4];else if(typeof t.filterType==="number")o=[t.filterType];else throw Error("unrecognised filter types");if(t.bitDepth===16)i*=2;let s=r*i,u=0,c=0,h=Buffer.alloc((s+1)*e),f=o[0];for(let l=0;l<e;l++){if(o.length>1){let g=1/0;for(let d=0;d<o.length;d++){let w=Mg[o[d]](n,c,s,i);if(w<g)f=o[d],g=w}}h[u]=f,u++,kg[f](n,c,s,h,u,i),u+=s,c+=s}return h}});var Ct=pn((q0,ss)=>{var Ln=Qr(),Eg=Xt(),vg=es(),Fg=os(),yg=Rn("zlib"),pr=ss.exports=function(n){if(this._options=n,n.deflateChunkSize=n.deflateChunkSize||32768,n.deflateLevel=n.deflateLevel!=null?n.deflateLevel:9,n.deflateStrategy=n.deflateStrategy!=null?n.deflateStrategy:3,n.inputHasAlpha=n.inputHasAlpha!=null?n.inputHasAlpha:!0,n.deflateFactory=n.deflateFactory||yg.createDeflate,n.bitDepth=n.bitDepth||8,n.colorType=typeof n.colorType==="number"?n.colorType:Ln.COLORTYPE_COLOR_ALPHA,n.inputColorType=typeof n.inputColorType==="number"?n.inputColorType:Ln.COLORTYPE_COLOR_ALPHA,[Ln.COLORTYPE_GRAYSCALE,Ln.COLORTYPE_COLOR,Ln.COLORTYPE_COLOR_ALPHA,Ln.COLORTYPE_ALPHA].indexOf(n.colorType)===-1)throw Error("option color type:"+n.colorType+" is not supported at present");if([Ln.COLORTYPE_GRAYSCALE,Ln.COLORTYPE_COLOR,Ln.COLORTYPE_COLOR_ALPHA,Ln.COLORTYPE_ALPHA].indexOf(n.inputColorType)===-1)throw Error("option input color type:"+n.inputColorType+" is not supported at present");if(n.bitDepth!==8&&n.bitDepth!==16)throw Error("option bit depth:"+n.bitDepth+" is not supported at present")};pr.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};pr.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};pr.prototype.filterData=function(n,r,e){let t=vg(n,r,e,this._options),i=Ln.COLORTYPE_TO_BPP_MAP[this._options.colorType];return Fg(t,r,e,this._options,i)};pr.prototype._packChunk=function(n,r){let e=r?r.length:0,t=Buffer.alloc(e+12);if(t.writeUInt32BE(e,0),t.writeUInt32BE(n,4),r)r.copy(t,8);return t.writeInt32BE(Eg.crc32(t.slice(4,t.length-4)),t.length-4),t};pr.prototype.packGAMA=function(n){let r=Buffer.alloc(4);return r.writeUInt32BE(Math.floor(n*Ln.GAMMA_DIVISION),0),this._packChunk(Ln.TYPE_gAMA,r)};pr.prototype.packIHDR=function(n,r){let e=Buffer.alloc(13);return e.writeUInt32BE(n,0),e.writeUInt32BE(r,4),e[8]=this._options.bitDepth,e[9]=this._options.colorType,e[10]=0,e[11]=0,e[12]=0,this._packChunk(Ln.TYPE_IHDR,e)};pr.prototype.packIDAT=function(n){return this._packChunk(Ln.TYPE_IDAT,n)};pr.prototype.packIEND=function(){return this._packChunk(Ln.TYPE_IEND,null)}});var fs=pn((A0,hs)=>{var Ig=Rn("util"),us=Rn("stream"),Sg=Qr(),Ng=Ct(),cs=hs.exports=function(n){us.call(this);let r=n||{};this._packer=new Ng(r),this._deflate=this._packer.createDeflate(),this.readable=!0};Ig.inherits(cs,us);cs.prototype.pack=function(n,r,e,t){if(this.emit("data",Buffer.from(Sg.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(r,e)),t)this.emit("data",this._packer.packGAMA(t));let i=this._packer.filterData(n,r,e);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(o){this.emit("data",this._packer.packIDAT(o))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(i)}});var $s=pn((we,ms)=>{var gs=Rn("assert").ok,Wr=Rn("zlib"),Hg=Rn("util"),ls=Rn("buffer").kMaxLength;function yr(n){if(!(this instanceof yr))return new yr(n);if(n&&n.chunkSize<Wr.Z_MIN_CHUNK)n.chunkSize=Wr.Z_MIN_CHUNK;if(Wr.Inflate.call(this,n),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,n&&n.maxLength!=null)this._maxLength=n.maxLength}function Og(n){return new yr(n)}function as(n,r){if(r)process.nextTick(r);if(!n._handle)return;n._handle.close(),n._handle=null}yr.prototype._processChunk=function(n,r,e){if(typeof e==="function")return Wr.Inflate._processChunk.call(this,n,r,e);let t=this,i=n&&n.length,o=this._chunkSize-this._offset,s=this._maxLength,u=0,c=[],h=0,f;this.on("error",function(w){f=w});function l(w,m){if(t._hadError)return;let b=o-m;if(gs(b>=0,"have should not go down"),b>0){let F=t._buffer.slice(t._offset,t._offset+b);if(t._offset+=b,F.length>s)F=F.slice(0,s);if(c.push(F),h+=F.length,s-=F.length,s===0)return!1}if(m===0||t._offset>=t._chunkSize)o=t._chunkSize,t._offset=0,t._buffer=Buffer.allocUnsafe(t._chunkSize);if(m===0)return u+=i-w,i=w,!0;return!1}gs(this._handle,"zlib binding closed");let g;do g=this._handle.writeSync(r,n,u,i,this._buffer,this._offset,o),g=g||this._writeState;while(!this._hadError&&l(g[0],g[1]));if(this._hadError)throw f;if(h>=ls)throw as(this),RangeError("Cannot create final Buffer. It would be larger than 0x"+ls.toString(16)+" bytes");let d=Buffer.concat(c,h);return as(this),d};Hg.inherits(yr,Wr.Inflate);function jg(n,r){if(typeof r==="string")r=Buffer.from(r);if(!(r instanceof Buffer))throw TypeError("Not a string or buffer");let e=n._finishFlushFlag;if(e==null)e=Wr.Z_FINISH;return n._processChunk(r,e)}function ds(n,r){return jg(new yr(r),n)}ms.exports=we=ds;we.Inflate=yr;we.createInflate=Og;we.inflateSync=ds});var _t=pn((X0,ps)=>{var ws=ps.exports=function(n){this._buffer=n,this._reads=[]};ws.prototype.read=function(n,r){this._reads.push({length:Math.abs(n),allowLess:n<0,func:r})};ws.prototype.process=function(){while(this._reads.length>0&&this._buffer.length){let n=this._reads[0];if(this._buffer.length&&(this._buffer.length>=n.length||n.allowLess)){this._reads.shift();let r=this._buffer;this._buffer=r.slice(n.length),n.func.call(this,r.slice(0,n.length))}else break}if(this._reads.length>0)throw Error("There are some read requests waitng on finished stream");if(this._buffer.length>0)throw Error("unrecognised content at end of stream")}});var bs=pn((Lg)=>{var Rg=_t(),Gg=Zt();Lg.process=function(n,r){let e=[],t=new Rg(n);return new Gg(r,{read:t.read.bind(t),write:function(o){e.push(o)},complete:function(){}}).start(),t.process(),Buffer.concat(e)}});var vs=pn((V0,Es)=>{var ks=!0,Ms=Rn("zlib"),Kg=$s();if(!Ms.deflateSync)ks=!1;var Pg=_t(),Ug=bs(),Qg=Tt(),Wg=Vt(),Zg=zt();Es.exports=function(n,r){if(!ks)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let e;function t(y){e=y}let i;function o(y){i=y}function s(y){i.transColor=y}function u(y){i.palette=y}function c(){i.alpha=!0}let h;function f(y){h=y}let l=[];function g(y){l.push(y)}let d=new Pg(n);if(new Qg(r,{read:d.read.bind(d),error:t,metadata:o,gamma:f,palette:u,transColor:s,inflateData:g,simpleTransparency:c}).start(),d.process(),e)throw e;let m=Buffer.concat(l);l.length=0;let b;if(i.interlace)b=Ms.inflateSync(m);else{let p=((i.width*i.bpp*i.depth+7>>3)+1)*i.height;b=Kg(m,{chunkSize:p,maxLength:p})}if(m=null,!b||!b.length)throw Error("bad png - invalid inflate data response");let F=Ug.process(b,i);m=null;let S=Wg.dataToBitMap(F,i);F=null;let k=Zg(S,i,r.skipRescale);return i.data=k,i.gamma=h||0,i}});var Ss=pn((z0,Is)=>{var Fs=!0,ys=Rn("zlib");if(!ys.deflateSync)Fs=!1;var qg=Qr(),Ag=Ct();Is.exports=function(n,r){if(!Fs)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let t=new Ag(r||{}),i=[];if(i.push(Buffer.from(qg.PNG_SIGNATURE)),i.push(t.packIHDR(n.width,n.height)),n.gamma)i.push(t.packGAMA(n.gamma));let o=t.filterData(n.data,n.width,n.height),s=ys.deflateSync(o,t.getDeflateOptions());if(o=null,!s||!s.length)throw Error("bad png - invalid compressed data response");return i.push(t.packIDAT(s)),i.push(t.packIEND()),Buffer.concat(i)}});var Ns=pn((Vg)=>{var Xg=vs(),Tg=Ss();Vg.read=function(n,r){return Xg(n,r||{})};Vg.write=function(n,r){return Tg(n,r)}});var Os=pn((Dg)=>{var Cg=Rn("util"),Hs=Rn("stream"),_g=ns(),Bg=fs(),xg=Ns(),Jn=Dg.PNG=function(n){if(Hs.call(this),n=n||{},this.width=n.width|0,this.height=n.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,n.fill&&this.data)this.data.fill(0);this.gamma=0,this.readable=this.writable=!0,this._parser=new _g(n),this._parser.on("error",this.emit.bind(this,"error")),this._parser.on("close",this._handleClose.bind(this)),this._parser.on("metadata",this._metadata.bind(this)),this._parser.on("gamma",this._gamma.bind(this)),this._parser.on("parsed",function(r){this.data=r,this.emit("parsed",r)}.bind(this)),this._packer=new Bg(n),this._packer.on("data",this.emit.bind(this,"data")),this._packer.on("end",this.emit.bind(this,"end")),this._parser.on("close",this._handleClose.bind(this)),this._packer.on("error",this.emit.bind(this,"error"))};Cg.inherits(Jn,Hs);Jn.sync=xg;Jn.prototype.pack=function(){if(!this.data||!this.data.length)return this.emit("error","No data provided"),this;return process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this};Jn.prototype.parse=function(n,r){if(r){let e,t;e=function(i){this.removeListener("error",t),this.data=i,r(null,this)}.bind(this),t=function(i){this.removeListener("parsed",e),r(i,null)}.bind(this),this.once("parsed",e),this.once("error",t)}return this.end(n),this};Jn.prototype.write=function(n){return this._parser.write(n),!0};Jn.prototype.end=function(n){this._parser.end(n)};Jn.prototype._metadata=function(n){this.width=n.width,this.height=n.height,this.emit("metadata",n)};Jn.prototype._gamma=function(n){this.gamma=n};Jn.prototype._handleClose=function(){if(!this._parser.writable&&!this._packer.readable)this.emit("close")};Jn.bitblt=function(n,r,e,t,i,o,s,u){if(e|=0,t|=0,i|=0,o|=0,s|=0,u|=0,e>n.width||t>n.height||e+i>n.width||t+o>n.height)throw Error("bitblt reading outside image");if(s>r.width||u>r.height||s+i>r.width||u+o>r.height)throw Error("bitblt writing outside image");for(let c=0;c<o;c++)n.data.copy(r.data,(u+c)*r.width+s<<2,(t+c)*n.width+e<<2,(t+c)*n.width+e+i<<2)};Jn.prototype.bitblt=function(n,r,e,t,i,o,s){return Jn.bitblt(this,n,r,e,t,i,o,s),this};Jn.adjustGamma=function(n){if(n.gamma){for(let r=0;r<n.height;r++)for(let e=0;e<n.width;e++){let t=n.width*r+e<<2;for(let i=0;i<3;i++){let o=n.data[t+i]/255;o=Math.pow(o,0.45454545454545453/n.gamma),n.data[t+i]=Math.round(o*255)}}n.gamma=0}};Jn.prototype.adjustGamma=function(){Jn.adjustGamma(this)}});var Wi=pn((op,kh)=>{var Qi={to(n,r){if(!r)return`\x1B[${n+1}G`;return`\x1B[${r+1};${n+1}H`},move(n,r){let e="";if(n<0)e+=`\x1B[${-n}D`;else if(n>0)e+=`\x1B[${n}C`;if(r<0)e+=`\x1B[${-r}A`;else if(r>0)e+=`\x1B[${r}B`;return e},up:(n=1)=>`\x1B[${n}A`,down:(n=1)=>`\x1B[${n}B`,forward:(n=1)=>`\x1B[${n}C`,backward:(n=1)=>`\x1B[${n}D`,nextLine:(n=1)=>"\x1B[E".repeat(n),prevLine:(n=1)=>"\x1B[F".repeat(n),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},tm={up:(n=1)=>"\x1B[S".repeat(n),down:(n=1)=>"\x1B[T".repeat(n)},im={screen:"\x1B[2J",up:(n=1)=>"\x1B[1J".repeat(n),down:(n=1)=>"\x1B[J".repeat(n),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(n){let r="";for(let e=0;e<n;e++)r+=this.line+(e<n-1?Qi.up():"");if(n)r+=Qi.left;return r}};kh.exports={cursor:Qi,scroll:tm,erase:im,beep:"\x07"}});import{isMainThread as h0}from"node:worker_threads";import{parseArgs as s0}from"node:util";var rr={name:"@kecan0406/ttheme",version:"1.0.31",type:"module",bin:{ttheme:"bin/ttheme.js"},files:["bin","dist/manifest.json","dist/ghostty/ttheme.conf","shell","!shell/check.zsh","ghostty/shaders"],description:"Character terminal palettes for ghostty, kitty, alacritty, wezterm and iTerm2",license:"MIT",author:"kecan0406",repository:{type:"git",url:"git+https://github.com/kecan0406/ttheme.git"},homepage:"https://github.com/kecan0406/ttheme#readme",bugs:"https://github.com/kecan0406/ttheme/issues",keywords:["terminal","theme","ghostty","kitty","alacritty","wezterm","iterm2"],devDependencies:{"@biomejs/biome":"^2.3.0","@clack/core":"^1.4.3","@clack/prompts":"^1.7.0","@material/material-color-utilities":"^0.4.0","@types/bun":"^1.3.0","@types/pngjs":"6.0.5","jpeg-js":"^0.4.4",pngjs:"7.0.0",typescript:"^5.8.2"},engines:{bun:">=1.3",node:">=20.11"}};import{rmSync as nc}from"node:fs";import{basename as da,join as Oe}from"node:path";var jf=/^#[0-9a-f]{6}$/;function Mo(n){return jf.test(n)}function Gn(n){let r=Number.parseInt(n.slice(1),16);return[r>>16&255,r>>8&255,r&255]}function _n(n){let[r,e,t]=Gn(n).map((i)=>{let o=i/255;return o<=0.03928?o/12.92:((o+0.055)/1.055)**2.4});return 0.2126*r+0.7152*e+0.0722*t}function ur(n,r){let e=_n(n),t=_n(r);return(Math.max(e,t)+0.05)/(Math.min(e,t)+0.05)}function Ve(n,r){return Math.round(ur(n,r)*100)/100}var mr=7,Eo=3,Gt=0.15,vo=1.6,Fo=[1,2,3,4,5,6,9,10,11,12,13,14],yo=[7,15];function le(n,r){let e=n.ansi[r];if(e===void 0)throw Error(`${n.name}: missing ANSI ${r}`);return e}function Lt(n,r,e){let t=n.background;return r.flatMap((i)=>{let o=le(n,i);return ur(o,t)<e?[`ANSI ${i} ${o} on ${t} is ${Ve(o,t)}:1, needs ${e}:1`]:[]})}function Io(n,r){return Math.min(...r.map((e)=>ur(le(n,e),n.background)))}var ze=[{rule:"foreground",label:"foreground on background",unit:"ratio",min:mr,measure:({foreground:n,background:r})=>ur(n,r),check:({foreground:n,background:r})=>ur(n,r)<mr?[`foreground ${n} on ${r} is ${Ve(n,r)}:1, needs ${mr}:1`]:[]},{rule:"accents",label:"weakest accent on background",unit:"ratio",min:Eo,measure:(n)=>Io(n,Fo),check:(n)=>Lt(n,Fo,Eo)},{rule:"ansi0-dark",label:"ansi0 luminance",unit:"luminance",max:Gt,measure:(n)=>_n(le(n,0)),check:(n)=>{let r=le(n,0);return _n(r)>Gt?[`ANSI 0 ${r} has luminance ${_n(r).toFixed(3)}, needs <= ${Gt}`]:[]}},{rule:"light-ansi",label:"ansi7 and ansi15 on background",unit:"ratio",min:mr,measure:(n)=>Io(n,yo),check:(n)=>Lt(n,yo,mr)},{rule:"ansi8-visible",label:"ansi8 on background",unit:"ratio",min:vo,measure:(n)=>ur(le(n,8),n.background),check:(n)=>Lt(n,[8],vo)},{rule:"selection",label:"foreground on selection",unit:"ratio",min:mr,measure:({foreground:n,selectionBackground:r})=>r===void 0?Number.NaN:ur(n,r),check:({foreground:n,selectionBackground:r})=>r!==void 0&&ur(n,r)<mr?[`foreground ${n} on selection ${r} is ${Ve(n,r)}:1, needs ${mr}:1`]:[]}],m0=ze.map((n)=>n.rule),Ye=ze.map(({rule:n,label:r,unit:e,min:t,max:i})=>({rule:n,label:r,unit:e,...t===void 0?{}:{min:t},...i===void 0?{}:{max:i}}));function So(n){return ze.map((r)=>Math.round(r.measure(n)*1000)/1000)}function Jt(n){return ze.filter((r)=>!n.waive.includes(r.rule)).flatMap((r)=>r.check(n).map((e)=>({theme:n.name,rule:r.rule,detail:e})))}function No(n){return n.flatMap(Jt)}var Rf=["black","red","green","yellow","blue","magenta","cyan","white"];function Ho(n,r){return[n,...Rf.map((e,t)=>`${e} = '${r[t]}'`),""].join(`
3
+ `)}var ae={id:"alacritty",limits:"no shaders, no runtime color API (OSC only)",emit(n){let r=[...Pr(n),"","[colors.primary]",`background = '${n.background}'`,`foreground = '${n.foreground}'`,"","[colors.cursor]",`cursor = '${n.cursor}'`,`text = '${n.background}'`,"","[colors.selection]",`background = '${n.selectionBackground}'`,`text = '${n.foreground}'`,"",Ho("[colors.normal]",n.ansi.slice(0,8)),Ho("[colors.bright]",n.ansi.slice(8,16))].join(`
4
+ `),e=[`# ${n.name} — font settings.`,`# Pair with the palette: import = ["~/.config/alacritty/themes/${n.name}.toml"]`,"","[font]",`size = ${n.font.size}`,"","[font.normal]",`family = '${n.font.family}'`,""].join(`
5
+ `);return[{path:`alacritty/themes/${n.name}.toml`,content:r},{path:`alacritty/config/${n.name}.toml`,content:e}]}};import{isDeepStrictEqual as Gf}from"node:util";var de={id:"ghostty",emit(n){let r=[...Pr(n),`background = ${n.background}`,`foreground = ${n.foreground}`,`cursor-color = ${n.cursor}`,`selection-background = ${n.selectionBackground}`,`selection-foreground = ${n.foreground}`,...n.ansi.map((e,t)=>`palette = ${t}=${e}`),"palette-generate = true","","macos-icon = custom-style",`macos-icon-ghost-color = ${n.ghostty.iconGhost}`,`macos-icon-screen-color = ${n.ghostty.iconScreen.join(",")}`,"macos-icon-frame = chrome",""].join(`
6
+ `);return[{path:`ghostty/themes/${n.name}`,content:r}]},emitShared(n){let[r]=n;if(!r)return[];for(let t of n)if(!Gf(t.font,r.font)||t.ghostty.shader!==r.ghostty.shader)throw Error(`${t.name}: per-theme font/shader overrides cannot be expressed in the shared ghostty/ttheme.conf`);return[{path:"ghostty/ttheme.conf",content:["# ttheme — shared font and shader, identical for every palette.","# Pick colors with: theme = <palette>",`font-family = ${r.font.family}`,`font-size = ${r.font.size}`,...r.font.codepointMap.map((t)=>`font-codepoint-map = ${t.range}=${t.family}`),...r.ghostty.shader?["",`custom-shader = ~/.config/ghostty/shaders/${r.ghostty.shader}`,"custom-shader-animation = true"]:[],""].join(`
7
+ `)}]}};function $r(n){let[r,e,t]=Gn(n);return{"Alpha Component":1,"Blue Component":t/255,"Color Space":"P3","Green Component":e/255,"Red Component":r/255}}function Oo(n){return{...Object.fromEntries(n.ansi.map((r,e)=>[`Ansi ${e} Color`,$r(r)])),"Background Color":$r(n.background),"Bold Color":$r(n.foreground),"Cursor Color":$r(n.cursor),"Cursor Text Color":$r(n.background),"Foreground Color":$r(n.foreground),"Selected Text Color":$r(n.foreground),"Selection Color":$r(n.selectionBackground)}}function Lf(n){return n?{"Background Image Location":n.image,"Background Image Mode":n.cover?2:3,Blend:n.opacity}:{"Background Image Location":""}}function jo(n,r,e,t){let i=(s,u)=>({Name:`ttheme · ${u}`,Guid:`ttheme-${u}`,...t?{"Dynamic Profile Parent GUID":t}:{},"Use Separate Colors for Light and Dark Mode":!1,"Harmonize 256 Colors":!0,...Lf(r.get(s.name)),...Oo(s)}),o=[...e?[i(e,"default")]:[],...n.map((s)=>i(s,s.name))];return`${JSON.stringify({Profiles:o},null,2)}
8
+ `}function Jf(n,r){return[` <key>${n}</key>`,"\t<dict>",...Object.entries(r).flatMap(([e,t])=>[` <key>${e}</key>`,typeof t==="string"?` <string>${t}</string>`:` <real>${t}</real>`]),"\t</dict>"].join(`
9
+ `)}var me={id:"iterm2",limits:"colors only — font lives in the profile; colors are Display P3, the space iTerm2 reads OSC colors in",emit(n){let r=['<?xml version="1.0" encoding="UTF-8"?>','<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">','<plist version="1.0">',"<dict>",...Object.entries(Oo(n)).map(([e,t])=>Jf(e,t)),"</dict>","</plist>",""].join(`
10
+ `);return[{path:`iterm2/${n.name}.itermcolors`,content:r}]}};var $e={id:"kitty",limits:"no GLSL shaders, no per-codepoint font mapping",emit(n){let r=[...Pr(n),`background ${n.background}`,`foreground ${n.foreground}`,`cursor ${n.cursor}`,`cursor_text_color ${n.background}`,`selection_background ${n.selectionBackground}`,`selection_foreground ${n.foreground}`,...n.ansi.map((t,i)=>`color${i} ${t}`),""].join(`
11
+ `),e=[`# ${n.name} — font settings.`,`# Pair with the palette: include themes/${n.name}.conf`,`font_family ${n.font.family}`,`font_size ${n.font.size}`,""].join(`
12
+ `);return[{path:`kitty/themes/${n.name}.conf`,content:r},{path:`kitty/config/${n.name}.conf`,content:e}]}};import{createHash as el}from"node:crypto";import{mkdirSync as qs,readdirSync as Ir,readFileSync as As,renameSync as Xs,rmSync as qr,statSync as tl,utimesSync as il,writeFileSync as xe}from"node:fs";import{isAbsolute as ol,join as Fn}from"node:path";var Gs=Te(Uo(),1),_e=Te(Os(),1),js=[137,80,78,71,13,10,26,10],Ls=13;function Js(n){return n.length>=js.length&&js.every((r,e)=>n[e]===r)}function nl(n){let r=_e.PNG.sync.read(Buffer.from(n));return{width:r.width,height:r.height,data:new Uint8Array(r.data)}}function Ks(n,r){if(Js(n)){let e=Bt(n);if(e&&e.width*e.height>r)throw Error(`${e.width}×${e.height} is over ${r/1e6} megapixels`);return nl(n)}if(n[0]===255&&n[1]===216){let e=Gs.decode(n,{useTArray:!0,formatAsRGBA:!0,maxResolutionInMP:r/1e6,maxMemoryUsageInMB:1024});return{width:e.width,height:e.height,data:e.data}}throw Error("not a PNG or JPEG image")}function Zr(n){let r=new _e.PNG({width:n.width,height:n.height});return r.data=Buffer.from(n.data),_e.PNG.sync.write(r)}function Rs(n,r){for(let e=0;e+r.length<=n.length;e++){let t=!0;for(let i=0;i<r.length&&t;i++)t=n[e+i]===r.charCodeAt(i);if(t)return e}return-1}function Bt(n){if(n.length<33||!Js(n))return null;let r=new DataView(n.buffer,n.byteOffset,n.byteLength),e=r.getUint32(16),t=r.getUint32(20);if(n[25]===4||n[25]===6)return{width:e,height:t,alpha:!0};let i=Rs(n,"IDAT");return{width:e,height:t,alpha:Rs(i===-1?n:n.subarray(0,i),"tRNS")!==-1}}function Ps(n,r=Ls){let{width:e,height:t}=n,i=-1,o=-1;for(let s=0;s<n.height;s++)for(let u=0;u<n.width;u++)if((n.data[(s*n.width+u)*4+3]??0)>=r)e=Math.min(e,u),i=Math.max(i,u),t=Math.min(t,s),o=Math.max(o,s);return i<0?null:{x:e,y:t,w:i-e+1,h:o-t+1}}function pe(n,r={x:0,y:0,w:n.width,h:n.height}){let e=0;for(let t=r.y;t<r.y+r.h;t++)for(let i=r.x;i<r.x+r.w;i++)if((n.data[(t*n.width+i)*4+3]??0)<Ls)e++;return Math.round(e*100/(r.w*r.h))}function rl(n,r){if(r<=1)return n;let e=Math.max(1,Math.floor(n.width/r)),t=Math.max(1,Math.floor(n.height/r)),i=new Uint8Array(e*t*4),o=n.data;for(let s=0;s<t;s++)for(let u=0;u<e;u++){let c=0,h=0,f=0,l=0;for(let d=0;d<r;d++)for(let w=0;w<r;w++){let m=((s*r+d)*n.width+u*r+w)*4,b=o[m+3]??0;c+=(o[m]??0)*b,h+=(o[m+1]??0)*b,f+=(o[m+2]??0)*b,l+=b}let g=(s*e+u)*4;if(l>0)i[g]=Math.round(c/l),i[g+1]=Math.round(h/l),i[g+2]=Math.round(f/l);i[g+3]=Math.round(l/(r*r))}return{width:e,height:t,data:i}}function Us(n,r,e){let t=Math.min(r/n.width,e/n.height),i=Math.max(1,Math.round(n.width*t)),o=Math.max(1,Math.round(n.height*t)),s=Be(n,{x:0,y:0,w:n.width,h:n.height},i,o),u=new Uint8Array(r*e*4),c=Math.floor((r-i)/2),h=Math.floor((e-o)/2);for(let f=0;f<o;f++)u.set(s.data.subarray(f*i*4,(f+1)*i*4),((h+f)*r+c)*4);return{width:r,height:e,data:u}}function Be(n,r,e,t){let i=Math.max(1,Math.floor(Math.min(r.w/e,r.h/t))),o=rl(n,i),s=o.data,u=new Uint8Array(e*t*4);for(let c=0;c<t;c++){let h=Math.min(o.height-1,Math.max(0,r.y/i+(c+0.5)*r.h/i/t-0.5)),f=Math.floor(h),l=Math.min(o.height-1,f+1),g=h-f;for(let d=0;d<e;d++){let w=Math.min(o.width-1,Math.max(0,r.x/i+(d+0.5)*r.w/i/e-0.5)),m=Math.floor(w),b=Math.min(o.width-1,m+1),F=w-m,S=(f*o.width+m)*4,k=(f*o.width+b)*4,y=(l*o.width+m)*4,p=(l*o.width+b)*4,R=(s[S+3]??0)*(1-F)*(1-g),M=(s[k+3]??0)*F*(1-g),j=(s[y+3]??0)*(1-F)*g,H=(s[p+3]??0)*F*g,J=R+M+j+H,G=(c*e+d)*4;if(J>0)for(let z=0;z<3;z++){let U=(s[S+z]??0)*R+(s[k+z]??0)*M+(s[y+z]??0)*j+(s[p+z]??0)*H;u[G+z]=Math.round(U/J)}u[G+3]=Math.round(J)}}return{width:e,height:t,data:u}}var Qs={width:2560,height:1550},sl=2560,ul=0.1,cr={tall:1.15,reach:0.4,widest:0.95,headroom:0.04,margin:0.03,stands:12},cl=_n(xt("#19161e","#9b86c8",0.2)),hl="shelf";function xt(n,r,e){let t=Gn(n),i=Gn(r);return`#${t.map((o,s)=>Math.round(o+((i[s]??0)-o)*e).toString(16).padStart(2,"0")).join("")}`}function fl(n,r){if(r==="background"||r==="foreground"||r==="cursor")return n[r];if(r==="selection"&&n.selection)return n.selection;let e=/^ansi(\d|1[0-5])$/.exec(r),t=e?n.ansi[Number(e[1])]:void 0;if(!t)throw Error(`${n.name} has no slot ${r}`);return t}function Ws(n){if(n(1))return 1;let r=0,e=1;for(let t=0;t<40;t++){let i=(r+e)/2;if(n(i))r=i;else e=i}return r}function Zs(n,r){let e=fl(n,r),i=Ws((h)=>Jt({name:n.name,background:xt(n.background,e,h),foreground:n.foreground,ansi:n.ansi,waive:n.waived??[]}).length===0),o=Ws((h)=>_n(xt(n.background,e,h))<=cl),s=Math.floor(Math.min(i,o)*1000)/1000,u=Gn(n.background),c=Math.hypot(...Gn(e).map((h,f)=>(h-(u[f]??0))*s));return{slot:r,color:e,cap:i,matched:o,opacity:s,reach:c}}function De(n,r){let e=Zs(n,"cursor");if(e.opacity>=ul)return e;return r.filter((t)=>t!=="cursor"&&t!=="background").map((t)=>Zs(n,t)).reduce((t,i)=>i.reach>t.reach?i:t,e)}function Dt(n,r,e){let t=Gn(r),i=Gn(e),o=n.data;for(let s=0;s<o.length;s+=4){let u=(0.299*(o[s]??0)+0.587*(o[s+1]??0)+0.114*(o[s+2]??0))/255;for(let c=0;c<3;c++)o[s+c]=Math.round((t[c]??0)+((i[c]??0)-(t[c]??0))*u)}return n}function gl(n,r,e){let t=Gn(r),i=n.data,o=new Uint8Array(i.length);for(let s=0;s<i.length;s+=4){let u=(i[s+3]??0)/255*e;for(let c=0;c<3;c++)o[s+c]=Math.round((t[c]??0)*(1-u)+(i[s+c]??0)*u);o[s+3]=255}return{width:n.width,height:n.height,data:o}}function Ts(n){return Ps(n)??{x:0,y:0,w:n.width,h:n.height}}function ll(n,r){if(n<=0||r<=0)return Qs;let e=Math.min(1,Qs.width/Math.max(n,r));return{width:Math.round(n*e),height:Math.round(r*e)}}function al(n,r){let e=Math.min(1,sl/Math.max(r.w,r.h));return Be(n,r,Math.round(r.w*e),Math.round(r.h*e))}function Vs(n,r,e,t){if(t<cr.stands){let c=n.w*e>n.h*r?{x:n.x+(n.w-n.h*r/e)/2,y:n.y,w:n.h*r/e,h:n.h}:{x:n.x,y:n.y,w:n.w,h:n.w*e/r};return{crop:c,at:{x:0,y:0,w:r,h:e},focus:(c.y-n.y+c.h/2)/n.h}}let i=Math.max(cr.tall*e,cr.reach*r*n.h/n.w),o=i*n.w/n.h;if(o>cr.widest*r)o=cr.widest*r,i=o*n.h/n.w;let s=cr.headroom*e,u=Math.min(1,(e-s)/i);return{crop:{x:n.x,y:n.y,w:n.w,h:n.h*u},at:{x:r*(1-cr.margin)-o,y:s,w:o,h:i*u},focus:Math.min(1,(e/2-s)/i)}}function zs(n,r,e,t){let i=Math.max(1,Math.round(r.at.w)),o=Math.max(1,Math.round(r.at.h)),s=Be(n,r.crop,i,o),u=new Uint8Array(e*t*4),c=Math.round(r.at.x),h=Math.round(r.at.y);for(let f=0;f<o;f++){let l=h+f,g=Math.max(0,-c),d=Math.min(i,e-c);if(l<0||l>=t||d<=g)continue;u.set(s.data.subarray((f*i+g)*4,(f*i+d)*4),(l*e+c+g)*4)}return{width:e,height:t,data:u}}function Ys(n,r,e,t,i){let o=Ts(n),s=zs(n,Vs(o,t,i,pe(n,o)),t,i);return gl(Dt(s,r.background,e.color),r.background,e.opacity)}function Sr(n){return Fn(n,"ttheme","backgrounds")}function dl(n,r,e,t,i){return[...t?[`# from ${t}`]:[],...i?[`# image ${i}`]:[],`background-image = ${r}`,"background-image-fit = cover","background-image-position = top-right",`background-image-opacity = ${e}`,`config-file = ?${n}.tune.conf`,`config-file = ?${n}.off.conf`,""].join(`
13
+ `)}function Cs(n,r,e){let t=new Map;for(let s of[`${r}.conf`,`${r}.tune.conf`,`${r}.off.conf`]){let u;try{u=As(Fn(n,s),"utf8")}catch{if(s===`${r}.conf`)return;continue}for(let c of u.split(`
14
+ `)){let h=/^(background-image(?:-fit|-opacity)?)\s*=\s*(.*?)\s*$/.exec(c);if(h)t.set(h[1],h[2])}}let i=t.get("background-image")??"";if(i==="")return;let o=Number(t.get("background-image-opacity")??1);return{image:i.startsWith("~/")?Fn(e,i.slice(2)):ol(i)?i:Fn(n,i),opacity:Number.isFinite(o)?o:1,cover:t.get("background-image-fit")==="cover"}}function ml(n,r){for(let e of Ir(n))if(ni(e,r))qr(Fn(n,e))}function $l(n){return`${n.site}_${n.id}`}function nt(n,r){return Fn(n,hl,r)}function ni(n,r){let e=n.slice(r.length);return n.startsWith(r)&&(e===".conf"||e===".tune.conf"||e===".off.conf"||/^(\.[0-9a-f]{8})?(@[a-z0-9-]+)?\.png$/.test(e))}function be(n,r){try{return/^# image (\S+)$/m.exec(As(Fn(n,`${r}.conf`),"utf8"))?.[1]}catch{return}}function wl(n,r){try{return Ir(nt(n,r))}catch{return[]}}function _s(n,r){let e=be(n,r);return[...e?[e]:[],...wl(n,r)].sort()}function Bs(n,r){let e=be(n,r);if(!e)return;let t=Fn(nt(n,r),e);qr(t,{recursive:!0,force:!0}),qs(t,{recursive:!0});for(let i of Ir(n))if(ni(i,r))Xs(Fn(n,i),Fn(t,i.slice(r.length)))}function xs(n,r,e){let t=Fn(nt(n,r),e);for(let i of Ir(t))Xs(Fn(t,i),Fn(n,`${r}${i}`));qr(t,{recursive:!0})}function Ds(n,r,e){try{return Ir(Fn(n,"originals")).find((t)=>t.startsWith(`${r}-${e}.`))}catch{return}}function nu(n,r,e){let t=Ds(n,r,e);if(t){let i=new Date;il(Fn(n,"originals",t),i,i)}}function ru(n,r,e){let t=Sr(n),i=_s(t,r),o=be(t,r);if(!o||i.length<2)throw Error(`${r} has no other image`);let s=(i.indexOf(o)+e+i.length)%i.length,u=i[s];return Bs(t,r),xs(t,r,u),nu(t,r,u),{key:u,at:s+1,of:i.length}}function eu(n,r){let e=Sr(n),t=Ir(e).filter((h)=>ni(h,r));if(t.length===0)throw Error(`${r} has no image`);let i=_s(e,r),o=be(e,r),s=o&&Ds(e,r,o);if(s)qr(Fn(e,"originals",s));for(let h of t)qr(Fn(e,h));let u=i.filter((h)=>h!==o),c=u[(o?i.indexOf(o):0)%u.length];if(c)xs(e,r,c),nu(e,r,c);return{key:o,left:u.length}}function pl(n,r,e){if(be(n,r)!==e)Bs(n,r);if(e)qr(Fn(nt(n,r),e),{recursive:!0,force:!0});ml(n,r)}function tu(n,r,e,t,i,o){let s=Sr(n),u=r.name,c=$l(i);qs(Fn(s,"originals"),{recursive:!0}),pl(s,u,c);let h=Ts(t),{width:f,height:l}=ll(o.width,o.height),g=Vs(h,f,l,pe(t,h)),d=Zr(Dt(al(t,h),r.background,e.color)),w=Zr(Dt(zs(t,g,f,l),r.background,e.color)),m=Fn(s,`${u}.${el("sha1").update(d).update(w).digest("hex").slice(0,8)}`),b=`${m}.png`,F=`${m}@fill-${Math.round(g.focus*100)}.png`,S=Fn(s,`${u}.conf`),k=Fn(s,"originals",`${u}-${i.site}_${i.id}.${i.ext}`);return xe(b,d),xe(F,w),xe(S,dl(u,F,e.opacity,i.from,c)),xe(k,i.bytes),[b,F,S,k]}function iu(n){let r=Fn(Sr(n),"originals"),e=new Map,t;try{t=Ir(r)}catch{return new Map}for(let i of t){let o=/^(.+)-([a-z.]+)_(\d+)\.[a-z]+$/.exec(i),[,s,u,c]=o??[];if(!s||!u||!c)continue;let h=tl(Fn(r,i)).mtimeMs,f=e.get(s);if(!f||h>f.at)e.set(s,{site:u,id:Number(c),at:h})}return new Map([...e].map(([i,{site:o,id:s}])=>[i,{site:o,id:s}]))}function ri(n){let{slot:r,color:e,opacity:t}=De({name:n.name,background:n.background,foreground:n.foreground,cursor:n.cursor,selection:n.selectionBackground,ansi:n.ansi,waived:n.waive},n.signatureSlots);return{name:n.name,group:n.group,...n.native?{native:n.native}:{},...n.lead?{lead:!0}:{},order:n.order,ansiSource:n.ansiSource,...n.booru?{booru:n.booru}:{},...n.booruSites?{booruSites:n.booruSites}:{},...n.role==="default"?{default:!0}:{},background:n.background,foreground:n.foreground,cursor:n.cursor,selection:n.selectionBackground,signature:n.signature,signatureSlots:n.signatureSlots,ansi:n.ansi,gate:So(n),...n.waive.length>0?{waived:n.waive}:{},backdrop:{slot:r,color:e,opacity:t}}}function Ar(n){return n.filter((r)=>r.default!==!0)}function bl(n){let[r]=n;if(!r)throw Error("manifest needs at least one theme");return{version:rr.version,gate:Ye,placement:cr,font:r.font,...r.ghostty.shader?{shader:r.ghostty.shader}:{},palettes:n.map(ri)}}var ei={id:"meta",emitShared(n){return[{path:"manifest.json",content:`${JSON.stringify(bl(n),null,2)}
15
+ `}]}};import{readdirSync as xl,readFileSync as ci}from"node:fs";import{basename as Dl,join as hi}from"node:path";import{readdirSync as kl,rmSync as Ml,statSync as El}from"node:fs";import{setDefaultAutoSelectFamilyAttemptTimeout as vl}from"node:net";import{homedir as Fl}from"node:os";import{join as Me}from"node:path";import{setTimeout as yl}from"node:timers/promises";var Nr=100,ii=25000000,Il=536870912,Ee=["safe","questionable","explicit"],Hr=["nudity","underwear"],Sl={nudity:new Set(["nude","naked","topless","bottomless","nipples","naked_towel","undressing"]),underwear:new Set(["underwear","panties","pantsu","bra","lingerie","pantyshot"])},ke={safe:"s",questionable:"q",explicit:"e"},Nl=8191,Hl=20000,Ol=5000,ou=3000,su=8,jl=3000,fu=60000,uu=3,Rl=`ttheme/${rr.version} (+${rr.homepage})`,Gl=["orig","tile","thumb","cut"],gu=new Map,Ll=Xl(process.env.TTHEME_FIND_HOSTS),Jl=Al(process.env.TTHEME_FIND_CUTOUTS);vl(jl);function cu(n){try{return kl(n)}catch{return[]}}function rt(n){return n.startsWith("//")?`https:${n}`:n}function ve(n){return(/\.([a-z0-9]+)(?:\?.*)?$/i.exec(n)?.[1]??"").toLowerCase()}function Fe(n){let r=n.trim();if(!r)return[];let e=JSON.parse(r);if(Array.isArray(e))return e;let t=e.posts;return Array.isArray(t)?t:[]}function Kl(n){let r=n.trim(),t=(r?JSON.parse(r):{}).tags??{};return new Map(Object.entries(t).map(([i,o])=>[i,String(o)]))}function ti(n,r,e){let t=rt(String(n??""));return{file:t,width:Number(r)||0,height:Number(e)||0,ext:ve(t)}}function lu(n,r){let e=rt(String(r.preview??""));if(!r.file||!e||!Number(n.id))return[];let t=Number(n.width??n.image_width)||0,i=Number(n.height??n.image_height)||0;return[{id:Number(n.id),width:t,height:i,file:r.file,preview:e,ext:r.ext,owner:String(r.owner??""),artist:r.artist,score:Number(n.score)||0,rating:String(n.rating??""),md5:String(r.md5??""),source:String(n.source??""),tags:r.tags.split(/\s+/).filter(Boolean),solo:r.solo,family:Number(n.parent_id)||(n.has_children===!0?Number(n.id):0),smaller:r.versions.filter((o)=>o.file&&o.width>0&&o.height>0&&o.width*o.height<t*i)}]}function Pl(n){let r=Kl(n);return Fe(n).flatMap((e)=>{let t=rt(String(e.file_url??"")),i=String(e.tags??"");return lu(e,{preview:e.preview_url,file:t,ext:String(e.file_ext||ve(t)).toLowerCase(),owner:e.author,artist:i.split(/\s+/).find((o)=>r.get(o)==="artist")??"",md5:e.md5,tags:i,solo:void 0,versions:[ti(e.jpeg_url,e.jpeg_width,e.jpeg_height),ti(e.sample_url,e.sample_width,e.sample_height)]})})}function Ul(n){return Fe(n).flatMap((r)=>{let e=rt(String(r.file_url??"")),t=String(r.tag_string??""),i=r.media_asset??{};return lu(r,{preview:i.variants?.find((o)=>o.type==="360x360")?.url??r.preview_file_url,file:e,ext:String(r.file_ext||ve(e)).toLowerCase(),owner:"",artist:String(r.tag_string_artist??"").split(/\s+/)[0]??"",md5:r.md5,tags:t,solo:t.split(/\s+/).includes("solo"),versions:(i.variants??[]).map((o)=>ti(o.url,o.width,o.height)).filter((o)=>o.ext==="jpg"||o.ext==="png").sort((o,s)=>s.width*s.height-o.width*o.height)})})}function Ql(n){return Fe(n).flatMap((r)=>{let e=String(r.value??"");return e?[{value:e,count:Number(r.post_count)||0}]:[]})}function Wl(n){return Fe(n).flatMap((r)=>{let e=String(r.name??"");return e?[{value:e,count:Number(r.count)||0}]:[]})}function Zl(n){return Number(/count="(\d+)"/.exec(n)?.[1]??0)}function ql(n){let r=n.trim()?JSON.parse(n):{};return Number(r.counts?.posts)||0}function Al(n){let r=new Map;for(let e of(n??"").split(/\s+/).filter(Boolean)){let t=e.indexOf("=");if(t>0)r.set(e.slice(0,t),e.slice(t+1).split(",").filter(Boolean))}return r}function Xl(n){let r=new Map;for(let e of(n??"").split(/[\s,]+/).filter(Boolean)){let t=e.indexOf("="),i=e.slice(0,t);try{let o=new URL(e.slice(t+1));if(i&&o.protocol==="https:")r.set(i,o.origin)}catch{}}return r}function au(n,r,e,t){let i=(n??"").split(/\s+/);if(t!==void 0&&i.includes(t))return[];let o=r.filter((s)=>i.includes(s));return o.length>0?o:[...e]}function et(n){return au(n,Ee,["safe"])}function tt(n){return au(n,Hr,Hr,"none")}function du(n,r,e){return{safe:new Set(n),questionable:new Set(r),explicit:new Set(e)}}function mu(n){let r=Ll.get(n.key),e=Jl.get(n.key);return{...n,origin:r??n.origin,moved:r!==void 0&&r!==n.origin,cutouts:e??n.cutouts,vouched:n.vouched&&e===void 0}}function $u(n){return n.length<2?n.join(""):n.map((r)=>`~${r}`).join(" ")}function hu(n){let r=mu(n),e=(t)=>new URLSearchParams({api_version:"2",include_tags:"1",...t});return{...r,cutouts:$u(r.cutouts),ratings:du([ke.safe],[ke.questionable],[ke.explicit]),rate:(t)=>{let[i]=t;if(t.length===1&&i)return`rating:${ke[i]}`;let o=Ee.filter((u)=>!t.includes(u)),[s]=o;return o.length===1&&s?`-rating:${ke[s]}`:""},best:"order:score",tagBudget:Number.POSITIVE_INFINITY,postsUrl:(t,i)=>`${r.origin}/post.json?${e({limit:String(Nr),page:String(i+1),tags:t})}`,countUrl:(t)=>`${r.origin}/post.xml?${new URLSearchParams({limit:"1",tags:t})}`,postUrl:(t)=>`${r.origin}/post.json?${e({tags:`id:${t}`})}`,pageUrl:(t)=>`${r.origin}/post/show/${t}`,parse:Pl,count:Zl}}function Tl(n){let r=mu(n),e=du(["g"],["s","q"],["e"]);return{...r,cutouts:$u(r.cutouts),ratings:e,rate:(t)=>t.length===Ee.length?"":`rating:${t.flatMap((i)=>[...e[i]]).join(",")}`,best:"order:score",tagBudget:2,postsUrl:(t,i)=>`${r.origin}/posts.json?${new URLSearchParams({limit:String(Nr),page:String(i+1),tags:t})}`,countUrl:(t)=>`${r.origin}/counts/posts.json?${new URLSearchParams({tags:t})}`,postUrl:(t)=>`${r.origin}/posts.json?${new URLSearchParams({limit:"1",tags:`id:${t}`})}`,pageUrl:(t)=>`${r.origin}/posts/${t}`,parse:Ul,count:ql}}function Vl(n){return Mn.find((r)=>r.key===n||r.name===n||new URL(r.origin).host===n)}function oi(n){return n.split(/\s+/).filter((r)=>r&&!r.startsWith("rating:")).length}function wu(n,r){let e=n.trim();if(/^\d+$/.test(e))return{site:r,id:Number(e)};let t=/^([\w.]+):(\d+)$/.exec(e);if(t){let u=Mn.find((c)=>c.key===t[1]||c.name===t[1]);return u&&{site:u,id:Number(t[2])}}let i;try{i=new URL(e)}catch{return}let o=Vl(i.host),s=Number(i.searchParams.get("id")??i.pathname.split("/").filter(Boolean).at(-1));return o&&s>0?{site:o,id:s}:void 0}var Mn=[Tl({key:"danbooru",name:"danbooru",origin:"https://danbooru.donmai.us",cutouts:["transparent_background"],vouched:!1,tunneled:!0,ansi:2}),hu({key:"konachan",name:"konachan",origin:"https://konachan.net",cutouts:["transparent","vector"],vouched:!1,tunneled:!1,ansi:6}),hu({key:"yande",name:"yande.re",origin:"https://yande.re",cutouts:["transparent_png"],vouched:!0,tunneled:!1,ansi:5})],Or=134217728;function tr(n,r){return Mn.indexOf(n)*Or+r}function si(n){let r;try{r=new URL(n).hostname}catch{return""}return r.split(".").slice(-2).join(".")}function pu(){return Mn.filter((n)=>!n.tunneled).map((n)=>si(n.origin)).flatMap((n)=>[n,`.${n}`]).join(",")}function bu(n,r=Hr){return n.tags.filter((e)=>r.some((t)=>Sl[t].has(e)))}function ku(n,r,e=["safe"]){return e.some((t)=>n.ratings[t].has(r.rating))}function ye(n){return[n,...n.smaller].find((r)=>r.width*r.height<=ii)}function Mu(n){let r=new Map;for(let[e,t]of[...n].sort(([i],[o])=>i<o?-1:1)){if(t==="")continue;r.set(t,[...r.get(t)??[],e])}return r}function Eu(){return Me(process.env.XDG_CACHE_HOME??Me(Fl(),".cache"),"ttheme")}function Mr(n){return Me(Eu(),n.key)}function vu(n=Il,r=Eu()){let e=[],t=0;for(let i of cu(r))for(let o of Gl){let s=Me(r,i,o);for(let u of cu(s)){let c=Me(s,u);try{let{size:h,mtimeMs:f}=El(c);e.push({path:c,size:h,at:f}),t+=h}catch{}}}e.sort((i,o)=>i.at-o.at);for(let i of e){if(t<=n)return;try{Ml(i.path,{force:!0}),t-=i.size}catch{}}}function zl(n,r){if(n!==null&&/^\s*\d+\s*$/.test(n))return Number(n)*1000;let e=n===null?Number.NaN:Date.parse(n);return Number.isNaN(e)?fu:Math.max(0,e-r)}function br(n){return gu.get(n.key)??0}function Yl(n){for(let r=n;r instanceof Error;r=r.cause)if(r.code==="ECONNRESET")return!0;return!1}function Cl(n){return(n.headers.get("server")??"").startsWith("cloudflare")&&n.headers.get("cf-mitigated")==="challenge"}async function kr(n,r,e,t={},i=Hl){for(let o=1;;o++){let s=br(n)-Date.now();if(s>0)await yl(s,void 0,{signal:e});let u;try{u=await fetch(r,{headers:{"User-Agent":Rl,Referer:`${n.origin}/`,...t},signal:i?AbortSignal.any([e,AbortSignal.timeout(i)]):e})}catch(c){if(o<uu&&!e.aborted&&Yl(c))continue;throw c}if(u.status===429&&o<uu){await u.body?.cancel();let c=zl(u.headers.get("retry-after"),Date.now());if(c>fu)throw Error(`${n.name} asks to wait ${Math.ceil(c/1000)}s`);gu.set(n.key,Math.max(br(n),Date.now()+c));continue}if(!u.ok)throw await u.body?.cancel(),Error(Cl(u)?`${n.name} is behind a Cloudflare challenge`:`${n.name} answered ${u.status}`);return u}}async function Fu(n,r,e,t){return n.parse(await(await kr(n,n.postsUrl(r,e),t)).text())}async function yu(n,r,e){return n.count(await(await kr(n,n.countUrl(r),e)).text())}async function ui(n,r,e){let[t]=n.parse(await(await kr(n,n.postUrl(r),e)).text());return t}function _l(n){let r=Mn.find((t)=>t.key==="danbooru"),e=new URLSearchParams({limit:String(2*Nr),only:"md5,tag_string",tags:`md5:${n.join(",")}`});return`${r.origin}/posts.json?${e}`}function Bl(n){return new Map(Fe(n).flatMap((r)=>{let e=String(r.md5??"");return e?[[e,String(r.tag_string??"").split(/\s+/).filter(Boolean)]]:[]}))}function Iu(n,r){for(let e of n){let t=r.get(e.md5);if(t)e.tags=[...new Set([...e.tags,...t])],e.solo=t.includes("solo")}}async function Su(n,r){let e=Mn.find((i)=>i.key==="danbooru"),t=new Map;if(br(e)>Date.now())return t;for(let i=0;i<n.length;i+=Nr){let o=await(await kr(e,_l(n.slice(i,i+Nr)),r,{},Ol)).text();for(let[s,u]of Bl(o))t.set(s,u)}return t}async function Nu(n,r){let e=Mn.find((o)=>o.key==="danbooru");if(br(e)<=Date.now())try{let o=new URLSearchParams({"search[query]":n,"search[type]":"tag_query",limit:String(su)}),s=`${e.origin}/autocomplete.json?${o}`;return Ql(await(await kr(e,s,r,{},ou)).text())}catch(o){if(r.aborted)throw o}let t=Mn.find((o)=>o.key==="yande"),i=new URLSearchParams({name:n,order:"count",limit:String(su)});return Wl(await(await kr(t,`${t.origin}/tag.json?${i}`,r,{},ou)).text())}async function Hu(n,r,e){let t=await kr(n,r,e,{Range:`bytes=0-${Nl}`});return Bt(new Uint8Array(await t.arrayBuffer()))}async function Ou(n,r,e,t){let i=await kr(n,r,e,{},0),o=Number(i.headers.get("content-length"))||0,s=i.body?.getReader();if(!s)return new Uint8Array(await i.arrayBuffer());let u=[],c=0;for(;;){let{done:l,value:g}=await s.read();if(l)break;u.push(g),c+=g.length,t?.(c,o)}let h=new Uint8Array(c),f=0;for(let l of u)h.set(l,f),f+=l.length;return h}var na="_defaults.toml",hr="_groups.toml",ju=3,Ru=["background","foreground","cursor","selection"],ra=new Set(["next","help","preview","pin","unpin","config"]);function yn(n,r){throw Error(`${n}: ${r}`)}function jr(n,r,e){if(typeof e!=="string"||!Mo(e))yn(n,`${r} must be "#rrggbb" (lowercase), got ${JSON.stringify(e)}`);return e}function Vn(n,r,e){if(typeof e!=="string"||e.length===0)yn(n,`${r} must be a non-empty string`);return e}function fr(n){return n&&typeof n==="object"?n:{}}function ea(n,r,e){let t={...fr(e),...fr(r)},i=t.codepoint_map??[];if(!Array.isArray(i))yn(n,"font.codepoint_map must be an array");return{family:Vn(n,"font.family",t.family),size:Number(t.size),codepointMap:i.map((o)=>{let s=fr(o);return{range:Vn(n,"font.codepoint_map[].range",s.range),family:Vn(n,"font.codepoint_map[].family",s.family)}})}}function ta(n,r,e){if(r===void 0)return[e.cursor,e.selectionBackground,e.background];let t=Array.isArray(r)?r:[r];if(t.length===0)yn(n,"ghostty.icon_screen must not be empty");return t.map((i,o)=>jr(n,`ghostty.icon_screen[${o}]`,i))}function ia(n,r,e,t){let i={...fr(e),...fr(r)};return{shader:i.shader===void 0?void 0:Vn(n,"ghostty.shader",i.shader),iconGhost:i.icon_ghost===void 0?t.cursor:jr(n,"ghostty.icon_ghost",i.icon_ghost),iconScreen:ta(n,i.icon_screen,t)}}function oa(n){return new Map([...Ru.map((r)=>[r,n[r]]),...n.ansi.map((r,e)=>[`ansi${e}`,r])])}function sa(n,r,e){if(!Array.isArray(r)||r.length!==ju)yn(n,`meta.signature must name exactly ${ju} palette slots`);let t=oa(e),i=[],o=[];for(let[s,u]of r.entries()){let c=`meta.signature[${s}]`,h=Vn(n,c,u),f=t.get(h);if(f===void 0)yn(n,`${c} ${JSON.stringify(u)} is not a palette slot — use ${Ru.join(", ")} or ansi0-ansi15`);i.push(h),o.push(f)}if(new Set(o).size!==o.length)yn(n,"meta.signature slots must resolve to three different colors");return{names:i,colors:o}}function ua(n,r,e){if(r===void 0)return;if(!e)yn(n,"meta.booru_sites renames meta.booru per site, so it needs meta.booru");if(!r||typeof r!=="object"||Array.isArray(r))yn(n,'meta.booru_sites must be a table of site = "tag" or site = ["tag", ...]');let t={};for(let[i,o]of Object.entries(r)){let s=Mn.find((c)=>c.key===i);if(!s)yn(n,`meta.booru_sites.${i} is not a find site — use ${Mn.map((c)=>c.key).join(", ")}`);let u=typeof o==="string"?[o]:Array.isArray(o)?o:void 0;if(!u||u.some((c)=>typeof c!=="string"||c===""||/\s/.test(c)))yn(n,`meta.booru_sites.${i} must be one tag or a list of tags, got ${JSON.stringify(o)}`);if(u.length>1&&Number.isFinite(s.tagBudget))yn(n,`meta.booru_sites.${i} takes one tag — ${s.name} searches ${s.tagBudget} tags at a time`);t[i]=u}return t}function ca(n){let e=Bun.TOML.parse(ci(hi(n,hr),"utf8")).group;if(!Array.isArray(e)||e.length===0)yn(hr,"needs at least one [[group]] table");return e.map((t)=>{let i=fr(t);return{name:Vn(hr,"group.name",i.name),native:i.native===void 0?void 0:Vn(hr,"group.native",i.native),lead:Vn(hr,"group.lead",i.lead)}})}function ha(n,r,e,t){let i=Bun.TOML.parse(r),o=fr(i.meta),s=fr(i.colors),u=fr(i.contrast),c=s.ansi;if(!Array.isArray(c)||c.length!==16)yn(n,`colors.ansi must hold exactly 16 colors, got ${Array.isArray(c)?c.length:typeof c}`);let h=Vn(n,"meta.name",o.name);if(h!==Dl(n,".toml"))yn(n,`meta.name "${h}" does not match the filename`);if(ra.has(h))yn(n,`meta.name "${h}" collides with a ttheme subcommand`);if(h.startsWith("-"))yn(n,`meta.name "${h}" would be read as a flag by the ttheme CLI`);let f=o.role;if(f!==void 0&&f!=="default")yn(n,`meta.role must be "default", got ${JSON.stringify(f)}`);let l=Vn(n,"meta.group",o.group),g=t.get(l);if(!g)yn(n,`meta.group "${l}" has no [[group]] table in ${hr}`);let d=jr(n,"colors.background",s.background),w=jr(n,"colors.foreground",s.foreground),m=jr(n,"colors.cursor",s.cursor),b=jr(n,"colors.selection_background",s.selection_background),F=c.map((R,M)=>jr(n,`colors.ansi[${M}]`,R)),S=sa(n,o.signature,{background:d,foreground:w,cursor:m,selection:b,ansi:F}),k=o.booru===void 0?void 0:Vn(n,"meta.booru",o.booru);if(k!==void 0&&/\s/.test(k))yn(n,`meta.booru must be a single booru tag, got ${JSON.stringify(k)}`);let y=ua(n,o.booru_sites,k),p=Array.isArray(u.waive)?u.waive.map(String):[];if(p.length>0&&typeof u.reason!=="string")yn(n,"contrast.waive needs a contrast.reason explaining why");return{name:h,group:l,native:g.native,lead:g.lead===h,order:Number(o.order),role:f,ansiSource:Vn(n,"meta.ansi_source",o.ansi_source),...k?{booru:k}:{},...y?{booruSites:y}:{},background:d,foreground:w,cursor:m,selectionBackground:b,ansi:F,signature:S.colors,signatureSlots:S.names,font:ea(n,i.font,e.font),ghostty:ia(n,i.ghostty,e.ghostty,{background:d,cursor:m,selectionBackground:b}),waive:p,waiveReason:typeof u.reason==="string"?u.reason:void 0}}function Gu(n){let r=Bun.TOML.parse(ci(hi(n,na),"utf8")),e=ca(n),t=new Map(e.map((s)=>[s.name,s]));if(t.size!==e.length)yn(hr,"group.name must be unique");let i=xl(n).filter((s)=>s.endsWith(".toml")&&!s.startsWith("_")).map((s)=>ha(s,ci(hi(n,s),"utf8"),r,t)).sort((s,u)=>s.order-u.order);if(new Set(i.map((s)=>s.order)).size!==i.length)throw Error("themes: meta.order must be unique across all themes");for(let s of e){let u=i.filter((c)=>c.group===s.name);if(u.length===0)yn(hr,`group "${s.name}" has no themes`);if(!u.some((c)=>c.name===s.lead))yn(hr,`group "${s.name}" lead "${s.lead}" is not one of its themes`)}return i}function Lu(n){return n.filter((r)=>r.role===void 0)}function Ie(n){let r=(e,t)=>e<t?-1:e>t?1:0;return[...n].sort((e,t)=>r(e.group.toLowerCase(),t.group.toLowerCase())||r(e.name,t.name))}var it=["ghostty","kitty","alacritty","wezterm","iterm2","windows-terminal","warp"];var Ju=/# ttheme begin\n[\s\S]*?# ttheme end\n?/;function ot(n,r){let e=`# ttheme begin
16
16
  ${r}
17
17
  # ttheme end
18
- `;if(Fu.test(n))return n.replace(Fu,t);if(n==="")return t;return`${n.replace(/\n*$/,`
18
+ `;if(Ju.test(n))return n.replace(Ju,e);if(n==="")return e;return`${n.replace(/\n*$/,`
19
19
  `)}
20
- ${t}`}function Iu(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 Nu(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(`
21
- `)}function yu(n){return`source ${n}/ttheme.zsh`}var Yl="# ttheme settings — uncomment a line to change it; exported variables win over this file",_t={TTHEME_TAB_PALETTE:{doc:"# new tabs: off keeps the configured terminal theme, seq rotates through the palettes (default off)",default:"off"},TTHEME_ANNOUNCE:{doc:'# the palette notice under "Last login:": 1 shows it, 0 silences it (default 1)',default:"1"},TTHEME_FX:{doc:"# search hint animation: typewriter, decode or glitch (default typewriter)",default:"typewriter"},TTHEME_SORT:{doc:"# series and palettes in ttheme and preview: abc sorts them by name, series keeps the order they were added (default abc)",default:"abc"},TTHEME_FIND_RATING:{doc:"# the ratings find lists, any of safe, questionable and explicit, each booru read in its own rating vocabulary (default safe)",default:"safe"},TTHEME_FIND_BLOCK:{doc:'# the posts find drops by tag: nudity, underwear, both, or none to keep them all (default "nudity underwear")',default:"nudity underwear"},TTHEME_FIND_POSTS:{doc:"# what find lists first: all is every post of the character, cutouts are the transparent ones (default all)",default:"all"},TTHEME_FIND_SOLO:{doc:"# on keeps the danbooru posts tagged solo, the character alone; off lists every post (default on)",default:"on"},TTHEME_FIND_CUTOUTS:{doc:'# the tags find calls a transparent cutout, per site as key=tag,tag pairs — e.g. "konachan=transparent,vector yande=transparent_png" (default the built-in tags)',default:""},TTHEME_FIND_ORDER:{doc:"# the order find lists posts in: fit ranks each page by how well it makes a backdrop, newest or score (default fit)",default:"fit"},TTHEME_FIND_SETS:{doc:"# runs of the same picture at the same size from one uploader: fold shows them as one tile, show lists each (default fold)",default:"fold"},TTHEME_FIND_REMOVE_BG:{doc:"# an opaque picture tried on in find: on cuts the character out with macOS Vision, off leaves it as it is (default on)",default:"on"},TTHEME_FIND_UNBLOCK:{doc:"# when a network blocks a booru by name, 1 sends find through a local proxy that splits the TLS handshake — find offers to turn it on (default 0)",default:"0"},TTHEME_FIND_HOSTS:{doc:'# send a find site somewhere else, as key=https://host pairs — e.g. "danbooru=https://safebooru.donmai.us" (default none)',default:""}};function ni(n,r){let t=`: \${${n}:=${r}}`;return _t[n]?.default===r?`# ${t}`:t}function Su(n){return new RegExp(String.raw`^#? ?: \$\{${n}[^\n]*$`,"m")}function Al(n,r){if(Su(r).test(n))return n;let t=_t[r];return`${n.replace(/\n*$/,`
20
+ ${e}`}function fi(n){if(n.TERM_PROGRAM==="WarpTerminal")return"warp";if(n.GHOSTTY_RESOURCES_DIR||n.TERM_PROGRAM==="ghostty")return"ghostty";if(n.KITTY_WINDOW_ID)return"kitty";if(n.WEZTERM_PANE)return"wezterm";if(n.ALACRITTY_WINDOW_ID)return"alacritty";if(n.ITERM_SESSION_ID||n.TERM_PROGRAM==="iTerm.app")return"iterm2";if(n.TERM_PROGRAM==="Apple_Terminal")return"terminal-app";if(n.WT_SESSION&&!n.TERM_PROGRAM)return"windows-terminal";if(n.TERM?.startsWith("foot"))return"foot";return"unknown"}function Pu(n,r){let e=[`command = ${n}/launch-tab.zsh`,"shell-integration = zsh"];if(r)e.push(`theme = ${r}`);return e.push(`config-file = ${n}/ttheme.conf`,`config-file = ?${n}/backgrounds/shown.conf`),e.join(`
21
+ `)}function Uu(n){return`source ${n}/ttheme.zsh`}var fa="# ttheme settings — uncomment a line to change it; exported variables win over this file",st={TTHEME_TAB_PALETTE:{doc:"# new tabs: off keeps the configured terminal theme, seq rotates through the palettes (default off)",default:"off"},TTHEME_ANNOUNCE:{doc:'# the palette notice under "Last login:": 1 shows it, 0 silences it (default 1)',default:"1"},TTHEME_FX:{doc:"# search hint animation: typewriter, decode or glitch (default typewriter)",default:"typewriter"},TTHEME_SORT:{doc:"# series and palettes in ttheme and preview: abc sorts them by name, series keeps the order they were added (default abc)",default:"abc"},TTHEME_FIND_RATING:{doc:"# the ratings find lists, any of safe, questionable and explicit, each booru read in its own rating vocabulary (default safe)",default:"safe"},TTHEME_FIND_BLOCK:{doc:'# the posts find drops by tag: nudity, underwear, both, or none to keep them all (default "nudity underwear")',default:"nudity underwear"},TTHEME_FIND_POSTS:{doc:"# what find lists first: all is every post of the character, cutouts are the transparent ones (default all)",default:"all"},TTHEME_FIND_SOLO:{doc:"# on keeps the danbooru posts tagged solo, the character alone; off lists every post (default on)",default:"on"},TTHEME_FIND_CUTOUTS:{doc:'# the tags find calls a transparent cutout, per site as key=tag,tag pairs — e.g. "konachan=transparent,vector yande=transparent_png" (default the built-in tags)',default:""},TTHEME_FIND_ORDER:{doc:"# the order find lists posts in: fit ranks each page by how well it makes a backdrop, newest or score (default fit)",default:"fit"},TTHEME_FIND_SETS:{doc:"# runs of the same picture at the same size from one uploader: fold shows them as one tile, show lists each (default fold)",default:"fold"},TTHEME_FIND_REMOVE_BG:{doc:"# an opaque picture tried on in find: on cuts the character out with macOS Vision, off leaves it as it is (default on)",default:"on"},TTHEME_FIND_UNBLOCK:{doc:"# when a network blocks a booru by name, 1 sends find through a local proxy that splits the TLS handshake — find offers to turn it on (default 0)",default:"0"},TTHEME_FIND_HOSTS:{doc:'# send a find site somewhere else, as key=https://host pairs — e.g. "danbooru=https://safebooru.donmai.us" (default none)',default:""}};function gi(n,r){let e=`: \${${n}:=${r}}`;return st[n]?.default===r?`# ${e}`:e}function Qu(n){return new RegExp(String.raw`^#? ?: \$\{${n}[^\n]*$`,"m")}function ga(n,r){if(Qu(r).test(n))return n;let e=st[r];return`${n.replace(/\n*$/,`
22
22
  `)}
23
- ${t.doc}
24
- ${ni(r,t.default)}
25
- `}function ri(){let n=Object.entries(_t).map(([r,t])=>`${t.doc}
26
- ${ni(r,t.default)}`);return`${[Yl,...n].join(`
23
+ ${e.doc}
24
+ ${gi(r,e.default)}
25
+ `}function li(){let n=Object.entries(st).map(([r,e])=>`${e.doc}
26
+ ${gi(r,e.default)}`);return`${[fa,...n].join(`
27
27
 
28
28
  `)}
29
- `}function Bt(n,r,t){let e=ni(r,t),i=Su(r);if(i.test(n))return n.replace(i,e);return`${n.replace(/\n*$/,`
29
+ `}function ut(n,r,e){let t=gi(r,e),i=Qu(r);if(i.test(n))return n.replace(i,t);return`${n.replace(/\n*$/,`
30
30
  `)}
31
+ ${t}
32
+ `}function Wu(n){if(n==="")return li();return Object.keys(st).reduce(ga,n)}function Zu(n){return n?`include themes/${n}.conf`:""}function qu(n){return n?`[general]
33
+ import = ["${n}"]`:""}var Ku=/-- ttheme begin\n[\s\S]*?-- ttheme end\n?/,la=/^return config[ \t]*$/gm;function Au(n){return`dofile(${JSON.stringify(n)})(config)`}function ct(n,r){let e=`-- ttheme begin
34
+ ${r}
35
+ -- ttheme end
36
+ `;if(Ku.test(n))return n.replace(Ku,e);if(n==="")return`local wezterm = require 'wezterm'
37
+ local config = wezterm.config_builder()
38
+
31
39
  ${e}
32
- `}function Hu(n){if(n==="")return ri();return Object.keys(_t).reduce(Al,n)}function ju(n){return n?`include themes/${n}.conf`:""}function Gu(n){return n?`[general]
33
- import = ["${n}"]`:""}function ti(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}"`,s=(u)=>u.map((c)=>c.name).join(" "),o=Wr(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='${ri().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=(${s(o)})`,"","# the same palettes by series name, then palette name: TTHEME_SORT=abc lists them this way",`typeset -ga TTHEME_ABC=(${s(pt(o))})`,"","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(`
34
- `)}var ei={id:"shell",emitShared(n){return[{path:"shell/palettes.zsh",content:ti(n.map(Ye))}]}};var Ou=(n)=>`[${n.map((r)=>`"${r}"`).join(", ")}]`,ii={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 = ${Ou(n.ansi.slice(0,8))}`,`brights = ${Ou(n.ansi.slice(8,16))}`,""].join(`
35
- `),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(`
36
- `);return[{path:`wezterm/colors/${n.name}.toml`,content:r},{path:`wezterm/config/${n.name}.lua`,content:t}]}};function Kr(n){return[`# ${n.name} — ${n.group}${n.native?` (${n.native})`:""}`,`# ANSI: ${n.ansiSource}`]}var Ju=Mt(import.meta.dirname,".."),Tl=Mt(Ju,"themes"),si=Mt(Ju,"dist"),xt=[ct,ft,ut,ii,ht],Cl=[ei,Ae],Ku=xt.map((n)=>n.id);async function Dt({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?xt.filter((s)=>n.includes(s.id)):xt,t=Eu(Tl),e=$s(t);if(e.length>0){for(let s of e)console.error(` ✗ ${s.theme} [${s.rule}] ${s.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===xt.length)Ru(si,{recursive:!0,force:!0});else for(let s of r)Ru(Mt(si,s.id),{recursive:!0,force:!0});let i=0;for(let s of[...r,...Cl]){let o=t.flatMap((h)=>s.emit?.(h)??[]),u=s.emitShared?.(t)??[];for(let h of[...o,...u])await Bun.write(Mt(si,h.path),h.content),i++;let c=o.length>0?`${t.length} themes${s.limits?` (${s.limits})`:""}`:u.map((h)=>zl(h.path)).join(" ");console.log(` ${s.id.padEnd(10)} ${c}`)}console.log(`
37
- ${t.length} themes (${vu(t).length} in the new-tab rotation) -> ${i} files in dist/`)}import{spawn as Kc}from"node:child_process";import{createHash as xd}from"node:crypto";import{existsSync as Tr,mkdirSync as vi,mkdtempSync as Dd,readFileSync as Lc,rmSync as wi,statSync as na,writeFileSync as Fi}from"node:fs";import{tmpdir as ra}from"node:os";import{dirname as yc,join as gr}from"node:path";import{existsSync as _l,mkdirSync as Bl,readFileSync as xl,writeFileSync as Dl}from"node:fs";import{dirname as nd,join as rd}from"node:path";var Lu="https://kecan0406.github.io/ttheme/manifest.json",td=20000;function ne(n){return rd(n,"ttheme","catalog.json")}function re(n,r){let t=ne(n);Bl(nd(t),{recursive:!0}),Dl(t,`${JSON.stringify(r,null,2)}
38
- `)}function Pn(n){let r=ne(n);if(!_l(r))throw Error(`no catalog at ${r} — run \`ttheme init\` first`);return Qu(xl(r,"utf8"))}function Qu(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 Pu(n){let r;try{r=await fetch(n,{signal:AbortSignal.timeout(td)})}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 Qu(await r.text())}function Zu(n){let r=new Set(n.waived??[]);return Pt.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 te(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 qu(n,r){let t=r.toLowerCase();return n.filter((e)=>[e.name,e.group,e.native??"",e.ansiSource].some((i)=>i.toLowerCase().includes(t)))}function Uu(n,r,t){let e=t.toLowerCase(),i=(s)=>s.name===r.name?0:s.group===r.group?1:2;return n.filter((s)=>s.booru?.toLowerCase().includes(e)).map((s,o)=>({p:s,at:o})).sort((s,o)=>i(s.p)-i(o.p)||s.at-o.at).map(({p:s})=>s)}function Wu(n,r){return n.booruSites?.[r]??(n.booru?[n.booru]:[])}import{spawn as ed}from"node:child_process";var id=30000,sd=3,od=97,ud=`ObjC.import('Vision')
40
+ return config
41
+ `;let t=[...n.matchAll(la)].at(-1);if(t?.index===void 0)return;return`${n.slice(0,t.index)}${e}
42
+ ${n.slice(t.index)}`}var Xu="[appearance.themes]";function Tu(n){let r=n.findIndex((t)=>t.trim()===Xu);if(r<0)return;let e=n.findIndex((t,i)=>i>r&&t.trimStart().startsWith("["));return[r,e<0?n.length:e]}function Vu(n){let r=n.split(`
43
+ `),e=Tu(r);if(!e)return;return r.slice(e[0]+1,e[1]).find((i)=>/^theme\s*=/.test(i))?.replace(/^theme\s*=\s*/,"").trim()}function zu(n){return`{ custom = { name = "${n}", path = "ttheme-${n}.yaml" } }`}function Yu(n,r){let e=n.split(`
44
+ `),t=Tu(e);if(!t)return r===void 0?n:`${n.replace(/\n*$/,`
45
+ `)}
46
+ ${Xu}
47
+ theme = ${r}
48
+ `;let i=e.findIndex((o,s)=>s>t[0]&&s<t[1]&&/^theme\s*=/.test(o));if(i>=0)e.splice(i,1,...r===void 0?[]:[`theme = ${r}`]);else if(r!==void 0)e.splice(t[0]+1,0,`theme = ${r}`);return e.join(`
49
+ `)}function ai(n,r,e=[]){for(let u of n)for(let c of[u.name,u.group,u.native??"",u.ansiSource])if(/["$`\\]/.test(c))throw Error(`${u.name}: "${c}" contains a character that breaks zsh quoting`);let t=Math.max(0,...n.map((u)=>u.name.length)),i=(u,c)=>` ${u.name.padEnd(t)} "${c}"`,o=(u)=>u.map((c)=>c.name).join(" "),s=Ar(n);return["# Generated by `mise run build` — do not edit.","# Source of truth: themes/*.toml in the ttheme repo.","",`typeset -g TTHEME_VERSION=${rr.version}`,"",'# the palette new tabs open with, which the iTerm2 "ttheme · default" profile wears',`typeset -g TTHEME_STARTUP=${r??""}`,"","# the terminals ttheme is wired into: a picture change reaches every one of them, from whichever runs the shell",`typeset -ga TTHEME_TERMINALS=(${e.join(" ")})`,"","# seed for `ttheme config` when no config.zsh exists yet",`typeset -g TTHEME_CONFIG_TEMPLATE='${li().trimEnd().replaceAll("'","'\\''")}'`,"","typeset -gA TTHEME_PALETTE=(",...n.map((u)=>i(u,[u.background,u.foreground,u.cursor,u.selection,...u.ansi].join(" "))),")","","# series order: new tabs cycle through it and TTHEME_SORT=series lists it — the default role stays applyable but unlisted",`typeset -ga TTHEME_ORDER=(${o(s)})`,"","# the same palettes by series name, then palette name: TTHEME_SORT=abc lists them this way",`typeset -ga TTHEME_ABC=(${o(Ie(s))})`,"","typeset -gA TTHEME_GROUP=(",...n.map((u)=>i(u,u.group)),")","","# original-language title, rendered dim next to the group","typeset -gA TTHEME_NATIVE=(",...n.filter((u)=>u.native).map((u)=>i(u,u.native??"")),")","","# where each palette's 16 ANSI colors came from","typeset -gA TTHEME_SRC=(",...n.map((u)=>i(u,u.ansiSource)),")",""].join(`
50
+ `)}var di={id:"shell",emitShared(n){return[{path:"shell/palettes.zsh",content:ai(n.map(ri))}]}};var aa=["black","red","green","yellow","blue","magenta","cyan","white"];function Cu(n,r){return[` ${n}:`,...aa.map((e,t)=>` ${e}: "${r[t]}"`)]}var Se={id:"warp",limits:"colors only — no selection color, and Warp paints one theme app-wide",emit(n){let r=[`name: "${n.name}"`,`background: "${n.background}"`,`foreground: "${n.foreground}"`,`accent: "${n.cursor}"`,`cursor: "${n.cursor}"`,`details: ${_n(n.background)<0.18?"darker":"lighter"}`,"terminal_colors:",...Cu("normal",n.ansi.slice(0,8)),...Cu("bright",n.ansi.slice(8,16)),""].join(`
51
+ `);return[{path:`warp/themes/ttheme-${n.name}.yaml`,content:r}]}};var _u=(n)=>`[${n.map((r)=>`"${r}"`).join(", ")}]`,Ne={id:"wezterm",limits:"no shaders; OSC repaints per pane, pictures show per window",emit(n){let r=["[metadata]",`name = "${n.name}"`,`origin_url = "${n.ansiSource}"`,"","[colors]",`foreground = "${n.foreground}"`,`background = "${n.background}"`,`cursor_bg = "${n.cursor}"`,`cursor_border = "${n.cursor}"`,`cursor_fg = "${n.background}"`,`selection_bg = "${n.selectionBackground}"`,`selection_fg = "${n.foreground}"`,"",`ansi = ${_u(n.ansi.slice(0,8))}`,`brights = ${_u(n.ansi.slice(8,16))}`,""].join(`
52
+ `),e=[`-- ${n.name} — font settings.`,"-- Merge into your wezterm.lua config table:",`-- local t = require("ttheme.${n.name}")`,`-- config.color_scheme = "${n.name}"`,"-- config.font = t.font","-- config.font_size = t.font_size","return {",` font = require("wezterm").font("${n.font.family}"),`,` font_size = ${n.font.size},`,"}",""].join(`
53
+ `);return[{path:`wezterm/colors/${n.name}.toml`,content:r},{path:`wezterm/config/${n.name}.lua`,content:e}]}},Xr=(n)=>JSON.stringify(n);function Bu(n){return["-- Generated by ttheme — rewritten on every add, remove and default; do not edit.","local wezterm = require 'wezterm'","",`local MODULE = ${Xr(n.path)}`,`local COLORS = ${Xr(n.colors)}`,`local BACKGROUNDS = ${Xr(n.backgrounds)}`,`local STARTUP = ${n.startup?Xr(n.startup):"nil"}`,"local PALETTES = {",...n.palettes.map((r)=>` [${Xr(r.name)}] = ${Xr(r.background)},`),"}","","local X = { left = 'Left', center = 'Center', right = 'Right' }","local Y = { top = 'Top', center = 'Middle', bottom = 'Bottom' }","local SIZE = { cover = 'Cover', contain = 'Contain', stretch = '100%' }","","local function locate(path)"," if path:sub(1, 2) == '~/' then"," return os.getenv('HOME') .. path:sub(2)"," elseif path:sub(1, 1) == '/' or path:match('^%a:[/\\\\]') then"," return path"," end"," return BACKGROUNDS .. '/' .. path","end","","local function read(path, into)"," local f = io.open(path, 'r')"," if not f then"," return false"," end"," for line in f:lines() do"," local key, value = line:match('^%s*([%w%-]+)%s*=%s*(.-)%s*$')"," if key == 'config-file' then"," read(locate((value:gsub('^%?', ''))), into)"," elseif key then"," into[key] = value"," end"," end"," f:close()"," return true","end","","local function layers(palette)"," local color = PALETTES[palette]"," local c = {}"," if not color or not read(BACKGROUNDS .. '/' .. palette .. '.conf', c) then"," return nil, 'none'"," end"," local image = c['background-image'] or ''"," local opacity = tonumber(c['background-image-opacity'] or '1') or 1"," if image == '' or opacity <= 0 then"," return nil, 'none'"," end"," local fit = c['background-image-fit'] or 'contain'"," local position = c['background-image-position'] or 'center'"," local y, x = position:match('^(%a+)-(%a+)$')"," local rep = c['background-image-repeat'] == 'true' and 'Repeat' or 'NoRepeat'"," return {"," { source = { Color = color }, width = '100%', height = '100%' },"," {"," source = { File = locate(image) },"," opacity = opacity,"," width = SIZE[fit],"," height = SIZE[fit],"," horizontal_align = X[x or 'center'],"," vertical_align = Y[y or 'center'],"," repeat_x = rep,"," repeat_y = rep,"," },"," }, table.concat({ color, image, opacity, fit, position, rep }, '|')","end","","local shown = {}","","local function show(window, pane)"," local want = pane:get_user_vars().ttheme_shown"," if not want or want == '' then"," return"," end"," local background, key = layers(want)"," local id = window:window_id()"," if shown[id] == key then"," return"," end"," shown[id] = key"," local overrides = window:get_config_overrides() or {}"," overrides.background = background"," window:set_config_overrides(overrides)","end","","wezterm.on('user-var-changed', function(window, pane, name)"," if name == 'ttheme_shown' then"," show(window, pane)"," end","end)","wezterm.on('update-status', show)","","return function(config)"," local dirs = config.color_scheme_dirs or {}"," table.insert(dirs, COLORS)"," config.color_scheme_dirs = dirs"," if STARTUP then"," config.color_scheme = STARTUP"," end"," wezterm.add_to_config_reload_watch_list(MODULE)","end",""].join(`
54
+ `)}var xu=["black","red","green","yellow","blue","purple","cyan","white"];function Du(n){return{name:n.name,background:n.background,foreground:n.foreground,cursorColor:n.cursor,selectionBackground:n.selectionBackground,...Object.fromEntries(xu.map((r,e)=>[r,n.ansi[e]])),...Object.fromEntries(xu.map((r,e)=>[`bright${r[0]?.toUpperCase()}${r.slice(1)}`,n.ansi[e+8]]))}}function mi(n,r,e){let t={...r&&e?{profiles:[{updates:r,colorScheme:e}]}:{},schemes:n.map(Du)};return`${JSON.stringify(t,null,2)}
55
+ `}var He={id:"windows-terminal",limits:"colors only — no kitty graphics, so no pictures; OSC repaints per pane",emit(n){return[{path:`windows-terminal/schemes/${n.name}.json`,content:`${JSON.stringify(Du(n),null,2)}
56
+ `}]},emitShared(n){return[{path:"windows-terminal/ttheme.json",content:mi(n)}]}};function Pr(n){return[`# ${n.name} — ${n.group}${n.native?` (${n.native})`:""}`,`# ANSI: ${n.ansiSource}`]}var rc=Oe(import.meta.dirname,".."),ma=Oe(rc,"themes"),$i=Oe(rc,"dist"),ht=[de,$e,ae,Ne,me,He,Se],$a=[di,ei],ec=ht.map((n)=>n.id);async function ft({only:n}={}){if(typeof Bun>"u")throw Error("ttheme build needs bun — run it from a checkout: bun src/bin.ts build");let r=n&&n.length>0?ht.filter((o)=>n.includes(o.id)):ht,e=Gu(ma),t=No(e);if(t.length>0){for(let o of t)console.error(` ✗ ${o.theme} [${o.rule}] ${o.detail}`);throw Error(`${t.length} contrast violation(s). Fix the palette, or waive the rule in its [contrast] section with a reason.`)}if(r.length===ht.length)nc($i,{recursive:!0,force:!0});else for(let o of r)nc(Oe($i,o.id),{recursive:!0,force:!0});let i=0;for(let o of[...r,...$a]){let s=e.flatMap((h)=>o.emit?.(h)??[]),u=o.emitShared?.(e)??[];for(let h of[...s,...u])await Bun.write(Oe($i,h.path),h.content),i++;let c=s.length>0?`${e.length} themes${o.limits?` (${o.limits})`:""}`:u.map((h)=>da(h.path)).join(" ");console.log(` ${o.id.padEnd(16)} ${c}`)}console.log(`
57
+ ${e.length} themes (${Lu(e).length} in the new-tab rotation) -> ${i} files in dist/`)}import{spawn as nh}from"node:child_process";import{createHash as Nd}from"node:crypto";import{existsSync as xr,mkdirSync as Li,mkdtempSync as Hd,readFileSync as rh,rmSync as Hi,statSync as Od,writeFileSync as Ji}from"node:fs";import{tmpdir as jd}from"node:os";import{dirname as Vc,join as ar}from"node:path";import{existsSync as wa,mkdirSync as pa,readFileSync as ba,writeFileSync as ka}from"node:fs";import{dirname as Ma,join as Ea}from"node:path";var tc="https://kecan0406.github.io/ttheme/manifest.json",va=20000;function gt(n){return Ea(n,"ttheme","catalog.json")}function lt(n,r){let e=gt(n);pa(Ma(e),{recursive:!0}),ka(e,`${JSON.stringify(r,null,2)}
58
+ `)}function Qn(n){let r=gt(n);if(!wa(r))throw Error(`no catalog at ${r} — run \`ttheme init\` first`);return ic(ba(r,"utf8"))}function ic(n){let r;try{r=JSON.parse(n)}catch{throw Error("catalog is not valid JSON")}let e=r;if(typeof e?.version!=="string"||!Array.isArray(e.palettes))throw Error("catalog has no version or palettes");for(let t of e.palettes)if(typeof t?.name!=="string"||!Array.isArray(t.ansi)||t.ansi.length!==16)throw Error(`catalog entry ${JSON.stringify(t?.name)} is missing name or its 16 ANSI colors`);return e}async function oc(n){let r;try{r=await fetch(n,{signal:AbortSignal.timeout(va)})}catch(e){throw Error(`cannot reach the registry at ${n} — ${e instanceof Error?e.message:String(e)}`)}if(!r.ok)throw Error(`registry at ${n} answered ${r.status}`);return ic(await r.text())}function sc(n){let r=new Set(n.waived??[]);return Ye.flatMap((e,t)=>{let i=n.gate?.[t];if(r.has(e.rule)||typeof i!=="number")return[];if(e.min!==void 0&&i<e.min)return[`${e.label} ${i} < ${e.min}`];if(e.max!==void 0&&i>e.max)return[`${e.label} ${i} > ${e.max}`];return[]})}function at(n,r){let e=n.find((t)=>t.name===r);if(!e)throw Error(`no palette named ${r} in the catalog — \`ttheme list\` shows what is there`);return e}function uc(n,r){let e=r.toLowerCase();return n.filter((t)=>[t.name,t.group,t.native??"",t.ansiSource].some((i)=>i.toLowerCase().includes(e)))}function cc(n,r,e){let t=e.toLowerCase(),i=(o)=>o.name===r.name?0:o.group===r.group?1:2;return n.filter((o)=>o.booru?.toLowerCase().includes(t)).map((o,s)=>({p:o,at:s})).sort((o,s)=>i(o.p)-i(s.p)||o.at-s.at).map(({p:o})=>o)}function hc(n,r){return n.booruSites?.[r]??(n.booru?[n.booru]:[])}import{spawn as Fa}from"node:child_process";var ya=30000,Ia=3,Sa=97,Na=`ObjC.import('Vision')
39
59
  ObjC.import('CoreImage')
40
60
  ObjC.import('CoreGraphics')
41
61
  function run(argv) {
@@ -54,104 +74,104 @@ function run(argv) {
54
74
  $.CIImage.imageWithCVPixelBuffer(buffer), $.NSURL.fileURLWithPath(argv[1]), $.kCIFormatRGBA8,
55
75
  $.CGColorSpaceCreateWithName($.kCGColorSpaceSRGB), $({}), error)
56
76
  if (!written) throw new Error('write failed')
57
- }`;function oi(){return process.platform==="darwin"}function Xu(n){return n>=sd&&n<=od}function Vu(n,r,t){return new Promise((e,i)=>{let s=ed("osascript",["-l","JavaScript","-e",ud,n,r],{stdio:["ignore","ignore","pipe"],signal:AbortSignal.any([t,AbortSignal.timeout(id)])}),o="";s.stderr.on("data",(u)=>{o+=u}),s.on("error",i),s.on("close",(u)=>{if(u===0){e();return}i(Error(o.trim().split(`
58
- `).at(-1)||`osascript exited ${u}`))})})}var Qn={pitch:25,cols:22,rows:9,height:13},jr={cols:25,rows:16},cd=2147483648,hd=-1073741826,fd=1600,gd="\x1B[0m",tr="\x1B[1m",cn="\x1B[2m",Et="\x1B[31m",hr="\x1B[32m",Zn="\x1B[33m",ee="\x1B[1;34m",ld="\x1B[35m",dd={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 zu(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(dd[`${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 Tu="\x1B]1337;ReportCellSize\x07\x1B[16t",Yu="\x1B]1337;ReportCellSize=";function hi(n){let r=n.indexOf(Yu);if(r!==-1){let i=n.slice(r+Yu.length),s=[i.indexOf("\x07"),i.indexOf("\x1B\\")].filter((c)=>c!==-1),o=s.length>0?Math.min(...s):-1,u=o===-1?null:/^([\d.]+);([\d.]+);([\d.]+)$/.exec(i.slice(0,o));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(o+(i[o]==="\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 Xr(n,r){return{perRow:Math.max(1,Math.floor((n+1)/Qn.pitch)),rowsVis:Math.max(1,Math.floor((r-4)/Qn.height))}}function Cu(n){return`\x1B_Ga=t,t=f,f=100,i=${n.id},q=2;${Buffer.from(n.path).toString("base64")}\x1B\\`}function _u(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 Bu(n){return`\x1B_Ga=d,d=I,i=${n},q=2\x1B\\`}function xu(n){return`\x1B[38;2;${On(n).join(";")}m`}function ui(n){return`\x1B[48;2;${On(n).join(";")}m`}function Yn(n){return Array.from(n).length}class ie{parts=[];cols;constructor(n){this.cols=n}put(n,r,t=""){return this.parts.push({col:n,text:r,sgr:t}),n+Yn(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+Yn(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?gd:""}`}return n}}function Du(n){return n>=1e6?`${(n/1e6).toFixed(1)} MB`:`${Math.max(1,Math.round(n/1000))} KB`}function ad(n,r){if(!r)return Du(n);return r>=1e6?`${(n/1e6).toFixed(1)}/${(r/1e6).toFixed(1)} MB`:`${Math.round(n/1000)}/${Math.round(r/1000)} KB`}function nc(n){return n.replace(/_\([^)]*\)?$/,"")}function rc(n){return[`${n.reduced?"↓":""}${n.width}×${n.height}`,Math.max(n.width,n.height)<fd?Zn:cn]}function vt(n,r,t,e){let i=[...e.keys??[]],s=e.lead,o=e.right,u=()=>{let f=[...s?[Yn(s[0])]:[],...i.map(([l,a])=>Yn(l)+1+Yn(a))];return(e.badge?Yn(e.badge)+4:0)+f.reduce((l,a)=>l+a,0)+3*Math.max(0,f.length-1)+(o?3+Yn(o[0])+1+Yn(o[1]):0)};while(u()>r)if(i.length>2)i.splice(-2,1);else if(o)o=void 0;else if(i.length>1)i.splice(-2,1);else break;if(s&&u()>r){let f=Math.max(0,Yn(s[0])-(u()-r)-1);s=[`${Array.from(s[0]).slice(0,f).join("")}…`,s[1]]}let c=0;if(e.badge)c=n.put(0,` ${e.badge} `,`\x1B[7;1m${t}`)+2;if([...s?[[s]]:[],...i.map(([f,g])=>[[f,tr],[` ${g}`,cn]])].forEach((f,g)=>{c=n.run(c+(g?3:0),f)}),o)n.right(r,[[o[0],tr],[` ${o[1]}`,cn]])}function md(n,r,t,e,i,s){let{ansi:o,selection:u,cursor:c}=s.colors,h=e<44?3:4;if(e>=56)h=Math.min(7,Math.floor((e+1)/8)-1);let f=t;for(let m=0;m<8;m++)f=(n[r]?.put(f,"▀".repeat(h),xu(o[m]??c)+ui(o[m+8]??c))??f)+1;let g=["❯ ",hr],l=[[["~/code/demo",ee],[" on ",cn],["main",ld],[" +2",hr],[" ~1",Zn]]];if(l.push([g,["git status -sb",""]]),e>=44)l.push([["## ",""],["main",hr],["...",""],["origin/main",Et],[" [ahead 1]",Zn]]);if(l.push([[" M",Et],[" src/main.rs",""]]),l.push([["??",Et],[" notes.md",""]]),l.push([]),e>=44)l.push([g,["ls",""]]),l.push([["docs",ee],[" ",""],["src",ee],[" ",""],["tests",ee],[" Cargo.toml README.md",""]]),l.push([]);l.push([g,["cargo test",""]]),l.push([[" ✓",hr],[" parses config",""]]);let a=[[" ✗",Et],[" renders frame",""]];if(e>=44)a.push([" expected ",cn],["3",hr],[", received ",cn],["2",Et]);l.push(a),l.push([]),l.push([g,["echo ",""],["selected text",ui(u)],[" ",""],[" ",ui(c)]]),l.forEach((m,b)=>{let E=r+2+b;if(E<=i)n[E]?.run(t,m)})}function $d(n,r,t,e,i,s){n[r]?.put(t,`╭${"─".repeat(i-2)}╮`,s);for(let o=r+1;o<r+e-1;o++)n[o]?.put(t,"│",s),n[o]?.put(t+i-1,"│",s);n[r+e-1]?.put(t,`╰${"─".repeat(i-2)}╯`,s)}function ci(n,r=n.site,t=n.siteAnsi){return[` ${r} `,`\x1B[7;${30+t}m`]}function bd(n){return`${pn[Math.floor(n/Sr)]?.name??""} ${n%Sr}`}function wd(n,r,t){let e=[{name:"all",moved:!1},...pn].flatMap((o,u)=>{let c=`${o.name}${o.moved?"*":""}`,h=o.name===t.site?ci(t,c):[` ${c} `,cn];return u?[[" ",""],h]:[h]}),i=e.reduce((o,[u])=>o+Yn(u),0)<=r,s=n.run(0,i?e:[ci(t)]);if(t.asking!==void 0)n.run(s,[[` ${t.asking} was cut off — this network may block it. turn on the unblock proxy? `,Zn],["y",tr],[" turn on ",cn],["n",tr],[" not now",cn]])}function kd(n,r,t,e){if(t.editing!==void 0){let u=n.run(0,[["⌕ ",e],[t.editing,""],["█",e]]),c=t.suggest?.length?" ↑↓ pick enter searches":" enter searches";n.put(u,t.editing?c:` a tag, a post url or an id — ${t.tag||"esc leaves"}`,cn);return}let i=n.run(0,[["⌕ ",e],[t.tag||"nothing yet — / searches",t.tag?"":cn]]),s=yr.filter((u)=>!t.block.includes(u)),o=[t.preset,...t.solo?["solo"]:[],t.order,...t.rating.join("+")==="safe"?[]:[t.rating.join("+")],...s.length>0?[`allows ${s.join("+")}`]:[],...t.unblocked?["unblock"]:[]];if(n.put(i,` ${o.join(" ")}`,cn),t.total>0||!t.searching){let u=[[`${t.tiles.length}/${t.checked}`,""]];if(t.checked<t.total)u.push([` of ${t.total}`,cn]);n.right(r,u)}}function pd(n){if(n.cut==="on")return[[`cut out · ${n.clear}% transparent`,hr]];if(n.cut==="off")return[["opaque · x cuts out",Zn]];if(n.cut==="failed")return[["opaque · no cut-out",Zn]];return[n.clear>0?[`${n.clear}% transparent`,hr]:["opaque",Zn]]}function Au(n){return n.site==="all"?"any site":n.site}function tc(n){if(n.installing!==void 0)return[`installing ${n.palette} ← ${bd(n.installing)}`,Zn];if(n.error)return[n.error,Zn];if(n.waiting!==void 0)return[`${n.slow??n.site} asked to slow down · ${n.waiting}s`,Zn];if(n.fetching)return[`fetching ${n.fetching.id%Sr} · ${ad(n.fetching.got,n.fetching.size)}`,Zn];if(n.cutting!==void 0)return[`cutting out ${n.cutting%Sr}`,Zn];if(n.preparing!==void 0)return[`preparing ${n.preparing%Sr}`,Zn];if(n.saved)return[n.saved,hr];if(n.note)return[n.note,cn];return}function Md(n,r,t,e,i,s){let{perRow:o,rowsVis:u}=Xr(t,e);kd(n[0],t,i,s),wd(n[1],t,i);for(let a=0;a<o*u;a++){let m=i.top*o+a,b=i.tiles[m];if(!b)break;let E=2+Math.floor(a/o)*Qn.height,F=a%o*Qn.pitch,H=m===i.focus;if(H)$d(n,E,F,Qn.height,Qn.pitch-1,s);if(b.thumb)r.push({id:b.key,path:b.thumb,row:E+1,col:F+1,cols:Qn.cols,rows:Qn.rows,z:-1});if(n[E+10]?.run(F+1,[...i.installed.includes(b.key)?[["✓ ",hr]]:[],...i.site==="all"?[["● ",`\x1B[${30+b.siteAnsi}m`]]:[],[String(b.id),H?tr:""],[" ",""],rc(b)]),b.mates.length>0)n[E+10]?.put(F+Qn.cols,"≈",s);let p=b.artist?nc(b.artist):b.owner&&`@${b.owner}`;if(p)n[E+11]?.put(F+1,p.slice(0,Qn.cols-8),cn);let I=[];if(b.score>0)I.push([`★${b.score}`,cn]);if(b.variants>1)I.push([` ×${b.variants}`,s]);if(I.length>0)n[E+11]?.right(F+Qn.cols+1,I)}let c=i.top*o,h=i.tiles.length-(i.top+u)*o,f=[...c>0?[`↑ ${c} above`]:[],...h>0?[`↓ ${h} more`]:[]];if(f.length>0)n[e-2]?.put(0,f.join(" "),cn);if(!i.searching&&i.tiles.length===0&&!i.error)n[3]?.put(0,i.preset==="cutouts"?`no transparent cutouts of ${i.tag} on ${Au(i)} — c searches every post, tab tries ${i.nextSite}`:`no posts of ${i.tag} on ${Au(i)} — tab tries ${i.nextSite}`,cn);let g=n[e-1],l=tc(i);if(i.searching&&i.tiles.length===0&&!l){vt(g,t,s,{badge:"FIND",lead:[i.preset==="cutouts"?"checking png headers":"fetching posts",cn],right:["esc","back"]});return}vt(g,t,s,{badge:"FIND",lead:l,keys:i.asking!==void 0?[]:[["←↑↓→","move"],["enter","try on"],["tab","site"],["s","settings"],["/","search"],["?","keys"]],right:i.asking!==void 0?void 0:["esc","back"]})}function Ed(n,r,t,e,i,s){let o=i.tiles[i.focus];if(!o)return;let u=i.shown?.id===o.key?i.shown:void 0,c=[ci(i,o.site,o.siteAnsi),[" ",""],[String(o.id),tr],[" ",""],rc(o)];if(o.artist)c.push([` · ${nc(o.artist)}`,""]);if(o.score>0)c.push([` · ★${o.score}`,cn]);if(u)c.push([` · ${Du(u.bytes)}`,cn]);if(c.push([` · ${o.owner}`,cn]),o.origin)c.push([` · ${o.origin}`,cn]);if(u)c.push([" ",""],...pd(u));if(n[0]?.run(0,c),o.mates.length>0)n[0]?.right(t,[["≈ ",s],[o.mates.join(" "),cn]]);if(md(n,3,2,t-4,e-2,i),i.shown)r.push({id:cd+i.shown.id,path:i.shown.path,row:0,col:0,cols:t,rows:e,z:hd});let h=tc(i);vt(n[e-1],t,s,{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 vd={grid:[["move","←↑↓→ home end pgup pgdn"],["try on","enter"],["site",`tab all, ${pn.map((n)=>n.name).join(", ")}`],["posts","c cutouts or every post"],["search","/ a tag, a post url or an id"],["unfold","space a set of ×N"],["open","o the post page in a browser"],["settings","s rating, block, posts, solo, order, sets, remove bg"],["back","esc returns to preview"],["close","? esc"]],try:[["browse","←→"],["install","enter"],["cut out","x the background off or on, on an opaque picture"],["open","o the post page in a browser"],["grid","esc"],["close","? esc"]]};function Fd(n,r,t,e,i){let s=e.panel??0,o=Math.max(...e.settings.map((l)=>l.label.length)),u=Math.max(...e.settings.map((l)=>l.choices.reduce((a,m)=>a+m.length+(l.multi?6:3),0))),c=Math.min(r-2,Math.max(28,o+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,a)=>{let m=n[g+2+a];m.put(f+3,l.label,a===s?tr:cn);let b=f+5+o,E=l.value.split(" ");l.choices.forEach((F,H)=>{let p=E.includes(F),I=l.multi&&a===s&&H===l.cursor?"4;":"",w=l.multi?` ${p?"[x]":"[ ]"} ${F} `:` ${F} `;b=m.put(b,w,p?`\x1B[${I}7;${30+e.siteAnsi}m`:I?`\x1B[4m${cn}`:cn)+1})}),n[g+h-1]?.put(f,`╰${"─".repeat(c-2)}╯`),vt(n[t-1],r,i,{badge:"SET",keys:[["↑↓","setting"],["←→","value"],["space","toggle"],["enter","save"]],right:["esc","undo"]})}function Id(n,r,t,e,i){let s=vd[e.mode],o=Math.min(r-2,50),u=s.length+4,c=Math.floor((r-o)/2),h=Math.max(2,Math.floor((t-u)/2));n[h]?.put(c,`╭─ keys ${"─".repeat(o-9)}╮`);for(let f=h+1;f<h+u-1;f++)n[f]?.put(c,`│${" ".repeat(o-2)}│`);s.forEach(([f,g],l)=>{n[h+2+l]?.put(c+3,f,tr),n[h+2+l]?.put(c+13,g.slice(0,o-16))}),n[h+u-1]?.put(c,`╰${"─".repeat(o-2)}╯`),vt(n[t-1],r,i,{badge:"KEYS",right:["? esc","close"]})}function Nd(n,r,t){let e=r.suggest??[],i=e.map((u)=>u.count>0?String(u.count):u.palette??"0"),s=Math.max(...e.map((u)=>Yn(u.value))),o=Math.max(7,...i.map(Yn));e.forEach((u,c)=>{let h=c===r.pick,f=n[1+c];f?.run(0,[[h?"▸ ":" ",t],[u.value,h?tr+t:""]]),f?.right(2+s+2+o,[[i[c],cn]])})}function ec(n,r,t){let e=Array.from({length:t},()=>new ie(r)),i=[],s=xu(n.colors.cursor);if(r<jr.cols||t<jr.rows)return e[0]?.put(0,"ttheme find",tr+s),e[1]?.put(0,`needs ${jr.cols}×${jr.rows} — now ${r}×${t}`),e[2]?.put(0,"esc quits",cn),{lines:e.map((o)=>o.render()),images:i};if(n.mode==="try")Ed(e,i,r,t,n,s);else Md(e,i,r,t,n,s);if(n.mode==="grid"&&n.editing!==void 0&&n.suggest?.length){for(let o=1;o<t-1;o++)e[o]=new ie(r);return Nd(e,n,s),{lines:e.map((o)=>o.render()),images:[]}}if(n.help||n.panel!==void 0){let o=n.mode==="try"?i:[];for(let u=0;u<t;u++)e[u]=new ie(r);if(n.help)Id(e,r,t,n,s);else Fd(e,r,t,n,s);return{lines:e.map((u)=>u.render()),images:o}}return{lines:e.map((o)=>o.render()),images:i}}var yd=new Set(["comic","4koma","monochrome","greyscale","sketch","lineart","speech_bubble"]),Sd=new Set(["scenery","landscape","scenic","no_humans","wide_shot","very_wide_shot"]),Hd=0.04,jd=0.1,Gd=0.05,Od=4096;function Rd(n){return new Set(n.cutouts.split(/\s+/).map((r)=>r.replace(/^~/,"")).filter(Boolean))}function Jd(n,r,t,e=0){let{site:i,post:s}=n,o=new Set(s.tags),u=[...Rd(i)].some((f)=>o.has(f)),c=Math.min(s.width,s.height),h=s.width>0&&s.height>0?s.width/s.height/(r.w/r.h):1;return(s.solo?2:0)+([...yd].some((f)=>o.has(f))?-3:0)+([...Sd].some((f)=>o.has(f))?-1.5:0)+2*Math.min(1,c/r.h)+(u?1.5:-Math.min(1.5,Math.abs(Math.log(h))))+(t>0?1.5*Math.log1p(Math.max(0,s.score))/Math.log1p(t):0)+2*e}function se(n,r,t=new Map){let e=new Map;for(let{site:i,post:s}of n)e.set(i,Math.max(e.get(i)??0,s.score));return n.map((i,s)=>({pick:i,at:s,score:Jd(i,r,e.get(i.site)??0,t.get(i.post))})).sort((i,s)=>s.score-i.score||i.at-s.at).map(({pick:i})=>i)}function sc(n){let r=new Map;for(let e of n)r.set(e.site,[...r.get(e.site)??[],e]);let t=[];for(let e=0;t.length<n.length;e++)for(let i of r.values()){let s=i[e];if(s)t.push(s)}return t}function fi(n){let r=n/255;return r<=0.04045?r/12.92:((r+0.055)/1.055)**2.4}function ic(n,r,t){let[e,i,s]=[fi(n),fi(r),fi(t)],o=Math.cbrt(0.4122214708*e+0.5363325363*i+0.0514459929*s),u=Math.cbrt(0.2119034982*e+0.6806995451*i+0.1073969566*s),c=Math.cbrt(0.0883024619*e+0.2817188376*i+0.6299787005*s);return[0.2104542553*o+0.793617785*u-0.0040720468*c,1.9779984951*o-2.428592205*u+0.4505937099*c,0.0259040371*o+0.7827717662*u-0.808675766*c]}function oc(n,r){let t=r.map((o)=>ic(...On(o))).filter(([,o,u])=>Math.hypot(o,u)>=Hd);if(t.length===0)return 0;let e=Math.max(1,Math.floor(Math.sqrt(n.width*n.height/Od))),i=t.map(()=>0),s=0;for(let o=0;o<n.height;o+=e)for(let u=0;u<n.width;u+=e){let c=(o*n.width+u)*4;if(n.data[c+3]<128)continue;s++;let[h,f,g]=ic(n.data[c],n.data[c+1],n.data[c+2]);t.forEach(([l,a,m],b)=>{if(Math.hypot(h-l,f-a,g-m)<jd)i[b]=i[b]+1})}if(s===0)return 0;return i.reduce((o,u)=>o+Math.min(1,u/s/Gd),0)/t.length}import{execFileSync as Kd}from"node:child_process";import{existsSync as gi,mkdirSync as oe,readFileSync as cc,rmSync as hc,writeFileSync as ue}from"node:fs";import{homedir as li}from"node:os";import{dirname as ce,join as Cn}from"node:path";var Ld={ghostty:ct,kitty:ft,alacritty:ut,iterm2:ht},uc="ttheme-default";function Vr(n=process.env.TTHEME_ITERM_SUITE??"com.googlecode.iterm2"){let r=(t,e)=>Kd(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 Yr(n){return n.keepTheme?void 0:Ar(n)}function Ft(n,r){if(!n.terminals.includes("iterm2"))return n;let t=r.read();return t&&!t.startsWith("ttheme-")?{...n,itermBase:t}:n}function It(n,r){if(!n.terminals.includes("iterm2"))return!1;let t=r.read(),e=Yr(n)?uc:t===uc?n.itermBase:void 0;if(!e||e===t)return!1;return r.write(e),!0}function _n(){return process.env.XDG_CONFIG_HOME??Cn(li(),".config")}function fc(n){return Cn(n,"Library","Application Support","iTerm2","DynamicProfiles","ttheme.json")}function gc(n){return Cn(n,"ttheme","installed.json")}function fr(n){let r=gc(n);if(!gi(r))throw Error(`nothing installed yet at ${r} — run \`ttheme init\` first`);let t=JSON.parse(cc(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)=>Tt.includes(e)),...t.startup?{startup:t.startup}:{},...t.keepTheme?{keepTheme:!0}:{},...t.itermBase?{itermBase:t.itermBase}:{},palettes:t.palettes}}function Nt(n,r){let t=gc(n);oe(ce(t),{recursive:!0}),ue(t,`${JSON.stringify(r,null,2)}
60
- `)}function di(n,r){return{name:n.name,group:n.group,...n.native?{native:n.native}:{},lead:n.lead===!0,order:n.order,...n.default?{role:"default"}:{},ansiSource:n.ansiSource,...n.booru?{booru:n.booru}:{},...n.booruSites?{booruSites:n.booruSites}:{},background:n.background,foreground:n.foreground,cursor:n.cursor,selectionBackground:n.selection,ansi:n.ansi,signature:n.signature,signatureSlots:n.signatureSlots,font:r.font,ghostty:{...r.shader?{shader:r.shader}:{},iconGhost:n.cursor,iconScreen:[n.cursor,n.selection,n.background]},waive:n.waived??[]}}function lc(n,r){let t=new Map(n.palettes.map((s)=>[s.name,s])),e=r.filter((s)=>!t.has(s));if(e.length>0)throw Error(`not in the catalog: ${e.join(", ")} — \`ttheme list\` shows what is there`);let i=r.flatMap((s)=>{let o=Zu(t.get(s));return o.length>0?[`${s}: ${o.join(", ")}`]:[]});if(i.length>0)throw Error(`these palettes fail the contrast gate:
77
+ }`;function wi(){return process.platform==="darwin"}function fc(n){return n>=Ia&&n<=Sa}function gc(n,r,e){return new Promise((t,i)=>{let o=Fa("osascript",["-l","JavaScript","-e",Na,n,r],{stdio:["ignore","ignore","pipe"],signal:AbortSignal.any([e,AbortSignal.timeout(ya)])}),s="";o.stderr.on("data",(u)=>{s+=u}),o.on("error",i),o.on("close",(u)=>{if(u===0){t();return}i(Error(s.trim().split(`
78
+ `).at(-1)||`osascript exited ${u}`))})})}var Un={pitch:25,cols:22,rows:9,height:13},Rr={cols:25,rows:16},Ha=2147483648,Oa=-1073741826,ja=1600,Ra="\x1B[0m",ir="\x1B[1m",cn="\x1B[2m",je="\x1B[31m",gr="\x1B[32m",Wn="\x1B[33m",dt="\x1B[1;34m",Ga="\x1B[35m",La={A:"up",B:"down",C:"right",D:"left",H:"home",F:"end","1~":"home","7~":"home","4~":"end","8~":"end","5~":"pgup","6~":"pgdn"};function dc(n){let r=[],e=0;while(e<n.length){let t=n[e]??"";if(t==="\x1B"){let i=/^(?:\[([0-9;]*)([A-Za-z~])|O([A-Za-z]))/.exec(n.slice(e+1));if(i){r.push(La[`${i[1]??""}${i[2]??i[3]??""}`]??"nop"),e+=1+i[0].length;continue}r.push("esc"),e++;continue}r.push(t==="\r"||t===`
79
+ `?"enter":t==="\t"?"tab":t==="\x03"?"ctrl-c":t===""||t==="\b"?"backspace":t),e++}return r}var mc="\x1B]1337;ReportCellSize\x07\x1B[16t",lc="\x1B]1337;ReportCellSize=";function ki(n){let r=n.indexOf(lc);if(r!==-1){let i=n.slice(r+lc.length),o=[i.indexOf("\x07"),i.indexOf("\x1B\\")].filter((c)=>c!==-1),s=o.length>0?Math.min(...o):-1,u=s===-1?null:/^([\d.]+);([\d.]+);([\d.]+)$/.exec(i.slice(0,s));if(u){let c=Number(u[3]);return{cell:{h:Math.round(Number(u[1])*c),w:Math.round(Number(u[2])*c)},rest:n.slice(0,r)+i.slice(s+(i[s]==="\x07"?1:2))}}}let e=n.indexOf("\x1B[6;"),t=e===-1?null:/^\[6;(\d+);(\d+)t/.exec(n.slice(e+1));if(!t)return null;return{cell:{h:Number(t[1]),w:Number(t[2])},rest:n.slice(0,e)+n.slice(e+1+t[0].length)}}function Tr(n,r){return{perRow:Math.max(1,Math.floor((n+1)/Un.pitch)),rowsVis:Math.max(1,Math.floor((r-4)/Un.height))}}function $c(n){return`\x1B_Ga=t,t=f,f=100,i=${n.id},q=2;${Buffer.from(n.path).toString("base64")}\x1B\\`}function wc(n){return`\x1B[${n.row+1};${n.col+1}H\x1B_Ga=p,i=${n.id},p=${n.id},c=${n.cols},r=${n.rows},C=1,z=${n.z},q=2\x1B\\`}function pc(n){return`\x1B_Ga=d,d=I,i=${n},q=2\x1B\\`}function bc(n){return`\x1B[38;2;${Gn(n).join(";")}m`}function pi(n){return`\x1B[48;2;${Gn(n).join(";")}m`}function zn(n){return Array.from(n).length}class mt{parts=[];cols;constructor(n){this.cols=n}put(n,r,e=""){return this.parts.push({col:n,text:r,sgr:e}),n+zn(r)}run(n,r){let e=n;for(let[t,i]of r)e=this.put(e,t,i);return e}right(n,r){this.run(n-r.reduce((e,[t])=>e+zn(t),0),r)}render(){let n="";for(let{col:r,text:e,sgr:t}of this.parts){if(r>=this.cols||r<0)continue;let i=Array.from(e).slice(0,this.cols-r).join("");n+=`\x1B[${r+1}G${t}${i}${t?Ra:""}`}return n}}function kc(n){return n>=1e6?`${(n/1e6).toFixed(1)} MB`:`${Math.max(1,Math.round(n/1000))} KB`}function Ja(n,r){if(!r)return kc(n);return r>=1e6?`${(n/1e6).toFixed(1)}/${(r/1e6).toFixed(1)} MB`:`${Math.round(n/1000)}/${Math.round(r/1000)} KB`}function Mc(n){return n.replace(/_\([^)]*\)?$/,"")}function Ec(n){return[`${n.reduced?"↓":""}${n.width}×${n.height}`,Math.max(n.width,n.height)<ja?Wn:cn]}function Re(n,r,e,t){let i=[...t.keys??[]],o=t.lead,s=t.right,u=()=>{let f=[...o?[zn(o[0])]:[],...i.map(([g,d])=>zn(g)+1+zn(d))];return(t.badge?zn(t.badge)+4:0)+f.reduce((g,d)=>g+d,0)+3*Math.max(0,f.length-1)+(s?3+zn(s[0])+1+zn(s[1]):0)};while(u()>r)if(i.length>2)i.splice(-2,1);else if(s)s=void 0;else if(i.length>1)i.splice(-2,1);else break;if(o&&u()>r){let f=Math.max(0,zn(o[0])-(u()-r)-1);o=[`${Array.from(o[0]).slice(0,f).join("")}…`,o[1]]}let c=0;if(t.badge)c=n.put(0,` ${t.badge} `,`\x1B[7;1m${e}`)+2;if([...o?[[o]]:[],...i.map(([f,l])=>[[f,ir],[` ${l}`,cn]])].forEach((f,l)=>{c=n.run(c+(l?3:0),f)}),s)n.right(r,[[s[0],ir],[` ${s[1]}`,cn]])}function Ka(n,r,e,t,i,o){let{ansi:s,selection:u,cursor:c}=o.colors,h=t<44?3:4;if(t>=56)h=Math.min(7,Math.floor((t+1)/8)-1);let f=e;for(let w=0;w<8;w++)f=(n[r]?.put(f,"▀".repeat(h),bc(s[w]??c)+pi(s[w+8]??c))??f)+1;let l=["❯ ",gr],g=[[["~/code/demo",dt],[" on ",cn],["main",Ga],[" +2",gr],[" ~1",Wn]]];if(g.push([l,["git status -sb",""]]),t>=44)g.push([["## ",""],["main",gr],["...",""],["origin/main",je],[" [ahead 1]",Wn]]);if(g.push([[" M",je],[" src/main.rs",""]]),g.push([["??",je],[" notes.md",""]]),g.push([]),t>=44)g.push([l,["ls",""]]),g.push([["docs",dt],[" ",""],["src",dt],[" ",""],["tests",dt],[" Cargo.toml README.md",""]]),g.push([]);g.push([l,["cargo test",""]]),g.push([[" ✓",gr],[" parses config",""]]);let d=[[" ✗",je],[" renders frame",""]];if(t>=44)d.push([" expected ",cn],["3",gr],[", received ",cn],["2",je]);g.push(d),g.push([]),g.push([l,["echo ",""],["selected text",pi(u)],[" ",""],[" ",pi(c)]]),g.forEach((w,m)=>{let b=r+2+m;if(b<=i)n[b]?.run(e,w)})}function Pa(n,r,e,t,i,o){n[r]?.put(e,`╭${"─".repeat(i-2)}╮`,o);for(let s=r+1;s<r+t-1;s++)n[s]?.put(e,"│",o),n[s]?.put(e+i-1,"│",o);n[r+t-1]?.put(e,`╰${"─".repeat(i-2)}╯`,o)}function bi(n,r=n.site,e=n.siteAnsi){return[` ${r} `,`\x1B[7;${30+e}m`]}function Ua(n){return`${Mn[Math.floor(n/Or)]?.name??""} ${n%Or}`}function Qa(n,r,e){let t=[{name:"all",moved:!1},...Mn].flatMap((s,u)=>{let c=`${s.name}${s.moved?"*":""}`,h=s.name===e.site?bi(e,c):[` ${c} `,cn];return u?[[" ",""],h]:[h]}),i=t.reduce((s,[u])=>s+zn(u),0)<=r,o=n.run(0,i?t:[bi(e)]);if(e.asking!==void 0)n.run(o,[[` ${e.asking} was cut off — this network may block it. turn on the unblock proxy? `,Wn],["y",ir],[" turn on ",cn],["n",ir],[" not now",cn]])}function Wa(n,r,e,t){if(e.editing!==void 0){let u=n.run(0,[["⌕ ",t],[e.editing,""],["█",t]]),c=e.suggest?.length?" ↑↓ pick enter searches":" enter searches";n.put(u,e.editing?c:` a tag, a post url or an id — ${e.tag||"esc leaves"}`,cn);return}let i=n.run(0,[["⌕ ",t],[e.tag||"nothing yet — / searches",e.tag?"":cn]]),o=Hr.filter((u)=>!e.block.includes(u)),s=[e.preset,...e.solo?["solo"]:[],e.order,...e.rating.join("+")==="safe"?[]:[e.rating.join("+")],...o.length>0?[`allows ${o.join("+")}`]:[],...e.unblocked?["unblock"]:[]];if(n.put(i,` ${s.join(" ")}`,cn),e.total>0||!e.searching){let u=[[`${e.tiles.length}/${e.checked}`,""]];if(e.checked<e.total)u.push([` of ${e.total}`,cn]);n.right(r,u)}}function Za(n){if(n.cut==="on")return[[`cut out · ${n.clear}% transparent`,gr]];if(n.cut==="off")return[["opaque · x cuts out",Wn]];if(n.cut==="failed")return[["opaque · no cut-out",Wn]];return[n.clear>0?[`${n.clear}% transparent`,gr]:["opaque",Wn]]}function ac(n){return n.site==="all"?"any site":n.site}function vc(n){if(n.installing!==void 0)return[`installing ${n.palette} ← ${Ua(n.installing)}`,Wn];if(n.error)return[n.error,Wn];if(n.waiting!==void 0)return[`${n.slow??n.site} asked to slow down · ${n.waiting}s`,Wn];if(n.fetching)return[`fetching ${n.fetching.id%Or} · ${Ja(n.fetching.got,n.fetching.size)}`,Wn];if(n.cutting!==void 0)return[`cutting out ${n.cutting%Or}`,Wn];if(n.preparing!==void 0)return[`preparing ${n.preparing%Or}`,Wn];if(n.saved)return[n.saved,gr];if(n.note)return[n.note,cn];return}function qa(n,r,e,t,i,o){let{perRow:s,rowsVis:u}=Tr(e,t);Wa(n[0],e,i,o),Qa(n[1],e,i);for(let d=0;d<s*u;d++){let w=i.top*s+d,m=i.tiles[w];if(!m)break;let b=2+Math.floor(d/s)*Un.height,F=d%s*Un.pitch,S=w===i.focus;if(S)Pa(n,b,F,Un.height,Un.pitch-1,o);if(m.thumb)r.push({id:m.key,path:m.thumb,row:b+1,col:F+1,cols:Un.cols,rows:Un.rows,z:-1});if(n[b+10]?.run(F+1,[...i.installed.includes(m.key)?[["✓ ",gr]]:[],...i.site==="all"?[["● ",`\x1B[${30+m.siteAnsi}m`]]:[],[String(m.id),S?ir:""],[" ",""],Ec(m)]),m.mates.length>0)n[b+10]?.put(F+Un.cols,"≈",o);let k=m.artist?Mc(m.artist):m.owner&&`@${m.owner}`;if(k)n[b+11]?.put(F+1,k.slice(0,Un.cols-8),cn);let y=[];if(m.score>0)y.push([`★${m.score}`,cn]);if(m.variants>1)y.push([` ×${m.variants}`,o]);if(y.length>0)n[b+11]?.right(F+Un.cols+1,y)}let c=i.top*s,h=i.tiles.length-(i.top+u)*s,f=[...c>0?[`↑ ${c} above`]:[],...h>0?[`↓ ${h} more`]:[]];if(f.length>0)n[t-2]?.put(0,f.join(" "),cn);if(!i.searching&&i.tiles.length===0&&!i.error)n[3]?.put(0,i.preset==="cutouts"?`no transparent cutouts of ${i.tag} on ${ac(i)} — c searches every post, tab tries ${i.nextSite}`:`no posts of ${i.tag} on ${ac(i)} — tab tries ${i.nextSite}`,cn);let l=n[t-1],g=vc(i);if(i.searching&&i.tiles.length===0&&!g){Re(l,e,o,{badge:"FIND",lead:[i.preset==="cutouts"?"checking png headers":"fetching posts",cn],right:["esc","back"]});return}Re(l,e,o,{badge:"FIND",lead:g,keys:i.asking!==void 0?[]:[["←↑↓→","move"],["enter","try on"],["tab","site"],["s","settings"],["/","search"],["?","keys"]],right:i.asking!==void 0?void 0:["esc","back"]})}function Aa(n,r,e,t,i,o){let s=i.tiles[i.focus];if(!s)return;let u=i.shown?.id===s.key?i.shown:void 0,c=[bi(i,s.site,s.siteAnsi),[" ",""],[String(s.id),ir],[" ",""],Ec(s)];if(s.artist)c.push([` · ${Mc(s.artist)}`,""]);if(s.score>0)c.push([` · ★${s.score}`,cn]);if(u)c.push([` · ${kc(u.bytes)}`,cn]);if(c.push([` · ${s.owner}`,cn]),s.origin)c.push([` · ${s.origin}`,cn]);if(u)c.push([" ",""],...Za(u));if(n[0]?.run(0,c),s.mates.length>0)n[0]?.right(e,[["≈ ",o],[s.mates.join(" "),cn]]);if(Ka(n,3,2,e-4,t-2,i),i.shown)r.push({id:Ha+i.shown.id,path:i.shown.path,row:0,col:0,cols:e,rows:t,z:Oa});let h=vc(i);Re(n[t-1],e,o,{badge:"TRY",lead:h,keys:i.installing===void 0?[["←→","browse"],["enter","install"],...i.shown?.cut==="on"||i.shown?.cut==="off"?[["x","cut out"]]:[],["?","keys"]]:[],right:i.installing===void 0?["esc","grid"]:void 0})}var Xa={grid:[["move","←↑↓→ home end pgup pgdn"],["try on","enter"],["site",`tab all, ${Mn.map((n)=>n.name).join(", ")}`],["posts","c cutouts or every post"],["search","/ a tag, a post url or an id"],["unfold","space a set of ×N"],["open","o the post page in a browser"],["settings","s rating, block, posts, solo, order, sets, remove bg"],["back","esc returns to preview"],["close","? esc"]],try:[["browse","←→"],["install","enter"],["cut out","x the background off or on, on an opaque picture"],["open","o the post page in a browser"],["grid","esc"],["close","? esc"]]};function Ta(n,r,e,t,i){let o=t.panel??0,s=Math.max(...t.settings.map((g)=>g.label.length)),u=Math.max(...t.settings.map((g)=>g.choices.reduce((d,w)=>d+w.length+(g.multi?6:3),0))),c=Math.min(r-2,Math.max(28,s+u+8)),h=t.settings.length+4,f=Math.floor((r-c)/2),l=Math.max(2,Math.floor((e-h)/2));n[l]?.put(f,`╭─ settings ${"─".repeat(Math.max(0,c-13))}╮`);for(let g=l+1;g<l+h-1;g++)n[g]?.put(f,`│${" ".repeat(c-2)}│`);t.settings.forEach((g,d)=>{let w=n[l+2+d];w.put(f+3,g.label,d===o?ir:cn);let m=f+5+s,b=g.value.split(" ");g.choices.forEach((F,S)=>{let k=b.includes(F),y=g.multi&&d===o&&S===g.cursor?"4;":"",p=g.multi?` ${k?"[x]":"[ ]"} ${F} `:` ${F} `;m=w.put(m,p,k?`\x1B[${y}7;${30+t.siteAnsi}m`:y?`\x1B[4m${cn}`:cn)+1})}),n[l+h-1]?.put(f,`╰${"─".repeat(c-2)}╯`),Re(n[e-1],r,i,{badge:"SET",keys:[["↑↓","setting"],["←→","value"],["space","toggle"],["enter","save"]],right:["esc","undo"]})}function Va(n,r,e,t,i){let o=Xa[t.mode],s=Math.min(r-2,50),u=o.length+4,c=Math.floor((r-s)/2),h=Math.max(2,Math.floor((e-u)/2));n[h]?.put(c,`╭─ keys ${"─".repeat(s-9)}╮`);for(let f=h+1;f<h+u-1;f++)n[f]?.put(c,`│${" ".repeat(s-2)}│`);o.forEach(([f,l],g)=>{n[h+2+g]?.put(c+3,f,ir),n[h+2+g]?.put(c+13,l.slice(0,s-16))}),n[h+u-1]?.put(c,`╰${"─".repeat(s-2)}╯`),Re(n[e-1],r,i,{badge:"KEYS",right:["? esc","close"]})}function za(n,r,e){let t=r.suggest??[],i=t.map((u)=>u.count>0?String(u.count):u.palette??"0"),o=Math.max(...t.map((u)=>zn(u.value))),s=Math.max(7,...i.map(zn));t.forEach((u,c)=>{let h=c===r.pick,f=n[1+c];f?.run(0,[[h?"▸ ":" ",e],[u.value,h?ir+e:""]]),f?.right(2+o+2+s,[[i[c],cn]])})}function Fc(n,r,e){let t=Array.from({length:e},()=>new mt(r)),i=[],o=bc(n.colors.cursor);if(r<Rr.cols||e<Rr.rows)return t[0]?.put(0,"ttheme find",ir+o),t[1]?.put(0,`needs ${Rr.cols}×${Rr.rows} — now ${r}×${e}`),t[2]?.put(0,"esc quits",cn),{lines:t.map((s)=>s.render()),images:i};if(n.mode==="try")Aa(t,i,r,e,n,o);else qa(t,i,r,e,n,o);if(n.mode==="grid"&&n.editing!==void 0&&n.suggest?.length){for(let s=1;s<e-1;s++)t[s]=new mt(r);return za(t,n,o),{lines:t.map((s)=>s.render()),images:[]}}if(n.help||n.panel!==void 0){let s=n.mode==="try"?i:[];for(let u=0;u<e;u++)t[u]=new mt(r);if(n.help)Va(t,r,e,n,o);else Ta(t,r,e,n,o);return{lines:t.map((u)=>u.render()),images:s}}return{lines:t.map((s)=>s.render()),images:i}}var Ya=new Set(["comic","4koma","monochrome","greyscale","sketch","lineart","speech_bubble"]),Ca=new Set(["scenery","landscape","scenic","no_humans","wide_shot","very_wide_shot"]),_a=0.04,Ba=0.1,xa=0.05,Da=4096;function nd(n){return new Set(n.cutouts.split(/\s+/).map((r)=>r.replace(/^~/,"")).filter(Boolean))}function rd(n,r,e,t=0){let{site:i,post:o}=n,s=new Set(o.tags),u=[...nd(i)].some((f)=>s.has(f)),c=Math.min(o.width,o.height),h=o.width>0&&o.height>0?o.width/o.height/(r.w/r.h):1;return(o.solo?2:0)+([...Ya].some((f)=>s.has(f))?-3:0)+([...Ca].some((f)=>s.has(f))?-1.5:0)+2*Math.min(1,c/r.h)+(u?1.5:-Math.min(1.5,Math.abs(Math.log(h))))+(e>0?1.5*Math.log1p(Math.max(0,o.score))/Math.log1p(e):0)+2*t}function $t(n,r,e=new Map){let t=new Map;for(let{site:i,post:o}of n)t.set(i,Math.max(t.get(i)??0,o.score));return n.map((i,o)=>({pick:i,at:o,score:rd(i,r,t.get(i.site)??0,e.get(i.post))})).sort((i,o)=>o.score-i.score||i.at-o.at).map(({pick:i})=>i)}function Ic(n){let r=new Map;for(let t of n)r.set(t.site,[...r.get(t.site)??[],t]);let e=[];for(let t=0;e.length<n.length;t++)for(let i of r.values()){let o=i[t];if(o)e.push(o)}return e}function Mi(n){let r=n/255;return r<=0.04045?r/12.92:((r+0.055)/1.055)**2.4}function yc(n,r,e){let[t,i,o]=[Mi(n),Mi(r),Mi(e)],s=Math.cbrt(0.4122214708*t+0.5363325363*i+0.0514459929*o),u=Math.cbrt(0.2119034982*t+0.6806995451*i+0.1073969566*o),c=Math.cbrt(0.0883024619*t+0.2817188376*i+0.6299787005*o);return[0.2104542553*s+0.793617785*u-0.0040720468*c,1.9779984951*s-2.428592205*u+0.4505937099*c,0.0259040371*s+0.7827717662*u-0.808675766*c]}function Sc(n,r){let e=r.map((s)=>yc(...Gn(s))).filter(([,s,u])=>Math.hypot(s,u)>=_a);if(e.length===0)return 0;let t=Math.max(1,Math.floor(Math.sqrt(n.width*n.height/Da))),i=e.map(()=>0),o=0;for(let s=0;s<n.height;s+=t)for(let u=0;u<n.width;u+=t){let c=(s*n.width+u)*4;if(n.data[c+3]<128)continue;o++;let[h,f,l]=yc(n.data[c],n.data[c+1],n.data[c+2]);e.forEach(([g,d,w],m)=>{if(Math.hypot(h-g,f-d,l-w)<Ba)i[m]=i[m]+1})}if(o===0)return 0;return i.reduce((s,u)=>s+Math.min(1,u/o/xa),0)/e.length}import{execFileSync as ed,spawn as td}from"node:child_process";import{existsSync as or,mkdirSync as Le,readFileSync as Vr,rmSync as vi,utimesSync as id,writeFileSync as zr}from"node:fs";import{homedir as wt}from"node:os";import{dirname as Je,join as bn}from"node:path";var od={ghostty:de,kitty:$e,alacritty:ae,wezterm:Ne,iterm2:me,"windows-terminal":He,warp:Se},Nc="ttheme-default";function Yr(n=process.env.TTHEME_ITERM_SUITE??"com.googlecode.iterm2"){let r=(e,t)=>ed(e,t,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();return{read:()=>{try{return process.platform==="darwin"?r("defaults",["read",n,"Default Bookmark Guid"])||void 0:void 0}catch{return}},write:(e)=>{if(process.platform==="darwin")r("defaults",["write",n,"Default Bookmark Guid","-string",e])},running:()=>{try{return r("pgrep",["-x","iTerm2"])!==""}catch{return!1}}}}function Cr(n){return n.keepTheme?void 0:_r(n)}function Ke(n,r){if(!n.terminals.includes("iterm2"))return n;let e=r.read();return e&&!e.startsWith("ttheme-")?{...n,itermBase:e}:n}function Pe(n,r){if(!n.terminals.includes("iterm2"))return!1;let e=r.read(),t=Cr(n)?Nc:e===Nc?n.itermBase:void 0;if(!t||t===e)return!1;return r.write(t),!0}function xn(){return process.env.XDG_CONFIG_HOME??bn(wt(),".config")}function Hc(n){return bn(n,"Library","Application Support","iTerm2","DynamicProfiles","ttheme.json")}function Oc(n){return bn(n,"ttheme","installed.json")}function lr(n){let r=Oc(n);if(!or(r))throw Error(`nothing installed yet at ${r} — run \`ttheme init\` first`);let e=JSON.parse(Vr(r,"utf8"));if(!Array.isArray(e?.palettes)||!Array.isArray(e.terminals))throw Error(`${r} has no palettes or terminals`);return{terminals:e.terminals.filter((t)=>it.includes(t)),...e.startup?{startup:e.startup}:{},...e.keepTheme?{keepTheme:!0}:{},...e.itermBase?{itermBase:e.itermBase}:{},...e.wtHome?{wtHome:e.wtHome}:{},...e.wtProfile?{wtProfile:e.wtProfile}:{},palettes:e.palettes}}function Ue(n,r){let e=Oc(n);Le(Je(e),{recursive:!0}),zr(e,`${JSON.stringify(r,null,2)}
80
+ `)}function Ge(n,r){return{name:n.name,group:n.group,...n.native?{native:n.native}:{},lead:n.lead===!0,order:n.order,...n.default?{role:"default"}:{},ansiSource:n.ansiSource,...n.booru?{booru:n.booru}:{},...n.booruSites?{booruSites:n.booruSites}:{},background:n.background,foreground:n.foreground,cursor:n.cursor,selectionBackground:n.selection,ansi:n.ansi,signature:n.signature,signatureSlots:n.signatureSlots,font:r.font,ghostty:{...r.shader?{shader:r.shader}:{},iconGhost:n.cursor,iconScreen:[n.cursor,n.selection,n.background]},waive:n.waived??[]}}function jc(n,r){let e=new Map(n.palettes.map((o)=>[o.name,o])),t=r.filter((o)=>!e.has(o));if(t.length>0)throw Error(`not in the catalog: ${t.join(", ")} — \`ttheme list\` shows what is there`);let i=r.flatMap((o)=>{let s=sc(e.get(o));return s.length>0?[`${o}: ${s.join(", ")}`]:[]});if(i.length>0)throw Error(`these palettes fail the contrast gate:
61
81
  ${i.join(`
62
- `)}`);return n.palettes.filter((s)=>r.includes(s.name))}function dc(n,r){return(Ld[n].emit?.(r)??[]).flatMap((t)=>{let[,e,i]=t.path.split("/");return e==="themes"&&i!==void 0?[{file:i,content:t.content}]:[]})}function Ar(n){return n.startup&&n.palettes.includes(n.startup)?n.startup:n.palettes[0]}function Qd(n,r,t){let e=Cn(r,"ttheme");if(n==="ghostty")return{file:Cn(r,"ghostty","config"),body:Nu(e,t)};if(n==="kitty")return{file:Cn(r,"kitty","kitty.conf"),body:ju(t)};let i=t?Cn(r,"alacritty","themes",`${t}.toml`):void 0;return{file:Cn(r,"alacritty","alacritty.toml"),body:Gu(i)}}function ac(n,r,t,e,i){let s=Ur(n),o=t.map((h)=>di(h,r)),u=new Map;for(let h of o){let f=Po(s,h.name,i);if(f)u.set(h.name,f)}let c=new Set(Wr(t).map((h)=>h.name));return ks(o.filter((h)=>c.has(h.name)),u,o.find((h)=>h.name===Yr(e)),e.itermBase)}function zr(n,r=li()){let t=fr(n);if(!t.terminals.includes("iterm2"))return;let e=Pn(n),i=fc(r);oe(ce(i),{recursive:!0}),ue(i,ac(n,e,lc(e,t.palettes),t,r))}function yt(n,r,t,e=li()){let i=lc(r,t.palettes),s=[],o=(h,f)=>{oe(ce(h),{recursive:!0}),ue(h,f),s.push(h)},u=Yr(t);for(let h of t.terminals){if(h==="iterm2"){o(fc(e),ac(n,r,i,t,e));continue}for(let a of i)for(let{file:m,content:b}of dc(h,di(a,r)))o(Cn(n,h,"themes",m),b);let{file:f,body:g}=Qd(h,n,u),l=gi(f)?cc(f,"utf8"):"";if(h==="alacritty"&&l!==""&&!l.includes("# ttheme begin"))continue;oe(ce(f),{recursive:!0}),ue(f,Ct(l,g)),s.push(f)}let c=Cn(n,"ttheme","palettes.zsh");return o(c,ti(i,u,t.terminals)),hc(`${c}.zwc`,{force:!0}),s}function ai(n,r,t,e){let i=[];for(let s of t)for(let o of r.palettes.filter((u)=>e.includes(u.name)))for(let{file:u}of dc(s,di(o,r))){let c=Cn(n,s,"themes",u);if(gi(c))hc(c,{force:!0}),i.push(c)}return i}import{mkdirSync as kc,readFileSync as pc,writeFileSync as Mc}from"node:fs";import{dirname as Ec}from"node:path";import{isMainThread as Ud,parentPort as vc,Worker as Wd}from"node:worker_threads";var Pd=/(?:^|[^0-9a-f])([0-9a-f]{32})(?:[^0-9a-f]|$)/i,Zd=[[/yande\.re\/post\/show\/(\d+)/,"yande"],[/konachan\.(?:com|net)\/post\/show\/(\d+)/,"konachan"],[/danbooru\.donmai\.us\/(?:posts|post\/show)\/(\d+)/,"danbooru"]];function mi(n){let r=/(\d+)_p(\d+)/.exec(n.source);return[...n.md5?[`md5:${n.md5}`]:[],...r&&n.source.includes("pximg")?[`pixiv:${r[1]}_p${r[2]}`]:[]]}function mc(n,r){let t=Pd.exec(r.source)?.[1]?.toLowerCase();return[`post:${n.key}:${r.id}`,...r.md5?[`md5:${r.md5}`]:[],...t&&t!==r.md5?[`md5:${t}`]:[],...Zd.flatMap(([e,i])=>{let s=e.exec(r.source)?.[1];return s?[`post:${i}:${Number(s)}`]:[]}),...r.family?[`family:${n.key}:${r.family}`]:[]]}function $c(n,r){let t=n.owner||n.artist;return t!==""&&t===(r.owner||r.artist)&&n.width===r.width&&n.height===r.height}function bc(n){let e=[];for(let s=0;s<8;s++){let o=Math.floor(s*n.height/8),u=Math.max(o+1,Math.floor((s+1)*n.height/8));for(let c=0;c<9;c++){let h=Math.floor(c*n.width/9),f=Math.max(h+1,Math.floor((c+1)*n.width/9)),g=0;for(let l=o;l<u;l++)for(let a=h;a<f;a++){let m=(l*n.width+a)*4,b=n.data[m+3]/255,E=0.299*n.data[m]+0.587*n.data[m+1]+0.114*n.data[m+2];g+=E*b+255*(1-b)}e.push(g/((f-h)*(u-o)))}}let i=0n;for(let s=0;s<8;s++)for(let o=0;o<8;o++)i=i<<1n|(e[s*9+o]>e[s*9+o+1]?1n:0n);return i.toString(16).padStart(16,"0")}function qd(n,r){let t=BigInt(`0x${n}`)^BigInt(`0x${r}`),e=0;while(t>0n)e+=Number(t&1n),t>>=1n;return e}function wc(n,r){if(n.width<=0||n.height<=0||r.width<=0||r.height<=0)return!1;return Math.abs(Math.log(n.width/n.height/(r.width/r.height)))<0.01&&qd(n.hash,r.hash)<=2}var Xd={thumb:"tile",match:"tile",show:"view",backdrop:"view"};function Vd(n){let r=Io(new Uint8Array(pc(n.from)),Te);if(n.job==="backdrop")return Ao(n.home,n.colors,n.tone,r,{...n.origin,bytes:new Uint8Array(pc(n.source))},n),0;if(n.job==="match")return{match:oc(r,n.colors),hash:bc(r)};if(n.job==="thumb")return kc(Ec(n.to),{recursive:!0}),Mc(n.to,Zr(yo(r,n.width,n.height))),0;let t=lt(r);return kc(Ec(n.to),{recursive:!0}),Mc(n.to,Zr(Qo(r,n.colors,n.tone,n.width,n.height))),t}function Yd(n){n.on("message",(r)=>{try{n.postMessage({id:r.id,value:Vd(r)})}catch(t){n.postMessage({id:r.id,error:t instanceof Error?t.message:String(t)})}})}class Fc{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 Wd(import.meta.filename);n.unref(),n.on("message",({id:t,value:e,error:i})=>{let s=this.waiting.get(t);if(this.waiting.delete(t),this.waiting.size===0)n.unref();if(i!==void 0)s?.no(Error(i));else s?.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 $i{lines=new Map;run(n){let r=Xd[n.job],t=this.lines.get(r);if(!t)t=new Fc,this.lines.set(r,t);return t.send(n)}close(){for(let n of this.lines.values())n.close();this.lines.clear()}}if(!Ud&&vc)Yd(vc);import{connect as Ad,createServer as zd}from"node:net";var Td=20,Ic=22;function bi(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 Cd(n,r=Td){let t=n.subarray(5);if(n[0]!==Ic||t.length<2)return[n];let e=Math.max(1,Math.min(r,t.length-1)),i=(s)=>bi([Uint8Array.from([n[0],n[1],n[2],s.length>>8,s.length&255]),s]);return[i(t.subarray(0,e)),i(t.subarray(e))]}function _d(n,r,t,e){let i=Ad(t,r,()=>{i.setNoDelay(!0),n.write(`HTTP/1.1 200 Connection Established\r
82
+ `)}`);return n.palettes.filter((o)=>r.includes(o.name))}function Rc(n,r){let e=n==="wezterm"?"colors":"themes";return(od[n].emit?.(r)??[]).flatMap((t)=>{let[,i,o]=t.path.split("/");return i===e&&o!==void 0?[{file:o,content:t.content}]:[]})}function pt(n){return process.platform==="darwin"?bn(n,".warp","themes"):bn(process.env.XDG_DATA_HOME??bn(n,".local","share"),"warp-terminal","themes")}function Ei(n,r,e){if(n==="warp")return pt(e);return bn(r,n,n==="wezterm"?"colors":"themes")}function sd(n,r){return process.platform==="darwin"?bn(n,".warp","settings.toml"):bn(r,"warp-terminal","settings.toml")}var ud='"dark"',cd="setTimeout(() => { const fs = require('node:fs'); const [file, next, seen] = process.argv.slice(-3); if (fs.readFileSync(file, 'utf8') === seen) fs.writeFileSync(file, next) }, 1500)";function hd(n,r,e,t){let i=sd(r,n);if(!or(i))return;let o=bn(n,"ttheme","warp.base"),s=Vr(i,"utf8"),u=Vu(s),c=u?.includes('path = "ttheme-')===!0,h;if(e){if(!c&&!or(o))Le(Je(o),{recursive:!0}),zr(o,u??"");h=zu(e)}else{if(!c)return;h=or(o)&&Vr(o,"utf8")||ud,vi(o,{force:!0})}let f=Yu(s,h);if(f===s)return;if(t)td(process.execPath,["-e",cd,i,f,s],{detached:!0,stdio:"ignore"}).unref();else zr(i,f);return i}function Fi(n,r){let e=bn(r,".wezterm.lua");return or(e)?e:bn(n,"wezterm","wezterm.lua")}function fd(n){return bn(n,"Microsoft","Windows Terminal","Fragments","ttheme","ttheme.json")}function gd(n){return[bn(n,"Packages","Microsoft.WindowsTerminal_8wekyb3d8bbwe","LocalState","settings.json"),bn(n,"Packages","Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe","LocalState","settings.json"),bn(n,"Microsoft","Windows Terminal","settings.json")].filter((r)=>or(r))}function ld(n){for(let r of n){let e=/"defaultProfile"\s*:\s*"(\{[0-9a-fA-F-]+\})"/.exec(Vr(r,"utf8"))?.[1];if(e)return e}return}function _r(n){return n.startup&&n.palettes.includes(n.startup)?n.startup:n.palettes[0]}function ad(n,r,e){let t=bn(r,"ttheme");if(n==="ghostty")return{file:bn(r,"ghostty","config"),body:Pu(t,e)};if(n==="kitty")return{file:bn(r,"kitty","kitty.conf"),body:Zu(e)};let i=e?bn(r,"alacritty","themes",`${e}.toml`):void 0;return{file:bn(r,"alacritty","alacritty.toml"),body:qu(i)}}function Gc(n,r,e,t,i){let o=Sr(n),s=e.map((h)=>Ge(h,r)),u=new Map;for(let h of s){let f=Cs(o,h.name,i);if(f)u.set(h.name,f)}let c=new Set(Ar(e).map((h)=>h.name));return jo(s.filter((h)=>c.has(h.name)),u,s.find((h)=>h.name===Cr(t)),t.itermBase)}function Br(n,r=wt()){let e=lr(n);if(!e.terminals.includes("iterm2"))return;let t=Qn(n),i=Hc(r);Le(Je(i),{recursive:!0}),zr(i,Gc(n,t,jc(t,e.palettes),e,r))}function Qe(n,r,e,t=wt()){let i=jc(r,e.palettes),o=[],s=(h,f)=>{Le(Je(h),{recursive:!0}),zr(h,f),o.push(h)},u=Cr(e);for(let h of e.terminals){if(h==="iterm2"){s(Hc(t),Gc(n,r,i,e,t));continue}if(h==="windows-terminal"){if(e.wtHome){let m=gd(e.wtHome),b=i.map((S)=>Ge(S,r));s(fd(e.wtHome),mi(b,e.wtProfile??ld(m),u));let F=new Date;for(let S of m)id(S,F,F)}continue}let f=u!==void 0&&h==="warp"&&!or(bn(pt(t),`ttheme-${u}.yaml`)),l=h==="warp"?hd(n,t,u,f):void 0;for(let m of i)for(let{file:b,content:F}of Rc(h,Ge(m,r)))s(bn(Ei(h,n,t),b),F);if(h==="warp"){if(l)o.push(l);continue}if(h==="wezterm"){let m=bn(n,"ttheme","wezterm.lua");s(m,Bu({path:m,colors:Ei("wezterm",n,t),backgrounds:Sr(n),...u?{startup:u}:{},palettes:i.map((S)=>Ge(S,r))}));let b=Fi(n,t),F=ct(or(b)?Vr(b,"utf8"):"",Au(m));if(F!==void 0)s(b,F);continue}let{file:g,body:d}=ad(h,n,u),w=or(g)?Vr(g,"utf8"):"";if(h==="alacritty"&&w!==""&&!w.includes("# ttheme begin"))continue;Le(Je(g),{recursive:!0}),zr(g,ot(w,d)),o.push(g)}let c=bn(n,"ttheme","palettes.zsh");return s(c,ai(i,u,e.terminals)),vi(`${c}.zwc`,{force:!0}),o}function yi(n,r,e,t,i=wt()){let o=[];for(let s of e)for(let u of r.palettes.filter((c)=>t.includes(c.name)))for(let{file:c}of Rc(s,Ge(u,r))){let h=bn(Ei(s,n,i),c);if(or(h))vi(h,{force:!0}),o.push(h)}return o}import{mkdirSync as Uc,readFileSync as Qc,writeFileSync as Wc}from"node:fs";import{dirname as Zc}from"node:path";import{isMainThread as wd,parentPort as qc,Worker as pd}from"node:worker_threads";var dd=/(?:^|[^0-9a-f])([0-9a-f]{32})(?:[^0-9a-f]|$)/i,md=[[/yande\.re\/post\/show\/(\d+)/,"yande"],[/konachan\.(?:com|net)\/post\/show\/(\d+)/,"konachan"],[/danbooru\.donmai\.us\/(?:posts|post\/show)\/(\d+)/,"danbooru"]];function Ii(n){let r=/(\d+)_p(\d+)/.exec(n.source);return[...n.md5?[`md5:${n.md5}`]:[],...r&&n.source.includes("pximg")?[`pixiv:${r[1]}_p${r[2]}`]:[]]}function Lc(n,r){let e=dd.exec(r.source)?.[1]?.toLowerCase();return[`post:${n.key}:${r.id}`,...r.md5?[`md5:${r.md5}`]:[],...e&&e!==r.md5?[`md5:${e}`]:[],...md.flatMap(([t,i])=>{let o=t.exec(r.source)?.[1];return o?[`post:${i}:${Number(o)}`]:[]}),...r.family?[`family:${n.key}:${r.family}`]:[]]}function Jc(n,r){let e=n.owner||n.artist;return e!==""&&e===(r.owner||r.artist)&&n.width===r.width&&n.height===r.height}function Kc(n){let t=[];for(let o=0;o<8;o++){let s=Math.floor(o*n.height/8),u=Math.max(s+1,Math.floor((o+1)*n.height/8));for(let c=0;c<9;c++){let h=Math.floor(c*n.width/9),f=Math.max(h+1,Math.floor((c+1)*n.width/9)),l=0;for(let g=s;g<u;g++)for(let d=h;d<f;d++){let w=(g*n.width+d)*4,m=n.data[w+3]/255,b=0.299*n.data[w]+0.587*n.data[w+1]+0.114*n.data[w+2];l+=b*m+255*(1-m)}t.push(l/((f-h)*(u-s)))}}let i=0n;for(let o=0;o<8;o++)for(let s=0;s<8;s++)i=i<<1n|(t[o*9+s]>t[o*9+s+1]?1n:0n);return i.toString(16).padStart(16,"0")}function $d(n,r){let e=BigInt(`0x${n}`)^BigInt(`0x${r}`),t=0;while(e>0n)t+=Number(e&1n),e>>=1n;return t}function Pc(n,r){if(n.width<=0||n.height<=0||r.width<=0||r.height<=0)return!1;return Math.abs(Math.log(n.width/n.height/(r.width/r.height)))<0.01&&$d(n.hash,r.hash)<=2}var bd={thumb:"tile",match:"tile",show:"view",backdrop:"view"};function kd(n){let r=Ks(new Uint8Array(Qc(n.from)),ii);if(n.job==="backdrop")return tu(n.home,n.colors,n.tone,r,{...n.origin,bytes:new Uint8Array(Qc(n.source))},n),0;if(n.job==="match")return{match:Sc(r,n.colors),hash:Kc(r)};if(n.job==="thumb")return Uc(Zc(n.to),{recursive:!0}),Wc(n.to,Zr(Us(r,n.width,n.height))),0;let e=pe(r);return Uc(Zc(n.to),{recursive:!0}),Wc(n.to,Zr(Ys(r,n.colors,n.tone,n.width,n.height))),e}function Md(n){n.on("message",(r)=>{try{n.postMessage({id:r.id,value:kd(r)})}catch(e){n.postMessage({id:r.id,error:e instanceof Error?e.message:String(e)})}})}class Ac{worker;next=1;waiting=new Map;send(n){let r=this.next++;return new Promise((e,t)=>{let i=this.open();this.waiting.set(r,{ok:e,no:t}),i.ref(),i.postMessage({...n,id:r})})}close(){this.worker?.terminate(),this.worker=void 0,this.drop(Error("renderer closed"))}open(){if(this.worker)return this.worker;let n=new pd(import.meta.filename);n.unref(),n.on("message",({id:e,value:t,error:i})=>{let o=this.waiting.get(e);if(this.waiting.delete(e),this.waiting.size===0)n.unref();if(i!==void 0)o?.no(Error(i));else o?.ok(t)});let r=(e)=>{if(this.worker===n)this.worker=void 0;this.drop(e instanceof Error?e:Error("renderer stopped"))};return n.on("error",r),n.on("exit",()=>r(void 0)),this.worker=n,n}drop(n){for(let r of this.waiting.values())r.no(n);this.waiting.clear()}}class Si{lines=new Map;run(n){let r=bd[n.job],e=this.lines.get(r);if(!e)e=new Ac,this.lines.set(r,e);return e.send(n)}close(){for(let n of this.lines.values())n.close();this.lines.clear()}}if(!wd&&qc)Md(qc);import{connect as Ed,createServer as vd}from"node:net";var Fd=20,Xc=22;function Ni(n){let r=new Uint8Array(n.reduce((t,i)=>t+i.length,0)),e=0;for(let t of n)r.set(t,e),e+=t.length;return r}function yd(n,r=Fd){let e=n.subarray(5);if(n[0]!==Xc||e.length<2)return[n];let t=Math.max(1,Math.min(r,e.length-1)),i=(o)=>Ni([Uint8Array.from([n[0],n[1],n[2],o.length>>8,o.length&255]),o]);return[i(e.subarray(0,t)),i(e.subarray(t))]}function Id(n,r,e,t){let i=Ed(e,r,()=>{i.setNoDelay(!0),n.write(`HTTP/1.1 200 Connection Established\r
63
83
  \r
64
- `);let s=e,o=!1,u=(c)=>{if(o){i.write(c);return}if(s=bi([s,c]),s.length<5)return;let h=s[3]*256+s[4];if(s[0]!==Ic){o=!0,i.write(s);return}if(s.length<5+h)return;o=!0;let[f,g]=Cd(s.subarray(0,5+h));i.write(f),setTimeout(()=>{if(g)i.write(g);i.write(s.subarray(5+h))},10)};if(n.on("data",u),s.length>0){let c=s;s=new Uint8Array(0),u(c)}i.pipe(n)});i.on("error",()=>n.destroy()),i.on("close",()=>n.destroy()),n.on("error",()=>i.destroy()),n.on("close",()=>i.destroy())}function Bd(n){n.setNoDelay(!0);let r=new Uint8Array(0),t=(e)=>{r=bi([r,e]);let i=Buffer.from(r).toString("latin1"),s=i.indexOf(`\r
84
+ `);let o=t,s=!1,u=(c)=>{if(s){i.write(c);return}if(o=Ni([o,c]),o.length<5)return;let h=o[3]*256+o[4];if(o[0]!==Xc){s=!0,i.write(o);return}if(o.length<5+h)return;s=!0;let[f,l]=yd(o.subarray(0,5+h));i.write(f),setTimeout(()=>{if(l)i.write(l);i.write(o.subarray(5+h))},10)};if(n.on("data",u),o.length>0){let c=o;o=new Uint8Array(0),u(c)}i.pipe(n)});i.on("error",()=>n.destroy()),i.on("close",()=>n.destroy()),n.on("error",()=>i.destroy()),n.on("close",()=>i.destroy())}function Sd(n){n.setNoDelay(!0);let r=new Uint8Array(0),e=(t)=>{r=Ni([r,t]);let i=Buffer.from(r).toString("latin1"),o=i.indexOf(`\r
65
85
  \r
66
- `);if(s===-1)return;n.off("data",t);let o=/^CONNECT ([^ :]+):(\d+)/.exec(i);if(!o){n.end(`HTTP/1.1 405 Method Not Allowed\r
86
+ `);if(o===-1)return;n.off("data",e);let s=/^CONNECT ([^ :]+):(\d+)/.exec(i);if(!s){n.end(`HTTP/1.1 405 Method Not Allowed\r
67
87
  \r
68
- `);return}_d(n,o[1],Number(o[2]),r.subarray(s+4))};n.on("data",t),n.on("error",()=>n.destroy())}function Nc(){let n=zd(Bd);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 Cr=[{name:"TTHEME_FIND_RATING",label:"rating",choices:$t,multi:{read:At}},{name:"TTHEME_FIND_BLOCK",label:"block",choices:yr,multi:{read:zt,none:"none"}},{name:"TTHEME_FIND_POSTS",label:"posts",choices:["all","cutouts"]},{name:"TTHEME_FIND_SOLO",label:"solo",choices:["on","off"]},{name:"TTHEME_FIND_ORDER",label:"order",choices:["fit","newest","score"]},{name:"TTHEME_FIND_SETS",label:"sets",choices:["fold","show"]},...oi()?[{name:"TTHEME_FIND_REMOVE_BG",label:"remove bg",choices:["on","off"]}]:[]];function ta(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 ea=["fit","newest","score"];function Sc(n){return ea.find((r)=>r===n)??"fit"}function ia(n){return n.length>=2&&!/^\d+$/.test(n)&&!n.includes("://")&&!/^[\w.]+:\d+$/.test(n)}var Hc=12,sa=4,oa=150,jc=12,ua=2,ca=150,ha=30,fa=1280,Gc=2,ga=3,la=8;function ki(n,r){return{key:n,groups:[],sources:[],queue:[],rounds:0,roundOf:new Map,last:new Map,kin:new Map,kindred:new Map,shapes:[],seen:new Set,same:new Map,checked:0,total:0,focus:0,top:0,searching:r}}function he(n){if(!(n instanceof Error))return String(n);if(n instanceof AggregateError&&n.errors[0])return he(n.errors[0]);if(n.cause)return he(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 pi(n,r){return`${n}: ${he(r)}`}function Oc(n){return n.width*n.height}function Rc(n){return`${n.id}-${xd("sha1").update(n.preview).digest("hex").slice(0,8)}`}function da(n){let r=n.lastIndexOf("\x1B");return r!==-1&&/^\[?[0-9;]*$/.test(n.slice(r+1))}function Mi(n,r){try{return JSON.parse(Lc(gr(pr(n),r),"utf8"))}catch{return{}}}function Ei(n,r,t){vi(pr(n),{recursive:!0}),Fi(gr(pr(n),r),`${JSON.stringify(t)}
69
- `)}class Qc{view;tone;session=new AbortController;cell={w:0,h:0};cols=process.stdout.columns||80;rows=process.stdout.rows||24;gen=0;pumping=0;boards=new Map;board;posts=new Map;thumbPath=new Map;looking=new Map;looked=new Map;matched=new Map;aheading=!1;pages=new Map;tab=0;values=new Map(Cr.map((n)=>[n.name,ta(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 $i;sent=new Map;placed=new Map;current;fetch;settle;partial;suggestTimer;suggesting;input="";probeWait;done;dirty=!1;unblock=!1;scratch=Dd(gr(ra(),"ttheme-find-"));home;catalog;entry;constructor(n,r,t,e){this.home=n,this.catalog=r,this.entry=t,this.tone=Xt(t,t.signatureSlots),this.view={palette:t.name,tag:e,site:this.tabName,siteAnsi:this.tabAnsi,nextSite:this.nextTabName,preset:this.setting("TTHEME_FIND_POSTS")==="all"?"all":"cutouts",order:Sc(this.setting("TTHEME_FIND_ORDER")),solo:this.setting("TTHEME_FIND_SOLO")==="on",rating:At(this.setting("TTHEME_FIND_RATING")),block:zt(this.setting("TTHEME_FIND_BLOCK")),sets:this.setting("TTHEME_FIND_SETS")==="show"?"show":"fold",unblocked:process.env.TTHEME_FIND_PROXY!==void 0,settings:Cr.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:[],installed:[],checked:0,total:0,searching:e!=="",focus:0,top:0,mode:"grid",help:!1,editing:e===""?"":void 0},this.board=ki(this.boardKey,e!==""),this.boards.set(this.board.key,this.board)}get signal(){return this.session.signal}get site(){return this.tab===0?void 0:pn[this.tab-1]}get sites(){return this.site?[this.site]:pn}get tabName(){return this.site?.name??"all"}get tabAnsi(){return this.site?.ansi??sa}get nextTabName(){let n=(this.tab+1)%(pn.length+1);return n===0?"all":pn[n-1].name}frame(){return{w:this.cols*(this.cell.w||10),h:this.rows*(this.cell.h||20)}}setting(n){return this.values.get(n)}get boardKey(){return`${this.site?.key??"all"}|${this.view.preset}|${this.view.order}`}origPath(n,r,t){return gr(pr(n),"orig",`${r}.${t}`)}previewPath(n){return gr(pr(n.site),"thumb",`${Rc(n.post)}.${bt(n.post.preview)}`)}tileOf(n,r){let{site:t,post:e}=n,i=rr(t,e.id),s=kt(e)??e;return{id:e.id,key:i,site:t.name,siteAnsi:t.ansi,width:s.width,height:s.height,reduced:s!==e,owner:e.owner,artist:e.artist,score:e.score,variants:r,origin:_e(e.source),mates:this.owners.get(t.key)?.get(e.owner)??[],thumb:this.thumbPath.get(i)}}show(){let n=this.view,r=this.board;n.tiles=r.groups.flatMap((t)=>t.open?t.posts.map((e)=>this.tileOf(e,0)):[this.tileOf(t.posts[0],t.posts.length)]),n.checked=r.checked,n.total=r.total,n.searching=r.searching,n.note=r.note,n.focus=Math.max(0,Math.min(r.focus,n.tiles.length-1)),n.top=r.top}syncSite(){let n=this.view;n.site=this.tabName,n.siteAnsi=this.tabAnsi,n.nextSite=this.nextTabName}async run(){let{stdin:n,stdout:r}=process;n.setRawMode(!0),n.resume(),n.on("data",this.onData),r.on("resize",this.onResize),this.write("\x1B[?25l\x1B[?7l\x1B[H\x1B[K\x1B[2H\x1B[J\x1B[H");let t=new Promise((o)=>{this.done=o}),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 s=await t;return this.session.abort(),this.fetch?.abort(),clearTimeout(this.settle),clearTimeout(this.partial),this.quietSuggest(),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(),wi(this.scratch,{recursive:!0,force:!0}),lu(),s}write(n){process.stdout.write(n)}get saved(){return this.view.saved}finish(n){this.done?.(n===2&&this.saved?0:n)}probe(){return new Promise((n)=>{let r=setTimeout(()=>{this.probeWait=void 0,n(null)},1000);this.probeWait=(t)=>{clearTimeout(r),this.probeWait=void 0,n(t)},this.write(Tu)})}onData=(n)=>{this.input+=n.toString("utf8");for(let r=hi(this.input);r;r=hi(this.input))this.input=r.rest,this.probeWait?.(r.cell);if(this.probeWait)return;if(clearTimeout(this.partial),da(this.input)){this.partial=setTimeout(this.flushKeys,ha);return}this.flushKeys()};flushKeys=()=>{let n=zu(this.input);this.input="";for(let r of n)this.key(r)};onClock=()=>{let n=this.sites.reduce((e,i)=>wr(i)>wr(e)?i:e),r=Math.ceil((wr(n)-Date.now())/1000),t=r>0?r:void 0;if(t!==this.view.waiting)this.view.waiting=t,this.view.slow=n.name,this.draw()};onResize=()=>{if(this.cols=process.stdout.columns||this.cols,this.rows=process.stdout.rows||this.rows,this.scroll(),this.view.mode==="try"&&this.current)this.reveal();this.pump(),this.draw()};key(n){let r=this.view;if(n==="ctrl-c"){this.finish(2);return}if(r.installing!==void 0)return;if(r.asking!==void 0){this.askKey(n);return}if(r.editing!==void 0){this.editKey(n);return}if(r.panel!==void 0){this.panelKey(n);return}if(r.help){if(n==="?"||n==="esc")r.help=!1,this.draw();return}if(this.cols<jr.cols||this.rows<jr.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}=Xr(this.cols,this.rows),s={left:-1,right:1,up:-t,down:t,pgup:-t*e,pgdn:t*e,home:-r.focus,end:r.tiles.length}[n];if(s!==void 0){this.focus(r.focus+s);return}if(n==="enter"&&r.tiles[r.focus]){r.mode="try",r.error=void 0,this.select();return}if(n==="c"){r.preset=r.preset==="cutouts"?"all":"cutouts",this.turn();return}if(n==="tab"){this.tab=(this.tab+1)%(pn.length+1),this.syncSite(),this.turn();return}if(n==="/"){r.editing="",this.draw();return}if(n===" "){this.unfold();return}if(n==="o"){this.openPage();return}if(n==="s"){r.panel=0,this.draw();return}if(n==="esc")this.finish(2)}panelKey(n){let r=this.view,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 s=e.choices.indexOf(e.value);e.value=e.choices[(s+i+e.choices.length)%e.choices.length]}this.draw();return}if(n===" "&&e?.multi){let i=e.value.split(" "),s=e.choices.filter((u,c)=>c===e.cursor?!i.includes(u):i.includes(u)),o=e.multi.none;if(s.length>0||o!==void 0)e.value=s.length>0?s.join(" "):o,this.draw();return}if(n==="esc"){r.settings.forEach((i,s)=>{i.value=this.setting(Cr[s]?.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=Cr.map((e)=>this.setting(e.name));n.settings.forEach((e,i)=>{let s=Cr[i];if(s)this.values.set(s.name,e.value)});let t=Cr.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=zt(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=Sc(this.setting("TTHEME_FIND_ORDER")),n.solo=this.setting("TTHEME_FIND_SOLO")==="on",this.boards.clear(),this.current=void 0,n.shown=void 0,n.mode="grid",this.search()}save(n){this.store(n.map((r)=>[r.name,this.setting(r.name)]))}store(n){let r=gr(this.home,"ttheme","config.zsh");try{let t=Tr(r)?Lc(r,"utf8"):"";return Fi(r,n.reduce((e,[i,s])=>Bt(e,i,s),t)),!0}catch(t){return this.view.error=t instanceof Error?t.message:String(t),!1}}askKey(n){let r=this.view;if(n==="y"){if(r.asking=void 0,this.store([["TTHEME_FIND_UNBLOCK","1"]])){this.unblock=!0,this.finish(0);return}this.draw();return}if(n==="n"||n==="esc")r.asking=void 0,this.draw()}editKey(n){let r=this.view,t=r.editing??"",e=r.suggest??[];if((n==="up"||n==="down")&&e.length>0){let i=r.pick??-1,s=n==="down"?Math.min(e.length-1,i+1):i-1;r.pick=s<0?void 0:s,this.draw();return}if(n==="esc"||n==="enter")this.quietSuggest();if(n==="esc"){if(r.editing=void 0,r.tag===""){this.finish(2);return}this.draw();return}if(n==="enter"){let i=r.pick===void 0?void 0:e[r.pick],s=i?t.replace(/\S*$/,i.value):t;if(r.editing=void 0,r.suggest=void 0,r.pick=void 0,s.trim()){this.commit(s.trim());return}if(r.tag===""){this.finish(2);return}this.draw();return}if(n==="backspace"){r.editing=t.slice(0,-1),this.suggest(),this.draw();return}if(n.length===1&&n>=" ")r.editing=t+n,this.suggest(),this.draw()}quietSuggest(){clearTimeout(this.suggestTimer),this.suggesting?.abort(),this.suggesting=void 0}suggest(){this.quietSuggest();let n=this.view;n.pick=void 0;let r=/\S*$/.exec(n.editing??"")?.[0]??"";if(!ia(r)){n.suggest=void 0;return}let t=[...new Map(Uu(this.catalog.palettes,this.entry,r).map((i)=>[i.booru,{value:i.booru,count:0,palette:i.name}])).values()].slice(0,ga);n.suggest=t.length>0?t:void 0;let e=new AbortController;this.suggesting=e,this.suggestTimer=setTimeout(async()=>{try{let i=await bu(r,AbortSignal.any([this.signal,e.signal]));if(this.suggesting===e&&n.editing!==void 0){let s=new Map(i.map((u)=>[u.value,u.count])),o=new Set(t.map((u)=>u.value));n.suggest=[...t.map((u)=>({...u,count:s.get(u.value)??0})),...i.filter((u)=>!o.has(u.value))].slice(0,la),n.pick=n.pick!==void 0&&n.pick<t.length?n.pick:void 0,this.draw()}}catch{}},oa)}async commit(n){let r=ou(n,this.site??pn[0]);if(r){await this.jump(r.site,r.id);return}this.view.tag=n,this.boards.clear(),await this.search()}async jump(n,r){let t=++this.gen;this.tab=pn.indexOf(n)+1,this.syncSite(),this.current=void 0,this.view.shown=void 0,this.view.error=void 0;let e=ki(`${n.key}|post:${r}`,!0);this.board=e,this.boards.set(e.key,e),this.show(),this.draw();try{let i=await Be(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{let s={site:n,post:i};this.posts.set(rr(n,i.id),s),e.groups=[{posts:[s],open:!1}],e.checked=1,e.total=1,this.thumbQueue.push(s),this.thumbs(),this.view.mode="try"}if(this.show(),i)this.select();this.draw()}catch(i){this.fail(t,i,n)}}async turn(){this.fetch?.abort(),this.current=void 0,this.view.shown=void 0;let n=this.boards.get(this.boardKey);if(!n){await this.search();return}this.gen++,this.board=n,this.view.error=n.error,this.show(),this.draw(),await this.pump()}unfold(){let n=this.view,r=0;for(let 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(rr(i.site,i.post.id)))this.thumbQueue.push(i);this.thumbs(),this.show(),this.scroll(),this.draw();return}r+=e}}openPage(){let n=this.view.tiles[this.view.focus],r=n&&this.posts.get(n.key);if(!r)return;let t=process.platform==="darwin"?"open":"xdg-open";try{Kc(t,[r.site.pageUrl(r.post.id)],{stdio:"ignore",detached:!0}).unref()}catch{}}tryKey(n){let r=this.view;if(n==="left"||n==="right"){this.direction=n==="left"?-1:1,this.focus(r.focus+this.direction);return}if(n==="o"){this.openPage();return}if(n==="x"){this.swap();return}if(n==="enter"){this.install();return}if(n==="esc")this.fetch?.abort(),clearTimeout(this.settle),r.fetching=void 0,r.mode="grid",r.error=void 0,this.draw()}focus(n){let r=this.view;if(r.tiles.length===0)return;let 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}=Xr(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===this.entry.booru?Wu(this.entry,n.key):[r.tag];if(t.length===0)return;let e=t.length>1,i=r.preset==="cutouts"?n.cutouts:"",s=e&&i.includes("~"),o=[e?t.map((h)=>`~${h}`).join(" "):t[0],n.rate(this.view.rating),s?"":i,r.order==="score"?n.best:""].filter(Boolean),u=[],c=[];for(let h of o)if(Ce([...u,h].join(" "))<=n.tagBudget)u.push(h);else c.push(h);return{tags:u.join(" "),notes:[...c.length>0?[`${n.name} takes ${n.tagBudget} tags — ${c.join(" ")} left out`]:[],...s?[`${n.name} ORs the names, so cutouts are told by the file`]:[]]}}async search(){let n=++this.gen,r=ki(this.boardKey,!0);this.board=r,this.boards.set(r.key,r),this.view.error=void 0;let t=this.sites.flatMap((s)=>{let o=this.query(s);return o?[{site:s,...o}]:[]}),e=this.sites.filter((s)=>!t.some((o)=>o.site===s)),i=[...t.flatMap(({notes:s})=>s),...e.length>0?[`${this.entry.name} has no tag on ${e.map((s)=>s.name).join(", ")}`]:[]];if(r.note=i.length>0?i.join(" · "):void 0,t.length===0)r.searching=!1;this.show(),this.draw(),this.tally(n,r,t);try{let s=await Promise.all(t.map(async(o)=>({plan:o,owners:await this.mateOwners(o.site)})));if(n!==this.gen)return;r.sources=s.flatMap(({plan:{site:o,tags:u},owners:c})=>[...Ce(u)+1<=o.tagBudget?[...c.keys()].map((h)=>({site:o,tags:`${u} user:${h}`,page:0,done:!1})):[],{site:o,tags:u,page:0,done:!1}]),this.show(),this.draw(),await this.pump()}catch(s){this.fail(n,s)}}async tally(n,r,t){let e=await Promise.allSettled(t.map(({site:i,tags:s})=>au(i,s,this.signal)));if(n===this.gen)r.total=e.reduce((i,s)=>i+(s.status==="fulfilled"?s.value:0),0),this.show(),this.draw()}fail(n,r,t=this.site){if(n!==this.gen||this.signal.aborted)return;this.board.error=pi(t?.name??this.tabName,r),this.board.searching=!1,this.view.error=this.board.error,this.offer(t,r),this.show(),this.draw()}offer(n,r){if(n&&!this.view.unblocked&&Pc()&&he(r)==="ECONNRESET")this.view.asking=n.name}drop(n,r,t){for(let e of n.sources)if(e.site===r)e.done=!0;n.note=[n.note,pi(r.name,t)].filter(Boolean).join(" · "),this.offer(r,t)}wants(){let{perRow:n,rowsVis:r}=Xr(this.cols,this.rows);return this.view.tiles.length<(this.board.top+r+Gc)*n}need(){let{perRow:n,rowsVis:r}=Xr(this.cols,this.rows);return(r+Gc)*n}live(n){return this.boards.get(n.key)===n}page(n,r,t){let e=`${n.key}|${r}|${t}`,i=this.pages.get(e);if(!i)i=du(n,r,t,this.signal).then((s)=>this.borrow(s)),this.pages.set(e,i),i.catch(()=>this.pages.delete(e));return i}async borrow(n){let r=n.filter((t)=>t.solo===void 0&&t.md5!=="");if(r.length>0)try{mu(r,await $u(r.map((t)=>t.md5),this.signal))}catch{}return n}async round(n){let r=pn.flatMap((u)=>{let c=n.sources.find((h)=>h.site===u&&!h.done);return c?[c]:[]}),t=await Promise.all(r.map(async(u)=>{try{return{source:u,posts:await this.page(u.site,u.tags,u.page)}}catch(c){if(n.sources.every((h)=>h.site===u.site)||this.signal.aborted)throw c;return this.drop(n,u.site,c),{source:u,posts:void 0}}}));if(!this.live(n))return;let e=[];for(let{source:u,posts:c}of t){if(!c)continue;u.page++,u.done=c.length<Nr;let h=n.last.get(u);for(let f of c){let g=h&&$c(h.post,f)?h.set:`set:${u.site.key}:${f.id}`;h={post:f,set:g};let l=rr(u.site,f.id);if(n.seen.has(l))continue;n.seen.add(l);let a={site:u.site,post:f};if(this.eligible(a))n.kin.set(a,[g,...mc(u.site,f)]),e.push(a);else n.checked++}if(h)n.last.set(u,h)}let i=this.dedupe(n,e),s=++n.rounds,o;if(this.view.order!=="fit")o=r.length>1?sc(i):i;else{let u=se(i,this.frame(),this.matched),c=u.slice(0,this.need());if(await this.looks(c),!this.live(n))return;o=[...se(c,this.frame(),this.matched),...u.slice(c.length)]}for(let u of o)n.roundOf.set(u,s);n.queue.push(...o),this.ahead(n)}ahead(n){if(this.aheading||this.view.order!=="fit"||!this.live(n))return;let r=n.queue.slice(0,this.need()).filter((t)=>!this.looking.has(rr(t.site,t.post.id)));if(r.length===0)return;this.aheading=!0,this.looks(r).then(()=>{this.aheading=!1;for(let t of new Set(r.map((e)=>n.roundOf.get(e)??0)))this.resort(n,t);this.ahead(n)})}resort(n,r){let t=n.queue.flatMap((i,s)=>n.roundOf.get(i)===r?[s]:[]),e=se(t.map((i)=>n.queue[i]),this.frame(),this.matched);t.forEach((i,s)=>{n.queue[i]=e[s]})}dedupe(n,r){let t=[];for(let e of r){let i=mi(e.post),s=i.map((u)=>n.same.get(u)).find(Boolean);if(!s){for(let u of i)n.same.set(u,e);t.push(e);continue}if(n.checked++,Oc(e.post)<=Oc(s.post))continue;for(let u of[...i,...mi(s.post)])n.same.set(u,e);let o=t.indexOf(s);if(o>=0){t[o]=e;continue}this.replace(n,s,e)}return t}replace(n,r,t){n.roundOf.set(t,n.roundOf.get(r)??0);let e=n.queue.indexOf(r);if(e>=0){n.queue[e]=t;return}for(let i of n.groups){let s=i.posts.indexOf(r);if(s>=0){i.posts[s]=t,this.posts.set(rr(t.site,t.post.id),t),this.thumbQueue.push(t),this.thumbs();return}}}async looks(n){let r=0;await Promise.all(Array.from({length:jc},async()=>{while(r<n.length)await this.look(n[r++])}))}look(n){let r=rr(n.site,n.post.id),t=this.looking.get(r);if(!t)t=(async()=>{let e=this.previewPath(n);await this.cached(n.site,e,n.post.preview);let i=await this.renders.run({job:"match",from:e,colors:this.entry.signature});return this.looked.set(r,i),this.matched.set(n.post,i.match),i})().catch(()=>{return}),this.looking.set(r,t);return t}async pump(){let n=this.gen,r=this.board;if(this.pumping===n||r.sources.length===0)return;this.pumping=n;let t=[],e;try{r.searching=!0;while(n===this.gen){while(t.length<Hc&&r.queue.length>0&&this.wants()){let o=r.queue.shift();t.push({pick:o,passed:this.vet(o)})}if(this.ahead(r),!e&&r.queue.length<Hc&&r.sources.some((o)=>!o.done)&&this.wants()){let o=this.round(r).then(()=>{if(e===o)e=void 0});o.catch(()=>{}),e=o}let i=t.shift();if(!i){if(!e)break;await e,this.show(),this.draw();continue}let s=await i.passed;if(n!==this.gen)return;if(r.checked++,s)this.admit(i.pick);this.show(),this.draw()}if(n===this.gen)r.searching=!1,this.show(),this.draw()}catch(i){this.fail(n,i)}finally{if(this.saveProbes(),this.pumping===n)this.pumping=0}}eligible({site:n,post:r}){let t=kt(r);if(!hu(n,r,this.view.rating)||cu(r,this.view.block).length>0||!t)return!1;if(this.view.solo&&r.solo===!1)return!1;return this.view.preset==="all"?["png","jpg","jpeg"].includes(t.ext):r.ext==="png"}async vet(n){let[r]=await Promise.all([this.passes(n),this.look(n)]);return r}async passes({site:n,post:r}){return this.view.preset==="all"||n.vouched||this.transparent(n,r)}probes(n){let r=this.probed.get(n.key);if(!r)r=Mi(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 wu(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=pn.find((t)=>t.key===n);if(r)Ei(r,"probes.json",this.probes(r))}this.unsaved.clear()}admit(n){let{site:r,post:t}=n,e=this.board,i=rr(r,t.id);this.posts.set(i,n);let s=e.kin.get(n)??[],o=this.looked.get(i),u=o&&{hash:o.hash,width:t.width,height:t.height},c=this.view.sets==="fold"?this.kindred(e,s,u):void 0;if(c){if(c.posts.push(n),this.register(e,c,s,u),c.open)this.thumbQueue.push(n),this.thumbs();return}let h={posts:[n],open:!1};e.groups.push(h),this.register(e,h,s,u),this.thumbQueue.push(n),this.thumbs()}kindred(n,r,t){for(let e of r){let i=n.kindred.get(e);if(i)return i}return t&&n.shapes.find((e)=>wc(e.shape,t))?.group}register(n,r,t,e){for(let i of t)if(!n.kindred.has(i))n.kindred.set(i,r);if(e)n.shapes.push({shape:e,group:r})}async mateOwners(n){let r=this.owners.get(n.key);if(r)return r;let t=zo(this.home),e=Mi(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}]:[]}),s=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 Be(n,c.id,this.signal))?.owner??""}}catch{return}})),o=new Map;for(let c of s)if(c)e[c.id]=c.owner,o.set(c.name,c.owner);Ei(n,"owners.json",e);let u=fu(o);return this.owners.set(n.key,u),u}async cached(n,r,t,e){if(Tr(r))return na(r).size;let i=this.inflight.get(r);if(i)return i;let s=(async()=>{let o=await ku(n,t,this.signal,e);return vi(yc(r),{recursive:!0}),Fi(r,o),o.length})();this.inflight.set(r,s);try{return await s}finally{this.inflight.delete(r)}}thumbs(){while(this.thumbing<jc&&this.thumbQueue.length>0){let n=this.thumbQueue.shift();this.thumbing++,this.thumb(n).catch(()=>{}).finally(()=>{this.thumbing--,this.thumbs()})}}async thumb(n){let{site:r,post:t}=n,e=Qn.cols*this.cell.w,i=Qn.rows*this.cell.h,s=gr(pr(r),"tile",`${Rc(t)}-${e}x${i}.png`);if(!Tr(s)){let o=this.previewPath(n);await this.cached(r,o,t.preview),await this.renders.run({job:"thumb",from:o,to:s,width:e,height:i})}this.thumbPath.set(rr(r,t.id),s),this.show(),this.draw()}select(){let n=this.view,r=n.tiles[n.focus];if(this.fetch?.abort(),clearTimeout(this.settle),n.fetching=void 0,!r)return;if(this.current?.key===r.key){this.reveal();return}this.settle=setTimeout(()=>void this.load(r),ca),this.draw()}async load(n){let r=this.view,t=this.posts.get(n.key),e=t&&kt(t.post);if(!t||!e)return;let{site:i}=t,s=this.board,o=new AbortController;this.fetch=o;try{let u=this.origPath(i,n.id,e.ext);if(!Tr(u))r.fetching={id:n.key,got:0,size:0},this.draw();let c=await this.cached(i,u,e.file,(g,l)=>{if(r.fetching?.id===n.key)r.fetching={id:n.key,got:g,size:l},this.draw()});if(o.signal.aborted)return;if(r.fetching=void 0,s!==this.board)return;let h={site:i,id:n.id,key:n.key,path:u,ext:e.ext,size:c,using:"plain",failed:!1};r.preparing=n.key,this.flush();let f=await this.render(h,"plain");if(o.signal.aborted||s!==this.board)return;if(f.clear===0&&oi()&&this.setting("TTHEME_FIND_REMOVE_BG")!=="off"){if(r.preparing=void 0,r.cutting=n.key,this.flush(),h.cut=await this.cutOut(i,n.id,u,o.signal),o.signal.aborted||s!==this.board)return;if(r.cutting=void 0,h.cut){r.preparing=n.key,this.flush();let g=await this.render(h,"cut").catch(()=>{return});if(o.signal.aborted||s!==this.board)return;if(g&&Xu(g.clear))h.using="cut";else wi(h.cut,{force:!0}),h.cut=void 0,h.failed=!0}else h.failed=!0}if(this.current=h,r.tiles[r.focus]?.key===n.key)await this.present();this.preload()}catch(u){if(!o.signal.aborted&&!this.signal.aborted)r.error=pi(i.name,u)}finally{if(r.fetching?.id===n.key)r.fetching=void 0;if(r.preparing===n.key)r.preparing=void 0;if(r.cutting===n.key)r.cutting=void 0;this.draw()}}async cutOut(n,r,t,e){let i=gr(pr(n),"cut",`${r}.png`);if(Tr(i))return i;try{return vi(yc(i),{recursive:!0}),await Vu(t,i,e),i}catch{wi(i,{force:!0});return}}swap(){let n=this.current;if(!n?.cut||this.view.shown?.id!==n.key)return;n.using=n.using==="cut"?"plain":"cut",this.reveal()}preload(){let n=this.view;if(n.mode!=="try")return;for(let r of[n.focus+this.direction,n.focus-this.direction]){if(this.prefetching>=ua)return;let t=n.tiles[r],e=t&&this.posts.get(t.key),i=e&&kt(e.post);if(!e||!i)continue;let{site:s,post:o}=e,u=this.origPath(s,o.id,i.ext);this.prefetching++,this.cached(s,u,i.file).then(()=>this.render({site:s,id:o.id,key:t.key,path:u,ext:i.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,fa),s=Math.max(1,Math.round(e*i/t)),o=gr(this.scratch,`${n.site.key}-${n.id}${r==="cut"?"c":""}-${i}x${s}.png`),u=`${n.site.key}:${n.id}:${r}`,c=this.clarity.get(u);if(c!==void 0&&Tr(o))return{clear:c,path:o};let h=await this.renders.run({job:"show",from:r==="cut"?n.cut:n.path,to:o,width:i,height:s,colors:this.entry,tone:this.tone});return this.clarity.set(u,h),{clear:h,path:o}}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.key,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?.key,this.flush(),this.present().catch((r)=>{n.error=r instanceof Error?r.message:String(r)}).finally(()=>{if(n.preparing===this.current?.key)n.preparing=void 0;this.draw()})}async install(){let n=this.view,r=n.tiles[n.focus],t=this.current;if(!r||t?.key!==r.key||n.preparing!==void 0||n.shown?.id!==r.key)return;n.installing=r.key,n.error=void 0,this.flush();try{await this.renders.run({job:"backdrop",from: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)}`},width:this.cols*this.cell.w,height:this.rows*this.cell.h});let e=Mi(t.site,"owners.json");e[t.id]=this.posts.get(t.key)?.post.owner??"",Ei(t.site,"owners.json",e),zr(this.home),n.saved=`background · ${this.entry.name} ← ${t.site.name} ${t.id}`,n.installed.push(r.key),this.fetch?.abort(),clearTimeout(this.settle),n.fetching=void 0,n.mode="grid"}catch(e){n.error=e instanceof Error?e.message:String(e)}n.installing=void 0,this.draw()}draw(){if(this.dirty)return;this.dirty=!0,setImmediate(()=>{this.dirty=!1,this.flush()})}flush(){let n=ec(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+=Cu(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+=_u(e),this.placed.set(e.id,i)}for(let e of this.sent.keys())if(!t.has(e))r+=Bu(e),this.sent.delete(e),this.placed.delete(e);this.write(`${r}\x1B[?2026l`)}}function Pc(){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 Jc(){if(!Pc())return process.stderr.write(`unblock needs node 22.21 or newer — this is ${process.versions.node}
70
- `),1;let n=await Nc(),r=Kc(process.execPath,process.argv.slice(1),{stdio:"inherit",env:{...process.env,NODE_USE_ENV_PROXY:"1",NODE_NO_WARNINGS:"1",HTTPS_PROXY:`http://127.0.0.1:${n.port}`,NO_PROXY:[process.env.NO_PROXY,uu()].filter(Boolean).join(","),TTHEME_FIND_PROXY:String(n.port)}}),t=await new Promise((e)=>r.on("exit",(i)=>e(i??1)));return n.close(),t}async function Zc(n){if(process.env.TTHEME_FIND_UNBLOCK==="1"&&!process.env.TTHEME_FIND_PROXY)return Jc();let r=_n(),t=Pn(r),e=te(t.palettes,n);if(!process.stdin.isTTY||!process.stdout.isTTY)throw Error("ttheme find needs a terminal");let i=new Qc(r,t,e,e.booru??""),s=await i.run(),o=i.unblock?await Jc():s;if(i.saved&&o!==0)return process.stderr.write(`${i.saved}
71
- `),0;return o}function qc(n,r){let t=_n();if(te(Pn(t).palettes,n),r==="next"||r==="prev"){let{key:e,at:i,of:s}=Vo(t,n,r==="next"?1:-1);return zr(t),process.stderr.write(`background · ${n} ${i}/${s} ${e}
72
- `),0}if(r==="drop"){let{key:e,left:i}=Yo(t,n);return zr(t),process.stderr.write(`background · ${n} removed ${e??"the picture"} · ${i} left
73
- `),0}if(r==="tuned")return zr(t),0;throw Error(`unknown image action ${r} — next, prev, drop or tuned`)}import{chmodSync as am,copyFileSync as mm,existsSync as dr,mkdirSync as Ai,readdirSync as $m,readFileSync as jt,rmSync as qh,writeFileSync as Uh}from"node:fs";import{homedir as bm}from"node:os";import{dirname as Ht,join as wn}from"node:path";import{styleText as Gi}from"node:util";import{stdout as ih,stdin as Ha}from"node:process";import ja from"node:readline";var Uc=(()=>{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}})(),Wc=(n)=>{return n===12288||n>=65281&&n<=65376||n>=65504&&n<=65510},Xc=(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 aa=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,ma=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Vc=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,$a=/\t{1,1000}/y,Yc=/[\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,ba=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,wa=/\p{M}+/gu,ka={limit:1/0,ellipsis:""},Ac=(n,r={},t={})=>{let e=r.limit??1/0,i=r.ellipsis??"",s=r?.ellipsisWidth??(i?Ac(i,ka,t).width:0),o=0,u=t.controlWidth??0,c=t.tabWidth??8,h=t.emojiWidth??2,f=2,g=t.regularWidth??1,l=t.wideWidth??2,a=[[ba,g],[aa,0],[ma,u],[$a,c],[Yc,h],[Vc,l]],m=0,b=0,E=n.length,F=0,H=!1,p=E,I=Math.max(0,e-s),w=0,O=0,k=0,G=0;n:while(!0){if(O>w||b>=E&&b>m){let S=n.slice(w,O)||n.slice(m,b);F=0;for(let K of S.replaceAll(wa,"")){let R=K.codePointAt(0)||0;if(Wc(R))G=2;else if(Xc(R))G=l;else G=g;if(k+G>I)p=Math.min(p,Math.max(w,m)+F);if(k+G>e){H=!0;break n}F+=K.length,k+=G}w=O=0}if(b>=E)break n;for(let S=0,K=a.length;S<K;S++){let[R,z]=a[S];if(R.lastIndex=b,R.test(n)){if(F=R===Vc?Uc(n.slice(b,R.lastIndex)):R===Yc?1:R.lastIndex-b,G=F*z,k+G>I)p=Math.min(p,b+Math.floor((I-k)/z));if(k+G>e){H=!0;break n}k+=G,w=m,O=b,b=m=R.lastIndex;continue n}}b+=1}return{width:H?I:k,index:H?p:E,truncated:H,ellipsed:H&&e>=s}},zc=Ac;var pa={limit:1/0,ellipsis:"",ellipsisWidth:0},Ma=(n,r={})=>{return zc(n,pa,r).width},Kn=Ma;var fe="\x1B",xc="›",Ea=39,Ni="\x07",Dc="[",va="]",nh="m",yi=`${va}8;;`,Tc=new RegExp(`(?:\\${Dc}(?<code>\\d+)m|\\${yi}(?<uri>.*)${Ni})`,"y"),Cc=(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},_c=(n)=>`${fe}${Dc}${n}${nh}`,Bc=(n)=>`${fe}${yi}${n}${Ni}`,Ii=(n,r,t)=>{let e=r[Symbol.iterator](),i=!1,s=!1,o=n.at(-1),u=o===void 0?0:Kn(o),c=e.next(),h=e.next(),f=0;while(!c.done){let g=c.value,l=Kn(g);if(u+l<=t)n[n.length-1]+=g;else n.push(g),u=0;if(g===fe||g===xc)i=!0,s=r.startsWith(yi,f+1);if(i){if(s){if(g===Ni)i=!1,s=!1}else if(g===nh)i=!1}else if(u+=l,u===t&&!h.done)n.push(""),u=0;c=h,h=e.next(),f+=g.length}if(o=n.at(-1),!u&&o!==void 0&&o.length&&n.length>1)n[n.length-2]+=n.pop()},Fa=(n)=>{let r=n.split(" "),t=r.length;while(t){if(Kn(r[t-1]))break;t--}if(t===r.length)return n;return r.slice(0,t).join(" ")+r.slice(t).join("")},Ia=(n,r,t={})=>{if(t.trim!==!1&&n.trim()==="")return"";let e="",i,s,o=n.split(" "),u=[""],c=0;for(let g=0;g<o.length;g++){let l=o[g];if(t.trim!==!1){let m=u.at(-1)??"",b=m.trimStart();if(m.length!==b.length)u[u.length-1]=b,c=Kn(b)}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 a=Kn(l);if(t.hard&&a>r){let m=r-c,b=1+Math.floor((a-m-1)/r);if(Math.floor((a-1)/r)<b)u.push("");Ii(u,l,r),c=Kn(u.at(-1)??"");continue}if(c+a>r&&c&&a){if(t.wordWrap===!1&&c<r){Ii(u,l,r),c=Kn(u.at(-1)??"");continue}u.push(""),c=0}if(c+a>r&&t.wordWrap===!1){Ii(u,l,r),c=Kn(u.at(-1)??"");continue}u[u.length-1]+=l,c+=a}if(t.trim!==!1)u=u.map((g)=>Fa(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===fe||l===xc){Tc.lastIndex=g+1;let m=Tc.exec(h)?.groups;if(m?.code!==void 0){let b=Number.parseFloat(m.code);i=b===Ea?void 0:b}else if(m?.uri!==void 0)s=m.uri.length===0?void 0:m.uri}if(h[g+1]===`
75
- `){if(s)e+=Bc("");let a=i?Cc(i):void 0;if(i&&a)e+=_c(a)}else if(l===`
76
- `){if(i&&Cc(i))e+=_c(i);if(s)e+=Bc(s)}}return e},Na=/\r?\n/;function Mr(n,r,t){return String(n).normalize().split(Na).map((e)=>Ia(e,r,t)).join(`
77
- `)}var qn=Kt(Hi(),1);function lr(n,r,t){if(!t.some((o)=>!o.disabled))return n;let e=n+r,i=Math.max(t.length-1,0),s=e<0?i:e>i?0:e;return t[s]?.disabled?lr(s,r<0?-1:1,t):s}function ge(n,r,t,e){let i=e.split(`
78
- `),s=0,o=n;for(let c of i){if(o<=c.length)break;o-=c.length+1,s++}for(s=Math.max(0,Math.min(i.length-1,s+t)),o=Math.min(o,i[s].length)+r;o<0&&s>0;)s--,o+=i[s].length+1;for(;o>i[s].length&&s<i.length-1;)o-=i[s].length+1,s++;o=Math.max(0,Math.min(i[s].length,o));let u=0;for(let c=0;c<s;c++)u+=i[c].length+1;return u+o}var Ga=["up","down","left","right","space","enter","cancel"],Oa=["January","February","March","April","May","June","July","August","September","October","November","December"],Ln={actions:new Set(Ga),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:[...Oa],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 sh(n,r){if(typeof n=="string")return Ln.aliases.get(n)===r;for(let t of n)if(t!==void 0&&sh(t,r))return!0;return!1}function Ra(n,r){if(n===r)return;let t=n.split(`
79
- `),e=r.split(`
80
- `),i=Math.max(t.length,e.length),s=[];for(let o=0;o<i;o++)t[o]!==e[o]&&s.push(o);return{lines:s,numLinesBefore:t.length,numLinesAfter:e.length,numLines:i}}var I1=globalThis.process.platform.startsWith("win"),Oi=Symbol("clack:cancel");function _r(n){return n===Oi}function le(n,r){let t=n;t.isTTY&&t.setRawMode(r)}var ae=(n)=>("columns"in n)&&typeof n.columns=="number"?n.columns:80,Ji=(n)=>("rows"in n)&&typeof n.rows=="number"?n.rows:20;function Er(n,r,t,e=t,i=t,s){let o=ae(n??ih);return Mr(r,o-t.length,{hard:!0,trim:!1}).split(`
81
- `).map((u,c,h)=>{let f=s?s(u,c):u;return c===0?`${e}${f}`:c===h.length-1?`${i}${f}`:`${t}${f}`}).join(`
82
- `)}function oh(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 er{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=Ha,output:e=ih,render:i,signal:s,...o}=n;this.opts=o,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=s,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(Oi);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=ja.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),le(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(qn.cursor.show),this.output.off("resize",this.render),le(this.input,!1),n(this.value)}),this.once("cancel",()=>{this.output.write(qn.cursor.show),this.output.off("resize",this.render),le(this.input,!1),n(Oi)})})}_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&&Ln.aliases.has(r.name)&&this.emit("cursor",Ln.aliases.get(r.name)),Ln.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=oh(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")}sh([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
- `),le(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(`
84
- `).length-1;this.output.write(qn.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(qn.cursor.hide);else{let r=Ra(this._prevFrame,n),t=Ji(this.output);if(this.restoreCursor(),r){let e=Math.max(0,r.numLinesAfter-t),i=Math.max(0,r.numLinesBefore-t),s=r.lines.find((o)=>o>=e);if(s===void 0){this._prevFrame=n;return}if(r.lines.length===1){this.output.write(qn.cursor.move(0,s-i)),this.output.write(qn.erase.lines(1));let o=n.split(`
85
- `);this.output.write(o[s]),this._prevFrame=n,this.output.write(qn.cursor.move(0,o.length-s-1));return}else if(r.lines.length>1){if(e<i)s=e;else{let u=s-i;u>0&&this.output.write(qn.cursor.move(0,u))}this.output.write(qn.erase.down());let o=n.split(`
86
- `).slice(s);this.output.write(o.join(`
87
- `)),this._prevFrame=n;return}}this.output.write(qn.erase.down())}this.output.write(n),this.state==="initial"&&(this.state="active"),this._prevFrame=n}}}function Ja(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 Ka(n,r){return(r.label??String(r.value)).toLowerCase().includes(n.toLowerCase())}function La(n,r){if(r)return n?r:r[0]}var Qa=class extends er{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#r=0;#i="";#n;#s;#u;get cursor(){return this.#r}get userInputWithCursor(){if(!this.userInput)return Gi(["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}${Gi("inverse",t)}${e}`}get options(){return typeof this.#s=="function"?this.#s():this.#s}constructor(r){super(r),this.#s=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??Ka;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 s=t.findIndex((o)=>o.value===i);s!==-1&&(this.toggleSelected(i),this.#r=s)}this.focusedValue=this.options[this.#r]?.value,this.on("key",(i,s)=>this.#t(i,s)),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",s=t.name==="return",o=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"&&o&&h){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(u,!0),this.isNavigating=!1;return}e||i?(this.#r=lr(this.#r,e?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#r]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):s?this.value=La(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((s)=>this.#n?.(r,s)):this.filteredOptions=[...t];let e=Ja(this.focusedValue,this.filteredOptions);this.#r=lr(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 Ki extends er{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(qn.cursor.move(0,-1)),this.value=r,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var Pa={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function th(n){return[...n].map((r)=>Pa[r])}function Za(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 ji(n){return Number.parseInt((n||"0").replace(/_/g,"0"),10)||0}function de(n){return{year:ji(n.year),month:ji(n.month),day:ji(n.day)}}function Ri(n,r){return new Date(n||2001,r||1,0).getDate()}function uh(n){let{year:r,month:t,day:e}=de(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 eh(n){let r=uh(n);return r?new Date(Date.UTC(r.year,r.month-1,r.day)):void 0}function qa(n,r,t,e){let i=t?{year:t.getUTCFullYear(),month:t.getUTCMonth()+1,day:t.getUTCDate()}:null,s=e?{year:e.getUTCFullYear(),month:e.getUTCMonth()+1,day:e.getUTCDate()}:null;return n==="year"?{min:i?.year??1,max:s?.year??9999}:n==="month"?{min:i&&r.year===i.year?i.month:1,max:s&&r.year===s.year?s.month:12}:{min:i&&r.year===i.year&&r.month===i.month?i.day:1,max:s&&r.year===s.year&&r.month===s.month?s.day:Ri(r.year,r.month)}}class ch extends er{#r;#i;#n;#s;#u;#t={segmentIndex:0,positionInSegment:0};#e=!0;#o=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(eh(this.#n)??void 0)}constructor(n){let r=n.format?{segments:th(n.format),separator:n.separator??"/"}:Za(n.locale),t=n.separator??r.separator,e=n.format?th(n.format):r.segments,i=n.initialValue??n.defaultValue,s=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:"__"},o=e.map((u)=>s[u.type]).join(t);super({...n,initialUserInput:o},!1),this.#r=e,this.#i=t,this.#n=s,this.#s=n.minDate,this.#u=n.maxDate,this.#c(),this.on("cursor",(u)=>this.#a(u)),this.on("key",(u,c)=>this.#m(u,c)),this.on("finalize",()=>this.#$(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.#o=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,"")==="",s=Number.parseInt((e||"0").replace(/_/g,"0"),10)||0,o=qa(t.type,de(this.#n),this.#s,this.#u),u;i?u=n===1?o.min:o.max:u=Math.max(Math.min(o.max,s+n),o.min),this.#n={...this.#n,[t.type]:u.toString().padStart(t.len,"0")},this.#e=!0,this.#o=null,this.#c()}#a(n){if(n)switch(n){case"right":return this.#f(1);case"left":return this.#f(-1);case"up":return this.#l(1);case"down":return this.#l(-1)}}#m(n,r){if(r?.name==="backspace"||r?.sequence===""||r?.sequence==="\b"||n===""||n==="\b"){this.inlineError="";let 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.#o!==null&&!i){let l=this.#o+n,a={...this.#n,[e.type]:l},m=this.#d(a,e);if(m){this.inlineError=m,this.#o=null,this.#e=!1;return}this.inlineError="",this.#n[e.type]=l,this.#o=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.#o=null;let s=this.#n[e.type],o=s.indexOf("_"),u=o>=0?o:Math.min(this.#t.positionInSegment,e.len-1);if(u<0||u>=e.len)return;let c=s.slice(0,u)+n+s.slice(u+1),h=!1;if(u===0&&s==="__"&&(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=(s.replace(/_/g,"")+n).padStart(e.len,"_")),!c.includes("_")){let l={...this.#n,[e.type]:c},a=this.#d(l,e);if(a){this.inlineError=a;return}}this.inlineError="",this.#n[e.type]=c;let f=c.includes("_")?void 0:uh(this.#n);if(f){let{year:l,month:a}=f,m=Ri(l,a);this.#n={year:String(Math.max(0,Math.min(9999,l))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,a))).padStart(2,"0"),day:String(Math.max(1,Math.min(m,f.day))).padStart(2,"0")}}this.#c();let g=c.indexOf("_");h?(this.#e=!0,this.#o=n):g>=0?this.#t.positionInSegment=g:o>=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)}}#d(n,r){let{month:t,day:e}=de(n);if(r.type==="month"&&(t<0||t>12))return Ln.date.messages.invalidMonth;if(r.type==="day"&&(e<0||e>31))return Ln.date.messages.invalidDay(31,"any month")}#$(n){let{year:r,month:t,day:e}=de(this.#n);if(r&&t&&e){let i=Ri(r,t);this.#n={...this.#n,day:String(Math.min(e,i)).padStart(2,"0")}}this.value=eh(this.#n)??n.defaultValue??void 0}}var Ua=class extends er{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((s)=>s.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((s)=>({...s,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}})}},Wa=new Set(["up","down","left","right"]);class hh extends er{#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===`
88
+ `);return}Id(n,s[1],Number(s[2]),r.subarray(o+4))};n.on("data",e),n.on("error",()=>n.destroy())}function Tc(){let n=vd(Sd);return new Promise((r,e)=>{n.once("error",e),n.listen(0,"127.0.0.1",()=>{r({port:n.address().port,close:()=>{n.close(),n.unref()}})})})}var Dr=[{name:"TTHEME_FIND_RATING",label:"rating",choices:Ee,multi:{read:et}},{name:"TTHEME_FIND_BLOCK",label:"block",choices:Hr,multi:{read:tt,none:"none"}},{name:"TTHEME_FIND_POSTS",label:"posts",choices:["all","cutouts"]},{name:"TTHEME_FIND_SOLO",label:"solo",choices:["on","off"]},{name:"TTHEME_FIND_ORDER",label:"order",choices:["fit","newest","score"]},{name:"TTHEME_FIND_SETS",label:"sets",choices:["fold","show"]},...wi()?[{name:"TTHEME_FIND_REMOVE_BG",label:"remove bg",choices:["on","off"]}]:[]];function Rd(n,r){if(n.multi)return n.multi.read(r).join(" ")||n.multi.none;return n.choices.find((e)=>e===r)??n.choices[0]}var Gd=["fit","newest","score"];function zc(n){return Gd.find((r)=>r===n)??"fit"}function Ld(n){return n.length>=2&&!/^\d+$/.test(n)&&!n.includes("://")&&!/^[\w.]+:\d+$/.test(n)}var Yc=12,Jd=4,Kd=150,Cc=12,Pd=2,Ud=150,Qd=30,Wd=1280,_c=2,Zd=3,qd=8;function Oi(n,r){return{key:n,groups:[],sources:[],queue:[],rounds:0,roundOf:new Map,last:new Map,kin:new Map,kindred:new Map,shapes:[],seen:new Set,same:new Map,checked:0,total:0,focus:0,top:0,searching:r}}function bt(n){if(!(n instanceof Error))return String(n);if(n instanceof AggregateError&&n.errors[0])return bt(n.errors[0]);if(n.cause)return bt(n.cause);let r=n.code;if(typeof r==="string")return r;let e=(n.message||n.name).split(".")[0]??"";return e.length>56?`${e.slice(0,55)}…`:e}function ji(n,r){return`${n}: ${bt(r)}`}function Bc(n){return n.width*n.height}function xc(n){return`${n.id}-${Nd("sha1").update(n.preview).digest("hex").slice(0,8)}`}function Ad(n){let r=n.lastIndexOf("\x1B");return r!==-1&&/^\[?[0-9;]*$/.test(n.slice(r+1))}function Ri(n,r){try{return JSON.parse(rh(ar(Mr(n),r),"utf8"))}catch{return{}}}function Gi(n,r,e){Li(Mr(n),{recursive:!0}),Ji(ar(Mr(n),r),`${JSON.stringify(e)}
89
+ `)}class eh{view;tone;session=new AbortController;cell={w:0,h:0};cols=process.stdout.columns||80;rows=process.stdout.rows||24;gen=0;pumping=0;boards=new Map;board;posts=new Map;thumbPath=new Map;looking=new Map;looked=new Map;matched=new Map;aheading=!1;pages=new Map;tab=0;values=new Map(Dr.map((n)=>[n.name,Rd(n,process.env[n.name])]));direction=1;prefetching=0;inflight=new Map;owners=new Map;probed=new Map;unsaved=new Set;thumbQueue=[];thumbing=0;clarity=new Map;renders=new Si;sent=new Map;placed=new Map;current;fetch;settle;partial;suggestTimer;suggesting;input="";probeWait;done;dirty=!1;unblock=!1;scratch=Hd(ar(jd(),"ttheme-find-"));home;catalog;entry;constructor(n,r,e,t){this.home=n,this.catalog=r,this.entry=e,this.tone=De(e,e.signatureSlots),this.view={palette:e.name,tag:t,site:this.tabName,siteAnsi:this.tabAnsi,nextSite:this.nextTabName,preset:this.setting("TTHEME_FIND_POSTS")==="all"?"all":"cutouts",order:zc(this.setting("TTHEME_FIND_ORDER")),solo:this.setting("TTHEME_FIND_SOLO")==="on",rating:et(this.setting("TTHEME_FIND_RATING")),block:tt(this.setting("TTHEME_FIND_BLOCK")),sets:this.setting("TTHEME_FIND_SETS")==="show"?"show":"fold",unblocked:process.env.TTHEME_FIND_PROXY!==void 0,settings:Dr.map((i)=>({label:i.label,choices:[...i.choices],value:this.setting(i.name),multi:i.multi&&{none:i.multi.none},cursor:0})),colors:{cursor:e.cursor,selection:e.selection,ansi:e.ansi},tiles:[],installed:[],checked:0,total:0,searching:t!=="",focus:0,top:0,mode:"grid",help:!1,editing:t===""?"":void 0},this.board=Oi(this.boardKey,t!==""),this.boards.set(this.board.key,this.board)}get signal(){return this.session.signal}get site(){return this.tab===0?void 0:Mn[this.tab-1]}get sites(){return this.site?[this.site]:Mn}get tabName(){return this.site?.name??"all"}get tabAnsi(){return this.site?.ansi??Jd}get nextTabName(){let n=(this.tab+1)%(Mn.length+1);return n===0?"all":Mn[n-1].name}frame(){return{w:this.cols*(this.cell.w||10),h:this.rows*(this.cell.h||20)}}setting(n){return this.values.get(n)}get boardKey(){return`${this.site?.key??"all"}|${this.view.preset}|${this.view.order}`}origPath(n,r,e){return ar(Mr(n),"orig",`${r}.${e}`)}previewPath(n){return ar(Mr(n.site),"thumb",`${xc(n.post)}.${ve(n.post.preview)}`)}tileOf(n,r){let{site:e,post:t}=n,i=tr(e,t.id),o=ye(t)??t;return{id:t.id,key:i,site:e.name,siteAnsi:e.ansi,width:o.width,height:o.height,reduced:o!==t,owner:t.owner,artist:t.artist,score:t.score,variants:r,origin:si(t.source),mates:this.owners.get(e.key)?.get(t.owner)??[],thumb:this.thumbPath.get(i)}}show(){let n=this.view,r=this.board;n.tiles=r.groups.flatMap((e)=>e.open?e.posts.map((t)=>this.tileOf(t,0)):[this.tileOf(e.posts[0],e.posts.length)]),n.checked=r.checked,n.total=r.total,n.searching=r.searching,n.note=r.note,n.focus=Math.max(0,Math.min(r.focus,n.tiles.length-1)),n.top=r.top}syncSite(){let n=this.view;n.site=this.tabName,n.siteAnsi=this.tabAnsi,n.nextSite=this.nextTabName}async run(){let{stdin:n,stdout:r}=process;n.setRawMode(!0),n.resume(),n.on("data",this.onData),r.on("resize",this.onResize),this.write("\x1B[?25l\x1B[?7l\x1B[H\x1B[K\x1B[2H\x1B[J\x1B[H");let e=new Promise((s)=>{this.done=s}),t=setInterval(this.onClock,250),i=await this.probe();if(i){if(this.cell=i,this.view.tag)this.search()}else this.view.searching=!1,this.view.error="this terminal does not report its cell size — find needs kitty graphics";this.draw();let o=await e;return this.session.abort(),this.fetch?.abort(),clearTimeout(this.settle),clearTimeout(this.partial),this.quietSuggest(),clearInterval(t),n.off("data",this.onData),r.off("resize",this.onResize),this.write("\x1B_Ga=d,d=A,q=2\x1B\\\x1B[H\x1B[K\x1B[2H\x1B[J\x1B[H"),n.setRawMode(!1),n.pause(),this.saveProbes(),this.renders.close(),Hi(this.scratch,{recursive:!0,force:!0}),vu(),o}write(n){process.stdout.write(n)}get saved(){return this.view.saved}finish(n){this.done?.(n===2&&this.saved?0:n)}probe(){return new Promise((n)=>{let r=setTimeout(()=>{this.probeWait=void 0,n(null)},1000);this.probeWait=(e)=>{clearTimeout(r),this.probeWait=void 0,n(e)},this.write(mc)})}onData=(n)=>{this.input+=n.toString("utf8");for(let r=ki(this.input);r;r=ki(this.input))this.input=r.rest,this.probeWait?.(r.cell);if(this.probeWait)return;if(clearTimeout(this.partial),Ad(this.input)){this.partial=setTimeout(this.flushKeys,Qd);return}this.flushKeys()};flushKeys=()=>{let n=dc(this.input);this.input="";for(let r of n)this.key(r)};onClock=()=>{let n=this.sites.reduce((t,i)=>br(i)>br(t)?i:t),r=Math.ceil((br(n)-Date.now())/1000),e=r>0?r:void 0;if(e!==this.view.waiting)this.view.waiting=e,this.view.slow=n.name,this.draw()};onResize=()=>{if(this.cols=process.stdout.columns||this.cols,this.rows=process.stdout.rows||this.rows,this.scroll(),this.view.mode==="try"&&this.current)this.reveal();this.pump(),this.draw()};key(n){let r=this.view;if(n==="ctrl-c"){this.finish(2);return}if(r.installing!==void 0)return;if(r.asking!==void 0){this.askKey(n);return}if(r.editing!==void 0){this.editKey(n);return}if(r.panel!==void 0){this.panelKey(n);return}if(r.help){if(n==="?"||n==="esc")r.help=!1,this.draw();return}if(this.cols<Rr.cols||this.rows<Rr.rows){if(n==="esc")this.finish(2);return}if(n==="?"){r.help=!0,this.draw();return}if(r.mode==="try"){this.tryKey(n);return}this.gridKey(n)}gridKey(n){let r=this.view,{perRow:e,rowsVis:t}=Tr(this.cols,this.rows),o={left:-1,right:1,up:-e,down:e,pgup:-e*t,pgdn:e*t,home:-r.focus,end:r.tiles.length}[n];if(o!==void 0){this.focus(r.focus+o);return}if(n==="enter"&&r.tiles[r.focus]){r.mode="try",r.error=void 0,this.select();return}if(n==="c"){r.preset=r.preset==="cutouts"?"all":"cutouts",this.turn();return}if(n==="tab"){this.tab=(this.tab+1)%(Mn.length+1),this.syncSite(),this.turn();return}if(n==="/"){r.editing="",this.draw();return}if(n===" "){this.unfold();return}if(n==="o"){this.openPage();return}if(n==="s"){r.panel=0,this.draw();return}if(n==="esc")this.finish(2)}panelKey(n){let r=this.view,e=r.panel??0,t=r.settings[e];if(n==="up"||n==="down"){r.panel=Math.max(0,Math.min(r.settings.length-1,e+(n==="up"?-1:1))),this.draw();return}if((n==="left"||n==="right")&&t){let i=n==="left"?-1:1;if(t.multi)t.cursor=(t.cursor+i+t.choices.length)%t.choices.length;else{let o=t.choices.indexOf(t.value);t.value=t.choices[(o+i+t.choices.length)%t.choices.length]}this.draw();return}if(n===" "&&t?.multi){let i=t.value.split(" "),o=t.choices.filter((u,c)=>c===t.cursor?!i.includes(u):i.includes(u)),s=t.multi.none;if(o.length>0||s!==void 0)t.value=o.length>0?o.join(" "):s,this.draw();return}if(n==="esc"){r.settings.forEach((i,o)=>{i.value=this.setting(Dr[o]?.name??"")}),r.panel=void 0,this.draw();return}if(n==="enter"||n==="alt-c")r.panel=void 0,this.adopt()}adopt(){let n=this.view,r=Dr.map((t)=>this.setting(t.name));n.settings.forEach((t,i)=>{let o=Dr[i];if(o)this.values.set(o.name,t.value)});let e=Dr.filter((t,i)=>this.setting(t.name)!==r[i]);if(e.length===0){this.draw();return}this.save(e),n.rating=et(this.setting("TTHEME_FIND_RATING")),n.block=tt(this.setting("TTHEME_FIND_BLOCK")),n.sets=this.setting("TTHEME_FIND_SETS")==="show"?"show":"fold",n.preset=this.setting("TTHEME_FIND_POSTS")==="all"?"all":"cutouts",n.order=zc(this.setting("TTHEME_FIND_ORDER")),n.solo=this.setting("TTHEME_FIND_SOLO")==="on",this.boards.clear(),this.current=void 0,n.shown=void 0,n.mode="grid",this.search()}save(n){this.store(n.map((r)=>[r.name,this.setting(r.name)]))}store(n){let r=ar(this.home,"ttheme","config.zsh");try{let e=xr(r)?rh(r,"utf8"):"";return Ji(r,n.reduce((t,[i,o])=>ut(t,i,o),e)),!0}catch(e){return this.view.error=e instanceof Error?e.message:String(e),!1}}askKey(n){let r=this.view;if(n==="y"){if(r.asking=void 0,this.store([["TTHEME_FIND_UNBLOCK","1"]])){this.unblock=!0,this.finish(0);return}this.draw();return}if(n==="n"||n==="esc")r.asking=void 0,this.draw()}editKey(n){let r=this.view,e=r.editing??"",t=r.suggest??[];if((n==="up"||n==="down")&&t.length>0){let i=r.pick??-1,o=n==="down"?Math.min(t.length-1,i+1):i-1;r.pick=o<0?void 0:o,this.draw();return}if(n==="esc"||n==="enter")this.quietSuggest();if(n==="esc"){if(r.editing=void 0,r.tag===""){this.finish(2);return}this.draw();return}if(n==="enter"){let i=r.pick===void 0?void 0:t[r.pick],o=i?e.replace(/\S*$/,i.value):e;if(r.editing=void 0,r.suggest=void 0,r.pick=void 0,o.trim()){this.commit(o.trim());return}if(r.tag===""){this.finish(2);return}this.draw();return}if(n==="backspace"){r.editing=e.slice(0,-1),this.suggest(),this.draw();return}if(n.length===1&&n>=" ")r.editing=e+n,this.suggest(),this.draw()}quietSuggest(){clearTimeout(this.suggestTimer),this.suggesting?.abort(),this.suggesting=void 0}suggest(){this.quietSuggest();let n=this.view;n.pick=void 0;let r=/\S*$/.exec(n.editing??"")?.[0]??"";if(!Ld(r)){n.suggest=void 0;return}let e=[...new Map(cc(this.catalog.palettes,this.entry,r).map((i)=>[i.booru,{value:i.booru,count:0,palette:i.name}])).values()].slice(0,Zd);n.suggest=e.length>0?e:void 0;let t=new AbortController;this.suggesting=t,this.suggestTimer=setTimeout(async()=>{try{let i=await Nu(r,AbortSignal.any([this.signal,t.signal]));if(this.suggesting===t&&n.editing!==void 0){let o=new Map(i.map((u)=>[u.value,u.count])),s=new Set(e.map((u)=>u.value));n.suggest=[...e.map((u)=>({...u,count:o.get(u.value)??0})),...i.filter((u)=>!s.has(u.value))].slice(0,qd),n.pick=n.pick!==void 0&&n.pick<e.length?n.pick:void 0,this.draw()}}catch{}},Kd)}async commit(n){let r=wu(n,this.site??Mn[0]);if(r){await this.jump(r.site,r.id);return}this.view.tag=n,this.boards.clear(),await this.search()}async jump(n,r){let e=++this.gen;this.tab=Mn.indexOf(n)+1,this.syncSite(),this.current=void 0,this.view.shown=void 0,this.view.error=void 0;let t=Oi(`${n.key}|post:${r}`,!0);this.board=t,this.boards.set(t.key,t),this.show(),this.draw();try{let i=await ui(n,r,this.signal);if(e!==this.gen)return;if(t.searching=!1,!i)t.error=`${n.name} has no post ${r}`,this.view.error=t.error;else{let o={site:n,post:i};this.posts.set(tr(n,i.id),o),t.groups=[{posts:[o],open:!1}],t.checked=1,t.total=1,this.thumbQueue.push(o),this.thumbs(),this.view.mode="try"}if(this.show(),i)this.select();this.draw()}catch(i){this.fail(e,i,n)}}async turn(){this.fetch?.abort(),this.current=void 0,this.view.shown=void 0;let n=this.boards.get(this.boardKey);if(!n){await this.search();return}this.gen++,this.board=n,this.view.error=n.error,this.show(),this.draw(),await this.pump()}unfold(){let n=this.view,r=0;for(let e of this.board.groups){let t=e.open?e.posts.length:1;if(n.focus<r+t){if(e.posts.length<2)return;e.open=!e.open,this.board.focus=r;for(let i of e.posts)if(!this.thumbPath.has(tr(i.site,i.post.id)))this.thumbQueue.push(i);this.thumbs(),this.show(),this.scroll(),this.draw();return}r+=t}}openPage(){let n=this.view.tiles[this.view.focus],r=n&&this.posts.get(n.key);if(!r)return;let e=process.platform==="darwin"?"open":"xdg-open";try{nh(e,[r.site.pageUrl(r.post.id)],{stdio:"ignore",detached:!0}).unref()}catch{}}tryKey(n){let r=this.view;if(n==="left"||n==="right"){this.direction=n==="left"?-1:1,this.focus(r.focus+this.direction);return}if(n==="o"){this.openPage();return}if(n==="x"){this.swap();return}if(n==="enter"){this.install();return}if(n==="esc")this.fetch?.abort(),clearTimeout(this.settle),r.fetching=void 0,r.mode="grid",r.error=void 0,this.draw()}focus(n){let r=this.view;if(r.tiles.length===0)return;let e=Math.max(0,Math.min(r.tiles.length-1,n));if(e===r.focus)return;if(r.focus=e,this.board.focus=e,this.scroll(),this.pump(),r.mode==="try")this.select();this.draw()}scroll(){let n=this.view,{perRow:r,rowsVis:e}=Tr(this.cols,this.rows),t=Math.floor(n.focus/r);if(t<n.top)n.top=t;if(t>n.top+e-1)n.top=t-e+1;this.board.top=n.top}query(n){let r=this.view,e=r.tag===this.entry.booru?hc(this.entry,n.key):[r.tag];if(e.length===0)return;let t=e.length>1,i=r.preset==="cutouts"?n.cutouts:"",o=t&&i.includes("~"),s=[t?e.map((h)=>`~${h}`).join(" "):e[0],n.rate(this.view.rating),o?"":i,r.order==="score"?n.best:""].filter(Boolean),u=[],c=[];for(let h of s)if(oi([...u,h].join(" "))<=n.tagBudget)u.push(h);else c.push(h);return{tags:u.join(" "),notes:[...c.length>0?[`${n.name} takes ${n.tagBudget} tags — ${c.join(" ")} left out`]:[],...o?[`${n.name} ORs the names, so cutouts are told by the file`]:[]]}}async search(){let n=++this.gen,r=Oi(this.boardKey,!0);this.board=r,this.boards.set(r.key,r),this.view.error=void 0;let e=this.sites.flatMap((o)=>{let s=this.query(o);return s?[{site:o,...s}]:[]}),t=this.sites.filter((o)=>!e.some((s)=>s.site===o)),i=[...e.flatMap(({notes:o})=>o),...t.length>0?[`${this.entry.name} has no tag on ${t.map((o)=>o.name).join(", ")}`]:[]];if(r.note=i.length>0?i.join(" · "):void 0,e.length===0)r.searching=!1;this.show(),this.draw(),this.tally(n,r,e);try{let o=await Promise.all(e.map(async(s)=>({plan:s,owners:await this.mateOwners(s.site)})));if(n!==this.gen)return;r.sources=o.flatMap(({plan:{site:s,tags:u},owners:c})=>[...oi(u)+1<=s.tagBudget?[...c.keys()].map((h)=>({site:s,tags:`${u} user:${h}`,page:0,done:!1})):[],{site:s,tags:u,page:0,done:!1}]),this.show(),this.draw(),await this.pump()}catch(o){this.fail(n,o)}}async tally(n,r,e){let t=await Promise.allSettled(e.map(({site:i,tags:o})=>yu(i,o,this.signal)));if(n===this.gen)r.total=t.reduce((i,o)=>i+(o.status==="fulfilled"?o.value:0),0),this.show(),this.draw()}fail(n,r,e=this.site){if(n!==this.gen||this.signal.aborted)return;this.board.error=ji(e?.name??this.tabName,r),this.board.searching=!1,this.view.error=this.board.error,this.offer(e,r),this.show(),this.draw()}offer(n,r){if(n&&!this.view.unblocked&&th()&&bt(r)==="ECONNRESET")this.view.asking=n.name}drop(n,r,e){for(let t of n.sources)if(t.site===r)t.done=!0;n.note=[n.note,ji(r.name,e)].filter(Boolean).join(" · "),this.offer(r,e)}wants(){let{perRow:n,rowsVis:r}=Tr(this.cols,this.rows);return this.view.tiles.length<(this.board.top+r+_c)*n}need(){let{perRow:n,rowsVis:r}=Tr(this.cols,this.rows);return(r+_c)*n}live(n){return this.boards.get(n.key)===n}page(n,r,e){let t=`${n.key}|${r}|${e}`,i=this.pages.get(t);if(!i)i=Fu(n,r,e,this.signal).then((o)=>this.borrow(o)),this.pages.set(t,i),i.catch(()=>this.pages.delete(t));return i}async borrow(n){let r=n.filter((e)=>e.solo===void 0&&e.md5!=="");if(r.length>0)try{Iu(r,await Su(r.map((e)=>e.md5),this.signal))}catch{}return n}async round(n){let r=Mn.flatMap((u)=>{let c=n.sources.find((h)=>h.site===u&&!h.done);return c?[c]:[]}),e=await Promise.all(r.map(async(u)=>{try{return{source:u,posts:await this.page(u.site,u.tags,u.page)}}catch(c){if(n.sources.every((h)=>h.site===u.site)||this.signal.aborted)throw c;return this.drop(n,u.site,c),{source:u,posts:void 0}}}));if(!this.live(n))return;let t=[];for(let{source:u,posts:c}of e){if(!c)continue;u.page++,u.done=c.length<Nr;let h=n.last.get(u);for(let f of c){let l=h&&Jc(h.post,f)?h.set:`set:${u.site.key}:${f.id}`;h={post:f,set:l};let g=tr(u.site,f.id);if(n.seen.has(g))continue;n.seen.add(g);let d={site:u.site,post:f};if(this.eligible(d))n.kin.set(d,[l,...Lc(u.site,f)]),t.push(d);else n.checked++}if(h)n.last.set(u,h)}let i=this.dedupe(n,t),o=++n.rounds,s;if(this.view.order!=="fit")s=r.length>1?Ic(i):i;else{let u=$t(i,this.frame(),this.matched),c=u.slice(0,this.need());if(await this.looks(c),!this.live(n))return;s=[...$t(c,this.frame(),this.matched),...u.slice(c.length)]}for(let u of s)n.roundOf.set(u,o);n.queue.push(...s),this.ahead(n)}ahead(n){if(this.aheading||this.view.order!=="fit"||!this.live(n))return;let r=n.queue.slice(0,this.need()).filter((e)=>!this.looking.has(tr(e.site,e.post.id)));if(r.length===0)return;this.aheading=!0,this.looks(r).then(()=>{this.aheading=!1;for(let e of new Set(r.map((t)=>n.roundOf.get(t)??0)))this.resort(n,e);this.ahead(n)})}resort(n,r){let e=n.queue.flatMap((i,o)=>n.roundOf.get(i)===r?[o]:[]),t=$t(e.map((i)=>n.queue[i]),this.frame(),this.matched);e.forEach((i,o)=>{n.queue[i]=t[o]})}dedupe(n,r){let e=[];for(let t of r){let i=Ii(t.post),o=i.map((u)=>n.same.get(u)).find(Boolean);if(!o){for(let u of i)n.same.set(u,t);e.push(t);continue}if(n.checked++,Bc(t.post)<=Bc(o.post))continue;for(let u of[...i,...Ii(o.post)])n.same.set(u,t);let s=e.indexOf(o);if(s>=0){e[s]=t;continue}this.replace(n,o,t)}return e}replace(n,r,e){n.roundOf.set(e,n.roundOf.get(r)??0);let t=n.queue.indexOf(r);if(t>=0){n.queue[t]=e;return}for(let i of n.groups){let o=i.posts.indexOf(r);if(o>=0){i.posts[o]=e,this.posts.set(tr(e.site,e.post.id),e),this.thumbQueue.push(e),this.thumbs();return}}}async looks(n){let r=0;await Promise.all(Array.from({length:Cc},async()=>{while(r<n.length)await this.look(n[r++])}))}look(n){let r=tr(n.site,n.post.id),e=this.looking.get(r);if(!e)e=(async()=>{let t=this.previewPath(n);await this.cached(n.site,t,n.post.preview);let i=await this.renders.run({job:"match",from:t,colors:this.entry.signature});return this.looked.set(r,i),this.matched.set(n.post,i.match),i})().catch(()=>{return}),this.looking.set(r,e);return e}async pump(){let n=this.gen,r=this.board;if(this.pumping===n||r.sources.length===0)return;this.pumping=n;let e=[],t;try{r.searching=!0;while(n===this.gen){while(e.length<Yc&&r.queue.length>0&&this.wants()){let s=r.queue.shift();e.push({pick:s,passed:this.vet(s)})}if(this.ahead(r),!t&&r.queue.length<Yc&&r.sources.some((s)=>!s.done)&&this.wants()){let s=this.round(r).then(()=>{if(t===s)t=void 0});s.catch(()=>{}),t=s}let i=e.shift();if(!i){if(!t)break;await t,this.show(),this.draw();continue}let o=await i.passed;if(n!==this.gen)return;if(r.checked++,o)this.admit(i.pick);this.show(),this.draw()}if(n===this.gen)r.searching=!1,this.show(),this.draw()}catch(i){this.fail(n,i)}finally{if(this.saveProbes(),this.pumping===n)this.pumping=0}}eligible({site:n,post:r}){let e=ye(r);if(!ku(n,r,this.view.rating)||bu(r,this.view.block).length>0||!e)return!1;if(this.view.solo&&r.solo===!1)return!1;return this.view.preset==="all"?["png","jpg","jpeg"].includes(e.ext):r.ext==="png"}async vet(n){let[r]=await Promise.all([this.passes(n),this.look(n)]);return r}async passes({site:n,post:r}){return this.view.preset==="all"||n.vouched||this.transparent(n,r)}probes(n){let r=this.probed.get(n.key);if(!r)r=Ri(n,"probes.json"),this.probed.set(n.key,r);return r}async transparent(n,r){let e=this.probes(n),t=e[r.id];if(t!==void 0)return t;try{let i=(await Hu(n,r.file,this.signal))?.alpha===!0;return e[r.id]=i,this.unsaved.add(n.key),i}catch{return!1}}saveProbes(){for(let n of this.unsaved){let r=Mn.find((e)=>e.key===n);if(r)Gi(r,"probes.json",this.probes(r))}this.unsaved.clear()}admit(n){let{site:r,post:e}=n,t=this.board,i=tr(r,e.id);this.posts.set(i,n);let o=t.kin.get(n)??[],s=this.looked.get(i),u=s&&{hash:s.hash,width:e.width,height:e.height},c=this.view.sets==="fold"?this.kindred(t,o,u):void 0;if(c){if(c.posts.push(n),this.register(t,c,o,u),c.open)this.thumbQueue.push(n),this.thumbs();return}let h={posts:[n],open:!1};t.groups.push(h),this.register(t,h,o,u),this.thumbQueue.push(n),this.thumbs()}kindred(n,r,e){for(let t of r){let i=n.kindred.get(t);if(i)return i}return e&&n.shapes.find((t)=>Pc(t.shape,e))?.group}register(n,r,e,t){for(let i of e)if(!n.kindred.has(i))n.kindred.set(i,r);if(t)n.shapes.push({shape:t,group:r})}async mateOwners(n){let r=this.owners.get(n.key);if(r)return r;let e=iu(this.home),t=Ri(n,"owners.json"),i=this.catalog.palettes.flatMap((c)=>{let h=e.get(c.name);return c.group===this.entry.group&&c.name!==this.entry.name&&h?.site===n.key?[{name:c.name,id:h.id}]:[]}),o=await Promise.all(i.map(async(c)=>{let h=t[c.id];if(h!==void 0)return{...c,owner:h};try{return{...c,owner:(await ui(n,c.id,this.signal))?.owner??""}}catch{return}})),s=new Map;for(let c of o)if(c)t[c.id]=c.owner,s.set(c.name,c.owner);Gi(n,"owners.json",t);let u=Mu(s);return this.owners.set(n.key,u),u}async cached(n,r,e,t){if(xr(r))return Od(r).size;let i=this.inflight.get(r);if(i)return i;let o=(async()=>{let s=await Ou(n,e,this.signal,t);return Li(Vc(r),{recursive:!0}),Ji(r,s),s.length})();this.inflight.set(r,o);try{return await o}finally{this.inflight.delete(r)}}thumbs(){while(this.thumbing<Cc&&this.thumbQueue.length>0){let n=this.thumbQueue.shift();this.thumbing++,this.thumb(n).catch(()=>{}).finally(()=>{this.thumbing--,this.thumbs()})}}async thumb(n){let{site:r,post:e}=n,t=Un.cols*this.cell.w,i=Un.rows*this.cell.h,o=ar(Mr(r),"tile",`${xc(e)}-${t}x${i}.png`);if(!xr(o)){let s=this.previewPath(n);await this.cached(r,s,e.preview),await this.renders.run({job:"thumb",from:s,to:o,width:t,height:i})}this.thumbPath.set(tr(r,e.id),o),this.show(),this.draw()}select(){let n=this.view,r=n.tiles[n.focus];if(this.fetch?.abort(),clearTimeout(this.settle),n.fetching=void 0,!r)return;if(this.current?.key===r.key){this.reveal();return}this.settle=setTimeout(()=>void this.load(r),Ud),this.draw()}async load(n){let r=this.view,e=this.posts.get(n.key),t=e&&ye(e.post);if(!e||!t)return;let{site:i}=e,o=this.board,s=new AbortController;this.fetch=s;try{let u=this.origPath(i,n.id,t.ext);if(!xr(u))r.fetching={id:n.key,got:0,size:0},this.draw();let c=await this.cached(i,u,t.file,(l,g)=>{if(r.fetching?.id===n.key)r.fetching={id:n.key,got:l,size:g},this.draw()});if(s.signal.aborted)return;if(r.fetching=void 0,o!==this.board)return;let h={site:i,id:n.id,key:n.key,path:u,ext:t.ext,size:c,using:"plain",failed:!1};r.preparing=n.key,this.flush();let f=await this.render(h,"plain");if(s.signal.aborted||o!==this.board)return;if(f.clear===0&&wi()&&this.setting("TTHEME_FIND_REMOVE_BG")!=="off"){if(r.preparing=void 0,r.cutting=n.key,this.flush(),h.cut=await this.cutOut(i,n.id,u,s.signal),s.signal.aborted||o!==this.board)return;if(r.cutting=void 0,h.cut){r.preparing=n.key,this.flush();let l=await this.render(h,"cut").catch(()=>{return});if(s.signal.aborted||o!==this.board)return;if(l&&fc(l.clear))h.using="cut";else Hi(h.cut,{force:!0}),h.cut=void 0,h.failed=!0}else h.failed=!0}if(this.current=h,r.tiles[r.focus]?.key===n.key)await this.present();this.preload()}catch(u){if(!s.signal.aborted&&!this.signal.aborted)r.error=ji(i.name,u)}finally{if(r.fetching?.id===n.key)r.fetching=void 0;if(r.preparing===n.key)r.preparing=void 0;if(r.cutting===n.key)r.cutting=void 0;this.draw()}}async cutOut(n,r,e,t){let i=ar(Mr(n),"cut",`${r}.png`);if(xr(i))return i;try{return Li(Vc(i),{recursive:!0}),await gc(e,i,t),i}catch{Hi(i,{force:!0});return}}swap(){let n=this.current;if(!n?.cut||this.view.shown?.id!==n.key)return;n.using=n.using==="cut"?"plain":"cut",this.reveal()}preload(){let n=this.view;if(n.mode!=="try")return;for(let r of[n.focus+this.direction,n.focus-this.direction]){if(this.prefetching>=Pd)return;let e=n.tiles[r],t=e&&this.posts.get(e.key),i=t&&ye(t.post);if(!t||!i)continue;let{site:o,post:s}=t,u=this.origPath(o,s.id,i.ext);this.prefetching++,this.cached(o,u,i.file).then(()=>this.render({site:o,id:s.id,key:e.key,path:u,ext:i.ext,size:0,using:"plain",failed:!1},"plain")).catch(()=>{}).finally(()=>{this.prefetching--})}}async render(n,r){let e=this.cols*this.cell.w,t=this.rows*this.cell.h,i=Math.min(e,Wd),o=Math.max(1,Math.round(t*i/e)),s=ar(this.scratch,`${n.site.key}-${n.id}${r==="cut"?"c":""}-${i}x${o}.png`),u=`${n.site.key}:${n.id}:${r}`,c=this.clarity.get(u);if(c!==void 0&&xr(s))return{clear:c,path:s};let h=await this.renders.run({job:"show",from:r==="cut"?n.cut:n.path,to:s,width:i,height:o,colors:this.entry,tone:this.tone});return this.clarity.set(u,h),{clear:h,path:s}}async present(){let n=this.current;if(!n)return;let r=n.using,{clear:e,path:t}=await this.render(n,r);if(this.current!==n||n.using!==r)return;this.view.shown={id:n.key,clear:e,bytes:n.size,path:t,cut:n.cut?r==="cut"?"on":"off":n.failed?"failed":"none"}}reveal(){let n=this.view;n.preparing=this.current?.key,this.flush(),this.present().catch((r)=>{n.error=r instanceof Error?r.message:String(r)}).finally(()=>{if(n.preparing===this.current?.key)n.preparing=void 0;this.draw()})}async install(){let n=this.view,r=n.tiles[n.focus],e=this.current;if(!r||e?.key!==r.key||n.preparing!==void 0||n.shown?.id!==r.key)return;n.installing=r.key,n.error=void 0,this.flush();try{await this.renders.run({job:"backdrop",from:e.using==="cut"?e.cut:e.path,source:e.path,home:this.home,colors:this.entry,tone:this.tone,origin:{site:e.site.key,id:e.id,ext:e.ext,from:`${e.site.name} ${e.id} ${e.site.pageUrl(e.id)}`},width:this.cols*this.cell.w,height:this.rows*this.cell.h});let t=Ri(e.site,"owners.json");t[e.id]=this.posts.get(e.key)?.post.owner??"",Gi(e.site,"owners.json",t),Br(this.home),n.saved=`background · ${this.entry.name} ← ${e.site.name} ${e.id}`,n.installed.push(r.key),this.fetch?.abort(),clearTimeout(this.settle),n.fetching=void 0,n.mode="grid"}catch(t){n.error=t instanceof Error?t.message:String(t)}n.installing=void 0,this.draw()}draw(){if(this.dirty)return;this.dirty=!0,setImmediate(()=>{this.dirty=!1,this.flush()})}flush(){let n=Fc(this.view,this.cols,this.rows),r="\x1B[?2026h";n.lines.forEach((t,i)=>{r+=`\x1B[${i+1};1H\x1B[K${t}`});let e=new Set;for(let t of n.images){if(e.add(t.id),this.sent.get(t.id)!==t.path)r+=$c(t),this.sent.set(t.id,t.path),this.placed.delete(t.id);let i=`${t.row};${t.col};${t.cols};${t.rows};${t.z}`;if(this.placed.get(t.id)!==i)r+=wc(t),this.placed.set(t.id,i)}for(let t of this.sent.keys())if(!e.has(t))r+=pc(t),this.sent.delete(t),this.placed.delete(t);this.write(`${r}\x1B[?2026l`)}}function th(){if(process.versions.bun)return!0;let[n=0,r=0]=process.versions.node.split(".").map(Number);return n>22||n===22&&r>=21}async function Dc(){if(!th())return process.stderr.write(`unblock needs node 22.21 or newer — this is ${process.versions.node}
90
+ `),1;let n=await Tc(),r=nh(process.execPath,process.argv.slice(1),{stdio:"inherit",env:{...process.env,NODE_USE_ENV_PROXY:"1",NODE_NO_WARNINGS:"1",HTTPS_PROXY:`http://127.0.0.1:${n.port}`,NO_PROXY:[process.env.NO_PROXY,pu()].filter(Boolean).join(","),TTHEME_FIND_PROXY:String(n.port)}}),e=await new Promise((t)=>r.on("exit",(i)=>t(i??1)));return n.close(),e}async function ih(n){if(process.env.TTHEME_FIND_UNBLOCK==="1"&&!process.env.TTHEME_FIND_PROXY)return Dc();let r=xn(),e=Qn(r),t=at(e.palettes,n);if(!process.stdin.isTTY||!process.stdout.isTTY)throw Error("ttheme find needs a terminal");let i=new eh(r,e,t,t.booru??""),o=await i.run(),s=i.unblock?await Dc():o;if(i.saved&&s!==0)return process.stderr.write(`${i.saved}
91
+ `),0;return s}function oh(n,r){let e=xn();if(at(Qn(e).palettes,n),r==="next"||r==="prev"){let{key:t,at:i,of:o}=ru(e,n,r==="next"?1:-1);return Br(e),process.stderr.write(`background · ${n} ${i}/${o} ${t}
92
+ `),0}if(r==="drop"){let{key:t,left:i}=eu(e,n);return Br(e),process.stderr.write(`background · ${n} removed ${t??"the picture"} · ${i} left
93
+ `),0}if(r==="tuned")return Br(e),0;throw Error(`unknown image action ${r} — next, prev, drop or tuned`)}import{execFileSync as Xm}from"node:child_process";import{chmodSync as Tm,copyFileSync as Vm,existsSync as qn,mkdirSync as to,readdirSync as zm,readFileSync as ie,rmSync as sf,writeFileSync as uf}from"node:fs";import{homedir as Ym}from"node:os";import{dirname as te,join as fn}from"node:path";import{styleText as qi}from"node:util";import{stdout as vh,stdin as om}from"node:process";import sm from"node:readline";var sh=(()=>{let n=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(r)=>{let e=0;n.lastIndex=0;while(n.test(r))e+=1;return r.length-e}})(),uh=(n)=>{return n===12288||n>=65281&&n<=65376||n>=65504&&n<=65510},ch=(n)=>{return n===8987||n===9001||n>=12272&&n<=12287||n>=12289&&n<=12350||n>=12441&&n<=12543||n>=12549&&n<=12591||n>=12593&&n<=12686||n>=12688&&n<=12771||n>=12783&&n<=12830||n>=12832&&n<=12871||n>=12880&&n<=19903||n>=65040&&n<=65049||n>=65072&&n<=65106||n>=65108&&n<=65126||n>=65128&&n<=65131||n>=127488&&n<=127490||n>=127504&&n<=127547||n>=127552&&n<=127560||n>=131072&&n<=196605||n>=196608&&n<=262141};var Xd=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,Td=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,hh=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,Vd=/\t{1,1000}/y,fh=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu,zd=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Yd=/\p{M}+/gu,Cd={limit:1/0,ellipsis:""},gh=(n,r={},e={})=>{let t=r.limit??1/0,i=r.ellipsis??"",o=r?.ellipsisWidth??(i?gh(i,Cd,e).width:0),s=0,u=e.controlWidth??0,c=e.tabWidth??8,h=e.emojiWidth??2,f=2,l=e.regularWidth??1,g=e.wideWidth??2,d=[[zd,l],[Xd,0],[Td,u],[Vd,c],[fh,h],[hh,g]],w=0,m=0,b=n.length,F=0,S=!1,k=b,y=Math.max(0,t-o),p=0,R=0,M=0,j=0;n:while(!0){if(R>p||m>=b&&m>w){let H=n.slice(p,R)||n.slice(w,m);F=0;for(let J of H.replaceAll(Yd,"")){let G=J.codePointAt(0)||0;if(uh(G))j=2;else if(ch(G))j=g;else j=l;if(M+j>y)k=Math.min(k,Math.max(p,w)+F);if(M+j>t){S=!0;break n}F+=J.length,M+=j}p=R=0}if(m>=b)break n;for(let H=0,J=d.length;H<J;H++){let[G,z]=d[H];if(G.lastIndex=m,G.test(n)){if(F=G===hh?sh(n.slice(m,G.lastIndex)):G===fh?1:G.lastIndex-m,j=F*z,M+j>y)k=Math.min(k,m+Math.floor((y-M)/z));if(M+j>t){S=!0;break n}M+=j,p=w,R=m,m=w=G.lastIndex;continue n}}m+=1}return{width:S?y:M,index:S?k:b,truncated:S,ellipsed:S&&t>=o}},lh=gh;var _d={limit:1/0,ellipsis:"",ellipsisWidth:0},Bd=(n,r={})=>{return lh(n,_d,r).width},Kn=Bd;var kt="\x1B",wh="›",xd=39,Pi="\x07",ph="[",Dd="]",bh="m",Ui=`${Dd}8;;`,ah=new RegExp(`(?:\\${ph}(?<code>\\d+)m|\\${Ui}(?<uri>.*)${Pi})`,"y"),dh=(n)=>{if(n>=30&&n<=37)return 39;if(n>=90&&n<=97)return 39;if(n>=40&&n<=47)return 49;if(n>=100&&n<=107)return 49;if(n===1||n===2)return 22;if(n===3)return 23;if(n===4)return 24;if(n===7)return 27;if(n===8)return 28;if(n===9)return 29;if(n===0)return 0;return},mh=(n)=>`${kt}${ph}${n}${bh}`,$h=(n)=>`${kt}${Ui}${n}${Pi}`,Ki=(n,r,e)=>{let t=r[Symbol.iterator](),i=!1,o=!1,s=n.at(-1),u=s===void 0?0:Kn(s),c=t.next(),h=t.next(),f=0;while(!c.done){let l=c.value,g=Kn(l);if(u+g<=e)n[n.length-1]+=l;else n.push(l),u=0;if(l===kt||l===wh)i=!0,o=r.startsWith(Ui,f+1);if(i){if(o){if(l===Pi)i=!1,o=!1}else if(l===bh)i=!1}else if(u+=g,u===e&&!h.done)n.push(""),u=0;c=h,h=t.next(),f+=l.length}if(s=n.at(-1),!u&&s!==void 0&&s.length&&n.length>1)n[n.length-2]+=n.pop()},nm=(n)=>{let r=n.split(" "),e=r.length;while(e){if(Kn(r[e-1]))break;e--}if(e===r.length)return n;return r.slice(0,e).join(" ")+r.slice(e).join("")},rm=(n,r,e={})=>{if(e.trim!==!1&&n.trim()==="")return"";let t="",i,o,s=n.split(" "),u=[""],c=0;for(let l=0;l<s.length;l++){let g=s[l];if(e.trim!==!1){let w=u.at(-1)??"",m=w.trimStart();if(w.length!==m.length)u[u.length-1]=m,c=Kn(m)}if(l!==0){if(c>=r&&(e.wordWrap===!1||e.trim===!1))u.push(""),c=0;if(c||e.trim===!1)u[u.length-1]+=" ",c++}let d=Kn(g);if(e.hard&&d>r){let w=r-c,m=1+Math.floor((d-w-1)/r);if(Math.floor((d-1)/r)<m)u.push("");Ki(u,g,r),c=Kn(u.at(-1)??"");continue}if(c+d>r&&c&&d){if(e.wordWrap===!1&&c<r){Ki(u,g,r),c=Kn(u.at(-1)??"");continue}u.push(""),c=0}if(c+d>r&&e.wordWrap===!1){Ki(u,g,r),c=Kn(u.at(-1)??"");continue}u[u.length-1]+=g,c+=d}if(e.trim!==!1)u=u.map((l)=>nm(l));let h=u.join(`
94
+ `),f=!1;for(let l=0;l<h.length;l++){let g=h[l];if(t+=g,!f){if(f=g>="\uD800"&&g<="\uDBFF",f)continue}else f=!1;if(g===kt||g===wh){ah.lastIndex=l+1;let w=ah.exec(h)?.groups;if(w?.code!==void 0){let m=Number.parseFloat(w.code);i=m===xd?void 0:m}else if(w?.uri!==void 0)o=w.uri.length===0?void 0:w.uri}if(h[l+1]===`
95
+ `){if(o)t+=$h("");let d=i?dh(i):void 0;if(i&&d)t+=mh(d)}else if(g===`
96
+ `){if(i&&dh(i))t+=mh(i);if(o)t+=$h(o)}}return t},em=/\r?\n/;function Er(n,r,e){return String(n).normalize().split(em).map((t)=>rm(t,r,e)).join(`
97
+ `)}var Zn=Te(Wi(),1);function dr(n,r,e){if(!e.some((s)=>!s.disabled))return n;let t=n+r,i=Math.max(e.length-1,0),o=t<0?i:t>i?0:t;return e[o]?.disabled?dr(o,r<0?-1:1,e):o}function Mt(n,r,e,t){let i=t.split(`
98
+ `),o=0,s=n;for(let c of i){if(s<=c.length)break;s-=c.length+1,o++}for(o=Math.max(0,Math.min(i.length-1,o+e)),s=Math.min(s,i[o].length)+r;s<0&&o>0;)o--,s+=i[o].length+1;for(;s>i[o].length&&o<i.length-1;)s-=i[o].length+1,o++;s=Math.max(0,Math.min(i[o].length,s));let u=0;for(let c=0;c<o;c++)u+=i[c].length+1;return u+s}var um=["up","down","left","right","space","enter","cancel"],cm=["January","February","March","April","May","June","July","August","September","October","November","December"],Pn={actions:new Set(um),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0,date:{monthNames:[...cm],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(n,r)=>`There are only ${n} days in ${r}`,afterMin:(n)=>`Date must be on or after ${n.toISOString().slice(0,10)}`,beforeMax:(n)=>`Date must be on or before ${n.toISOString().slice(0,10)}`}}};function Fh(n,r){if(typeof n=="string")return Pn.aliases.get(n)===r;for(let e of n)if(e!==void 0&&Fh(e,r))return!0;return!1}function hm(n,r){if(n===r)return;let e=n.split(`
99
+ `),t=r.split(`
100
+ `),i=Math.max(e.length,t.length),o=[];for(let s=0;s<i;s++)e[s]!==t[s]&&o.push(s);return{lines:o,numLinesBefore:e.length,numLinesAfter:t.length,numLines:i}}var fp=globalThis.process.platform.startsWith("win"),Ai=Symbol("clack:cancel");function ne(n){return n===Ai}function Et(n,r){let e=n;e.isTTY&&e.setRawMode(r)}var Ft=(n)=>("columns"in n)&&typeof n.columns=="number"?n.columns:80,Ti=(n)=>("rows"in n)&&typeof n.rows=="number"?n.rows:20;function vr(n,r,e,t=e,i=e,o){let s=Ft(n??vh);return Er(r,s-e.length,{hard:!0,trim:!1}).split(`
101
+ `).map((u,c,h)=>{let f=o?o(u,c):u;return c===0?`${t}${f}`:c===h.length-1?`${i}${f}`:`${e}${f}`}).join(`
102
+ `)}function yh(n,r){if("~standard"in n){let e=n["~standard"].validate(r);if(e instanceof Promise)throw TypeError("Schema validation must be synchronous. Update `validate()` and remove any asynchronous logic.");return e.issues?.at(0)?.message}return n(r)}class sr{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(n,r=!0){let{input:e=om,output:t=vh,render:i,signal:o,...s}=n;this.opts=s,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=i.bind(this),this._track=r,this._abortSignal=o,this.input=e,this.output=t}unsubscribe(){this._subscribers.clear()}setSubscriber(n,r){let e=this._subscribers.get(n)??[];e.push(r),this._subscribers.set(n,e)}on(n,r){this.setSubscriber(n,{cb:r})}once(n,r){this.setSubscriber(n,{cb:r,once:!0})}emit(n,...r){let e=this._subscribers.get(n)??[],t=[];for(let i of e)i.cb(...r),i.once&&t.push(()=>e.splice(e.indexOf(i),1));for(let i of t)i()}prompt(){return new Promise((n)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),n(Ai);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=sm.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on("keypress",this.onKeypress),Et(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(Zn.cursor.show),this.output.off("resize",this.render),Et(this.input,!1),n(this.value)}),this.once("cancel",()=>{this.output.write(Zn.cursor.show),this.output.off("resize",this.render),Et(this.input,!1),n(Ai)})})}_isActionKey(n,r){return n==="\t"}_shouldSubmit(n,r){return!0}_setValue(n){this.value=n,this.emit("value",this.value)}_setUserInput(n,r){this.userInput=n??"",this.emit("userInput",this.userInput),r&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}onKeypress(n,r){if(this._track&&r.name!=="return"&&(r.name&&this._isActionKey(n,r)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),r?.name&&(!this._track&&Pn.aliases.has(r.name)&&this.emit("cursor",Pn.aliases.get(r.name)),Pn.actions.has(r.name)&&this.emit("cursor",r.name)),n&&(n.toLowerCase()==="y"||n.toLowerCase()==="n")&&this.emit("confirm",n.toLowerCase()==="y"),this.emit("key",n,r),r?.name==="return"&&this._shouldSubmit(n,r)){if(this.opts.validate){let e=yh(this.opts.validate,this.value);e&&(this.error=e instanceof Error?e.message:e,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}Fh([n,r?.name,r?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
103
+ `),Et(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let n=Er(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
104
+ `).length-1;this.output.write(Zn.cursor.move(-999,n*-1))}render(){let n=Er(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(n!==this._prevFrame){if(this.state==="initial")this.output.write(Zn.cursor.hide);else{let r=hm(this._prevFrame,n),e=Ti(this.output);if(this.restoreCursor(),r){let t=Math.max(0,r.numLinesAfter-e),i=Math.max(0,r.numLinesBefore-e),o=r.lines.find((s)=>s>=t);if(o===void 0){this._prevFrame=n;return}if(r.lines.length===1){this.output.write(Zn.cursor.move(0,o-i)),this.output.write(Zn.erase.lines(1));let s=n.split(`
105
+ `);this.output.write(s[o]),this._prevFrame=n,this.output.write(Zn.cursor.move(0,s.length-o-1));return}else if(r.lines.length>1){if(t<i)o=t;else{let u=o-i;u>0&&this.output.write(Zn.cursor.move(0,u))}this.output.write(Zn.erase.down());let s=n.split(`
106
+ `).slice(o);this.output.write(s.join(`
107
+ `)),this._prevFrame=n;return}}this.output.write(Zn.erase.down())}this.output.write(n),this.state==="initial"&&(this.state="active"),this._prevFrame=n}}}function fm(n,r){if(n===void 0||r.length===0)return 0;let e=r.findIndex((t)=>t.value===n);return e!==-1?e:0}function gm(n,r){return(r.label??String(r.value)).toLowerCase().includes(n.toLowerCase())}function lm(n,r){if(r)return n?r:r[0]}var am=class extends sr{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#r=0;#i="";#n;#o;#u;get cursor(){return this.#r}get userInputWithCursor(){if(!this.userInput)return qi(["inverse","hidden"],"_");if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let r=this.userInput.slice(0,this.cursor),e=this.userInput.slice(this.cursor,this.cursor+1),t=this.userInput.slice(this.cursor+1);return`${r}${qi("inverse",e)}${t}`}get options(){return typeof this.#o=="function"?this.#o():this.#o}constructor(r){super(r),this.#o=r.options,this.#u=r.placeholder;let e=this.options;this.filteredOptions=[...e],this.multiple=r.multiple===!0,this.#n=typeof r.options=="function"?r.filter:r.filter??gm;let t;if(r.initialValue&&Array.isArray(r.initialValue)?this.multiple?t=r.initialValue:t=r.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(t=[this.options[0]?.value]),t)for(let i of t){let o=e.findIndex((s)=>s.value===i);o!==-1&&(this.toggleSelected(i),this.#r=o)}this.focusedValue=this.options[this.#r]?.value,this.on("key",(i,o)=>this.#e(i,o)),this.on("userInput",(i)=>this.#t(i))}_isActionKey(r,e){return r==="\t"||this.multiple&&this.isNavigating&&e.name==="space"&&r!==void 0&&r!==""}#e(r,e){let t=e.name==="up",i=e.name==="down",o=e.name==="return",s=this.userInput===""||this.userInput==="\t",u=this.#u,c=this.options,h=u!==void 0&&u!==""&&c.some((f)=>!f.disabled&&(this.#n?this.#n(u,f):!0));if(e.name==="tab"&&s&&h){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(u,!0),this.isNavigating=!1;return}t||i?(this.#r=dr(this.#r,t?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#r]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):o?this.value=lm(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(e.name==="tab"||this.isNavigating&&e.name==="space")?this.toggleSelected(this.focusedValue):this.isNavigating=!1:(this.focusedValue&&(this.selectedValues=[this.focusedValue]),this.isNavigating=!1)}deselectAll(){this.selectedValues=[]}toggleSelected(r){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(r)?this.selectedValues=this.selectedValues.filter((e)=>e!==r):this.selectedValues=[...this.selectedValues,r]:this.selectedValues=[r])}#t(r){if(r!==this.#i){this.#i=r;let e=this.options;r&&this.#n?this.filteredOptions=e.filter((o)=>this.#n?.(r,o)):this.filteredOptions=[...e];let t=fm(this.focusedValue,this.filteredOptions);this.#r=dr(t,0,this.filteredOptions);let i=this.filteredOptions[this.#r];i&&!i.disabled?this.focusedValue=i.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}};class Vi extends sr{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(n){super(n,!1),this.value=!!n.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(r)=>{this.output.write(Zn.cursor.move(0,-1)),this.value=r,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var dm={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function Mh(n){return[...n].map((r)=>dm[r])}function mm(n){let r=new Intl.DateTimeFormat(n,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2000,0,15)),e=[],t="/";for(let i of r)i.type==="literal"?t=i.value.trim()||i.value:(i.type==="year"||i.type==="month"||i.type==="day")&&e.push({type:i.type,len:i.type==="year"?4:2});return{segments:e,separator:t}}function Zi(n){return Number.parseInt((n||"0").replace(/_/g,"0"),10)||0}function vt(n){return{year:Zi(n.year),month:Zi(n.month),day:Zi(n.day)}}function Xi(n,r){return new Date(n||2001,r||1,0).getDate()}function Ih(n){let{year:r,month:e,day:t}=vt(n);if(!r||r<0||r>9999||!e||e<1||e>12||!t||t<1)return;let i=new Date(Date.UTC(r,e-1,t));if(!(i.getUTCFullYear()!==r||i.getUTCMonth()!==e-1||i.getUTCDate()!==t))return{year:r,month:e,day:t}}function Eh(n){let r=Ih(n);return r?new Date(Date.UTC(r.year,r.month-1,r.day)):void 0}function $m(n,r,e,t){let i=e?{year:e.getUTCFullYear(),month:e.getUTCMonth()+1,day:e.getUTCDate()}:null,o=t?{year:t.getUTCFullYear(),month:t.getUTCMonth()+1,day:t.getUTCDate()}:null;return n==="year"?{min:i?.year??1,max:o?.year??9999}:n==="month"?{min:i&&r.year===i.year?i.month:1,max:o&&r.year===o.year?o.month:12}:{min:i&&r.year===i.year&&r.month===i.month?i.day:1,max:o&&r.year===o.year&&r.month===o.month?o.day:Xi(r.year,r.month)}}class Sh extends sr{#r;#i;#n;#o;#u;#e={segmentIndex:0,positionInSegment:0};#t=!0;#s=null;inlineError="";get segmentCursor(){return{...this.#e}}get segmentValues(){return{...this.#n}}get segments(){return this.#r}get separator(){return this.#i}get formattedValue(){return this.#g(this.#n)}#g(n){return this.#r.map((r)=>n[r.type]).join(this.#i)}#c(){this._setUserInput(this.#g(this.#n)),this._setValue(Eh(this.#n)??void 0)}constructor(n){let r=n.format?{segments:Mh(n.format),separator:n.separator??"/"}:mm(n.locale),e=n.separator??r.separator,t=n.format?Mh(n.format):r.segments,i=n.initialValue??n.defaultValue,o=i?{year:String(i.getUTCFullYear()).padStart(4,"0"),month:String(i.getUTCMonth()+1).padStart(2,"0"),day:String(i.getUTCDate()).padStart(2,"0")}:{year:"____",month:"__",day:"__"},s=t.map((u)=>o[u.type]).join(e);super({...n,initialUserInput:s},!1),this.#r=t,this.#i=e,this.#n=o,this.#o=n.minDate,this.#u=n.maxDate,this.#c(),this.on("cursor",(u)=>this.#d(u)),this.on("key",(u,c)=>this.#m(u,c)),this.on("finalize",()=>this.#$(n))}#h(){let n=Math.max(0,Math.min(this.#e.segmentIndex,this.#r.length-1)),r=this.#r[n];if(r)return this.#e.positionInSegment=Math.max(0,Math.min(this.#e.positionInSegment,r.len-1)),{segment:r,index:n}}#f(n){this.inlineError="",this.#s=null;let r=this.#h();r&&(this.#e.segmentIndex=Math.max(0,Math.min(this.#r.length-1,r.index+n)),this.#e.positionInSegment=0,this.#t=!0)}#l(n){let r=this.#h();if(!r)return;let{segment:e}=r,t=this.#n[e.type],i=!t||t.replace(/_/g,"")==="",o=Number.parseInt((t||"0").replace(/_/g,"0"),10)||0,s=$m(e.type,vt(this.#n),this.#o,this.#u),u;i?u=n===1?s.min:s.max:u=Math.max(Math.min(s.max,o+n),s.min),this.#n={...this.#n,[e.type]:u.toString().padStart(e.len,"0")},this.#t=!0,this.#s=null,this.#c()}#d(n){if(n)switch(n){case"right":return this.#f(1);case"left":return this.#f(-1);case"up":return this.#l(1);case"down":return this.#l(-1)}}#m(n,r){if(r?.name==="backspace"||r?.sequence===""||r?.sequence==="\b"||n===""||n==="\b"){this.inlineError="";let e=this.#h();if(!e)return;if(!this.#n[e.segment.type].replace(/_/g,"")){this.#f(-1);return}this.#n[e.segment.type]="_".repeat(e.segment.len),this.#t=!0,this.#e.positionInSegment=0,this.#c();return}if(r?.name==="tab"){this.inlineError="";let e=this.#h();if(!e)return;let t=r.shift?-1:1,i=e.index+t;i>=0&&i<this.#r.length&&(this.#e.segmentIndex=i,this.#e.positionInSegment=0,this.#t=!0);return}if(n&&/^[0-9]$/.test(n)){let e=this.#h();if(!e)return;let{segment:t}=e,i=!this.#n[t.type].replace(/_/g,"");if(this.#t&&this.#s!==null&&!i){let g=this.#s+n,d={...this.#n,[t.type]:g},w=this.#a(d,t);if(w){this.inlineError=w,this.#s=null,this.#t=!1;return}this.inlineError="",this.#n[t.type]=g,this.#s=null,this.#t=!1,this.#c(),e.index<this.#r.length-1&&(this.#e.segmentIndex=e.index+1,this.#e.positionInSegment=0,this.#t=!0);return}this.#t&&!i&&(this.#n[t.type]="_".repeat(t.len),this.#e.positionInSegment=0),this.#t=!1,this.#s=null;let o=this.#n[t.type],s=o.indexOf("_"),u=s>=0?s:Math.min(this.#e.positionInSegment,t.len-1);if(u<0||u>=t.len)return;let c=o.slice(0,u)+n+o.slice(u+1),h=!1;if(u===0&&o==="__"&&(t.type==="month"||t.type==="day")){let g=Number.parseInt(n,10);c=`0${n}`,h=g<=(t.type==="month"?1:2)}if(t.type==="year"&&(c=(o.replace(/_/g,"")+n).padStart(t.len,"_")),!c.includes("_")){let g={...this.#n,[t.type]:c},d=this.#a(g,t);if(d){this.inlineError=d;return}}this.inlineError="",this.#n[t.type]=c;let f=c.includes("_")?void 0:Ih(this.#n);if(f){let{year:g,month:d}=f,w=Xi(g,d);this.#n={year:String(Math.max(0,Math.min(9999,g))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,d))).padStart(2,"0"),day:String(Math.max(1,Math.min(w,f.day))).padStart(2,"0")}}this.#c();let l=c.indexOf("_");h?(this.#t=!0,this.#s=n):l>=0?this.#e.positionInSegment=l:s>=0&&e.index<this.#r.length-1?(this.#e.segmentIndex=e.index+1,this.#e.positionInSegment=0,this.#t=!0):this.#e.positionInSegment=Math.min(u+1,t.len-1)}}#a(n,r){let{month:e,day:t}=vt(n);if(r.type==="month"&&(e<0||e>12))return Pn.date.messages.invalidMonth;if(r.type==="day"&&(t<0||t>31))return Pn.date.messages.invalidDay(31,"any month")}#$(n){let{year:r,month:e,day:t}=vt(this.#n);if(r&&e&&t){let i=Xi(r,e);this.#n={...this.#n,day:String(Math.min(t,i)).padStart(2,"0")}}this.value=Eh(this.#n)??n.defaultValue??void 0}}var wm=class extends sr{options;cursor=0;#r;getGroupItems(r){return this.options.filter((e)=>e.group===r)}isGroupSelected(r){let e=this.getGroupItems(r),t=this.value;return t===void 0?!1:e.every((i)=>t.includes(i.value))}toggleValue(){let r=this.options[this.cursor];if(r!==void 0)if(this.value===void 0&&(this.value=[]),r.group===!0){let e=r.value,t=this.getGroupItems(e);this.isGroupSelected(e)?this.value=this.value.filter((i)=>t.findIndex((o)=>o.value===i)===-1):this.value=[...this.value,...t.map((i)=>i.value)],this.value=Array.from(new Set(this.value))}else{let e=this.value.includes(r.value);this.value=e?this.value.filter((t)=>t!==r.value):[...this.value,r.value]}}constructor(r){super(r,!1);let{options:e}=r;this.#r=r.selectableGroups!==!1,this.options=Object.entries(e).flatMap(([t,i])=>[{value:t,group:!0,label:t},...i.map((o)=>({...o,group:t}))]),this.value=[...r.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:t})=>t===r.cursorAt),this.#r?0:1),this.on("cursor",(t)=>{switch(t){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let i=this.options[this.cursor]?.group===!0;!this.#r&&i&&(this.cursor=this.cursor===0?this.options.length-1:this.cursor-1);break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let i=this.options[this.cursor]?.group===!0;!this.#r&&i&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},pm=new Set(["up","down","left","right"]);class Nh extends sr{#r=!1;#i;focused="editor";get userInputWithCursor(){if(this.state==="submit")return this.userInput;let n=this.userInput;if(this.cursor>=n.length)return`${n}█`;let r=n.slice(0,this.cursor),e=n.slice(this.cursor,this.cursor+1),t=n.slice(this.cursor+1);return e===`
88
108
  `?`${r}█
89
- ${e}`:`${r}${Gi("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))}#s(n){let r=this.value??"";switch(n){case"up":this._cursor=ge(this._cursor,0,-1,r);return;case"down":this._cursor=ge(this._cursor,0,1,r);return;case"left":this._cursor=ge(this._cursor,-1,0,r);return;case"right":this._cursor=ge(this._cursor,1,0,r);return}}_shouldSubmit(n,r){if(this.#i)return this.focused==="submit"?!0:(this.#n(`
90
- `),this._cursor++,!1);let t=this.#r;return this.#r=!0,t&&this.cursor===this.userInput.length?(this.userInput[this.cursor-1]===`
109
+ ${t}`:`${r}${qi("inverse",e)}${t}`}get cursor(){return this._cursor}#n(n){if(this.userInput.length===0){this._setUserInput(n);return}this._setUserInput(this.userInput.slice(0,this.cursor)+n+this.userInput.slice(this.cursor))}#o(n){let r=this.value??"";switch(n){case"up":this._cursor=Mt(this._cursor,0,-1,r);return;case"down":this._cursor=Mt(this._cursor,0,1,r);return;case"left":this._cursor=Mt(this._cursor,-1,0,r);return;case"right":this._cursor=Mt(this._cursor,1,0,r);return}}_shouldSubmit(n,r){if(this.#i)return this.focused==="submit"?!0:(this.#n(`
110
+ `),this._cursor++,!1);let e=this.#r;return this.#r=!0,e&&this.cursor===this.userInput.length?(this.userInput[this.cursor-1]===`
91
111
  `&&(this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--),!0):(this.#n(`
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&&Wa.has(e.name)){this.#r=!1,this.#s(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 Li extends er{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?lr(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=lr(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=lr(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}var fh=class extends er{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?lr(e,1,this.options):e,this.changeValue(),this.on("cursor",(i)=>{switch(i){case"left":case"up":this.cursor=lr(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=lr(this.cursor,1,this.options);break}this.changeValue()})}};import{styleText as M,stripVTControlCharacters as J1}from"node:util";import An from"node:process";var mh=Kt(Hi(),1);function Xa(){if(An.platform!=="win32")return An.env.TERM!=="linux";return Boolean(An.env.CI)||Boolean(An.env.WT_SESSION)||Boolean(An.env.TERMINUS_SUBLIME)||An.env.ConEmuTask==="{cmd::Cmder}"||An.env.TERM_PROGRAM==="Terminus-Sublime"||An.env.TERM_PROGRAM==="vscode"||An.env.TERM==="xterm-256color"||An.env.TERM==="alacritty"||An.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var Va=Xa();var dn=(n,r)=>Va?n:r,Ya=dn("◆","*"),Aa=dn("■","x"),za=dn("▲","x"),$h=dn("◇","o"),Ta=dn("┌","T"),hn=dn("│","|"),Gr=dn("└","—"),P1=dn("┐","T"),Z1=dn("┘","—"),Qi=dn("●",">"),$e=dn("○"," "),Ca=dn("◻","[•]"),gh=dn("◼","[+]"),lh=dn("◻","[ ]"),q1=dn("▪","•"),dh=dn("─","-"),_a=dn("╮","+"),Ba=dn("├","+"),xa=dn("╯","+"),Da=dn("╰","+"),U1=dn("╭","+"),W1=dn("●","•"),X1=dn("◆","*"),V1=dn("▲","!"),Y1=dn("■","x"),Zi=(n)=>{switch(n){case"initial":case"active":return M("cyan",Ya);case"cancel":return M("red",Aa);case"error":return M("yellow",za);case"submit":return M("green",$h)}},bh=(n)=>{switch(n){case"initial":case"active":return M("cyan",hn);case"cancel":return M("red",hn);case"error":return M("yellow",hn);case"submit":return M("green",hn)}};function wh(n,r){let t=[`${r?`${M("cyan",hn)} `:""}${n.join(" • ")}`];return r&&t.push(M("cyan",Gr)),t}var ah=(n,r,t,e,i,s=!1)=>{let o=r,u=0;if(s)for(let c=e-1;c>=t;c--){let h=n[c];if(h&&(o-=h.length),u++,o<=i)break}else for(let c=t;c<e;c++){let h=n[c];if(h&&(o-=h.length),u++,o<=i)break}return{lineCount:o,removals:u}},Pi=({cursor:n,options:r,style:t,output:e=process.stdout,maxItems:i=Number.POSITIVE_INFINITY,columnPadding:s=0,rowPadding:o=4})=>{let u=ae(e)-s,c=Ji(e),h=M("dim","..."),f=Math.max(c-o,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 a=g<r.length&&l>0,m=g<r.length&&l+g<r.length,b=Math.min(l+g,r.length),E=[],F=0;a&&F++,m&&F++;let H=l+(a?1:0),p=b-(m?1:0);for(let w=H;w<p;w++){let O=r[w],k=O?t(O,w===n):"",G=Mr(k,u,{hard:!0,trim:!1}).split(`
93
- `);E.push(G),F+=G.length}if(F>f){let w=0,O=0,k=F,G=n-H,S=f,K=()=>ah(E,k,0,G,S),R=()=>ah(E,k,G+1,E.length,S,!0);a?({lineCount:k,removals:w}=K(),k>S&&(m||(S-=1),{lineCount:k,removals:O}=R())):(m||(S-=1),{lineCount:k,removals:O}=R(),k>S&&(S-=1,{lineCount:k,removals:w}=K())),w>0&&(a=!0,E.splice(0,w)),O>0&&(m=!0,E.splice(E.length-O,O))}let I=[];a&&I.push(h);for(let w of E)for(let O of w)I.push(O);return m&&I.push(h),I};var kh=(n)=>{let r=n.active??"Yes",t=n.inactive??"No";return new Ki({active:r,inactive:t,signal:n.signal,input:n.input,output:n.output,initialValue:n.initialValue??!0,render(){let e=n.withGuide??Ln.withGuide,i=`${Zi(this.state)} `,s=e?`${M("gray",hn)} `:"",o=Er(n.output,n.message,s,i),u=`${e?`${M("gray",hn)}
94
- `:""}${o}
95
- `,c=this.value?r:t;switch(this.state){case"submit":{let h=e?`${M("gray",hn)} `:"";return`${u}${h}${M("dim",c)}`}case"cancel":{let h=e?`${M("gray",hn)} `:"";return`${u}${h}${M(["strikethrough","dim"],c)}${e?`
96
- ${M("gray",hn)}`:""}`}default:{let h=e?`${M("cyan",hn)} `:"",f=e?M("cyan",Gr):"";return`${u}${h}${this.value?`${M("green",Qi)} ${r}`:`${M("dim",$e)} ${M("dim",r)}`}${n.vertical?e?`
97
- ${M("cyan",hn)} `:`
98
- `:` ${M("dim","/")} `}${this.value?`${M("dim",$e)} ${M("dim",t)}`:`${M("green",Qi)} ${t}`}
99
- ${f}
100
- `}}}}).prompt()};var nm=[`${M("dim","↑/↓")} to navigate`,`${M("dim","Space:")} select`,`${M("dim","Enter:")} confirm`],St=(n,r)=>n.split(`
101
- `).map((t)=>r(t)).join(`
102
- `),ph=(n)=>{let r=(i,s)=>{let o=i.label??String(i.value);return s==="disabled"?`${M("gray",lh)} ${St(o,(u)=>M(["strikethrough","gray"],u))}${i.hint?` ${M("dim",`(${i.hint??"disabled"})`)}`:""}`:s==="active"?`${M("cyan",Ca)} ${o}${i.hint?` ${M("dim",`(${i.hint})`)}`:""}`:s==="selected"?`${M("green",gh)} ${St(o,(u)=>M("dim",u))}${i.hint?` ${M("dim",`(${i.hint})`)}`:""}`:s==="cancelled"?`${St(o,(u)=>M(["strikethrough","dim"],u))}`:s==="active-selected"?`${M("green",gh)} ${o}${i.hint?` ${M("dim",`(${i.hint})`)}`:""}`:s==="submitted"?`${St(o,(u)=>M("dim",u))}`:`${M("dim",lh)} ${St(o,(u)=>M("dim",u))}`},t=n.required??!0,e=n.showInstructions??!0;return new Li({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
- ${M("reset",M("dim",`Press ${M(["gray","bgWhite","inverse"]," space ")} to select, ${M("gray",M("bgWhite",M("inverse"," enter ")))} to submit`))}`},render(){let i=n.withGuide??Ln.withGuide,s=Er(n.output,n.message,i?`${bh(this.state)} `:"",`${Zi(this.state)} `),o=`${i?`${M("gray",hn)}
112
+ `),this._cursor++,!1)}constructor(n){let r=n.initialUserInput??n.initialValue;super({...n,initialUserInput:r},!1),r!==void 0&&(this._cursor=r.length),this.#i=n.showSubmit??!1,this.on("key",(e,t)=>{if(t?.name&&pm.has(t.name)){this.#r=!1,this.#o(t.name);return}if(e==="\t"&&this.#i){this.focused=this.focused==="editor"?"submit":"editor";return}if(t?.name!=="return"){if(this.#r=!1,t?.name==="backspace"&&this.cursor>0){this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--;return}if(t?.name==="delete"&&this.cursor<this.userInput.length){this._setUserInput(this.userInput.slice(0,this.cursor)+this.userInput.slice(this.cursor+1));return}e&&(this.#i&&this.focused==="submit"&&(this.focused="editor"),this.#n(e??""),this._cursor++)}}),this.on("userInput",(e)=>{this._setValue(e)}),this.on("finalize",()=>{this.value||(this.value=n.defaultValue),this.value===void 0&&(this.value="")})}}class zi extends sr{options;cursor=0;get _value(){return this.options[this.cursor]?.value}get _enabledOptions(){return this.options.filter((n)=>n.disabled!==!0)}toggleAll(){let n=this._enabledOptions,r=this.value!==void 0&&this.value.length===n.length;this.value=r?[]:n.map((e)=>e.value)}toggleInvert(){let n=this.value;if(!n)return;let r=this._enabledOptions.filter((e)=>!n.includes(e.value));this.value=r.map((e)=>e.value)}toggleValue(){this.value===void 0&&(this.value=[]);let n=this.value.includes(this._value);this.value=n?this.value.filter((r)=>r!==this._value):[...this.value,this._value]}constructor(n){super(n,!1),this.options=n.options,this.value=[...n.initialValues??[]];let r=Math.max(this.options.findIndex(({value:e})=>e===n.cursorAt),0);this.cursor=this.options[r]?.disabled?dr(r,1,this.options):r,this.on("key",(e,t)=>{t.name==="a"&&this.toggleAll(),t.name==="i"&&this.toggleInvert()}),this.on("cursor",(e)=>{switch(e){case"left":case"up":this.cursor=dr(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=dr(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}var Hh=class extends sr{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){let r=this._selectedValue;this.value=r===void 0?void 0:r.value}constructor(r){super(r,!1),this.options=r.options;let e=this.options.findIndex(({value:i})=>i===r.initialValue),t=e===-1?0:e;this.cursor=this.options[t]?.disabled?dr(t,1,this.options):t,this.changeValue(),this.on("cursor",(i)=>{switch(i){case"left":case"up":this.cursor=dr(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=dr(this.cursor,1,this.options);break}this.changeValue()})}};import{styleText as E,stripVTControlCharacters as bp}from"node:util";import Yn from"node:process";var Lh=Te(Wi(),1);function bm(){if(Yn.platform!=="win32")return Yn.env.TERM!=="linux";return Boolean(Yn.env.CI)||Boolean(Yn.env.WT_SESSION)||Boolean(Yn.env.TERMINUS_SUBLIME)||Yn.env.ConEmuTask==="{cmd::Cmder}"||Yn.env.TERM_PROGRAM==="Terminus-Sublime"||Yn.env.TERM_PROGRAM==="vscode"||Yn.env.TERM==="xterm-256color"||Yn.env.TERM==="alacritty"||Yn.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var km=bm();var dn=(n,r)=>km?n:r,Mm=dn("◆","*"),Em=dn("■","x"),vm=dn("▲","x"),Jh=dn("◇","o"),Fm=dn("┌","T"),hn=dn("│","|"),Gr=dn("└","—"),vp=dn("┐","T"),Fp=dn("┘","—"),Yi=dn("●",">"),It=dn("○"," "),ym=dn("◻","[•]"),Oh=dn("◼","[+]"),jh=dn("◻","[ ]"),yp=dn("▪","•"),Rh=dn("─","-"),Im=dn("╮","+"),Sm=dn("├","+"),Nm=dn("╯","+"),Hm=dn("╰","+"),Ip=dn("╭","+"),Sp=dn("●","•"),Np=dn("◆","*"),Hp=dn("▲","!"),Op=dn("■","x"),_i=(n)=>{switch(n){case"initial":case"active":return E("cyan",Mm);case"cancel":return E("red",Em);case"error":return E("yellow",vm);case"submit":return E("green",Jh)}},Kh=(n)=>{switch(n){case"initial":case"active":return E("cyan",hn);case"cancel":return E("red",hn);case"error":return E("yellow",hn);case"submit":return E("green",hn)}};function Ph(n,r){let e=[`${r?`${E("cyan",hn)} `:""}${n.join(" • ")}`];return r&&e.push(E("cyan",Gr)),e}var Gh=(n,r,e,t,i,o=!1)=>{let s=r,u=0;if(o)for(let c=t-1;c>=e;c--){let h=n[c];if(h&&(s-=h.length),u++,s<=i)break}else for(let c=e;c<t;c++){let h=n[c];if(h&&(s-=h.length),u++,s<=i)break}return{lineCount:s,removals:u}},Ci=({cursor:n,options:r,style:e,output:t=process.stdout,maxItems:i=Number.POSITIVE_INFINITY,columnPadding:o=0,rowPadding:s=4})=>{let u=Ft(t)-o,c=Ti(t),h=E("dim","..."),f=Math.max(c-s,0),l=Math.max(Math.min(i,f),5),g=0;n>=l-3&&(g=Math.max(Math.min(n-l+3,r.length-l),0));let d=l<r.length&&g>0,w=l<r.length&&g+l<r.length,m=Math.min(g+l,r.length),b=[],F=0;d&&F++,w&&F++;let S=g+(d?1:0),k=m-(w?1:0);for(let p=S;p<k;p++){let R=r[p],M=R?e(R,p===n):"",j=Er(M,u,{hard:!0,trim:!1}).split(`
113
+ `);b.push(j),F+=j.length}if(F>f){let p=0,R=0,M=F,j=n-S,H=f,J=()=>Gh(b,M,0,j,H),G=()=>Gh(b,M,j+1,b.length,H,!0);d?({lineCount:M,removals:p}=J(),M>H&&(w||(H-=1),{lineCount:M,removals:R}=G())):(w||(H-=1),{lineCount:M,removals:R}=G(),M>H&&(H-=1,{lineCount:M,removals:p}=J())),p>0&&(d=!0,b.splice(0,p)),R>0&&(w=!0,b.splice(b.length-R,R))}let y=[];d&&y.push(h);for(let p of b)for(let R of p)y.push(R);return w&&y.push(h),y};var Uh=(n)=>{let r=n.active??"Yes",e=n.inactive??"No";return new Vi({active:r,inactive:e,signal:n.signal,input:n.input,output:n.output,initialValue:n.initialValue??!0,render(){let t=n.withGuide??Pn.withGuide,i=`${_i(this.state)} `,o=t?`${E("gray",hn)} `:"",s=vr(n.output,n.message,o,i),u=`${t?`${E("gray",hn)}
104
114
  `:""}${s}
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(M("dim",", "))||M("dim","none"),f=Er(n.output,h,i?`${M("gray",hn)} `:"");return`${o}${f}`}case"cancel":{let h=this.options.filter(({value:g})=>u.includes(g)).map((g)=>r(g,"cancelled")).join(M("dim",", "));if(h.trim()==="")return`${o}${M("gray",hn)}`;let f=Er(n.output,h,i?`${M("gray",hn)} `:"");return`${o}${f}${i?`
106
- ${M("gray",hn)}`:""}`}case"error":{let h=i?`${M("yellow",hn)} `:"",f=this.error.split(`
107
- `).map((a,m)=>m===0?`${i?`${M("yellow",Gr)} `:""}${M("yellow",a)}`:` ${a}`).join(`
108
- `),g=o.split(`
109
- `).length,l=f.split(`
110
- `).length+1;return`${o}${h}${Pi({output:n.output,options:this.options,cursor:this.cursor,maxItems:n.maxItems,columnPadding:h.length,rowPadding:g+l,style:c}).join(`
115
+ `,c=this.value?r:e;switch(this.state){case"submit":{let h=t?`${E("gray",hn)} `:"";return`${u}${h}${E("dim",c)}`}case"cancel":{let h=t?`${E("gray",hn)} `:"";return`${u}${h}${E(["strikethrough","dim"],c)}${t?`
116
+ ${E("gray",hn)}`:""}`}default:{let h=t?`${E("cyan",hn)} `:"",f=t?E("cyan",Gr):"";return`${u}${h}${this.value?`${E("green",Yi)} ${r}`:`${E("dim",It)} ${E("dim",r)}`}${n.vertical?t?`
117
+ ${E("cyan",hn)} `:`
118
+ `:` ${E("dim","/")} `}${this.value?`${E("dim",It)} ${E("dim",e)}`:`${E("green",Yi)} ${e}`}
119
+ ${f}
120
+ `}}}}).prompt()};var Om=[`${E("dim","↑/↓")} to navigate`,`${E("dim","Space:")} select`,`${E("dim","Enter:")} confirm`],We=(n,r)=>n.split(`
121
+ `).map((e)=>r(e)).join(`
122
+ `),Qh=(n)=>{let r=(i,o)=>{let s=i.label??String(i.value);return o==="disabled"?`${E("gray",jh)} ${We(s,(u)=>E(["strikethrough","gray"],u))}${i.hint?` ${E("dim",`(${i.hint??"disabled"})`)}`:""}`:o==="active"?`${E("cyan",ym)} ${s}${i.hint?` ${E("dim",`(${i.hint})`)}`:""}`:o==="selected"?`${E("green",Oh)} ${We(s,(u)=>E("dim",u))}${i.hint?` ${E("dim",`(${i.hint})`)}`:""}`:o==="cancelled"?`${We(s,(u)=>E(["strikethrough","dim"],u))}`:o==="active-selected"?`${E("green",Oh)} ${s}${i.hint?` ${E("dim",`(${i.hint})`)}`:""}`:o==="submitted"?`${We(s,(u)=>E("dim",u))}`:`${E("dim",jh)} ${We(s,(u)=>E("dim",u))}`},e=n.required??!0,t=n.showInstructions??!0;return new zi({options:n.options,signal:n.signal,input:n.input,output:n.output,initialValues:n.initialValues,required:e,cursorAt:n.cursorAt,validate(i){if(e&&(i===void 0||i.length===0))return`Please select at least one option.
123
+ ${E("reset",E("dim",`Press ${E(["gray","bgWhite","inverse"]," space ")} to select, ${E("gray",E("bgWhite",E("inverse"," enter ")))} to submit`))}`},render(){let i=n.withGuide??Pn.withGuide,o=vr(n.output,n.message,i?`${Kh(this.state)} `:"",`${_i(this.state)} `),s=`${i?`${E("gray",hn)}
124
+ `:""}${o}
125
+ `,u=this.value??[],c=(h,f)=>{if(h.disabled)return r(h,"disabled");let l=u.includes(h.value);return f&&l?r(h,"active-selected"):l?r(h,"selected"):r(h,f?"active":"inactive")};switch(this.state){case"submit":{let h=this.options.filter(({value:l})=>u.includes(l)).map((l)=>r(l,"submitted")).join(E("dim",", "))||E("dim","none"),f=vr(n.output,h,i?`${E("gray",hn)} `:"");return`${s}${f}`}case"cancel":{let h=this.options.filter(({value:l})=>u.includes(l)).map((l)=>r(l,"cancelled")).join(E("dim",", "));if(h.trim()==="")return`${s}${E("gray",hn)}`;let f=vr(n.output,h,i?`${E("gray",hn)} `:"");return`${s}${f}${i?`
126
+ ${E("gray",hn)}`:""}`}case"error":{let h=i?`${E("yellow",hn)} `:"",f=this.error.split(`
127
+ `).map((d,w)=>w===0?`${i?`${E("yellow",Gr)} `:""}${E("yellow",d)}`:` ${d}`).join(`
128
+ `),l=s.split(`
129
+ `).length,g=f.split(`
130
+ `).length+1;return`${s}${h}${Ci({output:n.output,options:this.options,cursor:this.cursor,maxItems:n.maxItems,columnPadding:h.length,rowPadding:l+g,style:c}).join(`
111
131
  ${h}`)}
112
132
  ${f}
113
- `}default:{let h=i?`${M("cyan",hn)} `:"",f=o.split(`
114
- `).length,g=e?wh(nm,i):i?[M("cyan",Gr)]:[],l=g.join(`
115
- `),a=g.length+1;return`${o}${h}${Pi({output:n.output,options:this.options,cursor:this.cursor,maxItems:n.maxItems,columnPadding:h.length,rowPadding:f+a,style:c}).join(`
133
+ `}default:{let h=i?`${E("cyan",hn)} `:"",f=s.split(`
134
+ `).length,l=t?Ph(Om,i):i?[E("cyan",Gr)]:[],g=l.join(`
135
+ `),d=l.length+1;return`${s}${h}${Ci({output:n.output,options:this.options,cursor:this.cursor,maxItems:n.maxItems,columnPadding:h.length,rowPadding:f+d,style:c}).join(`
116
136
  ${h}`)}
117
- ${l}
118
- `}}}}).prompt()};var be=(n="",r)=>{let t=r?.output??process.stdout,e=r?.withGuide??Ln.withGuide?`${M("gray",Gr)} `:"";t.write(`${e}${M("red",n)}
137
+ ${g}
138
+ `}}}}).prompt()};var St=(n="",r)=>{let e=r?.output??process.stdout,t=r?.withGuide??Pn.withGuide?`${E("gray",Gr)} `:"";e.write(`${t}${E("red",n)}
119
139
 
120
- `)},Mh=(n="",r)=>{let t=r?.output??process.stdout,e=r?.withGuide??Ln.withGuide?`${M("gray",Ta)} `:"";t.write(`${e}${n}
121
- `)},Eh=(n="",r)=>{let t=r?.output??process.stdout,e=r?.withGuide??Ln.withGuide?`${M("gray",hn)}
122
- ${M("gray",Gr)} `:"";t.write(`${e}${n}
140
+ `)},Wh=(n="",r)=>{let e=r?.output??process.stdout,t=r?.withGuide??Pn.withGuide?`${E("gray",Fm)} `:"";e.write(`${t}${n}
141
+ `)},Zh=(n="",r)=>{let e=r?.output??process.stdout,t=r?.withGuide??Pn.withGuide?`${E("gray",hn)}
142
+ ${E("gray",Gr)} `:"";e.write(`${t}${n}
123
143
 
124
- `)};var rm=(n)=>n,tm=(n,r,t)=>{let e={hard:!0,trim:!1},i=Mr(n,r,e).split(`
125
- `),s=i.reduce((c,h)=>Math.max(Kn(h),c),0),o=i.map(t).reduce((c,h)=>Math.max(Kn(h),c),0),u=r-(o-s);return Mr(n,u,e)},we=(n="",r="",t)=>{let e=t?.output??An.stdout,i=t?.withGuide??Ln.withGuide,s=t?.format??rm,o=["",...tm(n,ae(e)-6,s).split(`
126
- `).map(s),""],u=Kn(r),c=Math.max(o.reduce((l,a)=>{let m=Kn(a);return m>l?m:l},0),u)+2,h=o.map((l)=>`${M("gray",hn)} ${l}${" ".repeat(c-Kn(l))}${M("gray",hn)}`).join(`
127
- `),f=i?`${M("gray",hn)}
128
- `:"",g=i?Ba:Da;e.write(`${f}${M("green",$h)} ${M("reset",r)} ${M("gray",dh.repeat(Math.max(c-u-1,1))+_a)}
144
+ `)};var jm=(n)=>n,Rm=(n,r,e)=>{let t={hard:!0,trim:!1},i=Er(n,r,t).split(`
145
+ `),o=i.reduce((c,h)=>Math.max(Kn(h),c),0),s=i.map(e).reduce((c,h)=>Math.max(Kn(h),c),0),u=r-(s-o);return Er(n,u,t)},Nt=(n="",r="",e)=>{let t=e?.output??Yn.stdout,i=e?.withGuide??Pn.withGuide,o=e?.format??jm,s=["",...Rm(n,Ft(t)-6,o).split(`
146
+ `).map(o),""],u=Kn(r),c=Math.max(s.reduce((g,d)=>{let w=Kn(d);return w>g?w:g},0),u)+2,h=s.map((g)=>`${E("gray",hn)} ${g}${" ".repeat(c-Kn(g))}${E("gray",hn)}`).join(`
147
+ `),f=i?`${E("gray",hn)}
148
+ `:"",l=i?Sm:Hm;t.write(`${f}${E("green",Jh)} ${E("reset",r)} ${E("gray",Rh.repeat(Math.max(c-u-1,1))+Im)}
129
149
  ${h}
130
- ${M("gray",g+dh.repeat(c+2)+xa)}
131
- `)};var A1={light:dn("─","-"),heavy:dn("━","="),block:dn("█","#")};var em=[`${M("dim","↑/↓")} to navigate`,`${M("dim","Enter:")} confirm`],me=(n,r)=>n.includes(`
150
+ ${E("gray",l+Rh.repeat(c+2)+Nm)}
151
+ `)};var jp={light:dn("─","-"),heavy:dn("━","="),block:dn("█","#")};var Gm=[`${E("dim","↑/↓")} to navigate`,`${E("dim","Enter:")} confirm`],yt=(n,r)=>n.includes(`
132
152
  `)?n.split(`
133
- `).map((t)=>r(t)).join(`
134
- `):r(n),vh=(n)=>{let r=(e,i)=>{if(e===void 0)return"";let s=e.label??String(e.value);switch(i){case"disabled":return`${M("gray",$e)} ${me(s,(o)=>M("gray",o))}${e.hint?` ${M("dim",`(${e.hint??"disabled"})`)}`:""}`;case"selected":return`${me(s,(o)=>M("dim",o))}`;case"active":return`${M("green",Qi)} ${s}${e.hint?` ${M("dim",`(${e.hint})`)}`:""}`;case"cancelled":return`${me(s,(o)=>M(["strikethrough","dim"],o))}`;default:return`${M("dim",$e)} ${me(s,(o)=>M("dim",o))}`}},t=n.showInstructions??!0;return new fh({options:n.options,signal:n.signal,input:n.input,output:n.output,initialValue:n.initialValue,render(){let e=n.withGuide??Ln.withGuide,i=`${Zi(this.state)} `,s=`${bh(this.state)} `,o=Er(n.output,n.message,s,i),u=`${e?`${M("gray",hn)}
135
- `:""}${o}
136
- `;switch(this.state){case"submit":{let c=e?`${M("gray",hn)} `:"",h=Er(n.output,r(this.options[this.cursor],"selected"),c);return`${u}${h}`}case"cancel":{let c=e?`${M("gray",hn)} `:"",h=Er(n.output,r(this.options[this.cursor],"cancelled"),c);return`${u}${h}${e?`
137
- ${M("gray",hn)}`:""}`}default:{let c=e?`${M("cyan",hn)} `:"",h=u.split(`
138
- `).length,f=t?wh(em,e):e?[M("cyan",Gr)]:[],g=f.join(`
139
- `),l=f.length+1;return`${u}${c}${Pi({output:n.output,cursor:this.cursor,options:this.options,maxItems:n.maxItems,columnPadding:c.length,rowPadding:h+l,style:(a,m)=>r(a,a.disabled?"disabled":m?"active":"inactive")}).join(`
153
+ `).map((e)=>r(e)).join(`
154
+ `):r(n),qh=(n)=>{let r=(t,i)=>{if(t===void 0)return"";let o=t.label??String(t.value);switch(i){case"disabled":return`${E("gray",It)} ${yt(o,(s)=>E("gray",s))}${t.hint?` ${E("dim",`(${t.hint??"disabled"})`)}`:""}`;case"selected":return`${yt(o,(s)=>E("dim",s))}`;case"active":return`${E("green",Yi)} ${o}${t.hint?` ${E("dim",`(${t.hint})`)}`:""}`;case"cancelled":return`${yt(o,(s)=>E(["strikethrough","dim"],s))}`;default:return`${E("dim",It)} ${yt(o,(s)=>E("dim",s))}`}},e=n.showInstructions??!0;return new Hh({options:n.options,signal:n.signal,input:n.input,output:n.output,initialValue:n.initialValue,render(){let t=n.withGuide??Pn.withGuide,i=`${_i(this.state)} `,o=`${Kh(this.state)} `,s=vr(n.output,n.message,o,i),u=`${t?`${E("gray",hn)}
155
+ `:""}${s}
156
+ `;switch(this.state){case"submit":{let c=t?`${E("gray",hn)} `:"",h=vr(n.output,r(this.options[this.cursor],"selected"),c);return`${u}${h}`}case"cancel":{let c=t?`${E("gray",hn)} `:"",h=vr(n.output,r(this.options[this.cursor],"cancelled"),c);return`${u}${h}${t?`
157
+ ${E("gray",hn)}`:""}`}default:{let c=t?`${E("cyan",hn)} `:"",h=u.split(`
158
+ `).length,f=e?Ph(Gm,t):t?[E("cyan",Gr)]:[],l=f.join(`
159
+ `),g=f.length+1;return`${u}${c}${Ci({output:n.output,cursor:this.cursor,options:this.options,maxItems:n.maxItems,columnPadding:c.length,rowPadding:h+g,style:(d,w)=>r(d,d.disabled?"disabled":w?"active":"inactive")}).join(`
140
160
  ${c}`)}
141
- ${g}
142
- `}}}}).prompt()};var z1=`${M("gray",hn)} `;import{existsSync as lm}from"node:fs";import{openSync as im,writeSync as sm}from"node:fs";import{ReadStream as om}from"node:tty";var Ih=["10","11","12","17",...Array.from({length:16},(n,r)=>`4;${r}`)];function ke(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 Nh(n){let r=new Map;for(let t of n.split("\x1B")){let e=t.match(/^\](\d+(?:;\d+)?);(rgba?:[0-9a-fA-F/]+)/),[,i,s]=e??[];if(i&&s)r.set(i,s)}return r}function yh(n){return[...n].map(([r,t])=>`\x1B]${r};${t}\x1B\\`).join("")}async function Sh(){let n,r;try{n=im("/dev/tty","r+"),r=new om(n),r.setRawMode(!0)}catch{return new Map}try{sm(n,Ih.map((e)=>`\x1B]${e};?\x1B\\`).join(""));let t="";return await new Promise((e)=>{let i=setTimeout(e,120);r.on("data",(s)=>{if(t+=s.toString(),Nh(t).size>=Ih.length)clearTimeout(i),e()})}),Nh(t)}finally{r.setRawMode(!1),r.destroy()}}function Br(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 Hh(n,r){return`\x1B[48;2;${Br(r)}m ${n} \x1B[0m`}function qi(n,r){return`\x1B[48;2;${Br(n)};38;2;${Br(r)}m ● \x1B[0m`}function jh(n){return`\x1B[38;2;${Br(n)}m`}function Ui(n,r){return`\x1B[48;2;${Br(r)}m${n.map((t)=>`\x1B[38;2;${Br(t)}m▄`).join("")} \x1B[0m`}function pe(n,r){let t=r.toLowerCase();return[n.name,n.group,n.native??""].some((e)=>e.toLowerCase().includes(t))}function Oh(n,r,t){let e=t.trim(),i=[],s=new Set;for(let o of n){if(o.default||s.has(o.group))continue;s.add(o.group);let u=n.filter((f)=>!f.default&&f.group===o.group),c=e?u.filter((f)=>pe(f,e)):u;if(e&&c.length===0)continue;let h=e.length>0||r.has(o.group);if(i.push({kind:"group",name:o.group,native:o.native,lead:u.find((f)=>f.lead)??o,expanded:h,count:c.length}),h)i.push(...c.map((f)=>({kind:"palette",entry:f})))}return i}function um(n,r){let t=r.trim(),e=new Set(n.filter((i)=>!i.default&&(t===""||pe(i,t))).map((i)=>i.group));return Oh(n,new Set,"").filter((i)=>i.kind==="group"&&e.has(i.name))}function cm(n){let r=n.findIndex((t)=>t.kind==="palette");return r===-1?0:r}var Bn="\x1B[0m",xr="\x1B[2m",hm="\x1B[1m",Gh="\x1B[1;7m",fm="\x1B[36m",gm="\x1B[33m";function Rh(n){return n==="decode"||n==="glitch"?n:"typewriter"}class Wi extends er{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===""||pe(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"?um(this.entries,this.userInput):Oh(this.entries,this.expanded,this.userInput),e=t.length>0?cm(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:"",s=i?this.rows.findIndex((o)=>o.kind==="palette"&&o.entry.name===i):-1;this.cursor=s===-1?e:s}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 s=this.everyone(this.rows).every((u)=>this.picked.has(u.name))?"● ":"○ ",o=`(${n.count})`;return`${t}${s}select all ${this.color?`${xr}${o}${Bn}`:o}`}if(n.kind==="group"&&this.scope==="series"){let s=this.pickedIn(n.name)===n.count?"● ":"○ ",o=n.name.padEnd(this.seriesPad),u=`(${n.count})${n.native?` ${n.native}`:""}`;if(!this.color)return`${t}${s}${o} ${u}`;let c=n.lead;return`${t}${s}${o} ${qi(c.background,c.cursor)}${Ui(c.ansi.slice(1,7),c.background)} ${xr}${u}${Bn}`}if(n.kind==="group"){let s=n.expanded?"▾":"▸",o=this.rows[this.cursor],u=o?.kind==="palette"&&o.entry.group===n.name?o.entry:void 0,c=this.color?r?`${Gh} ${n.name} ${Bn}`:u?`${Gh}${jh(u.cursor)} ${n.name} ${Bn}`:` ${hm}${n.name}${Bn} `:r?`[${n.name}]`:` ${n.name}`,h=this.color?Hh("●",n.lead.selection):"",f=`${this.pickedIn(n.name)}/${n.count}`,g=this.color?` ${xr}(${f})${Bn}`:` (${f})`,l=n.native?this.color?` ${xr}${n.native}${Bn}`:` ${n.native}`:"";return`${s}${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)} ${qi(e.background,e.cursor)}${Ui(e.ansi.slice(1,7),e.background)} ${xr}${e.ansiSource}${Bn}`}draw(){let n=(b)=>this.color?`${xr}${b}${Bn}`:b,r=(b)=>this.color?`${fm}${b}${Bn}`:b,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,s=this.scope==="series"?this.rows.filter((b)=>b.kind==="group").length:e?this.named.filter((b)=>pe(b,e)).length:i,o=`${r("◆")} ${t} ${n(`(${s}/${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((b,E)=>`${r("│")} ${this.renderRow(b,this.top+E===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",a=this.scope==="series"?"continue":"install",m=this.state==="error"?`${r("└")} ${this.color?`${gm}${this.error}${Bn}`:this.error}`:`${r("└")} ${n(`↑↓ move${l} · space pick · type to filter · enter ${a} · esc cancel`)}`;return[o,u,...h,g,m].join(`
143
- `)}}function Xi(n,r,t,e){let i=Vr(),s=Boolean(Yr(t))!==Boolean(Yr(e)),o=s?Ft(e,i):e;if(yt(n,r,o),Nt(n,o),s)It(o,i)}function Vi(n){console.log(`
144
- ${n} palettes installed — open a new tab, or reload your terminal config`)}function Jh(n){let r=_n(),t=Pn(r),e=fr(r),i=n.filter((u)=>e.palettes.includes(u)),s=n.filter((u)=>!e.palettes.includes(u));if(s.length===0){console.log(`already installed: ${i.join(", ")}`);return}let o={...e,palettes:[...e.palettes,...s]};Xi(r,t,e,o);for(let u of s)console.log(` + ${u}`);Vi(o.palettes.length)}function Kh(n){let r=_n(),t=Pn(r),e=fr(r),i=n.filter((o)=>e.palettes.includes(o));if(i.length===0){console.log(`not installed: ${n.join(", ")}`);return}let s={...e,palettes:e.palettes.filter((o)=>!i.includes(o))};Xi(r,t,e,s),ai(r,t,e.terminals,i);for(let o of i)console.log(` - ${o}`);Vi(s.palettes.length)}function Lh(n){let r=_n(),t=Pn(r),e=fr(r);if(!e.palettes.includes(n))throw Error(`${n} is not installed — \`ttheme add ${n}\` first`);let{keepTheme:i,...s}=e,o=Vr(),u=Ft({...s,startup:n},o);yt(r,t,u),Nt(r,u);let c=It(u,o);console.log(dm(n,u.terminals,c&&o.running()).join(`
145
- `))}function dm(n,r,t){let e=r.filter((s)=>s!=="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 Qh(n){let r=_n(),t=Pn(r),e=new Set(fr(r).palettes),i=Wr(t.palettes),s=pt(n?qu(i,n):i),o=Math.max(...s.map((c)=>c.name.length),0);for(let c of s)console.log(` ${e.has(c.name)?"●":"○"} ${c.name.padEnd(o)} ${c.group}`);let u=n?`${s.length} of ${i.length}`:`${i.length}`;console.log(`
146
- ${u} palettes — ${s.filter((c)=>e.has(c.name)).length} installed`)}async function Ph(){let n=_n(),r=lm(ne(n))?Pn(n).palettes.length:0,t=await Pu(Lu);re(n,t);let e=t.palettes.length-r;console.log(`catalog ${t.version} — ${t.palettes.length} palettes${e>0?` (+${e})`:""}`)}async function Yi(n,r,t,e=!1){let i=process.env.TTHEME_SORT==="series"?n.palettes:pt(n.palettes),s=process.stdout.isTTY===!0&&!process.env.NO_COLOR,o=s?await Sh():new Map,u=new Wi({entries:i,scope:t,installed:r,required:e,color:!process.env.NO_COLOR,fx:Rh(process.env.TTHEME_FX),onFocus:s?(h)=>process.stdout.write(ke(h)):void 0}),c=await u.prompt();if(process.stdout.write(yh(o)),_r(c))return;return n.palettes.filter((h)=>u.picked.has(h.name)).map((h)=>h.name)}async function Zh(){let n=_n(),r=Pn(n),t=fr(n),e=await Yi(r,t.palettes,"palette");if(!e){console.log("nothing changed");return}let i=t.palettes.filter((u)=>!e.includes(u)),s=e.filter((u)=>!t.palettes.includes(u));if(s.length===0&&i.length===0){console.log("nothing changed");return}let o={...t,palettes:e};Xi(n,r,t,o),ai(n,r,t.terminals,i);for(let u of s)console.log(` + ${u}`);for(let u of i)console.log(` - ${u}`);Vi(o.palettes.length)}function Wh(n,r,t){for(let e of $m(r))n.push({from:wn(r,e),to:wn(t,e)})}function Ah(n){return JSON.parse(jt(wn(n,"dist","manifest.json"),"utf8"))}function Xh(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")}];Wh(i,wn(r.root,"shell","adapters"),wn(e,"adapters"));let s=[{file:wn(r.zdotdir,".zshrc"),block:yu(e)}],o=wn(e,"config.zsh"),u=Hu(dr(o)?jt(o,"utf8"):""),c={file:o,content:n.wear?Bt(u,"TTHEME_TAB_PALETTE",n.wear==="rotate"?"seq":"off"):u},h=[];if(n.terminals.includes("ghostty"))Wh(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(dr(g)&&!jt(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:s,settings:c,catalog:Ah(r.root),installed:f,notes:h}}function wm(n){try{return fr(n).itermBase}catch{return}}function Vh(n,r=Vr()){for(let s of n.copies)if(Ai(Ht(s.to),{recursive:!0}),qh(s.to,{force:!0}),qh(`${s.to}.zwc`,{force:!0}),mm(s.from,s.to),s.executable)am(s.to,493);Ai(Ht(n.settings.file),{recursive:!0}),Uh(n.settings.file,n.settings.content);let t=Ht(Ht(n.settings.file)),e=wm(t),i=Ft(e?{...n.installed,itermBase:e}:n.installed,r);re(t,n.catalog),Nt(t,i),yt(t,n.catalog,i,n.home);for(let s of n.edits){Ai(Ht(s.file),{recursive:!0});let o=dr(s.file)?jt(s.file,"utf8"):"";Uh(s.file,Ct(o,s.block))}return It(i,r)}function zi(n){if(_r(n))be("nothing changed"),process.exit(1);return n}function zh(){return Tt.filter((n)=>n!=="iterm2"||process.platform==="darwin")}function km(n,r){return n==="iterm2"?dr(wn(r.home,"Library","Application Support","iTerm2")):dr(wn(r.configHome,n))}async function pm(n,r){return zi(await ph({message:"wire which terminals?",options:zh().map((t)=>({value:t,hint:t===n?"detected":void 0})),initialValues:r,required:!0}))}function Mm(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 zi(await vh({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 Yh(n){let r=[...n.copies.filter((t)=>!dr(t.to)).map((t)=>t.to),...dr(n.settings.file)?[]:[n.settings.file],...n.edits.filter((t)=>!jt(t.file,"utf8").includes("# ttheme begin")).map((t)=>t.file)];if(r.length>0)throw Error(`init left gaps:
161
+ ${l}
162
+ `}}}}).prompt()};var Rp=`${E("gray",hn)} `;import{existsSync as qm}from"node:fs";import{openSync as Lm,writeSync as Jm}from"node:fs";import{ReadStream as Km}from"node:tty";var Xh=["10","11","12","17",...Array.from({length:16},(n,r)=>`4;${r}`)];function Ht(n){let r=n.ansi.map((e,t)=>`;${t};${e}`).join("");return[`\x1B]11;${n.background}\x1B\\`,`\x1B]10;${n.foreground}\x1B\\`,`\x1B]12;${n.cursor}\x1B\\`,`\x1B]17;${n.selection}\x1B\\`,`\x1B]4${r}\x1B\\`].join("")}function Th(n){let r=new Map;for(let e of n.split("\x1B")){let t=e.match(/^\](\d+(?:;\d+)?);(rgba?:[0-9a-fA-F/]+)/),[,i,o]=t??[];if(i&&o)r.set(i,o)}return r}function Vh(n){return[...n].map(([r,e])=>`\x1B]${r};${e}\x1B\\`).join("")}async function zh(){let n,r;try{n=Lm("/dev/tty","r+"),r=new Km(n),r.setRawMode(!0)}catch{return new Map}try{Jm(n,Xh.map((t)=>`\x1B]${t};?\x1B\\`).join(""));let e="";return await new Promise((t)=>{let i=setTimeout(t,120);r.on("data",(o)=>{if(e+=o.toString(),Th(e).size>=Xh.length)clearTimeout(i),t()})}),Th(e)}finally{r.setRawMode(!1),r.destroy()}}function re(n){let r=n.replace("#","");return[r.slice(0,2),r.slice(2,4),r.slice(4,6)].map((e)=>Number.parseInt(e,16)).join(";")}function Yh(n,r){return`\x1B[48;2;${re(r)}m ${n} \x1B[0m`}function Bi(n,r){return`\x1B[48;2;${re(n)};38;2;${re(r)}m ● \x1B[0m`}function Ch(n){return`\x1B[38;2;${re(n)}m`}function xi(n,r){return`\x1B[48;2;${re(r)}m${n.map((e)=>`\x1B[38;2;${re(e)}m▄`).join("")} \x1B[0m`}function Ot(n,r){let e=r.toLowerCase();return[n.name,n.group,n.native??""].some((t)=>t.toLowerCase().includes(e))}function Bh(n,r,e){let t=e.trim(),i=[],o=new Set;for(let s of n){if(s.default||o.has(s.group))continue;o.add(s.group);let u=n.filter((f)=>!f.default&&f.group===s.group),c=t?u.filter((f)=>Ot(f,t)):u;if(t&&c.length===0)continue;let h=t.length>0||r.has(s.group);if(i.push({kind:"group",name:s.group,native:s.native,lead:u.find((f)=>f.lead)??s,expanded:h,count:c.length}),h)i.push(...c.map((f)=>({kind:"palette",entry:f})))}return i}function Pm(n,r){let e=r.trim(),t=new Set(n.filter((i)=>!i.default&&(e===""||Ot(i,e))).map((i)=>i.group));return Bh(n,new Set,"").filter((i)=>i.kind==="group"&&t.has(i.name))}function Um(n){let r=n.findIndex((e)=>e.kind==="palette");return r===-1?0:r}var Dn="\x1B[0m",ee="\x1B[2m",Qm="\x1B[1m",_h="\x1B[1;7m",Wm="\x1B[36m",Zm="\x1B[33m";function xh(n){return n==="decode"||n==="glitch"?n:"typewriter"}class Di extends sr{picked;scope;entries;named;series;seriesPad;expanded=new Set;rows=[];cursor=0;top=0;maxItems;color;lastInput="";lastFocused="";onFocus;example="";fx;fxStep=0;fxSeed=0;fxTimer;constructor(n){super({render:()=>this.draw(),input:n.input,output:n.output,validate:n.required?()=>this.picked.size===0?`pick at least one ${this.scope}`:void 0:void 0},!0);this.entries=n.entries,this.scope=n.scope??"palette",this.picked=new Set(n.installed??[]),this.named=n.entries.filter((e)=>!e.default),this.series=[...new Set(this.named.map((e)=>e.group))],this.seriesPad=Math.max(0,...this.series.map((e)=>e.length)),this.maxItems=n.maxItems??12,this.color=n.color??!0,this.fx=n.fx??"typewriter",this.onFocus=n.onFocus,this.rollExample();let r=setInterval(()=>{this.rollExample(),this.fxStep=8,this.output.emit("resize")},3000);r.unref?.(),this.once("finalize",()=>{clearInterval(r),clearTimeout(this.fxTimer)}),this.rebuild("first"),this.on("cursor",(e)=>{if(e==="up")this.move(-1);else if(e==="down")this.move(1);else if(e==="left")this.fold(!1);else if(e==="right")this.fold(!0)}),this.on("userInput",(e)=>{if(e!==this.lastInput)this.lastInput=e,this.rebuild("keep")}),this.on("key",(e,t)=>{if(t?.name==="space")this.pick(this.rows[this.cursor])})}_isActionKey(n){return n==="\t"||n===" "}members(n){let r=this.scope==="palette"?this.userInput.trim():"";return this.named.filter((e)=>e.group===n&&(r===""||Ot(e,r)))}everyone(n){return n.flatMap((r)=>r.kind==="group"?this.members(r.name):[])}pick(n){let r=n?.kind==="palette"?[n.entry.name]:n?.kind==="group"?this.members(n.name).map((t)=>t.name):n?.kind==="all"?this.everyone(this.rows).map((t)=>t.name):[];if(r.length===0)return;let e=r.some((t)=>!this.picked.has(t));for(let t of r)if(e)this.picked.add(t);else this.picked.delete(t)}pickedIn(n){return this.members(n).filter((r)=>this.picked.has(r.name)).length}pickedCount(){if(this.scope==="palette")return this.picked.size;return this.series.filter((n)=>this.members(n).every((r)=>this.picked.has(r.name))).length}rollExample(){let n=this.named[Math.floor(Math.random()*this.named.length)],r=this.series[Math.floor(Math.random()*this.series.length)];if(!n||!r){this.example="";return}let e=`${n.name} | ${r}`;this.example=e.length>30?`${e.slice(0,29)}…`:e,this.fxSeed=Math.floor(Math.random()*997)}animatedExample(){if(this.fxStep===0)return this.example;if(!this.fxTimer)this.fxTimer=setTimeout(()=>{this.fxTimer=void 0,this.fxStep-=1,this.output.emit("resize")},60),this.fxTimer.unref?.();let n=Math.floor(this.example.length*(8-this.fxStep)/8);if(this.fx==="typewriter")return`${this.example.slice(0,n)}▏`;let r=this.fx==="decode"?"abcdefghijklmnopqrstuvwxyz":"▓▒░#*+=<>?/-_",e=this.fx==="decode"?(t)=>!/[a-z0-9]/i.test(t):(t)=>t===" ";return[...this.example].map((t,i)=>i+(i*7+this.fxSeed)%3<n||e(t)?t:r[Math.floor(Math.random()*r.length)]??t).join("")}sync(){let n=this.rows[this.cursor],r=n?.kind==="palette"?n.entry:n?.kind==="group"&&this.scope==="series"?n.lead:void 0;if(r&&r.name!==this.lastFocused)this.lastFocused=r.name,this.onFocus?.(r)}rebuild(n){let r=this.rows[this.cursor],e=this.scope==="series"?Pm(this.entries,this.userInput):Bh(this.entries,this.expanded,this.userInput),t=e.length>0?Um(e)+1:0;if(this.rows=e.length>0?[{kind:"all",count:this.allCount(e)},...e]:[],n==="first")this.cursor=t;else if(n==="keep"){let i=r?.kind==="palette"?r.entry.name:"",o=i?this.rows.findIndex((s)=>s.kind==="palette"&&s.entry.name===i):-1;this.cursor=o===-1?t:o}else if(this.cursor>=this.rows.length)this.cursor=Math.max(0,this.rows.length-1);this.sync()}allCount(n){return this.scope==="series"?n.length:this.everyone(n).length}move(n){let r=this.cursor+n;if(r>=0&&r<this.rows.length)this.cursor=r;this.sync()}toggle(n){if(this.expanded.has(n))this.expanded.delete(n);else this.expanded.add(n);this.rebuild("clamp")}fold(n){if(this.userInput||this.scope==="series")return;let r=this.rows[this.cursor];if(r?.kind==="group"){if(n!==r.expanded)this.toggle(r.name)}else if(r?.kind==="palette"&&!n&&!r.entry.default){let e=r.entry.group;if(this.expanded.delete(e),this.rebuild("clamp"),this.cursor=this.rows.findIndex((t)=>t.kind==="group"&&t.name===e),this.cursor===-1)this.cursor=0;this.sync()}}renderRow(n,r){let e=r?"▶ ":" ";if(n.kind==="all"){let o=this.everyone(this.rows).every((u)=>this.picked.has(u.name))?"● ":"○ ",s=`(${n.count})`;return`${e}${o}select all ${this.color?`${ee}${s}${Dn}`:s}`}if(n.kind==="group"&&this.scope==="series"){let o=this.pickedIn(n.name)===n.count?"● ":"○ ",s=n.name.padEnd(this.seriesPad),u=`(${n.count})${n.native?` ${n.native}`:""}`;if(!this.color)return`${e}${o}${s} ${u}`;let c=n.lead;return`${e}${o}${s} ${Bi(c.background,c.cursor)}${xi(c.ansi.slice(1,7),c.background)} ${ee}${u}${Dn}`}if(n.kind==="group"){let o=n.expanded?"▾":"▸",s=this.rows[this.cursor],u=s?.kind==="palette"&&s.entry.group===n.name?s.entry:void 0,c=this.color?r?`${_h} ${n.name} ${Dn}`:u?`${_h}${Ch(u.cursor)} ${n.name} ${Dn}`:` ${Qm}${n.name}${Dn} `:r?`[${n.name}]`:` ${n.name}`,h=this.color?Yh("●",n.lead.selection):"",f=`${this.pickedIn(n.name)}/${n.count}`,l=this.color?` ${ee}(${f})${Dn}`:` (${f})`,g=n.native?this.color?` ${ee}${n.native}${Dn}`:` ${n.native}`:"";return`${o}${c}${h}${l}${g}`}let t=n.entry,i=this.picked.has(t.name)?"● ":"○ ";if(!this.color)return` ${e}${i}${t.name.padEnd(13)} ● · ${t.ansiSource}`;return` ${e}${i}${t.name.padEnd(13)} ${Bi(t.background,t.cursor)}${xi(t.ansi.slice(1,7),t.background)} ${ee}${t.ansiSource}${Dn}`}draw(){let n=(m)=>this.color?`${ee}${m}${Dn}`:m,r=(m)=>this.color?`${Wm}${m}${Dn}`:m,e=this.scope==="series"?"series":"catalog";if(this.state==="submit")return`${n("◇")} ${e} ${n(`· ${this.pickedCount()} picked`)}`;if(this.state==="cancel")return`${n(`◇ ${e} · cancelled`)}`;let t=this.userInput.trim(),i=this.scope==="series"?this.series.length:this.named.length,o=this.scope==="series"?this.rows.filter((m)=>m.kind==="group").length:t?this.named.filter((m)=>Ot(m,t)).length:i,s=`${r("◆")} ${e} ${n(`(${o}/${i} · ${this.pickedCount()} picked)`)}`,u=`${r("│")} ${this.userInput?`⌕ ${this.userInput}_`:n(`⌕ search…${this.example?` e.g. ${this.animatedExample()}`:""}`)}`;if(this.cursor<this.top)this.top=this.cursor;if(this.cursor>=this.top+this.maxItems)this.top=this.cursor-this.maxItems+1;this.top=Math.min(this.top,Math.max(0,this.rows.length-this.maxItems));let c=this.rows.slice(this.top,this.top+this.maxItems),h=c.length>0?c.map((m,b)=>`${r("│")} ${this.renderRow(m,this.top+b===this.cursor)}`):[`${r("│")} ${n(`no ${this.scope==="series"?"series":"palettes"} match '${this.userInput}'`)}`];while(h.length<this.maxItems)h.push(r("│"));let f=this.rows.length-this.top-c.length,l=f>0?`${r("│")} ${n(`↓ ${f} more`)}`:r("│"),g=this.scope==="series"?"":" · ←→ fold",d=this.scope==="series"?"continue":"install",w=this.state==="error"?`${r("└")} ${this.color?`${Zm}${this.error}${Dn}`:this.error}`:`${r("└")} ${n(`↑↓ move${g} · space pick · type to filter · enter ${d} · esc cancel`)}`;return[s,u,...h,l,w].join(`
163
+ `)}}function no(n,r,e,t){let i=Yr(),o=Boolean(Cr(e))!==Boolean(Cr(t)),s=o?Ke(t,i):t;if(Qe(n,r,s),Ue(n,s),o)Pe(s,i)}function ro(n){console.log(`
164
+ ${n} palettes installed — open a new tab, or reload your terminal config`)}function Dh(n){let r=xn(),e=Qn(r),t=lr(r),i=n.filter((u)=>t.palettes.includes(u)),o=n.filter((u)=>!t.palettes.includes(u));if(o.length===0){console.log(`already installed: ${i.join(", ")}`);return}let s={...t,palettes:[...t.palettes,...o]};no(r,e,t,s);for(let u of o)console.log(` + ${u}`);ro(s.palettes.length)}function nf(n){let r=xn(),e=Qn(r),t=lr(r),i=n.filter((s)=>t.palettes.includes(s));if(i.length===0){console.log(`not installed: ${n.join(", ")}`);return}let o={...t,palettes:t.palettes.filter((s)=>!i.includes(s))};no(r,e,t,o),yi(r,e,t.terminals,i);for(let s of i)console.log(` - ${s}`);ro(o.palettes.length)}function rf(n){let r=xn(),e=Qn(r),t=lr(r);if(!t.palettes.includes(n))throw Error(`${n} is not installed — \`ttheme add ${n}\` first`);let{keepTheme:i,...o}=t,s=Yr(),u=Ke({...o,startup:n},s);Qe(r,e,u),Ue(r,u);let c=Pe(u,s);console.log(Am(n,u.terminals,c&&s.running()).join(`
165
+ `))}function Am(n,r,e){let t=r.filter((o)=>o!=="iterm2"),i=t.length>0?[`default ${n} · ${t.join(", ")} open new tabs with it once their config reloads`]:[];if(r.includes("iterm2"))i.push(e?'iterm2 new tabs open with it once iTerm2 restarts — "ttheme · default" is now its default profile':'iterm2 new tabs open with it — "ttheme · default" is its default profile');return i.length>0?i:[`default ${n} · no terminal is wired to open with it — \`ttheme init\` wires one`]}function ef(n){let r=xn(),e=Qn(r),t=new Set(lr(r).palettes),i=Ar(e.palettes),o=Ie(n?uc(i,n):i),s=Math.max(...o.map((c)=>c.name.length),0);for(let c of o)console.log(` ${t.has(c.name)?"●":"○"} ${c.name.padEnd(s)} ${c.group}`);let u=n?`${o.length} of ${i.length}`:`${i.length}`;console.log(`
166
+ ${u} palettes — ${o.filter((c)=>t.has(c.name)).length} installed`)}async function tf(){let n=xn(),r=qm(gt(n))?Qn(n).palettes.length:0,e=await oc(tc);lt(n,e);let t=e.palettes.length-r;console.log(`catalog ${e.version} — ${e.palettes.length} palettes${t>0?` (+${t})`:""}`)}async function eo(n,r,e,t=!1){let i=process.env.TTHEME_SORT==="series"?n.palettes:Ie(n.palettes),o=process.stdout.isTTY===!0&&!process.env.NO_COLOR,s=o?await zh():new Map,u=new Di({entries:i,scope:e,installed:r,required:t,color:!process.env.NO_COLOR,fx:xh(process.env.TTHEME_FX),onFocus:o?(h)=>process.stdout.write(Ht(h)):void 0}),c=await u.prompt();if(process.stdout.write(Vh(s)),ne(c))return;return n.palettes.filter((h)=>u.picked.has(h.name)).map((h)=>h.name)}async function of(){let n=xn(),r=Qn(n),e=lr(n),t=await eo(r,e.palettes,"palette");if(!t){console.log("nothing changed");return}let i=e.palettes.filter((u)=>!t.includes(u)),o=t.filter((u)=>!e.palettes.includes(u));if(o.length===0&&i.length===0){console.log("nothing changed");return}let s={...e,palettes:t};no(n,r,e,s),yi(n,r,e.terminals,i);for(let u of o)console.log(` + ${u}`);for(let u of i)console.log(` - ${u}`);ro(s.palettes.length)}function cf(n,r,e){for(let t of zm(r))n.push({from:fn(r,t),to:fn(e,t)})}function lf(n){return JSON.parse(ie(fn(n,"dist","manifest.json"),"utf8"))}function hf(n,r){let e=fn(r.root,"dist"),t=fn(r.configHome,"ttheme"),i=[{from:fn(r.root,"bin","ttheme.js"),to:fn(t,"ttheme.js")},{from:fn(r.root,"shell","ttheme.zsh"),to:fn(t,"ttheme.zsh")},{from:fn(r.root,"shell","launch-tab.zsh"),to:fn(t,"launch-tab.zsh"),executable:!0},{from:fn(e,"ghostty","ttheme.conf"),to:fn(t,"ttheme.conf")}];cf(i,fn(r.root,"shell","adapters"),fn(t,"adapters"));let o=[{file:fn(r.zdotdir,".zshrc"),block:Uu(t)}],s=fn(t,"config.zsh"),u=Wu(qn(s)?ie(s,"utf8"):""),c={file:s,content:n.wear?ut(u,"TTHEME_TAB_PALETTE",n.wear==="rotate"?"seq":"off"):u},h=[];if(n.terminals.includes("ghostty"))cf(i,fn(r.root,"ghostty","shaders"),fn(r.configHome,"ghostty","shaders"));if(n.terminals.includes("alacritty")){let g=fn(r.configHome,"alacritty","alacritty.toml");if(qn(g)&&!ie(g,"utf8").includes("# ttheme begin"))h.push("alacritty.toml already exists — ttheme left it alone; add its themes/ import yourself")}if(n.terminals.includes("wezterm")){let g=Fi(r.configHome,r.home);if(qn(g)&&ct(ie(g,"utf8"),"")===void 0)h.push(`${g} has no \`return config\` line — ttheme left it alone; call \`dofile("${fn(t,"wezterm.lua")}")(config)\` from it yourself`)}let f=n.terminals.includes("windows-terminal");if(f&&!r.wtHome)h.push("windows terminal: %LOCALAPPDATA% was not found — drop the release fragment into its Fragments folder yourself");if(n.terminals.includes("warp"))h.push("warp: wears the default palette app-wide through its settings.toml — the shell layer stays off in it, since Warp paints no tab background of its own");let l={terminals:n.terminals,palettes:n.palettes,...n.wear==="keep"?{keepTheme:!0}:{},...f&&r.wtHome?{wtHome:r.wtHome}:{},...f&&r.wtProfile?{wtProfile:r.wtProfile}:{}};return{home:r.home,copies:i,edits:o,settings:c,catalog:lf(r.root),installed:l,notes:h}}function Cm(n){try{return lr(n).itermBase}catch{return}}function ff(n,r=Yr()){for(let o of n.copies)if(to(te(o.to),{recursive:!0}),sf(o.to,{force:!0}),sf(`${o.to}.zwc`,{force:!0}),Vm(o.from,o.to),o.executable)Tm(o.to,493);to(te(n.settings.file),{recursive:!0}),uf(n.settings.file,n.settings.content);let e=te(te(n.settings.file)),t=Cm(e),i=Ke(t?{...n.installed,itermBase:t}:n.installed,r);lt(e,n.catalog),Ue(e,i),Qe(e,n.catalog,i,n.home);for(let o of n.edits){to(te(o.file),{recursive:!0});let s=qn(o.file)?ie(o.file,"utf8"):"";uf(o.file,ot(s,o.block))}return Pe(i,r)}function io(n){if(ne(n))St("nothing changed"),process.exit(1);return n}function af(n){return it.filter((r)=>{if(r==="iterm2")return process.platform==="darwin";if(r==="windows-terminal")return n.wtHome!==void 0;return r!=="warp"||process.platform!=="win32"})}function _m(n,r){if(n==="iterm2")return qn(fn(r.home,"Library","Application Support","iTerm2"));if(n==="windows-terminal")return r.wtHome!==void 0;if(n==="warp")return qn(te(pt(r.home)));if(n==="wezterm")return qn(fn(r.configHome,"wezterm"))||qn(fn(r.home,".wezterm.lua"));return qn(fn(r.configHome,n))}function Bm(){if(process.platform==="win32")return process.env.LOCALAPPDATA;if(!process.env.WSL_DISTRO_NAME)return;let n=(r,e)=>Xm(r,e,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();try{return n("wslpath",["-u",n("cmd.exe",["/d","/c","echo %LOCALAPPDATA%"])])||void 0}catch{return}}async function xm(n,r,e){return io(await Qh({message:"wire which terminals?",options:af(e).map((t)=>({value:t,hint:t===n?"detected":void 0})),initialValues:r,required:!0}))}function Dm(n,r){if(n==="keep")return"leave the terminal colors as they are";return n==="rotate"?`paint every new tab with the next palette, this tab with ${r} now`:`paint every tab with ${r}, this one now`}async function n0(n){return io(await qh({message:"how should the terminal wear them?",options:[{value:"default",label:"default",hint:`every tab wears ${n}`},{value:"rotate",label:"rotate",hint:"every new tab wears the next palette"},{value:"keep",label:"keep",hint:"leave my terminal colors alone"}],initialValue:"default"}))}function gf(n){let r=[...n.copies.filter((e)=>!qn(e.to)).map((e)=>e.to),...qn(n.settings.file)?[]:[n.settings.file],...n.edits.filter((e)=>!ie(e.file,"utf8").includes("# ttheme begin")).map((e)=>e.file)];if(r.length>0)throw Error(`init left gaps:
147
167
  ${r.join(`
148
- `)}`)}function Th(n,r){return[...new Set(n.palettes.filter((t)=>r.includes(t.name)).map((t)=>t.group))]}function vm(n,r){let t=n.palettes.find((i)=>i.name===Ar(r)),e=process.stdout.isTTY===!0&&!process.env.NO_COLOR&&!process.env.TMUX;if(!t||!e)return!1;return process.stdout.write(ke(t)),!0}function Fm(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 Im(n,r,t,e,i){let s=Th(n.catalog,r.palettes);we([`${s.join(", ")} (${r.palettes.length})`,...Fm(t,Ar(n.installed),e)].join(`
149
- `),`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(...Nm(t==="default"?Ar(n.installed):void 0,i));we([...o,...n.notes].join(`
150
- `),"next"),Eh("done")}function Nm(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 ym(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 Ch(n={}){let r=wn(import.meta.dirname,"..");if(!dr(wn(r,"bin","ttheme.js")))throw Error("bin/ttheme.js is missing — run `mise run bin:build` first");if(!dr(wn(r,"dist"))){if(typeof Bun>"u")throw Error("this package is missing dist/ — reinstall @kecan0406/ttheme");await Dt()}let t=bm(),e=process.env.XDG_CONFIG_HOME??wn(t,".config"),i=process.env.ZDOTDIR??t,s={root:r,home:t,configHome:e,zdotdir:i},o=Iu(process.env),u=zh().filter((F)=>F===o||km(F,s));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 F={terminals:u,palettes:[]},H=Xh(F,s);Vh(H),Yh(H),ym(H,F);return}Mh("ttheme init");let h=await pm(o,u),f=await Yi(Ah(r),[],"series",!0);if(!f)be("nothing changed"),process.exit(1);let g=Ar({terminals:h,palettes:f}),l=await Em(g),a={terminals:h,palettes:f,wear:l},m=Xh(a,s);if(we([`install ${f.length} palettes — ${Th(m.catalog,f).join(", ")}`,`copy ${m.copies.length} files under ${e}`,`write ${m.settings.file}`,...m.edits.map((F)=>`edit ${F.file}`),Mm(l,g),...h.includes("iterm2")&&l!=="keep"?['make "ttheme · default" the iTerm2 default profile']:[]].join(`
152
- `),`wiring ${h.join(", ")}`),!zi(await kh({message:"apply these changes?"})))be("nothing changed"),process.exit(1);let b=Vr(),E=Vh(m,b);Yh(m),Im(m,a,l,l!=="keep"&&vm(m.catalog,m.installed),E&&b.running())}var Dh=[{name:"build",args:[],about:"emit dist/ for every terminal, plus the zsh palette table",flags:{only:{type:"string",multiple:!0,value:"<terminal>",choices:Ku,about:"rebuild just this terminal — repeat it for more"}},run:(n,{only:r})=>Dt({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})=>Ch({yes:r})},{name:"browse",args:[],about:"pick palettes from the catalog in a live picker",run:()=>Zh()},{name:"list",args:["[query]"],about:"show the catalog, marking what is installed",run:([n])=>Qh(n)},{name:"add",args:["<palette...>"],about:"install palettes from the catalog",run:(n)=>Jh(n)},{name:"remove",args:["<palette...>"],about:"uninstall palettes",run:(n)=>Kh(n)},{name:"default",args:["<palette>"],about:"make an installed palette the one new tabs open with",run:([n])=>Lh(n)},{name:"find",args:["<palette>"],about:"pick a booru background for a palette — preview opens this on tab",hidden:!0,run:([n])=>Zc(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])=>qc(n,r)},{name:"update",args:[],about:"refresh the catalog from the registry",run:()=>Ph()}];class Or extends Error{verb;constructor(n,r){super(n);this.verb=r}}function _h(n){let r=Dh.find((t)=>t.name===n);if(!r)throw new Or(n.startsWith("-")?`unknown option '${n}'`:`unknown command '${n}'`);return r}function Hm(n,r){let t={help:{type:"boolean",short:"h"}};for(let[e,{type:i,multiple:s}]of Object.entries(n.flags??{}))t[e]={type:i,multiple:s===!0};try{return Sm({args:r,options:t,allowPositionals:!0})}catch(e){let[i=""]=(e instanceof Error?e.message:String(e)).split(". ");throw new Or(`${i.charAt(0).toLowerCase()}${i.slice(1)}`,n)}}function jm(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:_h(t[0]),code:0};let e=_h(r),i=Hm(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 Or(`--${f} takes ${g.join(", ")} — not ${l}`,e);let s=i.positionals,o=e.args.filter((f)=>f.startsWith("<")).length,u=e.args.some((f)=>f.includes("..."))?Number.POSITIVE_INFINITY:e.args.length;if(s.length<o)throw new Or(`missing ${e.args[s.length]}`,e);if(s.length>u)throw new Or(`too many arguments: ${s.slice(u).join(" ")}`,e);let{help:c,...h}=i.values;return{kind:"run",verb:e,args:s,flags:h}}function Bh(n){let r=Object.entries(n.flags??{}).map(([t,{value:e}])=>`[--${t}${e?` ${e}`:""}]`);return[n.name,...r,...n.args].join(" ")}function xh(n){let r=Math.max(...n.map(([t])=>t.length));return n.map(([t,e])=>` ${t.padEnd(r)} ${e}`)}function Ti(n){if(n){let r=Object.entries(n.flags??{}).map(([t,{value:e,about:i}])=>[`--${t}${e?` ${e}`:""}`,i]);return[`Usage: ttheme ${Bh(n)}`,"",n.about,...r.length>0?["","Options:",...xh(r)]:[]].join(`
153
- `)}return["Usage: ttheme <command>","",Dn.description,"","Commands:",...xh(Dh.filter((r)=>!r.hidden).map((r)=>[Bh(r),r.about])),"","ttheme <command> --help describes one command · ttheme --version prints the version"].join(`
154
- `)}async function nf(n){try{let r=jm(n);if(r.kind==="version")return console.log(Dn.version),0;if(r.kind==="help"){if(r.code===0)console.log(Ti(r.verb));else console.error(Ti(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 Or)return console.error(`ttheme${r.verb?` ${r.verb.name}`:""}: ${r.message}
168
+ `)}`)}function df(n,r){return[...new Set(n.palettes.filter((e)=>r.includes(e.name)).map((e)=>e.group))]}function r0(n,r){let e=n.palettes.find((i)=>i.name===_r(r)),t=process.stdout.isTTY===!0&&!process.env.NO_COLOR&&!process.env.TMUX&&fi(process.env)!=="warp";if(!e||!t)return!1;return process.stdout.write(Ht(e)),!0}function e0(n,r,e){if(n==="keep")return["terminal colors left alone — paint a tab with `ttheme <palette>`"," `ttheme default <palette>` sets the terminal default"];return[`default ${r}${e?" — this tab wears it already":""}`,n==="rotate"?"new tabs rotate through the palettes — change with `ttheme config`":`new tabs all wear ${r} — change with \`ttheme config\``]}function t0(n,r,e,t,i){let o=df(n.catalog,r.palettes);Nt([`${o.join(", ")} (${r.palettes.length})`,...e0(e,_r(n.installed),t)].join(`
169
+ `),`installed ${r.palettes.length} palettes`);let s=["exec zsh the ttheme command in this tab"];if(r.terminals.includes("ghostty"))s.push("restart ghostty new tabs pick up its config");if(r.terminals.includes("kitty"))s.push("new kitty window picks up its config");if(r.terminals.includes("wezterm"))s.push("wezterm reloads its config by itself");if(r.terminals.includes("windows-terminal"))s.push("windows terminal reloads its settings by itself");if(r.terminals.includes("iterm2"))s.push(...i0(e==="default"?_r(n.installed):void 0,i));Nt([...s,...n.notes].join(`
170
+ `),"next"),Zh("done")}function i0(n,r){let e=['iterm2 profiles a "ttheme · <palette>" per palette in Settings › Profiles'];if(n)e.push(r?`restart iterm2 new tabs open on "ttheme · default", which wears ${n}`:`iterm2 default "ttheme · default" wears ${n} and follows \`ttheme default\``);return e}function o0(n,r){let e=[`placed ${n.copies.length} files`,`settings in ${n.settings.file} — edit later with \`ttheme config\``,...n.edits.map((t)=>`wired ${t.file}`)];if(r.terminals.includes("ghostty"))e.push("restart ghostty to pick up its config");if(r.terminals.includes("kitty"))e.push("open a new kitty window to pick up its config");if(r.terminals.includes("wezterm")||r.terminals.includes("windows-terminal"))e.push("wezterm and windows terminal reload their config by themselves");if(r.terminals.includes("iterm2"))e.push('iterm2 gets a "ttheme · <palette>" profile per palette under Settings › Profiles');e.push(...n.notes),e.push("no palettes yet — open a new shell (`exec zsh`), then `ttheme browse` picks them from the catalog"),console.log(e.join(`
171
+ `))}async function mf(n={}){let r=fn(import.meta.dirname,"..");if(!qn(fn(r,"bin","ttheme.js")))throw Error("bin/ttheme.js is missing — run `mise run bin:build` first");if(!qn(fn(r,"dist"))){if(typeof Bun>"u")throw Error("this package is missing dist/ — reinstall @kecan0406/ttheme");await ft()}let e=Ym(),t=process.env.XDG_CONFIG_HOME??fn(e,".config"),i=process.env.ZDOTDIR??e,o=Bm(),s=process.env.WT_PROFILE_ID,u={root:r,home:e,configHome:t,zdotdir:i,...o?{wtHome:o}:{},...s?{wtProfile:s}:{}},c=fi(process.env),h=af(u).filter((k)=>k===c||_m(k,u));if(!(!n.yes&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0)){if(h.length===0)throw Error("no supported terminal detected — run this inside ghostty, kitty, alacritty, wezterm, iterm2, windows terminal or warp");let k={terminals:h,palettes:[]},y=hf(k,u);ff(y),gf(y),o0(y,k);return}Wh("ttheme init");let l=await xm(c,h,u),g=await eo(lf(r),[],"series",!0);if(!g)St("nothing changed"),process.exit(1);let d=_r({terminals:l,palettes:g}),w=await n0(d),m={terminals:l,palettes:g,wear:w},b=hf(m,u);if(Nt([`install ${g.length} palettes — ${df(b.catalog,g).join(", ")}`,`copy ${b.copies.length} files under ${t}`,`write ${b.settings.file}`,...b.edits.map((k)=>`edit ${k.file}`),Dm(w,d),...l.includes("iterm2")&&w!=="keep"?['make "ttheme · default" the iTerm2 default profile']:[]].join(`
172
+ `),`wiring ${l.join(", ")}`),!io(await Uh({message:"apply these changes?"})))St("nothing changed"),process.exit(1);let F=Yr(),S=ff(b,F);gf(b),t0(b,m,w,w!=="keep"&&r0(b.catalog,b.installed),S&&F.running())}var bf=[{name:"build",args:[],about:"emit dist/ for every terminal, plus the zsh palette table",flags:{only:{type:"string",multiple:!0,value:"<terminal>",choices:ec,about:"rebuild just this terminal — repeat it for more"}},run:(n,{only:r})=>ft({only:r})},{name:"init",args:[],about:"install the palettes and wire your terminal configs",flags:{yes:{type:"boolean",about:"accept every default without prompting"}},run:(n,{yes:r})=>mf({yes:r})},{name:"browse",args:[],about:"pick palettes from the catalog in a live picker",run:()=>of()},{name:"list",args:["[query]"],about:"show the catalog, marking what is installed",run:([n])=>ef(n)},{name:"add",args:["<palette...>"],about:"install palettes from the catalog",run:(n)=>Dh(n)},{name:"remove",args:["<palette...>"],about:"uninstall palettes",run:(n)=>nf(n)},{name:"default",args:["<palette>"],about:"make an installed palette the one new tabs open with",run:([n])=>rf(n)},{name:"find",args:["<palette>"],about:"pick a booru background for a palette — preview opens this on tab",hidden:!0,run:([n])=>ih(n)},{name:"image",args:["<palette>","<action>"],about:"switch a palette between its saved backgrounds, remove the one shown, or pass on tuning — preview calls this",hidden:!0,run:([n,r])=>oh(n,r)},{name:"update",args:[],about:"refresh the catalog from the registry",run:()=>tf()}];class Lr extends Error{verb;constructor(n,r){super(n);this.verb=r}}function $f(n){let r=bf.find((e)=>e.name===n);if(!r)throw new Lr(n.startsWith("-")?`unknown option '${n}'`:`unknown command '${n}'`);return r}function u0(n,r){let e={help:{type:"boolean",short:"h"}};for(let[t,{type:i,multiple:o}]of Object.entries(n.flags??{}))e[t]={type:i,multiple:o===!0};try{return s0({args:r,options:e,allowPositionals:!0})}catch(t){let[i=""]=(t instanceof Error?t.message:String(t)).split(". ");throw new Lr(`${i.charAt(0).toLowerCase()}${i.slice(1)}`,n)}}function c0(n){let[r,...e]=n;if(r===void 0)return{kind:"help",code:1};if(r==="-h"||r==="--help")return{kind:"help",code:0};if(r==="-V"||r==="--version")return{kind:"version"};if(r==="help")return e[0]===void 0?{kind:"help",code:0}:{kind:"help",verb:$f(e[0]),code:0};let t=$f(r),i=u0(t,e);if(i.values.help)return{kind:"help",verb:t,code:0};for(let[f,{choices:l}]of Object.entries(t.flags??{}))for(let g of[i.values[f]??[]].flat())if(l&&!l.includes(String(g)))throw new Lr(`--${f} takes ${l.join(", ")} — not ${g}`,t);let o=i.positionals,s=t.args.filter((f)=>f.startsWith("<")).length,u=t.args.some((f)=>f.includes("..."))?Number.POSITIVE_INFINITY:t.args.length;if(o.length<s)throw new Lr(`missing ${t.args[o.length]}`,t);if(o.length>u)throw new Lr(`too many arguments: ${o.slice(u).join(" ")}`,t);let{help:c,...h}=i.values;return{kind:"run",verb:t,args:o,flags:h}}function wf(n){let r=Object.entries(n.flags??{}).map(([e,{value:t}])=>`[--${e}${t?` ${t}`:""}]`);return[n.name,...r,...n.args].join(" ")}function pf(n){let r=Math.max(...n.map(([e])=>e.length));return n.map(([e,t])=>` ${e.padEnd(r)} ${t}`)}function oo(n){if(n){let r=Object.entries(n.flags??{}).map(([e,{value:t,about:i}])=>[`--${e}${t?` ${t}`:""}`,i]);return[`Usage: ttheme ${wf(n)}`,"",n.about,...r.length>0?["","Options:",...pf(r)]:[]].join(`
173
+ `)}return["Usage: ttheme <command>","",rr.description,"","Commands:",...pf(bf.filter((r)=>!r.hidden).map((r)=>[wf(r),r.about])),"","ttheme <command> --help describes one command · ttheme --version prints the version"].join(`
174
+ `)}async function kf(n){try{let r=c0(n);if(r.kind==="version")return console.log(rr.version),0;if(r.kind==="help"){if(r.code===0)console.log(oo(r.verb));else console.error(oo(r.verb));return r.code}let e=await r.verb.run(r.args,r.flags);return typeof e==="number"?e:0}catch(r){if(r instanceof Lr)return console.error(`ttheme${r.verb?` ${r.verb.name}`:""}: ${r.message}
155
175
 
156
- ${Ti(r.verb)}`),1;return console.error(`
157
- ${r instanceof Error?r.message:String(r)}`),1}}if(Gm)process.exitCode=await nf(process.argv.slice(2));
176
+ ${oo(r.verb)}`),1;return console.error(`
177
+ ${r instanceof Error?r.message:String(r)}`),1}}if(h0)process.exitCode=await kf(process.argv.slice(2));