@kecan0406/ttheme 1.0.48 → 1.0.49

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,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{createRequire as zg}from"node:module";var _g=Object.create;var{getPrototypeOf:qg,defineProperty:Fc,getOwnPropertyNames:Qg}=Object;var Yg=Object.prototype.hasOwnProperty;function Zg(e){return this[e]}var Xg,Vg,Ci=(e,n,t)=>{var r=e!=null&&typeof e==="object";if(r){var i=n?Xg??=new WeakMap:Vg??=new WeakMap,o=i.get(e);if(o)return o}t=e!=null?_g(qg(e)):{};let s=n||!e||!e.__esModule?Fc(t,"default",{value:e,enumerable:!0}):t;for(let u of Qg(e))if(!Yg.call(s,u))Fc(s,u,{get:Zg.bind(e,u),enumerable:!0});if(r)i.set(e,s);return s};var Me=(e,n)=>()=>(n||e((n={exports:{}}).exports,n),n.exports);var Ke=zg(import.meta.url);var Yc=Me((kE,xi)=>{var Qc=Qc||function(e){return Buffer.from(e).toString("base64")};function um(e){var n=this,t=Math.round,r=Math.floor,i=Array(64),o=Array(64),s=Array(64),u=Array(64),c,a,h,f,l=Array(65535),d=Array(65535),g=Array(64),p=Array(64),k=[],y=0,M=7,b=Array(64),S=Array(64),m=Array(64),P=Array(256),E=Array(2048),R,N=[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],X=[0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,125],j=[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],Le=[0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0],C=[0,1,2,3,4,5,6,7,8,9,10,11],D=[0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,119],Oe=[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 Ee(w){var T=[16,11,10,16,24,40,51,61,12,12,14,19,26,58,60,55,14,13,16,24,40,57,69,56,14,17,22,29,51,87,80,62,18,22,37,56,68,109,103,77,24,35,55,64,81,104,113,92,49,64,78,87,103,121,120,101,72,92,95,98,112,100,103,99];for(var W=0;W<64;W++){var U=r((T[W]*w+50)/100);if(U<1)U=1;else if(U>255)U=255;i[N[W]]=U}var Q=[17,18,24,47,99,99,99,99,18,21,26,66,99,99,99,99,24,26,56,99,99,99,99,99,47,66,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99];for(var Y=0;Y<64;Y++){var se=r((Q[Y]*w+50)/100);if(se<1)se=1;else if(se>255)se=255;o[N[Y]]=se}var ue=[1,1.387039845,1.306562965,1.175875602,1,0.785694958,0.5411961,0.275899379],Fe=0;for(var ve=0;ve<8;ve++)for(var I=0;I<8;I++)s[Fe]=1/(i[N[Fe]]*ue[ve]*ue[I]*8),u[Fe]=1/(o[N[Fe]]*ue[ve]*ue[I]*8),Fe++}function ee(w,T){var W=0,U=0,Q=[];for(var Y=1;Y<=16;Y++){for(var se=1;se<=w[Y];se++)Q[T[U]]=[],Q[T[U]][0]=W,Q[T[U]][1]=Y,U++,W++;W*=2}return Q}function Ae(){c=ee(H,A),a=ee(Le,C),h=ee(X,j),f=ee(D,Oe)}function ce(){var w=1,T=2;for(var W=1;W<=15;W++){for(var U=w;U<T;U++)d[32767+U]=W,l[32767+U]=[],l[32767+U][1]=W,l[32767+U][0]=U;for(var Q=-(T-1);Q<=-w;Q++)d[32767+Q]=W,l[32767+Q]=[],l[32767+Q][1]=W,l[32767+Q][0]=T-1+Q;w<<=1,T<<=1}}function te(){for(var w=0;w<256;w++)E[w]=19595*w,E[w+256>>0]=38470*w,E[w+512>>0]=7471*w+32768,E[w+768>>0]=-11059*w,E[w+1024>>0]=-21709*w,E[w+1280>>0]=32768*w+8421375,E[w+1536>>0]=-27439*w,E[w+1792>>0]=-5329*w}function V(w){var T=w[0],W=w[1]-1;while(W>=0){if(T&1<<W)y|=1<<M;if(W--,M--,M<0){if(y==255)$(255),$(0);else $(y);M=7,y=0}}}function $(w){k.push(w)}function G(w){$(w>>8&255),$(w&255)}function me(w,T){var W,U,Q,Y,se,ue,Fe,ve,I=0,L,q=8,Re=64;for(L=0;L<q;++L){W=w[I],U=w[I+1],Q=w[I+2],Y=w[I+3],se=w[I+4],ue=w[I+5],Fe=w[I+6],ve=w[I+7];var Z=W+ve,ne=W-ve,we=U+Fe,K=U-Fe,he=Q+ue,Ce=Q-ue,Ne=Y+se,sn=Y-se,yn=Z+Ne,lt=Z-Ne,Jt=we+he,Ct=we-he;w[I]=yn+Jt,w[I+4]=yn-Jt;var kr=(Ct+lt)*0.707106781;w[I+2]=lt+kr,w[I+6]=lt-kr,yn=sn+Ce,Jt=Ce+K,Ct=K+ne;var Er=(yn-Ct)*0.382683433,Gi=0.5411961*yn+Er,yr=1.306562965*Ct+Er,Sr=Jt*0.707106781,vr=ne+Sr,Mr=ne-Sr;w[I+5]=Mr+Gi,w[I+3]=Mr-Gi,w[I+1]=vr+yr,w[I+7]=vr-yr,I+=8}I=0;for(L=0;L<q;++L){W=w[I],U=w[I+8],Q=w[I+16],Y=w[I+24],se=w[I+32],ue=w[I+40],Fe=w[I+48],ve=w[I+56];var wc=W+ve,ls=W-ve,$c=U+Fe,bc=U-Fe,kc=Q+ue,Ec=Q-ue,yc=Y+se,Kg=Y-se,Ir=wc+yc,ds=wc-yc,Ui=$c+kc,ji=$c-kc;w[I]=Ir+Ui,w[I+32]=Ir-Ui;var Sc=(ji+ds)*0.707106781;w[I+16]=ds+Sc,w[I+48]=ds-Sc,Ir=Kg+Ec,Ui=Ec+bc,ji=bc+ls;var vc=(Ir-ji)*0.382683433,Mc=0.5411961*Ir+vc,Ic=1.306562965*ji+vc,Nc=Ui*0.707106781,Oc=ls+Nc,Rc=ls-Nc;w[I+40]=Rc+Mc,w[I+24]=Rc-Mc,w[I+8]=Oc+Ic,w[I+56]=Oc-Ic,I++}var Ji;for(L=0;L<Re;++L)Ji=w[L]*T[L],g[L]=Ji>0?Ji+0.5|0:Ji-0.5|0;return g}function pe(){G(65504),G(16),$(74),$(70),$(73),$(70),$(0),$(1),$(1),$(0),G(1),G(1),$(0),$(0)}function re(w){if(!w)return;if(G(65505),w[0]===69&&w[1]===120&&w[2]===105&&w[3]===102)G(w.length+2);else G(w.length+5+2),$(69),$(120),$(105),$(102),$(0);for(var T=0;T<w.length;T++)$(w[T])}function ie(w,T){G(65472),G(17),$(8),G(T),G(w),$(3),$(1),$(17),$(0),$(2),$(17),$(1),$(3),$(17),$(1)}function z(){G(65499),G(132),$(0);for(var w=0;w<64;w++)$(i[w]);$(1);for(var T=0;T<64;T++)$(o[T])}function F(){G(65476),G(418),$(0);for(var w=0;w<16;w++)$(H[w+1]);for(var T=0;T<=11;T++)$(A[T]);$(16);for(var W=0;W<16;W++)$(X[W+1]);for(var U=0;U<=161;U++)$(j[U]);$(1);for(var Q=0;Q<16;Q++)$(Le[Q+1]);for(var Y=0;Y<=11;Y++)$(C[Y]);$(17);for(var se=0;se<16;se++)$(D[se+1]);for(var ue=0;ue<=161;ue++)$(Oe[ue])}function O(w){if(typeof w>"u"||w.constructor!==Array)return;w.forEach((T)=>{if(typeof T!=="string")return;G(65534);var W=T.length;G(W+2);var U;for(U=0;U<W;U++)$(T.charCodeAt(U))})}function Se(){G(65498),G(12),$(3),$(1),$(0),$(2),$(17),$(3),$(17),$(0),$(63),$(0)}function _(w,T,W,U,Q){var Y=Q[0],se=Q[240],ue,Fe=16,ve=63,I=64,L=me(w,T);for(var q=0;q<I;++q)p[N[q]]=L[q];var Re=p[0]-W;if(W=p[0],Re==0)V(U[0]);else ue=32767+Re,V(U[d[ue]]),V(l[ue]);var Z=63;for(;Z>0&&p[Z]==0;Z--);if(Z==0)return V(Y),W;var ne=1,we;while(ne<=Z){var K=ne;for(;p[ne]==0&&ne<=Z;++ne);var he=ne-K;if(he>=Fe){we=he>>4;for(var Ce=1;Ce<=we;++Ce)V(se);he=he&15}ue=32767+p[ne],V(Q[(he<<4)+d[ue]]),V(l[ue]),ne++}if(Z!=ve)V(Y);return W}function B(){var w=String.fromCharCode;for(var T=0;T<256;T++)P[T]=w(T)}this.encode=function(w,T){var W=new Date().getTime();if(T)on(T);k=[],y=0,M=7,G(65496),pe(),O(w.comments),re(w.exifBuffer),z(),ie(w.width,w.height),F(),Se();var U=0,Q=0,Y=0;y=0,M=7,this.encode.displayName="_encode_";var{data:se,width:ue,height:Fe}=w,ve=ue*4,I=ue*3,L,q=0,Re,Z,ne,we,K,he,Ce,Ne;while(q<Fe){L=0;while(L<ve){we=ve*q+L,K=we,he=-1,Ce=0;for(Ne=0;Ne<64;Ne++){if(Ce=Ne>>3,he=(Ne&7)*4,K=we+Ce*ve+he,q+Ce>=Fe)K-=ve*(q+1+Ce-Fe);if(L+he>=ve)K-=L+he-ve+4;Re=se[K++],Z=se[K++],ne=se[K++],b[Ne]=(E[Re]+E[Z+256>>0]+E[ne+512>>0]>>16)-128,S[Ne]=(E[Re+768>>0]+E[Z+1024>>0]+E[ne+1280>>0]>>16)-128,m[Ne]=(E[Re+1280>>0]+E[Z+1536>>0]+E[ne+1792>>0]>>16)-128}U=_(b,s,U,c,h),Q=_(S,u,Q,a,f),Y=_(m,u,Y,a,f),L+=32}q+=8}if(M>=0){var sn=[];sn[1]=M+1,sn[0]=(1<<M+1)-1,V(sn)}if(G(65497),typeof xi>"u")return new Uint8Array(k);return Buffer.from(k);var yn,lt};function on(w){if(w<=0)w=1;if(w>100)w=100;if(R==w)return;var T=0;if(w<50)T=Math.floor(5000/w);else T=Math.floor(200-w*2);Ee(T),R=w}function ln(){var w=new Date().getTime();if(!e)e=50;B(),Ae(),ce(),te(),on(e);var T=new Date().getTime()-w}ln()}if(typeof xi<"u")xi.exports=qc;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].encode=qc;function qc(e,n){if(typeof n>"u")n=50;var t=new um(n),r=t.encode(e,n);return{data:r,width:e.width,height:e.height}}});var Xc=Me((EE,Ss)=>{var ys=function(){var n=new Int32Array([0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5,12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28,35,42,49,56,57,50,43,36,29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54,47,55,62,63]),t=4017,r=799,i=3406,o=2276,s=1567,u=3784,c=5793,a=2896;function h(){}function f(M,b){var S=0,m=[],P,E,R=16;while(R>0&&!M[R-1])R--;m.push({children:[],index:0});var N=m[0],H;for(P=0;P<R;P++){for(E=0;E<M[P];E++){N=m.pop(),N.children[N.index]=b[S];while(N.index>0){if(m.length===0)throw Error("Could not recreate Huffman Table");N=m.pop()}N.index++,m.push(N);while(m.length<=P)m.push(H={children:[],index:0}),N.children[N.index]=H.children,N=H;S++}if(P+1<R)m.push(H={children:[],index:0}),N.children[N.index]=H.children,N=H}return m[0].children}function l(M,b,S,m,P,E,R,N,H,A){var{precision:X,samplesPerLine:j,scanLines:Le,mcusPerLine:C,progressive:D,maxH:Oe,maxV:Ee}=S,ee=b,Ae=0,ce=0;function te(){if(ce>0)return ce--,Ae>>ce&1;if(Ae=M[b++],Ae==255){var I=M[b++];if(I)throw Error("unexpected marker: "+(Ae<<8|I).toString(16))}return ce=7,Ae>>>7}function V(I){var L=I,q;while((q=te())!==null){if(L=L[q],typeof L==="number")return L;if(typeof L!=="object")throw Error("invalid huffman sequence")}return null}function $(I){var L=0;while(I>0){var q=te();if(q===null)return;L=L<<1|q,I--}return L}function G(I){var L=$(I);if(L>=1<<I-1)return L;return L+(-1<<I)+1}function me(I,L){var q=V(I.huffmanTableDC),Re=q===0?0:G(q);L[0]=I.pred+=Re;var Z=1;while(Z<64){var ne=V(I.huffmanTableAC),we=ne&15,K=ne>>4;if(we===0){if(K<15)break;Z+=16;continue}Z+=K;var he=n[Z];L[he]=G(we),Z++}}function pe(I,L){var q=V(I.huffmanTableDC),Re=q===0?0:G(q)<<H;L[0]=I.pred+=Re}function re(I,L){L[0]|=te()<<H}var ie=0;function z(I,L){if(ie>0){ie--;return}var q=E,Re=R;while(q<=Re){var Z=V(I.huffmanTableAC),ne=Z&15,we=Z>>4;if(ne===0){if(we<15){ie=$(we)+(1<<we)-1;break}q+=16;continue}q+=we;var K=n[q];L[K]=G(ne)*(1<<H),q++}}var F=0,O;function Se(I,L){var q=E,Re=R,Z=0;while(q<=Re){var ne=n[q],we=L[ne]<0?-1:1;switch(F){case 0:var K=V(I.huffmanTableAC),he=K&15,Z=K>>4;if(he===0)if(Z<15)ie=$(Z)+(1<<Z),F=4;else Z=16,F=1;else{if(he!==1)throw Error("invalid ACn encoding");O=G(he),F=Z?2:3}continue;case 1:case 2:if(L[ne])L[ne]+=(te()<<H)*we;else if(Z--,Z===0)F=F==2?3:0;break;case 3:if(L[ne])L[ne]+=(te()<<H)*we;else L[ne]=O<<H,F=0;break;case 4:if(L[ne])L[ne]+=(te()<<H)*we;break}q++}if(F===4){if(ie--,ie===0)F=0}}function _(I,L,q,Re,Z){var ne=q/C|0,we=q%C,K=ne*I.v+Re,he=we*I.h+Z;if(I.blocks[K]===void 0&&A.tolerantDecoding)return;L(I,I.blocks[K][he])}function B(I,L,q){var Re=q/I.blocksPerLine|0,Z=q%I.blocksPerLine;if(I.blocks[Re]===void 0&&A.tolerantDecoding)return;L(I,I.blocks[Re][Z])}var on=m.length,ln,w,T,W,U,Q;if(D)if(E===0)Q=N===0?pe:re;else Q=N===0?z:Se;else Q=me;var Y=0,se,ue;if(on==1)ue=m[0].blocksPerLine*m[0].blocksPerColumn;else ue=C*S.mcusPerColumn;if(!P)P=ue;var Fe,ve;while(Y<ue){for(w=0;w<on;w++)m[w].pred=0;if(ie=0,on==1){ln=m[0];for(U=0;U<P;U++)B(ln,Q,Y),Y++}else for(U=0;U<P;U++){for(w=0;w<on;w++){ln=m[w],Fe=ln.h,ve=ln.v;for(T=0;T<ve;T++)for(W=0;W<Fe;W++)_(ln,Q,Y,T,W)}if(Y++,Y===ue)break}if(Y===ue)do{if(M[b]===255){if(M[b+1]!==0)break}b+=1}while(b<M.length-2);if(ce=0,se=M[b]<<8|M[b+1],se<65280)throw Error("marker was not found");if(se>=65488&&se<=65495)b+=2;else break}return b-ee}function d(M,b){var S=[],m=b.blocksPerLine,P=b.blocksPerColumn,E=m<<3,R=new Int32Array(64),N=new Uint8Array(64);function H(ee,Ae,ce){var te=b.quantizationTable,V,$,G,me,pe,re,ie,z,F,O=ce,Se;for(Se=0;Se<64;Se++)O[Se]=ee[Se]*te[Se];for(Se=0;Se<8;++Se){var _=8*Se;if(O[1+_]==0&&O[2+_]==0&&O[3+_]==0&&O[4+_]==0&&O[5+_]==0&&O[6+_]==0&&O[7+_]==0){F=c*O[0+_]+512>>10,O[0+_]=F,O[1+_]=F,O[2+_]=F,O[3+_]=F,O[4+_]=F,O[5+_]=F,O[6+_]=F,O[7+_]=F;continue}V=c*O[0+_]+128>>8,$=c*O[4+_]+128>>8,G=O[2+_],me=O[6+_],pe=a*(O[1+_]-O[7+_])+128>>8,z=a*(O[1+_]+O[7+_])+128>>8,re=O[3+_]<<4,ie=O[5+_]<<4,F=V-$+1>>1,V=V+$+1>>1,$=F,F=G*u+me*s+128>>8,G=G*s-me*u+128>>8,me=F,F=pe-ie+1>>1,pe=pe+ie+1>>1,ie=F,F=z+re+1>>1,re=z-re+1>>1,z=F,F=V-me+1>>1,V=V+me+1>>1,me=F,F=$-G+1>>1,$=$+G+1>>1,G=F,F=pe*o+z*i+2048>>12,pe=pe*i-z*o+2048>>12,z=F,F=re*r+ie*t+2048>>12,re=re*t-ie*r+2048>>12,ie=F,O[0+_]=V+z,O[7+_]=V-z,O[1+_]=$+ie,O[6+_]=$-ie,O[2+_]=G+re,O[5+_]=G-re,O[3+_]=me+pe,O[4+_]=me-pe}for(Se=0;Se<8;++Se){var B=Se;if(O[8+B]==0&&O[16+B]==0&&O[24+B]==0&&O[32+B]==0&&O[40+B]==0&&O[48+B]==0&&O[56+B]==0){F=c*ce[Se+0]+8192>>14,O[0+B]=F,O[8+B]=F,O[16+B]=F,O[24+B]=F,O[32+B]=F,O[40+B]=F,O[48+B]=F,O[56+B]=F;continue}V=c*O[0+B]+2048>>12,$=c*O[32+B]+2048>>12,G=O[16+B],me=O[48+B],pe=a*(O[8+B]-O[56+B])+2048>>12,z=a*(O[8+B]+O[56+B])+2048>>12,re=O[24+B],ie=O[40+B],F=V-$+1>>1,V=V+$+1>>1,$=F,F=G*u+me*s+2048>>12,G=G*s-me*u+2048>>12,me=F,F=pe-ie+1>>1,pe=pe+ie+1>>1,ie=F,F=z+re+1>>1,re=z-re+1>>1,z=F,F=V-me+1>>1,V=V+me+1>>1,me=F,F=$-G+1>>1,$=$+G+1>>1,G=F,F=pe*o+z*i+2048>>12,pe=pe*i-z*o+2048>>12,z=F,F=re*r+ie*t+2048>>12,re=re*t-ie*r+2048>>12,ie=F,O[0+B]=V+z,O[56+B]=V-z,O[8+B]=$+ie,O[48+B]=$-ie,O[16+B]=G+re,O[40+B]=G-re,O[24+B]=me+pe,O[32+B]=me-pe}for(Se=0;Se<64;++Se){var on=128+(O[Se]+8>>4);Ae[Se]=on<0?0:on>255?255:on}}y(E*P*8);var A,X;for(var j=0;j<P;j++){var Le=j<<3;for(A=0;A<8;A++)S.push(new Uint8Array(E));for(var C=0;C<m;C++){H(b.blocks[j][C],N,R);var D=0,Oe=C<<3;for(X=0;X<8;X++){var Ee=S[Le+X];for(A=0;A<8;A++)Ee[Oe+A]=N[D++]}}}return S}function g(M){return M<0?0:M>255?255:M}h.prototype={load:function(b){var S=new XMLHttpRequest;S.open("GET",b,!0),S.responseType="arraybuffer",S.onload=function(){var m=new Uint8Array(S.response||S.mozResponseArrayBuffer);if(this.parse(m),this.onload)this.onload()}.bind(this),S.send(null)},parse:function(b){var S=this.opts.maxResolutionInMP*1000*1000,m=0,P=b.length;function E(){var K=b[m]<<8|b[m+1];return m+=2,K}function R(){var K=E(),he=b.subarray(m,m+K-2);return m+=he.length,he}function N(K){var he=1,Ce=1,Ne,sn;for(sn in K.components)if(K.components.hasOwnProperty(sn)){if(Ne=K.components[sn],he<Ne.h)he=Ne.h;if(Ce<Ne.v)Ce=Ne.v}var yn=Math.ceil(K.samplesPerLine/8/he),lt=Math.ceil(K.scanLines/8/Ce);for(sn in K.components)if(K.components.hasOwnProperty(sn)){Ne=K.components[sn];var Jt=Math.ceil(Math.ceil(K.samplesPerLine/8)*Ne.h/he),Ct=Math.ceil(Math.ceil(K.scanLines/8)*Ne.v/Ce),kr=yn*Ne.h,Er=lt*Ne.v,Gi=Er*kr,yr=[];y(Gi*256);for(var Sr=0;Sr<Er;Sr++){var vr=[];for(var Mr=0;Mr<kr;Mr++)vr.push(new Int32Array(64));yr.push(vr)}Ne.blocksPerLine=Jt,Ne.blocksPerColumn=Ct,Ne.blocks=yr}K.maxH=he,K.maxV=Ce,K.mcusPerLine=yn,K.mcusPerColumn=lt}var H=null,A=null,X=null,j,Le,C=[],D=[],Oe=[],Ee=[],ee=E(),Ae=-1;if(this.comments=[],ee!=65496)throw Error("SOI not found");ee=E();while(ee!=65497){var ce,te,V;switch(ee){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 $=R();if(ee===65534){var G=String.fromCharCode.apply(null,$);this.comments.push(G)}if(ee===65504){if($[0]===74&&$[1]===70&&$[2]===73&&$[3]===70&&$[4]===0)H={version:{major:$[5],minor:$[6]},densityUnits:$[7],xDensity:$[8]<<8|$[9],yDensity:$[10]<<8|$[11],thumbWidth:$[12],thumbHeight:$[13],thumbData:$.subarray(14,14+3*$[12]*$[13])}}if(ee===65505){if($[0]===69&&$[1]===120&&$[2]===105&&$[3]===102&&$[4]===0)this.exifBuffer=$.subarray(5,$.length)}if(ee===65518){if($[0]===65&&$[1]===100&&$[2]===111&&$[3]===98&&$[4]===101&&$[5]===0)A={version:$[6],flags0:$[7]<<8|$[8],flags1:$[9]<<8|$[10],transformCode:$[11]}}break;case 65499:var me=E(),pe=me+m-2;while(m<pe){var re=b[m++];y(256);var ie=new Int32Array(64);if(re>>4===0)for(te=0;te<64;te++){var z=n[te];ie[z]=b[m++]}else if(re>>4===1)for(te=0;te<64;te++){var z=n[te];ie[z]=E()}else throw Error("DQT: invalid table spec");C[re&15]=ie}break;case 65472:case 65473:case 65474:E(),j={},j.extended=ee===65473,j.progressive=ee===65474,j.precision=b[m++],j.scanLines=E(),j.samplesPerLine=E(),j.components={},j.componentsOrder=[];var F=j.scanLines*j.samplesPerLine;if(F>S){var O=Math.ceil((F-S)/1e6);throw Error(`maxResolutionInMP limit exceeded by ${O}MP`)}var Se=b[m++],_,B=0,on=0;for(ce=0;ce<Se;ce++){_=b[m];var ln=b[m+1]>>4,w=b[m+1]&15,T=b[m+2];if(ln<=0||w<=0)throw Error("Invalid sampling factor, expected values above 0");j.componentsOrder.push(_),j.components[_]={h:ln,v:w,quantizationIdx:T},m+=3}N(j),D.push(j);break;case 65476:var W=E();for(ce=2;ce<W;){var U=b[m++],Q=new Uint8Array(16),Y=0;for(te=0;te<16;te++,m++)Y+=Q[te]=b[m];y(16+Y);var se=new Uint8Array(Y);for(te=0;te<Y;te++,m++)se[te]=b[m];ce+=17+Y,(U>>4===0?Ee:Oe)[U&15]=f(Q,se)}break;case 65501:E(),Le=E();break;case 65500:E(),E();break;case 65498:var ue=E(),Fe=b[m++],ve=[],I;for(ce=0;ce<Fe;ce++){I=j.components[b[m++]];var L=b[m++];I.huffmanTableDC=Ee[L>>4],I.huffmanTableAC=Oe[L&15],ve.push(I)}var q=b[m++],Re=b[m++],Z=b[m++],ne=l(b,m,j,ve,Le,q,Re,Z>>4,Z&15,this.opts);m+=ne;break;case 65535:if(b[m]!==255)m--;break;default:if(b[m-3]==255&&b[m-2]>=192&&b[m-2]<=254){m-=3;break}else if(ee===224||ee==225){if(Ae!==-1)throw Error(`first unknown JPEG marker at offset ${Ae.toString(16)}, second unknown JPEG marker ${ee.toString(16)} at offset ${(m-1).toString(16)}`);Ae=m-1;let K=E();if(b[m+K-2]===255){m+=K-2;break}}throw Error("unknown JPEG marker "+ee.toString(16))}ee=E()}if(D.length!=1)throw Error("only single frame JPEGs supported");for(var ce=0;ce<D.length;ce++){var we=D[ce].components;for(var te in we)we[te].quantizationTable=C[we[te].quantizationIdx],delete we[te].quantizationIdx}this.width=j.samplesPerLine,this.height=j.scanLines,this.jfif=H,this.adobe=A,this.components=[];for(var ce=0;ce<j.componentsOrder.length;ce++){var I=j.components[j.componentsOrder[ce]];this.components.push({lines:d(j,I),scaleX:I.h/j.maxH,scaleY:I.v/j.maxV})}},getData:function(b,S){var m=this.width/b,P=this.height/S,E,R,N,H,A,X,j,Le,C,D,Oe=0,Ee,ee,Ae,ce,te,V,$,G,me,pe,re,ie=b*S*this.components.length;y(ie);var z=new Uint8Array(ie);switch(this.components.length){case 1:E=this.components[0];for(D=0;D<S;D++){A=E.lines[0|D*E.scaleY*P];for(C=0;C<b;C++)Ee=A[0|C*E.scaleX*m],z[Oe++]=Ee}break;case 2:E=this.components[0],R=this.components[1];for(D=0;D<S;D++){A=E.lines[0|D*E.scaleY*P],X=R.lines[0|D*R.scaleY*P];for(C=0;C<b;C++)Ee=A[0|C*E.scaleX*m],z[Oe++]=Ee,Ee=X[0|C*R.scaleX*m],z[Oe++]=Ee}break;case 3:if(re=!0,this.adobe&&this.adobe.transformCode)re=!0;else if(typeof this.opts.colorTransform<"u")re=!!this.opts.colorTransform;E=this.components[0],R=this.components[1],N=this.components[2];for(D=0;D<S;D++){A=E.lines[0|D*E.scaleY*P],X=R.lines[0|D*R.scaleY*P],j=N.lines[0|D*N.scaleY*P];for(C=0;C<b;C++){if(!re)G=A[0|C*E.scaleX*m],me=X[0|C*R.scaleX*m],pe=j[0|C*N.scaleX*m];else Ee=A[0|C*E.scaleX*m],ee=X[0|C*R.scaleX*m],Ae=j[0|C*N.scaleX*m],G=g(Ee+1.402*(Ae-128)),me=g(Ee-0.3441363*(ee-128)-0.71413636*(Ae-128)),pe=g(Ee+1.772*(ee-128));z[Oe++]=G,z[Oe++]=me,z[Oe++]=pe}}break;case 4:if(!this.adobe)throw Error("Unsupported color mode (4 components)");if(re=!1,this.adobe&&this.adobe.transformCode)re=!0;else if(typeof this.opts.colorTransform<"u")re=!!this.opts.colorTransform;E=this.components[0],R=this.components[1],N=this.components[2],H=this.components[3];for(D=0;D<S;D++){A=E.lines[0|D*E.scaleY*P],X=R.lines[0|D*R.scaleY*P],j=N.lines[0|D*N.scaleY*P],Le=H.lines[0|D*H.scaleY*P];for(C=0;C<b;C++){if(!re)te=A[0|C*E.scaleX*m],V=X[0|C*R.scaleX*m],$=j[0|C*N.scaleX*m],ce=Le[0|C*H.scaleX*m];else Ee=A[0|C*E.scaleX*m],ee=X[0|C*R.scaleX*m],Ae=j[0|C*N.scaleX*m],ce=Le[0|C*H.scaleX*m],te=255-g(Ee+1.402*(Ae-128)),V=255-g(Ee-0.3441363*(ee-128)-0.71413636*(Ae-128)),$=255-g(Ee+1.772*(ee-128));z[Oe++]=255-te,z[Oe++]=255-V,z[Oe++]=255-$,z[Oe++]=255-ce}}break;default:throw Error("Unsupported color mode")}return z},copyToImageData:function(b,S){var{width:m,height:P,data:E}=b,R=this.getData(m,P),N=0,H=0,A,X,j,Le,C,D,Oe,Ee,ee;switch(this.components.length){case 1:for(X=0;X<P;X++)for(A=0;A<m;A++)if(j=R[N++],E[H++]=j,E[H++]=j,E[H++]=j,S)E[H++]=255;break;case 3:for(X=0;X<P;X++)for(A=0;A<m;A++)if(Oe=R[N++],Ee=R[N++],ee=R[N++],E[H++]=Oe,E[H++]=Ee,E[H++]=ee,S)E[H++]=255;break;case 4:for(X=0;X<P;X++)for(A=0;A<m;A++)if(C=R[N++],D=R[N++],j=R[N++],Le=R[N++],Oe=255-g(C*(1-Le/255)+Le),Ee=255-g(D*(1-Le/255)+Le),ee=255-g(j*(1-Le/255)+Le),E[H++]=Oe,E[H++]=Ee,E[H++]=ee,S)E[H++]=255;break;default:throw Error("Unsupported color mode")}}};var p=0,k=0;function y(M=0){var b=p+M;if(b>k){var S=Math.ceil((b-k)/1024/1024);throw Error(`maxMemoryUsageInMB limit exceeded by at least ${S}MB`)}p=b}return h.resetMaxMemoryUsage=function(M){p=0,k=M},h.getBytesAllocated=function(){return p},h.requestMemoryAllocation=y,h}();if(typeof Ss<"u")Ss.exports=Zc;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].decode=Zc;function Zc(e,n={}){var t={colorTransform:void 0,useTArray:!1,formatAsRGBA:!0,tolerantDecoding:!0,maxResolutionInMP:100,maxMemoryUsageInMB:512},r={...t,...n},i=new Uint8Array(e),o=new ys;o.opts=r,ys.resetMaxMemoryUsage(r.maxMemoryUsageInMB*1024*1024),o.parse(i);var s=r.formatAsRGBA?4:3,u=o.width*o.height*s;try{ys.requestMemoryAllocation(u);var c={width:o.width,height:o.height,exifBuffer:o.exifBuffer,data:r.useTArray?new Uint8Array(u):Buffer.alloc(u)};if(o.comments.length>0)c.comments=o.comments}catch(a){if(a instanceof RangeError)throw Error("Could not allocate enough memory for the image. Required: "+u);if(a instanceof ReferenceError){if(a.message==="Buffer is not defined")throw Error("Buffer is not globally defined in this environment. Consider setting useTArray to true")}throw a}return o.copyToImageData(c,r.formatAsRGBA),c}});var zc=Me((yE,Vc)=>{var cm=Yc(),am=Xc();Vc.exports={encode:cm,decode:am}});var vs=Me((SE,Dc)=>{var hm=Ke("util"),Bc=Ke("stream"),mn=Dc.exports=function(){Bc.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};hm.inherits(mn,Bc);mn.prototype.read=function(e,n){this._reads.push({length:Math.abs(e),allowLess:e<0,func:n}),process.nextTick(function(){if(this._process(),this._paused&&this._reads&&this._reads.length>0)this._paused=!1,this.emit("drain")}.bind(this))};mn.prototype.write=function(e,n){if(!this.writable)return this.emit("error",Error("Stream not writable")),!1;let t;if(Buffer.isBuffer(e))t=e;else t=Buffer.from(e,n||this._encoding);if(this._buffers.push(t),this._buffered+=t.length,this._process(),this._reads&&this._reads.length===0)this._paused=!0;return this.writable&&!this._paused};mn.prototype.end=function(e,n){if(e)this.write(e,n);if(this.writable=!1,!this._buffers)return;if(this._buffers.length===0)this._end();else this._buffers.push(null),this._process()};mn.prototype.destroySoon=mn.prototype.end;mn.prototype._end=function(){if(this._reads.length>0)this.emit("error",Error("Unexpected end of input"));this.destroy()};mn.prototype.destroy=function(){if(!this._buffers)return;this.writable=!1,this._reads=null,this._buffers=null,this.emit("close")};mn.prototype._processReadAllowingLess=function(e){this._reads.shift();let n=this._buffers[0];if(n.length>e.length)this._buffered-=e.length,this._buffers[0]=n.slice(e.length),e.func.call(this,n.slice(0,e.length));else this._buffered-=n.length,this._buffers.shift(),e.func.call(this,n)};mn.prototype._processRead=function(e){this._reads.shift();let n=0,t=0,r=Buffer.alloc(e.length);while(n<e.length){let i=this._buffers[t++],o=Math.min(i.length,e.length-n);if(i.copy(r,n,0,o),n+=o,o!==i.length)this._buffers[--t]=i.slice(o)}if(t>0)this._buffers.splice(0,t);this._buffered-=e.length,e.func.call(this,r)};mn.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 Ms=Me((fm)=>{var zn=[{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]}];fm.getImagePasses=function(e,n){let t=[],r=e%8,i=n%8,o=(e-r)/8,s=(n-i)/8;for(let u=0;u<zn.length;u++){let c=zn[u],a=o*c.x.length,h=s*c.y.length;for(let f=0;f<c.x.length;f++)if(c.x[f]<r)a++;else break;for(let f=0;f<c.y.length;f++)if(c.y[f]<i)h++;else break;if(a>0&&h>0)t.push({width:a,height:h,index:u})}return t};fm.getInterlaceIterator=function(e){return function(n,t,r){let i=n%zn[r].x.length,o=(n-i)/zn[r].x.length*8+zn[r].x[i],s=t%zn[r].y.length,u=(t-s)/zn[r].y.length*8+zn[r].y[s];return o*4+u*e*4}}});var Is=Me((ME,xc)=>{xc.exports=function(n,t,r){let i=n+t-r,o=Math.abs(i-n),s=Math.abs(i-t),u=Math.abs(i-r);if(o<=s&&o<=u)return n;if(s<=u)return t;return r}});var Ns=Me((IE,na)=>{var gm=Ms(),mm=Is();function ea(e,n,t){let r=e*n;if(t!==8)r=Math.ceil(r/(8/t));return r}var Qt=na.exports=function(e,n){let{width:t,height:r,interlace:i,bpp:o,depth:s}=e;if(this.read=n.read,this.write=n.write,this.complete=n.complete,this._imageIndex=0,this._images=[],i){let u=gm.getImagePasses(t,r);for(let c=0;c<u.length;c++)this._images.push({byteWidth:ea(u[c].width,o,s),height:u[c].height,lineIndex:0})}else this._images.push({byteWidth:ea(t,o,s),height:r,lineIndex:0});if(s===8)this._xComparison=o;else if(s===16)this._xComparison=o*2;else this._xComparison=1};Qt.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Qt.prototype._unFilterType1=function(e,n,t){let r=this._xComparison,i=r-1;for(let o=0;o<t;o++){let s=e[1+o],u=o>i?n[o-r]:0;n[o]=s+u}};Qt.prototype._unFilterType2=function(e,n,t){let r=this._lastLine;for(let i=0;i<t;i++){let o=e[1+i],s=r?r[i]:0;n[i]=o+s}};Qt.prototype._unFilterType3=function(e,n,t){let r=this._xComparison,i=r-1,o=this._lastLine;for(let s=0;s<t;s++){let u=e[1+s],c=o?o[s]:0,a=s>i?n[s-r]:0,h=Math.floor((a+c)/2);n[s]=u+h}};Qt.prototype._unFilterType4=function(e,n,t){let r=this._xComparison,i=r-1,o=this._lastLine;for(let s=0;s<t;s++){let u=e[1+s],c=o?o[s]:0,a=s>i?n[s-r]:0,h=s>i&&o?o[s-r]:0,f=mm(a,c,h);n[s]=u+f}};Qt.prototype._reverseFilterLine=function(e){let n=e[0],t,r=this._images[this._imageIndex],i=r.byteWidth;if(n===0)t=e.slice(1,i+1);else switch(t=Buffer.alloc(i),n){case 1:this._unFilterType1(e,t,i);break;case 2:this._unFilterType2(e,t,i);break;case 3:this._unFilterType3(e,t,i);break;case 4:this._unFilterType4(e,t,i);break;default:throw Error("Unrecognised filter type - "+n)}if(this.write(t),r.lineIndex++,r.lineIndex>=r.height)this._lastLine=null,this._imageIndex++,r=this._images[this._imageIndex];else this._lastLine=t;if(r)this.read(r.byteWidth+1,this._reverseFilterLine.bind(this));else this._lastLine=null,this.complete()}});var ia=Me((NE,ra)=>{var pm=Ke("util"),ta=vs(),wm=Ns(),$m=ra.exports=function(e){ta.call(this);let n=[],t=this;this._filter=new wm(e,{read:this.read.bind(this),write:function(r){n.push(r)},complete:function(){t.emit("complete",Buffer.concat(n))}}),this._filter.start()};pm.inherits($m,ta)});var Yt=Me((OE,oa)=>{oa.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 Fs=Me((RE,sa)=>{var Os=[];(function(){for(let e=0;e<256;e++){let n=e;for(let t=0;t<8;t++)if(n&1)n=3988292384^n>>>1;else n=n>>>1;Os[e]=n}})();var Rs=sa.exports=function(){this._crc=-1};Rs.prototype.write=function(e){for(let n=0;n<e.length;n++)this._crc=Os[(this._crc^e[n])&255]^this._crc>>>8;return!0};Rs.prototype.crc32=function(){return this._crc^-1};Rs.crc32=function(e){let n=-1;for(let t=0;t<e.length;t++)n=Os[(n^e[t])&255]^n>>>8;return n^-1}});var Ps=Me((FE,ua)=>{var je=Yt(),bm=Fs(),Je=ua.exports=function(e,n){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[je.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[je.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[je.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[je.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[je.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[je.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=n.read,this.error=n.error,this.metadata=n.metadata,this.gamma=n.gamma,this.transColor=n.transColor,this.palette=n.palette,this.parsed=n.parsed,this.inflateData=n.inflateData,this.finished=n.finished,this.simpleTransparency=n.simpleTransparency,this.headersFinished=n.headersFinished||function(){}};Je.prototype.start=function(){this.read(je.PNG_SIGNATURE.length,this._parseSignature.bind(this))};Je.prototype._parseSignature=function(e){let n=je.PNG_SIGNATURE;for(let t=0;t<n.length;t++)if(e[t]!==n[t]){this.error(Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};Je.prototype._parseChunkBegin=function(e){let n=e.readUInt32BE(0),t=e.readUInt32BE(4),r="";for(let o=4;o<8;o++)r+=String.fromCharCode(e[o]);let i=Boolean(e[4]&32);if(!this._hasIHDR&&t!==je.TYPE_IHDR){this.error(Error("Expected IHDR on beggining"));return}if(this._crc=new bm,this._crc.write(Buffer.from(r)),this._chunks[t])return this._chunks[t](n);if(!i){this.error(Error("Unsupported critical chunk type "+r));return}this.read(n+4,this._skipChunk.bind(this))};Je.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};Je.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};Je.prototype._parseChunkEnd=function(e){let n=e.readInt32BE(0),t=this._crc.crc32();if(this._options.checkCRC&&t!==n){this.error(Error("Crc error - "+n+" - "+t));return}if(!this._hasIEND)this.read(8,this._parseChunkBegin.bind(this))};Je.prototype._handleIHDR=function(e){this.read(e,this._parseIHDR.bind(this))};Je.prototype._parseIHDR=function(e){this._crc.write(e);let n=e.readUInt32BE(0),t=e.readUInt32BE(4),r=e[8],i=e[9],o=e[10],s=e[11],u=e[12];if(r!==8&&r!==4&&r!==2&&r!==1&&r!==16){this.error(Error("Unsupported bit depth "+r));return}if(!(i in je.COLORTYPE_TO_BPP_MAP)){this.error(Error("Unsupported color type"));return}if(o!==0){this.error(Error("Unsupported compression method"));return}if(s!==0){this.error(Error("Unsupported filter method"));return}if(u!==0&&u!==1){this.error(Error("Unsupported interlace method"));return}this._colorType=i;let c=je.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:n,height:t,depth:r,interlace:Boolean(u),palette:Boolean(i&je.COLORTYPE_PALETTE),color:Boolean(i&je.COLORTYPE_COLOR),alpha:Boolean(i&je.COLORTYPE_ALPHA),bpp:c,colorType:i}),this._handleChunkEnd()};Je.prototype._handlePLTE=function(e){this.read(e,this._parsePLTE.bind(this))};Je.prototype._parsePLTE=function(e){this._crc.write(e);let n=Math.floor(e.length/3);for(let t=0;t<n;t++)this._palette.push([e[t*3],e[t*3+1],e[t*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};Je.prototype._handleTRNS=function(e){this.simpleTransparency(),this.read(e,this._parseTRNS.bind(this))};Je.prototype._parseTRNS=function(e){if(this._crc.write(e),this._colorType===je.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 n=0;n<e.length;n++)this._palette[n][3]=e[n];this.palette(this._palette)}if(this._colorType===je.COLORTYPE_GRAYSCALE)this.transColor([e.readUInt16BE(0)]);if(this._colorType===je.COLORTYPE_COLOR)this.transColor([e.readUInt16BE(0),e.readUInt16BE(2),e.readUInt16BE(4)]);this._handleChunkEnd()};Je.prototype._handleGAMA=function(e){this.read(e,this._parseGAMA.bind(this))};Je.prototype._parseGAMA=function(e){this._crc.write(e),this.gamma(e.readUInt32BE(0)/je.GAMMA_DIVISION),this._handleChunkEnd()};Je.prototype._handleIDAT=function(e){if(!this._emittedHeadersFinished)this._emittedHeadersFinished=!0,this.headersFinished();this.read(-e,this._parseIDAT.bind(this,e))};Je.prototype._parseIDAT=function(e,n){if(this._crc.write(n),this._colorType===je.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw Error("Expected palette not found");this.inflateData(n);let t=e-n.length;if(t>0)this._handleIDAT(t);else this._handleChunkEnd()};Je.prototype._handleIEND=function(e){this.read(e,this._parseIEND.bind(this))};Je.prototype._parseIEND=function(e){if(this._crc.write(e),this._hasIEND=!0,this._handleChunkEnd(),this.finished)this.finished()}});var Hs=Me((Mm)=>{var ca=Ms(),km=[function(){},function(e,n,t,r){if(r===n.length)throw Error("Ran out of data");let i=n[r];e[t]=i,e[t+1]=i,e[t+2]=i,e[t+3]=255},function(e,n,t,r){if(r+1>=n.length)throw Error("Ran out of data");let i=n[r];e[t]=i,e[t+1]=i,e[t+2]=i,e[t+3]=n[r+1]},function(e,n,t,r){if(r+2>=n.length)throw Error("Ran out of data");e[t]=n[r],e[t+1]=n[r+1],e[t+2]=n[r+2],e[t+3]=255},function(e,n,t,r){if(r+3>=n.length)throw Error("Ran out of data");e[t]=n[r],e[t+1]=n[r+1],e[t+2]=n[r+2],e[t+3]=n[r+3]}],Em=[function(){},function(e,n,t,r){let i=n[0];e[t]=i,e[t+1]=i,e[t+2]=i,e[t+3]=r},function(e,n,t){let r=n[0];e[t]=r,e[t+1]=r,e[t+2]=r,e[t+3]=n[1]},function(e,n,t,r){e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=r},function(e,n,t){e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3]}];function ym(e,n){let t=[],r=0;function i(){if(r===e.length)throw Error("Ran out of data");let o=e[r];r++;let s,u,c,a,h,f,l,d;switch(n){default:throw Error("unrecognised depth");case 16:l=e[r],r++,t.push((o<<8)+l);break;case 4:l=o&15,d=o>>4,t.push(d,l);break;case 2:h=o&3,f=o>>2&3,l=o>>4&3,d=o>>6&3,t.push(d,l,f,h);break;case 1:s=o&1,u=o>>1&1,c=o>>2&1,a=o>>3&1,h=o>>4&1,f=o>>5&1,l=o>>6&1,d=o>>7&1,t.push(d,l,f,h,a,c,u,s);break}}return{get:function(o){while(t.length<o)i();let s=t.slice(0,o);return t=t.slice(o),s},resetAfterLine:function(){t.length=0},end:function(){if(r!==e.length)throw Error("extra data found")}}}function Sm(e,n,t,r,i,o){let{width:s,height:u,index:c}=e;for(let a=0;a<u;a++)for(let h=0;h<s;h++){let f=t(h,a,c);km[r](n,i,f,o),o+=r}return o}function vm(e,n,t,r,i,o){let{width:s,height:u,index:c}=e;for(let a=0;a<u;a++){for(let h=0;h<s;h++){let f=i.get(r),l=t(h,a,c);Em[r](n,f,l,o)}i.resetAfterLine()}}Mm.dataToBitMap=function(e,n){let{width:t,height:r,depth:i,bpp:o,interlace:s}=n,u;if(i!==8)u=ym(e,i);let c;if(i<=8)c=Buffer.alloc(t*r*4);else c=new Uint16Array(t*r*4);let a=Math.pow(2,i)-1,h=0,f,l;if(s)f=ca.getImagePasses(t,r),l=ca.getInterlaceIterator(t,r);else{let d=0;l=function(){let g=d;return d+=4,g},f=[{width:t,height:r}]}for(let d=0;d<f.length;d++)if(i===8)h=Sm(f[d],c,l,o,e,h);else vm(f[d],c,l,o,u,a);if(i===8){if(h!==e.length)throw Error("extra data found")}else u.end();return c}});var Ls=Me((HE,aa)=>{function Nm(e,n,t,r,i){let o=0;for(let s=0;s<r;s++)for(let u=0;u<t;u++){let c=i[e[o]];if(!c)throw Error("index "+e[o]+" not in palette");for(let a=0;a<4;a++)n[o+a]=c[a];o+=4}}function Om(e,n,t,r,i){let o=0;for(let s=0;s<r;s++)for(let u=0;u<t;u++){let c=!1;if(i.length===1){if(i[0]===e[o])c=!0}else if(i[0]===e[o]&&i[1]===e[o+1]&&i[2]===e[o+2])c=!0;if(c)for(let a=0;a<4;a++)n[o+a]=0;o+=4}}function Rm(e,n,t,r,i){let o=255,s=Math.pow(2,i)-1,u=0;for(let c=0;c<r;c++)for(let a=0;a<t;a++){for(let h=0;h<4;h++)n[u+h]=Math.floor(e[u+h]*o/s+0.5);u+=4}}aa.exports=function(e,n,t=!1){let{depth:r,width:i,height:o,colorType:s,transColor:u,palette:c}=n,a=e;if(s===3)Nm(e,a,i,o,c);else{if(u)Om(e,a,i,o,u);if(r!==8&&!t){if(r===16)a=Buffer.alloc(i*o*4);Rm(e,a,i,o,r)}}return a}});var la=Me((LE,fa)=>{var Fm=Ke("util"),As=Ke("zlib"),ha=vs(),Pm=ia(),Hm=Ps(),Lm=Hs(),Am=Ls(),Sn=fa.exports=function(e){ha.call(this),this._parser=new Hm(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()};Fm.inherits(Sn,ha);Sn.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};Sn.prototype._inflateData=function(e){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=As.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let t=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,r=Math.max(t,As.Z_MIN_CHUNK);this._inflate=As.createInflate({chunkSize:r});let i=t,o=this.emit.bind(this,"error");this._inflate.on("error",function(u){if(!i)return;o(u)}),this._filter.on("complete",this._complete.bind(this));let s=this._filter.write.bind(this._filter);this._inflate.on("data",function(u){if(!i)return;if(u.length>i)u=u.slice(0,i);i-=u.length,s(u)}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(e)};Sn.prototype._handleMetaData=function(e){this._metaData=e,this._bitmapInfo=Object.create(e),this._filter=new Pm(this._bitmapInfo)};Sn.prototype._handleTransColor=function(e){this._bitmapInfo.transColor=e};Sn.prototype._handlePalette=function(e){this._bitmapInfo.palette=e};Sn.prototype._simpleTransparency=function(){this._metaData.alpha=!0};Sn.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};Sn.prototype._finished=function(){if(this.errord)return;if(!this._inflate)this.emit("error","No Inflate block");else this._inflate.end()};Sn.prototype._complete=function(e){if(this.errord)return;let n;try{let t=Lm.dataToBitMap(e,this._bitmapInfo);n=Am(t,this._bitmapInfo,this._options.skipRescale),t=null}catch(t){this._handleError(t);return}this.emit("parsed",n)}});var ga=Me((AE,da)=>{var un=Yt();da.exports=function(e,n,t,r){let i=[un.COLORTYPE_COLOR_ALPHA,un.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 o=r.bitDepth!==16?e:new Uint16Array(e.buffer),s=255,u=un.COLORTYPE_TO_BPP_MAP[r.inputColorType];if(u===4&&!r.inputHasAlpha)u=3;let c=un.COLORTYPE_TO_BPP_MAP[r.colorType];if(r.bitDepth===16)s=65535,c*=2;let a=Buffer.alloc(n*t*c),h=0,f=0,l=r.bgColor||{};if(l.red===void 0)l.red=s;if(l.green===void 0)l.green=s;if(l.blue===void 0)l.blue=s;function d(){let g,p,k,y=s;switch(r.inputColorType){case un.COLORTYPE_COLOR_ALPHA:y=o[h+3],g=o[h],p=o[h+1],k=o[h+2];break;case un.COLORTYPE_COLOR:g=o[h],p=o[h+1],k=o[h+2];break;case un.COLORTYPE_ALPHA:y=o[h+1],g=o[h],p=g,k=g;break;case un.COLORTYPE_GRAYSCALE:g=o[h],p=g,k=g;break;default:throw Error("input color type:"+r.inputColorType+" is not supported at present")}if(r.inputHasAlpha){if(!i)y/=s,g=Math.min(Math.max(Math.round((1-y)*l.red+y*g),0),s),p=Math.min(Math.max(Math.round((1-y)*l.green+y*p),0),s),k=Math.min(Math.max(Math.round((1-y)*l.blue+y*k),0),s)}return{red:g,green:p,blue:k,alpha:y}}for(let g=0;g<t;g++)for(let p=0;p<n;p++){let k=d(o,h);switch(r.colorType){case un.COLORTYPE_COLOR_ALPHA:case un.COLORTYPE_COLOR:if(r.bitDepth===8){if(a[f]=k.red,a[f+1]=k.green,a[f+2]=k.blue,i)a[f+3]=k.alpha}else if(a.writeUInt16BE(k.red,f),a.writeUInt16BE(k.green,f+2),a.writeUInt16BE(k.blue,f+4),i)a.writeUInt16BE(k.alpha,f+6);break;case un.COLORTYPE_ALPHA:case un.COLORTYPE_GRAYSCALE:{let y=(k.red+k.green+k.blue)/3;if(r.bitDepth===8){if(a[f]=y,i)a[f+1]=k.alpha}else if(a.writeUInt16BE(y,f),i)a.writeUInt16BE(k.alpha,f+2);break}default:throw Error("unrecognised color Type "+r.colorType)}h+=u,f+=c}return a}});var wa=Me((TE,pa)=>{var ma=Is();function Tm(e,n,t,r,i){for(let o=0;o<t;o++)r[i+o]=e[n+o]}function Gm(e,n,t){let r=0,i=n+t;for(let o=n;o<i;o++)r+=Math.abs(e[o]);return r}function Um(e,n,t,r,i,o){for(let s=0;s<t;s++){let u=s>=o?e[n+s-o]:0,c=e[n+s]-u;r[i+s]=c}}function jm(e,n,t,r){let i=0;for(let o=0;o<t;o++){let s=o>=r?e[n+o-r]:0,u=e[n+o]-s;i+=Math.abs(u)}return i}function Jm(e,n,t,r,i){for(let o=0;o<t;o++){let s=n>0?e[n+o-t]:0,u=e[n+o]-s;r[i+o]=u}}function Cm(e,n,t){let r=0,i=n+t;for(let o=n;o<i;o++){let s=n>0?e[o-t]:0,u=e[o]-s;r+=Math.abs(u)}return r}function Wm(e,n,t,r,i,o){for(let s=0;s<t;s++){let u=s>=o?e[n+s-o]:0,c=n>0?e[n+s-t]:0,a=e[n+s]-(u+c>>1);r[i+s]=a}}function Km(e,n,t,r){let i=0;for(let o=0;o<t;o++){let s=o>=r?e[n+o-r]:0,u=n>0?e[n+o-t]:0,c=e[n+o]-(s+u>>1);i+=Math.abs(c)}return i}function _m(e,n,t,r,i,o){for(let s=0;s<t;s++){let u=s>=o?e[n+s-o]:0,c=n>0?e[n+s-t]:0,a=n>0&&s>=o?e[n+s-(t+o)]:0,h=e[n+s]-ma(u,c,a);r[i+s]=h}}function qm(e,n,t,r){let i=0;for(let o=0;o<t;o++){let s=o>=r?e[n+o-r]:0,u=n>0?e[n+o-t]:0,c=n>0&&o>=r?e[n+o-(t+r)]:0,a=e[n+o]-ma(s,u,c);i+=Math.abs(a)}return i}var Qm={0:Tm,1:Um,2:Jm,3:Wm,4:_m},Ym={0:Gm,1:jm,2:Cm,3:Km,4:qm};pa.exports=function(e,n,t,r,i){let o;if(!("filterType"in r)||r.filterType===-1)o=[0,1,2,3,4];else if(typeof r.filterType==="number")o=[r.filterType];else throw Error("unrecognised filter types");if(r.bitDepth===16)i*=2;let s=n*i,u=0,c=0,a=Buffer.alloc((s+1)*t),h=o[0];for(let f=0;f<t;f++){if(o.length>1){let l=1/0;for(let d=0;d<o.length;d++){let g=Ym[o[d]](e,c,s,i);if(g<l)h=o[d],l=g}}a[u]=h,u++,Qm[h](e,c,s,a,u,i),u+=s,c+=s}return a}});var Ts=Me((GE,$a)=>{var qe=Yt(),Zm=Fs(),Xm=ga(),Vm=wa(),zm=Ke("zlib"),Bn=$a.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||zm.createDeflate,e.bitDepth=e.bitDepth||8,e.colorType=typeof e.colorType==="number"?e.colorType:qe.COLORTYPE_COLOR_ALPHA,e.inputColorType=typeof e.inputColorType==="number"?e.inputColorType:qe.COLORTYPE_COLOR_ALPHA,[qe.COLORTYPE_GRAYSCALE,qe.COLORTYPE_COLOR,qe.COLORTYPE_COLOR_ALPHA,qe.COLORTYPE_ALPHA].indexOf(e.colorType)===-1)throw Error("option color type:"+e.colorType+" is not supported at present");if([qe.COLORTYPE_GRAYSCALE,qe.COLORTYPE_COLOR,qe.COLORTYPE_COLOR_ALPHA,qe.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")};Bn.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};Bn.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};Bn.prototype.filterData=function(e,n,t){let r=Xm(e,n,t,this._options),i=qe.COLORTYPE_TO_BPP_MAP[this._options.colorType];return Vm(r,n,t,this._options,i)};Bn.prototype._packChunk=function(e,n){let t=n?n.length:0,r=Buffer.alloc(t+12);if(r.writeUInt32BE(t,0),r.writeUInt32BE(e,4),n)n.copy(r,8);return r.writeInt32BE(Zm.crc32(r.slice(4,r.length-4)),r.length-4),r};Bn.prototype.packGAMA=function(e){let n=Buffer.alloc(4);return n.writeUInt32BE(Math.floor(e*qe.GAMMA_DIVISION),0),this._packChunk(qe.TYPE_gAMA,n)};Bn.prototype.packIHDR=function(e,n){let t=Buffer.alloc(13);return t.writeUInt32BE(e,0),t.writeUInt32BE(n,4),t[8]=this._options.bitDepth,t[9]=this._options.colorType,t[10]=0,t[11]=0,t[12]=0,this._packChunk(qe.TYPE_IHDR,t)};Bn.prototype.packIDAT=function(e){return this._packChunk(qe.TYPE_IDAT,e)};Bn.prototype.packIEND=function(){return this._packChunk(qe.TYPE_IEND,null)}});var ya=Me((UE,Ea)=>{var Bm=Ke("util"),ba=Ke("stream"),Dm=Yt(),xm=Ts(),ka=Ea.exports=function(e){ba.call(this);let n=e||{};this._packer=new xm(n),this._deflate=this._packer.createDeflate(),this.readable=!0};Bm.inherits(ka,ba);ka.prototype.pack=function(e,n,t,r){if(this.emit("data",Buffer.from(Dm.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(n,t)),r)this.emit("data",this._packer.packGAMA(r));let i=this._packer.filterData(e,n,t);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(o){this.emit("data",this._packer.packIDAT(o))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(i)}});var Oa=Me((Pr,Na)=>{var Sa=Ke("assert").ok,Zt=Ke("zlib"),ep=Ke("util"),va=Ke("buffer").kMaxLength;function mt(e){if(!(this instanceof mt))return new mt(e);if(e&&e.chunkSize<Zt.Z_MIN_CHUNK)e.chunkSize=Zt.Z_MIN_CHUNK;if(Zt.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 np(e){return new mt(e)}function Ma(e,n){if(n)process.nextTick(n);if(!e._handle)return;e._handle.close(),e._handle=null}mt.prototype._processChunk=function(e,n,t){if(typeof t==="function")return Zt.Inflate._processChunk.call(this,e,n,t);let r=this,i=e&&e.length,o=this._chunkSize-this._offset,s=this._maxLength,u=0,c=[],a=0,h;this.on("error",function(g){h=g});function f(g,p){if(r._hadError)return;let k=o-p;if(Sa(k>=0,"have should not go down"),k>0){let y=r._buffer.slice(r._offset,r._offset+k);if(r._offset+=k,y.length>s)y=y.slice(0,s);if(c.push(y),a+=y.length,s-=y.length,s===0)return!1}if(p===0||r._offset>=r._chunkSize)o=r._chunkSize,r._offset=0,r._buffer=Buffer.allocUnsafe(r._chunkSize);if(p===0)return u+=i-g,i=g,!0;return!1}Sa(this._handle,"zlib binding closed");let l;do l=this._handle.writeSync(n,e,u,i,this._buffer,this._offset,o),l=l||this._writeState;while(!this._hadError&&f(l[0],l[1]));if(this._hadError)throw h;if(a>=va)throw Ma(this),RangeError("Cannot create final Buffer. It would be larger than 0x"+va.toString(16)+" bytes");let d=Buffer.concat(c,a);return Ma(this),d};ep.inherits(mt,Zt.Inflate);function tp(e,n){if(typeof n==="string")n=Buffer.from(n);if(!(n instanceof Buffer))throw TypeError("Not a string or buffer");let t=e._finishFlushFlag;if(t==null)t=Zt.Z_FINISH;return e._processChunk(n,t)}function Ia(e,n){return tp(new mt(n),e)}Na.exports=Pr=Ia;Pr.Inflate=mt;Pr.createInflate=np;Pr.inflateSync=Ia});var Gs=Me((jE,Fa)=>{var Ra=Fa.exports=function(e){this._buffer=e,this._reads=[]};Ra.prototype.read=function(e,n){this._reads.push({length:Math.abs(e),allowLess:e<0,func:n})};Ra.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 n=this._buffer;this._buffer=n.slice(e.length),e.func.call(this,n.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 Pa=Me((op)=>{var rp=Gs(),ip=Ns();op.process=function(e,n){let t=[],r=new rp(e);return new ip(n,{read:r.read.bind(r),write:function(o){t.push(o)},complete:function(){}}).start(),r.process(),Buffer.concat(t)}});var Ta=Me((CE,Aa)=>{var Ha=!0,La=Ke("zlib"),up=Oa();if(!La.deflateSync)Ha=!1;var cp=Gs(),ap=Pa(),hp=Ps(),fp=Hs(),lp=Ls();Aa.exports=function(e,n){if(!Ha)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let t;function r(S){t=S}let i;function o(S){i=S}function s(S){i.transColor=S}function u(S){i.palette=S}function c(){i.alpha=!0}let a;function h(S){a=S}let f=[];function l(S){f.push(S)}let d=new cp(e);if(new hp(n,{read:d.read.bind(d),error:r,metadata:o,gamma:h,palette:u,transColor:s,inflateData:l,simpleTransparency:c}).start(),d.process(),t)throw t;let p=Buffer.concat(f);f.length=0;let k;if(i.interlace)k=La.inflateSync(p);else{let m=((i.width*i.bpp*i.depth+7>>3)+1)*i.height;k=up(p,{chunkSize:m,maxLength:m})}if(p=null,!k||!k.length)throw Error("bad png - invalid inflate data response");let y=ap.process(k,i);p=null;let M=fp.dataToBitMap(y,i);y=null;let b=lp(M,i,n.skipRescale);return i.data=b,i.gamma=a||0,i}});var Ja=Me((WE,ja)=>{var Ga=!0,Ua=Ke("zlib");if(!Ua.deflateSync)Ga=!1;var dp=Yt(),gp=Ts();ja.exports=function(e,n){if(!Ga)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let r=new gp(n||{}),i=[];if(i.push(Buffer.from(dp.PNG_SIGNATURE)),i.push(r.packIHDR(e.width,e.height)),e.gamma)i.push(r.packGAMA(e.gamma));let o=r.filterData(e.data,e.width,e.height),s=Ua.deflateSync(o,r.getDeflateOptions());if(o=null,!s||!s.length)throw Error("bad png - invalid compressed data response");return i.push(r.packIDAT(s)),i.push(r.packIEND()),Buffer.concat(i)}});var Ca=Me((wp)=>{var mp=Ta(),pp=Ja();wp.read=function(e,n){return mp(e,n||{})};wp.write=function(e,n){return pp(e,n)}});var Ka=Me((vp)=>{var kp=Ke("util"),Wa=Ke("stream"),Ep=la(),yp=ya(),Sp=Ca(),Ye=vp.PNG=function(e){if(Wa.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 Ep(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(n){this.data=n,this.emit("parsed",n)}.bind(this)),this._packer=new yp(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"))};kp.inherits(Ye,Wa);Ye.sync=Sp;Ye.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};Ye.prototype.parse=function(e,n){if(n){let t,r;t=function(i){this.removeListener("error",r),this.data=i,n(null,this)}.bind(this),r=function(i){this.removeListener("parsed",t),n(i,null)}.bind(this),this.once("parsed",t),this.once("error",r)}return this.end(e),this};Ye.prototype.write=function(e){return this._parser.write(e),!0};Ye.prototype.end=function(e){this._parser.end(e)};Ye.prototype._metadata=function(e){this.width=e.width,this.height=e.height,this.emit("metadata",e)};Ye.prototype._gamma=function(e){this.gamma=e};Ye.prototype._handleClose=function(){if(!this._parser.writable&&!this._packer.readable)this.emit("close")};Ye.bitblt=function(e,n,t,r,i,o,s,u){if(t|=0,r|=0,i|=0,o|=0,s|=0,u|=0,t>e.width||r>e.height||t+i>e.width||r+o>e.height)throw Error("bitblt reading outside image");if(s>n.width||u>n.height||s+i>n.width||u+o>n.height)throw Error("bitblt writing outside image");for(let c=0;c<o;c++)e.data.copy(n.data,(u+c)*n.width+s<<2,(r+c)*e.width+t<<2,(r+c)*e.width+t+i<<2)};Ye.prototype.bitblt=function(e,n,t,r,i,o,s){return Ye.bitblt(this,e,n,t,r,i,o,s),this};Ye.adjustGamma=function(e){if(e.gamma){for(let n=0;n<e.height;n++)for(let t=0;t<e.width;t++){let r=e.width*n+t<<2;for(let i=0;i<3;i++){let o=e.data[r+i]/255;o=Math.pow(o,0.45454545454545453/e.gamma),e.data[r+i]=Math.round(o*255)}}e.gamma=0}};Ye.prototype.adjustGamma=function(){Ye.adjustGamma(this)}});var lu=Me((bS,Jf)=>{var fu={to(e,n){if(!n)return`\x1B[${e+1}G`;return`\x1B[${n+1};${e+1}H`},move(e,n){let t="";if(e<0)t+=`\x1B[${-e}D`;else if(e>0)t+=`\x1B[${e}C`;if(n<0)t+=`\x1B[${-n}A`;else if(n>0)t+=`\x1B[${n}B`;return t},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"},w0={up:(e=1)=>"\x1B[S".repeat(e),down:(e=1)=>"\x1B[T".repeat(e)},$0={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 n="";for(let t=0;t<e;t++)n+=this.line+(t<e-1?fu.up():"");if(e)n+=fu.left;return n}};Jf.exports={cursor:fu,scroll:w0,erase:$0,beep:"\x07"}});import{spawnSync as U1}from"node:child_process";import{isMainThread as j1}from"node:worker_threads";import{parseArgs as H1}from"node:util";var _e={name:"@kecan0406/ttheme",version:"1.0.48",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","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{rmSync as Sf}from"node:fs";import{basename as n0,join as fi}from"node:path";var Dg=/^#[0-9a-f]{6}$/;function Wt(e){return Dg.test(e)}function We(e){let n=Number.parseInt(e.slice(1),16);return[n>>16&255,n>>8&255,n&255]}function Qe(e){let[n,t,r]=We(e).map((i)=>{let o=i/255;return o<=0.03928?o/12.92:((o+0.055)/1.055)**2.4});return 0.2126*n+0.7152*t+0.0722*r}function Be(e,n){let t=Qe(e),r=Qe(n);return(Math.max(t,r)+0.05)/(Math.min(t,r)+0.05)}function Wi(e,n){return Math.round(Be(e,n)*100)/100}function xg(e){let n=e/255;return n<=0.04045?n/12.92:((n+0.055)/1.055)**2.4}function dn(e){let[n,t,r]=We(e).map(xg),i=Math.cbrt(0.4122214708*n+0.5363325363*t+0.0514459929*r),o=Math.cbrt(0.2119034982*n+0.6806995451*t+0.1073969566*r),s=Math.cbrt(0.0883024619*n+0.2817188376*t+0.6299787005*r),u=1.9779984951*i-2.428592205*o+0.4505937099*s,c=0.0259040371*i+0.7827717662*o-0.808675766*s;return{l:0.2104542553*i+0.793617785*o-0.0040720468*s,c:Math.hypot(u,c),h:(Math.atan2(c,u)*180/Math.PI+360)%360}}var Zn=7,Pc=3,gs=0.15,Hc=1.6,ps=[1,2,3,4,5,6,9,10,11,12,13,14],Lc=[7,15],Kt=[1,2,3,4,5,6],Or={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}},ws=0.03,dt=25,Qi=15,Yi=0.08;function Gn(e,n){let t=e.ansi[n];if(t===void 0)throw Error(`${e.name}: missing ANSI ${n}`);return t}function ms(e,n,t){let r=e.background;return n.flatMap((i)=>{let o=Gn(e,i);return Be(o,r)<t?[`ANSI ${i} ${o} on ${r} is ${Wi(o,r)}:1, needs ${t}:1`]:[]})}function Ac(e,n){return Math.min(...n.map((t)=>Be(Gn(e,t),e.background)))}var Tc=[{rule:"foreground",label:"foreground on background",unit:"ratio",min:Zn,measure:({foreground:e,background:n})=>Be(e,n),check:({foreground:e,background:n})=>Be(e,n)<Zn?[`foreground ${e} on ${n} is ${Wi(e,n)}:1, needs ${Zn}:1`]:[]},{rule:"accents",label:"weakest accent on background",unit:"ratio",min:Pc,measure:(e)=>Ac(e,ps),check:(e)=>ms(e,ps,Pc)},{rule:"ansi0-dark",label:"ansi0 luminance",unit:"luminance",max:gs,measure:(e)=>Qe(Gn(e,0)),check:(e)=>{let n=Gn(e,0);return Qe(n)>gs?[`ANSI 0 ${n} has luminance ${Qe(n).toFixed(3)}, needs <= ${gs}`]:[]}},{rule:"light-ansi",label:"ansi7 and ansi15 on background",unit:"ratio",min:Zn,measure:(e)=>Ac(e,Lc),check:(e)=>ms(e,Lc,Zn)},{rule:"ansi8-visible",label:"ansi8 on background",unit:"ratio",min:Hc,measure:(e)=>Be(Gn(e,8),e.background),check:(e)=>ms(e,[8],Hc)},{rule:"selection",label:"foreground on selection",unit:"ratio",min:Zn,measure:({foreground:e,selectionBackground:n})=>n===void 0?Number.NaN:Be(e,n),check:({foreground:e,selectionBackground:n})=>n!==void 0&&Be(e,n)<Zn?[`foreground ${e} on selection ${n} is ${Wi(e,n)}:1, needs ${Zn}:1`]:[]}];function Xn(e,n){let t=Math.abs(e-n)%360;return Math.min(t,360-t)}var _t=(e)=>e>8?e-8:e;function Zi(e){let n=e.signatureSlots.filter((t)=>t.startsWith("ansi")).map((t)=>Number(t.slice(4)));return new Set(n.flatMap((t)=>Kt.includes(_t(t))?[t,t>8?t-8:t+8]:[t]))}function Nr(e,n){let t=dn(Gn(e,n));return t.c<ws?void 0:t}function Ki(e){let n=Zi(e);return ps.flatMap((t)=>{let r=Nr(e,t),i=Or[_t(t)];if(r===void 0||i===void 0||n.has(t))return[];let o=Xn(r.h,i.center)-i.width;return o>0?[{slot:t,hue:r.h,over:o}]:[]})}function _i(e){let n=new Set(e.signatureSlots);return Kt.flatMap((t)=>{let r=Nr(e,t),i=Nr(e,t+8);if(r===void 0||i===void 0||n.has(`ansi${t}`)&&n.has(`ansi${t+8}`))return[];return[{normal:t,gap:Xn(r.h,i.h)}]})}function qi(e){let n=Zi(e);return[0,8].flatMap((t)=>Kt.flatMap((r)=>Kt.filter((i)=>i>r).flatMap((i)=>{let[o,s]=[t+r,t+i],u=Nr(e,o),c=Nr(e,s);if(u===void 0||c===void 0||n.has(o)&&n.has(s))return[];return Xn(u.h,c.h)<Qi&&Math.abs(u.l-c.l)<Yi?[[o,s]]:[]})))}var em=[{rule:"ansi-role",label:"accent hue outside its ANSI role",unit:"degrees",max:0,measure:(e)=>Math.max(0,...Ki(e).map((n)=>n.over)),check:(e)=>Ki(e).map(({slot:n,hue:t,over:r})=>{let i=Or[_t(n)];return`ANSI ${n} ${Gn(e,n)} has hue ${t.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:dt,measure:(e)=>Math.max(0,..._i(e).map((n)=>n.gap)),check:(e)=>_i(e).filter((n)=>n.gap>dt).map(({normal:n,gap:t})=>`ANSI ${n+8} is ${t.toFixed(0)}° from ANSI ${n}, needs <= ${dt}°`)},{rule:"distinct",label:"accent pairs that read as one color",unit:"pairs",max:0,measure:(e)=>qi(e).length,check:(e)=>qi(e).map(([n,t])=>`ANSI ${n} ${Gn(e,n)} and ANSI ${t} ${Gn(e,t)} are within ${Qi}° hue and ${Yi} lightness`)}],Xi=[...Tc,...em],$s=Xi.map((e)=>e.rule),gt=Xi.map(({rule:e,label:n,unit:t,min:r,max:i})=>({rule:e,label:n,unit:t,...r===void 0?{}:{min:r},...i===void 0?{}:{max:i}}));function qt(e){return Xi.map((n)=>Math.round(n.measure(e)*1000)/1000)}function Gc(e,n){return e.filter((t)=>!n.waive.includes(t.rule)).flatMap((t)=>t.check(n).map((r)=>({theme:n.name,rule:t.rule,detail:r})))}function Vi(e){return Gc(Xi,e)}function Uc(e){return Gc(Tc,e)}function jc(e){return e.flatMap(Vi)}import{readdirSync as rw,readFileSync as bh}from"node:fs";import{basename as iw,join as kh}from"node:path";/*!
2
+ import{createRequire as Om}from"node:module";var ym=Object.create;var{getPrototypeOf:Em,defineProperty:ta,getOwnPropertyNames:Sm}=Object;var Mm=Object.prototype.hasOwnProperty;function vm(e){return this[e]}var Im,Nm,Vi=(e,n,t)=>{var r=e!=null&&typeof e==="object";if(r){var i=n?Im??=new WeakMap:Nm??=new WeakMap,o=i.get(e);if(o)return o}t=e!=null?ym(Em(e)):{};let s=n||!e||!e.__esModule?ta(t,"default",{value:e,enumerable:!0}):t;for(let u of Sm(e))if(!Mm.call(s,u))ta(s,u,{get:vm.bind(e,u),enumerable:!0});if(r)i.set(e,s);return s};var ve=(e,n)=>()=>(n||e((n={exports:{}}).exports,n),n.exports);var Ke=Om(import.meta.url);var ba=ve(($E,ao)=>{var wa=wa||function(e){return Buffer.from(e).toString("base64")};function Cm(e){var n=this,t=Math.round,r=Math.floor,i=Array(64),o=Array(64),s=Array(64),u=Array(64),c,a,f,h,l=Array(65535),d=Array(65535),g=Array(64),m=Array(64),$=[],S=0,v=7,k=Array(64),M=Array(64),p=Array(64),A=Array(256),y=Array(2048),F,N=[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],G=[0,1,2,3,4,5,6,7,8,9,10,11],ae=[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],Le=[0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0],J=[0,1,2,3,4,5,6,7,8,9,10,11],D=[0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,119],Oe=[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 ye(w){var L=[16,11,10,16,24,40,51,61,12,12,14,19,26,58,60,55,14,13,16,24,40,57,69,56,14,17,22,29,51,87,80,62,18,22,37,56,68,109,103,77,24,35,55,64,81,104,113,92,49,64,78,87,103,121,120,101,72,92,95,98,112,100,103,99];for(var _=0;_<64;_++){var U=r((L[_]*w+50)/100);if(U<1)U=1;else if(U>255)U=255;i[N[_]]=U}var Q=[17,18,24,47,99,99,99,99,18,21,26,66,99,99,99,99,24,26,56,99,99,99,99,99,47,66,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99];for(var Z=0;Z<64;Z++){var oe=r((Q[Z]*w+50)/100);if(oe<1)oe=1;else if(oe>255)oe=255;o[N[Z]]=oe}var se=[1,1.387039845,1.306562965,1.175875602,1,0.785694958,0.5411961,0.275899379],Fe=0;for(var Me=0;Me<8;Me++)for(var I=0;I<8;I++)s[Fe]=1/(i[N[Fe]]*se[Me]*se[I]*8),u[Fe]=1/(o[N[Fe]]*se[Me]*se[I]*8),Fe++}function ee(w,L){var _=0,U=0,Q=[];for(var Z=1;Z<=16;Z++){for(var oe=1;oe<=w[Z];oe++)Q[L[U]]=[],Q[L[U]][0]=_,Q[L[U]][1]=Z,U++,_++;_*=2}return Q}function Te(){c=ee(H,G),a=ee(Le,J),f=ee(ae,C),h=ee(D,Oe)}function ue(){var w=1,L=2;for(var _=1;_<=15;_++){for(var U=w;U<L;U++)d[32767+U]=_,l[32767+U]=[],l[32767+U][1]=_,l[32767+U][0]=U;for(var Q=-(L-1);Q<=-w;Q++)d[32767+Q]=_,l[32767+Q]=[],l[32767+Q][1]=_,l[32767+Q][0]=L-1+Q;w<<=1,L<<=1}}function te(){for(var w=0;w<256;w++)y[w]=19595*w,y[w+256>>0]=38470*w,y[w+512>>0]=7471*w+32768,y[w+768>>0]=-11059*w,y[w+1024>>0]=-21709*w,y[w+1280>>0]=32768*w+8421375,y[w+1536>>0]=-27439*w,y[w+1792>>0]=-5329*w}function z(w){var L=w[0],_=w[1]-1;while(_>=0){if(L&1<<_)S|=1<<v;if(_--,v--,v<0){if(S==255)b(255),b(0);else b(S);v=7,S=0}}}function b(w){$.push(w)}function T(w){b(w>>8&255),b(w&255)}function we(w,L){var _,U,Q,Z,oe,se,Fe,Me,I=0,P,q=8,Re=64;for(P=0;P<q;++P){_=w[I],U=w[I+1],Q=w[I+2],Z=w[I+3],oe=w[I+4],se=w[I+5],Fe=w[I+6],Me=w[I+7];var X=_+Me,ne=_-Me,$e=U+Fe,W=U-Fe,fe=Q+se,We=Q-se,Ne=Z+oe,un=Z-oe,Mn=X+Ne,gt=X-Ne,Qt=$e+fe,Yt=$e-fe;w[I]=Mn+Qt,w[I+4]=Mn-Qt;var Ar=(Yt+gt)*0.707106781;w[I+2]=gt+Ar,w[I+6]=gt-Ar,Mn=un+We,Qt=We+W,Yt=W+ne;var Hr=(Mn-Yt)*0.382683433,Yi=0.5411961*Mn+Hr,Lr=1.306562965*Yt+Hr,Tr=Qt*0.707106781,Gr=ne+Tr,Ur=ne-Tr;w[I+5]=Ur+Yi,w[I+3]=Ur-Yi,w[I+1]=Gr+Lr,w[I+7]=Gr-Lr,I+=8}I=0;for(P=0;P<q;++P){_=w[I],U=w[I+8],Q=w[I+16],Z=w[I+24],oe=w[I+32],se=w[I+40],Fe=w[I+48],Me=w[I+56];var Kc=_+Me,vs=_-Me,qc=U+Fe,Qc=U-Fe,Yc=Q+se,Zc=Q-se,Xc=Z+oe,km=Z-oe,jr=Kc+Xc,Is=Kc-Xc,Zi=qc+Yc,Xi=qc-Yc;w[I]=jr+Zi,w[I+32]=jr-Zi;var zc=(Xi+Is)*0.707106781;w[I+16]=Is+zc,w[I+48]=Is-zc,jr=km+Zc,Zi=Zc+Qc,Xi=Qc+vs;var Vc=(jr-Xi)*0.382683433,Bc=0.5411961*jr+Vc,Dc=1.306562965*Xi+Vc,xc=Zi*0.707106781,ea=vs+xc,na=vs-xc;w[I+40]=na+Bc,w[I+24]=na-Bc,w[I+8]=ea+Dc,w[I+56]=ea-Dc,I++}var zi;for(P=0;P<Re;++P)zi=w[P]*L[P],g[P]=zi>0?zi+0.5|0:zi-0.5|0;return g}function be(){T(65504),T(16),b(74),b(70),b(73),b(70),b(0),b(1),b(1),b(0),T(1),T(1),b(0),b(0)}function re(w){if(!w)return;if(T(65505),w[0]===69&&w[1]===120&&w[2]===105&&w[3]===102)T(w.length+2);else T(w.length+5+2),b(69),b(120),b(105),b(102),b(0);for(var L=0;L<w.length;L++)b(w[L])}function ie(w,L){T(65472),T(17),b(8),T(L),T(w),b(3),b(1),b(17),b(0),b(2),b(17),b(1),b(3),b(17),b(1)}function V(){T(65499),T(132),b(0);for(var w=0;w<64;w++)b(i[w]);b(1);for(var L=0;L<64;L++)b(o[L])}function R(){T(65476),T(418),b(0);for(var w=0;w<16;w++)b(H[w+1]);for(var L=0;L<=11;L++)b(G[L]);b(16);for(var _=0;_<16;_++)b(ae[_+1]);for(var U=0;U<=161;U++)b(C[U]);b(1);for(var Q=0;Q<16;Q++)b(Le[Q+1]);for(var Z=0;Z<=11;Z++)b(J[Z]);b(17);for(var oe=0;oe<16;oe++)b(D[oe+1]);for(var se=0;se<=161;se++)b(Oe[se])}function O(w){if(typeof w>"u"||w.constructor!==Array)return;w.forEach((L)=>{if(typeof L!=="string")return;T(65534);var _=L.length;T(_+2);var U;for(U=0;U<_;U++)b(L.charCodeAt(U))})}function Se(){T(65498),T(12),b(3),b(1),b(0),b(2),b(17),b(3),b(17),b(0),b(63),b(0)}function K(w,L,_,U,Q){var Z=Q[0],oe=Q[240],se,Fe=16,Me=63,I=64,P=we(w,L);for(var q=0;q<I;++q)m[N[q]]=P[q];var Re=m[0]-_;if(_=m[0],Re==0)z(U[0]);else se=32767+Re,z(U[d[se]]),z(l[se]);var X=63;for(;X>0&&m[X]==0;X--);if(X==0)return z(Z),_;var ne=1,$e;while(ne<=X){var W=ne;for(;m[ne]==0&&ne<=X;++ne);var fe=ne-W;if(fe>=Fe){$e=fe>>4;for(var We=1;We<=$e;++We)z(oe);fe=fe&15}se=32767+m[ne],z(Q[(fe<<4)+d[se]]),z(l[se]),ne++}if(X!=Me)z(Z);return _}function B(){var w=String.fromCharCode;for(var L=0;L<256;L++)A[L]=w(L)}this.encode=function(w,L){var _=new Date().getTime();if(L)sn(L);$=[],S=0,v=7,T(65496),be(),O(w.comments),re(w.exifBuffer),V(),ie(w.width,w.height),R(),Se();var U=0,Q=0,Z=0;S=0,v=7,this.encode.displayName="_encode_";var{data:oe,width:se,height:Fe}=w,Me=se*4,I=se*3,P,q=0,Re,X,ne,$e,W,fe,We,Ne;while(q<Fe){P=0;while(P<Me){$e=Me*q+P,W=$e,fe=-1,We=0;for(Ne=0;Ne<64;Ne++){if(We=Ne>>3,fe=(Ne&7)*4,W=$e+We*Me+fe,q+We>=Fe)W-=Me*(q+1+We-Fe);if(P+fe>=Me)W-=P+fe-Me+4;Re=oe[W++],X=oe[W++],ne=oe[W++],k[Ne]=(y[Re]+y[X+256>>0]+y[ne+512>>0]>>16)-128,M[Ne]=(y[Re+768>>0]+y[X+1024>>0]+y[ne+1280>>0]>>16)-128,p[Ne]=(y[Re+1280>>0]+y[X+1536>>0]+y[ne+1792>>0]>>16)-128}U=K(k,s,U,c,f),Q=K(M,u,Q,a,h),Z=K(p,u,Z,a,h),P+=32}q+=8}if(v>=0){var un=[];un[1]=v+1,un[0]=(1<<v+1)-1,z(un)}if(T(65497),typeof ao>"u")return new Uint8Array($);return Buffer.from($);var Mn,gt};function sn(w){if(w<=0)w=1;if(w>100)w=100;if(F==w)return;var L=0;if(w<50)L=Math.floor(5000/w);else L=Math.floor(200-w*2);ye(L),F=w}function gn(){var w=new Date().getTime();if(!e)e=50;B(),Te(),ue(),te(),sn(e);var L=new Date().getTime()-w}gn()}if(typeof ao<"u")ao.exports=pa;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].encode=pa;function pa(e,n){if(typeof n>"u")n=50;var t=new Cm(n),r=t.encode(e,n);return{data:r,width:e.width,height:e.height}}});var ka=ve((kE,Gs)=>{var Ts=function(){var n=new Int32Array([0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5,12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28,35,42,49,56,57,50,43,36,29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54,47,55,62,63]),t=4017,r=799,i=3406,o=2276,s=1567,u=3784,c=5793,a=2896;function f(){}function h(v,k){var M=0,p=[],A,y,F=16;while(F>0&&!v[F-1])F--;p.push({children:[],index:0});var N=p[0],H;for(A=0;A<F;A++){for(y=0;y<v[A];y++){N=p.pop(),N.children[N.index]=k[M];while(N.index>0){if(p.length===0)throw Error("Could not recreate Huffman Table");N=p.pop()}N.index++,p.push(N);while(p.length<=A)p.push(H={children:[],index:0}),N.children[N.index]=H.children,N=H;M++}if(A+1<F)p.push(H={children:[],index:0}),N.children[N.index]=H.children,N=H}return p[0].children}function l(v,k,M,p,A,y,F,N,H,G){var{precision:ae,samplesPerLine:C,scanLines:Le,mcusPerLine:J,progressive:D,maxH:Oe,maxV:ye}=M,ee=k,Te=0,ue=0;function te(){if(ue>0)return ue--,Te>>ue&1;if(Te=v[k++],Te==255){var I=v[k++];if(I)throw Error("unexpected marker: "+(Te<<8|I).toString(16))}return ue=7,Te>>>7}function z(I){var P=I,q;while((q=te())!==null){if(P=P[q],typeof P==="number")return P;if(typeof P!=="object")throw Error("invalid huffman sequence")}return null}function b(I){var P=0;while(I>0){var q=te();if(q===null)return;P=P<<1|q,I--}return P}function T(I){var P=b(I);if(P>=1<<I-1)return P;return P+(-1<<I)+1}function we(I,P){var q=z(I.huffmanTableDC),Re=q===0?0:T(q);P[0]=I.pred+=Re;var X=1;while(X<64){var ne=z(I.huffmanTableAC),$e=ne&15,W=ne>>4;if($e===0){if(W<15)break;X+=16;continue}X+=W;var fe=n[X];P[fe]=T($e),X++}}function be(I,P){var q=z(I.huffmanTableDC),Re=q===0?0:T(q)<<H;P[0]=I.pred+=Re}function re(I,P){P[0]|=te()<<H}var ie=0;function V(I,P){if(ie>0){ie--;return}var q=y,Re=F;while(q<=Re){var X=z(I.huffmanTableAC),ne=X&15,$e=X>>4;if(ne===0){if($e<15){ie=b($e)+(1<<$e)-1;break}q+=16;continue}q+=$e;var W=n[q];P[W]=T(ne)*(1<<H),q++}}var R=0,O;function Se(I,P){var q=y,Re=F,X=0;while(q<=Re){var ne=n[q],$e=P[ne]<0?-1:1;switch(R){case 0:var W=z(I.huffmanTableAC),fe=W&15,X=W>>4;if(fe===0)if(X<15)ie=b(X)+(1<<X),R=4;else X=16,R=1;else{if(fe!==1)throw Error("invalid ACn encoding");O=T(fe),R=X?2:3}continue;case 1:case 2:if(P[ne])P[ne]+=(te()<<H)*$e;else if(X--,X===0)R=R==2?3:0;break;case 3:if(P[ne])P[ne]+=(te()<<H)*$e;else P[ne]=O<<H,R=0;break;case 4:if(P[ne])P[ne]+=(te()<<H)*$e;break}q++}if(R===4){if(ie--,ie===0)R=0}}function K(I,P,q,Re,X){var ne=q/J|0,$e=q%J,W=ne*I.v+Re,fe=$e*I.h+X;if(I.blocks[W]===void 0&&G.tolerantDecoding)return;P(I,I.blocks[W][fe])}function B(I,P,q){var Re=q/I.blocksPerLine|0,X=q%I.blocksPerLine;if(I.blocks[Re]===void 0&&G.tolerantDecoding)return;P(I,I.blocks[Re][X])}var sn=p.length,gn,w,L,_,U,Q;if(D)if(y===0)Q=N===0?be:re;else Q=N===0?V:Se;else Q=we;var Z=0,oe,se;if(sn==1)se=p[0].blocksPerLine*p[0].blocksPerColumn;else se=J*M.mcusPerColumn;if(!A)A=se;var Fe,Me;while(Z<se){for(w=0;w<sn;w++)p[w].pred=0;if(ie=0,sn==1){gn=p[0];for(U=0;U<A;U++)B(gn,Q,Z),Z++}else for(U=0;U<A;U++){for(w=0;w<sn;w++){gn=p[w],Fe=gn.h,Me=gn.v;for(L=0;L<Me;L++)for(_=0;_<Fe;_++)K(gn,Q,Z,L,_)}if(Z++,Z===se)break}if(Z===se)do{if(v[k]===255){if(v[k+1]!==0)break}k+=1}while(k<v.length-2);if(ue=0,oe=v[k]<<8|v[k+1],oe<65280)throw Error("marker was not found");if(oe>=65488&&oe<=65495)k+=2;else break}return k-ee}function d(v,k){var M=[],p=k.blocksPerLine,A=k.blocksPerColumn,y=p<<3,F=new Int32Array(64),N=new Uint8Array(64);function H(ee,Te,ue){var te=k.quantizationTable,z,b,T,we,be,re,ie,V,R,O=ue,Se;for(Se=0;Se<64;Se++)O[Se]=ee[Se]*te[Se];for(Se=0;Se<8;++Se){var K=8*Se;if(O[1+K]==0&&O[2+K]==0&&O[3+K]==0&&O[4+K]==0&&O[5+K]==0&&O[6+K]==0&&O[7+K]==0){R=c*O[0+K]+512>>10,O[0+K]=R,O[1+K]=R,O[2+K]=R,O[3+K]=R,O[4+K]=R,O[5+K]=R,O[6+K]=R,O[7+K]=R;continue}z=c*O[0+K]+128>>8,b=c*O[4+K]+128>>8,T=O[2+K],we=O[6+K],be=a*(O[1+K]-O[7+K])+128>>8,V=a*(O[1+K]+O[7+K])+128>>8,re=O[3+K]<<4,ie=O[5+K]<<4,R=z-b+1>>1,z=z+b+1>>1,b=R,R=T*u+we*s+128>>8,T=T*s-we*u+128>>8,we=R,R=be-ie+1>>1,be=be+ie+1>>1,ie=R,R=V+re+1>>1,re=V-re+1>>1,V=R,R=z-we+1>>1,z=z+we+1>>1,we=R,R=b-T+1>>1,b=b+T+1>>1,T=R,R=be*o+V*i+2048>>12,be=be*i-V*o+2048>>12,V=R,R=re*r+ie*t+2048>>12,re=re*t-ie*r+2048>>12,ie=R,O[0+K]=z+V,O[7+K]=z-V,O[1+K]=b+ie,O[6+K]=b-ie,O[2+K]=T+re,O[5+K]=T-re,O[3+K]=we+be,O[4+K]=we-be}for(Se=0;Se<8;++Se){var B=Se;if(O[8+B]==0&&O[16+B]==0&&O[24+B]==0&&O[32+B]==0&&O[40+B]==0&&O[48+B]==0&&O[56+B]==0){R=c*ue[Se+0]+8192>>14,O[0+B]=R,O[8+B]=R,O[16+B]=R,O[24+B]=R,O[32+B]=R,O[40+B]=R,O[48+B]=R,O[56+B]=R;continue}z=c*O[0+B]+2048>>12,b=c*O[32+B]+2048>>12,T=O[16+B],we=O[48+B],be=a*(O[8+B]-O[56+B])+2048>>12,V=a*(O[8+B]+O[56+B])+2048>>12,re=O[24+B],ie=O[40+B],R=z-b+1>>1,z=z+b+1>>1,b=R,R=T*u+we*s+2048>>12,T=T*s-we*u+2048>>12,we=R,R=be-ie+1>>1,be=be+ie+1>>1,ie=R,R=V+re+1>>1,re=V-re+1>>1,V=R,R=z-we+1>>1,z=z+we+1>>1,we=R,R=b-T+1>>1,b=b+T+1>>1,T=R,R=be*o+V*i+2048>>12,be=be*i-V*o+2048>>12,V=R,R=re*r+ie*t+2048>>12,re=re*t-ie*r+2048>>12,ie=R,O[0+B]=z+V,O[56+B]=z-V,O[8+B]=b+ie,O[48+B]=b-ie,O[16+B]=T+re,O[40+B]=T-re,O[24+B]=we+be,O[32+B]=we-be}for(Se=0;Se<64;++Se){var sn=128+(O[Se]+8>>4);Te[Se]=sn<0?0:sn>255?255:sn}}S(y*A*8);var G,ae;for(var C=0;C<A;C++){var Le=C<<3;for(G=0;G<8;G++)M.push(new Uint8Array(y));for(var J=0;J<p;J++){H(k.blocks[C][J],N,F);var D=0,Oe=J<<3;for(ae=0;ae<8;ae++){var ye=M[Le+ae];for(G=0;G<8;G++)ye[Oe+G]=N[D++]}}}return M}function g(v){return v<0?0:v>255?255:v}f.prototype={load:function(k){var M=new XMLHttpRequest;M.open("GET",k,!0),M.responseType="arraybuffer",M.onload=function(){var p=new Uint8Array(M.response||M.mozResponseArrayBuffer);if(this.parse(p),this.onload)this.onload()}.bind(this),M.send(null)},parse:function(k){var M=this.opts.maxResolutionInMP*1000*1000,p=0,A=k.length;function y(){var W=k[p]<<8|k[p+1];return p+=2,W}function F(){var W=y(),fe=k.subarray(p,p+W-2);return p+=fe.length,fe}function N(W){var fe=1,We=1,Ne,un;for(un in W.components)if(W.components.hasOwnProperty(un)){if(Ne=W.components[un],fe<Ne.h)fe=Ne.h;if(We<Ne.v)We=Ne.v}var Mn=Math.ceil(W.samplesPerLine/8/fe),gt=Math.ceil(W.scanLines/8/We);for(un in W.components)if(W.components.hasOwnProperty(un)){Ne=W.components[un];var Qt=Math.ceil(Math.ceil(W.samplesPerLine/8)*Ne.h/fe),Yt=Math.ceil(Math.ceil(W.scanLines/8)*Ne.v/We),Ar=Mn*Ne.h,Hr=gt*Ne.v,Yi=Hr*Ar,Lr=[];S(Yi*256);for(var Tr=0;Tr<Hr;Tr++){var Gr=[];for(var Ur=0;Ur<Ar;Ur++)Gr.push(new Int32Array(64));Lr.push(Gr)}Ne.blocksPerLine=Qt,Ne.blocksPerColumn=Yt,Ne.blocks=Lr}W.maxH=fe,W.maxV=We,W.mcusPerLine=Mn,W.mcusPerColumn=gt}var H=null,G=null,ae=null,C,Le,J=[],D=[],Oe=[],ye=[],ee=y(),Te=-1;if(this.comments=[],ee!=65496)throw Error("SOI not found");ee=y();while(ee!=65497){var ue,te,z;switch(ee){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 b=F();if(ee===65534){var T=String.fromCharCode.apply(null,b);this.comments.push(T)}if(ee===65504){if(b[0]===74&&b[1]===70&&b[2]===73&&b[3]===70&&b[4]===0)H={version:{major:b[5],minor:b[6]},densityUnits:b[7],xDensity:b[8]<<8|b[9],yDensity:b[10]<<8|b[11],thumbWidth:b[12],thumbHeight:b[13],thumbData:b.subarray(14,14+3*b[12]*b[13])}}if(ee===65505){if(b[0]===69&&b[1]===120&&b[2]===105&&b[3]===102&&b[4]===0)this.exifBuffer=b.subarray(5,b.length)}if(ee===65518){if(b[0]===65&&b[1]===100&&b[2]===111&&b[3]===98&&b[4]===101&&b[5]===0)G={version:b[6],flags0:b[7]<<8|b[8],flags1:b[9]<<8|b[10],transformCode:b[11]}}break;case 65499:var we=y(),be=we+p-2;while(p<be){var re=k[p++];S(256);var ie=new Int32Array(64);if(re>>4===0)for(te=0;te<64;te++){var V=n[te];ie[V]=k[p++]}else if(re>>4===1)for(te=0;te<64;te++){var V=n[te];ie[V]=y()}else throw Error("DQT: invalid table spec");J[re&15]=ie}break;case 65472:case 65473:case 65474:y(),C={},C.extended=ee===65473,C.progressive=ee===65474,C.precision=k[p++],C.scanLines=y(),C.samplesPerLine=y(),C.components={},C.componentsOrder=[];var R=C.scanLines*C.samplesPerLine;if(R>M){var O=Math.ceil((R-M)/1e6);throw Error(`maxResolutionInMP limit exceeded by ${O}MP`)}var Se=k[p++],K,B=0,sn=0;for(ue=0;ue<Se;ue++){K=k[p];var gn=k[p+1]>>4,w=k[p+1]&15,L=k[p+2];if(gn<=0||w<=0)throw Error("Invalid sampling factor, expected values above 0");C.componentsOrder.push(K),C.components[K]={h:gn,v:w,quantizationIdx:L},p+=3}N(C),D.push(C);break;case 65476:var _=y();for(ue=2;ue<_;){var U=k[p++],Q=new Uint8Array(16),Z=0;for(te=0;te<16;te++,p++)Z+=Q[te]=k[p];S(16+Z);var oe=new Uint8Array(Z);for(te=0;te<Z;te++,p++)oe[te]=k[p];ue+=17+Z,(U>>4===0?ye:Oe)[U&15]=h(Q,oe)}break;case 65501:y(),Le=y();break;case 65500:y(),y();break;case 65498:var se=y(),Fe=k[p++],Me=[],I;for(ue=0;ue<Fe;ue++){I=C.components[k[p++]];var P=k[p++];I.huffmanTableDC=ye[P>>4],I.huffmanTableAC=Oe[P&15],Me.push(I)}var q=k[p++],Re=k[p++],X=k[p++],ne=l(k,p,C,Me,Le,q,Re,X>>4,X&15,this.opts);p+=ne;break;case 65535:if(k[p]!==255)p--;break;default:if(k[p-3]==255&&k[p-2]>=192&&k[p-2]<=254){p-=3;break}else if(ee===224||ee==225){if(Te!==-1)throw Error(`first unknown JPEG marker at offset ${Te.toString(16)}, second unknown JPEG marker ${ee.toString(16)} at offset ${(p-1).toString(16)}`);Te=p-1;let W=y();if(k[p+W-2]===255){p+=W-2;break}}throw Error("unknown JPEG marker "+ee.toString(16))}ee=y()}if(D.length!=1)throw Error("only single frame JPEGs supported");for(var ue=0;ue<D.length;ue++){var $e=D[ue].components;for(var te in $e)$e[te].quantizationTable=J[$e[te].quantizationIdx],delete $e[te].quantizationIdx}this.width=C.samplesPerLine,this.height=C.scanLines,this.jfif=H,this.adobe=G,this.components=[];for(var ue=0;ue<C.componentsOrder.length;ue++){var I=C.components[C.componentsOrder[ue]];this.components.push({lines:d(C,I),scaleX:I.h/C.maxH,scaleY:I.v/C.maxV})}},getData:function(k,M){var p=this.width/k,A=this.height/M,y,F,N,H,G,ae,C,Le,J,D,Oe=0,ye,ee,Te,ue,te,z,b,T,we,be,re,ie=k*M*this.components.length;S(ie);var V=new Uint8Array(ie);switch(this.components.length){case 1:y=this.components[0];for(D=0;D<M;D++){G=y.lines[0|D*y.scaleY*A];for(J=0;J<k;J++)ye=G[0|J*y.scaleX*p],V[Oe++]=ye}break;case 2:y=this.components[0],F=this.components[1];for(D=0;D<M;D++){G=y.lines[0|D*y.scaleY*A],ae=F.lines[0|D*F.scaleY*A];for(J=0;J<k;J++)ye=G[0|J*y.scaleX*p],V[Oe++]=ye,ye=ae[0|J*F.scaleX*p],V[Oe++]=ye}break;case 3:if(re=!0,this.adobe&&this.adobe.transformCode)re=!0;else if(typeof this.opts.colorTransform<"u")re=!!this.opts.colorTransform;y=this.components[0],F=this.components[1],N=this.components[2];for(D=0;D<M;D++){G=y.lines[0|D*y.scaleY*A],ae=F.lines[0|D*F.scaleY*A],C=N.lines[0|D*N.scaleY*A];for(J=0;J<k;J++){if(!re)T=G[0|J*y.scaleX*p],we=ae[0|J*F.scaleX*p],be=C[0|J*N.scaleX*p];else ye=G[0|J*y.scaleX*p],ee=ae[0|J*F.scaleX*p],Te=C[0|J*N.scaleX*p],T=g(ye+1.402*(Te-128)),we=g(ye-0.3441363*(ee-128)-0.71413636*(Te-128)),be=g(ye+1.772*(ee-128));V[Oe++]=T,V[Oe++]=we,V[Oe++]=be}}break;case 4:if(!this.adobe)throw Error("Unsupported color mode (4 components)");if(re=!1,this.adobe&&this.adobe.transformCode)re=!0;else if(typeof this.opts.colorTransform<"u")re=!!this.opts.colorTransform;y=this.components[0],F=this.components[1],N=this.components[2],H=this.components[3];for(D=0;D<M;D++){G=y.lines[0|D*y.scaleY*A],ae=F.lines[0|D*F.scaleY*A],C=N.lines[0|D*N.scaleY*A],Le=H.lines[0|D*H.scaleY*A];for(J=0;J<k;J++){if(!re)te=G[0|J*y.scaleX*p],z=ae[0|J*F.scaleX*p],b=C[0|J*N.scaleX*p],ue=Le[0|J*H.scaleX*p];else ye=G[0|J*y.scaleX*p],ee=ae[0|J*F.scaleX*p],Te=C[0|J*N.scaleX*p],ue=Le[0|J*H.scaleX*p],te=255-g(ye+1.402*(Te-128)),z=255-g(ye-0.3441363*(ee-128)-0.71413636*(Te-128)),b=255-g(ye+1.772*(ee-128));V[Oe++]=255-te,V[Oe++]=255-z,V[Oe++]=255-b,V[Oe++]=255-ue}}break;default:throw Error("Unsupported color mode")}return V},copyToImageData:function(k,M){var{width:p,height:A,data:y}=k,F=this.getData(p,A),N=0,H=0,G,ae,C,Le,J,D,Oe,ye,ee;switch(this.components.length){case 1:for(ae=0;ae<A;ae++)for(G=0;G<p;G++)if(C=F[N++],y[H++]=C,y[H++]=C,y[H++]=C,M)y[H++]=255;break;case 3:for(ae=0;ae<A;ae++)for(G=0;G<p;G++)if(Oe=F[N++],ye=F[N++],ee=F[N++],y[H++]=Oe,y[H++]=ye,y[H++]=ee,M)y[H++]=255;break;case 4:for(ae=0;ae<A;ae++)for(G=0;G<p;G++)if(J=F[N++],D=F[N++],C=F[N++],Le=F[N++],Oe=255-g(J*(1-Le/255)+Le),ye=255-g(D*(1-Le/255)+Le),ee=255-g(C*(1-Le/255)+Le),y[H++]=Oe,y[H++]=ye,y[H++]=ee,M)y[H++]=255;break;default:throw Error("Unsupported color mode")}}};var m=0,$=0;function S(v=0){var k=m+v;if(k>$){var M=Math.ceil((k-$)/1024/1024);throw Error(`maxMemoryUsageInMB limit exceeded by at least ${M}MB`)}m=k}return f.resetMaxMemoryUsage=function(v){m=0,$=v},f.getBytesAllocated=function(){return m},f.requestMemoryAllocation=S,f}();if(typeof Gs<"u")Gs.exports=$a;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].decode=$a;function $a(e,n={}){var t={colorTransform:void 0,useTArray:!1,formatAsRGBA:!0,tolerantDecoding:!0,maxResolutionInMP:100,maxMemoryUsageInMB:512},r={...t,...n},i=new Uint8Array(e),o=new Ts;o.opts=r,Ts.resetMaxMemoryUsage(r.maxMemoryUsageInMB*1024*1024),o.parse(i);var s=r.formatAsRGBA?4:3,u=o.width*o.height*s;try{Ts.requestMemoryAllocation(u);var c={width:o.width,height:o.height,exifBuffer:o.exifBuffer,data:r.useTArray?new Uint8Array(u):Buffer.alloc(u)};if(o.comments.length>0)c.comments=o.comments}catch(a){if(a instanceof RangeError)throw Error("Could not allocate enough memory for the image. Required: "+u);if(a instanceof ReferenceError){if(a.message==="Buffer is not defined")throw Error("Buffer is not globally defined in this environment. Consider setting useTArray to true")}throw a}return o.copyToImageData(c,r.formatAsRGBA),c}});var Ea=ve((yE,ya)=>{var Jm=ba(),_m=ka();ya.exports={encode:Jm,decode:_m}});var Us=ve((EE,Ma)=>{var Wm=Ke("util"),Sa=Ke("stream"),wn=Ma.exports=function(){Sa.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};Wm.inherits(wn,Sa);wn.prototype.read=function(e,n){this._reads.push({length:Math.abs(e),allowLess:e<0,func:n}),process.nextTick(function(){if(this._process(),this._paused&&this._reads&&this._reads.length>0)this._paused=!1,this.emit("drain")}.bind(this))};wn.prototype.write=function(e,n){if(!this.writable)return this.emit("error",Error("Stream not writable")),!1;let t;if(Buffer.isBuffer(e))t=e;else t=Buffer.from(e,n||this._encoding);if(this._buffers.push(t),this._buffered+=t.length,this._process(),this._reads&&this._reads.length===0)this._paused=!0;return this.writable&&!this._paused};wn.prototype.end=function(e,n){if(e)this.write(e,n);if(this.writable=!1,!this._buffers)return;if(this._buffers.length===0)this._end();else this._buffers.push(null),this._process()};wn.prototype.destroySoon=wn.prototype.end;wn.prototype._end=function(){if(this._reads.length>0)this.emit("error",Error("Unexpected end of input"));this.destroy()};wn.prototype.destroy=function(){if(!this._buffers)return;this.writable=!1,this._reads=null,this._buffers=null,this.emit("close")};wn.prototype._processReadAllowingLess=function(e){this._reads.shift();let n=this._buffers[0];if(n.length>e.length)this._buffered-=e.length,this._buffers[0]=n.slice(e.length),e.func.call(this,n.slice(0,e.length));else this._buffered-=n.length,this._buffers.shift(),e.func.call(this,n)};wn.prototype._processRead=function(e){this._reads.shift();let n=0,t=0,r=Buffer.alloc(e.length);while(n<e.length){let i=this._buffers[t++],o=Math.min(i.length,e.length-n);if(i.copy(r,n,0,o),n+=o,o!==i.length)this._buffers[--t]=i.slice(o)}if(t>0)this._buffers.splice(0,t);this._buffered-=e.length,e.func.call(this,r)};wn.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 js=ve((Km)=>{var xn=[{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]}];Km.getImagePasses=function(e,n){let t=[],r=e%8,i=n%8,o=(e-r)/8,s=(n-i)/8;for(let u=0;u<xn.length;u++){let c=xn[u],a=o*c.x.length,f=s*c.y.length;for(let h=0;h<c.x.length;h++)if(c.x[h]<r)a++;else break;for(let h=0;h<c.y.length;h++)if(c.y[h]<i)f++;else break;if(a>0&&f>0)t.push({width:a,height:f,index:u})}return t};Km.getInterlaceIterator=function(e){return function(n,t,r){let i=n%xn[r].x.length,o=(n-i)/xn[r].x.length*8+xn[r].x[i],s=t%xn[r].y.length,u=(t-s)/xn[r].y.length*8+xn[r].y[s];return o*4+u*e*4}}});var Cs=ve((ME,va)=>{va.exports=function(n,t,r){let i=n+t-r,o=Math.abs(i-n),s=Math.abs(i-t),u=Math.abs(i-r);if(o<=s&&o<=u)return n;if(s<=u)return t;return r}});var Js=ve((vE,Na)=>{var Ym=js(),Zm=Cs();function Ia(e,n,t){let r=e*n;if(t!==8)r=Math.ceil(r/(8/t));return r}var Bt=Na.exports=function(e,n){let{width:t,height:r,interlace:i,bpp:o,depth:s}=e;if(this.read=n.read,this.write=n.write,this.complete=n.complete,this._imageIndex=0,this._images=[],i){let u=Ym.getImagePasses(t,r);for(let c=0;c<u.length;c++)this._images.push({byteWidth:Ia(u[c].width,o,s),height:u[c].height,lineIndex:0})}else this._images.push({byteWidth:Ia(t,o,s),height:r,lineIndex:0});if(s===8)this._xComparison=o;else if(s===16)this._xComparison=o*2;else this._xComparison=1};Bt.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Bt.prototype._unFilterType1=function(e,n,t){let r=this._xComparison,i=r-1;for(let o=0;o<t;o++){let s=e[1+o],u=o>i?n[o-r]:0;n[o]=s+u}};Bt.prototype._unFilterType2=function(e,n,t){let r=this._lastLine;for(let i=0;i<t;i++){let o=e[1+i],s=r?r[i]:0;n[i]=o+s}};Bt.prototype._unFilterType3=function(e,n,t){let r=this._xComparison,i=r-1,o=this._lastLine;for(let s=0;s<t;s++){let u=e[1+s],c=o?o[s]:0,a=s>i?n[s-r]:0,f=Math.floor((a+c)/2);n[s]=u+f}};Bt.prototype._unFilterType4=function(e,n,t){let r=this._xComparison,i=r-1,o=this._lastLine;for(let s=0;s<t;s++){let u=e[1+s],c=o?o[s]:0,a=s>i?n[s-r]:0,f=s>i&&o?o[s-r]:0,h=Zm(a,c,f);n[s]=u+h}};Bt.prototype._reverseFilterLine=function(e){let n=e[0],t,r=this._images[this._imageIndex],i=r.byteWidth;if(n===0)t=e.slice(1,i+1);else switch(t=Buffer.alloc(i),n){case 1:this._unFilterType1(e,t,i);break;case 2:this._unFilterType2(e,t,i);break;case 3:this._unFilterType3(e,t,i);break;case 4:this._unFilterType4(e,t,i);break;default:throw Error("Unrecognised filter type - "+n)}if(this.write(t),r.lineIndex++,r.lineIndex>=r.height)this._lastLine=null,this._imageIndex++,r=this._images[this._imageIndex];else this._lastLine=t;if(r)this.read(r.byteWidth+1,this._reverseFilterLine.bind(this));else this._lastLine=null,this.complete()}});var Fa=ve((IE,Ra)=>{var Xm=Ke("util"),Oa=Us(),zm=Js(),Vm=Ra.exports=function(e){Oa.call(this);let n=[],t=this;this._filter=new zm(e,{read:this.read.bind(this),write:function(r){n.push(r)},complete:function(){t.emit("complete",Buffer.concat(n))}}),this._filter.start()};Xm.inherits(Vm,Oa)});var Dt=ve((NE,Pa)=>{Pa.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 Ks=ve((OE,Aa)=>{var _s=[];(function(){for(let e=0;e<256;e++){let n=e;for(let t=0;t<8;t++)if(n&1)n=3988292384^n>>>1;else n=n>>>1;_s[e]=n}})();var Ws=Aa.exports=function(){this._crc=-1};Ws.prototype.write=function(e){for(let n=0;n<e.length;n++)this._crc=_s[(this._crc^e[n])&255]^this._crc>>>8;return!0};Ws.prototype.crc32=function(){return this._crc^-1};Ws.crc32=function(e){let n=-1;for(let t=0;t<e.length;t++)n=_s[(n^e[t])&255]^n>>>8;return n^-1}});var qs=ve((RE,Ha)=>{var Ce=Dt(),Bm=Ks(),_e=Ha.exports=function(e,n){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[Ce.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[Ce.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[Ce.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[Ce.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[Ce.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[Ce.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=n.read,this.error=n.error,this.metadata=n.metadata,this.gamma=n.gamma,this.transColor=n.transColor,this.palette=n.palette,this.parsed=n.parsed,this.inflateData=n.inflateData,this.finished=n.finished,this.simpleTransparency=n.simpleTransparency,this.headersFinished=n.headersFinished||function(){}};_e.prototype.start=function(){this.read(Ce.PNG_SIGNATURE.length,this._parseSignature.bind(this))};_e.prototype._parseSignature=function(e){let n=Ce.PNG_SIGNATURE;for(let t=0;t<n.length;t++)if(e[t]!==n[t]){this.error(Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};_e.prototype._parseChunkBegin=function(e){let n=e.readUInt32BE(0),t=e.readUInt32BE(4),r="";for(let o=4;o<8;o++)r+=String.fromCharCode(e[o]);let i=Boolean(e[4]&32);if(!this._hasIHDR&&t!==Ce.TYPE_IHDR){this.error(Error("Expected IHDR on beggining"));return}if(this._crc=new Bm,this._crc.write(Buffer.from(r)),this._chunks[t])return this._chunks[t](n);if(!i){this.error(Error("Unsupported critical chunk type "+r));return}this.read(n+4,this._skipChunk.bind(this))};_e.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};_e.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};_e.prototype._parseChunkEnd=function(e){let n=e.readInt32BE(0),t=this._crc.crc32();if(this._options.checkCRC&&t!==n){this.error(Error("Crc error - "+n+" - "+t));return}if(!this._hasIEND)this.read(8,this._parseChunkBegin.bind(this))};_e.prototype._handleIHDR=function(e){this.read(e,this._parseIHDR.bind(this))};_e.prototype._parseIHDR=function(e){this._crc.write(e);let n=e.readUInt32BE(0),t=e.readUInt32BE(4),r=e[8],i=e[9],o=e[10],s=e[11],u=e[12];if(r!==8&&r!==4&&r!==2&&r!==1&&r!==16){this.error(Error("Unsupported bit depth "+r));return}if(!(i in Ce.COLORTYPE_TO_BPP_MAP)){this.error(Error("Unsupported color type"));return}if(o!==0){this.error(Error("Unsupported compression method"));return}if(s!==0){this.error(Error("Unsupported filter method"));return}if(u!==0&&u!==1){this.error(Error("Unsupported interlace method"));return}this._colorType=i;let c=Ce.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:n,height:t,depth:r,interlace:Boolean(u),palette:Boolean(i&Ce.COLORTYPE_PALETTE),color:Boolean(i&Ce.COLORTYPE_COLOR),alpha:Boolean(i&Ce.COLORTYPE_ALPHA),bpp:c,colorType:i}),this._handleChunkEnd()};_e.prototype._handlePLTE=function(e){this.read(e,this._parsePLTE.bind(this))};_e.prototype._parsePLTE=function(e){this._crc.write(e);let n=Math.floor(e.length/3);for(let t=0;t<n;t++)this._palette.push([e[t*3],e[t*3+1],e[t*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};_e.prototype._handleTRNS=function(e){this.simpleTransparency(),this.read(e,this._parseTRNS.bind(this))};_e.prototype._parseTRNS=function(e){if(this._crc.write(e),this._colorType===Ce.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 n=0;n<e.length;n++)this._palette[n][3]=e[n];this.palette(this._palette)}if(this._colorType===Ce.COLORTYPE_GRAYSCALE)this.transColor([e.readUInt16BE(0)]);if(this._colorType===Ce.COLORTYPE_COLOR)this.transColor([e.readUInt16BE(0),e.readUInt16BE(2),e.readUInt16BE(4)]);this._handleChunkEnd()};_e.prototype._handleGAMA=function(e){this.read(e,this._parseGAMA.bind(this))};_e.prototype._parseGAMA=function(e){this._crc.write(e),this.gamma(e.readUInt32BE(0)/Ce.GAMMA_DIVISION),this._handleChunkEnd()};_e.prototype._handleIDAT=function(e){if(!this._emittedHeadersFinished)this._emittedHeadersFinished=!0,this.headersFinished();this.read(-e,this._parseIDAT.bind(this,e))};_e.prototype._parseIDAT=function(e,n){if(this._crc.write(n),this._colorType===Ce.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw Error("Expected palette not found");this.inflateData(n);let t=e-n.length;if(t>0)this._handleIDAT(t);else this._handleChunkEnd()};_e.prototype._handleIEND=function(e){this.read(e,this._parseIEND.bind(this))};_e.prototype._parseIEND=function(e){if(this._crc.write(e),this._hasIEND=!0,this._handleChunkEnd(),this.finished)this.finished()}});var Qs=ve((rp)=>{var La=js(),Dm=[function(){},function(e,n,t,r){if(r===n.length)throw Error("Ran out of data");let i=n[r];e[t]=i,e[t+1]=i,e[t+2]=i,e[t+3]=255},function(e,n,t,r){if(r+1>=n.length)throw Error("Ran out of data");let i=n[r];e[t]=i,e[t+1]=i,e[t+2]=i,e[t+3]=n[r+1]},function(e,n,t,r){if(r+2>=n.length)throw Error("Ran out of data");e[t]=n[r],e[t+1]=n[r+1],e[t+2]=n[r+2],e[t+3]=255},function(e,n,t,r){if(r+3>=n.length)throw Error("Ran out of data");e[t]=n[r],e[t+1]=n[r+1],e[t+2]=n[r+2],e[t+3]=n[r+3]}],xm=[function(){},function(e,n,t,r){let i=n[0];e[t]=i,e[t+1]=i,e[t+2]=i,e[t+3]=r},function(e,n,t){let r=n[0];e[t]=r,e[t+1]=r,e[t+2]=r,e[t+3]=n[1]},function(e,n,t,r){e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=r},function(e,n,t){e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3]}];function ep(e,n){let t=[],r=0;function i(){if(r===e.length)throw Error("Ran out of data");let o=e[r];r++;let s,u,c,a,f,h,l,d;switch(n){default:throw Error("unrecognised depth");case 16:l=e[r],r++,t.push((o<<8)+l);break;case 4:l=o&15,d=o>>4,t.push(d,l);break;case 2:f=o&3,h=o>>2&3,l=o>>4&3,d=o>>6&3,t.push(d,l,h,f);break;case 1:s=o&1,u=o>>1&1,c=o>>2&1,a=o>>3&1,f=o>>4&1,h=o>>5&1,l=o>>6&1,d=o>>7&1,t.push(d,l,h,f,a,c,u,s);break}}return{get:function(o){while(t.length<o)i();let s=t.slice(0,o);return t=t.slice(o),s},resetAfterLine:function(){t.length=0},end:function(){if(r!==e.length)throw Error("extra data found")}}}function np(e,n,t,r,i,o){let{width:s,height:u,index:c}=e;for(let a=0;a<u;a++)for(let f=0;f<s;f++){let h=t(f,a,c);Dm[r](n,i,h,o),o+=r}return o}function tp(e,n,t,r,i,o){let{width:s,height:u,index:c}=e;for(let a=0;a<u;a++){for(let f=0;f<s;f++){let h=i.get(r),l=t(f,a,c);xm[r](n,h,l,o)}i.resetAfterLine()}}rp.dataToBitMap=function(e,n){let{width:t,height:r,depth:i,bpp:o,interlace:s}=n,u;if(i!==8)u=ep(e,i);let c;if(i<=8)c=Buffer.alloc(t*r*4);else c=new Uint16Array(t*r*4);let a=Math.pow(2,i)-1,f=0,h,l;if(s)h=La.getImagePasses(t,r),l=La.getInterlaceIterator(t,r);else{let d=0;l=function(){let g=d;return d+=4,g},h=[{width:t,height:r}]}for(let d=0;d<h.length;d++)if(i===8)f=np(h[d],c,l,o,e,f);else tp(h[d],c,l,o,u,a);if(i===8){if(f!==e.length)throw Error("extra data found")}else u.end();return c}});var Ys=ve((PE,Ta)=>{function op(e,n,t,r,i){let o=0;for(let s=0;s<r;s++)for(let u=0;u<t;u++){let c=i[e[o]];if(!c)throw Error("index "+e[o]+" not in palette");for(let a=0;a<4;a++)n[o+a]=c[a];o+=4}}function sp(e,n,t,r,i){let o=0;for(let s=0;s<r;s++)for(let u=0;u<t;u++){let c=!1;if(i.length===1){if(i[0]===e[o])c=!0}else if(i[0]===e[o]&&i[1]===e[o+1]&&i[2]===e[o+2])c=!0;if(c)for(let a=0;a<4;a++)n[o+a]=0;o+=4}}function up(e,n,t,r,i){let o=255,s=Math.pow(2,i)-1,u=0;for(let c=0;c<r;c++)for(let a=0;a<t;a++){for(let f=0;f<4;f++)n[u+f]=Math.floor(e[u+f]*o/s+0.5);u+=4}}Ta.exports=function(e,n,t=!1){let{depth:r,width:i,height:o,colorType:s,transColor:u,palette:c}=n,a=e;if(s===3)op(e,a,i,o,c);else{if(u)sp(e,a,i,o,u);if(r!==8&&!t){if(r===16)a=Buffer.alloc(i*o*4);up(e,a,i,o,r)}}return a}});var ja=ve((AE,Ua)=>{var cp=Ke("util"),Zs=Ke("zlib"),Ga=Us(),ap=Fa(),fp=qs(),hp=Qs(),lp=Ys(),vn=Ua.exports=function(e){Ga.call(this),this._parser=new fp(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()};cp.inherits(vn,Ga);vn.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};vn.prototype._inflateData=function(e){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=Zs.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let t=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,r=Math.max(t,Zs.Z_MIN_CHUNK);this._inflate=Zs.createInflate({chunkSize:r});let i=t,o=this.emit.bind(this,"error");this._inflate.on("error",function(u){if(!i)return;o(u)}),this._filter.on("complete",this._complete.bind(this));let s=this._filter.write.bind(this._filter);this._inflate.on("data",function(u){if(!i)return;if(u.length>i)u=u.slice(0,i);i-=u.length,s(u)}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(e)};vn.prototype._handleMetaData=function(e){this._metaData=e,this._bitmapInfo=Object.create(e),this._filter=new ap(this._bitmapInfo)};vn.prototype._handleTransColor=function(e){this._bitmapInfo.transColor=e};vn.prototype._handlePalette=function(e){this._bitmapInfo.palette=e};vn.prototype._simpleTransparency=function(){this._metaData.alpha=!0};vn.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};vn.prototype._finished=function(){if(this.errord)return;if(!this._inflate)this.emit("error","No Inflate block");else this._inflate.end()};vn.prototype._complete=function(e){if(this.errord)return;let n;try{let t=hp.dataToBitMap(e,this._bitmapInfo);n=lp(t,this._bitmapInfo,this._options.skipRescale),t=null}catch(t){this._handleError(t);return}this.emit("parsed",n)}});var Ja=ve((HE,Ca)=>{var cn=Dt();Ca.exports=function(e,n,t,r){let i=[cn.COLORTYPE_COLOR_ALPHA,cn.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 o=r.bitDepth!==16?e:new Uint16Array(e.buffer),s=255,u=cn.COLORTYPE_TO_BPP_MAP[r.inputColorType];if(u===4&&!r.inputHasAlpha)u=3;let c=cn.COLORTYPE_TO_BPP_MAP[r.colorType];if(r.bitDepth===16)s=65535,c*=2;let a=Buffer.alloc(n*t*c),f=0,h=0,l=r.bgColor||{};if(l.red===void 0)l.red=s;if(l.green===void 0)l.green=s;if(l.blue===void 0)l.blue=s;function d(){let g,m,$,S=s;switch(r.inputColorType){case cn.COLORTYPE_COLOR_ALPHA:S=o[f+3],g=o[f],m=o[f+1],$=o[f+2];break;case cn.COLORTYPE_COLOR:g=o[f],m=o[f+1],$=o[f+2];break;case cn.COLORTYPE_ALPHA:S=o[f+1],g=o[f],m=g,$=g;break;case cn.COLORTYPE_GRAYSCALE:g=o[f],m=g,$=g;break;default:throw Error("input color type:"+r.inputColorType+" is not supported at present")}if(r.inputHasAlpha){if(!i)S/=s,g=Math.min(Math.max(Math.round((1-S)*l.red+S*g),0),s),m=Math.min(Math.max(Math.round((1-S)*l.green+S*m),0),s),$=Math.min(Math.max(Math.round((1-S)*l.blue+S*$),0),s)}return{red:g,green:m,blue:$,alpha:S}}for(let g=0;g<t;g++)for(let m=0;m<n;m++){let $=d(o,f);switch(r.colorType){case cn.COLORTYPE_COLOR_ALPHA:case cn.COLORTYPE_COLOR:if(r.bitDepth===8){if(a[h]=$.red,a[h+1]=$.green,a[h+2]=$.blue,i)a[h+3]=$.alpha}else if(a.writeUInt16BE($.red,h),a.writeUInt16BE($.green,h+2),a.writeUInt16BE($.blue,h+4),i)a.writeUInt16BE($.alpha,h+6);break;case cn.COLORTYPE_ALPHA:case cn.COLORTYPE_GRAYSCALE:{let S=($.red+$.green+$.blue)/3;if(r.bitDepth===8){if(a[h]=S,i)a[h+1]=$.alpha}else if(a.writeUInt16BE(S,h),i)a.writeUInt16BE($.alpha,h+2);break}default:throw Error("unrecognised color Type "+r.colorType)}f+=u,h+=c}return a}});var Ka=ve((LE,Wa)=>{var _a=Cs();function dp(e,n,t,r,i){for(let o=0;o<t;o++)r[i+o]=e[n+o]}function gp(e,n,t){let r=0,i=n+t;for(let o=n;o<i;o++)r+=Math.abs(e[o]);return r}function mp(e,n,t,r,i,o){for(let s=0;s<t;s++){let u=s>=o?e[n+s-o]:0,c=e[n+s]-u;r[i+s]=c}}function pp(e,n,t,r){let i=0;for(let o=0;o<t;o++){let s=o>=r?e[n+o-r]:0,u=e[n+o]-s;i+=Math.abs(u)}return i}function wp(e,n,t,r,i){for(let o=0;o<t;o++){let s=n>0?e[n+o-t]:0,u=e[n+o]-s;r[i+o]=u}}function bp(e,n,t){let r=0,i=n+t;for(let o=n;o<i;o++){let s=n>0?e[o-t]:0,u=e[o]-s;r+=Math.abs(u)}return r}function $p(e,n,t,r,i,o){for(let s=0;s<t;s++){let u=s>=o?e[n+s-o]:0,c=n>0?e[n+s-t]:0,a=e[n+s]-(u+c>>1);r[i+s]=a}}function kp(e,n,t,r){let i=0;for(let o=0;o<t;o++){let s=o>=r?e[n+o-r]:0,u=n>0?e[n+o-t]:0,c=e[n+o]-(s+u>>1);i+=Math.abs(c)}return i}function yp(e,n,t,r,i,o){for(let s=0;s<t;s++){let u=s>=o?e[n+s-o]:0,c=n>0?e[n+s-t]:0,a=n>0&&s>=o?e[n+s-(t+o)]:0,f=e[n+s]-_a(u,c,a);r[i+s]=f}}function Ep(e,n,t,r){let i=0;for(let o=0;o<t;o++){let s=o>=r?e[n+o-r]:0,u=n>0?e[n+o-t]:0,c=n>0&&o>=r?e[n+o-(t+r)]:0,a=e[n+o]-_a(s,u,c);i+=Math.abs(a)}return i}var Sp={0:dp,1:mp,2:wp,3:$p,4:yp},Mp={0:gp,1:pp,2:bp,3:kp,4:Ep};Wa.exports=function(e,n,t,r,i){let o;if(!("filterType"in r)||r.filterType===-1)o=[0,1,2,3,4];else if(typeof r.filterType==="number")o=[r.filterType];else throw Error("unrecognised filter types");if(r.bitDepth===16)i*=2;let s=n*i,u=0,c=0,a=Buffer.alloc((s+1)*t),f=o[0];for(let h=0;h<t;h++){if(o.length>1){let l=1/0;for(let d=0;d<o.length;d++){let g=Mp[o[d]](e,c,s,i);if(g<l)f=o[d],l=g}}a[u]=f,u++,Sp[f](e,c,s,a,u,i),u+=s,c+=s}return a}});var Xs=ve((TE,qa)=>{var Qe=Dt(),vp=Ks(),Ip=Ja(),Np=Ka(),Op=Ke("zlib"),et=qa.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||Op.createDeflate,e.bitDepth=e.bitDepth||8,e.colorType=typeof e.colorType==="number"?e.colorType:Qe.COLORTYPE_COLOR_ALPHA,e.inputColorType=typeof e.inputColorType==="number"?e.inputColorType:Qe.COLORTYPE_COLOR_ALPHA,[Qe.COLORTYPE_GRAYSCALE,Qe.COLORTYPE_COLOR,Qe.COLORTYPE_COLOR_ALPHA,Qe.COLORTYPE_ALPHA].indexOf(e.colorType)===-1)throw Error("option color type:"+e.colorType+" is not supported at present");if([Qe.COLORTYPE_GRAYSCALE,Qe.COLORTYPE_COLOR,Qe.COLORTYPE_COLOR_ALPHA,Qe.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")};et.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};et.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};et.prototype.filterData=function(e,n,t){let r=Ip(e,n,t,this._options),i=Qe.COLORTYPE_TO_BPP_MAP[this._options.colorType];return Np(r,n,t,this._options,i)};et.prototype._packChunk=function(e,n){let t=n?n.length:0,r=Buffer.alloc(t+12);if(r.writeUInt32BE(t,0),r.writeUInt32BE(e,4),n)n.copy(r,8);return r.writeInt32BE(vp.crc32(r.slice(4,r.length-4)),r.length-4),r};et.prototype.packGAMA=function(e){let n=Buffer.alloc(4);return n.writeUInt32BE(Math.floor(e*Qe.GAMMA_DIVISION),0),this._packChunk(Qe.TYPE_gAMA,n)};et.prototype.packIHDR=function(e,n){let t=Buffer.alloc(13);return t.writeUInt32BE(e,0),t.writeUInt32BE(n,4),t[8]=this._options.bitDepth,t[9]=this._options.colorType,t[10]=0,t[11]=0,t[12]=0,this._packChunk(Qe.TYPE_IHDR,t)};et.prototype.packIDAT=function(e){return this._packChunk(Qe.TYPE_IDAT,e)};et.prototype.packIEND=function(){return this._packChunk(Qe.TYPE_IEND,null)}});var Xa=ve((GE,Za)=>{var Rp=Ke("util"),Qa=Ke("stream"),Fp=Dt(),Pp=Xs(),Ya=Za.exports=function(e){Qa.call(this);let n=e||{};this._packer=new Pp(n),this._deflate=this._packer.createDeflate(),this.readable=!0};Rp.inherits(Ya,Qa);Ya.prototype.pack=function(e,n,t,r){if(this.emit("data",Buffer.from(Fp.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(n,t)),r)this.emit("data",this._packer.packGAMA(r));let i=this._packer.filterData(e,n,t);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(o){this.emit("data",this._packer.packIDAT(o))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(i)}});var ef=ve((Kr,xa)=>{var za=Ke("assert").ok,xt=Ke("zlib"),Ap=Ke("util"),Va=Ke("buffer").kMaxLength;function wt(e){if(!(this instanceof wt))return new wt(e);if(e&&e.chunkSize<xt.Z_MIN_CHUNK)e.chunkSize=xt.Z_MIN_CHUNK;if(xt.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 Hp(e){return new wt(e)}function Ba(e,n){if(n)process.nextTick(n);if(!e._handle)return;e._handle.close(),e._handle=null}wt.prototype._processChunk=function(e,n,t){if(typeof t==="function")return xt.Inflate._processChunk.call(this,e,n,t);let r=this,i=e&&e.length,o=this._chunkSize-this._offset,s=this._maxLength,u=0,c=[],a=0,f;this.on("error",function(g){f=g});function h(g,m){if(r._hadError)return;let $=o-m;if(za($>=0,"have should not go down"),$>0){let S=r._buffer.slice(r._offset,r._offset+$);if(r._offset+=$,S.length>s)S=S.slice(0,s);if(c.push(S),a+=S.length,s-=S.length,s===0)return!1}if(m===0||r._offset>=r._chunkSize)o=r._chunkSize,r._offset=0,r._buffer=Buffer.allocUnsafe(r._chunkSize);if(m===0)return u+=i-g,i=g,!0;return!1}za(this._handle,"zlib binding closed");let l;do l=this._handle.writeSync(n,e,u,i,this._buffer,this._offset,o),l=l||this._writeState;while(!this._hadError&&h(l[0],l[1]));if(this._hadError)throw f;if(a>=Va)throw Ba(this),RangeError("Cannot create final Buffer. It would be larger than 0x"+Va.toString(16)+" bytes");let d=Buffer.concat(c,a);return Ba(this),d};Ap.inherits(wt,xt.Inflate);function Lp(e,n){if(typeof n==="string")n=Buffer.from(n);if(!(n instanceof Buffer))throw TypeError("Not a string or buffer");let t=e._finishFlushFlag;if(t==null)t=xt.Z_FINISH;return e._processChunk(n,t)}function Da(e,n){return Lp(new wt(n),e)}xa.exports=Kr=Da;Kr.Inflate=wt;Kr.createInflate=Hp;Kr.inflateSync=Da});var zs=ve((UE,tf)=>{var nf=tf.exports=function(e){this._buffer=e,this._reads=[]};nf.prototype.read=function(e,n){this._reads.push({length:Math.abs(e),allowLess:e<0,func:n})};nf.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 n=this._buffer;this._buffer=n.slice(e.length),e.func.call(this,n.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 rf=ve((Up)=>{var Tp=zs(),Gp=Js();Up.process=function(e,n){let t=[],r=new Tp(e);return new Gp(n,{read:r.read.bind(r),write:function(o){t.push(o)},complete:function(){}}).start(),r.process(),Buffer.concat(t)}});var cf=ve((CE,uf)=>{var of=!0,sf=Ke("zlib"),Cp=ef();if(!sf.deflateSync)of=!1;var Jp=zs(),_p=rf(),Wp=qs(),Kp=Qs(),qp=Ys();uf.exports=function(e,n){if(!of)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let t;function r(M){t=M}let i;function o(M){i=M}function s(M){i.transColor=M}function u(M){i.palette=M}function c(){i.alpha=!0}let a;function f(M){a=M}let h=[];function l(M){h.push(M)}let d=new Jp(e);if(new Wp(n,{read:d.read.bind(d),error:r,metadata:o,gamma:f,palette:u,transColor:s,inflateData:l,simpleTransparency:c}).start(),d.process(),t)throw t;let m=Buffer.concat(h);h.length=0;let $;if(i.interlace)$=sf.inflateSync(m);else{let p=((i.width*i.bpp*i.depth+7>>3)+1)*i.height;$=Cp(m,{chunkSize:p,maxLength:p})}if(m=null,!$||!$.length)throw Error("bad png - invalid inflate data response");let S=_p.process($,i);m=null;let v=Kp.dataToBitMap(S,i);S=null;let k=qp(v,i,n.skipRescale);return i.data=k,i.gamma=a||0,i}});var lf=ve((JE,hf)=>{var af=!0,ff=Ke("zlib");if(!ff.deflateSync)af=!1;var Qp=Dt(),Yp=Xs();hf.exports=function(e,n){if(!af)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let r=new Yp(n||{}),i=[];if(i.push(Buffer.from(Qp.PNG_SIGNATURE)),i.push(r.packIHDR(e.width,e.height)),e.gamma)i.push(r.packGAMA(e.gamma));let o=r.filterData(e.data,e.width,e.height),s=ff.deflateSync(o,r.getDeflateOptions());if(o=null,!s||!s.length)throw Error("bad png - invalid compressed data response");return i.push(r.packIDAT(s)),i.push(r.packIEND()),Buffer.concat(i)}});var df=ve((zp)=>{var Zp=cf(),Xp=lf();zp.read=function(e,n){return Zp(e,n||{})};zp.write=function(e,n){return Xp(e,n)}});var mf=ve((tw)=>{var Dp=Ke("util"),gf=Ke("stream"),xp=ja(),ew=Xa(),nw=df(),Xe=tw.PNG=function(e){if(gf.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 xp(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(n){this.data=n,this.emit("parsed",n)}.bind(this)),this._packer=new ew(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"))};Dp.inherits(Xe,gf);Xe.sync=nw;Xe.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};Xe.prototype.parse=function(e,n){if(n){let t,r;t=function(i){this.removeListener("error",r),this.data=i,n(null,this)}.bind(this),r=function(i){this.removeListener("parsed",t),n(i,null)}.bind(this),this.once("parsed",t),this.once("error",r)}return this.end(e),this};Xe.prototype.write=function(e){return this._parser.write(e),!0};Xe.prototype.end=function(e){this._parser.end(e)};Xe.prototype._metadata=function(e){this.width=e.width,this.height=e.height,this.emit("metadata",e)};Xe.prototype._gamma=function(e){this.gamma=e};Xe.prototype._handleClose=function(){if(!this._parser.writable&&!this._packer.readable)this.emit("close")};Xe.bitblt=function(e,n,t,r,i,o,s,u){if(t|=0,r|=0,i|=0,o|=0,s|=0,u|=0,t>e.width||r>e.height||t+i>e.width||r+o>e.height)throw Error("bitblt reading outside image");if(s>n.width||u>n.height||s+i>n.width||u+o>n.height)throw Error("bitblt writing outside image");for(let c=0;c<o;c++)e.data.copy(n.data,(u+c)*n.width+s<<2,(r+c)*e.width+t<<2,(r+c)*e.width+t+i<<2)};Xe.prototype.bitblt=function(e,n,t,r,i,o,s){return Xe.bitblt(this,e,n,t,r,i,o,s),this};Xe.adjustGamma=function(e){if(e.gamma){for(let n=0;n<e.height;n++)for(let t=0;t<e.width;t++){let r=e.width*n+t<<2;for(let i=0;i<3;i++){let o=e.data[r+i]/255;o=Math.pow(o,0.45454545454545453/e.gamma),e.data[r+i]=Math.round(o*255)}}e.gamma=0}};Xe.prototype.adjustGamma=function(){Xe.adjustGamma(this)}});var Au=ve((EM,$l)=>{var Pu={to(e,n){if(!n)return`\x1B[${e+1}G`;return`\x1B[${n+1};${e+1}H`},move(e,n){let t="";if(e<0)t+=`\x1B[${-e}D`;else if(e>0)t+=`\x1B[${e}C`;if(n<0)t+=`\x1B[${-n}A`;else if(n>0)t+=`\x1B[${n}B`;return t},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"},cb={up:(e=1)=>"\x1B[S".repeat(e),down:(e=1)=>"\x1B[T".repeat(e)},ab={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 n="";for(let t=0;t<e;t++)n+=this.line+(t<e-1?Pu.up():"");if(e)n+=Pu.left;return n}};$l.exports={cursor:Pu,scroll:cb,erase:ab,beep:"\x07"}});import{spawnSync as Gy}from"node:child_process";import{isMainThread as Uy}from"node:worker_threads";import{parseArgs as Py}from"node:util";var qe={name:"@kecan0406/ttheme",version:"1.0.49",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","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{rmSync as rl}from"node:fs";import{basename as Y0,join as yi}from"node:path";var Fm=/^#[0-9a-f]{6}$/;function Zt(e){return Fm.test(e)}function Je(e){let n=Number.parseInt(e.slice(1),16);return[n>>16&255,n>>8&255,n&255]}function Ze(e){let[n,t,r]=Je(e).map((i)=>{let o=i/255;return o<=0.03928?o/12.92:((o+0.055)/1.055)**2.4});return 0.2126*n+0.7152*t+0.0722*r}function De(e,n){let t=Ze(e),r=Ze(n);return(Math.max(t,r)+0.05)/(Math.min(t,r)+0.05)}function Bi(e,n){return Math.round(De(e,n)*100)/100}function Pm(e){let n=e/255;return n<=0.04045?n/12.92:((n+0.055)/1.055)**2.4}function mn(e){let[n,t,r]=Je(e).map(Pm),i=Math.cbrt(0.4122214708*n+0.5363325363*t+0.0514459929*r),o=Math.cbrt(0.2119034982*n+0.6806995451*t+0.1073969566*r),s=Math.cbrt(0.0883024619*n+0.2817188376*t+0.6299787005*r),u=1.9779984951*i-2.428592205*o+0.4505937099*s,c=0.0259040371*i+0.7827717662*o-0.808675766*s;return{l:0.2104542553*i+0.793617785*o-0.0040720468*s,c:Math.hypot(u,c),h:(Math.atan2(c,u)*180/Math.PI+360)%360}}var Vn=7,ra=3,Ns=0.15,ia=1.6,Rs=[1,2,3,4,5,6,9,10,11,12,13,14],oa=[7,15],Xt=[1,2,3,4,5,6],Jr={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}},Fs=0.03,mt=25,no=15,to=0.08;function Un(e,n){let t=e.ansi[n];if(t===void 0)throw Error(`${e.name}: missing ANSI ${n}`);return t}function Os(e,n,t){let r=e.background;return n.flatMap((i)=>{let o=Un(e,i);return De(o,r)<t?[`ANSI ${i} ${o} on ${r} is ${Bi(o,r)}:1, needs ${t}:1`]:[]})}function sa(e,n){return Math.min(...n.map((t)=>De(Un(e,t),e.background)))}var ua=[{rule:"foreground",label:"foreground on background",unit:"ratio",min:Vn,measure:({foreground:e,background:n})=>De(e,n),check:({foreground:e,background:n})=>De(e,n)<Vn?[`foreground ${e} on ${n} is ${Bi(e,n)}:1, needs ${Vn}:1`]:[]},{rule:"accents",label:"weakest accent on background",unit:"ratio",min:ra,measure:(e)=>sa(e,Rs),check:(e)=>Os(e,Rs,ra)},{rule:"ansi0-dark",label:"ansi0 luminance",unit:"luminance",max:Ns,measure:(e)=>Ze(Un(e,0)),check:(e)=>{let n=Un(e,0);return Ze(n)>Ns?[`ANSI 0 ${n} has luminance ${Ze(n).toFixed(3)}, needs <= ${Ns}`]:[]}},{rule:"light-ansi",label:"ansi7 and ansi15 on background",unit:"ratio",min:Vn,measure:(e)=>sa(e,oa),check:(e)=>Os(e,oa,Vn)},{rule:"ansi8-visible",label:"ansi8 on background",unit:"ratio",min:ia,measure:(e)=>De(Un(e,8),e.background),check:(e)=>Os(e,[8],ia)},{rule:"selection",label:"foreground on selection",unit:"ratio",min:Vn,measure:({foreground:e,selectionBackground:n})=>n===void 0?Number.NaN:De(e,n),check:({foreground:e,selectionBackground:n})=>n!==void 0&&De(e,n)<Vn?[`foreground ${e} on selection ${n} is ${Bi(e,n)}:1, needs ${Vn}:1`]:[]}];function Bn(e,n){let t=Math.abs(e-n)%360;return Math.min(t,360-t)}var zt=(e)=>e>8?e-8:e;function ro(e){let n=e.signatureSlots.filter((t)=>t.startsWith("ansi")).map((t)=>Number(t.slice(4)));return new Set(n.flatMap((t)=>Xt.includes(zt(t))?[t,t>8?t-8:t+8]:[t]))}function Cr(e,n){let t=mn(Un(e,n));return t.c<Fs?void 0:t}function Di(e){let n=ro(e);return Rs.flatMap((t)=>{let r=Cr(e,t),i=Jr[zt(t)];if(r===void 0||i===void 0||n.has(t))return[];let o=Bn(r.h,i.center)-i.width;return o>0?[{slot:t,hue:r.h,over:o}]:[]})}function xi(e){let n=new Set(e.signatureSlots);return Xt.flatMap((t)=>{let r=Cr(e,t),i=Cr(e,t+8);if(r===void 0||i===void 0||n.has(`ansi${t}`)&&n.has(`ansi${t+8}`))return[];return[{normal:t,gap:Bn(r.h,i.h)}]})}function eo(e){let n=ro(e);return[0,8].flatMap((t)=>Xt.flatMap((r)=>Xt.filter((i)=>i>r).flatMap((i)=>{let[o,s]=[t+r,t+i],u=Cr(e,o),c=Cr(e,s);if(u===void 0||c===void 0||n.has(o)&&n.has(s))return[];return Bn(u.h,c.h)<no&&Math.abs(u.l-c.l)<to?[[o,s]]:[]})))}var Am=[{rule:"ansi-role",label:"accent hue outside its ANSI role",unit:"degrees",max:0,measure:(e)=>Math.max(0,...Di(e).map((n)=>n.over)),check:(e)=>Di(e).map(({slot:n,hue:t,over:r})=>{let i=Jr[zt(n)];return`ANSI ${n} ${Un(e,n)} has hue ${t.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:mt,measure:(e)=>Math.max(0,...xi(e).map((n)=>n.gap)),check:(e)=>xi(e).filter((n)=>n.gap>mt).map(({normal:n,gap:t})=>`ANSI ${n+8} is ${t.toFixed(0)}° from ANSI ${n}, needs <= ${mt}°`)},{rule:"distinct",label:"accent pairs that read as one color",unit:"pairs",max:0,measure:(e)=>eo(e).length,check:(e)=>eo(e).map(([n,t])=>`ANSI ${n} ${Un(e,n)} and ANSI ${t} ${Un(e,t)} are within ${no}° hue and ${to} lightness`)}],io=[...ua,...Am],Ps=io.map((e)=>e.rule),pt=io.map(({rule:e,label:n,unit:t,min:r,max:i})=>({rule:e,label:n,unit:t,...r===void 0?{}:{min:r},...i===void 0?{}:{max:i}}));function Vt(e){return io.map((n)=>Math.round(n.measure(e)*1000)/1000)}function ca(e,n){return e.filter((t)=>!n.waive.includes(t.rule)).flatMap((t)=>t.check(n).map((r)=>({theme:n.name,rule:t.rule,detail:r})))}function oo(e){return ca(io,e)}function aa(e){return ca(ua,e)}function fa(e){return e.flatMap(oo)}import{readdirSync as Jw,readFileSync as Bf}from"node:fs";import{basename as _w,join as Df}from"node:path";/*!
3
3
  * Copyright (c) Squirrel Chat et al., All rights reserved.
4
4
  * SPDX-License-Identifier: BSD-3-Clause
5
5
  *
@@ -25,11 +25,11 @@ import{createRequire as zg}from"node:module";var _g=Object.create;var{getPrototy
25
25
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26
26
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
27
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
- */function nm(e,n){let t=e.slice(0,n).split(/\r?\n/);return[t.length,t.pop().length+1]}function tm(e,n,t){let r=e.split(/\r?\n/),i="",o=(Math.log10(n+1)|0)+1;for(let s=n-1;s<=n+1;s++){let u=r[s-1];if(!u)continue;if(i+=s.toString().padEnd(o," "),i+=": ",i+=u,i+=`
28
+ */function Hm(e,n){let t=e.slice(0,n).split(/\r?\n/);return[t.length,t.pop().length+1]}function Lm(e,n,t){let r=e.split(/\r?\n/),i="",o=(Math.log10(n+1)|0)+1;for(let s=n-1;s<=n+1;s++){let u=r[s-1];if(!u)continue;if(i+=s.toString().padEnd(o," "),i+=": ",i+=u,i+=`
29
29
  `,s===n)i+=" ".repeat(o+t+2),i+=`^
30
- `}return i}class J extends Error{line;column;codeblock;constructor(e,n){let[t,r]=nm(n.toml,n.ptr),i=tm(n.toml,t,r);super(`Invalid TOML document: ${e}
30
+ `}return i}class j extends Error{line;column;codeblock;constructor(e,n){let[t,r]=Hm(n.toml,n.ptr),i=Lm(n.toml,t,r);super(`Invalid TOML document: ${e}
31
31
 
32
- ${i}`,n);this.line=t,this.column=r,this.codeblock=i}static x(e,n,t){throw new J(e,{toml:n.s,ptr:t??n.p})}}/*!
32
+ ${i}`,n);this.line=t,this.column=r,this.codeblock=i}static x(e,n,t){throw new j(e,{toml:n.s,ptr:t??n.p})}}/*!
33
33
  * Copyright (c) Squirrel Chat et al., All rights reserved.
34
34
  * SPDX-License-Identifier: BSD-3-Clause
35
35
  *
@@ -55,8 +55,8 @@ ${i}`,n);this.line=t,this.column=r,this.codeblock=i}static x(e,n,t){throw new J(
55
55
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
56
56
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
57
57
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
58
- */function zi(e){let n=e.p,t=e.s.charCodeAt(e.p++),r=t,i=t===39,o=t===e.s.charCodeAt(e.p)&&t===e.s.charCodeAt(e.p+1);if(o){if((t=e.s.charCodeAt(e.p+=2))===10)e.p++;else if(t===13&&e.s.charCodeAt(e.p+1)===10)e.p+=2}let s="",u=e.p,c=0;for(;e.p<e.s.length;e.p++)if(t=e.s.charCodeAt(e.p),o&&(t===10||t===13&&e.s.charCodeAt(e.p+1)===10))c=c&&3;else if(t<32&&t!==9||t===127)J.x("control characters are not allowed in strings",e);else if((!c||c===3)&&t===r&&(!o||e.s.charCodeAt(e.p+1)===r&&e.s.charCodeAt(e.p+2)===r)){if(o){if(e.s.charCodeAt(e.p+3)===r)e.p++;if(e.s.charCodeAt(e.p+3)===r)e.p++}if(!c){let a=e.s.slice(u,e.p);s=s?s+a:a}return e.p+=o?3:1,s}else if(!c){if(!i&&t===92)s+=e.s.slice(u,u=e.p),c=1}else if(c===1)if(t===120||t===117||t===85){let a=e.p++-1,h=0,f=t===120?2:t===117?4:8;for(let l=0;l<f;l++,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);h=h<<4|g}if(h<0||h>1114111||h>=55296&&h<=57343)J.x("invalid unicode escape",e,a);s+=String.fromCodePoint(h),u=e.p--,c=0}else if(o&&(t===32||t===9))c=2;else{if(t===98)s+="\b";else if(t===116)s+="\t";else if(t===110)s+=`
59
- `;else if(t===102)s+="\f";else if(t===114)s+="\r";else if(t===101)s+="\x1B";else if(t===34)s+='"';else if(t===92)s+="\\";else J.x("unrecognised escape sequence",e);u=e.p+1,c=0}else if(t!==32&&t!==9){if(c===2)J.x("invalid escape: only line-ending whitespace may be escaped",e,u);c=!i&&t===92?1:0,u=e.p}J.x("unfinished string",e,n)}/*!
58
+ */function so(e){let n=e.p,t=e.s.charCodeAt(e.p++),r=t,i=t===39,o=t===e.s.charCodeAt(e.p)&&t===e.s.charCodeAt(e.p+1);if(o){if((t=e.s.charCodeAt(e.p+=2))===10)e.p++;else if(t===13&&e.s.charCodeAt(e.p+1)===10)e.p+=2}let s="",u=e.p,c=0;for(;e.p<e.s.length;e.p++)if(t=e.s.charCodeAt(e.p),o&&(t===10||t===13&&e.s.charCodeAt(e.p+1)===10))c=c&&3;else if(t<32&&t!==9||t===127)j.x("control characters are not allowed in strings",e);else if((!c||c===3)&&t===r&&(!o||e.s.charCodeAt(e.p+1)===r&&e.s.charCodeAt(e.p+2)===r)){if(o){if(e.s.charCodeAt(e.p+3)===r)e.p++;if(e.s.charCodeAt(e.p+3)===r)e.p++}if(!c){let a=e.s.slice(u,e.p);s=s?s+a:a}return e.p+=o?3:1,s}else if(!c){if(!i&&t===92)s+=e.s.slice(u,u=e.p),c=1}else if(c===1)if(t===120||t===117||t===85){let a=e.p++-1,f=0,h=t===120?2:t===117?4:8;for(let l=0;l<h;l++,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);f=f<<4|g}if(f<0||f>1114111||f>=55296&&f<=57343)j.x("invalid unicode escape",e,a);s+=String.fromCodePoint(f),u=e.p--,c=0}else if(o&&(t===32||t===9))c=2;else{if(t===98)s+="\b";else if(t===116)s+="\t";else if(t===110)s+=`
59
+ `;else if(t===102)s+="\f";else if(t===114)s+="\r";else if(t===101)s+="\x1B";else if(t===34)s+='"';else if(t===92)s+="\\";else j.x("unrecognised escape sequence",e);u=e.p+1,c=0}else if(t!==32&&t!==9){if(c===2)j.x("invalid escape: only line-ending whitespace may be escaped",e,u);c=!i&&t===92?1:0,u=e.p}j.x("unfinished string",e,n)}/*!
60
60
  * Copyright (c) Squirrel Chat et al., All rights reserved.
61
61
  * SPDX-License-Identifier: BSD-3-Clause
62
62
  *
@@ -82,7 +82,7 @@ ${i}`,n);this.line=t,this.column=r,this.codeblock=i}static x(e,n,t){throw new J(
82
82
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
83
83
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
84
84
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
85
- */var rm=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i;class Vn extends Date{#n=!1;#t=!1;#e=null;constructor(e,n,t){let r=!0,i=!0,o="Z",s;if(typeof e==="string")if(n)e:{if(n<3){if(+e.slice(11,13)>23){e="";break e}if(n===2)o=null,e+="Z";else if((s=e.charCodeAt(e.length-1))!==90&&s!==122)o=e.slice(e.length-6);if(t)e=e.slice(0,10)+"T"+e.slice(11)}else if(n===4)e=+e.slice(0,2)>23?"":`0000-01-01T${e}Z`;r=n!==4,i=n!==3}else{let u=e.match(rm);if(u){if(!u[1])r=!1,e=`0000-01-01T${e}`;if(i=!!u[2],i&&e[10]===" "&&(e=e.replace(" ","T")),u[2]&&+u[2]>23)e="";else if(o=u[3]||null,!o&&i)e+="Z"}else e=""}super(e);if(!isNaN(this.getTime()))this.#n=r,this.#t=i,this.#e=o}isDateTime(){return this.#n&&this.#t}isLocal(){return!this.#n||!this.#t||!this.#e}isDate(){return this.#n&&!this.#t}isTime(){return this.#t&&!this.#n}isValid(){return this.#n||this.#t}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 n=+this.#e.slice(1,3)*60+ +this.#e.slice(4,6);return n=this.#e[0]==="-"?n:-n,new Date(this.getTime()-n*60000).toISOString().slice(0,-1)+this.#e}static wrapAsOffsetDateTime(e,n="Z"){let t=new Vn(e);return t.#e=n,t}static wrapAsLocalDateTime(e){let n=new Vn(e);return n.#e=null,n}static wrapAsLocalDate(e){let n=new Vn(e);return n.#t=!1,n.#e=null,n}static wrapAsLocalTime(e){let n=new Vn(e);return n.#n=!1,n.#e=null,n}}/*!
85
+ */var Tm=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i;class Dn extends Date{#n=!1;#t=!1;#e=null;constructor(e,n,t){let r=!0,i=!0,o="Z",s;if(typeof e==="string")if(n)e:{if(n<3){if(+e.slice(11,13)>23){e="";break e}if(n===2)o=null,e+="Z";else if((s=e.charCodeAt(e.length-1))!==90&&s!==122)o=e.slice(e.length-6);if(t)e=e.slice(0,10)+"T"+e.slice(11)}else if(n===4)e=+e.slice(0,2)>23?"":`0000-01-01T${e}Z`;r=n!==4,i=n!==3}else{let u=e.match(Tm);if(u){if(!u[1])r=!1,e=`0000-01-01T${e}`;if(i=!!u[2],i&&e[10]===" "&&(e=e.replace(" ","T")),u[2]&&+u[2]>23)e="";else if(o=u[3]||null,!o&&i)e+="Z"}else e=""}super(e);if(!isNaN(this.getTime()))this.#n=r,this.#t=i,this.#e=o}isDateTime(){return this.#n&&this.#t}isLocal(){return!this.#n||!this.#t||!this.#e}isDate(){return this.#n&&!this.#t}isTime(){return this.#t&&!this.#n}isValid(){return this.#n||this.#t}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 n=+this.#e.slice(1,3)*60+ +this.#e.slice(4,6);return n=this.#e[0]==="-"?n:-n,new Date(this.getTime()-n*60000).toISOString().slice(0,-1)+this.#e}static wrapAsOffsetDateTime(e,n="Z"){let t=new Dn(e);return t.#e=n,t}static wrapAsLocalDateTime(e){let n=new Dn(e);return n.#e=null,n}static wrapAsLocalDate(e){let n=new Dn(e);return n.#t=!1,n.#e=null,n}static wrapAsLocalTime(e){let n=new Dn(e);return n.#n=!1,n.#e=null,n}}/*!
86
86
  * Copyright (c) Squirrel Chat et al., All rights reserved.
87
87
  * SPDX-License-Identifier: BSD-3-Clause
88
88
  *
@@ -108,7 +108,7 @@ ${i}`,n);this.line=t,this.column=r,this.codeblock=i}static x(e,n,t){throw new J(
108
108
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
109
109
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
110
110
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
111
- */function De(e,n=10){return n===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48+n}function ks(e,n){return e===32||e===9||e===10||e===13||n&&(e===n||e===44)||e===35}function Fr(e,n){let t=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?Wc(e):Cc(e);return e.d++,i}if(r===34||r===39)return zi(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,t);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,t);return e.p++,!1}if(r===43||r===45)return Bi(e,e.p,e.s.charCodeAt(++e.p),44-r,n);if(e.s.charCodeAt(e.p+4)===45&&e.s.charCodeAt(e.p+7)===45)return im(e,r,n);if(e.s.charCodeAt(e.p+2)===58)return om(e,r,n);return Bi(e,e.p,r,0,n)}function Bi(e,n,t,r,i){let o=t,s=0,u=!1;if(o===105){if(e.s.charCodeAt(++e.p)!==110||e.s.charCodeAt(++e.p)!==102)J.x("invalid value",e,n);return e.p++,(r||1)/0}if(o===110){if(e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==110)J.x("invalid value",e,n);return e.p++,NaN}if(o===48){if(++e.p>=e.s.length||ks(o=e.s.charCodeAt(e.p),i))return e.bi===!0?0n:0;if(!r){if(o===120)return bs(e,n,16,i);else if(o===98)return bs(e,n,2,i);else if(o===111)return bs(e,n,8,i)}if(o===46)s=2;else if(o===101||o===69)s=4;else J.x("illegal leading zero",e,n)}else if(!De(o))J.x("invalid value",e,n);while(++e.p<e.s.length&&(o=e.s.charCodeAt(e.p),!ks(o,i))){if(!s)s=1;if(o===95){if(!(s&1))J.x("illegal underscore",e);s+=11,u=!0}else if(s===1&&o===46)s=2;else if((s===1||s===3)&&(o===101||o===69))s=4;else if(s===4&&(o===43||o===45));else if(!De(o))J.x("illegal character in numeric literal",e);else if(s>9)s-=11;else if(!(s&1))s++}if(!s){let a=(t-48)*(r||1);return e.bi===!0?BigInt(a):a}if(!(s&1))J.x("unfinished numeric value",e,n);let c=e.s.slice(n,e.p);if(u)c=c.replaceAll("_","");return s>1?parseFloat(c):Jc(e,c,10,n)}function bs(e,n,t,r){let i,o=1;while(++e.p<e.s.length&&(i=e.s.charCodeAt(e.p),!ks(i,r)))if(i===95){if(o&1)J.x("illegal underscore",e);o=3}else if(!De(i,t))J.x("illegal character in numeric literal",e);else if(o&1)o--;if(o&1)J.x("unfinished numeric value",e);let s=e.s.slice(n+2,e.p);if(o)s=s.replaceAll("_","");return Jc(e,s,t,n)}function Jc(e,n,t,r){if(e.bi!==!0)e:{let i=parseInt(n,t);if(!Number.isSafeInteger(i)){if(e.bi)break e;J.x("integer value cannot be represented losslessly",e,r)}return i}return t===10?BigInt(n):BigInt((t===2?"0b":t===8?"0o":"0x")+n)}function im(e,n,t){let r=e.p++,i;if(!De(n)||!De(e.s.charCodeAt(e.p++))||!De(e.s.charCodeAt(e.p++))||!De(e.s.charCodeAt(e.p++)))return Bi(e,e.p=r,n,0,t);if(e.p+=5,!De(e.s.charCodeAt(e.p++)))J.x("invalid date-time: date part is malformed",e,r);if(e.p>=e.s.length||((n=e.s.charCodeAt(e.p))!==32||(i=!0,!De(e.s.charCodeAt(e.p+1))))&&n!==84&&n!==116){let s=e.s.slice(r,e.p);return Rr(e,s,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(De(e.s.charCodeAt(++e.p)));if(n=e.s.charCodeAt(e.p)){if(n===90||n===122){let s=e.s.slice(r,++e.p);return Rr(e,s,1,i,r,"[+00:00]")}if(n===43||n===45){let s=e.s.slice(r,e.p+=6);return Rr(e,s,1,i,r,!e.ld&&"["+e.s.slice(e.p-6,e.p)+"]")}}let o=e.s.slice(r,e.p);return Rr(e,o,2,i,r)}function om(e,n,t){let r=e.p;if(!De(n)||!De(e.s.charCodeAt(++e.p)))return Bi(e,--e.p,n,0,t);if(e.s.charCodeAt(e.p+=4)===58)e.p+=3;if(e.s.charCodeAt(e.p)===46)while(De(e.s.charCodeAt(++e.p)));let i=e.s.slice(r,e.p);return Rr(e,i,4,!1,r)}function Rr(e,n,t,r,i,o){if(e.ld){let s=new Vn(n,t,r);if(!s.isValid())J.x("invalid date",e,i);return s}try{if(o)n+=o;switch(t){case 1:return Temporal.ZonedDateTime.from(n);case 2:return Temporal.PlainDateTime.from(n);case 3:return Temporal.PlainDate.from(n);case 4:return Temporal.PlainTime.from(n)}}catch(s){J.x(s instanceof Error?s.message:""+s,e,i)}}/*!
111
+ */function xe(e,n=10){return n===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48+n}function Hs(e,n){return e===32||e===9||e===10||e===13||n&&(e===n||e===44)||e===35}function Wr(e,n){let t=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?da(e):la(e);return e.d++,i}if(r===34||r===39)return so(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,t);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,t);return e.p++,!1}if(r===43||r===45)return uo(e,e.p,e.s.charCodeAt(++e.p),44-r,n);if(e.s.charCodeAt(e.p+4)===45&&e.s.charCodeAt(e.p+7)===45)return Gm(e,r,n);if(e.s.charCodeAt(e.p+2)===58)return Um(e,r,n);return uo(e,e.p,r,0,n)}function uo(e,n,t,r,i){let o=t,s=0,u=!1;if(o===105){if(e.s.charCodeAt(++e.p)!==110||e.s.charCodeAt(++e.p)!==102)j.x("invalid value",e,n);return e.p++,(r||1)/0}if(o===110){if(e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==110)j.x("invalid value",e,n);return e.p++,NaN}if(o===48){if(++e.p>=e.s.length||Hs(o=e.s.charCodeAt(e.p),i))return e.bi===!0?0n:0;if(!r){if(o===120)return As(e,n,16,i);else if(o===98)return As(e,n,2,i);else if(o===111)return As(e,n,8,i)}if(o===46)s=2;else if(o===101||o===69)s=4;else j.x("illegal leading zero",e,n)}else if(!xe(o))j.x("invalid value",e,n);while(++e.p<e.s.length&&(o=e.s.charCodeAt(e.p),!Hs(o,i))){if(!s)s=1;if(o===95){if(!(s&1))j.x("illegal underscore",e);s+=11,u=!0}else if(s===1&&o===46)s=2;else if((s===1||s===3)&&(o===101||o===69))s=4;else if(s===4&&(o===43||o===45));else if(!xe(o))j.x("illegal character in numeric literal",e);else if(s>9)s-=11;else if(!(s&1))s++}if(!s){let a=(t-48)*(r||1);return e.bi===!0?BigInt(a):a}if(!(s&1))j.x("unfinished numeric value",e,n);let c=e.s.slice(n,e.p);if(u)c=c.replaceAll("_","");return s>1?parseFloat(c):ha(e,c,10,n)}function As(e,n,t,r){let i,o=1;while(++e.p<e.s.length&&(i=e.s.charCodeAt(e.p),!Hs(i,r)))if(i===95){if(o&1)j.x("illegal underscore",e);o=3}else if(!xe(i,t))j.x("illegal character in numeric literal",e);else if(o&1)o--;if(o&1)j.x("unfinished numeric value",e);let s=e.s.slice(n+2,e.p);if(o)s=s.replaceAll("_","");return ha(e,s,t,n)}function ha(e,n,t,r){if(e.bi!==!0)e:{let i=parseInt(n,t);if(!Number.isSafeInteger(i)){if(e.bi)break e;j.x("integer value cannot be represented losslessly",e,r)}return i}return t===10?BigInt(n):BigInt((t===2?"0b":t===8?"0o":"0x")+n)}function Gm(e,n,t){let r=e.p++,i;if(!xe(n)||!xe(e.s.charCodeAt(e.p++))||!xe(e.s.charCodeAt(e.p++))||!xe(e.s.charCodeAt(e.p++)))return uo(e,e.p=r,n,0,t);if(e.p+=5,!xe(e.s.charCodeAt(e.p++)))j.x("invalid date-time: date part is malformed",e,r);if(e.p>=e.s.length||((n=e.s.charCodeAt(e.p))!==32||(i=!0,!xe(e.s.charCodeAt(e.p+1))))&&n!==84&&n!==116){let s=e.s.slice(r,e.p);return _r(e,s,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(xe(e.s.charCodeAt(++e.p)));if(n=e.s.charCodeAt(e.p)){if(n===90||n===122){let s=e.s.slice(r,++e.p);return _r(e,s,1,i,r,"[+00:00]")}if(n===43||n===45){let s=e.s.slice(r,e.p+=6);return _r(e,s,1,i,r,!e.ld&&"["+e.s.slice(e.p-6,e.p)+"]")}}let o=e.s.slice(r,e.p);return _r(e,o,2,i,r)}function Um(e,n,t){let r=e.p;if(!xe(n)||!xe(e.s.charCodeAt(++e.p)))return uo(e,--e.p,n,0,t);if(e.s.charCodeAt(e.p+=4)===58)e.p+=3;if(e.s.charCodeAt(e.p)===46)while(xe(e.s.charCodeAt(++e.p)));let i=e.s.slice(r,e.p);return _r(e,i,4,!1,r)}function _r(e,n,t,r,i,o){if(e.ld){let s=new Dn(n,t,r);if(!s.isValid())j.x("invalid date",e,i);return s}try{if(o)n+=o;switch(t){case 1:return Temporal.ZonedDateTime.from(n);case 2:return Temporal.PlainDateTime.from(n);case 3:return Temporal.PlainDate.from(n);case 4:return Temporal.PlainTime.from(n)}}catch(s){j.x(s instanceof Error?s.message:""+s,e,i)}}/*!
112
112
  * Copyright (c) Squirrel Chat et al., All rights reserved.
113
113
  * SPDX-License-Identifier: BSD-3-Clause
114
114
  *
@@ -134,7 +134,7 @@ ${i}`,n);this.line=t,this.column=r,this.codeblock=i}static x(e,n,t){throw new J(
134
134
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
135
135
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
136
136
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
137
- */function sm(e){for(;e.p<e.s.length;e.p++){let n=e.s.charCodeAt(e.p);if(n===10)break;if(n===13&&e.s.charCodeAt(e.p+1)===10){e.p++;break}if(n<32&&n!==9||n===127)J.x("control characters are not allowed in comments",e)}}function gn(e,n,t){let r;while(e.p<e.s.length){while(e.p<e.s.length&&((r=e.s.charCodeAt(e.p))===32||r===9||!n&&(r===10||r===13&&e.s.charCodeAt(e.p+1)===10)))e.p++;if(t||r!==35)break;sm(e)}}/*!
137
+ */function jm(e){for(;e.p<e.s.length;e.p++){let n=e.s.charCodeAt(e.p);if(n===10)break;if(n===13&&e.s.charCodeAt(e.p+1)===10){e.p++;break}if(n<32&&n!==9||n===127)j.x("control characters are not allowed in comments",e)}}function pn(e,n,t){let r;while(e.p<e.s.length){while(e.p<e.s.length&&((r=e.s.charCodeAt(e.p))===32||r===9||!n&&(r===10||r===13&&e.s.charCodeAt(e.p+1)===10)))e.p++;if(t||r!==35)break;jm(e)}}/*!
138
138
  * Copyright (c) Squirrel Chat et al., All rights reserved.
139
139
  * SPDX-License-Identifier: BSD-3-Clause
140
140
  *
@@ -160,7 +160,7 @@ ${i}`,n);this.line=t,this.column=r,this.codeblock=i}static x(e,n,t){throw new J(
160
160
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
161
161
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
162
162
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
163
- */function Di(e,n=61){let t,r=0,i=[],o,s=e.s.charCodeAt(t=e.p);do if(s===n){if(!r)J.x("unexpected end of key",e);if(r===1)i.push(e.s.slice(o,e.p));return e.p++,i}else if(s===46){if(!r)J.x("illegal empty bare key",e);if(r===1)i.push(e.s.slice(o,e.p));r=0}else if(!r&&(s===34||s===39)){if(s===e.s.charCodeAt(e.p+1)&&s===e.s.charCodeAt(e.p+2))J.x("illegal quoted key: multiline strings are not allowed",e);i.push(zi(e)),r=2,e.p--}else if(s===32||s===9){if(r===1)i.push(e.s.slice(o,e.p)),r=2}else if(r===2||s<48&&s!==45||s>57&&s<65||s>90&&s<97&&s!==95||s>122)J.x("illegal character in key",e);else if(!r)r=1,o=e.p;while(s=e.s.charCodeAt(++e.p));J.x("incomplete key-value: cannot find end of key",e,t)}function Cc(e){let n=e.p++,t=Object.create(null),r=new Set,i;while(e.p<e.s.length){if(gn(e),(i=e.s.charCodeAt(e.p))===125)return e.p++,t;let o,s=t,u=!1,c=e.p,a=Di(e);for(let f=0;f<a.length;f++){if(f)s=u?s[o]:s[o]=Object.create(null);if(o=a[f],(u=Object.hasOwn(s,o))&&(typeof s[o]!=="object"||r.has(s[o])))J.x("trying to redefine an already defined value",e,c);let l=o==="__proto__";if(e.uk&&(l||o==="constructor")){s=e.uk!==1&&J.x("document contains an unsafe property",e,c);break}if(!u&&l)Object.defineProperty(s,o,{enumerable:!0,configurable:!0,writable:!0})}if(u)J.x("trying to redefine an already defined value",e,c);gn(e,!0,!0);let h=Fr(e,125);if(s&&typeof(s[o]=h)==="object")r.add(h);if(gn(e),(i=e.s.charCodeAt(e.p++))===125)return t;if(i!==44)J.x("expected comma or end of structure",e,e.p-1)}J.x("unfinished table",e,n)}function Wc(e){let n=e.p++,t=[],r;while(e.p<e.s.length){if(gn(e),(r=e.s.charCodeAt(e.p))===93)return e.p++,t;if(t.push(Fr(e,93)),gn(e),(r=e.s.charCodeAt(e.p++))===93)return t;if(r!==44)J.x("expected comma or end of structure",e,e.p-1)}J.x("unfinished array",e,n)}/*!
163
+ */function co(e,n=61){let t,r=0,i=[],o,s=e.s.charCodeAt(t=e.p);do if(s===n){if(!r)j.x("unexpected end of key",e);if(r===1)i.push(e.s.slice(o,e.p));return e.p++,i}else if(s===46){if(!r)j.x("illegal empty bare key",e);if(r===1)i.push(e.s.slice(o,e.p));r=0}else if(!r&&(s===34||s===39)){if(s===e.s.charCodeAt(e.p+1)&&s===e.s.charCodeAt(e.p+2))j.x("illegal quoted key: multiline strings are not allowed",e);i.push(so(e)),r=2,e.p--}else if(s===32||s===9){if(r===1)i.push(e.s.slice(o,e.p)),r=2}else if(r===2||s<48&&s!==45||s>57&&s<65||s>90&&s<97&&s!==95||s>122)j.x("illegal character in key",e);else if(!r)r=1,o=e.p;while(s=e.s.charCodeAt(++e.p));j.x("incomplete key-value: cannot find end of key",e,t)}function la(e){let n=e.p++,t=Object.create(null),r=new Set,i;while(e.p<e.s.length){if(pn(e),(i=e.s.charCodeAt(e.p))===125)return e.p++,t;let o,s=t,u=!1,c=e.p,a=co(e);for(let h=0;h<a.length;h++){if(h)s=u?s[o]:s[o]=Object.create(null);if(o=a[h],(u=Object.hasOwn(s,o))&&(typeof s[o]!=="object"||r.has(s[o])))j.x("trying to redefine an already defined value",e,c);let l=o==="__proto__";if(e.uk&&(l||o==="constructor")){s=e.uk!==1&&j.x("document contains an unsafe property",e,c);break}if(!u&&l)Object.defineProperty(s,o,{enumerable:!0,configurable:!0,writable:!0})}if(u)j.x("trying to redefine an already defined value",e,c);pn(e,!0,!0);let f=Wr(e,125);if(s&&typeof(s[o]=f)==="object")r.add(f);if(pn(e),(i=e.s.charCodeAt(e.p++))===125)return t;if(i!==44)j.x("expected comma or end of structure",e,e.p-1)}j.x("unfinished table",e,n)}function da(e){let n=e.p++,t=[],r;while(e.p<e.s.length){if(pn(e),(r=e.s.charCodeAt(e.p))===93)return e.p++,t;if(t.push(Wr(e,93)),pn(e),(r=e.s.charCodeAt(e.p++))===93)return t;if(r!==44)j.x("expected comma or end of structure",e,e.p-1)}j.x("unfinished array",e,n)}/*!
164
164
  * Copyright (c) Squirrel Chat et al., All rights reserved.
165
165
  * SPDX-License-Identifier: BSD-3-Clause
166
166
  *
@@ -186,7 +186,7 @@ ${i}`,n);this.line=t,this.column=r,this.codeblock=i}static x(e,n,t){throw new J(
186
186
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
187
187
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
188
188
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
189
- */function Kc(e,n,t,r,i){let o=t,s=r,u,c=!1,a;for(let h=0;h<n.length;h++){if(h){if(o=c?o[u]:o[u]=Object.create(null),s=(a=s[u]).c,i===0&&(a.t===1||a.t===2))return null;if(a.t===2){let f=o.length-1;o=o[f],s=s[f].c}}if(u=n[h],(c=Object.hasOwn(o,u))&&s[u]?.t===0&&s[u]?.d)return null;if(!c){let f=u==="__proto__";if(e.uk&&(f||u==="constructor"))return!1;if(f)Object.defineProperty(o,u,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(s,u,{enumerable:!0,configurable:!0,writable:!0});s[u]={t:h<n.length-1&&i===2?3:i,d:!1,i:0,c:Object.create(null)}}}if(a=s[u],a.t!==i&&!(i===1&&a.t===3))return null;if(i===2){if(!a.d)a.d=!0,o[u]=[];o[u].push(o=Object.create(null)),a.c[a.i++]=a={t:1,d:!1,i:0,c:Object.create(null)}}if(a.d)return null;if(a.d=!0,i===1)o=c?o[u]:o[u]=Object.create(null);else if(i===0&&c)return null;return[u,o,a.c]}function _c(e,n,t){if(n===null||e.uk===2)J.x(n===null?"trying to redefine an already defined table or value":"document contains an unsafe property",e,t)}function Es(e,n={}){let t={s:e,p:0,d:n.maxDepth??1000,bi:n.integersAsBigInt??!1,ld:n.useLegacyDate??!0,uk:n.unsafeKeyBehaviour==="throw"?2:n.unsafeKeyBehaviour==="drop"?1:0},r=Object.create(null),i=Object.create(null),o,s=!1,u=r,c=i;if(e.charCodeAt(0)===65279)t.p++;gn(t);while(t.p<e.length){if(e.charCodeAt(t.p)===91){let a=e.charCodeAt(++t.p)===91;o=t.p+=+a,s=!1;let h=Di(t,93);if(a){if(e.charCodeAt(t.p)!==93)J.x("expected end of table array declaration",t);t.p++}let f=Kc(t,h,r,i,a?2:1);if(!f)_c(t,f,o),s=!0;else c=f[2],u=f[1]}else{o=t.p;let a=Di(t),h=Kc(t,a,u,c,0);if(!h&&!s)_c(t,h,o);gn(t,!0,!0);let f=Fr(t,void 0);if(h&&!s)h[1][h[0]]=f}if(gn(t,!0),t.p<e.length&&(o=e.charCodeAt(t.p))!==10&&(o!==13||e.charCodeAt(t.p+1)!==10))J.x("each key-value declaration must be followed by an end-of-line",t);gn(t)}return r}/*!
189
+ */function ga(e,n,t,r,i){let o=t,s=r,u,c=!1,a;for(let f=0;f<n.length;f++){if(f){if(o=c?o[u]:o[u]=Object.create(null),s=(a=s[u]).c,i===0&&(a.t===1||a.t===2))return null;if(a.t===2){let h=o.length-1;o=o[h],s=s[h].c}}if(u=n[f],(c=Object.hasOwn(o,u))&&s[u]?.t===0&&s[u]?.d)return null;if(!c){let h=u==="__proto__";if(e.uk&&(h||u==="constructor"))return!1;if(h)Object.defineProperty(o,u,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(s,u,{enumerable:!0,configurable:!0,writable:!0});s[u]={t:f<n.length-1&&i===2?3:i,d:!1,i:0,c:Object.create(null)}}}if(a=s[u],a.t!==i&&!(i===1&&a.t===3))return null;if(i===2){if(!a.d)a.d=!0,o[u]=[];o[u].push(o=Object.create(null)),a.c[a.i++]=a={t:1,d:!1,i:0,c:Object.create(null)}}if(a.d)return null;if(a.d=!0,i===1)o=c?o[u]:o[u]=Object.create(null);else if(i===0&&c)return null;return[u,o,a.c]}function ma(e,n,t){if(n===null||e.uk===2)j.x(n===null?"trying to redefine an already defined table or value":"document contains an unsafe property",e,t)}function Ls(e,n={}){let t={s:e,p:0,d:n.maxDepth??1000,bi:n.integersAsBigInt??!1,ld:n.useLegacyDate??!0,uk:n.unsafeKeyBehaviour==="throw"?2:n.unsafeKeyBehaviour==="drop"?1:0},r=Object.create(null),i=Object.create(null),o,s=!1,u=r,c=i;if(e.charCodeAt(0)===65279)t.p++;pn(t);while(t.p<e.length){if(e.charCodeAt(t.p)===91){let a=e.charCodeAt(++t.p)===91;o=t.p+=+a,s=!1;let f=co(t,93);if(a){if(e.charCodeAt(t.p)!==93)j.x("expected end of table array declaration",t);t.p++}let h=ga(t,f,r,i,a?2:1);if(!h)ma(t,h,o),s=!0;else c=h[2],u=h[1]}else{o=t.p;let a=co(t),f=ga(t,a,u,c,0);if(!f&&!s)ma(t,f,o);pn(t,!0,!0);let h=Wr(t,void 0);if(f&&!s)f[1][f[0]]=h}if(pn(t,!0),t.p<e.length&&(o=e.charCodeAt(t.p))!==10&&(o!==13||e.charCodeAt(t.p+1)!==10))j.x("each key-value declaration must be followed by an end-of-line",t);pn(t)}return r}/*!
190
190
  * Copyright (c) Squirrel Chat et al., All rights reserved.
191
191
  * SPDX-License-Identifier: BSD-3-Clause
192
192
  *
@@ -212,7 +212,7 @@ ${i}`,n);this.line=t,this.column=r,this.codeblock=i}static x(e,n,t){throw new J(
212
212
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
213
213
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
214
214
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
215
- */var lE=!!"".isWellFormed;/*!
215
+ */var hE=!!"".isWellFormed;/*!
216
216
  * Copyright (c) Squirrel Chat et al., All rights reserved.
217
217
  * SPDX-License-Identifier: BSD-3-Clause
218
218
  *
@@ -238,147 +238,150 @@ ${i}`,n);this.line=t,this.column=r,this.codeblock=i}static x(e,n,t){throw new J(
238
238
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
239
239
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
240
240
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
241
- */import{readdirSync as Ip,rmSync as Np,statSync as Op}from"node:fs";import{setDefaultAutoSelectFamilyAttemptTimeout as Rp}from"node:net";import{homedir as Fp}from"node:os";import{join as Gr}from"node:path";import{setTimeout as Pp}from"node:timers/promises";var Qa=Ci(zc(),1),eo=Ci(Ka(),1),_a=[137,80,78,71,13,10,26,10],Ya=13;function Hr(e){return e.length>=_a.length&&_a.every((n,t)=>e[t]===n)}function Us(e){let n=eo.PNG.sync.read(Buffer.from(e));return{width:n.width,height:n.height,data:new Uint8Array(n.data)}}function Lr(e,n){if(Hr(e)){let t=Ar(e);if(t&&t.width*t.height>n)throw Error(`${t.width}×${t.height} is over ${n/1e6} megapixels`);return Us(e)}if(e[0]===255&&e[1]===216){let t=Qa.decode(e,{useTArray:!0,formatAsRGBA:!0,maxResolutionInMP:n/1e6,maxMemoryUsageInMB:1024});return{width:t.width,height:t.height,data:t.data}}throw Error("not a PNG or JPEG image")}function pt(e){let n=new eo.PNG({width:e.width,height:e.height});return n.data=Buffer.from(e.data),eo.PNG.sync.write(n)}function qa(e,n){for(let t=0;t+n.length<=e.length;t++){let r=!0;for(let i=0;i<n.length&&r;i++)r=e[t+i]===n.charCodeAt(i);if(r)return t}return-1}function Ar(e){if(e.length<33||!Hr(e))return null;let n=new DataView(e.buffer,e.byteOffset,e.byteLength),t=n.getUint32(16),r=n.getUint32(20);if(e[25]===4||e[25]===6)return{width:t,height:r,alpha:!0};let i=qa(e,"IDAT");return{width:t,height:r,alpha:qa(i===-1?e:e.subarray(0,i),"tRNS")!==-1}}function Za(e,n=Ya){let{width:t,height:r}=e,i=-1,o=-1;for(let s=0;s<e.height;s++)for(let u=0;u<e.width;u++)if((e.data[(s*e.width+u)*4+3]??0)>=n)t=Math.min(t,u),i=Math.max(i,u),r=Math.min(r,s),o=Math.max(o,s);return i<0?null:{x:t,y:r,w:i-t+1,h:o-r+1}}function Dn(e,n={x:0,y:0,w:e.width,h:e.height}){let t=0;for(let r=n.y;r<n.y+n.h;r++)for(let i=n.x;i<n.x+n.w;i++)if((e.data[(r*e.width+i)*4+3]??0)<Ya)t++;return Math.round(t*100/(n.w*n.h))}function Mp(e,n){if(n<=1)return e;let t=Math.max(1,Math.floor(e.width/n)),r=Math.max(1,Math.floor(e.height/n)),i=new Uint8Array(t*r*4),o=e.data;for(let s=0;s<r;s++)for(let u=0;u<t;u++){let c=0,a=0,h=0,f=0;for(let d=0;d<n;d++)for(let g=0;g<n;g++){let p=((s*n+d)*e.width+u*n+g)*4,k=o[p+3]??0;c+=(o[p]??0)*k,a+=(o[p+1]??0)*k,h+=(o[p+2]??0)*k,f+=k}let l=(s*t+u)*4;if(f>0)i[l]=Math.round(c/f),i[l+1]=Math.round(a/f),i[l+2]=Math.round(h/f);i[l+3]=Math.round(f/(n*n))}return{width:t,height:r,data:i}}function Xa(e,n,t){let r=Math.min(n/e.width,t/e.height),i=Math.max(1,Math.round(e.width*r)),o=Math.max(1,Math.round(e.height*r)),s=no(e,{x:0,y:0,w:e.width,h:e.height},i,o),u=new Uint8Array(n*t*4),c=Math.floor((n-i)/2),a=Math.floor((t-o)/2);for(let h=0;h<o;h++)u.set(s.data.subarray(h*i*4,(h+1)*i*4),((a+h)*n+c)*4);return{width:n,height:t,data:u}}function no(e,n,t,r){let i=Math.max(1,Math.floor(Math.min(n.w/t,n.h/r))),o=Mp(e,i),s=o.data,u=new Uint8Array(t*r*4);for(let c=0;c<r;c++){let a=Math.min(o.height-1,Math.max(0,n.y/i+(c+0.5)*n.h/i/r-0.5)),h=Math.floor(a),f=Math.min(o.height-1,h+1),l=a-h;for(let d=0;d<t;d++){let g=Math.min(o.width-1,Math.max(0,n.x/i+(d+0.5)*n.w/i/t-0.5)),p=Math.floor(g),k=Math.min(o.width-1,p+1),y=g-p,M=(h*o.width+p)*4,b=(h*o.width+k)*4,S=(f*o.width+p)*4,m=(f*o.width+k)*4,P=(s[M+3]??0)*(1-y)*(1-l),E=(s[b+3]??0)*y*(1-l),R=(s[S+3]??0)*(1-y)*l,N=(s[m+3]??0)*y*l,H=P+E+R+N,A=(c*t+d)*4;if(H>0)for(let X=0;X<3;X++){let j=(s[M+X]??0)*P+(s[b+X]??0)*E+(s[S+X]??0)*R+(s[m+X]??0)*N;u[A+X]=Math.round(j/H)}u[A+3]=Math.round(H)}}return{width:t,height:r,data:u}}var wt=100,vn=25000000,Hp=536870912,Ur=["safe","questionable","explicit"],$t=["nudity","underwear"],Lp={nudity:new Set(["nude","naked","topless","bottomless","nipples","naked_towel","undressing"]),underwear:new Set(["underwear","panties","pantsu","bra","lingerie","pantyshot"])},Tr={safe:"s",questionable:"q",explicit:"e"},Ap=8191,Tp=20000,Gp=5000,Va=3000,za=8,Up=3000,eh=60000,Ba=3,Js=`ttheme/${_e.version} (+${_e.homepage})`,jp=["orig","tile","thumb","cut"],nh=new Map,Jp=Vp(process.env.TTHEME_FIND_HOSTS),Cp=Xp(process.env.TTHEME_FIND_CUTOUTS);Rp(Up);function Da(e){try{return Ip(e)}catch{return[]}}function to(e){return e.startsWith("//")?`https:${e}`:e}function jr(e){return(/\.([a-z0-9]+)(?:\?.*)?$/i.exec(e)?.[1]??"").toLowerCase()}function Jr(e){let n=e.trim();if(!n)return[];let t=JSON.parse(n);if(Array.isArray(t))return t;let r=t.posts;return Array.isArray(r)?r:[]}function Wp(e){let n=e.trim(),r=(n?JSON.parse(n):{}).tags??{};return new Map(Object.entries(r).map(([i,o])=>[i,String(o)]))}function js(e,n,t){let r=to(String(e??""));return{file:r,width:Number(n)||0,height:Number(t)||0,ext:jr(r)}}function th(e,n){let t=to(String(n.preview??""));if(!n.file||!t||!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:n.file,preview:t,ext:n.ext,owner:String(n.owner??""),artist:n.artist,score:Number(e.score)||0,rating:String(e.rating??""),md5:String(n.md5??""),source:String(e.source??""),tags:n.tags.split(/\s+/).filter(Boolean),solo:n.solo,family:Number(e.parent_id)||(e.has_children===!0?Number(e.id):0),smaller:n.versions.filter((o)=>o.file&&o.width>0&&o.height>0&&o.width*o.height<r*i)}]}function Kp(e){let n=Wp(e);return Jr(e).flatMap((t)=>{let r=to(String(t.file_url??"")),i=String(t.tags??"");return th(t,{preview:t.preview_url,file:r,ext:String(t.file_ext||jr(r)).toLowerCase(),owner:t.author,artist:i.split(/\s+/).find((o)=>n.get(o)==="artist")??"",md5:t.md5,tags:i,solo:void 0,versions:[js(t.jpeg_url,t.jpeg_width,t.jpeg_height),js(t.sample_url,t.sample_width,t.sample_height)]})})}function _p(e){return Jr(e).flatMap((n)=>{let t=to(String(n.file_url??"")),r=String(n.tag_string??""),i=n.media_asset??{};return th(n,{preview:i.variants?.find((o)=>o.type==="360x360")?.url??n.preview_file_url,file:t,ext:String(n.file_ext||jr(t)).toLowerCase(),owner:"",artist:String(n.tag_string_artist??"").split(/\s+/)[0]??"",md5:n.md5,tags:r,solo:r.split(/\s+/).includes("solo"),versions:(i.variants??[]).map((o)=>js(o.url,o.width,o.height)).filter((o)=>o.ext==="jpg"||o.ext==="png").sort((o,s)=>s.width*s.height-o.width*o.height)})})}function qp(e){return Jr(e).flatMap((n)=>{let t=String(n.value??"");return t?[{value:t,count:Number(n.post_count)||0}]:[]})}function Qp(e){return Jr(e).flatMap((n)=>{let t=String(n.name??"");return t?[{value:t,count:Number(n.count)||0}]:[]})}function Yp(e){return Number(/count="(\d+)"/.exec(e)?.[1]??0)}function Zp(e){let n=e.trim()?JSON.parse(e):{};return Number(n.counts?.posts)||0}function Xp(e){let n=new Map;for(let t of(e??"").split(/\s+/).filter(Boolean)){let r=t.indexOf("=");if(r>0)n.set(t.slice(0,r),t.slice(r+1).split(",").filter(Boolean))}return n}function Vp(e){let n=new Map;for(let t of(e??"").split(/[\s,]+/).filter(Boolean)){let r=t.indexOf("="),i=t.slice(0,r);try{let o=new URL(t.slice(r+1));if(i&&o.protocol==="https:")n.set(i,o.origin)}catch{}}return n}function rh(e,n,t,r){let i=(e??"").split(/\s+/);if(r!==void 0&&i.includes(r))return[];let o=n.filter((s)=>i.includes(s));return o.length>0?o:[...t]}function Xt(e){return rh(e,Ur,["safe"])}function Vt(e){return rh(e,$t,$t,"none")}function ih(e,n,t){return{safe:new Set(e),questionable:new Set(n),explicit:new Set(t)}}function oh(e){let n=Jp.get(e.key),t=Cp.get(e.key);return{...e,origin:n??e.origin,moved:n!==void 0&&n!==e.origin,cutouts:t??e.cutouts,vouched:e.vouched&&t===void 0}}function sh(e){return e.length<2?e.join(""):e.map((n)=>`~${n}`).join(" ")}function xa(e){let n=oh(e),t=(r)=>new URLSearchParams({api_version:"2",include_tags:"1",...r});return{...n,cutouts:sh(n.cutouts),ratings:ih([Tr.safe],[Tr.questionable],[Tr.explicit]),rate:(r)=>{let[i]=r;if(r.length===1&&i)return`rating:${Tr[i]}`;let o=Ur.filter((u)=>!r.includes(u)),[s]=o;return o.length===1&&s?`-rating:${Tr[s]}`:""},best:"order:score",tagBudget:Number.POSITIVE_INFINITY,postsUrl:(r,i)=>`${n.origin}/post.json?${t({limit:String(wt),page:String(i+1),tags:r})}`,countUrl:(r)=>`${n.origin}/post.xml?${new URLSearchParams({limit:"1",tags:r})}`,postUrl:(r)=>`${n.origin}/post.json?${t({tags:`id:${r}`})}`,pageUrl:(r)=>`${n.origin}/post/show/${r}`,parse:Kp,count:Yp}}function zp(e){let n=oh(e),t=ih(["g"],["s","q"],["e"]);return{...n,cutouts:sh(n.cutouts),ratings:t,rate:(r)=>r.length===Ur.length?"":`rating:${r.flatMap((i)=>[...t[i]]).join(",")}`,best:"order:score",tagBudget:2,postsUrl:(r,i)=>`${n.origin}/posts.json?${new URLSearchParams({limit:String(wt),page:String(i+1),tags:r})}`,countUrl:(r)=>`${n.origin}/counts/posts.json?${new URLSearchParams({tags:r})}`,postUrl:(r)=>`${n.origin}/posts.json?${new URLSearchParams({limit:"1",tags:`id:${r}`})}`,pageUrl:(r)=>`${n.origin}/posts/${r}`,parse:_p,count:Zp}}function Bp(e){return x.find((n)=>n.key===e||n.name===e||new URL(n.origin).host===e)}function Cs(e){return e.split(/\s+/).filter((n)=>n&&!n.startsWith("rating:")).length}function ro(e,n){let t=e.trim();if(/^\d+$/.test(t))return{site:n,id:Number(t)};let r=/^([\w.]+):(\d+)$/.exec(t);if(r){let u=x.find((c)=>c.key===r[1]||c.name===r[1]);return u&&{site:u,id:Number(r[2])}}let i;try{i=new URL(t)}catch{return}let o=Bp(i.host),s=Number(i.searchParams.get("id")??i.pathname.split("/").filter(Boolean).at(-1));return o&&s>0?{site:o,id:s}:void 0}var x=[zp({key:"danbooru",name:"danbooru",origin:"https://danbooru.donmai.us",cutouts:["transparent_background"],vouched:!1,tunneled:!0,ansi:2}),xa({key:"konachan",name:"konachan",origin:"https://konachan.net",cutouts:["transparent","vector"],vouched:!1,tunneled:!1,ansi:6}),xa({key:"yande",name:"yande.re",origin:"https://yande.re",cutouts:["transparent_png"],vouched:!0,tunneled:!1,ansi:5})],Un=134217728;function Mn(e,n){let t=x.indexOf(e);return(t===-1?x.length:t)*Un+n}function Ws(e){let n;try{n=new URL(e).hostname}catch{return""}return n.split(".").slice(-2).join(".")}function uh(){return x.filter((e)=>!e.tunneled).map((e)=>Ws(e.origin)).flatMap((e)=>[e,`.${e}`]).join(",")}function io(e,n=$t){return e.tags.filter((t)=>n.some((r)=>Lp[r].has(t)))}function oo(e,n,t=["safe"]){return t.some((r)=>e.ratings[r].has(n.rating))}function bt(e){return[e,...e.smaller].find((n)=>n.width*n.height<=vn)}function ch(e){let n=new Map;for(let[t,r]of[...e].sort(([i],[o])=>i<o?-1:1)){if(r==="")continue;n.set(r,[...n.get(r)??[],t])}return n}function so(){return Gr(process.env.XDG_CACHE_HOME??Gr(Fp(),".cache"),"ttheme")}function pn(e){return Gr(so(),e.key)}function ah(e=Hp,n=so()){let t=[],r=0;for(let i of Da(n))for(let o of jp){let s=Gr(n,i,o);for(let u of Da(s)){let c=Gr(s,u);try{let{size:a,mtimeMs:h}=Op(c);t.push({path:c,size:a,at:h}),r+=a}catch{}}}t.sort((i,o)=>i.at-o.at);for(let i of t){if(r<=e)return;try{Np(i.path,{force:!0}),r-=i.size}catch{}}}function Dp(e,n){if(e!==null&&/^\s*\d+\s*$/.test(e))return Number(e)*1000;let t=e===null?Number.NaN:Date.parse(e);return Number.isNaN(t)?eh:Math.max(0,t-n)}function xn(e){return nh.get(e.key)??0}function xp(e){for(let n=e;n instanceof Error;n=n.cause)if(n.code==="ECONNRESET")return!0;return!1}function ew(e){return(e.headers.get("server")??"").startsWith("cloudflare")&&e.headers.get("cf-mitigated")==="challenge"}async function et(e,n,t,r={},i=Tp){for(let o=1;;o++){let s=xn(e)-Date.now();if(s>0)await Pp(s,void 0,{signal:t});let u;try{u=await fetch(n,{headers:{"User-Agent":Js,Referer:`${e.origin}/`,...r},signal:i?AbortSignal.any([t,AbortSignal.timeout(i)]):t})}catch(c){if(o<Ba&&!t.aborted&&xp(c))continue;throw c}if(u.status===429&&o<Ba){await u.body?.cancel();let c=Dp(u.headers.get("retry-after"),Date.now());if(c>eh)throw Error(`${e.name} asks to wait ${Math.ceil(c/1000)}s`);nh.set(e.key,Math.max(xn(e),Date.now()+c));continue}if(!u.ok)throw await u.body?.cancel(),Error(ew(u)?`${e.name} is behind a Cloudflare challenge`:`${e.name} answered ${u.status}`);return u}}async function hh(e,n,t,r){return e.parse(await(await et(e,e.postsUrl(n,t),r)).text())}async function fh(e,n,t){return e.count(await(await et(e,e.countUrl(n),t)).text())}async function Cr(e,n,t){let[r]=e.parse(await(await et(e,e.postUrl(n),t)).text());return r}function nw(e){let n=x.find((r)=>r.key==="danbooru"),t=new URLSearchParams({limit:String(2*wt),only:"md5,tag_string",tags:`md5:${e.join(",")}`});return`${n.origin}/posts.json?${t}`}function tw(e){return new Map(Jr(e).flatMap((n)=>{let t=String(n.md5??"");return t?[[t,String(n.tag_string??"").split(/\s+/).filter(Boolean)]]:[]}))}function lh(e,n){for(let t of e){let r=n.get(t.md5);if(r)t.tags=[...new Set([...t.tags,...r])],t.solo=r.includes("solo")}}async function dh(e,n){let t=x.find((i)=>i.key==="danbooru"),r=new Map;if(xn(t)>Date.now())return r;for(let i=0;i<e.length;i+=wt){let o=await(await et(t,nw(e.slice(i,i+wt)),n,{},Gp)).text();for(let[s,u]of tw(o))r.set(s,u)}return r}async function gh(e,n){let t=x.find((o)=>o.key==="danbooru");if(xn(t)<=Date.now())try{let o=new URLSearchParams({"search[query]":e,"search[type]":"tag_query",limit:String(za)}),s=`${t.origin}/autocomplete.json?${o}`;return qp(await(await et(t,s,n,{},Va)).text())}catch(o){if(n.aborted)throw o}let r=x.find((o)=>o.key==="yande"),i=new URLSearchParams({name:e,order:"count",limit:String(za)});return Qp(await(await et(r,`${r.origin}/tag.json?${i}`,n,{},Va)).text())}async function mh(e,n,t){let r=await et(e,n,t,{Range:`bytes=0-${Ap}`});return Ar(new Uint8Array(await r.arrayBuffer()))}async function uo(e,n,t,r){let i=await et(e,n,t,{},0),o=Number(i.headers.get("content-length"))||0,s=i.body?.getReader();if(!s)return new Uint8Array(await i.arrayBuffer());let u=[],c=0;for(;;){let{done:f,value:l}=await s.read();if(f)break;u.push(l),c+=l.length,r?.(c,o)}let a=new Uint8Array(c),h=0;for(let f of u)a.set(f,h),h+=f.length;return a}var Et=["top-left","top-center","top-right","center-left","center","center-right","bottom-left","bottom-center","bottom-right"],Wr="Original",ow=1e6,In="_groups.toml",ph=3,wh=8,Ks="[a-z0-9]+(?:-[a-z0-9]+)*",sw=new RegExp(`^(?:(${Ks})@(${Ks})/)?(${Ks})$`),Eh=["background","foreground","cursor","selection"];function ae(e,n){throw Error(`${e}: ${n}`)}function kt(e,n,t){if(typeof t!=="string"||!Wt(t))ae(e,`${n} must be "#rrggbb" (lowercase), got ${JSON.stringify(t)}`);return t}function Kr(e,n,t){if(typeof t!=="string"||t.length===0)ae(e,`${n} must be a non-empty string`);return t}function nt(e){return e.replace("@","--").replace("/","--")}function Te(e){let n=e.indexOf("/");return n<0?void 0:e.slice(0,n)}function ao(e){return e.slice(e.indexOf("/")+1)}function Nn(e){let n=sw.exec(e);if(!n)return"takes lowercase letters, digits and single hyphens, as <palette> or <owner>@<market>/<palette>";if((n[1]?.length??0)>39)return"has an owner longer than a GitHub handle can be";return(n[2]?.length??0)>40||(n[3]?.length??0)>40?"is longer than 40 characters":void 0}function _s(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 co(e,n,t){let r=Kr(e,n,t),i=_s(r);if(i)ae(e,`${n} ${JSON.stringify(r)} ${i}`);return r}function $h(e,n,t){let r=Kr(e,n,t),i=Nn(r);if(i)ae(e,`${n} "${r}" ${i}`);return r}function zt(e){return e&&typeof e==="object"?e:{}}function uw(e,n,t){if(n===void 0)return[t.cursor,t.selectionBackground,t.background];let r=Array.isArray(n)?n:[n];if(r.length===0)ae(e,"ghostty.icon_screen must not be empty");return r.map((i,o)=>kt(e,`ghostty.icon_screen[${o}]`,i))}function cw(e,n,t){let r=zt(n);return{iconGhost:r.icon_ghost===void 0?t.cursor:kt(e,"ghostty.icon_ghost",r.icon_ghost),iconScreen:uw(e,r.icon_screen,t)}}function aw(e){return new Map([...Eh.map((n)=>[n,e[n]]),...e.ansi.map((n,t)=>[`ansi${t}`,n])])}function hw(e,n,t){if(!Array.isArray(n)||n.length!==ph)ae(e,`meta.signature must name exactly ${ph} palette slots`);let r=aw(t),i=[],o=[];for(let[s,u]of n.entries()){let c=`meta.signature[${s}]`,a=Kr(e,c,u),h=r.get(a);if(h===void 0)ae(e,`${c} ${JSON.stringify(u)} is not a palette slot — use ${Eh.join(", ")} or ansi0-ansi15`);i.push(a),o.push(h)}if(new Set(o).size!==o.length)ae(e,"meta.signature slots must resolve to three different colors");return{names:i,colors:o}}function fw(e,n,t){if(n===void 0)return;if(!t)ae(e,"meta.booru_sites renames meta.booru per site, so it needs meta.booru");if(!n||typeof n!=="object"||Array.isArray(n))ae(e,'meta.booru_sites must be a table of site = "tag" or site = ["tag", ...]');let r={};for(let[i,o]of Object.entries(n)){let s=x.find((c)=>c.key===i);if(!s)ae(e,`meta.booru_sites.${i} is not a find site — use ${x.map((c)=>c.key).join(", ")}`);let u=typeof o==="string"?[o]:Array.isArray(o)?o:void 0;if(!u||u.some((c)=>typeof c!=="string"||c===""||/\s/.test(c)))ae(e,`meta.booru_sites.${i} must be one tag or a list of tags, got ${JSON.stringify(o)}`);if(u.length>1&&Number.isFinite(s.tagBudget))ae(e,`meta.booru_sites.${i} takes one tag — ${s.name} searches ${s.tagBudget} tags at a time`);r[i]=u}return r}function lw(e,n){if(n===void 0)return;if(!Array.isArray(n)||n.length===0||n.length>wh)ae(e,`[[picture]] holds 1 to ${wh} pictures`);return n.map((t,r)=>{let i=zt(t),o=`picture[${r}]`,s=x.find((h)=>h.key===i.site);if(!s)ae(e,`${o}.site must be one of ${x.map((h)=>h.key).join(", ")}`);if(typeof i.id!=="number"||!Number.isSafeInteger(i.id)||i.id<=0)ae(e,`${o}.id must be the post's number on ${s.name}`);let{size:u,position:c,opacity:a}=i;if(u!==void 0&&u!=="fill"&&!(Number.isInteger(u)&&Number(u)>=20&&Number(u)<=999))ae(e,`${o}.size must be "fill" or a percentage from 20 to 999`);if(c!==void 0&&!Et.includes(c))ae(e,`${o}.position must be one of ${Et.join(", ")}`);if(a!==void 0&&!(typeof a==="number"&&a>=0&&a<=1))ae(e,`${o}.opacity must be a number from 0 to 1`);return{site:s.key,id:i.id,...u!==void 0?{size:u}:{},...c!==void 0?{position:c}:{},...a!==void 0?{opacity:a}:{}}})}function yh(e,n){try{return Es(n)}catch(t){ae(e,`is not valid TOML — ${(t instanceof Error?t.message:String(t)).split(`
242
- `)[0]}`)}}function dw(e){let t=yh(In,bh(kh(e,In),"utf8")).group;if(!Array.isArray(t)||t.length===0)ae(In,"needs at least one [[group]] table");return t.map((r)=>{let i=zt(r);return{name:co(In,"group.name",i.name),native:i.native===void 0?void 0:co(In,"group.native",i.native),lead:Kr(In,"group.lead",i.lead)}})}function qs(e,n,t){let r=yh(e,n),i=zt(r.meta),o=zt(r.colors),s=zt(r.contrast),u=o.ansi;if(!Array.isArray(u)||u.length!==16)ae(e,`colors.ansi must hold exactly 16 colors, got ${Array.isArray(u)?u.length:typeof u}`);let c=$h(e,"meta.name",i.name);if(c!==t.name)ae(e,`meta.name "${c}" does not match its file — it lives at ${t.name}`);let a=t.open===!0;for(let N of["order","role"])if(a&&i[N]!==void 0)ae(e,`meta.${N} is for the official palettes — a market palette follows its base`);let h=i.role;if(h!==void 0&&h!=="default")ae(e,`meta.role must be "default", got ${JSON.stringify(h)}`);let f=i.base===void 0?void 0:$h(e,"meta.base",i.base);if(f!==void 0&&!a)ae(e,"meta.base is for market palettes");let l=f===void 0?void 0:t.bases?.get(f),d=a&&i.group===void 0?l?.group??Wr:co(e,"meta.group",i.group),g=t.groups.get(d);if(!g&&!(a&&(d===Wr||t.open)))ae(e,`meta.group "${d}" has no [[group]] table in ${In}`);let p=kt(e,"colors.background",o.background),k=kt(e,"colors.foreground",o.foreground),y=kt(e,"colors.cursor",o.cursor),M=kt(e,"colors.selection_background",o.selection_background),b=u.map((N,H)=>kt(e,`colors.ansi[${H}]`,N)),S=hw(e,i.signature,{background:p,foreground:k,cursor:y,selection:M,ansi:b}),m=i.booru===void 0?void 0:Kr(e,"meta.booru",i.booru);if(m!==void 0&&/[\s\p{Cc}]/u.test(m))ae(e,`meta.booru must be a single booru tag, got ${JSON.stringify(m)}`);let P=fw(e,i.booru_sites,m),E=Array.isArray(s.waive)?s.waive.map(String):[];if(E.length>0&&typeof s.reason!=="string")ae(e,"contrast.waive needs a contrast.reason explaining why");let R=lw(e,r.picture);return{name:c,...f?{base:f}:{},group:d,native:g?.native,lead:!a&&g?.lead===c,order:a?l?.order??ow:Number(i.order),role:h,ansiSource:a&&i.ansi_source===void 0?f??"original":co(e,"meta.ansi_source",i.ansi_source),...m?{booru:m}:{},...P?{booruSites:P}:{},background:p,foreground:k,cursor:y,selectionBackground:M,ansi:b,signature:S.colors,signatureSlots:S.names,ghostty:cw(e,r.ghostty,{background:p,cursor:y,selectionBackground:M}),waive:E,waiveReason:typeof s.reason==="string"?s.reason:void 0,...R?{pictures:R}:{}}}function Sh(e){let n=dw(e),t=new Map(n.map((o)=>[o.name,o]));if(t.size!==n.length)ae(In,"group.name must be unique");let r=rw(e).filter((o)=>o.endsWith(".toml")&&!o.startsWith("_")).map((o)=>qs(o,bh(kh(e,o),"utf8"),{name:iw(o,".toml"),groups:t})).sort((o,s)=>o.order-s.order);if(new Set(r.map((o)=>o.order)).size!==r.length)throw Error("themes: meta.order must be unique across all themes");for(let o of n){let s=r.filter((u)=>u.group===o.name);if(s.length===0)ae(In,`group "${o.name}" has no themes`);if(!s.some((u)=>u.name===o.lead))ae(In,`group "${o.name}" lead "${o.lead}" is not one of its themes`)}return r}function vh(e){return e.filter((n)=>n.role===void 0)}function _r(e){let n=(r,i)=>r<i?-1:r>i?1:0,t=(r)=>Te(r.name)?r.name:r.base??r.name;return[...e].sort((r,i)=>Number(Te(r.name)!==void 0)-Number(Te(i.name)!==void 0)||n(r.group.toLowerCase(),i.group.toLowerCase())||n(t(r),t(i))||Number(r.base!==void 0)-Number(i.base!==void 0)||n(r.name,i.name))}var gw=["black","red","green","yellow","blue","magenta","cyan","white"];function Mh(e,n){return[e,...gw.map((t,r)=>`${t} = '${n[r]}'`),""].join(`
243
- `)}var qr={id:"alacritty",limits:"no runtime color API (OSC only)",emit(e){let n=[...Bt(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}'`,"",Mh("[colors.normal]",e.ansi.slice(0,8)),Mh("[colors.bright]",e.ansi.slice(8,16))].join(`
244
- `);return[{path:`alacritty/themes/${fe(e.name)}.toml`,content:n}]}};var Qr={id:"ghostty",emit(e){let n=[...Bt(e),`background = ${e.background}`,`foreground = ${e.foreground}`,`cursor-color = ${e.cursor}`,`selection-background = ${e.selectionBackground}`,`selection-foreground = ${e.foreground}`,...e.ansi.map((t,r)=>`palette = ${r}=${t}`),"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(`
245
- `);return[{path:`ghostty/themes/${fe(e.name)}`,content:n}]}};function tt(e){let[n,t,r]=We(e);return{"Alpha Component":1,"Blue Component":r/255,"Color Space":"P3","Green Component":t/255,"Red Component":n/255}}function Ih(e){return{...Object.fromEntries(e.ansi.map((n,t)=>[`Ansi ${t} Color`,tt(n)])),"Background Color":tt(e.background),"Bold Color":tt(e.foreground),"Cursor Color":tt(e.cursor),"Cursor Text Color":tt(e.background),"Foreground Color":tt(e.foreground),"Selected Text Color":tt(e.foreground),"Selection Color":tt(e.selectionBackground)}}function mw(e){return e?{"Background Image Location":e.image,"Background Image Mode":e.cover?2:3,Blend:e.opacity}:{"Background Image Location":""}}function Nh(e,n,t,r){let i=(s,u)=>({Name:`ttheme · ${u}`,Guid:fe(u),...r?{"Dynamic Profile Parent GUID":r}:{},"Use Separate Colors for Light and Dark Mode":!1,"Harmonize 256 Colors":!0,...mw(n.get(s.name)),...Ih(s)}),o=[...t?[i(t,"default")]:[],...e.map((s)=>i(s,s.name))];return`${JSON.stringify({Profiles:o},null,2)}
246
- `}function pw(e,n){return[` <key>${e}</key>`,"\t<dict>",...Object.entries(n).flatMap(([t,r])=>[` <key>${t}</key>`,typeof r==="string"?` <string>${r}</string>`:` <real>${r}</real>`]),"\t</dict>"].join(`
247
- `)}var Yr={id:"iterm2",limits:"colors are Display P3, the space iTerm2 reads OSC colors in",emit(e){let n=['<?xml version="1.0" encoding="UTF-8"?>','<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">','<plist version="1.0">',"<dict>",...Object.entries(Ih(e)).map(([t,r])=>pw(t,r)),"</dict>","</plist>",""].join(`
248
- `);return[{path:`iterm2/${fe(e.name)}.itermcolors`,content:n}]}};var Zr={id:"kitty",emit(e){let n=[...Bt(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((t,r)=>`color${r} ${t}`),""].join(`
249
- `);return[{path:`kitty/themes/${fe(e.name)}.conf`,content:n}]}};function Oh(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(`
250
- `)}import{createHash as Iw}from"node:crypto";import{existsSync as Uh,mkdirSync as Nw,readdirSync as Ow,readFileSync as jh,renameSync as Jh,rmSync as xt}from"node:fs";import{basename as Ch,isAbsolute as Rw,join as oe}from"node:path";import{chmodSync as ww,copyFileSync as $w,existsSync as Dt,mkdirSync as bw,readFileSync as Qs,realpathSync as kw,renameSync as Ew,rmSync as Rh,statSync as yw,writeFileSync as Sw}from"node:fs";import{dirname as vw}from"node:path";function Fh(e){return`${e}.ttheme.bak`}var Mw=/^(?:#|--) ttheme begin$|path = "ttheme-/m;function Ys(e){let n=Fh(e);if(Dt(e)&&!Dt(n)&&!Mw.test(Qs(e,"utf8")))$w(e,n)}function $e(e,n){let t=Dt(e)?kw(e):e;bw(vw(t),{recursive:!0});let r=`${t}.ttheme-${process.pid}`;if(Sw(r,n),Dt(t))ww(r,yw(t).mode&4095);Ew(r,t)}function Xr(e,n){if((Dt(e)?Qs(e,"utf8"):void 0)===n)return!1;return Ys(e),$e(e,n),!0}function Ph(e,n){let t=Fh(e),r=Dt(t)?Qs(t,"utf8"):void 0;if(n===""&&r===void 0)return Rh(e,{force:!0}),"removed";if($e(e,n),r===void 0||r===n)return Rh(t,{force:!0}),"restored";return"kept backup"}var Zs={width:2560,height:1550},Fw=2560,Pw=0.1,jn={tall:1.15,reach:0.4,widest:0.95,headroom:0.04,margin:0.03,stands:12},Hw=Qe(Vs("#19161e","#9b86c8",0.2)),Lw="shelf",ho="originals",Aw="images.json",Xs=1;function Vs(e,n,t){let r=We(e),i=We(n);return`#${r.map((o,s)=>Math.round(o+((i[s]??0)-o)*t).toString(16).padStart(2,"0")).join("")}`}function Tw(e,n){if(n==="background"||n==="foreground"||n==="cursor")return e[n];if(n==="selection"&&e.selection)return e.selection;let t=/^ansi(\d|1[0-5])$/.exec(n),r=t?e.ansi[Number(t[1])]:void 0;if(!r)throw Error(`${e.name} has no slot ${n}`);return r}function Hh(e){if(e(1))return 1;let n=0,t=1;for(let r=0;r<40;r++){let i=(n+t)/2;if(e(i))n=i;else t=i}return n}function Lh(e,n){let t=Tw(e,n),i=Hh((a)=>Uc({name:e.name,background:Vs(e.background,t,a),foreground:e.foreground,ansi:e.ansi,waive:e.waived??[]}).length===0),o=Hh((a)=>Qe(Vs(e.background,t,a))<=Hw),s=Math.floor(Math.min(i,o)*1000)/1000,u=We(e.background),c=Math.hypot(...We(t).map((a,h)=>(a-(u[h]??0))*s));return{slot:n,color:t,cap:i,matched:o,opacity:s,reach:c}}function er(e,n){let t=Lh(e,"cursor");if(t.opacity>=Pw)return t;return n.filter((r)=>r!=="cursor"&&r!=="background").map((r)=>Lh(e,r)).reduce((r,i)=>i.reach>r.reach?i:r,t)}function zs(e,n,t){let r=We(n),i=We(t),o=e.data;for(let s=0;s<o.length;s+=4){let u=(0.299*(o[s]??0)+0.587*(o[s+1]??0)+0.114*(o[s+2]??0))/255;for(let c=0;c<3;c++)o[s+c]=Math.round((r[c]??0)+((i[c]??0)-(r[c]??0))*u)}return e}function Gw(e,n,t){let r=We(n),i=e.data,o=new Uint8Array(i.length);for(let s=0;s<i.length;s+=4){let u=(i[s+3]??0)/255*t;for(let c=0;c<3;c++)o[s+c]=Math.round((r[c]??0)*(1-u)+(i[s+c]??0)*u);o[s+3]=255}return{width:e.width,height:e.height,data:o}}function Wh(e){return Za(e)??{x:0,y:0,w:e.width,h:e.height}}function Uw(e,n){if(e<=0||n<=0)return Zs;let t=Math.min(1,Zs.width/Math.max(e,n));return{width:Math.round(e*t),height:Math.round(n*t)}}function jw(e,n){let t=Math.min(1,Fw/Math.max(n.w,n.h));return no(e,n,Math.round(n.w*t),Math.round(n.h*t))}function Kh(e,n,t,r){if(r<jn.stands){let c=e.w*t>e.h*n?{x:e.x+(e.w-e.h*n/t)/2,y:e.y,w:e.h*n/t,h:e.h}:{x:e.x,y:e.y,w:e.w,h:e.w*t/n};return{crop:c,at:{x:0,y:0,w:n,h:t},focus:(c.y-e.y+c.h/2)/e.h}}let i=Math.max(jn.tall*t,jn.reach*n*e.h/e.w),o=i*e.w/e.h;if(o>jn.widest*n)o=jn.widest*n,i=o*e.h/e.w;let s=jn.headroom*t,u=Math.min(1,(t-s)/i);return{crop:{x:e.x,y:e.y,w:e.w,h:e.h*u},at:{x:n*(1-jn.margin)-o,y:s,w:o,h:i*u},focus:Math.min(1,(t/2-s)/i)}}function xs(e,n,t,r){let i=Math.max(1,Math.round(n.at.w)),o=Math.max(1,Math.round(n.at.h)),s=no(e,n.crop,i,o),u=new Uint8Array(t*r*4),c=Math.round(n.at.x),a=Math.round(n.at.y);for(let h=0;h<o;h++){let f=a+h,l=Math.max(0,-c),d=Math.min(i,t-c);if(f<0||f>=r||d<=l)continue;u.set(s.data.subarray((h*i+l)*4,(h*i+d)*4),(f*t+c+l)*4)}return{width:t,height:r,data:u}}function _h(e,n,t,r,i){let o=Wh(e),s=xs(e,Kh(o,r,i,Dn(e,o)),r,i);return Gw(zs(s,n.background,t.color),n.background,t.opacity)}function Ze(e){return oe(e,"ttheme","backgrounds")}function Bs(e){return oe(e,Aw)}function Vr(e){try{return jh(e,"utf8")}catch{return}}function rt(e){try{return Ow(e)}catch{return[]}}function On(e){let n=Vr(Bs(e));if(n===void 0)return Cw(e);let t=JSON.parse(n);if(t.version!==Xs)throw Error(`${Bs(e)} is version ${t.version} — this ttheme reads version ${Xs}`);return t}function Jw(e,n){let t=n.pictures.findIndex((i)=>i.key===n.active),r=n.pictures[t];return[...r.from?[`# from ${r.from}`]:[],`# image ${r.key} ${t+1}/${n.pictures.length}`,`background-image = ${oe(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(`
251
- `)}function zr(e,n,t){$e(Bs(e),`${JSON.stringify(n,null,2)}
252
- `);for(let r of t){let i=n.palettes[r],o=oe(e,`${nt(r)}.conf`);if(i)$e(o,Jw(e,i));else xt(o,{force:!0})}}function qh(e,n){for(let t of rt(e))if(t.startsWith(`${n.stem}.`)||t.startsWith(`${n.stem}@`))xt(oe(e,t),{force:!0});if(n.original)xt(oe(e,n.original),{force:!0})}function Ah(e,n,t,r){let i=Ch(/^background-image\s*=\s*(.*?)\s*$/m.exec(n??"")?.[1]??"");if(!i.startsWith(`${e}.`)||!/^\.[0-9a-f]{8}@fill-\d+\.png$/.test(i.slice(e.length)))return;let o=i.slice(0,i.indexOf("@")),s=r??/^# image (\S+)$/m.exec(n??"")?.[1]??`picture_${o.slice(e.length+1)}`,u=/^# from (.+)$/m.exec(n??"")?.[1],c=Number(/^background-image-opacity\s*=\s*(\S+)/m.exec(n??"")?.[1]??1),a=t.find((h)=>h.startsWith(`${e}-${s}.`));return{key:s,stem:o,fill:i,opacity:Number.isFinite(c)?c:1,...u?{from:u}:{},...a?{original:oe(ho,a)}:{}}}function Th(e,n){if(Uh(e))Jh(e,n)}function Cw(e){let n={version:Xs,palettes:{}};if(!Uh(e))return n;let t=rt(oe(e,ho)),r=rt(e).filter((o)=>o.endsWith(".conf")&&o!=="shown.conf"&&!/\.(tune|off)\.conf$/.test(o)).map((o)=>o.slice(0,-5)),i=oe(e,Lw);for(let o of new Set([...r,...rt(i)])){let s=[],u=Ah(o,Vr(oe(e,`${o}.conf`)),t);if(u)Th(oe(e,`${o}.tune.conf`),oe(e,`${u.stem}.tune.conf`)),Th(oe(e,`${o}.off.conf`),oe(e,`${u.stem}.off.conf`)),s.push(u);for(let c of rt(oe(i,o))){let a=oe(i,o,c),h=Ah(o,Vr(oe(a,".conf")),t,c);if(!h)continue;for(let f of rt(a)){let l=f===".tune.conf"||f===".off.conf"?`${h.stem}${f}`:`${o}${f}`;if(f!==".conf")Jh(oe(a,f),oe(e,l))}xt(a,{recursive:!0}),s.push(h)}if(rt(oe(i,o)).length===0)xt(oe(i,o),{recursive:!0,force:!0});if(s.length>0)s.sort((c,a)=>c.key<a.key?-1:c.key>a.key?1:0),n.palettes[o]={active:(u??s[0]).key,pictures:s}}if(rt(i).length===0)xt(i,{recursive:!0,force:!0});return zr(e,n,Object.keys(n.palettes)),n}function Gh(e,n,t){return n.startsWith("~/")?oe(t,n.slice(2)):Rw(n)?n:oe(e,n)}function Qh(e,n,t){let r=new Map,i=(u,c)=>{let a=Vr(u);if(a===void 0)return!1;for(let h of a.split(`
253
- `)){let f=/^([a-z-]+)\s*=\s*(.*?)\s*$/.exec(h);if(f?.[1]==="config-file"&&c<4)i(Gh(e,f[2].replace(/^\?/,""),t),c+1);else if(f&&/^background-image(?:-fit|-opacity)?$/.test(f[1]))r.set(f[1],f[2])}return!0};if(!i(oe(e,`${nt(n)}.conf`),0))return;let o=r.get("background-image")??"";if(o==="")return;let s=Number(r.get("background-image-opacity")??1);return{image:Gh(e,o,t),opacity:Number.isFinite(s)?s:1,cover:r.get("background-image-fit")==="cover"}}function yt(e){return`${e.site}_${e.id}`}function Yh(e,n,t){let r=Ze(e),i=On(r),o=i.palettes[n];if(!o||o.pictures.length<2)throw Error(`${n} has no other image`);let s=o.pictures.length,u=(o.pictures.findIndex((c)=>c.key===o.active)+t+s)%s;return o.active=o.pictures[u].key,zr(r,i,[n]),{key:o.active,at:u+1,of:s}}function Zh(e,n){let t=Ze(e),r=On(t),i=r.palettes[n];if(!i)throw Error(`${n} has no image`);let o=i.pictures.findIndex((c)=>c.key===i.active),[s]=i.pictures.splice(o,1);qh(t,s);let u=i.pictures[o%Math.max(i.pictures.length,1)];if(u)i.active=u.key;else delete r.palettes[n];return zr(t,r,[n]),{key:s.key,left:i.pictures.length}}function fo(e,n,t,r,i,o){let s=Ze(e),u=n.name,c=yt(i),a=On(s),h=a.palettes[u]??{active:c,pictures:[]},f=Wh(r),{width:l,height:d}=Uw(o.width,o.height),g=Kh(f,l,d,Dn(r,f)),p=pt(zs(jw(r,f),n.background,t.color)),k=pt(zs(xs(r,g,l,d),n.background,t.color)),y=`${nt(u)}.${Iw("sha1").update(p).update(k).digest("hex").slice(0,8)}`,M={key:c,stem:y,fill:`${y}@fill-${Math.round(g.focus*100)}.png`,opacity:t.opacity,...i.from?{from:i.from}:{},original:oe(ho,`${nt(u)}-${c}.${i.ext}`)},b=h.pictures.find((m)=>m.key===c);if(b)qh(s,b);let S=[oe(s,`${y}.png`),oe(s,M.fill),oe(s,M.original)];return Nw(oe(s,ho),{recursive:!0}),$e(S[0],p),$e(S[1],k),$e(S[2],i.bytes),h.pictures=b?h.pictures.map((m)=>m===b?M:m):[...h.pictures,M],h.active=c,a.palettes[u]=h,zr(s,a,[u]),[...S,oe(s,`${nt(u)}.conf`)]}function Xh(e,n,t){let r=Ze(e),i=On(r),o=i.palettes[n];if(o?.pictures.some((s)=>s.key===t)&&o.active!==t)o.active=t,zr(r,i,[n])}function Br(e,n){let t=On(Ze(e)).palettes[n];if(!t)return[];return[...t.pictures.filter((i)=>i.key===t.active),...t.pictures.filter((i)=>i.key!==t.active)]}var Ds="top-right";function Ww(e,n,t,r,i,o,s,u=-1){let c=Math.trunc,a=(o-1)%3,h=c((o-1)/3),f=t*n>=r*e!==!s,l=f?c(i*t/100):c(i*r*e/(100*n)),d=f?c(i*t*n/(100*e)):c(i*r/100),g=c(a*(t-l)/2),p=c(h*(r-d)/2);if(u>=0){if(l>t)g=c((t-l)/2);if(d>r)p=Math.max(r-d,Math.min(0,c(r/2)-c(u*d/100)))}return{x:g,y:p,w:l,h:d}}function Vh(e,n){let t=Vr(oe(e,`${n.stem}.tune.conf`));if(t===void 0)return{};let r=(a)=>new RegExp(`^${a}\\s*=\\s*(.*?)\\s*$`,"m").exec(t)?.[1]??"",i=Ch(r("background-image")),o=/@(\d+)-/.exec(i)?.[1],s=/@fill-\d+\.png$/.test(i)?"fill":o?Number(o):r("background-image-fit")==="cover"?"fill":100,u=r("background-image-position").replace("center-center","center")||"center",c=Number(r("background-image-opacity")||1);return{...s!=="fill"?{size:s}:{},...u!==Ds?{position:u}:{},...Number.isFinite(c)&&c!==n.opacity?{opacity:c}:{}}}function zh(e,n,t,r,i){let o=t.size??"fill",s=t.position??Ds,u=t.opacity??n.opacity;if(o==="fill"&&s===Ds&&u===n.opacity)return;let c=Et.indexOf(s)+1,a=oe(e,`${n.stem}.png`),h=oe(e,n.fill),f=!0,l=typeof o==="number"&&(o>100||!r&&s!=="center");if(o===100&&!l)h=a,f=!1;else if(typeof o==="number"){let g=Us(new Uint8Array(jh(a))),{width:p,height:k}=l?Zs:g,y=l?Number(/@fill-(\d+)\.png$/.exec(n.fill)?.[1]??50):-1,M=Ww(g.width,g.height,p,k,o,c,!1,y);h=oe(e,`${n.stem}@${o}-${s}${l?`-${p}x${k}`:""}.png`);let b=xs(g,{crop:{x:0,y:0,w:g.width,h:g.height},at:M,focus:y},p,k);$e(h,pt(b)),f=l}let d=oe(e,`${n.stem}.tune.conf`);return $e(d,[`background-image = ${h.startsWith(`${i}/`)?`~${h.slice(i.length)}`:h}`,`background-image-fit = ${f?"cover":"contain"}`,`background-image-position = ${s}`,`background-image-opacity = ${u}`,""].join(`
254
- `)),d}function Bh(e){let n=new Map;for(let[t,r]of Object.entries(On(Ze(e)).palettes)){let[,i,o]=/^([a-z.]+)_(\d+)$/.exec(r.active)??[];if(i&&o)n.set(t,{site:i,id:Number(o)})}return n}function wn(e){let{slot:n,color:t,opacity:r}=er({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:qt(e),...e.waive.length>0?{waived:e.waive}:{},backdrop:{slot:n,color:t,opacity:r},...e.pictures?{pictures:e.pictures}:{}}}function cn(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 Kw=6,_w=["ansi1","ansi2","ansi4","ansi3","ansi5","ansi6"];function lo(e){let n=(o)=>o.startsWith("ansi")?e.ansi[Number(o.slice(4))]:o==="foreground"?e.foreground:o==="cursor"?e.cursor:o==="selection"?e.selection:void 0,t=(o)=>o.startsWith("ansi")?`ansi${Number(o.slice(4))%8}`:o,r=new Set,i=[];for(let o of["foreground",...e.signatureSlots,..._w]){let s=n(o);if(i.length===Kw||!s||r.has(t(o))||i.includes(s))continue;r.add(t(o)),i.push(s)}return i}function an(e){return e.filter((n)=>n.default!==!0)}function Dr(){return{version:_e.version,gate:gt,placement:jn,palettes:[]}}function qw(e){let[n]=e;if(!n)throw Error("manifest needs at least one theme");return{...Dr(),palettes:e.map(wn)}}var eu={id:"meta",emitShared(e){return[{path:"manifest.json",content:`${JSON.stringify(qw(e),null,2)}
255
- `}]}};var Qw=["ghostty","kitty","alacritty","wezterm","iterm2","windows-terminal","warp"],Yw=[{section:"tab",title:"This tab"},{section:"startup",title:"New tabs"},{section:"catalog",title:"Palettes"},{section:"own",title:"Your own"},{section:"setup",title:"Setup"}],ei=[{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 from the catalog in a live picker",section:"catalog",start:"install or drop palettes — every market you added, in one picker"},{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, installed"}}},{name:"add",args:["<palette...>"],about:"install palettes from the catalog, or from a share code: ttheme add tt1:…",section:"catalog"},{name:"remove",args:["<palette...>"],about:"uninstall palettes",section:"catalog"},{name:"update",args:[],about:"refresh every market you added",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, with how many palettes each holds"],["add <source>","add one: a repository (alice/ttheme-pastel), a folder, or official"],["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:Qw,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}];function xr(e){let n=Object.entries(e.flags??{}).map(([t,{value:r}])=>`[--${t}${r?` ${r}`:""}]`);return[e.name,...n,...e.args].join(" ")}function nu(e,n=Math.max(...e.map(([t])=>t.length))){return e.map(([t,r])=>` ${t.padEnd(n)} ${r}`)}var Zw=[["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 new rei --from rei","your own rei, <you>@<market>/rei, to edit and share"]];function ni(e,n=!1){let t=ei.filter((s)=>!s.hidden&&!(n&&s.section==="setup")),r=Yw.filter(({section:s})=>t.some((u)=>u.section===s)),i=[...n?["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 s=t.filter((c)=>c.start),u=Math.max(...r.map(({title:c})=>c.length));return["Usage: ttheme <command>","",_e.description,"","Start here",...nu(s.map((c)=>[xr(c),c.start])),"",...r.map(({section:c,title:a})=>`${a.padEnd(u)} ${t.filter((h)=>h.section===c).map((h)=>h.name).join(" · ")}`),"",...i].join(`
256
- `)}let o=Math.max(...t.map((s)=>xr(s).length));return["Usage: ttheme <command>","",_e.description,...r.flatMap(({section:s,title:u})=>["",u,...nu(t.filter((c)=>c.section===s).map((c)=>[xr(c),c.about]),o)]),"","Examples",...nu(Zw),"",...i].join(`
257
- `)}var go=["ghostty","kitty","alacritty","wezterm","iterm2","windows-terminal","warp"],nf="# ttheme begin",tf="# ttheme end",ti=/# ttheme begin\n[\s\S]*?# ttheme end\n?/;function ri(e,n){let t=`${nf}
241
+ */import{readdirSync as aw,rmSync as fw,statSync as hw}from"node:fs";import{setDefaultAutoSelectFamilyAttemptTimeout as lw}from"node:net";import{homedir as dw}from"node:os";import{join as Vr}from"node:path";import{setTimeout as gw}from"node:timers/promises";var wf=Vi(Ea(),1),fo=Vi(mf(),1);import{deflateSync as rw}from"node:zlib";var Qr=[137,80,78,71,13,10,26,10],bf=13,$f=3;function er(e){return e.length>=Qr.length&&Qr.every((n,t)=>e[t]===n)}function bt(e){let n=fo.PNG.sync.read(Buffer.from(e));return{width:n.width,height:n.height,data:new Uint8Array(n.data)}}function $t(e,n){if(er(e)){let t=kt(e);if(t&&t.width*t.height>n)throw Error(`${t.width}×${t.height} is over ${n/1e6} megapixels`);return bt(e)}if(e[0]===255&&e[1]===216){let t=wf.decode(e,{useTArray:!0,formatAsRGBA:!0,maxResolutionInMP:n/1e6,maxMemoryUsageInMB:1024});return{width:t.width,height:t.height,data:t.data}}throw Error("not a PNG or JPEG image")}function Vs(e){let n=new fo.PNG({width:e.width,height:e.height});return n.data=Buffer.from(e.data),fo.PNG.sync.write(n)}function pf(e,n){for(let t=0;t+n.length<=e.length;t++){let r=!0;for(let i=0;i<n.length&&r;i++)r=e[t+i]===n.charCodeAt(i);if(r)return t}return-1}function kt(e){if(e.length<33||!er(e))return null;let n=new DataView(e.buffer,e.byteOffset,e.byteLength),t=n.getUint32(16),r=n.getUint32(20);if(e[25]===4||e[25]===6)return{width:t,height:r,alpha:!0};let i=pf(e,"IDAT");return{width:t,height:r,alpha:pf(i===-1?e:e.subarray(0,i),"tRNS")!==-1}}function kf(e,n=bf){let{width:t,height:r}=e,i=-1,o=-1;for(let s=0;s<e.height;s++)for(let u=0;u<e.width;u++)if((e.data[(s*e.width+u)*4+3]??0)>=n)t=Math.min(t,u),i=Math.max(i,u),r=Math.min(r,s),o=Math.max(o,s);return i<0?null:{x:t,y:r,w:i-t+1,h:o-r+1}}function jn(e,n={x:0,y:0,w:e.width,h:e.height}){let t=0;for(let r=n.y;r<n.y+n.h;r++)for(let i=n.x;i<n.x+n.w;i++)if((e.data[(r*e.width+i)*4+3]??0)<bf)t++;return Math.round(t*100/(n.w*n.h))}function yf(e,n,t){let r=Math.min(n/e.width,t/e.height),i=Math.max(1,Math.round(e.width*r)),o=Math.max(1,Math.round(e.height*r)),s=ow(e,{x:0,y:0,w:e.width,h:e.height},i,o),u=new Uint8Array(n*t*4),c=Math.floor((n-i)/2),a=Math.floor((t-o)/2);for(let f=0;f<o;f++)u.set(s.data.subarray(f*i*4,(f+1)*i*4),((a+f)*n+c)*4);return{width:n,height:t,data:u}}function iw(e){let n=Math.abs(e);if(n<1)return(7*n*n*n-12*n*n+5.333333333333333)/6;if(n<2)return(-2.3333333333333335*n*n*n+12*n*n-20*n+10.666666666666666)/6;return 0}function Bs(e,n,t,r){if(t===r&&Number.isInteger(n)&&n>=0&&n+r<=e)return{first:Int32Array.from({length:r},(f,h)=>n+h),size:1,weights:new Float32Array(r).fill(1)};let i=t/r,o=Math.max(1,i),s=2*o,u=Math.min(e,Math.ceil(2*s)+2),c=new Int32Array(r),a=new Float32Array(r*u);for(let f=0;f<r;f++){let h=n+(f+0.5)*i,l=Math.floor(h-s-0.5),d=Math.max(0,Math.min(e-u,l));c[f]=d;let g=0;for(let m=l;m<=Math.ceil(h+s-0.5);m++){let $=iw((m+0.5-h)/o),S=f*u+Math.min(e-1,Math.max(0,m))-d;a[S]=(a[S]??0)+$,g+=$}for(let m=f*u;m<(f+1)*u;m++)a[m]=(a[m]??0)/g}return{first:c,size:u,weights:a}}function Ef(e,n,t,r,i,o){let s=Bs(e,n.y,n.h,r),u=t*i,c=new Float32Array(u*r),a=new Map;for(let f=0;f<r;f++){let h=s.first[f]??0;for(let d of a.keys())if(d<h)a.delete(d);let l=f*u;for(let d=0;d<s.size;d++){let g=s.weights[f*s.size+d]??0;if(g===0)continue;let m=a.get(h+d);if(!m)m=new Float32Array(u),o(h+d,m),a.set(h+d,m);for(let $=0;$<u;$++)c[l+$]=(c[l+$]??0)+(m[$]??0)*g}}return c}function ow(e,n,t,r){let i=Bs(e.width,n.x,n.w,t),o=e.data,s=Ef(e.height,n,t,r,4,(c,a)=>{let f=c*e.width;for(let h=0;h<t;h++){let l=f+(i.first[h]??0),d=h*i.size,g=0,m=0,$=0,S=0;for(let v=0;v<i.size;v++){let k=(l+v)*4,M=(i.weights[d+v]??0)*(o[k+3]??0);g+=(o[k]??0)*M,m+=(o[k+1]??0)*M,$+=(o[k+2]??0)*M,S+=M}a[h*4]=g,a[h*4+1]=m,a[h*4+2]=$,a[h*4+3]=S}}),u=new Uint8Array(t*r*4);for(let c=0;c<t*r;c++){let a=s[c*4+3]??0;if(a<=0)continue;for(let f=0;f<3;f++)u[c*4+f]=Math.min(255,Math.max(0,Math.round((s[c*4+f]??0)/a)));u[c*4+3]=Math.min(255,Math.round(a))}return{width:t,height:r,data:u}}function Sf(e,n,t,r){let i=Bs(e.width,n.x,n.w,t),o=e.data,s=Ef(e.height,n,t,r,1,(u,c)=>{let a=u*e.width;for(let f=0;f<t;f++){let h=a+(i.first[f]??0),l=f*i.size,d=0;for(let g=0;g<i.size;g++)d+=(o[h+g]??0)*(i.weights[l+g]??0);c[f]=d}});return{width:t,height:r,data:s}}function ho(e,n){if(n<=0)return e;let t=Math.max(1,Math.ceil(n*3)),r=Array.from({length:2*t+1},(f,h)=>Math.exp(-((h-t)**2)/(2*n*n))),i=r.reduce((f,h)=>f+h,0),{width:o,height:s,data:u}=e,c=new Float32Array(o*s);for(let f=0;f<s;f++){let h=f*o;for(let l=0;l<o;l++){let d=0;for(let g=-t;g<=t;g++)d+=(u[h+Math.min(o-1,Math.max(0,l+g))]??0)*(r[g+t]??0);c[h+l]=d/i}}let a=new Float32Array(o*s);for(let f=0;f<s;f++){let h=f*o;for(let l=-t;l<=t;l++){let d=(r[l+t]??0)/i,g=Math.min(s-1,Math.max(0,f+l))*o;for(let m=0;m<o;m++)a[h+m]=(a[h+m]??0)+(c[g+m]??0)*d}}return{width:o,height:s,data:a}}function Yr(e){let n=new Uint8Array(e.data.length);for(let t=0;t<n.length;t++)n[t]=Math.min(255,Math.max(0,Math.round(e.data[t]??0)));return{width:e.width,height:e.height,data:n}}function Zr(e){let n=new Uint8Array(e.width*e.height);for(let t=0;t<n.length;t++)n[t]=e.data[t*4+3]??0;return{width:e.width,height:e.height,data:n}}var sw=Array.from({length:256},(e,n)=>{let t=n;for(let r=0;r<8;r++)t=t&1?3988292384^t>>>1:t>>>1;return t>>>0});function uw(e){let n=4294967295;for(let t of e)n=(sw[(n^t)&255]??0)^n>>>8;return(n^4294967295)>>>0}function qr(e,n){let t=Buffer.alloc(12+n.length);return t.writeUInt32BE(n.length,0),t.write(e,4,"latin1"),t.set(n,8),t.writeUInt32BE(uw(t.subarray(4,8+n.length)),8+n.length),t}function cw(e,n,t){let r=n+1,i=new Uint8Array(t*r);for(let o=0;o<t;o++){let s=o*r,u=o*n,c=u-n;i[s]=4;for(let a=0;a<n;a++){let f=a>0?e[u+a-1]??0:0,h=o>0?e[c+a]??0:0,l=a>0&&o>0?e[c+a-1]??0:0,d=Math.abs(h-l),g=Math.abs(f-l),m=Math.abs(f+h-2*l);i[s+1+a]=(e[u+a]??0)-(d<=g&&d<=m?f:g<=m?h:l)&255}}return i}function Mf(e,n,t){let r=Buffer.alloc(13);return r.writeUInt32BE(e.width,0),r.writeUInt32BE(e.height,4),r[8]=8,r[9]=n,Buffer.concat([Buffer.from(Qr),qr("IHDR",r),...t,qr("IDAT",rw(cw(e.data,e.width,e.height))),qr("IEND",new Uint8Array)])}function vf(e){let[n,t,r]=Je(e),i=new Uint8Array(768);for(let o=0;o<256;o++)i.set([n,t,r],o*3);return qr("PLTE",i)}function Xr(e,n){return Mf(e,$f,[vf(n),qr("tRNS",Uint8Array.from({length:256},(t,r)=>r))])}function Ds(e){return Mf(e,0,[])}function If(e,n){if(!er(e)||e[25]!==$f)return;let t=Buffer.from(e.buffer,e.byteOffset,e.byteLength),r=[Buffer.from(Qr)],i=Qr.length;while(i+8<=t.length){let o=i+12+t.readUInt32BE(i);r.push(t.toString("latin1",i+4,i+8)==="PLTE"?vf(n):t.subarray(i,o)),i=o}return Buffer.concat(r)}var yt=100,an=25000000,mw=536870912,Br=["safe","questionable","explicit"],Et=["nudity","underwear"],pw={nudity:new Set(["nude","naked","topless","bottomless","nipples","naked_towel","undressing"]),underwear:new Set(["underwear","panties","pantsu","bra","lingerie","pantyshot"])},zr={safe:"s",questionable:"q",explicit:"e"},ww=8191,bw=20000,$w=5000,Nf=3000,Of=8,kw=3000,Af=60000,Rf=3,eu=`ttheme/${qe.version} (+${qe.homepage})`,yw=["orig","tile","thumb","cut"],Hf=new Map,Ew=Aw(process.env.TTHEME_FIND_HOSTS),Sw=Pw(process.env.TTHEME_FIND_CUTOUTS);lw(kw);function Ff(e){try{return aw(e)}catch{return[]}}function lo(e){return e.startsWith("//")?`https:${e}`:e}function Dr(e){return(/\.([a-z0-9]+)(?:\?.*)?$/i.exec(e)?.[1]??"").toLowerCase()}function xr(e){let n=e.trim();if(!n)return[];let t=JSON.parse(n);if(Array.isArray(t))return t;let r=t.posts;return Array.isArray(r)?r:[]}function Mw(e){let n=e.trim(),r=(n?JSON.parse(n):{}).tags??{};return new Map(Object.entries(r).map(([i,o])=>[i,String(o)]))}function xs(e,n,t){let r=lo(String(e??""));return{file:r,width:Number(n)||0,height:Number(t)||0,ext:Dr(r)}}function Lf(e,n){let t=lo(String(n.preview??""));if(!n.file||!t||!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:n.file,preview:t,ext:n.ext,owner:String(n.owner??""),artist:n.artist,score:Number(e.score)||0,rating:String(e.rating??""),md5:String(n.md5??""),source:String(e.source??""),tags:n.tags.split(/\s+/).filter(Boolean),solo:n.solo,family:Number(e.parent_id)||(e.has_children===!0?Number(e.id):0),smaller:n.versions.filter((o)=>o.file&&o.width>0&&o.height>0&&o.width*o.height<r*i)}]}function vw(e){let n=Mw(e);return xr(e).flatMap((t)=>{let r=lo(String(t.file_url??"")),i=String(t.tags??"");return Lf(t,{preview:t.preview_url,file:r,ext:String(t.file_ext||Dr(r)).toLowerCase(),owner:t.author,artist:i.split(/\s+/).find((o)=>n.get(o)==="artist")??"",md5:t.md5,tags:i,solo:void 0,versions:[xs(t.jpeg_url,t.jpeg_width,t.jpeg_height),xs(t.sample_url,t.sample_width,t.sample_height)]})})}function Iw(e){return xr(e).flatMap((n)=>{let t=lo(String(n.file_url??"")),r=String(n.tag_string??""),i=n.media_asset??{};return Lf(n,{preview:i.variants?.find((o)=>o.type==="360x360")?.url??n.preview_file_url,file:t,ext:String(n.file_ext||Dr(t)).toLowerCase(),owner:"",artist:String(n.tag_string_artist??"").split(/\s+/)[0]??"",md5:n.md5,tags:r,solo:r.split(/\s+/).includes("solo"),versions:(i.variants??[]).map((o)=>xs(o.url,o.width,o.height)).filter((o)=>o.ext==="jpg"||o.ext==="png").sort((o,s)=>s.width*s.height-o.width*o.height)})})}function Nw(e){return xr(e).flatMap((n)=>{let t=String(n.value??"");return t?[{value:t,count:Number(n.post_count)||0}]:[]})}function Ow(e){return xr(e).flatMap((n)=>{let t=String(n.name??"");return t?[{value:t,count:Number(n.count)||0}]:[]})}function Rw(e){return Number(/count="(\d+)"/.exec(e)?.[1]??0)}function Fw(e){let n=e.trim()?JSON.parse(e):{};return Number(n.counts?.posts)||0}function Pw(e){let n=new Map;for(let t of(e??"").split(/\s+/).filter(Boolean)){let r=t.indexOf("=");if(r>0)n.set(t.slice(0,r),t.slice(r+1).split(",").filter(Boolean))}return n}function Aw(e){let n=new Map;for(let t of(e??"").split(/[\s,]+/).filter(Boolean)){let r=t.indexOf("="),i=t.slice(0,r);try{let o=new URL(t.slice(r+1));if(i&&o.protocol==="https:")n.set(i,o.origin)}catch{}}return n}function Tf(e,n,t,r){let i=(e??"").split(/\s+/);if(r!==void 0&&i.includes(r))return[];let o=n.filter((s)=>i.includes(s));return o.length>0?o:[...t]}function nr(e){return Tf(e,Br,["safe"])}function tr(e){return Tf(e,Et,Et,"none")}function Gf(e,n,t){return{safe:new Set(e),questionable:new Set(n),explicit:new Set(t)}}function Uf(e){let n=Ew.get(e.key),t=Sw.get(e.key);return{...e,origin:n??e.origin,moved:n!==void 0&&n!==e.origin,cutouts:t??e.cutouts,vouched:e.vouched&&t===void 0}}function jf(e){return e.length<2?e.join(""):e.map((n)=>`~${n}`).join(" ")}function Pf(e){let n=Uf(e),t=(r)=>new URLSearchParams({api_version:"2",include_tags:"1",...r});return{...n,cutouts:jf(n.cutouts),ratings:Gf([zr.safe],[zr.questionable],[zr.explicit]),rate:(r)=>{let[i]=r;if(r.length===1&&i)return`rating:${zr[i]}`;let o=Br.filter((u)=>!r.includes(u)),[s]=o;return o.length===1&&s?`-rating:${zr[s]}`:""},best:"order:score",tagBudget:Number.POSITIVE_INFINITY,postsUrl:(r,i)=>`${n.origin}/post.json?${t({limit:String(yt),page:String(i+1),tags:r})}`,countUrl:(r)=>`${n.origin}/post.xml?${new URLSearchParams({limit:"1",tags:r})}`,postUrl:(r)=>`${n.origin}/post.json?${t({tags:`id:${r}`})}`,pageUrl:(r)=>`${n.origin}/post/show/${r}`,parse:vw,count:Rw}}function Hw(e){let n=Uf(e),t=Gf(["g"],["s","q"],["e"]);return{...n,cutouts:jf(n.cutouts),ratings:t,rate:(r)=>r.length===Br.length?"":`rating:${r.flatMap((i)=>[...t[i]]).join(",")}`,best:"order:score",tagBudget:2,postsUrl:(r,i)=>`${n.origin}/posts.json?${new URLSearchParams({limit:String(yt),page:String(i+1),tags:r})}`,countUrl:(r)=>`${n.origin}/counts/posts.json?${new URLSearchParams({tags:r})}`,postUrl:(r)=>`${n.origin}/posts.json?${new URLSearchParams({limit:"1",tags:`id:${r}`})}`,pageUrl:(r)=>`${n.origin}/posts/${r}`,parse:Iw,count:Fw}}function Lw(e){return x.find((n)=>n.key===e||n.name===e||new URL(n.origin).host===e)}function nu(e){return e.split(/\s+/).filter((n)=>n&&!n.startsWith("rating:")).length}function go(e,n){let t=e.trim();if(/^\d+$/.test(t))return{site:n,id:Number(t)};let r=/^([\w.]+):(\d+)$/.exec(t);if(r){let u=x.find((c)=>c.key===r[1]||c.name===r[1]);return u&&{site:u,id:Number(r[2])}}let i;try{i=new URL(t)}catch{return}let o=Lw(i.host),s=Number(i.searchParams.get("id")??i.pathname.split("/").filter(Boolean).at(-1));return o&&s>0?{site:o,id:s}:void 0}var x=[Hw({key:"danbooru",name:"danbooru",origin:"https://danbooru.donmai.us",cutouts:["transparent_background"],vouched:!1,tunneled:!0,ansi:2}),Pf({key:"konachan",name:"konachan",origin:"https://konachan.net",cutouts:["transparent","vector"],vouched:!1,tunneled:!1,ansi:6}),Pf({key:"yande",name:"yande.re",origin:"https://yande.re",cutouts:["transparent_png"],vouched:!0,tunneled:!1,ansi:5})],Cn=134217728;function In(e,n){let t=x.indexOf(e);return(t===-1?x.length:t)*Cn+n}function tu(e){let n;try{n=new URL(e).hostname}catch{return""}return n.split(".").slice(-2).join(".")}function Cf(){return x.filter((e)=>!e.tunneled).map((e)=>tu(e.origin)).flatMap((e)=>[e,`.${e}`]).join(",")}function mo(e,n=Et){return e.tags.filter((t)=>n.some((r)=>pw[r].has(t)))}function po(e,n,t=["safe"]){return t.some((r)=>e.ratings[r].has(n.rating))}function St(e){return[e,...e.smaller].find((n)=>n.width*n.height<=an)}function Jf(e){let n=new Map;for(let[t,r]of[...e].sort(([i],[o])=>i<o?-1:1)){if(r==="")continue;n.set(r,[...n.get(r)??[],t])}return n}function rr(){return Vr(process.env.XDG_CACHE_HOME??Vr(dw(),".cache"),"ttheme")}function bn(e){return Vr(rr(),e.key)}function _f(e=mw,n=rr()){let t=[],r=0;for(let i of Ff(n))for(let o of yw){let s=Vr(n,i,o);for(let u of Ff(s)){let c=Vr(s,u);try{let{size:a,mtimeMs:f}=hw(c);t.push({path:c,size:a,at:f}),r+=a}catch{}}}t.sort((i,o)=>i.at-o.at);for(let i of t){if(r<=e)return;try{fw(i.path,{force:!0}),r-=i.size}catch{}}}function Tw(e,n){if(e!==null&&/^\s*\d+\s*$/.test(e))return Number(e)*1000;let t=e===null?Number.NaN:Date.parse(e);return Number.isNaN(t)?Af:Math.max(0,t-n)}function nt(e){return Hf.get(e.key)??0}function Gw(e){for(let n=e;n instanceof Error;n=n.cause)if(n.code==="ECONNRESET")return!0;return!1}function Uw(e){return(e.headers.get("server")??"").startsWith("cloudflare")&&e.headers.get("cf-mitigated")==="challenge"}async function tt(e,n,t,r={},i=bw){for(let o=1;;o++){let s=nt(e)-Date.now();if(s>0)await gw(s,void 0,{signal:t});let u;try{u=await fetch(n,{headers:{"User-Agent":eu,Referer:`${e.origin}/`,...r},signal:i?AbortSignal.any([t,AbortSignal.timeout(i)]):t})}catch(c){if(o<Rf&&!t.aborted&&Gw(c))continue;throw c}if(u.status===429&&o<Rf){await u.body?.cancel();let c=Tw(u.headers.get("retry-after"),Date.now());if(c>Af)throw Error(`${e.name} asks to wait ${Math.ceil(c/1000)}s`);Hf.set(e.key,Math.max(nt(e),Date.now()+c));continue}if(!u.ok)throw await u.body?.cancel(),Error(Uw(u)?`${e.name} is behind a Cloudflare challenge`:`${e.name} answered ${u.status}`);return u}}async function Wf(e,n,t,r){return e.parse(await(await tt(e,e.postsUrl(n,t),r)).text())}async function Kf(e,n,t){return e.count(await(await tt(e,e.countUrl(n),t)).text())}async function ei(e,n,t){let[r]=e.parse(await(await tt(e,e.postUrl(n),t)).text());return r}function jw(e){let n=x.find((r)=>r.key==="danbooru"),t=new URLSearchParams({limit:String(2*yt),only:"md5,tag_string",tags:`md5:${e.join(",")}`});return`${n.origin}/posts.json?${t}`}function Cw(e){return new Map(xr(e).flatMap((n)=>{let t=String(n.md5??"");return t?[[t,String(n.tag_string??"").split(/\s+/).filter(Boolean)]]:[]}))}function qf(e,n){for(let t of e){let r=n.get(t.md5);if(r)t.tags=[...new Set([...t.tags,...r])],t.solo=r.includes("solo")}}async function Qf(e,n){let t=x.find((i)=>i.key==="danbooru"),r=new Map;if(nt(t)>Date.now())return r;for(let i=0;i<e.length;i+=yt){let o=await(await tt(t,jw(e.slice(i,i+yt)),n,{},$w)).text();for(let[s,u]of Cw(o))r.set(s,u)}return r}async function Yf(e,n){let t=x.find((o)=>o.key==="danbooru");if(nt(t)<=Date.now())try{let o=new URLSearchParams({"search[query]":e,"search[type]":"tag_query",limit:String(Of)}),s=`${t.origin}/autocomplete.json?${o}`;return Nw(await(await tt(t,s,n,{},Nf)).text())}catch(o){if(n.aborted)throw o}let r=x.find((o)=>o.key==="yande"),i=new URLSearchParams({name:e,order:"count",limit:String(Of)});return Ow(await(await tt(r,`${r.origin}/tag.json?${i}`,n,{},Nf)).text())}async function Zf(e,n,t){let r=await tt(e,n,t,{Range:`bytes=0-${ww}`});return kt(new Uint8Array(await r.arrayBuffer()))}async function wo(e,n,t,r){let i=await tt(e,n,t,{},0),o=Number(i.headers.get("content-length"))||0,s=i.body?.getReader();if(!s)return new Uint8Array(await i.arrayBuffer());let u=[],c=0;for(;;){let{done:h,value:l}=await s.read();if(h)break;u.push(l),c+=l.length,r?.(c,o)}let a=new Uint8Array(c),f=0;for(let h of u)a.set(h,f),f+=h.length;return a}var vt=["top-left","top-center","top-right","center-left","center","center-right","bottom-left","bottom-center","bottom-right"],ni="Original",Ww=1e6,Nn="_groups.toml",Xf=3,zf=8,ru="[a-z0-9]+(?:-[a-z0-9]+)*",Kw=new RegExp(`^(?:(${ru})@(${ru})/)?(${ru})$`),xf=["background","foreground","cursor","selection"];function ce(e,n){throw Error(`${e}: ${n}`)}function Mt(e,n,t){if(typeof t!=="string"||!Zt(t))ce(e,`${n} must be "#rrggbb" (lowercase), got ${JSON.stringify(t)}`);return t}function ti(e,n,t){if(typeof t!=="string"||t.length===0)ce(e,`${n} must be a non-empty string`);return t}function Jn(e){return e.replace("@","--").replace("/","--")}function Ge(e){let n=e.indexOf("/");return n<0?void 0:e.slice(0,n)}function $o(e){return e.slice(e.indexOf("/")+1)}function On(e){let n=Kw.exec(e);if(!n)return"takes lowercase letters, digits and single hyphens, as <palette> or <owner>@<market>/<palette>";if((n[1]?.length??0)>39)return"has an owner longer than a GitHub handle can be";return(n[2]?.length??0)>40||(n[3]?.length??0)>40?"is longer than 40 characters":void 0}function iu(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 bo(e,n,t){let r=ti(e,n,t),i=iu(r);if(i)ce(e,`${n} ${JSON.stringify(r)} ${i}`);return r}function Vf(e,n,t){let r=ti(e,n,t),i=On(r);if(i)ce(e,`${n} "${r}" ${i}`);return r}function ir(e){return e&&typeof e==="object"?e:{}}function qw(e,n,t){if(n===void 0)return[t.cursor,t.selectionBackground,t.background];let r=Array.isArray(n)?n:[n];if(r.length===0)ce(e,"ghostty.icon_screen must not be empty");return r.map((i,o)=>Mt(e,`ghostty.icon_screen[${o}]`,i))}function Qw(e,n,t){let r=ir(n);return{iconGhost:r.icon_ghost===void 0?t.cursor:Mt(e,"ghostty.icon_ghost",r.icon_ghost),iconScreen:qw(e,r.icon_screen,t)}}function Yw(e){return new Map([...xf.map((n)=>[n,e[n]]),...e.ansi.map((n,t)=>[`ansi${t}`,n])])}function Zw(e,n,t){if(!Array.isArray(n)||n.length!==Xf)ce(e,`meta.signature must name exactly ${Xf} palette slots`);let r=Yw(t),i=[],o=[];for(let[s,u]of n.entries()){let c=`meta.signature[${s}]`,a=ti(e,c,u),f=r.get(a);if(f===void 0)ce(e,`${c} ${JSON.stringify(u)} is not a palette slot — use ${xf.join(", ")} or ansi0-ansi15`);i.push(a),o.push(f)}if(new Set(o).size!==o.length)ce(e,"meta.signature slots must resolve to three different colors");return{names:i,colors:o}}function Xw(e,n,t){if(n===void 0)return;if(!t)ce(e,"meta.booru_sites renames meta.booru per site, so it needs meta.booru");if(!n||typeof n!=="object"||Array.isArray(n))ce(e,'meta.booru_sites must be a table of site = "tag" or site = ["tag", ...]');let r={};for(let[i,o]of Object.entries(n)){let s=x.find((c)=>c.key===i);if(!s)ce(e,`meta.booru_sites.${i} is not a find site — use ${x.map((c)=>c.key).join(", ")}`);let u=typeof o==="string"?[o]:Array.isArray(o)?o:void 0;if(!u||u.some((c)=>typeof c!=="string"||c===""||/\s/.test(c)))ce(e,`meta.booru_sites.${i} must be one tag or a list of tags, got ${JSON.stringify(o)}`);if(u.length>1&&Number.isFinite(s.tagBudget))ce(e,`meta.booru_sites.${i} takes one tag — ${s.name} searches ${s.tagBudget} tags at a time`);r[i]=u}return r}function zw(e,n){if(n===void 0)return;if(!Array.isArray(n)||n.length===0||n.length>zf)ce(e,`[[picture]] holds 1 to ${zf} pictures`);return n.map((t,r)=>{let i=ir(t),o=`picture[${r}]`,s=x.find((f)=>f.key===i.site);if(!s)ce(e,`${o}.site must be one of ${x.map((f)=>f.key).join(", ")}`);if(typeof i.id!=="number"||!Number.isSafeInteger(i.id)||i.id<=0)ce(e,`${o}.id must be the post's number on ${s.name}`);let{size:u,position:c,opacity:a}=i;if(u!==void 0&&u!=="fill"&&!(Number.isInteger(u)&&Number(u)>=20&&Number(u)<=999))ce(e,`${o}.size must be "fill" or a percentage from 20 to 999`);if(c!==void 0&&!vt.includes(c))ce(e,`${o}.position must be one of ${vt.join(", ")}`);if(a!==void 0&&!(typeof a==="number"&&a>=0&&a<=1))ce(e,`${o}.opacity must be a number from 0 to 1`);return{site:s.key,id:i.id,...u!==void 0?{size:u}:{},...c!==void 0?{position:c}:{},...a!==void 0?{opacity:a}:{}}})}function eh(e,n){try{return Ls(n)}catch(t){ce(e,`is not valid TOML — ${(t instanceof Error?t.message:String(t)).split(`
242
+ `)[0]}`)}}function Vw(e){let t=eh(Nn,Bf(Df(e,Nn),"utf8")).group;if(!Array.isArray(t)||t.length===0)ce(Nn,"needs at least one [[group]] table");return t.map((r)=>{let i=ir(r);return{name:bo(Nn,"group.name",i.name),native:i.native===void 0?void 0:bo(Nn,"group.native",i.native),lead:ti(Nn,"group.lead",i.lead)}})}function ou(e,n,t){let r=eh(e,n),i=ir(r.meta),o=ir(r.colors),s=ir(r.contrast),u=o.ansi;if(!Array.isArray(u)||u.length!==16)ce(e,`colors.ansi must hold exactly 16 colors, got ${Array.isArray(u)?u.length:typeof u}`);let c=Vf(e,"meta.name",i.name);if(c!==t.name)ce(e,`meta.name "${c}" does not match its file — it lives at ${t.name}`);let a=t.open===!0;for(let N of["order","role"])if(a&&i[N]!==void 0)ce(e,`meta.${N} is for the official palettes — a market palette follows its base`);let f=i.role;if(f!==void 0&&f!=="default")ce(e,`meta.role must be "default", got ${JSON.stringify(f)}`);let h=i.base===void 0?void 0:Vf(e,"meta.base",i.base);if(h!==void 0&&!a)ce(e,"meta.base is for market palettes");let l=h===void 0?void 0:t.bases?.get(h),d=a&&i.group===void 0?l?.group??ni:bo(e,"meta.group",i.group),g=t.groups.get(d);if(!g&&!(a&&(d===ni||t.open)))ce(e,`meta.group "${d}" has no [[group]] table in ${Nn}`);let m=Mt(e,"colors.background",o.background),$=Mt(e,"colors.foreground",o.foreground),S=Mt(e,"colors.cursor",o.cursor),v=Mt(e,"colors.selection_background",o.selection_background),k=u.map((N,H)=>Mt(e,`colors.ansi[${H}]`,N)),M=Zw(e,i.signature,{background:m,foreground:$,cursor:S,selection:v,ansi:k}),p=i.booru===void 0?void 0:ti(e,"meta.booru",i.booru);if(p!==void 0&&/[\s\p{Cc}]/u.test(p))ce(e,`meta.booru must be a single booru tag, got ${JSON.stringify(p)}`);let A=Xw(e,i.booru_sites,p),y=Array.isArray(s.waive)?s.waive.map(String):[];if(y.length>0&&typeof s.reason!=="string")ce(e,"contrast.waive needs a contrast.reason explaining why");let F=zw(e,r.picture);return{name:c,...h?{base:h}:{},group:d,native:g?.native,lead:!a&&g?.lead===c,order:a?l?.order??Ww:Number(i.order),role:f,ansiSource:a&&i.ansi_source===void 0?h??"original":bo(e,"meta.ansi_source",i.ansi_source),...p?{booru:p}:{},...A?{booruSites:A}:{},background:m,foreground:$,cursor:S,selectionBackground:v,ansi:k,signature:M.colors,signatureSlots:M.names,ghostty:Qw(e,r.ghostty,{background:m,cursor:S,selectionBackground:v}),waive:y,waiveReason:typeof s.reason==="string"?s.reason:void 0,...F?{pictures:F}:{}}}function nh(e){let n=Vw(e),t=new Map(n.map((o)=>[o.name,o]));if(t.size!==n.length)ce(Nn,"group.name must be unique");let r=Jw(e).filter((o)=>o.endsWith(".toml")&&!o.startsWith("_")).map((o)=>ou(o,Bf(Df(e,o),"utf8"),{name:_w(o,".toml"),groups:t})).sort((o,s)=>o.order-s.order);if(new Set(r.map((o)=>o.order)).size!==r.length)throw Error("themes: meta.order must be unique across all themes");for(let o of n){let s=r.filter((u)=>u.group===o.name);if(s.length===0)ce(Nn,`group "${o.name}" has no themes`);if(!s.some((u)=>u.name===o.lead))ce(Nn,`group "${o.name}" lead "${o.lead}" is not one of its themes`)}return r}function th(e){return e.filter((n)=>n.role===void 0)}function ri(e){let n=(r,i)=>r<i?-1:r>i?1:0,t=(r)=>Ge(r.name)?r.name:r.base??r.name;return[...e].sort((r,i)=>Number(Ge(r.name)!==void 0)-Number(Ge(i.name)!==void 0)||n(r.group.toLowerCase(),i.group.toLowerCase())||n(t(r),t(i))||Number(r.base!==void 0)-Number(i.base!==void 0)||n(r.name,i.name))}var Bw=["black","red","green","yellow","blue","magenta","cyan","white"];function rh(e,n){return[e,...Bw.map((t,r)=>`${t} = '${n[r]}'`),""].join(`
243
+ `)}var ii={id:"alacritty",limits:"no runtime color API (OSC only)",emit(e){let n=[...or(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}'`,"",rh("[colors.normal]",e.ansi.slice(0,8)),rh("[colors.bright]",e.ansi.slice(8,16))].join(`
244
+ `);return[{path:`alacritty/themes/${he(e.name)}.toml`,content:n}]}};var oi={id:"ghostty",emit(e){let n=[...or(e),`background = ${e.background}`,`foreground = ${e.foreground}`,`cursor-color = ${e.cursor}`,`selection-background = ${e.selectionBackground}`,`selection-foreground = ${e.foreground}`,...e.ansi.map((t,r)=>`palette = ${r}=${t}`),"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(`
245
+ `);return[{path:`ghostty/themes/${he(e.name)}`,content:n}]}};function rt(e){let[n,t,r]=Je(e);return{"Alpha Component":1,"Blue Component":r/255,"Color Space":"P3","Green Component":t/255,"Red Component":n/255}}function ih(e){return{...Object.fromEntries(e.ansi.map((n,t)=>[`Ansi ${t} Color`,rt(n)])),"Background Color":rt(e.background),"Bold Color":rt(e.foreground),"Cursor Color":rt(e.cursor),"Cursor Text Color":rt(e.background),"Foreground Color":rt(e.foreground),"Selected Text Color":rt(e.foreground),"Selection Color":rt(e.selectionBackground)}}function Dw(e){return e?{"Background Image Location":e.image,"Background Image Mode":e.cover?2:3,Blend:e.opacity}:{"Background Image Location":""}}function oh(e,n,t,r){let i=(s,u)=>({Name:`ttheme · ${u}`,Guid:he(u),...r?{"Dynamic Profile Parent GUID":r}:{},"Use Separate Colors for Light and Dark Mode":!1,"Harmonize 256 Colors":!0,...Dw(n.get(s.name)),...ih(s)}),o=[...t?[i(t,"default")]:[],...e.map((s)=>i(s,s.name))];return`${JSON.stringify({Profiles:o},null,2)}
246
+ `}function xw(e,n){return[` <key>${e}</key>`,"\t<dict>",...Object.entries(n).flatMap(([t,r])=>[` <key>${t}</key>`,typeof r==="string"?` <string>${r}</string>`:` <real>${r}</real>`]),"\t</dict>"].join(`
247
+ `)}var si={id:"iterm2",limits:"colors are Display P3, the space iTerm2 reads OSC colors in",emit(e){let n=['<?xml version="1.0" encoding="UTF-8"?>','<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">','<plist version="1.0">',"<dict>",...Object.entries(ih(e)).map(([t,r])=>xw(t,r)),"</dict>","</plist>",""].join(`
248
+ `);return[{path:`iterm2/${he(e.name)}.itermcolors`,content:n}]}};var ui={id:"kitty",emit(e){let n=[...or(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((t,r)=>`color${r} ${t}`),""].join(`
249
+ `);return[{path:`kitty/themes/${he(e.name)}.conf`,content:n}]}};function sh(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(`
250
+ `)}import{createHash as mh}from"node:crypto";import{copyFileSync as a0,existsSync as du,mkdirSync as f0,readdirSync as h0,readFileSync as Eo,renameSync as ph,rmSync as ur}from"node:fs";import{basename as wh,isAbsolute as l0,join as Y}from"node:path";import{chmodSync as e0,copyFileSync as n0,existsSync as sr,mkdirSync as t0,readFileSync as su,realpathSync as r0,renameSync as i0,rmSync as uh,statSync as o0,writeFileSync as s0}from"node:fs";import{dirname as u0}from"node:path";function ch(e){return`${e}.ttheme.bak`}var c0=/^(?:#|--) ttheme begin$|path = "ttheme-/m;function uu(e){let n=ch(e);if(sr(e)&&!sr(n)&&!c0.test(su(e,"utf8")))n0(e,n)}function me(e,n){let t=sr(e)?r0(e):e;t0(u0(t),{recursive:!0});let r=`${t}.ttheme-${process.pid}`;if(s0(r,n),sr(t))e0(r,o0(t).mode&4095);i0(r,t)}function ci(e,n){if((sr(e)?su(e,"utf8"):void 0)===n)return!1;return uu(e),me(e,n),!0}function ah(e,n){let t=ch(e),r=sr(t)?su(t,"utf8"):void 0;if(n===""&&r===void 0)return uh(e,{force:!0}),"removed";if(me(e,n),r===void 0||r===n)return uh(t,{force:!0}),"restored";return"kept backup"}var ko={width:2560,height:1550},d0=2560,g0=0.1,m0=0.99,p0=2,_n={tall:1.15,reach:0.4,widest:0.95,headroom:0.04,margin:0.03,stands:12},w0=Ze(au("#19161e","#9b86c8",0.2)),b0="shelf",So="originals",$0="images.json",cu=1;function au(e,n,t){let r=Je(e),i=Je(n);return`#${r.map((o,s)=>Math.round(o+((i[s]??0)-o)*t).toString(16).padStart(2,"0")).join("")}`}function k0(e,n){if(n==="background"||n==="foreground"||n==="cursor")return e[n];if(n==="selection"&&e.selection)return e.selection;let t=/^ansi(\d|1[0-5])$/.exec(n),r=t?e.ansi[Number(t[1])]:void 0;if(!r)throw Error(`${e.name} has no slot ${n}`);return r}function fh(e){if(e(1))return 1;let n=0,t=1;for(let r=0;r<40;r++){let i=(n+t)/2;if(e(i))n=i;else t=i}return n}function hh(e,n){let t=k0(e,n),i=fh((a)=>aa({name:e.name,background:au(e.background,t,a),foreground:e.foreground,ansi:e.ansi,waive:e.waived??[]}).length===0),o=fh((a)=>Ze(au(e.background,t,a))<=w0),s=Math.floor(Math.min(i,o)*1000)/1000,u=Je(e.background),c=Math.hypot(...Je(t).map((a,f)=>(a-(u[f]??0))*s));return{slot:n,color:t,cap:i,matched:o,opacity:s,reach:c}}function cr(e,n){let t=hh(e,"cursor");if(t.opacity>=g0)return t;return n.filter((r)=>r!=="cursor"&&r!=="background").map((r)=>hh(e,r)).reduce((r,i)=>i.reach>r.reach?i:r,t)}function y0(e){return kf(e)??{x:0,y:0,w:e.width,h:e.height}}function gu(e,n){if(e<=0||n<=0)return ko;let t=Math.min(1,ko.width/Math.max(e,n));return{width:Math.round(e*t),height:Math.round(n*t)}}function bh(e,n,t,r){if(r<_n.stands){let c=e.w*t>e.h*n?{x:e.x+(e.w-e.h*n/t)/2,y:e.y,w:e.h*n/t,h:e.h}:{x:e.x,y:e.y,w:e.w,h:e.w*t/n};return{crop:c,at:{x:0,y:0,w:n,h:t},focus:(c.y-e.y+c.h/2)/e.h}}let i=Math.max(_n.tall*t,_n.reach*n*e.h/e.w),o=i*e.w/e.h;if(o>_n.widest*n)o=_n.widest*n,i=o*e.h/e.w;let s=_n.headroom*t,u=Math.min(1,(t-s)/i);return{crop:{x:e.x,y:e.y,w:e.w,h:e.h*u},at:{x:n*(1-_n.margin)-o,y:s,w:o,h:i*u},focus:Math.min(1,(t/2-s)/i)}}function $h(e,n){return 0.299*(e[n]??0)+0.587*(e[n+1]??0)+0.114*(e[n+2]??0)}function E0(e,n){let t=new Uint32Array(256),r=Math.max(1,Math.floor(n.w*n.h/400000)),i=0;for(let s=0;s<n.w*n.h;s+=r){let u=((n.y+Math.floor(s/n.w))*e.width+n.x+s%n.w)*4;if((e.data[u+3]??0)>=128){let c=Math.round($h(e.data,u));t[c]=(t[c]??0)+1,i++}}let o=0;for(let s=0;s<256&&i>0;s++)if(o+=t[s]??0,o>=i*m0)return Math.min(p0,Math.max(1,255/Math.max(1,s)));return 1}function S0(e,n){let t=new Uint8Array(e.width*e.height);for(let r=0;r<t.length;r++){let i=r*4;t[r]=Math.round(Math.min(255,$h(e.data,i)*n)*(e.data[i+3]??0)/255)}return{width:e.width,height:e.height,data:t}}function yo(e,n,t,r){let i=new Float32Array(t*r),o=Math.max(0,Math.round(n.at.x)),s=Math.max(0,Math.round(n.at.y)),u=Math.min(t,Math.round(n.at.x+n.at.w)),c=Math.min(r,Math.round(n.at.y+n.at.h));if(u>o&&c>s){let a=n.crop.w/n.at.w,f=n.crop.h/n.at.h,h={x:n.crop.x+(o-n.at.x)*a,y:n.crop.y+(s-n.at.y)*f,w:(u-o)*a,h:(c-s)*f},l=Sf(e,h,u-o,c-s);for(let d=s;d<c;d++)i.set(l.data.subarray((d-s)*(u-o),(d-s+1)*(u-o)),d*t+o)}return{width:t,height:r,data:i}}function kh(e){let n=y0(e);return{box:n,clear:jn(e,n),ink:S0(e,E0(e,n))}}function yh(e,n,t,r){let{box:i,clear:o,ink:s}=kh(e),u=bh(i,n,t,o),c=Math.min(1,d0/Math.max(i.w,i.h)),a={x:0,y:0,w:Math.round(i.w*c),h:Math.round(i.h*c)},f=yo(s,{crop:i,at:a,focus:u.focus},a.w,a.h),h=yo(s,u,n,t);return{figure:Yr(ho(f,r*a.w*u.crop.w/(i.w*u.at.w))),fill:Yr(ho(h,r)),focus:u.focus}}function M0(e,n,t,r){let i=Je(n),o=Je(t),s=new Uint8Array(e.width*e.height*4);for(let u=0;u<e.data.length;u++){let c=(e.data[u]??0)/255*r;for(let a=0;a<3;a++)s[u*4+a]=Math.round((i[a]??0)+((o[a]??0)-(i[a]??0))*c);s[u*4+3]=255}return{width:e.width,height:e.height,data:s}}function Eh(e,n,t,r,i,o){let{box:s,clear:u,ink:c}=kh(e),a=yo(c,bh(s,r,i,u),r,i);return M0(Yr(ho(a,o)),n.background,t.color,t.opacity)}function Pe(e){return Y(e,"ttheme","backgrounds")}function fu(e){return Y(e,$0)}function It(e){try{return Eo(e,"utf8")}catch{return}}function it(e){try{return h0(e)}catch{return[]}}function ze(e){let n=It(fu(e));if(n===void 0)return I0(e);let t=JSON.parse(n);if(t.version!==cu)throw Error(`${fu(e)} is version ${t.version} — this ttheme reads version ${cu}`);return t}function v0(e,n){let t=n.pictures.findIndex((i)=>i.key===n.active),r=n.pictures[t];return[...r.from?[`# from ${r.from}`]:[],`# image ${r.key} ${t+1}/${n.pictures.length}`,`background-image = ${Y(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(`
251
+ `)}function Nt(e,n,t){me(fu(e),`${JSON.stringify(n,null,2)}
252
+ `);for(let r of t){let i=n.palettes[r],o=Y(e,`${Jn(r)}.conf`);if(i)me(o,v0(e,i));else ur(o,{force:!0})}}function Sh(e,n){return it(e).filter((t)=>t.startsWith(`${n}.`)||t.startsWith(`${n}@`))}function mu(e,n){for(let t of Sh(e,n))ur(Y(e,t),{force:!0})}function Mh(e,n){mu(e,n.stem);for(let t of[n.original,n.cut])if(t)ur(Y(e,t),{force:!0})}function lh(e,n,t,r){let i=wh(/^background-image\s*=\s*(.*?)\s*$/m.exec(n??"")?.[1]??"");if(!i.startsWith(`${e}.`)||!/^\.[0-9a-f]{8}@fill-\d+\.png$/.test(i.slice(e.length)))return;let o=i.slice(0,i.indexOf("@")),s=r??/^# image (\S+)$/m.exec(n??"")?.[1]??`picture_${o.slice(e.length+1)}`,u=/^# from (.+)$/m.exec(n??"")?.[1],c=Number(/^background-image-opacity\s*=\s*(\S+)/m.exec(n??"")?.[1]??1),a=t.find((f)=>f.startsWith(`${e}-${s}.`));return{key:s,stem:o,fill:i,opacity:Number.isFinite(c)?c:1,...u?{from:u}:{},...a?{original:Y(So,a)}:{}}}function dh(e,n){if(du(e))ph(e,n)}function I0(e){let n={version:cu,palettes:{}};if(!du(e))return n;let t=it(Y(e,So)),r=it(e).filter((o)=>o.endsWith(".conf")&&o!=="shown.conf"&&!/\.(tune|off)\.conf$/.test(o)).map((o)=>o.slice(0,-5)),i=Y(e,b0);for(let o of new Set([...r,...it(i)])){let s=[],u=lh(o,It(Y(e,`${o}.conf`)),t);if(u)dh(Y(e,`${o}.tune.conf`),Y(e,`${u.stem}.tune.conf`)),dh(Y(e,`${o}.off.conf`),Y(e,`${u.stem}.off.conf`)),s.push(u);for(let c of it(Y(i,o))){let a=Y(i,o,c),f=lh(o,It(Y(a,".conf")),t,c);if(!f)continue;for(let h of it(a)){let l=h===".tune.conf"||h===".off.conf"?`${f.stem}${h}`:`${o}${h}`;if(h!==".conf")ph(Y(a,h),Y(e,l))}ur(a,{recursive:!0}),s.push(f)}if(it(Y(i,o)).length===0)ur(Y(i,o),{recursive:!0,force:!0});if(s.length>0)s.sort((c,a)=>c.key<a.key?-1:c.key>a.key?1:0),n.palettes[o]={active:(u??s[0]).key,pictures:s}}if(it(i).length===0)ur(i,{recursive:!0,force:!0});return Nt(e,n,Object.keys(n.palettes)),n}function gh(e,n,t){return n.startsWith("~/")?Y(t,n.slice(2)):l0(n)?n:Y(e,n)}function vh(e,n,t){let r=new Map,i=(u,c)=>{let a=It(u);if(a===void 0)return!1;for(let f of a.split(`
253
+ `)){let h=/^([a-z-]+)\s*=\s*(.*?)\s*$/.exec(f);if(h?.[1]==="config-file"&&c<4)i(gh(e,h[2].replace(/^\?/,""),t),c+1);else if(h&&/^background-image(?:-fit|-opacity)?$/.test(h[1]))r.set(h[1],h[2])}return!0};if(!i(Y(e,`${Jn(n)}.conf`),0))return;let o=r.get("background-image")??"";if(o==="")return;let s=Number(r.get("background-image-opacity")??1);return{image:gh(e,o,t),opacity:Number.isFinite(s)?s:1,cover:r.get("background-image-fit")==="cover"}}function Ot(e){return`${e.site}_${e.id}`}function Ih(e,n,t){let r=Pe(e),i=ze(r),o=i.palettes[n];if(!o||o.pictures.length<2)throw Error(`${n} has no other image`);let s=o.pictures.length,u=(o.pictures.findIndex((c)=>c.key===o.active)+t+s)%s;return o.active=o.pictures[u].key,Nt(r,i,[n]),{key:o.active,at:u+1,of:s}}function Nh(e,n){let t=Pe(e),r=ze(t),i=r.palettes[n];if(!i)throw Error(`${n} has no image`);let o=i.pictures.findIndex((c)=>c.key===i.active),[s]=i.pictures.splice(o,1);Mh(t,s);let u=i.pictures[o%Math.max(i.pictures.length,1)];if(u)i.active=u.key;else delete r.palettes[n];return Nt(t,r,[n]),{key:s.key,left:i.pictures.length}}function Oh(e,n,t,r){let i=Xr(t.figure,r),o=Xr(t.fill,r),s=`${Jn(e)}.${mh("sha1").update(n).update(i).update(o).digest("hex").slice(0,8)}`,u=`${s}@fill-${Math.round(t.focus*100)}.png`;return{stem:s,fill:u,files:[[`${s}.png`,i],[u,o]]}}function hu(e,n){return Y(So,`${Jn(e)}-${n}`)}function pu(e,n){return n.map(([t,r])=>{let i=Y(e,t);return me(i,r),i})}function Mo(e,n,t,r,i,o,s){let u=Pe(e),c=n.name,a=Ot(i),f=ze(u),h=f.palettes[c]??{active:a,pictures:[]},l=gu(o.width,o.height),d=Oh(c,a,yh(r,l.width,l.height,s),t.color),g=hu(c,a),m={key:a,stem:d.stem,fill:d.fill,opacity:t.opacity,tone:t.color,blur:s,window:l,...i.from?{from:i.from}:{},original:`${g}.${i.ext}`,...i.cut?{cut:`${g}.cut.png`}:{}},$=h.pictures.find((v)=>v.key===a);if($)Mh(u,$);f0(Y(u,So),{recursive:!0});let S=pu(u,[...d.files,[m.original,i.bytes],...m.cut?[[m.cut,Ds(Zr(r))]]:[]]);return h.pictures=$?h.pictures.map((v)=>v===$?m:v):[...h.pictures,m],h.active=a,f.palettes[c]=h,Nt(u,f,[c]),[...S,Y(u,`${Jn(c)}.conf`)]}function Rh(e,n,t){let r=Pe(e),i=ze(r),o=i.palettes[n];if(o?.pictures.some((s)=>s.key===t)&&o.active!==t)o.active=t,Nt(r,i,[n])}function wu(e,n){let t=ze(Pe(e)).palettes[n];if(!t)return[];return[...t.pictures.filter((i)=>i.key===t.active),...t.pictures.filter((i)=>i.key!==t.active)]}var lu="top-right";function N0(e,n,t,r,i,o,s,u=-1){let c=Math.trunc,a=(o-1)%3,f=c((o-1)/3),h=t*n>=r*e!==!s,l=h?c(i*t/100):c(i*r*e/(100*n)),d=h?c(i*t*n/(100*e)):c(i*r/100),g=c(a*(t-l)/2),m=c(f*(r-d)/2);if(u>=0){if(l>t)g=c((t-l)/2);if(d>r)m=Math.max(r-d,Math.min(0,c(r/2)-c(u*d/100)))}return{x:g,y:m,w:l,h:d}}function bu(e,n){let t=It(Y(e,`${n.stem}.tune.conf`));if(t===void 0)return{};let r=(a)=>new RegExp(`^${a}\\s*=\\s*(.*?)\\s*$`,"m").exec(t)?.[1]??"",i=wh(r("background-image")),o=/@(\d+)-/.exec(i)?.[1],s=/@fill-\d+\.png$/.test(i)?"fill":o?Number(o):r("background-image-fit")==="cover"?"fill":100,u=r("background-image-position").replace("center-center","center")||"center",c=Number(r("background-image-opacity")||1);return{...s!=="fill"?{size:s}:{},...u!==lu?{position:u}:{},...Number.isFinite(c)&&c!==n.opacity?{opacity:c}:{}}}function $u(e,n,t,r,i){let o=t.size??"fill",s=t.position??lu,u=t.opacity??n.opacity;if(o==="fill"&&s===lu&&u===n.opacity)return;let c=vt.indexOf(s)+1,a=Y(e,`${n.stem}.png`),f=Y(e,n.fill),h=!0,l=typeof o==="number"&&(o>100||!r&&s!=="center");if(o===100&&!l)f=a,h=!1;else if(typeof o==="number"){if(!n.tone)throw Error(`${n.stem} was drawn before pictures kept their tone — init draws it again`);let g=Zr(bt(new Uint8Array(Eo(a)))),{width:m,height:$}=l?ko:g,S=l?Number(/@fill-(\d+)\.png$/.exec(n.fill)?.[1]??50):-1,v=N0(g.width,g.height,m,$,o,c,!1,S);f=Y(e,`${n.stem}@${o}-${s}${l?`-${m}x${$}`:""}.png`);let k={x:0,y:0,w:g.width,h:g.height};me(f,Xr(Yr(yo(g,{crop:k,at:v,focus:S},m,$)),n.tone)),h=l}let d=Y(e,`${n.stem}.tune.conf`);return me(d,[`background-image = ${f.startsWith(`${i}/`)?`~${f.slice(i.length)}`:f}`,`background-image-fit = ${h?"cover":"contain"}`,`background-image-position = ${s}`,`background-image-opacity = ${u}`,""].join(`
254
+ `)),d}function Fh(e){let n=new Map;for(let[t,r]of Object.entries(ze(Pe(e)).palettes)){let[,i,o]=/^([a-z.]+)_(\d+)$/.exec(r.active)??[];if(i&&o)n.set(t,{site:i,id:Number(o)})}return n}function O0(e){try{let n=kt(new Uint8Array(Eo(e)));return n?{width:n.width,height:n.height}:void 0}catch{return}}function vo(e,n,t,r,i,o,s,u,c){let a=Pe(e),f=t.window??O0(Y(a,t.fill))??ko,h=Oh(n,t.key,yh(r,f.width,f.height,o),i.color),l={...t,stem:h.stem,fill:h.fill,opacity:i.opacity,tone:i.color,blur:o,window:f,...c?{cut:`${hu(n,t.key)}.cut.png`}:{}};if(c)me(Y(a,`${hu(n,t.key)}.cut.png`),Ds(Zr(r)));if(h.stem===t.stem)return l;pu(a,h.files),$u(a,l,bu(a,t),s,u);let d=Y(a,`${t.stem}.off.conf`);if(du(d))a0(d,Y(a,`${l.stem}.off.conf`));return l}function Ph(e,n){let t=Pe(e),r=ze(t),i=new Set,o=[];for(let{name:s,picture:u}of n){let c=r.palettes[s],a=c?.pictures.findIndex((h)=>h.key===u.key)??-1,f=c?.pictures[a];if(!c||!f)continue;if(c.pictures[a]=u,i.add(s),f.stem!==u.stem)o.push(f.stem)}if(i.size===0)return;Nt(t,r,[...i]);for(let s of o)mu(t,s)}function R0(e,n,t,r){let i=(c)=>c.replace(/^background-image-opacity = (\S+)$/m,(a,f)=>Number(f)===t.opacity?`background-image-opacity = ${r.opacity}`:a);if(t.tone===r.color){let c=Y(e,`${t.stem}.tune.conf`),a=It(c);if(a!==void 0)me(c,i(a));return{...t,opacity:r.opacity}}let o=Sh(e,t.stem).filter((c)=>c.endsWith(".png")).map((c)=>{let a=new Uint8Array(Eo(Y(e,c)));return[c,If(a,r.color)??Xr(Zr(bt(a)),r.color)]}),s=(c)=>o.find(([a])=>a===c)?.[1]??new Uint8Array,u=`${Jn(n)}.${mh("sha1").update(t.key).update(s(`${t.stem}.png`)).update(s(t.fill)).digest("hex").slice(0,8)}`;pu(e,o.map(([c,a])=>[u+c.slice(t.stem.length),a]));for(let c of["tune","off"]){let a=It(Y(e,`${t.stem}.${c}.conf`));if(a!==void 0)me(Y(e,`${u}.${c}.conf`),i(a.split(t.stem).join(u)))}return{...t,stem:u,fill:u+t.fill.slice(t.stem.length),opacity:r.opacity,tone:r.color}}function Ah(e,n){let t=Pe(e),r=ze(t),i=[],o=[];for(let[s,u]of Object.entries(r.palettes)){let c=n.get(s),a=u.pictures.filter((f)=>c&&f.tone&&(f.tone!==c.color||f.opacity!==c.opacity));if(!c||a.length===0)continue;u.pictures=u.pictures.map((f)=>{if(!a.includes(f))return f;let h=R0(t,s,f,c);if(h.stem!==f.stem)o.push(f.stem);return h}),i.push(s)}if(i.length>0){Nt(t,r,i);for(let s of o)mu(t,s)}return i}function $n(e){let{slot:n,color:t,opacity:r}=cr({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:Vt(e),...e.waive.length>0?{waived:e.waive}:{},backdrop:{slot:n,color:t,opacity:r},...e.pictures?{pictures:e.pictures}:{}}}function fn(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 F0=6,P0=["ansi1","ansi2","ansi4","ansi3","ansi5","ansi6"];function Io(e){let n=(o)=>o.startsWith("ansi")?e.ansi[Number(o.slice(4))]:o==="foreground"?e.foreground:o==="cursor"?e.cursor:o==="selection"?e.selection:void 0,t=(o)=>o.startsWith("ansi")?`ansi${Number(o.slice(4))%8}`:o,r=new Set,i=[];for(let o of["foreground",...e.signatureSlots,...P0]){let s=n(o);if(i.length===F0||!s||r.has(t(o))||i.includes(s))continue;r.add(t(o)),i.push(s)}return i}function hn(e){return e.filter((n)=>n.default!==!0)}function ai(){return{version:qe.version,gate:pt,placement:_n,palettes:[]}}function A0(e){let[n]=e;if(!n)throw Error("manifest needs at least one theme");return{...ai(),palettes:e.map($n)}}var ku={id:"meta",emitShared(e){return[{path:"manifest.json",content:`${JSON.stringify(A0(e),null,2)}
255
+ `}]}};var H0=["ghostty","kitty","alacritty","wezterm","iterm2","windows-terminal","warp"],L0=[{section:"tab",title:"This tab"},{section:"startup",title:"New tabs"},{section:"catalog",title:"Palettes"},{section:"own",title:"Your own"},{section:"setup",title:"Setup"}],hi=[{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 from the catalog in a live picker",section:"catalog",start:"install or drop palettes — every market you added, in one picker"},{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, installed"}}},{name:"add",args:["<palette...>"],about:"install palettes from the catalog, or from a share code: ttheme add tt1:…",section:"catalog"},{name:"remove",args:["<palette...>"],about:"uninstall palettes",section:"catalog"},{name:"update",args:[],about:"refresh every market you added",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, with how many palettes each holds"],["add <source>","add one: a repository (alice/ttheme-pastel), a folder, or official"],["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:H0,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 fi(e){let n=Object.entries(e.flags??{}).map(([t,{value:r}])=>`[--${t}${r?` ${r}`:""}]`);return[e.name,...n,...e.args].join(" ")}function yu(e,n=Math.max(...e.map(([t])=>t.length))){return e.map(([t,r])=>` ${t.padEnd(n)} ${r}`)}var T0=[["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 new rei --from rei","your own rei, <you>@<market>/rei, to edit and share"]];function li(e,n=!1){let t=hi.filter((s)=>!s.hidden&&!(n&&s.section==="setup")),r=L0.filter(({section:s})=>t.some((u)=>u.section===s)),i=[...n?["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 s=t.filter((c)=>c.start),u=Math.max(...r.map(({title:c})=>c.length));return["Usage: ttheme <command>","",qe.description,"","Start here",...yu(s.map((c)=>[fi(c),c.start])),"",...r.map(({section:c,title:a})=>`${a.padEnd(u)} ${t.filter((f)=>f.section===c).map((f)=>f.name).join(" · ")}`),"",...i].join(`
256
+ `)}let o=Math.max(...t.map((s)=>fi(s).length));return["Usage: ttheme <command>","",qe.description,...r.flatMap(({section:s,title:u})=>["",u,...yu(t.filter((c)=>c.section===s).map((c)=>[fi(c),c.about]),o)]),"","Examples",...yu(T0),"",...i].join(`
257
+ `)}import{readFileSync as G0}from"node:fs";import{join as U0}from"node:path";var No=["ghostty","kitty","alacritty","wezterm","iterm2","windows-terminal","warp"],Gh="# ttheme begin",Uh="# ttheme end",di=/# ttheme begin\n[\s\S]*?# ttheme end\n?/;function gi(e,n){let t=`${Gh}
258
258
  ${n}
259
- ${tf}
260
- `;if(ti.test(e))return e.replace(ti,t);if(e==="")return t;return`${e.replace(/\n*$/,`
259
+ ${Uh}
260
+ `;if(di.test(e))return e.replace(di,t);if(e==="")return t;return`${e.replace(/\n*$/,`
261
261
  `)}
262
- ${t}`}function ii(e){let n=e.replace(/\n?# ttheme begin\n[\s\S]*?# ttheme end(?=\n|$)/,"");if(n===e)return e;return n.trim()===""?"":n.replace(/\n*$/,`
263
- `)}function St(e,n){let t=e.replace(ti,"");return new RegExp(String.raw`^[ \t]*${n}(?:[ \t]*=|[ \t]+\S)`,"m").test(t)}function mo(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 rf(e,n,t=""){let r=[];if(!St(t,"command")){if(r.push(`command = ${e}/launch-tab.zsh`),!St(t,"shell-integration"))r.push("shell-integration = zsh")}if(n)r.push(`theme = ${fe(n)}`);return r.push(`config-file = ?${e}/backgrounds/shown.conf`),r.join(`
264
- `)}function of(e){return`source ${e}/ttheme.zsh`}var Xw="# ttheme settings — uncomment a line to change it; exported variables win over this file",oi={TTHEME_TAB_PALETTE:{doc:"# new tabs: off keeps the configured terminal theme, seq rotates through the palettes (default off)",default:"off"},TTHEME_ANNOUNCE:{doc:'# the palette notice under "Last login:": 1 shows it, 0 silences it (default 1)',default:"1"},TTHEME_FX:{doc:"# search hint animation: typewriter, decode or glitch (default typewriter)",default:"typewriter"},TTHEME_SORT:{doc:"# series and palettes in ttheme and preview: abc sorts them by name, series keeps the order they were added (default abc)",default:"abc"},TTHEME_FIND_RATING:{doc:"# the ratings find lists, any of safe, questionable and explicit, each booru read in its own rating vocabulary (default safe)",default:"safe"},TTHEME_FIND_BLOCK:{doc:'# the posts find drops by tag: nudity, underwear, both, or none to keep them all (default "nudity underwear")',default:"nudity underwear"},TTHEME_FIND_POSTS:{doc:"# what find lists first: all is every post of the character, cutouts are the transparent ones (default all)",default:"all"},TTHEME_FIND_SOLO:{doc:"# on keeps the danbooru posts tagged solo, the character alone; off lists every post (default on)",default:"on"},TTHEME_FIND_CUTOUTS:{doc:'# the tags find calls a transparent cutout, per site as key=tag,tag pairs — e.g. "konachan=transparent,vector yande=transparent_png" (default the built-in tags)',default:""},TTHEME_FIND_ORDER:{doc:"# the order find lists posts in: fit ranks each page by how well it makes a backdrop, newest or score (default fit)",default:"fit"},TTHEME_FIND_SETS:{doc:"# runs of the same picture at the same size from one uploader: fold shows them as one tile, show lists each (default fold)",default:"fold"},TTHEME_FIND_REMOVE_BG:{doc:"# an opaque picture tried on in find: on cuts the character out with macOS Vision, off leaves it as it is (default on)",default:"on"},TTHEME_FIND_UNBLOCK:{doc:"# when a network blocks a booru by name, 1 sends find through a local proxy that splits the TLS handshake — find offers to turn it on (default 0)",default:"0"},TTHEME_FIND_HOSTS:{doc:'# send a find site somewhere else, as key=https://host pairs — e.g. "danbooru=https://safebooru.donmai.us" (default none)',default:""}};function tu(e,n){let t=`: \${${e}:=${n}}`;return oi[e]?.default===n?`# ${t}`:t}function sf(e){return new RegExp(String.raw`^#? ?: \$\{${e}[^\n]*$`,"m")}function Vw(e,n){if(sf(n).test(e))return e;let t=oi[n];return`${e.replace(/\n*$/,`
262
+ ${t}`}function mi(e){let n=e.replace(/\n?# ttheme begin\n[\s\S]*?# ttheme end(?=\n|$)/,"");if(n===e)return e;return n.trim()===""?"":n.replace(/\n*$/,`
263
+ `)}function Rt(e,n){let t=e.replace(di,"");return new RegExp(String.raw`^[ \t]*${n}(?:[ \t]*=|[ \t]+\S)`,"m").test(t)}function Oo(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 jh(e,n,t=""){let r=[];if(!Rt(t,"command")){if(r.push(`command = ${e}/launch-tab.zsh`),!Rt(t,"shell-integration"))r.push("shell-integration = zsh")}if(n)r.push(`theme = ${he(n)}`);return r.push(`config-file = ?${e}/backgrounds/shown.conf`),r.join(`
264
+ `)}function Ch(e){return`source ${e}/ttheme.zsh`}var j0="# ttheme settings — uncomment a line to change it; exported variables win over this file",ar={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 danbooru posts tagged solo, the character alone; off lists every post (default on)",default:"on"},TTHEME_FIND_CUTOUTS:{doc:'# the tags find calls a transparent cutout, per site as key=tag,tag pairs — e.g. "konachan=transparent,vector yande=transparent_png" (default the built-in tags)',default:""},TTHEME_FIND_ORDER:{doc:"# the order find lists posts in: fit ranks each page by how well it makes a backdrop, newest or score (default fit)",default:"fit"},TTHEME_FIND_SETS:{doc:"# runs of the same picture at the same size from one uploader: fold shows them as one tile, show lists each (default fold)",default:"fold"},TTHEME_FIND_REMOVE_BG:{doc:"# an opaque picture tried on in find: on cuts the character out with macOS Vision, off leaves it as it is (default on)",default:"on"},TTHEME_FIND_UNBLOCK:{doc:"# when a network blocks a booru by name, 1 sends find through a local proxy that splits the TLS handshake — find offers to turn it on (default 0)",default:"0"},TTHEME_FIND_HOSTS:{doc:'# send a find site somewhere else, as key=https://host pairs — e.g. "danbooru=https://safebooru.donmai.us" (default none)',default:""}};function Eu(e,n){let t=`: \${${e}:=${n}}`;return ar[e]?.default===n?`# ${t}`:t}function Jh(e){return new RegExp(String.raw`^#? ?: \$\{${e}[^\n]*$`,"m")}function C0(e,n){if(Jh(n).test(e))return e;let t=ar[n];return`${e.replace(/\n*$/,`
265
265
  `)}
266
266
  ${t.doc}
267
- ${tu(n,t.default)}
268
- `}var uf=Object.keys(oi);function ru(){let e=Object.entries(oi).map(([n,t])=>`${t.doc}
269
- ${tu(n,t.default)}`);return`${[Xw,...e].join(`
267
+ ${Eu(n,t.default)}
268
+ `}var _h=Object.keys(ar),J0=8;function fr(e){let n="";try{n=G0(U0(e,"ttheme","config.zsh"),"utf8")}catch{}let t=/^: \$\{TTHEME_BG_BLUR:=([^}\n]*)\}/m.exec(n)?.[1]??ar.TTHEME_BG_BLUR.default,r=Number(t.replace(/^(["'])(.*)\1$/,"$2"));return Number.isFinite(r)?Math.min(J0,Math.max(0,r)):0}function Su(){let e=Object.entries(ar).map(([n,t])=>`${t.doc}
269
+ ${Eu(n,t.default)}`);return`${[j0,...e].join(`
270
270
 
271
271
  `)}
272
- `}function cf(e,n,t){let r=tu(n,t),i=sf(n);if(i.test(e))return e.replace(i,r);return`${e.replace(/\n*$/,`
272
+ `}function Wh(e,n,t){let r=Eu(n,t),i=Jh(n);if(i.test(e))return e.replace(i,r);return`${e.replace(/\n*$/,`
273
273
  `)}
274
274
  ${r}
275
- `}function af(e){if(e==="")return ru();return Object.keys(oi).reduce(Vw,e)}function hf(e,n,t=""){return[...e?[`include themes/${fe(e)}.conf`]:[],`watcher ${n}`,...["window_logo_scale 100","window_logo_alpha 1"].filter((r)=>!St(t,r.split(" ")[0]))].join(`
276
- `)}function ff(e){let n=e.replace(ti,"");return/^[ \t]*\[colors[\].]/m.test(n)||/^[ \t]*colors[ \t]*[.=]/m.test(n)}var zw=/^[ \t]*\[general\][ \t]*(?:#.*)?$/m,Dh=/^[ \t]*\[/m,xh=/^[ \t]*import[ \t]*=/m,Bw=/^[ \t]*general[ \t]*[.=]/m;function Dw(e){return e?`[general]
277
- import = ["${e}"]`:""}function si(e,n){let t=e.replace(ti,""),r=zw.exec(t);if(!r){let c=t.search(Dh),a=c<0?t:t.slice(0,c);if(Bw.test(t)||xh.test(a))return;return ri(e,Dw(n))}let i=r.index+r[0].length,o=t.slice(i),s=o.search(Dh);if(xh.test(s<0?o:o.slice(0,s)))return;let u=n?`import = ["${n}"]
275
+ `}function Kh(e){if(e==="")return Su();return Object.keys(ar).reduce(C0,e)}function qh(e,n,t=""){return[...e?[`include themes/${he(e)}.conf`]:[],`watcher ${n}`,...["window_logo_scale 100","window_logo_alpha 1"].filter((r)=>!Rt(t,r.split(" ")[0]))].join(`
276
+ `)}function Qh(e){let n=e.replace(di,"");return/^[ \t]*\[colors[\].]/m.test(n)||/^[ \t]*colors[ \t]*[.=]/m.test(n)}var _0=/^[ \t]*\[general\][ \t]*(?:#.*)?$/m,Hh=/^[ \t]*\[/m,Lh=/^[ \t]*import[ \t]*=/m,W0=/^[ \t]*general[ \t]*[.=]/m;function K0(e){return e?`[general]
277
+ import = ["${e}"]`:""}function pi(e,n){let t=e.replace(di,""),r=_0.exec(t);if(!r){let c=t.search(Hh),a=c<0?t:t.slice(0,c);if(W0.test(t)||Lh.test(a))return;return gi(e,K0(n))}let i=r.index+r[0].length,o=t.slice(i),s=o.search(Hh);if(Lh.test(s<0?o:o.slice(0,s)))return;let u=n?`import = ["${n}"]
278
278
  `:"";return`${t.slice(0,i)}
279
- ${nf}
280
- ${u}${tf}${o}`}var ef=/-- ttheme begin\n[\s\S]*?-- ttheme end\n?/,xw=/^return config[ \t]*$/gm;function lf(e){return`dofile(${JSON.stringify(e)})(config)`}var df=`local wezterm = require 'wezterm'
279
+ ${Gh}
280
+ ${u}${Uh}${o}`}var Th=/-- ttheme begin\n[\s\S]*?-- ttheme end\n?/,q0=/^return config[ \t]*$/gm;function Yh(e){return`dofile(${JSON.stringify(e)})(config)`}var Zh=`local wezterm = require 'wezterm'
281
281
  local config = wezterm.config_builder()
282
282
 
283
- `;function gf(e){let n=e.replace(/-- ttheme begin\n[\s\S]*?-- ttheme end\n\n?/,"");return n===`${df}return config
284
- `?"":n}function ui(e,n){let t=`-- ttheme begin
283
+ `;function Xh(e){let n=e.replace(/-- ttheme begin\n[\s\S]*?-- ttheme end\n\n?/,"");return n===`${Zh}return config
284
+ `?"":n}function wi(e,n){let t=`-- ttheme begin
285
285
  ${n}
286
286
  -- ttheme end
287
- `;if(ef.test(e))return e.replace(ef,t);if(e==="")return`${df}${t}
287
+ `;if(Th.test(e))return e.replace(Th,t);if(e==="")return`${Zh}${t}
288
288
  return config
289
- `;let r=[...e.matchAll(xw)].at(-1);if(r?.index===void 0)return;return`${e.slice(0,r.index)}${t}
290
- ${e.slice(r.index)}`}var mf="[appearance.themes]";function pf(e){let n=e.findIndex((r)=>r.trim()===mf);if(n<0)return;let t=e.findIndex((r,i)=>i>n&&r.trimStart().startsWith("["));return[n,t<0?e.length:t]}function po(e){let n=e.split(`
291
- `),t=pf(n);if(!t)return;return n.slice(t[0]+1,t[1]).find((i)=>/^theme\s*=/.test(i))?.replace(/^theme\s*=\s*/,"").trim()}function wf(e){return`{ custom = { name = "${e}", path = "${fe(e)}.yaml" } }`}function wo(e,n){let t=e.split(`
292
- `),r=pf(t);if(!r)return n===void 0?e:`${e.replace(/\n*$/,`
289
+ `;let r=[...e.matchAll(q0)].at(-1);if(r?.index===void 0)return;return`${e.slice(0,r.index)}${t}
290
+ ${e.slice(r.index)}`}var zh="[appearance.themes]";function Vh(e){let n=e.findIndex((r)=>r.trim()===zh);if(n<0)return;let t=e.findIndex((r,i)=>i>n&&r.trimStart().startsWith("["));return[n,t<0?e.length:t]}function Ro(e){let n=e.split(`
291
+ `),t=Vh(n);if(!t)return;return n.slice(t[0]+1,t[1]).find((i)=>/^theme\s*=/.test(i))?.replace(/^theme\s*=\s*/,"").trim()}function Bh(e){return`{ custom = { name = "${e}", path = "${he(e)}.yaml" } }`}function Fo(e,n){let t=e.split(`
292
+ `),r=Vh(t);if(!r)return n===void 0?e:`${e.replace(/\n*$/,`
293
293
  `)}
294
- ${mf}
294
+ ${zh}
295
295
  theme = ${n}
296
296
  `;let i=t.findIndex((o,s)=>s>r[0]&&s<r[1]&&/^theme\s*=/.test(o));if(i>=0)t.splice(i,1,...n===void 0?[]:[`theme = ${n}`]);else if(n!==void 0)t.splice(r[0]+1,0,`theme = ${n}`);return t.join(`
297
- `)}function iu(e,n,t=[]){for(let a of e)for(let h of[a.name,a.group,a.native??"",a.ansiSource])if(/["$`\\]/.test(h))throw Error(`${a.name}: "${h}" contains a character that breaks zsh quoting`);let r=Math.max(0,...e.map((a)=>a.name.length)),i=(a,h)=>` ${a.name.padEnd(r)} "${h}"`,o=(a)=>a.map((h)=>h.name).join(" "),s=an(e),u=(a)=>`'${a.replaceAll("'","'\\''")}'`,c=ei.filter((a)=>a.section!=="setup"&&!a.hidden);return["# Generated by `mise run build` — do not edit.","# Source of truth: themes/*.toml in the ttheme repo.","",`typeset -g TTHEME_VERSION=${_e.version}`,"",'# the palette new tabs open with, which the iTerm2 "ttheme · default" profile wears',`typeset -g TTHEME_STARTUP=${n??""}`,"","# the terminals ttheme is wired into: a picture change reaches every one of them, from whichever runs the shell",`typeset -ga TTHEME_TERMINALS=(${t.join(" ")})`,"","# the commands the shell layer knows (src/verbs.ts): help, completion and argument checks read them",`typeset -ga TTHEME_VERBS=(${c.map((a)=>a.name).join(" ")})`,`typeset -ga TTHEME_SHELL_VERBS=(${c.filter((a)=>a.shell).map((a)=>a.name).join(" ")})`,"typeset -gA TTHEME_VERB_ARGS=(",...c.map((a)=>` ${a.name} ${u(a.args.join(" "))}`),")","typeset -gA TTHEME_VERB_ABOUT=(",...c.map((a)=>` ${a.name} ${u(a.about)}`),")",`typeset -g TTHEME_HELP=${u(ni(!1,!0))}`,`typeset -g TTHEME_HELP_ALL=${u(ni(!0,!0))}`,"","# the settings config.zsh holds, handed to the CLI on every call",`typeset -ga TTHEME_SETTINGS=(${uf.join(" ")})`,"","# seed for `ttheme config` when no config.zsh exists yet",`typeset -g TTHEME_CONFIG_TEMPLATE='${ru().trimEnd().replaceAll("'","'\\''")}'`,"","typeset -gA TTHEME_PALETTE=(",...e.map((a)=>i(a,[a.background,a.foreground,a.cursor,a.selection,...a.ansi].join(" "))),")","","# series order: new tabs cycle through it and TTHEME_SORT=series lists it — the default role stays applyable but unlisted",`typeset -ga TTHEME_ORDER=(${o(s)})`,"","# the same palettes by series name, then palette name: TTHEME_SORT=abc lists them this way",`typeset -ga TTHEME_ABC=(${o(_r(s))})`,"","typeset -gA TTHEME_GROUP=(",...e.map((a)=>i(a,a.group)),")","","# original-language title, rendered dim next to the group","typeset -gA TTHEME_NATIVE=(",...e.filter((a)=>a.native).map((a)=>i(a,a.native??"")),")","","# the six colors a list row shows: foreground, the signature, then red and green","typeset -gA TTHEME_SWATCH=(",...e.map((a)=>i(a,lo(a).join(" "))),")","","# where each palette's 16 ANSI colors came from","typeset -gA TTHEME_SRC=(",...e.map((a)=>i(a,a.ansiSource)),")",""].join(`
298
- `)}var ou={id:"shell",emitShared(e){return[{path:"shell/palettes.zsh",content:iu(e.map(wn))}]}};var e0=["black","red","green","yellow","blue","magenta","cyan","white"];function $f(e,n){return[` ${e}:`,...e0.map((t,r)=>` ${t}: "${n[r]}"`)]}var ci={id:"warp",limits:"no selection color, and Warp paints one theme app-wide",emit(e){let n=[`name: "${e.name}"`,`background: "${e.background}"`,`foreground: "${e.foreground}"`,`accent: "${e.cursor}"`,`cursor: "${e.cursor}"`,`details: ${Qe(e.background)<0.18?"darker":"lighter"}`,"terminal_colors:",...$f("normal",e.ansi.slice(0,8)),...$f("bright",e.ansi.slice(8,16)),""].join(`
299
- `);return[{path:`warp/themes/${fe(e.name)}.yaml`,content:n}]}};var bf=(e)=>`[${e.map((n)=>`"${n}"`).join(", ")}]`,ai={id:"wezterm",limits:"OSC repaints per pane, pictures show per window",emit(e){let n=["[metadata]",`name = "${fe(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 = ${bf(e.ansi.slice(0,8))}`,`brights = ${bf(e.ansi.slice(8,16))}`,""].join(`
300
- `);return[{path:`wezterm/colors/${fe(e.name)}.toml`,content:n}]}},nr=(e)=>JSON.stringify(e);function kf(e){return["-- Generated by ttheme — rewritten on every add, remove and default; do not edit.","local wezterm = require 'wezterm'","",`local MODULE = ${nr(e.path)}`,`local COLORS = ${nr(e.colors)}`,`local BACKGROUNDS = ${nr(e.backgrounds)}`,`local STARTUP = ${e.startup?nr(fe(e.startup)):"nil"}`,"local PALETTES = {",...e.palettes.map((n)=>` [${nr(n.name)}] = ${nr(n.background)},`),"}","","local X = { left = 'Left', center = 'Center', right = 'Right' }","local Y = { top = 'Top', center = 'Middle', bottom = 'Bottom' }","local SIZE = { cover = 'Cover', contain = 'Contain', stretch = '100%' }","","local function locate(path)"," if path:sub(1, 2) == '~/' then"," return os.getenv('HOME') .. path:sub(2)"," elseif path:sub(1, 1) == '/' or path:match('^%a:[/\\\\]') then"," return path"," end"," return BACKGROUNDS .. '/' .. path","end","","local function read(path, into)"," local f = io.open(path, 'r')"," if not f then"," return false"," end"," for line in f:lines() do"," local key, value = line:match('^%s*([%w%-]+)%s*=%s*(.-)%s*$')"," if key == 'config-file' then"," read(locate((value:gsub('^%?', ''))), into)"," elseif key then"," into[key] = value"," end"," end"," f:close()"," return true","end","","local function layers(palette)"," local color = PALETTES[palette]"," local c = {}"," if not color or not read(BACKGROUNDS .. '/' .. ((palette: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(`
301
- `)}var Ef=["black","red","green","yellow","blue","purple","cyan","white"];function yf(e){return{name:fe(e.name),background:e.background,foreground:e.foreground,cursorColor:e.cursor,selectionBackground:e.selectionBackground,...Object.fromEntries(Ef.map((n,t)=>[n,e.ansi[t]])),...Object.fromEntries(Ef.map((n,t)=>[`bright${n[0]?.toUpperCase()}${n.slice(1)}`,e.ansi[t+8]]))}}function su(e,n,t){let r={...n&&t?{profiles:[{updates:n,colorScheme:fe(t)}]}:{},schemes:e.map(yf)};return`${JSON.stringify(r,null,2)}
302
- `}var hi={id:"windows-terminal",limits:"no kitty graphics, so no pictures; OSC repaints per pane",emit(e){return[{path:`windows-terminal/schemes/${fe(e.name)}.json`,content:`${JSON.stringify(yf(e),null,2)}
303
- `}]},emitShared(e){return[{path:"windows-terminal/ttheme.json",content:su(e)}]}};function fe(e){return`ttheme-${nt(e)}`}function Bt(e){return[`# ${e.name} — ${e.group}${e.native?` (${e.native})`:""}`,`# ANSI: ${e.ansiSource}`]}var vf=fi(import.meta.dirname,".."),t0=fi(vf,"themes"),uu=fi(vf,"dist"),$o=[Qr,Zr,qr,ai,Yr,hi,ci],r0=[ou,eu],hS=$o.map((e)=>e.id);async function bo({only:e}={}){if(typeof Bun>"u")throw Error("needs bun — run it from a checkout: bun src/bin.ts build");let n=e&&e.length>0?$o.filter((o)=>e.includes(o.id)):$o,t=Sh(t0),r=jc(t);if(r.length>0){for(let o of r)console.error(` ✗ ${o.theme} [${o.rule}] ${o.detail}`);throw Error(`${r.length} contrast violation(s). Fix the palette, or waive the rule in its [contrast] section with a reason.`)}if(n.length===$o.length)Sf(uu,{recursive:!0,force:!0});else for(let o of n)Sf(fi(uu,o.id),{recursive:!0,force:!0});let i=0;for(let o of[...n,...r0]){let s=t.flatMap((a)=>o.emit?.(a)??[]),u=o.emitShared?.(t)??[];for(let a of[...s,...u])await Bun.write(fi(uu,a.path),a.content),i++;let c=s.length>0?`${t.length} themes${o.limits?` (${o.limits})`:""}`:u.map((a)=>n0(a.path)).join(" ");console.log(` ${o.id.padEnd(16)} ${c}`)}console.log(`
304
- ${t.length} themes (${vh(t).length} in the new-tab rotation) -> ${i} files in dist/`)}import{spawnSync as cb}from"node:child_process";import{existsSync as fr,mkdirSync as ab,mkdtempSync as hb,readFileSync as Xo,rmSync as fb,writeFileSync as lb}from"node:fs";import{tmpdir as db}from"node:os";import{basename as gb,dirname as od,join as _u}from"node:path";import{styleText as vo}from"node:util";import{stdout as Kf,stdin as b0}from"node:process";import k0 from"node:readline";var Mf=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(n)=>{let t=0;e.lastIndex=0;while(e.test(n))t+=1;return n.length-t}})(),If=(e)=>{return e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510},Nf=(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 i0=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,o0=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Of=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,s0=/\t{1,1000}/y,Rf=/[\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,u0=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,c0=/\p{M}+/gu,a0={limit:1/0,ellipsis:""},Ff=(e,n={},t={})=>{let r=n.limit??1/0,i=n.ellipsis??"",o=n?.ellipsisWidth??(i?Ff(i,a0,t).width:0),s=0,u=t.controlWidth??0,c=t.tabWidth??8,a=t.emojiWidth??2,h=2,f=t.regularWidth??1,l=t.wideWidth??2,d=[[u0,f],[i0,0],[o0,u],[s0,c],[Rf,a],[Of,l]],g=0,p=0,k=e.length,y=0,M=!1,b=k,S=Math.max(0,r-o),m=0,P=0,E=0,R=0;e:while(!0){if(P>m||p>=k&&p>g){let N=e.slice(m,P)||e.slice(g,p);y=0;for(let H of N.replaceAll(c0,"")){let A=H.codePointAt(0)||0;if(If(A))R=2;else if(Nf(A))R=l;else R=f;if(E+R>S)b=Math.min(b,Math.max(m,g)+y);if(E+R>r){M=!0;break e}y+=H.length,E+=R}m=P=0}if(p>=k)break e;for(let N=0,H=d.length;N<H;N++){let[A,X]=d[N];if(A.lastIndex=p,A.test(e)){if(y=A===Of?Mf(e.slice(p,A.lastIndex)):A===Rf?1:A.lastIndex-p,R=y*X,E+R>S)b=Math.min(b,p+Math.floor((S-E)/X));if(E+R>r){M=!0;break e}E+=R,m=g,P=p,p=g=A.lastIndex;continue e}}p+=1}return{width:M?S:E,index:M?b:k,truncated:M,ellipsed:M&&r>=o}},Pf=Ff;var h0={limit:1/0,ellipsis:"",ellipsisWidth:0},f0=(e,n={})=>{return Pf(e,h0,n).width},Xe=f0;var ko="\x1B",Gf="›",l0=39,au="\x07",Uf="[",d0="]",jf="m",hu=`${d0}8;;`,Hf=new RegExp(`(?:\\${Uf}(?<code>\\d+)m|\\${hu}(?<uri>.*)${au})`,"y"),Lf=(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},Af=(e)=>`${ko}${Uf}${e}${jf}`,Tf=(e)=>`${ko}${hu}${e}${au}`,cu=(e,n,t)=>{let r=n[Symbol.iterator](),i=!1,o=!1,s=e.at(-1),u=s===void 0?0:Xe(s),c=r.next(),a=r.next(),h=0;while(!c.done){let f=c.value,l=Xe(f);if(u+l<=t)e[e.length-1]+=f;else e.push(f),u=0;if(f===ko||f===Gf)i=!0,o=n.startsWith(hu,h+1);if(i){if(o){if(f===au)i=!1,o=!1}else if(f===jf)i=!1}else if(u+=l,u===t&&!a.done)e.push(""),u=0;c=a,a=r.next(),h+=f.length}if(s=e.at(-1),!u&&s!==void 0&&s.length&&e.length>1)e[e.length-2]+=e.pop()},g0=(e)=>{let n=e.split(" "),t=n.length;while(t){if(Xe(n[t-1]))break;t--}if(t===n.length)return e;return n.slice(0,t).join(" ")+n.slice(t).join("")},m0=(e,n,t={})=>{if(t.trim!==!1&&e.trim()==="")return"";let r="",i,o,s=e.split(" "),u=[""],c=0;for(let f=0;f<s.length;f++){let l=s[f];if(t.trim!==!1){let g=u.at(-1)??"",p=g.trimStart();if(g.length!==p.length)u[u.length-1]=p,c=Xe(p)}if(f!==0){if(c>=n&&(t.wordWrap===!1||t.trim===!1))u.push(""),c=0;if(c||t.trim===!1)u[u.length-1]+=" ",c++}let d=Xe(l);if(t.hard&&d>n){let g=n-c,p=1+Math.floor((d-g-1)/n);if(Math.floor((d-1)/n)<p)u.push("");cu(u,l,n),c=Xe(u.at(-1)??"");continue}if(c+d>n&&c&&d){if(t.wordWrap===!1&&c<n){cu(u,l,n),c=Xe(u.at(-1)??"");continue}u.push(""),c=0}if(c+d>n&&t.wordWrap===!1){cu(u,l,n),c=Xe(u.at(-1)??"");continue}u[u.length-1]+=l,c+=d}if(t.trim!==!1)u=u.map((f)=>g0(f));let a=u.join(`
305
- `),h=!1;for(let f=0;f<a.length;f++){let l=a[f];if(r+=l,!h){if(h=l>="\uD800"&&l<="\uDBFF",h)continue}else h=!1;if(l===ko||l===Gf){Hf.lastIndex=f+1;let g=Hf.exec(a)?.groups;if(g?.code!==void 0){let p=Number.parseFloat(g.code);i=p===l0?void 0:p}else if(g?.uri!==void 0)o=g.uri.length===0?void 0:g.uri}if(a[f+1]===`
306
- `){if(o)r+=Tf("");let d=i?Lf(i):void 0;if(i&&d)r+=Af(d)}else if(l===`
307
- `){if(i&&Lf(i))r+=Af(i);if(o)r+=Tf(o)}}return r},p0=/\r?\n/;function it(e,n,t){return String(e).normalize().split(p0).map((r)=>m0(r,n,t)).join(`
308
- `)}var xe=Ci(lu(),1);function tr(e,n,t){if(!t.some((s)=>!s.disabled))return e;let r=e+n,i=Math.max(t.length-1,0),o=r<0?i:r>i?0:r;return t[o]?.disabled?tr(o,n<0?-1:1,t):o}function Eo(e,n,t,r){let i=r.split(`
309
- `),o=0,s=e;for(let c of i){if(s<=c.length)break;s-=c.length+1,o++}for(o=Math.max(0,Math.min(i.length-1,o+t)),s=Math.min(s,i[o].length)+n;s<0&&o>0;)o--,s+=i[o].length+1;for(;s>i[o].length&&o<i.length-1;)s-=i[o].length+1,o++;s=Math.max(0,Math.min(i[o].length,s));let u=0;for(let c=0;c<o;c++)u+=i[c].length+1;return u+s}var E0=["up","down","left","right","space","enter","cancel"],y0=["January","February","March","April","May","June","July","August","September","October","November","December"],Ve={actions:new Set(E0),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:[...y0],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(e,n)=>`There are only ${e} days in ${n}`,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 _f(e,n){if(typeof e=="string")return Ve.aliases.get(e)===n;for(let t of e)if(t!==void 0&&_f(t,n))return!0;return!1}function S0(e,n){if(e===n)return;let t=e.split(`
297
+ `)}function Mu(e,n,t=[]){for(let a of e)for(let f of[a.name,a.group,a.native??"",a.ansiSource])if(/["$`\\]/.test(f))throw Error(`${a.name}: "${f}" contains a character that breaks zsh quoting`);let r=Math.max(0,...e.map((a)=>a.name.length)),i=(a,f)=>` ${a.name.padEnd(r)} "${f}"`,o=(a)=>a.map((f)=>f.name).join(" "),s=hn(e),u=(a)=>`'${a.replaceAll("'","'\\''")}'`,c=hi.filter((a)=>a.section!=="setup"&&!a.hidden);return["# Generated by `mise run build` — do not edit.","# Source of truth: themes/*.toml in the ttheme repo.","",`typeset -g TTHEME_VERSION=${qe.version}`,"",'# the palette new tabs open with, which the iTerm2 "ttheme · default" profile wears',`typeset -g TTHEME_STARTUP=${n??""}`,"","# the terminals ttheme is wired into: a picture change reaches every one of them, from whichever runs the shell",`typeset -ga TTHEME_TERMINALS=(${t.join(" ")})`,"","# the commands the shell layer knows (src/verbs.ts): help, completion and argument checks read them",`typeset -ga TTHEME_VERBS=(${c.map((a)=>a.name).join(" ")})`,`typeset -ga TTHEME_SHELL_VERBS=(${c.filter((a)=>a.shell).map((a)=>a.name).join(" ")})`,"typeset -gA TTHEME_VERB_ARGS=(",...c.map((a)=>` ${a.name} ${u(a.args.join(" "))}`),")","typeset -gA TTHEME_VERB_ABOUT=(",...c.map((a)=>` ${a.name} ${u(a.about)}`),")",`typeset -g TTHEME_HELP=${u(li(!1,!0))}`,`typeset -g TTHEME_HELP_ALL=${u(li(!0,!0))}`,"","# the settings config.zsh holds, handed to the CLI on every call",`typeset -ga TTHEME_SETTINGS=(${_h.join(" ")})`,"","# seed for `ttheme config` when no config.zsh exists yet",`typeset -g TTHEME_CONFIG_TEMPLATE='${Su().trimEnd().replaceAll("'","'\\''")}'`,"","typeset -gA TTHEME_PALETTE=(",...e.map((a)=>i(a,[a.background,a.foreground,a.cursor,a.selection,...a.ansi].join(" "))),")","","# series order: new tabs cycle through it and TTHEME_SORT=series lists it — the default role stays applyable but unlisted",`typeset -ga TTHEME_ORDER=(${o(s)})`,"","# the same palettes by series name, then palette name: TTHEME_SORT=abc lists them this way",`typeset -ga TTHEME_ABC=(${o(ri(s))})`,"","typeset -gA TTHEME_GROUP=(",...e.map((a)=>i(a,a.group)),")","","# original-language title, rendered dim next to the group","typeset -gA TTHEME_NATIVE=(",...e.filter((a)=>a.native).map((a)=>i(a,a.native??"")),")","","# the six colors a list row shows: foreground, the signature, then red and green","typeset -gA TTHEME_SWATCH=(",...e.map((a)=>i(a,Io(a).join(" "))),")","","# where each palette's 16 ANSI colors came from","typeset -gA TTHEME_SRC=(",...e.map((a)=>i(a,a.ansiSource)),")",""].join(`
298
+ `)}var vu={id:"shell",emitShared(e){return[{path:"shell/palettes.zsh",content:Mu(e.map($n))}]}};var Q0=["black","red","green","yellow","blue","magenta","cyan","white"];function Dh(e,n){return[` ${e}:`,...Q0.map((t,r)=>` ${t}: "${n[r]}"`)]}var bi={id:"warp",limits:"no selection color, and Warp paints one theme app-wide",emit(e){let n=[`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:",...Dh("normal",e.ansi.slice(0,8)),...Dh("bright",e.ansi.slice(8,16)),""].join(`
299
+ `);return[{path:`warp/themes/${he(e.name)}.yaml`,content:n}]}};var xh=(e)=>`[${e.map((n)=>`"${n}"`).join(", ")}]`,$i={id:"wezterm",limits:"OSC repaints per pane, pictures show per window",emit(e){let n=["[metadata]",`name = "${he(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 = ${xh(e.ansi.slice(0,8))}`,`brights = ${xh(e.ansi.slice(8,16))}`,""].join(`
300
+ `);return[{path:`wezterm/colors/${he(e.name)}.toml`,content:n}]}},hr=(e)=>JSON.stringify(e);function el(e){return["-- Generated by ttheme — rewritten on every add, remove and default; do not edit.","local wezterm = require 'wezterm'","",`local MODULE = ${hr(e.path)}`,`local COLORS = ${hr(e.colors)}`,`local BACKGROUNDS = ${hr(e.backgrounds)}`,`local STARTUP = ${e.startup?hr(he(e.startup)):"nil"}`,"local PALETTES = {",...e.palettes.map((n)=>` [${hr(n.name)}] = ${hr(n.background)},`),"}","","local X = { left = 'Left', center = 'Center', right = 'Right' }","local Y = { top = 'Top', center = 'Middle', bottom = 'Bottom' }","local SIZE = { cover = 'Cover', contain = 'Contain', stretch = '100%' }","","local function locate(path)"," if path:sub(1, 2) == '~/' then"," return os.getenv('HOME') .. path:sub(2)"," elseif path:sub(1, 1) == '/' or path:match('^%a:[/\\\\]') then"," return path"," end"," return BACKGROUNDS .. '/' .. path","end","","local function read(path, into)"," local f = io.open(path, 'r')"," if not f then"," return false"," end"," for line in f:lines() do"," local key, value = line:match('^%s*([%w%-]+)%s*=%s*(.-)%s*$')"," if key == 'config-file' then"," read(locate((value:gsub('^%?', ''))), into)"," elseif key then"," into[key] = value"," end"," end"," f:close()"," return true","end","","local function layers(palette)"," local color = PALETTES[palette]"," local c = {}"," if not color or not read(BACKGROUNDS .. '/' .. ((palette: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(`
301
+ `)}var nl=["black","red","green","yellow","blue","purple","cyan","white"];function tl(e){return{name:he(e.name),background:e.background,foreground:e.foreground,cursorColor:e.cursor,selectionBackground:e.selectionBackground,...Object.fromEntries(nl.map((n,t)=>[n,e.ansi[t]])),...Object.fromEntries(nl.map((n,t)=>[`bright${n[0]?.toUpperCase()}${n.slice(1)}`,e.ansi[t+8]]))}}function Iu(e,n,t){let r={...n&&t?{profiles:[{updates:n,colorScheme:he(t)}]}:{},schemes:e.map(tl)};return`${JSON.stringify(r,null,2)}
302
+ `}var ki={id:"windows-terminal",limits:"no kitty graphics, so no pictures; OSC repaints per pane",emit(e){return[{path:`windows-terminal/schemes/${he(e.name)}.json`,content:`${JSON.stringify(tl(e),null,2)}
303
+ `}]},emitShared(e){return[{path:"windows-terminal/ttheme.json",content:Iu(e)}]}};function he(e){return`ttheme-${Jn(e)}`}function or(e){return[`# ${e.name} — ${e.group}${e.native?` (${e.native})`:""}`,`# ANSI: ${e.ansiSource}`]}var il=yi(import.meta.dirname,".."),Z0=yi(il,"themes"),Nu=yi(il,"dist"),Po=[oi,ui,ii,$i,si,ki,bi],X0=[vu,ku],dM=Po.map((e)=>e.id);async function Ao({only:e}={}){if(typeof Bun>"u")throw Error("needs bun — run it from a checkout: bun src/bin.ts build");let n=e&&e.length>0?Po.filter((o)=>e.includes(o.id)):Po,t=nh(Z0),r=fa(t);if(r.length>0){for(let o of r)console.error(` ✗ ${o.theme} [${o.rule}] ${o.detail}`);throw Error(`${r.length} contrast violation(s). Fix the palette, or waive the rule in its [contrast] section with a reason.`)}if(n.length===Po.length)rl(Nu,{recursive:!0,force:!0});else for(let o of n)rl(yi(Nu,o.id),{recursive:!0,force:!0});let i=0;for(let o of[...n,...X0]){let s=t.flatMap((a)=>o.emit?.(a)??[]),u=o.emitShared?.(t)??[];for(let a of[...s,...u])await Bun.write(yi(Nu,a.path),a.content),i++;let c=s.length>0?`${t.length} themes${o.limits?` (${o.limits})`:""}`:u.map((a)=>Y0(a.path)).join(" ");console.log(` ${o.id.padEnd(16)} ${c}`)}console.log(`
304
+ ${t.length} themes (${th(t).length} in the new-tab rotation) -> ${i} files in dist/`)}import{spawnSync as ik}from"node:child_process";import{existsSync as Sr,mkdirSync as ok,mkdtempSync as sk,readFileSync as ss,rmSync as uk,writeFileSync as ck}from"node:fs";import{tmpdir as ak}from"node:os";import{basename as fk,dirname as Gd,join as dc}from"node:path";import{styleText as Uo}from"node:util";import{stdout as El,stdin as fb}from"node:process";import hb from"node:readline";var ol=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(n)=>{let t=0;e.lastIndex=0;while(e.test(n))t+=1;return n.length-t}})(),sl=(e)=>{return e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510},ul=(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 z0=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,V0=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,cl=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,B0=/\t{1,1000}/y,al=/[\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,D0=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,x0=/\p{M}+/gu,eb={limit:1/0,ellipsis:""},fl=(e,n={},t={})=>{let r=n.limit??1/0,i=n.ellipsis??"",o=n?.ellipsisWidth??(i?fl(i,eb,t).width:0),s=0,u=t.controlWidth??0,c=t.tabWidth??8,a=t.emojiWidth??2,f=2,h=t.regularWidth??1,l=t.wideWidth??2,d=[[D0,h],[z0,0],[V0,u],[B0,c],[al,a],[cl,l]],g=0,m=0,$=e.length,S=0,v=!1,k=$,M=Math.max(0,r-o),p=0,A=0,y=0,F=0;e:while(!0){if(A>p||m>=$&&m>g){let N=e.slice(p,A)||e.slice(g,m);S=0;for(let H of N.replaceAll(x0,"")){let G=H.codePointAt(0)||0;if(sl(G))F=2;else if(ul(G))F=l;else F=h;if(y+F>M)k=Math.min(k,Math.max(p,g)+S);if(y+F>r){v=!0;break e}S+=H.length,y+=F}p=A=0}if(m>=$)break e;for(let N=0,H=d.length;N<H;N++){let[G,ae]=d[N];if(G.lastIndex=m,G.test(e)){if(S=G===cl?ol(e.slice(m,G.lastIndex)):G===al?1:G.lastIndex-m,F=S*ae,y+F>M)k=Math.min(k,m+Math.floor((M-y)/ae));if(y+F>r){v=!0;break e}y+=F,p=g,A=m,m=g=G.lastIndex;continue e}}m+=1}return{width:v?M:y,index:v?k:$,truncated:v,ellipsed:v&&r>=o}},hl=fl;var nb={limit:1/0,ellipsis:"",ellipsisWidth:0},tb=(e,n={})=>{return hl(e,nb,n).width},Ve=tb;var Ho="\x1B",pl="›",rb=39,Ru="\x07",wl="[",ib="]",bl="m",Fu=`${ib}8;;`,ll=new RegExp(`(?:\\${wl}(?<code>\\d+)m|\\${Fu}(?<uri>.*)${Ru})`,"y"),dl=(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},gl=(e)=>`${Ho}${wl}${e}${bl}`,ml=(e)=>`${Ho}${Fu}${e}${Ru}`,Ou=(e,n,t)=>{let r=n[Symbol.iterator](),i=!1,o=!1,s=e.at(-1),u=s===void 0?0:Ve(s),c=r.next(),a=r.next(),f=0;while(!c.done){let h=c.value,l=Ve(h);if(u+l<=t)e[e.length-1]+=h;else e.push(h),u=0;if(h===Ho||h===pl)i=!0,o=n.startsWith(Fu,f+1);if(i){if(o){if(h===Ru)i=!1,o=!1}else if(h===bl)i=!1}else if(u+=l,u===t&&!a.done)e.push(""),u=0;c=a,a=r.next(),f+=h.length}if(s=e.at(-1),!u&&s!==void 0&&s.length&&e.length>1)e[e.length-2]+=e.pop()},ob=(e)=>{let n=e.split(" "),t=n.length;while(t){if(Ve(n[t-1]))break;t--}if(t===n.length)return e;return n.slice(0,t).join(" ")+n.slice(t).join("")},sb=(e,n,t={})=>{if(t.trim!==!1&&e.trim()==="")return"";let r="",i,o,s=e.split(" "),u=[""],c=0;for(let h=0;h<s.length;h++){let l=s[h];if(t.trim!==!1){let g=u.at(-1)??"",m=g.trimStart();if(g.length!==m.length)u[u.length-1]=m,c=Ve(m)}if(h!==0){if(c>=n&&(t.wordWrap===!1||t.trim===!1))u.push(""),c=0;if(c||t.trim===!1)u[u.length-1]+=" ",c++}let d=Ve(l);if(t.hard&&d>n){let g=n-c,m=1+Math.floor((d-g-1)/n);if(Math.floor((d-1)/n)<m)u.push("");Ou(u,l,n),c=Ve(u.at(-1)??"");continue}if(c+d>n&&c&&d){if(t.wordWrap===!1&&c<n){Ou(u,l,n),c=Ve(u.at(-1)??"");continue}u.push(""),c=0}if(c+d>n&&t.wordWrap===!1){Ou(u,l,n),c=Ve(u.at(-1)??"");continue}u[u.length-1]+=l,c+=d}if(t.trim!==!1)u=u.map((h)=>ob(h));let a=u.join(`
305
+ `),f=!1;for(let h=0;h<a.length;h++){let l=a[h];if(r+=l,!f){if(f=l>="\uD800"&&l<="\uDBFF",f)continue}else f=!1;if(l===Ho||l===pl){ll.lastIndex=h+1;let g=ll.exec(a)?.groups;if(g?.code!==void 0){let m=Number.parseFloat(g.code);i=m===rb?void 0:m}else if(g?.uri!==void 0)o=g.uri.length===0?void 0:g.uri}if(a[h+1]===`
306
+ `){if(o)r+=ml("");let d=i?dl(i):void 0;if(i&&d)r+=gl(d)}else if(l===`
307
+ `){if(i&&dl(i))r+=gl(i);if(o)r+=ml(o)}}return r},ub=/\r?\n/;function ot(e,n,t){return String(e).normalize().split(ub).map((r)=>sb(r,n,t)).join(`
308
+ `)}var en=Vi(Au(),1);function lr(e,n,t){if(!t.some((s)=>!s.disabled))return e;let r=e+n,i=Math.max(t.length-1,0),o=r<0?i:r>i?0:r;return t[o]?.disabled?lr(o,n<0?-1:1,t):o}function Lo(e,n,t,r){let i=r.split(`
309
+ `),o=0,s=e;for(let c of i){if(s<=c.length)break;s-=c.length+1,o++}for(o=Math.max(0,Math.min(i.length-1,o+t)),s=Math.min(s,i[o].length)+n;s<0&&o>0;)o--,s+=i[o].length+1;for(;s>i[o].length&&o<i.length-1;)s-=i[o].length+1,o++;s=Math.max(0,Math.min(i[o].length,s));let u=0;for(let c=0;c<o;c++)u+=i[c].length+1;return u+s}var lb=["up","down","left","right","space","enter","cancel"],db=["January","February","March","April","May","June","July","August","September","October","November","December"],Ye={actions:new Set(lb),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:[...db],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(e,n)=>`There are only ${e} days in ${n}`,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 Sl(e,n){if(typeof e=="string")return Ye.aliases.get(e)===n;for(let t of e)if(t!==void 0&&Sl(t,n))return!0;return!1}function gb(e,n){if(e===n)return;let t=e.split(`
310
310
  `),r=n.split(`
311
- `),i=Math.max(t.length,r.length),o=[];for(let s=0;s<i;s++)t[s]!==r[s]&&o.push(s);return{lines:o,numLinesBefore:t.length,numLinesAfter:r.length,numLines:i}}var vS=globalThis.process.platform.startsWith("win"),gu=Symbol("clack:cancel");function en(e){return e===gu}function yo(e,n){let t=e;t.isTTY&&t.setRawMode(n)}var Mo=(e)=>("columns"in e)&&typeof e.columns=="number"?e.columns:80,pu=(e)=>("rows"in e)&&typeof e.rows=="number"?e.rows:20;function li(e,n,t,r=t,i=t,o){let s=Mo(e??Kf);return it(n,s-t.length,{hard:!0,trim:!1}).split(`
312
- `).map((u,c,a)=>{let h=o?o(u,c):u;return c===0?`${r}${h}`:c===a.length-1?`${i}${h}`:`${t}${h}`}).join(`
313
- `)}function qf(e,n){if("~standard"in e){let t=e["~standard"].validate(n);if(t instanceof Promise)throw TypeError("Schema validation must be synchronous. Update `validate()` and remove any asynchronous logic.");return t.issues?.at(0)?.message}return e(n)}class Rn{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(e,n=!0){let{input:t=b0,output:r=Kf,render:i,signal:o,...s}=e;this.opts=s,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=i.bind(this),this._track=n,this._abortSignal=o,this.input=t,this.output=r}unsubscribe(){this._subscribers.clear()}setSubscriber(e,n){let t=this._subscribers.get(e)??[];t.push(n),this._subscribers.set(e,t)}on(e,n){this.setSubscriber(e,{cb:n})}once(e,n){this.setSubscriber(e,{cb:n,once:!0})}emit(e,...n){let t=this._subscribers.get(e)??[],r=[];for(let i of t)i.cb(...n),i.once&&r.push(()=>t.splice(t.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(gu);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=k0.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),yo(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(xe.cursor.show),this.output.off("resize",this.render),yo(this.input,!1),e(this.value)}),this.once("cancel",()=>{this.output.write(xe.cursor.show),this.output.off("resize",this.render),yo(this.input,!1),e(gu)})})}_isActionKey(e,n){return e==="\t"}_shouldSubmit(e,n){return!0}_setValue(e){this.value=e,this.emit("value",this.value)}_setUserInput(e,n){this.userInput=e??"",this.emit("userInput",this.userInput),n&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}onKeypress(e,n){if(this._track&&n.name!=="return"&&(n.name&&this._isActionKey(e,n)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),n?.name&&(!this._track&&Ve.aliases.has(n.name)&&this.emit("cursor",Ve.aliases.get(n.name)),Ve.actions.has(n.name)&&this.emit("cursor",n.name)),e&&(e.toLowerCase()==="y"||e.toLowerCase()==="n")&&this.emit("confirm",e.toLowerCase()==="y"),this.emit("key",e,n),n?.name==="return"&&this._shouldSubmit(e,n)){if(this.opts.validate){let t=qf(this.opts.validate,this.value);t&&(this.error=t instanceof Error?t.message:t,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}_f([e,n?.name,n?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
314
- `),yo(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=it(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
315
- `).length-1;this.output.write(xe.cursor.move(-999,e*-1))}render(){let e=it(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state==="initial")this.output.write(xe.cursor.hide);else{let n=S0(this._prevFrame,e),t=pu(this.output);if(this.restoreCursor(),n){let r=Math.max(0,n.numLinesAfter-t),i=Math.max(0,n.numLinesBefore-t),o=n.lines.find((s)=>s>=r);if(o===void 0){this._prevFrame=e;return}if(n.lines.length===1){this.output.write(xe.cursor.move(0,o-i)),this.output.write(xe.erase.lines(1));let s=e.split(`
316
- `);this.output.write(s[o]),this._prevFrame=e,this.output.write(xe.cursor.move(0,s.length-o-1));return}else if(n.lines.length>1){if(r<i)o=r;else{let u=o-i;u>0&&this.output.write(xe.cursor.move(0,u))}this.output.write(xe.erase.down());let s=e.split(`
311
+ `),i=Math.max(t.length,r.length),o=[];for(let s=0;s<i;s++)t[s]!==r[s]&&o.push(s);return{lines:o,numLinesBefore:t.length,numLinesAfter:r.length,numLines:i}}var NM=globalThis.process.platform.startsWith("win"),Lu=Symbol("clack:cancel");function nn(e){return e===Lu}function To(e,n){let t=e;t.isTTY&&t.setRawMode(n)}var jo=(e)=>("columns"in e)&&typeof e.columns=="number"?e.columns:80,Gu=(e)=>("rows"in e)&&typeof e.rows=="number"?e.rows:20;function Ei(e,n,t,r=t,i=t,o){let s=jo(e??El);return ot(n,s-t.length,{hard:!0,trim:!1}).split(`
312
+ `).map((u,c,a)=>{let f=o?o(u,c):u;return c===0?`${r}${f}`:c===a.length-1?`${i}${f}`:`${t}${f}`}).join(`
313
+ `)}function Ml(e,n){if("~standard"in e){let t=e["~standard"].validate(n);if(t instanceof Promise)throw TypeError("Schema validation must be synchronous. Update `validate()` and remove any asynchronous logic.");return t.issues?.at(0)?.message}return e(n)}class Rn{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(e,n=!0){let{input:t=fb,output:r=El,render:i,signal:o,...s}=e;this.opts=s,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=i.bind(this),this._track=n,this._abortSignal=o,this.input=t,this.output=r}unsubscribe(){this._subscribers.clear()}setSubscriber(e,n){let t=this._subscribers.get(e)??[];t.push(n),this._subscribers.set(e,t)}on(e,n){this.setSubscriber(e,{cb:n})}once(e,n){this.setSubscriber(e,{cb:n,once:!0})}emit(e,...n){let t=this._subscribers.get(e)??[],r=[];for(let i of t)i.cb(...n),i.once&&r.push(()=>t.splice(t.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(Lu);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=hb.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),To(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(en.cursor.show),this.output.off("resize",this.render),To(this.input,!1),e(this.value)}),this.once("cancel",()=>{this.output.write(en.cursor.show),this.output.off("resize",this.render),To(this.input,!1),e(Lu)})})}_isActionKey(e,n){return e==="\t"}_shouldSubmit(e,n){return!0}_setValue(e){this.value=e,this.emit("value",this.value)}_setUserInput(e,n){this.userInput=e??"",this.emit("userInput",this.userInput),n&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}onKeypress(e,n){if(this._track&&n.name!=="return"&&(n.name&&this._isActionKey(e,n)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),n?.name&&(!this._track&&Ye.aliases.has(n.name)&&this.emit("cursor",Ye.aliases.get(n.name)),Ye.actions.has(n.name)&&this.emit("cursor",n.name)),e&&(e.toLowerCase()==="y"||e.toLowerCase()==="n")&&this.emit("confirm",e.toLowerCase()==="y"),this.emit("key",e,n),n?.name==="return"&&this._shouldSubmit(e,n)){if(this.opts.validate){let t=Ml(this.opts.validate,this.value);t&&(this.error=t instanceof Error?t.message:t,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}Sl([e,n?.name,n?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
314
+ `),To(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=ot(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
315
+ `).length-1;this.output.write(en.cursor.move(-999,e*-1))}render(){let e=ot(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state==="initial")this.output.write(en.cursor.hide);else{let n=gb(this._prevFrame,e),t=Gu(this.output);if(this.restoreCursor(),n){let r=Math.max(0,n.numLinesAfter-t),i=Math.max(0,n.numLinesBefore-t),o=n.lines.find((s)=>s>=r);if(o===void 0){this._prevFrame=e;return}if(n.lines.length===1){this.output.write(en.cursor.move(0,o-i)),this.output.write(en.erase.lines(1));let s=e.split(`
316
+ `);this.output.write(s[o]),this._prevFrame=e,this.output.write(en.cursor.move(0,s.length-o-1));return}else if(n.lines.length>1){if(r<i)o=r;else{let u=o-i;u>0&&this.output.write(en.cursor.move(0,u))}this.output.write(en.erase.down());let s=e.split(`
317
317
  `).slice(o);this.output.write(s.join(`
318
- `)),this._prevFrame=e;return}}this.output.write(xe.erase.down())}this.output.write(e),this.state==="initial"&&(this.state="active"),this._prevFrame=e}}}function v0(e,n){if(e===void 0||n.length===0)return 0;let t=n.findIndex((r)=>r.value===e);return t!==-1?t:0}function M0(e,n){return(n.label??String(n.value)).toLowerCase().includes(e.toLowerCase())}function I0(e,n){if(n)return e?n:n[0]}var N0=class extends Rn{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#n=0;#t="";#e;#o;#u;get cursor(){return this.#n}get userInputWithCursor(){if(!this.userInput)return vo(["inverse","hidden"],"_");if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let n=this.userInput.slice(0,this.cursor),t=this.userInput.slice(this.cursor,this.cursor+1),r=this.userInput.slice(this.cursor+1);return`${n}${vo("inverse",t)}${r}`}get options(){return typeof this.#o=="function"?this.#o():this.#o}constructor(n){super(n),this.#o=n.options,this.#u=n.placeholder;let t=this.options;this.filteredOptions=[...t],this.multiple=n.multiple===!0,this.#e=typeof n.options=="function"?n.filter:n.filter??M0;let r;if(n.initialValue&&Array.isArray(n.initialValue)?this.multiple?r=n.initialValue:r=n.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(r=[this.options[0]?.value]),r)for(let i of r){let o=t.findIndex((s)=>s.value===i);o!==-1&&(this.toggleSelected(i),this.#n=o)}this.focusedValue=this.options[this.#n]?.value,this.on("key",(i,o)=>this.#r(i,o)),this.on("userInput",(i)=>this.#i(i))}_isActionKey(n,t){return n==="\t"||this.multiple&&this.isNavigating&&t.name==="space"&&n!==void 0&&n!==""}#r(n,t){let r=t.name==="up",i=t.name==="down",o=t.name==="return",s=this.userInput===""||this.userInput==="\t",u=this.#u,c=this.options,a=u!==void 0&&u!==""&&c.some((h)=>!h.disabled&&(this.#e?this.#e(u,h):!0));if(t.name==="tab"&&s&&a){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(u,!0),this.isNavigating=!1;return}r||i?(this.#n=tr(this.#n,r?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#n]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):o?this.value=I0(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(t.name==="tab"||this.isNavigating&&t.name==="space")?this.toggleSelected(this.focusedValue):this.isNavigating=!1:(this.focusedValue&&(this.selectedValues=[this.focusedValue]),this.isNavigating=!1)}deselectAll(){this.selectedValues=[]}toggleSelected(n){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(n)?this.selectedValues=this.selectedValues.filter((t)=>t!==n):this.selectedValues=[...this.selectedValues,n]:this.selectedValues=[n])}#i(n){if(n!==this.#t){this.#t=n;let t=this.options;n&&this.#e?this.filteredOptions=t.filter((o)=>this.#e?.(n,o)):this.filteredOptions=[...t];let r=v0(this.focusedValue,this.filteredOptions);this.#n=tr(r,0,this.filteredOptions);let i=this.filteredOptions[this.#n];i&&!i.disabled?this.focusedValue=i.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}};class wu extends Rn{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",(n)=>{this.output.write(xe.cursor.move(0,-1)),this.value=n,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var O0={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function Cf(e){return[...e].map((n)=>O0[n])}function R0(e){let n=new Intl.DateTimeFormat(e,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2000,0,15)),t=[],r="/";for(let i of n)i.type==="literal"?r=i.value.trim()||i.value:(i.type==="year"||i.type==="month"||i.type==="day")&&t.push({type:i.type,len:i.type==="year"?4:2});return{segments:t,separator:r}}function du(e){return Number.parseInt((e||"0").replace(/_/g,"0"),10)||0}function So(e){return{year:du(e.year),month:du(e.month),day:du(e.day)}}function mu(e,n){return new Date(e||2001,n||1,0).getDate()}function Qf(e){let{year:n,month:t,day:r}=So(e);if(!n||n<0||n>9999||!t||t<1||t>12||!r||r<1)return;let i=new Date(Date.UTC(n,t-1,r));if(!(i.getUTCFullYear()!==n||i.getUTCMonth()!==t-1||i.getUTCDate()!==r))return{year:n,month:t,day:r}}function Wf(e){let n=Qf(e);return n?new Date(Date.UTC(n.year,n.month-1,n.day)):void 0}function F0(e,n,t,r){let i=t?{year:t.getUTCFullYear(),month:t.getUTCMonth()+1,day:t.getUTCDate()}:null,o=r?{year:r.getUTCFullYear(),month:r.getUTCMonth()+1,day:r.getUTCDate()}:null;return e==="year"?{min:i?.year??1,max:o?.year??9999}:e==="month"?{min:i&&n.year===i.year?i.month:1,max:o&&n.year===o.year?o.month:12}:{min:i&&n.year===i.year&&n.month===i.month?i.day:1,max:o&&n.year===o.year&&n.month===o.month?o.day:mu(n.year,n.month)}}class Yf extends Rn{#n;#t;#e;#o;#u;#r={segmentIndex:0,positionInSegment:0};#i=!0;#s=null;inlineError="";get segmentCursor(){return{...this.#r}}get segmentValues(){return{...this.#e}}get segments(){return this.#n}get separator(){return this.#t}get formattedValue(){return this.#f(this.#e)}#f(e){return this.#n.map((n)=>e[n.type]).join(this.#t)}#c(){this._setUserInput(this.#f(this.#e)),this._setValue(Wf(this.#e)??void 0)}constructor(e){let n=e.format?{segments:Cf(e.format),separator:e.separator??"/"}:R0(e.locale),t=e.separator??n.separator,r=e.format?Cf(e.format):n.segments,i=e.initialValue??e.defaultValue,o=i?{year:String(i.getUTCFullYear()).padStart(4,"0"),month:String(i.getUTCMonth()+1).padStart(2,"0"),day:String(i.getUTCDate()).padStart(2,"0")}:{year:"____",month:"__",day:"__"},s=r.map((u)=>o[u.type]).join(t);super({...e,initialUserInput:s},!1),this.#n=r,this.#t=t,this.#e=o,this.#o=e.minDate,this.#u=e.maxDate,this.#c(),this.on("cursor",(u)=>this.#g(u)),this.on("key",(u,c)=>this.#m(u,c)),this.on("finalize",()=>this.#p(e))}#a(){let e=Math.max(0,Math.min(this.#r.segmentIndex,this.#n.length-1)),n=this.#n[e];if(n)return this.#r.positionInSegment=Math.max(0,Math.min(this.#r.positionInSegment,n.len-1)),{segment:n,index:e}}#h(e){this.inlineError="",this.#s=null;let n=this.#a();n&&(this.#r.segmentIndex=Math.max(0,Math.min(this.#n.length-1,n.index+e)),this.#r.positionInSegment=0,this.#i=!0)}#l(e){let n=this.#a();if(!n)return;let{segment:t}=n,r=this.#e[t.type],i=!r||r.replace(/_/g,"")==="",o=Number.parseInt((r||"0").replace(/_/g,"0"),10)||0,s=F0(t.type,So(this.#e),this.#o,this.#u),u;i?u=e===1?s.min:s.max:u=Math.max(Math.min(s.max,o+e),s.min),this.#e={...this.#e,[t.type]:u.toString().padStart(t.len,"0")},this.#i=!0,this.#s=null,this.#c()}#g(e){if(e)switch(e){case"right":return this.#h(1);case"left":return this.#h(-1);case"up":return this.#l(1);case"down":return this.#l(-1)}}#m(e,n){if(n?.name==="backspace"||n?.sequence===""||n?.sequence==="\b"||e===""||e==="\b"){this.inlineError="";let t=this.#a();if(!t)return;if(!this.#e[t.segment.type].replace(/_/g,"")){this.#h(-1);return}this.#e[t.segment.type]="_".repeat(t.segment.len),this.#i=!0,this.#r.positionInSegment=0,this.#c();return}if(n?.name==="tab"){this.inlineError="";let t=this.#a();if(!t)return;let r=n.shift?-1:1,i=t.index+r;i>=0&&i<this.#n.length&&(this.#r.segmentIndex=i,this.#r.positionInSegment=0,this.#i=!0);return}if(e&&/^[0-9]$/.test(e)){let t=this.#a();if(!t)return;let{segment:r}=t,i=!this.#e[r.type].replace(/_/g,"");if(this.#i&&this.#s!==null&&!i){let l=this.#s+e,d={...this.#e,[r.type]:l},g=this.#d(d,r);if(g){this.inlineError=g,this.#s=null,this.#i=!1;return}this.inlineError="",this.#e[r.type]=l,this.#s=null,this.#i=!1,this.#c(),t.index<this.#n.length-1&&(this.#r.segmentIndex=t.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.#s=null;let o=this.#e[r.type],s=o.indexOf("_"),u=s>=0?s:Math.min(this.#r.positionInSegment,r.len-1);if(u<0||u>=r.len)return;let c=o.slice(0,u)+e+o.slice(u+1),a=!1;if(u===0&&o==="__"&&(r.type==="month"||r.type==="day")){let l=Number.parseInt(e,10);c=`0${e}`,a=l<=(r.type==="month"?1:2)}if(r.type==="year"&&(c=(o.replace(/_/g,"")+e).padStart(r.len,"_")),!c.includes("_")){let l={...this.#e,[r.type]:c},d=this.#d(l,r);if(d){this.inlineError=d;return}}this.inlineError="",this.#e[r.type]=c;let h=c.includes("_")?void 0:Qf(this.#e);if(h){let{year:l,month:d}=h,g=mu(l,d);this.#e={year:String(Math.max(0,Math.min(9999,l))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,d))).padStart(2,"0"),day:String(Math.max(1,Math.min(g,h.day))).padStart(2,"0")}}this.#c();let f=c.indexOf("_");a?(this.#i=!0,this.#s=e):f>=0?this.#r.positionInSegment=f:s>=0&&t.index<this.#n.length-1?(this.#r.segmentIndex=t.index+1,this.#r.positionInSegment=0,this.#i=!0):this.#r.positionInSegment=Math.min(u+1,r.len-1)}}#d(e,n){let{month:t,day:r}=So(e);if(n.type==="month"&&(t<0||t>12))return Ve.date.messages.invalidMonth;if(n.type==="day"&&(r<0||r>31))return Ve.date.messages.invalidDay(31,"any month")}#p(e){let{year:n,month:t,day:r}=So(this.#e);if(n&&t&&r){let i=mu(n,t);this.#e={...this.#e,day:String(Math.min(r,i)).padStart(2,"0")}}this.value=Wf(this.#e)??e.defaultValue??void 0}}var P0=class extends Rn{options;cursor=0;#n;getGroupItems(n){return this.options.filter((t)=>t.group===n)}isGroupSelected(n){let t=this.getGroupItems(n),r=this.value;return r===void 0?!1:t.every((i)=>r.includes(i.value))}toggleValue(){let n=this.options[this.cursor];if(n!==void 0)if(this.value===void 0&&(this.value=[]),n.group===!0){let t=n.value,r=this.getGroupItems(t);this.isGroupSelected(t)?this.value=this.value.filter((i)=>r.findIndex((o)=>o.value===i)===-1):this.value=[...this.value,...r.map((i)=>i.value)],this.value=Array.from(new Set(this.value))}else{let t=this.value.includes(n.value);this.value=t?this.value.filter((r)=>r!==n.value):[...this.value,n.value]}}constructor(n){super(n,!1);let{options:t}=n;this.#n=n.selectableGroups!==!1,this.options=Object.entries(t).flatMap(([r,i])=>[{value:r,group:!0,label:r},...i.map((o)=>({...o,group:r}))]),this.value=[...n.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:r})=>r===n.cursorAt),this.#n?0:1),this.on("cursor",(r)=>{switch(r){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let i=this.options[this.cursor]?.group===!0;!this.#n&&i&&(this.cursor=this.cursor===0?this.options.length-1:this.cursor-1);break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let i=this.options[this.cursor]?.group===!0;!this.#n&&i&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},H0=new Set(["up","down","left","right"]);class Zf extends Rn{#n=!1;#t;focused="editor";get userInputWithCursor(){if(this.state==="submit")return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${e}█`;let n=e.slice(0,this.cursor),t=e.slice(this.cursor,this.cursor+1),r=e.slice(this.cursor+1);return t===`
318
+ `)),this._prevFrame=e;return}}this.output.write(en.erase.down())}this.output.write(e),this.state==="initial"&&(this.state="active"),this._prevFrame=e}}}function mb(e,n){if(e===void 0||n.length===0)return 0;let t=n.findIndex((r)=>r.value===e);return t!==-1?t:0}function pb(e,n){return(n.label??String(n.value)).toLowerCase().includes(e.toLowerCase())}function wb(e,n){if(n)return e?n:n[0]}var bb=class extends Rn{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#n=0;#t="";#e;#o;#u;get cursor(){return this.#n}get userInputWithCursor(){if(!this.userInput)return Uo(["inverse","hidden"],"_");if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let n=this.userInput.slice(0,this.cursor),t=this.userInput.slice(this.cursor,this.cursor+1),r=this.userInput.slice(this.cursor+1);return`${n}${Uo("inverse",t)}${r}`}get options(){return typeof this.#o=="function"?this.#o():this.#o}constructor(n){super(n),this.#o=n.options,this.#u=n.placeholder;let t=this.options;this.filteredOptions=[...t],this.multiple=n.multiple===!0,this.#e=typeof n.options=="function"?n.filter:n.filter??pb;let r;if(n.initialValue&&Array.isArray(n.initialValue)?this.multiple?r=n.initialValue:r=n.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(r=[this.options[0]?.value]),r)for(let i of r){let o=t.findIndex((s)=>s.value===i);o!==-1&&(this.toggleSelected(i),this.#n=o)}this.focusedValue=this.options[this.#n]?.value,this.on("key",(i,o)=>this.#r(i,o)),this.on("userInput",(i)=>this.#i(i))}_isActionKey(n,t){return n==="\t"||this.multiple&&this.isNavigating&&t.name==="space"&&n!==void 0&&n!==""}#r(n,t){let r=t.name==="up",i=t.name==="down",o=t.name==="return",s=this.userInput===""||this.userInput==="\t",u=this.#u,c=this.options,a=u!==void 0&&u!==""&&c.some((f)=>!f.disabled&&(this.#e?this.#e(u,f):!0));if(t.name==="tab"&&s&&a){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(u,!0),this.isNavigating=!1;return}r||i?(this.#n=lr(this.#n,r?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#n]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):o?this.value=wb(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(t.name==="tab"||this.isNavigating&&t.name==="space")?this.toggleSelected(this.focusedValue):this.isNavigating=!1:(this.focusedValue&&(this.selectedValues=[this.focusedValue]),this.isNavigating=!1)}deselectAll(){this.selectedValues=[]}toggleSelected(n){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(n)?this.selectedValues=this.selectedValues.filter((t)=>t!==n):this.selectedValues=[...this.selectedValues,n]:this.selectedValues=[n])}#i(n){if(n!==this.#t){this.#t=n;let t=this.options;n&&this.#e?this.filteredOptions=t.filter((o)=>this.#e?.(n,o)):this.filteredOptions=[...t];let r=mb(this.focusedValue,this.filteredOptions);this.#n=lr(r,0,this.filteredOptions);let i=this.filteredOptions[this.#n];i&&!i.disabled?this.focusedValue=i.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}};class Uu extends Rn{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",(n)=>{this.output.write(en.cursor.move(0,-1)),this.value=n,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var $b={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function kl(e){return[...e].map((n)=>$b[n])}function kb(e){let n=new Intl.DateTimeFormat(e,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2000,0,15)),t=[],r="/";for(let i of n)i.type==="literal"?r=i.value.trim()||i.value:(i.type==="year"||i.type==="month"||i.type==="day")&&t.push({type:i.type,len:i.type==="year"?4:2});return{segments:t,separator:r}}function Hu(e){return Number.parseInt((e||"0").replace(/_/g,"0"),10)||0}function Go(e){return{year:Hu(e.year),month:Hu(e.month),day:Hu(e.day)}}function Tu(e,n){return new Date(e||2001,n||1,0).getDate()}function vl(e){let{year:n,month:t,day:r}=Go(e);if(!n||n<0||n>9999||!t||t<1||t>12||!r||r<1)return;let i=new Date(Date.UTC(n,t-1,r));if(!(i.getUTCFullYear()!==n||i.getUTCMonth()!==t-1||i.getUTCDate()!==r))return{year:n,month:t,day:r}}function yl(e){let n=vl(e);return n?new Date(Date.UTC(n.year,n.month-1,n.day)):void 0}function yb(e,n,t,r){let i=t?{year:t.getUTCFullYear(),month:t.getUTCMonth()+1,day:t.getUTCDate()}:null,o=r?{year:r.getUTCFullYear(),month:r.getUTCMonth()+1,day:r.getUTCDate()}:null;return e==="year"?{min:i?.year??1,max:o?.year??9999}:e==="month"?{min:i&&n.year===i.year?i.month:1,max:o&&n.year===o.year?o.month:12}:{min:i&&n.year===i.year&&n.month===i.month?i.day:1,max:o&&n.year===o.year&&n.month===o.month?o.day:Tu(n.year,n.month)}}class Il extends Rn{#n;#t;#e;#o;#u;#r={segmentIndex:0,positionInSegment:0};#i=!0;#s=null;inlineError="";get segmentCursor(){return{...this.#r}}get segmentValues(){return{...this.#e}}get segments(){return this.#n}get separator(){return this.#t}get formattedValue(){return this.#h(this.#e)}#h(e){return this.#n.map((n)=>e[n.type]).join(this.#t)}#c(){this._setUserInput(this.#h(this.#e)),this._setValue(yl(this.#e)??void 0)}constructor(e){let n=e.format?{segments:kl(e.format),separator:e.separator??"/"}:kb(e.locale),t=e.separator??n.separator,r=e.format?kl(e.format):n.segments,i=e.initialValue??e.defaultValue,o=i?{year:String(i.getUTCFullYear()).padStart(4,"0"),month:String(i.getUTCMonth()+1).padStart(2,"0"),day:String(i.getUTCDate()).padStart(2,"0")}:{year:"____",month:"__",day:"__"},s=r.map((u)=>o[u.type]).join(t);super({...e,initialUserInput:s},!1),this.#n=r,this.#t=t,this.#e=o,this.#o=e.minDate,this.#u=e.maxDate,this.#c(),this.on("cursor",(u)=>this.#g(u)),this.on("key",(u,c)=>this.#m(u,c)),this.on("finalize",()=>this.#p(e))}#a(){let e=Math.max(0,Math.min(this.#r.segmentIndex,this.#n.length-1)),n=this.#n[e];if(n)return this.#r.positionInSegment=Math.max(0,Math.min(this.#r.positionInSegment,n.len-1)),{segment:n,index:e}}#f(e){this.inlineError="",this.#s=null;let n=this.#a();n&&(this.#r.segmentIndex=Math.max(0,Math.min(this.#n.length-1,n.index+e)),this.#r.positionInSegment=0,this.#i=!0)}#l(e){let n=this.#a();if(!n)return;let{segment:t}=n,r=this.#e[t.type],i=!r||r.replace(/_/g,"")==="",o=Number.parseInt((r||"0").replace(/_/g,"0"),10)||0,s=yb(t.type,Go(this.#e),this.#o,this.#u),u;i?u=e===1?s.min:s.max:u=Math.max(Math.min(s.max,o+e),s.min),this.#e={...this.#e,[t.type]:u.toString().padStart(t.len,"0")},this.#i=!0,this.#s=null,this.#c()}#g(e){if(e)switch(e){case"right":return this.#f(1);case"left":return this.#f(-1);case"up":return this.#l(1);case"down":return this.#l(-1)}}#m(e,n){if(n?.name==="backspace"||n?.sequence===""||n?.sequence==="\b"||e===""||e==="\b"){this.inlineError="";let t=this.#a();if(!t)return;if(!this.#e[t.segment.type].replace(/_/g,"")){this.#f(-1);return}this.#e[t.segment.type]="_".repeat(t.segment.len),this.#i=!0,this.#r.positionInSegment=0,this.#c();return}if(n?.name==="tab"){this.inlineError="";let t=this.#a();if(!t)return;let r=n.shift?-1:1,i=t.index+r;i>=0&&i<this.#n.length&&(this.#r.segmentIndex=i,this.#r.positionInSegment=0,this.#i=!0);return}if(e&&/^[0-9]$/.test(e)){let t=this.#a();if(!t)return;let{segment:r}=t,i=!this.#e[r.type].replace(/_/g,"");if(this.#i&&this.#s!==null&&!i){let l=this.#s+e,d={...this.#e,[r.type]:l},g=this.#d(d,r);if(g){this.inlineError=g,this.#s=null,this.#i=!1;return}this.inlineError="",this.#e[r.type]=l,this.#s=null,this.#i=!1,this.#c(),t.index<this.#n.length-1&&(this.#r.segmentIndex=t.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.#s=null;let o=this.#e[r.type],s=o.indexOf("_"),u=s>=0?s:Math.min(this.#r.positionInSegment,r.len-1);if(u<0||u>=r.len)return;let c=o.slice(0,u)+e+o.slice(u+1),a=!1;if(u===0&&o==="__"&&(r.type==="month"||r.type==="day")){let l=Number.parseInt(e,10);c=`0${e}`,a=l<=(r.type==="month"?1:2)}if(r.type==="year"&&(c=(o.replace(/_/g,"")+e).padStart(r.len,"_")),!c.includes("_")){let l={...this.#e,[r.type]:c},d=this.#d(l,r);if(d){this.inlineError=d;return}}this.inlineError="",this.#e[r.type]=c;let f=c.includes("_")?void 0:vl(this.#e);if(f){let{year:l,month:d}=f,g=Tu(l,d);this.#e={year:String(Math.max(0,Math.min(9999,l))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,d))).padStart(2,"0"),day:String(Math.max(1,Math.min(g,f.day))).padStart(2,"0")}}this.#c();let h=c.indexOf("_");a?(this.#i=!0,this.#s=e):h>=0?this.#r.positionInSegment=h:s>=0&&t.index<this.#n.length-1?(this.#r.segmentIndex=t.index+1,this.#r.positionInSegment=0,this.#i=!0):this.#r.positionInSegment=Math.min(u+1,r.len-1)}}#d(e,n){let{month:t,day:r}=Go(e);if(n.type==="month"&&(t<0||t>12))return Ye.date.messages.invalidMonth;if(n.type==="day"&&(r<0||r>31))return Ye.date.messages.invalidDay(31,"any month")}#p(e){let{year:n,month:t,day:r}=Go(this.#e);if(n&&t&&r){let i=Tu(n,t);this.#e={...this.#e,day:String(Math.min(r,i)).padStart(2,"0")}}this.value=yl(this.#e)??e.defaultValue??void 0}}var Eb=class extends Rn{options;cursor=0;#n;getGroupItems(n){return this.options.filter((t)=>t.group===n)}isGroupSelected(n){let t=this.getGroupItems(n),r=this.value;return r===void 0?!1:t.every((i)=>r.includes(i.value))}toggleValue(){let n=this.options[this.cursor];if(n!==void 0)if(this.value===void 0&&(this.value=[]),n.group===!0){let t=n.value,r=this.getGroupItems(t);this.isGroupSelected(t)?this.value=this.value.filter((i)=>r.findIndex((o)=>o.value===i)===-1):this.value=[...this.value,...r.map((i)=>i.value)],this.value=Array.from(new Set(this.value))}else{let t=this.value.includes(n.value);this.value=t?this.value.filter((r)=>r!==n.value):[...this.value,n.value]}}constructor(n){super(n,!1);let{options:t}=n;this.#n=n.selectableGroups!==!1,this.options=Object.entries(t).flatMap(([r,i])=>[{value:r,group:!0,label:r},...i.map((o)=>({...o,group:r}))]),this.value=[...n.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:r})=>r===n.cursorAt),this.#n?0:1),this.on("cursor",(r)=>{switch(r){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let i=this.options[this.cursor]?.group===!0;!this.#n&&i&&(this.cursor=this.cursor===0?this.options.length-1:this.cursor-1);break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let i=this.options[this.cursor]?.group===!0;!this.#n&&i&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},Sb=new Set(["up","down","left","right"]);class Nl extends Rn{#n=!1;#t;focused="editor";get userInputWithCursor(){if(this.state==="submit")return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${e}█`;let n=e.slice(0,this.cursor),t=e.slice(this.cursor,this.cursor+1),r=e.slice(this.cursor+1);return t===`
319
319
  `?`${n}█
320
- ${r}`:`${n}${vo("inverse",t)}${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))}#o(e){let n=this.value??"";switch(e){case"up":this._cursor=Eo(this._cursor,0,-1,n);return;case"down":this._cursor=Eo(this._cursor,0,1,n);return;case"left":this._cursor=Eo(this._cursor,-1,0,n);return;case"right":this._cursor=Eo(this._cursor,1,0,n);return}}_shouldSubmit(e,n){if(this.#t)return this.focused==="submit"?!0:(this.#e(`
320
+ ${r}`:`${n}${Uo("inverse",t)}${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))}#o(e){let n=this.value??"";switch(e){case"up":this._cursor=Lo(this._cursor,0,-1,n);return;case"down":this._cursor=Lo(this._cursor,0,1,n);return;case"left":this._cursor=Lo(this._cursor,-1,0,n);return;case"right":this._cursor=Lo(this._cursor,1,0,n);return}}_shouldSubmit(e,n){if(this.#t)return this.focused==="submit"?!0:(this.#e(`
321
321
  `),this._cursor++,!1);let t=this.#n;return this.#n=!0,t&&this.cursor===this.userInput.length?(this.userInput[this.cursor-1]===`
322
322
  `&&(this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--),!0):(this.#e(`
323
- `),this._cursor++,!1)}constructor(e){let n=e.initialUserInput??e.initialValue;super({...e,initialUserInput:n},!1),n!==void 0&&(this._cursor=n.length),this.#t=e.showSubmit??!1,this.on("key",(t,r)=>{if(r?.name&&H0.has(r.name)){this.#n=!1,this.#o(r.name);return}if(t==="\t"&&this.#t){this.focused=this.focused==="editor"?"submit":"editor";return}if(r?.name!=="return"){if(this.#n=!1,r?.name==="backspace"&&this.cursor>0){this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--;return}if(r?.name==="delete"&&this.cursor<this.userInput.length){this._setUserInput(this.userInput.slice(0,this.cursor)+this.userInput.slice(this.cursor+1));return}t&&(this.#t&&this.focused==="submit"&&(this.focused="editor"),this.#e(t??""),this._cursor++)}}),this.on("userInput",(t)=>{this._setValue(t)}),this.on("finalize",()=>{this.value||(this.value=e.defaultValue),this.value===void 0&&(this.value="")})}}class $u extends Rn{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,n=this.value!==void 0&&this.value.length===e.length;this.value=n?[]:e.map((t)=>t.value)}toggleInvert(){let e=this.value;if(!e)return;let n=this._enabledOptions.filter((t)=>!e.includes(t.value));this.value=n.map((t)=>t.value)}toggleValue(){this.value===void 0&&(this.value=[]);let e=this.value.includes(this._value);this.value=e?this.value.filter((n)=>n!==this._value):[...this.value,this._value]}constructor(e){super(e,!1),this.options=e.options,this.value=[...e.initialValues??[]];let n=Math.max(this.options.findIndex(({value:t})=>t===e.cursorAt),0);this.cursor=this.options[n]?.disabled?tr(n,1,this.options):n,this.on("key",(t,r)=>{r.name==="a"&&this.toggleAll(),r.name==="i"&&this.toggleInvert()}),this.on("cursor",(t)=>{switch(t){case"left":case"up":this.cursor=tr(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=tr(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}class bu extends Rn{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${this.userInput}█`;let n=e.slice(0,this.cursor),t=e.slice(this.cursor,this.cursor+1),r=e.slice(this.cursor+1);return`${n}${vo("inverse",t)}${r}`}get cursor(){return this._cursor}constructor(e){super({...e,initialUserInput:e.initialUserInput??e.initialValue}),this.on("userInput",(n)=>{this._setValue(n)}),this.on("finalize",()=>{this.value||(this.value=e.defaultValue),this.value===void 0&&(this.value="")})}}import{styleText as v,stripVTControlCharacters as LS}from"node:util";import hn from"node:process";var nl=Ci(lu(),1);function L0(){if(hn.platform!=="win32")return hn.env.TERM!=="linux";return Boolean(hn.env.CI)||Boolean(hn.env.WT_SESSION)||Boolean(hn.env.TERMINUS_SUBLIME)||hn.env.ConEmuTask==="{cmd::Cmder}"||hn.env.TERM_PROGRAM==="Terminus-Sublime"||hn.env.TERM_PROGRAM==="vscode"||hn.env.TERM==="xterm-256color"||hn.env.TERM==="alacritty"||hn.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var A0=L0();var be=(e,n)=>A0?e:n,T0=be("◆","*"),G0=be("■","x"),U0=be("▲","x"),tl=be("◇","o"),j0=be("┌","T"),le=be("│","|"),ot=be("└","—"),US=be("┐","T"),jS=be("┘","—"),Xf=be("●",">"),Vf=be("○"," "),J0=be("◻","[•]"),zf=be("◼","[+]"),Bf=be("◻","[ ]"),JS=be("▪","•"),Df=be("─","-"),C0=be("╮","+"),W0=be("├","+"),K0=be("╯","+"),_0=be("╰","+"),CS=be("╭","+"),WS=be("●","•"),KS=be("◆","*"),_S=be("▲","!"),qS=be("■","x"),ku=(e)=>{switch(e){case"initial":case"active":return v("cyan",T0);case"cancel":return v("red",G0);case"error":return v("yellow",U0);case"submit":return v("green",tl)}},q0=(e)=>{switch(e){case"initial":case"active":return v("cyan",le);case"cancel":return v("red",le);case"error":return v("yellow",le);case"submit":return v("green",le)}};function Q0(e,n){let t=[`${n?`${v("cyan",le)} `:""}${e.join(" • ")}`];return n&&t.push(v("cyan",ot)),t}var xf=(e,n,t,r,i,o=!1)=>{let s=n,u=0;if(o)for(let c=r-1;c>=t;c--){let a=e[c];if(a&&(s-=a.length),u++,s<=i)break}else for(let c=t;c<r;c++){let a=e[c];if(a&&(s-=a.length),u++,s<=i)break}return{lineCount:s,removals:u}},el=({cursor:e,options:n,style:t,output:r=process.stdout,maxItems:i=Number.POSITIVE_INFINITY,columnPadding:o=0,rowPadding:s=4})=>{let u=Mo(r)-o,c=pu(r),a=v("dim","..."),h=Math.max(c-s,0),f=Math.max(Math.min(i,h),5),l=0;e>=f-3&&(l=Math.max(Math.min(e-f+3,n.length-f),0));let d=f<n.length&&l>0,g=f<n.length&&l+f<n.length,p=Math.min(l+f,n.length),k=[],y=0;d&&y++,g&&y++;let M=l+(d?1:0),b=p-(g?1:0);for(let m=M;m<b;m++){let P=n[m],E=P?t(P,m===e):"",R=it(E,u,{hard:!0,trim:!1}).split(`
324
- `);k.push(R),y+=R.length}if(y>h){let m=0,P=0,E=y,R=e-M,N=h,H=()=>xf(k,E,0,R,N),A=()=>xf(k,E,R+1,k.length,N,!0);d?({lineCount:E,removals:m}=H(),E>N&&(g||(N-=1),{lineCount:E,removals:P}=A())):(g||(N-=1),{lineCount:E,removals:P}=A(),E>N&&(N-=1,{lineCount:E,removals:m}=H())),m>0&&(d=!0,k.splice(0,m)),P>0&&(g=!0,k.splice(k.length-P,P))}let S=[];d&&S.push(a);for(let m of k)for(let P of m)S.push(P);return g&&S.push(a),S};var st=(e)=>{let n=e.active??"Yes",t=e.inactive??"No";return new wu({active:n,inactive:t,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let r=e.withGuide??Ve.withGuide,i=`${ku(this.state)} `,o=r?`${v("gray",le)} `:"",s=li(e.output,e.message,o,i),u=`${r?`${v("gray",le)}
323
+ `),this._cursor++,!1)}constructor(e){let n=e.initialUserInput??e.initialValue;super({...e,initialUserInput:n},!1),n!==void 0&&(this._cursor=n.length),this.#t=e.showSubmit??!1,this.on("key",(t,r)=>{if(r?.name&&Sb.has(r.name)){this.#n=!1,this.#o(r.name);return}if(t==="\t"&&this.#t){this.focused=this.focused==="editor"?"submit":"editor";return}if(r?.name!=="return"){if(this.#n=!1,r?.name==="backspace"&&this.cursor>0){this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--;return}if(r?.name==="delete"&&this.cursor<this.userInput.length){this._setUserInput(this.userInput.slice(0,this.cursor)+this.userInput.slice(this.cursor+1));return}t&&(this.#t&&this.focused==="submit"&&(this.focused="editor"),this.#e(t??""),this._cursor++)}}),this.on("userInput",(t)=>{this._setValue(t)}),this.on("finalize",()=>{this.value||(this.value=e.defaultValue),this.value===void 0&&(this.value="")})}}class ju extends Rn{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,n=this.value!==void 0&&this.value.length===e.length;this.value=n?[]:e.map((t)=>t.value)}toggleInvert(){let e=this.value;if(!e)return;let n=this._enabledOptions.filter((t)=>!e.includes(t.value));this.value=n.map((t)=>t.value)}toggleValue(){this.value===void 0&&(this.value=[]);let e=this.value.includes(this._value);this.value=e?this.value.filter((n)=>n!==this._value):[...this.value,this._value]}constructor(e){super(e,!1),this.options=e.options,this.value=[...e.initialValues??[]];let n=Math.max(this.options.findIndex(({value:t})=>t===e.cursorAt),0);this.cursor=this.options[n]?.disabled?lr(n,1,this.options):n,this.on("key",(t,r)=>{r.name==="a"&&this.toggleAll(),r.name==="i"&&this.toggleInvert()}),this.on("cursor",(t)=>{switch(t){case"left":case"up":this.cursor=lr(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=lr(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}class Cu extends Rn{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${this.userInput}█`;let n=e.slice(0,this.cursor),t=e.slice(this.cursor,this.cursor+1),r=e.slice(this.cursor+1);return`${n}${Uo("inverse",t)}${r}`}get cursor(){return this._cursor}constructor(e){super({...e,initialUserInput:e.initialUserInput??e.initialValue}),this.on("userInput",(n)=>{this._setValue(n)}),this.on("finalize",()=>{this.value||(this.value=e.defaultValue),this.value===void 0&&(this.value="")})}}import{styleText as E,stripVTControlCharacters as GM}from"node:util";import ln from"node:process";var Tl=Vi(Au(),1);function Mb(){if(ln.platform!=="win32")return ln.env.TERM!=="linux";return Boolean(ln.env.CI)||Boolean(ln.env.WT_SESSION)||Boolean(ln.env.TERMINUS_SUBLIME)||ln.env.ConEmuTask==="{cmd::Cmder}"||ln.env.TERM_PROGRAM==="Terminus-Sublime"||ln.env.TERM_PROGRAM==="vscode"||ln.env.TERM==="xterm-256color"||ln.env.TERM==="alacritty"||ln.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var vb=Mb();var ke=(e,n)=>vb?e:n,Ib=ke("◆","*"),Nb=ke("■","x"),Ob=ke("▲","x"),Ju=ke("◇","o"),Rb=ke("┌","T"),le=ke("│","|"),ut=ke("└","—"),JM=ke("┐","T"),_M=ke("┘","—"),Ol=ke("●",">"),Rl=ke("○"," "),Fb=ke("◻","[•]"),Fl=ke("◼","[+]"),Pl=ke("◻","[ ]"),WM=ke("▪","•"),Al=ke("─","-"),Pb=ke("╮","+"),Ab=ke("├","+"),Hb=ke("╯","+"),Lb=ke("╰","+"),KM=ke("╭","+"),Tb=ke("●","•"),Gb=ke("◆","*"),Ub=ke("▲","!"),jb=ke("■","x"),_u=(e)=>{switch(e){case"initial":case"active":return E("cyan",Ib);case"cancel":return E("red",Nb);case"error":return E("yellow",Ob);case"submit":return E("green",Ju)}},Cb=(e)=>{switch(e){case"initial":case"active":return E("cyan",le);case"cancel":return E("red",le);case"error":return E("yellow",le);case"submit":return E("green",le)}};function Jb(e,n){let t=[`${n?`${E("cyan",le)} `:""}${e.join(" • ")}`];return n&&t.push(E("cyan",ut)),t}var Hl=(e,n,t,r,i,o=!1)=>{let s=n,u=0;if(o)for(let c=r-1;c>=t;c--){let a=e[c];if(a&&(s-=a.length),u++,s<=i)break}else for(let c=t;c<r;c++){let a=e[c];if(a&&(s-=a.length),u++,s<=i)break}return{lineCount:s,removals:u}},Ll=({cursor:e,options:n,style:t,output:r=process.stdout,maxItems:i=Number.POSITIVE_INFINITY,columnPadding:o=0,rowPadding:s=4})=>{let u=jo(r)-o,c=Gu(r),a=E("dim","..."),f=Math.max(c-s,0),h=Math.max(Math.min(i,f),5),l=0;e>=h-3&&(l=Math.max(Math.min(e-h+3,n.length-h),0));let d=h<n.length&&l>0,g=h<n.length&&l+h<n.length,m=Math.min(l+h,n.length),$=[],S=0;d&&S++,g&&S++;let v=l+(d?1:0),k=m-(g?1:0);for(let p=v;p<k;p++){let A=n[p],y=A?t(A,p===e):"",F=ot(y,u,{hard:!0,trim:!1}).split(`
324
+ `);$.push(F),S+=F.length}if(S>f){let p=0,A=0,y=S,F=e-v,N=f,H=()=>Hl($,y,0,F,N),G=()=>Hl($,y,F+1,$.length,N,!0);d?({lineCount:y,removals:p}=H(),y>N&&(g||(N-=1),{lineCount:y,removals:A}=G())):(g||(N-=1),{lineCount:y,removals:A}=G(),y>N&&(N-=1,{lineCount:y,removals:p}=H())),p>0&&(d=!0,$.splice(0,p)),A>0&&(g=!0,$.splice($.length-A,A))}let M=[];d&&M.push(a);for(let p of $)for(let A of p)M.push(A);return g&&M.push(a),M};var ct=(e)=>{let n=e.active??"Yes",t=e.inactive??"No";return new Uu({active:n,inactive:t,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let r=e.withGuide??Ye.withGuide,i=`${_u(this.state)} `,o=r?`${E("gray",le)} `:"",s=Ei(e.output,e.message,o,i),u=`${r?`${E("gray",le)}
325
325
  `:""}${s}
326
- `,c=this.value?n:t;switch(this.state){case"submit":{let a=r?`${v("gray",le)} `:"";return`${u}${a}${v("dim",c)}`}case"cancel":{let a=r?`${v("gray",le)} `:"";return`${u}${a}${v(["strikethrough","dim"],c)}${r?`
327
- ${v("gray",le)}`:""}`}default:{let a=r?`${v("cyan",le)} `:"",h=r?v("cyan",ot):"";return`${u}${a}${this.value?`${v("green",Xf)} ${n}`:`${v("dim",Vf)} ${v("dim",n)}`}${e.vertical?r?`
328
- ${v("cyan",le)} `:`
329
- `:` ${v("dim","/")} `}${this.value?`${v("dim",Vf)} ${v("dim",t)}`:`${v("green",Xf)} ${t}`}
330
- ${h}
331
- `}}}}).prompt()};var Y0=[`${v("dim","↑/↓")} to navigate`,`${v("dim","Space:")} select`,`${v("dim","Enter:")} confirm`],di=(e,n)=>e.split(`
326
+ `,c=this.value?n:t;switch(this.state){case"submit":{let a=r?`${E("gray",le)} `:"";return`${u}${a}${E("dim",c)}`}case"cancel":{let a=r?`${E("gray",le)} `:"";return`${u}${a}${E(["strikethrough","dim"],c)}${r?`
327
+ ${E("gray",le)}`:""}`}default:{let a=r?`${E("cyan",le)} `:"",f=r?E("cyan",ut):"";return`${u}${a}${this.value?`${E("green",Ol)} ${n}`:`${E("dim",Rl)} ${E("dim",n)}`}${e.vertical?r?`
328
+ ${E("cyan",le)} `:`
329
+ `:` ${E("dim","/")} `}${this.value?`${E("dim",Rl)} ${E("dim",t)}`:`${E("green",Ol)} ${t}`}
330
+ ${f}
331
+ `}}}}).prompt()};var _b=[`${E("dim","↑/↓")} to navigate`,`${E("dim","Space:")} select`,`${E("dim","Enter:")} confirm`],Si=(e,n)=>e.split(`
332
332
  `).map((t)=>n(t)).join(`
333
- `),rl=(e)=>{let n=(i,o)=>{let s=i.label??String(i.value);return o==="disabled"?`${v("gray",Bf)} ${di(s,(u)=>v(["strikethrough","gray"],u))}${i.hint?` ${v("dim",`(${i.hint??"disabled"})`)}`:""}`:o==="active"?`${v("cyan",J0)} ${s}${i.hint?` ${v("dim",`(${i.hint})`)}`:""}`:o==="selected"?`${v("green",zf)} ${di(s,(u)=>v("dim",u))}${i.hint?` ${v("dim",`(${i.hint})`)}`:""}`:o==="cancelled"?`${di(s,(u)=>v(["strikethrough","dim"],u))}`:o==="active-selected"?`${v("green",zf)} ${s}${i.hint?` ${v("dim",`(${i.hint})`)}`:""}`:o==="submitted"?`${di(s,(u)=>v("dim",u))}`:`${v("dim",Bf)} ${di(s,(u)=>v("dim",u))}`},t=e.required??!0,r=e.showInstructions??!0;return new $u({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValues:e.initialValues,required:t,cursorAt:e.cursorAt,validate(i){if(t&&(i===void 0||i.length===0))return`Please select at least one option.
334
- ${v("reset",v("dim",`Press ${v(["gray","bgWhite","inverse"]," space ")} to select, ${v("gray",v("bgWhite",v("inverse"," enter ")))} to submit`))}`},render(){let i=e.withGuide??Ve.withGuide,o=li(e.output,e.message,i?`${q0(this.state)} `:"",`${ku(this.state)} `),s=`${i?`${v("gray",le)}
333
+ `),Gl=(e)=>{let n=(i,o)=>{let s=i.label??String(i.value);return o==="disabled"?`${E("gray",Pl)} ${Si(s,(u)=>E(["strikethrough","gray"],u))}${i.hint?` ${E("dim",`(${i.hint??"disabled"})`)}`:""}`:o==="active"?`${E("cyan",Fb)} ${s}${i.hint?` ${E("dim",`(${i.hint})`)}`:""}`:o==="selected"?`${E("green",Fl)} ${Si(s,(u)=>E("dim",u))}${i.hint?` ${E("dim",`(${i.hint})`)}`:""}`:o==="cancelled"?`${Si(s,(u)=>E(["strikethrough","dim"],u))}`:o==="active-selected"?`${E("green",Fl)} ${s}${i.hint?` ${E("dim",`(${i.hint})`)}`:""}`:o==="submitted"?`${Si(s,(u)=>E("dim",u))}`:`${E("dim",Pl)} ${Si(s,(u)=>E("dim",u))}`},t=e.required??!0,r=e.showInstructions??!0;return new ju({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValues:e.initialValues,required:t,cursorAt:e.cursorAt,validate(i){if(t&&(i===void 0||i.length===0))return`Please select at least one option.
334
+ ${E("reset",E("dim",`Press ${E(["gray","bgWhite","inverse"]," space ")} to select, ${E("gray",E("bgWhite",E("inverse"," enter ")))} to submit`))}`},render(){let i=e.withGuide??Ye.withGuide,o=Ei(e.output,e.message,i?`${Cb(this.state)} `:"",`${_u(this.state)} `),s=`${i?`${E("gray",le)}
335
335
  `:""}${o}
336
- `,u=this.value??[],c=(a,h)=>{if(a.disabled)return n(a,"disabled");let f=u.includes(a.value);return h&&f?n(a,"active-selected"):f?n(a,"selected"):n(a,h?"active":"inactive")};switch(this.state){case"submit":{let a=this.options.filter(({value:f})=>u.includes(f)).map((f)=>n(f,"submitted")).join(v("dim",", "))||v("dim","none"),h=li(e.output,a,i?`${v("gray",le)} `:"");return`${s}${h}`}case"cancel":{let a=this.options.filter(({value:f})=>u.includes(f)).map((f)=>n(f,"cancelled")).join(v("dim",", "));if(a.trim()==="")return`${s}${v("gray",le)}`;let h=li(e.output,a,i?`${v("gray",le)} `:"");return`${s}${h}${i?`
337
- ${v("gray",le)}`:""}`}case"error":{let a=i?`${v("yellow",le)} `:"",h=this.error.split(`
338
- `).map((d,g)=>g===0?`${i?`${v("yellow",ot)} `:""}${v("yellow",d)}`:` ${d}`).join(`
339
- `),f=s.split(`
340
- `).length,l=h.split(`
341
- `).length+1;return`${s}${a}${el({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:a.length,rowPadding:f+l,style:c}).join(`
336
+ `,u=this.value??[],c=(a,f)=>{if(a.disabled)return n(a,"disabled");let h=u.includes(a.value);return f&&h?n(a,"active-selected"):h?n(a,"selected"):n(a,f?"active":"inactive")};switch(this.state){case"submit":{let a=this.options.filter(({value:h})=>u.includes(h)).map((h)=>n(h,"submitted")).join(E("dim",", "))||E("dim","none"),f=Ei(e.output,a,i?`${E("gray",le)} `:"");return`${s}${f}`}case"cancel":{let a=this.options.filter(({value:h})=>u.includes(h)).map((h)=>n(h,"cancelled")).join(E("dim",", "));if(a.trim()==="")return`${s}${E("gray",le)}`;let f=Ei(e.output,a,i?`${E("gray",le)} `:"");return`${s}${f}${i?`
337
+ ${E("gray",le)}`:""}`}case"error":{let a=i?`${E("yellow",le)} `:"",f=this.error.split(`
338
+ `).map((d,g)=>g===0?`${i?`${E("yellow",ut)} `:""}${E("yellow",d)}`:` ${d}`).join(`
339
+ `),h=s.split(`
340
+ `).length,l=f.split(`
341
+ `).length+1;return`${s}${a}${Ll({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:a.length,rowPadding:h+l,style:c}).join(`
342
342
  ${a}`)}
343
- ${h}
344
- `}default:{let a=i?`${v("cyan",le)} `:"",h=s.split(`
345
- `).length,f=r?Q0(Y0,i):i?[v("cyan",ot)]:[],l=f.join(`
346
- `),d=f.length+1;return`${s}${a}${el({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:a.length,rowPadding:h+d,style:c}).join(`
343
+ ${f}
344
+ `}default:{let a=i?`${E("cyan",le)} `:"",f=s.split(`
345
+ `).length,h=r?Jb(_b,i):i?[E("cyan",ut)]:[],l=h.join(`
346
+ `),d=h.length+1;return`${s}${a}${Ll({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:a.length,rowPadding:f+d,style:c}).join(`
347
347
  ${a}`)}
348
348
  ${l}
349
- `}}}}).prompt()};var rr=(e="",n)=>{let t=n?.output??process.stdout,r=n?.withGuide??Ve.withGuide?`${v("gray",ot)} `:"";t.write(`${r}${v("red",e)}
349
+ `}}}}).prompt()};var st={message:(e=[],{symbol:n=E("gray",le),secondarySymbol:t=E("gray",le),output:r=process.stdout,spacing:i=1,withGuide:o}={})=>{let s=[],u=o??Ye.withGuide,c=u?t:"",a=u?`${n} `:"",f=u?`${t} `:"";for(let l=0;l<i;l++)s.push(c);let h=Array.isArray(e)?e:e.split(`
350
+ `);if(h.length>0){let[l,...d]=h;l.length>0?s.push(`${a}${l}`):s.push(u?n:"");for(let g of d)g.length>0?s.push(`${f}${g}`):s.push(u?t:"")}r.write(`${s.join(`
351
+ `)}
352
+ `)},info:(e,n)=>{st.message(e,{...n,symbol:E("blue",Tb)})},success:(e,n)=>{st.message(e,{...n,symbol:E("green",Gb)})},step:(e,n)=>{st.message(e,{...n,symbol:E("green",Ju)})},warn:(e,n)=>{st.message(e,{...n,symbol:E("yellow",Ub)})},warning:(e,n)=>{st.warn(e,n)},error:(e,n)=>{st.message(e,{...n,symbol:E("red",jb)})}},dr=(e="",n)=>{let t=n?.output??process.stdout,r=n?.withGuide??Ye.withGuide?`${E("gray",ut)} `:"";t.write(`${r}${E("red",e)}
350
353
 
351
- `)},Io=(e="",n)=>{let t=n?.output??process.stdout,r=n?.withGuide??Ve.withGuide?`${v("gray",j0)} `:"";t.write(`${r}${e}
352
- `)},Eu=(e="",n)=>{let t=n?.output??process.stdout,r=n?.withGuide??Ve.withGuide?`${v("gray",le)}
353
- ${v("gray",ot)} `:"";t.write(`${r}${e}
354
+ `)},Co=(e="",n)=>{let t=n?.output??process.stdout,r=n?.withGuide??Ye.withGuide?`${E("gray",Rb)} `:"";t.write(`${r}${e}
355
+ `)},Wu=(e="",n)=>{let t=n?.output??process.stdout,r=n?.withGuide??Ye.withGuide?`${E("gray",le)}
356
+ ${E("gray",ut)} `:"";t.write(`${r}${e}
354
357
 
355
- `)};var Z0=(e)=>e,X0=(e,n,t)=>{let r={hard:!0,trim:!1},i=it(e,n,r).split(`
356
- `),o=i.reduce((c,a)=>Math.max(Xe(a),c),0),s=i.map(t).reduce((c,a)=>Math.max(Xe(a),c),0),u=n-(s-o);return it(e,u,r)},vt=(e="",n="",t)=>{let r=t?.output??hn.stdout,i=t?.withGuide??Ve.withGuide,o=t?.format??Z0,s=["",...X0(e,Mo(r)-6,o).split(`
357
- `).map(o),""],u=Xe(n),c=Math.max(s.reduce((l,d)=>{let g=Xe(d);return g>l?g:l},0),u)+2,a=s.map((l)=>`${v("gray",le)} ${l}${" ".repeat(c-Xe(l))}${v("gray",le)}`).join(`
358
- `),h=i?`${v("gray",le)}
359
- `:"",f=i?W0:_0;r.write(`${h}${v("green",tl)} ${v("reset",n)} ${v("gray",Df.repeat(Math.max(c-u-1,1))+C0)}
358
+ `)};var Wb=(e)=>e,Kb=(e,n,t)=>{let r={hard:!0,trim:!1},i=ot(e,n,r).split(`
359
+ `),o=i.reduce((c,a)=>Math.max(Ve(a),c),0),s=i.map(t).reduce((c,a)=>Math.max(Ve(a),c),0),u=n-(s-o);return ot(e,u,r)},Ft=(e="",n="",t)=>{let r=t?.output??ln.stdout,i=t?.withGuide??Ye.withGuide,o=t?.format??Wb,s=["",...Kb(e,jo(r)-6,o).split(`
360
+ `).map(o),""],u=Ve(n),c=Math.max(s.reduce((l,d)=>{let g=Ve(d);return g>l?g:l},0),u)+2,a=s.map((l)=>`${E("gray",le)} ${l}${" ".repeat(c-Ve(l))}${E("gray",le)}`).join(`
361
+ `),f=i?`${E("gray",le)}
362
+ `:"",h=i?Ab:Lb;r.write(`${f}${E("green",Ju)} ${E("reset",n)} ${E("gray",Al.repeat(Math.max(c-u-1,1))+Pb)}
360
363
  ${a}
361
- ${v("gray",f+Df.repeat(c+2)+K0)}
362
- `)};var QS={light:be("─","-"),heavy:be("━","="),block:be("█","#")};var YS=[`${v("dim","↑/↓")} to navigate`,`${v("dim","Enter:")} confirm`];var ZS=`${v("gray",le)} `;var yu=(e)=>new bu({validate:e.validate,placeholder:e.placeholder,defaultValue:e.defaultValue,initialValue:e.initialValue,output:e.output,signal:e.signal,input:e.input,render(){let n=e?.withGuide??Ve.withGuide,t=`${`${n?`${v("gray",le)}
363
- `:""}${ku(this.state)} `}${e.message}
364
- `,r=e.placeholder&&e.placeholder.length>0?v("inverse",e.placeholder[0])+v("dim",e.placeholder.slice(1)):v(["inverse","hidden"],"_"),i=this.userInput?this.userInputWithCursor:r,o=this.value??"";switch(this.state){case"error":{let s=this.error?` ${v("yellow",this.error)}`:"",u=n?`${v("yellow",le)} `:"",c=n?v("yellow",ot):"";return`${t.trim()}
364
+ ${E("gray",h+Al.repeat(c+2)+Hb)}
365
+ `)};var qM={light:ke("─","-"),heavy:ke("━","="),block:ke("█","#")};var QM=[`${E("dim","↑/↓")} to navigate`,`${E("dim","Enter:")} confirm`];var YM=`${E("gray",le)} `;var Ku=(e)=>new Cu({validate:e.validate,placeholder:e.placeholder,defaultValue:e.defaultValue,initialValue:e.initialValue,output:e.output,signal:e.signal,input:e.input,render(){let n=e?.withGuide??Ye.withGuide,t=`${`${n?`${E("gray",le)}
366
+ `:""}${_u(this.state)} `}${e.message}
367
+ `,r=e.placeholder&&e.placeholder.length>0?E("inverse",e.placeholder[0])+E("dim",e.placeholder.slice(1)):E(["inverse","hidden"],"_"),i=this.userInput?this.userInputWithCursor:r,o=this.value??"";switch(this.state){case"error":{let s=this.error?` ${E("yellow",this.error)}`:"",u=n?`${E("yellow",le)} `:"",c=n?E("yellow",ut):"";return`${t.trim()}
365
368
  ${u}${i}
366
369
  ${c}${s}
367
- `}case"submit":{let s=o?` ${v("dim",o)}`:"",u=n?v("gray",le):"";return`${t}${u}${s}`}case"cancel":{let s=o?` ${v(["strikethrough","dim"],o)}`:"",u=n?v("gray",le):"";return`${t}${u}${s}${o.trim()?`
368
- ${u}`:""}`}default:{let s=n?`${v("cyan",le)} `:"",u=n?v("cyan",ot):"";return`${t}${s}${i}
370
+ `}case"submit":{let s=o?` ${E("dim",o)}`:"",u=n?E("gray",le):"";return`${t}${u}${s}`}case"cancel":{let s=o?` ${E(["strikethrough","dim"],o)}`:"",u=n?E("gray",le):"";return`${t}${u}${s}${o.trim()?`
371
+ ${u}`:""}`}default:{let s=n?`${E("cyan",le)} `:"",u=n?E("cyan",ut):"";return`${t}${s}${i}
369
372
  ${u}
370
- `}}}}).prompt();import{existsSync as ml,readFileSync as Ou}from"node:fs";import{join as pl}from"node:path";import{existsSync as e$,readdirSync as n$,readFileSync as t$}from"node:fs";import{basename as r$,join as Fo}from"node:path";import{existsSync as V0,readFileSync as il}from"node:fs";import{homedir as ol}from"node:os";import{isAbsolute as sl,join as Mt,resolve as z0}from"node:path";var Ge="official",Jn="ttheme-market.json",No="ttheme-market",B0=/^[a-z0-9](?:[a-z0-9]|-(?=[a-z0-9])){0,38}$/i,D0=/^[\w.-]{1,100}$/;function ir(e){return Mt(e,"ttheme","installed.json")}function Cn(e){return e??[Ge]}function or(e){try{let{markets:n}=JSON.parse(il(ir(e),"utf8"));return Cn(Array.isArray(n)?n.filter((t)=>typeof t==="string"):void 0)}catch{return[Ge]}}function Wn(e){return sl(e)}function Oo(e){return e!==Ge&&!Wn(e)}function sr(e,n=process.cwd()){if(e===Ge)return Ge;if(e==="~"||e.startsWith("~/"))return Mt(ol(),e.slice(1));if(e.startsWith(".")||sl(e))return z0(n,e);let[t,r,...i]=e.replace(/^https:\/\/github\.com\//,"").replace(/\.git$/,"").split("/");if(!t||!B0.test(t)||!r||!D0.test(r)||i.length>0)throw Error(`${e} is not a market — give a repository (alice/ttheme-dust) or a path (./my-market)`);return`${t.toLowerCase()}/${r}`}function ul(e){return`https://raw.githubusercontent.com/${e}/HEAD/${Jn}`}function cl(e){return e.slice(0,e.indexOf("/"))}function x0(e){return Mt(e,"ttheme","markets")}function It(e,n){return Mt(x0(e),`${n.replace("/","--")}.json`)}function Ro(e){return Mt(e,"ttheme","market")}function Su(e,n){return Mt(Ro(e),n)}function vu(e,n){if(typeof e!=="string"||typeof n!=="string")return'needs an "owner" (the GitHub handle) and a "name"';return Nn(`${e}@${n}/x`)}function Fn({owner:e,name:n}){return`${e}@${n}`}function Nt(e){let n=Mt(e,Jn);if(!V0(n))throw Error(`${e} has no ${Jn} — \`ttheme market init ${e}\` makes one`);let t;try{t=JSON.parse(il(n,"utf8"))}catch{throw Error(`${n} is not valid JSON`)}let r=vu(t.owner,t.name);if(r)throw Error(`${n} ${r}`);return{owner:t.owner,name:t.name}}function $n(e){if(e===Ge)return"the ttheme catalog";if(!Wn(e))return`github.com/${e}`;let n=ol();return e===n||e.startsWith(`${n}/`)?`~${e.slice(n.length)}`:e}var ut="tt1:",al=["background","foreground","cursor","selection",...Array.from({length:16},(e,n)=>`ansi${n}`)];function Ot(e,n=!0){return or(e).filter(Wn).flatMap((t)=>{try{let r=Nt(t);return[{dir:t,...r,id:Fn(r)}]}catch(r){if(n)process.stderr.write(`ttheme: skipping the market at ${t} — ${r.message}
371
- `);return[]}})}function Rt(e){return Fo(e,"palettes")}function Mu(e,n){let t=Te(n);if(!t)throw Error(`${n} is an official palette — yours are named <you>@<market>/<palette>`);let r=Ot(e,!1).find((i)=>i.id===t);if(!r)throw Error(`${t} is not a local market — \`ttheme market add <dir>\` adds the folder that holds it`);return Fo(Rt(r.dir),`${ao(n)}.toml`)}function i$(e,n){let t=new Map;for(let i of n)if(i.group!==Wr&&!t.has(i.group)){let o=n.find((s)=>s.group===i.group&&s.lead)?.name??"";t.set(i.group,{name:i.group,...i.native?{native:i.native}:{},lead:o})}let r=new Map(n.filter((i)=>!i.default&&!Te(i.name)).map((i)=>[i.name,{group:i.group,order:i.order}]));return{name:e,groups:t,bases:r,open:!0}}function Kn(e,n,t){let r=ao(e),{native:i,...o}=qs(`${r}.toml`,n,i$(r,t)),s=Te(e);return{...o,name:e,...s?{group:s,lead:!1}:{}}}function mi(e,n,t,r=!0){let i=Rt(e);return(e$(i)?n$(i).sort():[]).filter((o)=>o.endsWith(".toml")).flatMap((o)=>{try{let s=t$(Fo(i,o),"utf8");return[wn(Kn(`${n}/${r$(o,".toml")}`,s,t))]}catch(s){if(r)process.stderr.write(`ttheme: skipping ${Fo(i,o)} — ${s.message}
372
- `);return[]}})}function Po(e,n,t=!0){return Ot(e,t).flatMap(({dir:r,id:i})=>mi(r,i,n,t))}function Iu(e,n=e.name,t){return{name:n,...e.base?{base:e.base}:{},...e.group!==Wr?{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:t??"kept from the palette"}:{},...e.pictures?{pictures:e.pictures}:{}}}var Pe=(e)=>JSON.stringify(e);function Nu(e){let n=["[meta]",`name = ${Pe(ao(e.name))}`,...e.base?[`base = ${Pe(e.base)}`]:[],...e.group?[`group = ${Pe(e.group)}`]:[],...e.ansiSource?[`ansi_source = ${Pe(e.ansiSource)}`]:[],...e.booru?[`booru = ${Pe(e.booru)}`]:[],`signature = [${e.signature.map(Pe).join(", ")}]`,...e.booruSites?["","[meta.booru_sites]",...Object.entries(e.booruSites).map(([t,r])=>`${t} = [${r.map(Pe).join(", ")}]`)]:[],"","[colors]",`background = ${Pe(e.background)}`,`foreground = ${Pe(e.foreground)}`,`cursor = ${Pe(e.cursor)}`,`selection_background = ${Pe(e.selection)}`,"ansi = [",...e.ansi.slice(0,8).map((t)=>` ${Pe(t)},`),"",...e.ansi.slice(8).map((t)=>` ${Pe(t)},`),"]"];if(e.waive&&e.waive.length>0)n.push("","[contrast]",`waive = [${e.waive.map(Pe).join(", ")}]`,`reason = ${Pe(e.reason??"")}`);for(let t of e.pictures??[]){if(n.push("","[[picture]]",`site = ${Pe(t.site)}`,`id = ${t.id}`),t.size!==void 0)n.push(`size = ${typeof t.size==="number"?t.size:Pe(t.size)}`);if(t.position!==void 0)n.push(`position = ${Pe(t.position)}`);if(t.opacity!==void 0)n.push(`opacity = ${t.opacity}`)}return`${n.join(`
373
+ `}}}}).prompt();import{existsSync as Xl,readFileSync as zu}from"node:fs";import{join as zl}from"node:path";import{existsSync as zb,readdirSync as Vb,readFileSync as Bb}from"node:fs";import{basename as Db,join as Ko}from"node:path";import{existsSync as qb,readFileSync as Ul}from"node:fs";import{homedir as jl}from"node:os";import{isAbsolute as Cl,join as Pt,resolve as Qb}from"node:path";var Ue="official",Wn="ttheme-market.json",Jo="ttheme-market",Yb=/^[a-z0-9](?:[a-z0-9]|-(?=[a-z0-9])){0,38}$/i,Zb=/^[\w.-]{1,100}$/;function gr(e){return Pt(e,"ttheme","installed.json")}function Kn(e){return e??[Ue]}function mr(e){try{let{markets:n}=JSON.parse(Ul(gr(e),"utf8"));return Kn(Array.isArray(n)?n.filter((t)=>typeof t==="string"):void 0)}catch{return[Ue]}}function qn(e){return Cl(e)}function _o(e){return e!==Ue&&!qn(e)}function pr(e,n=process.cwd()){if(e===Ue)return Ue;if(e==="~"||e.startsWith("~/"))return Pt(jl(),e.slice(1));if(e.startsWith(".")||Cl(e))return Qb(n,e);let[t,r,...i]=e.replace(/^https:\/\/github\.com\//,"").replace(/\.git$/,"").split("/");if(!t||!Yb.test(t)||!r||!Zb.test(r)||i.length>0)throw Error(`${e} is not a market — give a repository (alice/ttheme-dust) or a path (./my-market)`);return`${t.toLowerCase()}/${r}`}function Jl(e){return`https://raw.githubusercontent.com/${e}/HEAD/${Wn}`}function _l(e){return e.slice(0,e.indexOf("/"))}function Xb(e){return Pt(e,"ttheme","markets")}function At(e,n){return Pt(Xb(e),`${n.replace("/","--")}.json`)}function Wo(e){return Pt(e,"ttheme","market")}function qu(e,n){return Pt(Wo(e),n)}function Qu(e,n){if(typeof e!=="string"||typeof n!=="string")return'needs an "owner" (the GitHub handle) and a "name"';return On(`${e}@${n}/x`)}function Fn({owner:e,name:n}){return`${e}@${n}`}function Ht(e){let n=Pt(e,Wn);if(!qb(n))throw Error(`${e} has no ${Wn} — \`ttheme market init ${e}\` makes one`);let t;try{t=JSON.parse(Ul(n,"utf8"))}catch{throw Error(`${n} is not valid JSON`)}let r=Qu(t.owner,t.name);if(r)throw Error(`${n} ${r}`);return{owner:t.owner,name:t.name}}function kn(e){if(e===Ue)return"the ttheme catalog";if(!qn(e))return`github.com/${e}`;let n=jl();return e===n||e.startsWith(`${n}/`)?`~${e.slice(n.length)}`:e}var at="tt1:",Wl=["background","foreground","cursor","selection",...Array.from({length:16},(e,n)=>`ansi${n}`)];function Lt(e,n=!0){return mr(e).filter(qn).flatMap((t)=>{try{let r=Ht(t);return[{dir:t,...r,id:Fn(r)}]}catch(r){if(n)process.stderr.write(`ttheme: skipping the market at ${t} — ${r.message}
374
+ `);return[]}})}function Tt(e){return Ko(e,"palettes")}function Yu(e,n){let t=Ge(n);if(!t)throw Error(`${n} is an official palette — yours are named <you>@<market>/<palette>`);let r=Lt(e,!1).find((i)=>i.id===t);if(!r)throw Error(`${t} is not a local market — \`ttheme market add <dir>\` adds the folder that holds it`);return Ko(Tt(r.dir),`${$o(n)}.toml`)}function xb(e,n){let t=new Map;for(let i of n)if(i.group!==ni&&!t.has(i.group)){let o=n.find((s)=>s.group===i.group&&s.lead)?.name??"";t.set(i.group,{name:i.group,...i.native?{native:i.native}:{},lead:o})}let r=new Map(n.filter((i)=>!i.default&&!Ge(i.name)).map((i)=>[i.name,{group:i.group,order:i.order}]));return{name:e,groups:t,bases:r,open:!0}}function Qn(e,n,t){let r=$o(e),{native:i,...o}=ou(`${r}.toml`,n,xb(r,t)),s=Ge(e);return{...o,name:e,...s?{group:s,lead:!1}:{}}}function vi(e,n,t,r=!0){let i=Tt(e);return(zb(i)?Vb(i).sort():[]).filter((o)=>o.endsWith(".toml")).flatMap((o)=>{try{let s=Bb(Ko(i,o),"utf8");return[$n(Qn(`${n}/${Db(o,".toml")}`,s,t))]}catch(s){if(r)process.stderr.write(`ttheme: skipping ${Ko(i,o)} — ${s.message}
375
+ `);return[]}})}function qo(e,n,t=!0){return Lt(e,t).flatMap(({dir:r,id:i})=>vi(r,i,n,t))}function Zu(e,n=e.name,t){return{name:n,...e.base?{base:e.base}:{},...e.group!==ni?{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:t??"kept from the palette"}:{},...e.pictures?{pictures:e.pictures}:{}}}var Ae=(e)=>JSON.stringify(e);function Xu(e){let n=["[meta]",`name = ${Ae($o(e.name))}`,...e.base?[`base = ${Ae(e.base)}`]:[],...e.group?[`group = ${Ae(e.group)}`]:[],...e.ansiSource?[`ansi_source = ${Ae(e.ansiSource)}`]:[],...e.booru?[`booru = ${Ae(e.booru)}`]:[],`signature = [${e.signature.map(Ae).join(", ")}]`,...e.booruSites?["","[meta.booru_sites]",...Object.entries(e.booruSites).map(([t,r])=>`${t} = [${r.map(Ae).join(", ")}]`)]:[],"","[colors]",`background = ${Ae(e.background)}`,`foreground = ${Ae(e.foreground)}`,`cursor = ${Ae(e.cursor)}`,`selection_background = ${Ae(e.selection)}`,"ansi = [",...e.ansi.slice(0,8).map((t)=>` ${Ae(t)},`),"",...e.ansi.slice(8).map((t)=>` ${Ae(t)},`),"]"];if(e.waive&&e.waive.length>0)n.push("","[contrast]",`waive = [${e.waive.map(Ae).join(", ")}]`,`reason = ${Ae(e.reason??"")}`);for(let t of e.pictures??[]){if(n.push("","[[picture]]",`site = ${Ae(t.site)}`,`id = ${t.id}`),t.size!==void 0)n.push(`size = ${typeof t.size==="number"?t.size:Ae(t.size)}`);if(t.position!==void 0)n.push(`position = ${Ae(t.position)}`);if(t.opacity!==void 0)n.push(`opacity = ${t.opacity}`)}return`${n.join(`
373
376
  `)}
374
- `}class hl{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 n=new TextEncoder().encode(e);if(n.length>255)throw Error(`"${e}" is too long to share`);this.u8(n.length),this.bytes.push(...n)}color(e){let n=Number.parseInt(e.slice(1),16);this.u8(n>>16),this.u8(n>>8),this.u8(n)}done(){return Buffer.from(this.bytes).toString("base64url")}}class fl{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(),n=this.bytes.subarray(this.at,this.at+e);if(n.length!==e)throw Error("the share code is cut short");return this.at+=e,new TextDecoder("utf-8",{fatal:!0}).decode(n)}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 ll(e){let n=new hl;n.str(e.name);for(let r of[e.background,e.foreground,e.cursor,e.selection,...e.ansi])n.color(r);for(let r of e.signature)n.u8(al.indexOf(r));n.str(e.base),n.str(e.group),n.str(e.ansiSource),n.str(e.booru),n.u16((e.waive??[]).reduce((r,i)=>r|1<<$s.indexOf(i),0)),n.str(e.waive&&e.waive.length>0?e.reason:"");let t=e.pictures??[];n.u8(t.length);for(let r of t)n.u8(x.findIndex((i)=>i.key===r.site)),n.u32(r.id),n.u16(r.size===void 0?0:r.size==="fill"?1:r.size),n.u8(r.position===void 0?0:Et.indexOf(r.position)+1),n.u16(r.opacity===void 0?0:Math.round(r.opacity*1000)+1);return`${ut}${n.done()}`}function dl(e){if(!e.startsWith(ut))throw Error(`a share code starts with ${ut}`);let n=e.slice(ut.length);if(!/^[A-Za-z0-9_-]+$/.test(n))throw Error("the share code holds characters it never uses — was it copied whole?");let t=new fl(new Uint8Array(Buffer.from(n,"base64url"))),r=t.str(),[i,o,s,u,...c]=Array.from({length:20},()=>t.color()),a=[t.u8(),t.u8(),t.u8()].map((M)=>al[M]??`slot${M}`),h=t.str(),f=t.str(),l=t.str(),d=t.str(),g=t.u16(),p=t.str(),k=$s.filter((M,b)=>g&1<<b),y=Array.from({length:t.u8()},()=>{let M=x[t.u8()]?.key??"unknown",b=t.u32(),S=t.u16(),m=t.u8(),P=t.u16();return{site:M,id:b,...S===1?{size:"fill"}:S>1?{size:S}:{},...m>0?{position:Et[m-1]??"unknown"}:{},...P>0?{opacity:(P-1)/1000}:{}}});if(t.end(),![i,o,s,u,...c].every(Wt))throw Error("the share code holds a color that is not one");return{name:r,...h?{base:h}:{},...f?{group:f}:{},...l?{ansiSource:l}:{},...d?{booru:d}:{},signature:a,background:i,foreground:o,cursor:s,selection:u,ansi:c,...k.length>0?{waive:k,reason:p}:{},...y.length>0?{pictures:y}:{}}}function gl(e,n){let t=e.indexOf("ansi = ["),r=e.indexOf("]",t);if(t<0||r<0)throw Error("no ansi = [...] list to rewrite");let i=0,o=e.slice(t,r).replace(/"#[0-9a-fA-F]{6}"/g,()=>Pe(n.ansi[i++]));return(e.slice(0,t)+o+e.slice(r)).replace(/^(foreground\s*=\s*)"#[0-9a-fA-F]{6}"/m,(s,u)=>`${u}${Pe(n.foreground)}`).replace(/^(selection_background\s*=\s*)"#[0-9a-fA-F]{6}"/m,(s,u)=>`${u}${Pe(n.selectionBackground)}`)}function pi(e){let n=qt(cn(e)),t=new Set(e.waived??[]),r=Math.max(...gt.map((i)=>i.label.length));return gt.map((i,o)=>{let s=n[o],u=t.has(i.rule)||Number.isNaN(s)||(i.min===void 0||s>=i.min)&&(i.max===void 0||s<=i.max),c=i.min!==void 0?`≥ ${i.min}`:i.max!==void 0?`≤ ${i.max}`:"",a=Number.isNaN(s)?"—":Number.isInteger(s)?String(s):s.toFixed(2);return` ${u?"✓":"✗"} ${i.label.padEnd(r)} ${a.padStart(6)} ${c}${t.has(i.rule)?" waived":""}`})}var Ru="https://kecan0406.github.io/ttheme/manifest.json",o$=20000;function Ft(e){return pl(e,"ttheme","catalog.json")}function wi(e,n){$e(Ft(e),`${JSON.stringify(n,null,2)}
375
- `)}function He(e){let n=or(e),t=Ft(e),r=Dr();if(n.includes(Ge)){if(!ml(t))throw Error(`no catalog at ${t} — run \`ttheme init\` first`);r=ct(Ou(t,"utf8"))}let i=n.filter(Oo).flatMap((o)=>s$(e,o));return{...r,palettes:[...r.palettes,...i]}}function Ho(e,n){return Fu(Ou(It(e,n),"utf8"))}function $i(e,n){return Fn({owner:cl(e),name:n.name})}function s$(e,n){let t=It(e,n);if(!ml(t))return[];try{let r=Ho(e,n);return u$(r,$i(n,r))}catch(r){return process.stderr.write(`ttheme: skipping ${t} — ${r.message}
376
- `),[]}}function Fu(e){let n=ct(e),t=vu(n.owner,n.name);if(t)throw Error(`market index ${t}`);let r=n.palettes.find((i)=>Te(i.name)!==void 0);if(r)throw Error(`market index names ${r.name} with its market — its entries are bare palette names`);return n}function u$(e,n){return e.palettes.map(({lead:t,default:r,native:i,...o})=>({...o,name:`${n}/${o.name}`,group:n}))}function ct(e){let n;try{n=JSON.parse(e)}catch{throw Error("catalog is not valid JSON")}let t=n;if(typeof t?.version!=="string"||!Array.isArray(t.palettes))throw Error("catalog has no version or palettes");for(let r of t.palettes){let i=wl(r);if(i)throw Error(`catalog entry ${JSON.stringify(r?.name)} ${i}`)}return t}function wl(e){if(typeof e?.name!=="string"||!Array.isArray(e.ansi)||e.ansi.length!==16)return"is missing name or its 16 ANSI colors";let n=Nn(e.name)??(e.base===void 0?void 0:Nn(e.base));if(n)return n;if(![e.background,e.foreground,e.cursor,e.selection,...e.ansi].every((t)=>typeof t==="string"&&Wt(t)))return'holds a color that is not "#rrggbb"';for(let t of[e.group,e.native??"-",e.ansiSource]){let r=typeof t==="string"?_s(t):"has a field that is not text";if(r)return r}return}function $l(e){return pl(e,"ttheme","kept.json")}function Lo(e,n){$e($l(e),`${JSON.stringify({palettes:n},null,2)}
377
- `)}function bi(e){try{let{palettes:n}=JSON.parse(Ou($l(e),"utf8"));return Array.isArray(n)?n.filter((t)=>wl(t)===void 0):[]}catch{return[]}}function Ue(e,n,t=!0){let r=[...n.palettes,...Po(e,n.palettes,t)],i=new Set(r.map((o)=>o.name));return{...n,palettes:[...r,...bi(e).filter((o)=>!i.has(o.name))]}}function ur(e){return Ue(e,He(e))}class Ao extends Error{}class To extends Error{}async function ki(e,n){let t;try{t=await fetch(e,{signal:AbortSignal.timeout(o$)})}catch(r){throw Error(`cannot reach ${e} — ${r instanceof Error?r.message:String(r)}`)}if(t.status===404)throw new Ao(`nothing at ${e}`);if(t.status===403||t.status===429)throw new To(`${new URL(e).host} is turning requests away for now (${t.status}) — try again in a minute`);if(!t.ok)throw Error(`${e} answered ${t.status}`);return n(await t.text())}function Pu(e){let n=new Set(e.waived??[]),t=e.gate??qt(cn(e));return gt.flatMap((r,i)=>{let o=t[i];if(n.has(r.rule)||typeof o!=="number"||Number.isNaN(o))return[];if(r.min!==void 0&&o<r.min)return[`${r.label} ${o} < ${r.min}`];if(r.max!==void 0&&o>r.max)return[`${r.label} ${o} > ${r.max}`];return[]})}function Pt(e,n){let t=e.find((r)=>r.name===n);if(!t)throw Error(`no palette named ${n} in the catalog — ${Hu(e,[n])}`);return t}function Hu(e,n){let t=n.map((s)=>s.toLowerCase()),r=e.filter((s)=>t.some((u)=>s.name.includes(u))),i=e.filter((s)=>!r.includes(s)&&t.some((u)=>s.group.toLowerCase().includes(u))),o=[...r,...i].map((s)=>s.name).slice(0,3);return o.length>0?`did you mean: ${o.join(", ")}?`:"`ttheme list` shows what is there"}function bl(e,n){let t=n.toLowerCase();return e.filter((r)=>[r.name,r.group,r.native??"",r.ansiSource].some((i)=>i.toLowerCase().includes(t)))}function kl(e,n,t){let r=t.toLowerCase(),i=(o)=>o.name===n.name?0:o.group===n.group?1:2;return e.filter((o)=>o.booru?.toLowerCase().includes(r)).map((o,s)=>({p:o,at:s})).sort((o,s)=>i(o.p)-i(s.p)||o.at-s.at).map(({p:o})=>o)}function El(e,n){return e.booruSites?.[n]??(e.booru?[e.booru]:[])}var Au=5,c$=6,yl=0.05,a$=[1,2,3,4,5,6,9,10,11,12,13,14],Sl=(e,n)=>(n-e+360)%360<=180?1:-1;function Lu(e,n,t){let r=n*Math.cos(t*Math.PI/180),i=n*Math.sin(t*Math.PI/180),o=[e+0.3963377774*r+0.2158037573*i,e-0.1055613458*r-0.0638541728*i,e-0.0894841775*r-1.291485548*i].map((h)=>h**3),[s,u,c]=o,a=[4.0767416621*s-3.3077115913*u+0.2309699292*c,-1.2684380046*s+2.6097574011*u-0.3413193965*c,-0.0041960863*s-0.7034186147*u+1.707614701*c];if(a.some((h)=>h<-0.0001||h>1.0001))return;return a.map((h)=>{let f=Math.min(1,Math.max(0,h));return Math.round(255*(f<=0.0031308?12.92*f:1.055*f**0.4166666666666667-0.055))})}function Go(e,n,t){let r=0,i=n;if(Lu(e,n,t)===void 0)for(let s=0;s<24;s++){let u=(r+i)/2;if(Lu(e,u,t)===void 0)i=u;else r=u}else r=n;return`#${(Lu(e,r,t)??[0,0,0]).map((s)=>s.toString(16).padStart(2,"0")).join("")}`}function h$(e,n){let{l:t,c:r}=dn(e);return Go(t,r,(n+360)%360)}function f$(e,n,t){let{l:r,c:i,h:o}=dn(e),s=Qe(n)<0.18,u=(h)=>Go(s?r+(1-r)*h:r*(1-h),i,o);if(Be(u(1),n)<t+yl)return u(1);let c=0,a=1;for(let h=0;h<30;h++){let f=(c+a)/2;if(Be(u(f),n)>=t+yl)a=f;else c=f}return u(a)}function l$(e,n){let{l:t,c:r,h:i}=dn(e),o=0,s=t;for(let u=0;u<30;u++){let c=(o+s)/2;if(Qe(Go(c,r,i))<=n-0.005)o=c;else s=c}return Go(o,r,i)}function d$(e,n,t){let r=Or[n],[i,o]=[dn(e[n]),dn(e[n+8])],s=(h,f)=>t.has(h)?[f]:Array.from({length:2*r.width+1},(l,d)=>(r.center-r.width+d+360)%360),u=(h,f,l)=>Kt.every((d)=>{let g=(h>8?8:0)+d;if(g===h)return!0;let p=dn(e[g]);return p.c<ws||Xn(p.h,f)>=Qi+1||Math.abs(p.l-l)>=Yi}),c,a=Number.POSITIVE_INFINITY;for(let h of s(n,i.h)){if(!t.has(n)&&!u(n,h,i.l))continue;for(let f of s(n+8,o.h)){if(Xn(h,f)>dt-Au||!t.has(n+8)&&!u(n+8,f,o.l))continue;let l=Xn(h,i.h)+Xn(f,o.h);if(l<a)a=l,c=[h,f]}}return c}class vl{theme;moves=[];constructor(e){this.theme={...e,ansi:[...e.ansi]}}set(e,n,t){let r=this.get(e);if(t===r)return;if(this.moves.push({slot:e,rule:n,from:r,to:t}),e==="foreground")this.theme.foreground=t;else if(e==="selection")this.theme.selectionBackground=t;else this.theme.ansi[Number(e.slice(4))]=t}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,n,t){this.set(`ansi${e}`,n,h$(this.theme.ansi[e],t))}roles(){let e=new Set(this.theme.signatureSlots);for(let{slot:t,hue:r}of Ki(this.theme)){let i=Or[_t(t)];this.rehue(t,"ansi-role",i.center+Sl(i.center,r)*(i.width-Au))}for(let{normal:t,gap:r}of _i(this.theme)){if(r<=dt)continue;let[i,o]=e.has(`ansi${t+8}`)?[t+8,t]:[t,t+8],s=dn(this.theme.ansi[i]).h,u=dn(this.theme.ansi[o]).h;this.rehue(o,"bright-follows",s+Sl(s,u)*(dt-Au))}let n=Zi(this.theme);for(let[t,r]of qi(this.theme)){let i=_t(n.has(r)?t:r),o=d$(this.theme.ansi,i,n);if(o===void 0)continue;this.rehue(i,"distinct",o[0]),this.rehue(i+8,"distinct",o[1])}}readability(){let e=new Set(this.theme.waive),{background:n}=this.theme,t=(r,i,o,s=n)=>{if(e.has(r))return;for(let u of i)if(Be(this.get(u),s)<o)this.set(u,r,f$(this.get(u),s,o))};if(t("foreground",["foreground"],7),t("accents",a$.map((r)=>`ansi${r}`),3),t("light-ansi",["ansi7","ansi15"],7),t("ansi8-visible",["ansi8"],1.6),!e.has("ansi0-dark")&&Qe(this.get("ansi0"))>0.15)this.set("ansi0","ansi0-dark",l$(this.get("ansi0"),0.15));t("selection",["selection"],7,this.theme.foreground)}net(){return[...new Set(this.moves.map((e)=>e.slot))].flatMap((e)=>{let n=this.moves.filter((i)=>i.slot===e),t=n[0].from,r=this.get(e);return t===r?[]:[{slot:e,rule:[...new Set(n.map((i)=>i.rule))].join(", "),from:t,to:r}]})}}function Ml(e){let n=new vl(e);for(let t=0;t<c$;t++)if(n.readability(),n.roles(),Vi(n.theme).length===0)break;return{theme:n.theme,moves:n.net(),left:Vi(n.theme)}}import{execFileSync as N$}from"node:child_process";import{existsSync as Si,mkdirSync as Wo,readdirSync as jl,readFileSync as _o,rmSync as Tl}from"node:fs";import{basename as Jl,join as En}from"node:path";import{execFileSync as g$,spawn as m$}from"node:child_process";import{existsSync as bn,mkdirSync as p$,readFileSync as cr,realpathSync as w$,rmSync as Tu,utimesSync as $$,writeFileSync as b$}from"node:fs";import{homedir as ar}from"node:os";import{dirname as k$,join as Ie}from"node:path";var E$={ghostty:Qr,kitty:Zr,alacritty:qr,wezterm:ai,iterm2:Yr,"windows-terminal":hi,warp:ci},Il="ttheme-default";function _n(e=process.env.TTHEME_ITERM_SUITE??"com.googlecode.iterm2"){let n=(t,r)=>g$(t,r,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();return{read:()=>{try{return process.platform==="darwin"?n("defaults",["read",e,"Default Bookmark Guid"])||void 0:void 0}catch{return}},write:(t)=>{if(process.platform==="darwin")n("defaults",["write",e,"Default Bookmark Guid","-string",t])},running:()=>{try{return n("pgrep",["-x","iTerm2"])!==""}catch{return!1}}}}function kn(e){return e.off?void 0:Qn(e)}function Ei(e,n){if(!e.terminals.includes("iterm2"))return e;let t=n.read();return t&&!t.startsWith("ttheme-")?{...e,itermBase:t}:e}function At(e,n){if(!e.terminals.includes("iterm2"))return!1;let t=n.read(),r=kn(e)?Il:t===Il?e.itermBase:void 0;if(!r||r===t)return!1;return n.write(r),!0}function de(){return process.env.XDG_CONFIG_HOME??Ie(ar(),".config")}function yi(e){return Ie(e,"Library","Application Support","iTerm2","DynamicProfiles","ttheme.json")}function ke(e){let n=ir(e);if(!bn(n))throw Error(`nothing installed yet at ${n} — run \`ttheme init\` first`);let t=JSON.parse(cr(n,"utf8"));if(!Array.isArray(t?.palettes)||!Array.isArray(t.terminals))throw Error(`${n} has no palettes or terminals`);return{terminals:t.terminals.filter((r)=>go.includes(r)),...t.author?{author:t.author}:{},...t.startup?{startup:t.startup}:{},...t.off?{off:!0}:{},...t.itermBase?{itermBase:t.itermBase}:{},...t.wtHome?{wtHome:t.wtHome}:{},...t.wtProfile?{wtProfile:t.wtProfile}:{},...Array.isArray(t.markets)?{markets:t.markets.filter((r)=>typeof r==="string")}:{},palettes:t.palettes}}function qn(e,n){$e(ir(e),`${JSON.stringify(n,null,2)}
378
- `)}function Nl(e,n){let t=new Map(e.palettes.map((i)=>[i.name,i])),r=n.filter((i)=>!t.has(i));if(r.length>0){let i=[...new Set(r.flatMap((s)=>Te(s)??[]))].filter((s)=>!e.palettes.some((u)=>Te(u.name)===s)),o=i.length>0?`add ${i.join(", ")} first — \`ttheme market search\` finds a market's repository`:Hu(an(e.palettes),r);throw Error(`not in any market: ${r.join(", ")} — ${o}`)}return e.palettes.filter((i)=>n.includes(i.name))}function Ol(e,n){let t=e==="wezterm"?"colors":"themes";return(E$[e].emit?.(n)??[]).flatMap((r)=>{let[,i,o]=r.path.split("/");return i===t&&o!==void 0?[{file:o,content:r.content}]:[]})}function Uo(e){return process.platform==="darwin"?Ie(e,".warp","themes"):Ie(process.env.XDG_DATA_HOME??Ie(e,".local","share"),"warp-terminal","themes")}function Ht(e,n,t){if(e==="warp")return Uo(t);return Ie(n,e,e==="wezterm"?"colors":"themes")}function jo(e,n){return process.platform==="darwin"?Ie(e,".warp","settings.toml"):Ie(n,"warp-terminal","settings.toml")}var Gu='"dark"';function Uu(e){return Ie(e,"ttheme","warp.base")}var y$="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 S$(e,n,t,r){let i=jo(n,e);if(!bn(i))return;let o=Uu(e),s=cr(i,"utf8"),u=po(s),c=u?.includes(`path = "${fe("")}`)===!0,a;if(t){if(!c&&!bn(o))p$(k$(o),{recursive:!0}),b$(o,u??"");a=wf(t)}else{if(!c)return;a=bn(o)&&cr(o,"utf8")||Gu,Tu(o,{force:!0})}let h=wo(s,a);if(h===s)return;if(r)Ys(i),m$(process.execPath,["-e",y$,w$(i),h,s],{detached:!0,stdio:"ignore"}).unref();else Xr(i,h);return i}function Rl(e){return Ie(e,"ttheme","kitty.py")}function hr(e,n){let t=Ie(n,".wezterm.lua");return bn(t)?t:Ie(e,"wezterm","wezterm.lua")}function Jo(e){return Ie(e,"Microsoft","Windows Terminal","Fragments","ttheme","ttheme.json")}function ju(e){return[Ie(e,"Packages","Microsoft.WindowsTerminal_8wekyb3d8bbwe","LocalState","settings.json"),Ie(e,"Packages","Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe","LocalState","settings.json"),Ie(e,"Microsoft","Windows Terminal","settings.json")].filter((n)=>bn(n))}function v$(e){for(let n of e){let t=/"defaultProfile"\s*:\s*"(\{[0-9a-fA-F-]+\})"/.exec(cr(n,"utf8"))?.[1];if(t)return t}return}function Qn(e){return e.startup&&e.palettes.includes(e.startup)?e.startup:e.palettes[0]}function Lt(e,n){return e==="ghostty"?Ie(n,"ghostty","config"):Ie(n,"kitty","kitty.conf")}function Fl(e,n,t,r){return e==="ghostty"?rf(Ie(n,"ttheme"),t,r):hf(t,Rl(n),r)}function Pn(e){return bn(e)?cr(e,"utf8"):""}function Tt(e){return Ie(e,"alacritty","alacritty.toml")}function M$(e,n){return n?Ie(e,"alacritty","themes",`${fe(n)}.toml`):void 0}function Pl(e,n,t,r){let i=Ze(e),o=n.map(cn),s=new Map;for(let c of o){let a=Qh(i,c.name,r);if(a)s.set(c.name,a)}let u=new Set(an(n).map((c)=>c.name));return Nh(o.filter((c)=>u.has(c.name)),s,o.find((c)=>c.name===kn(t)),t.itermBase)}function at(e,n=ar()){let t=ke(e);if(!t.terminals.includes("iterm2"))return;$e(yi(n),Pl(e,Nl(ur(e),t.palettes),t,n))}function nn(e,n,t,r=ar()){On(Ze(e));let i=Nl(Ue(e,n),t.palettes);Lo(e,i);let o=[],s=(l,d)=>{if(o.push(l),bn(l)&&cr(l,"utf8")===d)return!1;return $e(l,d),!0},u=(l,d)=>{o.push(l),Xr(l,d)},c=kn(t),a=!1;for(let l of t.terminals){if(l==="iterm2"){s(yi(r),Pl(e,i,t,r));continue}if(l==="windows-terminal"){if(t.wtHome){let y=ju(t.wtHome),M=i.map(cn),b=su(M,t.wtProfile??v$(y),c);if(s(Jo(t.wtHome),b)){let S=new Date;for(let m of y)$$(m,S,S);a=y.length>0}}continue}let d=c!==void 0&&l==="warp"&&!bn(Ie(Uo(r),`${fe(c)}.yaml`)),g=l==="warp"?S$(e,r,c,d):void 0;for(let y of i)for(let{file:M,content:b}of Ol(l,cn(y)))s(Ie(Ht(l,e,r),M),b);if(l==="warp"){if(g)o.push(g);continue}if(l==="wezterm"){let y=Ie(e,"ttheme","wezterm.lua");s(y,kf({path:y,colors:Ht("wezterm",e,r),backgrounds:Ze(e),...c?{startup:c}:{},palettes:i.map(cn)}));let M=hr(e,r),b=ui(Pn(M),lf(y));if(b!==void 0)u(M,b);continue}if(l==="alacritty"){let y=Tt(e),M=si(Pn(y),M$(e,c));if(M!==void 0)u(y,M);continue}if(l==="kitty")s(Rl(e),Oh({themes:Ht("kitty",e,r),backgrounds:Ze(e)}));let p=Lt(l,e),k=Pn(p);u(p,ri(k,Fl(l,e,c,k)))}let h=Ie(e,"ttheme","palettes.zsh"),f=iu(i,c,t.terminals);if(a||Pn(h)!==f)$e(h,f),Tu(`${h}.zwc`,{force:!0});return o.push(h),o}function Hl(e,n){return e.startsWith(`${n}/`)?`~${e.slice(n.length)}`:e}function I$(e){return[...new Set(e.split(`
379
- `).map((n)=>n.split(/[ =]/)[0]))].join(", ")}function Ll(e,n,t=ar()){let r=kn(n),i=(s)=>Hl(s,t),o=[];for(let s of n.terminals){if(s==="iterm2"){o.push(`write ${i(yi(t))} — a "ttheme · <palette>" profile per palette`);continue}if(s==="windows-terminal"){if(n.wtHome)o.push(`write ${Jo(n.wtHome)} — its schemes, and touch settings.json so it reloads`);continue}if(o.push(`write ${i(Ht(s,e,t))}/${fe("*")} — a theme file per palette`),s==="warp"){let a=jo(t,e);if(r&&bn(a))o.push(`edit ${i(a)} — [appearance.themes] theme; \`ttheme off\` puts yours back`);continue}if(s==="wezterm"){let a=hr(e,t);if(ui(Pn(a),"")!==void 0)o.push(`edit ${i(a)} — a ttheme block before \`return config\`: color_scheme_dirs, color_scheme, pictures`);continue}if(s==="alacritty"){let a=Tt(e);if(si(Pn(a),void 0)!==void 0)o.push(`edit ${i(a)} — a ttheme block: general.import`);continue}let u=Lt(s,e),c=Pn(u);o.push(`edit ${i(u)} — a ttheme block: ${I$(Fl(s,e,r,c))}`)}return o}function Al(e,n,t=ar()){let r=[],i=(o)=>Hl(o,t);if(n.includes("ghostty")){let o=Lt("ghostty",e);if(St(Pn(o),"command"))r.push(`${i(o)} sets its own command — ttheme leaves it, so a new tab takes its palette once zsh starts`)}if(n.includes("kitty")){let o=Pn(Lt("kitty",e));if(St(o,"window_logo_scale")||St(o,"window_logo_alpha"))r.push("kitty.conf sets its own window_logo_scale or window_logo_alpha — pictures are drawn with them")}if(n.includes("alacritty")){let o=Tt(e);if(ff(Pn(o)))r.push(`${i(o)} sets its own colors, which win over an imported palette — remove them to open with ttheme's`)}return r}function Ju(e,n,t,r,i=ar()){let o=[],s=Ue(e,n,!1).palettes;for(let u of t)for(let c of s.filter((a)=>r.includes(a.name)))for(let{file:a}of Ol(u,cn(c))){let h=Ie(Ht(u,e,i),a);if(bn(h))Tu(h,{force:!0}),o.push(h)}return o}function ht(e,n,t,r){let i=_n(),o=Boolean(kn(t))!==Boolean(kn(r)),s=o?Ei(r,i):r;return nn(e,n,s),qn(e,s),o&&At(s,i)&&i.running()}var Cl=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,O$=["add","remove","search","init"];function Wl(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function R$(){try{let e=N$("gh",["api","user","--jq",".login"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4}).trim().toLowerCase();return Cl.test(e)?e:void 0}catch{return}}async function F$(e,n){if(n.author)return n.author;let t=R$();if(!t){if(!Wl())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 yu({message:"your GitHub handle — your palettes are named <handle>@<market>/<palette>",validate:(i)=>Cl.test((i??"").toLowerCase())&&(i??"").length<=39?void 0:"that is not a GitHub handle"});if(en(r))throw Error("no handle given");t=r.toLowerCase()}return qn(e,{...n,author:t}),console.log(`your palettes are named ${t}@<market>/<palette>`),t}function Yn(e){return`${e} palette${e===1?"":"s"}`}function Cu(e,n){if(n===Ge)return Ge;return Wn(n)?Fn(Nt(n)):$i(n,Ho(e,n))}function Ko(e,n){try{return Cu(e,n)}catch{return}}function Kl(e){return Te(e)??Ge}function qo(e){return He(e).palettes.filter((n)=>Te(n.name)===void 0)}function P$(e){let n=En(import.meta.dirname,"..","dist","manifest.json");return Si(n)?ct(_o(n,"utf8")).palettes:qo(e)}async function _l(e){try{return await ki(ul(e),Fu)}catch(n){if(n instanceof Ao)throw Error(`github.com/${e} has no ${Jn} — is the repository public, and has its action run?`);throw n}}function Co(e,n,t){let r=ke(e),i=Cn(r.markets),o=i.find((s)=>s!==n&&Ko(e,s)===t);if(o)throw Error(`${t} already names the market at ${$n(o)} — \`ttheme market remove ${t}\` first`);if(!i.includes(n))qn(e,{...r,markets:[...i,n]});return i}async function H$(e){let n=de(),t=sr(e);if(Cn(ke(n).markets).includes(t)){console.log(`${$n(t)} is already added`);return}if(t===Ge){let o=await ki(Ru,ct);Co(n,t,Ge),wi(n,o),console.log(`added the ttheme catalog — ${Yn(an(o.palettes).length)} · \`ttheme browse\` picks them`);return}if(Wn(t)){let o=Fn(Nt(t));Co(n,t,o);let s=mi(t,o,qo(n)).length;console.log(`added ${o} · ${$n(t)} — ${Yn(s)}, read in place`),console.log("\n`ttheme browse` picks them · `ttheme market build` there writes the index others fetch");return}let r=await _l(t),i=$i(t,r);Co(n,t,i),Wo(En(n,"ttheme","markets"),{recursive:!0}),$e(It(n,t),`${JSON.stringify(r,null,2)}
380
- `),console.log(`added ${i} · ${$n(t)} — ${Yn(r.palettes.length)}`),console.log(`
381
- \`ttheme browse\` picks them, or \`ttheme add ${i}/<palette>\``)}function L$(e){let n=de(),t=ke(n),r=Cn(t.markets),i=r.find((c)=>Ko(n,c)===e)??r.find((c)=>c===ql(e));if(!i)throw Error(`no market named ${e} — \`ttheme market\` lists them`);let o=Ko(n,i),s=t.palettes.filter((c)=>Kl(c)===o),u={...t,markets:r.filter((c)=>c!==i)};if(qn(n,u),i===Ge)Tl(Ft(n),{force:!0});else if(Oo(i))Tl(It(n,i),{force:!0});if(nn(n,He(n),u),console.log(`removed ${o??e} · ${$n(i)}`),s.length>0)console.log(`${Yn(s.length)} installed from it keep working — \`ttheme remove\` drops them`)}function ql(e){try{return sr(e)}catch{return}}function A$(e,n){try{if(n===Ge)return an(ct(_o(Ft(e),"utf8")).palettes).length;if(Wn(n))return mi(n,Cu(e,n),qo(e),!1).length;return Ho(e,n).palettes.length}catch{return}}function T$(){let e=de(),n=ke(e),t=Cn(n.markets);if(t.length===0){console.log("no markets — `ttheme market add official` brings the ttheme catalog back");return}let r=t.map((s)=>{let u=Ko(e,s)??"?",c=A$(e,s),a=n.palettes.filter((h)=>Kl(h)===u).length;return{name:u,where:$n(s),note:c===void 0?"unreadable":`${Yn(c)}${a>0?` · ${a} installed`:""}`}}),i=Math.max(...r.map((s)=>s.name.length)),o=Math.max(...r.map((s)=>s.where.length));for(let s of r)console.log(` ${s.name.padEnd(i)} ${s.where.padEnd(o)} ${s.note}`)}async function G$(e){try{let{items:n}=await ki(`https://api.github.com/search/repositories?q=${e}&sort=stars&per_page=50`,(t)=>JSON.parse(t));return n}catch(n){if(n instanceof To)throw Error("GitHub lets a search through about ten times a minute without signing in — try again in a minute");throw n}}async function U$(e){let n=de(),t=encodeURIComponent(`topic:${No}${e?` ${e}`:""}`),r=await G$(t);if(r.length===0){console.log(`no repository carries the ${No} topic${e?` and matches ${e}`:""} yet`);return}let i=new Set(Cn(ke(n).markets)),o=r.map((u)=>{let c=u.owner.login.toLowerCase();return{arg:`${c}/${u.name}`,added:i.has(`${c}/${u.name}`),stars:`★${u.stargazers_count}`,about:u.description??""}}),s=Math.max(...o.map((u)=>u.arg.length));for(let u of o)console.log(` ${u.added?"●":"○"} ${u.arg.padEnd(s)} ${u.stars.padStart(5)} ${u.about}`);console.log("\n`ttheme market add <name>` adds one")}var j$=`name: ttheme market
377
+ `}class Kl{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 n=new TextEncoder().encode(e);if(n.length>255)throw Error(`"${e}" is too long to share`);this.u8(n.length),this.bytes.push(...n)}color(e){let n=Number.parseInt(e.slice(1),16);this.u8(n>>16),this.u8(n>>8),this.u8(n)}done(){return Buffer.from(this.bytes).toString("base64url")}}class ql{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(),n=this.bytes.subarray(this.at,this.at+e);if(n.length!==e)throw Error("the share code is cut short");return this.at+=e,new TextDecoder("utf-8",{fatal:!0}).decode(n)}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 Ql(e){let n=new Kl;n.str(e.name);for(let r of[e.background,e.foreground,e.cursor,e.selection,...e.ansi])n.color(r);for(let r of e.signature)n.u8(Wl.indexOf(r));n.str(e.base),n.str(e.group),n.str(e.ansiSource),n.str(e.booru),n.u16((e.waive??[]).reduce((r,i)=>r|1<<Ps.indexOf(i),0)),n.str(e.waive&&e.waive.length>0?e.reason:"");let t=e.pictures??[];n.u8(t.length);for(let r of t)n.u8(x.findIndex((i)=>i.key===r.site)),n.u32(r.id),n.u16(r.size===void 0?0:r.size==="fill"?1:r.size),n.u8(r.position===void 0?0:vt.indexOf(r.position)+1),n.u16(r.opacity===void 0?0:Math.round(r.opacity*1000)+1);return`${at}${n.done()}`}function Yl(e){if(!e.startsWith(at))throw Error(`a share code starts with ${at}`);let n=e.slice(at.length);if(!/^[A-Za-z0-9_-]+$/.test(n))throw Error("the share code holds characters it never uses — was it copied whole?");let t=new ql(new Uint8Array(Buffer.from(n,"base64url"))),r=t.str(),[i,o,s,u,...c]=Array.from({length:20},()=>t.color()),a=[t.u8(),t.u8(),t.u8()].map((v)=>Wl[v]??`slot${v}`),f=t.str(),h=t.str(),l=t.str(),d=t.str(),g=t.u16(),m=t.str(),$=Ps.filter((v,k)=>g&1<<k),S=Array.from({length:t.u8()},()=>{let v=x[t.u8()]?.key??"unknown",k=t.u32(),M=t.u16(),p=t.u8(),A=t.u16();return{site:v,id:k,...M===1?{size:"fill"}:M>1?{size:M}:{},...p>0?{position:vt[p-1]??"unknown"}:{},...A>0?{opacity:(A-1)/1000}:{}}});if(t.end(),![i,o,s,u,...c].every(Zt))throw Error("the share code holds a color that is not one");return{name:r,...f?{base:f}:{},...h?{group:h}:{},...l?{ansiSource:l}:{},...d?{booru:d}:{},signature:a,background:i,foreground:o,cursor:s,selection:u,ansi:c,...$.length>0?{waive:$,reason:m}:{},...S.length>0?{pictures:S}:{}}}function Zl(e,n){let t=e.indexOf("ansi = ["),r=e.indexOf("]",t);if(t<0||r<0)throw Error("no ansi = [...] list to rewrite");let i=0,o=e.slice(t,r).replace(/"#[0-9a-fA-F]{6}"/g,()=>Ae(n.ansi[i++]));return(e.slice(0,t)+o+e.slice(r)).replace(/^(foreground\s*=\s*)"#[0-9a-fA-F]{6}"/m,(s,u)=>`${u}${Ae(n.foreground)}`).replace(/^(selection_background\s*=\s*)"#[0-9a-fA-F]{6}"/m,(s,u)=>`${u}${Ae(n.selectionBackground)}`)}function Ii(e){let n=Vt(fn(e)),t=new Set(e.waived??[]),r=Math.max(...pt.map((i)=>i.label.length));return pt.map((i,o)=>{let s=n[o],u=t.has(i.rule)||Number.isNaN(s)||(i.min===void 0||s>=i.min)&&(i.max===void 0||s<=i.max),c=i.min!==void 0?`≥ ${i.min}`:i.max!==void 0?`≤ ${i.max}`:"",a=Number.isNaN(s)?"—":Number.isInteger(s)?String(s):s.toFixed(2);return` ${u?"✓":"✗"} ${i.label.padEnd(r)} ${a.padStart(6)} ${c}${t.has(i.rule)?" waived":""}`})}var Vu="https://kecan0406.github.io/ttheme/manifest.json",e$=20000;function Gt(e){return zl(e,"ttheme","catalog.json")}function Ni(e,n){me(Gt(e),`${JSON.stringify(n,null,2)}
378
+ `)}function He(e){let n=mr(e),t=Gt(e),r=ai();if(n.includes(Ue)){if(!Xl(t))throw Error(`no catalog at ${t} — run \`ttheme init\` first`);r=ft(zu(t,"utf8"))}let i=n.filter(_o).flatMap((o)=>n$(e,o));return{...r,palettes:[...r.palettes,...i]}}function Qo(e,n){return Bu(zu(At(e,n),"utf8"))}function Oi(e,n){return Fn({owner:_l(e),name:n.name})}function n$(e,n){let t=At(e,n);if(!Xl(t))return[];try{let r=Qo(e,n);return t$(r,Oi(n,r))}catch(r){return process.stderr.write(`ttheme: skipping ${t} — ${r.message}
379
+ `),[]}}function Bu(e){let n=ft(e),t=Qu(n.owner,n.name);if(t)throw Error(`market index ${t}`);let r=n.palettes.find((i)=>Ge(i.name)!==void 0);if(r)throw Error(`market index names ${r.name} with its market — its entries are bare palette names`);return n}function t$(e,n){return e.palettes.map(({lead:t,default:r,native:i,...o})=>({...o,name:`${n}/${o.name}`,group:n}))}function ft(e){let n;try{n=JSON.parse(e)}catch{throw Error("catalog is not valid JSON")}let t=n;if(typeof t?.version!=="string"||!Array.isArray(t.palettes))throw Error("catalog has no version or palettes");for(let r of t.palettes){let i=Vl(r);if(i)throw Error(`catalog entry ${JSON.stringify(r?.name)} ${i}`)}return t}function Vl(e){if(typeof e?.name!=="string"||!Array.isArray(e.ansi)||e.ansi.length!==16)return"is missing name or its 16 ANSI colors";let n=On(e.name)??(e.base===void 0?void 0:On(e.base));if(n)return n;if(![e.background,e.foreground,e.cursor,e.selection,...e.ansi].every((t)=>typeof t==="string"&&Zt(t)))return'holds a color that is not "#rrggbb"';for(let t of[e.group,e.native??"-",e.ansiSource]){let r=typeof t==="string"?iu(t):"has a field that is not text";if(r)return r}return}function Bl(e){return zl(e,"ttheme","kept.json")}function Yo(e,n){me(Bl(e),`${JSON.stringify({palettes:n},null,2)}
380
+ `)}function Ri(e){try{let{palettes:n}=JSON.parse(zu(Bl(e),"utf8"));return Array.isArray(n)?n.filter((t)=>Vl(t)===void 0):[]}catch{return[]}}function je(e,n,t=!0){let r=[...n.palettes,...qo(e,n.palettes,t)],i=new Set(r.map((o)=>o.name));return{...n,palettes:[...r,...Ri(e).filter((o)=>!i.has(o.name))]}}function ht(e){return je(e,He(e))}class Zo extends Error{}class Xo extends Error{}async function Fi(e,n){let t;try{t=await fetch(e,{signal:AbortSignal.timeout(e$)})}catch(r){throw Error(`cannot reach ${e} — ${r instanceof Error?r.message:String(r)}`)}if(t.status===404)throw new Zo(`nothing at ${e}`);if(t.status===403||t.status===429)throw new Xo(`${new URL(e).host} is turning requests away for now (${t.status}) — try again in a minute`);if(!t.ok)throw Error(`${e} answered ${t.status}`);return n(await t.text())}function Du(e){let n=new Set(e.waived??[]),t=e.gate??Vt(fn(e));return pt.flatMap((r,i)=>{let o=t[i];if(n.has(r.rule)||typeof o!=="number"||Number.isNaN(o))return[];if(r.min!==void 0&&o<r.min)return[`${r.label} ${o} < ${r.min}`];if(r.max!==void 0&&o>r.max)return[`${r.label} ${o} > ${r.max}`];return[]})}function Ut(e,n){let t=e.find((r)=>r.name===n);if(!t)throw Error(`no palette named ${n} in the catalog — ${xu(e,[n])}`);return t}function xu(e,n){let t=n.map((s)=>s.toLowerCase()),r=e.filter((s)=>t.some((u)=>s.name.includes(u))),i=e.filter((s)=>!r.includes(s)&&t.some((u)=>s.group.toLowerCase().includes(u))),o=[...r,...i].map((s)=>s.name).slice(0,3);return o.length>0?`did you mean: ${o.join(", ")}?`:"`ttheme list` shows what is there"}function Dl(e,n){let t=n.toLowerCase();return e.filter((r)=>[r.name,r.group,r.native??"",r.ansiSource].some((i)=>i.toLowerCase().includes(t)))}function xl(e,n,t){let r=t.toLowerCase(),i=(o)=>o.name===n.name?0:o.group===n.group?1:2;return e.filter((o)=>o.booru?.toLowerCase().includes(r)).map((o,s)=>({p:o,at:s})).sort((o,s)=>i(o.p)-i(s.p)||o.at-s.at).map(({p:o})=>o)}function ed(e,n){return e.booruSites?.[n]??(e.booru?[e.booru]:[])}var nc=5,r$=6,nd=0.05,i$=[1,2,3,4,5,6,9,10,11,12,13,14],td=(e,n)=>(n-e+360)%360<=180?1:-1;function ec(e,n,t){let r=n*Math.cos(t*Math.PI/180),i=n*Math.sin(t*Math.PI/180),o=[e+0.3963377774*r+0.2158037573*i,e-0.1055613458*r-0.0638541728*i,e-0.0894841775*r-1.291485548*i].map((f)=>f**3),[s,u,c]=o,a=[4.0767416621*s-3.3077115913*u+0.2309699292*c,-1.2684380046*s+2.6097574011*u-0.3413193965*c,-0.0041960863*s-0.7034186147*u+1.707614701*c];if(a.some((f)=>f<-0.0001||f>1.0001))return;return a.map((f)=>{let h=Math.min(1,Math.max(0,f));return Math.round(255*(h<=0.0031308?12.92*h:1.055*h**0.4166666666666667-0.055))})}function zo(e,n,t){let r=0,i=n;if(ec(e,n,t)===void 0)for(let s=0;s<24;s++){let u=(r+i)/2;if(ec(e,u,t)===void 0)i=u;else r=u}else r=n;return`#${(ec(e,r,t)??[0,0,0]).map((s)=>s.toString(16).padStart(2,"0")).join("")}`}function o$(e,n){let{l:t,c:r}=mn(e);return zo(t,r,(n+360)%360)}function s$(e,n,t){let{l:r,c:i,h:o}=mn(e),s=Ze(n)<0.18,u=(f)=>zo(s?r+(1-r)*f:r*(1-f),i,o);if(De(u(1),n)<t+nd)return u(1);let c=0,a=1;for(let f=0;f<30;f++){let h=(c+a)/2;if(De(u(h),n)>=t+nd)a=h;else c=h}return u(a)}function u$(e,n){let{l:t,c:r,h:i}=mn(e),o=0,s=t;for(let u=0;u<30;u++){let c=(o+s)/2;if(Ze(zo(c,r,i))<=n-0.005)o=c;else s=c}return zo(o,r,i)}function c$(e,n,t){let r=Jr[n],[i,o]=[mn(e[n]),mn(e[n+8])],s=(f,h)=>t.has(f)?[h]:Array.from({length:2*r.width+1},(l,d)=>(r.center-r.width+d+360)%360),u=(f,h,l)=>Xt.every((d)=>{let g=(f>8?8:0)+d;if(g===f)return!0;let m=mn(e[g]);return m.c<Fs||Bn(m.h,h)>=no+1||Math.abs(m.l-l)>=to}),c,a=Number.POSITIVE_INFINITY;for(let f of s(n,i.h)){if(!t.has(n)&&!u(n,f,i.l))continue;for(let h of s(n+8,o.h)){if(Bn(f,h)>mt-nc||!t.has(n+8)&&!u(n+8,h,o.l))continue;let l=Bn(f,i.h)+Bn(h,o.h);if(l<a)a=l,c=[f,h]}}return c}class rd{theme;moves=[];constructor(e){this.theme={...e,ansi:[...e.ansi]}}set(e,n,t){let r=this.get(e);if(t===r)return;if(this.moves.push({slot:e,rule:n,from:r,to:t}),e==="foreground")this.theme.foreground=t;else if(e==="selection")this.theme.selectionBackground=t;else this.theme.ansi[Number(e.slice(4))]=t}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,n,t){this.set(`ansi${e}`,n,o$(this.theme.ansi[e],t))}roles(){let e=new Set(this.theme.signatureSlots);for(let{slot:t,hue:r}of Di(this.theme)){let i=Jr[zt(t)];this.rehue(t,"ansi-role",i.center+td(i.center,r)*(i.width-nc))}for(let{normal:t,gap:r}of xi(this.theme)){if(r<=mt)continue;let[i,o]=e.has(`ansi${t+8}`)?[t+8,t]:[t,t+8],s=mn(this.theme.ansi[i]).h,u=mn(this.theme.ansi[o]).h;this.rehue(o,"bright-follows",s+td(s,u)*(mt-nc))}let n=ro(this.theme);for(let[t,r]of eo(this.theme)){let i=zt(n.has(r)?t:r),o=c$(this.theme.ansi,i,n);if(o===void 0)continue;this.rehue(i,"distinct",o[0]),this.rehue(i+8,"distinct",o[1])}}readability(){let e=new Set(this.theme.waive),{background:n}=this.theme,t=(r,i,o,s=n)=>{if(e.has(r))return;for(let u of i)if(De(this.get(u),s)<o)this.set(u,r,s$(this.get(u),s,o))};if(t("foreground",["foreground"],7),t("accents",i$.map((r)=>`ansi${r}`),3),t("light-ansi",["ansi7","ansi15"],7),t("ansi8-visible",["ansi8"],1.6),!e.has("ansi0-dark")&&Ze(this.get("ansi0"))>0.15)this.set("ansi0","ansi0-dark",u$(this.get("ansi0"),0.15));t("selection",["selection"],7,this.theme.foreground)}net(){return[...new Set(this.moves.map((e)=>e.slot))].flatMap((e)=>{let n=this.moves.filter((i)=>i.slot===e),t=n[0].from,r=this.get(e);return t===r?[]:[{slot:e,rule:[...new Set(n.map((i)=>i.rule))].join(", "),from:t,to:r}]})}}function id(e){let n=new rd(e);for(let t=0;t<r$;t++)if(n.readability(),n.roles(),oo(n.theme).length===0)break;return{theme:n.theme,moves:n.net(),left:oo(n.theme)}}import{execFileSync as E$}from"node:child_process";import{existsSync as Hi,mkdirSync as es,readdirSync as wd,readFileSync as ts,rmSync as gd}from"node:fs";import{basename as bd,join as Sn}from"node:path";import{execFileSync as a$,spawn as f$}from"node:child_process";import{existsSync as yn,mkdirSync as h$,readFileSync as wr,realpathSync as l$,rmSync as tc,utimesSync as d$,writeFileSync as g$}from"node:fs";import{homedir as br}from"node:os";import{dirname as m$,join as Ie}from"node:path";var p$={ghostty:oi,kitty:ui,alacritty:ii,wezterm:$i,iterm2:si,"windows-terminal":ki,warp:bi},od="ttheme-default";function Yn(e=process.env.TTHEME_ITERM_SUITE??"com.googlecode.iterm2"){let n=(t,r)=>a$(t,r,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();return{read:()=>{try{return process.platform==="darwin"?n("defaults",["read",e,"Default Bookmark Guid"])||void 0:void 0}catch{return}},write:(t)=>{if(process.platform==="darwin")n("defaults",["write",e,"Default Bookmark Guid","-string",t])},running:()=>{try{return n("pgrep",["-x","iTerm2"])!==""}catch{return!1}}}}function En(e){return e.off?void 0:Xn(e)}function Pi(e,n){if(!e.terminals.includes("iterm2"))return e;let t=n.read();return t&&!t.startsWith("ttheme-")?{...e,itermBase:t}:e}function Jt(e,n){if(!e.terminals.includes("iterm2"))return!1;let t=n.read(),r=En(e)?od:t===od?e.itermBase:void 0;if(!r||r===t)return!1;return n.write(r),!0}function de(){return process.env.XDG_CONFIG_HOME??Ie(br(),".config")}function Ai(e){return Ie(e,"Library","Application Support","iTerm2","DynamicProfiles","ttheme.json")}function ge(e){let n=gr(e);if(!yn(n))throw Error(`nothing installed yet at ${n} — run \`ttheme init\` first`);let t=JSON.parse(wr(n,"utf8"));if(!Array.isArray(t?.palettes)||!Array.isArray(t.terminals))throw Error(`${n} has no palettes or terminals`);return{terminals:t.terminals.filter((r)=>No.includes(r)),...t.author?{author:t.author}:{},...t.startup?{startup:t.startup}:{},...t.off?{off:!0}:{},...t.itermBase?{itermBase:t.itermBase}:{},...t.wtHome?{wtHome:t.wtHome}:{},...t.wtProfile?{wtProfile:t.wtProfile}:{},...Array.isArray(t.markets)?{markets:t.markets.filter((r)=>typeof r==="string")}:{},palettes:t.palettes}}function Zn(e,n){me(gr(e),`${JSON.stringify(n,null,2)}
381
+ `)}function sd(e,n){let t=new Map(e.palettes.map((i)=>[i.name,i])),r=n.filter((i)=>!t.has(i));if(r.length>0){let i=[...new Set(r.flatMap((s)=>Ge(s)??[]))].filter((s)=>!e.palettes.some((u)=>Ge(u.name)===s)),o=i.length>0?`add ${i.join(", ")} first — \`ttheme market search\` finds a market's repository`:xu(hn(e.palettes),r);throw Error(`not in any market: ${r.join(", ")} — ${o}`)}return e.palettes.filter((i)=>n.includes(i.name))}function ud(e,n){let t=e==="wezterm"?"colors":"themes";return(p$[e].emit?.(n)??[]).flatMap((r)=>{let[,i,o]=r.path.split("/");return i===t&&o!==void 0?[{file:o,content:r.content}]:[]})}function Vo(e){return process.platform==="darwin"?Ie(e,".warp","themes"):Ie(process.env.XDG_DATA_HOME??Ie(e,".local","share"),"warp-terminal","themes")}function jt(e,n,t){if(e==="warp")return Vo(t);return Ie(n,e,e==="wezterm"?"colors":"themes")}function Bo(e,n){return process.platform==="darwin"?Ie(e,".warp","settings.toml"):Ie(n,"warp-terminal","settings.toml")}var rc='"dark"';function ic(e){return Ie(e,"ttheme","warp.base")}var w$="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 b$(e,n,t,r){let i=Bo(n,e);if(!yn(i))return;let o=ic(e),s=wr(i,"utf8"),u=Ro(s),c=u?.includes(`path = "${he("")}`)===!0,a;if(t){if(!c&&!yn(o))h$(m$(o),{recursive:!0}),g$(o,u??"");a=Bh(t)}else{if(!c)return;a=yn(o)&&wr(o,"utf8")||rc,tc(o,{force:!0})}let f=Fo(s,a);if(f===s)return;if(r)uu(i),f$(process.execPath,["-e",w$,l$(i),f,s],{detached:!0,stdio:"ignore"}).unref();else ci(i,f);return i}function cd(e){return Ie(e,"ttheme","kitty.py")}function $r(e,n){let t=Ie(n,".wezterm.lua");return yn(t)?t:Ie(e,"wezterm","wezterm.lua")}function Do(e){return Ie(e,"Microsoft","Windows Terminal","Fragments","ttheme","ttheme.json")}function oc(e){return[Ie(e,"Packages","Microsoft.WindowsTerminal_8wekyb3d8bbwe","LocalState","settings.json"),Ie(e,"Packages","Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe","LocalState","settings.json"),Ie(e,"Microsoft","Windows Terminal","settings.json")].filter((n)=>yn(n))}function $$(e){for(let n of e){let t=/"defaultProfile"\s*:\s*"(\{[0-9a-fA-F-]+\})"/.exec(wr(n,"utf8"))?.[1];if(t)return t}return}function Xn(e){return e.startup&&e.palettes.includes(e.startup)?e.startup:e.palettes[0]}function Ct(e,n){return e==="ghostty"?Ie(n,"ghostty","config"):Ie(n,"kitty","kitty.conf")}function ad(e,n,t,r){return e==="ghostty"?jh(Ie(n,"ttheme"),t,r):qh(t,cd(n),r)}function Pn(e){return yn(e)?wr(e,"utf8"):""}function _t(e){return Ie(e,"alacritty","alacritty.toml")}function k$(e,n){return n?Ie(e,"alacritty","themes",`${he(n)}.toml`):void 0}function fd(e,n,t,r){let i=Pe(e),o=n.map(fn),s=new Map;for(let c of o){let a=vh(i,c.name,r);if(a)s.set(c.name,a)}let u=new Set(hn(n).map((c)=>c.name));return oh(o.filter((c)=>u.has(c.name)),s,o.find((c)=>c.name===En(t)),t.itermBase)}function An(e,n=br()){let t=ge(e);if(!t.terminals.includes("iterm2"))return;me(Ai(n),fd(e,sd(ht(e),t.palettes),t,n))}function tn(e,n,t,r=br()){ze(Pe(e));let i=sd(je(e,n),t.palettes);Ah(e,new Map(i.map((l)=>[l.name,l.backdrop]))),Yo(e,i);let o=[],s=(l,d)=>{if(o.push(l),yn(l)&&wr(l,"utf8")===d)return!1;return me(l,d),!0},u=(l,d)=>{o.push(l),ci(l,d)},c=En(t),a=!1;for(let l of t.terminals){if(l==="iterm2"){s(Ai(r),fd(e,i,t,r));continue}if(l==="windows-terminal"){if(t.wtHome){let S=oc(t.wtHome),v=i.map(fn),k=Iu(v,t.wtProfile??$$(S),c);if(s(Do(t.wtHome),k)){let M=new Date;for(let p of S)d$(p,M,M);a=S.length>0}}continue}let d=c!==void 0&&l==="warp"&&!yn(Ie(Vo(r),`${he(c)}.yaml`)),g=l==="warp"?b$(e,r,c,d):void 0;for(let S of i)for(let{file:v,content:k}of ud(l,fn(S)))s(Ie(jt(l,e,r),v),k);if(l==="warp"){if(g)o.push(g);continue}if(l==="wezterm"){let S=Ie(e,"ttheme","wezterm.lua");s(S,el({path:S,colors:jt("wezterm",e,r),backgrounds:Pe(e),...c?{startup:c}:{},palettes:i.map(fn)}));let v=$r(e,r),k=wi(Pn(v),Yh(S));if(k!==void 0)u(v,k);continue}if(l==="alacritty"){let S=_t(e),v=pi(Pn(S),k$(e,c));if(v!==void 0)u(S,v);continue}if(l==="kitty")s(cd(e),sh({themes:jt("kitty",e,r),backgrounds:Pe(e)}));let m=Ct(l,e),$=Pn(m);u(m,gi($,ad(l,e,c,$)))}let f=Ie(e,"ttheme","palettes.zsh"),h=Mu(i,c,t.terminals);if(a||Pn(f)!==h)me(f,h),tc(`${f}.zwc`,{force:!0});return o.push(f),o}function hd(e,n){return e.startsWith(`${n}/`)?`~${e.slice(n.length)}`:e}function y$(e){return[...new Set(e.split(`
382
+ `).map((n)=>n.split(/[ =]/)[0]))].join(", ")}function ld(e,n,t=br()){let r=En(n),i=(s)=>hd(s,t),o=[];for(let s of n.terminals){if(s==="iterm2"){o.push(`write ${i(Ai(t))} — a "ttheme · <palette>" profile per palette`);continue}if(s==="windows-terminal"){if(n.wtHome)o.push(`write ${Do(n.wtHome)} — its schemes, and touch settings.json so it reloads`);continue}if(o.push(`write ${i(jt(s,e,t))}/${he("*")} — a theme file per palette`),s==="warp"){let a=Bo(t,e);if(r&&yn(a))o.push(`edit ${i(a)} — [appearance.themes] theme; \`ttheme off\` puts yours back`);continue}if(s==="wezterm"){let a=$r(e,t);if(wi(Pn(a),"")!==void 0)o.push(`edit ${i(a)} — a ttheme block before \`return config\`: color_scheme_dirs, color_scheme, pictures`);continue}if(s==="alacritty"){let a=_t(e);if(pi(Pn(a),void 0)!==void 0)o.push(`edit ${i(a)} — a ttheme block: general.import`);continue}let u=Ct(s,e),c=Pn(u);o.push(`edit ${i(u)} — a ttheme block: ${y$(ad(s,e,r,c))}`)}return o}function dd(e,n,t=br()){let r=[],i=(o)=>hd(o,t);if(n.includes("ghostty")){let o=Ct("ghostty",e);if(Rt(Pn(o),"command"))r.push(`${i(o)} sets its own command — ttheme leaves it, so a new tab takes its palette once zsh starts`)}if(n.includes("kitty")){let o=Pn(Ct("kitty",e));if(Rt(o,"window_logo_scale")||Rt(o,"window_logo_alpha"))r.push("kitty.conf sets its own window_logo_scale or window_logo_alpha — pictures are drawn with them")}if(n.includes("alacritty")){let o=_t(e);if(Qh(Pn(o)))r.push(`${i(o)} sets its own colors, which win over an imported palette — remove them to open with ttheme's`)}return r}function sc(e,n,t,r,i=br()){let o=[],s=je(e,n,!1).palettes;for(let u of t)for(let c of s.filter((a)=>r.includes(a.name)))for(let{file:a}of ud(u,fn(c))){let f=Ie(jt(u,e,i),a);if(yn(f))tc(f,{force:!0}),o.push(f)}return o}function lt(e,n,t,r){let i=Yn(),o=Boolean(En(t))!==Boolean(En(r)),s=o?Pi(r,i):r;return tn(e,n,s),Zn(e,s),o&&Jt(s,i)&&i.running()}var $d=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,S$=["add","remove","search","init"];function kd(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function M$(){try{let e=E$("gh",["api","user","--jq",".login"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4}).trim().toLowerCase();return $d.test(e)?e:void 0}catch{return}}async function v$(e,n){if(n.author)return n.author;let t=M$();if(!t){if(!kd())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 Ku({message:"your GitHub handle — your palettes are named <handle>@<market>/<palette>",validate:(i)=>$d.test((i??"").toLowerCase())&&(i??"").length<=39?void 0:"that is not a GitHub handle"});if(nn(r))throw Error("no handle given");t=r.toLowerCase()}return Zn(e,{...n,author:t}),console.log(`your palettes are named ${t}@<market>/<palette>`),t}function zn(e){return`${e} palette${e===1?"":"s"}`}function uc(e,n){if(n===Ue)return Ue;return qn(n)?Fn(Ht(n)):Oi(n,Qo(e,n))}function ns(e,n){try{return uc(e,n)}catch{return}}function yd(e){return Ge(e)??Ue}function rs(e){return He(e).palettes.filter((n)=>Ge(n.name)===void 0)}function I$(e){let n=Sn(import.meta.dirname,"..","dist","manifest.json");return Hi(n)?ft(ts(n,"utf8")).palettes:rs(e)}async function Ed(e){try{return await Fi(Jl(e),Bu)}catch(n){if(n instanceof Zo)throw Error(`github.com/${e} has no ${Wn} — is the repository public, and has its action run?`);throw n}}function xo(e,n,t){let r=ge(e),i=Kn(r.markets),o=i.find((s)=>s!==n&&ns(e,s)===t);if(o)throw Error(`${t} already names the market at ${kn(o)} — \`ttheme market remove ${t}\` first`);if(!i.includes(n))Zn(e,{...r,markets:[...i,n]});return i}async function N$(e){let n=de(),t=pr(e);if(Kn(ge(n).markets).includes(t)){console.log(`${kn(t)} is already added`);return}if(t===Ue){let o=await Fi(Vu,ft);xo(n,t,Ue),Ni(n,o),console.log(`added the ttheme catalog — ${zn(hn(o.palettes).length)} · \`ttheme browse\` picks them`);return}if(qn(t)){let o=Fn(Ht(t));xo(n,t,o);let s=vi(t,o,rs(n)).length;console.log(`added ${o} · ${kn(t)} — ${zn(s)}, read in place`),console.log("\n`ttheme browse` picks them · `ttheme market build` there writes the index others fetch");return}let r=await Ed(t),i=Oi(t,r);xo(n,t,i),es(Sn(n,"ttheme","markets"),{recursive:!0}),me(At(n,t),`${JSON.stringify(r,null,2)}
383
+ `),console.log(`added ${i} · ${kn(t)} — ${zn(r.palettes.length)}`),console.log(`
384
+ \`ttheme browse\` picks them, or \`ttheme add ${i}/<palette>\``)}function O$(e){let n=de(),t=ge(n),r=Kn(t.markets),i=r.find((c)=>ns(n,c)===e)??r.find((c)=>c===Sd(e));if(!i)throw Error(`no market named ${e} — \`ttheme market\` lists them`);let o=ns(n,i),s=t.palettes.filter((c)=>yd(c)===o),u={...t,markets:r.filter((c)=>c!==i)};if(Zn(n,u),i===Ue)gd(Gt(n),{force:!0});else if(_o(i))gd(At(n,i),{force:!0});if(tn(n,He(n),u),console.log(`removed ${o??e} · ${kn(i)}`),s.length>0)console.log(`${zn(s.length)} installed from it keep working — \`ttheme remove\` drops them`)}function Sd(e){try{return pr(e)}catch{return}}function R$(e,n){try{if(n===Ue)return hn(ft(ts(Gt(e),"utf8")).palettes).length;if(qn(n))return vi(n,uc(e,n),rs(e),!1).length;return Qo(e,n).palettes.length}catch{return}}function F$(){let e=de(),n=ge(e),t=Kn(n.markets);if(t.length===0){console.log("no markets — `ttheme market add official` brings the ttheme catalog back");return}let r=t.map((s)=>{let u=ns(e,s)??"?",c=R$(e,s),a=n.palettes.filter((f)=>yd(f)===u).length;return{name:u,where:kn(s),note:c===void 0?"unreadable":`${zn(c)}${a>0?` · ${a} installed`:""}`}}),i=Math.max(...r.map((s)=>s.name.length)),o=Math.max(...r.map((s)=>s.where.length));for(let s of r)console.log(` ${s.name.padEnd(i)} ${s.where.padEnd(o)} ${s.note}`)}async function P$(e){try{let{items:n}=await Fi(`https://api.github.com/search/repositories?q=${e}&sort=stars&per_page=50`,(t)=>JSON.parse(t));return n}catch(n){if(n instanceof Xo)throw Error("GitHub lets a search through about ten times a minute without signing in — try again in a minute");throw n}}async function A$(e){let n=de(),t=encodeURIComponent(`topic:${Jo}${e?` ${e}`:""}`),r=await P$(t);if(r.length===0){console.log(`no repository carries the ${Jo} topic${e?` and matches ${e}`:""} yet`);return}let i=new Set(Kn(ge(n).markets)),o=r.map((u)=>{let c=u.owner.login.toLowerCase();return{arg:`${c}/${u.name}`,added:i.has(`${c}/${u.name}`),stars:`★${u.stargazers_count}`,about:u.description??""}}),s=Math.max(...o.map((u)=>u.arg.length));for(let u of o)console.log(` ${u.added?"●":"○"} ${u.arg.padEnd(s)} ${u.stars.padStart(5)} ${u.about}`);console.log("\n`ttheme market add <name>` adds one")}var H$=`name: ttheme market
382
385
 
383
386
  on:
384
387
  push:
@@ -393,30 +396,30 @@ jobs:
393
396
  runs-on: ubuntu-latest
394
397
  steps:
395
398
  - uses: kecan0406/ttheme/market@v1
396
- `;function Ql({name:e}){return`ttheme-${e}`}function J$(e,n){Wo(Rt(e),{recursive:!0}),Wo(En(e,".github","workflows"),{recursive:!0}),Yl(e,n,[]),$e(En(e,".github","workflows","ttheme.yml"),j$),$e(En(e,"README.md"),`# ${Fn(n)}
399
+ `;function Md({name:e}){return`ttheme-${e}`}function L$(e,n){es(Tt(e),{recursive:!0}),es(Sn(e,".github","workflows"),{recursive:!0}),vd(e,n,[]),me(Sn(e,".github","workflows","ttheme.yml"),H$),me(Sn(e,"README.md"),`# ${Fn(n)}
397
400
 
398
401
  A [ttheme](https://github.com/kecan0406/ttheme) market:
399
402
 
400
403
  \`\`\`sh
401
- ttheme market add ${n.owner}/${Ql(n)}
404
+ ttheme market add ${n.owner}/${Md(n)}
402
405
  ttheme browse
403
406
  \`\`\`
404
- `)}function Yl(e,{owner:n,name:t},r){let{version:i,gate:o,placement:s}=Dr(),u={version:i,gate:o,placement:s,owner:n,name:t,palettes:r};$e(En(e,Jn),`${JSON.stringify(u,null,2)}
405
- `)}function Zl(e){return Nn(`x@${e}/x`)?"takes lowercase letters, digits and single hyphens":void 0}async function Xl(){if(!Wl())throw Error("name the market: ttheme market init <name>, or --in <name> on new");let e=await yu({message:"your market's name — its palettes are <you>@<name>/<palette>",validate:(n)=>Zl((n??"").toLowerCase())});if(en(e))throw Error("no market name given");return e.toLowerCase()}async function Vl(e,n){let t=Ot(e);if(n){let s=t.find((u)=>u.name===n||u.id===n||u.dir===ql(n));if(!s)throw Error(`${n} is not one of your local markets — \`ttheme market init ${n}\` makes it one`);return s}let[r,...i]=t;if(r&&i.length===0)return r;if(r)throw Error(`you have ${t.length} local markets — --in names one: ${t.map((s)=>s.name).join(", ")}`);let o=await Xl();return zl(e,Su(e,o),o)}async function zl(e,n,t){let r=!Si(En(n,Jn)),i;if(r){let s=Zl(t);if(s)throw Error(`the market name ${t} ${s}`);if(Si(n)&&jl(n).length>0)throw Error(`${n} is not empty — pick a new folder for the market`);i={owner:await F$(e,ke(e)),name:t},J$(n,i)}else i=Nt(n);let o=Fn(i);return Co(e,n,o),console.log(`${r?"made":"added"} your market ${o} · ${$n(n)}`),{dir:n,...i,id:o}}function Gl(e){return e.startsWith(".")||e.startsWith("/")||e.startsWith("~")}async function C$(e){let n=de(),t=e&&!Gl(e)?e.toLowerCase():e?Jl(sr(e)).toLowerCase():await Xl(),r=e&&Gl(e)?sr(e):Su(n,t),i=await zl(n,r,t),o=`${i.owner}/${Ql(i)}`;console.log(`
407
+ `)}function vd(e,{owner:n,name:t},r){let{version:i,gate:o,placement:s}=ai(),u={version:i,gate:o,placement:s,owner:n,name:t,palettes:r};me(Sn(e,Wn),`${JSON.stringify(u,null,2)}
408
+ `)}function Id(e){return On(`x@${e}/x`)?"takes lowercase letters, digits and single hyphens":void 0}async function Nd(){if(!kd())throw Error("name the market: ttheme market init <name>, or --in <name> on new");let e=await Ku({message:"your market's name — its palettes are <you>@<name>/<palette>",validate:(n)=>Id((n??"").toLowerCase())});if(nn(e))throw Error("no market name given");return e.toLowerCase()}async function Od(e,n){let t=Lt(e);if(n){let s=t.find((u)=>u.name===n||u.id===n||u.dir===Sd(n));if(!s)throw Error(`${n} is not one of your local markets — \`ttheme market init ${n}\` makes it one`);return s}let[r,...i]=t;if(r&&i.length===0)return r;if(r)throw Error(`you have ${t.length} local markets — --in names one: ${t.map((s)=>s.name).join(", ")}`);let o=await Nd();return Rd(e,qu(e,o),o)}async function Rd(e,n,t){let r=!Hi(Sn(n,Wn)),i;if(r){let s=Id(t);if(s)throw Error(`the market name ${t} ${s}`);if(Hi(n)&&wd(n).length>0)throw Error(`${n} is not empty — pick a new folder for the market`);i={owner:await v$(e,ge(e)),name:t},L$(n,i)}else i=Ht(n);let o=Fn(i);return xo(e,n,o),console.log(`${r?"made":"added"} your market ${o} · ${kn(n)}`),{dir:n,...i,id:o}}function md(e){return e.startsWith(".")||e.startsWith("/")||e.startsWith("~")}async function T$(e){let n=de(),t=e&&!md(e)?e.toLowerCase():e?bd(pr(e)).toLowerCase():await Nd(),r=e&&md(e)?pr(e):qu(n,t),i=await Rd(n,r,t),o=`${i.owner}/${Md(i)}`;console.log(`
406
409
  \`ttheme new <palette> --from <palette>\` puts palettes in it — others see them once it is on GitHub:
407
410
 
408
- cd ${$n(r)}
411
+ cd ${kn(r)}
409
412
  git init -b main && git add -A && git commit -m "${i.id}"
410
413
  gh repo create ${o} --public --source . --push
411
- gh repo edit ${o} --add-topic ${No}
414
+ gh repo edit ${o} --add-topic ${Jo}
412
415
 
413
- its action rebuilds ${Jn} on every push; then \`ttheme market add ${o}\` works anywhere`)}function W$(e){let n=e?sr(e):process.cwd(),t=Nt(n),r=Fn(t),i=P$(de()),o=Rt(n),s=(Si(o)?jl(o).sort():[]).filter((h)=>h.endsWith(".toml")),u=[],c=[];for(let h of s){let f=Jl(h,".toml");try{u.push({...Kn(`${r}/${f}`,_o(En(o,h),"utf8"),i),name:f})}catch(l){c.push(` ${En("palettes",h)}: ${l.message}`)}}if(c.length>0)return console.error(`${c.length} palettes cannot be read — the index was left as it was:
416
+ its action rebuilds ${Wn} on every push; then \`ttheme market add ${o}\` works anywhere`)}function G$(e){let n=e?pr(e):process.cwd(),t=Ht(n),r=Fn(t),i=I$(de()),o=Tt(n),s=(Hi(o)?wd(o).sort():[]).filter((f)=>f.endsWith(".toml")),u=[],c=[];for(let f of s){let h=bd(f,".toml");try{u.push({...Qn(`${r}/${h}`,ts(Sn(o,f),"utf8"),i),name:h})}catch(l){c.push(` ${Sn("palettes",f)}: ${l.message}`)}}if(c.length>0)return console.error(`${c.length} palettes cannot be read — the index was left as it was:
414
417
  ${c.join(`
415
- `)}`),1;let a=u.map(wn);for(let h of a){let l=pi(h).filter((d)=>d.startsWith(" ✗"));console.log(` ${h.name}${l.length>0?`
418
+ `)}`),1;let a=u.map($n);for(let f of a){let l=Ii(f).filter((d)=>d.startsWith(" ✗"));console.log(` ${f.name}${l.length>0?`
416
419
  ${l.join(`
417
- `)}`:" passes the gate"}`)}return Yl(n,t,a),console.log(`
418
- ${r} · ${Yn(a.length)} → ${En(n,Jn)}`),0}async function Bl(e,n){switch(e){case void 0:T$();return;case"add":await H$(Ul(e,n));return;case"remove":L$(Ul(e,n));return;case"search":await U$(n);return;case"init":await C$(n);return;case"build":return W$(n);default:throw Error(`unknown market action ${e} — ${O$.join(", ")}, or none to list them`)}}function Ul(e,n){if(!n)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 n}async function Dl(e,n){if(n===Ge){let r=Si(Ft(e))?an(ct(_o(Ft(e),"utf8")).palettes).length:0,i=await ki(Ru,ct);wi(e,i);let o=an(i.palettes).length;return`${Ge} ${i.version} — ${Yn(o)}${o>r?` (+${o-r})`:""}`}if(Wn(n)){let r=Cu(e,n);return`${r} — ${Yn(mi(n,r,qo(e),!1).length)}, read in place`}let t=await _l(n);return Wo(En(e,"ttheme","markets"),{recursive:!0}),$e(It(e,n),`${JSON.stringify(t,null,2)}
419
- `),`${$i(n,t)} — ${Yn(t.palettes.length)}`}import{existsSync as ed,mkdirSync as nd,readFileSync as td,writeFileSync as nb}from"node:fs";import{homedir as tb}from"node:os";import{dirname as rd,join as id}from"node:path";import{spawn as K$}from"node:child_process";var _$=30000,q$=3,Q$=97,Y$=`ObjC.import('Vision')
420
+ `)}`:" passes the gate"}`)}return vd(n,t,a),console.log(`
421
+ ${r} · ${zn(a.length)} → ${Sn(n,Wn)}`),0}async function Fd(e,n){switch(e){case void 0:F$();return;case"add":await N$(pd(e,n));return;case"remove":O$(pd(e,n));return;case"search":await A$(n);return;case"init":await T$(n);return;case"build":return G$(n);default:throw Error(`unknown market action ${e} — ${S$.join(", ")}, or none to list them`)}}function pd(e,n){if(!n)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 n}async function Pd(e,n){if(n===Ue){let r=Hi(Gt(e))?hn(ft(ts(Gt(e),"utf8")).palettes).length:0,i=await Fi(Vu,ft);Ni(e,i);let o=hn(i.palettes).length;return`${Ue} ${i.version} — ${zn(o)}${o>r?` (+${o-r})`:""}`}if(qn(n)){let r=uc(e,n);return`${r} — ${zn(vi(n,r,rs(e),!1).length)}, read in place`}let t=await Ed(n);return es(Sn(e,"ttheme","markets"),{recursive:!0}),me(At(e,n),`${JSON.stringify(t,null,2)}
422
+ `),`${Oi(n,t)} — ${zn(t.palettes.length)}`}import{existsSync as ac,mkdirSync as fc,readFileSync as yr,writeFileSync as V$}from"node:fs";import{homedir as B$}from"node:os";import{dirname as hc,join as Er}from"node:path";import{spawn as U$}from"node:child_process";var j$=30000,C$=3,J$=97,_$=`ObjC.import('Vision')
420
423
  ObjC.import('CoreImage')
421
424
  ObjC.import('CoreGraphics')
422
425
  function run(argv) {
@@ -435,36 +438,36 @@ function run(argv) {
435
438
  $.CIImage.imageWithCVPixelBuffer(buffer), $.NSURL.fileURLWithPath(argv[1]), $.kCIFormatRGBA8,
436
439
  $.CGColorSpaceCreateWithName($.kCGColorSpaceSRGB), $({}), error)
437
440
  if (!written) throw new Error('write failed')
438
- }`;function vi(){return process.platform==="darwin"}function Qo(e){return e>=q$&&e<=Q$}function Yo(e,n,t){return new Promise((r,i)=>{let o=K$("osascript",["-l","JavaScript","-e",Y$,e,n],{stdio:["ignore","ignore","pipe"],signal:AbortSignal.any([t,AbortSignal.timeout(_$)])}),s="";o.stderr.on("data",(u)=>{s+=u}),o.on("error",i),o.on("close",(u)=>{if(u===0){r();return}i(Error(s.trim().split(`
439
- `).at(-1)||`osascript exited ${u}`))})})}import{spawn as Z$}from"node:child_process";import{connect as X$,createServer as V$}from"node:net";var z$=20,xl=22;function Wu(e){let n=new Uint8Array(e.reduce((r,i)=>r+i.length,0)),t=0;for(let r of e)n.set(r,t),t+=r.length;return n}function B$(e,n=z$){let t=e.subarray(5);if(e[0]!==xl||t.length<2)return[e];let r=Math.max(1,Math.min(n,t.length-1)),i=(o)=>Wu([Uint8Array.from([e[0],e[1],e[2],o.length>>8,o.length&255]),o]);return[i(t.subarray(0,r)),i(t.subarray(r))]}function D$(e,n,t,r){let i=X$(t,n,()=>{i.setNoDelay(!0),e.write(`HTTP/1.1 200 Connection Established\r
441
+ }`;function kr(){return process.platform==="darwin"}function is(e){return e>=C$&&e<=J$}function Li(e,n,t){return new Promise((r,i)=>{let o=U$("osascript",["-l","JavaScript","-e",_$,e,n],{stdio:["ignore","ignore","pipe"],signal:AbortSignal.any([t,AbortSignal.timeout(j$)])}),s="";o.stderr.on("data",(u)=>{s+=u}),o.on("error",i),o.on("close",(u)=>{if(u===0){r();return}i(Error(s.trim().split(`
442
+ `).at(-1)||`osascript exited ${u}`))})})}import{spawn as W$}from"node:child_process";import{connect as K$,createServer as q$}from"node:net";var Q$=20,Ad=22;function cc(e){let n=new Uint8Array(e.reduce((r,i)=>r+i.length,0)),t=0;for(let r of e)n.set(r,t),t+=r.length;return n}function Y$(e,n=Q$){let t=e.subarray(5);if(e[0]!==Ad||t.length<2)return[e];let r=Math.max(1,Math.min(n,t.length-1)),i=(o)=>cc([Uint8Array.from([e[0],e[1],e[2],o.length>>8,o.length&255]),o]);return[i(t.subarray(0,r)),i(t.subarray(r))]}function Z$(e,n,t,r){let i=K$(t,n,()=>{i.setNoDelay(!0),e.write(`HTTP/1.1 200 Connection Established\r
440
443
  \r
441
- `);let o=r,s=!1,u=(c)=>{if(s){i.write(c);return}if(o=Wu([o,c]),o.length<5)return;let a=o[3]*256+o[4];if(o[0]!==xl){s=!0,i.write(o);return}if(o.length<5+a)return;s=!0;let[h,f]=B$(o.subarray(0,5+a));i.write(h),setTimeout(()=>{if(f)i.write(f);i.write(o.subarray(5+a))},10)};if(e.on("data",u),o.length>0){let c=o;o=new Uint8Array(0),u(c)}i.pipe(e)});i.on("error",()=>e.destroy()),i.on("close",()=>e.destroy()),e.on("error",()=>i.destroy()),e.on("close",()=>i.destroy())}function x$(e){e.setNoDelay(!0);let n=new Uint8Array(0),t=(r)=>{n=Wu([n,r]);let i=Buffer.from(n).toString("latin1"),o=i.indexOf(`\r
444
+ `);let o=r,s=!1,u=(c)=>{if(s){i.write(c);return}if(o=cc([o,c]),o.length<5)return;let a=o[3]*256+o[4];if(o[0]!==Ad){s=!0,i.write(o);return}if(o.length<5+a)return;s=!0;let[f,h]=Y$(o.subarray(0,5+a));i.write(f),setTimeout(()=>{if(h)i.write(h);i.write(o.subarray(5+a))},10)};if(e.on("data",u),o.length>0){let c=o;o=new Uint8Array(0),u(c)}i.pipe(e)});i.on("error",()=>e.destroy()),i.on("close",()=>e.destroy()),e.on("error",()=>i.destroy()),e.on("close",()=>i.destroy())}function X$(e){e.setNoDelay(!0);let n=new Uint8Array(0),t=(r)=>{n=cc([n,r]);let i=Buffer.from(n).toString("latin1"),o=i.indexOf(`\r
442
445
  \r
443
446
  `);if(o===-1)return;e.off("data",t);let s=/^CONNECT ([^ :]+):(\d+)/.exec(i);if(!s){e.end(`HTTP/1.1 405 Method Not Allowed\r
444
447
  \r
445
- `);return}D$(e,s[1],Number(s[2]),n.subarray(o+4))};e.on("data",t),e.on("error",()=>e.destroy())}function eb(){let e=V$(x$);return new Promise((n,t)=>{e.once("error",t),e.listen(0,"127.0.0.1",()=>{n({port:e.address().port,close:()=>{e.close(),e.unref()}})})})}function Mi(){if(process.versions.bun)return!0;let[e=0,n=0]=process.versions.node.split(".").map(Number);return e>22||e===22&&n>=21}async function Ii(){if(!Mi())return process.stderr.write(`unblock needs node 22.21 or newer — this is ${process.versions.node}
446
- `),1;let e=await eb(),n=Z$(process.execPath,process.argv.slice(1),{stdio:"inherit",env:{...process.env,NODE_USE_ENV_PROXY:"1",NODE_NO_WARNINGS:"1",HTTPS_PROXY:`http://127.0.0.1:${e.port}`,NO_PROXY:[process.env.NO_PROXY,uh()].filter(Boolean).join(","),TTHEME_FIND_PROXY:String(e.port)}}),t=await new Promise((r)=>n.on("exit",(i)=>r(i??1)));return e.close(),t}function Ni(){return process.env.TTHEME_FIND_UNBLOCK==="1"&&!process.env.TTHEME_FIND_PROXY}var rb=90000;function Ku(e,n){let t=Ze(e),r=Br(e,n).flatMap((i)=>{let[,o,s]=/^([a-z.]+)_(\d+)$/.exec(i.key)??[];return o&&s&&x.some((u)=>u.key===o)?[{site:o,id:Number(s),...Vh(t,i)}]:[]});return r.length>0?r:void 0}function ib(e,n){let t=new Set(On(Ze(e)).palettes[n.name]?.pictures.map((r)=>r.key));return(n.pictures??[]).filter((r)=>!t.has(yt(r)))}function Zo(e,n){let t=new Set((n??[]).map((r)=>yt(r)));return{...e,pictures:(e.pictures??[]).filter((r)=>!t.has(yt(r)))}}function ob(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 sb(e,n,t,r,i){let o=x.find((d)=>d.key===t.site);if(!o)throw Error(`no site called ${t.site}`);let s=await Cr(o,t.id,i);if(!s)throw Error("the post is gone");if(!oo(o,s,Xt(process.env.TTHEME_FIND_RATING))||io(s,Vt(process.env.TTHEME_FIND_BLOCK)).length>0)throw Error("outside your find filters — TTHEME_FIND_RATING and TTHEME_FIND_BLOCK");let u=bt(s);if(!u)throw Error("too large to use");let c=id(pn(o),"orig",`${t.id}.${u.ext}`),a;if(ed(c))a=new Uint8Array(td(c));else a=await uo(o,u.file,i),nd(rd(c),{recursive:!0}),nb(c,a);let h=Lr(a,vn);if(Dn(h)===0&&vi()&&process.env.TTHEME_FIND_REMOVE_BG!=="off"){let d=id(pn(o),"cut",`${t.id}.png`);try{if(!ed(d))nd(rd(d),{recursive:!0}),await Yo(c,d,i);let g=Lr(new Uint8Array(td(d)),vn);if(Qo(Dn(g)))h=g}catch{}}let f=ob(n);fo(e,f,er(f,n.signatureSlots),h,{site:o.key,id:t.id,ext:u.ext,bytes:a,from:`${o.name} ${t.id} ${o.pageUrl(t.id)}`},{width:0,height:0});let l=Br(e,n.name).find((d)=>d.key===yt(t));if(l)zh(Ze(e),l,t,r,tb())}async function ub(e,n,t,r){let i=0;for(let s of ib(e,n)){let u=`${n.name} · ${x.find((c)=>c.key===s.site)?.name??s.site} ${s.id}`;try{await sb(e,n,s,t,AbortSignal.timeout(rb)),r(` ▣ ${u}`),i++}catch(c){r(` ▢ ${u} — ${c instanceof Error?c.message:String(c)}`)}}let[o]=n.pictures??[];if(i>0&&o)Xh(e,n.name,yt(o));return i}async function Gt(e,n,t){let r=0;for(let i of n)r+=await ub(e,i,!t.includes("iterm2"),(o)=>console.log(o));if(r>0)at(e)}function mb(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function sd(e,n){if(e.includes("/"))return e;let t=Ot(n,!1),r=t.filter((o)=>fr(_u(Rt(o.dir),`${e}.toml`))),[i]=r.length===1?r:t.length===1?t:[];return i?`${i.id}/${e}`:e}function pb(e,n,t){let r=ke(e),i=t.filter((o)=>!r.palettes.includes(o));if(i.length>0)ht(e,n,r,{...r,palettes:[...r.palettes,...i]});else if(t.some((o)=>r.palettes.includes(o)))nn(e,n,r);return{state:r,fresh:i}}function wb(e){let n=Math.max(0,...e.map((t)=>t.slot.length));return e.map((t)=>` ${t.slot.padEnd(n)} ${t.from} → ${t.to} ${t.rule}`)}function ud(e,n,t){let r=dl(n),i=wn(Kn(r.name,Nu(r),t.palettes)),o=Ue(e,t,!1).palettes.find((s)=>s.name===i.name);if(o&&JSON.stringify(o)!==JSON.stringify(i))throw Error(`${i.name} is already in ${Te(i.name)??"the ttheme catalog"} and differs — \`ttheme add ${i.name}\` wears that one`);if(!o)Lo(e,[...bi(e),i]);return i.name}async function cd(e,n,t){let r=de(),i=He(r),o=ke(r),s=await Vl(r,t),u=e.includes("/")?e:`${s.id}/${e}`,c=Nn(u);if(c)throw Error(`${u} ${c}`);if(Te(u)!==s.id)throw Error(`palettes in ${s.dir} are named ${s.id}/<palette> — ${u} belongs elsewhere`);let a=Mu(r,u);if(fr(a))throw Error(`${u} already exists — \`ttheme edit ${u}\` changes it`);let h=Ue(r,i),f=n??Qn(o);if(!f)throw Error("--from names the palette to start from");let l=Pt(h.palettes,f),d=Te(l.name)?l.base:l.default?void 0:l.name,{base:g,ansiSource:p,group:k,...y}=Iu(l,u,`kept from ${l.name}`),M=Ku(r,l.name)??l.pictures,b=Nu({...y,...d?{base:d}:{},...M?{pictures:M}:{}});Kn(u,b,i.palettes),ab(od(a),{recursive:!0}),$e(a,b);let{state:S}=pb(r,i,[u]);console.log(` + ${u} from ${l.name}
447
- ${a}`),await Gt(r,Ue(r,i).palettes.filter((m)=>m.name===u),S.terminals),console.log(`
448
- \`ttheme edit ${u}\` changes its colors · \`ttheme use ${u}\` wears it`)}function $b(e){let n=process.env.VISUAL||process.env.EDITOR||"vi",t=cb("sh",["-c",`${n} "$1"`,"sh",e],{stdio:"inherit"});if(t.status!==0)throw Error(`${n} exited ${t.status??t.signal}`)}function bb(e,n,t){let r=wn(Kn(e,n,t.palettes));return Pu(r).length>0?pi(r).filter((i)=>i.startsWith(" ✗")):[]}async function ad(e){let n=de(),t=He(n),r=ke(n),i=Ue(n,t,!1),o=sd(e,n),s=Vo(n,o),u=s&&fr(s)?o:i.palettes.some((g)=>g.name===e)?e:o,c=Vo(n,u);if(!c||!fr(c)){let g=i.palettes.some((p)=>p.name===u);throw Error(g?`${u} is not one of yours — \`ttheme new <name> --from ${u}\` makes your own copy`:`no palette of yours called ${u} — \`ttheme new\` makes one`)}if(!mb())throw Error("edit opens your editor — run it in a terminal");let a=Xo(c,"utf8"),h=_u(hb(_u(db(),"ttheme-edit-")),gb(c));lb(h,a);let f=[];try{for(;;){$b(h);let g=Xo(h,"utf8");if(g===a){console.log("nothing changed");return}try{f=bb(u,g,t)}catch(p){console.log(`
449
- ${p.message}
450
- `);let k=await st({message:`${u} cannot be read like this — edit it again?`});if(en(k)||!k){console.log("kept the old one");return}continue}$e(c,g);break}}finally{fb(od(h),{recursive:!0,force:!0})}if(r.palettes.includes(u))nn(n,t,r);if(console.log(`saved ${u}${r.palettes.includes(u)?" — new tabs and `ttheme use` wear it":` — \`ttheme add ${u}\` installs it`}`),f.length>0)console.log(`
448
+ `);return}Z$(e,s[1],Number(s[2]),n.subarray(o+4))};e.on("data",t),e.on("error",()=>e.destroy())}function z$(){let e=q$(X$);return new Promise((n,t)=>{e.once("error",t),e.listen(0,"127.0.0.1",()=>{n({port:e.address().port,close:()=>{e.close(),e.unref()}})})})}function Ti(){if(process.versions.bun)return!0;let[e=0,n=0]=process.versions.node.split(".").map(Number);return e>22||e===22&&n>=21}async function Gi(){if(!Ti())return process.stderr.write(`unblock needs node 22.21 or newer — this is ${process.versions.node}
449
+ `),1;let e=await z$(),n=W$(process.execPath,process.argv.slice(1),{stdio:"inherit",env:{...process.env,NODE_USE_ENV_PROXY:"1",NODE_NO_WARNINGS:"1",HTTPS_PROXY:`http://127.0.0.1:${e.port}`,NO_PROXY:[process.env.NO_PROXY,Cf()].filter(Boolean).join(","),TTHEME_FIND_PROXY:String(e.port)}}),t=await new Promise((r)=>n.on("exit",(i)=>r(i??1)));return e.close(),t}function Ui(){return process.env.TTHEME_FIND_UNBLOCK==="1"&&!process.env.TTHEME_FIND_PROXY}var Ld=90000;function lc(e,n){let t=Pe(e),r=wu(e,n).flatMap((i)=>{let[,o,s]=/^([a-z.]+)_(\d+)$/.exec(i.key)??[];return o&&s&&x.some((u)=>u.key===o)?[{site:o,id:Number(s),...bu(t,i)}]:[]});return r.length>0?r:void 0}function D$(e,n){let t=new Set(ze(Pe(e)).palettes[n.name]?.pictures.map((r)=>r.key));return(n.pictures??[]).filter((r)=>!t.has(Ot(r)))}function os(e,n){let t=new Set((n??[]).map((r)=>Ot(r)));return{...e,pictures:(e.pictures??[]).filter((r)=>!t.has(Ot(r)))}}function x$(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 ek(e,n,t,r,i){let o=x.find((g)=>g.key===t.site);if(!o)throw Error(`no site called ${t.site}`);let s=await ei(o,t.id,i);if(!s)throw Error("the post is gone");if(!po(o,s,nr(process.env.TTHEME_FIND_RATING))||mo(s,tr(process.env.TTHEME_FIND_BLOCK)).length>0)throw Error("outside your find filters — TTHEME_FIND_RATING and TTHEME_FIND_BLOCK");let u=St(s);if(!u)throw Error("too large to use");let c=Er(bn(o),"orig",`${t.id}.${u.ext}`),a;if(ac(c))a=new Uint8Array(yr(c));else a=await wo(o,u.file,i),fc(hc(c),{recursive:!0}),V$(c,a);let f=$t(a,an),h=!1;if(jn(f)===0&&kr()&&process.env.TTHEME_FIND_REMOVE_BG!=="off"){let g=Er(bn(o),"cut",`${t.id}.png`);try{if(!ac(g))fc(hc(g),{recursive:!0}),await Li(c,g,i);let m=$t(new Uint8Array(yr(g)),an);if(is(jn(m)))f=m,h=!0}catch{}}let l=x$(n);Mo(e,l,cr(l,n.signatureSlots),f,{site:o.key,id:t.id,ext:u.ext,bytes:a,from:`${o.name} ${t.id} ${o.pageUrl(t.id)}`,cut:h},{width:0,height:0},fr(e));let d=wu(e,n.name).find((g)=>g.key===Ot(t));if(d)$u(Pe(e),d,t,r,B$())}async function nk(e,n,t,r){let i=0;for(let s of D$(e,n)){let u=`${n.name} · ${x.find((c)=>c.key===s.site)?.name??s.site} ${s.id}`;try{await ek(e,n,s,t,AbortSignal.timeout(Ld)),r(` ▣ ${u}`),i++}catch(c){r(` ▢ ${u} — ${c instanceof Error?c.message:String(c)}`)}}let[o]=n.pictures??[];if(i>0&&o)Rh(e,n.name,Ot(o));return i}async function Wt(e,n,t){let r=0;for(let i of n)r+=await nk(e,i,!t.includes("iterm2"),(o)=>console.log(o));if(r>0)An(e)}function Hd(e,n,t){if(n.width!==e.width||n.height!==e.height)return!1;for(let r=0;r<e.width*e.height;r++)e.data[r*4+3]=n.data[r*4+t]??0;return!0}async function tk(e,n){let[,t,r]=/^(.+)_(\d+)$/.exec(e)??[],i=Er(rr(),t??"local","cut",`${r??e}.png`);if(!ac(i)){if(!kr())return;fc(hc(i),{recursive:!0}),await Li(n,i,AbortSignal.timeout(Ld))}return $t(new Uint8Array(yr(i)),an)}function rk(e,n){try{return jn(bt(new Uint8Array(yr(Er(e,`${n.stem}.png`)))))>0}catch{return!1}}async function Td(e,n,t,r,i,o,s){let u=Pe(e),c=ze(u).palettes[n]?.pictures.find((h)=>h.key===t);if(!c?.original)return null;let a=Er(u,c.original),f=$t(new Uint8Array(yr(a)),an);if(c.cut){if(!Hd(f,bt(new Uint8Array(yr(Er(u,c.cut)))),0))return null;return vo(e,n,c,f,r,i,o,s,!1)}if(c.tone===void 0&&jn(f)===0&&rk(u,c)){let h=await tk(t,a);if(!h||!Hd(f,h,3))return null;return vo(e,n,c,f,r,i,o,s,!0)}return vo(e,n,c,f,r,i,o,s,!1)}function hk(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function Ud(e,n){if(e.includes("/"))return e;let t=Lt(n,!1),r=t.filter((o)=>Sr(dc(Tt(o.dir),`${e}.toml`))),[i]=r.length===1?r:t.length===1?t:[];return i?`${i.id}/${e}`:e}function lk(e,n,t){let r=ge(e),i=t.filter((o)=>!r.palettes.includes(o));if(i.length>0)lt(e,n,r,{...r,palettes:[...r.palettes,...i]});else if(t.some((o)=>r.palettes.includes(o)))tn(e,n,r);return{state:r,fresh:i}}function dk(e){let n=Math.max(0,...e.map((t)=>t.slot.length));return e.map((t)=>` ${t.slot.padEnd(n)} ${t.from} → ${t.to} ${t.rule}`)}function jd(e,n,t){let r=Yl(n),i=$n(Qn(r.name,Xu(r),t.palettes)),o=je(e,t,!1).palettes.find((s)=>s.name===i.name);if(o&&JSON.stringify(o)!==JSON.stringify(i))throw Error(`${i.name} is already in ${Ge(i.name)??"the ttheme catalog"} and differs — \`ttheme add ${i.name}\` wears that one`);if(!o)Yo(e,[...Ri(e),i]);return i.name}async function Cd(e,n,t){let r=de(),i=He(r),o=ge(r),s=await Od(r,t),u=e.includes("/")?e:`${s.id}/${e}`,c=On(u);if(c)throw Error(`${u} ${c}`);if(Ge(u)!==s.id)throw Error(`palettes in ${s.dir} are named ${s.id}/<palette> — ${u} belongs elsewhere`);let a=Yu(r,u);if(Sr(a))throw Error(`${u} already exists — \`ttheme edit ${u}\` changes it`);let f=je(r,i),h=n??Xn(o);if(!h)throw Error("--from names the palette to start from");let l=Ut(f.palettes,h),d=Ge(l.name)?l.base:l.default?void 0:l.name,{base:g,ansiSource:m,group:$,...S}=Zu(l,u,`kept from ${l.name}`),v=lc(r,l.name)??l.pictures,k=Xu({...S,...d?{base:d}:{},...v?{pictures:v}:{}});Qn(u,k,i.palettes),ok(Gd(a),{recursive:!0}),me(a,k);let{state:M}=lk(r,i,[u]);console.log(` + ${u} from ${l.name}
450
+ ${a}`),await Wt(r,je(r,i).palettes.filter((p)=>p.name===u),M.terminals),console.log(`
451
+ \`ttheme edit ${u}\` changes its colors · \`ttheme use ${u}\` wears it`)}function gk(e){let n=process.env.VISUAL||process.env.EDITOR||"vi",t=ik("sh",["-c",`${n} "$1"`,"sh",e],{stdio:"inherit"});if(t.status!==0)throw Error(`${n} exited ${t.status??t.signal}`)}function mk(e,n,t){let r=$n(Qn(e,n,t.palettes));return Du(r).length>0?Ii(r).filter((i)=>i.startsWith(" ✗")):[]}async function Jd(e){let n=de(),t=He(n),r=ge(n),i=je(n,t,!1),o=Ud(e,n),s=us(n,o),u=s&&Sr(s)?o:i.palettes.some((g)=>g.name===e)?e:o,c=us(n,u);if(!c||!Sr(c)){let g=i.palettes.some((m)=>m.name===u);throw Error(g?`${u} is not one of yours — \`ttheme new <name> --from ${u}\` makes your own copy`:`no palette of yours called ${u} — \`ttheme new\` makes one`)}if(!hk())throw Error("edit opens your editor — run it in a terminal");let a=ss(c,"utf8"),f=dc(sk(dc(ak(),"ttheme-edit-")),fk(c));ck(f,a);let h=[];try{for(;;){gk(f);let g=ss(f,"utf8");if(g===a){console.log("nothing changed");return}try{h=mk(u,g,t)}catch(m){console.log(`
452
+ ${m.message}
453
+ `);let $=await ct({message:`${u} cannot be read like this — edit it again?`});if(nn($)||!$){console.log("kept the old one");return}continue}me(c,g);break}}finally{uk(Gd(f),{recursive:!0,force:!0})}if(r.palettes.includes(u))tn(n,t,r);if(console.log(`saved ${u}${r.palettes.includes(u)?" — new tabs and `ttheme use` wear it":` — \`ttheme add ${u}\` installs it`}`),h.length>0)console.log(`
451
454
  it misses the contrast gate:
452
- ${f.join(`
455
+ ${h.join(`
453
456
  `)}
454
- \`ttheme check --fix ${u}\` suggests colors that pass`);let l=Ue(n,t).palettes.find((g)=>g.name===u),d=wn(Kn(u,a,t.palettes));if(l&&Br(n,u).length>0&&(l.background!==d.background||l.backdrop.color!==d.backdrop.color))console.log("its pictures keep the old tint — reinstall one from `ttheme preview` → tab to retint it");if(l&&r.palettes.includes(u))await Gt(n,[Zo(l,d.pictures)],r.terminals)}function hd(e,n,t){return Pt(e.palettes,e.palettes.some((r)=>r.name===n)?n:sd(n,t))}function fd(e,n=!1){let t=de(),r=He(t),i=ke(t),o=hd(Ue(t,r),e,t);if(console.log(`${o.name} · ${o.group}
455
- `),console.log(pi(o).join(`
456
- `)),Pu(o).length===0)return console.log(`
457
- passes the gate`),0;let{theme:u,moves:c,left:a}=Ml(cn(o));if(c.length===0)return console.log(`
457
+ \`ttheme check --fix ${u}\` suggests colors that pass`);let l=je(n,t).palettes.find((g)=>g.name===u),d=$n(Qn(u,a,t.palettes));if(l&&r.palettes.includes(u))await Wt(n,[os(l,d.pictures)],r.terminals)}function _d(e,n,t){return Ut(e.palettes,e.palettes.some((r)=>r.name===n)?n:Ud(n,t))}function Wd(e,n=!1){let t=de(),r=He(t),i=ge(t),o=_d(je(t,r),e,t);if(console.log(`${o.name} · ${o.group}
458
+ `),console.log(Ii(o).join(`
459
+ `)),Du(o).length===0)return console.log(`
460
+ passes the gate`),0;let{theme:u,moves:c,left:a}=id(fn(o));if(c.length===0)return console.log(`
458
461
  no color change fixes it — waive the rule in [contrast] with a reason, or pick other colors`),1;console.log(`
459
462
  ${a.length===0?"these colors pass":"these colors come closer"}:
460
- ${wb(c).join(`
461
- `)}`);let h=Vo(t,o.name);if(!h||!fr(h))return console.log(`
463
+ ${dk(c).join(`
464
+ `)}`);let f=us(t,o.name);if(!f||!Sr(f))return console.log(`
462
465
  \`ttheme new <name> --from ${o.name}\` makes a copy you can fix`),1;if(!n)return console.log(`
463
- \`ttheme check --fix ${o.name}\` writes them`),1;if($e(h,gl(Xo(h,"utf8"),u)),i.palettes.includes(o.name))nn(t,r,i);return console.log(`
464
- wrote ${h}`),a.length===0?0:1}function Vo(e,n){let t=Te(n);return t&&Ot(e,!1).some((r)=>r.id===t)?Mu(e,n):void 0}function kb(e,n){let t=Vo(e,n.name),r=t&&fr(t)?Kn(n.name,Xo(t,"utf8"),[n]).waiveReason:void 0,i=Ku(e,n.name)??n.pictures,{pictures:o,...s}=Iu(n,n.name,r);return{...s,...i?{pictures:i}:{}}}function ld(e){let n=de(),t=ll(kb(n,hd(Ue(n,He(n)),e,n)));if(console.log(t),process.stdout.isTTY)console.error(`
465
- anyone with ttheme wears it with: ttheme add ${ut}…`)}import{spawn as kk}from"node:child_process";import{createHash as ug}from"node:crypto";import{existsSync as dr,mkdirSync as Pi,mkdtempSync as Ek,readFileSync as cg,rmSync as tc,statSync as yk,writeFileSync as Hi}from"node:fs";import{tmpdir as Sk}from"node:os";import{dirname as os,join as Tn}from"node:path";import{pathToFileURL as vk}from"node:url";import{execFile as Eb}from"node:child_process";import{createHash as pd}from"node:crypto";import{existsSync as yb,mkdtempSync as Sb,readFileSync as xo,rmSync as vb,statSync as wd,writeFileSync as $d}from"node:fs";import{homedir as Mb,tmpdir as Ib}from"node:os";import{join as zo}from"node:path";import{fileURLToPath as Nb}from"node:url";import{promisify as Ob}from"node:util";var Hn=Ob(Eb),Bo=67108864,Rb=4096,Yu=["image/png","image/jpeg","image/webp","image/gif","image/tiff","image/heic"],Fb=["text/uri-list","text/plain;charset=utf-8","text/plain"],qu=[...Yu,"text/uri-list","text/plain"];function Pb(e){try{return wd(e).isFile()}catch{return!1}}function Hb(e){let n=[],t="",r="",i=!1;for(let o=0;o<e.length;o++){let s=e[o];if(r==="'")if(s==="'")r="";else t+=s;else if(r==='"')if(s==='"')r="";else if(s==="\\"&&'"\\$`'.includes(e[o+1]??""))t+=e[++o];else t+=s;else if(s==="\\"&&o+1<e.length)t+=e[++o],i=!0;else if(s==="'"||s==='"')r=s,i=!0;else if(/\s/.test(s)){if(i)n.push(t);t="",i=!1}else t+=s,i=!0}if(i)n.push(t);return n}function dd(e){if(/^file:\/\//i.test(e))try{return Nb(e)}catch{return}if(e.startsWith("~/"))return zo(Mb(),e.slice(2));return e.startsWith("/")?e:void 0}function es(e,n=Pb){let t=[];for(let r of e.replace(/\r\n?/g,`
466
+ \`ttheme check --fix ${o.name}\` writes them`),1;if(me(f,Zl(ss(f,"utf8"),u)),i.palettes.includes(o.name))tn(t,r,i);return console.log(`
467
+ wrote ${f}`),a.length===0?0:1}function us(e,n){let t=Ge(n);return t&&Lt(e,!1).some((r)=>r.id===t)?Yu(e,n):void 0}function pk(e,n){let t=us(e,n.name),r=t&&Sr(t)?Qn(n.name,ss(t,"utf8"),[n]).waiveReason:void 0,i=lc(e,n.name)??n.pictures,{pictures:o,...s}=Zu(n,n.name,r);return{...s,...i?{pictures:i}:{}}}function Kd(e){let n=de(),t=Ql(pk(n,_d(je(n,He(n)),e,n)));if(console.log(t),process.stdout.isTTY)console.error(`
468
+ anyone with ttheme wears it with: ttheme add ${at}…`)}import{spawn as p1}from"node:child_process";import{createHash as Ug}from"node:crypto";import{existsSync as vr,mkdirSync as _i,mkdtempSync as w1,readFileSync as jg,rmSync as Oc,statSync as b1,writeFileSync as Wi}from"node:fs";import{tmpdir as $1}from"node:os";import{dirname as ws,join as Gn}from"node:path";import{pathToFileURL as k1}from"node:url";import{execFile as wk}from"node:child_process";import{createHash as Zd}from"node:crypto";import{existsSync as bk,mkdtempSync as $k,readFileSync as hs,rmSync as kk,statSync as Xd,writeFileSync as zd}from"node:fs";import{homedir as yk,tmpdir as Ek}from"node:os";import{join as cs}from"node:path";import{fileURLToPath as Sk}from"node:url";import{promisify as Mk}from"node:util";var Hn=Mk(wk),as=67108864,vk=4096,pc=["image/png","image/jpeg","image/webp","image/gif","image/tiff","image/heic"],Ik=["text/uri-list","text/plain;charset=utf-8","text/plain"],gc=[...pc,"text/uri-list","text/plain"];function Nk(e){try{return Xd(e).isFile()}catch{return!1}}function Ok(e){let n=[],t="",r="",i=!1;for(let o=0;o<e.length;o++){let s=e[o];if(r==="'")if(s==="'")r="";else t+=s;else if(r==='"')if(s==='"')r="";else if(s==="\\"&&'"\\$`'.includes(e[o+1]??""))t+=e[++o];else t+=s;else if(s==="\\"&&o+1<e.length)t+=e[++o],i=!0;else if(s==="'"||s==='"')r=s,i=!0;else if(/\s/.test(s)){if(i)n.push(t);t="",i=!1}else t+=s,i=!0}if(i)n.push(t);return n}function qd(e){if(/^file:\/\//i.test(e))try{return Sk(e)}catch{return}if(e.startsWith("~/"))return cs(yk(),e.slice(2));return e.startsWith("/")?e:void 0}function ls(e,n=Nk){let t=[];for(let r of e.replace(/\r\n?/g,`
466
469
  `).split(`
467
- `)){let i=dd(r.trim());if(i&&n(i)){t.push(i);continue}for(let o of Hb(r)){if(/^https?:\/\/\S+$/i.test(o)){t.push(o);continue}let s=dd(o);if(s&&n(s))t.push(s)}}return t}function Lb(e){if(e[0]!==255||e[1]!==216)return null;let n=2;while(n+9<e.length){if(e[n]!==255){n++;continue}let t=e[n+1];if(t===255){n++;continue}let r=e[n+2]<<8|e[n+3];if(t>=192&&t<=207&&t!==196&&t!==200&&t!==204)return{height:e[n+5]<<8|e[n+6],width:e[n+7]<<8|e[n+8]};n+=2+r}return null}function gd(e){let n=Hr(e)?Ar(e):Lb(e);if(!n)return;return{ext:Hr(e)?"png":"jpg",width:n.width,height:n.height}}async function Do(e,n){let t=gd(e);if(t&&t.width*t.height<=vn)return{bytes:e,...t,source:n};if(process.platform!=="darwin")throw Error(t?`${t.width}×${t.height} is over ${vn/1e6} megapixels`:"only PNG and JPEG pictures work here");let r=Sb(zo(Ib(),"ttheme-attach-"));try{let i=zo(r,"in"),o=zo(r,"out.png");$d(i,e);let s=!t||t.width*t.height>vn?["--resampleHeightWidthMax",String(Rb)]:[];await Hn("sips",["-s","format","png",...s,i,"--out",o]).catch(()=>{throw Error("that is not a picture macOS can read")});let u=new Uint8Array(xo(o)),c=gd(u);if(!c)throw Error("that is not a picture macOS can read");return{bytes:u,...c,source:n}}finally{vb(r,{recursive:!0,force:!0})}}async function Zu(e,n){if(/^https?:\/\//i.test(e)){let t=await fetch(e,{headers:{"User-Agent":Js},signal:n});if(!t.ok)throw Error(`${new URL(e).host} answered ${t.status}`);if(Number(t.headers.get("content-length")??0)>Bo)throw Error("that picture is over 64 MB");let r=new Uint8Array(await t.arrayBuffer());if(/^text\/html/i.test(t.headers.get("content-type")??""))throw Error(`${new URL(e).host} sent a web page, not a picture — copy the image address instead`);return Do(r,e)}if(wd(e).size>Bo)throw Error("that picture is over 64 MB");return Do(new Uint8Array(xo(e)),e)}var bd=new Map,ns={key:"local",name:"local",origin:"file://",moved:!1,cutouts:"",best:"",tagBudget:0,vouched:!0,tunneled:!1,ansi:7,ratings:{safe:new Set,questionable:new Set,explicit:new Set},rate:()=>"",postsUrl:()=>"",countUrl:()=>"",postUrl:()=>"",pageUrl:(e)=>bd.get(e)??"",parse:()=>[],count:()=>0};function kd(e){if(/^https?:\/\//i.test(e))return"";return e.split("/").pop()??e}function Ed(e,n){bd.set(e,n)}function yd(e){return Number.parseInt(pd("sha1").update(e).digest("hex").slice(0,8),16)%Un}var Ab=`ObjC.import('AppKit')
470
+ `)){let i=qd(r.trim());if(i&&n(i)){t.push(i);continue}for(let o of Ok(r)){if(/^https?:\/\/\S+$/i.test(o)){t.push(o);continue}let s=qd(o);if(s&&n(s))t.push(s)}}return t}function Rk(e){if(e[0]!==255||e[1]!==216)return null;let n=2;while(n+9<e.length){if(e[n]!==255){n++;continue}let t=e[n+1];if(t===255){n++;continue}let r=e[n+2]<<8|e[n+3];if(t>=192&&t<=207&&t!==196&&t!==200&&t!==204)return{height:e[n+5]<<8|e[n+6],width:e[n+7]<<8|e[n+8]};n+=2+r}return null}function Qd(e){let n=er(e)?kt(e):Rk(e);if(!n)return;return{ext:er(e)?"png":"jpg",width:n.width,height:n.height}}async function fs(e,n){let t=Qd(e);if(t&&t.width*t.height<=an)return{bytes:e,...t,source:n};if(process.platform!=="darwin")throw Error(t?`${t.width}×${t.height} is over ${an/1e6} megapixels`:"only PNG and JPEG pictures work here");let r=$k(cs(Ek(),"ttheme-attach-"));try{let i=cs(r,"in"),o=cs(r,"out.png");zd(i,e);let s=!t||t.width*t.height>an?["--resampleHeightWidthMax",String(vk)]:[];await Hn("sips",["-s","format","png",...s,i,"--out",o]).catch(()=>{throw Error("that is not a picture macOS can read")});let u=new Uint8Array(hs(o)),c=Qd(u);if(!c)throw Error("that is not a picture macOS can read");return{bytes:u,...c,source:n}}finally{kk(r,{recursive:!0,force:!0})}}async function wc(e,n){if(/^https?:\/\//i.test(e)){let t=await fetch(e,{headers:{"User-Agent":eu},signal:n});if(!t.ok)throw Error(`${new URL(e).host} answered ${t.status}`);if(Number(t.headers.get("content-length")??0)>as)throw Error("that picture is over 64 MB");let r=new Uint8Array(await t.arrayBuffer());if(/^text\/html/i.test(t.headers.get("content-type")??""))throw Error(`${new URL(e).host} sent a web page, not a picture — copy the image address instead`);return fs(r,e)}if(Xd(e).size>as)throw Error("that picture is over 64 MB");return fs(new Uint8Array(hs(e)),e)}var Vd=new Map,ds={key:"local",name:"local",origin:"file://",moved:!1,cutouts:"",best:"",tagBudget:0,vouched:!0,tunneled:!1,ansi:7,ratings:{safe:new Set,questionable:new Set,explicit:new Set},rate:()=>"",postsUrl:()=>"",countUrl:()=>"",postUrl:()=>"",pageUrl:(e)=>Vd.get(e)??"",parse:()=>[],count:()=>0};function Bd(e){if(/^https?:\/\//i.test(e))return"";return e.split("/").pop()??e}function Dd(e,n){Vd.set(e,n)}function xd(e){return Number.parseInt(Zd("sha1").update(e).digest("hex").slice(0,8),16)%Cn}var Fk=`ObjC.import('AppKit')
468
471
  function run(argv) {
469
472
  const pb = $.NSPasteboard.generalPasteboard
470
473
  const files = pb.readObjectsForClassesOptions($([$.NSURL]), $({ NSPasteboardURLReadingFileURLsOnlyKey: true }))
@@ -489,16 +492,16 @@ function run(argv) {
489
492
  if (web && web.count > 0) return web.objectAtIndex(0).absoluteString.js
490
493
  const text = pb.stringForType('public.utf8-plain-text')
491
494
  return text && !text.isNil() ? text.js : ''
492
- }`,Tb=`Add-Type -AssemblyName System.Windows.Forms,System.Drawing
495
+ }`,Pk=`Add-Type -AssemblyName System.Windows.Forms,System.Drawing
493
496
  $c = [Windows.Forms.Clipboard]
494
497
  $f = $c::GetFileDropList(); if ($f.Count) { $f; exit }
495
498
  $p = Join-Path $env:TEMP 'ttheme-clipboard.png'
496
499
  $s = $c::GetData('PNG'); if ($s -is [IO.MemoryStream]) { [IO.File]::WriteAllBytes($p, $s.ToArray()); $p; exit }
497
500
  $i = $c::GetImage(); if ($i) { $i.Save($p, [Drawing.Imaging.ImageFormat]::Png); $p; exit }
498
- $c::GetText()`;function Sd(){if(process.platform!=="linux")return!1;try{return/microsoft/i.test(xo("/proc/version","utf8"))}catch{return!1}}async function Gb(e){let n=Boolean(process.env.WAYLAND_DISPLAY),t=n?["wl-paste",["--list-types"]]:["xclip",["-selection","clipboard","-t","TARGETS","-o"]],r=(await Hn(t[0],t[1])).stdout.split(`
499
- `).map((s)=>s.trim()),i=(s)=>n?Hn("wl-paste",["--no-newline","--type",s],{encoding:"buffer",maxBuffer:Bo}):Hn("xclip",["-selection","clipboard","-t",s,"-o"],{encoding:"buffer",maxBuffer:Bo});if(r.includes("text/uri-list"))return{text:(await i("text/uri-list")).stdout.toString("utf8")};let o=Yu.find((s)=>r.includes(s));if(o)return $d(e,(await i(o)).stdout),{image:e};return{text:r.some((s)=>s.startsWith("text/plain")||s==="UTF8_STRING")?(await i(r.includes("text/plain")?"text/plain":"UTF8_STRING")).stdout.toString("utf8"):""}}function Xu(){return Boolean(process.env.SSH_CONNECTION||process.env.SSH_TTY)}async function vd(e){if(process.platform==="darwin"){let n=(await Hn("osascript",["-l","JavaScript","-e",Ab,e])).stdout.trim();return n===e?{image:e}:{text:n}}if(Sd()){let n=(await Hn("powershell.exe",["-NoProfile","-STA","-Command",Tb])).stdout.replace(/\r/g,"").trim(),t=await Promise.all(n.split(`
501
+ $c::GetText()`;function eg(){if(process.platform!=="linux")return!1;try{return/microsoft/i.test(hs("/proc/version","utf8"))}catch{return!1}}async function Ak(e){let n=Boolean(process.env.WAYLAND_DISPLAY),t=n?["wl-paste",["--list-types"]]:["xclip",["-selection","clipboard","-t","TARGETS","-o"]],r=(await Hn(t[0],t[1])).stdout.split(`
502
+ `).map((s)=>s.trim()),i=(s)=>n?Hn("wl-paste",["--no-newline","--type",s],{encoding:"buffer",maxBuffer:as}):Hn("xclip",["-selection","clipboard","-t",s,"-o"],{encoding:"buffer",maxBuffer:as});if(r.includes("text/uri-list"))return{text:(await i("text/uri-list")).stdout.toString("utf8")};let o=pc.find((s)=>r.includes(s));if(o)return zd(e,(await i(o)).stdout),{image:e};return{text:r.some((s)=>s.startsWith("text/plain")||s==="UTF8_STRING")?(await i(r.includes("text/plain")?"text/plain":"UTF8_STRING")).stdout.toString("utf8"):""}}function bc(){return Boolean(process.env.SSH_CONNECTION||process.env.SSH_TTY)}async function ng(e){if(process.platform==="darwin"){let n=(await Hn("osascript",["-l","JavaScript","-e",Fk,e])).stdout.trim();return n===e?{image:e}:{text:n}}if(eg()){let n=(await Hn("powershell.exe",["-NoProfile","-STA","-Command",Pk])).stdout.replace(/\r/g,"").trim(),t=await Promise.all(n.split(`
500
503
  `).map(async(r)=>/^[A-Za-z]:\\/.test(r)?(await Hn("wslpath",["-u",r])).stdout.trim():r));return t.length===1&&/ttheme-clipboard\.png$/.test(t[0]??"")?{image:t[0]}:{text:t.join(`
501
- `)}}if(process.platform==="linux")return Gb(e);throw Error(`reading the clipboard is not supported on ${process.platform}`)}var Ub=`ObjC.import('AppKit')
504
+ `)}}if(process.platform==="linux")return Ak(e);throw Error(`reading the clipboard is not supported on ${process.platform}`)}var Hk=`ObjC.import('AppKit')
502
505
  function run() {
503
506
  const pb = $.NSPasteboard.generalPasteboard
504
507
  const files = pb.readObjectsForClassesOptions($([$.NSURL]), $({ NSPasteboardURLReadingFileURLsOnlyKey: true }))
@@ -510,31 +513,32 @@ function run() {
510
513
  picture = ['public.png', 'public.tiff', 'public.jpeg', 'public.heic'].some((t) => types.includes(t))
511
514
  }
512
515
  return pb.changeCount + '\\t' + (picture ? 'picture' : '')
513
- }`;async function Md(){if(Xu())return;if(process.platform==="darwin"){let[e="",n=""]=(await Hn("osascript",["-l","JavaScript","-e",Ub])).stdout.trim().split("\t");return{stamp:e,picture:n==="picture"}}if(process.platform==="linux"&&!Sd()){let n=Boolean(process.env.WAYLAND_DISPLAY)?(await Hn("wl-paste",["--list-types"])).stdout:(await Hn("xclip",["-selection","clipboard","-t","TARGETS","-o"])).stdout;return{stamp:n,picture:/^image\//m.test(n)}}return}function Id(e){let n=[],t="",r=0;while(r<e.length){if(e[r]!=="\x1B"){t+=e[r],r++;continue}if(e.startsWith("\x1B[200~",r)){let o=e.indexOf("\x1B[201~",r+6);if(o===-1)return{events:n,keys:t,pending:e.slice(r)};n.push({kind:"paste",text:e.slice(r+6,o)}),r=o+6;continue}if(e.startsWith("\x1B]5522;",r)||e.startsWith("\x1B]72;",r)){let o=[e.indexOf("\x1B\\",r),e.indexOf("\x07",r)].filter((f)=>f!==-1);if(o.length===0)return{events:n,keys:t,pending:e.slice(r)};let s=Math.min(...o),u=e.slice(r+2,s),[c="",a="",...h]=u.split(";");n.push({kind:"osc",code:c,meta:jb(a),payload:h.join(";")}),r=s+(e[s]==="\x07"?1:2);continue}let i=/^\[\?([\d;]*)(\$y|c)/.exec(e.slice(r+1,r+64));if(i){if(i[2]==="c")n.push({kind:"attributes"});else{let[o="0",s="0"]=(i[1]??"").split(";");n.push({kind:"mode",mode:Number(o),value:Number(s)})}r+=1+i[0].length;continue}if(/^(?:\[(?:\?[\d;$]*|2|20|200|201)?|\](?:5|55|552|5522|7|72)?)$/.test(e.slice(r+1)))return{events:n,keys:t,pending:e.slice(r)};t+=e[r],r++}return{events:n,keys:t,pending:""}}function jb(e){let n={};for(let t of e.split(":")){let r=t.indexOf("=");if(r>0)n[t.slice(0,r)]=t.slice(r+1)}return n}var Oi=(e)=>Buffer.from(e).toString("base64"),Qu=(e)=>Buffer.from(e,"base64");function md(e,n){return n.find((t)=>e.includes(t))}class Vu{clipboard=!1;drops=!1;reading;offered=[];dropping;pw=Oi(pd("sha1").update(`${process.pid}:${Date.now()}`).digest("hex"));send;deliver;constructor(e,n){this.send=e,this.deliver=n}start(){let e="\x1B[?2004h";if(this.clipboard)e+="\x1B[?5522h";if(this.drops)e+=`\x1B]72;t=a;${qu.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=${Oi("ttheme")}:pw=${this.pw};${Oi(".")}\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,n){if(e.type!=="read")return;let t=e.status??"";if(t==="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(t==="DATA"){if(r.mime=e.mime?Qu(e.mime).toString("utf8"):r.mime,n)r.chunks.push(Qu(n));return}if(this.reading=void 0,t!=="DONE"){this.deliver({kind:"error",message:t==="EPERM"?"the clipboard read was not allowed":`the terminal answered ${t}`});return}let i=Buffer.concat(r.chunks);if(r.listing){let o=i.toString("utf8").split(/\s+/).filter(Boolean),s=md(o,[...Yu,...Fb]);if(!s){this.deliver({kind:"text",text:""});return}let u=r.pw||this.pw,c=r.pw?"Paste event":"ttheme";this.reading={mime:s,chunks:[],pw:u,listing:!1},this.send(`\x1B]5522;type=read:name=${Oi(c)}:pw=${u};${Oi(s)}\x1B\\`);return}this.deliver(r.mime.startsWith("image/")?{kind:"bytes",bytes:new Uint8Array(i),source:"clipboard"}:{kind:"text",text:i.toString("utf8")})}drop(e,n){let t=e.t??"";if(t==="m"){if(e.x==="-1"){this.offered=[];return}if(n){this.offered=n.split(" ").filter(Boolean);let u=qu.filter((c)=>this.offered.includes(c));this.send(`\x1B]72;t=m:o=${u.length>0?1:0};${u.join(" ")}\x1B\\`)}return}if(t==="M"){let u=n?n.split(" ").filter(Boolean):this.offered,c=md(u,qu);if(!c){this.send("\x1B]72;t=r:o=0\x1B\\");return}this.dropping={mimes:u,index:u.indexOf(c)+1,chunks:[]},this.send(`\x1B]72;t=r:x=${this.dropping.index}\x1B\\`);return}let r=this.dropping;if(!r)return;if(t==="R"){this.dropping=void 0,this.send("\x1B]72;t=r:o=0\x1B\\"),this.deliver({kind:"error",message:`the drop failed: ${n.split(":")[0]||"unknown error"}`});return}if(t!=="r"&&t!=="")return;if(n)r.chunks.push(Qu(n));if(e.m==="1"||n)return;this.dropping=void 0;let i=Buffer.concat(r.chunks),o=r.mimes[r.index-1]??"",s;if(o.startsWith("image/"))s={kind:"bytes",bytes:new Uint8Array(i),source:"drop"};else{let u=i.toString("utf8"),c=o==="text/uri-list"?es(u).find((a)=>yb(a)):void 0;s=c?{kind:"bytes",bytes:new Uint8Array(xo(c)),source:c}:{kind:"text",text:u}}this.send("\x1B]72;t=r:o=1\x1B\\"),this.deliver(s)}}var ze={pitch:25,cols:22,rows:9,height:13},Ut={cols:25,rows:16},Jb=2147483648,Cb=-1073741826,Wb=1600,Kb="\x1B[0m",An="\x1B[1m",ge="\x1B[2m",Ri="\x1B[31m",Ln="\x1B[32m",tn="\x1B[33m",ts="\x1B[1;34m",_b="\x1B[35m",qb={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 Rd(e){let n=[],t=0;while(t<e.length){let r=e[t]??"";if(r==="\x1B"){let i=/^(?:\[([0-9;]*)([A-Za-z~])|O([A-Za-z]))/.exec(e.slice(t+1));if(i){n.push(qb[`${i[1]??""}${i[2]??i[3]??""}`]??"nop"),t+=1+i[0].length;continue}let o=e[t+1]??"";if(/^[a-z]$/.test(o)){n.push(`alt-${o}`),t+=2;continue}n.push("esc"),t++;continue}n.push(r==="\r"||r===`
514
- `?"enter":r==="\t"?"tab":r==="\x03"?"ctrl-c":r==="\x16"?"ctrl-v":r===""||r==="\b"?"backspace":r),t++}return n}var Fd="\x1B]1337;ReportCellSize\x07\x1B[16t",Nd="\x1B]1337;ReportCellSize=";function Du(e){let n=e.indexOf(Nd);if(n!==-1){let i=e.slice(n+Nd.length),o=[i.indexOf("\x07"),i.indexOf("\x1B\\")].filter((c)=>c!==-1),s=o.length>0?Math.min(...o):-1,u=s===-1?null:/^([\d.]+);([\d.]+);([\d.]+)$/.exec(i.slice(0,s));if(u){let c=Number(u[3]);return{cell:{h:Math.round(Number(u[1])*c),w:Math.round(Number(u[2])*c)},rest:e.slice(0,n)+i.slice(s+(i[s]==="\x07"?1:2))}}}let t=e.indexOf("\x1B[6;"),r=t===-1?null:/^\[6;(\d+);(\d+)t/.exec(e.slice(t+1));if(!r)return null;return{cell:{h:Number(r[1]),w:Number(r[2])},rest:e.slice(0,t)+e.slice(t+1+r[0].length)}}function lr(e,n){return{perRow:Math.max(1,Math.floor((e+1)/ze.pitch)),rowsVis:Math.max(1,Math.floor((n-4)/ze.height))}}function Pd(e){return`\x1B_Ga=t,t=f,f=100,i=${e.id},q=2;${Buffer.from(e.path).toString("base64")}\x1B\\`}function Hd(e){return`\x1B[${e.row+1};${e.col+1}H\x1B_Ga=p,i=${e.id},p=${e.id},c=${e.cols},r=${e.rows},C=1,z=${e.z},q=2\x1B\\`}function Ld(e){return`\x1B_Ga=d,d=I,i=${e},q=2\x1B\\`}function Ad(e){return`\x1B[38;2;${We(e).join(";")}m`}function zu(e){return`\x1B[48;2;${We(e).join(";")}m`}function fn(e){return Array.from(e).length}class rs{parts=[];cols;constructor(e){this.cols=e}put(e,n,t=""){return this.parts.push({col:e,text:n,sgr:t}),e+fn(n)}run(e,n){let t=e;for(let[r,i]of n)t=this.put(t,r,i);return t}right(e,n){this.run(e-n.reduce((t,[r])=>t+fn(r),0),n)}render(){let e="";for(let{col:n,text:t,sgr:r}of this.parts){if(n>=this.cols||n<0)continue;let i=Array.from(t).slice(0,this.cols-n).join("");e+=`\x1B[${n+1}G${r}${i}${r?Kb:""}`}return e}}function Td(e){return e>=1e6?`${(e/1e6).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1000))} KB`}function Qb(e,n){if(!n)return Td(e);return n>=1e6?`${(e/1e6).toFixed(1)}/${(n/1e6).toFixed(1)} MB`:`${Math.round(e/1000)}/${Math.round(n/1000)} KB`}function Gd(e){return e.replace(/_\([^)]*\)?$/,"")}function Ud(e){return[`${e.reduced?"↓":""}${e.width}×${e.height}`,Math.max(e.width,e.height)<Wb?tn:ge]}function Fi(e,n,t,r){let i=[...r.keys??[]],o=r.lead,s=r.right,u=()=>{let h=[...o?[fn(o[0])]:[],...i.map(([l,d])=>fn(l)+1+fn(d))];return(r.badge?fn(r.badge)+4:0)+h.reduce((l,d)=>l+d,0)+3*Math.max(0,h.length-1)+(s?3+fn(s[0])+1+fn(s[1]):0)};while(u()>n)if(i.length>2)i.splice(-2,1);else if(s)s=void 0;else if(i.length>1)i.splice(-2,1);else break;if(o&&u()>n){let h=Math.max(0,fn(o[0])-(u()-n)-1);o=[`${Array.from(o[0]).slice(0,h).join("")}…`,o[1]]}let c=0;if(r.badge)c=e.put(0,` ${r.badge} `,`\x1B[7;1m${t}`)+2;if([...o?[[o]]:[],...i.map(([h,f])=>[[h,An],[` ${f}`,ge]])].forEach((h,f)=>{c=e.run(c+(f?3:0),h)}),s)e.right(n,[[s[0],An],[` ${s[1]}`,ge]])}function Yb(e,n,t,r,i,o){let{ansi:s,selection:u,cursor:c}=o.colors,a=r<44?3:4;if(r>=56)a=Math.min(7,Math.floor((r+1)/8)-1);let h=t;for(let g=0;g<8;g++)h=(e[n]?.put(h,"▀".repeat(a),Ad(s[g]??c)+zu(s[g+8]??c))??h)+1;let f=["❯ ",Ln],l=[[["~/code/demo",ts],[" on ",ge],["main",_b],[" +2",Ln],[" ~1",tn]]];if(l.push([f,["git status -sb",""]]),r>=44)l.push([["## ",""],["main",Ln],["...",""],["origin/main",Ri],[" [ahead 1]",tn]]);if(l.push([[" M",Ri],[" src/main.rs",""]]),l.push([["??",Ri],[" notes.md",""]]),l.push([]),r>=44)l.push([f,["ls",""]]),l.push([["docs",ts],[" ",""],["src",ts],[" ",""],["tests",ts],[" Cargo.toml README.md",""]]),l.push([]);l.push([f,["cargo test",""]]),l.push([[" ✓",Ln],[" parses config",""]]);let d=[[" ✗",Ri],[" renders frame",""]];if(r>=44)d.push([" expected ",ge],["3",Ln],[", received ",ge],["2",Ri]);l.push(d),l.push([]),l.push([f,["echo ",""],["selected text",zu(u)],[" ",""],[" ",zu(c)]]),l.forEach((g,p)=>{let k=n+2+p;if(k<=i)e[k]?.run(t,g)})}function Zb(e,n,t,r,i,o){e[n]?.put(t,`╭${"─".repeat(i-2)}╮`,o);for(let s=n+1;s<n+r-1;s++)e[s]?.put(t,"│",o),e[s]?.put(t+i-1,"│",o);e[n+r-1]?.put(t,`╰${"─".repeat(i-2)}╯`,o)}function Bu(e,n=e.site,t=e.siteAnsi){return[` ${n} `,`\x1B[7;${30+t}m`]}function Xb(e){return`${x[Math.floor(e/Un)]?.name??"local"} ${e%Un}`}function Vb(e,n,t){let r=[{name:"all",moved:!1},...x].flatMap((s,u)=>{let c=`${s.name}${s.moved?"*":""}`,a=s.name===t.site?Bu(t,c):[` ${c} `,ge];return u?[[" ",""],a]:[a]}),i=r.reduce((s,[u])=>s+fn(u),0)<=n,o=e.run(0,i?r:[Bu(t)]);if(t.asking!==void 0)e.run(o,[[` ${t.asking} was cut off — this network may block it. turn on the unblock proxy? `,tn],["y",An],[" turn on ",ge],["n",An],[" not now",ge]])}function zb(e,n,t,r){if(t.editing!==void 0){let u=e.run(0,[["⌕ ",r],[t.editing,""],["█",r]]),c=t.suggest?.length?" ↑↓ pick enter searches":" enter searches";e.put(u,t.editing?c:` a tag, a post url or an id, or drop a picture or ctrl+v — ${t.tag||"esc leaves"}`,ge);return}let i=e.run(0,[["⌕ ",r],[t.tag||"nothing yet — / searches, ctrl+v pastes a picture",t.tag?"":ge]]),o=$t.filter((u)=>!t.block.includes(u)),s=[t.preset,...t.solo?["solo"]:[],t.order,...t.rating.join("+")==="safe"?[]:[t.rating.join("+")],...o.length>0?[`allows ${o.join("+")}`]:[],...t.unblocked?["unblock"]:[]];if(e.put(i,` ${s.join(" ")}`,ge),t.total>0||!t.searching){let u=[[`${t.tiles.length}/${t.checked}`,""]];if(t.checked<t.total)u.push([` of ${t.total}`,ge]);e.right(n,u)}}function Bb(e){if(e.cut==="on")return[[`cut out · ${e.clear}% transparent`,Ln]];if(e.cut==="off")return[["opaque · x cuts out",tn]];if(e.cut==="failed")return[["opaque · no cut-out",tn]];return[e.clear>0?[`${e.clear}% transparent`,Ln]:["opaque",tn]]}function Od(e){return e.site==="all"?"any site":e.site}function jd(e){if(e.installing!==void 0)return[`installing ${e.palette} ← ${Xb(e.installing)}`,tn];if(e.hint)return[e.hint,Ln];if(e.error)return[e.error,tn];if(e.waiting!==void 0)return[`${e.slow??e.site} asked to slow down · ${e.waiting}s`,tn];if(e.fetching)return[`fetching ${e.fetching.id%Un} · ${Qb(e.fetching.got,e.fetching.size)}`,tn];if(e.cutting!==void 0)return[`cutting out ${e.cutting%Un}`,tn];if(e.preparing!==void 0)return[`preparing ${e.preparing%Un}`,tn];if(e.saved)return[e.saved,Ln];if(e.note)return[e.note,ge];return}function Db(e,n,t,r,i,o){let{perRow:s,rowsVis:u}=lr(t,r);zb(e[0],t,i,o),Vb(e[1],t,i);for(let d=0;d<s*u;d++){let g=i.top*s+d,p=i.tiles[g];if(!p)break;let k=2+Math.floor(d/s)*ze.height,y=d%s*ze.pitch,M=g===i.focus;if(M)Zb(e,k,y,ze.height,ze.pitch-1,o);if(p.thumb)n.push({id:p.key,path:p.thumb,row:k+1,col:y+1,cols:ze.cols,rows:ze.rows,z:-1});if(e[k+10]?.run(y+1,[...i.installed.includes(p.key)?[["✓ ",Ln]]:[],...i.site==="all"?[["● ",`\x1B[${30+p.siteAnsi}m`]]:[],[String(p.id),M?An:""],[" ",""],Ud(p)]),p.mates.length>0)e[k+10]?.put(y+ze.cols,"≈",o);let b=p.artist?Gd(p.artist):p.owner&&`@${p.owner}`;if(b)e[k+11]?.put(y+1,b.slice(0,ze.cols-8),ge);let S=[];if(p.score>0)S.push([`★${p.score}`,ge]);if(p.variants>1)S.push([` ×${p.variants}`,o]);if(S.length>0)e[k+11]?.right(y+ze.cols+1,S)}let c=i.top*s,a=i.tiles.length-(i.top+u)*s,h=[...c>0?[`↑ ${c} above`]:[],...a>0?[`↓ ${a} more`]:[]];if(h.length>0)e[r-2]?.put(0,h.join(" "),ge);if(!i.searching&&i.tiles.length===0&&!i.error)e[3]?.put(0,i.preset==="cutouts"?`no transparent cutouts of ${i.tag} on ${Od(i)} — c searches every post, tab tries ${i.nextSite}`:`no posts of ${i.tag} on ${Od(i)} — tab tries ${i.nextSite}`,ge);let f=e[r-1],l=jd(i);if(i.searching&&i.tiles.length===0&&!l){Fi(f,t,o,{badge:"FIND",lead:[i.preset==="cutouts"?"checking png headers":"fetching posts",ge],right:["esc","back"]});return}Fi(f,t,o,{badge:"FIND",lead:l,keys:i.asking!==void 0?[]:[["←↑↓→","move"],["enter","try on"],["tab","site"],["ctrl+v","picture"],["s","settings"],["/","search"],["?","keys"]],right:i.asking!==void 0?void 0:["esc","back"]})}function xb(e,n,t,r,i,o){let s=i.tiles[i.focus];if(!s)return;let u=i.shown?.id===s.key?i.shown:void 0,c=[Bu(i,s.site,s.siteAnsi),[" ",""],[String(s.id),An],[" ",""],Ud(s)];if(s.artist)c.push([` · ${Gd(s.artist)}`,""]);if(s.score>0)c.push([` · ★${s.score}`,ge]);if(u)c.push([` · ${Td(u.bytes)}`,ge]);if(s.owner)c.push([` · ${s.owner}`,ge]);if(s.origin)c.push([` · ${s.origin}`,ge]);if(u)c.push([" ",""],...Bb(u));if(e[0]?.run(0,c),s.mates.length>0)e[0]?.right(t,[["≈ ",o],[s.mates.join(" "),ge]]);if(Yb(e,3,2,t-4,r-2,i),i.shown)n.push({id:Jb+i.shown.id,path:i.shown.path,row:0,col:0,cols:t,rows:r,z:Cb});let a=jd(i);Fi(e[r-1],t,o,{badge:"TRY",lead:a,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 ek={grid:[["move","←↑↓→ home end pgup pgdn"],["try on","enter"],["site",`tab all, ${x.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"],["back","esc returns to preview"],["close","? esc"]],try:[["browse","←→"],["install","enter"],["cut out","x the background off or on, on an opaque picture"],["open","o the post page in a browser"],["your own","ctrl+v or v a picture from the clipboard · drop one on the window"],["grid","esc"],["close","? esc"]]};function nk(e,n,t,r,i){let o=r.panel??0,s=Math.max(...r.settings.map((l)=>l.label.length)),u=Math.max(...r.settings.map((l)=>l.choices.reduce((d,g)=>d+g.length+(l.multi?6:3),0))),c=Math.min(n-2,Math.max(28,s+u+8)),a=r.settings.length+4,h=Math.floor((n-c)/2),f=Math.max(2,Math.floor((t-a)/2));e[f]?.put(h,`╭─ settings ${"─".repeat(Math.max(0,c-13))}╮`);for(let l=f+1;l<f+a-1;l++)e[l]?.put(h,`│${" ".repeat(c-2)}│`);r.settings.forEach((l,d)=>{let g=e[f+2+d];g.put(h+3,l.label,d===o?An:ge);let p=h+5+s,k=l.value.split(" ");l.choices.forEach((y,M)=>{let b=k.includes(y),S=l.multi&&d===o&&M===l.cursor?"4;":"",m=l.multi?` ${b?"[x]":"[ ]"} ${y} `:` ${y} `;p=g.put(p,m,b?`\x1B[${S}7;${30+r.siteAnsi}m`:S?`\x1B[4m${ge}`:ge)+1})}),e[f+a-1]?.put(h,`╰${"─".repeat(c-2)}╯`),Fi(e[t-1],n,i,{badge:"SET",keys:[["↑↓","setting"],["←→","value"],["space","toggle"],["enter","save"]],right:["esc","undo"]})}function tk(e,n,t,r,i){let o=ek[r.mode],s=Math.min(n-2,50),u=o.length+4,c=Math.floor((n-s)/2),a=Math.max(2,Math.floor((t-u)/2));e[a]?.put(c,`╭─ keys ${"─".repeat(s-9)}╮`);for(let h=a+1;h<a+u-1;h++)e[h]?.put(c,`│${" ".repeat(s-2)}│`);o.forEach(([h,f],l)=>{e[a+2+l]?.put(c+3,h,An),e[a+2+l]?.put(c+13,f.slice(0,s-16))}),e[a+u-1]?.put(c,`╰${"─".repeat(s-2)}╯`),Fi(e[t-1],n,i,{badge:"KEYS",right:["? esc","close"]})}function rk(e,n,t){let r=n.suggest??[],i=r.map((u)=>u.count>0?String(u.count):u.palette??"0"),o=Math.max(...r.map((u)=>fn(u.value))),s=Math.max(7,...i.map(fn));r.forEach((u,c)=>{let a=c===n.pick,h=e[1+c];h?.run(0,[[a?"▸ ":" ",t],[u.value,a?An+t:""]]),h?.right(2+o+2+s,[[i[c],ge]])})}function Jd(e,n,t){let r=Array.from({length:t},()=>new rs(n)),i=[],o=Ad(e.colors.cursor);if(n<Ut.cols||t<Ut.rows)return r[0]?.put(0,"ttheme find",An+o),r[1]?.put(0,`needs ${Ut.cols}×${Ut.rows} — now ${n}×${t}`),r[2]?.put(0,"esc quits",ge),{lines:r.map((s)=>s.render()),images:i};if(e.mode==="try")xb(r,i,n,t,e,o);else Db(r,i,n,t,e,o);if(e.mode==="grid"&&e.editing!==void 0&&e.suggest?.length){for(let s=1;s<t-1;s++)r[s]=new rs(n);return rk(r,e,o),{lines:r.map((s)=>s.render()),images:[]}}if(e.help||e.panel!==void 0){let s=e.mode==="try"?i:[];for(let u=0;u<t;u++)r[u]=new rs(n);if(e.help)tk(r,n,t,e,o);else nk(r,n,t,e,o);return{lines:r.map((u)=>u.render()),images:s}}return{lines:r.map((s)=>s.render()),images:i}}var ik=new Set(["comic","4koma","monochrome","greyscale","sketch","lineart","speech_bubble"]),ok=new Set(["scenery","landscape","scenic","no_humans","wide_shot","very_wide_shot"]),sk=0.04,uk=0.1,ck=0.05,ak=4096;function hk(e){return new Set(e.cutouts.split(/\s+/).map((n)=>n.replace(/^~/,"")).filter(Boolean))}function fk(e,n,t,r=0){let{site:i,post:o}=e,s=new Set(o.tags),u=[...hk(i)].some((h)=>s.has(h)),c=Math.min(o.width,o.height),a=o.width>0&&o.height>0?o.width/o.height/(n.w/n.h):1;return(o.solo?2:0)+([...ik].some((h)=>s.has(h))?-3:0)+([...ok].some((h)=>s.has(h))?-1.5:0)+2*Math.min(1,c/n.h)+(u?1.5:-Math.min(1.5,Math.abs(Math.log(a))))+(t>0?1.5*Math.log1p(Math.max(0,o.score))/Math.log1p(t):0)+2*r}function is(e,n,t=new Map){let r=new Map;for(let{site:i,post:o}of e)r.set(i,Math.max(r.get(i)??0,o.score));return e.map((i,o)=>({pick:i,at:o,score:fk(i,n,r.get(i.site)??0,t.get(i.post))})).sort((i,o)=>o.score-i.score||i.at-o.at).map(({pick:i})=>i)}function Wd(e){let n=new Map;for(let r of e)n.set(r.site,[...n.get(r.site)??[],r]);let t=[];for(let r=0;t.length<e.length;r++)for(let i of n.values()){let o=i[r];if(o)t.push(o)}return t}function xu(e){let n=e/255;return n<=0.04045?n/12.92:((n+0.055)/1.055)**2.4}function Cd(e,n,t){let[r,i,o]=[xu(e),xu(n),xu(t)],s=Math.cbrt(0.4122214708*r+0.5363325363*i+0.0514459929*o),u=Math.cbrt(0.2119034982*r+0.6806995451*i+0.1073969566*o),c=Math.cbrt(0.0883024619*r+0.2817188376*i+0.6299787005*o);return[0.2104542553*s+0.793617785*u-0.0040720468*c,1.9779984951*s-2.428592205*u+0.4505937099*c,0.0259040371*s+0.7827717662*u-0.808675766*c]}function Kd(e,n){let t=n.map((s)=>Cd(...We(s))).filter(([,s,u])=>Math.hypot(s,u)>=sk);if(t.length===0)return 0;let r=Math.max(1,Math.floor(Math.sqrt(e.width*e.height/ak))),i=t.map(()=>0),o=0;for(let s=0;s<e.height;s+=r)for(let u=0;u<e.width;u+=r){let c=(s*e.width+u)*4;if(e.data[c+3]<128)continue;o++;let[a,h,f]=Cd(e.data[c],e.data[c+1],e.data[c+2]);t.forEach(([l,d,g],p)=>{if(Math.hypot(a-l,h-d,f-g)<uk)i[p]=i[p]+1})}if(o===0)return 0;return i.reduce((s,u)=>s+Math.min(1,u/o/ck),0)/t.length}import{mkdirSync as Zd,readFileSync as Xd,writeFileSync as Vd}from"node:fs";import{dirname as zd}from"node:path";import{isMainThread as mk,parentPort as Bd,Worker as pk}from"node:worker_threads";var lk=/(?:^|[^0-9a-f])([0-9a-f]{32})(?:[^0-9a-f]|$)/i,dk=[[/yande\.re\/post\/show\/(\d+)/,"yande"],[/konachan\.(?:com|net)\/post\/show\/(\d+)/,"konachan"],[/danbooru\.donmai\.us\/(?:posts|post\/show)\/(\d+)/,"danbooru"]];function ec(e){let n=/(\d+)_p(\d+)/.exec(e.source);return[...e.md5?[`md5:${e.md5}`]:[],...n&&e.source.includes("pximg")?[`pixiv:${n[1]}_p${n[2]}`]:[]]}function _d(e,n){let t=lk.exec(n.source)?.[1]?.toLowerCase();return[`post:${e.key}:${n.id}`,...n.md5?[`md5:${n.md5}`]:[],...t&&t!==n.md5?[`md5:${t}`]:[],...dk.flatMap(([r,i])=>{let o=r.exec(n.source)?.[1];return o?[`post:${i}:${Number(o)}`]:[]}),...n.family?[`family:${e.key}:${n.family}`]:[]]}function qd(e,n){let t=e.owner||e.artist;return t!==""&&t===(n.owner||n.artist)&&e.width===n.width&&e.height===n.height}function Qd(e){let r=[];for(let o=0;o<8;o++){let s=Math.floor(o*e.height/8),u=Math.max(s+1,Math.floor((o+1)*e.height/8));for(let c=0;c<9;c++){let a=Math.floor(c*e.width/9),h=Math.max(a+1,Math.floor((c+1)*e.width/9)),f=0;for(let l=s;l<u;l++)for(let d=a;d<h;d++){let g=(l*e.width+d)*4,p=e.data[g+3]/255,k=0.299*e.data[g]+0.587*e.data[g+1]+0.114*e.data[g+2];f+=k*p+255*(1-p)}r.push(f/((h-a)*(u-s)))}}let i=0n;for(let o=0;o<8;o++)for(let s=0;s<8;s++)i=i<<1n|(r[o*9+s]>r[o*9+s+1]?1n:0n);return i.toString(16).padStart(16,"0")}function gk(e,n){let t=BigInt(`0x${e}`)^BigInt(`0x${n}`),r=0;while(t>0n)r+=Number(t&1n),t>>=1n;return r}function Yd(e,n){if(e.width<=0||e.height<=0||n.width<=0||n.height<=0)return!1;return Math.abs(Math.log(e.width/e.height/(n.width/n.height)))<0.01&&gk(e.hash,n.hash)<=2}var wk={thumb:"tile",match:"tile",show:"view",backdrop:"view"};function $k(e){let n=Lr(new Uint8Array(Xd(e.from)),vn);if(e.job==="backdrop")return fo(e.home,e.colors,e.tone,n,{...e.origin,bytes:new Uint8Array(Xd(e.source))},e),0;if(e.job==="match")return{match:Kd(n,e.colors),hash:Qd(n)};if(e.job==="thumb")return Zd(zd(e.to),{recursive:!0}),Vd(e.to,pt(Xa(n,e.width,e.height))),0;let t=Dn(n);return Zd(zd(e.to),{recursive:!0}),Vd(e.to,pt(_h(n,e.colors,e.tone,e.width,e.height))),t}function bk(e){e.on("message",(n)=>{try{e.postMessage({id:n.id,value:$k(n)})}catch(t){e.postMessage({id:n.id,error:t instanceof Error?t.message:String(t)})}})}class Dd{worker;next=1;waiting=new Map;send(e){let n=this.next++;return new Promise((t,r)=>{let i=this.open();this.waiting.set(n,{ok:t,no:r}),i.ref(),i.postMessage({...e,id:n})})}close(){this.worker?.terminate(),this.worker=void 0,this.drop(Error("renderer closed"))}open(){if(this.worker)return this.worker;let e=new pk(import.meta.filename);e.unref(),e.on("message",({id:t,value:r,error:i})=>{let o=this.waiting.get(t);if(this.waiting.delete(t),this.waiting.size===0)e.unref();if(i!==void 0)o?.no(Error(i));else o?.ok(r)});let n=(t)=>{if(this.worker===e)this.worker=void 0;this.drop(t instanceof Error?t:Error("renderer stopped"))};return e.on("error",n),e.on("exit",()=>n(void 0)),this.worker=e,e}drop(e){for(let n of this.waiting.values())n.no(e);this.waiting.clear()}}class nc{lines=new Map;run(e){let n=wk[e.job],t=this.lines.get(n);if(!t)t=new Dd,this.lines.set(n,t);return t.send(e)}close(){for(let e of this.lines.values())e.close();this.lines.clear()}}if(!mk&&Bd)bk(Bd);var gr=[{name:"TTHEME_FIND_RATING",label:"rating",choices:Ur,multi:{read:Xt}},{name:"TTHEME_FIND_BLOCK",label:"block",choices:$t,multi:{read:Vt,none:"none"}},{name:"TTHEME_FIND_POSTS",label:"posts",choices:["all","cutouts"]},{name:"TTHEME_FIND_SOLO",label:"solo",choices:["on","off"]},{name:"TTHEME_FIND_ORDER",label:"order",choices:["fit","newest","score"]},{name:"TTHEME_FIND_SETS",label:"sets",choices:["fold","show"]},...vi()?[{name:"TTHEME_FIND_REMOVE_BG",label:"remove bg",choices:["on","off"]}]:[]];function Mk(e,n){if(e.multi)return e.multi.read(n).join(" ")||e.multi.none;return e.choices.find((t)=>t===n)??e.choices[0]}var Ik=["fit","newest","score"];function xd(e){return Ik.find((n)=>n===e)??"fit"}function Nk(e){return e.length>=2&&!/^\d+$/.test(e)&&!e.includes("://")&&!/^[\w.]+:\d+$/.test(e)}var eg=12,Ok=4,Rk=150,ng=12,Fk=2,Pk=150,Hk=30,Lk=4000,Ak=8000,tg=/\.(png|jpe?g|gif|webp|heic|tiff?|bmp)$/i,Tk=process.platform==="win32"?"alt+v":"ctrl+v",rg=process.platform==="darwin"?"ctrl+shift+cmd+4 copies a screenshot":"copy a picture first",Gk=1280,ig=2,Uk=3,jk=8;function ss(e,n){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:n}}function mr(e){if(!(e instanceof Error))return String(e);if(e instanceof AggregateError&&e.errors[0])return mr(e.errors[0]);if(e.cause)return mr(e.cause);let n=e.code;if(typeof n==="string")return n;let t=(e.message||e.name).split(".")[0]??"";return t.length>56?`${t.slice(0,55)}…`:t}function rc(e,n){return`${e}: ${mr(n)}`}function og(e){return e.width*e.height}function sg(e){return`${e.id}-${ug("sha1").update(e.preview).digest("hex").slice(0,8)}`}function Jk(e){let n=e.lastIndexOf("\x1B");return n!==-1&&/^\[?[0-9;]*$/.test(e.slice(n+1))}function ic(e,n){try{return JSON.parse(cg(Tn(pn(e),n),"utf8"))}catch{return{}}}function oc(e,n,t){Pi(pn(e),{recursive:!0}),Hi(Tn(pn(e),n),`${JSON.stringify(t)}
515
- `)}class ag{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,Mk(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 nc;sent=new Map;placed=new Map;current;fetch;settle;partial;suggestTimer;suggesting;input="";typed="";grabber=new Vu((e)=>this.write(e),(e)=>void this.got(e));featureWait;noticeTimer;peekTimer;peeked;attaching;probeWait;done;dirty=!1;unblock=!1;scratch=Ek(Tn(Sk(),"ttheme-find-"));home;catalog;entry;constructor(e,n,t,r){this.home=e,this.catalog=n,this.entry=t,this.tone=er(t,t.signatureSlots),this.view={palette:t.name,tag:r,site:this.tabName,siteAnsi:this.tabAnsi,nextSite:this.nextTabName,preset:this.setting("TTHEME_FIND_POSTS")==="all"?"all":"cutouts",order:xd(this.setting("TTHEME_FIND_ORDER")),solo:this.setting("TTHEME_FIND_SOLO")==="on",rating:Xt(this.setting("TTHEME_FIND_RATING")),block:Vt(this.setting("TTHEME_FIND_BLOCK")),sets:this.setting("TTHEME_FIND_SETS")==="show"?"show":"fold",unblocked:process.env.TTHEME_FIND_PROXY!==void 0,settings:gr.map((i)=>({label:i.label,choices:[...i.choices],value:this.setting(i.name),multi:i.multi&&{none:i.multi.none},cursor:0})),colors:{cursor:t.cursor,selection:t.selection,ansi:t.ansi},tiles:[],installed:[],checked:0,total:0,searching:r!=="",focus:0,top:0,mode:"grid",help:!1,editing:r===""?"":void 0},this.board=ss(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:x[this.tab-1]}get sites(){return this.site?[this.site]:x}get tabName(){return this.site?.name??"all"}get tabAnsi(){return this.site?.ansi??Ok}get nextTabName(){let e=(this.tab+1)%(x.length+1);return e===0?"all":x[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)}get boardKey(){return`${this.site?.key??"all"}|${this.view.preset}|${this.view.order}`}origPath(e,n,t){return Tn(pn(e),"orig",`${n}.${t}`)}previewPath(e){return Tn(pn(e.site),"thumb",`${sg(e.post)}.${jr(e.post.preview)}`)}tileOf(e,n){let{site:t,post:r}=e,i=Mn(t,r.id),o=bt(r)??r;return{id:r.id,key:i,site:t.name,siteAnsi:t.ansi,width:o.width,height:o.height,reduced:o!==r,owner:r.owner,artist:t===ns?kd(r.source):r.artist,score:r.score,variants:n,origin:Ws(r.source),mates:this.owners.get(t.key)?.get(r.owner)??[],thumb:this.thumbPath.get(i)}}show(){let e=this.view,n=this.board;e.tiles=n.groups.flatMap((t)=>t.open?t.posts.map((r)=>this.tileOf(r,0)):[this.tileOf(t.posts[0],t.posts.length)]),e.checked=n.checked,e.total=n.total,e.searching=n.searching,e.note=n.note,e.focus=Math.max(0,Math.min(n.focus,e.tiles.length-1)),e.top=n.top}syncSite(){let e=this.view;e.site=this.tabName,e.siteAnsi=this.tabAnsi,e.nextSite=this.nextTabName}async run(){let{stdin:e,stdout:n}=process;e.setRawMode(!0),e.resume(),e.on("data",this.onData),n.on("resize",this.onResize),this.write("\x1B[?25l\x1B[?7l\x1B[H\x1B[K\x1B[2H\x1B[J\x1B[H");let t=new Promise((s)=>{this.done=s}),r=setInterval(this.onClock,250),i=await this.probe();if(i){if(this.cell=i,this.view.tag)this.search()}else this.view.searching=!1,this.view.error="this terminal does not report its cell size — find needs kitty graphics";await this.features(),this.grabber.start(),this.write("\x1B[?1004h"),this.peek(),this.draw();let o=await t;return this.grabber.stop(),this.write("\x1B[?1004l"),this.attaching?.abort(),clearTimeout(this.noticeTimer),clearTimeout(this.peekTimer),this.session.abort(),this.fetch?.abort(),clearTimeout(this.settle),clearTimeout(this.partial),this.quietSuggest(),clearInterval(r),e.off("data",this.onData),n.off("resize",this.onResize),this.write("\x1B_Ga=d,d=A,q=2\x1B\\\x1B[H\x1B[K\x1B[2H\x1B[J\x1B[H"),e.setRawMode(!1),e.pause(),this.saveProbes(),this.renders.close(),tc(this.scratch,{recursive:!0,force:!0}),ah(),o}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 n=setTimeout(()=>{this.probeWait=void 0,e(null)},1000);this.probeWait=(t)=>{clearTimeout(n),this.probeWait=void 0,e(t)},this.write(Fd)})}onData=(e)=>{this.input+=e.toString("utf8");for(let t=Du(this.input);t;t=Du(this.input))this.input=t.rest,this.probeWait?.(t.cell);if(this.probeWait)return;let n=Id(this.input);if(this.input=n.pending,this.view.editing===void 0&&n.keys.length>8&&/^(?:\/|~\/|file:|https?:)/.test(n.keys))this.pasted(n.keys),n.keys="";this.typed+=n.keys;for(let t of n.events)this.inbound(t);if(clearTimeout(this.partial),Jk(this.typed)){this.partial=setTimeout(this.flushKeys,Hk);return}this.flushKeys()};flushKeys=()=>{let e=Rd(this.typed);this.typed="";for(let n of e)this.key(n)};features(){if(process.env.TMUX)return Promise.resolve();return new Promise((e)=>{let n=setTimeout(()=>{this.featureWait=void 0,e()},500);this.featureWait=()=>{clearTimeout(n),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 n=this.view;if(n.editing!==void 0&&e.trim()!==""&&!this.picture(e)){n.editing+=e.replace(/[\r\n]+/g," "),this.suggest(),this.draw();return}if(n.installing!==void 0||n.asking!==void 0||n.panel!==void 0||n.help)return;if(e.trim()===""){this.fromClipboard();return}this.attach(e)}picture(e){let n=e.trim();if(/^https?:\/\/\S+$/i.test(n))return!ro(n,this.site??x[0]);return es(n).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 — ${rg}`);return}this.pasted(e.text);return}await this.bring(()=>Do(e.bytes,e.source))}notice(e,n=Lk){let t=this.view;t.error=e,clearTimeout(this.noticeTimer),this.noticeTimer=setTimeout(()=>{if(t.error===e)t.error=void 0,this.draw()},n),this.draw()}async peek(){let e=this.view,n;try{n=await Md()}catch{return}if(!n||n.stamp===this.peeked)return;if(this.peeked=n.stamp,!n.picture||e.installing!==void 0||e.asking!==void 0)return;e.hint=`picture on the clipboard · ${Tk} uses it`,clearTimeout(this.peekTimer),this.peekTimer=setTimeout(()=>{e.hint=void 0,this.draw()},Ak),this.draw()}async fromClipboard(){let e=this.view;if(Xu()){if(this.grabber.clipboard){this.grabber.ask();return}this.notice("over ssh the clipboard is not here — drop the file");return}let n;try{n=await vd(Tn(this.scratch,`clipboard-${Date.now()}.png`))}catch(r){this.notice(`could not read the clipboard: ${mr(r)}`);return}if(clearTimeout(this.peekTimer),e.hint=void 0,"image"in n){await this.bring(async(r)=>({...await Zu(n.image,r),source:"clipboard"}));return}let t=n.text.trim();if(!t){this.notice(`no picture on the clipboard — ${rg}`);return}if(this.picture(t)){await this.attach(t);return}if(e.editing===void 0)e.editing="";this.pasted(t)}async attach(e){let n=e.trim();if(/^https?:\/\//i.test(n)){let i=ro(n,this.site??x[0]);if(i){await this.jump(i.site,i.id);return}}let[t,...r]=es(n).sort((i,o)=>Number(!tg.test(i))-Number(!tg.test(o)));if(!t){this.notice("nothing to use in that — drop a picture, or paste one or its link");return}await this.bring((i)=>Zu(t,i),r.length)}async bring(e,n=0){let t=this.view;this.attaching?.abort();let r=new AbortController;this.attaching=r,t.error=void 0,t.saved=void 0,t.note="reading the picture…",this.draw();let i;try{i=await e(AbortSignal.any([r.signal,this.signal]))}catch(l){if(!r.signal.aborted)t.note=void 0,this.notice(mr(l),8000);return}if(r.signal.aborted)return;t.note=n>0?`the first picture of ${n+1} — drop one at a time to try the others`:void 0,this.quietSuggest(),t.editing=void 0,t.suggest=void 0,t.pick=void 0;let o=yd(i.bytes);Ed(o,i.source);let s=this.origPath(ns,o,i.ext);Pi(os(s),{recursive:!0}),Hi(s,i.bytes);let u=vk(s).href,c={id:o,file:u,width:i.width,height:i.height,ext:i.ext,preview:u,owner:"",artist:"",score:0,rating:"s",md5:ug("md5").update(i.bytes).digest("hex"),source:i.source,tags:[],solo:void 0,family:0,smaller:[]},a={site:ns,post:c},h=this.previewPath(a);Pi(os(h),{recursive:!0}),Hi(h,i.bytes),++this.gen,this.current=void 0,t.shown=void 0;let f=ss(`local|post:${o}`,!1);this.board=f,this.boards.set(f.key,f),this.single(f,a)}single(e,n){e.searching=!1,this.posts.set(Mn(n.site,n.post.id),n),e.groups=[{posts:[n],open:!1}],e.checked=1,e.total=1,this.thumbQueue.push(n),this.thumbs(),this.view.mode="try",this.show(),this.select(),this.draw()}onClock=()=>{let e=this.sites.reduce((r,i)=>xn(i)>xn(r)?i:r),n=Math.ceil((xn(e)-Date.now())/1000),t=n>0?n:void 0;if(t!==this.view.waiting)this.view.waiting=t,this.view.slow=e.name,this.draw()};onResize=()=>{if(this.cols=process.stdout.columns||this.cols,this.rows=process.stdout.rows||this.rows,this.scroll(),this.view.mode==="try"&&this.current)this.reveal();this.pump(),this.draw()};key(e){let n=this.view;if(e==="ctrl-c"){this.finish(2);return}if(n.installing!==void 0)return;if(n.asking!==void 0){this.askKey(e);return}if(e==="focus-in"){this.peek();return}if(e==="focus-out"||e==="nop")return;if((e==="ctrl-v"||e==="alt-v")&&n.panel===void 0){this.fromClipboard();return}if(n.editing!==void 0){this.editKey(e);return}if(n.panel!==void 0){this.panelKey(e);return}if(n.help){if(e==="?"||e==="esc")n.help=!1,this.draw();return}if(this.cols<Ut.cols||this.rows<Ut.rows){if(e==="esc")this.finish(2);return}if(e==="?"){n.help=!0,this.draw();return}if(n.mode==="try"){this.tryKey(e);return}this.gridKey(e)}gridKey(e){let n=this.view,{perRow:t,rowsVis:r}=lr(this.cols,this.rows),o={left:-1,right:1,up:-t,down:t,pgup:-t*r,pgdn:t*r,home:-n.focus,end:n.tiles.length}[e];if(o!==void 0){this.focus(n.focus+o);return}if(e==="enter"&&n.tiles[n.focus]){n.mode="try",n.error=void 0,this.select();return}if(e==="v"){this.fromClipboard();return}if(e==="c"){n.preset=n.preset==="cutouts"?"all":"cutouts",this.turn();return}if(e==="tab"){this.tab=(this.tab+1)%(x.length+1),this.syncSite(),this.turn();return}if(e==="/"){n.editing="",this.draw();return}if(e===" "){this.unfold();return}if(e==="o"){this.openPage();return}if(e==="s"){n.panel=0,this.draw();return}if(e==="esc")this.finish(2)}panelKey(e){let n=this.view,t=n.panel??0,r=n.settings[t];if(e==="up"||e==="down"){n.panel=Math.max(0,Math.min(n.settings.length-1,t+(e==="up"?-1:1))),this.draw();return}if((e==="left"||e==="right")&&r){let i=e==="left"?-1:1;if(r.multi)r.cursor=(r.cursor+i+r.choices.length)%r.choices.length;else{let o=r.choices.indexOf(r.value);r.value=r.choices[(o+i+r.choices.length)%r.choices.length]}this.draw();return}if(e===" "&&r?.multi){let i=r.value.split(" "),o=r.choices.filter((u,c)=>c===r.cursor?!i.includes(u):i.includes(u)),s=r.multi.none;if(o.length>0||s!==void 0)r.value=o.length>0?o.join(" "):s,this.draw();return}if(e==="esc"){n.settings.forEach((i,o)=>{i.value=this.setting(gr[o]?.name??"")}),n.panel=void 0,this.draw();return}if(e==="enter"||e==="alt-c")n.panel=void 0,this.adopt()}adopt(){let e=this.view,n=gr.map((r)=>this.setting(r.name));e.settings.forEach((r,i)=>{let o=gr[i];if(o)this.values.set(o.name,r.value)});let t=gr.filter((r,i)=>this.setting(r.name)!==n[i]);if(t.length===0){this.draw();return}this.save(t),e.rating=Xt(this.setting("TTHEME_FIND_RATING")),e.block=Vt(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=xd(this.setting("TTHEME_FIND_ORDER")),e.solo=this.setting("TTHEME_FIND_SOLO")==="on",this.boards.clear(),this.current=void 0,e.shown=void 0,e.mode="grid",this.search()}save(e){this.store(e.map((n)=>[n.name,this.setting(n.name)]))}store(e){let n=Tn(this.home,"ttheme","config.zsh");try{let t=dr(n)?cg(n,"utf8"):"";return Hi(n,e.reduce((r,[i,o])=>cf(r,i,o),t)),!0}catch(t){return this.view.error=t instanceof Error?t.message:String(t),!1}}askKey(e){let n=this.view;if(e==="y"){if(n.asking=void 0,this.store([["TTHEME_FIND_UNBLOCK","1"]])){this.unblock=!0,this.finish(0);return}this.draw();return}if(e==="n"||e==="esc")n.asking=void 0,this.draw()}editKey(e){let n=this.view,t=n.editing??"",r=n.suggest??[];if((e==="up"||e==="down")&&r.length>0){let i=n.pick??-1,o=e==="down"?Math.min(r.length-1,i+1):i-1;n.pick=o<0?void 0:o,this.draw();return}if(e==="esc"||e==="enter")this.quietSuggest();if(e==="esc"){if(n.editing=void 0,n.tag===""){this.finish(2);return}this.draw();return}if(e==="enter"){let i=n.pick===void 0?void 0:r[n.pick],o=i?t.replace(/\S*$/,i.value):t;if(n.editing=void 0,n.suggest=void 0,n.pick=void 0,o.trim()){this.commit(o.trim());return}if(n.tag===""){this.finish(2);return}this.draw();return}if(e==="backspace"){n.editing=t.slice(0,-1),this.suggest(),this.draw();return}if(e.length===1&&e>=" ")n.editing=t+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 n=/\S*$/.exec(e.editing??"")?.[0]??"";if(!Nk(n)){e.suggest=void 0;return}let t=[...new Map(kl(this.catalog.palettes,this.entry,n).map((i)=>[i.booru,{value:i.booru,count:0,palette:i.name}])).values()].slice(0,Uk);e.suggest=t.length>0?t:void 0;let r=new AbortController;this.suggesting=r,this.suggestTimer=setTimeout(async()=>{try{let i=await gh(n,AbortSignal.any([this.signal,r.signal]));if(this.suggesting===r&&e.editing!==void 0){let o=new Map(i.map((u)=>[u.value,u.count])),s=new Set(t.map((u)=>u.value));e.suggest=[...t.map((u)=>({...u,count:o.get(u.value)??0})),...i.filter((u)=>!s.has(u.value))].slice(0,jk),e.pick=e.pick!==void 0&&e.pick<t.length?e.pick:void 0,this.draw()}}catch{}},Rk)}async commit(e){let n=ro(e,this.site??x[0]);if(n){await this.jump(n.site,n.id);return}if(this.picture(e)){await this.attach(e);return}this.view.tag=e,this.boards.clear(),await this.search()}async jump(e,n){let t=++this.gen;this.tab=x.indexOf(e)+1,this.syncSite(),this.current=void 0,this.view.shown=void 0,this.view.error=void 0;let r=ss(`${e.key}|post:${n}`,!0);this.board=r,this.boards.set(r.key,r),this.show(),this.draw();try{let i=await Cr(e,n,this.signal);if(t!==this.gen)return;if(!i){r.searching=!1,r.error=`${e.name} has no post ${n}`,this.view.error=r.error,this.show(),this.draw();return}this.single(r,{site:e,post:i})}catch(i){this.fail(t,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,n=0;for(let t of this.board.groups){let r=t.open?t.posts.length:1;if(e.focus<n+r){if(t.posts.length<2)return;t.open=!t.open,this.board.focus=n;for(let i of t.posts)if(!this.thumbPath.has(Mn(i.site,i.post.id)))this.thumbQueue.push(i);this.thumbs(),this.show(),this.scroll(),this.draw();return}n+=r}}openPage(){let e=this.view.tiles[this.view.focus],n=e&&this.posts.get(e.key);if(!n)return;let t=process.platform==="darwin"?"open":"xdg-open";try{kk(t,[n.site.pageUrl(n.post.id)],{stdio:"ignore",detached:!0}).unref()}catch{}}tryKey(e){let n=this.view;if(e==="left"||e==="right"){this.direction=e==="left"?-1:1,this.focus(n.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),n.fetching=void 0,n.mode="grid",n.error=void 0,this.draw()}focus(e){let n=this.view;if(n.tiles.length===0)return;let t=Math.max(0,Math.min(n.tiles.length-1,e));if(t===n.focus)return;if(n.focus=t,this.board.focus=t,this.scroll(),this.pump(),n.mode==="try")this.select();this.draw()}scroll(){let e=this.view,{perRow:n,rowsVis:t}=lr(this.cols,this.rows),r=Math.floor(e.focus/n);if(r<e.top)e.top=r;if(r>e.top+t-1)e.top=r-t+1;this.board.top=e.top}query(e){let n=this.view,t=n.tag===this.entry.booru?El(this.entry,e.key):[n.tag];if(t.length===0)return;let r=t.length>1,i=n.preset==="cutouts"?e.cutouts:"",o=r&&i.includes("~"),s=[r?t.map((a)=>`~${a}`).join(" "):t[0],e.rate(this.view.rating),o?"":i,n.order==="score"?e.best:""].filter(Boolean),u=[],c=[];for(let a of s)if(Cs([...u,a].join(" "))<=e.tagBudget)u.push(a);else c.push(a);return{tags:u.join(" "),notes:[...c.length>0?[`${e.name} takes ${e.tagBudget} tags — ${c.join(" ")} left out`]:[],...o?[`${e.name} ORs the names, so cutouts are told by the file`]:[]]}}async search(){let e=++this.gen,n=ss(this.boardKey,!0);this.board=n,this.boards.set(n.key,n),this.view.error=void 0;let t=this.sites.flatMap((o)=>{let s=this.query(o);return s?[{site:o,...s}]:[]}),r=this.sites.filter((o)=>!t.some((s)=>s.site===o)),i=[...t.flatMap(({notes:o})=>o),...r.length>0?[`${this.entry.name} has no tag on ${r.map((o)=>o.name).join(", ")}`]:[]];if(n.note=i.length>0?i.join(" · "):void 0,t.length===0)n.searching=!1;this.show(),this.draw(),this.tally(e,n,t);try{let o=await Promise.all(t.map(async(s)=>({plan:s,owners:await this.mateOwners(s.site)})));if(e!==this.gen)return;n.sources=o.flatMap(({plan:{site:s,tags:u},owners:c})=>[...Cs(u)+1<=s.tagBudget?[...c.keys()].map((a)=>({site:s,tags:`${u} user:${a}`,page:0,done:!1})):[],{site:s,tags:u,page:0,done:!1}]),this.show(),this.draw(),await this.pump()}catch(o){this.fail(e,o)}}async tally(e,n,t){let r=await Promise.allSettled(t.map(({site:i,tags:o})=>fh(i,o,this.signal)));if(e===this.gen)n.total=r.reduce((i,o)=>i+(o.status==="fulfilled"?o.value:0),0),this.show(),this.draw()}fail(e,n,t=this.site){if(e!==this.gen||this.signal.aborted)return;this.board.error=rc(t?.name??this.tabName,n),this.board.searching=!1,this.view.error=this.board.error,this.offer(t,n),this.show(),this.draw()}offer(e,n){if(e&&!this.view.unblocked&&Mi()&&mr(n)==="ECONNRESET")this.view.asking=e.name}drop(e,n,t){for(let r of e.sources)if(r.site===n)r.done=!0;e.note=[e.note,rc(n.name,t)].filter(Boolean).join(" · "),this.offer(n,t)}wants(){let{perRow:e,rowsVis:n}=lr(this.cols,this.rows);return this.view.tiles.length<(this.board.top+n+ig)*e}need(){let{perRow:e,rowsVis:n}=lr(this.cols,this.rows);return(n+ig)*e}live(e){return this.boards.get(e.key)===e}page(e,n,t){let r=`${e.key}|${n}|${t}`,i=this.pages.get(r);if(!i)i=hh(e,n,t,this.signal).then((o)=>this.borrow(o)),this.pages.set(r,i),i.catch(()=>this.pages.delete(r));return i}async borrow(e){let n=e.filter((t)=>t.solo===void 0&&t.md5!=="");if(n.length>0)try{lh(n,await dh(n.map((t)=>t.md5),this.signal))}catch{}return e}async round(e){let n=x.flatMap((u)=>{let c=e.sources.find((a)=>a.site===u&&!a.done);return c?[c]:[]}),t=await Promise.all(n.map(async(u)=>{try{return{source:u,posts:await this.page(u.site,u.tags,u.page)}}catch(c){if(e.sources.every((a)=>a.site===u.site)||this.signal.aborted)throw c;return this.drop(e,u.site,c),{source:u,posts:void 0}}}));if(!this.live(e))return;let r=[];for(let{source:u,posts:c}of t){if(!c)continue;u.page++,u.done=c.length<wt;let a=e.last.get(u);for(let h of c){let f=a&&qd(a.post,h)?a.set:`set:${u.site.key}:${h.id}`;a={post:h,set:f};let l=Mn(u.site,h.id);if(e.seen.has(l))continue;e.seen.add(l);let d={site:u.site,post:h};if(this.eligible(d))e.kin.set(d,[f,..._d(u.site,h)]),r.push(d);else e.checked++}if(a)e.last.set(u,a)}let i=this.dedupe(e,r),o=++e.rounds,s;if(this.view.order!=="fit")s=n.length>1?Wd(i):i;else{let u=is(i,this.frame(),this.matched),c=u.slice(0,this.need());if(await this.looks(c),!this.live(e))return;s=[...is(c,this.frame(),this.matched),...u.slice(c.length)]}for(let u of s)e.roundOf.set(u,o);e.queue.push(...s),this.ahead(e)}ahead(e){if(this.aheading||this.view.order!=="fit"||!this.live(e))return;let n=e.queue.slice(0,this.need()).filter((t)=>!this.looking.has(Mn(t.site,t.post.id)));if(n.length===0)return;this.aheading=!0,this.looks(n).then(()=>{this.aheading=!1;for(let t of new Set(n.map((r)=>e.roundOf.get(r)??0)))this.resort(e,t);this.ahead(e)})}resort(e,n){let t=e.queue.flatMap((i,o)=>e.roundOf.get(i)===n?[o]:[]),r=is(t.map((i)=>e.queue[i]),this.frame(),this.matched);t.forEach((i,o)=>{e.queue[i]=r[o]})}dedupe(e,n){let t=[];for(let r of n){let i=ec(r.post),o=i.map((u)=>e.same.get(u)).find(Boolean);if(!o){for(let u of i)e.same.set(u,r);t.push(r);continue}if(e.checked++,og(r.post)<=og(o.post))continue;for(let u of[...i,...ec(o.post)])e.same.set(u,r);let s=t.indexOf(o);if(s>=0){t[s]=r;continue}this.replace(e,o,r)}return t}replace(e,n,t){e.roundOf.set(t,e.roundOf.get(n)??0);let r=e.queue.indexOf(n);if(r>=0){e.queue[r]=t;return}for(let i of e.groups){let o=i.posts.indexOf(n);if(o>=0){i.posts[o]=t,this.posts.set(Mn(t.site,t.post.id),t),this.thumbQueue.push(t),this.thumbs();return}}}async looks(e){let n=0;await Promise.all(Array.from({length:ng},async()=>{while(n<e.length)await this.look(e[n++])}))}look(e){let n=Mn(e.site,e.post.id),t=this.looking.get(n);if(!t)t=(async()=>{let r=this.previewPath(e);await this.cached(e.site,r,e.post.preview);let i=await this.renders.run({job:"match",from:r,colors:this.entry.signature});return this.looked.set(n,i),this.matched.set(e.post,i.match),i})().catch(()=>{return}),this.looking.set(n,t);return t}async pump(){let e=this.gen,n=this.board;if(this.pumping===e||n.sources.length===0)return;this.pumping=e;let t=[],r;try{n.searching=!0;while(e===this.gen){while(t.length<eg&&n.queue.length>0&&this.wants()){let s=n.queue.shift();t.push({pick:s,passed:this.vet(s)})}if(this.ahead(n),!r&&n.queue.length<eg&&n.sources.some((s)=>!s.done)&&this.wants()){let s=this.round(n).then(()=>{if(r===s)r=void 0});s.catch(()=>{}),r=s}let i=t.shift();if(!i){if(!r)break;await r,this.show(),this.draw();continue}let o=await i.passed;if(e!==this.gen)return;if(n.checked++,o)this.admit(i.pick);this.show(),this.draw()}if(e===this.gen)n.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:n}){let t=bt(n);if(!oo(e,n,this.view.rating)||io(n,this.view.block).length>0||!t)return!1;if(this.view.solo&&n.solo===!1)return!1;return this.view.preset==="all"?["png","jpg","jpeg"].includes(t.ext):n.ext==="png"}async vet(e){let[n]=await Promise.all([this.passes(e),this.look(e)]);return n}async passes({site:e,post:n}){return this.view.preset==="all"||e.vouched||this.transparent(e,n)}probes(e){let n=this.probed.get(e.key);if(!n)n=ic(e,"probes.json"),this.probed.set(e.key,n);return n}async transparent(e,n){let t=this.probes(e),r=t[n.id];if(r!==void 0)return r;try{let i=(await mh(e,n.file,this.signal))?.alpha===!0;return t[n.id]=i,this.unsaved.add(e.key),i}catch{return!1}}saveProbes(){for(let e of this.unsaved){let n=x.find((t)=>t.key===e);if(n)oc(n,"probes.json",this.probes(n))}this.unsaved.clear()}admit(e){let{site:n,post:t}=e,r=this.board,i=Mn(n,t.id);this.posts.set(i,e);let o=r.kin.get(e)??[],s=this.looked.get(i),u=s&&{hash:s.hash,width:t.width,height:t.height},c=this.view.sets==="fold"?this.kindred(r,o,u):void 0;if(c){if(c.posts.push(e),this.register(r,c,o,u),c.open)this.thumbQueue.push(e),this.thumbs();return}let a={posts:[e],open:!1};r.groups.push(a),this.register(r,a,o,u),this.thumbQueue.push(e),this.thumbs()}kindred(e,n,t){for(let r of n){let i=e.kindred.get(r);if(i)return i}return t&&e.shapes.find((r)=>Yd(r.shape,t))?.group}register(e,n,t,r){for(let i of t)if(!e.kindred.has(i))e.kindred.set(i,n);if(r)e.shapes.push({shape:r,group:n})}async mateOwners(e){let n=this.owners.get(e.key);if(n)return n;let t=Bh(this.home),r=ic(e,"owners.json"),i=this.catalog.palettes.flatMap((c)=>{let a=t.get(c.name);return c.group===this.entry.group&&c.name!==this.entry.name&&a?.site===e.key?[{name:c.name,id:a.id}]:[]}),o=await Promise.all(i.map(async(c)=>{let a=r[c.id];if(a!==void 0)return{...c,owner:a};try{return{...c,owner:(await Cr(e,c.id,this.signal))?.owner??""}}catch{return}})),s=new Map;for(let c of o)if(c)r[c.id]=c.owner,s.set(c.name,c.owner);oc(e,"owners.json",r);let u=ch(s);return this.owners.set(e.key,u),u}async cached(e,n,t,r){if(dr(n))return yk(n).size;let i=this.inflight.get(n);if(i)return i;let o=(async()=>{let s=await uo(e,t,this.signal,r);return Pi(os(n),{recursive:!0}),Hi(n,s),s.length})();this.inflight.set(n,o);try{return await o}finally{this.inflight.delete(n)}}thumbs(){while(this.thumbing<ng&&this.thumbQueue.length>0){let e=this.thumbQueue.shift();this.thumbing++,this.thumb(e).catch(()=>{}).finally(()=>{this.thumbing--,this.thumbs()})}}async thumb(e){let{site:n,post:t}=e,r=ze.cols*this.cell.w,i=ze.rows*this.cell.h,o=Tn(pn(n),"tile",`${sg(t)}-${r}x${i}.png`);if(!dr(o)){let s=this.previewPath(e);await this.cached(n,s,t.preview),await this.renders.run({job:"thumb",from:s,to:o,width:r,height:i})}this.thumbPath.set(Mn(n,t.id),o),this.show(),this.draw()}select(){let e=this.view,n=e.tiles[e.focus];if(this.fetch?.abort(),clearTimeout(this.settle),e.fetching=void 0,!n)return;if(this.current?.key===n.key){this.reveal();return}this.settle=setTimeout(()=>void this.load(n),Pk),this.draw()}async load(e){let n=this.view,t=this.posts.get(e.key),r=t&&bt(t.post);if(!t||!r)return;let{site:i}=t,o=this.board,s=new AbortController;this.fetch=s;try{let u=this.origPath(i,e.id,r.ext);if(!dr(u))n.fetching={id:e.key,got:0,size:0},this.draw();let c=await this.cached(i,u,r.file,(f,l)=>{if(n.fetching?.id===e.key)n.fetching={id:e.key,got:f,size:l},this.draw()});if(s.signal.aborted)return;if(n.fetching=void 0,o!==this.board)return;let a={site:i,id:e.id,key:e.key,path:u,ext:r.ext,size:c,using:"plain",failed:!1};n.preparing=e.key,this.flush();let h=await this.render(a,"plain");if(s.signal.aborted||o!==this.board)return;if(h.clear===0&&vi()&&this.setting("TTHEME_FIND_REMOVE_BG")!=="off"){if(n.preparing=void 0,n.cutting=e.key,this.flush(),a.cut=await this.cutOut(i,e.id,u,s.signal),s.signal.aborted||o!==this.board)return;if(n.cutting=void 0,a.cut){n.preparing=e.key,this.flush();let f=await this.render(a,"cut").catch(()=>{return});if(s.signal.aborted||o!==this.board)return;if(f&&Qo(f.clear))a.using="cut";else tc(a.cut,{force:!0}),a.cut=void 0,a.failed=!0}else a.failed=!0}if(this.current=a,n.tiles[n.focus]?.key===e.key)await this.present();this.preload()}catch(u){if(!s.signal.aborted&&!this.signal.aborted)n.error=rc(i.name,u)}finally{if(n.fetching?.id===e.key)n.fetching=void 0;if(n.preparing===e.key)n.preparing=void 0;if(n.cutting===e.key)n.cutting=void 0;this.draw()}}async cutOut(e,n,t,r){let i=Tn(pn(e),"cut",`${n}.png`);if(dr(i))return i;try{return Pi(os(i),{recursive:!0}),await Yo(t,i,r),i}catch{tc(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 n of[e.focus+this.direction,e.focus-this.direction]){if(this.prefetching>=Fk)return;let t=e.tiles[n],r=t&&this.posts.get(t.key),i=r&&bt(r.post);if(!r||!i)continue;let{site:o,post:s}=r,u=this.origPath(o,s.id,i.ext);this.prefetching++,this.cached(o,u,i.file).then(()=>this.render({site:o,id:s.id,key:t.key,path:u,ext:i.ext,size:0,using:"plain",failed:!1},"plain")).catch(()=>{}).finally(()=>{this.prefetching--})}}async render(e,n){let t=this.cols*this.cell.w,r=this.rows*this.cell.h,i=Math.min(t,Gk),o=Math.max(1,Math.round(r*i/t)),s=Tn(this.scratch,`${e.site.key}-${e.id}${n==="cut"?"c":""}-${i}x${o}.png`),u=`${e.site.key}:${e.id}:${n}`,c=this.clarity.get(u);if(c!==void 0&&dr(s))return{clear:c,path:s};let a=await this.renders.run({job:"show",from:n==="cut"?e.cut:e.path,to:s,width:i,height:o,colors:this.entry,tone:this.tone});return this.clarity.set(u,a),{clear:a,path:s}}async present(){let e=this.current;if(!e)return;let n=e.using,{clear:t,path:r}=await this.render(e,n);if(this.current!==e||e.using!==n)return;this.view.shown={id:e.key,clear:t,bytes:e.size,path:r,cut:e.cut?n==="cut"?"on":"off":e.failed?"failed":"none"}}reveal(){let e=this.view;e.preparing=this.current?.key,this.flush(),this.present().catch((n)=>{e.error=n instanceof Error?n.message:String(n)}).finally(()=>{if(e.preparing===this.current?.key)e.preparing=void 0;this.draw()})}async install(){let e=this.view,n=e.tiles[e.focus],t=this.current;if(!n||t?.key!==n.key||e.preparing!==void 0||e.shown?.id!==n.key)return;e.installing=n.key,e.error=void 0,this.flush();try{await this.renders.run({job:"backdrop",from:t.using==="cut"?t.cut:t.path,source:t.path,home:this.home,colors:this.entry,tone:this.tone,origin:{site:t.site.key,id:t.id,ext:t.ext,from:`${t.site.name} ${t.id} ${t.site.pageUrl(t.id)}`},width:this.cols*this.cell.w,height:this.rows*this.cell.h});let r=ic(t.site,"owners.json");r[t.id]=this.posts.get(t.key)?.post.owner??"",oc(t.site,"owners.json",r),at(this.home),e.saved=`background · ${this.entry.name} ← ${t.site.name} ${t.id}`,e.installed.push(n.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)return;this.dirty=!0,setImmediate(()=>{this.dirty=!1,this.flush()})}flush(){let e=Jd(this.view,this.cols,this.rows),n="\x1B[?2026h";e.lines.forEach((r,i)=>{n+=`\x1B[${i+1};1H\x1B[K${r}`});let t=new Set;for(let r of e.images){if(t.add(r.id),this.sent.get(r.id)!==r.path)n+=Pd(r),this.sent.set(r.id,r.path),this.placed.delete(r.id);let i=`${r.row};${r.col};${r.cols};${r.rows};${r.z}`;if(this.placed.get(r.id)!==i)n+=Hd(r),this.placed.set(r.id,i)}for(let r of this.sent.keys())if(!t.has(r))n+=Ld(r),this.sent.delete(r),this.placed.delete(r);this.write(`${n}\x1B[?2026l`)}}async function hg(e){if(Ni())return Ii();let n=de(),t=ur(n),r=Pt(t.palettes,e);if(!process.stdin.isTTY||!process.stdout.isTTY)throw Error("needs a terminal");let i=new ag(n,t,r,r.booru??""),o=await i.run(),s=i.unblock?await Ii():o;if(i.saved&&s!==0)return process.stderr.write(`${i.saved}
516
- `),0;return s}function fg(e,n){let t=de();if(Pt(ur(t).palettes,e),n==="next"||n==="prev"){let{key:r,at:i,of:o}=Yh(t,e,n==="next"?1:-1);return at(t),process.stderr.write(`background · ${e} ${i}/${o} ${r}
517
- `),0}if(n==="drop"){let{key:r,left:i}=Zh(t,e);return at(t),process.stderr.write(`background · ${e} removed ${r} · ${i} left
518
- `),0}if(n==="tuned")return at(t),0;throw Error(`unknown image action ${n} — next, prev, drop or tuned`)}import{execFileSync as Pg,spawnSync as e1}from"node:child_process";import{chmodSync as n1,copyFileSync as t1,existsSync as rn,mkdirSync as fc,readdirSync as r1,readFileSync as wr,rmSync as Rg,writeFileSync as i1}from"node:fs";import{homedir as o1}from"node:os";import{dirname as pr,join as ye}from"node:path";import{existsSync as xk}from"node:fs";import{openSync as Ck,writeSync as Wk}from"node:fs";import{ReadStream as Kk}from"node:tty";var _k=["10","11","12","17",...Array.from({length:16},(e,n)=>`4;${n}`)];function Li(e=process.env){return Boolean(e.NO_COLOR)||e.TERM==="dumb"}function us(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((n,t)=>`\x1B]4;${t};${n}\x1B\\`)].join("")}function qk(e){let n=new Map;for(let t of e.split("\x1B")){let r=t.match(/^\](\d+(?:;\d+)?);(rgba?:[0-9a-fA-F/]+)/),[,i,o]=r??[];if(i&&o)n.set(i,o)}return n}function lg(e){return[...e].map(([n,t])=>`\x1B]${n};${t}\x1B\\`).join("")}var Qk=`${_k.map((e)=>`\x1B]${e};?\x1B\\`).join("")}\x1B[5n`;function Yk(e){return e.includes("\x1B[0n")}async function dg(){let e,n;try{e=Ck("/dev/tty","r+"),n=new Kk(e),n.setRawMode(!0)}catch{return new Map}try{Wk(e,Qk);let t="";return await new Promise((r)=>{let i=setTimeout(r,120);n.on("data",(o)=>{if(t+=o.toString(),Yk(t))clearTimeout(i),r()})}),qk(t)}finally{n.setRawMode(!1),n.destroy()}}function sc(e){let n=e.replace("#","");return[n.slice(0,2),n.slice(2,4),n.slice(4,6)].map((t)=>Number.parseInt(t,16)).join(";")}function Ai(e){return`\x1B[38;2;${sc(e)}m`}function gg(e,n){return`\x1B[48;2;${sc(e)};38;2;${sc(n)}m`}function mg(e,n="\x1B[39m"){return`${e.map((t)=>`${Ai(t)}■`).join(" ")}${n}`}function cs(e,n){let t=n.toLowerCase();return[e.name,e.group,e.native??""].some((r)=>r.toLowerCase().includes(t))}function wg(e,n,t){let r=t.trim(),i=[],o=new Set;for(let s of e){if(s.default||o.has(s.group))continue;o.add(s.group);let u=e.filter((h)=>!h.default&&h.group===s.group),c=r?u.filter((h)=>cs(h,r)):u;if(r&&c.length===0)continue;let a=r.length>0||n.has(s.group);if(i.push({kind:"group",name:s.group,native:s.native,lead:u.find((h)=>h.lead)??s,expanded:a,count:c.length}),a)i.push(...c.map((h)=>({kind:"palette",entry:h})))}return i}function Zk(e,n){let t=n.trim(),r=new Set(e.filter((i)=>!i.default&&(t===""||cs(i,t))).map((i)=>i.group));return wg(e,new Set,"").filter((i)=>i.kind==="group"&&r.has(i.name))}function Xk(e){return e.includes("@")}function Vk(e){let n=e.findIndex((t)=>t.kind==="group"&&Xk(t.name));return n>0&&e.slice(0,n).some((t)=>t.kind==="group")?[...e.slice(0,n),{kind:"rule"},...e.slice(n)]:e}function zk(e){let n=e.findIndex((t)=>t.kind==="palette");return n===-1?0:n}var Ti="\x1B[0m",uc="\x1B[2m",pg="\x1B[1m",cc="\x1B[22m",Bk="\x1B[36m",Dk="\x1B[33m";function $g(e){return e==="decode"||e==="glitch"?e:"typewriter"}class ac extends Rn{picked;scope;entries;named;series;seriesPad;namePad;expanded=new Set;rows=[];cursor=0;top=0;maxItems;color;lastInput="";lastFocused="";onFocus;example="";fx;fxStep=0;fxSeed=0;fxTimer;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.entries=e.entries,this.scope=e.scope??"palette",this.picked=new Set(e.installed??[]),this.named=e.entries.filter((t)=>!t.default),this.series=[...new Set(this.named.map((t)=>t.group))],this.seriesPad=Math.max(0,...this.series.map((t)=>t.length)),this.namePad=Math.max(0,...this.named.map((t)=>t.name.length)),this.maxItems=e.maxItems??12,this.color=e.color??!0,this.fx=e.fx??"typewriter",this.onFocus=e.onFocus,this.rollExample();let n=setInterval(()=>{this.rollExample(),this.fxStep=8,this.output.emit("resize")},3000);n.unref?.(),this.once("finalize",()=>{clearInterval(n),clearTimeout(this.fxTimer)}),this.rebuild("first"),this.on("cursor",(t)=>{if(t==="up")this.move(-1);else if(t==="down")this.move(1);else if(t==="left")this.fold(!1);else if(t==="right")this.fold(!0)}),this.on("userInput",(t)=>{if(t!==this.lastInput)this.lastInput=t,this.rebuild("keep")}),this.on("key",(t,r)=>{if(r?.name==="space")this.pick(this.rows[this.cursor])})}_isActionKey(e){return e==="\t"||e===" "}members(e){let n=this.scope==="palette"?this.userInput.trim():"";return this.named.filter((t)=>t.group===e&&(n===""||cs(t,n)))}everyone(e){return e.flatMap((n)=>n.kind==="group"?this.members(n.name):[])}pick(e){let n=e?.kind==="palette"?[e.entry.name]:e?.kind==="group"?this.members(e.name).map((r)=>r.name):e?.kind==="all"?this.everyone(this.rows).map((r)=>r.name):[];if(n.length===0)return;let t=n.some((r)=>!this.picked.has(r));for(let r of n)if(t)this.picked.add(r);else this.picked.delete(r)}pickedIn(e){return this.members(e).filter((n)=>this.picked.has(n.name)).length}pickedCount(){if(this.scope==="palette")return this.picked.size;return this.series.filter((e)=>this.members(e).every((n)=>this.picked.has(n.name))).length}rollExample(){let e=this.named[Math.floor(Math.random()*this.named.length)],n=this.series[Math.floor(Math.random()*this.series.length)];if(!e||!n){this.example="";return}let t=`${e.name} | ${n}`;this.example=t.length>30?`${t.slice(0,29)}…`:t,this.fxSeed=Math.floor(Math.random()*997)}animatedExample(){if(this.fxStep===0)return this.example;if(!this.fxTimer)this.fxTimer=setTimeout(()=>{this.fxTimer=void 0,this.fxStep-=1,this.output.emit("resize")},60),this.fxTimer.unref?.();let e=Math.floor(this.example.length*(8-this.fxStep)/8);if(this.fx==="typewriter")return`${this.example.slice(0,e)}▏`;let n=this.fx==="decode"?"abcdefghijklmnopqrstuvwxyz":"▓▒░#*+=<>?/-_",t=this.fx==="decode"?(r)=>!/[a-z0-9]/i.test(r):(r)=>r===" ";return[...this.example].map((r,i)=>i+(i*7+this.fxSeed)%3<e||t(r)?r:n[Math.floor(Math.random()*n.length)]??r).join("")}sync(){let e=this.rows[this.cursor],n=e?.kind==="palette"?e.entry:e?.kind==="group"&&this.scope==="series"?e.lead:void 0;if(n&&n.name!==this.lastFocused)this.lastFocused=n.name,this.onFocus?.(n)}rebuild(e){let n=this.rows[this.cursor],t=this.scope==="series"?Zk(this.entries,this.userInput):wg(this.entries,this.expanded,this.userInput);this.rows=t.length>0?Vk([{kind:"all",count:this.allCount(t)},...t]):[];let r=t.length>0?this.rows.indexOf(t[zk(t)]):0;if(e==="first")this.cursor=r;else if(e==="keep"){let i=n?.kind==="palette"?n.entry.name:"",o=i?this.rows.findIndex((s)=>s.kind==="palette"&&s.entry.name===i):-1;this.cursor=o===-1?r:o}else if(this.cursor>=this.rows.length)this.cursor=Math.max(0,this.rows.length-1);this.sync()}allCount(e){return this.scope==="series"?e.length:this.everyone(e).length}move(e){let n=this.cursor+e;if(this.rows[n]?.kind==="rule")n+=e;if(n>=0&&n<this.rows.length)this.cursor=n;this.sync()}toggle(e){if(this.expanded.has(e))this.expanded.delete(e);else this.expanded.add(e);this.rebuild("clamp")}fold(e){if(this.userInput||this.scope==="series")return;let n=this.rows[this.cursor];if(n?.kind==="group"){if(e!==n.expanded)this.toggle(n.name)}else if(n?.kind==="palette"&&!e&&!n.entry.default){let t=n.entry.group;if(this.expanded.delete(t),this.rebuild("clamp"),this.cursor=this.rows.findIndex((r)=>r.kind==="group"&&r.name===t),this.cursor===-1)this.cursor=0;this.sync()}}renderRow(e,n){if(e.kind==="rule")return` ${this.color?`${uc}${"── markets ──────────"}${Ti}`:"── markets ──────────"}`;let t=e.kind==="palette"?e.entry:e.kind==="group"?e.lead:void 0,r=this.color&&n&&t!==void 0,i=(d)=>this.color?`${uc}${d}${cc}`:d,o=(d)=>this.color?`${pg}${d}${cc}`:d,s=(d)=>this.color?` ${mg(lo(d),r?Ai(d.foreground):"\x1B[39m")}`:"",u=n?r?`${Ai(t.cursor)}▌\x1B[39m `:"▌ ":" ",c=(d)=>r?`${u}${gg(t.selection,t.foreground)} ${d} ${Ti}`:`${u} ${d}`;if(e.kind==="all"){let d=this.everyone(this.rows).every((g)=>this.picked.has(g.name))?"●":"○";return c(`${d} select all ${i(`(${e.count})`)}`)}if(e.kind==="group"&&this.scope==="series"){let d=this.pickedIn(e.name)===e.count?"●":"○",g=`(${e.count})${e.native?` ${e.native}`:""}`;return c(`${d} ${o(e.name.padEnd(this.seriesPad))}${s(e.lead)}${this.color?" ":" "}${i(g)}`)}if(e.kind==="group"){let d=this.rows[this.cursor],g=d?.kind==="palette"&&d.entry.group===e.name?d.entry:void 0,p=this.color&&g?`${pg}${Ai(g.cursor)}${e.name}${cc}\x1B[39m`:o(e.name),k=e.native?` ${i(e.native)}`:"";return c(`${e.expanded?"▾":"▸"} ${p} ${i(`(${this.pickedIn(e.name)}/${e.count})`)}${k}`)}let a=e.entry,h=this.picked.has(a.name)?"●":"○",f=this.color?a.name.padEnd(this.namePad):a.name,l=n?o(f):f;return c(` ${h} ${l}${s(a)}`)}draw(){let e=(p)=>this.color?`${uc}${p}${Ti}`:p,n=(p)=>this.color?`${Bk}${p}${Ti}`:p,t=this.scope==="series"?"series":"catalog";if(this.state==="submit")return`${e("◇")} ${t} ${e(`· ${this.pickedCount()} picked`)}`;if(this.state==="cancel")return`${e(`◇ ${t} · cancelled`)}`;let r=this.userInput.trim(),i=this.scope==="series"?this.series.length:this.named.length,o=this.scope==="series"?this.rows.filter((p)=>p.kind==="group").length:r?this.named.filter((p)=>cs(p,r)).length:i,s=`${n("◆")} ${t} ${e(`(${o}/${i} · ${this.pickedCount()} picked)`)}`,u=`${n("│")} ${this.userInput?`${this.userInput}_`:e(`search…${this.example?` e.g. ${this.animatedExample()}`:""}`)}`;if(this.cursor<this.top)this.top=this.cursor;if(this.cursor>=this.top+this.maxItems)this.top=this.cursor-this.maxItems+1;this.top=Math.min(this.top,Math.max(0,this.rows.length-this.maxItems));let c=this.rows.slice(this.top,this.top+this.maxItems),a=c.length>0?c.map((p,k)=>`${n("│")} ${this.renderRow(p,this.top+k===this.cursor)}`):[`${n("│")} ${e(`no ${this.scope==="series"?"series":"palettes"} match '${this.userInput}'`)}`];while(a.length<this.maxItems)a.push(n("│"));let h=this.rows.length-this.top-c.length,f=h>0?`${n("│")} ${e(`↓ ${h} more`)}`:n("│"),l=this.scope==="series"?"":" · ←→ fold",d=this.scope==="series"?"continue":"install",g=this.state==="error"?`${n("└")} ${this.color?`${Dk}${this.error}${Ti}`:this.error}`:`${n("└")} ${e(`↑↓ move${l} · space pick · type to filter · enter ${d} · esc cancel`)}`;return[s,u,...a,f,g].join(`
519
- `)}}function hc(e){console.log(`
520
- ${e} palettes installed — open a new tab, or reload your terminal config`)}async function bg(e){let n=de(),t=He(n),r=[...new Set(e.map((c)=>c.startsWith(ut)?ud(n,c,t):c))],i=ke(n),o=r.filter((c)=>i.palettes.includes(c)),s=r.filter((c)=>!i.palettes.includes(c));if(s.length===0){nn(n,t,i),console.log(`already installed: ${o.join(", ")}`);return}let u={...i,palettes:[...i.palettes,...s]};ht(n,t,i,u);for(let c of s)console.log(` + ${c}`);await Gt(n,Ue(n,t,!1).palettes.filter((c)=>s.includes(c.name)),u.terminals),hc(u.palettes.length)}function kg(e){let n=de(),t=He(n),r=ke(n),i=e.filter((u)=>r.palettes.includes(u)),o=e.filter((u)=>!r.palettes.includes(u));if(i.length===0)throw Error(`not installed: ${o.join(", ")} — \`ttheme list\` marks what is`);let s={...r,palettes:r.palettes.filter((u)=>!i.includes(u))};ht(n,t,r,s),Ju(n,t,r.terminals,i);for(let u of i)console.log(` - ${u}`);if(hc(s.palettes.length),o.length>0)return console.error(`ttheme remove: not installed: ${o.join(", ")}`),1;return 0}function Eg(e){let n=de(),t=He(n),r=ke(n);if(!r.palettes.includes(e))throw Error(`${e} is not installed — \`ttheme add ${e}\` first`);let{off:i,...o}=r,s=_n(),u=Ei({...o,startup:e},s);nn(n,t,u),qn(n,u);let c=At(u,s);console.log(vg(e,u.terminals,c&&s.running()).join(`
521
- `))}function yg(){let e=de(),n=ke(e),t=Qn(n);if(!t)throw Error("no palettes installed — `ttheme browse` picks some");if(!n.off){console.log(`already on · ${t}`);return}let{off:r,...i}=n,o=ht(e,He(e),n,i);console.log(vg(t,i.terminals,o).join(`
522
- `))}function Sg(){let e=de(),n=ke(e);if(n.off){console.log("already off");return}let t=ht(e,He(e),n,{...n,off:!0}),r=Qn(n);if(console.log(`off · new tabs open in the terminal's own colors${r?` — \`ttheme on\` wears ${r} again`:""}`),t)console.log("iterm2 new tabs open on your own profile once iTerm2 restarts")}function vg(e,n,t){let r=n.filter((o)=>o!=="iterm2"),i=r.length>0?[`default ${e} · ${r.join(", ")} open new tabs with it once their config reloads`]:[];if(n.includes("iterm2"))i.push(t?'iterm2 new tabs open with it once iTerm2 restarts — "ttheme · default" is now its default profile':'iterm2 new tabs open with it — "ttheme · default" is its default profile');return i.length>0?i:[`default ${e} · no terminal is wired to open with it — \`ttheme init\` wires one`]}function Mg(e,n){let t=new Map(n.palettes.map((r)=>[r.name,"market"]));for(let r of Po(e,n.palettes,!1))t.set(r.name,"mine");return t}function Ig(e,n=!1){let t=de(),r=He(t),i=new Set(ke(t).palettes),o=Mg(t,r),s=an(Ue(t,r).palettes),u=_r(e?bl(s,e):s),c=(f)=>o.get(f)??"kept";if(n){let f=u.map((l)=>({name:l.name,group:l.group,installed:i.has(l.name),source:c(l.name)}));console.log(JSON.stringify(f,null,2));return}let a=Math.max(...u.map((f)=>f.name.length),0),h={market:"",mine:" · yours",kept:" · in no market you added"};for(let f of u)console.log(` ${i.has(f.name)?"●":"○"} ${f.name.padEnd(a)} ${f.group}${h[c(f.name)]}`);if(process.stdout.isTTY){let f=e?`${u.length} of ${s.length}`:`${s.length}`;console.log(`
523
- ${f} palettes — ${u.filter((l)=>i.has(l.name)).length} installed`)}}async function Ng(){let e=de(),n=or(e);if(n.length===0)console.log("no markets to update — `ttheme market add official` brings the ttheme catalog back");for(let u of n)try{console.log(` ${await Dl(e,u)}`)}catch(c){let a=$n(u);console.log(` ${a}: ${c.message} — kept the copy from the last update`)}if(!xk(ir(e)))return;let t=He(e),r=ke(e),i=Mg(e,t),o=r.palettes.filter((u)=>!i.has(u)),s=new Map(bi(e).map((u)=>[u.name,u.pictures]));nn(e,t,r);for(let u of o)console.log(` ${u} left its market — ttheme keeps the copy you have`);await Gt(e,Ue(e,t,!1).palettes.filter((u)=>r.palettes.includes(u.name)&&s.has(u.name)).map((u)=>Zo(u,s.get(u.name))),r.terminals)}async function as(e,n,t,r=!1){let i=process.env.TTHEME_SORT==="series"?e.palettes:_r(e.palettes),o=process.stdout.isTTY===!0&&!Li(),s=o?await dg():new Map,u=new ac({entries:i,scope:t,installed:n,required:r,color:!Li(),fx:$g(process.env.TTHEME_FX),onFocus:o?(a)=>process.stdout.write(us(a)):void 0}),c=await u.prompt();if(process.stdout.write(lg(s)),en(c))return;return e.palettes.filter((a)=>u.picked.has(a.name)).map((a)=>a.name)}async function Og(){let e=de(),n=He(e),t=ke(e),r=await as(Ue(e,n),t.palettes,"palette");if(!r){console.log("nothing changed");return}let i=t.palettes.filter((u)=>!r.includes(u)),o=r.filter((u)=>!t.palettes.includes(u));if(o.length===0&&i.length===0){console.log("nothing changed");return}let s={...t,palettes:r};ht(e,n,t,s),Ju(e,n,t.terminals,i);for(let u of o)console.log(` + ${u}`);for(let u of i)console.log(` - ${u}`);await Gt(e,Ue(e,n,!1).palettes.filter((u)=>o.includes(u.name)),s.terminals),hc(s.palettes.length)}function s1(e,n,t){for(let r of r1(n))e.push({from:ye(n,r),to:ye(t,r)})}function Hg(e){return JSON.parse(wr(ye(e,"dist","manifest.json"),"utf8"))}function lc(e,n){let t=ye(n.configHome,"ttheme"),r=[{from:ye(n.root,"bin","ttheme.js"),to:ye(t,"ttheme.js")},{from:ye(n.root,"bin","ttheme.js.map"),to:ye(t,"ttheme.js.map")},{from:ye(n.root,"shell","ttheme.zsh"),to:ye(t,"ttheme.zsh")},{from:ye(n.root,"shell","launch-tab.zsh"),to:ye(t,"launch-tab.zsh"),executable:!0}];s1(r,ye(n.root,"shell","adapters"),ye(t,"adapters"));let i=[{file:ye(n.zdotdir,".zshrc"),block:of(t)}],o=ye(t,"config.zsh"),s=af(rn(o)?wr(o,"utf8"):""),u={file:o,content:s},c=[];if(e.terminals.includes("alacritty")){let f=Tt(n.configHome);if(rn(f)&&si(wr(f,"utf8"),void 0)===void 0)c.push(`${f} already imports files under [general] — ttheme left it alone; add ${ye(n.configHome,"alacritty","themes")}/<palette>.toml to that import list yourself`)}if(e.terminals.includes("wezterm")){let f=hr(n.configHome,n.home);if(rn(f)&&ui(wr(f,"utf8"),"")===void 0)c.push(`${f} has no \`return config\` line — ttheme left it alone; call \`dofile("${ye(t,"wezterm.lua")}")(config)\` from it yourself`)}let a=e.terminals.includes("windows-terminal");if(a&&!n.wtHome)c.push("windows terminal: %LOCALAPPDATA% was not found — drop the release fragment into its Fragments folder yourself");if(e.terminals.includes("warp"))c.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 h={terminals:e.terminals,palettes:e.palettes,...a&&n.wtHome?{wtHome:n.wtHome}:{},...a&&n.wtProfile?{wtProfile:n.wtProfile}:{},...e.off?{off:!0}:{}};return c.push(...Al(n.configHome,e.terminals,n.home)),{home:n.home,copies:r,edits:i,settings:u,catalog:Hg(n.root),installed:h,notes:c}}function u1(e){try{return ke(e)}catch{return}}function c1(e){try{return Ue(e,He(e),!1).palettes}catch{return[]}}function a1(e,n){let t=lc({terminals:e.terminals,palettes:e.palettes,off:e.off},n),r=new Set([...t.catalog.palettes,...c1(n.configHome)].map((h)=>h.name)),i=e.palettes.filter((h)=>r.has(h)),o=e.palettes.filter((h)=>!r.has(h)),{startup:s,...u}=e,c={...u,palettes:i,...s&&i.includes(s)?{startup:s}:{}},a=o.length>0?[`dropped ${o.join(", ")} — no longer in the catalog`,...t.notes]:t.notes;return{...t,installed:c,notes:a}}function h1(e){try{return Pg(process.execPath,[ye(e,"ttheme","ttheme.js"),"--version"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function Lg(e){let n=kn(e);return[e.terminals.join(", "),`${e.palettes.length} palettes`,n?`default ${n}`:"no default — ttheme is off"].join(" · ")}function f1(e){try{return ke(e).itermBase}catch{return}}function dc(e,n=_n()){for(let o of e.copies)if(fc(pr(o.to),{recursive:!0}),Rg(o.to,{force:!0}),Rg(`${o.to}.zwc`,{force:!0}),t1(o.from,o.to),o.executable)n1(o.to,493);fc(pr(e.settings.file),{recursive:!0}),i1(e.settings.file,e.settings.content);let t=pr(pr(e.settings.file)),r=f1(t),i=Ei(r?{...e.installed,itermBase:r}:e.installed,n);if(Cn(i.markets).includes(Ge))wi(t,e.catalog);qn(t,i),nn(t,He(t),i,e.home);for(let o of e.edits){fc(pr(o.file),{recursive:!0});let s=rn(o.file)?wr(o.file,"utf8"):"";Xr(o.file,ri(s,o.block))}return At(i,n)}class ft extends Error{}function hs(e){if(en(e))throw rr("nothing changed"),new ft;return e}function Ag(e){return go.filter((n)=>{if(n==="iterm2")return process.platform==="darwin";if(n==="windows-terminal")return e.wtHome!==void 0;return n!=="warp"||process.platform!=="win32"})}function l1(e,n){if(e==="iterm2")return rn(ye(n.home,"Library","Application Support","iTerm2"));if(e==="windows-terminal")return n.wtHome!==void 0;if(e==="warp")return rn(pr(Uo(n.home)));if(e==="wezterm")return rn(ye(n.configHome,"wezterm"))||rn(ye(n.home,".wezterm.lua"));return rn(ye(n.configHome,e))}function d1(){if(process.platform==="win32")return process.env.LOCALAPPDATA;if(!process.env.WSL_DISTRO_NAME)return;let e=(n,t)=>Pg(n,t,{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 g1(e,n,t){return hs(await rl({message:"wire which terminals?",options:Ag(t).map((r)=>({value:r,hint:r===e?"detected":void 0})),initialValues:n,required:!0}))}function gc(e){let n=[...e.copies.filter((t)=>!rn(t.to)).map((t)=>t.to),...rn(e.settings.file)?[]:[e.settings.file],...e.edits.filter((t)=>!wr(t.file,"utf8").includes("# ttheme begin")).map((t)=>t.file)];if(n.length>0)throw Error(`init left gaps:
516
+ }`;async function tg(){if(bc())return;if(process.platform==="darwin"){let[e="",n=""]=(await Hn("osascript",["-l","JavaScript","-e",Hk])).stdout.trim().split("\t");return{stamp:e,picture:n==="picture"}}if(process.platform==="linux"&&!eg()){let n=Boolean(process.env.WAYLAND_DISPLAY)?(await Hn("wl-paste",["--list-types"])).stdout:(await Hn("xclip",["-selection","clipboard","-t","TARGETS","-o"])).stdout;return{stamp:n,picture:/^image\//m.test(n)}}return}function rg(e){let n=[],t="",r=0;while(r<e.length){if(e[r]!=="\x1B"){t+=e[r],r++;continue}if(e.startsWith("\x1B[200~",r)){let o=e.indexOf("\x1B[201~",r+6);if(o===-1)return{events:n,keys:t,pending:e.slice(r)};n.push({kind:"paste",text:e.slice(r+6,o)}),r=o+6;continue}if(e.startsWith("\x1B]5522;",r)||e.startsWith("\x1B]72;",r)){let o=[e.indexOf("\x1B\\",r),e.indexOf("\x07",r)].filter((h)=>h!==-1);if(o.length===0)return{events:n,keys:t,pending:e.slice(r)};let s=Math.min(...o),u=e.slice(r+2,s),[c="",a="",...f]=u.split(";");n.push({kind:"osc",code:c,meta:Lk(a),payload:f.join(";")}),r=s+(e[s]==="\x07"?1:2);continue}let i=/^\[\?([\d;]*)(\$y|c)/.exec(e.slice(r+1,r+64));if(i){if(i[2]==="c")n.push({kind:"attributes"});else{let[o="0",s="0"]=(i[1]??"").split(";");n.push({kind:"mode",mode:Number(o),value:Number(s)})}r+=1+i[0].length;continue}if(/^(?:\[(?:\?[\d;$]*|2|20|200|201)?|\](?:5|55|552|5522|7|72)?)$/.test(e.slice(r+1)))return{events:n,keys:t,pending:e.slice(r)};t+=e[r],r++}return{events:n,keys:t,pending:""}}function Lk(e){let n={};for(let t of e.split(":")){let r=t.indexOf("=");if(r>0)n[t.slice(0,r)]=t.slice(r+1)}return n}var ji=(e)=>Buffer.from(e).toString("base64"),mc=(e)=>Buffer.from(e,"base64");function Yd(e,n){return n.find((t)=>e.includes(t))}class $c{clipboard=!1;drops=!1;reading;offered=[];dropping;pw=ji(Zd("sha1").update(`${process.pid}:${Date.now()}`).digest("hex"));send;deliver;constructor(e,n){this.send=e,this.deliver=n}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=${ji("ttheme")}:pw=${this.pw};${ji(".")}\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,n){if(e.type!=="read")return;let t=e.status??"";if(t==="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(t==="DATA"){if(r.mime=e.mime?mc(e.mime).toString("utf8"):r.mime,n)r.chunks.push(mc(n));return}if(this.reading=void 0,t!=="DONE"){this.deliver({kind:"error",message:t==="EPERM"?"the clipboard read was not allowed":`the terminal answered ${t}`});return}let i=Buffer.concat(r.chunks);if(r.listing){let o=i.toString("utf8").split(/\s+/).filter(Boolean),s=Yd(o,[...pc,...Ik]);if(!s){this.deliver({kind:"text",text:""});return}let u=r.pw||this.pw,c=r.pw?"Paste event":"ttheme";this.reading={mime:s,chunks:[],pw:u,listing:!1},this.send(`\x1B]5522;type=read:name=${ji(c)}:pw=${u};${ji(s)}\x1B\\`);return}this.deliver(r.mime.startsWith("image/")?{kind:"bytes",bytes:new Uint8Array(i),source:"clipboard"}:{kind:"text",text:i.toString("utf8")})}drop(e,n){let t=e.t??"";if(t==="m"){if(e.x==="-1"){this.offered=[];return}if(n){this.offered=n.split(" ").filter(Boolean);let u=gc.filter((c)=>this.offered.includes(c));this.send(`\x1B]72;t=m:o=${u.length>0?1:0};${u.join(" ")}\x1B\\`)}return}if(t==="M"){let u=n?n.split(" ").filter(Boolean):this.offered,c=Yd(u,gc);if(!c){this.send("\x1B]72;t=r:o=0\x1B\\");return}this.dropping={mimes:u,index:u.indexOf(c)+1,chunks:[]},this.send(`\x1B]72;t=r:x=${this.dropping.index}\x1B\\`);return}let r=this.dropping;if(!r)return;if(t==="R"){this.dropping=void 0,this.send("\x1B]72;t=r:o=0\x1B\\"),this.deliver({kind:"error",message:`the drop failed: ${n.split(":")[0]||"unknown error"}`});return}if(t!=="r"&&t!=="")return;if(n)r.chunks.push(mc(n));if(e.m==="1"||n)return;this.dropping=void 0;let i=Buffer.concat(r.chunks),o=r.mimes[r.index-1]??"",s;if(o.startsWith("image/"))s={kind:"bytes",bytes:new Uint8Array(i),source:"drop"};else{let u=i.toString("utf8"),c=o==="text/uri-list"?ls(u).find((a)=>bk(a)):void 0;s=c?{kind:"bytes",bytes:new Uint8Array(hs(c)),source:c}:{kind:"text",text:u}}this.send("\x1B]72;t=r:o=1\x1B\\"),this.deliver(s)}}var Be={pitch:25,cols:22,rows:9,height:13},Kt={cols:25,rows:16},Tk=2147483648,Gk=-1073741826,Uk=1600,jk="\x1B[0m",Tn="\x1B[1m",pe="\x1B[2m",Ci="\x1B[31m",Ln="\x1B[32m",rn="\x1B[33m",gs="\x1B[1;34m",Ck="\x1B[35m",Jk={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 sg(e){let n=[],t=0;while(t<e.length){let r=e[t]??"";if(r==="\x1B"){let i=/^(?:\[([0-9;]*)([A-Za-z~])|O([A-Za-z]))/.exec(e.slice(t+1));if(i){n.push(Jk[`${i[1]??""}${i[2]??i[3]??""}`]??"nop"),t+=1+i[0].length;continue}let o=e[t+1]??"";if(/^[a-z]$/.test(o)){n.push(`alt-${o}`),t+=2;continue}n.push("esc"),t++;continue}n.push(r==="\r"||r===`
517
+ `?"enter":r==="\t"?"tab":r==="\x03"?"ctrl-c":r==="\x16"?"ctrl-v":r===""||r==="\b"?"backspace":r),t++}return n}var ug="\x1B]1337;ReportCellSize\x07\x1B[16t",ig="\x1B]1337;ReportCellSize=";function Ec(e){let n=e.indexOf(ig);if(n!==-1){let i=e.slice(n+ig.length),o=[i.indexOf("\x07"),i.indexOf("\x1B\\")].filter((c)=>c!==-1),s=o.length>0?Math.min(...o):-1,u=s===-1?null:/^([\d.]+);([\d.]+);([\d.]+)$/.exec(i.slice(0,s));if(u){let c=Number(u[3]);return{cell:{h:Math.round(Number(u[1])*c),w:Math.round(Number(u[2])*c)},rest:e.slice(0,n)+i.slice(s+(i[s]==="\x07"?1:2))}}}let t=e.indexOf("\x1B[6;"),r=t===-1?null:/^\[6;(\d+);(\d+)t/.exec(e.slice(t+1));if(!r)return null;return{cell:{h:Number(r[1]),w:Number(r[2])},rest:e.slice(0,t)+e.slice(t+1+r[0].length)}}function Mr(e,n){return{perRow:Math.max(1,Math.floor((e+1)/Be.pitch)),rowsVis:Math.max(1,Math.floor((n-4)/Be.height))}}function cg(e){return`\x1B_Ga=t,t=f,f=100,i=${e.id},q=2;${Buffer.from(e.path).toString("base64")}\x1B\\`}function ag(e){return`\x1B[${e.row+1};${e.col+1}H\x1B_Ga=p,i=${e.id},p=${e.id},c=${e.cols},r=${e.rows},C=1,z=${e.z},q=2\x1B\\`}function fg(e){return`\x1B_Ga=d,d=I,i=${e},q=2\x1B\\`}function hg(e){return`\x1B[38;2;${Je(e).join(";")}m`}function kc(e){return`\x1B[48;2;${Je(e).join(";")}m`}function dn(e){return Array.from(e).length}class ms{parts=[];cols;constructor(e){this.cols=e}put(e,n,t=""){return this.parts.push({col:e,text:n,sgr:t}),e+dn(n)}run(e,n){let t=e;for(let[r,i]of n)t=this.put(t,r,i);return t}right(e,n){this.run(e-n.reduce((t,[r])=>t+dn(r),0),n)}render(){let e="";for(let{col:n,text:t,sgr:r}of this.parts){if(n>=this.cols||n<0)continue;let i=Array.from(t).slice(0,this.cols-n).join("");e+=`\x1B[${n+1}G${r}${i}${r?jk:""}`}return e}}function lg(e){return e>=1e6?`${(e/1e6).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1000))} KB`}function _k(e,n){if(!n)return lg(e);return n>=1e6?`${(e/1e6).toFixed(1)}/${(n/1e6).toFixed(1)} MB`:`${Math.round(e/1000)}/${Math.round(n/1000)} KB`}function dg(e){return e.replace(/_\([^)]*\)?$/,"")}function gg(e){return[`${e.reduced?"↓":""}${e.width}×${e.height}`,Math.max(e.width,e.height)<Uk?rn:pe]}function Ji(e,n,t,r){let i=[...r.keys??[]],o=r.lead,s=r.right,u=()=>{let f=[...o?[dn(o[0])]:[],...i.map(([l,d])=>dn(l)+1+dn(d))];return(r.badge?dn(r.badge)+4:0)+f.reduce((l,d)=>l+d,0)+3*Math.max(0,f.length-1)+(s?3+dn(s[0])+1+dn(s[1]):0)};while(u()>n)if(i.length>2)i.splice(-2,1);else if(s)s=void 0;else if(i.length>1)i.splice(-2,1);else break;if(o&&u()>n){let f=Math.max(0,dn(o[0])-(u()-n)-1);o=[`${Array.from(o[0]).slice(0,f).join("")}…`,o[1]]}let c=0;if(r.badge)c=e.put(0,` ${r.badge} `,`\x1B[7;1m${t}`)+2;if([...o?[[o]]:[],...i.map(([f,h])=>[[f,Tn],[` ${h}`,pe]])].forEach((f,h)=>{c=e.run(c+(h?3:0),f)}),s)e.right(n,[[s[0],Tn],[` ${s[1]}`,pe]])}function Wk(e,n,t,r,i,o){let{ansi:s,selection:u,cursor:c}=o.colors,a=r<44?3:4;if(r>=56)a=Math.min(7,Math.floor((r+1)/8)-1);let f=t;for(let g=0;g<8;g++)f=(e[n]?.put(f,"▀".repeat(a),hg(s[g]??c)+kc(s[g+8]??c))??f)+1;let h=["❯ ",Ln],l=[[["~/code/demo",gs],[" on ",pe],["main",Ck],[" +2",Ln],[" ~1",rn]]];if(l.push([h,["git status -sb",""]]),r>=44)l.push([["## ",""],["main",Ln],["...",""],["origin/main",Ci],[" [ahead 1]",rn]]);if(l.push([[" M",Ci],[" src/main.rs",""]]),l.push([["??",Ci],[" notes.md",""]]),l.push([]),r>=44)l.push([h,["ls",""]]),l.push([["docs",gs],[" ",""],["src",gs],[" ",""],["tests",gs],[" Cargo.toml README.md",""]]),l.push([]);l.push([h,["cargo test",""]]),l.push([[" ✓",Ln],[" parses config",""]]);let d=[[" ✗",Ci],[" renders frame",""]];if(r>=44)d.push([" expected ",pe],["3",Ln],[", received ",pe],["2",Ci]);l.push(d),l.push([]),l.push([h,["echo ",""],["selected text",kc(u)],[" ",""],[" ",kc(c)]]),l.forEach((g,m)=>{let $=n+2+m;if($<=i)e[$]?.run(t,g)})}function Kk(e,n,t,r,i,o){e[n]?.put(t,`╭${"─".repeat(i-2)}╮`,o);for(let s=n+1;s<n+r-1;s++)e[s]?.put(t,"│",o),e[s]?.put(t+i-1,"│",o);e[n+r-1]?.put(t,`╰${"─".repeat(i-2)}╯`,o)}function yc(e,n=e.site,t=e.siteAnsi){return[` ${n} `,`\x1B[7;${30+t}m`]}function qk(e){return`${x[Math.floor(e/Cn)]?.name??"local"} ${e%Cn}`}function Qk(e,n,t){let r=[{name:"all",moved:!1},...x].flatMap((s,u)=>{let c=`${s.name}${s.moved?"*":""}`,a=s.name===t.site?yc(t,c):[` ${c} `,pe];return u?[[" ",""],a]:[a]}),i=r.reduce((s,[u])=>s+dn(u),0)<=n,o=e.run(0,i?r:[yc(t)]);if(t.asking!==void 0)e.run(o,[[` ${t.asking} was cut off — this network may block it. turn on the unblock proxy? `,rn],["y",Tn],[" turn on ",pe],["n",Tn],[" not now",pe]])}function Yk(e,n,t,r){if(t.editing!==void 0){let u=e.run(0,[["⌕ ",r],[t.editing,""],["█",r]]),c=t.suggest?.length?" ↑↓ pick enter searches":" enter searches";e.put(u,t.editing?c:` a tag, a post url or an id, or drop a picture or ctrl+v — ${t.tag||"esc leaves"}`,pe);return}let i=e.run(0,[["⌕ ",r],[t.tag||"nothing yet — / searches, ctrl+v pastes a picture",t.tag?"":pe]]),o=Et.filter((u)=>!t.block.includes(u)),s=[t.preset,...t.solo?["solo"]:[],t.order,...t.rating.join("+")==="safe"?[]:[t.rating.join("+")],...o.length>0?[`allows ${o.join("+")}`]:[],...t.unblocked?["unblock"]:[]];if(e.put(i,` ${s.join(" ")}`,pe),t.total>0||!t.searching){let u=[[`${t.tiles.length}/${t.checked}`,""]];if(t.checked<t.total)u.push([` of ${t.total}`,pe]);e.right(n,u)}}function Zk(e){if(e.cut==="on")return[[`cut out · ${e.clear}% transparent`,Ln]];if(e.cut==="off")return[["opaque · x cuts out",rn]];if(e.cut==="failed")return[["opaque · no cut-out",rn]];return[e.clear>0?[`${e.clear}% transparent`,Ln]:["opaque",rn]]}function og(e){return e.site==="all"?"any site":e.site}function mg(e){if(e.installing!==void 0)return[`installing ${e.palette} ← ${qk(e.installing)}`,rn];if(e.hint)return[e.hint,Ln];if(e.error)return[e.error,rn];if(e.waiting!==void 0)return[`${e.slow??e.site} asked to slow down · ${e.waiting}s`,rn];if(e.fetching)return[`fetching ${e.fetching.id%Cn} · ${_k(e.fetching.got,e.fetching.size)}`,rn];if(e.cutting!==void 0)return[`cutting out ${e.cutting%Cn}`,rn];if(e.preparing!==void 0)return[`preparing ${e.preparing%Cn}`,rn];if(e.saved)return[e.saved,Ln];if(e.note)return[e.note,pe];return}function Xk(e,n,t,r,i,o){let{perRow:s,rowsVis:u}=Mr(t,r);Yk(e[0],t,i,o),Qk(e[1],t,i);for(let d=0;d<s*u;d++){let g=i.top*s+d,m=i.tiles[g];if(!m)break;let $=2+Math.floor(d/s)*Be.height,S=d%s*Be.pitch,v=g===i.focus;if(v)Kk(e,$,S,Be.height,Be.pitch-1,o);if(m.thumb)n.push({id:m.key,path:m.thumb,row:$+1,col:S+1,cols:Be.cols,rows:Be.rows,z:-1});if(e[$+10]?.run(S+1,[...i.installed.includes(m.key)?[["✓ ",Ln]]:[],...i.site==="all"?[["● ",`\x1B[${30+m.siteAnsi}m`]]:[],[String(m.id),v?Tn:""],[" ",""],gg(m)]),m.mates.length>0)e[$+10]?.put(S+Be.cols,"≈",o);let k=m.artist?dg(m.artist):m.owner&&`@${m.owner}`;if(k)e[$+11]?.put(S+1,k.slice(0,Be.cols-8),pe);let M=[];if(m.score>0)M.push([`★${m.score}`,pe]);if(m.variants>1)M.push([` ×${m.variants}`,o]);if(M.length>0)e[$+11]?.right(S+Be.cols+1,M)}let c=i.top*s,a=i.tiles.length-(i.top+u)*s,f=[...c>0?[`↑ ${c} above`]:[],...a>0?[`↓ ${a} more`]:[]];if(f.length>0)e[r-2]?.put(0,f.join(" "),pe);if(!i.searching&&i.tiles.length===0&&!i.error)e[3]?.put(0,i.preset==="cutouts"?`no transparent cutouts of ${i.tag} on ${og(i)} — c searches every post, tab tries ${i.nextSite}`:`no posts of ${i.tag} on ${og(i)} — tab tries ${i.nextSite}`,pe);let h=e[r-1],l=mg(i);if(i.searching&&i.tiles.length===0&&!l){Ji(h,t,o,{badge:"FIND",lead:[i.preset==="cutouts"?"checking png headers":"fetching posts",pe],right:["esc","back"]});return}Ji(h,t,o,{badge:"FIND",lead:l,keys:i.asking!==void 0?[]:[["←↑↓→","move"],["enter","try on"],["tab","site"],["ctrl+v","picture"],["s","settings"],["/","search"],["?","keys"]],right:i.asking!==void 0?void 0:["esc","back"]})}function zk(e,n,t,r,i,o){let s=i.tiles[i.focus];if(!s)return;let u=i.shown?.id===s.key?i.shown:void 0,c=[yc(i,s.site,s.siteAnsi),[" ",""],[String(s.id),Tn],[" ",""],gg(s)];if(s.artist)c.push([` · ${dg(s.artist)}`,""]);if(s.score>0)c.push([` · ★${s.score}`,pe]);if(u)c.push([` · ${lg(u.bytes)}`,pe]);if(s.owner)c.push([` · ${s.owner}`,pe]);if(s.origin)c.push([` · ${s.origin}`,pe]);if(u)c.push([" ",""],...Zk(u));if(e[0]?.run(0,c),s.mates.length>0)e[0]?.right(t,[["≈ ",o],[s.mates.join(" "),pe]]);if(Wk(e,3,2,t-4,r-2,i),i.shown)n.push({id:Tk+i.shown.id,path:i.shown.path,row:0,col:0,cols:t,rows:r,z:Gk});let a=mg(i);Ji(e[r-1],t,o,{badge:"TRY",lead:a,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 Vk={grid:[["move","←↑↓→ home end pgup pgdn"],["try on","enter"],["site",`tab all, ${x.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"],["back","esc returns to preview"],["close","? esc"]],try:[["browse","←→"],["install","enter"],["cut out","x the background off or on, on an opaque picture"],["open","o the post page in a browser"],["your own","ctrl+v or v a picture from the clipboard · drop one on the window"],["grid","esc"],["close","? esc"]]};function Bk(e,n,t,r,i){let o=r.panel??0,s=Math.max(...r.settings.map((l)=>l.label.length)),u=Math.max(...r.settings.map((l)=>l.choices.reduce((d,g)=>d+g.length+(l.multi?6:3),0))),c=Math.min(n-2,Math.max(28,s+u+8)),a=r.settings.length+4,f=Math.floor((n-c)/2),h=Math.max(2,Math.floor((t-a)/2));e[h]?.put(f,`╭─ settings ${"─".repeat(Math.max(0,c-13))}╮`);for(let l=h+1;l<h+a-1;l++)e[l]?.put(f,`│${" ".repeat(c-2)}│`);r.settings.forEach((l,d)=>{let g=e[h+2+d];g.put(f+3,l.label,d===o?Tn:pe);let m=f+5+s,$=l.value.split(" ");l.choices.forEach((S,v)=>{let k=$.includes(S),M=l.multi&&d===o&&v===l.cursor?"4;":"",p=l.multi?` ${k?"[x]":"[ ]"} ${S} `:` ${S} `;m=g.put(m,p,k?`\x1B[${M}7;${30+r.siteAnsi}m`:M?`\x1B[4m${pe}`:pe)+1})}),e[h+a-1]?.put(f,`╰${"─".repeat(c-2)}╯`),Ji(e[t-1],n,i,{badge:"SET",keys:[["↑↓","setting"],["←→","value"],["space","toggle"],["enter","save"]],right:["esc","undo"]})}function Dk(e,n,t,r,i){let o=Vk[r.mode],s=Math.min(n-2,50),u=o.length+4,c=Math.floor((n-s)/2),a=Math.max(2,Math.floor((t-u)/2));e[a]?.put(c,`╭─ keys ${"─".repeat(s-9)}╮`);for(let f=a+1;f<a+u-1;f++)e[f]?.put(c,`│${" ".repeat(s-2)}│`);o.forEach(([f,h],l)=>{e[a+2+l]?.put(c+3,f,Tn),e[a+2+l]?.put(c+13,h.slice(0,s-16))}),e[a+u-1]?.put(c,`╰${"─".repeat(s-2)}╯`),Ji(e[t-1],n,i,{badge:"KEYS",right:["? esc","close"]})}function xk(e,n,t){let r=n.suggest??[],i=r.map((u)=>u.count>0?String(u.count):u.palette??"0"),o=Math.max(...r.map((u)=>dn(u.value))),s=Math.max(7,...i.map(dn));r.forEach((u,c)=>{let a=c===n.pick,f=e[1+c];f?.run(0,[[a?"▸ ":" ",t],[u.value,a?Tn+t:""]]),f?.right(2+o+2+s,[[i[c],pe]])})}function pg(e,n,t){let r=Array.from({length:t},()=>new ms(n)),i=[],o=hg(e.colors.cursor);if(n<Kt.cols||t<Kt.rows)return r[0]?.put(0,"ttheme find",Tn+o),r[1]?.put(0,`needs ${Kt.cols}×${Kt.rows} — now ${n}×${t}`),r[2]?.put(0,"esc quits",pe),{lines:r.map((s)=>s.render()),images:i};if(e.mode==="try")zk(r,i,n,t,e,o);else Xk(r,i,n,t,e,o);if(e.mode==="grid"&&e.editing!==void 0&&e.suggest?.length){for(let s=1;s<t-1;s++)r[s]=new ms(n);return xk(r,e,o),{lines:r.map((s)=>s.render()),images:[]}}if(e.help||e.panel!==void 0){let s=e.mode==="try"?i:[];for(let u=0;u<t;u++)r[u]=new ms(n);if(e.help)Dk(r,n,t,e,o);else Bk(r,n,t,e,o);return{lines:r.map((u)=>u.render()),images:s}}return{lines:r.map((s)=>s.render()),images:i}}var e1=new Set(["comic","4koma","monochrome","greyscale","sketch","lineart","speech_bubble"]),n1=new Set(["scenery","landscape","scenic","no_humans","wide_shot","very_wide_shot"]),t1=0.04,r1=0.1,i1=0.05,o1=4096;function s1(e){return new Set(e.cutouts.split(/\s+/).map((n)=>n.replace(/^~/,"")).filter(Boolean))}function u1(e,n,t,r=0){let{site:i,post:o}=e,s=new Set(o.tags),u=[...s1(i)].some((f)=>s.has(f)),c=Math.min(o.width,o.height),a=o.width>0&&o.height>0?o.width/o.height/(n.w/n.h):1;return(o.solo?2:0)+([...e1].some((f)=>s.has(f))?-3:0)+([...n1].some((f)=>s.has(f))?-1.5:0)+2*Math.min(1,c/n.h)+(u?1.5:-Math.min(1.5,Math.abs(Math.log(a))))+(t>0?1.5*Math.log1p(Math.max(0,o.score))/Math.log1p(t):0)+2*r}function ps(e,n,t=new Map){let r=new Map;for(let{site:i,post:o}of e)r.set(i,Math.max(r.get(i)??0,o.score));return e.map((i,o)=>({pick:i,at:o,score:u1(i,n,r.get(i.site)??0,t.get(i.post))})).sort((i,o)=>o.score-i.score||i.at-o.at).map(({pick:i})=>i)}function bg(e){let n=new Map;for(let r of e)n.set(r.site,[...n.get(r.site)??[],r]);let t=[];for(let r=0;t.length<e.length;r++)for(let i of n.values()){let o=i[r];if(o)t.push(o)}return t}function Sc(e){let n=e/255;return n<=0.04045?n/12.92:((n+0.055)/1.055)**2.4}function wg(e,n,t){let[r,i,o]=[Sc(e),Sc(n),Sc(t)],s=Math.cbrt(0.4122214708*r+0.5363325363*i+0.0514459929*o),u=Math.cbrt(0.2119034982*r+0.6806995451*i+0.1073969566*o),c=Math.cbrt(0.0883024619*r+0.2817188376*i+0.6299787005*o);return[0.2104542553*s+0.793617785*u-0.0040720468*c,1.9779984951*s-2.428592205*u+0.4505937099*c,0.0259040371*s+0.7827717662*u-0.808675766*c]}function $g(e,n){let t=n.map((s)=>wg(...Je(s))).filter(([,s,u])=>Math.hypot(s,u)>=t1);if(t.length===0)return 0;let r=Math.max(1,Math.floor(Math.sqrt(e.width*e.height/o1))),i=t.map(()=>0),o=0;for(let s=0;s<e.height;s+=r)for(let u=0;u<e.width;u+=r){let c=(s*e.width+u)*4;if(e.data[c+3]<128)continue;o++;let[a,f,h]=wg(e.data[c],e.data[c+1],e.data[c+2]);t.forEach(([l,d,g],m)=>{if(Math.hypot(a-l,f-d,h-g)<r1)i[m]=i[m]+1})}if(o===0)return 0;return i.reduce((s,u)=>s+Math.min(1,u/o/i1),0)/t.length}import{mkdirSync as Mg,readFileSync as vg,writeFileSync as Ig}from"node:fs";import{dirname as Ng}from"node:path";import{isMainThread as h1,parentPort as Og,Worker as l1}from"node:worker_threads";var c1=/(?:^|[^0-9a-f])([0-9a-f]{32})(?:[^0-9a-f]|$)/i,a1=[[/yande\.re\/post\/show\/(\d+)/,"yande"],[/konachan\.(?:com|net)\/post\/show\/(\d+)/,"konachan"],[/danbooru\.donmai\.us\/(?:posts|post\/show)\/(\d+)/,"danbooru"]];function Mc(e){let n=/(\d+)_p(\d+)/.exec(e.source);return[...e.md5?[`md5:${e.md5}`]:[],...n&&e.source.includes("pximg")?[`pixiv:${n[1]}_p${n[2]}`]:[]]}function kg(e,n){let t=c1.exec(n.source)?.[1]?.toLowerCase();return[`post:${e.key}:${n.id}`,...n.md5?[`md5:${n.md5}`]:[],...t&&t!==n.md5?[`md5:${t}`]:[],...a1.flatMap(([r,i])=>{let o=r.exec(n.source)?.[1];return o?[`post:${i}:${Number(o)}`]:[]}),...n.family?[`family:${e.key}:${n.family}`]:[]]}function yg(e,n){let t=e.owner||e.artist;return t!==""&&t===(n.owner||n.artist)&&e.width===n.width&&e.height===n.height}function Eg(e){let r=[];for(let o=0;o<8;o++){let s=Math.floor(o*e.height/8),u=Math.max(s+1,Math.floor((o+1)*e.height/8));for(let c=0;c<9;c++){let a=Math.floor(c*e.width/9),f=Math.max(a+1,Math.floor((c+1)*e.width/9)),h=0;for(let l=s;l<u;l++)for(let d=a;d<f;d++){let g=(l*e.width+d)*4,m=e.data[g+3]/255,$=0.299*e.data[g]+0.587*e.data[g+1]+0.114*e.data[g+2];h+=$*m+255*(1-m)}r.push(h/((f-a)*(u-s)))}}let i=0n;for(let o=0;o<8;o++)for(let s=0;s<8;s++)i=i<<1n|(r[o*9+s]>r[o*9+s+1]?1n:0n);return i.toString(16).padStart(16,"0")}function f1(e,n){let t=BigInt(`0x${e}`)^BigInt(`0x${n}`),r=0;while(t>0n)r+=Number(t&1n),t>>=1n;return r}function Sg(e,n){if(e.width<=0||e.height<=0||n.width<=0||n.height<=0)return!1;return Math.abs(Math.log(e.width/e.height/(n.width/n.height)))<0.01&&f1(e.hash,n.hash)<=2}var d1={thumb:"tile",match:"tile",show:"view",backdrop:"view",redraw:"view"};async function g1(e){if(e.job==="redraw")return Td(e.home,e.name,e.key,e.hue,e.blur,e.aligns,e.user);let n=$t(new Uint8Array(vg(e.from)),an);if(e.job==="backdrop")return Mo(e.home,e.colors,e.tone,n,{...e.origin,bytes:new Uint8Array(vg(e.source)),cut:e.from!==e.source},e,e.blur),0;if(e.job==="match")return{match:$g(n,e.colors),hash:Eg(n)};if(e.job==="thumb")return Mg(Ng(e.to),{recursive:!0}),Ig(e.to,Vs(yf(n,e.width,e.height))),0;let t=jn(n);return Mg(Ng(e.to),{recursive:!0}),Ig(e.to,Vs(Eh(n,e.colors,e.tone,e.width,e.height,e.blur))),t}function m1(e){e.on("message",async(n)=>{try{e.postMessage({id:n.id,value:await g1(n)})}catch(t){e.postMessage({id:n.id,error:t instanceof Error?t.message:String(t)})}})}class vc{worker;next=1;waiting=new Map;send(e){let n=this.next++;return new Promise((t,r)=>{let i=this.open();this.waiting.set(n,{ok:t,no:r}),i.ref(),i.postMessage({...e,id:n})})}close(){this.worker?.terminate(),this.worker=void 0,this.drop(Error("renderer closed"))}open(){if(this.worker)return this.worker;let e=new l1(import.meta.filename);e.unref(),e.on("message",({id:t,value:r,error:i})=>{let o=this.waiting.get(t);if(this.waiting.delete(t),this.waiting.size===0)e.unref();if(i!==void 0)o?.no(Error(i));else o?.ok(r)});let n=(t)=>{if(this.worker===e)this.worker=void 0;this.drop(t instanceof Error?t:Error("renderer stopped"))};return e.on("error",n),e.on("exit",()=>n(void 0)),this.worker=e,e}drop(e){for(let n of this.waiting.values())n.no(e);this.waiting.clear()}}class Ic{lines=new Map;run(e){let n=d1[e.job],t=this.lines.get(n);if(!t)t=new vc,this.lines.set(n,t);return t.send(e)}close(){for(let e of this.lines.values())e.close();this.lines.clear()}}class Nc{lines;constructor(e){this.lines=Array.from({length:Math.max(1,e)},()=>new vc)}async map(e){let n=[],t=0;return await Promise.all(this.lines.map(async(r)=>{while(t<e.length){let i=t++;try{n[i]=await r.send(e[i])}catch(o){n[i]=o instanceof Error?o:Error(String(o))}}})),n}close(){for(let e of this.lines)e.close()}}if(!h1&&Og)m1(Og);var Ir=[{name:"TTHEME_FIND_RATING",label:"rating",choices:Br,multi:{read:nr}},{name:"TTHEME_FIND_BLOCK",label:"block",choices:Et,multi:{read:tr,none:"none"}},{name:"TTHEME_FIND_POSTS",label:"posts",choices:["all","cutouts"]},{name:"TTHEME_FIND_SOLO",label:"solo",choices:["on","off"]},{name:"TTHEME_FIND_ORDER",label:"order",choices:["fit","newest","score"]},{name:"TTHEME_FIND_SETS",label:"sets",choices:["fold","show"]},...kr()?[{name:"TTHEME_FIND_REMOVE_BG",label:"remove bg",choices:["on","off"]}]:[]];function y1(e,n){if(e.multi)return e.multi.read(n).join(" ")||e.multi.none;return e.choices.find((t)=>t===n)??e.choices[0]}var E1=["fit","newest","score"];function Rg(e){return E1.find((n)=>n===e)??"fit"}function S1(e){return e.length>=2&&!/^\d+$/.test(e)&&!e.includes("://")&&!/^[\w.]+:\d+$/.test(e)}var Fg=12,M1=4,v1=150,Pg=12,I1=2,N1=150,O1=30,R1=4000,F1=8000,Ag=/\.(png|jpe?g|gif|webp|heic|tiff?|bmp)$/i,P1=process.platform==="win32"?"alt+v":"ctrl+v",Hg=process.platform==="darwin"?"ctrl+shift+cmd+4 copies a screenshot":"copy a picture first",A1=1280,Lg=2,H1=3,L1=8;function bs(e,n){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:n}}function Nr(e){if(!(e instanceof Error))return String(e);if(e instanceof AggregateError&&e.errors[0])return Nr(e.errors[0]);if(e.cause)return Nr(e.cause);let n=e.code;if(typeof n==="string")return n;let t=(e.message||e.name).split(".")[0]??"";return t.length>56?`${t.slice(0,55)}…`:t}function Rc(e,n){return`${e}: ${Nr(n)}`}function Tg(e){return e.width*e.height}function Gg(e){return`${e.id}-${Ug("sha1").update(e.preview).digest("hex").slice(0,8)}`}function T1(e){let n=e.lastIndexOf("\x1B");return n!==-1&&/^\[?[0-9;]*$/.test(e.slice(n+1))}function Fc(e,n){try{return JSON.parse(jg(Gn(bn(e),n),"utf8"))}catch{return{}}}function Pc(e,n,t){_i(bn(e),{recursive:!0}),Wi(Gn(bn(e),n),`${JSON.stringify(t)}
518
+ `)}class Cg{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(Ir.map((e)=>[e.name,y1(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 Ic;sent=new Map;placed=new Map;current;fetch;settle;partial;suggestTimer;suggesting;input="";typed="";grabber=new $c((e)=>this.write(e),(e)=>void this.got(e));featureWait;noticeTimer;peekTimer;peeked;attaching;probeWait;done;dirty=!1;unblock=!1;scratch=w1(Gn($1(),"ttheme-find-"));home;catalog;entry;blurring;constructor(e,n,t,r){this.home=e,this.catalog=n,this.entry=t,this.tone=cr(t,t.signatureSlots),this.blurring=fr(e),this.view={palette:t.name,tag:r,site:this.tabName,siteAnsi:this.tabAnsi,nextSite:this.nextTabName,preset:this.setting("TTHEME_FIND_POSTS")==="all"?"all":"cutouts",order:Rg(this.setting("TTHEME_FIND_ORDER")),solo:this.setting("TTHEME_FIND_SOLO")==="on",rating:nr(this.setting("TTHEME_FIND_RATING")),block:tr(this.setting("TTHEME_FIND_BLOCK")),sets:this.setting("TTHEME_FIND_SETS")==="show"?"show":"fold",unblocked:process.env.TTHEME_FIND_PROXY!==void 0,settings:Ir.map((i)=>({label:i.label,choices:[...i.choices],value:this.setting(i.name),multi:i.multi&&{none:i.multi.none},cursor:0})),colors:{cursor:t.cursor,selection:t.selection,ansi:t.ansi},tiles:[],installed:[],checked:0,total:0,searching:r!=="",focus:0,top:0,mode:"grid",help:!1,editing:r===""?"":void 0},this.board=bs(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:x[this.tab-1]}get sites(){return this.site?[this.site]:x}get tabName(){return this.site?.name??"all"}get tabAnsi(){return this.site?.ansi??M1}get nextTabName(){let e=(this.tab+1)%(x.length+1);return e===0?"all":x[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)}get boardKey(){return`${this.site?.key??"all"}|${this.view.preset}|${this.view.order}`}origPath(e,n,t){return Gn(bn(e),"orig",`${n}.${t}`)}previewPath(e){return Gn(bn(e.site),"thumb",`${Gg(e.post)}.${Dr(e.post.preview)}`)}tileOf(e,n){let{site:t,post:r}=e,i=In(t,r.id),o=St(r)??r;return{id:r.id,key:i,site:t.name,siteAnsi:t.ansi,width:o.width,height:o.height,reduced:o!==r,owner:r.owner,artist:t===ds?Bd(r.source):r.artist,score:r.score,variants:n,origin:tu(r.source),mates:this.owners.get(t.key)?.get(r.owner)??[],thumb:this.thumbPath.get(i)}}show(){let e=this.view,n=this.board;e.tiles=n.groups.flatMap((t)=>t.open?t.posts.map((r)=>this.tileOf(r,0)):[this.tileOf(t.posts[0],t.posts.length)]),e.checked=n.checked,e.total=n.total,e.searching=n.searching,e.note=n.note,e.focus=Math.max(0,Math.min(n.focus,e.tiles.length-1)),e.top=n.top}syncSite(){let e=this.view;e.site=this.tabName,e.siteAnsi=this.tabAnsi,e.nextSite=this.nextTabName}async run(){let{stdin:e,stdout:n}=process;e.setRawMode(!0),e.resume(),e.on("data",this.onData),n.on("resize",this.onResize),this.write("\x1B[?25l\x1B[?7l\x1B[H\x1B[K\x1B[2H\x1B[J\x1B[H");let t=new Promise((s)=>{this.done=s}),r=setInterval(this.onClock,250),i=await this.probe();if(i){if(this.cell=i,this.view.tag)this.search()}else this.view.searching=!1,this.view.error="this terminal does not report its cell size — find needs kitty graphics";await this.features(),this.grabber.start(),this.write("\x1B[?1004h"),this.peek(),this.draw();let o=await t;return this.grabber.stop(),this.write("\x1B[?1004l"),this.attaching?.abort(),clearTimeout(this.noticeTimer),clearTimeout(this.peekTimer),this.session.abort(),this.fetch?.abort(),clearTimeout(this.settle),clearTimeout(this.partial),this.quietSuggest(),clearInterval(r),e.off("data",this.onData),n.off("resize",this.onResize),this.write("\x1B_Ga=d,d=A,q=2\x1B\\\x1B[H\x1B[K\x1B[2H\x1B[J\x1B[H"),e.setRawMode(!1),e.pause(),this.saveProbes(),this.renders.close(),Oc(this.scratch,{recursive:!0,force:!0}),_f(),o}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 n=setTimeout(()=>{this.probeWait=void 0,e(null)},1000);this.probeWait=(t)=>{clearTimeout(n),this.probeWait=void 0,e(t)},this.write(ug)})}onData=(e)=>{this.input+=e.toString("utf8");for(let t=Ec(this.input);t;t=Ec(this.input))this.input=t.rest,this.probeWait?.(t.cell);if(this.probeWait)return;let n=rg(this.input);if(this.input=n.pending,this.view.editing===void 0&&n.keys.length>8&&/^(?:\/|~\/|file:|https?:)/.test(n.keys))this.pasted(n.keys),n.keys="";this.typed+=n.keys;for(let t of n.events)this.inbound(t);if(clearTimeout(this.partial),T1(this.typed)){this.partial=setTimeout(this.flushKeys,O1);return}this.flushKeys()};flushKeys=()=>{let e=sg(this.typed);this.typed="";for(let n of e)this.key(n)};features(){if(process.env.TMUX)return Promise.resolve();return new Promise((e)=>{let n=setTimeout(()=>{this.featureWait=void 0,e()},500);this.featureWait=()=>{clearTimeout(n),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 n=this.view;if(n.editing!==void 0&&e.trim()!==""&&!this.picture(e)){n.editing+=e.replace(/[\r\n]+/g," "),this.suggest(),this.draw();return}if(n.installing!==void 0||n.asking!==void 0||n.panel!==void 0||n.help)return;if(e.trim()===""){this.fromClipboard();return}this.attach(e)}picture(e){let n=e.trim();if(/^https?:\/\/\S+$/i.test(n))return!go(n,this.site??x[0]);return ls(n).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 — ${Hg}`);return}this.pasted(e.text);return}await this.bring(()=>fs(e.bytes,e.source))}notice(e,n=R1){let t=this.view;t.error=e,clearTimeout(this.noticeTimer),this.noticeTimer=setTimeout(()=>{if(t.error===e)t.error=void 0,this.draw()},n),this.draw()}async peek(){let e=this.view,n;try{n=await tg()}catch{return}if(!n||n.stamp===this.peeked)return;if(this.peeked=n.stamp,!n.picture||e.installing!==void 0||e.asking!==void 0)return;e.hint=`picture on the clipboard · ${P1} uses it`,clearTimeout(this.peekTimer),this.peekTimer=setTimeout(()=>{e.hint=void 0,this.draw()},F1),this.draw()}async fromClipboard(){let e=this.view;if(bc()){if(this.grabber.clipboard){this.grabber.ask();return}this.notice("over ssh the clipboard is not here — drop the file");return}let n;try{n=await ng(Gn(this.scratch,`clipboard-${Date.now()}.png`))}catch(r){this.notice(`could not read the clipboard: ${Nr(r)}`);return}if(clearTimeout(this.peekTimer),e.hint=void 0,"image"in n){await this.bring(async(r)=>({...await wc(n.image,r),source:"clipboard"}));return}let t=n.text.trim();if(!t){this.notice(`no picture on the clipboard — ${Hg}`);return}if(this.picture(t)){await this.attach(t);return}if(e.editing===void 0)e.editing="";this.pasted(t)}async attach(e){let n=e.trim();if(/^https?:\/\//i.test(n)){let i=go(n,this.site??x[0]);if(i){await this.jump(i.site,i.id);return}}let[t,...r]=ls(n).sort((i,o)=>Number(!Ag.test(i))-Number(!Ag.test(o)));if(!t){this.notice("nothing to use in that — drop a picture, or paste one or its link");return}await this.bring((i)=>wc(t,i),r.length)}async bring(e,n=0){let t=this.view;this.attaching?.abort();let r=new AbortController;this.attaching=r,t.error=void 0,t.saved=void 0,t.note="reading the picture…",this.draw();let i;try{i=await e(AbortSignal.any([r.signal,this.signal]))}catch(l){if(!r.signal.aborted)t.note=void 0,this.notice(Nr(l),8000);return}if(r.signal.aborted)return;t.note=n>0?`the first picture of ${n+1} — drop one at a time to try the others`:void 0,this.quietSuggest(),t.editing=void 0,t.suggest=void 0,t.pick=void 0;let o=xd(i.bytes);Dd(o,i.source);let s=this.origPath(ds,o,i.ext);_i(ws(s),{recursive:!0}),Wi(s,i.bytes);let u=k1(s).href,c={id:o,file:u,width:i.width,height:i.height,ext:i.ext,preview:u,owner:"",artist:"",score:0,rating:"s",md5:Ug("md5").update(i.bytes).digest("hex"),source:i.source,tags:[],solo:void 0,family:0,smaller:[]},a={site:ds,post:c},f=this.previewPath(a);_i(ws(f),{recursive:!0}),Wi(f,i.bytes),++this.gen,this.current=void 0,t.shown=void 0;let h=bs(`local|post:${o}`,!1);this.board=h,this.boards.set(h.key,h),this.single(h,a)}single(e,n){e.searching=!1,this.posts.set(In(n.site,n.post.id),n),e.groups=[{posts:[n],open:!1}],e.checked=1,e.total=1,this.thumbQueue.push(n),this.thumbs(),this.view.mode="try",this.show(),this.select(),this.draw()}onClock=()=>{let e=this.sites.reduce((r,i)=>nt(i)>nt(r)?i:r),n=Math.ceil((nt(e)-Date.now())/1000),t=n>0?n:void 0;if(t!==this.view.waiting)this.view.waiting=t,this.view.slow=e.name,this.draw()};onResize=()=>{if(this.cols=process.stdout.columns||this.cols,this.rows=process.stdout.rows||this.rows,this.scroll(),this.view.mode==="try"&&this.current)this.reveal();this.pump(),this.draw()};key(e){let n=this.view;if(e==="ctrl-c"){this.finish(2);return}if(n.installing!==void 0)return;if(n.asking!==void 0){this.askKey(e);return}if(e==="focus-in"){this.peek();return}if(e==="focus-out"||e==="nop")return;if((e==="ctrl-v"||e==="alt-v")&&n.panel===void 0){this.fromClipboard();return}if(n.editing!==void 0){this.editKey(e);return}if(n.panel!==void 0){this.panelKey(e);return}if(n.help){if(e==="?"||e==="esc")n.help=!1,this.draw();return}if(this.cols<Kt.cols||this.rows<Kt.rows){if(e==="esc")this.finish(2);return}if(e==="?"){n.help=!0,this.draw();return}if(n.mode==="try"){this.tryKey(e);return}this.gridKey(e)}gridKey(e){let n=this.view,{perRow:t,rowsVis:r}=Mr(this.cols,this.rows),o={left:-1,right:1,up:-t,down:t,pgup:-t*r,pgdn:t*r,home:-n.focus,end:n.tiles.length}[e];if(o!==void 0){this.focus(n.focus+o);return}if(e==="enter"&&n.tiles[n.focus]){n.mode="try",n.error=void 0,this.select();return}if(e==="v"){this.fromClipboard();return}if(e==="c"){n.preset=n.preset==="cutouts"?"all":"cutouts",this.turn();return}if(e==="tab"){this.tab=(this.tab+1)%(x.length+1),this.syncSite(),this.turn();return}if(e==="/"){n.editing="",this.draw();return}if(e===" "){this.unfold();return}if(e==="o"){this.openPage();return}if(e==="s"){n.panel=0,this.draw();return}if(e==="esc")this.finish(2)}panelKey(e){let n=this.view,t=n.panel??0,r=n.settings[t];if(e==="up"||e==="down"){n.panel=Math.max(0,Math.min(n.settings.length-1,t+(e==="up"?-1:1))),this.draw();return}if((e==="left"||e==="right")&&r){let i=e==="left"?-1:1;if(r.multi)r.cursor=(r.cursor+i+r.choices.length)%r.choices.length;else{let o=r.choices.indexOf(r.value);r.value=r.choices[(o+i+r.choices.length)%r.choices.length]}this.draw();return}if(e===" "&&r?.multi){let i=r.value.split(" "),o=r.choices.filter((u,c)=>c===r.cursor?!i.includes(u):i.includes(u)),s=r.multi.none;if(o.length>0||s!==void 0)r.value=o.length>0?o.join(" "):s,this.draw();return}if(e==="esc"){n.settings.forEach((i,o)=>{i.value=this.setting(Ir[o]?.name??"")}),n.panel=void 0,this.draw();return}if(e==="enter"||e==="alt-c")n.panel=void 0,this.adopt()}adopt(){let e=this.view,n=Ir.map((r)=>this.setting(r.name));e.settings.forEach((r,i)=>{let o=Ir[i];if(o)this.values.set(o.name,r.value)});let t=Ir.filter((r,i)=>this.setting(r.name)!==n[i]);if(t.length===0){this.draw();return}this.save(t),e.rating=nr(this.setting("TTHEME_FIND_RATING")),e.block=tr(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=Rg(this.setting("TTHEME_FIND_ORDER")),e.solo=this.setting("TTHEME_FIND_SOLO")==="on",this.boards.clear(),this.current=void 0,e.shown=void 0,e.mode="grid",this.search()}save(e){this.store(e.map((n)=>[n.name,this.setting(n.name)]))}store(e){let n=Gn(this.home,"ttheme","config.zsh");try{let t=vr(n)?jg(n,"utf8"):"";return Wi(n,e.reduce((r,[i,o])=>Wh(r,i,o),t)),!0}catch(t){return this.view.error=t instanceof Error?t.message:String(t),!1}}askKey(e){let n=this.view;if(e==="y"){if(n.asking=void 0,this.store([["TTHEME_FIND_UNBLOCK","1"]])){this.unblock=!0,this.finish(0);return}this.draw();return}if(e==="n"||e==="esc")n.asking=void 0,this.draw()}editKey(e){let n=this.view,t=n.editing??"",r=n.suggest??[];if((e==="up"||e==="down")&&r.length>0){let i=n.pick??-1,o=e==="down"?Math.min(r.length-1,i+1):i-1;n.pick=o<0?void 0:o,this.draw();return}if(e==="esc"||e==="enter")this.quietSuggest();if(e==="esc"){if(n.editing=void 0,n.tag===""){this.finish(2);return}this.draw();return}if(e==="enter"){let i=n.pick===void 0?void 0:r[n.pick],o=i?t.replace(/\S*$/,i.value):t;if(n.editing=void 0,n.suggest=void 0,n.pick=void 0,o.trim()){this.commit(o.trim());return}if(n.tag===""){this.finish(2);return}this.draw();return}if(e==="backspace"){n.editing=t.slice(0,-1),this.suggest(),this.draw();return}if(e.length===1&&e>=" ")n.editing=t+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 n=/\S*$/.exec(e.editing??"")?.[0]??"";if(!S1(n)){e.suggest=void 0;return}let t=[...new Map(xl(this.catalog.palettes,this.entry,n).map((i)=>[i.booru,{value:i.booru,count:0,palette:i.name}])).values()].slice(0,H1);e.suggest=t.length>0?t:void 0;let r=new AbortController;this.suggesting=r,this.suggestTimer=setTimeout(async()=>{try{let i=await Yf(n,AbortSignal.any([this.signal,r.signal]));if(this.suggesting===r&&e.editing!==void 0){let o=new Map(i.map((u)=>[u.value,u.count])),s=new Set(t.map((u)=>u.value));e.suggest=[...t.map((u)=>({...u,count:o.get(u.value)??0})),...i.filter((u)=>!s.has(u.value))].slice(0,L1),e.pick=e.pick!==void 0&&e.pick<t.length?e.pick:void 0,this.draw()}}catch{}},v1)}async commit(e){let n=go(e,this.site??x[0]);if(n){await this.jump(n.site,n.id);return}if(this.picture(e)){await this.attach(e);return}this.view.tag=e,this.boards.clear(),await this.search()}async jump(e,n){let t=++this.gen;this.tab=x.indexOf(e)+1,this.syncSite(),this.current=void 0,this.view.shown=void 0,this.view.error=void 0;let r=bs(`${e.key}|post:${n}`,!0);this.board=r,this.boards.set(r.key,r),this.show(),this.draw();try{let i=await ei(e,n,this.signal);if(t!==this.gen)return;if(!i){r.searching=!1,r.error=`${e.name} has no post ${n}`,this.view.error=r.error,this.show(),this.draw();return}this.single(r,{site:e,post:i})}catch(i){this.fail(t,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,n=0;for(let t of this.board.groups){let r=t.open?t.posts.length:1;if(e.focus<n+r){if(t.posts.length<2)return;t.open=!t.open,this.board.focus=n;for(let i of t.posts)if(!this.thumbPath.has(In(i.site,i.post.id)))this.thumbQueue.push(i);this.thumbs(),this.show(),this.scroll(),this.draw();return}n+=r}}openPage(){let e=this.view.tiles[this.view.focus],n=e&&this.posts.get(e.key);if(!n)return;let t=process.platform==="darwin"?"open":"xdg-open";try{p1(t,[n.site.pageUrl(n.post.id)],{stdio:"ignore",detached:!0}).unref()}catch{}}tryKey(e){let n=this.view;if(e==="left"||e==="right"){this.direction=e==="left"?-1:1,this.focus(n.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),n.fetching=void 0,n.mode="grid",n.error=void 0,this.draw()}focus(e){let n=this.view;if(n.tiles.length===0)return;let t=Math.max(0,Math.min(n.tiles.length-1,e));if(t===n.focus)return;if(n.focus=t,this.board.focus=t,this.scroll(),this.pump(),n.mode==="try")this.select();this.draw()}scroll(){let e=this.view,{perRow:n,rowsVis:t}=Mr(this.cols,this.rows),r=Math.floor(e.focus/n);if(r<e.top)e.top=r;if(r>e.top+t-1)e.top=r-t+1;this.board.top=e.top}query(e){let n=this.view,t=n.tag===this.entry.booru?ed(this.entry,e.key):[n.tag];if(t.length===0)return;let r=t.length>1,i=n.preset==="cutouts"?e.cutouts:"",o=r&&i.includes("~"),s=[r?t.map((a)=>`~${a}`).join(" "):t[0],e.rate(this.view.rating),o?"":i,n.order==="score"?e.best:""].filter(Boolean),u=[],c=[];for(let a of s)if(nu([...u,a].join(" "))<=e.tagBudget)u.push(a);else c.push(a);return{tags:u.join(" "),notes:[...c.length>0?[`${e.name} takes ${e.tagBudget} tags — ${c.join(" ")} left out`]:[],...o?[`${e.name} ORs the names, so cutouts are told by the file`]:[]]}}async search(){let e=++this.gen,n=bs(this.boardKey,!0);this.board=n,this.boards.set(n.key,n),this.view.error=void 0;let t=this.sites.flatMap((o)=>{let s=this.query(o);return s?[{site:o,...s}]:[]}),r=this.sites.filter((o)=>!t.some((s)=>s.site===o)),i=[...t.flatMap(({notes:o})=>o),...r.length>0?[`${this.entry.name} has no tag on ${r.map((o)=>o.name).join(", ")}`]:[]];if(n.note=i.length>0?i.join(" · "):void 0,t.length===0)n.searching=!1;this.show(),this.draw(),this.tally(e,n,t);try{let o=await Promise.all(t.map(async(s)=>({plan:s,owners:await this.mateOwners(s.site)})));if(e!==this.gen)return;n.sources=o.flatMap(({plan:{site:s,tags:u},owners:c})=>[...nu(u)+1<=s.tagBudget?[...c.keys()].map((a)=>({site:s,tags:`${u} user:${a}`,page:0,done:!1})):[],{site:s,tags:u,page:0,done:!1}]),this.show(),this.draw(),await this.pump()}catch(o){this.fail(e,o)}}async tally(e,n,t){let r=await Promise.allSettled(t.map(({site:i,tags:o})=>Kf(i,o,this.signal)));if(e===this.gen)n.total=r.reduce((i,o)=>i+(o.status==="fulfilled"?o.value:0),0),this.show(),this.draw()}fail(e,n,t=this.site){if(e!==this.gen||this.signal.aborted)return;this.board.error=Rc(t?.name??this.tabName,n),this.board.searching=!1,this.view.error=this.board.error,this.offer(t,n),this.show(),this.draw()}offer(e,n){if(e&&!this.view.unblocked&&Ti()&&Nr(n)==="ECONNRESET")this.view.asking=e.name}drop(e,n,t){for(let r of e.sources)if(r.site===n)r.done=!0;e.note=[e.note,Rc(n.name,t)].filter(Boolean).join(" · "),this.offer(n,t)}wants(){let{perRow:e,rowsVis:n}=Mr(this.cols,this.rows);return this.view.tiles.length<(this.board.top+n+Lg)*e}need(){let{perRow:e,rowsVis:n}=Mr(this.cols,this.rows);return(n+Lg)*e}live(e){return this.boards.get(e.key)===e}page(e,n,t){let r=`${e.key}|${n}|${t}`,i=this.pages.get(r);if(!i)i=Wf(e,n,t,this.signal).then((o)=>this.borrow(o)),this.pages.set(r,i),i.catch(()=>this.pages.delete(r));return i}async borrow(e){let n=e.filter((t)=>t.solo===void 0&&t.md5!=="");if(n.length>0)try{qf(n,await Qf(n.map((t)=>t.md5),this.signal))}catch{}return e}async round(e){let n=x.flatMap((u)=>{let c=e.sources.find((a)=>a.site===u&&!a.done);return c?[c]:[]}),t=await Promise.all(n.map(async(u)=>{try{return{source:u,posts:await this.page(u.site,u.tags,u.page)}}catch(c){if(e.sources.every((a)=>a.site===u.site)||this.signal.aborted)throw c;return this.drop(e,u.site,c),{source:u,posts:void 0}}}));if(!this.live(e))return;let r=[];for(let{source:u,posts:c}of t){if(!c)continue;u.page++,u.done=c.length<yt;let a=e.last.get(u);for(let f of c){let h=a&&yg(a.post,f)?a.set:`set:${u.site.key}:${f.id}`;a={post:f,set:h};let l=In(u.site,f.id);if(e.seen.has(l))continue;e.seen.add(l);let d={site:u.site,post:f};if(this.eligible(d))e.kin.set(d,[h,...kg(u.site,f)]),r.push(d);else e.checked++}if(a)e.last.set(u,a)}let i=this.dedupe(e,r),o=++e.rounds,s;if(this.view.order!=="fit")s=n.length>1?bg(i):i;else{let u=ps(i,this.frame(),this.matched),c=u.slice(0,this.need());if(await this.looks(c),!this.live(e))return;s=[...ps(c,this.frame(),this.matched),...u.slice(c.length)]}for(let u of s)e.roundOf.set(u,o);e.queue.push(...s),this.ahead(e)}ahead(e){if(this.aheading||this.view.order!=="fit"||!this.live(e))return;let n=e.queue.slice(0,this.need()).filter((t)=>!this.looking.has(In(t.site,t.post.id)));if(n.length===0)return;this.aheading=!0,this.looks(n).then(()=>{this.aheading=!1;for(let t of new Set(n.map((r)=>e.roundOf.get(r)??0)))this.resort(e,t);this.ahead(e)})}resort(e,n){let t=e.queue.flatMap((i,o)=>e.roundOf.get(i)===n?[o]:[]),r=ps(t.map((i)=>e.queue[i]),this.frame(),this.matched);t.forEach((i,o)=>{e.queue[i]=r[o]})}dedupe(e,n){let t=[];for(let r of n){let i=Mc(r.post),o=i.map((u)=>e.same.get(u)).find(Boolean);if(!o){for(let u of i)e.same.set(u,r);t.push(r);continue}if(e.checked++,Tg(r.post)<=Tg(o.post))continue;for(let u of[...i,...Mc(o.post)])e.same.set(u,r);let s=t.indexOf(o);if(s>=0){t[s]=r;continue}this.replace(e,o,r)}return t}replace(e,n,t){e.roundOf.set(t,e.roundOf.get(n)??0);let r=e.queue.indexOf(n);if(r>=0){e.queue[r]=t;return}for(let i of e.groups){let o=i.posts.indexOf(n);if(o>=0){i.posts[o]=t,this.posts.set(In(t.site,t.post.id),t),this.thumbQueue.push(t),this.thumbs();return}}}async looks(e){let n=0;await Promise.all(Array.from({length:Pg},async()=>{while(n<e.length)await this.look(e[n++])}))}look(e){let n=In(e.site,e.post.id),t=this.looking.get(n);if(!t)t=(async()=>{let r=this.previewPath(e);await this.cached(e.site,r,e.post.preview);let i=await this.renders.run({job:"match",from:r,colors:this.entry.signature});return this.looked.set(n,i),this.matched.set(e.post,i.match),i})().catch(()=>{return}),this.looking.set(n,t);return t}async pump(){let e=this.gen,n=this.board;if(this.pumping===e||n.sources.length===0)return;this.pumping=e;let t=[],r;try{n.searching=!0;while(e===this.gen){while(t.length<Fg&&n.queue.length>0&&this.wants()){let s=n.queue.shift();t.push({pick:s,passed:this.vet(s)})}if(this.ahead(n),!r&&n.queue.length<Fg&&n.sources.some((s)=>!s.done)&&this.wants()){let s=this.round(n).then(()=>{if(r===s)r=void 0});s.catch(()=>{}),r=s}let i=t.shift();if(!i){if(!r)break;await r,this.show(),this.draw();continue}let o=await i.passed;if(e!==this.gen)return;if(n.checked++,o)this.admit(i.pick);this.show(),this.draw()}if(e===this.gen)n.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:n}){let t=St(n);if(!po(e,n,this.view.rating)||mo(n,this.view.block).length>0||!t)return!1;if(this.view.solo&&n.solo===!1)return!1;return this.view.preset==="all"?["png","jpg","jpeg"].includes(t.ext):n.ext==="png"}async vet(e){let[n]=await Promise.all([this.passes(e),this.look(e)]);return n}async passes({site:e,post:n}){return this.view.preset==="all"||e.vouched||this.transparent(e,n)}probes(e){let n=this.probed.get(e.key);if(!n)n=Fc(e,"probes.json"),this.probed.set(e.key,n);return n}async transparent(e,n){let t=this.probes(e),r=t[n.id];if(r!==void 0)return r;try{let i=(await Zf(e,n.file,this.signal))?.alpha===!0;return t[n.id]=i,this.unsaved.add(e.key),i}catch{return!1}}saveProbes(){for(let e of this.unsaved){let n=x.find((t)=>t.key===e);if(n)Pc(n,"probes.json",this.probes(n))}this.unsaved.clear()}admit(e){let{site:n,post:t}=e,r=this.board,i=In(n,t.id);this.posts.set(i,e);let o=r.kin.get(e)??[],s=this.looked.get(i),u=s&&{hash:s.hash,width:t.width,height:t.height},c=this.view.sets==="fold"?this.kindred(r,o,u):void 0;if(c){if(c.posts.push(e),this.register(r,c,o,u),c.open)this.thumbQueue.push(e),this.thumbs();return}let a={posts:[e],open:!1};r.groups.push(a),this.register(r,a,o,u),this.thumbQueue.push(e),this.thumbs()}kindred(e,n,t){for(let r of n){let i=e.kindred.get(r);if(i)return i}return t&&e.shapes.find((r)=>Sg(r.shape,t))?.group}register(e,n,t,r){for(let i of t)if(!e.kindred.has(i))e.kindred.set(i,n);if(r)e.shapes.push({shape:r,group:n})}async mateOwners(e){let n=this.owners.get(e.key);if(n)return n;let t=Fh(this.home),r=Fc(e,"owners.json"),i=this.catalog.palettes.flatMap((c)=>{let a=t.get(c.name);return c.group===this.entry.group&&c.name!==this.entry.name&&a?.site===e.key?[{name:c.name,id:a.id}]:[]}),o=await Promise.all(i.map(async(c)=>{let a=r[c.id];if(a!==void 0)return{...c,owner:a};try{return{...c,owner:(await ei(e,c.id,this.signal))?.owner??""}}catch{return}})),s=new Map;for(let c of o)if(c)r[c.id]=c.owner,s.set(c.name,c.owner);Pc(e,"owners.json",r);let u=Jf(s);return this.owners.set(e.key,u),u}async cached(e,n,t,r){if(vr(n))return b1(n).size;let i=this.inflight.get(n);if(i)return i;let o=(async()=>{let s=await wo(e,t,this.signal,r);return _i(ws(n),{recursive:!0}),Wi(n,s),s.length})();this.inflight.set(n,o);try{return await o}finally{this.inflight.delete(n)}}thumbs(){while(this.thumbing<Pg&&this.thumbQueue.length>0){let e=this.thumbQueue.shift();this.thumbing++,this.thumb(e).catch(()=>{}).finally(()=>{this.thumbing--,this.thumbs()})}}async thumb(e){let{site:n,post:t}=e,r=Be.cols*this.cell.w,i=Be.rows*this.cell.h,o=Gn(bn(n),"tile",`${Gg(t)}-${r}x${i}.png`);if(!vr(o)){let s=this.previewPath(e);await this.cached(n,s,t.preview),await this.renders.run({job:"thumb",from:s,to:o,width:r,height:i})}this.thumbPath.set(In(n,t.id),o),this.show(),this.draw()}select(){let e=this.view,n=e.tiles[e.focus];if(this.fetch?.abort(),clearTimeout(this.settle),e.fetching=void 0,!n)return;if(this.current?.key===n.key){this.reveal();return}this.settle=setTimeout(()=>void this.load(n),N1),this.draw()}async load(e){let n=this.view,t=this.posts.get(e.key),r=t&&St(t.post);if(!t||!r)return;let{site:i}=t,o=this.board,s=new AbortController;this.fetch=s;try{let u=this.origPath(i,e.id,r.ext);if(!vr(u))n.fetching={id:e.key,got:0,size:0},this.draw();let c=await this.cached(i,u,r.file,(h,l)=>{if(n.fetching?.id===e.key)n.fetching={id:e.key,got:h,size:l},this.draw()});if(s.signal.aborted)return;if(n.fetching=void 0,o!==this.board)return;let a={site:i,id:e.id,key:e.key,path:u,ext:r.ext,size:c,using:"plain",failed:!1};n.preparing=e.key,this.flush();let f=await this.render(a,"plain");if(s.signal.aborted||o!==this.board)return;if(f.clear===0&&kr()&&this.setting("TTHEME_FIND_REMOVE_BG")!=="off"){if(n.preparing=void 0,n.cutting=e.key,this.flush(),a.cut=await this.cutOut(i,e.id,u,s.signal),s.signal.aborted||o!==this.board)return;if(n.cutting=void 0,a.cut){n.preparing=e.key,this.flush();let h=await this.render(a,"cut").catch(()=>{return});if(s.signal.aborted||o!==this.board)return;if(h&&is(h.clear))a.using="cut";else Oc(a.cut,{force:!0}),a.cut=void 0,a.failed=!0}else a.failed=!0}if(this.current=a,n.tiles[n.focus]?.key===e.key)await this.present();this.preload()}catch(u){if(!s.signal.aborted&&!this.signal.aborted)n.error=Rc(i.name,u)}finally{if(n.fetching?.id===e.key)n.fetching=void 0;if(n.preparing===e.key)n.preparing=void 0;if(n.cutting===e.key)n.cutting=void 0;this.draw()}}async cutOut(e,n,t,r){let i=Gn(bn(e),"cut",`${n}.png`);if(vr(i))return i;try{return _i(ws(i),{recursive:!0}),await Li(t,i,r),i}catch{Oc(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 n of[e.focus+this.direction,e.focus-this.direction]){if(this.prefetching>=I1)return;let t=e.tiles[n],r=t&&this.posts.get(t.key),i=r&&St(r.post);if(!r||!i)continue;let{site:o,post:s}=r,u=this.origPath(o,s.id,i.ext);this.prefetching++,this.cached(o,u,i.file).then(()=>this.render({site:o,id:s.id,key:t.key,path:u,ext:i.ext,size:0,using:"plain",failed:!1},"plain")).catch(()=>{}).finally(()=>{this.prefetching--})}}async render(e,n){let t=this.cols*this.cell.w,r=this.rows*this.cell.h,i=Math.min(t,A1),o=Math.max(1,Math.round(r*i/t)),s=Gn(this.scratch,`${e.site.key}-${e.id}${n==="cut"?"c":""}-${i}x${o}.png`),u=`${e.site.key}:${e.id}:${n}`,c=this.clarity.get(u);if(c!==void 0&&vr(s))return{clear:c,path:s};let a=await this.renders.run({job:"show",from:n==="cut"?e.cut:e.path,to:s,width:i,height:o,colors:this.entry,tone:this.tone,blur:this.blurring*i/gu(t,r).width});return this.clarity.set(u,a),{clear:a,path:s}}async present(){let e=this.current;if(!e)return;let n=e.using,{clear:t,path:r}=await this.render(e,n);if(this.current!==e||e.using!==n)return;this.view.shown={id:e.key,clear:t,bytes:e.size,path:r,cut:e.cut?n==="cut"?"on":"off":e.failed?"failed":"none"}}reveal(){let e=this.view;e.preparing=this.current?.key,this.flush(),this.present().catch((n)=>{e.error=n instanceof Error?n.message:String(n)}).finally(()=>{if(e.preparing===this.current?.key)e.preparing=void 0;this.draw()})}async install(){let e=this.view,n=e.tiles[e.focus],t=this.current;if(!n||t?.key!==n.key||e.preparing!==void 0||e.shown?.id!==n.key)return;e.installing=n.key,e.error=void 0,this.flush();try{await this.renders.run({job:"backdrop",from:t.using==="cut"?t.cut:t.path,source:t.path,home:this.home,colors:this.entry,tone:this.tone,origin:{site:t.site.key,id:t.id,ext:t.ext,from:`${t.site.name} ${t.id} ${t.site.pageUrl(t.id)}`},width:this.cols*this.cell.w,height:this.rows*this.cell.h,blur:this.blurring});let r=Fc(t.site,"owners.json");r[t.id]=this.posts.get(t.key)?.post.owner??"",Pc(t.site,"owners.json",r),An(this.home),e.saved=`background · ${this.entry.name} ← ${t.site.name} ${t.id}`,e.installed.push(n.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)return;this.dirty=!0,setImmediate(()=>{this.dirty=!1,this.flush()})}flush(){let e=pg(this.view,this.cols,this.rows),n="\x1B[?2026h";e.lines.forEach((r,i)=>{n+=`\x1B[${i+1};1H\x1B[K${r}`});let t=new Set;for(let r of e.images){if(t.add(r.id),this.sent.get(r.id)!==r.path)n+=cg(r),this.sent.set(r.id,r.path),this.placed.delete(r.id);let i=`${r.row};${r.col};${r.cols};${r.rows};${r.z}`;if(this.placed.get(r.id)!==i)n+=ag(r),this.placed.set(r.id,i)}for(let r of this.sent.keys())if(!t.has(r))n+=fg(r),this.sent.delete(r),this.placed.delete(r);this.write(`${n}\x1B[?2026l`)}}async function Jg(e){if(Ui())return Gi();let n=de(),t=ht(n),r=Ut(t.palettes,e);if(!process.stdin.isTTY||!process.stdout.isTTY)throw Error("needs a terminal");let i=new Cg(n,t,r,r.booru??""),o=await i.run(),s=i.unblock?await Gi():o;if(i.saved&&s!==0)return process.stderr.write(`${i.saved}
519
+ `),0;return s}function _g(e,n){let t=de();if(Ut(ht(t).palettes,e),n==="next"||n==="prev"){let{key:r,at:i,of:o}=Ih(t,e,n==="next"?1:-1);return An(t),process.stderr.write(`background · ${e} ${i}/${o} ${r}
520
+ `),0}if(n==="drop"){let{key:r,left:i}=Nh(t,e);return An(t),process.stderr.write(`background · ${e} removed ${r} · ${i} left
521
+ `),0}if(n==="tuned")return An(t),0;throw Error(`unknown image action ${n} — next, prev, drop or tuned`)}import{execFileSync as cm,spawnSync as x1}from"node:child_process";import{chmodSync as ey,copyFileSync as ny,existsSync as on,mkdirSync as Uc,readdirSync as ty,readFileSync as Rr,rmSync as sm,writeFileSync as ry}from"node:fs";import{homedir as iy}from"node:os";import{dirname as Or,join as Ee}from"node:path";import{existsSync as z1}from"node:fs";import{openSync as G1,writeSync as U1}from"node:fs";import{ReadStream as j1}from"node:tty";var C1=["10","11","12","17",...Array.from({length:16},(e,n)=>`4;${n}`)];function Ki(e=process.env){return Boolean(e.NO_COLOR)||e.TERM==="dumb"}function $s(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((n,t)=>`\x1B]4;${t};${n}\x1B\\`)].join("")}function J1(e){let n=new Map;for(let t of e.split("\x1B")){let r=t.match(/^\](\d+(?:;\d+)?);(rgba?:[0-9a-fA-F/]+)/),[,i,o]=r??[];if(i&&o)n.set(i,o)}return n}function Wg(e){return[...e].map(([n,t])=>`\x1B]${n};${t}\x1B\\`).join("")}var _1=`${C1.map((e)=>`\x1B]${e};?\x1B\\`).join("")}\x1B[5n`;function W1(e){return e.includes("\x1B[0n")}async function Kg(){let e,n;try{e=G1("/dev/tty","r+"),n=new j1(e),n.setRawMode(!0)}catch{return new Map}try{U1(e,_1);let t="";return await new Promise((r)=>{let i=setTimeout(r,120);n.on("data",(o)=>{if(t+=o.toString(),W1(t))clearTimeout(i),r()})}),J1(t)}finally{n.setRawMode(!1),n.destroy()}}function Ac(e){let n=e.replace("#","");return[n.slice(0,2),n.slice(2,4),n.slice(4,6)].map((t)=>Number.parseInt(t,16)).join(";")}function qi(e){return`\x1B[38;2;${Ac(e)}m`}function qg(e,n){return`\x1B[48;2;${Ac(e)};38;2;${Ac(n)}m`}function Qg(e,n="\x1B[39m"){return`${e.map((t)=>`${qi(t)}■`).join(" ")}${n}`}function ks(e,n){let t=n.toLowerCase();return[e.name,e.group,e.native??""].some((r)=>r.toLowerCase().includes(t))}function Zg(e,n,t){let r=t.trim(),i=[],o=new Set;for(let s of e){if(s.default||o.has(s.group))continue;o.add(s.group);let u=e.filter((f)=>!f.default&&f.group===s.group),c=r?u.filter((f)=>ks(f,r)):u;if(r&&c.length===0)continue;let a=r.length>0||n.has(s.group);if(i.push({kind:"group",name:s.group,native:s.native,lead:u.find((f)=>f.lead)??s,expanded:a,count:c.length}),a)i.push(...c.map((f)=>({kind:"palette",entry:f})))}return i}function K1(e,n){let t=n.trim(),r=new Set(e.filter((i)=>!i.default&&(t===""||ks(i,t))).map((i)=>i.group));return Zg(e,new Set,"").filter((i)=>i.kind==="group"&&r.has(i.name))}function q1(e){return e.includes("@")}function Q1(e){let n=e.findIndex((t)=>t.kind==="group"&&q1(t.name));return n>0&&e.slice(0,n).some((t)=>t.kind==="group")?[...e.slice(0,n),{kind:"rule"},...e.slice(n)]:e}function Y1(e){let n=e.findIndex((t)=>t.kind==="palette");return n===-1?0:n}var Qi="\x1B[0m",Hc="\x1B[2m",Yg="\x1B[1m",Lc="\x1B[22m",Z1="\x1B[36m",X1="\x1B[33m";function Xg(e){return e==="decode"||e==="glitch"?e:"typewriter"}class Tc extends Rn{picked;scope;entries;named;series;seriesPad;namePad;expanded=new Set;rows=[];cursor=0;top=0;maxItems;color;lastInput="";lastFocused="";onFocus;example="";fx;fxStep=0;fxSeed=0;fxTimer;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.entries=e.entries,this.scope=e.scope??"palette",this.picked=new Set(e.installed??[]),this.named=e.entries.filter((t)=>!t.default),this.series=[...new Set(this.named.map((t)=>t.group))],this.seriesPad=Math.max(0,...this.series.map((t)=>t.length)),this.namePad=Math.max(0,...this.named.map((t)=>t.name.length)),this.maxItems=e.maxItems??12,this.color=e.color??!0,this.fx=e.fx??"typewriter",this.onFocus=e.onFocus,this.rollExample();let n=setInterval(()=>{this.rollExample(),this.fxStep=8,this.output.emit("resize")},3000);n.unref?.(),this.once("finalize",()=>{clearInterval(n),clearTimeout(this.fxTimer)}),this.rebuild("first"),this.on("cursor",(t)=>{if(t==="up")this.move(-1);else if(t==="down")this.move(1);else if(t==="left")this.fold(!1);else if(t==="right")this.fold(!0)}),this.on("userInput",(t)=>{if(t!==this.lastInput)this.lastInput=t,this.rebuild("keep")}),this.on("key",(t,r)=>{if(r?.name==="space")this.pick(this.rows[this.cursor])})}_isActionKey(e){return e==="\t"||e===" "}members(e){let n=this.scope==="palette"?this.userInput.trim():"";return this.named.filter((t)=>t.group===e&&(n===""||ks(t,n)))}everyone(e){return e.flatMap((n)=>n.kind==="group"?this.members(n.name):[])}pick(e){let n=e?.kind==="palette"?[e.entry.name]:e?.kind==="group"?this.members(e.name).map((r)=>r.name):e?.kind==="all"?this.everyone(this.rows).map((r)=>r.name):[];if(n.length===0)return;let t=n.some((r)=>!this.picked.has(r));for(let r of n)if(t)this.picked.add(r);else this.picked.delete(r)}pickedIn(e){return this.members(e).filter((n)=>this.picked.has(n.name)).length}pickedCount(){if(this.scope==="palette")return this.picked.size;return this.series.filter((e)=>this.members(e).every((n)=>this.picked.has(n.name))).length}rollExample(){let e=this.named[Math.floor(Math.random()*this.named.length)],n=this.series[Math.floor(Math.random()*this.series.length)];if(!e||!n){this.example="";return}let t=`${e.name} | ${n}`;this.example=t.length>30?`${t.slice(0,29)}…`:t,this.fxSeed=Math.floor(Math.random()*997)}animatedExample(){if(this.fxStep===0)return this.example;if(!this.fxTimer)this.fxTimer=setTimeout(()=>{this.fxTimer=void 0,this.fxStep-=1,this.output.emit("resize")},60),this.fxTimer.unref?.();let e=Math.floor(this.example.length*(8-this.fxStep)/8);if(this.fx==="typewriter")return`${this.example.slice(0,e)}▏`;let n=this.fx==="decode"?"abcdefghijklmnopqrstuvwxyz":"▓▒░#*+=<>?/-_",t=this.fx==="decode"?(r)=>!/[a-z0-9]/i.test(r):(r)=>r===" ";return[...this.example].map((r,i)=>i+(i*7+this.fxSeed)%3<e||t(r)?r:n[Math.floor(Math.random()*n.length)]??r).join("")}sync(){let e=this.rows[this.cursor],n=e?.kind==="palette"?e.entry:e?.kind==="group"&&this.scope==="series"?e.lead:void 0;if(n&&n.name!==this.lastFocused)this.lastFocused=n.name,this.onFocus?.(n)}rebuild(e){let n=this.rows[this.cursor],t=this.scope==="series"?K1(this.entries,this.userInput):Zg(this.entries,this.expanded,this.userInput);this.rows=t.length>0?Q1([{kind:"all",count:this.allCount(t)},...t]):[];let r=t.length>0?this.rows.indexOf(t[Y1(t)]):0;if(e==="first")this.cursor=r;else if(e==="keep"){let i=n?.kind==="palette"?n.entry.name:"",o=i?this.rows.findIndex((s)=>s.kind==="palette"&&s.entry.name===i):-1;this.cursor=o===-1?r:o}else if(this.cursor>=this.rows.length)this.cursor=Math.max(0,this.rows.length-1);this.sync()}allCount(e){return this.scope==="series"?e.length:this.everyone(e).length}move(e){let n=this.cursor+e;if(this.rows[n]?.kind==="rule")n+=e;if(n>=0&&n<this.rows.length)this.cursor=n;this.sync()}toggle(e){if(this.expanded.has(e))this.expanded.delete(e);else this.expanded.add(e);this.rebuild("clamp")}fold(e){if(this.userInput||this.scope==="series")return;let n=this.rows[this.cursor];if(n?.kind==="group"){if(e!==n.expanded)this.toggle(n.name)}else if(n?.kind==="palette"&&!e&&!n.entry.default){let t=n.entry.group;if(this.expanded.delete(t),this.rebuild("clamp"),this.cursor=this.rows.findIndex((r)=>r.kind==="group"&&r.name===t),this.cursor===-1)this.cursor=0;this.sync()}}renderRow(e,n){if(e.kind==="rule")return` ${this.color?`${Hc}${"── markets ──────────"}${Qi}`:"── markets ──────────"}`;let t=e.kind==="palette"?e.entry:e.kind==="group"?e.lead:void 0,r=this.color&&n&&t!==void 0,i=(d)=>this.color?`${Hc}${d}${Lc}`:d,o=(d)=>this.color?`${Yg}${d}${Lc}`:d,s=(d)=>this.color?` ${Qg(Io(d),r?qi(d.foreground):"\x1B[39m")}`:"",u=n?r?`${qi(t.cursor)}▌\x1B[39m `:"▌ ":" ",c=(d)=>r?`${u}${qg(t.selection,t.foreground)} ${d} ${Qi}`:`${u} ${d}`;if(e.kind==="all"){let d=this.everyone(this.rows).every((g)=>this.picked.has(g.name))?"●":"○";return c(`${d} select all ${i(`(${e.count})`)}`)}if(e.kind==="group"&&this.scope==="series"){let d=this.pickedIn(e.name)===e.count?"●":"○",g=`(${e.count})${e.native?` ${e.native}`:""}`;return c(`${d} ${o(e.name.padEnd(this.seriesPad))}${s(e.lead)}${this.color?" ":" "}${i(g)}`)}if(e.kind==="group"){let d=this.rows[this.cursor],g=d?.kind==="palette"&&d.entry.group===e.name?d.entry:void 0,m=this.color&&g?`${Yg}${qi(g.cursor)}${e.name}${Lc}\x1B[39m`:o(e.name),$=e.native?` ${i(e.native)}`:"";return c(`${e.expanded?"▾":"▸"} ${m} ${i(`(${this.pickedIn(e.name)}/${e.count})`)}${$}`)}let a=e.entry,f=this.picked.has(a.name)?"●":"○",h=this.color?a.name.padEnd(this.namePad):a.name,l=n?o(h):h;return c(` ${f} ${l}${s(a)}`)}draw(){let e=(m)=>this.color?`${Hc}${m}${Qi}`:m,n=(m)=>this.color?`${Z1}${m}${Qi}`:m,t=this.scope==="series"?"series":"catalog";if(this.state==="submit")return`${e("◇")} ${t} ${e(`· ${this.pickedCount()} picked`)}`;if(this.state==="cancel")return`${e(`◇ ${t} · cancelled`)}`;let r=this.userInput.trim(),i=this.scope==="series"?this.series.length:this.named.length,o=this.scope==="series"?this.rows.filter((m)=>m.kind==="group").length:r?this.named.filter((m)=>ks(m,r)).length:i,s=`${n("◆")} ${t} ${e(`(${o}/${i} · ${this.pickedCount()} picked)`)}`,u=`${n("│")} ${this.userInput?`${this.userInput}_`:e(`search…${this.example?` e.g. ${this.animatedExample()}`:""}`)}`;if(this.cursor<this.top)this.top=this.cursor;if(this.cursor>=this.top+this.maxItems)this.top=this.cursor-this.maxItems+1;this.top=Math.min(this.top,Math.max(0,this.rows.length-this.maxItems));let c=this.rows.slice(this.top,this.top+this.maxItems),a=c.length>0?c.map((m,$)=>`${n("│")} ${this.renderRow(m,this.top+$===this.cursor)}`):[`${n("│")} ${e(`no ${this.scope==="series"?"series":"palettes"} match '${this.userInput}'`)}`];while(a.length<this.maxItems)a.push(n("│"));let f=this.rows.length-this.top-c.length,h=f>0?`${n("│")} ${e(`↓ ${f} more`)}`:n("│"),l=this.scope==="series"?"":" · ←→ fold",d=this.scope==="series"?"continue":"install",g=this.state==="error"?`${n("└")} ${this.color?`${X1}${this.error}${Qi}`:this.error}`:`${n("└")} ${e(`↑↓ move${l} · space pick · type to filter · enter ${d} · esc cancel`)}`;return[s,u,...a,h,g].join(`
522
+ `)}}function Gc(e){console.log(`
523
+ ${e} palettes installed — open a new tab, or reload your terminal config`)}async function zg(e){let n=de(),t=He(n),r=[...new Set(e.map((c)=>c.startsWith(at)?jd(n,c,t):c))],i=ge(n),o=r.filter((c)=>i.palettes.includes(c)),s=r.filter((c)=>!i.palettes.includes(c));if(s.length===0){tn(n,t,i),console.log(`already installed: ${o.join(", ")}`);return}let u={...i,palettes:[...i.palettes,...s]};lt(n,t,i,u);for(let c of s)console.log(` + ${c}`);await Wt(n,je(n,t,!1).palettes.filter((c)=>s.includes(c.name)),u.terminals),Gc(u.palettes.length)}function Vg(e){let n=de(),t=He(n),r=ge(n),i=e.filter((u)=>r.palettes.includes(u)),o=e.filter((u)=>!r.palettes.includes(u));if(i.length===0)throw Error(`not installed: ${o.join(", ")} — \`ttheme list\` marks what is`);let s={...r,palettes:r.palettes.filter((u)=>!i.includes(u))};lt(n,t,r,s),sc(n,t,r.terminals,i);for(let u of i)console.log(` - ${u}`);if(Gc(s.palettes.length),o.length>0)return console.error(`ttheme remove: not installed: ${o.join(", ")}`),1;return 0}function Bg(e){let n=de(),t=He(n),r=ge(n);if(!r.palettes.includes(e))throw Error(`${e} is not installed — \`ttheme add ${e}\` first`);let{off:i,...o}=r,s=Yn(),u=Pi({...o,startup:e},s);tn(n,t,u),Zn(n,u);let c=Jt(u,s);console.log(em(e,u.terminals,c&&s.running()).join(`
524
+ `))}function Dg(){let e=de(),n=ge(e),t=Xn(n);if(!t)throw Error("no palettes installed — `ttheme browse` picks some");if(!n.off){console.log(`already on · ${t}`);return}let{off:r,...i}=n,o=lt(e,He(e),n,i);console.log(em(t,i.terminals,o).join(`
525
+ `))}function xg(){let e=de(),n=ge(e);if(n.off){console.log("already off");return}let t=lt(e,He(e),n,{...n,off:!0}),r=Xn(n);if(console.log(`off · new tabs open in the terminal's own colors${r?` — \`ttheme on\` wears ${r} again`:""}`),t)console.log("iterm2 new tabs open on your own profile once iTerm2 restarts")}function em(e,n,t){let r=n.filter((o)=>o!=="iterm2"),i=r.length>0?[`default ${e} · ${r.join(", ")} open new tabs with it once their config reloads`]:[];if(n.includes("iterm2"))i.push(t?'iterm2 new tabs open with it once iTerm2 restarts — "ttheme · default" is now its default profile':'iterm2 new tabs open with it — "ttheme · default" is its default profile');return i.length>0?i:[`default ${e} · no terminal is wired to open with it — \`ttheme init\` wires one`]}function nm(e,n){let t=new Map(n.palettes.map((r)=>[r.name,"market"]));for(let r of qo(e,n.palettes,!1))t.set(r.name,"mine");return t}function tm(e,n=!1){let t=de(),r=He(t),i=new Set(ge(t).palettes),o=nm(t,r),s=hn(je(t,r).palettes),u=ri(e?Dl(s,e):s),c=(h)=>o.get(h)??"kept";if(n){let h=u.map((l)=>({name:l.name,group:l.group,installed:i.has(l.name),source:c(l.name)}));console.log(JSON.stringify(h,null,2));return}let a=Math.max(...u.map((h)=>h.name.length),0),f={market:"",mine:" · yours",kept:" · in no market you added"};for(let h of u)console.log(` ${i.has(h.name)?"●":"○"} ${h.name.padEnd(a)} ${h.group}${f[c(h.name)]}`);if(process.stdout.isTTY){let h=e?`${u.length} of ${s.length}`:`${s.length}`;console.log(`
526
+ ${h} palettes — ${u.filter((l)=>i.has(l.name)).length} installed`)}}async function rm(){let e=de(),n=mr(e);if(n.length===0)console.log("no markets to update — `ttheme market add official` brings the ttheme catalog back");for(let u of n)try{console.log(` ${await Pd(e,u)}`)}catch(c){let a=kn(u);console.log(` ${a}: ${c.message} — kept the copy from the last update`)}if(!z1(gr(e)))return;let t=He(e),r=ge(e),i=nm(e,t),o=r.palettes.filter((u)=>!i.has(u)),s=new Map(Ri(e).map((u)=>[u.name,u.pictures]));tn(e,t,r);for(let u of o)console.log(` ${u} left its market — ttheme keeps the copy you have`);await Wt(e,je(e,t,!1).palettes.filter((u)=>r.palettes.includes(u.name)&&s.has(u.name)).map((u)=>os(u,s.get(u.name))),r.terminals)}async function ys(e,n,t,r=!1){let i=process.env.TTHEME_SORT==="series"?e.palettes:ri(e.palettes),o=process.stdout.isTTY===!0&&!Ki(),s=o?await Kg():new Map,u=new Tc({entries:i,scope:t,installed:n,required:r,color:!Ki(),fx:Xg(process.env.TTHEME_FX),onFocus:o?(a)=>process.stdout.write($s(a)):void 0}),c=await u.prompt();if(process.stdout.write(Wg(s)),nn(c))return;return e.palettes.filter((a)=>u.picked.has(a.name)).map((a)=>a.name)}async function im(){let e=de(),n=He(e),t=ge(e),r=await ys(je(e,n),t.palettes,"palette");if(!r){console.log("nothing changed");return}let i=t.palettes.filter((u)=>!r.includes(u)),o=r.filter((u)=>!t.palettes.includes(u));if(o.length===0&&i.length===0){console.log("nothing changed");return}let s={...t,palettes:r};lt(e,n,t,s),sc(e,n,t.terminals,i);for(let u of o)console.log(` + ${u}`);for(let u of i)console.log(` - ${u}`);await Wt(e,je(e,n,!1).palettes.filter((u)=>o.includes(u.name)),s.terminals),Gc(s.palettes.length)}import{availableParallelism as V1,homedir as B1}from"node:os";var D1=4;async function Es(e,n,t=B1()){let r=ze(Pe(e)),i=fr(e),o=new Map(ht(e).palettes.map((h)=>[h.name,h.backdrop])),s=Object.entries(r.palettes).flatMap(([h,l])=>{let d=o.get(h);return d?l.pictures.filter((g)=>g.tone===void 0||(g.blur??0)!==i).map((g)=>({name:h,key:g.key,hue:d})):[]});if(s.length===0)return 0;n(`drawing ${s.length} background picture${s.length===1?"":"s"} again${i?` · blur ${i}px`:""}`);let u=!ge(e).terminals.includes("iterm2"),c=new Nc(Math.min(D1,V1()-1)),a=await c.map(s.map(({name:h,key:l,hue:d})=>({job:"redraw",home:e,user:t,name:h,key:l,hue:d,blur:i,aligns:u})));c.close();let f=[];return a.forEach((h,l)=>{let{name:d,key:g}=s[l];if(h instanceof Error||h===null){n(` ▢ ${d} ${g} — ${h instanceof Error?h.message:"no original to draw it from"}, left as it was`);return}f.push({name:d,picture:h})}),Ph(e,f),An(e,t),f.length}async function om(){return await Es(de(),(e)=>process.stderr.write(`${e}
527
+ `)),0}function oy(e,n,t){for(let r of ty(n))e.push({from:Ee(n,r),to:Ee(t,r)})}function am(e){return JSON.parse(Rr(Ee(e,"dist","manifest.json"),"utf8"))}function jc(e,n){let t=Ee(n.configHome,"ttheme"),r=[{from:Ee(n.root,"bin","ttheme.js"),to:Ee(t,"ttheme.js")},{from:Ee(n.root,"bin","ttheme.js.map"),to:Ee(t,"ttheme.js.map")},{from:Ee(n.root,"shell","ttheme.zsh"),to:Ee(t,"ttheme.zsh")},{from:Ee(n.root,"shell","launch-tab.zsh"),to:Ee(t,"launch-tab.zsh"),executable:!0}];oy(r,Ee(n.root,"shell","adapters"),Ee(t,"adapters"));let i=[{file:Ee(n.zdotdir,".zshrc"),block:Ch(t)}],o=Ee(t,"config.zsh"),s=Kh(on(o)?Rr(o,"utf8"):""),u={file:o,content:s},c=[];if(e.terminals.includes("alacritty")){let h=_t(n.configHome);if(on(h)&&pi(Rr(h,"utf8"),void 0)===void 0)c.push(`${h} already imports files under [general] — ttheme left it alone; add ${Ee(n.configHome,"alacritty","themes")}/<palette>.toml to that import list yourself`)}if(e.terminals.includes("wezterm")){let h=$r(n.configHome,n.home);if(on(h)&&wi(Rr(h,"utf8"),"")===void 0)c.push(`${h} has no \`return config\` line — ttheme left it alone; call \`dofile("${Ee(t,"wezterm.lua")}")(config)\` from it yourself`)}let a=e.terminals.includes("windows-terminal");if(a&&!n.wtHome)c.push("windows terminal: %LOCALAPPDATA% was not found — drop the release fragment into its Fragments folder yourself");if(e.terminals.includes("warp"))c.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 f={terminals:e.terminals,palettes:e.palettes,...a&&n.wtHome?{wtHome:n.wtHome}:{},...a&&n.wtProfile?{wtProfile:n.wtProfile}:{},...e.off?{off:!0}:{}};return c.push(...dd(n.configHome,e.terminals,n.home)),{home:n.home,copies:r,edits:i,settings:u,catalog:am(n.root),installed:f,notes:c}}function sy(e){try{return ge(e)}catch{return}}function uy(e){try{return je(e,He(e),!1).palettes}catch{return[]}}function cy(e,n){let t=jc({terminals:e.terminals,palettes:e.palettes,off:e.off},n),r=new Set([...t.catalog.palettes,...uy(n.configHome)].map((f)=>f.name)),i=e.palettes.filter((f)=>r.has(f)),o=e.palettes.filter((f)=>!r.has(f)),{startup:s,...u}=e,c={...u,palettes:i,...s&&i.includes(s)?{startup:s}:{}},a=o.length>0?[`dropped ${o.join(", ")} — no longer in the catalog`,...t.notes]:t.notes;return{...t,installed:c,notes:a}}function ay(e){try{return cm(process.execPath,[Ee(e,"ttheme","ttheme.js"),"--version"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function fm(e){let n=En(e);return[e.terminals.join(", "),`${e.palettes.length} palettes`,n?`default ${n}`:"no default — ttheme is off"].join(" · ")}function fy(e){try{return ge(e).itermBase}catch{return}}function Cc(e,n=Yn()){for(let o of e.copies)if(Uc(Or(o.to),{recursive:!0}),sm(o.to,{force:!0}),sm(`${o.to}.zwc`,{force:!0}),ny(o.from,o.to),o.executable)ey(o.to,493);Uc(Or(e.settings.file),{recursive:!0}),ry(e.settings.file,e.settings.content);let t=Or(Or(e.settings.file)),r=fy(t),i=Pi(r?{...e.installed,itermBase:r}:e.installed,n);if(Kn(i.markets).includes(Ue))Ni(t,e.catalog);Zn(t,i),tn(t,He(t),i,e.home);for(let o of e.edits){Uc(Or(o.file),{recursive:!0});let s=on(o.file)?Rr(o.file,"utf8"):"";ci(o.file,gi(s,o.block))}return Jt(i,n)}class dt extends Error{}function Ss(e){if(nn(e))throw dr("nothing changed"),new dt;return e}function hm(e){return No.filter((n)=>{if(n==="iterm2")return process.platform==="darwin";if(n==="windows-terminal")return e.wtHome!==void 0;return n!=="warp"||process.platform!=="win32"})}function hy(e,n){if(e==="iterm2")return on(Ee(n.home,"Library","Application Support","iTerm2"));if(e==="windows-terminal")return n.wtHome!==void 0;if(e==="warp")return on(Or(Vo(n.home)));if(e==="wezterm")return on(Ee(n.configHome,"wezterm"))||on(Ee(n.home,".wezterm.lua"));return on(Ee(n.configHome,e))}function ly(){if(process.platform==="win32")return process.env.LOCALAPPDATA;if(!process.env.WSL_DISTRO_NAME)return;let e=(n,t)=>cm(n,t,{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 dy(e,n,t){return Ss(await Gl({message:"wire which terminals?",options:hm(t).map((r)=>({value:r,hint:r===e?"detected":void 0})),initialValues:n,required:!0}))}function Jc(e){let n=[...e.copies.filter((t)=>!on(t.to)).map((t)=>t.to),...on(e.settings.file)?[]:[e.settings.file],...e.edits.filter((t)=>!Rr(t.file,"utf8").includes("# ttheme begin")).map((t)=>t.file)];if(n.length>0)throw Error(`init left gaps:
524
528
  ${n.join(`
525
- `)}`)}function Tg(e,n){return[...new Set(e.palettes.filter((t)=>n.includes(t.name)).map((t)=>t.group))]}function m1(e,n){let t=e.palettes.find((i)=>i.name===kn(n)),r=process.stdout.isTTY===!0&&!Li()&&!process.env.TMUX&&mo(process.env)!=="warp";if(!t||!r)return!1;return process.stdout.write(us(t)),!0}function p1(e,n){let t=kn(e);if(!t)return["default none — new tabs keep the terminal colors",`turn on \`ttheme on\` wears ${Qn(e)}`];return[`default ${t}${n?" — this tab wears it already":""}`,"change it `ttheme preview`, enter on a palette, then default"]}function w1(e){e1("zsh",["-c",'source "$1" && __tt_preview init',"zsh",ye(e,"ttheme","ttheme.zsh")],{stdio:"inherit"})}function $1(e,n,t,r){let i=Tg(e.catalog,n.palettes);vt([`${i.join(", ")} (${n.palettes.length})`,...p1(e.installed,t)].join(`
526
- `),`installed ${n.palettes.length} palettes`),vt(["exec zsh the ttheme command in this tab",...Gg(n.terminals,e,r)].join(`
527
- `),"next"),Eu("done")}function Gg(e,n,t){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(...b1(kn(n.installed),t));return[...r,...n.notes]}function Fg(e,n,t){let r=a1(e,n),i=_n(),o=dc(r,i);gc(r);let s=["exec zsh open tabs run the new layer — new tabs already do",...Gg(r.installed.terminals,r,o&&i.running())],u=`updated to ${_e.version} — kept ${Lg(r.installed)}`;if(!t){console.log([u,...s].join(`
528
- `));return}vt(s.join(`
529
- `),u),Eu("done")}function b1(e,n){let t=['iterm2 profiles a "ttheme · <palette>" per palette in Settings › Profiles'];if(e)t.push(n?`restart iterm2 new tabs open on "ttheme · default", which wears ${e}`:`iterm2 default "ttheme · default" wears ${e} and follows \`ttheme default\``);return t}function k1(e,n){let t=[`placed ${e.copies.length} files`,`settings in ${e.settings.file} — edit later with \`ttheme config\``,...e.edits.map((r)=>`wired ${r.file}`)];if(n.terminals.includes("ghostty"))t.push("restart ghostty to pick up its config");if(n.terminals.includes("kitty"))t.push("kitty reloads its colors by itself; pictures show in kitty windows opened from now on");if(n.terminals.includes("alacritty"))t.push("alacritty reloads its config by itself");if(n.terminals.includes("wezterm")||n.terminals.includes("windows-terminal"))t.push("wezterm and windows terminal reload their config by themselves");if(n.terminals.includes("iterm2"))t.push('iterm2 gets a "ttheme · <palette>" profile per palette under Settings › Profiles');t.push(...e.notes),t.push("no palettes yet — open a new shell (`exec zsh`), then `ttheme browse` picks them from the catalog"),console.log(t.join(`
530
- `))}async function Ug(e={}){let n=ye(import.meta.dirname,"..");if(!rn(ye(n,"bin","ttheme.js")))throw Error("bin/ttheme.js is missing — run `mise run bin:build` first");if(!rn(ye(n,"dist"))){if(typeof Bun>"u")throw Error("this package is missing dist/ — reinstall @kecan0406/ttheme");await bo()}let t=o1(),r=de(),i=process.env.ZDOTDIR??t,o=d1(),s=process.env.WT_PROFILE_ID,u={root:n,home:t,configHome:r,zdotdir:i,...o?{wtHome:o}:{},...s?{wtProfile:s}:{}},c=mo(process.env),a=Ag(u).filter((N)=>N===c||l1(N,u));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 h=u1(r);if(e.yes&&h){Fg(h,u,!1);return}if(e.yes){if(a.length===0)throw Error("no supported terminal detected — run this inside ghostty, kitty, alacritty, wezterm, iterm2, windows terminal or warp");let N={terminals:a,palettes:[]},H=lc(N,u);dc(H),gc(H),k1(H,N);return}if(Io("ttheme init"),h){let N=h1(r);if(hs(await st({message:`ttheme${N?` ${N}`:""} is installed — ${Lg(h)}
531
- ${N===_e.version?"reinstall":"update to"} ${_e.version} and keep all of it?`,active:"yes",inactive:"no, set it up again",initialValue:!0}))){Fg(h,u,!0);return}}let f=await g1(c,h?.terminals??a,u),l=Hg(n),d=h?await as(l,h.palettes,"palette",!0):await as(l,[],"series",!0);if(!d)throw rr("nothing changed"),new ft;let g=h&&Qn(h),p=g&&d.includes(g)?g:void 0,k=p??d[0],y=d.length>1&&mo(process.env)!=="warp",M=hs(await st({message:y?"pick a default palette in ttheme preview once installed?":`wear ${k} in every tab?`,initialValue:h?!h.off:!0})),b={terminals:f,palettes:d,off:!M},S=lc(b,u),m=p?{...S,installed:{...S.installed,startup:p}}:S;if(vt([`install ${d.length} palettes — ${Tg(m.catalog,d).join(", ")}`,`copy ${m.copies.length} files under ${r}`,`write ${m.settings.file}`,...m.edits.map((N)=>`edit ${N.file} — a ttheme block: source ttheme.zsh`),...Ll(r,m.installed,t),"each config is backed up once to <file>.ttheme.bak before the first edit — `npx @kecan0406/ttheme uninstall` takes it all out",M?y?`open ttheme preview — every tab wears the palette picked there, ${k} until then`:`paint every tab with ${k}, this one now`:"leave the terminal colors as they are — `ttheme on` wears a palette later",...f.includes("iterm2")&&M?['make "ttheme · default" the iTerm2 default profile']:[]].join(`
532
- `),`wiring ${f.join(", ")}`),!hs(await st({message:"apply these changes?"})))throw rr("nothing changed"),new ft;let P=_n(),E=dc(m,P);if(gc(m),M&&y)w1(r);let R=ke(r);$1({...m,installed:R},b,m1(m.catalog,R),E&&P.running())}import{existsSync as fs,readdirSync as E1,readFileSync as y1,rmSync as S1,utimesSync as v1}from"node:fs";import{homedir as M1}from"node:os";import{dirname as I1,join as $r}from"node:path";function mc(e){return fs(e)?y1(e,"utf8"):""}function N1(e){try{return ke(e)}catch{return}}function O1(e,n){let t=jo(n,e),r=mc(t);if(!po(r)?.includes(`path = "${fe("")}`))return;return{file:t,content:wo(r,mc(Uu(e))||Gu)}}function R1(e){let{home:n,configHome:t}=e,r=N1(t),i=[],o=(a,h)=>{let f=mc(a),l=h(f);if(l!==f)i.push({file:a,content:l})};o($r(e.zdotdir,".zshrc"),ii),o(Lt("ghostty",t),ii),o(Lt("kitty",t),ii),o(Tt(t),ii),o(hr(t,n),gf);let s=O1(t,n);if(s)i.push(s);let u=[];for(let a of["ghostty","kitty","alacritty","wezterm","warp"]){let h=Ht(a,t,n);if(fs(h))u.push(...E1(h).flatMap((f)=>f.startsWith(fe(""))?[$r(h,f)]:[]))}let c=[yi(n),...r?.wtHome?[I1(Jo(r.wtHome))]:[],$r(t,"ttheme"),e.cacheDir,e.stateDir];return u.push(...c.filter((a)=>fs(a))),{edits:i,removals:u,touches:r?.wtHome?ju(r.wtHome):[],...r?{state:r}:{}}}function F1(e,n=_n()){let t=[];for(let{file:i,content:o}of e.edits){let s=Ph(i,o);t.push(s==="removed"?`removed ${i} — ttheme had created it`:s==="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&&At({...e.state,off:!0},n))t.push("gave iTerm2 its own default profile back — it takes it at its next start");for(let i of e.removals)S1(i,{recursive:!0,force:!0});if(e.removals.length>0)t.push(`deleted ${e.removals.length} files and folders ttheme wrote`);let r=new Date;for(let i of e.touches)v1(i,r,r);return t}function P1(){let e=M1();return{home:e,configHome:de(),zdotdir:process.env.ZDOTDIR??e,cacheDir:so(),stateDir:$r(process.env.XDG_STATE_HOME??$r(e,".local","state"),"ttheme")}}async function jg(e=!1){let n=P1(),t=R1(n);if(t.edits.length===0&&t.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=$r(n.configHome,"ttheme");Io("ttheme uninstall"),vt([...t.edits.map((o)=>`take ttheme out of ${o.file}`),...t.removals.map((o)=>o===r?`delete ${o} — settings, pins, every installed picture${fs(Ro(n.configHome))?`, and your markets under ${Ro(n.configHome)} (push them to GitHub first to keep them)`:""}`:`delete ${o}`)].join(`
533
- `),"uninstall");let i=await st({message:"remove ttheme?"});if(en(i)||!i)throw rr("nothing changed"),new ft}for(let r of F1(t))console.log(r);console.log("open tabs keep their colors until they close — restart your terminal to drop ttheme everywhere")}var br=(e)=>(...n)=>Ni()&&Mi()?Ii():e(...n),L1={default:([e])=>Eg(e),on:()=>yg(),off:()=>Sg(),browse:br(()=>Og()),list:([e],{json:n})=>Ig(e,n),add:br((e)=>bg(e)),remove:(e)=>kg(e),update:br(()=>Ng()),market:br(([e,n])=>Bl(e,n)),new:br(([e],{from:n,in:t})=>cd(e,n,t)),edit:br(([e])=>ad(e)),check:([e],{fix:n})=>fd(e,n),share:([e])=>ld(e),init:(e,{yes:n})=>Ug({yes:n}),uninstall:(e,{yes:n})=>jg(n),build:(e,{only:n})=>bo({only:n}),find:([e])=>hg(e),image:([e,n])=>fg(e,n)},A1=ei.map((e)=>({...e,run:L1[e.name]}));class jt extends Error{verb;constructor(e,n){super(e);this.verb=n}}function Jg(e){let n=A1.find((t)=>t.name===e);if(!n)throw new jt(e.startsWith("-")?`unknown option '${e}'`:`unknown command '${e}'`);return n}function T1(e,n){let t={help:{type:"boolean",short:"h"}};for(let[r,{type:i,short:o,multiple:s}]of Object.entries(e.flags??{}))t[r]={type:i,multiple:s===!0,...o?{short:o}:{}};try{return H1({args:n,options:t,allowPositionals:!0})}catch(r){let[i=""]=(r instanceof Error?r.message:String(r)).split(". ");throw new jt(`${i.charAt(0).toLowerCase()}${i.slice(1)}`,e)}}function G1(e){let[n,...t]=e;if(n===void 0)return{kind:"help",code:1};if(n==="-h"||n==="--help")return{kind:"help",code:0};if(n==="-V"||n==="--version")return{kind:"version"};if(n==="help"){if(t[0]===void 0||t[0]==="all")return{kind:"help",all:t[0]==="all",code:0};return{kind:"help",verb:Jg(t[0]),code:0}}let r=Jg(n),i=T1(r,t);if(i.values.help)return{kind:"help",verb:r,code:0};for(let[h,{choices:f}]of Object.entries(r.flags??{}))for(let l of[i.values[h]??[]].flat())if(f&&!f.includes(String(l)))throw new jt(`--${h} takes ${f.join(", ")} — not ${l}`,r);let o=i.positionals,s=r.args.filter((h)=>h.startsWith("<")).length,u=r.args.some((h)=>h.includes("..."))?Number.POSITIVE_INFINITY:r.args.length;if(o.length<s)throw new jt(`missing ${r.args[o.length]}`,r);if(o.length>u)throw new jt(`too many arguments: ${o.slice(u).join(" ")}`,r);let{help:c,...a}=i.values;return{kind:"run",verb:r,args:o,flags:a}}function Cg(e){let n=Math.max(0,...e.map(([t])=>t.length));return e.map(([t,r])=>` ${t.padEnd(n)} ${r}`)}function pc(e,n=!1){if(!e)return ni(n);let t=Object.entries(e.flags??{}).map(([r,{short:i,value:o,about:s}])=>[`${i?`-${i}, `:""}--${r}${o?` ${o}`:""}`,s]);return[`Usage: ttheme ${xr(e)}`,"",e.about,...e.actions?["","Actions:",...Cg(e.actions)]:[],...t.length>0?["","Options:",...Cg(t)]:[]].join(`
534
- `)}async function Wg(e){let n;try{let t=G1(e);if(t.kind==="version")return console.log(_e.version),0;if(t.kind==="help"){if(t.code===0)console.log(pc(t.verb,t.all));else console.error(pc(t.verb,t.all));return t.code}if(n=t.verb,!t.verb.run)throw Error("runs in the shell layer — open a new tab once `ttheme init` has wired it");let r=await t.verb.run(t.args,t.flags);return typeof r==="number"?r:0}catch(t){if(t instanceof jt)return console.error(t.verb?`ttheme ${t.verb.name}: ${t.message}
529
+ `)}`)}function lm(e,n){return[...new Set(e.palettes.filter((t)=>n.includes(t.name)).map((t)=>t.group))]}function gy(e,n){let t=e.palettes.find((i)=>i.name===En(n)),r=process.stdout.isTTY===!0&&!Ki()&&!process.env.TMUX&&Oo(process.env)!=="warp";if(!t||!r)return!1;return process.stdout.write($s(t)),!0}function my(e,n){let t=En(e);if(!t)return["default none — new tabs keep the terminal colors",`turn on \`ttheme on\` wears ${Xn(e)}`];return[`default ${t}${n?" — this tab wears it already":""}`,"change it `ttheme preview`, enter on a palette, then default"]}function py(e){x1("zsh",["-c",'source "$1" && __tt_preview init',"zsh",Ee(e,"ttheme","ttheme.zsh")],{stdio:"inherit"})}function wy(e,n,t,r){let i=lm(e.catalog,n.palettes);Ft([`${i.join(", ")} (${n.palettes.length})`,...my(e.installed,t)].join(`
530
+ `),`installed ${n.palettes.length} palettes`),Ft(["exec zsh the ttheme command in this tab",...dm(n.terminals,e,r)].join(`
531
+ `),"next"),Wu("done")}function dm(e,n,t){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(...by(En(n.installed),t));return[...r,...n.notes]}function gm(e){return e?(n)=>st.step(n):(n)=>console.log(n)}async function um(e,n,t){let r=cy(e,n),i=Yn(),o=Cc(r,i);Jc(r),await Es(n.configHome,gm(t),n.home);let s=["exec zsh open tabs run the new layer — new tabs already do",...dm(r.installed.terminals,r,o&&i.running())],u=`updated to ${qe.version} — kept ${fm(r.installed)}`;if(!t){console.log([u,...s].join(`
532
+ `));return}Ft(s.join(`
533
+ `),u),Wu("done")}function by(e,n){let t=['iterm2 profiles a "ttheme · <palette>" per palette in Settings › Profiles'];if(e)t.push(n?`restart iterm2 new tabs open on "ttheme · default", which wears ${e}`:`iterm2 default "ttheme · default" wears ${e} and follows \`ttheme default\``);return t}function $y(e,n){let t=[`placed ${e.copies.length} files`,`settings in ${e.settings.file} — edit later with \`ttheme config\``,...e.edits.map((r)=>`wired ${r.file}`)];if(n.terminals.includes("ghostty"))t.push("restart ghostty to pick up its config");if(n.terminals.includes("kitty"))t.push("kitty reloads its colors by itself; pictures show in kitty windows opened from now on");if(n.terminals.includes("alacritty"))t.push("alacritty reloads its config by itself");if(n.terminals.includes("wezterm")||n.terminals.includes("windows-terminal"))t.push("wezterm and windows terminal reload their config by themselves");if(n.terminals.includes("iterm2"))t.push('iterm2 gets a "ttheme · <palette>" profile per palette under Settings › Profiles');t.push(...e.notes),t.push("no palettes yet — open a new shell (`exec zsh`), then `ttheme browse` picks them from the catalog"),console.log(t.join(`
534
+ `))}async function mm(e={}){let n=Ee(import.meta.dirname,"..");if(!on(Ee(n,"bin","ttheme.js")))throw Error("bin/ttheme.js is missing — run `mise run bin:build` first");if(!on(Ee(n,"dist"))){if(typeof Bun>"u")throw Error("this package is missing dist/ — reinstall @kecan0406/ttheme");await Ao()}let t=iy(),r=de(),i=process.env.ZDOTDIR??t,o=ly(),s=process.env.WT_PROFILE_ID,u={root:n,home:t,configHome:r,zdotdir:i,...o?{wtHome:o}:{},...s?{wtProfile:s}:{}},c=Oo(process.env),a=hm(u).filter((N)=>N===c||hy(N,u));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 f=sy(r);if(e.yes&&f){await um(f,u,!1);return}if(e.yes){if(a.length===0)throw Error("no supported terminal detected — run this inside ghostty, kitty, alacritty, wezterm, iterm2, windows terminal or warp");let N={terminals:a,palettes:[]},H=jc(N,u);Cc(H),Jc(H),$y(H,N);return}if(Co("ttheme init"),f){let N=ay(r);if(Ss(await ct({message:`ttheme${N?` ${N}`:""} is installed — ${fm(f)}
535
+ ${N===qe.version?"reinstall":"update to"} ${qe.version} and keep all of it?`,active:"yes",inactive:"no, set it up again",initialValue:!0}))){await um(f,u,!0);return}}let h=await dy(c,f?.terminals??a,u),l=am(n),d=f?await ys(l,f.palettes,"palette",!0):await ys(l,[],"series",!0);if(!d)throw dr("nothing changed"),new dt;let g=f&&Xn(f),m=g&&d.includes(g)?g:void 0,$=m??d[0],S=d.length>1&&Oo(process.env)!=="warp",v=Ss(await ct({message:S?"pick a default palette in ttheme preview once installed?":`wear ${$} in every tab?`,initialValue:f?!f.off:!0})),k={terminals:h,palettes:d,off:!v},M=jc(k,u),p=m?{...M,installed:{...M.installed,startup:m}}:M;if(Ft([`install ${d.length} palettes — ${lm(p.catalog,d).join(", ")}`,`copy ${p.copies.length} files under ${r}`,`write ${p.settings.file}`,...p.edits.map((N)=>`edit ${N.file} — a ttheme block: source ttheme.zsh`),...ld(r,p.installed,t),"each config is backed up once to <file>.ttheme.bak before the first edit — `npx @kecan0406/ttheme uninstall` takes it all out",v?S?`open ttheme preview — every tab wears the palette picked there, ${$} until then`:`paint every tab with ${$}, this one now`:"leave the terminal colors as they are — `ttheme on` wears a palette later",...h.includes("iterm2")&&v?['make "ttheme · default" the iTerm2 default profile']:[]].join(`
536
+ `),`wiring ${h.join(", ")}`),!Ss(await ct({message:"apply these changes?"})))throw dr("nothing changed"),new dt;let A=Yn(),y=Cc(p,A);if(Jc(p),await Es(r,gm(!0),t),v&&S)py(r);let F=ge(r);wy({...p,installed:F},k,gy(p.catalog,F),y&&A.running())}import{existsSync as Ms,readdirSync as ky,readFileSync as yy,rmSync as Ey,utimesSync as Sy}from"node:fs";import{homedir as My}from"node:os";import{dirname as vy,join as Fr}from"node:path";function _c(e){return Ms(e)?yy(e,"utf8"):""}function Iy(e){try{return ge(e)}catch{return}}function Ny(e,n){let t=Bo(n,e),r=_c(t);if(!Ro(r)?.includes(`path = "${he("")}`))return;return{file:t,content:Fo(r,_c(ic(e))||rc)}}function Oy(e){let{home:n,configHome:t}=e,r=Iy(t),i=[],o=(a,f)=>{let h=_c(a),l=f(h);if(l!==h)i.push({file:a,content:l})};o(Fr(e.zdotdir,".zshrc"),mi),o(Ct("ghostty",t),mi),o(Ct("kitty",t),mi),o(_t(t),mi),o($r(t,n),Xh);let s=Ny(t,n);if(s)i.push(s);let u=[];for(let a of["ghostty","kitty","alacritty","wezterm","warp"]){let f=jt(a,t,n);if(Ms(f))u.push(...ky(f).flatMap((h)=>h.startsWith(he(""))?[Fr(f,h)]:[]))}let c=[Ai(n),...r?.wtHome?[vy(Do(r.wtHome))]:[],Fr(t,"ttheme"),e.cacheDir,e.stateDir];return u.push(...c.filter((a)=>Ms(a))),{edits:i,removals:u,touches:r?.wtHome?oc(r.wtHome):[],...r?{state:r}:{}}}function Ry(e,n=Yn()){let t=[];for(let{file:i,content:o}of e.edits){let s=ah(i,o);t.push(s==="removed"?`removed ${i} — ttheme had created it`:s==="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&&Jt({...e.state,off:!0},n))t.push("gave iTerm2 its own default profile back — it takes it at its next start");for(let i of e.removals)Ey(i,{recursive:!0,force:!0});if(e.removals.length>0)t.push(`deleted ${e.removals.length} files and folders ttheme wrote`);let r=new Date;for(let i of e.touches)Sy(i,r,r);return t}function Fy(){let e=My();return{home:e,configHome:de(),zdotdir:process.env.ZDOTDIR??e,cacheDir:rr(),stateDir:Fr(process.env.XDG_STATE_HOME??Fr(e,".local","state"),"ttheme")}}async function pm(e=!1){let n=Fy(),t=Oy(n);if(t.edits.length===0&&t.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=Fr(n.configHome,"ttheme");Co("ttheme uninstall"),Ft([...t.edits.map((o)=>`take ttheme out of ${o.file}`),...t.removals.map((o)=>o===r?`delete ${o} — settings, pins, every installed picture${Ms(Wo(n.configHome))?`, and your markets under ${Wo(n.configHome)} (push them to GitHub first to keep them)`:""}`:`delete ${o}`)].join(`
537
+ `),"uninstall");let i=await ct({message:"remove ttheme?"});if(nn(i)||!i)throw dr("nothing changed"),new dt}for(let r of Ry(t))console.log(r);console.log("open tabs keep their colors until they close — restart your terminal to drop ttheme everywhere")}var Pr=(e)=>(...n)=>Ui()&&Ti()?Gi():e(...n),Ay={default:([e])=>Bg(e),on:()=>Dg(),off:()=>xg(),browse:Pr(()=>im()),list:([e],{json:n})=>tm(e,n),add:Pr((e)=>zg(e)),remove:(e)=>Vg(e),update:Pr(()=>rm()),market:Pr(([e,n])=>Fd(e,n)),new:Pr(([e],{from:n,in:t})=>Cd(e,n,t)),edit:Pr(([e])=>Jd(e)),check:([e],{fix:n})=>Wd(e,n),share:([e])=>Kd(e),init:(e,{yes:n})=>mm({yes:n}),uninstall:(e,{yes:n})=>pm(n),build:(e,{only:n})=>Ao({only:n}),find:([e])=>Jg(e),image:([e,n])=>_g(e,n),redraw:()=>om()},Hy=hi.map((e)=>({...e,run:Ay[e.name]}));class qt extends Error{verb;constructor(e,n){super(e);this.verb=n}}function wm(e){let n=Hy.find((t)=>t.name===e);if(!n)throw new qt(e.startsWith("-")?`unknown option '${e}'`:`unknown command '${e}'`);return n}function Ly(e,n){let t={help:{type:"boolean",short:"h"}};for(let[r,{type:i,short:o,multiple:s}]of Object.entries(e.flags??{}))t[r]={type:i,multiple:s===!0,...o?{short:o}:{}};try{return Py({args:n,options:t,allowPositionals:!0})}catch(r){let[i=""]=(r instanceof Error?r.message:String(r)).split(". ");throw new qt(`${i.charAt(0).toLowerCase()}${i.slice(1)}`,e)}}function Ty(e){let[n,...t]=e;if(n===void 0)return{kind:"help",code:1};if(n==="-h"||n==="--help")return{kind:"help",code:0};if(n==="-V"||n==="--version")return{kind:"version"};if(n==="help"){if(t[0]===void 0||t[0]==="all")return{kind:"help",all:t[0]==="all",code:0};return{kind:"help",verb:wm(t[0]),code:0}}let r=wm(n),i=Ly(r,t);if(i.values.help)return{kind:"help",verb:r,code:0};for(let[f,{choices:h}]of Object.entries(r.flags??{}))for(let l of[i.values[f]??[]].flat())if(h&&!h.includes(String(l)))throw new qt(`--${f} takes ${h.join(", ")} — not ${l}`,r);let o=i.positionals,s=r.args.filter((f)=>f.startsWith("<")).length,u=r.args.some((f)=>f.includes("..."))?Number.POSITIVE_INFINITY:r.args.length;if(o.length<s)throw new qt(`missing ${r.args[o.length]}`,r);if(o.length>u)throw new qt(`too many arguments: ${o.slice(u).join(" ")}`,r);let{help:c,...a}=i.values;return{kind:"run",verb:r,args:o,flags:a}}function bm(e){let n=Math.max(0,...e.map(([t])=>t.length));return e.map(([t,r])=>` ${t.padEnd(n)} ${r}`)}function Wc(e,n=!1){if(!e)return li(n);let t=Object.entries(e.flags??{}).map(([r,{short:i,value:o,about:s}])=>[`${i?`-${i}, `:""}--${r}${o?` ${o}`:""}`,s]);return[`Usage: ttheme ${fi(e)}`,"",e.about,...e.actions?["","Actions:",...bm(e.actions)]:[],...t.length>0?["","Options:",...bm(t)]:[]].join(`
538
+ `)}async function $m(e){let n;try{let t=Ty(e);if(t.kind==="version")return console.log(qe.version),0;if(t.kind==="help"){if(t.code===0)console.log(Wc(t.verb,t.all));else console.error(Wc(t.verb,t.all));return t.code}if(n=t.verb,!t.verb.run)throw Error("runs in the shell layer — open a new tab once `ttheme init` has wired it");let r=await t.verb.run(t.args,t.flags);return typeof r==="number"?r:0}catch(t){if(t instanceof qt)return console.error(t.verb?`ttheme ${t.verb.name}: ${t.message}
535
539
 
536
- ${pc(t.verb)}`:`ttheme: ${t.message} — see \`ttheme help\``),1;if(t instanceof ft)return 1;let r=process.env.TTHEME_DEBUG&&t instanceof Error?t.stack:void 0;return console.error(`
537
- ttheme${n?` ${n.name}`:""}: ${r??(t instanceof Error?t.message:String(t))}`),1}}if(j1)if(process.env.TTHEME_DEBUG&&typeof Bun>"u"&&!process.sourceMapsEnabled){let e=U1(process.execPath,["--enable-source-maps",...process.argv.slice(1)],{stdio:"inherit"});process.exitCode=e.status??1}else process.exitCode=await Wg(process.argv.slice(2));
540
+ ${Wc(t.verb)}`:`ttheme: ${t.message} — see \`ttheme help\``),1;if(t instanceof dt)return 1;let r=process.env.TTHEME_DEBUG&&t instanceof Error?t.stack:void 0;return console.error(`
541
+ ttheme${n?` ${n.name}`:""}: ${r??(t instanceof Error?t.message:String(t))}`),1}}if(Uy)if(process.env.TTHEME_DEBUG&&typeof Bun>"u"&&!process.sourceMapsEnabled){let e=Gy(process.execPath,["--enable-source-maps",...process.argv.slice(1)],{stdio:"inherit"});process.exitCode=e.status??1}else process.exitCode=await $m(process.argv.slice(2));
538
542
 
539
- //# debugId=9ACB4198213FBE7264756E2164756E21
543
+ //# debugId=C9229E29339E743B64756E2164756E21
540
544
  //# sourceMappingURL=ttheme.js.map