diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 34c68a7..d476b6e 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -37,8 +37,8 @@ jobs: - name: Check formatting with Prettier run: npm run format:check - - name: Run tests - run: npm run test:run + - name: Run tests with coverage + run: npm run test:coverage - name: Build project run: npm run build diff --git a/.gitignore b/.gitignore index 718f413..af61e16 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ node_modules dist +coverage env .aider* .env diff --git a/README.md b/README.md index c48ca02..a0ac39c 100644 --- a/README.md +++ b/README.md @@ -25,24 +25,6 @@ npx berget api-keys create --name "My CLI Key" export BERGET_API_KEY=sk_ber_your_api_key_here ``` -## Chat Command - -### Basic Usage - -```bash -# Interactive chat session -npx berget chat run - -# Use specific model -npx berget chat run openai/gpt-oss - -# Send direct message -npx berget chat run openai/gpt-oss "Explain what Docker is" - -# Use pipe for input -echo "What is Kubernetes?" | npx berget chat run openai/gpt-oss -``` - ## Environment Variables ```bash @@ -68,14 +50,11 @@ npx berget --help ```bash # Enable debug mode -npx berget --debug chat run openai/gpt-oss "test" +npx berget --debug auth whoami # Check authentication npx berget auth whoami -# List available models -npx berget chat list - # Check API key status npx berget api-keys list ``` diff --git a/coverage/base.css b/coverage/base.css deleted file mode 100644 index f418035..0000000 --- a/coverage/base.css +++ /dev/null @@ -1,224 +0,0 @@ -body, html { - margin:0; padding: 0; - height: 100%; -} -body { - font-family: Helvetica Neue, Helvetica, Arial; - font-size: 14px; - color:#333; -} -.small { font-size: 12px; } -*, *:after, *:before { - -webkit-box-sizing:border-box; - -moz-box-sizing:border-box; - box-sizing:border-box; - } -h1 { font-size: 20px; margin: 0;} -h2 { font-size: 14px; } -pre { - font: 12px/1.4 Consolas, "Liberation Mono", Menlo, Courier, monospace; - margin: 0; - padding: 0; - -moz-tab-size: 2; - -o-tab-size: 2; - tab-size: 2; -} -a { color:#0074D9; text-decoration:none; } -a:hover { text-decoration:underline; } -.strong { font-weight: bold; } -.space-top1 { padding: 10px 0 0 0; } -.pad2y { padding: 20px 0; } -.pad1y { padding: 10px 0; } -.pad2x { padding: 0 20px; } -.pad2 { padding: 20px; } -.pad1 { padding: 10px; } -.space-left2 { padding-left:55px; } -.space-right2 { padding-right:20px; } -.center { text-align:center; } -.clearfix { display:block; } -.clearfix:after { - content:''; - display:block; - height:0; - clear:both; - visibility:hidden; - } -.fl { float: left; } -@media only screen and (max-width:640px) { - .col3 { width:100%; max-width:100%; } - .hide-mobile { display:none!important; } -} - -.quiet { - color: #7f7f7f; - color: rgba(0,0,0,0.5); -} -.quiet a { opacity: 0.7; } - -.fraction { - font-family: Consolas, 'Liberation Mono', Menlo, Courier, monospace; - font-size: 10px; - color: #555; - background: #E8E8E8; - padding: 4px 5px; - border-radius: 3px; - vertical-align: middle; -} - -div.path a:link, div.path a:visited { color: #333; } -table.coverage { - border-collapse: collapse; - margin: 10px 0 0 0; - padding: 0; -} - -table.coverage td { - margin: 0; - padding: 0; - vertical-align: top; -} -table.coverage td.line-count { - text-align: right; - padding: 0 5px 0 20px; -} -table.coverage td.line-coverage { - text-align: right; - padding-right: 10px; - min-width:20px; -} - -table.coverage td span.cline-any { - display: inline-block; - padding: 0 5px; - width: 100%; -} -.missing-if-branch { - display: inline-block; - margin-right: 5px; - border-radius: 3px; - position: relative; - padding: 0 4px; - background: #333; - color: yellow; -} - -.skip-if-branch { - display: none; - margin-right: 10px; - position: relative; - padding: 0 4px; - background: #ccc; - color: white; -} -.missing-if-branch .typ, .skip-if-branch .typ { - color: inherit !important; -} -.coverage-summary { - border-collapse: collapse; - width: 100%; -} -.coverage-summary tr { border-bottom: 1px solid #bbb; } -.keyline-all { border: 1px solid #ddd; } -.coverage-summary td, .coverage-summary th { padding: 10px; } -.coverage-summary tbody { border: 1px solid #bbb; } -.coverage-summary td { border-right: 1px solid #bbb; } -.coverage-summary td:last-child { border-right: none; } -.coverage-summary th { - text-align: left; - font-weight: normal; - white-space: nowrap; -} -.coverage-summary th.file { border-right: none !important; } -.coverage-summary th.pct { } -.coverage-summary th.pic, -.coverage-summary th.abs, -.coverage-summary td.pct, -.coverage-summary td.abs { text-align: right; } -.coverage-summary td.file { white-space: nowrap; } -.coverage-summary td.pic { min-width: 120px !important; } -.coverage-summary tfoot td { } - -.coverage-summary .sorter { - height: 10px; - width: 7px; - display: inline-block; - margin-left: 0.5em; - background: url(sort-arrow-sprite.png) no-repeat scroll 0 0 transparent; -} -.coverage-summary .sorted .sorter { - background-position: 0 -20px; -} -.coverage-summary .sorted-desc .sorter { - background-position: 0 -10px; -} -.status-line { height: 10px; } -/* yellow */ -.cbranch-no { background: yellow !important; color: #111; } -/* dark red */ -.red.solid, .status-line.low, .low .cover-fill { background:#C21F39 } -.low .chart { border:1px solid #C21F39 } -.highlighted, -.highlighted .cstat-no, .highlighted .fstat-no, .highlighted .cbranch-no{ - background: #C21F39 !important; -} -/* medium red */ -.cstat-no, .fstat-no, .cbranch-no, .cbranch-no { background:#F6C6CE } -/* light red */ -.low, .cline-no { background:#FCE1E5 } -/* light green */ -.high, .cline-yes { background:rgb(230,245,208) } -/* medium green */ -.cstat-yes { background:rgb(161,215,106) } -/* dark green */ -.status-line.high, .high .cover-fill { background:rgb(77,146,33) } -.high .chart { border:1px solid rgb(77,146,33) } -/* dark yellow (gold) */ -.status-line.medium, .medium .cover-fill { background: #f9cd0b; } -.medium .chart { border:1px solid #f9cd0b; } -/* light yellow */ -.medium { background: #fff4c2; } - -.cstat-skip { background: #ddd; color: #111; } -.fstat-skip { background: #ddd; color: #111 !important; } -.cbranch-skip { background: #ddd !important; color: #111; } - -span.cline-neutral { background: #eaeaea; } - -.coverage-summary td.empty { - opacity: .5; - padding-top: 4px; - padding-bottom: 4px; - line-height: 1; - color: #888; -} - -.cover-fill, .cover-empty { - display:inline-block; - height: 12px; -} -.chart { - line-height: 0; -} -.cover-empty { - background: white; -} -.cover-full { - border-right: none !important; -} -pre.prettyprint { - border: none !important; - padding: 0 !important; - margin: 0 !important; -} -.com { color: #999 !important; } -.ignore-none { color: #999; font-weight: normal; } - -.wrapper { - min-height: 100%; - height: auto !important; - height: 100%; - margin: 0 auto -48px; -} -.footer, .push { - height: 48px; -} diff --git a/coverage/block-navigation.js b/coverage/block-navigation.js deleted file mode 100644 index 530d1ed..0000000 --- a/coverage/block-navigation.js +++ /dev/null @@ -1,87 +0,0 @@ -/* eslint-disable */ -var jumpToCode = (function init() { - // Classes of code we would like to highlight in the file view - var missingCoverageClasses = ['.cbranch-no', '.cstat-no', '.fstat-no']; - - // Elements to highlight in the file listing view - var fileListingElements = ['td.pct.low']; - - // We don't want to select elements that are direct descendants of another match - var notSelector = ':not(' + missingCoverageClasses.join('):not(') + ') > '; // becomes `:not(a):not(b) > ` - - // Selector that finds elements on the page to which we can jump - var selector = - fileListingElements.join(', ') + - ', ' + - notSelector + - missingCoverageClasses.join(', ' + notSelector); // becomes `:not(a):not(b) > a, :not(a):not(b) > b` - - // The NodeList of matching elements - var missingCoverageElements = document.querySelectorAll(selector); - - var currentIndex; - - function toggleClass(index) { - missingCoverageElements - .item(currentIndex) - .classList.remove('highlighted'); - missingCoverageElements.item(index).classList.add('highlighted'); - } - - function makeCurrent(index) { - toggleClass(index); - currentIndex = index; - missingCoverageElements.item(index).scrollIntoView({ - behavior: 'smooth', - block: 'center', - inline: 'center' - }); - } - - function goToPrevious() { - var nextIndex = 0; - if (typeof currentIndex !== 'number' || currentIndex === 0) { - nextIndex = missingCoverageElements.length - 1; - } else if (missingCoverageElements.length > 1) { - nextIndex = currentIndex - 1; - } - - makeCurrent(nextIndex); - } - - function goToNext() { - var nextIndex = 0; - - if ( - typeof currentIndex === 'number' && - currentIndex < missingCoverageElements.length - 1 - ) { - nextIndex = currentIndex + 1; - } - - makeCurrent(nextIndex); - } - - return function jump(event) { - if ( - document.getElementById('fileSearch') === document.activeElement && - document.activeElement != null - ) { - // if we're currently focused on the search input, we don't want to navigate - return; - } - - switch (event.which) { - case 78: // n - case 74: // j - goToNext(); - break; - case 66: // b - case 75: // k - case 80: // p - goToPrevious(); - break; - } - }; -})(); -window.addEventListener('keydown', jumpToCode); diff --git a/coverage/clover.xml b/coverage/clover.xml deleted file mode 100644 index 95df54d..0000000 --- a/coverage/clover.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/coverage/coverage-final.json b/coverage/coverage-final.json deleted file mode 100644 index 0967ef4..0000000 --- a/coverage/coverage-final.json +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/coverage/favicon.png b/coverage/favicon.png deleted file mode 100644 index c1525b8..0000000 Binary files a/coverage/favicon.png and /dev/null differ diff --git a/coverage/index.html b/coverage/index.html deleted file mode 100644 index 30510a0..0000000 --- a/coverage/index.html +++ /dev/null @@ -1,101 +0,0 @@ - - - - - - Code coverage report for All files - - - - - - - - - -
-
-

All files

-
- -
- Unknown% - Statements - 0/0 -
- - -
- Unknown% - Branches - 0/0 -
- - -
- Unknown% - Functions - 0/0 -
- - -
- Unknown% - Lines - 0/0 -
- - -
-

- Press n or j to go to the next uncovered block, b, p or k for the previous block. -

- -
-
-
- - - - - - - - - - - - - - - - -
FileStatementsBranchesFunctionsLines
-
-
-
- - - - - - - - \ No newline at end of file diff --git a/coverage/prettify.css b/coverage/prettify.css deleted file mode 100644 index b317a7c..0000000 --- a/coverage/prettify.css +++ /dev/null @@ -1 +0,0 @@ -.pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee} diff --git a/coverage/prettify.js b/coverage/prettify.js deleted file mode 100644 index b322523..0000000 --- a/coverage/prettify.js +++ /dev/null @@ -1,2 +0,0 @@ -/* eslint-disable */ -window.PR_SHOULD_USE_CONTINUATION=true;(function(){var h=["break,continue,do,else,for,if,return,while"];var u=[h,"auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"];var p=[u,"catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"];var l=[p,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"];var x=[p,"abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient"];var R=[x,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var"];var r="all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes";var w=[p,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"];var s="caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END";var I=[h,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"];var f=[h,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"];var H=[h,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"];var A=[l,R,w,s+I,f,H];var e=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/;var C="str";var z="kwd";var j="com";var O="typ";var G="lit";var L="pun";var F="pln";var m="tag";var E="dec";var J="src";var P="atn";var n="atv";var N="nocode";var M="(?:^^\\.?|[+-]|\\!|\\!=|\\!==|\\#|\\%|\\%=|&|&&|&&=|&=|\\(|\\*|\\*=|\\+=|\\,|\\-=|\\->|\\/|\\/=|:|::|\\;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|\\?|\\@|\\[|\\^|\\^=|\\^\\^|\\^\\^=|\\{|\\||\\|=|\\|\\||\\|\\|=|\\~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\\s*";function k(Z){var ad=0;var S=false;var ac=false;for(var V=0,U=Z.length;V122)){if(!(al<65||ag>90)){af.push([Math.max(65,ag)|32,Math.min(al,90)|32])}if(!(al<97||ag>122)){af.push([Math.max(97,ag)&~32,Math.min(al,122)&~32])}}}}af.sort(function(av,au){return(av[0]-au[0])||(au[1]-av[1])});var ai=[];var ap=[NaN,NaN];for(var ar=0;arat[0]){if(at[1]+1>at[0]){an.push("-")}an.push(T(at[1]))}}an.push("]");return an.join("")}function W(al){var aj=al.source.match(new RegExp("(?:\\[(?:[^\\x5C\\x5D]|\\\\[\\s\\S])*\\]|\\\\u[A-Fa-f0-9]{4}|\\\\x[A-Fa-f0-9]{2}|\\\\[0-9]+|\\\\[^ux0-9]|\\(\\?[:!=]|[\\(\\)\\^]|[^\\x5B\\x5C\\(\\)\\^]+)","g"));var ah=aj.length;var an=[];for(var ak=0,am=0;ak=2&&ai==="["){aj[ak]=X(ag)}else{if(ai!=="\\"){aj[ak]=ag.replace(/[a-zA-Z]/g,function(ao){var ap=ao.charCodeAt(0);return"["+String.fromCharCode(ap&~32,ap|32)+"]"})}}}}return aj.join("")}var aa=[];for(var V=0,U=Z.length;V=0;){S[ac.charAt(ae)]=Y}}var af=Y[1];var aa=""+af;if(!ag.hasOwnProperty(aa)){ah.push(af);ag[aa]=null}}ah.push(/[\0-\uffff]/);V=k(ah)})();var X=T.length;var W=function(ah){var Z=ah.sourceCode,Y=ah.basePos;var ad=[Y,F];var af=0;var an=Z.match(V)||[];var aj={};for(var ae=0,aq=an.length;ae=5&&"lang-"===ap.substring(0,5);if(am&&!(ai&&typeof ai[1]==="string")){am=false;ap=J}if(!am){aj[ag]=ap}}var ab=af;af+=ag.length;if(!am){ad.push(Y+ab,ap)}else{var al=ai[1];var ak=ag.indexOf(al);var ac=ak+al.length;if(ai[2]){ac=ag.length-ai[2].length;ak=ac-al.length}var ar=ap.substring(5);B(Y+ab,ag.substring(0,ak),W,ad);B(Y+ab+ak,al,q(ar,al),ad);B(Y+ab+ac,ag.substring(ac),W,ad)}}ah.decorations=ad};return W}function i(T){var W=[],S=[];if(T.tripleQuotedStrings){W.push([C,/^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\']))*(?:\'\'\'|$)|\"\"\"(?:[^\"\\]|\\[\s\S]|\"{1,2}(?=[^\"]))*(?:\"\"\"|$)|\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$))/,null,"'\""])}else{if(T.multiLineStrings){W.push([C,/^(?:\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)|\`(?:[^\\\`]|\\[\s\S])*(?:\`|$))/,null,"'\"`"])}else{W.push([C,/^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$)|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/,null,"\"'"])}}if(T.verbatimStrings){S.push([C,/^@\"(?:[^\"]|\"\")*(?:\"|$)/,null])}var Y=T.hashComments;if(Y){if(T.cStyleComments){if(Y>1){W.push([j,/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,null,"#"])}else{W.push([j,/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\r\n]*)/,null,"#"])}S.push([C,/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,null])}else{W.push([j,/^#[^\r\n]*/,null,"#"])}}if(T.cStyleComments){S.push([j,/^\/\/[^\r\n]*/,null]);S.push([j,/^\/\*[\s\S]*?(?:\*\/|$)/,null])}if(T.regexLiterals){var X=("/(?=[^/*])(?:[^/\\x5B\\x5C]|\\x5C[\\s\\S]|\\x5B(?:[^\\x5C\\x5D]|\\x5C[\\s\\S])*(?:\\x5D|$))+/");S.push(["lang-regex",new RegExp("^"+M+"("+X+")")])}var V=T.types;if(V){S.push([O,V])}var U=(""+T.keywords).replace(/^ | $/g,"");if(U.length){S.push([z,new RegExp("^(?:"+U.replace(/[\s,]+/g,"|")+")\\b"),null])}W.push([F,/^\s+/,null," \r\n\t\xA0"]);S.push([G,/^@[a-z_$][a-z_$@0-9]*/i,null],[O,/^(?:[@_]?[A-Z]+[a-z][A-Za-z_$@0-9]*|\w+_t\b)/,null],[F,/^[a-z_$][a-z_$@0-9]*/i,null],[G,new RegExp("^(?:0x[a-f0-9]+|(?:\\d(?:_\\d+)*\\d*(?:\\.\\d*)?|\\.\\d\\+)(?:e[+\\-]?\\d+)?)[a-z]*","i"),null,"0123456789"],[F,/^\\[\s\S]?/,null],[L,/^.[^\s\w\.$@\'\"\`\/\#\\]*/,null]);return g(W,S)}var K=i({keywords:A,hashComments:true,cStyleComments:true,multiLineStrings:true,regexLiterals:true});function Q(V,ag){var U=/(?:^|\s)nocode(?:\s|$)/;var ab=/\r\n?|\n/;var ac=V.ownerDocument;var S;if(V.currentStyle){S=V.currentStyle.whiteSpace}else{if(window.getComputedStyle){S=ac.defaultView.getComputedStyle(V,null).getPropertyValue("white-space")}}var Z=S&&"pre"===S.substring(0,3);var af=ac.createElement("LI");while(V.firstChild){af.appendChild(V.firstChild)}var W=[af];function ae(al){switch(al.nodeType){case 1:if(U.test(al.className)){break}if("BR"===al.nodeName){ad(al);if(al.parentNode){al.parentNode.removeChild(al)}}else{for(var an=al.firstChild;an;an=an.nextSibling){ae(an)}}break;case 3:case 4:if(Z){var am=al.nodeValue;var aj=am.match(ab);if(aj){var ai=am.substring(0,aj.index);al.nodeValue=ai;var ah=am.substring(aj.index+aj[0].length);if(ah){var ak=al.parentNode;ak.insertBefore(ac.createTextNode(ah),al.nextSibling)}ad(al);if(!ai){al.parentNode.removeChild(al)}}}break}}function ad(ak){while(!ak.nextSibling){ak=ak.parentNode;if(!ak){return}}function ai(al,ar){var aq=ar?al.cloneNode(false):al;var ao=al.parentNode;if(ao){var ap=ai(ao,1);var an=al.nextSibling;ap.appendChild(aq);for(var am=an;am;am=an){an=am.nextSibling;ap.appendChild(am)}}return aq}var ah=ai(ak.nextSibling,0);for(var aj;(aj=ah.parentNode)&&aj.nodeType===1;){ah=aj}W.push(ah)}for(var Y=0;Y=S){ah+=2}if(V>=ap){Z+=2}}}var t={};function c(U,V){for(var S=V.length;--S>=0;){var T=V[S];if(!t.hasOwnProperty(T)){t[T]=U}else{if(window.console){console.warn("cannot override language handler %s",T)}}}}function q(T,S){if(!(T&&t.hasOwnProperty(T))){T=/^\s*]*(?:>|$)/],[j,/^<\!--[\s\S]*?(?:-\->|$)/],["lang-",/^<\?([\s\S]+?)(?:\?>|$)/],["lang-",/^<%([\s\S]+?)(?:%>|$)/],[L,/^(?:<[%?]|[%?]>)/],["lang-",/^]*>([\s\S]+?)<\/xmp\b[^>]*>/i],["lang-js",/^]*>([\s\S]*?)(<\/script\b[^>]*>)/i],["lang-css",/^]*>([\s\S]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]),["default-markup","htm","html","mxml","xhtml","xml","xsl"]);c(g([[F,/^[\s]+/,null," \t\r\n"],[n,/^(?:\"[^\"]*\"?|\'[^\']*\'?)/,null,"\"'"]],[[m,/^^<\/?[a-z](?:[\w.:-]*\w)?|\/?>$/i],[P,/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^>\'\"\s]*(?:[^>\'\"\s\/]|\/(?=\s)))/],[L,/^[=<>\/]+/],["lang-js",/^on\w+\s*=\s*\"([^\"]+)\"/i],["lang-js",/^on\w+\s*=\s*\'([^\']+)\'/i],["lang-js",/^on\w+\s*=\s*([^\"\'>\s]+)/i],["lang-css",/^style\s*=\s*\"([^\"]+)\"/i],["lang-css",/^style\s*=\s*\'([^\']+)\'/i],["lang-css",/^style\s*=\s*([^\"\'>\s]+)/i]]),["in.tag"]);c(g([],[[n,/^[\s\S]+/]]),["uq.val"]);c(i({keywords:l,hashComments:true,cStyleComments:true,types:e}),["c","cc","cpp","cxx","cyc","m"]);c(i({keywords:"null,true,false"}),["json"]);c(i({keywords:R,hashComments:true,cStyleComments:true,verbatimStrings:true,types:e}),["cs"]);c(i({keywords:x,cStyleComments:true}),["java"]);c(i({keywords:H,hashComments:true,multiLineStrings:true}),["bsh","csh","sh"]);c(i({keywords:I,hashComments:true,multiLineStrings:true,tripleQuotedStrings:true}),["cv","py"]);c(i({keywords:s,hashComments:true,multiLineStrings:true,regexLiterals:true}),["perl","pl","pm"]);c(i({keywords:f,hashComments:true,multiLineStrings:true,regexLiterals:true}),["rb"]);c(i({keywords:w,cStyleComments:true,regexLiterals:true}),["js"]);c(i({keywords:r,hashComments:3,cStyleComments:true,multilineStrings:true,tripleQuotedStrings:true,regexLiterals:true}),["coffee"]);c(g([],[[C,/^[\s\S]+/]]),["regex"]);function d(V){var U=V.langExtension;try{var S=a(V.sourceNode);var T=S.sourceCode;V.sourceCode=T;V.spans=S.spans;V.basePos=0;q(U,T)(V);D(V)}catch(W){if("console" in window){console.log(W&&W.stack?W.stack:W)}}}function y(W,V,U){var S=document.createElement("PRE");S.innerHTML=W;if(U){Q(S,U)}var T={langExtension:V,numberLines:U,sourceNode:S};d(T);return S.innerHTML}function b(ad){function Y(af){return document.getElementsByTagName(af)}var ac=[Y("pre"),Y("code"),Y("xmp")];var T=[];for(var aa=0;aa=0){var ah=ai.match(ab);var am;if(!ah&&(am=o(aj))&&"CODE"===am.tagName){ah=am.className.match(ab)}if(ah){ah=ah[1]}var al=false;for(var ak=aj.parentNode;ak;ak=ak.parentNode){if((ak.tagName==="pre"||ak.tagName==="code"||ak.tagName==="xmp")&&ak.className&&ak.className.indexOf("prettyprint")>=0){al=true;break}}if(!al){var af=aj.className.match(/\blinenums\b(?::(\d+))?/);af=af?af[1]&&af[1].length?+af[1]:true:false;if(af){Q(aj,af)}S={langExtension:ah,sourceNode:aj,numberLines:af};d(S)}}}if(X]*(?:>|$)/],[PR.PR_COMMENT,/^<\!--[\s\S]*?(?:-\->|$)/],[PR.PR_PUNCTUATION,/^(?:<[%?]|[%?]>)/],["lang-",/^<\?([\s\S]+?)(?:\?>|$)/],["lang-",/^<%([\s\S]+?)(?:%>|$)/],["lang-",/^]*>([\s\S]+?)<\/xmp\b[^>]*>/i],["lang-handlebars",/^]*type\s*=\s*['"]?text\/x-handlebars-template['"]?\b[^>]*>([\s\S]*?)(<\/script\b[^>]*>)/i],["lang-js",/^]*>([\s\S]*?)(<\/script\b[^>]*>)/i],["lang-css",/^]*>([\s\S]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i],[PR.PR_DECLARATION,/^{{[#^>/]?\s*[\w.][^}]*}}/],[PR.PR_DECLARATION,/^{{&?\s*[\w.][^}]*}}/],[PR.PR_DECLARATION,/^{{{>?\s*[\w.][^}]*}}}/],[PR.PR_COMMENT,/^{{![^}]*}}/]]),["handlebars","hbs"]);PR.registerLangHandler(PR.createSimpleLexer([[PR.PR_PLAIN,/^[ \t\r\n\f]+/,null," \t\r\n\f"]],[[PR.PR_STRING,/^\"(?:[^\n\r\f\\\"]|\\(?:\r\n?|\n|\f)|\\[\s\S])*\"/,null],[PR.PR_STRING,/^\'(?:[^\n\r\f\\\']|\\(?:\r\n?|\n|\f)|\\[\s\S])*\'/,null],["lang-css-str",/^url\(([^\)\"\']*)\)/i],[PR.PR_KEYWORD,/^(?:url|rgb|\!important|@import|@page|@media|@charset|inherit)(?=[^\-\w]|$)/i,null],["lang-css-kw",/^(-?(?:[_a-z]|(?:\\[0-9a-f]+ ?))(?:[_a-z0-9\-]|\\(?:\\[0-9a-f]+ ?))*)\s*:/i],[PR.PR_COMMENT,/^\/\*[^*]*\*+(?:[^\/*][^*]*\*+)*\//],[PR.PR_COMMENT,/^(?:)/],[PR.PR_LITERAL,/^(?:\d+|\d*\.\d+)(?:%|[a-z]+)?/i],[PR.PR_LITERAL,/^#(?:[0-9a-f]{3}){1,2}/i],[PR.PR_PLAIN,/^-?(?:[_a-z]|(?:\\[\da-f]+ ?))(?:[_a-z\d\-]|\\(?:\\[\da-f]+ ?))*/i],[PR.PR_PUNCTUATION,/^[^\s\w\'\"]+/]]),["css"]);PR.registerLangHandler(PR.createSimpleLexer([],[[PR.PR_KEYWORD,/^-?(?:[_a-z]|(?:\\[\da-f]+ ?))(?:[_a-z\d\-]|\\(?:\\[\da-f]+ ?))*/i]]),["css-kw"]);PR.registerLangHandler(PR.createSimpleLexer([],[[PR.PR_STRING,/^[^\)\"\']+/]]),["css-str"]); diff --git a/coverage/sort-arrow-sprite.png b/coverage/sort-arrow-sprite.png deleted file mode 100644 index 6ed6831..0000000 Binary files a/coverage/sort-arrow-sprite.png and /dev/null differ diff --git a/coverage/sorter.js b/coverage/sorter.js deleted file mode 100644 index 4ed70ae..0000000 --- a/coverage/sorter.js +++ /dev/null @@ -1,210 +0,0 @@ -/* eslint-disable */ -var addSorting = (function() { - 'use strict'; - var cols, - currentSort = { - index: 0, - desc: false - }; - - // returns the summary table element - function getTable() { - return document.querySelector('.coverage-summary'); - } - // returns the thead element of the summary table - function getTableHeader() { - return getTable().querySelector('thead tr'); - } - // returns the tbody element of the summary table - function getTableBody() { - return getTable().querySelector('tbody'); - } - // returns the th element for nth column - function getNthColumn(n) { - return getTableHeader().querySelectorAll('th')[n]; - } - - function onFilterInput() { - const searchValue = document.getElementById('fileSearch').value; - const rows = document.getElementsByTagName('tbody')[0].children; - - // Try to create a RegExp from the searchValue. If it fails (invalid regex), - // it will be treated as a plain text search - let searchRegex; - try { - searchRegex = new RegExp(searchValue, 'i'); // 'i' for case-insensitive - } catch (error) { - searchRegex = null; - } - - for (let i = 0; i < rows.length; i++) { - const row = rows[i]; - let isMatch = false; - - if (searchRegex) { - // If a valid regex was created, use it for matching - isMatch = searchRegex.test(row.textContent); - } else { - // Otherwise, fall back to the original plain text search - isMatch = row.textContent - .toLowerCase() - .includes(searchValue.toLowerCase()); - } - - row.style.display = isMatch ? '' : 'none'; - } - } - - // loads the search box - function addSearchBox() { - var template = document.getElementById('filterTemplate'); - var templateClone = template.content.cloneNode(true); - templateClone.getElementById('fileSearch').oninput = onFilterInput; - template.parentElement.appendChild(templateClone); - } - - // loads all columns - function loadColumns() { - var colNodes = getTableHeader().querySelectorAll('th'), - colNode, - cols = [], - col, - i; - - for (i = 0; i < colNodes.length; i += 1) { - colNode = colNodes[i]; - col = { - key: colNode.getAttribute('data-col'), - sortable: !colNode.getAttribute('data-nosort'), - type: colNode.getAttribute('data-type') || 'string' - }; - cols.push(col); - if (col.sortable) { - col.defaultDescSort = col.type === 'number'; - colNode.innerHTML = - colNode.innerHTML + ''; - } - } - return cols; - } - // attaches a data attribute to every tr element with an object - // of data values keyed by column name - function loadRowData(tableRow) { - var tableCols = tableRow.querySelectorAll('td'), - colNode, - col, - data = {}, - i, - val; - for (i = 0; i < tableCols.length; i += 1) { - colNode = tableCols[i]; - col = cols[i]; - val = colNode.getAttribute('data-value'); - if (col.type === 'number') { - val = Number(val); - } - data[col.key] = val; - } - return data; - } - // loads all row data - function loadData() { - var rows = getTableBody().querySelectorAll('tr'), - i; - - for (i = 0; i < rows.length; i += 1) { - rows[i].data = loadRowData(rows[i]); - } - } - // sorts the table using the data for the ith column - function sortByIndex(index, desc) { - var key = cols[index].key, - sorter = function(a, b) { - a = a.data[key]; - b = b.data[key]; - return a < b ? -1 : a > b ? 1 : 0; - }, - finalSorter = sorter, - tableBody = document.querySelector('.coverage-summary tbody'), - rowNodes = tableBody.querySelectorAll('tr'), - rows = [], - i; - - if (desc) { - finalSorter = function(a, b) { - return -1 * sorter(a, b); - }; - } - - for (i = 0; i < rowNodes.length; i += 1) { - rows.push(rowNodes[i]); - tableBody.removeChild(rowNodes[i]); - } - - rows.sort(finalSorter); - - for (i = 0; i < rows.length; i += 1) { - tableBody.appendChild(rows[i]); - } - } - // removes sort indicators for current column being sorted - function removeSortIndicators() { - var col = getNthColumn(currentSort.index), - cls = col.className; - - cls = cls.replace(/ sorted$/, '').replace(/ sorted-desc$/, ''); - col.className = cls; - } - // adds sort indicators for current column being sorted - function addSortIndicators() { - getNthColumn(currentSort.index).className += currentSort.desc - ? ' sorted-desc' - : ' sorted'; - } - // adds event listeners for all sorter widgets - function enableUI() { - var i, - el, - ithSorter = function ithSorter(i) { - var col = cols[i]; - - return function() { - var desc = col.defaultDescSort; - - if (currentSort.index === i) { - desc = !currentSort.desc; - } - sortByIndex(i, desc); - removeSortIndicators(); - currentSort.index = i; - currentSort.desc = desc; - addSortIndicators(); - }; - }; - for (i = 0; i < cols.length; i += 1) { - if (cols[i].sortable) { - // add the click event handler on the th so users - // dont have to click on those tiny arrows - el = getNthColumn(i).querySelector('.sorter').parentElement; - if (el.addEventListener) { - el.addEventListener('click', ithSorter(i)); - } else { - el.attachEvent('onclick', ithSorter(i)); - } - } - } - } - // adds sorting functionality to the UI - return function() { - if (!getTable()) { - return; - } - cols = loadColumns(); - loadData(); - addSearchBox(); - addSortIndicators(); - enableUI(); - }; -})(); - -window.addEventListener('load', addSorting); diff --git a/package-lock.json b/package-lock.json index 8a35300..9936ca8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -18,8 +18,6 @@ "fs-extra": "^11.3.0", "globals": "^17.6.0", "jsonc-parser": "^3.3.1", - "marked": "^15.0.0", - "marked-terminal": "^7.3.0", "open": "^11.0.0", "openapi-fetch": "^0.17.0", "openapi-typescript": "^7.13.0", @@ -33,8 +31,6 @@ }, "devDependencies": { "@types/dotenv": "^6.1.1", - "@types/marked": "^5.0.2", - "@types/marked-terminal": "^6.1.1", "@types/node": "^22.15.17", "@types/which": "^3.0.4", "@vitest/coverage-v8": "^4.1.8", @@ -165,16 +161,6 @@ "node": ">= 20.12.0" } }, - "node_modules/@colors/colors": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.5.0.tgz", - "integrity": "sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ==", - "license": "MIT", - "optional": true, - "engines": { - "node": ">=0.1.90" - } - }, "node_modules/@emnapi/core": { "version": "1.10.0", "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.10.0.tgz", @@ -1215,18 +1201,6 @@ "dev": true, "license": "MIT" }, - "node_modules/@sindresorhus/is": { - "version": "4.6.0", - "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-4.6.0.tgz", - "integrity": "sha512-t09vSN3MdfsyCHoFcTRCH/iUtG7OJ0CsjzB8cjAmKc/va/kIgeDI/TxsigdncE/4be734m0cvIYwNaV4i2XqAw==", - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sindresorhus/is?sponsor=1" - } - }, "node_modules/@standard-schema/spec": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", @@ -1245,13 +1219,6 @@ "tslib": "^2.4.0" } }, - "node_modules/@types/cardinal": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/@types/cardinal/-/cardinal-2.1.1.tgz", - "integrity": "sha512-/xCVwg8lWvahHsV2wXZt4i64H1sdL+sN1Uoq7fAc8/FA6uYHjuIveDwPwvGUYp4VZiv85dVl6J/Bum3NDAOm8g==", - "dev": true, - "license": "MIT" - }, "node_modules/@types/chai": { "version": "5.2.3", "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", @@ -1301,39 +1268,6 @@ "dev": true, "license": "MIT" }, - "node_modules/@types/marked": { - "version": "5.0.2", - "resolved": "https://registry.npmjs.org/@types/marked/-/marked-5.0.2.tgz", - "integrity": "sha512-OucS4KMHhFzhz27KxmWg7J+kIYqyqoW5kdIEI319hqARQQUTqhao3M/F+uFnDXD0Rg72iDDZxZNxq5gvctmLlg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/marked-terminal": { - "version": "6.1.1", - "resolved": "https://registry.npmjs.org/@types/marked-terminal/-/marked-terminal-6.1.1.tgz", - "integrity": "sha512-DfoUqkmFDCED7eBY9vFUhJ9fW8oZcMAK5EwRDQ9drjTbpQa+DnBTQQCwWhTFVf4WsZ6yYcJTI8D91wxTWXRZZQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/cardinal": "^2.1", - "@types/node": "*", - "chalk": "^5.3.0", - "marked": ">=6.0.0 <12" - } - }, - "node_modules/@types/marked-terminal/node_modules/marked": { - "version": "11.2.0", - "resolved": "https://registry.npmjs.org/marked/-/marked-11.2.0.tgz", - "integrity": "sha512-HR0m3bvu0jAPYiIvLUUQtdg1g6D247//lvcekpHO1WMvbwDlwSkZAX9Lw4F4YHE1T0HaaNve0tuAWuV1UJ6vtw==", - "dev": true, - "license": "MIT", - "bin": { - "marked": "bin/marked.js" - }, - "engines": { - "node": ">= 18" - } - }, "node_modules/@types/node": { "version": "22.19.19", "resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.19.tgz", @@ -1847,6 +1781,7 @@ "version": "7.3.0", "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-7.3.0.tgz", "integrity": "sha512-BvU8nYgGQBxcmMuEeUEmNTvrMVjJNSH7RgW24vXexN4Ven6qCvy4TntnvlnwnMLTVlcRQQdbRY8NKnaIoeWDNg==", + "dev": true, "license": "MIT", "dependencies": { "environment": "^1.0.0" @@ -1862,6 +1797,7 @@ "version": "6.2.2", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz", "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==", + "dev": true, "license": "MIT", "engines": { "node": ">=12" @@ -1883,12 +1819,6 @@ "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, - "node_modules/any-promise": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz", - "integrity": "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==", - "license": "MIT" - }, "node_modules/argparse": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", @@ -2074,15 +2004,6 @@ "integrity": "sha512-HRQyTk2/YPEkt9TnUPbOpr64Uw3KOicFWPVBb+xiHvd6eBx/qPr9xqfBFDT8P2vWsvvz4jbEkfDe71W3VyNu2w==", "license": "MIT" }, - "node_modules/char-regex": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/char-regex/-/char-regex-1.0.2.tgz", - "integrity": "sha512-kWWXztvZ5SBQV+eRgKFeh8q5sLuZY2+8WUIzlxWVTg+oGwY14qylx1KbKzHd8P6ZYkAg0xyIDU9JMHhyJMZ1jw==", - "license": "MIT", - "engines": { - "node": ">=10" - } - }, "node_modules/ci-info": { "version": "4.4.0", "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-4.4.0.tgz", @@ -2138,117 +2059,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/cli-highlight": { - "version": "2.1.11", - "resolved": "https://registry.npmjs.org/cli-highlight/-/cli-highlight-2.1.11.tgz", - "integrity": "sha512-9KDcoEVwyUXrjcJNvHD0NFc/hiwe/WPVYIleQh2O1N2Zro5gWJZ/K+3DGn8w8P/F6FxOgzyC5bxDyHIgCSPhGg==", - "license": "ISC", - "dependencies": { - "chalk": "^4.0.0", - "highlight.js": "^10.7.1", - "mz": "^2.4.0", - "parse5": "^5.1.1", - "parse5-htmlparser2-tree-adapter": "^6.0.0", - "yargs": "^16.0.0" - }, - "bin": { - "highlight": "bin/highlight" - }, - "engines": { - "node": ">=8.0.0", - "npm": ">=5.0.0" - } - }, - "node_modules/cli-highlight/node_modules/ansi-styles": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", - "license": "MIT", - "dependencies": { - "color-convert": "^2.0.1" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, - "node_modules/cli-highlight/node_modules/chalk": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", - "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", - "license": "MIT", - "dependencies": { - "ansi-styles": "^4.1.0", - "supports-color": "^7.1.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/chalk?sponsor=1" - } - }, - "node_modules/cli-table3": { - "version": "0.6.5", - "resolved": "https://registry.npmjs.org/cli-table3/-/cli-table3-0.6.5.tgz", - "integrity": "sha512-+W/5efTR7y5HRD7gACw9yQjqMVvEMLBHmboM/kPWam+H+Hmyrgjh6YncVKK122YZkXrLudzTuAukUw9FnMf7IQ==", - "license": "MIT", - "dependencies": { - "string-width": "^4.2.0" - }, - "engines": { - "node": "10.* || >= 12.*" - }, - "optionalDependencies": { - "@colors/colors": "1.5.0" - } - }, - "node_modules/cli-table3/node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/cli-table3/node_modules/is-fullwidth-code-point": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", - "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/cli-table3/node_modules/string-width": { - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", - "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "license": "MIT", - "dependencies": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/cli-table3/node_modules/strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "license": "MIT", - "dependencies": { - "ansi-regex": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, "node_modules/cli-truncate": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/cli-truncate/-/cli-truncate-5.2.0.tgz", @@ -2266,111 +2076,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/cliui": { - "version": "7.0.4", - "resolved": "https://registry.npmjs.org/cliui/-/cliui-7.0.4.tgz", - "integrity": "sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ==", - "license": "ISC", - "dependencies": { - "string-width": "^4.2.0", - "strip-ansi": "^6.0.0", - "wrap-ansi": "^7.0.0" - } - }, - "node_modules/cliui/node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/cliui/node_modules/ansi-styles": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", - "license": "MIT", - "dependencies": { - "color-convert": "^2.0.1" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, - "node_modules/cliui/node_modules/is-fullwidth-code-point": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", - "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/cliui/node_modules/string-width": { - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", - "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "license": "MIT", - "dependencies": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/cliui/node_modules/strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "license": "MIT", - "dependencies": { - "ansi-regex": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/cliui/node_modules/wrap-ansi": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", - "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", - "license": "MIT", - "dependencies": { - "ansi-styles": "^4.0.0", - "string-width": "^4.1.0", - "strip-ansi": "^6.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/wrap-ansi?sponsor=1" - } - }, - "node_modules/color-convert": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", - "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", - "license": "MIT", - "dependencies": { - "color-name": "~1.1.4" - }, - "engines": { - "node": ">=7.0.0" - } - }, - "node_modules/color-name": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", - "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", - "license": "MIT" - }, "node_modules/colorette": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/colorette/-/colorette-1.4.0.tgz", @@ -2538,22 +2243,11 @@ "dev": true, "license": "ISC" }, - "node_modules/emoji-regex": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", - "license": "MIT" - }, - "node_modules/emojilib": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/emojilib/-/emojilib-2.4.0.tgz", - "integrity": "sha512-5U0rVMU5Y2n2+ykNLQqMoqklN9ICBT/KsvC1Gz6vqHbz2AXXGkG+Pm5rMWk/8Vjrr/mY9985Hi8DYzn1F09Nyw==", - "license": "MIT" - }, "node_modules/environment": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/environment/-/environment-1.1.0.tgz", "integrity": "sha512-xUtoPkMggbz0MPyPiIWr1Kp4aeWJjDZ6SMvURhimjdZgsRuDplF5/s9hcgGhyXMhs+6vpnuoiZ2kFiu3FMnS8Q==", + "dev": true, "license": "MIT", "engines": { "node": ">=18" @@ -2615,6 +2309,7 @@ "version": "3.2.0", "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, "license": "MIT", "engines": { "node": ">=6" @@ -3188,15 +2883,6 @@ "dev": true, "license": "MIT" }, - "node_modules/get-caller-file": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", - "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", - "license": "ISC", - "engines": { - "node": "6.* || 8.* || >= 10.*" - } - }, "node_modules/get-east-asian-width": { "version": "1.6.0", "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.6.0.tgz", @@ -3245,20 +2931,12 @@ "version": "4.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, "license": "MIT", "engines": { "node": ">=8" } }, - "node_modules/highlight.js": { - "version": "10.7.3", - "resolved": "https://registry.npmjs.org/highlight.js/-/highlight.js-10.7.3.tgz", - "integrity": "sha512-tzcUFauisWKNHaRkN4Wjl/ZA07gENAjFl3J/c480dprkGTg5EQstgaNFqBfUqCq54kZRIEcreTsAgF/m2quD7A==", - "license": "BSD-3-Clause", - "engines": { - "node": "*" - } - }, "node_modules/html-escaper": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", @@ -4082,39 +3760,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/marked": { - "version": "15.0.12", - "resolved": "https://registry.npmjs.org/marked/-/marked-15.0.12.tgz", - "integrity": "sha512-8dD6FusOQSrpv9Z1rdNMdlSgQOIP880DHqnohobOmYLElGEqAL/JvxvuxZO16r4HtjTlfPRDC1hbvxC9dPN2nA==", - "license": "MIT", - "bin": { - "marked": "bin/marked.js" - }, - "engines": { - "node": ">= 18" - } - }, - "node_modules/marked-terminal": { - "version": "7.3.0", - "resolved": "https://registry.npmjs.org/marked-terminal/-/marked-terminal-7.3.0.tgz", - "integrity": "sha512-t4rBvPsHc57uE/2nJOLmMbZCQ4tgAccAED3ngXQqW6g+TxA488JzJ+FK3lQkzBQOI1mRV/r/Kq+1ZlJ4D0owQw==", - "license": "MIT", - "dependencies": { - "ansi-escapes": "^7.0.0", - "ansi-regex": "^6.1.0", - "chalk": "^5.4.1", - "cli-highlight": "^2.1.11", - "cli-table3": "^0.6.5", - "node-emoji": "^2.2.0", - "supports-hyperlinks": "^3.1.0" - }, - "engines": { - "node": ">=16.0.0" - }, - "peerDependencies": { - "marked": ">=1 <16" - } - }, "node_modules/mimic-function": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/mimic-function/-/mimic-function-5.0.1.tgz", @@ -4150,17 +3795,6 @@ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", "license": "MIT" }, - "node_modules/mz": { - "version": "2.7.0", - "resolved": "https://registry.npmjs.org/mz/-/mz-2.7.0.tgz", - "integrity": "sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==", - "license": "MIT", - "dependencies": { - "any-promise": "^1.0.0", - "object-assign": "^4.0.1", - "thenify-all": "^1.0.0" - } - }, "node_modules/nanoid": { "version": "3.3.12", "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.12.tgz", @@ -4197,21 +3831,6 @@ "node": ">=18" } }, - "node_modules/node-emoji": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/node-emoji/-/node-emoji-2.2.0.tgz", - "integrity": "sha512-Z3lTE9pLaJF47NyMhd4ww1yFTAP8YhYI8SleJiHzM46Fgpm5cnNzSl9XfzFNqbaz+VlJrIj3fXQ4DeN1Rjm6cw==", - "license": "MIT", - "dependencies": { - "@sindresorhus/is": "^4.6.0", - "char-regex": "^1.0.2", - "emojilib": "^2.4.0", - "skin-tone": "^2.0.0" - }, - "engines": { - "node": ">=18" - } - }, "node_modules/node-releases": { "version": "2.0.47", "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.47.tgz", @@ -4231,15 +3850,6 @@ "url": "https://github.com/sponsors/panva" } }, - "node_modules/object-assign": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", - "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/obug": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/obug/-/obug-2.1.2.tgz", @@ -4417,27 +4027,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/parse5": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/parse5/-/parse5-5.1.1.tgz", - "integrity": "sha512-ugq4DFI0Ptb+WWjAdOK16+u/nHfiIrcE+sh8kZMaM0WllQKLI9rOUq6c2b7cwPkXdzfQESqvoqK6ug7U/Yyzug==", - "license": "MIT" - }, - "node_modules/parse5-htmlparser2-tree-adapter": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/parse5-htmlparser2-tree-adapter/-/parse5-htmlparser2-tree-adapter-6.0.1.tgz", - "integrity": "sha512-qPuWvbLgvDGilKc5BoicRovlT4MtYT6JfJyBOMDsKoiT+GiuP5qyrPCnR9HcPECIJJmZh5jRndyNThnhhb/vlA==", - "license": "MIT", - "dependencies": { - "parse5": "^6.0.1" - } - }, - "node_modules/parse5-htmlparser2-tree-adapter/node_modules/parse5": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/parse5/-/parse5-6.0.1.tgz", - "integrity": "sha512-Ofn/CTFzRGTTxwpNEs9PP93gXShHcTq255nzRYSKe8AkVpZY7e1fpmTfOyoIvjP5HG7Z2ZM7VS9PPhQGW2pOpw==", - "license": "MIT" - }, "node_modules/path-exists": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", @@ -4639,15 +4228,6 @@ "regjsparser": "bin/parser" } }, - "node_modules/require-directory": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", - "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/require-from-string": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", @@ -4804,18 +4384,6 @@ "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==", "license": "MIT" }, - "node_modules/skin-tone": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/skin-tone/-/skin-tone-2.0.0.tgz", - "integrity": "sha512-kUMbT1oBJCpgrnKoSr0o6wPtvRWT9W9UKvGLwfJYO2WuahZRHOpEyL1ckyMGgMWh0UdpmaoFqKKD29WTomNEGA==", - "license": "MIT", - "dependencies": { - "unicode-emoji-modifier-base": "^1.0.0" - }, - "engines": { - "node": ">=8" - } - }, "node_modules/slice-ansi": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-8.0.0.tgz", @@ -4917,6 +4485,7 @@ "version": "7.2.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, "license": "MIT", "dependencies": { "has-flag": "^4.0.0" @@ -4925,22 +4494,6 @@ "node": ">=8" } }, - "node_modules/supports-hyperlinks": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/supports-hyperlinks/-/supports-hyperlinks-3.2.0.tgz", - "integrity": "sha512-zFObLMyZeEwzAoKCyu1B91U79K2t7ApXuQfo8OuxwXLDgcKxuwM+YvcbIhm6QWqz7mHUH1TVytR1PwVVjEuMig==", - "license": "MIT", - "dependencies": { - "has-flag": "^4.0.0", - "supports-color": "^7.0.0" - }, - "engines": { - "node": ">=14.18" - }, - "funding": { - "url": "https://github.com/chalk/supports-hyperlinks?sponsor=1" - } - }, "node_modules/synckit": { "version": "0.11.13", "resolved": "https://registry.npmjs.org/synckit/-/synckit-0.11.13.tgz", @@ -4957,27 +4510,6 @@ "url": "https://opencollective.com/synckit" } }, - "node_modules/thenify": { - "version": "3.3.1", - "resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz", - "integrity": "sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==", - "license": "MIT", - "dependencies": { - "any-promise": "^1.0.0" - } - }, - "node_modules/thenify-all": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/thenify-all/-/thenify-all-1.6.0.tgz", - "integrity": "sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==", - "license": "MIT", - "dependencies": { - "thenify": ">= 3.1.0 < 4" - }, - "engines": { - "node": ">=0.8" - } - }, "node_modules/tinybench": { "version": "2.9.0", "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", @@ -5132,15 +4664,6 @@ "dev": true, "license": "MIT" }, - "node_modules/unicode-emoji-modifier-base": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/unicode-emoji-modifier-base/-/unicode-emoji-modifier-base-1.0.0.tgz", - "integrity": "sha512-yLSH4py7oFH3oG/9K+XWrz1pSi3dfUrWEnInbxMfArOfc1+33BlGPQtLsOYwvdMy11AwUBetYuaRxSPqgkq+8g==", - "license": "MIT", - "engines": { - "node": ">=4" - } - }, "node_modules/universalify": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz", @@ -5441,15 +4964,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/y18n": { - "version": "5.0.8", - "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", - "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", - "license": "ISC", - "engines": { - "node": ">=10" - } - }, "node_modules/yaml": { "version": "2.9.0", "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.0.tgz", @@ -5473,24 +4987,6 @@ "integrity": "sha512-2PTINUwsRqSd+s8XxKaJWQlUuEMHJQyEuh2edBbW8KNJz0SJPwUSD2zRWqezFEdN7IzAgeuYHFUCF7o8zRdZ0A==", "license": "Apache-2.0" }, - "node_modules/yargs": { - "version": "16.2.0", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-16.2.0.tgz", - "integrity": "sha512-D1mvvtDG0L5ft/jGWkLpG1+m0eQxOfaBvTNELraWj22wSVUMWxZUvYgJYcKh6jGGIkJFhH4IZPQhR4TKpc8mBw==", - "license": "MIT", - "dependencies": { - "cliui": "^7.0.2", - "escalade": "^3.1.1", - "get-caller-file": "^2.0.5", - "require-directory": "^2.1.1", - "string-width": "^4.2.0", - "y18n": "^5.0.5", - "yargs-parser": "^20.2.2" - }, - "engines": { - "node": ">=10" - } - }, "node_modules/yargs-parser": { "version": "21.1.1", "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", @@ -5500,59 +4996,6 @@ "node": ">=12" } }, - "node_modules/yargs/node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/yargs/node_modules/is-fullwidth-code-point": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", - "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/yargs/node_modules/string-width": { - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", - "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "license": "MIT", - "dependencies": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/yargs/node_modules/strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "license": "MIT", - "dependencies": { - "ansi-regex": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/yargs/node_modules/yargs-parser": { - "version": "20.2.9", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.9.tgz", - "integrity": "sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==", - "license": "ISC", - "engines": { - "node": ">=10" - } - }, "node_modules/yocto-queue": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", diff --git a/package.json b/package.json index a924e77..4cba65b 100644 --- a/package.json +++ b/package.json @@ -21,6 +21,7 @@ "build": "tsc", "test": "vitest", "test:run": "vitest run", + "test:coverage": "vitest run --coverage", "typecheck": "tsc --noEmit", "lint": "eslint .", "lint:fix": "eslint . --fix", @@ -35,8 +36,6 @@ "description": "This is a cli command for interacting with the AI infrastructure provider Berget", "devDependencies": { "@types/dotenv": "^6.1.1", - "@types/marked": "^5.0.2", - "@types/marked-terminal": "^6.1.1", "@types/node": "^22.15.17", "@types/which": "^3.0.4", "@vitest/coverage-v8": "^4.1.8", @@ -66,8 +65,6 @@ "fs-extra": "^11.3.0", "globals": "^17.6.0", "jsonc-parser": "^3.3.1", - "marked": "^15.0.0", - "marked-terminal": "^7.3.0", "open": "^11.0.0", "openapi-fetch": "^0.17.0", "openapi-typescript": "^7.13.0", diff --git a/src/commands/chat.ts b/src/commands/chat.ts deleted file mode 100644 index 4a16d15..0000000 --- a/src/commands/chat.ts +++ /dev/null @@ -1,524 +0,0 @@ -import { confirm as clackConfirm, isCancel } from '@clack/prompts'; -import chalk from 'chalk'; -import { Command } from 'commander'; -import readline from 'node:readline'; - -import { COMMAND_GROUPS, SUBCOMMANDS } from '../constants/command-structure.js'; -import { ApiKeyService } from '../services/api-key-service.js'; -import { AuthService } from '../services/auth-service.js'; -import { ChatCompletionOptions, ChatMessage, ChatService } from '../services/chat-service.js'; -import { DefaultApiKeyManager } from '../utils/default-api-key.js'; -import { handleError } from '../utils/error-handler.js'; -import { containsMarkdown, renderMarkdown } from '../utils/markdown-renderer.js'; - -/** - * Register chat commands - */ -export function registerChatCommands(program: Command): void { - const chat = program.command(COMMAND_GROUPS.CHAT).description('Interact with AI chat models'); - - chat - .command(SUBCOMMANDS.CHAT.RUN) - .description('Run a chat session with a specified model') - .argument('[message]', 'Message to send directly (skips interactive mode)') - .option('-m, --model ', 'Model to use (default: kimi-k2.6)') - .option('-t, --temperature ', 'Temperature (0-1)', Number.parseFloat) - .option('--max-tokens ', 'Maximum tokens to generate', Number.parseInt) - .option('-k, --api-key ', 'API key to use for this chat session') - .option('--api-key-id ', 'ID of the API key to use from your saved keys') - .option('--no-stream', 'Disable streaming (streaming is enabled by default)') - .action(async (message, options) => { - try { - let apiKey = await resolveApiKey(options); - - if (!apiKey && options.apiKeyId) { - apiKey = await resolveApiKeyFromId(options.apiKeyId); - } - - if (!(await verifyAuthentication(apiKey))) { - return; - } - - const messages: ChatMessage[] = []; - const inputMessage = await resolveInputMessage(message); - - if (inputMessage) { - await runSingleShotChat(inputMessage, options, apiKey); - return; - } - - await runInteractiveChat(options, apiKey, messages); - } catch (error) { - handleError('Failed to create chat completion', error); - } - }); - - chat - .command(SUBCOMMANDS.CHAT.LIST) - .description('List available chat models') - .option('-k, --api-key ', 'API key to use for this request') - .option('--api-key-id ', 'ID of the API key to use from your saved keys') - .action(async (options) => { - try { - const apiKey = await resolveApiKeyForList(options); - const chatService = ChatService.getInstance(); - const models = await chatService.listModels(apiKey); - - if (program.opts().debug) { - console.log(chalk.yellow('DEBUG: Models response:')); - console.log(chalk.yellow(JSON.stringify(models, null, 2))); - } - - displayModels(models); - } catch (error) { - handleError('Failed to list chat models', error); - } - }); -} - -function buildCompletionOptions( - options: any, - messages: ChatMessage[], - apiKey: string | undefined, -): ChatCompletionOptions { - const completionOptions: ChatCompletionOptions = { - max_tokens: options.maxTokens || 4096, - messages: messages, - model: options.model || 'openai/gpt-oss', - stream: options.stream !== false, - temperature: options.temperature === undefined ? 0.7 : options.temperature, - }; - - if (apiKey) { - completionOptions.apiKey = apiKey; - } - - return completionOptions; -} - -function createAskQuestion( - rl: readline.Interface, - messages: ChatMessage[], - apiKey: string | undefined, - options: any, - chatService: ChatService, -): () => void { - return () => { - rl.question(chalk.green('You: '), async (input) => { - if (input.toLowerCase() === 'exit') { - console.log(chalk.cyan('Goodbye!')); - rl.close(); - return; - } - - messages.push({ content: input, role: 'user' }); - - try { - const completionOptions = buildCompletionOptions(options, messages, apiKey); - - if (completionOptions.stream) { - await runInteractiveStreaming(chatService, completionOptions, messages); - } else { - await runInteractiveNonStreaming(chatService, completionOptions, messages); - } - - createAskQuestion(rl, messages, apiKey, options, chatService)(); - } catch (error) { - console.error(chalk.red('Error: Failed to get response')); - if (error instanceof Error) { - console.error(chalk.red(error.message)); - } - createAskQuestion(rl, messages, apiKey, options, chatService)(); - } - }); - }; -} - -function displayModels(models: any): void { - console.log(chalk.bold('Available Chat Models:')); - console.log(chalk.dim('─'.repeat(70))); - console.log(chalk.dim('MODEL ID'.padEnd(40)) + chalk.dim('CAPABILITIES')); - console.log(chalk.dim('─'.repeat(70))); - - const activeModels = models.data.filter((model: any) => model.active === true); - - for (const model of activeModels) { - const capabilities = []; - if (model.capabilities.vision) capabilities.push('vision'); - if (model.capabilities.function_calling) capabilities.push('function_calling'); - if (model.capabilities.json_mode) capabilities.push('json_mode'); - - const modelId = `${model.owned_by.toLowerCase()}/${model.id}`.padEnd(40); - console.log(modelId + capabilities.join(', ')); - } -} - -async function displayResponse(response: any): Promise { - if (!response || !response.choices || !response.choices[0] || !response.choices[0].message) { - console.error(chalk.red('Error: Unexpected response format from API')); - console.error(chalk.red('Response:', JSON.stringify(response, null, 2))); - throw new Error('Unexpected response format from API'); - } - - const assistantMessage = response.choices[0].message.content; - if (containsMarkdown(assistantMessage)) { - console.log(renderMarkdown(assistantMessage)); - } else { - console.log(assistantMessage); - } -} - -async function handleNonStreamingCompletion( - chatService: ChatService, - completionOptions: ChatCompletionOptions, -): Promise { - const response = await chatService.createCompletion(completionOptions); - await displayResponse(response); -} - -async function handleStreamingCompletion( - chatService: ChatService, - completionOptions: ChatCompletionOptions, -): Promise { - let assistantResponse = ''; - - completionOptions.onChunk = (chunk: any) => { - if ( - chunk.choices && - chunk.choices[0] && - chunk.choices[0].delta && - chunk.choices[0].delta.content - ) { - const content = chunk.choices[0].delta.content; - try { - process.stdout.write(content); - } catch (error: any) { - if (error.code === 'EPIPE') { - return; - } - throw error; - } - assistantResponse += content; - } - }; - - try { - await chatService.createCompletion(completionOptions); - } catch (streamError) { - console.error(chalk.red('\nStreaming error:'), streamError); - console.log(chalk.yellow('Falling back to non-streaming mode...')); - completionOptions.stream = false; - delete completionOptions.onChunk; - - const response = await chatService.createCompletion(completionOptions); - if (response && response.choices && response.choices[0] && response.choices[0].message) { - assistantResponse = response.choices[0].message.content; - console.log(assistantResponse); - } - } - - console.log(); -} - -async function resolveApiKey(options: any): Promise { - const environmentApiKey = process.env.BERGET_API_KEY; - if (environmentApiKey) { - console.log(chalk.dim('Using API key from BERGET_API_KEY environment variable')); - - if (process.argv.includes('--debug')) { - console.log( - chalk.yellow(`DEBUG: API key from env starts with: ${environmentApiKey.slice(0, 4)}...`), - ); - } - return environmentApiKey; - } - - if (options.apiKey) { - console.log(chalk.dim('Using API key from command line argument')); - return options.apiKey; - } - - if (!options.apiKeyId) { - return resolveDefaultApiKey(); - } - - return undefined; -} - -async function resolveApiKeyForList(options: any): Promise { - const apiKey = options.apiKey; - let apiKeyId = options.apiKeyId; - - if (!apiKey && !apiKeyId) { - const defaultApiKeyManager = DefaultApiKeyManager.getInstance(); - const defaultApiKeyData = defaultApiKeyManager.getDefaultApiKeyData(); - - if (defaultApiKeyData) { - apiKeyId = defaultApiKeyData.id; - console.log(chalk.dim(`Using default API key: ${defaultApiKeyData.name}`)); - } - } - - if (apiKeyId && !apiKey) { - return resolveApiKeyFromId(apiKeyId); - } - - return apiKey; -} - -async function resolveApiKeyFromId(apiKeyId: string): Promise { - try { - const apiKeyService = ApiKeyService.getInstance(); - const keys = await apiKeyService.list(); - const selectedKey = keys.find((key) => key.id.toString() === apiKeyId); - - if (!selectedKey) { - console.log( - chalk.yellow(`API key with ID ${apiKeyId} not found. Using default authentication.`), - ); - return undefined; - } - - console.log(chalk.dim(`Using API key: ${selectedKey.name}`)); - - const shouldRotate = await clackConfirm({ - message: `To use API key "${selectedKey.name}", it needs to be rotated. This will invalidate the current key. Continue?`, - }); - if (isCancel(shouldRotate)) { - console.log(chalk.yellow('Operation cancelled.')); - return undefined; - } - - if (shouldRotate) { - const rotatedKey = await apiKeyService.rotate(apiKeyId); - console.log(chalk.green(`API key "${selectedKey.name}" rotated successfully.`)); - return rotatedKey.key; - } else { - console.log(chalk.yellow('Using default authentication instead.')); - return undefined; - } - } catch (error) { - const errorMessage = error instanceof Error ? error.message : String(error); - const isAuthError = - errorMessage.includes('Unauthorized') || - errorMessage.includes('Authentication failed') || - errorMessage.includes('AUTH_FAILED'); - - if (isAuthError) { - console.log(chalk.yellow('Authentication required. Please run `berget auth login` first.')); - } else { - console.error(chalk.red('Error fetching API key:')); - console.error(error); - } - console.log(chalk.yellow('Using default authentication instead.')); - return undefined; - } -} - -async function resolveDefaultApiKey(): Promise { - try { - const defaultApiKeyManager = DefaultApiKeyManager.getInstance(); - const defaultApiKeyData = defaultApiKeyManager.getDefaultApiKeyData(); - - if (defaultApiKeyData) { - if (defaultApiKeyData.key) { - console.log(chalk.dim(`Using default API key: ${defaultApiKeyData.name}`)); - return defaultApiKeyData.key; - } - - console.log( - chalk.yellow( - `Default API key "${defaultApiKeyData.name}" exists but the key value is missing.`, - ), - ); - console.log( - chalk.yellow(`Try rotating the key with: berget api-keys rotate ${defaultApiKeyData.id}`), - ); - return undefined; - } - - console.log(chalk.yellow('No default API key set.')); - const apiKey = await defaultApiKeyManager.promptForDefaultApiKey(); - - if (!apiKey) { - console.log(chalk.red('Error: An API key is required to use the chat command.')); - console.log(chalk.yellow('You can:')); - console.log( - chalk.yellow('1. Create an API key with: berget api-keys create --name "My Key"'), - ); - console.log(chalk.yellow('2. Set a default API key with: berget api-keys set-default ')); - console.log(chalk.yellow('3. Provide an API key with the --api-key option')); - return undefined; - } - - return apiKey; - } catch (error) { - if (process.argv.includes('--debug')) { - console.log(chalk.yellow('DEBUG: Error checking default API key:')); - console.log(chalk.yellow(String(error))); - } - return undefined; - } -} - -async function resolveInputMessage(message: string | undefined): Promise { - let inputMessage = message; - let stdinContent = ''; - - if (!process.stdin.isTTY) { - const chunks = []; - for await (const chunk of process.stdin) { - chunks.push(chunk); - } - stdinContent = Buffer.concat(chunks).toString('utf8').trim(); - } - - if (stdinContent && message) { - inputMessage = `${stdinContent}\n\n${message}`; - } else if (stdinContent && !message) { - inputMessage = stdinContent; - } - - return inputMessage; -} - -async function runInteractiveChat( - options: any, - apiKey: string | undefined, - messages: ChatMessage[], -): Promise { - const rl = readline.createInterface({ - input: process.stdin, - output: process.stdout, - }); - - console.log(chalk.cyan('Chat with Berget AI (type "exit" to quit)')); - console.log(chalk.cyan('----------------------------------------')); - - const chatService = ChatService.getInstance(); - const askQuestion = createAskQuestion(rl, messages, apiKey, options, chatService); - askQuestion(); -} - -async function runInteractiveNonStreaming( - chatService: ChatService, - completionOptions: ChatCompletionOptions, - messages: ChatMessage[], -): Promise { - const response = await chatService.createCompletion(completionOptions); - - if (!response || !response.choices || !response.choices[0] || !response.choices[0].message) { - console.error(chalk.red('Error: Unexpected response format from API')); - console.error(chalk.red('Response:', JSON.stringify(response, null, 2))); - throw new Error('Unexpected response format from API'); - } - - const assistantMessage = response.choices[0].message.content; - messages.push({ content: assistantMessage, role: 'assistant' }); - - console.log(chalk.blue('Assistant: ')); - if (containsMarkdown(assistantMessage)) { - console.log(renderMarkdown(assistantMessage)); - } else { - console.log(assistantMessage); - } - - console.log(); -} - -async function runInteractiveStreaming( - chatService: ChatService, - completionOptions: ChatCompletionOptions, - messages: ChatMessage[], -): Promise { - let assistantResponse = ''; - console.log(chalk.blue('Assistant: ')); - - completionOptions.onChunk = (chunk: any) => { - if ( - chunk.choices && - chunk.choices[0] && - chunk.choices[0].delta && - chunk.choices[0].delta.content - ) { - const content = chunk.choices[0].delta.content; - try { - process.stdout.write(content); - } catch (error: any) { - if (error.code === 'EPIPE') { - return; - } - throw error; - } - assistantResponse += content; - } - }; - - try { - await chatService.createCompletion(completionOptions); - } catch (streamError) { - console.error(chalk.red('\nStreaming error:'), streamError); - console.log(chalk.yellow('Falling back to non-streaming mode...')); - completionOptions.stream = false; - delete completionOptions.onChunk; - - const response = await chatService.createCompletion(completionOptions); - if (response && response.choices && response.choices[0] && response.choices[0].message) { - assistantResponse = response.choices[0].message.content; - console.log(assistantResponse); - } - } - - console.log('\n'); - messages.push({ content: assistantResponse, role: 'assistant' }); -} - -async function runSingleShotChat( - inputMessage: string, - options: any, - apiKey: string | undefined, -): Promise { - const messages: ChatMessage[] = []; - - if (options.system) { - messages.push({ content: options.system, role: 'system' }); - } - - messages.push({ content: inputMessage, role: 'user' }); - - try { - const chatService = ChatService.getInstance(); - const completionOptions = buildCompletionOptions(options, messages, apiKey); - - if (completionOptions.stream) { - await handleStreamingCompletion(chatService, completionOptions); - } else { - await handleNonStreamingCompletion(chatService, completionOptions); - } - } catch (error) { - console.error(chalk.red('Error: Failed to get response')); - if (error instanceof Error) { - console.error(chalk.red(error.message)); - } - process.exitCode = 1; - } -} - -async function verifyAuthentication(apiKey: string | undefined): Promise { - if (apiKey) { - return true; - } - - try { - AuthService.getInstance(); - return true; - } catch { - console.log(chalk.red('Error: Authentication required for chat')); - console.log(chalk.yellow('Please either:')); - console.log(chalk.yellow('1. Log in with `berget auth login`')); - console.log(chalk.yellow('2. Provide an API key with `--api-key`')); - console.log(chalk.yellow('3. Provide an API key ID with `--api-key-id`')); - console.log(chalk.yellow('4. Set a default API key with `berget api-keys set-default `')); - return false; - } -} diff --git a/src/commands/index.ts b/src/commands/index.ts index 5b2c2f2..a1994fe 100644 --- a/src/commands/index.ts +++ b/src/commands/index.ts @@ -4,7 +4,6 @@ import { registerApiKeyCommands } from './api-keys.js'; import { registerAuthCommands } from './auth.js'; import { registerAutocompleteCommands } from './autocomplete.js'; import { registerBillingCommands } from './billing.js'; -import { registerChatCommands } from './chat.js'; import { registerClusterCommands } from './clusters.js'; import { registerCodeCommands } from './code.js'; import { registerModelCommands } from './models.js'; @@ -20,7 +19,6 @@ export function registerCommands(program: Command): void { registerBillingCommands(program); registerModelCommands(program); registerUserCommands(program); - registerChatCommands(program); registerAutocompleteCommands(program); registerCodeCommands(program); } diff --git a/src/constants/command-structure.ts b/src/constants/command-structure.ts index 472dd17..3b75524 100644 --- a/src/constants/command-structure.ts +++ b/src/constants/command-structure.ts @@ -9,7 +9,6 @@ export const COMMAND_GROUPS = { APPS: 'apps', AUTH: 'auth', BILLING: 'billing', - CHAT: 'chat', CLUSTERS: 'clusters', CODE: 'code', FLUX: 'flux', @@ -60,12 +59,6 @@ export const SUBCOMMANDS = { UPDATE_SUBSCRIPTION: 'update-subscription', }, - // Chat commands - CHAT: { - LIST: 'list', - RUN: 'run', - }, - // Clusters commands CLUSTERS: { DESCRIBE: 'describe', @@ -152,8 +145,6 @@ export const COMMAND_DESCRIPTIONS = { [`${COMMAND_GROUPS.BILLING} ${SUBCOMMANDS.BILLING.UPDATE_SUBSCRIPTION}`]: 'Update subscription plan', - [`${COMMAND_GROUPS.CHAT} ${SUBCOMMANDS.CHAT.LIST}`]: 'List available chat models', - [`${COMMAND_GROUPS.CHAT} ${SUBCOMMANDS.CHAT.RUN}`]: 'Run a chat session with a specified model', [`${COMMAND_GROUPS.CLUSTERS} ${SUBCOMMANDS.CLUSTERS.DESCRIBE}`]: 'Get detailed information about a cluster', @@ -190,8 +181,6 @@ export const COMMAND_DESCRIPTIONS = { // Billing group [COMMAND_GROUPS.BILLING]: 'Manage billing and usage', - // Chat group - [COMMAND_GROUPS.CHAT]: 'Interact with AI chat models', // Clusters group [COMMAND_GROUPS.CLUSTERS]: 'Manage Kubernetes clusters', diff --git a/src/services/chat-service.ts b/src/services/chat-service.ts deleted file mode 100644 index e794104..0000000 --- a/src/services/chat-service.ts +++ /dev/null @@ -1,487 +0,0 @@ -import { ReadableStreamDefaultReader } from 'node:stream/web'; - -import { createAuthenticatedClient } from '../client.js'; -import { logger } from '../utils/logger.js'; - -export interface ChatCompletionOptions { - apiKey?: string; - max_tokens?: number; - messages: ChatMessage[]; - model?: string; - onChunk?: (chunk: any) => void; - stream?: boolean; - temperature?: number; - top_p?: number; -} - -export interface ChatMessage { - content: string; - role: 'assistant' | 'system' | 'user'; -} - -interface StreamState { - buffer: string; - fullContent: string; - fullResponse: any; -} - -/** - * Service for interacting with the chat API - * Command group: chat - */ -export class ChatService { - // Command group name for this service - public static readonly COMMAND_GROUP = 'chat'; - // Subcommands for this service - public static readonly COMMANDS = { - LIST: 'list', - RUN: 'run', - }; - - private static instance: ChatService; - - private client = createAuthenticatedClient(); - - private constructor() {} - - public static getInstance(): ChatService { - if (!ChatService.instance) { - ChatService.instance = new ChatService(); - } - return ChatService.instance; - } - - /** - * Create a chat completion - * Command: berget chat completion - */ - public async createCompletion(options: ChatCompletionOptions): Promise { - try { - logger.debug('Starting createCompletion method'); - - const optionsCopy = options ? { ...options } : { messages: [] }; - - if (!optionsCopy.messages || !Array.isArray(optionsCopy.messages)) { - logger.error('messages is undefined or not an array'); - optionsCopy.messages = []; - } - - this.logCompletionOptions(optionsCopy); - - const headers: Record = {}; - - if (optionsCopy.apiKey) { - headers['Authorization'] = optionsCopy.apiKey; - } - - if (!optionsCopy.model) { - logger.debug('No model specified, using default: google/gemma-3-27b-it'); - optionsCopy.model = 'google/gemma-3-27b-it'; - } - - this.logCompletionOptions(optionsCopy); - - return this.executeCompletion(optionsCopy, headers); - } catch (error) { - throw this.formatCompletionError(error); - } - } - - /** - * List available models - * Command: berget chat list - */ - public async listModels(apiKey?: string): Promise { - try { - let data: any; - let error: any; - - if (apiKey) { - const result = await this.client.GET('/v1/models', { headers: { Authorization: apiKey } }); - data = result.data; - error = result.error; - } else { - const result = await this.client.GET('/v1/models'); - data = result.data; - error = result.error; - } - - if (error) throw new Error(JSON.stringify(error)); - return data; - } catch (error) { - throw this.formatListModelsError(error); - } - } - - private accumulateContent(parsedData: any, state: StreamState): void { - if ( - parsedData.choices && - parsedData.choices[0] && - parsedData.choices[0].delta && - parsedData.choices[0].delta.content - ) { - state.fullContent += parsedData.choices[0].delta.content; - } - } - - private buildStreamResult(state: StreamState): any { - if (state.fullResponse) { - if (state.fullContent) { - state.fullResponse.choices[0].message = { - content: state.fullContent, - role: 'assistant', - }; - } - return state.fullResponse; - } - - return { - choices: [{ message: { content: state.fullContent, role: 'assistant' } }], - }; - } - - /** - * Execute the completion request with the provided options - * @param options The completion options - * @param headers Additional headers to include - * @returns The completion response - */ - private async executeCompletion( - options: ChatCompletionOptions, - headers: Record = {}, - ): Promise { - try { - // If an API key is provided, use it for this request - if (options.apiKey) { - // API keys should be sent directly, not with Bearer prefix - headers['Authorization'] = options.apiKey; - } - - // Remove apiKey and onChunk from options before sending to API - const { apiKey: _, onChunk, ...requestOptions } = options; - - logger.debug('Request options:'); - logger.debug( - JSON.stringify( - { - ...requestOptions, - messages: requestOptions.messages - ? `${requestOptions.messages.length} messages` - : '0 messages', - }, - null, - 2, - ), - ); - - // Handle streaming responses differently - if (requestOptions.stream && onChunk) { - return await this.handleStreamingResponse({ ...requestOptions, onChunk }, headers); - } else { - // Ensure model is always defined for the API call - const requestBody = { - ...requestOptions, - model: requestOptions.model || 'google/gemma-3-27b-it', - }; - - // Debug the headers being sent - logger.debug('Headers being sent:'); - logger.debug(JSON.stringify(headers, null, 2)); - - const response = await this.client.POST('/v1/chat/completions', { - body: requestBody, - headers, - }); - - // Check if response has an error property - const responseAny = response as any; - if (responseAny && responseAny.error) throw new Error(JSON.stringify(responseAny.error)); - - logger.debug('API response:'); - logger.debug(JSON.stringify(response, null, 2)); - - // Output the complete response data for debugging - logger.debug('Complete response data:'); - logger.debug(JSON.stringify(response.data, null, 2)); - - return response.data; - } - } catch (requestError) { - logger.debug( - `Request error: ${ - requestError instanceof Error ? requestError.message : String(requestError) - }`, - ); - throw requestError; - } - } - - private formatCompletionError(error: unknown): Error { - let errorMessage = 'Failed to create chat completion'; - - if (error instanceof Error) { - try { - const parsedError = JSON.parse(error.message); - if (parsedError.error && parsedError.error.message) { - errorMessage = `Chat error: ${parsedError.error.message}`; - } - } catch { - errorMessage = `Chat error: ${error.message}`; - } - } - - logger.error(errorMessage); - return new Error(errorMessage); - } - - private formatListModelsError(error: unknown): Error { - let errorMessage = 'Failed to list models'; - - if (error instanceof Error) { - try { - const parsedError = JSON.parse(error.message); - if (parsedError.error) { - errorMessage = `Models error: ${ - typeof parsedError.error === 'string' - ? parsedError.error - : parsedError.error.message || JSON.stringify(parsedError.error) - }`; - } - } catch { - errorMessage = `Models error: ${error.message}`; - } - } - - logger.error(errorMessage); - return new Error(errorMessage); - } - - /** - * Handle streaming response from the API - * @param options Request options - * @param headers Request headers - * @returns A promise that resolves when the stream is complete - */ - private async handleStreamingResponse( - options: any, - headers: Record, - ): Promise { - const baseUrl = process.env.API_BASE_URL || 'https://api.berget.ai'; - const url = new URL(`${baseUrl}/v1/chat/completions`); - - try { - this.logStreamingRequest(url, headers, options); - const response = await this.makeStreamingRequest(url, options, headers); - const state: StreamState = { buffer: '', fullContent: '', fullResponse: null }; - await this.readStream(response.body!.getReader(), options, state); - return this.buildStreamResult(state); - } catch (error) { - logger.error(`Streaming error: ${error instanceof Error ? error.message : String(error)}`); - throw error; - } - } - - private hasBalancedBraces(jsonData: string): boolean { - let braceCount = 0; - let inString = false; - let escaped = false; - - for (const char of jsonData) { - if (escaped) { - escaped = false; - continue; - } - if (char === '\\') { - escaped = true; - continue; - } - if (char === '"') { - inString = !inString; - continue; - } - if (!inString && char === '{') { - braceCount++; - } else if (!inString && char === '}') { - braceCount--; - } - } - - return braceCount === 0; - } - - private logCompletionOptions(optionsCopy: ChatCompletionOptions): void { - try { - logger.debug( - JSON.stringify( - { - ...optionsCopy, - apiKey: optionsCopy.apiKey ? '***' : undefined, - messages: optionsCopy.messages - ? `${optionsCopy.messages.length} messages` - : '0 messages', - }, - null, - 2, - ), - ); - } catch (error) { - logger.error('Failed to stringify options:', error); - } - } - - private logParseError(error: unknown, jsonData: string): void { - logger.error(`Error parsing chunk: ${error}`); - const errorMsg = (error as any).message || ''; - const errorPos = Number.parseInt(errorMsg.match(/position (\d+)/)?.[1] || '0'); - if (errorPos > 0) { - const start = Math.max(0, errorPos - 20); - const end = Math.min(jsonData.length, errorPos + 20); - logger.error(`Context around error position ${errorPos}:`); - logger.error(`"${jsonData.substring(start, end)}"`); - logger.error( - `Character codes: ${[...jsonData.substring(start, end)].map((c) => c.charCodeAt(0)).join(' ')}`, - ); - } - } - - private logStreamingRequest(url: URL, headers: Record, options: any): void { - logger.debug(`Making streaming request to: ${url.toString()}`); - logger.debug(`Headers:`, JSON.stringify(headers, null, 2)); - logger.debug(`Body:`, JSON.stringify(options, null, 2)); - } - - private async makeStreamingRequest( - url: URL, - options: any, - headers: Record, - ): Promise { - const response = await fetch(url.toString(), { - body: JSON.stringify(options), - headers: { - Accept: 'text/event-stream', - 'Content-Type': 'application/json', - ...headers, - }, - method: 'POST', - }); - - logger.debug(`Response status: ${response.status}`); - logger.debug( - `Response headers:`, - JSON.stringify(Object.fromEntries(response.headers.entries()), null, 2), - ); - - if (!response.ok) { - const errorText = await response.text(); - logger.error(`Stream request failed: ${response.status} ${response.statusText}`); - logger.error(`Error response: ${errorText}`); - throw new Error( - `Stream request failed: ${response.status} ${response.statusText} - ${errorText}`, - ); - } - - if (!response.body) { - throw new Error('No response body received'); - } - - return response; - } - - private processLines(lines: string[], options: any, state: StreamState): number { - let processedLines = 0; - - for (const [index, line] of lines.entries()) { - logger.debug(`Line ${index}: "${line}"`); - - if (!line.startsWith('data:')) { - continue; - } - - const jsonData = line.slice(5).trim(); - logger.debug(`Extracted JSON data: "${jsonData}"`); - - if (jsonData === '' || jsonData === '[DONE]') { - logger.debug(`Skipping empty data or [DONE] marker`); - processedLines = index + 1; - continue; - } - - if (!jsonData.startsWith('{')) { - logger.warn( - `JSON data doesn't start with '{', might be partial: "${jsonData.slice(0, 50)}..."`, - ); - break; - } - - if (!this.hasBalancedBraces(jsonData)) { - logger.warn( - `JSON braces don't balance, treating as partial: "${jsonData.slice(0, 50)}..."`, - ); - break; - } - - if (this.tryParseAndProcess(jsonData, options, state)) { - processedLines = index + 1; - } else { - break; - } - } - - return processedLines; - } - - private async readStream( - reader: ReadableStreamDefaultReader, - options: any, - state: StreamState, - ): Promise { - const decoder = new TextDecoder(); - - while (true) { - const { done, value } = await reader.read(); - if (done) break; - - const chunk = decoder.decode(value, { stream: true }); - logger.debug(`Received chunk: ${chunk.length} bytes`); - - state.buffer += chunk; - logger.debug(`Added chunk to buffer. Buffer length: ${state.buffer.length}`); - - const lines = state.buffer.split('\n'); - logger.debug(`Processing ${lines.length} lines from buffer`); - - const processedLines = this.processLines(lines, options, state); - - if (processedLines > 0) { - const remainingLines = lines.slice(processedLines); - state.buffer = remainingLines.join('\n'); - logger.debug( - `Updated buffer. Remaining lines: ${remainingLines.length}, Buffer length: ${state.buffer.length}`, - ); - } - } - } - - private tryParseAndProcess(jsonData: string, options: any, state: StreamState): boolean { - try { - logger.debug(`Attempting to parse JSON of length: ${jsonData.length}`); - const parsedData = JSON.parse(jsonData); - logger.debug(`Successfully parsed JSON: ${JSON.stringify(parsedData, null, 2)}`); - - if (options.onChunk) { - options.onChunk(parsedData); - } - - if (state.fullResponse) { - this.accumulateContent(parsedData, state); - } else { - state.fullResponse = parsedData; - } - - return true; - } catch (error) { - this.logParseError(error, jsonData); - return false; - } - } -} diff --git a/src/utils/markdown-renderer.ts b/src/utils/markdown-renderer.ts deleted file mode 100644 index f44cf8a..0000000 --- a/src/utils/markdown-renderer.ts +++ /dev/null @@ -1,71 +0,0 @@ -import chalk from 'chalk'; -import { marked } from 'marked'; -import { markedTerminal } from 'marked-terminal'; - -// Configure marked to use the terminal renderer -// @types/marked-terminal is outdated; cast to suppress type error -marked.use( - markedTerminal({ - blockquote: chalk.gray.italic, - // Customize the rendering options - code: chalk.cyan, - // Customize code block rendering - codespan: chalk.cyan, - em: chalk.italic, - heading: chalk.bold.blueBright, - hr: chalk.gray, - link: chalk.blue.underline, - listitem: chalk.yellow, - strong: chalk.bold, - table: chalk.white, - // Adjust the width to fit the terminal - width: process.stdout.columns || 80, - }) as any, -); - -/** - * Check if a string contains markdown formatting - * @param text The text to check - * @returns True if the text contains markdown formatting - */ -export function containsMarkdown(text: string): boolean { - if (!text) return false; - - // Check for common markdown patterns - const markdownPatterns = [ - /^#+\s+/m, // Headers - /\*\*.*?\*\*/, // Bold - /\*.*?\*/, // Italic - /`.*?`/, // Inline code - /```[\s\S]*?```/, // Code blocks - /\[.*?\]\(.*?\)/, // Links - /^\s*[-*+]\s+/m, // Lists - /^\s*\d+\.\s+/m, // Numbered lists - /^\s*>\s+/m, // Blockquotes - /\|.*\|.*\|/, // Tables - /^---+$/m, // Horizontal rules - /^===+$/m, // Alternative headers - ]; - - return markdownPatterns.some((pattern) => pattern.test(text)); -} - -/** - * Render markdown text to terminal-friendly formatted text - * @param markdown The markdown text to render - * @returns Formatted text for terminal display - */ -export function renderMarkdown(markdown: string): string { - if (!markdown) return ''; - - try { - // Convert markdown to terminal-friendly text - // marked.parse() can return Promise when async extensions are used, - // but markedTerminal is synchronous so we cast - return marked.parse(markdown) as string; - } catch (error) { - // If rendering fails, return the original text - console.error(`Error rendering markdown: ${error}`); - return markdown; - } -} diff --git a/tests/commands/chat.test.ts b/tests/commands/chat.test.ts deleted file mode 100644 index 8ad3d4e..0000000 --- a/tests/commands/chat.test.ts +++ /dev/null @@ -1,118 +0,0 @@ -import { Command } from 'commander'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; - -import { registerChatCommands } from '../../src/commands/chat.js'; -import { ChatService } from '../../src/services/chat-service.js'; -import { DefaultApiKeyManager } from '../../src/utils/default-api-key.js'; - -// Mock dependencies -vi.mock('../../src/services/chat-service.js'); -vi.mock('../../src/utils/default-api-key.js'); -vi.mock('readline', () => ({ - createInterface: vi.fn(() => ({ - close: vi.fn(), - question: vi.fn(), - })), -})); - -describe('Chat Commands', () => { - let program: Command; - let mockChatService: any; - let mockDefaultApiKeyManager: any; - - beforeEach(() => { - program = new Command(); - - // Mock ChatService - mockChatService = { - createCompletion: vi.fn(), - listModels: vi.fn(), - }; - vi.mocked(ChatService.getInstance).mockReturnValue(mockChatService); - - // Mock DefaultApiKeyManager - mockDefaultApiKeyManager = { - getDefaultApiKeyData: vi.fn(), - promptForDefaultApiKey: vi.fn(), - }; - vi.mocked(DefaultApiKeyManager.getInstance).mockReturnValue(mockDefaultApiKeyManager); - - registerChatCommands(program); - }); - - afterEach(() => { - vi.clearAllMocks(); - delete process.env.BERGET_API_KEY; - }); - - describe('chat run command', () => { - it('should use berget/kimi-k2.6 as default model', () => { - const chatCommand = program.commands.find((cmd) => cmd.name() === 'chat'); - const runCommand = chatCommand?.commands.find((cmd) => cmd.name() === 'run'); - - expect(runCommand).toBeDefined(); - - // Check the help text which contains the default model - const helpText = runCommand?.helpInformation(); - expect(helpText).toContain('kimi-k2.6'); - }); - - it('should have streaming enabled by default', () => { - const chatCommand = program.commands.find((cmd) => cmd.name() === 'chat'); - const runCommand = chatCommand?.commands.find((cmd) => cmd.name() === 'run'); - - expect(runCommand).toBeDefined(); - - // Check that the option is --no-stream (meaning streaming is default) - const streamOption = runCommand?.options.find((opt) => opt.long === '--no-stream'); - expect(streamOption).toBeDefined(); - expect(streamOption?.description).toContain('Disable streaming'); - }); - - it('should create completion with correct default options', async () => { - // Mock API key - process.env.BERGET_API_KEY = 'test-key'; - - // Mock successful completion - mockChatService.createCompletion.mockResolvedValue({ - choices: [ - { - message: { content: 'Test response' }, - }, - ], - }); - - // This would normally test the actual command execution - // but since it involves readline interaction, we just verify - // that the service would be called with correct defaults - expect(mockChatService.createCompletion).not.toHaveBeenCalled(); - }); - }); - - describe('chat list command', () => { - it('should list available models', async () => { - const mockModels = { - data: [ - { - active: true, - capabilities: { - function_calling: true, - json_mode: true, - vision: false, - }, - id: 'gpt-oss', - owned_by: 'openai', - }, - ], - }; - - mockChatService.listModels.mockResolvedValue(mockModels); - - const chatCommand = program.commands.find((cmd) => cmd.name() === 'chat'); - const listCommand = chatCommand?.commands.find((cmd) => cmd.name() === 'list'); - - expect(listCommand).toBeDefined(); - expect(listCommand?.description()).toBe('List available chat models'); - }); - }); -}); diff --git a/tests/services/chat-service.test.ts b/tests/services/chat-service.test.ts deleted file mode 100644 index f3cc9f1..0000000 --- a/tests/services/chat-service.test.ts +++ /dev/null @@ -1,306 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest'; - -import { ChatService } from '../../src/services/chat-service.js'; - -const mockPost = vi.fn(); -const mockGet = vi.fn(); - -let fetchMock: any; - -vi.mock('../../src/client.js', () => ({ - createAuthenticatedClient: vi.fn(() => ({ - GET: mockGet, - POST: mockPost, - })), -})); - -vi.mock('../../src/utils/logger.js', () => ({ - logger: { - debug: vi.fn(), - error: vi.fn(), - warn: vi.fn(), - }, -})); - -describe('ChatService', () => { - let service: ChatService; - - beforeEach(() => { - (ChatService as any).instance = undefined; - service = ChatService.getInstance(); - mockPost.mockReset(); - mockGet.mockReset(); - fetchMock = vi.fn(); - globalThis.fetch = fetchMock; - }); - - describe('createCompletion', () => { - it('returns data for non-streaming request', async () => { - const mockResponse = { - choices: [{ message: { content: 'Hello', role: 'assistant' } }], - }; - mockPost.mockResolvedValue({ data: mockResponse, error: null }); - - const result = await service.createCompletion({ - messages: [{ content: 'Hi', role: 'user' }], - stream: false, - }); - - expect(result).toEqual(mockResponse); - }); - - it('sets default model when not provided', async () => { - mockPost.mockResolvedValue({ - data: { choices: [{ message: { content: 'Hi', role: 'assistant' } }] }, - error: null, - }); - - await service.createCompletion({ messages: [{ content: 'Hi', role: 'user' }] }); - - expect(mockPost).toHaveBeenCalledWith( - '/v1/chat/completions', - expect.objectContaining({ - body: expect.objectContaining({ model: 'google/gemma-3-27b-it' }), - }), - ); - }); - - it('uses provided model', async () => { - mockPost.mockResolvedValue({ - data: { choices: [{ message: { content: 'Hi', role: 'assistant' } }] }, - error: null, - }); - - await service.createCompletion({ - messages: [{ content: 'Hi', role: 'user' }], - model: 'custom-model', - }); - - expect(mockPost).toHaveBeenCalledWith( - '/v1/chat/completions', - expect.objectContaining({ - body: expect.objectContaining({ model: 'custom-model' }), - }), - ); - }); - - it('adds apiKey to headers', async () => { - mockPost.mockResolvedValue({ - data: { choices: [{ message: { content: 'Hi', role: 'assistant' } }] }, - error: null, - }); - - await service.createCompletion({ - apiKey: 'test-key', - messages: [{ content: 'Hi', role: 'user' }], - }); - - expect(mockPost).toHaveBeenCalledWith( - '/v1/chat/completions', - expect.objectContaining({ - headers: { Authorization: 'test-key' }, - }), - ); - }); - - it('throws on API error response', async () => { - mockPost.mockResolvedValue({ data: null, error: { message: 'Bad request' } }); - - await expect( - service.createCompletion({ messages: [{ content: 'Hi', role: 'user' }] }), - ).rejects.toThrow('Bad request'); - }); - - it('initializes empty messages array when missing', async () => { - mockPost.mockResolvedValue({ - data: { choices: [{ message: { content: 'Hi', role: 'assistant' } }] }, - error: null, - }); - - await service.createCompletion({ messages: [] as any }); - - expect(mockPost).toHaveBeenCalled(); - }); - - it('propagates unexpected errors from executeCompletion', async () => { - mockPost.mockRejectedValue(new Error('Unexpected failure')); - - await expect( - service.createCompletion({ messages: [{ content: 'Hi', role: 'user' }] }), - ).rejects.toThrow('Unexpected failure'); - }); - }); - - describe('listModels', () => { - it('returns models without apiKey', async () => { - const mockData = { data: [{ id: 'model-1' }] }; - mockGet.mockResolvedValue({ data: mockData, error: null }); - - const result = await service.listModels(); - - expect(result).toEqual(mockData); - expect(mockGet).toHaveBeenCalledWith('/v1/models'); - }); - - it('returns models with apiKey', async () => { - const mockData = { data: [{ id: 'model-1' }] }; - mockGet.mockResolvedValue({ data: mockData, error: null }); - - const result = await service.listModels('test-key'); - - expect(result).toEqual(mockData); - expect(mockGet).toHaveBeenCalledWith('/v1/models', { - headers: { Authorization: 'test-key' }, - }); - }); - - it('throws on API error', async () => { - mockGet.mockResolvedValue({ data: null, error: 'service unavailable' }); - - await expect(service.listModels()).rejects.toThrow('Failed to list models'); - }); - }); - - describe('handleStreamingResponse', () => { - function createMockStream(chunks: string[]) { - let index = 0; - return { - getReader: () => ({ - read: () => { - if (index >= chunks.length) { - return Promise.resolve({ done: true, value: undefined }); - } - const chunk = new TextEncoder().encode(chunks[index++]); - return Promise.resolve({ done: false, value: chunk }); - }, - }), - }; - } - - it('streams chunks and returns full response', async () => { - const chunks: string[] = [ - 'data: {"id":"1","choices":[{"delta":{"content":"Hello"}}]}\n\n', - 'data: {"id":"1","choices":[{"delta":{"content":" world"}}]}\n\n', - 'data: [DONE]\n\n', - ]; - - fetchMock.mockResolvedValue({ - body: createMockStream(chunks), - headers: new Headers(), - ok: true, - status: 200, - statusText: 'OK', - }); - - const receivedChunks: any[] = []; - - const result = await service.createCompletion({ - messages: [{ content: 'Hi', role: 'user' }], - onChunk: (chunk: any) => receivedChunks.push(chunk), - stream: true, - }); - - expect(receivedChunks).toHaveLength(2); - expect(result.choices[0].message.content).toBe(' world'); - }); - - it('handles first chunk as full response with no content', async () => { - const chunks: string[] = ['data: {"id":"1","choices":[{"delta":{"content":"Test"}}]}\n\n']; - - fetchMock.mockResolvedValue({ - body: createMockStream(chunks), - headers: new Headers(), - ok: true, - status: 200, - statusText: 'OK', - }); - - const result = await service.createCompletion({ - messages: [{ content: 'Hi', role: 'user' }], - onChunk: vi.fn(), - stream: true, - }); - - // First chunk sets fullResponse, but no content accumulated - expect(result.id).toBe('1'); - }); - - it('handles empty stream', async () => { - fetchMock.mockResolvedValue({ - body: createMockStream([]), - headers: new Headers(), - ok: true, - status: 200, - statusText: 'OK', - }); - - const result = await service.createCompletion({ - messages: [{ content: 'Hi', role: 'user' }], - onChunk: vi.fn(), - stream: true, - }); - - expect(result.choices[0].message.content).toBe(''); - }); - - it('throws on non-ok response', async () => { - fetchMock.mockResolvedValue({ - headers: new Headers(), - ok: false, - status: 401, - statusText: 'Unauthorized', - text: () => Promise.resolve('Invalid API key'), - }); - - await expect( - service.createCompletion({ - messages: [{ content: 'Hi', role: 'user' }], - onChunk: vi.fn(), - stream: true, - }), - ).rejects.toThrow('Stream request failed: 401 Unauthorized'); - }); - - it('throws when response body is missing', async () => { - fetchMock.mockResolvedValue({ - body: null, - headers: new Headers(), - ok: true, - status: 200, - statusText: 'OK', - }); - - await expect( - service.createCompletion({ - messages: [{ content: 'Hi', role: 'user' }], - onChunk: vi.fn(), - stream: true, - }), - ).rejects.toThrow('No response body received'); - }); - - it('handles partial JSON across chunks', async () => { - const fullJson = '{"id":"1","choices":[{"delta":{"content":"Hello"}}]}'; - const chunks: string[] = [ - `data: ${fullJson.slice(0, 20)}\n\n`, - `data: ${fullJson.slice(20)}\n\n`, - ]; - - fetchMock.mockResolvedValue({ - body: createMockStream(chunks), - headers: new Headers(), - ok: true, - status: 200, - statusText: 'OK', - }); - - const result = await service.createCompletion({ - messages: [{ content: 'Hi', role: 'user' }], - onChunk: vi.fn(), - stream: true, - }); - - expect(result).toBeDefined(); - }); - }); -}); diff --git a/vitest.config.ts b/vitest.config.ts index 724a15d..5db0715 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -2,6 +2,19 @@ import { defineConfig } from 'vitest/config'; export default defineConfig({ test: { + coverage: { + exclude: ['src/types/**', 'src/schemas/**', 'src/**/__tests__/**'], + include: ['src/**'], + provider: 'v8', + reporter: ['text', 'text-summary', 'lcov'], + reportsDirectory: './coverage', + thresholds: { + branches: 52, + functions: 48, + lines: 50, + statements: 50, + }, + }, environment: 'node', exclude: ['node_modules', 'dist'], globals: true,