UNPKG

bunny-log

Version:

🐰 Beautiful console logging with auto-categories, hex colors, and advanced tables

12 lines (11 loc) 18.1 kB
var m=(V=0)=>(q)=>`\x1B[${q+V}m`,d=(V=0)=>(q)=>`\x1B[${38+V};5;${q}m`,p=(V=0)=>(q,H,J)=>`\x1B[${38+V};2;${q};${H};${J}m`,G={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},v1=Object.keys(G.modifier),Z1=Object.keys(G.color),$1=Object.keys(G.bgColor),k1=[...Z1,...$1];function K1(){let V=new Map;for(let[q,H]of Object.entries(G)){for(let[J,X]of Object.entries(H))G[J]={open:`\x1B[${X[0]}m`,close:`\x1B[${X[1]}m`},H[J]=G[J],V.set(X[0],X[1]);Object.defineProperty(G,q,{value:H,enumerable:!1})}return Object.defineProperty(G,"codes",{value:V,enumerable:!1}),G.color.close="\x1B[39m",G.bgColor.close="\x1B[49m",G.color.ansi=m(),G.color.ansi256=d(),G.color.ansi16m=p(),G.bgColor.ansi=m(10),G.bgColor.ansi256=d(10),G.bgColor.ansi16m=p(10),Object.defineProperties(G,{rgbToAnsi256:{value(q,H,J){if(q===H&&H===J){if(q<8)return 16;if(q>248)return 231;return Math.round((q-8)/247*24)+232}return 16+36*Math.round(q/255*5)+6*Math.round(H/255*5)+Math.round(J/255*5)},enumerable:!1},hexToRgb:{value(q){let H=/[a-f\d]{6}|[a-f\d]{3}/i.exec(q.toString(16));if(!H)return[0,0,0];let[J]=H;if(J.length===3)J=[...J].map((Z)=>Z+Z).join("");let X=Number.parseInt(J,16);return[X>>16&255,X>>8&255,X&255]},enumerable:!1},hexToAnsi256:{value:(q)=>G.rgbToAnsi256(...G.hexToRgb(q)),enumerable:!1},ansi256ToAnsi:{value(q){if(q<8)return 30+q;if(q<16)return 90+(q-8);let H,J,X;if(q>=232)H=((q-232)*10+8)/255,J=H,X=H;else{q-=16;let K=q%36;H=Math.floor(q/36)/5,J=Math.floor(K/6)/5,X=K%6/5}let Z=Math.max(H,J,X)*2;if(Z===0)return 30;let Q=30+(Math.round(X)<<2|Math.round(J)<<1|Math.round(H));if(Z===2)Q+=60;return Q},enumerable:!1},rgbToAnsi:{value:(q,H,J)=>G.ansi256ToAnsi(G.rgbToAnsi256(q,H,J)),enumerable:!1},hexToAnsi:{value:(q)=>G.ansi256ToAnsi(G.hexToAnsi256(q)),enumerable:!1}}),G}var Q1=K1(),U=Q1;import b from"node:process";import D1 from"node:os";import g from"node:tty";function z(V,q=globalThis.Deno?globalThis.Deno.args:b.argv){let H=V.startsWith("-")?"":V.length===1?"-":"--",J=q.indexOf(H+V),X=q.indexOf("--");return J!==-1&&(X===-1||J<X)}var{env:O}=b,v;if(z("no-color")||z("no-colors")||z("color=false")||z("color=never"))v=0;else if(z("color")||z("colors")||z("color=true")||z("color=always"))v=1;function G1(){if("FORCE_COLOR"in O){if(O.FORCE_COLOR==="true")return 1;if(O.FORCE_COLOR==="false")return 0;return O.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(O.FORCE_COLOR,10),3)}}function O1(V){if(V===0)return!1;return{level:V,hasBasic:!0,has256:V>=2,has16m:V>=3}}function B1(V,{streamIsTTY:q,sniffFlags:H=!0}={}){let J=G1();if(J!==void 0)v=J;let X=H?v:J;if(X===0)return 0;if(H){if(z("color=16m")||z("color=full")||z("color=truecolor"))return 3;if(z("color=256"))return 2}if("TF_BUILD"in O&&"AGENT_NAME"in O)return 1;if(V&&!q&&X===void 0)return 0;let Z=X||0;if(O.TERM==="dumb")return Z;if(b.platform==="win32"){let Q=D1.release().split(".");if(Number(Q[0])>=10&&Number(Q[2])>=10586)return Number(Q[2])>=14931?3:2;return 1}if("CI"in O){if("GITHUB_ACTIONS"in O||"GITEA_ACTIONS"in O)return 3;if(["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some((Q)=>(Q in O))||O.CI_NAME==="codeship")return 1;return Z}if("TEAMCITY_VERSION"in O)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(O.TEAMCITY_VERSION)?1:0;if(O.COLORTERM==="truecolor")return 3;if(O.TERM==="xterm-kitty")return 3;if("TERM_PROGRAM"in O){let Q=Number.parseInt((O.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(O.TERM_PROGRAM){case"iTerm.app":return Q>=3?3:2;case"Apple_Terminal":return 2}}if(/-256(color)?$/i.test(O.TERM))return 2;if(/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(O.TERM))return 1;if("COLORTERM"in O)return 1;return Z}function c(V,q={}){let H=B1(V,{streamIsTTY:V&&V.isTTY,...q});return O1(H)}var z1={stdout:c({isTTY:g.isatty(1)}),stderr:c({isTTY:g.isatty(2)})},n=z1;function i(V,q,H){let J=V.indexOf(q);if(J===-1)return V;let X=q.length,Z=0,Q="";do Q+=V.slice(Z,J)+q+H,Z=J+X,J=V.indexOf(q,Z);while(J!==-1);return Q+=V.slice(Z),Q}function a(V,q,H,J){let X=0,Z="";do{let Q=V[J-1]==="\r";Z+=V.slice(X,Q?J-1:J)+q+(Q?`\r `:` `)+H,X=J+1,J=V.indexOf(` `,X)}while(J!==-1);return Z+=V.slice(X),Z}var{stdout:r,stderr:s}=n,u=Symbol("GENERATOR"),A=Symbol("STYLER"),E=Symbol("IS_EMPTY"),l=["ansi","ansi","ansi256","ansi16m"],T=Object.create(null),Y1=(V,q={})=>{if(q.level&&!(Number.isInteger(q.level)&&q.level>=0&&q.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");let H=r?r.level:0;V.level=q.level===void 0?H:q.level};var U1=(V)=>{let q=(...H)=>H.join(" ");return Y1(q,V),Object.setPrototypeOf(q,j.prototype),q};function j(V){return U1(V)}Object.setPrototypeOf(j.prototype,Function.prototype);for(let[V,q]of Object.entries(U))T[V]={get(){let H=k(this,h(q.open,q.close,this[A]),this[E]);return Object.defineProperty(this,V,{value:H}),H}};T.visible={get(){let V=k(this,this[A],!0);return Object.defineProperty(this,"visible",{value:V}),V}};var f=(V,q,H,...J)=>{if(V==="rgb"){if(q==="ansi16m")return U[H].ansi16m(...J);if(q==="ansi256")return U[H].ansi256(U.rgbToAnsi256(...J));return U[H].ansi(U.rgbToAnsi(...J))}if(V==="hex")return f("rgb",q,H,...U.hexToRgb(...J));return U[H][V](...J)},I1=["rgb","hex","ansi256"];for(let V of I1){T[V]={get(){let{level:H}=this;return function(...J){let X=h(f(V,l[H],"color",...J),U.color.close,this[A]);return k(this,X,this[E])}}};let q="bg"+V[0].toUpperCase()+V.slice(1);T[q]={get(){let{level:H}=this;return function(...J){let X=h(f(V,l[H],"bgColor",...J),U.bgColor.close,this[A]);return k(this,X,this[E])}}}}var N1=Object.defineProperties(()=>{},{...T,level:{enumerable:!0,get(){return this[u].level},set(V){this[u].level=V}}}),h=(V,q,H)=>{let J,X;if(H===void 0)J=V,X=q;else J=H.openAll+V,X=q+H.closeAll;return{open:V,close:q,openAll:J,closeAll:X,parent:H}},k=(V,q,H)=>{let J=(...X)=>W1(J,X.length===1?""+X[0]:X.join(" "));return Object.setPrototypeOf(J,N1),J[u]=V,J[A]=q,J[E]=H,J},W1=(V,q)=>{if(V.level<=0||!q)return V[E]?"":q;let H=V[A];if(H===void 0)return q;let{openAll:J,closeAll:X}=H;if(q.includes("\x1B"))while(H!==void 0)q=i(q,H.close,H.open),H=H.parent;let Z=q.indexOf(` `);if(Z!==-1)q=a(q,X,J,Z);return J+q+X};Object.defineProperties(j.prototype,T);var R1=j(),m1=j({level:s?s.level:0});var $=R1;class C{constructor(V=!1){if(this.categoryColors=new Map,this.timeFormat="24h",this.showSeconds=!0,this.colorText=!1,V)this.categoryColors.set("info",$.blue),this.categoryColors.set("error",$.red),this.categoryColors.set("warn",$.yellow),this.categoryColors.set("success",$.green);return this.initializeDefaultMethods(),new Proxy(this,{get(q,H){if(H in q||typeof H==="symbol"){let J=q[H];return typeof J==="function"?J.bind(q):J}if(typeof H==="string"){if(!q.categoryColors.has(H)){let J=$.white;switch(H.toLowerCase()){case"info":J=$.blue;break;case"error":J=$.red;break;case"warn":case"warning":J=$.yellow;break;case"success":J=$.green;break;case"debug":J=$.magenta;break;case"server":J=$.cyan;break;case"database":case"db":J=$.blueBright;break;case"api":J=$.magentaBright;break;default:J=$.white}q.categoryColors.set(H,J)}return(...J)=>{return q.log(H,...J),q}}return q[H]}})}initializeDefaultMethods(){Array.from(this.categoryColors.keys()).forEach((q)=>{this[q]=(...H)=>{return this.log(q,...H),this}})}getTimestamp(){let q={hour12:this.timeFormat==="12h",hour:"2-digit",minute:"2-digit"};if(this.showSeconds)q.second="2-digit";return $.gray(new Date().toLocaleTimeString("en-US",q))}log(V,...q){if(!this.categoryColors.has(V)){let K=$.white;switch(V.toLowerCase()){case"info":K=$.blue;break;case"error":K=$.red;break;case"warn":case"warning":K=$.yellow;break;case"success":K=$.green;break;case"debug":K=$.magenta;break;case"server":K=$.cyan;break;case"database":case"db":K=$.blueBright;break;case"api":K=$.magentaBright;break;default:K=$.white}this.categoryColors.set(V,K)}let H=this.categoryColors.get(V)||$.white,J=this.getTimestamp(),X=q.map((K)=>{if(K instanceof Error)return $.red(K.message);else if(typeof K==="object")return this.colorizeJson(K);else return String(K)}).join(" "),Z=this.colorText?H(X):X,Q=`${J} | [${H(V.toUpperCase())}] - ${Z}`;switch(V){case"error":console.error(Q);break;case"warn":console.warn(Q);break;case"info":console.info(Q);break;case"table":console.log(`${J} | [${H(V.toUpperCase())}] -`),console.table(q[0]);break;default:console.log(Q);break}return this}setTimeFormat(V){if(V==="12h"||V==="24h")this.timeFormat=V;else throw new Error("Time format must be '12h' or '24h'");return this}getTimeFormat(){return this.timeFormat}use12HourFormat(){return this.timeFormat="12h",this}use24HourFormat(){return this.timeFormat="24h",this}setShowSeconds(V){return this.showSeconds=Boolean(V),this}getShowSeconds(){return this.showSeconds}showSecondsInTime(){return this.showSeconds=!0,this}hideSecondsInTime(){return this.showSeconds=!1,this}setTextColor(V){return this.colorText=Boolean(V),this}getTextColor(){return this.colorText}enableTextColor(){return this.colorText=!0,this}disableTextColor(){return this.colorText=!1,this}colorizeJson(V,q=0){if(V===null)return $.red("null");if(V===void 0)return $.red("undefined");if(typeof V==="string")return $.green(`"${V}"`);if(typeof V==="number")return $.yellow(V);if(typeof V==="boolean")return $.blue(V);let H=" ".repeat(q);if(Array.isArray(V)){if(V.length===0)return $.white("[]");let J=V.map((X)=>this.colorizeJson(X,q+1));return`${$.white(`[ `)}${J.map((X)=>`${H} ${X}`).join($.white(`, `))} ${H}${$.white("]")}`}if(typeof V==="object"){let J=Object.keys(V);if(J.length===0)return $.white("{}");let X=J.map((Z)=>{let Q=V[Z],K=$.cyan(`"${Z}"`),B=this.colorizeJson(Q,q+1);return`${H} ${K}${$.white(":")} ${B}`});return`${$.white(`{ `)}${X.join($.white(`, `))} ${H}${$.white("}")}`}return $.gray(String(V))}hex(V,q){return this.categoryColors.set(V,$.hex(q)),this[V]=(...H)=>{return this.log(V,...H),this},this}rgb(V,q,H,J){return this.categoryColors.set(V,$.rgb(q,H,J)),this[V]=(...X)=>{return this.log(V,...X),this},this}table(V,q={}){let H=V;if(q.columns&&Array.isArray(q.columns))H=V.map((J)=>{let X={};return q.columns.forEach((Z)=>{if(J.hasOwnProperty(Z))X[Z]=J[Z]}),X});return this.log("table",H),this}getCategories(){return Array.from(this.categoryColors.keys())}setColor(V,q){return this.categoryColors.set(V,q),this}setHex(V,q){return this.categoryColors.set(V,$.hex(q)),this}removeCategory(V){return this.categoryColors.delete(V),delete this[V],this}static clean(){return new C(!1)}}var M1=new C;import*as o from"os";var y=o.EOL;function t(V){if(typeof V!=="string")return 0;let q=/\u001b\[[0-9;]*m/g,H=V.replace(q,""),J=0;for(let X of H){let Z=X.codePointAt(0);if(Z>=128512&&Z<=128591)J+=2;else if(Z>=127744&&Z<=128511)J+=2;else if(Z>=128640&&Z<=128767)J+=2;else if(Z>=9728&&Z<=9983)J+=2;else if(Z>=9984&&Z<=10175)J+=2;else J+=1}return J}var w={Black:0,Red:1,Green:2,Yellow:3,Blue:4,Magenta:5,Cyan:6,White:7,BrightBlack:8,BrightRed:9,BrightGreen:10,BrightYellow:11,BrightBlue:12,BrightMagenta:13,BrightCyan:14,BrightWhite:15};function x1(V){return V<=w.White?30+V:90+(V-w.BrightBlack)}function A1(V){return V<=w.White?40+V:100+(V-w.BrightBlack)}class L{constructor(V={}){if(this.bold=!1,this.italic=!1,this.underline=!1,this.fg=void 0,this.bg=void 0,V)Object.assign(this,V)}toAnsi(){let V=[];if(typeof this.fg==="number")V.push(x1(this.fg));if(typeof this.bg==="number")V.push(A1(this.bg));if(this.bold)V.push(1);if(this.italic)V.push(3);if(this.underline)V.push(4);return`\x1B[${V.join(";")||"0"}m`}static reset="\x1B[0m"}var P={Left:"left",Center:"center",Right:"right"};class x{constructor(V="",q={}){this.lines=V.split(y),this.width=this.lines.reduce((H,J)=>Math.max(H,t(J)),0),this.align=q.align??P.Left,this.style=q.style??new L,this.hspan=Math.max(1,q.hspan??1)}height(){return this.lines.length}writeLine(V,q,H=" "){let J=this.lines[V]??"",X=Math.max(0,q-t(J)),Z=0;switch(this.align){case P.Right:Z=X;break;case P.Center:Z=Math.floor(X/2);break;default:Z=0}let Q=X-Z;return H.repeat(Z)+J+H.repeat(Q)}renderLine(V,q,H=!1,J=!1){let X=this.writeLine(V,q);if(!H||this.style&&this.style.toAnsi()==="\x1B[0m")return X;return`${this.style.toAnsi()}${X}${L.reset}${J?"":""}`}}var D={Top:0,Title:1,Intern:2,Bottom:3},I={Left:0,Intern:1,Right:2};class Y{constructor(V,q,H,J){this.line=V,this.junc=q,this.ljunc=H,this.rjunc=J}print(V,q,H,J={},X=0){let{colSep:Z=!1,lBorder:Q=!1,rBorder:K=!1}=J,B=[];if(X)B.push(" ".repeat(X));if(Q)B.push(this.ljunc);if(V.forEach((R,M)=>{if(B.push(this.line.repeat(R+q+H)),Z&&M<V.length-1)B.push(this.junc)}),K)B.push(this.rjunc);return B.join("")+y}}class W{constructor(){this.csep=void 0,this.lborder=void 0,this.rborder=void 0,this.lsep=void 0,this.tsep=void 0,this.topSep=void 0,this.bottomSep=void 0,this.padLeft=0,this.padRight=0,this.indent=0}withPadding(V,q){return this.padLeft=V,this.padRight=q,this}withColumnSeparator(V){return this.csep=V,this}withBorders(V){return this.lborder=V,this.rborder=V,this}withLeftBorder(V){return this.lborder=V,this}withRightBorder(V){return this.rborder=V,this}withSeparator(V,q){switch(V){case D.Top:this.topSep=q;break;case D.Bottom:this.bottomSep=q;break;case D.Title:this.tsep=q;break;case D.Intern:this.lsep=q;break}return this}withIndent(V){return this.indent=V,this}columnSep(V){switch(V){case I.Left:return this.lborder;case I.Intern:return this.csep;case I.Right:return this.rborder}}lineSep(V){switch(V){case D.Top:return this.topSep;case D.Bottom:return this.bottomSep;case D.Title:return this.tsep??this.lsep;case D.Intern:return this.lsep}}printLine(V,q){let H=this.lineSep(q);if(!H)return"";return H.print(V,this.padLeft,this.padRight,{colSep:!!this.csep,lBorder:!!this.lborder,rBorder:!!this.rborder},this.indent)}}class S{constructor(V){this.cells=V}len(){return this.cells.length}height(){return this.cells.reduce((V,q)=>Math.max(V,q.height()),1)}columnCount(){return this.cells.reduce((V,q)=>V+q.hspan,0)}cell(V){return this.cells[V]}columnWidth(V,q){let H=0;for(let J of this.cells){if(H+J.hspan>V){if(J.hspan===1)return J.width;let X=q.csep?1:0,Z=q.padLeft+q.padRight+X,Q=Math.max(0,J.width-Z);return Math.ceil(Q/J.hspan)}H+=J.hspan}return 0}renderInternal(V,q,H){let J=[],X=q.length,Z=this.height();for(let Q=0;Q<Z;Q++){let K=[];if(V.indent)K.push(" ".repeat(V.indent));if(V.columnSep(I.Left))K.push(V.columnSep(I.Left));let B=0;for(let R=0;R<this.cells.length;R++){let M=this.cells[R],F=M.hspan,H1=q.slice(B,B+F).reduce((_,X1)=>_+X1,0)+(F-1)*(V.padLeft+V.padRight+(V.csep?1:0));K.push(" ".repeat(V.padLeft));let J1=B+F===X&&!V.columnSep(I.Right);if(K.push(M.renderLine(Q,H1,H,J1)),K.push(" ".repeat(V.padRight)),B+=F,B<X){let _=V.columnSep(I.Intern);if(_)K.push(_)}}while(B<X){let R=new x;if(K.push(" ".repeat(V.padLeft)),K.push(R.renderLine(Q,q[B],H)),K.push(" ".repeat(V.padRight)),B++,B<X){let M=V.columnSep(I.Intern);if(M)K.push(M)}}if(V.columnSep(I.Right))K.push(V.columnSep(I.Right));K.push(y),J.push(K.join(""))}return J.join("")}render(V,q,H=!1){return this.renderInternal(V,q,H)}}var N=new Y("-","+","+","+"),e=new Y("=","+","+","+"),V1=new W().withColumnSeparator("|").withBorders("|").withSeparator(D.Title,e).withSeparator(D.Intern,N).withSeparator(D.Bottom,N).withSeparator(D.Top,N).withPadding(1,1),T1=new W().withColumnSeparator("|").withBorders("|").withSeparator(D.Intern,N).withSeparator(D.Title,N).withSeparator(D.Bottom,N).withSeparator(D.Top,N).withPadding(1,1),E1=new W().withColumnSeparator("|").withBorders("|").withSeparator(D.Title,N).withPadding(1,1),j1=new W().withColumnSeparator("|").withBorders("|").withPadding(1,1),w1=new W().withColumnSeparator("│").withBorders("│").withSeparator(D.Title,new Y("═","╪","╞","╡")).withSeparator(D.Intern,new Y("─","┼","├","┤")).withSeparator(D.Bottom,new Y("─","┴","└","┘")).withSeparator(D.Top,new Y("─","┬","┌","┐")).withPadding(1,1),F1=new W().withColumnSeparator("│").withBorders("│").withSeparator(D.Title,new Y("═","╪","╞","╡")).withSeparator(D.Intern,new Y("─","┼","├","┤")).withSeparator(D.Bottom,new Y("─","┴","╰","╯")).withSeparator(D.Top,new Y("─","┬","╭","╮")).withPadding(1,1);class q1{constructor(){this.rows=[],this.titles=void 0,this.format=V1}setFormat(V){this.format=V}getFormat(){return this.format}async addRow(V){let q=V.map((H)=>H instanceof x?H:new x(String(H)));this.rows.push(new S(q))}async addRows(V){for(let q of V)await this.addRow(q)}async setTitle(V){let q=V.map((H)=>H instanceof x?H:new x(String(H)));this.titles=new S(q)}columnCount(){let V=this.titles?this.titles.columnCount():0;for(let q of this.rows)V=Math.max(V,q.columnCount());return V}collectColWidths(){let V=this.columnCount(),q=new Array(V).fill(0),H=(J)=>{for(let X=0;X<V;X++)q[X]=Math.max(q[X],J.columnWidth(X,this.format))};if(this.titles)H(this.titles);return this.rows.forEach(H),q}render(V=!1){let q=this.collectColWidths(),H=this.format,J=[];if(J.push(H.printLine(q,D.Top)),this.titles)J.push(this.titles.render(H,q,V)),J.push(H.printLine(q,D.Title));return this.rows.forEach((X,Z)=>{if(J.push(X.render(H,q,V)),Z<this.rows.length-1)J.push(H.printLine(q,D.Intern))}),J.push(H.printLine(q,D.Bottom)),J.join("")}}export{M1 as bunnyLog,W as TableFormat,q1 as Table,L as Style,S as Row,N as MINUS_PLUS_SEP,Y as LineSeparator,D as LinePosition,F1 as FORMAT_UNICODE_ROUND,w1 as FORMAT_UNICODE,T1 as FORMAT_NO_TITLE,E1 as FORMAT_NO_LINESEP_WITH_TITLE,j1 as FORMAT_NO_LINESEP,V1 as FORMAT_DEFAULT,e as EQU_PLUS_SEP,I as ColumnPosition,w as Color,x as Cell,C as BunnyLogger,P as Alignment};