@kecan0406/ttheme 1.0.30 → 1.0.32
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/README.md +129 -18
- package/bin/ttheme.js +191 -117
- package/dist/manifest.json +1 -1
- package/package.json +1 -1
- package/shell/adapters/_bg.zsh +4 -1
- package/shell/adapters/_osc.zsh +41 -7
- package/shell/adapters/alacritty.zsh +1 -0
- package/shell/adapters/iterm2.zsh +16 -3
- package/shell/adapters/kitty.zsh +50 -27
- package/shell/adapters/terminal-app.zsh +35 -0
- package/shell/adapters/wezterm.zsh +19 -0
- package/shell/adapters/windows-terminal.zsh +3 -0
- package/shell/ttheme.zsh +56 -13
package/bin/ttheme.js
CHANGED
|
@@ -1,41 +1,114 @@
|
|
|
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
|
|
4
|
-
`),
|
|
5
|
-
`);return[{path:`alacritty/themes/${
|
|
6
|
-
`);return[{path:`ghostty/themes/${
|
|
7
|
-
`)}]}};function
|
|
8
|
-
`}function
|
|
9
|
-
`)}var
|
|
10
|
-
`);return[{path:`iterm2/${
|
|
11
|
-
`),
|
|
12
|
-
`);return[{path:`kitty/themes/${
|
|
13
|
-
`)}function
|
|
14
|
-
`)
|
|
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
|
|
16
|
-
${r}
|
|
2
|
+
import{createRequire as pa}from"node:module";var ha=Object.create;var{getPrototypeOf:fa,defineProperty:Xo,getOwnPropertyNames:aa}=Object;var la=Object.prototype.hasOwnProperty;function ga(t){return this[t]}var da,ma,er=(t,n,e)=>{var r=t!=null&&typeof t==="object";if(r){var i=n?da??=new WeakMap:ma??=new WeakMap,o=i.get(t);if(o)return o}e=t!=null?ha(fa(t)):{};let s=n||!t||!t.__esModule?Xo(e,"default",{value:t,enumerable:!0}):e;for(let c of aa(t))if(!la.call(s,c))Xo(s,c,{get:ga.bind(t,c),enumerable:!0});if(r)i.set(t,s);return s};var bt=(t,n)=>()=>(n||t((n={exports:{}}).exports,n),n.exports);var Rt=pa(import.meta.url);var ss=bt((L0,sr)=>{var os=os||function(t){return Buffer.from(t).toString("base64")};function va(t){var n=this,e=Math.round,r=Math.floor,i=Array(64),o=Array(64),s=Array(64),c=Array(64),u,h,f,a,l=Array(65535),g=Array(65535),d=Array(64),m=Array(64),E=[],y=0,N=7,k=Array(64),S=Array(64),$=Array(64),H=Array(256),b=Array(2048),j,O=[0,1,5,6,14,15,27,28,2,4,7,13,16,26,29,42,3,8,12,17,25,30,41,43,9,11,18,24,31,40,44,53,10,19,23,32,39,45,52,54,20,22,33,38,46,51,55,60,21,34,37,47,50,56,59,61,35,36,48,49,57,58,62,63],L=[0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0],P=[0,1,2,3,4,5,6,7,8,9,10,11],C=[0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,125],A=[1,2,3,0,4,17,5,18,33,49,65,6,19,81,97,7,34,113,20,50,129,145,161,8,35,66,177,193,21,82,209,240,36,51,98,114,130,9,10,22,23,24,25,26,37,38,39,40,41,42,52,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,225,226,227,228,229,230,231,232,233,234,241,242,243,244,245,246,247,248,249,250],Ft=[0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0],U=[0,1,2,3,4,5,6,7,8,9,10,11],V=[0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,119],Et=[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 mt(p){var G=[16,11,10,16,24,40,51,61,12,12,14,19,26,58,60,55,14,13,16,24,40,57,69,56,14,17,22,29,51,87,80,62,18,22,37,56,68,109,103,77,24,35,55,64,81,104,113,92,49,64,78,87,103,121,120,101,72,92,95,98,112,100,103,99];for(var T=0;T<64;T++){var J=r((G[T]*p+50)/100);if(J<1)J=1;else if(J>255)J=255;i[O[T]]=J}var Z=[17,18,24,47,99,99,99,99,18,21,26,66,99,99,99,99,24,26,56,99,99,99,99,99,47,66,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99];for(var X=0;X<64;X++){var rt=r((Z[X]*p+50)/100);if(rt<1)rt=1;else if(rt>255)rt=255;o[O[X]]=rt}var it=[1,1.387039845,1.306562965,1.175875602,1,0.785694958,0.5411961,0.275899379],St=0;for(var $t=0;$t<8;$t++)for(var v=0;v<8;v++)s[St]=1/(i[O[St]]*it[$t]*it[v]*8),c[St]=1/(o[O[St]]*it[$t]*it[v]*8),St++}function B(p,G){var T=0,J=0,Z=[];for(var X=1;X<=16;X++){for(var rt=1;rt<=p[X];rt++)Z[G[J]]=[],Z[G[J]][0]=T,Z[G[J]][1]=X,J++,T++;T*=2}return Z}function It(){u=B(L,P),h=B(Ft,U),f=B(C,A),a=B(V,Et)}function ot(){var p=1,G=2;for(var T=1;T<=15;T++){for(var J=p;J<G;J++)g[32767+J]=T,l[32767+J]=[],l[32767+J][1]=T,l[32767+J][0]=J;for(var Z=-(G-1);Z<=-p;Z++)g[32767+Z]=T,l[32767+Z]=[],l[32767+Z][1]=T,l[32767+Z][0]=G-1+Z;p<<=1,G<<=1}}function tt(){for(var p=0;p<256;p++)b[p]=19595*p,b[p+256>>0]=38470*p,b[p+512>>0]=7471*p+32768,b[p+768>>0]=-11059*p,b[p+1024>>0]=-21709*p,b[p+1280>>0]=32768*p+8421375,b[p+1536>>0]=-27439*p,b[p+1792>>0]=-5329*p}function x(p){var G=p[0],T=p[1]-1;while(T>=0){if(G&1<<T)y|=1<<N;if(T--,N--,N<0){if(y==255)w(255),w(0);else w(y);N=7,y=0}}}function w(p){E.push(p)}function K(p){w(p>>8&255),w(p&255)}function ft(p,G){var T,J,Z,X,rt,it,St,$t,v=0,R,q=8,Mt=64;for(R=0;R<q;++R){T=p[v],J=p[v+1],Z=p[v+2],X=p[v+3],rt=p[v+4],it=p[v+5],St=p[v+6],$t=p[v+7];var _=T+$t,D=T-$t,lt=J+St,W=J-St,st=Z+it,Ht=Z-it,kt=X+rt,Zt=X-rt,tn=_+kt,On=_-kt,Tn=lt+st,Wn=lt-st;p[v]=tn+Tn,p[v+4]=tn-Tn;var ue=(Wn+On)*0.707106781;p[v+2]=On+ue,p[v+6]=On-ue,tn=Zt+Ht,Tn=Ht+W,Wn=W+D;var he=(tn-Wn)*0.382683433,Be=0.5411961*tn+he,fe=1.306562965*Wn+he,ae=Tn*0.707106781,le=D+ae,ge=D-ae;p[v+5]=ge+Be,p[v+3]=ge-Be,p[v+1]=le+fe,p[v+7]=le-fe,v+=8}v=0;for(R=0;R<q;++R){T=p[v],J=p[v+8],Z=p[v+16],X=p[v+24],rt=p[v+32],it=p[v+40],St=p[v+48],$t=p[v+56];var jo=T+$t,Br=T-$t,Po=J+St,Go=J-St,Lo=Z+it,Ko=Z-it,Jo=X+rt,ua=X-rt,de=jo+Jo,Dr=jo-Jo,De=Po+Lo,tr=Po-Lo;p[v]=de+De,p[v+32]=de-De;var Ao=(tr+Dr)*0.707106781;p[v+16]=Dr+Ao,p[v+48]=Dr-Ao,de=ua+Ko,De=Ko+Go,tr=Go+Br;var Uo=(de-tr)*0.382683433,To=0.5411961*de+Uo,Wo=1.306562965*tr+Uo,Qo=De*0.707106781,qo=Br+Qo,Zo=Br-Qo;p[v+40]=Zo+To,p[v+24]=Zo-To,p[v+8]=qo+Wo,p[v+56]=qo-Wo,v++}var nr;for(R=0;R<Mt;++R)nr=p[R]*G[R],d[R]=nr>0?nr+0.5|0:nr-0.5|0;return d}function at(){K(65504),K(16),w(74),w(70),w(73),w(70),w(0),w(1),w(1),w(0),K(1),K(1),w(0),w(0)}function nt(p){if(!p)return;if(K(65505),p[0]===69&&p[1]===120&&p[2]===105&&p[3]===102)K(p.length+2);else K(p.length+5+2),w(69),w(120),w(105),w(102),w(0);for(var G=0;G<p.length;G++)w(p[G])}function et(p,G){K(65472),K(17),w(8),K(G),K(p),w(3),w(1),w(17),w(0),w(2),w(17),w(1),w(3),w(17),w(1)}function Y(){K(65499),K(132),w(0);for(var p=0;p<64;p++)w(i[p]);w(1);for(var G=0;G<64;G++)w(o[G])}function I(){K(65476),K(418),w(0);for(var p=0;p<16;p++)w(L[p+1]);for(var G=0;G<=11;G++)w(P[G]);w(16);for(var T=0;T<16;T++)w(C[T+1]);for(var J=0;J<=161;J++)w(A[J]);w(1);for(var Z=0;Z<16;Z++)w(Ft[Z+1]);for(var X=0;X<=11;X++)w(U[X]);w(17);for(var rt=0;rt<16;rt++)w(V[rt+1]);for(var it=0;it<=161;it++)w(Et[it])}function F(p){if(typeof p>"u"||p.constructor!==Array)return;p.forEach((G)=>{if(typeof G!=="string")return;K(65534);var T=G.length;K(T+2);var J;for(J=0;J<T;J++)w(G.charCodeAt(J))})}function wt(){K(65498),K(12),w(3),w(1),w(0),w(2),w(17),w(3),w(17),w(0),w(63),w(0)}function Q(p,G,T,J,Z){var X=Z[0],rt=Z[240],it,St=16,$t=63,v=64,R=ft(p,G);for(var q=0;q<v;++q)m[O[q]]=R[q];var Mt=m[0]-T;if(T=m[0],Mt==0)x(J[0]);else it=32767+Mt,x(J[g[it]]),x(l[it]);var _=63;for(;_>0&&m[_]==0;_--);if(_==0)return x(X),T;var D=1,lt;while(D<=_){var W=D;for(;m[D]==0&&D<=_;++D);var st=D-W;if(st>=St){lt=st>>4;for(var Ht=1;Ht<=lt;++Ht)x(rt);st=st&15}it=32767+m[D],x(Z[(st<<4)+g[it]]),x(l[it]),D++}if(_!=$t)x(X);return T}function z(){var p=String.fromCharCode;for(var G=0;G<256;G++)H[G]=p(G)}this.encode=function(p,G){var T=new Date().getTime();if(G)qt(G);E=[],y=0,N=7,K(65496),at(),F(p.comments),nt(p.exifBuffer),Y(),et(p.width,p.height),I(),wt();var J=0,Z=0,X=0;y=0,N=7,this.encode.displayName="_encode_";var{data:rt,width:it,height:St}=p,$t=it*4,v=it*3,R,q=0,Mt,_,D,lt,W,st,Ht,kt;while(q<St){R=0;while(R<$t){lt=$t*q+R,W=lt,st=-1,Ht=0;for(kt=0;kt<64;kt++){if(Ht=kt>>3,st=(kt&7)*4,W=lt+Ht*$t+st,q+Ht>=St)W-=$t*(q+1+Ht-St);if(R+st>=$t)W-=R+st-$t+4;Mt=rt[W++],_=rt[W++],D=rt[W++],k[kt]=(b[Mt]+b[_+256>>0]+b[D+512>>0]>>16)-128,S[kt]=(b[Mt+768>>0]+b[_+1024>>0]+b[D+1280>>0]>>16)-128,$[kt]=(b[Mt+1280>>0]+b[_+1536>>0]+b[D+1792>>0]>>16)-128}J=Q(k,s,J,u,f),Z=Q(S,c,Z,h,a),X=Q($,c,X,h,a),R+=32}q+=8}if(N>=0){var Zt=[];Zt[1]=N+1,Zt[0]=(1<<N+1)-1,x(Zt)}if(K(65497),typeof sr>"u")return new Uint8Array(E);return Buffer.from(E);var tn,On};function qt(p){if(p<=0)p=1;if(p>100)p=100;if(j==p)return;var G=0;if(p<50)G=Math.floor(5000/p);else G=Math.floor(200-p*2);mt(G),j=p}function zt(){var p=new Date().getTime();if(!t)t=50;z(),It(),ot(),tt(),qt(t);var G=new Date().getTime()-p}zt()}if(typeof sr<"u")sr.exports=is;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].encode=is;function is(t,n){if(typeof n>"u")n=50;var e=new va(n),r=e.encode(t,n);return{data:r,width:t.width,height:t.height}}});var us=bt((K0,ii)=>{var ri=function(){var n=new Int32Array([0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5,12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28,35,42,49,56,57,50,43,36,29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54,47,55,62,63]),e=4017,r=799,i=3406,o=2276,s=1567,c=3784,u=5793,h=2896;function f(){}function a(N,k){var S=0,$=[],H,b,j=16;while(j>0&&!N[j-1])j--;$.push({children:[],index:0});var O=$[0],L;for(H=0;H<j;H++){for(b=0;b<N[H];b++){O=$.pop(),O.children[O.index]=k[S];while(O.index>0){if($.length===0)throw Error("Could not recreate Huffman Table");O=$.pop()}O.index++,$.push(O);while($.length<=H)$.push(L={children:[],index:0}),O.children[O.index]=L.children,O=L;S++}if(H+1<j)$.push(L={children:[],index:0}),O.children[O.index]=L.children,O=L}return $[0].children}function l(N,k,S,$,H,b,j,O,L,P){var{precision:C,samplesPerLine:A,scanLines:Ft,mcusPerLine:U,progressive:V,maxH:Et,maxV:mt}=S,B=k,It=0,ot=0;function tt(){if(ot>0)return ot--,It>>ot&1;if(It=N[k++],It==255){var v=N[k++];if(v)throw Error("unexpected marker: "+(It<<8|v).toString(16))}return ot=7,It>>>7}function x(v){var R=v,q;while((q=tt())!==null){if(R=R[q],typeof R==="number")return R;if(typeof R!=="object")throw Error("invalid huffman sequence")}return null}function w(v){var R=0;while(v>0){var q=tt();if(q===null)return;R=R<<1|q,v--}return R}function K(v){var R=w(v);if(R>=1<<v-1)return R;return R+(-1<<v)+1}function ft(v,R){var q=x(v.huffmanTableDC),Mt=q===0?0:K(q);R[0]=v.pred+=Mt;var _=1;while(_<64){var D=x(v.huffmanTableAC),lt=D&15,W=D>>4;if(lt===0){if(W<15)break;_+=16;continue}_+=W;var st=n[_];R[st]=K(lt),_++}}function at(v,R){var q=x(v.huffmanTableDC),Mt=q===0?0:K(q)<<L;R[0]=v.pred+=Mt}function nt(v,R){R[0]|=tt()<<L}var et=0;function Y(v,R){if(et>0){et--;return}var q=b,Mt=j;while(q<=Mt){var _=x(v.huffmanTableAC),D=_&15,lt=_>>4;if(D===0){if(lt<15){et=w(lt)+(1<<lt)-1;break}q+=16;continue}q+=lt;var W=n[q];R[W]=K(D)*(1<<L),q++}}var I=0,F;function wt(v,R){var q=b,Mt=j,_=0;while(q<=Mt){var D=n[q],lt=R[D]<0?-1:1;switch(I){case 0:var W=x(v.huffmanTableAC),st=W&15,_=W>>4;if(st===0)if(_<15)et=w(_)+(1<<_),I=4;else _=16,I=1;else{if(st!==1)throw Error("invalid ACn encoding");F=K(st),I=_?2:3}continue;case 1:case 2:if(R[D])R[D]+=(tt()<<L)*lt;else if(_--,_===0)I=I==2?3:0;break;case 3:if(R[D])R[D]+=(tt()<<L)*lt;else R[D]=F<<L,I=0;break;case 4:if(R[D])R[D]+=(tt()<<L)*lt;break}q++}if(I===4){if(et--,et===0)I=0}}function Q(v,R,q,Mt,_){var D=q/U|0,lt=q%U,W=D*v.v+Mt,st=lt*v.h+_;if(v.blocks[W]===void 0&&P.tolerantDecoding)return;R(v,v.blocks[W][st])}function z(v,R,q){var Mt=q/v.blocksPerLine|0,_=q%v.blocksPerLine;if(v.blocks[Mt]===void 0&&P.tolerantDecoding)return;R(v,v.blocks[Mt][_])}var qt=$.length,zt,p,G,T,J,Z;if(V)if(b===0)Z=O===0?at:nt;else Z=O===0?Y:wt;else Z=ft;var X=0,rt,it;if(qt==1)it=$[0].blocksPerLine*$[0].blocksPerColumn;else it=U*S.mcusPerColumn;if(!H)H=it;var St,$t;while(X<it){for(p=0;p<qt;p++)$[p].pred=0;if(et=0,qt==1){zt=$[0];for(J=0;J<H;J++)z(zt,Z,X),X++}else for(J=0;J<H;J++){for(p=0;p<qt;p++){zt=$[p],St=zt.h,$t=zt.v;for(G=0;G<$t;G++)for(T=0;T<St;T++)Q(zt,Z,X,G,T)}if(X++,X===it)break}if(X===it)do{if(N[k]===255){if(N[k+1]!==0)break}k+=1}while(k<N.length-2);if(ot=0,rt=N[k]<<8|N[k+1],rt<65280)throw Error("marker was not found");if(rt>=65488&&rt<=65495)k+=2;else break}return k-B}function g(N,k){var S=[],$=k.blocksPerLine,H=k.blocksPerColumn,b=$<<3,j=new Int32Array(64),O=new Uint8Array(64);function L(B,It,ot){var tt=k.quantizationTable,x,w,K,ft,at,nt,et,Y,I,F=ot,wt;for(wt=0;wt<64;wt++)F[wt]=B[wt]*tt[wt];for(wt=0;wt<8;++wt){var Q=8*wt;if(F[1+Q]==0&&F[2+Q]==0&&F[3+Q]==0&&F[4+Q]==0&&F[5+Q]==0&&F[6+Q]==0&&F[7+Q]==0){I=u*F[0+Q]+512>>10,F[0+Q]=I,F[1+Q]=I,F[2+Q]=I,F[3+Q]=I,F[4+Q]=I,F[5+Q]=I,F[6+Q]=I,F[7+Q]=I;continue}x=u*F[0+Q]+128>>8,w=u*F[4+Q]+128>>8,K=F[2+Q],ft=F[6+Q],at=h*(F[1+Q]-F[7+Q])+128>>8,Y=h*(F[1+Q]+F[7+Q])+128>>8,nt=F[3+Q]<<4,et=F[5+Q]<<4,I=x-w+1>>1,x=x+w+1>>1,w=I,I=K*c+ft*s+128>>8,K=K*s-ft*c+128>>8,ft=I,I=at-et+1>>1,at=at+et+1>>1,et=I,I=Y+nt+1>>1,nt=Y-nt+1>>1,Y=I,I=x-ft+1>>1,x=x+ft+1>>1,ft=I,I=w-K+1>>1,w=w+K+1>>1,K=I,I=at*o+Y*i+2048>>12,at=at*i-Y*o+2048>>12,Y=I,I=nt*r+et*e+2048>>12,nt=nt*e-et*r+2048>>12,et=I,F[0+Q]=x+Y,F[7+Q]=x-Y,F[1+Q]=w+et,F[6+Q]=w-et,F[2+Q]=K+nt,F[5+Q]=K-nt,F[3+Q]=ft+at,F[4+Q]=ft-at}for(wt=0;wt<8;++wt){var z=wt;if(F[8+z]==0&&F[16+z]==0&&F[24+z]==0&&F[32+z]==0&&F[40+z]==0&&F[48+z]==0&&F[56+z]==0){I=u*ot[wt+0]+8192>>14,F[0+z]=I,F[8+z]=I,F[16+z]=I,F[24+z]=I,F[32+z]=I,F[40+z]=I,F[48+z]=I,F[56+z]=I;continue}x=u*F[0+z]+2048>>12,w=u*F[32+z]+2048>>12,K=F[16+z],ft=F[48+z],at=h*(F[8+z]-F[56+z])+2048>>12,Y=h*(F[8+z]+F[56+z])+2048>>12,nt=F[24+z],et=F[40+z],I=x-w+1>>1,x=x+w+1>>1,w=I,I=K*c+ft*s+2048>>12,K=K*s-ft*c+2048>>12,ft=I,I=at-et+1>>1,at=at+et+1>>1,et=I,I=Y+nt+1>>1,nt=Y-nt+1>>1,Y=I,I=x-ft+1>>1,x=x+ft+1>>1,ft=I,I=w-K+1>>1,w=w+K+1>>1,K=I,I=at*o+Y*i+2048>>12,at=at*i-Y*o+2048>>12,Y=I,I=nt*r+et*e+2048>>12,nt=nt*e-et*r+2048>>12,et=I,F[0+z]=x+Y,F[56+z]=x-Y,F[8+z]=w+et,F[48+z]=w-et,F[16+z]=K+nt,F[40+z]=K-nt,F[24+z]=ft+at,F[32+z]=ft-at}for(wt=0;wt<64;++wt){var qt=128+(F[wt]+8>>4);It[wt]=qt<0?0:qt>255?255:qt}}y(b*H*8);var P,C;for(var A=0;A<H;A++){var Ft=A<<3;for(P=0;P<8;P++)S.push(new Uint8Array(b));for(var U=0;U<$;U++){L(k.blocks[A][U],O,j);var V=0,Et=U<<3;for(C=0;C<8;C++){var mt=S[Ft+C];for(P=0;P<8;P++)mt[Et+P]=O[V++]}}}return S}function d(N){return N<0?0:N>255?255:N}f.prototype={load:function(k){var S=new XMLHttpRequest;S.open("GET",k,!0),S.responseType="arraybuffer",S.onload=function(){var $=new Uint8Array(S.response||S.mozResponseArrayBuffer);if(this.parse($),this.onload)this.onload()}.bind(this),S.send(null)},parse:function(k){var S=this.opts.maxResolutionInMP*1000*1000,$=0,H=k.length;function b(){var W=k[$]<<8|k[$+1];return $+=2,W}function j(){var W=b(),st=k.subarray($,$+W-2);return $+=st.length,st}function O(W){var st=1,Ht=1,kt,Zt;for(Zt in W.components)if(W.components.hasOwnProperty(Zt)){if(kt=W.components[Zt],st<kt.h)st=kt.h;if(Ht<kt.v)Ht=kt.v}var tn=Math.ceil(W.samplesPerLine/8/st),On=Math.ceil(W.scanLines/8/Ht);for(Zt in W.components)if(W.components.hasOwnProperty(Zt)){kt=W.components[Zt];var Tn=Math.ceil(Math.ceil(W.samplesPerLine/8)*kt.h/st),Wn=Math.ceil(Math.ceil(W.scanLines/8)*kt.v/Ht),ue=tn*kt.h,he=On*kt.v,Be=he*ue,fe=[];y(Be*256);for(var ae=0;ae<he;ae++){var le=[];for(var ge=0;ge<ue;ge++)le.push(new Int32Array(64));fe.push(le)}kt.blocksPerLine=Tn,kt.blocksPerColumn=Wn,kt.blocks=fe}W.maxH=st,W.maxV=Ht,W.mcusPerLine=tn,W.mcusPerColumn=On}var L=null,P=null,C=null,A,Ft,U=[],V=[],Et=[],mt=[],B=b(),It=-1;if(this.comments=[],B!=65496)throw Error("SOI not found");B=b();while(B!=65497){var ot,tt,x;switch(B){case 65280:break;case 65504:case 65505:case 65506:case 65507:case 65508:case 65509:case 65510:case 65511:case 65512:case 65513:case 65514:case 65515:case 65516:case 65517:case 65518:case 65519:case 65534:var w=j();if(B===65534){var K=String.fromCharCode.apply(null,w);this.comments.push(K)}if(B===65504){if(w[0]===74&&w[1]===70&&w[2]===73&&w[3]===70&&w[4]===0)L={version:{major:w[5],minor:w[6]},densityUnits:w[7],xDensity:w[8]<<8|w[9],yDensity:w[10]<<8|w[11],thumbWidth:w[12],thumbHeight:w[13],thumbData:w.subarray(14,14+3*w[12]*w[13])}}if(B===65505){if(w[0]===69&&w[1]===120&&w[2]===105&&w[3]===102&&w[4]===0)this.exifBuffer=w.subarray(5,w.length)}if(B===65518){if(w[0]===65&&w[1]===100&&w[2]===111&&w[3]===98&&w[4]===101&&w[5]===0)P={version:w[6],flags0:w[7]<<8|w[8],flags1:w[9]<<8|w[10],transformCode:w[11]}}break;case 65499:var ft=b(),at=ft+$-2;while($<at){var nt=k[$++];y(256);var et=new Int32Array(64);if(nt>>4===0)for(tt=0;tt<64;tt++){var Y=n[tt];et[Y]=k[$++]}else if(nt>>4===1)for(tt=0;tt<64;tt++){var Y=n[tt];et[Y]=b()}else throw Error("DQT: invalid table spec");U[nt&15]=et}break;case 65472:case 65473:case 65474:b(),A={},A.extended=B===65473,A.progressive=B===65474,A.precision=k[$++],A.scanLines=b(),A.samplesPerLine=b(),A.components={},A.componentsOrder=[];var I=A.scanLines*A.samplesPerLine;if(I>S){var F=Math.ceil((I-S)/1e6);throw Error(`maxResolutionInMP limit exceeded by ${F}MP`)}var wt=k[$++],Q,z=0,qt=0;for(ot=0;ot<wt;ot++){Q=k[$];var zt=k[$+1]>>4,p=k[$+1]&15,G=k[$+2];if(zt<=0||p<=0)throw Error("Invalid sampling factor, expected values above 0");A.componentsOrder.push(Q),A.components[Q]={h:zt,v:p,quantizationIdx:G},$+=3}O(A),V.push(A);break;case 65476:var T=b();for(ot=2;ot<T;){var J=k[$++],Z=new Uint8Array(16),X=0;for(tt=0;tt<16;tt++,$++)X+=Z[tt]=k[$];y(16+X);var rt=new Uint8Array(X);for(tt=0;tt<X;tt++,$++)rt[tt]=k[$];ot+=17+X,(J>>4===0?mt:Et)[J&15]=a(Z,rt)}break;case 65501:b(),Ft=b();break;case 65500:b(),b();break;case 65498:var it=b(),St=k[$++],$t=[],v;for(ot=0;ot<St;ot++){v=A.components[k[$++]];var R=k[$++];v.huffmanTableDC=mt[R>>4],v.huffmanTableAC=Et[R&15],$t.push(v)}var q=k[$++],Mt=k[$++],_=k[$++],D=l(k,$,A,$t,Ft,q,Mt,_>>4,_&15,this.opts);$+=D;break;case 65535:if(k[$]!==255)$--;break;default:if(k[$-3]==255&&k[$-2]>=192&&k[$-2]<=254){$-=3;break}else if(B===224||B==225){if(It!==-1)throw Error(`first unknown JPEG marker at offset ${It.toString(16)}, second unknown JPEG marker ${B.toString(16)} at offset ${($-1).toString(16)}`);It=$-1;let W=b();if(k[$+W-2]===255){$+=W-2;break}}throw Error("unknown JPEG marker "+B.toString(16))}B=b()}if(V.length!=1)throw Error("only single frame JPEGs supported");for(var ot=0;ot<V.length;ot++){var lt=V[ot].components;for(var tt in lt)lt[tt].quantizationTable=U[lt[tt].quantizationIdx],delete lt[tt].quantizationIdx}this.width=A.samplesPerLine,this.height=A.scanLines,this.jfif=L,this.adobe=P,this.components=[];for(var ot=0;ot<A.componentsOrder.length;ot++){var v=A.components[A.componentsOrder[ot]];this.components.push({lines:g(A,v),scaleX:v.h/A.maxH,scaleY:v.v/A.maxV})}},getData:function(k,S){var $=this.width/k,H=this.height/S,b,j,O,L,P,C,A,Ft,U,V,Et=0,mt,B,It,ot,tt,x,w,K,ft,at,nt,et=k*S*this.components.length;y(et);var Y=new Uint8Array(et);switch(this.components.length){case 1:b=this.components[0];for(V=0;V<S;V++){P=b.lines[0|V*b.scaleY*H];for(U=0;U<k;U++)mt=P[0|U*b.scaleX*$],Y[Et++]=mt}break;case 2:b=this.components[0],j=this.components[1];for(V=0;V<S;V++){P=b.lines[0|V*b.scaleY*H],C=j.lines[0|V*j.scaleY*H];for(U=0;U<k;U++)mt=P[0|U*b.scaleX*$],Y[Et++]=mt,mt=C[0|U*j.scaleX*$],Y[Et++]=mt}break;case 3:if(nt=!0,this.adobe&&this.adobe.transformCode)nt=!0;else if(typeof this.opts.colorTransform<"u")nt=!!this.opts.colorTransform;b=this.components[0],j=this.components[1],O=this.components[2];for(V=0;V<S;V++){P=b.lines[0|V*b.scaleY*H],C=j.lines[0|V*j.scaleY*H],A=O.lines[0|V*O.scaleY*H];for(U=0;U<k;U++){if(!nt)K=P[0|U*b.scaleX*$],ft=C[0|U*j.scaleX*$],at=A[0|U*O.scaleX*$];else mt=P[0|U*b.scaleX*$],B=C[0|U*j.scaleX*$],It=A[0|U*O.scaleX*$],K=d(mt+1.402*(It-128)),ft=d(mt-0.3441363*(B-128)-0.71413636*(It-128)),at=d(mt+1.772*(B-128));Y[Et++]=K,Y[Et++]=ft,Y[Et++]=at}}break;case 4:if(!this.adobe)throw Error("Unsupported color mode (4 components)");if(nt=!1,this.adobe&&this.adobe.transformCode)nt=!0;else if(typeof this.opts.colorTransform<"u")nt=!!this.opts.colorTransform;b=this.components[0],j=this.components[1],O=this.components[2],L=this.components[3];for(V=0;V<S;V++){P=b.lines[0|V*b.scaleY*H],C=j.lines[0|V*j.scaleY*H],A=O.lines[0|V*O.scaleY*H],Ft=L.lines[0|V*L.scaleY*H];for(U=0;U<k;U++){if(!nt)tt=P[0|U*b.scaleX*$],x=C[0|U*j.scaleX*$],w=A[0|U*O.scaleX*$],ot=Ft[0|U*L.scaleX*$];else mt=P[0|U*b.scaleX*$],B=C[0|U*j.scaleX*$],It=A[0|U*O.scaleX*$],ot=Ft[0|U*L.scaleX*$],tt=255-d(mt+1.402*(It-128)),x=255-d(mt-0.3441363*(B-128)-0.71413636*(It-128)),w=255-d(mt+1.772*(B-128));Y[Et++]=255-tt,Y[Et++]=255-x,Y[Et++]=255-w,Y[Et++]=255-ot}}break;default:throw Error("Unsupported color mode")}return Y},copyToImageData:function(k,S){var{width:$,height:H,data:b}=k,j=this.getData($,H),O=0,L=0,P,C,A,Ft,U,V,Et,mt,B;switch(this.components.length){case 1:for(C=0;C<H;C++)for(P=0;P<$;P++)if(A=j[O++],b[L++]=A,b[L++]=A,b[L++]=A,S)b[L++]=255;break;case 3:for(C=0;C<H;C++)for(P=0;P<$;P++)if(Et=j[O++],mt=j[O++],B=j[O++],b[L++]=Et,b[L++]=mt,b[L++]=B,S)b[L++]=255;break;case 4:for(C=0;C<H;C++)for(P=0;P<$;P++)if(U=j[O++],V=j[O++],A=j[O++],Ft=j[O++],Et=255-d(U*(1-Ft/255)+Ft),mt=255-d(V*(1-Ft/255)+Ft),B=255-d(A*(1-Ft/255)+Ft),b[L++]=Et,b[L++]=mt,b[L++]=B,S)b[L++]=255;break;default:throw Error("Unsupported color mode")}}};var m=0,E=0;function y(N=0){var k=m+N;if(k>E){var S=Math.ceil((k-E)/1024/1024);throw Error(`maxMemoryUsageInMB limit exceeded by at least ${S}MB`)}m=k}return f.resetMaxMemoryUsage=function(N){m=0,E=N},f.getBytesAllocated=function(){return m},f.requestMemoryAllocation=y,f}();if(typeof ii<"u")ii.exports=cs;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].decode=cs;function cs(t,n={}){var e={colorTransform:void 0,useTArray:!1,formatAsRGBA:!0,tolerantDecoding:!0,maxResolutionInMP:100,maxMemoryUsageInMB:512},r={...e,...n},i=new Uint8Array(t),o=new ri;o.opts=r,ri.resetMaxMemoryUsage(r.maxMemoryUsageInMB*1024*1024),o.parse(i);var s=r.formatAsRGBA?4:3,c=o.width*o.height*s;try{ri.requestMemoryAllocation(c);var u={width:o.width,height:o.height,exifBuffer:o.exifBuffer,data:r.useTArray?new Uint8Array(c):Buffer.alloc(c)};if(o.comments.length>0)u.comments=o.comments}catch(h){if(h instanceof RangeError)throw Error("Could not allocate enough memory for the image. Required: "+c);if(h instanceof ReferenceError){if(h.message==="Buffer is not defined")throw Error("Buffer is not globally defined in this environment. Consider setting useTArray to true")}throw h}return o.copyToImageData(u,r.formatAsRGBA),u}});var fs=bt((J0,hs)=>{var ya=ss(),Sa=us();hs.exports={encode:ya,decode:Sa}});var oi=bt((A0,ls)=>{var Fa=Rt("util"),as=Rt("stream"),Bt=ls.exports=function(){as.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};Fa.inherits(Bt,as);Bt.prototype.read=function(t,n){this._reads.push({length:Math.abs(t),allowLess:t<0,func:n}),process.nextTick(function(){if(this._process(),this._paused&&this._reads&&this._reads.length>0)this._paused=!1,this.emit("drain")}.bind(this))};Bt.prototype.write=function(t,n){if(!this.writable)return this.emit("error",Error("Stream not writable")),!1;let e;if(Buffer.isBuffer(t))e=t;else e=Buffer.from(t,n||this._encoding);if(this._buffers.push(e),this._buffered+=e.length,this._process(),this._reads&&this._reads.length===0)this._paused=!0;return this.writable&&!this._paused};Bt.prototype.end=function(t,n){if(t)this.write(t,n);if(this.writable=!1,!this._buffers)return;if(this._buffers.length===0)this._end();else this._buffers.push(null),this._process()};Bt.prototype.destroySoon=Bt.prototype.end;Bt.prototype._end=function(){if(this._reads.length>0)this.emit("error",Error("Unexpected end of input"));this.destroy()};Bt.prototype.destroy=function(){if(!this._buffers)return;this.writable=!1,this._reads=null,this._buffers=null,this.emit("close")};Bt.prototype._processReadAllowingLess=function(t){this._reads.shift();let n=this._buffers[0];if(n.length>t.length)this._buffered-=t.length,this._buffers[0]=n.slice(t.length),t.func.call(this,n.slice(0,t.length));else this._buffered-=n.length,this._buffers.shift(),t.func.call(this,n)};Bt.prototype._processRead=function(t){this._reads.shift();let n=0,e=0,r=Buffer.alloc(t.length);while(n<t.length){let i=this._buffers[e++],o=Math.min(i.length,t.length-n);if(i.copy(r,n,0,o),n+=o,o!==i.length)this._buffers[--e]=i.slice(o)}if(e>0)this._buffers.splice(0,e);this._buffered-=t.length,t.func.call(this,r)};Bt.prototype._process=function(){try{while(this._buffered>0&&this._reads&&this._reads.length>0){let t=this._reads[0];if(t.allowLess)this._processReadAllowingLess(t);else if(this._buffered>=t.length)this._processRead(t);else break}if(this._buffers&&!this.writable)this._end()}catch(t){this.emit("error",t)}}});var si=bt((Ia)=>{var bn=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];Ia.getImagePasses=function(t,n){let e=[],r=t%8,i=n%8,o=(t-r)/8,s=(n-i)/8;for(let c=0;c<bn.length;c++){let u=bn[c],h=o*u.x.length,f=s*u.y.length;for(let a=0;a<u.x.length;a++)if(u.x[a]<r)h++;else break;for(let a=0;a<u.y.length;a++)if(u.y[a]<i)f++;else break;if(h>0&&f>0)e.push({width:h,height:f,index:c})}return e};Ia.getInterlaceIterator=function(t){return function(n,e,r){let i=n%bn[r].x.length,o=(n-i)/bn[r].x.length*8+bn[r].x[i],s=e%bn[r].y.length,c=(e-s)/bn[r].y.length*8+bn[r].y[s];return o*4+c*t*4}}});var ci=bt((T0,gs)=>{gs.exports=function(n,e,r){let i=n+e-r,o=Math.abs(i-n),s=Math.abs(i-e),c=Math.abs(i-r);if(o<=s&&o<=c)return n;if(s<=c)return e;return r}});var ui=bt((W0,ms)=>{var Ha=si(),Ra=ci();function ds(t,n,e){let r=t*n;if(e!==8)r=Math.ceil(r/(8/e));return r}var qn=ms.exports=function(t,n){let{width:e,height:r,interlace:i,bpp:o,depth:s}=t;if(this.read=n.read,this.write=n.write,this.complete=n.complete,this._imageIndex=0,this._images=[],i){let c=Ha.getImagePasses(e,r);for(let u=0;u<c.length;u++)this._images.push({byteWidth:ds(c[u].width,o,s),height:c[u].height,lineIndex:0})}else this._images.push({byteWidth:ds(e,o,s),height:r,lineIndex:0});if(s===8)this._xComparison=o;else if(s===16)this._xComparison=o*2;else this._xComparison=1};qn.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};qn.prototype._unFilterType1=function(t,n,e){let r=this._xComparison,i=r-1;for(let o=0;o<e;o++){let s=t[1+o],c=o>i?n[o-r]:0;n[o]=s+c}};qn.prototype._unFilterType2=function(t,n,e){let r=this._lastLine;for(let i=0;i<e;i++){let o=t[1+i],s=r?r[i]:0;n[i]=o+s}};qn.prototype._unFilterType3=function(t,n,e){let r=this._xComparison,i=r-1,o=this._lastLine;for(let s=0;s<e;s++){let c=t[1+s],u=o?o[s]:0,h=s>i?n[s-r]:0,f=Math.floor((h+u)/2);n[s]=c+f}};qn.prototype._unFilterType4=function(t,n,e){let r=this._xComparison,i=r-1,o=this._lastLine;for(let s=0;s<e;s++){let c=t[1+s],u=o?o[s]:0,h=s>i?n[s-r]:0,f=s>i&&o?o[s-r]:0,a=Ra(h,u,f);n[s]=c+a}};qn.prototype._reverseFilterLine=function(t){let n=t[0],e,r=this._images[this._imageIndex],i=r.byteWidth;if(n===0)e=t.slice(1,i+1);else switch(e=Buffer.alloc(i),n){case 1:this._unFilterType1(t,e,i);break;case 2:this._unFilterType2(t,e,i);break;case 3:this._unFilterType3(t,e,i);break;case 4:this._unFilterType4(t,e,i);break;default:throw Error("Unrecognised filter type - "+n)}if(this.write(e),r.lineIndex++,r.lineIndex>=r.height)this._lastLine=null,this._imageIndex++,r=this._images[this._imageIndex];else this._lastLine=e;if(r)this.read(r.byteWidth+1,this._reverseFilterLine.bind(this));else this._lastLine=null,this.complete()}});var $s=bt((Q0,ws)=>{var ja=Rt("util"),ps=oi(),Pa=ui(),Ga=ws.exports=function(t){ps.call(this);let n=[],e=this;this._filter=new Pa(t,{read:this.read.bind(this),write:function(r){n.push(r)},complete:function(){e.emit("complete",Buffer.concat(n))}}),this._filter.start()};ja.inherits(Ga,ps)});var Zn=bt((q0,bs)=>{bs.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 ai=bt((Z0,ks)=>{var hi=[];(function(){for(let t=0;t<256;t++){let n=t;for(let e=0;e<8;e++)if(n&1)n=3988292384^n>>>1;else n=n>>>1;hi[t]=n}})();var fi=ks.exports=function(){this._crc=-1};fi.prototype.write=function(t){for(let n=0;n<t.length;n++)this._crc=hi[(this._crc^t[n])&255]^this._crc>>>8;return!0};fi.prototype.crc32=function(){return this._crc^-1};fi.crc32=function(t){let n=-1;for(let e=0;e<t.length;e++)n=hi[(n^t[e])&255]^n>>>8;return n^-1}});var li=bt((X0,Es)=>{var Nt=Zn(),La=ai(),Ot=Es.exports=function(t,n){this._options=t,t.checkCRC=t.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[Nt.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[Nt.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[Nt.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[Nt.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[Nt.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[Nt.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=n.read,this.error=n.error,this.metadata=n.metadata,this.gamma=n.gamma,this.transColor=n.transColor,this.palette=n.palette,this.parsed=n.parsed,this.inflateData=n.inflateData,this.finished=n.finished,this.simpleTransparency=n.simpleTransparency,this.headersFinished=n.headersFinished||function(){}};Ot.prototype.start=function(){this.read(Nt.PNG_SIGNATURE.length,this._parseSignature.bind(this))};Ot.prototype._parseSignature=function(t){let n=Nt.PNG_SIGNATURE;for(let e=0;e<n.length;e++)if(t[e]!==n[e]){this.error(Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};Ot.prototype._parseChunkBegin=function(t){let n=t.readUInt32BE(0),e=t.readUInt32BE(4),r="";for(let o=4;o<8;o++)r+=String.fromCharCode(t[o]);let i=Boolean(t[4]&32);if(!this._hasIHDR&&e!==Nt.TYPE_IHDR){this.error(Error("Expected IHDR on beggining"));return}if(this._crc=new La,this._crc.write(Buffer.from(r)),this._chunks[e])return this._chunks[e](n);if(!i){this.error(Error("Unsupported critical chunk type "+r));return}this.read(n+4,this._skipChunk.bind(this))};Ot.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};Ot.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};Ot.prototype._parseChunkEnd=function(t){let n=t.readInt32BE(0),e=this._crc.crc32();if(this._options.checkCRC&&e!==n){this.error(Error("Crc error - "+n+" - "+e));return}if(!this._hasIEND)this.read(8,this._parseChunkBegin.bind(this))};Ot.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};Ot.prototype._parseIHDR=function(t){this._crc.write(t);let n=t.readUInt32BE(0),e=t.readUInt32BE(4),r=t[8],i=t[9],o=t[10],s=t[11],c=t[12];if(r!==8&&r!==4&&r!==2&&r!==1&&r!==16){this.error(Error("Unsupported bit depth "+r));return}if(!(i in Nt.COLORTYPE_TO_BPP_MAP)){this.error(Error("Unsupported color type"));return}if(o!==0){this.error(Error("Unsupported compression method"));return}if(s!==0){this.error(Error("Unsupported filter method"));return}if(c!==0&&c!==1){this.error(Error("Unsupported interlace method"));return}this._colorType=i;let u=Nt.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:n,height:e,depth:r,interlace:Boolean(c),palette:Boolean(i&Nt.COLORTYPE_PALETTE),color:Boolean(i&Nt.COLORTYPE_COLOR),alpha:Boolean(i&Nt.COLORTYPE_ALPHA),bpp:u,colorType:i}),this._handleChunkEnd()};Ot.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};Ot.prototype._parsePLTE=function(t){this._crc.write(t);let n=Math.floor(t.length/3);for(let e=0;e<n;e++)this._palette.push([t[e*3],t[e*3+1],t[e*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};Ot.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};Ot.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===Nt.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(Error("Transparency chunk must be after palette"));return}if(t.length>this._palette.length){this.error(Error("More transparent colors than palette size"));return}for(let n=0;n<t.length;n++)this._palette[n][3]=t[n];this.palette(this._palette)}if(this._colorType===Nt.COLORTYPE_GRAYSCALE)this.transColor([t.readUInt16BE(0)]);if(this._colorType===Nt.COLORTYPE_COLOR)this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]);this._handleChunkEnd()};Ot.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};Ot.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/Nt.GAMMA_DIVISION),this._handleChunkEnd()};Ot.prototype._handleIDAT=function(t){if(!this._emittedHeadersFinished)this._emittedHeadersFinished=!0,this.headersFinished();this.read(-t,this._parseIDAT.bind(this,t))};Ot.prototype._parseIDAT=function(t,n){if(this._crc.write(n),this._colorType===Nt.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw Error("Expected palette not found");this.inflateData(n);let e=t-n.length;if(e>0)this._handleIDAT(e);else this._handleChunkEnd()};Ot.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};Ot.prototype._parseIEND=function(t){if(this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished)this.finished()}});var gi=bt((Wa)=>{var Ms=si(),Ka=[function(){},function(t,n,e,r){if(r===n.length)throw Error("Ran out of data");let i=n[r];t[e]=i,t[e+1]=i,t[e+2]=i,t[e+3]=255},function(t,n,e,r){if(r+1>=n.length)throw Error("Ran out of data");let i=n[r];t[e]=i,t[e+1]=i,t[e+2]=i,t[e+3]=n[r+1]},function(t,n,e,r){if(r+2>=n.length)throw Error("Ran out of data");t[e]=n[r],t[e+1]=n[r+1],t[e+2]=n[r+2],t[e+3]=255},function(t,n,e,r){if(r+3>=n.length)throw Error("Ran out of data");t[e]=n[r],t[e+1]=n[r+1],t[e+2]=n[r+2],t[e+3]=n[r+3]}],Ja=[function(){},function(t,n,e,r){let i=n[0];t[e]=i,t[e+1]=i,t[e+2]=i,t[e+3]=r},function(t,n,e){let r=n[0];t[e]=r,t[e+1]=r,t[e+2]=r,t[e+3]=n[1]},function(t,n,e,r){t[e]=n[0],t[e+1]=n[1],t[e+2]=n[2],t[e+3]=r},function(t,n,e){t[e]=n[0],t[e+1]=n[1],t[e+2]=n[2],t[e+3]=n[3]}];function Aa(t,n){let e=[],r=0;function i(){if(r===t.length)throw Error("Ran out of data");let o=t[r];r++;let s,c,u,h,f,a,l,g;switch(n){default:throw Error("unrecognised depth");case 16:l=t[r],r++,e.push((o<<8)+l);break;case 4:l=o&15,g=o>>4,e.push(g,l);break;case 2:f=o&3,a=o>>2&3,l=o>>4&3,g=o>>6&3,e.push(g,l,a,f);break;case 1:s=o&1,c=o>>1&1,u=o>>2&1,h=o>>3&1,f=o>>4&1,a=o>>5&1,l=o>>6&1,g=o>>7&1,e.push(g,l,a,f,h,u,c,s);break}}return{get:function(o){while(e.length<o)i();let s=e.slice(0,o);return e=e.slice(o),s},resetAfterLine:function(){e.length=0},end:function(){if(r!==t.length)throw Error("extra data found")}}}function Ua(t,n,e,r,i,o){let{width:s,height:c,index:u}=t;for(let h=0;h<c;h++)for(let f=0;f<s;f++){let a=e(f,h,u);Ka[r](n,i,a,o),o+=r}return o}function Ta(t,n,e,r,i,o){let{width:s,height:c,index:u}=t;for(let h=0;h<c;h++){for(let f=0;f<s;f++){let a=i.get(r),l=e(f,h,u);Ja[r](n,a,l,o)}i.resetAfterLine()}}Wa.dataToBitMap=function(t,n){let{width:e,height:r,depth:i,bpp:o,interlace:s}=n,c;if(i!==8)c=Aa(t,i);let u;if(i<=8)u=Buffer.alloc(e*r*4);else u=new Uint16Array(e*r*4);let h=Math.pow(2,i)-1,f=0,a,l;if(s)a=Ms.getImagePasses(e,r),l=Ms.getInterlaceIterator(e,r);else{let g=0;l=function(){let d=g;return g+=4,d},a=[{width:e,height:r}]}for(let g=0;g<a.length;g++)if(i===8)f=Ua(a[g],u,l,o,t,f);else Ta(a[g],u,l,o,c,h);if(i===8){if(f!==t.length)throw Error("extra data found")}else c.end();return u}});var di=bt((C0,vs)=>{function qa(t,n,e,r,i){let o=0;for(let s=0;s<r;s++)for(let c=0;c<e;c++){let u=i[t[o]];if(!u)throw Error("index "+t[o]+" not in palette");for(let h=0;h<4;h++)n[o+h]=u[h];o+=4}}function Za(t,n,e,r,i){let o=0;for(let s=0;s<r;s++)for(let c=0;c<e;c++){let u=!1;if(i.length===1){if(i[0]===t[o])u=!0}else if(i[0]===t[o]&&i[1]===t[o+1]&&i[2]===t[o+2])u=!0;if(u)for(let h=0;h<4;h++)n[o+h]=0;o+=4}}function Xa(t,n,e,r,i){let o=255,s=Math.pow(2,i)-1,c=0;for(let u=0;u<r;u++)for(let h=0;h<e;h++){for(let f=0;f<4;f++)n[c+f]=Math.floor(t[c+f]*o/s+0.5);c+=4}}vs.exports=function(t,n,e=!1){let{depth:r,width:i,height:o,colorType:s,transColor:c,palette:u}=n,h=t;if(s===3)qa(t,h,i,o,u);else{if(c)Za(t,h,i,o,c);if(r!==8&&!e){if(r===16)h=Buffer.alloc(i*o*4);Xa(t,h,i,o,r)}}return h}});var Fs=bt((x0,Ss)=>{var _a=Rt("util"),mi=Rt("zlib"),ys=oi(),Ca=$s(),xa=li(),Ya=gi(),za=di(),en=Ss.exports=function(t){ys.call(this),this._parser=new xa(t,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,"gamma"),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=t,this.writable=!0,this._parser.start()};_a.inherits(en,ys);en.prototype._handleError=function(t){if(this.emit("error",t),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy)this._inflate.destroy();if(this._filter)this._filter.destroy(),this._filter.on("error",function(){});this.errord=!0};en.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=mi.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let e=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,r=Math.max(e,mi.Z_MIN_CHUNK);this._inflate=mi.createInflate({chunkSize:r});let i=e,o=this.emit.bind(this,"error");this._inflate.on("error",function(c){if(!i)return;o(c)}),this._filter.on("complete",this._complete.bind(this));let s=this._filter.write.bind(this._filter);this._inflate.on("data",function(c){if(!i)return;if(c.length>i)c=c.slice(0,i);i-=c.length,s(c)}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};en.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new Ca(this._bitmapInfo)};en.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};en.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};en.prototype._simpleTransparency=function(){this._metaData.alpha=!0};en.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};en.prototype._finished=function(){if(this.errord)return;if(!this._inflate)this.emit("error","No Inflate block");else this._inflate.end()};en.prototype._complete=function(t){if(this.errord)return;let n;try{let e=Ya.dataToBitMap(t,this._bitmapInfo);n=za(e,this._bitmapInfo,this._options.skipRescale),e=null}catch(e){this._handleError(e);return}this.emit("parsed",n)}});var Ns=bt((Y0,Is)=>{var Xt=Zn();Is.exports=function(t,n,e,r){let i=[Xt.COLORTYPE_COLOR_ALPHA,Xt.COLORTYPE_ALPHA].indexOf(r.colorType)!==-1;if(r.colorType===r.inputColorType){let d=function(){let m=new ArrayBuffer(2);return new DataView(m).setInt16(0,256,!0),new Int16Array(m)[0]!==256}();if(r.bitDepth===8||r.bitDepth===16&&d)return t}let o=r.bitDepth!==16?t:new Uint16Array(t.buffer),s=255,c=Xt.COLORTYPE_TO_BPP_MAP[r.inputColorType];if(c===4&&!r.inputHasAlpha)c=3;let u=Xt.COLORTYPE_TO_BPP_MAP[r.colorType];if(r.bitDepth===16)s=65535,u*=2;let h=Buffer.alloc(n*e*u),f=0,a=0,l=r.bgColor||{};if(l.red===void 0)l.red=s;if(l.green===void 0)l.green=s;if(l.blue===void 0)l.blue=s;function g(){let d,m,E,y=s;switch(r.inputColorType){case Xt.COLORTYPE_COLOR_ALPHA:y=o[f+3],d=o[f],m=o[f+1],E=o[f+2];break;case Xt.COLORTYPE_COLOR:d=o[f],m=o[f+1],E=o[f+2];break;case Xt.COLORTYPE_ALPHA:y=o[f+1],d=o[f],m=d,E=d;break;case Xt.COLORTYPE_GRAYSCALE:d=o[f],m=d,E=d;break;default:throw Error("input color type:"+r.inputColorType+" is not supported at present")}if(r.inputHasAlpha){if(!i)y/=s,d=Math.min(Math.max(Math.round((1-y)*l.red+y*d),0),s),m=Math.min(Math.max(Math.round((1-y)*l.green+y*m),0),s),E=Math.min(Math.max(Math.round((1-y)*l.blue+y*E),0),s)}return{red:d,green:m,blue:E,alpha:y}}for(let d=0;d<e;d++)for(let m=0;m<n;m++){let E=g(o,f);switch(r.colorType){case Xt.COLORTYPE_COLOR_ALPHA:case Xt.COLORTYPE_COLOR:if(r.bitDepth===8){if(h[a]=E.red,h[a+1]=E.green,h[a+2]=E.blue,i)h[a+3]=E.alpha}else if(h.writeUInt16BE(E.red,a),h.writeUInt16BE(E.green,a+2),h.writeUInt16BE(E.blue,a+4),i)h.writeUInt16BE(E.alpha,a+6);break;case Xt.COLORTYPE_ALPHA:case Xt.COLORTYPE_GRAYSCALE:{let y=(E.red+E.green+E.blue)/3;if(r.bitDepth===8){if(h[a]=y,i)h[a+1]=E.alpha}else if(h.writeUInt16BE(y,a),i)h.writeUInt16BE(E.alpha,a+2);break}default:throw Error("unrecognised color Type "+r.colorType)}f+=c,a+=u}return h}});var Rs=bt((z0,Hs)=>{var Os=ci();function Va(t,n,e,r,i){for(let o=0;o<e;o++)r[i+o]=t[n+o]}function Ba(t,n,e){let r=0,i=n+e;for(let o=n;o<i;o++)r+=Math.abs(t[o]);return r}function Da(t,n,e,r,i,o){for(let s=0;s<e;s++){let c=s>=o?t[n+s-o]:0,u=t[n+s]-c;r[i+s]=u}}function tl(t,n,e,r){let i=0;for(let o=0;o<e;o++){let s=o>=r?t[n+o-r]:0,c=t[n+o]-s;i+=Math.abs(c)}return i}function nl(t,n,e,r,i){for(let o=0;o<e;o++){let s=n>0?t[n+o-e]:0,c=t[n+o]-s;r[i+o]=c}}function el(t,n,e){let r=0,i=n+e;for(let o=n;o<i;o++){let s=n>0?t[o-e]:0,c=t[o]-s;r+=Math.abs(c)}return r}function rl(t,n,e,r,i,o){for(let s=0;s<e;s++){let c=s>=o?t[n+s-o]:0,u=n>0?t[n+s-e]:0,h=t[n+s]-(c+u>>1);r[i+s]=h}}function il(t,n,e,r){let i=0;for(let o=0;o<e;o++){let s=o>=r?t[n+o-r]:0,c=n>0?t[n+o-e]:0,u=t[n+o]-(s+c>>1);i+=Math.abs(u)}return i}function ol(t,n,e,r,i,o){for(let s=0;s<e;s++){let c=s>=o?t[n+s-o]:0,u=n>0?t[n+s-e]:0,h=n>0&&s>=o?t[n+s-(e+o)]:0,f=t[n+s]-Os(c,u,h);r[i+s]=f}}function sl(t,n,e,r){let i=0;for(let o=0;o<e;o++){let s=o>=r?t[n+o-r]:0,c=n>0?t[n+o-e]:0,u=n>0&&o>=r?t[n+o-(e+r)]:0,h=t[n+o]-Os(s,c,u);i+=Math.abs(h)}return i}var cl={0:Va,1:Da,2:nl,3:rl,4:ol},ul={0:Ba,1:tl,2:el,3:il,4:sl};Hs.exports=function(t,n,e,r,i){let o;if(!("filterType"in r)||r.filterType===-1)o=[0,1,2,3,4];else if(typeof r.filterType==="number")o=[r.filterType];else throw Error("unrecognised filter types");if(r.bitDepth===16)i*=2;let s=n*i,c=0,u=0,h=Buffer.alloc((s+1)*e),f=o[0];for(let a=0;a<e;a++){if(o.length>1){let l=1/0;for(let g=0;g<o.length;g++){let d=ul[o[g]](t,u,s,i);if(d<l)f=o[g],l=d}}h[c]=f,c++,cl[f](t,u,s,h,c,i),c+=s,u+=s}return h}});var pi=bt((V0,js)=>{var Pt=Zn(),hl=ai(),fl=Ns(),al=Rs(),ll=Rt("zlib"),kn=js.exports=function(t){if(this._options=t,t.deflateChunkSize=t.deflateChunkSize||32768,t.deflateLevel=t.deflateLevel!=null?t.deflateLevel:9,t.deflateStrategy=t.deflateStrategy!=null?t.deflateStrategy:3,t.inputHasAlpha=t.inputHasAlpha!=null?t.inputHasAlpha:!0,t.deflateFactory=t.deflateFactory||ll.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType==="number"?t.colorType:Pt.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType==="number"?t.inputColorType:Pt.COLORTYPE_COLOR_ALPHA,[Pt.COLORTYPE_GRAYSCALE,Pt.COLORTYPE_COLOR,Pt.COLORTYPE_COLOR_ALPHA,Pt.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw Error("option color type:"+t.colorType+" is not supported at present");if([Pt.COLORTYPE_GRAYSCALE,Pt.COLORTYPE_COLOR,Pt.COLORTYPE_COLOR_ALPHA,Pt.COLORTYPE_ALPHA].indexOf(t.inputColorType)===-1)throw Error("option input color type:"+t.inputColorType+" is not supported at present");if(t.bitDepth!==8&&t.bitDepth!==16)throw Error("option bit depth:"+t.bitDepth+" is not supported at present")};kn.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};kn.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};kn.prototype.filterData=function(t,n,e){let r=fl(t,n,e,this._options),i=Pt.COLORTYPE_TO_BPP_MAP[this._options.colorType];return al(r,n,e,this._options,i)};kn.prototype._packChunk=function(t,n){let e=n?n.length:0,r=Buffer.alloc(e+12);if(r.writeUInt32BE(e,0),r.writeUInt32BE(t,4),n)n.copy(r,8);return r.writeInt32BE(hl.crc32(r.slice(4,r.length-4)),r.length-4),r};kn.prototype.packGAMA=function(t){let n=Buffer.alloc(4);return n.writeUInt32BE(Math.floor(t*Pt.GAMMA_DIVISION),0),this._packChunk(Pt.TYPE_gAMA,n)};kn.prototype.packIHDR=function(t,n){let e=Buffer.alloc(13);return e.writeUInt32BE(t,0),e.writeUInt32BE(n,4),e[8]=this._options.bitDepth,e[9]=this._options.colorType,e[10]=0,e[11]=0,e[12]=0,this._packChunk(Pt.TYPE_IHDR,e)};kn.prototype.packIDAT=function(t){return this._packChunk(Pt.TYPE_IDAT,t)};kn.prototype.packIEND=function(){return this._packChunk(Pt.TYPE_IEND,null)}});var Ks=bt((B0,Ls)=>{var gl=Rt("util"),Ps=Rt("stream"),dl=Zn(),ml=pi(),Gs=Ls.exports=function(t){Ps.call(this);let n=t||{};this._packer=new ml(n),this._deflate=this._packer.createDeflate(),this.readable=!0};gl.inherits(Gs,Ps);Gs.prototype.pack=function(t,n,e,r){if(this.emit("data",Buffer.from(dl.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(n,e)),r)this.emit("data",this._packer.packGAMA(r));let i=this._packer.filterData(t,n,e);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(o){this.emit("data",this._packer.packIDAT(o))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(i)}});var Qs=bt((ke,Ws)=>{var Js=Rt("assert").ok,Xn=Rt("zlib"),pl=Rt("util"),As=Rt("buffer").kMaxLength;function Hn(t){if(!(this instanceof Hn))return new Hn(t);if(t&&t.chunkSize<Xn.Z_MIN_CHUNK)t.chunkSize=Xn.Z_MIN_CHUNK;if(Xn.Inflate.call(this,t),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,t&&t.maxLength!=null)this._maxLength=t.maxLength}function wl(t){return new Hn(t)}function Us(t,n){if(n)process.nextTick(n);if(!t._handle)return;t._handle.close(),t._handle=null}Hn.prototype._processChunk=function(t,n,e){if(typeof e==="function")return Xn.Inflate._processChunk.call(this,t,n,e);let r=this,i=t&&t.length,o=this._chunkSize-this._offset,s=this._maxLength,c=0,u=[],h=0,f;this.on("error",function(d){f=d});function a(d,m){if(r._hadError)return;let E=o-m;if(Js(E>=0,"have should not go down"),E>0){let y=r._buffer.slice(r._offset,r._offset+E);if(r._offset+=E,y.length>s)y=y.slice(0,s);if(u.push(y),h+=y.length,s-=y.length,s===0)return!1}if(m===0||r._offset>=r._chunkSize)o=r._chunkSize,r._offset=0,r._buffer=Buffer.allocUnsafe(r._chunkSize);if(m===0)return c+=i-d,i=d,!0;return!1}Js(this._handle,"zlib binding closed");let l;do l=this._handle.writeSync(n,t,c,i,this._buffer,this._offset,o),l=l||this._writeState;while(!this._hadError&&a(l[0],l[1]));if(this._hadError)throw f;if(h>=As)throw Us(this),RangeError("Cannot create final Buffer. It would be larger than 0x"+As.toString(16)+" bytes");let g=Buffer.concat(u,h);return Us(this),g};pl.inherits(Hn,Xn.Inflate);function $l(t,n){if(typeof n==="string")n=Buffer.from(n);if(!(n instanceof Buffer))throw TypeError("Not a string or buffer");let e=t._finishFlushFlag;if(e==null)e=Xn.Z_FINISH;return t._processChunk(n,e)}function Ts(t,n){return $l(new Hn(n),t)}Ws.exports=ke=Ts;ke.Inflate=Hn;ke.createInflate=wl;ke.inflateSync=Ts});var wi=bt((D0,Zs)=>{var qs=Zs.exports=function(t){this._buffer=t,this._reads=[]};qs.prototype.read=function(t,n){this._reads.push({length:Math.abs(t),allowLess:t<0,func:n})};qs.prototype.process=function(){while(this._reads.length>0&&this._buffer.length){let t=this._reads[0];if(this._buffer.length&&(this._buffer.length>=t.length||t.allowLess)){this._reads.shift();let n=this._buffer;this._buffer=n.slice(t.length),t.func.call(this,n.slice(0,t.length))}else break}if(this._reads.length>0)throw Error("There are some read requests waitng on finished stream");if(this._buffer.length>0)throw Error("unrecognised content at end of stream")}});var Xs=bt((El)=>{var bl=wi(),kl=ui();El.process=function(t,n){let e=[],r=new bl(t);return new kl(n,{read:r.read.bind(r),write:function(o){e.push(o)},complete:function(){}}).start(),r.process(),Buffer.concat(e)}});var Ys=bt((nw,xs)=>{var _s=!0,Cs=Rt("zlib"),vl=Qs();if(!Cs.deflateSync)_s=!1;var yl=wi(),Sl=Xs(),Fl=li(),Il=gi(),Nl=di();xs.exports=function(t,n){if(!_s)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let e;function r(S){e=S}let i;function o(S){i=S}function s(S){i.transColor=S}function c(S){i.palette=S}function u(){i.alpha=!0}let h;function f(S){h=S}let a=[];function l(S){a.push(S)}let g=new yl(t);if(new Fl(n,{read:g.read.bind(g),error:r,metadata:o,gamma:f,palette:c,transColor:s,inflateData:l,simpleTransparency:u}).start(),g.process(),e)throw e;let m=Buffer.concat(a);a.length=0;let E;if(i.interlace)E=Cs.inflateSync(m);else{let $=((i.width*i.bpp*i.depth+7>>3)+1)*i.height;E=vl(m,{chunkSize:$,maxLength:$})}if(m=null,!E||!E.length)throw Error("bad png - invalid inflate data response");let y=Sl.process(E,i);m=null;let N=Il.dataToBitMap(y,i);y=null;let k=Nl(N,i,n.skipRescale);return i.data=k,i.gamma=h||0,i}});var Ds=bt((ew,Bs)=>{var zs=!0,Vs=Rt("zlib");if(!Vs.deflateSync)zs=!1;var Ol=Zn(),Hl=pi();Bs.exports=function(t,n){if(!zs)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let r=new Hl(n||{}),i=[];if(i.push(Buffer.from(Ol.PNG_SIGNATURE)),i.push(r.packIHDR(t.width,t.height)),t.gamma)i.push(r.packGAMA(t.gamma));let o=r.filterData(t.data,t.width,t.height),s=Vs.deflateSync(o,r.getDeflateOptions());if(o=null,!s||!s.length)throw Error("bad png - invalid compressed data response");return i.push(r.packIDAT(s)),i.push(r.packIEND()),Buffer.concat(i)}});var tc=bt((Pl)=>{var Rl=Ys(),jl=Ds();Pl.read=function(t,n){return Rl(t,n||{})};Pl.write=function(t,n){return jl(t,n)}});var ec=bt((Tl)=>{var Kl=Rt("util"),nc=Rt("stream"),Jl=Fs(),Al=Ks(),Ul=tc(),Gt=Tl.PNG=function(t){if(nc.call(this),t=t||{},this.width=t.width|0,this.height=t.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,t.fill&&this.data)this.data.fill(0);this.gamma=0,this.readable=this.writable=!0,this._parser=new Jl(t),this._parser.on("error",this.emit.bind(this,"error")),this._parser.on("close",this._handleClose.bind(this)),this._parser.on("metadata",this._metadata.bind(this)),this._parser.on("gamma",this._gamma.bind(this)),this._parser.on("parsed",function(n){this.data=n,this.emit("parsed",n)}.bind(this)),this._packer=new Al(t),this._packer.on("data",this.emit.bind(this,"data")),this._packer.on("end",this.emit.bind(this,"end")),this._parser.on("close",this._handleClose.bind(this)),this._packer.on("error",this.emit.bind(this,"error"))};Kl.inherits(Gt,nc);Gt.sync=Ul;Gt.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};Gt.prototype.parse=function(t,n){if(n){let e,r;e=function(i){this.removeListener("error",r),this.data=i,n(null,this)}.bind(this),r=function(i){this.removeListener("parsed",e),n(i,null)}.bind(this),this.once("parsed",e),this.once("error",r)}return this.end(t),this};Gt.prototype.write=function(t){return this._parser.write(t),!0};Gt.prototype.end=function(t){this._parser.end(t)};Gt.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};Gt.prototype._gamma=function(t){this.gamma=t};Gt.prototype._handleClose=function(){if(!this._parser.writable&&!this._packer.readable)this.emit("close")};Gt.bitblt=function(t,n,e,r,i,o,s,c){if(e|=0,r|=0,i|=0,o|=0,s|=0,c|=0,e>t.width||r>t.height||e+i>t.width||r+o>t.height)throw Error("bitblt reading outside image");if(s>n.width||c>n.height||s+i>n.width||c+o>n.height)throw Error("bitblt writing outside image");for(let u=0;u<o;u++)t.data.copy(n.data,(c+u)*n.width+s<<2,(r+u)*t.width+e<<2,(r+u)*t.width+e+i<<2)};Gt.prototype.bitblt=function(t,n,e,r,i,o,s){return Gt.bitblt(this,t,n,e,r,i,o,s),this};Gt.adjustGamma=function(t){if(t.gamma){for(let n=0;n<t.height;n++)for(let e=0;e<t.width;e++){let r=t.width*n+e<<2;for(let i=0;i<3;i++){let o=t.data[r+i]/255;o=Math.pow(o,0.45454545454545453/t.gamma),t.data[r+i]=Math.round(o*255)}}t.gamma=0}};Gt.prototype.adjustGamma=function(){Gt.adjustGamma(this)}});var fo=bt((Ib,uf)=>{var ho={to(t,n){if(!n)return`\x1B[${t+1}G`;return`\x1B[${n+1};${t+1}H`},move(t,n){let e="";if(t<0)e+=`\x1B[${-t}D`;else if(t>0)e+=`\x1B[${t}C`;if(n<0)e+=`\x1B[${-n}A`;else if(n>0)e+=`\x1B[${n}B`;return e},up:(t=1)=>`\x1B[${t}A`,down:(t=1)=>`\x1B[${t}B`,forward:(t=1)=>`\x1B[${t}C`,backward:(t=1)=>`\x1B[${t}D`,nextLine:(t=1)=>"\x1B[E".repeat(t),prevLine:(t=1)=>"\x1B[F".repeat(t),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},dp={up:(t=1)=>"\x1B[S".repeat(t),down:(t=1)=>"\x1B[T".repeat(t)},mp={screen:"\x1B[2J",up:(t=1)=>"\x1B[1J".repeat(t),down:(t=1)=>"\x1B[J".repeat(t),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(t){let n="";for(let e=0;e<t;e++)n+=this.line+(e<t-1?ho.up():"");if(t)n+=ho.left;return n}};uf.exports={cursor:ho,scroll:dp,erase:mp,beep:"\x07"}});import{isMainThread as $0}from"node:worker_threads";import{parseArgs as m0}from"node:util";var nn={name:"@kecan0406/ttheme",version:"1.0.32",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 yu}from"node:fs";import{basename as rd,join as Ke}from"node:path";var $a=/^#[0-9a-f]{6}$/;function _o(t){return $a.test(t)}function jt(t){let n=Number.parseInt(t.slice(1),16);return[n>>16&255,n>>8&255,n&255]}function Vt(t){let[n,e,r]=jt(t).map((i)=>{let o=i/255;return o<=0.03928?o/12.92:((o+0.055)/1.055)**2.4});return 0.2126*n+0.7152*e+0.0722*r}function fn(t,n){let e=Vt(t),r=Vt(n);return(Math.max(e,r)+0.05)/(Math.min(e,r)+0.05)}function rr(t,n){return Math.round(fn(t,n)*100)/100}var wn=7,Co=3,ti=0.15,xo=1.6,Yo=[1,2,3,4,5,6,9,10,11,12,13,14],zo=[7,15];function me(t,n){let e=t.ansi[n];if(e===void 0)throw Error(`${t.name}: missing ANSI ${n}`);return e}function ni(t,n,e){let r=t.background;return n.flatMap((i)=>{let o=me(t,i);return fn(o,r)<e?[`ANSI ${i} ${o} on ${r} is ${rr(o,r)}:1, needs ${e}:1`]:[]})}function Vo(t,n){return Math.min(...n.map((e)=>fn(me(t,e),t.background)))}var ir=[{rule:"foreground",label:"foreground on background",unit:"ratio",min:wn,measure:({foreground:t,background:n})=>fn(t,n),check:({foreground:t,background:n})=>fn(t,n)<wn?[`foreground ${t} on ${n} is ${rr(t,n)}:1, needs ${wn}:1`]:[]},{rule:"accents",label:"weakest accent on background",unit:"ratio",min:Co,measure:(t)=>Vo(t,Yo),check:(t)=>ni(t,Yo,Co)},{rule:"ansi0-dark",label:"ansi0 luminance",unit:"luminance",max:ti,measure:(t)=>Vt(me(t,0)),check:(t)=>{let n=me(t,0);return Vt(n)>ti?[`ANSI 0 ${n} has luminance ${Vt(n).toFixed(3)}, needs <= ${ti}`]:[]}},{rule:"light-ansi",label:"ansi7 and ansi15 on background",unit:"ratio",min:wn,measure:(t)=>Vo(t,zo),check:(t)=>ni(t,zo,wn)},{rule:"ansi8-visible",label:"ansi8 on background",unit:"ratio",min:xo,measure:(t)=>fn(me(t,8),t.background),check:(t)=>ni(t,[8],xo)},{rule:"selection",label:"foreground on selection",unit:"ratio",min:wn,measure:({foreground:t,selectionBackground:n})=>n===void 0?Number.NaN:fn(t,n),check:({foreground:t,selectionBackground:n})=>n!==void 0&&fn(t,n)<wn?[`foreground ${t} on selection ${n} is ${rr(t,n)}:1, needs ${wn}:1`]:[]}],y0=ir.map((t)=>t.rule),or=ir.map(({rule:t,label:n,unit:e,min:r,max:i})=>({rule:t,label:n,unit:e,...r===void 0?{}:{min:r},...i===void 0?{}:{max:i}}));function Bo(t){return ir.map((n)=>Math.round(n.measure(t)*1000)/1000)}function ei(t){return ir.filter((n)=>!t.waive.includes(n.rule)).flatMap((n)=>n.check(t).map((e)=>({theme:t.name,rule:n.rule,detail:e})))}function Do(t){return t.flatMap(ei)}var ba=["black","red","green","yellow","blue","magenta","cyan","white"];function ts(t,n){return[t,...ba.map((e,r)=>`${e} = '${n[r]}'`),""].join(`
|
|
3
|
+
`)}var pe={id:"alacritty",limits:"no shaders, no runtime color API (OSC only)",emit(t){let n=[...Qn(t),"","[colors.primary]",`background = '${t.background}'`,`foreground = '${t.foreground}'`,"","[colors.cursor]",`cursor = '${t.cursor}'`,`text = '${t.background}'`,"","[colors.selection]",`background = '${t.selectionBackground}'`,`text = '${t.foreground}'`,"",ts("[colors.normal]",t.ansi.slice(0,8)),ts("[colors.bright]",t.ansi.slice(8,16))].join(`
|
|
4
|
+
`),e=[`# ${t.name} — font settings.`,`# Pair with the palette: import = ["~/.config/alacritty/themes/${t.name}.toml"]`,"","[font]",`size = ${t.font.size}`,"","[font.normal]",`family = '${t.font.family}'`,""].join(`
|
|
5
|
+
`);return[{path:`alacritty/themes/${t.name}.toml`,content:n},{path:`alacritty/config/${t.name}.toml`,content:e}]}};import{isDeepStrictEqual as ka}from"node:util";var we={id:"ghostty",emit(t){let n=[...Qn(t),`background = ${t.background}`,`foreground = ${t.foreground}`,`cursor-color = ${t.cursor}`,`selection-background = ${t.selectionBackground}`,`selection-foreground = ${t.foreground}`,...t.ansi.map((e,r)=>`palette = ${r}=${e}`),"palette-generate = true","","macos-icon = custom-style",`macos-icon-ghost-color = ${t.ghostty.iconGhost}`,`macos-icon-screen-color = ${t.ghostty.iconScreen.join(",")}`,"macos-icon-frame = chrome",""].join(`
|
|
6
|
+
`);return[{path:`ghostty/themes/${t.name}`,content:n}]},emitShared(t){let[n]=t;if(!n)return[];for(let r of t)if(!ka(r.font,n.font)||r.ghostty.shader!==n.ghostty.shader)throw Error(`${r.name}: per-theme font/shader overrides cannot be expressed in the shared ghostty/ttheme.conf`);return[{path:"ghostty/ttheme.conf",content:["# ttheme — shared font and shader, identical for every palette.","# Pick colors with: theme = <palette>",`font-family = ${n.font.family}`,`font-size = ${n.font.size}`,...n.font.codepointMap.map((r)=>`font-codepoint-map = ${r.range}=${r.family}`),...n.ghostty.shader?["",`custom-shader = ~/.config/ghostty/shaders/${n.ghostty.shader}`,"custom-shader-animation = true"]:[],""].join(`
|
|
7
|
+
`)}]}};function $n(t){let[n,e,r]=jt(t);return{"Alpha Component":1,"Blue Component":r/255,"Color Space":"P3","Green Component":e/255,"Red Component":n/255}}function ns(t){return{...Object.fromEntries(t.ansi.map((n,e)=>[`Ansi ${e} Color`,$n(n)])),"Background Color":$n(t.background),"Bold Color":$n(t.foreground),"Cursor Color":$n(t.cursor),"Cursor Text Color":$n(t.background),"Foreground Color":$n(t.foreground),"Selected Text Color":$n(t.foreground),"Selection Color":$n(t.selectionBackground)}}function Ea(t){return t?{"Background Image Location":t.image,"Background Image Mode":t.cover?2:3,Blend:t.opacity}:{"Background Image Location":""}}function es(t,n,e,r){let i=(s,c)=>({Name:`ttheme · ${c}`,Guid:`ttheme-${c}`,...r?{"Dynamic Profile Parent GUID":r}:{},"Use Separate Colors for Light and Dark Mode":!1,"Harmonize 256 Colors":!0,...Ea(n.get(s.name)),...ns(s)}),o=[...e?[i(e,"default")]:[],...t.map((s)=>i(s,s.name))];return`${JSON.stringify({Profiles:o},null,2)}
|
|
8
|
+
`}function Ma(t,n){return[` <key>${t}</key>`,"\t<dict>",...Object.entries(n).flatMap(([e,r])=>[` <key>${e}</key>`,typeof r==="string"?` <string>${r}</string>`:` <real>${r}</real>`]),"\t</dict>"].join(`
|
|
9
|
+
`)}var $e={id:"iterm2",limits:"colors only — font lives in the profile; colors are Display P3, the space iTerm2 reads OSC colors in",emit(t){let n=['<?xml version="1.0" encoding="UTF-8"?>','<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">','<plist version="1.0">',"<dict>",...Object.entries(ns(t)).map(([e,r])=>Ma(e,r)),"</dict>","</plist>",""].join(`
|
|
10
|
+
`);return[{path:`iterm2/${t.name}.itermcolors`,content:n}]}};var be={id:"kitty",limits:"no GLSL shaders, no per-codepoint font mapping",emit(t){let n=[...Qn(t),`background ${t.background}`,`foreground ${t.foreground}`,`cursor ${t.cursor}`,`cursor_text_color ${t.background}`,`selection_background ${t.selectionBackground}`,`selection_foreground ${t.foreground}`,...t.ansi.map((r,i)=>`color${i} ${r}`),""].join(`
|
|
11
|
+
`),e=[`# ${t.name} — font settings.`,`# Pair with the palette: include themes/${t.name}.conf`,`font_family ${t.font.family}`,`font_size ${t.font.size}`,""].join(`
|
|
12
|
+
`);return[{path:`kitty/themes/${t.name}.conf`,content:n},{path:`kitty/config/${t.name}.conf`,content:e}]}};function rs(t){return["# Generated by ttheme — rewritten on every add, remove and default; do not edit.","import os","",`THEMES = ${JSON.stringify(t.themes)}`,`BACKGROUNDS = ${JSON.stringify(t.backgrounds)}`,"PLACES = {"," 'top-left': 'top-left', 'top-center': 'top', 'top-right': 'top-right',"," 'center-left': 'left', 'center': 'center', 'center-center': 'center', 'center-right': 'right',"," 'bottom-left': 'bottom-left', 'bottom-center': 'bottom', 'bottom-right': 'bottom-right',","}","","shown = {}","faded = {}","worn = {}","","","def locate(path):"," if path.startswith('~/'):"," return os.path.expanduser(path)"," return path if os.path.isabs(path) else os.path.join(BACKGROUNDS, path)","","","def read(path, into):"," try:"," with open(path, encoding='utf-8') as f:"," lines = f.read().splitlines()"," except OSError:"," return False"," for line in lines:"," key, sep, value = line.partition('=')"," key, value = key.strip(), value.strip()"," if not sep or not key or key.startswith('#'):"," continue"," if key == 'config-file':"," read(locate(value.lstrip('?')), into)"," else:"," into[key] = value"," return True","","","def logo(palette):"," c = {}"," if not palette or not read(os.path.join(BACKGROUNDS, palette + '.conf'), c):"," return None"," image = c.get('background-image', '')"," try:"," opacity = min(float(c.get('background-image-opacity', '1')), 1.0)"," except ValueError:"," opacity = 1.0"," if not image or opacity <= 0:"," return None"," return locate(image), PLACES.get(c.get('background-image-position', 'center'), 'center'), opacity","","","def fade(path, opacity):"," key = f'{path}#{opacity}'"," if key not in faded:"," from kitty.fast_data_types import load_png_data, png_from_32bit_rgba_data"," with open(path, 'rb') as f:"," rgba, width, height = load_png_data(f.read())"," data = bytearray(rgba)"," data[3::4] = data[3::4].translate(bytes(round(a * opacity) for a in range(256)))"," if len(faded) > 8:"," faded.clear()"," faded[key] = png_from_32bit_rgba_data(bytes(data), width, height)"," return key, faded[key]","","","def show(window):"," want = logo(window.user_vars.get('ttheme_shown') or '')"," if window.id in shown and shown[window.id] == want:"," return"," shown[window.id] = want"," try:"," if want is None:"," window.set_logo('')"," elif want[2] < 1:"," key, png = fade(want[0], want[2])"," window.set_logo(key, want[1], 1, png)"," else:"," window.set_logo(want[0], want[1], 1)"," except Exception:"," shown.pop(window.id, None)","","","def theme(palette):"," path = os.path.join(THEMES, palette + '.conf')"," if not palette or not os.path.exists(path):"," return None"," from kitty.colors import parse_colors"," return parse_colors([path])","","","def wear(palette):"," colors = theme(palette) if worn.get('startup') != palette else None"," if colors is None:"," return"," from kitty.colors import patch_colors"," patch_colors(colors[0], colors[1], True, ())"," worn['startup'] = palette","","","def rewear(boss):"," from kitty.colors import patch_colors"," for window in tuple(boss.all_windows):"," colors = theme(window.user_vars.get('ttheme_worn') or '')"," if colors is not None:"," patch_colors(colors[0], colors[1], False, (window,))","","","def on_load(boss, data):"," if getattr(boss, 'ttheme_rewears', False):"," return"," load = boss.load_config_file",""," def reload(*args, **kwargs):"," load(*args, **kwargs)"," worn.pop('startup', None)"," rewear(boss)",""," boss.load_config_file = reload"," boss.ttheme_rewears = True","","","def on_set_user_var(boss, window, data):"," if data['key'] == 'ttheme_shown':"," show(window)"," elif data['key'] == 'ttheme_startup':"," wear(data['value'] or '')","","","def on_focus_change(boss, window, data):"," if data['focused']:"," show(window)","","","def on_close(boss, window, data):"," shown.pop(window.id, None)",""].join(`
|
|
13
|
+
`)}import{createHash as ql}from"node:crypto";import{mkdirSync as gc,readdirSync as Rn,readFileSync as dc,renameSync as mc,rmSync as Cn,statSync as Zl,utimesSync as Xl,writeFileSync as hr}from"node:fs";import{isAbsolute as _l,join as vt}from"node:path";var oc=er(fs(),1),cr=er(ec(),1),rc=[137,80,78,71,13,10,26,10],sc=13;function Ee(t){return t.length>=rc.length&&rc.every((n,e)=>t[e]===n)}function Wl(t){let n=cr.PNG.sync.read(Buffer.from(t));return{width:n.width,height:n.height,data:new Uint8Array(n.data)}}function cc(t,n){if(Ee(t)){let e=Me(t);if(e&&e.width*e.height>n)throw Error(`${e.width}×${e.height} is over ${n/1e6} megapixels`);return Wl(t)}if(t[0]===255&&t[1]===216){let e=oc.decode(t,{useTArray:!0,formatAsRGBA:!0,maxResolutionInMP:n/1e6,maxMemoryUsageInMB:1024});return{width:e.width,height:e.height,data:e.data}}throw Error("not a PNG or JPEG image")}function _n(t){let n=new cr.PNG({width:t.width,height:t.height});return n.data=Buffer.from(t.data),cr.PNG.sync.write(n)}function ic(t,n){for(let e=0;e+n.length<=t.length;e++){let r=!0;for(let i=0;i<n.length&&r;i++)r=t[e+i]===n.charCodeAt(i);if(r)return e}return-1}function Me(t){if(t.length<33||!Ee(t))return null;let n=new DataView(t.buffer,t.byteOffset,t.byteLength),e=n.getUint32(16),r=n.getUint32(20);if(t[25]===4||t[25]===6)return{width:e,height:r,alpha:!0};let i=ic(t,"IDAT");return{width:e,height:r,alpha:ic(i===-1?t:t.subarray(0,i),"tRNS")!==-1}}function uc(t,n=sc){let{width:e,height:r}=t,i=-1,o=-1;for(let s=0;s<t.height;s++)for(let c=0;c<t.width;c++)if((t.data[(s*t.width+c)*4+3]??0)>=n)e=Math.min(e,c),i=Math.max(i,c),r=Math.min(r,s),o=Math.max(o,s);return i<0?null:{x:e,y:r,w:i-e+1,h:o-r+1}}function ve(t,n={x:0,y:0,w:t.width,h:t.height}){let e=0;for(let r=n.y;r<n.y+n.h;r++)for(let i=n.x;i<n.x+n.w;i++)if((t.data[(r*t.width+i)*4+3]??0)<sc)e++;return Math.round(e*100/(n.w*n.h))}function Ql(t,n){if(n<=1)return t;let e=Math.max(1,Math.floor(t.width/n)),r=Math.max(1,Math.floor(t.height/n)),i=new Uint8Array(e*r*4),o=t.data;for(let s=0;s<r;s++)for(let c=0;c<e;c++){let u=0,h=0,f=0,a=0;for(let g=0;g<n;g++)for(let d=0;d<n;d++){let m=((s*n+g)*t.width+c*n+d)*4,E=o[m+3]??0;u+=(o[m]??0)*E,h+=(o[m+1]??0)*E,f+=(o[m+2]??0)*E,a+=E}let l=(s*e+c)*4;if(a>0)i[l]=Math.round(u/a),i[l+1]=Math.round(h/a),i[l+2]=Math.round(f/a);i[l+3]=Math.round(a/(n*n))}return{width:e,height:r,data:i}}function hc(t,n,e){let r=Math.min(n/t.width,e/t.height),i=Math.max(1,Math.round(t.width*r)),o=Math.max(1,Math.round(t.height*r)),s=ur(t,{x:0,y:0,w:t.width,h:t.height},i,o),c=new Uint8Array(n*e*4),u=Math.floor((n-i)/2),h=Math.floor((e-o)/2);for(let f=0;f<o;f++)c.set(s.data.subarray(f*i*4,(f+1)*i*4),((h+f)*n+u)*4);return{width:n,height:e,data:c}}function ur(t,n,e,r){let i=Math.max(1,Math.floor(Math.min(n.w/e,n.h/r))),o=Ql(t,i),s=o.data,c=new Uint8Array(e*r*4);for(let u=0;u<r;u++){let h=Math.min(o.height-1,Math.max(0,n.y/i+(u+0.5)*n.h/i/r-0.5)),f=Math.floor(h),a=Math.min(o.height-1,f+1),l=h-f;for(let g=0;g<e;g++){let d=Math.min(o.width-1,Math.max(0,n.x/i+(g+0.5)*n.w/i/e-0.5)),m=Math.floor(d),E=Math.min(o.width-1,m+1),y=d-m,N=(f*o.width+m)*4,k=(f*o.width+E)*4,S=(a*o.width+m)*4,$=(a*o.width+E)*4,H=(s[N+3]??0)*(1-y)*(1-l),b=(s[k+3]??0)*y*(1-l),j=(s[S+3]??0)*(1-y)*l,O=(s[$+3]??0)*y*l,L=H+b+j+O,P=(u*e+g)*4;if(L>0)for(let C=0;C<3;C++){let A=(s[N+C]??0)*H+(s[k+C]??0)*b+(s[S+C]??0)*j+(s[$+C]??0)*O;c[P+C]=Math.round(A/L)}c[P+3]=Math.round(L)}}return{width:e,height:r,data:c}}var fc={width:2560,height:1550},Cl=2560,xl=0.1,an={tall:1.15,reach:0.4,widest:0.95,headroom:0.04,margin:0.03,stands:12},Yl=Vt($i("#19161e","#9b86c8",0.2)),zl="shelf";function $i(t,n,e){let r=jt(t),i=jt(n);return`#${r.map((o,s)=>Math.round(o+((i[s]??0)-o)*e).toString(16).padStart(2,"0")).join("")}`}function Vl(t,n){if(n==="background"||n==="foreground"||n==="cursor")return t[n];if(n==="selection"&&t.selection)return t.selection;let e=/^ansi(\d|1[0-5])$/.exec(n),r=e?t.ansi[Number(e[1])]:void 0;if(!r)throw Error(`${t.name} has no slot ${n}`);return r}function ac(t){if(t(1))return 1;let n=0,e=1;for(let r=0;r<40;r++){let i=(n+e)/2;if(t(i))n=i;else e=i}return n}function lc(t,n){let e=Vl(t,n),i=ac((h)=>ei({name:t.name,background:$i(t.background,e,h),foreground:t.foreground,ansi:t.ansi,waive:t.waived??[]}).length===0),o=ac((h)=>Vt($i(t.background,e,h))<=Yl),s=Math.floor(Math.min(i,o)*1000)/1000,c=jt(t.background),u=Math.hypot(...jt(e).map((h,f)=>(h-(c[f]??0))*s));return{slot:n,color:e,cap:i,matched:o,opacity:s,reach:u}}function fr(t,n){let e=lc(t,"cursor");if(e.opacity>=xl)return e;return n.filter((r)=>r!=="cursor"&&r!=="background").map((r)=>lc(t,r)).reduce((r,i)=>i.reach>r.reach?i:r,e)}function bi(t,n,e){let r=jt(n),i=jt(e),o=t.data;for(let s=0;s<o.length;s+=4){let c=(0.299*(o[s]??0)+0.587*(o[s+1]??0)+0.114*(o[s+2]??0))/255;for(let u=0;u<3;u++)o[s+u]=Math.round((r[u]??0)+((i[u]??0)-(r[u]??0))*c)}return t}function Bl(t,n,e){let r=jt(n),i=t.data,o=new Uint8Array(i.length);for(let s=0;s<i.length;s+=4){let c=(i[s+3]??0)/255*e;for(let u=0;u<3;u++)o[s+u]=Math.round((r[u]??0)*(1-c)+(i[s+u]??0)*c);o[s+3]=255}return{width:t.width,height:t.height,data:o}}function pc(t){return uc(t)??{x:0,y:0,w:t.width,h:t.height}}function Dl(t,n){if(t<=0||n<=0)return fc;let e=Math.min(1,fc.width/Math.max(t,n));return{width:Math.round(t*e),height:Math.round(n*e)}}function tg(t,n){let e=Math.min(1,Cl/Math.max(n.w,n.h));return ur(t,n,Math.round(n.w*e),Math.round(n.h*e))}function wc(t,n,e,r){if(r<an.stands){let u=t.w*e>t.h*n?{x:t.x+(t.w-t.h*n/e)/2,y:t.y,w:t.h*n/e,h:t.h}:{x:t.x,y:t.y,w:t.w,h:t.w*e/n};return{crop:u,at:{x:0,y:0,w:n,h:e},focus:(u.y-t.y+u.h/2)/t.h}}let i=Math.max(an.tall*e,an.reach*n*t.h/t.w),o=i*t.w/t.h;if(o>an.widest*n)o=an.widest*n,i=o*t.h/t.w;let s=an.headroom*e,c=Math.min(1,(e-s)/i);return{crop:{x:t.x,y:t.y,w:t.w,h:t.h*c},at:{x:n*(1-an.margin)-o,y:s,w:o,h:i*c},focus:Math.min(1,(e/2-s)/i)}}function $c(t,n,e,r){let i=Math.max(1,Math.round(n.at.w)),o=Math.max(1,Math.round(n.at.h)),s=ur(t,n.crop,i,o),c=new Uint8Array(e*r*4),u=Math.round(n.at.x),h=Math.round(n.at.y);for(let f=0;f<o;f++){let a=h+f,l=Math.max(0,-u),g=Math.min(i,e-u);if(a<0||a>=r||g<=l)continue;c.set(s.data.subarray((f*i+l)*4,(f*i+g)*4),(a*e+u+l)*4)}return{width:e,height:r,data:c}}function bc(t,n,e,r,i){let o=pc(t),s=$c(t,wc(o,r,i,ve(t,o)),r,i);return Bl(bi(s,n.background,e.color),n.background,e.opacity)}function En(t){return vt(t,"ttheme","backgrounds")}function ng(t,n,e,r,i){return[...r?[`# from ${r}`]:[],...i?[`# image ${i}`]:[],`background-image = ${n}`,"background-image-fit = cover","background-image-position = top-right",`background-image-opacity = ${e}`,`config-file = ?${t}.tune.conf`,`config-file = ?${t}.off.conf`,""].join(`
|
|
14
|
+
`)}function kc(t,n,e){let r=new Map;for(let s of[`${n}.conf`,`${n}.tune.conf`,`${n}.off.conf`]){let c;try{c=dc(vt(t,s),"utf8")}catch{if(s===`${n}.conf`)return;continue}for(let u of c.split(`
|
|
15
|
+
`)){let h=/^(background-image(?:-fit|-opacity)?)\s*=\s*(.*?)\s*$/.exec(u);if(h)r.set(h[1],h[2])}}let i=r.get("background-image")??"";if(i==="")return;let o=Number(r.get("background-image-opacity")??1);return{image:i.startsWith("~/")?vt(e,i.slice(2)):_l(i)?i:vt(t,i),opacity:Number.isFinite(o)?o:1,cover:r.get("background-image-fit")==="cover"}}function eg(t,n){for(let e of Rn(t))if(ki(e,n))Cn(vt(t,e))}function rg(t){return`${t.site}_${t.id}`}function ar(t,n){return vt(t,zl,n)}function ki(t,n){let e=t.slice(n.length);return t.startsWith(n)&&(e===".conf"||e===".tune.conf"||e===".off.conf"||/^(\.[0-9a-f]{8})?(@[a-z0-9-]+)?\.png$/.test(e))}function ye(t,n){try{return/^# image (\S+)$/m.exec(dc(vt(t,`${n}.conf`),"utf8"))?.[1]}catch{return}}function ig(t,n){try{return Rn(ar(t,n))}catch{return[]}}function Ec(t,n){let e=ye(t,n);return[...e?[e]:[],...ig(t,n)].sort()}function Mc(t,n){let e=ye(t,n);if(!e)return;let r=vt(ar(t,n),e);Cn(r,{recursive:!0,force:!0}),gc(r,{recursive:!0});for(let i of Rn(t))if(ki(i,n))mc(vt(t,i),vt(r,i.slice(n.length)))}function vc(t,n,e){let r=vt(ar(t,n),e);for(let i of Rn(r))mc(vt(r,i),vt(t,`${n}${i}`));Cn(r,{recursive:!0})}function yc(t,n,e){try{return Rn(vt(t,"originals")).find((r)=>r.startsWith(`${n}-${e}.`))}catch{return}}function Sc(t,n,e){let r=yc(t,n,e);if(r){let i=new Date;Xl(vt(t,"originals",r),i,i)}}function Fc(t,n,e){let r=En(t),i=Ec(r,n),o=ye(r,n);if(!o||i.length<2)throw Error(`${n} has no other image`);let s=(i.indexOf(o)+e+i.length)%i.length,c=i[s];return Mc(r,n),vc(r,n,c),Sc(r,n,c),{key:c,at:s+1,of:i.length}}function Ic(t,n){let e=En(t),r=Rn(e).filter((h)=>ki(h,n));if(r.length===0)throw Error(`${n} has no image`);let i=Ec(e,n),o=ye(e,n),s=o&&yc(e,n,o);if(s)Cn(vt(e,"originals",s));for(let h of r)Cn(vt(e,h));let c=i.filter((h)=>h!==o),u=c[(o?i.indexOf(o):0)%c.length];if(u)vc(e,n,u),Sc(e,n,u);return{key:o,left:c.length}}function og(t,n,e){if(ye(t,n)!==e)Mc(t,n);if(e)Cn(vt(ar(t,n),e),{recursive:!0,force:!0});eg(t,n)}function Nc(t,n,e,r,i,o){let s=En(t),c=n.name,u=rg(i);gc(vt(s,"originals"),{recursive:!0}),og(s,c,u);let h=pc(r),{width:f,height:a}=Dl(o.width,o.height),l=wc(h,f,a,ve(r,h)),g=_n(bi(tg(r,h),n.background,e.color)),d=_n(bi($c(r,l,f,a),n.background,e.color)),m=vt(s,`${c}.${ql("sha1").update(g).update(d).digest("hex").slice(0,8)}`),E=`${m}.png`,y=`${m}@fill-${Math.round(l.focus*100)}.png`,N=vt(s,`${c}.conf`),k=vt(s,"originals",`${c}-${i.site}_${i.id}.${i.ext}`);return hr(E,g),hr(y,d),hr(N,ng(c,y,e.opacity,i.from,u)),hr(k,i.bytes),[E,y,N,k]}function Oc(t){let n=vt(En(t),"originals"),e=new Map,r;try{r=Rn(n)}catch{return new Map}for(let i of r){let o=/^(.+)-([a-z.]+)_(\d+)\.[a-z]+$/.exec(i),[,s,c,u]=o??[];if(!s||!c||!u)continue;let h=Zl(vt(n,i)).mtimeMs,f=e.get(s);if(!f||h>f.at)e.set(s,{site:c,id:Number(u),at:h})}return new Map([...e].map(([i,{site:o,id:s}])=>[i,{site:o,id:s}]))}function Ei(t){let{slot:n,color:e,opacity:r}=fr({name:t.name,background:t.background,foreground:t.foreground,cursor:t.cursor,selection:t.selectionBackground,ansi:t.ansi,waived:t.waive},t.signatureSlots);return{name:t.name,group:t.group,...t.native?{native:t.native}:{},...t.lead?{lead:!0}:{},order:t.order,ansiSource:t.ansiSource,...t.booru?{booru:t.booru}:{},...t.booruSites?{booruSites:t.booruSites}:{},...t.role==="default"?{default:!0}:{},background:t.background,foreground:t.foreground,cursor:t.cursor,selection:t.selectionBackground,signature:t.signature,signatureSlots:t.signatureSlots,ansi:t.ansi,gate:Bo(t),...t.waive.length>0?{waived:t.waive}:{},backdrop:{slot:n,color:e,opacity:r}}}function xn(t){return t.filter((n)=>n.default!==!0)}function sg(t){let[n]=t;if(!n)throw Error("manifest needs at least one theme");return{version:nn.version,gate:or,placement:an,font:n.font,...n.ghostty.shader?{shader:n.ghostty.shader}:{},palettes:t.map(Ei)}}var Mi={id:"meta",emitShared(t){return[{path:"manifest.json",content:`${JSON.stringify(sg(t),null,2)}
|
|
16
|
+
`}]}};import{readdirSync as Ag,readFileSync as Ni}from"node:fs";import{basename as Ug,join as Oi}from"node:path";import{readdirSync as cg,rmSync as ug,statSync as hg}from"node:fs";import{setDefaultAutoSelectFamilyAttemptTimeout as fg}from"node:net";import{homedir as ag}from"node:os";import{join as Fe}from"node:path";import{setTimeout as lg}from"node:timers/promises";var jn=100,Gn=25000000,gg=536870912,Ie=["safe","questionable","explicit"],Pn=["nudity","underwear"],dg={nudity:new Set(["nude","naked","topless","bottomless","nipples","naked_towel","undressing"]),underwear:new Set(["underwear","panties","pantsu","bra","lingerie","pantyshot"])},Se={safe:"s",questionable:"q",explicit:"e"},mg=8191,pg=20000,wg=5000,Hc=3000,Rc=8,$g=3000,Lc=60000,jc=3,yi=`ttheme/${nn.version} (+${nn.homepage})`,bg=["orig","tile","thumb","cut"],Kc=new Map,kg=Hg(process.env.TTHEME_FIND_HOSTS),Eg=Og(process.env.TTHEME_FIND_CUTOUTS);fg($g);function Pc(t){try{return cg(t)}catch{return[]}}function lr(t){return t.startsWith("//")?`https:${t}`:t}function Ne(t){return(/\.([a-z0-9]+)(?:\?.*)?$/i.exec(t)?.[1]??"").toLowerCase()}function Oe(t){let n=t.trim();if(!n)return[];let e=JSON.parse(n);if(Array.isArray(e))return e;let r=e.posts;return Array.isArray(r)?r:[]}function Mg(t){let n=t.trim(),r=(n?JSON.parse(n):{}).tags??{};return new Map(Object.entries(r).map(([i,o])=>[i,String(o)]))}function vi(t,n,e){let r=lr(String(t??""));return{file:r,width:Number(n)||0,height:Number(e)||0,ext:Ne(r)}}function Jc(t,n){let e=lr(String(n.preview??""));if(!n.file||!e||!Number(t.id))return[];let r=Number(t.width??t.image_width)||0,i=Number(t.height??t.image_height)||0;return[{id:Number(t.id),width:r,height:i,file:n.file,preview:e,ext:n.ext,owner:String(n.owner??""),artist:n.artist,score:Number(t.score)||0,rating:String(t.rating??""),md5:String(n.md5??""),source:String(t.source??""),tags:n.tags.split(/\s+/).filter(Boolean),solo:n.solo,family:Number(t.parent_id)||(t.has_children===!0?Number(t.id):0),smaller:n.versions.filter((o)=>o.file&&o.width>0&&o.height>0&&o.width*o.height<r*i)}]}function vg(t){let n=Mg(t);return Oe(t).flatMap((e)=>{let r=lr(String(e.file_url??"")),i=String(e.tags??"");return Jc(e,{preview:e.preview_url,file:r,ext:String(e.file_ext||Ne(r)).toLowerCase(),owner:e.author,artist:i.split(/\s+/).find((o)=>n.get(o)==="artist")??"",md5:e.md5,tags:i,solo:void 0,versions:[vi(e.jpeg_url,e.jpeg_width,e.jpeg_height),vi(e.sample_url,e.sample_width,e.sample_height)]})})}function yg(t){return Oe(t).flatMap((n)=>{let e=lr(String(n.file_url??"")),r=String(n.tag_string??""),i=n.media_asset??{};return Jc(n,{preview:i.variants?.find((o)=>o.type==="360x360")?.url??n.preview_file_url,file:e,ext:String(n.file_ext||Ne(e)).toLowerCase(),owner:"",artist:String(n.tag_string_artist??"").split(/\s+/)[0]??"",md5:n.md5,tags:r,solo:r.split(/\s+/).includes("solo"),versions:(i.variants??[]).map((o)=>vi(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 Sg(t){return Oe(t).flatMap((n)=>{let e=String(n.value??"");return e?[{value:e,count:Number(n.post_count)||0}]:[]})}function Fg(t){return Oe(t).flatMap((n)=>{let e=String(n.name??"");return e?[{value:e,count:Number(n.count)||0}]:[]})}function Ig(t){return Number(/count="(\d+)"/.exec(t)?.[1]??0)}function Ng(t){let n=t.trim()?JSON.parse(t):{};return Number(n.counts?.posts)||0}function Og(t){let n=new Map;for(let e of(t??"").split(/\s+/).filter(Boolean)){let r=e.indexOf("=");if(r>0)n.set(e.slice(0,r),e.slice(r+1).split(",").filter(Boolean))}return n}function Hg(t){let n=new Map;for(let e of(t??"").split(/[\s,]+/).filter(Boolean)){let r=e.indexOf("="),i=e.slice(0,r);try{let o=new URL(e.slice(r+1));if(i&&o.protocol==="https:")n.set(i,o.origin)}catch{}}return n}function Ac(t,n,e,r){let i=(t??"").split(/\s+/);if(r!==void 0&&i.includes(r))return[];let o=n.filter((s)=>i.includes(s));return o.length>0?o:[...e]}function gr(t){return Ac(t,Ie,["safe"])}function dr(t){return Ac(t,Pn,Pn,"none")}function Uc(t,n,e){return{safe:new Set(t),questionable:new Set(n),explicit:new Set(e)}}function Tc(t){let n=kg.get(t.key),e=Eg.get(t.key);return{...t,origin:n??t.origin,moved:n!==void 0&&n!==t.origin,cutouts:e??t.cutouts,vouched:t.vouched&&e===void 0}}function Wc(t){return t.length<2?t.join(""):t.map((n)=>`~${n}`).join(" ")}function Gc(t){let n=Tc(t),e=(r)=>new URLSearchParams({api_version:"2",include_tags:"1",...r});return{...n,cutouts:Wc(n.cutouts),ratings:Uc([Se.safe],[Se.questionable],[Se.explicit]),rate:(r)=>{let[i]=r;if(r.length===1&&i)return`rating:${Se[i]}`;let o=Ie.filter((c)=>!r.includes(c)),[s]=o;return o.length===1&&s?`-rating:${Se[s]}`:""},best:"order:score",tagBudget:Number.POSITIVE_INFINITY,postsUrl:(r,i)=>`${n.origin}/post.json?${e({limit:String(jn),page:String(i+1),tags:r})}`,countUrl:(r)=>`${n.origin}/post.xml?${new URLSearchParams({limit:"1",tags:r})}`,postUrl:(r)=>`${n.origin}/post.json?${e({tags:`id:${r}`})}`,pageUrl:(r)=>`${n.origin}/post/show/${r}`,parse:vg,count:Ig}}function Rg(t){let n=Tc(t),e=Uc(["g"],["s","q"],["e"]);return{...n,cutouts:Wc(n.cutouts),ratings:e,rate:(r)=>r.length===Ie.length?"":`rating:${r.flatMap((i)=>[...e[i]]).join(",")}`,best:"order:score",tagBudget:2,postsUrl:(r,i)=>`${n.origin}/posts.json?${new URLSearchParams({limit:String(jn),page:String(i+1),tags:r})}`,countUrl:(r)=>`${n.origin}/counts/posts.json?${new URLSearchParams({tags:r})}`,postUrl:(r)=>`${n.origin}/posts.json?${new URLSearchParams({limit:"1",tags:`id:${r}`})}`,pageUrl:(r)=>`${n.origin}/posts/${r}`,parse:yg,count:Ng}}function jg(t){return gt.find((n)=>n.key===t||n.name===t||new URL(n.origin).host===t)}function Si(t){return t.split(/\s+/).filter((n)=>n&&!n.startsWith("rating:")).length}function mr(t,n){let e=t.trim();if(/^\d+$/.test(e))return{site:n,id:Number(e)};let r=/^([\w.]+):(\d+)$/.exec(e);if(r){let c=gt.find((u)=>u.key===r[1]||u.name===r[1]);return c&&{site:c,id:Number(r[2])}}let i;try{i=new URL(e)}catch{return}let o=jg(i.host),s=Number(i.searchParams.get("id")??i.pathname.split("/").filter(Boolean).at(-1));return o&&s>0?{site:o,id:s}:void 0}var gt=[Rg({key:"danbooru",name:"danbooru",origin:"https://danbooru.donmai.us",cutouts:["transparent_background"],vouched:!1,tunneled:!0,ansi:2}),Gc({key:"konachan",name:"konachan",origin:"https://konachan.net",cutouts:["transparent","vector"],vouched:!1,tunneled:!1,ansi:6}),Gc({key:"yande",name:"yande.re",origin:"https://yande.re",cutouts:["transparent_png"],vouched:!0,tunneled:!1,ansi:5})],ln=134217728;function rn(t,n){let e=gt.indexOf(t);return(e===-1?gt.length:e)*ln+n}function Fi(t){let n;try{n=new URL(t).hostname}catch{return""}return n.split(".").slice(-2).join(".")}function Qc(){return gt.filter((t)=>!t.tunneled).map((t)=>Fi(t.origin)).flatMap((t)=>[t,`.${t}`]).join(",")}function qc(t,n=Pn){return t.tags.filter((e)=>n.some((r)=>dg[r].has(e)))}function Zc(t,n,e=["safe"]){return e.some((r)=>t.ratings[r].has(n.rating))}function He(t){return[t,...t.smaller].find((n)=>n.width*n.height<=Gn)}function Xc(t){let n=new Map;for(let[e,r]of[...t].sort(([i],[o])=>i<o?-1:1)){if(r==="")continue;n.set(r,[...n.get(r)??[],e])}return n}function _c(){return Fe(process.env.XDG_CACHE_HOME??Fe(ag(),".cache"),"ttheme")}function yn(t){return Fe(_c(),t.key)}function Cc(t=gg,n=_c()){let e=[],r=0;for(let i of Pc(n))for(let o of bg){let s=Fe(n,i,o);for(let c of Pc(s)){let u=Fe(s,c);try{let{size:h,mtimeMs:f}=hg(u);e.push({path:u,size:h,at:f}),r+=h}catch{}}}e.sort((i,o)=>i.at-o.at);for(let i of e){if(r<=t)return;try{ug(i.path,{force:!0}),r-=i.size}catch{}}}function Pg(t,n){if(t!==null&&/^\s*\d+\s*$/.test(t))return Number(t)*1000;let e=t===null?Number.NaN:Date.parse(t);return Number.isNaN(e)?Lc:Math.max(0,e-n)}function Mn(t){return Kc.get(t.key)??0}function Gg(t){for(let n=t;n instanceof Error;n=n.cause)if(n.code==="ECONNRESET")return!0;return!1}function Lg(t){return(t.headers.get("server")??"").startsWith("cloudflare")&&t.headers.get("cf-mitigated")==="challenge"}async function vn(t,n,e,r={},i=pg){for(let o=1;;o++){let s=Mn(t)-Date.now();if(s>0)await lg(s,void 0,{signal:e});let c;try{c=await fetch(n,{headers:{"User-Agent":yi,Referer:`${t.origin}/`,...r},signal:i?AbortSignal.any([e,AbortSignal.timeout(i)]):e})}catch(u){if(o<jc&&!e.aborted&&Gg(u))continue;throw u}if(c.status===429&&o<jc){await c.body?.cancel();let u=Pg(c.headers.get("retry-after"),Date.now());if(u>Lc)throw Error(`${t.name} asks to wait ${Math.ceil(u/1000)}s`);Kc.set(t.key,Math.max(Mn(t),Date.now()+u));continue}if(!c.ok)throw await c.body?.cancel(),Error(Lg(c)?`${t.name} is behind a Cloudflare challenge`:`${t.name} answered ${c.status}`);return c}}async function xc(t,n,e,r){return t.parse(await(await vn(t,t.postsUrl(n,e),r)).text())}async function Yc(t,n,e){return t.count(await(await vn(t,t.countUrl(n),e)).text())}async function Ii(t,n,e){let[r]=t.parse(await(await vn(t,t.postUrl(n),e)).text());return r}function Kg(t){let n=gt.find((r)=>r.key==="danbooru"),e=new URLSearchParams({limit:String(2*jn),only:"md5,tag_string",tags:`md5:${t.join(",")}`});return`${n.origin}/posts.json?${e}`}function Jg(t){return new Map(Oe(t).flatMap((n)=>{let e=String(n.md5??"");return e?[[e,String(n.tag_string??"").split(/\s+/).filter(Boolean)]]:[]}))}function zc(t,n){for(let e of t){let r=n.get(e.md5);if(r)e.tags=[...new Set([...e.tags,...r])],e.solo=r.includes("solo")}}async function Vc(t,n){let e=gt.find((i)=>i.key==="danbooru"),r=new Map;if(Mn(e)>Date.now())return r;for(let i=0;i<t.length;i+=jn){let o=await(await vn(e,Kg(t.slice(i,i+jn)),n,{},wg)).text();for(let[s,c]of Jg(o))r.set(s,c)}return r}async function Bc(t,n){let e=gt.find((o)=>o.key==="danbooru");if(Mn(e)<=Date.now())try{let o=new URLSearchParams({"search[query]":t,"search[type]":"tag_query",limit:String(Rc)}),s=`${e.origin}/autocomplete.json?${o}`;return Sg(await(await vn(e,s,n,{},Hc)).text())}catch(o){if(n.aborted)throw o}let r=gt.find((o)=>o.key==="yande"),i=new URLSearchParams({name:t,order:"count",limit:String(Rc)});return Fg(await(await vn(r,`${r.origin}/tag.json?${i}`,n,{},Hc)).text())}async function Dc(t,n,e){let r=await vn(t,n,e,{Range:`bytes=0-${mg}`});return Me(new Uint8Array(await r.arrayBuffer()))}async function tu(t,n,e,r){let i=await vn(t,n,e,{},0),o=Number(i.headers.get("content-length"))||0,s=i.body?.getReader();if(!s)return new Uint8Array(await i.arrayBuffer());let c=[],u=0;for(;;){let{done:a,value:l}=await s.read();if(a)break;c.push(l),u+=l.length,r?.(u,o)}let h=new Uint8Array(u),f=0;for(let a of c)h.set(a,f),f+=a.length;return h}var Tg="_defaults.toml",gn="_groups.toml",nu=3,eu=["background","foreground","cursor","selection"],Wg=new Set(["next","help","preview","pin","unpin","config"]);function yt(t,n){throw Error(`${t}: ${n}`)}function Ln(t,n,e){if(typeof e!=="string"||!_o(e))yt(t,`${n} must be "#rrggbb" (lowercase), got ${JSON.stringify(e)}`);return e}function _t(t,n,e){if(typeof e!=="string"||e.length===0)yt(t,`${n} must be a non-empty string`);return e}function dn(t){return t&&typeof t==="object"?t:{}}function Qg(t,n,e){let r={...dn(e),...dn(n)},i=r.codepoint_map??[];if(!Array.isArray(i))yt(t,"font.codepoint_map must be an array");return{family:_t(t,"font.family",r.family),size:Number(r.size),codepointMap:i.map((o)=>{let s=dn(o);return{range:_t(t,"font.codepoint_map[].range",s.range),family:_t(t,"font.codepoint_map[].family",s.family)}})}}function qg(t,n,e){if(n===void 0)return[e.cursor,e.selectionBackground,e.background];let r=Array.isArray(n)?n:[n];if(r.length===0)yt(t,"ghostty.icon_screen must not be empty");return r.map((i,o)=>Ln(t,`ghostty.icon_screen[${o}]`,i))}function Zg(t,n,e,r){let i={...dn(e),...dn(n)};return{shader:i.shader===void 0?void 0:_t(t,"ghostty.shader",i.shader),iconGhost:i.icon_ghost===void 0?r.cursor:Ln(t,"ghostty.icon_ghost",i.icon_ghost),iconScreen:qg(t,i.icon_screen,r)}}function Xg(t){return new Map([...eu.map((n)=>[n,t[n]]),...t.ansi.map((n,e)=>[`ansi${e}`,n])])}function _g(t,n,e){if(!Array.isArray(n)||n.length!==nu)yt(t,`meta.signature must name exactly ${nu} palette slots`);let r=Xg(e),i=[],o=[];for(let[s,c]of n.entries()){let u=`meta.signature[${s}]`,h=_t(t,u,c),f=r.get(h);if(f===void 0)yt(t,`${u} ${JSON.stringify(c)} is not a palette slot — use ${eu.join(", ")} or ansi0-ansi15`);i.push(h),o.push(f)}if(new Set(o).size!==o.length)yt(t,"meta.signature slots must resolve to three different colors");return{names:i,colors:o}}function Cg(t,n,e){if(n===void 0)return;if(!e)yt(t,"meta.booru_sites renames meta.booru per site, so it needs meta.booru");if(!n||typeof n!=="object"||Array.isArray(n))yt(t,'meta.booru_sites must be a table of site = "tag" or site = ["tag", ...]');let r={};for(let[i,o]of Object.entries(n)){let s=gt.find((u)=>u.key===i);if(!s)yt(t,`meta.booru_sites.${i} is not a find site — use ${gt.map((u)=>u.key).join(", ")}`);let c=typeof o==="string"?[o]:Array.isArray(o)?o:void 0;if(!c||c.some((u)=>typeof u!=="string"||u===""||/\s/.test(u)))yt(t,`meta.booru_sites.${i} must be one tag or a list of tags, got ${JSON.stringify(o)}`);if(c.length>1&&Number.isFinite(s.tagBudget))yt(t,`meta.booru_sites.${i} takes one tag — ${s.name} searches ${s.tagBudget} tags at a time`);r[i]=c}return r}function xg(t){let e=Bun.TOML.parse(Ni(Oi(t,gn),"utf8")).group;if(!Array.isArray(e)||e.length===0)yt(gn,"needs at least one [[group]] table");return e.map((r)=>{let i=dn(r);return{name:_t(gn,"group.name",i.name),native:i.native===void 0?void 0:_t(gn,"group.native",i.native),lead:_t(gn,"group.lead",i.lead)}})}function Yg(t,n,e,r){let i=Bun.TOML.parse(n),o=dn(i.meta),s=dn(i.colors),c=dn(i.contrast),u=s.ansi;if(!Array.isArray(u)||u.length!==16)yt(t,`colors.ansi must hold exactly 16 colors, got ${Array.isArray(u)?u.length:typeof u}`);let h=_t(t,"meta.name",o.name);if(h!==Ug(t,".toml"))yt(t,`meta.name "${h}" does not match the filename`);if(Wg.has(h))yt(t,`meta.name "${h}" collides with a ttheme subcommand`);if(h.startsWith("-"))yt(t,`meta.name "${h}" would be read as a flag by the ttheme CLI`);let f=o.role;if(f!==void 0&&f!=="default")yt(t,`meta.role must be "default", got ${JSON.stringify(f)}`);let a=_t(t,"meta.group",o.group),l=r.get(a);if(!l)yt(t,`meta.group "${a}" has no [[group]] table in ${gn}`);let g=Ln(t,"colors.background",s.background),d=Ln(t,"colors.foreground",s.foreground),m=Ln(t,"colors.cursor",s.cursor),E=Ln(t,"colors.selection_background",s.selection_background),y=u.map((H,b)=>Ln(t,`colors.ansi[${b}]`,H)),N=_g(t,o.signature,{background:g,foreground:d,cursor:m,selection:E,ansi:y}),k=o.booru===void 0?void 0:_t(t,"meta.booru",o.booru);if(k!==void 0&&/\s/.test(k))yt(t,`meta.booru must be a single booru tag, got ${JSON.stringify(k)}`);let S=Cg(t,o.booru_sites,k),$=Array.isArray(c.waive)?c.waive.map(String):[];if($.length>0&&typeof c.reason!=="string")yt(t,"contrast.waive needs a contrast.reason explaining why");return{name:h,group:a,native:l.native,lead:l.lead===h,order:Number(o.order),role:f,ansiSource:_t(t,"meta.ansi_source",o.ansi_source),...k?{booru:k}:{},...S?{booruSites:S}:{},background:g,foreground:d,cursor:m,selectionBackground:E,ansi:y,signature:N.colors,signatureSlots:N.names,font:Qg(t,i.font,e.font),ghostty:Zg(t,i.ghostty,e.ghostty,{background:g,cursor:m,selectionBackground:E}),waive:$,waiveReason:typeof c.reason==="string"?c.reason:void 0}}function ru(t){let n=Bun.TOML.parse(Ni(Oi(t,Tg),"utf8")),e=xg(t),r=new Map(e.map((s)=>[s.name,s]));if(r.size!==e.length)yt(gn,"group.name must be unique");let i=Ag(t).filter((s)=>s.endsWith(".toml")&&!s.startsWith("_")).map((s)=>Yg(s,Ni(Oi(t,s),"utf8"),n,r)).sort((s,c)=>s.order-c.order);if(new Set(i.map((s)=>s.order)).size!==i.length)throw Error("themes: meta.order must be unique across all themes");for(let s of e){let c=i.filter((u)=>u.group===s.name);if(c.length===0)yt(gn,`group "${s.name}" has no themes`);if(!c.some((u)=>u.name===s.lead))yt(gn,`group "${s.name}" lead "${s.lead}" is not one of its themes`)}return i}function iu(t){return t.filter((n)=>n.role===void 0)}function Re(t){let n=(e,r)=>e<r?-1:e>r?1:0;return[...t].sort((e,r)=>n(e.group.toLowerCase(),r.group.toLowerCase())||n(e.name,r.name))}var pr=["ghostty","kitty","alacritty","wezterm","iterm2","windows-terminal","warp"];var Hi=/# ttheme begin\n[\s\S]*?# ttheme end\n?/;function je(t,n){let e=`# ttheme begin
|
|
17
|
+
${n}
|
|
17
18
|
# ttheme end
|
|
18
|
-
`;if(
|
|
19
|
+
`;if(Hi.test(t))return t.replace(Hi,e);if(t==="")return e;return`${t.replace(/\n*$/,`
|
|
19
20
|
`)}
|
|
20
|
-
${
|
|
21
|
-
`)}function
|
|
21
|
+
${e}`}function Ri(t){if(t.TERM_PROGRAM==="WarpTerminal")return"warp";if(t.GHOSTTY_RESOURCES_DIR||t.TERM_PROGRAM==="ghostty")return"ghostty";if(t.KITTY_WINDOW_ID)return"kitty";if(t.WEZTERM_PANE)return"wezterm";if(t.ALACRITTY_WINDOW_ID)return"alacritty";if(t.ITERM_SESSION_ID||t.TERM_PROGRAM==="iTerm.app")return"iterm2";if(t.TERM_PROGRAM==="Apple_Terminal")return"terminal-app";if(t.WT_SESSION&&!t.TERM_PROGRAM)return"windows-terminal";if(t.TERM?.startsWith("foot"))return"foot";return"unknown"}function uu(t,n){let e=[`command = ${t}/launch-tab.zsh`,"shell-integration = zsh"];if(n)e.push(`theme = ${n}`);return e.push(`config-file = ${t}/ttheme.conf`,`config-file = ?${t}/backgrounds/shown.conf`),e.join(`
|
|
22
|
+
`)}function hu(t){return`source ${t}/ttheme.zsh`}var zg="# ttheme settings — uncomment a line to change it; exported variables win over this file",wr={TTHEME_TAB_PALETTE:{doc:"# new tabs: off keeps the configured terminal theme, seq rotates through the palettes (default off)",default:"off"},TTHEME_ANNOUNCE:{doc:'# the palette notice under "Last login:": 1 shows it, 0 silences it (default 1)',default:"1"},TTHEME_FX:{doc:"# search hint animation: typewriter, decode or glitch (default typewriter)",default:"typewriter"},TTHEME_SORT:{doc:"# series and palettes in ttheme and preview: abc sorts them by name, series keeps the order they were added (default abc)",default:"abc"},TTHEME_FIND_RATING:{doc:"# the ratings find lists, any of safe, questionable and explicit, each booru read in its own rating vocabulary (default safe)",default:"safe"},TTHEME_FIND_BLOCK:{doc:'# the posts find drops by tag: nudity, underwear, both, or none to keep them all (default "nudity underwear")',default:"nudity underwear"},TTHEME_FIND_POSTS:{doc:"# what find lists first: all is every post of the character, cutouts are the transparent ones (default all)",default:"all"},TTHEME_FIND_SOLO:{doc:"# on keeps the danbooru posts tagged solo, the character alone; off lists every post (default on)",default:"on"},TTHEME_FIND_CUTOUTS:{doc:'# the tags find calls a transparent cutout, per site as key=tag,tag pairs — e.g. "konachan=transparent,vector yande=transparent_png" (default the built-in tags)',default:""},TTHEME_FIND_ORDER:{doc:"# the order find lists posts in: fit ranks each page by how well it makes a backdrop, newest or score (default fit)",default:"fit"},TTHEME_FIND_SETS:{doc:"# runs of the same picture at the same size from one uploader: fold shows them as one tile, show lists each (default fold)",default:"fold"},TTHEME_FIND_REMOVE_BG:{doc:"# an opaque picture tried on in find: on cuts the character out with macOS Vision, off leaves it as it is (default on)",default:"on"},TTHEME_FIND_UNBLOCK:{doc:"# when a network blocks a booru by name, 1 sends find through a local proxy that splits the TLS handshake — find offers to turn it on (default 0)",default:"0"},TTHEME_FIND_HOSTS:{doc:'# send a find site somewhere else, as key=https://host pairs — e.g. "danbooru=https://safebooru.donmai.us" (default none)',default:""}};function ji(t,n){let e=`: \${${t}:=${n}}`;return wr[t]?.default===n?`# ${e}`:e}function fu(t){return new RegExp(String.raw`^#? ?: \$\{${t}[^\n]*$`,"m")}function Vg(t,n){if(fu(n).test(t))return t;let e=wr[n];return`${t.replace(/\n*$/,`
|
|
22
23
|
`)}
|
|
23
|
-
${
|
|
24
|
-
${
|
|
25
|
-
`}function
|
|
26
|
-
${
|
|
24
|
+
${e.doc}
|
|
25
|
+
${ji(n,e.default)}
|
|
26
|
+
`}function Pi(){let t=Object.entries(wr).map(([n,e])=>`${e.doc}
|
|
27
|
+
${ji(n,e.default)}`);return`${[zg,...t].join(`
|
|
27
28
|
|
|
28
29
|
`)}
|
|
29
|
-
`}function
|
|
30
|
+
`}function $r(t,n,e){let r=ji(n,e),i=fu(n);if(i.test(t))return t.replace(i,r);return`${t.replace(/\n*$/,`
|
|
30
31
|
`)}
|
|
32
|
+
${r}
|
|
33
|
+
`}function au(t){if(t==="")return Pi();return Object.keys(wr).reduce(Vg,t)}function lu(t,n){return[...t?[`include themes/${t}.conf`]:[],`watcher ${n}`,"window_logo_scale 100","window_logo_alpha 1"].join(`
|
|
34
|
+
`)}var Bg=/^[ \t]*\[general\][ \t]*(?:#.*)?$/m,ou=/^[ \t]*\[/m,su=/^[ \t]*import[ \t]*=/m,Dg=/^[ \t]*general[ \t]*[.=]/m;function td(t){return t?`[general]
|
|
35
|
+
import = ["${t}"]`:""}function br(t,n){let e=t.replace(Hi,""),r=Bg.exec(e);if(!r){let u=e.search(ou),h=u<0?e:e.slice(0,u);if(Dg.test(e)||su.test(h))return;return je(t,td(n))}let i=r.index+r[0].length,o=e.slice(i),s=o.search(ou);if(su.test(s<0?o:o.slice(0,s)))return;let c=n?`import = ["${n}"]
|
|
36
|
+
`:"";return`${e.slice(0,i)}
|
|
37
|
+
# ttheme begin
|
|
38
|
+
${c}# ttheme end${o}`}var cu=/-- ttheme begin\n[\s\S]*?-- ttheme end\n?/,nd=/^return config[ \t]*$/gm;function gu(t){return`dofile(${JSON.stringify(t)})(config)`}function kr(t,n){let e=`-- ttheme begin
|
|
39
|
+
${n}
|
|
40
|
+
-- ttheme end
|
|
41
|
+
`;if(cu.test(t))return t.replace(cu,e);if(t==="")return`local wezterm = require 'wezterm'
|
|
42
|
+
local config = wezterm.config_builder()
|
|
43
|
+
|
|
31
44
|
${e}
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
`),
|
|
36
|
-
`)
|
|
37
|
-
|
|
38
|
-
|
|
45
|
+
return config
|
|
46
|
+
`;let r=[...t.matchAll(nd)].at(-1);if(r?.index===void 0)return;return`${t.slice(0,r.index)}${e}
|
|
47
|
+
${t.slice(r.index)}`}var du="[appearance.themes]";function mu(t){let n=t.findIndex((r)=>r.trim()===du);if(n<0)return;let e=t.findIndex((r,i)=>i>n&&r.trimStart().startsWith("["));return[n,e<0?t.length:e]}function pu(t){let n=t.split(`
|
|
48
|
+
`),e=mu(n);if(!e)return;return n.slice(e[0]+1,e[1]).find((i)=>/^theme\s*=/.test(i))?.replace(/^theme\s*=\s*/,"").trim()}function wu(t){return`{ custom = { name = "${t}", path = "ttheme-${t}.yaml" } }`}function $u(t,n){let e=t.split(`
|
|
49
|
+
`),r=mu(e);if(!r)return n===void 0?t:`${t.replace(/\n*$/,`
|
|
50
|
+
`)}
|
|
51
|
+
${du}
|
|
52
|
+
theme = ${n}
|
|
53
|
+
`;let i=e.findIndex((o,s)=>s>r[0]&&s<r[1]&&/^theme\s*=/.test(o));if(i>=0)e.splice(i,1,...n===void 0?[]:[`theme = ${n}`]);else if(n!==void 0)e.splice(r[0]+1,0,`theme = ${n}`);return e.join(`
|
|
54
|
+
`)}function Gi(t,n,e=[]){for(let c of t)for(let u of[c.name,c.group,c.native??"",c.ansiSource])if(/["$`\\]/.test(u))throw Error(`${c.name}: "${u}" contains a character that breaks zsh quoting`);let r=Math.max(0,...t.map((c)=>c.name.length)),i=(c,u)=>` ${c.name.padEnd(r)} "${u}"`,o=(c)=>c.map((u)=>u.name).join(" "),s=xn(t);return["# Generated by `mise run build` — do not edit.","# Source of truth: themes/*.toml in the ttheme repo.","",`typeset -g TTHEME_VERSION=${nn.version}`,"",'# the palette new tabs open with, which the iTerm2 "ttheme · default" profile wears',`typeset -g TTHEME_STARTUP=${n??""}`,"","# the terminals ttheme is wired into: a picture change reaches every one of them, from whichever runs the shell",`typeset -ga TTHEME_TERMINALS=(${e.join(" ")})`,"","# seed for `ttheme config` when no config.zsh exists yet",`typeset -g TTHEME_CONFIG_TEMPLATE='${Pi().trimEnd().replaceAll("'","'\\''")}'`,"","typeset -gA TTHEME_PALETTE=(",...t.map((c)=>i(c,[c.background,c.foreground,c.cursor,c.selection,...c.ansi].join(" "))),")","","# series order: new tabs cycle through it and TTHEME_SORT=series lists it — the default role stays applyable but unlisted",`typeset -ga TTHEME_ORDER=(${o(s)})`,"","# the same palettes by series name, then palette name: TTHEME_SORT=abc lists them this way",`typeset -ga TTHEME_ABC=(${o(Re(s))})`,"","typeset -gA TTHEME_GROUP=(",...t.map((c)=>i(c,c.group)),")","","# original-language title, rendered dim next to the group","typeset -gA TTHEME_NATIVE=(",...t.filter((c)=>c.native).map((c)=>i(c,c.native??"")),")","","# where each palette's 16 ANSI colors came from","typeset -gA TTHEME_SRC=(",...t.map((c)=>i(c,c.ansiSource)),")",""].join(`
|
|
55
|
+
`)}var Li={id:"shell",emitShared(t){return[{path:"shell/palettes.zsh",content:Gi(t.map(Ei))}]}};var ed=["black","red","green","yellow","blue","magenta","cyan","white"];function bu(t,n){return[` ${t}:`,...ed.map((e,r)=>` ${e}: "${n[r]}"`)]}var Pe={id:"warp",limits:"colors only — no selection color, and Warp paints one theme app-wide",emit(t){let n=[`name: "${t.name}"`,`background: "${t.background}"`,`foreground: "${t.foreground}"`,`accent: "${t.cursor}"`,`cursor: "${t.cursor}"`,`details: ${Vt(t.background)<0.18?"darker":"lighter"}`,"terminal_colors:",...bu("normal",t.ansi.slice(0,8)),...bu("bright",t.ansi.slice(8,16)),""].join(`
|
|
56
|
+
`);return[{path:`warp/themes/ttheme-${t.name}.yaml`,content:n}]}};var ku=(t)=>`[${t.map((n)=>`"${n}"`).join(", ")}]`,Ge={id:"wezterm",limits:"no shaders; OSC repaints per pane, pictures show per window",emit(t){let n=["[metadata]",`name = "${t.name}"`,`origin_url = "${t.ansiSource}"`,"","[colors]",`foreground = "${t.foreground}"`,`background = "${t.background}"`,`cursor_bg = "${t.cursor}"`,`cursor_border = "${t.cursor}"`,`cursor_fg = "${t.background}"`,`selection_bg = "${t.selectionBackground}"`,`selection_fg = "${t.foreground}"`,"",`ansi = ${ku(t.ansi.slice(0,8))}`,`brights = ${ku(t.ansi.slice(8,16))}`,""].join(`
|
|
57
|
+
`),e=[`-- ${t.name} — font settings.`,"-- Merge into your wezterm.lua config table:",`-- local t = require("ttheme.${t.name}")`,`-- config.color_scheme = "${t.name}"`,"-- config.font = t.font","-- config.font_size = t.font_size","return {",` font = require("wezterm").font("${t.font.family}"),`,` font_size = ${t.font.size},`,"}",""].join(`
|
|
58
|
+
`);return[{path:`wezterm/colors/${t.name}.toml`,content:n},{path:`wezterm/config/${t.name}.lua`,content:e}]}},Yn=(t)=>JSON.stringify(t);function Eu(t){return["-- Generated by ttheme — rewritten on every add, remove and default; do not edit.","local wezterm = require 'wezterm'","",`local MODULE = ${Yn(t.path)}`,`local COLORS = ${Yn(t.colors)}`,`local BACKGROUNDS = ${Yn(t.backgrounds)}`,`local STARTUP = ${t.startup?Yn(t.startup):"nil"}`,"local PALETTES = {",...t.palettes.map((n)=>` [${Yn(n.name)}] = ${Yn(n.background)},`),"}","","local X = { left = 'Left', center = 'Center', right = 'Right' }","local Y = { top = 'Top', center = 'Middle', bottom = 'Bottom' }","local SIZE = { cover = 'Cover', contain = 'Contain', stretch = '100%' }","","local function locate(path)"," if path:sub(1, 2) == '~/' then"," return os.getenv('HOME') .. path:sub(2)"," elseif path:sub(1, 1) == '/' or path:match('^%a:[/\\\\]') then"," return path"," end"," return BACKGROUNDS .. '/' .. path","end","","local function read(path, into)"," local f = io.open(path, 'r')"," if not f then"," return false"," end"," for line in f:lines() do"," local key, value = line:match('^%s*([%w%-]+)%s*=%s*(.-)%s*$')"," if key == 'config-file' then"," read(locate((value:gsub('^%?', ''))), into)"," elseif key then"," into[key] = value"," end"," end"," f:close()"," return true","end","","local function layers(palette)"," local color = PALETTES[palette]"," local c = {}"," if not color or not read(BACKGROUNDS .. '/' .. palette .. '.conf', c) then"," return nil, 'none'"," end"," local image = c['background-image'] or ''"," local opacity = tonumber(c['background-image-opacity'] or '1') or 1"," if image == '' or opacity <= 0 then"," return nil, 'none'"," end"," local fit = c['background-image-fit'] or 'contain'"," local position = c['background-image-position'] or 'center'"," local y, x = position:match('^(%a+)-(%a+)$')"," local rep = c['background-image-repeat'] == 'true' and 'Repeat' or 'NoRepeat'"," return {"," { source = { Color = color }, width = '100%', height = '100%' },"," {"," source = { File = locate(image) },"," opacity = opacity,"," width = SIZE[fit],"," height = SIZE[fit],"," horizontal_align = X[x or 'center'],"," vertical_align = Y[y or 'center'],"," repeat_x = rep,"," repeat_y = rep,"," },"," }, table.concat({ color, image, opacity, fit, position, rep }, '|')","end","","local shown = {}","","local function show(window, pane)"," local want = pane:get_user_vars().ttheme_shown"," if not want or want == '' then"," return"," end"," local background, key = layers(want)"," local id = window:window_id()"," if shown[id] == key then"," return"," end"," shown[id] = key"," local overrides = window:get_config_overrides() or {}"," overrides.background = background"," window:set_config_overrides(overrides)","end","","wezterm.on('user-var-changed', function(window, pane, name)"," if name == 'ttheme_shown' then"," show(window, pane)"," end","end)","wezterm.on('update-status', show)","","return function(config)"," local dirs = config.color_scheme_dirs or {}"," table.insert(dirs, COLORS)"," config.color_scheme_dirs = dirs"," if STARTUP then"," config.color_scheme = STARTUP"," end"," wezterm.add_to_config_reload_watch_list(MODULE)","end",""].join(`
|
|
59
|
+
`)}var Mu=["black","red","green","yellow","blue","purple","cyan","white"];function vu(t){return{name:t.name,background:t.background,foreground:t.foreground,cursorColor:t.cursor,selectionBackground:t.selectionBackground,...Object.fromEntries(Mu.map((n,e)=>[n,t.ansi[e]])),...Object.fromEntries(Mu.map((n,e)=>[`bright${n[0]?.toUpperCase()}${n.slice(1)}`,t.ansi[e+8]]))}}function Ki(t,n,e){let r={...n&&e?{profiles:[{updates:n,colorScheme:e}]}:{},schemes:t.map(vu)};return`${JSON.stringify(r,null,2)}
|
|
60
|
+
`}var Le={id:"windows-terminal",limits:"colors only — no kitty graphics, so no pictures; OSC repaints per pane",emit(t){return[{path:`windows-terminal/schemes/${t.name}.json`,content:`${JSON.stringify(vu(t),null,2)}
|
|
61
|
+
`}]},emitShared(t){return[{path:"windows-terminal/ttheme.json",content:Ki(t)}]}};function Qn(t){return[`# ${t.name} — ${t.group}${t.native?` (${t.native})`:""}`,`# ANSI: ${t.ansiSource}`]}var Su=Ke(import.meta.dirname,".."),id=Ke(Su,"themes"),Ji=Ke(Su,"dist"),Er=[we,be,pe,Ge,$e,Le,Pe],od=[Li,Mi],Fu=Er.map((t)=>t.id);async function Mr({only:t}={}){if(typeof Bun>"u")throw Error("ttheme build needs bun — run it from a checkout: bun src/bin.ts build");let n=t&&t.length>0?Er.filter((o)=>t.includes(o.id)):Er,e=ru(id),r=Do(e);if(r.length>0){for(let o of r)console.error(` ✗ ${o.theme} [${o.rule}] ${o.detail}`);throw Error(`${r.length} contrast violation(s). Fix the palette, or waive the rule in its [contrast] section with a reason.`)}if(n.length===Er.length)yu(Ji,{recursive:!0,force:!0});else for(let o of n)yu(Ke(Ji,o.id),{recursive:!0,force:!0});let i=0;for(let o of[...n,...od]){let s=e.flatMap((h)=>o.emit?.(h)??[]),c=o.emitShared?.(e)??[];for(let h of[...s,...c])await Bun.write(Ke(Ji,h.path),h.content),i++;let u=s.length>0?`${e.length} themes${o.limits?` (${o.limits})`:""}`:c.map((h)=>rd(h.path)).join(" ");console.log(` ${o.id.padEnd(16)} ${u}`)}console.log(`
|
|
62
|
+
${e.length} themes (${iu(e).length} in the new-tab rotation) -> ${i} files in dist/`)}import{spawn as Th}from"node:child_process";import{createHash as Wh}from"node:crypto";import{existsSync as ee,mkdirSync as Ce,mkdtempSync as Km,readFileSync as Qh,rmSync as eo,statSync as Jm,writeFileSync as xe}from"node:fs";import{tmpdir as Am}from"node:os";import{dirname as Ar,join as un}from"node:path";import{pathToFileURL as Um}from"node:url";import{execFile as sd}from"node:child_process";import{createHash as Hu}from"node:crypto";import{existsSync as cd,mkdtempSync as ud,readFileSync as Fr,rmSync as hd,statSync as Ru,writeFileSync as ju}from"node:fs";import{homedir as fd,tmpdir as ad}from"node:os";import{join as vr}from"node:path";import{fileURLToPath as ld}from"node:url";import{promisify as gd}from"node:util";var on=gd(sd),yr=67108864,dd=4096,Ti=["image/png","image/jpeg","image/webp","image/gif","image/tiff","image/heic"],md=["text/uri-list","text/plain;charset=utf-8","text/plain"],Ai=[...Ti,"text/uri-list","text/plain"];function pd(t){try{return Ru(t).isFile()}catch{return!1}}function wd(t){let n=[],e="",r="",i=!1;for(let o=0;o<t.length;o++){let s=t[o];if(r==="'")if(s==="'")r="";else e+=s;else if(r==='"')if(s==='"')r="";else if(s==="\\"&&'"\\$`'.includes(t[o+1]??""))e+=t[++o];else e+=s;else if(s==="\\"&&o+1<t.length)e+=t[++o],i=!0;else if(s==="'"||s==='"')r=s,i=!0;else if(/\s/.test(s)){if(i)n.push(e);e="",i=!1}else e+=s,i=!0}if(i)n.push(e);return n}function Iu(t){if(/^file:\/\//i.test(t))try{return ld(t)}catch{return}if(t.startsWith("~/"))return vr(fd(),t.slice(2));return t.startsWith("/")?t:void 0}function Ir(t,n=pd){let e=[];for(let r of t.replace(/\r\n?/g,`
|
|
63
|
+
`).split(`
|
|
64
|
+
`)){let i=Iu(r.trim());if(i&&n(i)){e.push(i);continue}for(let o of wd(r)){if(/^https?:\/\/\S+$/i.test(o)){e.push(o);continue}let s=Iu(o);if(s&&n(s))e.push(s)}}return e}function $d(t){if(t[0]!==255||t[1]!==216)return null;let n=2;while(n+9<t.length){if(t[n]!==255){n++;continue}let e=t[n+1];if(e===255){n++;continue}let r=t[n+2]<<8|t[n+3];if(e>=192&&e<=207&&e!==196&&e!==200&&e!==204)return{height:t[n+5]<<8|t[n+6],width:t[n+7]<<8|t[n+8]};n+=2+r}return null}function Nu(t){let n=Ee(t)?Me(t):$d(t);if(!n)return;return{ext:Ee(t)?"png":"jpg",width:n.width,height:n.height}}async function Sr(t,n){let e=Nu(t);if(e&&e.width*e.height<=Gn)return{bytes:t,...e,source:n};if(process.platform!=="darwin")throw Error(e?`${e.width}×${e.height} is over ${Gn/1e6} megapixels`:"only PNG and JPEG pictures work here");let r=ud(vr(ad(),"ttheme-attach-"));try{let i=vr(r,"in"),o=vr(r,"out.png");ju(i,t);let s=!e||e.width*e.height>Gn?["--resampleHeightWidthMax",String(dd)]:[];await on("sips",["-s","format","png",...s,i,"--out",o]).catch(()=>{throw Error("that is not a picture macOS can read")});let c=new Uint8Array(Fr(o)),u=Nu(c);if(!u)throw Error("that is not a picture macOS can read");return{bytes:c,...u,source:n}}finally{hd(r,{recursive:!0,force:!0})}}async function Wi(t,n){if(/^https?:\/\//i.test(t)){let e=await fetch(t,{headers:{"User-Agent":yi},signal:n});if(!e.ok)throw Error(`${new URL(t).host} answered ${e.status}`);if(Number(e.headers.get("content-length")??0)>yr)throw Error("that picture is over 64 MB");let r=new Uint8Array(await e.arrayBuffer());if(/^text\/html/i.test(e.headers.get("content-type")??""))throw Error(`${new URL(t).host} sent a web page, not a picture — copy the image address instead`);return Sr(r,t)}if(Ru(t).size>yr)throw Error("that picture is over 64 MB");return Sr(new Uint8Array(Fr(t)),t)}var Pu=new Map,Nr={key:"local",name:"local",origin:"file://",moved:!1,cutouts:"",best:"",tagBudget:0,vouched:!0,tunneled:!1,ansi:7,ratings:{safe:new Set,questionable:new Set,explicit:new Set},rate:()=>"",postsUrl:()=>"",countUrl:()=>"",postUrl:()=>"",pageUrl:(t)=>Pu.get(t)??"",parse:()=>[],count:()=>0};function Gu(t){if(/^https?:\/\//i.test(t))return"";return t.split("/").pop()??t}function Lu(t,n){Pu.set(t,n)}function Ku(t){return Number.parseInt(Hu("sha1").update(t).digest("hex").slice(0,8),16)%ln}var bd=`ObjC.import('AppKit')
|
|
65
|
+
function run(argv) {
|
|
66
|
+
const pb = $.NSPasteboard.generalPasteboard
|
|
67
|
+
const files = pb.readObjectsForClassesOptions($([$.NSURL]), $({ NSPasteboardURLReadingFileURLsOnlyKey: true }))
|
|
68
|
+
if (files && files.count > 0) {
|
|
69
|
+
const out = []
|
|
70
|
+
for (let i = 0; i < files.count; i++) out.push(files.objectAtIndex(i).path.js)
|
|
71
|
+
return out.join('\\n')
|
|
72
|
+
}
|
|
73
|
+
for (const type of ['public.png', 'public.tiff', 'public.jpeg', 'public.heic']) {
|
|
74
|
+
const data = pb.dataForType(type)
|
|
75
|
+
if (!data || data.isNil()) continue
|
|
76
|
+
if (type === 'public.png') {
|
|
77
|
+
data.writeToFileAtomically(argv[0], true)
|
|
78
|
+
return argv[0]
|
|
79
|
+
}
|
|
80
|
+
const rep = $.NSBitmapImageRep.imageRepWithData(data)
|
|
81
|
+
if (rep.isNil()) continue
|
|
82
|
+
rep.representationUsingTypeProperties($.NSBitmapImageFileTypePNG, $({})).writeToFileAtomically(argv[0], true)
|
|
83
|
+
return argv[0]
|
|
84
|
+
}
|
|
85
|
+
const web = pb.readObjectsForClassesOptions($([$.NSURL]), $({}))
|
|
86
|
+
if (web && web.count > 0) return web.objectAtIndex(0).absoluteString.js
|
|
87
|
+
const text = pb.stringForType('public.utf8-plain-text')
|
|
88
|
+
return text && !text.isNil() ? text.js : ''
|
|
89
|
+
}`,kd=`Add-Type -AssemblyName System.Windows.Forms,System.Drawing
|
|
90
|
+
$c = [Windows.Forms.Clipboard]
|
|
91
|
+
$f = $c::GetFileDropList(); if ($f.Count) { $f; exit }
|
|
92
|
+
$p = Join-Path $env:TEMP 'ttheme-clipboard.png'
|
|
93
|
+
$s = $c::GetData('PNG'); if ($s -is [IO.MemoryStream]) { [IO.File]::WriteAllBytes($p, $s.ToArray()); $p; exit }
|
|
94
|
+
$i = $c::GetImage(); if ($i) { $i.Save($p, [Drawing.Imaging.ImageFormat]::Png); $p; exit }
|
|
95
|
+
$c::GetText()`;function Ju(){if(process.platform!=="linux")return!1;try{return/microsoft/i.test(Fr("/proc/version","utf8"))}catch{return!1}}async function Ed(t){let n=Boolean(process.env.WAYLAND_DISPLAY),e=n?["wl-paste",["--list-types"]]:["xclip",["-selection","clipboard","-t","TARGETS","-o"]],r=(await on(e[0],e[1])).stdout.split(`
|
|
96
|
+
`).map((s)=>s.trim()),i=(s)=>n?on("wl-paste",["--no-newline","--type",s],{encoding:"buffer",maxBuffer:yr}):on("xclip",["-selection","clipboard","-t",s,"-o"],{encoding:"buffer",maxBuffer:yr});if(r.includes("text/uri-list"))return{text:(await i("text/uri-list")).stdout.toString("utf8")};let o=Ti.find((s)=>r.includes(s));if(o)return ju(t,(await i(o)).stdout),{image:t};return{text:r.some((s)=>s.startsWith("text/plain")||s==="UTF8_STRING")?(await i(r.includes("text/plain")?"text/plain":"UTF8_STRING")).stdout.toString("utf8"):""}}function Qi(){return Boolean(process.env.SSH_CONNECTION||process.env.SSH_TTY)}async function Au(t){if(process.platform==="darwin"){let n=(await on("osascript",["-l","JavaScript","-e",bd,t])).stdout.trim();return n===t?{image:t}:{text:n}}if(Ju()){let n=(await on("powershell.exe",["-NoProfile","-STA","-Command",kd])).stdout.replace(/\r/g,"").trim(),e=await Promise.all(n.split(`
|
|
97
|
+
`).map(async(r)=>/^[A-Za-z]:\\/.test(r)?(await on("wslpath",["-u",r])).stdout.trim():r));return e.length===1&&/ttheme-clipboard\.png$/.test(e[0]??"")?{image:e[0]}:{text:e.join(`
|
|
98
|
+
`)}}if(process.platform==="linux")return Ed(t);throw Error(`reading the clipboard is not supported on ${process.platform}`)}var Md=`ObjC.import('AppKit')
|
|
99
|
+
function run() {
|
|
100
|
+
const pb = $.NSPasteboard.generalPasteboard
|
|
101
|
+
const files = pb.readObjectsForClassesOptions($([$.NSURL]), $({ NSPasteboardURLReadingFileURLsOnlyKey: true }))
|
|
102
|
+
let picture = false
|
|
103
|
+
if (files && files.count > 0) {
|
|
104
|
+
for (let i = 0; i < files.count; i++) picture ||= /\\.(png|jpe?g|gif|webp|heic|tiff?|bmp)$/i.test(files.objectAtIndex(i).path.js)
|
|
105
|
+
} else {
|
|
106
|
+
const types = pb.types.js.map((t) => t.js)
|
|
107
|
+
picture = ['public.png', 'public.tiff', 'public.jpeg', 'public.heic'].some((t) => types.includes(t))
|
|
108
|
+
}
|
|
109
|
+
return pb.changeCount + '\\t' + (picture ? 'picture' : '')
|
|
110
|
+
}`;async function Uu(){if(Qi())return;if(process.platform==="darwin"){let[t="",n=""]=(await on("osascript",["-l","JavaScript","-e",Md])).stdout.trim().split("\t");return{stamp:t,picture:n==="picture"}}if(process.platform==="linux"&&!Ju()){let n=Boolean(process.env.WAYLAND_DISPLAY)?(await on("wl-paste",["--list-types"])).stdout:(await on("xclip",["-selection","clipboard","-t","TARGETS","-o"])).stdout;return{stamp:n,picture:/^image\//m.test(n)}}return}function Tu(t){let n=[],e="",r=0;while(r<t.length){if(t[r]!=="\x1B"){e+=t[r],r++;continue}if(t.startsWith("\x1B[200~",r)){let o=t.indexOf("\x1B[201~",r+6);if(o===-1)return{events:n,keys:e,pending:t.slice(r)};n.push({kind:"paste",text:t.slice(r+6,o)}),r=o+6;continue}if(t.startsWith("\x1B]5522;",r)||t.startsWith("\x1B]72;",r)){let o=[t.indexOf("\x1B\\",r),t.indexOf("\x07",r)].filter((a)=>a!==-1);if(o.length===0)return{events:n,keys:e,pending:t.slice(r)};let s=Math.min(...o),c=t.slice(r+2,s),[u="",h="",...f]=c.split(";");n.push({kind:"osc",code:u,meta:vd(h),payload:f.join(";")}),r=s+(t[s]==="\x07"?1:2);continue}let i=/^\[\?([\d;]*)(\$y|c)/.exec(t.slice(r+1,r+64));if(i){if(i[2]==="c")n.push({kind:"attributes"});else{let[o="0",s="0"]=(i[1]??"").split(";");n.push({kind:"mode",mode:Number(o),value:Number(s)})}r+=1+i[0].length;continue}if(/^(?:\[(?:\?[\d;$]*|2|20|200|201)?|\](?:5|55|552|5522|7|72)?)$/.test(t.slice(r+1)))return{events:n,keys:e,pending:t.slice(r)};e+=t[r],r++}return{events:n,keys:e,pending:""}}function vd(t){let n={};for(let e of t.split(":")){let r=e.indexOf("=");if(r>0)n[e.slice(0,r)]=e.slice(r+1)}return n}var Je=(t)=>Buffer.from(t).toString("base64"),Ui=(t)=>Buffer.from(t,"base64");function Ou(t,n){return n.find((e)=>t.includes(e))}class qi{clipboard=!1;drops=!1;reading;offered=[];dropping;pw=Je(Hu("sha1").update(`${process.pid}:${Date.now()}`).digest("hex"));send;deliver;constructor(t,n){this.send=t,this.deliver=n}start(){let t="\x1B[?2004h";if(this.clipboard)t+="\x1B[?5522h";if(this.drops)t+=`\x1B]72;t=a;${Ai.join(" ")}\x1B\\`;this.send(t)}stop(){this.send(`\x1B[?2004l${this.clipboard?"\x1B[?5522l":""}${this.drops?"\x1B]72;t=A\x1B\\":""}`)}ask(){this.reading={mime:".",chunks:[],pw:"",listing:!0},this.send(`\x1B]5522;type=read:name=${Je("ttheme")}:pw=${this.pw};${Je(".")}\x1B\\`)}take(t){if(t.code==="5522")this.clip(t.meta,t.payload);else if(t.code==="72")this.drop(t.meta,t.payload)}clip(t,n){if(t.type!=="read")return;let e=t.status??"";if(e==="OK"){if(this.reading??={mime:".",chunks:[],pw:t.pw??"",listing:!0},t.pw)this.reading.pw=t.pw;return}let r=this.reading;if(!r)return;if(e==="DATA"){if(r.mime=t.mime?Ui(t.mime).toString("utf8"):r.mime,n)r.chunks.push(Ui(n));return}if(this.reading=void 0,e!=="DONE"){this.deliver({kind:"error",message:e==="EPERM"?"the clipboard read was not allowed":`the terminal answered ${e}`});return}let i=Buffer.concat(r.chunks);if(r.listing){let o=i.toString("utf8").split(/\s+/).filter(Boolean),s=Ou(o,[...Ti,...md]);if(!s){this.deliver({kind:"text",text:""});return}let c=r.pw||this.pw,u=r.pw?"Paste event":"ttheme";this.reading={mime:s,chunks:[],pw:c,listing:!1},this.send(`\x1B]5522;type=read:name=${Je(u)}:pw=${c};${Je(s)}\x1B\\`);return}this.deliver(r.mime.startsWith("image/")?{kind:"bytes",bytes:new Uint8Array(i),source:"clipboard"}:{kind:"text",text:i.toString("utf8")})}drop(t,n){let e=t.t??"";if(e==="m"){if(t.x==="-1"){this.offered=[];return}if(n){this.offered=n.split(" ").filter(Boolean);let c=Ai.filter((u)=>this.offered.includes(u));this.send(`\x1B]72;t=m:o=${c.length>0?1:0};${c.join(" ")}\x1B\\`)}return}if(e==="M"){let c=n?n.split(" ").filter(Boolean):this.offered,u=Ou(c,Ai);if(!u){this.send("\x1B]72;t=r:o=0\x1B\\");return}this.dropping={mimes:c,index:c.indexOf(u)+1,chunks:[]},this.send(`\x1B]72;t=r:x=${this.dropping.index}\x1B\\`);return}let r=this.dropping;if(!r)return;if(e==="R"){this.dropping=void 0,this.send("\x1B]72;t=r:o=0\x1B\\"),this.deliver({kind:"error",message:`the drop failed: ${n.split(":")[0]||"unknown error"}`});return}if(e!=="r"&&e!=="")return;if(n)r.chunks.push(Ui(n));if(t.m==="1"||n)return;this.dropping=void 0;let i=Buffer.concat(r.chunks),o=r.mimes[r.index-1]??"",s;if(o.startsWith("image/"))s={kind:"bytes",bytes:new Uint8Array(i),source:"drop"};else{let c=i.toString("utf8"),u=o==="text/uri-list"?Ir(c).find((h)=>cd(h)):void 0;s=u?{kind:"bytes",bytes:new Uint8Array(Fr(u)),source:u}:{kind:"text",text:c}}this.send("\x1B]72;t=r:o=1\x1B\\"),this.deliver(s)}}import{existsSync as yd,mkdirSync as Sd,readFileSync as Fd,writeFileSync as Id}from"node:fs";import{dirname as Nd,join as Od}from"node:path";var Wu="https://kecan0406.github.io/ttheme/manifest.json",Hd=20000;function Or(t){return Od(t,"ttheme","catalog.json")}function Hr(t,n){let e=Or(t);Sd(Nd(e),{recursive:!0}),Id(e,`${JSON.stringify(n,null,2)}
|
|
111
|
+
`)}function Ut(t){let n=Or(t);if(!yd(n))throw Error(`no catalog at ${n} — run \`ttheme init\` first`);return Qu(Fd(n,"utf8"))}function Qu(t){let n;try{n=JSON.parse(t)}catch{throw Error("catalog is not valid JSON")}let e=n;if(typeof e?.version!=="string"||!Array.isArray(e.palettes))throw Error("catalog has no version or palettes");for(let r of e.palettes)if(typeof r?.name!=="string"||!Array.isArray(r.ansi)||r.ansi.length!==16)throw Error(`catalog entry ${JSON.stringify(r?.name)} is missing name or its 16 ANSI colors`);return e}async function qu(t){let n;try{n=await fetch(t,{signal:AbortSignal.timeout(Hd)})}catch(e){throw Error(`cannot reach the registry at ${t} — ${e instanceof Error?e.message:String(e)}`)}if(!n.ok)throw Error(`registry at ${t} answered ${n.status}`);return Qu(await n.text())}function Zu(t){let n=new Set(t.waived??[]);return or.flatMap((e,r)=>{let i=t.gate?.[r];if(n.has(e.rule)||typeof i!=="number")return[];if(e.min!==void 0&&i<e.min)return[`${e.label} ${i} < ${e.min}`];if(e.max!==void 0&&i>e.max)return[`${e.label} ${i} > ${e.max}`];return[]})}function Rr(t,n){let e=t.find((r)=>r.name===n);if(!e)throw Error(`no palette named ${n} in the catalog — \`ttheme list\` shows what is there`);return e}function Xu(t,n){let e=n.toLowerCase();return t.filter((r)=>[r.name,r.group,r.native??"",r.ansiSource].some((i)=>i.toLowerCase().includes(e)))}function _u(t,n,e){let r=e.toLowerCase(),i=(o)=>o.name===n.name?0:o.group===n.group?1:2;return t.filter((o)=>o.booru?.toLowerCase().includes(r)).map((o,s)=>({p:o,at:s})).sort((o,s)=>i(o.p)-i(s.p)||o.at-s.at).map(({p:o})=>o)}function Cu(t,n){return t.booruSites?.[n]??(t.booru?[t.booru]:[])}import{spawn as Rd}from"node:child_process";var jd=30000,Pd=3,Gd=97,Ld=`ObjC.import('Vision')
|
|
39
112
|
ObjC.import('CoreImage')
|
|
40
113
|
ObjC.import('CoreGraphics')
|
|
41
114
|
function run(argv) {
|
|
@@ -54,104 +127,105 @@ function run(argv) {
|
|
|
54
127
|
$.CIImage.imageWithCVPixelBuffer(buffer), $.NSURL.fileURLWithPath(argv[1]), $.kCIFormatRGBA8,
|
|
55
128
|
$.CGColorSpaceCreateWithName($.kCGColorSpaceSRGB), $({}), error)
|
|
56
129
|
if (!written) throw new Error('write failed')
|
|
57
|
-
}`;function
|
|
58
|
-
`).at(-1)||`osascript exited ${
|
|
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
|
|
130
|
+
}`;function Zi(){return process.platform==="darwin"}function xu(t){return t>=Pd&&t<=Gd}function Yu(t,n,e){return new Promise((r,i)=>{let o=Rd("osascript",["-l","JavaScript","-e",Ld,t,n],{stdio:["ignore","ignore","pipe"],signal:AbortSignal.any([e,AbortSignal.timeout(jd)])}),s="";o.stderr.on("data",(c)=>{s+=c}),o.on("error",i),o.on("close",(c)=>{if(c===0){r();return}i(Error(s.trim().split(`
|
|
131
|
+
`).at(-1)||`osascript exited ${c}`))})})}var At={pitch:25,cols:22,rows:9,height:13},Kn={cols:25,rows:16},Kd=2147483648,Jd=-1073741826,Ad=1600,Ud="\x1B[0m",cn="\x1B[1m",ct="\x1B[2m",Ae="\x1B[31m",sn="\x1B[32m",Tt="\x1B[33m",jr="\x1B[1;34m",Td="\x1B[35m",Wd={A:"up",B:"down",C:"right",D:"left",H:"home",F:"end","1~":"home","7~":"home","4~":"end","8~":"end","5~":"pgup","6~":"pgdn",I:"focus-in",O:"focus-out"};function Bu(t){let n=[],e=0;while(e<t.length){let r=t[e]??"";if(r==="\x1B"){let i=/^(?:\[([0-9;]*)([A-Za-z~])|O([A-Za-z]))/.exec(t.slice(e+1));if(i){n.push(Wd[`${i[1]??""}${i[2]??i[3]??""}`]??"nop"),e+=1+i[0].length;continue}let o=t[e+1]??"";if(/^[a-z]$/.test(o)){n.push(`alt-${o}`),e+=2;continue}n.push("esc"),e++;continue}n.push(r==="\r"||r===`
|
|
132
|
+
`?"enter":r==="\t"?"tab":r==="\x03"?"ctrl-c":r==="\x16"?"ctrl-v":r===""||r==="\b"?"backspace":r),e++}return n}var Du="\x1B]1337;ReportCellSize\x07\x1B[16t",zu="\x1B]1337;ReportCellSize=";function Ci(t){let n=t.indexOf(zu);if(n!==-1){let i=t.slice(n+zu.length),o=[i.indexOf("\x07"),i.indexOf("\x1B\\")].filter((u)=>u!==-1),s=o.length>0?Math.min(...o):-1,c=s===-1?null:/^([\d.]+);([\d.]+);([\d.]+)$/.exec(i.slice(0,s));if(c){let u=Number(c[3]);return{cell:{h:Math.round(Number(c[1])*u),w:Math.round(Number(c[2])*u)},rest:t.slice(0,n)+i.slice(s+(i[s]==="\x07"?1:2))}}}let e=t.indexOf("\x1B[6;"),r=e===-1?null:/^\[6;(\d+);(\d+)t/.exec(t.slice(e+1));if(!r)return null;return{cell:{h:Number(r[1]),w:Number(r[2])},rest:t.slice(0,e)+t.slice(e+1+r[0].length)}}function zn(t,n){return{perRow:Math.max(1,Math.floor((t+1)/At.pitch)),rowsVis:Math.max(1,Math.floor((n-4)/At.height))}}function th(t){return`\x1B_Ga=t,t=f,f=100,i=${t.id},q=2;${Buffer.from(t.path).toString("base64")}\x1B\\`}function nh(t){return`\x1B[${t.row+1};${t.col+1}H\x1B_Ga=p,i=${t.id},p=${t.id},c=${t.cols},r=${t.rows},C=1,z=${t.z},q=2\x1B\\`}function eh(t){return`\x1B_Ga=d,d=I,i=${t},q=2\x1B\\`}function rh(t){return`\x1B[38;2;${jt(t).join(";")}m`}function Xi(t){return`\x1B[48;2;${jt(t).join(";")}m`}function Ct(t){return Array.from(t).length}class Pr{parts=[];cols;constructor(t){this.cols=t}put(t,n,e=""){return this.parts.push({col:t,text:n,sgr:e}),t+Ct(n)}run(t,n){let e=t;for(let[r,i]of n)e=this.put(e,r,i);return e}right(t,n){this.run(t-n.reduce((e,[r])=>e+Ct(r),0),n)}render(){let t="";for(let{col:n,text:e,sgr:r}of this.parts){if(n>=this.cols||n<0)continue;let i=Array.from(e).slice(0,this.cols-n).join("");t+=`\x1B[${n+1}G${r}${i}${r?Ud:""}`}return t}}function ih(t){return t>=1e6?`${(t/1e6).toFixed(1)} MB`:`${Math.max(1,Math.round(t/1000))} KB`}function Qd(t,n){if(!n)return ih(t);return n>=1e6?`${(t/1e6).toFixed(1)}/${(n/1e6).toFixed(1)} MB`:`${Math.round(t/1000)}/${Math.round(n/1000)} KB`}function oh(t){return t.replace(/_\([^)]*\)?$/,"")}function sh(t){return[`${t.reduced?"↓":""}${t.width}×${t.height}`,Math.max(t.width,t.height)<Ad?Tt:ct]}function Ue(t,n,e,r){let i=[...r.keys??[]],o=r.lead,s=r.right,c=()=>{let f=[...o?[Ct(o[0])]:[],...i.map(([l,g])=>Ct(l)+1+Ct(g))];return(r.badge?Ct(r.badge)+4:0)+f.reduce((l,g)=>l+g,0)+3*Math.max(0,f.length-1)+(s?3+Ct(s[0])+1+Ct(s[1]):0)};while(c()>n)if(i.length>2)i.splice(-2,1);else if(s)s=void 0;else if(i.length>1)i.splice(-2,1);else break;if(o&&c()>n){let f=Math.max(0,Ct(o[0])-(c()-n)-1);o=[`${Array.from(o[0]).slice(0,f).join("")}…`,o[1]]}let u=0;if(r.badge)u=t.put(0,` ${r.badge} `,`\x1B[7;1m${e}`)+2;if([...o?[[o]]:[],...i.map(([f,a])=>[[f,cn],[` ${a}`,ct]])].forEach((f,a)=>{u=t.run(u+(a?3:0),f)}),s)t.right(n,[[s[0],cn],[` ${s[1]}`,ct]])}function qd(t,n,e,r,i,o){let{ansi:s,selection:c,cursor:u}=o.colors,h=r<44?3:4;if(r>=56)h=Math.min(7,Math.floor((r+1)/8)-1);let f=e;for(let d=0;d<8;d++)f=(t[n]?.put(f,"▀".repeat(h),rh(s[d]??u)+Xi(s[d+8]??u))??f)+1;let a=["❯ ",sn],l=[[["~/code/demo",jr],[" on ",ct],["main",Td],[" +2",sn],[" ~1",Tt]]];if(l.push([a,["git status -sb",""]]),r>=44)l.push([["## ",""],["main",sn],["...",""],["origin/main",Ae],[" [ahead 1]",Tt]]);if(l.push([[" M",Ae],[" src/main.rs",""]]),l.push([["??",Ae],[" notes.md",""]]),l.push([]),r>=44)l.push([a,["ls",""]]),l.push([["docs",jr],[" ",""],["src",jr],[" ",""],["tests",jr],[" Cargo.toml README.md",""]]),l.push([]);l.push([a,["cargo test",""]]),l.push([[" ✓",sn],[" parses config",""]]);let g=[[" ✗",Ae],[" renders frame",""]];if(r>=44)g.push([" expected ",ct],["3",sn],[", received ",ct],["2",Ae]);l.push(g),l.push([]),l.push([a,["echo ",""],["selected text",Xi(c)],[" ",""],[" ",Xi(u)]]),l.forEach((d,m)=>{let E=n+2+m;if(E<=i)t[E]?.run(e,d)})}function Zd(t,n,e,r,i,o){t[n]?.put(e,`╭${"─".repeat(i-2)}╮`,o);for(let s=n+1;s<n+r-1;s++)t[s]?.put(e,"│",o),t[s]?.put(e+i-1,"│",o);t[n+r-1]?.put(e,`╰${"─".repeat(i-2)}╯`,o)}function _i(t,n=t.site,e=t.siteAnsi){return[` ${n} `,`\x1B[7;${30+e}m`]}function Xd(t){return`${gt[Math.floor(t/ln)]?.name??"local"} ${t%ln}`}function _d(t,n,e){let r=[{name:"all",moved:!1},...gt].flatMap((s,c)=>{let u=`${s.name}${s.moved?"*":""}`,h=s.name===e.site?_i(e,u):[` ${u} `,ct];return c?[[" ",""],h]:[h]}),i=r.reduce((s,[c])=>s+Ct(c),0)<=n,o=t.run(0,i?r:[_i(e)]);if(e.asking!==void 0)t.run(o,[[` ${e.asking} was cut off — this network may block it. turn on the unblock proxy? `,Tt],["y",cn],[" turn on ",ct],["n",cn],[" not now",ct]])}function Cd(t,n,e,r){if(e.editing!==void 0){let c=t.run(0,[["⌕ ",r],[e.editing,""],["█",r]]),u=e.suggest?.length?" ↑↓ pick enter searches":" enter searches";t.put(c,e.editing?u:` a tag, a post url or an id, or drop a picture or ctrl+v — ${e.tag||"esc leaves"}`,ct);return}let i=t.run(0,[["⌕ ",r],[e.tag||"nothing yet — / searches, ctrl+v pastes a picture",e.tag?"":ct]]),o=Pn.filter((c)=>!e.block.includes(c)),s=[e.preset,...e.solo?["solo"]:[],e.order,...e.rating.join("+")==="safe"?[]:[e.rating.join("+")],...o.length>0?[`allows ${o.join("+")}`]:[],...e.unblocked?["unblock"]:[]];if(t.put(i,` ${s.join(" ")}`,ct),e.total>0||!e.searching){let c=[[`${e.tiles.length}/${e.checked}`,""]];if(e.checked<e.total)c.push([` of ${e.total}`,ct]);t.right(n,c)}}function xd(t){if(t.cut==="on")return[[`cut out · ${t.clear}% transparent`,sn]];if(t.cut==="off")return[["opaque · x cuts out",Tt]];if(t.cut==="failed")return[["opaque · no cut-out",Tt]];return[t.clear>0?[`${t.clear}% transparent`,sn]:["opaque",Tt]]}function Vu(t){return t.site==="all"?"any site":t.site}function ch(t){if(t.installing!==void 0)return[`installing ${t.palette} ← ${Xd(t.installing)}`,Tt];if(t.hint)return[t.hint,sn];if(t.error)return[t.error,Tt];if(t.waiting!==void 0)return[`${t.slow??t.site} asked to slow down · ${t.waiting}s`,Tt];if(t.fetching)return[`fetching ${t.fetching.id%ln} · ${Qd(t.fetching.got,t.fetching.size)}`,Tt];if(t.cutting!==void 0)return[`cutting out ${t.cutting%ln}`,Tt];if(t.preparing!==void 0)return[`preparing ${t.preparing%ln}`,Tt];if(t.saved)return[t.saved,sn];if(t.note)return[t.note,ct];return}function Yd(t,n,e,r,i,o){let{perRow:s,rowsVis:c}=zn(e,r);Cd(t[0],e,i,o),_d(t[1],e,i);for(let g=0;g<s*c;g++){let d=i.top*s+g,m=i.tiles[d];if(!m)break;let E=2+Math.floor(g/s)*At.height,y=g%s*At.pitch,N=d===i.focus;if(N)Zd(t,E,y,At.height,At.pitch-1,o);if(m.thumb)n.push({id:m.key,path:m.thumb,row:E+1,col:y+1,cols:At.cols,rows:At.rows,z:-1});if(t[E+10]?.run(y+1,[...i.installed.includes(m.key)?[["✓ ",sn]]:[],...i.site==="all"?[["● ",`\x1B[${30+m.siteAnsi}m`]]:[],[String(m.id),N?cn:""],[" ",""],sh(m)]),m.mates.length>0)t[E+10]?.put(y+At.cols,"≈",o);let k=m.artist?oh(m.artist):m.owner&&`@${m.owner}`;if(k)t[E+11]?.put(y+1,k.slice(0,At.cols-8),ct);let S=[];if(m.score>0)S.push([`★${m.score}`,ct]);if(m.variants>1)S.push([` ×${m.variants}`,o]);if(S.length>0)t[E+11]?.right(y+At.cols+1,S)}let u=i.top*s,h=i.tiles.length-(i.top+c)*s,f=[...u>0?[`↑ ${u} above`]:[],...h>0?[`↓ ${h} more`]:[]];if(f.length>0)t[r-2]?.put(0,f.join(" "),ct);if(!i.searching&&i.tiles.length===0&&!i.error)t[3]?.put(0,i.preset==="cutouts"?`no transparent cutouts of ${i.tag} on ${Vu(i)} — c searches every post, tab tries ${i.nextSite}`:`no posts of ${i.tag} on ${Vu(i)} — tab tries ${i.nextSite}`,ct);let a=t[r-1],l=ch(i);if(i.searching&&i.tiles.length===0&&!l){Ue(a,e,o,{badge:"FIND",lead:[i.preset==="cutouts"?"checking png headers":"fetching posts",ct],right:["esc","back"]});return}Ue(a,e,o,{badge:"FIND",lead:l,keys:i.asking!==void 0?[]:[["←↑↓→","move"],["enter","try on"],["tab","site"],["ctrl+v","picture"],["s","settings"],["/","search"],["?","keys"]],right:i.asking!==void 0?void 0:["esc","back"]})}function zd(t,n,e,r,i,o){let s=i.tiles[i.focus];if(!s)return;let c=i.shown?.id===s.key?i.shown:void 0,u=[_i(i,s.site,s.siteAnsi),[" ",""],[String(s.id),cn],[" ",""],sh(s)];if(s.artist)u.push([` · ${oh(s.artist)}`,""]);if(s.score>0)u.push([` · ★${s.score}`,ct]);if(c)u.push([` · ${ih(c.bytes)}`,ct]);if(s.owner)u.push([` · ${s.owner}`,ct]);if(s.origin)u.push([` · ${s.origin}`,ct]);if(c)u.push([" ",""],...xd(c));if(t[0]?.run(0,u),s.mates.length>0)t[0]?.right(e,[["≈ ",o],[s.mates.join(" "),ct]]);if(qd(t,3,2,e-4,r-2,i),i.shown)n.push({id:Kd+i.shown.id,path:i.shown.path,row:0,col:0,cols:e,rows:r,z:Jd});let h=ch(i);Ue(t[r-1],e,o,{badge:"TRY",lead:h,keys:i.installing===void 0?[["←→","browse"],["enter","install"],...i.shown?.cut==="on"||i.shown?.cut==="off"?[["x","cut out"]]:[],["?","keys"]]:[],right:i.installing===void 0?["esc","grid"]:void 0})}var Vd={grid:[["move","←↑↓→ home end pgup pgdn"],["try on","enter"],["site",`tab all, ${gt.map((t)=>t.name).join(", ")}`],["posts","c cutouts or every post"],["search","/ a tag, a post url or an id"],["your own","ctrl+v or v a picture from the clipboard · drop one on the window or paste its link"],["unfold","space a set of ×N"],["open","o the post page in a browser"],["settings","s rating, block, posts, solo, order, sets, remove bg"],["back","esc returns to preview"],["close","? esc"]],try:[["browse","←→"],["install","enter"],["cut out","x the background off or on, on an opaque picture"],["open","o the post page in a browser"],["your own","ctrl+v or v a picture from the clipboard · drop one on the window"],["grid","esc"],["close","? esc"]]};function Bd(t,n,e,r,i){let o=r.panel??0,s=Math.max(...r.settings.map((l)=>l.label.length)),c=Math.max(...r.settings.map((l)=>l.choices.reduce((g,d)=>g+d.length+(l.multi?6:3),0))),u=Math.min(n-2,Math.max(28,s+c+8)),h=r.settings.length+4,f=Math.floor((n-u)/2),a=Math.max(2,Math.floor((e-h)/2));t[a]?.put(f,`╭─ settings ${"─".repeat(Math.max(0,u-13))}╮`);for(let l=a+1;l<a+h-1;l++)t[l]?.put(f,`│${" ".repeat(u-2)}│`);r.settings.forEach((l,g)=>{let d=t[a+2+g];d.put(f+3,l.label,g===o?cn:ct);let m=f+5+s,E=l.value.split(" ");l.choices.forEach((y,N)=>{let k=E.includes(y),S=l.multi&&g===o&&N===l.cursor?"4;":"",$=l.multi?` ${k?"[x]":"[ ]"} ${y} `:` ${y} `;m=d.put(m,$,k?`\x1B[${S}7;${30+r.siteAnsi}m`:S?`\x1B[4m${ct}`:ct)+1})}),t[a+h-1]?.put(f,`╰${"─".repeat(u-2)}╯`),Ue(t[e-1],n,i,{badge:"SET",keys:[["↑↓","setting"],["←→","value"],["space","toggle"],["enter","save"]],right:["esc","undo"]})}function Dd(t,n,e,r,i){let o=Vd[r.mode],s=Math.min(n-2,50),c=o.length+4,u=Math.floor((n-s)/2),h=Math.max(2,Math.floor((e-c)/2));t[h]?.put(u,`╭─ keys ${"─".repeat(s-9)}╮`);for(let f=h+1;f<h+c-1;f++)t[f]?.put(u,`│${" ".repeat(s-2)}│`);o.forEach(([f,a],l)=>{t[h+2+l]?.put(u+3,f,cn),t[h+2+l]?.put(u+13,a.slice(0,s-16))}),t[h+c-1]?.put(u,`╰${"─".repeat(s-2)}╯`),Ue(t[e-1],n,i,{badge:"KEYS",right:["? esc","close"]})}function tm(t,n,e){let r=n.suggest??[],i=r.map((c)=>c.count>0?String(c.count):c.palette??"0"),o=Math.max(...r.map((c)=>Ct(c.value))),s=Math.max(7,...i.map(Ct));r.forEach((c,u)=>{let h=u===n.pick,f=t[1+u];f?.run(0,[[h?"▸ ":" ",e],[c.value,h?cn+e:""]]),f?.right(2+o+2+s,[[i[u],ct]])})}function uh(t,n,e){let r=Array.from({length:e},()=>new Pr(n)),i=[],o=rh(t.colors.cursor);if(n<Kn.cols||e<Kn.rows)return r[0]?.put(0,"ttheme find",cn+o),r[1]?.put(0,`needs ${Kn.cols}×${Kn.rows} — now ${n}×${e}`),r[2]?.put(0,"esc quits",ct),{lines:r.map((s)=>s.render()),images:i};if(t.mode==="try")zd(r,i,n,e,t,o);else Yd(r,i,n,e,t,o);if(t.mode==="grid"&&t.editing!==void 0&&t.suggest?.length){for(let s=1;s<e-1;s++)r[s]=new Pr(n);return tm(r,t,o),{lines:r.map((s)=>s.render()),images:[]}}if(t.help||t.panel!==void 0){let s=t.mode==="try"?i:[];for(let c=0;c<e;c++)r[c]=new Pr(n);if(t.help)Dd(r,n,e,t,o);else Bd(r,n,e,t,o);return{lines:r.map((c)=>c.render()),images:s}}return{lines:r.map((s)=>s.render()),images:i}}var nm=new Set(["comic","4koma","monochrome","greyscale","sketch","lineart","speech_bubble"]),em=new Set(["scenery","landscape","scenic","no_humans","wide_shot","very_wide_shot"]),rm=0.04,im=0.1,om=0.05,sm=4096;function cm(t){return new Set(t.cutouts.split(/\s+/).map((n)=>n.replace(/^~/,"")).filter(Boolean))}function um(t,n,e,r=0){let{site:i,post:o}=t,s=new Set(o.tags),c=[...cm(i)].some((f)=>s.has(f)),u=Math.min(o.width,o.height),h=o.width>0&&o.height>0?o.width/o.height/(n.w/n.h):1;return(o.solo?2:0)+([...nm].some((f)=>s.has(f))?-3:0)+([...em].some((f)=>s.has(f))?-1.5:0)+2*Math.min(1,u/n.h)+(c?1.5:-Math.min(1.5,Math.abs(Math.log(h))))+(e>0?1.5*Math.log1p(Math.max(0,o.score))/Math.log1p(e):0)+2*r}function Gr(t,n,e=new Map){let r=new Map;for(let{site:i,post:o}of t)r.set(i,Math.max(r.get(i)??0,o.score));return t.map((i,o)=>({pick:i,at:o,score:um(i,n,r.get(i.site)??0,e.get(i.post))})).sort((i,o)=>o.score-i.score||i.at-o.at).map(({pick:i})=>i)}function fh(t){let n=new Map;for(let r of t)n.set(r.site,[...n.get(r.site)??[],r]);let e=[];for(let r=0;e.length<t.length;r++)for(let i of n.values()){let o=i[r];if(o)e.push(o)}return e}function xi(t){let n=t/255;return n<=0.04045?n/12.92:((n+0.055)/1.055)**2.4}function hh(t,n,e){let[r,i,o]=[xi(t),xi(n),xi(e)],s=Math.cbrt(0.4122214708*r+0.5363325363*i+0.0514459929*o),c=Math.cbrt(0.2119034982*r+0.6806995451*i+0.1073969566*o),u=Math.cbrt(0.0883024619*r+0.2817188376*i+0.6299787005*o);return[0.2104542553*s+0.793617785*c-0.0040720468*u,1.9779984951*s-2.428592205*c+0.4505937099*u,0.0259040371*s+0.7827717662*c-0.808675766*u]}function ah(t,n){let e=n.map((s)=>hh(...jt(s))).filter(([,s,c])=>Math.hypot(s,c)>=rm);if(e.length===0)return 0;let r=Math.max(1,Math.floor(Math.sqrt(t.width*t.height/sm))),i=e.map(()=>0),o=0;for(let s=0;s<t.height;s+=r)for(let c=0;c<t.width;c+=r){let u=(s*t.width+c)*4;if(t.data[u+3]<128)continue;o++;let[h,f,a]=hh(t.data[u],t.data[u+1],t.data[u+2]);e.forEach(([l,g,d],m)=>{if(Math.hypot(h-l,f-g,a-d)<im)i[m]=i[m]+1})}if(o===0)return 0;return i.reduce((s,c)=>s+Math.min(1,c/o/om),0)/e.length}import{execFileSync as hm,spawn as fm}from"node:child_process";import{existsSync as xt,mkdirSync as We,readFileSync as Sn,rmSync as Yi,utimesSync as am,writeFileSync as Vn}from"node:fs";import{homedir as Kr}from"node:os";import{dirname as Qe,join as pt}from"node:path";var lm={ghostty:we,kitty:be,alacritty:pe,wezterm:Ge,iterm2:$e,"windows-terminal":Le,warp:Pe},lh="ttheme-default";function Bn(t=process.env.TTHEME_ITERM_SUITE??"com.googlecode.iterm2"){let n=(e,r)=>hm(e,r,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();return{read:()=>{try{return process.platform==="darwin"?n("defaults",["read",t,"Default Bookmark Guid"])||void 0:void 0}catch{return}},write:(e)=>{if(process.platform==="darwin")n("defaults",["write",t,"Default Bookmark Guid","-string",e])},running:()=>{try{return n("pgrep",["-x","iTerm2"])!==""}catch{return!1}}}}function Dn(t){return t.keepTheme?void 0:te(t)}function qe(t,n){if(!t.terminals.includes("iterm2"))return t;let e=n.read();return e&&!e.startsWith("ttheme-")?{...t,itermBase:e}:t}function Ze(t,n){if(!t.terminals.includes("iterm2"))return!1;let e=n.read(),r=Dn(t)?lh:e===lh?t.itermBase:void 0;if(!r||r===e)return!1;return n.write(r),!0}function Dt(){return process.env.XDG_CONFIG_HOME??pt(Kr(),".config")}function gh(t){return pt(t,"Library","Application Support","iTerm2","DynamicProfiles","ttheme.json")}function dh(t){return pt(t,"ttheme","installed.json")}function mn(t){let n=dh(t);if(!xt(n))throw Error(`nothing installed yet at ${n} — run \`ttheme init\` first`);let e=JSON.parse(Sn(n,"utf8"));if(!Array.isArray(e?.palettes)||!Array.isArray(e.terminals))throw Error(`${n} has no palettes or terminals`);return{terminals:e.terminals.filter((r)=>pr.includes(r)),...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 Xe(t,n){let e=dh(t);We(Qe(e),{recursive:!0}),Vn(e,`${JSON.stringify(n,null,2)}
|
|
133
|
+
`)}function Te(t,n){return{name:t.name,group:t.group,...t.native?{native:t.native}:{},lead:t.lead===!0,order:t.order,...t.default?{role:"default"}:{},ansiSource:t.ansiSource,...t.booru?{booru:t.booru}:{},...t.booruSites?{booruSites:t.booruSites}:{},background:t.background,foreground:t.foreground,cursor:t.cursor,selectionBackground:t.selection,ansi:t.ansi,signature:t.signature,signatureSlots:t.signatureSlots,font:n.font,ghostty:{...n.shader?{shader:n.shader}:{},iconGhost:t.cursor,iconScreen:[t.cursor,t.selection,t.background]},waive:t.waived??[]}}function mh(t,n){let e=new Map(t.palettes.map((o)=>[o.name,o])),r=n.filter((o)=>!e.has(o));if(r.length>0)throw Error(`not in the catalog: ${r.join(", ")} — \`ttheme list\` shows what is there`);let i=n.flatMap((o)=>{let s=Zu(e.get(o));return s.length>0?[`${o}: ${s.join(", ")}`]:[]});if(i.length>0)throw Error(`these palettes fail the contrast gate:
|
|
61
134
|
${i.join(`
|
|
62
|
-
`)}`);return
|
|
135
|
+
`)}`);return t.palettes.filter((o)=>n.includes(o.name))}function ph(t,n){let e=t==="wezterm"?"colors":"themes";return(lm[t].emit?.(n)??[]).flatMap((r)=>{let[,i,o]=r.path.split("/");return i===e&&o!==void 0?[{file:o,content:r.content}]:[]})}function Jr(t){return process.platform==="darwin"?pt(t,".warp","themes"):pt(process.env.XDG_DATA_HOME??pt(t,".local","share"),"warp-terminal","themes")}function Lr(t,n,e){if(t==="warp")return Jr(e);return pt(n,t,t==="wezterm"?"colors":"themes")}function gm(t,n){return process.platform==="darwin"?pt(t,".warp","settings.toml"):pt(n,"warp-terminal","settings.toml")}var dm='"dark"',mm="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 pm(t,n,e,r){let i=gm(n,t);if(!xt(i))return;let o=pt(t,"ttheme","warp.base"),s=Sn(i,"utf8"),c=pu(s),u=c?.includes('path = "ttheme-')===!0,h;if(e){if(!u&&!xt(o))We(Qe(o),{recursive:!0}),Vn(o,c??"");h=wu(e)}else{if(!u)return;h=xt(o)&&Sn(o,"utf8")||dm,Yi(o,{force:!0})}let f=$u(s,h);if(f===s)return;if(r)fm(process.execPath,["-e",mm,i,f,s],{detached:!0,stdio:"ignore"}).unref();else Vn(i,f);return i}function wh(t){return pt(t,"ttheme","kitty.py")}function zi(t,n){let e=pt(n,".wezterm.lua");return xt(e)?e:pt(t,"wezterm","wezterm.lua")}function wm(t){return pt(t,"Microsoft","Windows Terminal","Fragments","ttheme","ttheme.json")}function $m(t){return[pt(t,"Packages","Microsoft.WindowsTerminal_8wekyb3d8bbwe","LocalState","settings.json"),pt(t,"Packages","Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe","LocalState","settings.json"),pt(t,"Microsoft","Windows Terminal","settings.json")].filter((n)=>xt(n))}function bm(t){for(let n of t){let e=/"defaultProfile"\s*:\s*"(\{[0-9a-fA-F-]+\})"/.exec(Sn(n,"utf8"))?.[1];if(e)return e}return}function te(t){return t.startup&&t.palettes.includes(t.startup)?t.startup:t.palettes[0]}function km(t,n,e){if(t==="ghostty")return{file:pt(n,"ghostty","config"),body:uu(pt(n,"ttheme"),e)};return{file:pt(n,"kitty","kitty.conf"),body:lu(e,wh(n))}}function Vi(t){return pt(t,"alacritty","alacritty.toml")}function Em(t,n){return n?pt(t,"alacritty","themes",`${n}.toml`):void 0}function $h(t,n,e,r,i){let o=En(t),s=e.map((h)=>Te(h,n)),c=new Map;for(let h of s){let f=kc(o,h.name,i);if(f)c.set(h.name,f)}let u=new Set(xn(e).map((h)=>h.name));return es(s.filter((h)=>u.has(h.name)),c,s.find((h)=>h.name===Dn(r)),r.itermBase)}function ne(t,n=Kr()){let e=mn(t);if(!e.terminals.includes("iterm2"))return;let r=Ut(t),i=gh(n);We(Qe(i),{recursive:!0}),Vn(i,$h(t,r,mh(r,e.palettes),e,n))}function _e(t,n,e,r=Kr()){let i=mh(n,e.palettes),o=[],s=(h,f)=>{if(o.push(h),xt(h)&&Sn(h,"utf8")===f)return!1;return We(Qe(h),{recursive:!0}),Vn(h,f),!0},c=Dn(e);for(let h of e.terminals){if(h==="iterm2"){s(gh(r),$h(t,n,i,e,r));continue}if(h==="windows-terminal"){if(e.wtHome){let d=$m(e.wtHome),m=i.map((y)=>Te(y,n)),E=Ki(m,e.wtProfile??bm(d),c);if(s(wm(e.wtHome),E)){let y=new Date;for(let N of d)am(N,y,y)}}continue}let f=c!==void 0&&h==="warp"&&!xt(pt(Jr(r),`ttheme-${c}.yaml`)),a=h==="warp"?pm(t,r,c,f):void 0;for(let d of i)for(let{file:m,content:E}of ph(h,Te(d,n)))s(pt(Lr(h,t,r),m),E);if(h==="warp"){if(a)o.push(a);continue}if(h==="wezterm"){let d=pt(t,"ttheme","wezterm.lua");s(d,Eu({path:d,colors:Lr("wezterm",t,r),backgrounds:En(t),...c?{startup:c}:{},palettes:i.map((y)=>Te(y,n))}));let m=zi(t,r),E=kr(xt(m)?Sn(m,"utf8"):"",gu(d));if(E!==void 0)s(m,E);continue}if(h==="alacritty"){let d=Vi(t),m=br(xt(d)?Sn(d,"utf8"):"",Em(t,c));if(m!==void 0)s(d,m);continue}if(h==="kitty")s(wh(t),rs({themes:Lr("kitty",t,r),backgrounds:En(t)}));let{file:l,body:g}=km(h,t,c);s(l,je(xt(l)?Sn(l,"utf8"):"",g))}let u=pt(t,"ttheme","palettes.zsh");return We(Qe(u),{recursive:!0}),Vn(u,Gi(i,c,e.terminals)),o.push(u),Yi(`${u}.zwc`,{force:!0}),o}function Bi(t,n,e,r,i=Kr()){let o=[];for(let s of e)for(let c of n.palettes.filter((u)=>r.includes(u.name)))for(let{file:u}of ph(s,Te(c,n))){let h=pt(Lr(s,t,i),u);if(xt(h))Yi(h,{force:!0}),o.push(h)}return o}import{mkdirSync as vh,readFileSync as yh,writeFileSync as Sh}from"node:fs";import{dirname as Fh}from"node:path";import{isMainThread as Sm,parentPort as Ih,Worker as Fm}from"node:worker_threads";var Mm=/(?:^|[^0-9a-f])([0-9a-f]{32})(?:[^0-9a-f]|$)/i,vm=[[/yande\.re\/post\/show\/(\d+)/,"yande"],[/konachan\.(?:com|net)\/post\/show\/(\d+)/,"konachan"],[/danbooru\.donmai\.us\/(?:posts|post\/show)\/(\d+)/,"danbooru"]];function Di(t){let n=/(\d+)_p(\d+)/.exec(t.source);return[...t.md5?[`md5:${t.md5}`]:[],...n&&t.source.includes("pximg")?[`pixiv:${n[1]}_p${n[2]}`]:[]]}function bh(t,n){let e=Mm.exec(n.source)?.[1]?.toLowerCase();return[`post:${t.key}:${n.id}`,...n.md5?[`md5:${n.md5}`]:[],...e&&e!==n.md5?[`md5:${e}`]:[],...vm.flatMap(([r,i])=>{let o=r.exec(n.source)?.[1];return o?[`post:${i}:${Number(o)}`]:[]}),...n.family?[`family:${t.key}:${n.family}`]:[]]}function kh(t,n){let e=t.owner||t.artist;return e!==""&&e===(n.owner||n.artist)&&t.width===n.width&&t.height===n.height}function Eh(t){let r=[];for(let o=0;o<8;o++){let s=Math.floor(o*t.height/8),c=Math.max(s+1,Math.floor((o+1)*t.height/8));for(let u=0;u<9;u++){let h=Math.floor(u*t.width/9),f=Math.max(h+1,Math.floor((u+1)*t.width/9)),a=0;for(let l=s;l<c;l++)for(let g=h;g<f;g++){let d=(l*t.width+g)*4,m=t.data[d+3]/255,E=0.299*t.data[d]+0.587*t.data[d+1]+0.114*t.data[d+2];a+=E*m+255*(1-m)}r.push(a/((f-h)*(c-s)))}}let i=0n;for(let o=0;o<8;o++)for(let s=0;s<8;s++)i=i<<1n|(r[o*9+s]>r[o*9+s+1]?1n:0n);return i.toString(16).padStart(16,"0")}function ym(t,n){let e=BigInt(`0x${t}`)^BigInt(`0x${n}`),r=0;while(e>0n)r+=Number(e&1n),e>>=1n;return r}function Mh(t,n){if(t.width<=0||t.height<=0||n.width<=0||n.height<=0)return!1;return Math.abs(Math.log(t.width/t.height/(n.width/n.height)))<0.01&&ym(t.hash,n.hash)<=2}var Im={thumb:"tile",match:"tile",show:"view",backdrop:"view"};function Nm(t){let n=cc(new Uint8Array(yh(t.from)),Gn);if(t.job==="backdrop")return Nc(t.home,t.colors,t.tone,n,{...t.origin,bytes:new Uint8Array(yh(t.source))},t),0;if(t.job==="match")return{match:ah(n,t.colors),hash:Eh(n)};if(t.job==="thumb")return vh(Fh(t.to),{recursive:!0}),Sh(t.to,_n(hc(n,t.width,t.height))),0;let e=ve(n);return vh(Fh(t.to),{recursive:!0}),Sh(t.to,_n(bc(n,t.colors,t.tone,t.width,t.height))),e}function Om(t){t.on("message",(n)=>{try{t.postMessage({id:n.id,value:Nm(n)})}catch(e){t.postMessage({id:n.id,error:e instanceof Error?e.message:String(e)})}})}class Nh{worker;next=1;waiting=new Map;send(t){let n=this.next++;return new Promise((e,r)=>{let i=this.open();this.waiting.set(n,{ok:e,no:r}),i.ref(),i.postMessage({...t,id:n})})}close(){this.worker?.terminate(),this.worker=void 0,this.drop(Error("renderer closed"))}open(){if(this.worker)return this.worker;let t=new Fm(import.meta.filename);t.unref(),t.on("message",({id:e,value:r,error:i})=>{let o=this.waiting.get(e);if(this.waiting.delete(e),this.waiting.size===0)t.unref();if(i!==void 0)o?.no(Error(i));else o?.ok(r)});let n=(e)=>{if(this.worker===t)this.worker=void 0;this.drop(e instanceof Error?e:Error("renderer stopped"))};return t.on("error",n),t.on("exit",()=>n(void 0)),this.worker=t,t}drop(t){for(let n of this.waiting.values())n.no(t);this.waiting.clear()}}class to{lines=new Map;run(t){let n=Im[t.job],e=this.lines.get(n);if(!e)e=new Nh,this.lines.set(n,e);return e.send(t)}close(){for(let t of this.lines.values())t.close();this.lines.clear()}}if(!Sm&&Ih)Om(Ih);import{connect as Hm,createServer as Rm}from"node:net";var jm=20,Oh=22;function no(t){let n=new Uint8Array(t.reduce((r,i)=>r+i.length,0)),e=0;for(let r of t)n.set(r,e),e+=r.length;return n}function Pm(t,n=jm){let e=t.subarray(5);if(t[0]!==Oh||e.length<2)return[t];let r=Math.max(1,Math.min(n,e.length-1)),i=(o)=>no([Uint8Array.from([t[0],t[1],t[2],o.length>>8,o.length&255]),o]);return[i(e.subarray(0,r)),i(e.subarray(r))]}function Gm(t,n,e,r){let i=Hm(e,n,()=>{i.setNoDelay(!0),t.write(`HTTP/1.1 200 Connection Established\r
|
|
63
136
|
\r
|
|
64
|
-
`);let
|
|
137
|
+
`);let o=r,s=!1,c=(u)=>{if(s){i.write(u);return}if(o=no([o,u]),o.length<5)return;let h=o[3]*256+o[4];if(o[0]!==Oh){s=!0,i.write(o);return}if(o.length<5+h)return;s=!0;let[f,a]=Pm(o.subarray(0,5+h));i.write(f),setTimeout(()=>{if(a)i.write(a);i.write(o.subarray(5+h))},10)};if(t.on("data",c),o.length>0){let u=o;o=new Uint8Array(0),c(u)}i.pipe(t)});i.on("error",()=>t.destroy()),i.on("close",()=>t.destroy()),t.on("error",()=>i.destroy()),t.on("close",()=>i.destroy())}function Lm(t){t.setNoDelay(!0);let n=new Uint8Array(0),e=(r)=>{n=no([n,r]);let i=Buffer.from(n).toString("latin1"),o=i.indexOf(`\r
|
|
65
138
|
\r
|
|
66
|
-
`);if(
|
|
139
|
+
`);if(o===-1)return;t.off("data",e);let s=/^CONNECT ([^ :]+):(\d+)/.exec(i);if(!s){t.end(`HTTP/1.1 405 Method Not Allowed\r
|
|
67
140
|
\r
|
|
68
|
-
`);return}
|
|
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
|
|
71
|
-
`),0;return
|
|
72
|
-
`),0}if(
|
|
73
|
-
`),0}if(
|
|
74
|
-
`),f=!1;for(let
|
|
75
|
-
`){if(
|
|
76
|
-
`){if(i&&
|
|
77
|
-
`)}var
|
|
78
|
-
`),
|
|
79
|
-
`),
|
|
80
|
-
`),i=Math.max(
|
|
81
|
-
`).map((u,
|
|
82
|
-
`)}function
|
|
83
|
-
`),
|
|
84
|
-
`).length-1;this.output.write(
|
|
85
|
-
`);this.output.write(o
|
|
86
|
-
`).slice(
|
|
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
|
-
`?`${
|
|
89
|
-
${
|
|
90
|
-
`),this._cursor++,!1);let
|
|
91
|
-
`&&(this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--),!0):(this.#
|
|
92
|
-
`),this._cursor++,!1)}constructor(
|
|
93
|
-
`);E.push(
|
|
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)}
|
|
141
|
+
`);return}Gm(t,s[1],Number(s[2]),n.subarray(o+4))};t.on("data",e),t.on("error",()=>t.destroy())}function Hh(){let t=Rm(Lm);return new Promise((n,e)=>{t.once("error",e),t.listen(0,"127.0.0.1",()=>{n({port:t.address().port,close:()=>{t.close(),t.unref()}})})})}var re=[{name:"TTHEME_FIND_RATING",label:"rating",choices:Ie,multi:{read:gr}},{name:"TTHEME_FIND_BLOCK",label:"block",choices:Pn,multi:{read:dr,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"]},...Zi()?[{name:"TTHEME_FIND_REMOVE_BG",label:"remove bg",choices:["on","off"]}]:[]];function Tm(t,n){if(t.multi)return t.multi.read(n).join(" ")||t.multi.none;return t.choices.find((e)=>e===n)??t.choices[0]}var Wm=["fit","newest","score"];function Rh(t){return Wm.find((n)=>n===t)??"fit"}function Qm(t){return t.length>=2&&!/^\d+$/.test(t)&&!t.includes("://")&&!/^[\w.]+:\d+$/.test(t)}var jh=12,qm=4,Zm=150,Ph=12,Xm=2,_m=150,Cm=30,xm=4000,Ym=8000,Gh=/\.(png|jpe?g|gif|webp|heic|tiff?|bmp)$/i,zm=process.platform==="win32"?"alt+v":"ctrl+v",Lh=process.platform==="darwin"?"ctrl+shift+cmd+4 copies a screenshot":"copy a picture first",Vm=1280,Kh=2,Bm=3,Dm=8;function Ur(t,n){return{key:t,groups:[],sources:[],queue:[],rounds:0,roundOf:new Map,last:new Map,kin:new Map,kindred:new Map,shapes:[],seen:new Set,same:new Map,checked:0,total:0,focus:0,top:0,searching:n}}function ie(t){if(!(t instanceof Error))return String(t);if(t instanceof AggregateError&&t.errors[0])return ie(t.errors[0]);if(t.cause)return ie(t.cause);let n=t.code;if(typeof n==="string")return n;let e=(t.message||t.name).split(".")[0]??"";return e.length>56?`${e.slice(0,55)}…`:e}function ro(t,n){return`${t}: ${ie(n)}`}function Jh(t){return t.width*t.height}function Ah(t){return`${t.id}-${Wh("sha1").update(t.preview).digest("hex").slice(0,8)}`}function tp(t){let n=t.lastIndexOf("\x1B");return n!==-1&&/^\[?[0-9;]*$/.test(t.slice(n+1))}function io(t,n){try{return JSON.parse(Qh(un(yn(t),n),"utf8"))}catch{return{}}}function oo(t,n,e){Ce(yn(t),{recursive:!0}),xe(un(yn(t),n),`${JSON.stringify(e)}
|
|
142
|
+
`)}class qh{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(re.map((t)=>[t.name,Tm(t,process.env[t.name])]));direction=1;prefetching=0;inflight=new Map;owners=new Map;probed=new Map;unsaved=new Set;thumbQueue=[];thumbing=0;clarity=new Map;renders=new to;sent=new Map;placed=new Map;current;fetch;settle;partial;suggestTimer;suggesting;input="";typed="";grabber=new qi((t)=>this.write(t),(t)=>void this.got(t));featureWait;noticeTimer;peekTimer;peeked;attaching;probeWait;done;dirty=!1;unblock=!1;scratch=Km(un(Am(),"ttheme-find-"));home;catalog;entry;constructor(t,n,e,r){this.home=t,this.catalog=n,this.entry=e,this.tone=fr(e,e.signatureSlots),this.view={palette:e.name,tag:r,site:this.tabName,siteAnsi:this.tabAnsi,nextSite:this.nextTabName,preset:this.setting("TTHEME_FIND_POSTS")==="all"?"all":"cutouts",order:Rh(this.setting("TTHEME_FIND_ORDER")),solo:this.setting("TTHEME_FIND_SOLO")==="on",rating:gr(this.setting("TTHEME_FIND_RATING")),block:dr(this.setting("TTHEME_FIND_BLOCK")),sets:this.setting("TTHEME_FIND_SETS")==="show"?"show":"fold",unblocked:process.env.TTHEME_FIND_PROXY!==void 0,settings:re.map((i)=>({label:i.label,choices:[...i.choices],value:this.setting(i.name),multi:i.multi&&{none:i.multi.none},cursor:0})),colors:{cursor:e.cursor,selection:e.selection,ansi:e.ansi},tiles:[],installed:[],checked:0,total:0,searching:r!=="",focus:0,top:0,mode:"grid",help:!1,editing:r===""?"":void 0},this.board=Ur(this.boardKey,r!==""),this.boards.set(this.board.key,this.board)}get signal(){return this.session.signal}get site(){return this.tab===0?void 0:gt[this.tab-1]}get sites(){return this.site?[this.site]:gt}get tabName(){return this.site?.name??"all"}get tabAnsi(){return this.site?.ansi??qm}get nextTabName(){let t=(this.tab+1)%(gt.length+1);return t===0?"all":gt[t-1].name}frame(){return{w:this.cols*(this.cell.w||10),h:this.rows*(this.cell.h||20)}}setting(t){return this.values.get(t)}get boardKey(){return`${this.site?.key??"all"}|${this.view.preset}|${this.view.order}`}origPath(t,n,e){return un(yn(t),"orig",`${n}.${e}`)}previewPath(t){return un(yn(t.site),"thumb",`${Ah(t.post)}.${Ne(t.post.preview)}`)}tileOf(t,n){let{site:e,post:r}=t,i=rn(e,r.id),o=He(r)??r;return{id:r.id,key:i,site:e.name,siteAnsi:e.ansi,width:o.width,height:o.height,reduced:o!==r,owner:r.owner,artist:e===Nr?Gu(r.source):r.artist,score:r.score,variants:n,origin:Fi(r.source),mates:this.owners.get(e.key)?.get(r.owner)??[],thumb:this.thumbPath.get(i)}}show(){let t=this.view,n=this.board;t.tiles=n.groups.flatMap((e)=>e.open?e.posts.map((r)=>this.tileOf(r,0)):[this.tileOf(e.posts[0],e.posts.length)]),t.checked=n.checked,t.total=n.total,t.searching=n.searching,t.note=n.note,t.focus=Math.max(0,Math.min(n.focus,t.tiles.length-1)),t.top=n.top}syncSite(){let t=this.view;t.site=this.tabName,t.siteAnsi=this.tabAnsi,t.nextSite=this.nextTabName}async run(){let{stdin:t,stdout:n}=process;t.setRawMode(!0),t.resume(),t.on("data",this.onData),n.on("resize",this.onResize),this.write("\x1B[?25l\x1B[?7l\x1B[H\x1B[K\x1B[2H\x1B[J\x1B[H");let e=new Promise((s)=>{this.done=s}),r=setInterval(this.onClock,250),i=await this.probe();if(i){if(this.cell=i,this.view.tag)this.search()}else this.view.searching=!1,this.view.error="this terminal does not report its cell size — find needs kitty graphics";await this.features(),this.grabber.start(),this.write("\x1B[?1004h"),this.peek(),this.draw();let o=await e;return this.grabber.stop(),this.write("\x1B[?1004l"),this.attaching?.abort(),clearTimeout(this.noticeTimer),clearTimeout(this.peekTimer),this.session.abort(),this.fetch?.abort(),clearTimeout(this.settle),clearTimeout(this.partial),this.quietSuggest(),clearInterval(r),t.off("data",this.onData),n.off("resize",this.onResize),this.write("\x1B_Ga=d,d=A,q=2\x1B\\\x1B[H\x1B[K\x1B[2H\x1B[J\x1B[H"),t.setRawMode(!1),t.pause(),this.saveProbes(),this.renders.close(),eo(this.scratch,{recursive:!0,force:!0}),Cc(),o}write(t){process.stdout.write(t)}get saved(){return this.view.saved}finish(t){this.done?.(t===2&&this.saved?0:t)}probe(){return new Promise((t)=>{let n=setTimeout(()=>{this.probeWait=void 0,t(null)},1000);this.probeWait=(e)=>{clearTimeout(n),this.probeWait=void 0,t(e)},this.write(Du)})}onData=(t)=>{this.input+=t.toString("utf8");for(let e=Ci(this.input);e;e=Ci(this.input))this.input=e.rest,this.probeWait?.(e.cell);if(this.probeWait)return;let n=Tu(this.input);if(this.input=n.pending,this.view.editing===void 0&&n.keys.length>8&&/^(?:\/|~\/|file:|https?:)/.test(n.keys))this.pasted(n.keys),n.keys="";this.typed+=n.keys;for(let e of n.events)this.inbound(e);if(clearTimeout(this.partial),tp(this.typed)){this.partial=setTimeout(this.flushKeys,Cm);return}this.flushKeys()};flushKeys=()=>{let t=Bu(this.typed);this.typed="";for(let n of t)this.key(n)};features(){if(process.env.TMUX)return Promise.resolve();return new Promise((t)=>{let n=setTimeout(()=>{this.featureWait=void 0,t()},500);this.featureWait=()=>{clearTimeout(n),this.featureWait=void 0,t()},this.write("\x1B[?5522$p\x1B]72;t=q\x1B\\\x1B[c")})}inbound(t){if(t.kind==="mode"){if(t.mode===5522)this.grabber.clipboard=t.value!==0&&t.value!==4;return}if(t.kind==="attributes"){this.featureWait?.();return}if(t.kind==="osc"){if(t.code==="72"&&t.meta.t==="q"){this.grabber.drops=!0;return}this.grabber.take(t);return}this.pasted(t.text)}pasted(t){let n=this.view;if(n.editing!==void 0&&t.trim()!==""&&!this.picture(t)){n.editing+=t.replace(/[\r\n]+/g," "),this.suggest(),this.draw();return}if(n.installing!==void 0||n.asking!==void 0||n.panel!==void 0||n.help)return;if(t.trim()===""){this.fromClipboard();return}this.attach(t)}picture(t){let n=t.trim();if(/^https?:\/\/\S+$/i.test(n))return!mr(n,this.site??gt[0]);return Ir(n).length>0}async got(t){if(t.kind==="error"){this.notice(t.message);return}if(t.kind==="text"){if(t.text.trim()===""){this.notice(`no picture on the clipboard — ${Lh}`);return}this.pasted(t.text);return}await this.bring(()=>Sr(t.bytes,t.source))}notice(t,n=xm){let e=this.view;e.error=t,clearTimeout(this.noticeTimer),this.noticeTimer=setTimeout(()=>{if(e.error===t)e.error=void 0,this.draw()},n),this.draw()}async peek(){let t=this.view,n;try{n=await Uu()}catch{return}if(!n||n.stamp===this.peeked)return;if(this.peeked=n.stamp,!n.picture||t.installing!==void 0||t.asking!==void 0)return;t.hint=`picture on the clipboard · ${zm} uses it`,clearTimeout(this.peekTimer),this.peekTimer=setTimeout(()=>{t.hint=void 0,this.draw()},Ym),this.draw()}async fromClipboard(){let t=this.view;if(Qi()){if(this.grabber.clipboard){this.grabber.ask();return}this.notice("over ssh the clipboard is not here — drop the file");return}let n;try{n=await Au(un(this.scratch,`clipboard-${Date.now()}.png`))}catch(r){this.notice(`could not read the clipboard: ${ie(r)}`);return}if(clearTimeout(this.peekTimer),t.hint=void 0,"image"in n){await this.bring(async(r)=>({...await Wi(n.image,r),source:"clipboard"}));return}let e=n.text.trim();if(!e){this.notice(`no picture on the clipboard — ${Lh}`);return}if(this.picture(e)){await this.attach(e);return}if(t.editing===void 0)t.editing="";this.pasted(e)}async attach(t){let n=t.trim();if(/^https?:\/\//i.test(n)){let i=mr(n,this.site??gt[0]);if(i){await this.jump(i.site,i.id);return}}let[e,...r]=Ir(n).sort((i,o)=>Number(!Gh.test(i))-Number(!Gh.test(o)));if(!e){this.notice("nothing to use in that — drop a picture, or paste one or its link");return}await this.bring((i)=>Wi(e,i),r.length)}async bring(t,n=0){let e=this.view;this.attaching?.abort();let r=new AbortController;this.attaching=r,e.error=void 0,e.saved=void 0,e.note="reading the picture…",this.draw();let i;try{i=await t(AbortSignal.any([r.signal,this.signal]))}catch(l){if(!r.signal.aborted)e.note=void 0,this.notice(ie(l),8000);return}if(r.signal.aborted)return;e.note=n>0?`the first picture of ${n+1} — drop one at a time to try the others`:void 0,this.quietSuggest(),e.editing=void 0,e.suggest=void 0,e.pick=void 0;let o=Ku(i.bytes);Lu(o,i.source);let s=this.origPath(Nr,o,i.ext);Ce(Ar(s),{recursive:!0}),xe(s,i.bytes);let c=Um(s).href,u={id:o,file:c,width:i.width,height:i.height,ext:i.ext,preview:c,owner:"",artist:"",score:0,rating:"s",md5:Wh("md5").update(i.bytes).digest("hex"),source:i.source,tags:[],solo:void 0,family:0,smaller:[]},h={site:Nr,post:u},f=this.previewPath(h);Ce(Ar(f),{recursive:!0}),xe(f,i.bytes),++this.gen,this.current=void 0,e.shown=void 0;let a=Ur(`local|post:${o}`,!1);this.board=a,this.boards.set(a.key,a),this.single(a,h)}single(t,n){t.searching=!1,this.posts.set(rn(n.site,n.post.id),n),t.groups=[{posts:[n],open:!1}],t.checked=1,t.total=1,this.thumbQueue.push(n),this.thumbs(),this.view.mode="try",this.show(),this.select(),this.draw()}onClock=()=>{let t=this.sites.reduce((r,i)=>Mn(i)>Mn(r)?i:r),n=Math.ceil((Mn(t)-Date.now())/1000),e=n>0?n:void 0;if(e!==this.view.waiting)this.view.waiting=e,this.view.slow=t.name,this.draw()};onResize=()=>{if(this.cols=process.stdout.columns||this.cols,this.rows=process.stdout.rows||this.rows,this.scroll(),this.view.mode==="try"&&this.current)this.reveal();this.pump(),this.draw()};key(t){let n=this.view;if(t==="ctrl-c"){this.finish(2);return}if(n.installing!==void 0)return;if(n.asking!==void 0){this.askKey(t);return}if(t==="focus-in"){this.peek();return}if(t==="focus-out"||t==="nop")return;if((t==="ctrl-v"||t==="alt-v")&&n.panel===void 0){this.fromClipboard();return}if(n.editing!==void 0){this.editKey(t);return}if(n.panel!==void 0){this.panelKey(t);return}if(n.help){if(t==="?"||t==="esc")n.help=!1,this.draw();return}if(this.cols<Kn.cols||this.rows<Kn.rows){if(t==="esc")this.finish(2);return}if(t==="?"){n.help=!0,this.draw();return}if(n.mode==="try"){this.tryKey(t);return}this.gridKey(t)}gridKey(t){let n=this.view,{perRow:e,rowsVis:r}=zn(this.cols,this.rows),o={left:-1,right:1,up:-e,down:e,pgup:-e*r,pgdn:e*r,home:-n.focus,end:n.tiles.length}[t];if(o!==void 0){this.focus(n.focus+o);return}if(t==="enter"&&n.tiles[n.focus]){n.mode="try",n.error=void 0,this.select();return}if(t==="v"){this.fromClipboard();return}if(t==="c"){n.preset=n.preset==="cutouts"?"all":"cutouts",this.turn();return}if(t==="tab"){this.tab=(this.tab+1)%(gt.length+1),this.syncSite(),this.turn();return}if(t==="/"){n.editing="",this.draw();return}if(t===" "){this.unfold();return}if(t==="o"){this.openPage();return}if(t==="s"){n.panel=0,this.draw();return}if(t==="esc")this.finish(2)}panelKey(t){let n=this.view,e=n.panel??0,r=n.settings[e];if(t==="up"||t==="down"){n.panel=Math.max(0,Math.min(n.settings.length-1,e+(t==="up"?-1:1))),this.draw();return}if((t==="left"||t==="right")&&r){let i=t==="left"?-1:1;if(r.multi)r.cursor=(r.cursor+i+r.choices.length)%r.choices.length;else{let o=r.choices.indexOf(r.value);r.value=r.choices[(o+i+r.choices.length)%r.choices.length]}this.draw();return}if(t===" "&&r?.multi){let i=r.value.split(" "),o=r.choices.filter((c,u)=>u===r.cursor?!i.includes(c):i.includes(c)),s=r.multi.none;if(o.length>0||s!==void 0)r.value=o.length>0?o.join(" "):s,this.draw();return}if(t==="esc"){n.settings.forEach((i,o)=>{i.value=this.setting(re[o]?.name??"")}),n.panel=void 0,this.draw();return}if(t==="enter"||t==="alt-c")n.panel=void 0,this.adopt()}adopt(){let t=this.view,n=re.map((r)=>this.setting(r.name));t.settings.forEach((r,i)=>{let o=re[i];if(o)this.values.set(o.name,r.value)});let e=re.filter((r,i)=>this.setting(r.name)!==n[i]);if(e.length===0){this.draw();return}this.save(e),t.rating=gr(this.setting("TTHEME_FIND_RATING")),t.block=dr(this.setting("TTHEME_FIND_BLOCK")),t.sets=this.setting("TTHEME_FIND_SETS")==="show"?"show":"fold",t.preset=this.setting("TTHEME_FIND_POSTS")==="all"?"all":"cutouts",t.order=Rh(this.setting("TTHEME_FIND_ORDER")),t.solo=this.setting("TTHEME_FIND_SOLO")==="on",this.boards.clear(),this.current=void 0,t.shown=void 0,t.mode="grid",this.search()}save(t){this.store(t.map((n)=>[n.name,this.setting(n.name)]))}store(t){let n=un(this.home,"ttheme","config.zsh");try{let e=ee(n)?Qh(n,"utf8"):"";return xe(n,t.reduce((r,[i,o])=>$r(r,i,o),e)),!0}catch(e){return this.view.error=e instanceof Error?e.message:String(e),!1}}askKey(t){let n=this.view;if(t==="y"){if(n.asking=void 0,this.store([["TTHEME_FIND_UNBLOCK","1"]])){this.unblock=!0,this.finish(0);return}this.draw();return}if(t==="n"||t==="esc")n.asking=void 0,this.draw()}editKey(t){let n=this.view,e=n.editing??"",r=n.suggest??[];if((t==="up"||t==="down")&&r.length>0){let i=n.pick??-1,o=t==="down"?Math.min(r.length-1,i+1):i-1;n.pick=o<0?void 0:o,this.draw();return}if(t==="esc"||t==="enter")this.quietSuggest();if(t==="esc"){if(n.editing=void 0,n.tag===""){this.finish(2);return}this.draw();return}if(t==="enter"){let i=n.pick===void 0?void 0:r[n.pick],o=i?e.replace(/\S*$/,i.value):e;if(n.editing=void 0,n.suggest=void 0,n.pick=void 0,o.trim()){this.commit(o.trim());return}if(n.tag===""){this.finish(2);return}this.draw();return}if(t==="backspace"){n.editing=e.slice(0,-1),this.suggest(),this.draw();return}if(t.length===1&&t>=" ")n.editing=e+t,this.suggest(),this.draw()}quietSuggest(){clearTimeout(this.suggestTimer),this.suggesting?.abort(),this.suggesting=void 0}suggest(){this.quietSuggest();let t=this.view;t.pick=void 0;let n=/\S*$/.exec(t.editing??"")?.[0]??"";if(!Qm(n)){t.suggest=void 0;return}let e=[...new Map(_u(this.catalog.palettes,this.entry,n).map((i)=>[i.booru,{value:i.booru,count:0,palette:i.name}])).values()].slice(0,Bm);t.suggest=e.length>0?e:void 0;let r=new AbortController;this.suggesting=r,this.suggestTimer=setTimeout(async()=>{try{let i=await Bc(n,AbortSignal.any([this.signal,r.signal]));if(this.suggesting===r&&t.editing!==void 0){let o=new Map(i.map((c)=>[c.value,c.count])),s=new Set(e.map((c)=>c.value));t.suggest=[...e.map((c)=>({...c,count:o.get(c.value)??0})),...i.filter((c)=>!s.has(c.value))].slice(0,Dm),t.pick=t.pick!==void 0&&t.pick<e.length?t.pick:void 0,this.draw()}}catch{}},Zm)}async commit(t){let n=mr(t,this.site??gt[0]);if(n){await this.jump(n.site,n.id);return}if(this.picture(t)){await this.attach(t);return}this.view.tag=t,this.boards.clear(),await this.search()}async jump(t,n){let e=++this.gen;this.tab=gt.indexOf(t)+1,this.syncSite(),this.current=void 0,this.view.shown=void 0,this.view.error=void 0;let r=Ur(`${t.key}|post:${n}`,!0);this.board=r,this.boards.set(r.key,r),this.show(),this.draw();try{let i=await Ii(t,n,this.signal);if(e!==this.gen)return;if(!i){r.searching=!1,r.error=`${t.name} has no post ${n}`,this.view.error=r.error,this.show(),this.draw();return}this.single(r,{site:t,post:i})}catch(i){this.fail(e,i,t)}}async turn(){this.fetch?.abort(),this.current=void 0,this.view.shown=void 0;let t=this.boards.get(this.boardKey);if(!t){await this.search();return}this.gen++,this.board=t,this.view.error=t.error,this.show(),this.draw(),await this.pump()}unfold(){let t=this.view,n=0;for(let e of this.board.groups){let r=e.open?e.posts.length:1;if(t.focus<n+r){if(e.posts.length<2)return;e.open=!e.open,this.board.focus=n;for(let i of e.posts)if(!this.thumbPath.has(rn(i.site,i.post.id)))this.thumbQueue.push(i);this.thumbs(),this.show(),this.scroll(),this.draw();return}n+=r}}openPage(){let t=this.view.tiles[this.view.focus],n=t&&this.posts.get(t.key);if(!n)return;let e=process.platform==="darwin"?"open":"xdg-open";try{Th(e,[n.site.pageUrl(n.post.id)],{stdio:"ignore",detached:!0}).unref()}catch{}}tryKey(t){let n=this.view;if(t==="left"||t==="right"){this.direction=t==="left"?-1:1,this.focus(n.focus+this.direction);return}if(t==="o"){this.openPage();return}if(t==="x"){this.swap();return}if(t==="v"){this.fromClipboard();return}if(t==="enter"){this.install();return}if(t==="esc")this.fetch?.abort(),clearTimeout(this.settle),n.fetching=void 0,n.mode="grid",n.error=void 0,this.draw()}focus(t){let n=this.view;if(n.tiles.length===0)return;let e=Math.max(0,Math.min(n.tiles.length-1,t));if(e===n.focus)return;if(n.focus=e,this.board.focus=e,this.scroll(),this.pump(),n.mode==="try")this.select();this.draw()}scroll(){let t=this.view,{perRow:n,rowsVis:e}=zn(this.cols,this.rows),r=Math.floor(t.focus/n);if(r<t.top)t.top=r;if(r>t.top+e-1)t.top=r-e+1;this.board.top=t.top}query(t){let n=this.view,e=n.tag===this.entry.booru?Cu(this.entry,t.key):[n.tag];if(e.length===0)return;let r=e.length>1,i=n.preset==="cutouts"?t.cutouts:"",o=r&&i.includes("~"),s=[r?e.map((h)=>`~${h}`).join(" "):e[0],t.rate(this.view.rating),o?"":i,n.order==="score"?t.best:""].filter(Boolean),c=[],u=[];for(let h of s)if(Si([...c,h].join(" "))<=t.tagBudget)c.push(h);else u.push(h);return{tags:c.join(" "),notes:[...u.length>0?[`${t.name} takes ${t.tagBudget} tags — ${u.join(" ")} left out`]:[],...o?[`${t.name} ORs the names, so cutouts are told by the file`]:[]]}}async search(){let t=++this.gen,n=Ur(this.boardKey,!0);this.board=n,this.boards.set(n.key,n),this.view.error=void 0;let e=this.sites.flatMap((o)=>{let s=this.query(o);return s?[{site:o,...s}]:[]}),r=this.sites.filter((o)=>!e.some((s)=>s.site===o)),i=[...e.flatMap(({notes:o})=>o),...r.length>0?[`${this.entry.name} has no tag on ${r.map((o)=>o.name).join(", ")}`]:[]];if(n.note=i.length>0?i.join(" · "):void 0,e.length===0)n.searching=!1;this.show(),this.draw(),this.tally(t,n,e);try{let o=await Promise.all(e.map(async(s)=>({plan:s,owners:await this.mateOwners(s.site)})));if(t!==this.gen)return;n.sources=o.flatMap(({plan:{site:s,tags:c},owners:u})=>[...Si(c)+1<=s.tagBudget?[...u.keys()].map((h)=>({site:s,tags:`${c} user:${h}`,page:0,done:!1})):[],{site:s,tags:c,page:0,done:!1}]),this.show(),this.draw(),await this.pump()}catch(o){this.fail(t,o)}}async tally(t,n,e){let r=await Promise.allSettled(e.map(({site:i,tags:o})=>Yc(i,o,this.signal)));if(t===this.gen)n.total=r.reduce((i,o)=>i+(o.status==="fulfilled"?o.value:0),0),this.show(),this.draw()}fail(t,n,e=this.site){if(t!==this.gen||this.signal.aborted)return;this.board.error=ro(e?.name??this.tabName,n),this.board.searching=!1,this.view.error=this.board.error,this.offer(e,n),this.show(),this.draw()}offer(t,n){if(t&&!this.view.unblocked&&Zh()&&ie(n)==="ECONNRESET")this.view.asking=t.name}drop(t,n,e){for(let r of t.sources)if(r.site===n)r.done=!0;t.note=[t.note,ro(n.name,e)].filter(Boolean).join(" · "),this.offer(n,e)}wants(){let{perRow:t,rowsVis:n}=zn(this.cols,this.rows);return this.view.tiles.length<(this.board.top+n+Kh)*t}need(){let{perRow:t,rowsVis:n}=zn(this.cols,this.rows);return(n+Kh)*t}live(t){return this.boards.get(t.key)===t}page(t,n,e){let r=`${t.key}|${n}|${e}`,i=this.pages.get(r);if(!i)i=xc(t,n,e,this.signal).then((o)=>this.borrow(o)),this.pages.set(r,i),i.catch(()=>this.pages.delete(r));return i}async borrow(t){let n=t.filter((e)=>e.solo===void 0&&e.md5!=="");if(n.length>0)try{zc(n,await Vc(n.map((e)=>e.md5),this.signal))}catch{}return t}async round(t){let n=gt.flatMap((c)=>{let u=t.sources.find((h)=>h.site===c&&!h.done);return u?[u]:[]}),e=await Promise.all(n.map(async(c)=>{try{return{source:c,posts:await this.page(c.site,c.tags,c.page)}}catch(u){if(t.sources.every((h)=>h.site===c.site)||this.signal.aborted)throw u;return this.drop(t,c.site,u),{source:c,posts:void 0}}}));if(!this.live(t))return;let r=[];for(let{source:c,posts:u}of e){if(!u)continue;c.page++,c.done=u.length<jn;let h=t.last.get(c);for(let f of u){let a=h&&kh(h.post,f)?h.set:`set:${c.site.key}:${f.id}`;h={post:f,set:a};let l=rn(c.site,f.id);if(t.seen.has(l))continue;t.seen.add(l);let g={site:c.site,post:f};if(this.eligible(g))t.kin.set(g,[a,...bh(c.site,f)]),r.push(g);else t.checked++}if(h)t.last.set(c,h)}let i=this.dedupe(t,r),o=++t.rounds,s;if(this.view.order!=="fit")s=n.length>1?fh(i):i;else{let c=Gr(i,this.frame(),this.matched),u=c.slice(0,this.need());if(await this.looks(u),!this.live(t))return;s=[...Gr(u,this.frame(),this.matched),...c.slice(u.length)]}for(let c of s)t.roundOf.set(c,o);t.queue.push(...s),this.ahead(t)}ahead(t){if(this.aheading||this.view.order!=="fit"||!this.live(t))return;let n=t.queue.slice(0,this.need()).filter((e)=>!this.looking.has(rn(e.site,e.post.id)));if(n.length===0)return;this.aheading=!0,this.looks(n).then(()=>{this.aheading=!1;for(let e of new Set(n.map((r)=>t.roundOf.get(r)??0)))this.resort(t,e);this.ahead(t)})}resort(t,n){let e=t.queue.flatMap((i,o)=>t.roundOf.get(i)===n?[o]:[]),r=Gr(e.map((i)=>t.queue[i]),this.frame(),this.matched);e.forEach((i,o)=>{t.queue[i]=r[o]})}dedupe(t,n){let e=[];for(let r of n){let i=Di(r.post),o=i.map((c)=>t.same.get(c)).find(Boolean);if(!o){for(let c of i)t.same.set(c,r);e.push(r);continue}if(t.checked++,Jh(r.post)<=Jh(o.post))continue;for(let c of[...i,...Di(o.post)])t.same.set(c,r);let s=e.indexOf(o);if(s>=0){e[s]=r;continue}this.replace(t,o,r)}return e}replace(t,n,e){t.roundOf.set(e,t.roundOf.get(n)??0);let r=t.queue.indexOf(n);if(r>=0){t.queue[r]=e;return}for(let i of t.groups){let o=i.posts.indexOf(n);if(o>=0){i.posts[o]=e,this.posts.set(rn(e.site,e.post.id),e),this.thumbQueue.push(e),this.thumbs();return}}}async looks(t){let n=0;await Promise.all(Array.from({length:Ph},async()=>{while(n<t.length)await this.look(t[n++])}))}look(t){let n=rn(t.site,t.post.id),e=this.looking.get(n);if(!e)e=(async()=>{let r=this.previewPath(t);await this.cached(t.site,r,t.post.preview);let i=await this.renders.run({job:"match",from:r,colors:this.entry.signature});return this.looked.set(n,i),this.matched.set(t.post,i.match),i})().catch(()=>{return}),this.looking.set(n,e);return e}async pump(){let t=this.gen,n=this.board;if(this.pumping===t||n.sources.length===0)return;this.pumping=t;let e=[],r;try{n.searching=!0;while(t===this.gen){while(e.length<jh&&n.queue.length>0&&this.wants()){let s=n.queue.shift();e.push({pick:s,passed:this.vet(s)})}if(this.ahead(n),!r&&n.queue.length<jh&&n.sources.some((s)=>!s.done)&&this.wants()){let s=this.round(n).then(()=>{if(r===s)r=void 0});s.catch(()=>{}),r=s}let i=e.shift();if(!i){if(!r)break;await r,this.show(),this.draw();continue}let o=await i.passed;if(t!==this.gen)return;if(n.checked++,o)this.admit(i.pick);this.show(),this.draw()}if(t===this.gen)n.searching=!1,this.show(),this.draw()}catch(i){this.fail(t,i)}finally{if(this.saveProbes(),this.pumping===t)this.pumping=0}}eligible({site:t,post:n}){let e=He(n);if(!Zc(t,n,this.view.rating)||qc(n,this.view.block).length>0||!e)return!1;if(this.view.solo&&n.solo===!1)return!1;return this.view.preset==="all"?["png","jpg","jpeg"].includes(e.ext):n.ext==="png"}async vet(t){let[n]=await Promise.all([this.passes(t),this.look(t)]);return n}async passes({site:t,post:n}){return this.view.preset==="all"||t.vouched||this.transparent(t,n)}probes(t){let n=this.probed.get(t.key);if(!n)n=io(t,"probes.json"),this.probed.set(t.key,n);return n}async transparent(t,n){let e=this.probes(t),r=e[n.id];if(r!==void 0)return r;try{let i=(await Dc(t,n.file,this.signal))?.alpha===!0;return e[n.id]=i,this.unsaved.add(t.key),i}catch{return!1}}saveProbes(){for(let t of this.unsaved){let n=gt.find((e)=>e.key===t);if(n)oo(n,"probes.json",this.probes(n))}this.unsaved.clear()}admit(t){let{site:n,post:e}=t,r=this.board,i=rn(n,e.id);this.posts.set(i,t);let o=r.kin.get(t)??[],s=this.looked.get(i),c=s&&{hash:s.hash,width:e.width,height:e.height},u=this.view.sets==="fold"?this.kindred(r,o,c):void 0;if(u){if(u.posts.push(t),this.register(r,u,o,c),u.open)this.thumbQueue.push(t),this.thumbs();return}let h={posts:[t],open:!1};r.groups.push(h),this.register(r,h,o,c),this.thumbQueue.push(t),this.thumbs()}kindred(t,n,e){for(let r of n){let i=t.kindred.get(r);if(i)return i}return e&&t.shapes.find((r)=>Mh(r.shape,e))?.group}register(t,n,e,r){for(let i of e)if(!t.kindred.has(i))t.kindred.set(i,n);if(r)t.shapes.push({shape:r,group:n})}async mateOwners(t){let n=this.owners.get(t.key);if(n)return n;let e=Oc(this.home),r=io(t,"owners.json"),i=this.catalog.palettes.flatMap((u)=>{let h=e.get(u.name);return u.group===this.entry.group&&u.name!==this.entry.name&&h?.site===t.key?[{name:u.name,id:h.id}]:[]}),o=await Promise.all(i.map(async(u)=>{let h=r[u.id];if(h!==void 0)return{...u,owner:h};try{return{...u,owner:(await Ii(t,u.id,this.signal))?.owner??""}}catch{return}})),s=new Map;for(let u of o)if(u)r[u.id]=u.owner,s.set(u.name,u.owner);oo(t,"owners.json",r);let c=Xc(s);return this.owners.set(t.key,c),c}async cached(t,n,e,r){if(ee(n))return Jm(n).size;let i=this.inflight.get(n);if(i)return i;let o=(async()=>{let s=await tu(t,e,this.signal,r);return Ce(Ar(n),{recursive:!0}),xe(n,s),s.length})();this.inflight.set(n,o);try{return await o}finally{this.inflight.delete(n)}}thumbs(){while(this.thumbing<Ph&&this.thumbQueue.length>0){let t=this.thumbQueue.shift();this.thumbing++,this.thumb(t).catch(()=>{}).finally(()=>{this.thumbing--,this.thumbs()})}}async thumb(t){let{site:n,post:e}=t,r=At.cols*this.cell.w,i=At.rows*this.cell.h,o=un(yn(n),"tile",`${Ah(e)}-${r}x${i}.png`);if(!ee(o)){let s=this.previewPath(t);await this.cached(n,s,e.preview),await this.renders.run({job:"thumb",from:s,to:o,width:r,height:i})}this.thumbPath.set(rn(n,e.id),o),this.show(),this.draw()}select(){let t=this.view,n=t.tiles[t.focus];if(this.fetch?.abort(),clearTimeout(this.settle),t.fetching=void 0,!n)return;if(this.current?.key===n.key){this.reveal();return}this.settle=setTimeout(()=>void this.load(n),_m),this.draw()}async load(t){let n=this.view,e=this.posts.get(t.key),r=e&&He(e.post);if(!e||!r)return;let{site:i}=e,o=this.board,s=new AbortController;this.fetch=s;try{let c=this.origPath(i,t.id,r.ext);if(!ee(c))n.fetching={id:t.key,got:0,size:0},this.draw();let u=await this.cached(i,c,r.file,(a,l)=>{if(n.fetching?.id===t.key)n.fetching={id:t.key,got:a,size:l},this.draw()});if(s.signal.aborted)return;if(n.fetching=void 0,o!==this.board)return;let h={site:i,id:t.id,key:t.key,path:c,ext:r.ext,size:u,using:"plain",failed:!1};n.preparing=t.key,this.flush();let f=await this.render(h,"plain");if(s.signal.aborted||o!==this.board)return;if(f.clear===0&&Zi()&&this.setting("TTHEME_FIND_REMOVE_BG")!=="off"){if(n.preparing=void 0,n.cutting=t.key,this.flush(),h.cut=await this.cutOut(i,t.id,c,s.signal),s.signal.aborted||o!==this.board)return;if(n.cutting=void 0,h.cut){n.preparing=t.key,this.flush();let a=await this.render(h,"cut").catch(()=>{return});if(s.signal.aborted||o!==this.board)return;if(a&&xu(a.clear))h.using="cut";else eo(h.cut,{force:!0}),h.cut=void 0,h.failed=!0}else h.failed=!0}if(this.current=h,n.tiles[n.focus]?.key===t.key)await this.present();this.preload()}catch(c){if(!s.signal.aborted&&!this.signal.aborted)n.error=ro(i.name,c)}finally{if(n.fetching?.id===t.key)n.fetching=void 0;if(n.preparing===t.key)n.preparing=void 0;if(n.cutting===t.key)n.cutting=void 0;this.draw()}}async cutOut(t,n,e,r){let i=un(yn(t),"cut",`${n}.png`);if(ee(i))return i;try{return Ce(Ar(i),{recursive:!0}),await Yu(e,i,r),i}catch{eo(i,{force:!0});return}}swap(){let t=this.current;if(!t?.cut||this.view.shown?.id!==t.key)return;t.using=t.using==="cut"?"plain":"cut",this.reveal()}preload(){let t=this.view;if(t.mode!=="try")return;for(let n of[t.focus+this.direction,t.focus-this.direction]){if(this.prefetching>=Xm)return;let e=t.tiles[n],r=e&&this.posts.get(e.key),i=r&&He(r.post);if(!r||!i)continue;let{site:o,post:s}=r,c=this.origPath(o,s.id,i.ext);this.prefetching++,this.cached(o,c,i.file).then(()=>this.render({site:o,id:s.id,key:e.key,path:c,ext:i.ext,size:0,using:"plain",failed:!1},"plain")).catch(()=>{}).finally(()=>{this.prefetching--})}}async render(t,n){let e=this.cols*this.cell.w,r=this.rows*this.cell.h,i=Math.min(e,Vm),o=Math.max(1,Math.round(r*i/e)),s=un(this.scratch,`${t.site.key}-${t.id}${n==="cut"?"c":""}-${i}x${o}.png`),c=`${t.site.key}:${t.id}:${n}`,u=this.clarity.get(c);if(u!==void 0&&ee(s))return{clear:u,path:s};let h=await this.renders.run({job:"show",from:n==="cut"?t.cut:t.path,to:s,width:i,height:o,colors:this.entry,tone:this.tone});return this.clarity.set(c,h),{clear:h,path:s}}async present(){let t=this.current;if(!t)return;let n=t.using,{clear:e,path:r}=await this.render(t,n);if(this.current!==t||t.using!==n)return;this.view.shown={id:t.key,clear:e,bytes:t.size,path:r,cut:t.cut?n==="cut"?"on":"off":t.failed?"failed":"none"}}reveal(){let t=this.view;t.preparing=this.current?.key,this.flush(),this.present().catch((n)=>{t.error=n instanceof Error?n.message:String(n)}).finally(()=>{if(t.preparing===this.current?.key)t.preparing=void 0;this.draw()})}async install(){let t=this.view,n=t.tiles[t.focus],e=this.current;if(!n||e?.key!==n.key||t.preparing!==void 0||t.shown?.id!==n.key)return;t.installing=n.key,t.error=void 0,this.flush();try{await this.renders.run({job:"backdrop",from:e.using==="cut"?e.cut:e.path,source:e.path,home:this.home,colors:this.entry,tone:this.tone,origin:{site:e.site.key,id:e.id,ext:e.ext,from:`${e.site.name} ${e.id} ${e.site.pageUrl(e.id)}`},width:this.cols*this.cell.w,height:this.rows*this.cell.h});let r=io(e.site,"owners.json");r[e.id]=this.posts.get(e.key)?.post.owner??"",oo(e.site,"owners.json",r),ne(this.home),t.saved=`background · ${this.entry.name} ← ${e.site.name} ${e.id}`,t.installed.push(n.key),this.fetch?.abort(),clearTimeout(this.settle),t.fetching=void 0,t.mode="grid"}catch(r){t.error=r instanceof Error?r.message:String(r)}t.installing=void 0,this.draw()}draw(){if(this.dirty)return;this.dirty=!0,setImmediate(()=>{this.dirty=!1,this.flush()})}flush(){let t=uh(this.view,this.cols,this.rows),n="\x1B[?2026h";t.lines.forEach((r,i)=>{n+=`\x1B[${i+1};1H\x1B[K${r}`});let e=new Set;for(let r of t.images){if(e.add(r.id),this.sent.get(r.id)!==r.path)n+=th(r),this.sent.set(r.id,r.path),this.placed.delete(r.id);let i=`${r.row};${r.col};${r.cols};${r.rows};${r.z}`;if(this.placed.get(r.id)!==i)n+=nh(r),this.placed.set(r.id,i)}for(let r of this.sent.keys())if(!e.has(r))n+=eh(r),this.sent.delete(r),this.placed.delete(r);this.write(`${n}\x1B[?2026l`)}}function Zh(){if(process.versions.bun)return!0;let[t=0,n=0]=process.versions.node.split(".").map(Number);return t>22||t===22&&n>=21}async function Uh(){if(!Zh())return process.stderr.write(`unblock needs node 22.21 or newer — this is ${process.versions.node}
|
|
143
|
+
`),1;let t=await Hh(),n=Th(process.execPath,process.argv.slice(1),{stdio:"inherit",env:{...process.env,NODE_USE_ENV_PROXY:"1",NODE_NO_WARNINGS:"1",HTTPS_PROXY:`http://127.0.0.1:${t.port}`,NO_PROXY:[process.env.NO_PROXY,Qc()].filter(Boolean).join(","),TTHEME_FIND_PROXY:String(t.port)}}),e=await new Promise((r)=>n.on("exit",(i)=>r(i??1)));return t.close(),e}async function Xh(t){if(process.env.TTHEME_FIND_UNBLOCK==="1"&&!process.env.TTHEME_FIND_PROXY)return Uh();let n=Dt(),e=Ut(n),r=Rr(e.palettes,t);if(!process.stdin.isTTY||!process.stdout.isTTY)throw Error("ttheme find needs a terminal");let i=new qh(n,e,r,r.booru??""),o=await i.run(),s=i.unblock?await Uh():o;if(i.saved&&s!==0)return process.stderr.write(`${i.saved}
|
|
144
|
+
`),0;return s}function _h(t,n){let e=Dt();if(Rr(Ut(e).palettes,t),n==="next"||n==="prev"){let{key:r,at:i,of:o}=Fc(e,t,n==="next"?1:-1);return ne(e),process.stderr.write(`background · ${t} ${i}/${o} ${r}
|
|
145
|
+
`),0}if(n==="drop"){let{key:r,left:i}=Ic(e,t);return ne(e),process.stderr.write(`background · ${t} removed ${r??"the picture"} · ${i} left
|
|
146
|
+
`),0}if(n==="tuned")return ne(e),0;throw Error(`unknown image action ${n} — next, prev, drop or tuned`)}import{execFileSync as Dp}from"node:child_process";import{chmodSync as t0,copyFileSync as n0,existsSync as Qt,mkdirSync as Oo,readdirSync as e0,readFileSync as ce,rmSync as Cf,writeFileSync as xf}from"node:fs";import{homedir as r0}from"node:os";import{dirname as se,join as ht}from"node:path";import{styleText as lo}from"node:util";import{stdout as af,stdin as pp}from"node:process";import wp from"node:readline";var Ch=(()=>{let t=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(n)=>{let e=0;t.lastIndex=0;while(t.test(n))e+=1;return n.length-e}})(),xh=(t)=>{return t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510},Yh=(t)=>{return t===8987||t===9001||t>=12272&&t<=12287||t>=12289&&t<=12350||t>=12441&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12783&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=65040&&t<=65049||t>=65072&&t<=65106||t>=65108&&t<=65126||t>=65128&&t<=65131||t>=127488&&t<=127490||t>=127504&&t<=127547||t>=127552&&t<=127560||t>=131072&&t<=196605||t>=196608&&t<=262141};var np=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,ep=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,zh=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,rp=/\t{1,1000}/y,Vh=/[\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,ip=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,op=/\p{M}+/gu,sp={limit:1/0,ellipsis:""},Bh=(t,n={},e={})=>{let r=n.limit??1/0,i=n.ellipsis??"",o=n?.ellipsisWidth??(i?Bh(i,sp,e).width:0),s=0,c=e.controlWidth??0,u=e.tabWidth??8,h=e.emojiWidth??2,f=2,a=e.regularWidth??1,l=e.wideWidth??2,g=[[ip,a],[np,0],[ep,c],[rp,u],[Vh,h],[zh,l]],d=0,m=0,E=t.length,y=0,N=!1,k=E,S=Math.max(0,r-o),$=0,H=0,b=0,j=0;t:while(!0){if(H>$||m>=E&&m>d){let O=t.slice($,H)||t.slice(d,m);y=0;for(let L of O.replaceAll(op,"")){let P=L.codePointAt(0)||0;if(xh(P))j=2;else if(Yh(P))j=l;else j=a;if(b+j>S)k=Math.min(k,Math.max($,d)+y);if(b+j>r){N=!0;break t}y+=L.length,b+=j}$=H=0}if(m>=E)break t;for(let O=0,L=g.length;O<L;O++){let[P,C]=g[O];if(P.lastIndex=m,P.test(t)){if(y=P===zh?Ch(t.slice(m,P.lastIndex)):P===Vh?1:P.lastIndex-m,j=y*C,b+j>S)k=Math.min(k,m+Math.floor((S-b)/C));if(b+j>r){N=!0;break t}b+=j,$=d,H=m,m=d=P.lastIndex;continue t}}m+=1}return{width:N?S:b,index:N?k:E,truncated:N,ellipsed:N&&r>=o}},Dh=Bh;var cp={limit:1/0,ellipsis:"",ellipsisWidth:0},up=(t,n={})=>{return Dh(t,cp,n).width},Lt=up;var Tr="\x1B",of="",hp=39,co="\x07",sf="[",fp="]",cf="m",uo=`${fp}8;;`,tf=new RegExp(`(?:\\${sf}(?<code>\\d+)m|\\${uo}(?<uri>.*)${co})`,"y"),nf=(t)=>{if(t>=30&&t<=37)return 39;if(t>=90&&t<=97)return 39;if(t>=40&&t<=47)return 49;if(t>=100&&t<=107)return 49;if(t===1||t===2)return 22;if(t===3)return 23;if(t===4)return 24;if(t===7)return 27;if(t===8)return 28;if(t===9)return 29;if(t===0)return 0;return},ef=(t)=>`${Tr}${sf}${t}${cf}`,rf=(t)=>`${Tr}${uo}${t}${co}`,so=(t,n,e)=>{let r=n[Symbol.iterator](),i=!1,o=!1,s=t.at(-1),c=s===void 0?0:Lt(s),u=r.next(),h=r.next(),f=0;while(!u.done){let a=u.value,l=Lt(a);if(c+l<=e)t[t.length-1]+=a;else t.push(a),c=0;if(a===Tr||a===of)i=!0,o=n.startsWith(uo,f+1);if(i){if(o){if(a===co)i=!1,o=!1}else if(a===cf)i=!1}else if(c+=l,c===e&&!h.done)t.push(""),c=0;u=h,h=r.next(),f+=a.length}if(s=t.at(-1),!c&&s!==void 0&&s.length&&t.length>1)t[t.length-2]+=t.pop()},ap=(t)=>{let n=t.split(" "),e=n.length;while(e){if(Lt(n[e-1]))break;e--}if(e===n.length)return t;return n.slice(0,e).join(" ")+n.slice(e).join("")},lp=(t,n,e={})=>{if(e.trim!==!1&&t.trim()==="")return"";let r="",i,o,s=t.split(" "),c=[""],u=0;for(let a=0;a<s.length;a++){let l=s[a];if(e.trim!==!1){let d=c.at(-1)??"",m=d.trimStart();if(d.length!==m.length)c[c.length-1]=m,u=Lt(m)}if(a!==0){if(u>=n&&(e.wordWrap===!1||e.trim===!1))c.push(""),u=0;if(u||e.trim===!1)c[c.length-1]+=" ",u++}let g=Lt(l);if(e.hard&&g>n){let d=n-u,m=1+Math.floor((g-d-1)/n);if(Math.floor((g-1)/n)<m)c.push("");so(c,l,n),u=Lt(c.at(-1)??"");continue}if(u+g>n&&u&&g){if(e.wordWrap===!1&&u<n){so(c,l,n),u=Lt(c.at(-1)??"");continue}c.push(""),u=0}if(u+g>n&&e.wordWrap===!1){so(c,l,n),u=Lt(c.at(-1)??"");continue}c[c.length-1]+=l,u+=g}if(e.trim!==!1)c=c.map((a)=>ap(a));let h=c.join(`
|
|
147
|
+
`),f=!1;for(let a=0;a<h.length;a++){let l=h[a];if(r+=l,!f){if(f=l>="\uD800"&&l<="\uDBFF",f)continue}else f=!1;if(l===Tr||l===of){tf.lastIndex=a+1;let d=tf.exec(h)?.groups;if(d?.code!==void 0){let m=Number.parseFloat(d.code);i=m===hp?void 0:m}else if(d?.uri!==void 0)o=d.uri.length===0?void 0:d.uri}if(h[a+1]===`
|
|
148
|
+
`){if(o)r+=rf("");let g=i?nf(i):void 0;if(i&&g)r+=ef(g)}else if(l===`
|
|
149
|
+
`){if(i&&nf(i))r+=ef(i);if(o)r+=rf(o)}}return r},gp=/\r?\n/;function Fn(t,n,e){return String(t).normalize().split(gp).map((r)=>lp(r,n,e)).join(`
|
|
150
|
+
`)}var Wt=er(fo(),1);function pn(t,n,e){if(!e.some((s)=>!s.disabled))return t;let r=t+n,i=Math.max(e.length-1,0),o=r<0?i:r>i?0:r;return e[o]?.disabled?pn(o,n<0?-1:1,e):o}function Wr(t,n,e,r){let i=r.split(`
|
|
151
|
+
`),o=0,s=t;for(let u of i){if(s<=u.length)break;s-=u.length+1,o++}for(o=Math.max(0,Math.min(i.length-1,o+e)),s=Math.min(s,i[o].length)+n;s<0&&o>0;)o--,s+=i[o].length+1;for(;s>i[o].length&&o<i.length-1;)s-=i[o].length+1,o++;s=Math.max(0,Math.min(i[o].length,s));let c=0;for(let u=0;u<o;u++)c+=i[u].length+1;return c+s}var $p=["up","down","left","right","space","enter","cancel"],bp=["January","February","March","April","May","June","July","August","September","October","November","December"],Kt={actions:new Set($p),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:[...bp],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(t,n)=>`There are only ${t} days in ${n}`,afterMin:(t)=>`Date must be on or after ${t.toISOString().slice(0,10)}`,beforeMax:(t)=>`Date must be on or before ${t.toISOString().slice(0,10)}`}}};function lf(t,n){if(typeof t=="string")return Kt.aliases.get(t)===n;for(let e of t)if(e!==void 0&&lf(e,n))return!0;return!1}function kp(t,n){if(t===n)return;let e=t.split(`
|
|
152
|
+
`),r=n.split(`
|
|
153
|
+
`),i=Math.max(e.length,r.length),o=[];for(let s=0;s<i;s++)e[s]!==r[s]&&o.push(s);return{lines:o,numLinesBefore:e.length,numLinesAfter:r.length,numLines:i}}var jb=globalThis.process.platform.startsWith("win"),go=Symbol("clack:cancel");function Jn(t){return t===go}function Qr(t,n){let e=t;e.isTTY&&e.setRawMode(n)}var Zr=(t)=>("columns"in t)&&typeof t.columns=="number"?t.columns:80,po=(t)=>("rows"in t)&&typeof t.rows=="number"?t.rows:20;function In(t,n,e,r=e,i=e,o){let s=Zr(t??af);return Fn(n,s-e.length,{hard:!0,trim:!1}).split(`
|
|
154
|
+
`).map((c,u,h)=>{let f=o?o(c,u):c;return u===0?`${r}${f}`:u===h.length-1?`${i}${f}`:`${e}${f}`}).join(`
|
|
155
|
+
`)}function gf(t,n){if("~standard"in t){let e=t["~standard"].validate(n);if(e instanceof Promise)throw TypeError("Schema validation must be synchronous. Update `validate()` and remove any asynchronous logic.");return e.issues?.at(0)?.message}return t(n)}class hn{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(t,n=!0){let{input:e=pp,output:r=af,render:i,signal:o,...s}=t;this.opts=s,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=i.bind(this),this._track=n,this._abortSignal=o,this.input=e,this.output=r}unsubscribe(){this._subscribers.clear()}setSubscriber(t,n){let e=this._subscribers.get(t)??[];e.push(n),this._subscribers.set(t,e)}on(t,n){this.setSubscriber(t,{cb:n})}once(t,n){this.setSubscriber(t,{cb:n,once:!0})}emit(t,...n){let e=this._subscribers.get(t)??[],r=[];for(let i of e)i.cb(...n),i.once&&r.push(()=>e.splice(e.indexOf(i),1));for(let i of r)i()}prompt(){return new Promise((t)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),t(go);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=wp.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),Qr(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(Wt.cursor.show),this.output.off("resize",this.render),Qr(this.input,!1),t(this.value)}),this.once("cancel",()=>{this.output.write(Wt.cursor.show),this.output.off("resize",this.render),Qr(this.input,!1),t(go)})})}_isActionKey(t,n){return t==="\t"}_shouldSubmit(t,n){return!0}_setValue(t){this.value=t,this.emit("value",this.value)}_setUserInput(t,n){this.userInput=t??"",this.emit("userInput",this.userInput),n&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}onKeypress(t,n){if(this._track&&n.name!=="return"&&(n.name&&this._isActionKey(t,n)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),n?.name&&(!this._track&&Kt.aliases.has(n.name)&&this.emit("cursor",Kt.aliases.get(n.name)),Kt.actions.has(n.name)&&this.emit("cursor",n.name)),t&&(t.toLowerCase()==="y"||t.toLowerCase()==="n")&&this.emit("confirm",t.toLowerCase()==="y"),this.emit("key",t,n),n?.name==="return"&&this._shouldSubmit(t,n)){if(this.opts.validate){let e=gf(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")}lf([t,n?.name,n?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
|
|
156
|
+
`),Qr(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let t=Fn(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
|
|
157
|
+
`).length-1;this.output.write(Wt.cursor.move(-999,t*-1))}render(){let t=Fn(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(t!==this._prevFrame){if(this.state==="initial")this.output.write(Wt.cursor.hide);else{let n=kp(this._prevFrame,t),e=po(this.output);if(this.restoreCursor(),n){let r=Math.max(0,n.numLinesAfter-e),i=Math.max(0,n.numLinesBefore-e),o=n.lines.find((s)=>s>=r);if(o===void 0){this._prevFrame=t;return}if(n.lines.length===1){this.output.write(Wt.cursor.move(0,o-i)),this.output.write(Wt.erase.lines(1));let s=t.split(`
|
|
158
|
+
`);this.output.write(s[o]),this._prevFrame=t,this.output.write(Wt.cursor.move(0,s.length-o-1));return}else if(n.lines.length>1){if(r<i)o=r;else{let c=o-i;c>0&&this.output.write(Wt.cursor.move(0,c))}this.output.write(Wt.erase.down());let s=t.split(`
|
|
159
|
+
`).slice(o);this.output.write(s.join(`
|
|
160
|
+
`)),this._prevFrame=t;return}}this.output.write(Wt.erase.down())}this.output.write(t),this.state==="initial"&&(this.state="active"),this._prevFrame=t}}}function Ep(t,n){if(t===void 0||n.length===0)return 0;let e=n.findIndex((r)=>r.value===t);return e!==-1?e:0}function Mp(t,n){return(n.label??String(n.value)).toLowerCase().includes(t.toLowerCase())}function vp(t,n){if(n)return t?n:n[0]}var yp=class extends hn{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#n=0;#i="";#t;#o;#c;get cursor(){return this.#n}get userInputWithCursor(){if(!this.userInput)return lo(["inverse","hidden"],"_");if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let n=this.userInput.slice(0,this.cursor),e=this.userInput.slice(this.cursor,this.cursor+1),r=this.userInput.slice(this.cursor+1);return`${n}${lo("inverse",e)}${r}`}get options(){return typeof this.#o=="function"?this.#o():this.#o}constructor(n){super(n),this.#o=n.options,this.#c=n.placeholder;let e=this.options;this.filteredOptions=[...e],this.multiple=n.multiple===!0,this.#t=typeof n.options=="function"?n.filter:n.filter??Mp;let r;if(n.initialValue&&Array.isArray(n.initialValue)?this.multiple?r=n.initialValue:r=n.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(r=[this.options[0]?.value]),r)for(let i of r){let o=e.findIndex((s)=>s.value===i);o!==-1&&(this.toggleSelected(i),this.#n=o)}this.focusedValue=this.options[this.#n]?.value,this.on("key",(i,o)=>this.#e(i,o)),this.on("userInput",(i)=>this.#r(i))}_isActionKey(n,e){return n==="\t"||this.multiple&&this.isNavigating&&e.name==="space"&&n!==void 0&&n!==""}#e(n,e){let r=e.name==="up",i=e.name==="down",o=e.name==="return",s=this.userInput===""||this.userInput==="\t",c=this.#c,u=this.options,h=c!==void 0&&c!==""&&u.some((f)=>!f.disabled&&(this.#t?this.#t(c,f):!0));if(e.name==="tab"&&s&&h){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(c,!0),this.isNavigating=!1;return}r||i?(this.#n=pn(this.#n,r?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#n]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):o?this.value=vp(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(e.name==="tab"||this.isNavigating&&e.name==="space")?this.toggleSelected(this.focusedValue):this.isNavigating=!1:(this.focusedValue&&(this.selectedValues=[this.focusedValue]),this.isNavigating=!1)}deselectAll(){this.selectedValues=[]}toggleSelected(n){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(n)?this.selectedValues=this.selectedValues.filter((e)=>e!==n):this.selectedValues=[...this.selectedValues,n]:this.selectedValues=[n])}#r(n){if(n!==this.#i){this.#i=n;let e=this.options;n&&this.#t?this.filteredOptions=e.filter((o)=>this.#t?.(n,o)):this.filteredOptions=[...e];let r=Ep(this.focusedValue,this.filteredOptions);this.#n=pn(r,0,this.filteredOptions);let i=this.filteredOptions[this.#n];i&&!i.disabled?this.focusedValue=i.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}};class wo extends hn{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(t){super(t,!1),this.value=!!t.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(n)=>{this.output.write(Wt.cursor.move(0,-1)),this.value=n,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var Sp={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function hf(t){return[...t].map((n)=>Sp[n])}function Fp(t){let n=new Intl.DateTimeFormat(t,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2000,0,15)),e=[],r="/";for(let i of n)i.type==="literal"?r=i.value.trim()||i.value:(i.type==="year"||i.type==="month"||i.type==="day")&&e.push({type:i.type,len:i.type==="year"?4:2});return{segments:e,separator:r}}function ao(t){return Number.parseInt((t||"0").replace(/_/g,"0"),10)||0}function qr(t){return{year:ao(t.year),month:ao(t.month),day:ao(t.day)}}function mo(t,n){return new Date(t||2001,n||1,0).getDate()}function df(t){let{year:n,month:e,day:r}=qr(t);if(!n||n<0||n>9999||!e||e<1||e>12||!r||r<1)return;let i=new Date(Date.UTC(n,e-1,r));if(!(i.getUTCFullYear()!==n||i.getUTCMonth()!==e-1||i.getUTCDate()!==r))return{year:n,month:e,day:r}}function ff(t){let n=df(t);return n?new Date(Date.UTC(n.year,n.month-1,n.day)):void 0}function Ip(t,n,e,r){let i=e?{year:e.getUTCFullYear(),month:e.getUTCMonth()+1,day:e.getUTCDate()}:null,o=r?{year:r.getUTCFullYear(),month:r.getUTCMonth()+1,day:r.getUTCDate()}:null;return t==="year"?{min:i?.year??1,max:o?.year??9999}:t==="month"?{min:i&&n.year===i.year?i.month:1,max:o&&n.year===o.year?o.month:12}:{min:i&&n.year===i.year&&n.month===i.month?i.day:1,max:o&&n.year===o.year&&n.month===o.month?o.day:mo(n.year,n.month)}}class mf extends hn{#n;#i;#t;#o;#c;#e={segmentIndex:0,positionInSegment:0};#r=!0;#s=null;inlineError="";get segmentCursor(){return{...this.#e}}get segmentValues(){return{...this.#t}}get segments(){return this.#n}get separator(){return this.#i}get formattedValue(){return this.#a(this.#t)}#a(t){return this.#n.map((n)=>t[n.type]).join(this.#i)}#u(){this._setUserInput(this.#a(this.#t)),this._setValue(ff(this.#t)??void 0)}constructor(t){let n=t.format?{segments:hf(t.format),separator:t.separator??"/"}:Fp(t.locale),e=t.separator??n.separator,r=t.format?hf(t.format):n.segments,i=t.initialValue??t.defaultValue,o=i?{year:String(i.getUTCFullYear()).padStart(4,"0"),month:String(i.getUTCMonth()+1).padStart(2,"0"),day:String(i.getUTCDate()).padStart(2,"0")}:{year:"____",month:"__",day:"__"},s=r.map((c)=>o[c.type]).join(e);super({...t,initialUserInput:s},!1),this.#n=r,this.#i=e,this.#t=o,this.#o=t.minDate,this.#c=t.maxDate,this.#u(),this.on("cursor",(c)=>this.#d(c)),this.on("key",(c,u)=>this.#m(c,u)),this.on("finalize",()=>this.#p(t))}#h(){let t=Math.max(0,Math.min(this.#e.segmentIndex,this.#n.length-1)),n=this.#n[t];if(n)return this.#e.positionInSegment=Math.max(0,Math.min(this.#e.positionInSegment,n.len-1)),{segment:n,index:t}}#f(t){this.inlineError="",this.#s=null;let n=this.#h();n&&(this.#e.segmentIndex=Math.max(0,Math.min(this.#n.length-1,n.index+t)),this.#e.positionInSegment=0,this.#r=!0)}#l(t){let n=this.#h();if(!n)return;let{segment:e}=n,r=this.#t[e.type],i=!r||r.replace(/_/g,"")==="",o=Number.parseInt((r||"0").replace(/_/g,"0"),10)||0,s=Ip(e.type,qr(this.#t),this.#o,this.#c),c;i?c=t===1?s.min:s.max:c=Math.max(Math.min(s.max,o+t),s.min),this.#t={...this.#t,[e.type]:c.toString().padStart(e.len,"0")},this.#r=!0,this.#s=null,this.#u()}#d(t){if(t)switch(t){case"right":return this.#f(1);case"left":return this.#f(-1);case"up":return this.#l(1);case"down":return this.#l(-1)}}#m(t,n){if(n?.name==="backspace"||n?.sequence===""||n?.sequence==="\b"||t===""||t==="\b"){this.inlineError="";let e=this.#h();if(!e)return;if(!this.#t[e.segment.type].replace(/_/g,"")){this.#f(-1);return}this.#t[e.segment.type]="_".repeat(e.segment.len),this.#r=!0,this.#e.positionInSegment=0,this.#u();return}if(n?.name==="tab"){this.inlineError="";let e=this.#h();if(!e)return;let r=n.shift?-1:1,i=e.index+r;i>=0&&i<this.#n.length&&(this.#e.segmentIndex=i,this.#e.positionInSegment=0,this.#r=!0);return}if(t&&/^[0-9]$/.test(t)){let e=this.#h();if(!e)return;let{segment:r}=e,i=!this.#t[r.type].replace(/_/g,"");if(this.#r&&this.#s!==null&&!i){let l=this.#s+t,g={...this.#t,[r.type]:l},d=this.#g(g,r);if(d){this.inlineError=d,this.#s=null,this.#r=!1;return}this.inlineError="",this.#t[r.type]=l,this.#s=null,this.#r=!1,this.#u(),e.index<this.#n.length-1&&(this.#e.segmentIndex=e.index+1,this.#e.positionInSegment=0,this.#r=!0);return}this.#r&&!i&&(this.#t[r.type]="_".repeat(r.len),this.#e.positionInSegment=0),this.#r=!1,this.#s=null;let o=this.#t[r.type],s=o.indexOf("_"),c=s>=0?s:Math.min(this.#e.positionInSegment,r.len-1);if(c<0||c>=r.len)return;let u=o.slice(0,c)+t+o.slice(c+1),h=!1;if(c===0&&o==="__"&&(r.type==="month"||r.type==="day")){let l=Number.parseInt(t,10);u=`0${t}`,h=l<=(r.type==="month"?1:2)}if(r.type==="year"&&(u=(o.replace(/_/g,"")+t).padStart(r.len,"_")),!u.includes("_")){let l={...this.#t,[r.type]:u},g=this.#g(l,r);if(g){this.inlineError=g;return}}this.inlineError="",this.#t[r.type]=u;let f=u.includes("_")?void 0:df(this.#t);if(f){let{year:l,month:g}=f,d=mo(l,g);this.#t={year:String(Math.max(0,Math.min(9999,l))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,g))).padStart(2,"0"),day:String(Math.max(1,Math.min(d,f.day))).padStart(2,"0")}}this.#u();let a=u.indexOf("_");h?(this.#r=!0,this.#s=t):a>=0?this.#e.positionInSegment=a:s>=0&&e.index<this.#n.length-1?(this.#e.segmentIndex=e.index+1,this.#e.positionInSegment=0,this.#r=!0):this.#e.positionInSegment=Math.min(c+1,r.len-1)}}#g(t,n){let{month:e,day:r}=qr(t);if(n.type==="month"&&(e<0||e>12))return Kt.date.messages.invalidMonth;if(n.type==="day"&&(r<0||r>31))return Kt.date.messages.invalidDay(31,"any month")}#p(t){let{year:n,month:e,day:r}=qr(this.#t);if(n&&e&&r){let i=mo(n,e);this.#t={...this.#t,day:String(Math.min(r,i)).padStart(2,"0")}}this.value=ff(this.#t)??t.defaultValue??void 0}}var Np=class extends hn{options;cursor=0;#n;getGroupItems(n){return this.options.filter((e)=>e.group===n)}isGroupSelected(n){let e=this.getGroupItems(n),r=this.value;return r===void 0?!1:e.every((i)=>r.includes(i.value))}toggleValue(){let n=this.options[this.cursor];if(n!==void 0)if(this.value===void 0&&(this.value=[]),n.group===!0){let e=n.value,r=this.getGroupItems(e);this.isGroupSelected(e)?this.value=this.value.filter((i)=>r.findIndex((o)=>o.value===i)===-1):this.value=[...this.value,...r.map((i)=>i.value)],this.value=Array.from(new Set(this.value))}else{let e=this.value.includes(n.value);this.value=e?this.value.filter((r)=>r!==n.value):[...this.value,n.value]}}constructor(n){super(n,!1);let{options:e}=n;this.#n=n.selectableGroups!==!1,this.options=Object.entries(e).flatMap(([r,i])=>[{value:r,group:!0,label:r},...i.map((o)=>({...o,group:r}))]),this.value=[...n.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:r})=>r===n.cursorAt),this.#n?0:1),this.on("cursor",(r)=>{switch(r){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let i=this.options[this.cursor]?.group===!0;!this.#n&&i&&(this.cursor=this.cursor===0?this.options.length-1:this.cursor-1);break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let i=this.options[this.cursor]?.group===!0;!this.#n&&i&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},Op=new Set(["up","down","left","right"]);class pf extends hn{#n=!1;#i;focused="editor";get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t=this.userInput;if(this.cursor>=t.length)return`${t}█`;let n=t.slice(0,this.cursor),e=t.slice(this.cursor,this.cursor+1),r=t.slice(this.cursor+1);return e===`
|
|
161
|
+
`?`${n}█
|
|
162
|
+
${r}`:`${n}${lo("inverse",e)}${r}`}get cursor(){return this._cursor}#t(t){if(this.userInput.length===0){this._setUserInput(t);return}this._setUserInput(this.userInput.slice(0,this.cursor)+t+this.userInput.slice(this.cursor))}#o(t){let n=this.value??"";switch(t){case"up":this._cursor=Wr(this._cursor,0,-1,n);return;case"down":this._cursor=Wr(this._cursor,0,1,n);return;case"left":this._cursor=Wr(this._cursor,-1,0,n);return;case"right":this._cursor=Wr(this._cursor,1,0,n);return}}_shouldSubmit(t,n){if(this.#i)return this.focused==="submit"?!0:(this.#t(`
|
|
163
|
+
`),this._cursor++,!1);let e=this.#n;return this.#n=!0,e&&this.cursor===this.userInput.length?(this.userInput[this.cursor-1]===`
|
|
164
|
+
`&&(this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--),!0):(this.#t(`
|
|
165
|
+
`),this._cursor++,!1)}constructor(t){let n=t.initialUserInput??t.initialValue;super({...t,initialUserInput:n},!1),n!==void 0&&(this._cursor=n.length),this.#i=t.showSubmit??!1,this.on("key",(e,r)=>{if(r?.name&&Op.has(r.name)){this.#n=!1,this.#o(r.name);return}if(e==="\t"&&this.#i){this.focused=this.focused==="editor"?"submit":"editor";return}if(r?.name!=="return"){if(this.#n=!1,r?.name==="backspace"&&this.cursor>0){this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--;return}if(r?.name==="delete"&&this.cursor<this.userInput.length){this._setUserInput(this.userInput.slice(0,this.cursor)+this.userInput.slice(this.cursor+1));return}e&&(this.#i&&this.focused==="submit"&&(this.focused="editor"),this.#t(e??""),this._cursor++)}}),this.on("userInput",(e)=>{this._setValue(e)}),this.on("finalize",()=>{this.value||(this.value=t.defaultValue),this.value===void 0&&(this.value="")})}}class $o extends hn{options;cursor=0;get _value(){return this.options[this.cursor]?.value}get _enabledOptions(){return this.options.filter((t)=>t.disabled!==!0)}toggleAll(){let t=this._enabledOptions,n=this.value!==void 0&&this.value.length===t.length;this.value=n?[]:t.map((e)=>e.value)}toggleInvert(){let t=this.value;if(!t)return;let n=this._enabledOptions.filter((e)=>!t.includes(e.value));this.value=n.map((e)=>e.value)}toggleValue(){this.value===void 0&&(this.value=[]);let t=this.value.includes(this._value);this.value=t?this.value.filter((n)=>n!==this._value):[...this.value,this._value]}constructor(t){super(t,!1),this.options=t.options,this.value=[...t.initialValues??[]];let n=Math.max(this.options.findIndex(({value:e})=>e===t.cursorAt),0);this.cursor=this.options[n]?.disabled?pn(n,1,this.options):n,this.on("key",(e,r)=>{r.name==="a"&&this.toggleAll(),r.name==="i"&&this.toggleInvert()}),this.on("cursor",(e)=>{switch(e){case"left":case"up":this.cursor=pn(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=pn(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}var Xr=class extends hn{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){let n=this._selectedValue;this.value=n===void 0?void 0:n.value}constructor(n){super(n,!1),this.options=n.options;let e=this.options.findIndex(({value:i})=>i===n.initialValue),r=e===-1?0:e;this.cursor=this.options[r]?.disabled?pn(r,1,this.options):r,this.changeValue(),this.on("cursor",(i)=>{switch(i){case"left":case"up":this.cursor=pn(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=pn(this.cursor,1,this.options);break}this.changeValue()})}};import{styleText as M,stripVTControlCharacters as Wb}from"node:util";import Yt from"node:process";var Ef=er(fo(),1);function Hp(){if(Yt.platform!=="win32")return Yt.env.TERM!=="linux";return Boolean(Yt.env.CI)||Boolean(Yt.env.WT_SESSION)||Boolean(Yt.env.TERMINUS_SUBLIME)||Yt.env.ConEmuTask==="{cmd::Cmder}"||Yt.env.TERM_PROGRAM==="Terminus-Sublime"||Yt.env.TERM_PROGRAM==="vscode"||Yt.env.TERM==="xterm-256color"||Yt.env.TERM==="alacritty"||Yt.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var Rp=Hp();var dt=(t,n)=>Rp?t:n,jp=dt("◆","*"),Pp=dt("■","x"),Gp=dt("▲","x"),Mf=dt("◇","o"),Lp=dt("┌","T"),ut=dt("│","|"),An=dt("└","—"),Xb=dt("┐","T"),_b=dt("┘","—"),bo=dt("●",">"),Cr=dt("○"," "),Kp=dt("◻","[•]"),wf=dt("◼","[+]"),$f=dt("◻","[ ]"),Cb=dt("▪","•"),bf=dt("─","-"),Jp=dt("╮","+"),Ap=dt("├","+"),Up=dt("╯","+"),Tp=dt("╰","+"),xb=dt("╭","+"),Yb=dt("●","•"),zb=dt("◆","*"),Vb=dt("▲","!"),Bb=dt("■","x"),Eo=(t)=>{switch(t){case"initial":case"active":return M("cyan",jp);case"cancel":return M("red",Pp);case"error":return M("yellow",Gp);case"submit":return M("green",Mf)}},vf=(t)=>{switch(t){case"initial":case"active":return M("cyan",ut);case"cancel":return M("red",ut);case"error":return M("yellow",ut);case"submit":return M("green",ut)}};function yf(t,n){let e=[`${n?`${M("cyan",ut)} `:""}${t.join(" • ")}`];return n&&e.push(M("cyan",An)),e}var kf=(t,n,e,r,i,o=!1)=>{let s=n,c=0;if(o)for(let u=r-1;u>=e;u--){let h=t[u];if(h&&(s-=h.length),c++,s<=i)break}else for(let u=e;u<r;u++){let h=t[u];if(h&&(s-=h.length),c++,s<=i)break}return{lineCount:s,removals:c}},ko=({cursor:t,options:n,style:e,output:r=process.stdout,maxItems:i=Number.POSITIVE_INFINITY,columnPadding:o=0,rowPadding:s=4})=>{let c=Zr(r)-o,u=po(r),h=M("dim","..."),f=Math.max(u-s,0),a=Math.max(Math.min(i,f),5),l=0;t>=a-3&&(l=Math.max(Math.min(t-a+3,n.length-a),0));let g=a<n.length&&l>0,d=a<n.length&&l+a<n.length,m=Math.min(l+a,n.length),E=[],y=0;g&&y++,d&&y++;let N=l+(g?1:0),k=m-(d?1:0);for(let $=N;$<k;$++){let H=n[$],b=H?e(H,$===t):"",j=Fn(b,c,{hard:!0,trim:!1}).split(`
|
|
166
|
+
`);E.push(j),y+=j.length}if(y>f){let $=0,H=0,b=y,j=t-N,O=f,L=()=>kf(E,b,0,j,O),P=()=>kf(E,b,j+1,E.length,O,!0);g?({lineCount:b,removals:$}=L(),b>O&&(d||(O-=1),{lineCount:b,removals:H}=P())):(d||(O-=1),{lineCount:b,removals:H}=P(),b>O&&(O-=1,{lineCount:b,removals:$}=L())),$>0&&(g=!0,E.splice(0,$)),H>0&&(d=!0,E.splice(E.length-H,H))}let S=[];g&&S.push(h);for(let $ of E)for(let H of $)S.push(H);return d&&S.push(h),S};var Sf=(t)=>{let n=t.active??"Yes",e=t.inactive??"No";return new wo({active:n,inactive:e,signal:t.signal,input:t.input,output:t.output,initialValue:t.initialValue??!0,render(){let r=t.withGuide??Kt.withGuide,i=`${Eo(this.state)} `,o=r?`${M("gray",ut)} `:"",s=In(t.output,t.message,o,i),c=`${r?`${M("gray",ut)}
|
|
104
167
|
`:""}${s}
|
|
105
|
-
`,u=this.value
|
|
106
|
-
${M("gray",
|
|
107
|
-
|
|
108
|
-
`),
|
|
168
|
+
`,u=this.value?n:e;switch(this.state){case"submit":{let h=r?`${M("gray",ut)} `:"";return`${c}${h}${M("dim",u)}`}case"cancel":{let h=r?`${M("gray",ut)} `:"";return`${c}${h}${M(["strikethrough","dim"],u)}${r?`
|
|
169
|
+
${M("gray",ut)}`:""}`}default:{let h=r?`${M("cyan",ut)} `:"",f=r?M("cyan",An):"";return`${c}${h}${this.value?`${M("green",bo)} ${n}`:`${M("dim",Cr)} ${M("dim",n)}`}${t.vertical?r?`
|
|
170
|
+
${M("cyan",ut)} `:`
|
|
171
|
+
`:` ${M("dim","/")} `}${this.value?`${M("dim",Cr)} ${M("dim",e)}`:`${M("green",bo)} ${e}`}
|
|
172
|
+
${f}
|
|
173
|
+
`}}}}).prompt()};var Wp=[`${M("dim","↑/↓")} to navigate`,`${M("dim","Space:")} select`,`${M("dim","Enter:")} confirm`],Ye=(t,n)=>t.split(`
|
|
174
|
+
`).map((e)=>n(e)).join(`
|
|
175
|
+
`),Ff=(t)=>{let n=(i,o)=>{let s=i.label??String(i.value);return o==="disabled"?`${M("gray",$f)} ${Ye(s,(c)=>M(["strikethrough","gray"],c))}${i.hint?` ${M("dim",`(${i.hint??"disabled"})`)}`:""}`:o==="active"?`${M("cyan",Kp)} ${s}${i.hint?` ${M("dim",`(${i.hint})`)}`:""}`:o==="selected"?`${M("green",wf)} ${Ye(s,(c)=>M("dim",c))}${i.hint?` ${M("dim",`(${i.hint})`)}`:""}`:o==="cancelled"?`${Ye(s,(c)=>M(["strikethrough","dim"],c))}`:o==="active-selected"?`${M("green",wf)} ${s}${i.hint?` ${M("dim",`(${i.hint})`)}`:""}`:o==="submitted"?`${Ye(s,(c)=>M("dim",c))}`:`${M("dim",$f)} ${Ye(s,(c)=>M("dim",c))}`},e=t.required??!0,r=t.showInstructions??!0;return new $o({options:t.options,signal:t.signal,input:t.input,output:t.output,initialValues:t.initialValues,required:e,cursorAt:t.cursorAt,validate(i){if(e&&(i===void 0||i.length===0))return`Please select at least one option.
|
|
176
|
+
${M("reset",M("dim",`Press ${M(["gray","bgWhite","inverse"]," space ")} to select, ${M("gray",M("bgWhite",M("inverse"," enter ")))} to submit`))}`},render(){let i=t.withGuide??Kt.withGuide,o=In(t.output,t.message,i?`${vf(this.state)} `:"",`${Eo(this.state)} `),s=`${i?`${M("gray",ut)}
|
|
177
|
+
`:""}${o}
|
|
178
|
+
`,c=this.value??[],u=(h,f)=>{if(h.disabled)return n(h,"disabled");let a=c.includes(h.value);return f&&a?n(h,"active-selected"):a?n(h,"selected"):n(h,f?"active":"inactive")};switch(this.state){case"submit":{let h=this.options.filter(({value:a})=>c.includes(a)).map((a)=>n(a,"submitted")).join(M("dim",", "))||M("dim","none"),f=In(t.output,h,i?`${M("gray",ut)} `:"");return`${s}${f}`}case"cancel":{let h=this.options.filter(({value:a})=>c.includes(a)).map((a)=>n(a,"cancelled")).join(M("dim",", "));if(h.trim()==="")return`${s}${M("gray",ut)}`;let f=In(t.output,h,i?`${M("gray",ut)} `:"");return`${s}${f}${i?`
|
|
179
|
+
${M("gray",ut)}`:""}`}case"error":{let h=i?`${M("yellow",ut)} `:"",f=this.error.split(`
|
|
180
|
+
`).map((g,d)=>d===0?`${i?`${M("yellow",An)} `:""}${M("yellow",g)}`:` ${g}`).join(`
|
|
181
|
+
`),a=s.split(`
|
|
109
182
|
`).length,l=f.split(`
|
|
110
|
-
`).length+1;return`${
|
|
183
|
+
`).length+1;return`${s}${h}${ko({output:t.output,options:this.options,cursor:this.cursor,maxItems:t.maxItems,columnPadding:h.length,rowPadding:a+l,style:u}).join(`
|
|
111
184
|
${h}`)}
|
|
112
185
|
${f}
|
|
113
|
-
`}default:{let h=i?`${M("cyan",
|
|
114
|
-
`).length,
|
|
115
|
-
`),a
|
|
186
|
+
`}default:{let h=i?`${M("cyan",ut)} `:"",f=s.split(`
|
|
187
|
+
`).length,a=r?yf(Wp,i):i?[M("cyan",An)]:[],l=a.join(`
|
|
188
|
+
`),g=a.length+1;return`${s}${h}${ko({output:t.output,options:this.options,cursor:this.cursor,maxItems:t.maxItems,columnPadding:h.length,rowPadding:f+g,style:u}).join(`
|
|
116
189
|
${h}`)}
|
|
117
190
|
${l}
|
|
118
|
-
`}}}}).prompt()};var
|
|
191
|
+
`}}}}).prompt()};var ze=(t="",n)=>{let e=n?.output??process.stdout,r=n?.withGuide??Kt.withGuide?`${M("gray",An)} `:"";e.write(`${r}${M("red",t)}
|
|
119
192
|
|
|
120
|
-
`)},
|
|
121
|
-
`)},
|
|
122
|
-
${M("gray",
|
|
193
|
+
`)},If=(t="",n)=>{let e=n?.output??process.stdout,r=n?.withGuide??Kt.withGuide?`${M("gray",Lp)} `:"";e.write(`${r}${t}
|
|
194
|
+
`)},Nf=(t="",n)=>{let e=n?.output??process.stdout,r=n?.withGuide??Kt.withGuide?`${M("gray",ut)}
|
|
195
|
+
${M("gray",An)} `:"";e.write(`${r}${t}
|
|
123
196
|
|
|
124
|
-
`)};var
|
|
125
|
-
`),
|
|
126
|
-
`).map(
|
|
127
|
-
`),f=i?`${M("gray",
|
|
128
|
-
`:"",
|
|
197
|
+
`)};var Qp=(t)=>t,qp=(t,n,e)=>{let r={hard:!0,trim:!1},i=Fn(t,n,r).split(`
|
|
198
|
+
`),o=i.reduce((u,h)=>Math.max(Lt(h),u),0),s=i.map(e).reduce((u,h)=>Math.max(Lt(h),u),0),c=n-(s-o);return Fn(t,c,r)},xr=(t="",n="",e)=>{let r=e?.output??Yt.stdout,i=e?.withGuide??Kt.withGuide,o=e?.format??Qp,s=["",...qp(t,Zr(r)-6,o).split(`
|
|
199
|
+
`).map(o),""],c=Lt(n),u=Math.max(s.reduce((l,g)=>{let d=Lt(g);return d>l?d:l},0),c)+2,h=s.map((l)=>`${M("gray",ut)} ${l}${" ".repeat(u-Lt(l))}${M("gray",ut)}`).join(`
|
|
200
|
+
`),f=i?`${M("gray",ut)}
|
|
201
|
+
`:"",a=i?Ap:Tp;r.write(`${f}${M("green",Mf)} ${M("reset",n)} ${M("gray",bf.repeat(Math.max(u-c-1,1))+Jp)}
|
|
129
202
|
${h}
|
|
130
|
-
${M("gray",
|
|
131
|
-
`)};var
|
|
132
|
-
`)?
|
|
133
|
-
`).map((
|
|
134
|
-
`):
|
|
135
|
-
`:""}${
|
|
136
|
-
`;switch(this.state){case"submit":{let
|
|
137
|
-
${M("gray",
|
|
138
|
-
`).length,f=
|
|
139
|
-
`),l=f.length+1;return`${
|
|
140
|
-
${
|
|
141
|
-
${
|
|
142
|
-
`}}}}).prompt()};var
|
|
143
|
-
`)}}
|
|
144
|
-
|
|
145
|
-
`)
|
|
146
|
-
|
|
147
|
-
${r.
|
|
148
|
-
|
|
149
|
-
`)
|
|
150
|
-
`)
|
|
151
|
-
`))}
|
|
152
|
-
`)
|
|
153
|
-
`)}
|
|
154
|
-
`)}
|
|
203
|
+
${M("gray",a+bf.repeat(u+2)+Up)}
|
|
204
|
+
`)};var Db={light:dt("─","-"),heavy:dt("━","="),block:dt("█","#")};var Zp=[`${M("dim","↑/↓")} to navigate`,`${M("dim","Enter:")} confirm`],_r=(t,n)=>t.includes(`
|
|
205
|
+
`)?t.split(`
|
|
206
|
+
`).map((e)=>n(e)).join(`
|
|
207
|
+
`):n(t),Of=(t)=>{let n=(r,i)=>{if(r===void 0)return"";let o=r.label??String(r.value);switch(i){case"disabled":return`${M("gray",Cr)} ${_r(o,(s)=>M("gray",s))}${r.hint?` ${M("dim",`(${r.hint??"disabled"})`)}`:""}`;case"selected":return`${_r(o,(s)=>M("dim",s))}`;case"active":return`${M("green",bo)} ${o}${r.hint?` ${M("dim",`(${r.hint})`)}`:""}`;case"cancelled":return`${_r(o,(s)=>M(["strikethrough","dim"],s))}`;default:return`${M("dim",Cr)} ${_r(o,(s)=>M("dim",s))}`}},e=t.showInstructions??!0;return new Xr({options:t.options,signal:t.signal,input:t.input,output:t.output,initialValue:t.initialValue,render(){let r=t.withGuide??Kt.withGuide,i=`${Eo(this.state)} `,o=`${vf(this.state)} `,s=In(t.output,t.message,o,i),c=`${r?`${M("gray",ut)}
|
|
208
|
+
`:""}${s}
|
|
209
|
+
`;switch(this.state){case"submit":{let u=r?`${M("gray",ut)} `:"",h=In(t.output,n(this.options[this.cursor],"selected"),u);return`${c}${h}`}case"cancel":{let u=r?`${M("gray",ut)} `:"",h=In(t.output,n(this.options[this.cursor],"cancelled"),u);return`${c}${h}${r?`
|
|
210
|
+
${M("gray",ut)}`:""}`}default:{let u=r?`${M("cyan",ut)} `:"",h=c.split(`
|
|
211
|
+
`).length,f=e?yf(Zp,r):r?[M("cyan",An)]:[],a=f.join(`
|
|
212
|
+
`),l=f.length+1;return`${c}${u}${ko({output:t.output,cursor:this.cursor,options:this.options,maxItems:t.maxItems,columnPadding:u.length,rowPadding:h+l,style:(g,d)=>n(g,g.disabled?"disabled":d?"active":"inactive")}).join(`
|
|
213
|
+
${u}`)}
|
|
214
|
+
${a}
|
|
215
|
+
`}}}}).prompt()};var t1=`${M("gray",ut)} `;import{existsSync as Vp}from"node:fs";import{openSync as Xp,writeSync as _p}from"node:fs";import{ReadStream as Cp}from"node:tty";var Rf=["10","11","12","17",...Array.from({length:16},(t,n)=>`4;${n}`)];function Ve(t){return[`\x1B]11;${t.background}\x1B\\`,`\x1B]10;${t.foreground}\x1B\\`,`\x1B]12;${t.cursor}\x1B\\`,`\x1B]17;${t.selection}\x1B\\`,...t.ansi.map((n,e)=>`\x1B]4;${e};${n}\x1B\\`)].join("")}function jf(t){let n=new Map;for(let e of t.split("\x1B")){let r=e.match(/^\](\d+(?:;\d+)?);(rgba?:[0-9a-fA-F/]+)/),[,i,o]=r??[];if(i&&o)n.set(i,o)}return n}function Mo(t){return[...t].map(([n,e])=>`\x1B]${n};${e}\x1B\\`).join("")}async function vo(){let t,n;try{t=Xp("/dev/tty","r+"),n=new Cp(t),n.setRawMode(!0)}catch{return new Map}try{_p(t,Rf.map((r)=>`\x1B]${r};?\x1B\\`).join(""));let e="";return await new Promise((r)=>{let i=setTimeout(r,120);n.on("data",(o)=>{if(e+=o.toString(),jf(e).size>=Rf.length)clearTimeout(i),r()})}),jf(e)}finally{n.setRawMode(!1),n.destroy()}}function oe(t){let n=t.replace("#","");return[n.slice(0,2),n.slice(2,4),n.slice(4,6)].map((e)=>Number.parseInt(e,16)).join(";")}function Pf(t,n){return`\x1B[48;2;${oe(n)}m ${t} \x1B[0m`}function Yr(t,n){return`\x1B[48;2;${oe(t)};38;2;${oe(n)}m ● \x1B[0m`}function Gf(t){return`\x1B[38;2;${oe(t)}m`}function zr(t,n){return`\x1B[48;2;${oe(n)}m${t.map((e)=>`\x1B[38;2;${oe(e)}m▄`).join("")} \x1B[0m`}function Vr(t,n){let e=n.toLowerCase();return[t.name,t.group,t.native??""].some((r)=>r.toLowerCase().includes(e))}function Kf(t,n,e){let r=e.trim(),i=[],o=new Set;for(let s of t){if(s.default||o.has(s.group))continue;o.add(s.group);let c=t.filter((f)=>!f.default&&f.group===s.group),u=r?c.filter((f)=>Vr(f,r)):c;if(r&&u.length===0)continue;let h=r.length>0||n.has(s.group);if(i.push({kind:"group",name:s.group,native:s.native,lead:c.find((f)=>f.lead)??s,expanded:h,count:u.length}),h)i.push(...u.map((f)=>({kind:"palette",entry:f})))}return i}function xp(t,n){let e=n.trim(),r=new Set(t.filter((i)=>!i.default&&(e===""||Vr(i,e))).map((i)=>i.group));return Kf(t,new Set,"").filter((i)=>i.kind==="group"&&r.has(i.name))}function Yp(t){let n=t.findIndex((e)=>e.kind==="palette");return n===-1?0:n}var Jt="\x1B[0m",Nn="\x1B[2m",Jf="\x1B[1m",Lf="\x1B[1;7m",Af="\x1B[36m",zp="\x1B[33m";function Uf(t){return t==="decode"||t==="glitch"?t:"typewriter"}class yo extends hn{picked;scope;entries;named;series;seriesPad;expanded=new Set;rows=[];cursor=0;top=0;maxItems;color;lastInput="";lastFocused="";onFocus;example="";fx;fxStep=0;fxSeed=0;fxTimer;constructor(t){super({render:()=>this.draw(),input:t.input,output:t.output,validate:t.required?()=>this.picked.size===0?`pick at least one ${this.scope}`:void 0:void 0},!0);this.entries=t.entries,this.scope=t.scope??"palette",this.picked=new Set(t.installed??[]),this.named=t.entries.filter((e)=>!e.default),this.series=[...new Set(this.named.map((e)=>e.group))],this.seriesPad=Math.max(0,...this.series.map((e)=>e.length)),this.maxItems=t.maxItems??12,this.color=t.color??!0,this.fx=t.fx??"typewriter",this.onFocus=t.onFocus,this.rollExample();let n=setInterval(()=>{this.rollExample(),this.fxStep=8,this.output.emit("resize")},3000);n.unref?.(),this.once("finalize",()=>{clearInterval(n),clearTimeout(this.fxTimer)}),this.rebuild("first"),this.on("cursor",(e)=>{if(e==="up")this.move(-1);else if(e==="down")this.move(1);else if(e==="left")this.fold(!1);else if(e==="right")this.fold(!0)}),this.on("userInput",(e)=>{if(e!==this.lastInput)this.lastInput=e,this.rebuild("keep")}),this.on("key",(e,r)=>{if(r?.name==="space")this.pick(this.rows[this.cursor])})}_isActionKey(t){return t==="\t"||t===" "}members(t){let n=this.scope==="palette"?this.userInput.trim():"";return this.named.filter((e)=>e.group===t&&(n===""||Vr(e,n)))}everyone(t){return t.flatMap((n)=>n.kind==="group"?this.members(n.name):[])}pick(t){let n=t?.kind==="palette"?[t.entry.name]:t?.kind==="group"?this.members(t.name).map((r)=>r.name):t?.kind==="all"?this.everyone(this.rows).map((r)=>r.name):[];if(n.length===0)return;let e=n.some((r)=>!this.picked.has(r));for(let r of n)if(e)this.picked.add(r);else this.picked.delete(r)}pickedIn(t){return this.members(t).filter((n)=>this.picked.has(n.name)).length}pickedCount(){if(this.scope==="palette")return this.picked.size;return this.series.filter((t)=>this.members(t).every((n)=>this.picked.has(n.name))).length}rollExample(){let t=this.named[Math.floor(Math.random()*this.named.length)],n=this.series[Math.floor(Math.random()*this.series.length)];if(!t||!n){this.example="";return}let e=`${t.name} | ${n}`;this.example=e.length>30?`${e.slice(0,29)}…`:e,this.fxSeed=Math.floor(Math.random()*997)}animatedExample(){if(this.fxStep===0)return this.example;if(!this.fxTimer)this.fxTimer=setTimeout(()=>{this.fxTimer=void 0,this.fxStep-=1,this.output.emit("resize")},60),this.fxTimer.unref?.();let t=Math.floor(this.example.length*(8-this.fxStep)/8);if(this.fx==="typewriter")return`${this.example.slice(0,t)}▏`;let n=this.fx==="decode"?"abcdefghijklmnopqrstuvwxyz":"▓▒░#*+=<>?/-_",e=this.fx==="decode"?(r)=>!/[a-z0-9]/i.test(r):(r)=>r===" ";return[...this.example].map((r,i)=>i+(i*7+this.fxSeed)%3<t||e(r)?r:n[Math.floor(Math.random()*n.length)]??r).join("")}sync(){let t=this.rows[this.cursor],n=t?.kind==="palette"?t.entry:t?.kind==="group"&&this.scope==="series"?t.lead:void 0;if(n&&n.name!==this.lastFocused)this.lastFocused=n.name,this.onFocus?.(n)}rebuild(t){let n=this.rows[this.cursor],e=this.scope==="series"?xp(this.entries,this.userInput):Kf(this.entries,this.expanded,this.userInput),r=e.length>0?Yp(e)+1:0;if(this.rows=e.length>0?[{kind:"all",count:this.allCount(e)},...e]:[],t==="first")this.cursor=r;else if(t==="keep"){let i=n?.kind==="palette"?n.entry.name:"",o=i?this.rows.findIndex((s)=>s.kind==="palette"&&s.entry.name===i):-1;this.cursor=o===-1?r:o}else if(this.cursor>=this.rows.length)this.cursor=Math.max(0,this.rows.length-1);this.sync()}allCount(t){return this.scope==="series"?t.length:this.everyone(t).length}move(t){let n=this.cursor+t;if(n>=0&&n<this.rows.length)this.cursor=n;this.sync()}toggle(t){if(this.expanded.has(t))this.expanded.delete(t);else this.expanded.add(t);this.rebuild("clamp")}fold(t){if(this.userInput||this.scope==="series")return;let n=this.rows[this.cursor];if(n?.kind==="group"){if(t!==n.expanded)this.toggle(n.name)}else if(n?.kind==="palette"&&!t&&!n.entry.default){let e=n.entry.group;if(this.expanded.delete(e),this.rebuild("clamp"),this.cursor=this.rows.findIndex((r)=>r.kind==="group"&&r.name===e),this.cursor===-1)this.cursor=0;this.sync()}}renderRow(t,n){let e=n?"▶ ":" ";if(t.kind==="all"){let o=this.everyone(this.rows).every((c)=>this.picked.has(c.name))?"● ":"○ ",s=`(${t.count})`;return`${e}${o}select all ${this.color?`${Nn}${s}${Jt}`:s}`}if(t.kind==="group"&&this.scope==="series"){let o=this.pickedIn(t.name)===t.count?"● ":"○ ",s=t.name.padEnd(this.seriesPad),c=`(${t.count})${t.native?` ${t.native}`:""}`;if(!this.color)return`${e}${o}${s} ${c}`;let u=t.lead;return`${e}${o}${s} ${Yr(u.background,u.cursor)}${zr(u.ansi.slice(1,7),u.background)} ${Nn}${c}${Jt}`}if(t.kind==="group"){let o=t.expanded?"▾":"▸",s=this.rows[this.cursor],c=s?.kind==="palette"&&s.entry.group===t.name?s.entry:void 0,u=this.color?n?`${Lf} ${t.name} ${Jt}`:c?`${Lf}${Gf(c.cursor)} ${t.name} ${Jt}`:` ${Jf}${t.name}${Jt} `:n?`[${t.name}]`:` ${t.name}`,h=this.color?Pf("●",t.lead.selection):"",f=`${this.pickedIn(t.name)}/${t.count}`,a=this.color?` ${Nn}(${f})${Jt}`:` (${f})`,l=t.native?this.color?` ${Nn}${t.native}${Jt}`:` ${t.native}`:"";return`${o}${u}${h}${a}${l}`}let r=t.entry,i=this.picked.has(r.name)?"● ":"○ ";if(!this.color)return` ${e}${i}${r.name.padEnd(13)} ● · ${r.ansiSource}`;return` ${e}${i}${r.name.padEnd(13)} ${Yr(r.background,r.cursor)}${zr(r.ansi.slice(1,7),r.background)} ${Nn}${r.ansiSource}${Jt}`}draw(){let t=(m)=>this.color?`${Nn}${m}${Jt}`:m,n=(m)=>this.color?`${Af}${m}${Jt}`:m,e=this.scope==="series"?"series":"catalog";if(this.state==="submit")return`${t("◇")} ${e} ${t(`· ${this.pickedCount()} picked`)}`;if(this.state==="cancel")return`${t(`◇ ${e} · cancelled`)}`;let r=this.userInput.trim(),i=this.scope==="series"?this.series.length:this.named.length,o=this.scope==="series"?this.rows.filter((m)=>m.kind==="group").length:r?this.named.filter((m)=>Vr(m,r)).length:i,s=`${n("◆")} ${e} ${t(`(${o}/${i} · ${this.pickedCount()} picked)`)}`,c=`${n("│")} ${this.userInput?`⌕ ${this.userInput}_`:t(`⌕ search…${this.example?` e.g. ${this.animatedExample()}`:""}`)}`;if(this.cursor<this.top)this.top=this.cursor;if(this.cursor>=this.top+this.maxItems)this.top=this.cursor-this.maxItems+1;this.top=Math.min(this.top,Math.max(0,this.rows.length-this.maxItems));let u=this.rows.slice(this.top,this.top+this.maxItems),h=u.length>0?u.map((m,E)=>`${n("│")} ${this.renderRow(m,this.top+E===this.cursor)}`):[`${n("│")} ${t(`no ${this.scope==="series"?"series":"palettes"} match '${this.userInput}'`)}`];while(h.length<this.maxItems)h.push(n("│"));let f=this.rows.length-this.top-u.length,a=f>0?`${n("│")} ${t(`↓ ${f} more`)}`:n("│"),l=this.scope==="series"?"":" · ←→ fold",g=this.scope==="series"?"continue":"install",d=this.state==="error"?`${n("└")} ${this.color?`${zp}${this.error}${Jt}`:this.error}`:`${n("└")} ${t(`↑↓ move${l} · space pick · type to filter · enter ${g} · esc cancel`)}`;return[s,c,...h,a,d].join(`
|
|
216
|
+
`)}}class So extends Xr{entries;top=0;maxItems;color;namePad;constructor(t){super({options:t.entries.map((e)=>({value:e.name})),input:t.input,output:t.output,render:()=>this.draw()});this.entries=t.entries,this.maxItems=t.maxItems??12,this.color=t.color??!0,this.namePad=Math.max(0,...t.entries.map((e)=>e.name.length));let n=()=>{let e=this.entries[this.cursor];if(e)t.onFocus?.(e)};n(),this.on("cursor",n)}row(t,n){let e=n?"▶ ":" ",r=t.name.padEnd(this.namePad);if(!this.color)return`${e}${r} ${t.group}`;let i=n?`${Jf}${r}${Jt}`:r;return`${e}${i} ${Yr(t.background,t.cursor)}${zr(t.ansi.slice(1,7),t.background)} ${Nn}${t.group}${Jt}`}draw(){let t=(h)=>this.color?`${Nn}${h}${Jt}`:h,n=(h)=>this.color?`${Af}${h}${Jt}`:h,e=this.entries[this.cursor]?.name??"";if(this.state==="submit")return`${t("◇")} default palette ${t(`· ${e}`)}`;if(this.state==="cancel")return`${t("◇ default palette · cancelled")}`;if(this.cursor<this.top)this.top=this.cursor;if(this.cursor>=this.top+this.maxItems)this.top=this.cursor-this.maxItems+1;let r=this.entries.slice(this.top,this.top+this.maxItems),i=`${n("◆")} default palette ${t(`(${this.cursor+1}/${this.entries.length})`)}`,o=r.map((h,f)=>`${n("│")} ${this.row(h,this.top+f===this.cursor)}`),s=this.entries.length-this.top-r.length,c=s>0?`${n("│")} ${t(`↓ ${s} more`)}`:n("│"),u=`${n("└")} ${t("↑↓ try on · enter choose · esc cancel")}`;return[i,...o,c,u].join(`
|
|
217
|
+
`)}}function Fo(t,n,e,r){let i=Bn(),o=Boolean(Dn(e))!==Boolean(Dn(r)),s=o?qe(r,i):r;if(_e(t,n,s),Xe(t,s),o)Ze(s,i)}function Io(t){console.log(`
|
|
218
|
+
${t} palettes installed — open a new tab, or reload your terminal config`)}function Tf(t){let n=Dt(),e=Ut(n),r=mn(n),i=t.filter((c)=>r.palettes.includes(c)),o=t.filter((c)=>!r.palettes.includes(c));if(o.length===0){console.log(`already installed: ${i.join(", ")}`);return}let s={...r,palettes:[...r.palettes,...o]};Fo(n,e,r,s);for(let c of o)console.log(` + ${c}`);Io(s.palettes.length)}function Wf(t){let n=Dt(),e=Ut(n),r=mn(n),i=t.filter((s)=>r.palettes.includes(s));if(i.length===0){console.log(`not installed: ${t.join(", ")}`);return}let o={...r,palettes:r.palettes.filter((s)=>!i.includes(s))};Fo(n,e,r,o),Bi(n,e,r.terminals,i);for(let s of i)console.log(` - ${s}`);Io(o.palettes.length)}function Qf(t){let n=Dt(),e=Ut(n),r=mn(n);if(!r.palettes.includes(t))throw Error(`${t} is not installed — \`ttheme add ${t}\` first`);let{keepTheme:i,...o}=r,s=Bn(),c=qe({...o,startup:t},s);_e(n,e,c),Xe(n,c);let u=Ze(c,s);console.log(Bp(t,c.terminals,u&&s.running()).join(`
|
|
219
|
+
`))}function Bp(t,n,e){let r=n.filter((o)=>o!=="iterm2"),i=r.length>0?[`default ${t} · ${r.join(", ")} open new tabs with it once their config reloads`]:[];if(n.includes("iterm2"))i.push(e?'iterm2 new tabs open with it once iTerm2 restarts — "ttheme · default" is now its default profile':'iterm2 new tabs open with it — "ttheme · default" is its default profile');return i.length>0?i:[`default ${t} · no terminal is wired to open with it — \`ttheme init\` wires one`]}function qf(t){let n=Dt(),e=Ut(n),r=new Set(mn(n).palettes),i=xn(e.palettes),o=Re(t?Xu(i,t):i),s=Math.max(...o.map((u)=>u.name.length),0);for(let u of o)console.log(` ${r.has(u.name)?"●":"○"} ${u.name.padEnd(s)} ${u.group}`);let c=t?`${o.length} of ${i.length}`:`${i.length}`;console.log(`
|
|
220
|
+
${c} palettes — ${o.filter((u)=>r.has(u.name)).length} installed`)}async function Zf(){let t=Dt(),n=Vp(Or(t))?Ut(t).palettes.length:0,e=await qu(Wu);Hr(t,e);let r=e.palettes.length-n;console.log(`catalog ${e.version} — ${e.palettes.length} palettes${r>0?` (+${r})`:""}`)}async function No(t,n,e,r=!1){let i=process.env.TTHEME_SORT==="series"?t.palettes:Re(t.palettes),o=process.stdout.isTTY===!0&&!process.env.NO_COLOR,s=o?await vo():new Map,c=new yo({entries:i,scope:e,installed:n,required:r,color:!process.env.NO_COLOR,fx:Uf(process.env.TTHEME_FX),onFocus:o?(h)=>process.stdout.write(Ve(h)):void 0}),u=await c.prompt();if(process.stdout.write(Mo(s)),Jn(u))return;return t.palettes.filter((h)=>c.picked.has(h.name)).map((h)=>h.name)}async function Xf(t,n){let e=process.stdout.isTTY===!0&&!process.env.NO_COLOR,r=e?await vo():new Map,o=await new So({entries:t.palettes.filter((s)=>n.includes(s.name)),color:!process.env.NO_COLOR,onFocus:e?(s)=>process.stdout.write(Ve(s)):void 0}).prompt();return process.stdout.write(Mo(r)),Jn(o)?void 0:o}async function _f(){let t=Dt(),n=Ut(t),e=mn(t),r=await No(n,e.palettes,"palette");if(!r){console.log("nothing changed");return}let i=e.palettes.filter((c)=>!r.includes(c)),o=r.filter((c)=>!e.palettes.includes(c));if(o.length===0&&i.length===0){console.log("nothing changed");return}let s={...e,palettes:r};Fo(t,n,e,s),Bi(t,n,e.terminals,i);for(let c of o)console.log(` + ${c}`);for(let c of i)console.log(` - ${c}`);Io(s.palettes.length)}function Yf(t,n,e){for(let r of e0(n))t.push({from:ht(n,r),to:ht(e,r)})}function Df(t){return JSON.parse(ce(ht(t,"dist","manifest.json"),"utf8"))}function zf(t,n){let e=ht(n.root,"dist"),r=ht(n.configHome,"ttheme"),i=[{from:ht(n.root,"bin","ttheme.js"),to:ht(r,"ttheme.js")},{from:ht(n.root,"shell","ttheme.zsh"),to:ht(r,"ttheme.zsh")},{from:ht(n.root,"shell","launch-tab.zsh"),to:ht(r,"launch-tab.zsh"),executable:!0},{from:ht(e,"ghostty","ttheme.conf"),to:ht(r,"ttheme.conf")}];Yf(i,ht(n.root,"shell","adapters"),ht(r,"adapters"));let o=[{file:ht(n.zdotdir,".zshrc"),block:hu(r)}],s=ht(r,"config.zsh"),c=au(Qt(s)?ce(s,"utf8"):""),u={file:s,content:t.wear?$r(c,"TTHEME_TAB_PALETTE",t.wear==="rotate"?"seq":"off"):c},h=[];if(t.terminals.includes("ghostty"))Yf(i,ht(n.root,"ghostty","shaders"),ht(n.configHome,"ghostty","shaders"));if(t.terminals.includes("alacritty")){let l=Vi(n.configHome);if(Qt(l)&&br(ce(l,"utf8"),void 0)===void 0)h.push(`${l} already imports files under [general] — ttheme left it alone; add ${ht(n.configHome,"alacritty","themes")}/<palette>.toml to that import list yourself`)}if(t.terminals.includes("wezterm")){let l=zi(n.configHome,n.home);if(Qt(l)&&kr(ce(l,"utf8"),"")===void 0)h.push(`${l} has no \`return config\` line — ttheme left it alone; call \`dofile("${ht(r,"wezterm.lua")}")(config)\` from it yourself`)}let f=t.terminals.includes("windows-terminal");if(f&&!n.wtHome)h.push("windows terminal: %LOCALAPPDATA% was not found — drop the release fragment into its Fragments folder yourself");if(t.terminals.includes("warp"))h.push("warp: wears the default palette app-wide through its settings.toml — the shell layer stays off in it, since Warp paints no tab background of its own");let a={terminals:t.terminals,palettes:t.palettes,...t.startup?{startup:t.startup}:{},...t.wear==="keep"?{keepTheme:!0}:{},...f&&n.wtHome?{wtHome:n.wtHome}:{},...f&&n.wtProfile?{wtProfile:n.wtProfile}:{}};return{home:n.home,copies:i,edits:o,settings:u,catalog:Df(n.root),installed:a,notes:h}}function i0(t){try{return mn(t).itermBase}catch{return}}function Vf(t,n=Bn()){for(let o of t.copies)if(Oo(se(o.to),{recursive:!0}),Cf(o.to,{force:!0}),Cf(`${o.to}.zwc`,{force:!0}),n0(o.from,o.to),o.executable)t0(o.to,493);Oo(se(t.settings.file),{recursive:!0}),xf(t.settings.file,t.settings.content);let e=se(se(t.settings.file)),r=i0(e),i=qe(r?{...t.installed,itermBase:r}:t.installed,n);Hr(e,t.catalog),Xe(e,i),_e(e,t.catalog,i,t.home);for(let o of t.edits){Oo(se(o.file),{recursive:!0});let s=Qt(o.file)?ce(o.file,"utf8"):"";xf(o.file,je(s,o.block))}return Ze(i,n)}function Ho(t){if(Jn(t))ze("nothing changed"),process.exit(1);return t}function ta(t){return pr.filter((n)=>{if(n==="iterm2")return process.platform==="darwin";if(n==="windows-terminal")return t.wtHome!==void 0;return n!=="warp"||process.platform!=="win32"})}function o0(t,n){if(t==="iterm2")return Qt(ht(n.home,"Library","Application Support","iTerm2"));if(t==="windows-terminal")return n.wtHome!==void 0;if(t==="warp")return Qt(se(Jr(n.home)));if(t==="wezterm")return Qt(ht(n.configHome,"wezterm"))||Qt(ht(n.home,".wezterm.lua"));return Qt(ht(n.configHome,t))}function s0(){if(process.platform==="win32")return process.env.LOCALAPPDATA;if(!process.env.WSL_DISTRO_NAME)return;let t=(n,e)=>Dp(n,e,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();try{return t("wslpath",["-u",t("cmd.exe",["/d","/c","echo %LOCALAPPDATA%"])])||void 0}catch{return}}async function c0(t,n,e){return Ho(await Ff({message:"wire which terminals?",options:ta(e).map((r)=>({value:r,hint:r===t?"detected":void 0})),initialValues:n,required:!0}))}function u0(t,n){if(t==="keep")return"leave the terminal colors as they are";return t==="rotate"?`paint every new tab with the next palette, this tab with ${n} now`:`paint every tab with ${n}, this one now`}async function h0(t){return Ho(await Of({message:"how should the terminal wear them?",options:[{value:"default",label:"default",hint:t.length>1?"every tab wears one palette — pick it next":`every tab wears ${t[0]}`},{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 Bf(t){let n=[...t.copies.filter((e)=>!Qt(e.to)).map((e)=>e.to),...Qt(t.settings.file)?[]:[t.settings.file],...t.edits.filter((e)=>!ce(e.file,"utf8").includes("# ttheme begin")).map((e)=>e.file)];if(n.length>0)throw Error(`init left gaps:
|
|
221
|
+
${n.join(`
|
|
222
|
+
`)}`)}function na(t,n){return[...new Set(t.palettes.filter((e)=>n.includes(e.name)).map((e)=>e.group))]}function f0(t,n){let e=t.palettes.find((i)=>i.name===te(n)),r=process.stdout.isTTY===!0&&!process.env.NO_COLOR&&!process.env.TMUX&&Ri(process.env)!=="warp";if(!e||!r)return!1;return process.stdout.write(Ve(e)),!0}function a0(t,n,e){if(t==="keep")return["terminal colors left alone — paint a tab with `ttheme <palette>`"," `ttheme default <palette>` sets the terminal default"];return[`default ${n}${e?" — this tab wears it already":""}`,t==="rotate"?"new tabs rotate through the palettes — change with `ttheme config`":`new tabs all wear ${n} — change with \`ttheme config\``]}function l0(t,n,e,r,i){let o=na(t.catalog,n.palettes);xr([`${o.join(", ")} (${n.palettes.length})`,...a0(e,te(t.installed),r)].join(`
|
|
223
|
+
`),`installed ${n.palettes.length} palettes`);let s=["exec zsh the ttheme command in this tab"];if(n.terminals.includes("ghostty"))s.push("restart ghostty new tabs pick up its config");if(n.terminals.includes("kitty"))s.push("new kitty window pictures follow it — kitty reloads its colors by itself");if(n.terminals.includes("alacritty"))s.push("alacritty reloads its config by itself");if(n.terminals.includes("wezterm"))s.push("wezterm reloads its config by itself");if(n.terminals.includes("windows-terminal"))s.push("windows terminal reloads its settings by itself");if(n.terminals.includes("iterm2"))s.push(...g0(e==="default"?te(t.installed):void 0,i));xr([...s,...t.notes].join(`
|
|
224
|
+
`),"next"),Nf("done")}function g0(t,n){let e=['iterm2 profiles a "ttheme · <palette>" per palette in Settings › Profiles'];if(t)e.push(n?`restart iterm2 new tabs open on "ttheme · default", which wears ${t}`:`iterm2 default "ttheme · default" wears ${t} and follows \`ttheme default\``);return e}function d0(t,n){let e=[`placed ${t.copies.length} files`,`settings in ${t.settings.file} — edit later with \`ttheme config\``,...t.edits.map((r)=>`wired ${r.file}`)];if(n.terminals.includes("ghostty"))e.push("restart ghostty to pick up its config");if(n.terminals.includes("kitty"))e.push("kitty reloads its colors by itself; pictures show in kitty windows opened from now on");if(n.terminals.includes("alacritty"))e.push("alacritty reloads its config by itself");if(n.terminals.includes("wezterm")||n.terminals.includes("windows-terminal"))e.push("wezterm and windows terminal reload their config by themselves");if(n.terminals.includes("iterm2"))e.push('iterm2 gets a "ttheme · <palette>" profile per palette under Settings › Profiles');e.push(...t.notes),e.push("no palettes yet — open a new shell (`exec zsh`), then `ttheme browse` picks them from the catalog"),console.log(e.join(`
|
|
225
|
+
`))}async function ea(t={}){let n=ht(import.meta.dirname,"..");if(!Qt(ht(n,"bin","ttheme.js")))throw Error("bin/ttheme.js is missing — run `mise run bin:build` first");if(!Qt(ht(n,"dist"))){if(typeof Bun>"u")throw Error("this package is missing dist/ — reinstall @kecan0406/ttheme");await Mr()}let e=r0(),r=process.env.XDG_CONFIG_HOME??ht(e,".config"),i=process.env.ZDOTDIR??e,o=s0(),s=process.env.WT_PROFILE_ID,c={root:n,home:e,configHome:r,zdotdir:i,...o?{wtHome:o}:{},...s?{wtProfile:s}:{}},u=Ri(process.env),h=ta(c).filter((H)=>H===u||o0(H,c));if(!(!t.yes&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0)){if(h.length===0)throw Error("no supported terminal detected — run this inside ghostty, kitty, alacritty, wezterm, iterm2, windows terminal or warp");let H={terminals:h,palettes:[]},b=zf(H,c);Vf(b),Bf(b),d0(b,H);return}If("ttheme init");let a=await c0(u,h,c),l=Df(n),g=await No(l,[],"series",!0);if(!g)ze("nothing changed"),process.exit(1);let d=await h0(g),m=d==="default"&&g.length>1,E=m?await Xf(l,g):void 0;if(m&&!E)ze("nothing changed"),process.exit(1);let y=te({terminals:a,palettes:g,startup:E}),N={terminals:a,palettes:g,wear:d,startup:E},k=zf(N,c);if(xr([`install ${g.length} palettes — ${na(k.catalog,g).join(", ")}`,`copy ${k.copies.length} files under ${r}`,`write ${k.settings.file}`,...k.edits.map((H)=>`edit ${H.file}`),u0(d,y),...a.includes("iterm2")&&d!=="keep"?['make "ttheme · default" the iTerm2 default profile']:[]].join(`
|
|
226
|
+
`),`wiring ${a.join(", ")}`),!Ho(await Sf({message:"apply these changes?"})))ze("nothing changed"),process.exit(1);let S=Bn(),$=Vf(k,S);Bf(k),l0(k,N,d,d!=="keep"&&f0(k.catalog,k.installed),$&&S.running())}var sa=[{name:"build",args:[],about:"emit dist/ for every terminal, plus the zsh palette table",flags:{only:{type:"string",multiple:!0,value:"<terminal>",choices:Fu,about:"rebuild just this terminal — repeat it for more"}},run:(t,{only:n})=>Mr({only:n})},{name:"init",args:[],about:"install the palettes and wire your terminal configs",flags:{yes:{type:"boolean",about:"accept every default without prompting"}},run:(t,{yes:n})=>ea({yes:n})},{name:"browse",args:[],about:"pick palettes from the catalog in a live picker",run:()=>_f()},{name:"list",args:["[query]"],about:"show the catalog, marking what is installed",run:([t])=>qf(t)},{name:"add",args:["<palette...>"],about:"install palettes from the catalog",run:(t)=>Tf(t)},{name:"remove",args:["<palette...>"],about:"uninstall palettes",run:(t)=>Wf(t)},{name:"default",args:["<palette>"],about:"make an installed palette the one new tabs open with",run:([t])=>Qf(t)},{name:"find",args:["<palette>"],about:"pick a booru background for a palette — preview opens this on tab",hidden:!0,run:([t])=>Xh(t)},{name:"image",args:["<palette>","<action>"],about:"switch a palette between its saved backgrounds, remove the one shown, or pass on tuning — preview calls this",hidden:!0,run:([t,n])=>_h(t,n)},{name:"update",args:[],about:"refresh the catalog from the registry",run:()=>Zf()}];class Un extends Error{verb;constructor(t,n){super(t);this.verb=n}}function ra(t){let n=sa.find((e)=>e.name===t);if(!n)throw new Un(t.startsWith("-")?`unknown option '${t}'`:`unknown command '${t}'`);return n}function p0(t,n){let e={help:{type:"boolean",short:"h"}};for(let[r,{type:i,multiple:o}]of Object.entries(t.flags??{}))e[r]={type:i,multiple:o===!0};try{return m0({args:n,options:e,allowPositionals:!0})}catch(r){let[i=""]=(r instanceof Error?r.message:String(r)).split(". ");throw new Un(`${i.charAt(0).toLowerCase()}${i.slice(1)}`,t)}}function w0(t){let[n,...e]=t;if(n===void 0)return{kind:"help",code:1};if(n==="-h"||n==="--help")return{kind:"help",code:0};if(n==="-V"||n==="--version")return{kind:"version"};if(n==="help")return e[0]===void 0?{kind:"help",code:0}:{kind:"help",verb:ra(e[0]),code:0};let r=ra(n),i=p0(r,e);if(i.values.help)return{kind:"help",verb:r,code:0};for(let[f,{choices:a}]of Object.entries(r.flags??{}))for(let l of[i.values[f]??[]].flat())if(a&&!a.includes(String(l)))throw new Un(`--${f} takes ${a.join(", ")} — not ${l}`,r);let o=i.positionals,s=r.args.filter((f)=>f.startsWith("<")).length,c=r.args.some((f)=>f.includes("..."))?Number.POSITIVE_INFINITY:r.args.length;if(o.length<s)throw new Un(`missing ${r.args[o.length]}`,r);if(o.length>c)throw new Un(`too many arguments: ${o.slice(c).join(" ")}`,r);let{help:u,...h}=i.values;return{kind:"run",verb:r,args:o,flags:h}}function ia(t){let n=Object.entries(t.flags??{}).map(([e,{value:r}])=>`[--${e}${r?` ${r}`:""}]`);return[t.name,...n,...t.args].join(" ")}function oa(t){let n=Math.max(...t.map(([e])=>e.length));return t.map(([e,r])=>` ${e.padEnd(n)} ${r}`)}function Ro(t){if(t){let n=Object.entries(t.flags??{}).map(([e,{value:r,about:i}])=>[`--${e}${r?` ${r}`:""}`,i]);return[`Usage: ttheme ${ia(t)}`,"",t.about,...n.length>0?["","Options:",...oa(n)]:[]].join(`
|
|
227
|
+
`)}return["Usage: ttheme <command>","",nn.description,"","Commands:",...oa(sa.filter((n)=>!n.hidden).map((n)=>[ia(n),n.about])),"","ttheme <command> --help describes one command · ttheme --version prints the version"].join(`
|
|
228
|
+
`)}async function ca(t){try{let n=w0(t);if(n.kind==="version")return console.log(nn.version),0;if(n.kind==="help"){if(n.code===0)console.log(Ro(n.verb));else console.error(Ro(n.verb));return n.code}let e=await n.verb.run(n.args,n.flags);return typeof e==="number"?e:0}catch(n){if(n instanceof Un)return console.error(`ttheme${n.verb?` ${n.verb.name}`:""}: ${n.message}
|
|
155
229
|
|
|
156
|
-
${
|
|
157
|
-
${
|
|
230
|
+
${Ro(n.verb)}`),1;return console.error(`
|
|
231
|
+
${n instanceof Error?n.message:String(n)}`),1}}if($0)process.exitCode=await ca(process.argv.slice(2));
|