@visulima/cerebro 1.0.49 → 1.0.51

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,16 @@
1
+ ## @visulima/cerebro [1.0.51](https://github.com/visulima/visulima/compare/@visulima/cerebro@1.0.50...@visulima/cerebro@1.0.51) (2024-06-20)
2
+
3
+ ### Bug Fixes
4
+
5
+ * **cerebro:** fixed handling of option conflicts ([#425](https://github.com/visulima/visulima/issues/425)) ([97856a3](https://github.com/visulima/visulima/commit/97856a32030ffd5382f9c84a9f479db2dc7034f6))
6
+
7
+ ## @visulima/cerebro [1.0.50](https://github.com/visulima/visulima/compare/@visulima/cerebro@1.0.49...@visulima/cerebro@1.0.50) (2024-06-20)
8
+
9
+
10
+ ### Dependencies
11
+
12
+ * **@visulima/package:** upgraded to 3.0.0
13
+
1
14
  ## @visulima/cerebro [1.0.49](https://github.com/visulima/visulima/compare/@visulima/cerebro@1.0.48...@visulima/cerebro@1.0.49) (2024-06-19)
2
15
 
3
16
 
package/LICENSE.md CHANGED
@@ -19,3 +19,106 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
19
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
20
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
21
  SOFTWARE.
22
+
23
+ <!-- DEPENDENCIES -->
24
+
25
+ # Licenses of bundled dependencies
26
+ The published @visulima/cerebro artifact additionally contains code with the following licenses:
27
+ MIT
28
+
29
+ # Bundled dependencies:
30
+ ## @visulima/path
31
+ License: MIT
32
+ By: Daniel Bannert
33
+ Repository: git+https://github.com/visulima/visulima.git
34
+
35
+ > MIT License
36
+ >
37
+ > Copyright (c) 2024 visulima
38
+ >
39
+ > Permission is hereby granted, free of charge, to any person obtaining a copy
40
+ > of this software and associated documentation files (the "Software"), to deal
41
+ > in the Software without restriction, including without limitation the rights
42
+ > to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
43
+ > copies of the Software, and to permit persons to whom the Software is
44
+ > furnished to do so, subject to the following conditions:
45
+ >
46
+ > The above copyright notice and this permission notice shall be included in all
47
+ > copies or substantial portions of the Software.
48
+ >
49
+ > THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
50
+ > IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
51
+ > FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
52
+ > AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
53
+ > LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
54
+ > OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
55
+ > SOFTWARE.
56
+ >
57
+ > ---
58
+ >
59
+ > MIT License
60
+ >
61
+ > Copyright (c) Pooya Parsa <pooya@pi0.io> - Daniel Roe <daniel@roe.dev>
62
+ >
63
+ > Permission is hereby granted, free of charge, to any person obtaining a copy
64
+ > of this software and associated documentation files (the "Software"), to deal
65
+ > in the Software without restriction, including without limitation the rights
66
+ > to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
67
+ > copies of the Software, and to permit persons to whom the Software is
68
+ > furnished to do so, subject to the following conditions:
69
+ >
70
+ > The above copyright notice and this permission notice shall be included in all
71
+ > copies or substantial portions of the Software.
72
+ >
73
+ > THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
74
+ > IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
75
+ > FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
76
+ > AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
77
+ > LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
78
+ > OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
79
+ > SOFTWARE.
80
+ >
81
+ > ---
82
+ >
83
+ > Copyright Joyent, Inc. and other Node contributors.
84
+ >
85
+ > Permission is hereby granted, free of charge, to any person obtaining a
86
+ > copy of this software and associated documentation files (the
87
+ > "Software"), to deal in the Software without restriction, including
88
+ > without limitation the rights to use, copy, modify, merge, publish,
89
+ > distribute, sublicense, and/or sell copies of the Software, and to permit
90
+ > persons to whom the Software is furnished to do so, subject to the
91
+ > following conditions:
92
+ >
93
+ > The above copyright notice and this permission notice shall be included
94
+ > in all copies or substantial portions of the Software.
95
+ >
96
+ > THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
97
+ > OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
98
+ > MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
99
+ > NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
100
+ > DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
101
+ > OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
102
+ > USE OR OTHER DEALINGS IN THE SOFTWARE.
103
+
104
+ ---------------------------------------
105
+
106
+ ## camelcase
107
+ License: MIT
108
+ By: Sindre Sorhus
109
+ Repository: sindresorhus/camelcase
110
+
111
+ > MIT License
112
+ >
113
+ > Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
114
+ >
115
+ > Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
116
+ >
117
+ > The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
118
+ >
119
+ > THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
120
+
121
+ <!-- DEPENDENCIES -->
122
+
123
+ <!-- TYPE_DEPENDENCIES -->
124
+ <!-- TYPE_DEPENDENCIES -->
@@ -0,0 +1 @@
1
+ "use strict";var k=Object.defineProperty;var i=(e,t)=>k(e,"name",{value:t,configurable:!0});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("node:fs"),A=require("@visulima/find-cache-dir"),N=require("node:https");var O=Object.defineProperty,_=i((e,t)=>O(e,"name",{value:t,configurable:!0}),"o$1");const x=_((e,t)=>{const r=e.split(".").map(Number),n=t.split(".").map(Number);for(const[o,s]of r.entries()){if(s>n[o])return!0;if(s<n[o])return!1}return!1},"semverGt");var C=Object.defineProperty,U=i((e,t)=>{for(var r in t)C(e,r,{get:t[r],enumerable:!0})},"A"),P=/^[A-Z]:\//i,E=i((e="")=>e&&e.replaceAll("\\","/").replace(P,t=>t.toUpperCase()),"T"),c=E,D={};U(D,{basename:i(()=>j,"basename"),delimiter:i(()=>z,"delimiter"),dirname:i(()=>h,"dirname"),extname:i(()=>w,"extname"),format:i(()=>M,"format"),isAbsolute:i(()=>f,"isAbsolute"),join:i(()=>b,"join"),normalize:i(()=>y,"normalize"),normalizeString:i(()=>g,"normalizeString"),parse:i(()=>W,"parse"),relative:i(()=>J,"relative"),resolve:i(()=>d,"resolve"),sep:i(()=>q,"sep"),toNamespacedPath:i(()=>F,"toNamespacedPath")});var L=/^[/\\]{2}/,I=/^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Z]:[/\\]/i,$=/^[A-Z]:$/i,m=/^\/([A-Z]:)?$/i,T=/.(\.[^./]+)$/,Z=i(()=>typeof process<"u"&&typeof process.cwd=="function"?process.cwd().replaceAll("\\","/"):"/","_"),q="/",z=":",g=i((e,t)=>{let r="",n=0,o=-1,s=0,l=null;for(let a=0;a<=e.length;++a){if(a<e.length)l=e[a];else{if(l==="/")break;l="/"}if(l==="/"){if(!(o===a-1||s===1))if(s===2){if(r.length<2||n!==2||!r.endsWith(".")||r.at(-2)!=="."){if(r.length>2){let u=r.lastIndexOf("/");u===-1?(r="",n=0):(r=r.slice(0,u),n=r.length-1-r.lastIndexOf("/")),o=a,s=0;continue}else if(r.length>0){r="",n=0,o=a,s=0;continue}}t&&(r+=r.length>0?"/..":"..",n=2)}else r.length>0?r+=`/${e.slice(o+1,a)}`:r=e.slice(o+1,a),n=a-o-1;o=a,s=0}else l==="."&&s!==-1?++s:s=-1}return r},"g$2"),f=i(e=>I.test(e),"f"),y=i(function(e){if(e.length===0)return".";e=c(e);let t=L.exec(e),r=f(e),n=e.at(-1)==="/";return e=g(e,!r),e.length===0?r?"/":n?"./":".":(n&&(e+="/"),$.test(e)&&(e+="/"),t?r?`//${e}`:`//./${e}`:r&&!f(e)?`/${e}`:e)},"m$1"),b=i(function(...e){if(e.length===0)return".";let t;for(let r of e)r&&r.length>0&&(t===void 0?t=r:t+=`/${r}`);return t===void 0?".":y(t.replaceAll(/\/{2,}/g,"/"))},"z"),d=i(function(...e){e=e.map(n=>c(n));let t="",r=!1;for(let n=e.length-1;n>=-1&&!r;n--){let o=n>=0?e[n]:Z();!o||o.length===0||(t=`${o}/${t}`,r=f(o))}return t=g(t,!r),r&&!f(t)?`/${t}`:t.length>0?t:"."},"a"),F=i(function(e){return c(e)},"L"),w=i(function(e){return T.exec(c(e))?.[1]??""},"h"),J=i(function(e,t){let r=d(e).replace(m,"$1").split("/"),n=d(t).replace(m,"$1").split("/");if(n[0][1]===":"&&r[0][1]===":"&&r[0]!==n[0])return n.join("/");let o=[...r];for(let s of o){if(n[0]!==s)break;r.shift(),n.shift()}return[...r.map(()=>".."),...n].join("/")},"N"),h=i(e=>{let t=c(e).replace(/\/$/,"").split("/").slice(0,-1);return t.length===1&&$.test(t[0])&&(t[0]+="/"),t.join("/")||(f(e)?"/":".")},"x"),M=i(function(e){let t=[e.root,e.dir,e.base??e.name+e.ext].filter(Boolean);return c(e.root?d(...t):t.join("/"))},"C"),j=i((e,t)=>{let r=c(e).split("/").pop();return t&&r.endsWith(t)?r.slice(0,-t.length):r},"E"),W=i(function(e){let t=c(e).split("/").shift();t===""?t="/":t+="/";let r=j(e),n=w(r);return{base:r,dir:h(e),ext:n,name:r.slice(0,r.length-n.length),root:t}},"U"),V=Object.defineProperty,v=i((e,t)=>V(e,"name",{value:t,configurable:!0}),"r");const B="last-update-check.json",S=v(e=>{const t=A.findCacheDirSync(e);if(t===void 0)throw new Error("Could not find cache directory");return b(t,B)},"getConfigFile"),G=v(e=>{const t=S(e);try{if(!p.existsSync(t))return;const{lastUpdateCheck:r}=JSON.parse(p.readFileSync(t,"utf8"));return r}catch{return}},"getLastUpdate"),R=v(e=>{const t=S(e),r=h(t);p.existsSync(r)||p.mkdirSync(r,{recursive:!0}),p.writeFileSync(t,JSON.stringify({lastUpdateCheck:Date.now()}))},"saveLastUpdate");var H=Object.defineProperty,K=i((e,t)=>H(e,"name",{value:t,configurable:!0}),"g");const Q=K(async(e,t,r)=>{const n=r.replace("__NAME__",e);return await new Promise((o,s)=>{N.get(n,l=>{let a="";l.on("data",u=>a+=u),l.on("end",()=>{try{const u=JSON.parse(a)[t];u||s(new Error("Error getting version")),o(u)}catch{s(new Error("Could not parse version response"))}})}).on("error",l=>s(l))})},"getDistributionVersion");var X=Object.defineProperty,Y=i((e,t)=>X(e,"name",{value:t,configurable:!0}),"i");const ee=Y(async({alwaysRun:e,debug:t,distTag:r="latest",pkg:n,registryUrl:o="https://registry.npmjs.org/-/package/__NAME__/dist-tags",updateCheckInterval:s=1e3*60*60*24})=>{const l=G(n.name);if(e||!l||l<Date.now()-s){const a=await Q(n.name,r,o);if(R(n.name),x(a,n.version))return a;t&&console.error(`Latest version (${a}) not newer than current version (${n.version})`)}else t&&console.error(`Too recent to check for a new update. simpleUpdateNotifier() interval set to ${s}ms but only ${Date.now()-l}ms since last check.`);return null},"hasNewVersion");exports.default=ee;
@@ -0,0 +1 @@
1
+ var A=Object.defineProperty;var o=(e,t)=>A(e,"name",{value:t,configurable:!0});import{existsSync as v,readFileSync as N,mkdirSync as x,writeFileSync as O}from"node:fs";import{findCacheDirSync as S}from"@visulima/find-cache-dir";import{get as U}from"node:https";var C=Object.defineProperty,_=o((e,t)=>C(e,"name",{value:t,configurable:!0}),"o$1");const P=_((e,t)=>{const r=e.split(".").map(Number),n=t.split(".").map(Number);for(const[i,a]of r.entries()){if(a>n[i])return!0;if(a<n[i])return!1}return!1},"semverGt");var E=Object.defineProperty,L=o((e,t)=>{for(var r in t)E(e,r,{get:t[r],enumerable:!0})},"A"),D=/^[A-Z]:\//i,I=o((e="")=>e&&e.replaceAll("\\","/").replace(D,t=>t.toUpperCase()),"T"),c=I,Z={};L(Z,{basename:o(()=>j,"basename"),delimiter:o(()=>M,"delimiter"),dirname:o(()=>d,"dirname"),extname:o(()=>w,"extname"),format:o(()=>G,"format"),isAbsolute:o(()=>u,"isAbsolute"),join:o(()=>b,"join"),normalize:o(()=>y,"normalize"),normalizeString:o(()=>g,"normalizeString"),parse:o(()=>R,"parse"),relative:o(()=>B,"relative"),resolve:o(()=>p,"resolve"),sep:o(()=>W,"sep"),toNamespacedPath:o(()=>V,"toNamespacedPath")});var z=/^[/\\]{2}/,F=/^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Z]:[/\\]/i,$=/^[A-Z]:$/i,m=/^\/([A-Z]:)?$/i,J=/.(\.[^./]+)$/,T=o(()=>typeof process<"u"&&typeof process.cwd=="function"?process.cwd().replaceAll("\\","/"):"/","_"),W="/",M=":",g=o((e,t)=>{let r="",n=0,i=-1,a=0,l=null;for(let s=0;s<=e.length;++s){if(s<e.length)l=e[s];else{if(l==="/")break;l="/"}if(l==="/"){if(!(i===s-1||a===1))if(a===2){if(r.length<2||n!==2||!r.endsWith(".")||r.at(-2)!=="."){if(r.length>2){let f=r.lastIndexOf("/");f===-1?(r="",n=0):(r=r.slice(0,f),n=r.length-1-r.lastIndexOf("/")),i=s,a=0;continue}else if(r.length>0){r="",n=0,i=s,a=0;continue}}t&&(r+=r.length>0?"/..":"..",n=2)}else r.length>0?r+=`/${e.slice(i+1,s)}`:r=e.slice(i+1,s),n=s-i-1;i=s,a=0}else l==="."&&a!==-1?++a:a=-1}return r},"g$2"),u=o(e=>F.test(e),"f"),y=o(function(e){if(e.length===0)return".";e=c(e);let t=z.exec(e),r=u(e),n=e.at(-1)==="/";return e=g(e,!r),e.length===0?r?"/":n?"./":".":(n&&(e+="/"),$.test(e)&&(e+="/"),t?r?`//${e}`:`//./${e}`:r&&!u(e)?`/${e}`:e)},"m$1"),b=o(function(...e){if(e.length===0)return".";let t;for(let r of e)r&&r.length>0&&(t===void 0?t=r:t+=`/${r}`);return t===void 0?".":y(t.replaceAll(/\/{2,}/g,"/"))},"z"),p=o(function(...e){e=e.map(n=>c(n));let t="",r=!1;for(let n=e.length-1;n>=-1&&!r;n--){let i=n>=0?e[n]:T();!i||i.length===0||(t=`${i}/${t}`,r=u(i))}return t=g(t,!r),r&&!u(t)?`/${t}`:t.length>0?t:"."},"a"),V=o(function(e){return c(e)},"L"),w=o(function(e){return J.exec(c(e))?.[1]??""},"h"),B=o(function(e,t){let r=p(e).replace(m,"$1").split("/"),n=p(t).replace(m,"$1").split("/");if(n[0][1]===":"&&r[0][1]===":"&&r[0]!==n[0])return n.join("/");let i=[...r];for(let a of i){if(n[0]!==a)break;r.shift(),n.shift()}return[...r.map(()=>".."),...n].join("/")},"N"),d=o(e=>{let t=c(e).replace(/\/$/,"").split("/").slice(0,-1);return t.length===1&&$.test(t[0])&&(t[0]+="/"),t.join("/")||(u(e)?"/":".")},"x"),G=o(function(e){let t=[e.root,e.dir,e.base??e.name+e.ext].filter(Boolean);return c(e.root?p(...t):t.join("/"))},"C"),j=o((e,t)=>{let r=c(e).split("/").pop();return t&&r.endsWith(t)?r.slice(0,-t.length):r},"E"),R=o(function(e){let t=c(e).split("/").shift();t===""?t="/":t+="/";let r=j(e),n=w(r);return{base:r,dir:d(e),ext:n,name:r.slice(0,r.length-n.length),root:t}},"U"),q=Object.defineProperty,h=o((e,t)=>q(e,"name",{value:t,configurable:!0}),"r");const H="last-update-check.json",k=h(e=>{const t=S(e);if(t===void 0)throw new Error("Could not find cache directory");return b(t,H)},"getConfigFile"),K=h(e=>{const t=k(e);try{if(!v(t))return;const{lastUpdateCheck:r}=JSON.parse(N(t,"utf8"));return r}catch{return}},"getLastUpdate"),Q=h(e=>{const t=k(e),r=d(t);v(r)||x(r,{recursive:!0}),O(t,JSON.stringify({lastUpdateCheck:Date.now()}))},"saveLastUpdate");var X=Object.defineProperty,Y=o((e,t)=>X(e,"name",{value:t,configurable:!0}),"g");const ee=Y(async(e,t,r)=>{const n=r.replace("__NAME__",e);return await new Promise((i,a)=>{U(n,l=>{let s="";l.on("data",f=>s+=f),l.on("end",()=>{try{const f=JSON.parse(s)[t];f||a(new Error("Error getting version")),i(f)}catch{a(new Error("Could not parse version response"))}})}).on("error",l=>a(l))})},"getDistributionVersion");var te=Object.defineProperty,re=o((e,t)=>te(e,"name",{value:t,configurable:!0}),"i");const se=re(async({alwaysRun:e,debug:t,distTag:r="latest",pkg:n,registryUrl:i="https://registry.npmjs.org/-/package/__NAME__/dist-tags",updateCheckInterval:a=1e3*60*60*24})=>{const l=K(n.name);if(e||!l||l<Date.now()-a){const s=await ee(n.name,r,i);if(Q(n.name),P(s,n.version))return s;t&&console.error(`Latest version (${s}) not newer than current version (${n.version})`)}else t&&console.error(`Too recent to check for a new update. simpleUpdateNotifier() interval set to ${a}ms but only ${Date.now()-l}ms since last check.`);return null},"hasNewVersion");export{se as default};
package/dist/index.cjs CHANGED
@@ -1,36 +1,10 @@
1
- 'use strict';
2
-
3
- var chunk764E7XDY_cjs = require('./chunk-764E7XDY.cjs');
4
- var process$1 = require('process');
5
- var boxen = require('@visulima/boxen');
6
- var colorize = require('@visulima/colorize');
7
- var server = require('@visulima/pail/server');
8
- var dt = require('command-line-args');
9
- var L = require('cli-table3');
10
- var Oe = require('@visulima/colorize/template');
11
- var Ee = require('os');
12
- var fastestLevenshtein = require('fastest-levenshtein');
13
-
14
- function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
15
-
16
- var dt__default = /*#__PURE__*/_interopDefault(dt);
17
- var L__default = /*#__PURE__*/_interopDefault(L);
18
- var Oe__default = /*#__PURE__*/_interopDefault(Oe);
19
- var Ee__default = /*#__PURE__*/_interopDefault(Ee);
20
-
21
- chunk764E7XDY_cjs.c();chunk764E7XDY_cjs.c();chunk764E7XDY_cjs.c();var de=/[\p{Lu}]/u,ge=/[\p{Ll}]/u,M=/^[\p{Lu}](?![\p{Lu}])/gu,F=/([\p{Alpha}\p{N}_]|$)/u,w=/[_.\- ]+/,ue=new RegExp("^"+w.source),j=new RegExp(w.source+F.source,"gu"),Y=new RegExp("\\d+"+F.source,"gu"),fe=(o,e,t,n)=>{let r=!1,i=!1,s=!1,a=!1;for(let p=0;p<o.length;p++){let c=o[p];a=p>2?o[p-3]==="-":!0,r&&de.test(c)?(o=o.slice(0,p)+"-"+o.slice(p),r=!1,s=i,i=!0,p++):i&&s&&ge.test(c)&&(!a||n)?(o=o.slice(0,p-1)+"-"+o.slice(p-1),s=i,i=!1,r=!0):(r=e(c)===c&&t(c)!==c,s=i,i=t(c)===c&&e(c)!==c);}return o},he=(o,e)=>(M.lastIndex=0,o.replaceAll(M,t=>e(t))),ye=(o,e)=>(j.lastIndex=0,Y.lastIndex=0,o.replaceAll(Y,(t,n,r)=>["_","-"].includes(o.charAt(r+t.length))?t:e(t)).replaceAll(j,(t,n)=>e(n)));function A(o,e){if(!(typeof o=="string"||Array.isArray(o)))throw new TypeError("Expected the input to be `string | string[]`");if(e={pascalCase:!1,preserveConsecutiveUppercase:!1,...e},Array.isArray(o)?o=o.map(i=>i.trim()).filter(i=>i.length).join("-"):o=o.trim(),o.length===0)return "";let t=e.locale===!1?i=>i.toLowerCase():i=>i.toLocaleLowerCase(e.locale),n=e.locale===!1?i=>i.toUpperCase():i=>i.toLocaleUpperCase(e.locale);return o.length===1?w.test(o)?"":e.pascalCase?n(o):t(o):(o!==t(o)&&(o=fe(o,t,n,e.preserveConsecutiveUppercase)),o=o.replace(ue,""),o=e.preserveConsecutiveUppercase?he(o,t):t(o),e.pascalCase&&(o=n(o.charAt(0))+o.slice(1)),ye(o,n))}chunk764E7XDY_cjs.c();chunk764E7XDY_cjs.c();var be=[{description:"Turn on verbose output",group:"global",name:"verbose",type:Boolean},{description:"Turn on debugging output",group:"global",name:"debug",type:Boolean},{alias:"h",description:"Print out helpful usage information",group:"global",name:"help",type:Boolean},{alias:"q",description:"Silence output",group:"global",name:"quiet",type:Boolean},{alias:"V",description:"Print version info",group:"global",name:"version",type:Boolean},{description:"Turn off colored output",group:"global",name:"no-color",type:Boolean},{description:"Force colored output",group:"global",name:"color",type:Boolean}],b=be;chunk764E7XDY_cjs.c();chunk764E7XDY_cjs.c();chunk764E7XDY_cjs.c();var Ce=o=>o?Oe__default.default(Object.assign([],{raw:[o.replaceAll("`","\\`")]})):"",d=Ce;chunk764E7XDY_cjs.c();var N=class{lines;constructor(){this.lines=[];}add(e){this.lines.push(e);}toString(){return this.lines.join(Ee__default.default.EOL)}header(e){this.add(colorize.bold(e)),this.lines.push("");}},T=N;var v={chars:{bottom:"","bottom-left":"","bottom-mid":"","bottom-right":"",left:" ","left-mid":"",mid:"","mid-mid":"",middle:" ",right:"","right-mid":"",top:"","top-left":"","top-mid":"","top-right":""},colWidths:[40,60],style:{border:[],compact:!0,head:[],"padding-left":2,"padding-right":1},wordWrap:!0},P=class extends T{constructor(e){if(super(),e.header&&this.header(d(e.header)),e.content){if(e.raw)if(Array.isArray(e.content)&&e.content.every(t=>typeof t=="string"))e.content.forEach(t=>{Array.isArray(t)?t.forEach(n=>this.add(d(n))):this.add(d(t));});else if(typeof e.content=="string")this.add(d(e.content));else throw new TypeError("Invalid raw content, must be a string or array of strings.");else this.add(this.getContentLines(e.content));this.add("");}}getContentLines(e){if(typeof e=="string"){let t=new L__default.default({...v,colWidths:[80]});return t.push([d(e)]),t.toString()}if(Array.isArray(e)&&e.every(t=>typeof t=="string"||Array.isArray(t)&&t.every(n=>typeof n=="string"))){let t=new L__default.default({...v});return e.forEach(n=>{Array.isArray(n)?t.push(n.map(r=>d(r))):t.push([d(n)]);}),t.toString()}if(typeof e=="object"){let t=e;if(!t.options||!t.data)throw new Error(`Must have an "options" or "data" property
22
- ${JSON.stringify(e)}`);let n=new L__default.default({...v,...t.options,style:{...v.style,...t.options.style}});return t.data.forEach(r=>{Array.isArray(r)?n.push(r.map(i=>d(i))):n.push([d(r)]);}),n.toString()}throw new Error(`invalid input - 'content' must be a string, array of strings or a object:
23
-
24
- ${JSON.stringify(e)}`)}},G=P;chunk764E7XDY_cjs.c();var _=class extends T{constructor(e){super();let t=e.optionList??[],n=Array.isArray(e.hide)?e.hide:[e.hide].filter(Boolean),r=Array.isArray(e.group)?e.group:[e.group].filter(Boolean);n.length>0&&(t=t.filter(s=>!n.includes(s.name))),e.header&&this.header(d(e.header)),r.length>0&&(t=t.filter(s=>{let a=r.includes("_none")&&!s.group,p=this.intersect(Array.isArray(s.group)?s.group:[s.group],r);return a||p?s:void 0}));let i=new L__default.default({chars:{bottom:"","bottom-left":"","bottom-mid":"","bottom-right":"",left:" ","left-mid":"",mid:"","mid-mid":"",middle:" ",right:"","right-mid":"",top:"","top-left":"","top-mid":"","top-right":""},colWidths:[40,40],style:{"padding-left":2,"padding-right":1},wordWrap:!0});t.forEach(s=>i.push([this.getOptionNames(s,e.reverseNameOrder??!1,e.isArgument??!1),d(s.description)])),this.add(i.toString()),this.lines.push("");}getOptionNames(e,t,n){if(!e.name)throw new TypeError("Invalid option definition, name is required.");let r=e.type?e.type.name.toLowerCase():"string",i=e.multiple||e.lazyMultiple?"[]":"";r=d(e.typeLabel??`{underline ${r}${i}}`);let s;if(e.alias)if(e.name){let a=n?e.name:`{yellow --${e.name}}`;s=t?d(`{bold ${a}}, {bold -${e.alias}} ${r}`):d(`{bold -${e.alias}}, {bold ${a}} ${r}`);}else t?s=d(`{bold -${e.alias}} ${r}`):s=d(`{bold -${e.alias}} ${r}`);else s=d(`{bold ${n?e.name:`{yellow --${e.name}}`}} ${r}`);return s}intersect(e,t){return e.some(n=>t.includes(n))}},q=_;var Ie=o=>(Array.isArray(o)?o:[o]).length===0?"":`
25
- ${o.map(t=>t.optionList?new q(t).toString():new G(t).toString()).join(`
26
- `)}`,R=Ie;var J="__Other",W=o=>o.charAt(0).toUpperCase()+o.slice(1),xe=(o,e,t,n)=>{o.debug("no command given, printing general help...");let r=[...new Set(t.values())].filter(s=>!s.hidden);n&&(r=r.filter(s=>s.group===n));let i=r.reduce((s,a)=>{let p=a.group??J;return s[p]||(s[p]=[]),s[p].push(a),s},{});o.raw(R([{content:`{cyan ${e.getCliName()}} {green <command>} [positional arguments] {yellow [options]}`,header:"{inverse.cyan Usage }"},...Object.keys(i).map(s=>({content:i[s].map(a=>{let p="";return typeof a.alias=="string"?p=a.alias:Array.isArray(a.alias)&&(p=a.alias.join(", ")),p!==""&&(p=` [${p}]`),[`{green ${a.name}} ${p}`,a.description??""]}),header:s===J||n?`{inverse.green Available${n?` ${W(n)}`:""} Commands }`:` {inverse.green ${W(s)} }`})),t.has("help")?{header:"{inverse.yellow Command Options }",optionList:t.get("help").options?.filter(s=>!s.hidden)}:void 0,{header:"{inverse.yellow Global Options }",optionList:b},{content:`Run "{cyan ${e.getCliName()}} {green help <command>}" or "{cyan ${e.getCliName()}} {green <command>} {yellow --help}" for help with a specific command.`,raw:!0}].filter(Boolean)));},we=(o,e,t,n)=>{let r=t.get(n),i=[];if(i.push({content:`{cyan ${e.getCliName()}} {green ${r.name}}${r.argument?" [positional arguments]":""}${r.options?" [options]":""}`,header:"{inverse.cyan Usage }"}),r.description&&i.push({content:r.description,header:"{inverse.green Description }"}),r.argument&&i.push({header:"Command Positional Arguments",isArgument:!0,optionList:[r.argument]}),Array.isArray(r.options)&&r.options.length>0&&i.push({header:"{inverse.yellow Command Options }",optionList:r.options.filter(s=>!s.hidden)}),i.push({header:"{inverse.yellow Global Options }",optionList:b}),r.alias!==void 0&&r.alias.length>0){let s=r.alias;typeof r.alias=="string"&&(s=[r.alias]),i.splice(1,0,{content:s,header:"Alias(es)"});}Array.isArray(r.examples)&&r.examples.length>0&&i.push({content:r.examples,header:"Examples"}),o.raw(R(i));},$=class{name="help";options=[{description:"Display only the specified group",name:"group",type:String}];commands;constructor(e){this.commands=e;}execute(e){let{commandName:t,logger:n,options:r,runtime:i}=e,{footer:s,header:a}=i.getCommandSection();a&&n.raw(d(a)),t==="help"?xe(n,i,this.commands,r?.group):we(n,i,this.commands,t),s&&n.raw(d(s));}},H=$;chunk764E7XDY_cjs.c();var K={alias:["v","V"],description:"Output the version number",execute:({logger:o,runtime:e})=>{let t=e.getPackageVersion();t===void 0?(o.warn("Unknown version"),o.debug("The version number was not provided by the cli constructor.")):o.info(t);},name:"version",options:[],usage:[]};chunk764E7XDY_cjs.c();var C="positionals";chunk764E7XDY_cjs.c();var S=class{result;argv;options;argument;command;commandName;runtime;logger;constructor(e,t){this.commandName=e,this.command=t;}},z=S;chunk764E7XDY_cjs.c();var Ae=()=>{let o=process.env.CEREBRO_MIN_NODE_VERSION?Number(process.env.CEREBRO_MIN_NODE_VERSION):18,e=process.version.replace("v","");Number(/v([^.]+)/.exec(process.version)[1])<o&&(console.log(`cerebro supports a minimum Node version of ${o}. You have ${e}. Read our version support policy: https://github.com/visulima/visulima#supported-nodejs-versions`),process.exit(1));},Q=Ae;chunk764E7XDY_cjs.c();chunk764E7XDY_cjs.c();var Ne=/^-{1,2}(\w+)(=(\w+))?$/,Le=(o,e)=>{let t=Ne.exec(o);if(t==null)return {};let n=t[1],r=e.find(i=>i.name===n||i.alias===n);return r!==void 0?{argName:r.name,argValue:t[3],option:r}:{}},I=Le;chunk764E7XDY_cjs.c();var Pe=o=>o.type?.name==="Boolean",y=Pe;var X=(o,e)=>{if(e.type===void 0)return o;if(e.type.name==="Boolean"){if(o==="true"||o==="1")return e.type(!0);if(o==="false"||o==="0")return e.type(!1)}return e.type(o)},_e=new Set(["1","0","true","false"]),Re=(o,e)=>{let t=(n,r)=>{let{argName:i,argValue:s,option:a}=I(r,e),{lastOption:p}=n;return a&&y(a)&&s&&i?n.partial[i]=X(s,a):n.lastName&&p&&y(p)&&_e.has(r)&&(n.partial[n.lastName]=X(r,p)),{lastName:i,lastOption:a,partial:n.partial}};return o.reduce(t,{partial:{}}).partial},Z=Re;chunk764E7XDY_cjs.c();var $e=o=>{let e=o.type?o.type.name.toLowerCase():"string",t=o.multiple??o.lazyMultiple?"[]":"";return e&&(e=e==="boolean"?"":`{underline ${e}${t}}`),e},Se=o=>(y(o)||(o.typeLabel=o.typeLabel??$e(o),o.defaultOption&&(o.typeLabel=`${o.typeLabel} (D)`),o.required&&(o.typeLabel=`${o.typeLabel} (R)`)),o),ee=Se;chunk764E7XDY_cjs.c();var De=new Set(["1","0","true","false"]),Ve=(o,e)=>{let t=(n,r)=>{let{argValue:i,option:s}=I(r,e),{lastOption:a}=n;if(a&&y(a)&&De.has(r)){let p=[...n.args];return p.pop(),{args:p}}return s&&y(s)&&i?{args:n.args}:{args:[...n.args,r],lastOption:s}};return o.reduce(t,{args:[]}).args},te=Ve;chunk764E7XDY_cjs.c();var Be=new RegExp(/^-([^\d-])$/),Ue=new RegExp(/^--(\S+)/),ke=new RegExp(/^-([^\d-]{2,})$/),Me=o=>Be.test(o)||Ue.test(o)||ke.test(o),je=(o,e)=>{let t=e[0]&&Me(e[0])||e.length===0?null:e.shift()??null;if(!o.includes(t)){let n=new Error(`Command not recognised: ${t}`);throw n.command=t,n.name="INVALID_COMMAND",n}return {argv:e,command:t}},oe=je;chunk764E7XDY_cjs.c();var Fe=(o,e)=>fastestLevenshtein.distance(o,e)<=o.length/3||e.includes(o),Ge=(o,e)=>{let t=o.toLowerCase();return e.filter(n=>Fe(n.toLowerCase(),t))},D=Ge;chunk764E7XDY_cjs.c();var qe=(o,e)=>o.filter(t=>t.required&&e[t.name]==null).filter(t=>t.type?.name==="Boolean"?(e[t.name]=!1,!1):!0),ne=qe;chunk764E7XDY_cjs.c();var Je=o=>{let e=new Map;return o.forEach(t=>{e.set(t.name,{...e.get(t.name),...t});}),[...e.values()]},ie=Je;chunk764E7XDY_cjs.c();chunk764E7XDY_cjs.c();var We=()=>!!process.versions.electron,He=()=>We()&&!process.defaultApp,Ke=()=>He()?0:1,ze=o=>o.slice(Ke()+1),re=ze;var Qe=" ",Xe=(o,e)=>o.length===e.length&&o.every((t,n)=>t===e[n]),Ze=o=>typeof o=="string"?o.split(Qe):Xe(o,process.argv)?re(o):o,se=Ze;chunk764E7XDY_cjs.c();var et=o=>{process.on("uncaughtException",e=>{o.error(`Uncaught exception: ${e}`),e?.stack&&o.error(e.stack),process.exit(1);}),process.on("unhandledRejection",e=>{o.error(`Promise rejection: ${e}`),e?.stack&&o.error(e.stack),process.exit(1);});},ae=et;var gt="CI"in process$1.env&&("GITHUB_ACTIONS"in process$1.env||"GITLAB_CI"in process$1.env||"CIRCLECI"in process$1.env),ut=o=>o.charAt(0).toLowerCase()+o.slice(1),B=class{logger;argv;cwd;cliName;packageVersion;packageName;extensions=[];commands;defaultCommand;updateNotifierOptions;commandSection;constructor(e,t={}){let{argv:n,cwd:r,packageName:i,packageVersion:s}={argv:process$1.argv,cwd:process$1.cwd(),...t};this.argv=se(n),this.argv.includes("--quiet")||this.argv.includes("-q")?process$1.env.CEREBRO_OUTPUT_LEVEL=String(16):this.argv.includes("--verbose")||this.argv.includes("-v")?process$1.env.CEREBRO_OUTPUT_LEVEL=String(64):this.argv.includes("--debug")||this.argv.includes("-vvv")||"DEBUG"in process$1.env?process$1.env.CEREBRO_OUTPUT_LEVEL=String(128):process$1.env.CEREBRO_OUTPUT_LEVEL=String(32);let a={32:"informational",64:"trace",128:"debug"};this.logger=server.createPail({logLevel:process$1.env.CEREBRO_OUTPUT_LEVEL?a[process$1.env.CEREBRO_OUTPUT_LEVEL]??"informational":"informational",...t.logger}),process$1.env.CEREBRO_OUTPUT_LEVEL===String(16)&&this.logger.disable(),Q(),ae(this.logger),this.cliName=e,this.packageVersion=s,this.packageName=i,this.cwd=r,this.defaultCommand="help",this.commandSection={header:`${this.cliName}${this.packageVersion?` v${this.packageVersion}`:""}`},this.commands=new Map,this.addCoreExtensions(),this.addCommand(K),this.addCommand(new H(this.commands));}setCommandSection(e){return this.commandSection=e,this}getCommandSection(){return this.commandSection}setDefaultCommand(e){return this.defaultCommand=e,this}addCommand(e){if(this.commands.has(e.name))throw new Error(`Ignored command with name "${e.name}, it was found in the command list."`);if(e.options?.map(t=>ee(t)),this.validateDoubleOptions(e),this.addNegatableOption(e),e.options?.forEach(t=>{t.__camelCaseName__=A(t.name);}),this.commands.set(e.name,e),e.alias!==void 0){let t=e.alias;typeof e.alias=="string"&&(t=[e.alias]),t.forEach(n=>{if(this.logger.debug("adding alias",n),this.commands.has(n))throw new Error(`Ignoring command alias "${n}, command with the same name was found."`);this.commands.set(n,e);});}return this}addExtension(e){return this.extensions.push(e),this}enableUpdateNotifier(e={}){if(!this.packageName||!this.packageVersion)throw new Error("Cannot enable update notifier without package name and version.");let t=Object.keys(e);if(t.length>0&&!t.includes("alwaysRun")&&!t.includes("distTag")&&!t.includes("updateCheckInterval"))throw new Error("Invalid update notifier options, please check the documentation.");return this.updateNotifierOptions={alwaysRun:!1,debug:process$1.env.CEREBRO_OUTPUT_LEVEL===String(128),distTag:"latest",pkg:{name:this.packageName,version:this.packageVersion},updateCheckInterval:1e3*60*60*24,...e},this}getCliName(){return this.cliName}getPackageVersion(){return this.packageVersion}getPackageName(){return this.packageName}getCommands(){return this.commands}getCwd(){return this.cwd}async run(e={}){let{shouldExitProcess:t=!0,...n}=e,r=[...this.commands.keys()],i;this.logger.debug(`process.execPath: ${process$1.execPath}`),this.logger.debug(`process.execArgv: ${process$1.execArgv.join(" ")}`),this.logger.debug(`process.argv: ${process$1.argv.join(" ")}`);try{i=oe([null,...r],this.argv);}catch(h){if(h.name==="INVALID_COMMAND"&&h.command){let U="",k=D(h.command,[...this.commands.keys()]);k.length>0&&(U=` Did you mean: \r
27
- - ${k.join(` \r
28
- - `)}`),this.logger.error(`"${h.command}" is not an available command.${U}`);}else this.logger.error(h);return t?process$1.exit(1):void 0}let s=i.command??this.defaultCommand,a=this.commands.get(s);if(typeof a.execute!="function")return this.logger.error(`Command "${a.name}" has no function to execute.`),t?process$1.exit(1):void 0;let p=i.argv;this.logger.debug(`command '${s}' found, parsing command args: ${p.join(", ")}`);let c=ie([...a.options??[],...b]);c.forEach(h=>{if(h.multiple&&h.lazyMultiple)throw new Error(`Argument "${h.name}" cannot have both multiple and lazyMultiple options, please choose one.`)}),a.argument&&(this.logger.debug("command has positional argument, parsing them..."),c=[{defaultOption:!0,description:a.argument?.description,group:"positionals",multiple:!0,name:C,type:a.argument?.type,typeLabel:a.argument?.typeLabel},...c]);let f=dt__default.default(c,{argv:te(p,a.options??[]),camelCase:!0,partial:!0,stopAtFirstUnknown:!0}),E=Z(p,a.options??[]),O={...f,_all:{...f._all,...E}};this.validateCommandOptions(c,O,a);let u=new z(a.name,a);u.runtime=this,await this.registerExtensions(u),await this.updateNotifier(u);let{_all:x,positionals:ce}=O;return x[C]&&delete x[C],u.argument=ce?.[C]??[],u.argv=this.argv,u.options={...x,...n},this.mapNegatableOptions(u,a),this.mapImpliesOptions(u,a),this.validateCommandArgsForConflicts(c,u.options,a),this.logger.debug("command options parsed from options:"),this.logger.debug(JSON.stringify(u.options,null,2)),this.logger.debug("command argument parsed from argument:"),this.logger.debug(JSON.stringify(u.argument,null,2)),await this.prepareToolboxResult(O,u,a),t?process$1.exit(0):void 0}validateDoubleOptions(e){if(Array.isArray(e.options)){let t=e.options.reduce((i,s)=>{let a=`${s.name}-${s.alias}`;return i[a]||(i[a]=[]),i[a].push(s),i},{}),n=Object.values(t).filter(i=>i.length>1),r="";if(n.forEach(i=>{let s=i[0],a=i[1],p="alias";s.name===a.name&&(p="name",s.alias===a.alias&&(p+=" and alias")),r+=`Cannot add option ${p} "${JSON.stringify(a)}" to command "${e.name}" due to conflicting option ${JSON.stringify(s)}
29
- `;}),r.length>0)throw new Error(r)}}addCoreExtensions(){this.addExtension({execute:e=>{e.logger=this.logger;},name:"logger"});}async prepareToolboxResult(e,t,n){if(e.global?.help){this.logger.debug("'--help' option found, running 'help' for given command...");let r=this.commands.get("help");if(!r)throw new Error("Help command not found.");await r.execute(t);return}if(e.global?.version||e.global?.V){this.logger.debug("'--version' option found, running 'version' for given command...");let r=this.commands.get("version");if(!r)throw new Error("Version command not found.");await r.execute(t);return}await n.execute(t);}async updateNotifier({logger:e}){if(this.updateNotifierOptions&&this.updateNotifierOptions.alwaysRun||!(process$1.env.NO_UPDATE_NOTIFIER||process$1.env.NODE_ENV==="test"||this.argv.includes("--no-update-notifier")||gt)&&this.updateNotifierOptions){e.raw("Checking for updates...");let n=await(await import('./has-new-version-RNHOSICQ.cjs').then(r=>r.default))(this.updateNotifierOptions);if(n){let r="Update available "+colorize.dim(this.packageVersion+"")+colorize.reset(" \u2192 ")+colorize.green(n);this.logger.error(boxen.boxen(r,{borderColor:i=>colorize.yellow(i),borderStyle:"round",margin:1,padding:1,textAlignment:"center"}));}}}validateCommandOptions(e,t,n){let r=ne(e,t);if(r.length>0)throw new Error(`You called the command "${n.name}" without the required options: ${r.map(i=>i.name).join(", ")}`);if(t._unknown&&t._unknown.length>0){let i=[];if(t._unknown.forEach(s=>{let a=s.startsWith("--"),p=`Found unknown ${a?"option":"argument"} "${s}"`;if(a){let c=D(s.replace("--",""),[...(n.options??[]).map(f=>f.name),...b.map(f=>f.name)]);if(c.length>0){let[f,...E]=c.map(O=>`--${O}`);p+=E.length>0?`, did you mean ${f} or ${E.join(", ")}?`:`, did you mean ${f}?`;}}i.push(p);}),i.length>0)throw new Error(i.join(`
30
- `))}}validateCommandArgsForConflicts(e,t,n){let r=e.filter(i=>i.conflicts!==void 0);if(r.length>0){let i=r.find(s=>Array.isArray(s.conflicts)?s.conflicts.some(a=>t[a]!==void 0):t[s.conflicts]!==void 0);if(i)throw new Error(`You called the command "${n.name}" with conflicting options: ${i.name} and ${typeof i.conflicts=="string"?i.conflicts:i.conflicts?.join(", ")}`)}}addNegatableOption(e){Array.isArray(e.options)&&e.options.forEach(t=>{if(t.name.startsWith("no-")&&!e.options.some(n=>n.name===t.name.replace("no-",""))){if(t.type!==Boolean){this.logger.debug(`Cannot add negated option "${t.name}" to command "${e.name}" because it is not a boolean.`);return}let n={...t,defaultValue:t.defaultValue===void 0?!0:!t.defaultValue,name:`${t.name.replace("no-","")}`};e.options.push(n);}});}async registerExtensions(e){let t=async n=>typeof n.execute!="function"?(this.logger.warn(`Skipped ${n.name} because execute is not a function.`),null):(await n.execute(e),null);for(let n of this.extensions)await t(n);}mapNegatableOptions(e,t){Object.entries(e.options).forEach(([n,r])=>{if(/^no\w+/.test(n)){let i=ut(n.replace("no",""));this.logger.debug(`mapping negated option "${n}" to "${i}"`),e.options[i]=!r,t.options?.forEach(s=>{s.name===i&&(s.__negated__=!0);});}});}mapImpliesOptions(e,t){Object.keys(e.options).forEach(n=>{let r=t.options?.find(i=>i.__camelCaseName__===n&&i.__negated__===void 0&&i.implies!==void 0);if(r?.implies){let i=r.implies;Object.entries(i).forEach(([s,a])=>{if(e.options[s]===void 0)e.options[s]=a;else {let p=t.options?.find(c=>c.name===s);(p?.defaultValue===void 0||e.options[s]===p.defaultValue)&&(e.options[s]=a);}});}});}};
31
-
32
- module.exports = B;
33
- //# sourceMappingURL=out.js.map
34
-
35
- module.exports = module.exports;
36
- //# sourceMappingURL=index.cjs.map
1
+ "use strict";var Z=Object.create;var x=Object.defineProperty;var ee=Object.getOwnPropertyDescriptor;var te=Object.getOwnPropertyNames;var ne=Object.getPrototypeOf,oe=Object.prototype.hasOwnProperty;var c=(t,e)=>x(t,"name",{value:e,configurable:!0});var ae=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of te(e))!oe.call(t,a)&&a!==n&&x(t,a,{get:()=>e[a],enumerable:!(o=ee(e,a))||o.enumerable});return t};var re=(t,e,n)=>(n=t!=null?Z(ne(t)):{},ae(e||!t||!t.__esModule?x(n,"default",{value:t,enumerable:!0}):n,t));const p=require("node:process"),se=require("@visulima/boxen"),v=require("@visulima/colorize"),ie=require("@visulima/pail/server"),le=require("command-line-args"),ce=require("cli-table3"),pe=require("@visulima/colorize/template"),de=require("node:os"),me=require("fastest-levenshtein"),A=c(t=>t&&typeof t=="object"&&"default"in t?t.default:t,"_interopDefaultCompat"),ue=A(le),O=A(ce),ge=A(pe),he=A(de),fe=/[\p{Lu}]/u,ve=/[\p{Ll}]/u,I=/^[\p{Lu}](?![\p{Lu}])/gu,G=/([\p{Alpha}\p{N}_]|$)/u,S=/[_.\- ]+/,ye=new RegExp("^"+S.source),j=new RegExp(S.source+G.source,"gu"),B=new RegExp("\\d+"+G.source,"gu"),be=c((t,e,n,o)=>{let a=!1,r=!1,s=!1,i=!1;for(let l=0;l<t.length;l++){const d=t[l];i=l>2?t[l-3]==="-":!0,a&&fe.test(d)?(t=t.slice(0,l)+"-"+t.slice(l),a=!1,s=r,r=!0,l++):r&&s&&ve.test(d)&&(!i||o)?(t=t.slice(0,l-1)+"-"+t.slice(l-1),s=r,r=!1,a=!0):(a=e(d)===d&&n(d)!==d,s=r,r=n(d)===d&&e(d)!==d)}return t},"preserveCamelCase"),$e=c((t,e)=>(I.lastIndex=0,t.replaceAll(I,n=>e(n))),"preserveConsecutiveUppercase"),Ee=c((t,e)=>(j.lastIndex=0,B.lastIndex=0,t.replaceAll(B,(n,o,a)=>["_","-"].includes(t.charAt(a+n.length))?n:e(n)).replaceAll(j,(n,o)=>e(o))),"postProcess");function we(t,e){if(!(typeof t=="string"||Array.isArray(t)))throw new TypeError("Expected the input to be `string | string[]`");if(e={pascalCase:!1,preserveConsecutiveUppercase:!1,...e},Array.isArray(t)?t=t.map(r=>r.trim()).filter(r=>r.length).join("-"):t=t.trim(),t.length===0)return"";const n=e.locale===!1?r=>r.toLowerCase():r=>r.toLocaleLowerCase(e.locale),o=e.locale===!1?r=>r.toUpperCase():r=>r.toLocaleUpperCase(e.locale);return t.length===1?S.test(t)?"":e.pascalCase?o(t):n(t):(t!==n(t)&&(t=be(t,n,o,e.preserveConsecutiveUppercase)),t=t.replace(ye,""),t=e.preserveConsecutiveUppercase?$e(t,n):n(t),e.pascalCase&&(t=o(t.charAt(0))+t.slice(1)),Ee(t,o))}c(we,"camelCase");const C=[{description:"Turn on verbose output",group:"global",name:"verbose",type:Boolean},{description:"Turn on debugging output",group:"global",name:"debug",type:Boolean},{alias:"h",description:"Print out helpful usage information",group:"global",name:"help",type:Boolean},{alias:"q",description:"Silence output",group:"global",name:"quiet",type:Boolean},{alias:"V",description:"Print version info",group:"global",name:"version",type:Boolean},{description:"Turn off colored output",group:"global",name:"no-color",type:Boolean},{description:"Force colored output",group:"global",name:"color",type:Boolean}];var Oe=Object.defineProperty,Ce=c((t,e)=>Oe(t,"name",{value:e,configurable:!0}),"e$5");const m=Ce(t=>t?ge(Object.assign([],{raw:[t.replaceAll("`","\\`")]})):"","templateFormat");var Ae=Object.defineProperty,Ne=c((t,e)=>Ae(t,"name",{value:e,configurable:!0}),"t$6");let W=class{static{c(this,"n")}static{Ne(this,"BaseSection")}lines;constructor(){this.lines=[]}add(e){this.lines.push(e)}toString(){return this.lines.join(he.EOL)}header(e){this.add(v.bold(e)),this.lines.push("")}};var _e=Object.defineProperty,Le=c((t,e)=>_e(t,"name",{value:e,configurable:!0}),"p$4");const E={chars:{bottom:"","bottom-left":"","bottom-mid":"","bottom-right":"",left:" ","left-mid":"",mid:"","mid-mid":"",middle:" ",right:"","right-mid":"",top:"","top-left":"","top-mid":"","top-right":""},colWidths:[40,60],style:{border:[],compact:!0,head:[],"padding-left":2,"padding-right":1},wordWrap:!0};let xe=class extends W{static{c(this,"y")}static{Le(this,"ContentSection")}constructor(e){if(super(),e.header&&this.header(m(e.header)),e.content){if(e.raw)if(Array.isArray(e.content)&&e.content.every(n=>typeof n=="string"))e.content.forEach(n=>{Array.isArray(n)?n.forEach(o=>this.add(m(o))):this.add(m(n))});else if(typeof e.content=="string")this.add(m(e.content));else throw new TypeError("Invalid raw content, must be a string or array of strings.");else this.add(this.getContentLines(e.content));this.add("")}}getContentLines(e){if(typeof e=="string"){const n=new O({...E,colWidths:[80]});return n.push([m(e)]),n.toString()}if(Array.isArray(e)&&e.every(n=>typeof n=="string"||Array.isArray(n)&&n.every(o=>typeof o=="string"))){const n=new O({...E});return e.forEach(o=>{Array.isArray(o)?n.push(o.map(a=>m(a))):n.push([m(o)])}),n.toString()}if(typeof e=="object"){const n=e;if(!n.options||!n.data)throw new Error(`Must have an "options" or "data" property
2
+ ${JSON.stringify(e)}`);const o=new O({...E,...n.options,style:{...E.style,...n.options.style}});return n.data.forEach(a=>{Array.isArray(a)?o.push(a.map(r=>m(r))):o.push([m(a)])}),o.toString()}throw new Error(`invalid input - 'content' must be a string, array of strings or a object:
3
+
4
+ ${JSON.stringify(e)}`)}};var Re=Object.defineProperty,Se=c((t,e)=>Re(t,"name",{value:e,configurable:!0}),"a$3");let Pe=class extends W{static{c(this,"c")}static{Se(this,"OptionListSection")}constructor(e){super();let n=e.optionList??[];const o=Array.isArray(e.hide)?e.hide:[e.hide].filter(Boolean),a=Array.isArray(e.group)?e.group:[e.group].filter(Boolean);o.length>0&&(n=n.filter(s=>!o.includes(s.name))),e.header&&this.header(m(e.header)),a.length>0&&(n=n.filter(s=>{const i=a.includes("_none")&&!s.group,l=this.intersect(Array.isArray(s.group)?s.group:[s.group],a);return i||l?s:void 0}));const r=new O({chars:{bottom:"","bottom-left":"","bottom-mid":"","bottom-right":"",left:" ","left-mid":"",mid:"","mid-mid":"",middle:" ",right:"","right-mid":"",top:"","top-left":"","top-mid":"","top-right":""},colWidths:[40,40],style:{"padding-left":2,"padding-right":1},wordWrap:!0});n.forEach(s=>r.push([this.getOptionNames(s,e.reverseNameOrder??!1,e.isArgument??!1),m(s.description)])),this.add(r.toString()),this.lines.push("")}getOptionNames(e,n,o){if(!e.name)throw new TypeError("Invalid option definition, name is required.");let a=e.type?e.type.name.toLowerCase():"string";const r=e.multiple||e.lazyMultiple?"[]":"";a=m(e.typeLabel??`{underline ${a}${r}}`);let s;if(e.alias)if(e.name){const i=o?e.name:`{yellow --${e.name}}`;s=m(n?`{bold ${i}}, {bold -${e.alias}} ${a}`:`{bold -${e.alias}}, {bold ${i}} ${a}`)}else n?s=m(`{bold -${e.alias}} ${a}`):s=m(`{bold -${e.alias}} ${a}`);else s=m(`{bold ${o?e.name:`{yellow --${e.name}}`}} ${a}`);return s}intersect(e,n){return e.some(o=>n.includes(o))}};var Te=Object.defineProperty,Ie=c((t,e)=>Te(t,"name",{value:e,configurable:!0}),"o$3");const Y=Ie(t=>(Array.isArray(t)?t:[t]).length===0?"":`
5
+ ${t.map(e=>e.optionList?new Pe(e).toString():new xe(e).toString()).join(`
6
+ `)}`,"commandLineUsage");var je=Object.defineProperty,N=c((t,e)=>je(t,"name",{value:e,configurable:!0}),"p$2");const V="__Other",k=N(t=>t.charAt(0).toUpperCase()+t.slice(1),"upperFirstChar"),Be=N((t,e,n,o)=>{t.debug("no command given, printing general help...");let a=[...new Set(n.values())].filter(s=>!s.hidden);o&&(a=a.filter(s=>s.group===o));const r=a.reduce((s,i)=>{const l=i.group??V;return s[l]||(s[l]=[]),s[l].push(i),s},{});t.raw(Y([{content:`{cyan ${e.getCliName()}} {green <command>} [positional arguments] {yellow [options]}`,header:"{inverse.cyan Usage }"},...Object.keys(r).map(s=>({content:r[s].map(i=>{let l="";return typeof i.alias=="string"?l=i.alias:Array.isArray(i.alias)&&(l=i.alias.join(", ")),l!==""&&(l=` [${l}]`),[`{green ${i.name}} ${l}`,i.description??""]}),header:s===V||o?`{inverse.green Available${o?` ${k(o)}`:""} Commands }`:` {inverse.green ${k(s)} }`})),n.has("help")?{header:"{inverse.yellow Command Options }",optionList:n.get("help").options?.filter(s=>!s.hidden)}:void 0,{header:"{inverse.yellow Global Options }",optionList:C},{content:`Run "{cyan ${e.getCliName()}} {green help <command>}" or "{cyan ${e.getCliName()}} {green <command>} {yellow --help}" for help with a specific command.`,raw:!0}].filter(Boolean)))},"printGeneralHelp"),Ve=N((t,e,n,o)=>{const a=n.get(o),r=[];if(r.push({content:`{cyan ${e.getCliName()}} {green ${a.name}}${a.argument?" [positional arguments]":""}${a.options?" [options]":""}`,header:"{inverse.cyan Usage }"}),a.description&&r.push({content:a.description,header:"{inverse.green Description }"}),a.argument&&r.push({header:"Command Positional Arguments",isArgument:!0,optionList:[a.argument]}),Array.isArray(a.options)&&a.options.length>0&&r.push({header:"{inverse.yellow Command Options }",optionList:a.options.filter(s=>!s.hidden)}),r.push({header:"{inverse.yellow Global Options }",optionList:C}),a.alias!==void 0&&a.alias.length>0){let s=a.alias;typeof a.alias=="string"&&(s=[a.alias]),r.splice(1,0,{content:s,header:"Alias(es)"})}Array.isArray(a.examples)&&a.examples.length>0&&r.push({content:a.examples,header:"Examples"}),t.raw(Y(r))},"printCommandHelp");class ke{static{c(this,"y")}static{N(this,"HelpCommand")}name="help";options=[{description:"Display only the specified group",name:"group",type:String}];commands;constructor(e){this.commands=e}execute(e){const{commandName:n,logger:o,options:a,runtime:r}=e,{footer:s,header:i}=r.getCommandSection();i&&o.raw(m(i)),n==="help"?Be(o,r,this.commands,a?.group):Ve(o,r,this.commands,n),s&&o.raw(m(s))}}var Ue=Object.defineProperty,De=c((t,e)=>Ue(t,"name",{value:e,configurable:!0}),"s$5");const qe={alias:["v","V"],description:"Output the version number",execute:De(({logger:t,runtime:e})=>{const n=e.getPackageVersion();n===void 0?(t.warn("Unknown version"),t.debug("The version number was not provided by the cli constructor.")):t.info(n)},"execute"),name:"version",options:[],usage:[]},U=16,Me=32,Fe=64,D=128,w="positionals";var Ge=Object.defineProperty,We=c((t,e)=>Ge(t,"name",{value:e,configurable:!0}),"m$4");let Ye=class{static{c(this,"c")}static{We(this,"EmptyToolbox")}result;argv;options;argument;command;commandName;runtime;logger;constructor(e,n){this.commandName=e,this.command=n}};var He=Object.defineProperty,Je=c((t,e)=>He(t,"name",{value:e,configurable:!0}),"s$4");const ze=Je(()=>{const t=process.env.CEREBRO_MIN_NODE_VERSION?Number(process.env.CEREBRO_MIN_NODE_VERSION):18,e=process.version.replace("v","");Number(/v([^.]+)/.exec(process.version)[1])<t&&(console.log(`cerebro supports a minimum Node version of ${t}. You have ${e}. Read our version support policy: https://github.com/visulima/visulima#supported-nodejs-versions`),process.exit(1))},"checkNodeVersion");var Ke=Object.defineProperty,Qe=c((t,e)=>Ke(t,"name",{value:e,configurable:!0}),"a$2");const Xe=/^-{1,2}(\w+)(=(\w+))?$/,H=Qe((t,e)=>{const n=Xe.exec(t);if(n==null)return{};const o=n[1],a=e.find(r=>r.name===o||r.alias===o);return a!==void 0?{argName:a.name,argValue:n[3],option:a}:{}},"getParameterOption");var Ze=Object.defineProperty,et=c((t,e)=>Ze(t,"name",{value:e,configurable:!0}),"e$4");const b=et(t=>t.type?.name==="Boolean","isBoolean");var tt=Object.defineProperty,R=c((t,e)=>tt(t,"name",{value:e,configurable:!0}),"n$2");const q=R((t,e)=>{if(e.type===void 0)return t;if(e.type.name==="Boolean"){if(t==="true"||t==="1")return e.type(!0);if(t==="false"||t==="0")return e.type(!1)}return e.type(t)},"convertType"),nt=new Set(["1","0","true","false"]),ot=R((t,e)=>{const n=R((o,a)=>{const{argName:r,argValue:s,option:i}=H(a,e),{lastOption:l}=o;return i&&b(i)&&s&&r?o.partial[r]=q(s,i):o.lastName&&l&&b(l)&&nt.has(a)&&(o.partial[o.lastName]=q(a,l)),{lastName:r,lastOption:i,partial:o.partial}},"getBooleanValue");return t.reduce(n,{partial:{}}).partial},"getBooleanValues");var at=Object.defineProperty,J=c((t,e)=>at(t,"name",{value:e,configurable:!0}),"p$1");const rt=J(t=>{let e=t.type?t.type.name.toLowerCase():"string";const n=t.multiple??t.lazyMultiple?"[]":"";return e&&(e=e==="boolean"?"":`{underline ${e}${n}}`),e},"getTypeLabel"),st=J(t=>(b(t)||(t.typeLabel=t.typeLabel??rt(t),t.defaultOption&&(t.typeLabel=`${t.typeLabel} (D)`),t.required&&(t.typeLabel=`${t.typeLabel} (R)`)),t),"mapOptionTypeLabel");var it=Object.defineProperty,M=c((t,e)=>it(t,"name",{value:e,configurable:!0}),"e$3");const lt=new Set(["1","0","true","false"]),ct=M((t,e)=>{const n=M((o,a)=>{const{argValue:r,option:s}=H(a,e),{lastOption:i}=o;if(i&&b(i)&&lt.has(a)){const l=[...o.args];return l.pop(),{args:l}}return s&&b(s)&&r?{args:o.args}:{args:[...o.args,a],lastOption:s}},"removeBooleanArguments");return t.reduce(n,{args:[]}).args},"removeBooleanValues");var pt=Object.defineProperty,z=c((t,e)=>pt(t,"name",{value:e,configurable:!0}),"e$2");const dt=new RegExp(/^-([^\d-])$/),mt=new RegExp(/^--(\S+)/),ut=new RegExp(/^-([^\d-]{2,})$/),gt=z(t=>dt.test(t)||mt.test(t)||ut.test(t),"isOption"),ht=z((t,e)=>{const n=e[0]&&gt(e[0])||e.length===0?null:e.shift()??null;if(!t.includes(n)){const o=new Error(`Command not recognised: ${n}`);throw o.command=n,o.name="INVALID_COMMAND",o}return{argv:e,command:n}},"commandLineCommands");var ft=Object.defineProperty,K=c((t,e)=>ft(t,"name",{value:e,configurable:!0}),"i$1");const vt=K((t,e)=>me.distance(t,e)<=t.length/3||e.includes(t),"isSimilar"),F=K((t,e)=>{const n=t.toLowerCase();return e.filter(o=>vt(o.toLowerCase(),n))},"findAlternatives");var yt=Object.defineProperty,bt=c((t,e)=>yt(t,"name",{value:e,configurable:!0}),"t$3");const $t=bt((t,e)=>t.filter(n=>n.required&&e[n.name]==null).filter(n=>n.type?.name==="Boolean"?(e[n.name]=!1,!1):!0),"listMissingArguments");var Et=Object.defineProperty,wt=c((t,e)=>Et(t,"name",{value:e,configurable:!0}),"o");const Ot=wt(t=>{const e=new Map;return t.forEach(n=>{e.set(n.name,{...e.get(n.name),...n})}),[...e.values()]},"mergeArguments");var Ct=Object.defineProperty,_=c((t,e)=>Ct(t,"name",{value:e,configurable:!0}),"e$1");const At=_(()=>!!process.versions.electron,"isElectronApp"),Nt=_(()=>At()&&!process.defaultApp,"isBundledElectronApp"),_t=_(()=>Nt()?0:1,"getProcessArgvBinIndex"),Lt=_(t=>t.slice(_t()+1),"hideBin");var xt=Object.defineProperty,Q=c((t,e)=>xt(t,"name",{value:e,configurable:!0}),"i");const Rt=" ",St=Q((t,e)=>t.length===e.length&&t.every((n,o)=>n===e[o]),"equals"),Pt=Q(t=>typeof t=="string"?t.split(Rt):St(t,process.argv)?Lt(t):t,"parseRawCommand");var Tt=Object.defineProperty,It=c((t,e)=>Tt(t,"name",{value:e,configurable:!0}),"t");const jt=It(t=>{process.on("uncaughtException",e=>{t.error(`Uncaught exception: ${e}`),e?.stack&&t.error(e.stack),process.exit(1)}),process.on("unhandledRejection",e=>{t.error(`Promise rejection: ${e}`),e?.stack&&t.error(e.stack),process.exit(1)})},"registerExceptionHandler");var Bt=Object.defineProperty,y=c((t,e)=>Bt(t,"name",{value:e,configurable:!0}),"c");const Vt="CI"in p.env&&("GITHUB_ACTIONS"in p.env||"GITLAB_CI"in p.env||"CIRCLECI"in p.env),kt=y(t=>t.charAt(0).toLowerCase()+t.slice(1),"lowerFirstChar");class Ut{static{c(this,"Cli")}static{y(this,"Cli")}logger;argv;cwd;cliName;packageVersion;packageName;extensions=[];commands;defaultCommand;updateNotifierOptions;commandSection;constructor(e,n={}){const{argv:o,cwd:a,packageName:r,packageVersion:s}={argv:p.argv,cwd:p.cwd(),...n};this.argv=Pt(o),this.argv.includes("--quiet")||this.argv.includes("-q")?p.env.CEREBRO_OUTPUT_LEVEL=String(U):this.argv.includes("--verbose")||this.argv.includes("-v")?p.env.CEREBRO_OUTPUT_LEVEL=String(Fe):this.argv.includes("--debug")||this.argv.includes("-vvv")||"DEBUG"in p.env?p.env.CEREBRO_OUTPUT_LEVEL=String(D):p.env.CEREBRO_OUTPUT_LEVEL=String(Me);const i={32:"informational",64:"trace",128:"debug"};this.logger=ie.createPail({logLevel:p.env.CEREBRO_OUTPUT_LEVEL?i[p.env.CEREBRO_OUTPUT_LEVEL]??"informational":"informational",...n.logger}),p.env.CEREBRO_OUTPUT_LEVEL===String(U)&&this.logger.disable(),ze(),jt(this.logger),this.cliName=e,this.packageVersion=s,this.packageName=r,this.cwd=a,this.defaultCommand="help",this.commandSection={header:`${this.cliName}${this.packageVersion?` v${this.packageVersion}`:""}`},this.commands=new Map,this.addCoreExtensions(),this.addCommand(qe),this.addCommand(new ke(this.commands))}setCommandSection(e){return this.commandSection=e,this}getCommandSection(){return this.commandSection}setDefaultCommand(e){return this.defaultCommand=e,this}addCommand(e){if(this.commands.has(e.name))throw new Error(`Ignored command with name "${e.name}, it was found in the command list."`);if(e.options?.map(n=>st(n)),this.validateDoubleOptions(e),this.addNegatableOption(e),e.options?.forEach(n=>{n.__camelCaseName__=we(n.name)}),this.commands.set(e.name,e),e.alias!==void 0){let n=e.alias;typeof e.alias=="string"&&(n=[e.alias]),n.forEach(o=>{if(this.logger.debug("adding alias",o),this.commands.has(o))throw new Error(`Ignoring command alias "${o}, command with the same name was found."`);this.commands.set(o,e)})}return this}addExtension(e){return this.extensions.push(e),this}enableUpdateNotifier(e={}){if(!this.packageName||!this.packageVersion)throw new Error("Cannot enable update notifier without package name and version.");const n=Object.keys(e);if(n.length>0&&!n.includes("alwaysRun")&&!n.includes("distTag")&&!n.includes("updateCheckInterval"))throw new Error("Invalid update notifier options, please check the documentation.");return this.updateNotifierOptions={alwaysRun:!1,debug:p.env.CEREBRO_OUTPUT_LEVEL===String(D),distTag:"latest",pkg:{name:this.packageName,version:this.packageVersion},updateCheckInterval:1e3*60*60*24,...e},this}getCliName(){return this.cliName}getPackageVersion(){return this.packageVersion}getPackageName(){return this.packageName}getCommands(){return this.commands}getCwd(){return this.cwd}async run(e={}){const{shouldExitProcess:n=!0,...o}=e,a=[...this.commands.keys()];let r;this.logger.debug(`process.execPath: ${p.execPath}`),this.logger.debug(`process.execArgv: ${p.execArgv.join(" ")}`),this.logger.debug(`process.argv: ${p.argv.join(" ")}`);try{r=ht([null,...a],this.argv)}catch(h){if(h.name==="INVALID_COMMAND"&&h.command){let P="";const T=F(h.command,[...this.commands.keys()]);T.length>0&&(P=` Did you mean: \r
7
+ - ${T.join(` \r
8
+ - `)}`),this.logger.error(`"${h.command}" is not an available command.${P}`)}else this.logger.error(h);return n?p.exit(1):void 0}const s=r.command??this.defaultCommand,i=this.commands.get(s);if(typeof i.execute!="function")return this.logger.error(`Command "${i.name}" has no function to execute.`),n?p.exit(1):void 0;const l=r.argv;this.logger.debug(`command '${s}' found, parsing command args: ${l.join(", ")}`);let d=Ot([...i.options??[],...C]);d.forEach(h=>{if(h.multiple&&h.lazyMultiple)throw new Error(`Argument "${h.name}" cannot have both multiple and lazyMultiple options, please choose one.`)}),i.argument&&(this.logger.debug("command has positional argument, parsing them..."),d=[{defaultOption:!0,description:i.argument?.description,group:"positionals",multiple:!0,name:w,type:i.argument?.type,typeLabel:i.argument?.typeLabel},...d]);const g=ue(d,{argv:ct(l,i.options??[]),camelCase:!0,partial:!0,stopAtFirstUnknown:!0}),$=ot(l,i.options??[]),f={...g,_all:{...g._all,...$}};this.validateCommandOptions(d,f,i);const u=new Ye(i.name,i);u.runtime=this,await this.registerExtensions(u),await this.updateNotifier(u);const{_all:L,positionals:X}=f;return L[w]&&delete L[w],u.argument=X?.[w]??[],u.argv=this.argv,u.options={...L,...o},this.mapNegatableOptions(u,i),this.mapImpliesOptions(u,i),this.validateCommandArgsForConflicts(d,u.options,i),this.logger.debug("command options parsed from options:"),this.logger.debug(JSON.stringify(u.options,null,2)),this.logger.debug("command argument parsed from argument:"),this.logger.debug(JSON.stringify(u.argument,null,2)),await this.prepareToolboxResult(f,u,i),n?p.exit(0):void 0}validateDoubleOptions(e){if(Array.isArray(e.options)){const n=e.options.reduce((r,s)=>{const i=`${s.name}-${s.alias}`;return r[i]||(r[i]=[]),r[i].push(s),r},{}),o=Object.values(n).filter(r=>r.length>1);let a="";if(o.forEach(r=>{const s=r[0],i=r[1];let l="alias";s.name===i.name&&(l="name",s.alias===i.alias&&(l+=" and alias")),a+=`Cannot add option ${l} "${JSON.stringify(i)}" to command "${e.name}" due to conflicting option ${JSON.stringify(s)}
9
+ `}),a.length>0)throw new Error(a)}}addCoreExtensions(){this.addExtension({execute:y(e=>{e.logger=this.logger},"execute"),name:"logger"})}async prepareToolboxResult(e,n,o){if(e.global?.help){this.logger.debug("'--help' option found, running 'help' for given command...");const a=this.commands.get("help");if(!a)throw new Error("Help command not found.");await a.execute(n);return}if(e.global?.version||e.global?.V){this.logger.debug("'--version' option found, running 'version' for given command...");const a=this.commands.get("version");if(!a)throw new Error("Version command not found.");await a.execute(n);return}await o.execute(n)}async updateNotifier({logger:e}){if(this.updateNotifierOptions&&this.updateNotifierOptions.alwaysRun||!(p.env.NO_UPDATE_NOTIFIER||p.env.NODE_ENV==="test"||this.argv.includes("--no-update-notifier")||Vt)&&this.updateNotifierOptions){e.raw("Checking for updates...");const n=await(await import("./chunks/has-new-version.cjs").then(o=>o.default))(this.updateNotifierOptions);if(n){const o="Update available "+v.dim(this.packageVersion+"")+v.reset(" → ")+v.green(n);this.logger.error(se.boxen(o,{borderColor:y(a=>v.yellow(a),"borderColor"),borderStyle:"round",margin:1,padding:1,textAlignment:"center"}))}}}validateCommandOptions(e,n,o){const a=$t(e,n);if(a.length>0)throw new Error(`You called the command "${o.name}" without the required options: ${a.map(r=>r.name).join(", ")}`);if(n._unknown&&n._unknown.length>0){const r=[];if(n._unknown.forEach(s=>{const i=s.startsWith("--");let l=`Found unknown ${i?"option":"argument"} "${s}"`;if(i){const d=F(s.replace("--",""),[...(o.options??[]).map(g=>g.name),...C.map(g=>g.name)]);if(d.length>0){const[g,...$]=d.map(f=>`--${f}`);l+=$.length>0?`, did you mean ${g} or ${$.join(", ")}?`:`, did you mean ${g}?`}}r.push(l)}),r.length>0)throw new Error(r.join(`
10
+ `))}}validateCommandArgsForConflicts(e,n,o){const a=e.filter(r=>r.conflicts!==void 0);if(a.length>0){const r=a.find(s=>Array.isArray(s.conflicts)?s.conflicts.some(i=>n[i]!==void 0):n[s.conflicts]!==void 0);if(r)throw new Error(`You called the command "${o.name}" with conflicting options: ${r.name} and ${typeof r.conflicts=="string"?r.conflicts:r.conflicts?.join(", ")}`)}}addNegatableOption(e){Array.isArray(e.options)&&e.options.forEach(n=>{if(n.name.startsWith("no-")&&!e.options.some(o=>o.name===n.name.replace("no-",""))){if(n.type!==Boolean){this.logger.debug(`Cannot add negated option "${n.name}" to command "${e.name}" because it is not a boolean.`);return}const o={...n,defaultValue:n.defaultValue===void 0?!0:!n.defaultValue,name:`${n.name.replace("no-","")}`};e.options.push(o)}})}async registerExtensions(e){const n=y(async o=>typeof o.execute!="function"?(this.logger.warn(`Skipped ${o.name} because execute is not a function.`),null):(await o.execute(e),null),"callback");for(const o of this.extensions)await n(o)}mapNegatableOptions(e,n){Object.entries(e.options).forEach(([o,a])=>{if(/^no\w+/.test(o)){const r=kt(o.replace("no",""));this.logger.debug(`mapping negated option "${o}" to "${r}"`),e.options[r]=!a,n.options?.forEach(s=>{s.name===r&&(s.__negated__=!0)})}})}mapImpliesOptions(e,n){Object.keys(e.options).forEach(o=>{const a=n.options?.find(r=>r.__camelCaseName__===o&&r.__negated__===void 0&&r.implies!==void 0);if(a?.implies){const r=a.implies;Object.entries(r).forEach(([s,i])=>{if(e.options[s]===void 0)e.options[s]=i;else{const l=n.options?.find(d=>d.name===s);(l?.defaultValue===void 0||e.options[s]===l.defaultValue)&&(e.options[s]=i)}})}})}}module.exports=Ut;
package/dist/index.d.cts CHANGED
@@ -99,13 +99,6 @@ interface Cli$1 {
99
99
  setDefaultCommand: (commandName: string) => this;
100
100
  }
101
101
 
102
- declare global {
103
- namespace Cerebro {
104
- interface ExtensionOverrides {
105
- }
106
- }
107
- }
108
-
109
102
  type CliOptions = {
110
103
  argv?: string[];
111
104
  cwd?: string;
@@ -0,0 +1,149 @@
1
+ import { OptionDefinition as OptionDefinition$1 } from 'command-line-args';
2
+ import { TableConstructorOptions } from 'cli-table3';
3
+ import { Pail, ConstructorOptions } from '@visulima/pail/server';
4
+
5
+ type UpdateNotifierOptions = {
6
+ alwaysRun?: boolean;
7
+ debug?: boolean;
8
+ distTag?: string;
9
+ pkg: {
10
+ name: string;
11
+ version: string;
12
+ };
13
+ registryUrl?: string;
14
+ shouldNotifyInNpmScript?: boolean;
15
+ updateCheckInterval?: number;
16
+ };
17
+
18
+ interface Content {
19
+ content?: string[] | string[][] | string | {
20
+ data: string[];
21
+ options: TableConstructorOptions;
22
+ };
23
+ header?: string;
24
+ raw?: boolean;
25
+ }
26
+
27
+ type Options = Record<string, any>;
28
+
29
+ interface Toolbox extends Cerebro.ExtensionOverrides {
30
+ argument: string[];
31
+ argv: Record<string, any>;
32
+ command: Command;
33
+ commandName: string;
34
+ logger: Pail<never, string>;
35
+ options: Options;
36
+ runtime: Cli$1;
37
+ }
38
+
39
+ type TypeConstructor<T> = (value: any) => T extends (infer R)[] ? R | undefined : T | undefined;
40
+ type MultiplePropertyOptions<T> = any[] extends T ? {
41
+ lazyMultiple: true;
42
+ } | {
43
+ multiple: true;
44
+ } : unknown;
45
+ type OptionDefinition<T> = MultiplePropertyOptions<T> & Omit<OptionDefinition$1, "type|defaultValue"> & {
46
+ conflicts?: string[] | string;
47
+ defaultValue?: T | undefined;
48
+ description?: string | undefined;
49
+ hidden?: boolean;
50
+ implies?: Record<string, any>;
51
+ required?: boolean;
52
+ type?: TypeConstructor<T> | undefined;
53
+ typeLabel?: string | undefined;
54
+ };
55
+ type ArgumentDefinition<T = any> = Omit<OptionDefinition<T>, "multiple|lazyMultiple|defaultOption|alias|group|defaultValue">;
56
+ interface Command<O = any, TContext extends Toolbox = Toolbox> {
57
+ alias?: string[] | string;
58
+ argument?: ArgumentDefinition;
59
+ commandPath?: string[];
60
+ description?: string;
61
+ examples?: string[] | string[][];
62
+ execute: ((toolbox: TContext) => Promise<void>) | ((toolbox: TContext) => void);
63
+ file?: string;
64
+ group?: string;
65
+ hidden?: boolean;
66
+ name: string;
67
+ options?: (OptionDefinition<boolean[]> | OptionDefinition<boolean> | OptionDefinition<number[]> | OptionDefinition<number> | OptionDefinition<O> | OptionDefinition<string[]> | OptionDefinition<string>)[];
68
+ usage?: Content[];
69
+ }
70
+
71
+ type ExtensionSetup = (toolbox: Toolbox) => Promise<void> | void;
72
+ interface Extension {
73
+ description?: string;
74
+ execute: ExtensionSetup;
75
+ file?: string;
76
+ name: string;
77
+ }
78
+
79
+ type CommandSection = {
80
+ footer?: string;
81
+ header?: string;
82
+ };
83
+ type CliRunOptions = {
84
+ [key: string]: any;
85
+ shouldExitProcess?: boolean;
86
+ };
87
+ interface Cli$1 {
88
+ addCommand: (command: Command) => this;
89
+ addExtension: (extension: Extension) => this;
90
+ enableUpdateNotifier: ({ alwaysRun, distTag, updateCheckInterval }: Partial<Omit<UpdateNotifierOptions, "debug | pkg">>) => this;
91
+ getCliName: () => string;
92
+ getCommandSection: () => CommandSection;
93
+ getCommands: () => Map<string, Command>;
94
+ getCwd: () => string;
95
+ getPackageName: () => string | undefined;
96
+ getPackageVersion: () => string | undefined;
97
+ run: (extraOptions: CliRunOptions) => Promise<void>;
98
+ setCommandSection: (commandSection: CommandSection) => this;
99
+ setDefaultCommand: (commandName: string) => this;
100
+ }
101
+
102
+ type CliOptions = {
103
+ argv?: string[];
104
+ cwd?: string;
105
+ logger?: ConstructorOptions<string, string>;
106
+ packageName?: string;
107
+ packageVersion?: string;
108
+ };
109
+ declare class Cli implements Cli$1 {
110
+ private readonly logger;
111
+ private readonly argv;
112
+ private readonly cwd;
113
+ private readonly cliName;
114
+ private readonly packageVersion;
115
+ private readonly packageName;
116
+ private readonly extensions;
117
+ private readonly commands;
118
+ private defaultCommand;
119
+ private updateNotifierOptions;
120
+ private commandSection;
121
+ constructor(cliName: string, options?: CliOptions);
122
+ setCommandSection(commandSection: CommandSection): this;
123
+ getCommandSection(): CommandSection;
124
+ setDefaultCommand(commandName: string): this;
125
+ addCommand<OT = any>(command: Command<OT>): this;
126
+ addExtension(extension: Extension): this;
127
+ enableUpdateNotifier(options?: Partial<Omit<UpdateNotifierOptions, "debug | pkg">>): this;
128
+ getCliName(): string;
129
+ getPackageVersion(): string | undefined;
130
+ getPackageName(): string | undefined;
131
+ getCommands(): Map<string, Command>;
132
+ getCwd(): string;
133
+ run(extraOptions?: CliRunOptions): Promise<void>;
134
+ private validateDoubleOptions;
135
+ private addCoreExtensions;
136
+ private prepareToolboxResult;
137
+ private updateNotifier;
138
+ private validateCommandOptions;
139
+ private validateCommandArgsForConflicts;
140
+ private addNegatableOption;
141
+ private registerExtensions;
142
+ private mapNegatableOptions;
143
+ private mapImpliesOptions;
144
+ }
145
+
146
+ type OutputType = 1 | 2 | 4;
147
+ type VERBOSITY_LEVEL = 16 | 32 | 64 | 128 | 256;
148
+
149
+ export { type ArgumentDefinition, type Cli$1 as Cli, type CliOptions, type Command, type Extension, type OptionDefinition, type OutputType, type Toolbox, type VERBOSITY_LEVEL, Cli as default };
package/dist/index.d.ts CHANGED
@@ -99,13 +99,6 @@ interface Cli$1 {
99
99
  setDefaultCommand: (commandName: string) => this;
100
100
  }
101
101
 
102
- declare global {
103
- namespace Cerebro {
104
- interface ExtensionOverrides {
105
- }
106
- }
107
- }
108
-
109
102
  type CliOptions = {
110
103
  argv?: string[];
111
104
  cwd?: string;
package/dist/index.mjs ADDED
@@ -0,0 +1,10 @@
1
+ var X=Object.defineProperty;var c=(t,e)=>X(t,"name",{value:e,configurable:!0});import{argv as P,cwd as Z,env as d,execPath as ee,execArgv as te,exit as L}from"node:process";import{boxen as oe}from"@visulima/boxen";import{bold as ne,dim as ae,reset as re,green as ie,yellow as se}from"@visulima/colorize";import{createPail as le}from"@visulima/pail/server";import ce from"command-line-args";import w from"cli-table3";import pe from"@visulima/colorize/template";import me from"node:os";import{distance as de}from"fastest-levenshtein";const ge=/[\p{Lu}]/u,ue=/[\p{Ll}]/u,T=/^[\p{Lu}](?![\p{Lu}])/gu,q=/([\p{Alpha}\p{N}_]|$)/u,x=/[_.\- ]+/,he=new RegExp("^"+x.source),I=new RegExp(x.source+q.source,"gu"),j=new RegExp("\\d+"+q.source,"gu"),fe=c((t,e,o,n)=>{let r=!1,a=!1,i=!1,s=!1;for(let l=0;l<t.length;l++){const p=t[l];s=l>2?t[l-3]==="-":!0,r&&ge.test(p)?(t=t.slice(0,l)+"-"+t.slice(l),r=!1,i=a,a=!0,l++):a&&i&&ue.test(p)&&(!s||n)?(t=t.slice(0,l-1)+"-"+t.slice(l-1),i=a,a=!1,r=!0):(r=e(p)===p&&o(p)!==p,i=a,a=o(p)===p&&e(p)!==p)}return t},"preserveCamelCase"),ve=c((t,e)=>(T.lastIndex=0,t.replaceAll(T,o=>e(o))),"preserveConsecutiveUppercase"),ye=c((t,e)=>(I.lastIndex=0,j.lastIndex=0,t.replaceAll(j,(o,n,r)=>["_","-"].includes(t.charAt(r+o.length))?o:e(o)).replaceAll(I,(o,n)=>e(n))),"postProcess");function be(t,e){if(!(typeof t=="string"||Array.isArray(t)))throw new TypeError("Expected the input to be `string | string[]`");if(e={pascalCase:!1,preserveConsecutiveUppercase:!1,...e},Array.isArray(t)?t=t.map(a=>a.trim()).filter(a=>a.length).join("-"):t=t.trim(),t.length===0)return"";const o=e.locale===!1?a=>a.toLowerCase():a=>a.toLocaleLowerCase(e.locale),n=e.locale===!1?a=>a.toUpperCase():a=>a.toLocaleUpperCase(e.locale);return t.length===1?x.test(t)?"":e.pascalCase?n(t):o(t):(t!==o(t)&&(t=fe(t,o,n,e.preserveConsecutiveUppercase)),t=t.replace(he,""),t=e.preserveConsecutiveUppercase?ve(t,o):o(t),e.pascalCase&&(t=n(t.charAt(0))+t.slice(1)),ye(t,n))}c(be,"camelCase");const O=[{description:"Turn on verbose output",group:"global",name:"verbose",type:Boolean},{description:"Turn on debugging output",group:"global",name:"debug",type:Boolean},{alias:"h",description:"Print out helpful usage information",group:"global",name:"help",type:Boolean},{alias:"q",description:"Silence output",group:"global",name:"quiet",type:Boolean},{alias:"V",description:"Print version info",group:"global",name:"version",type:Boolean},{description:"Turn off colored output",group:"global",name:"no-color",type:Boolean},{description:"Force colored output",group:"global",name:"color",type:Boolean}];var $e=Object.defineProperty,Ee=c((t,e)=>$e(t,"name",{value:e,configurable:!0}),"e$5");const m=Ee(t=>t?pe(Object.assign([],{raw:[t.replaceAll("`","\\`")]})):"","templateFormat");var we=Object.defineProperty,Oe=c((t,e)=>we(t,"name",{value:e,configurable:!0}),"t$6");let G=class{static{c(this,"n")}static{Oe(this,"BaseSection")}lines;constructor(){this.lines=[]}add(e){this.lines.push(e)}toString(){return this.lines.join(me.EOL)}header(e){this.add(ne(e)),this.lines.push("")}};var Ce=Object.defineProperty,Ae=c((t,e)=>Ce(t,"name",{value:e,configurable:!0}),"p$4");const $={chars:{bottom:"","bottom-left":"","bottom-mid":"","bottom-right":"",left:" ","left-mid":"",mid:"","mid-mid":"",middle:" ",right:"","right-mid":"",top:"","top-left":"","top-mid":"","top-right":""},colWidths:[40,60],style:{border:[],compact:!0,head:[],"padding-left":2,"padding-right":1},wordWrap:!0};let Ne=class extends G{static{c(this,"y")}static{Ae(this,"ContentSection")}constructor(e){if(super(),e.header&&this.header(m(e.header)),e.content){if(e.raw)if(Array.isArray(e.content)&&e.content.every(o=>typeof o=="string"))e.content.forEach(o=>{Array.isArray(o)?o.forEach(n=>this.add(m(n))):this.add(m(o))});else if(typeof e.content=="string")this.add(m(e.content));else throw new TypeError("Invalid raw content, must be a string or array of strings.");else this.add(this.getContentLines(e.content));this.add("")}}getContentLines(e){if(typeof e=="string"){const o=new w({...$,colWidths:[80]});return o.push([m(e)]),o.toString()}if(Array.isArray(e)&&e.every(o=>typeof o=="string"||Array.isArray(o)&&o.every(n=>typeof n=="string"))){const o=new w({...$});return e.forEach(n=>{Array.isArray(n)?o.push(n.map(r=>m(r))):o.push([m(n)])}),o.toString()}if(typeof e=="object"){const o=e;if(!o.options||!o.data)throw new Error(`Must have an "options" or "data" property
2
+ ${JSON.stringify(e)}`);const n=new w({...$,...o.options,style:{...$.style,...o.options.style}});return o.data.forEach(r=>{Array.isArray(r)?n.push(r.map(a=>m(a))):n.push([m(r)])}),n.toString()}throw new Error(`invalid input - 'content' must be a string, array of strings or a object:
3
+
4
+ ${JSON.stringify(e)}`)}};var Le=Object.defineProperty,_e=c((t,e)=>Le(t,"name",{value:e,configurable:!0}),"a$3");let xe=class extends G{static{c(this,"c")}static{_e(this,"OptionListSection")}constructor(e){super();let o=e.optionList??[];const n=Array.isArray(e.hide)?e.hide:[e.hide].filter(Boolean),r=Array.isArray(e.group)?e.group:[e.group].filter(Boolean);n.length>0&&(o=o.filter(i=>!n.includes(i.name))),e.header&&this.header(m(e.header)),r.length>0&&(o=o.filter(i=>{const s=r.includes("_none")&&!i.group,l=this.intersect(Array.isArray(i.group)?i.group:[i.group],r);return s||l?i:void 0}));const a=new w({chars:{bottom:"","bottom-left":"","bottom-mid":"","bottom-right":"",left:" ","left-mid":"",mid:"","mid-mid":"",middle:" ",right:"","right-mid":"",top:"","top-left":"","top-mid":"","top-right":""},colWidths:[40,40],style:{"padding-left":2,"padding-right":1},wordWrap:!0});o.forEach(i=>a.push([this.getOptionNames(i,e.reverseNameOrder??!1,e.isArgument??!1),m(i.description)])),this.add(a.toString()),this.lines.push("")}getOptionNames(e,o,n){if(!e.name)throw new TypeError("Invalid option definition, name is required.");let r=e.type?e.type.name.toLowerCase():"string";const a=e.multiple||e.lazyMultiple?"[]":"";r=m(e.typeLabel??`{underline ${r}${a}}`);let i;if(e.alias)if(e.name){const s=n?e.name:`{yellow --${e.name}}`;i=m(o?`{bold ${s}}, {bold -${e.alias}} ${r}`:`{bold -${e.alias}}, {bold ${s}} ${r}`)}else o?i=m(`{bold -${e.alias}} ${r}`):i=m(`{bold -${e.alias}} ${r}`);else i=m(`{bold ${n?e.name:`{yellow --${e.name}}`}} ${r}`);return i}intersect(e,o){return e.some(n=>o.includes(n))}};var Re=Object.defineProperty,Se=c((t,e)=>Re(t,"name",{value:e,configurable:!0}),"o$3");const W=Se(t=>(Array.isArray(t)?t:[t]).length===0?"":`
5
+ ${t.map(e=>e.optionList?new xe(e).toString():new Ne(e).toString()).join(`
6
+ `)}`,"commandLineUsage");var Pe=Object.defineProperty,C=c((t,e)=>Pe(t,"name",{value:e,configurable:!0}),"p$2");const V="__Other",B=C(t=>t.charAt(0).toUpperCase()+t.slice(1),"upperFirstChar"),Te=C((t,e,o,n)=>{t.debug("no command given, printing general help...");let r=[...new Set(o.values())].filter(i=>!i.hidden);n&&(r=r.filter(i=>i.group===n));const a=r.reduce((i,s)=>{const l=s.group??V;return i[l]||(i[l]=[]),i[l].push(s),i},{});t.raw(W([{content:`{cyan ${e.getCliName()}} {green <command>} [positional arguments] {yellow [options]}`,header:"{inverse.cyan Usage }"},...Object.keys(a).map(i=>({content:a[i].map(s=>{let l="";return typeof s.alias=="string"?l=s.alias:Array.isArray(s.alias)&&(l=s.alias.join(", ")),l!==""&&(l=` [${l}]`),[`{green ${s.name}} ${l}`,s.description??""]}),header:i===V||n?`{inverse.green Available${n?` ${B(n)}`:""} Commands }`:` {inverse.green ${B(i)} }`})),o.has("help")?{header:"{inverse.yellow Command Options }",optionList:o.get("help").options?.filter(i=>!i.hidden)}:void 0,{header:"{inverse.yellow Global Options }",optionList:O},{content:`Run "{cyan ${e.getCliName()}} {green help <command>}" or "{cyan ${e.getCliName()}} {green <command>} {yellow --help}" for help with a specific command.`,raw:!0}].filter(Boolean)))},"printGeneralHelp"),Ie=C((t,e,o,n)=>{const r=o.get(n),a=[];if(a.push({content:`{cyan ${e.getCliName()}} {green ${r.name}}${r.argument?" [positional arguments]":""}${r.options?" [options]":""}`,header:"{inverse.cyan Usage }"}),r.description&&a.push({content:r.description,header:"{inverse.green Description }"}),r.argument&&a.push({header:"Command Positional Arguments",isArgument:!0,optionList:[r.argument]}),Array.isArray(r.options)&&r.options.length>0&&a.push({header:"{inverse.yellow Command Options }",optionList:r.options.filter(i=>!i.hidden)}),a.push({header:"{inverse.yellow Global Options }",optionList:O}),r.alias!==void 0&&r.alias.length>0){let i=r.alias;typeof r.alias=="string"&&(i=[r.alias]),a.splice(1,0,{content:i,header:"Alias(es)"})}Array.isArray(r.examples)&&r.examples.length>0&&a.push({content:r.examples,header:"Examples"}),t.raw(W(a))},"printCommandHelp");class je{static{c(this,"y")}static{C(this,"HelpCommand")}name="help";options=[{description:"Display only the specified group",name:"group",type:String}];commands;constructor(e){this.commands=e}execute(e){const{commandName:o,logger:n,options:r,runtime:a}=e,{footer:i,header:s}=a.getCommandSection();s&&n.raw(m(s)),o==="help"?Te(n,a,this.commands,r?.group):Ie(n,a,this.commands,o),i&&n.raw(m(i))}}var Ve=Object.defineProperty,Be=c((t,e)=>Ve(t,"name",{value:e,configurable:!0}),"s$5");const ke={alias:["v","V"],description:"Output the version number",execute:Be(({logger:t,runtime:e})=>{const o=e.getPackageVersion();o===void 0?(t.warn("Unknown version"),t.debug("The version number was not provided by the cli constructor.")):t.info(o)},"execute"),name:"version",options:[],usage:[]},k=16,Ue=32,De=64,U=128,E="positionals";var Me=Object.defineProperty,Fe=c((t,e)=>Me(t,"name",{value:e,configurable:!0}),"m$4");let qe=class{static{c(this,"c")}static{Fe(this,"EmptyToolbox")}result;argv;options;argument;command;commandName;runtime;logger;constructor(e,o){this.commandName=e,this.command=o}};var Ge=Object.defineProperty,We=c((t,e)=>Ge(t,"name",{value:e,configurable:!0}),"s$4");const Ye=We(()=>{const t=process.env.CEREBRO_MIN_NODE_VERSION?Number(process.env.CEREBRO_MIN_NODE_VERSION):18,e=process.version.replace("v","");Number(/v([^.]+)/.exec(process.version)[1])<t&&(console.log(`cerebro supports a minimum Node version of ${t}. You have ${e}. Read our version support policy: https://github.com/visulima/visulima#supported-nodejs-versions`),process.exit(1))},"checkNodeVersion");var He=Object.defineProperty,Je=c((t,e)=>He(t,"name",{value:e,configurable:!0}),"a$2");const ze=/^-{1,2}(\w+)(=(\w+))?$/,Y=Je((t,e)=>{const o=ze.exec(t);if(o==null)return{};const n=o[1],r=e.find(a=>a.name===n||a.alias===n);return r!==void 0?{argName:r.name,argValue:o[3],option:r}:{}},"getParameterOption");var Ke=Object.defineProperty,Qe=c((t,e)=>Ke(t,"name",{value:e,configurable:!0}),"e$4");const y=Qe(t=>t.type?.name==="Boolean","isBoolean");var Xe=Object.defineProperty,_=c((t,e)=>Xe(t,"name",{value:e,configurable:!0}),"n$2");const D=_((t,e)=>{if(e.type===void 0)return t;if(e.type.name==="Boolean"){if(t==="true"||t==="1")return e.type(!0);if(t==="false"||t==="0")return e.type(!1)}return e.type(t)},"convertType"),Ze=new Set(["1","0","true","false"]),et=_((t,e)=>{const o=_((n,r)=>{const{argName:a,argValue:i,option:s}=Y(r,e),{lastOption:l}=n;return s&&y(s)&&i&&a?n.partial[a]=D(i,s):n.lastName&&l&&y(l)&&Ze.has(r)&&(n.partial[n.lastName]=D(r,l)),{lastName:a,lastOption:s,partial:n.partial}},"getBooleanValue");return t.reduce(o,{partial:{}}).partial},"getBooleanValues");var tt=Object.defineProperty,H=c((t,e)=>tt(t,"name",{value:e,configurable:!0}),"p$1");const ot=H(t=>{let e=t.type?t.type.name.toLowerCase():"string";const o=t.multiple??t.lazyMultiple?"[]":"";return e&&(e=e==="boolean"?"":`{underline ${e}${o}}`),e},"getTypeLabel"),nt=H(t=>(y(t)||(t.typeLabel=t.typeLabel??ot(t),t.defaultOption&&(t.typeLabel=`${t.typeLabel} (D)`),t.required&&(t.typeLabel=`${t.typeLabel} (R)`)),t),"mapOptionTypeLabel");var at=Object.defineProperty,M=c((t,e)=>at(t,"name",{value:e,configurable:!0}),"e$3");const rt=new Set(["1","0","true","false"]),it=M((t,e)=>{const o=M((n,r)=>{const{argValue:a,option:i}=Y(r,e),{lastOption:s}=n;if(s&&y(s)&&rt.has(r)){const l=[...n.args];return l.pop(),{args:l}}return i&&y(i)&&a?{args:n.args}:{args:[...n.args,r],lastOption:i}},"removeBooleanArguments");return t.reduce(o,{args:[]}).args},"removeBooleanValues");var st=Object.defineProperty,J=c((t,e)=>st(t,"name",{value:e,configurable:!0}),"e$2");const lt=new RegExp(/^-([^\d-])$/),ct=new RegExp(/^--(\S+)/),pt=new RegExp(/^-([^\d-]{2,})$/),mt=J(t=>lt.test(t)||ct.test(t)||pt.test(t),"isOption"),dt=J((t,e)=>{const o=e[0]&&mt(e[0])||e.length===0?null:e.shift()??null;if(!t.includes(o)){const n=new Error(`Command not recognised: ${o}`);throw n.command=o,n.name="INVALID_COMMAND",n}return{argv:e,command:o}},"commandLineCommands");var gt=Object.defineProperty,z=c((t,e)=>gt(t,"name",{value:e,configurable:!0}),"i$1");const ut=z((t,e)=>de(t,e)<=t.length/3||e.includes(t),"isSimilar"),F=z((t,e)=>{const o=t.toLowerCase();return e.filter(n=>ut(n.toLowerCase(),o))},"findAlternatives");var ht=Object.defineProperty,ft=c((t,e)=>ht(t,"name",{value:e,configurable:!0}),"t$3");const vt=ft((t,e)=>t.filter(o=>o.required&&e[o.name]==null).filter(o=>o.type?.name==="Boolean"?(e[o.name]=!1,!1):!0),"listMissingArguments");var yt=Object.defineProperty,bt=c((t,e)=>yt(t,"name",{value:e,configurable:!0}),"o");const $t=bt(t=>{const e=new Map;return t.forEach(o=>{e.set(o.name,{...e.get(o.name),...o})}),[...e.values()]},"mergeArguments");var Et=Object.defineProperty,A=c((t,e)=>Et(t,"name",{value:e,configurable:!0}),"e$1");const wt=A(()=>!!process.versions.electron,"isElectronApp"),Ot=A(()=>wt()&&!process.defaultApp,"isBundledElectronApp"),Ct=A(()=>Ot()?0:1,"getProcessArgvBinIndex"),At=A(t=>t.slice(Ct()+1),"hideBin");var Nt=Object.defineProperty,K=c((t,e)=>Nt(t,"name",{value:e,configurable:!0}),"i");const Lt=" ",_t=K((t,e)=>t.length===e.length&&t.every((o,n)=>o===e[n]),"equals"),xt=K(t=>typeof t=="string"?t.split(Lt):_t(t,process.argv)?At(t):t,"parseRawCommand");var Rt=Object.defineProperty,St=c((t,e)=>Rt(t,"name",{value:e,configurable:!0}),"t");const Pt=St(t=>{process.on("uncaughtException",e=>{t.error(`Uncaught exception: ${e}`),e?.stack&&t.error(e.stack),process.exit(1)}),process.on("unhandledRejection",e=>{t.error(`Promise rejection: ${e}`),e?.stack&&t.error(e.stack),process.exit(1)})},"registerExceptionHandler");var Tt=Object.defineProperty,v=c((t,e)=>Tt(t,"name",{value:e,configurable:!0}),"c");const It="CI"in d&&("GITHUB_ACTIONS"in d||"GITLAB_CI"in d||"CIRCLECI"in d),jt=v(t=>t.charAt(0).toLowerCase()+t.slice(1),"lowerFirstChar");class Kt{static{c(this,"Cli")}static{v(this,"Cli")}logger;argv;cwd;cliName;packageVersion;packageName;extensions=[];commands;defaultCommand;updateNotifierOptions;commandSection;constructor(e,o={}){const{argv:n,cwd:r,packageName:a,packageVersion:i}={argv:P,cwd:Z(),...o};this.argv=xt(n),this.argv.includes("--quiet")||this.argv.includes("-q")?d.CEREBRO_OUTPUT_LEVEL=String(k):this.argv.includes("--verbose")||this.argv.includes("-v")?d.CEREBRO_OUTPUT_LEVEL=String(De):this.argv.includes("--debug")||this.argv.includes("-vvv")||"DEBUG"in d?d.CEREBRO_OUTPUT_LEVEL=String(U):d.CEREBRO_OUTPUT_LEVEL=String(Ue);const s={32:"informational",64:"trace",128:"debug"};this.logger=le({logLevel:d.CEREBRO_OUTPUT_LEVEL?s[d.CEREBRO_OUTPUT_LEVEL]??"informational":"informational",...o.logger}),d.CEREBRO_OUTPUT_LEVEL===String(k)&&this.logger.disable(),Ye(),Pt(this.logger),this.cliName=e,this.packageVersion=i,this.packageName=a,this.cwd=r,this.defaultCommand="help",this.commandSection={header:`${this.cliName}${this.packageVersion?` v${this.packageVersion}`:""}`},this.commands=new Map,this.addCoreExtensions(),this.addCommand(ke),this.addCommand(new je(this.commands))}setCommandSection(e){return this.commandSection=e,this}getCommandSection(){return this.commandSection}setDefaultCommand(e){return this.defaultCommand=e,this}addCommand(e){if(this.commands.has(e.name))throw new Error(`Ignored command with name "${e.name}, it was found in the command list."`);if(e.options?.map(o=>nt(o)),this.validateDoubleOptions(e),this.addNegatableOption(e),e.options?.forEach(o=>{o.__camelCaseName__=be(o.name)}),this.commands.set(e.name,e),e.alias!==void 0){let o=e.alias;typeof e.alias=="string"&&(o=[e.alias]),o.forEach(n=>{if(this.logger.debug("adding alias",n),this.commands.has(n))throw new Error(`Ignoring command alias "${n}, command with the same name was found."`);this.commands.set(n,e)})}return this}addExtension(e){return this.extensions.push(e),this}enableUpdateNotifier(e={}){if(!this.packageName||!this.packageVersion)throw new Error("Cannot enable update notifier without package name and version.");const o=Object.keys(e);if(o.length>0&&!o.includes("alwaysRun")&&!o.includes("distTag")&&!o.includes("updateCheckInterval"))throw new Error("Invalid update notifier options, please check the documentation.");return this.updateNotifierOptions={alwaysRun:!1,debug:d.CEREBRO_OUTPUT_LEVEL===String(U),distTag:"latest",pkg:{name:this.packageName,version:this.packageVersion},updateCheckInterval:1e3*60*60*24,...e},this}getCliName(){return this.cliName}getPackageVersion(){return this.packageVersion}getPackageName(){return this.packageName}getCommands(){return this.commands}getCwd(){return this.cwd}async run(e={}){const{shouldExitProcess:o=!0,...n}=e,r=[...this.commands.keys()];let a;this.logger.debug(`process.execPath: ${ee}`),this.logger.debug(`process.execArgv: ${te.join(" ")}`),this.logger.debug(`process.argv: ${P.join(" ")}`);try{a=dt([null,...r],this.argv)}catch(h){if(h.name==="INVALID_COMMAND"&&h.command){let R="";const S=F(h.command,[...this.commands.keys()]);S.length>0&&(R=` Did you mean: \r
7
+ - ${S.join(` \r
8
+ - `)}`),this.logger.error(`"${h.command}" is not an available command.${R}`)}else this.logger.error(h);return o?L(1):void 0}const i=a.command??this.defaultCommand,s=this.commands.get(i);if(typeof s.execute!="function")return this.logger.error(`Command "${s.name}" has no function to execute.`),o?L(1):void 0;const l=a.argv;this.logger.debug(`command '${i}' found, parsing command args: ${l.join(", ")}`);let p=$t([...s.options??[],...O]);p.forEach(h=>{if(h.multiple&&h.lazyMultiple)throw new Error(`Argument "${h.name}" cannot have both multiple and lazyMultiple options, please choose one.`)}),s.argument&&(this.logger.debug("command has positional argument, parsing them..."),p=[{defaultOption:!0,description:s.argument?.description,group:"positionals",multiple:!0,name:E,type:s.argument?.type,typeLabel:s.argument?.typeLabel},...p]);const u=ce(p,{argv:it(l,s.options??[]),camelCase:!0,partial:!0,stopAtFirstUnknown:!0}),b=et(l,s.options??[]),f={...u,_all:{...u._all,...b}};this.validateCommandOptions(p,f,s);const g=new qe(s.name,s);g.runtime=this,await this.registerExtensions(g),await this.updateNotifier(g);const{_all:N,positionals:Q}=f;return N[E]&&delete N[E],g.argument=Q?.[E]??[],g.argv=this.argv,g.options={...N,...n},this.mapNegatableOptions(g,s),this.mapImpliesOptions(g,s),this.validateCommandArgsForConflicts(p,g.options,s),this.logger.debug("command options parsed from options:"),this.logger.debug(JSON.stringify(g.options,null,2)),this.logger.debug("command argument parsed from argument:"),this.logger.debug(JSON.stringify(g.argument,null,2)),await this.prepareToolboxResult(f,g,s),o?L(0):void 0}validateDoubleOptions(e){if(Array.isArray(e.options)){const o=e.options.reduce((a,i)=>{const s=`${i.name}-${i.alias}`;return a[s]||(a[s]=[]),a[s].push(i),a},{}),n=Object.values(o).filter(a=>a.length>1);let r="";if(n.forEach(a=>{const i=a[0],s=a[1];let l="alias";i.name===s.name&&(l="name",i.alias===s.alias&&(l+=" and alias")),r+=`Cannot add option ${l} "${JSON.stringify(s)}" to command "${e.name}" due to conflicting option ${JSON.stringify(i)}
9
+ `}),r.length>0)throw new Error(r)}}addCoreExtensions(){this.addExtension({execute:v(e=>{e.logger=this.logger},"execute"),name:"logger"})}async prepareToolboxResult(e,o,n){if(e.global?.help){this.logger.debug("'--help' option found, running 'help' for given command...");const r=this.commands.get("help");if(!r)throw new Error("Help command not found.");await r.execute(o);return}if(e.global?.version||e.global?.V){this.logger.debug("'--version' option found, running 'version' for given command...");const r=this.commands.get("version");if(!r)throw new Error("Version command not found.");await r.execute(o);return}await n.execute(o)}async updateNotifier({logger:e}){if(this.updateNotifierOptions&&this.updateNotifierOptions.alwaysRun||!(d.NO_UPDATE_NOTIFIER||d.NODE_ENV==="test"||this.argv.includes("--no-update-notifier")||It)&&this.updateNotifierOptions){e.raw("Checking for updates...");const o=await(await import("./chunks/has-new-version.mjs").then(n=>n.default))(this.updateNotifierOptions);if(o){const n="Update available "+ae(this.packageVersion+"")+re(" → ")+ie(o);this.logger.error(oe(n,{borderColor:v(r=>se(r),"borderColor"),borderStyle:"round",margin:1,padding:1,textAlignment:"center"}))}}}validateCommandOptions(e,o,n){const r=vt(e,o);if(r.length>0)throw new Error(`You called the command "${n.name}" without the required options: ${r.map(a=>a.name).join(", ")}`);if(o._unknown&&o._unknown.length>0){const a=[];if(o._unknown.forEach(i=>{const s=i.startsWith("--");let l=`Found unknown ${s?"option":"argument"} "${i}"`;if(s){const p=F(i.replace("--",""),[...(n.options??[]).map(u=>u.name),...O.map(u=>u.name)]);if(p.length>0){const[u,...b]=p.map(f=>`--${f}`);l+=b.length>0?`, did you mean ${u} or ${b.join(", ")}?`:`, did you mean ${u}?`}}a.push(l)}),a.length>0)throw new Error(a.join(`
10
+ `))}}validateCommandArgsForConflicts(e,o,n){const r=e.filter(a=>a.conflicts!==void 0);if(r.length>0){const a=r.find(i=>Array.isArray(i.conflicts)?i.conflicts.some(s=>o[s]!==void 0):o[i.conflicts]!==void 0);if(a)throw new Error(`You called the command "${n.name}" with conflicting options: ${a.name} and ${typeof a.conflicts=="string"?a.conflicts:a.conflicts?.join(", ")}`)}}addNegatableOption(e){Array.isArray(e.options)&&e.options.forEach(o=>{if(o.name.startsWith("no-")&&!e.options.some(n=>n.name===o.name.replace("no-",""))){if(o.type!==Boolean){this.logger.debug(`Cannot add negated option "${o.name}" to command "${e.name}" because it is not a boolean.`);return}const n={...o,defaultValue:o.defaultValue===void 0?!0:!o.defaultValue,name:`${o.name.replace("no-","")}`};e.options.push(n)}})}async registerExtensions(e){const o=v(async n=>typeof n.execute!="function"?(this.logger.warn(`Skipped ${n.name} because execute is not a function.`),null):(await n.execute(e),null),"callback");for(const n of this.extensions)await o(n)}mapNegatableOptions(e,o){Object.entries(e.options).forEach(([n,r])=>{if(/^no\w+/.test(n)){const a=jt(n.replace("no",""));this.logger.debug(`mapping negated option "${n}" to "${a}"`),e.options[a]=!r,o.options?.forEach(i=>{i.name===a&&(i.__negated__=!0)})}})}mapImpliesOptions(e,o){Object.keys(e.options).forEach(n=>{const r=o.options?.find(a=>a.__camelCaseName__===n&&a.__negated__===void 0&&a.implies!==void 0);if(r?.implies){const a=r.implies;Object.entries(a).forEach(([i,s])=>{if(e.options[i]===void 0)e.options[i]=s;else{const l=o.options?.find(p=>p.name===i);(l?.defaultValue===void 0||e.options[i]===l.defaultValue)&&(e.options[i]=s)}})}})}}export{Kt as default};