@kecan0406/ttheme 1.1.4 → 1.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/ttheme.js CHANGED
@@ -1,74 +1,74 @@
1
1
  #!/usr/bin/env node
2
- import{createRequire as gw}from"node:module";var aw=Object.create;var{getPrototypeOf:uw,defineProperty:El,getOwnPropertyNames:cw}=Object;var lw=Object.prototype.hasOwnProperty;function hw(e){return this[e]}var fw,dw,Ts=(e,t,n)=>{var r=e!=null&&typeof e==="object";if(r){var i=t?fw??=new WeakMap:dw??=new WeakMap,s=i.get(e);if(s)return s}n=e!=null?aw(uw(e)):{};let o=t||!e||!e.__esModule?El(n,"default",{value:e,enumerable:!0}):n;for(let a of cw(e))if(!lw.call(o,a))El(o,a,{get:hw.bind(e,a),enumerable:!0});if(r)i.set(e,o);return o};var Pe=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Be=gw(import.meta.url);var Ia=Pe((bM,Ul)=>{var Sa={to(e,t){if(!t)return`\x1B[${e+1}G`;return`\x1B[${t+1};${e+1}H`},move(e,t){let n="";if(e<0)n+=`\x1B[${-e}D`;else if(e>0)n+=`\x1B[${e}C`;if(t<0)n+=`\x1B[${-t}A`;else if(t>0)n+=`\x1B[${t}B`;return n},up:(e=1)=>`\x1B[${e}A`,down:(e=1)=>`\x1B[${e}B`,forward:(e=1)=>`\x1B[${e}C`,backward:(e=1)=>`\x1B[${e}D`,nextLine:(e=1)=>"\x1B[E".repeat(e),prevLine:(e=1)=>"\x1B[F".repeat(e),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},Fw={up:(e=1)=>"\x1B[S".repeat(e),down:(e=1)=>"\x1B[T".repeat(e)},Pw={screen:"\x1B[2J",up:(e=1)=>"\x1B[1J".repeat(e),down:(e=1)=>"\x1B[J".repeat(e),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(e){let t="";for(let n=0;n<e;n++)t+=this.line+(n<e-1?Sa.up():"");if(e)t+=Sa.left;return t}};Ul.exports={cursor:Sa,scroll:Fw,erase:Pw,beep:"\x07"}});var wh=Pe((xM,Vs)=>{var ph=ph||function(e){return Buffer.from(e).toString("base64")};function Mb(e){var t=this,n=Math.round,r=Math.floor,i=Array(64),s=Array(64),o=Array(64),a=Array(64),u,c,l,h,f=Array(65535),d=Array(65535),g=Array(64),m=Array(64),b=[],p=0,E=7,v=Array(64),S=Array(64),w=Array(64),N=Array(256),y=Array(2048),R,P=[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],G=[0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0],A=[0,1,2,3,4,5,6,7,8,9,10,11],_=[0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,125],C=[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],H=[0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0],O=[0,1,2,3,4,5,6,7,8,9,10,11],K=[0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,119],Ee=[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 le($){var U=[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 W=r((U[q]*$+50)/100);if(W<1)W=1;else if(W>255)W=255;i[P[q]]=W}var B=[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 fe=r((B[X]*$+50)/100);if(fe<1)fe=1;else if(fe>255)fe=255;s[P[X]]=fe}var de=[1,1.387039845,1.306562965,1.175875602,1,0.785694958,0.5411961,0.275899379],Ue=0;for(var Fe=0;Fe<8;Fe++)for(var I=0;I<8;I++)o[Ue]=1/(i[P[Ue]]*de[Fe]*de[I]*8),a[Ue]=1/(s[P[Ue]]*de[Fe]*de[I]*8),Ue++}function D($,U){var q=0,W=0,B=[];for(var X=1;X<=16;X++){for(var fe=1;fe<=$[X];fe++)B[U[W]]=[],B[U[W]][0]=q,B[U[W]][1]=X,W++,q++;q*=2}return B}function Ge(){u=D(G,A),c=D(H,O),l=D(_,C),h=D(K,Ee)}function ge(){var $=1,U=2;for(var q=1;q<=15;q++){for(var W=$;W<U;W++)d[32767+W]=q,f[32767+W]=[],f[32767+W][1]=q,f[32767+W][0]=W;for(var B=-(U-1);B<=-$;B++)d[32767+B]=q,f[32767+B]=[],f[32767+B][1]=q,f[32767+B][0]=U-1+B;$<<=1,U<<=1}}function oe(){for(var $=0;$<256;$++)y[$]=19595*$,y[$+256>>0]=38470*$,y[$+512>>0]=7471*$+32768,y[$+768>>0]=-11059*$,y[$+1024>>0]=-21709*$,y[$+1280>>0]=32768*$+8421375,y[$+1536>>0]=-27439*$,y[$+1792>>0]=-5329*$}function ee($){var U=$[0],q=$[1]-1;while(q>=0){if(U&1<<q)p|=1<<E;if(q--,E--,E<0){if(p==255)k(255),k(0);else k(p);E=7,p=0}}}function k($){b.push($)}function j($){k($>>8&255),k($&255)}function ve($,U){var q,W,B,X,fe,de,Ue,Fe,I=0,L,Z=8,He=64;for(L=0;L<Z;++L){q=$[I],W=$[I+1],B=$[I+2],X=$[I+3],fe=$[I+4],de=$[I+5],Ue=$[I+6],Fe=$[I+7];var x=q+Fe,ie=q-Fe,Se=W+Ue,Q=W-Ue,pe=B+de,Ze=B-de,Ae=X+fe,pt=X-fe,Ut=x+Ae,jn=x-Ae,pr=Se+pe,wr=Se-pe;$[I]=Ut+pr,$[I+4]=Ut-pr;var ci=(wr+jn)*0.707106781;$[I+2]=jn+ci,$[I+6]=jn-ci,Ut=pt+Ze,pr=Ze+Q,wr=Q+ie;var li=(Ut-wr)*0.382683433,Rs=0.5411961*Ut+li,hi=1.306562965*wr+li,fi=pr*0.707106781,di=ie+fi,gi=ie-fi;$[I+5]=gi+Rs,$[I+3]=gi-Rs,$[I+1]=di+hi,$[I+7]=di-hi,I+=8}I=0;for(L=0;L<Z;++L){q=$[I],W=$[I+8],B=$[I+16],X=$[I+24],fe=$[I+32],de=$[I+40],Ue=$[I+48],Fe=$[I+56];var cl=q+Fe,ka=q-Fe,ll=W+Ue,hl=W-Ue,fl=B+de,dl=B-de,gl=X+fe,ow=X-fe,mi=cl+gl,ya=cl-gl,Fs=ll+fl,Ps=ll-fl;$[I]=mi+Fs,$[I+32]=mi-Fs;var ml=(Ps+ya)*0.707106781;$[I+16]=ya+ml,$[I+48]=ya-ml,mi=ow+dl,Fs=dl+hl,Ps=hl+ka;var pl=(mi-Ps)*0.382683433,wl=0.5411961*mi+pl,bl=1.306562965*Ps+pl,$l=Fs*0.707106781,kl=ka+$l,yl=ka-$l;$[I+40]=yl+wl,$[I+24]=yl-wl,$[I+8]=kl+bl,$[I+56]=kl-bl,I++}var Os;for(L=0;L<He;++L)Os=$[L]*U[L],g[L]=Os>0?Os+0.5|0:Os-0.5|0;return g}function Me(){j(65504),j(16),k(74),k(70),k(73),k(70),k(0),k(1),k(1),k(0),j(1),j(1),k(0),k(0)}function ae($){if(!$)return;if(j(65505),$[0]===69&&$[1]===120&&$[2]===105&&$[3]===102)j($.length+2);else j($.length+5+2),k(69),k(120),k(105),k(102),k(0);for(var U=0;U<$.length;U++)k($[U])}function ue($,U){j(65472),j(17),k(8),j(U),j($),k(3),k(1),k(17),k(0),k(2),k(17),k(1),k(3),k(17),k(1)}function ne(){j(65499),j(132),k(0);for(var $=0;$<64;$++)k(i[$]);k(1);for(var U=0;U<64;U++)k(s[U])}function T(){j(65476),j(418),k(0);for(var $=0;$<16;$++)k(G[$+1]);for(var U=0;U<=11;U++)k(A[U]);k(16);for(var q=0;q<16;q++)k(_[q+1]);for(var W=0;W<=161;W++)k(C[W]);k(1);for(var B=0;B<16;B++)k(H[B+1]);for(var X=0;X<=11;X++)k(O[X]);k(17);for(var fe=0;fe<16;fe++)k(K[fe+1]);for(var de=0;de<=161;de++)k(Ee[de])}function F($){if(typeof $>"u"||$.constructor!==Array)return;$.forEach((U)=>{if(typeof U!=="string")return;j(65534);var q=U.length;j(q+2);var W;for(W=0;W<q;W++)k(U.charCodeAt(W))})}function Re(){j(65498),j(12),k(3),k(1),k(0),k(2),k(17),k(3),k(17),k(0),k(63),k(0)}function Y($,U,q,W,B){var X=B[0],fe=B[240],de,Ue=16,Fe=63,I=64,L=ve($,U);for(var Z=0;Z<I;++Z)m[P[Z]]=L[Z];var He=m[0]-q;if(q=m[0],He==0)ee(W[0]);else de=32767+He,ee(W[d[de]]),ee(f[de]);var x=63;for(;x>0&&m[x]==0;x--);if(x==0)return ee(X),q;var ie=1,Se;while(ie<=x){var Q=ie;for(;m[ie]==0&&ie<=x;++ie);var pe=ie-Q;if(pe>=Ue){Se=pe>>4;for(var Ze=1;Ze<=Se;++Ze)ee(fe);pe=pe&15}de=32767+m[ie],ee(B[(pe<<4)+d[de]]),ee(f[de]),ie++}if(x!=Fe)ee(X);return q}function re(){var $=String.fromCharCode;for(var U=0;U<256;U++)N[U]=$(U)}this.encode=function($,U){var q=new Date().getTime();if(U)mt(U);b=[],p=0,E=7,j(65496),Me(),F($.comments),ae($.exifBuffer),ne(),ue($.width,$.height),T(),Re();var W=0,B=0,X=0;p=0,E=7,this.encode.displayName="_encode_";var{data:fe,width:de,height:Ue}=$,Fe=de*4,I=de*3,L,Z=0,He,x,ie,Se,Q,pe,Ze,Ae;while(Z<Ue){L=0;while(L<Fe){Se=Fe*Z+L,Q=Se,pe=-1,Ze=0;for(Ae=0;Ae<64;Ae++){if(Ze=Ae>>3,pe=(Ae&7)*4,Q=Se+Ze*Fe+pe,Z+Ze>=Ue)Q-=Fe*(Z+1+Ze-Ue);if(L+pe>=Fe)Q-=L+pe-Fe+4;He=fe[Q++],x=fe[Q++],ie=fe[Q++],v[Ae]=(y[He]+y[x+256>>0]+y[ie+512>>0]>>16)-128,S[Ae]=(y[He+768>>0]+y[x+1024>>0]+y[ie+1280>>0]>>16)-128,w[Ae]=(y[He+1280>>0]+y[x+1536>>0]+y[ie+1792>>0]>>16)-128}W=Y(v,o,W,u,l),B=Y(S,a,B,c,h),X=Y(w,a,X,c,h),L+=32}Z+=8}if(E>=0){var pt=[];pt[1]=E+1,pt[0]=(1<<E+1)-1,ee(pt)}if(j(65497),typeof Vs>"u")return new Uint8Array(b);return Buffer.from(b);var Ut,jn};function mt($){if($<=0)$=1;if($>100)$=100;if(R==$)return;var U=0;if($<50)U=Math.floor(5000/$);else U=Math.floor(200-$*2);le(U),R=$}function Mt(){var $=new Date().getTime();if(!e)e=50;re(),Ge(),ge(),oe(),mt(e);var U=new Date().getTime()-$}Mt()}if(typeof Vs<"u")Vs.exports=mh;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].encode=mh;function mh(e,t){if(typeof t>"u")t=50;var n=new Mb(t),r=n.encode(e,t);return{data:r,width:e.width,height:e.height}}});var $h=Pe((DM,Za)=>{var Ya=function(){var t=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]),n=4017,r=799,i=3406,s=2276,o=1567,a=3784,u=5793,c=2896;function l(){}function h(E,v){var S=0,w=[],N,y,R=16;while(R>0&&!E[R-1])R--;w.push({children:[],index:0});var P=w[0],G;for(N=0;N<R;N++){for(y=0;y<E[N];y++){P=w.pop(),P.children[P.index]=v[S];while(P.index>0){if(w.length===0)throw Error("Could not recreate Huffman Table");P=w.pop()}P.index++,w.push(P);while(w.length<=N)w.push(G={children:[],index:0}),P.children[P.index]=G.children,P=G;S++}if(N+1<R)w.push(G={children:[],index:0}),P.children[P.index]=G.children,P=G}return w[0].children}function f(E,v,S,w,N,y,R,P,G,A){var{precision:_,samplesPerLine:C,scanLines:H,mcusPerLine:O,progressive:K,maxH:Ee,maxV:le}=S,D=v,Ge=0,ge=0;function oe(){if(ge>0)return ge--,Ge>>ge&1;if(Ge=E[v++],Ge==255){var I=E[v++];if(I)throw Error("unexpected marker: "+(Ge<<8|I).toString(16))}return ge=7,Ge>>>7}function ee(I){var L=I,Z;while((Z=oe())!==null){if(L=L[Z],typeof L==="number")return L;if(typeof L!=="object")throw Error("invalid huffman sequence")}return null}function k(I){var L=0;while(I>0){var Z=oe();if(Z===null)return;L=L<<1|Z,I--}return L}function j(I){var L=k(I);if(L>=1<<I-1)return L;return L+(-1<<I)+1}function ve(I,L){var Z=ee(I.huffmanTableDC),He=Z===0?0:j(Z);L[0]=I.pred+=He;var x=1;while(x<64){var ie=ee(I.huffmanTableAC),Se=ie&15,Q=ie>>4;if(Se===0){if(Q<15)break;x+=16;continue}x+=Q;var pe=t[x];L[pe]=j(Se),x++}}function Me(I,L){var Z=ee(I.huffmanTableDC),He=Z===0?0:j(Z)<<G;L[0]=I.pred+=He}function ae(I,L){L[0]|=oe()<<G}var ue=0;function ne(I,L){if(ue>0){ue--;return}var Z=y,He=R;while(Z<=He){var x=ee(I.huffmanTableAC),ie=x&15,Se=x>>4;if(ie===0){if(Se<15){ue=k(Se)+(1<<Se)-1;break}Z+=16;continue}Z+=Se;var Q=t[Z];L[Q]=j(ie)*(1<<G),Z++}}var T=0,F;function Re(I,L){var Z=y,He=R,x=0;while(Z<=He){var ie=t[Z],Se=L[ie]<0?-1:1;switch(T){case 0:var Q=ee(I.huffmanTableAC),pe=Q&15,x=Q>>4;if(pe===0)if(x<15)ue=k(x)+(1<<x),T=4;else x=16,T=1;else{if(pe!==1)throw Error("invalid ACn encoding");F=j(pe),T=x?2:3}continue;case 1:case 2:if(L[ie])L[ie]+=(oe()<<G)*Se;else if(x--,x===0)T=T==2?3:0;break;case 3:if(L[ie])L[ie]+=(oe()<<G)*Se;else L[ie]=F<<G,T=0;break;case 4:if(L[ie])L[ie]+=(oe()<<G)*Se;break}Z++}if(T===4){if(ue--,ue===0)T=0}}function Y(I,L,Z,He,x){var ie=Z/O|0,Se=Z%O,Q=ie*I.v+He,pe=Se*I.h+x;if(I.blocks[Q]===void 0&&A.tolerantDecoding)return;L(I,I.blocks[Q][pe])}function re(I,L,Z){var He=Z/I.blocksPerLine|0,x=Z%I.blocksPerLine;if(I.blocks[He]===void 0&&A.tolerantDecoding)return;L(I,I.blocks[He][x])}var mt=w.length,Mt,$,U,q,W,B;if(K)if(y===0)B=P===0?Me:ae;else B=P===0?ne:Re;else B=ve;var X=0,fe,de;if(mt==1)de=w[0].blocksPerLine*w[0].blocksPerColumn;else de=O*S.mcusPerColumn;if(!N)N=de;var Ue,Fe;while(X<de){for($=0;$<mt;$++)w[$].pred=0;if(ue=0,mt==1){Mt=w[0];for(W=0;W<N;W++)re(Mt,B,X),X++}else for(W=0;W<N;W++){for($=0;$<mt;$++){Mt=w[$],Ue=Mt.h,Fe=Mt.v;for(U=0;U<Fe;U++)for(q=0;q<Ue;q++)Y(Mt,B,X,U,q)}if(X++,X===de)break}if(X===de)do{if(E[v]===255){if(E[v+1]!==0)break}v+=1}while(v<E.length-2);if(ge=0,fe=E[v]<<8|E[v+1],fe<65280)throw Error("marker was not found");if(fe>=65488&&fe<=65495)v+=2;else break}return v-D}function d(E,v){var S=[],w=v.blocksPerLine,N=v.blocksPerColumn,y=w<<3,R=new Int32Array(64),P=new Uint8Array(64);function G(D,Ge,ge){var oe=v.quantizationTable,ee,k,j,ve,Me,ae,ue,ne,T,F=ge,Re;for(Re=0;Re<64;Re++)F[Re]=D[Re]*oe[Re];for(Re=0;Re<8;++Re){var Y=8*Re;if(F[1+Y]==0&&F[2+Y]==0&&F[3+Y]==0&&F[4+Y]==0&&F[5+Y]==0&&F[6+Y]==0&&F[7+Y]==0){T=u*F[0+Y]+512>>10,F[0+Y]=T,F[1+Y]=T,F[2+Y]=T,F[3+Y]=T,F[4+Y]=T,F[5+Y]=T,F[6+Y]=T,F[7+Y]=T;continue}ee=u*F[0+Y]+128>>8,k=u*F[4+Y]+128>>8,j=F[2+Y],ve=F[6+Y],Me=c*(F[1+Y]-F[7+Y])+128>>8,ne=c*(F[1+Y]+F[7+Y])+128>>8,ae=F[3+Y]<<4,ue=F[5+Y]<<4,T=ee-k+1>>1,ee=ee+k+1>>1,k=T,T=j*a+ve*o+128>>8,j=j*o-ve*a+128>>8,ve=T,T=Me-ue+1>>1,Me=Me+ue+1>>1,ue=T,T=ne+ae+1>>1,ae=ne-ae+1>>1,ne=T,T=ee-ve+1>>1,ee=ee+ve+1>>1,ve=T,T=k-j+1>>1,k=k+j+1>>1,j=T,T=Me*s+ne*i+2048>>12,Me=Me*i-ne*s+2048>>12,ne=T,T=ae*r+ue*n+2048>>12,ae=ae*n-ue*r+2048>>12,ue=T,F[0+Y]=ee+ne,F[7+Y]=ee-ne,F[1+Y]=k+ue,F[6+Y]=k-ue,F[2+Y]=j+ae,F[5+Y]=j-ae,F[3+Y]=ve+Me,F[4+Y]=ve-Me}for(Re=0;Re<8;++Re){var re=Re;if(F[8+re]==0&&F[16+re]==0&&F[24+re]==0&&F[32+re]==0&&F[40+re]==0&&F[48+re]==0&&F[56+re]==0){T=u*ge[Re+0]+8192>>14,F[0+re]=T,F[8+re]=T,F[16+re]=T,F[24+re]=T,F[32+re]=T,F[40+re]=T,F[48+re]=T,F[56+re]=T;continue}ee=u*F[0+re]+2048>>12,k=u*F[32+re]+2048>>12,j=F[16+re],ve=F[48+re],Me=c*(F[8+re]-F[56+re])+2048>>12,ne=c*(F[8+re]+F[56+re])+2048>>12,ae=F[24+re],ue=F[40+re],T=ee-k+1>>1,ee=ee+k+1>>1,k=T,T=j*a+ve*o+2048>>12,j=j*o-ve*a+2048>>12,ve=T,T=Me-ue+1>>1,Me=Me+ue+1>>1,ue=T,T=ne+ae+1>>1,ae=ne-ae+1>>1,ne=T,T=ee-ve+1>>1,ee=ee+ve+1>>1,ve=T,T=k-j+1>>1,k=k+j+1>>1,j=T,T=Me*s+ne*i+2048>>12,Me=Me*i-ne*s+2048>>12,ne=T,T=ae*r+ue*n+2048>>12,ae=ae*n-ue*r+2048>>12,ue=T,F[0+re]=ee+ne,F[56+re]=ee-ne,F[8+re]=k+ue,F[48+re]=k-ue,F[16+re]=j+ae,F[40+re]=j-ae,F[24+re]=ve+Me,F[32+re]=ve-Me}for(Re=0;Re<64;++Re){var mt=128+(F[Re]+8>>4);Ge[Re]=mt<0?0:mt>255?255:mt}}p(y*N*8);var A,_;for(var C=0;C<N;C++){var H=C<<3;for(A=0;A<8;A++)S.push(new Uint8Array(y));for(var O=0;O<w;O++){G(v.blocks[C][O],P,R);var K=0,Ee=O<<3;for(_=0;_<8;_++){var le=S[H+_];for(A=0;A<8;A++)le[Ee+A]=P[K++]}}}return S}function g(E){return E<0?0:E>255?255:E}l.prototype={load:function(v){var S=new XMLHttpRequest;S.open("GET",v,!0),S.responseType="arraybuffer",S.onload=function(){var w=new Uint8Array(S.response||S.mozResponseArrayBuffer);if(this.parse(w),this.onload)this.onload()}.bind(this),S.send(null)},parse:function(v){var S=this.opts.maxResolutionInMP*1000*1000,w=0,N=v.length;function y(){var Q=v[w]<<8|v[w+1];return w+=2,Q}function R(){var Q=y(),pe=v.subarray(w,w+Q-2);return w+=pe.length,pe}function P(Q){var pe=1,Ze=1,Ae,pt;for(pt in Q.components)if(Q.components.hasOwnProperty(pt)){if(Ae=Q.components[pt],pe<Ae.h)pe=Ae.h;if(Ze<Ae.v)Ze=Ae.v}var Ut=Math.ceil(Q.samplesPerLine/8/pe),jn=Math.ceil(Q.scanLines/8/Ze);for(pt in Q.components)if(Q.components.hasOwnProperty(pt)){Ae=Q.components[pt];var pr=Math.ceil(Math.ceil(Q.samplesPerLine/8)*Ae.h/pe),wr=Math.ceil(Math.ceil(Q.scanLines/8)*Ae.v/Ze),ci=Ut*Ae.h,li=jn*Ae.v,Rs=li*ci,hi=[];p(Rs*256);for(var fi=0;fi<li;fi++){var di=[];for(var gi=0;gi<ci;gi++)di.push(new Int32Array(64));hi.push(di)}Ae.blocksPerLine=pr,Ae.blocksPerColumn=wr,Ae.blocks=hi}Q.maxH=pe,Q.maxV=Ze,Q.mcusPerLine=Ut,Q.mcusPerColumn=jn}var G=null,A=null,_=null,C,H,O=[],K=[],Ee=[],le=[],D=y(),Ge=-1;if(this.comments=[],D!=65496)throw Error("SOI not found");D=y();while(D!=65497){var ge,oe,ee;switch(D){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 k=R();if(D===65534){var j=String.fromCharCode.apply(null,k);this.comments.push(j)}if(D===65504){if(k[0]===74&&k[1]===70&&k[2]===73&&k[3]===70&&k[4]===0)G={version:{major:k[5],minor:k[6]},densityUnits:k[7],xDensity:k[8]<<8|k[9],yDensity:k[10]<<8|k[11],thumbWidth:k[12],thumbHeight:k[13],thumbData:k.subarray(14,14+3*k[12]*k[13])}}if(D===65505){if(k[0]===69&&k[1]===120&&k[2]===105&&k[3]===102&&k[4]===0)this.exifBuffer=k.subarray(5,k.length)}if(D===65518){if(k[0]===65&&k[1]===100&&k[2]===111&&k[3]===98&&k[4]===101&&k[5]===0)A={version:k[6],flags0:k[7]<<8|k[8],flags1:k[9]<<8|k[10],transformCode:k[11]}}break;case 65499:var ve=y(),Me=ve+w-2;while(w<Me){var ae=v[w++];p(256);var ue=new Int32Array(64);if(ae>>4===0)for(oe=0;oe<64;oe++){var ne=t[oe];ue[ne]=v[w++]}else if(ae>>4===1)for(oe=0;oe<64;oe++){var ne=t[oe];ue[ne]=y()}else throw Error("DQT: invalid table spec");O[ae&15]=ue}break;case 65472:case 65473:case 65474:y(),C={},C.extended=D===65473,C.progressive=D===65474,C.precision=v[w++],C.scanLines=y(),C.samplesPerLine=y(),C.components={},C.componentsOrder=[];var T=C.scanLines*C.samplesPerLine;if(T>S){var F=Math.ceil((T-S)/1e6);throw Error(`maxResolutionInMP limit exceeded by ${F}MP`)}var Re=v[w++],Y,re=0,mt=0;for(ge=0;ge<Re;ge++){Y=v[w];var Mt=v[w+1]>>4,$=v[w+1]&15,U=v[w+2];if(Mt<=0||$<=0)throw Error("Invalid sampling factor, expected values above 0");C.componentsOrder.push(Y),C.components[Y]={h:Mt,v:$,quantizationIdx:U},w+=3}P(C),K.push(C);break;case 65476:var q=y();for(ge=2;ge<q;){var W=v[w++],B=new Uint8Array(16),X=0;for(oe=0;oe<16;oe++,w++)X+=B[oe]=v[w];p(16+X);var fe=new Uint8Array(X);for(oe=0;oe<X;oe++,w++)fe[oe]=v[w];ge+=17+X,(W>>4===0?le:Ee)[W&15]=h(B,fe)}break;case 65501:y(),H=y();break;case 65500:y(),y();break;case 65498:var de=y(),Ue=v[w++],Fe=[],I;for(ge=0;ge<Ue;ge++){I=C.components[v[w++]];var L=v[w++];I.huffmanTableDC=le[L>>4],I.huffmanTableAC=Ee[L&15],Fe.push(I)}var Z=v[w++],He=v[w++],x=v[w++],ie=f(v,w,C,Fe,H,Z,He,x>>4,x&15,this.opts);w+=ie;break;case 65535:if(v[w]!==255)w--;break;default:if(v[w-3]==255&&v[w-2]>=192&&v[w-2]<=254){w-=3;break}else if(D===224||D==225){if(Ge!==-1)throw Error(`first unknown JPEG marker at offset ${Ge.toString(16)}, second unknown JPEG marker ${D.toString(16)} at offset ${(w-1).toString(16)}`);Ge=w-1;let Q=y();if(v[w+Q-2]===255){w+=Q-2;break}}throw Error("unknown JPEG marker "+D.toString(16))}D=y()}if(K.length!=1)throw Error("only single frame JPEGs supported");for(var ge=0;ge<K.length;ge++){var Se=K[ge].components;for(var oe in Se)Se[oe].quantizationTable=O[Se[oe].quantizationIdx],delete Se[oe].quantizationIdx}this.width=C.samplesPerLine,this.height=C.scanLines,this.jfif=G,this.adobe=A,this.components=[];for(var ge=0;ge<C.componentsOrder.length;ge++){var I=C.components[C.componentsOrder[ge]];this.components.push({lines:d(C,I),scaleX:I.h/C.maxH,scaleY:I.v/C.maxV})}},getData:function(v,S){var w=this.width/v,N=this.height/S,y,R,P,G,A,_,C,H,O,K,Ee=0,le,D,Ge,ge,oe,ee,k,j,ve,Me,ae,ue=v*S*this.components.length;p(ue);var ne=new Uint8Array(ue);switch(this.components.length){case 1:y=this.components[0];for(K=0;K<S;K++){A=y.lines[0|K*y.scaleY*N];for(O=0;O<v;O++)le=A[0|O*y.scaleX*w],ne[Ee++]=le}break;case 2:y=this.components[0],R=this.components[1];for(K=0;K<S;K++){A=y.lines[0|K*y.scaleY*N],_=R.lines[0|K*R.scaleY*N];for(O=0;O<v;O++)le=A[0|O*y.scaleX*w],ne[Ee++]=le,le=_[0|O*R.scaleX*w],ne[Ee++]=le}break;case 3:if(ae=!0,this.adobe&&this.adobe.transformCode)ae=!0;else if(typeof this.opts.colorTransform<"u")ae=!!this.opts.colorTransform;y=this.components[0],R=this.components[1],P=this.components[2];for(K=0;K<S;K++){A=y.lines[0|K*y.scaleY*N],_=R.lines[0|K*R.scaleY*N],C=P.lines[0|K*P.scaleY*N];for(O=0;O<v;O++){if(!ae)j=A[0|O*y.scaleX*w],ve=_[0|O*R.scaleX*w],Me=C[0|O*P.scaleX*w];else le=A[0|O*y.scaleX*w],D=_[0|O*R.scaleX*w],Ge=C[0|O*P.scaleX*w],j=g(le+1.402*(Ge-128)),ve=g(le-0.3441363*(D-128)-0.71413636*(Ge-128)),Me=g(le+1.772*(D-128));ne[Ee++]=j,ne[Ee++]=ve,ne[Ee++]=Me}}break;case 4:if(!this.adobe)throw Error("Unsupported color mode (4 components)");if(ae=!1,this.adobe&&this.adobe.transformCode)ae=!0;else if(typeof this.opts.colorTransform<"u")ae=!!this.opts.colorTransform;y=this.components[0],R=this.components[1],P=this.components[2],G=this.components[3];for(K=0;K<S;K++){A=y.lines[0|K*y.scaleY*N],_=R.lines[0|K*R.scaleY*N],C=P.lines[0|K*P.scaleY*N],H=G.lines[0|K*G.scaleY*N];for(O=0;O<v;O++){if(!ae)oe=A[0|O*y.scaleX*w],ee=_[0|O*R.scaleX*w],k=C[0|O*P.scaleX*w],ge=H[0|O*G.scaleX*w];else le=A[0|O*y.scaleX*w],D=_[0|O*R.scaleX*w],Ge=C[0|O*P.scaleX*w],ge=H[0|O*G.scaleX*w],oe=255-g(le+1.402*(Ge-128)),ee=255-g(le-0.3441363*(D-128)-0.71413636*(Ge-128)),k=255-g(le+1.772*(D-128));ne[Ee++]=255-oe,ne[Ee++]=255-ee,ne[Ee++]=255-k,ne[Ee++]=255-ge}}break;default:throw Error("Unsupported color mode")}return ne},copyToImageData:function(v,S){var{width:w,height:N,data:y}=v,R=this.getData(w,N),P=0,G=0,A,_,C,H,O,K,Ee,le,D;switch(this.components.length){case 1:for(_=0;_<N;_++)for(A=0;A<w;A++)if(C=R[P++],y[G++]=C,y[G++]=C,y[G++]=C,S)y[G++]=255;break;case 3:for(_=0;_<N;_++)for(A=0;A<w;A++)if(Ee=R[P++],le=R[P++],D=R[P++],y[G++]=Ee,y[G++]=le,y[G++]=D,S)y[G++]=255;break;case 4:for(_=0;_<N;_++)for(A=0;A<w;A++)if(O=R[P++],K=R[P++],C=R[P++],H=R[P++],Ee=255-g(O*(1-H/255)+H),le=255-g(K*(1-H/255)+H),D=255-g(C*(1-H/255)+H),y[G++]=Ee,y[G++]=le,y[G++]=D,S)y[G++]=255;break;default:throw Error("Unsupported color mode")}}};var m=0,b=0;function p(E=0){var v=m+E;if(v>b){var S=Math.ceil((v-b)/1024/1024);throw Error(`maxMemoryUsageInMB limit exceeded by at least ${S}MB`)}m=v}return l.resetMaxMemoryUsage=function(E){m=0,b=E},l.getBytesAllocated=function(){return m},l.requestMemoryAllocation=p,l}();if(typeof Za<"u")Za.exports=bh;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].decode=bh;function bh(e,t={}){var n={colorTransform:void 0,useTArray:!1,formatAsRGBA:!0,tolerantDecoding:!0,maxResolutionInMP:100,maxMemoryUsageInMB:512},r={...n,...t},i=new Uint8Array(e),s=new Ya;s.opts=r,Ya.resetMaxMemoryUsage(r.maxMemoryUsageInMB*1024*1024),s.parse(i);var o=r.formatAsRGBA?4:3,a=s.width*s.height*o;try{Ya.requestMemoryAllocation(a);var u={width:s.width,height:s.height,exifBuffer:s.exifBuffer,data:r.useTArray?new Uint8Array(a):Buffer.alloc(a)};if(s.comments.length>0)u.comments=s.comments}catch(c){if(c instanceof RangeError)throw Error("Could not allocate enough memory for the image. Required: "+a);if(c instanceof ReferenceError){if(c.message==="Buffer is not defined")throw Error("Buffer is not globally defined in this environment. Consider setting useTArray to true")}throw c}return s.copyToImageData(u,r.formatAsRGBA),u}});var yh=Pe((eS,kh)=>{var Sb=wh(),Ib=$h();kh.exports={encode:Sb,decode:Ib}});var za=Pe((tS,vh)=>{var Nb=Be("util"),Eh=Be("stream"),It=vh.exports=function(){Eh.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};Nb.inherits(It,Eh);It.prototype.read=function(e,t){this._reads.push({length:Math.abs(e),allowLess:e<0,func:t}),process.nextTick(function(){if(this._process(),this._paused&&this._reads&&this._reads.length>0)this._paused=!1,this.emit("drain")}.bind(this))};It.prototype.write=function(e,t){if(!this.writable)return this.emit("error",Error("Stream not writable")),!1;let n;if(Buffer.isBuffer(e))n=e;else n=Buffer.from(e,t||this._encoding);if(this._buffers.push(n),this._buffered+=n.length,this._process(),this._reads&&this._reads.length===0)this._paused=!0;return this.writable&&!this._paused};It.prototype.end=function(e,t){if(e)this.write(e,t);if(this.writable=!1,!this._buffers)return;if(this._buffers.length===0)this._end();else this._buffers.push(null),this._process()};It.prototype.destroySoon=It.prototype.end;It.prototype._end=function(){if(this._reads.length>0)this.emit("error",Error("Unexpected end of input"));this.destroy()};It.prototype.destroy=function(){if(!this._buffers)return;this.writable=!1,this._reads=null,this._buffers=null,this.emit("close")};It.prototype._processReadAllowingLess=function(e){this._reads.shift();let t=this._buffers[0];if(t.length>e.length)this._buffered-=e.length,this._buffers[0]=t.slice(e.length),e.func.call(this,t.slice(0,e.length));else this._buffered-=t.length,this._buffers.shift(),e.func.call(this,t)};It.prototype._processRead=function(e){this._reads.shift();let t=0,n=0,r=Buffer.alloc(e.length);while(t<e.length){let i=this._buffers[n++],s=Math.min(i.length,e.length-t);if(i.copy(r,t,0,s),t+=s,s!==i.length)this._buffers[--n]=i.slice(s)}if(n>0)this._buffers.splice(0,n);this._buffered-=e.length,e.func.call(this,r)};It.prototype._process=function(){try{while(this._buffered>0&&this._reads&&this._reads.length>0){let e=this._reads[0];if(e.allowLess)this._processReadAllowingLess(e);else if(this._buffered>=e.length)this._processRead(e);else break}if(this._buffers&&!this.writable)this._end()}catch(e){this.emit("error",e)}}});var Ba=Pe((Rb)=>{var $n=[{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]}];Rb.getImagePasses=function(e,t){let n=[],r=e%8,i=t%8,s=(e-r)/8,o=(t-i)/8;for(let a=0;a<$n.length;a++){let u=$n[a],c=s*u.x.length,l=o*u.y.length;for(let h=0;h<u.x.length;h++)if(u.x[h]<r)c++;else break;for(let h=0;h<u.y.length;h++)if(u.y[h]<i)l++;else break;if(c>0&&l>0)n.push({width:c,height:l,index:a})}return n};Rb.getInterlaceIterator=function(e){return function(t,n,r){let i=t%$n[r].x.length,s=(t-i)/$n[r].x.length*8+$n[r].x[i],o=n%$n[r].y.length,a=(n-o)/$n[r].y.length*8+$n[r].y[o];return s*4+a*e*4}}});var Va=Pe((rS,Mh)=>{Mh.exports=function(t,n,r){let i=t+n-r,s=Math.abs(i-t),o=Math.abs(i-n),a=Math.abs(i-r);if(s<=o&&s<=a)return t;if(o<=a)return n;return r}});var Xa=Pe((iS,Ih)=>{var Ob=Ba(),Tb=Va();function Sh(e,t,n){let r=e*t;if(n!==8)r=Math.ceil(r/(8/n));return r}var Ir=Ih.exports=function(e,t){let{width:n,height:r,interlace:i,bpp:s,depth:o}=e;if(this.read=t.read,this.write=t.write,this.complete=t.complete,this._imageIndex=0,this._images=[],i){let a=Ob.getImagePasses(n,r);for(let u=0;u<a.length;u++)this._images.push({byteWidth:Sh(a[u].width,s,o),height:a[u].height,lineIndex:0})}else this._images.push({byteWidth:Sh(n,s,o),height:r,lineIndex:0});if(o===8)this._xComparison=s;else if(o===16)this._xComparison=s*2;else this._xComparison=1};Ir.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Ir.prototype._unFilterType1=function(e,t,n){let r=this._xComparison,i=r-1;for(let s=0;s<n;s++){let o=e[1+s],a=s>i?t[s-r]:0;t[s]=o+a}};Ir.prototype._unFilterType2=function(e,t,n){let r=this._lastLine;for(let i=0;i<n;i++){let s=e[1+i],o=r?r[i]:0;t[i]=s+o}};Ir.prototype._unFilterType3=function(e,t,n){let r=this._xComparison,i=r-1,s=this._lastLine;for(let o=0;o<n;o++){let a=e[1+o],u=s?s[o]:0,c=o>i?t[o-r]:0,l=Math.floor((c+u)/2);t[o]=a+l}};Ir.prototype._unFilterType4=function(e,t,n){let r=this._xComparison,i=r-1,s=this._lastLine;for(let o=0;o<n;o++){let a=e[1+o],u=s?s[o]:0,c=o>i?t[o-r]:0,l=o>i&&s?s[o-r]:0,h=Tb(c,u,l);t[o]=a+h}};Ir.prototype._reverseFilterLine=function(e){let t=e[0],n,r=this._images[this._imageIndex],i=r.byteWidth;if(t===0)n=e.slice(1,i+1);else switch(n=Buffer.alloc(i),t){case 1:this._unFilterType1(e,n,i);break;case 2:this._unFilterType2(e,n,i);break;case 3:this._unFilterType3(e,n,i);break;case 4:this._unFilterType4(e,n,i);break;default:throw Error("Unrecognised filter type - "+t)}if(this.write(n),r.lineIndex++,r.lineIndex>=r.height)this._lastLine=null,this._imageIndex++,r=this._images[this._imageIndex];else this._lastLine=n;if(r)this.read(r.byteWidth+1,this._reverseFilterLine.bind(this));else this._lastLine=null,this.complete()}});var Fh=Pe((sS,Rh)=>{var Ab=Be("util"),Nh=za(),Hb=Xa(),Lb=Rh.exports=function(e){Nh.call(this);let t=[],n=this;this._filter=new Hb(e,{read:this.read.bind(this),write:function(r){t.push(r)},complete:function(){n.emit("complete",Buffer.concat(t))}}),this._filter.start()};Ab.inherits(Lb,Nh)});var Nr=Pe((oS,Ph)=>{Ph.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 eu=Pe((aS,Oh)=>{var xa=[];(function(){for(let e=0;e<256;e++){let t=e;for(let n=0;n<8;n++)if(t&1)t=3988292384^t>>>1;else t=t>>>1;xa[e]=t}})();var Da=Oh.exports=function(){this._crc=-1};Da.prototype.write=function(e){for(let t=0;t<e.length;t++)this._crc=xa[(this._crc^e[t])&255]^this._crc>>>8;return!0};Da.prototype.crc32=function(){return this._crc^-1};Da.crc32=function(e){let t=-1;for(let n=0;n<e.length;n++)t=xa[(t^e[n])&255]^t>>>8;return t^-1}});var tu=Pe((uS,Th)=>{var qe=Nr(),Gb=eu(),Ye=Th.exports=function(e,t){this._options=e,e.checkCRC=e.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[qe.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[qe.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[qe.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[qe.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[qe.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[qe.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=t.read,this.error=t.error,this.metadata=t.metadata,this.gamma=t.gamma,this.transColor=t.transColor,this.palette=t.palette,this.parsed=t.parsed,this.inflateData=t.inflateData,this.finished=t.finished,this.simpleTransparency=t.simpleTransparency,this.headersFinished=t.headersFinished||function(){}};Ye.prototype.start=function(){this.read(qe.PNG_SIGNATURE.length,this._parseSignature.bind(this))};Ye.prototype._parseSignature=function(e){let t=qe.PNG_SIGNATURE;for(let n=0;n<t.length;n++)if(e[n]!==t[n]){this.error(Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};Ye.prototype._parseChunkBegin=function(e){let t=e.readUInt32BE(0),n=e.readUInt32BE(4),r="";for(let s=4;s<8;s++)r+=String.fromCharCode(e[s]);let i=Boolean(e[4]&32);if(!this._hasIHDR&&n!==qe.TYPE_IHDR){this.error(Error("Expected IHDR on beggining"));return}if(this._crc=new Gb,this._crc.write(Buffer.from(r)),this._chunks[n])return this._chunks[n](t);if(!i){this.error(Error("Unsupported critical chunk type "+r));return}this.read(t+4,this._skipChunk.bind(this))};Ye.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};Ye.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};Ye.prototype._parseChunkEnd=function(e){let t=e.readInt32BE(0),n=this._crc.crc32();if(this._options.checkCRC&&n!==t){this.error(Error("Crc error - "+t+" - "+n));return}if(!this._hasIEND)this.read(8,this._parseChunkBegin.bind(this))};Ye.prototype._handleIHDR=function(e){this.read(e,this._parseIHDR.bind(this))};Ye.prototype._parseIHDR=function(e){this._crc.write(e);let t=e.readUInt32BE(0),n=e.readUInt32BE(4),r=e[8],i=e[9],s=e[10],o=e[11],a=e[12];if(r!==8&&r!==4&&r!==2&&r!==1&&r!==16){this.error(Error("Unsupported bit depth "+r));return}if(!(i in qe.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(a!==0&&a!==1){this.error(Error("Unsupported interlace method"));return}this._colorType=i;let u=qe.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:t,height:n,depth:r,interlace:Boolean(a),palette:Boolean(i&qe.COLORTYPE_PALETTE),color:Boolean(i&qe.COLORTYPE_COLOR),alpha:Boolean(i&qe.COLORTYPE_ALPHA),bpp:u,colorType:i}),this._handleChunkEnd()};Ye.prototype._handlePLTE=function(e){this.read(e,this._parsePLTE.bind(this))};Ye.prototype._parsePLTE=function(e){this._crc.write(e);let t=Math.floor(e.length/3);for(let n=0;n<t;n++)this._palette.push([e[n*3],e[n*3+1],e[n*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};Ye.prototype._handleTRNS=function(e){this.simpleTransparency(),this.read(e,this._parseTRNS.bind(this))};Ye.prototype._parseTRNS=function(e){if(this._crc.write(e),this._colorType===qe.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(Error("Transparency chunk must be after palette"));return}if(e.length>this._palette.length){this.error(Error("More transparent colors than palette size"));return}for(let t=0;t<e.length;t++)this._palette[t][3]=e[t];this.palette(this._palette)}if(this._colorType===qe.COLORTYPE_GRAYSCALE)this.transColor([e.readUInt16BE(0)]);if(this._colorType===qe.COLORTYPE_COLOR)this.transColor([e.readUInt16BE(0),e.readUInt16BE(2),e.readUInt16BE(4)]);this._handleChunkEnd()};Ye.prototype._handleGAMA=function(e){this.read(e,this._parseGAMA.bind(this))};Ye.prototype._parseGAMA=function(e){this._crc.write(e),this.gamma(e.readUInt32BE(0)/qe.GAMMA_DIVISION),this._handleChunkEnd()};Ye.prototype._handleIDAT=function(e){if(!this._emittedHeadersFinished)this._emittedHeadersFinished=!0,this.headersFinished();this.read(-e,this._parseIDAT.bind(this,e))};Ye.prototype._parseIDAT=function(e,t){if(this._crc.write(t),this._colorType===qe.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw Error("Expected palette not found");this.inflateData(t);let n=e-t.length;if(n>0)this._handleIDAT(n);else this._handleChunkEnd()};Ye.prototype._handleIEND=function(e){this.read(e,this._parseIEND.bind(this))};Ye.prototype._parseIEND=function(e){if(this._crc.write(e),this._hasIEND=!0,this._handleChunkEnd(),this.finished)this.finished()}});var nu=Pe((Jb)=>{var Ah=Ba(),Ub=[function(){},function(e,t,n,r){if(r===t.length)throw Error("Ran out of data");let i=t[r];e[n]=i,e[n+1]=i,e[n+2]=i,e[n+3]=255},function(e,t,n,r){if(r+1>=t.length)throw Error("Ran out of data");let i=t[r];e[n]=i,e[n+1]=i,e[n+2]=i,e[n+3]=t[r+1]},function(e,t,n,r){if(r+2>=t.length)throw Error("Ran out of data");e[n]=t[r],e[n+1]=t[r+1],e[n+2]=t[r+2],e[n+3]=255},function(e,t,n,r){if(r+3>=t.length)throw Error("Ran out of data");e[n]=t[r],e[n+1]=t[r+1],e[n+2]=t[r+2],e[n+3]=t[r+3]}],_b=[function(){},function(e,t,n,r){let i=t[0];e[n]=i,e[n+1]=i,e[n+2]=i,e[n+3]=r},function(e,t,n){let r=t[0];e[n]=r,e[n+1]=r,e[n+2]=r,e[n+3]=t[1]},function(e,t,n,r){e[n]=t[0],e[n+1]=t[1],e[n+2]=t[2],e[n+3]=r},function(e,t,n){e[n]=t[0],e[n+1]=t[1],e[n+2]=t[2],e[n+3]=t[3]}];function Cb(e,t){let n=[],r=0;function i(){if(r===e.length)throw Error("Ran out of data");let s=e[r];r++;let o,a,u,c,l,h,f,d;switch(t){default:throw Error("unrecognised depth");case 16:f=e[r],r++,n.push((s<<8)+f);break;case 4:f=s&15,d=s>>4,n.push(d,f);break;case 2:l=s&3,h=s>>2&3,f=s>>4&3,d=s>>6&3,n.push(d,f,h,l);break;case 1:o=s&1,a=s>>1&1,u=s>>2&1,c=s>>3&1,l=s>>4&1,h=s>>5&1,f=s>>6&1,d=s>>7&1,n.push(d,f,h,l,c,u,a,o);break}}return{get:function(s){while(n.length<s)i();let o=n.slice(0,s);return n=n.slice(s),o},resetAfterLine:function(){n.length=0},end:function(){if(r!==e.length)throw Error("extra data found")}}}function jb(e,t,n,r,i,s){let{width:o,height:a,index:u}=e;for(let c=0;c<a;c++)for(let l=0;l<o;l++){let h=n(l,c,u);Ub[r](t,i,h,s),s+=r}return s}function Wb(e,t,n,r,i,s){let{width:o,height:a,index:u}=e;for(let c=0;c<a;c++){for(let l=0;l<o;l++){let h=i.get(r),f=n(l,c,u);_b[r](t,h,f,s)}i.resetAfterLine()}}Jb.dataToBitMap=function(e,t){let{width:n,height:r,depth:i,bpp:s,interlace:o}=t,a;if(i!==8)a=Cb(e,i);let u;if(i<=8)u=Buffer.alloc(n*r*4);else u=new Uint16Array(n*r*4);let c=Math.pow(2,i)-1,l=0,h,f;if(o)h=Ah.getImagePasses(n,r),f=Ah.getInterlaceIterator(n,r);else{let d=0;f=function(){let g=d;return d+=4,g},h=[{width:n,height:r}]}for(let d=0;d<h.length;d++)if(i===8)l=jb(h[d],u,f,s,e,l);else Wb(h[d],u,f,s,a,c);if(i===8){if(l!==e.length)throw Error("extra data found")}else a.end();return u}});var ru=Pe((lS,Hh)=>{function qb(e,t,n,r,i){let s=0;for(let o=0;o<r;o++)for(let a=0;a<n;a++){let u=i[e[s]];if(!u)throw Error("index "+e[s]+" not in palette");for(let c=0;c<4;c++)t[s+c]=u[c];s+=4}}function Qb(e,t,n,r,i){let s=0;for(let o=0;o<r;o++)for(let a=0;a<n;a++){let u=!1;if(i.length===1){if(i[0]===e[s])u=!0}else if(i[0]===e[s]&&i[1]===e[s+1]&&i[2]===e[s+2])u=!0;if(u)for(let c=0;c<4;c++)t[s+c]=0;s+=4}}function Yb(e,t,n,r,i){let s=255,o=Math.pow(2,i)-1,a=0;for(let u=0;u<r;u++)for(let c=0;c<n;c++){for(let l=0;l<4;l++)t[a+l]=Math.floor(e[a+l]*s/o+0.5);a+=4}}Hh.exports=function(e,t,n=!1){let{depth:r,width:i,height:s,colorType:o,transColor:a,palette:u}=t,c=e;if(o===3)qb(e,c,i,s,u);else{if(a)Qb(e,c,i,s,a);if(r!==8&&!n){if(r===16)c=Buffer.alloc(i*s*4);Yb(e,c,i,s,r)}}return c}});var Uh=Pe((hS,Gh)=>{var Zb=Be("util"),iu=Be("zlib"),Lh=za(),zb=Fh(),Bb=tu(),Vb=nu(),Xb=ru(),Wt=Gh.exports=function(e){Lh.call(this),this._parser=new Bb(e,{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=e,this.writable=!0,this._parser.start()};Zb.inherits(Wt,Lh);Wt.prototype._handleError=function(e){if(this.emit("error",e),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};Wt.prototype._inflateData=function(e){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=iu.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 n=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,r=Math.max(n,iu.Z_MIN_CHUNK);this._inflate=iu.createInflate({chunkSize:r});let i=n,s=this.emit.bind(this,"error");this._inflate.on("error",function(a){if(!i)return;s(a)}),this._filter.on("complete",this._complete.bind(this));let o=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){if(!i)return;if(a.length>i)a=a.slice(0,i);i-=a.length,o(a)}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(e)};Wt.prototype._handleMetaData=function(e){this._metaData=e,this._bitmapInfo=Object.create(e),this._filter=new zb(this._bitmapInfo)};Wt.prototype._handleTransColor=function(e){this._bitmapInfo.transColor=e};Wt.prototype._handlePalette=function(e){this._bitmapInfo.palette=e};Wt.prototype._simpleTransparency=function(){this._metaData.alpha=!0};Wt.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};Wt.prototype._finished=function(){if(this.errord)return;if(!this._inflate)this.emit("error","No Inflate block");else this._inflate.end()};Wt.prototype._complete=function(e){if(this.errord)return;let t;try{let n=Vb.dataToBitMap(e,this._bitmapInfo);t=Xb(n,this._bitmapInfo,this._options.skipRescale),n=null}catch(n){this._handleError(n);return}this.emit("parsed",t)}});var Ch=Pe((fS,_h)=>{var $t=Nr();_h.exports=function(e,t,n,r){let i=[$t.COLORTYPE_COLOR_ALPHA,$t.COLORTYPE_ALPHA].indexOf(r.colorType)!==-1;if(r.colorType===r.inputColorType){let g=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&&g)return e}let s=r.bitDepth!==16?e:new Uint16Array(e.buffer),o=255,a=$t.COLORTYPE_TO_BPP_MAP[r.inputColorType];if(a===4&&!r.inputHasAlpha)a=3;let u=$t.COLORTYPE_TO_BPP_MAP[r.colorType];if(r.bitDepth===16)o=65535,u*=2;let c=Buffer.alloc(t*n*u),l=0,h=0,f=r.bgColor||{};if(f.red===void 0)f.red=o;if(f.green===void 0)f.green=o;if(f.blue===void 0)f.blue=o;function d(){let g,m,b,p=o;switch(r.inputColorType){case $t.COLORTYPE_COLOR_ALPHA:p=s[l+3],g=s[l],m=s[l+1],b=s[l+2];break;case $t.COLORTYPE_COLOR:g=s[l],m=s[l+1],b=s[l+2];break;case $t.COLORTYPE_ALPHA:p=s[l+1],g=s[l],m=g,b=g;break;case $t.COLORTYPE_GRAYSCALE:g=s[l],m=g,b=g;break;default:throw Error("input color type:"+r.inputColorType+" is not supported at present")}if(r.inputHasAlpha){if(!i)p/=o,g=Math.min(Math.max(Math.round((1-p)*f.red+p*g),0),o),m=Math.min(Math.max(Math.round((1-p)*f.green+p*m),0),o),b=Math.min(Math.max(Math.round((1-p)*f.blue+p*b),0),o)}return{red:g,green:m,blue:b,alpha:p}}for(let g=0;g<n;g++)for(let m=0;m<t;m++){let b=d(s,l);switch(r.colorType){case $t.COLORTYPE_COLOR_ALPHA:case $t.COLORTYPE_COLOR:if(r.bitDepth===8){if(c[h]=b.red,c[h+1]=b.green,c[h+2]=b.blue,i)c[h+3]=b.alpha}else if(c.writeUInt16BE(b.red,h),c.writeUInt16BE(b.green,h+2),c.writeUInt16BE(b.blue,h+4),i)c.writeUInt16BE(b.alpha,h+6);break;case $t.COLORTYPE_ALPHA:case $t.COLORTYPE_GRAYSCALE:{let p=(b.red+b.green+b.blue)/3;if(r.bitDepth===8){if(c[h]=p,i)c[h+1]=b.alpha}else if(c.writeUInt16BE(p,h),i)c.writeUInt16BE(b.alpha,h+2);break}default:throw Error("unrecognised color Type "+r.colorType)}l+=a,h+=u}return c}});var Jh=Pe((dS,Wh)=>{var jh=Va();function xb(e,t,n,r,i){for(let s=0;s<n;s++)r[i+s]=e[t+s]}function Db(e,t,n){let r=0,i=t+n;for(let s=t;s<i;s++)r+=Math.abs(e[s]);return r}function e0(e,t,n,r,i,s){for(let o=0;o<n;o++){let a=o>=s?e[t+o-s]:0,u=e[t+o]-a;r[i+o]=u}}function t0(e,t,n,r){let i=0;for(let s=0;s<n;s++){let o=s>=r?e[t+s-r]:0,a=e[t+s]-o;i+=Math.abs(a)}return i}function n0(e,t,n,r,i){for(let s=0;s<n;s++){let o=t>0?e[t+s-n]:0,a=e[t+s]-o;r[i+s]=a}}function r0(e,t,n){let r=0,i=t+n;for(let s=t;s<i;s++){let o=t>0?e[s-n]:0,a=e[s]-o;r+=Math.abs(a)}return r}function i0(e,t,n,r,i,s){for(let o=0;o<n;o++){let a=o>=s?e[t+o-s]:0,u=t>0?e[t+o-n]:0,c=e[t+o]-(a+u>>1);r[i+o]=c}}function s0(e,t,n,r){let i=0;for(let s=0;s<n;s++){let o=s>=r?e[t+s-r]:0,a=t>0?e[t+s-n]:0,u=e[t+s]-(o+a>>1);i+=Math.abs(u)}return i}function o0(e,t,n,r,i,s){for(let o=0;o<n;o++){let a=o>=s?e[t+o-s]:0,u=t>0?e[t+o-n]:0,c=t>0&&o>=s?e[t+o-(n+s)]:0,l=e[t+o]-jh(a,u,c);r[i+o]=l}}function a0(e,t,n,r){let i=0;for(let s=0;s<n;s++){let o=s>=r?e[t+s-r]:0,a=t>0?e[t+s-n]:0,u=t>0&&s>=r?e[t+s-(n+r)]:0,c=e[t+s]-jh(o,a,u);i+=Math.abs(c)}return i}var u0={0:xb,1:e0,2:n0,3:i0,4:o0},c0={0:Db,1:t0,2:r0,3:s0,4:a0};Wh.exports=function(e,t,n,r,i){let s;if(!("filterType"in r)||r.filterType===-1)s=[0,1,2,3,4];else if(typeof r.filterType==="number")s=[r.filterType];else throw Error("unrecognised filter types");if(r.bitDepth===16)i*=2;let o=t*i,a=0,u=0,c=Buffer.alloc((o+1)*n),l=s[0];for(let h=0;h<n;h++){if(s.length>1){let f=1/0;for(let d=0;d<s.length;d++){let g=c0[s[d]](e,u,o,i);if(g<f)l=s[d],f=g}}c[a]=l,a++,u0[l](e,u,o,c,a,i),a+=o,u+=o}return c}});var su=Pe((gS,Kh)=>{var De=Nr(),l0=eu(),h0=Ch(),f0=Jh(),d0=Be("zlib"),kn=Kh.exports=function(e){if(this._options=e,e.deflateChunkSize=e.deflateChunkSize||32768,e.deflateLevel=e.deflateLevel!=null?e.deflateLevel:9,e.deflateStrategy=e.deflateStrategy!=null?e.deflateStrategy:3,e.inputHasAlpha=e.inputHasAlpha!=null?e.inputHasAlpha:!0,e.deflateFactory=e.deflateFactory||d0.createDeflate,e.bitDepth=e.bitDepth||8,e.colorType=typeof e.colorType==="number"?e.colorType:De.COLORTYPE_COLOR_ALPHA,e.inputColorType=typeof e.inputColorType==="number"?e.inputColorType:De.COLORTYPE_COLOR_ALPHA,[De.COLORTYPE_GRAYSCALE,De.COLORTYPE_COLOR,De.COLORTYPE_COLOR_ALPHA,De.COLORTYPE_ALPHA].indexOf(e.colorType)===-1)throw Error("option color type:"+e.colorType+" is not supported at present");if([De.COLORTYPE_GRAYSCALE,De.COLORTYPE_COLOR,De.COLORTYPE_COLOR_ALPHA,De.COLORTYPE_ALPHA].indexOf(e.inputColorType)===-1)throw Error("option input color type:"+e.inputColorType+" is not supported at present");if(e.bitDepth!==8&&e.bitDepth!==16)throw Error("option bit depth:"+e.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(e,t,n){let r=h0(e,t,n,this._options),i=De.COLORTYPE_TO_BPP_MAP[this._options.colorType];return f0(r,t,n,this._options,i)};kn.prototype._packChunk=function(e,t){let n=t?t.length:0,r=Buffer.alloc(n+12);if(r.writeUInt32BE(n,0),r.writeUInt32BE(e,4),t)t.copy(r,8);return r.writeInt32BE(l0.crc32(r.slice(4,r.length-4)),r.length-4),r};kn.prototype.packGAMA=function(e){let t=Buffer.alloc(4);return t.writeUInt32BE(Math.floor(e*De.GAMMA_DIVISION),0),this._packChunk(De.TYPE_gAMA,t)};kn.prototype.packIHDR=function(e,t){let n=Buffer.alloc(13);return n.writeUInt32BE(e,0),n.writeUInt32BE(t,4),n[8]=this._options.bitDepth,n[9]=this._options.colorType,n[10]=0,n[11]=0,n[12]=0,this._packChunk(De.TYPE_IHDR,n)};kn.prototype.packIDAT=function(e){return this._packChunk(De.TYPE_IDAT,e)};kn.prototype.packIEND=function(){return this._packChunk(De.TYPE_IEND,null)}});var Zh=Pe((mS,Yh)=>{var g0=Be("util"),qh=Be("stream"),m0=Nr(),p0=su(),Qh=Yh.exports=function(e){qh.call(this);let t=e||{};this._packer=new p0(t),this._deflate=this._packer.createDeflate(),this.readable=!0};g0.inherits(Qh,qh);Qh.prototype.pack=function(e,t,n,r){if(this.emit("data",Buffer.from(m0.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(t,n)),r)this.emit("data",this._packer.packGAMA(r));let i=this._packer.filterData(e,t,n);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 Dh=Pe((yi,xh)=>{var zh=Be("assert").ok,Rr=Be("zlib"),w0=Be("util"),Bh=Be("buffer").kMaxLength;function Kn(e){if(!(this instanceof Kn))return new Kn(e);if(e&&e.chunkSize<Rr.Z_MIN_CHUNK)e.chunkSize=Rr.Z_MIN_CHUNK;if(Rr.Inflate.call(this,e),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,e&&e.maxLength!=null)this._maxLength=e.maxLength}function b0(e){return new Kn(e)}function Vh(e,t){if(t)process.nextTick(t);if(!e._handle)return;e._handle.close(),e._handle=null}Kn.prototype._processChunk=function(e,t,n){if(typeof n==="function")return Rr.Inflate._processChunk.call(this,e,t,n);let r=this,i=e&&e.length,s=this._chunkSize-this._offset,o=this._maxLength,a=0,u=[],c=0,l;this.on("error",function(g){l=g});function h(g,m){if(r._hadError)return;let b=s-m;if(zh(b>=0,"have should not go down"),b>0){let p=r._buffer.slice(r._offset,r._offset+b);if(r._offset+=b,p.length>o)p=p.slice(0,o);if(u.push(p),c+=p.length,o-=p.length,o===0)return!1}if(m===0||r._offset>=r._chunkSize)s=r._chunkSize,r._offset=0,r._buffer=Buffer.allocUnsafe(r._chunkSize);if(m===0)return a+=i-g,i=g,!0;return!1}zh(this._handle,"zlib binding closed");let f;do f=this._handle.writeSync(t,e,a,i,this._buffer,this._offset,s),f=f||this._writeState;while(!this._hadError&&h(f[0],f[1]));if(this._hadError)throw l;if(c>=Bh)throw Vh(this),RangeError("Cannot create final Buffer. It would be larger than 0x"+Bh.toString(16)+" bytes");let d=Buffer.concat(u,c);return Vh(this),d};w0.inherits(Kn,Rr.Inflate);function $0(e,t){if(typeof t==="string")t=Buffer.from(t);if(!(t instanceof Buffer))throw TypeError("Not a string or buffer");let n=e._finishFlushFlag;if(n==null)n=Rr.Z_FINISH;return e._processChunk(t,n)}function Xh(e,t){return $0(new Kn(t),e)}xh.exports=yi=Xh;yi.Inflate=Kn;yi.createInflate=b0;yi.inflateSync=Xh});var ou=Pe((pS,tf)=>{var ef=tf.exports=function(e){this._buffer=e,this._reads=[]};ef.prototype.read=function(e,t){this._reads.push({length:Math.abs(e),allowLess:e<0,func:t})};ef.prototype.process=function(){while(this._reads.length>0&&this._buffer.length){let e=this._reads[0];if(this._buffer.length&&(this._buffer.length>=e.length||e.allowLess)){this._reads.shift();let t=this._buffer;this._buffer=t.slice(e.length),e.func.call(this,t.slice(0,e.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 nf=Pe((E0)=>{var k0=ou(),y0=Xa();E0.process=function(e,t){let n=[],r=new k0(e);return new y0(t,{read:r.read.bind(r),write:function(s){n.push(s)},complete:function(){}}).start(),r.process(),Buffer.concat(n)}});var af=Pe((bS,of)=>{var rf=!0,sf=Be("zlib"),M0=Dh();if(!sf.deflateSync)rf=!1;var S0=ou(),I0=nf(),N0=tu(),R0=nu(),F0=ru();of.exports=function(e,t){if(!rf)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n;function r(S){n=S}let i;function s(S){i=S}function o(S){i.transColor=S}function a(S){i.palette=S}function u(){i.alpha=!0}let c;function l(S){c=S}let h=[];function f(S){h.push(S)}let d=new S0(e);if(new N0(t,{read:d.read.bind(d),error:r,metadata:s,gamma:l,palette:a,transColor:o,inflateData:f,simpleTransparency:u}).start(),d.process(),n)throw n;let m=Buffer.concat(h);h.length=0;let b;if(i.interlace)b=sf.inflateSync(m);else{let w=((i.width*i.bpp*i.depth+7>>3)+1)*i.height;b=M0(m,{chunkSize:w,maxLength:w})}if(m=null,!b||!b.length)throw Error("bad png - invalid inflate data response");let p=I0.process(b,i);m=null;let E=R0.dataToBitMap(p,i);p=null;let v=F0(E,i,t.skipRescale);return i.data=v,i.gamma=c||0,i}});var hf=Pe(($S,lf)=>{var uf=!0,cf=Be("zlib");if(!cf.deflateSync)uf=!1;var P0=Nr(),O0=su();lf.exports=function(e,t){if(!uf)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let r=new O0(t||{}),i=[];if(i.push(Buffer.from(P0.PNG_SIGNATURE)),i.push(r.packIHDR(e.width,e.height)),e.gamma)i.push(r.packGAMA(e.gamma));let s=r.filterData(e.data,e.width,e.height),o=cf.deflateSync(s,r.getDeflateOptions());if(s=null,!o||!o.length)throw Error("bad png - invalid compressed data response");return i.push(r.packIDAT(o)),i.push(r.packIEND()),Buffer.concat(i)}});var ff=Pe((H0)=>{var T0=af(),A0=hf();H0.read=function(e,t){return T0(e,t||{})};H0.write=function(e,t){return A0(e,t)}});var gf=Pe((W0)=>{var U0=Be("util"),df=Be("stream"),_0=Uh(),C0=Zh(),j0=ff(),it=W0.PNG=function(e){if(df.call(this),e=e||{},this.width=e.width|0,this.height=e.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,e.fill&&this.data)this.data.fill(0);this.gamma=0,this.readable=this.writable=!0,this._parser=new _0(e),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(t){this.data=t,this.emit("parsed",t)}.bind(this)),this._packer=new C0(e),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"))};U0.inherits(it,df);it.sync=j0;it.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};it.prototype.parse=function(e,t){if(t){let n,r;n=function(i){this.removeListener("error",r),this.data=i,t(null,this)}.bind(this),r=function(i){this.removeListener("parsed",n),t(i,null)}.bind(this),this.once("parsed",n),this.once("error",r)}return this.end(e),this};it.prototype.write=function(e){return this._parser.write(e),!0};it.prototype.end=function(e){this._parser.end(e)};it.prototype._metadata=function(e){this.width=e.width,this.height=e.height,this.emit("metadata",e)};it.prototype._gamma=function(e){this.gamma=e};it.prototype._handleClose=function(){if(!this._parser.writable&&!this._packer.readable)this.emit("close")};it.bitblt=function(e,t,n,r,i,s,o,a){if(n|=0,r|=0,i|=0,s|=0,o|=0,a|=0,n>e.width||r>e.height||n+i>e.width||r+s>e.height)throw Error("bitblt reading outside image");if(o>t.width||a>t.height||o+i>t.width||a+s>t.height)throw Error("bitblt writing outside image");for(let u=0;u<s;u++)e.data.copy(t.data,(a+u)*t.width+o<<2,(r+u)*e.width+n<<2,(r+u)*e.width+n+i<<2)};it.prototype.bitblt=function(e,t,n,r,i,s,o){return it.bitblt(this,e,t,n,r,i,s,o),this};it.adjustGamma=function(e){if(e.gamma){for(let t=0;t<e.height;t++)for(let n=0;n<e.width;n++){let r=e.width*t+n<<2;for(let i=0;i<3;i++){let s=e.data[r+i]/255;s=Math.pow(s,0.45454545454545453/e.gamma),e.data[r+i]=Math.round(s*255)}}e.gamma=0}};it.prototype.adjustGamma=function(){it.adjustGamma(this)}});import{spawnSync as oM}from"node:child_process";import{isMainThread as aM}from"node:worker_threads";import{parseArgs as eM}from"node:util";var Ve={name:"@kecan0406/ttheme",version:"1.1.4",type:"module",bin:{ttheme:"bin/ttheme.js"},files:["bin","dist/manifest.json","shell","!shell/check.zsh"],description:"Character terminal palettes for Ghostty, kitty, Alacritty, WezTerm, iTerm2, Windows Terminal and Warp",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","fast-string-width":"^3.0.2","jpeg-js":"^0.4.4",pngjs:"7.0.0","smol-toml":"^1.9.0",typescript:"^5.8.2"},engines:{bun:">=1.3",node:">=20.11"}};import{existsSync as R1,readFileSync as Lm}from"node:fs";import{styleText as Us}from"node:util";import{stdout as jl,stdin as Ow}from"node:process";import Tw from"node:readline";var vl=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(t)=>{let n=0;e.lastIndex=0;while(e.test(t))n+=1;return t.length-n}})(),Ml=(e)=>{return e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510},Sl=(e)=>{return e===8987||e===9001||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141};var pw=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,ww=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Il=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,bw=/\t{1,1000}/y,Nl=/[\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,$w=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,kw=/\p{M}+/gu,yw={limit:1/0,ellipsis:""},Rl=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??"",s=t?.ellipsisWidth??(i?Rl(i,yw,n).width:0),o=0,a=n.controlWidth??0,u=n.tabWidth??8,c=n.emojiWidth??2,l=2,h=n.regularWidth??1,f=n.wideWidth??2,d=[[$w,h],[pw,0],[ww,a],[bw,u],[Nl,c],[Il,f]],g=0,m=0,b=e.length,p=0,E=!1,v=b,S=Math.max(0,r-s),w=0,N=0,y=0,R=0;e:while(!0){if(N>w||m>=b&&m>g){let P=e.slice(w,N)||e.slice(g,m);p=0;for(let G of P.replaceAll(kw,"")){let A=G.codePointAt(0)||0;if(Ml(A))R=2;else if(Sl(A))R=f;else R=h;if(y+R>S)v=Math.min(v,Math.max(w,g)+p);if(y+R>r){E=!0;break e}p+=G.length,y+=R}w=N=0}if(m>=b)break e;for(let P=0,G=d.length;P<G;P++){let[A,_]=d[P];if(A.lastIndex=m,A.test(e)){if(p=A===Il?vl(e.slice(m,A.lastIndex)):A===Nl?1:A.lastIndex-m,R=p*_,y+R>S)v=Math.min(v,m+Math.floor((S-y)/_));if(y+R>r){E=!0;break e}y+=R,w=g,N=m,m=g=A.lastIndex;continue e}}m+=1}return{width:E?S:y,index:E?v:b,truncated:E,ellipsed:E&&r>=s}},Fl=Rl;var Ew={limit:1/0,ellipsis:"",ellipsisWidth:0},vw=(e,t={})=>{return Fl(e,Ew,t).width},je=vw;var As="\x1B",Hl="›",Mw=39,va="\x07",Ll="[",Sw="]",Gl="m",Ma=`${Sw}8;;`,Pl=new RegExp(`(?:\\${Ll}(?<code>\\d+)m|\\${Ma}(?<uri>.*)${va})`,"y"),Ol=(e)=>{if(e>=30&&e<=37)return 39;if(e>=90&&e<=97)return 39;if(e>=40&&e<=47)return 49;if(e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0;return},Tl=(e)=>`${As}${Ll}${e}${Gl}`,Al=(e)=>`${As}${Ma}${e}${va}`,Ea=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,s=!1,o=e.at(-1),a=o===void 0?0:je(o),u=r.next(),c=r.next(),l=0;while(!u.done){let h=u.value,f=je(h);if(a+f<=n)e[e.length-1]+=h;else e.push(h),a=0;if(h===As||h===Hl)i=!0,s=t.startsWith(Ma,l+1);if(i){if(s){if(h===va)i=!1,s=!1}else if(h===Gl)i=!1}else if(a+=f,a===n&&!c.done)e.push(""),a=0;u=c,c=r.next(),l+=h.length}if(o=e.at(-1),!a&&o!==void 0&&o.length&&e.length>1)e[e.length-2]+=e.pop()},Iw=(e)=>{let t=e.split(" "),n=t.length;while(n){if(je(t[n-1]))break;n--}if(n===t.length)return e;return t.slice(0,n).join(" ")+t.slice(n).join("")},Nw=(e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let r="",i,s,o=e.split(" "),a=[""],u=0;for(let h=0;h<o.length;h++){let f=o[h];if(n.trim!==!1){let g=a.at(-1)??"",m=g.trimStart();if(g.length!==m.length)a[a.length-1]=m,u=je(m)}if(h!==0){if(u>=t&&(n.wordWrap===!1||n.trim===!1))a.push(""),u=0;if(u||n.trim===!1)a[a.length-1]+=" ",u++}let d=je(f);if(n.hard&&d>t){let g=t-u,m=1+Math.floor((d-g-1)/t);if(Math.floor((d-1)/t)<m)a.push("");Ea(a,f,t),u=je(a.at(-1)??"");continue}if(u+d>t&&u&&d){if(n.wordWrap===!1&&u<t){Ea(a,f,t),u=je(a.at(-1)??"");continue}a.push(""),u=0}if(u+d>t&&n.wordWrap===!1){Ea(a,f,t),u=je(a.at(-1)??"");continue}a[a.length-1]+=f,u+=d}if(n.trim!==!1)a=a.map((h)=>Iw(h));let c=a.join(`
3
- `),l=!1;for(let h=0;h<c.length;h++){let f=c[h];if(r+=f,!l){if(l=f>="\uD800"&&f<="\uDBFF",l)continue}else l=!1;if(f===As||f===Hl){Pl.lastIndex=h+1;let g=Pl.exec(c)?.groups;if(g?.code!==void 0){let m=Number.parseFloat(g.code);i=m===Mw?void 0:m}else if(g?.uri!==void 0)s=g.uri.length===0?void 0:g.uri}if(c[h+1]===`
4
- `){if(s)r+=Al("");let d=i?Ol(i):void 0;if(i&&d)r+=Tl(d)}else if(f===`
5
- `){if(i&&Ol(i))r+=Tl(i);if(s)r+=Al(s)}}return r},Rw=/\r?\n/;function dn(e,t,n){return String(e).normalize().split(Rw).map((r)=>Nw(r,t,n)).join(`
6
- `)}var ut=Ts(Ia(),1);function br(e,t,n){if(!n.some((o)=>!o.disabled))return e;let r=e+t,i=Math.max(n.length-1,0),s=r<0?i:r>i?0:r;return n[s]?.disabled?br(s,t<0?-1:1,n):s}function Hs(e,t,n,r){let i=r.split(`
7
- `),s=0,o=e;for(let u of i){if(o<=u.length)break;o-=u.length+1,s++}for(s=Math.max(0,Math.min(i.length-1,s+n)),o=Math.min(o,i[s].length)+t;o<0&&s>0;)s--,o+=i[s].length+1;for(;o>i[s].length&&s<i.length-1;)o-=i[s].length+1,s++;o=Math.max(0,Math.min(i[s].length,o));let a=0;for(let u=0;u<s;u++)a+=i[u].length+1;return a+o}var Aw=["up","down","left","right","space","enter","cancel"],Hw=["January","February","March","April","May","June","July","August","September","October","November","December"],Xe={actions:new Set(Aw),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:[...Hw],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(e,t)=>`There are only ${e} days in ${t}`,afterMin:(e)=>`Date must be on or after ${e.toISOString().slice(0,10)}`,beforeMax:(e)=>`Date must be on or before ${e.toISOString().slice(0,10)}`}}};function Wl(e,t){if(typeof e=="string")return Xe.aliases.get(e)===t;for(let n of e)if(n!==void 0&&Wl(n,t))return!0;return!1}function Lw(e,t){if(e===t)return;let n=e.split(`
2
+ import{createRequire as _w}from"node:module";var Ow=Object.create;var{getPrototypeOf:Tw,defineProperty:mh,getOwnPropertyNames:Hw}=Object;var Aw=Object.prototype.hasOwnProperty;function Lw(e){return this[e]}var xw,Cw,ko=(e,t,n)=>{var r=e!=null&&typeof e==="object";if(r){var i=t?xw??=new WeakMap:Cw??=new WeakMap,s=i.get(e);if(s)return s}n=e!=null?Ow(Tw(e)):{};let o=t||!e||!e.__esModule?mh(n,"default",{value:e,enumerable:!0}):n;for(let a of Hw(e))if(!Aw.call(o,a))mh(o,a,{get:Lw.bind(e,a),enumerable:!0});if(r)i.set(e,o);return o};var Oe=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var tt=_w(import.meta.url);var mu=Oe((NI,Rh)=>{var gu={to(e,t){if(!t)return`\x1B[${e+1}G`;return`\x1B[${t+1};${e+1}H`},move(e,t){let n="";if(e<0)n+=`\x1B[${-e}D`;else if(e>0)n+=`\x1B[${e}C`;if(t<0)n+=`\x1B[${-t}A`;else if(t>0)n+=`\x1B[${t}B`;return n},up:(e=1)=>`\x1B[${e}A`,down:(e=1)=>`\x1B[${e}B`,forward:(e=1)=>`\x1B[${e}C`,backward:(e=1)=>`\x1B[${e}D`,nextLine:(e=1)=>"\x1B[E".repeat(e),prevLine:(e=1)=>"\x1B[F".repeat(e),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},Dw={up:(e=1)=>"\x1B[S".repeat(e),down:(e=1)=>"\x1B[T".repeat(e)},e0={screen:"\x1B[2J",up:(e=1)=>"\x1B[1J".repeat(e),down:(e=1)=>"\x1B[J".repeat(e),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(e){let t="";for(let n=0;n<e;n++)t+=this.line+(n<e-1?gu.up():"");if(e)t+=gu.left;return t}};Rh.exports={cursor:gu,scroll:Dw,erase:e0,beep:"\x07"}});var lf=Oe((aN,To)=>{var cf=cf||function(e){return Buffer.from(e).toString("base64")};function Y0(e){var t=this,n=Math.round,r=Math.floor,i=Array(64),s=Array(64),o=Array(64),a=Array(64),u,c,l,h,f=Array(65535),d=Array(65535),g=Array(64),p=Array(64),b=[],m=0,$=7,k=Array(64),S=Array(64),w=Array(64),M=Array(256),y=Array(2048),N,R=[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],H=[0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0],A=[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],G=[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],L=[0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0],O=[0,1,2,3,4,5,6,7,8,9,10,11],J=[0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,119],Ee=[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 pe(E){var _=[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 B=0;B<64;B++){var j=r((_[B]*E+50)/100);if(j<1)j=1;else if(j>255)j=255;i[R[B]]=j}var ee=[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 te=0;te<64;te++){var ge=r((ee[te]*E+50)/100);if(ge<1)ge=1;else if(ge>255)ge=255;s[R[te]]=ge}var me=[1,1.387039845,1.306562965,1.175875602,1,0.785694958,0.5411961,0.275899379],Ge=0;for(var Re=0;Re<8;Re++)for(var P=0;P<8;P++)o[Ge]=1/(i[R[Ge]]*me[Re]*me[P]*8),a[Ge]=1/(s[R[Ge]]*me[Re]*me[P]*8),Ge++}function z(E,_){var B=0,j=0,ee=[];for(var te=1;te<=16;te++){for(var ge=1;ge<=E[te];ge++)ee[_[j]]=[],ee[_[j]][0]=B,ee[_[j]][1]=te,j++,B++;B*=2}return ee}function Ae(){u=z(H,A),c=z(L,O),l=z(C,G),h=z(J,Ee)}function he(){var E=1,_=2;for(var B=1;B<=15;B++){for(var j=E;j<_;j++)d[32767+j]=B,f[32767+j]=[],f[32767+j][1]=B,f[32767+j][0]=j;for(var ee=-(_-1);ee<=-E;ee++)d[32767+ee]=B,f[32767+ee]=[],f[32767+ee][1]=B,f[32767+ee][0]=_-1+ee;E<<=1,_<<=1}}function oe(){for(var E=0;E<256;E++)y[E]=19595*E,y[E+256>>0]=38470*E,y[E+512>>0]=7471*E+32768,y[E+768>>0]=-11059*E,y[E+1024>>0]=-21709*E,y[E+1280>>0]=32768*E+8421375,y[E+1536>>0]=-27439*E,y[E+1792>>0]=-5329*E}function re(E){var _=E[0],B=E[1]-1;while(B>=0){if(_&1<<B)m|=1<<$;if(B--,$--,$<0){if(m==255)v(255),v(0);else v(m);$=7,m=0}}}function v(E){b.push(E)}function U(E){v(E>>8&255),v(E&255)}function Me(E,_){var B,j,ee,te,ge,me,Ge,Re,P=0,x,Q=8,Ce=64;for(x=0;x<Q;++x){B=E[P],j=E[P+1],ee=E[P+2],te=E[P+3],ge=E[P+4],me=E[P+5],Ge=E[P+6],Re=E[P+7];var ne=B+Re,ue=B-Re,Ie=j+Ge,q=j-Ge,be=ee+me,Xe=ee-me,Le=te+ge,St=te-ge,zt=ne+Le,rr=ne-Le,Lr=Ie+be,xr=Ie-be;E[P]=zt+Lr,E[P+4]=zt-Lr;var Ai=(xr+rr)*0.707106781;E[P+2]=rr+Ai,E[P+6]=rr-Ai,zt=St+Xe,Lr=Xe+q,xr=q+ue;var Li=(zt-xr)*0.382683433,po=0.5411961*zt+Li,xi=1.306562965*xr+Li,Ci=Lr*0.707106781,_i=ue+Ci,Gi=ue-Ci;E[P+5]=Gi+po,E[P+3]=Gi-po,E[P+1]=_i+xi,E[P+7]=_i-xi,P+=8}P=0;for(x=0;x<Q;++x){B=E[P],j=E[P+8],ee=E[P+16],te=E[P+24],ge=E[P+32],me=E[P+40],Ge=E[P+48],Re=E[P+56];var nh=B+Re,cu=B-Re,rh=j+Ge,ih=j-Ge,sh=ee+me,oh=ee-me,ah=te+ge,Rw=te-ge,Ui=nh+ah,lu=nh-ah,bo=rh+sh,wo=rh-sh;E[P]=Ui+bo,E[P+32]=Ui-bo;var uh=(wo+lu)*0.707106781;E[P+16]=lu+uh,E[P+48]=lu-uh,Ui=Rw+oh,bo=oh+ih,wo=ih+cu;var ch=(Ui-wo)*0.382683433,lh=0.5411961*Ui+ch,hh=1.306562965*wo+ch,fh=bo*0.707106781,dh=cu+fh,gh=cu-fh;E[P+40]=gh+lh,E[P+24]=gh-lh,E[P+8]=dh+hh,E[P+56]=dh-hh,P++}var $o;for(x=0;x<Ce;++x)$o=E[x]*_[x],g[x]=$o>0?$o+0.5|0:$o-0.5|0;return g}function Se(){U(65504),U(16),v(74),v(70),v(73),v(70),v(0),v(1),v(1),v(0),U(1),U(1),v(0),v(0)}function ce(E){if(!E)return;if(U(65505),E[0]===69&&E[1]===120&&E[2]===105&&E[3]===102)U(E.length+2);else U(E.length+5+2),v(69),v(120),v(105),v(102),v(0);for(var _=0;_<E.length;_++)v(E[_])}function le(E,_){U(65472),U(17),v(8),U(_),U(E),v(3),v(1),v(17),v(0),v(2),v(17),v(1),v(3),v(17),v(1)}function ie(){U(65499),U(132),v(0);for(var E=0;E<64;E++)v(i[E]);v(1);for(var _=0;_<64;_++)v(s[_])}function T(){U(65476),U(418),v(0);for(var E=0;E<16;E++)v(H[E+1]);for(var _=0;_<=11;_++)v(A[_]);v(16);for(var B=0;B<16;B++)v(C[B+1]);for(var j=0;j<=161;j++)v(G[j]);v(1);for(var ee=0;ee<16;ee++)v(L[ee+1]);for(var te=0;te<=11;te++)v(O[te]);v(17);for(var ge=0;ge<16;ge++)v(J[ge+1]);for(var me=0;me<=161;me++)v(Ee[me])}function F(E){if(typeof E>"u"||E.constructor!==Array)return;E.forEach((_)=>{if(typeof _!=="string")return;U(65534);var B=_.length;U(B+2);var j;for(j=0;j<B;j++)v(_.charCodeAt(j))})}function Fe(){U(65498),U(12),v(3),v(1),v(0),v(2),v(17),v(3),v(17),v(0),v(63),v(0)}function Y(E,_,B,j,ee){var te=ee[0],ge=ee[240],me,Ge=16,Re=63,P=64,x=Me(E,_);for(var Q=0;Q<P;++Q)p[R[Q]]=x[Q];var Ce=p[0]-B;if(B=p[0],Ce==0)re(j[0]);else me=32767+Ce,re(j[d[me]]),re(f[me]);var ne=63;for(;ne>0&&p[ne]==0;ne--);if(ne==0)return re(te),B;var ue=1,Ie;while(ue<=ne){var q=ue;for(;p[ue]==0&&ue<=ne;++ue);var be=ue-q;if(be>=Ge){Ie=be>>4;for(var Xe=1;Xe<=Ie;++Xe)re(ge);be=be&15}me=32767+p[ue],re(ee[(be<<4)+d[me]]),re(f[me]),ue++}if(ne!=Re)re(te);return B}function se(){var E=String.fromCharCode;for(var _=0;_<256;_++)M[_]=E(_)}this.encode=function(E,_){var B=new Date().getTime();if(_)Mt(_);b=[],m=0,$=7,U(65496),Se(),F(E.comments),ce(E.exifBuffer),ie(),le(E.width,E.height),T(),Fe();var j=0,ee=0,te=0;m=0,$=7,this.encode.displayName="_encode_";var{data:ge,width:me,height:Ge}=E,Re=me*4,P=me*3,x,Q=0,Ce,ne,ue,Ie,q,be,Xe,Le;while(Q<Ge){x=0;while(x<Re){Ie=Re*Q+x,q=Ie,be=-1,Xe=0;for(Le=0;Le<64;Le++){if(Xe=Le>>3,be=(Le&7)*4,q=Ie+Xe*Re+be,Q+Xe>=Ge)q-=Re*(Q+1+Xe-Ge);if(x+be>=Re)q-=x+be-Re+4;Ce=ge[q++],ne=ge[q++],ue=ge[q++],k[Le]=(y[Ce]+y[ne+256>>0]+y[ue+512>>0]>>16)-128,S[Le]=(y[Ce+768>>0]+y[ne+1024>>0]+y[ue+1280>>0]>>16)-128,w[Le]=(y[Ce+1280>>0]+y[ne+1536>>0]+y[ue+1792>>0]>>16)-128}j=Y(k,o,j,u,l),ee=Y(S,a,ee,c,h),te=Y(w,a,te,c,h),x+=32}Q+=8}if($>=0){var St=[];St[1]=$+1,St[0]=(1<<$+1)-1,re(St)}if(U(65497),typeof To>"u")return new Uint8Array(b);return Buffer.from(b);var zt,rr};function Mt(E){if(E<=0)E=1;if(E>100)E=100;if(N==E)return;var _=0;if(E<50)_=Math.floor(5000/E);else _=Math.floor(200-E*2);pe(_),N=E}function _t(){var E=new Date().getTime();if(!e)e=50;se(),Ae(),he(),oe(),Mt(e);var _=new Date().getTime()-E}_t()}if(typeof To<"u")To.exports=uf;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].encode=uf;function uf(e,t){if(typeof t>"u")t=50;var n=new Y0(t),r=n.encode(e,t);return{data:r,width:e.width,height:e.height}}});var ff=Oe((uN,Lu)=>{var Au=function(){var t=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]),n=4017,r=799,i=3406,s=2276,o=1567,a=3784,u=5793,c=2896;function l(){}function h($,k){var S=0,w=[],M,y,N=16;while(N>0&&!$[N-1])N--;w.push({children:[],index:0});var R=w[0],H;for(M=0;M<N;M++){for(y=0;y<$[M];y++){R=w.pop(),R.children[R.index]=k[S];while(R.index>0){if(w.length===0)throw Error("Could not recreate Huffman Table");R=w.pop()}R.index++,w.push(R);while(w.length<=M)w.push(H={children:[],index:0}),R.children[R.index]=H.children,R=H;S++}if(M+1<N)w.push(H={children:[],index:0}),R.children[R.index]=H.children,R=H}return w[0].children}function f($,k,S,w,M,y,N,R,H,A){var{precision:C,samplesPerLine:G,scanLines:L,mcusPerLine:O,progressive:J,maxH:Ee,maxV:pe}=S,z=k,Ae=0,he=0;function oe(){if(he>0)return he--,Ae>>he&1;if(Ae=$[k++],Ae==255){var P=$[k++];if(P)throw Error("unexpected marker: "+(Ae<<8|P).toString(16))}return he=7,Ae>>>7}function re(P){var x=P,Q;while((Q=oe())!==null){if(x=x[Q],typeof x==="number")return x;if(typeof x!=="object")throw Error("invalid huffman sequence")}return null}function v(P){var x=0;while(P>0){var Q=oe();if(Q===null)return;x=x<<1|Q,P--}return x}function U(P){var x=v(P);if(x>=1<<P-1)return x;return x+(-1<<P)+1}function Me(P,x){var Q=re(P.huffmanTableDC),Ce=Q===0?0:U(Q);x[0]=P.pred+=Ce;var ne=1;while(ne<64){var ue=re(P.huffmanTableAC),Ie=ue&15,q=ue>>4;if(Ie===0){if(q<15)break;ne+=16;continue}ne+=q;var be=t[ne];x[be]=U(Ie),ne++}}function Se(P,x){var Q=re(P.huffmanTableDC),Ce=Q===0?0:U(Q)<<H;x[0]=P.pred+=Ce}function ce(P,x){x[0]|=oe()<<H}var le=0;function ie(P,x){if(le>0){le--;return}var Q=y,Ce=N;while(Q<=Ce){var ne=re(P.huffmanTableAC),ue=ne&15,Ie=ne>>4;if(ue===0){if(Ie<15){le=v(Ie)+(1<<Ie)-1;break}Q+=16;continue}Q+=Ie;var q=t[Q];x[q]=U(ue)*(1<<H),Q++}}var T=0,F;function Fe(P,x){var Q=y,Ce=N,ne=0;while(Q<=Ce){var ue=t[Q],Ie=x[ue]<0?-1:1;switch(T){case 0:var q=re(P.huffmanTableAC),be=q&15,ne=q>>4;if(be===0)if(ne<15)le=v(ne)+(1<<ne),T=4;else ne=16,T=1;else{if(be!==1)throw Error("invalid ACn encoding");F=U(be),T=ne?2:3}continue;case 1:case 2:if(x[ue])x[ue]+=(oe()<<H)*Ie;else if(ne--,ne===0)T=T==2?3:0;break;case 3:if(x[ue])x[ue]+=(oe()<<H)*Ie;else x[ue]=F<<H,T=0;break;case 4:if(x[ue])x[ue]+=(oe()<<H)*Ie;break}Q++}if(T===4){if(le--,le===0)T=0}}function Y(P,x,Q,Ce,ne){var ue=Q/O|0,Ie=Q%O,q=ue*P.v+Ce,be=Ie*P.h+ne;if(P.blocks[q]===void 0&&A.tolerantDecoding)return;x(P,P.blocks[q][be])}function se(P,x,Q){var Ce=Q/P.blocksPerLine|0,ne=Q%P.blocksPerLine;if(P.blocks[Ce]===void 0&&A.tolerantDecoding)return;x(P,P.blocks[Ce][ne])}var Mt=w.length,_t,E,_,B,j,ee;if(J)if(y===0)ee=R===0?Se:ce;else ee=R===0?ie:Fe;else ee=Me;var te=0,ge,me;if(Mt==1)me=w[0].blocksPerLine*w[0].blocksPerColumn;else me=O*S.mcusPerColumn;if(!M)M=me;var Ge,Re;while(te<me){for(E=0;E<Mt;E++)w[E].pred=0;if(le=0,Mt==1){_t=w[0];for(j=0;j<M;j++)se(_t,ee,te),te++}else for(j=0;j<M;j++){for(E=0;E<Mt;E++){_t=w[E],Ge=_t.h,Re=_t.v;for(_=0;_<Re;_++)for(B=0;B<Ge;B++)Y(_t,ee,te,_,B)}if(te++,te===me)break}if(te===me)do{if($[k]===255){if($[k+1]!==0)break}k+=1}while(k<$.length-2);if(he=0,ge=$[k]<<8|$[k+1],ge<65280)throw Error("marker was not found");if(ge>=65488&&ge<=65495)k+=2;else break}return k-z}function d($,k){var S=[],w=k.blocksPerLine,M=k.blocksPerColumn,y=w<<3,N=new Int32Array(64),R=new Uint8Array(64);function H(z,Ae,he){var oe=k.quantizationTable,re,v,U,Me,Se,ce,le,ie,T,F=he,Fe;for(Fe=0;Fe<64;Fe++)F[Fe]=z[Fe]*oe[Fe];for(Fe=0;Fe<8;++Fe){var Y=8*Fe;if(F[1+Y]==0&&F[2+Y]==0&&F[3+Y]==0&&F[4+Y]==0&&F[5+Y]==0&&F[6+Y]==0&&F[7+Y]==0){T=u*F[0+Y]+512>>10,F[0+Y]=T,F[1+Y]=T,F[2+Y]=T,F[3+Y]=T,F[4+Y]=T,F[5+Y]=T,F[6+Y]=T,F[7+Y]=T;continue}re=u*F[0+Y]+128>>8,v=u*F[4+Y]+128>>8,U=F[2+Y],Me=F[6+Y],Se=c*(F[1+Y]-F[7+Y])+128>>8,ie=c*(F[1+Y]+F[7+Y])+128>>8,ce=F[3+Y]<<4,le=F[5+Y]<<4,T=re-v+1>>1,re=re+v+1>>1,v=T,T=U*a+Me*o+128>>8,U=U*o-Me*a+128>>8,Me=T,T=Se-le+1>>1,Se=Se+le+1>>1,le=T,T=ie+ce+1>>1,ce=ie-ce+1>>1,ie=T,T=re-Me+1>>1,re=re+Me+1>>1,Me=T,T=v-U+1>>1,v=v+U+1>>1,U=T,T=Se*s+ie*i+2048>>12,Se=Se*i-ie*s+2048>>12,ie=T,T=ce*r+le*n+2048>>12,ce=ce*n-le*r+2048>>12,le=T,F[0+Y]=re+ie,F[7+Y]=re-ie,F[1+Y]=v+le,F[6+Y]=v-le,F[2+Y]=U+ce,F[5+Y]=U-ce,F[3+Y]=Me+Se,F[4+Y]=Me-Se}for(Fe=0;Fe<8;++Fe){var se=Fe;if(F[8+se]==0&&F[16+se]==0&&F[24+se]==0&&F[32+se]==0&&F[40+se]==0&&F[48+se]==0&&F[56+se]==0){T=u*he[Fe+0]+8192>>14,F[0+se]=T,F[8+se]=T,F[16+se]=T,F[24+se]=T,F[32+se]=T,F[40+se]=T,F[48+se]=T,F[56+se]=T;continue}re=u*F[0+se]+2048>>12,v=u*F[32+se]+2048>>12,U=F[16+se],Me=F[48+se],Se=c*(F[8+se]-F[56+se])+2048>>12,ie=c*(F[8+se]+F[56+se])+2048>>12,ce=F[24+se],le=F[40+se],T=re-v+1>>1,re=re+v+1>>1,v=T,T=U*a+Me*o+2048>>12,U=U*o-Me*a+2048>>12,Me=T,T=Se-le+1>>1,Se=Se+le+1>>1,le=T,T=ie+ce+1>>1,ce=ie-ce+1>>1,ie=T,T=re-Me+1>>1,re=re+Me+1>>1,Me=T,T=v-U+1>>1,v=v+U+1>>1,U=T,T=Se*s+ie*i+2048>>12,Se=Se*i-ie*s+2048>>12,ie=T,T=ce*r+le*n+2048>>12,ce=ce*n-le*r+2048>>12,le=T,F[0+se]=re+ie,F[56+se]=re-ie,F[8+se]=v+le,F[48+se]=v-le,F[16+se]=U+ce,F[40+se]=U-ce,F[24+se]=Me+Se,F[32+se]=Me-Se}for(Fe=0;Fe<64;++Fe){var Mt=128+(F[Fe]+8>>4);Ae[Fe]=Mt<0?0:Mt>255?255:Mt}}m(y*M*8);var A,C;for(var G=0;G<M;G++){var L=G<<3;for(A=0;A<8;A++)S.push(new Uint8Array(y));for(var O=0;O<w;O++){H(k.blocks[G][O],R,N);var J=0,Ee=O<<3;for(C=0;C<8;C++){var pe=S[L+C];for(A=0;A<8;A++)pe[Ee+A]=R[J++]}}}return S}function g($){return $<0?0:$>255?255:$}l.prototype={load:function(k){var S=new XMLHttpRequest;S.open("GET",k,!0),S.responseType="arraybuffer",S.onload=function(){var w=new Uint8Array(S.response||S.mozResponseArrayBuffer);if(this.parse(w),this.onload)this.onload()}.bind(this),S.send(null)},parse:function(k){var S=this.opts.maxResolutionInMP*1000*1000,w=0,M=k.length;function y(){var q=k[w]<<8|k[w+1];return w+=2,q}function N(){var q=y(),be=k.subarray(w,w+q-2);return w+=be.length,be}function R(q){var be=1,Xe=1,Le,St;for(St in q.components)if(q.components.hasOwnProperty(St)){if(Le=q.components[St],be<Le.h)be=Le.h;if(Xe<Le.v)Xe=Le.v}var zt=Math.ceil(q.samplesPerLine/8/be),rr=Math.ceil(q.scanLines/8/Xe);for(St in q.components)if(q.components.hasOwnProperty(St)){Le=q.components[St];var Lr=Math.ceil(Math.ceil(q.samplesPerLine/8)*Le.h/be),xr=Math.ceil(Math.ceil(q.scanLines/8)*Le.v/Xe),Ai=zt*Le.h,Li=rr*Le.v,po=Li*Ai,xi=[];m(po*256);for(var Ci=0;Ci<Li;Ci++){var _i=[];for(var Gi=0;Gi<Ai;Gi++)_i.push(new Int32Array(64));xi.push(_i)}Le.blocksPerLine=Lr,Le.blocksPerColumn=xr,Le.blocks=xi}q.maxH=be,q.maxV=Xe,q.mcusPerLine=zt,q.mcusPerColumn=rr}var H=null,A=null,C=null,G,L,O=[],J=[],Ee=[],pe=[],z=y(),Ae=-1;if(this.comments=[],z!=65496)throw Error("SOI not found");z=y();while(z!=65497){var he,oe,re;switch(z){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 v=N();if(z===65534){var U=String.fromCharCode.apply(null,v);this.comments.push(U)}if(z===65504){if(v[0]===74&&v[1]===70&&v[2]===73&&v[3]===70&&v[4]===0)H={version:{major:v[5],minor:v[6]},densityUnits:v[7],xDensity:v[8]<<8|v[9],yDensity:v[10]<<8|v[11],thumbWidth:v[12],thumbHeight:v[13],thumbData:v.subarray(14,14+3*v[12]*v[13])}}if(z===65505){if(v[0]===69&&v[1]===120&&v[2]===105&&v[3]===102&&v[4]===0)this.exifBuffer=v.subarray(5,v.length)}if(z===65518){if(v[0]===65&&v[1]===100&&v[2]===111&&v[3]===98&&v[4]===101&&v[5]===0)A={version:v[6],flags0:v[7]<<8|v[8],flags1:v[9]<<8|v[10],transformCode:v[11]}}break;case 65499:var Me=y(),Se=Me+w-2;while(w<Se){var ce=k[w++];m(256);var le=new Int32Array(64);if(ce>>4===0)for(oe=0;oe<64;oe++){var ie=t[oe];le[ie]=k[w++]}else if(ce>>4===1)for(oe=0;oe<64;oe++){var ie=t[oe];le[ie]=y()}else throw Error("DQT: invalid table spec");O[ce&15]=le}break;case 65472:case 65473:case 65474:y(),G={},G.extended=z===65473,G.progressive=z===65474,G.precision=k[w++],G.scanLines=y(),G.samplesPerLine=y(),G.components={},G.componentsOrder=[];var T=G.scanLines*G.samplesPerLine;if(T>S){var F=Math.ceil((T-S)/1e6);throw Error(`maxResolutionInMP limit exceeded by ${F}MP`)}var Fe=k[w++],Y,se=0,Mt=0;for(he=0;he<Fe;he++){Y=k[w];var _t=k[w+1]>>4,E=k[w+1]&15,_=k[w+2];if(_t<=0||E<=0)throw Error("Invalid sampling factor, expected values above 0");G.componentsOrder.push(Y),G.components[Y]={h:_t,v:E,quantizationIdx:_},w+=3}R(G),J.push(G);break;case 65476:var B=y();for(he=2;he<B;){var j=k[w++],ee=new Uint8Array(16),te=0;for(oe=0;oe<16;oe++,w++)te+=ee[oe]=k[w];m(16+te);var ge=new Uint8Array(te);for(oe=0;oe<te;oe++,w++)ge[oe]=k[w];he+=17+te,(j>>4===0?pe:Ee)[j&15]=h(ee,ge)}break;case 65501:y(),L=y();break;case 65500:y(),y();break;case 65498:var me=y(),Ge=k[w++],Re=[],P;for(he=0;he<Ge;he++){P=G.components[k[w++]];var x=k[w++];P.huffmanTableDC=pe[x>>4],P.huffmanTableAC=Ee[x&15],Re.push(P)}var Q=k[w++],Ce=k[w++],ne=k[w++],ue=f(k,w,G,Re,L,Q,Ce,ne>>4,ne&15,this.opts);w+=ue;break;case 65535:if(k[w]!==255)w--;break;default:if(k[w-3]==255&&k[w-2]>=192&&k[w-2]<=254){w-=3;break}else if(z===224||z==225){if(Ae!==-1)throw Error(`first unknown JPEG marker at offset ${Ae.toString(16)}, second unknown JPEG marker ${z.toString(16)} at offset ${(w-1).toString(16)}`);Ae=w-1;let q=y();if(k[w+q-2]===255){w+=q-2;break}}throw Error("unknown JPEG marker "+z.toString(16))}z=y()}if(J.length!=1)throw Error("only single frame JPEGs supported");for(var he=0;he<J.length;he++){var Ie=J[he].components;for(var oe in Ie)Ie[oe].quantizationTable=O[Ie[oe].quantizationIdx],delete Ie[oe].quantizationIdx}this.width=G.samplesPerLine,this.height=G.scanLines,this.jfif=H,this.adobe=A,this.components=[];for(var he=0;he<G.componentsOrder.length;he++){var P=G.components[G.componentsOrder[he]];this.components.push({lines:d(G,P),scaleX:P.h/G.maxH,scaleY:P.v/G.maxV})}},getData:function(k,S){var w=this.width/k,M=this.height/S,y,N,R,H,A,C,G,L,O,J,Ee=0,pe,z,Ae,he,oe,re,v,U,Me,Se,ce,le=k*S*this.components.length;m(le);var ie=new Uint8Array(le);switch(this.components.length){case 1:y=this.components[0];for(J=0;J<S;J++){A=y.lines[0|J*y.scaleY*M];for(O=0;O<k;O++)pe=A[0|O*y.scaleX*w],ie[Ee++]=pe}break;case 2:y=this.components[0],N=this.components[1];for(J=0;J<S;J++){A=y.lines[0|J*y.scaleY*M],C=N.lines[0|J*N.scaleY*M];for(O=0;O<k;O++)pe=A[0|O*y.scaleX*w],ie[Ee++]=pe,pe=C[0|O*N.scaleX*w],ie[Ee++]=pe}break;case 3:if(ce=!0,this.adobe&&this.adobe.transformCode)ce=!0;else if(typeof this.opts.colorTransform<"u")ce=!!this.opts.colorTransform;y=this.components[0],N=this.components[1],R=this.components[2];for(J=0;J<S;J++){A=y.lines[0|J*y.scaleY*M],C=N.lines[0|J*N.scaleY*M],G=R.lines[0|J*R.scaleY*M];for(O=0;O<k;O++){if(!ce)U=A[0|O*y.scaleX*w],Me=C[0|O*N.scaleX*w],Se=G[0|O*R.scaleX*w];else pe=A[0|O*y.scaleX*w],z=C[0|O*N.scaleX*w],Ae=G[0|O*R.scaleX*w],U=g(pe+1.402*(Ae-128)),Me=g(pe-0.3441363*(z-128)-0.71413636*(Ae-128)),Se=g(pe+1.772*(z-128));ie[Ee++]=U,ie[Ee++]=Me,ie[Ee++]=Se}}break;case 4:if(!this.adobe)throw Error("Unsupported color mode (4 components)");if(ce=!1,this.adobe&&this.adobe.transformCode)ce=!0;else if(typeof this.opts.colorTransform<"u")ce=!!this.opts.colorTransform;y=this.components[0],N=this.components[1],R=this.components[2],H=this.components[3];for(J=0;J<S;J++){A=y.lines[0|J*y.scaleY*M],C=N.lines[0|J*N.scaleY*M],G=R.lines[0|J*R.scaleY*M],L=H.lines[0|J*H.scaleY*M];for(O=0;O<k;O++){if(!ce)oe=A[0|O*y.scaleX*w],re=C[0|O*N.scaleX*w],v=G[0|O*R.scaleX*w],he=L[0|O*H.scaleX*w];else pe=A[0|O*y.scaleX*w],z=C[0|O*N.scaleX*w],Ae=G[0|O*R.scaleX*w],he=L[0|O*H.scaleX*w],oe=255-g(pe+1.402*(Ae-128)),re=255-g(pe-0.3441363*(z-128)-0.71413636*(Ae-128)),v=255-g(pe+1.772*(z-128));ie[Ee++]=255-oe,ie[Ee++]=255-re,ie[Ee++]=255-v,ie[Ee++]=255-he}}break;default:throw Error("Unsupported color mode")}return ie},copyToImageData:function(k,S){var{width:w,height:M,data:y}=k,N=this.getData(w,M),R=0,H=0,A,C,G,L,O,J,Ee,pe,z;switch(this.components.length){case 1:for(C=0;C<M;C++)for(A=0;A<w;A++)if(G=N[R++],y[H++]=G,y[H++]=G,y[H++]=G,S)y[H++]=255;break;case 3:for(C=0;C<M;C++)for(A=0;A<w;A++)if(Ee=N[R++],pe=N[R++],z=N[R++],y[H++]=Ee,y[H++]=pe,y[H++]=z,S)y[H++]=255;break;case 4:for(C=0;C<M;C++)for(A=0;A<w;A++)if(O=N[R++],J=N[R++],G=N[R++],L=N[R++],Ee=255-g(O*(1-L/255)+L),pe=255-g(J*(1-L/255)+L),z=255-g(G*(1-L/255)+L),y[H++]=Ee,y[H++]=pe,y[H++]=z,S)y[H++]=255;break;default:throw Error("Unsupported color mode")}}};var p=0,b=0;function m($=0){var k=p+$;if(k>b){var S=Math.ceil((k-b)/1024/1024);throw Error(`maxMemoryUsageInMB limit exceeded by at least ${S}MB`)}p=k}return l.resetMaxMemoryUsage=function($){p=0,b=$},l.getBytesAllocated=function(){return p},l.requestMemoryAllocation=m,l}();if(typeof Lu<"u")Lu.exports=hf;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].decode=hf;function hf(e,t={}){var n={colorTransform:void 0,useTArray:!1,formatAsRGBA:!0,tolerantDecoding:!0,maxResolutionInMP:100,maxMemoryUsageInMB:512},r={...n,...t},i=new Uint8Array(e),s=new Au;s.opts=r,Au.resetMaxMemoryUsage(r.maxMemoryUsageInMB*1024*1024),s.parse(i);var o=r.formatAsRGBA?4:3,a=s.width*s.height*o;try{Au.requestMemoryAllocation(a);var u={width:s.width,height:s.height,exifBuffer:s.exifBuffer,data:r.useTArray?new Uint8Array(a):Buffer.alloc(a)};if(s.comments.length>0)u.comments=s.comments}catch(c){if(c instanceof RangeError)throw Error("Could not allocate enough memory for the image. Required: "+a);if(c instanceof ReferenceError){if(c.message==="Buffer is not defined")throw Error("Buffer is not globally defined in this environment. Consider setting useTArray to true")}throw c}return s.copyToImageData(u,r.formatAsRGBA),u}});var gf=Oe((cN,df)=>{var Q0=lf(),Z0=ff();df.exports={encode:Q0,decode:Z0}});var xu=Oe((lN,pf)=>{var V0=tt("util"),mf=tt("stream"),Ut=pf.exports=function(){mf.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};V0.inherits(Ut,mf);Ut.prototype.read=function(e,t){this._reads.push({length:Math.abs(e),allowLess:e<0,func:t}),process.nextTick(function(){if(this._process(),this._paused&&this._reads&&this._reads.length>0)this._paused=!1,this.emit("drain")}.bind(this))};Ut.prototype.write=function(e,t){if(!this.writable)return this.emit("error",Error("Stream not writable")),!1;let n;if(Buffer.isBuffer(e))n=e;else n=Buffer.from(e,t||this._encoding);if(this._buffers.push(n),this._buffered+=n.length,this._process(),this._reads&&this._reads.length===0)this._paused=!0;return this.writable&&!this._paused};Ut.prototype.end=function(e,t){if(e)this.write(e,t);if(this.writable=!1,!this._buffers)return;if(this._buffers.length===0)this._end();else this._buffers.push(null),this._process()};Ut.prototype.destroySoon=Ut.prototype.end;Ut.prototype._end=function(){if(this._reads.length>0)this.emit("error",Error("Unexpected end of input"));this.destroy()};Ut.prototype.destroy=function(){if(!this._buffers)return;this.writable=!1,this._reads=null,this._buffers=null,this.emit("close")};Ut.prototype._processReadAllowingLess=function(e){this._reads.shift();let t=this._buffers[0];if(t.length>e.length)this._buffered-=e.length,this._buffers[0]=t.slice(e.length),e.func.call(this,t.slice(0,e.length));else this._buffered-=t.length,this._buffers.shift(),e.func.call(this,t)};Ut.prototype._processRead=function(e){this._reads.shift();let t=0,n=0,r=Buffer.alloc(e.length);while(t<e.length){let i=this._buffers[n++],s=Math.min(i.length,e.length-t);if(i.copy(r,t,0,s),t+=s,s!==i.length)this._buffers[--n]=i.slice(s)}if(n>0)this._buffers.splice(0,n);this._buffered-=e.length,e.func.call(this,r)};Ut.prototype._process=function(){try{while(this._buffered>0&&this._reads&&this._reads.length>0){let e=this._reads[0];if(e.allowLess)this._processReadAllowingLess(e);else if(this._buffered>=e.length)this._processRead(e);else break}if(this._buffers&&!this.writable)this._end()}catch(e){this.emit("error",e)}}});var Cu=Oe((X0)=>{var Hn=[{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]}];X0.getImagePasses=function(e,t){let n=[],r=e%8,i=t%8,s=(e-r)/8,o=(t-i)/8;for(let a=0;a<Hn.length;a++){let u=Hn[a],c=s*u.x.length,l=o*u.y.length;for(let h=0;h<u.x.length;h++)if(u.x[h]<r)c++;else break;for(let h=0;h<u.y.length;h++)if(u.y[h]<i)l++;else break;if(c>0&&l>0)n.push({width:c,height:l,index:a})}return n};X0.getInterlaceIterator=function(e){return function(t,n,r){let i=t%Hn[r].x.length,s=(t-i)/Hn[r].x.length*8+Hn[r].x[i],o=n%Hn[r].y.length,a=(n-o)/Hn[r].y.length*8+Hn[r].y[o];return s*4+a*e*4}}});var _u=Oe((fN,bf)=>{bf.exports=function(t,n,r){let i=t+n-r,s=Math.abs(i-t),o=Math.abs(i-n),a=Math.abs(i-r);if(s<=o&&s<=a)return t;if(o<=a)return n;return r}});var Gu=Oe((dN,$f)=>{var t$=Cu(),n$=_u();function wf(e,t,n){let r=e*t;if(n!==8)r=Math.ceil(r/(8/n));return r}var Jr=$f.exports=function(e,t){let{width:n,height:r,interlace:i,bpp:s,depth:o}=e;if(this.read=t.read,this.write=t.write,this.complete=t.complete,this._imageIndex=0,this._images=[],i){let a=t$.getImagePasses(n,r);for(let u=0;u<a.length;u++)this._images.push({byteWidth:wf(a[u].width,s,o),height:a[u].height,lineIndex:0})}else this._images.push({byteWidth:wf(n,s,o),height:r,lineIndex:0});if(o===8)this._xComparison=s;else if(o===16)this._xComparison=s*2;else this._xComparison=1};Jr.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Jr.prototype._unFilterType1=function(e,t,n){let r=this._xComparison,i=r-1;for(let s=0;s<n;s++){let o=e[1+s],a=s>i?t[s-r]:0;t[s]=o+a}};Jr.prototype._unFilterType2=function(e,t,n){let r=this._lastLine;for(let i=0;i<n;i++){let s=e[1+i],o=r?r[i]:0;t[i]=s+o}};Jr.prototype._unFilterType3=function(e,t,n){let r=this._xComparison,i=r-1,s=this._lastLine;for(let o=0;o<n;o++){let a=e[1+o],u=s?s[o]:0,c=o>i?t[o-r]:0,l=Math.floor((c+u)/2);t[o]=a+l}};Jr.prototype._unFilterType4=function(e,t,n){let r=this._xComparison,i=r-1,s=this._lastLine;for(let o=0;o<n;o++){let a=e[1+o],u=s?s[o]:0,c=o>i?t[o-r]:0,l=o>i&&s?s[o-r]:0,h=n$(c,u,l);t[o]=a+h}};Jr.prototype._reverseFilterLine=function(e){let t=e[0],n,r=this._images[this._imageIndex],i=r.byteWidth;if(t===0)n=e.slice(1,i+1);else switch(n=Buffer.alloc(i),t){case 1:this._unFilterType1(e,n,i);break;case 2:this._unFilterType2(e,n,i);break;case 3:this._unFilterType3(e,n,i);break;case 4:this._unFilterType4(e,n,i);break;default:throw Error("Unrecognised filter type - "+t)}if(this.write(n),r.lineIndex++,r.lineIndex>=r.height)this._lastLine=null,this._imageIndex++,r=this._images[this._imageIndex];else this._lastLine=n;if(r)this.read(r.byteWidth+1,this._reverseFilterLine.bind(this));else this._lastLine=null,this.complete()}});var Ef=Oe((gN,yf)=>{var r$=tt("util"),kf=xu(),i$=Gu(),s$=yf.exports=function(e){kf.call(this);let t=[],n=this;this._filter=new i$(e,{read:this.read.bind(this),write:function(r){t.push(r)},complete:function(){n.emit("complete",Buffer.concat(t))}}),this._filter.start()};r$.inherits(s$,kf)});var Br=Oe((mN,vf)=>{vf.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 Wu=Oe((pN,Mf)=>{var Uu=[];(function(){for(let e=0;e<256;e++){let t=e;for(let n=0;n<8;n++)if(t&1)t=3988292384^t>>>1;else t=t>>>1;Uu[e]=t}})();var ju=Mf.exports=function(){this._crc=-1};ju.prototype.write=function(e){for(let t=0;t<e.length;t++)this._crc=Uu[(this._crc^e[t])&255]^this._crc>>>8;return!0};ju.prototype.crc32=function(){return this._crc^-1};ju.crc32=function(e){let t=-1;for(let n=0;n<e.length;n++)t=Uu[(t^e[n])&255]^t>>>8;return t^-1}});var Ku=Oe((bN,Sf)=>{var Ze=Br(),o$=Wu(),Ve=Sf.exports=function(e,t){this._options=e,e.checkCRC=e.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[Ze.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[Ze.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[Ze.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[Ze.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[Ze.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[Ze.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=t.read,this.error=t.error,this.metadata=t.metadata,this.gamma=t.gamma,this.transColor=t.transColor,this.palette=t.palette,this.parsed=t.parsed,this.inflateData=t.inflateData,this.finished=t.finished,this.simpleTransparency=t.simpleTransparency,this.headersFinished=t.headersFinished||function(){}};Ve.prototype.start=function(){this.read(Ze.PNG_SIGNATURE.length,this._parseSignature.bind(this))};Ve.prototype._parseSignature=function(e){let t=Ze.PNG_SIGNATURE;for(let n=0;n<t.length;n++)if(e[n]!==t[n]){this.error(Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};Ve.prototype._parseChunkBegin=function(e){let t=e.readUInt32BE(0),n=e.readUInt32BE(4),r="";for(let s=4;s<8;s++)r+=String.fromCharCode(e[s]);let i=Boolean(e[4]&32);if(!this._hasIHDR&&n!==Ze.TYPE_IHDR){this.error(Error("Expected IHDR on beggining"));return}if(this._crc=new o$,this._crc.write(Buffer.from(r)),this._chunks[n])return this._chunks[n](t);if(!i){this.error(Error("Unsupported critical chunk type "+r));return}this.read(t+4,this._skipChunk.bind(this))};Ve.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};Ve.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};Ve.prototype._parseChunkEnd=function(e){let t=e.readInt32BE(0),n=this._crc.crc32();if(this._options.checkCRC&&n!==t){this.error(Error("Crc error - "+t+" - "+n));return}if(!this._hasIEND)this.read(8,this._parseChunkBegin.bind(this))};Ve.prototype._handleIHDR=function(e){this.read(e,this._parseIHDR.bind(this))};Ve.prototype._parseIHDR=function(e){this._crc.write(e);let t=e.readUInt32BE(0),n=e.readUInt32BE(4),r=e[8],i=e[9],s=e[10],o=e[11],a=e[12];if(r!==8&&r!==4&&r!==2&&r!==1&&r!==16){this.error(Error("Unsupported bit depth "+r));return}if(!(i in Ze.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(a!==0&&a!==1){this.error(Error("Unsupported interlace method"));return}this._colorType=i;let u=Ze.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:t,height:n,depth:r,interlace:Boolean(a),palette:Boolean(i&Ze.COLORTYPE_PALETTE),color:Boolean(i&Ze.COLORTYPE_COLOR),alpha:Boolean(i&Ze.COLORTYPE_ALPHA),bpp:u,colorType:i}),this._handleChunkEnd()};Ve.prototype._handlePLTE=function(e){this.read(e,this._parsePLTE.bind(this))};Ve.prototype._parsePLTE=function(e){this._crc.write(e);let t=Math.floor(e.length/3);for(let n=0;n<t;n++)this._palette.push([e[n*3],e[n*3+1],e[n*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};Ve.prototype._handleTRNS=function(e){this.simpleTransparency(),this.read(e,this._parseTRNS.bind(this))};Ve.prototype._parseTRNS=function(e){if(this._crc.write(e),this._colorType===Ze.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(Error("Transparency chunk must be after palette"));return}if(e.length>this._palette.length){this.error(Error("More transparent colors than palette size"));return}for(let t=0;t<e.length;t++)this._palette[t][3]=e[t];this.palette(this._palette)}if(this._colorType===Ze.COLORTYPE_GRAYSCALE)this.transColor([e.readUInt16BE(0)]);if(this._colorType===Ze.COLORTYPE_COLOR)this.transColor([e.readUInt16BE(0),e.readUInt16BE(2),e.readUInt16BE(4)]);this._handleChunkEnd()};Ve.prototype._handleGAMA=function(e){this.read(e,this._parseGAMA.bind(this))};Ve.prototype._parseGAMA=function(e){this._crc.write(e),this.gamma(e.readUInt32BE(0)/Ze.GAMMA_DIVISION),this._handleChunkEnd()};Ve.prototype._handleIDAT=function(e){if(!this._emittedHeadersFinished)this._emittedHeadersFinished=!0,this.headersFinished();this.read(-e,this._parseIDAT.bind(this,e))};Ve.prototype._parseIDAT=function(e,t){if(this._crc.write(t),this._colorType===Ze.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw Error("Expected palette not found");this.inflateData(t);let n=e-t.length;if(n>0)this._handleIDAT(n);else this._handleChunkEnd()};Ve.prototype._handleIEND=function(e){this.read(e,this._parseIEND.bind(this))};Ve.prototype._parseIEND=function(e){if(this._crc.write(e),this._hasIEND=!0,this._handleChunkEnd(),this.finished)this.finished()}});var Ju=Oe((f$)=>{var If=Cu(),a$=[function(){},function(e,t,n,r){if(r===t.length)throw Error("Ran out of data");let i=t[r];e[n]=i,e[n+1]=i,e[n+2]=i,e[n+3]=255},function(e,t,n,r){if(r+1>=t.length)throw Error("Ran out of data");let i=t[r];e[n]=i,e[n+1]=i,e[n+2]=i,e[n+3]=t[r+1]},function(e,t,n,r){if(r+2>=t.length)throw Error("Ran out of data");e[n]=t[r],e[n+1]=t[r+1],e[n+2]=t[r+2],e[n+3]=255},function(e,t,n,r){if(r+3>=t.length)throw Error("Ran out of data");e[n]=t[r],e[n+1]=t[r+1],e[n+2]=t[r+2],e[n+3]=t[r+3]}],u$=[function(){},function(e,t,n,r){let i=t[0];e[n]=i,e[n+1]=i,e[n+2]=i,e[n+3]=r},function(e,t,n){let r=t[0];e[n]=r,e[n+1]=r,e[n+2]=r,e[n+3]=t[1]},function(e,t,n,r){e[n]=t[0],e[n+1]=t[1],e[n+2]=t[2],e[n+3]=r},function(e,t,n){e[n]=t[0],e[n+1]=t[1],e[n+2]=t[2],e[n+3]=t[3]}];function c$(e,t){let n=[],r=0;function i(){if(r===e.length)throw Error("Ran out of data");let s=e[r];r++;let o,a,u,c,l,h,f,d;switch(t){default:throw Error("unrecognised depth");case 16:f=e[r],r++,n.push((s<<8)+f);break;case 4:f=s&15,d=s>>4,n.push(d,f);break;case 2:l=s&3,h=s>>2&3,f=s>>4&3,d=s>>6&3,n.push(d,f,h,l);break;case 1:o=s&1,a=s>>1&1,u=s>>2&1,c=s>>3&1,l=s>>4&1,h=s>>5&1,f=s>>6&1,d=s>>7&1,n.push(d,f,h,l,c,u,a,o);break}}return{get:function(s){while(n.length<s)i();let o=n.slice(0,s);return n=n.slice(s),o},resetAfterLine:function(){n.length=0},end:function(){if(r!==e.length)throw Error("extra data found")}}}function l$(e,t,n,r,i,s){let{width:o,height:a,index:u}=e;for(let c=0;c<a;c++)for(let l=0;l<o;l++){let h=n(l,c,u);a$[r](t,i,h,s),s+=r}return s}function h$(e,t,n,r,i,s){let{width:o,height:a,index:u}=e;for(let c=0;c<a;c++){for(let l=0;l<o;l++){let h=i.get(r),f=n(l,c,u);u$[r](t,h,f,s)}i.resetAfterLine()}}f$.dataToBitMap=function(e,t){let{width:n,height:r,depth:i,bpp:s,interlace:o}=t,a;if(i!==8)a=c$(e,i);let u;if(i<=8)u=Buffer.alloc(n*r*4);else u=new Uint16Array(n*r*4);let c=Math.pow(2,i)-1,l=0,h,f;if(o)h=If.getImagePasses(n,r),f=If.getInterlaceIterator(n,r);else{let d=0;f=function(){let g=d;return d+=4,g},h=[{width:n,height:r}]}for(let d=0;d<h.length;d++)if(i===8)l=l$(h[d],u,f,s,e,l);else h$(h[d],u,f,s,a,c);if(i===8){if(l!==e.length)throw Error("extra data found")}else a.end();return u}});var Bu=Oe(($N,Nf)=>{function g$(e,t,n,r,i){let s=0;for(let o=0;o<r;o++)for(let a=0;a<n;a++){let u=i[e[s]];if(!u)throw Error("index "+e[s]+" not in palette");for(let c=0;c<4;c++)t[s+c]=u[c];s+=4}}function m$(e,t,n,r,i){let s=0;for(let o=0;o<r;o++)for(let a=0;a<n;a++){let u=!1;if(i.length===1){if(i[0]===e[s])u=!0}else if(i[0]===e[s]&&i[1]===e[s+1]&&i[2]===e[s+2])u=!0;if(u)for(let c=0;c<4;c++)t[s+c]=0;s+=4}}function p$(e,t,n,r,i){let s=255,o=Math.pow(2,i)-1,a=0;for(let u=0;u<r;u++)for(let c=0;c<n;c++){for(let l=0;l<4;l++)t[a+l]=Math.floor(e[a+l]*s/o+0.5);a+=4}}Nf.exports=function(e,t,n=!1){let{depth:r,width:i,height:s,colorType:o,transColor:a,palette:u}=t,c=e;if(o===3)g$(e,c,i,s,u);else{if(a)m$(e,c,i,s,a);if(r!==8&&!n){if(r===16)c=Buffer.alloc(i*s*4);p$(e,c,i,s,r)}}return c}});var Rf=Oe((kN,Ff)=>{var b$=tt("util"),qu=tt("zlib"),Pf=xu(),w$=Ef(),$$=Ku(),k$=Ju(),y$=Bu(),Zt=Ff.exports=function(e){Pf.call(this),this._parser=new $$(e,{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=e,this.writable=!0,this._parser.start()};b$.inherits(Zt,Pf);Zt.prototype._handleError=function(e){if(this.emit("error",e),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};Zt.prototype._inflateData=function(e){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=qu.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 n=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,r=Math.max(n,qu.Z_MIN_CHUNK);this._inflate=qu.createInflate({chunkSize:r});let i=n,s=this.emit.bind(this,"error");this._inflate.on("error",function(a){if(!i)return;s(a)}),this._filter.on("complete",this._complete.bind(this));let o=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){if(!i)return;if(a.length>i)a=a.slice(0,i);i-=a.length,o(a)}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(e)};Zt.prototype._handleMetaData=function(e){this._metaData=e,this._bitmapInfo=Object.create(e),this._filter=new w$(this._bitmapInfo)};Zt.prototype._handleTransColor=function(e){this._bitmapInfo.transColor=e};Zt.prototype._handlePalette=function(e){this._bitmapInfo.palette=e};Zt.prototype._simpleTransparency=function(){this._metaData.alpha=!0};Zt.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};Zt.prototype._finished=function(){if(this.errord)return;if(!this._inflate)this.emit("error","No Inflate block");else this._inflate.end()};Zt.prototype._complete=function(e){if(this.errord)return;let t;try{let n=k$.dataToBitMap(e,this._bitmapInfo);t=y$(n,this._bitmapInfo,this._options.skipRescale),n=null}catch(n){this._handleError(n);return}this.emit("parsed",t)}});var Tf=Oe((yN,Of)=>{var Pt=Br();Of.exports=function(e,t,n,r){let i=[Pt.COLORTYPE_COLOR_ALPHA,Pt.COLORTYPE_ALPHA].indexOf(r.colorType)!==-1;if(r.colorType===r.inputColorType){let g=function(){let p=new ArrayBuffer(2);return new DataView(p).setInt16(0,256,!0),new Int16Array(p)[0]!==256}();if(r.bitDepth===8||r.bitDepth===16&&g)return e}let s=r.bitDepth!==16?e:new Uint16Array(e.buffer),o=255,a=Pt.COLORTYPE_TO_BPP_MAP[r.inputColorType];if(a===4&&!r.inputHasAlpha)a=3;let u=Pt.COLORTYPE_TO_BPP_MAP[r.colorType];if(r.bitDepth===16)o=65535,u*=2;let c=Buffer.alloc(t*n*u),l=0,h=0,f=r.bgColor||{};if(f.red===void 0)f.red=o;if(f.green===void 0)f.green=o;if(f.blue===void 0)f.blue=o;function d(){let g,p,b,m=o;switch(r.inputColorType){case Pt.COLORTYPE_COLOR_ALPHA:m=s[l+3],g=s[l],p=s[l+1],b=s[l+2];break;case Pt.COLORTYPE_COLOR:g=s[l],p=s[l+1],b=s[l+2];break;case Pt.COLORTYPE_ALPHA:m=s[l+1],g=s[l],p=g,b=g;break;case Pt.COLORTYPE_GRAYSCALE:g=s[l],p=g,b=g;break;default:throw Error("input color type:"+r.inputColorType+" is not supported at present")}if(r.inputHasAlpha){if(!i)m/=o,g=Math.min(Math.max(Math.round((1-m)*f.red+m*g),0),o),p=Math.min(Math.max(Math.round((1-m)*f.green+m*p),0),o),b=Math.min(Math.max(Math.round((1-m)*f.blue+m*b),0),o)}return{red:g,green:p,blue:b,alpha:m}}for(let g=0;g<n;g++)for(let p=0;p<t;p++){let b=d(s,l);switch(r.colorType){case Pt.COLORTYPE_COLOR_ALPHA:case Pt.COLORTYPE_COLOR:if(r.bitDepth===8){if(c[h]=b.red,c[h+1]=b.green,c[h+2]=b.blue,i)c[h+3]=b.alpha}else if(c.writeUInt16BE(b.red,h),c.writeUInt16BE(b.green,h+2),c.writeUInt16BE(b.blue,h+4),i)c.writeUInt16BE(b.alpha,h+6);break;case Pt.COLORTYPE_ALPHA:case Pt.COLORTYPE_GRAYSCALE:{let m=(b.red+b.green+b.blue)/3;if(r.bitDepth===8){if(c[h]=m,i)c[h+1]=b.alpha}else if(c.writeUInt16BE(m,h),i)c.writeUInt16BE(b.alpha,h+2);break}default:throw Error("unrecognised color Type "+r.colorType)}l+=a,h+=u}return c}});var Lf=Oe((EN,Af)=>{var Hf=_u();function E$(e,t,n,r,i){for(let s=0;s<n;s++)r[i+s]=e[t+s]}function v$(e,t,n){let r=0,i=t+n;for(let s=t;s<i;s++)r+=Math.abs(e[s]);return r}function M$(e,t,n,r,i,s){for(let o=0;o<n;o++){let a=o>=s?e[t+o-s]:0,u=e[t+o]-a;r[i+o]=u}}function S$(e,t,n,r){let i=0;for(let s=0;s<n;s++){let o=s>=r?e[t+s-r]:0,a=e[t+s]-o;i+=Math.abs(a)}return i}function I$(e,t,n,r,i){for(let s=0;s<n;s++){let o=t>0?e[t+s-n]:0,a=e[t+s]-o;r[i+s]=a}}function N$(e,t,n){let r=0,i=t+n;for(let s=t;s<i;s++){let o=t>0?e[s-n]:0,a=e[s]-o;r+=Math.abs(a)}return r}function P$(e,t,n,r,i,s){for(let o=0;o<n;o++){let a=o>=s?e[t+o-s]:0,u=t>0?e[t+o-n]:0,c=e[t+o]-(a+u>>1);r[i+o]=c}}function F$(e,t,n,r){let i=0;for(let s=0;s<n;s++){let o=s>=r?e[t+s-r]:0,a=t>0?e[t+s-n]:0,u=e[t+s]-(o+a>>1);i+=Math.abs(u)}return i}function R$(e,t,n,r,i,s){for(let o=0;o<n;o++){let a=o>=s?e[t+o-s]:0,u=t>0?e[t+o-n]:0,c=t>0&&o>=s?e[t+o-(n+s)]:0,l=e[t+o]-Hf(a,u,c);r[i+o]=l}}function O$(e,t,n,r){let i=0;for(let s=0;s<n;s++){let o=s>=r?e[t+s-r]:0,a=t>0?e[t+s-n]:0,u=t>0&&s>=r?e[t+s-(n+r)]:0,c=e[t+s]-Hf(o,a,u);i+=Math.abs(c)}return i}var T$={0:E$,1:M$,2:I$,3:P$,4:R$},H$={0:v$,1:S$,2:N$,3:F$,4:O$};Af.exports=function(e,t,n,r,i){let s;if(!("filterType"in r)||r.filterType===-1)s=[0,1,2,3,4];else if(typeof r.filterType==="number")s=[r.filterType];else throw Error("unrecognised filter types");if(r.bitDepth===16)i*=2;let o=t*i,a=0,u=0,c=Buffer.alloc((o+1)*n),l=s[0];for(let h=0;h<n;h++){if(s.length>1){let f=1/0;for(let d=0;d<s.length;d++){let g=H$[s[d]](e,u,o,i);if(g<f)l=s[d],f=g}}c[a]=l,a++,T$[l](e,u,o,c,a,i),a+=o,u+=o}return c}});var zu=Oe((vN,xf)=>{var it=Br(),A$=Wu(),L$=Tf(),x$=Lf(),C$=tt("zlib"),An=xf.exports=function(e){if(this._options=e,e.deflateChunkSize=e.deflateChunkSize||32768,e.deflateLevel=e.deflateLevel!=null?e.deflateLevel:9,e.deflateStrategy=e.deflateStrategy!=null?e.deflateStrategy:3,e.inputHasAlpha=e.inputHasAlpha!=null?e.inputHasAlpha:!0,e.deflateFactory=e.deflateFactory||C$.createDeflate,e.bitDepth=e.bitDepth||8,e.colorType=typeof e.colorType==="number"?e.colorType:it.COLORTYPE_COLOR_ALPHA,e.inputColorType=typeof e.inputColorType==="number"?e.inputColorType:it.COLORTYPE_COLOR_ALPHA,[it.COLORTYPE_GRAYSCALE,it.COLORTYPE_COLOR,it.COLORTYPE_COLOR_ALPHA,it.COLORTYPE_ALPHA].indexOf(e.colorType)===-1)throw Error("option color type:"+e.colorType+" is not supported at present");if([it.COLORTYPE_GRAYSCALE,it.COLORTYPE_COLOR,it.COLORTYPE_COLOR_ALPHA,it.COLORTYPE_ALPHA].indexOf(e.inputColorType)===-1)throw Error("option input color type:"+e.inputColorType+" is not supported at present");if(e.bitDepth!==8&&e.bitDepth!==16)throw Error("option bit depth:"+e.bitDepth+" is not supported at present")};An.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};An.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};An.prototype.filterData=function(e,t,n){let r=L$(e,t,n,this._options),i=it.COLORTYPE_TO_BPP_MAP[this._options.colorType];return x$(r,t,n,this._options,i)};An.prototype._packChunk=function(e,t){let n=t?t.length:0,r=Buffer.alloc(n+12);if(r.writeUInt32BE(n,0),r.writeUInt32BE(e,4),t)t.copy(r,8);return r.writeInt32BE(A$.crc32(r.slice(4,r.length-4)),r.length-4),r};An.prototype.packGAMA=function(e){let t=Buffer.alloc(4);return t.writeUInt32BE(Math.floor(e*it.GAMMA_DIVISION),0),this._packChunk(it.TYPE_gAMA,t)};An.prototype.packIHDR=function(e,t){let n=Buffer.alloc(13);return n.writeUInt32BE(e,0),n.writeUInt32BE(t,4),n[8]=this._options.bitDepth,n[9]=this._options.colorType,n[10]=0,n[11]=0,n[12]=0,this._packChunk(it.TYPE_IHDR,n)};An.prototype.packIDAT=function(e){return this._packChunk(it.TYPE_IDAT,e)};An.prototype.packIEND=function(){return this._packChunk(it.TYPE_IEND,null)}});var Uf=Oe((MN,Gf)=>{var _$=tt("util"),Cf=tt("stream"),G$=Br(),U$=zu(),_f=Gf.exports=function(e){Cf.call(this);let t=e||{};this._packer=new U$(t),this._deflate=this._packer.createDeflate(),this.readable=!0};_$.inherits(_f,Cf);_f.prototype.pack=function(e,t,n,r){if(this.emit("data",Buffer.from(G$.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(t,n)),r)this.emit("data",this._packer.packGAMA(r));let i=this._packer.filterData(e,t,n);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 qf=Oe((Yi,Bf)=>{var jf=tt("assert").ok,qr=tt("zlib"),j$=tt("util"),Wf=tt("buffer").kMaxLength;function ur(e){if(!(this instanceof ur))return new ur(e);if(e&&e.chunkSize<qr.Z_MIN_CHUNK)e.chunkSize=qr.Z_MIN_CHUNK;if(qr.Inflate.call(this,e),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,e&&e.maxLength!=null)this._maxLength=e.maxLength}function W$(e){return new ur(e)}function Kf(e,t){if(t)process.nextTick(t);if(!e._handle)return;e._handle.close(),e._handle=null}ur.prototype._processChunk=function(e,t,n){if(typeof n==="function")return qr.Inflate._processChunk.call(this,e,t,n);let r=this,i=e&&e.length,s=this._chunkSize-this._offset,o=this._maxLength,a=0,u=[],c=0,l;this.on("error",function(g){l=g});function h(g,p){if(r._hadError)return;let b=s-p;if(jf(b>=0,"have should not go down"),b>0){let m=r._buffer.slice(r._offset,r._offset+b);if(r._offset+=b,m.length>o)m=m.slice(0,o);if(u.push(m),c+=m.length,o-=m.length,o===0)return!1}if(p===0||r._offset>=r._chunkSize)s=r._chunkSize,r._offset=0,r._buffer=Buffer.allocUnsafe(r._chunkSize);if(p===0)return a+=i-g,i=g,!0;return!1}jf(this._handle,"zlib binding closed");let f;do f=this._handle.writeSync(t,e,a,i,this._buffer,this._offset,s),f=f||this._writeState;while(!this._hadError&&h(f[0],f[1]));if(this._hadError)throw l;if(c>=Wf)throw Kf(this),RangeError("Cannot create final Buffer. It would be larger than 0x"+Wf.toString(16)+" bytes");let d=Buffer.concat(u,c);return Kf(this),d};j$.inherits(ur,qr.Inflate);function K$(e,t){if(typeof t==="string")t=Buffer.from(t);if(!(t instanceof Buffer))throw TypeError("Not a string or buffer");let n=e._finishFlushFlag;if(n==null)n=qr.Z_FINISH;return e._processChunk(t,n)}function Jf(e,t){return K$(new ur(t),e)}Bf.exports=Yi=Jf;Yi.Inflate=ur;Yi.createInflate=W$;Yi.inflateSync=Jf});var Yu=Oe((SN,Yf)=>{var zf=Yf.exports=function(e){this._buffer=e,this._reads=[]};zf.prototype.read=function(e,t){this._reads.push({length:Math.abs(e),allowLess:e<0,func:t})};zf.prototype.process=function(){while(this._reads.length>0&&this._buffer.length){let e=this._reads[0];if(this._buffer.length&&(this._buffer.length>=e.length||e.allowLess)){this._reads.shift();let t=this._buffer;this._buffer=t.slice(e.length),e.func.call(this,t.slice(0,e.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 Qf=Oe((q$)=>{var J$=Yu(),B$=Gu();q$.process=function(e,t){let n=[],r=new J$(e);return new B$(t,{read:r.read.bind(r),write:function(s){n.push(s)},complete:function(){}}).start(),r.process(),Buffer.concat(n)}});var Df=Oe((NN,Xf)=>{var Zf=!0,Vf=tt("zlib"),Y$=qf();if(!Vf.deflateSync)Zf=!1;var Q$=Yu(),Z$=Qf(),V$=Ku(),X$=Ju(),D$=Bu();Xf.exports=function(e,t){if(!Zf)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n;function r(S){n=S}let i;function s(S){i=S}function o(S){i.transColor=S}function a(S){i.palette=S}function u(){i.alpha=!0}let c;function l(S){c=S}let h=[];function f(S){h.push(S)}let d=new Q$(e);if(new V$(t,{read:d.read.bind(d),error:r,metadata:s,gamma:l,palette:a,transColor:o,inflateData:f,simpleTransparency:u}).start(),d.process(),n)throw n;let p=Buffer.concat(h);h.length=0;let b;if(i.interlace)b=Vf.inflateSync(p);else{let w=((i.width*i.bpp*i.depth+7>>3)+1)*i.height;b=Y$(p,{chunkSize:w,maxLength:w})}if(p=null,!b||!b.length)throw Error("bad png - invalid inflate data response");let m=Z$.process(b,i);p=null;let $=X$.dataToBitMap(m,i);m=null;let k=D$($,i,t.skipRescale);return i.data=k,i.gamma=c||0,i}});var rd=Oe((PN,nd)=>{var ed=!0,td=tt("zlib");if(!td.deflateSync)ed=!1;var ek=Br(),tk=zu();nd.exports=function(e,t){if(!ed)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let r=new tk(t||{}),i=[];if(i.push(Buffer.from(ek.PNG_SIGNATURE)),i.push(r.packIHDR(e.width,e.height)),e.gamma)i.push(r.packGAMA(e.gamma));let s=r.filterData(e.data,e.width,e.height),o=td.deflateSync(s,r.getDeflateOptions());if(s=null,!o||!o.length)throw Error("bad png - invalid compressed data response");return i.push(r.packIDAT(o)),i.push(r.packIEND()),Buffer.concat(i)}});var id=Oe((ik)=>{var nk=Df(),rk=rd();ik.read=function(e,t){return nk(e,t||{})};ik.write=function(e,t){return rk(e,t)}});var od=Oe((hk)=>{var ak=tt("util"),sd=tt("stream"),uk=Rf(),ck=Uf(),lk=id(),at=hk.PNG=function(e){if(sd.call(this),e=e||{},this.width=e.width|0,this.height=e.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,e.fill&&this.data)this.data.fill(0);this.gamma=0,this.readable=this.writable=!0,this._parser=new uk(e),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(t){this.data=t,this.emit("parsed",t)}.bind(this)),this._packer=new ck(e),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"))};ak.inherits(at,sd);at.sync=lk;at.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};at.prototype.parse=function(e,t){if(t){let n,r;n=function(i){this.removeListener("error",r),this.data=i,t(null,this)}.bind(this),r=function(i){this.removeListener("parsed",n),t(i,null)}.bind(this),this.once("parsed",n),this.once("error",r)}return this.end(e),this};at.prototype.write=function(e){return this._parser.write(e),!0};at.prototype.end=function(e){this._parser.end(e)};at.prototype._metadata=function(e){this.width=e.width,this.height=e.height,this.emit("metadata",e)};at.prototype._gamma=function(e){this.gamma=e};at.prototype._handleClose=function(){if(!this._parser.writable&&!this._packer.readable)this.emit("close")};at.bitblt=function(e,t,n,r,i,s,o,a){if(n|=0,r|=0,i|=0,s|=0,o|=0,a|=0,n>e.width||r>e.height||n+i>e.width||r+s>e.height)throw Error("bitblt reading outside image");if(o>t.width||a>t.height||o+i>t.width||a+s>t.height)throw Error("bitblt writing outside image");for(let u=0;u<s;u++)e.data.copy(t.data,(a+u)*t.width+o<<2,(r+u)*e.width+n<<2,(r+u)*e.width+n+i<<2)};at.prototype.bitblt=function(e,t,n,r,i,s,o){return at.bitblt(this,e,t,n,r,i,s,o),this};at.adjustGamma=function(e){if(e.gamma){for(let t=0;t<e.height;t++)for(let n=0;n<e.width;n++){let r=e.width*t+n<<2;for(let i=0;i<3;i++){let s=e.data[r+i]/255;s=Math.pow(s,0.45454545454545453/e.gamma),e.data[r+i]=Math.round(s*255)}}e.gamma=0}};at.prototype.adjustGamma=function(){at.adjustGamma(this)}});import{spawnSync as mI}from"node:child_process";import{isMainThread as pI}from"node:worker_threads";import{parseArgs as cI}from"node:util";var nt={name:"@kecan0406/ttheme",version:"1.1.6",type:"module",bin:{ttheme:"bin/ttheme.js"},files:["bin","dist/manifest.json","shell","!shell/check.zsh"],description:"Character terminal palettes for Ghostty, kitty, Alacritty, WezTerm, iTerm2, Windows Terminal and Warp",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","fast-string-width":"^3.0.2","jpeg-js":"^0.4.4",pngjs:"7.0.0","smol-toml":"^1.9.0",typescript:"^5.8.2"},engines:{bun:">=1.3",node:">=20.11"}};import{existsSync as kS,readFileSync as uw}from"node:fs";import{styleText as So}from"node:util";import{stdout as Hh,stdin as t0}from"node:process";import n0 from"node:readline";var ph=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(t)=>{let n=0;e.lastIndex=0;while(e.test(t))n+=1;return t.length-n}})(),bh=(e)=>{return e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510},wh=(e)=>{return e===8987||e===9001||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141};var Uw=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,jw=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,$h=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,Ww=/\t{1,1000}/y,kh=/[\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,Kw=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Jw=/\p{M}+/gu,Bw={limit:1/0,ellipsis:""},yh=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??"",s=t?.ellipsisWidth??(i?yh(i,Bw,n).width:0),o=0,a=n.controlWidth??0,u=n.tabWidth??8,c=n.emojiWidth??2,l=2,h=n.regularWidth??1,f=n.wideWidth??2,d=[[Kw,h],[Uw,0],[jw,a],[Ww,u],[kh,c],[$h,f]],g=0,p=0,b=e.length,m=0,$=!1,k=b,S=Math.max(0,r-s),w=0,M=0,y=0,N=0;e:while(!0){if(M>w||p>=b&&p>g){let R=e.slice(w,M)||e.slice(g,p);m=0;for(let H of R.replaceAll(Jw,"")){let A=H.codePointAt(0)||0;if(bh(A))N=2;else if(wh(A))N=f;else N=h;if(y+N>S)k=Math.min(k,Math.max(w,g)+m);if(y+N>r){$=!0;break e}m+=H.length,y+=N}w=M=0}if(p>=b)break e;for(let R=0,H=d.length;R<H;R++){let[A,C]=d[R];if(A.lastIndex=p,A.test(e)){if(m=A===$h?ph(e.slice(p,A.lastIndex)):A===kh?1:A.lastIndex-p,N=m*C,y+N>S)k=Math.min(k,p+Math.floor((S-y)/C));if(y+N>r){$=!0;break e}y+=N,w=g,M=p,p=g=A.lastIndex;continue e}}p+=1}return{width:$?S:y,index:$?k:b,truncated:$,ellipsed:$&&r>=s}},Eh=yh;var qw={limit:1/0,ellipsis:"",ellipsisWidth:0},zw=(e,t={})=>{return Eh(e,qw,t).width},we=zw;var yo="\x1B",Nh="›",Yw=39,fu="\x07",Ph="[",Qw="]",Fh="m",du=`${Qw}8;;`,vh=new RegExp(`(?:\\${Ph}(?<code>\\d+)m|\\${du}(?<uri>.*)${fu})`,"y"),Mh=(e)=>{if(e>=30&&e<=37)return 39;if(e>=90&&e<=97)return 39;if(e>=40&&e<=47)return 49;if(e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0;return},Sh=(e)=>`${yo}${Ph}${e}${Fh}`,Ih=(e)=>`${yo}${du}${e}${fu}`,hu=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,s=!1,o=e.at(-1),a=o===void 0?0:we(o),u=r.next(),c=r.next(),l=0;while(!u.done){let h=u.value,f=we(h);if(a+f<=n)e[e.length-1]+=h;else e.push(h),a=0;if(h===yo||h===Nh)i=!0,s=t.startsWith(du,l+1);if(i){if(s){if(h===fu)i=!1,s=!1}else if(h===Fh)i=!1}else if(a+=f,a===n&&!c.done)e.push(""),a=0;u=c,c=r.next(),l+=h.length}if(o=e.at(-1),!a&&o!==void 0&&o.length&&e.length>1)e[e.length-2]+=e.pop()},Zw=(e)=>{let t=e.split(" "),n=t.length;while(n){if(we(t[n-1]))break;n--}if(n===t.length)return e;return t.slice(0,n).join(" ")+t.slice(n).join("")},Vw=(e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let r="",i,s,o=e.split(" "),a=[""],u=0;for(let h=0;h<o.length;h++){let f=o[h];if(n.trim!==!1){let g=a.at(-1)??"",p=g.trimStart();if(g.length!==p.length)a[a.length-1]=p,u=we(p)}if(h!==0){if(u>=t&&(n.wordWrap===!1||n.trim===!1))a.push(""),u=0;if(u||n.trim===!1)a[a.length-1]+=" ",u++}let d=we(f);if(n.hard&&d>t){let g=t-u,p=1+Math.floor((d-g-1)/t);if(Math.floor((d-1)/t)<p)a.push("");hu(a,f,t),u=we(a.at(-1)??"");continue}if(u+d>t&&u&&d){if(n.wordWrap===!1&&u<t){hu(a,f,t),u=we(a.at(-1)??"");continue}a.push(""),u=0}if(u+d>t&&n.wordWrap===!1){hu(a,f,t),u=we(a.at(-1)??"");continue}a[a.length-1]+=f,u+=d}if(n.trim!==!1)a=a.map((h)=>Zw(h));let c=a.join(`
3
+ `),l=!1;for(let h=0;h<c.length;h++){let f=c[h];if(r+=f,!l){if(l=f>="\uD800"&&f<="\uDBFF",l)continue}else l=!1;if(f===yo||f===Nh){vh.lastIndex=h+1;let g=vh.exec(c)?.groups;if(g?.code!==void 0){let p=Number.parseFloat(g.code);i=p===Yw?void 0:p}else if(g?.uri!==void 0)s=g.uri.length===0?void 0:g.uri}if(c[h+1]===`
4
+ `){if(s)r+=Ih("");let d=i?Mh(i):void 0;if(i&&d)r+=Sh(d)}else if(f===`
5
+ `){if(i&&Mh(i))r+=Sh(i);if(s)r+=Ih(s)}}return r},Xw=/\r?\n/;function Mn(e,t,n){return String(e).normalize().split(Xw).map((r)=>Vw(r,t,n)).join(`
6
+ `)}var dt=ko(mu(),1);function Cr(e,t,n){if(!n.some((o)=>!o.disabled))return e;let r=e+t,i=Math.max(n.length-1,0),s=r<0?i:r>i?0:r;return n[s]?.disabled?Cr(s,t<0?-1:1,n):s}function Eo(e,t,n,r){let i=r.split(`
7
+ `),s=0,o=e;for(let u of i){if(o<=u.length)break;o-=u.length+1,s++}for(s=Math.max(0,Math.min(i.length-1,s+n)),o=Math.min(o,i[s].length)+t;o<0&&s>0;)s--,o+=i[s].length+1;for(;o>i[s].length&&s<i.length-1;)o-=i[s].length+1,s++;o=Math.max(0,Math.min(i[s].length,o));let a=0;for(let u=0;u<s;u++)a+=i[u].length+1;return a+o}var r0=["up","down","left","right","space","enter","cancel"],i0=["January","February","March","April","May","June","July","August","September","October","November","December"],rt={actions:new Set(r0),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:[...i0],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(e,t)=>`There are only ${e} days in ${t}`,afterMin:(e)=>`Date must be on or after ${e.toISOString().slice(0,10)}`,beforeMax:(e)=>`Date must be on or before ${e.toISOString().slice(0,10)}`}}};function Ah(e,t){if(typeof e=="string")return rt.aliases.get(e)===t;for(let n of e)if(n!==void 0&&Ah(n,t))return!0;return!1}function s0(e,t){if(e===t)return;let n=e.split(`
8
8
  `),r=t.split(`
9
- `),i=Math.max(n.length,r.length),s=[];for(let o=0;o<i;o++)n[o]!==r[o]&&s.push(o);return{lines:s,numLinesBefore:n.length,numLinesAfter:r.length,numLines:i}}var vM=globalThis.process.platform.startsWith("win"),Ra=Symbol("clack:cancel");function xe(e){return e===Ra}function Ls(e,t){let n=e;n.isTTY&&n.setRawMode(t)}var _s=(e)=>("columns"in e)&&typeof e.columns=="number"?e.columns:80,Pa=(e)=>("rows"in e)&&typeof e.rows=="number"?e.rows:20;function pi(e,t,n,r=n,i=n,s){let o=_s(e??jl);return dn(t,o-n.length,{hard:!0,trim:!1}).split(`
9
+ `),i=Math.max(n.length,r.length),s=[];for(let o=0;o<i;o++)n[o]!==r[o]&&s.push(o);return{lines:s,numLinesBefore:n.length,numLinesAfter:r.length,numLines:i}}var TI=globalThis.process.platform.startsWith("win"),bu=Symbol("clack:cancel");function ft(e){return e===bu}function vo(e,t){let n=e;n.isTTY&&n.setRawMode(t)}var Io=(e)=>("columns"in e)&&typeof e.columns=="number"?e.columns:80,$u=(e)=>("rows"in e)&&typeof e.rows=="number"?e.rows:20;function ji(e,t,n,r=n,i=n,s){let o=Io(e??Hh);return Mn(t,o-n.length,{hard:!0,trim:!1}).split(`
10
10
  `).map((a,u,c)=>{let l=s?s(a,u):a;return u===0?`${r}${l}`:u===c.length-1?`${i}${l}`:`${n}${l}`}).join(`
11
- `)}function Jl(e,t){if("~standard"in e){let n=e["~standard"].validate(t);if(n instanceof Promise)throw TypeError("Schema validation must be synchronous. Update `validate()` and remove any asynchronous logic.");return n.issues?.at(0)?.message}return e(t)}class wt{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(e,t=!0){let{input:n=Ow,output:r=jl,render:i,signal:s,...o}=e;this.opts=o,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=i.bind(this),this._track=t,this._abortSignal=s,this.input=n,this.output=r}unsubscribe(){this._subscribers.clear()}setSubscriber(e,t){let n=this._subscribers.get(e)??[];n.push(t),this._subscribers.set(e,n)}on(e,t){this.setSubscriber(e,{cb:t})}once(e,t){this.setSubscriber(e,{cb:t,once:!0})}emit(e,...t){let n=this._subscribers.get(e)??[],r=[];for(let i of n)i.cb(...t),i.once&&r.push(()=>n.splice(n.indexOf(i),1));for(let i of r)i()}prompt(){return new Promise((e)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),e(Ra);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=Tw.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),Ls(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(ut.cursor.show),this.output.off("resize",this.render),Ls(this.input,!1),e(this.value)}),this.once("cancel",()=>{this.output.write(ut.cursor.show),this.output.off("resize",this.render),Ls(this.input,!1),e(Ra)})})}_isActionKey(e,t){return e==="\t"}_shouldSubmit(e,t){return!0}_setValue(e){this.value=e,this.emit("value",this.value)}_setUserInput(e,t){this.userInput=e??"",this.emit("userInput",this.userInput),t&&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(e,t){if(this._track&&t.name!=="return"&&(t.name&&this._isActionKey(e,t)&&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"),t?.name&&(!this._track&&Xe.aliases.has(t.name)&&this.emit("cursor",Xe.aliases.get(t.name)),Xe.actions.has(t.name)&&this.emit("cursor",t.name)),e&&(e.toLowerCase()==="y"||e.toLowerCase()==="n")&&this.emit("confirm",e.toLowerCase()==="y"),this.emit("key",e,t),t?.name==="return"&&this._shouldSubmit(e,t)){if(this.opts.validate){let n=Jl(this.opts.validate,this.value);n&&(this.error=n instanceof Error?n.message:n,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}Wl([e,t?.name,t?.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(`
12
- `),Ls(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=dn(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
13
- `).length-1;this.output.write(ut.cursor.move(-999,e*-1))}render(){let e=dn(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state==="initial")this.output.write(ut.cursor.hide);else{let t=Lw(this._prevFrame,e),n=Pa(this.output);if(this.restoreCursor(),t){let r=Math.max(0,t.numLinesAfter-n),i=Math.max(0,t.numLinesBefore-n),s=t.lines.find((o)=>o>=r);if(s===void 0){this._prevFrame=e;return}if(t.lines.length===1){this.output.write(ut.cursor.move(0,s-i)),this.output.write(ut.erase.lines(1));let o=e.split(`
14
- `);this.output.write(o[s]),this._prevFrame=e,this.output.write(ut.cursor.move(0,o.length-s-1));return}else if(t.lines.length>1){if(r<i)s=r;else{let a=s-i;a>0&&this.output.write(ut.cursor.move(0,a))}this.output.write(ut.erase.down());let o=e.split(`
11
+ `)}function Lh(e,t){if("~standard"in e){let n=e["~standard"].validate(t);if(n instanceof Promise)throw TypeError("Schema validation must be synchronous. Update `validate()` and remove any asynchronous logic.");return n.issues?.at(0)?.message}return e(t)}class It{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(e,t=!0){let{input:n=t0,output:r=Hh,render:i,signal:s,...o}=e;this.opts=o,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=i.bind(this),this._track=t,this._abortSignal=s,this.input=n,this.output=r}unsubscribe(){this._subscribers.clear()}setSubscriber(e,t){let n=this._subscribers.get(e)??[];n.push(t),this._subscribers.set(e,n)}on(e,t){this.setSubscriber(e,{cb:t})}once(e,t){this.setSubscriber(e,{cb:t,once:!0})}emit(e,...t){let n=this._subscribers.get(e)??[],r=[];for(let i of n)i.cb(...t),i.once&&r.push(()=>n.splice(n.indexOf(i),1));for(let i of r)i()}prompt(){return new Promise((e)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),e(bu);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=n0.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),vo(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(dt.cursor.show),this.output.off("resize",this.render),vo(this.input,!1),e(this.value)}),this.once("cancel",()=>{this.output.write(dt.cursor.show),this.output.off("resize",this.render),vo(this.input,!1),e(bu)})})}_isActionKey(e,t){return e==="\t"}_shouldSubmit(e,t){return!0}_setValue(e){this.value=e,this.emit("value",this.value)}_setUserInput(e,t){this.userInput=e??"",this.emit("userInput",this.userInput),t&&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(e,t){if(this._track&&t.name!=="return"&&(t.name&&this._isActionKey(e,t)&&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"),t?.name&&(!this._track&&rt.aliases.has(t.name)&&this.emit("cursor",rt.aliases.get(t.name)),rt.actions.has(t.name)&&this.emit("cursor",t.name)),e&&(e.toLowerCase()==="y"||e.toLowerCase()==="n")&&this.emit("confirm",e.toLowerCase()==="y"),this.emit("key",e,t),t?.name==="return"&&this._shouldSubmit(e,t)){if(this.opts.validate){let n=Lh(this.opts.validate,this.value);n&&(this.error=n instanceof Error?n.message:n,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}Ah([e,t?.name,t?.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(`
12
+ `),vo(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=Mn(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
13
+ `).length-1;this.output.write(dt.cursor.move(-999,e*-1))}render(){let e=Mn(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state==="initial")this.output.write(dt.cursor.hide);else{let t=s0(this._prevFrame,e),n=$u(this.output);if(this.restoreCursor(),t){let r=Math.max(0,t.numLinesAfter-n),i=Math.max(0,t.numLinesBefore-n),s=t.lines.find((o)=>o>=r);if(s===void 0){this._prevFrame=e;return}if(t.lines.length===1){this.output.write(dt.cursor.move(0,s-i)),this.output.write(dt.erase.lines(1));let o=e.split(`
14
+ `);this.output.write(o[s]),this._prevFrame=e,this.output.write(dt.cursor.move(0,o.length-s-1));return}else if(t.lines.length>1){if(r<i)s=r;else{let a=s-i;a>0&&this.output.write(dt.cursor.move(0,a))}this.output.write(dt.erase.down());let o=e.split(`
15
15
  `).slice(s);this.output.write(o.join(`
16
- `)),this._prevFrame=e;return}}this.output.write(ut.erase.down())}this.output.write(e),this.state==="initial"&&(this.state="active"),this._prevFrame=e}}}function Gw(e,t){if(e===void 0||t.length===0)return 0;let n=t.findIndex((r)=>r.value===e);return n!==-1?n:0}function Uw(e,t){return(t.label??String(t.value)).toLowerCase().includes(e.toLowerCase())}function _w(e,t){if(t)return e?t:t[0]}var Cw=class extends wt{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#t=0;#n="";#e;#s;#a;get cursor(){return this.#t}get userInputWithCursor(){if(!this.userInput)return Us(["inverse","hidden"],"_");if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let t=this.userInput.slice(0,this.cursor),n=this.userInput.slice(this.cursor,this.cursor+1),r=this.userInput.slice(this.cursor+1);return`${t}${Us("inverse",n)}${r}`}get options(){return typeof this.#s=="function"?this.#s():this.#s}constructor(t){super(t),this.#s=t.options,this.#a=t.placeholder;let n=this.options;this.filteredOptions=[...n],this.multiple=t.multiple===!0,this.#e=typeof t.options=="function"?t.filter:t.filter??Uw;let r;if(t.initialValue&&Array.isArray(t.initialValue)?this.multiple?r=t.initialValue:r=t.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(r=[this.options[0]?.value]),r)for(let i of r){let s=n.findIndex((o)=>o.value===i);s!==-1&&(this.toggleSelected(i),this.#t=s)}this.focusedValue=this.options[this.#t]?.value,this.on("key",(i,s)=>this.#r(i,s)),this.on("userInput",(i)=>this.#i(i))}_isActionKey(t,n){return t==="\t"||this.multiple&&this.isNavigating&&n.name==="space"&&t!==void 0&&t!==""}#r(t,n){let r=n.name==="up",i=n.name==="down",s=n.name==="return",o=this.userInput===""||this.userInput==="\t",a=this.#a,u=this.options,c=a!==void 0&&a!==""&&u.some((l)=>!l.disabled&&(this.#e?this.#e(a,l):!0));if(n.name==="tab"&&o&&c){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(a,!0),this.isNavigating=!1;return}r||i?(this.#t=br(this.#t,r?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#t]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):s?this.value=_w(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(n.name==="tab"||this.isNavigating&&n.name==="space")?this.toggleSelected(this.focusedValue):this.isNavigating=!1:(this.focusedValue&&(this.selectedValues=[this.focusedValue]),this.isNavigating=!1)}deselectAll(){this.selectedValues=[]}toggleSelected(t){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(t)?this.selectedValues=this.selectedValues.filter((n)=>n!==t):this.selectedValues=[...this.selectedValues,t]:this.selectedValues=[t])}#i(t){if(t!==this.#n){this.#n=t;let n=this.options;t&&this.#e?this.filteredOptions=n.filter((s)=>this.#e?.(t,s)):this.filteredOptions=[...n];let r=Gw(this.focusedValue,this.filteredOptions);this.#t=br(r,0,this.filteredOptions);let i=this.filteredOptions[this.#t];i&&!i.disabled?this.focusedValue=i.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}};class Oa extends wt{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(e){super(e,!1),this.value=!!e.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(t)=>{this.output.write(ut.cursor.move(0,-1)),this.value=t,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var jw={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function _l(e){return[...e].map((t)=>jw[t])}function Ww(e){let t=new Intl.DateTimeFormat(e,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2000,0,15)),n=[],r="/";for(let i of t)i.type==="literal"?r=i.value.trim()||i.value:(i.type==="year"||i.type==="month"||i.type==="day")&&n.push({type:i.type,len:i.type==="year"?4:2});return{segments:n,separator:r}}function Na(e){return Number.parseInt((e||"0").replace(/_/g,"0"),10)||0}function Gs(e){return{year:Na(e.year),month:Na(e.month),day:Na(e.day)}}function Fa(e,t){return new Date(e||2001,t||1,0).getDate()}function Kl(e){let{year:t,month:n,day:r}=Gs(e);if(!t||t<0||t>9999||!n||n<1||n>12||!r||r<1)return;let i=new Date(Date.UTC(t,n-1,r));if(!(i.getUTCFullYear()!==t||i.getUTCMonth()!==n-1||i.getUTCDate()!==r))return{year:t,month:n,day:r}}function Cl(e){let t=Kl(e);return t?new Date(Date.UTC(t.year,t.month-1,t.day)):void 0}function Jw(e,t,n,r){let i=n?{year:n.getUTCFullYear(),month:n.getUTCMonth()+1,day:n.getUTCDate()}:null,s=r?{year:r.getUTCFullYear(),month:r.getUTCMonth()+1,day:r.getUTCDate()}:null;return e==="year"?{min:i?.year??1,max:s?.year??9999}:e==="month"?{min:i&&t.year===i.year?i.month:1,max:s&&t.year===s.year?s.month:12}:{min:i&&t.year===i.year&&t.month===i.month?i.day:1,max:s&&t.year===s.year&&t.month===s.month?s.day:Fa(t.year,t.month)}}class ql extends wt{#t;#n;#e;#s;#a;#r={segmentIndex:0,positionInSegment:0};#i=!0;#o=null;inlineError="";get segmentCursor(){return{...this.#r}}get segmentValues(){return{...this.#e}}get segments(){return this.#t}get separator(){return this.#n}get formattedValue(){return this.#h(this.#e)}#h(e){return this.#t.map((t)=>e[t.type]).join(this.#n)}#u(){this._setUserInput(this.#h(this.#e)),this._setValue(Cl(this.#e)??void 0)}constructor(e){let t=e.format?{segments:_l(e.format),separator:e.separator??"/"}:Ww(e.locale),n=e.separator??t.separator,r=e.format?_l(e.format):t.segments,i=e.initialValue??e.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=r.map((a)=>s[a.type]).join(n);super({...e,initialUserInput:o},!1),this.#t=r,this.#n=n,this.#e=s,this.#s=e.minDate,this.#a=e.maxDate,this.#u(),this.on("cursor",(a)=>this.#g(a)),this.on("key",(a,u)=>this.#m(a,u)),this.on("finalize",()=>this.#p(e))}#c(){let e=Math.max(0,Math.min(this.#r.segmentIndex,this.#t.length-1)),t=this.#t[e];if(t)return this.#r.positionInSegment=Math.max(0,Math.min(this.#r.positionInSegment,t.len-1)),{segment:t,index:e}}#l(e){this.inlineError="",this.#o=null;let t=this.#c();t&&(this.#r.segmentIndex=Math.max(0,Math.min(this.#t.length-1,t.index+e)),this.#r.positionInSegment=0,this.#i=!0)}#f(e){let t=this.#c();if(!t)return;let{segment:n}=t,r=this.#e[n.type],i=!r||r.replace(/_/g,"")==="",s=Number.parseInt((r||"0").replace(/_/g,"0"),10)||0,o=Jw(n.type,Gs(this.#e),this.#s,this.#a),a;i?a=e===1?o.min:o.max:a=Math.max(Math.min(o.max,s+e),o.min),this.#e={...this.#e,[n.type]:a.toString().padStart(n.len,"0")},this.#i=!0,this.#o=null,this.#u()}#g(e){if(e)switch(e){case"right":return this.#l(1);case"left":return this.#l(-1);case"up":return this.#f(1);case"down":return this.#f(-1)}}#m(e,t){if(t?.name==="backspace"||t?.sequence===""||t?.sequence==="\b"||e===""||e==="\b"){this.inlineError="";let n=this.#c();if(!n)return;if(!this.#e[n.segment.type].replace(/_/g,"")){this.#l(-1);return}this.#e[n.segment.type]="_".repeat(n.segment.len),this.#i=!0,this.#r.positionInSegment=0,this.#u();return}if(t?.name==="tab"){this.inlineError="";let n=this.#c();if(!n)return;let r=t.shift?-1:1,i=n.index+r;i>=0&&i<this.#t.length&&(this.#r.segmentIndex=i,this.#r.positionInSegment=0,this.#i=!0);return}if(e&&/^[0-9]$/.test(e)){let n=this.#c();if(!n)return;let{segment:r}=n,i=!this.#e[r.type].replace(/_/g,"");if(this.#i&&this.#o!==null&&!i){let f=this.#o+e,d={...this.#e,[r.type]:f},g=this.#d(d,r);if(g){this.inlineError=g,this.#o=null,this.#i=!1;return}this.inlineError="",this.#e[r.type]=f,this.#o=null,this.#i=!1,this.#u(),n.index<this.#t.length-1&&(this.#r.segmentIndex=n.index+1,this.#r.positionInSegment=0,this.#i=!0);return}this.#i&&!i&&(this.#e[r.type]="_".repeat(r.len),this.#r.positionInSegment=0),this.#i=!1,this.#o=null;let s=this.#e[r.type],o=s.indexOf("_"),a=o>=0?o:Math.min(this.#r.positionInSegment,r.len-1);if(a<0||a>=r.len)return;let u=s.slice(0,a)+e+s.slice(a+1),c=!1;if(a===0&&s==="__"&&(r.type==="month"||r.type==="day")){let f=Number.parseInt(e,10);u=`0${e}`,c=f<=(r.type==="month"?1:2)}if(r.type==="year"&&(u=(s.replace(/_/g,"")+e).padStart(r.len,"_")),!u.includes("_")){let f={...this.#e,[r.type]:u},d=this.#d(f,r);if(d){this.inlineError=d;return}}this.inlineError="",this.#e[r.type]=u;let l=u.includes("_")?void 0:Kl(this.#e);if(l){let{year:f,month:d}=l,g=Fa(f,d);this.#e={year:String(Math.max(0,Math.min(9999,f))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,d))).padStart(2,"0"),day:String(Math.max(1,Math.min(g,l.day))).padStart(2,"0")}}this.#u();let h=u.indexOf("_");c?(this.#i=!0,this.#o=e):h>=0?this.#r.positionInSegment=h:o>=0&&n.index<this.#t.length-1?(this.#r.segmentIndex=n.index+1,this.#r.positionInSegment=0,this.#i=!0):this.#r.positionInSegment=Math.min(a+1,r.len-1)}}#d(e,t){let{month:n,day:r}=Gs(e);if(t.type==="month"&&(n<0||n>12))return Xe.date.messages.invalidMonth;if(t.type==="day"&&(r<0||r>31))return Xe.date.messages.invalidDay(31,"any month")}#p(e){let{year:t,month:n,day:r}=Gs(this.#e);if(t&&n&&r){let i=Fa(t,n);this.#e={...this.#e,day:String(Math.min(r,i)).padStart(2,"0")}}this.value=Cl(this.#e)??e.defaultValue??void 0}}var Kw=class extends wt{options;cursor=0;#t;getGroupItems(t){return this.options.filter((n)=>n.group===t)}isGroupSelected(t){let n=this.getGroupItems(t),r=this.value;return r===void 0?!1:n.every((i)=>r.includes(i.value))}toggleValue(){let t=this.options[this.cursor];if(t!==void 0)if(this.value===void 0&&(this.value=[]),t.group===!0){let n=t.value,r=this.getGroupItems(n);this.isGroupSelected(n)?this.value=this.value.filter((i)=>r.findIndex((s)=>s.value===i)===-1):this.value=[...this.value,...r.map((i)=>i.value)],this.value=Array.from(new Set(this.value))}else{let n=this.value.includes(t.value);this.value=n?this.value.filter((r)=>r!==t.value):[...this.value,t.value]}}constructor(t){super(t,!1);let{options:n}=t;this.#t=t.selectableGroups!==!1,this.options=Object.entries(n).flatMap(([r,i])=>[{value:r,group:!0,label:r},...i.map((s)=>({...s,group:r}))]),this.value=[...t.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:r})=>r===t.cursorAt),this.#t?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.#t&&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.#t&&i&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},qw=new Set(["up","down","left","right"]);class Ql extends wt{#t=!1;#n;focused="editor";get userInputWithCursor(){if(this.state==="submit")return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${e}█`;let t=e.slice(0,this.cursor),n=e.slice(this.cursor,this.cursor+1),r=e.slice(this.cursor+1);return n===`
16
+ `)),this._prevFrame=e;return}}this.output.write(dt.erase.down())}this.output.write(e),this.state==="initial"&&(this.state="active"),this._prevFrame=e}}}function o0(e,t){if(e===void 0||t.length===0)return 0;let n=t.findIndex((r)=>r.value===e);return n!==-1?n:0}function a0(e,t){return(t.label??String(t.value)).toLowerCase().includes(e.toLowerCase())}function u0(e,t){if(t)return e?t:t[0]}var c0=class extends It{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#t=0;#n="";#e;#s;#a;get cursor(){return this.#t}get userInputWithCursor(){if(!this.userInput)return So(["inverse","hidden"],"_");if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let t=this.userInput.slice(0,this.cursor),n=this.userInput.slice(this.cursor,this.cursor+1),r=this.userInput.slice(this.cursor+1);return`${t}${So("inverse",n)}${r}`}get options(){return typeof this.#s=="function"?this.#s():this.#s}constructor(t){super(t),this.#s=t.options,this.#a=t.placeholder;let n=this.options;this.filteredOptions=[...n],this.multiple=t.multiple===!0,this.#e=typeof t.options=="function"?t.filter:t.filter??a0;let r;if(t.initialValue&&Array.isArray(t.initialValue)?this.multiple?r=t.initialValue:r=t.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(r=[this.options[0]?.value]),r)for(let i of r){let s=n.findIndex((o)=>o.value===i);s!==-1&&(this.toggleSelected(i),this.#t=s)}this.focusedValue=this.options[this.#t]?.value,this.on("key",(i,s)=>this.#r(i,s)),this.on("userInput",(i)=>this.#i(i))}_isActionKey(t,n){return t==="\t"||this.multiple&&this.isNavigating&&n.name==="space"&&t!==void 0&&t!==""}#r(t,n){let r=n.name==="up",i=n.name==="down",s=n.name==="return",o=this.userInput===""||this.userInput==="\t",a=this.#a,u=this.options,c=a!==void 0&&a!==""&&u.some((l)=>!l.disabled&&(this.#e?this.#e(a,l):!0));if(n.name==="tab"&&o&&c){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(a,!0),this.isNavigating=!1;return}r||i?(this.#t=Cr(this.#t,r?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#t]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):s?this.value=u0(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(n.name==="tab"||this.isNavigating&&n.name==="space")?this.toggleSelected(this.focusedValue):this.isNavigating=!1:(this.focusedValue&&(this.selectedValues=[this.focusedValue]),this.isNavigating=!1)}deselectAll(){this.selectedValues=[]}toggleSelected(t){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(t)?this.selectedValues=this.selectedValues.filter((n)=>n!==t):this.selectedValues=[...this.selectedValues,t]:this.selectedValues=[t])}#i(t){if(t!==this.#n){this.#n=t;let n=this.options;t&&this.#e?this.filteredOptions=n.filter((s)=>this.#e?.(t,s)):this.filteredOptions=[...n];let r=o0(this.focusedValue,this.filteredOptions);this.#t=Cr(r,0,this.filteredOptions);let i=this.filteredOptions[this.#t];i&&!i.disabled?this.focusedValue=i.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}};class ku extends It{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(e){super(e,!1),this.value=!!e.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(t)=>{this.output.write(dt.cursor.move(0,-1)),this.value=t,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var l0={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function Oh(e){return[...e].map((t)=>l0[t])}function h0(e){let t=new Intl.DateTimeFormat(e,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2000,0,15)),n=[],r="/";for(let i of t)i.type==="literal"?r=i.value.trim()||i.value:(i.type==="year"||i.type==="month"||i.type==="day")&&n.push({type:i.type,len:i.type==="year"?4:2});return{segments:n,separator:r}}function pu(e){return Number.parseInt((e||"0").replace(/_/g,"0"),10)||0}function Mo(e){return{year:pu(e.year),month:pu(e.month),day:pu(e.day)}}function wu(e,t){return new Date(e||2001,t||1,0).getDate()}function xh(e){let{year:t,month:n,day:r}=Mo(e);if(!t||t<0||t>9999||!n||n<1||n>12||!r||r<1)return;let i=new Date(Date.UTC(t,n-1,r));if(!(i.getUTCFullYear()!==t||i.getUTCMonth()!==n-1||i.getUTCDate()!==r))return{year:t,month:n,day:r}}function Th(e){let t=xh(e);return t?new Date(Date.UTC(t.year,t.month-1,t.day)):void 0}function f0(e,t,n,r){let i=n?{year:n.getUTCFullYear(),month:n.getUTCMonth()+1,day:n.getUTCDate()}:null,s=r?{year:r.getUTCFullYear(),month:r.getUTCMonth()+1,day:r.getUTCDate()}:null;return e==="year"?{min:i?.year??1,max:s?.year??9999}:e==="month"?{min:i&&t.year===i.year?i.month:1,max:s&&t.year===s.year?s.month:12}:{min:i&&t.year===i.year&&t.month===i.month?i.day:1,max:s&&t.year===s.year&&t.month===s.month?s.day:wu(t.year,t.month)}}class Ch extends It{#t;#n;#e;#s;#a;#r={segmentIndex:0,positionInSegment:0};#i=!0;#o=null;inlineError="";get segmentCursor(){return{...this.#r}}get segmentValues(){return{...this.#e}}get segments(){return this.#t}get separator(){return this.#n}get formattedValue(){return this.#h(this.#e)}#h(e){return this.#t.map((t)=>e[t.type]).join(this.#n)}#u(){this._setUserInput(this.#h(this.#e)),this._setValue(Th(this.#e)??void 0)}constructor(e){let t=e.format?{segments:Oh(e.format),separator:e.separator??"/"}:h0(e.locale),n=e.separator??t.separator,r=e.format?Oh(e.format):t.segments,i=e.initialValue??e.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=r.map((a)=>s[a.type]).join(n);super({...e,initialUserInput:o},!1),this.#t=r,this.#n=n,this.#e=s,this.#s=e.minDate,this.#a=e.maxDate,this.#u(),this.on("cursor",(a)=>this.#g(a)),this.on("key",(a,u)=>this.#m(a,u)),this.on("finalize",()=>this.#p(e))}#c(){let e=Math.max(0,Math.min(this.#r.segmentIndex,this.#t.length-1)),t=this.#t[e];if(t)return this.#r.positionInSegment=Math.max(0,Math.min(this.#r.positionInSegment,t.len-1)),{segment:t,index:e}}#l(e){this.inlineError="",this.#o=null;let t=this.#c();t&&(this.#r.segmentIndex=Math.max(0,Math.min(this.#t.length-1,t.index+e)),this.#r.positionInSegment=0,this.#i=!0)}#f(e){let t=this.#c();if(!t)return;let{segment:n}=t,r=this.#e[n.type],i=!r||r.replace(/_/g,"")==="",s=Number.parseInt((r||"0").replace(/_/g,"0"),10)||0,o=f0(n.type,Mo(this.#e),this.#s,this.#a),a;i?a=e===1?o.min:o.max:a=Math.max(Math.min(o.max,s+e),o.min),this.#e={...this.#e,[n.type]:a.toString().padStart(n.len,"0")},this.#i=!0,this.#o=null,this.#u()}#g(e){if(e)switch(e){case"right":return this.#l(1);case"left":return this.#l(-1);case"up":return this.#f(1);case"down":return this.#f(-1)}}#m(e,t){if(t?.name==="backspace"||t?.sequence===""||t?.sequence==="\b"||e===""||e==="\b"){this.inlineError="";let n=this.#c();if(!n)return;if(!this.#e[n.segment.type].replace(/_/g,"")){this.#l(-1);return}this.#e[n.segment.type]="_".repeat(n.segment.len),this.#i=!0,this.#r.positionInSegment=0,this.#u();return}if(t?.name==="tab"){this.inlineError="";let n=this.#c();if(!n)return;let r=t.shift?-1:1,i=n.index+r;i>=0&&i<this.#t.length&&(this.#r.segmentIndex=i,this.#r.positionInSegment=0,this.#i=!0);return}if(e&&/^[0-9]$/.test(e)){let n=this.#c();if(!n)return;let{segment:r}=n,i=!this.#e[r.type].replace(/_/g,"");if(this.#i&&this.#o!==null&&!i){let f=this.#o+e,d={...this.#e,[r.type]:f},g=this.#d(d,r);if(g){this.inlineError=g,this.#o=null,this.#i=!1;return}this.inlineError="",this.#e[r.type]=f,this.#o=null,this.#i=!1,this.#u(),n.index<this.#t.length-1&&(this.#r.segmentIndex=n.index+1,this.#r.positionInSegment=0,this.#i=!0);return}this.#i&&!i&&(this.#e[r.type]="_".repeat(r.len),this.#r.positionInSegment=0),this.#i=!1,this.#o=null;let s=this.#e[r.type],o=s.indexOf("_"),a=o>=0?o:Math.min(this.#r.positionInSegment,r.len-1);if(a<0||a>=r.len)return;let u=s.slice(0,a)+e+s.slice(a+1),c=!1;if(a===0&&s==="__"&&(r.type==="month"||r.type==="day")){let f=Number.parseInt(e,10);u=`0${e}`,c=f<=(r.type==="month"?1:2)}if(r.type==="year"&&(u=(s.replace(/_/g,"")+e).padStart(r.len,"_")),!u.includes("_")){let f={...this.#e,[r.type]:u},d=this.#d(f,r);if(d){this.inlineError=d;return}}this.inlineError="",this.#e[r.type]=u;let l=u.includes("_")?void 0:xh(this.#e);if(l){let{year:f,month:d}=l,g=wu(f,d);this.#e={year:String(Math.max(0,Math.min(9999,f))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,d))).padStart(2,"0"),day:String(Math.max(1,Math.min(g,l.day))).padStart(2,"0")}}this.#u();let h=u.indexOf("_");c?(this.#i=!0,this.#o=e):h>=0?this.#r.positionInSegment=h:o>=0&&n.index<this.#t.length-1?(this.#r.segmentIndex=n.index+1,this.#r.positionInSegment=0,this.#i=!0):this.#r.positionInSegment=Math.min(a+1,r.len-1)}}#d(e,t){let{month:n,day:r}=Mo(e);if(t.type==="month"&&(n<0||n>12))return rt.date.messages.invalidMonth;if(t.type==="day"&&(r<0||r>31))return rt.date.messages.invalidDay(31,"any month")}#p(e){let{year:t,month:n,day:r}=Mo(this.#e);if(t&&n&&r){let i=wu(t,n);this.#e={...this.#e,day:String(Math.min(r,i)).padStart(2,"0")}}this.value=Th(this.#e)??e.defaultValue??void 0}}var d0=class extends It{options;cursor=0;#t;getGroupItems(t){return this.options.filter((n)=>n.group===t)}isGroupSelected(t){let n=this.getGroupItems(t),r=this.value;return r===void 0?!1:n.every((i)=>r.includes(i.value))}toggleValue(){let t=this.options[this.cursor];if(t!==void 0)if(this.value===void 0&&(this.value=[]),t.group===!0){let n=t.value,r=this.getGroupItems(n);this.isGroupSelected(n)?this.value=this.value.filter((i)=>r.findIndex((s)=>s.value===i)===-1):this.value=[...this.value,...r.map((i)=>i.value)],this.value=Array.from(new Set(this.value))}else{let n=this.value.includes(t.value);this.value=n?this.value.filter((r)=>r!==t.value):[...this.value,t.value]}}constructor(t){super(t,!1);let{options:n}=t;this.#t=t.selectableGroups!==!1,this.options=Object.entries(n).flatMap(([r,i])=>[{value:r,group:!0,label:r},...i.map((s)=>({...s,group:r}))]),this.value=[...t.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:r})=>r===t.cursorAt),this.#t?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.#t&&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.#t&&i&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},g0=new Set(["up","down","left","right"]);class _h extends It{#t=!1;#n;focused="editor";get userInputWithCursor(){if(this.state==="submit")return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${e}█`;let t=e.slice(0,this.cursor),n=e.slice(this.cursor,this.cursor+1),r=e.slice(this.cursor+1);return n===`
17
17
  `?`${t}█
18
- ${r}`:`${t}${Us("inverse",n)}${r}`}get cursor(){return this._cursor}#e(e){if(this.userInput.length===0){this._setUserInput(e);return}this._setUserInput(this.userInput.slice(0,this.cursor)+e+this.userInput.slice(this.cursor))}#s(e){let t=this.value??"";switch(e){case"up":this._cursor=Hs(this._cursor,0,-1,t);return;case"down":this._cursor=Hs(this._cursor,0,1,t);return;case"left":this._cursor=Hs(this._cursor,-1,0,t);return;case"right":this._cursor=Hs(this._cursor,1,0,t);return}}_shouldSubmit(e,t){if(this.#n)return this.focused==="submit"?!0:(this.#e(`
18
+ ${r}`:`${t}${So("inverse",n)}${r}`}get cursor(){return this._cursor}#e(e){if(this.userInput.length===0){this._setUserInput(e);return}this._setUserInput(this.userInput.slice(0,this.cursor)+e+this.userInput.slice(this.cursor))}#s(e){let t=this.value??"";switch(e){case"up":this._cursor=Eo(this._cursor,0,-1,t);return;case"down":this._cursor=Eo(this._cursor,0,1,t);return;case"left":this._cursor=Eo(this._cursor,-1,0,t);return;case"right":this._cursor=Eo(this._cursor,1,0,t);return}}_shouldSubmit(e,t){if(this.#n)return this.focused==="submit"?!0:(this.#e(`
19
19
  `),this._cursor++,!1);let n=this.#t;return this.#t=!0,n&&this.cursor===this.userInput.length?(this.userInput[this.cursor-1]===`
20
20
  `&&(this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--),!0):(this.#e(`
21
- `),this._cursor++,!1)}constructor(e){let t=e.initialUserInput??e.initialValue;super({...e,initialUserInput:t},!1),t!==void 0&&(this._cursor=t.length),this.#n=e.showSubmit??!1,this.on("key",(n,r)=>{if(r?.name&&qw.has(r.name)){this.#t=!1,this.#s(r.name);return}if(n==="\t"&&this.#n){this.focused=this.focused==="editor"?"submit":"editor";return}if(r?.name!=="return"){if(this.#t=!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}n&&(this.#n&&this.focused==="submit"&&(this.focused="editor"),this.#e(n??""),this._cursor++)}}),this.on("userInput",(n)=>{this._setValue(n)}),this.on("finalize",()=>{this.value||(this.value=e.defaultValue),this.value===void 0&&(this.value="")})}}class Ta extends wt{options;cursor=0;get _value(){return this.options[this.cursor]?.value}get _enabledOptions(){return this.options.filter((e)=>e.disabled!==!0)}toggleAll(){let e=this._enabledOptions,t=this.value!==void 0&&this.value.length===e.length;this.value=t?[]:e.map((n)=>n.value)}toggleInvert(){let e=this.value;if(!e)return;let t=this._enabledOptions.filter((n)=>!e.includes(n.value));this.value=t.map((n)=>n.value)}toggleValue(){this.value===void 0&&(this.value=[]);let e=this.value.includes(this._value);this.value=e?this.value.filter((t)=>t!==this._value):[...this.value,this._value]}constructor(e){super(e,!1),this.options=e.options,this.value=[...e.initialValues??[]];let t=Math.max(this.options.findIndex(({value:n})=>n===e.cursorAt),0);this.cursor=this.options[t]?.disabled?br(t,1,this.options):t,this.on("key",(n,r)=>{r.name==="a"&&this.toggleAll(),r.name==="i"&&this.toggleInvert()}),this.on("cursor",(n)=>{switch(n){case"left":case"up":this.cursor=br(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=br(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}class Aa extends wt{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${this.userInput}█`;let t=e.slice(0,this.cursor),n=e.slice(this.cursor,this.cursor+1),r=e.slice(this.cursor+1);return`${t}${Us("inverse",n)}${r}`}get cursor(){return this._cursor}constructor(e){super({...e,initialUserInput:e.initialUserInput??e.initialValue}),this.on("userInput",(t)=>{this._setValue(t)}),this.on("finalize",()=>{this.value||(this.value=e.defaultValue),this.value===void 0&&(this.value="")})}}import{styleText as M,stripVTControlCharacters as TM}from"node:util";import bt from"node:process";var Dl=Ts(Ia(),1);function Qw(){if(bt.platform!=="win32")return bt.env.TERM!=="linux";return Boolean(bt.env.CI)||Boolean(bt.env.WT_SESSION)||Boolean(bt.env.TERMINUS_SUBLIME)||bt.env.ConEmuTask==="{cmd::Cmder}"||bt.env.TERM_PROGRAM==="Terminus-Sublime"||bt.env.TERM_PROGRAM==="vscode"||bt.env.TERM==="xterm-256color"||bt.env.TERM==="alacritty"||bt.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var Yw=Qw();var Ie=(e,t)=>Yw?e:t,Zw=Ie("◆","*"),zw=Ie("■","x"),Bw=Ie("▲","x"),Ha=Ie("◇","o"),Vw=Ie("┌","T"),we=Ie("│","|"),mn=Ie("└","—"),GM=Ie("┐","T"),UM=Ie("┘","—"),Yl=Ie("●",">"),Zl=Ie("○"," "),Xw=Ie("◻","[•]"),zl=Ie("◼","[+]"),Bl=Ie("◻","[ ]"),_M=Ie("▪","•"),Vl=Ie("─","-"),xw=Ie("╮","+"),Dw=Ie("├","+"),eb=Ie("╯","+"),tb=Ie("╰","+"),CM=Ie("╭","+"),nb=Ie("●","•"),rb=Ie("◆","*"),ib=Ie("▲","!"),sb=Ie("■","x"),La=(e)=>{switch(e){case"initial":case"active":return M("cyan",Zw);case"cancel":return M("red",zw);case"error":return M("yellow",Bw);case"submit":return M("green",Ha)}},ob=(e)=>{switch(e){case"initial":case"active":return M("cyan",we);case"cancel":return M("red",we);case"error":return M("yellow",we);case"submit":return M("green",we)}};function ab(e,t){let n=[`${t?`${M("cyan",we)} `:""}${e.join(" • ")}`];return t&&n.push(M("cyan",mn)),n}var Xl=(e,t,n,r,i,s=!1)=>{let o=t,a=0;if(s)for(let u=r-1;u>=n;u--){let c=e[u];if(c&&(o-=c.length),a++,o<=i)break}else for(let u=n;u<r;u++){let c=e[u];if(c&&(o-=c.length),a++,o<=i)break}return{lineCount:o,removals:a}},xl=({cursor:e,options:t,style:n,output:r=process.stdout,maxItems:i=Number.POSITIVE_INFINITY,columnPadding:s=0,rowPadding:o=4})=>{let a=_s(r)-s,u=Pa(r),c=M("dim","..."),l=Math.max(u-o,0),h=Math.max(Math.min(i,l),5),f=0;e>=h-3&&(f=Math.max(Math.min(e-h+3,t.length-h),0));let d=h<t.length&&f>0,g=h<t.length&&f+h<t.length,m=Math.min(f+h,t.length),b=[],p=0;d&&p++,g&&p++;let E=f+(d?1:0),v=m-(g?1:0);for(let w=E;w<v;w++){let N=t[w],y=N?n(N,w===e):"",R=dn(y,a,{hard:!0,trim:!1}).split(`
22
- `);b.push(R),p+=R.length}if(p>l){let w=0,N=0,y=p,R=e-E,P=l,G=()=>Xl(b,y,0,R,P),A=()=>Xl(b,y,R+1,b.length,P,!0);d?({lineCount:y,removals:w}=G(),y>P&&(g||(P-=1),{lineCount:y,removals:N}=A())):(g||(P-=1),{lineCount:y,removals:N}=A(),y>P&&(P-=1,{lineCount:y,removals:w}=G())),w>0&&(d=!0,b.splice(0,w)),N>0&&(g=!0,b.splice(b.length-N,N))}let S=[];d&&S.push(c);for(let w of b)for(let N of w)S.push(N);return g&&S.push(c),S};var _t=(e)=>{let t=e.active??"Yes",n=e.inactive??"No";return new Oa({active:t,inactive:n,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let r=e.withGuide??Xe.withGuide,i=`${La(this.state)} `,s=r?`${M("gray",we)} `:"",o=pi(e.output,e.message,s,i),a=`${r?`${M("gray",we)}
21
+ `),this._cursor++,!1)}constructor(e){let t=e.initialUserInput??e.initialValue;super({...e,initialUserInput:t},!1),t!==void 0&&(this._cursor=t.length),this.#n=e.showSubmit??!1,this.on("key",(n,r)=>{if(r?.name&&g0.has(r.name)){this.#t=!1,this.#s(r.name);return}if(n==="\t"&&this.#n){this.focused=this.focused==="editor"?"submit":"editor";return}if(r?.name!=="return"){if(this.#t=!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}n&&(this.#n&&this.focused==="submit"&&(this.focused="editor"),this.#e(n??""),this._cursor++)}}),this.on("userInput",(n)=>{this._setValue(n)}),this.on("finalize",()=>{this.value||(this.value=e.defaultValue),this.value===void 0&&(this.value="")})}}class yu extends It{options;cursor=0;get _value(){return this.options[this.cursor]?.value}get _enabledOptions(){return this.options.filter((e)=>e.disabled!==!0)}toggleAll(){let e=this._enabledOptions,t=this.value!==void 0&&this.value.length===e.length;this.value=t?[]:e.map((n)=>n.value)}toggleInvert(){let e=this.value;if(!e)return;let t=this._enabledOptions.filter((n)=>!e.includes(n.value));this.value=t.map((n)=>n.value)}toggleValue(){this.value===void 0&&(this.value=[]);let e=this.value.includes(this._value);this.value=e?this.value.filter((t)=>t!==this._value):[...this.value,this._value]}constructor(e){super(e,!1),this.options=e.options,this.value=[...e.initialValues??[]];let t=Math.max(this.options.findIndex(({value:n})=>n===e.cursorAt),0);this.cursor=this.options[t]?.disabled?Cr(t,1,this.options):t,this.on("key",(n,r)=>{r.name==="a"&&this.toggleAll(),r.name==="i"&&this.toggleInvert()}),this.on("cursor",(n)=>{switch(n){case"left":case"up":this.cursor=Cr(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=Cr(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}class Eu extends It{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${this.userInput}█`;let t=e.slice(0,this.cursor),n=e.slice(this.cursor,this.cursor+1),r=e.slice(this.cursor+1);return`${t}${So("inverse",n)}${r}`}get cursor(){return this._cursor}constructor(e){super({...e,initialUserInput:e.initialUserInput??e.initialValue}),this.on("userInput",(t)=>{this._setValue(t)}),this.on("finalize",()=>{this.value||(this.value=e.defaultValue),this.value===void 0&&(this.value="")})}}import{styleText as I,stripVTControlCharacters as jI}from"node:util";import Nt from"node:process";var qh=ko(mu(),1);function m0(){if(Nt.platform!=="win32")return Nt.env.TERM!=="linux";return Boolean(Nt.env.CI)||Boolean(Nt.env.WT_SESSION)||Boolean(Nt.env.TERMINUS_SUBLIME)||Nt.env.ConEmuTask==="{cmd::Cmder}"||Nt.env.TERM_PROGRAM==="Terminus-Sublime"||Nt.env.TERM_PROGRAM==="vscode"||Nt.env.TERM==="xterm-256color"||Nt.env.TERM==="alacritty"||Nt.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var p0=m0();var Ne=(e,t)=>p0?e:t,b0=Ne("◆","*"),w0=Ne("■","x"),$0=Ne("▲","x"),vu=Ne("◇","o"),k0=Ne("┌","T"),$e=Ne("│","|"),In=Ne("└","—"),BI=Ne("┐","T"),qI=Ne("┘","—"),Gh=Ne("●",">"),Uh=Ne("○"," "),y0=Ne("◻","[•]"),jh=Ne("◼","[+]"),Wh=Ne("◻","[ ]"),zI=Ne("▪","•"),Kh=Ne("─","-"),E0=Ne("╮","+"),v0=Ne("├","+"),M0=Ne("╯","+"),S0=Ne("╰","+"),YI=Ne("╭","+"),I0=Ne("●","•"),N0=Ne("◆","*"),P0=Ne("▲","!"),F0=Ne("■","x"),Mu=(e)=>{switch(e){case"initial":case"active":return I("cyan",b0);case"cancel":return I("red",w0);case"error":return I("yellow",$0);case"submit":return I("green",vu)}},R0=(e)=>{switch(e){case"initial":case"active":return I("cyan",$e);case"cancel":return I("red",$e);case"error":return I("yellow",$e);case"submit":return I("green",$e)}};function O0(e,t){let n=[`${t?`${I("cyan",$e)} `:""}${e.join(" • ")}`];return t&&n.push(I("cyan",In)),n}var Jh=(e,t,n,r,i,s=!1)=>{let o=t,a=0;if(s)for(let u=r-1;u>=n;u--){let c=e[u];if(c&&(o-=c.length),a++,o<=i)break}else for(let u=n;u<r;u++){let c=e[u];if(c&&(o-=c.length),a++,o<=i)break}return{lineCount:o,removals:a}},Bh=({cursor:e,options:t,style:n,output:r=process.stdout,maxItems:i=Number.POSITIVE_INFINITY,columnPadding:s=0,rowPadding:o=4})=>{let a=Io(r)-s,u=$u(r),c=I("dim","..."),l=Math.max(u-o,0),h=Math.max(Math.min(i,l),5),f=0;e>=h-3&&(f=Math.max(Math.min(e-h+3,t.length-h),0));let d=h<t.length&&f>0,g=h<t.length&&f+h<t.length,p=Math.min(f+h,t.length),b=[],m=0;d&&m++,g&&m++;let $=f+(d?1:0),k=p-(g?1:0);for(let w=$;w<k;w++){let M=t[w],y=M?n(M,w===e):"",N=Mn(y,a,{hard:!0,trim:!1}).split(`
22
+ `);b.push(N),m+=N.length}if(m>l){let w=0,M=0,y=m,N=e-$,R=l,H=()=>Jh(b,y,0,N,R),A=()=>Jh(b,y,N+1,b.length,R,!0);d?({lineCount:y,removals:w}=H(),y>R&&(g||(R-=1),{lineCount:y,removals:M}=A())):(g||(R-=1),{lineCount:y,removals:M}=A(),y>R&&(R-=1,{lineCount:y,removals:w}=H())),w>0&&(d=!0,b.splice(0,w)),M>0&&(g=!0,b.splice(b.length-M,M))}let S=[];d&&S.push(c);for(let w of b)for(let M of w)S.push(M);return g&&S.push(c),S};var Nn=(e)=>{let t=e.active??"Yes",n=e.inactive??"No";return new ku({active:t,inactive:n,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let r=e.withGuide??rt.withGuide,i=`${Mu(this.state)} `,s=r?`${I("gray",$e)} `:"",o=ji(e.output,e.message,s,i),a=`${r?`${I("gray",$e)}
23
23
  `:""}${o}
24
- `,u=this.value?t:n;switch(this.state){case"submit":{let c=r?`${M("gray",we)} `:"";return`${a}${c}${M("dim",u)}`}case"cancel":{let c=r?`${M("gray",we)} `:"";return`${a}${c}${M(["strikethrough","dim"],u)}${r?`
25
- ${M("gray",we)}`:""}`}default:{let c=r?`${M("cyan",we)} `:"",l=r?M("cyan",mn):"";return`${a}${c}${this.value?`${M("green",Yl)} ${t}`:`${M("dim",Zl)} ${M("dim",t)}`}${e.vertical?r?`
26
- ${M("cyan",we)} `:`
27
- `:` ${M("dim","/")} `}${this.value?`${M("dim",Zl)} ${M("dim",n)}`:`${M("green",Yl)} ${n}`}
24
+ `,u=this.value?t:n;switch(this.state){case"submit":{let c=r?`${I("gray",$e)} `:"";return`${a}${c}${I("dim",u)}`}case"cancel":{let c=r?`${I("gray",$e)} `:"";return`${a}${c}${I(["strikethrough","dim"],u)}${r?`
25
+ ${I("gray",$e)}`:""}`}default:{let c=r?`${I("cyan",$e)} `:"",l=r?I("cyan",In):"";return`${a}${c}${this.value?`${I("green",Gh)} ${t}`:`${I("dim",Uh)} ${I("dim",t)}`}${e.vertical?r?`
26
+ ${I("cyan",$e)} `:`
27
+ `:` ${I("dim","/")} `}${this.value?`${I("dim",Uh)} ${I("dim",n)}`:`${I("green",Gh)} ${n}`}
28
28
  ${l}
29
- `}}}}).prompt()};var ub=[`${M("dim","↑/↓")} to navigate`,`${M("dim","Space:")} select`,`${M("dim","Enter:")} confirm`],wi=(e,t)=>e.split(`
29
+ `}}}}).prompt()};var T0=[`${I("dim","↑/↓")} to navigate`,`${I("dim","Space:")} select`,`${I("dim","Enter:")} confirm`],Wi=(e,t)=>e.split(`
30
30
  `).map((n)=>t(n)).join(`
31
- `),eh=(e)=>{let t=(i,s)=>{let o=i.label??String(i.value);return s==="disabled"?`${M("gray",Bl)} ${wi(o,(a)=>M(["strikethrough","gray"],a))}${i.hint?` ${M("dim",`(${i.hint??"disabled"})`)}`:""}`:s==="active"?`${M("cyan",Xw)} ${o}${i.hint?` ${M("dim",`(${i.hint})`)}`:""}`:s==="selected"?`${M("green",zl)} ${wi(o,(a)=>M("dim",a))}${i.hint?` ${M("dim",`(${i.hint})`)}`:""}`:s==="cancelled"?`${wi(o,(a)=>M(["strikethrough","dim"],a))}`:s==="active-selected"?`${M("green",zl)} ${o}${i.hint?` ${M("dim",`(${i.hint})`)}`:""}`:s==="submitted"?`${wi(o,(a)=>M("dim",a))}`:`${M("dim",Bl)} ${wi(o,(a)=>M("dim",a))}`},n=e.required??!0,r=e.showInstructions??!0;return new Ta({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValues:e.initialValues,required:n,cursorAt:e.cursorAt,validate(i){if(n&&(i===void 0||i.length===0))return`Please select at least one option.
32
- ${M("reset",M("dim",`Press ${M(["gray","bgWhite","inverse"]," space ")} to select, ${M("gray",M("bgWhite",M("inverse"," enter ")))} to submit`))}`},render(){let i=e.withGuide??Xe.withGuide,s=pi(e.output,e.message,i?`${ob(this.state)} `:"",`${La(this.state)} `),o=`${i?`${M("gray",we)}
31
+ `),zh=(e)=>{let t=(i,s)=>{let o=i.label??String(i.value);return s==="disabled"?`${I("gray",Wh)} ${Wi(o,(a)=>I(["strikethrough","gray"],a))}${i.hint?` ${I("dim",`(${i.hint??"disabled"})`)}`:""}`:s==="active"?`${I("cyan",y0)} ${o}${i.hint?` ${I("dim",`(${i.hint})`)}`:""}`:s==="selected"?`${I("green",jh)} ${Wi(o,(a)=>I("dim",a))}${i.hint?` ${I("dim",`(${i.hint})`)}`:""}`:s==="cancelled"?`${Wi(o,(a)=>I(["strikethrough","dim"],a))}`:s==="active-selected"?`${I("green",jh)} ${o}${i.hint?` ${I("dim",`(${i.hint})`)}`:""}`:s==="submitted"?`${Wi(o,(a)=>I("dim",a))}`:`${I("dim",Wh)} ${Wi(o,(a)=>I("dim",a))}`},n=e.required??!0,r=e.showInstructions??!0;return new yu({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValues:e.initialValues,required:n,cursorAt:e.cursorAt,validate(i){if(n&&(i===void 0||i.length===0))return`Please select at least one option.
32
+ ${I("reset",I("dim",`Press ${I(["gray","bgWhite","inverse"]," space ")} to select, ${I("gray",I("bgWhite",I("inverse"," enter ")))} to submit`))}`},render(){let i=e.withGuide??rt.withGuide,s=ji(e.output,e.message,i?`${R0(this.state)} `:"",`${Mu(this.state)} `),o=`${i?`${I("gray",$e)}
33
33
  `:""}${s}
34
- `,a=this.value??[],u=(c,l)=>{if(c.disabled)return t(c,"disabled");let h=a.includes(c.value);return l&&h?t(c,"active-selected"):h?t(c,"selected"):t(c,l?"active":"inactive")};switch(this.state){case"submit":{let c=this.options.filter(({value:h})=>a.includes(h)).map((h)=>t(h,"submitted")).join(M("dim",", "))||M("dim","none"),l=pi(e.output,c,i?`${M("gray",we)} `:"");return`${o}${l}`}case"cancel":{let c=this.options.filter(({value:h})=>a.includes(h)).map((h)=>t(h,"cancelled")).join(M("dim",", "));if(c.trim()==="")return`${o}${M("gray",we)}`;let l=pi(e.output,c,i?`${M("gray",we)} `:"");return`${o}${l}${i?`
35
- ${M("gray",we)}`:""}`}case"error":{let c=i?`${M("yellow",we)} `:"",l=this.error.split(`
36
- `).map((d,g)=>g===0?`${i?`${M("yellow",mn)} `:""}${M("yellow",d)}`:` ${d}`).join(`
34
+ `,a=this.value??[],u=(c,l)=>{if(c.disabled)return t(c,"disabled");let h=a.includes(c.value);return l&&h?t(c,"active-selected"):h?t(c,"selected"):t(c,l?"active":"inactive")};switch(this.state){case"submit":{let c=this.options.filter(({value:h})=>a.includes(h)).map((h)=>t(h,"submitted")).join(I("dim",", "))||I("dim","none"),l=ji(e.output,c,i?`${I("gray",$e)} `:"");return`${o}${l}`}case"cancel":{let c=this.options.filter(({value:h})=>a.includes(h)).map((h)=>t(h,"cancelled")).join(I("dim",", "));if(c.trim()==="")return`${o}${I("gray",$e)}`;let l=ji(e.output,c,i?`${I("gray",$e)} `:"");return`${o}${l}${i?`
35
+ ${I("gray",$e)}`:""}`}case"error":{let c=i?`${I("yellow",$e)} `:"",l=this.error.split(`
36
+ `).map((d,g)=>g===0?`${i?`${I("yellow",In)} `:""}${I("yellow",d)}`:` ${d}`).join(`
37
37
  `),h=o.split(`
38
38
  `).length,f=l.split(`
39
- `).length+1;return`${o}${c}${xl({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:c.length,rowPadding:h+f,style:u}).join(`
39
+ `).length+1;return`${o}${c}${Bh({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:c.length,rowPadding:h+f,style:u}).join(`
40
40
  ${c}`)}
41
41
  ${l}
42
- `}default:{let c=i?`${M("cyan",we)} `:"",l=o.split(`
43
- `).length,h=r?ab(ub,i):i?[M("cyan",mn)]:[],f=h.join(`
44
- `),d=h.length+1;return`${o}${c}${xl({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:c.length,rowPadding:l+d,style:u}).join(`
42
+ `}default:{let c=i?`${I("cyan",$e)} `:"",l=o.split(`
43
+ `).length,h=r?O0(T0,i):i?[I("cyan",In)]:[],f=h.join(`
44
+ `),d=h.length+1;return`${o}${c}${Bh({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:c.length,rowPadding:l+d,style:u}).join(`
45
45
  ${c}`)}
46
46
  ${f}
47
- `}}}}).prompt()};var gn={message:(e=[],{symbol:t=M("gray",we),secondarySymbol:n=M("gray",we),output:r=process.stdout,spacing:i=1,withGuide:s}={})=>{let o=[],a=s??Xe.withGuide,u=a?n:"",c=a?`${t} `:"",l=a?`${n} `:"";for(let f=0;f<i;f++)o.push(u);let h=Array.isArray(e)?e:e.split(`
47
+ `}}}}).prompt()};var Sn={message:(e=[],{symbol:t=I("gray",$e),secondarySymbol:n=I("gray",$e),output:r=process.stdout,spacing:i=1,withGuide:s}={})=>{let o=[],a=s??rt.withGuide,u=a?n:"",c=a?`${t} `:"",l=a?`${n} `:"";for(let f=0;f<i;f++)o.push(u);let h=Array.isArray(e)?e:e.split(`
48
48
  `);if(h.length>0){let[f,...d]=h;f.length>0?o.push(`${c}${f}`):o.push(a?t:"");for(let g of d)g.length>0?o.push(`${l}${g}`):o.push(a?n:"")}r.write(`${o.join(`
49
49
  `)}
50
- `)},info:(e,t)=>{gn.message(e,{...t,symbol:M("blue",nb)})},success:(e,t)=>{gn.message(e,{...t,symbol:M("green",rb)})},step:(e,t)=>{gn.message(e,{...t,symbol:M("green",Ha)})},warn:(e,t)=>{gn.message(e,{...t,symbol:M("yellow",ib)})},warning:(e,t)=>{gn.warn(e,t)},error:(e,t)=>{gn.message(e,{...t,symbol:M("red",sb)})}},$r=(e="",t)=>{let n=t?.output??process.stdout,r=t?.withGuide??Xe.withGuide?`${M("gray",mn)} `:"";n.write(`${r}${M("red",e)}
50
+ `)},info:(e,t)=>{Sn.message(e,{...t,symbol:I("blue",I0)})},success:(e,t)=>{Sn.message(e,{...t,symbol:I("green",N0)})},step:(e,t)=>{Sn.message(e,{...t,symbol:I("green",vu)})},warn:(e,t)=>{Sn.message(e,{...t,symbol:I("yellow",P0)})},warning:(e,t)=>{Sn.warn(e,t)},error:(e,t)=>{Sn.message(e,{...t,symbol:I("red",F0)})}},_r=(e="",t)=>{let n=t?.output??process.stdout,r=t?.withGuide??rt.withGuide?`${I("gray",In)} `:"";n.write(`${r}${I("red",e)}
51
51
 
52
- `)},Cs=(e="",t)=>{let n=t?.output??process.stdout,r=t?.withGuide??Xe.withGuide?`${M("gray",Vw)} `:"";n.write(`${r}${e}
53
- `)},Ga=(e="",t)=>{let n=t?.output??process.stdout,r=t?.withGuide??Xe.withGuide?`${M("gray",we)}
54
- ${M("gray",mn)} `:"";n.write(`${r}${e}
52
+ `)},No=(e="",t)=>{let n=t?.output??process.stdout,r=t?.withGuide??rt.withGuide?`${I("gray",k0)} `:"";n.write(`${r}${e}
53
+ `)},Su=(e="",t)=>{let n=t?.output??process.stdout,r=t?.withGuide??rt.withGuide?`${I("gray",$e)}
54
+ ${I("gray",In)} `:"";n.write(`${r}${e}
55
55
 
56
- `)};var cb=(e)=>e,lb=(e,t,n)=>{let r={hard:!0,trim:!1},i=dn(e,t,r).split(`
57
- `),s=i.reduce((u,c)=>Math.max(je(c),u),0),o=i.map(n).reduce((u,c)=>Math.max(je(c),u),0),a=t-(o-s);return dn(e,a,r)},Wn=(e="",t="",n)=>{let r=n?.output??bt.stdout,i=n?.withGuide??Xe.withGuide,s=n?.format??cb,o=["",...lb(e,_s(r)-6,s).split(`
58
- `).map(s),""],a=je(t),u=Math.max(o.reduce((f,d)=>{let g=je(d);return g>f?g:f},0),a)+2,c=o.map((f)=>`${M("gray",we)} ${f}${" ".repeat(u-je(f))}${M("gray",we)}`).join(`
59
- `),l=i?`${M("gray",we)}
60
- `:"",h=i?Dw:tb;r.write(`${l}${M("green",Ha)} ${M("reset",t)} ${M("gray",Vl.repeat(Math.max(u-a-1,1))+xw)}
56
+ `)};var H0=(e)=>e,A0=(e,t,n)=>{let r={hard:!0,trim:!1},i=Mn(e,t,r).split(`
57
+ `),s=i.reduce((u,c)=>Math.max(we(c),u),0),o=i.map(n).reduce((u,c)=>Math.max(we(c),u),0),a=t-(o-s);return Mn(e,a,r)},ir=(e="",t="",n)=>{let r=n?.output??Nt.stdout,i=n?.withGuide??rt.withGuide,s=n?.format??H0,o=["",...A0(e,Io(r)-6,s).split(`
58
+ `).map(s),""],a=we(t),u=Math.max(o.reduce((f,d)=>{let g=we(d);return g>f?g:f},0),a)+2,c=o.map((f)=>`${I("gray",$e)} ${f}${" ".repeat(u-we(f))}${I("gray",$e)}`).join(`
59
+ `),l=i?`${I("gray",$e)}
60
+ `:"",h=i?v0:S0;r.write(`${l}${I("green",vu)} ${I("reset",t)} ${I("gray",Kh.repeat(Math.max(u-a-1,1))+E0)}
61
61
  ${c}
62
- ${M("gray",h+Vl.repeat(u+2)+eb)}
63
- `)};var jM={light:Ie("─","-"),heavy:Ie("━","="),block:Ie("█","#")};var WM=[`${M("dim","↑/↓")} to navigate`,`${M("dim","Enter:")} confirm`];var JM=`${M("gray",we)} `;var Ua=(e)=>new Aa({validate:e.validate,placeholder:e.placeholder,defaultValue:e.defaultValue,initialValue:e.initialValue,output:e.output,signal:e.signal,input:e.input,render(){let t=e?.withGuide??Xe.withGuide,n=`${`${t?`${M("gray",we)}
64
- `:""}${La(this.state)} `}${e.message}
65
- `,r=e.placeholder&&e.placeholder.length>0?M("inverse",e.placeholder[0])+M("dim",e.placeholder.slice(1)):M(["inverse","hidden"],"_"),i=this.userInput?this.userInputWithCursor:r,s=this.value??"";switch(this.state){case"error":{let o=this.error?` ${M("yellow",this.error)}`:"",a=t?`${M("yellow",we)} `:"",u=t?M("yellow",mn):"";return`${n.trim()}
62
+ ${I("gray",h+Kh.repeat(u+2)+M0)}
63
+ `)};var QI={light:Ne("─","-"),heavy:Ne("━","="),block:Ne("█","#")};var ZI=[`${I("dim","↑/↓")} to navigate`,`${I("dim","Enter:")} confirm`];var VI=`${I("gray",$e)} `;var Iu=(e)=>new Eu({validate:e.validate,placeholder:e.placeholder,defaultValue:e.defaultValue,initialValue:e.initialValue,output:e.output,signal:e.signal,input:e.input,render(){let t=e?.withGuide??rt.withGuide,n=`${`${t?`${I("gray",$e)}
64
+ `:""}${Mu(this.state)} `}${e.message}
65
+ `,r=e.placeholder&&e.placeholder.length>0?I("inverse",e.placeholder[0])+I("dim",e.placeholder.slice(1)):I(["inverse","hidden"],"_"),i=this.userInput?this.userInputWithCursor:r,s=this.value??"";switch(this.state){case"error":{let o=this.error?` ${I("yellow",this.error)}`:"",a=t?`${I("yellow",$e)} `:"",u=t?I("yellow",In):"";return`${n.trim()}
66
66
  ${a}${i}
67
67
  ${u}${o}
68
- `}case"submit":{let o=s?` ${M("dim",s)}`:"",a=t?M("gray",we):"";return`${n}${a}${o}`}case"cancel":{let o=s?` ${M(["strikethrough","dim"],s)}`:"",a=t?M("gray",we):"";return`${n}${a}${o}${s.trim()?`
69
- ${a}`:""}`}default:{let o=t?`${M("cyan",we)} `:"",a=t?M("cyan",mn):"";return`${n}${o}${i}
68
+ `}case"submit":{let o=s?` ${I("dim",s)}`:"",a=t?I("gray",$e):"";return`${n}${a}${o}`}case"cancel":{let o=s?` ${I(["strikethrough","dim"],s)}`:"",a=t?I("gray",$e):"";return`${n}${a}${o}${s.trim()?`
69
+ ${a}`:""}`}default:{let o=t?`${I("cyan",$e)} `:"",a=t?I("cyan",In):"";return`${n}${o}${i}
70
70
  ${a}
71
- `}}}}).prompt();function _a(e){let t=e.replace("#","");return[t.slice(0,2),t.slice(2,4),t.slice(4,6)].map((n)=>Number.parseInt(n,16)).join(";")}function pn(e){return`\x1B[38;2;${_a(e)}m`}function js(e,t){return`\x1B[48;2;${_a(e)};38;2;${_a(t)}m`}function th(e,t="\x1B[39m"){return`${e.map((n)=>`${pn(n)}■`).join(" ")}${t}`}function hb(e,t){if(e[t]!=="\x1B"||e[t+1]!=="[")return 0;let n=t+2;while(n<e.length&&!/[@-~]/.test(e[n]))n++;return n<e.length?n-t+1:0}function nh(e,t){let n="",r=0,i=0;while(i<e.length){let s=hb(e,i);if(s>0){n+=e.slice(i,i+s),i+=s;continue}let o=String.fromCodePoint(e.codePointAt(i)),a=je(o);if(r+a>t)break;n+=o,r+=a,i+=o.length}return{head:n,used:r}}function Ct(e,t,n=!0){if(t<=0)return"";let r=je(e);if(r<=t)return n?e+" ".repeat(t-r):e;let{head:i,used:s}=nh(e,t-1);return`${i}${e.includes("\x1B")?"\x1B[0m":""}…${n?" ".repeat(t-1-s):""}`}function rh(e,t,n){let r=n-je(t)-1;return r<=0?Ct(e,n):`${Ct(e,r)} ${t}`}function tt(e,t){let n=[],r="";for(let i of e.split(/\s+/).filter(Boolean)){let s=r?`${r} ${i}`:i;if(je(s)<=t){r=s;continue}if(r)n.push(r);while(je(i)>t){let{head:o}=nh(i,t),a=Math.max(o.lastIndexOf("/")+1,o.lastIndexOf("#")),u=a>0?a:o.length;n.push(i.slice(0,u)),i=i.slice(u)}r=i}if(r)n.push(r);return n}import{existsSync as Yd,readFileSync as Ku}from"node:fs";import{join as Zd}from"node:path";var fb=/^#[0-9a-f]{6}$/;function yr(e){return fb.test(e)}function Qe(e){let t=Number.parseInt(e.slice(1),16);return[t>>16&255,t>>8&255,t&255]}function rt(e,t,n){let r=Qe(e),i=Qe(t);return`#${r.map((s,o)=>Math.round(s+((i[o]??0)-s)*n).toString(16).padStart(2,"0")).join("")}`}function nt(e){let[t,n,r]=Qe(e).map((i)=>{let s=i/255;return s<=0.03928?s/12.92:((s+0.055)/1.055)**2.4});return 0.2126*t+0.7152*n+0.0722*r}function ct(e,t){let n=nt(e),r=nt(t);return(Math.max(n,r)+0.05)/(Math.min(n,r)+0.05)}function Ws(e,t){return Math.round(ct(e,t)*100)/100}function db(e){let t=e/255;return t<=0.04045?t/12.92:((t+0.055)/1.055)**2.4}function St(e){let[t,n,r]=Qe(e).map(db),i=Math.cbrt(0.4122214708*t+0.5363325363*n+0.0514459929*r),s=Math.cbrt(0.2119034982*t+0.6806995451*n+0.1073969566*r),o=Math.cbrt(0.0883024619*t+0.2817188376*n+0.6299787005*r),a=1.9779984951*i-2.428592205*s+0.4505937099*o,u=0.0259040371*i+0.7827717662*s-0.808675766*o;return{l:0.2104542553*i+0.793617785*s-0.0040720468*o,c:Math.hypot(a,u),h:(Math.atan2(u,a)*180/Math.PI+360)%360}}var wn=7,ih=3,Ca=0.15,sh=1.6,Wa=[1,2,3,4,5,6,9,10,11,12,13,14],oh=[7,15],Er=[1,2,3,4,5,6],$i={1:{name:"red",center:19,width:25},2:{name:"green",center:132,width:35},3:{name:"yellow",center:88,width:35},4:{name:"blue",center:250,width:60},5:{name:"magenta",center:329,width:40},6:{name:"cyan",center:197,width:60}},Ja=0.03,Jn=25,Qs=15,Ys=0.08;function en(e,t){let n=e.ansi[t];if(n===void 0)throw Error(`${e.name}: missing ANSI ${t}`);return n}function ja(e,t,n){let r=e.background;return t.flatMap((i)=>{let s=en(e,i);return ct(s,r)<n?[`ANSI ${i} ${s} on ${r} is ${Ws(s,r)}:1, needs ${n}:1`]:[]})}function ah(e,t){return Math.min(...t.map((n)=>ct(en(e,n),e.background)))}var uh=[{rule:"foreground",label:"foreground on background",unit:"ratio",min:wn,measure:({foreground:e,background:t})=>ct(e,t),check:({foreground:e,background:t})=>ct(e,t)<wn?[`foreground ${e} on ${t} is ${Ws(e,t)}:1, needs ${wn}:1`]:[]},{rule:"accents",label:"weakest accent on background",unit:"ratio",min:ih,measure:(e)=>ah(e,Wa),check:(e)=>ja(e,Wa,ih)},{rule:"ansi0-dark",label:"ansi0 luminance",unit:"luminance",max:Ca,measure:(e)=>nt(en(e,0)),check:(e)=>{let t=en(e,0);return nt(t)>Ca?[`ANSI 0 ${t} has luminance ${nt(t).toFixed(3)}, needs <= ${Ca}`]:[]}},{rule:"light-ansi",label:"ansi7 and ansi15 on background",unit:"ratio",min:wn,measure:(e)=>ah(e,oh),check:(e)=>ja(e,oh,wn)},{rule:"ansi8-visible",label:"ansi8 on background",unit:"ratio",min:sh,measure:(e)=>ct(en(e,8),e.background),check:(e)=>ja(e,[8],sh)},{rule:"selection",label:"foreground on selection",unit:"ratio",min:wn,measure:({foreground:e,selectionBackground:t})=>t===void 0?Number.NaN:ct(e,t),check:({foreground:e,selectionBackground:t})=>t!==void 0&&ct(e,t)<wn?[`foreground ${e} on selection ${t} is ${Ws(e,t)}:1, needs ${wn}:1`]:[]}];function bn(e,t){let n=Math.abs(e-t)%360;return Math.min(n,360-n)}var vr=(e)=>e>8?e-8:e;function Zs(e){let t=e.signatureSlots.filter((n)=>n.startsWith("ansi")).map((n)=>Number(n.slice(4)));return new Set(t.flatMap((n)=>Er.includes(vr(n))?[n,n>8?n-8:n+8]:[n]))}function bi(e,t){let n=St(en(e,t));return n.c<Ja?void 0:n}function Js(e){let t=Zs(e);return Wa.flatMap((n)=>{let r=bi(e,n),i=$i[vr(n)];if(r===void 0||i===void 0||t.has(n))return[];let s=bn(r.h,i.center)-i.width;return s>0?[{slot:n,hue:r.h,over:s}]:[]})}function Ks(e){let t=new Set(e.signatureSlots);return Er.flatMap((n)=>{let r=bi(e,n),i=bi(e,n+8);if(r===void 0||i===void 0||t.has(`ansi${n}`)&&t.has(`ansi${n+8}`))return[];return[{normal:n,gap:bn(r.h,i.h)}]})}function qs(e){let t=Zs(e);return[0,8].flatMap((n)=>Er.flatMap((r)=>Er.filter((i)=>i>r).flatMap((i)=>{let[s,o]=[n+r,n+i],a=bi(e,s),u=bi(e,o);if(a===void 0||u===void 0||t.has(s)&&t.has(o))return[];return bn(a.h,u.h)<Qs&&Math.abs(a.l-u.l)<Ys?[[s,o]]:[]})))}var gb=[{rule:"ansi-role",label:"accent hue outside its ANSI role",unit:"degrees",max:0,measure:(e)=>Math.max(0,...Js(e).map((t)=>t.over)),check:(e)=>Js(e).map(({slot:t,hue:n,over:r})=>{let i=$i[vr(t)];return`ANSI ${t} ${en(e,t)} has hue ${n.toFixed(0)}°, ${r.toFixed(0)}° outside ${i.name} (${i.center}±${i.width}°)`})},{rule:"bright-follows",label:"widest normal to bright hue gap",unit:"degrees",max:Jn,measure:(e)=>Math.max(0,...Ks(e).map((t)=>t.gap)),check:(e)=>Ks(e).filter((t)=>t.gap>Jn).map(({normal:t,gap:n})=>`ANSI ${t+8} is ${n.toFixed(0)}° from ANSI ${t}, needs <= ${Jn}°`)},{rule:"distinct",label:"accent pairs that read as one color",unit:"pairs",max:0,measure:(e)=>qs(e).length,check:(e)=>qs(e).map(([t,n])=>`ANSI ${t} ${en(e,t)} and ANSI ${n} ${en(e,n)} are within ${Qs}° hue and ${Ys} lightness`)}],zs=[...uh,...gb],Ka=zs.map((e)=>e.rule),jt=zs.map(({rule:e,label:t,unit:n,min:r,max:i})=>({rule:e,label:t,unit:n,...r===void 0?{}:{min:r},...i===void 0?{}:{max:i}}));function Mr(e){return zs.map((t)=>Math.round(t.measure(e)*1000)/1000)}function ch(e,t){return e.filter((n)=>!t.waive.includes(n.rule)).flatMap((n)=>n.check(t).map((r)=>({theme:t.name,rule:n.rule,detail:r})))}function Bs(e){return ch(zs,e)}function lh(e){return ch(uh,e)}function hh(e){return e.flatMap(Bs)}import{chmodSync as mb,copyFileSync as pb,existsSync as Sr,mkdirSync as wb,readFileSync as qa,realpathSync as bb,renameSync as $b,rmSync as fh,statSync as kb,writeFileSync as yb}from"node:fs";import{dirname as Eb}from"node:path";function dh(e){return`${e}.ttheme.bak`}var vb=/^(?:#|--) ttheme begin$|path = "ttheme-/m;function Qa(e){let t=dh(e);if(Sr(e)&&!Sr(t)&&!vb.test(qa(e,"utf8")))pb(e,t)}function ke(e,t){let n=Sr(e)?bb(e):e;wb(Eb(n),{recursive:!0});let r=`${n}.ttheme-${process.pid}`;if(yb(r,t),Sr(n))mb(r,kb(n).mode&4095);$b(r,n)}function ki(e,t){if((Sr(e)?qa(e,"utf8"):void 0)===t)return!1;return Qa(e),ke(e,t),!0}function gh(e,t){let n=dh(e),r=Sr(n)?qa(n,"utf8"):void 0;if(t===""&&r===void 0)return fh(e,{force:!0}),"removed";if(ke(e,t),r===void 0||r===t)return fh(n,{force:!0}),"restored";return"kept backup"}import{createHash as md}from"node:crypto";import{copyFileSync as V$,existsSync as Ru,mkdirSync as X$,readdirSync as x$,readFileSync as wo,renameSync as pd,rmSync as Lr}from"node:fs";import{basename as wd,isAbsolute as D$,join as V}from"node:path";var pf=Ts(yh(),1),Xs=Ts(gf(),1);import{deflateSync as J0}from"node:zlib";var vi=[137,80,78,71,13,10,26,10],wf=13,bf=3;function Fr(e){return e.length>=vi.length&&vi.every((t,n)=>e[n]===t)}function qn(e){let t=Xs.PNG.sync.read(Buffer.from(e));return{width:t.width,height:t.height,data:new Uint8Array(t.data)}}function Qn(e,t){if(Fr(e)){let n=yn(e);if(n&&n.width*n.height>t)throw Error(`${n.width}×${n.height} is over ${t/1e6} megapixels`);return qn(e)}if(e[0]===255&&e[1]===216){let n=pf.decode(e,{useTArray:!0,formatAsRGBA:!0,maxResolutionInMP:t/1e6,maxMemoryUsageInMB:1024});return{width:n.width,height:n.height,data:n.data}}throw Error("not a PNG or JPEG image")}function xs(e){let t=new Xs.PNG({width:e.width,height:e.height});return t.data=Buffer.from(e.data),Xs.PNG.sync.write(t)}function mf(e,t){for(let n=0;n+t.length<=e.length;n++){let r=!0;for(let i=0;i<t.length&&r;i++)r=e[n+i]===t.charCodeAt(i);if(r)return n}return-1}function yn(e){if(e.length<33||!Fr(e))return null;let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=t.getUint32(16),r=t.getUint32(20);if(e[25]===4||e[25]===6)return{width:n,height:r,alpha:!0};let i=mf(e,"IDAT");return{width:n,height:r,alpha:mf(i===-1?e:e.subarray(0,i),"tRNS")!==-1}}function $f(e,t=wf){let{width:n,height:r}=e,i=-1,s=-1;for(let o=0;o<e.height;o++)for(let a=0;a<e.width;a++)if((e.data[(o*e.width+a)*4+3]??0)>=t)n=Math.min(n,a),i=Math.max(i,a),r=Math.min(r,o),s=Math.max(s,o);return i<0?null:{x:n,y:r,w:i-n+1,h:s-r+1}}function tn(e,t={x:0,y:0,w:e.width,h:e.height}){let n=0;for(let r=t.y;r<t.y+t.h;r++)for(let i=t.x;i<t.x+t.w;i++)if((e.data[(r*e.width+i)*4+3]??0)<wf)n++;return Math.round(n*100/(t.w*t.h))}function kf(e,t,n){let r=Math.min(t/e.width,n/e.height),i=Math.max(1,Math.round(e.width*r)),s=Math.max(1,Math.round(e.height*r)),o=q0(e,{x:0,y:0,w:e.width,h:e.height},i,s),a=new Uint8Array(t*n*4),u=Math.floor((t-i)/2),c=Math.floor((n-s)/2);for(let l=0;l<s;l++)a.set(o.data.subarray(l*i*4,(l+1)*i*4),((c+l)*t+u)*4);return{width:t,height:n,data:a}}function K0(e){let t=Math.abs(e);if(t<1)return(7*t*t*t-12*t*t+5.333333333333333)/6;if(t<2)return(-2.3333333333333335*t*t*t+12*t*t-20*t+10.666666666666666)/6;return 0}function au(e,t,n,r){if(n===r&&Number.isInteger(t)&&t>=0&&t+r<=e)return{first:Int32Array.from({length:r},(l,h)=>t+h),size:1,weights:new Float32Array(r).fill(1)};let i=n/r,s=Math.max(1,i),o=2*s,a=Math.min(e,Math.ceil(2*o)+2),u=new Int32Array(r),c=new Float32Array(r*a);for(let l=0;l<r;l++){let h=t+(l+0.5)*i,f=Math.floor(h-o-0.5),d=Math.max(0,Math.min(e-a,f));u[l]=d;let g=0;for(let m=f;m<=Math.ceil(h+o-0.5);m++){let b=K0((m+0.5-h)/s),p=l*a+Math.min(e-1,Math.max(0,m))-d;c[p]=(c[p]??0)+b,g+=b}for(let m=l*a;m<(l+1)*a;m++)c[m]=(c[m]??0)/g}return{first:u,size:a,weights:c}}function yf(e,t,n,r,i,s){let o=au(e,t.y,t.h,r),a=n*i,u=new Float32Array(a*r),c=new Map;for(let l=0;l<r;l++){let h=o.first[l]??0;for(let d of c.keys())if(d<h)c.delete(d);let f=l*a;for(let d=0;d<o.size;d++){let g=o.weights[l*o.size+d]??0;if(g===0)continue;let m=c.get(h+d);if(!m)m=new Float32Array(a),s(h+d,m),c.set(h+d,m);for(let b=0;b<a;b++)u[f+b]=(u[f+b]??0)+(m[b]??0)*g}}return u}function q0(e,t,n,r){let i=au(e.width,t.x,t.w,n),s=e.data,o=yf(e.height,t,n,r,4,(u,c)=>{let l=u*e.width;for(let h=0;h<n;h++){let f=l+(i.first[h]??0),d=h*i.size,g=0,m=0,b=0,p=0;for(let E=0;E<i.size;E++){let v=(f+E)*4,S=(i.weights[d+E]??0)*(s[v+3]??0);g+=(s[v]??0)*S,m+=(s[v+1]??0)*S,b+=(s[v+2]??0)*S,p+=S}c[h*4]=g,c[h*4+1]=m,c[h*4+2]=b,c[h*4+3]=p}}),a=new Uint8Array(n*r*4);for(let u=0;u<n*r;u++){let c=o[u*4+3]??0;if(c<=0)continue;for(let l=0;l<3;l++)a[u*4+l]=Math.min(255,Math.max(0,Math.round((o[u*4+l]??0)/c)));a[u*4+3]=Math.min(255,Math.round(c))}return{width:n,height:r,data:a}}function Ef(e,t,n,r){let i=au(e.width,t.x,t.w,n),s=e.data,o=yf(e.height,t,n,r,1,(a,u)=>{let c=a*e.width;for(let l=0;l<n;l++){let h=c+(i.first[l]??0),f=l*i.size,d=0;for(let g=0;g<i.size;g++)d+=(s[h+g]??0)*(i.weights[f+g]??0);u[l]=d}});return{width:n,height:r,data:o}}function Ds(e,t){if(t<=0)return e;let n=Math.max(1,Math.ceil(t*3)),r=Array.from({length:2*n+1},(l,h)=>Math.exp(-((h-n)**2)/(2*t*t))),i=r.reduce((l,h)=>l+h,0),{width:s,height:o,data:a}=e,u=new Float32Array(s*o);for(let l=0;l<o;l++){let h=l*s;for(let f=0;f<s;f++){let d=0;for(let g=-n;g<=n;g++)d+=(a[h+Math.min(s-1,Math.max(0,f+g))]??0)*(r[g+n]??0);u[h+f]=d/i}}let c=new Float32Array(s*o);for(let l=0;l<o;l++){let h=l*s;for(let f=-n;f<=n;f++){let d=(r[f+n]??0)/i,g=Math.min(o-1,Math.max(0,l+f))*s;for(let m=0;m<s;m++)c[h+m]=(c[h+m]??0)+(u[g+m]??0)*d}}return{width:s,height:o,data:c}}function Mi(e){let t=new Uint8Array(e.data.length);for(let n=0;n<t.length;n++)t[n]=Math.min(255,Math.max(0,Math.round(e.data[n]??0)));return{width:e.width,height:e.height,data:t}}function Si(e){let t=new Uint8Array(e.width*e.height);for(let n=0;n<t.length;n++)t[n]=e.data[n*4+3]??0;return{width:e.width,height:e.height,data:t}}var Q0=Array.from({length:256},(e,t)=>{let n=t;for(let r=0;r<8;r++)n=n&1?3988292384^n>>>1:n>>>1;return n>>>0});function Y0(e){let t=4294967295;for(let n of e)t=(Q0[(t^n)&255]??0)^t>>>8;return(t^4294967295)>>>0}function Ei(e,t){let n=Buffer.alloc(12+t.length);return n.writeUInt32BE(t.length,0),n.write(e,4,"latin1"),n.set(t,8),n.writeUInt32BE(Y0(n.subarray(4,8+t.length)),8+t.length),n}function Z0(e,t,n){let r=t+1,i=new Uint8Array(n*r);for(let s=0;s<n;s++){let o=s*r,a=s*t,u=a-t;i[o]=4;for(let c=0;c<t;c++){let l=c>0?e[a+c-1]??0:0,h=s>0?e[u+c]??0:0,f=c>0&&s>0?e[u+c-1]??0:0,d=Math.abs(h-f),g=Math.abs(l-f),m=Math.abs(l+h-2*f);i[o+1+c]=(e[a+c]??0)-(d<=g&&d<=m?l:g<=m?h:f)&255}}return i}function vf(e,t,n){let r=Buffer.alloc(13);return r.writeUInt32BE(e.width,0),r.writeUInt32BE(e.height,4),r[8]=8,r[9]=t,Buffer.concat([Buffer.from(vi),Ei("IHDR",r),...n,Ei("IDAT",J0(Z0(e.data,e.width,e.height))),Ei("IEND",new Uint8Array)])}function Mf(e){let[t,n,r]=Qe(e),i=new Uint8Array(768);for(let s=0;s<256;s++)i.set([t,n,r],s*3);return Ei("PLTE",i)}function Ii(e,t){return vf(e,bf,[Mf(t),Ei("tRNS",Uint8Array.from({length:256},(n,r)=>r))])}function uu(e){return vf(e,0,[])}function Sf(e,t){if(!Fr(e)||e[25]!==bf)return;let n=Buffer.from(e.buffer,e.byteOffset,e.byteLength),r=[Buffer.from(vi)],i=vi.length;while(i+8<=n.length){let s=i+12+n.readUInt32BE(i);r.push(n.toString("latin1",i+4,i+8)==="PLTE"?Mf(t):n.subarray(i,s)),i=s}return Buffer.concat(r)}import{readdirSync as C$,readFileSync as id}from"node:fs";import{basename as j$,join as sd}from"node:path";/*!
71
+ `}}}}).prompt();function Nu(e){let t=e.replace("#","");return[t.slice(0,2),t.slice(2,4),t.slice(4,6)].map((n)=>Number.parseInt(n,16)).join(";")}function Yt(e){return`\x1B[38;2;${Nu(e)}m`}function Po(e,t){return`\x1B[48;2;${Nu(e)};38;2;${Nu(t)}m`}function Yh(e,t="\x1B[39m"){return`${e.map((n)=>`${Yt(n)}■`).join(" ")}${t}`}var Ji="⧉";function Fo(e,t){return t?`\x1B]8;;${t}\x1B\\${e}\x1B]8;;\x1B\\`:e}function L0(e,t){if(e[t]!=="\x1B")return 0;if(e[t+1]==="]"){let r=e.indexOf("\x07",t+2),i=e.indexOf("\x1B\\",t+2),s=r!==-1&&(i===-1||r<i)?r+1:i!==-1?i+2:0;return s?s-t:0}if(e[t+1]!=="[")return 0;let n=t+2;while(n<e.length&&!/[@-~]/.test(e[n]))n++;return n<e.length?n-t+1:0}function Qh(e,t){let n="",r=0,i=0;while(i<e.length){let s=L0(e,i);if(s>0){n+=e.slice(i,i+s),i+=s;continue}let o=String.fromCodePoint(e.codePointAt(i)),a=we(o);if(r+a>t)break;n+=o,r+=a,i+=o.length}return{head:n,used:r}}function De(e,t,n=!0){if(t<=0)return"";let r=we(e);if(r<=t)return n?e+" ".repeat(t-r):e;let{head:i,used:s}=Qh(e,t-1);return`${i}${e.includes("\x1B")?"\x1B[0m":""}…${n?" ".repeat(t-1-s):""}`}function cn(e,t,n){let r=n-we(t)-1;return r<=0?De(e,n):`${De(e,r)} ${t}`}function Qe(e,t){let n=[],r="";for(let i of e.split(/\s+/).filter(Boolean)){let s=r?`${r} ${i}`:i;if(we(s)<=t){r=s;continue}if(r)n.push(r);while(we(i)>t){let{head:o}=Qh(i,t),a=Math.max(o.lastIndexOf("/")+1,o.lastIndexOf("#")),u=a>0?a:o.length;n.push(i.slice(0,u)),i=i.slice(u)}r=i}if(r)n.push(r);return n}import{existsSync as Wg,readFileSync as Tc}from"node:fs";import{join as Kg}from"node:path";var x0=/^#[0-9a-f]{6}$/;function Pn(e){return x0.test(e)}function Ue(e){let t=Number.parseInt(e.slice(1),16);return[t>>16&255,t>>8&255,t&255]}function ot(e,t,n){let r=Ue(e),i=Ue(t);return`#${r.map((s,o)=>Math.round(s+((i[o]??0)-s)*n).toString(16).padStart(2,"0")).join("")}`}function ze(e){let[t,n,r]=Ue(e).map((i)=>{let s=i/255;return s<=0.03928?s/12.92:((s+0.055)/1.055)**2.4});return 0.2126*t+0.7152*n+0.0722*r}function Ke(e,t){let n=ze(e),r=ze(t);return(Math.max(n,r)+0.05)/(Math.min(n,r)+0.05)}function Ro(e,t){return Math.round(Ke(e,t)*100)/100}function C0(e){let t=e/255;return t<=0.04045?t/12.92:((t+0.055)/1.055)**2.4}function Je(e){let[t,n,r]=Ue(e).map(C0),i=Math.cbrt(0.4122214708*t+0.5363325363*n+0.0514459929*r),s=Math.cbrt(0.2119034982*t+0.6806995451*n+0.1073969566*r),o=Math.cbrt(0.0883024619*t+0.2817188376*n+0.6299787005*r),a=1.9779984951*i-2.428592205*s+0.4505937099*o,u=0.0259040371*i+0.7827717662*s-0.808675766*o;return{l:0.2104542553*i+0.793617785*s-0.0040720468*o,c:Math.hypot(a,u),h:(Math.atan2(u,a)*180/Math.PI+360)%360}}var Fn=7,Zh=3,Pu=0.15,Vh=1.6,Ru=[1,2,3,4,5,6,9,10,11,12,13,14],Xh=[7,15],Rn=[1,2,3,4,5,6],hn={1:{name:"red",center:19,width:25},2:{name:"green",center:132,width:35},3:{name:"yellow",center:88,width:35},4:{name:"blue",center:250,width:60},5:{name:"magenta",center:329,width:40},6:{name:"cyan",center:197,width:60}},qi=0.03,Gt=25,Ur=15,jr=0.08;function ln(e,t){let n=e.ansi[t];if(n===void 0)throw Error(`${e.name}: missing ANSI ${t}`);return n}function Fu(e,t,n){let r=e.background;return t.flatMap((i)=>{let s=ln(e,i);return Ke(s,r)<n?[`ANSI ${i} ${s} on ${r} is ${Ro(s,r)}:1, needs ${n}:1`]:[]})}function Dh(e,t){return Math.min(...t.map((n)=>Ke(ln(e,n),e.background)))}var ef=[{rule:"foreground",label:"foreground on background",unit:"ratio",min:Fn,measure:({foreground:e,background:t})=>Ke(e,t),check:({foreground:e,background:t})=>Ke(e,t)<Fn?[`foreground ${e} on ${t} is ${Ro(e,t)}:1, needs ${Fn}:1`]:[]},{rule:"accents",label:"weakest accent on background",unit:"ratio",min:Zh,measure:(e)=>Dh(e,Ru),check:(e)=>Fu(e,Ru,Zh)},{rule:"ansi0-dark",label:"ansi0 luminance",unit:"luminance",max:Pu,measure:(e)=>ze(ln(e,0)),check:(e)=>{let t=ln(e,0);return ze(t)>Pu?[`ANSI 0 ${t} has luminance ${ze(t).toFixed(3)}, needs <= ${Pu}`]:[]}},{rule:"light-ansi",label:"ansi7 and ansi15 on background",unit:"ratio",min:Fn,measure:(e)=>Dh(e,Xh),check:(e)=>Fu(e,Xh,Fn)},{rule:"ansi8-visible",label:"ansi8 on background",unit:"ratio",min:Vh,measure:(e)=>Ke(ln(e,8),e.background),check:(e)=>Fu(e,[8],Vh)},{rule:"selection",label:"foreground on selection",unit:"ratio",min:Fn,measure:({foreground:e,selectionBackground:t})=>t===void 0?Number.NaN:Ke(e,t),check:({foreground:e,selectionBackground:t})=>t!==void 0&&Ke(e,t)<Fn?[`foreground ${e} on selection ${t} is ${Ro(e,t)}:1, needs ${Fn}:1`]:[]}];function Qt(e,t){let n=Math.abs(e-t)%360;return Math.min(n,360-n)}var On=(e)=>e>8?e-8:e;function Wr(e){let t=e.signatureSlots.filter((n)=>n.startsWith("ansi")).map((n)=>Number(n.slice(4)));return new Set(t.flatMap((n)=>Rn.includes(On(n))?[n,n>8?n-8:n+8]:[n]))}function Bi(e,t){let n=Je(ln(e,t));return n.c<qi?void 0:n}function Gr(e){let t=Wr(e);return Ru.flatMap((n)=>{let r=Bi(e,n),i=hn[On(n)];if(r===void 0||i===void 0||t.has(n))return[];let s=Qt(r.h,i.center)-i.width;return s>0?[{slot:n,hue:r.h,over:s}]:[]})}function sr(e){let t=new Set(e.signatureSlots);return Rn.flatMap((n)=>{let r=Bi(e,n),i=Bi(e,n+8);if(r===void 0||i===void 0||t.has(`ansi${n}`)&&t.has(`ansi${n+8}`))return[];return[{normal:n,gap:Qt(r.h,i.h)}]})}function or(e){let t=Wr(e);return[0,8].flatMap((n)=>Rn.flatMap((r)=>Rn.filter((i)=>i>r).flatMap((i)=>{let[s,o]=[n+r,n+i],a=Bi(e,s),u=Bi(e,o);if(a===void 0||u===void 0||t.has(s)&&t.has(o))return[];return Qt(a.h,u.h)<Ur&&Math.abs(a.l-u.l)<jr?[[s,o]]:[]})))}var _0=[{rule:"ansi-role",label:"accent hue outside its ANSI role",unit:"degrees",max:0,measure:(e)=>Math.max(0,...Gr(e).map((t)=>t.over)),check:(e)=>Gr(e).map(({slot:t,hue:n,over:r})=>{let i=hn[On(t)];return`ANSI ${t} ${ln(e,t)} has hue ${n.toFixed(0)}°, ${r.toFixed(0)}° outside ${i.name} (${i.center}±${i.width}°)`})},{rule:"bright-follows",label:"widest normal to bright hue gap",unit:"degrees",max:Gt,measure:(e)=>Math.max(0,...sr(e).map((t)=>t.gap)),check:(e)=>sr(e).filter((t)=>t.gap>Gt).map(({normal:t,gap:n})=>`ANSI ${t+8} is ${n.toFixed(0)}° from ANSI ${t}, needs <= ${Gt}°`)},{rule:"distinct",label:"accent pairs that read as one color",unit:"pairs",max:0,measure:(e)=>or(e).length,check:(e)=>or(e).map(([t,n])=>`ANSI ${t} ${ln(e,t)} and ANSI ${n} ${ln(e,n)} are within ${Ur}° hue and ${jr} lightness`)}],Oo=[...ef,..._0],Ou=Oo.map((e)=>e.rule),gt=Oo.map(({rule:e,label:t,unit:n,min:r,max:i})=>({rule:e,label:t,unit:n,...r===void 0?{}:{min:r},...i===void 0?{}:{max:i}}));function Tn(e){return Oo.map((t)=>Math.round(t.measure(e)*1000)/1000)}function tf(e,t){return e.filter((n)=>!t.waive.includes(n.rule)).flatMap((n)=>n.check(t).map((r)=>({theme:t.name,rule:n.rule,detail:r})))}function ar(e){return tf(Oo,e)}function nf(e){return tf(ef,e)}function rf(e){return e.flatMap(ar)}import{chmodSync as G0,copyFileSync as U0,existsSync as Kr,mkdirSync as j0,readFileSync as Tu,realpathSync as W0,renameSync as K0,rmSync as sf,statSync as J0,writeFileSync as B0}from"node:fs";import{dirname as q0}from"node:path";function of(e){return`${e}.ttheme.bak`}var z0=/^(?:#|--) ttheme begin$|path = "ttheme-/m;function Hu(e){let t=of(e);if(Kr(e)&&!Kr(t)&&!z0.test(Tu(e,"utf8")))U0(e,t)}function Z(e,t){let n=Kr(e)?W0(e):e;j0(q0(n),{recursive:!0});let r=`${n}.ttheme-${process.pid}`;if(B0(r,t),Kr(n))G0(r,J0(n).mode&4095);K0(r,n)}function zi(e,t){if((Kr(e)?Tu(e,"utf8"):void 0)===t)return!1;return Hu(e),Z(e,t),!0}function af(e,t){let n=of(e),r=Kr(n)?Tu(n,"utf8"):void 0;if(t===""&&r===void 0)return sf(e,{force:!0}),"removed";if(Z(e,t),r===void 0||r===t)return sf(n,{force:!0}),"restored";return"kept backup"}import{createHash as lg}from"node:crypto";import{copyFileSync as Iy,existsSync as pc,mkdirSync as Ny,readdirSync as Py,readFileSync as ea,renameSync as hg,rmSync as ti}from"node:fs";import{basename as fg,isAbsolute as Fy,join as X}from"node:path";var ud=ko(gf(),1),Ho=ko(od(),1);import{deflateSync as fk}from"node:zlib";var Zi=[137,80,78,71,13,10,26,10],cd=13,ld=3;function zr(e){return e.length>=Zi.length&&Zi.every((t,n)=>e[n]===t)}function cr(e){let t=Ho.PNG.sync.read(Buffer.from(e));return{width:t.width,height:t.height,data:new Uint8Array(t.data)}}function Ln(e,t){if(zr(e)){let n=xn(e);if(n&&n.width*n.height>t)throw Error(`${n.width}×${n.height} is over ${t/1e6} megapixels`);return cr(e)}if(e[0]===255&&e[1]===216){let n=ud.decode(e,{useTArray:!0,formatAsRGBA:!0,maxResolutionInMP:t/1e6,maxMemoryUsageInMB:1024});return{width:n.width,height:n.height,data:n.data}}throw Error("not a PNG or JPEG image")}function Ao(e){let t=new Ho.PNG({width:e.width,height:e.height});return t.data=Buffer.from(e.data),Ho.PNG.sync.write(t)}function ad(e,t){for(let n=0;n+t.length<=e.length;n++){let r=!0;for(let i=0;i<t.length&&r;i++)r=e[n+i]===t.charCodeAt(i);if(r)return n}return-1}function xn(e){if(e.length<33||!zr(e))return null;let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=t.getUint32(16),r=t.getUint32(20);if(e[25]===4||e[25]===6)return{width:n,height:r,alpha:!0};let i=ad(e,"IDAT");return{width:n,height:r,alpha:ad(i===-1?e:e.subarray(0,i),"tRNS")!==-1}}function hd(e,t=cd){let{width:n,height:r}=e,i=-1,s=-1;for(let o=0;o<e.height;o++)for(let a=0;a<e.width;a++)if((e.data[(o*e.width+a)*4+3]??0)>=t)n=Math.min(n,a),i=Math.max(i,a),r=Math.min(r,o),s=Math.max(s,o);return i<0?null:{x:n,y:r,w:i-n+1,h:s-r+1}}function fn(e,t={x:0,y:0,w:e.width,h:e.height}){let n=0;for(let r=t.y;r<t.y+t.h;r++)for(let i=t.x;i<t.x+t.w;i++)if((e.data[(r*e.width+i)*4+3]??0)<cd)n++;return Math.round(n*100/(t.w*t.h))}function fd(e,t,n){let r=Math.min(t/e.width,n/e.height),i=Math.max(1,Math.round(e.width*r)),s=Math.max(1,Math.round(e.height*r)),o=gk(e,{x:0,y:0,w:e.width,h:e.height},i,s),a=new Uint8Array(t*n*4),u=Math.floor((t-i)/2),c=Math.floor((n-s)/2);for(let l=0;l<s;l++)a.set(o.data.subarray(l*i*4,(l+1)*i*4),((c+l)*t+u)*4);return{width:t,height:n,data:a}}function dk(e){let t=Math.abs(e);if(t<1)return(7*t*t*t-12*t*t+5.333333333333333)/6;if(t<2)return(-2.3333333333333335*t*t*t+12*t*t-20*t+10.666666666666666)/6;return 0}function Qu(e,t,n,r){if(n===r&&Number.isInteger(t)&&t>=0&&t+r<=e)return{first:Int32Array.from({length:r},(l,h)=>t+h),size:1,weights:new Float32Array(r).fill(1)};let i=n/r,s=Math.max(1,i),o=2*s,a=Math.min(e,Math.ceil(2*o)+2),u=new Int32Array(r),c=new Float32Array(r*a);for(let l=0;l<r;l++){let h=t+(l+0.5)*i,f=Math.floor(h-o-0.5),d=Math.max(0,Math.min(e-a,f));u[l]=d;let g=0;for(let p=f;p<=Math.ceil(h+o-0.5);p++){let b=dk((p+0.5-h)/s),m=l*a+Math.min(e-1,Math.max(0,p))-d;c[m]=(c[m]??0)+b,g+=b}for(let p=l*a;p<(l+1)*a;p++)c[p]=(c[p]??0)/g}return{first:u,size:a,weights:c}}function dd(e,t,n,r,i,s){let o=Qu(e,t.y,t.h,r),a=n*i,u=new Float32Array(a*r),c=new Map;for(let l=0;l<r;l++){let h=o.first[l]??0;for(let d of c.keys())if(d<h)c.delete(d);let f=l*a;for(let d=0;d<o.size;d++){let g=o.weights[l*o.size+d]??0;if(g===0)continue;let p=c.get(h+d);if(!p)p=new Float32Array(a),s(h+d,p),c.set(h+d,p);for(let b=0;b<a;b++)u[f+b]=(u[f+b]??0)+(p[b]??0)*g}}return u}function gk(e,t,n,r){let i=Qu(e.width,t.x,t.w,n),s=e.data,o=dd(e.height,t,n,r,4,(u,c)=>{let l=u*e.width;for(let h=0;h<n;h++){let f=l+(i.first[h]??0),d=h*i.size,g=0,p=0,b=0,m=0;for(let $=0;$<i.size;$++){let k=(f+$)*4,S=(i.weights[d+$]??0)*(s[k+3]??0);g+=(s[k]??0)*S,p+=(s[k+1]??0)*S,b+=(s[k+2]??0)*S,m+=S}c[h*4]=g,c[h*4+1]=p,c[h*4+2]=b,c[h*4+3]=m}}),a=new Uint8Array(n*r*4);for(let u=0;u<n*r;u++){let c=o[u*4+3]??0;if(c<=0)continue;for(let l=0;l<3;l++)a[u*4+l]=Math.min(255,Math.max(0,Math.round((o[u*4+l]??0)/c)));a[u*4+3]=Math.min(255,Math.round(c))}return{width:n,height:r,data:a}}function gd(e,t,n,r){let i=Qu(e.width,t.x,t.w,n),s=e.data,o=dd(e.height,t,n,r,1,(a,u)=>{let c=a*e.width;for(let l=0;l<n;l++){let h=c+(i.first[l]??0),f=l*i.size,d=0;for(let g=0;g<i.size;g++)d+=(s[h+g]??0)*(i.weights[f+g]??0);u[l]=d}});return{width:n,height:r,data:o}}function Lo(e,t){if(t<=0)return e;let n=Math.max(1,Math.ceil(t*3)),r=Array.from({length:2*n+1},(l,h)=>Math.exp(-((h-n)**2)/(2*t*t))),i=r.reduce((l,h)=>l+h,0),{width:s,height:o,data:a}=e,u=new Float32Array(s*o);for(let l=0;l<o;l++){let h=l*s;for(let f=0;f<s;f++){let d=0;for(let g=-n;g<=n;g++)d+=(a[h+Math.min(s-1,Math.max(0,f+g))]??0)*(r[g+n]??0);u[h+f]=d/i}}let c=new Float32Array(s*o);for(let l=0;l<o;l++){let h=l*s;for(let f=-n;f<=n;f++){let d=(r[f+n]??0)/i,g=Math.min(o-1,Math.max(0,l+f))*s;for(let p=0;p<s;p++)c[h+p]=(c[h+p]??0)+(u[g+p]??0)*d}}return{width:s,height:o,data:c}}function Vi(e){let t=new Uint8Array(e.data.length);for(let n=0;n<t.length;n++)t[n]=Math.min(255,Math.max(0,Math.round(e.data[n]??0)));return{width:e.width,height:e.height,data:t}}function Xi(e){let t=new Uint8Array(e.width*e.height);for(let n=0;n<t.length;n++)t[n]=e.data[n*4+3]??0;return{width:e.width,height:e.height,data:t}}var mk=Array.from({length:256},(e,t)=>{let n=t;for(let r=0;r<8;r++)n=n&1?3988292384^n>>>1:n>>>1;return n>>>0});function pk(e){let t=4294967295;for(let n of e)t=(mk[(t^n)&255]??0)^t>>>8;return(t^4294967295)>>>0}function Qi(e,t){let n=Buffer.alloc(12+t.length);return n.writeUInt32BE(t.length,0),n.write(e,4,"latin1"),n.set(t,8),n.writeUInt32BE(pk(n.subarray(4,8+t.length)),8+t.length),n}function bk(e,t,n){let r=t+1,i=new Uint8Array(n*r);for(let s=0;s<n;s++){let o=s*r,a=s*t,u=a-t;i[o]=4;for(let c=0;c<t;c++){let l=c>0?e[a+c-1]??0:0,h=s>0?e[u+c]??0:0,f=c>0&&s>0?e[u+c-1]??0:0,d=Math.abs(h-f),g=Math.abs(l-f),p=Math.abs(l+h-2*f);i[o+1+c]=(e[a+c]??0)-(d<=g&&d<=p?l:g<=p?h:f)&255}}return i}function md(e,t,n){let r=Buffer.alloc(13);return r.writeUInt32BE(e.width,0),r.writeUInt32BE(e.height,4),r[8]=8,r[9]=t,Buffer.concat([Buffer.from(Zi),Qi("IHDR",r),...n,Qi("IDAT",fk(bk(e.data,e.width,e.height))),Qi("IEND",new Uint8Array)])}function pd(e){let[t,n,r]=Ue(e),i=new Uint8Array(768);for(let s=0;s<256;s++)i.set([t,n,r],s*3);return Qi("PLTE",i)}function Di(e,t){return md(e,ld,[pd(t),Qi("tRNS",Uint8Array.from({length:256},(n,r)=>r))])}function Zu(e){return md(e,0,[])}function bd(e,t){if(!zr(e)||e[25]!==ld)return;let n=Buffer.from(e.buffer,e.byteOffset,e.byteLength),r=[Buffer.from(Zi)],i=Zi.length;while(i+8<=n.length){let s=i+12+n.readUInt32BE(i);r.push(n.toString("latin1",i+4,i+8)==="PLTE"?pd(t):n.subarray(i,s)),i=s}return Buffer.concat(r)}import{readdirSync as gy,readFileSync as Xd}from"node:fs";import{basename as my,join as Dd}from"node:path";/*!
72
72
  * Copyright (c) Squirrel Chat et al., All rights reserved.
73
73
  * SPDX-License-Identifier: BSD-3-Clause
74
74
  *
@@ -94,11 +94,11 @@ ${a}
94
94
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
95
95
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
96
96
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
97
- */function z0(e,t){let n=e.slice(0,t).split(/\r?\n/);return[n.length,n.pop().length+1]}function B0(e,t,n){let r=e.split(/\r?\n/),i="",s=(Math.log10(t+1)|0)+1;for(let o=t-1;o<=t+1;o++){let a=r[o-1];if(!a)continue;if(i+=o.toString().padEnd(s," "),i+=": ",i+=a,i+=`
97
+ */function wk(e,t){let n=e.slice(0,t).split(/\r?\n/);return[n.length,n.pop().length+1]}function $k(e,t,n){let r=e.split(/\r?\n/),i="",s=(Math.log10(t+1)|0)+1;for(let o=t-1;o<=t+1;o++){let a=r[o-1];if(!a)continue;if(i+=o.toString().padEnd(s," "),i+=": ",i+=a,i+=`
98
98
  `,o===t)i+=" ".repeat(s+n+2),i+=`^
99
- `}return i}class J extends Error{line;column;codeblock;constructor(e,t){let[n,r]=z0(t.toml,t.ptr),i=B0(t.toml,n,r);super(`Invalid TOML document: ${e}
99
+ `}return i}class W extends Error{line;column;codeblock;constructor(e,t){let[n,r]=wk(t.toml,t.ptr),i=$k(t.toml,n,r);super(`Invalid TOML document: ${e}
100
100
 
101
- ${i}`,t);this.line=n,this.column=r,this.codeblock=i}static x(e,t,n){throw new J(e,{toml:t.s,ptr:n??t.p})}}/*!
101
+ ${i}`,t);this.line=n,this.column=r,this.codeblock=i}static x(e,t,n){throw new W(e,{toml:t.s,ptr:n??t.p})}}/*!
102
102
  * Copyright (c) Squirrel Chat et al., All rights reserved.
103
103
  * SPDX-License-Identifier: BSD-3-Clause
104
104
  *
@@ -124,8 +124,8 @@ ${i}`,t);this.line=n,this.column=r,this.codeblock=i}static x(e,t,n){throw new J(
124
124
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
125
125
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
126
126
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
127
- */function eo(e){let t=e.p,n=e.s.charCodeAt(e.p++),r=n,i=n===39,s=n===e.s.charCodeAt(e.p)&&n===e.s.charCodeAt(e.p+1);if(s){if((n=e.s.charCodeAt(e.p+=2))===10)e.p++;else if(n===13&&e.s.charCodeAt(e.p+1)===10)e.p+=2}let o="",a=e.p,u=0;for(;e.p<e.s.length;e.p++)if(n=e.s.charCodeAt(e.p),s&&(n===10||n===13&&e.s.charCodeAt(e.p+1)===10))u=u&&3;else if(n<32&&n!==9||n===127)J.x("control characters are not allowed in strings",e);else if((!u||u===3)&&n===r&&(!s||e.s.charCodeAt(e.p+1)===r&&e.s.charCodeAt(e.p+2)===r)){if(s){if(e.s.charCodeAt(e.p+3)===r)e.p++;if(e.s.charCodeAt(e.p+3)===r)e.p++}if(!u){let c=e.s.slice(a,e.p);o=o?o+c:c}return e.p+=s?3:1,o}else if(!u){if(!i&&n===92)o+=e.s.slice(a,a=e.p),u=1}else if(u===1)if(n===120||n===117||n===85){let c=e.p++-1,l=0,h=n===120?2:n===117?4:8;for(let f=0;f<h;f++,e.p++){let d=e.s.charCodeAt(e.p),g=d>=48&&d<=57?d-48:d>=65&&d<=70?d-65+10:d>=97&&d<=102?d-97+10:-1;if(g<0)J.x("invalid non-hex character in unicode escape",e);l=l<<4|g}if(l<0||l>1114111||l>=55296&&l<=57343)J.x("invalid unicode escape",e,c);o+=String.fromCodePoint(l),a=e.p--,u=0}else if(s&&(n===32||n===9))u=2;else{if(n===98)o+="\b";else if(n===116)o+="\t";else if(n===110)o+=`
128
- `;else if(n===102)o+="\f";else if(n===114)o+="\r";else if(n===101)o+="\x1B";else if(n===34)o+='"';else if(n===92)o+="\\";else J.x("unrecognised escape sequence",e);a=e.p+1,u=0}else if(n!==32&&n!==9){if(u===2)J.x("invalid escape: only line-ending whitespace may be escaped",e,a);u=!i&&n===92?1:0,a=e.p}J.x("unfinished string",e,t)}/*!
127
+ */function xo(e){let t=e.p,n=e.s.charCodeAt(e.p++),r=n,i=n===39,s=n===e.s.charCodeAt(e.p)&&n===e.s.charCodeAt(e.p+1);if(s){if((n=e.s.charCodeAt(e.p+=2))===10)e.p++;else if(n===13&&e.s.charCodeAt(e.p+1)===10)e.p+=2}let o="",a=e.p,u=0;for(;e.p<e.s.length;e.p++)if(n=e.s.charCodeAt(e.p),s&&(n===10||n===13&&e.s.charCodeAt(e.p+1)===10))u=u&&3;else if(n<32&&n!==9||n===127)W.x("control characters are not allowed in strings",e);else if((!u||u===3)&&n===r&&(!s||e.s.charCodeAt(e.p+1)===r&&e.s.charCodeAt(e.p+2)===r)){if(s){if(e.s.charCodeAt(e.p+3)===r)e.p++;if(e.s.charCodeAt(e.p+3)===r)e.p++}if(!u){let c=e.s.slice(a,e.p);o=o?o+c:c}return e.p+=s?3:1,o}else if(!u){if(!i&&n===92)o+=e.s.slice(a,a=e.p),u=1}else if(u===1)if(n===120||n===117||n===85){let c=e.p++-1,l=0,h=n===120?2:n===117?4:8;for(let f=0;f<h;f++,e.p++){let d=e.s.charCodeAt(e.p),g=d>=48&&d<=57?d-48:d>=65&&d<=70?d-65+10:d>=97&&d<=102?d-97+10:-1;if(g<0)W.x("invalid non-hex character in unicode escape",e);l=l<<4|g}if(l<0||l>1114111||l>=55296&&l<=57343)W.x("invalid unicode escape",e,c);o+=String.fromCodePoint(l),a=e.p--,u=0}else if(s&&(n===32||n===9))u=2;else{if(n===98)o+="\b";else if(n===116)o+="\t";else if(n===110)o+=`
128
+ `;else if(n===102)o+="\f";else if(n===114)o+="\r";else if(n===101)o+="\x1B";else if(n===34)o+='"';else if(n===92)o+="\\";else W.x("unrecognised escape sequence",e);a=e.p+1,u=0}else if(n!==32&&n!==9){if(u===2)W.x("invalid escape: only line-ending whitespace may be escaped",e,a);u=!i&&n===92?1:0,a=e.p}W.x("unfinished string",e,t)}/*!
129
129
  * Copyright (c) Squirrel Chat et al., All rights reserved.
130
130
  * SPDX-License-Identifier: BSD-3-Clause
131
131
  *
@@ -151,7 +151,7 @@ ${i}`,t);this.line=n,this.column=r,this.codeblock=i}static x(e,t,n){throw new J(
151
151
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
152
152
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
153
153
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
154
- */var V0=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i;class En extends Date{#t=!1;#n=!1;#e=null;constructor(e,t,n){let r=!0,i=!0,s="Z",o;if(typeof e==="string")if(t)e:{if(t<3){if(+e.slice(11,13)>23){e="";break e}if(t===2)s=null,e+="Z";else if((o=e.charCodeAt(e.length-1))!==90&&o!==122)s=e.slice(e.length-6);if(n)e=e.slice(0,10)+"T"+e.slice(11)}else if(t===4)e=+e.slice(0,2)>23?"":`0000-01-01T${e}Z`;r=t!==4,i=t!==3}else{let a=e.match(V0);if(a){if(!a[1])r=!1,e=`0000-01-01T${e}`;if(i=!!a[2],i&&e[10]===" "&&(e=e.replace(" ","T")),a[2]&&+a[2]>23)e="";else if(s=a[3]||null,!s&&i)e+="Z"}else e=""}super(e);if(!isNaN(this.getTime()))this.#t=r,this.#n=i,this.#e=s}isDateTime(){return this.#t&&this.#n}isLocal(){return!this.#t||!this.#n||!this.#e}isDate(){return this.#t&&!this.#n}isTime(){return this.#n&&!this.#t}isValid(){return this.#t||this.#n}toISOString(){let e=super.toISOString();if(this.isDate())return e.slice(0,10);if(this.isTime())return e.slice(11,23);if(this.#e===null)return e.slice(0,-1);if(this.#e==="Z"||this.#e==="z")return e;let t=+this.#e.slice(1,3)*60+ +this.#e.slice(4,6);return t=this.#e[0]==="-"?t:-t,new Date(this.getTime()-t*60000).toISOString().slice(0,-1)+this.#e}static wrapAsOffsetDateTime(e,t="Z"){let n=new En(e);return n.#e=t,n}static wrapAsLocalDateTime(e){let t=new En(e);return t.#e=null,t}static wrapAsLocalDate(e){let t=new En(e);return t.#n=!1,t.#e=null,t}static wrapAsLocalTime(e){let t=new En(e);return t.#t=!1,t.#e=null,t}}/*!
154
+ */var kk=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i;class Cn extends Date{#t=!1;#n=!1;#e=null;constructor(e,t,n){let r=!0,i=!0,s="Z",o;if(typeof e==="string")if(t)e:{if(t<3){if(+e.slice(11,13)>23){e="";break e}if(t===2)s=null,e+="Z";else if((o=e.charCodeAt(e.length-1))!==90&&o!==122)s=e.slice(e.length-6);if(n)e=e.slice(0,10)+"T"+e.slice(11)}else if(t===4)e=+e.slice(0,2)>23?"":`0000-01-01T${e}Z`;r=t!==4,i=t!==3}else{let a=e.match(kk);if(a){if(!a[1])r=!1,e=`0000-01-01T${e}`;if(i=!!a[2],i&&e[10]===" "&&(e=e.replace(" ","T")),a[2]&&+a[2]>23)e="";else if(s=a[3]||null,!s&&i)e+="Z"}else e=""}super(e);if(!isNaN(this.getTime()))this.#t=r,this.#n=i,this.#e=s}isDateTime(){return this.#t&&this.#n}isLocal(){return!this.#t||!this.#n||!this.#e}isDate(){return this.#t&&!this.#n}isTime(){return this.#n&&!this.#t}isValid(){return this.#t||this.#n}toISOString(){let e=super.toISOString();if(this.isDate())return e.slice(0,10);if(this.isTime())return e.slice(11,23);if(this.#e===null)return e.slice(0,-1);if(this.#e==="Z"||this.#e==="z")return e;let t=+this.#e.slice(1,3)*60+ +this.#e.slice(4,6);return t=this.#e[0]==="-"?t:-t,new Date(this.getTime()-t*60000).toISOString().slice(0,-1)+this.#e}static wrapAsOffsetDateTime(e,t="Z"){let n=new Cn(e);return n.#e=t,n}static wrapAsLocalDateTime(e){let t=new Cn(e);return t.#e=null,t}static wrapAsLocalDate(e){let t=new Cn(e);return t.#n=!1,t.#e=null,t}static wrapAsLocalTime(e){let t=new Cn(e);return t.#t=!1,t.#e=null,t}}/*!
155
155
  * Copyright (c) Squirrel Chat et al., All rights reserved.
156
156
  * SPDX-License-Identifier: BSD-3-Clause
157
157
  *
@@ -177,7 +177,7 @@ ${i}`,t);this.line=n,this.column=r,this.codeblock=i}static x(e,t,n){throw new J(
177
177
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
178
178
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
179
179
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
180
- */function lt(e,t=10){return t===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48+t}function lu(e,t){return e===32||e===9||e===10||e===13||t&&(e===t||e===44)||e===35}function Ri(e,t){let n=e.p,r=e.s.charCodeAt(e.p);if(r===91||r===123){e.d--||J.x("document contains excessively nested structures. aborting.",e);let i=r===91?Rf(e):Nf(e);return e.d++,i}if(r===34||r===39)return eo(e);if(r===116){if(e.s.charCodeAt(++e.p)!==114||e.s.charCodeAt(++e.p)!==117||e.s.charCodeAt(++e.p)!==101)J.x("invalid value",e,n);return e.p++,!0}if(r===102){if(e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==108||e.s.charCodeAt(++e.p)!==115||e.s.charCodeAt(++e.p)!==101)J.x("invalid value",e,n);return e.p++,!1}if(r===43||r===45)return to(e,e.p,e.s.charCodeAt(++e.p),44-r,t);if(e.s.charCodeAt(e.p+4)===45&&e.s.charCodeAt(e.p+7)===45)return X0(e,r,t);if(e.s.charCodeAt(e.p+2)===58)return x0(e,r,t);return to(e,e.p,r,0,t)}function to(e,t,n,r,i){let s=n,o=0,a=!1;if(s===105){if(e.s.charCodeAt(++e.p)!==110||e.s.charCodeAt(++e.p)!==102)J.x("invalid value",e,t);return e.p++,(r||1)/0}if(s===110){if(e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==110)J.x("invalid value",e,t);return e.p++,NaN}if(s===48){if(++e.p>=e.s.length||lu(s=e.s.charCodeAt(e.p),i))return e.bi===!0?0n:0;if(!r){if(s===120)return cu(e,t,16,i);else if(s===98)return cu(e,t,2,i);else if(s===111)return cu(e,t,8,i)}if(s===46)o=2;else if(s===101||s===69)o=4;else J.x("illegal leading zero",e,t)}else if(!lt(s))J.x("invalid value",e,t);while(++e.p<e.s.length&&(s=e.s.charCodeAt(e.p),!lu(s,i))){if(!o)o=1;if(s===95){if(!(o&1))J.x("illegal underscore",e);o+=11,a=!0}else if(o===1&&s===46)o=2;else if((o===1||o===3)&&(s===101||s===69))o=4;else if(o===4&&(s===43||s===45));else if(!lt(s))J.x("illegal character in numeric literal",e);else if(o>9)o-=11;else if(!(o&1))o++}if(!o){let c=(n-48)*(r||1);return e.bi===!0?BigInt(c):c}if(!(o&1))J.x("unfinished numeric value",e,t);let u=e.s.slice(t,e.p);if(a)u=u.replaceAll("_","");return o>1?parseFloat(u):If(e,u,10,t)}function cu(e,t,n,r){let i,s=1;while(++e.p<e.s.length&&(i=e.s.charCodeAt(e.p),!lu(i,r)))if(i===95){if(s&1)J.x("illegal underscore",e);s=3}else if(!lt(i,n))J.x("illegal character in numeric literal",e);else if(s&1)s--;if(s&1)J.x("unfinished numeric value",e);let o=e.s.slice(t+2,e.p);if(s)o=o.replaceAll("_","");return If(e,o,n,t)}function If(e,t,n,r){if(e.bi!==!0)e:{let i=parseInt(t,n);if(!Number.isSafeInteger(i)){if(e.bi)break e;J.x("integer value cannot be represented losslessly",e,r)}return i}return n===10?BigInt(t):BigInt((n===2?"0b":n===8?"0o":"0x")+t)}function X0(e,t,n){let r=e.p++,i;if(!lt(t)||!lt(e.s.charCodeAt(e.p++))||!lt(e.s.charCodeAt(e.p++))||!lt(e.s.charCodeAt(e.p++)))return to(e,e.p=r,t,0,n);if(e.p+=5,!lt(e.s.charCodeAt(e.p++)))J.x("invalid date-time: date part is malformed",e,r);if(e.p>=e.s.length||((t=e.s.charCodeAt(e.p))!==32||(i=!0,!lt(e.s.charCodeAt(e.p+1))))&&t!==84&&t!==116){let o=e.s.slice(r,e.p);return Ni(e,o,3,!1,r)}if(e.s.charCodeAt(e.p+=3)!==58)J.x("invalid date-time: time part is malformed",e,r);if(e.s.charCodeAt(e.p+=3)===58)e.p+=3;if(e.s.charCodeAt(e.p)===46)while(lt(e.s.charCodeAt(++e.p)));if(t=e.s.charCodeAt(e.p)){if(t===90||t===122){let o=e.s.slice(r,++e.p);return Ni(e,o,1,i,r,"[+00:00]")}if(t===43||t===45){let o=e.s.slice(r,e.p+=6);return Ni(e,o,1,i,r,!e.ld&&"["+e.s.slice(e.p-6,e.p)+"]")}}let s=e.s.slice(r,e.p);return Ni(e,s,2,i,r)}function x0(e,t,n){let r=e.p;if(!lt(t)||!lt(e.s.charCodeAt(++e.p)))return to(e,--e.p,t,0,n);if(e.s.charCodeAt(e.p+=4)===58)e.p+=3;if(e.s.charCodeAt(e.p)===46)while(lt(e.s.charCodeAt(++e.p)));let i=e.s.slice(r,e.p);return Ni(e,i,4,!1,r)}function Ni(e,t,n,r,i,s){if(e.ld){let o=new En(t,n,r);if(!o.isValid())J.x("invalid date",e,i);return o}try{if(s)t+=s;switch(n){case 1:return Temporal.ZonedDateTime.from(t);case 2:return Temporal.PlainDateTime.from(t);case 3:return Temporal.PlainDate.from(t);case 4:return Temporal.PlainTime.from(t)}}catch(o){J.x(o instanceof Error?o.message:""+o,e,i)}}/*!
180
+ */function mt(e,t=10){return t===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48+t}function Xu(e,t){return e===32||e===9||e===10||e===13||t&&(e===t||e===44)||e===35}function ts(e,t){let n=e.p,r=e.s.charCodeAt(e.p);if(r===91||r===123){e.d--||W.x("document contains excessively nested structures. aborting.",e);let i=r===91?kd(e):$d(e);return e.d++,i}if(r===34||r===39)return xo(e);if(r===116){if(e.s.charCodeAt(++e.p)!==114||e.s.charCodeAt(++e.p)!==117||e.s.charCodeAt(++e.p)!==101)W.x("invalid value",e,n);return e.p++,!0}if(r===102){if(e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==108||e.s.charCodeAt(++e.p)!==115||e.s.charCodeAt(++e.p)!==101)W.x("invalid value",e,n);return e.p++,!1}if(r===43||r===45)return Co(e,e.p,e.s.charCodeAt(++e.p),44-r,t);if(e.s.charCodeAt(e.p+4)===45&&e.s.charCodeAt(e.p+7)===45)return yk(e,r,t);if(e.s.charCodeAt(e.p+2)===58)return Ek(e,r,t);return Co(e,e.p,r,0,t)}function Co(e,t,n,r,i){let s=n,o=0,a=!1;if(s===105){if(e.s.charCodeAt(++e.p)!==110||e.s.charCodeAt(++e.p)!==102)W.x("invalid value",e,t);return e.p++,(r||1)/0}if(s===110){if(e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==110)W.x("invalid value",e,t);return e.p++,NaN}if(s===48){if(++e.p>=e.s.length||Xu(s=e.s.charCodeAt(e.p),i))return e.bi===!0?0n:0;if(!r){if(s===120)return Vu(e,t,16,i);else if(s===98)return Vu(e,t,2,i);else if(s===111)return Vu(e,t,8,i)}if(s===46)o=2;else if(s===101||s===69)o=4;else W.x("illegal leading zero",e,t)}else if(!mt(s))W.x("invalid value",e,t);while(++e.p<e.s.length&&(s=e.s.charCodeAt(e.p),!Xu(s,i))){if(!o)o=1;if(s===95){if(!(o&1))W.x("illegal underscore",e);o+=11,a=!0}else if(o===1&&s===46)o=2;else if((o===1||o===3)&&(s===101||s===69))o=4;else if(o===4&&(s===43||s===45));else if(!mt(s))W.x("illegal character in numeric literal",e);else if(o>9)o-=11;else if(!(o&1))o++}if(!o){let c=(n-48)*(r||1);return e.bi===!0?BigInt(c):c}if(!(o&1))W.x("unfinished numeric value",e,t);let u=e.s.slice(t,e.p);if(a)u=u.replaceAll("_","");return o>1?parseFloat(u):wd(e,u,10,t)}function Vu(e,t,n,r){let i,s=1;while(++e.p<e.s.length&&(i=e.s.charCodeAt(e.p),!Xu(i,r)))if(i===95){if(s&1)W.x("illegal underscore",e);s=3}else if(!mt(i,n))W.x("illegal character in numeric literal",e);else if(s&1)s--;if(s&1)W.x("unfinished numeric value",e);let o=e.s.slice(t+2,e.p);if(s)o=o.replaceAll("_","");return wd(e,o,n,t)}function wd(e,t,n,r){if(e.bi!==!0)e:{let i=parseInt(t,n);if(!Number.isSafeInteger(i)){if(e.bi)break e;W.x("integer value cannot be represented losslessly",e,r)}return i}return n===10?BigInt(t):BigInt((n===2?"0b":n===8?"0o":"0x")+t)}function yk(e,t,n){let r=e.p++,i;if(!mt(t)||!mt(e.s.charCodeAt(e.p++))||!mt(e.s.charCodeAt(e.p++))||!mt(e.s.charCodeAt(e.p++)))return Co(e,e.p=r,t,0,n);if(e.p+=5,!mt(e.s.charCodeAt(e.p++)))W.x("invalid date-time: date part is malformed",e,r);if(e.p>=e.s.length||((t=e.s.charCodeAt(e.p))!==32||(i=!0,!mt(e.s.charCodeAt(e.p+1))))&&t!==84&&t!==116){let o=e.s.slice(r,e.p);return es(e,o,3,!1,r)}if(e.s.charCodeAt(e.p+=3)!==58)W.x("invalid date-time: time part is malformed",e,r);if(e.s.charCodeAt(e.p+=3)===58)e.p+=3;if(e.s.charCodeAt(e.p)===46)while(mt(e.s.charCodeAt(++e.p)));if(t=e.s.charCodeAt(e.p)){if(t===90||t===122){let o=e.s.slice(r,++e.p);return es(e,o,1,i,r,"[+00:00]")}if(t===43||t===45){let o=e.s.slice(r,e.p+=6);return es(e,o,1,i,r,!e.ld&&"["+e.s.slice(e.p-6,e.p)+"]")}}let s=e.s.slice(r,e.p);return es(e,s,2,i,r)}function Ek(e,t,n){let r=e.p;if(!mt(t)||!mt(e.s.charCodeAt(++e.p)))return Co(e,--e.p,t,0,n);if(e.s.charCodeAt(e.p+=4)===58)e.p+=3;if(e.s.charCodeAt(e.p)===46)while(mt(e.s.charCodeAt(++e.p)));let i=e.s.slice(r,e.p);return es(e,i,4,!1,r)}function es(e,t,n,r,i,s){if(e.ld){let o=new Cn(t,n,r);if(!o.isValid())W.x("invalid date",e,i);return o}try{if(s)t+=s;switch(n){case 1:return Temporal.ZonedDateTime.from(t);case 2:return Temporal.PlainDateTime.from(t);case 3:return Temporal.PlainDate.from(t);case 4:return Temporal.PlainTime.from(t)}}catch(o){W.x(o instanceof Error?o.message:""+o,e,i)}}/*!
181
181
  * Copyright (c) Squirrel Chat et al., All rights reserved.
182
182
  * SPDX-License-Identifier: BSD-3-Clause
183
183
  *
@@ -203,7 +203,7 @@ ${i}`,t);this.line=n,this.column=r,this.codeblock=i}static x(e,t,n){throw new J(
203
203
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
204
204
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
205
205
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
206
- */function D0(e){for(;e.p<e.s.length;e.p++){let t=e.s.charCodeAt(e.p);if(t===10)break;if(t===13&&e.s.charCodeAt(e.p+1)===10){e.p++;break}if(t<32&&t!==9||t===127)J.x("control characters are not allowed in comments",e)}}function Nt(e,t,n){let r;while(e.p<e.s.length){while(e.p<e.s.length&&((r=e.s.charCodeAt(e.p))===32||r===9||!t&&(r===10||r===13&&e.s.charCodeAt(e.p+1)===10)))e.p++;if(n||r!==35)break;D0(e)}}/*!
206
+ */function vk(e){for(;e.p<e.s.length;e.p++){let t=e.s.charCodeAt(e.p);if(t===10)break;if(t===13&&e.s.charCodeAt(e.p+1)===10){e.p++;break}if(t<32&&t!==9||t===127)W.x("control characters are not allowed in comments",e)}}function jt(e,t,n){let r;while(e.p<e.s.length){while(e.p<e.s.length&&((r=e.s.charCodeAt(e.p))===32||r===9||!t&&(r===10||r===13&&e.s.charCodeAt(e.p+1)===10)))e.p++;if(n||r!==35)break;vk(e)}}/*!
207
207
  * Copyright (c) Squirrel Chat et al., All rights reserved.
208
208
  * SPDX-License-Identifier: BSD-3-Clause
209
209
  *
@@ -229,7 +229,7 @@ ${i}`,t);this.line=n,this.column=r,this.codeblock=i}static x(e,t,n){throw new J(
229
229
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
230
230
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
231
231
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
232
- */function no(e,t=61){let n,r=0,i=[],s,o=e.s.charCodeAt(n=e.p);do if(o===t){if(!r)J.x("unexpected end of key",e);if(r===1)i.push(e.s.slice(s,e.p));return e.p++,i}else if(o===46){if(!r)J.x("illegal empty bare key",e);if(r===1)i.push(e.s.slice(s,e.p));r=0}else if(!r&&(o===34||o===39)){if(o===e.s.charCodeAt(e.p+1)&&o===e.s.charCodeAt(e.p+2))J.x("illegal quoted key: multiline strings are not allowed",e);i.push(eo(e)),r=2,e.p--}else if(o===32||o===9){if(r===1)i.push(e.s.slice(s,e.p)),r=2}else if(r===2||o<48&&o!==45||o>57&&o<65||o>90&&o<97&&o!==95||o>122)J.x("illegal character in key",e);else if(!r)r=1,s=e.p;while(o=e.s.charCodeAt(++e.p));J.x("incomplete key-value: cannot find end of key",e,n)}function Nf(e){let t=e.p++,n=Object.create(null),r=new Set,i;while(e.p<e.s.length){if(Nt(e),(i=e.s.charCodeAt(e.p))===125)return e.p++,n;let s,o=n,a=!1,u=e.p,c=no(e);for(let h=0;h<c.length;h++){if(h)o=a?o[s]:o[s]=Object.create(null);if(s=c[h],(a=Object.hasOwn(o,s))&&(typeof o[s]!=="object"||r.has(o[s])))J.x("trying to redefine an already defined value",e,u);let f=s==="__proto__";if(e.uk&&(f||s==="constructor")){o=e.uk!==1&&J.x("document contains an unsafe property",e,u);break}if(!a&&f)Object.defineProperty(o,s,{enumerable:!0,configurable:!0,writable:!0})}if(a)J.x("trying to redefine an already defined value",e,u);Nt(e,!0,!0);let l=Ri(e,125);if(o&&typeof(o[s]=l)==="object")r.add(l);if(Nt(e),(i=e.s.charCodeAt(e.p++))===125)return n;if(i!==44)J.x("expected comma or end of structure",e,e.p-1)}J.x("unfinished table",e,t)}function Rf(e){let t=e.p++,n=[],r;while(e.p<e.s.length){if(Nt(e),(r=e.s.charCodeAt(e.p))===93)return e.p++,n;if(n.push(Ri(e,93)),Nt(e),(r=e.s.charCodeAt(e.p++))===93)return n;if(r!==44)J.x("expected comma or end of structure",e,e.p-1)}J.x("unfinished array",e,t)}/*!
232
+ */function _o(e,t=61){let n,r=0,i=[],s,o=e.s.charCodeAt(n=e.p);do if(o===t){if(!r)W.x("unexpected end of key",e);if(r===1)i.push(e.s.slice(s,e.p));return e.p++,i}else if(o===46){if(!r)W.x("illegal empty bare key",e);if(r===1)i.push(e.s.slice(s,e.p));r=0}else if(!r&&(o===34||o===39)){if(o===e.s.charCodeAt(e.p+1)&&o===e.s.charCodeAt(e.p+2))W.x("illegal quoted key: multiline strings are not allowed",e);i.push(xo(e)),r=2,e.p--}else if(o===32||o===9){if(r===1)i.push(e.s.slice(s,e.p)),r=2}else if(r===2||o<48&&o!==45||o>57&&o<65||o>90&&o<97&&o!==95||o>122)W.x("illegal character in key",e);else if(!r)r=1,s=e.p;while(o=e.s.charCodeAt(++e.p));W.x("incomplete key-value: cannot find end of key",e,n)}function $d(e){let t=e.p++,n=Object.create(null),r=new Set,i;while(e.p<e.s.length){if(jt(e),(i=e.s.charCodeAt(e.p))===125)return e.p++,n;let s,o=n,a=!1,u=e.p,c=_o(e);for(let h=0;h<c.length;h++){if(h)o=a?o[s]:o[s]=Object.create(null);if(s=c[h],(a=Object.hasOwn(o,s))&&(typeof o[s]!=="object"||r.has(o[s])))W.x("trying to redefine an already defined value",e,u);let f=s==="__proto__";if(e.uk&&(f||s==="constructor")){o=e.uk!==1&&W.x("document contains an unsafe property",e,u);break}if(!a&&f)Object.defineProperty(o,s,{enumerable:!0,configurable:!0,writable:!0})}if(a)W.x("trying to redefine an already defined value",e,u);jt(e,!0,!0);let l=ts(e,125);if(o&&typeof(o[s]=l)==="object")r.add(l);if(jt(e),(i=e.s.charCodeAt(e.p++))===125)return n;if(i!==44)W.x("expected comma or end of structure",e,e.p-1)}W.x("unfinished table",e,t)}function kd(e){let t=e.p++,n=[],r;while(e.p<e.s.length){if(jt(e),(r=e.s.charCodeAt(e.p))===93)return e.p++,n;if(n.push(ts(e,93)),jt(e),(r=e.s.charCodeAt(e.p++))===93)return n;if(r!==44)W.x("expected comma or end of structure",e,e.p-1)}W.x("unfinished array",e,t)}/*!
233
233
  * Copyright (c) Squirrel Chat et al., All rights reserved.
234
234
  * SPDX-License-Identifier: BSD-3-Clause
235
235
  *
@@ -255,7 +255,7 @@ ${i}`,t);this.line=n,this.column=r,this.codeblock=i}static x(e,t,n){throw new J(
255
255
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
256
256
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
257
257
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
258
- */function Ff(e,t,n,r,i){let s=n,o=r,a,u=!1,c;for(let l=0;l<t.length;l++){if(l){if(s=u?s[a]:s[a]=Object.create(null),o=(c=o[a]).c,i===0&&(c.t===1||c.t===2))return null;if(c.t===2){let h=s.length-1;s=s[h],o=o[h].c}}if(a=t[l],(u=Object.hasOwn(s,a))&&o[a]?.t===0&&o[a]?.d)return null;if(!u){let h=a==="__proto__";if(e.uk&&(h||a==="constructor"))return!1;if(h)Object.defineProperty(s,a,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(o,a,{enumerable:!0,configurable:!0,writable:!0});o[a]={t:l<t.length-1&&i===2?3:i,d:!1,i:0,c:Object.create(null)}}}if(c=o[a],c.t!==i&&!(i===1&&c.t===3))return null;if(i===2){if(!c.d)c.d=!0,s[a]=[];s[a].push(s=Object.create(null)),c.c[c.i++]=c={t:1,d:!1,i:0,c:Object.create(null)}}if(c.d)return null;if(c.d=!0,i===1)s=u?s[a]:s[a]=Object.create(null);else if(i===0&&u)return null;return[a,s,c.c]}function Pf(e,t,n){if(t===null||e.uk===2)J.x(t===null?"trying to redefine an already defined table or value":"document contains an unsafe property",e,n)}function hu(e,t={}){let n={s:e,p:0,d:t.maxDepth??1000,bi:t.integersAsBigInt??!1,ld:t.useLegacyDate??!0,uk:t.unsafeKeyBehaviour==="throw"?2:t.unsafeKeyBehaviour==="drop"?1:0},r=Object.create(null),i=Object.create(null),s,o=!1,a=r,u=i;if(e.charCodeAt(0)===65279)n.p++;Nt(n);while(n.p<e.length){if(e.charCodeAt(n.p)===91){let c=e.charCodeAt(++n.p)===91;s=n.p+=+c,o=!1;let l=no(n,93);if(c){if(e.charCodeAt(n.p)!==93)J.x("expected end of table array declaration",n);n.p++}let h=Ff(n,l,r,i,c?2:1);if(!h)Pf(n,h,s),o=!0;else u=h[2],a=h[1]}else{s=n.p;let c=no(n),l=Ff(n,c,a,u,0);if(!l&&!o)Pf(n,l,s);Nt(n,!0,!0);let h=Ri(n,void 0);if(l&&!o)l[1][l[0]]=h}if(Nt(n,!0),n.p<e.length&&(s=e.charCodeAt(n.p))!==10&&(s!==13||e.charCodeAt(n.p+1)!==10))J.x("each key-value declaration must be followed by an end-of-line",n);Nt(n)}return r}/*!
258
+ */function yd(e,t,n,r,i){let s=n,o=r,a,u=!1,c;for(let l=0;l<t.length;l++){if(l){if(s=u?s[a]:s[a]=Object.create(null),o=(c=o[a]).c,i===0&&(c.t===1||c.t===2))return null;if(c.t===2){let h=s.length-1;s=s[h],o=o[h].c}}if(a=t[l],(u=Object.hasOwn(s,a))&&o[a]?.t===0&&o[a]?.d)return null;if(!u){let h=a==="__proto__";if(e.uk&&(h||a==="constructor"))return!1;if(h)Object.defineProperty(s,a,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(o,a,{enumerable:!0,configurable:!0,writable:!0});o[a]={t:l<t.length-1&&i===2?3:i,d:!1,i:0,c:Object.create(null)}}}if(c=o[a],c.t!==i&&!(i===1&&c.t===3))return null;if(i===2){if(!c.d)c.d=!0,s[a]=[];s[a].push(s=Object.create(null)),c.c[c.i++]=c={t:1,d:!1,i:0,c:Object.create(null)}}if(c.d)return null;if(c.d=!0,i===1)s=u?s[a]:s[a]=Object.create(null);else if(i===0&&u)return null;return[a,s,c.c]}function Ed(e,t,n){if(t===null||e.uk===2)W.x(t===null?"trying to redefine an already defined table or value":"document contains an unsafe property",e,n)}function Du(e,t={}){let n={s:e,p:0,d:t.maxDepth??1000,bi:t.integersAsBigInt??!1,ld:t.useLegacyDate??!0,uk:t.unsafeKeyBehaviour==="throw"?2:t.unsafeKeyBehaviour==="drop"?1:0},r=Object.create(null),i=Object.create(null),s,o=!1,a=r,u=i;if(e.charCodeAt(0)===65279)n.p++;jt(n);while(n.p<e.length){if(e.charCodeAt(n.p)===91){let c=e.charCodeAt(++n.p)===91;s=n.p+=+c,o=!1;let l=_o(n,93);if(c){if(e.charCodeAt(n.p)!==93)W.x("expected end of table array declaration",n);n.p++}let h=yd(n,l,r,i,c?2:1);if(!h)Ed(n,h,s),o=!0;else u=h[2],a=h[1]}else{s=n.p;let c=_o(n),l=yd(n,c,a,u,0);if(!l&&!o)Ed(n,l,s);jt(n,!0,!0);let h=ts(n,void 0);if(l&&!o)l[1][l[0]]=h}if(jt(n,!0),n.p<e.length&&(s=e.charCodeAt(n.p))!==10&&(s!==13||e.charCodeAt(n.p+1)!==10))W.x("each key-value declaration must be followed by an end-of-line",n);jt(n)}return r}/*!
259
259
  * Copyright (c) Squirrel Chat et al., All rights reserved.
260
260
  * SPDX-License-Identifier: BSD-3-Clause
261
261
  *
@@ -281,7 +281,7 @@ ${i}`,t);this.line=n,this.column=r,this.codeblock=i}static x(e,t,n){throw new J(
281
281
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
282
282
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
283
283
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
284
- */var ZS=!!"".isWellFormed;/*!
284
+ */var nP=!!"".isWellFormed;/*!
285
285
  * Copyright (c) Squirrel Chat et al., All rights reserved.
286
286
  * SPDX-License-Identifier: BSD-3-Clause
287
287
  *
@@ -307,78 +307,82 @@ ${i}`,t);this.line=n,this.column=r,this.codeblock=i}static x(e,t,n){throw new J(
307
307
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
308
308
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
309
309
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
310
- */import{readdirSync as e$,rmSync as t$,statSync as n$}from"node:fs";import{setDefaultAutoSelectFamilyAttemptTimeout as r$}from"node:net";import{homedir as i$}from"node:os";import{join as Pi}from"node:path";import{setTimeout as s$}from"node:timers/promises";var vn=100,kt=25000000,o$=536870912,Oi=["safe","questionable","explicit"],Yn=["nudity","underwear"],gu=["comic","monochrome","sketch","chibi"],Uf=["off","5","10","25","50","100"],_f=["off","720","1080","1440","1800","2560"],Cf={nudity:new Set(["nude","naked","topless","bottomless","nipples","naked_towel","undressing"]),underwear:new Set(["underwear","panties","pantsu","bra","lingerie","pantyshot"])},a$={comic:new Set(["comic","4koma"]),monochrome:new Set(["monochrome","greyscale"]),sketch:new Set(["sketch","lineart","line_art"]),chibi:new Set(["chibi"])},u$=/^(?:rating|score|width|height|filetype|dimension):/,Fi={safe:"s",questionable:"q",explicit:"e"},jf=8191,c$=20000,l$=5000,Of=3000,Tf=8,h$=3000,Wf=60000,Af=3,f$=3,d$="https://static.zerochan.net",Jf="https://s1.zerochan.net",mu=`ttheme/${Ve.version} (+${Ve.homepage})`,g$=["orig","tile","thumb","cut"],Kf=new Map,m$=F$(process.env.TTHEME_FIND_HOSTS),p$=R$(process.env.TTHEME_FIND_CUTOUTS);r$(h$);function Hf(e){try{return e$(e)}catch{return[]}}function Pr(e){return e.startsWith("//")?`https:${e}`:e}function Sn(e){return(/\.([a-z0-9]+)(?:\?.*)?$/i.exec(e)?.[1]??"").toLowerCase()}function Ti(e){let t=e.trim();if(!t)return[];let n=JSON.parse(t);if(Array.isArray(n))return n;let r=n.posts;return Array.isArray(r)?r:[]}function w$(e){let t=e.trim(),r=(t?JSON.parse(t):{}).tags??{};return new Map(Object.entries(r).map(([i,s])=>[i,String(s)]))}function du(e,t,n){let r=Pr(String(e??""));return{file:r,width:Number(t)||0,height:Number(n)||0,ext:Sn(r)}}function qf(e,t){let n=Pr(String(t.preview??""));if(!t.file||!n||!Number(e.id))return[];let r=Number(e.width??e.image_width)||0,i=Number(e.height??e.image_height)||0;return[{id:Number(e.id),width:r,height:i,file:t.file,preview:n,ext:t.ext,owner:String(t.owner??""),artist:t.artist,score:Number(e.score)||0,rating:String(e.rating??""),md5:String(t.md5??""),source:String(e.source??""),tags:t.tags.split(/\s+/).filter(Boolean),solo:t.solo,family:Number(e.parent_id)||(e.has_children===!0?Number(e.id):0),smaller:t.versions.filter((s)=>s.file&&s.width>0&&s.height>0&&s.width*s.height<r*i)}]}function b$(e){let t=w$(e);return Ti(e).flatMap((n)=>{let r=Pr(String(n.file_url??"")),i=String(n.tags??"");return qf(n,{preview:n.preview_url,file:r,ext:String(n.file_ext||Sn(r)).toLowerCase(),owner:n.author,artist:i.split(/\s+/).find((s)=>t.get(s)==="artist")??"",md5:n.md5,tags:i,solo:void 0,versions:[du(n.jpeg_url,n.jpeg_width,n.jpeg_height),du(n.sample_url,n.sample_width,n.sample_height)]})})}function $$(e){return Ti(e).flatMap((t)=>{let n=Pr(String(t.file_url??"")),r=String(t.tag_string??""),i=t.media_asset??{};return qf(t,{preview:i.variants?.find((s)=>s.type==="360x360")?.url??t.preview_file_url,file:n,ext:String(t.file_ext||Sn(n)).toLowerCase(),owner:"",artist:String(t.tag_string_artist??"").split(/\s+/)[0]??"",md5:t.md5,tags:r,solo:r.split(/\s+/).includes("solo"),versions:(i.variants??[]).map((s)=>du(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 k$(e){return(Array.isArray(e)?e:[]).map((t)=>String(t).toLowerCase().replace(/\s+/g,"_"))}function y$(e){return String(e??"").replace(/[^0-9a-z]+/gi,".").replace(/^\.+|\.+$/g,"")||"zerochan"}function E$(e){let t=e.trim(),n=t?JSON.parse(t):{};return(Array.isArray(n.items)?n.items:n.id?[n]:[]).flatMap((i)=>{let s=Number(i.id);if(!s)return[];let o=k$(i.tags),a=Pr(String(i.full??""));return[{id:s,width:Number(i.width)||0,height:Number(i.height)||0,file:a,ext:Sn(a),preview:`${Jf}/${y$(i.tag??i.primary)}.600.${s}.jpg`,owner:"",artist:"",score:0,rating:o.some((u)=>Cf.nudity.has(u))?"q":"g",md5:String(i.md5??i.hash??""),source:String(i.source??""),tags:o,solo:o.includes("solo"),family:0,smaller:[]}]})}function v$(e){return Number(/Zerochan has ([\d,]+) /.exec(e)?.[1]?.replace(/,/g,"")??0)}function M$(e){return Ti(e).flatMap((t)=>{let n=String(t.value??"");return n?[{value:n,count:Number(t.post_count)||0}]:[]})}function S$(e){return Ti(e).flatMap((t)=>{let n=String(t.name??"");return n?[{value:n,count:Number(t.count)||0}]:[]})}function I$(e){return Number(/count="(\d+)"/.exec(e)?.[1]??0)}function N$(e){let n=(e.trim()?JSON.parse(e):{}).counts?.posts;return n===null?Number.NaN:Number(n)||0}function R$(e){let t=new Map;for(let n of(e??"").split(/\s+/).filter(Boolean)){let r=n.indexOf("=");if(r>0)t.set(n.slice(0,r),n.slice(r+1).split(",").filter(Boolean))}return t}function F$(e){let t=new Map;for(let n of(e??"").split(/[\s,]+/).filter(Boolean)){let r=n.indexOf("="),i=n.slice(0,r);try{let s=new URL(n.slice(r+1));if(i&&s.protocol==="https:")t.set(i,s.origin)}catch{}}return t}function io(e,t,n,r){let i=(e??"").split(/\s+/);if(r!==void 0&&i.includes(r))return[];let s=t.filter((o)=>i.includes(o));return s.length>0?s:[...n]}function zn(e){return io(e,Oi,["safe"])}function Or(e){return io(e,Yn,Yn,"none")}function so(e){return io(e,gu,[],"none")}function Ai(e){let t=te.map((n)=>n.name);return io(e,t,t)}function pu(e,t,n){return{score:Number(e)||0,size:Number(t)||0,png:n==="on"}}function Hi(e){return[...new Set((e??"").toLowerCase().split(/[\s,]+/).map((t)=>t.replace(/^-+/,"")).filter(Boolean))]}function wu(e,t,n){return{safe:new Set(e),questionable:new Set(t),explicit:new Set(n)}}function bu(e){let t=m$.get(e.key),n=p$.get(e.key);return{...e,origin:t??e.origin,moved:t!==void 0&&t!==e.origin,cutouts:n??e.cutouts,vouched:e.vouched&&n===void 0}}function Qf(e){return e.length<2?e.join(""):e.map((t)=>`~${t}`).join(" ")}function Yf(e){return e>0?[`width:>=${e}`,`height:>=${e}`]:[]}function Lf(e){let t=bu(e),n=(r)=>new URLSearchParams({api_version:"2",include_tags:"1",...r});return{...t,scored:!0,narrow:({score:r,size:i})=>[...r>0?[`score:>=${r}`]:[],...Yf(i)],cutouts:Qf(t.cutouts),ratings:wu([Fi.safe],[Fi.questionable],[Fi.explicit]),rate:(r)=>{let[i]=r;if(r.length===1&&i)return`rating:${Fi[i]}`;let s=Oi.filter((a)=>!r.includes(a)),[o]=s;return s.length===1&&o?`-rating:${Fi[o]}`:""},best:"order:score",tagBudget:Number.POSITIVE_INFINITY,postsUrl:(r,i)=>`${t.origin}/post.json?${n({limit:String(vn),page:String(i+1),tags:r})}`,countUrl:(r)=>`${t.origin}/post.xml?${new URLSearchParams({limit:"1",tags:r})}`,postUrl:(r)=>`${t.origin}/post.json?${n({tags:`id:${r}`})}`,pageUrl:(r)=>`${t.origin}/post/show/${r}`,parse:b$,count:I$}}function P$(e){let t=bu(e),n=wu(["g"],["s","q"],["e"]);return{...t,scored:!0,narrow:({score:r,size:i,png:s})=>[...r>0?[`score:>=${r}`]:[],...Yf(i),...s?["filetype:png"]:[]],cutouts:Qf(t.cutouts),ratings:n,rate:(r)=>r.length===Oi.length?"":`rating:${r.flatMap((i)=>[...n[i]]).join(",")}`,best:"order:score",tagBudget:2,postsUrl:(r,i)=>`${t.origin}/posts.json?${new URLSearchParams({limit:String(vn),page:String(i+1),tags:r})}`,countUrl:(r)=>`${t.origin}/counts/posts.json?${new URLSearchParams({tags:r})}`,postUrl:(r)=>`${t.origin}/posts.json?${new URLSearchParams({limit:"1",tags:`id:${r}`})}`,pageUrl:(r)=>`${t.origin}/posts/${r}`,parse:$$,count:N$}}function fu(e){return e.split(/\s+/).filter((t)=>t&&!/^(?:order|dimension):/.test(t)).map((t)=>t.split("_").map(encodeURIComponent).join("+")).join(",")}function Gf(e){let t=e.split(/\s+/),n=t.find((r)=>r.startsWith("dimension:"))?.slice(10);return{s:t.includes("order:fav")?"fav":"id",...n?{d:n}:{}}}function O$(e){let t=bu(e);return{...t,scored:!1,narrow:({size:n})=>n>=1800?["dimension:huge"]:n>0?["dimension:large"]:[],cutouts:t.cutouts[0]??"",ratings:wu(["g"],["q"],["e"]),rate:()=>"",best:"order:fav",tagBudget:3,missing:404,postsUrl:(n,r)=>`${t.origin}/${fu(n)}?${new URLSearchParams({json:"",l:String(vn),p:String(r+1),...Gf(n)})}`,countUrl:(n)=>`${t.origin}/${fu(n)}?${new URLSearchParams({xml:"",l:"1"})}`,postUrl:(n)=>`${t.origin}/${n}?json=`,pageUrl:(n)=>`${t.origin}/${n}`,parse:E$,count:v$,counts:(n)=>fu(n).split(",").length===1&&!("d"in Gf(n)),guesses:(n)=>(n.tags.includes("transparent_background")?["png","jpg"]:["jpg","png"]).map((r)=>n.preview.replace(Jf,d$).replace(/\.600\.(\d+)\.jpg$/,`.full.$1.${r}`))}}function T$(e){let t=ro(`https://${e}`);return te.find((n)=>ro(n.origin)===t)}function $u(e){return e.split(/\s+/).filter((t)=>t&&!u$.test(t)).length}function oo(e,t){let n=e.trim();if(/^\d+$/.test(n))return{site:t,id:Number(n)};let r=/^([\w.]+):(\d+)$/.exec(n);if(r){let a=te.find((u)=>u.key===r[1]||u.name===r[1]);return a&&{site:a,id:Number(r[2])}}let i;try{i=new URL(n)}catch{return}let s=T$(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 te=[P$({key:"danbooru",name:"danbooru",origin:"https://shima.donmai.us",cutouts:["transparent_background"],vouched:!1,ansi:2}),Lf({key:"konachan",name:"konachan",origin:"https://konachan.net",cutouts:["transparent","vector"],vouched:!1,ansi:6}),Lf({key:"yande",name:"yande.re",origin:"https://yande.re",cutouts:["transparent_png"],vouched:!0,ansi:5}),O$({key:"zerochan",name:"zerochan",origin:"https://www.zerochan.net",cutouts:["transparent_background"],vouched:!1,ansi:3})],Jt=te.find((e)=>e.key==="danbooru"),nn=134217728;function Rt(e,t){let n=te.indexOf(e);return(n===-1?te.length:n)*nn+t}function ro(e){let t;try{t=new URL(e).hostname}catch{return""}return t.split(".").slice(-2).join(".")}function ao(e,t,n=t){return t.mirror&&n===t?{site:Jt,url:t.mirror.file}:{site:e,url:n.file}}function uo(e,t){return t.mirror?{site:Jt,url:t.mirror.preview}:{site:e,url:t.preview}}function co(e,t=Yn){return e.tags.filter((n)=>t.some((r)=>Cf[r].has(n)))}function Zf(e,t){return e.tags.filter((n)=>t.some((r)=>a$[r].has(n)))}function lo(e,t,n=["safe"]){return n.some((r)=>e.ratings[r].has(t.rating))}function rn(e){return[e,...e.smaller].find((t)=>t.width*t.height<=kt)}function zf(e){let t=new Map;for(let[n,r]of[...e].sort(([i],[s])=>i<s?-1:1)){if(r==="")continue;t.set(r,[...t.get(r)??[],n])}return t}function Tr(){return Pi(process.env.XDG_CACHE_HOME??Pi(i$(),".cache"),"ttheme")}function Ft(e){return Pi(Tr(),e.key)}function Bf(e=o$,t=Tr()){let n=[],r=0;for(let i of Hf(t))for(let s of g$){let o=Pi(t,i,s);for(let a of Hf(o)){let u=Pi(o,a);try{let{size:c,mtimeMs:l}=n$(u);n.push({path:u,size:c,at:l}),r+=c}catch{}}}n.sort((i,s)=>i.at-s.at);for(let i of n){if(r<=e)return;try{t$(i.path,{force:!0}),r-=i.size}catch{}}}function A$(e,t){if(e!==null&&/^\s*\d+\s*$/.test(e))return Number(e)*1000;let n=e===null?Number.NaN:Date.parse(e);return Number.isNaN(n)?Wf:Math.max(0,n-t)}function Mn(e){return Kf.get(e.key)??0}function H$(e){for(let t=e;t instanceof Error;t=t.cause)if(t.code==="ECONNRESET")return!0;return!1}function L$(e){return(e.headers.get("server")??"").startsWith("cloudflare")&&e.headers.get("cf-mitigated")==="challenge"}function G$(e,t){let n=new URL(t,e);if(!n.search)n.search=new URL(e).search;return n.href}async function Zn(e,t,n,r={},i=c$){let s=t;for(let o=1,a=0;;o++){let u=Mn(e)-Date.now();if(u>0)await s$(u,void 0,{signal:n});let c;try{c=await fetch(s,{headers:{"User-Agent":mu,Referer:`${e.origin}/`,...r},redirect:"manual",signal:i?AbortSignal.any([n,AbortSignal.timeout(i)]):n})}catch(h){if(o<Af&&!n.aborted&&H$(h))continue;throw h}let l=c.headers.get("location");if(l&&c.status>=300&&c.status<400&&a<f$){await c.body?.cancel(),s=G$(s,l),a++,o--;continue}if(c.status===429&&o<Af){await c.body?.cancel();let h=A$(c.headers.get("retry-after"),Date.now());if(h>Wf)throw Error(`${e.name} asks to wait ${Math.ceil(h/1000)}s`);Kf.set(e.key,Math.max(Mn(e),Date.now()+h));continue}if(!c.ok)throw await c.body?.cancel(),Object.assign(Error(L$(c)?`${e.name} is behind a Cloudflare challenge`:`${e.name} answered ${c.status}`),{status:c.status});return c}}async function ku(e,t,n){try{return await(await Zn(e,t,n)).text()}catch(r){if(e.missing!==void 0&&r.status===e.missing)return"";throw r}}async function Vf(e,t,n,r){return e.parse(await ku(e,e.postsUrl(t,n),r))}async function yu(e,t,n){return e.count(await ku(e,e.countUrl(t),n))}async function Li(e,t,n){let[r]=e.parse(await ku(e,e.postUrl(t),n));return r}function U$(e){let t=new URLSearchParams({limit:String(2*vn),only:"md5,tag_string,file_url",tags:`md5:${e.join(",")}`});return`${Jt.origin}/posts.json?${t}`}function _$(e){return new Map(Ti(e).flatMap((t)=>{let n=String(t.md5??"");return n?[[n,{tags:String(t.tag_string??"").split(/\s+/).filter(Boolean),file:Pr(String(t.file_url??""))}]]:[]}))}function Xf(e,t){for(let n of e){let r=t.get(n.md5);if(!r)continue;if(n.tags=[...new Set([...n.tags,...r.tags])],n.solo=r.tags.includes("solo"),r.file.includes("/original/")){if(n.mirror={file:r.file,preview:r.file.replace("/original/","/360x360/").replace(/\.[a-z0-9]+$/i,".jpg")},!n.file)n.file=r.file,n.ext=Sn(r.file)}}}async function xf(e,t){let n=new Map;if(Mn(Jt)>Date.now())return n;for(let r=0;r<e.length;r+=vn){let i=await(await Zn(Jt,U$(e.slice(r,r+vn)),t,{},l$)).text();for(let[s,o]of _$(i))n.set(s,o)}return n}async function ho(e,t,n){if(t.file||!e.guesses)return;for(let r of e.guesses(t))try{let i=await Zn(e,r,n,{Range:`bytes=0-${jf}`}),s=yn(new Uint8Array(await i.arrayBuffer()));return t.file=r,t.ext=Sn(r),s}catch(i){if(n.aborted||i.status!==404)throw i}throw Error(`${e.name} keeps no png or jpg of ${t.id}`)}async function Df(e,t){if(Mn(Jt)<=Date.now())try{let i=new URLSearchParams({"search[query]":e,"search[type]":"tag_query",limit:String(Tf)}),s=`${Jt.origin}/autocomplete.json?${i}`;return M$(await(await Zn(Jt,s,t,{},Of)).text())}catch(i){if(t.aborted)throw i}let n=te.find((i)=>i.key==="yande"),r=new URLSearchParams({name:e,order:"count",limit:String(Tf)});return S$(await(await Zn(n,`${n.origin}/tag.json?${r}`,t,{},Of)).text())}async function ed(e,t,n){let r=await Zn(e,t,n,{Range:`bytes=0-${jf}`});return yn(new Uint8Array(await r.arrayBuffer()))}async function fo(e,t,n,r){let i=await Zn(e,t,n,{},0),s=Number(i.headers.get("content-length"))||0,o=i.body?.getReader();if(!o)return new Uint8Array(await i.arrayBuffer());let a=[],u=0;for(;;){let{done:h,value:f}=await o.read();if(h)break;a.push(f),u+=f.length,r?.(u,s)}let c=new Uint8Array(u),l=0;for(let h of a)c.set(h,l),l+=h.length;return c}var Vn=["top-left","top-center","top-right","center-left","center","center-right","bottom-left","bottom-center","bottom-right"],Gi="Original",W$=1e6,Kt="_groups.toml",td=3,nd=8,Eu="[a-z0-9]+(?:-[a-z0-9]+)*",J$=new RegExp(`^(?:(${Eu})@(${Eu})/)?(${Eu})$`),od=["background","foreground","cursor","selection"];function me(e,t){throw Error(`${e}: ${t}`)}function Bn(e,t,n){if(typeof n!=="string"||!yr(n))me(e,`${t} must be "#rrggbb" (lowercase), got ${JSON.stringify(n)}`);return n}function Ui(e,t,n){if(typeof n!=="string"||n.length===0)me(e,`${t} must be a non-empty string`);return n}function sn(e){return e.replace("@","--").replace("/","--")}function ye(e){let t=e.indexOf("/");return t<0?void 0:e.slice(0,t)}function Hr(e){return e.slice(e.indexOf("/")+1)}function qt(e){let t=J$.exec(e);if(!t)return"takes lowercase letters, digits and single hyphens, as <palette> or <owner>@<market>/<palette>";if((t[1]?.length??0)>39)return"has an owner longer than a GitHub handle can be";return(t[2]?.length??0)>40||(t[3]?.length??0)>40?"is longer than 40 characters":void 0}function _i(e){if(/[\p{Cc}"$`\\]/u.test(e))return"holds a control character, a quote, $, ` or \\";return e.length>80?"is longer than 80 characters":void 0}function go(e,t,n){let r=Ui(e,t,n),i=_i(r);if(i)me(e,`${t} ${JSON.stringify(r)} ${i}`);return r}function rd(e,t,n){let r=Ui(e,t,n),i=qt(r);if(i)me(e,`${t} "${r}" ${i}`);return r}function Ar(e){return e&&typeof e==="object"?e:{}}function K$(e,t,n){if(t===void 0)return[n.cursor,n.selectionBackground,n.background];let r=Array.isArray(t)?t:[t];if(r.length===0)me(e,"ghostty.icon_screen must not be empty");return r.map((i,s)=>Bn(e,`ghostty.icon_screen[${s}]`,i))}function q$(e,t,n){let r=Ar(t);return{iconGhost:r.icon_ghost===void 0?n.cursor:Bn(e,"ghostty.icon_ghost",r.icon_ghost),iconScreen:K$(e,r.icon_screen,n)}}function Q$(e){return new Map([...od.map((t)=>[t,e[t]]),...e.ansi.map((t,n)=>[`ansi${n}`,t])])}function Y$(e,t,n){if(!Array.isArray(t)||t.length!==td)me(e,`meta.signature must name exactly ${td} palette slots`);let r=Q$(n),i=[],s=[];for(let[o,a]of t.entries()){let u=`meta.signature[${o}]`,c=Ui(e,u,a),l=r.get(c);if(l===void 0)me(e,`${u} ${JSON.stringify(a)} is not a palette slot — use ${od.join(", ")} or ansi0-ansi15`);i.push(c),s.push(l)}if(new Set(s).size!==s.length)me(e,"meta.signature slots must resolve to three different colors");return{names:i,colors:s}}function Z$(e,t,n){if(t===void 0)return;if(!n)me(e,"meta.booru_sites renames meta.booru per site, so it needs meta.booru");if(!t||typeof t!=="object"||Array.isArray(t))me(e,'meta.booru_sites must be a table of site = "tag" or site = ["tag", ...]');let r={};for(let[i,s]of Object.entries(t)){let o=te.find((u)=>u.key===i);if(!o)me(e,`meta.booru_sites.${i} is not a find site — use ${te.map((u)=>u.key).join(", ")}`);let a=typeof s==="string"?[s]:Array.isArray(s)?s:void 0;if(!a||a.some((u)=>typeof u!=="string"||u===""||/\s/.test(u)))me(e,`meta.booru_sites.${i} must be one tag or a list of tags, got ${JSON.stringify(s)}`);if(a.length>1&&Number.isFinite(o.tagBudget))me(e,`meta.booru_sites.${i} takes one tag — ${o.name} searches ${o.tagBudget} tags at a time`);r[i]=a}return r}function z$(e,t){if(t===void 0)return;if(!Array.isArray(t)||t.length===0||t.length>nd)me(e,`[[picture]] holds 1 to ${nd} pictures`);return t.map((n,r)=>{let i=Ar(n),s=`picture[${r}]`,o=te.find((l)=>l.key===i.site);if(!o)me(e,`${s}.site must be one of ${te.map((l)=>l.key).join(", ")}`);if(typeof i.id!=="number"||!Number.isSafeInteger(i.id)||i.id<=0)me(e,`${s}.id must be the post's number on ${o.name}`);let{size:a,position:u,opacity:c}=i;if(a!==void 0&&a!=="fill"&&!(Number.isInteger(a)&&Number(a)>=20&&Number(a)<=999))me(e,`${s}.size must be "fill" or a percentage from 20 to 999`);if(u!==void 0&&!Vn.includes(u))me(e,`${s}.position must be one of ${Vn.join(", ")}`);if(c!==void 0&&!(typeof c==="number"&&c>=0&&c<=1))me(e,`${s}.opacity must be a number from 0 to 1`);return{site:o.key,id:i.id,...a!==void 0?{size:a}:{},...u!==void 0?{position:u}:{},...c!==void 0?{opacity:c}:{}}})}function ad(e,t){try{return hu(t)}catch(n){me(e,`is not valid TOML — ${(n instanceof Error?n.message:String(n)).split(`
311
- `)[0]}`)}}function B$(e){let n=ad(Kt,id(sd(e,Kt),"utf8")).group;if(!Array.isArray(n)||n.length===0)me(Kt,"needs at least one [[group]] table");return n.map((r)=>{let i=Ar(r);return{name:go(Kt,"group.name",i.name),native:i.native===void 0?void 0:go(Kt,"group.native",i.native),lead:Ui(Kt,"group.lead",i.lead)}})}function vu(e,t,n){let r=ad(e,t),i=Ar(r.meta),s=Ar(r.colors),o=Ar(r.contrast),a=s.ansi;if(!Array.isArray(a)||a.length!==16)me(e,`colors.ansi must hold exactly 16 colors, got ${Array.isArray(a)?a.length:typeof a}`);let u=rd(e,"meta.name",i.name);if(u!==n.name)me(e,`meta.name "${u}" does not match its file — it lives at ${n.name}`);let c=n.open===!0;for(let P of["order","role"])if(c&&i[P]!==void 0)me(e,`meta.${P} is for the official palettes — a market palette follows its base`);let l=i.role;if(l!==void 0&&l!=="default")me(e,`meta.role must be "default", got ${JSON.stringify(l)}`);let h=i.base===void 0?void 0:rd(e,"meta.base",i.base);if(h!==void 0&&!c)me(e,"meta.base is for market palettes");let f=h===void 0?void 0:n.bases?.get(h),d=c&&i.group===void 0?f?.group??Gi:go(e,"meta.group",i.group),g=n.groups.get(d);if(!g&&!(c&&(d===Gi||n.open)))me(e,`meta.group "${d}" has no [[group]] table in ${Kt}`);let m=Bn(e,"colors.background",s.background),b=Bn(e,"colors.foreground",s.foreground),p=Bn(e,"colors.cursor",s.cursor),E=Bn(e,"colors.selection_background",s.selection_background),v=a.map((P,G)=>Bn(e,`colors.ansi[${G}]`,P)),S=Y$(e,i.signature,{background:m,foreground:b,cursor:p,selection:E,ansi:v}),w=i.booru===void 0?void 0:Ui(e,"meta.booru",i.booru);if(w!==void 0&&/[\s\p{Cc}]/u.test(w))me(e,`meta.booru must be a single booru tag, got ${JSON.stringify(w)}`);let N=Z$(e,i.booru_sites,w),y=Array.isArray(o.waive)?o.waive.map(String):[];if(y.length>0&&typeof o.reason!=="string")me(e,"contrast.waive needs a contrast.reason explaining why");let R=z$(e,r.picture);return{name:u,...h?{base:h}:{},group:d,native:g?.native,lead:!c&&g?.lead===u,order:c?f?.order??W$:Number(i.order),role:l,ansiSource:c&&i.ansi_source===void 0?h??"original":go(e,"meta.ansi_source",i.ansi_source),...w?{booru:w}:{},...N?{booruSites:N}:{},background:m,foreground:b,cursor:p,selectionBackground:E,ansi:v,signature:S.colors,signatureSlots:S.names,ghostty:q$(e,r.ghostty,{background:m,cursor:p,selectionBackground:E}),waive:y,waiveReason:typeof o.reason==="string"?o.reason:void 0,...R?{pictures:R}:{}}}function ud(e){let t=B$(e),n=new Map(t.map((s)=>[s.name,s]));if(n.size!==t.length)me(Kt,"group.name must be unique");let r=C$(e).filter((s)=>s.endsWith(".toml")&&!s.startsWith("_")).map((s)=>vu(s,id(sd(e,s),"utf8"),{name:j$(s,".toml"),groups:n})).sort((s,o)=>s.order-o.order);if(new Set(r.map((s)=>s.order)).size!==r.length)throw Error("themes: meta.order must be unique across all themes");for(let s of t){let o=r.filter((a)=>a.group===s.name);if(o.length===0)me(Kt,`group "${s.name}" has no themes`);if(!o.some((a)=>a.name===s.lead))me(Kt,`group "${s.name}" lead "${s.lead}" is not one of its themes`)}return r}function cd(e){return e.filter((t)=>t.role===void 0)}function Xn(e){let t=(r,i)=>r<i?-1:r>i?1:0,n=(r)=>ye(r.name)?r.name:r.base??r.name;return[...e].sort((r,i)=>Number(ye(r.name)!==void 0)-Number(ye(i.name)!==void 0)||t(r.group.toLowerCase(),i.group.toLowerCase())||Number(r.catalog===void 0)-Number(i.catalog===void 0)||t((r.catalog??"").toLowerCase(),(i.catalog??"").toLowerCase())||t(n(r),n(i))||Number(r.base!==void 0)-Number(i.base!==void 0)||t(r.name,i.name))}var mo={width:2560,height:1550},ek=2560,tk=0.1,nk=0.99,rk=2,on={tall:1.15,reach:0.4,widest:0.95,headroom:0.04,margin:0.03,stands:12},ik=nt(rt("#19161e","#9b86c8",0.2)),sk="shelf",bo="originals",ok="images.json",Mu=1;function ak(e,t){if(t==="background"||t==="foreground"||t==="cursor")return e[t];if(t==="selection"&&e.selection)return e.selection;let n=/^ansi(\d|1[0-5])$/.exec(t),r=n?e.ansi[Number(n[1])]:void 0;if(!r)throw Error(`${e.name} has no slot ${t}`);return r}function ld(e){if(e(1))return 1;let t=0,n=1;for(let r=0;r<40;r++){let i=(t+n)/2;if(e(i))t=i;else n=i}return t}function hd(e,t){let n=ak(e,t),i=ld((c)=>lh({name:e.name,background:rt(e.background,n,c),foreground:e.foreground,ansi:e.ansi,waive:e.waived??[]}).length===0),s=ld((c)=>nt(rt(e.background,n,c))<=ik),o=Math.floor(Math.min(i,s)*1000)/1000,a=Qe(e.background),u=Math.hypot(...Qe(n).map((c,l)=>(c-(a[l]??0))*o));return{slot:t,color:n,cap:i,matched:s,opacity:o,reach:u}}function Gr(e,t){let n=hd(e,"cursor");if(n.opacity>=tk)return n;return t.filter((r)=>r!=="cursor"&&r!=="background").map((r)=>hd(e,r)).reduce((r,i)=>i.reach>r.reach?i:r,n)}function uk(e){return $f(e)??{x:0,y:0,w:e.width,h:e.height}}function Fu(e,t){if(e<=0||t<=0)return mo;let n=Math.min(1,mo.width/Math.max(e,t));return{width:Math.round(e*n),height:Math.round(t*n)}}function bd(e,t,n,r){if(r<on.stands){let u=e.w*n>e.h*t?{x:e.x+(e.w-e.h*t/n)/2,y:e.y,w:e.h*t/n,h:e.h}:{x:e.x,y:e.y,w:e.w,h:e.w*n/t};return{crop:u,at:{x:0,y:0,w:t,h:n},focus:(u.y-e.y+u.h/2)/e.h}}let i=Math.max(on.tall*n,on.reach*t*e.h/e.w),s=i*e.w/e.h;if(s>on.widest*t)s=on.widest*t,i=s*e.h/e.w;let o=on.headroom*n,a=Math.min(1,(n-o)/i);return{crop:{x:e.x,y:e.y,w:e.w,h:e.h*a},at:{x:t*(1-on.margin)-s,y:o,w:s,h:i*a},focus:Math.min(1,(n/2-o)/i)}}function $d(e,t){return 0.299*(e[t]??0)+0.587*(e[t+1]??0)+0.114*(e[t+2]??0)}function ck(e,t){let n=new Uint32Array(256),r=Math.max(1,Math.floor(t.w*t.h/400000)),i=0;for(let o=0;o<t.w*t.h;o+=r){let a=((t.y+Math.floor(o/t.w))*e.width+t.x+o%t.w)*4;if((e.data[a+3]??0)>=128){let u=Math.round($d(e.data,a));n[u]=(n[u]??0)+1,i++}}let s=0;for(let o=0;o<256&&i>0;o++)if(s+=n[o]??0,s>=i*nk)return Math.min(rk,Math.max(1,255/Math.max(1,o)));return 1}function lk(e,t){let n=new Uint8Array(e.width*e.height);for(let r=0;r<n.length;r++){let i=r*4;n[r]=Math.round(Math.min(255,$d(e.data,i)*t)*(e.data[i+3]??0)/255)}return{width:e.width,height:e.height,data:n}}function po(e,t,n,r){let i=new Float32Array(n*r),s=Math.max(0,Math.round(t.at.x)),o=Math.max(0,Math.round(t.at.y)),a=Math.min(n,Math.round(t.at.x+t.at.w)),u=Math.min(r,Math.round(t.at.y+t.at.h));if(a>s&&u>o){let c=t.crop.w/t.at.w,l=t.crop.h/t.at.h,h={x:t.crop.x+(s-t.at.x)*c,y:t.crop.y+(o-t.at.y)*l,w:(a-s)*c,h:(u-o)*l},f=Ef(e,h,a-s,u-o);for(let d=o;d<u;d++)i.set(f.data.subarray((d-o)*(a-s),(d-o+1)*(a-s)),d*n+s)}return{width:n,height:r,data:i}}function kd(e){let t=uk(e);return{box:t,clear:tn(e,t),ink:lk(e,ck(e,t))}}function yd(e,t,n,r){let{box:i,clear:s,ink:o}=kd(e),a=bd(i,t,n,s),u=Math.min(1,ek/Math.max(i.w,i.h)),c={x:0,y:0,w:Math.round(i.w*u),h:Math.round(i.h*u)},l=po(o,{crop:i,at:c,focus:a.focus},c.w,c.h),h=po(o,a,t,n);return{figure:Mi(Ds(l,r*c.w*a.crop.w/(i.w*a.at.w))),fill:Mi(Ds(h,r)),focus:a.focus}}function hk(e,t,n,r){let i=Qe(t),s=Qe(n),o=new Uint8Array(e.width*e.height*4);for(let a=0;a<e.data.length;a++){let u=(e.data[a]??0)/255*r;for(let c=0;c<3;c++)o[a*4+c]=Math.round((i[c]??0)+((s[c]??0)-(i[c]??0))*u);o[a*4+3]=255}return{width:e.width,height:e.height,data:o}}function Ed(e,t,n,r,i,s){let{box:o,clear:a,ink:u}=kd(e),c=po(u,bd(o,r,i,a),r,i);return hk(Mi(Ds(c,s)),t.background,n.color,n.opacity)}function We(e){return V(e,"ttheme","backgrounds")}function Su(e){return V(e,ok)}function xn(e){try{return wo(e,"utf8")}catch{return}}function In(e){try{return x$(e)}catch{return[]}}function st(e){let t=xn(Su(e));if(t===void 0)return dk(e);let n=JSON.parse(t);if(n.version!==Mu)throw Error(`${Su(e)} is version ${n.version} — this ttheme reads version ${Mu}`);return n}function fk(e,t){let n=t.pictures.findIndex((i)=>i.key===t.active),r=t.pictures[n];return[...r.from?[`# from ${r.from}`]:[],`# image ${r.key} ${n+1}/${t.pictures.length}`,`background-image = ${V(e,r.fill)}`,"background-image-fit = cover","background-image-position = top-right",`background-image-opacity = ${r.opacity}`,`config-file = ?${r.stem}.tune.conf`,`config-file = ?${r.stem}.off.conf`,""].join(`
312
- `)}function Dn(e,t,n){ke(Su(e),`${JSON.stringify(t,null,2)}
313
- `);for(let r of n){let i=t.palettes[r],s=V(e,`${sn(r)}.conf`);if(i)ke(s,fk(e,i));else Lr(s,{force:!0})}}function vd(e,t){return In(e).filter((n)=>n.startsWith(`${t}.`)||n.startsWith(`${t}@`))}function Pu(e,t){for(let n of vd(e,t))Lr(V(e,n),{force:!0})}function Md(e,t){Pu(e,t.stem);for(let n of[t.original,t.cut])if(n)Lr(V(e,n),{force:!0})}function fd(e,t,n,r){let i=wd(/^background-image\s*=\s*(.*?)\s*$/m.exec(t??"")?.[1]??"");if(!i.startsWith(`${e}.`)||!/^\.[0-9a-f]{8}@fill-\d+\.png$/.test(i.slice(e.length)))return;let s=i.slice(0,i.indexOf("@")),o=r??/^# image (\S+)$/m.exec(t??"")?.[1]??`picture_${s.slice(e.length+1)}`,a=/^# from (.+)$/m.exec(t??"")?.[1],u=Number(/^background-image-opacity\s*=\s*(\S+)/m.exec(t??"")?.[1]??1),c=n.find((l)=>l.startsWith(`${e}-${o}.`));return{key:o,stem:s,fill:i,opacity:Number.isFinite(u)?u:1,...a?{from:a}:{},...c?{original:V(bo,c)}:{}}}function dd(e,t){if(Ru(e))pd(e,t)}function dk(e){let t={version:Mu,palettes:{}};if(!Ru(e))return t;let n=In(V(e,bo)),r=In(e).filter((s)=>s.endsWith(".conf")&&s!=="shown.conf"&&!/\.(tune|off)\.conf$/.test(s)).map((s)=>s.slice(0,-5)),i=V(e,sk);for(let s of new Set([...r,...In(i)])){let o=[],a=fd(s,xn(V(e,`${s}.conf`)),n);if(a)dd(V(e,`${s}.tune.conf`),V(e,`${a.stem}.tune.conf`)),dd(V(e,`${s}.off.conf`),V(e,`${a.stem}.off.conf`)),o.push(a);for(let u of In(V(i,s))){let c=V(i,s,u),l=fd(s,xn(V(c,".conf")),n,u);if(!l)continue;for(let h of In(c)){let f=h===".tune.conf"||h===".off.conf"?`${l.stem}${h}`:`${s}${h}`;if(h!==".conf")pd(V(c,h),V(e,f))}Lr(c,{recursive:!0}),o.push(l)}if(In(V(i,s)).length===0)Lr(V(i,s),{recursive:!0,force:!0});if(o.length>0)o.sort((u,c)=>u.key<c.key?-1:u.key>c.key?1:0),t.palettes[s]={active:(a??o[0]).key,pictures:o}}if(In(i).length===0)Lr(i,{recursive:!0,force:!0});return Dn(e,t,Object.keys(t.palettes)),t}function gd(e,t,n){return t.startsWith("~/")?V(n,t.slice(2)):D$(t)?t:V(e,t)}function Sd(e,t,n){let r=new Map,i=(a,u)=>{let c=xn(a);if(c===void 0)return!1;for(let l of c.split(`
314
- `)){let h=/^([a-z-]+)\s*=\s*(.*?)\s*$/.exec(l);if(h?.[1]==="config-file"&&u<4)i(gd(e,h[2].replace(/^\?/,""),n),u+1);else if(h&&/^background-image(?:-fit|-opacity)?$/.test(h[1]))r.set(h[1],h[2])}return!0};if(!i(V(e,`${sn(t)}.conf`),0))return;let s=r.get("background-image")??"";if(s==="")return;let o=Number(r.get("background-image-opacity")??1);return{image:gd(e,s,n),opacity:Number.isFinite(o)?o:1,cover:r.get("background-image-fit")==="cover"}}function er(e){return`${e.site}_${e.id}`}function Id(e,t,n){let r=We(e),i=st(r),s=i.palettes[t];if(!s||s.pictures.length<2)throw Error(`${t} has no other image`);let o=s.pictures.length,a=(s.pictures.findIndex((u)=>u.key===s.active)+n+o)%o;return s.active=s.pictures[a].key,Dn(r,i,[t]),{key:s.active,at:a+1,of:o}}function Nd(e,t){let n=We(e),r=st(n),i=r.palettes[t];if(!i)throw Error(`${t} has no image`);let s=i.pictures.findIndex((u)=>u.key===i.active),[o]=i.pictures.splice(s,1);Md(n,o);let a=i.pictures[s%Math.max(i.pictures.length,1)];if(a)i.active=a.key;else delete r.palettes[t];return Dn(n,r,[t]),{key:o.key,left:i.pictures.length}}function Rd(e,t,n,r){let i=Ii(n.figure,r),s=Ii(n.fill,r),o=`${sn(e)}.${md("sha1").update(t).update(i).update(s).digest("hex").slice(0,8)}`,a=`${o}@fill-${Math.round(n.focus*100)}.png`;return{stem:o,fill:a,files:[[`${o}.png`,i],[a,s]]}}function Iu(e,t){return V(bo,`${sn(e)}-${t}`)}function Ou(e,t){return t.map(([n,r])=>{let i=V(e,n);return ke(i,r),i})}function $o(e,t,n,r,i,s,o){let a=We(e),u=t.name,c=er(i),l=st(a),h=l.palettes[u]??{active:c,pictures:[]},f=Fu(s.width,s.height),d=Rd(u,c,yd(r,f.width,f.height,o),n.color),g=Iu(u,c),m={key:c,stem:d.stem,fill:d.fill,opacity:n.opacity,tone:n.color,blur:o,window:f,...i.from?{from:i.from}:{},original:`${g}.${i.ext}`,...i.cut?{cut:`${g}.cut.png`}:{}},b=h.pictures.find((E)=>E.key===c);if(b)Md(a,b);X$(V(a,bo),{recursive:!0});let p=Ou(a,[...d.files,[m.original,i.bytes],...m.cut?[[m.cut,uu(Si(r))]]:[]]);return h.pictures=b?h.pictures.map((E)=>E===b?m:E):[...h.pictures,m],h.active=c,l.palettes[u]=h,Dn(a,l,[u]),[...p,V(a,`${sn(u)}.conf`)]}function Fd(e,t,n){let r=We(e),i=st(r),s=i.palettes[t];if(s?.pictures.some((o)=>o.key===n)&&s.active!==n)s.active=n,Dn(r,i,[t])}function Tu(e,t){let n=st(We(e)).palettes[t];if(!n)return[];return[...n.pictures.filter((i)=>i.key===n.active),...n.pictures.filter((i)=>i.key!==n.active)]}var Nu="top-right";function gk(e,t,n,r,i,s,o,a=-1){let u=Math.trunc,c=(s-1)%3,l=u((s-1)/3),h=n*t>=r*e!==!o,f=h?u(i*n/100):u(i*r*e/(100*t)),d=h?u(i*n*t/(100*e)):u(i*r/100),g=u(c*(n-f)/2),m=u(l*(r-d)/2);if(a>=0){if(f>n)g=u((n-f)/2);if(d>r)m=Math.max(r-d,Math.min(0,u(r/2)-u(a*d/100)))}return{x:g,y:m,w:f,h:d}}function Au(e,t){let n=xn(V(e,`${t.stem}.tune.conf`));if(n===void 0)return{};let r=(c)=>new RegExp(`^${c}\\s*=\\s*(.*?)\\s*$`,"m").exec(n)?.[1]??"",i=wd(r("background-image")),s=/@(\d+)-/.exec(i)?.[1],o=/@fill-\d+\.png$/.test(i)?"fill":s?Number(s):r("background-image-fit")==="cover"?"fill":100,a=r("background-image-position").replace("center-center","center")||"center",u=Number(r("background-image-opacity")||1);return{...o!=="fill"?{size:o}:{},...a!==Nu?{position:a}:{},...Number.isFinite(u)&&u!==t.opacity?{opacity:u}:{}}}function Hu(e,t,n,r,i){let s=n.size??"fill",o=n.position??Nu,a=n.opacity??t.opacity;if(s==="fill"&&o===Nu&&a===t.opacity)return;let u=Vn.indexOf(o)+1,c=V(e,`${t.stem}.png`),l=V(e,t.fill),h=!0,f=typeof s==="number"&&(s>100||!r&&o!=="center");if(s===100&&!f)l=c,h=!1;else if(typeof s==="number"){if(!t.tone)throw Error(`${t.stem} was drawn before pictures kept their tone — init draws it again`);let g=Si(qn(new Uint8Array(wo(c)))),{width:m,height:b}=f?mo:g,p=f?Number(/@fill-(\d+)\.png$/.exec(t.fill)?.[1]??50):-1,E=gk(g.width,g.height,m,b,s,u,!1,p);l=V(e,`${t.stem}@${s}-${o}${f?`-${m}x${b}`:""}.png`);let v={x:0,y:0,w:g.width,h:g.height};ke(l,Ii(Mi(po(g,{crop:v,at:E,focus:p},m,b)),t.tone)),h=f}let d=V(e,`${t.stem}.tune.conf`);return ke(d,[`background-image = ${l.startsWith(`${i}/`)?`~${l.slice(i.length)}`:l}`,`background-image-fit = ${h?"cover":"contain"}`,`background-image-position = ${o}`,`background-image-opacity = ${a}`,""].join(`
315
- `)),d}function Pd(e){let t=new Map;for(let[n,r]of Object.entries(st(We(e)).palettes)){let[,i,s]=/^([a-z.]+)_(\d+)$/.exec(r.active)??[];if(i&&s)t.set(n,{site:i,id:Number(s)})}return t}function mk(e){try{let t=yn(new Uint8Array(wo(e)));return t?{width:t.width,height:t.height}:void 0}catch{return}}function ko(e,t,n,r,i,s,o,a,u){let c=We(e),l=n.window??mk(V(c,n.fill))??mo,h=Rd(t,n.key,yd(r,l.width,l.height,s),i.color),f={...n,stem:h.stem,fill:h.fill,opacity:i.opacity,tone:i.color,blur:s,window:l,...u?{cut:`${Iu(t,n.key)}.cut.png`}:{}};if(u)ke(V(c,`${Iu(t,n.key)}.cut.png`),uu(Si(r)));if(h.stem===n.stem)return f;Ou(c,h.files),Hu(c,f,Au(c,n),o,a);let d=V(c,`${n.stem}.off.conf`);if(Ru(d))V$(d,V(c,`${f.stem}.off.conf`));return f}function Od(e,t){let n=We(e),r=st(n),i=new Set,s=[];for(let{name:o,picture:a}of t){let u=r.palettes[o],c=u?.pictures.findIndex((h)=>h.key===a.key)??-1,l=u?.pictures[c];if(!u||!l)continue;if(u.pictures[c]=a,i.add(o),l.stem!==a.stem)s.push(l.stem)}if(i.size===0)return;Dn(n,r,[...i]);for(let o of s)Pu(n,o)}function pk(e,t,n,r){let i=(u)=>u.replace(/^background-image-opacity = (\S+)$/m,(c,l)=>Number(l)===n.opacity?`background-image-opacity = ${r.opacity}`:c);if(n.tone===r.color){let u=V(e,`${n.stem}.tune.conf`),c=xn(u);if(c!==void 0)ke(u,i(c));return{...n,opacity:r.opacity}}let s=vd(e,n.stem).filter((u)=>u.endsWith(".png")).map((u)=>{let c=new Uint8Array(wo(V(e,u)));return[u,Sf(c,r.color)??Ii(Si(qn(c)),r.color)]}),o=(u)=>s.find(([c])=>c===u)?.[1]??new Uint8Array,a=`${sn(t)}.${md("sha1").update(n.key).update(o(`${n.stem}.png`)).update(o(n.fill)).digest("hex").slice(0,8)}`;Ou(e,s.map(([u,c])=>[a+u.slice(n.stem.length),c]));for(let u of["tune","off"]){let c=xn(V(e,`${n.stem}.${u}.conf`));if(c!==void 0)ke(V(e,`${a}.${u}.conf`),i(c.split(n.stem).join(a)))}return{...n,stem:a,fill:a+n.fill.slice(n.stem.length),opacity:r.opacity,tone:r.color}}function Td(e,t){let n=We(e),r=st(n),i=[],s=[];for(let[o,a]of Object.entries(r.palettes)){let u=t.get(o),c=a.pictures.filter((l)=>u&&l.tone&&(l.tone!==u.color||l.opacity!==u.opacity));if(!u||c.length===0)continue;a.pictures=a.pictures.map((l)=>{if(!c.includes(l))return l;let h=pk(n,o,l,u);if(h.stem!==l.stem)s.push(l.stem);return h}),i.push(o)}if(i.length>0){Dn(n,r,i);for(let o of s)Pu(n,o)}return i}function Pt(e){let{slot:t,color:n,opacity:r}=Gr({name:e.name,background:e.background,foreground:e.foreground,cursor:e.cursor,selection:e.selectionBackground,ansi:e.ansi,waived:e.waive},e.signatureSlots);return{name:e.name,...e.base?{base:e.base}:{},group:e.group,...e.native?{native:e.native}:{},...e.lead?{lead:!0}:{},order:e.order,ansiSource:e.ansiSource,...e.booru?{booru:e.booru}:{},...e.booruSites?{booruSites:e.booruSites}:{},...e.role==="default"?{default:!0}:{},background:e.background,foreground:e.foreground,cursor:e.cursor,selection:e.selectionBackground,signature:e.signature,signatureSlots:e.signatureSlots,ansi:e.ansi,gate:Mr(e),...e.waive.length>0?{waived:e.waive}:{},backdrop:{slot:t,color:n,opacity:r},...e.pictures?{pictures:e.pictures}:{}}}function yt(e){return{name:e.name,...e.base?{base:e.base}:{},group:e.group,...e.native?{native:e.native}:{},lead:e.lead===!0,order:e.order,...e.default?{role:"default"}:{},ansiSource:e.ansiSource,...e.booru?{booru:e.booru}:{},...e.booruSites?{booruSites:e.booruSites}:{},background:e.background,foreground:e.foreground,cursor:e.cursor,selectionBackground:e.selection,ansi:e.ansi,signature:e.signature,signatureSlots:e.signatureSlots,ghostty:{iconGhost:e.cursor,iconScreen:[e.cursor,e.selection,e.background]},waive:e.waived??[],...e.pictures?{pictures:e.pictures}:{}}}var wk=6,bk=["ansi1","ansi2","ansi4","ansi3","ansi5","ansi6"];function yo(e){let t=(s)=>s.startsWith("ansi")?e.ansi[Number(s.slice(4))]:s==="foreground"?e.foreground:s==="cursor"?e.cursor:s==="selection"?e.selection:void 0,n=(s)=>s.startsWith("ansi")?`ansi${Number(s.slice(4))%8}`:s,r=new Set,i=[];for(let s of["foreground",...e.signatureSlots,...bk]){let o=t(s);if(i.length===wk||!o||r.has(n(s))||i.includes(o))continue;r.add(n(s)),i.push(o)}return i}function et(e){return e.filter((t)=>t.default!==!0)}function Ci(){return{version:Ve.version,gate:jt,placement:on,palettes:[]}}function $k(e){let[t]=e;if(!t)throw Error("manifest needs at least one theme");return{...Ci(),palettes:e.map(Pt)}}var Lu={id:"meta",emitShared(e){return[{path:"manifest.json",content:`${JSON.stringify($k(e),null,2)}
316
- `}]}};import{existsSync as Ik,readdirSync as _d,readFileSync as Nk}from"node:fs";import{basename as Cd,join as ji}from"node:path";import{existsSync as kk,readFileSync as Ad}from"node:fs";import{homedir as Hd}from"node:os";import{isAbsolute as Ld,join as tr,resolve as yk}from"node:path";var z="official",Qt="ttheme-market.json",Ur="ttheme-market",Ek=/^[a-z0-9](?:[a-z0-9]|-(?=[a-z0-9])){0,38}$/i,vk=/^[\w.-]{1,100}$/,Mk=/^\w[\w.+/-]{0,199}$/;function Rn(e){return tr(e,"ttheme","installed.json")}function ze(e){return e??[z]}function _r(e){try{let{markets:t}=JSON.parse(Ad(Rn(e),"utf8"));return ze(Array.isArray(t)?t.filter((n)=>typeof n==="string"):void 0)}catch{return[z]}}function Oe(e){return Ld(e)}function ht(e){return e!==z&&!Oe(e)}function Nn(e){let t=e.indexOf("#");return ht(e)&&t>=0?e.slice(0,t):e}function Gu(e){let t=e.indexOf("#");return ht(e)&&t>=0?e.slice(t+1):void 0}function Cr(e,t){return Nn(e)===Nn(t)}function Fn(e,t){return!Oe(e)&&(t?.[e]??e===z)}function Sk(e){return!Mk.test(e)||e.includes("..")||e.includes("//")||/(?:[./]|\.lock)$/.test(e)}function Pn(e,t=process.cwd()){if(e===z)return z;if(e==="~"||e.startsWith("~/"))return tr(Hd(),e.slice(1));if(e.startsWith(".")||Ld(e))return yk(t,e);let[n="",r,...i]=e.split("#"),[s,o,...a]=n.replace(/^https:\/\/github\.com\//,"").replace(/\.git$/,"").split("/");if(!s||!Ek.test(s)||!o||!vk.test(o)||a.length>0||i.length>0||r!==void 0&&Sk(r))throw Error(`${e} is not a market — give a repository (alice/ttheme-dust, #v1 pins a tag or branch) or a path (./my-market)`);return`${s.toLowerCase()}/${o}${r===void 0?"":`#${r}`}`}function Gd(e){let t=Gu(e)?.split("/").map(encodeURIComponent).join("/")??"HEAD";return`https://raw.githubusercontent.com/${Nn(e)}/${t}/${Qt}`}function Ud(e){return e.slice(0,e.indexOf("/"))}function Uu(e){return tr(e,"ttheme","markets")}function Ot(e,t){return tr(Uu(e),`${Nn(t).replace("/","--")}.json`)}function Eo(e){return tr(e,"ttheme","market")}function _u(e,t){return tr(Eo(e),t)}function Cu(e,t){if(typeof e!=="string"||typeof t!=="string")return'needs an "owner" (the GitHub handle) and a "name"';return qt(`${e}@${t}/x`)}function ft({owner:e,name:t}){return`${e}@${t}`}function Yt(e){let t=tr(e,Qt);if(!kk(t))throw Error(`${e} has no ${Qt} — \`ttheme market init ${e}\` makes one`);let n;try{n=JSON.parse(Ad(t,"utf8"))}catch{throw Error(`${t} is not valid JSON`)}let r=Cu(n.owner,n.name);if(r)throw Error(`${t} ${r}`);return{owner:n.owner,name:n.name}}function be(e){if(e===z)return"the ttheme catalog";if(!Oe(e))return`github.com/${e}`;let t=Hd();return e===t||e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e}var an="tt1:",jd=["background","foreground","cursor","selection",...Array.from({length:16},(e,t)=>`ansi${t}`)];function nr(e,t=!0){return _r(e).filter(Oe).flatMap((n)=>{try{let r=Yt(n);return[{dir:n,...r,id:ft(r)}]}catch(r){if(t)process.stderr.write(`ttheme: skipping the market at ${n} — ${r.message}
317
- `);return[]}})}function vo(e){return ji(e,"palettes")}function On(e){let t=vo(e);if(!Ik(t))return[];let n=[],r=[];for(let i of _d(t,{withFileTypes:!0}).sort((s,o)=>s.name<o.name?-1:1)){if(i.name.startsWith("."))continue;if(i.isDirectory()){for(let s of _d(ji(t,i.name)).sort())if(s.endsWith(".toml"))n.push({path:ji(t,i.name,s),slug:Cd(s,".toml"),catalog:i.name})}else if(i.name.endsWith(".toml"))r.push({path:ji(t,i.name),slug:Cd(i.name,".toml")})}return[...n,...r]}function Wi(e,t){let n=t.get(e.slug);if(n)return`${e.slug} is also ${n.catalog?`in ${n.catalog}`:"outside a catalog"} — a palette name is used once in a market`;let r=e.catalog===void 0?void 0:_i(e.catalog);return r?`the catalog folder ${JSON.stringify(e.catalog)} ${r}`:void 0}function ju(e,t){let n=ye(t);if(!n)throw Error(`${t} is an official palette — yours are named <you>@<market>/<palette>`);let r=nr(e,!1).find((s)=>s.id===n);if(!r)throw Error(`${n} is not a local market — \`ttheme market add <dir>\` adds the folder that holds it`);let i=Hr(t);return On(r.dir).find((s)=>s.slug===i)?.path??ji(vo(r.dir),`${i}.toml`)}function Rk(e,t){let n=new Map;for(let i of t)if(i.group!==Gi&&!n.has(i.group)){let s=t.find((o)=>o.group===i.group&&o.lead)?.name??"";n.set(i.group,{name:i.group,...i.native?{native:i.native}:{},lead:s})}let r=new Map(t.filter((i)=>!i.default&&!ye(i.name)).map((i)=>[i.name,{group:i.group,order:i.order}]));return{name:e,groups:n,bases:r,open:!0}}function Tt(e,t,n){let r=Hr(e),{native:i,...s}=vu(`${r}.toml`,t,Rk(r,n)),o=ye(e);return{...s,name:e,...o?{group:o,lead:!1}:{}}}function Tn(e,t,n,r=!0){let i=new Map;return On(e).flatMap((s)=>{try{let o=Wi(s,i);if(o)throw Error(o);i.set(s.slug,s);let a=Pt(Tt(`${t}/${s.slug}`,Nk(s.path,"utf8"),n));return[s.catalog?{...a,catalog:s.catalog}:a]}catch(o){if(r)process.stderr.write(`ttheme: skipping ${s.path} — ${o.message}
318
- `);return[]}})}function Mo(e,t,n=!0){return nr(e,n).flatMap(({dir:r,id:i})=>Tn(r,i,t,n))}function Wu(e,t=e.name,n){return{name:t,...e.base?{base:e.base}:{},...e.group!==Gi?{group:e.group}:{},ansiSource:e.ansiSource,...e.booru?{booru:e.booru}:{},...e.booruSites?{booruSites:e.booruSites}:{},signature:e.signatureSlots,background:e.background,foreground:e.foreground,cursor:e.cursor,selection:e.selection,ansi:e.ansi,...e.waived&&e.waived.length>0?{waive:e.waived,reason:n??"kept from the palette"}:{},...e.pictures?{pictures:e.pictures}:{}}}var Je=(e)=>JSON.stringify(e);function Ju(e){let t=["[meta]",`name = ${Je(Hr(e.name))}`,...e.base?[`base = ${Je(e.base)}`]:[],...e.group?[`group = ${Je(e.group)}`]:[],...e.ansiSource?[`ansi_source = ${Je(e.ansiSource)}`]:[],...e.booru?[`booru = ${Je(e.booru)}`]:[],`signature = [${e.signature.map(Je).join(", ")}]`,...e.booruSites?["","[meta.booru_sites]",...Object.entries(e.booruSites).map(([n,r])=>`${n} = [${r.map(Je).join(", ")}]`)]:[],"","[colors]",`background = ${Je(e.background)}`,`foreground = ${Je(e.foreground)}`,`cursor = ${Je(e.cursor)}`,`selection_background = ${Je(e.selection)}`,"ansi = [",...e.ansi.slice(0,8).map((n)=>` ${Je(n)},`),"",...e.ansi.slice(8).map((n)=>` ${Je(n)},`),"]"];if(e.waive&&e.waive.length>0)t.push("","[contrast]",`waive = [${e.waive.map(Je).join(", ")}]`,`reason = ${Je(e.reason??"")}`);for(let n of e.pictures??[]){if(t.push("","[[picture]]",`site = ${Je(n.site)}`,`id = ${n.id}`),n.size!==void 0)t.push(`size = ${typeof n.size==="number"?n.size:Je(n.size)}`);if(n.position!==void 0)t.push(`position = ${Je(n.position)}`);if(n.opacity!==void 0)t.push(`opacity = ${n.opacity}`)}return`${t.join(`
310
+ */import{readdirSync as Mk,rmSync as Sk,statSync as Ik}from"node:fs";import{setDefaultAutoSelectFamilyAttemptTimeout as Nk}from"node:net";import{homedir as Pk}from"node:os";import{join as rs}from"node:path";import{setTimeout as Fk}from"node:timers/promises";var _n=100,pt=25000000,Rk=536870912,Yr=["safe","questionable","explicit"],lr=["nudity","underwear"],rc=["comic","monochrome","sketch","chibi"],Od=["off","5","10","25","50","100"],Td=["off","720","1080","1440","1800","2560"],Hd={nudity:new Set(["nude","naked","topless","bottomless","nipples","naked_towel","undressing"]),underwear:new Set(["underwear","panties","pantsu","bra","lingerie","pantyshot"])},Ok={comic:new Set(["comic","4koma"]),monochrome:new Set(["monochrome","greyscale"]),sketch:new Set(["sketch","lineart","line_art"]),chibi:new Set(["chibi"])},Tk=/^(?:rating|score|width|height|filetype|dimension):/,ns={safe:"s",questionable:"q",explicit:"e"},Ad=8191,Hk=20000,Ak=5000,vd=3000,Md=8,Lk=3000,Ld=60000,Sd=3,xk=3,Ck="https://static.zerochan.net",xd="https://s1.zerochan.net",ic=`ttheme/${nt.version} (+${nt.homepage})`,_k=["orig","tile","thumb","cut"],Cd=new Map,Gk=ny(process.env.TTHEME_FIND_HOSTS),Uk=ty(process.env.TTHEME_FIND_CUTOUTS);Nk(Lk);var jk=["artist","character","copyright"];function Id(e){try{return Mk(e)}catch{return[]}}function Qr(e){return e.startsWith("//")?`https:${e}`:e}function Un(e){return(/\.([a-z0-9]+)(?:\?.*)?$/i.exec(e)?.[1]??"").toLowerCase()}function is(e){let t=e.trim();if(!t)return[];let n=JSON.parse(t);if(Array.isArray(n))return n;let r=n.posts;return Array.isArray(r)?r:[]}function Wk(e){let t=e.trim(),r=(t?JSON.parse(t):{}).tags??{};return new Map(Object.entries(r).map(([i,s])=>[i,String(s)]))}function tc(e,t,n){let r=Qr(String(e??""));return{file:r,width:Number(t)||0,height:Number(n)||0,ext:Un(r)}}function dn(e){return String(e??"").split(/\s+/).filter(Boolean)}function nc(e){let t=typeof e==="number"?new Date(e*1000):typeof e==="string"?new Date(e):void 0;return t&&!Number.isNaN(t.getTime())?t.toISOString().slice(0,10):void 0}function _d(e,t){let n=Qr(String(t.preview??""));if(!t.file||!n||!Number(e.id))return[];let r=Number(e.width??e.image_width)||0,i=Number(e.height??e.image_height)||0;return[{id:Number(e.id),width:r,height:i,file:t.file,preview:n,ext:t.ext,owner:String(t.owner??""),score:Number(e.score)||0,rating:String(e.rating??""),md5:String(t.md5??""),source:String(e.source??""),tags:dn(t.tags),named:t.named,...nc(e.created_at)?{posted:nc(e.created_at)}:{},solo:t.solo,family:Number(e.parent_id)||(e.has_children===!0?Number(e.id):0),smaller:t.versions.filter((s)=>s.file&&s.width>0&&s.height>0&&s.width*s.height<r*i)}]}function Kk(e){let t=Wk(e);return is(e).flatMap((n)=>{let r=Qr(String(n.file_url??"")),i=String(n.tags??""),s=(o)=>dn(i).filter((a)=>t.get(a)===o);return _d(n,{preview:n.preview_url,file:r,ext:String(n.file_ext||Un(r)).toLowerCase(),owner:n.author,md5:n.md5,tags:i,named:{artist:s("artist"),character:s("character"),copyright:s("copyright")},solo:void 0,versions:[tc(n.jpeg_url,n.jpeg_width,n.jpeg_height),tc(n.sample_url,n.sample_width,n.sample_height)]})})}function Jk(e){return is(e).flatMap((t)=>{let n=Qr(String(t.file_url??"")),r=String(t.tag_string??""),i=t.media_asset??{};return _d(t,{preview:i.variants?.find((s)=>s.type==="360x360")?.url??t.preview_file_url,file:n,ext:String(t.file_ext||Un(n)).toLowerCase(),owner:"",md5:t.md5,tags:r,named:{artist:dn(t.tag_string_artist),character:dn(t.tag_string_character),copyright:dn(t.tag_string_copyright)},solo:r.split(/\s+/).includes("solo"),versions:(i.variants??[]).map((s)=>tc(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 Gd(e){return e.toLowerCase().replace(/\s+/g,"_")}function Bk(e){return(Array.isArray(e)?e:[]).map((t)=>Gd(String(t)))}function qk(e){return String(e??"").replace(/[^0-9a-z]+/gi,".").replace(/^\.+|\.+$/g,"")||"zerochan"}function zk(e){let t=e.trim(),n=t?JSON.parse(t):{};return(Array.isArray(n.items)?n.items:n.id?[n]:[]).flatMap((i)=>{let s=Number(i.id);if(!s)return[];let o=Bk(i.tags),a=Qr(String(i.full??""));return[{id:s,width:Number(i.width)||0,height:Number(i.height)||0,file:a,ext:Un(a),preview:`${xd}/${qk(i.tag??i.primary)}.600.${s}.jpg`,owner:"",score:0,rating:o.some((u)=>Hd.nudity.has(u))?"q":"g",md5:String(i.md5??i.hash??""),source:String(i.source??""),tags:o,named:{artist:[],character:[],copyright:[]},solo:o.includes("solo"),family:0,smaller:[]}]})}var Yk={mangaka:"artist",studio:"artist",character:"character",series:"copyright",game:"copyright"};function Nd(e){return e.replace(/&(?:#(\d+)|amp|quot|apos|lt|gt);/g,(t,n)=>n?String.fromCharCode(Number(n)):{"&amp;":"&","&quot;":'"',"&apos;":"'","&lt;":"<","&gt;":">"}[t]??t)}function Qk(e){let t={artist:[],character:[],copyright:[]};for(let[,r,i]of e.matchAll(/<li class="([a-z]+)[^"]*"[^>]*\bdata-tag="([^"]*)"/g)){let s=Yk[r],o=Gd(Nd(i));if(s&&!t[s].includes(o))t[s].push(o)}let n=nc(/"datePublished":\s*"([^"]+)"/.exec(e)?.[1]);return{named:t,source:"",owner:Nd(/\buploader = \{\s*name: '([^']*)'/.exec(e)?.[1]??""),...n?{posted:n}:{}}}function Zk(e){return Number(/Zerochan has ([\d,]+) /.exec(e)?.[1]?.replace(/,/g,"")??0)}function Vk(e){return is(e).flatMap((t)=>{let n=String(t.value??"");return n?[{value:n,count:Number(t.post_count)||0}]:[]})}function Xk(e){return is(e).flatMap((t)=>{let n=String(t.name??"");return n?[{value:n,count:Number(t.count)||0}]:[]})}function Dk(e){return Number(/count="(\d+)"/.exec(e)?.[1]??0)}function ey(e){let n=(e.trim()?JSON.parse(e):{}).counts?.posts;return n===null?Number.NaN:Number(n)||0}function ty(e){let t=new Map;for(let n of(e??"").split(/\s+/).filter(Boolean)){let r=n.indexOf("=");if(r>0)t.set(n.slice(0,r),n.slice(r+1).split(",").filter(Boolean))}return t}function ny(e){let t=new Map;for(let n of(e??"").split(/[\s,]+/).filter(Boolean)){let r=n.indexOf("="),i=n.slice(0,r);try{let s=new URL(n.slice(r+1));if(i&&s.protocol==="https:")t.set(i,s.origin)}catch{}}return t}function Go(e,t,n,r){let i=(e??"").split(/\s+/);if(r!==void 0&&i.includes(r))return[];let s=t.filter((o)=>i.includes(o));return s.length>0?s:[...n]}function fr(e){return Go(e,Yr,["safe"])}function Zr(e){return Go(e,lr,lr,"none")}function Uo(e){return Go(e,rc,[],"none")}function ss(e){let t=V.map((n)=>n.name);return Go(e,t,t)}function sc(e,t,n){return{score:Number(e)||0,size:Number(t)||0,png:n==="on"}}function os(e){return[...new Set((e??"").toLowerCase().split(/[\s,]+/).map((t)=>t.replace(/^-+/,"")).filter(Boolean))]}function oc(e,t,n){return{safe:new Set(e),questionable:new Set(t),explicit:new Set(n)}}function ac(e){let t=Gk.get(e.key),n=Uk.get(e.key);return{...e,origin:t??e.origin,moved:t!==void 0&&t!==e.origin,cutouts:n??e.cutouts,vouched:e.vouched&&n===void 0}}function Ud(e){return e.length<2?e.join(""):e.map((t)=>`~${t}`).join(" ")}function jd(e){return e>0?[`width:>=${e}`,`height:>=${e}`]:[]}function Pd(e){let t=ac(e),n=(r)=>new URLSearchParams({api_version:"2",include_tags:"1",...r});return{...t,scored:!0,narrow:({score:r,size:i})=>[...r>0?[`score:>=${r}`]:[],...jd(i)],cutouts:Ud(t.cutouts),ratings:oc([ns.safe],[ns.questionable],[ns.explicit]),rate:(r)=>{let[i]=r;if(r.length===1&&i)return`rating:${ns[i]}`;let s=Yr.filter((a)=>!r.includes(a)),[o]=s;return s.length===1&&o?`-rating:${ns[o]}`:""},best:"order:score",tagBudget:Number.POSITIVE_INFINITY,postsUrl:(r,i)=>`${t.origin}/post.json?${n({limit:String(_n),page:String(i+1),tags:r})}`,countUrl:(r)=>`${t.origin}/post.xml?${new URLSearchParams({limit:"1",tags:r})}`,postUrl:(r)=>`${t.origin}/post.json?${n({tags:`id:${r}`})}`,pageUrl:(r)=>`${t.origin}/post/show/${r}`,parse:Kk,count:Dk,uploadedBy:(r)=>`user:${r}`}}function ry(e){let t=ac(e),n=oc(["g"],["s","q"],["e"]);return{...t,scored:!0,narrow:({score:r,size:i,png:s})=>[...r>0?[`score:>=${r}`]:[],...jd(i),...s?["filetype:png"]:[]],cutouts:Ud(t.cutouts),ratings:n,rate:(r)=>r.length===Yr.length?"":`rating:${r.flatMap((i)=>[...n[i]]).join(",")}`,best:"order:score",tagBudget:2,postsUrl:(r,i)=>`${t.origin}/posts.json?${new URLSearchParams({limit:String(_n),page:String(i+1),tags:r})}`,countUrl:(r)=>`${t.origin}/counts/posts.json?${new URLSearchParams({tags:r})}`,postUrl:(r)=>`${t.origin}/posts.json?${new URLSearchParams({limit:"1",tags:`id:${r}`})}`,pageUrl:(r)=>`${t.origin}/posts/${r}`,parse:Jk,count:ey,uploadedBy:(r)=>`user:${r}`}}function ec(e){return e.split(/\s+/).filter((t)=>t&&!/^(?:order|dimension):/.test(t)).map((t)=>t.split("_").map(encodeURIComponent).join("+")).join(",")}function Fd(e){let t=e.split(/\s+/),n=t.find((r)=>r.startsWith("dimension:"))?.slice(10);return{s:t.includes("order:fav")?"fav":"id",...n?{d:n}:{}}}function iy(e){let t=ac(e);return{...t,scored:!1,narrow:({size:n})=>n>=1800?["dimension:huge"]:n>0?["dimension:large"]:[],cutouts:t.cutouts[0]??"",ratings:oc(["g"],["q"],["e"]),rate:()=>"",best:"order:fav",tagBudget:3,missing:404,postsUrl:(n,r)=>`${t.origin}/${ec(n)}?${new URLSearchParams({json:"",l:String(_n),p:String(r+1),...Fd(n)})}`,countUrl:(n)=>`${t.origin}/${ec(n)}?${new URLSearchParams({xml:"",l:"1"})}`,postUrl:(n)=>`${t.origin}/${n}?json=`,pageUrl:(n)=>`${t.origin}/${n}`,parse:zk,count:Zk,credits:Qk,counts:(n)=>ec(n).split(",").length===1&&!("d"in Fd(n)),guesses:(n)=>(n.tags.includes("transparent_background")?["png","jpg"]:["jpg","png"]).map((r)=>n.preview.replace(xd,Ck).replace(/\.600\.(\d+)\.jpg$/,`.full.$1.${r}`))}}function sy(e){let t=Rd(`https://${e}`);return V.find((n)=>Rd(n.origin)===t)}function uc(e){return e.split(/\s+/).filter((t)=>t&&!Tk.test(t)).length}function jo(e,t){let n=e.trim();if(/^\d+$/.test(n))return{site:t,id:Number(n)};let r=/^([\w.]+):(\d+)$/.exec(n);if(r){let a=V.find((u)=>u.key===r[1]||u.name===r[1]);return a&&{site:a,id:Number(r[2])}}let i;try{i=new URL(n)}catch{return}let s=sy(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 V=[ry({key:"danbooru",name:"danbooru",origin:"https://shima.donmai.us",cutouts:["transparent_background"],vouched:!1,ansi:2}),Pd({key:"konachan",name:"konachan",origin:"https://konachan.net",cutouts:["transparent","vector"],vouched:!1,ansi:6}),Pd({key:"yande",name:"yande.re",origin:"https://yande.re",cutouts:["transparent_png"],vouched:!0,ansi:5}),iy({key:"zerochan",name:"zerochan",origin:"https://www.zerochan.net",cutouts:["transparent_background"],vouched:!1,ansi:3})],Ft=V.find((e)=>e.key==="danbooru"),jn=134217728;function Rt(e,t){let n=V.indexOf(e);return(n===-1?V.length:n)*jn+t}function Rd(e){let t;try{t=new URL(e).hostname}catch{return""}return t.split(".").slice(-2).join(".")}function Vr(e,t,n=t){return t.mirror&&n===t?{site:Ft,url:t.mirror.file}:{site:e,url:n.file}}function Wo(e,t){return t.mirror?{site:Ft,url:t.mirror.preview}:{site:e,url:t.preview}}function Ko(e,t=lr){return e.tags.filter((n)=>t.some((r)=>Hd[r].has(n)))}function Wd(e,t){return e.tags.filter((n)=>t.some((r)=>Ok[r].has(n)))}function Jo(e,t,n=["safe"]){return n.some((r)=>e.ratings[r].has(t.rating))}function Kd(e,t){return e.rate(["safe"])===""?void 0:Yr.find((n)=>e.ratings[n].has(t.rating))}function Vt(e){return[e,...e.smaller].find((t)=>t.width*t.height<=pt)}function Jd(e){let t=new Map;for(let[n,r]of[...e].sort(([i],[s])=>i<s?-1:1)){if(r==="")continue;t.set(r,[...t.get(r)??[],n])}return t}function Xr(){return rs(process.env.XDG_CACHE_HOME??rs(Pk(),".cache"),"ttheme")}function Xt(e){return rs(Xr(),e.key)}function Bd(e=Rk,t=Xr()){let n=[],r=0;for(let i of Id(t))for(let s of _k){let o=rs(t,i,s);for(let a of Id(o)){let u=rs(o,a);try{let{size:c,mtimeMs:l}=Ik(u);n.push({path:u,size:c,at:l}),r+=c}catch{}}}n.sort((i,s)=>i.at-s.at);for(let i of n){if(r<=e)return;try{Sk(i.path,{force:!0}),r-=i.size}catch{}}}function oy(e,t){if(e!==null&&/^\s*\d+\s*$/.test(e))return Number(e)*1000;let n=e===null?Number.NaN:Date.parse(e);return Number.isNaN(n)?Ld:Math.max(0,n-t)}function Gn(e){return Cd.get(e.key)??0}function ay(e){for(let t=e;t instanceof Error;t=t.cause)if(t.code==="ECONNRESET")return!0;return!1}function uy(e){return(e.headers.get("server")??"").startsWith("cloudflare")&&e.headers.get("cf-mitigated")==="challenge"}function cy(e,t){let n=new URL(t,e);if(!n.search)n.search=new URL(e).search;return n.href}async function hr(e,t,n,r={},i=Hk){let s=t;for(let o=1,a=0;;o++){let u=Gn(e)-Date.now();if(u>0)await Fk(u,void 0,{signal:n});let c;try{c=await fetch(s,{headers:{"User-Agent":ic,Referer:`${e.origin}/`,...r},redirect:"manual",signal:i?AbortSignal.any([n,AbortSignal.timeout(i)]):n})}catch(h){if(o<Sd&&!n.aborted&&ay(h))continue;throw h}let l=c.headers.get("location");if(l&&c.status>=300&&c.status<400&&a<xk){await c.body?.cancel(),s=cy(s,l),a++,o--;continue}if(c.status===429&&o<Sd){await c.body?.cancel();let h=oy(c.headers.get("retry-after"),Date.now());if(h>Ld)throw Error(`${e.name} asks to wait ${Math.ceil(h/1000)}s`);Cd.set(e.key,Math.max(Gn(e),Date.now()+h));continue}if(!c.ok)throw await c.body?.cancel(),Object.assign(Error(uy(c)?`${e.name} is behind a Cloudflare challenge`:`${e.name} answered ${c.status}`),{status:c.status});return c}}async function Bo(e,t,n){try{return await(await hr(e,t,n)).text()}catch(r){if(e.missing!==void 0&&r.status===e.missing)return"";throw r}}async function qd(e,t,n,r){return e.parse(await Bo(e,e.postsUrl(t,n),r))}async function cc(e,t,n){return e.count(await Bo(e,e.countUrl(t),n))}async function as(e,t,n){let[r]=e.parse(await Bo(e,e.postUrl(t),n));return r}async function qo(e,t,n){return e.credits?.(await Bo(e,e.pageUrl(t),n))}var ly=/^https?:\/\/(?:i\.pximg\.net|i\d*\.pixiv\.net|img\d*\.pixiv\.net)\/\S*\/(\d+)(?:_p\d+)?(?:_\w+)?\.\w+(?:[?#]\S*)?$/i,hy=/^https?:\/\/(?:www\.)?pixiv\.net\/member_illust\.php\?\S*\billust_id=(\d+)/i;function us(e){let t=ly.exec(e)?.[1]??hy.exec(e)?.[1];return t?`https://www.pixiv.net/artworks/${t}`:e}function zo(e,t){return e.credits!==void 0&&t.named.artist.length===0}function cs(e,t){for(let n of jk){let r=t.named?.[n]??[];if(e.named[n].length===0&&r.length>0)e.named[n]=r}if(e.source||=t.source??"",e.owner||=t.owner??"",!e.posted&&t.posted)e.posted=t.posted}function fy(e){let t=new URLSearchParams({limit:String(2*_n),only:"md5,tag_string,tag_string_artist,tag_string_character,tag_string_copyright,source,file_url",tags:`md5:${e.join(",")}`});return`${Ft.origin}/posts.json?${t}`}function dy(e){return new Map(is(e).flatMap((t)=>{let n=String(t.md5??"");return n?[[n,{tags:dn(t.tag_string),named:{artist:dn(t.tag_string_artist),character:dn(t.tag_string_character),copyright:dn(t.tag_string_copyright)},source:String(t.source??""),file:Qr(String(t.file_url??""))}]]:[]}))}function Yo(e,t){for(let n of e){let r=t.get(n.md5);if(!r)continue;if(n.tags=[...new Set([...n.tags,...r.tags])],cs(n,r),n.solo=r.tags.includes("solo"),r.file.includes("/original/")){if(n.mirror={file:r.file,preview:r.file.replace("/original/","/360x360/").replace(/\.[a-z0-9]+$/i,".jpg")},!n.file)n.file=r.file,n.ext=Un(r.file)}}}async function Qo(e,t){let n=new Map;if(Gn(Ft)>Date.now())return n;for(let r=0;r<e.length;r+=_n){let i=await(await hr(Ft,fy(e.slice(r,r+_n)),t,{},Ak)).text();for(let[s,o]of dy(i))n.set(s,o)}return n}async function Zo(e,t,n){if(t.file||!e.guesses)return;for(let r of e.guesses(t))try{let i=await hr(e,r,n,{Range:`bytes=0-${Ad}`}),s=xn(new Uint8Array(await i.arrayBuffer()));return t.file=r,t.ext=Un(r),s}catch(i){if(n.aborted||i.status!==404)throw i}throw Error(`${e.name} keeps no png or jpg of ${t.id}`)}async function zd(e,t){if(Gn(Ft)<=Date.now())try{let i=new URLSearchParams({"search[query]":e,"search[type]":"tag_query",limit:String(Md)}),s=`${Ft.origin}/autocomplete.json?${i}`;return Vk(await(await hr(Ft,s,t,{},vd)).text())}catch(i){if(t.aborted)throw i}let n=V.find((i)=>i.key==="yande"),r=new URLSearchParams({name:e,order:"count",limit:String(Md)});return Xk(await(await hr(n,`${n.origin}/tag.json?${r}`,t,{},vd)).text())}async function Yd(e,t,n){let r=await hr(e,t,n,{Range:`bytes=0-${Ad}`});return xn(new Uint8Array(await r.arrayBuffer()))}async function Vo(e,t,n,r){let i=await hr(e,t,n,{},0),s=Number(i.headers.get("content-length"))||0,o=i.body?.getReader();if(!o)return new Uint8Array(await i.arrayBuffer());let a=[],u=0;for(;;){let{done:h,value:f}=await o.read();if(h)break;a.push(f),u+=f.length,r?.(u,s)}let c=new Uint8Array(u),l=0;for(let h of a)c.set(h,l),l+=h.length;return c}var bt=["top-left","top-center","top-right","center-left","center","center-right","bottom-left","bottom-center","bottom-right"],ls="Original",py=1e6,Dt="_groups.toml",Qd=3,Zd=8,lc="[a-z0-9]+(?:-[a-z0-9]+)*",by=new RegExp(`^(?:(${lc})@(${lc})/)?(${lc})$`),eg=["background","foreground","cursor","selection"];function fe(e,t){throw Error(`${e}: ${t}`)}function dr(e,t,n){if(typeof n!=="string"||!Pn(n))fe(e,`${t} must be "#rrggbb" (lowercase), got ${JSON.stringify(n)}`);return n}function fs(e,t,n){if(typeof n!=="string"||n.length===0)fe(e,`${t} must be a non-empty string`);return n}function en(e){return e.replace("@","--").replace("/","--")}function ve(e){let t=e.indexOf("/");return t<0?void 0:e.slice(0,t)}function ei(e){return e.slice(e.indexOf("/")+1)}function tn(e){let t=by.exec(e);if(!t)return"takes lowercase letters, digits and single hyphens, as <palette> or <owner>@<market>/<palette>";if((t[1]?.length??0)>39)return"has an owner longer than a GitHub handle can be";return(t[2]?.length??0)>40||(t[3]?.length??0)>40?"is longer than 40 characters":void 0}function ds(e){if(/[\p{Cc}"$`\\]/u.test(e))return"holds a control character, a quote, $, ` or \\";return e.length>80?"is longer than 80 characters":void 0}function hs(e,t,n){let r=fs(e,t,n),i=ds(r);if(i)fe(e,`${t} ${JSON.stringify(r)} ${i}`);return r}function Vd(e,t,n){let r=fs(e,t,n),i=tn(r);if(i)fe(e,`${t} "${r}" ${i}`);return r}function Dr(e){return e&&typeof e==="object"?e:{}}function wy(e,t,n){if(t===void 0)return[n.cursor,n.selectionBackground,n.background];let r=Array.isArray(t)?t:[t];if(r.length===0)fe(e,"ghostty.icon_screen must not be empty");return r.map((i,s)=>dr(e,`ghostty.icon_screen[${s}]`,i))}function $y(e,t,n){let r=Dr(t);return{iconGhost:r.icon_ghost===void 0?n.cursor:dr(e,"ghostty.icon_ghost",r.icon_ghost),iconScreen:wy(e,r.icon_screen,n)}}function ky(e){return new Map([...eg.map((t)=>[t,e[t]]),...e.ansi.map((t,n)=>[`ansi${n}`,t])])}function yy(e,t,n){if(!Array.isArray(t)||t.length!==Qd)fe(e,`meta.signature must name exactly ${Qd} palette slots`);let r=ky(n),i=[],s=[];for(let[o,a]of t.entries()){let u=`meta.signature[${o}]`,c=fs(e,u,a),l=r.get(c);if(l===void 0)fe(e,`${u} ${JSON.stringify(a)} is not a palette slot — use ${eg.join(", ")} or ansi0-ansi15`);i.push(c),s.push(l)}if(new Set(s).size!==s.length)fe(e,"meta.signature slots must resolve to three different colors");return{names:i,colors:s}}function Ey(e,t,n){if(t===void 0)return;if(!n)fe(e,"meta.booru_sites renames meta.booru per site, so it needs meta.booru");if(!t||typeof t!=="object"||Array.isArray(t))fe(e,'meta.booru_sites must be a table of site = "tag" or site = ["tag", ...]');let r={};for(let[i,s]of Object.entries(t)){let o=V.find((u)=>u.key===i);if(!o)fe(e,`meta.booru_sites.${i} is not a find site — use ${V.map((u)=>u.key).join(", ")}`);let a=typeof s==="string"?[s]:Array.isArray(s)?s:void 0;if(!a||a.some((u)=>typeof u!=="string"||u===""||/\s/.test(u)))fe(e,`meta.booru_sites.${i} must be one tag or a list of tags, got ${JSON.stringify(s)}`);if(a.length>1&&Number.isFinite(o.tagBudget))fe(e,`meta.booru_sites.${i} takes one tag — ${o.name} searches ${o.tagBudget} tags at a time`);r[i]=a}return r}function vy(e,t){if(t===void 0)return;if(!Array.isArray(t)||t.length===0||t.length>Zd)fe(e,`[[picture]] holds 1 to ${Zd} pictures`);return t.map((n,r)=>{let i=Dr(n),s=`picture[${r}]`,o=V.find((l)=>l.key===i.site);if(!o)fe(e,`${s}.site must be one of ${V.map((l)=>l.key).join(", ")}`);if(typeof i.id!=="number"||!Number.isSafeInteger(i.id)||i.id<=0)fe(e,`${s}.id must be the post's number on ${o.name}`);let{size:a,position:u,opacity:c}=i;if(a!==void 0&&a!=="fill"&&!(Number.isInteger(a)&&Number(a)>=20&&Number(a)<=999))fe(e,`${s}.size must be "fill" or a percentage from 20 to 999`);if(u!==void 0&&!bt.includes(u))fe(e,`${s}.position must be one of ${bt.join(", ")}`);if(c!==void 0&&!(typeof c==="number"&&c>=0&&c<=1))fe(e,`${s}.opacity must be a number from 0 to 1`);return{site:o.key,id:i.id,...a!==void 0?{size:a}:{},...u!==void 0?{position:u}:{},...c!==void 0?{opacity:c}:{}}})}function tg(e,t){try{return Du(t)}catch(n){fe(e,`is not valid TOML — ${(n instanceof Error?n.message:String(n)).split(`
311
+ `)[0]}`)}}function My(e){let n=tg(Dt,Xd(Dd(e,Dt),"utf8")).group;if(!Array.isArray(n)||n.length===0)fe(Dt,"needs at least one [[group]] table");return n.map((r)=>{let i=Dr(r);return{name:hs(Dt,"group.name",i.name),native:i.native===void 0?void 0:hs(Dt,"group.native",i.native),lead:fs(Dt,"group.lead",i.lead)}})}function Sy(e,t){if(!Array.isArray(t)||t.length===0)fe(e,'meta.native_names must be a list of names, like ["後藤ひとり"]');return t.map((n,r)=>{let i=hs(e,`meta.native_names[${r}]`,n);if(i.includes("|"))fe(e,`meta.native_names[${r}] ${JSON.stringify(i)} contains |`);return i})}function hc(e,t,n){let r=tg(e,t),i=Dr(r.meta),s=Dr(r.colors),o=Dr(r.contrast),a=s.ansi;if(!Array.isArray(a)||a.length!==16)fe(e,`colors.ansi must hold exactly 16 colors, got ${Array.isArray(a)?a.length:typeof a}`);let u=Vd(e,"meta.name",i.name);if(u!==n.name)fe(e,`meta.name "${u}" does not match its file — it lives at ${n.name}`);let c=n.open===!0;for(let H of["order","role"])if(c&&i[H]!==void 0)fe(e,`meta.${H} is for the official palettes — a market palette follows its base`);let l=i.role;if(l!==void 0&&l!=="default")fe(e,`meta.role must be "default", got ${JSON.stringify(l)}`);let h=i.base===void 0?void 0:Vd(e,"meta.base",i.base);if(h!==void 0&&!c)fe(e,"meta.base is for market palettes");let f=h===void 0?void 0:n.bases?.get(h),d=c&&i.group===void 0?f?.group??ls:hs(e,"meta.group",i.group),g=n.groups.get(d);if(!g&&!(c&&(d===ls||n.open)))fe(e,`meta.group "${d}" has no [[group]] table in ${Dt}`);let p=dr(e,"colors.background",s.background),b=dr(e,"colors.foreground",s.foreground),m=dr(e,"colors.cursor",s.cursor),$=dr(e,"colors.selection_background",s.selection_background),k=a.map((H,A)=>dr(e,`colors.ansi[${A}]`,H)),S=yy(e,i.signature,{background:p,foreground:b,cursor:m,selection:$,ansi:k}),w=i.booru===void 0?void 0:fs(e,"meta.booru",i.booru);if(w!==void 0&&/[\s\p{Cc}]/u.test(w))fe(e,`meta.booru must be a single booru tag, got ${JSON.stringify(w)}`);let M=Ey(e,i.booru_sites,w),y=i.native_names===void 0?void 0:Sy(e,i.native_names),N=Array.isArray(o.waive)?o.waive.map(String):[];if(N.length>0&&typeof o.reason!=="string")fe(e,"contrast.waive needs a contrast.reason explaining why");let R=vy(e,r.picture);return{name:u,...h?{base:h}:{},group:d,native:g?.native,...y?{nativeNames:y}:{},lead:!c&&g?.lead===u,order:c?f?.order??py:Number(i.order),role:l,ansiSource:c&&i.ansi_source===void 0?h??"original":hs(e,"meta.ansi_source",i.ansi_source),...w?{booru:w}:{},...M?{booruSites:M}:{},background:p,foreground:b,cursor:m,selectionBackground:$,ansi:k,signature:S.colors,signatureSlots:S.names,ghostty:$y(e,r.ghostty,{background:p,cursor:m,selectionBackground:$}),waive:N,waiveReason:typeof o.reason==="string"?o.reason:void 0,...R?{pictures:R}:{}}}function ng(e){let t=My(e),n=new Map(t.map((s)=>[s.name,s]));if(n.size!==t.length)fe(Dt,"group.name must be unique");let r=gy(e).filter((s)=>s.endsWith(".toml")&&!s.startsWith("_")).map((s)=>hc(s,Xd(Dd(e,s),"utf8"),{name:my(s,".toml"),groups:n})).sort((s,o)=>s.order-o.order);if(new Set(r.map((s)=>s.order)).size!==r.length)throw Error("themes: meta.order must be unique across all themes");for(let s of t){let o=r.filter((a)=>a.group===s.name);if(o.length===0)fe(Dt,`group "${s.name}" has no themes`);if(!o.some((a)=>a.name===s.lead))fe(Dt,`group "${s.name}" lead "${s.lead}" is not one of its themes`)}return r}function rg(e){return e.filter((t)=>t.role===void 0)}function gr(e){let t=(r,i)=>r<i?-1:r>i?1:0,n=(r)=>ve(r.name)?r.name:r.base??r.name;return[...e].sort((r,i)=>Number(ve(r.name)!==void 0)-Number(ve(i.name)!==void 0)||t(r.group.toLowerCase(),i.group.toLowerCase())||Number(r.catalog===void 0)-Number(i.catalog===void 0)||t((r.catalog??"").toLowerCase(),(i.catalog??"").toLowerCase())||t(n(r),n(i))||Number(r.base!==void 0)-Number(i.base!==void 0)||t(r.name,i.name))}var Xo={width:2560,height:1550},Ry=2560,Oy=0.1,Ty=0.99,Hy=2,gn={tall:1.15,reach:0.4,widest:0.95,headroom:0.04,margin:0.03,stands:12},Ay=ze(ot("#19161e","#9b86c8",0.2)),Ly="shelf",ta="originals",xy="images.json",fc=1;function Cy(e,t){if(t==="background"||t==="foreground"||t==="cursor")return e[t];if(t==="selection"&&e.selection)return e.selection;let n=/^ansi(\d|1[0-5])$/.exec(t),r=n?e.ansi[Number(n[1])]:void 0;if(!r)throw Error(`${e.name} has no slot ${t}`);return r}function ig(e){if(e(1))return 1;let t=0,n=1;for(let r=0;r<40;r++){let i=(t+n)/2;if(e(i))t=i;else n=i}return t}function sg(e,t){let n=Cy(e,t),i=ig((c)=>nf({name:e.name,background:ot(e.background,n,c),foreground:e.foreground,ansi:e.ansi,waive:e.waived??[]}).length===0),s=ig((c)=>ze(ot(e.background,n,c))<=Ay),o=Math.floor(Math.min(i,s)*100)/100,a=Ue(e.background),u=Math.hypot(...Ue(n).map((c,l)=>(c-(a[l]??0))*o));return{slot:t,color:n,cap:i,matched:s,opacity:o,reach:u}}function ni(e,t){let n=sg(e,"cursor");if(n.opacity>=Oy)return n;return t.filter((r)=>r!=="cursor"&&r!=="background").map((r)=>sg(e,r)).reduce((r,i)=>i.reach>r.reach?i:r,n)}function _y(e){return hd(e)??{x:0,y:0,w:e.width,h:e.height}}function bc(e,t){if(e<=0||t<=0)return Xo;let n=Math.min(1,Xo.width/Math.max(e,t));return{width:Math.round(e*n),height:Math.round(t*n)}}function dg(e,t,n,r){if(r<gn.stands){let u=e.w*n>e.h*t?{x:e.x+(e.w-e.h*t/n)/2,y:e.y,w:e.h*t/n,h:e.h}:{x:e.x,y:e.y,w:e.w,h:e.w*n/t};return{crop:u,at:{x:0,y:0,w:t,h:n},focus:(u.y-e.y+u.h/2)/e.h}}let i=Math.max(gn.tall*n,gn.reach*t*e.h/e.w),s=i*e.w/e.h;if(s>gn.widest*t)s=gn.widest*t,i=s*e.h/e.w;let o=gn.headroom*n,a=Math.min(1,(n-o)/i);return{crop:{x:e.x,y:e.y,w:e.w,h:e.h*a},at:{x:t*(1-gn.margin)-s,y:o,w:s,h:i*a},focus:Math.min(1,(n/2-o)/i)}}function gg(e,t){return 0.299*(e[t]??0)+0.587*(e[t+1]??0)+0.114*(e[t+2]??0)}function Gy(e,t){let n=new Uint32Array(256),r=Math.max(1,Math.floor(t.w*t.h/400000)),i=0;for(let o=0;o<t.w*t.h;o+=r){let a=((t.y+Math.floor(o/t.w))*e.width+t.x+o%t.w)*4;if((e.data[a+3]??0)>=128){let u=Math.round(gg(e.data,a));n[u]=(n[u]??0)+1,i++}}let s=0;for(let o=0;o<256&&i>0;o++)if(s+=n[o]??0,s>=i*Ty)return Math.min(Hy,Math.max(1,255/Math.max(1,o)));return 1}function Uy(e,t){let n=new Uint8Array(e.width*e.height);for(let r=0;r<n.length;r++){let i=r*4;n[r]=Math.round(Math.min(255,gg(e.data,i)*t)*(e.data[i+3]??0)/255)}return{width:e.width,height:e.height,data:n}}function Do(e,t,n,r){let i=new Float32Array(n*r),s=Math.max(0,Math.round(t.at.x)),o=Math.max(0,Math.round(t.at.y)),a=Math.min(n,Math.round(t.at.x+t.at.w)),u=Math.min(r,Math.round(t.at.y+t.at.h));if(a>s&&u>o){let c=t.crop.w/t.at.w,l=t.crop.h/t.at.h,h={x:t.crop.x+(s-t.at.x)*c,y:t.crop.y+(o-t.at.y)*l,w:(a-s)*c,h:(u-o)*l},f=gd(e,h,a-s,u-o);for(let d=o;d<u;d++)i.set(f.data.subarray((d-o)*(a-s),(d-o+1)*(a-s)),d*n+s)}return{width:n,height:r,data:i}}function wc(e){let t=_y(e);return{box:t,clear:fn(e,t),ink:Uy(e,Gy(e,t))}}function mg(e,t,n,r){let{box:i,clear:s,ink:o}=wc(e),a=dg(i,t,n,s),u=Math.min(1,Ry/Math.max(i.w,i.h)),c={x:0,y:0,w:Math.round(i.w*u),h:Math.round(i.h*u)},l=Do(o,{crop:i,at:c,focus:a.focus},c.w,c.h),h=Do(o,a,t,n);return{figure:Vi(Lo(l,r*c.w*a.crop.w/(i.w*a.at.w))),fill:Vi(Lo(h,r)),focus:a.focus}}function jy(e,t,n,r){let i=Ue(t),s=Ue(n),o=new Uint8Array(e.width*e.height*4);for(let a=0;a<e.data.length;a++){let u=(e.data[a]??0)/255*r;for(let c=0;c<3;c++)o[a*4+c]=Math.round((i[c]??0)+((s[c]??0)-(i[c]??0))*u);o[a*4+3]=255}return{width:e.width,height:e.height,data:o}}function pg(e,t,n,r,i,s,o){let{box:a,clear:u,ink:c}=e,l=dg(a,r,i,u),h=Math.round(100*l.at.w/l.crop.w/Math.min(r/a.w,i/a.h)),f=o?.size??"fill",d=f==="fill"?l:{crop:a,at:vg(a.w,a.h,r,i,f,o?.at??5,!1,f>100?Math.round(l.focus*100):-1),focus:l.focus};return{image:jy(Vi(Lo(Do(c,d,r,i),s)),t.background,n.color,o?.opacity??n.opacity),fill:h}}function je(e){return X(e,"ttheme","backgrounds")}function dc(e){return X(e,xy)}function Kn(e){try{return ea(e,"utf8")}catch{return}}function Wn(e){try{return Py(e)}catch{return[]}}function ut(e){let t=Kn(dc(e));if(t===void 0)return Wy(e);let n=JSON.parse(t);if(n.version!==fc)throw Error(`${dc(e)} is version ${n.version} — this ttheme reads version ${fc}`);return n}function og(e){return(e.artist??[]).map((t)=>t.replace(/[\s,]+/g,"_")).join(",")}function bg(e,t){let n=t.pictures.findIndex((i)=>i.key===t.active),r=t.pictures[n];return[...r.artist?.length?[`# by ${og(r)}`]:[],...r.from?[`# from ${r.from}`]:[],`# image ${r.key} ${n+1}/${t.pictures.length}`,...t.pictures.map((i)=>[`# picture ${i.key} ${i.stem} ${i.fill} ${i.opacity} ${i.artist?.length?og(i):"-"}`,...i.from?[i.from]:[]].join(" ")),`background-image = ${X(e,r.fill)}`,"background-image-fit = cover","background-image-position = top-right",`background-image-opacity = ${r.opacity}`,`config-file = ?${r.stem}.tune.conf`,`config-file = ?${r.stem}.off.conf`,""].join(`
312
+ `)}function wg(e){let t=je(e);for(let[n,r]of Object.entries(ut(t).palettes)){let i=X(t,`${en(n)}.conf`),s=bg(t,r);if(Kn(i)!==s)Z(i,s)}}function ri(e,t,n){Z(dc(e),`${JSON.stringify(t,null,2)}
313
+ `);for(let r of n){let i=t.palettes[r],s=X(e,`${en(r)}.conf`);if(i)Z(s,bg(e,i));else ti(s,{force:!0})}}function $g(e,t){return Wn(e).filter((n)=>n.startsWith(`${t}.`)||n.startsWith(`${t}@`))}function $c(e,t){for(let n of $g(e,t))ti(X(e,n),{force:!0})}function kg(e,t){$c(e,t.stem);for(let n of[t.original,t.cut])if(n)ti(X(e,n),{force:!0})}function ag(e,t,n,r){let i=fg(/^background-image\s*=\s*(.*?)\s*$/m.exec(t??"")?.[1]??"");if(!i.startsWith(`${e}.`)||!/^\.[0-9a-f]{8}@fill-\d+\.png$/.test(i.slice(e.length)))return;let s=i.slice(0,i.indexOf("@")),o=r??/^# image (\S+)$/m.exec(t??"")?.[1]??`picture_${s.slice(e.length+1)}`,a=/^# from (.+)$/m.exec(t??"")?.[1],u=Number(/^background-image-opacity\s*=\s*(\S+)/m.exec(t??"")?.[1]??1),c=n.find((l)=>l.startsWith(`${e}-${o}.`));return{key:o,stem:s,fill:i,opacity:Number.isFinite(u)?u:1,...a?{from:a}:{},...c?{original:X(ta,c)}:{}}}function ug(e,t){if(pc(e))hg(e,t)}function Wy(e){let t={version:fc,palettes:{}};if(!pc(e))return t;let n=Wn(X(e,ta)),r=Wn(e).filter((s)=>s.endsWith(".conf")&&s!=="shown.conf"&&!/\.(tune|off)\.conf$/.test(s)).map((s)=>s.slice(0,-5)),i=X(e,Ly);for(let s of new Set([...r,...Wn(i)])){let o=[],a=ag(s,Kn(X(e,`${s}.conf`)),n);if(a)ug(X(e,`${s}.tune.conf`),X(e,`${a.stem}.tune.conf`)),ug(X(e,`${s}.off.conf`),X(e,`${a.stem}.off.conf`)),o.push(a);for(let u of Wn(X(i,s))){let c=X(i,s,u),l=ag(s,Kn(X(c,".conf")),n,u);if(!l)continue;for(let h of Wn(c)){let f=h===".tune.conf"||h===".off.conf"?`${l.stem}${h}`:`${s}${h}`;if(h!==".conf")hg(X(c,h),X(e,f))}ti(c,{recursive:!0}),o.push(l)}if(Wn(X(i,s)).length===0)ti(X(i,s),{recursive:!0,force:!0});if(o.length>0)o.sort((u,c)=>u.key<c.key?-1:u.key>c.key?1:0),t.palettes[s]={active:(a??o[0]).key,pictures:o}}if(Wn(i).length===0)ti(i,{recursive:!0,force:!0});return ri(e,t,Object.keys(t.palettes)),t}function cg(e,t,n){return t.startsWith("~/")?X(n,t.slice(2)):Fy(t)?t:X(e,t)}function yg(e,t,n){let r=new Map,i=(a,u)=>{let c=Kn(a);if(c===void 0)return!1;for(let l of c.split(`
314
+ `)){let h=/^([a-z-]+)\s*=\s*(.*?)\s*$/.exec(l);if(h?.[1]==="config-file"&&u<4)i(cg(e,h[2].replace(/^\?/,""),n),u+1);else if(h&&/^background-image(?:-fit|-opacity)?$/.test(h[1]))r.set(h[1],h[2])}return!0};if(!i(X(e,`${en(t)}.conf`),0))return;let s=r.get("background-image")??"";if(s==="")return;let o=Number(r.get("background-image-opacity")??1);return{image:cg(e,s,n),opacity:Number.isFinite(o)?o:1,cover:r.get("background-image-fit")==="cover"}}function ct(e){return`${e.site}_${e.id}`}function na(e,t,n){let r=je(e),i=ut(r),s=i.palettes[t];if(!s)throw Error(`${t} has no image`);let o=s.pictures.findIndex((c)=>c.key===(n??s.active));if(o===-1)throw Error(`${t} has no picture ${n}`);let[a]=s.pictures.splice(o,1);kg(r,a);let u=s.pictures[o%Math.max(s.pictures.length,1)];if(!u)delete i.palettes[t];else if(a.key===s.active)s.active=u.key;return ri(r,i,[t]),{key:a.key,left:s.pictures.length}}function Eg(e,t,n,r){let i=Di(n.figure,r),s=Di(n.fill,r),o=`${en(e)}.${lg("sha1").update(t).update(i).update(s).digest("hex").slice(0,8)}`,a=`${o}@fill-${Math.round(n.focus*100)}.png`;return{stem:o,fill:a,files:[[`${o}.png`,i],[a,s]]}}function gc(e,t){return X(ta,`${en(e)}-${t}`)}function kc(e,t){return t.map(([n,r])=>{let i=X(e,n);return Z(i,r),i})}function ra(e,t,n,r,i,s,o){let a=je(e),u=t.name,c=ct(i),l=ut(a),h=l.palettes[u]??{active:c,pictures:[]},f=bc(s.width,s.height),d=Eg(u,c,mg(r,f.width,f.height,o),n.color),g=gc(u,c),p={key:c,stem:d.stem,fill:d.fill,opacity:n.opacity,tone:n.color,blur:o,window:f,...i.from?{from:i.from}:{},...i.artist?.length?{artist:i.artist}:{},...i.source?{source:i.source}:{},original:`${g}.${i.ext}`,...i.cut?{cut:`${g}.cut.png`}:{}},b=h.pictures.find(($)=>$.key===c);if(b)kg(a,b);Ny(X(a,ta),{recursive:!0});let m=kc(a,[...d.files,[p.original,i.bytes],...p.cut?[[p.cut,Zu(Xi(r))]]:[]]);return h.pictures=b?h.pictures.map(($)=>$===b?p:$):[...h.pictures,p],h.active=c,l.palettes[u]=h,ri(a,l,[u]),[...m,X(a,`${en(u)}.conf`)]}function ii(e,t,n){let r=je(e),i=ut(r),s=i.palettes[t],o=s?s.pictures.findIndex((a)=>a.key===n):-1;if(!s||o===-1)throw Error(`${t} has no picture ${n}`);if(s.active!==n)s.active=n,ri(r,i,[t]);return{at:o+1,of:s.pictures.length}}function Ot(e,t){let n=ut(je(e)).palettes[t];if(!n)return[];return[...n.pictures.filter((i)=>i.key===n.active),...n.pictures.filter((i)=>i.key!==n.active)]}var mc="top-right";function vg(e,t,n,r,i,s,o,a=-1){let u=Math.trunc,c=(s-1)%3,l=u((s-1)/3),h=n*t>=r*e!==!o,f=h?u(i*n/100):u(i*r*e/(100*t)),d=h?u(i*n*t/(100*e)):u(i*r/100),g=u(c*(n-f)/2),p=u(l*(r-d)/2);if(a>=0){if(f>n)g=u((n-f)/2);if(d>r)p=Math.max(r-d,Math.min(0,u(r/2)-u(a*d/100)))}return{x:g,y:p,w:f,h:d}}function yc(e,t){let n=Kn(X(e,`${t.stem}.tune.conf`));if(n===void 0)return{};let r=(c)=>new RegExp(`^${c}\\s*=\\s*(.*?)\\s*$`,"m").exec(n)?.[1]??"",i=fg(r("background-image")),s=/@(\d+)-/.exec(i)?.[1],o=/@fill-\d+\.png$/.test(i)?"fill":s?Number(s):r("background-image-fit")==="cover"?"fill":100,a=r("background-image-position").replace("center-center","center")||"center",u=Number(r("background-image-opacity")||1);return{...o!=="fill"?{size:o}:{},...a!==mc?{position:a}:{},...Number.isFinite(u)&&u!==t.opacity?{opacity:u}:{}}}function gs(e,t,n,r,i){let s=n.size??"fill",o=n.position??mc,a=n.opacity??t.opacity;if(s==="fill"&&o===mc&&a===t.opacity)return;let u=bt.indexOf(o)+1,c=X(e,`${t.stem}.png`),l=X(e,t.fill),h=!0,f=typeof s==="number"&&(s>100||!r&&o!=="center");if(s===100&&!f)l=c,h=!1;else if(typeof s==="number"){if(!t.tone)throw Error(`${t.stem} was drawn before pictures kept their tone — init draws it again`);let g=Xi(cr(new Uint8Array(ea(c)))),{width:p,height:b}=f?Xo:g,m=f?Number(/@fill-(\d+)\.png$/.exec(t.fill)?.[1]??50):-1,$=vg(g.width,g.height,p,b,s,u,!1,m);l=X(e,`${t.stem}@${s}-${o}${f?`-${p}x${b}`:""}.png`);let k={x:0,y:0,w:g.width,h:g.height};Z(l,Di(Vi(Do(g,{crop:k,at:$,focus:m},p,b)),t.tone)),h=f}let d=X(e,`${t.stem}.tune.conf`);return Z(d,[`background-image = ${l.startsWith(`${i}/`)?`~${l.slice(i.length)}`:l}`,`background-image-fit = ${h?"cover":"contain"}`,`background-image-position = ${o}`,`background-image-opacity = ${a}`,""].join(`
315
+ `)),d}function Mg(e){let t=new Map;for(let[n,r]of Object.entries(ut(je(e)).palettes)){let[,i,s]=/^([a-z.]+)_(\d+)$/.exec(r.active)??[];if(i&&s)t.set(n,{site:i,id:Number(s)})}return t}function Ky(e){try{let t=xn(new Uint8Array(ea(e)));return t?{width:t.width,height:t.height}:void 0}catch{return}}function ia(e,t,n,r,i,s,o,a,u){let c=je(e),l=n.window??Ky(X(c,n.fill))??Xo,h=Eg(t,n.key,mg(r,l.width,l.height,s),i.color),f={...n,stem:h.stem,fill:h.fill,opacity:i.opacity,tone:i.color,blur:s,window:l,...u?{cut:`${gc(t,n.key)}.cut.png`}:{}};if(u)Z(X(c,`${gc(t,n.key)}.cut.png`),Zu(Xi(r)));if(h.stem===n.stem)return f;kc(c,h.files),gs(c,f,yc(c,n),o,a);let d=X(c,`${n.stem}.off.conf`);if(pc(d))Iy(d,X(c,`${f.stem}.off.conf`));return f}function Sg(e,t){let n=je(e),r=ut(n),i=new Set,s=[];for(let{name:o,picture:a}of t){let u=r.palettes[o],c=u?.pictures.findIndex((h)=>h.key===a.key)??-1,l=u?.pictures[c];if(!u||!l)continue;if(u.pictures[c]=a,i.add(o),l.stem!==a.stem)s.push(l.stem)}if(i.size===0)return;ri(n,r,[...i]);for(let o of s)$c(n,o)}function Jy(e,t,n,r){let i=(u)=>u.replace(/^background-image-opacity = (\S+)$/m,(c,l)=>Number(l)===n.opacity?`background-image-opacity = ${r.opacity}`:c);if(n.tone===r.color){let u=X(e,`${n.stem}.tune.conf`),c=Kn(u);if(c!==void 0)Z(u,i(c));return{...n,opacity:r.opacity}}let s=$g(e,n.stem).filter((u)=>u.endsWith(".png")).map((u)=>{let c=new Uint8Array(ea(X(e,u)));return[u,bd(c,r.color)??Di(Xi(cr(c)),r.color)]}),o=(u)=>s.find(([c])=>c===u)?.[1]??new Uint8Array,a=`${en(t)}.${lg("sha1").update(n.key).update(o(`${n.stem}.png`)).update(o(n.fill)).digest("hex").slice(0,8)}`;kc(e,s.map(([u,c])=>[a+u.slice(n.stem.length),c]));for(let u of["tune","off"]){let c=Kn(X(e,`${n.stem}.${u}.conf`));if(c!==void 0)Z(X(e,`${a}.${u}.conf`),i(c.split(n.stem).join(a)))}return{...n,stem:a,fill:a+n.fill.slice(n.stem.length),opacity:r.opacity,tone:r.color}}function Ig(e,t){let n=je(e),r=ut(n),i=[],s=[];for(let[o,a]of Object.entries(r.palettes)){let u=t.get(o),c=a.pictures.filter((l)=>u&&l.tone&&(l.tone!==u.color||l.opacity!==u.opacity));if(!u||c.length===0)continue;a.pictures=a.pictures.map((l)=>{if(!c.includes(l))return l;let h=Jy(n,o,l,u);if(h.stem!==l.stem)s.push(l.stem);return h}),i.push(o)}if(i.length>0){ri(n,r,i);for(let o of s)$c(n,o)}return i}function Wt(e){let{slot:t,color:n,opacity:r}=ni({name:e.name,background:e.background,foreground:e.foreground,cursor:e.cursor,selection:e.selectionBackground,ansi:e.ansi,waived:e.waive},e.signatureSlots);return{name:e.name,...e.base?{base:e.base}:{},group:e.group,...e.native?{native:e.native}:{},...e.nativeNames?{nativeNames:e.nativeNames}:{},...e.lead?{lead:!0}:{},order:e.order,ansiSource:e.ansiSource,...e.booru?{booru:e.booru}:{},...e.booruSites?{booruSites:e.booruSites}:{},...e.role==="default"?{default:!0}:{},background:e.background,foreground:e.foreground,cursor:e.cursor,selection:e.selectionBackground,signature:e.signature,signatureSlots:e.signatureSlots,ansi:e.ansi,gate:Tn(e),...e.waive.length>0?{waived:e.waive}:{},backdrop:{slot:t,color:n,opacity:r},...e.pictures?{pictures:e.pictures}:{}}}function Tt(e){return{name:e.name,...e.base?{base:e.base}:{},group:e.group,...e.native?{native:e.native}:{},...e.nativeNames?{nativeNames:e.nativeNames}:{},lead:e.lead===!0,order:e.order,...e.default?{role:"default"}:{},ansiSource:e.ansiSource,...e.booru?{booru:e.booru}:{},...e.booruSites?{booruSites:e.booruSites}:{},background:e.background,foreground:e.foreground,cursor:e.cursor,selectionBackground:e.selection,ansi:e.ansi,signature:e.signature,signatureSlots:e.signatureSlots,ghostty:{iconGhost:e.cursor,iconScreen:[e.cursor,e.selection,e.background]},waive:e.waived??[],...e.pictures?{pictures:e.pictures}:{}}}var By=6,qy=["ansi1","ansi2","ansi4","ansi3","ansi5","ansi6"];function sa(e){let t=(s)=>s.startsWith("ansi")?e.ansi[Number(s.slice(4))]:s==="foreground"?e.foreground:s==="cursor"?e.cursor:s==="selection"?e.selection:void 0,n=(s)=>s.startsWith("ansi")?`ansi${Number(s.slice(4))%8}`:s,r=new Set,i=[];for(let s of["foreground",...e.signatureSlots,...qy]){let o=t(s);if(i.length===By||!o||r.has(n(s))||i.includes(o))continue;r.add(n(s)),i.push(o)}return i}function st(e){return e.filter((t)=>t.default!==!0)}function ms(){return{version:nt.version,gate:gt,placement:gn,palettes:[]}}function zy(e){let[t]=e;if(!t)throw Error("manifest needs at least one theme");return{...ms(),palettes:e.map(Wt)}}var Ec={id:"meta",emitShared(e){return[{path:"manifest.json",content:`${JSON.stringify(zy(e),null,2)}
316
+ `}]}};import{existsSync as e1,readdirSync as Tg,readFileSync as t1}from"node:fs";import{basename as Hg,join as ps}from"node:path";import{existsSync as Yy,readFileSync as Ng}from"node:fs";import{homedir as Pg}from"node:os";import{isAbsolute as Fg,join as mr,resolve as Qy}from"node:path";var D="official",nn="ttheme-market.json",si="ttheme-market",Zy=/^[a-z0-9](?:[a-z0-9]|-(?=[a-z0-9])){0,38}$/i,Vy=/^[\w.-]{1,100}$/,Xy=/^\w[\w.+/-]{0,199}$/;function Bn(e){return mr(e,"ttheme","installed.json")}function et(e){return e??[D]}function oi(e){try{let{markets:t}=JSON.parse(Ng(Bn(e),"utf8"));return et(Array.isArray(t)?t.filter((n)=>typeof n==="string"):void 0)}catch{return[D]}}function Te(e){return Fg(e)}function wt(e){return e!==D&&!Te(e)}function Jn(e){let t=e.indexOf("#");return wt(e)&&t>=0?e.slice(0,t):e}function vc(e){let t=e.indexOf("#");return wt(e)&&t>=0?e.slice(t+1):void 0}function ai(e,t){return Jn(e)===Jn(t)}function qn(e,t){return!Te(e)&&(t?.[e]??e===D)}function Dy(e){return!Xy.test(e)||e.includes("..")||e.includes("//")||/(?:[./]|\.lock)$/.test(e)}function zn(e,t=process.cwd()){if(e===D)return D;if(e==="~"||e.startsWith("~/"))return mr(Pg(),e.slice(1));if(e.startsWith(".")||Fg(e))return Qy(t,e);let[n="",r,...i]=e.split("#"),[s,o,...a]=n.replace(/^https:\/\/github\.com\//,"").replace(/\.git$/,"").split("/");if(!s||!Zy.test(s)||!o||!Vy.test(o)||a.length>0||i.length>0||r!==void 0&&Dy(r))throw Error(`${e} is not a market — give a repository (alice/ttheme-dust, #v1 pins a tag or branch) or a path (./my-market)`);return`${s.toLowerCase()}/${o}${r===void 0?"":`#${r}`}`}function Rg(e){let t=vc(e)?.split("/").map(encodeURIComponent).join("/")??"HEAD";return`https://raw.githubusercontent.com/${Jn(e)}/${t}/${nn}`}function Og(e){return e.slice(0,e.indexOf("/"))}function Mc(e){return mr(e,"ttheme","markets")}function Kt(e,t){return mr(Mc(e),`${Jn(t).replace("/","--")}.json`)}function oa(e){return mr(e,"ttheme","market")}function Sc(e,t){return mr(oa(e),t)}function Ic(e,t){if(typeof e!=="string"||typeof t!=="string")return'needs an "owner" (the GitHub handle) and a "name"';return tn(`${e}@${t}/x`)}function $t({owner:e,name:t}){return`${e}@${t}`}function rn(e){let t=mr(e,nn);if(!Yy(t))throw Error(`${e} has no ${nn} — \`ttheme market init ${e}\` makes one`);let n;try{n=JSON.parse(Ng(t,"utf8"))}catch{throw Error(`${t} is not valid JSON`)}let r=Ic(n.owner,n.name);if(r)throw Error(`${t} ${r}`);return{owner:n.owner,name:n.name}}function ke(e){if(e===D)return"the ttheme catalog";if(!Te(e))return`github.com/${e}`;let t=Pg();return e===t||e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e}var mn="tt1:",Ag=["background","foreground","cursor","selection",...Array.from({length:16},(e,t)=>`ansi${t}`)];function pr(e,t=!0){return oi(e).filter(Te).flatMap((n)=>{try{let r=rn(n);return[{dir:n,...r,id:$t(r)}]}catch(r){if(t)process.stderr.write(`ttheme: skipping the market at ${n} — ${r.message}
317
+ `);return[]}})}function aa(e){return ps(e,"palettes")}function Yn(e){let t=aa(e);if(!e1(t))return[];let n=[],r=[];for(let i of Tg(t,{withFileTypes:!0}).sort((s,o)=>s.name<o.name?-1:1)){if(i.name.startsWith("."))continue;if(i.isDirectory()){for(let s of Tg(ps(t,i.name)).sort())if(s.endsWith(".toml"))n.push({path:ps(t,i.name,s),slug:Hg(s,".toml"),catalog:i.name})}else if(i.name.endsWith(".toml"))r.push({path:ps(t,i.name),slug:Hg(i.name,".toml")})}return[...n,...r]}function bs(e,t){let n=t.get(e.slug);if(n)return`${e.slug} is also ${n.catalog?`in ${n.catalog}`:"outside a catalog"} — a palette name is used once in a market`;let r=e.catalog===void 0?void 0:ds(e.catalog);return r?`the catalog folder ${JSON.stringify(e.catalog)} ${r}`:void 0}function Nc(e,t){let n=ve(t);if(!n)throw Error(`${t} is an official palette — yours are named <you>@<market>/<palette>`);let r=pr(e,!1).find((s)=>s.id===n);if(!r)throw Error(`${n} is not a local market — \`ttheme market add <dir>\` adds the folder that holds it`);let i=ei(t);return Yn(r.dir).find((s)=>s.slug===i)?.path??ps(aa(r.dir),`${i}.toml`)}function n1(e,t){let n=new Map;for(let i of t)if(i.group!==ls&&!n.has(i.group)){let s=t.find((o)=>o.group===i.group&&o.lead)?.name??"";n.set(i.group,{name:i.group,...i.native?{native:i.native}:{},lead:s})}let r=new Map(t.filter((i)=>!i.default&&!ve(i.name)).map((i)=>[i.name,{group:i.group,order:i.order}]));return{name:e,groups:n,bases:r,open:!0}}function kt(e,t,n){let r=ei(e),{native:i,...s}=hc(`${r}.toml`,t,n1(r,n)),o=ve(e);return{...s,name:e,...o?{group:o,lead:!1}:{}}}function Qn(e,t,n,r=!0){let i=new Map;return Yn(e).flatMap((s)=>{try{let o=bs(s,i);if(o)throw Error(o);i.set(s.slug,s);let a=Wt(kt(`${t}/${s.slug}`,t1(s.path,"utf8"),n));return[s.catalog?{...a,catalog:s.catalog}:a]}catch(o){if(r)process.stderr.write(`ttheme: skipping ${s.path} — ${o.message}
318
+ `);return[]}})}function ua(e,t,n=!0){return pr(e,n).flatMap(({dir:r,id:i})=>Qn(r,i,t,n))}function Pc(e,t=e.name,n){return{name:t,...e.base?{base:e.base}:{},...e.group!==ls?{group:e.group}:{},ansiSource:e.ansiSource,...e.booru?{booru:e.booru}:{},...e.booruSites?{booruSites:e.booruSites}:{},signature:e.signatureSlots,background:e.background,foreground:e.foreground,cursor:e.cursor,selection:e.selection,ansi:e.ansi,...e.waived&&e.waived.length>0?{waive:e.waived,reason:n??"kept from the palette"}:{},...e.pictures?{pictures:e.pictures}:{}}}var qe=(e)=>JSON.stringify(e);function Lg(e){return["[[picture]]",`site = ${qe(e.site)}`,`id = ${e.id}`,...e.size===void 0?[]:[`size = ${typeof e.size==="number"?e.size:qe(e.size)}`],...e.position===void 0?[]:[`position = ${qe(e.position)}`],...e.opacity===void 0?[]:[`opacity = ${e.opacity}`]]}function xg(e,t){return t.length===0?e:`${e.replace(/\n*$/,`
319
+ `)}${t.map((n)=>`
320
+ ${Lg(n).join(`
319
321
  `)}
320
- `}class Wd{bytes=[];u8(e){this.bytes.push(e&255)}u16(e){this.u8(e>>8),this.u8(e)}u32(e){this.u16(Math.floor(e/65536)),this.u16(e%65536)}str(e=""){let t=new TextEncoder().encode(e);if(t.length>255)throw Error(`"${e}" is too long to share`);this.u8(t.length),this.bytes.push(...t)}color(e){let t=Number.parseInt(e.slice(1),16);this.u8(t>>16),this.u8(t>>8),this.u8(t)}done(){return Buffer.from(this.bytes).toString("base64url")}}class Jd{at=0;bytes;constructor(e){this.bytes=e}u8(){let e=this.bytes[this.at++];if(e===void 0)throw Error("the share code is cut short");return e}u16(){return this.u8()*256+this.u8()}u32(){return this.u16()*65536+this.u16()}str(){let e=this.u8(),t=this.bytes.subarray(this.at,this.at+e);if(t.length!==e)throw Error("the share code is cut short");return this.at+=e,new TextDecoder("utf-8",{fatal:!0}).decode(t)}color(){return`#${[this.u8(),this.u8(),this.u8()].map((e)=>e.toString(16).padStart(2,"0")).join("")}`}end(){if(this.at!==this.bytes.length)throw Error("the share code has bytes left over")}}function Kd(e){let t=new Wd;t.str(e.name);for(let r of[e.background,e.foreground,e.cursor,e.selection,...e.ansi])t.color(r);for(let r of e.signature)t.u8(jd.indexOf(r));t.str(e.base),t.str(e.group),t.str(e.ansiSource),t.str(e.booru),t.u16((e.waive??[]).reduce((r,i)=>r|1<<Ka.indexOf(i),0)),t.str(e.waive&&e.waive.length>0?e.reason:"");let n=e.pictures??[];t.u8(n.length);for(let r of n)t.u8(te.findIndex((i)=>i.key===r.site)),t.u32(r.id),t.u16(r.size===void 0?0:r.size==="fill"?1:r.size),t.u8(r.position===void 0?0:Vn.indexOf(r.position)+1),t.u16(r.opacity===void 0?0:Math.round(r.opacity*1000)+1);return`${an}${t.done()}`}function qd(e){if(!e.startsWith(an))throw Error(`a share code starts with ${an}`);let t=e.slice(an.length);if(!/^[A-Za-z0-9_-]+$/.test(t))throw Error("the share code holds characters it never uses — was it copied whole?");let n=new Jd(new Uint8Array(Buffer.from(t,"base64url"))),r=n.str(),[i,s,o,a,...u]=Array.from({length:20},()=>n.color()),c=[n.u8(),n.u8(),n.u8()].map((E)=>jd[E]??`slot${E}`),l=n.str(),h=n.str(),f=n.str(),d=n.str(),g=n.u16(),m=n.str(),b=Ka.filter((E,v)=>g&1<<v),p=Array.from({length:n.u8()},()=>{let E=te[n.u8()]?.key??"unknown",v=n.u32(),S=n.u16(),w=n.u8(),N=n.u16();return{site:E,id:v,...S===1?{size:"fill"}:S>1?{size:S}:{},...w>0?{position:Vn[w-1]??"unknown"}:{},...N>0?{opacity:(N-1)/1000}:{}}});if(n.end(),![i,s,o,a,...u].every(yr))throw Error("the share code holds a color that is not one");return{name:r,...l?{base:l}:{},...h?{group:h}:{},...f?{ansiSource:f}:{},...d?{booru:d}:{},signature:c,background:i,foreground:s,cursor:o,selection:a,ansi:u,...b.length>0?{waive:b,reason:m}:{},...p.length>0?{pictures:p}:{}}}function Qd(e,t){let n=e.indexOf("ansi = ["),r=e.indexOf("]",n);if(n<0||r<0)throw Error("no ansi = [...] list to rewrite");let i=0,s=e.slice(n,r).replace(/"#[0-9a-fA-F]{6}"/g,()=>Je(t.ansi[i++]));return(e.slice(0,n)+s+e.slice(r)).replace(/^(foreground\s*=\s*)"#[0-9a-fA-F]{6}"/m,(o,a)=>`${a}${Je(t.foreground)}`).replace(/^(selection_background\s*=\s*)"#[0-9a-fA-F]{6}"/m,(o,a)=>`${a}${Je(t.selectionBackground)}`)}function Ji(e){let t=Mr(yt(e)),n=new Set(e.waived??[]),r=Math.max(...jt.map((i)=>i.label.length));return jt.map((i,s)=>{let o=t[s],a=n.has(i.rule)||Number.isNaN(o)||(i.min===void 0||o>=i.min)&&(i.max===void 0||o<=i.max),u=i.min!==void 0?`≥ ${i.min}`:i.max!==void 0?`≤ ${i.max}`:"",c=Number.isNaN(o)?"—":Number.isInteger(o)?String(o):o.toFixed(2);return` ${a?"✓":"✗"} ${i.label.padEnd(r)} ${c.padStart(6)} ${u}${n.has(i.rule)?" waived":""}`})}var zd="https://kecan0406.github.io/ttheme/manifest.json",Fk=20000;function At(e){return Zd(e,"ttheme","catalog.json")}function So(e,t){ke(At(e),`${JSON.stringify(t,null,2)}
321
- `)}function Le(e,t=!0){let n=_r(e),r=At(e),i=Ci();if(n.includes(z)){if(!Yd(r))throw Error(`no catalog at ${r} — run \`ttheme init\` first`);i=Zt(Ku(r,"utf8"))}let s=n.filter(ht).flatMap((o)=>Pk(e,o,t));return{...i,palettes:[...i.palettes,...s]}}function An(e,t){return qu(Ku(Ot(e,t),"utf8"))}function jr(e,t){return ft({owner:Ud(e),name:t.name})}function Pk(e,t,n){let r=Ot(e,t);if(!Yd(r))return[];try{let i=An(e,t);return Io(i,jr(t,i))}catch(i){if(n)process.stderr.write(`ttheme: skipping ${r} — ${i.message}
322
- `);return[]}}function qu(e){let t=Zt(e),n=Cu(t.owner,t.name);if(n)throw Error(`market index ${n}`);let r=t.palettes.find((i)=>ye(i.name)!==void 0);if(r)throw Error(`market index names ${r.name} with its market — its entries are bare palette names`);return t}function Io(e,t){return e.palettes.map(({lead:n,default:r,native:i,...s})=>({...s,name:`${t}/${s.name}`,group:t}))}function Zt(e){let t;try{t=JSON.parse(e)}catch{throw Error("catalog is not valid JSON")}let n=t;if(typeof n?.version!=="string"||!Array.isArray(n.palettes))throw Error("catalog has no version or palettes");for(let r of n.palettes){let i=Bd(r);if(i)throw Error(`catalog entry ${JSON.stringify(r?.name)} ${i}`)}return n}function Bd(e){if(typeof e?.name!=="string"||!Array.isArray(e.ansi)||e.ansi.length!==16)return"is missing name or its 16 ANSI colors";let t=qt(e.name)??(e.base===void 0?void 0:qt(e.base));if(t)return t;if(![e.background,e.foreground,e.cursor,e.selection,...e.ansi].every((n)=>typeof n==="string"&&yr(n)))return'holds a color that is not "#rrggbb"';for(let n of[e.group,e.native??"-",e.catalog??"-",e.ansiSource]){let r=typeof n==="string"?_i(n):"has a field that is not text";if(r)return r}return}function Vd(e){return Zd(e,"ttheme","kept.json")}function No(e,t){ke(Vd(e),`${JSON.stringify({palettes:t},null,2)}
323
- `)}function un(e){try{let{palettes:t}=JSON.parse(Ku(Vd(e),"utf8"));return Array.isArray(t)?t.filter((n)=>Bd(n)===void 0):[]}catch{return[]}}function _e(e,t,n=!0){let r=[...t.palettes,...Mo(e,t.palettes,n)],i=new Set(r.map((s)=>s.name));return{...t,palettes:[...r,...un(e).filter((s)=>!i.has(s.name))]}}function Hn(e){return _e(e,Le(e))}class Ro extends Error{}class Fo extends Error{}async function Ki(e,t,n=Fk,r){let i;try{let s=AbortSignal.timeout(n);i=await fetch(e,{signal:r?AbortSignal.any([s,r]):s})}catch(s){throw Error(`cannot reach ${e} — ${s instanceof Error?s.message:String(s)}`)}if(i.status===404)throw new Ro(`nothing at ${e}`);if(i.status===403||i.status===429)throw new Fo(`${new URL(e).host} is turning requests away for now (${i.status}) — try again in a minute`);if(!i.ok)throw Error(`${e} answered ${i.status}`);return t(await i.text())}function qi(e){let t=new Set(e.waived??[]),n=e.gate??Mr(yt(e));return jt.flatMap((r,i)=>{let s=n[i];if(t.has(r.rule)||typeof s!=="number"||Number.isNaN(s))return[];if(r.min!==void 0&&s<r.min)return[`${r.label} ${s} < ${r.min}`];if(r.max!==void 0&&s>r.max)return[`${r.label} ${s} > ${r.max}`];return[]})}function rr(e,t){let n=e.find((r)=>r.name===t);if(!n)throw Error(`no palette named ${t} in the catalog — ${Qu(e,[t])}`);return n}function Qu(e,t){let n=t.map((o)=>o.toLowerCase()),r=e.filter((o)=>n.some((a)=>o.name.includes(a))),i=e.filter((o)=>!r.includes(o)&&n.some((a)=>o.group.toLowerCase().includes(a))),s=[...r,...i].map((o)=>o.name).slice(0,3);return s.length>0?`did you mean: ${s.join(", ")}?`:"`ttheme list` shows what is there"}function Xd(e,t){let n=t.toLowerCase();return e.filter((r)=>[r.name,r.group,r.native??"",r.ansiSource].some((i)=>i.toLowerCase().includes(n)))}function xd(e,t,n){let r=n.toLowerCase(),i=(s)=>s.name===t.name?0:s.group===t.group?1:2;return e.filter((s)=>s.booru?.toLowerCase().includes(r)).map((s,o)=>({p:s,at:o})).sort((s,o)=>i(s.p)-i(o.p)||s.at-o.at).map(({p:s})=>s)}function Dd(e,t){return e.booruSites?.[t]??(e.booru?[e.booru]:[])}import{execFileSync as Gy}from"node:child_process";import{existsSync as dc,mkdirSync as Zg,readdirSync as Uy,readFileSync as mc,rmSync as zg}from"node:fs";import{basename as _y,join as cr,relative as Cy}from"node:path";import{execFileSync as Zk,spawn as zk}from"node:child_process";import{existsSync as Ht,mkdirSync as Bk,readFileSync as Zr,realpathSync as Vk,rmSync as Du,utimesSync as Xk,writeFileSync as xk}from"node:fs";import{homedir as zr}from"node:os";import{dirname as Dk,join as Te}from"node:path";var Ok=["black","red","green","yellow","blue","magenta","cyan","white"];function eg(e,t){return[e,...Ok.map((n,r)=>`${n} = '${t[r]}'`),""].join(`
324
- `)}var Qi={id:"alacritty",limits:"no runtime color API (OSC only)",emit(e){let t=[...Wr(e),"","[colors.primary]",`background = '${e.background}'`,`foreground = '${e.foreground}'`,"","[colors.cursor]",`cursor = '${e.cursor}'`,`text = '${e.background}'`,"","[colors.selection]",`background = '${e.selectionBackground}'`,`text = '${e.foreground}'`,"",eg("[colors.normal]",e.ansi.slice(0,8)),eg("[colors.bright]",e.ansi.slice(8,16))].join(`
325
- `);return[{path:`alacritty/themes/${$e(e.name)}.toml`,content:t}]}};var Yi={id:"ghostty",emit(e){let t=[...Wr(e),`background = ${e.background}`,`foreground = ${e.foreground}`,`cursor-color = ${e.cursor}`,`selection-background = ${e.selectionBackground}`,`selection-foreground = ${e.foreground}`,...e.ansi.map((n,r)=>`palette = ${r}=${n}`),"palette-generate = true","","macos-icon = custom-style",`macos-icon-ghost-color = ${e.ghostty.iconGhost}`,`macos-icon-screen-color = ${e.ghostty.iconScreen.join(",")}`,"macos-icon-frame = chrome",""].join(`
326
- `);return[{path:`ghostty/themes/${$e(e.name)}`,content:t}]}};function Ln(e){let[t,n,r]=Qe(e);return{"Alpha Component":1,"Blue Component":r/255,"Color Space":"P3","Green Component":n/255,"Red Component":t/255}}function tg(e){return{...Object.fromEntries(e.ansi.map((t,n)=>[`Ansi ${n} Color`,Ln(t)])),"Background Color":Ln(e.background),"Bold Color":Ln(e.foreground),"Cursor Color":Ln(e.cursor),"Cursor Text Color":Ln(e.background),"Foreground Color":Ln(e.foreground),"Selected Text Color":Ln(e.foreground),"Selection Color":Ln(e.selectionBackground)}}function Tk(e){return e?{"Background Image Location":e.image,"Background Image Mode":e.cover?2:3,Blend:e.opacity}:{"Background Image Location":""}}function ng(e,t,n,r){let i=(o,a)=>({Name:`ttheme · ${a}`,Guid:$e(a),...r?{"Dynamic Profile Parent GUID":r}:{},"Use Separate Colors for Light and Dark Mode":!1,"Harmonize 256 Colors":!0,...Tk(t.get(o.name)),...tg(o)}),s=[...n?[i(n,"default")]:[],...e.map((o)=>i(o,o.name))];return`${JSON.stringify({Profiles:s},null,2)}
327
- `}function Ak(e,t){return[` <key>${e}</key>`,"\t<dict>",...Object.entries(t).flatMap(([n,r])=>[` <key>${n}</key>`,typeof r==="string"?` <string>${r}</string>`:` <real>${r}</real>`]),"\t</dict>"].join(`
328
- `)}var Zi={id:"iterm2",limits:"colors are Display P3, the space iTerm2 reads OSC colors in",emit(e){let t=['<?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(tg(e)).map(([n,r])=>Ak(n,r)),"</dict>","</plist>",""].join(`
329
- `);return[{path:`iterm2/${$e(e.name)}.itermcolors`,content:t}]}};var zi={id:"kitty",emit(e){let t=[...Wr(e),`background ${e.background}`,`foreground ${e.foreground}`,`cursor ${e.cursor}`,`cursor_text_color ${e.background}`,`selection_background ${e.selectionBackground}`,`selection_foreground ${e.foreground}`,...e.ansi.map((n,r)=>`color${r} ${n}`),""].join(`
330
- `);return[{path:`kitty/themes/${$e(e.name)}.conf`,content:t}]}};function rg(e){return["# Generated by ttheme — rewritten on every add, remove and default; do not edit.","import os","",`THEMES = ${JSON.stringify(e.themes)}`,`BACKGROUNDS = ${JSON.stringify(e.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.replace('@', '--', 1).replace('/', '--', 1) + '.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, 'ttheme-' + palette.replace('@', '--', 1).replace('/', '--', 1) + '.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(`
331
- `)}var Hk=["ghostty","kitty","alacritty","wezterm","iterm2","windows-terminal","warp"],Lk=[{section:"tab",title:"This tab"},{section:"startup",title:"New tabs"},{section:"catalog",title:"Palettes"},{section:"own",title:"Your own"},{section:"setup",title:"Setup"}],Vi=[{name:"preview",args:[],about:"Browse live — focus repaints, enter keeps (this tab or default), esc restores, ? lists keys",section:"tab",start:"Try every palette live — enter keeps the one you land on",shell:!0},{name:"use",args:["<palette>"],about:"Paint this tab — a unique prefix works: ttheme use ho",section:"tab",start:"Paint this tab with one — ttheme use homura",shell:!0},{name:"next",args:[],about:"Advance this tab to the next palette",section:"tab",shell:!0},{name:"default",args:["<palette>"],about:"Make a palette the one new tabs open with",section:"startup"},{name:"on",args:[],about:"Wear the default palette in new tabs again",section:"startup"},{name:"off",args:[],about:"Take the palette and picture off every tab — the terminal's own colors until `ttheme on`",section:"startup"},{name:"pin",args:[],about:"Pick a palette for this directory — cd into it repaints, cd out restores",section:"tab",shell:!0},{name:"unpin",args:[],about:"Drop the palette pinned to this directory",section:"tab",shell:!0},{name:"config",args:[],about:"Edit settings in $EDITOR — they apply in new tabs",section:"startup",shell:!0},{name:"browse",args:[],about:"Pick palettes and markets in a live picker — tab moves between Catalog, Installed, Markets and Errors",section:"catalog",start:"Install or drop palettes, add markets — every change applies at once on enter"},{name:"list",args:["[query]"],about:"Show the catalog, marking what is installed",section:"catalog",flags:{json:{type:"boolean",about:"Print the matches as JSON: name, group, catalog, installed"}}},{name:"add",args:["<palette...>"],about:"Install palettes from the catalog, or from a share code: ttheme add tt1:…",section:"catalog",flags:{market:{type:"string",value:"<source>",about:"Add this market first — a repository, a folder or official — and take bare palette names from it"}}},{name:"remove",args:["<palette...>"],about:"Uninstall palettes",section:"catalog"},{name:"update",args:[],about:"Refresh every market you added now — those with auto-update refresh on their own once a day",section:"catalog"},{name:"market",args:["[action]","[source]"],about:"The markets you added — add, remove and search them; init makes one of your own",actions:[["(none)","List the markets you added: palettes, auto-update and the last update"],["add <source>","Add one: a repository (alice/ttheme-pastel, #v1 pins a tag or branch), a folder, or official — asks whether it updates on its own"],["remove <market>","Drop one by its name (alice@pastel) — the palettes you installed from it keep working"],["search [query]","Repositories on GitHub with the ttheme-market topic"],["init [name]","Make a market of your own, <you>@<name>, in ~/.config/ttheme/market/<name> (or give a folder)"]],section:"catalog"},{name:"new",args:["<name>"],about:"Make a palette of your own, <you>@<market>/<name>, in your local market — installed at once",section:"own",flags:{from:{type:"string",value:"<palette>",about:"The palette to start from — the default one when left out"},in:{type:"string",value:"<market>",about:"The local market to put it in, when you have more than one"}}},{name:"edit",args:["<palette>"],about:"Change one of your palettes in $EDITOR — the contrast gate advises, never refuses",section:"own"},{name:"check",args:["<palette>"],about:"Measure a palette against the contrast gate and suggest colors that pass",section:"own",flags:{fix:{type:"boolean",about:"Write the suggested colors into your palette"}}},{name:"share",args:["<palette>"],about:"Print a share code — ttheme add <code> installs it anywhere, pictures included",section:"own"},{name:"init",args:[],about:"Install the shell layer and wire your terminal configs",section:"setup",flags:{yes:{type:"boolean",short:"y",about:"Accept every default without prompting"}}},{name:"uninstall",args:[],about:"Take ttheme out of every terminal config and delete what it wrote",section:"setup",flags:{yes:{type:"boolean",short:"y",about:"Remove without asking"}}},{name:"build",args:[],about:"Emit dist/ for every terminal, plus the zsh palette table — from a checkout",section:"setup",hidden:!0,flags:{only:{type:"string",multiple:!0,value:"<terminal>",choices:Hk,about:"Rebuild just this terminal — repeat it for more"}}},{name:"find",args:["<palette>"],about:"Pick a booru background for a palette — preview opens this on tab",section:"setup",hidden:!0},{name:"image",args:["<palette>","<action>"],about:"Switch a palette between its saved backgrounds, remove the one shown, or pass on tuning — preview calls this",section:"setup",hidden:!0},{name:"redraw",args:[],about:"Draw the background pictures again after TTHEME_BG_BLUR changed — ttheme config and preview call this",section:"setup",hidden:!0}];function Bi(e){let t=Object.entries(e.flags??{}).map(([n,{value:r}])=>`[--${n}${r?` ${r}`:""}]`);return[e.name,...t,...e.args].join(" ")}function Yu(e,t=Math.max(...e.map(([n])=>n.length))){return e.map(([n,r])=>` ${n.padEnd(t)} ${r}`)}var Gk=[["npx @kecan0406/ttheme init -y","Wire the terminals found here, no prompts"],["ttheme add homura madoka","Install two palettes"],["ttheme use homura","Paint this tab with one"],["ttheme list --json madoka","The madoka series as JSON"],["ttheme market add alice/ttheme-pastel","alice's market, alice@pastel — ttheme add alice@pastel/dusk"],["ttheme add dusk --market alice/ttheme-pastel","The same in one step"],["ttheme new rei --from rei","Your own rei, <you>@<market>/rei, to edit and share"]];function Xi(e,t=!1){let n=Vi.filter((o)=>!o.hidden&&!(t&&o.section==="setup")),r=Lk.filter(({section:o})=>n.some((a)=>a.section===o)),i=[...t?["ttheme alone lists every installed palette, grouped, with previews"]:[],e?"ttheme help <command> describes one command · ttheme --version prints the version":"ttheme help <command> describes one · ttheme help all lists every command with what it does","https://kecan0406.github.io/ttheme"];if(!e){let o=n.filter((u)=>u.start),a=Math.max(...r.map(({title:u})=>u.length));return["Usage: ttheme <command>","",Ve.description,"","Start here",...Yu(o.map((u)=>[Bi(u),u.start])),"",...r.map(({section:u,title:c})=>`${c.padEnd(a)} ${n.filter((l)=>l.section===u).map((l)=>l.name).join(" · ")}`),"",...i].join(`
332
- `)}let s=Math.max(...n.map((o)=>Bi(o).length));return["Usage: ttheme <command>","",Ve.description,...r.flatMap(({section:o,title:a})=>["",a,...Yu(n.filter((u)=>u.section===o).map((u)=>[Bi(u),u.about]),s)]),"","Examples",...Yu(Gk),"",...i].join(`
333
- `)}import{readFileSync as Uk}from"node:fs";import{join as _k}from"node:path";var Po=["ghostty","kitty","alacritty","wezterm","iterm2","windows-terminal","warp"],Jr={ghostty:"Ghostty",kitty:"kitty",alacritty:"Alacritty",wezterm:"WezTerm",iterm2:"iTerm2","windows-terminal":"Windows Terminal",warp:"Warp"},ag="# ttheme begin",ug="# ttheme end",xi=/# ttheme begin\n[\s\S]*?# ttheme end\n?/;function Di(e,t){let n=`${ag}
322
+ `).join("")}`}function Fc(e){let t=["[meta]",`name = ${qe(ei(e.name))}`,...e.base?[`base = ${qe(e.base)}`]:[],...e.group?[`group = ${qe(e.group)}`]:[],...e.ansiSource?[`ansi_source = ${qe(e.ansiSource)}`]:[],...e.booru?[`booru = ${qe(e.booru)}`]:[],`signature = [${e.signature.map(qe).join(", ")}]`,...e.booruSites?["","[meta.booru_sites]",...Object.entries(e.booruSites).map(([n,r])=>`${n} = [${r.map(qe).join(", ")}]`)]:[],"","[colors]",`background = ${qe(e.background)}`,`foreground = ${qe(e.foreground)}`,`cursor = ${qe(e.cursor)}`,`selection_background = ${qe(e.selection)}`,"ansi = [",...e.ansi.slice(0,8).map((n)=>` ${qe(n)},`),"",...e.ansi.slice(8).map((n)=>` ${qe(n)},`),"]"];if(e.waive&&e.waive.length>0)t.push("","[contrast]",`waive = [${e.waive.map(qe).join(", ")}]`,`reason = ${qe(e.reason??"")}`);for(let n of e.pictures??[])t.push("",...Lg(n));return`${t.join(`
323
+ `)}
324
+ `}class Cg{bytes=[];u8(e){this.bytes.push(e&255)}u16(e){this.u8(e>>8),this.u8(e)}u32(e){this.u16(Math.floor(e/65536)),this.u16(e%65536)}str(e=""){let t=new TextEncoder().encode(e);if(t.length>255)throw Error(`"${e}" is too long to share`);this.u8(t.length),this.bytes.push(...t)}color(e){let t=Number.parseInt(e.slice(1),16);this.u8(t>>16),this.u8(t>>8),this.u8(t)}done(){return Buffer.from(this.bytes).toString("base64url")}}class _g{at=0;bytes;constructor(e){this.bytes=e}u8(){let e=this.bytes[this.at++];if(e===void 0)throw Error("the share code is cut short");return e}u16(){return this.u8()*256+this.u8()}u32(){return this.u16()*65536+this.u16()}str(){let e=this.u8(),t=this.bytes.subarray(this.at,this.at+e);if(t.length!==e)throw Error("the share code is cut short");return this.at+=e,new TextDecoder("utf-8",{fatal:!0}).decode(t)}color(){return`#${[this.u8(),this.u8(),this.u8()].map((e)=>e.toString(16).padStart(2,"0")).join("")}`}end(){if(this.at!==this.bytes.length)throw Error("the share code has bytes left over")}}function Gg(e){let t=new Cg;t.str(e.name);for(let r of[e.background,e.foreground,e.cursor,e.selection,...e.ansi])t.color(r);for(let r of e.signature)t.u8(Ag.indexOf(r));t.str(e.base),t.str(e.group),t.str(e.ansiSource),t.str(e.booru),t.u16((e.waive??[]).reduce((r,i)=>r|1<<Ou.indexOf(i),0)),t.str(e.waive&&e.waive.length>0?e.reason:"");let n=e.pictures??[];t.u8(n.length);for(let r of n)t.u8(V.findIndex((i)=>i.key===r.site)),t.u32(r.id),t.u16(r.size===void 0?0:r.size==="fill"?1:r.size),t.u8(r.position===void 0?0:bt.indexOf(r.position)+1),t.u16(r.opacity===void 0?0:Math.round(r.opacity*1000)+1);return`${mn}${t.done()}`}function Ug(e){if(!e.startsWith(mn))throw Error(`a share code starts with ${mn}`);let t=e.slice(mn.length);if(!/^[A-Za-z0-9_-]+$/.test(t))throw Error("the share code holds characters it never uses — was it copied whole?");let n=new _g(new Uint8Array(Buffer.from(t,"base64url"))),r=n.str(),[i,s,o,a,...u]=Array.from({length:20},()=>n.color()),c=[n.u8(),n.u8(),n.u8()].map(($)=>Ag[$]??`slot${$}`),l=n.str(),h=n.str(),f=n.str(),d=n.str(),g=n.u16(),p=n.str(),b=Ou.filter(($,k)=>g&1<<k),m=Array.from({length:n.u8()},()=>{let $=V[n.u8()]?.key??"unknown",k=n.u32(),S=n.u16(),w=n.u8(),M=n.u16();return{site:$,id:k,...S===1?{size:"fill"}:S>1?{size:S}:{},...w>0?{position:bt[w-1]??"unknown"}:{},...M>0?{opacity:(M-1)/1000}:{}}});if(n.end(),![i,s,o,a,...u].every(Pn))throw Error("the share code holds a color that is not one");return{name:r,...l?{base:l}:{},...h?{group:h}:{},...f?{ansiSource:f}:{},...d?{booru:d}:{},signature:c,background:i,foreground:s,cursor:o,selection:a,ansi:u,...b.length>0?{waive:b,reason:p}:{},...m.length>0?{pictures:m}:{}}}function Rc(e){return{background:e.background,foreground:e.foreground,cursor:e.cursor,selection:e.selectionBackground,ansi:e.ansi}}function Oc(e,t){let n=e.indexOf("ansi = ["),r=e.indexOf("]",n);if(n<0||r<0)throw Error("no ansi = [...] list to rewrite");let i=0,s=e.slice(n,r).replace(/"#[0-9a-fA-F]{6}"/g,()=>qe(t.ansi[i++]));return[["background",t.background],["foreground",t.foreground],["cursor",t.cursor],["selection_background",t.selection]].reduce((a,[u,c])=>a.replace(new RegExp(`^(${u}\\s*=\\s*)"#[0-9a-fA-F]{6}"`,"m"),(l,h)=>`${h}${qe(c)}`),e.slice(0,n)+s+e.slice(r))}function jg(e,t){return e.replace(/^(signature\s*=\s*)\[[^\]]*\]/m,(n,r)=>`${r}[${t.map(qe).join(", ")}]`)}function ws(e){let t=Tn(Tt(e)),n=new Set(e.waived??[]),r=Math.max(...gt.map((i)=>i.label.length));return gt.map((i,s)=>{let o=t[s],a=n.has(i.rule)||Number.isNaN(o)||(i.min===void 0||o>=i.min)&&(i.max===void 0||o<=i.max),u=i.min!==void 0?`≥ ${i.min}`:i.max!==void 0?`≤ ${i.max}`:"",c=Number.isNaN(o)?"—":Number.isInteger(o)?String(o):o.toFixed(2);return` ${a?"✓":"✗"} ${i.label.padEnd(r)} ${c.padStart(6)} ${u}${n.has(i.rule)?" waived":""}`})}var Jg="https://kecan0406.github.io/ttheme/manifest.json",r1=20000;function Jt(e){return Kg(e,"ttheme","catalog.json")}function ca(e,t){Z(Jt(e),`${JSON.stringify(t,null,2)}
325
+ `)}function _e(e,t=!0){let n=oi(e),r=Jt(e),i=ms();if(n.includes(D)){if(!Wg(r))throw Error(`no catalog at ${r} — run \`ttheme init\` first`);i=sn(Tc(r,"utf8"))}let s=n.filter(wt).flatMap((o)=>i1(e,o,t));return{...i,palettes:[...i.palettes,...s]}}function Zn(e,t){return Hc(Tc(Kt(e,t),"utf8"))}function ui(e,t){return $t({owner:Og(e),name:t.name})}function i1(e,t,n){let r=Kt(e,t);if(!Wg(r))return[];try{let i=Zn(e,t);return la(i,ui(t,i))}catch(i){if(n)process.stderr.write(`ttheme: skipping ${r} — ${i.message}
326
+ `);return[]}}function Hc(e){let t=sn(e),n=Ic(t.owner,t.name);if(n)throw Error(`market index ${n}`);let r=t.palettes.find((i)=>ve(i.name)!==void 0);if(r)throw Error(`market index names ${r.name} with its market — its entries are bare palette names`);return t}function la(e,t){return e.palettes.map(({lead:n,default:r,native:i,...s})=>({...s,name:`${t}/${s.name}`,group:t}))}function sn(e){let t;try{t=JSON.parse(e)}catch{throw Error("catalog is not valid JSON")}let n=t;if(typeof n?.version!=="string"||!Array.isArray(n.palettes))throw Error("catalog has no version or palettes");for(let r of n.palettes){let i=Bg(r);if(i)throw Error(`catalog entry ${JSON.stringify(r?.name)} ${i}`)}return n}function Bg(e){if(typeof e?.name!=="string"||!Array.isArray(e.ansi)||e.ansi.length!==16)return"is missing name or its 16 ANSI colors";let t=tn(e.name)??(e.base===void 0?void 0:tn(e.base));if(t)return t;if(![e.background,e.foreground,e.cursor,e.selection,...e.ansi].every((n)=>typeof n==="string"&&Pn(n)))return'holds a color that is not "#rrggbb"';for(let n of[e.group,e.native??"-",e.catalog??"-",e.ansiSource]){let r=typeof n==="string"?ds(n):"has a field that is not text";if(r)return r}return}function qg(e){return Kg(e,"ttheme","kept.json")}function ha(e,t){Z(qg(e),`${JSON.stringify({palettes:t},null,2)}
327
+ `)}function pn(e){try{let{palettes:t}=JSON.parse(Tc(qg(e),"utf8"));return Array.isArray(t)?t.filter((n)=>Bg(n)===void 0):[]}catch{return[]}}function We(e,t,n=!0){let r=[...t.palettes,...ua(e,t.palettes,n)],i=new Set(r.map((s)=>s.name));return{...t,palettes:[...r,...pn(e).filter((s)=>!i.has(s.name))]}}function bn(e){return We(e,_e(e))}class fa extends Error{}class da extends Error{}async function $s(e,t,n=r1,r){let i;try{let s=AbortSignal.timeout(n);i=await fetch(e,{signal:r?AbortSignal.any([s,r]):s})}catch(s){throw Error(`cannot reach ${e} — ${s instanceof Error?s.message:String(s)}`)}if(i.status===404)throw new fa(`nothing at ${e}`);if(i.status===403||i.status===429)throw new da(`${new URL(e).host} is turning requests away for now (${i.status}) — try again in a minute`);if(!i.ok)throw Error(`${e} answered ${i.status}`);return t(await i.text())}function ks(e){let t=new Set(e.waived??[]),n=e.gate??Tn(Tt(e));return gt.flatMap((r,i)=>{let s=n[i];if(t.has(r.rule)||typeof s!=="number"||Number.isNaN(s))return[];if(r.min!==void 0&&s<r.min)return[`${r.label} ${s} < ${r.min}`];if(r.max!==void 0&&s>r.max)return[`${r.label} ${s} > ${r.max}`];return[]})}function br(e,t){let n=e.find((r)=>r.name===t);if(!n)throw Error(`no palette named ${t} in the catalog — ${Ac(e,[t])}`);return n}function Ac(e,t){let n=t.map((o)=>o.toLowerCase()),r=e.filter((o)=>n.some((a)=>o.name.includes(a))),i=e.filter((o)=>!r.includes(o)&&n.some((a)=>o.group.toLowerCase().includes(a))),s=[...r,...i].map((o)=>o.name).slice(0,3);return s.length>0?`did you mean: ${s.join(", ")}?`:"`ttheme list` shows what is there"}function zg(e,t){let n=t.toLowerCase();return e.filter((r)=>[r.name,r.group,r.native??"",r.ansiSource].some((i)=>i.toLowerCase().includes(n)))}function Yg(e,t,n){let r=n.toLowerCase(),i=(s)=>s.name===t.name?0:s.group===t.group?1:2;return e.filter((s)=>s.booru?.toLowerCase().includes(r)).map((s,o)=>({p:s,at:o})).sort((s,o)=>i(s.p)-i(o.p)||s.at-o.at).map(({p:s})=>s)}function Qg(e,t){return e.booruSites?.[t]??(e.booru?[e.booru]:[])}import{execFileSync as fE}from"node:child_process";import{existsSync as Dc,mkdirSync as Dm,readdirSync as dE,readFileSync as tl,rmSync as ep}from"node:fs";import{basename as gE,join as Sr,relative as mE}from"node:path";import{execFileSync as F1,spawn as R1}from"node:child_process";import{existsSync as Bt,mkdirSync as O1,readFileSync as pi,realpathSync as T1,rmSync as Kc,utimesSync as H1,writeFileSync as A1}from"node:fs";import{homedir as bi}from"node:os";import{dirname as L1,join as He}from"node:path";var s1=["black","red","green","yellow","blue","magenta","cyan","white"];function Zg(e,t){return[e,...s1.map((n,r)=>`${n} = '${t[r]}'`),""].join(`
328
+ `)}var ys={id:"alacritty",limits:"no runtime color API (OSC only)",emit(e){let t=[...ci(e),"","[colors.primary]",`background = '${e.background}'`,`foreground = '${e.foreground}'`,"","[colors.cursor]",`cursor = '${e.cursor}'`,`text = '${e.background}'`,"","[colors.selection]",`background = '${e.selectionBackground}'`,`text = '${e.foreground}'`,"",Zg("[colors.normal]",e.ansi.slice(0,8)),Zg("[colors.bright]",e.ansi.slice(8,16))].join(`
329
+ `);return[{path:`alacritty/themes/${ye(e.name)}.toml`,content:t}]}};var Es={id:"ghostty",emit(e){let t=[...ci(e),`background = ${e.background}`,`foreground = ${e.foreground}`,`cursor-color = ${e.cursor}`,`selection-background = ${e.selectionBackground}`,`selection-foreground = ${e.foreground}`,...e.ansi.map((n,r)=>`palette = ${r}=${n}`),"palette-generate = true","","macos-icon = custom-style",`macos-icon-ghost-color = ${e.ghostty.iconGhost}`,`macos-icon-screen-color = ${e.ghostty.iconScreen.join(",")}`,"macos-icon-frame = chrome",""].join(`
330
+ `);return[{path:`ghostty/themes/${ye(e.name)}`,content:t}]}};function Vn(e){let[t,n,r]=Ue(e);return{"Alpha Component":1,"Blue Component":r/255,"Color Space":"P3","Green Component":n/255,"Red Component":t/255}}function Vg(e){return{...Object.fromEntries(e.ansi.map((t,n)=>[`Ansi ${n} Color`,Vn(t)])),"Background Color":Vn(e.background),"Bold Color":Vn(e.foreground),"Cursor Color":Vn(e.cursor),"Cursor Text Color":Vn(e.background),"Foreground Color":Vn(e.foreground),"Selected Text Color":Vn(e.foreground),"Selection Color":Vn(e.selectionBackground)}}function o1(e){return e?{"Background Image Location":e.image,"Background Image Mode":e.cover?2:3,Blend:e.opacity}:{"Background Image Location":""}}function Xg(e,t,n,r){let i=(o,a)=>({Name:`ttheme · ${a}`,Guid:ye(a),...r?{"Dynamic Profile Parent GUID":r}:{},"Use Separate Colors for Light and Dark Mode":!1,"Harmonize 256 Colors":!0,...o1(t.get(o.name)),...Vg(o)}),s=[...n?[i(n,"default")]:[],...e.map((o)=>i(o,o.name))];return`${JSON.stringify({Profiles:s},null,2)}
331
+ `}function a1(e,t){return[` <key>${e}</key>`,"\t<dict>",...Object.entries(t).flatMap(([n,r])=>[` <key>${n}</key>`,typeof r==="string"?` <string>${r}</string>`:` <real>${r}</real>`]),"\t</dict>"].join(`
332
+ `)}var vs={id:"iterm2",limits:"colors are Display P3, the space iTerm2 reads OSC colors in",emit(e){let t=['<?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(Vg(e)).map(([n,r])=>a1(n,r)),"</dict>","</plist>",""].join(`
333
+ `);return[{path:`iterm2/${ye(e.name)}.itermcolors`,content:t}]}};var Ms={id:"kitty",emit(e){let t=[...ci(e),`background ${e.background}`,`foreground ${e.foreground}`,`cursor ${e.cursor}`,`cursor_text_color ${e.background}`,`selection_background ${e.selectionBackground}`,`selection_foreground ${e.foreground}`,...e.ansi.map((n,r)=>`color${r} ${n}`),""].join(`
334
+ `);return[{path:`kitty/themes/${ye(e.name)}.conf`,content:t}]}};function Dg(e){return["# Generated by ttheme — rewritten on every add, remove and default; do not edit.","import os","",`THEMES = ${JSON.stringify(e.themes)}`,`BACKGROUNDS = ${JSON.stringify(e.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.replace('@', '--', 1).replace('/', '--', 1) + '.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, 'ttheme-' + palette.replace('@', '--', 1).replace('/', '--', 1) + '.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(`
335
+ `)}var em=44,Ht=[{name:"Shell",lines:["«B4»~/code/demo«d» on «5»main«2» +2«3» ~1","«2»❯ «»git status -sb","«w»## «2»main«»...«1»origin/main«3» [ahead 1]","«1» M«» src/main.rs","«1»??«» notes.md","","«w»«2»❯ «»ls","«w»«B4»docs«» «B4»src«» «B4»tests«» Cargo.toml README.md","«w»","«2»❯ «»cargo test","«2» ✓«» parses config","«n»«1» ✗«» renders frame","«w»«1» ✗«» renders frame«d» expected «2»3«d», received «1»2","","«2»❯ «»echo «s»selected text«» «c» "]},{name:"Code",lines:["«d» 12 │ «5»import«» { readFile } «5»from «2»'node:fs/promises'","«d» 13 │","«d» 14 │ «8»// Read a palette and check its sixteen colors","«d» 15 │ «5»export async function «4»load«»(path: «6»string«») {","«d» 16 │ «5»const«» text = «5»await «4»readFile«»(path, «2»'utf8'«»)","«b» 17 «d»│ «5»const«» colors = «s»parse(text)«».colors ?? {}","«d» 18 │ «5»if«» (colors.ansi.length !== «3»16«») {","«d» 19 │ «5»throw new «6»Error«»(«2»'needs 16 colors'«»)","«d» 20 │ }","«d» 21 │ «5»return«» { ...colors, ratio: «c»4«3».5«» }","«d» 22 │ }"]},{name:"Diff",lines:["«2»❯ «»git diff --stat","«» src/theme.ts | 3 «2»++«1»-","«2»❯ «»git diff","«b»diff --git a/src/theme.ts b/src/theme.ts","«6»@@ -16,3 +16,4 @@«» export async function load(","«» const text = await readFile(path, 'utf8')","«1»- const colors = parse(text).colors","«2»+ const colors = parse(text).colors ?? {}","«2»+ const ratio = contrast(colors)","«2»❯ «»git log --oneline --graph -4","«3»* 3f2a1c9 («B6»HEAD -> «B2»main«3»)«» Check contrast on load","«3»* 9b04e7d«» Merge branch ansi","«1»|«5»\\","«1»| «5»* «3»51cd0aa«» Add sixteen ANSI colors","«1»|«5»/","«3»* 07be2f1 («B1»origin/main«3», «B3»tag: v1.0«3»)«» Read palette files"]},{name:"Logs",lines:["«2»❯ «»npm run dev","«B2» VITE v6.2.0«d» ready in «b»412«d» ms","«2» ➜ «b»Local«»: «6»http://localhost:5173/","«d»10:42:07 «2»INFO «» GET /api/palettes «2»200«d» 12 ms","«d»10:42:08 «2»INFO «» GET /api/themes/kita «2»200«d» 8 ms","«d»10:42:09 «3»WARN «» slow query: palettes «3»812 ms","«d»10:42:10 «4»DEBUG«» cache hit themes/kita","«d»10:42:11 «B1»ERROR«» POST /api/share «1»500«d» 41 ms","«1» Error«»: read ECONNRESET","«d» at «»TCP.onStreamRead «d»(«6»node:net:216:20«d»)","«d» at «»share «d»(«6»src/share.ts:48:11«d»)","«d»10:42:12 «2»INFO «» retry 1/3 in 200 ms"]},{name:"Monitor",lines:["«6» 1 «b»[«2»|||||||||||||«1»||«» 42.1%«b»]«6» Tasks: «b»128«», 412 thr; «B2»3«» running","«6» 2 «b»[«2»||||||«4»||«» 21.4%«b»]«6» Load average: «b»1.42 «»1.18 0.97","«6» 3 «b»[«2»||||||||||||||«1»|||||«» 71.0%«b»]«6» Uptime: «b»3 days, 04:12:55","«6» 4 «b»[«2»||«» 7.9%«b»]","«6» Mem«b»[«2»||||||||«4»||«3»||«» 6.21G/16.0G«b»]","«6» Swp«b»[«1»|«» 0.10G/2.00G«b»]","","«K2» PID USER CPU% MEM% TIME+ Command ","«s» 4127 kec 38.2 2.1 3:12.44 node dev.js ","«» 2210 kec 12.0 4.8 1:02.10 «b»ghostty","«» 3301 kec 4.4 1.2 0:05.61 «b»zsh","«» 812 «1»root«» 3.1 0.3 0:44.02 «d»kernel_task","«» 167 «1»root«» 0.9 0.1 0:12.80 «d»WindowServer"]}];function ga(e){let t=Ht.length;return Ht[(e%t+t)%t]}function tm(e,t){let n=e.split("«"),r=n[0]?[[n[0],""]]:[];for(let i of n.slice(1)){let s=i.indexOf("»"),o=i.slice(0,s),a=i.slice(s+1);if(o==="w"||o==="n"){if(o==="w"!==t>=44)return}if(a)r.push([a,o==="w"||o==="n"?"":o])}return r}import{openSync as u1,writeSync as c1}from"node:fs";import{ReadStream as l1}from"node:tty";var li=["11","10","12","17",...Array.from({length:16},(e,t)=>`4;${t}`)];function At(e=process.env){return Boolean(e.NO_COLOR)||e.TERM==="dumb"}function Lc(e,t){return`\x1B]${li[e]};${t}\x1B\\`}function ma(e,t){return[e.background,e.foreground,e.cursor,e.selection,...e.ansi].map((n,r)=>t&&!t.includes(r)?"":Lc(r,n)).join("")}function h1(e){return`\x1B]${e.startsWith("4;")?`104;${e.slice(2)}`:`1${e}`}\x1B\\`}function f1(e){let t=new Map;for(let n of e.split("\x1B")){let r=n.match(/^\](\d+(?:;\d+)?);(rgba?:[0-9a-fA-F/]+)/),[,i,s]=r??[];if(i&&s)t.set(i,s)}return t}function nm(e,t=[...e.keys()]){return t.map((n)=>{let r=e.get(n);return r?`\x1B]${n};${r}\x1B\\`:h1(n)}).join("")}function d1(e=li){return`${e.map((t)=>`\x1B]${t};?\x1B\\`).join("")}\x1B[5n`}function g1(e){return e.includes("\x1B[0n")}async function rm(e=li){let t,n;try{t=u1("/dev/tty","r+"),n=new l1(t),n.setRawMode(!0)}catch{return new Map}try{c1(t,d1(e));let r="";return await new Promise((i)=>{let s=setTimeout(i,120);n.on("data",(o)=>{if(r+=o.toString(),g1(r))clearTimeout(s),i()})}),f1(r)}finally{n.setRawMode(!1),n.destroy()}}function wr(e){if(e.TERM_PROGRAM==="WarpTerminal")return"warp";if(e.GHOSTTY_RESOURCES_DIR||e.TERM_PROGRAM==="ghostty")return"ghostty";if(e.KITTY_WINDOW_ID)return"kitty";if(e.WEZTERM_PANE)return"wezterm";if(e.ALACRITTY_WINDOW_ID)return"alacritty";if(e.ITERM_SESSION_ID||e.TERM_PROGRAM==="iTerm.app")return"iterm2";if(e.TERM_PROGRAM==="Apple_Terminal")return"terminal-app";if(e.WT_SESSION&&!e.TERM_PROGRAM)return"windows-terminal";if(e.TERM?.startsWith("foot"))return"foot";return"unknown"}var Xn={ghostty:{links:!0,pictures:!0,bands:!1,paints:!0},kitty:{links:!0,pictures:!0,bands:!1,paints:!0},iterm2:{links:!0,pictures:!0,bands:!0,paints:!0,repaint:[0,1]},wezterm:{links:!0,pictures:!1,bands:!1,paints:!0},alacritty:{links:!0,pictures:!1,bands:!1,paints:!0},"windows-terminal":{links:!0,pictures:!1,bands:!1,paints:!0},foot:{links:!0,pictures:!1,bands:!1,paints:!0},"terminal-app":{links:!1,pictures:!1,bands:!1,paints:!0},warp:{links:!1,pictures:!1,bands:!1,paints:!1},unknown:{links:!1,pictures:!1,bands:!1,paints:!0}};function im(e){return Xn[wr(e)].links}function sm(e){return Xn[wr(e)].pictures&&!e.TMUX}function om(e){return Xn[wr(e)].bands}var hi="\x1B[H\x1B[K\x1B[2H\x1B[J\x1B[H";function Dn(e,t){let n=Xn[wr(e)];if(!t||At(e)||e.TMUX||!n.paints)return;let r=n.repaint??li.map((s,o)=>o),i=li.filter((s,o)=>r.includes(o));return{slots:r,paint:(s)=>ma(s,r),saved:()=>rm(i),restore:(s)=>nm(s,i)}}var m1=["ghostty","kitty","alacritty","wezterm","iterm2","windows-terminal","warp"],p1=[{section:"tab",title:"This tab"},{section:"startup",title:"New tabs"},{section:"catalog",title:"Palettes"},{section:"own",title:"Your own"},{section:"setup",title:"Setup"}],Is=[{name:"preview",args:[],about:"Browse live — focus repaints, enter keeps (this tab or default), esc restores, ? lists keys",section:"tab",start:"Try every palette live — enter keeps the one you land on",shell:!0},{name:"use",args:["<palette>"],about:"Paint this tab — a unique prefix works: ttheme use ho",section:"tab",start:"Paint this tab with one — ttheme use homura",shell:!0},{name:"next",args:[],about:"Advance this tab to the next palette",section:"tab",shell:!0},{name:"default",args:["<palette>"],about:"Make a palette the one new tabs open with",section:"startup"},{name:"on",args:[],about:"Wear the default palette in new tabs again",section:"startup"},{name:"off",args:[],about:"Take the palette and picture off every tab — the terminal's own colors until `ttheme on`",section:"startup"},{name:"pin",args:["[directory]"],about:"Pick a palette for this directory, everything below it or its repository — cd in repaints, cd out restores",section:"tab",shell:!0},{name:"unpin",args:["[directory]"],about:"Drop a pin — this directory's, every one below it, or the one above that paints it",section:"tab",shell:!0},{name:"pins",args:[],about:"Map every pinned directory as a tree in its palette's colors, and the pin that covers this one",section:"tab",shell:!0},{name:"config",args:[],about:"Edit settings in $EDITOR — they apply in new tabs",section:"startup",shell:!0},{name:"browse",args:[],about:"Pick palettes and markets in a live picker — tab moves between Catalog, Installed, Markets and Errors",section:"catalog",start:"Install or drop palettes, add markets — every change applies at once on enter"},{name:"list",args:["[query]"],about:"Show the catalog, marking what is installed",section:"catalog",flags:{json:{type:"boolean",about:"Print the matches as JSON: name, group, catalog, installed"}}},{name:"add",args:["<palette...>"],about:"Install palettes from the catalog, or from a share code: ttheme add tt1:…",section:"catalog",flags:{market:{type:"string",value:"<source>",about:"Add this market first — a repository, a folder or official — and take bare palette names from it"}}},{name:"remove",args:["<palette...>"],about:"Uninstall palettes",section:"catalog"},{name:"update",args:[],about:"Refresh every market you added now — those with auto-update refresh on their own once a day",section:"catalog"},{name:"market",args:["[action]","[source]"],about:"The markets you added — add, remove and search them; init makes one of your own",actions:[["(none)","List the markets you added: palettes, auto-update and the last update"],["add <source>","Add one: a repository (alice/ttheme-pastel, #v1 pins a tag or branch), a folder, or official — asks whether it updates on its own"],["remove <market>","Drop one by its name (alice@pastel) — the palettes you installed from it keep working"],["search [query]","Repositories on GitHub with the ttheme-market topic"],["init [name]","Make a market of your own, <you>@<name>, in ~/.config/ttheme/market/<name> (or give a folder)"]],section:"catalog"},{name:"new",args:["<name>"],about:"Make a palette of your own, <you>@<market>/<name>, from blank in the palette editor — installed at once",section:"own",flags:{from:{type:"string",value:"<palette>",about:"Open the editor on this palette's colors instead of blank"},in:{type:"string",value:"<market>",about:"The local market to put it in, when you have more than one"}}},{name:"edit",args:["<palette>"],about:"Change one of your palettes in the palette editor — the contrast gate advises, never refuses",section:"own"},{name:"check",args:["<palette>"],about:"Measure a palette against the contrast gate and suggest colors that pass",section:"own",flags:{fix:{type:"boolean",about:"Write the suggested colors into your palette"}}},{name:"share",args:["<palette>"],about:"Print a share code — ttheme add <code> installs it anywhere, pictures included",section:"own"},{name:"init",args:[],about:"Install the shell layer and wire your terminal configs",section:"setup",flags:{yes:{type:"boolean",short:"y",about:"Accept every default without prompting"}}},{name:"uninstall",args:[],about:"Take ttheme out of every terminal config and delete what it wrote",section:"setup",flags:{yes:{type:"boolean",short:"y",about:"Remove without asking"}}},{name:"build",args:[],about:"Emit dist/ for every terminal, plus the zsh palette table — from a checkout",section:"setup",hidden:!0,flags:{only:{type:"string",multiple:!0,value:"<terminal>",choices:m1,about:"Rebuild just this terminal — repeat it for more"}}},{name:"find",args:["<palette>"],about:"Pick a booru background for a palette — preview opens this on tab",section:"setup",hidden:!0},{name:"image",args:["<palette>","<action>","[picture]"],about:"Show one of a palette's saved backgrounds, remove one, or pass on tuning — preview calls this",section:"setup",hidden:!0},{name:"redraw",args:[],about:"Draw the background pictures again after TTHEME_BG_BLUR changed — ttheme config and preview call this",section:"setup",hidden:!0}];function Ss(e){let t=Object.entries(e.flags??{}).map(([n,{value:r}])=>`[--${n}${r?` ${r}`:""}]`);return[e.name,...t,...e.args].join(" ")}function xc(e,t=Math.max(...e.map(([n])=>n.length))){return e.map(([n,r])=>` ${n.padEnd(t)} ${r}`)}var b1=[["npx @kecan0406/ttheme init -y","Wire the terminals found here, no prompts"],["ttheme add homura madoka","Install two palettes"],["ttheme use homura","Paint this tab with one"],["ttheme list --json madoka","The madoka series as JSON"],["ttheme market add alice/ttheme-pastel","alice's market, alice@pastel — ttheme add alice@pastel/dusk"],["ttheme add dusk --market alice/ttheme-pastel","The same in one step"],["ttheme new rei --from rei","Your own rei, <you>@<market>/rei, to edit and share"]];function Ns(e,t=!1){let n=Is.filter((o)=>!o.hidden&&!(t&&o.section==="setup")),r=p1.filter(({section:o})=>n.some((a)=>a.section===o)),i=[...t?["ttheme alone lists every installed palette, grouped, with previews"]:[],e?"ttheme help <command> describes one command · ttheme --version prints the version":"ttheme help <command> describes one · ttheme help all lists every command with what it does","https://kecan0406.github.io/ttheme"];if(!e){let o=n.filter((u)=>u.start),a=Math.max(...r.map(({title:u})=>u.length));return["Usage: ttheme <command>","",nt.description,"","Start here",...xc(o.map((u)=>[Ss(u),u.start])),"",...r.map(({section:u,title:c})=>`${c.padEnd(a)} ${n.filter((l)=>l.section===u).map((l)=>l.name).join(" · ")}`),"",...i].join(`
336
+ `)}let s=Math.max(...n.map((o)=>Ss(o).length));return["Usage: ttheme <command>","",nt.description,...r.flatMap(({section:o,title:a})=>["",a,...xc(n.filter((u)=>u.section===o).map((u)=>[Ss(u),u.about]),s)]),"","Examples",...xc(b1),"",...i].join(`
337
+ `)}import{readFileSync as w1}from"node:fs";import{join as $1}from"node:path";var pa=["ghostty","kitty","alacritty","wezterm","iterm2","windows-terminal","warp"],fi={ghostty:"Ghostty",kitty:"kitty",alacritty:"Alacritty",wezterm:"WezTerm",iterm2:"iTerm2","windows-terminal":"Windows Terminal",warp:"Warp"},lm="# ttheme begin",hm="# ttheme end",Ps=/# ttheme begin\n[\s\S]*?# ttheme end\n?/;function Fs(e,t){let n=`${lm}
334
338
  ${t}
335
- ${ug}
336
- `;if(xi.test(e))return e.replace(xi,n);if(e==="")return n;return`${e.replace(/\n*$/,`
339
+ ${hm}
340
+ `;if(Ps.test(e))return e.replace(Ps,n);if(e==="")return n;return`${e.replace(/\n*$/,`
337
341
  `)}
338
- ${n}`}function es(e){let t=e.replace(/\n?# ttheme begin\n[\s\S]*?# ttheme end(?=\n|$)/,"");if(t===e)return e;return t.trim()===""?"":t.replace(/\n*$/,`
339
- `)}function ir(e,t){let n=e.replace(xi,"");return new RegExp(String.raw`^[ \t]*${t}(?:[ \t]*=|[ \t]+\S)`,"m").test(n)}function Kr(e){if(e.TERM_PROGRAM==="WarpTerminal")return"warp";if(e.GHOSTTY_RESOURCES_DIR||e.TERM_PROGRAM==="ghostty")return"ghostty";if(e.KITTY_WINDOW_ID)return"kitty";if(e.WEZTERM_PANE)return"wezterm";if(e.ALACRITTY_WINDOW_ID)return"alacritty";if(e.ITERM_SESSION_ID||e.TERM_PROGRAM==="iTerm.app")return"iterm2";if(e.TERM_PROGRAM==="Apple_Terminal")return"terminal-app";if(e.WT_SESSION&&!e.TERM_PROGRAM)return"windows-terminal";if(e.TERM?.startsWith("foot"))return"foot";return"unknown"}function cg(e,t,n=""){let r=[];if(!ir(n,"command")){if(r.push(`command = ${e}/launch-tab.zsh`),!ir(n,"shell-integration"))r.push("shell-integration = zsh")}if(t)r.push(`theme = ${$e(t)}`);return r.push(`config-file = ?${e}/backgrounds/shown.conf`),r.join(`
340
- `)}function lg(e){return`source ${e}/ttheme.zsh`}var Ck="# ttheme settings — uncomment a line to change it; exported variables win over this file",qr={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_BG_BLUR:{doc:"# soften the background pictures behind the text: a blur radius in screen pixels, 0 keeps them sharp — changing it draws every picture again (default 0)",default:"0"},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 posts tagged solo, the character alone, by danbooru or zerochan; 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_MIN_SCORE:{doc:"# the lowest score find lists: off, or a number such as 5, 10, 25, 50 or 100 — danbooru, konachan and yande.re filter by it, zerochan keeps no score (default off)",default:"off"},TTHEME_FIND_MIN_SIZE:{doc:"# the shortest side a picture find lists must reach, in pixels: off, or a number such as 720, 1080, 1440, 1800 or 2560 (default off)",default:"off"},TTHEME_FIND_SITES:{doc:"# the sites find mixes in its all tab: any of danbooru, konachan, yande.re and zerochan (default all four)",default:"danbooru konachan yande.re zerochan"},TTHEME_FIND_HIDE:{doc:"# the kinds of picture find leaves out by tag: comic, monochrome, sketch, chibi, or none to keep them all (default none)",default:"none"},TTHEME_FIND_HIDE_TAGS:{doc:'# more tags find leaves out, spaced — e.g. "cosplay multiple_girls" (default none)',default:""},TTHEME_FIND_PNG:{doc:"# on lists PNG originals only — a zerochan post counts only where danbooru holds the same file (default off)",default:"off"},TTHEME_FIND_HOSTS:{doc:'# send a find site somewhere else, as key=https://host pairs — e.g. "danbooru=https://danbooru.donmai.us" (default none)',default:""}};function Zu(e){return qr[e]?.default}function zu(e,t){let n=`: \${${e}:=${t}}`;return Zu(e)===t?`# ${n}`:n}function hg(e){return new RegExp(String.raw`^#? ?: \$\{${e}[^\n]*$`,"m")}function jk(e,t){if(hg(t).test(e))return e;let n=qr[t];return`${e.replace(/\n*$/,`
342
+ ${n}`}function Rs(e){let t=e.replace(/\n?# ttheme begin\n[\s\S]*?# ttheme end(?=\n|$)/,"");if(t===e)return e;return t.trim()===""?"":t.replace(/\n*$/,`
343
+ `)}function $r(e,t){let n=e.replace(Ps,"");return new RegExp(String.raw`^[ \t]*${t}(?:[ \t]*=|[ \t]+\S)`,"m").test(n)}function fm(e,t,n=""){let r=[];if(!$r(n,"command")){if(r.push(`command = ${e}/launch-tab.zsh`),!$r(n,"shell-integration"))r.push("shell-integration = zsh")}if(t)r.push(`theme = ${ye(t)}`);return r.push(`config-file = ?${e}/backgrounds/shown.conf`),r.join(`
344
+ `)}function dm(e){return`source ${e}/ttheme.zsh`}var k1="# ttheme settings — uncomment a line to change it; exported variables win over this file",di={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_BG_BLUR:{doc:"# soften the background pictures behind the text: a blur radius in screen pixels, 0 keeps them sharp — changing it draws every picture again (default 0)",default:"0"},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 posts tagged solo, the character alone, by danbooru or zerochan; 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_MIN_SCORE:{doc:"# the lowest score find lists: off, or a number such as 5, 10, 25, 50 or 100 — danbooru, konachan and yande.re filter by it, zerochan keeps no score (default off)",default:"off"},TTHEME_FIND_MIN_SIZE:{doc:"# the shortest side a picture find lists must reach, in pixels: off, or a number such as 720, 1080, 1440, 1800 or 2560 (default off)",default:"off"},TTHEME_FIND_SITES:{doc:"# the sites find mixes in its all tab: any of danbooru, konachan, yande.re and zerochan (default all four)",default:"danbooru konachan yande.re zerochan"},TTHEME_FIND_HIDE:{doc:"# the kinds of picture find leaves out by tag: comic, monochrome, sketch, chibi, or none to keep them all (default none)",default:"none"},TTHEME_FIND_HIDE_TAGS:{doc:'# more tags find leaves out, spaced — e.g. "cosplay multiple_girls" (default none)',default:""},TTHEME_FIND_PNG:{doc:"# on lists PNG originals only — a zerochan post counts only where danbooru holds the same file (default off)",default:"off"},TTHEME_FIND_HOSTS:{doc:'# send a find site somewhere else, as key=https://host pairs — e.g. "danbooru=https://danbooru.donmai.us" (default none)',default:""}};function Cc(e){return di[e]?.default}function _c(e,t){let n=`: \${${e}:=${t}}`;return Cc(e)===t?`# ${n}`:n}function gm(e){return new RegExp(String.raw`^#? ?: \$\{${e}[^\n]*$`,"m")}function y1(e,t){if(gm(t).test(e))return e;let n=di[t];return`${e.replace(/\n*$/,`
341
345
  `)}
342
346
  ${n.doc}
343
- ${zu(t,n.default)}
344
- `}var fg=Object.keys(qr),Wk=8;function Qr(e){let t="";try{t=Uk(_k(e,"ttheme","config.zsh"),"utf8")}catch{}let n=/^: \$\{TTHEME_BG_BLUR:=([^}\n]*)\}/m.exec(t)?.[1]??qr.TTHEME_BG_BLUR.default,r=Number(n.replace(/^(["'])(.*)\1$/,"$2"));return Number.isFinite(r)?Math.min(Wk,Math.max(0,r)):0}function Bu(){let e=Object.entries(qr).map(([t,n])=>`${n.doc}
345
- ${zu(t,n.default)}`);return`${[Ck,...e].join(`
347
+ ${_c(t,n.default)}
348
+ `}var mm=Object.keys(di),E1=8;function gi(e){let t="";try{t=w1($1(e,"ttheme","config.zsh"),"utf8")}catch{}let n=/^: \$\{TTHEME_BG_BLUR:=([^}\n]*)\}/m.exec(t)?.[1]??di.TTHEME_BG_BLUR.default,r=Number(n.replace(/^(["'])(.*)\1$/,"$2"));return Number.isFinite(r)?Math.min(E1,Math.max(0,r)):0}function Gc(){let e=Object.entries(di).map(([t,n])=>`${n.doc}
349
+ ${_c(t,n.default)}`);return`${[k1,...e].join(`
346
350
 
347
351
  `)}
348
- `}function dg(e,t,n){let r=zu(t,n),i=hg(t);if(i.test(e))return e.replace(i,r);return`${e.replace(/\n*$/,`
352
+ `}function pm(e,t,n){let r=_c(t,n),i=gm(t);if(i.test(e))return e.replace(i,r);return`${e.replace(/\n*$/,`
349
353
  `)}
350
354
  ${r}
351
- `}function gg(e){if(e==="")return Bu();return Object.keys(qr).reduce(jk,e)}function mg(e,t,n=""){return[...e?[`include themes/${$e(e)}.conf`]:[],`watcher ${t}`,...["window_logo_scale 100","window_logo_alpha 1"].filter((r)=>!ir(n,r.split(" ")[0]))].join(`
352
- `)}function pg(e){let t=e.replace(xi,"");return/^[ \t]*\[colors[\].]/m.test(t)||/^[ \t]*colors[ \t]*[.=]/m.test(t)}var Jk=/^[ \t]*\[general\][ \t]*(?:#.*)?$/m,ig=/^[ \t]*\[/m,sg=/^[ \t]*import[ \t]*=/m,Kk=/^[ \t]*general[ \t]*[.=]/m;function qk(e){return e?`[general]
353
- import = ["${e}"]`:""}function ts(e,t){let n=e.replace(xi,""),r=Jk.exec(n);if(!r){let u=n.search(ig),c=u<0?n:n.slice(0,u);if(Kk.test(n)||sg.test(c))return;return Di(e,qk(t))}let i=r.index+r[0].length,s=n.slice(i),o=s.search(ig);if(sg.test(o<0?s:s.slice(0,o)))return;let a=t?`import = ["${t}"]
355
+ `}function bm(e){if(e==="")return Gc();return Object.keys(di).reduce(y1,e)}function wm(e,t,n=""){return[...e?[`include themes/${ye(e)}.conf`]:[],`watcher ${t}`,...["window_logo_scale 100","window_logo_alpha 1"].filter((r)=>!$r(n,r.split(" ")[0]))].join(`
356
+ `)}function $m(e){let t=e.replace(Ps,"");return/^[ \t]*\[colors[\].]/m.test(t)||/^[ \t]*colors[ \t]*[.=]/m.test(t)}var v1=/^[ \t]*\[general\][ \t]*(?:#.*)?$/m,am=/^[ \t]*\[/m,um=/^[ \t]*import[ \t]*=/m,M1=/^[ \t]*general[ \t]*[.=]/m;function S1(e){return e?`[general]
357
+ import = ["${e}"]`:""}function Os(e,t){let n=e.replace(Ps,""),r=v1.exec(n);if(!r){let u=n.search(am),c=u<0?n:n.slice(0,u);if(M1.test(n)||um.test(c))return;return Fs(e,S1(t))}let i=r.index+r[0].length,s=n.slice(i),o=s.search(am);if(um.test(o<0?s:s.slice(0,o)))return;let a=t?`import = ["${t}"]
354
358
  `:"";return`${n.slice(0,i)}
355
- ${ag}
356
- ${a}${ug}${s}`}var og=/-- ttheme begin\n[\s\S]*?-- ttheme end\n?/,Qk=/^return config[ \t]*$/gm;function wg(e){return`dofile(${JSON.stringify(e)})(config)`}var bg=`local wezterm = require 'wezterm'
359
+ ${lm}
360
+ ${a}${hm}${s}`}var cm=/-- ttheme begin\n[\s\S]*?-- ttheme end\n?/,I1=/^return config[ \t]*$/gm;function km(e){return`dofile(${JSON.stringify(e)})(config)`}var ym=`local wezterm = require 'wezterm'
357
361
  local config = wezterm.config_builder()
358
362
 
359
- `;function $g(e){let t=e.replace(/-- ttheme begin\n[\s\S]*?-- ttheme end\n\n?/,"");return t===`${bg}return config
360
- `?"":t}function ns(e,t){let n=`-- ttheme begin
363
+ `;function Em(e){let t=e.replace(/-- ttheme begin\n[\s\S]*?-- ttheme end\n\n?/,"");return t===`${ym}return config
364
+ `?"":t}function Ts(e,t){let n=`-- ttheme begin
361
365
  ${t}
362
366
  -- ttheme end
363
- `;if(og.test(e))return e.replace(og,n);if(e==="")return`${bg}${n}
367
+ `;if(cm.test(e))return e.replace(cm,n);if(e==="")return`${ym}${n}
364
368
  return config
365
- `;let r=[...e.matchAll(Qk)].at(-1);if(r?.index===void 0)return;return`${e.slice(0,r.index)}${n}
366
- ${e.slice(r.index)}`}var kg="[appearance.themes]";function yg(e){let t=e.findIndex((r)=>r.trim()===kg);if(t<0)return;let n=e.findIndex((r,i)=>i>t&&r.trimStart().startsWith("["));return[t,n<0?e.length:n]}function Oo(e){let t=e.split(`
367
- `),n=yg(t);if(!n)return;return t.slice(n[0]+1,n[1]).find((i)=>/^theme\s*=/.test(i))?.replace(/^theme\s*=\s*/,"").trim()}function Eg(e){return`{ custom = { name = "${e}", path = "${$e(e)}.yaml" } }`}function To(e,t){let n=e.split(`
368
- `),r=yg(n);if(!r)return t===void 0?e:`${e.replace(/\n*$/,`
369
+ `;let r=[...e.matchAll(I1)].at(-1);if(r?.index===void 0)return;return`${e.slice(0,r.index)}${n}
370
+ ${e.slice(r.index)}`}var vm="[appearance.themes]";function Mm(e){let t=e.findIndex((r)=>r.trim()===vm);if(t<0)return;let n=e.findIndex((r,i)=>i>t&&r.trimStart().startsWith("["));return[t,n<0?e.length:n]}function ba(e){let t=e.split(`
371
+ `),n=Mm(t);if(!n)return;return t.slice(n[0]+1,n[1]).find((i)=>/^theme\s*=/.test(i))?.replace(/^theme\s*=\s*/,"").trim()}function Sm(e){return`{ custom = { name = "${e}", path = "${ye(e)}.yaml" } }`}function wa(e,t){let n=e.split(`
372
+ `),r=Mm(n);if(!r)return t===void 0?e:`${e.replace(/\n*$/,`
369
373
  `)}
370
- ${kg}
374
+ ${vm}
371
375
  theme = ${t}
372
376
  `;let i=n.findIndex((s,o)=>o>r[0]&&o<r[1]&&/^theme\s*=/.test(s));if(i>=0)n.splice(i,1,...t===void 0?[]:[`theme = ${t}`]);else if(t!==void 0)n.splice(r[0]+1,0,`theme = ${t}`);return n.join(`
373
- `)}function Vu(e,t,n=[]){for(let c of e)for(let l of[c.name,c.group,c.native??"",c.ansiSource])if(/["$`\\]/.test(l))throw Error(`${c.name}: "${l}" contains a character that breaks zsh quoting`);let r=Math.max(0,...e.map((c)=>c.name.length)),i=(c,l)=>` ${c.name.padEnd(r)} "${l}"`,s=(c)=>c.map((l)=>l.name).join(" "),o=et(e),a=(c)=>`'${c.replaceAll("'","'\\''")}'`,u=Vi.filter((c)=>c.section!=="setup"&&!c.hidden);return["# Generated by `mise run build` — do not edit.","# Source of truth: themes/*.toml in the ttheme repo.","",`typeset -g TTHEME_VERSION=${Ve.version}`,"",'# the palette new tabs open with, which the iTerm2 "ttheme · default" profile wears',`typeset -g TTHEME_STARTUP=${t??""}`,"","# the terminals ttheme is wired into: a picture change reaches every one of them, from whichever runs the shell",`typeset -ga TTHEME_TERMINALS=(${n.join(" ")})`,"","# the commands the shell layer knows (src/verbs.ts): help, completion and argument checks read them",`typeset -ga TTHEME_VERBS=(${u.map((c)=>c.name).join(" ")})`,`typeset -ga TTHEME_SHELL_VERBS=(${u.filter((c)=>c.shell).map((c)=>c.name).join(" ")})`,"typeset -gA TTHEME_VERB_ARGS=(",...u.map((c)=>` ${c.name} ${a(c.args.join(" "))}`),")","typeset -gA TTHEME_VERB_ABOUT=(",...u.map((c)=>` ${c.name} ${a(c.about)}`),")",`typeset -g TTHEME_HELP=${a(Xi(!1,!0))}`,`typeset -g TTHEME_HELP_ALL=${a(Xi(!0,!0))}`,"","# the settings config.zsh holds, handed to the CLI on every call",`typeset -ga TTHEME_SETTINGS=(${fg.join(" ")})`,"","# seed for `ttheme config` when no config.zsh exists yet",`typeset -g TTHEME_CONFIG_TEMPLATE='${Bu().trimEnd().replaceAll("'","'\\''")}'`,"","typeset -gA TTHEME_PALETTE=(",...e.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=(${s(o)})`,"","# the same palettes by series name, then palette name: TTHEME_SORT=abc lists them this way",`typeset -ga TTHEME_ABC=(${s(Xn(o))})`,"","typeset -gA TTHEME_GROUP=(",...e.map((c)=>i(c,c.group)),")","","# the catalog a market palette sits in — the folder under the market's palettes/, one level below the market in every list","typeset -gA TTHEME_CATALOG=(",...e.filter((c)=>c.catalog).map((c)=>i(c,c.catalog??"")),")","","# original-language title, rendered dim next to the group","typeset -gA TTHEME_NATIVE=(",...e.filter((c)=>c.native).map((c)=>i(c,c.native??"")),")","","# the six colors a list row shows: foreground, the signature, then red and green","typeset -gA TTHEME_SWATCH=(",...e.map((c)=>i(c,yo(c).join(" "))),")","","# where each palette's 16 ANSI colors came from","typeset -gA TTHEME_SRC=(",...e.map((c)=>i(c,c.ansiSource)),")",""].join(`
374
- `)}var Xu={id:"shell",emitShared(e){return[{path:"shell/palettes.zsh",content:Vu(e.map(Pt))}]}};var Yk=["black","red","green","yellow","blue","magenta","cyan","white"];function vg(e,t){return[` ${e}:`,...Yk.map((n,r)=>` ${n}: "${t[r]}"`)]}var rs={id:"warp",limits:"no selection color, and Warp paints one theme app-wide",emit(e){let t=[`name: "${e.name}"`,`background: "${e.background}"`,`foreground: "${e.foreground}"`,`accent: "${e.cursor}"`,`cursor: "${e.cursor}"`,`details: ${nt(e.background)<0.18?"darker":"lighter"}`,"terminal_colors:",...vg("normal",e.ansi.slice(0,8)),...vg("bright",e.ansi.slice(8,16)),""].join(`
375
- `);return[{path:`warp/themes/${$e(e.name)}.yaml`,content:t}]}};var Mg=(e)=>`[${e.map((t)=>`"${t}"`).join(", ")}]`,is={id:"wezterm",limits:"OSC repaints per pane, pictures show per window",emit(e){let t=["[metadata]",`name = "${$e(e.name)}"`,`origin_url = "${e.ansiSource}"`,"","[colors]",`foreground = "${e.foreground}"`,`background = "${e.background}"`,`cursor_bg = "${e.cursor}"`,`cursor_border = "${e.cursor}"`,`cursor_fg = "${e.background}"`,`selection_bg = "${e.selectionBackground}"`,`selection_fg = "${e.foreground}"`,"",`ansi = ${Mg(e.ansi.slice(0,8))}`,`brights = ${Mg(e.ansi.slice(8,16))}`,""].join(`
376
- `);return[{path:`wezterm/colors/${$e(e.name)}.toml`,content:t}]}},Yr=(e)=>JSON.stringify(e);function Sg(e){return["-- Generated by ttheme — rewritten on every add, remove and default; do not edit.","local wezterm = require 'wezterm'","",`local MODULE = ${Yr(e.path)}`,`local COLORS = ${Yr(e.colors)}`,`local BACKGROUNDS = ${Yr(e.backgrounds)}`,`local STARTUP = ${e.startup?Yr($e(e.startup)):"nil"}`,"local PALETTES = {",...e.palettes.map((t)=>` [${Yr(t.name)}] = ${Yr(t.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:gsub('@', '--', 1)):gsub('/', '--', 1)) .. '.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(`
377
- `)}var Ig=["black","red","green","yellow","blue","purple","cyan","white"];function Ng(e){return{name:$e(e.name),background:e.background,foreground:e.foreground,cursorColor:e.cursor,selectionBackground:e.selectionBackground,...Object.fromEntries(Ig.map((t,n)=>[t,e.ansi[n]])),...Object.fromEntries(Ig.map((t,n)=>[`bright${t[0]?.toUpperCase()}${t.slice(1)}`,e.ansi[n+8]]))}}function xu(e,t,n){let r={...t&&n?{profiles:[{updates:t,colorScheme:$e(n)}]}:{},schemes:e.map(Ng)};return`${JSON.stringify(r,null,2)}
378
- `}var ss={id:"windows-terminal",limits:"no kitty graphics, so no pictures; OSC repaints per pane",emit(e){return[{path:`windows-terminal/schemes/${$e(e.name)}.json`,content:`${JSON.stringify(Ng(e),null,2)}
379
- `}]},emitShared(e){return[{path:"windows-terminal/ttheme.json",content:xu(e)}]}};function $e(e){return`ttheme-${sn(e)}`}function Wr(e){return[`# ${e.name} — ${e.group}${e.native?` (${e.native})`:""}`,`# ANSI: ${e.ansiSource}`]}var ey={ghostty:Yi,kitty:zi,alacritty:Qi,wezterm:is,iterm2:Zi,"windows-terminal":ss,warp:rs},Rg="ttheme-default";function cn(e=process.env.TTHEME_ITERM_SUITE??"com.googlecode.iterm2"){let t=(n,r)=>Zk(n,r,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();return{read:()=>{try{return process.platform==="darwin"?t("defaults",["read",e,"Default Bookmark Guid"])||void 0:void 0}catch{return}},write:(n)=>{if(process.platform==="darwin")t("defaults",["write",e,"Default Bookmark Guid","-string",n])},running:()=>{try{return t("pgrep",["-x","iTerm2"])!==""}catch{return!1}}}}function dt(e){return e.off?void 0:ln(e)}function os(e,t){if(!e.terminals.includes("iterm2"))return e;let n=t.read();return n&&!n.startsWith("ttheme-")?{...e,itermBase:n}:e}function ar(e,t){if(!e.terminals.includes("iterm2"))return!1;let n=t.read(),r=dt(e)?Rg:n===Rg?e.itermBase:void 0;if(!r||r===n)return!1;return t.write(r),!0}function he(){return process.env.XDG_CONFIG_HOME??Te(zr(),".config")}function as(e){return Te(e,"Library","Application Support","iTerm2","DynamicProfiles","ttheme.json")}function se(e){let t=Rn(e);if(!Ht(t))throw Error(`nothing installed yet at ${t} — run \`ttheme init\` first`);let n=JSON.parse(Zr(t,"utf8"));if(!Array.isArray(n?.palettes)||!Array.isArray(n.terminals))throw Error(`${t} has no palettes or terminals`);return{terminals:n.terminals.filter((r)=>Po.includes(r)),...n.author?{author:n.author}:{},...n.startup?{startup:n.startup}:{},...n.off?{off:!0}:{},...n.itermBase?{itermBase:n.itermBase}:{},...n.wtHome?{wtHome:n.wtHome}:{},...n.wtProfile?{wtProfile:n.wtProfile}:{},...Array.isArray(n.markets)?{markets:n.markets.filter((r)=>typeof r==="string")}:{},...n.updates&&typeof n.updates==="object"?{updates:Object.fromEntries(Object.entries(n.updates).filter((r)=>typeof r[1]==="boolean"))}:{},palettes:n.palettes}}function Et(e,t){ke(Rn(e),`${JSON.stringify(t,null,2)}
380
- `)}function Fg(e,t){let n=new Map(e.palettes.map((i)=>[i.name,i])),r=t.filter((i)=>!n.has(i));if(r.length>0){let i=[...new Set(r.flatMap((o)=>ye(o)??[]))].filter((o)=>!e.palettes.some((a)=>ye(a.name)===o)),s=i.length>0?`add ${i.join(", ")} first — \`ttheme market search\` finds a market's repository`:Qu(et(e.palettes),r);throw Error(`not in any market: ${r.join(", ")} — ${s}`)}return e.palettes.filter((i)=>t.includes(i.name))}function Pg(e,t){let n=e==="wezterm"?"colors":"themes";return(ey[e].emit?.(t)??[]).flatMap((r)=>{let[,i,s]=r.path.split("/");return i===n&&s!==void 0?[{file:s,content:r.content}]:[]})}function Ao(e){return process.platform==="darwin"?Te(e,".warp","themes"):Te(process.env.XDG_DATA_HOME??Te(e,".local","share"),"warp-terminal","themes")}function sr(e,t,n){if(e==="warp")return Ao(n);return Te(t,e,e==="wezterm"?"colors":"themes")}function Ho(e,t){return process.platform==="darwin"?Te(e,".warp","settings.toml"):Te(t,"warp-terminal","settings.toml")}var ec='"dark"';function tc(e){return Te(e,"ttheme","warp.base")}var ty="setTimeout(() => { const fs = require('node:fs'); const [file, next, seen] = process.argv.slice(-3); if (fs.readFileSync(file, 'utf8') !== seen) return; const tmp = file + '.ttheme-' + process.pid; fs.writeFileSync(tmp, next); fs.chmodSync(tmp, fs.statSync(file).mode & 0o7777); fs.renameSync(tmp, file) }, 1500)";function ny(e,t,n,r){let i=Ho(t,e);if(!Ht(i))return;let s=tc(e),o=Zr(i,"utf8"),a=Oo(o),u=a?.includes(`path = "${$e("")}`)===!0,c;if(n){if(!u&&!Ht(s))Bk(Dk(s),{recursive:!0}),xk(s,a??"");c=Eg(n)}else{if(!u)return;c=Ht(s)&&Zr(s,"utf8")||ec,Du(s,{force:!0})}let l=To(o,c);if(l===o)return;if(r)Qa(i),zk(process.execPath,["-e",ty,Vk(i),l,o],{detached:!0,stdio:"ignore"}).unref();else ki(i,l);return i}function Og(e){return Te(e,"ttheme","kitty.py")}function Br(e,t){let n=Te(t,".wezterm.lua");return Ht(n)?n:Te(e,"wezterm","wezterm.lua")}function Lo(e){return Te(e,"Microsoft","Windows Terminal","Fragments","ttheme","ttheme.json")}function nc(e){return[Te(e,"Packages","Microsoft.WindowsTerminal_8wekyb3d8bbwe","LocalState","settings.json"),Te(e,"Packages","Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe","LocalState","settings.json"),Te(e,"Microsoft","Windows Terminal","settings.json")].filter((t)=>Ht(t))}function ry(e){for(let t of e){let n=/"defaultProfile"\s*:\s*"(\{[0-9a-fA-F-]+\})"/.exec(Zr(t,"utf8"))?.[1];if(n)return n}return}function ln(e){return e.startup&&e.palettes.includes(e.startup)?e.startup:e.palettes[0]}function or(e,t){return e==="ghostty"?Te(t,"ghostty","config"):Te(t,"kitty","kitty.conf")}function Tg(e,t,n,r){return e==="ghostty"?cg(Te(t,"ttheme"),n,r):mg(n,Og(t),r)}function zt(e){return Ht(e)?Zr(e,"utf8"):""}function ur(e){return Te(e,"alacritty","alacritty.toml")}function iy(e,t){return t?Te(e,"alacritty","themes",`${$e(t)}.toml`):void 0}function Ag(e,t,n,r){let i=We(e),s=t.map(yt),o=new Map;for(let u of s){let c=Sd(i,u.name,r);if(c)o.set(u.name,c)}let a=new Set(et(t).map((u)=>u.name));return ng(s.filter((u)=>a.has(u.name)),o,s.find((u)=>u.name===dt(n)),n.itermBase)}function Bt(e,t=zr()){let n=se(e);if(!n.terminals.includes("iterm2"))return;ke(as(t),Ag(e,Fg(Hn(e),n.palettes),n,t))}function ot(e,t,n,r=zr()){st(We(e));let i=Fg(_e(e,t),n.palettes);Td(e,new Map(i.map((f)=>[f.name,f.backdrop]))),No(e,i);let s=[],o=(f,d)=>{if(s.push(f),Ht(f)&&Zr(f,"utf8")===d)return!1;return ke(f,d),!0},a=(f,d)=>{s.push(f),ki(f,d)},u=dt(n),c=!1;for(let f of n.terminals){if(f==="iterm2"){o(as(r),Ag(e,i,n,r));continue}if(f==="windows-terminal"){if(n.wtHome){let p=nc(n.wtHome),E=i.map(yt),v=xu(E,n.wtProfile??ry(p),u);if(o(Lo(n.wtHome),v)){let S=new Date;for(let w of p)Xk(w,S,S);c=p.length>0}}continue}let d=u!==void 0&&f==="warp"&&!Ht(Te(Ao(r),`${$e(u)}.yaml`)),g=f==="warp"?ny(e,r,u,d):void 0;for(let p of i)for(let{file:E,content:v}of Pg(f,yt(p)))o(Te(sr(f,e,r),E),v);if(f==="warp"){if(g)s.push(g);continue}if(f==="wezterm"){let p=Te(e,"ttheme","wezterm.lua");o(p,Sg({path:p,colors:sr("wezterm",e,r),backgrounds:We(e),...u?{startup:u}:{},palettes:i.map(yt)}));let E=Br(e,r),v=ns(zt(E),wg(p));if(v!==void 0)a(E,v);continue}if(f==="alacritty"){let p=ur(e),E=ts(zt(p),iy(e,u));if(E!==void 0)a(p,E);continue}if(f==="kitty")o(Og(e),rg({themes:sr("kitty",e,r),backgrounds:We(e)}));let m=or(f,e),b=zt(m);a(m,Di(b,Tg(f,e,u,b)))}let l=Te(e,"ttheme","palettes.zsh"),h=Vu(i,u,n.terminals);if(c||zt(l)!==h)ke(l,h),Du(`${l}.zwc`,{force:!0});return s.push(l),s}function Hg(e,t){return e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e}function sy(e){return[...new Set(e.split(`
381
- `).map((t)=>t.split(/[ =]/)[0]))].join(", ")}function Lg(e,t,n=zr()){let r=dt(t),i=(o)=>Hg(o,n),s=[];for(let o of t.terminals){if(o==="iterm2"){s.push(`Write ${i(as(n))} — a "ttheme · <palette>" profile per palette`);continue}if(o==="windows-terminal"){if(t.wtHome)s.push(`Write ${Lo(t.wtHome)} — its schemes, and touch settings.json so it reloads`);continue}if(s.push(`Write ${i(sr(o,e,n))}/${$e("*")} — a theme file per palette`),o==="warp"){let c=Ho(n,e);if(r&&Ht(c))s.push(`Edit ${i(c)} — [appearance.themes] theme; \`ttheme off\` puts yours back`);continue}if(o==="wezterm"){let c=Br(e,n);if(ns(zt(c),"")!==void 0)s.push(`Edit ${i(c)} — a ttheme block before \`return config\`: color_scheme_dirs, color_scheme, pictures`);continue}if(o==="alacritty"){let c=ur(e);if(ts(zt(c),void 0)!==void 0)s.push(`Edit ${i(c)} — a ttheme block: general.import`);continue}let a=or(o,e),u=zt(a);s.push(`Edit ${i(a)} — a ttheme block: ${sy(Tg(o,e,r,u))}`)}return s}function Gg(e,t,n=zr()){let r=[],i=(s)=>Hg(s,n);if(t.includes("ghostty")){let s=or("ghostty",e);if(ir(zt(s),"command"))r.push(`${i(s)} sets its own command — ttheme leaves it, so a new tab takes its palette once zsh starts`)}if(t.includes("kitty")){let s=zt(or("kitty",e));if(ir(s,"window_logo_scale")||ir(s,"window_logo_alpha"))r.push("kitty.conf sets its own window_logo_scale or window_logo_alpha — pictures are drawn with them")}if(t.includes("alacritty")){let s=ur(e);if(pg(zt(s)))r.push(`${i(s)} sets its own colors, which win over an imported palette — remove them to open with ttheme's`)}return r}function Go(e,t,n,r,i=zr()){let s=[],o=_e(e,t,!1).palettes;for(let a of n)for(let u of o.filter((c)=>r.includes(c.name)))for(let{file:c}of Pg(a,yt(u))){let l=Te(sr(a,e,i),c);if(Ht(l))Du(l,{force:!0}),s.push(l)}return s}function hn(e,t,n,r){let i=cn(),s=Boolean(dt(n))!==Boolean(dt(r)),o=s?os(r,i):r;return ot(e,t,o),Et(e,o),s&&ar(o,i)&&i.running()}import{openSync as oy,writeSync as ay}from"node:fs";import{ReadStream as uy}from"node:tty";var cy=["10","11","12","17",...Array.from({length:16},(e,t)=>`4;${t}`)];function Vt(e=process.env){return Boolean(e.NO_COLOR)||e.TERM==="dumb"}function Vr(e){return[`\x1B]11;${e.background}\x1B\\`,`\x1B]10;${e.foreground}\x1B\\`,`\x1B]12;${e.cursor}\x1B\\`,`\x1B]17;${e.selection}\x1B\\`,...e.ansi.map((t,n)=>`\x1B]4;${n};${t}\x1B\\`)].join("")}function ly(e){let t=new Map;for(let n of e.split("\x1B")){let r=n.match(/^\](\d+(?:;\d+)?);(rgba?:[0-9a-fA-F/]+)/),[,i,s]=r??[];if(i&&s)t.set(i,s)}return t}function Uo(e){return[...e].map(([t,n])=>`\x1B]${t};${n}\x1B\\`).join("")}var hy=`${cy.map((e)=>`\x1B]${e};?\x1B\\`).join("")}\x1B[5n`;function fy(e){return e.includes("\x1B[0n")}async function _o(){let e,t;try{e=oy("/dev/tty","r+"),t=new uy(e),t.setRawMode(!0)}catch{return new Map}try{ay(e,hy);let n="";return await new Promise((r)=>{let i=setTimeout(r,120);t.on("data",(s)=>{if(n+=s.toString(),fy(n))clearTimeout(i),r()})}),ly(n)}finally{t.setRawMode(!1),t.destroy()}}var dy=300,gy=80,Ug=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];function rc(e){return e>=1e6?`${(e/1e6).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1000))} KB`}function Co(e,t){if(!t)return rc(e);return t>=1e6?`${(e/1e6).toFixed(1)}/${(t/1e6).toFixed(1)} MB`:`${Math.round(e/1000)}/${Math.round(t/1000)} KB`}function Gn(e=""){let t=process.stdout;if(!t.isTTY||process.env.TERM==="dumb")return{set(){},say:(c)=>console.log(c),done(){}};let[n,r]=Vt()?["",""]:["\x1B[2m","\x1B[22m"],i=0,s=!1,o,a=()=>{t.write(`\r\x1B[2K${n}${Ct(`${Ug[i%Ug.length]} ${e}`,(t.columns||80)-1,!1)}${r}`)},u=setTimeout(()=>{s=!0,a(),o=setInterval(()=>{i++,a()},gy),o.unref()},dy);return u.unref(),{set(c){if(e=c,s)a()},say(c){if(s)t.write("\r\x1B[2K");if(console.log(c),s)a()},done(){if(clearTimeout(u),clearInterval(o),s)t.write("\r\x1B[2K"),s=!1}}}import{existsSync as Ny,mkdirSync as Kg,readFileSync as qg,statSync as Ry}from"node:fs";import{homedir as Fy}from"node:os";import{dirname as Py,join as Wg}from"node:path";import{existsSync as ic,mkdirSync as sc,readFileSync as xr,writeFileSync as ky}from"node:fs";import{homedir as yy}from"node:os";import{dirname as oc,join as Dr}from"node:path";import{spawn as my}from"node:child_process";var py=30000,wy=3,by=97,$y=`ObjC.import('Vision')
377
+ `)}var Im=/["$`\\]/;function N1(e){return e.replace(/_\([^)]*\)$/,"").replaceAll("_"," ")}function Uc(e,t,n=[]){for(let c of e)for(let l of[c.name,c.group,c.native??"",...c.nativeNames??[],c.ansiSource])if(Im.test(l))throw Error(`${c.name}: "${l}" contains a character that breaks zsh quoting`);let r=Math.max(0,...e.map((c)=>c.name.length)),i=(c,l)=>` ${c.name.padEnd(r)} "${l}"`,s=(c)=>c.map((l)=>l.name).join(" "),o=st(e),a=(c)=>`'${c.replaceAll("'","'\\''")}'`,u=Is.filter((c)=>c.section!=="setup"&&!c.hidden);return["# Generated by `mise run build` — do not edit.","# Source of truth: themes/*.toml in the ttheme repo.","",`typeset -g TTHEME_VERSION=${nt.version}`,"",'# the palette new tabs open with, which the iTerm2 "ttheme · default" profile wears',`typeset -g TTHEME_STARTUP=${t??""}`,"","# the terminals ttheme is wired into: a picture change reaches every one of them, from whichever runs the shell",`typeset -ga TTHEME_TERMINALS=(${n.join(" ")})`,"","# the commands the shell layer knows (src/verbs.ts): help, completion and argument checks read them",`typeset -ga TTHEME_VERBS=(${u.map((c)=>c.name).join(" ")})`,`typeset -ga TTHEME_SHELL_VERBS=(${u.filter((c)=>c.shell).map((c)=>c.name).join(" ")})`,"typeset -gA TTHEME_VERB_ARGS=(",...u.map((c)=>` ${c.name} ${a(c.args.join(" "))}`),")","typeset -gA TTHEME_VERB_ABOUT=(",...u.map((c)=>` ${c.name} ${a(c.about)}`),")",`typeset -g TTHEME_HELP=${a(Ns(!1,!0))}`,`typeset -g TTHEME_HELP_ALL=${a(Ns(!0,!0))}`,"","# the settings config.zsh holds, handed to the CLI on every call",`typeset -ga TTHEME_SETTINGS=(${mm.join(" ")})`,"","# seed for `ttheme config` when no config.zsh exists yet",`typeset -g TTHEME_CONFIG_TEMPLATE='${Gc().trimEnd().replaceAll("'","'\\''")}'`,"","typeset -gA TTHEME_PALETTE=(",...e.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=(${s(o)})`,"","# the same palettes by series name, then palette name: TTHEME_SORT=abc lists them this way",`typeset -ga TTHEME_ABC=(${s(gr(o))})`,"","typeset -gA TTHEME_GROUP=(",...e.map((c)=>i(c,c.group)),")","","# the catalog a market palette sits in — the folder under the market's palettes/, one level below the market in every list","typeset -gA TTHEME_CATALOG=(",...e.filter((c)=>c.catalog).map((c)=>i(c,c.catalog??"")),")","","# original-language title, rendered dim next to the group","typeset -gA TTHEME_NATIVE=(",...e.filter((c)=>c.native).map((c)=>i(c,c.native??"")),")","","# the character's names in its original language, |-separated, and as its booru tag spells it: preview searches both","typeset -gA TTHEME_NATIVE_NAMES=(",...e.filter((c)=>c.nativeNames).map((c)=>i(c,(c.nativeNames??[]).join("|"))),")","typeset -gA TTHEME_CHARACTER=(",...e.filter((c)=>c.booru&&!Im.test(c.booru)).map((c)=>i(c,N1(c.booru??""))),")","","# the example scenes preview draws beside the list (src/scenes.ts), each line as «role»text runs",`typeset -ga TTHEME_SCENES=(${Ht.map((c)=>c.name).join(" ")})`,...Ht.flatMap((c,l)=>[`typeset -ga TTHEME_SCENE_${l+1}=(`,...c.lines.map((h)=>` ${a(h)}`),")"]),"","# each booru's ANSI color, which marks a link to one of its posts",`typeset -gA TTHEME_SITE_ANSI=(${V.map((c)=>`${c.name} ${c.ansi}`).join(" ")})`,"","# the terminals that open OSC 8 links (src/terminal.ts)",`typeset -ga TTHEME_LINKS=(${Object.entries(Xn).flatMap(([c,l])=>l.links?[c]:[]).join(" ")})`,"","# the six colors a list row shows: foreground, the signature, then red and green","typeset -gA TTHEME_SWATCH=(",...e.map((c)=>i(c,sa(c).join(" "))),")","","# where each palette's 16 ANSI colors came from","typeset -gA TTHEME_SRC=(",...e.map((c)=>i(c,c.ansiSource)),")",""].join(`
378
+ `)}var jc={id:"shell",emitShared(e){return[{path:"shell/palettes.zsh",content:Uc(e.map(Wt))}]}};var P1=["black","red","green","yellow","blue","magenta","cyan","white"];function Nm(e,t){return[` ${e}:`,...P1.map((n,r)=>` ${n}: "${t[r]}"`)]}var Hs={id:"warp",limits:"no selection color, and Warp paints one theme app-wide",emit(e){let t=[`name: "${e.name}"`,`background: "${e.background}"`,`foreground: "${e.foreground}"`,`accent: "${e.cursor}"`,`cursor: "${e.cursor}"`,`details: ${ze(e.background)<0.18?"darker":"lighter"}`,"terminal_colors:",...Nm("normal",e.ansi.slice(0,8)),...Nm("bright",e.ansi.slice(8,16)),""].join(`
379
+ `);return[{path:`warp/themes/${ye(e.name)}.yaml`,content:t}]}};var Pm=(e)=>`[${e.map((t)=>`"${t}"`).join(", ")}]`,As={id:"wezterm",limits:"OSC repaints per pane, pictures show per window",emit(e){let t=["[metadata]",`name = "${ye(e.name)}"`,`origin_url = "${e.ansiSource}"`,"","[colors]",`foreground = "${e.foreground}"`,`background = "${e.background}"`,`cursor_bg = "${e.cursor}"`,`cursor_border = "${e.cursor}"`,`cursor_fg = "${e.background}"`,`selection_bg = "${e.selectionBackground}"`,`selection_fg = "${e.foreground}"`,"",`ansi = ${Pm(e.ansi.slice(0,8))}`,`brights = ${Pm(e.ansi.slice(8,16))}`,""].join(`
380
+ `);return[{path:`wezterm/colors/${ye(e.name)}.toml`,content:t}]}},mi=(e)=>JSON.stringify(e);function Fm(e){return["-- Generated by ttheme — rewritten on every add, remove and default; do not edit.","local wezterm = require 'wezterm'","",`local MODULE = ${mi(e.path)}`,`local COLORS = ${mi(e.colors)}`,`local BACKGROUNDS = ${mi(e.backgrounds)}`,`local STARTUP = ${e.startup?mi(ye(e.startup)):"nil"}`,"local PALETTES = {",...e.palettes.map((t)=>` [${mi(t.name)}] = ${mi(t.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:gsub('@', '--', 1)):gsub('/', '--', 1)) .. '.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 function framed(window, view)"," local color, image, opacity, W, H, w, h, x, y, at ="," view:match('^([^|]*)|([^|]*)|([^|]*)|(%d+)|(%d+)|(%-?%d+)|(%-?%d+)|(%-?%d+)|(%-?%d+)|(%d)$')"," if not image or image == '' or tonumber(W) == 0 or tonumber(H) == 0 then"," return nil, 'none'"," end"," local d = window:get_dimensions()"," local k = math.max(d.pixel_width / W, d.pixel_height / H)"," local n = tonumber(at) - 1"," local ax, ay = n % 3, n // 3"," local px = function(n) return string.format('%.2fpx', n) end"," return {"," { source = { Color = color }, width = '100%', height = '100%' },"," {"," source = { File = image },"," opacity = tonumber(opacity) or 1,"," width = px(w * k),"," height = px(h * k),"," horizontal_align = 'Left',"," vertical_align = 'Top',"," horizontal_offset = px(ax * (d.pixel_width - W * k) / 2 + x * k),"," vertical_offset = px(ay * (d.pixel_height - H * k) / 2 + y * k),"," repeat_x = 'NoRepeat',"," repeat_y = 'NoRepeat',"," },"," }, table.concat({ view, d.pixel_width, d.pixel_height }, '|')","end","","local shown = {}","","local function show(window, pane)"," local vars = pane:get_user_vars()"," local id = window:window_id()"," local background, key"," if vars.ttheme_view and vars.ttheme_view ~= '' then"," background, key = framed(window, vars.ttheme_view)"," elseif vars.ttheme_shown and vars.ttheme_shown ~= '' then"," background, key = layers(vars.ttheme_shown)"," elseif shown[id] == nil then"," return"," end"," 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' or name == 'ttheme_view' 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(`
381
+ `)}var Rm=["black","red","green","yellow","blue","purple","cyan","white"];function Om(e){return{name:ye(e.name),background:e.background,foreground:e.foreground,cursorColor:e.cursor,selectionBackground:e.selectionBackground,...Object.fromEntries(Rm.map((t,n)=>[t,e.ansi[n]])),...Object.fromEntries(Rm.map((t,n)=>[`bright${t[0]?.toUpperCase()}${t.slice(1)}`,e.ansi[n+8]]))}}function Wc(e,t,n){let r={...t&&n?{profiles:[{updates:t,colorScheme:ye(n)}]}:{},schemes:e.map(Om)};return`${JSON.stringify(r,null,2)}
382
+ `}var Ls={id:"windows-terminal",limits:"no kitty graphics, so no pictures; OSC repaints per pane",emit(e){return[{path:`windows-terminal/schemes/${ye(e.name)}.json`,content:`${JSON.stringify(Om(e),null,2)}
383
+ `}]},emitShared(e){return[{path:"windows-terminal/ttheme.json",content:Wc(e)}]}};function ye(e){return`ttheme-${en(e)}`}function ci(e){return[`# ${e.name} — ${e.group}${e.native?` (${e.native})`:""}`,`# ANSI: ${e.ansiSource}`]}var x1={ghostty:Es,kitty:Ms,alacritty:ys,wezterm:As,iterm2:vs,"windows-terminal":Ls,warp:Hs},Tm="ttheme-default";function wn(e=process.env.TTHEME_ITERM_SUITE??"com.googlecode.iterm2"){let t=(n,r)=>F1(n,r,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();return{read:()=>{try{return process.platform==="darwin"?t("defaults",["read",e,"Default Bookmark Guid"])||void 0:void 0}catch{return}},write:(n)=>{if(process.platform==="darwin")t("defaults",["write",e,"Default Bookmark Guid","-string",n])},running:()=>{try{return t("pgrep",["-x","iTerm2"])!==""}catch{return!1}}}}function yt(e){return e.off?void 0:vr(e)}function Cs(e,t){if(!e.terminals.includes("iterm2"))return e;let n=t.read();return n&&!n.startsWith("ttheme-")?{...e,itermBase:n}:e}function Er(e,t){if(!e.terminals.includes("iterm2"))return!1;let n=t.read(),r=yt(e)?Tm:n===Tm?e.itermBase:void 0;if(!r||r===n)return!1;return t.write(r),!0}function de(){return process.env.XDG_CONFIG_HOME??He(bi(),".config")}function _s(e){return He(e,"Library","Application Support","iTerm2","DynamicProfiles","ttheme.json")}var xs=(e)=>typeof e==="string"&&e!==""?e:void 0,C1={author:xs,startup:xs,off:(e)=>e?!0:void 0,itermBase:xs,wtHome:xs,wtProfile:xs,markets:(e)=>Array.isArray(e)?e.filter((t)=>typeof t==="string"):void 0,updates:(e)=>e&&typeof e==="object"?Object.fromEntries(Object.entries(e).filter((t)=>typeof t[1]==="boolean")):void 0};function ae(e){let t=Bn(e);if(!Bt(t))throw Error(`nothing installed yet at ${t} — run \`ttheme init\` first`);let n=JSON.parse(pi(t,"utf8"));if(!Array.isArray(n?.palettes)||!Array.isArray(n.terminals))throw Error(`${t} has no palettes or terminals`);return{terminals:n.terminals.filter((r)=>pa.includes(r)),...Object.fromEntries(Object.entries(C1).flatMap(([r,i])=>{let s=i(n[r]);return s===void 0?[]:[[r,s]]})),palettes:n.palettes}}function Lt(e,t){Z(Bn(e),`${JSON.stringify(t,null,2)}
384
+ `)}function Hm(e,t){let n=new Map(e.palettes.map((i)=>[i.name,i])),r=t.filter((i)=>!n.has(i));if(r.length>0){let i=[...new Set(r.flatMap((o)=>ve(o)??[]))].filter((o)=>!e.palettes.some((a)=>ve(a.name)===o)),s=i.length>0?`add ${i.join(", ")} first — \`ttheme market search\` finds a market's repository`:Ac(st(e.palettes),r);throw Error(`not in any market: ${r.join(", ")} — ${s}`)}return e.palettes.filter((i)=>t.includes(i.name))}function Am(e,t){let n=e==="wezterm"?"colors":"themes";return(x1[e].emit?.(t)??[]).flatMap((r)=>{let[,i,s]=r.path.split("/");return i===n&&s!==void 0?[{file:s,content:r.content}]:[]})}function $a(e){return process.platform==="darwin"?He(e,".warp","themes"):He(process.env.XDG_DATA_HOME??He(e,".local","share"),"warp-terminal","themes")}function kr(e,t,n){if(e==="warp")return $a(n);return He(t,e,e==="wezterm"?"colors":"themes")}function ka(e,t){return process.platform==="darwin"?He(e,".warp","settings.toml"):He(t,"warp-terminal","settings.toml")}var Jc='"dark"';function Bc(e){return He(e,"ttheme","warp.base")}var _1="setTimeout(() => { const fs = require('node:fs'); const [file, next, seen] = process.argv.slice(-3); if (fs.readFileSync(file, 'utf8') !== seen) return; const tmp = file + '.ttheme-' + process.pid; fs.writeFileSync(tmp, next); fs.chmodSync(tmp, fs.statSync(file).mode & 0o7777); fs.renameSync(tmp, file) }, 1500)";function G1(e,t,n,r){let i=ka(t,e);if(!Bt(i))return;let s=Bc(e),o=pi(i,"utf8"),a=ba(o),u=a?.includes(`path = "${ye("")}`)===!0,c;if(n){if(!u&&!Bt(s))O1(L1(s),{recursive:!0}),A1(s,a??"");c=Sm(n)}else{if(!u)return;c=Bt(s)&&pi(s,"utf8")||Jc,Kc(s,{force:!0})}let l=wa(o,c);if(l===o)return;if(r)Hu(i),R1(process.execPath,["-e",_1,T1(i),l,o],{detached:!0,stdio:"ignore"}).unref();else zi(i,l);return i}function Lm(e){return He(e,"ttheme","kitty.py")}function wi(e,t){let n=He(t,".wezterm.lua");return Bt(n)?n:He(e,"wezterm","wezterm.lua")}function ya(e){return He(e,"Microsoft","Windows Terminal","Fragments","ttheme","ttheme.json")}function qc(e){return[He(e,"Packages","Microsoft.WindowsTerminal_8wekyb3d8bbwe","LocalState","settings.json"),He(e,"Packages","Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe","LocalState","settings.json"),He(e,"Microsoft","Windows Terminal","settings.json")].filter((t)=>Bt(t))}function U1(e){for(let t of e){let n=/"defaultProfile"\s*:\s*"(\{[0-9a-fA-F-]+\})"/.exec(pi(t,"utf8"))?.[1];if(n)return n}return}function vr(e){return e.startup&&e.palettes.includes(e.startup)?e.startup:e.palettes[0]}function yr(e,t){return e==="ghostty"?He(t,"ghostty","config"):He(t,"kitty","kitty.conf")}function xm(e,t,n,r){return e==="ghostty"?fm(He(t,"ttheme"),n,r):wm(n,Lm(t),r)}function on(e){return Bt(e)?pi(e,"utf8"):""}function Mr(e){return He(e,"alacritty","alacritty.toml")}function j1(e,t){return t?He(e,"alacritty","themes",`${ye(t)}.toml`):void 0}function Cm(e,t,n,r){let i=je(e),s=t.map(Tt),o=new Map;for(let u of s){let c=yg(i,u.name,r);if(c)o.set(u.name,c)}let a=new Set(st(t).map((u)=>u.name));return Xg(s.filter((u)=>a.has(u.name)),o,s.find((u)=>u.name===yt(n)),n.itermBase)}function xt(e,t=bi()){let n=ae(e);if(!n.terminals.includes("iterm2"))return;Z(_s(t),Cm(e,Hm(bn(e),n.palettes),n,t))}function lt(e,t,n,r=bi()){ut(je(e));let i=Hm(We(e,t),n.palettes);Ig(e,new Map(i.map((f)=>[f.name,f.backdrop]))),wg(e),ha(e,i);let s=[],o=(f,d)=>{if(s.push(f),Bt(f)&&pi(f,"utf8")===d)return!1;return Z(f,d),!0},a=(f,d)=>{s.push(f),zi(f,d)},u=yt(n),c=!1;for(let f of n.terminals){if(f==="iterm2"){o(_s(r),Cm(e,i,n,r));continue}if(f==="windows-terminal"){if(n.wtHome){let m=qc(n.wtHome),$=i.map(Tt),k=Wc($,n.wtProfile??U1(m),u);if(o(ya(n.wtHome),k)){let S=new Date;for(let w of m)H1(w,S,S);c=m.length>0}}continue}let d=u!==void 0&&f==="warp"&&!Bt(He($a(r),`${ye(u)}.yaml`)),g=f==="warp"?G1(e,r,u,d):void 0;for(let m of i)for(let{file:$,content:k}of Am(f,Tt(m)))o(He(kr(f,e,r),$),k);if(f==="warp"){if(g)s.push(g);continue}if(f==="wezterm"){let m=He(e,"ttheme","wezterm.lua");o(m,Fm({path:m,colors:kr("wezterm",e,r),backgrounds:je(e),...u?{startup:u}:{},palettes:i.map(Tt)}));let $=wi(e,r),k=Ts(on($),km(m));if(k!==void 0)a($,k);continue}if(f==="alacritty"){let m=Mr(e),$=Os(on(m),j1(e,u));if($!==void 0)a(m,$);continue}if(f==="kitty")o(Lm(e),Dg({themes:kr("kitty",e,r),backgrounds:je(e)}));let p=yr(f,e),b=on(p);a(p,Fs(b,xm(f,e,u,b)))}let l=He(e,"ttheme","palettes.zsh"),h=Uc(i,u,n.terminals);if(c||on(l)!==h)Z(l,h),Kc(`${l}.zwc`,{force:!0});return s.push(l),s}function _m(e,t){return e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e}function W1(e){return[...new Set(e.split(`
385
+ `).map((t)=>t.split(/[ =]/)[0]))].join(", ")}function Gm(e,t,n=bi()){let r=yt(t),i=(o)=>_m(o,n),s=[];for(let o of t.terminals){if(o==="iterm2"){s.push(`Write ${i(_s(n))} — a "ttheme · <palette>" profile per palette`);continue}if(o==="windows-terminal"){if(t.wtHome)s.push(`Write ${ya(t.wtHome)} — its schemes, and touch settings.json so it reloads`);continue}if(s.push(`Write ${i(kr(o,e,n))}/${ye("*")} — a theme file per palette`),o==="warp"){let c=ka(n,e);if(r&&Bt(c))s.push(`Edit ${i(c)} — [appearance.themes] theme; \`ttheme off\` puts yours back`);continue}if(o==="wezterm"){let c=wi(e,n);if(Ts(on(c),"")!==void 0)s.push(`Edit ${i(c)} — a ttheme block before \`return config\`: color_scheme_dirs, color_scheme, pictures`);continue}if(o==="alacritty"){let c=Mr(e);if(Os(on(c),void 0)!==void 0)s.push(`Edit ${i(c)} — a ttheme block: general.import`);continue}let a=yr(o,e),u=on(a);s.push(`Edit ${i(a)} — a ttheme block: ${W1(xm(o,e,r,u))}`)}return s}function Um(e,t,n=bi()){let r=[],i=(s)=>_m(s,n);if(t.includes("ghostty")){let s=yr("ghostty",e);if($r(on(s),"command"))r.push(`${i(s)} sets its own command — ttheme leaves it, so a new tab takes its palette once zsh starts`)}if(t.includes("kitty")){let s=on(yr("kitty",e));if($r(s,"window_logo_scale")||$r(s,"window_logo_alpha"))r.push("kitty.conf sets its own window_logo_scale or window_logo_alpha — pictures are drawn with them")}if(t.includes("alacritty")){let s=Mr(e);if($m(on(s)))r.push(`${i(s)} sets its own colors, which win over an imported palette — remove them to open with ttheme's`)}return r}function Ea(e,t,n,r,i=bi()){let s=[],o=We(e,t,!1).palettes;for(let a of n)for(let u of o.filter((c)=>r.includes(c.name)))for(let{file:c}of Am(a,Tt(u))){let l=He(kr(a,e,i),c);if(Bt(l))Kc(l,{force:!0}),s.push(l)}return s}function $n(e,t,n,r){let i=wn(),s=Boolean(yt(n))!==Boolean(yt(r)),o=s?Cs(r,i):r;return lt(e,t,o),Lt(e,o),s&&Er(o,i)&&i.running()}var K1=300,J1=80,jm=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];function va(e){return e>=1e6?`${(e/1e6).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1000))} KB`}function Ma(e,t){if(!t)return va(e);return t>=1e6?`${(e/1e6).toFixed(1)}/${(t/1e6).toFixed(1)} MB`:`${Math.round(e/1000)}/${Math.round(t/1000)} KB`}function er(e=""){let t=process.stdout;if(!t.isTTY||process.env.TERM==="dumb")return{set(){},say:(c)=>console.log(c),done(){}};let[n,r]=At()?["",""]:["\x1B[2m","\x1B[22m"],i=0,s=!1,o,a=()=>{t.write(`\r\x1B[2K${n}${De(`${jm[i%jm.length]} ${e}`,(t.columns||80)-1,!1)}${r}`)},u=setTimeout(()=>{s=!0,a(),o=setInterval(()=>{i++,a()},J1),o.unref()},K1);return u.unref(),{set(c){if(e=c,s)a()},say(c){if(s)t.write("\r\x1B[2K");if(console.log(c),s)a()},done(){if(clearTimeout(u),clearInterval(o),s)t.write("\r\x1B[2K"),s=!1}}}import{existsSync as rE,mkdirSync as Qm,readFileSync as Zm,statSync as iE}from"node:fs";import{homedir as sE}from"node:os";import{dirname as oE,join as zm}from"node:path";import{existsSync as zc,mkdirSync as Km,readFileSync as ki}from"node:fs";import{homedir as Z1}from"node:os";import{dirname as Jm,join as yi}from"node:path";import{spawn as B1}from"node:child_process";var q1=30000,z1=3,Y1=97,Q1=`ObjC.import('Vision')
382
386
  ObjC.import('CoreImage')
383
387
  ObjC.import('CoreGraphics')
384
388
  function run(argv) {
@@ -397,11 +401,11 @@ function run(argv) {
397
401
  $.CIImage.imageWithCVPixelBuffer(buffer), $.NSURL.fileURLWithPath(argv[1]), $.kCIFormatRGBA8,
398
402
  $.CGColorSpaceCreateWithName($.kCGColorSpaceSRGB), $({}), error)
399
403
  if (!written) throw new Error('write failed')
400
- }`;function Xr(){return process.platform==="darwin"}function jo(e){return e>=wy&&e<=by}function us(e,t,n){return new Promise((r,i)=>{let s=my("osascript",["-l","JavaScript","-e",$y,e,t],{stdio:["ignore","ignore","pipe"],signal:AbortSignal.any([n,AbortSignal.timeout(py)])}),o="";s.stderr.on("data",(a)=>{o+=a}),s.on("error",i),s.on("close",(a)=>{if(a===0){r();return}i(Error(o.trim().split(`
401
- `).at(-1)||`osascript exited ${a}`))})})}var Cg=90000;function ac(e,t){let n=We(e),r=Tu(e,t).flatMap((i)=>{let[,s,o]=/^([a-z.]+)_(\d+)$/.exec(i.key)??[];return s&&o&&te.some((a)=>a.key===s)?[{site:s,id:Number(o),...Au(n,i)}]:[]});return r.length>0?r:void 0}function Ey(e,t){let n=new Set(st(We(e)).palettes[t.name]?.pictures.map((r)=>r.key));return(t.pictures??[]).filter((r)=>!n.has(er(r)))}function Un(e,t){let n=new Set((t??[]).map((r)=>er(r)));return{...e,pictures:(e.pictures??[]).filter((r)=>!n.has(er(r)))}}function vy(e){return{name:e.name,background:e.background,foreground:e.foreground,cursor:e.cursor,selection:e.selection,ansi:e.ansi,...e.waived?{waived:e.waived}:{}}}async function My(e,t,n,r,i,s){let o=te.find((m)=>m.key===n.site);if(!o)throw Error(`no site called ${n.site}`);s("Fetching");let a=await Li(o,n.id,i);if(!a)throw Error("the post is gone");if(!lo(o,a,zn(process.env.TTHEME_FIND_RATING))||co(a,Or(process.env.TTHEME_FIND_BLOCK)).length>0)throw Error("outside your find filters — TTHEME_FIND_RATING and TTHEME_FIND_BLOCK");let u=rn(a);if(!u)throw Error("too large to use");let c=Dr(Ft(o),"orig",`${n.id}.${u.ext}`),l;if(ic(c))l=new Uint8Array(xr(c));else s("Downloading"),l=await fo(o,u.file,i,(m,b)=>s("Downloading",Co(m,b))),sc(oc(c),{recursive:!0}),ky(c,l);let h=Qn(l,kt),f=!1;if(tn(h)===0&&Xr()&&process.env.TTHEME_FIND_REMOVE_BG!=="off"){let m=Dr(Ft(o),"cut",`${n.id}.png`);try{if(!ic(m))s("Cutting out"),sc(oc(m),{recursive:!0}),await us(c,m,i);let b=Qn(new Uint8Array(xr(m)),kt);if(jo(tn(b)))h=b,f=!0}catch{}}let d=vy(t);s("Drawing"),$o(e,d,Gr(d,t.signatureSlots),h,{site:o.key,id:n.id,ext:u.ext,bytes:l,from:`${o.name} ${n.id} ${o.pageUrl(n.id)}`,cut:f},{width:0,height:0},Qr(e));let g=Tu(e,t.name).find((m)=>m.key===er(n));if(g)Hu(We(e),g,n,r,yy())}async function Xt(e,t,n){let r=t.flatMap((a)=>Ey(e,a).map((u)=>({entry:a,shared:u})));if(r.length===0)return;let i=!n.includes("iterm2"),s=new Set,o=Gn();for(let[a,{entry:u,shared:c}]of r.entries()){let l=`${u.name} · ${te.find((d)=>d.key===c.site)?.name??c.site} ${c.id}`,h=r.length>1?` · ${a+1}/${r.length}`:"",f=(d,g)=>o.set(`${d} ${l}${g?` · ${g}`:""}${h}`);try{await My(e,u,c,i,AbortSignal.timeout(Cg),f),o.say(` ▣ ${l}`),s.add(u)}catch(d){o.say(` ▢ ${l} — ${d instanceof Error?d.message:String(d)}`)}}o.done();for(let a of s){let[u]=a.pictures??[];if(u)Fd(e,a.name,er(u))}if(s.size>0)Bt(e)}function _g(e,t,n){if(t.width!==e.width||t.height!==e.height)return!1;for(let r=0;r<e.width*e.height;r++)e.data[r*4+3]=t.data[r*4+n]??0;return!0}async function Sy(e,t){let[,n,r]=/^(.+)_(\d+)$/.exec(e)??[],i=Dr(Tr(),n??"local","cut",`${r??e}.png`);if(!ic(i)){if(!Xr())return;sc(oc(i),{recursive:!0}),await us(t,i,AbortSignal.timeout(Cg))}return Qn(new Uint8Array(xr(i)),kt)}function Iy(e,t){try{return tn(qn(new Uint8Array(xr(Dr(e,`${t.stem}.png`)))))>0}catch{return!1}}async function jg(e,t,n,r,i,s,o){let a=We(e),u=st(a).palettes[t]?.pictures.find((h)=>h.key===n);if(!u?.original)return null;let c=Dr(a,u.original),l=Qn(new Uint8Array(xr(c)),kt);if(u.cut){if(!_g(l,qn(new Uint8Array(xr(Dr(a,u.cut)))),0))return null;return ko(e,t,u,l,r,i,s,o,!1)}if(u.tone===void 0&&tn(l)===0&&Iy(a,u)){let h=await Sy(n,c);if(!h||!_g(l,h,3))return null;return ko(e,t,u,l,r,i,s,o,!0)}return ko(e,t,u,l,r,i,s,o,!1)}var Oy=86400000,Ty=3600000,cc=5000;function uc(){return Wg(process.env.XDG_STATE_HOME??Wg(Fy(),".local","state"),"ttheme","markets.json")}function fn(){try{let e=JSON.parse(qg(uc(),"utf8"));return Object.fromEntries(Object.entries(e).filter((t)=>typeof t[1]?.at==="number"&&typeof t[1].error==="string"))}catch{return{}}}function Jg(e,t){let n=fn();if(t===void 0){if(!(e in n))return;delete n[e]}else n[e]={at:Date.now(),error:t};Kg(Py(uc()),{recursive:!0}),ke(uc(),`${JSON.stringify(n,null,2)}
402
- `)}function cs(e,t){let n=t===z?At(e):ht(t)?Ot(e,t):void 0;try{return n?Ry(n).mtimeMs:void 0}catch{return}}function Ay(e,t,n,r){return e&&(t===void 0||r-t>=Oy)&&(n===void 0||r-n>=Ty)}function lc(e,t,n=Date.now()){let r=fn();return ze(t.markets).filter((i)=>Ay(Fn(i,t.updates),cs(e,i),r[i]?.at,n))}async function Hy(e,t,n){try{return await Ki(Gd(e),qu,t,n)}catch(r){if(r instanceof Ro)throw Error(`${be(e)} has no ${Qt} — is the repository public, and has its action run?`);throw r}}async function ls(e,t,n){if(e===z){let s=await Ki(zd,Zt,t,n);return{source:e,id:z,manifest:s,entries:s.palettes}}let r=await Hy(e,t,n),i=jr(e,r);return{source:e,id:i,manifest:r,entries:Io(r,i)}}function ei(e,t){if(t.source===z){So(e,t.manifest);return}Kg(Uu(e),{recursive:!0}),ke(Ot(e,t.source),`${JSON.stringify(t.manifest,null,2)}
403
- `)}function ti(e,t){try{if(t===z)return Zt(qg(At(e),"utf8")).palettes;let n=An(e,t);return Io(n,jr(t,n))}catch{return[]}}function Ly(e,t){let n=new Map(e.map((i)=>[i.name,JSON.stringify(i)])),r=new Map(t.map((i)=>[i.name,JSON.stringify(i)]));return{added:[...r.keys()].filter((i)=>!n.has(i)),changed:[...r].filter(([i,s])=>n.has(i)&&n.get(i)!==s).map(([i])=>i),gone:[...n.keys()].filter((i)=>!r.has(i))}}async function hs(e,t,n){let r=ti(e,t),i;try{i=await ls(t,n)}catch(s){throw Jg(t,s.message),s}return ei(e,i),Jg(t,void 0),{source:t,id:i.id,...t===z?{version:i.manifest.version}:{},count:et(i.entries).length,change:Ly(r,i.entries)}}function at(e){return`${e} palette${e===1?"":"s"}`}function fs(e,t=Date.now()){let n=Math.floor(Math.max(0,t-e)/60000);if(n<1)return"just now";if(n<60)return`${n}m ago`;let r=Math.floor(n/60);return r<48?`${r}h ago`:`${Math.floor(r/24)}d ago`}function Qg({added:e,changed:t,gone:n}){return[e.length>0?`${e.length} new`:"",t.length>0?`${t.length} changed`:"",n.length>0?`${n.length} gone`:""].filter(Boolean).join(", ")}function hc(e){let t=Qg(e.change);return`${e.version?`${e.id} ${e.version}`:e.id} — ${at(e.count)}${t?` (${t})`:""}`}function fc(e){return Qg(e.change)?`Updated ${hc(e)}`:void 0}async function Wo(e,t,n,r){let i=new Set(r.flatMap((c)=>[...c.change.changed,...c.change.gone])),s=t.palettes.filter((c)=>i.has(c));if(s.length===0)return;let o=Le(e,!1);ot(e,o,t);let a=new Set(r.flatMap((c)=>c.change.gone));for(let c of s.filter((l)=>a.has(l)))console.log(`${c} left its market — ttheme keeps the copy you have`);let u=new Map(n.map((c)=>[c.name,c.pictures]));await Xt(e,_e(e,o,!1).palettes.filter((c)=>s.includes(c.name)&&u.has(c.name)).map((c)=>Un(c,u.get(c.name))),t.terminals)}async function Yg(e=he()){try{if(!Ny(Rn(e)))return;let t=se(e),n=lc(e,t);if(n.length===0)return;let r=un(e),i=Gn(`Checking ${n.map(be).join(", ")} for updates`),s=(await Promise.allSettled(n.map((a)=>hs(e,a,cc)))).flatMap((a)=>a.status==="fulfilled"?[a.value]:[]);i.done();let o=s.flatMap((a)=>fc(a)??[]);if(o.length===0)return;for(let a of o)console.log(a);await Wo(e,t,r,s)}catch{return}}var Xg=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,jy=["add","remove","search","init"];function pc(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function Wy(){try{let e=Gy("gh",["api","user","--jq",".login"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4}).trim().toLowerCase();return Xg.test(e)?e:void 0}catch{return}}async function Jy(e,t){if(t.author)return t.author;let n=Wy();if(!n){if(!pc())throw Error("your palettes are named after your GitHub handle — log in with `gh auth login`, or run this in a terminal");let r=await Ua({message:"Your GitHub handle — your palettes are named <handle>@<market>/<palette>",validate:(i)=>Xg.test((i??"").toLowerCase())&&(i??"").length<=39?void 0:"that is not a GitHub handle"});if(xe(r))throw Error("no handle given");n=r.toLowerCase()}return Et(e,{...t,author:n}),console.log(`Your palettes are named ${n}@<market>/<palette>`),n}function ni(e,t){if(t===z)return z;return Oe(t)?ft(Yt(t)):jr(t,An(e,t))}function Jo(e,t){try{return ni(e,t)}catch{return}}function xg(e){return ye(e)??z}function Ko(e){return Le(e).palettes.filter((t)=>ye(t.name)===void 0)}function Ky(e){let t=cr(import.meta.dirname,"..","dist","manifest.json");return dc(t)?Zt(mc(t,"utf8")).palettes:Ko(e)}function ds(e,t,n){let{updates:r,...i}=e,s=Object.entries(n).filter(([o,a])=>t.includes(o)&&a!==Fn(o,{}));return{...i,markets:t,...s.length>0?{updates:Object.fromEntries(s)}:{}}}function Dg(e,t,n,r){return t.find((i)=>i!==n&&!Cr(i,n)&&Jo(e,i)===r)}function gc(e,t,n,r){let i=se(e),s=ze(i.markets),o=Dg(e,s,t,n);if(o)throw Error(`${n} already names the market at ${be(o)} — \`ttheme market remove ${n}\` first`);let a=r===void 0?{...i.updates}:{...i.updates,[t]:r};Et(e,ds(i,s.includes(t)?s:[...s,t],a))}async function qy(e){if(!pc())return!1;let t=await _t({message:`Update ${e} on its own when its author changes it? ttheme checks once a day, when you run it`,initialValue:!1});if(xe(t))throw Error("no answer given — nothing was added");return t}async function em(e){let t=Gn(`Fetching ${be(e)}`);try{return await ls(e)}finally{t.done()}}async function Qy(e,t,n){let r=await em(n),i=se(e),s=ze(i.markets),o=Dg(e,s,n,r.id);if(o)throw Error(`${r.id} already names the market at ${be(o)} — \`ttheme market remove ${r.id}\` first`);let{[t]:a,...u}=i.updates??{},c=a===void 0?u:{...u,[n]:a};return Et(e,ds(i,s.map((l)=>l===t?n:l),c)),ei(e,r),r}async function wc(e,t){let n=Pn(t),r=ze(se(e).markets);if(r.includes(n))return console.log(`${be(n)} is already added`),{source:n,id:ni(e,n),fresh:!1};let i=ht(n)?r.find((u)=>ht(u)&&Cr(u,n)):void 0;if(i){let u=await Qy(e,i,n);return console.log(`Moved ${u.id} to ${Gu(n)??"its default branch"} · ${be(n)} — ${at(et(u.entries).length)}`),{source:n,id:u.id,fresh:!1}}if(Oe(n)){let u=ft(Yt(n));gc(e,n,u);let c=Tn(n,u,Ko(e)).length;return console.log(`Added ${u} · ${be(n)} — ${at(c)}, read in place`),{source:n,id:u,fresh:!0}}let s=await em(n),o=n===z?void 0:await qy(s.id);gc(e,n,s.id,o),ei(e,s);let a=at(et(s.entries).length);return console.log(n===z?`Added the ttheme catalog — ${a}`:`Added ${s.id} · ${be(n)} — ${a}${o?", updating on its own":""}`),{source:n,id:s.id,fresh:!0}}async function Yy(e){let t=he(),{source:n,id:r,fresh:i}=await wc(t,e);if(!i)return;if(Oe(n))console.log("\n`ttheme browse` picks them · `ttheme market build` there writes the index others fetch");else if(n===z)console.log("\n`ttheme browse` picks them");else console.log(`
404
- \`ttheme browse\` picks them, or \`ttheme add ${r}/<palette>\``)}function bc(e,t){if(t===z)zg(At(e),{force:!0});else if(ht(t))zg(Ot(e,t),{force:!0})}function $c(e){return`${at(e.length)} installed from it keep${e.length===1?"s":""} working: ${e.join(", ")} — \`ttheme remove\` drops ${e.length===1?"it":"them"}`}function Zy(e){let t=he(),n=se(t),r=ze(n.markets),i=r.find((c)=>Jo(t,c)===e)??r.find((c)=>c===tm(e));if(!i)throw Error(`no market named ${e} — \`ttheme market\` lists them`);let s=Jo(t,i),o=n.palettes.filter((c)=>xg(c)===s),a=r.filter((c)=>c!==i),u=ds(n,a,n.updates??{});if(Et(t,u),bc(t,i),ot(t,Le(t),u),console.log(`Removed ${s??e} · ${be(i)}`),o.length>0)console.log($c(o))}function tm(e){try{return Pn(e)}catch{return}}function zy(e,t){try{if(t===z)return et(Zt(mc(At(e),"utf8")).palettes).length;if(Oe(t))return Tn(t,ni(e,t),Ko(e),!1).length;return An(e,t).palettes.length}catch{return}}function kc(e,t,n=fn(),r=Date.now()){if(Oe(t))return"read in place";let i=n[t],s=cs(e,t);if(i&&(s===void 0||i.at>s))return`update failed ${fs(i.at,r)}`;return s===void 0?"never updated":`updated ${fs(s,r)}`}function By(){let e=he(),t=se(e),n=ze(t.markets);if(n.length===0){console.log("No markets — `ttheme market add official` brings the ttheme catalog back");return}let r=fn(),i=n.map((a)=>{let u=Jo(e,a)??"?",c=zy(e,a),l=t.palettes.filter((f)=>xg(f)===u).length,h=Oe(a)?[]:[`auto-update ${Fn(a,t.updates)?"on":"off"}`];return{name:u,where:be(a),note:[c===void 0?"Unreadable":at(c),...l>0?[`${l} installed`]:[],...h,kc(e,a,r)].join(" · ")}}),s=Math.max(...i.map((a)=>a.name.length)),o=Math.max(...i.map((a)=>a.where.length));for(let a of i)console.log(` ${a.name.padEnd(s)} ${a.where.padEnd(o)} ${a.note}`)}function yc(e){return`${e.owner.login.toLowerCase()}/${e.name}`}async function Ec(e,t){let n=encodeURIComponent(`topic:${Ur}${e?` ${e}`:""}`);try{let{items:r}=await Ki(`https://api.github.com/search/repositories?q=${n}&sort=stars&per_page=50`,(i)=>JSON.parse(i),void 0,t);return r}catch(r){if(r instanceof Fo)throw Error("GitHub lets a search through about ten times a minute without signing in — try again in a minute");throw r}}async function Vy(e){let t=he(),n=await Ec(e);if(n.length===0){console.log(`No repository carries the ${Ur} topic${e?` and matches ${e}`:""} yet`);return}let r=new Set(ze(se(t).markets).map(Nn)),i=n.map((o)=>{let a=yc(o);return{arg:a,added:r.has(a),stars:`★${o.stargazers_count}`,about:o.description??""}}),s=Math.max(...i.map((o)=>o.arg.length));for(let o of i)console.log(` ${o.added?"●":"○"} ${o.arg.padEnd(s)} ${o.stars.padStart(5)} ${o.about}`);console.log("\n`ttheme market add <name>` adds one")}var Xy=`name: ttheme market
404
+ }`;function $i(){return process.platform==="darwin"}function Sa(e){return e>=z1&&e<=Y1}function Gs(e,t,n){return new Promise((r,i)=>{let s=B1("osascript",["-l","JavaScript","-e",Q1,e,t],{stdio:["ignore","ignore","pipe"],signal:AbortSignal.any([n,AbortSignal.timeout(q1)])}),o="";s.stderr.on("data",(a)=>{o+=a}),s.on("error",i),s.on("close",(a)=>{if(a===0){r();return}i(Error(o.trim().split(`
405
+ `).at(-1)||`osascript exited ${a}`))})})}var Bm=90000;function Ia(e,t){let n=je(e),r=Ot(e,t).flatMap((i)=>{let[,s,o]=/^([a-z.]+)_(\d+)$/.exec(i.key)??[];return s&&o&&V.some((a)=>a.key===s)?[{site:s,id:Number(o),...yc(n,i)}]:[]});return r.length>0?r:void 0}function V1(e,t){let n=new Set(ut(je(e)).palettes[t.name]?.pictures.map((r)=>r.key));return(t.pictures??[]).filter((r)=>!n.has(ct(r)))}function Ei(e,t){let n=new Set((t??[]).map((r)=>ct(r)));return{...e,pictures:(e.pictures??[]).filter((r)=>!n.has(ct(r)))}}function X1(e){return{name:e.name,background:e.background,foreground:e.foreground,cursor:e.cursor,selection:e.selection,ansi:e.ansi,...e.waived?{waived:e.waived}:{}}}async function D1(e,t,n,r,i,s){let o=V.find((b)=>b.key===n.site);if(!o)throw Error(`no site called ${n.site}`);s("Fetching");let a=await as(o,n.id,i);if(!a)throw Error("the post is gone");if(o!==Ft&&a.md5)try{Yo([a],await Qo([a.md5],i))}catch{}let u=zo(o,a)?qo(o,a.id,i).then((b)=>{if(b)cs(a,b)},()=>{}):void 0;if(!Jo(o,a,fr(process.env.TTHEME_FIND_RATING))||Ko(a,Zr(process.env.TTHEME_FIND_BLOCK)).length>0)throw Error("outside your find filters — TTHEME_FIND_RATING and TTHEME_FIND_BLOCK");let c=Vt(a);if(!c)throw Error("too large to use");let l=yi(Xt(o),"orig",`${n.id}.${c.ext}`),h;if(zc(l))h=new Uint8Array(ki(l));else{s("Downloading");let b=Vr(o,a,c);h=await Vo(b.site,b.url,i,(m,$)=>s("Downloading",Ma(m,$))),Z(l,h)}let f=Ln(h,pt),d=!1;if(fn(f)===0&&$i()&&process.env.TTHEME_FIND_REMOVE_BG!=="off"){let b=yi(Xt(o),"cut",`${n.id}.png`);try{if(!zc(b))s("Cutting out"),Km(Jm(b),{recursive:!0}),await Gs(l,b,i);let m=Ln(new Uint8Array(ki(b)),pt);if(Sa(fn(m)))f=m,d=!0}catch{}}await u;let g=X1(t);s("Drawing"),ra(e,g,ni(g,t.signatureSlots),f,{site:o.key,id:n.id,ext:c.ext,bytes:h,from:`${o.name} ${n.id} ${o.pageUrl(n.id)}`,artist:a.named.artist,source:us(a.source),cut:d},{width:0,height:0},gi(e));let p=Ot(e,t.name).find((b)=>b.key===ct(n));if(p)gs(je(e),p,n,r,Z1())}function eE(e,t){let n=V.find((s)=>s.key===e.site),r=`${n?.name??e.site} ${e.id}`;if(!n||!t)return r;return`${At()?Ji:`\x1B[${30+n.ansi}m${Ji}\x1B[39m`} ${Fo(r,n.pageUrl(e.id))}`}async function kn(e,t,n){let r=t.flatMap((u)=>V1(e,u).map((c)=>({entry:u,shared:c})));if(r.length===0)return;let i=!n.includes("iterm2"),s=process.stdout.isTTY&&im(process.env),o=new Set,a=er();for(let[u,{entry:c,shared:l}]of r.entries()){let h=`${c.name} · ${eE(l,s)}`,f=r.length>1?` · ${u+1}/${r.length}`:"",d=(g,p)=>a.set(`${g} ${h}${p?` · ${p}`:""}${f}`);try{await D1(e,c,l,i,AbortSignal.timeout(Bm),d),a.say(` ▣ ${h}`),o.add(c)}catch(g){a.say(` ▢ ${h} — ${g instanceof Error?g.message:String(g)}`)}}a.done();for(let u of o){let c=(u.pictures??[]).find((l)=>Ot(e,u.name).some((h)=>h.key===ct(l)));if(c)ii(e,u.name,ct(c))}if(o.size>0)xt(e)}function Wm(e,t,n){if(t.width!==e.width||t.height!==e.height)return!1;for(let r=0;r<e.width*e.height;r++)e.data[r*4+3]=t.data[r*4+n]??0;return!0}async function tE(e,t){let[,n,r]=/^(.+)_(\d+)$/.exec(e)??[],i=yi(Xr(),n??"local","cut",`${r??e}.png`);if(!zc(i)){if(!$i())return;Km(Jm(i),{recursive:!0}),await Gs(t,i,AbortSignal.timeout(Bm))}return Ln(new Uint8Array(ki(i)),pt)}function nE(e,t){try{return fn(cr(new Uint8Array(ki(yi(e,`${t.stem}.png`)))))>0}catch{return!1}}async function qm(e,t,n,r,i,s,o){let a=je(e),u=ut(a).palettes[t]?.pictures.find((h)=>h.key===n);if(!u?.original)return null;let c=yi(a,u.original),l=Ln(new Uint8Array(ki(c)),pt);if(u.cut){if(!Wm(l,cr(new Uint8Array(ki(yi(a,u.cut)))),0))return null;return ia(e,t,u,l,r,i,s,o,!1)}if(u.tone===void 0&&fn(l)===0&&nE(a,u)){let h=await tE(n,c);if(!h||!Wm(l,h,3))return null;return ia(e,t,u,l,r,i,s,o,!0)}return ia(e,t,u,l,r,i,s,o,!1)}var aE=86400000,uE=3600000,Qc=5000;function Yc(){return zm(process.env.XDG_STATE_HOME??zm(sE(),".local","state"),"ttheme","markets.json")}function yn(){try{let e=JSON.parse(Zm(Yc(),"utf8"));return Object.fromEntries(Object.entries(e).filter((t)=>typeof t[1]?.at==="number"&&typeof t[1].error==="string"))}catch{return{}}}function Ym(e,t){let n=yn();if(t===void 0){if(!(e in n))return;delete n[e]}else n[e]={at:Date.now(),error:t};Qm(oE(Yc()),{recursive:!0}),Z(Yc(),`${JSON.stringify(n,null,2)}
406
+ `)}function Us(e,t){let n=t===D?Jt(e):wt(t)?Kt(e,t):void 0;try{return n?iE(n).mtimeMs:void 0}catch{return}}function cE(e,t,n,r){return e&&(t===void 0||r-t>=aE)&&(n===void 0||r-n>=uE)}function Zc(e,t,n=Date.now()){let r=yn();return et(t.markets).filter((i)=>cE(qn(i,t.updates),Us(e,i),r[i]?.at,n))}async function lE(e,t,n){try{return await $s(Rg(e),Hc,t,n)}catch(r){if(r instanceof fa)throw Error(`${ke(e)} has no ${nn} — is the repository public, and has its action run?`);throw r}}async function js(e,t,n){if(e===D){let s=await $s(Jg,sn,t,n);return{source:e,id:D,manifest:s,entries:s.palettes}}let r=await lE(e,t,n),i=ui(e,r);return{source:e,id:i,manifest:r,entries:la(r,i)}}function vi(e,t){if(t.source===D){ca(e,t.manifest);return}Qm(Mc(e),{recursive:!0}),Z(Kt(e,t.source),`${JSON.stringify(t.manifest,null,2)}
407
+ `)}function Mi(e,t){try{if(t===D)return sn(Zm(Jt(e),"utf8")).palettes;let n=Zn(e,t);return la(n,ui(t,n))}catch{return[]}}function hE(e,t){let n=new Map(e.map((i)=>[i.name,JSON.stringify(i)])),r=new Map(t.map((i)=>[i.name,JSON.stringify(i)]));return{added:[...r.keys()].filter((i)=>!n.has(i)),changed:[...r].filter(([i,s])=>n.has(i)&&n.get(i)!==s).map(([i])=>i),gone:[...n.keys()].filter((i)=>!r.has(i))}}async function Ws(e,t,n){let r=Mi(e,t),i;try{i=await js(t,n)}catch(s){throw Ym(t,s.message),s}return vi(e,i),Ym(t,void 0),{source:t,id:i.id,...t===D?{version:i.manifest.version}:{},count:st(i.entries).length,change:hE(r,i.entries)}}function ht(e){return`${e} palette${e===1?"":"s"}`}function Ks(e,t=Date.now()){let n=Math.floor(Math.max(0,t-e)/60000);if(n<1)return"just now";if(n<60)return`${n}m ago`;let r=Math.floor(n/60);return r<48?`${r}h ago`:`${Math.floor(r/24)}d ago`}function Vm({added:e,changed:t,gone:n}){return[e.length>0?`${e.length} new`:"",t.length>0?`${t.length} changed`:"",n.length>0?`${n.length} gone`:""].filter(Boolean).join(", ")}function Vc(e){let t=Vm(e.change);return`${e.version?`${e.id} ${e.version}`:e.id} — ${ht(e.count)}${t?` (${t})`:""}`}function Xc(e){return Vm(e.change)?`Updated ${Vc(e)}`:void 0}async function Na(e,t,n,r){let i=new Set(r.flatMap((c)=>[...c.change.changed,...c.change.gone])),s=t.palettes.filter((c)=>i.has(c));if(s.length===0)return;let o=_e(e,!1);lt(e,o,t);let a=new Set(r.flatMap((c)=>c.change.gone));for(let c of s.filter((l)=>a.has(l)))console.log(`${c} left its market — ttheme keeps the copy you have`);let u=new Map(n.map((c)=>[c.name,c.pictures]));await kn(e,We(e,o,!1).palettes.filter((c)=>s.includes(c.name)&&u.has(c.name)).map((c)=>Ei(c,u.get(c.name))),t.terminals)}async function Xm(e=de()){try{if(!rE(Bn(e)))return;let t=ae(e),n=Zc(e,t);if(n.length===0)return;let r=pn(e),i=er(`Checking ${n.map(ke).join(", ")} for updates`),s=(await Promise.allSettled(n.map((a)=>Ws(e,a,Qc)))).flatMap((a)=>a.status==="fulfilled"?[a.value]:[]);i.done();let o=s.flatMap((a)=>Xc(a)??[]);if(o.length===0)return;for(let a of o)console.log(a);await Na(e,t,r,s)}catch{return}}var rp=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,pE=["add","remove","search","init"];function nl(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function bE(){try{let e=fE("gh",["api","user","--jq",".login"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4}).trim().toLowerCase();return rp.test(e)?e:void 0}catch{return}}async function wE(e,t){if(t.author)return t.author;let n=bE();if(!n){if(!nl())throw Error("your palettes are named after your GitHub handle — log in with `gh auth login`, or run this in a terminal");let r=await Iu({message:"Your GitHub handle — your palettes are named <handle>@<market>/<palette>",validate:(i)=>rp.test((i??"").toLowerCase())&&(i??"").length<=39?void 0:"that is not a GitHub handle"});if(ft(r))throw Error("no handle given");n=r.toLowerCase()}return Lt(e,{...t,author:n}),console.log(`Your palettes are named ${n}@<market>/<palette>`),n}function Si(e,t){if(t===D)return D;return Te(t)?$t(rn(t)):ui(t,Zn(e,t))}function Pa(e,t){try{return Si(e,t)}catch{return}}function ip(e){return ve(e)??D}function Fa(e){return _e(e).palettes.filter((t)=>ve(t.name)===void 0)}function $E(e){let t=Sr(import.meta.dirname,"..","dist","manifest.json");return Dc(t)?sn(tl(t,"utf8")).palettes:Fa(e)}function Js(e,t,n){let{updates:r,...i}=e,s=Object.entries(n).filter(([o,a])=>t.includes(o)&&a!==qn(o,{}));return{...i,markets:t,...s.length>0?{updates:Object.fromEntries(s)}:{}}}function sp(e,t,n,r){return t.find((i)=>i!==n&&!ai(i,n)&&Pa(e,i)===r)}function el(e,t,n,r){let i=ae(e),s=et(i.markets),o=sp(e,s,t,n);if(o)throw Error(`${n} already names the market at ${ke(o)} — \`ttheme market remove ${n}\` first`);let a=r===void 0?{...i.updates}:{...i.updates,[t]:r};Lt(e,Js(i,s.includes(t)?s:[...s,t],a))}async function kE(e){if(!nl())return!1;let t=await Nn({message:`Update ${e} on its own when its author changes it? ttheme checks once a day, when you run it`,initialValue:!1});if(ft(t))throw Error("no answer given — nothing was added");return t}async function op(e){let t=er(`Fetching ${ke(e)}`);try{return await js(e)}finally{t.done()}}async function yE(e,t,n){let r=await op(n),i=ae(e),s=et(i.markets),o=sp(e,s,n,r.id);if(o)throw Error(`${r.id} already names the market at ${ke(o)} — \`ttheme market remove ${r.id}\` first`);let{[t]:a,...u}=i.updates??{},c=a===void 0?u:{...u,[n]:a};return Lt(e,Js(i,s.map((l)=>l===t?n:l),c)),vi(e,r),r}async function rl(e,t){let n=zn(t),r=et(ae(e).markets);if(r.includes(n))return console.log(`${ke(n)} is already added`),{source:n,id:Si(e,n),fresh:!1};let i=wt(n)?r.find((u)=>wt(u)&&ai(u,n)):void 0;if(i){let u=await yE(e,i,n);return console.log(`Moved ${u.id} to ${vc(n)??"its default branch"} · ${ke(n)} — ${ht(st(u.entries).length)}`),{source:n,id:u.id,fresh:!1}}if(Te(n)){let u=$t(rn(n));el(e,n,u);let c=Qn(n,u,Fa(e)).length;return console.log(`Added ${u} · ${ke(n)} — ${ht(c)}, read in place`),{source:n,id:u,fresh:!0}}let s=await op(n),o=n===D?void 0:await kE(s.id);el(e,n,s.id,o),vi(e,s);let a=ht(st(s.entries).length);return console.log(n===D?`Added the ttheme catalog — ${a}`:`Added ${s.id} · ${ke(n)} — ${a}${o?", updating on its own":""}`),{source:n,id:s.id,fresh:!0}}async function EE(e){let t=de(),{source:n,id:r,fresh:i}=await rl(t,e);if(!i)return;if(Te(n))console.log("\n`ttheme browse` picks them · `ttheme market build` there writes the index others fetch");else if(n===D)console.log("\n`ttheme browse` picks them");else console.log(`
408
+ \`ttheme browse\` picks them, or \`ttheme add ${r}/<palette>\``)}function il(e,t){if(t===D)ep(Jt(e),{force:!0});else if(wt(t))ep(Kt(e,t),{force:!0})}function sl(e){return`${ht(e.length)} installed from it keep${e.length===1?"s":""} working: ${e.join(", ")} — \`ttheme remove\` drops ${e.length===1?"it":"them"}`}function vE(e){let t=de(),n=ae(t),r=et(n.markets),i=r.find((c)=>Pa(t,c)===e)??r.find((c)=>c===ap(e));if(!i)throw Error(`no market named ${e} — \`ttheme market\` lists them`);let s=Pa(t,i),o=n.palettes.filter((c)=>ip(c)===s),a=r.filter((c)=>c!==i),u=Js(n,a,n.updates??{});if(Lt(t,u),il(t,i),lt(t,_e(t),u),console.log(`Removed ${s??e} · ${ke(i)}`),o.length>0)console.log(sl(o))}function ap(e){try{return zn(e)}catch{return}}function ME(e,t){try{if(t===D)return st(sn(tl(Jt(e),"utf8")).palettes).length;if(Te(t))return Qn(t,Si(e,t),Fa(e),!1).length;return Zn(e,t).palettes.length}catch{return}}function ol(e,t,n=yn(),r=Date.now()){if(Te(t))return"read in place";let i=n[t],s=Us(e,t);if(i&&(s===void 0||i.at>s))return`update failed ${Ks(i.at,r)}`;return s===void 0?"never updated":`updated ${Ks(s,r)}`}function SE(){let e=de(),t=ae(e),n=et(t.markets);if(n.length===0){console.log("No markets — `ttheme market add official` brings the ttheme catalog back");return}let r=yn(),i=n.map((a)=>{let u=Pa(e,a)??"?",c=ME(e,a),l=t.palettes.filter((f)=>ip(f)===u).length,h=Te(a)?[]:[`auto-update ${qn(a,t.updates)?"on":"off"}`];return{name:u,where:ke(a),note:[c===void 0?"Unreadable":ht(c),...l>0?[`${l} installed`]:[],...h,ol(e,a,r)].join(" · ")}}),s=Math.max(...i.map((a)=>a.name.length)),o=Math.max(...i.map((a)=>a.where.length));for(let a of i)console.log(` ${a.name.padEnd(s)} ${a.where.padEnd(o)} ${a.note}`)}function al(e){return`${e.owner.login.toLowerCase()}/${e.name}`}async function ul(e,t){let n=encodeURIComponent(`topic:${si}${e?` ${e}`:""}`);try{let{items:r}=await $s(`https://api.github.com/search/repositories?q=${n}&sort=stars&per_page=50`,(i)=>JSON.parse(i),void 0,t);return r}catch(r){if(r instanceof da)throw Error("GitHub lets a search through about ten times a minute without signing in — try again in a minute");throw r}}async function IE(e){let t=de(),n=await ul(e);if(n.length===0){console.log(`No repository carries the ${si} topic${e?` and matches ${e}`:""} yet`);return}let r=new Set(et(ae(t).markets).map(Jn)),i=n.map((o)=>{let a=al(o);return{arg:a,added:r.has(a),stars:`★${o.stargazers_count}`,about:o.description??""}}),s=Math.max(...i.map((o)=>o.arg.length));for(let o of i)console.log(` ${o.added?"●":"○"} ${o.arg.padEnd(s)} ${o.stars.padStart(5)} ${o.about}`);console.log("\n`ttheme market add <name>` adds one")}var NE=`name: ttheme market
405
409
 
406
410
  on:
407
411
  push:
@@ -416,57 +420,33 @@ jobs:
416
420
  runs-on: ubuntu-latest
417
421
  steps:
418
422
  - uses: kecan0406/ttheme/market@v1
419
- `;function nm({name:e}){return`ttheme-${e}`}function xy(e,t){Zg(vo(e),{recursive:!0}),Zg(cr(e,".github","workflows"),{recursive:!0}),rm(e,t,[]),ke(cr(e,".github","workflows","ttheme.yml"),Xy),ke(cr(e,"README.md"),`# ${ft(t)}
423
+ `;function up({name:e}){return`ttheme-${e}`}function PE(e,t){Dm(aa(e),{recursive:!0}),Dm(Sr(e,".github","workflows"),{recursive:!0}),cp(e,t,[]),Z(Sr(e,".github","workflows","ttheme.yml"),NE),Z(Sr(e,"README.md"),`# ${$t(t)}
420
424
 
421
425
  A [ttheme](https://github.com/kecan0406/ttheme) market:
422
426
 
423
427
  \`\`\`sh
424
- ttheme market add ${t.owner}/${nm(t)}
428
+ ttheme market add ${t.owner}/${up(t)}
425
429
  ttheme browse
426
430
  \`\`\`
427
- `)}function rm(e,{owner:t,name:n},r){let{version:i,gate:s,placement:o}=Ci(),a={version:i,gate:s,placement:o,owner:t,name:n,palettes:r};ke(cr(e,Qt),`${JSON.stringify(a,null,2)}
428
- `)}function im(e){return qt(`x@${e}/x`)?"takes lowercase letters, digits and single hyphens":void 0}async function sm(){if(!pc())throw Error("name the market: ttheme market init <name>, or --in <name> on new");let e=await Ua({message:"Your market's name — its palettes are <you>@<name>/<palette>",validate:(t)=>im((t??"").toLowerCase())});if(xe(e))throw Error("no market name given");return e.toLowerCase()}async function om(e,t){let n=nr(e);if(t){let o=n.find((a)=>a.name===t||a.id===t||a.dir===tm(t));if(!o)throw Error(`${t} is not one of your local markets — \`ttheme market init ${t}\` makes it one`);return o}let[r,...i]=n;if(r&&i.length===0)return r;if(r)throw Error(`you have ${n.length} local markets — --in names one: ${n.map((o)=>o.name).join(", ")}`);let s=await sm();return am(e,_u(e,s),s)}async function am(e,t,n){let r=!dc(cr(t,Qt)),i;if(r){let o=im(n);if(o)throw Error(`the market name ${n} ${o}`);if(dc(t)&&Uy(t).length>0)throw Error(`${t} is not empty — pick a new folder for the market`);i={owner:await Jy(e,se(e)),name:n},xy(t,i)}else i=Yt(t);let s=ft(i);return gc(e,t,s),console.log(`${r?"Made":"Added"} your market ${s} · ${be(t)}`),{dir:t,...i,id:s}}function Bg(e){return e.startsWith(".")||e.startsWith("/")||e.startsWith("~")}async function Dy(e){let t=he(),n=e&&!Bg(e)?e.toLowerCase():e?_y(Pn(e)).toLowerCase():await sm(),r=e&&Bg(e)?Pn(e):_u(t,n),i=await am(t,r,n),s=`${i.owner}/${nm(i)}`;console.log(`
431
+ `)}function cp(e,{owner:t,name:n},r){let{version:i,gate:s,placement:o}=ms(),a={version:i,gate:s,placement:o,owner:t,name:n,palettes:r};Z(Sr(e,nn),`${JSON.stringify(a,null,2)}
432
+ `)}function lp(e){return tn(`x@${e}/x`)?"takes lowercase letters, digits and single hyphens":void 0}async function hp(){if(!nl())throw Error("name the market: ttheme market init <name>, or --in <name> on new");let e=await Iu({message:"Your market's name — its palettes are <you>@<name>/<palette>",validate:(t)=>lp((t??"").toLowerCase())});if(ft(e))throw Error("no market name given");return e.toLowerCase()}async function fp(e,t){let n=pr(e);if(t){let o=n.find((a)=>a.name===t||a.id===t||a.dir===ap(t));if(!o)throw Error(`${t} is not one of your local markets — \`ttheme market init ${t}\` makes it one`);return o}let[r,...i]=n;if(r&&i.length===0)return r;if(r)throw Error(`you have ${n.length} local markets — --in names one: ${n.map((o)=>o.name).join(", ")}`);let s=await hp();return dp(e,Sc(e,s),s)}async function dp(e,t,n){let r=!Dc(Sr(t,nn)),i;if(r){let o=lp(n);if(o)throw Error(`the market name ${n} ${o}`);if(Dc(t)&&dE(t).length>0)throw Error(`${t} is not empty — pick a new folder for the market`);i={owner:await wE(e,ae(e)),name:n},PE(t,i)}else i=rn(t);let s=$t(i);return el(e,t,s),console.log(`${r?"Made":"Added"} your market ${s} · ${ke(t)}`),{dir:t,...i,id:s}}function tp(e){return e.startsWith(".")||e.startsWith("/")||e.startsWith("~")}async function FE(e){let t=de(),n=e&&!tp(e)?e.toLowerCase():e?gE(zn(e)).toLowerCase():await hp(),r=e&&tp(e)?zn(e):Sc(t,n),i=await dp(t,r,n),s=`${i.owner}/${up(i)}`;console.log(`
429
433
  \`ttheme new <palette> --from <palette>\` puts palettes in it, and a folder under palettes/ shelves them in a catalog — others see them once it is on GitHub:
430
434
 
431
- cd ${be(r)}
435
+ cd ${ke(r)}
432
436
  git init -b main && git add -A && git commit -m "${i.id}"
433
437
  gh repo create ${s} --public --source . --push
434
- gh repo edit ${s} --add-topic ${Ur}
438
+ gh repo edit ${s} --add-topic ${si}
435
439
 
436
- Its action rebuilds ${Qt} on every push; then \`ttheme market add ${s}\` works anywhere`)}function e1(e){let t=e?Pn(e):process.cwd(),n=Yt(t),r=ft(n),i=Ky(he()),s=new Map,o=[],a=[];for(let u of On(t))try{let c=Wi(u,s);if(c)throw Error(c);s.set(u.slug,u);let l=Tt(`${r}/${u.slug}`,mc(u.path,"utf8"),i),h=Pt({...l,name:u.slug});o.push(u.catalog?{...h,catalog:u.catalog}:h)}catch(c){a.push(` ${Cy(t,u.path)}: ${c.message}`)}if(a.length>0)return console.error(`${a.length} palettes cannot be read — the index was left as it was:
440
+ Its action rebuilds ${nn} on every push; then \`ttheme market add ${s}\` works anywhere`)}function RE(e){let t=e?zn(e):process.cwd(),n=rn(t),r=$t(n),i=$E(de()),s=new Map,o=[],a=[];for(let u of Yn(t))try{let c=bs(u,s);if(c)throw Error(c);s.set(u.slug,u);let l=kt(`${r}/${u.slug}`,tl(u.path,"utf8"),i),h=Wt({...l,name:u.slug});o.push(u.catalog?{...h,catalog:u.catalog}:h)}catch(c){a.push(` ${mE(t,u.path)}: ${c.message}`)}if(a.length>0)return console.error(`${a.length} palettes cannot be read — the index was left as it was:
437
441
  ${a.join(`
438
- `)}`),1;for(let u of o){let l=Ji(u).filter((f)=>f.startsWith(" ✗")),h=u.catalog?`${u.catalog}/${u.name}`:u.name;console.log(` ${h}${l.length>0?`
442
+ `)}`),1;for(let u of o){let l=ws(u).filter((f)=>f.startsWith(" ✗")),h=u.catalog?`${u.catalog}/${u.name}`:u.name;console.log(` ${h}${l.length>0?`
439
443
  ${l.join(`
440
- `)}`:" passes the gate"}`)}return rm(t,n,o),console.log(`
441
- ${r} · ${at(o.length)} → ${cr(t,Qt)}`),0}async function um(e,t){switch(e){case void 0:By();return;case"add":await Yy(Vg(e,t));return;case"remove":Zy(Vg(e,t));return;case"search":await Vy(t);return;case"init":await Dy(t);return;case"build":return e1(t);default:throw Error(`unknown market action ${e} — ${jy.join(", ")}, or none to list them`)}}function Vg(e,t){if(!t)throw Error(e==="add"?"market add takes a repository or a folder: ttheme market add alice/ttheme-dust":"market remove takes a market name — `ttheme market` lists them");return t}function cm(e,t){let n=ni(e,t);return`${n} — ${at(Tn(t,n,Ko(e),!1).length)}, read in place`}function ms(e,t){return`${e}/${t}`}function lm(e){return ye(e.name)?Hr(e.name):e.name}function gs(e){return e.catalog!==void 0&&fm(e.group)?ms(e.group,e.catalog):void 0}function vc(e){if(e?.kind==="palette")return`palette ${e.entry.name}`;if(e?.kind==="group")return`group ${e.name}`;if(e?.kind==="catalog")return`catalog ${ms(e.group,e.name)}`;return e?.kind??""}function qo(e,t){let n=t.toLowerCase();return[e.name,e.group,e.native??"",e.catalog??""].some((r)=>r.toLowerCase().includes(n))}function hm(e,t,n){let r=n.trim(),i=[],s=new Set,o=(a)=>({kind:"palette",entry:a});for(let a of e){if(a.default||s.has(a.group))continue;s.add(a.group);let u=e.filter((f)=>!f.default&&f.group===a.group),c=r?u.filter((f)=>qo(f,r)):u;if(r&&c.length===0)continue;let l=r.length>0||t.has(a.group);if(i.push({kind:"group",name:a.group,native:a.native,lead:u.find((f)=>f.lead)??a,expanded:l,count:c.length}),!l)continue;let h=c.filter((f)=>gs(f)!==void 0);for(let f of new Set(h.map((d)=>d.catalog))){let d=h.filter((m)=>m.catalog===f),g=r.length>0||t.has(ms(a.group,f));if(i.push({kind:"catalog",group:a.group,name:f,lead:d[0],expanded:g,count:d.length}),g)i.push(...d.map(o))}i.push(...c.filter((f)=>gs(f)===void 0).map(o))}return i}function t1(e,t){let n=t.trim(),r=new Set(e.filter((i)=>!i.default&&(n===""||qo(i,n))).map((i)=>i.group));return hm(e,new Set,"").filter((i)=>i.kind==="group"&&r.has(i.name))}function fm(e){return e.includes("@")}function n1(e){let t=e.findIndex((n)=>n.kind==="group"&&fm(n.name));return t>0&&e.slice(0,t).some((n)=>n.kind==="group")?[...e.slice(0,t),{kind:"rule"},...e.slice(t)]:e}function r1(e){let t=e.findIndex((n)=>n.kind==="palette");return t===-1?0:t}var _n="\x1B[0m",ps="\x1B[2m",ws="\x1B[1m",lr="\x1B[22m",Mc="\x1B[36m",Sc="\x1B[33m";function Qo(e){return e==="decode"||e==="glitch"?e:"typewriter"}class bs{picked;scope;maxItems;named=[];series=[];color;onFocus;entries=[];seriesPad=0;namePad=0;expanded=new Set;rows=[];cursor=0;top=0;filter="";lastFocused="";constructor(e){this.picked=e.picked,this.scope=e.scope??"palette",this.maxItems=e.maxItems??12,this.color=e.color??!0,this.onFocus=e.onFocus,this.load(e.entries),this.rebuild("first")}load(e){this.entries=e,this.named=e.filter((t)=>!t.default),this.series=[...new Set(this.named.map((t)=>t.group))],this.seriesPad=Math.max(0,...this.series.map((t)=>t.length)),this.namePad=Math.max(0,...this.named.map((t)=>this.indent(t).length+lm(t).length))}indent(e){return gs(e)===void 0?" ":" "}setEntries(e){this.load(e),this.rebuild("stay")}setFilter(e){if(e!==this.filter)this.filter=e,this.rebuild("keep")}focusedRow(){return this.rows[this.cursor]}refocus(){this.lastFocused="",this.sync()}members(e,t){let n=this.scope==="palette"?this.filter.trim():"";return this.named.filter((r)=>r.group===e&&(t===void 0||r.catalog===t)&&(n===""||qo(r,n)))}everyone(e){return e.flatMap((t)=>t.kind==="group"?this.members(t.name):[])}pick(){let e=this.rows[this.cursor],t=e?.kind==="palette"?[e.entry.name]:e?.kind==="group"?this.members(e.name).map((r)=>r.name):e?.kind==="catalog"?this.members(e.group,e.name).map((r)=>r.name):e?.kind==="all"?this.everyone(this.rows).map((r)=>r.name):[];if(t.length===0)return;let n=t.some((r)=>!this.picked.has(r));for(let r of t)if(n)this.picked.add(r);else this.picked.delete(r)}pickedIn(e,t){return this.members(e,t).filter((n)=>this.picked.has(n.name)).length}pickedCount(){if(this.scope==="palette")return this.named.filter((e)=>this.picked.has(e.name)).length;return this.series.filter((e)=>this.members(e).every((t)=>this.picked.has(t.name))).length}total(){return this.scope==="series"?this.series.length:this.named.length}matched(){let e=this.filter.trim();if(this.scope==="series")return this.rows.filter((t)=>t.kind==="group").length;return e?this.named.filter((t)=>qo(t,e)).length:this.named.length}sync(){let e=this.rows[this.cursor],t=e?.kind==="palette"?e.entry:e?.kind==="group"&&this.scope==="series"?e.lead:void 0;if(t&&t.name!==this.lastFocused)this.lastFocused=t.name,this.onFocus?.(t)}rebuild(e){let t=this.rows[this.cursor],n=this.scope==="series"?t1(this.entries,this.filter):hm(this.entries,this.expanded,this.filter);this.rows=n.length>0?n1([{kind:"all",count:this.allCount(n)},...n]):[];let r=n.length>0?this.rows.indexOf(n[r1(n)]):0;if(e==="first")this.cursor=r;else if(e==="keep"||e==="stay"){let i=vc(t),s=t?.kind==="palette"||e==="stay"?this.rows.findIndex((o)=>vc(o)===i):-1;this.cursor=s===-1?r:s}else if(this.cursor>=this.rows.length)this.cursor=Math.max(0,this.rows.length-1);this.sync()}allCount(e){return this.scope==="series"?e.length:this.everyone(e).length}move(e){let t=this.cursor+e;if(this.rows[t]?.kind==="rule")t+=e;if(t>=0&&t<this.rows.length)this.cursor=t;this.sync()}toggle(e){if(this.expanded.has(e))this.expanded.delete(e);else this.expanded.add(e);this.rebuild("clamp")}climb(e,t){this.expanded.delete(e),this.rebuild("clamp"),this.cursor=Math.max(0,this.rows.findIndex((n)=>vc(n)===t)),this.sync()}fold(e){if(this.filter||this.scope==="series")return;let t=this.rows[this.cursor];if(t?.kind==="group"){if(e!==t.expanded)this.toggle(t.name)}else if(t?.kind==="catalog"){if(e!==t.expanded)this.toggle(ms(t.group,t.name));else if(!e)this.climb(t.group,`group ${t.group}`)}else if(t?.kind==="palette"&&!e&&!t.entry.default){let n=gs(t.entry);if(n===void 0)this.climb(t.entry.group,`group ${t.entry.group}`);else this.climb(n,`catalog ${n}`)}}window(){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 e=this.rows.slice(this.top,this.top+this.maxItems);return{lines:e.map((t,n)=>this.renderRow(t,this.top+n===this.cursor)),below:this.rows.length-this.top-e.length}}renderRow(e,t){if(e.kind==="rule")return` ${this.color?`${ps}${"── Markets ──────────"}${_n}`:"── Markets ──────────"}`;let n=e.kind==="palette"?e.entry:e.kind==="all"?void 0:e.lead,r=this.color&&t&&n!==void 0,i=(p)=>this.color?`${ps}${p}${lr}`:p,s=(p)=>this.color?`${ws}${p}${lr}`:p,o=(p)=>this.color?` ${th(yo(p),r?pn(p.foreground):"\x1B[39m")}`:"",a=t?r?`${pn(n.cursor)}▌\x1B[39m `:"▌ ":" ",u=(p)=>r?`${a}${js(n.selection,n.foreground)} ${p} ${_n}`:`${a} ${p}`;if(e.kind==="all"){let p=this.everyone(this.rows).every((E)=>this.picked.has(E.name))?"●":"○";return u(`${p} Select all ${i(`(${e.count})`)}`)}if(e.kind==="group"&&this.scope==="series"){let p=this.pickedIn(e.name)===e.count?"●":"○",E=`(${e.count})${e.native?` ${e.native}`:""}`;return u(`${p} ${s(e.name.padEnd(this.seriesPad))}${o(e.lead)}${this.color?" ":" "}${i(E)}`)}let c=this.rows[this.cursor],l=(p,E)=>this.color&&c?.kind==="palette"&&p?`${ws}${pn(c.entry.cursor)}${E}${lr}\x1B[39m`:s(E);if(e.kind==="group"){let p=l(c?.kind==="palette"&&c.entry.group===e.name,e.name),E=e.native?` ${i(e.native)}`:"";return u(`${e.expanded?"▾":"▸"} ${p} ${i(`(${this.pickedIn(e.name)}/${e.count})`)}${E}`)}if(e.kind==="catalog"){let p=c?.kind==="palette"&&gs(c.entry)===ms(e.group,e.name),E=i(`(${this.pickedIn(e.group,e.name)}/${e.count})`);return u(` ${e.expanded?"▾":"▸"} ${l(p,e.name)} ${E}`)}let h=e.entry,f=this.picked.has(h.name)?"●":"○",d=this.indent(h),g=lm(h),m=this.color?g.padEnd(this.namePad-d.length):g,b=t?s(m):m;return u(`${d}${f} ${b}${o(h)}`)}}function Ic(e){let t=e.named[Math.floor(Math.random()*e.named.length)],n=e.series[Math.floor(Math.random()*e.series.length)];return t&&n?`${t.name} | ${n}`:""}class Yo{fx;make;redraw;roller;example="";step=0;seed=0;timer;constructor(e,t,n){this.fx=e,this.make=t,this.redraw=n,this.roll(),this.roller=setInterval(()=>{this.roll(),this.step=8,this.redraw()},3000),this.roller.unref?.()}stop(){clearInterval(this.roller),clearTimeout(this.timer)}roll(){let e=this.make();this.example=e.length>30?`${e.slice(0,29)}…`:e,this.seed=Math.floor(Math.random()*997)}text(){if(this.step===0)return this.example;if(!this.timer)this.timer=setTimeout(()=>{this.timer=void 0,this.step-=1,this.redraw()},60),this.timer.unref?.();let e=Math.floor(this.example.length*(8-this.step)/8);if(this.fx==="typewriter")return`${this.example.slice(0,e)}▏`;let t=this.fx==="decode"?"abcdefghijklmnopqrstuvwxyz":"▓▒░#*+=<>?/-_",n=this.fx==="decode"?(r)=>!/[a-z0-9]/i.test(r):(r)=>r===" ";return[...this.example].map((r,i)=>i+(i*7+this.seed)%3<e||n(r)?r:t[Math.floor(Math.random()*t.length)]??r).join("")}}class Nc extends wt{picked;list;scope;color;hint;lastInput="";constructor(e){super({render:()=>this.draw(),input:e.input,output:e.output,validate:e.required?()=>this.picked.size===0?`Pick at least one ${this.scope}`:void 0:void 0},!0);this.scope=e.scope??"palette",this.picked=new Set(e.installed??[]),this.color=e.color??!0,this.list=new bs({entries:e.entries,picked:this.picked,scope:this.scope,...e.maxItems===void 0?{}:{maxItems:e.maxItems},color:this.color,...e.onFocus?{onFocus:e.onFocus}:{}}),this.hint=new Yo(e.fx??"typewriter",()=>Ic(this.list),()=>this.output.emit("resize")),this.once("finalize",()=>this.hint.stop()),this.on("cursor",(t)=>{if(t==="up")this.list.move(-1);else if(t==="down")this.list.move(1);else if(t==="left")this.list.fold(!1);else if(t==="right")this.list.fold(!0)}),this.on("userInput",(t)=>{if(t!==this.lastInput)this.lastInput=t,this.list.setFilter(t)}),this.on("key",(t,n)=>{if(n?.name==="space")this.list.pick()})}_isActionKey(e){return e==="\t"||e===" "}draw(){let e=(d)=>this.color?`${ps}${d}${_n}`:d,t=(d)=>this.color?`${Mc}${d}${_n}`:d,n=this.scope==="series"?"Series":"Catalog";if(this.state==="submit")return`${e("◇")} ${n} ${e(`· ${this.list.pickedCount()} picked`)}`;if(this.state==="cancel")return`${e(`◇ ${n} · cancelled`)}`;let r=`${t("◆")} ${n} ${e(`(${this.list.matched()}/${this.list.total()} · ${this.list.pickedCount()} picked)`)}`,i=this.hint.text(),s=`${t("│")} ${this.userInput?`${this.userInput}_`:e(`Search…${i?` e.g. ${i}`:""}`)}`,{lines:o,below:a}=this.list.window(),u=o.length>0?o.map((d)=>`${t("│")} ${d}`):[`${t("│")} ${e(`No ${this.scope==="series"?"series":"palettes"} match '${this.userInput}'`)}`];while(u.length<this.list.maxItems)u.push(t("│"));let c=a>0?`${t("│")} ${e(`↓ ${a} more`)}`:t("│"),l=this.scope==="series"?"":" · ←→ fold",h=this.scope==="series"?"continue":"install",f=this.state==="error"?`${t("└")} ${this.color?`${Sc}${this.error}${_n}`:this.error}`:`${t("└")} ${e(`↑↓ move${l} · space pick · type to filter · enter ${h} · esc cancel`)}`;return[r,s,...u,c,f].join(`
442
- `)}}var $s=[{tab:"catalog",title:"Catalog"},{tab:"installed",title:"Installed"},{tab:"markets",title:"Markets"},{tab:"errors",title:"Errors"}],Rc=34,i1=72,s1=94,Fc={title:"",lines:[],brief:""};function Zo(e){let t=e.trim();if(t!==z&&!t.includes("/")&&!t.startsWith("~"))return;try{return Pn(t)}catch{return}}function o1(e){return e.charAt(0).toUpperCase()+e.slice(1)}class Pc extends wt{picked;tab="catalog";filters={catalog:"",installed:"",markets:"",errors:""};cursor={markets:0,errors:0};top={markets:0,errors:0};adds=new Map;removes=new Set;want=new Map;busy=new Map;failed=new Map;refreshed=[];inflight=new Set;markets;problems;kept;installed;startup;io;order;color;maxItems;paint;catalog;mine;hint;asking;repos;searching=!1;searchError;lastInput="";constructor(e){super({render:()=>this.draw(),input:e.input,output:e.output},!0);this.markets=e.markets,this.problems=e.problems,this.kept=e.kept,this.installed=new Set(e.installed),this.startup=e.startup,this.io=e.io,this.order=e.order??((n)=>n),this.color=e.color??!0,this.maxItems=e.maxItems??12,this.paint=e.onFocus,this.picked=new Set(e.installed);let t=this.entries();this.catalog=new bs({entries:t,picked:this.picked,color:this.color,maxItems:this.maxItems,onFocus:(n)=>this.focus("catalog",n)}),this.mine=new bs({entries:this.mineOf(t),picked:this.picked,color:this.color,maxItems:this.maxItems,onFocus:(n)=>this.focus("installed",n)}),this.hint=new Yo(e.fx??"typewriter",()=>Ic(this.tab==="installed"?this.mine:this.catalog),()=>this.redraw()),this.once("finalize",()=>this.hint.stop()),this.on("cursor",(n)=>{if(this.asking)return;if(n==="up"||n==="down")this.move(n==="up"?-1:1);else if(n==="left"||n==="right")this.side(n==="right")}),this.on("userInput",(n)=>{if(n!==this.lastInput)this.lastInput=n,this.filters[this.tab]=n,this.list()?.setFilter(n)}),this.on("key",(n,r)=>this.key(n,r));for(let n of e.due)this.update(n)}_isActionKey(e){return e==="\t"||e===" "||this.asking!==void 0&&e!==void 0}_shouldSubmit(){return this.asking===void 0}async idle(){await Promise.allSettled([...this.inflight])}result(){let e=new Set(this.entries().map((t)=>t.name));return{picked:new Set([...this.picked].filter((t)=>e.has(t))),adds:[...this.adds.values()],removes:[...this.removes],auto:Object.fromEntries(this.want),refreshed:this.refreshed}}key(e,t){if(this.asking){if(t?.name==="escape")this.asking=void 0,Object.assign(t,{name:"answered",sequence:""});else if(e&&/^[yn]$/i.test(e))this.answer(e.toLowerCase()==="y");return}if(t?.name==="tab")this.switchTab(t.shift?-1:1);else if(t?.name==="space")this.activate();else if(t?.ctrl&&t.name==="r"){let n=this.tab==="markets"?this.marketRow():void 0;if(n?.kind==="market"&&!this.adds.has(n.market.source))this.update(n.market.source)}}redraw(){if(this.state==="active"||this.state==="error")this.output.emit("resize")}focus(e,t){if(this.tab===e&&this.state!=="submit"&&this.state!=="cancel")this.paint?.(t)}track(e){this.inflight.add(e);let t=()=>this.inflight.delete(e);return e.then(t,t),e}list(){return this.tab==="catalog"?this.catalog:this.tab==="installed"?this.mine:void 0}active(){return[...this.markets.filter((e)=>!this.removes.has(e.source)),...this.adds.values()]}entries(){let e=this.active().flatMap((i)=>i.entries),t=new Set(e.map((i)=>i.name)),n=new Map,r=this.markets.filter((i)=>this.removes.has(i.source)).flatMap((i)=>i.entries);for(let i of[...this.kept,...r])if(this.installed.has(i.name)&&!t.has(i.name))n.set(i.name,i);return this.order([...e,...n.values()])}mineOf(e){return e.filter((t)=>this.installed.has(t.name))}reload(){let e=this.entries();this.catalog.setEntries(e),this.mine.setEntries(this.mineOf(e))}switchTab(e){let t=$s.findIndex((i)=>i.tab===this.tab),n=$s[(t+e+$s.length)%$s.length]?.tab??"catalog",r=this.filters[n];this.tab=n,this._clearUserInput(),this._setUserInput(r,!0),this.lastInput=r,this.list()?.refocus()}move(e){let t=this.list();if(t){t.move(e);return}let n=this.tab==="markets"?"markets":"errors",r=n==="markets"?this.marketRows().map((s)=>s.kind==="rule"):this.problemRows().map(()=>!1),i=this.cursor[n]+e;if(r[i])i+=e;if(i>=0&&i<r.length)this.cursor[n]=i}side(e){let t=this.list();if(t){t.fold(e);return}let n=this.tab==="markets"?this.marketRow():void 0;if(n?.kind==="market"&&!Oe(n.market.source))if(e===n.market.auto)this.want.delete(n.market.source);else this.want.set(n.market.source,e)}activate(){let e=this.list();if(e){e.pick();return}let t=this.tab==="markets"?this.marketRow():void 0;if(t?.kind==="market")this.toggleMarket(t.market);else if(t?.kind==="add")this.fetch(t.source);else if(t?.kind==="repo"){let n=this.known(t.source),r=this.marketRows().findIndex((i)=>i.kind==="market"&&i.market===n);if(n&&r>=0)this.cursor.markets=r;else if(!n)this.fetch(t.source)}else if(t?.kind==="find")this.search()}toggleMarket(e){if(this.adds.has(e.source))this.adds.delete(e.source),this.want.delete(e.source);else if(this.removes.has(e.source))this.removes.delete(e.source);else this.removes.add(e.source);this.reload()}known(e){return[...this.markets,...this.adds.values()].find((t)=>Cr(t.source,e))}fetch(e){if(this.busy.has(e))return;this.failed.delete(e),this.busy.set(e,"Fetching…"),this.track(this.io.fetch(e)).then((t)=>{this.busy.delete(e);let n=this.active().find((r)=>r.id===t.id);if(n)this.failed.set(e,`${t.id} already names the market at ${n.shown}`);else if(Oe(e)||e===z)this.stage(t,t.auto);else this.asking=t;this.redraw()},(t)=>{this.busy.delete(e),this.failed.set(e,t.message),this.redraw()})}answer(e){let t=this.asking;if(this.asking=void 0,t)this.stage(t,e)}stage(e,t){if(this.adds.set(e.source,e),t===e.auto)this.want.delete(e.source);else this.want.set(e.source,t);this.reload(),this.cursor.markets=Math.max(0,this.marketRows().findIndex((n)=>n.kind==="market"&&n.market.source===e.source))}update(e){if(this.busy.has(e))return;this.failed.delete(e),this.busy.set(e,"Updating…"),this.track(this.io.refresh(e)).then(({market:t,refreshed:n})=>{this.busy.delete(e),this.markets=this.markets.map((r)=>r.source===e?t:r),this.problems=this.problems.filter((r)=>r.source!==e),this.refreshed.push(n),this.reload(),this.redraw()},(t)=>{this.busy.delete(e),this.failed.set(e,`Update failed: ${t.message}`),this.redraw()})}search(){if(this.searching)return;this.searching=!0,this.searchError=void 0;let e=this.filters.markets.trim();this.track(this.io.search(e&&!Zo(e)?e:void 0)).then((t)=>{this.searching=!1,this.repos=t,this.redraw()},(t)=>{this.searching=!1,this.searchError=t.message,this.redraw()})}marketRows(){let e=this.filters.markets.trim().toLowerCase(),t=(...o)=>e===""||o.some((a)=>a.toLowerCase().includes(e)),n=[...this.markets,...this.adds.values()],r=n.filter((o)=>t(o.id,o.shown,o.source)).map((o)=>({kind:"market",market:o})),i=Zo(this.filters.markets);if(i&&!n.some((o)=>Cr(o.source,i)))r.push({kind:"add",source:i});r.push({kind:"find"});let s=(this.repos??[]).map((o)=>({repo:o,source:yc(o)})).filter(({repo:o,source:a})=>t(a,o.description??""));if(s.length>0)r.push({kind:"rule"},...s.map(({repo:o,source:a})=>({kind:"repo",repo:o,source:a})));return r}marketRow(){let e=this.marketRows();return e[Math.min(this.cursor.markets,e.length-1)]}problemList(){let e=new Map([...this.markets,...this.adds.values()].map((t)=>[t.source,t.id]));return[...this.problems.filter((t)=>!(t.update&&t.source&&this.failed.has(t.source))),...[...this.failed].map(([t,n])=>({where:e.get(t)??t,message:n,source:t}))]}problemRows(){let e=this.filters.errors.trim().toLowerCase();return this.problemList().filter((t)=>e===""||`${t.where} ${t.message}`.toLowerCase().includes(e))}windowOf(e,t,n,r=()=>!1){let i=Math.min(this.cursor[t],Math.max(0,e.length-1));if(r(e[i]))i-=1;this.cursor[t]=i;let s=Math.min(this.top[t],i);if(i>=s+this.maxItems)s=i-this.maxItems+1;s=Math.max(0,Math.min(s,e.length-this.maxItems)),this.top[t]=s;let o=e.slice(s,s+this.maxItems);return{lines:o.map((a,u)=>n(a,s+u===i)),below:e.length-s-o.length}}dim(e){return this.color?`${ps}${e}${lr}`:e}bold(e){return this.color?`${ws}${e}${lr}`:e}warn(e){return this.color?`${Sc}${e}\x1B[39m`:e}lit(e,t,n){if(t&&this.color&&e)return`${pn(e.cursor)}▌\x1B[39m ${js(e.selection,e.foreground)} ${n} ${_n}`;return`${t?"▌ ":" "} ${n}`}status(e){return this.adds.has(e.source)?"Will add":this.removes.has(e.source)?"Will remove":this.busy.get(e.source)??(this.failed.has(e.source)||e.status.startsWith("update failed")?"Update failed":"")}marketLine(e,t){if(e.kind==="rule")return` ${this.dim("── On GitHub ──────────")}`;if(e.kind==="market"){let i=e.market,s=this.status(i),o=this.removes.has(i.source)?"○":"●",a=t?this.bold(i.id):i.id;return this.lit(i.entries.find((u)=>!u.default),t,`${o} ${a}${s?` ${this.dim(s)}`:""}`)}if(e.kind==="add"){let i=this.busy.get(e.source);return this.lit(void 0,t,`+ Add ${be(e.source)}${i?` ${this.dim(i)}`:""}`)}if(e.kind==="find"){let i=this.filters.markets.trim(),s=this.searching?"Searching GitHub…":i&&!Zo(i)?`Find "${i}" on GitHub`:"Find markets on GitHub";return this.lit(void 0,t,`⌕ ${s}`)}let n=this.busy.get(e.source),r=this.known(e.source)?"●":"○";return this.lit(void 0,t,`${r} ${e.source} ${this.dim(`★${e.repo.stargazers_count}`)}${n?` ${this.dim(n)}`:""}`)}problemLine(e,t){return this.lit(void 0,t,`${this.warn("✗")} ${e.where} ${this.dim(e.message)}`)}body(){let e=this.list();if(e){let n=this.filters[this.tab];return{...e.window(),empty:n?`No palettes match '${n}'`:this.tab==="installed"?"Nothing installed yet":"No palettes"}}if(this.tab==="markets")return{...this.windowOf(this.marketRows(),"markets",(n,r)=>this.marketLine(n,r),(n)=>n?.kind==="rule"),empty:""};let t=this.filters.errors;return{...this.windowOf(this.problemRows(),"errors",(n,r)=>this.problemLine(n,r)),empty:t?`No problems match '${t}'`:"No problems"}}changes(){return this.adds.size+this.removes.size+this.want.size}counts(){let e=[...this.busy.values()].includes("Updating…")?"Updating… · ":"",t=this.list();if(t)return`${e}${t.matched()}/${t.total()} · ${t.pickedCount()} picked`;if(this.tab==="markets"){let n=this.markets.length+this.adds.size,r=this.marketRows().filter((s)=>s.kind==="market").length,i=this.changes();return`${e}${r}/${n} markets${i>0?` · ${i} to apply`:""}`}return`${this.problemRows().length}/${this.problemList().length}`}searchText(){if(this.userInput)return`${this.userInput}_`;if(this.tab==="markets")return this.dim("Search… or add one: owner/repo");let e=this.tab==="errors"?"":this.hint.text();return this.dim(`Search…${e?` e.g. ${e}`:""}`)}tabBar(){return $s.map(({tab:e,title:t})=>{let n=e==="errors"?this.problemList().length:0,r=n>0?`${t} ${n}`:t;if(!this.color)return e===this.tab?`[${r}]`:` ${r} `;return e===this.tab?this.bold(r):this.dim(r)}).join(this.color?" ":" ")}sourceOf(e){let t=this.active().find((n)=>n.entries.some((r)=>r.name===e.name));if(!t)return"In no market you added";return t.source===z?"The ttheme catalog":t.shown}paletteState(e){let t=this.picked.has(e.name),n=this.installed.has(e.name),r=t&&n?"Installed":t?"Will install":n?"Will remove":"Not installed";return this.startup===e.name?`${r} · Default`:r}paletteDetail(e,t){if(!e||e.kind==="rule")return Fc;if(e.kind==="all")return{title:this.bold("Select all"),lines:["space picks every palette shown"],brief:""};if(e.kind==="group"){let c=this.entries().filter((f)=>f.group===e.name&&!f.default),l=this.sourceOf(e.lead),h=`${at(c.length)} · ${c.filter((f)=>this.installed.has(f.name)).length} installed`;return{title:this.bold(e.name),lines:[...e.native?tt(e.native,t).map((f)=>this.dim(f)):[],...tt(l,t),h],brief:`${l} · ${h}`}}if(e.kind==="catalog"){let c=this.entries().filter((f)=>f.group===e.group&&f.catalog===e.name),l=this.sourceOf(e.lead),h=`${at(c.length)} · ${c.filter((f)=>this.installed.has(f.name)).length} installed`;return{title:this.bold(e.name),lines:[e.group,...tt(l,t),h],brief:`${e.group} · ${h}`}}let n=e.entry,r=this.sourceOf(n),i=qi(n),s=`Gate ${jt.length-i.length}/${jt.length}`,o=n.pictures?.length??0,a=[...o>0?[`${o} picture${o===1?"":"s"}`]:[],...n.base?[`Base ${n.base}`]:[]].join(" · "),u=ye(n.name)?n.catalog?[n.catalog]:[]:[n.group,...n.native?[this.dim(n.native)]:[]];return{title:this.color?`${ws}${pn(n.cursor)}${n.name}${lr}\x1B[39m`:n.name,lines:[...tt(r,t),...u,this.paletteState(n),"",i.length===0?`${s} · passes`:s,...i.flatMap((c)=>tt(c,t-2).map((l,h)=>`${h===0?this.warn("✗"):" "} ${l}`)),...a?["",a]:[]],brief:[r,s,...a?[a]:[],this.paletteState(n)].join(" · ")}}marketDetail(e,t){if(!e||e.kind==="rule")return Fc;if(e.kind==="market"){let i=e.market,s=i.source===z?"The ttheme catalog":i.shown,o=i.entries.filter((d)=>!d.default),a=o.filter((d)=>this.installed.has(d.name)).map((d)=>d.name),u=`${at(o.length)} · ${a.length} installed`,c=Oe(i.source)?"Read in place":`Auto-update ${this.want.get(i.source)??i.auto?"on":"off"}`,l=this.busy.get(i.source)??o1(i.status),h=this.failed.get(i.source),f=this.adds.has(i.source)?["Will add"]:this.removes.has(i.source)?[a.length>0?`Will remove — ${a.join(", ")} stay${a.length===1?"s":""} installed`:"Will remove"]:this.want.has(i.source)?[`Auto-update turns ${this.want.get(i.source)?"on":"off"}`]:[];return{title:this.bold(i.id),lines:[...tt(s,t),u,"",Oe(i.source)?c:`${c} ${this.dim("←→")}`,...Oe(i.source)?[]:[l],...h?tt(h,t).map((d)=>this.warn(d)):[],...f.length>0?["",...f.flatMap((d)=>tt(d,t))]:[]],brief:[s,c,...f,...Oe(i.source)?[]:[l]].join(" · ")}}if(e.kind==="add"){let i=this.busy.get(e.source)??this.failed.get(e.source)??"space fetches its index";return{title:this.bold(be(e.source)),lines:["Not added","",...tt(i,t)],brief:i}}if(e.kind==="find"){let i=this.filters.markets.trim(),s=this.searchError??(this.searching?"Searching…":this.repos?`${this.repos.length} found`:"space searches GitHub");return{title:this.bold("GitHub"),lines:[...tt(`Repositories with the ${Ur} topic`,t),...i&&!Zo(i)?[`Matching "${i}"`]:[],"",...tt(s,t)],brief:s}}let r=this.known(e.source)?"Added":this.busy.get(e.source)??this.failed.get(e.source)??"space adds it";return{title:this.bold(e.source),lines:[`★ ${e.repo.stargazers_count}`,...tt(e.repo.description??"",t),"",...tt(r,t)],brief:r}}detail(e){let t=this.list();if(t)return this.paletteDetail(t.focusedRow(),e);if(this.tab==="markets")return this.marketDetail(this.marketRow(),e);let n=this.problemRows(),r=n[Math.min(this.cursor.errors,n.length-1)];return r?{title:this.bold(r.where),lines:tt(r.message,e),brief:r.message}:Fc}footer(e,t){if(this.asking)return`${e("└")} Update ${this.asking.id} on its own when its author changes it? ${this.dim("y yes · n no · esc back")}`;let n={catalog:["tab switch","↑↓ move","←→ fold","space pick",t?"type to filter":""],installed:["tab switch","↑↓ move","←→ fold","space pick",t?"type to filter":""],markets:["tab switch","space add/remove","←→ auto-update",t?"ctrl+r update":""],errors:["tab switch","↑↓ move","type to filter"]}[this.tab];return`${e("└")} ${this.dim([...n.filter(Boolean),"enter apply","esc cancel"].join(" · "))}`}summary(){let e=this.changes();return`${this.catalog.pickedCount()} picked${e>0?` · ${e} market change${e===1?"":"s"}`:""}`}columns(){return this.output.columns??100}draw(){let e=(h)=>this.color?`${Mc}${h}${_n}`:h;if(this.state==="submit")return`${this.dim("◇")} Browse ${this.dim(`· ${this.summary()}`)}`;if(this.state==="cancel")return this.dim("◇ Browse · cancelled");let t=this.columns(),n=t>=s1,r=n?Math.min(t-Rc-4,i1):t-1,{lines:i,below:s,empty:o}=this.body(),a=i.length>0?i.map((h)=>`${e("│")} ${h}`):[`${e("│")} ${this.dim(o)}`];while(a.length<this.maxItems)a.push(e("│"));let u=[`${e("◆")} ${this.tabBar()}`,rh(`${e("│")} ${this.searchText()}`,this.dim(this.counts()),r),...a,s>0?`${e("│")} ${this.dim(`↓ ${s} more`)}`:e("│")],c=this.detail(n?Rc:r-2);return[...n?u.map((h,f)=>`${Ct(h,r)} ${this.dim("│")} ${Ct(f===0?c.title:c.lines[f-1]??"",Rc,!1)}`):[...u.map((h)=>Ct(h,r,!1)),Ct(`${e("│")} ${this.dim(c.brief)}`,r,!1)],Ct(this.footer(e,n),t-1,!1)].join(`
443
- `)}}import{existsSync as I1}from"node:fs";import{spawnSync as d1}from"node:child_process";import{existsSync as ks,mkdirSync as g1,mkdtempSync as m1,readFileSync as Bo,rmSync as p1,writeFileSync as w1}from"node:fs";import{tmpdir as b1}from"node:os";import{basename as $1,dirname as bm,join as wm}from"node:path";var Tc=5,a1=6,dm=0.05,u1=[1,2,3,4,5,6,9,10,11,12,13,14],gm=(e,t)=>(t-e+360)%360<=180?1:-1;function Oc(e,t,n){let r=t*Math.cos(n*Math.PI/180),i=t*Math.sin(n*Math.PI/180),s=[e+0.3963377774*r+0.2158037573*i,e-0.1055613458*r-0.0638541728*i,e-0.0894841775*r-1.291485548*i].map((l)=>l**3),[o,a,u]=s,c=[4.0767416621*o-3.3077115913*a+0.2309699292*u,-1.2684380046*o+2.6097574011*a-0.3413193965*u,-0.0041960863*o-0.7034186147*a+1.707614701*u];if(c.some((l)=>l<-0.0001||l>1.0001))return;return c.map((l)=>{let h=Math.min(1,Math.max(0,l));return Math.round(255*(h<=0.0031308?12.92*h:1.055*h**0.4166666666666667-0.055))})}function zo(e,t,n){let r=0,i=t;if(Oc(e,t,n)===void 0)for(let o=0;o<24;o++){let a=(r+i)/2;if(Oc(e,a,n)===void 0)i=a;else r=a}else r=t;return`#${(Oc(e,r,n)??[0,0,0]).map((o)=>o.toString(16).padStart(2,"0")).join("")}`}function c1(e,t){let{l:n,c:r}=St(e);return zo(n,r,(t+360)%360)}function l1(e,t,n){let{l:r,c:i,h:s}=St(e),o=nt(t)<0.18,a=(l)=>zo(o?r+(1-r)*l:r*(1-l),i,s);if(ct(a(1),t)<n+dm)return a(1);let u=0,c=1;for(let l=0;l<30;l++){let h=(u+c)/2;if(ct(a(h),t)>=n+dm)c=h;else u=h}return a(c)}function h1(e,t){let{l:n,c:r,h:i}=St(e),s=0,o=n;for(let a=0;a<30;a++){let u=(s+o)/2;if(nt(zo(u,r,i))<=t-0.005)s=u;else o=u}return zo(s,r,i)}function f1(e,t,n){let r=$i[t],[i,s]=[St(e[t]),St(e[t+8])],o=(l,h)=>n.has(l)?[h]:Array.from({length:2*r.width+1},(f,d)=>(r.center-r.width+d+360)%360),a=(l,h,f)=>Er.every((d)=>{let g=(l>8?8:0)+d;if(g===l)return!0;let m=St(e[g]);return m.c<Ja||bn(m.h,h)>=Qs+1||Math.abs(m.l-f)>=Ys}),u,c=Number.POSITIVE_INFINITY;for(let l of o(t,i.h)){if(!n.has(t)&&!a(t,l,i.l))continue;for(let h of o(t+8,s.h)){if(bn(l,h)>Jn-Tc||!n.has(t+8)&&!a(t+8,h,s.l))continue;let f=bn(l,i.h)+bn(h,s.h);if(f<c)c=f,u=[l,h]}}return u}class mm{theme;moves=[];constructor(e){this.theme={...e,ansi:[...e.ansi]}}set(e,t,n){let r=this.get(e);if(n===r)return;if(this.moves.push({slot:e,rule:t,from:r,to:n}),e==="foreground")this.theme.foreground=n;else if(e==="selection")this.theme.selectionBackground=n;else this.theme.ansi[Number(e.slice(4))]=n}get(e){if(e==="foreground")return this.theme.foreground;if(e==="selection")return this.theme.selectionBackground;return this.theme.ansi[Number(e.slice(4))]}rehue(e,t,n){this.set(`ansi${e}`,t,c1(this.theme.ansi[e],n))}roles(){let e=new Set(this.theme.signatureSlots);for(let{slot:n,hue:r}of Js(this.theme)){let i=$i[vr(n)];this.rehue(n,"ansi-role",i.center+gm(i.center,r)*(i.width-Tc))}for(let{normal:n,gap:r}of Ks(this.theme)){if(r<=Jn)continue;let[i,s]=e.has(`ansi${n+8}`)?[n+8,n]:[n,n+8],o=St(this.theme.ansi[i]).h,a=St(this.theme.ansi[s]).h;this.rehue(s,"bright-follows",o+gm(o,a)*(Jn-Tc))}let t=Zs(this.theme);for(let[n,r]of qs(this.theme)){let i=vr(t.has(r)?n:r),s=f1(this.theme.ansi,i,t);if(s===void 0)continue;this.rehue(i,"distinct",s[0]),this.rehue(i+8,"distinct",s[1])}}readability(){let e=new Set(this.theme.waive),{background:t}=this.theme,n=(r,i,s,o=t)=>{if(e.has(r))return;for(let a of i)if(ct(this.get(a),o)<s)this.set(a,r,l1(this.get(a),o,s))};if(n("foreground",["foreground"],7),n("accents",u1.map((r)=>`ansi${r}`),3),n("light-ansi",["ansi7","ansi15"],7),n("ansi8-visible",["ansi8"],1.6),!e.has("ansi0-dark")&&nt(this.get("ansi0"))>0.15)this.set("ansi0","ansi0-dark",h1(this.get("ansi0"),0.15));n("selection",["selection"],7,this.theme.foreground)}net(){return[...new Set(this.moves.map((e)=>e.slot))].flatMap((e)=>{let t=this.moves.filter((i)=>i.slot===e),n=t[0].from,r=this.get(e);return n===r?[]:[{slot:e,rule:[...new Set(t.map((i)=>i.rule))].join(", "),from:n,to:r}]})}}function pm(e){let t=new mm(e);for(let n=0;n<a1;n++)if(t.readability(),t.roles(),Bs(t.theme).length===0)break;return{theme:t.theme,moves:t.net(),left:Bs(t.theme)}}function k1(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function $m(e,t){if(e.includes("/"))return e;let n=nr(t,!1),r=n.filter((s)=>On(s.dir).some((o)=>o.slug===e)),[i]=r.length===1?r:n.length===1?n:[];return i?`${i.id}/${e}`:e}function y1(e,t,n){let r=se(e),i=n.filter((s)=>!r.palettes.includes(s));if(i.length>0)hn(e,t,r,{...r,palettes:[...r.palettes,...i]});else if(n.some((s)=>r.palettes.includes(s)))ot(e,t,r);return{state:r,fresh:i}}function E1(e){let t=Math.max(0,...e.map((n)=>n.slot.length));return e.map((n)=>` ${n.slot.padEnd(t)} ${n.from} → ${n.to} ${n.rule}`)}function km(e,t,n){let r=qd(t),i=Pt(Tt(r.name,Ju(r),n.palettes)),s=_e(e,n,!1).palettes.find((o)=>o.name===i.name);if(s&&JSON.stringify(s)!==JSON.stringify(i))throw Error(`${i.name} is already in ${ye(i.name)??"the ttheme catalog"} and differs — \`ttheme add ${i.name}\` wears that one`);if(!s)No(e,[...un(e),i]);return i.name}async function ym(e,t,n){let r=he(),i=Le(r),s=se(r),o=await om(r,n),a=e.includes("/")?e:`${o.id}/${e}`,u=qt(a);if(u)throw Error(`${a} ${u}`);if(ye(a)!==o.id)throw Error(`palettes in ${o.dir} are named ${o.id}/<palette> — ${a} belongs elsewhere`);let c=ju(r,a);if(ks(c))throw Error(`${a} already exists — \`ttheme edit ${a}\` changes it`);let l=_e(r,i),h=t??ln(s);if(!h)throw Error("--from names the palette to start from");let f=rr(l.palettes,h),d=ye(f.name)?f.base:f.default?void 0:f.name,{base:g,ansiSource:m,group:b,...p}=Wu(f,a,`kept from ${f.name}`),E=ac(r,f.name)??f.pictures,v=Ju({...p,...d?{base:d}:{},...E?{pictures:E}:{}});Tt(a,v,i.palettes),g1(bm(c),{recursive:!0}),ke(c,v);let{state:S}=y1(r,i,[a]);console.log(` + ${a} from ${f.name}
444
- ${c}`),await Xt(r,_e(r,i).palettes.filter((w)=>w.name===a),S.terminals),console.log(`
445
- \`ttheme edit ${a}\` changes its colors · \`ttheme use ${a}\` wears it`)}function v1(e){let t=process.env.VISUAL||process.env.EDITOR||"vi",n=d1("sh",["-c",`${t} "$1"`,"sh",e],{stdio:"inherit"});if(n.status!==0)throw Error(`${t} exited ${n.status??n.signal}`)}function M1(e,t,n){let r=Pt(Tt(e,t,n.palettes));return qi(r).length>0?Ji(r).filter((i)=>i.startsWith(" ✗")):[]}async function Em(e){let t=he(),n=Le(t),r=se(t),i=_e(t,n,!1),s=$m(e,t),o=Vo(t,s),a=o&&ks(o)?s:i.palettes.some((g)=>g.name===e)?e:s,u=Vo(t,a);if(!u||!ks(u)){let g=i.palettes.some((m)=>m.name===a);throw Error(g?`${a} is not one of yours — \`ttheme new <name> --from ${a}\` makes your own copy`:`no palette of yours called ${a} — \`ttheme new\` makes one`)}if(!k1())throw Error("edit opens your editor — run it in a terminal");let c=Bo(u,"utf8"),l=wm(m1(wm(b1(),"ttheme-edit-")),$1(u));w1(l,c);let h=[];try{for(;;){v1(l);let g=Bo(l,"utf8");if(g===c){console.log("Nothing changed");return}try{h=M1(a,g,n)}catch(m){console.log(`
446
- ${m.message}
447
- `);let b=await _t({message:`${a} cannot be read like this — edit it again?`});if(xe(b)||!b){console.log("Kept the old one");return}continue}ke(u,g);break}}finally{p1(bm(l),{recursive:!0,force:!0})}if(r.palettes.includes(a))ot(t,n,r);if(console.log(`Saved ${a}${r.palettes.includes(a)?" — new tabs and `ttheme use` wear it":` — \`ttheme add ${a}\` installs it`}`),h.length>0)console.log(`
448
- It misses the contrast gate:
449
- ${h.join(`
450
- `)}
451
- \`ttheme check --fix ${a}\` suggests colors that pass`);let f=_e(t,n).palettes.find((g)=>g.name===a),d=Pt(Tt(a,c,n.palettes));if(f&&r.palettes.includes(a))await Xt(t,[Un(f,d.pictures)],r.terminals)}function vm(e,t,n){return rr(e.palettes,e.palettes.some((r)=>r.name===t)?t:$m(t,n))}function Mm(e,t=!1){let n=he(),r=Le(n),i=se(n),s=vm(_e(n,r),e,n);if(console.log(`${s.name} · ${s.group}
452
- `),console.log(Ji(s).join(`
453
- `)),qi(s).length===0)return console.log(`
454
- Passes the gate`),0;let{theme:a,moves:u,left:c}=pm(yt(s));if(u.length===0)return console.log(`
455
- No color change fixes it — waive the rule in [contrast] with a reason, or pick other colors`),1;console.log(`
456
- ${c.length===0?"These colors pass":"These colors come closer"}:
457
- ${E1(u).join(`
458
- `)}`);let l=Vo(n,s.name);if(!l||!ks(l))return console.log(`
459
- \`ttheme new <name> --from ${s.name}\` makes a copy you can fix`),1;if(!t)return console.log(`
460
- \`ttheme check --fix ${s.name}\` writes them`),1;if(ke(l,Qd(Bo(l,"utf8"),a)),i.palettes.includes(s.name))ot(n,r,i);return console.log(`
461
- Wrote ${l}`),c.length===0?0:1}function Vo(e,t){let n=ye(t);return n&&nr(e,!1).some((r)=>r.id===n)?ju(e,t):void 0}function S1(e,t){let n=Vo(e,t.name),r=n&&ks(n)?Tt(t.name,Bo(n,"utf8"),[t]).waiveReason:void 0,i=ac(e,t.name)??t.pictures,{pictures:s,...o}=Wu(t,t.name,r);return{...o,...i?{pictures:i}:{}}}function Sm(e){let t=he(),n=Kd(S1(t,vm(_e(t,Le(t)),e,t)));if(console.log(n),process.stdout.isTTY)console.error(`
462
- Anyone with ttheme wears it with: ttheme add ${an}…`)}function Xo(e){console.log(`
463
- ${e} palettes installed — open a new tab, or reload your terminal config`)}function N1(e,t){return e.map((n)=>{if(n.startsWith(an))return n;let r=ye(n);if(r===void 0)return t===z?n:`${t}/${n}`;if(r!==t)throw Error(`${n} is not in ${t} — give its bare name, or leave --market out`);return n})}async function Im(e,t){let n=he(),r=t?N1(e,(await wc(n,t)).id):e,i=Le(n),s=[...new Set(r.map((l)=>l.startsWith(an)?km(n,l,i):l))],o=se(n),a=s.filter((l)=>o.palettes.includes(l)),u=s.filter((l)=>!o.palettes.includes(l));if(u.length===0){ot(n,i,o),console.log(`Already installed: ${a.join(", ")}`);return}let c={...o,palettes:[...o.palettes,...u]};hn(n,i,o,c);for(let l of u)console.log(` + ${l}`);await Xt(n,_e(n,i,!1).palettes.filter((l)=>u.includes(l.name)),c.terminals),Xo(c.palettes.length)}function Nm(e){let t=he(),n=Le(t),r=se(t),i=e.filter((a)=>r.palettes.includes(a)),s=e.filter((a)=>!r.palettes.includes(a));if(i.length===0)throw Error(`not installed: ${s.join(", ")} — \`ttheme list\` marks what is`);let o={...r,palettes:r.palettes.filter((a)=>!i.includes(a))};hn(t,n,r,o),Go(t,n,r.terminals,i);for(let a of i)console.log(` - ${a}`);if(Xo(o.palettes.length),s.length>0)return console.error(`ttheme remove: not installed: ${s.join(", ")}`),1;return 0}function Rm(e){let t=he(),n=Le(t),r=se(t);if(!r.palettes.includes(e))throw Error(`${e} is not installed — \`ttheme add ${e}\` first`);let{off:i,...s}=r,o=cn(),a=os({...s,startup:e},o);ot(t,n,a),Et(t,a);let u=ar(a,o);console.log(Om(e,a.terminals,u&&o.running()).join(`
464
- `))}function Fm(){let e=he(),t=se(e),n=ln(t);if(!n)throw Error("no palettes installed — `ttheme browse` picks some");if(!t.off){console.log(`Already on · ${n}`);return}let{off:r,...i}=t,s=hn(e,Le(e),t,i);console.log(Om(n,i.terminals,s).join(`
465
- `))}function Pm(){let e=he(),t=se(e);if(t.off){console.log("Already off");return}let n=hn(e,Le(e),t,{...t,off:!0}),r=ln(t);if(console.log(`Off · new tabs open in the terminal's own colors${r?` — \`ttheme on\` wears ${r} again`:""}`),n)console.log("iTerm2 new tabs open on your own profile once iTerm2 restarts")}function Om(e,t,n){let r=t.filter((s)=>s!=="iterm2"),i=r.length>0?[`Default ${e} · ${r.map((s)=>Jr[s]).join(", ")} open new tabs with it once their config reloads`]:[];if(t.includes("iterm2"))i.push(n?'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 ${e} · no terminal is wired to open with it — \`ttheme init\` wires one`]}function Tm(e,t){let n=new Map(t.palettes.map((r)=>[r.name,"market"]));for(let r of Mo(e,t.palettes,!1))n.set(r.name,"mine");return n}function Am(e,t=!1){let n=he(),r=Le(n),i=new Set(se(n).palettes),s=Tm(n,r),o=et(_e(n,r).palettes),a=Xn(e?Xd(o,e):o),u=(h)=>s.get(h)??"kept";if(t){let h=a.map((f)=>({name:f.name,group:f.group,...f.catalog?{catalog:f.catalog}:{},installed:i.has(f.name),source:u(f.name)}));console.log(JSON.stringify(h,null,2));return}let c=Math.max(...a.map((h)=>h.name.length),0),l={market:"",mine:" · yours",kept:" · in no market you added"};for(let h of a){let f=h.catalog?`${h.group} / ${h.catalog}`:h.group;console.log(` ${i.has(h.name)?"●":"○"} ${h.name.padEnd(c)} ${f}${l[u(h.name)]}`)}if(process.stdout.isTTY){let h=e?`${a.length} of ${o.length}`:`${o.length}`;console.log(`
466
- ${h} palettes — ${a.filter((f)=>i.has(f.name)).length} installed`)}}async function Hm(){let e=he(),t=_r(e);if(t.length===0)console.log("No markets to update — `ttheme market add official` brings the ttheme catalog back");let n=(f,d)=>`${be(f)}: ${d.message} — kept the copy from the last update`;for(let f of t.filter(Oe))try{console.log(` ${cm(e,f)}`)}catch(d){console.log(` ${n(f,d)}`)}let r=t.filter((f)=>!Oe(f)),i=new Set(r),s=Gn(),o=()=>s.set(`Updating ${[...i].map(be).join(", ")}${r.length>1?` · ${r.length-i.size}/${r.length}`:""}`);if(o(),await Promise.all(r.map(async(f)=>{let d;try{d=hc(await hs(e,f))}catch(g){d=n(f,g)}if(i.delete(f),i.size>0)o();else s.done();s.say(` ${d}`)})),s.done(),!I1(Rn(e)))return;let a=Le(e),u=se(e),c=Tm(e,a),l=u.palettes.filter((f)=>!c.has(f)),h=new Map(un(e).map((f)=>[f.name,f.pictures]));ot(e,a,u);for(let f of l)console.log(` ${f} left its market — ttheme keeps the copy you have`);await Xt(e,_e(e,a,!1).palettes.filter((f)=>u.palettes.includes(f.name)&&h.has(f.name)).map((f)=>Un(f,h.get(f.name))),u.terminals)}async function Ac(e,t,n,r=!1){let i=process.env.TTHEME_SORT==="series"?e.palettes:Xn(e.palettes),s=process.stdout.isTTY===!0&&!Vt(),o=s?await _o():new Map,a=new Nc({entries:i,scope:n,installed:t,required:r,color:!Vt(),fx:Qo(process.env.TTHEME_FX),onFocus:s?(c)=>process.stdout.write(Vr(c)):void 0}),u=await a.prompt();if(process.stdout.write(Uo(o)),xe(u))return;return e.palettes.filter((c)=>a.picked.has(c.name)).map((c)=>c.name)}function Hc(e,t,n,r){let i;try{i=ni(e,n)}catch{i=ht(n)?Nn(n):be(n)}let s=[];if(Oe(n))try{s=Tn(n,i,ti(e,z),!1)}catch{s=[]}else s=ti(e,n);return{source:n,id:i,shown:be(n),entries:s,auto:Fn(n,t.updates),status:kc(e,n,r)}}function xo(e){return e instanceof Error?e.message:String(e)}function F1(e,t,n,r){let i=new Map(r.map((o)=>[o.source,o.id])),s=[];for(let o of ze(t.markets)){let a=i.get(o)??be(o),u=n[o],c=cs(e,o);if(u&&(c===void 0||u.at>c))s.push({where:a,source:o,update:!0,message:`Update failed ${fs(u.at)}: ${u.error}`});if(o===z)try{Zt(Lm(At(e),"utf8"))}catch(l){s.push({where:a,source:o,message:`${be(At(e))}: ${xo(l)}`})}else if(ht(o))if(!R1(Ot(e,o)))s.push({where:a,source:o,message:"No copy of its index yet — `ttheme update` fetches it"});else try{An(e,o)}catch(l){s.push({where:a,source:o,message:`${be(Ot(e,o))}: ${xo(l)}`})}else try{let l=ft(Yt(o)),h=new Map;for(let f of On(o))try{let d=Wi(f,h);if(d)throw Error(d);h.set(f.slug,f),Tt(`${l}/${f.slug}`,Lm(f.path,"utf8"),ti(e,z))}catch(d){s.push({where:be(f.path),message:xo(d)})}}catch(l){s.push({where:a,message:xo(l)})}}return s}function P1(e,t,n,r){return{refresh:async(i)=>{if(Oe(i)){let o=Hc(e,t,i,fn());return{market:o,refreshed:{source:i,id:o.id,count:et(o.entries).length,change:{added:[],changed:[],gone:[]}}}}let s=await hs(e,i,cc);return{market:Hc(e,t,i,fn()),refreshed:s}},fetch:async(i)=>{if(Oe(i)){let o=ft(Yt(i));return{source:i,id:o,shown:be(i),entries:Tn(i,o,ti(e,z),!1),auto:!1,status:"read in place"}}let s=await ls(i,void 0,r);return n.set(i,s),{source:i,id:s.id,shown:be(i),entries:s.entries,auto:Fn(i,{}),status:"not added yet"}},search:(i)=>Ec(i,r)}}function O1(e,t,n){let r=[];for(let i of e.adds){let s=i.source!==z&&(e.auto[i.source]??i.auto);r.push(`Added ${i.id} · ${i.shown} — ${at(et(i.entries).length)}${s?", updating on its own":""}`)}for(let i of e.removes){let s=t.find((a)=>a.source===i)?.id??i;r.push(`Removed ${s} · ${be(i)}`);let o=n.filter((a)=>(ye(a)??z)===s);if(o.length>0)r.push($c(o))}for(let[i,s]of Object.entries(e.auto)){let o=t.find((a)=>a.source===i);if(o&&!e.removes.includes(i))r.push(`${o.id} ${s?"updates on its own now":"no longer updates on its own"}`)}return r}async function T1(e,t,n,r,i){let s=se(e),o=r.adds.length+r.removes.length+Object.keys(r.auto).length>0;for(let p of r.adds){let E=i.get(p.source);if(E)ei(e,E)}for(let p of r.removes)bc(e,p);let a=[...ze(s.markets).filter((p)=>!r.removes.includes(p)),...r.adds.map((p)=>p.source)],u=ds(s,a,{...s.updates,...r.auto});if(o)Et(e,u);let c=Le(e,!1),l=_e(e,c,!1).palettes.filter((p)=>r.picked.has(p.name)).map((p)=>p.name),h=s.palettes.filter((p)=>!l.includes(p)),f=l.filter((p)=>!s.palettes.includes(p));if(!o&&f.length===0&&h.length===0){await Wo(e,s,t,r.refreshed),console.log("Nothing changed");return}let d={...u,palettes:l};hn(e,c,s,d),Go(e,c,s.terminals,h);for(let p of O1(r,n,l))console.log(p);for(let p of f)console.log(` + ${p}`);for(let p of h)console.log(` - ${p}`);let g=new Map(t.map((p)=>[p.name,p.pictures])),m=new Set(r.refreshed.flatMap((p)=>[...p.change.changed,...p.change.gone])),b=_e(e,c,!1).palettes;if(await Xt(e,[...b.filter((p)=>f.includes(p.name)),...b.filter((p)=>l.includes(p.name)&&!f.includes(p.name)&&m.has(p.name)&&g.has(p.name)).map((p)=>Un(p,g.get(p.name)))],d.terminals),f.length>0||h.length>0)Xo(d.palettes.length)}async function Gm(){let e=he(),t=se(e),n=un(e),r=fn(),i=ze(t.markets).map((m)=>Hc(e,t,m,r)),s=new Set(i.flatMap((m)=>m.entries.map((b)=>b.name))),o=n.filter((m)=>t.palettes.includes(m.name)&&!s.has(m.name)),a=new Map,u=new AbortController,c=process.stdout.isTTY===!0&&!Vt(),l=c?await _o():new Map,h=dt(t),f=new Pc({markets:i,kept:o,installed:t.palettes,...h?{startup:h}:{},problems:F1(e,t,r,i),due:lc(e,t),io:P1(e,t,a,u.signal),...process.env.TTHEME_SORT==="series"?{}:{order:Xn},color:!Vt(),fx:Qo(process.env.TTHEME_FX),...c?{onFocus:(m)=>process.stdout.write(Vr(m))}:{}}),d=await f.prompt();process.stdout.write(Uo(l)),u.abort(),await f.idle();let g=f.result();for(let m of g.refreshed){let b=fc(m);if(b)console.log(b)}if(xe(d)){await Wo(e,se(e),n,g.refreshed),console.log("Nothing changed");return}await T1(e,n,i,g,a)}import{rmSync as Um}from"node:fs";import{basename as A1,join as ys}from"node:path";var _m=ys(import.meta.dirname,".."),H1=ys(_m,"themes"),Lc=ys(_m,"dist"),Do=[Yi,zi,Qi,is,Zi,ss,rs],L1=[Xu,Lu],iP=Do.map((e)=>e.id);async function ea({only:e}={}){if(typeof Bun>"u")throw Error("needs bun — run it from a checkout: bun src/bin.ts build");let t=e&&e.length>0?Do.filter((s)=>e.includes(s.id)):Do,n=ud(H1),r=hh(n);if(r.length>0){for(let s of r)console.error(` ✗ ${s.theme} [${s.rule}] ${s.detail}`);throw Error(`${r.length} contrast violation(s). Fix the palette, or waive the rule in its [contrast] section with a reason.`)}if(t.length===Do.length)Um(Lc,{recursive:!0,force:!0});else for(let s of t)Um(ys(Lc,s.id),{recursive:!0,force:!0});let i=0;for(let s of[...t,...L1]){let o=n.flatMap((c)=>s.emit?.(c)??[]),a=s.emitShared?.(n)??[];for(let c of[...o,...a])await Bun.write(ys(Lc,c.path),c.content),i++;let u=o.length>0?`${n.length} themes${s.limits?` (${s.limits})`:""}`:a.map((c)=>A1(c.path)).join(" ");console.log(` ${s.id.padEnd(16)} ${u}`)}console.log(`
467
- ${n.length} themes (${cd(n).length} in the new-tab rotation) -> ${i} files in dist/`)}import{spawn as ZE}from"node:child_process";import{createHash as Cp}from"node:crypto";import{existsSync as si,mkdirSync as Ss,mkdtempSync as zE,readFileSync as jp,rmSync as da,statSync as BE,writeFileSync as Is}from"node:fs";import{tmpdir as VE}from"node:os";import{dirname as ga,join as Gt}from"node:path";import{pathToFileURL as XE}from"node:url";import{execFile as G1}from"node:child_process";import{createHash as Jm}from"node:crypto";import{existsSync as U1,mkdtempSync as _1,readFileSync as ia,rmSync as C1,statSync as Km,writeFileSync as qm}from"node:fs";import{homedir as j1,tmpdir as W1}from"node:os";import{join as ta}from"node:path";import{fileURLToPath as J1}from"node:url";import{promisify as K1}from"node:util";var xt=K1(G1),na=67108864,q1=4096,_c=["image/png","image/jpeg","image/webp","image/gif","image/tiff","image/heic"],Q1=["text/uri-list","text/plain;charset=utf-8","text/plain"],Gc=[..._c,"text/uri-list","text/plain"];function Y1(e){try{return Km(e).isFile()}catch{return!1}}function Z1(e){let t=[],n="",r="",i=!1;for(let s=0;s<e.length;s++){let o=e[s];if(r==="'")if(o==="'")r="";else n+=o;else if(r==='"')if(o==='"')r="";else if(o==="\\"&&'"\\$`'.includes(e[s+1]??""))n+=e[++s];else n+=o;else if(o==="\\"&&s+1<e.length)n+=e[++s],i=!0;else if(o==="'"||o==='"')r=o,i=!0;else if(/\s/.test(o)){if(i)t.push(n);n="",i=!1}else n+=o,i=!0}if(i)t.push(n);return t}function Cm(e){if(/^file:\/\//i.test(e))try{return J1(e)}catch{return}if(e.startsWith("~/"))return ta(j1(),e.slice(2));return e.startsWith("/")?e:void 0}function sa(e,t=Y1){let n=[];for(let r of e.replace(/\r\n?/g,`
444
+ `)}`:" passes the gate"}`)}return cp(t,n,o),console.log(`
445
+ ${r} · ${ht(o.length)} → ${Sr(t,nn)}`),0}async function gp(e,t){switch(e){case void 0:SE();return;case"add":await EE(np(e,t));return;case"remove":vE(np(e,t));return;case"search":await IE(t);return;case"init":await FE(t);return;case"build":return RE(t);default:throw Error(`unknown market action ${e} — ${pE.join(", ")}, or none to list them`)}}function np(e,t){if(!t)throw Error(e==="add"?"market add takes a repository or a folder: ttheme market add alice/ttheme-dust":"market remove takes a market name — `ttheme market` lists them");return t}function mp(e,t){let n=Si(e,t);return`${n} — ${ht(Qn(t,n,Fa(e),!1).length)}, read in place`}function qs(e,t){return`${e}/${t}`}function pp(e){return ve(e.name)?ei(e.name):e.name}function Bs(e){return e.catalog!==void 0&&wp(e.group)?qs(e.group,e.catalog):void 0}function cl(e){if(e?.kind==="palette")return`palette ${e.entry.name}`;if(e?.kind==="group")return`group ${e.name}`;if(e?.kind==="catalog")return`catalog ${qs(e.group,e.name)}`;return e?.kind??""}function Ra(e,t){let n=t.toLowerCase();return[e.name,e.group,e.native??"",e.catalog??""].some((r)=>r.toLowerCase().includes(n))}function bp(e,t,n){let r=n.trim(),i=[],s=new Set,o=(a)=>({kind:"palette",entry:a});for(let a of e){if(a.default||s.has(a.group))continue;s.add(a.group);let u=e.filter((f)=>!f.default&&f.group===a.group),c=r?u.filter((f)=>Ra(f,r)):u;if(r&&c.length===0)continue;let l=r.length>0||t.has(a.group);if(i.push({kind:"group",name:a.group,native:a.native,lead:u.find((f)=>f.lead)??a,expanded:l,count:c.length}),!l)continue;let h=c.filter((f)=>Bs(f)!==void 0);for(let f of new Set(h.map((d)=>d.catalog))){let d=h.filter((p)=>p.catalog===f),g=r.length>0||t.has(qs(a.group,f));if(i.push({kind:"catalog",group:a.group,name:f,lead:d[0],expanded:g,count:d.length}),g)i.push(...d.map(o))}i.push(...c.filter((f)=>Bs(f)===void 0).map(o))}return i}function OE(e,t){let n=t.trim(),r=new Set(e.filter((i)=>!i.default&&(n===""||Ra(i,n))).map((i)=>i.group));return bp(e,new Set,"").filter((i)=>i.kind==="group"&&r.has(i.name))}function wp(e){return e.includes("@")}function ll(e,t,n,r){let i=n-1;if(i<0)return e;let s;if(!Number.isFinite(t))s=t>0?i:0;else if(t>0)s=e>=i?0:Math.min(i,e+t);else s=e<=0?i:Math.max(0,e+t);return r(s)?s+Math.sign(t):s}function hl(e,t){let n={home:Number.NEGATIVE_INFINITY,end:Number.POSITIVE_INFINITY,pageup:-t,pagedown:t};return e===void 0?void 0:n[e]}function TE(e){let t=e.findIndex((n)=>n.kind==="group"&&wp(n.name));return t>0&&e.slice(0,t).some((n)=>n.kind==="group")?[...e.slice(0,t),{kind:"rule"},...e.slice(t)]:e}function HE(e){let t=e.findIndex((n)=>n.kind==="palette");return t===-1?0:t}var tr="\x1B[0m",zs="\x1B[2m",Ys="\x1B[1m",Ir="\x1B[22m",fl="\x1B[36m",dl="\x1B[33m";function Oa(e){return e==="decode"||e==="glitch"?e:"typewriter"}class Qs{picked;scope;maxItems;named=[];series=[];color;onFocus;entries=[];seriesPad=0;namePad=0;expanded=new Set;rows=[];cursor=0;top=0;filter="";lastFocused="";constructor(e){this.picked=e.picked,this.scope=e.scope??"palette",this.maxItems=e.maxItems??12,this.color=e.color??!0,this.onFocus=e.onFocus,this.load(e.entries),this.rebuild("first")}load(e){this.entries=e,this.named=e.filter((t)=>!t.default),this.series=[...new Set(this.named.map((t)=>t.group))],this.seriesPad=Math.max(0,...this.series.map((t)=>t.length)),this.namePad=Math.max(0,...this.named.map((t)=>this.indent(t).length+pp(t).length))}indent(e){return Bs(e)===void 0?" ":" "}setEntries(e){this.load(e),this.rebuild("stay")}setFilter(e){if(e!==this.filter)this.filter=e,this.rebuild("keep")}focusedRow(){return this.rows[this.cursor]}refocus(){this.lastFocused="",this.sync()}members(e,t){let n=this.scope==="palette"?this.filter.trim():"";return this.named.filter((r)=>r.group===e&&(t===void 0||r.catalog===t)&&(n===""||Ra(r,n)))}everyone(e){return e.flatMap((t)=>t.kind==="group"?this.members(t.name):[])}pick(){let e=this.rows[this.cursor],t=e?.kind==="palette"?[e.entry.name]:e?.kind==="group"?this.members(e.name).map((r)=>r.name):e?.kind==="catalog"?this.members(e.group,e.name).map((r)=>r.name):e?.kind==="all"?this.everyone(this.rows).map((r)=>r.name):[];if(t.length===0)return;let n=t.some((r)=>!this.picked.has(r));for(let r of t)if(n)this.picked.add(r);else this.picked.delete(r)}pickedIn(e,t){return this.members(e,t).filter((n)=>this.picked.has(n.name)).length}pickedCount(){if(this.scope==="palette")return this.named.filter((e)=>this.picked.has(e.name)).length;return this.series.filter((e)=>this.members(e).every((t)=>this.picked.has(t.name))).length}total(){return this.scope==="series"?this.series.length:this.named.length}matched(){let e=this.filter.trim();if(this.scope==="series")return this.rows.filter((t)=>t.kind==="group").length;return e?this.named.filter((t)=>Ra(t,e)).length:this.named.length}sync(){let e=this.rows[this.cursor],t=e?.kind==="palette"?e.entry:e?.kind==="group"&&this.scope==="series"?e.lead:void 0;if(t&&t.name!==this.lastFocused)this.lastFocused=t.name,this.onFocus?.(t)}rebuild(e){let t=this.rows[this.cursor],n=this.scope==="series"?OE(this.entries,this.filter):bp(this.entries,this.expanded,this.filter);this.rows=n.length>0?TE([{kind:"all",count:this.allCount(n)},...n]):[];let r=n.length>0?this.rows.indexOf(n[HE(n)]):0;if(e==="first")this.cursor=r;else if(e==="keep"||e==="stay"){let i=cl(t),s=t?.kind==="palette"||e==="stay"?this.rows.findIndex((o)=>cl(o)===i):-1;this.cursor=s===-1?r:s}else if(this.cursor>=this.rows.length)this.cursor=Math.max(0,this.rows.length-1);this.sync()}allCount(e){return this.scope==="series"?e.length:this.everyone(e).length}move(e){this.cursor=ll(this.cursor,e,this.rows.length,(t)=>this.rows[t]?.kind==="rule"),this.sync()}toggle(e){if(this.expanded.has(e))this.expanded.delete(e);else this.expanded.add(e);this.rebuild("clamp")}climb(e,t){this.expanded.delete(e),this.rebuild("clamp"),this.cursor=Math.max(0,this.rows.findIndex((n)=>cl(n)===t)),this.sync()}fold(e){if(this.filter||this.scope==="series")return;let t=this.rows[this.cursor];if(t?.kind==="group"){if(e!==t.expanded)this.toggle(t.name)}else if(t?.kind==="catalog"){if(e!==t.expanded)this.toggle(qs(t.group,t.name));else if(!e)this.climb(t.group,`group ${t.group}`)}else if(t?.kind==="palette"&&!e&&!t.entry.default){let n=Bs(t.entry);if(n===void 0)this.climb(t.entry.group,`group ${t.entry.group}`);else this.climb(n,`catalog ${n}`)}}window(){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 e=this.rows.slice(this.top,this.top+this.maxItems);return{lines:e.map((t,n)=>this.renderRow(t,this.top+n===this.cursor)),below:this.rows.length-this.top-e.length}}renderRow(e,t){if(e.kind==="rule")return` ${this.color?`${zs}${"── Markets ──────────"}${tr}`:"── Markets ──────────"}`;let n=e.kind==="palette"?e.entry:e.kind==="all"?void 0:e.lead,r=this.color&&t&&n!==void 0,i=(m)=>this.color?`${zs}${m}${Ir}`:m,s=(m)=>this.color?`${Ys}${m}${Ir}`:m,o=(m)=>this.color?` ${Yh(sa(m),r?Yt(m.foreground):"\x1B[39m")}`:"",a=t?r?`${Yt(n.cursor)}▌\x1B[39m `:"▌ ":" ",u=(m)=>r?`${a}${Po(n.selection,n.foreground)} ${m} ${tr}`:`${a} ${m}`;if(e.kind==="all"){let m=this.everyone(this.rows).every(($)=>this.picked.has($.name))?"●":"○";return u(`${m} Select all ${i(`(${e.count})`)}`)}if(e.kind==="group"&&this.scope==="series"){let m=this.pickedIn(e.name)===e.count?"●":"○",$=`(${e.count})${e.native?` ${e.native}`:""}`;return u(`${m} ${s(e.name.padEnd(this.seriesPad))}${o(e.lead)}${this.color?" ":" "}${i($)}`)}let c=this.rows[this.cursor],l=(m,$)=>this.color&&c?.kind==="palette"&&m?`${Ys}${Yt(c.entry.cursor)}${$}${Ir}\x1B[39m`:s($);if(e.kind==="group"){let m=l(c?.kind==="palette"&&c.entry.group===e.name,e.name),$=e.native?` ${i(e.native)}`:"";return u(`${e.expanded?"▾":"▸"} ${m} ${i(`(${this.pickedIn(e.name)}/${e.count})`)}${$}`)}if(e.kind==="catalog"){let m=c?.kind==="palette"&&Bs(c.entry)===qs(e.group,e.name),$=i(`(${this.pickedIn(e.group,e.name)}/${e.count})`);return u(` ${e.expanded?"▾":"▸"} ${l(m,e.name)} ${$}`)}let h=e.entry,f=this.picked.has(h.name)?"●":"○",d=this.indent(h),g=pp(h),p=this.color?g.padEnd(this.namePad-d.length):g,b=t?s(p):p;return u(`${d}${f} ${b}${o(h)}`)}}function gl(e){let t=e.named[Math.floor(Math.random()*e.named.length)],n=e.series[Math.floor(Math.random()*e.series.length)];return t&&n?`${t.name} | ${n}`:""}class Ta{fx;make;redraw;roller;example="";step=0;seed=0;timer;constructor(e,t,n){this.fx=e,this.make=t,this.redraw=n,this.roll(),this.roller=setInterval(()=>{this.roll(),this.step=8,this.redraw()},3000),this.roller.unref?.()}stop(){clearInterval(this.roller),clearTimeout(this.timer)}roll(){let e=this.make();this.example=e.length>30?`${e.slice(0,29)}…`:e,this.seed=Math.floor(Math.random()*997)}text(){if(this.step===0)return this.example;if(!this.timer)this.timer=setTimeout(()=>{this.timer=void 0,this.step-=1,this.redraw()},60),this.timer.unref?.();let e=Math.floor(this.example.length*(8-this.step)/8);if(this.fx==="typewriter")return`${this.example.slice(0,e)}▏`;let t=this.fx==="decode"?"abcdefghijklmnopqrstuvwxyz":"▓▒░#*+=<>?/-_",n=this.fx==="decode"?(r)=>!/[a-z0-9]/i.test(r):(r)=>r===" ";return[...this.example].map((r,i)=>i+(i*7+this.seed)%3<e||n(r)?r:t[Math.floor(Math.random()*t.length)]??r).join("")}}class ml extends It{picked;list;scope;color;hint;lastInput="";constructor(e){super({render:()=>this.draw(),input:e.input,output:e.output,validate:e.required?()=>this.picked.size===0?`Pick at least one ${this.scope}`:void 0:void 0},!0);this.scope=e.scope??"palette",this.picked=new Set(e.installed??[]),this.color=e.color??!0,this.list=new Qs({entries:e.entries,picked:this.picked,scope:this.scope,...e.maxItems===void 0?{}:{maxItems:e.maxItems},color:this.color,...e.onFocus?{onFocus:e.onFocus}:{}}),this.hint=new Ta(e.fx??"typewriter",()=>gl(this.list),()=>this.output.emit("resize")),this.once("finalize",()=>this.hint.stop()),this.on("cursor",(t)=>{if(t==="up")this.list.move(-1);else if(t==="down")this.list.move(1);else if(t==="left")this.list.fold(!1);else if(t==="right")this.list.fold(!0)}),this.on("userInput",(t)=>{if(t!==this.lastInput)this.lastInput=t,this.list.setFilter(t)}),this.on("key",(t,n)=>{let r=hl(n?.name,this.list.maxItems);if(r!==void 0)this.list.move(r);else if(n?.name==="space")this.list.pick()})}_isActionKey(e){return e==="\t"||e===" "}draw(){let e=(d)=>this.color?`${zs}${d}${tr}`:d,t=(d)=>this.color?`${fl}${d}${tr}`:d,n=this.scope==="series"?"Series":"Catalog";if(this.state==="submit")return`${e("◇")} ${n} ${e(`· ${this.list.pickedCount()} picked`)}`;if(this.state==="cancel")return`${e(`◇ ${n} · cancelled`)}`;let r=`${t("◆")} ${n} ${e(`(${this.list.matched()}/${this.list.total()} · ${this.list.pickedCount()} picked)`)}`,i=this.hint.text(),s=`${t("│")} ${this.userInput?`${this.userInput}_`:e(`Search…${i?` e.g. ${i}`:""}`)}`,{lines:o,below:a}=this.list.window(),u=o.length>0?o.map((d)=>`${t("│")} ${d}`):[`${t("│")} ${e(`No ${this.scope==="series"?"series":"palettes"} match '${this.userInput}'`)}`];while(u.length<this.list.maxItems)u.push(t("│"));let c=a>0?`${t("│")} ${e(`↓ ${a} more`)}`:t("│"),l=this.scope==="series"?"":" · ←→ fold",h=this.scope==="series"?"continue":"install",f=this.state==="error"?`${t("└")} ${this.color?`${dl}${this.error}${tr}`:this.error}`:`${t("└")} ${e(`↑↓ move${l} · space pick · type to filter · enter ${h} · esc cancel`)}`;return[r,s,...u,c,f].join(`
446
+ `)}}var Zs=[{tab:"catalog",title:"Catalog"},{tab:"installed",title:"Installed"},{tab:"markets",title:"Markets"},{tab:"errors",title:"Errors"}],pl=34,AE=72,LE=94,bl={title:"",lines:[],brief:""};function Ha(e){let t=e.trim();if(t!==D&&!t.includes("/")&&!t.startsWith("~"))return;try{return zn(t)}catch{return}}function xE(e){return e.charAt(0).toUpperCase()+e.slice(1)}class wl extends It{picked;tab="catalog";filters={catalog:"",installed:"",markets:"",errors:""};cursor={markets:0,errors:0};top={markets:0,errors:0};adds=new Map;removes=new Set;want=new Map;busy=new Map;failed=new Map;refreshed=[];inflight=new Set;markets;problems;kept;installed;startup;io;order;color;maxItems;paint;catalog;mine;hint;asking;repos;searching=!1;searchError;lastInput="";constructor(e){super({render:()=>this.draw(),input:e.input,output:e.output},!0);this.markets=e.markets,this.problems=e.problems,this.kept=e.kept,this.installed=new Set(e.installed),this.startup=e.startup,this.io=e.io,this.order=e.order??((n)=>n),this.color=e.color??!0,this.maxItems=e.maxItems??12,this.paint=e.onFocus,this.picked=new Set(e.installed);let t=this.entries();this.catalog=new Qs({entries:t,picked:this.picked,color:this.color,maxItems:this.maxItems,onFocus:(n)=>this.focus("catalog",n)}),this.mine=new Qs({entries:this.mineOf(t),picked:this.picked,color:this.color,maxItems:this.maxItems,onFocus:(n)=>this.focus("installed",n)}),this.hint=new Ta(e.fx??"typewriter",()=>gl(this.tab==="installed"?this.mine:this.catalog),()=>this.redraw()),this.once("finalize",()=>this.hint.stop()),this.on("cursor",(n)=>{if(this.asking)return;if(n==="up"||n==="down")this.move(n==="up"?-1:1);else if(n==="left"||n==="right")this.side(n==="right")}),this.on("userInput",(n)=>{if(n!==this.lastInput)this.lastInput=n,this.filters[this.tab]=n,this.list()?.setFilter(n)}),this.on("key",(n,r)=>this.key(n,r));for(let n of e.due)this.update(n)}_isActionKey(e){return e==="\t"||e===" "||this.asking!==void 0&&e!==void 0}_shouldSubmit(){return this.asking===void 0}async idle(){await Promise.allSettled([...this.inflight])}result(){let e=new Set(this.entries().map((t)=>t.name));return{picked:new Set([...this.picked].filter((t)=>e.has(t))),adds:[...this.adds.values()],removes:[...this.removes],auto:Object.fromEntries(this.want),refreshed:this.refreshed}}key(e,t){if(this.asking){if(t?.name==="escape")this.asking=void 0,Object.assign(t,{name:"answered",sequence:""});else if(e&&/^[yn]$/i.test(e))this.answer(e.toLowerCase()==="y");return}let n=hl(t?.name,this.maxItems);if(n!==void 0)this.move(n);else if(t?.name==="tab")this.switchTab(t.shift?-1:1);else if(t?.name==="space")this.activate();else if(t?.ctrl&&t.name==="r"){let r=this.tab==="markets"?this.marketRow():void 0;if(r?.kind==="market"&&!this.adds.has(r.market.source))this.update(r.market.source)}}redraw(){if(this.state==="active"||this.state==="error")this.output.emit("resize")}focus(e,t){if(this.tab===e&&this.state!=="submit"&&this.state!=="cancel")this.paint?.(t)}track(e){this.inflight.add(e);let t=()=>this.inflight.delete(e);return e.then(t,t),e}list(){return this.tab==="catalog"?this.catalog:this.tab==="installed"?this.mine:void 0}active(){return[...this.markets.filter((e)=>!this.removes.has(e.source)),...this.adds.values()]}entries(){let e=this.active().flatMap((i)=>i.entries),t=new Set(e.map((i)=>i.name)),n=new Map,r=this.markets.filter((i)=>this.removes.has(i.source)).flatMap((i)=>i.entries);for(let i of[...this.kept,...r])if(this.installed.has(i.name)&&!t.has(i.name))n.set(i.name,i);return this.order([...e,...n.values()])}mineOf(e){return e.filter((t)=>this.installed.has(t.name))}reload(){let e=this.entries();this.catalog.setEntries(e),this.mine.setEntries(this.mineOf(e))}switchTab(e){let t=Zs.findIndex((i)=>i.tab===this.tab),n=Zs[(t+e+Zs.length)%Zs.length]?.tab??"catalog",r=this.filters[n];this.tab=n,this._clearUserInput(),this._setUserInput(r,!0),this.lastInput=r,this.list()?.refocus()}move(e){let t=this.list();if(t){t.move(e);return}let n=this.tab==="markets"?"markets":"errors",r=n==="markets"?this.marketRows().map((i)=>i.kind==="rule"):this.problemRows().map(()=>!1);this.cursor[n]=ll(this.cursor[n],e,r.length,(i)=>r[i]===!0)}side(e){let t=this.list();if(t){t.fold(e);return}let n=this.tab==="markets"?this.marketRow():void 0;if(n?.kind==="market"&&!Te(n.market.source))if(e===n.market.auto)this.want.delete(n.market.source);else this.want.set(n.market.source,e)}activate(){let e=this.list();if(e){e.pick();return}let t=this.tab==="markets"?this.marketRow():void 0;if(t?.kind==="market")this.toggleMarket(t.market);else if(t?.kind==="add")this.fetch(t.source);else if(t?.kind==="repo"){let n=this.known(t.source),r=this.marketRows().findIndex((i)=>i.kind==="market"&&i.market===n);if(n&&r>=0)this.cursor.markets=r;else if(!n)this.fetch(t.source)}else if(t?.kind==="find")this.search()}toggleMarket(e){if(this.adds.has(e.source))this.adds.delete(e.source),this.want.delete(e.source);else if(this.removes.has(e.source))this.removes.delete(e.source);else this.removes.add(e.source);this.reload()}known(e){return[...this.markets,...this.adds.values()].find((t)=>ai(t.source,e))}fetch(e){if(this.busy.has(e))return;this.failed.delete(e),this.busy.set(e,"Fetching…"),this.track(this.io.fetch(e)).then((t)=>{this.busy.delete(e);let n=this.active().find((r)=>r.id===t.id);if(n)this.failed.set(e,`${t.id} already names the market at ${n.shown}`);else if(Te(e)||e===D)this.stage(t,t.auto);else this.asking=t;this.redraw()},(t)=>{this.busy.delete(e),this.failed.set(e,t.message),this.redraw()})}answer(e){let t=this.asking;if(this.asking=void 0,t)this.stage(t,e)}stage(e,t){if(this.adds.set(e.source,e),t===e.auto)this.want.delete(e.source);else this.want.set(e.source,t);this.reload(),this.cursor.markets=Math.max(0,this.marketRows().findIndex((n)=>n.kind==="market"&&n.market.source===e.source))}update(e){if(this.busy.has(e))return;this.failed.delete(e),this.busy.set(e,"Updating…"),this.track(this.io.refresh(e)).then(({market:t,refreshed:n})=>{this.busy.delete(e),this.markets=this.markets.map((r)=>r.source===e?t:r),this.problems=this.problems.filter((r)=>r.source!==e),this.refreshed.push(n),this.reload(),this.redraw()},(t)=>{this.busy.delete(e),this.failed.set(e,`Update failed: ${t.message}`),this.redraw()})}search(){if(this.searching)return;this.searching=!0,this.searchError=void 0;let e=this.filters.markets.trim();this.track(this.io.search(e&&!Ha(e)?e:void 0)).then((t)=>{this.searching=!1,this.repos=t,this.redraw()},(t)=>{this.searching=!1,this.searchError=t.message,this.redraw()})}marketRows(){let e=this.filters.markets.trim().toLowerCase(),t=(...o)=>e===""||o.some((a)=>a.toLowerCase().includes(e)),n=[...this.markets,...this.adds.values()],r=n.filter((o)=>t(o.id,o.shown,o.source)).map((o)=>({kind:"market",market:o})),i=Ha(this.filters.markets);if(i&&!n.some((o)=>ai(o.source,i)))r.push({kind:"add",source:i});r.push({kind:"find"});let s=(this.repos??[]).map((o)=>({repo:o,source:al(o)})).filter(({repo:o,source:a})=>t(a,o.description??""));if(s.length>0)r.push({kind:"rule"},...s.map(({repo:o,source:a})=>({kind:"repo",repo:o,source:a})));return r}marketRow(){let e=this.marketRows();return e[Math.min(this.cursor.markets,e.length-1)]}problemList(){let e=new Map([...this.markets,...this.adds.values()].map((t)=>[t.source,t.id]));return[...this.problems.filter((t)=>!(t.update&&t.source&&this.failed.has(t.source))),...[...this.failed].map(([t,n])=>({where:e.get(t)??t,message:n,source:t}))]}problemRows(){let e=this.filters.errors.trim().toLowerCase();return this.problemList().filter((t)=>e===""||`${t.where} ${t.message}`.toLowerCase().includes(e))}windowOf(e,t,n,r=()=>!1){let i=Math.min(this.cursor[t],Math.max(0,e.length-1));if(r(e[i]))i-=1;this.cursor[t]=i;let s=Math.min(this.top[t],i);if(i>=s+this.maxItems)s=i-this.maxItems+1;s=Math.max(0,Math.min(s,e.length-this.maxItems)),this.top[t]=s;let o=e.slice(s,s+this.maxItems);return{lines:o.map((a,u)=>n(a,s+u===i)),below:e.length-s-o.length}}dim(e){return this.color?`${zs}${e}${Ir}`:e}bold(e){return this.color?`${Ys}${e}${Ir}`:e}warn(e){return this.color?`${dl}${e}\x1B[39m`:e}lit(e,t,n){if(t&&this.color&&e)return`${Yt(e.cursor)}▌\x1B[39m ${Po(e.selection,e.foreground)} ${n} ${tr}`;return`${t?"▌ ":" "} ${n}`}status(e){return this.adds.has(e.source)?"Will add":this.removes.has(e.source)?"Will remove":this.busy.get(e.source)??(this.failed.has(e.source)||e.status.startsWith("update failed")?"Update failed":"")}marketLine(e,t){if(e.kind==="rule")return` ${this.dim("── On GitHub ──────────")}`;if(e.kind==="market"){let i=e.market,s=this.status(i),o=this.removes.has(i.source)?"○":"●",a=t?this.bold(i.id):i.id;return this.lit(i.entries.find((u)=>!u.default),t,`${o} ${a}${s?` ${this.dim(s)}`:""}`)}if(e.kind==="add"){let i=this.busy.get(e.source);return this.lit(void 0,t,`+ Add ${ke(e.source)}${i?` ${this.dim(i)}`:""}`)}if(e.kind==="find"){let i=this.filters.markets.trim(),s=this.searching?"Searching GitHub…":i&&!Ha(i)?`Find "${i}" on GitHub`:"Find markets on GitHub";return this.lit(void 0,t,`⌕ ${s}`)}let n=this.busy.get(e.source),r=this.known(e.source)?"●":"○";return this.lit(void 0,t,`${r} ${e.source} ${this.dim(`★${e.repo.stargazers_count}`)}${n?` ${this.dim(n)}`:""}`)}problemLine(e,t){return this.lit(void 0,t,`${this.warn("✗")} ${e.where} ${this.dim(e.message)}`)}body(){let e=this.list();if(e){let n=this.filters[this.tab];return{...e.window(),empty:n?`No palettes match '${n}'`:this.tab==="installed"?"Nothing installed yet":"No palettes"}}if(this.tab==="markets")return{...this.windowOf(this.marketRows(),"markets",(n,r)=>this.marketLine(n,r),(n)=>n?.kind==="rule"),empty:""};let t=this.filters.errors;return{...this.windowOf(this.problemRows(),"errors",(n,r)=>this.problemLine(n,r)),empty:t?`No problems match '${t}'`:"No problems"}}changes(){return this.adds.size+this.removes.size+this.want.size}counts(){let e=[...this.busy.values()].includes("Updating…")?"Updating… · ":"",t=this.list();if(t)return`${e}${t.matched()}/${t.total()} · ${t.pickedCount()} picked`;if(this.tab==="markets"){let n=this.markets.length+this.adds.size,r=this.marketRows().filter((s)=>s.kind==="market").length,i=this.changes();return`${e}${r}/${n} markets${i>0?` · ${i} to apply`:""}`}return`${this.problemRows().length}/${this.problemList().length}`}searchText(){if(this.userInput)return`${this.userInput}_`;if(this.tab==="markets")return this.dim("Search… or add one: owner/repo");let e=this.tab==="errors"?"":this.hint.text();return this.dim(`Search…${e?` e.g. ${e}`:""}`)}tabBar(){return Zs.map(({tab:e,title:t})=>{let n=e==="errors"?this.problemList().length:0,r=n>0?`${t} ${n}`:t;if(!this.color)return e===this.tab?`[${r}]`:` ${r} `;return e===this.tab?this.bold(r):this.dim(r)}).join(this.color?" ":" ")}sourceOf(e){let t=this.active().find((n)=>n.entries.some((r)=>r.name===e.name));if(!t)return"In no market you added";return t.source===D?"The ttheme catalog":t.shown}paletteState(e){let t=this.picked.has(e.name),n=this.installed.has(e.name),r=t&&n?"Installed":t?"Will install":n?"Will remove":"Not installed";return this.startup===e.name?`${r} · Default`:r}paletteDetail(e,t){if(!e||e.kind==="rule")return bl;if(e.kind==="all")return{title:this.bold("Select all"),lines:["space picks every palette shown"],brief:""};if(e.kind==="group"){let c=this.entries().filter((f)=>f.group===e.name&&!f.default),l=this.sourceOf(e.lead),h=`${ht(c.length)} · ${c.filter((f)=>this.installed.has(f.name)).length} installed`;return{title:this.bold(e.name),lines:[...e.native?Qe(e.native,t).map((f)=>this.dim(f)):[],...Qe(l,t),h],brief:`${l} · ${h}`}}if(e.kind==="catalog"){let c=this.entries().filter((f)=>f.group===e.group&&f.catalog===e.name),l=this.sourceOf(e.lead),h=`${ht(c.length)} · ${c.filter((f)=>this.installed.has(f.name)).length} installed`;return{title:this.bold(e.name),lines:[e.group,...Qe(l,t),h],brief:`${e.group} · ${h}`}}let n=e.entry,r=this.sourceOf(n),i=ks(n),s=`Gate ${gt.length-i.length}/${gt.length}`,o=n.pictures?.length??0,a=[...o>0?[`${o} picture${o===1?"":"s"}`]:[],...n.base?[`Base ${n.base}`]:[]].join(" · "),u=ve(n.name)?n.catalog?[n.catalog]:[]:[n.group,...n.native?[this.dim(n.native)]:[]];return{title:this.color?`${Ys}${Yt(n.cursor)}${n.name}${Ir}\x1B[39m`:n.name,lines:[...Qe(r,t),...u,this.paletteState(n),"",i.length===0?`${s} · passes`:s,...i.flatMap((c)=>Qe(c,t-2).map((l,h)=>`${h===0?this.warn("✗"):" "} ${l}`)),...a?["",a]:[]],brief:[r,s,...a?[a]:[],this.paletteState(n)].join(" · ")}}marketDetail(e,t){if(!e||e.kind==="rule")return bl;if(e.kind==="market"){let i=e.market,s=i.source===D?"The ttheme catalog":i.shown,o=i.entries.filter((d)=>!d.default),a=o.filter((d)=>this.installed.has(d.name)).map((d)=>d.name),u=`${ht(o.length)} · ${a.length} installed`,c=Te(i.source)?"Read in place":`Auto-update ${this.want.get(i.source)??i.auto?"on":"off"}`,l=this.busy.get(i.source)??xE(i.status),h=this.failed.get(i.source),f=this.adds.has(i.source)?["Will add"]:this.removes.has(i.source)?[a.length>0?`Will remove — ${a.join(", ")} stay${a.length===1?"s":""} installed`:"Will remove"]:this.want.has(i.source)?[`Auto-update turns ${this.want.get(i.source)?"on":"off"}`]:[];return{title:this.bold(i.id),lines:[...Qe(s,t),u,"",Te(i.source)?c:`${c} ${this.dim("←→")}`,...Te(i.source)?[]:[l],...h?Qe(h,t).map((d)=>this.warn(d)):[],...f.length>0?["",...f.flatMap((d)=>Qe(d,t))]:[]],brief:[s,c,...f,...Te(i.source)?[]:[l]].join(" · ")}}if(e.kind==="add"){let i=this.busy.get(e.source)??this.failed.get(e.source)??"space fetches its index";return{title:this.bold(ke(e.source)),lines:["Not added","",...Qe(i,t)],brief:i}}if(e.kind==="find"){let i=this.filters.markets.trim(),s=this.searchError??(this.searching?"Searching…":this.repos?`${this.repos.length} found`:"space searches GitHub");return{title:this.bold("GitHub"),lines:[...Qe(`Repositories with the ${si} topic`,t),...i&&!Ha(i)?[`Matching "${i}"`]:[],"",...Qe(s,t)],brief:s}}let r=this.known(e.source)?"Added":this.busy.get(e.source)??this.failed.get(e.source)??"space adds it";return{title:this.bold(e.source),lines:[`★ ${e.repo.stargazers_count}`,...Qe(e.repo.description??"",t),"",...Qe(r,t)],brief:r}}detail(e){let t=this.list();if(t)return this.paletteDetail(t.focusedRow(),e);if(this.tab==="markets")return this.marketDetail(this.marketRow(),e);let n=this.problemRows(),r=n[Math.min(this.cursor.errors,n.length-1)];return r?{title:this.bold(r.where),lines:Qe(r.message,e),brief:r.message}:bl}footer(e,t){if(this.asking)return`${e("└")} Update ${this.asking.id} on its own when its author changes it? ${this.dim("y yes · n no · esc back")}`;let n={catalog:["tab switch","↑↓ move","←→ fold","space pick",t?"type to filter":""],installed:["tab switch","↑↓ move","←→ fold","space pick",t?"type to filter":""],markets:["tab switch","space add/remove","←→ auto-update",t?"ctrl+r update":""],errors:["tab switch","↑↓ move","type to filter"]}[this.tab];return`${e("└")} ${this.dim([...n.filter(Boolean),"enter apply","esc cancel"].join(" · "))}`}summary(){let e=this.changes();return`${this.catalog.pickedCount()} picked${e>0?` · ${e} market change${e===1?"":"s"}`:""}`}columns(){return this.output.columns??100}draw(){let e=(h)=>this.color?`${fl}${h}${tr}`:h;if(this.state==="submit")return`${this.dim("◇")} Browse ${this.dim(`· ${this.summary()}`)}`;if(this.state==="cancel")return this.dim("◇ Browse · cancelled");let t=this.columns(),n=t>=LE,r=n?Math.min(t-pl-4,AE):t-1,{lines:i,below:s,empty:o}=this.body(),a=i.length>0?i.map((h)=>`${e("│")} ${h}`):[`${e("│")} ${this.dim(o)}`];while(a.length<this.maxItems)a.push(e("│"));let u=[`${e("◆")} ${this.tabBar()}`,cn(`${e("│")} ${this.searchText()}`,this.dim(this.counts()),r),...a,s>0?`${e("│")} ${this.dim(`↓ ${s} more`)}`:e("│")],c=this.detail(n?pl:r-2);return[...n?u.map((h,f)=>`${De(h,r)} ${this.dim("│")} ${De(f===0?c.title:c.lines[f-1]??"",pl,!1)}`):[...u.map((h)=>De(h,r,!1)),De(`${e("│")} ${this.dim(c.brief)}`,r,!1)],De(this.footer(e,n),t-1,!1)].join(`
447
+ `)}}import{existsSync as wS}from"node:fs";import{existsSync as fo,mkdirSync as lS,readFileSync as zl}from"node:fs";import{dirname as hS}from"node:path";import{execFile as CE}from"node:child_process";import{createHash as Ep}from"node:crypto";import{existsSync as _E,mkdtempSync as GE,readFileSync as Ca,rmSync as UE,statSync as vp,writeFileSync as Mp}from"node:fs";import{homedir as jE,tmpdir as WE}from"node:os";import{join as Aa}from"node:path";import{fileURLToPath as KE}from"node:url";import{promisify as JE}from"node:util";var an=JE(CE),La=67108864,BE=4096,yl=["image/png","image/jpeg","image/webp","image/gif","image/tiff","image/heic"],qE=["text/uri-list","text/plain;charset=utf-8","text/plain"],$l=[...yl,"text/uri-list","text/plain"];function zE(e){try{return vp(e).isFile()}catch{return!1}}function YE(e){let t=[],n="",r="",i=!1;for(let s=0;s<e.length;s++){let o=e[s];if(r==="'")if(o==="'")r="";else n+=o;else if(r==='"')if(o==='"')r="";else if(o==="\\"&&'"\\$`'.includes(e[s+1]??""))n+=e[++s];else n+=o;else if(o==="\\"&&s+1<e.length)n+=e[++s],i=!0;else if(o==="'"||o==='"')r=o,i=!0;else if(/\s/.test(o)){if(i)t.push(n);n="",i=!1}else n+=o,i=!0}if(i)t.push(n);return t}function $p(e){if(/^file:\/\//i.test(e))try{return KE(e)}catch{return}if(e.startsWith("~/"))return Aa(jE(),e.slice(2));return e.startsWith("/")?e:void 0}function Ii(e,t=zE){let n=[];for(let r of e.replace(/\r\n?/g,`
468
448
  `).split(`
469
- `)){let i=Cm(r.trim());if(i&&t(i)){n.push(i);continue}for(let s of Z1(r)){if(/^https?:\/\/\S+$/i.test(s)){n.push(s);continue}let o=Cm(s);if(o&&t(o))n.push(o)}}return n}function z1(e){if(e[0]!==255||e[1]!==216)return null;let t=2;while(t+9<e.length){if(e[t]!==255){t++;continue}let n=e[t+1];if(n===255){t++;continue}let r=e[t+2]<<8|e[t+3];if(n>=192&&n<=207&&n!==196&&n!==200&&n!==204)return{height:e[t+5]<<8|e[t+6],width:e[t+7]<<8|e[t+8]};t+=2+r}return null}function jm(e){let t=Fr(e)?yn(e):z1(e);if(!t)return;return{ext:Fr(e)?"png":"jpg",width:t.width,height:t.height}}async function ra(e,t){let n=jm(e);if(n&&n.width*n.height<=kt)return{bytes:e,...n,source:t};if(process.platform!=="darwin")throw Error(n?`${n.width}×${n.height} is over ${kt/1e6} megapixels`:"only PNG and JPEG pictures work here");let r=_1(ta(W1(),"ttheme-attach-"));try{let i=ta(r,"in"),s=ta(r,"out.png");qm(i,e);let o=!n||n.width*n.height>kt?["--resampleHeightWidthMax",String(q1)]:[];await xt("sips",["-s","format","png",...o,i,"--out",s]).catch(()=>{throw Error("that is not a picture macOS can read")});let a=new Uint8Array(ia(s)),u=jm(a);if(!u)throw Error("that is not a picture macOS can read");return{bytes:a,...u,source:t}}finally{C1(r,{recursive:!0,force:!0})}}async function Cc(e,t){if(/^https?:\/\//i.test(e)){let n=await fetch(e,{headers:{"User-Agent":mu},signal:t});if(!n.ok)throw Error(`${new URL(e).host} answered ${n.status}`);if(Number(n.headers.get("content-length")??0)>na)throw Error("that picture is over 64 MB");let r=new Uint8Array(await n.arrayBuffer());if(/^text\/html/i.test(n.headers.get("content-type")??""))throw Error(`${new URL(e).host} sent a web page, not a picture — copy the image address instead`);return ra(r,e)}if(Km(e).size>na)throw Error("that picture is over 64 MB");return ra(new Uint8Array(ia(e)),e)}var Qm=new Map,oa={key:"local",name:"local",origin:"file://",moved:!1,cutouts:"",best:"",tagBudget:0,vouched:!0,scored:!1,ansi:7,ratings:{safe:new Set,questionable:new Set,explicit:new Set},rate:()=>"",narrow:()=>[],postsUrl:()=>"",countUrl:()=>"",postUrl:()=>"",pageUrl:(e)=>Qm.get(e)??"",parse:()=>[],count:()=>0};function Ym(e){if(/^https?:\/\//i.test(e))return"";return e.split("/").pop()??e}function Zm(e,t){Qm.set(e,t)}function zm(e){return Number.parseInt(Jm("sha1").update(e).digest("hex").slice(0,8),16)%nn}var B1=`ObjC.import('AppKit')
449
+ `)){let i=$p(r.trim());if(i&&t(i)){n.push(i);continue}for(let s of YE(r)){if(/^https?:\/\/\S+$/i.test(s)){n.push(s);continue}let o=$p(s);if(o&&t(o))n.push(o)}}return n}function QE(e){if(e[0]!==255||e[1]!==216)return null;let t=2;while(t+9<e.length){if(e[t]!==255){t++;continue}let n=e[t+1];if(n===255){t++;continue}let r=e[t+2]<<8|e[t+3];if(n>=192&&n<=207&&n!==196&&n!==200&&n!==204)return{height:e[t+5]<<8|e[t+6],width:e[t+7]<<8|e[t+8]};t+=2+r}return null}function kp(e){let t=zr(e)?xn(e):QE(e);if(!t)return;return{ext:zr(e)?"png":"jpg",width:t.width,height:t.height}}async function xa(e,t){let n=kp(e);if(n&&n.width*n.height<=pt)return{bytes:e,...n,source:t};if(process.platform!=="darwin")throw Error(n?`${n.width}×${n.height} is over ${pt/1e6} megapixels`:"only PNG and JPEG pictures work here");let r=GE(Aa(WE(),"ttheme-attach-"));try{let i=Aa(r,"in"),s=Aa(r,"out.png");Mp(i,e);let o=!n||n.width*n.height>pt?["--resampleHeightWidthMax",String(BE)]:[];await an("sips",["-s","format","png",...o,i,"--out",s]).catch(()=>{throw Error("that is not a picture macOS can read")});let a=new Uint8Array(Ca(s)),u=kp(a);if(!u)throw Error("that is not a picture macOS can read");return{bytes:a,...u,source:t}}finally{UE(r,{recursive:!0,force:!0})}}async function El(e,t){if(/^https?:\/\//i.test(e)){let n=await fetch(e,{headers:{"User-Agent":ic},signal:t});if(!n.ok)throw Error(`${new URL(e).host} answered ${n.status}`);if(Number(n.headers.get("content-length")??0)>La)throw Error("that picture is over 64 MB");let r=new Uint8Array(await n.arrayBuffer());if(/^text\/html/i.test(n.headers.get("content-type")??""))throw Error(`${new URL(e).host} sent a web page, not a picture — copy the image address instead`);return xa(r,e)}if(vp(e).size>La)throw Error("that picture is over 64 MB");return xa(new Uint8Array(Ca(e)),e)}var Sp=new Map,Nr={key:"local",name:"local",origin:"file://",moved:!1,cutouts:"",best:"",tagBudget:0,vouched:!0,scored:!1,ansi:7,ratings:{safe:new Set,questionable:new Set,explicit:new Set},rate:()=>"",narrow:()=>[],postsUrl:()=>"",countUrl:()=>"",postUrl:()=>"",pageUrl:(e)=>Sp.get(e)??"",parse:()=>[],count:()=>0};function Ip(e){if(/^https?:\/\//i.test(e))return"";return e.split("/").pop()??e}function Np(e,t){Sp.set(e,t)}function Pp(e){return Number.parseInt(Ep("sha1").update(e).digest("hex").slice(0,8),16)%jn}var ZE=`ObjC.import('AppKit')
470
450
  function run(argv) {
471
451
  const pb = $.NSPasteboard.generalPasteboard
472
452
  const files = pb.readObjectsForClassesOptions($([$.NSURL]), $({ NSPasteboardURLReadingFileURLsOnlyKey: true }))
@@ -491,16 +471,16 @@ function run(argv) {
491
471
  if (web && web.count > 0) return web.objectAtIndex(0).absoluteString.js
492
472
  const text = pb.stringForType('public.utf8-plain-text')
493
473
  return text && !text.isNil() ? text.js : ''
494
- }`,V1=`Add-Type -AssemblyName System.Windows.Forms,System.Drawing
474
+ }`,VE=`Add-Type -AssemblyName System.Windows.Forms,System.Drawing
495
475
  $c = [Windows.Forms.Clipboard]
496
476
  $f = $c::GetFileDropList(); if ($f.Count) { $f; exit }
497
477
  $p = Join-Path $env:TEMP 'ttheme-clipboard.png'
498
478
  $s = $c::GetData('PNG'); if ($s -is [IO.MemoryStream]) { [IO.File]::WriteAllBytes($p, $s.ToArray()); $p; exit }
499
479
  $i = $c::GetImage(); if ($i) { $i.Save($p, [Drawing.Imaging.ImageFormat]::Png); $p; exit }
500
- $c::GetText()`;function Bm(){if(process.platform!=="linux")return!1;try{return/microsoft/i.test(ia("/proc/version","utf8"))}catch{return!1}}async function X1(e){let t=Boolean(process.env.WAYLAND_DISPLAY),n=t?["wl-paste",["--list-types"]]:["xclip",["-selection","clipboard","-t","TARGETS","-o"]],r=(await xt(n[0],n[1])).stdout.split(`
501
- `).map((o)=>o.trim()),i=(o)=>t?xt("wl-paste",["--no-newline","--type",o],{encoding:"buffer",maxBuffer:na}):xt("xclip",["-selection","clipboard","-t",o,"-o"],{encoding:"buffer",maxBuffer:na});if(r.includes("text/uri-list"))return{text:(await i("text/uri-list")).stdout.toString("utf8")};let s=_c.find((o)=>r.includes(o));if(s)return qm(e,(await i(s)).stdout),{image:e};return{text:r.some((o)=>o.startsWith("text/plain")||o==="UTF8_STRING")?(await i(r.includes("text/plain")?"text/plain":"UTF8_STRING")).stdout.toString("utf8"):""}}function jc(){return Boolean(process.env.SSH_CONNECTION||process.env.SSH_TTY)}async function Vm(e){if(process.platform==="darwin"){let t=(await xt("osascript",["-l","JavaScript","-e",B1,e])).stdout.trim();return t===e?{image:e}:{text:t}}if(Bm()){let t=(await xt("powershell.exe",["-NoProfile","-STA","-Command",V1])).stdout.replace(/\r/g,"").trim(),n=await Promise.all(t.split(`
502
- `).map(async(r)=>/^[A-Za-z]:\\/.test(r)?(await xt("wslpath",["-u",r])).stdout.trim():r));return n.length===1&&/ttheme-clipboard\.png$/.test(n[0]??"")?{image:n[0]}:{text:n.join(`
503
- `)}}if(process.platform==="linux")return X1(e);throw Error(`reading the clipboard is not supported on ${process.platform}`)}var x1=`ObjC.import('AppKit')
480
+ $c::GetText()`;function Fp(){if(process.platform!=="linux")return!1;try{return/microsoft/i.test(Ca("/proc/version","utf8"))}catch{return!1}}async function XE(e){let t=Boolean(process.env.WAYLAND_DISPLAY),n=t?["wl-paste",["--list-types"]]:["xclip",["-selection","clipboard","-t","TARGETS","-o"]],r=(await an(n[0],n[1])).stdout.split(`
481
+ `).map((o)=>o.trim()),i=(o)=>t?an("wl-paste",["--no-newline","--type",o],{encoding:"buffer",maxBuffer:La}):an("xclip",["-selection","clipboard","-t",o,"-o"],{encoding:"buffer",maxBuffer:La});if(r.includes("text/uri-list"))return{text:(await i("text/uri-list")).stdout.toString("utf8")};let s=yl.find((o)=>r.includes(o));if(s)return Mp(e,(await i(s)).stdout),{image:e};return{text:r.some((o)=>o.startsWith("text/plain")||o==="UTF8_STRING")?(await i(r.includes("text/plain")?"text/plain":"UTF8_STRING")).stdout.toString("utf8"):""}}function vl(){return Boolean(process.env.SSH_CONNECTION||process.env.SSH_TTY)}async function Rp(e){if(process.platform==="darwin"){let t=(await an("osascript",["-l","JavaScript","-e",ZE,e])).stdout.trim();return t===e?{image:e}:{text:t}}if(Fp()){let t=(await an("powershell.exe",["-NoProfile","-STA","-Command",VE])).stdout.replace(/\r/g,"").trim(),n=await Promise.all(t.split(`
482
+ `).map(async(r)=>/^[A-Za-z]:\\/.test(r)?(await an("wslpath",["-u",r])).stdout.trim():r));return n.length===1&&/ttheme-clipboard\.png$/.test(n[0]??"")?{image:n[0]}:{text:n.join(`
483
+ `)}}if(process.platform==="linux")return XE(e);throw Error(`reading the clipboard is not supported on ${process.platform}`)}var DE=`ObjC.import('AppKit')
504
484
  function run() {
505
485
  const pb = $.NSPasteboard.generalPasteboard
506
486
  const files = pb.readObjectsForClassesOptions($([$.NSURL]), $({ NSPasteboardURLReadingFileURLsOnlyKey: true }))
@@ -512,27 +492,49 @@ function run() {
512
492
  picture = ['public.png', 'public.tiff', 'public.jpeg', 'public.heic'].some((t) => types.includes(t))
513
493
  }
514
494
  return pb.changeCount + '\\t' + (picture ? 'picture' : '')
515
- }`;async function Xm(){if(jc())return;if(process.platform==="darwin"){let[e="",t=""]=(await xt("osascript",["-l","JavaScript","-e",x1])).stdout.trim().split("\t");return{stamp:e,picture:t==="picture"}}if(process.platform==="linux"&&!Bm()){let t=Boolean(process.env.WAYLAND_DISPLAY)?(await xt("wl-paste",["--list-types"])).stdout:(await xt("xclip",["-selection","clipboard","-t","TARGETS","-o"])).stdout;return{stamp:t,picture:/^image\//m.test(t)}}return}function xm(e){let t=[],n="",r=0;while(r<e.length){if(e[r]!=="\x1B"){n+=e[r],r++;continue}if(e.startsWith("\x1B[200~",r)){let s=e.indexOf("\x1B[201~",r+6);if(s===-1)return{events:t,keys:n,pending:e.slice(r)};t.push({kind:"paste",text:e.slice(r+6,s)}),r=s+6;continue}if(e.startsWith("\x1B]5522;",r)||e.startsWith("\x1B]72;",r)){let s=[e.indexOf("\x1B\\",r),e.indexOf("\x07",r)].filter((h)=>h!==-1);if(s.length===0)return{events:t,keys:n,pending:e.slice(r)};let o=Math.min(...s),a=e.slice(r+2,o),[u="",c="",...l]=a.split(";");t.push({kind:"osc",code:u,meta:D1(c),payload:l.join(";")}),r=o+(e[o]==="\x07"?1:2);continue}let i=/^\[\?([\d;]*)(\$y|c)/.exec(e.slice(r+1,r+64));if(i){if(i[2]==="c")t.push({kind:"attributes"});else{let[s="0",o="0"]=(i[1]??"").split(";");t.push({kind:"mode",mode:Number(s),value:Number(o)})}r+=1+i[0].length;continue}if(/^(?:\[(?:\?[\d;$]*|2|20|200|201)?|\](?:5|55|552|5522|7|72)?)$/.test(e.slice(r+1)))return{events:t,keys:n,pending:e.slice(r)};n+=e[r],r++}return{events:t,keys:n,pending:""}}function D1(e){let t={};for(let n of e.split(":")){let r=n.indexOf("=");if(r>0)t[n.slice(0,r)]=n.slice(r+1)}return t}var Es=(e)=>Buffer.from(e).toString("base64"),Uc=(e)=>Buffer.from(e,"base64");function Wm(e,t){return t.find((n)=>e.includes(n))}class Wc{clipboard=!1;drops=!1;reading;offered=[];dropping;pw=Es(Jm("sha1").update(`${process.pid}:${Date.now()}`).digest("hex"));send;deliver;constructor(e,t){this.send=e,this.deliver=t}start(){let e="\x1B[?2004h";if(this.clipboard)e+="\x1B[?5522h";if(this.drops)e+=`\x1B]72;t=a;${Gc.join(" ")}\x1B\\`;this.send(e)}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=${Es("ttheme")}:pw=${this.pw};${Es(".")}\x1B\\`)}take(e){if(e.code==="5522")this.clip(e.meta,e.payload);else if(e.code==="72")this.drop(e.meta,e.payload)}clip(e,t){if(e.type!=="read")return;let n=e.status??"";if(n==="OK"){if(this.reading??={mime:".",chunks:[],pw:e.pw??"",listing:!0},e.pw)this.reading.pw=e.pw;return}let r=this.reading;if(!r)return;if(n==="DATA"){if(r.mime=e.mime?Uc(e.mime).toString("utf8"):r.mime,t)r.chunks.push(Uc(t));return}if(this.reading=void 0,n!=="DONE"){this.deliver({kind:"error",message:n==="EPERM"?"The clipboard read was not allowed":`The terminal answered ${n}`});return}let i=Buffer.concat(r.chunks);if(r.listing){let s=i.toString("utf8").split(/\s+/).filter(Boolean),o=Wm(s,[..._c,...Q1]);if(!o){this.deliver({kind:"text",text:""});return}let a=r.pw||this.pw,u=r.pw?"Paste event":"ttheme";this.reading={mime:o,chunks:[],pw:a,listing:!1},this.send(`\x1B]5522;type=read:name=${Es(u)}:pw=${a};${Es(o)}\x1B\\`);return}this.deliver(r.mime.startsWith("image/")?{kind:"bytes",bytes:new Uint8Array(i),source:"clipboard"}:{kind:"text",text:i.toString("utf8")})}drop(e,t){let n=e.t??"";if(n==="m"){if(e.x==="-1"){this.offered=[];return}if(t){this.offered=t.split(" ").filter(Boolean);let a=Gc.filter((u)=>this.offered.includes(u));this.send(`\x1B]72;t=m:o=${a.length>0?1:0};${a.join(" ")}\x1B\\`)}return}if(n==="M"){let a=t?t.split(" ").filter(Boolean):this.offered,u=Wm(a,Gc);if(!u){this.send("\x1B]72;t=r:o=0\x1B\\");return}this.dropping={mimes:a,index:a.indexOf(u)+1,chunks:[]},this.send(`\x1B]72;t=r:x=${this.dropping.index}\x1B\\`);return}let r=this.dropping;if(!r)return;if(n==="R"){this.dropping=void 0,this.send("\x1B]72;t=r:o=0\x1B\\"),this.deliver({kind:"error",message:`The drop failed: ${t.split(":")[0]||"unknown error"}`});return}if(n!=="r"&&n!=="")return;if(t)r.chunks.push(Uc(t));if(e.m==="1"||t)return;this.dropping=void 0;let i=Buffer.concat(r.chunks),s=r.mimes[r.index-1]??"",o;if(s.startsWith("image/"))o={kind:"bytes",bytes:new Uint8Array(i),source:"drop"};else{let a=i.toString("utf8"),u=s==="text/uri-list"?sa(a).find((c)=>U1(c)):void 0;o=u?{kind:"bytes",bytes:new Uint8Array(ia(u)),source:u}:{kind:"text",text:a}}this.send("\x1B]72;t=r:o=1\x1B\\"),this.deliver(o)}}var Ke={pitch:25,cols:22,rows:9,height:13},fr={cols:25,rows:16},eE=2147483648,tE=-1073741826,nE=1600,Dm=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],rE=56,iE=4,ep=20,sE=50,tp=[["space","unfolds a set of ×N"],["o","opens the post page in a browser"],["c","switches between cutouts and every post"],["a","opens the advanced filters"],["ctrl+v","tries on a picture from the clipboard — or drop one on the window"]],oE="\x1B[0m",Lt="\x1B[1m",ce="\x1B[2m",vs="\x1B[31m",Dt="\x1B[32m",vt="\x1B[33m",aa="\x1B[1;34m",aE="\x1B[35m",uE={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 cp(e){let t=[],n=0;while(n<e.length){let r=e[n]??"";if(r==="\x1B"){let i=/^(?:\[([0-9;]*)([A-Za-z~])|O([A-Za-z]))/.exec(e.slice(n+1));if(i){t.push(uE[`${i[1]??""}${i[2]??i[3]??""}`]??"nop"),n+=1+i[0].length;continue}let s=e[n+1]??"";if(/^[a-z]$/.test(s)){t.push(`alt-${s}`),n+=2;continue}t.push("esc"),n++;continue}t.push(r==="\r"||r===`
516
- `?"enter":r==="\t"?"tab":r==="\x03"?"ctrl-c":r==="\x16"?"ctrl-v":r===""||r==="\b"?"backspace":r),n++}return t}var lp="\x1B]1337;ReportCellSize\x07\x1B[16t",np="\x1B]1337;ReportCellSize=";function qc(e){let t=e.indexOf(np);if(t!==-1){let i=e.slice(t+np.length),s=[i.indexOf("\x07"),i.indexOf("\x1B\\")].filter((u)=>u!==-1),o=s.length>0?Math.min(...s):-1,a=o===-1?null:/^([\d.]+);([\d.]+);([\d.]+)$/.exec(i.slice(0,o));if(a){let u=Number(a[3]);return{cell:{h:Math.round(Number(a[1])*u),w:Math.round(Number(a[2])*u)},rest:e.slice(0,t)+i.slice(o+(i[o]==="\x07"?1:2))}}}let n=e.indexOf("\x1B[6;"),r=n===-1?null:/^\[6;(\d+);(\d+)t/.exec(e.slice(n+1));if(!r)return null;return{cell:{h:Number(r[1]),w:Number(r[2])},rest:e.slice(0,n)+e.slice(n+1+r[0].length)}}function dr(e,t){let n=t-4;return{perRow:Math.max(1,Math.floor((e-1)/Ke.pitch)),rowsVis:Math.max(1,Math.floor(n/Ke.height)),height:n}}function hp(e){return`\x1B_Ga=t,t=f,f=100,i=${e.id},q=2;${Buffer.from(e.path).toString("base64")}\x1B\\`}function fp(e,t){let n=e.crop===void 0?"":`,x=0,y=${e.crop*t.h},w=${e.cols*t.w},h=${e.rows*t.h}`;return`\x1B[${e.row+1};${e.col+1}H\x1B_Ga=p,i=${e.id},p=${e.id}${n},c=${e.cols},r=${e.rows},C=1,z=${e.z},q=2\x1B\\`}function dp(e){return`\x1B_Ga=d,d=I,i=${e},q=2\x1B\\`}function ri(e){return`\x1B[38;2;${Qe(e).join(";")}m`}function ua(e){return`\x1B[48;2;${Qe(e).join(";")}m`}var Jc=!1;function la(e){return Jc=!0,e.beat}function ii(e){return Dm[la(e)%Dm.length]}function Ce(e){return Array.from(e).length}class ca{parts=[];cols;constructor(e){this.cols=e}put(e,t,n=""){return this.parts.push({col:e,text:t,sgr:n}),e+Ce(t)}run(e,t){let n=e;for(let[r,i]of t)n=this.put(n,r,i);return n}right(e,t){this.run(e-t.reduce((n,[r])=>n+Ce(r),0),t)}center(e,t){this.run(Math.floor((e-t.reduce((n,[r])=>n+Ce(r),0))/2),t)}render(){let e="";for(let{col:t,text:n,sgr:r}of this.parts){if(t>=this.cols||t<0)continue;let i=Array.from(n).slice(0,this.cols-t).join("");e+=`\x1B[${t+1}G${r}${i}${r?oE:""}`}return e}}function gp(e){return e.replace(/_\([^)]*\)?$/,"")}function mp(e){return[`${e.reduced?"↓":""}${e.width}×${e.height}`,Math.max(e.width,e.height)<nE?vt:ce]}function ha(e,t,n,r){let i=[...r.keys??[]],s=r.lead,o=r.right,a=()=>{let l=[...s?[Ce(s[0])]:[],...i.map(([f,d])=>Ce(f)+1+Ce(d))];return(r.badge?Ce(r.badge)+4:0)+l.reduce((f,d)=>f+d,0)+3*Math.max(0,l.length-1)+(o?3+Ce(o[0])+1+Ce(o[1]):0)};while(a()>t)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&&a()>t){let l=Math.max(0,Ce(s[0])-(a()-t)-1);s=[`${Array.from(s[0]).slice(0,l).join("")}…`,s[1]]}let u=0;if(r.badge)u=e.put(0,` ${r.badge} `,`\x1B[7;1m${n}`)+2;if([...s?[[s]]:[],...i.map(([l,h])=>[[l,Lt],[` ${h}`,ce]])].forEach((l,h)=>{u=e.run(u+(h?3:0),l)}),o)e.right(t,[[o[0],Lt],[` ${o[1]}`,ce]])}function cE(e,t,n,r,i,s){let{ansi:o,selection:a,cursor:u}=s.colors,c=r<44?3:4;if(r>=56)c=Math.min(7,Math.floor((r+1)/8)-1);let l=n;for(let g=0;g<8;g++)l=(e[t]?.put(l,"▀".repeat(c),ri(o[g]??u)+ua(o[g+8]??u))??l)+1;let h=["❯ ",Dt],f=[[["~/code/demo",aa],[" on ",ce],["main",aE],[" +2",Dt],[" ~1",vt]]];if(f.push([h,["git status -sb",""]]),r>=44)f.push([["## ",""],["main",Dt],["...",""],["origin/main",vs],[" [ahead 1]",vt]]);if(f.push([[" M",vs],[" src/main.rs",""]]),f.push([["??",vs],[" notes.md",""]]),f.push([]),r>=44)f.push([h,["ls",""]]),f.push([["docs",aa],[" ",""],["src",aa],[" ",""],["tests",aa],[" Cargo.toml README.md",""]]),f.push([]);f.push([h,["cargo test",""]]),f.push([[" ✓",Dt],[" parses config",""]]);let d=[[" ✗",vs],[" renders frame",""]];if(r>=44)d.push([" expected ",ce],["3",Dt],[", received ",ce],["2",vs]);f.push(d),f.push([]),f.push([h,["echo ",""],["selected text",ua(a)],[" ",""],[" ",ua(u)]]),f.forEach((g,m)=>{let b=t+2+m;if(b<=i)e[b]?.run(n,g)})}function lE(e,t,n,r,i,s){e[t]?.put(n,`╭${"─".repeat(i-2)}╮`,s);for(let o=t+1;o<t+r-1;o++)e[o]?.put(n,"│",s),e[o]?.put(n+i-1,"│",s);e[t+r-1]?.put(n,`╰${"─".repeat(i-2)}╯`,s)}function Kc(e,t=e.site,n=e.siteAnsi){return[` ${t} `,`\x1B[7;${30+n}m`]}function hE(e){return`${te[Math.floor(e/nn)]?.name??"local"} ${e%nn}`}function fE(e,t,n){let r=[{name:"all",moved:!1},...te].flatMap((s,o)=>{let a=`${s.name}${s.moved?"*":""}`,u=s.name===n.site?Kc(n,a):[` ${a} `,ce];return o?[[" ",""],u]:[u]}),i=r.reduce((s,[o])=>s+Ce(o),0)<=t;e.run(0,i?r:[Kc(n)])}function dE(e,t,n,r){if(n.editing!==void 0){let u=e.run(0,[["⌕ ",r],[n.editing,""],["█",r]]),c=n.suggest?.length?" ↑↓ pick enter searches":" enter searches";e.put(u,n.editing?c:` A tag, a post URL or an id, or drop a picture or ctrl+v — ${n.tag||"esc leaves"}`,ce);return}let i=e.run(0,[["⌕ ",r],[n.tag||"Nothing yet — / searches, ctrl+v pastes a picture",n.tag?"":ce]]),s=Yn.filter((u)=>!n.block.includes(u)),o=te.filter((u)=>!n.enabled.includes(u.name)).map((u)=>u.name),a=[n.preset,...n.solo?["solo"]:[],n.order,...n.rating.join("+")==="safe"?[]:[n.rating.join("+")],...s.length>0?[`allows ${s.join("+")}`]:[],...n.narrow.size>0?[`≥${n.narrow.size}px`]:[],...n.narrow.score>0?[`score≥${n.narrow.score}`]:[],...n.narrow.png?["png"]:[],...n.hide.length+n.hideTags.length>0?[`hides ${[...n.hide,...n.hideTags].join("+")}`]:[],...o.length>0?[`all skips ${o.join("+")}`]:[]];if(e.put(i,` ${a.join(" ")}`,ce),n.total>0||!n.searching){let u=[[`${n.tiles.length}/${n.checked}`,""]];if(n.checked<n.total)u.push([` of ${n.total}`,ce]);e.right(t,u)}}function gE(e){if(e.cut==="on")return[[`Cut out · ${e.clear}% transparent`,Dt]];if(e.cut==="off")return[["Opaque · x cuts out",vt]];if(e.cut==="failed")return[["Opaque · no cut-out",vt]];return[e.clear>0?[`${e.clear}% transparent`,Dt]:["Opaque",vt]]}function rp(e){return e.site==="all"?"any site":e.site}function pp(e,t){if(e.installing!==void 0)return[`${ii(e)} Installing ${e.palette} ← ${hE(e.installing)}`,vt];if(e.hint)return[e.hint,Dt];if(e.error)return[e.error,vt];if(e.waiting!==void 0)return[`${e.slow??e.site} asked to slow down · ${e.waiting}s`,vt];if(e.fetching)return[`${ii(e)} Fetching ${e.fetching.id%nn} · ${Co(e.fetching.got,e.fetching.size)}`,vt];if(e.cutting!==void 0)return[`${ii(e)} Cutting out ${e.cutting%nn}`,vt];if(e.preparing!==void 0)return[`${ii(e)} Preparing ${e.preparing%nn}`,vt];if(t)return t;if(e.saved)return[e.saved,Dt];if(e.note)return[e.note,ce];return}function wp(e){if(e.ranking)return"Ranking previews by palette colors";if(e.stage==="check")return e.preset==="cutouts"?"Checking PNG headers":"Loading previews";return"Fetching posts"}function bp(e,t){return e.ranking?`${t}${e.ranking.done}/${e.ranking.total}`:""}function mE(e,t,n,r,i){let{background:s,cursor:o,selection:a}=r.colors,{ranking:u}=r,c=u?Math.round(n*u.done/u.total):-1,l=Math.max(6,Math.round(n*0.22)),h=la(r)%(ep*2)/ep,f=Math.round((n-l)*(0.5-0.5*Math.cos(Math.PI*(h<1?h:2-h)))),d=rt(s,o,i),g=rt(s,rt(a,s,0.15),i),m=Array.from({length:n},(p,E)=>{let v=(c>=0?E<c:E>=f&&E<f+l)?d:g;return E===0||E===n-1?rt(v,s,0.55):v}),b=0;for(let p=1;p<=n;p++)if(p===n||m[p]!==m[b])e?.put(t+b," ".repeat(p-b),ua(m[b])),b=p}function pE(e,t,n,r,i){let{background:s,foreground:o}=i.colors,a=i.loaderFrom===void 0?0:Math.min(1,(la(i)-i.loaderFrom)/iE),u=t+(n>=5?Math.floor((n-5)/2):0);e[u]?.center(r,[[wp(i),Lt+ri(rt(s,o,a))],[bp(i," "),ri(rt(s,rt(o,s,0.45),a))]]);let c=Math.min(rE,r-8);if(mE(e[u+(n>=3?2:1)],Math.floor((r-c)/2),c,i,a),n<5)return;e[u+4]?.center(r,i.sites.flatMap(({name:l,arrived:h},f)=>[...f?[[" · ",ri(rt(s,o,0.25*a))]]:[],[l,ri(rt(s,h?rt(o,s,0.2):o,h?a:0.32*a))]]))}function wE(e,t,n,r,i,s){if(i<=r)return;let o=Math.max(1,Math.round(r*r/i)),a=Math.max(0,Math.min(r-o,Math.round(n.scroll*r/i)));for(let u=0;u<r;u++){let c=u>=a&&u<a+o;e[2+u]?.put(t-1,c?"┃":"│",c?s:ce)}}function bE(e,t,n){if(t)return[`${ii(e)} ${wp(e)}${bp(e," · ")}`,ce];let r=n.filter((s)=>!s.missing),i=r.filter((s)=>s.thumb).length;return i<r.length?[`${ii(e)} Loading thumbnails · ${i}/${r.length}`,ce]:void 0}function $E(e,t,n,r,i,s){let{perRow:o,rowsVis:a,height:u}=dr(n,r);dE(e[0],n,i,s),fE(e[1],n,i);let c=e.map((y,R)=>R>=2&&R<2+u?y:void 0),l=Math.floor(i.scroll/Ke.height),h=Math.floor((i.scroll+u-1)/Ke.height),f=[];for(let y=l;y<=h;y++){let R=2+y*Ke.height-i.scroll;for(let P=0;P<o;P++){let G=y*o+P,A=P*Ke.pitch,_=i.tiles[G];if(!_)continue;f.push(_);let C=G===i.focus;if(C)lE(c,R,A,Ke.height,Ke.pitch-1,s);let H=R+1,O=Math.max(H,2),K=Math.min(H+Ke.rows,2+u);if(_.thumb&&K>O)t.push({id:_.key,path:_.thumb,row:O,col:A+1,cols:Ke.cols,rows:K-O,...K-O<Ke.rows?{crop:O-H}:{},z:-1});if(c[R+10]?.run(A+1,[...i.installed.includes(_.key)?[["✓ ",Dt]]:[],...i.site==="all"?[["● ",`\x1B[${30+_.siteAnsi}m`]]:[],[String(_.id),C?Lt:""],[" ",""],mp(_)]),_.mates.length>0)c[R+10]?.put(A+Ke.cols,"≈",s);let Ee=_.artist?gp(_.artist):_.owner&&`@${_.owner}`;if(Ee)c[R+11]?.put(A+1,Ee.slice(0,Ke.cols-8),ce);let le=[];if(_.score>0)le.push([`★${_.score}`,ce]);if(_.variants>1)le.push([` ×${_.variants}`,s]);if(le.length>0)c[R+11]?.right(A+Ke.cols+1,le)}}let d=Math.ceil(i.tiles.length/o)*Ke.height;wE(e,n,i,u,d,s);let g=Math.max(2,2+d-i.scroll),m=2+u-g,b=i.searching&&m>=2;if(b)pE(c,g,m,n-1,i);let p=i.searching&&i.tiles.length===0;if(p&&!i.error){let[y,R]=tp[Math.floor(la(i)/sE)%tp.length];e[r-2]?.run(0,[["Tip ",ce],[y,Lt],[` ${R}`,ce]])}let E=i.top*o,v=i.tiles.length-(i.top+a)*o,S=[...E>0?[`↑ ${E} above`]:[],...v>0?[`↓ ${v} more`]:[]];if(S.length>0)e[r-2]?.put(0,S.join(" "),ce);if(!i.searching&&i.tiles.length===0&&!i.error)e[3]?.put(0,i.preset==="cutouts"?`No transparent cutouts of ${i.tag} on ${rp(i)} — c searches every post, tab tries ${i.nextSite}`:`No posts of ${i.tag} on ${rp(i)} — tab tries ${i.nextSite}`,ce);let w=bE(i,b,f),N=pp(i,w);return ha(e[r-1],n,s,{badge:"FIND",lead:N,keys:p&&N===w?[]:[["←↑↓→","move"],["enter","try on"],["tab","site"],["ctrl+v","picture"],["s","settings"],["/","search"],["?","keys"]],right:["esc","back"]}),b}function kE(e,t,n,r,i,s){let o=i.tiles[i.focus];if(!o)return;let a=i.shown?.id===o.key?i.shown:void 0,u=[Kc(i,o.site,o.siteAnsi),[" ",""],[String(o.id),Lt],[" ",""],mp(o)];if(o.artist)u.push([` · ${gp(o.artist)}`,""]);if(o.score>0)u.push([` · ★${o.score}`,ce]);if(a)u.push([` · ${rc(a.bytes)}`,ce]);if(o.owner)u.push([` · ${o.owner}`,ce]);if(o.origin)u.push([` · ${o.origin}`,ce]);if(a)u.push([" ",""],...gE(a));if(e[0]?.run(0,u),o.mates.length>0)e[0]?.right(n,[["≈ ",s],[o.mates.join(" "),ce]]);if(cE(e,3,2,n-4,r-2,i),i.shown)t.push({id:eE+i.shown.id,path:i.shown.path,row:0,col:0,cols:n,rows:r,z:tE});let c=pp(i);ha(e[r-1],n,s,{badge:"TRY",lead:c,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 yE={grid:[["Move","←↑↓→ home end pgup pgdn"],["Try on","enter"],["Site",`tab all, ${te.map((e)=>e.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"],["Advanced","a or Advanced › in settings min score, min size, sites, hide, hide tags, PNG only"],["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"]]},Qc=6,EE=24;function Ms(e){return[...e.settings.flatMap((t,n)=>Boolean(t.advanced)===e.advanced?[n]:[]),e.settings.length]}function vE(e){return e.replace(/^[A-Z](?=[a-z])/,(t)=>t.toLowerCase())}function ip(e){let t=e.settings.filter((n)=>Boolean(n.advanced)!==e.advanced).map((n)=>vE(n.label));return`${e.advanced?"Back to":"More filters:"} ${t.join(", ")} — enter opens the page, or a from any row`}function $p(e,t,n){let r=e.indexOf(t);if(r!==-1)return e[(r+n+e.length)%e.length];let i=Number(t)||0;return(n>0?e.find((o)=>(Number(o)||0)>i):[...e].reverse().find((o)=>(Number(o)||0)<i))??e[n>0?0:e.length-1]}function hr(e,t){let n=[],r="";for(let i of e.split(" "))if(r&&Ce(r)+1+Ce(i)>t)n.push(r),r=i;else r=r?`${r} ${i}`:i;return r?[...n,r]:n}function ME(e){if(e.entry!=="number"||e.choices.includes(e.value))return e.choices;let t=e.choices.findIndex((n)=>(Number(n)||0)>Number(e.value));return t===-1?[...e.choices,e.value]:[...e.choices.slice(0,t),e.value,...e.choices.slice(t)]}function SE(e,t,n,r){let i=`\x1B[7;${30+r}m`,s=t&&n!==void 0;if(e.entry==="text")return[{text:` ${s?`${n}█`:e.value||"none"} `,sgr:s||t&&e.value?i:e.value?"":ce}];let o=s?[]:e.value.split(" "),a=(s?e.choices:ME(e)).map((u,c)=>{let l=o.includes(u),h=e.multi&&t&&c===e.cursor?"4;":"";return{text:e.multi?` ${l?"[x]":"[ ]"} ${u} `:` ${u} `,sgr:l?t?`\x1B[${h}7;${30+r}m`:"":h?`\x1B[4m${ce}`:ce}});return s?[...a,{text:` ${n}█ `,sgr:i}]:a}function sp(e){if(e.entry==="text")return[{text:" ".repeat(EE),sgr:""}];let t=e.choices.map((n)=>({text:e.multi?` [x] ${n} `:` ${n} `,sgr:""}));return e.entry==="number"?[...t,{text:` ${"0".repeat(Qc)}█ `,sgr:""}]:t}function IE(e){return e.reduce((t,n)=>t+Ce(n.text)+1,0)-1}function op(e,t){let n=[[]],r=0;for(let i of e){let s=Ce(i.text)>t?{...i,text:` …${Array.from(i.text).slice(-(t-2)).join("")}`}:i;if(r>0&&r+Ce(s.text)>t)n.push([]),r=0;n[n.length-1]?.push(s),r+=Ce(s.text)+1}return n}function ap(e){if(e.multi&&e.choices.every((t)=>e.default.split(" ").includes(t)))return"Default all";return`Default ${e.default&&e.default!==e.multi?.none?e.default:"none"}`}function up(e){if(!e.tag)return"";if(!e.counts)return`${e.tag}: counting…`;let t=e.counts.map(({site:n,count:r})=>`${n} ${r===void 0?"no count":r.toLocaleString("en-US")}`);return`${e.tag}: ${t.join(" · ")}`}function NE(e,t){let n=e.advanced?"basic":"advanced";if(!t)return{keys:[["↑↓","setting"],["enter",n],["s","save"]],right:["esc","undo"]};if(e.typing!==void 0)return{keys:[["⌫","erase"],["enter","done"]],right:["esc","cancel"]};if(t.entry)return{keys:[["↑↓","setting"],...t.entry==="number"?[["←→","step"]]:[],["a",n],["enter","type"],["s","save"]],right:["esc","undo"]};return{keys:[["↑↓","setting"],["←→","value"],["a",n],...t.multi?[["space","toggle"]]:[],["enter","save"]],right:["esc","undo"]}}function RE(e,t,n,r,i){let s=r.panel??0,o=r.settings.length,u=6+Math.max(...r.settings.map((H)=>Ce(H.label))),c=Math.max(...r.settings.map((H)=>Ce(ap(H)))),l=u+Math.max(...r.settings.map((H)=>IE(sp(H))))+c+5,h=Math.min(t-2,Math.max(48,l)),f=h-u-c-5,d=h-7,g=[!1,!0].map((H)=>({advanced:H,rows:Ms({settings:r.settings,advanced:H}).slice(0,-1)})),m=r.settings.map((H)=>op(sp(H),f).length),b=Math.max(...g.map((H)=>H.rows.reduce((O,K)=>O+m[K],0))),p=Math.max(...g.map((H)=>hr(ip({settings:r.settings,advanced:H.advanced}),d).length),...r.settings.map((H)=>hr(H.about,d).length)),E=`${r.tag}: ${te.map((H)=>`${H.name} 0,000,000`).join(" · ")}`,v=r.tag?Math.max(hr(E,d).length,hr(up(r),d).length):0,S=b+p+v+8,w=Math.floor((t-h)/2),N=Math.max(1,Math.floor((n-1-S)/2)),y=`\x1B[7;${30+r.siteAnsi}m`;e[N]?.put(w,`╭─ Settings ${"─".repeat(Math.max(0,h-13))}╮`);for(let H=N+1;H<N+S-1;H++)e[H]?.put(w,`│${" ".repeat(h-2)}│`);let R=N+2;for(let H of Ms(r).slice(0,-1)){let O=r.settings[H],K=H===s;if(K)e[R]?.put(w+2,"▶",i);if(e[R]?.put(w+4,O.label,K?Lt:""),O.value!==O.default)e[R]?.right(w+h-3,[[ap(O),ce]]);op(SE(O,K,r.typing,r.siteAnsi),f).forEach((Ee,le)=>{let D=w+u;for(let Ge of Ee)D=e[R+le].put(D,Ge.text,Ge.sgr)+1}),R+=m[H]}let P=g.find((H)=>H.advanced!==r.advanced)?.rows??[],G=e[N+3+b];if(s===o)G.put(w+2,"▶",i);let A=G.put(w+3,r.advanced?" ‹ Basic ":" Advanced › ",s===o?y:Lt);if(P.some((H)=>r.settings[H]?.value!==r.settings[H]?.default))G.put(A+1,"•",ce);e[N+5+b]?.put(w+2,"─".repeat(h-4),ce),hr(r.settings[s]?.about??ip(r),d).forEach((H,O)=>{e[N+6+b+O]?.put(w+4,H)}),hr(up(r),d).forEach((H,O)=>{e[N+6+b+p+O]?.put(w+4,H,ce)}),e[N+S-1]?.put(w,`╰${"─".repeat(h-2)}╯`);let{keys:_,right:C}=NE(r,r.settings[s]);ha(e[n-1],t,i,{badge:"SET",keys:_,right:C})}function FE(e,t,n,r,i){let s=yE[r.mode],o=Math.min(t-2,Math.max(50,...s.map(([,f])=>Ce(f)+16))),a=s.map(([f,d])=>({label:f,parts:hr(d,o-16)})),u=a.reduce((f,{parts:d})=>f+d.length,0)+4,c=Math.floor((t-o)/2),l=Math.max(2,Math.floor((n-u)/2));e[l]?.put(c,`╭─ Keys ${"─".repeat(o-9)}╮`);for(let f=l+1;f<l+u-1;f++)e[f]?.put(c,`│${" ".repeat(o-2)}│`);let h=l+2;for(let{label:f,parts:d}of a){e[h]?.put(c+3,f,Lt);for(let g of d)e[h]?.put(c+13,g),h++}e[l+u-1]?.put(c,`╰${"─".repeat(o-2)}╯`),ha(e[n-1],t,i,{badge:"KEYS",right:["? esc","close"]})}function PE(e,t,n){let r=t.suggest??[],i=r.map((a)=>a.count>0?String(a.count):a.palette??"0"),s=Math.max(...r.map((a)=>Ce(a.value))),o=Math.max(7,...i.map(Ce));r.forEach((a,u)=>{let c=u===t.pick,l=e[1+u];l?.run(0,[[c?"▸ ":" ",n],[a.value,c?Lt+n:""]]),l?.right(2+s+2+o,[[i[u],ce]])})}function Yc(e,t,n){let r=Array.from({length:n},()=>new ca(t)),i=[],s=ri(e.colors.cursor);if(Jc=!1,t<fr.cols||n<fr.rows)return r[0]?.put(0,"ttheme find",Lt+s),r[1]?.put(0,`Needs ${fr.cols}×${fr.rows} — now ${t}×${n}`),r[2]?.put(0,"esc quits",ce),{lines:r.map((a)=>a.render()),images:i,loader:!1,tick:!1};let o=!1;if(e.mode==="try")kE(r,i,t,n,e,s);else o=$E(r,i,t,n,e,s);if(e.mode==="grid"&&e.editing!==void 0&&e.suggest?.length){for(let a=1;a<n-1;a++)r[a]=new ca(t);return PE(r,e,s),{lines:r.map((a)=>a.render()),images:[],loader:!1,tick:!1}}if(e.help||e.panel!==void 0){let a=e.mode==="try"?i:[];for(let u=0;u<n;u++)r[u]=new ca(t);if(e.help)FE(r,t,n,e,s);else RE(r,t,n,e,s);return{lines:r.map((u)=>u.render()),images:a,loader:!1,tick:!1}}return{lines:r.map((a)=>a.render()),images:i,loader:o,tick:Jc}}var OE=new Set(["comic","4koma","monochrome","greyscale","sketch","lineart","speech_bubble"]),TE=new Set(["scenery","landscape","scenic","no_humans","wide_shot","very_wide_shot"]),AE=0.04,HE=0.1,LE=0.05,GE=4096;function UE(e){return new Set(e.cutouts.split(/\s+/).map((t)=>t.replace(/^~/,"")).filter(Boolean))}function _E(e,t,n,r=0){let{site:i,post:s}=e,o=new Set(s.tags),a=[...UE(i)].some((l)=>o.has(l)),u=Math.min(s.width,s.height),c=s.width>0&&s.height>0?s.width/s.height/(t.w/t.h):1;return(s.solo?2:0)+([...OE].some((l)=>o.has(l))?-3:0)+([...TE].some((l)=>o.has(l))?-1.5:0)+2*Math.min(1,u/t.h)+(a?1.5:-Math.min(1.5,Math.abs(Math.log(c))))+(n>0?1.5*Math.log1p(Math.max(0,s.score))/Math.log1p(n):0)+2*r}function fa(e,t,n=new Map){let r=new Map;for(let{site:i,post:s}of e)r.set(i,Math.max(r.get(i)??0,s.score));return e.map((i,s)=>({pick:i,at:s,score:_E(i,t,r.get(i.site)??0,n.get(i.post))})).sort((i,s)=>s.score-i.score||i.at-s.at).map(({pick:i})=>i)}function yp(e){let t=new Map;for(let r of e)t.set(r.site,[...t.get(r.site)??[],r]);let n=[];for(let r=0;n.length<e.length;r++)for(let i of t.values()){let s=i[r];if(s)n.push(s)}return n}function Zc(e){let t=e/255;return t<=0.04045?t/12.92:((t+0.055)/1.055)**2.4}function kp(e,t,n){let[r,i,s]=[Zc(e),Zc(t),Zc(n)],o=Math.cbrt(0.4122214708*r+0.5363325363*i+0.0514459929*s),a=Math.cbrt(0.2119034982*r+0.6806995451*i+0.1073969566*s),u=Math.cbrt(0.0883024619*r+0.2817188376*i+0.6299787005*s);return[0.2104542553*o+0.793617785*a-0.0040720468*u,1.9779984951*o-2.428592205*a+0.4505937099*u,0.0259040371*o+0.7827717662*a-0.808675766*u]}function Ep(e,t){let n=t.map((o)=>kp(...Qe(o))).filter(([,o,a])=>Math.hypot(o,a)>=AE);if(n.length===0)return 0;let r=Math.max(1,Math.floor(Math.sqrt(e.width*e.height/GE))),i=n.map(()=>0),s=0;for(let o=0;o<e.height;o+=r)for(let a=0;a<e.width;a+=r){let u=(o*e.width+a)*4;if(e.data[u+3]<128)continue;s++;let[c,l,h]=kp(e.data[u],e.data[u+1],e.data[u+2]);n.forEach(([f,d,g],m)=>{if(Math.hypot(c-f,l-d,h-g)<HE)i[m]=i[m]+1})}if(s===0)return 0;return i.reduce((o,a)=>o+Math.min(1,a/s/LE),0)/n.length}import{mkdirSync as Np,readFileSync as Rp,writeFileSync as Bc}from"node:fs";import{dirname as Fp}from"node:path";import{isMainThread as JE,parentPort as Pp,Worker as KE}from"node:worker_threads";var CE=/(?:^|[^0-9a-f])([0-9a-f]{32})(?:[^0-9a-f]|$)/i,jE=[[/yande\.re\/post\/show\/(\d+)/,"yande"],[/konachan\.(?:com|net)\/post\/show\/(\d+)/,"konachan"],[/danbooru\.donmai\.us\/(?:posts|post\/show)\/(\d+)/,"danbooru"],[/zerochan\.net\/(\d+)(?:[?#\s]|$)/,"zerochan"]];function zc(e){let t=/(\d+)_p(\d+)/.exec(e.source);return[...e.md5?[`md5:${e.md5}`]:[],...t&&e.source.includes("pximg")?[`pixiv:${t[1]}_p${t[2]}`]:[]]}function vp(e,t){let n=CE.exec(t.source)?.[1]?.toLowerCase();return[`post:${e.key}:${t.id}`,...t.md5?[`md5:${t.md5}`]:[],...n&&n!==t.md5?[`md5:${n}`]:[],...jE.flatMap(([r,i])=>{let s=r.exec(t.source)?.[1];return s?[`post:${i}:${Number(s)}`]:[]}),...t.family?[`family:${e.key}:${t.family}`]:[]]}function Mp(e,t){let n=e.owner||e.artist;return n!==""&&n===(t.owner||t.artist)&&e.width===t.width&&e.height===t.height}function Sp(e){let r=[];for(let s=0;s<8;s++){let o=Math.floor(s*e.height/8),a=Math.max(o+1,Math.floor((s+1)*e.height/8));for(let u=0;u<9;u++){let c=Math.floor(u*e.width/9),l=Math.max(c+1,Math.floor((u+1)*e.width/9)),h=0;for(let f=o;f<a;f++)for(let d=c;d<l;d++){let g=(f*e.width+d)*4,m=e.data[g+3]/255,b=0.299*e.data[g]+0.587*e.data[g+1]+0.114*e.data[g+2];h+=b*m+255*(1-m)}r.push(h/((l-c)*(a-o)))}}let i=0n;for(let s=0;s<8;s++)for(let o=0;o<8;o++)i=i<<1n|(r[s*9+o]>r[s*9+o+1]?1n:0n);return i.toString(16).padStart(16,"0")}function WE(e,t){let n=BigInt(`0x${e}`)^BigInt(`0x${t}`),r=0;while(n>0n)r+=Number(n&1n),n>>=1n;return r}function Ip(e,t){if(e.width<=0||e.height<=0||t.width<=0||t.height<=0)return!1;return Math.abs(Math.log(e.width/e.height/(t.width/t.height)))<0.01&&WE(e.hash,t.hash)<=2}var qE={thumb:"tile",band:"band",match:"tile",show:"view",backdrop:"view",redraw:"view"};async function QE(e){if(e.job==="redraw")return jg(e.home,e.name,e.key,e.hue,e.blur,e.aligns,e.user);let t=Qn(new Uint8Array(Rp(e.from)),kt);if(e.job==="backdrop")return $o(e.home,e.colors,e.tone,t,{...e.origin,bytes:new Uint8Array(Rp(e.source)),cut:e.from!==e.source},e,e.blur),0;if(e.job==="match")return{match:Ep(t,e.colors),hash:Sp(t)};if(e.job==="thumb")return Np(Fp(e.to),{recursive:!0}),Bc(e.to,xs(kf(t,e.width,e.height))),0;if(e.job==="band"){let r=t.data.subarray(e.y*t.width*4,(e.y+e.height)*t.width*4);return Bc(e.to,xs({width:t.width,height:e.height,data:r})),0}let n=tn(t);return Np(Fp(e.to),{recursive:!0}),Bc(e.to,xs(Ed(t,e.colors,e.tone,e.width,e.height,e.blur))),n}function YE(e){e.on("message",async(t)=>{try{e.postMessage({id:t.id,value:await QE(t)})}catch(n){e.postMessage({id:t.id,error:n instanceof Error?n.message:String(n)})}})}class Vc{worker;next=1;waiting=new Map;send(e){let t=this.next++;return new Promise((n,r)=>{let i=this.open();this.waiting.set(t,{ok:n,no:r}),i.ref(),i.postMessage({...e,id:t})})}close(){this.worker?.terminate(),this.worker=void 0,this.drop(Error("renderer closed"))}open(){if(this.worker)return this.worker;let e=new KE(import.meta.filename);e.unref(),e.on("message",({id:n,value:r,error:i})=>{let s=this.waiting.get(n);if(this.waiting.delete(n),this.waiting.size===0)e.unref();if(i!==void 0)s?.no(Error(i));else s?.ok(r)});let t=(n)=>{if(this.worker===e)this.worker=void 0;this.drop(n instanceof Error?n:Error("renderer stopped"))};return e.on("error",t),e.on("exit",()=>t(void 0)),this.worker=e,e}drop(e){for(let t of this.waiting.values())t.no(e);this.waiting.clear()}}class Xc{lines=new Map;run(e){let t=qE[e.job],n=this.lines.get(t);if(!n)n=new Vc,this.lines.set(t,n);return n.send(e)}close(){for(let e of this.lines.values())e.close();this.lines.clear()}}class xc{lines;constructor(e){this.lines=Array.from({length:Math.max(1,e)},()=>new Vc)}async map(e){let t=[],n=0;return await Promise.all(this.lines.map(async(r)=>{while(n<e.length){let i=n++;try{t[i]=await r.send(e[i])}catch(s){t[i]=s instanceof Error?s:Error(String(s))}}})),t}close(){for(let e of this.lines)e.close()}}if(!JE&&Pp)YE(Pp);var gr=[{name:"TTHEME_FIND_RATING",label:"Rating",about:"The ratings to list, each site read in its own words — space ticks one, and one stays ticked",choices:Oi,multi:{read:zn}},{name:"TTHEME_FIND_BLOCK",label:"Block",about:"Posts tagged with nudity or underwear are left out — space unticks one",choices:Yn,multi:{read:Or,none:"none"}},{name:"TTHEME_FIND_POSTS",label:"Posts",about:"Every post of the character, or only the transparent cutouts",choices:["all","cutouts"]},{name:"TTHEME_FIND_SOLO",label:"Solo",about:"When on, only the posts known to show the character alone — checked as posts arrive, so the counts below leave it out",choices:["on","off"]},{name:"TTHEME_FIND_ORDER",label:"Order",about:"How posts are ranked: fit, by how well each makes a backdrop; newest; or score",choices:["fit","newest","score"]},{name:"TTHEME_FIND_SETS",label:"Sets",about:"One picture posted over and over, or held by another site too: fold it into one tile, or show each",choices:["fold","show"]},...Xr()?[{name:"TTHEME_FIND_REMOVE_BG",label:"Remove bg",about:"Cut the character out of an opaque picture you try on, with macOS Vision",choices:["on","off"]}]:[],{name:"TTHEME_FIND_MIN_SCORE",label:"Min score",about:"Posts scored at least this — danbooru, konachan and yande.re; zerochan keeps no score. ←→ steps, or type any number",choices:Uf,entry:"number",advanced:!0},{name:"TTHEME_FIND_MIN_SIZE",label:"Min size",about:"The shorter side of a picture, in px — every site filters it. ←→ steps, or type any number",choices:_f,entry:"number",advanced:!0},{name:"TTHEME_FIND_SITES",label:"Sites",about:"The sites the all tab mixes — each keeps its own tab. Space ticks one, and one stays ticked",choices:te.map((e)=>e.name),multi:{read:Ai},advanced:!0},{name:"TTHEME_FIND_HIDE",label:"Hide",about:"Comics, monochrome, sketches or chibi, told by tag in every site's spelling — checked as posts arrive",choices:gu,multi:{read:so,none:"none"},advanced:!0},{name:"TTHEME_FIND_HIDE_TAGS",label:"Hide tags",about:"Posts with any of these tags are left out, spaced like cosplay multiple_girls — checked as posts arrive",choices:[],entry:"text",advanced:!0},{name:"TTHEME_FIND_PNG",label:"PNG only",about:"PNG originals only — danbooru counts it, the others are told by the file; zerochan only where danbooru holds it",choices:["off","on"],advanced:!0}];function Op(e,t){if(e.multi)return e.multi.read(t).join(" ")||e.multi.none;if(e.entry==="number")return/^\d+$/.test(t??"")&&Number(t)>0?String(Number(t)):"off";if(e.entry==="text")return Hi(t).join(" ");return e.choices.find((n)=>n===t)??e.choices[0]}var xE=["fit","newest","score"];function Dc(e){return xE.find((t)=>t===e)??"fit"}function DE(e){return e.length>=2&&!/^\d+$/.test(e)&&!e.includes("://")&&!/^[\w.]+:\d+$/.test(e)}var Tp=12,ev=4,tv=150,nv=300,Ap=12,rv=2,iv=150,sv=30,ov=4000,av=8000,Hp=/\.(png|jpe?g|gif|webp|heic|tiff?|bmp)$/i,uv=process.platform==="win32"?"alt+v":"ctrl+v",Lp=process.platform==="darwin"?"ctrl+shift+cmd+4 copies a screenshot":"copy a picture first",cv=1280,Gp=2,lv=80,hv=16,fv=0.4,dv=3221225472,gv=256,mv=3,pv=8;function ma(e,t){return{key:e,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:t,stage:"fetch",arrived:new Set}}function Ns(e){if(!(e instanceof Error))return String(e);if(e instanceof AggregateError&&e.errors[0])return Ns(e.errors[0]);if(e.cause)return Ns(e.cause);let t=e.code;if(typeof t==="string")return t;let n=(e.message||e.name).split(".")[0]??"";return n.length>56?`${n.slice(0,55)}…`:n}function el(e,t){return`${e}: ${Ns(t)}`}function Up(e){return e.width*e.height}function _p(e,t){return`${e}-${Cp("sha1").update(t).digest("hex").slice(0,8)}`}function wv(e){let t=e.lastIndexOf("\x1B");return t!==-1&&/^\[?[0-9;]*$/.test(e.slice(t+1))}function tl(e,t){try{return JSON.parse(jp(Gt(Ft(e),t),"utf8"))}catch{return{}}}function nl(e,t,n){Ss(Ft(e),{recursive:!0}),Is(Gt(Ft(e),t),`${JSON.stringify(n)}
517
- `)}class Wp{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(gr.map((e)=>[e.name,Op(e,process.env[e.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 Xc;sent=new Map;placed=new Map;screen=[];ticking;gliding;showing;thumbless=new Set;bands=Kr(process.env)==="iterm2";bandFiles=new Map;nextBand=dv;current;fetch;settle;partial;suggestTimer;suggesting;countTimer;counting;input="";typed="";grabber=new Wc((e)=>this.write(e),(e)=>void this.got(e));featureWait;noticeTimer;peekTimer;peeked;attaching;probeWait;done;dirty=!1;scratch=zE(Gt(VE(),"ttheme-find-"));home;catalog;entry;blurring;constructor(e,t,n,r){this.home=e,this.catalog=t,this.entry=n,this.tone=Gr(n,n.signatureSlots),this.blurring=Qr(e),this.view={palette:n.name,tag:r,site:this.tabName,siteAnsi:this.tabAnsi,nextSite:this.nextTabName,preset:this.setting("TTHEME_FIND_POSTS")==="all"?"all":"cutouts",order:Dc(this.setting("TTHEME_FIND_ORDER")),solo:this.setting("TTHEME_FIND_SOLO")==="on",rating:zn(this.setting("TTHEME_FIND_RATING")),block:Or(this.setting("TTHEME_FIND_BLOCK")),sets:this.setting("TTHEME_FIND_SETS")==="show"?"show":"fold",narrow:this.narrowed(),enabled:Ai(this.setting("TTHEME_FIND_SITES")),hide:so(this.setting("TTHEME_FIND_HIDE")),hideTags:Hi(this.setting("TTHEME_FIND_HIDE_TAGS")),advanced:!1,settings:gr.map((i)=>({label:i.label,choices:[...i.choices],value:this.setting(i.name),default:Op(i,Zu(i.name)),multi:i.multi&&{none:i.multi.none},about:i.about,entry:i.entry,advanced:i.advanced,cursor:0})),colors:{cursor:n.cursor,selection:n.selection,background:n.background,foreground:n.foreground,ansi:n.ansi},tiles:[],installed:[],checked:0,total:0,searching:r!=="",stage:"fetch",sites:[],focus:0,top:0,scroll:0,beat:0,mode:"grid",help:!1,editing:r===""?"":void 0},this.board=ma(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:te[this.tab-1]}get sites(){return this.site?[this.site]:te.filter((e)=>this.view.enabled.includes(e.name))}get tabName(){return this.site?.name??"all"}get tabAnsi(){return this.site?.ansi??ev}get nextTabName(){let e=(this.tab+1)%(te.length+1);return e===0?"all":te[e-1].name}frame(){return{w:this.cols*(this.cell.w||10),h:this.rows*(this.cell.h||20)}}setting(e){return this.values.get(e)}narrowed(){return pu(this.setting("TTHEME_FIND_MIN_SCORE"),this.setting("TTHEME_FIND_MIN_SIZE"),this.setting("TTHEME_FIND_PNG"))}get boardKey(){return`${this.site?.key??"all"}|${this.view.preset}|${this.view.order}`}origPath(e,t,n){return Gt(Ft(e),"orig",`${t}.${n}`)}previewPath(e){let{url:t}=uo(e.site,e.post);return Gt(Ft(e.site),"thumb",`${_p(e.post.id,t)}.${Sn(t)}`)}tileOf(e,t){let{site:n,post:r}=e,i=Rt(n,r.id),s=rn(r)??r;return{id:r.id,key:i,site:n.name,siteAnsi:n.ansi,width:s.width,height:s.height,reduced:s!==r,owner:r.owner,artist:n===oa?Ym(r.source):r.artist,score:r.score,variants:t,origin:ro(r.source),mates:this.owners.get(n.key)?.get(r.owner)??[],thumb:this.thumbPath.get(i),missing:this.thumbless.has(i)}}show(){let e=this.view,t=this.board;if(e.tiles=t.groups.flatMap((n)=>n.open?n.posts.map((r)=>this.tileOf(r,0)):[this.tileOf(n.posts[0],n.posts.length)]),e.checked=t.checked,e.total=t.total,e.searching=t.searching,this.stageOf(t),e.note=t.note,e.focus=Math.max(0,Math.min(t.focus,e.tiles.length-1)),e.top=t.top,this.showing!==t)this.showing=t,this.snap()}stageOf(e){let t=this.view;t.stage=e.stage,t.ranking=e.ranking,t.sites=this.sites.map((n)=>({name:n.name,arrived:e.arrived.has(n.name)}))}syncSite(){let e=this.view;e.site=this.tabName,e.siteAnsi=this.tabAnsi,e.nextSite=this.nextTabName}async run(){let{stdin:e,stdout:t}=process;e.setRawMode(!0),e.resume(),e.on("data",this.onData),t.on("resize",this.onResize),this.write("\x1B[?25l\x1B[?7l\x1B[H\x1B[K\x1B[2H\x1B[J\x1B[H");let n=new Promise((o)=>{this.done=o}),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 s=await n;return this.session.abort(),this.grabber.stop(),this.write("\x1B[?1004l"),this.attaching?.abort(),clearTimeout(this.noticeTimer),clearTimeout(this.peekTimer),this.fetch?.abort(),clearTimeout(this.settle),clearTimeout(this.partial),this.quietSuggest(),this.quietCount(),clearInterval(r),clearInterval(this.ticking),clearTimeout(this.gliding),e.off("data",this.onData),t.off("resize",this.onResize),this.write("\x1B_Ga=d,d=A,q=2\x1B\\\x1B[H\x1B[K\x1B[2H\x1B[J\x1B[H"),e.setRawMode(!1),e.pause(),this.saveProbes(),this.renders.close(),da(this.scratch,{recursive:!0,force:!0}),Bf(),s}write(e){process.stdout.write(e)}get saved(){return this.view.saved}finish(e){this.done?.(e===2&&this.saved?0:e)}probe(){return new Promise((e)=>{let t=setTimeout(()=>{this.probeWait=void 0,e(null)},1000);this.probeWait=(n)=>{clearTimeout(t),this.probeWait=void 0,e(n)},this.write(lp)})}onData=(e)=>{this.input+=e.toString("utf8");for(let n=qc(this.input);n;n=qc(this.input))this.input=n.rest,this.probeWait?.(n.cell);if(this.probeWait)return;let t=xm(this.input);if(this.input=t.pending,this.view.editing===void 0&&t.keys.length>8&&/^(?:\/|~\/|file:|https?:)/.test(t.keys))this.pasted(t.keys),t.keys="";this.typed+=t.keys;for(let n of t.events)this.inbound(n);if(clearTimeout(this.partial),wv(this.typed)){this.partial=setTimeout(this.flushKeys,sv);return}this.flushKeys()};flushKeys=()=>{let e=cp(this.typed);this.typed="";for(let t of e)this.key(t)};features(){if(process.env.TMUX)return Promise.resolve();return new Promise((e)=>{let t=setTimeout(()=>{this.featureWait=void 0,e()},500);this.featureWait=()=>{clearTimeout(t),this.featureWait=void 0,e()},this.write("\x1B[?5522$p\x1B]72;t=q\x1B\\\x1B[c")})}inbound(e){if(e.kind==="mode"){if(e.mode===5522)this.grabber.clipboard=e.value!==0&&e.value!==4;return}if(e.kind==="attributes"){this.featureWait?.();return}if(e.kind==="osc"){if(e.code==="72"&&e.meta.t==="q"){this.grabber.drops=!0;return}this.grabber.take(e);return}this.pasted(e.text)}pasted(e){let t=this.view;if(t.editing!==void 0&&e.trim()!==""&&!this.picture(e)){t.editing+=e.replace(/[\r\n]+/g," "),this.suggest(),this.draw();return}if(t.installing!==void 0||t.panel!==void 0||t.help)return;if(e.trim()===""){this.fromClipboard();return}this.attach(e)}picture(e){let t=e.trim();if(/^https?:\/\/\S+$/i.test(t))return!oo(t,this.site??te[0]);return sa(t).length>0}async got(e){if(e.kind==="error"){this.notice(e.message);return}if(e.kind==="text"){if(e.text.trim()===""){this.notice(`No picture on the clipboard — ${Lp}`);return}this.pasted(e.text);return}await this.bring(()=>ra(e.bytes,e.source))}notice(e,t=ov){let n=this.view;n.error=e,clearTimeout(this.noticeTimer),this.noticeTimer=setTimeout(()=>{if(n.error===e)n.error=void 0,this.draw()},t),this.draw()}async peek(){let e=this.view,t;try{t=await Xm()}catch{return}if(!t||t.stamp===this.peeked)return;if(this.peeked=t.stamp,!t.picture||e.installing!==void 0)return;e.hint=`Picture on the clipboard · ${uv} uses it`,clearTimeout(this.peekTimer),this.peekTimer=setTimeout(()=>{e.hint=void 0,this.draw()},av),this.draw()}async fromClipboard(){let e=this.view;if(jc()){if(this.grabber.clipboard){this.grabber.ask();return}this.notice("Over SSH the clipboard is not here — drop the file");return}let t;try{t=await Vm(Gt(this.scratch,`clipboard-${Date.now()}.png`))}catch(r){this.notice(`Could not read the clipboard: ${Ns(r)}`);return}if(clearTimeout(this.peekTimer),e.hint=void 0,"image"in t){await this.bring(async(r)=>({...await Cc(t.image,r),source:"clipboard"}));return}let n=t.text.trim();if(!n){this.notice(`No picture on the clipboard — ${Lp}`);return}if(this.picture(n)){await this.attach(n);return}if(e.editing===void 0)e.editing="";this.pasted(n)}async attach(e){let t=e.trim();if(/^https?:\/\//i.test(t)){let i=oo(t,this.site??te[0]);if(i){await this.jump(i.site,i.id);return}}let[n,...r]=sa(t).sort((i,s)=>Number(!Hp.test(i))-Number(!Hp.test(s)));if(!n){this.notice("Nothing to use in that — drop a picture, or paste one or its link");return}await this.bring((i)=>Cc(n,i),r.length)}async bring(e,t=0){let n=this.view;this.attaching?.abort();let r=new AbortController;this.attaching=r,n.error=void 0,n.saved=void 0,n.note="Reading the picture…",this.draw();let i;try{i=await e(AbortSignal.any([r.signal,this.signal]))}catch(f){if(!r.signal.aborted)n.note=void 0,this.notice(Ns(f),8000);return}if(r.signal.aborted)return;n.note=t>0?`The first picture of ${t+1} — drop one at a time to try the others`:void 0,this.quietSuggest(),n.editing=void 0,n.suggest=void 0,n.pick=void 0;let s=zm(i.bytes);Zm(s,i.source);let o=this.origPath(oa,s,i.ext);Ss(ga(o),{recursive:!0}),Is(o,i.bytes);let a=XE(o).href,u={id:s,file:a,width:i.width,height:i.height,ext:i.ext,preview:a,owner:"",artist:"",score:0,rating:"s",md5:Cp("md5").update(i.bytes).digest("hex"),source:i.source,tags:[],solo:void 0,family:0,smaller:[]},c={site:oa,post:u},l=this.previewPath(c);Ss(ga(l),{recursive:!0}),Is(l,i.bytes),++this.gen,this.current=void 0,n.shown=void 0;let h=ma(`local|post:${s}`,!1);this.board=h,this.boards.set(h.key,h),this.single(h,c)}single(e,t){e.searching=!1,this.posts.set(Rt(t.site,t.post.id),t),e.groups=[{posts:[t],open:!1}],e.checked=1,e.total=1,this.thumbQueue.push(t),this.thumbs(),this.view.mode="try",this.show(),this.select(),this.draw()}onClock=()=>{let e=this.sites.reduce((r,i)=>Mn(i)>Mn(r)?i:r),t=Math.ceil((Mn(e)-Date.now())/1000),n=t>0?t:void 0;if(n!==this.view.waiting)this.view.waiting=n,this.view.slow=e.name,this.draw()};onResize=()=>{if(this.cols=process.stdout.columns||this.cols,this.rows=process.stdout.rows||this.rows,this.screen=[],this.scroll(),this.snap(),this.view.mode==="try"&&this.current)this.reveal();this.pump(),this.draw()};key(e){let t=this.view;if(e==="ctrl-c"){this.finish(2);return}if(t.installing!==void 0)return;if(e==="focus-in"){this.peek();return}if(e==="focus-out"||e==="nop")return;if((e==="ctrl-v"||e==="alt-v")&&t.panel===void 0){this.fromClipboard();return}if(t.editing!==void 0){this.editKey(e);return}if(t.panel!==void 0){this.panelKey(e);return}if(t.help){if(e==="?"||e==="esc")t.help=!1,this.draw();return}if(this.cols<fr.cols||this.rows<fr.rows){if(e==="esc")this.finish(2);return}if(e==="?"){t.help=!0,this.draw();return}if(t.mode==="try"){this.tryKey(e);return}this.gridKey(e)}gridKey(e){let t=this.view,{perRow:n,rowsVis:r}=dr(this.cols,this.rows),s={left:-1,right:1,up:-n,down:n,pgup:-n*r,pgdn:n*r,home:-t.focus,end:t.tiles.length}[e];if(s!==void 0){this.focus(t.focus+s);return}if(e==="enter"&&t.tiles[t.focus]){t.mode="try",t.error=void 0,this.select();return}if(e==="v"){this.fromClipboard();return}if(e==="c"){t.preset=t.preset==="cutouts"?"all":"cutouts",this.turn();return}if(e==="tab"){this.tab=(this.tab+1)%(te.length+1),this.syncSite(),this.turn();return}if(e==="/"){t.editing="",this.draw();return}if(e===" "){this.unfold();return}if(e==="o"){this.openPage();return}if(e==="s"){t.panel=0,t.advanced=!1,this.recount(),this.draw();return}if(e==="esc")this.finish(2)}panelKey(e){let t=this.view,n=t.panel??0,r=t.settings[n];if(t.typing!==void 0&&r){this.typeKey(r,e);return}let i=Ms(t);if(e==="up"||e==="down"){let s=i.indexOf(n)+(e==="up"?-1:1);t.panel=i[Math.max(0,Math.min(i.length-1,s))]??n,this.draw();return}if(e==="a"||e==="enter"&&n===t.settings.length){t.advanced=!t.advanced,t.panel=Ms(t)[0]??0,this.draw();return}if(r?.entry&&(e==="enter"||r.entry==="number"&&/^[0-9]$/.test(e))){t.typing=e==="enter"?r.entry==="text"?r.value:"":e,this.draw();return}if((e==="left"||e==="right")&&r&&r.entry!=="text"){let s=e==="left"?-1:1;if(r.multi)r.cursor=(r.cursor+s+r.choices.length)%r.choices.length;else r.value=$p(r.choices,r.value,s),this.recount();this.draw();return}if(e===" "&&r?.multi){let s=r.value.split(" "),o=r.choices.filter((u,c)=>c===r.cursor?!s.includes(u):s.includes(u)),a=r.multi.none;if(o.length>0||a!==void 0)r.value=o.length>0?o.join(" "):a,this.recount(),this.draw();return}if(e==="esc"){t.settings.forEach((s,o)=>{s.value=this.setting(gr[o]?.name??"")}),t.panel=void 0,t.advanced=!1,this.quietCount(),this.draw();return}if(e==="enter"||e==="s"||e==="alt-c")t.panel=void 0,t.advanced=!1,this.quietCount(),this.adopt()}typeKey(e,t){let n=this.view,r=n.typing??"";if(t==="esc"){n.typing=void 0,this.draw();return}if(t==="enter"||t==="up"||t==="down"){if(e.value=e.entry==="number"?Number(r)>0?String(Number(r)):"off":Hi(r).join(" "),n.typing=void 0,this.recount(),t==="enter"){this.draw();return}this.panelKey(t);return}if(t==="backspace"){n.typing=r.slice(0,-1),this.draw();return}if(e.entry==="number"?/^[0-9]$/.test(t)&&r.length<Qc:/^[\x20-\x7e]$/.test(t))n.typing=r+t,this.draw()}quietCount(){clearTimeout(this.countTimer),this.counting?.abort(),this.counting=void 0}recount(){if(this.quietCount(),this.view.counts=void 0,!this.view.tag)return;let e=new AbortController;this.counting=e,this.countTimer=setTimeout(()=>void this.countPending(e),nv)}pending(){let e=(t)=>this.view.settings[gr.findIndex((n)=>n.name===t)]?.value??this.setting(t);return{tag:this.view.tag,preset:e("TTHEME_FIND_POSTS")==="all"?"all":"cutouts",order:Dc(e("TTHEME_FIND_ORDER")),rating:zn(e("TTHEME_FIND_RATING")),narrow:pu(e("TTHEME_FIND_MIN_SCORE"),e("TTHEME_FIND_MIN_SIZE"),e("TTHEME_FIND_PNG")),enabled:Ai(e("TTHEME_FIND_SITES"))}}async countPending(e){let t=this.pending(),n=this.site?[this.site]:te.filter((s)=>t.enabled.includes(s.name)),r=AbortSignal.any([this.signal,e.signal]),i=await Promise.all(n.map(async(s)=>{let o=this.query(s,t);if(!o)return{site:s.name,count:0};if(s.counts&&!s.counts(o.tags))return{site:s.name};try{let a=await yu(s,o.tags,r);return{site:s.name,...Number.isFinite(a)?{count:a}:{}}}catch{return{site:s.name}}}));if(this.counting===e&&this.view.panel!==void 0)this.view.counts=i,this.draw()}adopt(){let e=this.view,t=gr.map((r)=>this.setting(r.name));e.settings.forEach((r,i)=>{let s=gr[i];if(s)this.values.set(s.name,r.value)});let n=gr.filter((r,i)=>this.setting(r.name)!==t[i]);if(n.length===0){this.draw();return}this.save(n),e.rating=zn(this.setting("TTHEME_FIND_RATING")),e.block=Or(this.setting("TTHEME_FIND_BLOCK")),e.sets=this.setting("TTHEME_FIND_SETS")==="show"?"show":"fold",e.preset=this.setting("TTHEME_FIND_POSTS")==="all"?"all":"cutouts",e.order=Dc(this.setting("TTHEME_FIND_ORDER")),e.solo=this.setting("TTHEME_FIND_SOLO")==="on",e.narrow=this.narrowed(),e.enabled=Ai(this.setting("TTHEME_FIND_SITES")),e.hide=so(this.setting("TTHEME_FIND_HIDE")),e.hideTags=Hi(this.setting("TTHEME_FIND_HIDE_TAGS")),this.boards.clear(),this.current=void 0,e.shown=void 0,e.mode="grid",this.search()}save(e){this.store(e.map((t)=>[t.name,this.setting(t.name)]))}store(e){let t=Gt(this.home,"ttheme","config.zsh");try{let n=si(t)?jp(t,"utf8"):"";return Is(t,e.reduce((r,[i,s])=>dg(r,i,s),n)),!0}catch(n){return this.view.error=n instanceof Error?n.message:String(n),!1}}editKey(e){let t=this.view,n=t.editing??"",r=t.suggest??[];if((e==="up"||e==="down")&&r.length>0){let i=t.pick??-1,s=e==="down"?Math.min(r.length-1,i+1):i-1;t.pick=s<0?void 0:s,this.draw();return}if(e==="esc"||e==="enter")this.quietSuggest();if(e==="esc"){if(t.editing=void 0,t.tag===""){this.finish(2);return}this.draw();return}if(e==="enter"){let i=t.pick===void 0?void 0:r[t.pick],s=i?n.replace(/\S*$/,i.value):n;if(t.editing=void 0,t.suggest=void 0,t.pick=void 0,s.trim()){this.commit(s.trim());return}if(t.tag===""){this.finish(2);return}this.draw();return}if(e==="backspace"){t.editing=n.slice(0,-1),this.suggest(),this.draw();return}if(e.length===1&&e>=" ")t.editing=n+e,this.suggest(),this.draw()}quietSuggest(){clearTimeout(this.suggestTimer),this.suggesting?.abort(),this.suggesting=void 0}suggest(){this.quietSuggest();let e=this.view;e.pick=void 0;let t=/\S*$/.exec(e.editing??"")?.[0]??"";if(!DE(t)){e.suggest=void 0;return}let n=[...new Map(xd(this.catalog.palettes,this.entry,t).map((i)=>[i.booru,{value:i.booru,count:0,palette:i.name}])).values()].slice(0,mv);e.suggest=n.length>0?n:void 0;let r=new AbortController;this.suggesting=r,this.suggestTimer=setTimeout(async()=>{try{let i=await Df(t,AbortSignal.any([this.signal,r.signal]));if(this.suggesting===r&&e.editing!==void 0){let s=new Map(i.map((a)=>[a.value,a.count])),o=new Set(n.map((a)=>a.value));e.suggest=[...n.map((a)=>({...a,count:s.get(a.value)??0})),...i.filter((a)=>!o.has(a.value))].slice(0,pv),e.pick=e.pick!==void 0&&e.pick<n.length?e.pick:void 0,this.draw()}}catch{}},tv)}async commit(e){let t=oo(e,this.site??te[0]);if(t){await this.jump(t.site,t.id);return}if(this.picture(e)){await this.attach(e);return}this.view.tag=e,this.boards.clear(),await this.search()}async jump(e,t){let n=++this.gen;this.tab=te.indexOf(e)+1,this.syncSite(),this.current=void 0,this.view.shown=void 0,this.view.error=void 0;let r=ma(`${e.key}|post:${t}`,!0);this.board=r,this.boards.set(r.key,r),this.show(),this.draw();try{let i=await Li(e,t,this.signal);if(n!==this.gen)return;if(!i){r.searching=!1,r.error=`${e.name} has no post ${t}`,this.view.error=r.error,this.show(),this.draw();return}this.single(r,{site:e,post:i})}catch(i){this.fail(n,i,e)}}async turn(){this.fetch?.abort(),this.current=void 0,this.view.shown=void 0;let e=this.boards.get(this.boardKey);if(!e){await this.search();return}this.gen++,this.board=e,this.view.error=e.error,this.show(),this.draw(),await this.pump()}unfold(){let e=this.view,t=0;for(let n of this.board.groups){let r=n.open?n.posts.length:1;if(e.focus<t+r){if(n.posts.length<2)return;n.open=!n.open,this.board.focus=t;for(let i of n.posts)if(!this.thumbPath.has(Rt(i.site,i.post.id)))this.thumbQueue.push(i);this.thumbs(),this.show(),this.scroll(),this.glide(),this.draw();return}t+=r}}openPage(){let e=this.view.tiles[this.view.focus],t=e&&this.posts.get(e.key);if(!t)return;let n=process.platform==="darwin"?"open":"xdg-open";try{ZE(n,[t.site.pageUrl(t.post.id)],{stdio:"ignore",detached:!0}).unref()}catch{}}tryKey(e){let t=this.view;if(e==="left"||e==="right"){this.direction=e==="left"?-1:1,this.focus(t.focus+this.direction);return}if(e==="o"){this.openPage();return}if(e==="x"){this.swap();return}if(e==="v"){this.fromClipboard();return}if(e==="enter"){this.install();return}if(e==="esc")this.fetch?.abort(),clearTimeout(this.settle),t.fetching=void 0,t.mode="grid",t.error=void 0,this.draw()}focus(e){let t=this.view;if(t.tiles.length===0)return;let n=Math.max(0,Math.min(t.tiles.length-1,e));if(n===t.focus)return;if(t.focus=n,this.board.focus=n,this.scroll(),this.glide(),this.pump(),t.mode==="try")this.select();this.draw()}scroll(){let e=this.view,{perRow:t,rowsVis:n}=dr(this.cols,this.rows),r=Math.floor(e.focus/t);if(r<e.top)e.top=r;if(r>e.top+n-1)e.top=r-n+1;this.board.top=e.top}glide(){if(this.bands)this.prebake();if(this.gliding)return;let e=dr(this.cols,this.rows).height,t=()=>{let n=this.view,r=n.top*Ke.height,i=r-n.scroll;if(i===0||n.mode!=="grid"){n.scroll=r;let s=this.gliding!==void 0;if(this.gliding=void 0,s)this.draw();return}if(Math.abs(i)>2*e)n.scroll=r-Math.sign(i)*e,i=r-n.scroll;n.scroll+=Math.sign(i)*Math.max(1,Math.round(Math.abs(i)*fv)),this.draw(),this.gliding=setTimeout(t,hv)};t()}snap(){clearTimeout(this.gliding),this.gliding=void 0,this.view.scroll=this.view.top*Ke.height}prebake(){let e=this.view;for(let t of Yc({...e,scroll:e.top*Ke.height},this.cols,this.rows).images)if(t.crop!==void 0)this.band(t.path,t.crop,t.rows)}query(e,t=this.view){let n=t.tag===this.entry.booru?Dd(this.entry,e.key):[t.tag];if(n.length===0)return;let r=n.length>1,i=t.preset==="cutouts"?e.cutouts:"",s=r&&i.includes("~"),o=[r?n.map((c)=>`~${c}`).join(" "):n[0],e.rate(t.rating),...e.narrow(t.narrow),s?"":i,t.order==="score"?e.best:""].filter(Boolean),a=[],u=[];for(let c of o)if($u([...a,c].join(" "))<=e.tagBudget)a.push(c);else u.push(c);return{tags:a.join(" "),notes:[...u.length>0?[`${e.name} takes ${e.tagBudget} tags — ${u.join(" ")} left out`]:[],...s?[`${e.name} ORs the names, so cutouts are told by the file`]:[],...t.narrow.score>0&&!e.scored?[`${e.name} keeps no score`]:[],...t.narrow.png&&e.guesses?[`${e.name} names a file type only where danbooru holds the file`]:[]]}}async search(){let e=++this.gen,t=ma(this.boardKey,!0);this.board=t,this.boards.set(t.key,t),this.view.error=void 0;let n=this.sites.flatMap((s)=>{let o=this.query(s);return o?[{site:s,...o}]:[]}),r=this.sites.filter((s)=>!n.some((o)=>o.site===s)),i=[...n.flatMap(({notes:s})=>s),...r.length>0?[`${this.entry.name} has no tag on ${r.map((s)=>s.name).join(", ")}`]:[]];if(t.note=i.length>0?i.join(" · "):void 0,n.length===0)t.searching=!1;this.show(),this.draw(),this.tally(e,t,n);try{let s=await Promise.all(n.map(async(o)=>({plan:o,owners:await this.mateOwners(o.site)})));if(e!==this.gen)return;t.sources=s.flatMap(({plan:{site:o,tags:a},owners:u})=>[...$u(a)+1<=o.tagBudget?[...u.keys()].map((c)=>({site:o,tags:`${a} user:${c}`,page:0,done:!1})):[],{site:o,tags:a,page:0,done:!1}]),this.show(),this.draw(),await this.pump()}catch(s){this.fail(e,s)}}async tally(e,t,n){let r=await Promise.allSettled(n.map(({site:i,tags:s})=>yu(i,s,this.signal)));if(e===this.gen)t.total=r.reduce((i,s)=>i+(s.status==="fulfilled"&&Number.isFinite(s.value)?s.value:0),0),this.show(),this.draw()}fail(e,t,n=this.site){if(e!==this.gen||this.signal.aborted)return;this.board.error=el(n?.name??this.tabName,t),this.board.searching=!1,this.view.error=this.board.error,this.show(),this.draw()}drop(e,t,n){for(let r of e.sources)if(r.site===t)r.done=!0;e.note=[e.note,el(t.name,n)].filter(Boolean).join(" · ")}wants(){let{perRow:e,rowsVis:t}=dr(this.cols,this.rows);return this.view.tiles.length<(this.board.top+t+Gp)*e}need(){let{perRow:e,rowsVis:t}=dr(this.cols,this.rows);return(t+Gp)*e}live(e){return this.boards.get(e.key)===e}page(e,t,n){let r=`${e.key}|${t}|${n}`,i=this.pages.get(r);if(!i)i=Vf(e,t,n,this.signal).then((s)=>this.borrow(e,s)),this.pages.set(r,i),i.catch(()=>this.pages.delete(r));return i}async borrow(e,t){let n=e===Jt?[]:t.filter((r)=>r.md5!=="");if(n.length>0)try{Xf(n,await xf(n.map((r)=>r.md5),this.signal))}catch{}return t}staged(e){if(e===this.board)this.stageOf(e),this.draw()}async round(e){e.stage="fetch",this.staged(e);let t=te.flatMap((a)=>{let u=e.sources.find((c)=>c.site===a&&!c.done);return u?[u]:[]}),n=await Promise.all(t.map(async(a)=>{try{let u=await this.page(a.site,a.tags,a.page);return e.arrived.add(a.site.name),this.staged(e),{source:a,posts:u}}catch(u){if(e.sources.every((c)=>c.site===a.site)||this.signal.aborted)throw u;return this.drop(e,a.site,u),{source:a,posts:void 0}}}));if(!this.live(e))return;let r=[];for(let{source:a,posts:u}of n){if(!u)continue;a.page++,a.done=u.length<vn;let c=e.last.get(a);for(let l of u){let h=c&&Mp(c.post,l)?c.set:`set:${a.site.key}:${l.id}`;c={post:l,set:h};let f=Rt(a.site,l.id);if(e.seen.has(f))continue;e.seen.add(f);let d={site:a.site,post:l};if(this.eligible(d))e.kin.set(d,[h,...vp(a.site,l)]),r.push(d);else e.checked++}if(c)e.last.set(a,c)}let i=this.dedupe(e,r),s=++e.rounds,o;if(this.view.order!=="fit")o=t.length>1?yp(i):i;else{let a=fa(i,this.frame(),this.matched),u=a.slice(0,this.need()),c={done:0,total:u.length};if(e.ranking=c,this.staged(e),await this.looks(u,()=>{c.done++,this.staged(e)}),e.ranking=void 0,!this.live(e))return;o=[...fa(u,this.frame(),this.matched),...a.slice(u.length)]}e.stage="check",this.staged(e);for(let a of o)e.roundOf.set(a,s);e.queue.push(...o),this.ahead(e)}ahead(e){if(this.aheading||this.view.order!=="fit"||!this.live(e))return;let t=e.queue.slice(0,this.need()).filter((n)=>!this.looking.has(Rt(n.site,n.post.id)));if(t.length===0)return;this.aheading=!0,this.looks(t).then(()=>{this.aheading=!1;for(let n of new Set(t.map((r)=>e.roundOf.get(r)??0)))this.resort(e,n);this.ahead(e)})}resort(e,t){let n=e.queue.flatMap((i,s)=>e.roundOf.get(i)===t?[s]:[]),r=fa(n.map((i)=>e.queue[i]),this.frame(),this.matched);n.forEach((i,s)=>{e.queue[i]=r[s]})}dedupe(e,t){let n=[];for(let r of t){let i=zc(r.post),s=i.map((a)=>e.same.get(a)).find(Boolean);if(!s){for(let a of i)e.same.set(a,r);n.push(r);continue}if(e.checked++,Up(r.post)<=Up(s.post))continue;for(let a of[...i,...zc(s.post)])e.same.set(a,r);let o=n.indexOf(s);if(o>=0){n[o]=r;continue}this.replace(e,s,r)}return n}replace(e,t,n){e.roundOf.set(n,e.roundOf.get(t)??0);let r=e.queue.indexOf(t);if(r>=0){e.queue[r]=n;return}for(let i of e.groups){let s=i.posts.indexOf(t);if(s>=0){i.posts[s]=n,this.posts.set(Rt(n.site,n.post.id),n),this.thumbQueue.push(n),this.thumbs();return}}}async looks(e,t){let n=0;await Promise.all(Array.from({length:Ap},async()=>{while(n<e.length)await this.look(e[n++]),t?.()}))}look(e){let t=Rt(e.site,e.post.id),n=this.looking.get(t);if(!n)n=(async()=>{let r=this.previewPath(e),i=uo(e.site,e.post);await this.cached(i.site,r,i.url);let s=await this.renders.run({job:"match",from:r,colors:this.entry.signature});return this.looked.set(t,s),this.matched.set(e.post,s.match),s})().catch(()=>{return}),this.looking.set(t,n);return n}async pump(){let e=this.gen,t=this.board;if(this.pumping===e||t.sources.length===0)return;this.pumping=e;let n=[],r;try{t.searching=!0;while(e===this.gen){while(n.length<Tp&&t.queue.length>0&&this.wants()){let o=t.queue.shift();n.push({pick:o,passed:this.vet(o)})}if(this.ahead(t),!r&&t.queue.length<Tp&&t.sources.some((o)=>!o.done)&&this.wants()){let o=this.round(t).then(()=>{if(r===o)r=void 0});o.catch(()=>{}),r=o}let i=n.shift();if(!i){if(!r)break;await r,this.show(),this.draw();continue}let s=await i.passed;if(e!==this.gen)return;if(t.checked++,s)this.admit(i.pick);this.show(),this.draw()}if(e===this.gen)t.searching=!1,this.show(),this.draw()}catch(i){this.fail(e,i)}finally{if(this.saveProbes(),this.pumping===e)this.pumping=0}}eligible({site:e,post:t}){let n=rn(t);if(!lo(e,t,this.view.rating)||co(t,this.view.block).length>0||!n)return!1;if(this.view.solo&&t.solo===!1)return!1;let{score:r,size:i,png:s}=this.view.narrow;if(Math.min(t.width,t.height)<i||e.scored&&t.score<r||s&&t.ext!=="png"||Zf(t,this.view.hide).length>0||this.view.hideTags.some((o)=>t.tags.includes(o)))return!1;return this.view.preset==="all"?["png","jpg","jpeg",""].includes(n.ext):["png",""].includes(t.ext)}async vet(e){let[t]=await Promise.all([this.passes(e),this.look(e)]);return t}async passes({site:e,post:t}){return this.view.preset==="all"||e.vouched||this.transparent(e,t)}probes(e){let t=this.probed.get(e.key);if(!t)t=tl(e,"probes.json"),this.probed.set(e.key,t);return t}async transparent(e,t){let n=this.probes(e),r=n[t.id];if(r!==void 0)return r;try{let i=await ho(e,t,this.signal),s=ao(e,t),o=(i===void 0?await ed(s.site,s.url,this.signal):i)?.alpha===!0;return n[t.id]=o,this.unsaved.add(e.key),o}catch{return!1}}saveProbes(){for(let e of this.unsaved){let t=te.find((n)=>n.key===e);if(t)nl(t,"probes.json",this.probes(t))}this.unsaved.clear()}admit(e){let{site:t,post:n}=e,r=this.board,i=Rt(t,n.id);this.posts.set(i,e);let s=r.kin.get(e)??[],o=this.looked.get(i),a=o&&{hash:o.hash,width:n.width,height:n.height},u=this.view.sets==="fold"?this.kindred(r,s,a):void 0;if(u){if(u.posts.push(e),this.register(r,u,s,a),u.open)this.thumbQueue.push(e),this.thumbs();return}let c={posts:[e],open:!1};r.groups.push(c),this.register(r,c,s,a),this.thumbQueue.push(e),this.thumbs()}kindred(e,t,n){for(let r of t){let i=e.kindred.get(r);if(i)return i}return n&&e.shapes.find((r)=>Ip(r.shape,n))?.group}register(e,t,n,r){for(let i of n)if(!e.kindred.has(i))e.kindred.set(i,t);if(r)e.shapes.push({shape:r,group:t})}async mateOwners(e){let t=this.owners.get(e.key);if(t)return t;let n=Pd(this.home),r=tl(e,"owners.json"),i=this.catalog.palettes.flatMap((u)=>{let c=n.get(u.name);return u.group===this.entry.group&&u.name!==this.entry.name&&c?.site===e.key?[{name:u.name,id:c.id}]:[]}),s=await Promise.all(i.map(async(u)=>{let c=r[u.id];if(c!==void 0)return{...u,owner:c};try{return{...u,owner:(await Li(e,u.id,this.signal))?.owner??""}}catch{return}})),o=new Map;for(let u of s)if(u)r[u.id]=u.owner,o.set(u.name,u.owner);nl(e,"owners.json",r);let a=zf(o);return this.owners.set(e.key,a),a}async cached(e,t,n,r){if(si(t))return BE(t).size;let i=this.inflight.get(t);if(i)return i;let s=(async()=>{let o=await fo(e,n,this.signal,r);return Ss(ga(t),{recursive:!0}),Is(t,o),o.length})();this.inflight.set(t,s);try{return await s}finally{this.inflight.delete(t)}}thumbs(){while(!this.signal.aborted&&this.thumbing<Ap&&this.thumbQueue.length>0){let e=this.thumbQueue.shift();this.thumbing++,this.thumb(e).catch(()=>{this.thumbless.add(Rt(e.site,e.post.id)),this.show(),this.draw()}).finally(()=>{this.thumbing--,this.thumbs()})}}async thumb(e){let{site:t,post:n}=e,r=Ke.cols*this.cell.w,i=Ke.rows*this.cell.h,s=uo(t,n),o=Gt(Ft(t),"tile",`${_p(n.id,s.url)}-${r}x${i}.png`);if(!si(o)){let a=this.previewPath(e);if(await this.cached(s.site,a,s.url),this.signal.aborted)return;await this.renders.run({job:"thumb",from:a,to:o,width:r,height:i})}this.thumbPath.set(Rt(t,n.id),o),this.show(),this.draw()}select(){let e=this.view,t=e.tiles[e.focus];if(this.fetch?.abort(),clearTimeout(this.settle),e.fetching=void 0,!t)return;if(this.current?.key===t.key){this.reveal();return}this.settle=setTimeout(()=>void this.load(t),iv),this.draw()}async load(e){let t=this.view,n=this.posts.get(e.key);if(!n||!rn(n.post))return;let{site:r}=n,i=this.board,s=new AbortController;this.fetch=s;try{await ho(r,n.post,s.signal);let o=rn(n.post),a=this.origPath(r,e.id,o.ext);if(!si(a))t.fetching={id:e.key,got:0,size:0},this.draw();let u=ao(r,n.post,o),c=await this.cached(u.site,a,u.url,(f,d)=>{if(t.fetching?.id===e.key)t.fetching={id:e.key,got:f,size:d},this.draw()});if(s.signal.aborted)return;if(t.fetching=void 0,i!==this.board)return;let l={site:r,id:e.id,key:e.key,path:a,ext:o.ext,size:c,using:"plain",failed:!1};t.preparing=e.key,this.flush();let h=await this.render(l,"plain");if(s.signal.aborted||i!==this.board)return;if(h.clear===0&&Xr()&&this.setting("TTHEME_FIND_REMOVE_BG")!=="off"){if(t.preparing=void 0,t.cutting=e.key,this.flush(),l.cut=await this.cutOut(r,e.id,a,s.signal),s.signal.aborted||i!==this.board)return;if(t.cutting=void 0,l.cut){t.preparing=e.key,this.flush();let f=await this.render(l,"cut").catch(()=>{return});if(s.signal.aborted||i!==this.board)return;if(f&&jo(f.clear))l.using="cut";else da(l.cut,{force:!0}),l.cut=void 0,l.failed=!0}else l.failed=!0}if(this.current=l,t.tiles[t.focus]?.key===e.key)await this.present();this.preload()}catch(o){if(!s.signal.aborted&&!this.signal.aborted)t.error=el(r.name,o)}finally{if(t.fetching?.id===e.key)t.fetching=void 0;if(t.preparing===e.key)t.preparing=void 0;if(t.cutting===e.key)t.cutting=void 0;this.draw()}}async cutOut(e,t,n,r){let i=Gt(Ft(e),"cut",`${t}.png`);if(si(i))return i;try{return Ss(ga(i),{recursive:!0}),await us(n,i,r),i}catch{da(i,{force:!0});return}}swap(){let e=this.current;if(!e?.cut||this.view.shown?.id!==e.key)return;e.using=e.using==="cut"?"plain":"cut",this.reveal()}preload(){let e=this.view;if(e.mode!=="try")return;for(let t of[e.focus+this.direction,e.focus-this.direction]){if(this.prefetching>=rv)return;let n=e.tiles[t],r=n&&this.posts.get(n.key);if(!r||!rn(r.post))continue;let{site:i,post:s}=r;this.prefetching++,ho(i,s,this.signal).then(async()=>{let o=rn(s),a=this.origPath(i,s.id,o.ext),u=ao(i,s,o);return await this.cached(u.site,a,u.url),this.render({site:i,id:s.id,key:n.key,path:a,ext:o.ext,size:0,using:"plain",failed:!1},"plain")}).catch(()=>{}).finally(()=>{this.prefetching--})}}async render(e,t){let n=this.cols*this.cell.w,r=this.rows*this.cell.h,i=Math.min(n,cv),s=Math.max(1,Math.round(r*i/n)),o=Gt(this.scratch,`${e.site.key}-${e.id}${t==="cut"?"c":""}-${i}x${s}.png`),a=`${e.site.key}:${e.id}:${t}`,u=this.clarity.get(a);if(u!==void 0&&si(o))return{clear:u,path:o};let c=await this.renders.run({job:"show",from:t==="cut"?e.cut:e.path,to:o,width:i,height:s,colors:this.entry,tone:this.tone,blur:this.blurring*i/Fu(n,r).width});return this.clarity.set(a,c),{clear:c,path:o}}async present(){let e=this.current;if(!e)return;let t=e.using,{clear:n,path:r}=await this.render(e,t);if(this.current!==e||e.using!==t)return;this.view.shown={id:e.key,clear:n,bytes:e.size,path:r,cut:e.cut?t==="cut"?"on":"off":e.failed?"failed":"none"}}reveal(){let e=this.view;e.preparing=this.current?.key,this.flush(),this.present().catch((t)=>{e.error=t instanceof Error?t.message:String(t)}).finally(()=>{if(e.preparing===this.current?.key)e.preparing=void 0;this.draw()})}async install(){let e=this.view,t=e.tiles[e.focus],n=this.current;if(!t||n?.key!==t.key||e.preparing!==void 0||e.shown?.id!==t.key)return;e.installing=t.key,e.error=void 0,this.flush();try{await this.renders.run({job:"backdrop",from:n.using==="cut"?n.cut:n.path,source:n.path,home:this.home,colors:this.entry,tone:this.tone,origin:{site:n.site.key,id:n.id,ext:n.ext,from:`${n.site.name} ${n.id} ${n.site.pageUrl(n.id)}`},width:this.cols*this.cell.w,height:this.rows*this.cell.h,blur:this.blurring});let r=tl(n.site,"owners.json");r[n.id]=this.posts.get(n.key)?.post.owner??"",nl(n.site,"owners.json",r),Bt(this.home),e.saved=`Background · ${this.entry.name} ← ${n.site.name} ${n.id}`,e.installed.push(t.key),this.fetch?.abort(),clearTimeout(this.settle),e.fetching=void 0,e.mode="grid"}catch(r){e.error=r instanceof Error?r.message:String(r)}e.installing=void 0,this.draw()}draw(){if(this.dirty||this.signal.aborted)return;this.dirty=!0,setImmediate(()=>{this.dirty=!1,this.flush()})}flush(){if(this.signal.aborted)return;let e=Yc(this.view,this.cols,this.rows);this.view.loaderFrom=e.loader?this.view.loaderFrom??this.view.beat:void 0;let t="";e.lines.forEach((r,i)=>{if(this.screen[i]!==r)t+=`\x1B[${i+1};1H\x1B[K${r}`,this.screen[i]=r});let n=new Set;for(let r of e.images){let i=this.bands?this.banded(r):r;if(!i)continue;if(n.add(i.id),this.sent.get(i.id)!==i.path)t+=hp(i),this.sent.set(i.id,i.path),this.placed.delete(i.id);let s=`${i.row};${i.col};${i.cols};${i.rows};${i.crop};${i.z}`;if(this.placed.get(i.id)!==s)t+=fp(i,this.cell),this.placed.set(i.id,s)}for(let r of this.sent.keys())if(!n.has(r))t+=dp(r),this.sent.delete(r),this.placed.delete(r);if(t)this.write(`\x1B[?2026h${t}\x1B[?2026l`);this.pace(e.tick)}pace(e){if(e)this.ticking??=setInterval(()=>{this.view.beat++,this.draw()},lv);else if(this.ticking)clearInterval(this.ticking),this.ticking=void 0}banded(e){if(e.crop===void 0)return e;let t=this.band(e.path,e.crop,e.rows,!this.gliding);return t?.ready?{...e,id:t.id,path:t.path,crop:void 0}:void 0}band(e,t,n,r=!0){let i=`${e}|${t}|${n}`,s=this.bandFiles.get(i);if(s||!r)return s;let o=this.nextBand++,a={id:o,path:Gt(this.scratch,`band-${o}.png`),ready:!1};return this.bandFiles.set(i,a),this.renders.run({job:"band",from:e,to:a.path,y:t*this.cell.h,height:n*this.cell.h}).then(()=>{a.ready=!0,this.draw()}).catch(()=>{}),this.trimBands(),a}trimBands(){for(let[e,t]of this.bandFiles){if(this.bandFiles.size<=gv)return;if(t.ready&&!this.sent.has(t.id))this.bandFiles.delete(e),da(t.path,{force:!0})}}}async function Jp(e){let t=he(),n=Hn(t),r=rr(n.palettes,e);if(!process.stdin.isTTY||!process.stdout.isTTY)throw Error("needs a terminal");let i=new Wp(t,n,r,r.booru??""),s=await i.run();if(i.saved&&s!==0)return process.stderr.write(`${i.saved}
518
- `),0;return s}function Kp(e,t){let n=he();if(rr(Hn(n).palettes,e),t==="next"||t==="prev"){let{key:r,at:i,of:s}=Id(n,e,t==="next"?1:-1);return Bt(n),process.stderr.write(`Background · ${e} ${i}/${s} ${r}
519
- `),0}if(t==="drop"){let{key:r,left:i}=Nd(n,e);return Bt(n),process.stderr.write(`Background · ${e} removed ${r} · ${i} left
520
- `),0}if(t==="tuned")return Bt(n),0;throw Error(`unknown image action ${t} — next, prev, drop or tuned`)}import{execFileSync as Zp,spawnSync as yv}from"node:child_process";import{chmodSync as Ev,copyFileSync as vv,existsSync as gt,mkdirSync as rl,readdirSync as Mv,readFileSync as ai,rmSync as Qp,writeFileSync as Sv}from"node:fs";import{homedir as Iv}from"node:os";import{dirname as oi,join as Ne}from"node:path";import{availableParallelism as bv,homedir as $v}from"node:os";var kv=4;async function pa(e,t,n=$v()){let r=st(We(e)),i=Qr(e),s=new Map(Hn(e).palettes.map((h)=>[h.name,h.backdrop])),o=Object.entries(r.palettes).flatMap(([h,f])=>{let d=s.get(h);return d?f.pictures.filter((g)=>g.tone===void 0||(g.blur??0)!==i).map((g)=>({name:h,key:g.key,hue:d})):[]});if(o.length===0)return 0;t(`Drawing ${o.length} background picture${o.length===1?"":"s"} again${i?` · blur ${i}px`:""}`);let a=!se(e).terminals.includes("iterm2"),u=new xc(Math.min(kv,bv()-1)),c=await u.map(o.map(({name:h,key:f,hue:d})=>({job:"redraw",home:e,user:n,name:h,key:f,hue:d,blur:i,aligns:a})));u.close();let l=[];return c.forEach((h,f)=>{let{name:d,key:g}=o[f];if(h instanceof Error||h===null){t(` ▢ ${d} ${g} — ${h instanceof Error?h.message:"no original to draw it from"}, left as it was`);return}l.push({name:d,picture:h})}),Od(e,l),Bt(e,n),l.length}async function qp(){return await pa(he(),(e)=>process.stderr.write(`${e}
521
- `)),0}function Nv(e,t,n){for(let r of Mv(t))e.push({from:Ne(t,r),to:Ne(n,r)})}function ol(e){return JSON.parse(ai(Ne(e,"dist","manifest.json"),"utf8"))}function ba(e,t){let n=Ne(t.configHome,"ttheme"),r=[{from:Ne(t.root,"bin","ttheme.js"),to:Ne(n,"ttheme.js")},{from:Ne(t.root,"bin","ttheme.js.map"),to:Ne(n,"ttheme.js.map")},{from:Ne(t.root,"shell","ttheme.zsh"),to:Ne(n,"ttheme.zsh")},{from:Ne(t.root,"shell","launch-tab.zsh"),to:Ne(n,"launch-tab.zsh"),executable:!0}];Nv(r,Ne(t.root,"shell","adapters"),Ne(n,"adapters"));let i=[{file:Ne(t.zdotdir,".zshrc"),block:lg(n)}],s=Ne(n,"config.zsh"),o=gg(gt(s)?ai(s,"utf8"):""),a={file:s,content:o},u=[];if(e.terminals.includes("alacritty")){let h=ur(t.configHome);if(gt(h)&&ts(ai(h,"utf8"),void 0)===void 0)u.push(`${h} already imports files under [general] — ttheme left it alone; add ${Ne(t.configHome,"alacritty","themes")}/<palette>.toml to that import list yourself`)}if(e.terminals.includes("wezterm")){let h=Br(t.configHome,t.home);if(gt(h)&&ns(ai(h,"utf8"),"")===void 0)u.push(`${h} has no \`return config\` line — ttheme left it alone; call \`dofile("${Ne(n,"wezterm.lua")}")(config)\` from it yourself`)}let c=e.terminals.includes("windows-terminal");if(c&&!t.wtHome)u.push("Windows Terminal: %LOCALAPPDATA% was not found — drop the release fragment into its Fragments folder yourself");if(e.terminals.includes("warp"))u.push("Warp wears the default palette app-wide through its settings.toml — the shell layer stays off in it, since Warp paints no tab background of its own");let l={terminals:e.terminals,palettes:e.palettes,...c&&t.wtHome?{wtHome:t.wtHome}:{},...c&&t.wtProfile?{wtProfile:t.wtProfile}:{},...e.off?{off:!0}:{}};return u.push(...Gg(t.configHome,e.terminals,t.home)),{home:t.home,copies:r,edits:i,settings:a,catalog:ol(t.root),installed:l,notes:u}}function Rv(e){try{return se(e)}catch{return}}function zp(e){try{return _e(e,Le(e),!1).palettes}catch{return[]}}function Fv(e,t){let n=ol(t.root),r=ze(e.markets).includes(z)?n.palettes:[],i=new Set(r.map((o)=>o.name)),s=zp(t.configHome).filter((o)=>!i.has(o.name)&&(ye(o.name)!==void 0||e.palettes.includes(o.name)));return{...n,palettes:[...r,...s]}}function Bp(e,t){let n=ln(e);return n&&t.includes(n)?n:void 0}function Pv(e,t,n){let r=ba(t,n),i=Bp(e,t.palettes),{author:s,markets:o,updates:a}=e;return{...r,installed:{...r.installed,...s?{author:s}:{},...i?{startup:i}:{},...o?{markets:o}:{},...a?{updates:a}:{}}}}function Ov(e,t){let n=ba({terminals:e.terminals,palettes:e.palettes,off:e.off},t),r=new Set([...n.catalog.palettes,...zp(t.configHome)].map((l)=>l.name)),i=e.palettes.filter((l)=>r.has(l)),s=e.palettes.filter((l)=>!r.has(l)),{startup:o,...a}=e,u={...a,palettes:i,...o&&i.includes(o)?{startup:o}:{}},c=s.length>0?[`Dropped ${s.join(", ")} — no longer in the catalog`,...n.notes]:n.notes;return{...n,installed:u,notes:c}}function Tv(e){try{return Zp(process.execPath,[Ne(e,"ttheme","ttheme.js"),"--version"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function Vp(e){let t=dt(e);return[e.terminals.map((n)=>Jr[n]).join(", "),`${e.palettes.length} palettes`,t?`default ${t}`:"no default — ttheme is off"].join(" · ")}function Av(e){try{return se(e).itermBase}catch{return}}function il(e,t=cn()){for(let s of e.copies)if(rl(oi(s.to),{recursive:!0}),Qp(s.to,{force:!0}),Qp(`${s.to}.zwc`,{force:!0}),vv(s.from,s.to),s.executable)Ev(s.to,493);rl(oi(e.settings.file),{recursive:!0}),Sv(e.settings.file,e.settings.content);let n=oi(oi(e.settings.file)),r=Av(n),i=os(r?{...e.installed,itermBase:r}:e.installed,t);if(ze(i.markets).includes(z))So(n,e.catalog);Et(n,i),ot(n,Le(n),i,e.home);for(let s of e.edits){rl(oi(s.file),{recursive:!0});let o=gt(s.file)?ai(s.file,"utf8"):"";ki(s.file,Di(o,s.block))}return ar(i,t)}class Cn extends Error{}function wa(e){if(xe(e))throw $r("Nothing changed"),new Cn;return e}function Xp(e){return Po.filter((t)=>{if(t==="iterm2")return process.platform==="darwin";if(t==="windows-terminal")return e.wtHome!==void 0;return t!=="warp"||process.platform!=="win32"})}function Hv(e,t){if(e==="iterm2")return gt(Ne(t.home,"Library","Application Support","iTerm2"));if(e==="windows-terminal")return t.wtHome!==void 0;if(e==="warp")return gt(oi(Ao(t.home)));if(e==="wezterm")return gt(Ne(t.configHome,"wezterm"))||gt(Ne(t.home,".wezterm.lua"));return gt(Ne(t.configHome,e))}function Lv(){if(process.platform==="win32")return process.env.LOCALAPPDATA;if(!process.env.WSL_DISTRO_NAME)return;let e=(t,n)=>Zp(t,n,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();try{return e("wslpath",["-u",e("cmd.exe",["/d","/c","echo %LOCALAPPDATA%"])])||void 0}catch{return}}async function Gv(e,t,n){return wa(await eh({message:"Wire which terminals?",options:Xp(n).map((r)=>({value:r,label:Jr[r],hint:r===e?"detected":void 0})),initialValues:t,required:!0}))}function sl(e){let t=[...e.copies.filter((n)=>!gt(n.to)).map((n)=>n.to),...gt(e.settings.file)?[]:[e.settings.file],...e.edits.filter((n)=>!ai(n.file,"utf8").includes("# ttheme begin")).map((n)=>n.file)];if(t.length>0)throw Error(`init left gaps:
495
+ }`;async function Op(){if(vl())return;if(process.platform==="darwin"){let[e="",t=""]=(await an("osascript",["-l","JavaScript","-e",DE])).stdout.trim().split("\t");return{stamp:e,picture:t==="picture"}}if(process.platform==="linux"&&!Fp()){let t=Boolean(process.env.WAYLAND_DISPLAY)?(await an("wl-paste",["--list-types"])).stdout:(await an("xclip",["-selection","clipboard","-t","TARGETS","-o"])).stdout;return{stamp:t,picture:/^image\//m.test(t)}}return}function _a(e){let t=[],n="",r=0;while(r<e.length){if(e[r]!=="\x1B"){n+=e[r],r++;continue}if(e.startsWith("\x1B[200~",r)){let s=e.indexOf("\x1B[201~",r+6);if(s===-1)return{events:t,keys:n,pending:e.slice(r)};t.push({kind:"paste",text:e.slice(r+6,s)}),r=s+6;continue}if(e.startsWith("\x1B]5522;",r)||e.startsWith("\x1B]72;",r)){let s=[e.indexOf("\x1B\\",r),e.indexOf("\x07",r)].filter((h)=>h!==-1);if(s.length===0)return{events:t,keys:n,pending:e.slice(r)};let o=Math.min(...s),a=e.slice(r+2,o),[u="",c="",...l]=a.split(";");t.push({kind:"osc",code:u,meta:ev(c),payload:l.join(";")}),r=o+(e[o]==="\x07"?1:2);continue}let i=/^\[\?([\d;]*)(\$y|c)/.exec(e.slice(r+1,r+64));if(i){if(i[2]==="c")t.push({kind:"attributes"});else{let[s="0",o="0"]=(i[1]??"").split(";");t.push({kind:"mode",mode:Number(s),value:Number(o)})}r+=1+i[0].length;continue}if(/^(?:\[(?:\?[\d;$]*|2|20|200|201)?|\](?:5|55|552|5522|7|72)?)$/.test(e.slice(r+1)))return{events:t,keys:n,pending:e.slice(r)};n+=e[r],r++}return{events:t,keys:n,pending:""}}function ev(e){let t={};for(let n of e.split(":")){let r=n.indexOf("=");if(r>0)t[n.slice(0,r)]=n.slice(r+1)}return t}var Vs=(e)=>Buffer.from(e).toString("base64"),kl=(e)=>Buffer.from(e,"base64");function yp(e,t){return t.find((n)=>e.includes(n))}class Ml{clipboard=!1;drops=!1;reading;offered=[];dropping;pw=Vs(Ep("sha1").update(`${process.pid}:${Date.now()}`).digest("hex"));send;deliver;constructor(e,t){this.send=e,this.deliver=t}start(){let e="\x1B[?2004h";if(this.clipboard)e+="\x1B[?5522h";if(this.drops)e+=`\x1B]72;t=a;${$l.join(" ")}\x1B\\`;this.send(e)}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=${Vs("ttheme")}:pw=${this.pw};${Vs(".")}\x1B\\`)}take(e){if(e.code==="5522")this.clip(e.meta,e.payload);else if(e.code==="72")this.drop(e.meta,e.payload)}clip(e,t){if(e.type!=="read")return;let n=e.status??"";if(n==="OK"){if(this.reading??={mime:".",chunks:[],pw:e.pw??"",listing:!0},e.pw)this.reading.pw=e.pw;return}let r=this.reading;if(!r)return;if(n==="DATA"){if(r.mime=e.mime?kl(e.mime).toString("utf8"):r.mime,t)r.chunks.push(kl(t));return}if(this.reading=void 0,n!=="DONE"){this.deliver({kind:"error",message:n==="EPERM"?"The clipboard read was not allowed":`The terminal answered ${n}`});return}let i=Buffer.concat(r.chunks);if(r.listing){let s=i.toString("utf8").split(/\s+/).filter(Boolean),o=yp(s,[...yl,...qE]);if(!o){this.deliver({kind:"text",text:""});return}let a=r.pw||this.pw,u=r.pw?"Paste event":"ttheme";this.reading={mime:o,chunks:[],pw:a,listing:!1},this.send(`\x1B]5522;type=read:name=${Vs(u)}:pw=${a};${Vs(o)}\x1B\\`);return}this.deliver(r.mime.startsWith("image/")?{kind:"bytes",bytes:new Uint8Array(i),source:"clipboard"}:{kind:"text",text:i.toString("utf8")})}drop(e,t){let n=e.t??"";if(n==="m"){if(e.x==="-1"){this.offered=[];return}if(t){this.offered=t.split(" ").filter(Boolean);let a=$l.filter((u)=>this.offered.includes(u));this.send(`\x1B]72;t=m:o=${a.length>0?1:0};${a.join(" ")}\x1B\\`)}return}if(n==="M"){let a=t?t.split(" ").filter(Boolean):this.offered,u=yp(a,$l);if(!u){this.send("\x1B]72;t=r:o=0\x1B\\");return}this.dropping={mimes:a,index:a.indexOf(u)+1,chunks:[]},this.send(`\x1B]72;t=r:x=${this.dropping.index}\x1B\\`);return}let r=this.dropping;if(!r)return;if(n==="R"){this.dropping=void 0,this.send("\x1B]72;t=r:o=0\x1B\\"),this.deliver({kind:"error",message:`The drop failed: ${t.split(":")[0]||"unknown error"}`});return}if(n!=="r"&&n!=="")return;if(t)r.chunks.push(kl(t));if(e.m==="1"||t)return;this.dropping=void 0;let i=Buffer.concat(r.chunks),s=r.mimes[r.index-1]??"",o;if(s.startsWith("image/"))o={kind:"bytes",bytes:new Uint8Array(i),source:"drop"};else{let a=i.toString("utf8"),u=s==="text/uri-list"?Ii(a).find((c)=>_E(c)):void 0;o=u?{kind:"bytes",bytes:new Uint8Array(Ca(u)),source:u}:{kind:"text",text:a}}this.send("\x1B]72;t=r:o=1\x1B\\"),this.deliver(o)}}var Be={pitch:25,cols:22,rows:9,height:13},Fr={cols:25,rows:16},tv=2147483648,nv=-1073741826,rv=1600,Tp=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],iv=56,sv=4,Hp=20,ov=50,Ap=[["space","unfolds a set of ×N"],["o","opens the post page in a browser"],["c","switches between cutouts and every post"],["a","opens the advanced filters"],["ctrl+v","tries on a picture from the clipboard — or drop one on the window"]],av="\x1B[0m",Ye="\x1B[1m",K="\x1B[2m",eo="\x1B[32m",un="\x1B[33m",uv={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",Z:"shift-tab","1;2C":"shift-right","1;2D":"shift-left"};function ja(e){let t=[],n=0;while(n<e.length){let r=e[n]??"";if(r==="\x1B"){let i=/^(?:\[([0-9;]*)([A-Za-z~])|O([A-Za-z]))/.exec(e.slice(n+1));if(i){t.push(uv[`${i[1]??""}${i[2]??i[3]??""}`]??"nop"),n+=1+i[0].length;continue}let s=e[n+1]??"";if(/^[a-z]$/.test(s)){t.push(`alt-${s}`),n+=2;continue}t.push("esc"),n++;continue}t.push(r==="\r"||r===`
496
+ `?"enter":r==="\t"?"tab":r==="\x03"?"ctrl-c":r==="\x16"?"ctrl-v":r===""||r==="\b"?"backspace":r),n++}return t}var Kp="\x1B]1337;ReportCellSize\x07\x1B[16t",Lp="\x1B]1337;ReportCellSize=";function Fl(e){let t=e.indexOf(Lp);if(t!==-1){let i=e.slice(t+Lp.length),s=[i.indexOf("\x07"),i.indexOf("\x1B\\")].filter((u)=>u!==-1),o=s.length>0?Math.min(...s):-1,a=o===-1?null:/^([\d.]+);([\d.]+);([\d.]+)$/.exec(i.slice(0,o));if(a){let u=Number(a[3]);return{cell:{h:Math.round(Number(a[1])*u),w:Math.round(Number(a[2])*u)},rest:e.slice(0,t)+i.slice(o+(i[o]==="\x07"?1:2))}}}let n=e.indexOf("\x1B[6;"),r=n===-1?null:/^\[6;(\d+);(\d+)t/.exec(e.slice(n+1));if(!r)return null;return{cell:{h:Number(r[1]),w:Number(r[2])},rest:e.slice(0,n)+e.slice(n+1+r[0].length)}}function Rr(e,t){let n=t-4;return{perRow:Math.max(1,Math.floor((e-1)/Be.pitch)),rowsVis:Math.max(1,Math.floor(n/Be.height)),height:n}}function Jp(e){return`\x1B_Ga=t,t=f,f=100,i=${e.id},q=2;${Buffer.from(e.path).toString("base64")}\x1B\\`}function Bp(e,t){let n=e.crop===void 0?"":`,x=0,y=${e.crop*t.h},w=${e.cols*t.w},h=${e.rows*t.h}`;return`\x1B[${e.row+1};${e.col+1}H\x1B_Ga=p,i=${e.id},p=${e.id}${n},c=${e.cols},r=${e.rows},C=1,z=${e.z},q=2\x1B\\`}function qp(e){return`\x1B_Ga=d,d=I,i=${e},q=2\x1B\\`}function Ni(e){return`\x1B[38;2;${Ue(e).join(";")}m`}function Ua(e){return`\x1B[48;2;${Ue(e).join(";")}m`}var Sl=!1;function Wa(e){return Sl=!0,e.beat}function Pi(e){return Tp[Wa(e)%Tp.length]}function xe(e){return we(e)}function zp(e,t){if(we(e)<=t)return e;let n="";for(let r of e){if(we(n+r)>t)break;n+=r}return n}function Fi(e){return`\x1B[${30+e}m`}function Ri(e,t,n,r){return n?[[`${Ji} `,r],[e,t,n]]:[[e,t]]}function Il(e){return e.reduce((t,[n])=>t+xe(n),0)}function cv(e,t){let n=[],r=t;for(let[i,s,o]of e){let a=xe(i);if(a<=r){n.push([i,s,o]),r-=a;continue}n.push([`${zp(i,r)}…`,s,o]);break}return n}class Ga{parts=[];cols;constructor(e){this.cols=e}put(e,t,n="",r){return this.parts.push({col:e,text:t,sgr:n,...r?{link:r}:{}}),e+xe(t)}run(e,t){let n=e;for(let[r,i,s]of t)n=this.put(n,r,i,s);return n}right(e,t){this.run(e-t.reduce((n,[r])=>n+xe(r),0),t)}center(e,t){this.run(Math.floor((e-t.reduce((n,[r])=>n+xe(r),0))/2),t)}render(){let e="";for(let{col:t,text:n,sgr:r,link:i}of this.parts){if(t>=this.cols||t<0)continue;let s=zp(n,this.cols-t);e+=`\x1B[${t+1}G${r}${Fo(s,i)}${r?av:""}`}return e}}function lv(e){return e.replace(/_\([^)]*\)?$/,"")}function Yp(e){return[`${e.reduced?"↓":""}${e.width}×${e.height}`,Math.max(e.width,e.height)<rv?un:K]}function to(e,t,n,r){let i=[...r.keys??[]],s=r.lead,o=r.right,a=()=>{let l=[...s?[Il(s)]:[],...i.map(([f,d])=>xe(f)+1+xe(d))];return(r.badge?xe(r.badge)+4:0)+l.reduce((f,d)=>f+d,0)+3*Math.max(0,l.length-1)+(o?3+xe(o[0])+1+xe(o[1]):0)};while(a()>t)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&&a()>t)s=cv(s,Math.max(0,Il(s)-(a()-t)-1));let u=0;if(r.badge)u=e.put(0,` ${r.badge} `,`\x1B[7;1m${n}`)+2;if([...s?[s]:[],...i.map(([l,h])=>[[l,Ye],[` ${h}`,K]])].forEach((l,h)=>{u=e.run(u+(h?3:0),l)}),o)e.right(t,[[o[0],Ye],[` ${o[1]}`,K]])}function hv(e,t){if(e==="d")return K;if(e==="b")return Ye;if(e==="s")return Ua(t.colors.selection);if(e==="c")return Ua(t.colors.cursor);let n=/^([BK]?)(\d+)$/.exec(e);if(!n)return"";let r=Number(n[2]),i=(s)=>r<8?s+r:s+52+r;if(n[1]==="K")return`\x1B[30;${i(40)}m`;return`\x1B[${n[1]==="B"?"1;":""}${i(30)}m`}function fv(e,t,n,r,i){let s=Ht.indexOf(ga(r.scene)),o=Ht.flatMap((u,c)=>[...c?[[" ",""]]:[],[u.name,c===s?Ye+i:K]]),a=o.reduce((u,[c])=>u+xe(c),0)<=n;e?.run(t,a?o:[[ga(r.scene).name,Ye+i],[` ${s+1}/${Ht.length}`,K]])}function dv(e,t,n,r,i,s,o){let{ansi:a,cursor:u}=s.colors;fv(e[t-2],n,r,s,o);let c=r<em?3:4;if(r>=56)c=Math.min(7,Math.floor((r+1)/8)-1);let l=n;for(let f=0;f<8;f++)l=(e[t]?.put(l,"▀".repeat(c),Ni(a[f]??u)+Ua(a[f+8]??u))??l)+1;let h=t+2;for(let f of ga(s.scene).lines){let d=tm(f,r);if(!d)continue;if(h>i)return;e[h]?.run(n,d.map(([g,p])=>[g,hv(p,s)])),h++}}function gv(e,t,n){let r=[[]];for(let o of e){let a=r[r.length-1];if(a.length===0||xe([...a,o].join(" "))<=t)a.push(o);else if(r.length<n)r.push([o]);else break}let i=r.reduce((o,a)=>o+a.length,0),s=r[r.length-1];while(i<e.length&&s.length>0&&xe([...s,`+${e.length-i}`].join(" "))>t)s.pop(),i--;if(i<e.length)s.push(`+${e.length-i}`);return r.filter((o)=>o.length>0).map((o)=>o.join(" "))}function xp(e){return e.replace(/^https?:\/\/(?:www\.)?/,"")}function mv(e,t,n,r,i){let s=r.info,o=s?.artists??[],a=Fi(r.tiles[r.focus]?.siteAnsi??r.siteAnsi);[["Post",s?.page?Ri(xp(s.page),"",s.page,a):[["—",K]]],["Source",s?.source?Ri(xp(s.source),"",s.link,i):[["—",K]]],["Artist",[o.length>0?[o.join(" "),""]:["—",K]]]].forEach(([c,l],h)=>{e[t+h]?.put(n,c,K),e[t+h]?.run(n+12,l)})}function pv(e,t,n,r,i,s){let o=s.info,a=s.tiles[s.focus];if(!o||!a)return;let u=s.shown?.id===a.key?s.shown:void 0,c=n+12,l=Math.max(12,r-12),h=[`${a.width}×${a.height}${o.ext?` ${o.ext.toUpperCase()}`:""}`,...u?[va(u.bytes)]:[]].join(" · "),f=[o.rating??"—",a.score>0?`★${a.score}`:"",o.posted??""].filter(Boolean).join(" · "),d=(b,m)=>b.length>0?gv(b,l,m).map(($)=>[[$,""]]):[[["—",K]]],g=[["Characters",d(o.characters,2)],["Series",d(o.series,1)],["Tags",d(o.tags,3)],["Rating",[[[f,f==="—"?K:""]]]],["File",[[[h,""],...u?[[" ",""]]:[],...u?Qp(u):[]]]],["Uploader",[[o.uploader?[o.uploader,""]:["—",K]]]]],p=t;for(let[b,m]of g){if(p+m.length-1>i)return;e[p]?.put(n,b,K);for(let $ of m)e[p]?.run(c,$),p++}}var bv=["Size","Position","Opacity"],wv=[0,3,6];function $v(e,t){let{tune:n,untuned:r}=e;return t===0?n.size!==r.size:t===1?n.at!==r.at:n.opacity!==r.opacity}function kv(e){return e.toFixed(2)}function yv(e,t,n,r,i,s){let o=i.tuning;if(!o)return;let a=i.tiles[i.focus];e[t-3]?.run(n,[[i.palette,Ye+s],[" Background",K],...a?[[" · ",K],...Ri(`${a.site} ${a.id}`,K,a.page||void 0,Fi(a.siteAnsi))]:[]]);let u=Math.max(8,r-n-21),c=20,l=Math.max(100,o.fill);for(let[h,f]of bv.entries()){let d=t+wv[h],g=o.field===h,p=g?Ye:K;if(g)e[d]?.put(n,"▶",s);e[d]?.put(n+2,f,p);let b;if(h===1){for(let m=1;m<=9;m++){let $=m===i.tune.at;e[t+2+Math.floor((m-1)/3)]?.put(n+12+(m-1)%3*3,$?"■":"·",$?Ye+s:K)}b=bt[i.tune.at-1]??"center"}else{let m;if(h===0){let{size:$}=i.tune;m=$==="fill"?u-1:Math.floor(($-c)*(u-1)/(l-c+1)),b=$==="fill"?"fill":`${$}%`}else m=Math.floor(Math.round(i.tune.opacity*100)*(u-1)/100),b=kv(i.tune.opacity);m=Math.max(0,Math.min(u-1,m)),e[d]?.run(n+12,[["━".repeat(m),s],["●",Ye],["─".repeat(u-1-m),K]])}if(e[d]?.right(r-2,[[b,p]]),$v(i,h))e[d]?.put(r-1,"↺",g?Ye+s:K)}}function Ev(e,t,n,r,i,s){e[t]?.put(n,`╭${"─".repeat(i-2)}╮`,s);for(let o=t+1;o<t+r-1;o++)e[o]?.put(n,"│",s),e[o]?.put(n+i-1,"│",s);e[t+r-1]?.put(n,`╰${"─".repeat(i-2)}╯`,s)}function Nl(e,t=e.site,n=e.siteAnsi){return[` ${t} `,`\x1B[7;${30+n}m`]}function Ds(e){return`${V[Math.floor(e/jn)]?.name??"local"} ${e%jn}`}function Xs(e,t,n){let r=V[Math.floor(t/jn)],i=Ds(t),s=e.indexOf(i);if(!r||s===-1)return[[e,n]];return[[e.slice(0,s),n],...Ri(i,n,r.pageUrl(t%jn),Fi(r.ansi)),[e.slice(s+i.length),n]].filter(([a])=>a!=="")}function vv(e,t,n){let r=[{name:"all",moved:!1},...V].flatMap((s,o)=>{let a=`${s.name}${s.moved?"*":""}`,u=s.name===n.site?Nl(n,a):[` ${a} `,K];return o?[[" ",""],u]:[u]}),i=r.reduce((s,[o])=>s+xe(o),0)<=t;e.run(0,i?r:[Nl(n)])}function Mv(e,t,n,r){if(n.editing!==void 0){let u=e.run(0,[["⌕ ",r],[n.editing,""],["█",r]]),c=n.suggest?.length?" ↑↓ pick enter searches":" enter searches";e.put(u,n.editing?c:` A tag, a post URL or an id, or drop a picture or ctrl+v — ${n.tag||"esc leaves"}`,K);return}let i=e.run(0,[["⌕ ",r],[n.tag||"Nothing yet — / searches, ctrl+v pastes a picture",n.tag?"":K]]),s=lr.filter((u)=>!n.block.includes(u)),o=V.filter((u)=>!n.enabled.includes(u.name)).map((u)=>u.name),a=[n.preset,...n.solo?["solo"]:[],n.order,...n.rating.join("+")==="safe"?[]:[n.rating.join("+")],...s.length>0?[`allows ${s.join("+")}`]:[],...n.narrow.size>0?[`≥${n.narrow.size}px`]:[],...n.narrow.score>0?[`score≥${n.narrow.score}`]:[],...n.narrow.png?["png"]:[],...n.hide.length+n.hideTags.length>0?[`hides ${[...n.hide,...n.hideTags].join("+")}`]:[],...o.length>0?[`all skips ${o.join("+")}`]:[]];if(e.put(i,` ${a.join(" ")}`,K),n.total>0||!n.searching){let u=[[`${n.tiles.length}/${n.checked}`,""]];if(n.checked<n.total)u.push([` of ${n.total}`,K]);e.right(t,u)}}function Qp(e){if(e.cut==="on")return[[`Cut out · ${e.clear}% transparent`,eo]];if(e.cut==="off")return[["Opaque · x cuts out",un]];if(e.cut==="failed")return[["Opaque · no cut-out",un]];return[e.clear>0?[`${e.clear}% transparent`,eo]:["Opaque",un]]}function Cp(e){return e.site==="all"?"any site":e.site}function Pl(e,t){if(e.installing!==void 0)return Xs(`${Pi(e)} Installing ${e.palette} ← ${Ds(e.installing)}`,e.installing,un);if(e.hint)return[[e.hint,eo]];if(e.error)return[[e.error,un]];if(e.waiting!==void 0)return[[`${e.slow??e.site} asked to slow down · ${e.waiting}s`,un]];if(e.fetching){let{id:n,got:r,size:i}=e.fetching;return Xs(`${Pi(e)} Fetching ${Ds(n)} · ${Ma(r,i)}`,n,un)}if(e.cutting!==void 0)return Xs(`${Pi(e)} Cutting out ${Ds(e.cutting)}`,e.cutting,un);if(e.preparing!==void 0)return Xs(`${Pi(e)} Preparing ${Ds(e.preparing)}`,e.preparing,un);if(t)return[t];if(e.saved)return Xs(e.saved.text,e.saved.key,eo);if(e.note)return[[e.note,K]];return}function Zp(e){if(e.ranking)return"Ranking previews by palette colors";if(e.stage==="check")return e.preset==="cutouts"?"Checking PNG headers":"Loading previews";return"Fetching posts"}function Vp(e,t){return e.ranking?`${t}${e.ranking.done}/${e.ranking.total}`:""}function Sv(e,t,n,r,i){let{background:s,cursor:o,selection:a}=r.colors,{ranking:u}=r,c=u?Math.round(n*u.done/u.total):-1,l=Math.max(6,Math.round(n*0.22)),h=Wa(r)%(Hp*2)/Hp,f=Math.round((n-l)*(0.5-0.5*Math.cos(Math.PI*(h<1?h:2-h)))),d=ot(s,o,i),g=ot(s,ot(a,s,0.15),i),p=Array.from({length:n},(m,$)=>{let k=(c>=0?$<c:$>=f&&$<f+l)?d:g;return $===0||$===n-1?ot(k,s,0.55):k}),b=0;for(let m=1;m<=n;m++)if(m===n||p[m]!==p[b])e?.put(t+b," ".repeat(m-b),Ua(p[b])),b=m}function Iv(e,t,n,r,i){let{background:s,foreground:o}=i.colors,a=i.loaderFrom===void 0?0:Math.min(1,(Wa(i)-i.loaderFrom)/sv),u=t+(n>=5?Math.floor((n-5)/2):0);e[u]?.center(r,[[Zp(i),Ye+Ni(ot(s,o,a))],[Vp(i," "),Ni(ot(s,ot(o,s,0.45),a))]]);let c=Math.min(iv,r-8);if(Sv(e[u+(n>=3?2:1)],Math.floor((r-c)/2),c,i,a),n<5)return;e[u+4]?.center(r,i.sites.flatMap(({name:l,arrived:h},f)=>[...f?[[" · ",Ni(ot(s,o,0.25*a))]]:[],[l,Ni(ot(s,h?ot(o,s,0.2):o,h?a:0.32*a))]]))}function Nv(e,t,n,r,i,s){if(i<=r)return;let o=Math.max(1,Math.round(r*r/i)),a=Math.max(0,Math.min(r-o,Math.round(n.scroll*r/i)));for(let u=0;u<r;u++){let c=u>=a&&u<a+o;e[2+u]?.put(t-1,c?"┃":"│",c?s:K)}}function Pv(e,t,n){if(t)return[`${Pi(e)} ${Zp(e)}${Vp(e," · ")}`,K];let r=n.filter((s)=>!s.missing),i=r.filter((s)=>s.thumb).length;return i<r.length?[`${Pi(e)} Loading thumbnails · ${i}/${r.length}`,K]:void 0}function Fv(e,t,n,r,i,s){let{perRow:o,rowsVis:a,height:u}=Rr(n,r);Mv(e[0],n,i,s),vv(e[1],n,i);let c=e.map((y,N)=>N>=2&&N<2+u?y:void 0),l=Math.floor(i.scroll/Be.height),h=Math.floor((i.scroll+u-1)/Be.height),f=[];for(let y=l;y<=h;y++){let N=2+y*Be.height-i.scroll;for(let R=0;R<o;R++){let H=y*o+R,A=R*Be.pitch,C=i.tiles[H];if(!C)continue;f.push(C);let G=H===i.focus;if(G)Ev(c,N,A,Be.height,Be.pitch-1,s);let L=N+1,O=Math.max(L,2),J=Math.min(L+Be.rows,2+u);if(C.thumb&&J>O)t.push({id:C.key,path:C.thumb,row:O,col:A+1,cols:Be.cols,rows:J-O,...J-O<Be.rows?{crop:O-L}:{},z:-1});let Ee=[...i.installed.includes(C.key)?[["✓ ",eo]]:[],...C.page||i.site!=="all"?Ri(String(C.id),G?Ye:"",C.page||void 0,Fi(C.siteAnsi)):[["● ",Fi(C.siteAnsi)],[String(C.id),G?Ye:""]],[" ",""],Yp(C)],pe=Be.cols-(C.mates.length>0?1:0);if(c[N+10]?.run(A+1,Il(Ee)>pe?Ee.map(([Ae,he,oe])=>[Ae.replace(/^(\S) $/,"$1"),he,oe]):Ee),C.mates.length>0)c[N+10]?.put(A+Be.cols,"≈",s);c[N+11]?.put(A+1,C.artist?lv(C.artist).slice(0,Be.cols-8):"—",K);let z=[];if(C.score>0)z.push([`★${C.score}`,K]);if(C.variants>1)z.push([` ×${C.variants}`,s]);if(z.length>0)c[N+11]?.right(A+Be.cols+1,z)}}let d=Math.ceil(i.tiles.length/o)*Be.height;Nv(e,n,i,u,d,s);let g=Math.max(2,2+d-i.scroll),p=2+u-g,b=i.searching&&p>=2;if(b)Iv(c,g,p,n-1,i);let m=i.searching&&i.tiles.length===0;if(m&&!i.error){let[y,N]=Ap[Math.floor(Wa(i)/ov)%Ap.length];e[r-2]?.run(0,[["Tip ",K],[y,Ye],[` ${N}`,K]])}let $=i.top*o,k=i.tiles.length-(i.top+a)*o,S=[...$>0?[`↑ ${$} above`]:[],...k>0?[`↓ ${k} more`]:[]];if(S.length>0)e[r-2]?.put(0,S.join(" "),K);if(!i.searching&&i.tiles.length===0&&!i.error&&i.tag)e[3]?.put(0,i.preset==="cutouts"?`No transparent cutouts of ${i.tag} on ${Cp(i)} — c searches every post, tab tries ${i.nextSite}`:`No posts of ${i.tag} on ${Cp(i)} — tab tries ${i.nextSite}`,K);let w=Pv(i,b,f),M=Pl(i,w);return to(e[r-1],n,s,{badge:"FIND",lead:M,keys:m&&M?.[0]===w?[]:[["←↑↓→","move"],["enter","try on"],["tab","site"],["ctrl+v","picture"],["s","settings"],["/","search"],["?","keys"]],right:["esc","back"]}),b}function Rv(e,t,n,r,i,s){let o=i.tiles[i.focus];if(!o)return;let a=i.shown?.id===o.key?i.shown:void 0,u=[Nl(i,o.site,o.siteAnsi),[" ",""],...Ri(String(o.id),Ye,o.page||void 0,Fi(o.siteAnsi)),[" ",""],Yp(o)];if(o.score>0)u.push([` · ★${o.score}`,K]);if(a)u.push([` · ${va(a.bytes)}`,K]);if(a)u.push([" ",""],...Qp(a));if(e[0]?.run(0,u),o.mates.length>0)e[0]?.right(n,[["≈ ",s],[o.mates.join(" "),K]]);if(mv(e,1,2,i,s),i.tuning)yv(e,8,2,2+Math.min(n-4,60),i,s);else if(i.details)pv(e,5,2,Math.min(n-4,Math.max(48,Math.floor(n*0.55))),r-2,i);else dv(e,7,2,n-4,r-2,i,s);if(i.shown)t.push({id:tv+i.shown.id,path:i.shown.path,row:0,col:0,cols:n,rows:r,z:nv});if(i.tuning){to(e[r-1],n,s,{badge:"TUNE",lead:Pl(i),keys:[["↑↓","field"],["←→","step"],["=","reset"],["+","reset all"],i.tuning.field===1?["1-9","place"]:["⇧←→","×10"],["enter","keep"]],right:["esc","undo"]});return}let c=Pl(i);to(e[r-1],n,s,{badge:"TRY",lead:c,keys:i.installing===void 0?[["←→","browse"],["enter","install"],["t","tune"],["i","details"],...i.details?[]:[["⇧←→","example"]],...i.shown?.cut==="on"||i.shown?.cut==="off"?[["x","cut out"]]:[],["?","keys"]]:[],right:i.installing===void 0?["esc","grid"]:void 0})}var Ov=[["Field","↑↓ size, position, opacity"],["Step","←→ · ⇧←→ ×10"],["Place","1-9 the nine positions"],["Reset","= this field back to its default · + every field"],["Keep","enter back to try, installed with the picture"],["Undo","esc"],["Close","? esc"]],Tv={grid:[["Move","←↑↓→ home end pgup pgdn"],["Try on","enter"],["Site",`tab shift+tab all, ${V.map((e)=>e.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"],["Advanced","a or Advanced › in settings min score, min size, sites, hide, hide tags, PNG only"],["Back","esc returns to preview"],["Close","? esc"]],try:[["Browse","←→"],["Install","enter"],["Tune","t size, position and opacity, installed with the picture"],["Details","i characters, series, tags, rating and file, under Post, Source and Artist"],["Example",`⇧←→ ${Ht.map((e)=>e.name.toLowerCase()).join(", ")}`],["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"]]},Rl=6,Hv=24;function no(e){return[...e.settings.flatMap((t,n)=>Boolean(t.advanced)===e.advanced?[n]:[]),e.settings.length]}function Av(e){return e.replace(/^[A-Z](?=[a-z])/,(t)=>t.toLowerCase())}function _p(e){let t=e.settings.filter((n)=>Boolean(n.advanced)!==e.advanced).map((n)=>Av(n.label));return`${e.advanced?"Back to":"More filters:"} ${t.join(", ")} — enter opens the page, or a from any row`}function Xp(e,t,n){let r=e.indexOf(t);if(r!==-1)return e[(r+n+e.length)%e.length];let i=Number(t)||0;return(n>0?e.find((o)=>(Number(o)||0)>i):[...e].reverse().find((o)=>(Number(o)||0)<i))??e[n>0?0:e.length-1]}function Pr(e,t){let n=[],r="";for(let i of e.split(" "))if(r&&xe(r)+1+xe(i)>t)n.push(r),r=i;else r=r?`${r} ${i}`:i;return r?[...n,r]:n}function Lv(e){if(e.entry!=="number"||e.choices.includes(e.value))return e.choices;let t=e.choices.findIndex((n)=>(Number(n)||0)>Number(e.value));return t===-1?[...e.choices,e.value]:[...e.choices.slice(0,t),e.value,...e.choices.slice(t)]}function xv(e,t,n,r){let i=`\x1B[7;${30+r}m`,s=t&&n!==void 0;if(e.entry==="text")return[{text:` ${s?`${n}█`:e.value||"none"} `,sgr:s||t&&e.value?i:e.value?"":K}];let o=s?[]:e.value.split(" "),a=(s?e.choices:Lv(e)).map((u,c)=>{let l=o.includes(u),h=e.multi&&t&&c===e.cursor?"4;":"";return{text:e.multi?` ${l?"[x]":"[ ]"} ${u} `:` ${u} `,sgr:l?t?`\x1B[${h}7;${30+r}m`:"":h?`\x1B[4m${K}`:K}});return s?[...a,{text:` ${n}█ `,sgr:i}]:a}function Gp(e){if(e.entry==="text")return[{text:" ".repeat(Hv),sgr:""}];let t=e.choices.map((n)=>({text:e.multi?` [x] ${n} `:` ${n} `,sgr:""}));return e.entry==="number"?[...t,{text:` ${"0".repeat(Rl)}█ `,sgr:""}]:t}function Cv(e){return e.reduce((t,n)=>t+xe(n.text)+1,0)-1}function Up(e,t){let n=[[]],r=0;for(let i of e){let s=xe(i.text)>t?{...i,text:` …${Array.from(i.text).slice(-(t-2)).join("")}`}:i;if(r>0&&r+xe(s.text)>t)n.push([]),r=0;n[n.length-1]?.push(s),r+=xe(s.text)+1}return n}function jp(e){if(e.multi&&e.choices.every((t)=>e.default.split(" ").includes(t)))return"Default all";return`Default ${e.default&&e.default!==e.multi?.none?e.default:"none"}`}function Wp(e){if(!e.tag)return"";if(!e.counts)return`${e.tag}: counting…`;let t=e.counts.map(({site:n,count:r})=>`${n} ${r===void 0?"no count":r.toLocaleString("en-US")}`);return`${e.tag}: ${t.join(" · ")}`}function _v(e,t){let n=e.advanced?"basic":"advanced";if(!t)return{keys:[["↑↓","setting"],["enter",n],["s","save"]],right:["esc","undo"]};if(e.typing!==void 0)return{keys:[["⌫","erase"],["enter","done"]],right:["esc","cancel"]};if(t.entry)return{keys:[["↑↓","setting"],...t.entry==="number"?[["←→","step"]]:[],["a",n],["enter","type"],["s","save"]],right:["esc","undo"]};return{keys:[["↑↓","setting"],["←→","value"],["a",n],...t.multi?[["space","toggle"]]:[],["enter","save"]],right:["esc","undo"]}}function Gv(e,t,n,r,i){let s=r.panel??0,o=r.settings.length,u=6+Math.max(...r.settings.map((L)=>xe(L.label))),c=Math.max(...r.settings.map((L)=>xe(jp(L)))),l=u+Math.max(...r.settings.map((L)=>Cv(Gp(L))))+c+5,h=Math.min(t-2,Math.max(48,l)),f=h-u-c-5,d=h-7,g=[!1,!0].map((L)=>({advanced:L,rows:no({settings:r.settings,advanced:L}).slice(0,-1)})),p=r.settings.map((L)=>Up(Gp(L),f).length),b=Math.max(...g.map((L)=>L.rows.reduce((O,J)=>O+p[J],0))),m=Math.max(...g.map((L)=>Pr(_p({settings:r.settings,advanced:L.advanced}),d).length),...r.settings.map((L)=>Pr(L.about,d).length)),$=`${r.tag}: ${V.map((L)=>`${L.name} 0,000,000`).join(" · ")}`,k=r.tag?Math.max(Pr($,d).length,Pr(Wp(r),d).length):0,S=b+m+k+8,w=Math.floor((t-h)/2),M=Math.max(1,Math.floor((n-1-S)/2)),y=`\x1B[7;${30+r.siteAnsi}m`;e[M]?.put(w,`╭─ Settings ${"─".repeat(Math.max(0,h-13))}╮`);for(let L=M+1;L<M+S-1;L++)e[L]?.put(w,`│${" ".repeat(h-2)}│`);let N=M+2;for(let L of no(r).slice(0,-1)){let O=r.settings[L],J=L===s;if(J)e[N]?.put(w+2,"▶",i);if(e[N]?.put(w+4,O.label,J?Ye:""),O.value!==O.default)e[N]?.right(w+h-3,[[jp(O),K]]);Up(xv(O,J,r.typing,r.siteAnsi),f).forEach((Ee,pe)=>{let z=w+u;for(let Ae of Ee)z=e[N+pe].put(z,Ae.text,Ae.sgr)+1}),N+=p[L]}let R=g.find((L)=>L.advanced!==r.advanced)?.rows??[],H=e[M+3+b];if(s===o)H.put(w+2,"▶",i);let A=H.put(w+3,r.advanced?" ‹ Basic ":" Advanced › ",s===o?y:Ye);if(R.some((L)=>r.settings[L]?.value!==r.settings[L]?.default))H.put(A+1,"•",K);e[M+5+b]?.put(w+2,"─".repeat(h-4),K),Pr(r.settings[s]?.about??_p(r),d).forEach((L,O)=>{e[M+6+b+O]?.put(w+4,L)}),Pr(Wp(r),d).forEach((L,O)=>{e[M+6+b+m+O]?.put(w+4,L,K)}),e[M+S-1]?.put(w,`╰${"─".repeat(h-2)}╯`);let{keys:C,right:G}=_v(r,r.settings[s]);to(e[n-1],t,i,{badge:"SET",keys:C,right:G})}function Uv(e,t,n,r,i){let s=r.tuning?Ov:Tv[r.mode],o=Math.min(t-2,Math.max(50,...s.map(([,f])=>xe(f)+16))),a=s.map(([f,d])=>({label:f,parts:Pr(d,o-16)})),u=a.reduce((f,{parts:d})=>f+d.length,0)+4,c=Math.floor((t-o)/2),l=Math.max(2,Math.floor((n-u)/2));e[l]?.put(c,`╭─ Keys ${"─".repeat(o-9)}╮`);for(let f=l+1;f<l+u-1;f++)e[f]?.put(c,`│${" ".repeat(o-2)}│`);let h=l+2;for(let{label:f,parts:d}of a){e[h]?.put(c+3,f,Ye);for(let g of d)e[h]?.put(c+13,g),h++}e[l+u-1]?.put(c,`╰${"─".repeat(o-2)}╯`),to(e[n-1],t,i,{badge:"KEYS",right:["? esc","close"]})}function jv(e,t,n){let r=t.suggest??[],i=r.map((a)=>a.count>0?String(a.count):a.palette??"0"),s=Math.max(...r.map((a)=>xe(a.value))),o=Math.max(7,...i.map(xe));r.forEach((a,u)=>{let c=u===t.pick,l=e[1+u];l?.run(0,[[c?"▸ ":" ",n],[a.value,c?Ye+n:""]]),l?.right(2+s+2+o,[[i[u],K]])})}function Ol(e,t,n){let r=Array.from({length:n},()=>new Ga(t)),i=[],s=Ni(e.colors.cursor);if(Sl=!1,t<Fr.cols||n<Fr.rows)return r[0]?.put(0,"ttheme find",Ye+s),r[1]?.put(0,`Needs ${Fr.cols}×${Fr.rows} — now ${t}×${n}`),r[2]?.put(0,"esc quits",K),{lines:r.map((a)=>a.render()),images:i,loader:!1,tick:!1};let o=!1;if(e.mode==="try")Rv(r,i,t,n,e,s);else o=Fv(r,i,t,n,e,s);if(e.mode==="grid"&&e.editing!==void 0&&e.suggest?.length){for(let a=1;a<n-1;a++)r[a]=new Ga(t);return jv(r,e,s),{lines:r.map((a)=>a.render()),images:[],loader:!1,tick:!1}}if(e.help||e.panel!==void 0){let a=e.mode==="try"?i:[];for(let u=0;u<n;u++)r[u]=new Ga(t);if(e.help)Uv(r,t,n,e,s);else Gv(r,t,n,e,s);return{lines:r.map((u)=>u.render()),images:a,loader:!1,tick:!1}}return{lines:r.map((a)=>a.render()),images:i,loader:o,tick:Sl}}var Tl=5,Wv=6,Dp=0.05,Kv=[1,2,3,4,5,6,9,10,11,12,13,14],eb=(e,t)=>(t-e+360)%360<=180?1:-1;function ro(e,t,n){let r=t*Math.cos(n*Math.PI/180),i=t*Math.sin(n*Math.PI/180),s=[e+0.3963377774*r+0.2158037573*i,e-0.1055613458*r-0.0638541728*i,e-0.0894841775*r-1.291485548*i].map((l)=>l**3),[o,a,u]=s,c=[4.0767416621*o-3.3077115913*a+0.2309699292*u,-1.2684380046*o+2.6097574011*a-0.3413193965*u,-0.0041960863*o-0.7034186147*a+1.707614701*u];if(c.some((l)=>l<-0.0001||l>1.0001))return;return c.map((l)=>{let h=Math.min(1,Math.max(0,l));return Math.round(255*(h<=0.0031308?12.92*h:1.055*h**0.4166666666666667-0.055))})}function Ct(e,t,n){let r=0,i=t;if(ro(e,t,n)===void 0)for(let o=0;o<24;o++){let a=(r+i)/2;if(ro(e,a,n)===void 0)i=a;else r=a}else r=t;return`#${(ro(e,r,n)??[0,0,0]).map((o)=>o.toString(16).padStart(2,"0")).join("")}`}function Jv(e,t){let{l:n,c:r}=Je(e);return Ct(n,r,(t+360)%360)}function Bv(e,t,n){let{l:r,c:i,h:s}=Je(e),o=ze(t)<0.18,a=(l)=>Ct(o?r+(1-r)*l:r*(1-l),i,s);if(Ke(a(1),t)<n+Dp)return a(1);let u=0,c=1;for(let l=0;l<30;l++){let h=(u+c)/2;if(Ke(a(h),t)>=n+Dp)c=h;else u=h}return a(c)}function qv(e,t){let{l:n,c:r,h:i}=Je(e),s=0,o=n;for(let a=0;a<30;a++){let u=(s+o)/2;if(ze(Ct(u,r,i))<=t-0.005)s=u;else o=u}return Ct(s,r,i)}function zv(e,t,n){let r=hn[t],[i,s]=[Je(e[t]),Je(e[t+8])],o=(l,h)=>n.has(l)?[h]:Array.from({length:2*r.width+1},(f,d)=>(r.center-r.width+d+360)%360),a=(l,h,f)=>Rn.every((d)=>{let g=(l>8?8:0)+d;if(g===l)return!0;let p=Je(e[g]);return p.c<qi||Qt(p.h,h)>=Ur+1||Math.abs(p.l-f)>=jr}),u,c=Number.POSITIVE_INFINITY;for(let l of o(t,i.h)){if(!n.has(t)&&!a(t,l,i.l))continue;for(let h of o(t+8,s.h)){if(Qt(l,h)>Gt-Tl||!n.has(t+8)&&!a(t+8,h,s.l))continue;let f=Qt(l,i.h)+Qt(h,s.h);if(f<c)c=f,u=[l,h]}}return u}class tb{theme;moves=[];constructor(e){this.theme={...e,ansi:[...e.ansi]}}set(e,t,n){let r=this.get(e);if(n===r)return;if(this.moves.push({slot:e,rule:t,from:r,to:n}),e==="foreground")this.theme.foreground=n;else if(e==="selection")this.theme.selectionBackground=n;else this.theme.ansi[Number(e.slice(4))]=n}get(e){if(e==="foreground")return this.theme.foreground;if(e==="selection")return this.theme.selectionBackground;return this.theme.ansi[Number(e.slice(4))]}rehue(e,t,n){this.set(`ansi${e}`,t,Jv(this.theme.ansi[e],n))}roles(){let e=new Set(this.theme.signatureSlots);for(let{slot:n,hue:r}of Gr(this.theme)){let i=hn[On(n)];this.rehue(n,"ansi-role",i.center+eb(i.center,r)*(i.width-Tl))}for(let{normal:n,gap:r}of sr(this.theme)){if(r<=Gt)continue;let[i,s]=e.has(`ansi${n+8}`)?[n+8,n]:[n,n+8],o=Je(this.theme.ansi[i]).h,a=Je(this.theme.ansi[s]).h;this.rehue(s,"bright-follows",o+eb(o,a)*(Gt-Tl))}let t=Wr(this.theme);for(let[n,r]of or(this.theme)){let i=On(t.has(r)?n:r),s=zv(this.theme.ansi,i,t);if(s===void 0)continue;this.rehue(i,"distinct",s[0]),this.rehue(i+8,"distinct",s[1])}}readability(){let e=new Set(this.theme.waive),{background:t}=this.theme,n=(r,i,s,o=t)=>{if(e.has(r))return;for(let a of i)if(Ke(this.get(a),o)<s)this.set(a,r,Bv(this.get(a),o,s))};if(n("foreground",["foreground"],7),n("accents",Kv.map((r)=>`ansi${r}`),3),n("light-ansi",["ansi7","ansi15"],7),n("ansi8-visible",["ansi8"],1.6),!e.has("ansi0-dark")&&ze(this.get("ansi0"))>0.15)this.set("ansi0","ansi0-dark",qv(this.get("ansi0"),0.15));n("selection",["selection"],7,this.theme.foreground)}net(){return[...new Set(this.moves.map((e)=>e.slot))].flatMap((e)=>{let t=this.moves.filter((i)=>i.slot===e),n=t[0].from,r=this.get(e);return n===r?[]:[{slot:e,rule:[...new Set(t.map((i)=>i.rule))].join(", "),from:n,to:r}]})}}function Ka(e){let t=new tb(e);for(let n=0;n<Wv;n++)if(t.readability(),t.roles(),ar(t.theme).length===0)break;return{theme:t.theme,moves:t.net(),left:ar(t.theme)}}var io=[{key:"background",label:"Background",min:0,max:0.5,step:0.01,digits:2},{key:"foreground",label:"Foreground",min:0.5,max:1,step:0.01,digits:2},{key:"hue",label:"Hue",min:0,max:360,step:1,digits:0,wraps:!0},{key:"tint",label:"Tint",min:0,max:0.1,step:0.005,digits:3},{key:"lightness",label:"Accent lightness",min:0.4,max:0.95,step:0.01,digits:2},{key:"chroma",label:"Accent chroma",min:0,max:0.3,step:0.005,digits:3},{key:"brights",label:"Brights",min:-0.2,max:0.2,step:0.01,digits:2}],Ja={background:0.21,foreground:0.88,hue:265,tint:0.02,lightness:0.72,chroma:0.12,brights:0.06},nb=(e,t,n)=>Math.min(n,Math.max(t,e));function rb(e,t,n){let r=e[t.key]+t.step*n,i=t.wraps?(r%t.max+t.max)%t.max:nb(r,t.min,t.max);return{...e,[t.key]:Math.round(i*1e4)/1e4}}function Or(e){let t=(r,i,s)=>Ct(nb(r,0,1),i,s),n=Array.from({length:16},()=>"#000000");n[0]=t(e.background+0.06,e.tint,e.hue),n[8]=t(e.background+0.25,e.tint,e.hue),n[7]=t(e.foreground-0.06,e.tint/2,e.hue),n[15]=t(e.foreground+0.06,e.tint/2,e.hue);for(let r of Rn){let i=hn[r].center;n[r]=t(e.lightness,e.chroma,i),n[r+8]=t(e.lightness+e.brights,e.chroma,i)}return{background:t(e.background,e.tint,e.hue),foreground:t(e.foreground,e.tint/2,e.hue),cursor:t(e.lightness+e.brights,Math.max(e.chroma,0.08),e.hue),selection:t(e.background+0.1,e.tint*2,e.hue),ansi:n}}var ao=["background","foreground","cursor","selection",...Array.from({length:16},(e,t)=>`ansi${t}`)],Et=["Background","Foreground","Cursor","Selection"],Qa=["Black","Red","Green","Yellow","Blue","Magenta","Cyan","White"],so=Et.length+Qa.length,Tr=[{key:"l",label:"Lightness",min:0,max:1,step:0.01,digits:2},{key:"c",label:"Chroma",min:0,max:0.37,step:0.005,digits:3},{key:"h",label:"Hue",min:0,max:360,step:1,digits:0,wraps:!0}],ib=5;function Yv(e){let t=e.trim();return/^https?:\/\/\S+$/i.test(t)||Ii(t).length>0}function Ba(e){return[e.background,e.foreground,e.cursor,e.selection,...e.ansi]}function vn(e){let[t,n,r,i,...s]=e;return{background:t,foreground:n,cursor:r,selection:i,ansi:s}}function qa(e){if(e<Et.length)return{name:Et[e],about:ao[e]};let t=e-Et.length,n=Qa[t%8];return t<8?{name:n,about:`ansi ${t}`}:{name:`Bright ${n.toLowerCase()}`,about:`ansi ${t}`}}var za=(e,t,n)=>Math.min(n,Math.max(t,e));function Qv(e){return za(Math.round(e),0,255).toString(16).padStart(2,"0")}function sb(e){let t=e.trim().toLowerCase(),n=/^#?([0-9a-f]{6}|[0-9a-f]{3})$/.exec(t);if(n){let s=n[1];return`#${s.length===3?[...s].map((o)=>o+o).join(""):s}`}let r=/^rgb\(\s*(\d+)[\s,]+(\d+)[\s,]+(\d+)\s*\)$/.exec(t);if(r)return`#${r.slice(1,4).map((s)=>Qv(Number(s))).join("")}`;let i=/^oklch\(\s*([\d.]+)(%?)[\s,]+([\d.]+)[\s,]+([\d.]+)(?:deg|°)?\s*\)$/.exec(t);if(i){let s=Number(i[1])/(i[2]?100:1);return Ct(za(s,0,1),Number(i[3]),Number(i[4])%360)}return}function Ya(e){let t=gt.find((n)=>n.rule===e);return t?.min??t?.max??0}function oo(e,t,n){let r=vn(e);return{name:"draft",background:r.background,foreground:r.foreground,selectionBackground:r.selection,ansi:r.ansi,waive:n,signatureSlots:t}}function Zv(e,t,n){let r=oo(e,t,n),i=(h)=>!n.includes(h),{background:s,foreground:o,selection:a,ansi:u}=vn(e),c=new Set,l=(h,f,d,g)=>{if(i(g)&&Ke(f,d)<Ya(g))c.add(h)};l(1,o,s,"foreground"),l(3,o,a,"selection");for(let h of[1,2,3,4,5,6,9,10,11,12,13,14])l(4+h,u[h],s,"accents");for(let h of[7,15])l(4+h,u[h],s,"light-ansi");if(l(12,u[8],s,"ansi8-visible"),i("ansi0-dark")&&ze(u[0])>Ya("ansi0-dark"))c.add(4);if(i("ansi-role"))for(let{slot:h}of Gr(r))c.add(4+h);if(i("bright-follows")){for(let{normal:h,gap:f}of sr(r))if(f>Gt)c.add(4+h+8)}if(i("distinct"))for(let[h,f]of or(r))c.add(4+h).add(4+f);return c}function En(e,t,n,r,i){let s=Ke(e,t),o=Ya(n);if(i.includes(n))return{ok:void 0,text:`${r} ${s.toFixed(2)}:1 · waived`};return{ok:s>=o,text:`${r} ${s.toFixed(2)}:1 · ≥ ${o}`}}function ob(e,t,n,r){let i=vn(e),s=oo(e,t,n);if(r===0){let m=[1,2,3,4,5,6,9,10,11,12,13,14].reduce(($,k)=>Ke(i.ansi[$],i.background)<=Ke(i.ansi[k],i.background)?$:k);return[En(i.foreground,i.background,"foreground","Foreground on it",n),En(i.ansi[m],i.background,"accents",`Weakest, ANSI ${m},`,n),En(i.ansi[8],i.background,"ansi8-visible","ANSI 8 on it",n)]}if(r===1)return[En(i.foreground,i.background,"foreground","On background",n),En(i.foreground,i.selection,"selection","On the selection",n)];if(r===2)return[{ok:void 0,text:`On background ${Ke(i.cursor,i.background).toFixed(2)}:1`}];if(r===3)return[En(i.foreground,i.selection,"selection","Foreground on it",n)];let o=r-Et.length,a=i.ansi[o];if(o===0){let b=ze(a),m=Ya("ansi0-dark");return[n.includes("ansi0-dark")?{ok:void 0,text:`Luminance ${b.toFixed(3)} · waived`}:{ok:b<=m,text:`Luminance ${b.toFixed(3)} · ≤ ${m}`}]}if(o===7||o===15)return[En(a,i.background,"light-ansi","On background",n)];if(o===8)return[En(a,i.background,"ansi8-visible","On background",n)];let u=[En(a,i.background,"accents","On background",n)],c=Je(a),l=On(o),h=hn[l],f=`${h.name} ${h.center}±${h.width}°`;if(c.c<qi)u.push({ok:void 0,text:"Too grey to have a hue"});else if(Wr(s).has(o))u.push({ok:void 0,text:`Hue ${c.h.toFixed(0)}° · a signature, free of ${f}`});else if(n.includes("ansi-role"))u.push({ok:void 0,text:`Hue ${c.h.toFixed(0)}° · ${f} waived`});else{let b=Qt(c.h,h.center)-h.width;u.push(b>0?{ok:!1,text:`Hue ${c.h.toFixed(0)}° · ${b.toFixed(0)}° outside ${f}`}:{ok:!0,text:`Hue ${c.h.toFixed(0)}° · in ${f}`})}let d=o<8?o+8:o-8,g=sr(s).find((b)=>b.normal===l);if(g)u.push(n.includes("bright-follows")?{ok:void 0,text:`${g.gap.toFixed(0)}° from ANSI ${d} · waived`}:{ok:g.gap<=Gt,text:`${g.gap.toFixed(0)}° from ANSI ${d} · ≤ ${Gt}°`});let p=or(s).flatMap(([b,m])=>b===o?[m]:m===o?[b]:[]);if(p.length>0&&!n.includes("distinct"))u.push({ok:!1,text:`Reads as ANSI ${p.join(", ")} · within ${Ur}° and ${jr} lightness`});return u}function ab(e,t,n){let r=Tn(oo(e,t,n));return gt.map((i,s)=>{let o=r[s],a=n.includes(i.rule);return{ok:a||Number.isNaN(o)?void 0:(i.min===void 0||o>=i.min)&&(i.max===void 0||o<=i.max),label:i.label,value:Number.isNaN(o)?"—":Number.isInteger(o)?String(o):o.toFixed(2),bound:a?"waived":i.min!==void 0?`≥ ${i.min}`:i.max!==void 0?`≤ ${i.max}`:""}})}var Vv=new Set(["reset","hex","paste","fix","open","seeds","tune","sig","follow"]);class Hl{mode;seeds=Ja;field=0;list;lch;start;signature;row=0;col=0;channel=0;typing;overlay;quitting=!1;compare=!1;notice;filter="";pick=0;result;wants;pictures;startPictures;options;fresh;startSignature;seeded=!1;seedsBack=!1;tuneFrom;clip;history=[];future=[];lastEdit;constructor(e){this.options=e,this.fresh=e.colors===void 0,this.mode=this.fresh?"seeds":"list",this.list=Ba(e.colors??Or(this.seeds)),this.lch=this.list.map(Je),this.start=[...this.list],this.signature=[...e.signature],this.startSignature=[...e.signature],this.pictures=e.pictures??0,this.startPictures=this.pictures}get added(){return Math.max(0,this.pictures-this.startPictures)}found(e){this.pictures=e.count,this.notice=e.note}get waive(){return this.options.waive??[]}get tuned(){return this.tuneFrom?.hex}colors(){return vn(this.list)}edited(){return{colors:this.colors(),signature:[...this.signature]}}shown(){return this.compare?this.start:this.list}slot(){return this.row<Et.length?this.row:this.row+(this.col===1?8:0)}dirty(){return this.seeded||this.pictures!==this.startPictures||this.list.some((e,t)=>e!==this.start[t])||this.signature.join()!==this.startSignature.join()}misses(){return Zv(this.list,this.signature,this.waive)}failing(){return ar(oo(this.list,this.signature,this.waive))}choices(){let e=this.filter.toLowerCase();return(this.options.palettes??[]).filter((t)=>t.name.toLowerCase().includes(e))}paste(e){if(this.notice=void 0,this.overlay==="open"){this.filter+=e.replace(/\s+/g,"").toLowerCase(),this.pick=0;return}if(this.overlay)return;if(e.trim()===""){this.findPictures({clipboard:!0});return}if(Yv(e)){this.findPictures({paste:e});return}if(this.mode==="seeds")return;let t=sb(e);if(!t){this.notice="Not a color — #rrggbb, rgb(r g b) or oklch(l c h)";return}if(this.typing=void 0,this.mode==="tune")this.list[this.slot()]=t,this.lch[this.slot()]=Je(t);else this.set(this.slot(),t,"paste")}press(e){if(this.notice=void 0,e==="ctrl-c"){this.result="cancelled";return}if(this.quitting){if(this.quitting=!1,e==="y"||e==="Y")this.result="cancelled";return}if(this.typing!==void 0){this.type(e);return}if(this.overlay==="keys"){this.overlay=void 0;return}if(this.overlay==="open"){this.openKey(e);return}if(e==="?"){this.overlay="keys";return}if(e==="ctrl-v"||e==="alt-v"){this.findPictures({clipboard:!0});return}if(e==="p"&&this.mode!=="tune"){this.findPictures();return}if(e===" "&&this.mode!=="seeds"){this.compare=!this.compare;return}if(this.compare&&e==="esc"){this.compare=!1;return}if(this.mode==="seeds")this.seedKey(e);else if(this.mode==="tune")this.tuneKey(e);else this.listKey(e)}seedKey(e){let t=io.length;if(e==="up"||e==="down")this.field=(this.field+(e==="up"?t-1:1))%t;else if(e==="home"||e==="end")this.field=e==="home"?0:t-1;else if(e==="left"||e==="right"||e==="shift-left"||e==="shift-right"){let n=io[this.field],r=(e.endsWith("left")?-1:1)*(e.startsWith("shift")?n.wraps?10:ib:1);this.seeds=rb(this.seeds,n,r),this.list=Ba(Or(this.seeds)),this.lch=this.list.map(Je)}else if(e==="enter")this.leaveSeeds();else if(e==="o")this.openPalettes();else if(e==="esc")if(this.seedsBack){let n=this.history.pop();if(n)this.restore(n);this.mode="list",this.seedsBack=!1}else this.result="cancelled"}leaveSeeds(){if(this.fresh&&!this.seeded)this.start=[...this.list];this.seeded=!0,this.seedsBack=!1,this.mode="list"}findPictures(e){if(!this.options.find){this.notice="Pictures need Ghostty, iTerm2 or kitty, outside tmux";return}this.wants=e?{start:e}:{}}openPalettes(){if((this.options.palettes??[]).length>0)this.overlay="open",this.pick=0;else this.notice="No other palettes to take colors from"}listKey(e){if(e==="up"||e==="down")this.row=(this.row+(e==="up"?so-1:1))%so,this.lastEdit=void 0;else if(e==="home"||e==="end")this.row=e==="home"?0:so-1;else if(e==="pgup"||e==="pgdn")this.row=e==="pgup"?0:Et.length;else if(e==="left"||e==="right")this.col=e==="left"?0:1,this.lastEdit=void 0;else if(e==="tab")this.tune();else if(e==="#")this.typing="";else if(e==="c")this.clip=this.list[this.slot()],this.notice=`Copied ${this.clip}`;else if(e==="v")if(this.clip)this.set(this.slot(),this.clip,"paste");else this.notice="Nothing copied yet — c copies a slot";else if(e==="r")this.set(this.slot(),this.start[this.slot()],"reset");else if(e==="=")this.follow();else if(e==="*")this.mark();else if(e==="f")this.fix();else if(e==="s")this.remember("seeds"),this.mode="seeds",this.seedsBack=!0;else if(e==="o")this.openPalettes();else if(e==="u")this.undo();else if(e==="\x12")this.redo();else if(e==="enter"||e==="\x13")this.save();else if(e==="esc")if(this.dirty())this.quitting=!0;else this.result="cancelled"}tune(){let e=this.slot();this.remember("tune"),this.tuneFrom={hex:this.list[e],lch:this.lch[e]},this.mode="tune"}tuneKey(e){let t=Tr.length;if(e==="up"||e==="down"||e==="tab"||e==="shift-tab")this.channel=(this.channel+(e==="up"||e==="shift-tab"?t-1:1))%t;else if(e==="left"||e==="right"||e==="shift-left"||e==="shift-right"){let n=Tr[this.channel];this.step((e.endsWith("left")?-1:1)*(e.startsWith("shift")?n.wraps?10:ib:1))}else if(/^[0-9]$/.test(e)){let n=Tr[this.channel];this.put(n.min+(n.max-n.min)*Number(e)/10)}else if(e==="#")this.typing="";else if(e==="enter"){if(this.tuneFrom&&this.list[this.slot()]===this.tuneFrom.hex)this.history.pop();this.tuneFrom=void 0,this.mode="list"}else if(e==="esc"){let n=this.slot();if(this.tuneFrom)this.list[n]=this.tuneFrom.hex,this.lch[n]=this.tuneFrom.lch,this.history.pop();this.tuneFrom=void 0,this.mode="list"}}step(e){let t=Tr[this.channel],n=this.lch[this.slot()][t.key];this.put(n+t.step*e)}put(e){let t=this.slot(),n=Tr[this.channel],r=n.wraps?(e%n.max+n.max)%n.max:za(e,n.min,n.max),i={...this.lch[t],[n.key]:Math.round(r*1e4)/1e4};this.lch[t]=i,this.list[t]=Ct(i.l,i.c,i.h)}type(e){let t=this.typing??"";if(e==="esc")this.typing=void 0;else if(e==="enter"){let n=sb(t);if(!n){this.notice="Not a color — #rrggbb, rgb(r g b) or oklch(l c h)";return}if(this.typing=void 0,this.mode==="tune")this.list[this.slot()]=n,this.lch[this.slot()]=Je(n);else this.set(this.slot(),n,"hex")}else if(e==="backspace")this.typing=t.slice(0,-1);else if(e==="\x15")this.typing="";else if(e.length===1&&/^[0-9a-z#(),.% ]$/i.test(e)&&t.length<28)this.typing=t+e.toLowerCase()}openKey(e){let t=this.choices();if(e==="esc")this.overlay=void 0,this.filter="";else if(e==="up"||e==="down"){let n=Math.max(1,t.length);this.pick=(this.pick+(e==="up"?n-1:1))%n}else if(e==="home"||e==="end")this.pick=e==="home"?0:Math.max(0,t.length-1);else if(e==="backspace")this.filter=this.filter.slice(0,-1),this.pick=0;else if(e==="\x15")this.filter="",this.pick=0;else if(e==="enter"){let n=t[this.pick];if(!n)return;if(this.remember("open"),this.list=Ba(n.colors),this.lch=this.list.map(Je),this.overlay=void 0,this.filter="",this.notice=`Took the colors of ${n.name}`,this.mode==="seeds")this.leaveSeeds()}else if(e.length===1&&/^[a-z0-9@/-]$/i.test(e))this.filter+=e.toLowerCase(),this.pick=0}remember(e){if(e!==this.lastEdit||Vv.has(e))this.history.push({list:[...this.list],lch:[...this.lch],signature:[...this.signature]}),this.future=[];this.lastEdit=e}set(e,t,n){if(!Pn(t)||this.list[e]===t)return;this.remember(n),this.list[e]=t,this.lch[e]=Je(t)}follow(){if(this.row<Et.length){this.notice="= works on an ANSI row — the bright takes its normal";return}let e=this.row,t=this.row+8,n=this.lch[e],r={l:za(n.l+0.06,0,1),c:n.c,h:n.h};this.remember("follow"),this.lch[t]=r,this.list[t]=Ct(r.l,r.c,r.h),this.col=1,this.notice=`${qa(t).name} follows ${qa(e).name.toLowerCase()}`}mark(){let e=ao[this.slot()];this.remember("sig"),this.signature=this.signature.includes(e)?this.signature.filter((t)=>t!==e):[...this.signature,e].slice(-3),this.notice=this.signature.length===3?`Signature: ${this.signature.join(", ")}`:`The signature needs three slots — ${this.signature.length} marked`}fix(){let e=oo(this.list,this.signature,this.waive),{theme:t,moves:n,left:r}=Ka({...e,selectionBackground:e.selectionBackground,signatureSlots:this.signature});if(n.length===0){this.notice=ar(e).length===0?"Already passes the gate":"No color change fixes it";return}this.remember("fix");let i=Ba({...this.colors(),foreground:t.foreground,selection:t.selectionBackground,ansi:t.ansi});this.lch=i.map((s,o)=>s===this.list[o]?this.lch[o]:Je(s)),this.list=i,this.notice=`Moved ${n.length} ${n.length===1?"color":"colors"}${r.length===0?" — passes the gate":" closer to the gate"}`}save(){let e=this.options.check(this.edited());if(e){this.notice=e;return}this.result="saved"}undo(){let e=this.history.pop();if(!e){this.notice="Nothing to undo";return}this.future.push({list:[...this.list],lch:[...this.lch],signature:[...this.signature]}),this.restore(e)}redo(){let e=this.future.pop();if(!e){this.notice="Nothing to redo";return}this.history.push({list:[...this.list],lch:[...this.lch],signature:[...this.signature]}),this.restore(e)}restore(e){this.list=[...e.list],this.lch=[...e.lch],this.signature=[...e.signature],this.lastEdit=void 0}}var Ll=80,xl=24,Za=48,Al=11;function Xv(e){return{color:e,dim:(t)=>e?`\x1B[2m${t}\x1B[22m`:t,bold:(t)=>e?`\x1B[1m${t}\x1B[22m`:t,fg:(t)=>e?Yt(t):"",bg:(t)=>e?`\x1B[48;2;${Ue(t).join(";")}m`:""}}function Dv(e){return ze(e)>0.35?"#000000":"#ffffff"}function cb(e,t,n,r){let i=Math.max(0,Math.min(t.length-1,n));if(!e.color)return t.map((s,o)=>o===i?"●":r?"━":"─").join("");return t.map((s,o)=>{let a=s??"#000000";if(o===i)return`${e.bg(a)}${e.fg(Dv(a))}●\x1B[39;49m`;return s?`${e.fg(s)}█`:`${e.fg(r?"#777777":"#555555")}░`}).join("").concat("\x1B[39m")}function eM(e,t,n){return Array.from({length:n},(r,i)=>{let s=t.min+(t.max-t.min)*i/(n-1),o={...e,[t.key]:s};return ro(o.l,o.c,o.h)?Ct(o.l,o.c,o.h):void 0})}function lb(e,t,n,r){return Math.round((e-t)/(n-t)*(r-1))}var ub={background:(e)=>e.background,foreground:(e)=>e.foreground,hue:(e)=>e.cursor,tint:(e)=>e.background,lightness:(e)=>e.ansi[4],chroma:(e)=>e.ansi[1],brights:(e)=>e.ansi[12]};function hb(e,t){return t===void 0?e.dim("·"):t?e.dim("✓"):e.bold("✗")}function fb(e,t,n){let r=ab(t.list,t.signature,t.waive).sort((a,u)=>Number(a.ok!==!1)-Number(u.ok!==!1)),i=r.filter((a)=>a.ok===!1).length,s=` ${e.dim("Gate")} ${i===0?e.dim("passes"):e.bold(`${i} ${i===1?"miss":"misses"}`)}`,o=Za-4;return[s,...r.slice(0,Math.max(0,n-1)).map((a)=>{let u=`${a.value} ${a.bound}`;return` ${hb(e,a.ok)} ${cn(a.ok===!1?a.label:e.dim(a.label),e.dim(u),o-2)}`})]}function tM(e,t,n){let r=t.misses(),i=vn(t.list),s=t.slot(),o=(l)=>e.color?`${e.bg(i.selection)}${e.fg(i.foreground)}${l}\x1B[39;49m`:`[${l}]`,a=(l)=>{let h=t.list[l],f=l===s,d=t.signature.includes(ao[l])?"◆":e.color?"■":" ",g=l===0?void 0:l===3?Ke(i.foreground,i.selection):Ke(h,i.background),p=g===void 0?"":g.toFixed(1),b=r.has(l)?"✗":" ",$=`${e.color?`${e.fg(h)}${d}${f?e.fg(i.foreground):"\x1B[39m"} `:`${d} `}${h} ${p.padStart(4)}${b}`;return f?o(` ${$} `):` ${$} `},u=(l)=>l?e.color?`${e.fg(i.cursor)}▌\x1B[39m `:"▌ ":" ",c=[` ${e.dim("Base")}`];for(let l=0;l<Et.length;l++){let h=l===t.row,f=Et[l].padEnd(10);c.push(`${u(h)}${h?e.bold(f):f}${a(l)}`)}c.push("",` ${e.dim(`${"ANSI".padEnd(10)} Normal${" ".repeat(11)}Bright`)}`);for(let l=Et.length;l<so;l++){let h=l===t.row,f=Qa[l-Et.length].padEnd(10);c.push(`${u(h)}${h?e.bold(f):f}${a(l)}${a(l+8)}`)}return c.push(""),[...c,...fb(e,t,n-c.length)]}function nM(e,t,n){let r=vn(t.list),i=[` ${e.dim("Seeds")}`];io.forEach((s,o)=>{let a=o===t.field,u=t.seeds[s.key],c=Array.from({length:Al},(p,b)=>{let m=s.min+(s.max-s.min)*b/(Al-1);return ub[s.key](Or({...t.seeds,[s.key]:m}))}),l=cb(e,c,lb(u,s.min,s.max,Al),a),h=`${u.toFixed(s.digits)}${s.wraps?"°":""}`.padStart(6),f=ub[s.key](r),d=a?e.color?`${e.fg(r.cursor)}▌\x1B[39m `:"▌ ":" ",g=s.label.padEnd(17);i.push(`${d}${a?e.bold(g):g}${l} ${h} ${e.color?`${e.fg(f)}■\x1B[39m `:""}${e.dim(f)}`)}),i.push("");for(let s of Qe("Seven seeds grow all twenty colors, each accent on the hue its ANSI role reads as — whatever the seeds, they pass the gate. enter moves on to tune each slot.",Za-4))i.push(` ${e.dim(s)}`);return i.push(""),[...i,...fb(e,t,n-i.length)]}function db(e,t,n){let r=(h)=>e.fg(t.ansi[h]),i=e.fg(t.foreground),s=`${e.bg(t.background)}${i}`,o=(h)=>e.color?`\x1B[1m${h}\x1B[22m`:h,a=`${r(2)}❯${i} `,u=Math.max(2,Math.min(4,Math.floor((n-9)/8)));return[Array.from({length:8},(h,f)=>`${e.fg(t.ansi[f])}${e.bg(t.ansi[f+8])}${(e.color?"▀":"#").repeat(u)}${s} `).join(""),"",`${o(`${r(4)}~/code/demo`)}${i} on ${r(5)}main${r(2)} +2${r(3)} ~1${i}`,`${a}git status -sb`,`## ${r(2)}main${i}...${r(1)}origin/main${r(3)} [ahead 1]${i}`,`${r(1)} M${i} src/main.rs ${r(1)}??${i} notes.md`,`${a}git diff`,`${r(6)}@@ -12,2 +12,2 @@${i}`,`${r(1)}- let size = 12;${i}`,`${r(2)}+ let size = 14;${i}`,`${a}cargo test`,`${r(2)} ✓${i} parses config`,`${r(1)} ✗${i} renders frame ${r(8)}expected 3, received 2${i}`,`${r(11)} ⚠ 1 warning${i} ${r(12)}ℹ 2 notes${i} ${r(13)}λ${i} ${r(14)}~${i} ${r(9)}✗${i} ${r(10)}✓${i}`,`${a}ls`,`${o(`${r(4)}docs`)} ${o(`${r(4)}src`)} ${r(2)}run.sh${i} ${r(6)}link${i} Cargo.toml`,`${a}echo ${e.bg(t.selection)}selected text${s} ${e.bg(t.cursor)} ${s}`,`${r(7)}ansi 7 text${i} ${r(15)}ansi 15 text${i} ${r(8)}# ansi 8 comment${i}`].map((h)=>`${s} ${De(h,n-2)} ${e.color?"\x1B[0m":""}`)}function rM(e,t,n,r){let i=t.slot(),s=t.list[i],o=t.lch[i],a=Je(s),u=t.start[i],{name:c,about:l}=qa(i),h=t.signature.includes(ao[i]),f=[cn(`${e.bold(c)} ${e.dim(l)}`,h?e.dim("◆ signature"):"",n),""],d=e.color?`${e.fg(s)}${"█".repeat(8)}\x1B[39m `:"",g=t.typing!==void 0?`${e.bold(`${t.typing}▏`)}`:void 0,[p,b,m]=Ue(s),$=g??`${e.bold(s)}${u!==s?e.dim(` was ${e.color?`${e.fg(u)}■\x1B[39m `:""}${u}`):""}`;f.push(`${d}${$}`),f.push(`${d}${e.dim(`rgb ${p} ${b} ${m}`)}`),f.push(`${d}${e.dim(`oklch ${a.l.toFixed(3)} ${a.c.toFixed(3)} ${a.h.toFixed(0)}°`)}`),f.push("");let k=Math.max(8,Math.min(64,n-12));Tr.forEach((M,y)=>{let N=t.mode==="tune"&&y===t.channel,R=o[M.key],H=`${R.toFixed(M.digits)}${M.wraps?"°":""}`.padStart(6),A=cb(e,eM(o,M,k),lb(R,M.min,M.max,k),N),C=M.key.toUpperCase();f.push(`${N?e.bold(`▸${C}`):e.dim(` ${C}`)} ${A} ${N?e.bold(H):e.dim(H)}`)}),f.push("");let S=ob(t.list,t.signature,t.waive,i);if(a.c<o.c-0.005)S.push({ok:void 0,text:`Chroma held at the sRGB edge — ${a.c.toFixed(3)} of ${o.c.toFixed(3)}`});for(let M of S)Qe(M.text,n-2).forEach((y,N)=>{f.push(`${N===0?hb(e,M.ok):" "} ${M.ok===!1?y:e.dim(y)}`)});let w=r-f.length-1;if(w>=3)f.push("",...db(e,vn(t.shown()),n).slice(0,w));return f}function iM(e,t,n,r){return[cn(`${e.bold("Specimen")} ${e.dim("what the seeds grow")}`,"",n),"",...db(e,vn(t.list),n).slice(0,r-2)]}var sM=[["Slots","↑↓ slot · ←→ normal or bright · home end · pgup the base colors · pgdn the ANSI ones"],["Tune","tab · ↑↓ lightness, chroma or hue · ←→ step · ⇧←→ ×5, hue ×10 · 0-9 jump · enter keeps · esc undoes"],["Type","# then #rrggbb, rgb(r g b) or oklch(l c h) — a paste works too"],["Slot","c copies · v pastes · r puts it back · = the bright follows its normal · * marks it a signature color"],["Palette","f moves the colors the gate misses · o takes another palette’s colors · s goes back to the seeds"],["History","u undo · ctrl+r redo"],["Pictures","p finds one on the boorus, tried on in these colors · drop a picture on the window, or paste one, its path or its link · ctrl+v takes the clipboard’s"],["Compare","space shows the colors you started from, on the terminal too"],["Save","enter saves · esc cancels, asking first when something changed"]];function oM(e,t,n){let r=[` ${e.bold("Keys")}`,""];for(let[i,s]of sM.filter(([o])=>o!=="Pictures"||t.options.find))Qe(s,n-16).forEach((o,a)=>{r.push(` ${e.bold((a===0?i:"").padEnd(11))} ${o}`)});return r}function aM(e,t,n,r){let i=t.choices(),s=t.options.palettes?.length??0,o=t.filter?`${e.bold(t.filter)}▏`:e.dim("type to filter"),a=[cn(` ${e.bold("Take colors from")} ${o}`,e.dim(`${i.length}/${s}`),n),""],u=r-2,c=Math.max(0,Math.min(t.pick-Math.floor(u/2),i.length-u)),l=Math.min(40,Math.max(12,...i.map((h)=>we(h.name))));if(i.slice(c,c+u).forEach((h,f)=>{let d=c+f===t.pick,g=h.colors,p=e.color?`${e.bg(g.background)} ${[...g.ansi].map(($)=>`${e.fg($)}■`).join("")} ${e.fg(g.foreground)}Aa \x1B[0m`:"",b=d?"▌ ":" ",m=h.name.padEnd(l);a.push(`${b}${d?e.bold(m):m} ${p}`)}),i.length===0)a.push(` ${e.dim(`No palettes match '${t.filter}'`)}`);return a}function uM(e,t,n){let r=e.fg(t.list[2]),i="",s="",o=[],a="";if(t.quitting)i="QUIT",s=t.added>0?`Discard changes and ${t.added} ${t.added===1?"picture":"pictures"}?`:"Discard changes?",o=[["y","discard"],["n","keep editing"]];else if(t.typing!==void 0)i="TYPE",s=e.dim("#rrggbb, rgb(r g b) or oklch(l c h)"),o=[["enter","set"],["ctrl+u","clear"]],a="esc back";else if(t.overlay==="keys")i="KEYS",a="any key closes";else if(t.overlay==="open")i="OPEN",o=[["↑↓","palette"],["a-z","filter"],["enter","take its colors"]],a="esc close";else if(t.compare)i="BEFORE",s="The colors you started from",o=[["space","back to yours"]],a="esc back";else if(t.mode==="seeds")i="SEEDS",o=[["↑↓","seed"],["←→","step"],["⇧←→","×5"],["enter","tune slots"],["o","open a palette"],["p","picture"],["?","keys"]],a=t.fresh&&!t.dirty()?"esc cancel":"esc back";else if(t.mode==="tune")i="TUNE",o=[["↑↓","L C H"],["←→","step"],["⇧←→","faster"],["0-9","jump"],["#","type"],["enter","keep"]],a="esc undo";else o=[["↑↓","slot"],["←→","normal or bright"],["tab","tune"],["#","type"],["f","fix"],["p","picture"],["u","undo"],["enter","save"],["?","keys"]],a="esc cancel";if(!t.options.find)o=o.filter(([l])=>l!=="p");if(t.notice)s=e.color?`\x1B[33m${t.notice}\x1B[39m`:t.notice,o=[];let u=i?e.color?`\x1B[7;1m${r} ${i} \x1B[0m `:`[${i}] `:"",c=a?`${e.bold(a.split(" ")[0])} ${e.dim(a.split(" ").slice(1).join(" "))}`:"";for(;;){let l=[s,...o.map(([f,d])=>`${e.bold(f)} ${e.dim(d)}`)].filter(Boolean),h=`${u}${l.join(" ")}`;if(we(h)+we(a)+3<=n||o.length<=1)return a?cn(h,c,n):De(h,n);o=[...o.slice(0,-2),...o.slice(-1)]}}function cM(e,t,n,r){let i=Xv(r);if(t<Ll||n<xl){let g=[i.bold("ttheme palette editor"),`Needs ${Ll}×${xl} — now ${t}×${n}`,i.dim("esc cancels")];return Array.from({length:n},(p,b)=>De(g[b]??"",t))}let s=e.failing().length,o=s===0?"✓ Passes the gate":`✗ ${s} ${s===1?"miss":"misses"} in the gate`,a=e.pictures>0?i.dim(`▣ ${e.pictures} ${e.pictures===1?"picture":"pictures"} `):"",u=`${e.dirty()?`${i.color?"\x1B[33m●\x1B[39m":"●"} unsaved `:""}${a}${i.dim(o)}`,l=`${i.fg(e.list[2])}◆${i.color?"\x1B[39m":""} ${i.bold(e.options.title)} ${i.dim(`· ${e.options.name}`)}`,h=n-4,f;if(e.overlay==="keys")f=oM(i,e,t);else if(e.overlay==="open")f=aM(i,e,t,h);else{let g=t-Za-2,p=e.mode==="seeds"?nM(i,e,h):tM(i,e,h),b=e.mode==="seeds"?iM(i,e,g,h):rM(i,e,g,h);f=Array.from({length:h},(m,$)=>`${De(p[$]??"",Za)}${i.dim("│")} ${De(b[$]??"",g)}`)}let d=[cn(l,u,t),""];for(let g=0;g<h;g++)d.push(De(f[g]??"",t));return d.push("",uM(i,e,t)),d}async function gb(e,t){let n=new Hl(e),{stdin:r,stdout:i}=process,s=i.columns||Ll,o=i.rows||xl,a=[],u=[],c="",l,h=(k)=>i.write(k),f=()=>{l=void 0;let k="";if(n.shown().forEach((S,w)=>{if(u[w]!==S&&t.only?.includes(w))k+=Lc(w,S),u[w]=S}),k)h(k)},d=()=>{let k=cM(n,s,o,t.color),S="";if(k.forEach((w,M)=>{if(a[M]!==w)S+=`\x1B[${M+1};1H\x1B[0m\x1B[2K${w}`}),a=k,S)h(`\x1B[?2026h${S}\x1B[0m\x1B[?2026l`);if(t.only)l??=setTimeout(f,33)},g,p,b=!1,m=()=>{h(`\x1B[?1049h\x1B[?25l\x1B[?7l\x1B[?2004h${hi}`),r.setRawMode(!0),r.resume()},$=(k)=>{if(g&&p)r[k?"on":"off"]("data",g),i[k?"on":"off"]("resize",p)};m();try{return await new Promise((k)=>{let S=async(w)=>{let M=e.find;if(!M)return;b=!0,$(!1),clearTimeout(l),l=void 0;try{n.found(await M(n.edited(),w))}catch(y){n.notice=y instanceof Error?y.message:String(y)}b=!1,m(),$(!0),s=i.columns||s,o=i.rows||o,a=[],u.length=0,d()};p=()=>{s=i.columns||s,o=i.rows||o,a=[],h(hi),d()},g=(w)=>{c+=w.toString("utf8");let M=_a(c);c=M.pending;for(let N of M.events)if(N.kind==="paste")n.paste(N.text);if(M.keys.length>8&&/^(?:\/|~\/|file:|https?:)/.test(M.keys)&&n.typing===void 0)n.paste(M.keys);else for(let N of ja(M.keys))if(n.press(N),n.result||n.wants)break;if(n.result){k(n.result==="saved"?n.edited():void 0);return}let y=n.wants;if(y&&!b){n.wants=void 0,S(y.start);return}d()},$(!0),d()})}finally{clearTimeout(l),$(!1),r.setRawMode(!1),r.pause(),h("\x1B[?2004l\x1B[?7h\x1B[?25h\x1B[?1049l")}}import{spawn as PM}from"node:child_process";import{createHash as Lb}from"node:crypto";import{existsSync as Oi,mkdirSync as FM,mkdtempSync as RM,readFileSync as xb,rmSync as uo,statSync as OM}from"node:fs";import{homedir as TM,tmpdir as HM}from"node:os";import{dirname as AM,join as qt}from"node:path";import{pathToFileURL as Mb}from"node:url";var lM=new Set(["comic","4koma","monochrome","greyscale","sketch","lineart","speech_bubble"]),hM=new Set(["scenery","landscape","scenic","no_humans","wide_shot","very_wide_shot"]),fM=0.04,dM=0.1,gM=0.05,mM=4096;function pM(e){return new Set(e.cutouts.split(/\s+/).map((t)=>t.replace(/^~/,"")).filter(Boolean))}function bM(e,t,n,r=0){let{site:i,post:s}=e,o=new Set(s.tags),a=[...pM(i)].some((l)=>o.has(l)),u=Math.min(s.width,s.height),c=s.width>0&&s.height>0?s.width/s.height/(t.w/t.h):1;return(s.solo?2:0)+([...lM].some((l)=>o.has(l))?-3:0)+([...hM].some((l)=>o.has(l))?-1.5:0)+2*Math.min(1,u/t.h)+(a?1.5:-Math.min(1.5,Math.abs(Math.log(c))))+(n>0?1.5*Math.log1p(Math.max(0,s.score))/Math.log1p(n):0)+2*r}function Va(e,t,n=new Map){let r=new Map;for(let{site:i,post:s}of e)r.set(i,Math.max(r.get(i)??0,s.score));return e.map((i,s)=>({pick:i,at:s,score:bM(i,t,r.get(i.site)??0,n.get(i.post))})).sort((i,s)=>s.score-i.score||i.at-s.at).map(({pick:i})=>i)}function pb(e){let t=new Map;for(let r of e)t.set(r.site,[...t.get(r.site)??[],r]);let n=[];for(let r=0;n.length<e.length;r++)for(let i of t.values()){let s=i[r];if(s)n.push(s)}return n}function Cl(e){let t=e/255;return t<=0.04045?t/12.92:((t+0.055)/1.055)**2.4}function mb(e,t,n){let[r,i,s]=[Cl(e),Cl(t),Cl(n)],o=Math.cbrt(0.4122214708*r+0.5363325363*i+0.0514459929*s),a=Math.cbrt(0.2119034982*r+0.6806995451*i+0.1073969566*s),u=Math.cbrt(0.0883024619*r+0.2817188376*i+0.6299787005*s);return[0.2104542553*o+0.793617785*a-0.0040720468*u,1.9779984951*o-2.428592205*a+0.4505937099*u,0.0259040371*o+0.7827717662*a-0.808675766*u]}function bb(e,t){let n=t.map((o)=>mb(...Ue(o))).filter(([,o,a])=>Math.hypot(o,a)>=fM);if(n.length===0)return 0;let r=Math.max(1,Math.floor(Math.sqrt(e.width*e.height/mM))),i=n.map(()=>0),s=0;for(let o=0;o<e.height;o+=r)for(let a=0;a<e.width;a+=r){let u=(o*e.width+a)*4;if(e.data[u+3]<128)continue;s++;let[c,l,h]=mb(e.data[u],e.data[u+1],e.data[u+2]);n.forEach(([f,d,g],p)=>{if(Math.hypot(c-f,l-d,h-g)<dM)i[p]=i[p]+1})}if(s===0)return 0;return i.reduce((o,a)=>o+Math.min(1,a/s/gM),0)/n.length}import{mkdirSync as yM,readFileSync as Gl,writeFileSync as Eb}from"node:fs";import{dirname as EM}from"node:path";import{isMainThread as vM,parentPort as vb,Worker as MM}from"node:worker_threads";var wM=/(?:^|[^0-9a-f])([0-9a-f]{32})(?:[^0-9a-f]|$)/i,$M=[[/yande\.re\/post\/show\/(\d+)/,"yande"],[/konachan\.(?:com|net)\/post\/show\/(\d+)/,"konachan"],[/danbooru\.donmai\.us\/(?:posts|post\/show)\/(\d+)/,"danbooru"],[/zerochan\.net\/(\d+)(?:[?#\s]|$)/,"zerochan"]];function _l(e){let t=/(\d+)_p(\d+)/.exec(e.source);return[...e.md5?[`md5:${e.md5}`]:[],...t&&e.source.includes("pximg")?[`pixiv:${t[1]}_p${t[2]}`]:[]]}function wb(e,t){let n=wM.exec(t.source)?.[1]?.toLowerCase();return[`post:${e.key}:${t.id}`,...t.md5?[`md5:${t.md5}`]:[],...n&&n!==t.md5?[`md5:${n}`]:[],...$M.flatMap(([r,i])=>{let s=r.exec(t.source)?.[1];return s?[`post:${i}:${Number(s)}`]:[]}),...t.family?[`family:${e.key}:${t.family}`]:[]]}function $b(e,t){let n=e.owner||e.named.artist[0]||"";return n!==""&&n===(t.owner||t.named.artist[0]||"")&&e.width===t.width&&e.height===t.height}function kb(e){let r=[];for(let s=0;s<8;s++){let o=Math.floor(s*e.height/8),a=Math.max(o+1,Math.floor((s+1)*e.height/8));for(let u=0;u<9;u++){let c=Math.floor(u*e.width/9),l=Math.max(c+1,Math.floor((u+1)*e.width/9)),h=0;for(let f=o;f<a;f++)for(let d=c;d<l;d++){let g=(f*e.width+d)*4,p=e.data[g+3]/255,b=0.299*e.data[g]+0.587*e.data[g+1]+0.114*e.data[g+2];h+=b*p+255*(1-p)}r.push(h/((l-c)*(a-o)))}}let i=0n;for(let s=0;s<8;s++)for(let o=0;o<8;o++)i=i<<1n|(r[s*9+o]>r[s*9+o+1]?1n:0n);return i.toString(16).padStart(16,"0")}function kM(e,t){let n=BigInt(`0x${e}`)^BigInt(`0x${t}`),r=0;while(n>0n)r+=Number(n&1n),n>>=1n;return r}function yb(e,t){if(e.width<=0||e.height<=0||t.width<=0||t.height<=0)return!1;return Math.abs(Math.log(e.width/e.height/(t.width/t.height)))<0.01&&kM(e.hash,t.hash)<=2}var SM={thumb:"tile",band:"band",match:"tile",show:"view",backdrop:"view",redraw:"view"},Xa;async function IM(e){if(e.job==="redraw")return qm(e.home,e.name,e.key,e.hue,e.blur,e.aligns,e.user);if(e.job==="show"){if(Xa?.from!==e.from){let s=Ln(new Uint8Array(Gl(e.from)),pt);Xa={from:e.from,clear:fn(s),inked:wc(s)}}let{image:r,fill:i}=pg(Xa.inked,e.colors,e.tone,e.width,e.height,e.blur,e.tune);return yM(EM(e.to),{recursive:!0}),Eb(e.to,Ao(r)),{clear:Xa.clear,fill:i}}let t=Ln(new Uint8Array(Gl(e.from)),pt);if(e.job==="backdrop"){ra(e.home,e.colors,e.tone,t,{...e.origin,bytes:new Uint8Array(Gl(e.source)),cut:e.from!==e.source},e,e.blur);let r=e.tune&&Ot(e.home,e.colors.name).find((i)=>i.key===ct(e.origin));if(e.tune&&r)gs(je(e.home),r,e.tune,e.aligns??!0,e.user??e.home);return 0}if(e.job==="match")return{match:bb(t,e.colors),hash:kb(t)};if(e.job==="thumb")return Z(e.to,Ao(fd(t,e.width,e.height))),0;let n=t.data.subarray(e.y*t.width*4,(e.y+e.height)*t.width*4);return Eb(e.to,Ao({width:t.width,height:e.height,data:n})),0}function NM(e){e.on("message",async(t)=>{try{e.postMessage({id:t.id,value:await IM(t)})}catch(n){e.postMessage({id:t.id,error:n instanceof Error?n.message:String(n)})}})}class Ul{worker;next=1;waiting=new Map;send(e){let t=this.next++;return new Promise((n,r)=>{let i=this.open();this.waiting.set(t,{ok:n,no:r}),i.ref(),i.postMessage({...e,id:t})})}close(){this.worker?.terminate(),this.worker=void 0,this.drop(Error("renderer closed"))}open(){if(this.worker)return this.worker;let e=new MM(import.meta.filename);e.unref(),e.on("message",({id:n,value:r,error:i})=>{let s=this.waiting.get(n);if(this.waiting.delete(n),this.waiting.size===0)e.unref();if(i!==void 0)s?.no(Error(i));else s?.ok(r)});let t=(n)=>{if(this.worker===e)this.worker=void 0;this.drop(n instanceof Error?n:Error("renderer stopped"))};return e.on("error",t),e.on("exit",()=>t(void 0)),this.worker=e,e}drop(e){for(let t of this.waiting.values())t.no(e);this.waiting.clear()}}class jl{lines=new Map;run(e){let t=SM[e.job],n=this.lines.get(t);if(!n)n=new Ul,this.lines.set(t,n);return n.send(e)}close(){for(let e of this.lines.values())e.close();this.lines.clear()}}class Wl{lines;constructor(e){this.lines=Array.from({length:Math.max(1,e)},()=>new Ul)}async map(e){let t=[],n=0;return await Promise.all(this.lines.map(async(r)=>{while(n<e.length){let i=n++;try{t[i]=await r.send(e[i])}catch(s){t[i]=s instanceof Error?s:Error(String(s))}}})),t}close(){for(let e of this.lines)e.close()}}if(!vM&&vb)NM(vb);var Hr=[{name:"TTHEME_FIND_RATING",label:"Rating",about:"The ratings to list, each site read in its own words — space ticks one, and one stays ticked",choices:Yr,multi:{read:fr}},{name:"TTHEME_FIND_BLOCK",label:"Block",about:"Posts tagged with nudity or underwear are left out — space unticks one",choices:lr,multi:{read:Zr,none:"none"}},{name:"TTHEME_FIND_POSTS",label:"Posts",about:"Every post of the character, or only the transparent cutouts",choices:["all","cutouts"]},{name:"TTHEME_FIND_SOLO",label:"Solo",about:"When on, only the posts known to show the character alone — checked as posts arrive, so the counts below leave it out",choices:["on","off"]},{name:"TTHEME_FIND_ORDER",label:"Order",about:"How posts are ranked: fit, by how well each makes a backdrop; newest; or score",choices:["fit","newest","score"]},{name:"TTHEME_FIND_SETS",label:"Sets",about:"One picture posted over and over, or held by another site too: fold it into one tile, or show each",choices:["fold","show"]},...$i()?[{name:"TTHEME_FIND_REMOVE_BG",label:"Remove bg",about:"Cut the character out of an opaque picture you try on, with macOS Vision",choices:["on","off"]}]:[],{name:"TTHEME_FIND_MIN_SCORE",label:"Min score",about:"Posts scored at least this — danbooru, konachan and yande.re; zerochan keeps no score. ←→ steps, or type any number",choices:Od,entry:"number",advanced:!0},{name:"TTHEME_FIND_MIN_SIZE",label:"Min size",about:"The shorter side of a picture, in px — every site filters it. ←→ steps, or type any number",choices:Td,entry:"number",advanced:!0},{name:"TTHEME_FIND_SITES",label:"Sites",about:"The sites the all tab mixes — each keeps its own tab. Space ticks one, and one stays ticked",choices:V.map((e)=>e.name),multi:{read:ss},advanced:!0},{name:"TTHEME_FIND_HIDE",label:"Hide",about:"Comics, monochrome, sketches or chibi, told by tag in every site's spelling — checked as posts arrive",choices:rc,multi:{read:Uo,none:"none"},advanced:!0},{name:"TTHEME_FIND_HIDE_TAGS",label:"Hide tags",about:"Posts with any of these tags are left out, spaced like cosplay multiple_girls — checked as posts arrive",choices:[],entry:"text",advanced:!0},{name:"TTHEME_FIND_PNG",label:"PNG only",about:"PNG originals only — danbooru counts it, the others are told by the file; zerochan only where danbooru holds it",choices:["off","on"],advanced:!0}];function Sb(e,t){if(e.multi)return e.multi.read(t).join(" ")||e.multi.none;if(e.entry==="number")return/^\d+$/.test(t??"")&&Number(t)>0?String(Number(t)):"off";if(e.entry==="text")return os(t).join(" ");return e.choices.find((n)=>n===t)??e.choices[0]}var LM=["fit","newest","score"];function Kl(e){return LM.find((t)=>t===e)??"fit"}var xM={left:-1,right:1,"shift-left":-10,"shift-right":10};function CM(e){let t=/^(\d+) (\d+)$/.exec(e??"");return t&&(Number(t[1])>0||Number(t[2])>0)?{x:Number(t[1]),y:Number(t[2])}:void 0}var Jl=CM(process.env.TTHEME_BG_MARGIN);function _M(e,t,n){if(t<0){if(e!=="fill")return Math.max(Rb,e+t);if(!n)return e;return Math.max(Rb,Math.max(100,n)+t+1)}return e==="fill"||e+t>n?"fill":e+t}function Cb(e,t){return e.size===t.size&&e.at===t.at&&e.opacity===t.opacity}function GM(e,t){if(Cb(e,t))return;return{...e.size!=="fill"?{size:e.size}:{},...e.at!==t.at?{position:bt[e.at-1]}:{},...e.opacity!==t.opacity?{opacity:e.opacity}:{}}}function UM(e){return e.length>=2&&!/^\d+$/.test(e)&&!e.includes("://")&&!/^[\w.]+:\d+$/.test(e)}var Ib=12,jM=4,WM=150,KM=300,Nb=12,JM=2,BM=150,qM=30,zM=4000,YM=8000,Pb=/\.(png|jpe?g|gif|webp|heic|tiff?|bmp)$/i,QM=process.platform==="win32"?"alt+v":"ctrl+v",Fb=process.platform==="darwin"?"ctrl+shift+cmd+4 copies a screenshot":"copy a picture first",ZM=1280,VM=16,XM=bt.indexOf("top-right")+1,Rb=20,co=2147483645,lo=2147483646,Ob=-1073741827,DM=-1073741828,Tb=2,eS=80,tS=16,nS=0.4,rS=3221225472,iS=256,sS=3,oS=8;function Da(e,t){return{key:e,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:t,stage:"fetch",arrived:new Set}}function ho(e){if(!(e instanceof Error))return String(e);if(e instanceof AggregateError&&e.errors[0])return ho(e.errors[0]);if(e.cause)return ho(e.cause);let t=e.code;if(typeof t==="string")return t;let n=(e.message||e.name).split(".")[0]??"";return n.length>56?`${n.slice(0,55)}…`:n}function Bl(e,t){return`${e}: ${ho(t)}`}function Hb(e){return e.width*e.height}function Ab(e,t){return`${e}-${Lb("sha1").update(t).digest("hex").slice(0,8)}`}function aS(e){let t=e.lastIndexOf("\x1B");return t!==-1&&/^\[?[0-9;]*$/.test(e.slice(t+1))}function uS(e,t){try{return JSON.parse(xb(qt(Xt(e),t),"utf8"))}catch{return{}}}function cS(e,t,n){Z(qt(Xt(e),t),`${JSON.stringify(n)}
497
+ `)}class ql{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(Hr.map((e)=>[e.name,Sb(e,process.env[e.name])]));direction=1;prefetching=0;inflight=new Map;owners=new Map;kept=new Map;unsaved=new Set;crediting=new Map;thumbQueue=[];thumbing=0;clarity=new Map;tunedFiles=[];presenting=!1;again=!1;covered="";renders=new jl;sent=new Map;placed=new Map;screen=[];ticking;gliding;showing;thumbless=new Set;bands=om(process.env);bandFiles=new Map;nextBand=rS;current;fetch;settle;partial;suggestTimer;suggesting;countTimer;counting;input="";typed="";grabber=new Ml((e)=>this.write(e),(e)=>void this.got(e));featureWait;noticeTimer;peekTimer;peeked;attaching;probeWait;done;dirty=!1;scratch=RM(qt(HM(),"ttheme-find-"));home;catalog;entry;blurring;start;constructor(e,t,n,r,i){this.start=i,this.home=e,this.catalog=t,this.entry=n,this.tone=ni(n,n.signatureSlots),this.blurring=gi(e);let s={size:"fill",at:XM,opacity:this.tone.opacity};this.view={palette:n.name,tag:r,site:this.tabName,siteAnsi:this.tabAnsi,nextSite:this.nextTabName,preset:this.setting("TTHEME_FIND_POSTS")==="all"?"all":"cutouts",order:Kl(this.setting("TTHEME_FIND_ORDER")),solo:this.setting("TTHEME_FIND_SOLO")==="on",rating:fr(this.setting("TTHEME_FIND_RATING")),block:Zr(this.setting("TTHEME_FIND_BLOCK")),sets:this.setting("TTHEME_FIND_SETS")==="show"?"show":"fold",narrow:this.narrowed(),enabled:ss(this.setting("TTHEME_FIND_SITES")),hide:Uo(this.setting("TTHEME_FIND_HIDE")),hideTags:os(this.setting("TTHEME_FIND_HIDE_TAGS")),advanced:!1,settings:Hr.map((o)=>({label:o.label,choices:[...o.choices],value:this.setting(o.name),default:Sb(o,Cc(o.name)),multi:o.multi&&{none:o.multi.none},about:o.about,entry:o.entry,advanced:o.advanced,cursor:0})),colors:{cursor:n.cursor,selection:n.selection,background:n.background,foreground:n.foreground,ansi:n.ansi},tiles:[],installed:[],checked:0,total:0,searching:r!=="",stage:"fetch",sites:[],focus:0,top:0,scroll:0,beat:0,mode:"grid",help:!1,scene:Math.max(0,Ht.findIndex((o)=>o.name.toLowerCase()===process.env.TTHEME_SCENE)),details:!1,tune:{...s},untuned:s,editing:r===""?"":void 0},this.board=Da(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:V[this.tab-1]}get sites(){return this.site?[this.site]:V.filter((e)=>this.view.enabled.includes(e.name))}get tabName(){return this.site?.name??"all"}get tabAnsi(){return this.site?.ansi??jM}get nextTabName(){let e=(this.tab+1)%(V.length+1);return e===0?"all":V[e-1].name}frame(){return{w:this.cols*(this.cell.w||10),h:this.rows*(this.cell.h||20)}}setting(e){return this.values.get(e)}narrowed(){return sc(this.setting("TTHEME_FIND_MIN_SCORE"),this.setting("TTHEME_FIND_MIN_SIZE"),this.setting("TTHEME_FIND_PNG"))}get boardKey(){return`${this.site?.key??"all"}|${this.view.preset}|${this.view.order}`}origPath(e,t,n){return qt(Xt(e),"orig",`${t}.${n}`)}previewPath(e){let{url:t}=Wo(e.site,e.post);return qt(Xt(e.site),"thumb",`${Ab(e.post.id,t)}.${Un(t)}`)}tileOf(e,t){let{site:n,post:r}=e,i=Rt(n,r.id),s=Vt(r)??r;return{id:r.id,key:i,site:n.name,siteAnsi:n.ansi,width:s.width,height:s.height,reduced:s!==r,page:n===Nr?"":n.pageUrl(r.id),artist:n===Nr?Ip(r.source):r.named.artist[0]??"",score:r.score,variants:t,mates:this.owners.get(n.key)?.get(r.owner)??[],thumb:this.thumbPath.get(i),missing:this.thumbless.has(i)}}show(){let e=this.view,t=this.board;if(e.tiles=t.groups.flatMap((n)=>n.open?n.posts.map((r)=>this.tileOf(r,0)):[this.tileOf(n.posts[0],n.posts.length)]),e.checked=t.checked,e.total=t.total,e.searching=t.searching,this.stageOf(t),e.note=t.note,e.focus=Math.max(0,Math.min(t.focus,e.tiles.length-1)),e.top=t.top,this.showing!==t)this.showing=t,this.snap()}stageOf(e){let t=this.view;t.stage=e.stage,t.ranking=e.ranking,t.sites=this.sites.map((n)=>({name:n.name,arrived:e.arrived.has(n.name)}))}syncSite(){let e=this.view;e.site=this.tabName,e.siteAnsi=this.tabAnsi,e.nextSite=this.nextTabName}async run(){let{stdin:e,stdout:t}=process;e.setRawMode(!0),e.resume(),e.on("data",this.onData),t.on("resize",this.onResize),this.write(`\x1B[?25l\x1B[?7l${hi}`);let n=new Promise((o)=>{this.done=o}),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";if(await this.features(),this.grabber.start(),this.write("\x1B[?1004h"),this.start&&"paste"in this.start)this.pasted(this.start.paste);else if(this.start)this.fromClipboard();else this.peek();this.draw();let s=await n;return this.session.abort(),this.grabber.stop(),this.write("\x1B[?1004l"),this.attaching?.abort(),clearTimeout(this.noticeTimer),clearTimeout(this.peekTimer),this.fetch?.abort(),clearTimeout(this.settle),clearTimeout(this.partial),this.quietSuggest(),this.quietCount(),clearInterval(r),clearInterval(this.ticking),clearTimeout(this.gliding),e.off("data",this.onData),t.off("resize",this.onResize),this.write(`\x1B_Ga=d,d=A,q=2\x1B\\${hi}`),e.setRawMode(!1),e.pause(),this.saveKept(),this.renders.close(),uo(this.scratch,{recursive:!0,force:!0}),Bd(),s}write(e){process.stdout.write(e)}get saved(){return this.view.saved?.text}get installs(){return this.view.installed.length}finish(e){this.done?.(e===2&&this.saved?0:e)}probe(){return new Promise((e)=>{let t=setTimeout(()=>{this.probeWait=void 0,e(null)},1000);this.probeWait=(n)=>{clearTimeout(t),this.probeWait=void 0,e(n)},this.write(Kp)})}onData=(e)=>{this.input+=e.toString("utf8");for(let n=Fl(this.input);n;n=Fl(this.input))this.input=n.rest,this.probeWait?.(n.cell);if(this.probeWait)return;let t=_a(this.input);if(this.input=t.pending,this.view.editing===void 0&&t.keys.length>8&&/^(?:\/|~\/|file:|https?:)/.test(t.keys))this.pasted(t.keys),t.keys="";this.typed+=t.keys;for(let n of t.events)this.inbound(n);if(clearTimeout(this.partial),aS(this.typed)){this.partial=setTimeout(this.flushKeys,qM);return}this.flushKeys()};flushKeys=()=>{let e=ja(this.typed);this.typed="";for(let t of e)this.key(t)};features(){if(process.env.TMUX)return Promise.resolve();return new Promise((e)=>{let t=setTimeout(()=>{this.featureWait=void 0,e()},500);this.featureWait=()=>{clearTimeout(t),this.featureWait=void 0,e()},this.write("\x1B[?5522$p\x1B]72;t=q\x1B\\\x1B[c")})}inbound(e){if(e.kind==="mode"){if(e.mode===5522)this.grabber.clipboard=e.value!==0&&e.value!==4;return}if(e.kind==="attributes"){this.featureWait?.();return}if(e.kind==="osc"){if(e.code==="72"&&e.meta.t==="q"){this.grabber.drops=!0;return}this.grabber.take(e);return}this.pasted(e.text)}pasted(e){let t=this.view;if(t.editing!==void 0&&e.trim()!==""&&!this.picture(e)){t.editing+=e.replace(/[\r\n]+/g," "),this.suggest(),this.draw();return}if(t.installing!==void 0||t.panel!==void 0||t.help)return;if(e.trim()===""){this.fromClipboard();return}this.attach(e)}picture(e){let t=e.trim();if(/^https?:\/\/\S+$/i.test(t))return!jo(t,this.site??V[0]);return Ii(t).length>0}async got(e){if(e.kind==="error"){this.notice(e.message);return}if(e.kind==="text"){if(e.text.trim()===""){this.notice(`No picture on the clipboard — ${Fb}`);return}this.pasted(e.text);return}await this.bring(()=>xa(e.bytes,e.source))}notice(e,t=zM){let n=this.view;n.error=e,clearTimeout(this.noticeTimer),this.noticeTimer=setTimeout(()=>{if(n.error===e)n.error=void 0,this.draw()},t),this.draw()}async peek(){let e=this.view,t;try{t=await Op()}catch{return}if(!t||t.stamp===this.peeked)return;if(this.peeked=t.stamp,!t.picture||e.installing!==void 0)return;e.hint=`Picture on the clipboard · ${QM} uses it`,clearTimeout(this.peekTimer),this.peekTimer=setTimeout(()=>{e.hint=void 0,this.draw()},YM),this.draw()}async fromClipboard(){let e=this.view;if(vl()){if(this.grabber.clipboard){this.grabber.ask();return}this.notice("Over SSH the clipboard is not here — drop the file");return}let t;try{t=await Rp(qt(this.scratch,`clipboard-${Date.now()}.png`))}catch(r){this.notice(`Could not read the clipboard: ${ho(r)}`);return}if(clearTimeout(this.peekTimer),e.hint=void 0,"image"in t){await this.bring(async(r)=>({...await El(t.image,r),source:"clipboard"}));return}let n=t.text.trim();if(!n){this.notice(`No picture on the clipboard — ${Fb}`);return}if(this.picture(n)){await this.attach(n);return}if(e.editing===void 0)e.editing="";this.pasted(n)}async attach(e){let t=e.trim();if(/^https?:\/\//i.test(t)){let i=jo(t,this.site??V[0]);if(i){await this.jump(i.site,i.id);return}}let[n,...r]=Ii(t).sort((i,s)=>Number(!Pb.test(i))-Number(!Pb.test(s)));if(!n){this.notice("Nothing to use in that — drop a picture, or paste one or its link");return}await this.bring((i)=>El(n,i),r.length)}async bring(e,t=0){let n=this.view;this.attaching?.abort();let r=new AbortController;this.attaching=r,n.error=void 0,n.saved=void 0,n.note="Reading the picture…",this.draw();let i;try{i=await e(AbortSignal.any([r.signal,this.signal]))}catch(f){if(!r.signal.aborted)n.note=void 0,this.notice(ho(f),8000);return}if(r.signal.aborted)return;n.note=t>0?`The first picture of ${t+1} — drop one at a time to try the others`:void 0,this.quietSuggest(),n.editing=void 0,n.suggest=void 0,n.pick=void 0;let s=Pp(i.bytes);Np(s,i.source);let o=this.origPath(Nr,s,i.ext);Z(o,i.bytes);let a=Mb(o).href,u={id:s,file:a,width:i.width,height:i.height,ext:i.ext,preview:a,owner:"",score:0,rating:"s",md5:Lb("md5").update(i.bytes).digest("hex"),source:i.source,tags:[],named:{artist:[],character:[],copyright:[]},solo:void 0,family:0,smaller:[]},c={site:Nr,post:u},l=this.previewPath(c);Z(l,i.bytes),++this.gen,this.current=void 0,n.shown=void 0;let h=Da(`local|post:${s}`,!1);this.board=h,this.boards.set(h.key,h),this.single(h,c)}single(e,t){e.searching=!1,this.posts.set(Rt(t.site,t.post.id),t),e.groups=[{posts:[t],open:!1}],e.checked=1,e.total=1,this.thumbQueue.push(t),this.thumbs(),this.view.mode="try",this.show(),this.select(),this.draw()}onClock=()=>{let e=this.sites.reduce((r,i)=>Gn(i)>Gn(r)?i:r),t=Math.ceil((Gn(e)-Date.now())/1000),n=t>0?t:void 0;if(n!==this.view.waiting)this.view.waiting=n,this.view.slow=e.name,this.draw()};onResize=()=>{if(this.cols=process.stdout.columns||this.cols,this.rows=process.stdout.rows||this.rows,this.screen=[],this.scroll(),this.snap(),this.view.mode==="try"&&this.current)this.reveal();this.pump(),this.draw()};key(e){let t=this.view;if(e==="ctrl-c"){this.finish(2);return}if(t.installing!==void 0)return;if(e==="focus-in"){this.peek();return}if(e==="focus-out"||e==="nop")return;if((e==="ctrl-v"||e==="alt-v")&&t.panel===void 0){this.fromClipboard();return}if(t.editing!==void 0){this.editKey(e);return}if(t.panel!==void 0){this.panelKey(e);return}if(t.help){if(e==="?"||e==="esc")t.help=!1,this.draw();return}if(this.cols<Fr.cols||this.rows<Fr.rows){if(e==="esc")this.finish(2);return}if(e==="?"){t.help=!0,this.draw();return}if(t.mode==="try"){this.tryKey(e);return}this.gridKey(e)}gridKey(e){let t=this.view,{perRow:n,rowsVis:r}=Rr(this.cols,this.rows),s={left:-1,right:1,up:-n,down:n,pgup:-n*r,pgdn:n*r,home:-t.focus,end:t.tiles.length}[e];if(s!==void 0){this.focus(t.focus+s);return}if(e==="enter"&&t.tiles[t.focus]){t.mode="try",t.error=void 0,this.select();return}if(e==="v"){this.fromClipboard();return}if(e==="c"){t.preset=t.preset==="cutouts"?"all":"cutouts",this.turn();return}if(e==="tab"||e==="shift-tab"){let o=V.length+1;this.tab=(this.tab+(e==="tab"?1:o-1))%o,this.syncSite(),this.turn();return}if(e==="/"){t.editing="",this.draw();return}if(e===" "){this.unfold();return}if(e==="o"){this.openPage();return}if(e==="s"){t.panel=0,t.advanced=!1,this.recount(),this.draw();return}if(e==="esc")this.finish(2)}panelKey(e){let t=this.view,n=t.panel??0,r=t.settings[n];if(t.typing!==void 0&&r){this.typeKey(r,e);return}let i=no(t);if(e==="up"||e==="down"){let s=i.indexOf(n)+(e==="up"?-1:1);t.panel=i[(s+i.length)%i.length]??n,this.draw();return}if(e==="a"||e==="enter"&&n===t.settings.length){t.advanced=!t.advanced,t.panel=no(t)[0]??0,this.draw();return}if(r?.entry&&(e==="enter"||r.entry==="number"&&/^[0-9]$/.test(e))){t.typing=e==="enter"?r.entry==="text"?r.value:"":e,this.draw();return}if((e==="left"||e==="right")&&r&&r.entry!=="text"){let s=e==="left"?-1:1;if(r.multi)r.cursor=(r.cursor+s+r.choices.length)%r.choices.length;else r.value=Xp(r.choices,r.value,s),this.recount();this.draw();return}if(e===" "&&r?.multi){let s=r.value.split(" "),o=r.choices.filter((u,c)=>c===r.cursor?!s.includes(u):s.includes(u)),a=r.multi.none;if(o.length>0||a!==void 0)r.value=o.length>0?o.join(" "):a,this.recount(),this.draw();return}if(e==="esc"){t.settings.forEach((s,o)=>{s.value=this.setting(Hr[o]?.name??"")}),t.panel=void 0,t.advanced=!1,this.quietCount(),this.draw();return}if(e==="enter"||e==="s"||e==="alt-c")t.panel=void 0,t.advanced=!1,this.quietCount(),this.adopt()}typeKey(e,t){let n=this.view,r=n.typing??"";if(t==="esc"){n.typing=void 0,this.draw();return}if(t==="enter"||t==="up"||t==="down"){if(e.value=e.entry==="number"?Number(r)>0?String(Number(r)):"off":os(r).join(" "),n.typing=void 0,this.recount(),t==="enter"){this.draw();return}this.panelKey(t);return}if(t==="backspace"){n.typing=r.slice(0,-1),this.draw();return}if(e.entry==="number"?/^[0-9]$/.test(t)&&r.length<Rl:/^[\x20-\x7e]$/.test(t))n.typing=r+t,this.draw()}quietCount(){clearTimeout(this.countTimer),this.counting?.abort(),this.counting=void 0}recount(){if(this.quietCount(),this.view.counts=void 0,!this.view.tag)return;let e=new AbortController;this.counting=e,this.countTimer=setTimeout(()=>void this.countPending(e),KM)}pending(){let e=(t)=>this.view.settings[Hr.findIndex((n)=>n.name===t)]?.value??this.setting(t);return{tag:this.view.tag,preset:e("TTHEME_FIND_POSTS")==="all"?"all":"cutouts",order:Kl(e("TTHEME_FIND_ORDER")),rating:fr(e("TTHEME_FIND_RATING")),narrow:sc(e("TTHEME_FIND_MIN_SCORE"),e("TTHEME_FIND_MIN_SIZE"),e("TTHEME_FIND_PNG")),enabled:ss(e("TTHEME_FIND_SITES"))}}async countPending(e){let t=this.pending(),n=this.site?[this.site]:V.filter((s)=>t.enabled.includes(s.name)),r=AbortSignal.any([this.signal,e.signal]),i=await Promise.all(n.map(async(s)=>{let o=this.query(s,t);if(!o)return{site:s.name,count:0};if(s.counts&&!s.counts(o.tags))return{site:s.name};try{let a=await cc(s,o.tags,r);return{site:s.name,...Number.isFinite(a)?{count:a}:{}}}catch{return{site:s.name}}}));if(this.counting===e&&this.view.panel!==void 0)this.view.counts=i,this.draw()}adopt(){let e=this.view,t=Hr.map((r)=>this.setting(r.name));e.settings.forEach((r,i)=>{let s=Hr[i];if(s)this.values.set(s.name,r.value)});let n=Hr.filter((r,i)=>this.setting(r.name)!==t[i]);if(n.length===0){this.draw();return}this.save(n),e.rating=fr(this.setting("TTHEME_FIND_RATING")),e.block=Zr(this.setting("TTHEME_FIND_BLOCK")),e.sets=this.setting("TTHEME_FIND_SETS")==="show"?"show":"fold",e.preset=this.setting("TTHEME_FIND_POSTS")==="all"?"all":"cutouts",e.order=Kl(this.setting("TTHEME_FIND_ORDER")),e.solo=this.setting("TTHEME_FIND_SOLO")==="on",e.narrow=this.narrowed(),e.enabled=ss(this.setting("TTHEME_FIND_SITES")),e.hide=Uo(this.setting("TTHEME_FIND_HIDE")),e.hideTags=os(this.setting("TTHEME_FIND_HIDE_TAGS")),this.boards.clear(),this.current=void 0,e.shown=void 0,e.mode="grid",this.search()}save(e){this.store(e.map((t)=>[t.name,this.setting(t.name)]))}store(e){let t=qt(this.home,"ttheme","config.zsh");try{let n=Oi(t)?xb(t,"utf8"):"";return Z(t,e.reduce((r,[i,s])=>pm(r,i,s),n)),!0}catch(n){return this.view.error=n instanceof Error?n.message:String(n),!1}}editKey(e){let t=this.view,n=t.editing??"",r=t.suggest??[];if((e==="up"||e==="down")&&r.length>0){let s=((t.pick??r.length)+(e==="down"?1:r.length))%(r.length+1);t.pick=s===r.length?void 0:s,this.draw();return}if(e==="esc"||e==="enter")this.quietSuggest();if(e==="esc"){if(t.editing=void 0,t.tag===""){this.finish(2);return}this.draw();return}if(e==="enter"){let i=t.pick===void 0?void 0:r[t.pick],s=i?n.replace(/\S*$/,i.value):n;if(t.editing=void 0,t.suggest=void 0,t.pick=void 0,s.trim()){this.commit(s.trim());return}if(t.tag===""){this.finish(2);return}this.draw();return}if(e==="backspace"){t.editing=n.slice(0,-1),this.suggest(),this.draw();return}if(e.length===1&&e>=" ")t.editing=n+e,this.suggest(),this.draw()}quietSuggest(){clearTimeout(this.suggestTimer),this.suggesting?.abort(),this.suggesting=void 0}suggest(){this.quietSuggest();let e=this.view;e.pick=void 0;let t=/\S*$/.exec(e.editing??"")?.[0]??"";if(!UM(t)){e.suggest=void 0;return}let n=[...new Map(Yg(this.catalog.palettes,this.entry,t).map((i)=>[i.booru,{value:i.booru,count:0,palette:i.name}])).values()].slice(0,sS);e.suggest=n.length>0?n:void 0;let r=new AbortController;this.suggesting=r,this.suggestTimer=setTimeout(async()=>{try{let i=await zd(t,AbortSignal.any([this.signal,r.signal]));if(this.suggesting===r&&e.editing!==void 0){let s=new Map(i.map((a)=>[a.value,a.count])),o=new Set(n.map((a)=>a.value));e.suggest=[...n.map((a)=>({...a,count:s.get(a.value)??0})),...i.filter((a)=>!o.has(a.value))].slice(0,oS),e.pick=e.pick!==void 0&&e.pick<n.length?e.pick:void 0,this.draw()}}catch{}},WM)}async commit(e){let t=jo(e,this.site??V[0]);if(t){await this.jump(t.site,t.id);return}if(this.picture(e)){await this.attach(e);return}this.view.tag=e,this.boards.clear(),await this.search()}async jump(e,t){let n=++this.gen;this.tab=V.indexOf(e)+1,this.syncSite(),this.current=void 0,this.view.shown=void 0,this.view.error=void 0;let r=Da(`${e.key}|post:${t}`,!0);this.board=r,this.boards.set(r.key,r),this.show(),this.draw();try{let i=await as(e,t,this.signal);if(n!==this.gen)return;if(!i){r.searching=!1,r.error=`${e.name} has no post ${t}`,this.view.error=r.error,this.show(),this.draw();return}this.single(r,{site:e,post:i})}catch(i){this.fail(n,i,e)}}async turn(){this.fetch?.abort(),this.current=void 0,this.view.shown=void 0;let e=this.boards.get(this.boardKey);if(!e){await this.search();return}this.gen++,this.board=e,this.view.error=e.error,this.show(),this.draw(),await this.pump()}unfold(){let e=this.view,t=0;for(let n of this.board.groups){let r=n.open?n.posts.length:1;if(e.focus<t+r){if(n.posts.length<2)return;n.open=!n.open,this.board.focus=t;for(let i of n.posts)if(!this.thumbPath.has(Rt(i.site,i.post.id)))this.thumbQueue.push(i);this.thumbs(),this.show(),this.scroll(),this.glide(),this.draw();return}t+=r}}openPage(){let e=this.view.tiles[this.view.focus],t=e&&this.posts.get(e.key);if(!t)return;let n=process.platform==="darwin"?"open":"xdg-open";try{PM(n,[t.site.pageUrl(t.post.id)],{stdio:"ignore",detached:!0}).unref()}catch{}}tryKey(e){let t=this.view;if(t.tuning){this.tuneKey(e);return}if(e==="left"||e==="right"){this.direction=e==="left"?-1:1,this.focus(t.focus+this.direction);return}if(e==="shift-left"||e==="shift-right"){t.scene+=e==="shift-left"?-1:1,t.details=!1,this.draw();return}if(e==="i"){t.details=!t.details,this.inform(),this.draw();return}if(e==="t"){t.tuning={field:0,held:{...t.tune},fill:this.current?.fill??0},this.draw();return}if(e==="o"){this.openPage();return}if(e==="x"){this.swap();return}if(e==="v"){this.fromClipboard();return}if(e==="enter"){this.install();return}if(e==="esc")this.fetch?.abort(),clearTimeout(this.settle),t.fetching=void 0,t.mode="grid",t.error=void 0,this.draw()}tuneKey(e){let t=this.view,n=t.tuning,r=t.tune;if(e==="up"||e==="down"){n.field=(n.field+(e==="up"?2:1))%3,this.draw();return}let i=xM[e];if(i!==void 0){if(n.field===0)r.size=_M(r.size,i,n.fill);else if(n.field===1)r.at=(r.at-1+Math.sign(i)+9)%9+1;else r.opacity=Math.max(0,Math.min(100,Math.round(r.opacity*100)+i))/100;this.retune();return}if(/^[1-9]$/.test(e)){n.field=1,r.at=Number(e),this.retune();return}if(e==="="){let s=t.untuned;if(n.field===0)r.size=s.size;else if(n.field===1)r.at=s.at;else r.opacity=s.opacity;this.retune();return}if(e==="+"){t.tune={...t.untuned},this.retune();return}if(e==="enter"){t.tuning=void 0,this.draw();return}if(e==="esc")t.tune={...n.held},t.tuning=void 0,this.retune()}retune(){if(this.draw(),this.current&&this.view.shown?.id===this.current.key)this.reveal()}inform(){let e=this.view,t=e.tiles[e.focus],n=t&&this.posts.get(t.key);e.info=n?this.infoOf(n):void 0}infoOf(e){let{site:t,post:n}=e,r=n.named,i=Kd(t,n),s=new Set([...r.artist,...r.character,...r.copyright]),o=us(n.source),a=/^https?:\/\//i.test(o)?o:t===Nr&&o.startsWith("/")?Mb(o).href:void 0;return{page:t===Nr?"":t.pageUrl(n.id),source:o,...a?{link:a}:{},artists:r.artist,characters:r.character,series:r.copyright,tags:n.tags.filter((u)=>!s.has(u)),...i?{rating:i}:{},...n.posted?{posted:n.posted}:{},ext:(Vt(n)??n).ext,uploader:n.owner}}focus(e){let t=this.view;if(t.tiles.length===0)return;let n=Math.max(0,Math.min(t.tiles.length-1,e));if(n===t.focus)return;if(t.focus=n,this.board.focus=n,this.scroll(),this.glide(),this.pump(),t.mode==="try")this.select();this.draw()}scroll(){let e=this.view,{perRow:t,rowsVis:n}=Rr(this.cols,this.rows),r=Math.floor(e.focus/t);if(r<e.top)e.top=r;if(r>e.top+n-1)e.top=r-n+1;this.board.top=e.top}glide(){if(this.bands)this.prebake();if(this.gliding)return;let e=Rr(this.cols,this.rows).height,t=()=>{let n=this.view,r=n.top*Be.height,i=r-n.scroll;if(i===0||n.mode!=="grid"){n.scroll=r;let s=this.gliding!==void 0;if(this.gliding=void 0,s)this.draw();return}if(Math.abs(i)>2*e)n.scroll=r-Math.sign(i)*e,i=r-n.scroll;n.scroll+=Math.sign(i)*Math.max(1,Math.round(Math.abs(i)*nS)),this.draw(),this.gliding=setTimeout(t,tS)};t()}snap(){clearTimeout(this.gliding),this.gliding=void 0,this.view.scroll=this.view.top*Be.height}prebake(){let e=this.view;for(let t of Ol({...e,scroll:e.top*Be.height},this.cols,this.rows).images)if(t.crop!==void 0)this.band(t.path,t.crop,t.rows)}query(e,t=this.view){let n=t.tag===this.entry.booru?Qg(this.entry,e.key):[t.tag];if(n.length===0)return;let r=n.length>1,i=t.preset==="cutouts"?e.cutouts:"",s=r&&i.includes("~"),o=[r?n.map((c)=>`~${c}`).join(" "):n[0],e.rate(t.rating),...e.narrow(t.narrow),s?"":i,t.order==="score"?e.best:""].filter(Boolean),a=[],u=[];for(let c of o)if(uc([...a,c].join(" "))<=e.tagBudget)a.push(c);else u.push(c);return{tags:a.join(" "),notes:[...u.length>0?[`${e.name} takes ${e.tagBudget} tags — ${u.join(" ")} left out`]:[],...s?[`${e.name} ORs the names, so cutouts are told by the file`]:[],...t.narrow.score>0&&!e.scored?[`${e.name} keeps no score`]:[],...t.narrow.png&&e.guesses?[`${e.name} names a file type only where danbooru holds the file`]:[]]}}async search(){let e=++this.gen,t=Da(this.boardKey,!0);this.board=t,this.boards.set(t.key,t),this.view.error=void 0;let n=this.sites.flatMap((s)=>{let o=this.query(s);return o?[{site:s,...o}]:[]}),r=this.sites.filter((s)=>!n.some((o)=>o.site===s)),i=[...n.flatMap(({notes:s})=>s),...r.length>0?[`${this.entry.name} has no tag on ${r.map((s)=>s.name).join(", ")}`]:[]];if(t.note=i.length>0?i.join(" · "):void 0,n.length===0)t.searching=!1;this.show(),this.draw(),this.tally(e,t,n);try{let s=await Promise.all(n.map(async(o)=>({plan:o,owners:await this.mateOwners(o.site)})));if(e!==this.gen)return;t.sources=s.flatMap(({plan:{site:o,tags:a},owners:u})=>{let c=uc(a)+1<=o.tagBudget?o.uploadedBy:void 0;return[...c?[...u.keys()].map((l)=>({site:o,tags:`${a} ${c(l)}`,page:0,done:!1})):[],{site:o,tags:a,page:0,done:!1}]}),this.show(),this.draw(),await this.pump()}catch(s){this.fail(e,s)}}async tally(e,t,n){let r=await Promise.allSettled(n.map(({site:i,tags:s})=>cc(i,s,this.signal)));if(e===this.gen)t.total=r.reduce((i,s)=>i+(s.status==="fulfilled"&&Number.isFinite(s.value)?s.value:0),0),this.show(),this.draw()}fail(e,t,n=this.site){if(e!==this.gen||this.signal.aborted)return;this.board.error=Bl(n?.name??this.tabName,t),this.board.searching=!1,this.view.error=this.board.error,this.show(),this.draw()}drop(e,t,n){for(let r of e.sources)if(r.site===t)r.done=!0;e.note=[e.note,Bl(t.name,n)].filter(Boolean).join(" · ")}wants(){let{perRow:e,rowsVis:t}=Rr(this.cols,this.rows);return this.view.tiles.length<(this.board.top+t+Tb)*e}need(){let{perRow:e,rowsVis:t}=Rr(this.cols,this.rows);return(t+Tb)*e}live(e){return this.boards.get(e.key)===e}page(e,t,n){let r=`${e.key}|${t}|${n}`,i=this.pages.get(r);if(!i)i=qd(e,t,n,this.signal).then((s)=>this.borrow(e,s)),this.pages.set(r,i),i.catch(()=>this.pages.delete(r));return i}async borrow(e,t){let n=e===Ft?[]:t.filter((r)=>r.md5!=="");if(n.length>0)try{Yo(n,await Qo(n.map((r)=>r.md5),this.signal))}catch{}return t}staged(e){if(e===this.board)this.stageOf(e),this.draw()}async round(e){e.stage="fetch",this.staged(e);let t=V.flatMap((a)=>{let u=e.sources.find((c)=>c.site===a&&!c.done);return u?[u]:[]}),n=await Promise.all(t.map(async(a)=>{try{let u=await this.page(a.site,a.tags,a.page);return e.arrived.add(a.site.name),this.staged(e),{source:a,posts:u}}catch(u){if(e.sources.every((c)=>c.site===a.site)||this.signal.aborted)throw u;return this.drop(e,a.site,u),{source:a,posts:void 0}}}));if(!this.live(e))return;let r=[];for(let{source:a,posts:u}of n){if(!u)continue;a.page++,a.done=u.length<_n;let c=e.last.get(a);for(let l of u){let h=c&&$b(c.post,l)?c.set:`set:${a.site.key}:${l.id}`;c={post:l,set:h};let f=Rt(a.site,l.id);if(e.seen.has(f))continue;e.seen.add(f);let d={site:a.site,post:l};if(this.eligible(d))e.kin.set(d,[h,...wb(a.site,l)]),r.push(d);else e.checked++}if(c)e.last.set(a,c)}let i=this.dedupe(e,r),s=++e.rounds,o;if(this.view.order!=="fit")o=t.length>1?pb(i):i;else{let a=Va(i,this.frame(),this.matched),u=a.slice(0,this.need()),c={done:0,total:u.length};if(e.ranking=c,this.staged(e),await this.looks(u,()=>{c.done++,this.staged(e)}),e.ranking=void 0,!this.live(e))return;o=[...Va(u,this.frame(),this.matched),...a.slice(u.length)]}e.stage="check",this.staged(e);for(let a of o)e.roundOf.set(a,s);e.queue.push(...o),this.ahead(e)}ahead(e){if(this.aheading||this.view.order!=="fit"||!this.live(e))return;let t=e.queue.slice(0,this.need()).filter((n)=>!this.looking.has(Rt(n.site,n.post.id)));if(t.length===0)return;this.aheading=!0,this.looks(t).then(()=>{this.aheading=!1;for(let n of new Set(t.map((r)=>e.roundOf.get(r)??0)))this.resort(e,n);this.ahead(e)})}resort(e,t){let n=e.queue.flatMap((i,s)=>e.roundOf.get(i)===t?[s]:[]),r=Va(n.map((i)=>e.queue[i]),this.frame(),this.matched);n.forEach((i,s)=>{e.queue[i]=r[s]})}dedupe(e,t){let n=[];for(let r of t){let i=_l(r.post),s=i.map((a)=>e.same.get(a)).find(Boolean);if(!s){for(let a of i)e.same.set(a,r);n.push(r);continue}if(e.checked++,Hb(r.post)<=Hb(s.post))continue;for(let a of[...i,..._l(s.post)])e.same.set(a,r);let o=n.indexOf(s);if(o>=0){n[o]=r;continue}this.replace(e,s,r)}return n}replace(e,t,n){e.roundOf.set(n,e.roundOf.get(t)??0);let r=e.queue.indexOf(t);if(r>=0){e.queue[r]=n;return}for(let i of e.groups){let s=i.posts.indexOf(t);if(s>=0){i.posts[s]=n,this.posts.set(Rt(n.site,n.post.id),n),this.thumbQueue.push(n),this.thumbs();return}}}async looks(e,t){let n=0;await Promise.all(Array.from({length:Nb},async()=>{while(n<e.length)await this.look(e[n++]),t?.()}))}look(e){let t=Rt(e.site,e.post.id),n=this.looking.get(t);if(!n)n=(async()=>{let r=this.previewPath(e),i=Wo(e.site,e.post);await this.cached(i.site,r,i.url);let s=await this.renders.run({job:"match",from:r,colors:this.entry.signature});return this.looked.set(t,s),this.matched.set(e.post,s.match),s})().catch(()=>{return}),this.looking.set(t,n);return n}async pump(){let e=this.gen,t=this.board;if(this.pumping===e||t.sources.length===0)return;this.pumping=e;let n=[],r;try{t.searching=!0;while(e===this.gen){while(n.length<Ib&&t.queue.length>0&&this.wants()){let o=t.queue.shift();n.push({pick:o,passed:this.vet(o)})}if(this.ahead(t),!r&&t.queue.length<Ib&&t.sources.some((o)=>!o.done)&&this.wants()){let o=this.round(t).then(()=>{if(r===o)r=void 0});o.catch(()=>{}),r=o}let i=n.shift();if(!i){if(!r)break;await r,this.show(),this.draw();continue}let s=await i.passed;if(e!==this.gen)return;if(t.checked++,s)this.admit(i.pick);this.show(),this.draw()}if(e===this.gen)t.searching=!1,this.show(),this.draw()}catch(i){this.fail(e,i)}finally{if(this.saveKept(),this.pumping===e)this.pumping=0}}eligible({site:e,post:t}){let n=Vt(t);if(!Jo(e,t,this.view.rating)||Ko(t,this.view.block).length>0||!n)return!1;if(this.view.solo&&t.solo===!1)return!1;let{score:r,size:i,png:s}=this.view.narrow;if(Math.min(t.width,t.height)<i||e.scored&&t.score<r||s&&t.ext!=="png"||Wd(t,this.view.hide).length>0||this.view.hideTags.some((o)=>t.tags.includes(o)))return!1;return this.view.preset==="all"?["png","jpg","jpeg",""].includes(n.ext):["png",""].includes(t.ext)}async vet(e){let[t]=await Promise.all([this.passes(e),this.look(e)]);return t}async passes({site:e,post:t}){return this.view.preset==="all"||e.vouched||this.transparent(e,t)}keep(e,t){let n=`${e.key}/${t}`,r=this.kept.get(n);if(!r)r=uS(e,t),this.kept.set(n,r);return r}async transparent(e,t){let n=this.keep(e,"probes.json"),r=n[t.id];if(r!==void 0)return r;try{let i=await Zo(e,t,this.signal),s=Vr(e,t),o=(i===void 0?await Yd(s.site,s.url,this.signal):i)?.alpha===!0;return n[t.id]=o,this.unsaved.add(`${e.key}/probes.json`),o}catch{return!1}}saveKept(){for(let e of this.unsaved){let[t,n]=e.split("/"),r=V.find((i)=>i.key===t);if(r)cS(r,n,this.keep(r,n))}this.unsaved.clear()}admit(e){let{site:t,post:n}=e,r=this.board,i=Rt(t,n.id);this.posts.set(i,e);let s=r.kin.get(e)??[],o=this.looked.get(i),a=o&&{hash:o.hash,width:n.width,height:n.height},u=this.view.sets==="fold"?this.kindred(r,s,a):void 0;if(u){if(u.posts.push(e),this.register(r,u,s,a),u.open)this.thumbQueue.push(e),this.thumbs();return}let c={posts:[e],open:!1};r.groups.push(c),this.register(r,c,s,a),this.thumbQueue.push(e),this.thumbs()}kindred(e,t,n){for(let r of t){let i=e.kindred.get(r);if(i)return i}return n&&e.shapes.find((r)=>yb(r.shape,n))?.group}register(e,t,n,r){for(let i of n)if(!e.kindred.has(i))e.kindred.set(i,t);if(r)e.shapes.push({shape:r,group:t})}credit(e,t){let{site:n,post:r}=e;if(!zo(n,r))return Promise.resolve();let i=Rt(n,r.id),s=this.crediting.get(i);if(!s)s=this.credits(e,t).finally(()=>this.crediting.delete(i)),this.crediting.set(i,s);return s}async credits({site:e,post:t},n){let r=this.keep(e,"credits.json"),i=r[t.id];if(!i){try{i=await qo(e,t.id,n)}catch{return}if(!i?.owner)return;r[t.id]=i,this.unsaved.add(`${e.key}/credits.json`)}cs(t,i),this.show(),this.inform(),this.draw()}async mateOwners(e){let t=this.owners.get(e.key);if(t)return t;let n=Mg(this.home),r=this.keep(e,"owners.json"),i=this.catalog.palettes.flatMap((u)=>{let c=n.get(u.name);return u.group===this.entry.group&&u.name!==this.entry.name&&c?.site===e.key?[{name:u.name,id:c.id}]:[]}),s=await Promise.all(i.map(async(u)=>{let c=r[u.id];if(c!==void 0)return{...u,owner:c};try{return{...u,owner:(await as(e,u.id,this.signal))?.owner??""}}catch{return}})),o=new Map;for(let u of s)if(u)r[u.id]=u.owner,o.set(u.name,u.owner);this.unsaved.add(`${e.key}/owners.json`);let a=Jd(o);return this.owners.set(e.key,a),a}async cached(e,t,n,r){if(Oi(t))return OM(t).size;let i=this.inflight.get(t);if(i)return i;let s=(async()=>{let o=await Vo(e,n,this.signal,r);return Z(t,o),o.length})();this.inflight.set(t,s);try{return await s}finally{this.inflight.delete(t)}}thumbs(){while(!this.signal.aborted&&this.thumbing<Nb&&this.thumbQueue.length>0){let e=this.thumbQueue.shift();this.thumbing++,this.thumb(e).catch(()=>{this.thumbless.add(Rt(e.site,e.post.id)),this.show(),this.draw()}).finally(()=>{this.thumbing--,this.thumbs()})}}async thumb(e){let{site:t,post:n}=e,r=Be.cols*this.cell.w,i=Be.rows*this.cell.h,s=Wo(t,n),o=qt(Xt(t),"tile",`${Ab(n.id,s.url)}-${r}x${i}.png`);if(!Oi(o)){let a=this.previewPath(e);if(await this.cached(s.site,a,s.url),this.signal.aborted)return;await this.renders.run({job:"thumb",from:a,to:o,width:r,height:i})}this.thumbPath.set(Rt(t,n.id),o),this.show(),this.draw()}select(){let e=this.view,t=e.tiles[e.focus];if(this.fetch?.abort(),clearTimeout(this.settle),e.fetching=void 0,this.inform(),!t)return;if(this.current?.key===t.key){this.reveal();return}this.settle=setTimeout(()=>void this.load(t),BM),this.draw()}async load(e){let t=this.view,n=this.posts.get(e.key);if(!n)return;let r=new AbortController;if(this.fetch=r,this.credit(n,r.signal),!Vt(n.post))return;let{site:i}=n,s=this.board;try{await Zo(i,n.post,r.signal);let o=Vt(n.post),a=this.origPath(i,e.id,o.ext);if(!Oi(a))t.fetching={id:e.key,got:0,size:0},this.draw();let u=Vr(i,n.post,o),c=await this.cached(u.site,a,u.url,(f,d)=>{if(t.fetching?.id===e.key)t.fetching={id:e.key,got:f,size:d},this.draw()});if(r.signal.aborted)return;if(t.fetching=void 0,s!==this.board)return;let l={site:i,id:e.id,key:e.key,path:a,ext:o.ext,size:c,using:"plain",failed:!1};t.preparing=e.key,this.flush();let h=await this.render(l,"plain");if(r.signal.aborted||s!==this.board)return;if(h.clear===0&&$i()&&this.setting("TTHEME_FIND_REMOVE_BG")!=="off"){if(t.preparing=void 0,t.cutting=e.key,this.flush(),l.cut=await this.cutOut(i,e.id,a,r.signal),r.signal.aborted||s!==this.board)return;if(t.cutting=void 0,l.cut){t.preparing=e.key,this.flush();let f=await this.render(l,"cut").catch(()=>{return});if(r.signal.aborted||s!==this.board)return;if(f&&Sa(f.clear))l.using="cut";else uo(l.cut,{force:!0}),l.cut=void 0,l.failed=!0}else l.failed=!0}if(this.current=l,t.tiles[t.focus]?.key===e.key)await this.present();this.preload()}catch(o){if(!r.signal.aborted&&!this.signal.aborted)t.error=Bl(i.name,o)}finally{if(t.fetching?.id===e.key)t.fetching=void 0;if(t.preparing===e.key)t.preparing=void 0;if(t.cutting===e.key)t.cutting=void 0;this.draw()}}async cutOut(e,t,n,r){let i=qt(Xt(e),"cut",`${t}.png`);if(Oi(i))return i;try{return FM(AM(i),{recursive:!0}),await Gs(n,i,r),i}catch{uo(i,{force:!0});return}}swap(){let e=this.current;if(!e?.cut||this.view.shown?.id!==e.key)return;e.using=e.using==="cut"?"plain":"cut",this.reveal()}preload(){let e=this.view;if(e.mode!=="try")return;for(let t of[e.focus+this.direction,e.focus-this.direction]){let n=e.tiles[t],r=n&&this.posts.get(n.key);if(r)this.credit(r,this.signal);if(this.prefetching>=JM||!r||!Vt(r.post))continue;let{site:i,post:s}=r;this.prefetching++,Zo(i,s,this.signal).then(async()=>{let o=Vt(s),a=this.origPath(i,s.id,o.ext),u=Vr(i,s,o);return await this.cached(u.site,a,u.url),this.render({site:i,id:s.id,key:n.key,path:a,ext:o.ext,size:0,using:"plain",failed:!1},"plain")}).catch(()=>{}).finally(()=>{this.prefetching--})}}async render(e,t){let n=this.cols*this.cell.w,r=this.rows*this.cell.h,i=Math.min(n,ZM),s=Math.max(1,Math.round(r*i/n)),o={...this.view.tune},a=!Cb(o,this.view.untuned),u=a?`-${o.size}-${o.at}-${Math.round(o.opacity*100)}`:"",c=qt(this.scratch,`${e.site.key}-${e.id}${t==="cut"?"c":""}-${i}x${s}${u}.png`),l=`${e.site.key}:${e.id}:${t}:${i}x${s}`,h=this.clarity.get(l);if(h&&Oi(c))return e.fill=h.fill,{clear:h.clear,path:c};let f=await this.renders.run({job:"show",from:t==="cut"?e.cut:e.path,to:c,width:i,height:s,colors:this.entry,tone:this.tone,blur:this.blurring*i/bc(n,r).width,...a?{tune:o}:{}});if(this.clarity.set(l,f),e.fill=f.fill,a)this.keepTuned(c);return{clear:f.clear,path:c}}keepTuned(e){this.tunedFiles.push(e);while(this.tunedFiles.length>VM){let t=this.tunedFiles.findIndex((n)=>n!==this.view.shown?.path&&n!==e);if(t===-1)return;uo(this.tunedFiles.splice(t,1)[0],{force:!0})}}async present(){let e=this.current;if(!e)return;let t=e.using,{clear:n,path:r}=await this.render(e,t);if(this.current!==e||e.using!==t)return;if(this.view.tuning&&e.fill)this.view.tuning.fill=e.fill;this.view.shown={id:e.key,clear:n,bytes:e.size,path:r,cut:e.cut?t==="cut"?"on":"off":e.failed?"failed":"none"}}reveal(){let e=this.view;if(this.presenting){this.again=!0;return}this.presenting=!0,e.preparing=this.current?.key,this.flush(),this.present().catch((t)=>{e.error=t instanceof Error?t.message:String(t)}).finally(()=>{if(this.presenting=!1,this.again){this.again=!1,this.reveal();return}if(e.preparing===this.current?.key)e.preparing=void 0;this.draw()})}async install(){let e=this.view,t=e.tiles[e.focus],n=this.current;if(!t||n?.key!==t.key||e.preparing!==void 0||e.shown?.id!==t.key)return;e.installing=t.key,e.error=void 0,this.flush();let r=GM(e.tune,e.untuned),i=this.posts.get(n.key)?.post;try{await this.renders.run({job:"backdrop",from:n.using==="cut"?n.cut:n.path,source:n.path,home:this.home,colors:this.entry,tone:this.tone,origin:{site:n.site.key,id:n.id,ext:n.ext,from:`${n.site.name} ${n.id} ${n.site.pageUrl(n.id)}`,artist:i?.named.artist??[],source:us(i?.source??"")},width:this.cols*this.cell.w,height:this.rows*this.cell.h,blur:this.blurring,...r?{tune:r,aligns:!ae(this.home).terminals.includes("iterm2"),user:TM()}:{}}),this.keep(n.site,"owners.json")[n.id]=i?.owner??"",this.unsaved.add(`${n.site.key}/owners.json`),xt(this.home);let{size:s,at:o,opacity:a}=e.tune,u=r?` · ${s==="fill"?"fill":`${s}%`} · ${bt[o-1]} · ${a.toFixed(2)}`:"",c=i?.named.artist.length?`${i.named.artist.join(", ")} · `:"";e.saved={text:`Background · ${this.entry.name} ← ${c}${n.site.name} ${n.id}${u}`,key:t.key},e.installed.push(t.key),this.fetch?.abort(),clearTimeout(this.settle),e.fetching=void 0,e.mode="grid"}catch(s){e.error=s instanceof Error?s.message:String(s)}e.installing=void 0,this.draw()}draw(){if(this.dirty||this.signal.aborted)return;this.dirty=!0,setImmediate(()=>{this.dirty=!1,this.flush()})}flush(){if(this.signal.aborted)return;let e=Ol(this.view,this.cols,this.rows);this.view.loaderFrom=e.loader?this.view.loaderFrom??this.view.beat:void 0;let t="";e.lines.forEach((i,s)=>{if(this.screen[s]!==i)t+=`\x1B[${s+1};1H\x1B[K${i}`,this.screen[s]=i});let n=new Set;for(let i of e.images){let s=this.bands?this.banded(i):i;if(!s)continue;if(n.add(s.id),this.sent.get(s.id)!==s.path)t+=Jp(s),this.sent.set(s.id,s.path),this.placed.delete(s.id);let o=`${s.row};${s.col};${s.cols};${s.rows};${s.crop};${s.z}`;if(this.placed.get(s.id)!==o)t+=Bp(s,this.cell),this.placed.set(s.id,o)}for(let i of this.sent.keys())if(!n.has(i))t+=qp(i),this.sent.delete(i),this.placed.delete(i);t+=this.cover();let r=this.view.mode==="grid"&&this.view.editing!==void 0?this.caret():"";if(t||r)this.write(`\x1B[?2026h${t}${r}\x1B[?2026l`);this.pace(e.tick)}cover(){let e=`${this.cols};${this.rows}`;if(this.covered===e)return"";let t="";if(!this.covered){let n=Buffer.from(Ue(this.entry.background)).toString("base64");if(t+=`\x1B_Ga=t,f=24,s=1,v=1,i=${co},q=2;${n}\x1B\\`,Jl)t+=`\x1B_Ga=t,f=32,s=1,v=1,i=${lo},q=2;AAAAAA==\x1B\\\x1B[H\x1B_Ga=p,i=${lo},p=${lo},c=1,r=1,C=1,z=${DM},q=2\x1B\\`}if(this.covered=e,Jl){let{x:n,y:r}=Jl;return`${t}\x1B_Ga=p,i=${co},p=${co},P=${lo},Q=${lo},H=${-n},V=${-r},c=${this.cols+2*n},r=${this.rows+2*r},C=1,z=${Ob},q=2\x1B\\`}return`${t}\x1B[H\x1B_Ga=p,i=${co},p=${co},c=${this.cols},r=${this.rows},C=1,z=${Ob},q=2\x1B\\`}caret(){return`\x1B[1;${Math.min(this.cols,we(`⌕ ${this.view.editing??""}`)+1)}H`}pace(e){if(e)this.ticking??=setInterval(()=>{this.view.beat++,this.draw()},eS);else if(this.ticking)clearInterval(this.ticking),this.ticking=void 0}banded(e){if(e.crop===void 0)return e;let t=this.band(e.path,e.crop,e.rows,!this.gliding);return t?.ready?{...e,id:t.id,path:t.path,crop:void 0}:void 0}band(e,t,n,r=!0){let i=`${e}|${t}|${n}`,s=this.bandFiles.get(i);if(s||!r)return s;let o=this.nextBand++,a={id:o,path:qt(this.scratch,`band-${o}.png`),ready:!1};return this.bandFiles.set(i,a),this.renders.run({job:"band",from:e,to:a.path,y:t*this.cell.h,height:n*this.cell.h}).then(()=>{a.ready=!0,this.draw()}).catch(()=>{}),this.trimBands(),a}trimBands(){for(let[e,t]of this.bandFiles){if(this.bandFiles.size<=iS)return;if(t.ready&&!this.sent.has(t.id))this.bandFiles.delete(e),uo(t.path,{force:!0})}}}async function _b(e,t,n){let r=new ql(e,bn(e),t,t.booru??"",n);return await r.run(),{saved:r.saved,installs:r.installs}}async function Gb(e){let t=de(),n=bn(t),r=br(n.palettes,e);if(!process.stdin.isTTY||!process.stdout.isTTY)throw Error("needs a terminal");let i=new ql(t,n,r,r.booru??""),s=await i.run();if(i.saved&&s!==0)return process.stderr.write(`${i.saved}
498
+ `),0;return s}function Ub(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function jb(e,t){if(e.includes("/"))return e;let n=pr(t,!1),r=n.filter((s)=>Yn(s.dir).some((o)=>o.slug===e)),[i]=r.length===1?r:n.length===1?n:[];return i?`${i.id}/${e}`:e}function fS(e,t,n){let r=ae(e),i=n.filter((s)=>!r.palettes.includes(s));if(i.length>0)$n(e,t,r,{...r,palettes:[...r.palettes,...i]});else if(n.some((s)=>r.palettes.includes(s)))lt(e,t,r);return{state:r,fresh:i}}function dS(e){let t=Math.max(0,...e.map((n)=>n.slot.length));return e.map((n)=>` ${n.slot.padEnd(t)} ${n.from} → ${n.to} ${n.rule}`)}function Wb(e,t,n){let r=Ug(t),i=Wt(kt(r.name,Fc(r),n.palettes)),s=We(e,n,!1).palettes.find((o)=>o.name===i.name);if(s&&JSON.stringify(s)!==JSON.stringify(i))throw Error(`${i.name} is already in ${ve(i.name)??"the ttheme catalog"} and differs — \`ttheme add ${i.name}\` wears that one`);if(!s)ha(e,[...pn(e),i]);return i.name}var gS=["background","foreground","cursor"];function Kb(e){try{e();return}catch(t){return t.message}}function Jb(e,t,n){return We(e,t,!1).palettes.filter((r)=>r.name!==n).map((r)=>({name:r.name,colors:{background:r.background,foreground:r.foreground,cursor:r.cursor,selection:r.selection,ansi:r.ansi}}))}function Bb(e,t){let n=new Set(Ot(e,t).map((r)=>r.key));return{count:()=>Ot(e,t).length,added:()=>Ot(e,t).filter((r)=>!n.has(r.key)).length,fresh:()=>(Ia(e,t)??[]).filter((r)=>!n.has(ct(r))),discard:()=>{let r=Ot(e,t).filter((i)=>!n.has(i.key));for(let i of r)ii(e,t,i.key),na(e,t);if(r.length>0)xt(e)}}}function mS(...e){let t=new Map;for(let n of e.flatMap((r)=>r??[]))t.set(ct(n),n);return t.size>0?[...t.values()]:void 0}function qb(e,t,n,r){if(!sm(process.env))return;return async(i,s)=>{let o=Wt(kt(t,r(i),n.palettes)),{saved:a}=await _b(e,o,s);return{...a?{note:a}:{},count:Ot(e,t).length}}}async function zb(e){let t=Dn(process.env,process.stdout.isTTY===!0),n=t?await t.saved():new Map;try{return await gb(e,{color:!At(),...t?{only:t.slots}:{}})}finally{if(t)process.stdout.write(t.restore(n))}}async function Yb(e,t,n){let r=de(),i=_e(r),s=await fp(r,n),o=e.includes("/")?e:`${s.id}/${e}`,a=tn(o);if(a)throw Error(`${o} ${a}`);if(ve(o)!==s.id)throw Error(`palettes in ${s.dir} are named ${s.id}/<palette> — ${o} belongs elsewhere`);let u=Nc(r,o);if(fo(u))throw Error(`${o} already exists — \`ttheme edit ${o}\` changes it`);let c=t?br(We(r,i).palettes,t):void 0;if(!Ub())throw Error("new opens the palette editor — run it in a terminal");let l=c&&(ve(c.name)?c.base:c.default?void 0:c.name),h=c?Pc(c,o,`kept from ${c.name}`):void 0,f=c?Ia(r,c.name)??c.pictures:void 0,{base:d,ansiSource:g,group:p,...b}=h??{name:o,signature:gS,...Or(Ja)},m=Bb(r,o),$=({colors:w,signature:M})=>{let y=mS(f,m.fresh());return Fc({...b,...w,signature:M,...l?{base:l}:{},...y?{pictures:y}:{}})},k=await zb({title:"New palette",name:o,...h?{colors:h}:{},signature:b.signature,...b.waive?{waive:b.waive}:{},palettes:Jb(r,i,o),pictures:m.count(),find:qb(r,o,i,$),check:(w)=>Kb(()=>kt(o,$(w),i.palettes))});if(!k){m.discard(),console.log("Nothing made");return}lS(hS(u),{recursive:!0}),Z(u,$(k));let{state:S}=fS(r,i,[o]);console.log(` + ${o}${c?` from ${c.name}`:""}
499
+ ${u}`),await kn(r,We(r,i).palettes.filter((w)=>w.name===o),S.terminals),console.log(`
500
+ \`ttheme use ${o}\` wears it · \`ttheme edit ${o}\` opens it again`)}function pS(e,t,n){let r=Wt(kt(e,t,n.palettes));return ks(r).length>0?ws(r).filter((i)=>i.startsWith(" ✗")):[]}async function Qb(e){let t=de(),n=_e(t),r=ae(t),i=We(t,n,!1),s=jb(e,t),o=eu(t,s),a=o&&fo(o)?s:i.palettes.some((m)=>m.name===e)?e:s,u=eu(t,a);if(!u||!fo(u)){let m=i.palettes.some(($)=>$.name===a);throw Error(m?`${a} is not one of yours — \`ttheme new <name> --from ${a}\` makes your own copy`:`no palette of yours called ${a} — \`ttheme new\` makes one`)}if(!Ub())throw Error("edit opens the palette editor — run it in a terminal");let c=zl(u,"utf8"),l;try{l=kt(a,c,n.palettes)}catch(m){throw Error(`${u} cannot be read — ${m.message}`)}let h=Bb(t,a),f=new Set((l.pictures??[]).map((m)=>ct(m))),d=({colors:m,signature:$})=>xg(jg(Oc(c,m),$),h.fresh().filter((k)=>!f.has(ct(k)))),g=await zb({title:"Edit palette",name:a,colors:Rc(l),signature:l.signatureSlots,waive:l.waive,palettes:Jb(t,n,a),pictures:h.count(),find:qb(t,a,n,d),check:(m)=>Kb(()=>kt(a,d(m),n.palettes))});if(!g){h.discard(),console.log("Nothing changed");return}let p=d(g);if(p===c){console.log(h.added()>0?`Kept the pictures you added to ${a}`:"Nothing changed");return}if(Z(u,p),r.palettes.includes(a))lt(t,n,r);console.log(`Saved ${a}${r.palettes.includes(a)?" — new tabs and `ttheme use` wear it":` — \`ttheme add ${a}\` installs it`}`);let b=pS(a,p,n);if(b.length>0)console.log(`
501
+ It misses the contrast gate:
502
+ ${b.join(`
503
+ `)}
504
+ \`ttheme check --fix ${a}\` suggests colors that pass`)}function Zb(e,t,n){return br(e.palettes,e.palettes.some((r)=>r.name===t)?t:jb(t,n))}function Vb(e,t=!1){let n=de(),r=_e(n),i=ae(n),s=Zb(We(n,r),e,n);if(console.log(`${s.name} · ${s.group}
505
+ `),console.log(ws(s).join(`
506
+ `)),ks(s).length===0)return console.log(`
507
+ Passes the gate`),0;let{theme:a,moves:u,left:c}=Ka(Tt(s));if(u.length===0)return console.log(`
508
+ No color change fixes it — waive the rule in [contrast] with a reason, or pick other colors`),1;console.log(`
509
+ ${c.length===0?"These colors pass":"These colors come closer"}:
510
+ ${dS(u).join(`
511
+ `)}`);let l=eu(n,s.name);if(!l||!fo(l))return console.log(`
512
+ \`ttheme new <name> --from ${s.name}\` makes a copy you can fix`),1;if(!t)return console.log(`
513
+ \`ttheme check --fix ${s.name}\` writes them`),1;if(Z(l,Oc(zl(l,"utf8"),Rc(a))),i.palettes.includes(s.name))lt(n,r,i);return console.log(`
514
+ Wrote ${l}`),c.length===0?0:1}function eu(e,t){let n=ve(t);return n&&pr(e,!1).some((r)=>r.id===n)?Nc(e,t):void 0}function bS(e,t){let n=eu(e,t.name),r=n&&fo(n)?kt(t.name,zl(n,"utf8"),[t]).waiveReason:void 0,i=Ia(e,t.name)??t.pictures,{pictures:s,...o}=Pc(t,t.name,r);return{...o,...i?{pictures:i}:{}}}function Xb(e){let t=de(),n=Gg(bS(t,Zb(We(t,_e(t)),e,t)));if(console.log(n),process.stdout.isTTY)console.error(`
515
+ Anyone with ttheme wears it with: ttheme add ${mn}…`)}function tu(e){console.log(`
516
+ ${e} palettes installed — open a new tab, or reload your terminal config`)}function $S(e,t){return e.map((n)=>{if(n.startsWith(mn))return n;let r=ve(n);if(r===void 0)return t===D?n:`${t}/${n}`;if(r!==t)throw Error(`${n} is not in ${t} — give its bare name, or leave --market out`);return n})}async function Db(e,t){let n=de(),r=t?$S(e,(await rl(n,t)).id):e,i=_e(n),s=[...new Set(r.map((l)=>l.startsWith(mn)?Wb(n,l,i):l))],o=ae(n),a=s.filter((l)=>o.palettes.includes(l)),u=s.filter((l)=>!o.palettes.includes(l));if(u.length===0){lt(n,i,o),console.log(`Already installed: ${a.join(", ")}`);return}let c={...o,palettes:[...o.palettes,...u]};$n(n,i,o,c);for(let l of u)console.log(` + ${l}`);await kn(n,We(n,i,!1).palettes.filter((l)=>u.includes(l.name)),c.terminals),tu(c.palettes.length)}function ew(e){let t=de(),n=_e(t),r=ae(t),i=e.filter((a)=>r.palettes.includes(a)),s=e.filter((a)=>!r.palettes.includes(a));if(i.length===0)throw Error(`not installed: ${s.join(", ")} — \`ttheme list\` marks what is`);let o={...r,palettes:r.palettes.filter((a)=>!i.includes(a))};$n(t,n,r,o),Ea(t,n,r.terminals,i);for(let a of i)console.log(` - ${a}`);if(tu(o.palettes.length),s.length>0)return console.error(`ttheme remove: not installed: ${s.join(", ")}`),1;return 0}function tw(e){let t=de(),n=_e(t),r=ae(t);if(!r.palettes.includes(e))throw Error(`${e} is not installed — \`ttheme add ${e}\` first`);let{off:i,...s}=r,o=wn(),a=Cs({...s,startup:e},o);lt(t,n,a),Lt(t,a);let u=Er(a,o);console.log(iw(e,a.terminals,u&&o.running()).join(`
517
+ `))}function nw(){let e=de(),t=ae(e),n=vr(t);if(!n)throw Error("no palettes installed — `ttheme browse` picks some");if(!t.off){console.log(`Already on · ${n}`);return}let{off:r,...i}=t,s=$n(e,_e(e),t,i);console.log(iw(n,i.terminals,s).join(`
518
+ `))}function rw(){let e=de(),t=ae(e);if(t.off){console.log("Already off");return}let n=$n(e,_e(e),t,{...t,off:!0}),r=vr(t);if(console.log(`Off · new tabs open in the terminal's own colors${r?` — \`ttheme on\` wears ${r} again`:""}`),n)console.log("iTerm2 new tabs open on your own profile once iTerm2 restarts")}function iw(e,t,n){let r=t.filter((s)=>s!=="iterm2"),i=r.length>0?[`Default ${e} · ${r.map((s)=>fi[s]).join(", ")} open new tabs with it once their config reloads`]:[];if(t.includes("iterm2"))i.push(n?'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 ${e} · no terminal is wired to open with it — \`ttheme init\` wires one`]}function sw(e,t){let n=new Map(t.palettes.map((r)=>[r.name,"market"]));for(let r of ua(e,t.palettes,!1))n.set(r.name,"mine");return n}function ow(e,t=!1){let n=de(),r=_e(n),i=new Set(ae(n).palettes),s=sw(n,r),o=st(We(n,r).palettes),a=gr(e?zg(o,e):o),u=(h)=>s.get(h)??"kept";if(t){let h=a.map((f)=>({name:f.name,group:f.group,...f.catalog?{catalog:f.catalog}:{},installed:i.has(f.name),source:u(f.name)}));console.log(JSON.stringify(h,null,2));return}let c=Math.max(...a.map((h)=>h.name.length),0),l={market:"",mine:" · yours",kept:" · in no market you added"};for(let h of a){let f=h.catalog?`${h.group} / ${h.catalog}`:h.group;console.log(` ${i.has(h.name)?"●":"○"} ${h.name.padEnd(c)} ${f}${l[u(h.name)]}`)}if(process.stdout.isTTY){let h=e?`${a.length} of ${o.length}`:`${o.length}`;console.log(`
519
+ ${h} palettes — ${a.filter((f)=>i.has(f.name)).length} installed`)}}async function aw(){let e=de(),t=oi(e);if(t.length===0)console.log("No markets to update — `ttheme market add official` brings the ttheme catalog back");let n=(f,d)=>`${ke(f)}: ${d.message} — kept the copy from the last update`;for(let f of t.filter(Te))try{console.log(` ${mp(e,f)}`)}catch(d){console.log(` ${n(f,d)}`)}let r=t.filter((f)=>!Te(f)),i=new Set(r),s=er(),o=()=>s.set(`Updating ${[...i].map(ke).join(", ")}${r.length>1?` · ${r.length-i.size}/${r.length}`:""}`);if(o(),await Promise.all(r.map(async(f)=>{let d;try{d=Vc(await Ws(e,f))}catch(g){d=n(f,g)}if(i.delete(f),i.size>0)o();else s.done();s.say(` ${d}`)})),s.done(),!wS(Bn(e)))return;let a=_e(e),u=ae(e),c=sw(e,a),l=u.palettes.filter((f)=>!c.has(f)),h=new Map(pn(e).map((f)=>[f.name,f.pictures]));lt(e,a,u);for(let f of l)console.log(` ${f} left its market — ttheme keeps the copy you have`);await kn(e,We(e,a,!1).palettes.filter((f)=>u.palettes.includes(f.name)&&h.has(f.name)).map((f)=>Ei(f,h.get(f.name))),u.terminals)}async function Yl(e,t,n,r=!1){let i=process.env.TTHEME_SORT==="series"?e.palettes:gr(e.palettes),s=Dn(process.env,process.stdout.isTTY===!0),o=s?await s.saved():new Map,a=new ml({entries:i,scope:n,installed:t,required:r,color:!At(),fx:Oa(process.env.TTHEME_FX),onFocus:s?(c)=>process.stdout.write(s.paint(c)):void 0}),u=await a.prompt();if(s)process.stdout.write(s.restore(o));if(ft(u))return;return e.palettes.filter((c)=>a.picked.has(c.name)).map((c)=>c.name)}function Ql(e,t,n,r){let i;try{i=Si(e,n)}catch{i=wt(n)?Jn(n):ke(n)}let s=[];if(Te(n))try{s=Qn(n,i,Mi(e,D),!1)}catch{s=[]}else s=Mi(e,n);return{source:n,id:i,shown:ke(n),entries:s,auto:qn(n,t.updates),status:ol(e,n,r)}}function nu(e){return e instanceof Error?e.message:String(e)}function yS(e,t,n,r){let i=new Map(r.map((o)=>[o.source,o.id])),s=[];for(let o of et(t.markets)){let a=i.get(o)??ke(o),u=n[o],c=Us(e,o);if(u&&(c===void 0||u.at>c))s.push({where:a,source:o,update:!0,message:`Update failed ${Ks(u.at)}: ${u.error}`});if(o===D)try{sn(uw(Jt(e),"utf8"))}catch(l){s.push({where:a,source:o,message:`${ke(Jt(e))}: ${nu(l)}`})}else if(wt(o))if(!kS(Kt(e,o)))s.push({where:a,source:o,message:"No copy of its index yet — `ttheme update` fetches it"});else try{Zn(e,o)}catch(l){s.push({where:a,source:o,message:`${ke(Kt(e,o))}: ${nu(l)}`})}else try{let l=$t(rn(o)),h=new Map;for(let f of Yn(o))try{let d=bs(f,h);if(d)throw Error(d);h.set(f.slug,f),kt(`${l}/${f.slug}`,uw(f.path,"utf8"),Mi(e,D))}catch(d){s.push({where:ke(f.path),message:nu(d)})}}catch(l){s.push({where:a,message:nu(l)})}}return s}function ES(e,t,n,r){return{refresh:async(i)=>{if(Te(i)){let o=Ql(e,t,i,yn());return{market:o,refreshed:{source:i,id:o.id,count:st(o.entries).length,change:{added:[],changed:[],gone:[]}}}}let s=await Ws(e,i,Qc);return{market:Ql(e,t,i,yn()),refreshed:s}},fetch:async(i)=>{if(Te(i)){let o=$t(rn(i));return{source:i,id:o,shown:ke(i),entries:Qn(i,o,Mi(e,D),!1),auto:!1,status:"read in place"}}let s=await js(i,void 0,r);return n.set(i,s),{source:i,id:s.id,shown:ke(i),entries:s.entries,auto:qn(i,{}),status:"not added yet"}},search:(i)=>ul(i,r)}}function vS(e,t,n){let r=[];for(let i of e.adds){let s=i.source!==D&&(e.auto[i.source]??i.auto);r.push(`Added ${i.id} · ${i.shown} — ${ht(st(i.entries).length)}${s?", updating on its own":""}`)}for(let i of e.removes){let s=t.find((a)=>a.source===i)?.id??i;r.push(`Removed ${s} · ${ke(i)}`);let o=n.filter((a)=>(ve(a)??D)===s);if(o.length>0)r.push(sl(o))}for(let[i,s]of Object.entries(e.auto)){let o=t.find((a)=>a.source===i);if(o&&!e.removes.includes(i))r.push(`${o.id} ${s?"updates on its own now":"no longer updates on its own"}`)}return r}async function MS(e,t,n,r,i){let s=ae(e),o=r.adds.length+r.removes.length+Object.keys(r.auto).length>0;for(let m of r.adds){let $=i.get(m.source);if($)vi(e,$)}for(let m of r.removes)il(e,m);let a=[...et(s.markets).filter((m)=>!r.removes.includes(m)),...r.adds.map((m)=>m.source)],u=Js(s,a,{...s.updates,...r.auto});if(o)Lt(e,u);let c=_e(e,!1),l=We(e,c,!1).palettes.filter((m)=>r.picked.has(m.name)).map((m)=>m.name),h=s.palettes.filter((m)=>!l.includes(m)),f=l.filter((m)=>!s.palettes.includes(m));if(!o&&f.length===0&&h.length===0){await Na(e,s,t,r.refreshed),console.log("Nothing changed");return}let d={...u,palettes:l};$n(e,c,s,d),Ea(e,c,s.terminals,h);for(let m of vS(r,n,l))console.log(m);for(let m of f)console.log(` + ${m}`);for(let m of h)console.log(` - ${m}`);let g=new Map(t.map((m)=>[m.name,m.pictures])),p=new Set(r.refreshed.flatMap((m)=>[...m.change.changed,...m.change.gone])),b=We(e,c,!1).palettes;if(await kn(e,[...b.filter((m)=>f.includes(m.name)),...b.filter((m)=>l.includes(m.name)&&!f.includes(m.name)&&p.has(m.name)&&g.has(m.name)).map((m)=>Ei(m,g.get(m.name)))],d.terminals),f.length>0||h.length>0)tu(d.palettes.length)}async function cw(){let e=de(),t=ae(e),n=pn(e),r=yn(),i=et(t.markets).map((p)=>Ql(e,t,p,r)),s=new Set(i.flatMap((p)=>p.entries.map((b)=>b.name))),o=n.filter((p)=>t.palettes.includes(p.name)&&!s.has(p.name)),a=new Map,u=new AbortController,c=Dn(process.env,process.stdout.isTTY===!0),l=c?await c.saved():new Map,h=yt(t),f=new wl({markets:i,kept:o,installed:t.palettes,...h?{startup:h}:{},problems:yS(e,t,r,i),due:Zc(e,t),io:ES(e,t,a,u.signal),...process.env.TTHEME_SORT==="series"?{}:{order:gr},color:!At(),fx:Oa(process.env.TTHEME_FX),...c?{onFocus:(p)=>process.stdout.write(c.paint(p))}:{}}),d=await f.prompt();if(c)process.stdout.write(c.restore(l));u.abort(),await f.idle();let g=f.result();for(let p of g.refreshed){let b=Xc(p);if(b)console.log(b)}if(ft(d)){await Na(e,ae(e),n,g.refreshed),console.log("Nothing changed");return}await MS(e,n,i,g,a)}import{rmSync as lw}from"node:fs";import{basename as SS,join as go}from"node:path";var hw=go(import.meta.dirname,".."),IS=go(hw,"themes"),Zl=go(hw,"dist"),ru=[Es,Ms,ys,As,vs,Ls,Hs],NS=[jc,Ec],ZT=ru.map((e)=>e.id);async function iu({only:e}={}){if(typeof Bun>"u")throw Error("needs bun — run it from a checkout: bun src/bin.ts build");let t=e&&e.length>0?ru.filter((s)=>e.includes(s.id)):ru,n=ng(IS),r=rf(n);if(r.length>0){for(let s of r)console.error(` ✗ ${s.theme} [${s.rule}] ${s.detail}`);throw Error(`${r.length} contrast violation(s). Fix the palette, or waive the rule in its [contrast] section with a reason.`)}if(t.length===ru.length)lw(Zl,{recursive:!0,force:!0});else for(let s of t)lw(go(Zl,s.id),{recursive:!0,force:!0});let i=0;for(let s of[...t,...NS]){let o=n.flatMap((c)=>s.emit?.(c)??[]),a=s.emitShared?.(n)??[];for(let c of[...o,...a])await Bun.write(go(Zl,c.path),c.content),i++;let u=o.length>0?`${n.length} themes${s.limits?` (${s.limits})`:""}`:a.map((c)=>SS(c.path)).join(" ");console.log(` ${s.id.padEnd(16)} ${u}`)}console.log(`
520
+ ${n.length} themes (${rg(n).length} in the new-tab rotation) -> ${i} files in dist/`)}function fw(e,t,n){let r=de();if(br(bn(r).palettes,e),t==="show"){if(!n)throw Error("image show needs the picture to show");let{at:i,of:s}=ii(r,e,n);return xt(r),process.stderr.write(`Background · ${e} ${i}/${s} ${n}
521
+ `),0}if(t==="drop"){let{key:i,left:s}=na(r,e,n);return xt(r),process.stderr.write(`Background · ${e} removed ${i} · ${s} left
522
+ `),0}if(t==="tuned")return xt(r),0;throw Error(`unknown image action ${t} — show, drop or tuned`)}import{execFileSync as bw,spawnSync as OS}from"node:child_process";import{chmodSync as TS,copyFileSync as HS,existsSync as vt,mkdirSync as gw,readdirSync as AS,readFileSync as Ti,rmSync as mw}from"node:fs";import{homedir as LS}from"node:os";import{dirname as mo,join as Pe}from"node:path";import{availableParallelism as PS,homedir as FS}from"node:os";var RS=4;async function su(e,t,n=FS()){let r=ut(je(e)),i=gi(e),s=new Map(bn(e).palettes.map((h)=>[h.name,h.backdrop])),o=Object.entries(r.palettes).flatMap(([h,f])=>{let d=s.get(h);return d?f.pictures.filter((g)=>g.tone===void 0||(g.blur??0)!==i).map((g)=>({name:h,key:g.key,hue:d})):[]});if(o.length===0)return 0;t(`Drawing ${o.length} background picture${o.length===1?"":"s"} again${i?` · blur ${i}px`:""}`);let a=!ae(e).terminals.includes("iterm2"),u=new Wl(Math.min(RS,PS()-1)),c=await u.map(o.map(({name:h,key:f,hue:d})=>({job:"redraw",home:e,user:n,name:h,key:f,hue:d,blur:i,aligns:a})));u.close();let l=[];return c.forEach((h,f)=>{let{name:d,key:g}=o[f];if(h instanceof Error||h===null){t(` ▢ ${d} ${g} — ${h instanceof Error?h.message:"no original to draw it from"}, left as it was`);return}l.push({name:d,picture:h})}),Sg(e,l),xt(e,n),l.length}async function dw(){return await su(de(),(e)=>process.stderr.write(`${e}
523
+ `)),0}function xS(e,t,n){for(let r of AS(t))e.push({from:Pe(t,r),to:Pe(n,r)})}function Dl(e){return JSON.parse(Ti(Pe(e,"dist","manifest.json"),"utf8"))}function au(e,t){let n=Pe(t.configHome,"ttheme"),r=[{from:Pe(t.root,"bin","ttheme.js"),to:Pe(n,"ttheme.js")},{from:Pe(t.root,"bin","ttheme.js.map"),to:Pe(n,"ttheme.js.map")},{from:Pe(t.root,"shell","ttheme.zsh"),to:Pe(n,"ttheme.zsh")},{from:Pe(t.root,"shell","launch-tab.zsh"),to:Pe(n,"launch-tab.zsh"),executable:!0}];xS(r,Pe(t.root,"shell","adapters"),Pe(n,"adapters"));let i=[{file:Pe(t.zdotdir,".zshrc"),block:dm(n)}],s=Pe(n,"config.zsh"),o=bm(vt(s)?Ti(s,"utf8"):""),a={file:s,content:o},u=[];if(e.terminals.includes("alacritty")){let h=Mr(t.configHome);if(vt(h)&&Os(Ti(h,"utf8"),void 0)===void 0)u.push(`${h} already imports files under [general] — ttheme left it alone; add ${Pe(t.configHome,"alacritty","themes")}/<palette>.toml to that import list yourself`)}if(e.terminals.includes("wezterm")){let h=wi(t.configHome,t.home);if(vt(h)&&Ts(Ti(h,"utf8"),"")===void 0)u.push(`${h} has no \`return config\` line — ttheme left it alone; call \`dofile("${Pe(n,"wezterm.lua")}")(config)\` from it yourself`)}let c=e.terminals.includes("windows-terminal");if(c&&!t.wtHome)u.push("Windows Terminal: %LOCALAPPDATA% was not found — drop the release fragment into its Fragments folder yourself");if(e.terminals.includes("warp"))u.push("Warp wears the default palette app-wide through its settings.toml — the shell layer stays off in it, since Warp paints no tab background of its own");let l={terminals:e.terminals,palettes:e.palettes,...c&&t.wtHome?{wtHome:t.wtHome}:{},...c&&t.wtProfile?{wtProfile:t.wtProfile}:{},...e.off?{off:!0}:{}};return u.push(...Um(t.configHome,e.terminals,t.home)),{home:t.home,copies:r,edits:i,settings:a,catalog:Dl(t.root),installed:l,notes:u}}function CS(e){try{return ae(e)}catch{return}}function ww(e){try{return We(e,_e(e),!1).palettes}catch{return[]}}function _S(e,t){let n=Dl(t.root),r=et(e.markets).includes(D)?n.palettes:[],i=new Set(r.map((o)=>o.name)),s=ww(t.configHome).filter((o)=>!i.has(o.name)&&(ve(o.name)!==void 0||e.palettes.includes(o.name)));return{...n,palettes:[...r,...s]}}function $w(e,t){let n=vr(e);return n&&t.includes(n)?n:void 0}function GS(e,t,n){let r=au(t,n),i=$w(e,t.palettes),{terminals:s,palettes:o,off:a,wtHome:u,wtProfile:c,startup:l,...h}=e;return{...r,installed:{...h,...r.installed,...i?{startup:i}:{}}}}function US(e,t){let n=au({terminals:e.terminals,palettes:e.palettes,off:e.off},t),r=new Set([...n.catalog.palettes,...ww(t.configHome)].map((l)=>l.name)),i=e.palettes.filter((l)=>r.has(l)),s=e.palettes.filter((l)=>!r.has(l)),{startup:o,...a}=e,u={...a,palettes:i,...o&&i.includes(o)?{startup:o}:{}},c=s.length>0?[`Dropped ${s.join(", ")} — no longer in the catalog`,...n.notes]:n.notes;return{...n,installed:u,notes:c}}function jS(e){try{return bw(process.execPath,[Pe(e,"ttheme","ttheme.js"),"--version"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function kw(e){let t=yt(e);return[e.terminals.map((n)=>fi[n]).join(", "),`${e.palettes.length} palettes`,t?`default ${t}`:"no default — ttheme is off"].join(" · ")}function WS(e){try{return ae(e).itermBase}catch{return}}function Vl(e,t=wn()){for(let s of e.copies)if(gw(mo(s.to),{recursive:!0}),mw(s.to,{force:!0}),mw(`${s.to}.zwc`,{force:!0}),HS(s.from,s.to),s.executable)TS(s.to,493);Z(e.settings.file,e.settings.content);let n=mo(mo(e.settings.file)),r=WS(n),i=Cs(r?{...e.installed,itermBase:r}:e.installed,t);if(et(i.markets).includes(D))ca(n,e.catalog);Lt(n,i),lt(n,_e(n),i,e.home);for(let s of e.edits){gw(mo(s.file),{recursive:!0});let o=vt(s.file)?Ti(s.file,"utf8"):"";zi(s.file,Fs(o,s.block))}return Er(i,t)}class nr extends Error{}function ou(e){if(ft(e))throw _r("Nothing changed"),new nr;return e}function yw(e){return pa.filter((t)=>{if(t==="iterm2")return process.platform==="darwin";if(t==="windows-terminal")return e.wtHome!==void 0;return t!=="warp"||process.platform!=="win32"})}function KS(e,t){if(e==="iterm2")return vt(Pe(t.home,"Library","Application Support","iTerm2"));if(e==="windows-terminal")return t.wtHome!==void 0;if(e==="warp")return vt(mo($a(t.home)));if(e==="wezterm")return vt(Pe(t.configHome,"wezterm"))||vt(Pe(t.home,".wezterm.lua"));return vt(Pe(t.configHome,e))}function JS(){if(process.platform==="win32")return process.env.LOCALAPPDATA;if(!process.env.WSL_DISTRO_NAME)return;let e=(t,n)=>bw(t,n,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();try{return e("wslpath",["-u",e("cmd.exe",["/d","/c","echo %LOCALAPPDATA%"])])||void 0}catch{return}}async function BS(e,t,n){return ou(await zh({message:"Wire which terminals?",options:yw(n).map((r)=>({value:r,label:fi[r],hint:r===e?"detected":void 0})),initialValues:t,required:!0}))}function Xl(e){let t=[...e.copies.filter((n)=>!vt(n.to)).map((n)=>n.to),...vt(e.settings.file)?[]:[e.settings.file],...e.edits.filter((n)=>!Ti(n.file,"utf8").includes("# ttheme begin")).map((n)=>n.file)];if(t.length>0)throw Error(`init left gaps:
522
524
  ${t.join(`
523
- `)}`)}function xp(e,t){return[...new Set(e.palettes.filter((n)=>t.includes(n.name)).map((n)=>n.group))]}function Uv(e,t){let n=e.palettes.find((i)=>i.name===dt(t)),r=process.stdout.isTTY===!0&&!Vt()&&!process.env.TMUX&&Kr(process.env)!=="warp";if(!n||!r)return!1;return process.stdout.write(Vr(n)),!0}function _v(e,t){let n=dt(e);if(!n)return["Default none — new tabs keep the terminal colors",`Turn on \`ttheme on\` wears ${ln(e)}`];return[`Default ${n}${t?" — this tab wears it already":""}`,"Change it `ttheme preview`, enter on a palette, then default"]}function Cv(e){yv("zsh",["-c",'source "$1" && __tt_preview init',"zsh",Ne(e,"ttheme","ttheme.zsh")],{stdio:"inherit"})}function jv(e,t,n,r){let i=xp(e.catalog,t.palettes);Wn([`${i.join(", ")} (${t.palettes.length})`,..._v(e.installed,n)].join(`
524
- `),`Installed ${t.palettes.length} palettes`),Wn(["exec zsh The ttheme command in this tab",...Dp(t.terminals,e,r)].join(`
525
- `),"Next"),Ga("Done")}function Dp(e,t,n){let r=[];if(e.includes("ghostty"))r.push("Restart Ghostty New tabs pick up its config");if(e.includes("kitty"))r.push("New kitty window Pictures follow it — kitty reloads its colors by itself");if(e.includes("alacritty"))r.push("Alacritty Reloads its config by itself");if(e.includes("wezterm"))r.push("WezTerm Reloads its config by itself");if(e.includes("windows-terminal"))r.push("Windows Terminal Reloads its settings by itself");if(e.includes("iterm2"))r.push(...Wv(dt(t.installed),n));return[...r,...t.notes]}function ew(e){return e?(t)=>gn.step(t):(t)=>console.log(t)}async function Yp(e,t,n){let r=Ov(e,t),i=cn(),s=il(r,i);sl(r),await pa(t.configHome,ew(n),t.home);let o=["exec zsh Open tabs run the new layer — new tabs already do",...Dp(r.installed.terminals,r,s&&i.running())],a=`Updated to ${Ve.version} — kept ${Vp(r.installed)}`;if(!n){console.log([a,...o].join(`
526
- `));return}Wn(o.join(`
527
- `),a),Ga("Done")}function Wv(e,t){let n=['iTerm2 profiles A "ttheme · <palette>" per palette in Settings › Profiles'];if(e)n.push(t?`Restart iTerm2 New tabs open on "ttheme · default", which wears ${e}`:`iTerm2 default "ttheme · default" wears ${e} and follows \`ttheme default\``);return n}function Jv(e,t){let n=[`Placed ${e.copies.length} files`,`Settings in ${e.settings.file} — edit later with \`ttheme config\``,...e.edits.map((r)=>`Wired ${r.file}`)];if(t.terminals.includes("ghostty"))n.push("Restart Ghostty to pick up its config");if(t.terminals.includes("kitty"))n.push("kitty reloads its colors by itself; pictures show in kitty windows opened from now on");if(t.terminals.includes("alacritty"))n.push("Alacritty reloads its config by itself");if(t.terminals.includes("wezterm")||t.terminals.includes("windows-terminal"))n.push("WezTerm and Windows Terminal reload their config by themselves");if(t.terminals.includes("iterm2"))n.push('iTerm2 gets a "ttheme · <palette>" profile per palette under Settings › Profiles');n.push(...e.notes),n.push("No palettes yet — open a new shell (`exec zsh`), then `ttheme browse` picks them from the catalog"),console.log(n.join(`
528
- `))}async function tw(e={}){let t=Ne(import.meta.dirname,"..");if(!gt(Ne(t,"bin","ttheme.js")))throw Error("bin/ttheme.js is missing — run `mise run bin:build` first");if(!gt(Ne(t,"dist"))){if(typeof Bun>"u")throw Error("this package is missing dist/ — reinstall @kecan0406/ttheme");await ea()}let n=Iv(),r=he(),i=process.env.ZDOTDIR??n,s=Lv(),o=process.env.WT_PROFILE_ID,a={root:t,home:n,configHome:r,zdotdir:i,...s?{wtHome:s}:{},...o?{wtProfile:o}:{}},u=Kr(process.env),c=Xp(a).filter((N)=>N===u||Hv(N,a));if(!e.yes&&(process.stdin.isTTY!==!0||process.stdout.isTTY!==!0))throw Error("init asks before it edits your configs — run it in a terminal, or pass --yes to accept the defaults");let l=Rv(r);if(e.yes&&l){await Yp(l,a,!1);return}if(e.yes){if(c.length===0)throw Error("no supported terminal detected — run this inside ghostty, kitty, alacritty, wezterm, iterm2, windows terminal or warp");let N={terminals:c,palettes:[]},y=ba(N,a);il(y),sl(y),Jv(y,N);return}if(Cs("ttheme init"),l){let N=Tv(r);if(wa(await _t({message:`ttheme${N?` ${N}`:""} is installed — ${Vp(l)}
529
- ${N===Ve.version?"Reinstall":"Update to"} ${Ve.version} and keep all of it?`,active:"Yes",inactive:"No, set it up again",initialValue:!0}))){await Yp(l,a,!0);return}}let h=await Gv(u,l?.terminals??c,a),f=l?Fv(l,a):ol(t),d=l?await Ac(f,l.palettes,"palette",!0):await Ac(f,[],"series",!0);if(!d)throw $r("Nothing changed"),new Cn;let g=(l&&Bp(l,d))??d[0],m=d.length>1&&Kr(process.env)!=="warp",b=wa(await _t({message:m?"Pick a default palette in ttheme preview once installed?":`Wear ${g} in every tab?`,initialValue:l?!l.off:!0})),p={terminals:h,palettes:d,off:!b},E=l?Pv(l,p,a):ba(p,a);if(Wn([`Install ${d.length} palettes — ${xp(f,d).join(", ")}`,`Copy ${E.copies.length} files under ${r}`,`Write ${E.settings.file}`,...E.edits.map((N)=>`Edit ${N.file} — a ttheme block: source ttheme.zsh`),...Lg(r,E.installed,n),"Each config is backed up once to <file>.ttheme.bak before the first edit — `npx @kecan0406/ttheme uninstall` takes it all out",b?m?`Open ttheme preview — every tab wears the palette picked there, ${g} until then`:`Paint every tab with ${g}, this one now`:"Leave the terminal colors as they are — `ttheme on` wears a palette later",...h.includes("iterm2")&&b?['Make "ttheme · default" the iTerm2 default profile']:[]].join(`
530
- `),`Wiring ${h.map((N)=>Jr[N]).join(", ")}`),!wa(await _t({message:"Apply these changes?"})))throw $r("Nothing changed"),new Cn;let v=cn(),S=il(E,v);if(sl(E),await pa(r,ew(!0),n),b&&m)Cv(r);let w=se(r);jv({...E,catalog:f,installed:w},p,Uv(f,w),S&&v.running())}import{existsSync as $a,readdirSync as Kv,readFileSync as qv,rmSync as Qv,utimesSync as Yv}from"node:fs";import{homedir as Zv}from"node:os";import{dirname as zv,join as ui}from"node:path";function al(e){return $a(e)?qv(e,"utf8"):""}function Bv(e){try{return se(e)}catch{return}}function Vv(e,t){let n=Ho(t,e),r=al(n);if(!Oo(r)?.includes(`path = "${$e("")}`))return;return{file:n,content:To(r,al(tc(e))||ec)}}function Xv(e){let{home:t,configHome:n}=e,r=Bv(n),i=[],s=(c,l)=>{let h=al(c),f=l(h);if(f!==h)i.push({file:c,content:f})};s(ui(e.zdotdir,".zshrc"),es),s(or("ghostty",n),es),s(or("kitty",n),es),s(ur(n),es),s(Br(n,t),$g);let o=Vv(n,t);if(o)i.push(o);let a=[];for(let c of["ghostty","kitty","alacritty","wezterm","warp"]){let l=sr(c,n,t);if($a(l))a.push(...Kv(l).flatMap((h)=>h.startsWith($e(""))?[ui(l,h)]:[]))}let u=[as(t),...r?.wtHome?[zv(Lo(r.wtHome))]:[],ui(n,"ttheme"),e.cacheDir,e.stateDir];return a.push(...u.filter((c)=>$a(c))),{edits:i,removals:a,touches:r?.wtHome?nc(r.wtHome):[],...r?{state:r}:{}}}function xv(e,t=cn()){let n=[];for(let{file:i,content:s}of e.edits){let o=gh(i,s);n.push(o==="removed"?`Removed ${i} — ttheme had created it`:o==="restored"?`Took ttheme out of ${i}`:`Took ttheme out of ${i} — kept ${i}.ttheme.bak, since the file changed after ttheme's first edit`)}if(e.state&&ar({...e.state,off:!0},t))n.push("Gave iTerm2 its own default profile back — it takes it at its next start");for(let i of e.removals)Qv(i,{recursive:!0,force:!0});if(e.removals.length>0)n.push(`Deleted ${e.removals.length} files and folders ttheme wrote`);let r=new Date;for(let i of e.touches)Yv(i,r,r);return n}function Dv(){let e=Zv();return{home:e,configHome:he(),zdotdir:process.env.ZDOTDIR??e,cacheDir:Tr(),stateDir:ui(process.env.XDG_STATE_HOME??ui(e,".local","state"),"ttheme")}}async function nw(e=!1){let t=Dv(),n=Xv(t);if(n.edits.length===0&&n.removals.length===0){console.log("Nothing of ttheme is installed");return}if(!e){if(process.stdin.isTTY!==!0||process.stdout.isTTY!==!0)throw Error("uninstall asks before it deletes anything — run it in a terminal, or pass --yes");let r=ui(t.configHome,"ttheme");Cs("ttheme uninstall"),Wn([...n.edits.map((s)=>`Take ttheme out of ${s.file}`),...n.removals.map((s)=>s===r?`Delete ${s} — settings, pins, every installed picture${$a(Eo(t.configHome))?`, and your markets under ${Eo(t.configHome)} (push them to GitHub first to keep them)`:""}`:`Delete ${s}`)].join(`
531
- `),"Uninstall");let i=await _t({message:"Remove ttheme?"});if(xe(i)||!i)throw $r("Nothing changed"),new Cn}for(let r of xv(n))console.log(r);console.log("Open tabs keep their colors until they close — restart your terminal to drop ttheme everywhere")}var tM=new Set(["add","remove","market","default","on","off"]),nM={default:([e])=>Rm(e),on:()=>Fm(),off:()=>Pm(),browse:()=>Gm(),list:([e],{json:t})=>Am(e,t),add:(e,{market:t})=>Im(e,t),remove:(e)=>Nm(e),update:()=>Hm(),market:([e,t])=>um(e,t),new:([e],{from:t,in:n})=>ym(e,t,n),edit:([e])=>Em(e),check:([e],{fix:t})=>Mm(e,t),share:([e])=>Sm(e),init:(e,{yes:t})=>tw({yes:t}),uninstall:(e,{yes:t})=>nw(t),build:(e,{only:t})=>ea({only:t}),find:([e])=>Jp(e),image:([e,t])=>Kp(e,t),redraw:()=>qp()},rM=Vi.map((e)=>({...e,run:nM[e.name]}));class mr extends Error{verb;constructor(e,t){super(e);this.verb=t}}function rw(e){let t=rM.find((n)=>n.name===e);if(!t)throw new mr(e.startsWith("-")?`unknown option '${e}'`:`unknown command '${e}'`);return t}function iM(e,t){let n={help:{type:"boolean",short:"h"}};for(let[r,{type:i,short:s,multiple:o}]of Object.entries(e.flags??{}))n[r]={type:i,multiple:o===!0,...s?{short:s}:{}};try{return eM({args:t,options:n,allowPositionals:!0})}catch(r){let[i=""]=(r instanceof Error?r.message:String(r)).split(". ");throw new mr(`${i.charAt(0).toLowerCase()}${i.slice(1)}`,e)}}function sM(e){let[t,...n]=e;if(t===void 0)return{kind:"help",code:1};if(t==="-h"||t==="--help")return{kind:"help",code:0};if(t==="-V"||t==="--version")return{kind:"version"};if(t==="help"){if(n[0]===void 0||n[0]==="all")return{kind:"help",all:n[0]==="all",code:0};return{kind:"help",verb:rw(n[0]),code:0}}let r=rw(t),i=iM(r,n);if(i.values.help)return{kind:"help",verb:r,code:0};for(let[l,{choices:h}]of Object.entries(r.flags??{}))for(let f of[i.values[l]??[]].flat())if(h&&!h.includes(String(f)))throw new mr(`--${l} takes ${h.join(", ")} — not ${f}`,r);let s=i.positionals,o=r.args.filter((l)=>l.startsWith("<")).length,a=r.args.some((l)=>l.includes("..."))?Number.POSITIVE_INFINITY:r.args.length;if(s.length<o)throw new mr(`missing ${r.args[s.length]}`,r);if(s.length>a)throw new mr(`too many arguments: ${s.slice(a).join(" ")}`,r);let{help:u,...c}=i.values;return{kind:"run",verb:r,args:s,flags:c}}function iw(e){let t=Math.max(0,...e.map(([n])=>n.length));return e.map(([n,r])=>` ${n.padEnd(t)} ${r}`)}function ul(e,t=!1){if(!e)return Xi(t);let n=Object.entries(e.flags??{}).map(([r,{short:i,value:s,about:o}])=>[`${i?`-${i}, `:""}--${r}${s?` ${s}`:""}`,o]);return[`Usage: ttheme ${Bi(e)}`,"",e.about,...e.actions?["","Actions:",...iw(e.actions)]:[],...n.length>0?["","Options:",...iw(n)]:[]].join(`
532
- `)}async function sw(e){let t;try{let n=sM(e);if(n.kind==="version")return console.log(Ve.version),0;if(n.kind==="help"){if(n.code===0)console.log(ul(n.verb,n.all));else console.error(ul(n.verb,n.all));return n.code}if(t=n.verb,!n.verb.run)throw Error("runs in the shell layer — open a new tab once `ttheme init` has wired it");if(tM.has(n.verb.name))await Yg();let r=await n.verb.run(n.args,n.flags);return typeof r==="number"?r:0}catch(n){if(n instanceof mr)return console.error(n.verb?`ttheme ${n.verb.name}: ${n.message}
525
+ `)}`)}function Ew(e,t){return[...new Set(e.palettes.filter((n)=>t.includes(n.name)).map((n)=>n.group))]}function qS(e,t){let n=e.palettes.find((r)=>r.name===yt(t));if(!n||!Dn(process.env,process.stdout.isTTY===!0))return!1;return process.stdout.write(ma(n)),!0}function zS(e,t){let n=yt(e);if(!n)return["Default none — new tabs keep the terminal colors",`Turn on \`ttheme on\` wears ${vr(e)}`];return[`Default ${n}${t?" — this tab wears it already":""}`,"Change it `ttheme preview`, enter on a palette, then default"]}function YS(e){OS("zsh",["-c",'source "$1" && __tt_preview init',"zsh",Pe(e,"ttheme","ttheme.zsh")],{stdio:"inherit"})}function QS(e,t,n,r){let i=Ew(e.catalog,t.palettes);ir([`${i.join(", ")} (${t.palettes.length})`,...zS(e.installed,n)].join(`
526
+ `),`Installed ${t.palettes.length} palettes`),ir(["exec zsh The ttheme command in this tab",...vw(t.terminals,e,r)].join(`
527
+ `),"Next"),Su("Done")}function vw(e,t,n){let r=[];if(e.includes("ghostty"))r.push("Restart Ghostty New tabs pick up its config");if(e.includes("kitty"))r.push("New kitty window Pictures follow it — kitty reloads its colors by itself");if(e.includes("alacritty"))r.push("Alacritty Reloads its config by itself");if(e.includes("wezterm"))r.push("WezTerm Reloads its config by itself");if(e.includes("windows-terminal"))r.push("Windows Terminal Reloads its settings by itself");if(e.includes("iterm2"))r.push(...ZS(yt(t.installed),n));return[...r,...t.notes]}function Mw(e){return e?(t)=>Sn.step(t):(t)=>console.log(t)}async function pw(e,t,n){let r=US(e,t),i=wn(),s=Vl(r,i);Xl(r),await su(t.configHome,Mw(n),t.home);let o=["exec zsh Open tabs run the new layer — new tabs already do",...vw(r.installed.terminals,r,s&&i.running())],a=`Updated to ${nt.version} — kept ${kw(r.installed)}`;if(!n){console.log([a,...o].join(`
528
+ `));return}ir(o.join(`
529
+ `),a),Su("Done")}function ZS(e,t){let n=['iTerm2 profiles A "ttheme · <palette>" per palette in Settings › Profiles'];if(e)n.push(t?`Restart iTerm2 New tabs open on "ttheme · default", which wears ${e}`:`iTerm2 default "ttheme · default" wears ${e} and follows \`ttheme default\``);return n}function VS(e,t){let n=[`Placed ${e.copies.length} files`,`Settings in ${e.settings.file} — edit later with \`ttheme config\``,...e.edits.map((r)=>`Wired ${r.file}`)];if(t.terminals.includes("ghostty"))n.push("Restart Ghostty to pick up its config");if(t.terminals.includes("kitty"))n.push("kitty reloads its colors by itself; pictures show in kitty windows opened from now on");if(t.terminals.includes("alacritty"))n.push("Alacritty reloads its config by itself");if(t.terminals.includes("wezterm")||t.terminals.includes("windows-terminal"))n.push("WezTerm and Windows Terminal reload their config by themselves");if(t.terminals.includes("iterm2"))n.push('iTerm2 gets a "ttheme · <palette>" profile per palette under Settings › Profiles');n.push(...e.notes),n.push("No palettes yet — open a new shell (`exec zsh`), then `ttheme browse` picks them from the catalog"),console.log(n.join(`
530
+ `))}async function Sw(e={}){let t=Pe(import.meta.dirname,"..");if(!vt(Pe(t,"bin","ttheme.js")))throw Error("bin/ttheme.js is missing — run `mise run bin:build` first");if(!vt(Pe(t,"dist"))){if(typeof Bun>"u")throw Error("this package is missing dist/ — reinstall @kecan0406/ttheme");await iu()}let n=LS(),r=de(),i=process.env.ZDOTDIR??n,s=JS(),o=process.env.WT_PROFILE_ID,a={root:t,home:n,configHome:r,zdotdir:i,...s?{wtHome:s}:{},...o?{wtProfile:o}:{}},u=wr(process.env),c=yw(a).filter((M)=>M===u||KS(M,a));if(!e.yes&&(process.stdin.isTTY!==!0||process.stdout.isTTY!==!0))throw Error("init asks before it edits your configs — run it in a terminal, or pass --yes to accept the defaults");let l=CS(r);if(e.yes&&l){await pw(l,a,!1);return}if(e.yes){if(c.length===0)throw Error("no supported terminal detected — run this inside ghostty, kitty, alacritty, wezterm, iterm2, windows terminal or warp");let M={terminals:c,palettes:[]},y=au(M,a);Vl(y),Xl(y),VS(y,M);return}if(No("ttheme init"),l){let M=jS(r);if(ou(await Nn({message:`ttheme${M?` ${M}`:""} is installed — ${kw(l)}
531
+ ${M===nt.version?"Reinstall":"Update to"} ${nt.version} and keep all of it?`,active:"Yes",inactive:"No, set it up again",initialValue:!0}))){await pw(l,a,!0);return}}let h=await BS(u,l?.terminals??c,a),f=l?_S(l,a):Dl(t),d=l?await Yl(f,l.palettes,"palette",!0):await Yl(f,[],"series",!0);if(!d)throw _r("Nothing changed"),new nr;let g=(l&&$w(l,d))??d[0],p=d.length>1&&Xn[wr(process.env)].paints,b=ou(await Nn({message:p?"Pick a default palette in ttheme preview once installed?":`Wear ${g} in every tab?`,initialValue:l?!l.off:!0})),m={terminals:h,palettes:d,off:!b},$=l?GS(l,m,a):au(m,a);if(ir([`Install ${d.length} palettes — ${Ew(f,d).join(", ")}`,`Copy ${$.copies.length} files under ${r}`,`Write ${$.settings.file}`,...$.edits.map((M)=>`Edit ${M.file} — a ttheme block: source ttheme.zsh`),...Gm(r,$.installed,n),"Each config is backed up once to <file>.ttheme.bak before the first edit — `npx @kecan0406/ttheme uninstall` takes it all out",b?p?`Open ttheme preview — every tab wears the palette picked there, ${g} until then`:`Paint every tab with ${g}, this one now`:"Leave the terminal colors as they are — `ttheme on` wears a palette later",...h.includes("iterm2")&&b?['Make "ttheme · default" the iTerm2 default profile']:[]].join(`
532
+ `),`Wiring ${h.map((M)=>fi[M]).join(", ")}`),!ou(await Nn({message:"Apply these changes?"})))throw _r("Nothing changed"),new nr;let k=wn(),S=Vl($,k);if(Xl($),await su(r,Mw(!0),n),b&&p)YS(r);let w=ae(r);QS({...$,catalog:f,installed:w},m,qS(f,w),S&&k.running())}import{existsSync as uu,readdirSync as XS,readFileSync as DS,rmSync as eI,utimesSync as tI}from"node:fs";import{homedir as nI}from"node:os";import{dirname as rI,join as Hi}from"node:path";function eh(e){return uu(e)?DS(e,"utf8"):""}function iI(e){try{return ae(e)}catch{return}}function sI(e,t){let n=ka(t,e),r=eh(n);if(!ba(r)?.includes(`path = "${ye("")}`))return;return{file:n,content:wa(r,eh(Bc(e))||Jc)}}function oI(e){let{home:t,configHome:n}=e,r=iI(n),i=[],s=(c,l)=>{let h=eh(c),f=l(h);if(f!==h)i.push({file:c,content:f})};s(Hi(e.zdotdir,".zshrc"),Rs),s(yr("ghostty",n),Rs),s(yr("kitty",n),Rs),s(Mr(n),Rs),s(wi(n,t),Em);let o=sI(n,t);if(o)i.push(o);let a=[];for(let c of["ghostty","kitty","alacritty","wezterm","warp"]){let l=kr(c,n,t);if(uu(l))a.push(...XS(l).flatMap((h)=>h.startsWith(ye(""))?[Hi(l,h)]:[]))}let u=[_s(t),...r?.wtHome?[rI(ya(r.wtHome))]:[],Hi(n,"ttheme"),e.cacheDir,e.stateDir];return a.push(...u.filter((c)=>uu(c))),{edits:i,removals:a,touches:r?.wtHome?qc(r.wtHome):[],...r?{state:r}:{}}}function aI(e,t=wn()){let n=[];for(let{file:i,content:s}of e.edits){let o=af(i,s);n.push(o==="removed"?`Removed ${i} — ttheme had created it`:o==="restored"?`Took ttheme out of ${i}`:`Took ttheme out of ${i} — kept ${i}.ttheme.bak, since the file changed after ttheme's first edit`)}if(e.state&&Er({...e.state,off:!0},t))n.push("Gave iTerm2 its own default profile back — it takes it at its next start");for(let i of e.removals)eI(i,{recursive:!0,force:!0});if(e.removals.length>0)n.push(`Deleted ${e.removals.length} files and folders ttheme wrote`);let r=new Date;for(let i of e.touches)tI(i,r,r);return n}function uI(){let e=nI();return{home:e,configHome:de(),zdotdir:process.env.ZDOTDIR??e,cacheDir:Xr(),stateDir:Hi(process.env.XDG_STATE_HOME??Hi(e,".local","state"),"ttheme")}}async function Iw(e=!1){let t=uI(),n=oI(t);if(n.edits.length===0&&n.removals.length===0){console.log("Nothing of ttheme is installed");return}if(!e){if(process.stdin.isTTY!==!0||process.stdout.isTTY!==!0)throw Error("uninstall asks before it deletes anything — run it in a terminal, or pass --yes");let r=Hi(t.configHome,"ttheme");No("ttheme uninstall"),ir([...n.edits.map((s)=>`Take ttheme out of ${s.file}`),...n.removals.map((s)=>s===r?`Delete ${s} — settings, pins, every installed picture${uu(oa(t.configHome))?`, and your markets under ${oa(t.configHome)} (push them to GitHub first to keep them)`:""}`:`Delete ${s}`)].join(`
533
+ `),"Uninstall");let i=await Nn({message:"Remove ttheme?"});if(ft(i)||!i)throw _r("Nothing changed"),new nr}for(let r of aI(n))console.log(r);console.log("Open tabs keep their colors until they close — restart your terminal to drop ttheme everywhere")}var lI=new Set(["add","remove","market","default","on","off"]),hI={default:([e])=>tw(e),on:()=>nw(),off:()=>rw(),browse:()=>cw(),list:([e],{json:t})=>ow(e,t),add:(e,{market:t})=>Db(e,t),remove:(e)=>ew(e),update:()=>aw(),market:([e,t])=>gp(e,t),new:([e],{from:t,in:n})=>Yb(e,t,n),edit:([e])=>Qb(e),check:([e],{fix:t})=>Vb(e,t),share:([e])=>Xb(e),init:(e,{yes:t})=>Sw({yes:t}),uninstall:(e,{yes:t})=>Iw(t),build:(e,{only:t})=>iu({only:t}),find:([e])=>Gb(e),image:([e,t,n])=>fw(e,t,n),redraw:()=>dw()},fI=Is.map((e)=>({...e,run:hI[e.name]}));class Ar extends Error{verb;constructor(e,t){super(e);this.verb=t}}function Nw(e){let t=fI.find((n)=>n.name===e);if(!t)throw new Ar(e.startsWith("-")?`unknown option '${e}'`:`unknown command '${e}'`);return t}function dI(e,t){let n={help:{type:"boolean",short:"h"}};for(let[r,{type:i,short:s,multiple:o}]of Object.entries(e.flags??{}))n[r]={type:i,multiple:o===!0,...s?{short:s}:{}};try{return cI({args:t,options:n,allowPositionals:!0})}catch(r){let[i=""]=(r instanceof Error?r.message:String(r)).split(". ");throw new Ar(`${i.charAt(0).toLowerCase()}${i.slice(1)}`,e)}}function gI(e){let[t,...n]=e;if(t===void 0)return{kind:"help",code:1};if(t==="-h"||t==="--help")return{kind:"help",code:0};if(t==="-V"||t==="--version")return{kind:"version"};if(t==="help"){if(n[0]===void 0||n[0]==="all")return{kind:"help",all:n[0]==="all",code:0};return{kind:"help",verb:Nw(n[0]),code:0}}let r=Nw(t),i=dI(r,n);if(i.values.help)return{kind:"help",verb:r,code:0};for(let[l,{choices:h}]of Object.entries(r.flags??{}))for(let f of[i.values[l]??[]].flat())if(h&&!h.includes(String(f)))throw new Ar(`--${l} takes ${h.join(", ")} — not ${f}`,r);let s=i.positionals,o=r.args.filter((l)=>l.startsWith("<")).length,a=r.args.some((l)=>l.includes("..."))?Number.POSITIVE_INFINITY:r.args.length;if(s.length<o)throw new Ar(`missing ${r.args[s.length]}`,r);if(s.length>a)throw new Ar(`too many arguments: ${s.slice(a).join(" ")}`,r);let{help:u,...c}=i.values;return{kind:"run",verb:r,args:s,flags:c}}function Pw(e){let t=Math.max(0,...e.map(([n])=>n.length));return e.map(([n,r])=>` ${n.padEnd(t)} ${r}`)}function th(e,t=!1){if(!e)return Ns(t);let n=Object.entries(e.flags??{}).map(([r,{short:i,value:s,about:o}])=>[`${i?`-${i}, `:""}--${r}${s?` ${s}`:""}`,o]);return[`Usage: ttheme ${Ss(e)}`,"",e.about,...e.actions?["","Actions:",...Pw(e.actions)]:[],...n.length>0?["","Options:",...Pw(n)]:[]].join(`
534
+ `)}async function Fw(e){let t;try{let n=gI(e);if(n.kind==="version")return console.log(nt.version),0;if(n.kind==="help"){if(n.code===0)console.log(th(n.verb,n.all));else console.error(th(n.verb,n.all));return n.code}if(t=n.verb,!n.verb.run)throw Error("runs in the shell layer — open a new tab once `ttheme init` has wired it");if(lI.has(n.verb.name))await Xm();let r=await n.verb.run(n.args,n.flags);return typeof r==="number"?r:0}catch(n){if(n instanceof Ar)return console.error(n.verb?`ttheme ${n.verb.name}: ${n.message}
533
535
 
534
- ${ul(n.verb)}`:`ttheme: ${n.message} — see \`ttheme help\``),1;if(n instanceof Cn)return 1;let r=process.env.TTHEME_DEBUG&&n instanceof Error?n.stack:void 0;return console.error(`
535
- ttheme${t?` ${t.name}`:""}: ${r??(n instanceof Error?n.message:String(n))}`),1}}if(aM)if(process.env.TTHEME_DEBUG&&typeof Bun>"u"&&!process.sourceMapsEnabled){let e=oM(process.execPath,["--enable-source-maps",...process.argv.slice(1)],{stdio:"inherit"});process.exitCode=e.status??1}else process.exitCode=await sw(process.argv.slice(2));
536
+ ${th(n.verb)}`:`ttheme: ${n.message} — see \`ttheme help\``),1;if(n instanceof nr)return 1;let r=process.env.TTHEME_DEBUG&&n instanceof Error?n.stack:void 0;return console.error(`
537
+ ttheme${t?` ${t.name}`:""}: ${r??(n instanceof Error?n.message:String(n))}`),1}}if(pI)if(process.env.TTHEME_DEBUG&&typeof Bun>"u"&&!process.sourceMapsEnabled){let e=mI(process.execPath,["--enable-source-maps",...process.argv.slice(1)],{stdio:"inherit"});process.exitCode=e.status??1}else process.exitCode=await Fw(process.argv.slice(2));
536
538
 
537
- //# debugId=D69222FFAC173BBA64756E2164756E21
539
+ //# debugId=A7681C5944E2F91D64756E2164756E21
538
540
  //# sourceMappingURL=ttheme.js.map