@kecan0406/ttheme 1.0.33 → 1.0.34
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -7
- package/bin/ttheme.js +129 -126
- package/bin/ttheme.js.map +1 -0
- package/dist/manifest.json +1 -1
- package/package.json +2 -2
- package/shell/adapters/_osc.zsh +2 -0
- package/shell/adapters/ghostty.zsh +13 -0
- package/shell/ttheme.zsh +110 -53
package/bin/ttheme.js
CHANGED
|
@@ -1,67 +1,67 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as fa}from"node:module";var ra=Object.create;var{getPrototypeOf:ia,defineProperty:Ko,getOwnPropertyNames:oa}=Object;var sa=Object.prototype.hasOwnProperty;function ca(t){return this[t]}var ua,ha,nr=(t,n,e)=>{var r=t!=null&&typeof t==="object";if(r){var i=n?ua??=new WeakMap:ha??=new WeakMap,o=i.get(t);if(o)return o}e=t!=null?ra(ia(t)):{};let s=n||!t||!t.__esModule?Ko(e,"default",{value:t,enumerable:!0}):e;for(let c of oa(t))if(!sa.call(s,c))Ko(s,c,{get:ca.bind(t,c),enumerable:!0});if(r)i.set(t,s);return s};var $t=(t,n)=>()=>(n||t((n={exports:{}}).exports,n),n.exports);var jt=fa(import.meta.url);var xo=$t((j0,or)=>{var Vo=Vo||function(t){return Buffer.from(t).toString("base64")};function wa(t){var n=this,e=Math.round,r=Math.floor,i=Array(64),o=Array(64),s=Array(64),c=Array(64),u,h,f,a,g=Array(65535),d=Array(65535),p=Array(64),l=Array(64),k=[],v=0,I=7,E=Array(64),y=Array(64),$=Array(64),H=Array(256),b=Array(2048),R,O=[0,1,5,6,14,15,27,28,2,4,7,13,16,26,29,42,3,8,12,17,25,30,41,43,9,11,18,24,31,40,44,53,10,19,23,32,39,45,52,54,20,22,33,38,46,51,55,60,21,34,37,47,50,56,59,61,35,36,48,49,57,58,62,63],P=[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],C=[0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,125],A=[1,2,3,0,4,17,5,18,33,49,65,6,19,81,97,7,34,113,20,50,129,145,161,8,35,66,177,193,21,82,209,240,36,51,98,114,130,9,10,22,23,24,25,26,37,38,39,40,41,42,52,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,225,226,227,228,229,230,231,232,233,234,241,242,243,244,245,246,247,248,249,250],Ft=[0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0],U=[0,1,2,3,4,5,6,7,8,9,10,11],x=[0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,119],kt=[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 dt(m){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 T=0;T<64;T++){var J=r((L[T]*m+50)/100);if(J<1)J=1;else if(J>255)J=255;i[O[T]]=J}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 X=0;X<64;X++){var rt=r((q[X]*m+50)/100);if(rt<1)rt=1;else if(rt>255)rt=255;o[O[X]]=rt}var it=[1,1.387039845,1.306562965,1.175875602,1,0.785694958,0.5411961,0.275899379],St=0;for(var wt=0;wt<8;wt++)for(var M=0;M<8;M++)s[St]=1/(i[O[St]]*it[wt]*it[M]*8),c[St]=1/(o[O[St]]*it[wt]*it[M]*8),St++}function B(m,L){var T=0,J=0,q=[];for(var X=1;X<=16;X++){for(var rt=1;rt<=m[X];rt++)q[L[J]]=[],q[L[J]][0]=T,q[L[J]][1]=X,J++,T++;T*=2}return q}function It(){u=B(P,G),h=B(Ft,U),f=B(C,A),a=B(x,kt)}function ot(){var m=1,L=2;for(var T=1;T<=15;T++){for(var J=m;J<L;J++)d[32767+J]=T,g[32767+J]=[],g[32767+J][1]=T,g[32767+J][0]=J;for(var q=-(L-1);q<=-m;q++)d[32767+q]=T,g[32767+q]=[],g[32767+q][1]=T,g[32767+q][0]=L-1+q;m<<=1,L<<=1}}function tt(){for(var m=0;m<256;m++)b[m]=19595*m,b[m+256>>0]=38470*m,b[m+512>>0]=7471*m+32768,b[m+768>>0]=-11059*m,b[m+1024>>0]=-21709*m,b[m+1280>>0]=32768*m+8421375,b[m+1536>>0]=-27439*m,b[m+1792>>0]=-5329*m}function z(m){var L=m[0],T=m[1]-1;while(T>=0){if(L&1<<T)v|=1<<I;if(T--,I--,I<0){if(v==255)w(255),w(0);else w(v);I=7,v=0}}}function w(m){k.push(m)}function K(m){w(m>>8&255),w(m&255)}function ht(m,L){var T,J,q,X,rt,it,St,wt,M=0,j,Z=8,Et=64;for(j=0;j<Z;++j){T=m[M],J=m[M+1],q=m[M+2],X=m[M+3],rt=m[M+4],it=m[M+5],St=m[M+6],wt=m[M+7];var _=T+wt,D=T-wt,at=J+St,W=J-St,st=q+it,Ht=q-it,bt=X+rt,qt=X-rt,nn=_+bt,In=_-bt,Kn=at+st,Jn=at-st;m[M]=nn+Kn,m[M+4]=nn-Kn;var ce=(Jn+In)*0.707106781;m[M+2]=In+ce,m[M+6]=In-ce,nn=qt+Ht,Kn=Ht+W,Jn=W+D;var ue=(nn-Jn)*0.382683433,xe=0.5411961*nn+ue,he=1.306562965*Jn+ue,fe=Kn*0.707106781,ae=D+fe,ge=D-fe;m[M+5]=ge+xe,m[M+3]=ge-xe,m[M+1]=ae+he,m[M+7]=ae-he,M+=8}M=0;for(j=0;j<Z;++j){T=m[M],J=m[M+8],q=m[M+16],X=m[M+24],rt=m[M+32],it=m[M+40],St=m[M+48],wt=m[M+56];var vo=T+wt,zr=T-wt,yo=J+St,So=J-St,Fo=q+it,Io=q-it,No=X+rt,ea=X-rt,le=vo+No,Yr=vo-No,Be=yo+Fo,De=yo-Fo;m[M]=le+Be,m[M+32]=le-Be;var Oo=(De+Yr)*0.707106781;m[M+16]=Yr+Oo,m[M+48]=Yr-Oo,le=ea+Io,Be=Io+So,De=So+zr;var Ho=(le-De)*0.382683433,jo=0.5411961*le+Ho,Ro=1.306562965*De+Ho,Go=Be*0.707106781,Lo=zr+Go,Po=zr-Go;m[M+40]=Po+jo,m[M+24]=Po-jo,m[M+8]=Lo+Ro,m[M+56]=Lo-Ro,M++}var tr;for(j=0;j<Et;++j)tr=m[j]*L[j],p[j]=tr>0?tr+0.5|0:tr-0.5|0;return p}function ft(){K(65504),K(16),w(74),w(70),w(73),w(70),w(0),w(1),w(1),w(0),K(1),K(1),w(0),w(0)}function nt(m){if(!m)return;if(K(65505),m[0]===69&&m[1]===120&&m[2]===105&&m[3]===102)K(m.length+2);else K(m.length+5+2),w(69),w(120),w(105),w(102),w(0);for(var L=0;L<m.length;L++)w(m[L])}function et(m,L){K(65472),K(17),w(8),K(L),K(m),w(3),w(1),w(17),w(0),w(2),w(17),w(1),w(3),w(17),w(1)}function Y(){K(65499),K(132),w(0);for(var m=0;m<64;m++)w(i[m]);w(1);for(var L=0;L<64;L++)w(o[L])}function N(){K(65476),K(418),w(0);for(var m=0;m<16;m++)w(P[m+1]);for(var L=0;L<=11;L++)w(G[L]);w(16);for(var T=0;T<16;T++)w(C[T+1]);for(var J=0;J<=161;J++)w(A[J]);w(1);for(var q=0;q<16;q++)w(Ft[q+1]);for(var X=0;X<=11;X++)w(U[X]);w(17);for(var rt=0;rt<16;rt++)w(x[rt+1]);for(var it=0;it<=161;it++)w(kt[it])}function F(m){if(typeof m>"u"||m.constructor!==Array)return;m.forEach((L)=>{if(typeof L!=="string")return;K(65534);var T=L.length;K(T+2);var J;for(J=0;J<T;J++)w(L.charCodeAt(J))})}function pt(){K(65498),K(12),w(3),w(1),w(0),w(2),w(17),w(3),w(17),w(0),w(63),w(0)}function Q(m,L,T,J,q){var X=q[0],rt=q[240],it,St=16,wt=63,M=64,j=ht(m,L);for(var Z=0;Z<M;++Z)l[O[Z]]=j[Z];var Et=l[0]-T;if(T=l[0],Et==0)z(J[0]);else it=32767+Et,z(J[d[it]]),z(g[it]);var _=63;for(;_>0&&l[_]==0;_--);if(_==0)return z(X),T;var D=1,at;while(D<=_){var W=D;for(;l[D]==0&&D<=_;++D);var st=D-W;if(st>=St){at=st>>4;for(var Ht=1;Ht<=at;++Ht)z(rt);st=st&15}it=32767+l[D],z(q[(st<<4)+d[it]]),z(g[it]),D++}if(_!=wt)z(X);return T}function V(){var m=String.fromCharCode;for(var L=0;L<256;L++)H[L]=m(L)}this.encode=function(m,L){var T=new Date().getTime();if(L)Zt(L);k=[],v=0,I=7,K(65496),ft(),F(m.comments),nt(m.exifBuffer),Y(),et(m.width,m.height),N(),pt();var J=0,q=0,X=0;v=0,I=7,this.encode.displayName="_encode_";var{data:rt,width:it,height:St}=m,wt=it*4,M=it*3,j,Z=0,Et,_,D,at,W,st,Ht,bt;while(Z<St){j=0;while(j<wt){at=wt*Z+j,W=at,st=-1,Ht=0;for(bt=0;bt<64;bt++){if(Ht=bt>>3,st=(bt&7)*4,W=at+Ht*wt+st,Z+Ht>=St)W-=wt*(Z+1+Ht-St);if(j+st>=wt)W-=j+st-wt+4;Et=rt[W++],_=rt[W++],D=rt[W++],E[bt]=(b[Et]+b[_+256>>0]+b[D+512>>0]>>16)-128,y[bt]=(b[Et+768>>0]+b[_+1024>>0]+b[D+1280>>0]>>16)-128,$[bt]=(b[Et+1280>>0]+b[_+1536>>0]+b[D+1792>>0]>>16)-128}J=Q(E,s,J,u,f),q=Q(y,c,q,h,a),X=Q($,c,X,h,a),j+=32}Z+=8}if(I>=0){var qt=[];qt[1]=I+1,qt[0]=(1<<I+1)-1,z(qt)}if(K(65497),typeof or>"u")return new Uint8Array(k);return Buffer.from(k);var nn,In};function Zt(m){if(m<=0)m=1;if(m>100)m=100;if(R==m)return;var L=0;if(m<50)L=Math.floor(5000/m);else L=Math.floor(200-m*2);dt(L),R=m}function xt(){var m=new Date().getTime();if(!t)t=50;V(),It(),ot(),tt(),Zt(t);var L=new Date().getTime()-m}xt()}if(typeof or<"u")or.exports=Yo;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].encode=Yo;function Yo(t,n){if(typeof n>"u")n=50;var e=new wa(n),r=e.encode(t,n);return{data:r,width:t.width,height:t.height}}});var Do=$t((R0,ti)=>{var Dr=function(){var n=new Int32Array([0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5,12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28,35,42,49,56,57,50,43,36,29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54,47,55,62,63]),e=4017,r=799,i=3406,o=2276,s=1567,c=3784,u=5793,h=2896;function f(){}function a(I,E){var y=0,$=[],H,b,R=16;while(R>0&&!I[R-1])R--;$.push({children:[],index:0});var O=$[0],P;for(H=0;H<R;H++){for(b=0;b<I[H];b++){O=$.pop(),O.children[O.index]=E[y];while(O.index>0){if($.length===0)throw Error("Could not recreate Huffman Table");O=$.pop()}O.index++,$.push(O);while($.length<=H)$.push(P={children:[],index:0}),O.children[O.index]=P.children,O=P;y++}if(H+1<R)$.push(P={children:[],index:0}),O.children[O.index]=P.children,O=P}return $[0].children}function g(I,E,y,$,H,b,R,O,P,G){var{precision:C,samplesPerLine:A,scanLines:Ft,mcusPerLine:U,progressive:x,maxH:kt,maxV:dt}=y,B=E,It=0,ot=0;function tt(){if(ot>0)return ot--,It>>ot&1;if(It=I[E++],It==255){var M=I[E++];if(M)throw Error("unexpected marker: "+(It<<8|M).toString(16))}return ot=7,It>>>7}function z(M){var j=M,Z;while((Z=tt())!==null){if(j=j[Z],typeof j==="number")return j;if(typeof j!=="object")throw Error("invalid huffman sequence")}return null}function w(M){var j=0;while(M>0){var Z=tt();if(Z===null)return;j=j<<1|Z,M--}return j}function K(M){var j=w(M);if(j>=1<<M-1)return j;return j+(-1<<M)+1}function ht(M,j){var Z=z(M.huffmanTableDC),Et=Z===0?0:K(Z);j[0]=M.pred+=Et;var _=1;while(_<64){var D=z(M.huffmanTableAC),at=D&15,W=D>>4;if(at===0){if(W<15)break;_+=16;continue}_+=W;var st=n[_];j[st]=K(at),_++}}function ft(M,j){var Z=z(M.huffmanTableDC),Et=Z===0?0:K(Z)<<P;j[0]=M.pred+=Et}function nt(M,j){j[0]|=tt()<<P}var et=0;function Y(M,j){if(et>0){et--;return}var Z=b,Et=R;while(Z<=Et){var _=z(M.huffmanTableAC),D=_&15,at=_>>4;if(D===0){if(at<15){et=w(at)+(1<<at)-1;break}Z+=16;continue}Z+=at;var W=n[Z];j[W]=K(D)*(1<<P),Z++}}var N=0,F;function pt(M,j){var Z=b,Et=R,_=0;while(Z<=Et){var D=n[Z],at=j[D]<0?-1:1;switch(N){case 0:var W=z(M.huffmanTableAC),st=W&15,_=W>>4;if(st===0)if(_<15)et=w(_)+(1<<_),N=4;else _=16,N=1;else{if(st!==1)throw Error("invalid ACn encoding");F=K(st),N=_?2:3}continue;case 1:case 2:if(j[D])j[D]+=(tt()<<P)*at;else if(_--,_===0)N=N==2?3:0;break;case 3:if(j[D])j[D]+=(tt()<<P)*at;else j[D]=F<<P,N=0;break;case 4:if(j[D])j[D]+=(tt()<<P)*at;break}Z++}if(N===4){if(et--,et===0)N=0}}function Q(M,j,Z,Et,_){var D=Z/U|0,at=Z%U,W=D*M.v+Et,st=at*M.h+_;if(M.blocks[W]===void 0&&G.tolerantDecoding)return;j(M,M.blocks[W][st])}function V(M,j,Z){var Et=Z/M.blocksPerLine|0,_=Z%M.blocksPerLine;if(M.blocks[Et]===void 0&&G.tolerantDecoding)return;j(M,M.blocks[Et][_])}var Zt=$.length,xt,m,L,T,J,q;if(x)if(b===0)q=O===0?ft:nt;else q=O===0?Y:pt;else q=ht;var X=0,rt,it;if(Zt==1)it=$[0].blocksPerLine*$[0].blocksPerColumn;else it=U*y.mcusPerColumn;if(!H)H=it;var St,wt;while(X<it){for(m=0;m<Zt;m++)$[m].pred=0;if(et=0,Zt==1){xt=$[0];for(J=0;J<H;J++)V(xt,q,X),X++}else for(J=0;J<H;J++){for(m=0;m<Zt;m++){xt=$[m],St=xt.h,wt=xt.v;for(L=0;L<wt;L++)for(T=0;T<St;T++)Q(xt,q,X,L,T)}if(X++,X===it)break}if(X===it)do{if(I[E]===255){if(I[E+1]!==0)break}E+=1}while(E<I.length-2);if(ot=0,rt=I[E]<<8|I[E+1],rt<65280)throw Error("marker was not found");if(rt>=65488&&rt<=65495)E+=2;else break}return E-B}function d(I,E){var y=[],$=E.blocksPerLine,H=E.blocksPerColumn,b=$<<3,R=new Int32Array(64),O=new Uint8Array(64);function P(B,It,ot){var tt=E.quantizationTable,z,w,K,ht,ft,nt,et,Y,N,F=ot,pt;for(pt=0;pt<64;pt++)F[pt]=B[pt]*tt[pt];for(pt=0;pt<8;++pt){var Q=8*pt;if(F[1+Q]==0&&F[2+Q]==0&&F[3+Q]==0&&F[4+Q]==0&&F[5+Q]==0&&F[6+Q]==0&&F[7+Q]==0){N=u*F[0+Q]+512>>10,F[0+Q]=N,F[1+Q]=N,F[2+Q]=N,F[3+Q]=N,F[4+Q]=N,F[5+Q]=N,F[6+Q]=N,F[7+Q]=N;continue}z=u*F[0+Q]+128>>8,w=u*F[4+Q]+128>>8,K=F[2+Q],ht=F[6+Q],ft=h*(F[1+Q]-F[7+Q])+128>>8,Y=h*(F[1+Q]+F[7+Q])+128>>8,nt=F[3+Q]<<4,et=F[5+Q]<<4,N=z-w+1>>1,z=z+w+1>>1,w=N,N=K*c+ht*s+128>>8,K=K*s-ht*c+128>>8,ht=N,N=ft-et+1>>1,ft=ft+et+1>>1,et=N,N=Y+nt+1>>1,nt=Y-nt+1>>1,Y=N,N=z-ht+1>>1,z=z+ht+1>>1,ht=N,N=w-K+1>>1,w=w+K+1>>1,K=N,N=ft*o+Y*i+2048>>12,ft=ft*i-Y*o+2048>>12,Y=N,N=nt*r+et*e+2048>>12,nt=nt*e-et*r+2048>>12,et=N,F[0+Q]=z+Y,F[7+Q]=z-Y,F[1+Q]=w+et,F[6+Q]=w-et,F[2+Q]=K+nt,F[5+Q]=K-nt,F[3+Q]=ht+ft,F[4+Q]=ht-ft}for(pt=0;pt<8;++pt){var V=pt;if(F[8+V]==0&&F[16+V]==0&&F[24+V]==0&&F[32+V]==0&&F[40+V]==0&&F[48+V]==0&&F[56+V]==0){N=u*ot[pt+0]+8192>>14,F[0+V]=N,F[8+V]=N,F[16+V]=N,F[24+V]=N,F[32+V]=N,F[40+V]=N,F[48+V]=N,F[56+V]=N;continue}z=u*F[0+V]+2048>>12,w=u*F[32+V]+2048>>12,K=F[16+V],ht=F[48+V],ft=h*(F[8+V]-F[56+V])+2048>>12,Y=h*(F[8+V]+F[56+V])+2048>>12,nt=F[24+V],et=F[40+V],N=z-w+1>>1,z=z+w+1>>1,w=N,N=K*c+ht*s+2048>>12,K=K*s-ht*c+2048>>12,ht=N,N=ft-et+1>>1,ft=ft+et+1>>1,et=N,N=Y+nt+1>>1,nt=Y-nt+1>>1,Y=N,N=z-ht+1>>1,z=z+ht+1>>1,ht=N,N=w-K+1>>1,w=w+K+1>>1,K=N,N=ft*o+Y*i+2048>>12,ft=ft*i-Y*o+2048>>12,Y=N,N=nt*r+et*e+2048>>12,nt=nt*e-et*r+2048>>12,et=N,F[0+V]=z+Y,F[56+V]=z-Y,F[8+V]=w+et,F[48+V]=w-et,F[16+V]=K+nt,F[40+V]=K-nt,F[24+V]=ht+ft,F[32+V]=ht-ft}for(pt=0;pt<64;++pt){var Zt=128+(F[pt]+8>>4);It[pt]=Zt<0?0:Zt>255?255:Zt}}v(b*H*8);var G,C;for(var A=0;A<H;A++){var Ft=A<<3;for(G=0;G<8;G++)y.push(new Uint8Array(b));for(var U=0;U<$;U++){P(E.blocks[A][U],O,R);var x=0,kt=U<<3;for(C=0;C<8;C++){var dt=y[Ft+C];for(G=0;G<8;G++)dt[kt+G]=O[x++]}}}return y}function p(I){return I<0?0:I>255?255:I}f.prototype={load:function(E){var y=new XMLHttpRequest;y.open("GET",E,!0),y.responseType="arraybuffer",y.onload=function(){var $=new Uint8Array(y.response||y.mozResponseArrayBuffer);if(this.parse($),this.onload)this.onload()}.bind(this),y.send(null)},parse:function(E){var y=this.opts.maxResolutionInMP*1000*1000,$=0,H=E.length;function b(){var W=E[$]<<8|E[$+1];return $+=2,W}function R(){var W=b(),st=E.subarray($,$+W-2);return $+=st.length,st}function O(W){var st=1,Ht=1,bt,qt;for(qt in W.components)if(W.components.hasOwnProperty(qt)){if(bt=W.components[qt],st<bt.h)st=bt.h;if(Ht<bt.v)Ht=bt.v}var nn=Math.ceil(W.samplesPerLine/8/st),In=Math.ceil(W.scanLines/8/Ht);for(qt in W.components)if(W.components.hasOwnProperty(qt)){bt=W.components[qt];var Kn=Math.ceil(Math.ceil(W.samplesPerLine/8)*bt.h/st),Jn=Math.ceil(Math.ceil(W.scanLines/8)*bt.v/Ht),ce=nn*bt.h,ue=In*bt.v,xe=ue*ce,he=[];v(xe*256);for(var fe=0;fe<ue;fe++){var ae=[];for(var ge=0;ge<ce;ge++)ae.push(new Int32Array(64));he.push(ae)}bt.blocksPerLine=Kn,bt.blocksPerColumn=Jn,bt.blocks=he}W.maxH=st,W.maxV=Ht,W.mcusPerLine=nn,W.mcusPerColumn=In}var P=null,G=null,C=null,A,Ft,U=[],x=[],kt=[],dt=[],B=b(),It=-1;if(this.comments=[],B!=65496)throw Error("SOI not found");B=b();while(B!=65497){var ot,tt,z;switch(B){case 65280:break;case 65504:case 65505:case 65506:case 65507:case 65508:case 65509:case 65510:case 65511:case 65512:case 65513:case 65514:case 65515:case 65516:case 65517:case 65518:case 65519:case 65534:var w=R();if(B===65534){var K=String.fromCharCode.apply(null,w);this.comments.push(K)}if(B===65504){if(w[0]===74&&w[1]===70&&w[2]===73&&w[3]===70&&w[4]===0)P={version:{major:w[5],minor:w[6]},densityUnits:w[7],xDensity:w[8]<<8|w[9],yDensity:w[10]<<8|w[11],thumbWidth:w[12],thumbHeight:w[13],thumbData:w.subarray(14,14+3*w[12]*w[13])}}if(B===65505){if(w[0]===69&&w[1]===120&&w[2]===105&&w[3]===102&&w[4]===0)this.exifBuffer=w.subarray(5,w.length)}if(B===65518){if(w[0]===65&&w[1]===100&&w[2]===111&&w[3]===98&&w[4]===101&&w[5]===0)G={version:w[6],flags0:w[7]<<8|w[8],flags1:w[9]<<8|w[10],transformCode:w[11]}}break;case 65499:var ht=b(),ft=ht+$-2;while($<ft){var nt=E[$++];v(256);var et=new Int32Array(64);if(nt>>4===0)for(tt=0;tt<64;tt++){var Y=n[tt];et[Y]=E[$++]}else if(nt>>4===1)for(tt=0;tt<64;tt++){var Y=n[tt];et[Y]=b()}else throw Error("DQT: invalid table spec");U[nt&15]=et}break;case 65472:case 65473:case 65474:b(),A={},A.extended=B===65473,A.progressive=B===65474,A.precision=E[$++],A.scanLines=b(),A.samplesPerLine=b(),A.components={},A.componentsOrder=[];var N=A.scanLines*A.samplesPerLine;if(N>y){var F=Math.ceil((N-y)/1e6);throw Error(`maxResolutionInMP limit exceeded by ${F}MP`)}var pt=E[$++],Q,V=0,Zt=0;for(ot=0;ot<pt;ot++){Q=E[$];var xt=E[$+1]>>4,m=E[$+1]&15,L=E[$+2];if(xt<=0||m<=0)throw Error("Invalid sampling factor, expected values above 0");A.componentsOrder.push(Q),A.components[Q]={h:xt,v:m,quantizationIdx:L},$+=3}O(A),x.push(A);break;case 65476:var T=b();for(ot=2;ot<T;){var J=E[$++],q=new Uint8Array(16),X=0;for(tt=0;tt<16;tt++,$++)X+=q[tt]=E[$];v(16+X);var rt=new Uint8Array(X);for(tt=0;tt<X;tt++,$++)rt[tt]=E[$];ot+=17+X,(J>>4===0?dt:kt)[J&15]=a(q,rt)}break;case 65501:b(),Ft=b();break;case 65500:b(),b();break;case 65498:var it=b(),St=E[$++],wt=[],M;for(ot=0;ot<St;ot++){M=A.components[E[$++]];var j=E[$++];M.huffmanTableDC=dt[j>>4],M.huffmanTableAC=kt[j&15],wt.push(M)}var Z=E[$++],Et=E[$++],_=E[$++],D=g(E,$,A,wt,Ft,Z,Et,_>>4,_&15,this.opts);$+=D;break;case 65535:if(E[$]!==255)$--;break;default:if(E[$-3]==255&&E[$-2]>=192&&E[$-2]<=254){$-=3;break}else if(B===224||B==225){if(It!==-1)throw Error(`first unknown JPEG marker at offset ${It.toString(16)}, second unknown JPEG marker ${B.toString(16)} at offset ${($-1).toString(16)}`);It=$-1;let W=b();if(E[$+W-2]===255){$+=W-2;break}}throw Error("unknown JPEG marker "+B.toString(16))}B=b()}if(x.length!=1)throw Error("only single frame JPEGs supported");for(var ot=0;ot<x.length;ot++){var at=x[ot].components;for(var tt in at)at[tt].quantizationTable=U[at[tt].quantizationIdx],delete at[tt].quantizationIdx}this.width=A.samplesPerLine,this.height=A.scanLines,this.jfif=P,this.adobe=G,this.components=[];for(var ot=0;ot<A.componentsOrder.length;ot++){var M=A.components[A.componentsOrder[ot]];this.components.push({lines:d(A,M),scaleX:M.h/A.maxH,scaleY:M.v/A.maxV})}},getData:function(E,y){var $=this.width/E,H=this.height/y,b,R,O,P,G,C,A,Ft,U,x,kt=0,dt,B,It,ot,tt,z,w,K,ht,ft,nt,et=E*y*this.components.length;v(et);var Y=new Uint8Array(et);switch(this.components.length){case 1:b=this.components[0];for(x=0;x<y;x++){G=b.lines[0|x*b.scaleY*H];for(U=0;U<E;U++)dt=G[0|U*b.scaleX*$],Y[kt++]=dt}break;case 2:b=this.components[0],R=this.components[1];for(x=0;x<y;x++){G=b.lines[0|x*b.scaleY*H],C=R.lines[0|x*R.scaleY*H];for(U=0;U<E;U++)dt=G[0|U*b.scaleX*$],Y[kt++]=dt,dt=C[0|U*R.scaleX*$],Y[kt++]=dt}break;case 3:if(nt=!0,this.adobe&&this.adobe.transformCode)nt=!0;else if(typeof this.opts.colorTransform<"u")nt=!!this.opts.colorTransform;b=this.components[0],R=this.components[1],O=this.components[2];for(x=0;x<y;x++){G=b.lines[0|x*b.scaleY*H],C=R.lines[0|x*R.scaleY*H],A=O.lines[0|x*O.scaleY*H];for(U=0;U<E;U++){if(!nt)K=G[0|U*b.scaleX*$],ht=C[0|U*R.scaleX*$],ft=A[0|U*O.scaleX*$];else dt=G[0|U*b.scaleX*$],B=C[0|U*R.scaleX*$],It=A[0|U*O.scaleX*$],K=p(dt+1.402*(It-128)),ht=p(dt-0.3441363*(B-128)-0.71413636*(It-128)),ft=p(dt+1.772*(B-128));Y[kt++]=K,Y[kt++]=ht,Y[kt++]=ft}}break;case 4:if(!this.adobe)throw Error("Unsupported color mode (4 components)");if(nt=!1,this.adobe&&this.adobe.transformCode)nt=!0;else if(typeof this.opts.colorTransform<"u")nt=!!this.opts.colorTransform;b=this.components[0],R=this.components[1],O=this.components[2],P=this.components[3];for(x=0;x<y;x++){G=b.lines[0|x*b.scaleY*H],C=R.lines[0|x*R.scaleY*H],A=O.lines[0|x*O.scaleY*H],Ft=P.lines[0|x*P.scaleY*H];for(U=0;U<E;U++){if(!nt)tt=G[0|U*b.scaleX*$],z=C[0|U*R.scaleX*$],w=A[0|U*O.scaleX*$],ot=Ft[0|U*P.scaleX*$];else dt=G[0|U*b.scaleX*$],B=C[0|U*R.scaleX*$],It=A[0|U*O.scaleX*$],ot=Ft[0|U*P.scaleX*$],tt=255-p(dt+1.402*(It-128)),z=255-p(dt-0.3441363*(B-128)-0.71413636*(It-128)),w=255-p(dt+1.772*(B-128));Y[kt++]=255-tt,Y[kt++]=255-z,Y[kt++]=255-w,Y[kt++]=255-ot}}break;default:throw Error("Unsupported color mode")}return Y},copyToImageData:function(E,y){var{width:$,height:H,data:b}=E,R=this.getData($,H),O=0,P=0,G,C,A,Ft,U,x,kt,dt,B;switch(this.components.length){case 1:for(C=0;C<H;C++)for(G=0;G<$;G++)if(A=R[O++],b[P++]=A,b[P++]=A,b[P++]=A,y)b[P++]=255;break;case 3:for(C=0;C<H;C++)for(G=0;G<$;G++)if(kt=R[O++],dt=R[O++],B=R[O++],b[P++]=kt,b[P++]=dt,b[P++]=B,y)b[P++]=255;break;case 4:for(C=0;C<H;C++)for(G=0;G<$;G++)if(U=R[O++],x=R[O++],A=R[O++],Ft=R[O++],kt=255-p(U*(1-Ft/255)+Ft),dt=255-p(x*(1-Ft/255)+Ft),B=255-p(A*(1-Ft/255)+Ft),b[P++]=kt,b[P++]=dt,b[P++]=B,y)b[P++]=255;break;default:throw Error("Unsupported color mode")}}};var l=0,k=0;function v(I=0){var E=l+I;if(E>k){var y=Math.ceil((E-k)/1024/1024);throw Error(`maxMemoryUsageInMB limit exceeded by at least ${y}MB`)}l=E}return f.resetMaxMemoryUsage=function(I){l=0,k=I},f.getBytesAllocated=function(){return l},f.requestMemoryAllocation=v,f}();if(typeof ti<"u")ti.exports=Bo;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].decode=Bo;function Bo(t,n={}){var e={colorTransform:void 0,useTArray:!1,formatAsRGBA:!0,tolerantDecoding:!0,maxResolutionInMP:100,maxMemoryUsageInMB:512},r={...e,...n},i=new Uint8Array(t),o=new Dr;o.opts=r,Dr.resetMaxMemoryUsage(r.maxMemoryUsageInMB*1024*1024),o.parse(i);var s=r.formatAsRGBA?4:3,c=o.width*o.height*s;try{Dr.requestMemoryAllocation(c);var u={width:o.width,height:o.height,exifBuffer:o.exifBuffer,data:r.useTArray?new Uint8Array(c):Buffer.alloc(c)};if(o.comments.length>0)u.comments=o.comments}catch(h){if(h instanceof RangeError)throw Error("Could not allocate enough memory for the image. Required: "+c);if(h instanceof ReferenceError){if(h.message==="Buffer is not defined")throw Error("Buffer is not globally defined in this environment. Consider setting useTArray to true")}throw h}return o.copyToImageData(u,r.formatAsRGBA),u}});var ns=$t((G0,ts)=>{var $a=xo(),ba=Do();ts.exports={encode:$a,decode:ba}});var ni=$t((L0,rs)=>{var ka=jt("util"),es=jt("stream"),Dt=rs.exports=function(){es.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};ka.inherits(Dt,es);Dt.prototype.read=function(t,n){this._reads.push({length:Math.abs(t),allowLess:t<0,func:n}),process.nextTick(function(){if(this._process(),this._paused&&this._reads&&this._reads.length>0)this._paused=!1,this.emit("drain")}.bind(this))};Dt.prototype.write=function(t,n){if(!this.writable)return this.emit("error",Error("Stream not writable")),!1;let e;if(Buffer.isBuffer(t))e=t;else e=Buffer.from(t,n||this._encoding);if(this._buffers.push(e),this._buffered+=e.length,this._process(),this._reads&&this._reads.length===0)this._paused=!0;return this.writable&&!this._paused};Dt.prototype.end=function(t,n){if(t)this.write(t,n);if(this.writable=!1,!this._buffers)return;if(this._buffers.length===0)this._end();else this._buffers.push(null),this._process()};Dt.prototype.destroySoon=Dt.prototype.end;Dt.prototype._end=function(){if(this._reads.length>0)this.emit("error",Error("Unexpected end of input"));this.destroy()};Dt.prototype.destroy=function(){if(!this._buffers)return;this.writable=!1,this._reads=null,this._buffers=null,this.emit("close")};Dt.prototype._processReadAllowingLess=function(t){this._reads.shift();let n=this._buffers[0];if(n.length>t.length)this._buffered-=t.length,this._buffers[0]=n.slice(t.length),t.func.call(this,n.slice(0,t.length));else this._buffered-=n.length,this._buffers.shift(),t.func.call(this,n)};Dt.prototype._processRead=function(t){this._reads.shift();let n=0,e=0,r=Buffer.alloc(t.length);while(n<t.length){let i=this._buffers[e++],o=Math.min(i.length,t.length-n);if(i.copy(r,n,0,o),n+=o,o!==i.length)this._buffers[--e]=i.slice(o)}if(e>0)this._buffers.splice(0,e);this._buffered-=t.length,t.func.call(this,r)};Dt.prototype._process=function(){try{while(this._buffered>0&&this._reads&&this._reads.length>0){let t=this._reads[0];if(t.allowLess)this._processReadAllowingLess(t);else if(this._buffered>=t.length)this._processRead(t);else break}if(this._buffers&&!this.writable)this._end()}catch(t){this.emit("error",t)}}});var ei=$t((Ea)=>{var bn=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];Ea.getImagePasses=function(t,n){let e=[],r=t%8,i=n%8,o=(t-r)/8,s=(n-i)/8;for(let c=0;c<bn.length;c++){let u=bn[c],h=o*u.x.length,f=s*u.y.length;for(let a=0;a<u.x.length;a++)if(u.x[a]<r)h++;else break;for(let a=0;a<u.y.length;a++)if(u.y[a]<i)f++;else break;if(h>0&&f>0)e.push({width:h,height:f,index:c})}return e};Ea.getInterlaceIterator=function(t){return function(n,e,r){let i=n%bn[r].x.length,o=(n-i)/bn[r].x.length*8+bn[r].x[i],s=e%bn[r].y.length,c=(e-s)/bn[r].y.length*8+bn[r].y[s];return o*4+c*t*4}}});var ri=$t((K0,is)=>{is.exports=function(n,e,r){let i=n+e-r,o=Math.abs(i-n),s=Math.abs(i-e),c=Math.abs(i-r);if(o<=s&&o<=c)return n;if(s<=c)return e;return r}});var ii=$t((J0,ss)=>{var ya=ei(),Sa=ri();function os(t,n,e){let r=t*n;if(e!==8)r=Math.ceil(r/(8/e));return r}var Un=ss.exports=function(t,n){let{width:e,height:r,interlace:i,bpp:o,depth:s}=t;if(this.read=n.read,this.write=n.write,this.complete=n.complete,this._imageIndex=0,this._images=[],i){let c=ya.getImagePasses(e,r);for(let u=0;u<c.length;u++)this._images.push({byteWidth:os(c[u].width,o,s),height:c[u].height,lineIndex:0})}else this._images.push({byteWidth:os(e,o,s),height:r,lineIndex:0});if(s===8)this._xComparison=o;else if(s===16)this._xComparison=o*2;else this._xComparison=1};Un.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Un.prototype._unFilterType1=function(t,n,e){let r=this._xComparison,i=r-1;for(let o=0;o<e;o++){let s=t[1+o],c=o>i?n[o-r]:0;n[o]=s+c}};Un.prototype._unFilterType2=function(t,n,e){let r=this._lastLine;for(let i=0;i<e;i++){let o=t[1+i],s=r?r[i]:0;n[i]=o+s}};Un.prototype._unFilterType3=function(t,n,e){let r=this._xComparison,i=r-1,o=this._lastLine;for(let s=0;s<e;s++){let c=t[1+s],u=o?o[s]:0,h=s>i?n[s-r]:0,f=Math.floor((h+u)/2);n[s]=c+f}};Un.prototype._unFilterType4=function(t,n,e){let r=this._xComparison,i=r-1,o=this._lastLine;for(let s=0;s<e;s++){let c=t[1+s],u=o?o[s]:0,h=s>i?n[s-r]:0,f=s>i&&o?o[s-r]:0,a=Sa(h,u,f);n[s]=c+a}};Un.prototype._reverseFilterLine=function(t){let n=t[0],e,r=this._images[this._imageIndex],i=r.byteWidth;if(n===0)e=t.slice(1,i+1);else switch(e=Buffer.alloc(i),n){case 1:this._unFilterType1(t,e,i);break;case 2:this._unFilterType2(t,e,i);break;case 3:this._unFilterType3(t,e,i);break;case 4:this._unFilterType4(t,e,i);break;default:throw Error("Unrecognised filter type - "+n)}if(this.write(e),r.lineIndex++,r.lineIndex>=r.height)this._lastLine=null,this._imageIndex++,r=this._images[this._imageIndex];else this._lastLine=e;if(r)this.read(r.byteWidth+1,this._reverseFilterLine.bind(this));else this._lastLine=null,this.complete()}});var hs=$t((A0,us)=>{var Fa=jt("util"),cs=ni(),Ia=ii(),Na=us.exports=function(t){cs.call(this);let n=[],e=this;this._filter=new Ia(t,{read:this.read.bind(this),write:function(r){n.push(r)},complete:function(){e.emit("complete",Buffer.concat(n))}}),this._filter.start()};Fa.inherits(Na,cs)});var Tn=$t((U0,fs)=>{fs.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 ci=$t((T0,as)=>{var oi=[];(function(){for(let t=0;t<256;t++){let n=t;for(let e=0;e<8;e++)if(n&1)n=3988292384^n>>>1;else n=n>>>1;oi[t]=n}})();var si=as.exports=function(){this._crc=-1};si.prototype.write=function(t){for(let n=0;n<t.length;n++)this._crc=oi[(this._crc^t[n])&255]^this._crc>>>8;return!0};si.prototype.crc32=function(){return this._crc^-1};si.crc32=function(t){let n=-1;for(let e=0;e<t.length;e++)n=oi[(n^t[e])&255]^n>>>8;return n^-1}});var ui=$t((W0,gs)=>{var Nt=Tn(),Oa=ci(),Ot=gs.exports=function(t,n){this._options=t,t.checkCRC=t.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[Nt.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[Nt.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[Nt.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[Nt.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[Nt.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[Nt.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=n.read,this.error=n.error,this.metadata=n.metadata,this.gamma=n.gamma,this.transColor=n.transColor,this.palette=n.palette,this.parsed=n.parsed,this.inflateData=n.inflateData,this.finished=n.finished,this.simpleTransparency=n.simpleTransparency,this.headersFinished=n.headersFinished||function(){}};Ot.prototype.start=function(){this.read(Nt.PNG_SIGNATURE.length,this._parseSignature.bind(this))};Ot.prototype._parseSignature=function(t){let n=Nt.PNG_SIGNATURE;for(let e=0;e<n.length;e++)if(t[e]!==n[e]){this.error(Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};Ot.prototype._parseChunkBegin=function(t){let n=t.readUInt32BE(0),e=t.readUInt32BE(4),r="";for(let o=4;o<8;o++)r+=String.fromCharCode(t[o]);let i=Boolean(t[4]&32);if(!this._hasIHDR&&e!==Nt.TYPE_IHDR){this.error(Error("Expected IHDR on beggining"));return}if(this._crc=new Oa,this._crc.write(Buffer.from(r)),this._chunks[e])return this._chunks[e](n);if(!i){this.error(Error("Unsupported critical chunk type "+r));return}this.read(n+4,this._skipChunk.bind(this))};Ot.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};Ot.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};Ot.prototype._parseChunkEnd=function(t){let n=t.readInt32BE(0),e=this._crc.crc32();if(this._options.checkCRC&&e!==n){this.error(Error("Crc error - "+n+" - "+e));return}if(!this._hasIEND)this.read(8,this._parseChunkBegin.bind(this))};Ot.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};Ot.prototype._parseIHDR=function(t){this._crc.write(t);let n=t.readUInt32BE(0),e=t.readUInt32BE(4),r=t[8],i=t[9],o=t[10],s=t[11],c=t[12];if(r!==8&&r!==4&&r!==2&&r!==1&&r!==16){this.error(Error("Unsupported bit depth "+r));return}if(!(i in Nt.COLORTYPE_TO_BPP_MAP)){this.error(Error("Unsupported color type"));return}if(o!==0){this.error(Error("Unsupported compression method"));return}if(s!==0){this.error(Error("Unsupported filter method"));return}if(c!==0&&c!==1){this.error(Error("Unsupported interlace method"));return}this._colorType=i;let u=Nt.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:n,height:e,depth:r,interlace:Boolean(c),palette:Boolean(i&Nt.COLORTYPE_PALETTE),color:Boolean(i&Nt.COLORTYPE_COLOR),alpha:Boolean(i&Nt.COLORTYPE_ALPHA),bpp:u,colorType:i}),this._handleChunkEnd()};Ot.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};Ot.prototype._parsePLTE=function(t){this._crc.write(t);let n=Math.floor(t.length/3);for(let e=0;e<n;e++)this._palette.push([t[e*3],t[e*3+1],t[e*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};Ot.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};Ot.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===Nt.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(Error("Transparency chunk must be after palette"));return}if(t.length>this._palette.length){this.error(Error("More transparent colors than palette size"));return}for(let n=0;n<t.length;n++)this._palette[n][3]=t[n];this.palette(this._palette)}if(this._colorType===Nt.COLORTYPE_GRAYSCALE)this.transColor([t.readUInt16BE(0)]);if(this._colorType===Nt.COLORTYPE_COLOR)this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]);this._handleChunkEnd()};Ot.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};Ot.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/Nt.GAMMA_DIVISION),this._handleChunkEnd()};Ot.prototype._handleIDAT=function(t){if(!this._emittedHeadersFinished)this._emittedHeadersFinished=!0,this.headersFinished();this.read(-t,this._parseIDAT.bind(this,t))};Ot.prototype._parseIDAT=function(t,n){if(this._crc.write(n),this._colorType===Nt.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw Error("Expected palette not found");this.inflateData(n);let e=t-n.length;if(e>0)this._handleIDAT(e);else this._handleChunkEnd()};Ot.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};Ot.prototype._parseIEND=function(t){if(this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished)this.finished()}});var hi=$t((Pa)=>{var ls=ei(),Ha=[function(){},function(t,n,e,r){if(r===n.length)throw Error("Ran out of data");let i=n[r];t[e]=i,t[e+1]=i,t[e+2]=i,t[e+3]=255},function(t,n,e,r){if(r+1>=n.length)throw Error("Ran out of data");let i=n[r];t[e]=i,t[e+1]=i,t[e+2]=i,t[e+3]=n[r+1]},function(t,n,e,r){if(r+2>=n.length)throw Error("Ran out of data");t[e]=n[r],t[e+1]=n[r+1],t[e+2]=n[r+2],t[e+3]=255},function(t,n,e,r){if(r+3>=n.length)throw Error("Ran out of data");t[e]=n[r],t[e+1]=n[r+1],t[e+2]=n[r+2],t[e+3]=n[r+3]}],ja=[function(){},function(t,n,e,r){let i=n[0];t[e]=i,t[e+1]=i,t[e+2]=i,t[e+3]=r},function(t,n,e){let r=n[0];t[e]=r,t[e+1]=r,t[e+2]=r,t[e+3]=n[1]},function(t,n,e,r){t[e]=n[0],t[e+1]=n[1],t[e+2]=n[2],t[e+3]=r},function(t,n,e){t[e]=n[0],t[e+1]=n[1],t[e+2]=n[2],t[e+3]=n[3]}];function Ra(t,n){let e=[],r=0;function i(){if(r===t.length)throw Error("Ran out of data");let o=t[r];r++;let s,c,u,h,f,a,g,d;switch(n){default:throw Error("unrecognised depth");case 16:g=t[r],r++,e.push((o<<8)+g);break;case 4:g=o&15,d=o>>4,e.push(d,g);break;case 2:f=o&3,a=o>>2&3,g=o>>4&3,d=o>>6&3,e.push(d,g,a,f);break;case 1:s=o&1,c=o>>1&1,u=o>>2&1,h=o>>3&1,f=o>>4&1,a=o>>5&1,g=o>>6&1,d=o>>7&1,e.push(d,g,a,f,h,u,c,s);break}}return{get:function(o){while(e.length<o)i();let s=e.slice(0,o);return e=e.slice(o),s},resetAfterLine:function(){e.length=0},end:function(){if(r!==t.length)throw Error("extra data found")}}}function Ga(t,n,e,r,i,o){let{width:s,height:c,index:u}=t;for(let h=0;h<c;h++)for(let f=0;f<s;f++){let a=e(f,h,u);Ha[r](n,i,a,o),o+=r}return o}function La(t,n,e,r,i,o){let{width:s,height:c,index:u}=t;for(let h=0;h<c;h++){for(let f=0;f<s;f++){let a=i.get(r),g=e(f,h,u);ja[r](n,a,g,o)}i.resetAfterLine()}}Pa.dataToBitMap=function(t,n){let{width:e,height:r,depth:i,bpp:o,interlace:s}=n,c;if(i!==8)c=Ra(t,i);let u;if(i<=8)u=Buffer.alloc(e*r*4);else u=new Uint16Array(e*r*4);let h=Math.pow(2,i)-1,f=0,a,g;if(s)a=ls.getImagePasses(e,r),g=ls.getInterlaceIterator(e,r);else{let d=0;g=function(){let p=d;return d+=4,p},a=[{width:e,height:r}]}for(let d=0;d<a.length;d++)if(i===8)f=Ga(a[d],u,g,o,t,f);else La(a[d],u,g,o,c,h);if(i===8){if(f!==t.length)throw Error("extra data found")}else c.end();return u}});var fi=$t((Z0,ds)=>{function Ja(t,n,e,r,i){let o=0;for(let s=0;s<r;s++)for(let c=0;c<e;c++){let u=i[t[o]];if(!u)throw Error("index "+t[o]+" not in palette");for(let h=0;h<4;h++)n[o+h]=u[h];o+=4}}function Aa(t,n,e,r,i){let o=0;for(let s=0;s<r;s++)for(let c=0;c<e;c++){let u=!1;if(i.length===1){if(i[0]===t[o])u=!0}else if(i[0]===t[o]&&i[1]===t[o+1]&&i[2]===t[o+2])u=!0;if(u)for(let h=0;h<4;h++)n[o+h]=0;o+=4}}function Ua(t,n,e,r,i){let o=255,s=Math.pow(2,i)-1,c=0;for(let u=0;u<r;u++)for(let h=0;h<e;h++){for(let f=0;f<4;f++)n[c+f]=Math.floor(t[c+f]*o/s+0.5);c+=4}}ds.exports=function(t,n,e=!1){let{depth:r,width:i,height:o,colorType:s,transColor:c,palette:u}=n,h=t;if(s===3)Ja(t,h,i,o,u);else{if(c)Aa(t,h,i,o,c);if(r!==8&&!e){if(r===16)h=Buffer.alloc(i*o*4);Ua(t,h,i,o,r)}}return h}});var ws=$t((q0,ps)=>{var Ta=jt("util"),ai=jt("zlib"),ms=ni(),Wa=hs(),Qa=ui(),Za=hi(),qa=fi(),rn=ps.exports=function(t){ms.call(this),this._parser=new Qa(t,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,"gamma"),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=t,this.writable=!0,this._parser.start()};Ta.inherits(rn,ms);rn.prototype._handleError=function(t){if(this.emit("error",t),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy)this._inflate.destroy();if(this._filter)this._filter.destroy(),this._filter.on("error",function(){});this.errord=!0};rn.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=ai.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let e=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,r=Math.max(e,ai.Z_MIN_CHUNK);this._inflate=ai.createInflate({chunkSize:r});let i=e,o=this.emit.bind(this,"error");this._inflate.on("error",function(c){if(!i)return;o(c)}),this._filter.on("complete",this._complete.bind(this));let s=this._filter.write.bind(this._filter);this._inflate.on("data",function(c){if(!i)return;if(c.length>i)c=c.slice(0,i);i-=c.length,s(c)}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};rn.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new Wa(this._bitmapInfo)};rn.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};rn.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};rn.prototype._simpleTransparency=function(){this._metaData.alpha=!0};rn.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};rn.prototype._finished=function(){if(this.errord)return;if(!this._inflate)this.emit("error","No Inflate block");else this._inflate.end()};rn.prototype._complete=function(t){if(this.errord)return;let n;try{let e=Za.dataToBitMap(t,this._bitmapInfo);n=qa(e,this._bitmapInfo,this._options.skipRescale),e=null}catch(e){this._handleError(e);return}this.emit("parsed",n)}});var bs=$t((X0,$s)=>{var Xt=Tn();$s.exports=function(t,n,e,r){let i=[Xt.COLORTYPE_COLOR_ALPHA,Xt.COLORTYPE_ALPHA].indexOf(r.colorType)!==-1;if(r.colorType===r.inputColorType){let p=function(){let l=new ArrayBuffer(2);return new DataView(l).setInt16(0,256,!0),new Int16Array(l)[0]!==256}();if(r.bitDepth===8||r.bitDepth===16&&p)return t}let o=r.bitDepth!==16?t:new Uint16Array(t.buffer),s=255,c=Xt.COLORTYPE_TO_BPP_MAP[r.inputColorType];if(c===4&&!r.inputHasAlpha)c=3;let u=Xt.COLORTYPE_TO_BPP_MAP[r.colorType];if(r.bitDepth===16)s=65535,u*=2;let h=Buffer.alloc(n*e*u),f=0,a=0,g=r.bgColor||{};if(g.red===void 0)g.red=s;if(g.green===void 0)g.green=s;if(g.blue===void 0)g.blue=s;function d(){let p,l,k,v=s;switch(r.inputColorType){case Xt.COLORTYPE_COLOR_ALPHA:v=o[f+3],p=o[f],l=o[f+1],k=o[f+2];break;case Xt.COLORTYPE_COLOR:p=o[f],l=o[f+1],k=o[f+2];break;case Xt.COLORTYPE_ALPHA:v=o[f+1],p=o[f],l=p,k=p;break;case Xt.COLORTYPE_GRAYSCALE:p=o[f],l=p,k=p;break;default:throw Error("input color type:"+r.inputColorType+" is not supported at present")}if(r.inputHasAlpha){if(!i)v/=s,p=Math.min(Math.max(Math.round((1-v)*g.red+v*p),0),s),l=Math.min(Math.max(Math.round((1-v)*g.green+v*l),0),s),k=Math.min(Math.max(Math.round((1-v)*g.blue+v*k),0),s)}return{red:p,green:l,blue:k,alpha:v}}for(let p=0;p<e;p++)for(let l=0;l<n;l++){let k=d(o,f);switch(r.colorType){case Xt.COLORTYPE_COLOR_ALPHA:case Xt.COLORTYPE_COLOR:if(r.bitDepth===8){if(h[a]=k.red,h[a+1]=k.green,h[a+2]=k.blue,i)h[a+3]=k.alpha}else if(h.writeUInt16BE(k.red,a),h.writeUInt16BE(k.green,a+2),h.writeUInt16BE(k.blue,a+4),i)h.writeUInt16BE(k.alpha,a+6);break;case Xt.COLORTYPE_ALPHA:case Xt.COLORTYPE_GRAYSCALE:{let v=(k.red+k.green+k.blue)/3;if(r.bitDepth===8){if(h[a]=v,i)h[a+1]=k.alpha}else if(h.writeUInt16BE(v,a),i)h.writeUInt16BE(k.alpha,a+2);break}default:throw Error("unrecognised color Type "+r.colorType)}f+=c,a+=u}return h}});var Ms=$t((_0,Es)=>{var ks=ri();function Xa(t,n,e,r,i){for(let o=0;o<e;o++)r[i+o]=t[n+o]}function _a(t,n,e){let r=0,i=n+e;for(let o=n;o<i;o++)r+=Math.abs(t[o]);return r}function Ca(t,n,e,r,i,o){for(let s=0;s<e;s++){let c=s>=o?t[n+s-o]:0,u=t[n+s]-c;r[i+s]=u}}function za(t,n,e,r){let i=0;for(let o=0;o<e;o++){let s=o>=r?t[n+o-r]:0,c=t[n+o]-s;i+=Math.abs(c)}return i}function Ya(t,n,e,r,i){for(let o=0;o<e;o++){let s=n>0?t[n+o-e]:0,c=t[n+o]-s;r[i+o]=c}}function Va(t,n,e){let r=0,i=n+e;for(let o=n;o<i;o++){let s=n>0?t[o-e]:0,c=t[o]-s;r+=Math.abs(c)}return r}function xa(t,n,e,r,i,o){for(let s=0;s<e;s++){let c=s>=o?t[n+s-o]:0,u=n>0?t[n+s-e]:0,h=t[n+s]-(c+u>>1);r[i+s]=h}}function Ba(t,n,e,r){let i=0;for(let o=0;o<e;o++){let s=o>=r?t[n+o-r]:0,c=n>0?t[n+o-e]:0,u=t[n+o]-(s+c>>1);i+=Math.abs(u)}return i}function Da(t,n,e,r,i,o){for(let s=0;s<e;s++){let c=s>=o?t[n+s-o]:0,u=n>0?t[n+s-e]:0,h=n>0&&s>=o?t[n+s-(e+o)]:0,f=t[n+s]-ks(c,u,h);r[i+s]=f}}function tg(t,n,e,r){let i=0;for(let o=0;o<e;o++){let s=o>=r?t[n+o-r]:0,c=n>0?t[n+o-e]:0,u=n>0&&o>=r?t[n+o-(e+r)]:0,h=t[n+o]-ks(s,c,u);i+=Math.abs(h)}return i}var ng={0:Xa,1:Ca,2:Ya,3:xa,4:Da},eg={0:_a,1:za,2:Va,3:Ba,4:tg};Es.exports=function(t,n,e,r,i){let o;if(!("filterType"in r)||r.filterType===-1)o=[0,1,2,3,4];else if(typeof r.filterType==="number")o=[r.filterType];else throw Error("unrecognised filter types");if(r.bitDepth===16)i*=2;let s=n*i,c=0,u=0,h=Buffer.alloc((s+1)*e),f=o[0];for(let a=0;a<e;a++){if(o.length>1){let g=1/0;for(let d=0;d<o.length;d++){let p=eg[o[d]](t,u,s,i);if(p<g)f=o[d],g=p}}h[c]=f,c++,ng[f](t,u,s,h,c,i),c+=s,u+=s}return h}});var gi=$t((C0,vs)=>{var Gt=Tn(),rg=ci(),ig=bs(),og=Ms(),sg=jt("zlib"),kn=vs.exports=function(t){if(this._options=t,t.deflateChunkSize=t.deflateChunkSize||32768,t.deflateLevel=t.deflateLevel!=null?t.deflateLevel:9,t.deflateStrategy=t.deflateStrategy!=null?t.deflateStrategy:3,t.inputHasAlpha=t.inputHasAlpha!=null?t.inputHasAlpha:!0,t.deflateFactory=t.deflateFactory||sg.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType==="number"?t.colorType:Gt.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType==="number"?t.inputColorType:Gt.COLORTYPE_COLOR_ALPHA,[Gt.COLORTYPE_GRAYSCALE,Gt.COLORTYPE_COLOR,Gt.COLORTYPE_COLOR_ALPHA,Gt.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw Error("option color type:"+t.colorType+" is not supported at present");if([Gt.COLORTYPE_GRAYSCALE,Gt.COLORTYPE_COLOR,Gt.COLORTYPE_COLOR_ALPHA,Gt.COLORTYPE_ALPHA].indexOf(t.inputColorType)===-1)throw Error("option input color type:"+t.inputColorType+" is not supported at present");if(t.bitDepth!==8&&t.bitDepth!==16)throw Error("option bit depth:"+t.bitDepth+" is not supported at present")};kn.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};kn.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};kn.prototype.filterData=function(t,n,e){let r=ig(t,n,e,this._options),i=Gt.COLORTYPE_TO_BPP_MAP[this._options.colorType];return og(r,n,e,this._options,i)};kn.prototype._packChunk=function(t,n){let e=n?n.length:0,r=Buffer.alloc(e+12);if(r.writeUInt32BE(e,0),r.writeUInt32BE(t,4),n)n.copy(r,8);return r.writeInt32BE(rg.crc32(r.slice(4,r.length-4)),r.length-4),r};kn.prototype.packGAMA=function(t){let n=Buffer.alloc(4);return n.writeUInt32BE(Math.floor(t*Gt.GAMMA_DIVISION),0),this._packChunk(Gt.TYPE_gAMA,n)};kn.prototype.packIHDR=function(t,n){let e=Buffer.alloc(13);return e.writeUInt32BE(t,0),e.writeUInt32BE(n,4),e[8]=this._options.bitDepth,e[9]=this._options.colorType,e[10]=0,e[11]=0,e[12]=0,this._packChunk(Gt.TYPE_IHDR,e)};kn.prototype.packIDAT=function(t){return this._packChunk(Gt.TYPE_IDAT,t)};kn.prototype.packIEND=function(){return this._packChunk(Gt.TYPE_IEND,null)}});var Is=$t((z0,Fs)=>{var cg=jt("util"),ys=jt("stream"),ug=Tn(),hg=gi(),Ss=Fs.exports=function(t){ys.call(this);let n=t||{};this._packer=new hg(n),this._deflate=this._packer.createDeflate(),this.readable=!0};cg.inherits(Ss,ys);Ss.prototype.pack=function(t,n,e,r){if(this.emit("data",Buffer.from(ug.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(n,e)),r)this.emit("data",this._packer.packGAMA(r));let i=this._packer.filterData(t,n,e);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(o){this.emit("data",this._packer.packIDAT(o))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(i)}});var Gs=$t((be,Rs)=>{var Ns=jt("assert").ok,Wn=jt("zlib"),fg=jt("util"),Os=jt("buffer").kMaxLength;function Nn(t){if(!(this instanceof Nn))return new Nn(t);if(t&&t.chunkSize<Wn.Z_MIN_CHUNK)t.chunkSize=Wn.Z_MIN_CHUNK;if(Wn.Inflate.call(this,t),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,t&&t.maxLength!=null)this._maxLength=t.maxLength}function ag(t){return new Nn(t)}function Hs(t,n){if(n)process.nextTick(n);if(!t._handle)return;t._handle.close(),t._handle=null}Nn.prototype._processChunk=function(t,n,e){if(typeof e==="function")return Wn.Inflate._processChunk.call(this,t,n,e);let r=this,i=t&&t.length,o=this._chunkSize-this._offset,s=this._maxLength,c=0,u=[],h=0,f;this.on("error",function(p){f=p});function a(p,l){if(r._hadError)return;let k=o-l;if(Ns(k>=0,"have should not go down"),k>0){let v=r._buffer.slice(r._offset,r._offset+k);if(r._offset+=k,v.length>s)v=v.slice(0,s);if(u.push(v),h+=v.length,s-=v.length,s===0)return!1}if(l===0||r._offset>=r._chunkSize)o=r._chunkSize,r._offset=0,r._buffer=Buffer.allocUnsafe(r._chunkSize);if(l===0)return c+=i-p,i=p,!0;return!1}Ns(this._handle,"zlib binding closed");let g;do g=this._handle.writeSync(n,t,c,i,this._buffer,this._offset,o),g=g||this._writeState;while(!this._hadError&&a(g[0],g[1]));if(this._hadError)throw f;if(h>=Os)throw Hs(this),RangeError("Cannot create final Buffer. It would be larger than 0x"+Os.toString(16)+" bytes");let d=Buffer.concat(u,h);return Hs(this),d};fg.inherits(Nn,Wn.Inflate);function gg(t,n){if(typeof n==="string")n=Buffer.from(n);if(!(n instanceof Buffer))throw TypeError("Not a string or buffer");let e=t._finishFlushFlag;if(e==null)e=Wn.Z_FINISH;return t._processChunk(n,e)}function js(t,n){return gg(new Nn(n),t)}Rs.exports=be=js;be.Inflate=Nn;be.createInflate=ag;be.inflateSync=js});var li=$t((Y0,Ps)=>{var Ls=Ps.exports=function(t){this._buffer=t,this._reads=[]};Ls.prototype.read=function(t,n){this._reads.push({length:Math.abs(t),allowLess:t<0,func:n})};Ls.prototype.process=function(){while(this._reads.length>0&&this._buffer.length){let t=this._reads[0];if(this._buffer.length&&(this._buffer.length>=t.length||t.allowLess)){this._reads.shift();let n=this._buffer;this._buffer=n.slice(t.length),t.func.call(this,n.slice(0,t.length))}else break}if(this._reads.length>0)throw Error("There are some read requests waitng on finished stream");if(this._buffer.length>0)throw Error("unrecognised content at end of stream")}});var Ks=$t((mg)=>{var lg=li(),dg=ii();mg.process=function(t,n){let e=[],r=new lg(t);return new dg(n,{read:r.read.bind(r),write:function(o){e.push(o)},complete:function(){}}).start(),r.process(),Buffer.concat(e)}});var Ts=$t((x0,Us)=>{var Js=!0,As=jt("zlib"),wg=Gs();if(!As.deflateSync)Js=!1;var $g=li(),bg=Ks(),kg=ui(),Eg=hi(),Mg=fi();Us.exports=function(t,n){if(!Js)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let e;function r(y){e=y}let i;function o(y){i=y}function s(y){i.transColor=y}function c(y){i.palette=y}function u(){i.alpha=!0}let h;function f(y){h=y}let a=[];function g(y){a.push(y)}let d=new $g(t);if(new kg(n,{read:d.read.bind(d),error:r,metadata:o,gamma:f,palette:c,transColor:s,inflateData:g,simpleTransparency:u}).start(),d.process(),e)throw e;let l=Buffer.concat(a);a.length=0;let k;if(i.interlace)k=As.inflateSync(l);else{let $=((i.width*i.bpp*i.depth+7>>3)+1)*i.height;k=wg(l,{chunkSize:$,maxLength:$})}if(l=null,!k||!k.length)throw Error("bad png - invalid inflate data response");let v=bg.process(k,i);l=null;let I=Eg.dataToBitMap(v,i);v=null;let E=Mg(I,i,n.skipRescale);return i.data=E,i.gamma=h||0,i}});var qs=$t((B0,Zs)=>{var Ws=!0,Qs=jt("zlib");if(!Qs.deflateSync)Ws=!1;var vg=Tn(),yg=gi();Zs.exports=function(t,n){if(!Ws)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let r=new yg(n||{}),i=[];if(i.push(Buffer.from(vg.PNG_SIGNATURE)),i.push(r.packIHDR(t.width,t.height)),t.gamma)i.push(r.packGAMA(t.gamma));let o=r.filterData(t.data,t.width,t.height),s=Qs.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 Xs=$t((Ig)=>{var Sg=Ts(),Fg=qs();Ig.read=function(t,n){return Sg(t,n||{})};Ig.write=function(t,n){return Fg(t,n)}});var Cs=$t((Lg)=>{var Hg=jt("util"),_s=jt("stream"),jg=ws(),Rg=Is(),Gg=Xs(),Lt=Lg.PNG=function(t){if(_s.call(this),t=t||{},this.width=t.width|0,this.height=t.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,t.fill&&this.data)this.data.fill(0);this.gamma=0,this.readable=this.writable=!0,this._parser=new jg(t),this._parser.on("error",this.emit.bind(this,"error")),this._parser.on("close",this._handleClose.bind(this)),this._parser.on("metadata",this._metadata.bind(this)),this._parser.on("gamma",this._gamma.bind(this)),this._parser.on("parsed",function(n){this.data=n,this.emit("parsed",n)}.bind(this)),this._packer=new Rg(t),this._packer.on("data",this.emit.bind(this,"data")),this._packer.on("end",this.emit.bind(this,"end")),this._parser.on("close",this._handleClose.bind(this)),this._packer.on("error",this.emit.bind(this,"error"))};Hg.inherits(Lt,_s);Lt.sync=Gg;Lt.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};Lt.prototype.parse=function(t,n){if(n){let e,r;e=function(i){this.removeListener("error",r),this.data=i,n(null,this)}.bind(this),r=function(i){this.removeListener("parsed",e),n(i,null)}.bind(this),this.once("parsed",e),this.once("error",r)}return this.end(t),this};Lt.prototype.write=function(t){return this._parser.write(t),!0};Lt.prototype.end=function(t){this._parser.end(t)};Lt.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};Lt.prototype._gamma=function(t){this.gamma=t};Lt.prototype._handleClose=function(){if(!this._parser.writable&&!this._packer.readable)this.emit("close")};Lt.bitblt=function(t,n,e,r,i,o,s,c){if(e|=0,r|=0,i|=0,o|=0,s|=0,c|=0,e>t.width||r>t.height||e+i>t.width||r+o>t.height)throw Error("bitblt reading outside image");if(s>n.width||c>n.height||s+i>n.width||c+o>n.height)throw Error("bitblt writing outside image");for(let u=0;u<o;u++)t.data.copy(n.data,(c+u)*n.width+s<<2,(r+u)*t.width+e<<2,(r+u)*t.width+e+i<<2)};Lt.prototype.bitblt=function(t,n,e,r,i,o,s){return Lt.bitblt(this,t,n,e,r,i,o,s),this};Lt.adjustGamma=function(t){if(t.gamma){for(let n=0;n<t.height;n++)for(let e=0;e<t.width;e++){let r=t.width*n+e<<2;for(let i=0;i<3;i++){let o=t.data[r+i]/255;o=Math.pow(o,0.45454545454545453/t.gamma),t.data[r+i]=Math.round(o*255)}}t.gamma=0}};Lt.prototype.adjustGamma=function(){Lt.adjustGamma(this)}});var oo=$t((vb,Dh)=>{var io={to(t,n){if(!n)return`\x1B[${t+1}G`;return`\x1B[${n+1};${t+1}H`},move(t,n){let e="";if(t<0)e+=`\x1B[${-t}D`;else if(t>0)e+=`\x1B[${t}C`;if(n<0)e+=`\x1B[${-n}A`;else if(n>0)e+=`\x1B[${n}B`;return e},up:(t=1)=>`\x1B[${t}A`,down:(t=1)=>`\x1B[${t}B`,forward:(t=1)=>`\x1B[${t}C`,backward:(t=1)=>`\x1B[${t}D`,nextLine:(t=1)=>"\x1B[E".repeat(t),prevLine:(t=1)=>"\x1B[F".repeat(t),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},up={up:(t=1)=>"\x1B[S".repeat(t),down:(t=1)=>"\x1B[T".repeat(t)},hp={screen:"\x1B[2J",up:(t=1)=>"\x1B[1J".repeat(t),down:(t=1)=>"\x1B[J".repeat(t),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(t){let n="";for(let e=0;e<t;e++)n+=this.line+(e<t-1?io.up():"");if(t)n+=io.left;return n}};Dh.exports={cursor:io,scroll:up,erase:hp,beep:"\x07"}});import{isMainThread as d0}from"node:worker_threads";import{parseArgs as a0}from"node:util";var en={name:"@kecan0406/ttheme",version:"1.0.33",type:"module",bin:{ttheme:"bin/ttheme.js"},files:["bin","dist/manifest.json","dist/ghostty/ttheme.conf","shell","!shell/check.zsh","ghostty/shaders"],description:"Character terminal palettes for ghostty, kitty, alacritty, wezterm and iTerm2",license:"MIT",author:"kecan0406",repository:{type:"git",url:"git+https://github.com/kecan0406/ttheme.git"},homepage:"https://github.com/kecan0406/ttheme#readme",bugs:"https://github.com/kecan0406/ttheme/issues",keywords:["terminal","theme","ghostty","kitty","alacritty","wezterm","iterm2"],devDependencies:{"@biomejs/biome":"^2.3.0","@clack/core":"^1.4.3","@clack/prompts":"^1.7.0","@material/material-color-utilities":"^0.4.0","@types/bun":"^1.3.0","@types/pngjs":"6.0.5","jpeg-js":"^0.4.4",pngjs:"7.0.0",typescript:"^5.8.2"},engines:{bun:">=1.3",node:">=20.11"}};import{rmSync as pu}from"node:fs";import{basename as xl,join as Pe}from"node:path";var ga=/^#[0-9a-f]{6}$/;function Jo(t){return ga.test(t)}function Rt(t){let n=Number.parseInt(t.slice(1),16);return[n>>16&255,n>>8&255,n&255]}function Bt(t){let[n,e,r]=Rt(t).map((i)=>{let o=i/255;return o<=0.03928?o/12.92:((o+0.055)/1.055)**2.4});return 0.2126*n+0.7152*e+0.0722*r}function an(t,n){let e=Bt(t),r=Bt(n);return(Math.max(e,r)+0.05)/(Math.min(e,r)+0.05)}function er(t,n){return Math.round(an(t,n)*100)/100}var wn=7,Ao=3,Vr=0.15,Uo=1.6,To=[1,2,3,4,5,6,9,10,11,12,13,14],Wo=[7,15];function de(t,n){let e=t.ansi[n];if(e===void 0)throw Error(`${t.name}: missing ANSI ${n}`);return e}function xr(t,n,e){let r=t.background;return n.flatMap((i)=>{let o=de(t,i);return an(o,r)<e?[`ANSI ${i} ${o} on ${r} is ${er(o,r)}:1, needs ${e}:1`]:[]})}function Qo(t,n){return Math.min(...n.map((e)=>an(de(t,e),t.background)))}var rr=[{rule:"foreground",label:"foreground on background",unit:"ratio",min:wn,measure:({foreground:t,background:n})=>an(t,n),check:({foreground:t,background:n})=>an(t,n)<wn?[`foreground ${t} on ${n} is ${er(t,n)}:1, needs ${wn}:1`]:[]},{rule:"accents",label:"weakest accent on background",unit:"ratio",min:Ao,measure:(t)=>Qo(t,To),check:(t)=>xr(t,To,Ao)},{rule:"ansi0-dark",label:"ansi0 luminance",unit:"luminance",max:Vr,measure:(t)=>Bt(de(t,0)),check:(t)=>{let n=de(t,0);return Bt(n)>Vr?[`ANSI 0 ${n} has luminance ${Bt(n).toFixed(3)}, needs <= ${Vr}`]:[]}},{rule:"light-ansi",label:"ansi7 and ansi15 on background",unit:"ratio",min:wn,measure:(t)=>Qo(t,Wo),check:(t)=>xr(t,Wo,wn)},{rule:"ansi8-visible",label:"ansi8 on background",unit:"ratio",min:Uo,measure:(t)=>an(de(t,8),t.background),check:(t)=>xr(t,[8],Uo)},{rule:"selection",label:"foreground on selection",unit:"ratio",min:wn,measure:({foreground:t,selectionBackground:n})=>n===void 0?Number.NaN:an(t,n),check:({foreground:t,selectionBackground:n})=>n!==void 0&&an(t,n)<wn?[`foreground ${t} on selection ${n} is ${er(t,n)}:1, needs ${wn}:1`]:[]}],k0=rr.map((t)=>t.rule),ir=rr.map(({rule:t,label:n,unit:e,min:r,max:i})=>({rule:t,label:n,unit:e,...r===void 0?{}:{min:r},...i===void 0?{}:{max:i}}));function Zo(t){return rr.map((n)=>Math.round(n.measure(t)*1000)/1000)}function Br(t){return rr.filter((n)=>!t.waive.includes(n.rule)).flatMap((n)=>n.check(t).map((e)=>({theme:t.name,rule:n.rule,detail:e})))}function qo(t){return t.flatMap(Br)}var la=["black","red","green","yellow","blue","magenta","cyan","white"];function Xo(t,n){return[t,...la.map((e,r)=>`${e} = '${n[r]}'`),""].join(`
|
|
3
|
-
`)}var
|
|
4
|
-
`),
|
|
5
|
-
`);return[{path:`alacritty/themes/${t.name}.toml`,content:
|
|
6
|
-
`);return[{path:`ghostty/themes/${t.name}`,content:
|
|
7
|
-
`)}]}};function
|
|
8
|
-
`}function
|
|
9
|
-
`)}var
|
|
10
|
-
`);return[{path:`iterm2/${t.name}.itermcolors`,content:
|
|
11
|
-
`),
|
|
12
|
-
`);return[{path:`kitty/themes/${t.name}.conf`,content:
|
|
13
|
-
`)}import{createHash as
|
|
14
|
-
`)}function
|
|
15
|
-
`)){let h=/^(background-image(?:-fit|-opacity)?)\s*=\s*(.*?)\s*$/.exec(u);if(h)r.set(h[1],h[2])}}let i=r.get("background-image")??"";if(i==="")return;let o=Number(r.get("background-image-opacity")??1);return{image:i.startsWith("~/")?Mt(
|
|
16
|
-
`}]}};import{readdirSync as Rl,readFileSync as yi}from"node:fs";import{basename as Gl,join as Si}from"node:path";import{readdirSync as nl,rmSync as el,statSync as rl}from"node:fs";import{setDefaultAutoSelectFamilyAttemptTimeout as il}from"node:net";import{homedir as ol}from"node:os";import{join as Se}from"node:path";import{setTimeout as sl}from"node:timers/promises";var Hn=100,Rn=25000000,cl=536870912,Fe=["safe","questionable","explicit"],jn=["nudity","underwear"],ul={nudity:new Set(["nude","naked","topless","bottomless","nipples","naked_towel","undressing"]),underwear:new Set(["underwear","panties","pantsu","bra","lingerie","pantyshot"])},ye={safe:"s",questionable:"q",explicit:"e"},hl=8191,fl=20000,al=5000,Ec=3000,Mc=8,gl=3000,Fc=60000,vc=3,ki=`ttheme/${en.version} (+${en.homepage})`,ll=["orig","tile","thumb","cut"],Ic=new Map,dl=yl(process.env.TTHEME_FIND_HOSTS),ml=vl(process.env.TTHEME_FIND_CUTOUTS);il(gl);function yc(t){try{return nl(t)}catch{return[]}}function ar(t){return t.startsWith("//")?`https:${t}`:t}function Ie(t){return(/\.([a-z0-9]+)(?:\?.*)?$/i.exec(t)?.[1]??"").toLowerCase()}function Ne(t){let n=t.trim();if(!n)return[];let e=JSON.parse(n);if(Array.isArray(e))return e;let r=e.posts;return Array.isArray(r)?r:[]}function pl(t){let n=t.trim(),r=(n?JSON.parse(n):{}).tags??{};return new Map(Object.entries(r).map(([i,o])=>[i,String(o)]))}function bi(t,n,e){let r=ar(String(t??""));return{file:r,width:Number(n)||0,height:Number(e)||0,ext:Ie(r)}}function Nc(t,n){let e=ar(String(n.preview??""));if(!n.file||!e||!Number(t.id))return[];let r=Number(t.width??t.image_width)||0,i=Number(t.height??t.image_height)||0;return[{id:Number(t.id),width:r,height:i,file:n.file,preview:e,ext:n.ext,owner:String(n.owner??""),artist:n.artist,score:Number(t.score)||0,rating:String(t.rating??""),md5:String(n.md5??""),source:String(t.source??""),tags:n.tags.split(/\s+/).filter(Boolean),solo:n.solo,family:Number(t.parent_id)||(t.has_children===!0?Number(t.id):0),smaller:n.versions.filter((o)=>o.file&&o.width>0&&o.height>0&&o.width*o.height<r*i)}]}function wl(t){let n=pl(t);return Ne(t).flatMap((e)=>{let r=ar(String(e.file_url??"")),i=String(e.tags??"");return Nc(e,{preview:e.preview_url,file:r,ext:String(e.file_ext||Ie(r)).toLowerCase(),owner:e.author,artist:i.split(/\s+/).find((o)=>n.get(o)==="artist")??"",md5:e.md5,tags:i,solo:void 0,versions:[bi(e.jpeg_url,e.jpeg_width,e.jpeg_height),bi(e.sample_url,e.sample_width,e.sample_height)]})})}function $l(t){return Ne(t).flatMap((n)=>{let e=ar(String(n.file_url??"")),r=String(n.tag_string??""),i=n.media_asset??{};return Nc(n,{preview:i.variants?.find((o)=>o.type==="360x360")?.url??n.preview_file_url,file:e,ext:String(n.file_ext||Ie(e)).toLowerCase(),owner:"",artist:String(n.tag_string_artist??"").split(/\s+/)[0]??"",md5:n.md5,tags:r,solo:r.split(/\s+/).includes("solo"),versions:(i.variants??[]).map((o)=>bi(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 bl(t){return Ne(t).flatMap((n)=>{let e=String(n.value??"");return e?[{value:e,count:Number(n.post_count)||0}]:[]})}function kl(t){return Ne(t).flatMap((n)=>{let e=String(n.name??"");return e?[{value:e,count:Number(n.count)||0}]:[]})}function El(t){return Number(/count="(\d+)"/.exec(t)?.[1]??0)}function Ml(t){let n=t.trim()?JSON.parse(t):{};return Number(n.counts?.posts)||0}function vl(t){let n=new Map;for(let e of(t??"").split(/\s+/).filter(Boolean)){let r=e.indexOf("=");if(r>0)n.set(e.slice(0,r),e.slice(r+1).split(",").filter(Boolean))}return n}function yl(t){let n=new Map;for(let e of(t??"").split(/[\s,]+/).filter(Boolean)){let r=e.indexOf("="),i=e.slice(0,r);try{let o=new URL(e.slice(r+1));if(i&&o.protocol==="https:")n.set(i,o.origin)}catch{}}return n}function Oc(t,n,e,r){let i=(t??"").split(/\s+/);if(r!==void 0&&i.includes(r))return[];let o=n.filter((s)=>i.includes(s));return o.length>0?o:[...e]}function gr(t){return Oc(t,Fe,["safe"])}function lr(t){return Oc(t,jn,jn,"none")}function Hc(t,n,e){return{safe:new Set(t),questionable:new Set(n),explicit:new Set(e)}}function jc(t){let n=dl.get(t.key),e=ml.get(t.key);return{...t,origin:n??t.origin,moved:n!==void 0&&n!==t.origin,cutouts:e??t.cutouts,vouched:t.vouched&&e===void 0}}function Rc(t){return t.length<2?t.join(""):t.map((n)=>`~${n}`).join(" ")}function Sc(t){let n=jc(t),e=(r)=>new URLSearchParams({api_version:"2",include_tags:"1",...r});return{...n,cutouts:Rc(n.cutouts),ratings:Hc([ye.safe],[ye.questionable],[ye.explicit]),rate:(r)=>{let[i]=r;if(r.length===1&&i)return`rating:${ye[i]}`;let o=Fe.filter((c)=>!r.includes(c)),[s]=o;return o.length===1&&s?`-rating:${ye[s]}`:""},best:"order:score",tagBudget:Number.POSITIVE_INFINITY,postsUrl:(r,i)=>`${n.origin}/post.json?${e({limit:String(Hn),page:String(i+1),tags:r})}`,countUrl:(r)=>`${n.origin}/post.xml?${new URLSearchParams({limit:"1",tags:r})}`,postUrl:(r)=>`${n.origin}/post.json?${e({tags:`id:${r}`})}`,pageUrl:(r)=>`${n.origin}/post/show/${r}`,parse:wl,count:El}}function Sl(t){let n=jc(t),e=Hc(["g"],["s","q"],["e"]);return{...n,cutouts:Rc(n.cutouts),ratings:e,rate:(r)=>r.length===Fe.length?"":`rating:${r.flatMap((i)=>[...e[i]]).join(",")}`,best:"order:score",tagBudget:2,postsUrl:(r,i)=>`${n.origin}/posts.json?${new URLSearchParams({limit:String(Hn),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:$l,count:Ml}}function Fl(t){return gt.find((n)=>n.key===t||n.name===t||new URL(n.origin).host===t)}function Ei(t){return t.split(/\s+/).filter((n)=>n&&!n.startsWith("rating:")).length}function dr(t,n){let e=t.trim();if(/^\d+$/.test(e))return{site:n,id:Number(e)};let r=/^([\w.]+):(\d+)$/.exec(e);if(r){let c=gt.find((u)=>u.key===r[1]||u.name===r[1]);return c&&{site:c,id:Number(r[2])}}let i;try{i=new URL(e)}catch{return}let o=Fl(i.host),s=Number(i.searchParams.get("id")??i.pathname.split("/").filter(Boolean).at(-1));return o&&s>0?{site:o,id:s}:void 0}var gt=[Sl({key:"danbooru",name:"danbooru",origin:"https://danbooru.donmai.us",cutouts:["transparent_background"],vouched:!1,tunneled:!0,ansi:2}),Sc({key:"konachan",name:"konachan",origin:"https://konachan.net",cutouts:["transparent","vector"],vouched:!1,tunneled:!1,ansi:6}),Sc({key:"yande",name:"yande.re",origin:"https://yande.re",cutouts:["transparent_png"],vouched:!0,tunneled:!1,ansi:5})],ln=134217728;function on(t,n){let e=gt.indexOf(t);return(e===-1?gt.length:e)*ln+n}function Mi(t){let n;try{n=new URL(t).hostname}catch{return""}return n.split(".").slice(-2).join(".")}function Gc(){return gt.filter((t)=>!t.tunneled).map((t)=>Mi(t.origin)).flatMap((t)=>[t,`.${t}`]).join(",")}function Lc(t,n=jn){return t.tags.filter((e)=>n.some((r)=>ul[r].has(e)))}function Pc(t,n,e=["safe"]){return e.some((r)=>t.ratings[r].has(n.rating))}function Oe(t){return[t,...t.smaller].find((n)=>n.width*n.height<=Rn)}function Kc(t){let n=new Map;for(let[e,r]of[...t].sort(([i],[o])=>i<o?-1:1)){if(r==="")continue;n.set(r,[...n.get(r)??[],e])}return n}function Jc(){return Se(process.env.XDG_CACHE_HOME??Se(ol(),".cache"),"ttheme")}function yn(t){return Se(Jc(),t.key)}function Ac(t=cl,n=Jc()){let e=[],r=0;for(let i of yc(n))for(let o of ll){let s=Se(n,i,o);for(let c of yc(s)){let u=Se(s,c);try{let{size:h,mtimeMs:f}=rl(u);e.push({path:u,size:h,at:f}),r+=h}catch{}}}e.sort((i,o)=>i.at-o.at);for(let i of e){if(r<=t)return;try{el(i.path,{force:!0}),r-=i.size}catch{}}}function Il(t,n){if(t!==null&&/^\s*\d+\s*$/.test(t))return Number(t)*1000;let e=t===null?Number.NaN:Date.parse(t);return Number.isNaN(e)?Fc:Math.max(0,e-n)}function Mn(t){return Ic.get(t.key)??0}function Nl(t){for(let n=t;n instanceof Error;n=n.cause)if(n.code==="ECONNRESET")return!0;return!1}function Ol(t){return(t.headers.get("server")??"").startsWith("cloudflare")&&t.headers.get("cf-mitigated")==="challenge"}async function vn(t,n,e,r={},i=fl){for(let o=1;;o++){let s=Mn(t)-Date.now();if(s>0)await sl(s,void 0,{signal:e});let c;try{c=await fetch(n,{headers:{"User-Agent":ki,Referer:`${t.origin}/`,...r},signal:i?AbortSignal.any([e,AbortSignal.timeout(i)]):e})}catch(u){if(o<vc&&!e.aborted&&Nl(u))continue;throw u}if(c.status===429&&o<vc){await c.body?.cancel();let u=Il(c.headers.get("retry-after"),Date.now());if(u>Fc)throw Error(`${t.name} asks to wait ${Math.ceil(u/1000)}s`);Ic.set(t.key,Math.max(Mn(t),Date.now()+u));continue}if(!c.ok)throw await c.body?.cancel(),Error(Ol(c)?`${t.name} is behind a Cloudflare challenge`:`${t.name} answered ${c.status}`);return c}}async function Uc(t,n,e,r){return t.parse(await(await vn(t,t.postsUrl(n,e),r)).text())}async function Tc(t,n,e){return t.count(await(await vn(t,t.countUrl(n),e)).text())}async function vi(t,n,e){let[r]=t.parse(await(await vn(t,t.postUrl(n),e)).text());return r}function Hl(t){let n=gt.find((r)=>r.key==="danbooru"),e=new URLSearchParams({limit:String(2*Hn),only:"md5,tag_string",tags:`md5:${t.join(",")}`});return`${n.origin}/posts.json?${e}`}function jl(t){return new Map(Ne(t).flatMap((n)=>{let e=String(n.md5??"");return e?[[e,String(n.tag_string??"").split(/\s+/).filter(Boolean)]]:[]}))}function Wc(t,n){for(let e of t){let r=n.get(e.md5);if(r)e.tags=[...new Set([...e.tags,...r])],e.solo=r.includes("solo")}}async function Qc(t,n){let e=gt.find((i)=>i.key==="danbooru"),r=new Map;if(Mn(e)>Date.now())return r;for(let i=0;i<t.length;i+=Hn){let o=await(await vn(e,Hl(t.slice(i,i+Hn)),n,{},al)).text();for(let[s,c]of jl(o))r.set(s,c)}return r}async function Zc(t,n){let e=gt.find((o)=>o.key==="danbooru");if(Mn(e)<=Date.now())try{let o=new URLSearchParams({"search[query]":t,"search[type]":"tag_query",limit:String(Mc)}),s=`${e.origin}/autocomplete.json?${o}`;return bl(await(await vn(e,s,n,{},Ec)).text())}catch(o){if(n.aborted)throw o}let r=gt.find((o)=>o.key==="yande"),i=new URLSearchParams({name:t,order:"count",limit:String(Mc)});return kl(await(await vn(r,`${r.origin}/tag.json?${i}`,n,{},Ec)).text())}async function qc(t,n,e){let r=await vn(t,n,e,{Range:`bytes=0-${hl}`});return Ee(new Uint8Array(await r.arrayBuffer()))}async function Xc(t,n,e,r){let i=await vn(t,n,e,{},0),o=Number(i.headers.get("content-length"))||0,s=i.body?.getReader();if(!s)return new Uint8Array(await i.arrayBuffer());let c=[],u=0;for(;;){let{done:a,value:g}=await s.read();if(a)break;c.push(g),u+=g.length,r?.(u,o)}let h=new Uint8Array(u),f=0;for(let a of c)h.set(a,f),f+=a.length;return h}var Ll="_defaults.toml",dn="_groups.toml",_c=3,Cc=["background","foreground","cursor","selection"],Pl=new Set(["next","help","preview","pin","unpin","config"]);function vt(t,n){throw Error(`${t}: ${n}`)}function Gn(t,n,e){if(typeof e!=="string"||!Jo(e))vt(t,`${n} must be "#rrggbb" (lowercase), got ${JSON.stringify(e)}`);return e}function _t(t,n,e){if(typeof e!=="string"||e.length===0)vt(t,`${n} must be a non-empty string`);return e}function mn(t){return t&&typeof t==="object"?t:{}}function Kl(t,n,e){let r={...mn(e),...mn(n)},i=r.codepoint_map??[];if(!Array.isArray(i))vt(t,"font.codepoint_map must be an array");return{family:_t(t,"font.family",r.family),size:Number(r.size),codepointMap:i.map((o)=>{let s=mn(o);return{range:_t(t,"font.codepoint_map[].range",s.range),family:_t(t,"font.codepoint_map[].family",s.family)}})}}function Jl(t,n,e){if(n===void 0)return[e.cursor,e.selectionBackground,e.background];let r=Array.isArray(n)?n:[n];if(r.length===0)vt(t,"ghostty.icon_screen must not be empty");return r.map((i,o)=>Gn(t,`ghostty.icon_screen[${o}]`,i))}function Al(t,n,e,r){let i={...mn(e),...mn(n)};return{shader:i.shader===void 0?void 0:_t(t,"ghostty.shader",i.shader),iconGhost:i.icon_ghost===void 0?r.cursor:Gn(t,"ghostty.icon_ghost",i.icon_ghost),iconScreen:Jl(t,i.icon_screen,r)}}function Ul(t){return new Map([...Cc.map((n)=>[n,t[n]]),...t.ansi.map((n,e)=>[`ansi${e}`,n])])}function Tl(t,n,e){if(!Array.isArray(n)||n.length!==_c)vt(t,`meta.signature must name exactly ${_c} palette slots`);let r=Ul(e),i=[],o=[];for(let[s,c]of n.entries()){let u=`meta.signature[${s}]`,h=_t(t,u,c),f=r.get(h);if(f===void 0)vt(t,`${u} ${JSON.stringify(c)} is not a palette slot — use ${Cc.join(", ")} or ansi0-ansi15`);i.push(h),o.push(f)}if(new Set(o).size!==o.length)vt(t,"meta.signature slots must resolve to three different colors");return{names:i,colors:o}}function Wl(t,n,e){if(n===void 0)return;if(!e)vt(t,"meta.booru_sites renames meta.booru per site, so it needs meta.booru");if(!n||typeof n!=="object"||Array.isArray(n))vt(t,'meta.booru_sites must be a table of site = "tag" or site = ["tag", ...]');let r={};for(let[i,o]of Object.entries(n)){let s=gt.find((u)=>u.key===i);if(!s)vt(t,`meta.booru_sites.${i} is not a find site — use ${gt.map((u)=>u.key).join(", ")}`);let c=typeof o==="string"?[o]:Array.isArray(o)?o:void 0;if(!c||c.some((u)=>typeof u!=="string"||u===""||/\s/.test(u)))vt(t,`meta.booru_sites.${i} must be one tag or a list of tags, got ${JSON.stringify(o)}`);if(c.length>1&&Number.isFinite(s.tagBudget))vt(t,`meta.booru_sites.${i} takes one tag — ${s.name} searches ${s.tagBudget} tags at a time`);r[i]=c}return r}function Ql(t){let e=Bun.TOML.parse(yi(Si(t,dn),"utf8")).group;if(!Array.isArray(e)||e.length===0)vt(dn,"needs at least one [[group]] table");return e.map((r)=>{let i=mn(r);return{name:_t(dn,"group.name",i.name),native:i.native===void 0?void 0:_t(dn,"group.native",i.native),lead:_t(dn,"group.lead",i.lead)}})}function Zl(t,n,e,r){let i=Bun.TOML.parse(n),o=mn(i.meta),s=mn(i.colors),c=mn(i.contrast),u=s.ansi;if(!Array.isArray(u)||u.length!==16)vt(t,`colors.ansi must hold exactly 16 colors, got ${Array.isArray(u)?u.length:typeof u}`);let h=_t(t,"meta.name",o.name);if(h!==Gl(t,".toml"))vt(t,`meta.name "${h}" does not match the filename`);if(Pl.has(h))vt(t,`meta.name "${h}" collides with a ttheme subcommand`);if(h.startsWith("-"))vt(t,`meta.name "${h}" would be read as a flag by the ttheme CLI`);let f=o.role;if(f!==void 0&&f!=="default")vt(t,`meta.role must be "default", got ${JSON.stringify(f)}`);let a=_t(t,"meta.group",o.group),g=r.get(a);if(!g)vt(t,`meta.group "${a}" has no [[group]] table in ${dn}`);let d=Gn(t,"colors.background",s.background),p=Gn(t,"colors.foreground",s.foreground),l=Gn(t,"colors.cursor",s.cursor),k=Gn(t,"colors.selection_background",s.selection_background),v=u.map((H,b)=>Gn(t,`colors.ansi[${b}]`,H)),I=Tl(t,o.signature,{background:d,foreground:p,cursor:l,selection:k,ansi:v}),E=o.booru===void 0?void 0:_t(t,"meta.booru",o.booru);if(E!==void 0&&/\s/.test(E))vt(t,`meta.booru must be a single booru tag, got ${JSON.stringify(E)}`);let y=Wl(t,o.booru_sites,E),$=Array.isArray(c.waive)?c.waive.map(String):[];if($.length>0&&typeof c.reason!=="string")vt(t,"contrast.waive needs a contrast.reason explaining why");return{name:h,group:a,native:g.native,lead:g.lead===h,order:Number(o.order),role:f,ansiSource:_t(t,"meta.ansi_source",o.ansi_source),...E?{booru:E}:{},...y?{booruSites:y}:{},background:d,foreground:p,cursor:l,selectionBackground:k,ansi:v,signature:I.colors,signatureSlots:I.names,font:Kl(t,i.font,e.font),ghostty:Al(t,i.ghostty,e.ghostty,{background:d,cursor:l,selectionBackground:k}),waive:$,waiveReason:typeof c.reason==="string"?c.reason:void 0}}function zc(t){let n=Bun.TOML.parse(yi(Si(t,Ll),"utf8")),e=Ql(t),r=new Map(e.map((s)=>[s.name,s]));if(r.size!==e.length)vt(dn,"group.name must be unique");let i=Rl(t).filter((s)=>s.endsWith(".toml")&&!s.startsWith("_")).map((s)=>Zl(s,yi(Si(t,s),"utf8"),n,r)).sort((s,c)=>s.order-c.order);if(new Set(i.map((s)=>s.order)).size!==i.length)throw Error("themes: meta.order must be unique across all themes");for(let s of e){let c=i.filter((u)=>u.group===s.name);if(c.length===0)vt(dn,`group "${s.name}" has no themes`);if(!c.some((u)=>u.name===s.lead))vt(dn,`group "${s.name}" lead "${s.lead}" is not one of its themes`)}return i}function Yc(t){return t.filter((n)=>n.role===void 0)}function He(t){let n=(e,r)=>e<r?-1:e>r?1:0;return[...t].sort((e,r)=>n(e.group.toLowerCase(),r.group.toLowerCase())||n(e.name,r.name))}var mr=["ghostty","kitty","alacritty","wezterm","iterm2","windows-terminal","warp"];var Fi=/# ttheme begin\n[\s\S]*?# ttheme end\n?/;function je(t,n){let e=`# ttheme begin
|
|
17
|
-
${
|
|
2
|
+
import{createRequire as da}from"node:module";var ca=Object.create;var{getPrototypeOf:ua,defineProperty:Wo,getOwnPropertyNames:ha}=Object;var fa=Object.prototype.hasOwnProperty;function aa(t){return this[t]}var la,ga,ir=(t,e,n)=>{var r=t!=null&&typeof t==="object";if(r){var i=e?la??=new WeakMap:ga??=new WeakMap,o=i.get(t);if(o)return o}n=t!=null?ca(ua(t)):{};let s=e||!t||!t.__esModule?Wo(n,"default",{value:t,enumerable:!0}):n;for(let c of ha(t))if(!fa.call(s,c))Wo(s,c,{get:aa.bind(t,c),enumerable:!0});if(r)i.set(t,s);return s};var bt=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var jt=da(import.meta.url);var ns=bt((A0,ur)=>{var es=es||function(t){return Buffer.from(t).toString("base64")};function Ea(t){var e=this,n=Math.round,r=Math.floor,i=Array(64),o=Array(64),s=Array(64),c=Array(64),u,h,f,a,l=Array(65535),d=Array(65535),p=Array(64),g=Array(64),k=[],y=0,I=7,E=Array(64),v=Array(64),b=Array(64),O=Array(256),$=Array(2048),R,H=[0,1,5,6,14,15,27,28,2,4,7,13,16,26,29,42,3,8,12,17,25,30,41,43,9,11,18,24,31,40,44,53,10,19,23,32,39,45,52,54,20,22,33,38,46,51,55,60,21,34,37,47,50,56,59,61,35,36,48,49,57,58,62,63],P=[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],C=[0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,125],A=[1,2,3,0,4,17,5,18,33,49,65,6,19,81,97,7,34,113,20,50,129,145,161,8,35,66,177,193,21,82,209,240,36,51,98,114,130,9,10,22,23,24,25,26,37,38,39,40,41,42,52,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,225,226,227,228,229,230,231,232,233,234,241,242,243,244,245,246,247,248,249,250],Ft=[0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0],T=[0,1,2,3,4,5,6,7,8,9,10,11],Y=[0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,119],kt=[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 dt(m){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 U=0;U<64;U++){var J=r((L[U]*m+50)/100);if(J<1)J=1;else if(J>255)J=255;i[H[U]]=J}var Z=[17,18,24,47,99,99,99,99,18,21,26,66,99,99,99,99,24,26,56,99,99,99,99,99,47,66,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99];for(var _=0;_<64;_++){var rt=r((Z[_]*m+50)/100);if(rt<1)rt=1;else if(rt>255)rt=255;o[H[_]]=rt}var it=[1,1.387039845,1.306562965,1.175875602,1,0.785694958,0.5411961,0.275899379],vt=0;for(var wt=0;wt<8;wt++)for(var M=0;M<8;M++)s[vt]=1/(i[H[vt]]*it[wt]*it[M]*8),c[vt]=1/(o[H[vt]]*it[wt]*it[M]*8),vt++}function B(m,L){var U=0,J=0,Z=[];for(var _=1;_<=16;_++){for(var rt=1;rt<=m[_];rt++)Z[L[J]]=[],Z[L[J]][0]=U,Z[L[J]][1]=_,J++,U++;U*=2}return Z}function It(){u=B(P,G),h=B(Ft,T),f=B(C,A),a=B(Y,kt)}function ot(){var m=1,L=2;for(var U=1;U<=15;U++){for(var J=m;J<L;J++)d[32767+J]=U,l[32767+J]=[],l[32767+J][1]=U,l[32767+J][0]=J;for(var Z=-(L-1);Z<=-m;Z++)d[32767+Z]=U,l[32767+Z]=[],l[32767+Z][1]=U,l[32767+Z][0]=L-1+Z;m<<=1,L<<=1}}function tt(){for(var m=0;m<256;m++)$[m]=19595*m,$[m+256>>0]=38470*m,$[m+512>>0]=7471*m+32768,$[m+768>>0]=-11059*m,$[m+1024>>0]=-21709*m,$[m+1280>>0]=32768*m+8421375,$[m+1536>>0]=-27439*m,$[m+1792>>0]=-5329*m}function V(m){var L=m[0],U=m[1]-1;while(U>=0){if(L&1<<U)y|=1<<I;if(U--,I--,I<0){if(y==255)w(255),w(0);else w(y);I=7,y=0}}}function w(m){k.push(m)}function K(m){w(m>>8&255),w(m&255)}function ht(m,L){var U,J,Z,_,rt,it,vt,wt,M=0,j,q=8,Et=64;for(j=0;j<q;++j){U=m[M],J=m[M+1],Z=m[M+2],_=m[M+3],rt=m[M+4],it=m[M+5],vt=m[M+6],wt=m[M+7];var X=U+wt,D=U-wt,at=J+vt,W=J-vt,st=Z+it,Ot=Z-it,$t=_+rt,Zt=_-rt,ee=X+$t,Fe=X-$t,Ke=at+st,Je=at-st;m[M]=ee+Ke,m[M+4]=ee-Ke;var un=(Je+Fe)*0.707106781;m[M+2]=Fe+un,m[M+6]=Fe-un,ee=Zt+Ot,Ke=Ot+W,Je=W+D;var hn=(ee-Je)*0.382683433,tr=0.5411961*ee+hn,fn=1.306562965*Je+hn,an=Ke*0.707106781,ln=D+an,gn=D-an;m[M+5]=gn+tr,m[M+3]=gn-tr,m[M+1]=ln+fn,m[M+7]=ln-fn,M+=8}M=0;for(j=0;j<q;++j){U=m[M],J=m[M+8],Z=m[M+16],_=m[M+24],rt=m[M+32],it=m[M+40],vt=m[M+48],wt=m[M+56];var No=U+wt,Yr=U-wt,Ho=J+vt,Oo=J-vt,jo=Z+it,Ro=Z-it,Go=_+rt,sa=_-rt,dn=No+Go,Br=No-Go,er=Ho+jo,nr=Ho-jo;m[M]=dn+er,m[M+32]=dn-er;var Lo=(nr+Br)*0.707106781;m[M+16]=Br+Lo,m[M+48]=Br-Lo,dn=sa+Ro,er=Ro+Oo,nr=Oo+Yr;var Po=(dn-nr)*0.382683433,Ko=0.5411961*dn+Po,Jo=1.306562965*nr+Po,Ao=er*0.707106781,To=Yr+Ao,Uo=Yr-Ao;m[M+40]=Uo+Ko,m[M+24]=Uo-Ko,m[M+8]=To+Jo,m[M+56]=To-Jo,M++}var rr;for(j=0;j<Et;++j)rr=m[j]*L[j],p[j]=rr>0?rr+0.5|0:rr-0.5|0;return p}function ft(){K(65504),K(16),w(74),w(70),w(73),w(70),w(0),w(1),w(1),w(0),K(1),K(1),w(0),w(0)}function et(m){if(!m)return;if(K(65505),m[0]===69&&m[1]===120&&m[2]===105&&m[3]===102)K(m.length+2);else K(m.length+5+2),w(69),w(120),w(105),w(102),w(0);for(var L=0;L<m.length;L++)w(m[L])}function nt(m,L){K(65472),K(17),w(8),K(L),K(m),w(3),w(1),w(17),w(0),w(2),w(17),w(1),w(3),w(17),w(1)}function x(){K(65499),K(132),w(0);for(var m=0;m<64;m++)w(i[m]);w(1);for(var L=0;L<64;L++)w(o[L])}function N(){K(65476),K(418),w(0);for(var m=0;m<16;m++)w(P[m+1]);for(var L=0;L<=11;L++)w(G[L]);w(16);for(var U=0;U<16;U++)w(C[U+1]);for(var J=0;J<=161;J++)w(A[J]);w(1);for(var Z=0;Z<16;Z++)w(Ft[Z+1]);for(var _=0;_<=11;_++)w(T[_]);w(17);for(var rt=0;rt<16;rt++)w(Y[rt+1]);for(var it=0;it<=161;it++)w(kt[it])}function F(m){if(typeof m>"u"||m.constructor!==Array)return;m.forEach((L)=>{if(typeof L!=="string")return;K(65534);var U=L.length;K(U+2);var J;for(J=0;J<U;J++)w(L.charCodeAt(J))})}function pt(){K(65498),K(12),w(3),w(1),w(0),w(2),w(17),w(3),w(17),w(0),w(63),w(0)}function Q(m,L,U,J,Z){var _=Z[0],rt=Z[240],it,vt=16,wt=63,M=64,j=ht(m,L);for(var q=0;q<M;++q)g[H[q]]=j[q];var Et=g[0]-U;if(U=g[0],Et==0)V(J[0]);else it=32767+Et,V(J[d[it]]),V(l[it]);var X=63;for(;X>0&&g[X]==0;X--);if(X==0)return V(_),U;var D=1,at;while(D<=X){var W=D;for(;g[D]==0&&D<=X;++D);var st=D-W;if(st>=vt){at=st>>4;for(var Ot=1;Ot<=at;++Ot)V(rt);st=st&15}it=32767+g[D],V(Z[(st<<4)+d[it]]),V(l[it]),D++}if(X!=wt)V(_);return U}function z(){var m=String.fromCharCode;for(var L=0;L<256;L++)O[L]=m(L)}this.encode=function(m,L){var U=new Date().getTime();if(L)qt(L);k=[],y=0,I=7,K(65496),ft(),F(m.comments),et(m.exifBuffer),x(),nt(m.width,m.height),N(),pt();var J=0,Z=0,_=0;y=0,I=7,this.encode.displayName="_encode_";var{data:rt,width:it,height:vt}=m,wt=it*4,M=it*3,j,q=0,Et,X,D,at,W,st,Ot,$t;while(q<vt){j=0;while(j<wt){at=wt*q+j,W=at,st=-1,Ot=0;for($t=0;$t<64;$t++){if(Ot=$t>>3,st=($t&7)*4,W=at+Ot*wt+st,q+Ot>=vt)W-=wt*(q+1+Ot-vt);if(j+st>=wt)W-=j+st-wt+4;Et=rt[W++],X=rt[W++],D=rt[W++],E[$t]=($[Et]+$[X+256>>0]+$[D+512>>0]>>16)-128,v[$t]=($[Et+768>>0]+$[X+1024>>0]+$[D+1280>>0]>>16)-128,b[$t]=($[Et+1280>>0]+$[X+1536>>0]+$[D+1792>>0]>>16)-128}J=Q(E,s,J,u,f),Z=Q(v,c,Z,h,a),_=Q(b,c,_,h,a),j+=32}q+=8}if(I>=0){var Zt=[];Zt[1]=I+1,Zt[0]=(1<<I+1)-1,V(Zt)}if(K(65497),typeof ur>"u")return new Uint8Array(k);return Buffer.from(k);var ee,Fe};function qt(m){if(m<=0)m=1;if(m>100)m=100;if(R==m)return;var L=0;if(m<50)L=Math.floor(5000/m);else L=Math.floor(200-m*2);dt(L),R=m}function Yt(){var m=new Date().getTime();if(!t)t=50;z(),It(),ot(),tt(),qt(t);var L=new Date().getTime()-m}Yt()}if(typeof ur<"u")ur.exports=ts;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].encode=ts;function ts(t,e){if(typeof e>"u")e=50;var n=new Ea(e),r=n.encode(t,e);return{data:r,width:t.width,height:t.height}}});var is=bt((T0,ri)=>{var ni=function(){var e=new Int32Array([0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5,12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28,35,42,49,56,57,50,43,36,29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54,47,55,62,63]),n=4017,r=799,i=3406,o=2276,s=1567,c=3784,u=5793,h=2896;function f(){}function a(I,E){var v=0,b=[],O,$,R=16;while(R>0&&!I[R-1])R--;b.push({children:[],index:0});var H=b[0],P;for(O=0;O<R;O++){for($=0;$<I[O];$++){H=b.pop(),H.children[H.index]=E[v];while(H.index>0){if(b.length===0)throw Error("Could not recreate Huffman Table");H=b.pop()}H.index++,b.push(H);while(b.length<=O)b.push(P={children:[],index:0}),H.children[H.index]=P.children,H=P;v++}if(O+1<R)b.push(P={children:[],index:0}),H.children[H.index]=P.children,H=P}return b[0].children}function l(I,E,v,b,O,$,R,H,P,G){var{precision:C,samplesPerLine:A,scanLines:Ft,mcusPerLine:T,progressive:Y,maxH:kt,maxV:dt}=v,B=E,It=0,ot=0;function tt(){if(ot>0)return ot--,It>>ot&1;if(It=I[E++],It==255){var M=I[E++];if(M)throw Error("unexpected marker: "+(It<<8|M).toString(16))}return ot=7,It>>>7}function V(M){var j=M,q;while((q=tt())!==null){if(j=j[q],typeof j==="number")return j;if(typeof j!=="object")throw Error("invalid huffman sequence")}return null}function w(M){var j=0;while(M>0){var q=tt();if(q===null)return;j=j<<1|q,M--}return j}function K(M){var j=w(M);if(j>=1<<M-1)return j;return j+(-1<<M)+1}function ht(M,j){var q=V(M.huffmanTableDC),Et=q===0?0:K(q);j[0]=M.pred+=Et;var X=1;while(X<64){var D=V(M.huffmanTableAC),at=D&15,W=D>>4;if(at===0){if(W<15)break;X+=16;continue}X+=W;var st=e[X];j[st]=K(at),X++}}function ft(M,j){var q=V(M.huffmanTableDC),Et=q===0?0:K(q)<<P;j[0]=M.pred+=Et}function et(M,j){j[0]|=tt()<<P}var nt=0;function x(M,j){if(nt>0){nt--;return}var q=$,Et=R;while(q<=Et){var X=V(M.huffmanTableAC),D=X&15,at=X>>4;if(D===0){if(at<15){nt=w(at)+(1<<at)-1;break}q+=16;continue}q+=at;var W=e[q];j[W]=K(D)*(1<<P),q++}}var N=0,F;function pt(M,j){var q=$,Et=R,X=0;while(q<=Et){var D=e[q],at=j[D]<0?-1:1;switch(N){case 0:var W=V(M.huffmanTableAC),st=W&15,X=W>>4;if(st===0)if(X<15)nt=w(X)+(1<<X),N=4;else X=16,N=1;else{if(st!==1)throw Error("invalid ACn encoding");F=K(st),N=X?2:3}continue;case 1:case 2:if(j[D])j[D]+=(tt()<<P)*at;else if(X--,X===0)N=N==2?3:0;break;case 3:if(j[D])j[D]+=(tt()<<P)*at;else j[D]=F<<P,N=0;break;case 4:if(j[D])j[D]+=(tt()<<P)*at;break}q++}if(N===4){if(nt--,nt===0)N=0}}function Q(M,j,q,Et,X){var D=q/T|0,at=q%T,W=D*M.v+Et,st=at*M.h+X;if(M.blocks[W]===void 0&&G.tolerantDecoding)return;j(M,M.blocks[W][st])}function z(M,j,q){var Et=q/M.blocksPerLine|0,X=q%M.blocksPerLine;if(M.blocks[Et]===void 0&&G.tolerantDecoding)return;j(M,M.blocks[Et][X])}var qt=b.length,Yt,m,L,U,J,Z;if(Y)if($===0)Z=H===0?ft:et;else Z=H===0?x:pt;else Z=ht;var _=0,rt,it;if(qt==1)it=b[0].blocksPerLine*b[0].blocksPerColumn;else it=T*v.mcusPerColumn;if(!O)O=it;var vt,wt;while(_<it){for(m=0;m<qt;m++)b[m].pred=0;if(nt=0,qt==1){Yt=b[0];for(J=0;J<O;J++)z(Yt,Z,_),_++}else for(J=0;J<O;J++){for(m=0;m<qt;m++){Yt=b[m],vt=Yt.h,wt=Yt.v;for(L=0;L<wt;L++)for(U=0;U<vt;U++)Q(Yt,Z,_,L,U)}if(_++,_===it)break}if(_===it)do{if(I[E]===255){if(I[E+1]!==0)break}E+=1}while(E<I.length-2);if(ot=0,rt=I[E]<<8|I[E+1],rt<65280)throw Error("marker was not found");if(rt>=65488&&rt<=65495)E+=2;else break}return E-B}function d(I,E){var v=[],b=E.blocksPerLine,O=E.blocksPerColumn,$=b<<3,R=new Int32Array(64),H=new Uint8Array(64);function P(B,It,ot){var tt=E.quantizationTable,V,w,K,ht,ft,et,nt,x,N,F=ot,pt;for(pt=0;pt<64;pt++)F[pt]=B[pt]*tt[pt];for(pt=0;pt<8;++pt){var Q=8*pt;if(F[1+Q]==0&&F[2+Q]==0&&F[3+Q]==0&&F[4+Q]==0&&F[5+Q]==0&&F[6+Q]==0&&F[7+Q]==0){N=u*F[0+Q]+512>>10,F[0+Q]=N,F[1+Q]=N,F[2+Q]=N,F[3+Q]=N,F[4+Q]=N,F[5+Q]=N,F[6+Q]=N,F[7+Q]=N;continue}V=u*F[0+Q]+128>>8,w=u*F[4+Q]+128>>8,K=F[2+Q],ht=F[6+Q],ft=h*(F[1+Q]-F[7+Q])+128>>8,x=h*(F[1+Q]+F[7+Q])+128>>8,et=F[3+Q]<<4,nt=F[5+Q]<<4,N=V-w+1>>1,V=V+w+1>>1,w=N,N=K*c+ht*s+128>>8,K=K*s-ht*c+128>>8,ht=N,N=ft-nt+1>>1,ft=ft+nt+1>>1,nt=N,N=x+et+1>>1,et=x-et+1>>1,x=N,N=V-ht+1>>1,V=V+ht+1>>1,ht=N,N=w-K+1>>1,w=w+K+1>>1,K=N,N=ft*o+x*i+2048>>12,ft=ft*i-x*o+2048>>12,x=N,N=et*r+nt*n+2048>>12,et=et*n-nt*r+2048>>12,nt=N,F[0+Q]=V+x,F[7+Q]=V-x,F[1+Q]=w+nt,F[6+Q]=w-nt,F[2+Q]=K+et,F[5+Q]=K-et,F[3+Q]=ht+ft,F[4+Q]=ht-ft}for(pt=0;pt<8;++pt){var z=pt;if(F[8+z]==0&&F[16+z]==0&&F[24+z]==0&&F[32+z]==0&&F[40+z]==0&&F[48+z]==0&&F[56+z]==0){N=u*ot[pt+0]+8192>>14,F[0+z]=N,F[8+z]=N,F[16+z]=N,F[24+z]=N,F[32+z]=N,F[40+z]=N,F[48+z]=N,F[56+z]=N;continue}V=u*F[0+z]+2048>>12,w=u*F[32+z]+2048>>12,K=F[16+z],ht=F[48+z],ft=h*(F[8+z]-F[56+z])+2048>>12,x=h*(F[8+z]+F[56+z])+2048>>12,et=F[24+z],nt=F[40+z],N=V-w+1>>1,V=V+w+1>>1,w=N,N=K*c+ht*s+2048>>12,K=K*s-ht*c+2048>>12,ht=N,N=ft-nt+1>>1,ft=ft+nt+1>>1,nt=N,N=x+et+1>>1,et=x-et+1>>1,x=N,N=V-ht+1>>1,V=V+ht+1>>1,ht=N,N=w-K+1>>1,w=w+K+1>>1,K=N,N=ft*o+x*i+2048>>12,ft=ft*i-x*o+2048>>12,x=N,N=et*r+nt*n+2048>>12,et=et*n-nt*r+2048>>12,nt=N,F[0+z]=V+x,F[56+z]=V-x,F[8+z]=w+nt,F[48+z]=w-nt,F[16+z]=K+et,F[40+z]=K-et,F[24+z]=ht+ft,F[32+z]=ht-ft}for(pt=0;pt<64;++pt){var qt=128+(F[pt]+8>>4);It[pt]=qt<0?0:qt>255?255:qt}}y($*O*8);var G,C;for(var A=0;A<O;A++){var Ft=A<<3;for(G=0;G<8;G++)v.push(new Uint8Array($));for(var T=0;T<b;T++){P(E.blocks[A][T],H,R);var Y=0,kt=T<<3;for(C=0;C<8;C++){var dt=v[Ft+C];for(G=0;G<8;G++)dt[kt+G]=H[Y++]}}}return v}function p(I){return I<0?0:I>255?255:I}f.prototype={load:function(E){var v=new XMLHttpRequest;v.open("GET",E,!0),v.responseType="arraybuffer",v.onload=function(){var b=new Uint8Array(v.response||v.mozResponseArrayBuffer);if(this.parse(b),this.onload)this.onload()}.bind(this),v.send(null)},parse:function(E){var v=this.opts.maxResolutionInMP*1000*1000,b=0,O=E.length;function $(){var W=E[b]<<8|E[b+1];return b+=2,W}function R(){var W=$(),st=E.subarray(b,b+W-2);return b+=st.length,st}function H(W){var st=1,Ot=1,$t,Zt;for(Zt in W.components)if(W.components.hasOwnProperty(Zt)){if($t=W.components[Zt],st<$t.h)st=$t.h;if(Ot<$t.v)Ot=$t.v}var ee=Math.ceil(W.samplesPerLine/8/st),Fe=Math.ceil(W.scanLines/8/Ot);for(Zt in W.components)if(W.components.hasOwnProperty(Zt)){$t=W.components[Zt];var Ke=Math.ceil(Math.ceil(W.samplesPerLine/8)*$t.h/st),Je=Math.ceil(Math.ceil(W.scanLines/8)*$t.v/Ot),un=ee*$t.h,hn=Fe*$t.v,tr=hn*un,fn=[];y(tr*256);for(var an=0;an<hn;an++){var ln=[];for(var gn=0;gn<un;gn++)ln.push(new Int32Array(64));fn.push(ln)}$t.blocksPerLine=Ke,$t.blocksPerColumn=Je,$t.blocks=fn}W.maxH=st,W.maxV=Ot,W.mcusPerLine=ee,W.mcusPerColumn=Fe}var P=null,G=null,C=null,A,Ft,T=[],Y=[],kt=[],dt=[],B=$(),It=-1;if(this.comments=[],B!=65496)throw Error("SOI not found");B=$();while(B!=65497){var ot,tt,V;switch(B){case 65280:break;case 65504:case 65505:case 65506:case 65507:case 65508:case 65509:case 65510:case 65511:case 65512:case 65513:case 65514:case 65515:case 65516:case 65517:case 65518:case 65519:case 65534:var w=R();if(B===65534){var K=String.fromCharCode.apply(null,w);this.comments.push(K)}if(B===65504){if(w[0]===74&&w[1]===70&&w[2]===73&&w[3]===70&&w[4]===0)P={version:{major:w[5],minor:w[6]},densityUnits:w[7],xDensity:w[8]<<8|w[9],yDensity:w[10]<<8|w[11],thumbWidth:w[12],thumbHeight:w[13],thumbData:w.subarray(14,14+3*w[12]*w[13])}}if(B===65505){if(w[0]===69&&w[1]===120&&w[2]===105&&w[3]===102&&w[4]===0)this.exifBuffer=w.subarray(5,w.length)}if(B===65518){if(w[0]===65&&w[1]===100&&w[2]===111&&w[3]===98&&w[4]===101&&w[5]===0)G={version:w[6],flags0:w[7]<<8|w[8],flags1:w[9]<<8|w[10],transformCode:w[11]}}break;case 65499:var ht=$(),ft=ht+b-2;while(b<ft){var et=E[b++];y(256);var nt=new Int32Array(64);if(et>>4===0)for(tt=0;tt<64;tt++){var x=e[tt];nt[x]=E[b++]}else if(et>>4===1)for(tt=0;tt<64;tt++){var x=e[tt];nt[x]=$()}else throw Error("DQT: invalid table spec");T[et&15]=nt}break;case 65472:case 65473:case 65474:$(),A={},A.extended=B===65473,A.progressive=B===65474,A.precision=E[b++],A.scanLines=$(),A.samplesPerLine=$(),A.components={},A.componentsOrder=[];var N=A.scanLines*A.samplesPerLine;if(N>v){var F=Math.ceil((N-v)/1e6);throw Error(`maxResolutionInMP limit exceeded by ${F}MP`)}var pt=E[b++],Q,z=0,qt=0;for(ot=0;ot<pt;ot++){Q=E[b];var Yt=E[b+1]>>4,m=E[b+1]&15,L=E[b+2];if(Yt<=0||m<=0)throw Error("Invalid sampling factor, expected values above 0");A.componentsOrder.push(Q),A.components[Q]={h:Yt,v:m,quantizationIdx:L},b+=3}H(A),Y.push(A);break;case 65476:var U=$();for(ot=2;ot<U;){var J=E[b++],Z=new Uint8Array(16),_=0;for(tt=0;tt<16;tt++,b++)_+=Z[tt]=E[b];y(16+_);var rt=new Uint8Array(_);for(tt=0;tt<_;tt++,b++)rt[tt]=E[b];ot+=17+_,(J>>4===0?dt:kt)[J&15]=a(Z,rt)}break;case 65501:$(),Ft=$();break;case 65500:$(),$();break;case 65498:var it=$(),vt=E[b++],wt=[],M;for(ot=0;ot<vt;ot++){M=A.components[E[b++]];var j=E[b++];M.huffmanTableDC=dt[j>>4],M.huffmanTableAC=kt[j&15],wt.push(M)}var q=E[b++],Et=E[b++],X=E[b++],D=l(E,b,A,wt,Ft,q,Et,X>>4,X&15,this.opts);b+=D;break;case 65535:if(E[b]!==255)b--;break;default:if(E[b-3]==255&&E[b-2]>=192&&E[b-2]<=254){b-=3;break}else if(B===224||B==225){if(It!==-1)throw Error(`first unknown JPEG marker at offset ${It.toString(16)}, second unknown JPEG marker ${B.toString(16)} at offset ${(b-1).toString(16)}`);It=b-1;let W=$();if(E[b+W-2]===255){b+=W-2;break}}throw Error("unknown JPEG marker "+B.toString(16))}B=$()}if(Y.length!=1)throw Error("only single frame JPEGs supported");for(var ot=0;ot<Y.length;ot++){var at=Y[ot].components;for(var tt in at)at[tt].quantizationTable=T[at[tt].quantizationIdx],delete at[tt].quantizationIdx}this.width=A.samplesPerLine,this.height=A.scanLines,this.jfif=P,this.adobe=G,this.components=[];for(var ot=0;ot<A.componentsOrder.length;ot++){var M=A.components[A.componentsOrder[ot]];this.components.push({lines:d(A,M),scaleX:M.h/A.maxH,scaleY:M.v/A.maxV})}},getData:function(E,v){var b=this.width/E,O=this.height/v,$,R,H,P,G,C,A,Ft,T,Y,kt=0,dt,B,It,ot,tt,V,w,K,ht,ft,et,nt=E*v*this.components.length;y(nt);var x=new Uint8Array(nt);switch(this.components.length){case 1:$=this.components[0];for(Y=0;Y<v;Y++){G=$.lines[0|Y*$.scaleY*O];for(T=0;T<E;T++)dt=G[0|T*$.scaleX*b],x[kt++]=dt}break;case 2:$=this.components[0],R=this.components[1];for(Y=0;Y<v;Y++){G=$.lines[0|Y*$.scaleY*O],C=R.lines[0|Y*R.scaleY*O];for(T=0;T<E;T++)dt=G[0|T*$.scaleX*b],x[kt++]=dt,dt=C[0|T*R.scaleX*b],x[kt++]=dt}break;case 3:if(et=!0,this.adobe&&this.adobe.transformCode)et=!0;else if(typeof this.opts.colorTransform<"u")et=!!this.opts.colorTransform;$=this.components[0],R=this.components[1],H=this.components[2];for(Y=0;Y<v;Y++){G=$.lines[0|Y*$.scaleY*O],C=R.lines[0|Y*R.scaleY*O],A=H.lines[0|Y*H.scaleY*O];for(T=0;T<E;T++){if(!et)K=G[0|T*$.scaleX*b],ht=C[0|T*R.scaleX*b],ft=A[0|T*H.scaleX*b];else dt=G[0|T*$.scaleX*b],B=C[0|T*R.scaleX*b],It=A[0|T*H.scaleX*b],K=p(dt+1.402*(It-128)),ht=p(dt-0.3441363*(B-128)-0.71413636*(It-128)),ft=p(dt+1.772*(B-128));x[kt++]=K,x[kt++]=ht,x[kt++]=ft}}break;case 4:if(!this.adobe)throw Error("Unsupported color mode (4 components)");if(et=!1,this.adobe&&this.adobe.transformCode)et=!0;else if(typeof this.opts.colorTransform<"u")et=!!this.opts.colorTransform;$=this.components[0],R=this.components[1],H=this.components[2],P=this.components[3];for(Y=0;Y<v;Y++){G=$.lines[0|Y*$.scaleY*O],C=R.lines[0|Y*R.scaleY*O],A=H.lines[0|Y*H.scaleY*O],Ft=P.lines[0|Y*P.scaleY*O];for(T=0;T<E;T++){if(!et)tt=G[0|T*$.scaleX*b],V=C[0|T*R.scaleX*b],w=A[0|T*H.scaleX*b],ot=Ft[0|T*P.scaleX*b];else dt=G[0|T*$.scaleX*b],B=C[0|T*R.scaleX*b],It=A[0|T*H.scaleX*b],ot=Ft[0|T*P.scaleX*b],tt=255-p(dt+1.402*(It-128)),V=255-p(dt-0.3441363*(B-128)-0.71413636*(It-128)),w=255-p(dt+1.772*(B-128));x[kt++]=255-tt,x[kt++]=255-V,x[kt++]=255-w,x[kt++]=255-ot}}break;default:throw Error("Unsupported color mode")}return x},copyToImageData:function(E,v){var{width:b,height:O,data:$}=E,R=this.getData(b,O),H=0,P=0,G,C,A,Ft,T,Y,kt,dt,B;switch(this.components.length){case 1:for(C=0;C<O;C++)for(G=0;G<b;G++)if(A=R[H++],$[P++]=A,$[P++]=A,$[P++]=A,v)$[P++]=255;break;case 3:for(C=0;C<O;C++)for(G=0;G<b;G++)if(kt=R[H++],dt=R[H++],B=R[H++],$[P++]=kt,$[P++]=dt,$[P++]=B,v)$[P++]=255;break;case 4:for(C=0;C<O;C++)for(G=0;G<b;G++)if(T=R[H++],Y=R[H++],A=R[H++],Ft=R[H++],kt=255-p(T*(1-Ft/255)+Ft),dt=255-p(Y*(1-Ft/255)+Ft),B=255-p(A*(1-Ft/255)+Ft),$[P++]=kt,$[P++]=dt,$[P++]=B,v)$[P++]=255;break;default:throw Error("Unsupported color mode")}}};var g=0,k=0;function y(I=0){var E=g+I;if(E>k){var v=Math.ceil((E-k)/1024/1024);throw Error(`maxMemoryUsageInMB limit exceeded by at least ${v}MB`)}g=E}return f.resetMaxMemoryUsage=function(I){g=0,k=I},f.getBytesAllocated=function(){return g},f.requestMemoryAllocation=y,f}();if(typeof ri<"u")ri.exports=rs;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].decode=rs;function rs(t,e={}){var n={colorTransform:void 0,useTArray:!1,formatAsRGBA:!0,tolerantDecoding:!0,maxResolutionInMP:100,maxMemoryUsageInMB:512},r={...n,...e},i=new Uint8Array(t),o=new ni;o.opts=r,ni.resetMaxMemoryUsage(r.maxMemoryUsageInMB*1024*1024),o.parse(i);var s=r.formatAsRGBA?4:3,c=o.width*o.height*s;try{ni.requestMemoryAllocation(c);var u={width:o.width,height:o.height,exifBuffer:o.exifBuffer,data:r.useTArray?new Uint8Array(c):Buffer.alloc(c)};if(o.comments.length>0)u.comments=o.comments}catch(h){if(h instanceof RangeError)throw Error("Could not allocate enough memory for the image. Required: "+c);if(h instanceof ReferenceError){if(h.message==="Buffer is not defined")throw Error("Buffer is not globally defined in this environment. Consider setting useTArray to true")}throw h}return o.copyToImageData(u,r.formatAsRGBA),u}});var ss=bt((U0,os)=>{var Ma=ns(),ya=is();os.exports={encode:Ma,decode:ya}});var ii=bt((W0,us)=>{var va=jt("util"),cs=jt("stream"),Dt=us.exports=function(){cs.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};va.inherits(Dt,cs);Dt.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e}),process.nextTick(function(){if(this._process(),this._paused&&this._reads&&this._reads.length>0)this._paused=!1,this.emit("drain")}.bind(this))};Dt.prototype.write=function(t,e){if(!this.writable)return this.emit("error",Error("Stream not writable")),!1;let n;if(Buffer.isBuffer(t))n=t;else n=Buffer.from(t,e||this._encoding);if(this._buffers.push(n),this._buffered+=n.length,this._process(),this._reads&&this._reads.length===0)this._paused=!0;return this.writable&&!this._paused};Dt.prototype.end=function(t,e){if(t)this.write(t,e);if(this.writable=!1,!this._buffers)return;if(this._buffers.length===0)this._end();else this._buffers.push(null),this._process()};Dt.prototype.destroySoon=Dt.prototype.end;Dt.prototype._end=function(){if(this._reads.length>0)this.emit("error",Error("Unexpected end of input"));this.destroy()};Dt.prototype.destroy=function(){if(!this._buffers)return;this.writable=!1,this._reads=null,this._buffers=null,this.emit("close")};Dt.prototype._processReadAllowingLess=function(t){this._reads.shift();let e=this._buffers[0];if(e.length>t.length)this._buffered-=t.length,this._buffers[0]=e.slice(t.length),t.func.call(this,e.slice(0,t.length));else this._buffered-=e.length,this._buffers.shift(),t.func.call(this,e)};Dt.prototype._processRead=function(t){this._reads.shift();let e=0,n=0,r=Buffer.alloc(t.length);while(e<t.length){let i=this._buffers[n++],o=Math.min(i.length,t.length-e);if(i.copy(r,e,0,o),e+=o,o!==i.length)this._buffers[--n]=i.slice(o)}if(n>0)this._buffers.splice(0,n);this._buffered-=t.length,t.func.call(this,r)};Dt.prototype._process=function(){try{while(this._buffered>0&&this._reads&&this._reads.length>0){let t=this._reads[0];if(t.allowLess)this._processReadAllowingLess(t);else if(this._buffered>=t.length)this._processRead(t);else break}if(this._buffers&&!this.writable)this._end()}catch(t){this.emit("error",t)}}});var oi=bt((Sa)=>{var be=[{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]}];Sa.getImagePasses=function(t,e){let n=[],r=t%8,i=e%8,o=(t-r)/8,s=(e-i)/8;for(let c=0;c<be.length;c++){let u=be[c],h=o*u.x.length,f=s*u.y.length;for(let a=0;a<u.x.length;a++)if(u.x[a]<r)h++;else break;for(let a=0;a<u.y.length;a++)if(u.y[a]<i)f++;else break;if(h>0&&f>0)n.push({width:h,height:f,index:c})}return n};Sa.getInterlaceIterator=function(t){return function(e,n,r){let i=e%be[r].x.length,o=(e-i)/be[r].x.length*8+be[r].x[i],s=n%be[r].y.length,c=(n-s)/be[r].y.length*8+be[r].y[s];return o*4+c*t*4}}});var si=bt((q0,hs)=>{hs.exports=function(e,n,r){let i=e+n-r,o=Math.abs(i-e),s=Math.abs(i-n),c=Math.abs(i-r);if(o<=s&&o<=c)return e;if(s<=c)return n;return r}});var ci=bt((Z0,as)=>{var Na=oi(),Ha=si();function fs(t,e,n){let r=t*e;if(n!==8)r=Math.ceil(r/(8/n));return r}var Te=as.exports=function(t,e){let{width:n,height:r,interlace:i,bpp:o,depth:s}=t;if(this.read=e.read,this.write=e.write,this.complete=e.complete,this._imageIndex=0,this._images=[],i){let c=Na.getImagePasses(n,r);for(let u=0;u<c.length;u++)this._images.push({byteWidth:fs(c[u].width,o,s),height:c[u].height,lineIndex:0})}else this._images.push({byteWidth:fs(n,o,s),height:r,lineIndex:0});if(s===8)this._xComparison=o;else if(s===16)this._xComparison=o*2;else this._xComparison=1};Te.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Te.prototype._unFilterType1=function(t,e,n){let r=this._xComparison,i=r-1;for(let o=0;o<n;o++){let s=t[1+o],c=o>i?e[o-r]:0;e[o]=s+c}};Te.prototype._unFilterType2=function(t,e,n){let r=this._lastLine;for(let i=0;i<n;i++){let o=t[1+i],s=r?r[i]:0;e[i]=o+s}};Te.prototype._unFilterType3=function(t,e,n){let r=this._xComparison,i=r-1,o=this._lastLine;for(let s=0;s<n;s++){let c=t[1+s],u=o?o[s]:0,h=s>i?e[s-r]:0,f=Math.floor((h+u)/2);e[s]=c+f}};Te.prototype._unFilterType4=function(t,e,n){let r=this._xComparison,i=r-1,o=this._lastLine;for(let s=0;s<n;s++){let c=t[1+s],u=o?o[s]:0,h=s>i?e[s-r]:0,f=s>i&&o?o[s-r]:0,a=Ha(h,u,f);e[s]=c+a}};Te.prototype._reverseFilterLine=function(t){let e=t[0],n,r=this._images[this._imageIndex],i=r.byteWidth;if(e===0)n=t.slice(1,i+1);else switch(n=Buffer.alloc(i),e){case 1:this._unFilterType1(t,n,i);break;case 2:this._unFilterType2(t,n,i);break;case 3:this._unFilterType3(t,n,i);break;case 4:this._unFilterType4(t,n,i);break;default:throw Error("Unrecognised filter type - "+e)}if(this.write(n),r.lineIndex++,r.lineIndex>=r.height)this._lastLine=null,this._imageIndex++,r=this._images[this._imageIndex];else this._lastLine=n;if(r)this.read(r.byteWidth+1,this._reverseFilterLine.bind(this));else this._lastLine=null,this.complete()}});var ds=bt((_0,gs)=>{var Oa=jt("util"),ls=ii(),ja=ci(),Ra=gs.exports=function(t){ls.call(this);let e=[],n=this;this._filter=new ja(t,{read:this.read.bind(this),write:function(r){e.push(r)},complete:function(){n.emit("complete",Buffer.concat(e))}}),this._filter.start()};Oa.inherits(Ra,ls)});var Ue=bt((X0,ms)=>{ms.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 fi=bt((C0,ps)=>{var ui=[];(function(){for(let t=0;t<256;t++){let e=t;for(let n=0;n<8;n++)if(e&1)e=3988292384^e>>>1;else e=e>>>1;ui[t]=e}})();var hi=ps.exports=function(){this._crc=-1};hi.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=ui[(this._crc^t[e])&255]^this._crc>>>8;return!0};hi.prototype.crc32=function(){return this._crc^-1};hi.crc32=function(t){let e=-1;for(let n=0;n<t.length;n++)e=ui[(e^t[n])&255]^e>>>8;return e^-1}});var ai=bt((V0,ws)=>{var Nt=Ue(),Ga=fi(),Ht=ws.exports=function(t,e){this._options=t,t.checkCRC=t.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[Nt.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[Nt.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[Nt.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[Nt.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[Nt.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[Nt.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=e.read,this.error=e.error,this.metadata=e.metadata,this.gamma=e.gamma,this.transColor=e.transColor,this.palette=e.palette,this.parsed=e.parsed,this.inflateData=e.inflateData,this.finished=e.finished,this.simpleTransparency=e.simpleTransparency,this.headersFinished=e.headersFinished||function(){}};Ht.prototype.start=function(){this.read(Nt.PNG_SIGNATURE.length,this._parseSignature.bind(this))};Ht.prototype._parseSignature=function(t){let e=Nt.PNG_SIGNATURE;for(let n=0;n<e.length;n++)if(t[n]!==e[n]){this.error(Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};Ht.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),n=t.readUInt32BE(4),r="";for(let o=4;o<8;o++)r+=String.fromCharCode(t[o]);let i=Boolean(t[4]&32);if(!this._hasIHDR&&n!==Nt.TYPE_IHDR){this.error(Error("Expected IHDR on beggining"));return}if(this._crc=new Ga,this._crc.write(Buffer.from(r)),this._chunks[n])return this._chunks[n](e);if(!i){this.error(Error("Unsupported critical chunk type "+r));return}this.read(e+4,this._skipChunk.bind(this))};Ht.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};Ht.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};Ht.prototype._parseChunkEnd=function(t){let e=t.readInt32BE(0),n=this._crc.crc32();if(this._options.checkCRC&&n!==e){this.error(Error("Crc error - "+e+" - "+n));return}if(!this._hasIEND)this.read(8,this._parseChunkBegin.bind(this))};Ht.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};Ht.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),n=t.readUInt32BE(4),r=t[8],i=t[9],o=t[10],s=t[11],c=t[12];if(r!==8&&r!==4&&r!==2&&r!==1&&r!==16){this.error(Error("Unsupported bit depth "+r));return}if(!(i in Nt.COLORTYPE_TO_BPP_MAP)){this.error(Error("Unsupported color type"));return}if(o!==0){this.error(Error("Unsupported compression method"));return}if(s!==0){this.error(Error("Unsupported filter method"));return}if(c!==0&&c!==1){this.error(Error("Unsupported interlace method"));return}this._colorType=i;let u=Nt.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:n,depth:r,interlace:Boolean(c),palette:Boolean(i&Nt.COLORTYPE_PALETTE),color:Boolean(i&Nt.COLORTYPE_COLOR),alpha:Boolean(i&Nt.COLORTYPE_ALPHA),bpp:u,colorType:i}),this._handleChunkEnd()};Ht.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};Ht.prototype._parsePLTE=function(t){this._crc.write(t);let e=Math.floor(t.length/3);for(let n=0;n<e;n++)this._palette.push([t[n*3],t[n*3+1],t[n*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};Ht.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};Ht.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===Nt.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(Error("Transparency chunk must be after palette"));return}if(t.length>this._palette.length){this.error(Error("More transparent colors than palette size"));return}for(let e=0;e<t.length;e++)this._palette[e][3]=t[e];this.palette(this._palette)}if(this._colorType===Nt.COLORTYPE_GRAYSCALE)this.transColor([t.readUInt16BE(0)]);if(this._colorType===Nt.COLORTYPE_COLOR)this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]);this._handleChunkEnd()};Ht.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};Ht.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/Nt.GAMMA_DIVISION),this._handleChunkEnd()};Ht.prototype._handleIDAT=function(t){if(!this._emittedHeadersFinished)this._emittedHeadersFinished=!0,this.headersFinished();this.read(-t,this._parseIDAT.bind(this,t))};Ht.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===Nt.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw Error("Expected palette not found");this.inflateData(e);let n=t-e.length;if(n>0)this._handleIDAT(n);else this._handleChunkEnd()};Ht.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};Ht.prototype._parseIEND=function(t){if(this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished)this.finished()}});var li=bt((Ta)=>{var bs=oi(),La=[function(){},function(t,e,n,r){if(r===e.length)throw Error("Ran out of data");let i=e[r];t[n]=i,t[n+1]=i,t[n+2]=i,t[n+3]=255},function(t,e,n,r){if(r+1>=e.length)throw Error("Ran out of data");let i=e[r];t[n]=i,t[n+1]=i,t[n+2]=i,t[n+3]=e[r+1]},function(t,e,n,r){if(r+2>=e.length)throw Error("Ran out of data");t[n]=e[r],t[n+1]=e[r+1],t[n+2]=e[r+2],t[n+3]=255},function(t,e,n,r){if(r+3>=e.length)throw Error("Ran out of data");t[n]=e[r],t[n+1]=e[r+1],t[n+2]=e[r+2],t[n+3]=e[r+3]}],Pa=[function(){},function(t,e,n,r){let i=e[0];t[n]=i,t[n+1]=i,t[n+2]=i,t[n+3]=r},function(t,e,n){let r=e[0];t[n]=r,t[n+1]=r,t[n+2]=r,t[n+3]=e[1]},function(t,e,n,r){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=r},function(t,e,n){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=e[3]}];function Ka(t,e){let n=[],r=0;function i(){if(r===t.length)throw Error("Ran out of data");let o=t[r];r++;let s,c,u,h,f,a,l,d;switch(e){default:throw Error("unrecognised depth");case 16:l=t[r],r++,n.push((o<<8)+l);break;case 4:l=o&15,d=o>>4,n.push(d,l);break;case 2:f=o&3,a=o>>2&3,l=o>>4&3,d=o>>6&3,n.push(d,l,a,f);break;case 1:s=o&1,c=o>>1&1,u=o>>2&1,h=o>>3&1,f=o>>4&1,a=o>>5&1,l=o>>6&1,d=o>>7&1,n.push(d,l,a,f,h,u,c,s);break}}return{get:function(o){while(n.length<o)i();let s=n.slice(0,o);return n=n.slice(o),s},resetAfterLine:function(){n.length=0},end:function(){if(r!==t.length)throw Error("extra data found")}}}function Ja(t,e,n,r,i,o){let{width:s,height:c,index:u}=t;for(let h=0;h<c;h++)for(let f=0;f<s;f++){let a=n(f,h,u);La[r](e,i,a,o),o+=r}return o}function Aa(t,e,n,r,i,o){let{width:s,height:c,index:u}=t;for(let h=0;h<c;h++){for(let f=0;f<s;f++){let a=i.get(r),l=n(f,h,u);Pa[r](e,a,l,o)}i.resetAfterLine()}}Ta.dataToBitMap=function(t,e){let{width:n,height:r,depth:i,bpp:o,interlace:s}=e,c;if(i!==8)c=Ka(t,i);let u;if(i<=8)u=Buffer.alloc(n*r*4);else u=new Uint16Array(n*r*4);let h=Math.pow(2,i)-1,f=0,a,l;if(s)a=bs.getImagePasses(n,r),l=bs.getInterlaceIterator(n,r);else{let d=0;l=function(){let p=d;return d+=4,p},a=[{width:n,height:r}]}for(let d=0;d<a.length;d++)if(i===8)f=Ja(a[d],u,l,o,t,f);else Aa(a[d],u,l,o,c,h);if(i===8){if(f!==t.length)throw Error("extra data found")}else c.end();return u}});var gi=bt((z0,$s)=>{function Wa(t,e,n,r,i){let o=0;for(let s=0;s<r;s++)for(let c=0;c<n;c++){let u=i[t[o]];if(!u)throw Error("index "+t[o]+" not in palette");for(let h=0;h<4;h++)e[o+h]=u[h];o+=4}}function Qa(t,e,n,r,i){let o=0;for(let s=0;s<r;s++)for(let c=0;c<n;c++){let u=!1;if(i.length===1){if(i[0]===t[o])u=!0}else if(i[0]===t[o]&&i[1]===t[o+1]&&i[2]===t[o+2])u=!0;if(u)for(let h=0;h<4;h++)e[o+h]=0;o+=4}}function qa(t,e,n,r,i){let o=255,s=Math.pow(2,i)-1,c=0;for(let u=0;u<r;u++)for(let h=0;h<n;h++){for(let f=0;f<4;f++)e[c+f]=Math.floor(t[c+f]*o/s+0.5);c+=4}}$s.exports=function(t,e,n=!1){let{depth:r,width:i,height:o,colorType:s,transColor:c,palette:u}=e,h=t;if(s===3)Wa(t,h,i,o,u);else{if(c)Qa(t,h,i,o,c);if(r!==8&&!n){if(r===16)h=Buffer.alloc(i*o*4);qa(t,h,i,o,r)}}return h}});var Ms=bt((Y0,Es)=>{var Za=jt("util"),di=jt("zlib"),ks=ii(),_a=ds(),Xa=ai(),Ca=li(),Va=gi(),re=Es.exports=function(t){ks.call(this),this._parser=new Xa(t,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,"gamma"),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=t,this.writable=!0,this._parser.start()};Za.inherits(re,ks);re.prototype._handleError=function(t){if(this.emit("error",t),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy)this._inflate.destroy();if(this._filter)this._filter.destroy(),this._filter.on("error",function(){});this.errord=!0};re.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=di.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let n=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,r=Math.max(n,di.Z_MIN_CHUNK);this._inflate=di.createInflate({chunkSize:r});let i=n,o=this.emit.bind(this,"error");this._inflate.on("error",function(c){if(!i)return;o(c)}),this._filter.on("complete",this._complete.bind(this));let s=this._filter.write.bind(this._filter);this._inflate.on("data",function(c){if(!i)return;if(c.length>i)c=c.slice(0,i);i-=c.length,s(c)}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};re.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new _a(this._bitmapInfo)};re.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};re.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};re.prototype._simpleTransparency=function(){this._metaData.alpha=!0};re.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};re.prototype._finished=function(){if(this.errord)return;if(!this._inflate)this.emit("error","No Inflate block");else this._inflate.end()};re.prototype._complete=function(t){if(this.errord)return;let e;try{let n=Ca.dataToBitMap(t,this._bitmapInfo);e=Va(n,this._bitmapInfo,this._options.skipRescale),n=null}catch(n){this._handleError(n);return}this.emit("parsed",e)}});var vs=bt((B0,ys)=>{var _t=Ue();ys.exports=function(t,e,n,r){let i=[_t.COLORTYPE_COLOR_ALPHA,_t.COLORTYPE_ALPHA].indexOf(r.colorType)!==-1;if(r.colorType===r.inputColorType){let p=function(){let g=new ArrayBuffer(2);return new DataView(g).setInt16(0,256,!0),new Int16Array(g)[0]!==256}();if(r.bitDepth===8||r.bitDepth===16&&p)return t}let o=r.bitDepth!==16?t:new Uint16Array(t.buffer),s=255,c=_t.COLORTYPE_TO_BPP_MAP[r.inputColorType];if(c===4&&!r.inputHasAlpha)c=3;let u=_t.COLORTYPE_TO_BPP_MAP[r.colorType];if(r.bitDepth===16)s=65535,u*=2;let h=Buffer.alloc(e*n*u),f=0,a=0,l=r.bgColor||{};if(l.red===void 0)l.red=s;if(l.green===void 0)l.green=s;if(l.blue===void 0)l.blue=s;function d(){let p,g,k,y=s;switch(r.inputColorType){case _t.COLORTYPE_COLOR_ALPHA:y=o[f+3],p=o[f],g=o[f+1],k=o[f+2];break;case _t.COLORTYPE_COLOR:p=o[f],g=o[f+1],k=o[f+2];break;case _t.COLORTYPE_ALPHA:y=o[f+1],p=o[f],g=p,k=p;break;case _t.COLORTYPE_GRAYSCALE:p=o[f],g=p,k=p;break;default:throw Error("input color type:"+r.inputColorType+" is not supported at present")}if(r.inputHasAlpha){if(!i)y/=s,p=Math.min(Math.max(Math.round((1-y)*l.red+y*p),0),s),g=Math.min(Math.max(Math.round((1-y)*l.green+y*g),0),s),k=Math.min(Math.max(Math.round((1-y)*l.blue+y*k),0),s)}return{red:p,green:g,blue:k,alpha:y}}for(let p=0;p<n;p++)for(let g=0;g<e;g++){let k=d(o,f);switch(r.colorType){case _t.COLORTYPE_COLOR_ALPHA:case _t.COLORTYPE_COLOR:if(r.bitDepth===8){if(h[a]=k.red,h[a+1]=k.green,h[a+2]=k.blue,i)h[a+3]=k.alpha}else if(h.writeUInt16BE(k.red,a),h.writeUInt16BE(k.green,a+2),h.writeUInt16BE(k.blue,a+4),i)h.writeUInt16BE(k.alpha,a+6);break;case _t.COLORTYPE_ALPHA:case _t.COLORTYPE_GRAYSCALE:{let y=(k.red+k.green+k.blue)/3;if(r.bitDepth===8){if(h[a]=y,i)h[a+1]=k.alpha}else if(h.writeUInt16BE(y,a),i)h.writeUInt16BE(k.alpha,a+2);break}default:throw Error("unrecognised color Type "+r.colorType)}f+=c,a+=u}return h}});var Is=bt((D0,Fs)=>{var Ss=si();function xa(t,e,n,r,i){for(let o=0;o<n;o++)r[i+o]=t[e+o]}function za(t,e,n){let r=0,i=e+n;for(let o=e;o<i;o++)r+=Math.abs(t[o]);return r}function Ya(t,e,n,r,i,o){for(let s=0;s<n;s++){let c=s>=o?t[e+s-o]:0,u=t[e+s]-c;r[i+s]=u}}function Ba(t,e,n,r){let i=0;for(let o=0;o<n;o++){let s=o>=r?t[e+o-r]:0,c=t[e+o]-s;i+=Math.abs(c)}return i}function Da(t,e,n,r,i){for(let o=0;o<n;o++){let s=e>0?t[e+o-n]:0,c=t[e+o]-s;r[i+o]=c}}function tl(t,e,n){let r=0,i=e+n;for(let o=e;o<i;o++){let s=e>0?t[o-n]:0,c=t[o]-s;r+=Math.abs(c)}return r}function el(t,e,n,r,i,o){for(let s=0;s<n;s++){let c=s>=o?t[e+s-o]:0,u=e>0?t[e+s-n]:0,h=t[e+s]-(c+u>>1);r[i+s]=h}}function nl(t,e,n,r){let i=0;for(let o=0;o<n;o++){let s=o>=r?t[e+o-r]:0,c=e>0?t[e+o-n]:0,u=t[e+o]-(s+c>>1);i+=Math.abs(u)}return i}function rl(t,e,n,r,i,o){for(let s=0;s<n;s++){let c=s>=o?t[e+s-o]:0,u=e>0?t[e+s-n]:0,h=e>0&&s>=o?t[e+s-(n+o)]:0,f=t[e+s]-Ss(c,u,h);r[i+s]=f}}function il(t,e,n,r){let i=0;for(let o=0;o<n;o++){let s=o>=r?t[e+o-r]:0,c=e>0?t[e+o-n]:0,u=e>0&&o>=r?t[e+o-(n+r)]:0,h=t[e+o]-Ss(s,c,u);i+=Math.abs(h)}return i}var ol={0:xa,1:Ya,2:Da,3:el,4:rl},sl={0:za,1:Ba,2:tl,3:nl,4:il};Fs.exports=function(t,e,n,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=e*i,c=0,u=0,h=Buffer.alloc((s+1)*n),f=o[0];for(let a=0;a<n;a++){if(o.length>1){let l=1/0;for(let d=0;d<o.length;d++){let p=sl[o[d]](t,u,s,i);if(p<l)f=o[d],l=p}}h[c]=f,c++,ol[f](t,u,s,h,c,i),c+=s,u+=s}return h}});var mi=bt((tw,Ns)=>{var Gt=Ue(),cl=fi(),ul=vs(),hl=Is(),fl=jt("zlib"),$e=Ns.exports=function(t){if(this._options=t,t.deflateChunkSize=t.deflateChunkSize||32768,t.deflateLevel=t.deflateLevel!=null?t.deflateLevel:9,t.deflateStrategy=t.deflateStrategy!=null?t.deflateStrategy:3,t.inputHasAlpha=t.inputHasAlpha!=null?t.inputHasAlpha:!0,t.deflateFactory=t.deflateFactory||fl.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType==="number"?t.colorType:Gt.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType==="number"?t.inputColorType:Gt.COLORTYPE_COLOR_ALPHA,[Gt.COLORTYPE_GRAYSCALE,Gt.COLORTYPE_COLOR,Gt.COLORTYPE_COLOR_ALPHA,Gt.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw Error("option color type:"+t.colorType+" is not supported at present");if([Gt.COLORTYPE_GRAYSCALE,Gt.COLORTYPE_COLOR,Gt.COLORTYPE_COLOR_ALPHA,Gt.COLORTYPE_ALPHA].indexOf(t.inputColorType)===-1)throw Error("option input color type:"+t.inputColorType+" is not supported at present");if(t.bitDepth!==8&&t.bitDepth!==16)throw Error("option bit depth:"+t.bitDepth+" is not supported at present")};$e.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};$e.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};$e.prototype.filterData=function(t,e,n){let r=ul(t,e,n,this._options),i=Gt.COLORTYPE_TO_BPP_MAP[this._options.colorType];return hl(r,e,n,this._options,i)};$e.prototype._packChunk=function(t,e){let n=e?e.length:0,r=Buffer.alloc(n+12);if(r.writeUInt32BE(n,0),r.writeUInt32BE(t,4),e)e.copy(r,8);return r.writeInt32BE(cl.crc32(r.slice(4,r.length-4)),r.length-4),r};$e.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*Gt.GAMMA_DIVISION),0),this._packChunk(Gt.TYPE_gAMA,e)};$e.prototype.packIHDR=function(t,e){let n=Buffer.alloc(13);return n.writeUInt32BE(t,0),n.writeUInt32BE(e,4),n[8]=this._options.bitDepth,n[9]=this._options.colorType,n[10]=0,n[11]=0,n[12]=0,this._packChunk(Gt.TYPE_IHDR,n)};$e.prototype.packIDAT=function(t){return this._packChunk(Gt.TYPE_IDAT,t)};$e.prototype.packIEND=function(){return this._packChunk(Gt.TYPE_IEND,null)}});var Rs=bt((ew,js)=>{var al=jt("util"),Hs=jt("stream"),ll=Ue(),gl=mi(),Os=js.exports=function(t){Hs.call(this);let e=t||{};this._packer=new gl(e),this._deflate=this._packer.createDeflate(),this.readable=!0};al.inherits(Os,Hs);Os.prototype.pack=function(t,e,n,r){if(this.emit("data",Buffer.from(ll.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,n)),r)this.emit("data",this._packer.packGAMA(r));let i=this._packer.filterData(t,e,n);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 As=bt((kn,Js)=>{var Gs=jt("assert").ok,We=jt("zlib"),dl=jt("util"),Ls=jt("buffer").kMaxLength;function Ie(t){if(!(this instanceof Ie))return new Ie(t);if(t&&t.chunkSize<We.Z_MIN_CHUNK)t.chunkSize=We.Z_MIN_CHUNK;if(We.Inflate.call(this,t),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,t&&t.maxLength!=null)this._maxLength=t.maxLength}function ml(t){return new Ie(t)}function Ps(t,e){if(e)process.nextTick(e);if(!t._handle)return;t._handle.close(),t._handle=null}Ie.prototype._processChunk=function(t,e,n){if(typeof n==="function")return We.Inflate._processChunk.call(this,t,e,n);let r=this,i=t&&t.length,o=this._chunkSize-this._offset,s=this._maxLength,c=0,u=[],h=0,f;this.on("error",function(p){f=p});function a(p,g){if(r._hadError)return;let k=o-g;if(Gs(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(u.push(y),h+=y.length,s-=y.length,s===0)return!1}if(g===0||r._offset>=r._chunkSize)o=r._chunkSize,r._offset=0,r._buffer=Buffer.allocUnsafe(r._chunkSize);if(g===0)return c+=i-p,i=p,!0;return!1}Gs(this._handle,"zlib binding closed");let l;do l=this._handle.writeSync(e,t,c,i,this._buffer,this._offset,o),l=l||this._writeState;while(!this._hadError&&a(l[0],l[1]));if(this._hadError)throw f;if(h>=Ls)throw Ps(this),RangeError("Cannot create final Buffer. It would be larger than 0x"+Ls.toString(16)+" bytes");let d=Buffer.concat(u,h);return Ps(this),d};dl.inherits(Ie,We.Inflate);function pl(t,e){if(typeof e==="string")e=Buffer.from(e);if(!(e instanceof Buffer))throw TypeError("Not a string or buffer");let n=t._finishFlushFlag;if(n==null)n=We.Z_FINISH;return t._processChunk(e,n)}function Ks(t,e){return pl(new Ie(e),t)}Js.exports=kn=Ks;kn.Inflate=Ie;kn.createInflate=ml;kn.inflateSync=Ks});var pi=bt((nw,Us)=>{var Ts=Us.exports=function(t){this._buffer=t,this._reads=[]};Ts.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};Ts.prototype.process=function(){while(this._reads.length>0&&this._buffer.length){let t=this._reads[0];if(this._buffer.length&&(this._buffer.length>=t.length||t.allowLess)){this._reads.shift();let e=this._buffer;this._buffer=e.slice(t.length),t.func.call(this,e.slice(0,t.length))}else break}if(this._reads.length>0)throw Error("There are some read requests waitng on finished stream");if(this._buffer.length>0)throw Error("unrecognised content at end of stream")}});var Ws=bt(($l)=>{var wl=pi(),bl=ci();$l.process=function(t,e){let n=[],r=new wl(t);return new bl(e,{read:r.read.bind(r),write:function(o){n.push(o)},complete:function(){}}).start(),r.process(),Buffer.concat(n)}});var _s=bt((iw,Zs)=>{var Qs=!0,qs=jt("zlib"),El=As();if(!qs.deflateSync)Qs=!1;var Ml=pi(),yl=Ws(),vl=ai(),Sl=li(),Fl=gi();Zs.exports=function(t,e){if(!Qs)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n;function r(v){n=v}let i;function o(v){i=v}function s(v){i.transColor=v}function c(v){i.palette=v}function u(){i.alpha=!0}let h;function f(v){h=v}let a=[];function l(v){a.push(v)}let d=new Ml(t);if(new vl(e,{read:d.read.bind(d),error:r,metadata:o,gamma:f,palette:c,transColor:s,inflateData:l,simpleTransparency:u}).start(),d.process(),n)throw n;let g=Buffer.concat(a);a.length=0;let k;if(i.interlace)k=qs.inflateSync(g);else{let b=((i.width*i.bpp*i.depth+7>>3)+1)*i.height;k=El(g,{chunkSize:b,maxLength:b})}if(g=null,!k||!k.length)throw Error("bad png - invalid inflate data response");let y=yl.process(k,i);g=null;let I=Sl.dataToBitMap(y,i);y=null;let E=Fl(I,i,e.skipRescale);return i.data=E,i.gamma=h||0,i}});var xs=bt((ow,Vs)=>{var Xs=!0,Cs=jt("zlib");if(!Cs.deflateSync)Xs=!1;var Il=Ue(),Nl=mi();Vs.exports=function(t,e){if(!Xs)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let r=new Nl(e||{}),i=[];if(i.push(Buffer.from(Il.PNG_SIGNATURE)),i.push(r.packIHDR(t.width,t.height)),t.gamma)i.push(r.packGAMA(t.gamma));let o=r.filterData(t.data,t.width,t.height),s=Cs.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 zs=bt((jl)=>{var Hl=_s(),Ol=xs();jl.read=function(t,e){return Hl(t,e||{})};jl.write=function(t,e){return Ol(t,e)}});var Bs=bt((Al)=>{var Ll=jt("util"),Ys=jt("stream"),Pl=Ms(),Kl=Rs(),Jl=zs(),Lt=Al.PNG=function(t){if(Ys.call(this),t=t||{},this.width=t.width|0,this.height=t.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,t.fill&&this.data)this.data.fill(0);this.gamma=0,this.readable=this.writable=!0,this._parser=new Pl(t),this._parser.on("error",this.emit.bind(this,"error")),this._parser.on("close",this._handleClose.bind(this)),this._parser.on("metadata",this._metadata.bind(this)),this._parser.on("gamma",this._gamma.bind(this)),this._parser.on("parsed",function(e){this.data=e,this.emit("parsed",e)}.bind(this)),this._packer=new Kl(t),this._packer.on("data",this.emit.bind(this,"data")),this._packer.on("end",this.emit.bind(this,"end")),this._parser.on("close",this._handleClose.bind(this)),this._packer.on("error",this.emit.bind(this,"error"))};Ll.inherits(Lt,Ys);Lt.sync=Jl;Lt.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};Lt.prototype.parse=function(t,e){if(e){let n,r;n=function(i){this.removeListener("error",r),this.data=i,e(null,this)}.bind(this),r=function(i){this.removeListener("parsed",n),e(i,null)}.bind(this),this.once("parsed",n),this.once("error",r)}return this.end(t),this};Lt.prototype.write=function(t){return this._parser.write(t),!0};Lt.prototype.end=function(t){this._parser.end(t)};Lt.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};Lt.prototype._gamma=function(t){this.gamma=t};Lt.prototype._handleClose=function(){if(!this._parser.writable&&!this._packer.readable)this.emit("close")};Lt.bitblt=function(t,e,n,r,i,o,s,c){if(n|=0,r|=0,i|=0,o|=0,s|=0,c|=0,n>t.width||r>t.height||n+i>t.width||r+o>t.height)throw Error("bitblt reading outside image");if(s>e.width||c>e.height||s+i>e.width||c+o>e.height)throw Error("bitblt writing outside image");for(let u=0;u<o;u++)t.data.copy(e.data,(c+u)*e.width+s<<2,(r+u)*t.width+n<<2,(r+u)*t.width+n+i<<2)};Lt.prototype.bitblt=function(t,e,n,r,i,o,s){return Lt.bitblt(this,t,e,n,r,i,o,s),this};Lt.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let n=0;n<t.width;n++){let r=t.width*e+n<<2;for(let i=0;i<3;i++){let o=t.data[r+i]/255;o=Math.pow(o,0.45454545454545453/t.gamma),t.data[r+i]=Math.round(o*255)}}t.gamma=0}};Lt.prototype.adjustGamma=function(){Lt.adjustGamma(this)}});var ho=bt((G$,of)=>{var uo={to(t,e){if(!e)return`\x1B[${t+1}G`;return`\x1B[${e+1};${t+1}H`},move(t,e){let n="";if(t<0)n+=`\x1B[${-t}D`;else if(t>0)n+=`\x1B[${t}C`;if(e<0)n+=`\x1B[${-e}A`;else if(e>0)n+=`\x1B[${e}B`;return n},up:(t=1)=>`\x1B[${t}A`,down:(t=1)=>`\x1B[${t}B`,forward:(t=1)=>`\x1B[${t}C`,backward:(t=1)=>`\x1B[${t}D`,nextLine:(t=1)=>"\x1B[E".repeat(t),prevLine:(t=1)=>"\x1B[F".repeat(t),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},lp={up:(t=1)=>"\x1B[S".repeat(t),down:(t=1)=>"\x1B[T".repeat(t)},gp={screen:"\x1B[2J",up:(t=1)=>"\x1B[1J".repeat(t),down:(t=1)=>"\x1B[J".repeat(t),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(t){let e="";for(let n=0;n<t;n++)e+=this.line+(n<t-1?uo.up():"");if(t)e+=uo.left;return e}};of.exports={cursor:uo,scroll:lp,erase:gp,beep:"\x07"}});import{spawnSync as k0}from"node:child_process";import{isMainThread as E0}from"node:worker_threads";import{parseArgs as m0}from"node:util";var ne={name:"@kecan0406/ttheme",version:"1.0.34",type:"module",bin:{ttheme:"bin/ttheme.js"},files:["bin","dist/manifest.json","dist/ghostty/ttheme.conf","shell","!shell/check.zsh","ghostty/shaders"],description:"Character terminal palettes for Ghostty, kitty, Alacritty, WezTerm, 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",typescript:"^5.8.2"},engines:{bun:">=1.3",node:">=20.11"}};import{rmSync as Mu}from"node:fs";import{basename as ed,join as Jn}from"node:path";var pa=/^#[0-9a-f]{6}$/;function Qo(t){return pa.test(t)}function Rt(t){let e=Number.parseInt(t.slice(1),16);return[e>>16&255,e>>8&255,e&255]}function Bt(t){let[e,n,r]=Rt(t).map((i)=>{let o=i/255;return o<=0.03928?o/12.92:((o+0.055)/1.055)**2.4});return 0.2126*e+0.7152*n+0.0722*r}function fe(t,e){let n=Bt(t),r=Bt(e);return(Math.max(n,r)+0.05)/(Math.min(n,r)+0.05)}function or(t,e){return Math.round(fe(t,e)*100)/100}var pe=7,qo=3,Dr=0.15,Zo=1.6,_o=[1,2,3,4,5,6,9,10,11,12,13,14],Xo=[7,15];function mn(t,e){let n=t.ansi[e];if(n===void 0)throw Error(`${t.name}: missing ANSI ${e}`);return n}function ti(t,e,n){let r=t.background;return e.flatMap((i)=>{let o=mn(t,i);return fe(o,r)<n?[`ANSI ${i} ${o} on ${r} is ${or(o,r)}:1, needs ${n}:1`]:[]})}function Co(t,e){return Math.min(...e.map((n)=>fe(mn(t,n),t.background)))}var sr=[{rule:"foreground",label:"foreground on background",unit:"ratio",min:pe,measure:({foreground:t,background:e})=>fe(t,e),check:({foreground:t,background:e})=>fe(t,e)<pe?[`foreground ${t} on ${e} is ${or(t,e)}:1, needs ${pe}:1`]:[]},{rule:"accents",label:"weakest accent on background",unit:"ratio",min:qo,measure:(t)=>Co(t,_o),check:(t)=>ti(t,_o,qo)},{rule:"ansi0-dark",label:"ansi0 luminance",unit:"luminance",max:Dr,measure:(t)=>Bt(mn(t,0)),check:(t)=>{let e=mn(t,0);return Bt(e)>Dr?[`ANSI 0 ${e} has luminance ${Bt(e).toFixed(3)}, needs <= ${Dr}`]:[]}},{rule:"light-ansi",label:"ansi7 and ansi15 on background",unit:"ratio",min:pe,measure:(t)=>Co(t,Xo),check:(t)=>ti(t,Xo,pe)},{rule:"ansi8-visible",label:"ansi8 on background",unit:"ratio",min:Zo,measure:(t)=>fe(mn(t,8),t.background),check:(t)=>ti(t,[8],Zo)},{rule:"selection",label:"foreground on selection",unit:"ratio",min:pe,measure:({foreground:t,selectionBackground:e})=>e===void 0?Number.NaN:fe(t,e),check:({foreground:t,selectionBackground:e})=>e!==void 0&&fe(t,e)<pe?[`foreground ${t} on selection ${e} is ${or(t,e)}:1, needs ${pe}:1`]:[]}],I0=sr.map((t)=>t.rule),cr=sr.map(({rule:t,label:e,unit:n,min:r,max:i})=>({rule:t,label:e,unit:n,...r===void 0?{}:{min:r},...i===void 0?{}:{max:i}}));function Vo(t){return sr.map((e)=>Math.round(e.measure(t)*1000)/1000)}function ei(t){return sr.filter((e)=>!t.waive.includes(e.rule)).flatMap((e)=>e.check(t).map((n)=>({theme:t.name,rule:e.rule,detail:n})))}function xo(t){return t.flatMap(ei)}var wa=["black","red","green","yellow","blue","magenta","cyan","white"];function zo(t,e){return[t,...wa.map((n,r)=>`${n} = '${e[r]}'`),""].join(`
|
|
3
|
+
`)}var pn={id:"alacritty",limits:"no shaders, no runtime color API (OSC only)",emit(t){let e=[...Ae(t),"","[colors.primary]",`background = '${t.background}'`,`foreground = '${t.foreground}'`,"","[colors.cursor]",`cursor = '${t.cursor}'`,`text = '${t.background}'`,"","[colors.selection]",`background = '${t.selectionBackground}'`,`text = '${t.foreground}'`,"",zo("[colors.normal]",t.ansi.slice(0,8)),zo("[colors.bright]",t.ansi.slice(8,16))].join(`
|
|
4
|
+
`),n=[`# ${t.name} — font settings.`,`# Pair with the palette: import = ["~/.config/alacritty/themes/${t.name}.toml"]`,"","[font]",`size = ${t.font.size}`,"","[font.normal]",`family = '${t.font.family}'`,""].join(`
|
|
5
|
+
`);return[{path:`alacritty/themes/${t.name}.toml`,content:e},{path:`alacritty/config/${t.name}.toml`,content:n}]}};import{isDeepStrictEqual as ba}from"node:util";var wn={id:"ghostty",emit(t){let e=[...Ae(t),`background = ${t.background}`,`foreground = ${t.foreground}`,`cursor-color = ${t.cursor}`,`selection-background = ${t.selectionBackground}`,`selection-foreground = ${t.foreground}`,...t.ansi.map((n,r)=>`palette = ${r}=${n}`),"palette-generate = true","","macos-icon = custom-style",`macos-icon-ghost-color = ${t.ghostty.iconGhost}`,`macos-icon-screen-color = ${t.ghostty.iconScreen.join(",")}`,"macos-icon-frame = chrome",""].join(`
|
|
6
|
+
`);return[{path:`ghostty/themes/${t.name}`,content:e}]},emitShared(t){let[e]=t;if(!e)return[];for(let r of t)if(!ba(r.font,e.font)||r.ghostty.shader!==e.ghostty.shader)throw Error(`${r.name}: per-theme font/shader overrides cannot be expressed in the shared ghostty/ttheme.conf`);return[{path:"ghostty/ttheme.conf",content:["# ttheme — shared font and shader, identical for every palette.","# Pick colors with: theme = <palette>",`font-family = ${e.font.family}`,`font-size = ${e.font.size}`,...e.font.codepointMap.map((r)=>`font-codepoint-map = ${r.range}=${r.family}`),...e.ghostty.shader?["",`custom-shader = ~/.config/ghostty/shaders/${e.ghostty.shader}`,"custom-shader-animation = true"]:[],""].join(`
|
|
7
|
+
`)}]}};function we(t){let[e,n,r]=Rt(t);return{"Alpha Component":1,"Blue Component":r/255,"Color Space":"P3","Green Component":n/255,"Red Component":e/255}}function Yo(t){return{...Object.fromEntries(t.ansi.map((e,n)=>[`Ansi ${n} Color`,we(e)])),"Background Color":we(t.background),"Bold Color":we(t.foreground),"Cursor Color":we(t.cursor),"Cursor Text Color":we(t.background),"Foreground Color":we(t.foreground),"Selected Text Color":we(t.foreground),"Selection Color":we(t.selectionBackground)}}function $a(t){return t?{"Background Image Location":t.image,"Background Image Mode":t.cover?2:3,Blend:t.opacity}:{"Background Image Location":""}}function Bo(t,e,n,r){let i=(s,c)=>({Name:`ttheme · ${c}`,Guid:`ttheme-${c}`,...r?{"Dynamic Profile Parent GUID":r}:{},"Use Separate Colors for Light and Dark Mode":!1,"Harmonize 256 Colors":!0,...$a(e.get(s.name)),...Yo(s)}),o=[...n?[i(n,"default")]:[],...t.map((s)=>i(s,s.name))];return`${JSON.stringify({Profiles:o},null,2)}
|
|
8
|
+
`}function ka(t,e){return[` <key>${t}</key>`,"\t<dict>",...Object.entries(e).flatMap(([n,r])=>[` <key>${n}</key>`,typeof r==="string"?` <string>${r}</string>`:` <real>${r}</real>`]),"\t</dict>"].join(`
|
|
9
|
+
`)}var bn={id:"iterm2",limits:"colors only — font lives in the profile; colors are Display P3, the space iTerm2 reads OSC colors in",emit(t){let e=['<?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(Yo(t)).map(([n,r])=>ka(n,r)),"</dict>","</plist>",""].join(`
|
|
10
|
+
`);return[{path:`iterm2/${t.name}.itermcolors`,content:e}]}};var $n={id:"kitty",limits:"no GLSL shaders, no per-codepoint font mapping",emit(t){let e=[...Ae(t),`background ${t.background}`,`foreground ${t.foreground}`,`cursor ${t.cursor}`,`cursor_text_color ${t.background}`,`selection_background ${t.selectionBackground}`,`selection_foreground ${t.foreground}`,...t.ansi.map((r,i)=>`color${i} ${r}`),""].join(`
|
|
11
|
+
`),n=[`# ${t.name} — font settings.`,`# Pair with the palette: include themes/${t.name}.conf`,`font_family ${t.font.family}`,`font_size ${t.font.size}`,""].join(`
|
|
12
|
+
`);return[{path:`kitty/themes/${t.name}.conf`,content:e},{path:`kitty/config/${t.name}.conf`,content:n}]}};function Do(t){return["# Generated by ttheme — rewritten on every add, remove and default; do not edit.","import os","",`THEMES = ${JSON.stringify(t.themes)}`,`BACKGROUNDS = ${JSON.stringify(t.backgrounds)}`,"PLACES = {"," 'top-left': 'top-left', 'top-center': 'top', 'top-right': 'top-right',"," 'center-left': 'left', 'center': 'center', 'center-center': 'center', 'center-right': 'right',"," 'bottom-left': 'bottom-left', 'bottom-center': 'bottom', 'bottom-right': 'bottom-right',","}","","shown = {}","faded = {}","worn = {}","","","def locate(path):"," if path.startswith('~/'):"," return os.path.expanduser(path)"," return path if os.path.isabs(path) else os.path.join(BACKGROUNDS, path)","","","def read(path, into):"," try:"," with open(path, encoding='utf-8') as f:"," lines = f.read().splitlines()"," except OSError:"," return False"," for line in lines:"," key, sep, value = line.partition('=')"," key, value = key.strip(), value.strip()"," if not sep or not key or key.startswith('#'):"," continue"," if key == 'config-file':"," read(locate(value.lstrip('?')), into)"," else:"," into[key] = value"," return True","","","def logo(palette):"," c = {}"," if not palette or not read(os.path.join(BACKGROUNDS, palette + '.conf'), c):"," return None"," image = c.get('background-image', '')"," try:"," opacity = min(float(c.get('background-image-opacity', '1')), 1.0)"," except ValueError:"," opacity = 1.0"," if not image or opacity <= 0:"," return None"," return locate(image), PLACES.get(c.get('background-image-position', 'center'), 'center'), opacity","","","def fade(path, opacity):"," key = f'{path}#{opacity}'"," if key not in faded:"," from kitty.fast_data_types import load_png_data, png_from_32bit_rgba_data"," with open(path, 'rb') as f:"," rgba, width, height = load_png_data(f.read())"," data = bytearray(rgba)"," data[3::4] = data[3::4].translate(bytes(round(a * opacity) for a in range(256)))"," if len(faded) > 8:"," faded.clear()"," faded[key] = png_from_32bit_rgba_data(bytes(data), width, height)"," return key, faded[key]","","","def show(window):"," want = logo(window.user_vars.get('ttheme_shown') or '')"," if window.id in shown and shown[window.id] == want:"," return"," shown[window.id] = want"," try:"," if want is None:"," window.set_logo('')"," elif want[2] < 1:"," key, png = fade(want[0], want[2])"," window.set_logo(key, want[1], 1, png)"," else:"," window.set_logo(want[0], want[1], 1)"," except Exception:"," shown.pop(window.id, None)","","","def theme(palette):"," path = os.path.join(THEMES, palette + '.conf')"," if not palette or not os.path.exists(path):"," return None"," from kitty.colors import parse_colors"," return parse_colors([path])","","","def wear(palette):"," colors = theme(palette) if worn.get('startup') != palette else None"," if colors is None:"," return"," from kitty.colors import patch_colors"," patch_colors(colors[0], colors[1], True, ())"," worn['startup'] = palette","","","def rewear(boss):"," from kitty.colors import patch_colors"," for window in tuple(boss.all_windows):"," colors = theme(window.user_vars.get('ttheme_worn') or '')"," if colors is not None:"," patch_colors(colors[0], colors[1], False, (window,))","","","def on_load(boss, data):"," if getattr(boss, 'ttheme_rewears', False):"," return"," load = boss.load_config_file",""," def reload(*args, **kwargs):"," load(*args, **kwargs)"," worn.pop('startup', None)"," rewear(boss)",""," boss.load_config_file = reload"," boss.ttheme_rewears = True","","","def on_set_user_var(boss, window, data):"," if data['key'] == 'ttheme_shown':"," show(window)"," elif data['key'] == 'ttheme_startup':"," wear(data['value'] or '')","","","def on_focus_change(boss, window, data):"," if data['focused']:"," show(window)","","","def on_close(boss, window, data):"," shown.pop(window.id, None)",""].join(`
|
|
13
|
+
`)}import{createHash as Wl}from"node:crypto";import{mkdirSync as hc,readdirSync as Ne,readFileSync as fc,renameSync as ac,rmSync as qe,statSync as Ql,utimesSync as ql,writeFileSync as ar}from"node:fs";import{isAbsolute as Zl,join as Mt}from"node:path";var ec=ir(ss(),1),hr=ir(Bs(),1),Ds=[137,80,78,71,13,10,26,10],nc=13;function En(t){return t.length>=Ds.length&&Ds.every((e,n)=>t[n]===e)}function Tl(t){let e=hr.PNG.sync.read(Buffer.from(t));return{width:e.width,height:e.height,data:new Uint8Array(e.data)}}function rc(t,e){if(En(t)){let n=Mn(t);if(n&&n.width*n.height>e)throw Error(`${n.width}×${n.height} is over ${e/1e6} megapixels`);return Tl(t)}if(t[0]===255&&t[1]===216){let n=ec.decode(t,{useTArray:!0,formatAsRGBA:!0,maxResolutionInMP:e/1e6,maxMemoryUsageInMB:1024});return{width:n.width,height:n.height,data:n.data}}throw Error("not a PNG or JPEG image")}function Qe(t){let e=new hr.PNG({width:t.width,height:t.height});return e.data=Buffer.from(t.data),hr.PNG.sync.write(e)}function tc(t,e){for(let n=0;n+e.length<=t.length;n++){let r=!0;for(let i=0;i<e.length&&r;i++)r=t[n+i]===e.charCodeAt(i);if(r)return n}return-1}function Mn(t){if(t.length<33||!En(t))return null;let e=new DataView(t.buffer,t.byteOffset,t.byteLength),n=e.getUint32(16),r=e.getUint32(20);if(t[25]===4||t[25]===6)return{width:n,height:r,alpha:!0};let i=tc(t,"IDAT");return{width:n,height:r,alpha:tc(i===-1?t:t.subarray(0,i),"tRNS")!==-1}}function ic(t,e=nc){let{width:n,height:r}=t,i=-1,o=-1;for(let s=0;s<t.height;s++)for(let c=0;c<t.width;c++)if((t.data[(s*t.width+c)*4+3]??0)>=e)n=Math.min(n,c),i=Math.max(i,c),r=Math.min(r,s),o=Math.max(o,s);return i<0?null:{x:n,y:r,w:i-n+1,h:o-r+1}}function yn(t,e={x:0,y:0,w:t.width,h:t.height}){let n=0;for(let r=e.y;r<e.y+e.h;r++)for(let i=e.x;i<e.x+e.w;i++)if((t.data[(r*t.width+i)*4+3]??0)<nc)n++;return Math.round(n*100/(e.w*e.h))}function Ul(t,e){if(e<=1)return t;let n=Math.max(1,Math.floor(t.width/e)),r=Math.max(1,Math.floor(t.height/e)),i=new Uint8Array(n*r*4),o=t.data;for(let s=0;s<r;s++)for(let c=0;c<n;c++){let u=0,h=0,f=0,a=0;for(let d=0;d<e;d++)for(let p=0;p<e;p++){let g=((s*e+d)*t.width+c*e+p)*4,k=o[g+3]??0;u+=(o[g]??0)*k,h+=(o[g+1]??0)*k,f+=(o[g+2]??0)*k,a+=k}let l=(s*n+c)*4;if(a>0)i[l]=Math.round(u/a),i[l+1]=Math.round(h/a),i[l+2]=Math.round(f/a);i[l+3]=Math.round(a/(e*e))}return{width:n,height:r,data:i}}function oc(t,e,n){let r=Math.min(e/t.width,n/t.height),i=Math.max(1,Math.round(t.width*r)),o=Math.max(1,Math.round(t.height*r)),s=fr(t,{x:0,y:0,w:t.width,h:t.height},i,o),c=new Uint8Array(e*n*4),u=Math.floor((e-i)/2),h=Math.floor((n-o)/2);for(let f=0;f<o;f++)c.set(s.data.subarray(f*i*4,(f+1)*i*4),((h+f)*e+u)*4);return{width:e,height:n,data:c}}function fr(t,e,n,r){let i=Math.max(1,Math.floor(Math.min(e.w/n,e.h/r))),o=Ul(t,i),s=o.data,c=new Uint8Array(n*r*4);for(let u=0;u<r;u++){let h=Math.min(o.height-1,Math.max(0,e.y/i+(u+0.5)*e.h/i/r-0.5)),f=Math.floor(h),a=Math.min(o.height-1,f+1),l=h-f;for(let d=0;d<n;d++){let p=Math.min(o.width-1,Math.max(0,e.x/i+(d+0.5)*e.w/i/n-0.5)),g=Math.floor(p),k=Math.min(o.width-1,g+1),y=p-g,I=(f*o.width+g)*4,E=(f*o.width+k)*4,v=(a*o.width+g)*4,b=(a*o.width+k)*4,O=(s[I+3]??0)*(1-y)*(1-l),$=(s[E+3]??0)*y*(1-l),R=(s[v+3]??0)*(1-y)*l,H=(s[b+3]??0)*y*l,P=O+$+R+H,G=(u*n+d)*4;if(P>0)for(let C=0;C<3;C++){let A=(s[I+C]??0)*O+(s[E+C]??0)*$+(s[v+C]??0)*R+(s[b+C]??0)*H;c[G+C]=Math.round(A/P)}c[G+3]=Math.round(P)}}return{width:n,height:r,data:c}}var sc={width:2560,height:1550},_l=2560,Xl=0.1,ae={tall:1.15,reach:0.4,widest:0.95,headroom:0.04,margin:0.03,stands:12},Cl=Bt(wi("#19161e","#9b86c8",0.2)),Vl="shelf";function wi(t,e,n){let r=Rt(t),i=Rt(e);return`#${r.map((o,s)=>Math.round(o+((i[s]??0)-o)*n).toString(16).padStart(2,"0")).join("")}`}function xl(t,e){if(e==="background"||e==="foreground"||e==="cursor")return t[e];if(e==="selection"&&t.selection)return t.selection;let n=/^ansi(\d|1[0-5])$/.exec(e),r=n?t.ansi[Number(n[1])]:void 0;if(!r)throw Error(`${t.name} has no slot ${e}`);return r}function cc(t){if(t(1))return 1;let e=0,n=1;for(let r=0;r<40;r++){let i=(e+n)/2;if(t(i))e=i;else n=i}return e}function uc(t,e){let n=xl(t,e),i=cc((h)=>ei({name:t.name,background:wi(t.background,n,h),foreground:t.foreground,ansi:t.ansi,waive:t.waived??[]}).length===0),o=cc((h)=>Bt(wi(t.background,n,h))<=Cl),s=Math.floor(Math.min(i,o)*1000)/1000,c=Rt(t.background),u=Math.hypot(...Rt(n).map((h,f)=>(h-(c[f]??0))*s));return{slot:e,color:n,cap:i,matched:o,opacity:s,reach:u}}function lr(t,e){let n=uc(t,"cursor");if(n.opacity>=Xl)return n;return e.filter((r)=>r!=="cursor"&&r!=="background").map((r)=>uc(t,r)).reduce((r,i)=>i.reach>r.reach?i:r,n)}function bi(t,e,n){let r=Rt(e),i=Rt(n),o=t.data;for(let s=0;s<o.length;s+=4){let c=(0.299*(o[s]??0)+0.587*(o[s+1]??0)+0.114*(o[s+2]??0))/255;for(let u=0;u<3;u++)o[s+u]=Math.round((r[u]??0)+((i[u]??0)-(r[u]??0))*c)}return t}function zl(t,e,n){let r=Rt(e),i=t.data,o=new Uint8Array(i.length);for(let s=0;s<i.length;s+=4){let c=(i[s+3]??0)/255*n;for(let u=0;u<3;u++)o[s+u]=Math.round((r[u]??0)*(1-c)+(i[s+u]??0)*c);o[s+3]=255}return{width:t.width,height:t.height,data:o}}function lc(t){return ic(t)??{x:0,y:0,w:t.width,h:t.height}}function Yl(t,e){if(t<=0||e<=0)return sc;let n=Math.min(1,sc.width/Math.max(t,e));return{width:Math.round(t*n),height:Math.round(e*n)}}function Bl(t,e){let n=Math.min(1,_l/Math.max(e.w,e.h));return fr(t,e,Math.round(e.w*n),Math.round(e.h*n))}function gc(t,e,n,r){if(r<ae.stands){let u=t.w*n>t.h*e?{x:t.x+(t.w-t.h*e/n)/2,y:t.y,w:t.h*e/n,h:t.h}:{x:t.x,y:t.y,w:t.w,h:t.w*n/e};return{crop:u,at:{x:0,y:0,w:e,h:n},focus:(u.y-t.y+u.h/2)/t.h}}let i=Math.max(ae.tall*n,ae.reach*e*t.h/t.w),o=i*t.w/t.h;if(o>ae.widest*e)o=ae.widest*e,i=o*t.h/t.w;let s=ae.headroom*n,c=Math.min(1,(n-s)/i);return{crop:{x:t.x,y:t.y,w:t.w,h:t.h*c},at:{x:e*(1-ae.margin)-o,y:s,w:o,h:i*c},focus:Math.min(1,(n/2-s)/i)}}function dc(t,e,n,r){let i=Math.max(1,Math.round(e.at.w)),o=Math.max(1,Math.round(e.at.h)),s=fr(t,e.crop,i,o),c=new Uint8Array(n*r*4),u=Math.round(e.at.x),h=Math.round(e.at.y);for(let f=0;f<o;f++){let a=h+f,l=Math.max(0,-u),d=Math.min(i,n-u);if(a<0||a>=r||d<=l)continue;c.set(s.data.subarray((f*i+l)*4,(f*i+d)*4),(a*n+u+l)*4)}return{width:n,height:r,data:c}}function mc(t,e,n,r,i){let o=lc(t),s=dc(t,gc(o,r,i,yn(t,o)),r,i);return zl(bi(s,e.background,n.color),e.background,n.opacity)}function ke(t){return Mt(t,"ttheme","backgrounds")}function Dl(t,e,n,r,i){return[...r?[`# from ${r}`]:[],...i?[`# image ${i}`]:[],`background-image = ${e}`,"background-image-fit = cover","background-image-position = top-right",`background-image-opacity = ${n}`,`config-file = ?${t}.tune.conf`,`config-file = ?${t}.off.conf`,""].join(`
|
|
14
|
+
`)}function pc(t,e,n){let r=new Map;for(let s of[`${e}.conf`,`${e}.tune.conf`,`${e}.off.conf`]){let c;try{c=fc(Mt(t,s),"utf8")}catch{if(s===`${e}.conf`)return;continue}for(let u of c.split(`
|
|
15
|
+
`)){let h=/^(background-image(?:-fit|-opacity)?)\s*=\s*(.*?)\s*$/.exec(u);if(h)r.set(h[1],h[2])}}let i=r.get("background-image")??"";if(i==="")return;let o=Number(r.get("background-image-opacity")??1);return{image:i.startsWith("~/")?Mt(n,i.slice(2)):Zl(i)?i:Mt(t,i),opacity:Number.isFinite(o)?o:1,cover:r.get("background-image-fit")==="cover"}}function tg(t,e){for(let n of Ne(t))if($i(n,e))qe(Mt(t,n))}function eg(t){return`${t.site}_${t.id}`}function gr(t,e){return Mt(t,Vl,e)}function $i(t,e){let n=t.slice(e.length);return t.startsWith(e)&&(n===".conf"||n===".tune.conf"||n===".off.conf"||/^(\.[0-9a-f]{8})?(@[a-z0-9-]+)?\.png$/.test(n))}function vn(t,e){try{return/^# image (\S+)$/m.exec(fc(Mt(t,`${e}.conf`),"utf8"))?.[1]}catch{return}}function ng(t,e){try{return Ne(gr(t,e))}catch{return[]}}function wc(t,e){let n=vn(t,e);return[...n?[n]:[],...ng(t,e)].sort()}function bc(t,e){let n=vn(t,e);if(!n)return;let r=Mt(gr(t,e),n);qe(r,{recursive:!0,force:!0}),hc(r,{recursive:!0});for(let i of Ne(t))if($i(i,e))ac(Mt(t,i),Mt(r,i.slice(e.length)))}function $c(t,e,n){let r=Mt(gr(t,e),n);for(let i of Ne(r))ac(Mt(r,i),Mt(t,`${e}${i}`));qe(r,{recursive:!0})}function kc(t,e,n){try{return Ne(Mt(t,"originals")).find((r)=>r.startsWith(`${e}-${n}.`))}catch{return}}function Ec(t,e,n){let r=kc(t,e,n);if(r){let i=new Date;ql(Mt(t,"originals",r),i,i)}}function Mc(t,e,n){let r=ke(t),i=wc(r,e),o=vn(r,e);if(!o||i.length<2)throw Error(`${e} has no other image`);let s=(i.indexOf(o)+n+i.length)%i.length,c=i[s];return bc(r,e),$c(r,e,c),Ec(r,e,c),{key:c,at:s+1,of:i.length}}function yc(t,e){let n=ke(t),r=Ne(n).filter((h)=>$i(h,e));if(r.length===0)throw Error(`${e} has no image`);let i=wc(n,e),o=vn(n,e),s=o&&kc(n,e,o);if(s)qe(Mt(n,"originals",s));for(let h of r)qe(Mt(n,h));let c=i.filter((h)=>h!==o),u=c[(o?i.indexOf(o):0)%c.length];if(u)$c(n,e,u),Ec(n,e,u);return{key:o,left:c.length}}function rg(t,e,n){if(vn(t,e)!==n)bc(t,e);if(n)qe(Mt(gr(t,e),n),{recursive:!0,force:!0});tg(t,e)}function vc(t,e,n,r,i,o){let s=ke(t),c=e.name,u=eg(i);hc(Mt(s,"originals"),{recursive:!0}),rg(s,c,u);let h=lc(r),{width:f,height:a}=Yl(o.width,o.height),l=gc(h,f,a,yn(r,h)),d=Qe(bi(Bl(r,h),e.background,n.color)),p=Qe(bi(dc(r,l,f,a),e.background,n.color)),g=Mt(s,`${c}.${Wl("sha1").update(d).update(p).digest("hex").slice(0,8)}`),k=`${g}.png`,y=`${g}@fill-${Math.round(l.focus*100)}.png`,I=Mt(s,`${c}.conf`),E=Mt(s,"originals",`${c}-${i.site}_${i.id}.${i.ext}`);return ar(k,d),ar(y,p),ar(I,Dl(c,y,n.opacity,i.from,u)),ar(E,i.bytes),[k,y,I,E]}function Sc(t){let e=Mt(ke(t),"originals"),n=new Map,r;try{r=Ne(e)}catch{return new Map}for(let i of r){let o=/^(.+)-([a-z.]+)_(\d+)\.[a-z]+$/.exec(i),[,s,c,u]=o??[];if(!s||!c||!u)continue;let h=Ql(Mt(e,i)).mtimeMs,f=n.get(s);if(!f||h>f.at)n.set(s,{site:c,id:Number(u),at:h})}return new Map([...n].map(([i,{site:o,id:s}])=>[i,{site:o,id:s}]))}function ki(t){let{slot:e,color:n,opacity:r}=lr({name:t.name,background:t.background,foreground:t.foreground,cursor:t.cursor,selection:t.selectionBackground,ansi:t.ansi,waived:t.waive},t.signatureSlots);return{name:t.name,group:t.group,...t.native?{native:t.native}:{},...t.lead?{lead:!0}:{},order:t.order,ansiSource:t.ansiSource,...t.booru?{booru:t.booru}:{},...t.booruSites?{booruSites:t.booruSites}:{},...t.role==="default"?{default:!0}:{},background:t.background,foreground:t.foreground,cursor:t.cursor,selection:t.selectionBackground,signature:t.signature,signatureSlots:t.signatureSlots,ansi:t.ansi,gate:Vo(t),...t.waive.length>0?{waived:t.waive}:{},backdrop:{slot:e,color:n,opacity:r}}}function He(t){return t.filter((e)=>e.default!==!0)}function ig(t){let[e]=t;if(!e)throw Error("manifest needs at least one theme");return{version:ne.version,gate:cr,placement:ae,font:e.font,...e.ghostty.shader?{shader:e.ghostty.shader}:{},palettes:t.map(ki)}}var Ei={id:"meta",emitShared(t){return[{path:"manifest.json",content:`${JSON.stringify(ig(t),null,2)}
|
|
16
|
+
`}]}};import{readdirSync as Kg,readFileSync as Ii}from"node:fs";import{basename as Jg,join as Ni}from"node:path";import{readdirSync as og,rmSync as sg,statSync as cg}from"node:fs";import{setDefaultAutoSelectFamilyAttemptTimeout as ug}from"node:net";import{homedir as hg}from"node:os";import{join as Fn}from"node:path";import{setTimeout as fg}from"node:timers/promises";var Oe=100,Re=25000000,ag=536870912,In=["safe","questionable","explicit"],je=["nudity","underwear"],lg={nudity:new Set(["nude","naked","topless","bottomless","nipples","naked_towel","undressing"]),underwear:new Set(["underwear","panties","pantsu","bra","lingerie","pantyshot"])},Sn={safe:"s",questionable:"q",explicit:"e"},gg=8191,dg=20000,mg=5000,Fc=3000,Ic=8,pg=3000,jc=60000,Nc=3,yi=`ttheme/${ne.version} (+${ne.homepage})`,wg=["orig","tile","thumb","cut"],Rc=new Map,bg=Ng(process.env.TTHEME_FIND_HOSTS),$g=Ig(process.env.TTHEME_FIND_CUTOUTS);ug(pg);function Hc(t){try{return og(t)}catch{return[]}}function dr(t){return t.startsWith("//")?`https:${t}`:t}function Nn(t){return(/\.([a-z0-9]+)(?:\?.*)?$/i.exec(t)?.[1]??"").toLowerCase()}function Hn(t){let e=t.trim();if(!e)return[];let n=JSON.parse(e);if(Array.isArray(n))return n;let r=n.posts;return Array.isArray(r)?r:[]}function kg(t){let e=t.trim(),r=(e?JSON.parse(e):{}).tags??{};return new Map(Object.entries(r).map(([i,o])=>[i,String(o)]))}function Mi(t,e,n){let r=dr(String(t??""));return{file:r,width:Number(e)||0,height:Number(n)||0,ext:Nn(r)}}function Gc(t,e){let n=dr(String(e.preview??""));if(!e.file||!n||!Number(t.id))return[];let r=Number(t.width??t.image_width)||0,i=Number(t.height??t.image_height)||0;return[{id:Number(t.id),width:r,height:i,file:e.file,preview:n,ext:e.ext,owner:String(e.owner??""),artist:e.artist,score:Number(t.score)||0,rating:String(t.rating??""),md5:String(e.md5??""),source:String(t.source??""),tags:e.tags.split(/\s+/).filter(Boolean),solo:e.solo,family:Number(t.parent_id)||(t.has_children===!0?Number(t.id):0),smaller:e.versions.filter((o)=>o.file&&o.width>0&&o.height>0&&o.width*o.height<r*i)}]}function Eg(t){let e=kg(t);return Hn(t).flatMap((n)=>{let r=dr(String(n.file_url??"")),i=String(n.tags??"");return Gc(n,{preview:n.preview_url,file:r,ext:String(n.file_ext||Nn(r)).toLowerCase(),owner:n.author,artist:i.split(/\s+/).find((o)=>e.get(o)==="artist")??"",md5:n.md5,tags:i,solo:void 0,versions:[Mi(n.jpeg_url,n.jpeg_width,n.jpeg_height),Mi(n.sample_url,n.sample_width,n.sample_height)]})})}function Mg(t){return Hn(t).flatMap((e)=>{let n=dr(String(e.file_url??"")),r=String(e.tag_string??""),i=e.media_asset??{};return Gc(e,{preview:i.variants?.find((o)=>o.type==="360x360")?.url??e.preview_file_url,file:n,ext:String(e.file_ext||Nn(n)).toLowerCase(),owner:"",artist:String(e.tag_string_artist??"").split(/\s+/)[0]??"",md5:e.md5,tags:r,solo:r.split(/\s+/).includes("solo"),versions:(i.variants??[]).map((o)=>Mi(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 yg(t){return Hn(t).flatMap((e)=>{let n=String(e.value??"");return n?[{value:n,count:Number(e.post_count)||0}]:[]})}function vg(t){return Hn(t).flatMap((e)=>{let n=String(e.name??"");return n?[{value:n,count:Number(e.count)||0}]:[]})}function Sg(t){return Number(/count="(\d+)"/.exec(t)?.[1]??0)}function Fg(t){let e=t.trim()?JSON.parse(t):{};return Number(e.counts?.posts)||0}function Ig(t){let e=new Map;for(let n of(t??"").split(/\s+/).filter(Boolean)){let r=n.indexOf("=");if(r>0)e.set(n.slice(0,r),n.slice(r+1).split(",").filter(Boolean))}return e}function Ng(t){let e=new Map;for(let n of(t??"").split(/[\s,]+/).filter(Boolean)){let r=n.indexOf("="),i=n.slice(0,r);try{let o=new URL(n.slice(r+1));if(i&&o.protocol==="https:")e.set(i,o.origin)}catch{}}return e}function Lc(t,e,n,r){let i=(t??"").split(/\s+/);if(r!==void 0&&i.includes(r))return[];let o=e.filter((s)=>i.includes(s));return o.length>0?o:[...n]}function mr(t){return Lc(t,In,["safe"])}function pr(t){return Lc(t,je,je,"none")}function Pc(t,e,n){return{safe:new Set(t),questionable:new Set(e),explicit:new Set(n)}}function Kc(t){let e=bg.get(t.key),n=$g.get(t.key);return{...t,origin:e??t.origin,moved:e!==void 0&&e!==t.origin,cutouts:n??t.cutouts,vouched:t.vouched&&n===void 0}}function Jc(t){return t.length<2?t.join(""):t.map((e)=>`~${e}`).join(" ")}function Oc(t){let e=Kc(t),n=(r)=>new URLSearchParams({api_version:"2",include_tags:"1",...r});return{...e,cutouts:Jc(e.cutouts),ratings:Pc([Sn.safe],[Sn.questionable],[Sn.explicit]),rate:(r)=>{let[i]=r;if(r.length===1&&i)return`rating:${Sn[i]}`;let o=In.filter((c)=>!r.includes(c)),[s]=o;return o.length===1&&s?`-rating:${Sn[s]}`:""},best:"order:score",tagBudget:Number.POSITIVE_INFINITY,postsUrl:(r,i)=>`${e.origin}/post.json?${n({limit:String(Oe),page:String(i+1),tags:r})}`,countUrl:(r)=>`${e.origin}/post.xml?${new URLSearchParams({limit:"1",tags:r})}`,postUrl:(r)=>`${e.origin}/post.json?${n({tags:`id:${r}`})}`,pageUrl:(r)=>`${e.origin}/post/show/${r}`,parse:Eg,count:Sg}}function Hg(t){let e=Kc(t),n=Pc(["g"],["s","q"],["e"]);return{...e,cutouts:Jc(e.cutouts),ratings:n,rate:(r)=>r.length===In.length?"":`rating:${r.flatMap((i)=>[...n[i]]).join(",")}`,best:"order:score",tagBudget:2,postsUrl:(r,i)=>`${e.origin}/posts.json?${new URLSearchParams({limit:String(Oe),page:String(i+1),tags:r})}`,countUrl:(r)=>`${e.origin}/counts/posts.json?${new URLSearchParams({tags:r})}`,postUrl:(r)=>`${e.origin}/posts.json?${new URLSearchParams({limit:"1",tags:`id:${r}`})}`,pageUrl:(r)=>`${e.origin}/posts/${r}`,parse:Mg,count:Fg}}function Og(t){return lt.find((e)=>e.key===t||e.name===t||new URL(e.origin).host===t)}function vi(t){return t.split(/\s+/).filter((e)=>e&&!e.startsWith("rating:")).length}function wr(t,e){let n=t.trim();if(/^\d+$/.test(n))return{site:e,id:Number(n)};let r=/^([\w.]+):(\d+)$/.exec(n);if(r){let c=lt.find((u)=>u.key===r[1]||u.name===r[1]);return c&&{site:c,id:Number(r[2])}}let i;try{i=new URL(n)}catch{return}let o=Og(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 lt=[Hg({key:"danbooru",name:"danbooru",origin:"https://danbooru.donmai.us",cutouts:["transparent_background"],vouched:!1,tunneled:!0,ansi:2}),Oc({key:"konachan",name:"konachan",origin:"https://konachan.net",cutouts:["transparent","vector"],vouched:!1,tunneled:!1,ansi:6}),Oc({key:"yande",name:"yande.re",origin:"https://yande.re",cutouts:["transparent_png"],vouched:!0,tunneled:!1,ansi:5})],le=134217728;function ie(t,e){let n=lt.indexOf(t);return(n===-1?lt.length:n)*le+e}function Si(t){let e;try{e=new URL(t).hostname}catch{return""}return e.split(".").slice(-2).join(".")}function Ac(){return lt.filter((t)=>!t.tunneled).map((t)=>Si(t.origin)).flatMap((t)=>[t,`.${t}`]).join(",")}function Tc(t,e=je){return t.tags.filter((n)=>e.some((r)=>lg[r].has(n)))}function Uc(t,e,n=["safe"]){return n.some((r)=>t.ratings[r].has(e.rating))}function On(t){return[t,...t.smaller].find((e)=>e.width*e.height<=Re)}function Wc(t){let e=new Map;for(let[n,r]of[...t].sort(([i],[o])=>i<o?-1:1)){if(r==="")continue;e.set(r,[...e.get(r)??[],n])}return e}function Qc(){return Fn(process.env.XDG_CACHE_HOME??Fn(hg(),".cache"),"ttheme")}function ye(t){return Fn(Qc(),t.key)}function qc(t=ag,e=Qc()){let n=[],r=0;for(let i of Hc(e))for(let o of wg){let s=Fn(e,i,o);for(let c of Hc(s)){let u=Fn(s,c);try{let{size:h,mtimeMs:f}=cg(u);n.push({path:u,size:h,at:f}),r+=h}catch{}}}n.sort((i,o)=>i.at-o.at);for(let i of n){if(r<=t)return;try{sg(i.path,{force:!0}),r-=i.size}catch{}}}function jg(t,e){if(t!==null&&/^\s*\d+\s*$/.test(t))return Number(t)*1000;let n=t===null?Number.NaN:Date.parse(t);return Number.isNaN(n)?jc:Math.max(0,n-e)}function Ee(t){return Rc.get(t.key)??0}function Rg(t){for(let e=t;e instanceof Error;e=e.cause)if(e.code==="ECONNRESET")return!0;return!1}function Gg(t){return(t.headers.get("server")??"").startsWith("cloudflare")&&t.headers.get("cf-mitigated")==="challenge"}async function Me(t,e,n,r={},i=dg){for(let o=1;;o++){let s=Ee(t)-Date.now();if(s>0)await fg(s,void 0,{signal:n});let c;try{c=await fetch(e,{headers:{"User-Agent":yi,Referer:`${t.origin}/`,...r},signal:i?AbortSignal.any([n,AbortSignal.timeout(i)]):n})}catch(u){if(o<Nc&&!n.aborted&&Rg(u))continue;throw u}if(c.status===429&&o<Nc){await c.body?.cancel();let u=jg(c.headers.get("retry-after"),Date.now());if(u>jc)throw Error(`${t.name} asks to wait ${Math.ceil(u/1000)}s`);Rc.set(t.key,Math.max(Ee(t),Date.now()+u));continue}if(!c.ok)throw await c.body?.cancel(),Error(Gg(c)?`${t.name} is behind a Cloudflare challenge`:`${t.name} answered ${c.status}`);return c}}async function Zc(t,e,n,r){return t.parse(await(await Me(t,t.postsUrl(e,n),r)).text())}async function _c(t,e,n){return t.count(await(await Me(t,t.countUrl(e),n)).text())}async function Fi(t,e,n){let[r]=t.parse(await(await Me(t,t.postUrl(e),n)).text());return r}function Lg(t){let e=lt.find((r)=>r.key==="danbooru"),n=new URLSearchParams({limit:String(2*Oe),only:"md5,tag_string",tags:`md5:${t.join(",")}`});return`${e.origin}/posts.json?${n}`}function Pg(t){return new Map(Hn(t).flatMap((e)=>{let n=String(e.md5??"");return n?[[n,String(e.tag_string??"").split(/\s+/).filter(Boolean)]]:[]}))}function Xc(t,e){for(let n of t){let r=e.get(n.md5);if(r)n.tags=[...new Set([...n.tags,...r])],n.solo=r.includes("solo")}}async function Cc(t,e){let n=lt.find((i)=>i.key==="danbooru"),r=new Map;if(Ee(n)>Date.now())return r;for(let i=0;i<t.length;i+=Oe){let o=await(await Me(n,Lg(t.slice(i,i+Oe)),e,{},mg)).text();for(let[s,c]of Pg(o))r.set(s,c)}return r}async function Vc(t,e){let n=lt.find((o)=>o.key==="danbooru");if(Ee(n)<=Date.now())try{let o=new URLSearchParams({"search[query]":t,"search[type]":"tag_query",limit:String(Ic)}),s=`${n.origin}/autocomplete.json?${o}`;return yg(await(await Me(n,s,e,{},Fc)).text())}catch(o){if(e.aborted)throw o}let r=lt.find((o)=>o.key==="yande"),i=new URLSearchParams({name:t,order:"count",limit:String(Ic)});return vg(await(await Me(r,`${r.origin}/tag.json?${i}`,e,{},Fc)).text())}async function xc(t,e,n){let r=await Me(t,e,n,{Range:`bytes=0-${gg}`});return Mn(new Uint8Array(await r.arrayBuffer()))}async function zc(t,e,n,r){let i=await Me(t,e,n,{},0),o=Number(i.headers.get("content-length"))||0,s=i.body?.getReader();if(!s)return new Uint8Array(await i.arrayBuffer());let c=[],u=0;for(;;){let{done:a,value:l}=await s.read();if(a)break;c.push(l),u+=l.length,r?.(u,o)}let h=new Uint8Array(u),f=0;for(let a of c)h.set(a,f),f+=a.length;return h}var Ag="_defaults.toml",ge="_groups.toml",Yc=3,Bc=["background","foreground","cursor","selection"];function St(t,e){throw Error(`${t}: ${e}`)}function Ge(t,e,n){if(typeof n!=="string"||!Qo(n))St(t,`${e} must be "#rrggbb" (lowercase), got ${JSON.stringify(n)}`);return n}function Xt(t,e,n){if(typeof n!=="string"||n.length===0)St(t,`${e} must be a non-empty string`);return n}function de(t){return t&&typeof t==="object"?t:{}}function Tg(t,e,n){let r={...de(n),...de(e)},i=r.codepoint_map??[];if(!Array.isArray(i))St(t,"font.codepoint_map must be an array");return{family:Xt(t,"font.family",r.family),size:Number(r.size),codepointMap:i.map((o)=>{let s=de(o);return{range:Xt(t,"font.codepoint_map[].range",s.range),family:Xt(t,"font.codepoint_map[].family",s.family)}})}}function Ug(t,e,n){if(e===void 0)return[n.cursor,n.selectionBackground,n.background];let r=Array.isArray(e)?e:[e];if(r.length===0)St(t,"ghostty.icon_screen must not be empty");return r.map((i,o)=>Ge(t,`ghostty.icon_screen[${o}]`,i))}function Wg(t,e,n,r){let i={...de(n),...de(e)};return{shader:i.shader===void 0?void 0:Xt(t,"ghostty.shader",i.shader),iconGhost:i.icon_ghost===void 0?r.cursor:Ge(t,"ghostty.icon_ghost",i.icon_ghost),iconScreen:Ug(t,i.icon_screen,r)}}function Qg(t){return new Map([...Bc.map((e)=>[e,t[e]]),...t.ansi.map((e,n)=>[`ansi${n}`,e])])}function qg(t,e,n){if(!Array.isArray(e)||e.length!==Yc)St(t,`meta.signature must name exactly ${Yc} palette slots`);let r=Qg(n),i=[],o=[];for(let[s,c]of e.entries()){let u=`meta.signature[${s}]`,h=Xt(t,u,c),f=r.get(h);if(f===void 0)St(t,`${u} ${JSON.stringify(c)} is not a palette slot — use ${Bc.join(", ")} or ansi0-ansi15`);i.push(h),o.push(f)}if(new Set(o).size!==o.length)St(t,"meta.signature slots must resolve to three different colors");return{names:i,colors:o}}function Zg(t,e,n){if(e===void 0)return;if(!n)St(t,"meta.booru_sites renames meta.booru per site, so it needs meta.booru");if(!e||typeof e!=="object"||Array.isArray(e))St(t,'meta.booru_sites must be a table of site = "tag" or site = ["tag", ...]');let r={};for(let[i,o]of Object.entries(e)){let s=lt.find((u)=>u.key===i);if(!s)St(t,`meta.booru_sites.${i} is not a find site — use ${lt.map((u)=>u.key).join(", ")}`);let c=typeof o==="string"?[o]:Array.isArray(o)?o:void 0;if(!c||c.some((u)=>typeof u!=="string"||u===""||/\s/.test(u)))St(t,`meta.booru_sites.${i} must be one tag or a list of tags, got ${JSON.stringify(o)}`);if(c.length>1&&Number.isFinite(s.tagBudget))St(t,`meta.booru_sites.${i} takes one tag — ${s.name} searches ${s.tagBudget} tags at a time`);r[i]=c}return r}function _g(t){let n=Bun.TOML.parse(Ii(Ni(t,ge),"utf8")).group;if(!Array.isArray(n)||n.length===0)St(ge,"needs at least one [[group]] table");return n.map((r)=>{let i=de(r);return{name:Xt(ge,"group.name",i.name),native:i.native===void 0?void 0:Xt(ge,"group.native",i.native),lead:Xt(ge,"group.lead",i.lead)}})}function Xg(t,e,n,r){let i=Bun.TOML.parse(e),o=de(i.meta),s=de(i.colors),c=de(i.contrast),u=s.ansi;if(!Array.isArray(u)||u.length!==16)St(t,`colors.ansi must hold exactly 16 colors, got ${Array.isArray(u)?u.length:typeof u}`);let h=Xt(t,"meta.name",o.name);if(h!==Jg(t,".toml"))St(t,`meta.name "${h}" does not match the filename`);if(h.startsWith("-"))St(t,`meta.name "${h}" would be read as a flag by the ttheme CLI`);let f=o.role;if(f!==void 0&&f!=="default")St(t,`meta.role must be "default", got ${JSON.stringify(f)}`);let a=Xt(t,"meta.group",o.group),l=r.get(a);if(!l)St(t,`meta.group "${a}" has no [[group]] table in ${ge}`);let d=Ge(t,"colors.background",s.background),p=Ge(t,"colors.foreground",s.foreground),g=Ge(t,"colors.cursor",s.cursor),k=Ge(t,"colors.selection_background",s.selection_background),y=u.map((O,$)=>Ge(t,`colors.ansi[${$}]`,O)),I=qg(t,o.signature,{background:d,foreground:p,cursor:g,selection:k,ansi:y}),E=o.booru===void 0?void 0:Xt(t,"meta.booru",o.booru);if(E!==void 0&&/\s/.test(E))St(t,`meta.booru must be a single booru tag, got ${JSON.stringify(E)}`);let v=Zg(t,o.booru_sites,E),b=Array.isArray(c.waive)?c.waive.map(String):[];if(b.length>0&&typeof c.reason!=="string")St(t,"contrast.waive needs a contrast.reason explaining why");return{name:h,group:a,native:l.native,lead:l.lead===h,order:Number(o.order),role:f,ansiSource:Xt(t,"meta.ansi_source",o.ansi_source),...E?{booru:E}:{},...v?{booruSites:v}:{},background:d,foreground:p,cursor:g,selectionBackground:k,ansi:y,signature:I.colors,signatureSlots:I.names,font:Tg(t,i.font,n.font),ghostty:Wg(t,i.ghostty,n.ghostty,{background:d,cursor:g,selectionBackground:k}),waive:b,waiveReason:typeof c.reason==="string"?c.reason:void 0}}function Dc(t){let e=Bun.TOML.parse(Ii(Ni(t,Ag),"utf8")),n=_g(t),r=new Map(n.map((s)=>[s.name,s]));if(r.size!==n.length)St(ge,"group.name must be unique");let i=Kg(t).filter((s)=>s.endsWith(".toml")&&!s.startsWith("_")).map((s)=>Xg(s,Ii(Ni(t,s),"utf8"),e,r)).sort((s,c)=>s.order-c.order);if(new Set(i.map((s)=>s.order)).size!==i.length)throw Error("themes: meta.order must be unique across all themes");for(let s of n){let c=i.filter((u)=>u.group===s.name);if(c.length===0)St(ge,`group "${s.name}" has no themes`);if(!c.some((u)=>u.name===s.lead))St(ge,`group "${s.name}" lead "${s.lead}" is not one of its themes`)}return i}function tu(t){return t.filter((e)=>e.role===void 0)}function jn(t){let e=(n,r)=>n<r?-1:n>r?1:0;return[...t].sort((n,r)=>e(n.group.toLowerCase(),r.group.toLowerCase())||e(n.name,r.name))}var Cg=["ghostty","kitty","alacritty","wezterm","iterm2","windows-terminal","warp"],br=[{name:"use",args:["<palette>"],about:"paint this tab — a unique prefix works: ttheme use ho",section:"tab",shell:!0},{name:"preview",args:[],about:"browse live — focus repaints, enter keeps (this tab or default), esc restores, ? lists keys",section:"tab",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:"tab"},{name:"on",args:[],about:"wear the default palette in new tabs again",section:"tab"},{name:"off",args:[],about:"take the palette and picture off every tab — the terminal's own colors until `ttheme on`",section:"tab"},{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:"tab",shell:!0},{name:"browse",args:[],about:"pick palettes from the catalog in a live picker",section:"catalog"},{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",section:"catalog"},{name:"remove",args:["<palette...>"],about:"uninstall palettes",section:"catalog"},{name:"update",args:[],about:"refresh the catalog from the registry",section:"catalog"},{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:"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:Cg,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}];var $r=["ghostty","kitty","alacritty","wezterm","iterm2","windows-terminal","warp"];var Hi=/# ttheme begin\n[\s\S]*?# ttheme end\n?/;function Rn(t,e){let n=`# ttheme begin
|
|
17
|
+
${e}
|
|
18
18
|
# ttheme end
|
|
19
|
-
`;if(
|
|
19
|
+
`;if(Hi.test(t))return t.replace(Hi,n);if(t==="")return n;return`${t.replace(/\n*$/,`
|
|
20
20
|
`)}
|
|
21
|
-
${
|
|
22
|
-
`)}function
|
|
21
|
+
${n}`}function kr(t){if(t.TERM_PROGRAM==="WarpTerminal")return"warp";if(t.GHOSTTY_RESOURCES_DIR||t.TERM_PROGRAM==="ghostty")return"ghostty";if(t.KITTY_WINDOW_ID)return"kitty";if(t.WEZTERM_PANE)return"wezterm";if(t.ALACRITTY_WINDOW_ID)return"alacritty";if(t.ITERM_SESSION_ID||t.TERM_PROGRAM==="iTerm.app")return"iterm2";if(t.TERM_PROGRAM==="Apple_Terminal")return"terminal-app";if(t.WT_SESSION&&!t.TERM_PROGRAM)return"windows-terminal";if(t.TERM?.startsWith("foot"))return"foot";return"unknown"}function iu(t,e){let n=[`command = ${t}/launch-tab.zsh`,"shell-integration = zsh"];if(e)n.push(`theme = ${e}`);return n.push(`config-file = ${t}/ttheme.conf`,`config-file = ?${t}/backgrounds/shown.conf`),n.join(`
|
|
22
|
+
`)}function ou(t){return`source ${t}/ttheme.zsh`}var Vg="# ttheme settings — uncomment a line to change it; exported variables win over this file",Gn={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 Oi(t,e){let n=`: \${${t}:=${e}}`;return Gn[t]?.default===e?`# ${n}`:n}function su(t){return new RegExp(String.raw`^#? ?: \$\{${t}[^\n]*$`,"m")}function xg(t,e){if(su(e).test(t))return t;let n=Gn[e];return`${t.replace(/\n*$/,`
|
|
23
23
|
`)}
|
|
24
|
-
${
|
|
25
|
-
${
|
|
26
|
-
`}function
|
|
27
|
-
${
|
|
24
|
+
${n.doc}
|
|
25
|
+
${Oi(e,n.default)}
|
|
26
|
+
`}var cu=Object.keys(Gn);function ji(){let t=Object.entries(Gn).map(([e,n])=>`${n.doc}
|
|
27
|
+
${Oi(e,n.default)}`);return`${[Vg,...t].join(`
|
|
28
28
|
|
|
29
29
|
`)}
|
|
30
|
-
`}function
|
|
30
|
+
`}function uu(t,e,n){let r=Oi(e,n),i=su(e);if(i.test(t))return t.replace(i,r);return`${t.replace(/\n*$/,`
|
|
31
31
|
`)}
|
|
32
32
|
${r}
|
|
33
|
-
`}function
|
|
34
|
-
`)}var
|
|
35
|
-
import = ["${t}"]`:""}function
|
|
36
|
-
`:"";return`${
|
|
33
|
+
`}function hu(t){if(t==="")return ji();return Object.keys(Gn).reduce(xg,t)}function fu(t,e){return[...t?[`include themes/${t}.conf`]:[],`watcher ${e}`,"window_logo_scale 100","window_logo_alpha 1"].join(`
|
|
34
|
+
`)}var zg=/^[ \t]*\[general\][ \t]*(?:#.*)?$/m,eu=/^[ \t]*\[/m,nu=/^[ \t]*import[ \t]*=/m,Yg=/^[ \t]*general[ \t]*[.=]/m;function Bg(t){return t?`[general]
|
|
35
|
+
import = ["${t}"]`:""}function Er(t,e){let n=t.replace(Hi,""),r=zg.exec(n);if(!r){let u=n.search(eu),h=u<0?n:n.slice(0,u);if(Yg.test(n)||nu.test(h))return;return Rn(t,Bg(e))}let i=r.index+r[0].length,o=n.slice(i),s=o.search(eu);if(nu.test(s<0?o:o.slice(0,s)))return;let c=e?`import = ["${e}"]
|
|
36
|
+
`:"";return`${n.slice(0,i)}
|
|
37
37
|
# ttheme begin
|
|
38
|
-
${c}# ttheme end${o}`}var
|
|
39
|
-
${
|
|
38
|
+
${c}# ttheme end${o}`}var ru=/-- ttheme begin\n[\s\S]*?-- ttheme end\n?/,Dg=/^return config[ \t]*$/gm;function au(t){return`dofile(${JSON.stringify(t)})(config)`}function Mr(t,e){let n=`-- ttheme begin
|
|
39
|
+
${e}
|
|
40
40
|
-- ttheme end
|
|
41
|
-
`;if(
|
|
41
|
+
`;if(ru.test(t))return t.replace(ru,n);if(t==="")return`local wezterm = require 'wezterm'
|
|
42
42
|
local config = wezterm.config_builder()
|
|
43
43
|
|
|
44
|
-
${
|
|
44
|
+
${n}
|
|
45
45
|
return config
|
|
46
|
-
`;let r=[...t.matchAll(
|
|
47
|
-
${t.slice(r.index)}`}var
|
|
48
|
-
`),
|
|
49
|
-
`),r=
|
|
46
|
+
`;let r=[...t.matchAll(Dg)].at(-1);if(r?.index===void 0)return;return`${t.slice(0,r.index)}${n}
|
|
47
|
+
${t.slice(r.index)}`}var lu="[appearance.themes]";function gu(t){let e=t.findIndex((r)=>r.trim()===lu);if(e<0)return;let n=t.findIndex((r,i)=>i>e&&r.trimStart().startsWith("["));return[e,n<0?t.length:n]}function du(t){let e=t.split(`
|
|
48
|
+
`),n=gu(e);if(!n)return;return e.slice(n[0]+1,n[1]).find((i)=>/^theme\s*=/.test(i))?.replace(/^theme\s*=\s*/,"").trim()}function mu(t){return`{ custom = { name = "${t}", path = "ttheme-${t}.yaml" } }`}function pu(t,e){let n=t.split(`
|
|
49
|
+
`),r=gu(n);if(!r)return e===void 0?t:`${t.replace(/\n*$/,`
|
|
50
50
|
`)}
|
|
51
|
-
${
|
|
52
|
-
theme = ${
|
|
53
|
-
`;let i=
|
|
54
|
-
`)}function
|
|
55
|
-
`)}var
|
|
56
|
-
`);return[{path:`warp/themes/ttheme-${t.name}.yaml`,content:
|
|
57
|
-
`),
|
|
58
|
-
`);return[{path:`wezterm/colors/${t.name}.toml`,content:
|
|
59
|
-
`)}var
|
|
60
|
-
`}var
|
|
61
|
-
`}]},emitShared(t){return[{path:"windows-terminal/ttheme.json",content:
|
|
62
|
-
${
|
|
51
|
+
${lu}
|
|
52
|
+
theme = ${e}
|
|
53
|
+
`;let i=n.findIndex((o,s)=>s>r[0]&&s<r[1]&&/^theme\s*=/.test(o));if(i>=0)n.splice(i,1,...e===void 0?[]:[`theme = ${e}`]);else if(e!==void 0)n.splice(r[0]+1,0,`theme = ${e}`);return n.join(`
|
|
54
|
+
`)}function Ri(t,e,n=[]){for(let f of t)for(let a of[f.name,f.group,f.native??"",f.ansiSource])if(/["$`\\]/.test(a))throw Error(`${f.name}: "${a}" contains a character that breaks zsh quoting`);let r=Math.max(0,...t.map((f)=>f.name.length)),i=(f,a)=>` ${f.name.padEnd(r)} "${a}"`,o=(f)=>f.map((a)=>a.name).join(" "),s=He(t),c=(f)=>`'${f.replaceAll("'","'\\''")}'`,u=br.filter((f)=>f.section!=="setup"&&!f.hidden),h=u.flatMap((f,a)=>a>0&&u[a-1]?.section!==f.section?["-",f.name]:[f.name]);return["# Generated by `mise run build` — do not edit.","# Source of truth: themes/*.toml in the ttheme repo.","",`typeset -g TTHEME_VERSION=${ne.version}`,"",'# the palette new tabs open with, which the iTerm2 "ttheme · default" profile wears',`typeset -g TTHEME_STARTUP=${e??""}`,"","# the terminals ttheme is wired into: a picture change reaches every one of them, from whichever runs the shell",`typeset -ga TTHEME_TERMINALS=(${n.join(" ")})`,"","# the commands the shell layer knows (src/verbs.ts): help, completion and argument checks read them",`typeset -ga TTHEME_VERBS=(${h.join(" ")})`,`typeset -ga TTHEME_SHELL_VERBS=(${u.filter((f)=>f.shell).map((f)=>f.name).join(" ")})`,"typeset -gA TTHEME_VERB_ARGS=(",...u.map((f)=>` ${f.name} ${c(f.args.join(" "))}`),")","typeset -gA TTHEME_VERB_ABOUT=(",...u.map((f)=>` ${f.name} ${c(f.about)}`),")","","# the settings config.zsh holds, handed to the CLI on every call",`typeset -ga TTHEME_SETTINGS=(${cu.join(" ")})`,"","# seed for `ttheme config` when no config.zsh exists yet",`typeset -g TTHEME_CONFIG_TEMPLATE='${ji().trimEnd().replaceAll("'","'\\''")}'`,"","typeset -gA TTHEME_PALETTE=(",...t.map((f)=>i(f,[f.background,f.foreground,f.cursor,f.selection,...f.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(jn(s))})`,"","typeset -gA TTHEME_GROUP=(",...t.map((f)=>i(f,f.group)),")","","# original-language title, rendered dim next to the group","typeset -gA TTHEME_NATIVE=(",...t.filter((f)=>f.native).map((f)=>i(f,f.native??"")),")","","# where each palette's 16 ANSI colors came from","typeset -gA TTHEME_SRC=(",...t.map((f)=>i(f,f.ansiSource)),")",""].join(`
|
|
55
|
+
`)}var Gi={id:"shell",emitShared(t){return[{path:"shell/palettes.zsh",content:Ri(t.map(ki))}]}};var td=["black","red","green","yellow","blue","magenta","cyan","white"];function wu(t,e){return[` ${t}:`,...td.map((n,r)=>` ${n}: "${e[r]}"`)]}var Ln={id:"warp",limits:"colors only — no selection color, and Warp paints one theme app-wide",emit(t){let e=[`name: "${t.name}"`,`background: "${t.background}"`,`foreground: "${t.foreground}"`,`accent: "${t.cursor}"`,`cursor: "${t.cursor}"`,`details: ${Bt(t.background)<0.18?"darker":"lighter"}`,"terminal_colors:",...wu("normal",t.ansi.slice(0,8)),...wu("bright",t.ansi.slice(8,16)),""].join(`
|
|
56
|
+
`);return[{path:`warp/themes/ttheme-${t.name}.yaml`,content:e}]}};var bu=(t)=>`[${t.map((e)=>`"${e}"`).join(", ")}]`,Pn={id:"wezterm",limits:"no shaders; OSC repaints per pane, pictures show per window",emit(t){let e=["[metadata]",`name = "${t.name}"`,`origin_url = "${t.ansiSource}"`,"","[colors]",`foreground = "${t.foreground}"`,`background = "${t.background}"`,`cursor_bg = "${t.cursor}"`,`cursor_border = "${t.cursor}"`,`cursor_fg = "${t.background}"`,`selection_bg = "${t.selectionBackground}"`,`selection_fg = "${t.foreground}"`,"",`ansi = ${bu(t.ansi.slice(0,8))}`,`brights = ${bu(t.ansi.slice(8,16))}`,""].join(`
|
|
57
|
+
`),n=[`-- ${t.name} — font settings.`,"-- Merge into your wezterm.lua config table:",`-- local t = require("ttheme.${t.name}")`,`-- config.color_scheme = "${t.name}"`,"-- config.font = t.font","-- config.font_size = t.font_size","return {",` font = require("wezterm").font("${t.font.family}"),`,` font_size = ${t.font.size},`,"}",""].join(`
|
|
58
|
+
`);return[{path:`wezterm/colors/${t.name}.toml`,content:e},{path:`wezterm/config/${t.name}.lua`,content:n}]}},Ze=(t)=>JSON.stringify(t);function $u(t){return["-- Generated by ttheme — rewritten on every add, remove and default; do not edit.","local wezterm = require 'wezterm'","",`local MODULE = ${Ze(t.path)}`,`local COLORS = ${Ze(t.colors)}`,`local BACKGROUNDS = ${Ze(t.backgrounds)}`,`local STARTUP = ${t.startup?Ze(t.startup):"nil"}`,"local PALETTES = {",...t.palettes.map((e)=>` [${Ze(e.name)}] = ${Ze(e.background)},`),"}","","local X = { left = 'Left', center = 'Center', right = 'Right' }","local Y = { top = 'Top', center = 'Middle', bottom = 'Bottom' }","local SIZE = { cover = 'Cover', contain = 'Contain', stretch = '100%' }","","local function locate(path)"," if path:sub(1, 2) == '~/' then"," return os.getenv('HOME') .. path:sub(2)"," elseif path:sub(1, 1) == '/' or path:match('^%a:[/\\\\]') then"," return path"," end"," return BACKGROUNDS .. '/' .. path","end","","local function read(path, into)"," local f = io.open(path, 'r')"," if not f then"," return false"," end"," for line in f:lines() do"," local key, value = line:match('^%s*([%w%-]+)%s*=%s*(.-)%s*$')"," if key == 'config-file' then"," read(locate((value:gsub('^%?', ''))), into)"," elseif key then"," into[key] = value"," end"," end"," f:close()"," return true","end","","local function layers(palette)"," local color = PALETTES[palette]"," local c = {}"," if not color or not read(BACKGROUNDS .. '/' .. palette .. '.conf', c) then"," return nil, 'none'"," end"," local image = c['background-image'] or ''"," local opacity = tonumber(c['background-image-opacity'] or '1') or 1"," if image == '' or opacity <= 0 then"," return nil, 'none'"," end"," local fit = c['background-image-fit'] or 'contain'"," local position = c['background-image-position'] or 'center'"," local y, x = position:match('^(%a+)-(%a+)$')"," local rep = c['background-image-repeat'] == 'true' and 'Repeat' or 'NoRepeat'"," return {"," { source = { Color = color }, width = '100%', height = '100%' },"," {"," source = { File = locate(image) },"," opacity = opacity,"," width = SIZE[fit],"," height = SIZE[fit],"," horizontal_align = X[x or 'center'],"," vertical_align = Y[y or 'center'],"," repeat_x = rep,"," repeat_y = rep,"," },"," }, table.concat({ color, image, opacity, fit, position, rep }, '|')","end","","local shown = {}","","local function show(window, pane)"," local want = pane:get_user_vars().ttheme_shown"," if not want or want == '' then"," return"," end"," local background, key = layers(want)"," local id = window:window_id()"," if shown[id] == key then"," return"," end"," shown[id] = key"," local overrides = window:get_config_overrides() or {}"," overrides.background = background"," window:set_config_overrides(overrides)","end","","wezterm.on('user-var-changed', function(window, pane, name)"," if name == 'ttheme_shown' then"," show(window, pane)"," end","end)","wezterm.on('update-status', show)","","return function(config)"," local dirs = config.color_scheme_dirs or {}"," table.insert(dirs, COLORS)"," config.color_scheme_dirs = dirs"," if STARTUP then"," config.color_scheme = STARTUP"," end"," wezterm.add_to_config_reload_watch_list(MODULE)","end",""].join(`
|
|
59
|
+
`)}var ku=["black","red","green","yellow","blue","purple","cyan","white"];function Eu(t){return{name:t.name,background:t.background,foreground:t.foreground,cursorColor:t.cursor,selectionBackground:t.selectionBackground,...Object.fromEntries(ku.map((e,n)=>[e,t.ansi[n]])),...Object.fromEntries(ku.map((e,n)=>[`bright${e[0]?.toUpperCase()}${e.slice(1)}`,t.ansi[n+8]]))}}function Li(t,e,n){let r={...e&&n?{profiles:[{updates:e,colorScheme:n}]}:{},schemes:t.map(Eu)};return`${JSON.stringify(r,null,2)}
|
|
60
|
+
`}var Kn={id:"windows-terminal",limits:"colors only — no kitty graphics, so no pictures; OSC repaints per pane",emit(t){return[{path:`windows-terminal/schemes/${t.name}.json`,content:`${JSON.stringify(Eu(t),null,2)}
|
|
61
|
+
`}]},emitShared(t){return[{path:"windows-terminal/ttheme.json",content:Li(t)}]}};function Ae(t){return[`# ${t.name} — ${t.group}${t.native?` (${t.native})`:""}`,`# ANSI: ${t.ansiSource}`]}var yu=Jn(import.meta.dirname,".."),nd=Jn(yu,"themes"),Pi=Jn(yu,"dist"),yr=[wn,$n,pn,Pn,bn,Kn,Ln],rd=[Gi,Ei],cb=yr.map((t)=>t.id);async function vr({only:t}={}){if(typeof Bun>"u")throw Error("needs bun — run it from a checkout: bun src/bin.ts build");let e=t&&t.length>0?yr.filter((o)=>t.includes(o.id)):yr,n=Dc(nd),r=xo(n);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(e.length===yr.length)Mu(Pi,{recursive:!0,force:!0});else for(let o of e)Mu(Jn(Pi,o.id),{recursive:!0,force:!0});let i=0;for(let o of[...e,...rd]){let s=n.flatMap((h)=>o.emit?.(h)??[]),c=o.emitShared?.(n)??[];for(let h of[...s,...c])await Bun.write(Jn(Pi,h.path),h.content),i++;let u=s.length>0?`${n.length} themes${o.limits?` (${o.limits})`:""}`:c.map((h)=>ed(h.path)).join(" ");console.log(` ${o.id.padEnd(16)} ${u}`)}console.log(`
|
|
62
|
+
${n.length} themes (${tu(n).length} in the new-tab rotation) -> ${i} files in dist/`)}import{spawn as Jh}from"node:child_process";import{createHash as Ah}from"node:crypto";import{existsSync as ze,mkdirSync as Vn,mkdtempSync as Lm,readFileSync as Th,rmSync as eo,statSync as Pm,writeFileSync as xn}from"node:fs";import{tmpdir as Km}from"node:os";import{dirname as Ur,join as he}from"node:path";import{pathToFileURL as Jm}from"node:url";import{execFile as id}from"node:child_process";import{createHash as Iu}from"node:crypto";import{existsSync as od,mkdtempSync as sd,readFileSync as Nr,rmSync as cd,statSync as Nu,writeFileSync as Hu}from"node:fs";import{homedir as ud,tmpdir as hd}from"node:os";import{join as Sr}from"node:path";import{fileURLToPath as fd}from"node:url";import{promisify as ad}from"node:util";var oe=ad(id),Fr=67108864,ld=4096,Ai=["image/png","image/jpeg","image/webp","image/gif","image/tiff","image/heic"],gd=["text/uri-list","text/plain;charset=utf-8","text/plain"],Ki=[...Ai,"text/uri-list","text/plain"];function dd(t){try{return Nu(t).isFile()}catch{return!1}}function md(t){let e=[],n="",r="",i=!1;for(let o=0;o<t.length;o++){let s=t[o];if(r==="'")if(s==="'")r="";else n+=s;else if(r==='"')if(s==='"')r="";else if(s==="\\"&&'"\\$`'.includes(t[o+1]??""))n+=t[++o];else n+=s;else if(s==="\\"&&o+1<t.length)n+=t[++o],i=!0;else if(s==="'"||s==='"')r=s,i=!0;else if(/\s/.test(s)){if(i)e.push(n);n="",i=!1}else n+=s,i=!0}if(i)e.push(n);return e}function vu(t){if(/^file:\/\//i.test(t))try{return fd(t)}catch{return}if(t.startsWith("~/"))return Sr(ud(),t.slice(2));return t.startsWith("/")?t:void 0}function Hr(t,e=dd){let n=[];for(let r of t.replace(/\r\n?/g,`
|
|
63
63
|
`).split(`
|
|
64
|
-
`)){let i=
|
|
64
|
+
`)){let i=vu(r.trim());if(i&&e(i)){n.push(i);continue}for(let o of md(r)){if(/^https?:\/\/\S+$/i.test(o)){n.push(o);continue}let s=vu(o);if(s&&e(s))n.push(s)}}return n}function pd(t){if(t[0]!==255||t[1]!==216)return null;let e=2;while(e+9<t.length){if(t[e]!==255){e++;continue}let n=t[e+1];if(n===255){e++;continue}let r=t[e+2]<<8|t[e+3];if(n>=192&&n<=207&&n!==196&&n!==200&&n!==204)return{height:t[e+5]<<8|t[e+6],width:t[e+7]<<8|t[e+8]};e+=2+r}return null}function Su(t){let e=En(t)?Mn(t):pd(t);if(!e)return;return{ext:En(t)?"png":"jpg",width:e.width,height:e.height}}async function Ir(t,e){let n=Su(t);if(n&&n.width*n.height<=Re)return{bytes:t,...n,source:e};if(process.platform!=="darwin")throw Error(n?`${n.width}×${n.height} is over ${Re/1e6} megapixels`:"only PNG and JPEG pictures work here");let r=sd(Sr(hd(),"ttheme-attach-"));try{let i=Sr(r,"in"),o=Sr(r,"out.png");Hu(i,t);let s=!n||n.width*n.height>Re?["--resampleHeightWidthMax",String(ld)]:[];await oe("sips",["-s","format","png",...s,i,"--out",o]).catch(()=>{throw Error("that is not a picture macOS can read")});let c=new Uint8Array(Nr(o)),u=Su(c);if(!u)throw Error("that is not a picture macOS can read");return{bytes:c,...u,source:e}}finally{cd(r,{recursive:!0,force:!0})}}async function Ti(t,e){if(/^https?:\/\//i.test(t)){let n=await fetch(t,{headers:{"User-Agent":yi},signal:e});if(!n.ok)throw Error(`${new URL(t).host} answered ${n.status}`);if(Number(n.headers.get("content-length")??0)>Fr)throw Error("that picture is over 64 MB");let r=new Uint8Array(await n.arrayBuffer());if(/^text\/html/i.test(n.headers.get("content-type")??""))throw Error(`${new URL(t).host} sent a web page, not a picture — copy the image address instead`);return Ir(r,t)}if(Nu(t).size>Fr)throw Error("that picture is over 64 MB");return Ir(new Uint8Array(Nr(t)),t)}var Ou=new Map,Or={key:"local",name:"local",origin:"file://",moved:!1,cutouts:"",best:"",tagBudget:0,vouched:!0,tunneled:!1,ansi:7,ratings:{safe:new Set,questionable:new Set,explicit:new Set},rate:()=>"",postsUrl:()=>"",countUrl:()=>"",postUrl:()=>"",pageUrl:(t)=>Ou.get(t)??"",parse:()=>[],count:()=>0};function ju(t){if(/^https?:\/\//i.test(t))return"";return t.split("/").pop()??t}function Ru(t,e){Ou.set(t,e)}function Gu(t){return Number.parseInt(Iu("sha1").update(t).digest("hex").slice(0,8),16)%le}var wd=`ObjC.import('AppKit')
|
|
65
65
|
function run(argv) {
|
|
66
66
|
const pb = $.NSPasteboard.generalPasteboard
|
|
67
67
|
const files = pb.readObjectsForClassesOptions($([$.NSURL]), $({ NSPasteboardURLReadingFileURLsOnlyKey: true }))
|
|
@@ -86,16 +86,16 @@ function run(argv) {
|
|
|
86
86
|
if (web && web.count > 0) return web.objectAtIndex(0).absoluteString.js
|
|
87
87
|
const text = pb.stringForType('public.utf8-plain-text')
|
|
88
88
|
return text && !text.isNil() ? text.js : ''
|
|
89
|
-
}`,
|
|
89
|
+
}`,bd=`Add-Type -AssemblyName System.Windows.Forms,System.Drawing
|
|
90
90
|
$c = [Windows.Forms.Clipboard]
|
|
91
91
|
$f = $c::GetFileDropList(); if ($f.Count) { $f; exit }
|
|
92
92
|
$p = Join-Path $env:TEMP 'ttheme-clipboard.png'
|
|
93
93
|
$s = $c::GetData('PNG'); if ($s -is [IO.MemoryStream]) { [IO.File]::WriteAllBytes($p, $s.ToArray()); $p; exit }
|
|
94
94
|
$i = $c::GetImage(); if ($i) { $i.Save($p, [Drawing.Imaging.ImageFormat]::Png); $p; exit }
|
|
95
|
-
$c::GetText()`;function
|
|
96
|
-
`).map((s)=>s.trim()),i=(s)=>
|
|
97
|
-
`).map(async(r)=>/^[A-Za-z]:\\/.test(r)?(await
|
|
98
|
-
`)}}if(process.platform==="linux")return
|
|
95
|
+
$c::GetText()`;function Lu(){if(process.platform!=="linux")return!1;try{return/microsoft/i.test(Nr("/proc/version","utf8"))}catch{return!1}}async function $d(t){let e=Boolean(process.env.WAYLAND_DISPLAY),n=e?["wl-paste",["--list-types"]]:["xclip",["-selection","clipboard","-t","TARGETS","-o"]],r=(await oe(n[0],n[1])).stdout.split(`
|
|
96
|
+
`).map((s)=>s.trim()),i=(s)=>e?oe("wl-paste",["--no-newline","--type",s],{encoding:"buffer",maxBuffer:Fr}):oe("xclip",["-selection","clipboard","-t",s,"-o"],{encoding:"buffer",maxBuffer:Fr});if(r.includes("text/uri-list"))return{text:(await i("text/uri-list")).stdout.toString("utf8")};let o=Ai.find((s)=>r.includes(s));if(o)return Hu(t,(await i(o)).stdout),{image:t};return{text:r.some((s)=>s.startsWith("text/plain")||s==="UTF8_STRING")?(await i(r.includes("text/plain")?"text/plain":"UTF8_STRING")).stdout.toString("utf8"):""}}function Ui(){return Boolean(process.env.SSH_CONNECTION||process.env.SSH_TTY)}async function Pu(t){if(process.platform==="darwin"){let e=(await oe("osascript",["-l","JavaScript","-e",wd,t])).stdout.trim();return e===t?{image:t}:{text:e}}if(Lu()){let e=(await oe("powershell.exe",["-NoProfile","-STA","-Command",bd])).stdout.replace(/\r/g,"").trim(),n=await Promise.all(e.split(`
|
|
97
|
+
`).map(async(r)=>/^[A-Za-z]:\\/.test(r)?(await oe("wslpath",["-u",r])).stdout.trim():r));return n.length===1&&/ttheme-clipboard\.png$/.test(n[0]??"")?{image:n[0]}:{text:n.join(`
|
|
98
|
+
`)}}if(process.platform==="linux")return $d(t);throw Error(`reading the clipboard is not supported on ${process.platform}`)}var kd=`ObjC.import('AppKit')
|
|
99
99
|
function run() {
|
|
100
100
|
const pb = $.NSPasteboard.generalPasteboard
|
|
101
101
|
const files = pb.readObjectsForClassesOptions($([$.NSURL]), $({ NSPasteboardURLReadingFileURLsOnlyKey: true }))
|
|
@@ -107,8 +107,8 @@ function run() {
|
|
|
107
107
|
picture = ['public.png', 'public.tiff', 'public.jpeg', 'public.heic'].some((t) => types.includes(t))
|
|
108
108
|
}
|
|
109
109
|
return pb.changeCount + '\\t' + (picture ? 'picture' : '')
|
|
110
|
-
}`;async function
|
|
111
|
-
`)}function Pt(t){let
|
|
110
|
+
}`;async function Ku(){if(Ui())return;if(process.platform==="darwin"){let[t="",e=""]=(await oe("osascript",["-l","JavaScript","-e",kd])).stdout.trim().split("\t");return{stamp:t,picture:e==="picture"}}if(process.platform==="linux"&&!Lu()){let e=Boolean(process.env.WAYLAND_DISPLAY)?(await oe("wl-paste",["--list-types"])).stdout:(await oe("xclip",["-selection","clipboard","-t","TARGETS","-o"])).stdout;return{stamp:e,picture:/^image\//m.test(e)}}return}function Ju(t){let e=[],n="",r=0;while(r<t.length){if(t[r]!=="\x1B"){n+=t[r],r++;continue}if(t.startsWith("\x1B[200~",r)){let o=t.indexOf("\x1B[201~",r+6);if(o===-1)return{events:e,keys:n,pending:t.slice(r)};e.push({kind:"paste",text:t.slice(r+6,o)}),r=o+6;continue}if(t.startsWith("\x1B]5522;",r)||t.startsWith("\x1B]72;",r)){let o=[t.indexOf("\x1B\\",r),t.indexOf("\x07",r)].filter((a)=>a!==-1);if(o.length===0)return{events:e,keys:n,pending:t.slice(r)};let s=Math.min(...o),c=t.slice(r+2,s),[u="",h="",...f]=c.split(";");e.push({kind:"osc",code:u,meta:Ed(h),payload:f.join(";")}),r=s+(t[s]==="\x07"?1:2);continue}let i=/^\[\?([\d;]*)(\$y|c)/.exec(t.slice(r+1,r+64));if(i){if(i[2]==="c")e.push({kind:"attributes"});else{let[o="0",s="0"]=(i[1]??"").split(";");e.push({kind:"mode",mode:Number(o),value:Number(s)})}r+=1+i[0].length;continue}if(/^(?:\[(?:\?[\d;$]*|2|20|200|201)?|\](?:5|55|552|5522|7|72)?)$/.test(t.slice(r+1)))return{events:e,keys:n,pending:t.slice(r)};n+=t[r],r++}return{events:e,keys:n,pending:""}}function Ed(t){let e={};for(let n of t.split(":")){let r=n.indexOf("=");if(r>0)e[n.slice(0,r)]=n.slice(r+1)}return e}var An=(t)=>Buffer.from(t).toString("base64"),Ji=(t)=>Buffer.from(t,"base64");function Fu(t,e){return e.find((n)=>t.includes(n))}class Wi{clipboard=!1;drops=!1;reading;offered=[];dropping;pw=An(Iu("sha1").update(`${process.pid}:${Date.now()}`).digest("hex"));send;deliver;constructor(t,e){this.send=t,this.deliver=e}start(){let t="\x1B[?2004h";if(this.clipboard)t+="\x1B[?5522h";if(this.drops)t+=`\x1B]72;t=a;${Ki.join(" ")}\x1B\\`;this.send(t)}stop(){this.send(`\x1B[?2004l${this.clipboard?"\x1B[?5522l":""}${this.drops?"\x1B]72;t=A\x1B\\":""}`)}ask(){this.reading={mime:".",chunks:[],pw:"",listing:!0},this.send(`\x1B]5522;type=read:name=${An("ttheme")}:pw=${this.pw};${An(".")}\x1B\\`)}take(t){if(t.code==="5522")this.clip(t.meta,t.payload);else if(t.code==="72")this.drop(t.meta,t.payload)}clip(t,e){if(t.type!=="read")return;let n=t.status??"";if(n==="OK"){if(this.reading??={mime:".",chunks:[],pw:t.pw??"",listing:!0},t.pw)this.reading.pw=t.pw;return}let r=this.reading;if(!r)return;if(n==="DATA"){if(r.mime=t.mime?Ji(t.mime).toString("utf8"):r.mime,e)r.chunks.push(Ji(e));return}if(this.reading=void 0,n!=="DONE"){this.deliver({kind:"error",message:n==="EPERM"?"the clipboard read was not allowed":`the terminal answered ${n}`});return}let i=Buffer.concat(r.chunks);if(r.listing){let o=i.toString("utf8").split(/\s+/).filter(Boolean),s=Fu(o,[...Ai,...gd]);if(!s){this.deliver({kind:"text",text:""});return}let c=r.pw||this.pw,u=r.pw?"Paste event":"ttheme";this.reading={mime:s,chunks:[],pw:c,listing:!1},this.send(`\x1B]5522;type=read:name=${An(u)}:pw=${c};${An(s)}\x1B\\`);return}this.deliver(r.mime.startsWith("image/")?{kind:"bytes",bytes:new Uint8Array(i),source:"clipboard"}:{kind:"text",text:i.toString("utf8")})}drop(t,e){let n=t.t??"";if(n==="m"){if(t.x==="-1"){this.offered=[];return}if(e){this.offered=e.split(" ").filter(Boolean);let c=Ki.filter((u)=>this.offered.includes(u));this.send(`\x1B]72;t=m:o=${c.length>0?1:0};${c.join(" ")}\x1B\\`)}return}if(n==="M"){let c=e?e.split(" ").filter(Boolean):this.offered,u=Fu(c,Ki);if(!u){this.send("\x1B]72;t=r:o=0\x1B\\");return}this.dropping={mimes:c,index:c.indexOf(u)+1,chunks:[]},this.send(`\x1B]72;t=r:x=${this.dropping.index}\x1B\\`);return}let r=this.dropping;if(!r)return;if(n==="R"){this.dropping=void 0,this.send("\x1B]72;t=r:o=0\x1B\\"),this.deliver({kind:"error",message:`the drop failed: ${e.split(":")[0]||"unknown error"}`});return}if(n!=="r"&&n!=="")return;if(e)r.chunks.push(Ji(e));if(t.m==="1"||e)return;this.dropping=void 0;let i=Buffer.concat(r.chunks),o=r.mimes[r.index-1]??"",s;if(o.startsWith("image/"))s={kind:"bytes",bytes:new Uint8Array(i),source:"drop"};else{let c=i.toString("utf8"),u=o==="text/uri-list"?Hr(c).find((h)=>od(h)):void 0;s=u?{kind:"bytes",bytes:new Uint8Array(Nr(u)),source:u}:{kind:"text",text:c}}this.send("\x1B]72;t=r:o=1\x1B\\"),this.deliver(s)}}import{existsSync as Md,mkdirSync as yd,readFileSync as vd,writeFileSync as Sd}from"node:fs";import{dirname as Fd,join as Id}from"node:path";var Au="https://kecan0406.github.io/ttheme/manifest.json",Nd=20000;function jr(t){return Id(t,"ttheme","catalog.json")}function Rr(t,e){let n=jr(t);yd(Fd(n),{recursive:!0}),Sd(n,`${JSON.stringify(e,null,2)}
|
|
111
|
+
`)}function Pt(t){let e=jr(t);if(!Md(e))throw Error(`no catalog at ${e} — run \`ttheme init\` first`);return Tu(vd(e,"utf8"))}function Tu(t){let e;try{e=JSON.parse(t)}catch{throw Error("catalog is not valid JSON")}let n=e;if(typeof n?.version!=="string"||!Array.isArray(n.palettes))throw Error("catalog has no version or palettes");for(let r of n.palettes)if(typeof r?.name!=="string"||!Array.isArray(r.ansi)||r.ansi.length!==16)throw Error(`catalog entry ${JSON.stringify(r?.name)} is missing name or its 16 ANSI colors`);return n}async function Uu(t){let e;try{e=await fetch(t,{signal:AbortSignal.timeout(Nd)})}catch(n){throw Error(`cannot reach the registry at ${t} — ${n instanceof Error?n.message:String(n)}`)}if(!e.ok)throw Error(`registry at ${t} answered ${e.status}`);return Tu(await e.text())}function Wu(t){let e=new Set(t.waived??[]);return cr.flatMap((n,r)=>{let i=t.gate?.[r];if(e.has(n.rule)||typeof i!=="number")return[];if(n.min!==void 0&&i<n.min)return[`${n.label} ${i} < ${n.min}`];if(n.max!==void 0&&i>n.max)return[`${n.label} ${i} > ${n.max}`];return[]})}function Gr(t,e){let n=t.find((r)=>r.name===e);if(!n)throw Error(`no palette named ${e} in the catalog — ${Qi(t,[e])}`);return n}function Qi(t,e){let n=e.map((s)=>s.toLowerCase()),r=t.filter((s)=>n.some((c)=>s.name.includes(c))),i=t.filter((s)=>!r.includes(s)&&n.some((c)=>s.group.toLowerCase().includes(c))),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 Qu(t,e){let n=e.toLowerCase();return t.filter((r)=>[r.name,r.group,r.native??"",r.ansiSource].some((i)=>i.toLowerCase().includes(n)))}function qu(t,e,n){let r=n.toLowerCase(),i=(o)=>o.name===e.name?0:o.group===e.group?1:2;return t.filter((o)=>o.booru?.toLowerCase().includes(r)).map((o,s)=>({p:o,at:s})).sort((o,s)=>i(o.p)-i(s.p)||o.at-s.at).map(({p:o})=>o)}function Zu(t,e){return t.booruSites?.[e]??(t.booru?[t.booru]:[])}import{spawn as Hd}from"node:child_process";var Od=30000,jd=3,Rd=97,Gd=`ObjC.import('Vision')
|
|
112
112
|
ObjC.import('CoreImage')
|
|
113
113
|
ObjC.import('CoreGraphics')
|
|
114
114
|
function run(argv) {
|
|
@@ -127,94 +127,97 @@ function run(argv) {
|
|
|
127
127
|
$.CIImage.imageWithCVPixelBuffer(buffer), $.NSURL.fileURLWithPath(argv[1]), $.kCIFormatRGBA8,
|
|
128
128
|
$.CGColorSpaceCreateWithName($.kCGColorSpaceSRGB), $({}), error)
|
|
129
129
|
if (!written) throw new Error('write failed')
|
|
130
|
-
}`;function
|
|
131
|
-
`).at(-1)||`osascript exited ${c}`))})})}var
|
|
132
|
-
`?"enter":r==="\t"?"tab":r==="\x03"?"ctrl-c":r==="\x16"?"ctrl-v":r===""||r==="\b"?"backspace":r),e++}return n}var Xu="\x1B]1337;ReportCellSize\x07\x1B[16t",Qu="\x1B]1337;ReportCellSize=";function Qi(t){let n=t.indexOf(Qu);if(n!==-1){let i=t.slice(n+Qu.length),o=[i.indexOf("\x07"),i.indexOf("\x1B\\")].filter((u)=>u!==-1),s=o.length>0?Math.min(...o):-1,c=s===-1?null:/^([\d.]+);([\d.]+);([\d.]+)$/.exec(i.slice(0,s));if(c){let u=Number(c[3]);return{cell:{h:Math.round(Number(c[1])*u),w:Math.round(Number(c[2])*u)},rest:t.slice(0,n)+i.slice(s+(i[s]==="\x07"?1:2))}}}let e=t.indexOf("\x1B[6;"),r=e===-1?null:/^\[6;(\d+);(\d+)t/.exec(t.slice(e+1));if(!r)return null;return{cell:{h:Number(r[1]),w:Number(r[2])},rest:t.slice(0,e)+t.slice(e+1+r[0].length)}}function _n(t,n){return{perRow:Math.max(1,Math.floor((t+1)/Jt.pitch)),rowsVis:Math.max(1,Math.floor((n-4)/Jt.height))}}function _u(t){return`\x1B_Ga=t,t=f,f=100,i=${t.id},q=2;${Buffer.from(t.path).toString("base64")}\x1B\\`}function Cu(t){return`\x1B[${t.row+1};${t.col+1}H\x1B_Ga=p,i=${t.id},p=${t.id},c=${t.cols},r=${t.rows},C=1,z=${t.z},q=2\x1B\\`}function zu(t){return`\x1B_Ga=d,d=I,i=${t},q=2\x1B\\`}function Yu(t){return`\x1B[38;2;${Rt(t).join(";")}m`}function Ti(t){return`\x1B[48;2;${Rt(t).join(";")}m`}function Ct(t){return Array.from(t).length}class Rr{parts=[];cols;constructor(t){this.cols=t}put(t,n,e=""){return this.parts.push({col:t,text:n,sgr:e}),t+Ct(n)}run(t,n){let e=t;for(let[r,i]of n)e=this.put(e,r,i);return e}right(t,n){this.run(t-n.reduce((e,[r])=>e+Ct(r),0),n)}render(){let t="";for(let{col:n,text:e,sgr:r}of this.parts){if(n>=this.cols||n<0)continue;let i=Array.from(e).slice(0,this.cols-n).join("");t+=`\x1B[${n+1}G${r}${i}${r?Gd:""}`}return t}}function Vu(t){return t>=1e6?`${(t/1e6).toFixed(1)} MB`:`${Math.max(1,Math.round(t/1000))} KB`}function Kd(t,n){if(!n)return Vu(t);return n>=1e6?`${(t/1e6).toFixed(1)}/${(n/1e6).toFixed(1)} MB`:`${Math.round(t/1000)}/${Math.round(n/1000)} KB`}function xu(t){return t.replace(/_\([^)]*\)?$/,"")}function Bu(t){return[`${t.reduced?"↓":""}${t.width}×${t.height}`,Math.max(t.width,t.height)<Rd?Ut:ut]}function Ae(t,n,e,r){let i=[...r.keys??[]],o=r.lead,s=r.right,c=()=>{let f=[...o?[Ct(o[0])]:[],...i.map(([g,d])=>Ct(g)+1+Ct(d))];return(r.badge?Ct(r.badge)+4:0)+f.reduce((g,d)=>g+d,0)+3*Math.max(0,f.length-1)+(s?3+Ct(s[0])+1+Ct(s[1]):0)};while(c()>n)if(i.length>2)i.splice(-2,1);else if(s)s=void 0;else if(i.length>1)i.splice(-2,1);else break;if(o&&c()>n){let f=Math.max(0,Ct(o[0])-(c()-n)-1);o=[`${Array.from(o[0]).slice(0,f).join("")}…`,o[1]]}let u=0;if(r.badge)u=t.put(0,` ${r.badge} `,`\x1B[7;1m${e}`)+2;if([...o?[[o]]:[],...i.map(([f,a])=>[[f,un],[` ${a}`,ut]])].forEach((f,a)=>{u=t.run(u+(a?3:0),f)}),s)t.right(n,[[s[0],un],[` ${s[1]}`,ut]])}function Jd(t,n,e,r,i,o){let{ansi:s,selection:c,cursor:u}=o.colors,h=r<44?3:4;if(r>=56)h=Math.min(7,Math.floor((r+1)/8)-1);let f=e;for(let p=0;p<8;p++)f=(t[n]?.put(f,"▀".repeat(h),Yu(s[p]??u)+Ti(s[p+8]??u))??f)+1;let a=["❯ ",cn],g=[[["~/code/demo",jr],[" on ",ut],["main",Ld],[" +2",cn],[" ~1",Ut]]];if(g.push([a,["git status -sb",""]]),r>=44)g.push([["## ",""],["main",cn],["...",""],["origin/main",Je],[" [ahead 1]",Ut]]);if(g.push([[" M",Je],[" src/main.rs",""]]),g.push([["??",Je],[" notes.md",""]]),g.push([]),r>=44)g.push([a,["ls",""]]),g.push([["docs",jr],[" ",""],["src",jr],[" ",""],["tests",jr],[" Cargo.toml README.md",""]]),g.push([]);g.push([a,["cargo test",""]]),g.push([[" ✓",cn],[" parses config",""]]);let d=[[" ✗",Je],[" renders frame",""]];if(r>=44)d.push([" expected ",ut],["3",cn],[", received ",ut],["2",Je]);g.push(d),g.push([]),g.push([a,["echo ",""],["selected text",Ti(c)],[" ",""],[" ",Ti(u)]]),g.forEach((p,l)=>{let k=n+2+l;if(k<=i)t[k]?.run(e,p)})}function Ad(t,n,e,r,i,o){t[n]?.put(e,`╭${"─".repeat(i-2)}╮`,o);for(let s=n+1;s<n+r-1;s++)t[s]?.put(e,"│",o),t[s]?.put(e+i-1,"│",o);t[n+r-1]?.put(e,`╰${"─".repeat(i-2)}╯`,o)}function Wi(t,n=t.site,e=t.siteAnsi){return[` ${n} `,`\x1B[7;${30+e}m`]}function Ud(t){return`${gt[Math.floor(t/ln)]?.name??"local"} ${t%ln}`}function Td(t,n,e){let r=[{name:"all",moved:!1},...gt].flatMap((s,c)=>{let u=`${s.name}${s.moved?"*":""}`,h=s.name===e.site?Wi(e,u):[` ${u} `,ut];return c?[[" ",""],h]:[h]}),i=r.reduce((s,[c])=>s+Ct(c),0)<=n,o=t.run(0,i?r:[Wi(e)]);if(e.asking!==void 0)t.run(o,[[` ${e.asking} was cut off — this network may block it. turn on the unblock proxy? `,Ut],["y",un],[" turn on ",ut],["n",un],[" not now",ut]])}function Wd(t,n,e,r){if(e.editing!==void 0){let c=t.run(0,[["⌕ ",r],[e.editing,""],["█",r]]),u=e.suggest?.length?" ↑↓ pick enter searches":" enter searches";t.put(c,e.editing?u:` a tag, a post url or an id, or drop a picture or ctrl+v — ${e.tag||"esc leaves"}`,ut);return}let i=t.run(0,[["⌕ ",r],[e.tag||"nothing yet — / searches, ctrl+v pastes a picture",e.tag?"":ut]]),o=jn.filter((c)=>!e.block.includes(c)),s=[e.preset,...e.solo?["solo"]:[],e.order,...e.rating.join("+")==="safe"?[]:[e.rating.join("+")],...o.length>0?[`allows ${o.join("+")}`]:[],...e.unblocked?["unblock"]:[]];if(t.put(i,` ${s.join(" ")}`,ut),e.total>0||!e.searching){let c=[[`${e.tiles.length}/${e.checked}`,""]];if(e.checked<e.total)c.push([` of ${e.total}`,ut]);t.right(n,c)}}function Qd(t){if(t.cut==="on")return[[`cut out · ${t.clear}% transparent`,cn]];if(t.cut==="off")return[["opaque · x cuts out",Ut]];if(t.cut==="failed")return[["opaque · no cut-out",Ut]];return[t.clear>0?[`${t.clear}% transparent`,cn]:["opaque",Ut]]}function Zu(t){return t.site==="all"?"any site":t.site}function Du(t){if(t.installing!==void 0)return[`installing ${t.palette} ← ${Ud(t.installing)}`,Ut];if(t.hint)return[t.hint,cn];if(t.error)return[t.error,Ut];if(t.waiting!==void 0)return[`${t.slow??t.site} asked to slow down · ${t.waiting}s`,Ut];if(t.fetching)return[`fetching ${t.fetching.id%ln} · ${Kd(t.fetching.got,t.fetching.size)}`,Ut];if(t.cutting!==void 0)return[`cutting out ${t.cutting%ln}`,Ut];if(t.preparing!==void 0)return[`preparing ${t.preparing%ln}`,Ut];if(t.saved)return[t.saved,cn];if(t.note)return[t.note,ut];return}function Zd(t,n,e,r,i,o){let{perRow:s,rowsVis:c}=_n(e,r);Wd(t[0],e,i,o),Td(t[1],e,i);for(let d=0;d<s*c;d++){let p=i.top*s+d,l=i.tiles[p];if(!l)break;let k=2+Math.floor(d/s)*Jt.height,v=d%s*Jt.pitch,I=p===i.focus;if(I)Ad(t,k,v,Jt.height,Jt.pitch-1,o);if(l.thumb)n.push({id:l.key,path:l.thumb,row:k+1,col:v+1,cols:Jt.cols,rows:Jt.rows,z:-1});if(t[k+10]?.run(v+1,[...i.installed.includes(l.key)?[["✓ ",cn]]:[],...i.site==="all"?[["● ",`\x1B[${30+l.siteAnsi}m`]]:[],[String(l.id),I?un:""],[" ",""],Bu(l)]),l.mates.length>0)t[k+10]?.put(v+Jt.cols,"≈",o);let E=l.artist?xu(l.artist):l.owner&&`@${l.owner}`;if(E)t[k+11]?.put(v+1,E.slice(0,Jt.cols-8),ut);let y=[];if(l.score>0)y.push([`★${l.score}`,ut]);if(l.variants>1)y.push([` ×${l.variants}`,o]);if(y.length>0)t[k+11]?.right(v+Jt.cols+1,y)}let u=i.top*s,h=i.tiles.length-(i.top+c)*s,f=[...u>0?[`↑ ${u} above`]:[],...h>0?[`↓ ${h} more`]:[]];if(f.length>0)t[r-2]?.put(0,f.join(" "),ut);if(!i.searching&&i.tiles.length===0&&!i.error)t[3]?.put(0,i.preset==="cutouts"?`no transparent cutouts of ${i.tag} on ${Zu(i)} — c searches every post, tab tries ${i.nextSite}`:`no posts of ${i.tag} on ${Zu(i)} — tab tries ${i.nextSite}`,ut);let a=t[r-1],g=Du(i);if(i.searching&&i.tiles.length===0&&!g){Ae(a,e,o,{badge:"FIND",lead:[i.preset==="cutouts"?"checking png headers":"fetching posts",ut],right:["esc","back"]});return}Ae(a,e,o,{badge:"FIND",lead:g,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 qd(t,n,e,r,i,o){let s=i.tiles[i.focus];if(!s)return;let c=i.shown?.id===s.key?i.shown:void 0,u=[Wi(i,s.site,s.siteAnsi),[" ",""],[String(s.id),un],[" ",""],Bu(s)];if(s.artist)u.push([` · ${xu(s.artist)}`,""]);if(s.score>0)u.push([` · ★${s.score}`,ut]);if(c)u.push([` · ${Vu(c.bytes)}`,ut]);if(s.owner)u.push([` · ${s.owner}`,ut]);if(s.origin)u.push([` · ${s.origin}`,ut]);if(c)u.push([" ",""],...Qd(c));if(t[0]?.run(0,u),s.mates.length>0)t[0]?.right(e,[["≈ ",o],[s.mates.join(" "),ut]]);if(Jd(t,3,2,e-4,r-2,i),i.shown)n.push({id:Hd+i.shown.id,path:i.shown.path,row:0,col:0,cols:e,rows:r,z:jd});let h=Du(i);Ae(t[r-1],e,o,{badge:"TRY",lead:h,keys:i.installing===void 0?[["←→","browse"],["enter","install"],...i.shown?.cut==="on"||i.shown?.cut==="off"?[["x","cut out"]]:[],["?","keys"]]:[],right:i.installing===void 0?["esc","grid"]:void 0})}var Xd={grid:[["move","←↑↓→ home end pgup pgdn"],["try on","enter"],["site",`tab all, ${gt.map((t)=>t.name).join(", ")}`],["posts","c cutouts or every post"],["search","/ a tag, a post url or an id"],["your own","ctrl+v or v a picture from the clipboard · drop one on the window or paste its link"],["unfold","space a set of ×N"],["open","o the post page in a browser"],["settings","s rating, block, posts, solo, order, sets, remove bg"],["back","esc returns to preview"],["close","? esc"]],try:[["browse","←→"],["install","enter"],["cut out","x the background off or on, on an opaque picture"],["open","o the post page in a browser"],["your own","ctrl+v or v a picture from the clipboard · drop one on the window"],["grid","esc"],["close","? esc"]]};function _d(t,n,e,r,i){let o=r.panel??0,s=Math.max(...r.settings.map((g)=>g.label.length)),c=Math.max(...r.settings.map((g)=>g.choices.reduce((d,p)=>d+p.length+(g.multi?6:3),0))),u=Math.min(n-2,Math.max(28,s+c+8)),h=r.settings.length+4,f=Math.floor((n-u)/2),a=Math.max(2,Math.floor((e-h)/2));t[a]?.put(f,`╭─ settings ${"─".repeat(Math.max(0,u-13))}╮`);for(let g=a+1;g<a+h-1;g++)t[g]?.put(f,`│${" ".repeat(u-2)}│`);r.settings.forEach((g,d)=>{let p=t[a+2+d];p.put(f+3,g.label,d===o?un:ut);let l=f+5+s,k=g.value.split(" ");g.choices.forEach((v,I)=>{let E=k.includes(v),y=g.multi&&d===o&&I===g.cursor?"4;":"",$=g.multi?` ${E?"[x]":"[ ]"} ${v} `:` ${v} `;l=p.put(l,$,E?`\x1B[${y}7;${30+r.siteAnsi}m`:y?`\x1B[4m${ut}`:ut)+1})}),t[a+h-1]?.put(f,`╰${"─".repeat(u-2)}╯`),Ae(t[e-1],n,i,{badge:"SET",keys:[["↑↓","setting"],["←→","value"],["space","toggle"],["enter","save"]],right:["esc","undo"]})}function Cd(t,n,e,r,i){let o=Xd[r.mode],s=Math.min(n-2,50),c=o.length+4,u=Math.floor((n-s)/2),h=Math.max(2,Math.floor((e-c)/2));t[h]?.put(u,`╭─ keys ${"─".repeat(s-9)}╮`);for(let f=h+1;f<h+c-1;f++)t[f]?.put(u,`│${" ".repeat(s-2)}│`);o.forEach(([f,a],g)=>{t[h+2+g]?.put(u+3,f,un),t[h+2+g]?.put(u+13,a.slice(0,s-16))}),t[h+c-1]?.put(u,`╰${"─".repeat(s-2)}╯`),Ae(t[e-1],n,i,{badge:"KEYS",right:["? esc","close"]})}function zd(t,n,e){let r=n.suggest??[],i=r.map((c)=>c.count>0?String(c.count):c.palette??"0"),o=Math.max(...r.map((c)=>Ct(c.value))),s=Math.max(7,...i.map(Ct));r.forEach((c,u)=>{let h=u===n.pick,f=t[1+u];f?.run(0,[[h?"▸ ":" ",e],[c.value,h?un+e:""]]),f?.right(2+o+2+s,[[i[u],ut]])})}function th(t,n,e){let r=Array.from({length:e},()=>new Rr(n)),i=[],o=Yu(t.colors.cursor);if(n<Ln.cols||e<Ln.rows)return r[0]?.put(0,"ttheme find",un+o),r[1]?.put(0,`needs ${Ln.cols}×${Ln.rows} — now ${n}×${e}`),r[2]?.put(0,"esc quits",ut),{lines:r.map((s)=>s.render()),images:i};if(t.mode==="try")qd(r,i,n,e,t,o);else Zd(r,i,n,e,t,o);if(t.mode==="grid"&&t.editing!==void 0&&t.suggest?.length){for(let s=1;s<e-1;s++)r[s]=new Rr(n);return zd(r,t,o),{lines:r.map((s)=>s.render()),images:[]}}if(t.help||t.panel!==void 0){let s=t.mode==="try"?i:[];for(let c=0;c<e;c++)r[c]=new Rr(n);if(t.help)Cd(r,n,e,t,o);else _d(r,n,e,t,o);return{lines:r.map((c)=>c.render()),images:s}}return{lines:r.map((s)=>s.render()),images:i}}var Yd=new Set(["comic","4koma","monochrome","greyscale","sketch","lineart","speech_bubble"]),Vd=new Set(["scenery","landscape","scenic","no_humans","wide_shot","very_wide_shot"]),xd=0.04,Bd=0.1,Dd=0.05,tm=4096;function nm(t){return new Set(t.cutouts.split(/\s+/).map((n)=>n.replace(/^~/,"")).filter(Boolean))}function em(t,n,e,r=0){let{site:i,post:o}=t,s=new Set(o.tags),c=[...nm(i)].some((f)=>s.has(f)),u=Math.min(o.width,o.height),h=o.width>0&&o.height>0?o.width/o.height/(n.w/n.h):1;return(o.solo?2:0)+([...Yd].some((f)=>s.has(f))?-3:0)+([...Vd].some((f)=>s.has(f))?-1.5:0)+2*Math.min(1,u/n.h)+(c?1.5:-Math.min(1.5,Math.abs(Math.log(h))))+(e>0?1.5*Math.log1p(Math.max(0,o.score))/Math.log1p(e):0)+2*r}function Gr(t,n,e=new Map){let r=new Map;for(let{site:i,post:o}of t)r.set(i,Math.max(r.get(i)??0,o.score));return t.map((i,o)=>({pick:i,at:o,score:em(i,n,r.get(i.site)??0,e.get(i.post))})).sort((i,o)=>o.score-i.score||i.at-o.at).map(({pick:i})=>i)}function eh(t){let n=new Map;for(let r of t)n.set(r.site,[...n.get(r.site)??[],r]);let e=[];for(let r=0;e.length<t.length;r++)for(let i of n.values()){let o=i[r];if(o)e.push(o)}return e}function Zi(t){let n=t/255;return n<=0.04045?n/12.92:((n+0.055)/1.055)**2.4}function nh(t,n,e){let[r,i,o]=[Zi(t),Zi(n),Zi(e)],s=Math.cbrt(0.4122214708*r+0.5363325363*i+0.0514459929*o),c=Math.cbrt(0.2119034982*r+0.6806995451*i+0.1073969566*o),u=Math.cbrt(0.0883024619*r+0.2817188376*i+0.6299787005*o);return[0.2104542553*s+0.793617785*c-0.0040720468*u,1.9779984951*s-2.428592205*c+0.4505937099*u,0.0259040371*s+0.7827717662*c-0.808675766*u]}function rh(t,n){let e=n.map((s)=>nh(...Rt(s))).filter(([,s,c])=>Math.hypot(s,c)>=xd);if(e.length===0)return 0;let r=Math.max(1,Math.floor(Math.sqrt(t.width*t.height/tm))),i=e.map(()=>0),o=0;for(let s=0;s<t.height;s+=r)for(let c=0;c<t.width;c+=r){let u=(s*t.width+c)*4;if(t.data[u+3]<128)continue;o++;let[h,f,a]=nh(t.data[u],t.data[u+1],t.data[u+2]);e.forEach(([g,d,p],l)=>{if(Math.hypot(h-g,f-d,a-p)<Bd)i[l]=i[l]+1})}if(o===0)return 0;return i.reduce((s,c)=>s+Math.min(1,c/o/Dd),0)/e.length}import{execFileSync as rm,spawn as im}from"node:child_process";import{existsSync as zt,mkdirSync as Te,readFileSync as Sn,rmSync as qi,utimesSync as om,writeFileSync as Cn}from"node:fs";import{homedir as Pr}from"node:os";import{dirname as We,join as mt}from"node:path";var sm={ghostty:pe,kitty:$e,alacritty:me,wezterm:Ge,iterm2:we,"windows-terminal":Le,warp:Re},ih="ttheme-default";function zn(t=process.env.TTHEME_ITERM_SUITE??"com.googlecode.iterm2"){let n=(e,r)=>rm(e,r,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();return{read:()=>{try{return process.platform==="darwin"?n("defaults",["read",t,"Default Bookmark Guid"])||void 0:void 0}catch{return}},write:(e)=>{if(process.platform==="darwin")n("defaults",["write",t,"Default Bookmark Guid","-string",e])},running:()=>{try{return n("pgrep",["-x","iTerm2"])!==""}catch{return!1}}}}function hn(t){return t.off?void 0:Yn(t)}function Qe(t,n){if(!t.terminals.includes("iterm2"))return t;let e=n.read();return e&&!e.startsWith("ttheme-")?{...t,itermBase:e}:t}function Ze(t,n){if(!t.terminals.includes("iterm2"))return!1;let e=n.read(),r=hn(t)?ih:e===ih?t.itermBase:void 0;if(!r||r===e)return!1;return n.write(r),!0}function Tt(){return process.env.XDG_CONFIG_HOME??mt(Pr(),".config")}function oh(t){return mt(t,"Library","Application Support","iTerm2","DynamicProfiles","ttheme.json")}function sh(t){return mt(t,"ttheme","installed.json")}function Yt(t){let n=sh(t);if(!zt(n))throw Error(`nothing installed yet at ${n} — run \`ttheme init\` first`);let e=JSON.parse(Sn(n,"utf8"));if(!Array.isArray(e?.palettes)||!Array.isArray(e.terminals))throw Error(`${n} has no palettes or terminals`);return{terminals:e.terminals.filter((r)=>mr.includes(r)),...e.startup?{startup:e.startup}:{},...e.off?{off:!0}:{},...e.itermBase?{itermBase:e.itermBase}:{},...e.wtHome?{wtHome:e.wtHome}:{},...e.wtProfile?{wtProfile:e.wtProfile}:{},palettes:e.palettes}}function qe(t,n){let e=sh(t);Te(We(e),{recursive:!0}),Cn(e,`${JSON.stringify(n,null,2)}
|
|
133
|
-
`)}function
|
|
130
|
+
}`;function qi(){return process.platform==="darwin"}function _u(t){return t>=jd&&t<=Rd}function Xu(t,e,n){return new Promise((r,i)=>{let o=Hd("osascript",["-l","JavaScript","-e",Gd,t,e],{stdio:["ignore","ignore","pipe"],signal:AbortSignal.any([n,AbortSignal.timeout(Od)])}),s="";o.stderr.on("data",(c)=>{s+=c}),o.on("error",i),o.on("close",(c)=>{if(c===0){r();return}i(Error(s.trim().split(`
|
|
131
|
+
`).at(-1)||`osascript exited ${c}`))})})}var At={pitch:25,cols:22,rows:9,height:13},Le={cols:25,rows:16},Ld=2147483648,Pd=-1073741826,Kd=1600,Jd="\x1B[0m",ce="\x1B[1m",ut="\x1B[2m",Tn="\x1B[31m",se="\x1B[32m",Ut="\x1B[33m",Lr="\x1B[1;34m",Ad="\x1B[35m",Td={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 xu(t){let e=[],n=0;while(n<t.length){let r=t[n]??"";if(r==="\x1B"){let i=/^(?:\[([0-9;]*)([A-Za-z~])|O([A-Za-z]))/.exec(t.slice(n+1));if(i){e.push(Td[`${i[1]??""}${i[2]??i[3]??""}`]??"nop"),n+=1+i[0].length;continue}let o=t[n+1]??"";if(/^[a-z]$/.test(o)){e.push(`alt-${o}`),n+=2;continue}e.push("esc"),n++;continue}e.push(r==="\r"||r===`
|
|
132
|
+
`?"enter":r==="\t"?"tab":r==="\x03"?"ctrl-c":r==="\x16"?"ctrl-v":r===""||r==="\b"?"backspace":r),n++}return e}var zu="\x1B]1337;ReportCellSize\x07\x1B[16t",Cu="\x1B]1337;ReportCellSize=";function Xi(t){let e=t.indexOf(Cu);if(e!==-1){let i=t.slice(e+Cu.length),o=[i.indexOf("\x07"),i.indexOf("\x1B\\")].filter((u)=>u!==-1),s=o.length>0?Math.min(...o):-1,c=s===-1?null:/^([\d.]+);([\d.]+);([\d.]+)$/.exec(i.slice(0,s));if(c){let u=Number(c[3]);return{cell:{h:Math.round(Number(c[1])*u),w:Math.round(Number(c[2])*u)},rest:t.slice(0,e)+i.slice(s+(i[s]==="\x07"?1:2))}}}let n=t.indexOf("\x1B[6;"),r=n===-1?null:/^\[6;(\d+);(\d+)t/.exec(t.slice(n+1));if(!r)return null;return{cell:{h:Number(r[1]),w:Number(r[2])},rest:t.slice(0,n)+t.slice(n+1+r[0].length)}}function _e(t,e){return{perRow:Math.max(1,Math.floor((t+1)/At.pitch)),rowsVis:Math.max(1,Math.floor((e-4)/At.height))}}function Yu(t){return`\x1B_Ga=t,t=f,f=100,i=${t.id},q=2;${Buffer.from(t.path).toString("base64")}\x1B\\`}function Bu(t){return`\x1B[${t.row+1};${t.col+1}H\x1B_Ga=p,i=${t.id},p=${t.id},c=${t.cols},r=${t.rows},C=1,z=${t.z},q=2\x1B\\`}function Du(t){return`\x1B_Ga=d,d=I,i=${t},q=2\x1B\\`}function th(t){return`\x1B[38;2;${Rt(t).join(";")}m`}function Zi(t){return`\x1B[48;2;${Rt(t).join(";")}m`}function Ct(t){return Array.from(t).length}class Pr{parts=[];cols;constructor(t){this.cols=t}put(t,e,n=""){return this.parts.push({col:t,text:e,sgr:n}),t+Ct(e)}run(t,e){let n=t;for(let[r,i]of e)n=this.put(n,r,i);return n}right(t,e){this.run(t-e.reduce((n,[r])=>n+Ct(r),0),e)}render(){let t="";for(let{col:e,text:n,sgr:r}of this.parts){if(e>=this.cols||e<0)continue;let i=Array.from(n).slice(0,this.cols-e).join("");t+=`\x1B[${e+1}G${r}${i}${r?Jd:""}`}return t}}function eh(t){return t>=1e6?`${(t/1e6).toFixed(1)} MB`:`${Math.max(1,Math.round(t/1000))} KB`}function Ud(t,e){if(!e)return eh(t);return e>=1e6?`${(t/1e6).toFixed(1)}/${(e/1e6).toFixed(1)} MB`:`${Math.round(t/1000)}/${Math.round(e/1000)} KB`}function nh(t){return t.replace(/_\([^)]*\)?$/,"")}function rh(t){return[`${t.reduced?"↓":""}${t.width}×${t.height}`,Math.max(t.width,t.height)<Kd?Ut:ut]}function Un(t,e,n,r){let i=[...r.keys??[]],o=r.lead,s=r.right,c=()=>{let f=[...o?[Ct(o[0])]:[],...i.map(([l,d])=>Ct(l)+1+Ct(d))];return(r.badge?Ct(r.badge)+4:0)+f.reduce((l,d)=>l+d,0)+3*Math.max(0,f.length-1)+(s?3+Ct(s[0])+1+Ct(s[1]):0)};while(c()>e)if(i.length>2)i.splice(-2,1);else if(s)s=void 0;else if(i.length>1)i.splice(-2,1);else break;if(o&&c()>e){let f=Math.max(0,Ct(o[0])-(c()-e)-1);o=[`${Array.from(o[0]).slice(0,f).join("")}…`,o[1]]}let u=0;if(r.badge)u=t.put(0,` ${r.badge} `,`\x1B[7;1m${n}`)+2;if([...o?[[o]]:[],...i.map(([f,a])=>[[f,ce],[` ${a}`,ut]])].forEach((f,a)=>{u=t.run(u+(a?3:0),f)}),s)t.right(e,[[s[0],ce],[` ${s[1]}`,ut]])}function Wd(t,e,n,r,i,o){let{ansi:s,selection:c,cursor:u}=o.colors,h=r<44?3:4;if(r>=56)h=Math.min(7,Math.floor((r+1)/8)-1);let f=n;for(let p=0;p<8;p++)f=(t[e]?.put(f,"▀".repeat(h),th(s[p]??u)+Zi(s[p+8]??u))??f)+1;let a=["❯ ",se],l=[[["~/code/demo",Lr],[" on ",ut],["main",Ad],[" +2",se],[" ~1",Ut]]];if(l.push([a,["git status -sb",""]]),r>=44)l.push([["## ",""],["main",se],["...",""],["origin/main",Tn],[" [ahead 1]",Ut]]);if(l.push([[" M",Tn],[" src/main.rs",""]]),l.push([["??",Tn],[" notes.md",""]]),l.push([]),r>=44)l.push([a,["ls",""]]),l.push([["docs",Lr],[" ",""],["src",Lr],[" ",""],["tests",Lr],[" Cargo.toml README.md",""]]),l.push([]);l.push([a,["cargo test",""]]),l.push([[" ✓",se],[" parses config",""]]);let d=[[" ✗",Tn],[" renders frame",""]];if(r>=44)d.push([" expected ",ut],["3",se],[", received ",ut],["2",Tn]);l.push(d),l.push([]),l.push([a,["echo ",""],["selected text",Zi(c)],[" ",""],[" ",Zi(u)]]),l.forEach((p,g)=>{let k=e+2+g;if(k<=i)t[k]?.run(n,p)})}function Qd(t,e,n,r,i,o){t[e]?.put(n,`╭${"─".repeat(i-2)}╮`,o);for(let s=e+1;s<e+r-1;s++)t[s]?.put(n,"│",o),t[s]?.put(n+i-1,"│",o);t[e+r-1]?.put(n,`╰${"─".repeat(i-2)}╯`,o)}function _i(t,e=t.site,n=t.siteAnsi){return[` ${e} `,`\x1B[7;${30+n}m`]}function qd(t){return`${lt[Math.floor(t/le)]?.name??"local"} ${t%le}`}function Zd(t,e,n){let r=[{name:"all",moved:!1},...lt].flatMap((s,c)=>{let u=`${s.name}${s.moved?"*":""}`,h=s.name===n.site?_i(n,u):[` ${u} `,ut];return c?[[" ",""],h]:[h]}),i=r.reduce((s,[c])=>s+Ct(c),0)<=e,o=t.run(0,i?r:[_i(n)]);if(n.asking!==void 0)t.run(o,[[` ${n.asking} was cut off — this network may block it. turn on the unblock proxy? `,Ut],["y",ce],[" turn on ",ut],["n",ce],[" not now",ut]])}function _d(t,e,n,r){if(n.editing!==void 0){let c=t.run(0,[["⌕ ",r],[n.editing,""],["█",r]]),u=n.suggest?.length?" ↑↓ pick enter searches":" enter searches";t.put(c,n.editing?u:` a tag, a post url or an id, or drop a picture or ctrl+v — ${n.tag||"esc leaves"}`,ut);return}let i=t.run(0,[["⌕ ",r],[n.tag||"nothing yet — / searches, ctrl+v pastes a picture",n.tag?"":ut]]),o=je.filter((c)=>!n.block.includes(c)),s=[n.preset,...n.solo?["solo"]:[],n.order,...n.rating.join("+")==="safe"?[]:[n.rating.join("+")],...o.length>0?[`allows ${o.join("+")}`]:[],...n.unblocked?["unblock"]:[]];if(t.put(i,` ${s.join(" ")}`,ut),n.total>0||!n.searching){let c=[[`${n.tiles.length}/${n.checked}`,""]];if(n.checked<n.total)c.push([` of ${n.total}`,ut]);t.right(e,c)}}function Xd(t){if(t.cut==="on")return[[`cut out · ${t.clear}% transparent`,se]];if(t.cut==="off")return[["opaque · x cuts out",Ut]];if(t.cut==="failed")return[["opaque · no cut-out",Ut]];return[t.clear>0?[`${t.clear}% transparent`,se]:["opaque",Ut]]}function Vu(t){return t.site==="all"?"any site":t.site}function ih(t){if(t.installing!==void 0)return[`installing ${t.palette} ← ${qd(t.installing)}`,Ut];if(t.hint)return[t.hint,se];if(t.error)return[t.error,Ut];if(t.waiting!==void 0)return[`${t.slow??t.site} asked to slow down · ${t.waiting}s`,Ut];if(t.fetching)return[`fetching ${t.fetching.id%le} · ${Ud(t.fetching.got,t.fetching.size)}`,Ut];if(t.cutting!==void 0)return[`cutting out ${t.cutting%le}`,Ut];if(t.preparing!==void 0)return[`preparing ${t.preparing%le}`,Ut];if(t.saved)return[t.saved,se];if(t.note)return[t.note,ut];return}function Cd(t,e,n,r,i,o){let{perRow:s,rowsVis:c}=_e(n,r);_d(t[0],n,i,o),Zd(t[1],n,i);for(let d=0;d<s*c;d++){let p=i.top*s+d,g=i.tiles[p];if(!g)break;let k=2+Math.floor(d/s)*At.height,y=d%s*At.pitch,I=p===i.focus;if(I)Qd(t,k,y,At.height,At.pitch-1,o);if(g.thumb)e.push({id:g.key,path:g.thumb,row:k+1,col:y+1,cols:At.cols,rows:At.rows,z:-1});if(t[k+10]?.run(y+1,[...i.installed.includes(g.key)?[["✓ ",se]]:[],...i.site==="all"?[["● ",`\x1B[${30+g.siteAnsi}m`]]:[],[String(g.id),I?ce:""],[" ",""],rh(g)]),g.mates.length>0)t[k+10]?.put(y+At.cols,"≈",o);let E=g.artist?nh(g.artist):g.owner&&`@${g.owner}`;if(E)t[k+11]?.put(y+1,E.slice(0,At.cols-8),ut);let v=[];if(g.score>0)v.push([`★${g.score}`,ut]);if(g.variants>1)v.push([` ×${g.variants}`,o]);if(v.length>0)t[k+11]?.right(y+At.cols+1,v)}let u=i.top*s,h=i.tiles.length-(i.top+c)*s,f=[...u>0?[`↑ ${u} above`]:[],...h>0?[`↓ ${h} more`]:[]];if(f.length>0)t[r-2]?.put(0,f.join(" "),ut);if(!i.searching&&i.tiles.length===0&&!i.error)t[3]?.put(0,i.preset==="cutouts"?`no transparent cutouts of ${i.tag} on ${Vu(i)} — c searches every post, tab tries ${i.nextSite}`:`no posts of ${i.tag} on ${Vu(i)} — tab tries ${i.nextSite}`,ut);let a=t[r-1],l=ih(i);if(i.searching&&i.tiles.length===0&&!l){Un(a,n,o,{badge:"FIND",lead:[i.preset==="cutouts"?"checking png headers":"fetching posts",ut],right:["esc","back"]});return}Un(a,n,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 Vd(t,e,n,r,i,o){let s=i.tiles[i.focus];if(!s)return;let c=i.shown?.id===s.key?i.shown:void 0,u=[_i(i,s.site,s.siteAnsi),[" ",""],[String(s.id),ce],[" ",""],rh(s)];if(s.artist)u.push([` · ${nh(s.artist)}`,""]);if(s.score>0)u.push([` · ★${s.score}`,ut]);if(c)u.push([` · ${eh(c.bytes)}`,ut]);if(s.owner)u.push([` · ${s.owner}`,ut]);if(s.origin)u.push([` · ${s.origin}`,ut]);if(c)u.push([" ",""],...Xd(c));if(t[0]?.run(0,u),s.mates.length>0)t[0]?.right(n,[["≈ ",o],[s.mates.join(" "),ut]]);if(Wd(t,3,2,n-4,r-2,i),i.shown)e.push({id:Ld+i.shown.id,path:i.shown.path,row:0,col:0,cols:n,rows:r,z:Pd});let h=ih(i);Un(t[r-1],n,o,{badge:"TRY",lead:h,keys:i.installing===void 0?[["←→","browse"],["enter","install"],...i.shown?.cut==="on"||i.shown?.cut==="off"?[["x","cut out"]]:[],["?","keys"]]:[],right:i.installing===void 0?["esc","grid"]:void 0})}var xd={grid:[["move","←↑↓→ home end pgup pgdn"],["try on","enter"],["site",`tab all, ${lt.map((t)=>t.name).join(", ")}`],["posts","c cutouts or every post"],["search","/ a tag, a post url or an id"],["your own","ctrl+v or v a picture from the clipboard · drop one on the window or paste its link"],["unfold","space a set of ×N"],["open","o the post page in a browser"],["settings","s rating, block, posts, solo, order, sets, remove bg"],["back","esc returns to preview"],["close","? esc"]],try:[["browse","←→"],["install","enter"],["cut out","x the background off or on, on an opaque picture"],["open","o the post page in a browser"],["your own","ctrl+v or v a picture from the clipboard · drop one on the window"],["grid","esc"],["close","? esc"]]};function zd(t,e,n,r,i){let o=r.panel??0,s=Math.max(...r.settings.map((l)=>l.label.length)),c=Math.max(...r.settings.map((l)=>l.choices.reduce((d,p)=>d+p.length+(l.multi?6:3),0))),u=Math.min(e-2,Math.max(28,s+c+8)),h=r.settings.length+4,f=Math.floor((e-u)/2),a=Math.max(2,Math.floor((n-h)/2));t[a]?.put(f,`╭─ settings ${"─".repeat(Math.max(0,u-13))}╮`);for(let l=a+1;l<a+h-1;l++)t[l]?.put(f,`│${" ".repeat(u-2)}│`);r.settings.forEach((l,d)=>{let p=t[a+2+d];p.put(f+3,l.label,d===o?ce:ut);let g=f+5+s,k=l.value.split(" ");l.choices.forEach((y,I)=>{let E=k.includes(y),v=l.multi&&d===o&&I===l.cursor?"4;":"",b=l.multi?` ${E?"[x]":"[ ]"} ${y} `:` ${y} `;g=p.put(g,b,E?`\x1B[${v}7;${30+r.siteAnsi}m`:v?`\x1B[4m${ut}`:ut)+1})}),t[a+h-1]?.put(f,`╰${"─".repeat(u-2)}╯`),Un(t[n-1],e,i,{badge:"SET",keys:[["↑↓","setting"],["←→","value"],["space","toggle"],["enter","save"]],right:["esc","undo"]})}function Yd(t,e,n,r,i){let o=xd[r.mode],s=Math.min(e-2,50),c=o.length+4,u=Math.floor((e-s)/2),h=Math.max(2,Math.floor((n-c)/2));t[h]?.put(u,`╭─ keys ${"─".repeat(s-9)}╮`);for(let f=h+1;f<h+c-1;f++)t[f]?.put(u,`│${" ".repeat(s-2)}│`);o.forEach(([f,a],l)=>{t[h+2+l]?.put(u+3,f,ce),t[h+2+l]?.put(u+13,a.slice(0,s-16))}),t[h+c-1]?.put(u,`╰${"─".repeat(s-2)}╯`),Un(t[n-1],e,i,{badge:"KEYS",right:["? esc","close"]})}function Bd(t,e,n){let r=e.suggest??[],i=r.map((c)=>c.count>0?String(c.count):c.palette??"0"),o=Math.max(...r.map((c)=>Ct(c.value))),s=Math.max(7,...i.map(Ct));r.forEach((c,u)=>{let h=u===e.pick,f=t[1+u];f?.run(0,[[h?"▸ ":" ",n],[c.value,h?ce+n:""]]),f?.right(2+o+2+s,[[i[u],ut]])})}function oh(t,e,n){let r=Array.from({length:n},()=>new Pr(e)),i=[],o=th(t.colors.cursor);if(e<Le.cols||n<Le.rows)return r[0]?.put(0,"ttheme find",ce+o),r[1]?.put(0,`needs ${Le.cols}×${Le.rows} — now ${e}×${n}`),r[2]?.put(0,"esc quits",ut),{lines:r.map((s)=>s.render()),images:i};if(t.mode==="try")Vd(r,i,e,n,t,o);else Cd(r,i,e,n,t,o);if(t.mode==="grid"&&t.editing!==void 0&&t.suggest?.length){for(let s=1;s<n-1;s++)r[s]=new Pr(e);return Bd(r,t,o),{lines:r.map((s)=>s.render()),images:[]}}if(t.help||t.panel!==void 0){let s=t.mode==="try"?i:[];for(let c=0;c<n;c++)r[c]=new Pr(e);if(t.help)Yd(r,e,n,t,o);else zd(r,e,n,t,o);return{lines:r.map((c)=>c.render()),images:s}}return{lines:r.map((s)=>s.render()),images:i}}var Dd=new Set(["comic","4koma","monochrome","greyscale","sketch","lineart","speech_bubble"]),tm=new Set(["scenery","landscape","scenic","no_humans","wide_shot","very_wide_shot"]),em=0.04,nm=0.1,rm=0.05,im=4096;function om(t){return new Set(t.cutouts.split(/\s+/).map((e)=>e.replace(/^~/,"")).filter(Boolean))}function sm(t,e,n,r=0){let{site:i,post:o}=t,s=new Set(o.tags),c=[...om(i)].some((f)=>s.has(f)),u=Math.min(o.width,o.height),h=o.width>0&&o.height>0?o.width/o.height/(e.w/e.h):1;return(o.solo?2:0)+([...Dd].some((f)=>s.has(f))?-3:0)+([...tm].some((f)=>s.has(f))?-1.5:0)+2*Math.min(1,u/e.h)+(c?1.5:-Math.min(1.5,Math.abs(Math.log(h))))+(n>0?1.5*Math.log1p(Math.max(0,o.score))/Math.log1p(n):0)+2*r}function Kr(t,e,n=new Map){let r=new Map;for(let{site:i,post:o}of t)r.set(i,Math.max(r.get(i)??0,o.score));return t.map((i,o)=>({pick:i,at:o,score:sm(i,e,r.get(i.site)??0,n.get(i.post))})).sort((i,o)=>o.score-i.score||i.at-o.at).map(({pick:i})=>i)}function ch(t){let e=new Map;for(let r of t)e.set(r.site,[...e.get(r.site)??[],r]);let n=[];for(let r=0;n.length<t.length;r++)for(let i of e.values()){let o=i[r];if(o)n.push(o)}return n}function Ci(t){let e=t/255;return e<=0.04045?e/12.92:((e+0.055)/1.055)**2.4}function sh(t,e,n){let[r,i,o]=[Ci(t),Ci(e),Ci(n)],s=Math.cbrt(0.4122214708*r+0.5363325363*i+0.0514459929*o),c=Math.cbrt(0.2119034982*r+0.6806995451*i+0.1073969566*o),u=Math.cbrt(0.0883024619*r+0.2817188376*i+0.6299787005*o);return[0.2104542553*s+0.793617785*c-0.0040720468*u,1.9779984951*s-2.428592205*c+0.4505937099*u,0.0259040371*s+0.7827717662*c-0.808675766*u]}function uh(t,e){let n=e.map((s)=>sh(...Rt(s))).filter(([,s,c])=>Math.hypot(s,c)>=em);if(n.length===0)return 0;let r=Math.max(1,Math.floor(Math.sqrt(t.width*t.height/im))),i=n.map(()=>0),o=0;for(let s=0;s<t.height;s+=r)for(let c=0;c<t.width;c+=r){let u=(s*t.width+c)*4;if(t.data[u+3]<128)continue;o++;let[h,f,a]=sh(t.data[u],t.data[u+1],t.data[u+2]);n.forEach(([l,d,p],g)=>{if(Math.hypot(h-l,f-d,a-p)<nm)i[g]=i[g]+1})}if(o===0)return 0;return i.reduce((s,c)=>s+Math.min(1,c/o/rm),0)/n.length}import{execFileSync as cm,spawn as um}from"node:child_process";import{existsSync as Vt,mkdirSync as Qn,readFileSync as ve,rmSync as Vi,utimesSync as hm,writeFileSync as Xe}from"node:fs";import{homedir as Ar}from"node:os";import{dirname as qn,join as mt}from"node:path";var fm={ghostty:wn,kitty:$n,alacritty:pn,wezterm:Pn,iterm2:bn,"windows-terminal":Kn,warp:Ln},hh="ttheme-default";function Ce(t=process.env.TTHEME_ITERM_SUITE??"com.googlecode.iterm2"){let e=(n,r)=>cm(n,r,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();return{read:()=>{try{return process.platform==="darwin"?e("defaults",["read",t,"Default Bookmark Guid"])||void 0:void 0}catch{return}},write:(n)=>{if(process.platform==="darwin")e("defaults",["write",t,"Default Bookmark Guid","-string",n])},running:()=>{try{return e("pgrep",["-x","iTerm2"])!==""}catch{return!1}}}}function ue(t){return t.off?void 0:Ve(t)}function Zn(t,e){if(!t.terminals.includes("iterm2"))return t;let n=e.read();return n&&!n.startsWith("ttheme-")?{...t,itermBase:n}:t}function _n(t,e){if(!t.terminals.includes("iterm2"))return!1;let n=e.read(),r=ue(t)?hh:n===hh?t.itermBase:void 0;if(!r||r===n)return!1;return e.write(r),!0}function Kt(){return process.env.XDG_CONFIG_HOME??mt(Ar(),".config")}function fh(t){return mt(t,"Library","Application Support","iTerm2","DynamicProfiles","ttheme.json")}function ah(t){return mt(t,"ttheme","installed.json")}function xt(t){let e=ah(t);if(!Vt(e))throw Error(`nothing installed yet at ${e} — run \`ttheme init\` first`);let n=JSON.parse(ve(e,"utf8"));if(!Array.isArray(n?.palettes)||!Array.isArray(n.terminals))throw Error(`${e} has no palettes or terminals`);return{terminals:n.terminals.filter((r)=>$r.includes(r)),...n.startup?{startup:n.startup}:{},...n.off?{off:!0}:{},...n.itermBase?{itermBase:n.itermBase}:{},...n.wtHome?{wtHome:n.wtHome}:{},...n.wtProfile?{wtProfile:n.wtProfile}:{},palettes:n.palettes}}function Xn(t,e){let n=ah(t);Qn(qn(n),{recursive:!0}),Xe(n,`${JSON.stringify(e,null,2)}
|
|
133
|
+
`)}function Wn(t,e){return{name:t.name,group:t.group,...t.native?{native:t.native}:{},lead:t.lead===!0,order:t.order,...t.default?{role:"default"}:{},ansiSource:t.ansiSource,...t.booru?{booru:t.booru}:{},...t.booruSites?{booruSites:t.booruSites}:{},background:t.background,foreground:t.foreground,cursor:t.cursor,selectionBackground:t.selection,ansi:t.ansi,signature:t.signature,signatureSlots:t.signatureSlots,font:e.font,ghostty:{...e.shader?{shader:e.shader}:{},iconGhost:t.cursor,iconScreen:[t.cursor,t.selection,t.background]},waive:t.waived??[]}}function lh(t,e){let n=new Map(t.palettes.map((o)=>[o.name,o])),r=e.filter((o)=>!n.has(o));if(r.length>0)throw Error(`not in the catalog: ${r.join(", ")} — ${Qi(He(t.palettes),r)}`);let i=e.flatMap((o)=>{let s=Wu(n.get(o));return s.length>0?[`${o}: ${s.join(", ")}`]:[]});if(i.length>0)throw Error(`these palettes fail the contrast gate:
|
|
134
134
|
${i.join(`
|
|
135
|
-
`)}`);return t.palettes.filter((o)=>
|
|
135
|
+
`)}`);return t.palettes.filter((o)=>e.includes(o.name))}function gh(t,e){let n=t==="wezterm"?"colors":"themes";return(fm[t].emit?.(e)??[]).flatMap((r)=>{let[,i,o]=r.path.split("/");return i===n&&o!==void 0?[{file:o,content:r.content}]:[]})}function Tr(t){return process.platform==="darwin"?mt(t,".warp","themes"):mt(process.env.XDG_DATA_HOME??mt(t,".local","share"),"warp-terminal","themes")}function Jr(t,e,n){if(t==="warp")return Tr(n);return mt(e,t,t==="wezterm"?"colors":"themes")}function am(t,e){return process.platform==="darwin"?mt(t,".warp","settings.toml"):mt(e,"warp-terminal","settings.toml")}var lm='"dark"',gm="setTimeout(() => { const fs = require('node:fs'); const [file, next, seen] = process.argv.slice(-3); if (fs.readFileSync(file, 'utf8') === seen) fs.writeFileSync(file, next) }, 1500)";function dm(t,e,n,r){let i=am(e,t);if(!Vt(i))return;let o=mt(t,"ttheme","warp.base"),s=ve(i,"utf8"),c=du(s),u=c?.includes('path = "ttheme-')===!0,h;if(n){if(!u&&!Vt(o))Qn(qn(o),{recursive:!0}),Xe(o,c??"");h=mu(n)}else{if(!u)return;h=Vt(o)&&ve(o,"utf8")||lm,Vi(o,{force:!0})}let f=pu(s,h);if(f===s)return;if(r)um(process.execPath,["-e",gm,i,f,s],{detached:!0,stdio:"ignore"}).unref();else Xe(i,f);return i}function dh(t){return mt(t,"ttheme","kitty.py")}function xi(t,e){let n=mt(e,".wezterm.lua");return Vt(n)?n:mt(t,"wezterm","wezterm.lua")}function mm(t){return mt(t,"Microsoft","Windows Terminal","Fragments","ttheme","ttheme.json")}function pm(t){return[mt(t,"Packages","Microsoft.WindowsTerminal_8wekyb3d8bbwe","LocalState","settings.json"),mt(t,"Packages","Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe","LocalState","settings.json"),mt(t,"Microsoft","Windows Terminal","settings.json")].filter((e)=>Vt(e))}function wm(t){for(let e of t){let n=/"defaultProfile"\s*:\s*"(\{[0-9a-fA-F-]+\})"/.exec(ve(e,"utf8"))?.[1];if(n)return n}return}function Ve(t){return t.startup&&t.palettes.includes(t.startup)?t.startup:t.palettes[0]}function bm(t,e,n){if(t==="ghostty")return{file:mt(e,"ghostty","config"),body:iu(mt(e,"ttheme"),n)};return{file:mt(e,"kitty","kitty.conf"),body:fu(n,dh(e))}}function zi(t){return mt(t,"alacritty","alacritty.toml")}function $m(t,e){return e?mt(t,"alacritty","themes",`${e}.toml`):void 0}function mh(t,e,n,r,i){let o=ke(t),s=n.map((h)=>Wn(h,e)),c=new Map;for(let h of s){let f=pc(o,h.name,i);if(f)c.set(h.name,f)}let u=new Set(He(n).map((h)=>h.name));return Bo(s.filter((h)=>u.has(h.name)),c,s.find((h)=>h.name===ue(r)),r.itermBase)}function xe(t,e=Ar()){let n=xt(t);if(!n.terminals.includes("iterm2"))return;let r=Pt(t),i=fh(e);Qn(qn(i),{recursive:!0}),Xe(i,mh(t,r,lh(r,n.palettes),n,e))}function Cn(t,e,n,r=Ar()){let i=lh(e,n.palettes),o=[],s=(h,f)=>{if(o.push(h),Vt(h)&&ve(h,"utf8")===f)return!1;return Qn(qn(h),{recursive:!0}),Xe(h,f),!0},c=ue(n);for(let h of n.terminals){if(h==="iterm2"){s(fh(r),mh(t,e,i,n,r));continue}if(h==="windows-terminal"){if(n.wtHome){let p=pm(n.wtHome),g=i.map((y)=>Wn(y,e)),k=Li(g,n.wtProfile??wm(p),c);if(s(mm(n.wtHome),k)){let y=new Date;for(let I of p)hm(I,y,y)}}continue}let f=c!==void 0&&h==="warp"&&!Vt(mt(Tr(r),`ttheme-${c}.yaml`)),a=h==="warp"?dm(t,r,c,f):void 0;for(let p of i)for(let{file:g,content:k}of gh(h,Wn(p,e)))s(mt(Jr(h,t,r),g),k);if(h==="warp"){if(a)o.push(a);continue}if(h==="wezterm"){let p=mt(t,"ttheme","wezterm.lua");s(p,$u({path:p,colors:Jr("wezterm",t,r),backgrounds:ke(t),...c?{startup:c}:{},palettes:i.map((y)=>Wn(y,e))}));let g=xi(t,r),k=Mr(Vt(g)?ve(g,"utf8"):"",au(p));if(k!==void 0)s(g,k);continue}if(h==="alacritty"){let p=zi(t),g=Er(Vt(p)?ve(p,"utf8"):"",$m(t,c));if(g!==void 0)s(p,g);continue}if(h==="kitty")s(dh(t),Do({themes:Jr("kitty",t,r),backgrounds:ke(t)}));let{file:l,body:d}=bm(h,t,c);s(l,Rn(Vt(l)?ve(l,"utf8"):"",d))}let u=mt(t,"ttheme","palettes.zsh");return Qn(qn(u),{recursive:!0}),Xe(u,Ri(i,c,n.terminals)),o.push(u),Vi(`${u}.zwc`,{force:!0}),o}function Yi(t,e,n,r,i=Ar()){let o=[];for(let s of n)for(let c of e.palettes.filter((u)=>r.includes(u.name)))for(let{file:u}of gh(s,Wn(c,e))){let h=mt(Jr(s,t,i),u);if(Vt(h))Vi(h,{force:!0}),o.push(h)}return o}import{mkdirSync as kh,readFileSync as Eh,writeFileSync as Mh}from"node:fs";import{dirname as yh}from"node:path";import{isMainThread as ym,parentPort as vh,Worker as vm}from"node:worker_threads";var km=/(?:^|[^0-9a-f])([0-9a-f]{32})(?:[^0-9a-f]|$)/i,Em=[[/yande\.re\/post\/show\/(\d+)/,"yande"],[/konachan\.(?:com|net)\/post\/show\/(\d+)/,"konachan"],[/danbooru\.donmai\.us\/(?:posts|post\/show)\/(\d+)/,"danbooru"]];function Bi(t){let e=/(\d+)_p(\d+)/.exec(t.source);return[...t.md5?[`md5:${t.md5}`]:[],...e&&t.source.includes("pximg")?[`pixiv:${e[1]}_p${e[2]}`]:[]]}function ph(t,e){let n=km.exec(e.source)?.[1]?.toLowerCase();return[`post:${t.key}:${e.id}`,...e.md5?[`md5:${e.md5}`]:[],...n&&n!==e.md5?[`md5:${n}`]:[],...Em.flatMap(([r,i])=>{let o=r.exec(e.source)?.[1];return o?[`post:${i}:${Number(o)}`]:[]}),...e.family?[`family:${t.key}:${e.family}`]:[]]}function wh(t,e){let n=t.owner||t.artist;return n!==""&&n===(e.owner||e.artist)&&t.width===e.width&&t.height===e.height}function bh(t){let r=[];for(let o=0;o<8;o++){let s=Math.floor(o*t.height/8),c=Math.max(s+1,Math.floor((o+1)*t.height/8));for(let u=0;u<9;u++){let h=Math.floor(u*t.width/9),f=Math.max(h+1,Math.floor((u+1)*t.width/9)),a=0;for(let l=s;l<c;l++)for(let d=h;d<f;d++){let p=(l*t.width+d)*4,g=t.data[p+3]/255,k=0.299*t.data[p]+0.587*t.data[p+1]+0.114*t.data[p+2];a+=k*g+255*(1-g)}r.push(a/((f-h)*(c-s)))}}let i=0n;for(let o=0;o<8;o++)for(let s=0;s<8;s++)i=i<<1n|(r[o*9+s]>r[o*9+s+1]?1n:0n);return i.toString(16).padStart(16,"0")}function Mm(t,e){let n=BigInt(`0x${t}`)^BigInt(`0x${e}`),r=0;while(n>0n)r+=Number(n&1n),n>>=1n;return r}function $h(t,e){if(t.width<=0||t.height<=0||e.width<=0||e.height<=0)return!1;return Math.abs(Math.log(t.width/t.height/(e.width/e.height)))<0.01&&Mm(t.hash,e.hash)<=2}var Sm={thumb:"tile",match:"tile",show:"view",backdrop:"view"};function Fm(t){let e=rc(new Uint8Array(Eh(t.from)),Re);if(t.job==="backdrop")return vc(t.home,t.colors,t.tone,e,{...t.origin,bytes:new Uint8Array(Eh(t.source))},t),0;if(t.job==="match")return{match:uh(e,t.colors),hash:bh(e)};if(t.job==="thumb")return kh(yh(t.to),{recursive:!0}),Mh(t.to,Qe(oc(e,t.width,t.height))),0;let n=yn(e);return kh(yh(t.to),{recursive:!0}),Mh(t.to,Qe(mc(e,t.colors,t.tone,t.width,t.height))),n}function Im(t){t.on("message",(e)=>{try{t.postMessage({id:e.id,value:Fm(e)})}catch(n){t.postMessage({id:e.id,error:n instanceof Error?n.message:String(n)})}})}class Sh{worker;next=1;waiting=new Map;send(t){let e=this.next++;return new Promise((n,r)=>{let i=this.open();this.waiting.set(e,{ok:n,no:r}),i.ref(),i.postMessage({...t,id:e})})}close(){this.worker?.terminate(),this.worker=void 0,this.drop(Error("renderer closed"))}open(){if(this.worker)return this.worker;let t=new vm(import.meta.filename);t.unref(),t.on("message",({id:n,value:r,error:i})=>{let o=this.waiting.get(n);if(this.waiting.delete(n),this.waiting.size===0)t.unref();if(i!==void 0)o?.no(Error(i));else o?.ok(r)});let e=(n)=>{if(this.worker===t)this.worker=void 0;this.drop(n instanceof Error?n:Error("renderer stopped"))};return t.on("error",e),t.on("exit",()=>e(void 0)),this.worker=t,t}drop(t){for(let e of this.waiting.values())e.no(t);this.waiting.clear()}}class Di{lines=new Map;run(t){let e=Sm[t.job],n=this.lines.get(e);if(!n)n=new Sh,this.lines.set(e,n);return n.send(t)}close(){for(let t of this.lines.values())t.close();this.lines.clear()}}if(!ym&&vh)Im(vh);import{connect as Nm,createServer as Hm}from"node:net";var Om=20,Fh=22;function to(t){let e=new Uint8Array(t.reduce((r,i)=>r+i.length,0)),n=0;for(let r of t)e.set(r,n),n+=r.length;return e}function jm(t,e=Om){let n=t.subarray(5);if(t[0]!==Fh||n.length<2)return[t];let r=Math.max(1,Math.min(e,n.length-1)),i=(o)=>to([Uint8Array.from([t[0],t[1],t[2],o.length>>8,o.length&255]),o]);return[i(n.subarray(0,r)),i(n.subarray(r))]}function Rm(t,e,n,r){let i=Nm(n,e,()=>{i.setNoDelay(!0),t.write(`HTTP/1.1 200 Connection Established\r
|
|
136
136
|
\r
|
|
137
|
-
`);let o=r,s=!1,c=(u)=>{if(s){i.write(u);return}if(o=
|
|
137
|
+
`);let o=r,s=!1,c=(u)=>{if(s){i.write(u);return}if(o=to([o,u]),o.length<5)return;let h=o[3]*256+o[4];if(o[0]!==Fh){s=!0,i.write(o);return}if(o.length<5+h)return;s=!0;let[f,a]=jm(o.subarray(0,5+h));i.write(f),setTimeout(()=>{if(a)i.write(a);i.write(o.subarray(5+h))},10)};if(t.on("data",c),o.length>0){let u=o;o=new Uint8Array(0),c(u)}i.pipe(t)});i.on("error",()=>t.destroy()),i.on("close",()=>t.destroy()),t.on("error",()=>i.destroy()),t.on("close",()=>i.destroy())}function Gm(t){t.setNoDelay(!0);let e=new Uint8Array(0),n=(r)=>{e=to([e,r]);let i=Buffer.from(e).toString("latin1"),o=i.indexOf(`\r
|
|
138
138
|
\r
|
|
139
|
-
`);if(o===-1)return;t.off("data",
|
|
139
|
+
`);if(o===-1)return;t.off("data",n);let s=/^CONNECT ([^ :]+):(\d+)/.exec(i);if(!s){t.end(`HTTP/1.1 405 Method Not Allowed\r
|
|
140
140
|
\r
|
|
141
|
-
`);return}
|
|
142
|
-
`)}class Ph{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(Bn.map((t)=>[t.name,Lm(t,process.env[t.name])]));direction=1;prefetching=0;inflight=new Map;owners=new Map;probed=new Map;unsaved=new Set;thumbQueue=[];thumbing=0;clarity=new Map;renders=new Yi;sent=new Map;placed=new Map;current;fetch;settle;partial;suggestTimer;suggesting;input="";typed="";grabber=new Ai((t)=>this.write(t),(t)=>void this.got(t));featureWait;noticeTimer;peekTimer;peeked;attaching;probeWait;done;dirty=!1;unblock=!1;scratch=Hm(fn(Rm(),"ttheme-find-"));home;catalog;entry;constructor(t,n,e,r){this.home=t,this.catalog=n,this.entry=e,this.tone=hr(e,e.signatureSlots),this.view={palette:e.name,tag:r,site:this.tabName,siteAnsi:this.tabAnsi,nextSite:this.nextTabName,preset:this.setting("TTHEME_FIND_POSTS")==="all"?"all":"cutouts",order:vh(this.setting("TTHEME_FIND_ORDER")),solo:this.setting("TTHEME_FIND_SOLO")==="on",rating:gr(this.setting("TTHEME_FIND_RATING")),block:lr(this.setting("TTHEME_FIND_BLOCK")),sets:this.setting("TTHEME_FIND_SETS")==="show"?"show":"fold",unblocked:process.env.TTHEME_FIND_PROXY!==void 0,settings:Bn.map((i)=>({label:i.label,choices:[...i.choices],value:this.setting(i.name),multi:i.multi&&{none:i.multi.none},cursor:0})),colors:{cursor:e.cursor,selection:e.selection,ansi:e.ansi},tiles:[],installed:[],checked:0,total:0,searching:r!=="",focus:0,top:0,mode:"grid",help:!1,editing:r===""?"":void 0},this.board=Ar(this.boardKey,r!==""),this.boards.set(this.board.key,this.board)}get signal(){return this.session.signal}get site(){return this.tab===0?void 0:gt[this.tab-1]}get sites(){return this.site?[this.site]:gt}get tabName(){return this.site?.name??"all"}get tabAnsi(){return this.site?.ansi??Jm}get nextTabName(){let t=(this.tab+1)%(gt.length+1);return t===0?"all":gt[t-1].name}frame(){return{w:this.cols*(this.cell.w||10),h:this.rows*(this.cell.h||20)}}setting(t){return this.values.get(t)}get boardKey(){return`${this.site?.key??"all"}|${this.view.preset}|${this.view.order}`}origPath(t,n,e){return fn(yn(t),"orig",`${n}.${e}`)}previewPath(t){return fn(yn(t.site),"thumb",`${Hh(t.post)}.${Ie(t.post.preview)}`)}tileOf(t,n){let{site:e,post:r}=t,i=on(e,r.id),o=Oe(r)??r;return{id:r.id,key:i,site:e.name,siteAnsi:e.ansi,width:o.width,height:o.height,reduced:o!==r,owner:r.owner,artist:e===Ir?Fu(r.source):r.artist,score:r.score,variants:n,origin:Mi(r.source),mates:this.owners.get(e.key)?.get(r.owner)??[],thumb:this.thumbPath.get(i)}}show(){let t=this.view,n=this.board;t.tiles=n.groups.flatMap((e)=>e.open?e.posts.map((r)=>this.tileOf(r,0)):[this.tileOf(e.posts[0],e.posts.length)]),t.checked=n.checked,t.total=n.total,t.searching=n.searching,t.note=n.note,t.focus=Math.max(0,Math.min(n.focus,t.tiles.length-1)),t.top=n.top}syncSite(){let t=this.view;t.site=this.tabName,t.siteAnsi=this.tabAnsi,t.nextSite=this.nextTabName}async run(){let{stdin:t,stdout:n}=process;t.setRawMode(!0),t.resume(),t.on("data",this.onData),n.on("resize",this.onResize),this.write("\x1B[?25l\x1B[?7l\x1B[H\x1B[K\x1B[2H\x1B[J\x1B[H");let e=new Promise((s)=>{this.done=s}),r=setInterval(this.onClock,250),i=await this.probe();if(i){if(this.cell=i,this.view.tag)this.search()}else this.view.searching=!1,this.view.error="this terminal does not report its cell size — find needs kitty graphics";await this.features(),this.grabber.start(),this.write("\x1B[?1004h"),this.peek(),this.draw();let o=await e;return this.grabber.stop(),this.write("\x1B[?1004l"),this.attaching?.abort(),clearTimeout(this.noticeTimer),clearTimeout(this.peekTimer),this.session.abort(),this.fetch?.abort(),clearTimeout(this.settle),clearTimeout(this.partial),this.quietSuggest(),clearInterval(r),t.off("data",this.onData),n.off("resize",this.onResize),this.write("\x1B_Ga=d,d=A,q=2\x1B\\\x1B[H\x1B[K\x1B[2H\x1B[J\x1B[H"),t.setRawMode(!1),t.pause(),this.saveProbes(),this.renders.close(),xi(this.scratch,{recursive:!0,force:!0}),Ac(),o}write(t){process.stdout.write(t)}get saved(){return this.view.saved}finish(t){this.done?.(t===2&&this.saved?0:t)}probe(){return new Promise((t)=>{let n=setTimeout(()=>{this.probeWait=void 0,t(null)},1000);this.probeWait=(e)=>{clearTimeout(n),this.probeWait=void 0,t(e)},this.write(Xu)})}onData=(t)=>{this.input+=t.toString("utf8");for(let e=Qi(this.input);e;e=Qi(this.input))this.input=e.rest,this.probeWait?.(e.cell);if(this.probeWait)return;let n=Ru(this.input);if(this.input=n.pending,this.view.editing===void 0&&n.keys.length>8&&/^(?:\/|~\/|file:|https?:)/.test(n.keys))this.pasted(n.keys),n.keys="";this.typed+=n.keys;for(let e of n.events)this.inbound(e);if(clearTimeout(this.partial),zm(this.typed)){this.partial=setTimeout(this.flushKeys,Wm);return}this.flushKeys()};flushKeys=()=>{let t=qu(this.typed);this.typed="";for(let n of t)this.key(n)};features(){if(process.env.TMUX)return Promise.resolve();return new Promise((t)=>{let n=setTimeout(()=>{this.featureWait=void 0,t()},500);this.featureWait=()=>{clearTimeout(n),this.featureWait=void 0,t()},this.write("\x1B[?5522$p\x1B]72;t=q\x1B\\\x1B[c")})}inbound(t){if(t.kind==="mode"){if(t.mode===5522)this.grabber.clipboard=t.value!==0&&t.value!==4;return}if(t.kind==="attributes"){this.featureWait?.();return}if(t.kind==="osc"){if(t.code==="72"&&t.meta.t==="q"){this.grabber.drops=!0;return}this.grabber.take(t);return}this.pasted(t.text)}pasted(t){let n=this.view;if(n.editing!==void 0&&t.trim()!==""&&!this.picture(t)){n.editing+=t.replace(/[\r\n]+/g," "),this.suggest(),this.draw();return}if(n.installing!==void 0||n.asking!==void 0||n.panel!==void 0||n.help)return;if(t.trim()===""){this.fromClipboard();return}this.attach(t)}picture(t){let n=t.trim();if(/^https?:\/\/\S+$/i.test(n))return!dr(n,this.site??gt[0]);return Fr(n).length>0}async got(t){if(t.kind==="error"){this.notice(t.message);return}if(t.kind==="text"){if(t.text.trim()===""){this.notice(`no picture on the clipboard — ${Ih}`);return}this.pasted(t.text);return}await this.bring(()=>yr(t.bytes,t.source))}notice(t,n=Qm){let e=this.view;e.error=t,clearTimeout(this.noticeTimer),this.noticeTimer=setTimeout(()=>{if(e.error===t)e.error=void 0,this.draw()},n),this.draw()}async peek(){let t=this.view,n;try{n=await ju()}catch{return}if(!n||n.stamp===this.peeked)return;if(this.peeked=n.stamp,!n.picture||t.installing!==void 0||t.asking!==void 0)return;t.hint=`picture on the clipboard · ${qm} uses it`,clearTimeout(this.peekTimer),this.peekTimer=setTimeout(()=>{t.hint=void 0,this.draw()},Zm),this.draw()}async fromClipboard(){let t=this.view;if(Ji()){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 Hu(fn(this.scratch,`clipboard-${Date.now()}.png`))}catch(r){this.notice(`could not read the clipboard: ${Dn(r)}`);return}if(clearTimeout(this.peekTimer),t.hint=void 0,"image"in n){await this.bring(async(r)=>({...await Ki(n.image,r),source:"clipboard"}));return}let e=n.text.trim();if(!e){this.notice(`no picture on the clipboard — ${Ih}`);return}if(this.picture(e)){await this.attach(e);return}if(t.editing===void 0)t.editing="";this.pasted(e)}async attach(t){let n=t.trim();if(/^https?:\/\//i.test(n)){let i=dr(n,this.site??gt[0]);if(i){await this.jump(i.site,i.id);return}}let[e,...r]=Fr(n).sort((i,o)=>Number(!Fh.test(i))-Number(!Fh.test(o)));if(!e){this.notice("nothing to use in that — drop a picture, or paste one or its link");return}await this.bring((i)=>Ki(e,i),r.length)}async bring(t,n=0){let e=this.view;this.attaching?.abort();let r=new AbortController;this.attaching=r,e.error=void 0,e.saved=void 0,e.note="reading the picture…",this.draw();let i;try{i=await t(AbortSignal.any([r.signal,this.signal]))}catch(g){if(!r.signal.aborted)e.note=void 0,this.notice(Dn(g),8000);return}if(r.signal.aborted)return;e.note=n>0?`the first picture of ${n+1} — drop one at a time to try the others`:void 0,this.quietSuggest(),e.editing=void 0,e.suggest=void 0,e.pick=void 0;let o=Nu(i.bytes);Iu(o,i.source);let s=this.origPath(Ir,o,i.ext);_e(Jr(s),{recursive:!0}),Ce(s,i.bytes);let c=Gm(s).href,u={id:o,file:c,width:i.width,height:i.height,ext:i.ext,preview:c,owner:"",artist:"",score:0,rating:"s",md5:Gh("md5").update(i.bytes).digest("hex"),source:i.source,tags:[],solo:void 0,family:0,smaller:[]},h={site:Ir,post:u},f=this.previewPath(h);_e(Jr(f),{recursive:!0}),Ce(f,i.bytes),++this.gen,this.current=void 0,e.shown=void 0;let a=Ar(`local|post:${o}`,!1);this.board=a,this.boards.set(a.key,a),this.single(a,h)}single(t,n){t.searching=!1,this.posts.set(on(n.site,n.post.id),n),t.groups=[{posts:[n],open:!1}],t.checked=1,t.total=1,this.thumbQueue.push(n),this.thumbs(),this.view.mode="try",this.show(),this.select(),this.draw()}onClock=()=>{let t=this.sites.reduce((r,i)=>Mn(i)>Mn(r)?i:r),n=Math.ceil((Mn(t)-Date.now())/1000),e=n>0?n:void 0;if(e!==this.view.waiting)this.view.waiting=e,this.view.slow=t.name,this.draw()};onResize=()=>{if(this.cols=process.stdout.columns||this.cols,this.rows=process.stdout.rows||this.rows,this.scroll(),this.view.mode==="try"&&this.current)this.reveal();this.pump(),this.draw()};key(t){let n=this.view;if(t==="ctrl-c"){this.finish(2);return}if(n.installing!==void 0)return;if(n.asking!==void 0){this.askKey(t);return}if(t==="focus-in"){this.peek();return}if(t==="focus-out"||t==="nop")return;if((t==="ctrl-v"||t==="alt-v")&&n.panel===void 0){this.fromClipboard();return}if(n.editing!==void 0){this.editKey(t);return}if(n.panel!==void 0){this.panelKey(t);return}if(n.help){if(t==="?"||t==="esc")n.help=!1,this.draw();return}if(this.cols<Ln.cols||this.rows<Ln.rows){if(t==="esc")this.finish(2);return}if(t==="?"){n.help=!0,this.draw();return}if(n.mode==="try"){this.tryKey(t);return}this.gridKey(t)}gridKey(t){let n=this.view,{perRow:e,rowsVis:r}=_n(this.cols,this.rows),o={left:-1,right:1,up:-e,down:e,pgup:-e*r,pgdn:e*r,home:-n.focus,end:n.tiles.length}[t];if(o!==void 0){this.focus(n.focus+o);return}if(t==="enter"&&n.tiles[n.focus]){n.mode="try",n.error=void 0,this.select();return}if(t==="v"){this.fromClipboard();return}if(t==="c"){n.preset=n.preset==="cutouts"?"all":"cutouts",this.turn();return}if(t==="tab"){this.tab=(this.tab+1)%(gt.length+1),this.syncSite(),this.turn();return}if(t==="/"){n.editing="",this.draw();return}if(t===" "){this.unfold();return}if(t==="o"){this.openPage();return}if(t==="s"){n.panel=0,this.draw();return}if(t==="esc")this.finish(2)}panelKey(t){let n=this.view,e=n.panel??0,r=n.settings[e];if(t==="up"||t==="down"){n.panel=Math.max(0,Math.min(n.settings.length-1,e+(t==="up"?-1:1))),this.draw();return}if((t==="left"||t==="right")&&r){let i=t==="left"?-1:1;if(r.multi)r.cursor=(r.cursor+i+r.choices.length)%r.choices.length;else{let o=r.choices.indexOf(r.value);r.value=r.choices[(o+i+r.choices.length)%r.choices.length]}this.draw();return}if(t===" "&&r?.multi){let i=r.value.split(" "),o=r.choices.filter((c,u)=>u===r.cursor?!i.includes(c):i.includes(c)),s=r.multi.none;if(o.length>0||s!==void 0)r.value=o.length>0?o.join(" "):s,this.draw();return}if(t==="esc"){n.settings.forEach((i,o)=>{i.value=this.setting(Bn[o]?.name??"")}),n.panel=void 0,this.draw();return}if(t==="enter"||t==="alt-c")n.panel=void 0,this.adopt()}adopt(){let t=this.view,n=Bn.map((r)=>this.setting(r.name));t.settings.forEach((r,i)=>{let o=Bn[i];if(o)this.values.set(o.name,r.value)});let e=Bn.filter((r,i)=>this.setting(r.name)!==n[i]);if(e.length===0){this.draw();return}this.save(e),t.rating=gr(this.setting("TTHEME_FIND_RATING")),t.block=lr(this.setting("TTHEME_FIND_BLOCK")),t.sets=this.setting("TTHEME_FIND_SETS")==="show"?"show":"fold",t.preset=this.setting("TTHEME_FIND_POSTS")==="all"?"all":"cutouts",t.order=vh(this.setting("TTHEME_FIND_ORDER")),t.solo=this.setting("TTHEME_FIND_SOLO")==="on",this.boards.clear(),this.current=void 0,t.shown=void 0,t.mode="grid",this.search()}save(t){this.store(t.map((n)=>[n.name,this.setting(n.name)]))}store(t){let n=fn(this.home,"ttheme","config.zsh");try{let e=xn(n)?Lh(n,"utf8"):"";return Ce(n,t.reduce((r,[i,o])=>eu(r,i,o),e)),!0}catch(e){return this.view.error=e instanceof Error?e.message:String(e),!1}}askKey(t){let n=this.view;if(t==="y"){if(n.asking=void 0,this.store([["TTHEME_FIND_UNBLOCK","1"]])){this.unblock=!0,this.finish(0);return}this.draw();return}if(t==="n"||t==="esc")n.asking=void 0,this.draw()}editKey(t){let n=this.view,e=n.editing??"",r=n.suggest??[];if((t==="up"||t==="down")&&r.length>0){let i=n.pick??-1,o=t==="down"?Math.min(r.length-1,i+1):i-1;n.pick=o<0?void 0:o,this.draw();return}if(t==="esc"||t==="enter")this.quietSuggest();if(t==="esc"){if(n.editing=void 0,n.tag===""){this.finish(2);return}this.draw();return}if(t==="enter"){let i=n.pick===void 0?void 0:r[n.pick],o=i?e.replace(/\S*$/,i.value):e;if(n.editing=void 0,n.suggest=void 0,n.pick=void 0,o.trim()){this.commit(o.trim());return}if(n.tag===""){this.finish(2);return}this.draw();return}if(t==="backspace"){n.editing=e.slice(0,-1),this.suggest(),this.draw();return}if(t.length===1&&t>=" ")n.editing=e+t,this.suggest(),this.draw()}quietSuggest(){clearTimeout(this.suggestTimer),this.suggesting?.abort(),this.suggesting=void 0}suggest(){this.quietSuggest();let t=this.view;t.pick=void 0;let n=/\S*$/.exec(t.editing??"")?.[0]??"";if(!Km(n)){t.suggest=void 0;return}let e=[...new Map(Au(this.catalog.palettes,this.entry,n).map((i)=>[i.booru,{value:i.booru,count:0,palette:i.name}])).values()].slice(0,_m);t.suggest=e.length>0?e:void 0;let r=new AbortController;this.suggesting=r,this.suggestTimer=setTimeout(async()=>{try{let i=await Zc(n,AbortSignal.any([this.signal,r.signal]));if(this.suggesting===r&&t.editing!==void 0){let o=new Map(i.map((c)=>[c.value,c.count])),s=new Set(e.map((c)=>c.value));t.suggest=[...e.map((c)=>({...c,count:o.get(c.value)??0})),...i.filter((c)=>!s.has(c.value))].slice(0,Cm),t.pick=t.pick!==void 0&&t.pick<e.length?t.pick:void 0,this.draw()}}catch{}},Am)}async commit(t){let n=dr(t,this.site??gt[0]);if(n){await this.jump(n.site,n.id);return}if(this.picture(t)){await this.attach(t);return}this.view.tag=t,this.boards.clear(),await this.search()}async jump(t,n){let e=++this.gen;this.tab=gt.indexOf(t)+1,this.syncSite(),this.current=void 0,this.view.shown=void 0,this.view.error=void 0;let r=Ar(`${t.key}|post:${n}`,!0);this.board=r,this.boards.set(r.key,r),this.show(),this.draw();try{let i=await vi(t,n,this.signal);if(e!==this.gen)return;if(!i){r.searching=!1,r.error=`${t.name} has no post ${n}`,this.view.error=r.error,this.show(),this.draw();return}this.single(r,{site:t,post:i})}catch(i){this.fail(e,i,t)}}async turn(){this.fetch?.abort(),this.current=void 0,this.view.shown=void 0;let t=this.boards.get(this.boardKey);if(!t){await this.search();return}this.gen++,this.board=t,this.view.error=t.error,this.show(),this.draw(),await this.pump()}unfold(){let t=this.view,n=0;for(let e of this.board.groups){let r=e.open?e.posts.length:1;if(t.focus<n+r){if(e.posts.length<2)return;e.open=!e.open,this.board.focus=n;for(let i of e.posts)if(!this.thumbPath.has(on(i.site,i.post.id)))this.thumbQueue.push(i);this.thumbs(),this.show(),this.scroll(),this.draw();return}n+=r}}openPage(){let t=this.view.tiles[this.view.focus],n=t&&this.posts.get(t.key);if(!n)return;let e=process.platform==="darwin"?"open":"xdg-open";try{Rh(e,[n.site.pageUrl(n.post.id)],{stdio:"ignore",detached:!0}).unref()}catch{}}tryKey(t){let n=this.view;if(t==="left"||t==="right"){this.direction=t==="left"?-1:1,this.focus(n.focus+this.direction);return}if(t==="o"){this.openPage();return}if(t==="x"){this.swap();return}if(t==="v"){this.fromClipboard();return}if(t==="enter"){this.install();return}if(t==="esc")this.fetch?.abort(),clearTimeout(this.settle),n.fetching=void 0,n.mode="grid",n.error=void 0,this.draw()}focus(t){let n=this.view;if(n.tiles.length===0)return;let e=Math.max(0,Math.min(n.tiles.length-1,t));if(e===n.focus)return;if(n.focus=e,this.board.focus=e,this.scroll(),this.pump(),n.mode==="try")this.select();this.draw()}scroll(){let t=this.view,{perRow:n,rowsVis:e}=_n(this.cols,this.rows),r=Math.floor(t.focus/n);if(r<t.top)t.top=r;if(r>t.top+e-1)t.top=r-e+1;this.board.top=t.top}query(t){let n=this.view,e=n.tag===this.entry.booru?Uu(this.entry,t.key):[n.tag];if(e.length===0)return;let r=e.length>1,i=n.preset==="cutouts"?t.cutouts:"",o=r&&i.includes("~"),s=[r?e.map((h)=>`~${h}`).join(" "):e[0],t.rate(this.view.rating),o?"":i,n.order==="score"?t.best:""].filter(Boolean),c=[],u=[];for(let h of s)if(Ei([...c,h].join(" "))<=t.tagBudget)c.push(h);else u.push(h);return{tags:c.join(" "),notes:[...u.length>0?[`${t.name} takes ${t.tagBudget} tags — ${u.join(" ")} left out`]:[],...o?[`${t.name} ORs the names, so cutouts are told by the file`]:[]]}}async search(){let t=++this.gen,n=Ar(this.boardKey,!0);this.board=n,this.boards.set(n.key,n),this.view.error=void 0;let e=this.sites.flatMap((o)=>{let s=this.query(o);return s?[{site:o,...s}]:[]}),r=this.sites.filter((o)=>!e.some((s)=>s.site===o)),i=[...e.flatMap(({notes:o})=>o),...r.length>0?[`${this.entry.name} has no tag on ${r.map((o)=>o.name).join(", ")}`]:[]];if(n.note=i.length>0?i.join(" · "):void 0,e.length===0)n.searching=!1;this.show(),this.draw(),this.tally(t,n,e);try{let o=await Promise.all(e.map(async(s)=>({plan:s,owners:await this.mateOwners(s.site)})));if(t!==this.gen)return;n.sources=o.flatMap(({plan:{site:s,tags:c},owners:u})=>[...Ei(c)+1<=s.tagBudget?[...u.keys()].map((h)=>({site:s,tags:`${c} user:${h}`,page:0,done:!1})):[],{site:s,tags:c,page:0,done:!1}]),this.show(),this.draw(),await this.pump()}catch(o){this.fail(t,o)}}async tally(t,n,e){let r=await Promise.allSettled(e.map(({site:i,tags:o})=>Tc(i,o,this.signal)));if(t===this.gen)n.total=r.reduce((i,o)=>i+(o.status==="fulfilled"?o.value:0),0),this.show(),this.draw()}fail(t,n,e=this.site){if(t!==this.gen||this.signal.aborted)return;this.board.error=Bi(e?.name??this.tabName,n),this.board.searching=!1,this.view.error=this.board.error,this.offer(e,n),this.show(),this.draw()}offer(t,n){if(t&&!this.view.unblocked&&Kh()&&Dn(n)==="ECONNRESET")this.view.asking=t.name}drop(t,n,e){for(let r of t.sources)if(r.site===n)r.done=!0;t.note=[t.note,Bi(n.name,e)].filter(Boolean).join(" · "),this.offer(n,e)}wants(){let{perRow:t,rowsVis:n}=_n(this.cols,this.rows);return this.view.tiles.length<(this.board.top+n+Nh)*t}need(){let{perRow:t,rowsVis:n}=_n(this.cols,this.rows);return(n+Nh)*t}live(t){return this.boards.get(t.key)===t}page(t,n,e){let r=`${t.key}|${n}|${e}`,i=this.pages.get(r);if(!i)i=Uc(t,n,e,this.signal).then((o)=>this.borrow(o)),this.pages.set(r,i),i.catch(()=>this.pages.delete(r));return i}async borrow(t){let n=t.filter((e)=>e.solo===void 0&&e.md5!=="");if(n.length>0)try{Wc(n,await Qc(n.map((e)=>e.md5),this.signal))}catch{}return t}async round(t){let n=gt.flatMap((c)=>{let u=t.sources.find((h)=>h.site===c&&!h.done);return u?[u]:[]}),e=await Promise.all(n.map(async(c)=>{try{return{source:c,posts:await this.page(c.site,c.tags,c.page)}}catch(u){if(t.sources.every((h)=>h.site===c.site)||this.signal.aborted)throw u;return this.drop(t,c.site,u),{source:c,posts:void 0}}}));if(!this.live(t))return;let r=[];for(let{source:c,posts:u}of e){if(!u)continue;c.page++,c.done=u.length<Hn;let h=t.last.get(c);for(let f of u){let a=h&&gh(h.post,f)?h.set:`set:${c.site.key}:${f.id}`;h={post:f,set:a};let g=on(c.site,f.id);if(t.seen.has(g))continue;t.seen.add(g);let d={site:c.site,post:f};if(this.eligible(d))t.kin.set(d,[a,...ah(c.site,f)]),r.push(d);else t.checked++}if(h)t.last.set(c,h)}let i=this.dedupe(t,r),o=++t.rounds,s;if(this.view.order!=="fit")s=n.length>1?eh(i):i;else{let c=Gr(i,this.frame(),this.matched),u=c.slice(0,this.need());if(await this.looks(u),!this.live(t))return;s=[...Gr(u,this.frame(),this.matched),...c.slice(u.length)]}for(let c of s)t.roundOf.set(c,o);t.queue.push(...s),this.ahead(t)}ahead(t){if(this.aheading||this.view.order!=="fit"||!this.live(t))return;let n=t.queue.slice(0,this.need()).filter((e)=>!this.looking.has(on(e.site,e.post.id)));if(n.length===0)return;this.aheading=!0,this.looks(n).then(()=>{this.aheading=!1;for(let e of new Set(n.map((r)=>t.roundOf.get(r)??0)))this.resort(t,e);this.ahead(t)})}resort(t,n){let e=t.queue.flatMap((i,o)=>t.roundOf.get(i)===n?[o]:[]),r=Gr(e.map((i)=>t.queue[i]),this.frame(),this.matched);e.forEach((i,o)=>{t.queue[i]=r[o]})}dedupe(t,n){let e=[];for(let r of n){let i=zi(r.post),o=i.map((c)=>t.same.get(c)).find(Boolean);if(!o){for(let c of i)t.same.set(c,r);e.push(r);continue}if(t.checked++,Oh(r.post)<=Oh(o.post))continue;for(let c of[...i,...zi(o.post)])t.same.set(c,r);let s=e.indexOf(o);if(s>=0){e[s]=r;continue}this.replace(t,o,r)}return e}replace(t,n,e){t.roundOf.set(e,t.roundOf.get(n)??0);let r=t.queue.indexOf(n);if(r>=0){t.queue[r]=e;return}for(let i of t.groups){let o=i.posts.indexOf(n);if(o>=0){i.posts[o]=e,this.posts.set(on(e.site,e.post.id),e),this.thumbQueue.push(e),this.thumbs();return}}}async looks(t){let n=0;await Promise.all(Array.from({length:Sh},async()=>{while(n<t.length)await this.look(t[n++])}))}look(t){let n=on(t.site,t.post.id),e=this.looking.get(n);if(!e)e=(async()=>{let r=this.previewPath(t);await this.cached(t.site,r,t.post.preview);let i=await this.renders.run({job:"match",from:r,colors:this.entry.signature});return this.looked.set(n,i),this.matched.set(t.post,i.match),i})().catch(()=>{return}),this.looking.set(n,e);return e}async pump(){let t=this.gen,n=this.board;if(this.pumping===t||n.sources.length===0)return;this.pumping=t;let e=[],r;try{n.searching=!0;while(t===this.gen){while(e.length<yh&&n.queue.length>0&&this.wants()){let s=n.queue.shift();e.push({pick:s,passed:this.vet(s)})}if(this.ahead(n),!r&&n.queue.length<yh&&n.sources.some((s)=>!s.done)&&this.wants()){let s=this.round(n).then(()=>{if(r===s)r=void 0});s.catch(()=>{}),r=s}let i=e.shift();if(!i){if(!r)break;await r,this.show(),this.draw();continue}let o=await i.passed;if(t!==this.gen)return;if(n.checked++,o)this.admit(i.pick);this.show(),this.draw()}if(t===this.gen)n.searching=!1,this.show(),this.draw()}catch(i){this.fail(t,i)}finally{if(this.saveProbes(),this.pumping===t)this.pumping=0}}eligible({site:t,post:n}){let e=Oe(n);if(!Pc(t,n,this.view.rating)||Lc(n,this.view.block).length>0||!e)return!1;if(this.view.solo&&n.solo===!1)return!1;return this.view.preset==="all"?["png","jpg","jpeg"].includes(e.ext):n.ext==="png"}async vet(t){let[n]=await Promise.all([this.passes(t),this.look(t)]);return n}async passes({site:t,post:n}){return this.view.preset==="all"||t.vouched||this.transparent(t,n)}probes(t){let n=this.probed.get(t.key);if(!n)n=Di(t,"probes.json"),this.probed.set(t.key,n);return n}async transparent(t,n){let e=this.probes(t),r=e[n.id];if(r!==void 0)return r;try{let i=(await qc(t,n.file,this.signal))?.alpha===!0;return e[n.id]=i,this.unsaved.add(t.key),i}catch{return!1}}saveProbes(){for(let t of this.unsaved){let n=gt.find((e)=>e.key===t);if(n)to(n,"probes.json",this.probes(n))}this.unsaved.clear()}admit(t){let{site:n,post:e}=t,r=this.board,i=on(n,e.id);this.posts.set(i,t);let o=r.kin.get(t)??[],s=this.looked.get(i),c=s&&{hash:s.hash,width:e.width,height:e.height},u=this.view.sets==="fold"?this.kindred(r,o,c):void 0;if(u){if(u.posts.push(t),this.register(r,u,o,c),u.open)this.thumbQueue.push(t),this.thumbs();return}let h={posts:[t],open:!1};r.groups.push(h),this.register(r,h,o,c),this.thumbQueue.push(t),this.thumbs()}kindred(t,n,e){for(let r of n){let i=t.kindred.get(r);if(i)return i}return e&&t.shapes.find((r)=>dh(r.shape,e))?.group}register(t,n,e,r){for(let i of e)if(!t.kindred.has(i))t.kindred.set(i,n);if(r)t.shapes.push({shape:r,group:n})}async mateOwners(t){let n=this.owners.get(t.key);if(n)return n;let e=kc(this.home),r=Di(t,"owners.json"),i=this.catalog.palettes.flatMap((u)=>{let h=e.get(u.name);return u.group===this.entry.group&&u.name!==this.entry.name&&h?.site===t.key?[{name:u.name,id:h.id}]:[]}),o=await Promise.all(i.map(async(u)=>{let h=r[u.id];if(h!==void 0)return{...u,owner:h};try{return{...u,owner:(await vi(t,u.id,this.signal))?.owner??""}}catch{return}})),s=new Map;for(let u of o)if(u)r[u.id]=u.owner,s.set(u.name,u.owner);to(t,"owners.json",r);let c=Kc(s);return this.owners.set(t.key,c),c}async cached(t,n,e,r){if(xn(n))return jm(n).size;let i=this.inflight.get(n);if(i)return i;let o=(async()=>{let s=await Xc(t,e,this.signal,r);return _e(Jr(n),{recursive:!0}),Ce(n,s),s.length})();this.inflight.set(n,o);try{return await o}finally{this.inflight.delete(n)}}thumbs(){while(this.thumbing<Sh&&this.thumbQueue.length>0){let t=this.thumbQueue.shift();this.thumbing++,this.thumb(t).catch(()=>{}).finally(()=>{this.thumbing--,this.thumbs()})}}async thumb(t){let{site:n,post:e}=t,r=Jt.cols*this.cell.w,i=Jt.rows*this.cell.h,o=fn(yn(n),"tile",`${Hh(e)}-${r}x${i}.png`);if(!xn(o)){let s=this.previewPath(t);await this.cached(n,s,e.preview),await this.renders.run({job:"thumb",from:s,to:o,width:r,height:i})}this.thumbPath.set(on(n,e.id),o),this.show(),this.draw()}select(){let t=this.view,n=t.tiles[t.focus];if(this.fetch?.abort(),clearTimeout(this.settle),t.fetching=void 0,!n)return;if(this.current?.key===n.key){this.reveal();return}this.settle=setTimeout(()=>void this.load(n),Tm),this.draw()}async load(t){let n=this.view,e=this.posts.get(t.key),r=e&&Oe(e.post);if(!e||!r)return;let{site:i}=e,o=this.board,s=new AbortController;this.fetch=s;try{let c=this.origPath(i,t.id,r.ext);if(!xn(c))n.fetching={id:t.key,got:0,size:0},this.draw();let u=await this.cached(i,c,r.file,(a,g)=>{if(n.fetching?.id===t.key)n.fetching={id:t.key,got:a,size:g},this.draw()});if(s.signal.aborted)return;if(n.fetching=void 0,o!==this.board)return;let h={site:i,id:t.id,key:t.key,path:c,ext:r.ext,size:u,using:"plain",failed:!1};n.preparing=t.key,this.flush();let f=await this.render(h,"plain");if(s.signal.aborted||o!==this.board)return;if(f.clear===0&&Ui()&&this.setting("TTHEME_FIND_REMOVE_BG")!=="off"){if(n.preparing=void 0,n.cutting=t.key,this.flush(),h.cut=await this.cutOut(i,t.id,c,s.signal),s.signal.aborted||o!==this.board)return;if(n.cutting=void 0,h.cut){n.preparing=t.key,this.flush();let a=await this.render(h,"cut").catch(()=>{return});if(s.signal.aborted||o!==this.board)return;if(a&&Tu(a.clear))h.using="cut";else xi(h.cut,{force:!0}),h.cut=void 0,h.failed=!0}else h.failed=!0}if(this.current=h,n.tiles[n.focus]?.key===t.key)await this.present();this.preload()}catch(c){if(!s.signal.aborted&&!this.signal.aborted)n.error=Bi(i.name,c)}finally{if(n.fetching?.id===t.key)n.fetching=void 0;if(n.preparing===t.key)n.preparing=void 0;if(n.cutting===t.key)n.cutting=void 0;this.draw()}}async cutOut(t,n,e,r){let i=fn(yn(t),"cut",`${n}.png`);if(xn(i))return i;try{return _e(Jr(i),{recursive:!0}),await Wu(e,i,r),i}catch{xi(i,{force:!0});return}}swap(){let t=this.current;if(!t?.cut||this.view.shown?.id!==t.key)return;t.using=t.using==="cut"?"plain":"cut",this.reveal()}preload(){let t=this.view;if(t.mode!=="try")return;for(let n of[t.focus+this.direction,t.focus-this.direction]){if(this.prefetching>=Um)return;let e=t.tiles[n],r=e&&this.posts.get(e.key),i=r&&Oe(r.post);if(!r||!i)continue;let{site:o,post:s}=r,c=this.origPath(o,s.id,i.ext);this.prefetching++,this.cached(o,c,i.file).then(()=>this.render({site:o,id:s.id,key:e.key,path:c,ext:i.ext,size:0,using:"plain",failed:!1},"plain")).catch(()=>{}).finally(()=>{this.prefetching--})}}async render(t,n){let e=this.cols*this.cell.w,r=this.rows*this.cell.h,i=Math.min(e,Xm),o=Math.max(1,Math.round(r*i/e)),s=fn(this.scratch,`${t.site.key}-${t.id}${n==="cut"?"c":""}-${i}x${o}.png`),c=`${t.site.key}:${t.id}:${n}`,u=this.clarity.get(c);if(u!==void 0&&xn(s))return{clear:u,path:s};let h=await this.renders.run({job:"show",from:n==="cut"?t.cut:t.path,to:s,width:i,height:o,colors:this.entry,tone:this.tone});return this.clarity.set(c,h),{clear:h,path:s}}async present(){let t=this.current;if(!t)return;let n=t.using,{clear:e,path:r}=await this.render(t,n);if(this.current!==t||t.using!==n)return;this.view.shown={id:t.key,clear:e,bytes:t.size,path:r,cut:t.cut?n==="cut"?"on":"off":t.failed?"failed":"none"}}reveal(){let t=this.view;t.preparing=this.current?.key,this.flush(),this.present().catch((n)=>{t.error=n instanceof Error?n.message:String(n)}).finally(()=>{if(t.preparing===this.current?.key)t.preparing=void 0;this.draw()})}async install(){let t=this.view,n=t.tiles[t.focus],e=this.current;if(!n||e?.key!==n.key||t.preparing!==void 0||t.shown?.id!==n.key)return;t.installing=n.key,t.error=void 0,this.flush();try{await this.renders.run({job:"backdrop",from:e.using==="cut"?e.cut:e.path,source:e.path,home:this.home,colors:this.entry,tone:this.tone,origin:{site:e.site.key,id:e.id,ext:e.ext,from:`${e.site.name} ${e.id} ${e.site.pageUrl(e.id)}`},width:this.cols*this.cell.w,height:this.rows*this.cell.h});let r=Di(e.site,"owners.json");r[e.id]=this.posts.get(e.key)?.post.owner??"",to(e.site,"owners.json",r),Vn(this.home),t.saved=`background · ${this.entry.name} ← ${e.site.name} ${e.id}`,t.installed.push(n.key),this.fetch?.abort(),clearTimeout(this.settle),t.fetching=void 0,t.mode="grid"}catch(r){t.error=r instanceof Error?r.message:String(r)}t.installing=void 0,this.draw()}draw(){if(this.dirty)return;this.dirty=!0,setImmediate(()=>{this.dirty=!1,this.flush()})}flush(){let t=th(this.view,this.cols,this.rows),n="\x1B[?2026h";t.lines.forEach((r,i)=>{n+=`\x1B[${i+1};1H\x1B[K${r}`});let e=new Set;for(let r of t.images){if(e.add(r.id),this.sent.get(r.id)!==r.path)n+=_u(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+=Cu(r),this.placed.set(r.id,i)}for(let r of this.sent.keys())if(!e.has(r))n+=zu(r),this.sent.delete(r),this.placed.delete(r);this.write(`${n}\x1B[?2026l`)}}function Kh(){if(process.versions.bun)return!0;let[t=0,n=0]=process.versions.node.split(".").map(Number);return t>22||t===22&&n>=21}async function jh(){if(!Kh())return process.stderr.write(`unblock needs node 22.21 or newer — this is ${process.versions.node}
|
|
143
|
-
`),1;let t=await
|
|
144
|
-
`),0;return s}function
|
|
145
|
-
`),0}if(
|
|
146
|
-
`),0}if(
|
|
147
|
-
`),f=!1;for(let a=0;a<h.length;a++){let
|
|
148
|
-
`){if(o)r+=
|
|
149
|
-
`){if(i&&
|
|
150
|
-
`)}var Wt=
|
|
151
|
-
`),o=0,s=t;for(let u of i){if(s<=u.length)break;s-=u.length+1,o++}for(o=Math.max(0,Math.min(i.length-1,o+
|
|
152
|
-
`),r=
|
|
153
|
-
`),i=Math.max(
|
|
154
|
-
`).map((c,u,h)=>{let f=o?o(c,u):c;return u===0?`${r}${f}`:u===h.length-1?`${i}${f}`:`${
|
|
155
|
-
`)}function
|
|
156
|
-
`),
|
|
157
|
-
`).length-1;this.output.write(Wt.cursor.move(-999,t*-1))}render(){let t=
|
|
158
|
-
`);this.output.write(s[o]),this._prevFrame=t,this.output.write(Wt.cursor.move(0,s.length-o-1));return}else if(
|
|
141
|
+
`);return}Rm(t,s[1],Number(s[2]),e.subarray(o+4))};t.on("data",n),t.on("error",()=>t.destroy())}function Ih(){let t=Hm(Gm);return new Promise((e,n)=>{t.once("error",n),t.listen(0,"127.0.0.1",()=>{e({port:t.address().port,close:()=>{t.close(),t.unref()}})})})}var Ye=[{name:"TTHEME_FIND_RATING",label:"rating",choices:In,multi:{read:mr}},{name:"TTHEME_FIND_BLOCK",label:"block",choices:je,multi:{read:pr,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"]},...qi()?[{name:"TTHEME_FIND_REMOVE_BG",label:"remove bg",choices:["on","off"]}]:[]];function Am(t,e){if(t.multi)return t.multi.read(e).join(" ")||t.multi.none;return t.choices.find((n)=>n===e)??t.choices[0]}var Tm=["fit","newest","score"];function Nh(t){return Tm.find((e)=>e===t)??"fit"}function Um(t){return t.length>=2&&!/^\d+$/.test(t)&&!t.includes("://")&&!/^[\w.]+:\d+$/.test(t)}var Hh=12,Wm=4,Qm=150,Oh=12,qm=2,Zm=150,_m=30,Xm=4000,Cm=8000,jh=/\.(png|jpe?g|gif|webp|heic|tiff?|bmp)$/i,Vm=process.platform==="win32"?"alt+v":"ctrl+v",Rh=process.platform==="darwin"?"ctrl+shift+cmd+4 copies a screenshot":"copy a picture first",xm=1280,Gh=2,zm=3,Ym=8;function Wr(t,e){return{key:t,groups:[],sources:[],queue:[],rounds:0,roundOf:new Map,last:new Map,kin:new Map,kindred:new Map,shapes:[],seen:new Set,same:new Map,checked:0,total:0,focus:0,top:0,searching:e}}function Be(t){if(!(t instanceof Error))return String(t);if(t instanceof AggregateError&&t.errors[0])return Be(t.errors[0]);if(t.cause)return Be(t.cause);let e=t.code;if(typeof e==="string")return e;let n=(t.message||t.name).split(".")[0]??"";return n.length>56?`${n.slice(0,55)}…`:n}function no(t,e){return`${t}: ${Be(e)}`}function Lh(t){return t.width*t.height}function Ph(t){return`${t.id}-${Ah("sha1").update(t.preview).digest("hex").slice(0,8)}`}function Bm(t){let e=t.lastIndexOf("\x1B");return e!==-1&&/^\[?[0-9;]*$/.test(t.slice(e+1))}function ro(t,e){try{return JSON.parse(Th(he(ye(t),e),"utf8"))}catch{return{}}}function io(t,e,n){Vn(ye(t),{recursive:!0}),xn(he(ye(t),e),`${JSON.stringify(n)}
|
|
142
|
+
`)}class Uh{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(Ye.map((t)=>[t.name,Am(t,process.env[t.name])]));direction=1;prefetching=0;inflight=new Map;owners=new Map;probed=new Map;unsaved=new Set;thumbQueue=[];thumbing=0;clarity=new Map;renders=new Di;sent=new Map;placed=new Map;current;fetch;settle;partial;suggestTimer;suggesting;input="";typed="";grabber=new Wi((t)=>this.write(t),(t)=>void this.got(t));featureWait;noticeTimer;peekTimer;peeked;attaching;probeWait;done;dirty=!1;unblock=!1;scratch=Lm(he(Km(),"ttheme-find-"));home;catalog;entry;constructor(t,e,n,r){this.home=t,this.catalog=e,this.entry=n,this.tone=lr(n,n.signatureSlots),this.view={palette:n.name,tag:r,site:this.tabName,siteAnsi:this.tabAnsi,nextSite:this.nextTabName,preset:this.setting("TTHEME_FIND_POSTS")==="all"?"all":"cutouts",order:Nh(this.setting("TTHEME_FIND_ORDER")),solo:this.setting("TTHEME_FIND_SOLO")==="on",rating:mr(this.setting("TTHEME_FIND_RATING")),block:pr(this.setting("TTHEME_FIND_BLOCK")),sets:this.setting("TTHEME_FIND_SETS")==="show"?"show":"fold",unblocked:process.env.TTHEME_FIND_PROXY!==void 0,settings:Ye.map((i)=>({label:i.label,choices:[...i.choices],value:this.setting(i.name),multi:i.multi&&{none:i.multi.none},cursor:0})),colors:{cursor:n.cursor,selection:n.selection,ansi:n.ansi},tiles:[],installed:[],checked:0,total:0,searching:r!=="",focus:0,top:0,mode:"grid",help:!1,editing:r===""?"":void 0},this.board=Wr(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:lt[this.tab-1]}get sites(){return this.site?[this.site]:lt}get tabName(){return this.site?.name??"all"}get tabAnsi(){return this.site?.ansi??Wm}get nextTabName(){let t=(this.tab+1)%(lt.length+1);return t===0?"all":lt[t-1].name}frame(){return{w:this.cols*(this.cell.w||10),h:this.rows*(this.cell.h||20)}}setting(t){return this.values.get(t)}get boardKey(){return`${this.site?.key??"all"}|${this.view.preset}|${this.view.order}`}origPath(t,e,n){return he(ye(t),"orig",`${e}.${n}`)}previewPath(t){return he(ye(t.site),"thumb",`${Ph(t.post)}.${Nn(t.post.preview)}`)}tileOf(t,e){let{site:n,post:r}=t,i=ie(n,r.id),o=On(r)??r;return{id:r.id,key:i,site:n.name,siteAnsi:n.ansi,width:o.width,height:o.height,reduced:o!==r,owner:r.owner,artist:n===Or?ju(r.source):r.artist,score:r.score,variants:e,origin:Si(r.source),mates:this.owners.get(n.key)?.get(r.owner)??[],thumb:this.thumbPath.get(i)}}show(){let t=this.view,e=this.board;t.tiles=e.groups.flatMap((n)=>n.open?n.posts.map((r)=>this.tileOf(r,0)):[this.tileOf(n.posts[0],n.posts.length)]),t.checked=e.checked,t.total=e.total,t.searching=e.searching,t.note=e.note,t.focus=Math.max(0,Math.min(e.focus,t.tiles.length-1)),t.top=e.top}syncSite(){let t=this.view;t.site=this.tabName,t.siteAnsi=this.tabAnsi,t.nextSite=this.nextTabName}async run(){let{stdin:t,stdout:e}=process;t.setRawMode(!0),t.resume(),t.on("data",this.onData),e.on("resize",this.onResize),this.write("\x1B[?25l\x1B[?7l\x1B[H\x1B[K\x1B[2H\x1B[J\x1B[H");let n=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 n;return this.grabber.stop(),this.write("\x1B[?1004l"),this.attaching?.abort(),clearTimeout(this.noticeTimer),clearTimeout(this.peekTimer),this.session.abort(),this.fetch?.abort(),clearTimeout(this.settle),clearTimeout(this.partial),this.quietSuggest(),clearInterval(r),t.off("data",this.onData),e.off("resize",this.onResize),this.write("\x1B_Ga=d,d=A,q=2\x1B\\\x1B[H\x1B[K\x1B[2H\x1B[J\x1B[H"),t.setRawMode(!1),t.pause(),this.saveProbes(),this.renders.close(),eo(this.scratch,{recursive:!0,force:!0}),qc(),o}write(t){process.stdout.write(t)}get saved(){return this.view.saved}finish(t){this.done?.(t===2&&this.saved?0:t)}probe(){return new Promise((t)=>{let e=setTimeout(()=>{this.probeWait=void 0,t(null)},1000);this.probeWait=(n)=>{clearTimeout(e),this.probeWait=void 0,t(n)},this.write(zu)})}onData=(t)=>{this.input+=t.toString("utf8");for(let n=Xi(this.input);n;n=Xi(this.input))this.input=n.rest,this.probeWait?.(n.cell);if(this.probeWait)return;let e=Ju(this.input);if(this.input=e.pending,this.view.editing===void 0&&e.keys.length>8&&/^(?:\/|~\/|file:|https?:)/.test(e.keys))this.pasted(e.keys),e.keys="";this.typed+=e.keys;for(let n of e.events)this.inbound(n);if(clearTimeout(this.partial),Bm(this.typed)){this.partial=setTimeout(this.flushKeys,_m);return}this.flushKeys()};flushKeys=()=>{let t=xu(this.typed);this.typed="";for(let e of t)this.key(e)};features(){if(process.env.TMUX)return Promise.resolve();return new Promise((t)=>{let e=setTimeout(()=>{this.featureWait=void 0,t()},500);this.featureWait=()=>{clearTimeout(e),this.featureWait=void 0,t()},this.write("\x1B[?5522$p\x1B]72;t=q\x1B\\\x1B[c")})}inbound(t){if(t.kind==="mode"){if(t.mode===5522)this.grabber.clipboard=t.value!==0&&t.value!==4;return}if(t.kind==="attributes"){this.featureWait?.();return}if(t.kind==="osc"){if(t.code==="72"&&t.meta.t==="q"){this.grabber.drops=!0;return}this.grabber.take(t);return}this.pasted(t.text)}pasted(t){let e=this.view;if(e.editing!==void 0&&t.trim()!==""&&!this.picture(t)){e.editing+=t.replace(/[\r\n]+/g," "),this.suggest(),this.draw();return}if(e.installing!==void 0||e.asking!==void 0||e.panel!==void 0||e.help)return;if(t.trim()===""){this.fromClipboard();return}this.attach(t)}picture(t){let e=t.trim();if(/^https?:\/\/\S+$/i.test(e))return!wr(e,this.site??lt[0]);return Hr(e).length>0}async got(t){if(t.kind==="error"){this.notice(t.message);return}if(t.kind==="text"){if(t.text.trim()===""){this.notice(`no picture on the clipboard — ${Rh}`);return}this.pasted(t.text);return}await this.bring(()=>Ir(t.bytes,t.source))}notice(t,e=Xm){let n=this.view;n.error=t,clearTimeout(this.noticeTimer),this.noticeTimer=setTimeout(()=>{if(n.error===t)n.error=void 0,this.draw()},e),this.draw()}async peek(){let t=this.view,e;try{e=await Ku()}catch{return}if(!e||e.stamp===this.peeked)return;if(this.peeked=e.stamp,!e.picture||t.installing!==void 0||t.asking!==void 0)return;t.hint=`picture on the clipboard · ${Vm} uses it`,clearTimeout(this.peekTimer),this.peekTimer=setTimeout(()=>{t.hint=void 0,this.draw()},Cm),this.draw()}async fromClipboard(){let t=this.view;if(Ui()){if(this.grabber.clipboard){this.grabber.ask();return}this.notice("over ssh the clipboard is not here — drop the file");return}let e;try{e=await Pu(he(this.scratch,`clipboard-${Date.now()}.png`))}catch(r){this.notice(`could not read the clipboard: ${Be(r)}`);return}if(clearTimeout(this.peekTimer),t.hint=void 0,"image"in e){await this.bring(async(r)=>({...await Ti(e.image,r),source:"clipboard"}));return}let n=e.text.trim();if(!n){this.notice(`no picture on the clipboard — ${Rh}`);return}if(this.picture(n)){await this.attach(n);return}if(t.editing===void 0)t.editing="";this.pasted(n)}async attach(t){let e=t.trim();if(/^https?:\/\//i.test(e)){let i=wr(e,this.site??lt[0]);if(i){await this.jump(i.site,i.id);return}}let[n,...r]=Hr(e).sort((i,o)=>Number(!jh.test(i))-Number(!jh.test(o)));if(!n){this.notice("nothing to use in that — drop a picture, or paste one or its link");return}await this.bring((i)=>Ti(n,i),r.length)}async bring(t,e=0){let n=this.view;this.attaching?.abort();let r=new AbortController;this.attaching=r,n.error=void 0,n.saved=void 0,n.note="reading the picture…",this.draw();let i;try{i=await t(AbortSignal.any([r.signal,this.signal]))}catch(l){if(!r.signal.aborted)n.note=void 0,this.notice(Be(l),8000);return}if(r.signal.aborted)return;n.note=e>0?`the first picture of ${e+1} — drop one at a time to try the others`:void 0,this.quietSuggest(),n.editing=void 0,n.suggest=void 0,n.pick=void 0;let o=Gu(i.bytes);Ru(o,i.source);let s=this.origPath(Or,o,i.ext);Vn(Ur(s),{recursive:!0}),xn(s,i.bytes);let c=Jm(s).href,u={id:o,file:c,width:i.width,height:i.height,ext:i.ext,preview:c,owner:"",artist:"",score:0,rating:"s",md5:Ah("md5").update(i.bytes).digest("hex"),source:i.source,tags:[],solo:void 0,family:0,smaller:[]},h={site:Or,post:u},f=this.previewPath(h);Vn(Ur(f),{recursive:!0}),xn(f,i.bytes),++this.gen,this.current=void 0,n.shown=void 0;let a=Wr(`local|post:${o}`,!1);this.board=a,this.boards.set(a.key,a),this.single(a,h)}single(t,e){t.searching=!1,this.posts.set(ie(e.site,e.post.id),e),t.groups=[{posts:[e],open:!1}],t.checked=1,t.total=1,this.thumbQueue.push(e),this.thumbs(),this.view.mode="try",this.show(),this.select(),this.draw()}onClock=()=>{let t=this.sites.reduce((r,i)=>Ee(i)>Ee(r)?i:r),e=Math.ceil((Ee(t)-Date.now())/1000),n=e>0?e:void 0;if(n!==this.view.waiting)this.view.waiting=n,this.view.slow=t.name,this.draw()};onResize=()=>{if(this.cols=process.stdout.columns||this.cols,this.rows=process.stdout.rows||this.rows,this.scroll(),this.view.mode==="try"&&this.current)this.reveal();this.pump(),this.draw()};key(t){let e=this.view;if(t==="ctrl-c"){this.finish(2);return}if(e.installing!==void 0)return;if(e.asking!==void 0){this.askKey(t);return}if(t==="focus-in"){this.peek();return}if(t==="focus-out"||t==="nop")return;if((t==="ctrl-v"||t==="alt-v")&&e.panel===void 0){this.fromClipboard();return}if(e.editing!==void 0){this.editKey(t);return}if(e.panel!==void 0){this.panelKey(t);return}if(e.help){if(t==="?"||t==="esc")e.help=!1,this.draw();return}if(this.cols<Le.cols||this.rows<Le.rows){if(t==="esc")this.finish(2);return}if(t==="?"){e.help=!0,this.draw();return}if(e.mode==="try"){this.tryKey(t);return}this.gridKey(t)}gridKey(t){let e=this.view,{perRow:n,rowsVis:r}=_e(this.cols,this.rows),o={left:-1,right:1,up:-n,down:n,pgup:-n*r,pgdn:n*r,home:-e.focus,end:e.tiles.length}[t];if(o!==void 0){this.focus(e.focus+o);return}if(t==="enter"&&e.tiles[e.focus]){e.mode="try",e.error=void 0,this.select();return}if(t==="v"){this.fromClipboard();return}if(t==="c"){e.preset=e.preset==="cutouts"?"all":"cutouts",this.turn();return}if(t==="tab"){this.tab=(this.tab+1)%(lt.length+1),this.syncSite(),this.turn();return}if(t==="/"){e.editing="",this.draw();return}if(t===" "){this.unfold();return}if(t==="o"){this.openPage();return}if(t==="s"){e.panel=0,this.draw();return}if(t==="esc")this.finish(2)}panelKey(t){let e=this.view,n=e.panel??0,r=e.settings[n];if(t==="up"||t==="down"){e.panel=Math.max(0,Math.min(e.settings.length-1,n+(t==="up"?-1:1))),this.draw();return}if((t==="left"||t==="right")&&r){let i=t==="left"?-1:1;if(r.multi)r.cursor=(r.cursor+i+r.choices.length)%r.choices.length;else{let o=r.choices.indexOf(r.value);r.value=r.choices[(o+i+r.choices.length)%r.choices.length]}this.draw();return}if(t===" "&&r?.multi){let i=r.value.split(" "),o=r.choices.filter((c,u)=>u===r.cursor?!i.includes(c):i.includes(c)),s=r.multi.none;if(o.length>0||s!==void 0)r.value=o.length>0?o.join(" "):s,this.draw();return}if(t==="esc"){e.settings.forEach((i,o)=>{i.value=this.setting(Ye[o]?.name??"")}),e.panel=void 0,this.draw();return}if(t==="enter"||t==="alt-c")e.panel=void 0,this.adopt()}adopt(){let t=this.view,e=Ye.map((r)=>this.setting(r.name));t.settings.forEach((r,i)=>{let o=Ye[i];if(o)this.values.set(o.name,r.value)});let n=Ye.filter((r,i)=>this.setting(r.name)!==e[i]);if(n.length===0){this.draw();return}this.save(n),t.rating=mr(this.setting("TTHEME_FIND_RATING")),t.block=pr(this.setting("TTHEME_FIND_BLOCK")),t.sets=this.setting("TTHEME_FIND_SETS")==="show"?"show":"fold",t.preset=this.setting("TTHEME_FIND_POSTS")==="all"?"all":"cutouts",t.order=Nh(this.setting("TTHEME_FIND_ORDER")),t.solo=this.setting("TTHEME_FIND_SOLO")==="on",this.boards.clear(),this.current=void 0,t.shown=void 0,t.mode="grid",this.search()}save(t){this.store(t.map((e)=>[e.name,this.setting(e.name)]))}store(t){let e=he(this.home,"ttheme","config.zsh");try{let n=ze(e)?Th(e,"utf8"):"";return xn(e,t.reduce((r,[i,o])=>uu(r,i,o),n)),!0}catch(n){return this.view.error=n instanceof Error?n.message:String(n),!1}}askKey(t){let e=this.view;if(t==="y"){if(e.asking=void 0,this.store([["TTHEME_FIND_UNBLOCK","1"]])){this.unblock=!0,this.finish(0);return}this.draw();return}if(t==="n"||t==="esc")e.asking=void 0,this.draw()}editKey(t){let e=this.view,n=e.editing??"",r=e.suggest??[];if((t==="up"||t==="down")&&r.length>0){let i=e.pick??-1,o=t==="down"?Math.min(r.length-1,i+1):i-1;e.pick=o<0?void 0:o,this.draw();return}if(t==="esc"||t==="enter")this.quietSuggest();if(t==="esc"){if(e.editing=void 0,e.tag===""){this.finish(2);return}this.draw();return}if(t==="enter"){let i=e.pick===void 0?void 0:r[e.pick],o=i?n.replace(/\S*$/,i.value):n;if(e.editing=void 0,e.suggest=void 0,e.pick=void 0,o.trim()){this.commit(o.trim());return}if(e.tag===""){this.finish(2);return}this.draw();return}if(t==="backspace"){e.editing=n.slice(0,-1),this.suggest(),this.draw();return}if(t.length===1&&t>=" ")e.editing=n+t,this.suggest(),this.draw()}quietSuggest(){clearTimeout(this.suggestTimer),this.suggesting?.abort(),this.suggesting=void 0}suggest(){this.quietSuggest();let t=this.view;t.pick=void 0;let e=/\S*$/.exec(t.editing??"")?.[0]??"";if(!Um(e)){t.suggest=void 0;return}let n=[...new Map(qu(this.catalog.palettes,this.entry,e).map((i)=>[i.booru,{value:i.booru,count:0,palette:i.name}])).values()].slice(0,zm);t.suggest=n.length>0?n:void 0;let r=new AbortController;this.suggesting=r,this.suggestTimer=setTimeout(async()=>{try{let i=await Vc(e,AbortSignal.any([this.signal,r.signal]));if(this.suggesting===r&&t.editing!==void 0){let o=new Map(i.map((c)=>[c.value,c.count])),s=new Set(n.map((c)=>c.value));t.suggest=[...n.map((c)=>({...c,count:o.get(c.value)??0})),...i.filter((c)=>!s.has(c.value))].slice(0,Ym),t.pick=t.pick!==void 0&&t.pick<n.length?t.pick:void 0,this.draw()}}catch{}},Qm)}async commit(t){let e=wr(t,this.site??lt[0]);if(e){await this.jump(e.site,e.id);return}if(this.picture(t)){await this.attach(t);return}this.view.tag=t,this.boards.clear(),await this.search()}async jump(t,e){let n=++this.gen;this.tab=lt.indexOf(t)+1,this.syncSite(),this.current=void 0,this.view.shown=void 0,this.view.error=void 0;let r=Wr(`${t.key}|post:${e}`,!0);this.board=r,this.boards.set(r.key,r),this.show(),this.draw();try{let i=await Fi(t,e,this.signal);if(n!==this.gen)return;if(!i){r.searching=!1,r.error=`${t.name} has no post ${e}`,this.view.error=r.error,this.show(),this.draw();return}this.single(r,{site:t,post:i})}catch(i){this.fail(n,i,t)}}async turn(){this.fetch?.abort(),this.current=void 0,this.view.shown=void 0;let t=this.boards.get(this.boardKey);if(!t){await this.search();return}this.gen++,this.board=t,this.view.error=t.error,this.show(),this.draw(),await this.pump()}unfold(){let t=this.view,e=0;for(let n of this.board.groups){let r=n.open?n.posts.length:1;if(t.focus<e+r){if(n.posts.length<2)return;n.open=!n.open,this.board.focus=e;for(let i of n.posts)if(!this.thumbPath.has(ie(i.site,i.post.id)))this.thumbQueue.push(i);this.thumbs(),this.show(),this.scroll(),this.draw();return}e+=r}}openPage(){let t=this.view.tiles[this.view.focus],e=t&&this.posts.get(t.key);if(!e)return;let n=process.platform==="darwin"?"open":"xdg-open";try{Jh(n,[e.site.pageUrl(e.post.id)],{stdio:"ignore",detached:!0}).unref()}catch{}}tryKey(t){let e=this.view;if(t==="left"||t==="right"){this.direction=t==="left"?-1:1,this.focus(e.focus+this.direction);return}if(t==="o"){this.openPage();return}if(t==="x"){this.swap();return}if(t==="v"){this.fromClipboard();return}if(t==="enter"){this.install();return}if(t==="esc")this.fetch?.abort(),clearTimeout(this.settle),e.fetching=void 0,e.mode="grid",e.error=void 0,this.draw()}focus(t){let e=this.view;if(e.tiles.length===0)return;let n=Math.max(0,Math.min(e.tiles.length-1,t));if(n===e.focus)return;if(e.focus=n,this.board.focus=n,this.scroll(),this.pump(),e.mode==="try")this.select();this.draw()}scroll(){let t=this.view,{perRow:e,rowsVis:n}=_e(this.cols,this.rows),r=Math.floor(t.focus/e);if(r<t.top)t.top=r;if(r>t.top+n-1)t.top=r-n+1;this.board.top=t.top}query(t){let e=this.view,n=e.tag===this.entry.booru?Zu(this.entry,t.key):[e.tag];if(n.length===0)return;let r=n.length>1,i=e.preset==="cutouts"?t.cutouts:"",o=r&&i.includes("~"),s=[r?n.map((h)=>`~${h}`).join(" "):n[0],t.rate(this.view.rating),o?"":i,e.order==="score"?t.best:""].filter(Boolean),c=[],u=[];for(let h of s)if(vi([...c,h].join(" "))<=t.tagBudget)c.push(h);else u.push(h);return{tags:c.join(" "),notes:[...u.length>0?[`${t.name} takes ${t.tagBudget} tags — ${u.join(" ")} left out`]:[],...o?[`${t.name} ORs the names, so cutouts are told by the file`]:[]]}}async search(){let t=++this.gen,e=Wr(this.boardKey,!0);this.board=e,this.boards.set(e.key,e),this.view.error=void 0;let n=this.sites.flatMap((o)=>{let s=this.query(o);return s?[{site:o,...s}]:[]}),r=this.sites.filter((o)=>!n.some((s)=>s.site===o)),i=[...n.flatMap(({notes:o})=>o),...r.length>0?[`${this.entry.name} has no tag on ${r.map((o)=>o.name).join(", ")}`]:[]];if(e.note=i.length>0?i.join(" · "):void 0,n.length===0)e.searching=!1;this.show(),this.draw(),this.tally(t,e,n);try{let o=await Promise.all(n.map(async(s)=>({plan:s,owners:await this.mateOwners(s.site)})));if(t!==this.gen)return;e.sources=o.flatMap(({plan:{site:s,tags:c},owners:u})=>[...vi(c)+1<=s.tagBudget?[...u.keys()].map((h)=>({site:s,tags:`${c} user:${h}`,page:0,done:!1})):[],{site:s,tags:c,page:0,done:!1}]),this.show(),this.draw(),await this.pump()}catch(o){this.fail(t,o)}}async tally(t,e,n){let r=await Promise.allSettled(n.map(({site:i,tags:o})=>_c(i,o,this.signal)));if(t===this.gen)e.total=r.reduce((i,o)=>i+(o.status==="fulfilled"?o.value:0),0),this.show(),this.draw()}fail(t,e,n=this.site){if(t!==this.gen||this.signal.aborted)return;this.board.error=no(n?.name??this.tabName,e),this.board.searching=!1,this.view.error=this.board.error,this.offer(n,e),this.show(),this.draw()}offer(t,e){if(t&&!this.view.unblocked&&Wh()&&Be(e)==="ECONNRESET")this.view.asking=t.name}drop(t,e,n){for(let r of t.sources)if(r.site===e)r.done=!0;t.note=[t.note,no(e.name,n)].filter(Boolean).join(" · "),this.offer(e,n)}wants(){let{perRow:t,rowsVis:e}=_e(this.cols,this.rows);return this.view.tiles.length<(this.board.top+e+Gh)*t}need(){let{perRow:t,rowsVis:e}=_e(this.cols,this.rows);return(e+Gh)*t}live(t){return this.boards.get(t.key)===t}page(t,e,n){let r=`${t.key}|${e}|${n}`,i=this.pages.get(r);if(!i)i=Zc(t,e,n,this.signal).then((o)=>this.borrow(o)),this.pages.set(r,i),i.catch(()=>this.pages.delete(r));return i}async borrow(t){let e=t.filter((n)=>n.solo===void 0&&n.md5!=="");if(e.length>0)try{Xc(e,await Cc(e.map((n)=>n.md5),this.signal))}catch{}return t}async round(t){let e=lt.flatMap((c)=>{let u=t.sources.find((h)=>h.site===c&&!h.done);return u?[u]:[]}),n=await Promise.all(e.map(async(c)=>{try{return{source:c,posts:await this.page(c.site,c.tags,c.page)}}catch(u){if(t.sources.every((h)=>h.site===c.site)||this.signal.aborted)throw u;return this.drop(t,c.site,u),{source:c,posts:void 0}}}));if(!this.live(t))return;let r=[];for(let{source:c,posts:u}of n){if(!u)continue;c.page++,c.done=u.length<Oe;let h=t.last.get(c);for(let f of u){let a=h&&wh(h.post,f)?h.set:`set:${c.site.key}:${f.id}`;h={post:f,set:a};let l=ie(c.site,f.id);if(t.seen.has(l))continue;t.seen.add(l);let d={site:c.site,post:f};if(this.eligible(d))t.kin.set(d,[a,...ph(c.site,f)]),r.push(d);else t.checked++}if(h)t.last.set(c,h)}let i=this.dedupe(t,r),o=++t.rounds,s;if(this.view.order!=="fit")s=e.length>1?ch(i):i;else{let c=Kr(i,this.frame(),this.matched),u=c.slice(0,this.need());if(await this.looks(u),!this.live(t))return;s=[...Kr(u,this.frame(),this.matched),...c.slice(u.length)]}for(let c of s)t.roundOf.set(c,o);t.queue.push(...s),this.ahead(t)}ahead(t){if(this.aheading||this.view.order!=="fit"||!this.live(t))return;let e=t.queue.slice(0,this.need()).filter((n)=>!this.looking.has(ie(n.site,n.post.id)));if(e.length===0)return;this.aheading=!0,this.looks(e).then(()=>{this.aheading=!1;for(let n of new Set(e.map((r)=>t.roundOf.get(r)??0)))this.resort(t,n);this.ahead(t)})}resort(t,e){let n=t.queue.flatMap((i,o)=>t.roundOf.get(i)===e?[o]:[]),r=Kr(n.map((i)=>t.queue[i]),this.frame(),this.matched);n.forEach((i,o)=>{t.queue[i]=r[o]})}dedupe(t,e){let n=[];for(let r of e){let i=Bi(r.post),o=i.map((c)=>t.same.get(c)).find(Boolean);if(!o){for(let c of i)t.same.set(c,r);n.push(r);continue}if(t.checked++,Lh(r.post)<=Lh(o.post))continue;for(let c of[...i,...Bi(o.post)])t.same.set(c,r);let s=n.indexOf(o);if(s>=0){n[s]=r;continue}this.replace(t,o,r)}return n}replace(t,e,n){t.roundOf.set(n,t.roundOf.get(e)??0);let r=t.queue.indexOf(e);if(r>=0){t.queue[r]=n;return}for(let i of t.groups){let o=i.posts.indexOf(e);if(o>=0){i.posts[o]=n,this.posts.set(ie(n.site,n.post.id),n),this.thumbQueue.push(n),this.thumbs();return}}}async looks(t){let e=0;await Promise.all(Array.from({length:Oh},async()=>{while(e<t.length)await this.look(t[e++])}))}look(t){let e=ie(t.site,t.post.id),n=this.looking.get(e);if(!n)n=(async()=>{let r=this.previewPath(t);await this.cached(t.site,r,t.post.preview);let i=await this.renders.run({job:"match",from:r,colors:this.entry.signature});return this.looked.set(e,i),this.matched.set(t.post,i.match),i})().catch(()=>{return}),this.looking.set(e,n);return n}async pump(){let t=this.gen,e=this.board;if(this.pumping===t||e.sources.length===0)return;this.pumping=t;let n=[],r;try{e.searching=!0;while(t===this.gen){while(n.length<Hh&&e.queue.length>0&&this.wants()){let s=e.queue.shift();n.push({pick:s,passed:this.vet(s)})}if(this.ahead(e),!r&&e.queue.length<Hh&&e.sources.some((s)=>!s.done)&&this.wants()){let s=this.round(e).then(()=>{if(r===s)r=void 0});s.catch(()=>{}),r=s}let i=n.shift();if(!i){if(!r)break;await r,this.show(),this.draw();continue}let o=await i.passed;if(t!==this.gen)return;if(e.checked++,o)this.admit(i.pick);this.show(),this.draw()}if(t===this.gen)e.searching=!1,this.show(),this.draw()}catch(i){this.fail(t,i)}finally{if(this.saveProbes(),this.pumping===t)this.pumping=0}}eligible({site:t,post:e}){let n=On(e);if(!Uc(t,e,this.view.rating)||Tc(e,this.view.block).length>0||!n)return!1;if(this.view.solo&&e.solo===!1)return!1;return this.view.preset==="all"?["png","jpg","jpeg"].includes(n.ext):e.ext==="png"}async vet(t){let[e]=await Promise.all([this.passes(t),this.look(t)]);return e}async passes({site:t,post:e}){return this.view.preset==="all"||t.vouched||this.transparent(t,e)}probes(t){let e=this.probed.get(t.key);if(!e)e=ro(t,"probes.json"),this.probed.set(t.key,e);return e}async transparent(t,e){let n=this.probes(t),r=n[e.id];if(r!==void 0)return r;try{let i=(await xc(t,e.file,this.signal))?.alpha===!0;return n[e.id]=i,this.unsaved.add(t.key),i}catch{return!1}}saveProbes(){for(let t of this.unsaved){let e=lt.find((n)=>n.key===t);if(e)io(e,"probes.json",this.probes(e))}this.unsaved.clear()}admit(t){let{site:e,post:n}=t,r=this.board,i=ie(e,n.id);this.posts.set(i,t);let o=r.kin.get(t)??[],s=this.looked.get(i),c=s&&{hash:s.hash,width:n.width,height:n.height},u=this.view.sets==="fold"?this.kindred(r,o,c):void 0;if(u){if(u.posts.push(t),this.register(r,u,o,c),u.open)this.thumbQueue.push(t),this.thumbs();return}let h={posts:[t],open:!1};r.groups.push(h),this.register(r,h,o,c),this.thumbQueue.push(t),this.thumbs()}kindred(t,e,n){for(let r of e){let i=t.kindred.get(r);if(i)return i}return n&&t.shapes.find((r)=>$h(r.shape,n))?.group}register(t,e,n,r){for(let i of n)if(!t.kindred.has(i))t.kindred.set(i,e);if(r)t.shapes.push({shape:r,group:e})}async mateOwners(t){let e=this.owners.get(t.key);if(e)return e;let n=Sc(this.home),r=ro(t,"owners.json"),i=this.catalog.palettes.flatMap((u)=>{let h=n.get(u.name);return u.group===this.entry.group&&u.name!==this.entry.name&&h?.site===t.key?[{name:u.name,id:h.id}]:[]}),o=await Promise.all(i.map(async(u)=>{let h=r[u.id];if(h!==void 0)return{...u,owner:h};try{return{...u,owner:(await Fi(t,u.id,this.signal))?.owner??""}}catch{return}})),s=new Map;for(let u of o)if(u)r[u.id]=u.owner,s.set(u.name,u.owner);io(t,"owners.json",r);let c=Wc(s);return this.owners.set(t.key,c),c}async cached(t,e,n,r){if(ze(e))return Pm(e).size;let i=this.inflight.get(e);if(i)return i;let o=(async()=>{let s=await zc(t,n,this.signal,r);return Vn(Ur(e),{recursive:!0}),xn(e,s),s.length})();this.inflight.set(e,o);try{return await o}finally{this.inflight.delete(e)}}thumbs(){while(this.thumbing<Oh&&this.thumbQueue.length>0){let t=this.thumbQueue.shift();this.thumbing++,this.thumb(t).catch(()=>{}).finally(()=>{this.thumbing--,this.thumbs()})}}async thumb(t){let{site:e,post:n}=t,r=At.cols*this.cell.w,i=At.rows*this.cell.h,o=he(ye(e),"tile",`${Ph(n)}-${r}x${i}.png`);if(!ze(o)){let s=this.previewPath(t);await this.cached(e,s,n.preview),await this.renders.run({job:"thumb",from:s,to:o,width:r,height:i})}this.thumbPath.set(ie(e,n.id),o),this.show(),this.draw()}select(){let t=this.view,e=t.tiles[t.focus];if(this.fetch?.abort(),clearTimeout(this.settle),t.fetching=void 0,!e)return;if(this.current?.key===e.key){this.reveal();return}this.settle=setTimeout(()=>void this.load(e),Zm),this.draw()}async load(t){let e=this.view,n=this.posts.get(t.key),r=n&&On(n.post);if(!n||!r)return;let{site:i}=n,o=this.board,s=new AbortController;this.fetch=s;try{let c=this.origPath(i,t.id,r.ext);if(!ze(c))e.fetching={id:t.key,got:0,size:0},this.draw();let u=await this.cached(i,c,r.file,(a,l)=>{if(e.fetching?.id===t.key)e.fetching={id:t.key,got:a,size:l},this.draw()});if(s.signal.aborted)return;if(e.fetching=void 0,o!==this.board)return;let h={site:i,id:t.id,key:t.key,path:c,ext:r.ext,size:u,using:"plain",failed:!1};e.preparing=t.key,this.flush();let f=await this.render(h,"plain");if(s.signal.aborted||o!==this.board)return;if(f.clear===0&&qi()&&this.setting("TTHEME_FIND_REMOVE_BG")!=="off"){if(e.preparing=void 0,e.cutting=t.key,this.flush(),h.cut=await this.cutOut(i,t.id,c,s.signal),s.signal.aborted||o!==this.board)return;if(e.cutting=void 0,h.cut){e.preparing=t.key,this.flush();let a=await this.render(h,"cut").catch(()=>{return});if(s.signal.aborted||o!==this.board)return;if(a&&_u(a.clear))h.using="cut";else eo(h.cut,{force:!0}),h.cut=void 0,h.failed=!0}else h.failed=!0}if(this.current=h,e.tiles[e.focus]?.key===t.key)await this.present();this.preload()}catch(c){if(!s.signal.aborted&&!this.signal.aborted)e.error=no(i.name,c)}finally{if(e.fetching?.id===t.key)e.fetching=void 0;if(e.preparing===t.key)e.preparing=void 0;if(e.cutting===t.key)e.cutting=void 0;this.draw()}}async cutOut(t,e,n,r){let i=he(ye(t),"cut",`${e}.png`);if(ze(i))return i;try{return Vn(Ur(i),{recursive:!0}),await Xu(n,i,r),i}catch{eo(i,{force:!0});return}}swap(){let t=this.current;if(!t?.cut||this.view.shown?.id!==t.key)return;t.using=t.using==="cut"?"plain":"cut",this.reveal()}preload(){let t=this.view;if(t.mode!=="try")return;for(let e of[t.focus+this.direction,t.focus-this.direction]){if(this.prefetching>=qm)return;let n=t.tiles[e],r=n&&this.posts.get(n.key),i=r&&On(r.post);if(!r||!i)continue;let{site:o,post:s}=r,c=this.origPath(o,s.id,i.ext);this.prefetching++,this.cached(o,c,i.file).then(()=>this.render({site:o,id:s.id,key:n.key,path:c,ext:i.ext,size:0,using:"plain",failed:!1},"plain")).catch(()=>{}).finally(()=>{this.prefetching--})}}async render(t,e){let n=this.cols*this.cell.w,r=this.rows*this.cell.h,i=Math.min(n,xm),o=Math.max(1,Math.round(r*i/n)),s=he(this.scratch,`${t.site.key}-${t.id}${e==="cut"?"c":""}-${i}x${o}.png`),c=`${t.site.key}:${t.id}:${e}`,u=this.clarity.get(c);if(u!==void 0&&ze(s))return{clear:u,path:s};let h=await this.renders.run({job:"show",from:e==="cut"?t.cut:t.path,to:s,width:i,height:o,colors:this.entry,tone:this.tone});return this.clarity.set(c,h),{clear:h,path:s}}async present(){let t=this.current;if(!t)return;let e=t.using,{clear:n,path:r}=await this.render(t,e);if(this.current!==t||t.using!==e)return;this.view.shown={id:t.key,clear:n,bytes:t.size,path:r,cut:t.cut?e==="cut"?"on":"off":t.failed?"failed":"none"}}reveal(){let t=this.view;t.preparing=this.current?.key,this.flush(),this.present().catch((e)=>{t.error=e instanceof Error?e.message:String(e)}).finally(()=>{if(t.preparing===this.current?.key)t.preparing=void 0;this.draw()})}async install(){let t=this.view,e=t.tiles[t.focus],n=this.current;if(!e||n?.key!==e.key||t.preparing!==void 0||t.shown?.id!==e.key)return;t.installing=e.key,t.error=void 0,this.flush();try{await this.renders.run({job:"backdrop",from:n.using==="cut"?n.cut:n.path,source:n.path,home:this.home,colors:this.entry,tone:this.tone,origin:{site:n.site.key,id:n.id,ext:n.ext,from:`${n.site.name} ${n.id} ${n.site.pageUrl(n.id)}`},width:this.cols*this.cell.w,height:this.rows*this.cell.h});let r=ro(n.site,"owners.json");r[n.id]=this.posts.get(n.key)?.post.owner??"",io(n.site,"owners.json",r),xe(this.home),t.saved=`background · ${this.entry.name} ← ${n.site.name} ${n.id}`,t.installed.push(e.key),this.fetch?.abort(),clearTimeout(this.settle),t.fetching=void 0,t.mode="grid"}catch(r){t.error=r instanceof Error?r.message:String(r)}t.installing=void 0,this.draw()}draw(){if(this.dirty)return;this.dirty=!0,setImmediate(()=>{this.dirty=!1,this.flush()})}flush(){let t=oh(this.view,this.cols,this.rows),e="\x1B[?2026h";t.lines.forEach((r,i)=>{e+=`\x1B[${i+1};1H\x1B[K${r}`});let n=new Set;for(let r of t.images){if(n.add(r.id),this.sent.get(r.id)!==r.path)e+=Yu(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)e+=Bu(r),this.placed.set(r.id,i)}for(let r of this.sent.keys())if(!n.has(r))e+=Du(r),this.sent.delete(r),this.placed.delete(r);this.write(`${e}\x1B[?2026l`)}}function Wh(){if(process.versions.bun)return!0;let[t=0,e=0]=process.versions.node.split(".").map(Number);return t>22||t===22&&e>=21}async function Kh(){if(!Wh())return process.stderr.write(`unblock needs node 22.21 or newer — this is ${process.versions.node}
|
|
143
|
+
`),1;let t=await Ih(),e=Jh(process.execPath,process.argv.slice(1),{stdio:"inherit",env:{...process.env,NODE_USE_ENV_PROXY:"1",NODE_NO_WARNINGS:"1",HTTPS_PROXY:`http://127.0.0.1:${t.port}`,NO_PROXY:[process.env.NO_PROXY,Ac()].filter(Boolean).join(","),TTHEME_FIND_PROXY:String(t.port)}}),n=await new Promise((r)=>e.on("exit",(i)=>r(i??1)));return t.close(),n}async function Qh(t){if(process.env.TTHEME_FIND_UNBLOCK==="1"&&!process.env.TTHEME_FIND_PROXY)return Kh();let e=Kt(),n=Pt(e),r=Gr(n.palettes,t);if(!process.stdin.isTTY||!process.stdout.isTTY)throw Error("needs a terminal");let i=new Uh(e,n,r,r.booru??""),o=await i.run(),s=i.unblock?await Kh():o;if(i.saved&&s!==0)return process.stderr.write(`${i.saved}
|
|
144
|
+
`),0;return s}function qh(t,e){let n=Kt();if(Gr(Pt(n).palettes,t),e==="next"||e==="prev"){let{key:r,at:i,of:o}=Mc(n,t,e==="next"?1:-1);return xe(n),process.stderr.write(`background · ${t} ${i}/${o} ${r}
|
|
145
|
+
`),0}if(e==="drop"){let{key:r,left:i}=yc(n,t);return xe(n),process.stderr.write(`background · ${t} removed ${r??"the picture"} · ${i} left
|
|
146
|
+
`),0}if(e==="tuned")return xe(n),0;throw Error(`unknown image action ${e} — next, prev, drop or tuned`)}import{execFileSync as Dp,spawnSync as t0}from"node:child_process";import{chmodSync as e0,copyFileSync as n0,existsSync as Qt,mkdirSync as vo,readdirSync as r0,readFileSync as sn,rmSync as Xf,writeFileSync as Cf}from"node:fs";import{homedir as i0}from"node:os";import{dirname as on,join as ct}from"node:path";import{styleText as ao}from"node:util";import{stdout as uf,stdin as dp}from"node:process";import mp from"node:readline";var Zh=(()=>{let t=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(e)=>{let n=0;t.lastIndex=0;while(t.test(e))n+=1;return e.length-n}})(),_h=(t)=>{return t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510},Xh=(t)=>{return t===8987||t===9001||t>=12272&&t<=12287||t>=12289&&t<=12350||t>=12441&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12783&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=65040&&t<=65049||t>=65072&&t<=65106||t>=65108&&t<=65126||t>=65128&&t<=65131||t>=127488&&t<=127490||t>=127504&&t<=127547||t>=127552&&t<=127560||t>=131072&&t<=196605||t>=196608&&t<=262141};var Dm=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,tp=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Ch=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,ep=/\t{1,1000}/y,Vh=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu,np=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,rp=/\p{M}+/gu,ip={limit:1/0,ellipsis:""},xh=(t,e={},n={})=>{let r=e.limit??1/0,i=e.ellipsis??"",o=e?.ellipsisWidth??(i?xh(i,ip,n).width:0),s=0,c=n.controlWidth??0,u=n.tabWidth??8,h=n.emojiWidth??2,f=2,a=n.regularWidth??1,l=n.wideWidth??2,d=[[np,a],[Dm,0],[tp,c],[ep,u],[Vh,h],[Ch,l]],p=0,g=0,k=t.length,y=0,I=!1,E=k,v=Math.max(0,r-o),b=0,O=0,$=0,R=0;t:while(!0){if(O>b||g>=k&&g>p){let H=t.slice(b,O)||t.slice(p,g);y=0;for(let P of H.replaceAll(rp,"")){let G=P.codePointAt(0)||0;if(_h(G))R=2;else if(Xh(G))R=l;else R=a;if($+R>v)E=Math.min(E,Math.max(b,p)+y);if($+R>r){I=!0;break t}y+=P.length,$+=R}b=O=0}if(g>=k)break t;for(let H=0,P=d.length;H<P;H++){let[G,C]=d[H];if(G.lastIndex=g,G.test(t)){if(y=G===Ch?Zh(t.slice(g,G.lastIndex)):G===Vh?1:G.lastIndex-g,R=y*C,$+R>v)E=Math.min(E,g+Math.floor((v-$)/C));if($+R>r){I=!0;break t}$+=R,b=p,O=g,g=p=G.lastIndex;continue t}}g+=1}return{width:I?v:$,index:I?E:k,truncated:I,ellipsed:I&&r>=o}},zh=xh;var op={limit:1/0,ellipsis:"",ellipsisWidth:0},sp=(t,e={})=>{return zh(t,op,e).width},Jt=sp;var Qr="\x1B",ef="",cp=39,so="\x07",nf="[",up="]",rf="m",co=`${up}8;;`,Yh=new RegExp(`(?:\\${nf}(?<code>\\d+)m|\\${co}(?<uri>.*)${so})`,"y"),Bh=(t)=>{if(t>=30&&t<=37)return 39;if(t>=90&&t<=97)return 39;if(t>=40&&t<=47)return 49;if(t>=100&&t<=107)return 49;if(t===1||t===2)return 22;if(t===3)return 23;if(t===4)return 24;if(t===7)return 27;if(t===8)return 28;if(t===9)return 29;if(t===0)return 0;return},Dh=(t)=>`${Qr}${nf}${t}${rf}`,tf=(t)=>`${Qr}${co}${t}${so}`,oo=(t,e,n)=>{let r=e[Symbol.iterator](),i=!1,o=!1,s=t.at(-1),c=s===void 0?0:Jt(s),u=r.next(),h=r.next(),f=0;while(!u.done){let a=u.value,l=Jt(a);if(c+l<=n)t[t.length-1]+=a;else t.push(a),c=0;if(a===Qr||a===ef)i=!0,o=e.startsWith(co,f+1);if(i){if(o){if(a===so)i=!1,o=!1}else if(a===rf)i=!1}else if(c+=l,c===n&&!h.done)t.push(""),c=0;u=h,h=r.next(),f+=a.length}if(s=t.at(-1),!c&&s!==void 0&&s.length&&t.length>1)t[t.length-2]+=t.pop()},hp=(t)=>{let e=t.split(" "),n=e.length;while(n){if(Jt(e[n-1]))break;n--}if(n===e.length)return t;return e.slice(0,n).join(" ")+e.slice(n).join("")},fp=(t,e,n={})=>{if(n.trim!==!1&&t.trim()==="")return"";let r="",i,o,s=t.split(" "),c=[""],u=0;for(let a=0;a<s.length;a++){let l=s[a];if(n.trim!==!1){let p=c.at(-1)??"",g=p.trimStart();if(p.length!==g.length)c[c.length-1]=g,u=Jt(g)}if(a!==0){if(u>=e&&(n.wordWrap===!1||n.trim===!1))c.push(""),u=0;if(u||n.trim===!1)c[c.length-1]+=" ",u++}let d=Jt(l);if(n.hard&&d>e){let p=e-u,g=1+Math.floor((d-p-1)/e);if(Math.floor((d-1)/e)<g)c.push("");oo(c,l,e),u=Jt(c.at(-1)??"");continue}if(u+d>e&&u&&d){if(n.wordWrap===!1&&u<e){oo(c,l,e),u=Jt(c.at(-1)??"");continue}c.push(""),u=0}if(u+d>e&&n.wordWrap===!1){oo(c,l,e),u=Jt(c.at(-1)??"");continue}c[c.length-1]+=l,u+=d}if(n.trim!==!1)c=c.map((a)=>hp(a));let h=c.join(`
|
|
147
|
+
`),f=!1;for(let a=0;a<h.length;a++){let l=h[a];if(r+=l,!f){if(f=l>="\uD800"&&l<="\uDBFF",f)continue}else f=!1;if(l===Qr||l===ef){Yh.lastIndex=a+1;let p=Yh.exec(h)?.groups;if(p?.code!==void 0){let g=Number.parseFloat(p.code);i=g===cp?void 0:g}else if(p?.uri!==void 0)o=p.uri.length===0?void 0:p.uri}if(h[a+1]===`
|
|
148
|
+
`){if(o)r+=tf("");let d=i?Bh(i):void 0;if(i&&d)r+=Dh(d)}else if(l===`
|
|
149
|
+
`){if(i&&Bh(i))r+=Dh(i);if(o)r+=tf(o)}}return r},ap=/\r?\n/;function Se(t,e,n){return String(t).normalize().split(ap).map((r)=>fp(r,e,n)).join(`
|
|
150
|
+
`)}var Wt=ir(ho(),1);function De(t,e,n){if(!n.some((s)=>!s.disabled))return t;let r=t+e,i=Math.max(n.length-1,0),o=r<0?i:r>i?0:r;return n[o]?.disabled?De(o,e<0?-1:1,n):o}function qr(t,e,n,r){let i=r.split(`
|
|
151
|
+
`),o=0,s=t;for(let u of i){if(s<=u.length)break;s-=u.length+1,o++}for(o=Math.max(0,Math.min(i.length-1,o+n)),s=Math.min(s,i[o].length)+e;s<0&&o>0;)o--,s+=i[o].length+1;for(;s>i[o].length&&o<i.length-1;)s-=i[o].length+1,o++;s=Math.max(0,Math.min(i[o].length,s));let c=0;for(let u=0;u<o;u++)c+=i[u].length+1;return c+s}var pp=["up","down","left","right","space","enter","cancel"],wp=["January","February","March","April","May","June","July","August","September","October","November","December"],Tt={actions:new Set(pp),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:[...wp],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(t,e)=>`There are only ${t} days in ${e}`,afterMin:(t)=>`Date must be on or after ${t.toISOString().slice(0,10)}`,beforeMax:(t)=>`Date must be on or before ${t.toISOString().slice(0,10)}`}}};function hf(t,e){if(typeof t=="string")return Tt.aliases.get(t)===e;for(let n of t)if(n!==void 0&&hf(n,e))return!0;return!1}function bp(t,e){if(t===e)return;let n=t.split(`
|
|
152
|
+
`),r=e.split(`
|
|
153
|
+
`),i=Math.max(n.length,r.length),o=[];for(let s=0;s<i;s++)n[s]!==r[s]&&o.push(s);return{lines:o,numLinesBefore:n.length,numLinesAfter:r.length,numLines:i}}var A$=globalThis.process.platform.startsWith("win"),lo=Symbol("clack:cancel");function tn(t){return t===lo}function Zr(t,e){let n=t;n.isTTY&&n.setRawMode(e)}var Xr=(t)=>("columns"in t)&&typeof t.columns=="number"?t.columns:80,mo=(t)=>("rows"in t)&&typeof t.rows=="number"?t.rows:20;function zn(t,e,n,r=n,i=n,o){let s=Xr(t??uf);return Se(e,s-n.length,{hard:!0,trim:!1}).split(`
|
|
154
|
+
`).map((c,u,h)=>{let f=o?o(c,u):c;return u===0?`${r}${f}`:u===h.length-1?`${i}${f}`:`${n}${f}`}).join(`
|
|
155
|
+
`)}function ff(t,e){if("~standard"in t){let n=t["~standard"].validate(e);if(n instanceof Promise)throw TypeError("Schema validation must be synchronous. Update `validate()` and remove any asynchronous logic.");return n.issues?.at(0)?.message}return t(e)}class me{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(t,e=!0){let{input:n=dp,output:r=uf,render:i,signal:o,...s}=t;this.opts=s,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=i.bind(this),this._track=e,this._abortSignal=o,this.input=n,this.output=r}unsubscribe(){this._subscribers.clear()}setSubscriber(t,e){let n=this._subscribers.get(t)??[];n.push(e),this._subscribers.set(t,n)}on(t,e){this.setSubscriber(t,{cb:e})}once(t,e){this.setSubscriber(t,{cb:e,once:!0})}emit(t,...e){let n=this._subscribers.get(t)??[],r=[];for(let i of n)i.cb(...e),i.once&&r.push(()=>n.splice(n.indexOf(i),1));for(let i of r)i()}prompt(){return new Promise((t)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),t(lo);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=mp.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),Zr(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(Wt.cursor.show),this.output.off("resize",this.render),Zr(this.input,!1),t(this.value)}),this.once("cancel",()=>{this.output.write(Wt.cursor.show),this.output.off("resize",this.render),Zr(this.input,!1),t(lo)})})}_isActionKey(t,e){return t==="\t"}_shouldSubmit(t,e){return!0}_setValue(t){this.value=t,this.emit("value",this.value)}_setUserInput(t,e){this.userInput=t??"",this.emit("userInput",this.userInput),e&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}onKeypress(t,e){if(this._track&&e.name!=="return"&&(e.name&&this._isActionKey(t,e)&&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"),e?.name&&(!this._track&&Tt.aliases.has(e.name)&&this.emit("cursor",Tt.aliases.get(e.name)),Tt.actions.has(e.name)&&this.emit("cursor",e.name)),t&&(t.toLowerCase()==="y"||t.toLowerCase()==="n")&&this.emit("confirm",t.toLowerCase()==="y"),this.emit("key",t,e),e?.name==="return"&&this._shouldSubmit(t,e)){if(this.opts.validate){let n=ff(this.opts.validate,this.value);n&&(this.error=n instanceof Error?n.message:n,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}hf([t,e?.name,e?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
|
|
156
|
+
`),Zr(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let t=Se(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
|
|
157
|
+
`).length-1;this.output.write(Wt.cursor.move(-999,t*-1))}render(){let t=Se(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(t!==this._prevFrame){if(this.state==="initial")this.output.write(Wt.cursor.hide);else{let e=bp(this._prevFrame,t),n=mo(this.output);if(this.restoreCursor(),e){let r=Math.max(0,e.numLinesAfter-n),i=Math.max(0,e.numLinesBefore-n),o=e.lines.find((s)=>s>=r);if(o===void 0){this._prevFrame=t;return}if(e.lines.length===1){this.output.write(Wt.cursor.move(0,o-i)),this.output.write(Wt.erase.lines(1));let s=t.split(`
|
|
158
|
+
`);this.output.write(s[o]),this._prevFrame=t,this.output.write(Wt.cursor.move(0,s.length-o-1));return}else if(e.lines.length>1){if(r<i)o=r;else{let c=o-i;c>0&&this.output.write(Wt.cursor.move(0,c))}this.output.write(Wt.erase.down());let s=t.split(`
|
|
159
159
|
`).slice(o);this.output.write(s.join(`
|
|
160
|
-
`)),this._prevFrame=t;return}}this.output.write(Wt.erase.down())}this.output.write(t),this.state==="initial"&&(this.state="active"),this._prevFrame=t}}}function mp(t,n){if(t===void 0||n.length===0)return 0;let e=n.findIndex((r)=>r.value===t);return e!==-1?e:0}function pp(t,n){return(n.label??String(n.value)).toLowerCase().includes(t.toLowerCase())}function wp(t,n){if(n)return t?n:n[0]}var $p=class extends pn{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#n=0;#i="";#t;#o;#c;get cursor(){return this.#n}get userInputWithCursor(){if(!this.userInput)return co(["inverse","hidden"],"_");if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let n=this.userInput.slice(0,this.cursor),e=this.userInput.slice(this.cursor,this.cursor+1),r=this.userInput.slice(this.cursor+1);return`${n}${co("inverse",e)}${r}`}get options(){return typeof this.#o=="function"?this.#o():this.#o}constructor(n){super(n),this.#o=n.options,this.#c=n.placeholder;let e=this.options;this.filteredOptions=[...e],this.multiple=n.multiple===!0,this.#t=typeof n.options=="function"?n.filter:n.filter??pp;let r;if(n.initialValue&&Array.isArray(n.initialValue)?this.multiple?r=n.initialValue:r=n.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(r=[this.options[0]?.value]),r)for(let i of r){let o=e.findIndex((s)=>s.value===i);o!==-1&&(this.toggleSelected(i),this.#n=o)}this.focusedValue=this.options[this.#n]?.value,this.on("key",(i,o)=>this.#e(i,o)),this.on("userInput",(i)=>this.#r(i))}_isActionKey(n,e){return n==="\t"||this.multiple&&this.isNavigating&&e.name==="space"&&n!==void 0&&n!==""}#e(n,e){let r=e.name==="up",i=e.name==="down",o=e.name==="return",s=this.userInput===""||this.userInput==="\t",c=this.#c,u=this.options,h=c!==void 0&&c!==""&&u.some((f)=>!f.disabled&&(this.#t?this.#t(c,f):!0));if(e.name==="tab"&&s&&h){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(c,!0),this.isNavigating=!1;return}r||i?(this.#n=te(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=wp(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(e.name==="tab"||this.isNavigating&&e.name==="space")?this.toggleSelected(this.focusedValue):this.isNavigating=!1:(this.focusedValue&&(this.selectedValues=[this.focusedValue]),this.isNavigating=!1)}deselectAll(){this.selectedValues=[]}toggleSelected(n){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(n)?this.selectedValues=this.selectedValues.filter((e)=>e!==n):this.selectedValues=[...this.selectedValues,n]:this.selectedValues=[n])}#r(n){if(n!==this.#i){this.#i=n;let e=this.options;n&&this.#t?this.filteredOptions=e.filter((o)=>this.#t?.(n,o)):this.filteredOptions=[...e];let r=mp(this.focusedValue,this.filteredOptions);this.#n=te(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 ao extends pn{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(t){super(t,!1),this.value=!!t.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(n)=>{this.output.write(Wt.cursor.move(0,-1)),this.value=n,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var bp={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function tf(t){return[...t].map((n)=>bp[n])}function kp(t){let n=new Intl.DateTimeFormat(t,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2000,0,15)),e=[],r="/";for(let i of n)i.type==="literal"?r=i.value.trim()||i.value:(i.type==="year"||i.type==="month"||i.type==="day")&&e.push({type:i.type,len:i.type==="year"?4:2});return{segments:e,separator:r}}function so(t){return Number.parseInt((t||"0").replace(/_/g,"0"),10)||0}function Qr(t){return{year:so(t.year),month:so(t.month),day:so(t.day)}}function ho(t,n){return new Date(t||2001,n||1,0).getDate()}function sf(t){let{year:n,month:e,day:r}=Qr(t);if(!n||n<0||n>9999||!e||e<1||e>12||!r||r<1)return;let i=new Date(Date.UTC(n,e-1,r));if(!(i.getUTCFullYear()!==n||i.getUTCMonth()!==e-1||i.getUTCDate()!==r))return{year:n,month:e,day:r}}function nf(t){let n=sf(t);return n?new Date(Date.UTC(n.year,n.month-1,n.day)):void 0}function Ep(t,n,e,r){let i=e?{year:e.getUTCFullYear(),month:e.getUTCMonth()+1,day:e.getUTCDate()}:null,o=r?{year:r.getUTCFullYear(),month:r.getUTCMonth()+1,day:r.getUTCDate()}:null;return t==="year"?{min:i?.year??1,max:o?.year??9999}:t==="month"?{min:i&&n.year===i.year?i.month:1,max:o&&n.year===o.year?o.month:12}:{min:i&&n.year===i.year&&n.month===i.month?i.day:1,max:o&&n.year===o.year&&n.month===o.month?o.day:ho(n.year,n.month)}}class cf extends pn{#n;#i;#t;#o;#c;#e={segmentIndex:0,positionInSegment:0};#r=!0;#s=null;inlineError="";get segmentCursor(){return{...this.#e}}get segmentValues(){return{...this.#t}}get segments(){return this.#n}get separator(){return this.#i}get formattedValue(){return this.#a(this.#t)}#a(t){return this.#n.map((n)=>t[n.type]).join(this.#i)}#u(){this._setUserInput(this.#a(this.#t)),this._setValue(nf(this.#t)??void 0)}constructor(t){let n=t.format?{segments:tf(t.format),separator:t.separator??"/"}:kp(t.locale),e=t.separator??n.separator,r=t.format?tf(t.format):n.segments,i=t.initialValue??t.defaultValue,o=i?{year:String(i.getUTCFullYear()).padStart(4,"0"),month:String(i.getUTCMonth()+1).padStart(2,"0"),day:String(i.getUTCDate()).padStart(2,"0")}:{year:"____",month:"__",day:"__"},s=r.map((c)=>o[c.type]).join(e);super({...t,initialUserInput:s},!1),this.#n=r,this.#i=e,this.#t=o,this.#o=t.minDate,this.#c=t.maxDate,this.#u(),this.on("cursor",(c)=>this.#d(c)),this.on("key",(c,u)=>this.#m(c,u)),this.on("finalize",()=>this.#p(t))}#h(){let t=Math.max(0,Math.min(this.#e.segmentIndex,this.#n.length-1)),n=this.#n[t];if(n)return this.#e.positionInSegment=Math.max(0,Math.min(this.#e.positionInSegment,n.len-1)),{segment:n,index:t}}#f(t){this.inlineError="",this.#s=null;let n=this.#h();n&&(this.#e.segmentIndex=Math.max(0,Math.min(this.#n.length-1,n.index+t)),this.#e.positionInSegment=0,this.#r=!0)}#g(t){let n=this.#h();if(!n)return;let{segment:e}=n,r=this.#t[e.type],i=!r||r.replace(/_/g,"")==="",o=Number.parseInt((r||"0").replace(/_/g,"0"),10)||0,s=Ep(e.type,Qr(this.#t),this.#o,this.#c),c;i?c=t===1?s.min:s.max:c=Math.max(Math.min(s.max,o+t),s.min),this.#t={...this.#t,[e.type]:c.toString().padStart(e.len,"0")},this.#r=!0,this.#s=null,this.#u()}#d(t){if(t)switch(t){case"right":return this.#f(1);case"left":return this.#f(-1);case"up":return this.#g(1);case"down":return this.#g(-1)}}#m(t,n){if(n?.name==="backspace"||n?.sequence===""||n?.sequence==="\b"||t===""||t==="\b"){this.inlineError="";let e=this.#h();if(!e)return;if(!this.#t[e.segment.type].replace(/_/g,"")){this.#f(-1);return}this.#t[e.segment.type]="_".repeat(e.segment.len),this.#r=!0,this.#e.positionInSegment=0,this.#u();return}if(n?.name==="tab"){this.inlineError="";let e=this.#h();if(!e)return;let r=n.shift?-1:1,i=e.index+r;i>=0&&i<this.#n.length&&(this.#e.segmentIndex=i,this.#e.positionInSegment=0,this.#r=!0);return}if(t&&/^[0-9]$/.test(t)){let e=this.#h();if(!e)return;let{segment:r}=e,i=!this.#t[r.type].replace(/_/g,"");if(this.#r&&this.#s!==null&&!i){let g=this.#s+t,d={...this.#t,[r.type]:g},p=this.#l(d,r);if(p){this.inlineError=p,this.#s=null,this.#r=!1;return}this.inlineError="",this.#t[r.type]=g,this.#s=null,this.#r=!1,this.#u(),e.index<this.#n.length-1&&(this.#e.segmentIndex=e.index+1,this.#e.positionInSegment=0,this.#r=!0);return}this.#r&&!i&&(this.#t[r.type]="_".repeat(r.len),this.#e.positionInSegment=0),this.#r=!1,this.#s=null;let o=this.#t[r.type],s=o.indexOf("_"),c=s>=0?s:Math.min(this.#e.positionInSegment,r.len-1);if(c<0||c>=r.len)return;let u=o.slice(0,c)+t+o.slice(c+1),h=!1;if(c===0&&o==="__"&&(r.type==="month"||r.type==="day")){let g=Number.parseInt(t,10);u=`0${t}`,h=g<=(r.type==="month"?1:2)}if(r.type==="year"&&(u=(o.replace(/_/g,"")+t).padStart(r.len,"_")),!u.includes("_")){let g={...this.#t,[r.type]:u},d=this.#l(g,r);if(d){this.inlineError=d;return}}this.inlineError="",this.#t[r.type]=u;let f=u.includes("_")?void 0:sf(this.#t);if(f){let{year:g,month:d}=f,p=ho(g,d);this.#t={year:String(Math.max(0,Math.min(9999,g))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,d))).padStart(2,"0"),day:String(Math.max(1,Math.min(p,f.day))).padStart(2,"0")}}this.#u();let a=u.indexOf("_");h?(this.#r=!0,this.#s=t):a>=0?this.#e.positionInSegment=a:s>=0&&e.index<this.#n.length-1?(this.#e.segmentIndex=e.index+1,this.#e.positionInSegment=0,this.#r=!0):this.#e.positionInSegment=Math.min(c+1,r.len-1)}}#l(t,n){let{month:e,day:r}=Qr(t);if(n.type==="month"&&(e<0||e>12))return At.date.messages.invalidMonth;if(n.type==="day"&&(r<0||r>31))return At.date.messages.invalidDay(31,"any month")}#p(t){let{year:n,month:e,day:r}=Qr(this.#t);if(n&&e&&r){let i=ho(n,e);this.#t={...this.#t,day:String(Math.min(r,i)).padStart(2,"0")}}this.value=nf(this.#t)??t.defaultValue??void 0}}var Mp=class extends pn{options;cursor=0;#n;getGroupItems(n){return this.options.filter((e)=>e.group===n)}isGroupSelected(n){let e=this.getGroupItems(n),r=this.value;return r===void 0?!1:e.every((i)=>r.includes(i.value))}toggleValue(){let n=this.options[this.cursor];if(n!==void 0)if(this.value===void 0&&(this.value=[]),n.group===!0){let e=n.value,r=this.getGroupItems(e);this.isGroupSelected(e)?this.value=this.value.filter((i)=>r.findIndex((o)=>o.value===i)===-1):this.value=[...this.value,...r.map((i)=>i.value)],this.value=Array.from(new Set(this.value))}else{let e=this.value.includes(n.value);this.value=e?this.value.filter((r)=>r!==n.value):[...this.value,n.value]}}constructor(n){super(n,!1);let{options:e}=n;this.#n=n.selectableGroups!==!1,this.options=Object.entries(e).flatMap(([r,i])=>[{value:r,group:!0,label:r},...i.map((o)=>({...o,group:r}))]),this.value=[...n.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:r})=>r===n.cursorAt),this.#n?0:1),this.on("cursor",(r)=>{switch(r){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let i=this.options[this.cursor]?.group===!0;!this.#n&&i&&(this.cursor=this.cursor===0?this.options.length-1:this.cursor-1);break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let i=this.options[this.cursor]?.group===!0;!this.#n&&i&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},vp=new Set(["up","down","left","right"]);class uf extends pn{#n=!1;#i;focused="editor";get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t=this.userInput;if(this.cursor>=t.length)return`${t}█`;let n=t.slice(0,this.cursor),e=t.slice(this.cursor,this.cursor+1),r=t.slice(this.cursor+1);return e===`
|
|
161
|
-
`?`${
|
|
162
|
-
${r}`:`${
|
|
163
|
-
`),this._cursor++,!1);let
|
|
160
|
+
`)),this._prevFrame=t;return}}this.output.write(Wt.erase.down())}this.output.write(t),this.state==="initial"&&(this.state="active"),this._prevFrame=t}}}function $p(t,e){if(t===void 0||e.length===0)return 0;let n=e.findIndex((r)=>r.value===t);return n!==-1?n:0}function kp(t,e){return(e.label??String(e.value)).toLowerCase().includes(t.toLowerCase())}function Ep(t,e){if(e)return t?e:e[0]}var Mp=class extends me{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#e=0;#i="";#t;#o;#c;get cursor(){return this.#e}get userInputWithCursor(){if(!this.userInput)return ao(["inverse","hidden"],"_");if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let e=this.userInput.slice(0,this.cursor),n=this.userInput.slice(this.cursor,this.cursor+1),r=this.userInput.slice(this.cursor+1);return`${e}${ao("inverse",n)}${r}`}get options(){return typeof this.#o=="function"?this.#o():this.#o}constructor(e){super(e),this.#o=e.options,this.#c=e.placeholder;let n=this.options;this.filteredOptions=[...n],this.multiple=e.multiple===!0,this.#t=typeof e.options=="function"?e.filter:e.filter??kp;let r;if(e.initialValue&&Array.isArray(e.initialValue)?this.multiple?r=e.initialValue:r=e.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(r=[this.options[0]?.value]),r)for(let i of r){let o=n.findIndex((s)=>s.value===i);o!==-1&&(this.toggleSelected(i),this.#e=o)}this.focusedValue=this.options[this.#e]?.value,this.on("key",(i,o)=>this.#n(i,o)),this.on("userInput",(i)=>this.#r(i))}_isActionKey(e,n){return e==="\t"||this.multiple&&this.isNavigating&&n.name==="space"&&e!==void 0&&e!==""}#n(e,n){let r=n.name==="up",i=n.name==="down",o=n.name==="return",s=this.userInput===""||this.userInput==="\t",c=this.#c,u=this.options,h=c!==void 0&&c!==""&&u.some((f)=>!f.disabled&&(this.#t?this.#t(c,f):!0));if(n.name==="tab"&&s&&h){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(c,!0),this.isNavigating=!1;return}r||i?(this.#e=De(this.#e,r?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#e]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):o?this.value=Ep(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(n.name==="tab"||this.isNavigating&&n.name==="space")?this.toggleSelected(this.focusedValue):this.isNavigating=!1:(this.focusedValue&&(this.selectedValues=[this.focusedValue]),this.isNavigating=!1)}deselectAll(){this.selectedValues=[]}toggleSelected(e){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(e)?this.selectedValues=this.selectedValues.filter((n)=>n!==e):this.selectedValues=[...this.selectedValues,e]:this.selectedValues=[e])}#r(e){if(e!==this.#i){this.#i=e;let n=this.options;e&&this.#t?this.filteredOptions=n.filter((o)=>this.#t?.(e,o)):this.filteredOptions=[...n];let r=$p(this.focusedValue,this.filteredOptions);this.#e=De(r,0,this.filteredOptions);let i=this.filteredOptions[this.#e];i&&!i.disabled?this.focusedValue=i.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}};class po extends me{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(t){super(t,!1),this.value=!!t.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(e)=>{this.output.write(Wt.cursor.move(0,-1)),this.value=e,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var yp={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function sf(t){return[...t].map((e)=>yp[e])}function vp(t){let e=new Intl.DateTimeFormat(t,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2000,0,15)),n=[],r="/";for(let i of e)i.type==="literal"?r=i.value.trim()||i.value:(i.type==="year"||i.type==="month"||i.type==="day")&&n.push({type:i.type,len:i.type==="year"?4:2});return{segments:n,separator:r}}function fo(t){return Number.parseInt((t||"0").replace(/_/g,"0"),10)||0}function _r(t){return{year:fo(t.year),month:fo(t.month),day:fo(t.day)}}function go(t,e){return new Date(t||2001,e||1,0).getDate()}function af(t){let{year:e,month:n,day:r}=_r(t);if(!e||e<0||e>9999||!n||n<1||n>12||!r||r<1)return;let i=new Date(Date.UTC(e,n-1,r));if(!(i.getUTCFullYear()!==e||i.getUTCMonth()!==n-1||i.getUTCDate()!==r))return{year:e,month:n,day:r}}function cf(t){let e=af(t);return e?new Date(Date.UTC(e.year,e.month-1,e.day)):void 0}function Sp(t,e,n,r){let i=n?{year:n.getUTCFullYear(),month:n.getUTCMonth()+1,day:n.getUTCDate()}:null,o=r?{year:r.getUTCFullYear(),month:r.getUTCMonth()+1,day:r.getUTCDate()}:null;return t==="year"?{min:i?.year??1,max:o?.year??9999}:t==="month"?{min:i&&e.year===i.year?i.month:1,max:o&&e.year===o.year?o.month:12}:{min:i&&e.year===i.year&&e.month===i.month?i.day:1,max:o&&e.year===o.year&&e.month===o.month?o.day:go(e.year,e.month)}}class lf extends me{#e;#i;#t;#o;#c;#n={segmentIndex:0,positionInSegment:0};#r=!0;#s=null;inlineError="";get segmentCursor(){return{...this.#n}}get segmentValues(){return{...this.#t}}get segments(){return this.#e}get separator(){return this.#i}get formattedValue(){return this.#a(this.#t)}#a(t){return this.#e.map((e)=>t[e.type]).join(this.#i)}#u(){this._setUserInput(this.#a(this.#t)),this._setValue(cf(this.#t)??void 0)}constructor(t){let e=t.format?{segments:sf(t.format),separator:t.separator??"/"}:vp(t.locale),n=t.separator??e.separator,r=t.format?sf(t.format):e.segments,i=t.initialValue??t.defaultValue,o=i?{year:String(i.getUTCFullYear()).padStart(4,"0"),month:String(i.getUTCMonth()+1).padStart(2,"0"),day:String(i.getUTCDate()).padStart(2,"0")}:{year:"____",month:"__",day:"__"},s=r.map((c)=>o[c.type]).join(n);super({...t,initialUserInput:s},!1),this.#e=r,this.#i=n,this.#t=o,this.#o=t.minDate,this.#c=t.maxDate,this.#u(),this.on("cursor",(c)=>this.#d(c)),this.on("key",(c,u)=>this.#m(c,u)),this.on("finalize",()=>this.#p(t))}#h(){let t=Math.max(0,Math.min(this.#n.segmentIndex,this.#e.length-1)),e=this.#e[t];if(e)return this.#n.positionInSegment=Math.max(0,Math.min(this.#n.positionInSegment,e.len-1)),{segment:e,index:t}}#f(t){this.inlineError="",this.#s=null;let e=this.#h();e&&(this.#n.segmentIndex=Math.max(0,Math.min(this.#e.length-1,e.index+t)),this.#n.positionInSegment=0,this.#r=!0)}#l(t){let e=this.#h();if(!e)return;let{segment:n}=e,r=this.#t[n.type],i=!r||r.replace(/_/g,"")==="",o=Number.parseInt((r||"0").replace(/_/g,"0"),10)||0,s=Sp(n.type,_r(this.#t),this.#o,this.#c),c;i?c=t===1?s.min:s.max:c=Math.max(Math.min(s.max,o+t),s.min),this.#t={...this.#t,[n.type]:c.toString().padStart(n.len,"0")},this.#r=!0,this.#s=null,this.#u()}#d(t){if(t)switch(t){case"right":return this.#f(1);case"left":return this.#f(-1);case"up":return this.#l(1);case"down":return this.#l(-1)}}#m(t,e){if(e?.name==="backspace"||e?.sequence===""||e?.sequence==="\b"||t===""||t==="\b"){this.inlineError="";let n=this.#h();if(!n)return;if(!this.#t[n.segment.type].replace(/_/g,"")){this.#f(-1);return}this.#t[n.segment.type]="_".repeat(n.segment.len),this.#r=!0,this.#n.positionInSegment=0,this.#u();return}if(e?.name==="tab"){this.inlineError="";let n=this.#h();if(!n)return;let r=e.shift?-1:1,i=n.index+r;i>=0&&i<this.#e.length&&(this.#n.segmentIndex=i,this.#n.positionInSegment=0,this.#r=!0);return}if(t&&/^[0-9]$/.test(t)){let n=this.#h();if(!n)return;let{segment:r}=n,i=!this.#t[r.type].replace(/_/g,"");if(this.#r&&this.#s!==null&&!i){let l=this.#s+t,d={...this.#t,[r.type]:l},p=this.#g(d,r);if(p){this.inlineError=p,this.#s=null,this.#r=!1;return}this.inlineError="",this.#t[r.type]=l,this.#s=null,this.#r=!1,this.#u(),n.index<this.#e.length-1&&(this.#n.segmentIndex=n.index+1,this.#n.positionInSegment=0,this.#r=!0);return}this.#r&&!i&&(this.#t[r.type]="_".repeat(r.len),this.#n.positionInSegment=0),this.#r=!1,this.#s=null;let o=this.#t[r.type],s=o.indexOf("_"),c=s>=0?s:Math.min(this.#n.positionInSegment,r.len-1);if(c<0||c>=r.len)return;let u=o.slice(0,c)+t+o.slice(c+1),h=!1;if(c===0&&o==="__"&&(r.type==="month"||r.type==="day")){let l=Number.parseInt(t,10);u=`0${t}`,h=l<=(r.type==="month"?1:2)}if(r.type==="year"&&(u=(o.replace(/_/g,"")+t).padStart(r.len,"_")),!u.includes("_")){let l={...this.#t,[r.type]:u},d=this.#g(l,r);if(d){this.inlineError=d;return}}this.inlineError="",this.#t[r.type]=u;let f=u.includes("_")?void 0:af(this.#t);if(f){let{year:l,month:d}=f,p=go(l,d);this.#t={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(p,f.day))).padStart(2,"0")}}this.#u();let a=u.indexOf("_");h?(this.#r=!0,this.#s=t):a>=0?this.#n.positionInSegment=a:s>=0&&n.index<this.#e.length-1?(this.#n.segmentIndex=n.index+1,this.#n.positionInSegment=0,this.#r=!0):this.#n.positionInSegment=Math.min(c+1,r.len-1)}}#g(t,e){let{month:n,day:r}=_r(t);if(e.type==="month"&&(n<0||n>12))return Tt.date.messages.invalidMonth;if(e.type==="day"&&(r<0||r>31))return Tt.date.messages.invalidDay(31,"any month")}#p(t){let{year:e,month:n,day:r}=_r(this.#t);if(e&&n&&r){let i=go(e,n);this.#t={...this.#t,day:String(Math.min(r,i)).padStart(2,"0")}}this.value=cf(this.#t)??t.defaultValue??void 0}}var Fp=class extends me{options;cursor=0;#e;getGroupItems(e){return this.options.filter((n)=>n.group===e)}isGroupSelected(e){let n=this.getGroupItems(e),r=this.value;return r===void 0?!1:n.every((i)=>r.includes(i.value))}toggleValue(){let e=this.options[this.cursor];if(e!==void 0)if(this.value===void 0&&(this.value=[]),e.group===!0){let n=e.value,r=this.getGroupItems(n);this.isGroupSelected(n)?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 n=this.value.includes(e.value);this.value=n?this.value.filter((r)=>r!==e.value):[...this.value,e.value]}}constructor(e){super(e,!1);let{options:n}=e;this.#e=e.selectableGroups!==!1,this.options=Object.entries(n).flatMap(([r,i])=>[{value:r,group:!0,label:r},...i.map((o)=>({...o,group:r}))]),this.value=[...e.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:r})=>r===e.cursorAt),this.#e?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.#e&&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.#e&&i&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},Ip=new Set(["up","down","left","right"]);class gf extends me{#e=!1;#i;focused="editor";get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t=this.userInput;if(this.cursor>=t.length)return`${t}█`;let e=t.slice(0,this.cursor),n=t.slice(this.cursor,this.cursor+1),r=t.slice(this.cursor+1);return n===`
|
|
161
|
+
`?`${e}█
|
|
162
|
+
${r}`:`${e}${ao("inverse",n)}${r}`}get cursor(){return this._cursor}#t(t){if(this.userInput.length===0){this._setUserInput(t);return}this._setUserInput(this.userInput.slice(0,this.cursor)+t+this.userInput.slice(this.cursor))}#o(t){let e=this.value??"";switch(t){case"up":this._cursor=qr(this._cursor,0,-1,e);return;case"down":this._cursor=qr(this._cursor,0,1,e);return;case"left":this._cursor=qr(this._cursor,-1,0,e);return;case"right":this._cursor=qr(this._cursor,1,0,e);return}}_shouldSubmit(t,e){if(this.#i)return this.focused==="submit"?!0:(this.#t(`
|
|
163
|
+
`),this._cursor++,!1);let n=this.#e;return this.#e=!0,n&&this.cursor===this.userInput.length?(this.userInput[this.cursor-1]===`
|
|
164
164
|
`&&(this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--),!0):(this.#t(`
|
|
165
|
-
`),this._cursor++,!1)}constructor(t){let
|
|
166
|
-
`);k.push(R),
|
|
165
|
+
`),this._cursor++,!1)}constructor(t){let e=t.initialUserInput??t.initialValue;super({...t,initialUserInput:e},!1),e!==void 0&&(this._cursor=e.length),this.#i=t.showSubmit??!1,this.on("key",(n,r)=>{if(r?.name&&Ip.has(r.name)){this.#e=!1,this.#o(r.name);return}if(n==="\t"&&this.#i){this.focused=this.focused==="editor"?"submit":"editor";return}if(r?.name!=="return"){if(this.#e=!1,r?.name==="backspace"&&this.cursor>0){this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--;return}if(r?.name==="delete"&&this.cursor<this.userInput.length){this._setUserInput(this.userInput.slice(0,this.cursor)+this.userInput.slice(this.cursor+1));return}n&&(this.#i&&this.focused==="submit"&&(this.focused="editor"),this.#t(n??""),this._cursor++)}}),this.on("userInput",(n)=>{this._setValue(n)}),this.on("finalize",()=>{this.value||(this.value=t.defaultValue),this.value===void 0&&(this.value="")})}}class wo extends me{options;cursor=0;get _value(){return this.options[this.cursor]?.value}get _enabledOptions(){return this.options.filter((t)=>t.disabled!==!0)}toggleAll(){let t=this._enabledOptions,e=this.value!==void 0&&this.value.length===t.length;this.value=e?[]:t.map((n)=>n.value)}toggleInvert(){let t=this.value;if(!t)return;let e=this._enabledOptions.filter((n)=>!t.includes(n.value));this.value=e.map((n)=>n.value)}toggleValue(){this.value===void 0&&(this.value=[]);let t=this.value.includes(this._value);this.value=t?this.value.filter((e)=>e!==this._value):[...this.value,this._value]}constructor(t){super(t,!1),this.options=t.options,this.value=[...t.initialValues??[]];let e=Math.max(this.options.findIndex(({value:n})=>n===t.cursorAt),0);this.cursor=this.options[e]?.disabled?De(e,1,this.options):e,this.on("key",(n,r)=>{r.name==="a"&&this.toggleAll(),r.name==="i"&&this.toggleInvert()}),this.on("cursor",(n)=>{switch(n){case"left":case"up":this.cursor=De(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=De(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}import{styleText as S,stripVTControlCharacters as V$}from"node:util";import zt from"node:process";var Ef=ir(ho(),1);function Np(){if(zt.platform!=="win32")return zt.env.TERM!=="linux";return Boolean(zt.env.CI)||Boolean(zt.env.WT_SESSION)||Boolean(zt.env.TERMINUS_SUBLIME)||zt.env.ConEmuTask==="{cmd::Cmder}"||zt.env.TERM_PROGRAM==="Terminus-Sublime"||zt.env.TERM_PROGRAM==="vscode"||zt.env.TERM==="xterm-256color"||zt.env.TERM==="alacritty"||zt.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var Hp=Np();var gt=(t,e)=>Hp?t:e,Op=gt("◆","*"),jp=gt("■","x"),Rp=gt("▲","x"),Mf=gt("◇","o"),Gp=gt("┌","T"),yt=gt("│","|"),en=gt("└","—"),B$=gt("┐","T"),D$=gt("┘","—"),df=gt("●",">"),mf=gt("○"," "),Lp=gt("◻","[•]"),pf=gt("◼","[+]"),wf=gt("◻","[ ]"),t1=gt("▪","•"),bf=gt("─","-"),Pp=gt("╮","+"),Kp=gt("├","+"),Jp=gt("╯","+"),Ap=gt("╰","+"),e1=gt("╭","+"),n1=gt("●","•"),r1=gt("◆","*"),i1=gt("▲","!"),o1=gt("■","x"),yf=(t)=>{switch(t){case"initial":case"active":return S("cyan",Op);case"cancel":return S("red",jp);case"error":return S("yellow",Rp);case"submit":return S("green",Mf)}},Tp=(t)=>{switch(t){case"initial":case"active":return S("cyan",yt);case"cancel":return S("red",yt);case"error":return S("yellow",yt);case"submit":return S("green",yt)}};function Up(t,e){let n=[`${e?`${S("cyan",yt)} `:""}${t.join(" • ")}`];return e&&n.push(S("cyan",en)),n}var $f=(t,e,n,r,i,o=!1)=>{let s=e,c=0;if(o)for(let u=r-1;u>=n;u--){let h=t[u];if(h&&(s-=h.length),c++,s<=i)break}else for(let u=n;u<r;u++){let h=t[u];if(h&&(s-=h.length),c++,s<=i)break}return{lineCount:s,removals:c}},kf=({cursor:t,options:e,style:n,output:r=process.stdout,maxItems:i=Number.POSITIVE_INFINITY,columnPadding:o=0,rowPadding:s=4})=>{let c=Xr(r)-o,u=mo(r),h=S("dim","..."),f=Math.max(u-s,0),a=Math.max(Math.min(i,f),5),l=0;t>=a-3&&(l=Math.max(Math.min(t-a+3,e.length-a),0));let d=a<e.length&&l>0,p=a<e.length&&l+a<e.length,g=Math.min(l+a,e.length),k=[],y=0;d&&y++,p&&y++;let I=l+(d?1:0),E=g-(p?1:0);for(let b=I;b<E;b++){let O=e[b],$=O?n(O,b===t):"",R=Se($,c,{hard:!0,trim:!1}).split(`
|
|
166
|
+
`);k.push(R),y+=R.length}if(y>f){let b=0,O=0,$=y,R=t-I,H=f,P=()=>$f(k,$,0,R,H),G=()=>$f(k,$,R+1,k.length,H,!0);d?({lineCount:$,removals:b}=P(),$>H&&(p||(H-=1),{lineCount:$,removals:O}=G())):(p||(H-=1),{lineCount:$,removals:O}=G(),$>H&&(H-=1,{lineCount:$,removals:b}=P())),b>0&&(d=!0,k.splice(0,b)),O>0&&(p=!0,k.splice(k.length-O,O))}let v=[];d&&v.push(h);for(let b of k)for(let O of b)v.push(O);return p&&v.push(h),v};var bo=(t)=>{let e=t.active??"Yes",n=t.inactive??"No";return new po({active:e,inactive:n,signal:t.signal,input:t.input,output:t.output,initialValue:t.initialValue??!0,render(){let r=t.withGuide??Tt.withGuide,i=`${yf(this.state)} `,o=r?`${S("gray",yt)} `:"",s=zn(t.output,t.message,o,i),c=`${r?`${S("gray",yt)}
|
|
167
167
|
`:""}${s}
|
|
168
|
-
`,u=this.value?n
|
|
169
|
-
${S("gray",yt)}`:""}`}default:{let h=r?`${S("cyan",yt)} `:"",f=r?S("cyan",
|
|
168
|
+
`,u=this.value?e:n;switch(this.state){case"submit":{let h=r?`${S("gray",yt)} `:"";return`${c}${h}${S("dim",u)}`}case"cancel":{let h=r?`${S("gray",yt)} `:"";return`${c}${h}${S(["strikethrough","dim"],u)}${r?`
|
|
169
|
+
${S("gray",yt)}`:""}`}default:{let h=r?`${S("cyan",yt)} `:"",f=r?S("cyan",en):"";return`${c}${h}${this.value?`${S("green",df)} ${e}`:`${S("dim",mf)} ${S("dim",e)}`}${t.vertical?r?`
|
|
170
170
|
${S("cyan",yt)} `:`
|
|
171
|
-
`:` ${S("dim","/")} `}${this.value?`${S("dim",
|
|
171
|
+
`:` ${S("dim","/")} `}${this.value?`${S("dim",mf)} ${S("dim",n)}`:`${S("green",df)} ${n}`}
|
|
172
172
|
${f}
|
|
173
|
-
`}}}}).prompt()};var
|
|
174
|
-
`).map((
|
|
175
|
-
`),
|
|
176
|
-
${S("reset",S("dim",`Press ${S(["gray","bgWhite","inverse"]," space ")} to select, ${S("gray",S("bgWhite",S("inverse"," enter ")))} to submit`))}`},render(){let i=t.withGuide??
|
|
173
|
+
`}}}}).prompt()};var Wp=[`${S("dim","↑/↓")} to navigate`,`${S("dim","Space:")} select`,`${S("dim","Enter:")} confirm`],Yn=(t,e)=>t.split(`
|
|
174
|
+
`).map((n)=>e(n)).join(`
|
|
175
|
+
`),vf=(t)=>{let e=(i,o)=>{let s=i.label??String(i.value);return o==="disabled"?`${S("gray",wf)} ${Yn(s,(c)=>S(["strikethrough","gray"],c))}${i.hint?` ${S("dim",`(${i.hint??"disabled"})`)}`:""}`:o==="active"?`${S("cyan",Lp)} ${s}${i.hint?` ${S("dim",`(${i.hint})`)}`:""}`:o==="selected"?`${S("green",pf)} ${Yn(s,(c)=>S("dim",c))}${i.hint?` ${S("dim",`(${i.hint})`)}`:""}`:o==="cancelled"?`${Yn(s,(c)=>S(["strikethrough","dim"],c))}`:o==="active-selected"?`${S("green",pf)} ${s}${i.hint?` ${S("dim",`(${i.hint})`)}`:""}`:o==="submitted"?`${Yn(s,(c)=>S("dim",c))}`:`${S("dim",wf)} ${Yn(s,(c)=>S("dim",c))}`},n=t.required??!0,r=t.showInstructions??!0;return new wo({options:t.options,signal:t.signal,input:t.input,output:t.output,initialValues:t.initialValues,required:n,cursorAt:t.cursorAt,validate(i){if(n&&(i===void 0||i.length===0))return`Please select at least one option.
|
|
176
|
+
${S("reset",S("dim",`Press ${S(["gray","bgWhite","inverse"]," space ")} to select, ${S("gray",S("bgWhite",S("inverse"," enter ")))} to submit`))}`},render(){let i=t.withGuide??Tt.withGuide,o=zn(t.output,t.message,i?`${Tp(this.state)} `:"",`${yf(this.state)} `),s=`${i?`${S("gray",yt)}
|
|
177
177
|
`:""}${o}
|
|
178
|
-
`,c=this.value??[],u=(h,f)=>{if(h.disabled)return
|
|
178
|
+
`,c=this.value??[],u=(h,f)=>{if(h.disabled)return e(h,"disabled");let a=c.includes(h.value);return f&&a?e(h,"active-selected"):a?e(h,"selected"):e(h,f?"active":"inactive")};switch(this.state){case"submit":{let h=this.options.filter(({value:a})=>c.includes(a)).map((a)=>e(a,"submitted")).join(S("dim",", "))||S("dim","none"),f=zn(t.output,h,i?`${S("gray",yt)} `:"");return`${s}${f}`}case"cancel":{let h=this.options.filter(({value:a})=>c.includes(a)).map((a)=>e(a,"cancelled")).join(S("dim",", "));if(h.trim()==="")return`${s}${S("gray",yt)}`;let f=zn(t.output,h,i?`${S("gray",yt)} `:"");return`${s}${f}${i?`
|
|
179
179
|
${S("gray",yt)}`:""}`}case"error":{let h=i?`${S("yellow",yt)} `:"",f=this.error.split(`
|
|
180
|
-
`).map((d,p)=>p===0?`${i?`${S("yellow",
|
|
180
|
+
`).map((d,p)=>p===0?`${i?`${S("yellow",en)} `:""}${S("yellow",d)}`:` ${d}`).join(`
|
|
181
181
|
`),a=s.split(`
|
|
182
|
-
`).length,
|
|
183
|
-
`).length+1;return`${s}${h}${
|
|
182
|
+
`).length,l=f.split(`
|
|
183
|
+
`).length+1;return`${s}${h}${kf({output:t.output,options:this.options,cursor:this.cursor,maxItems:t.maxItems,columnPadding:h.length,rowPadding:a+l,style:u}).join(`
|
|
184
184
|
${h}`)}
|
|
185
185
|
${f}
|
|
186
186
|
`}default:{let h=i?`${S("cyan",yt)} `:"",f=s.split(`
|
|
187
|
-
`).length,a=r?
|
|
188
|
-
`),d=a.length+1;return`${s}${h}${
|
|
187
|
+
`).length,a=r?Up(Wp,i):i?[S("cyan",en)]:[],l=a.join(`
|
|
188
|
+
`),d=a.length+1;return`${s}${h}${kf({output:t.output,options:this.options,cursor:this.cursor,maxItems:t.maxItems,columnPadding:h.length,rowPadding:f+d,style:u}).join(`
|
|
189
189
|
${h}`)}
|
|
190
|
-
${
|
|
191
|
-
`}}}}).prompt()};var
|
|
190
|
+
${l}
|
|
191
|
+
`}}}}).prompt()};var Cr=(t="",e)=>{let n=e?.output??process.stdout,r=e?.withGuide??Tt.withGuide?`${S("gray",en)} `:"";n.write(`${r}${S("red",t)}
|
|
192
192
|
|
|
193
|
-
`)},
|
|
194
|
-
`)},
|
|
195
|
-
${S("gray",
|
|
193
|
+
`)},Sf=(t="",e)=>{let n=e?.output??process.stdout,r=e?.withGuide??Tt.withGuide?`${S("gray",Gp)} `:"";n.write(`${r}${t}
|
|
194
|
+
`)},Ff=(t="",e)=>{let n=e?.output??process.stdout,r=e?.withGuide??Tt.withGuide?`${S("gray",yt)}
|
|
195
|
+
${S("gray",en)} `:"";n.write(`${r}${t}
|
|
196
196
|
|
|
197
|
-
`)};var
|
|
198
|
-
`),o=i.reduce((u,h)=>Math.max(
|
|
199
|
-
`).map(o),""],c=
|
|
197
|
+
`)};var Qp=(t)=>t,qp=(t,e,n)=>{let r={hard:!0,trim:!1},i=Se(t,e,r).split(`
|
|
198
|
+
`),o=i.reduce((u,h)=>Math.max(Jt(h),u),0),s=i.map(n).reduce((u,h)=>Math.max(Jt(h),u),0),c=e-(s-o);return Se(t,c,r)},Vr=(t="",e="",n)=>{let r=n?.output??zt.stdout,i=n?.withGuide??Tt.withGuide,o=n?.format??Qp,s=["",...qp(t,Xr(r)-6,o).split(`
|
|
199
|
+
`).map(o),""],c=Jt(e),u=Math.max(s.reduce((l,d)=>{let p=Jt(d);return p>l?p:l},0),c)+2,h=s.map((l)=>`${S("gray",yt)} ${l}${" ".repeat(u-Jt(l))}${S("gray",yt)}`).join(`
|
|
200
200
|
`),f=i?`${S("gray",yt)}
|
|
201
|
-
`:"",a=i?
|
|
201
|
+
`:"",a=i?Kp:Ap;r.write(`${f}${S("green",Mf)} ${S("reset",e)} ${S("gray",bf.repeat(Math.max(u-c-1,1))+Pp)}
|
|
202
202
|
${h}
|
|
203
|
-
${S("gray",a+
|
|
204
|
-
`)};var
|
|
205
|
-
`)}}function
|
|
206
|
-
${t} palettes installed — open a new tab, or reload your terminal config`)}function
|
|
207
|
-
`))}function
|
|
208
|
-
`))}function
|
|
209
|
-
${
|
|
210
|
-
${
|
|
211
|
-
`)}`)}function
|
|
212
|
-
`),`installed ${
|
|
213
|
-
`),"next"),
|
|
214
|
-
`))}async function
|
|
215
|
-
`),`wiring ${a.join(", ")}`),!
|
|
216
|
-
`)}return["Usage: ttheme <command>","",
|
|
217
|
-
`)}async function
|
|
203
|
+
${S("gray",a+bf.repeat(u+2)+Jp)}
|
|
204
|
+
`)};var s1={light:gt("─","-"),heavy:gt("━","="),block:gt("█","#")};var c1=[`${S("dim","↑/↓")} to navigate`,`${S("dim","Enter:")} confirm`];var u1=`${S("gray",yt)} `;import{existsSync as Bp}from"node:fs";import{openSync as Zp,writeSync as _p}from"node:fs";import{ReadStream as Xp}from"node:tty";var Nf=["10","11","12","17",...Array.from({length:16},(t,e)=>`4;${e}`)];function Bn(t=process.env){return Boolean(t.NO_COLOR)||t.TERM==="dumb"}function xr(t){return[`\x1B]11;${t.background}\x1B\\`,`\x1B]10;${t.foreground}\x1B\\`,`\x1B]12;${t.cursor}\x1B\\`,`\x1B]17;${t.selection}\x1B\\`,...t.ansi.map((e,n)=>`\x1B]4;${n};${e}\x1B\\`)].join("")}function Hf(t){let e=new Map;for(let n of t.split("\x1B")){let r=n.match(/^\](\d+(?:;\d+)?);(rgba?:[0-9a-fA-F/]+)/),[,i,o]=r??[];if(i&&o)e.set(i,o)}return e}function Of(t){return[...t].map(([e,n])=>`\x1B]${e};${n}\x1B\\`).join("")}async function jf(){let t,e;try{t=Zp("/dev/tty","r+"),e=new Xp(t),e.setRawMode(!0)}catch{return new Map}try{_p(t,Nf.map((r)=>`\x1B]${r};?\x1B\\`).join(""));let n="";return await new Promise((r)=>{let i=setTimeout(r,120);e.on("data",(o)=>{if(n+=o.toString(),Hf(n).size>=Nf.length)clearTimeout(i),r()})}),Hf(n)}finally{e.setRawMode(!1),e.destroy()}}function nn(t){let e=t.replace("#","");return[e.slice(0,2),e.slice(2,4),e.slice(4,6)].map((n)=>Number.parseInt(n,16)).join(";")}function Rf(t,e){return`\x1B[48;2;${nn(e)}m ${t} \x1B[0m`}function $o(t,e){return`\x1B[48;2;${nn(t)};38;2;${nn(e)}m ● \x1B[0m`}function Gf(t){return`\x1B[38;2;${nn(t)}m`}function ko(t,e){return`\x1B[48;2;${nn(e)}m${t.map((n)=>`\x1B[38;2;${nn(n)}m▄`).join("")} \x1B[0m`}function zr(t,e){let n=e.toLowerCase();return[t.name,t.group,t.native??""].some((r)=>r.toLowerCase().includes(n))}function Pf(t,e,n){let r=n.trim(),i=[],o=new Set;for(let s of t){if(s.default||o.has(s.group))continue;o.add(s.group);let c=t.filter((f)=>!f.default&&f.group===s.group),u=r?c.filter((f)=>zr(f,r)):c;if(r&&u.length===0)continue;let h=r.length>0||e.has(s.group);if(i.push({kind:"group",name:s.group,native:s.native,lead:c.find((f)=>f.lead)??s,expanded:h,count:u.length}),h)i.push(...u.map((f)=>({kind:"palette",entry:f})))}return i}function Cp(t,e){let n=e.trim(),r=new Set(t.filter((i)=>!i.default&&(n===""||zr(i,n))).map((i)=>i.group));return Pf(t,new Set,"").filter((i)=>i.kind==="group"&&r.has(i.name))}function Vp(t){let e=t.findIndex((n)=>n.kind==="palette");return e===-1?0:e}var te="\x1B[0m",rn="\x1B[2m",xp="\x1B[1m",Lf="\x1B[1;7m",zp="\x1B[36m",Yp="\x1B[33m";function Kf(t){return t==="decode"||t==="glitch"?t:"typewriter"}class Eo extends me{picked;scope;entries;named;series;seriesPad;expanded=new Set;rows=[];cursor=0;top=0;maxItems;color;lastInput="";lastFocused="";onFocus;example="";fx;fxStep=0;fxSeed=0;fxTimer;constructor(t){super({render:()=>this.draw(),input:t.input,output:t.output,validate:t.required?()=>this.picked.size===0?`pick at least one ${this.scope}`:void 0:void 0},!0);this.entries=t.entries,this.scope=t.scope??"palette",this.picked=new Set(t.installed??[]),this.named=t.entries.filter((n)=>!n.default),this.series=[...new Set(this.named.map((n)=>n.group))],this.seriesPad=Math.max(0,...this.series.map((n)=>n.length)),this.maxItems=t.maxItems??12,this.color=t.color??!0,this.fx=t.fx??"typewriter",this.onFocus=t.onFocus,this.rollExample();let e=setInterval(()=>{this.rollExample(),this.fxStep=8,this.output.emit("resize")},3000);e.unref?.(),this.once("finalize",()=>{clearInterval(e),clearTimeout(this.fxTimer)}),this.rebuild("first"),this.on("cursor",(n)=>{if(n==="up")this.move(-1);else if(n==="down")this.move(1);else if(n==="left")this.fold(!1);else if(n==="right")this.fold(!0)}),this.on("userInput",(n)=>{if(n!==this.lastInput)this.lastInput=n,this.rebuild("keep")}),this.on("key",(n,r)=>{if(r?.name==="space")this.pick(this.rows[this.cursor])})}_isActionKey(t){return t==="\t"||t===" "}members(t){let e=this.scope==="palette"?this.userInput.trim():"";return this.named.filter((n)=>n.group===t&&(e===""||zr(n,e)))}everyone(t){return t.flatMap((e)=>e.kind==="group"?this.members(e.name):[])}pick(t){let e=t?.kind==="palette"?[t.entry.name]:t?.kind==="group"?this.members(t.name).map((r)=>r.name):t?.kind==="all"?this.everyone(this.rows).map((r)=>r.name):[];if(e.length===0)return;let n=e.some((r)=>!this.picked.has(r));for(let r of e)if(n)this.picked.add(r);else this.picked.delete(r)}pickedIn(t){return this.members(t).filter((e)=>this.picked.has(e.name)).length}pickedCount(){if(this.scope==="palette")return this.picked.size;return this.series.filter((t)=>this.members(t).every((e)=>this.picked.has(e.name))).length}rollExample(){let t=this.named[Math.floor(Math.random()*this.named.length)],e=this.series[Math.floor(Math.random()*this.series.length)];if(!t||!e){this.example="";return}let n=`${t.name} | ${e}`;this.example=n.length>30?`${n.slice(0,29)}…`:n,this.fxSeed=Math.floor(Math.random()*997)}animatedExample(){if(this.fxStep===0)return this.example;if(!this.fxTimer)this.fxTimer=setTimeout(()=>{this.fxTimer=void 0,this.fxStep-=1,this.output.emit("resize")},60),this.fxTimer.unref?.();let t=Math.floor(this.example.length*(8-this.fxStep)/8);if(this.fx==="typewriter")return`${this.example.slice(0,t)}▏`;let e=this.fx==="decode"?"abcdefghijklmnopqrstuvwxyz":"▓▒░#*+=<>?/-_",n=this.fx==="decode"?(r)=>!/[a-z0-9]/i.test(r):(r)=>r===" ";return[...this.example].map((r,i)=>i+(i*7+this.fxSeed)%3<t||n(r)?r:e[Math.floor(Math.random()*e.length)]??r).join("")}sync(){let t=this.rows[this.cursor],e=t?.kind==="palette"?t.entry:t?.kind==="group"&&this.scope==="series"?t.lead:void 0;if(e&&e.name!==this.lastFocused)this.lastFocused=e.name,this.onFocus?.(e)}rebuild(t){let e=this.rows[this.cursor],n=this.scope==="series"?Cp(this.entries,this.userInput):Pf(this.entries,this.expanded,this.userInput),r=n.length>0?Vp(n)+1:0;if(this.rows=n.length>0?[{kind:"all",count:this.allCount(n)},...n]:[],t==="first")this.cursor=r;else if(t==="keep"){let i=e?.kind==="palette"?e.entry.name:"",o=i?this.rows.findIndex((s)=>s.kind==="palette"&&s.entry.name===i):-1;this.cursor=o===-1?r:o}else if(this.cursor>=this.rows.length)this.cursor=Math.max(0,this.rows.length-1);this.sync()}allCount(t){return this.scope==="series"?t.length:this.everyone(t).length}move(t){let e=this.cursor+t;if(e>=0&&e<this.rows.length)this.cursor=e;this.sync()}toggle(t){if(this.expanded.has(t))this.expanded.delete(t);else this.expanded.add(t);this.rebuild("clamp")}fold(t){if(this.userInput||this.scope==="series")return;let e=this.rows[this.cursor];if(e?.kind==="group"){if(t!==e.expanded)this.toggle(e.name)}else if(e?.kind==="palette"&&!t&&!e.entry.default){let n=e.entry.group;if(this.expanded.delete(n),this.rebuild("clamp"),this.cursor=this.rows.findIndex((r)=>r.kind==="group"&&r.name===n),this.cursor===-1)this.cursor=0;this.sync()}}renderRow(t,e){let n=e?"▶ ":" ";if(t.kind==="all"){let o=this.everyone(this.rows).every((c)=>this.picked.has(c.name))?"● ":"○ ",s=`(${t.count})`;return`${n}${o}select all ${this.color?`${rn}${s}${te}`:s}`}if(t.kind==="group"&&this.scope==="series"){let o=this.pickedIn(t.name)===t.count?"● ":"○ ",s=t.name.padEnd(this.seriesPad),c=`(${t.count})${t.native?` ${t.native}`:""}`;if(!this.color)return`${n}${o}${s} ${c}`;let u=t.lead;return`${n}${o}${s} ${$o(u.background,u.cursor)}${ko(u.ansi.slice(1,7),u.background)} ${rn}${c}${te}`}if(t.kind==="group"){let o=t.expanded?"▾":"▸",s=this.rows[this.cursor],c=s?.kind==="palette"&&s.entry.group===t.name?s.entry:void 0,u=this.color?e?`${Lf} ${t.name} ${te}`:c?`${Lf}${Gf(c.cursor)} ${t.name} ${te}`:` ${xp}${t.name}${te} `:e?`[${t.name}]`:` ${t.name}`,h=this.color?Rf("●",t.lead.selection):"",f=`${this.pickedIn(t.name)}/${t.count}`,a=this.color?` ${rn}(${f})${te}`:` (${f})`,l=t.native?this.color?` ${rn}${t.native}${te}`:` ${t.native}`:"";return`${o}${u}${h}${a}${l}`}let r=t.entry,i=this.picked.has(r.name)?"● ":"○ ";if(!this.color)return` ${n}${i}${r.name.padEnd(13)} ● · ${r.ansiSource}`;return` ${n}${i}${r.name.padEnd(13)} ${$o(r.background,r.cursor)}${ko(r.ansi.slice(1,7),r.background)} ${rn}${r.ansiSource}${te}`}draw(){let t=(g)=>this.color?`${rn}${g}${te}`:g,e=(g)=>this.color?`${zp}${g}${te}`:g,n=this.scope==="series"?"series":"catalog";if(this.state==="submit")return`${t("◇")} ${n} ${t(`· ${this.pickedCount()} picked`)}`;if(this.state==="cancel")return`${t(`◇ ${n} · cancelled`)}`;let r=this.userInput.trim(),i=this.scope==="series"?this.series.length:this.named.length,o=this.scope==="series"?this.rows.filter((g)=>g.kind==="group").length:r?this.named.filter((g)=>zr(g,r)).length:i,s=`${e("◆")} ${n} ${t(`(${o}/${i} · ${this.pickedCount()} picked)`)}`,c=`${e("│")} ${this.userInput?`⌕ ${this.userInput}_`:t(`⌕ search…${this.example?` e.g. ${this.animatedExample()}`:""}`)}`;if(this.cursor<this.top)this.top=this.cursor;if(this.cursor>=this.top+this.maxItems)this.top=this.cursor-this.maxItems+1;this.top=Math.min(this.top,Math.max(0,this.rows.length-this.maxItems));let u=this.rows.slice(this.top,this.top+this.maxItems),h=u.length>0?u.map((g,k)=>`${e("│")} ${this.renderRow(g,this.top+k===this.cursor)}`):[`${e("│")} ${t(`no ${this.scope==="series"?"series":"palettes"} match '${this.userInput}'`)}`];while(h.length<this.maxItems)h.push(e("│"));let f=this.rows.length-this.top-u.length,a=f>0?`${e("│")} ${t(`↓ ${f} more`)}`:e("│"),l=this.scope==="series"?"":" · ←→ fold",d=this.scope==="series"?"continue":"install",p=this.state==="error"?`${e("└")} ${this.color?`${Yp}${this.error}${te}`:this.error}`:`${e("└")} ${t(`↑↓ move${l} · space pick · type to filter · enter ${d} · esc cancel`)}`;return[s,c,...h,a,p].join(`
|
|
205
|
+
`)}}function Dn(t,e,n,r){let i=Ce(),o=Boolean(ue(n))!==Boolean(ue(r)),s=o?Zn(r,i):r;return Cn(t,e,s),Xn(t,s),o&&_n(s,i)&&i.running()}function Mo(t){console.log(`
|
|
206
|
+
${t} palettes installed — open a new tab, or reload your terminal config`)}function Jf(t){let e=Kt(),n=Pt(e),r=xt(e),i=t.filter((c)=>r.palettes.includes(c)),o=t.filter((c)=>!r.palettes.includes(c));if(o.length===0){console.log(`already installed: ${i.join(", ")}`);return}let s={...r,palettes:[...r.palettes,...o]};Dn(e,n,r,s);for(let c of o)console.log(` + ${c}`);Mo(s.palettes.length)}function Af(t){let e=Kt(),n=Pt(e),r=xt(e),i=t.filter((s)=>r.palettes.includes(s));if(i.length===0){console.log(`not installed: ${t.join(", ")}`);return}let o={...r,palettes:r.palettes.filter((s)=>!i.includes(s))};Dn(e,n,r,o),Yi(e,n,r.terminals,i);for(let s of i)console.log(` - ${s}`);Mo(o.palettes.length)}function Tf(t){let e=Kt(),n=Pt(e),r=xt(e);if(!r.palettes.includes(t))throw Error(`${t} is not installed — \`ttheme add ${t}\` first`);let{off:i,...o}=r,s=Ce(),c=Zn({...o,startup:t},s);Cn(e,n,c),Xn(e,c);let u=_n(c,s);console.log(Qf(t,c.terminals,u&&s.running()).join(`
|
|
207
|
+
`))}function Uf(){let t=Kt(),e=xt(t),n=Ve(e);if(!n)throw Error("no palettes installed — `ttheme browse` picks some");if(!e.off){console.log(`already on · ${n}`);return}let{off:r,...i}=e,o=Dn(t,Pt(t),e,i);console.log(Qf(n,i.terminals,o).join(`
|
|
208
|
+
`))}function Wf(){let t=Kt(),e=xt(t);if(e.off){console.log("already off");return}let n=Dn(t,Pt(t),e,{...e,off:!0}),r=Ve(e);if(console.log(`off · new tabs open in the terminal's own colors${r?` — \`ttheme on\` wears ${r} again`:""}`),n)console.log("iterm2 new tabs open on your own profile once iTerm2 restarts")}function Qf(t,e,n){let r=e.filter((o)=>o!=="iterm2"),i=r.length>0?[`default ${t} · ${r.join(", ")} open new tabs with it once their config reloads`]:[];if(e.includes("iterm2"))i.push(n?'iterm2 new tabs open with it once iTerm2 restarts — "ttheme · default" is now its default profile':'iterm2 new tabs open with it — "ttheme · default" is its default profile');return i.length>0?i:[`default ${t} · no terminal is wired to open with it — \`ttheme init\` wires one`]}function qf(t,e=!1){let n=Kt(),r=Pt(n),i=new Set(xt(n).palettes),o=He(r.palettes),s=jn(t?Qu(o,t):o);if(e){let u=s.map((h)=>({name:h.name,group:h.group,installed:i.has(h.name)}));console.log(JSON.stringify(u,null,2));return}let c=Math.max(...s.map((u)=>u.name.length),0);for(let u of s)console.log(` ${i.has(u.name)?"●":"○"} ${u.name.padEnd(c)} ${u.group}`);if(process.stdout.isTTY){let u=t?`${s.length} of ${o.length}`:`${o.length}`;console.log(`
|
|
209
|
+
${u} palettes — ${s.filter((h)=>i.has(h.name)).length} installed`)}}async function Zf(){let t=Kt(),e=Bp(jr(t))?Pt(t).palettes.length:0,n=await Uu(Au);Rr(t,n);let r=n.palettes.length-e;console.log(`catalog ${n.version} — ${n.palettes.length} palettes${r>0?` (+${r})`:""}`)}async function yo(t,e,n,r=!1){let i=process.env.TTHEME_SORT==="series"?t.palettes:jn(t.palettes),o=process.stdout.isTTY===!0&&!Bn(),s=o?await jf():new Map,c=new Eo({entries:i,scope:n,installed:e,required:r,color:!Bn(),fx:Kf(process.env.TTHEME_FX),onFocus:o?(h)=>process.stdout.write(xr(h)):void 0}),u=await c.prompt();if(process.stdout.write(Of(s)),tn(u))return;return t.palettes.filter((h)=>c.picked.has(h.name)).map((h)=>h.name)}async function _f(){let t=Kt(),e=Pt(t),n=xt(t),r=await yo(e,n.palettes,"palette");if(!r){console.log("nothing changed");return}let i=n.palettes.filter((c)=>!r.includes(c)),o=r.filter((c)=>!n.palettes.includes(c));if(o.length===0&&i.length===0){console.log("nothing changed");return}let s={...n,palettes:r};Dn(t,e,n,s),Yi(t,e,n.terminals,i);for(let c of o)console.log(` + ${c}`);for(let c of i)console.log(` - ${c}`);Mo(s.palettes.length)}function Vf(t,e,n){for(let r of r0(e))t.push({from:ct(e,r),to:ct(n,r)})}function Bf(t){return JSON.parse(sn(ct(t,"dist","manifest.json"),"utf8"))}function xf(t,e){let n=ct(e.root,"dist"),r=ct(e.configHome,"ttheme"),i=[{from:ct(e.root,"bin","ttheme.js"),to:ct(r,"ttheme.js")},{from:ct(e.root,"bin","ttheme.js.map"),to:ct(r,"ttheme.js.map")},{from:ct(e.root,"shell","ttheme.zsh"),to:ct(r,"ttheme.zsh")},{from:ct(e.root,"shell","launch-tab.zsh"),to:ct(r,"launch-tab.zsh"),executable:!0},{from:ct(n,"ghostty","ttheme.conf"),to:ct(r,"ttheme.conf")}];Vf(i,ct(e.root,"shell","adapters"),ct(r,"adapters"));let o=[{file:ct(e.zdotdir,".zshrc"),block:ou(r)}],s=ct(r,"config.zsh"),c=hu(Qt(s)?sn(s,"utf8"):""),u={file:s,content:c},h=[];if(t.terminals.includes("ghostty"))Vf(i,ct(e.root,"ghostty","shaders"),ct(e.configHome,"ghostty","shaders"));if(t.terminals.includes("alacritty")){let l=zi(e.configHome);if(Qt(l)&&Er(sn(l,"utf8"),void 0)===void 0)h.push(`${l} already imports files under [general] — ttheme left it alone; add ${ct(e.configHome,"alacritty","themes")}/<palette>.toml to that import list yourself`)}if(t.terminals.includes("wezterm")){let l=xi(e.configHome,e.home);if(Qt(l)&&Mr(sn(l,"utf8"),"")===void 0)h.push(`${l} has no \`return config\` line — ttheme left it alone; call \`dofile("${ct(r,"wezterm.lua")}")(config)\` from it yourself`)}let f=t.terminals.includes("windows-terminal");if(f&&!e.wtHome)h.push("windows terminal: %LOCALAPPDATA% was not found — drop the release fragment into its Fragments folder yourself");if(t.terminals.includes("warp"))h.push("warp: wears the default palette app-wide through its settings.toml — the shell layer stays off in it, since Warp paints no tab background of its own");let a={terminals:t.terminals,palettes:t.palettes,...f&&e.wtHome?{wtHome:e.wtHome}:{},...f&&e.wtProfile?{wtProfile:e.wtProfile}:{},...t.off?{off:!0}:{}};return{home:e.home,copies:i,edits:o,settings:u,catalog:Bf(e.root),installed:a,notes:h}}function o0(t){try{return xt(t).itermBase}catch{return}}function zf(t,e=Ce()){for(let o of t.copies)if(vo(on(o.to),{recursive:!0}),Xf(o.to,{force:!0}),Xf(`${o.to}.zwc`,{force:!0}),n0(o.from,o.to),o.executable)e0(o.to,493);vo(on(t.settings.file),{recursive:!0}),Cf(t.settings.file,t.settings.content);let n=on(on(t.settings.file)),r=o0(n),i=Zn(r?{...t.installed,itermBase:r}:t.installed,e);Rr(n,t.catalog),Xn(n,i),Cn(n,t.catalog,i,t.home);for(let o of t.edits){vo(on(o.file),{recursive:!0});let s=Qt(o.file)?sn(o.file,"utf8"):"";Cf(o.file,Rn(s,o.block))}return _n(i,e)}class cn extends Error{}function So(t){if(tn(t))throw Cr("nothing changed"),new cn;return t}function Df(t){return $r.filter((e)=>{if(e==="iterm2")return process.platform==="darwin";if(e==="windows-terminal")return t.wtHome!==void 0;return e!=="warp"||process.platform!=="win32"})}function s0(t,e){if(t==="iterm2")return Qt(ct(e.home,"Library","Application Support","iTerm2"));if(t==="windows-terminal")return e.wtHome!==void 0;if(t==="warp")return Qt(on(Tr(e.home)));if(t==="wezterm")return Qt(ct(e.configHome,"wezterm"))||Qt(ct(e.home,".wezterm.lua"));return Qt(ct(e.configHome,t))}function c0(){if(process.platform==="win32")return process.env.LOCALAPPDATA;if(!process.env.WSL_DISTRO_NAME)return;let t=(e,n)=>Dp(e,n,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();try{return t("wslpath",["-u",t("cmd.exe",["/d","/c","echo %LOCALAPPDATA%"])])||void 0}catch{return}}async function u0(t,e,n){return So(await vf({message:"wire which terminals?",options:Df(n).map((r)=>({value:r,hint:r===t?"detected":void 0})),initialValues:e,required:!0}))}function Yf(t){let e=[...t.copies.filter((n)=>!Qt(n.to)).map((n)=>n.to),...Qt(t.settings.file)?[]:[t.settings.file],...t.edits.filter((n)=>!sn(n.file,"utf8").includes("# ttheme begin")).map((n)=>n.file)];if(e.length>0)throw Error(`init left gaps:
|
|
210
|
+
${e.join(`
|
|
211
|
+
`)}`)}function ta(t,e){return[...new Set(t.palettes.filter((n)=>e.includes(n.name)).map((n)=>n.group))]}function h0(t,e){let n=t.palettes.find((i)=>i.name===ue(e)),r=process.stdout.isTTY===!0&&!Bn()&&!process.env.TMUX&&kr(process.env)!=="warp";if(!n||!r)return!1;return process.stdout.write(xr(n)),!0}function f0(t,e){let n=ue(t);if(!n)return["default none — new tabs keep the terminal colors",`turn on \`ttheme on\` wears ${Ve(t)}`];return[`default ${n}${e?" — this tab wears it already":""}`,"change it `ttheme preview`, enter on a palette, then default"]}function a0(t){t0("zsh",["-c",'source "$1" && __tt_preview init',"zsh",ct(t,"ttheme","ttheme.zsh")],{stdio:"inherit"})}function l0(t,e,n,r){let i=ta(t.catalog,e.palettes);Vr([`${i.join(", ")} (${e.palettes.length})`,...f0(t.installed,n)].join(`
|
|
212
|
+
`),`installed ${e.palettes.length} palettes`);let o=["exec zsh the ttheme command in this tab"];if(e.terminals.includes("ghostty"))o.push("restart ghostty new tabs pick up its config");if(e.terminals.includes("kitty"))o.push("new kitty window pictures follow it — kitty reloads its colors by itself");if(e.terminals.includes("alacritty"))o.push("alacritty reloads its config by itself");if(e.terminals.includes("wezterm"))o.push("wezterm reloads its config by itself");if(e.terminals.includes("windows-terminal"))o.push("windows terminal reloads its settings by itself");if(e.terminals.includes("iterm2"))o.push(...g0(ue(t.installed),r));Vr([...o,...t.notes].join(`
|
|
213
|
+
`),"next"),Ff("done")}function g0(t,e){let n=['iterm2 profiles a "ttheme · <palette>" per palette in Settings › Profiles'];if(t)n.push(e?`restart iterm2 new tabs open on "ttheme · default", which wears ${t}`:`iterm2 default "ttheme · default" wears ${t} and follows \`ttheme default\``);return n}function d0(t,e){let n=[`placed ${t.copies.length} files`,`settings in ${t.settings.file} — edit later with \`ttheme config\``,...t.edits.map((r)=>`wired ${r.file}`)];if(e.terminals.includes("ghostty"))n.push("restart ghostty to pick up its config");if(e.terminals.includes("kitty"))n.push("kitty reloads its colors by itself; pictures show in kitty windows opened from now on");if(e.terminals.includes("alacritty"))n.push("alacritty reloads its config by itself");if(e.terminals.includes("wezterm")||e.terminals.includes("windows-terminal"))n.push("wezterm and windows terminal reload their config by themselves");if(e.terminals.includes("iterm2"))n.push('iterm2 gets a "ttheme · <palette>" profile per palette under Settings › Profiles');n.push(...t.notes),n.push("no palettes yet — open a new shell (`exec zsh`), then `ttheme browse` picks them from the catalog"),console.log(n.join(`
|
|
214
|
+
`))}async function ea(t={}){let e=ct(import.meta.dirname,"..");if(!Qt(ct(e,"bin","ttheme.js")))throw Error("bin/ttheme.js is missing — run `mise run bin:build` first");if(!Qt(ct(e,"dist"))){if(typeof Bun>"u")throw Error("this package is missing dist/ — reinstall @kecan0406/ttheme");await vr()}let n=i0(),r=Kt(),i=process.env.ZDOTDIR??n,o=c0(),s=process.env.WT_PROFILE_ID,c={root:e,home:n,configHome:r,zdotdir:i,...o?{wtHome:o}:{},...s?{wtProfile:s}:{}},u=kr(process.env),h=Df(c).filter((O)=>O===u||s0(O,c));if(!(!t.yes&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0)){if(h.length===0)throw Error("no supported terminal detected — run this inside ghostty, kitty, alacritty, wezterm, iterm2, windows terminal or warp");let O={terminals:h,palettes:[]},$=xf(O,c);zf($),Yf($),d0($,O);return}Sf("ttheme init");let a=await u0(u,h,c),l=Bf(e),d=await yo(l,[],"series",!0);if(!d)throw Cr("nothing changed"),new cn;let p=d[0],g=d.length>1&&kr(process.env)!=="warp",k=So(await bo({message:g?"pick a default palette in ttheme preview once installed?":`wear ${p} in every tab?`})),y={terminals:a,palettes:d,off:!k},I=xf(y,c);if(Vr([`install ${d.length} palettes — ${ta(I.catalog,d).join(", ")}`,`copy ${I.copies.length} files under ${r}`,`write ${I.settings.file}`,...I.edits.map((O)=>`edit ${O.file}`),k?g?`open ttheme preview — every tab wears the palette picked there, ${p} until then`:`paint every tab with ${p}, this one now`:"leave the terminal colors as they are — `ttheme on` wears a palette later",...a.includes("iterm2")&&k?['make "ttheme · default" the iTerm2 default profile']:[]].join(`
|
|
215
|
+
`),`wiring ${a.join(", ")}`),!So(await bo({message:"apply these changes?"})))throw Cr("nothing changed"),new cn;let E=Ce(),v=zf(I,E);if(Yf(I),k&&g)a0(r);let b=xt(r);l0({...I,installed:b},y,h0(I.catalog,b),v&&E.running())}var p0={default:([t])=>Tf(t),on:()=>Uf(),off:()=>Wf(),browse:()=>_f(),list:([t],{json:e})=>qf(t,e),add:(t)=>Jf(t),remove:(t)=>Af(t),update:()=>Zf(),init:(t,{yes:e})=>ea({yes:e}),build:(t,{only:e})=>vr({only:e}),find:([t])=>Qh(t),image:([t,e])=>qh(t,e)},ia=br.map((t)=>({...t,run:p0[t.name]}));class Pe extends Error{verb;constructor(t,e){super(t);this.verb=e}}function na(t){let e=ia.find((n)=>n.name===t);if(!e)throw new Pe(t.startsWith("-")?`unknown option '${t}'`:`unknown command '${t}'`);return e}function w0(t,e){let n={help:{type:"boolean",short:"h"}};for(let[r,{type:i,short:o,multiple:s}]of Object.entries(t.flags??{}))n[r]={type:i,multiple:s===!0,...o?{short:o}:{}};try{return m0({args:e,options:n,allowPositionals:!0})}catch(r){let[i=""]=(r instanceof Error?r.message:String(r)).split(". ");throw new Pe(`${i.charAt(0).toLowerCase()}${i.slice(1)}`,t)}}function b0(t){let[e,...n]=t;if(e===void 0)return{kind:"help",code:1};if(e==="-h"||e==="--help")return{kind:"help",code:0};if(e==="-V"||e==="--version")return{kind:"version"};if(e==="help")return n[0]===void 0?{kind:"help",code:0}:{kind:"help",verb:na(n[0]),code:0};let r=na(e),i=w0(r,n);if(i.values.help)return{kind:"help",verb:r,code:0};for(let[f,{choices:a}]of Object.entries(r.flags??{}))for(let l of[i.values[f]??[]].flat())if(a&&!a.includes(String(l)))throw new Pe(`--${f} takes ${a.join(", ")} — not ${l}`,r);let o=i.positionals,s=r.args.filter((f)=>f.startsWith("<")).length,c=r.args.some((f)=>f.includes("..."))?Number.POSITIVE_INFINITY:r.args.length;if(o.length<s)throw new Pe(`missing ${r.args[o.length]}`,r);if(o.length>c)throw new Pe(`too many arguments: ${o.slice(c).join(" ")}`,r);let{help:u,...h}=i.values;return{kind:"run",verb:r,args:o,flags:h}}function Fo(t){let e=Object.entries(t.flags??{}).map(([n,{value:r}])=>`[--${n}${r?` ${r}`:""}]`);return[t.name,...e,...t.args].join(" ")}function ra(t,e=Math.max(...t.map(([n])=>n.length))){return t.map(([n,r])=>` ${n.padEnd(e)} ${r}`)}var $0=["tab","catalog","setup"];function Io(t){if(t){let i=Object.entries(t.flags??{}).map(([o,{short:s,value:c,about:u}])=>[`${s?`-${s}, `:""}--${o}${c?` ${c}`:""}`,u]);return[`Usage: ttheme ${Fo(t)}`,"",t.about,...i.length>0?["","Options:",...ra(i)]:[]].join(`
|
|
216
|
+
`)}let e=ia.filter((i)=>!i.hidden),n=(i)=>e.filter((o)=>o.section===i).map((o)=>[Fo(o),o.about]),r=Math.max(...e.map((i)=>Fo(i).length));return["Usage: ttheme <command>","",ne.description,"","Commands:",...$0.flatMap((i,o)=>[...o>0?[""]:[],...ra(n(i),r)]),"","Examples:"," 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 <command> --help describes one command · ttheme --version prints the version","https://kecan0406.github.io/ttheme"].join(`
|
|
217
|
+
`)}async function oa(t){let e;try{let n=b0(t);if(n.kind==="version")return console.log(ne.version),0;if(n.kind==="help"){if(n.code===0)console.log(Io(n.verb));else console.error(Io(n.verb));return n.code}if(e=n.verb,!n.verb.run)throw Error("runs in the shell layer — open a new tab once `ttheme init` has wired it");let r=await n.verb.run(n.args,n.flags);return typeof r==="number"?r:0}catch(n){if(n instanceof Pe)return console.error(`ttheme${n.verb?` ${n.verb.name}`:""}: ${n.message}
|
|
218
|
+
|
|
219
|
+
${Io(n.verb)}`),1;if(n instanceof cn)return 1;let r=process.env.TTHEME_DEBUG&&n instanceof Error?n.stack:void 0;return console.error(`
|
|
220
|
+
ttheme${e?` ${e.name}`:""}: ${r??(n instanceof Error?n.message:String(n))}`),1}}if(E0)if(process.env.TTHEME_DEBUG&&typeof Bun>"u"&&!process.sourceMapsEnabled){let t=k0(process.execPath,["--enable-source-maps",...process.argv.slice(1)],{stdio:"inherit"});process.exitCode=t.status??1}else process.exitCode=await oa(process.argv.slice(2));
|
|
218
221
|
|
|
219
|
-
|
|
220
|
-
|
|
222
|
+
//# debugId=576562C19E0BB68D64756E2164756E21
|
|
223
|
+
//# sourceMappingURL=ttheme.js.map
|