bob-core 2.0.0-beta.13 → 2.0.0-beta.15

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/dist/cjs/index.js CHANGED
@@ -1,21 +1,17 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const w=require("prompts"),ie=require("minimist"),se=require("node:fs"),V=require("path"),oe=require("string-similarity");function Q(r){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(r){for(const t in r)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(r,t);Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:()=>r[t]})}}return e.default=r,Object.freeze(e)}const ae=Q(se),le=Q(oe);class I{logger;constructor(e){this.logger=e}log(...e){this.logger.log(...e)}info(...e){this.logger.info(...e)}warn(...e){this.logger.warn(...e)}error(...e){this.logger.error(...e)}debug(...e){this.logger.debug(...e)}async askForConfirmation(e="Do you want to continue?",t){return(await w({type:"confirm",name:"value",message:e,initial:t??!1})).value}async askForInput(e,t,n){return(await w({type:"text",name:"value",message:e,initial:t,...n}))?.value??null}async askForDate(e,t,n){return(await w({type:"date",name:"value",message:e,initial:t,...n}))?.value??null}async askForList(e,t,n){return(await w({type:"list",name:"value",message:e,initial:t,...n}))?.value??null}async askForToggle(e,t,n){return(await w({type:"toggle",name:"value",message:e,initial:t,...n}))?.value??null}async askForSelect(e,t,n){if(t.length===0)throw new Error("No options provided");const i=[];for(const o of t)typeof o=="string"?i.push({title:o,value:o}):i.push(o);return(await w({type:"select",name:"value",message:e,choices:i,...n}))?.value??null}newLoader(e="",t=["⠙","⠘","⠰","⠴","⠤","⠦","⠆","⠃","⠋","⠉"],n=100){let i=e,s=null,o=0;const u=setInterval(function(){s&&(process.stdout.write(new TextEncoder().encode("\r"+" ".repeat(s.length+5)+"\r")),s=null),process.stdout.write(new TextEncoder().encode("\r"+t[o++]+" "+i)),o=o%t.length},n),m=()=>{clearInterval(u),process.stdout.write(new TextEncoder().encode("\r"+" ".repeat(i.length+5)+"\r"))};return{[Symbol.dispose]:m,[Symbol.asyncDispose]:m,updateText:h=>{s=i,i=h},stop:m}}}const k=10,D=(r=0)=>e=>`\x1B[${e+r}m`,H=(r=0)=>e=>`\x1B[${38+r};5;${e}m`,W=(r=0)=>(e,t,n)=>`\x1B[${38+r};2;${e};${t};${n}m`,c={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(c.modifier);const ue=Object.keys(c.color),me=Object.keys(c.bgColor);[...ue,...me];function de(){const r=new Map;for(const[e,t]of Object.entries(c)){for(const[n,i]of Object.entries(t))c[n]={open:`\x1B[${i[0]}m`,close:`\x1B[${i[1]}m`},t[n]=c[n],r.set(i[0],i[1]);Object.defineProperty(c,e,{value:t,enumerable:!1})}return Object.defineProperty(c,"codes",{value:r,enumerable:!1}),c.color.close="\x1B[39m",c.bgColor.close="\x1B[49m",c.color.ansi=D(),c.color.ansi256=H(),c.color.ansi16m=W(),c.bgColor.ansi=D(k),c.bgColor.ansi256=H(k),c.bgColor.ansi16m=W(k),Object.defineProperties(c,{rgbToAnsi256:{value(e,t,n){return e===t&&t===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(n/255*5)},enumerable:!1},hexToRgb:{value(e){const t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[n]=t;n.length===3&&(n=[...n].map(s=>s+s).join(""));const i=Number.parseInt(n,16);return[i>>16&255,i>>8&255,i&255]},enumerable:!1},hexToAnsi256:{value:e=>c.rgbToAnsi256(...c.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let t,n,i;if(e>=232)t=((e-232)*10+8)/255,n=t,i=t;else{e-=16;const u=e%36;t=Math.floor(e/36)/5,n=Math.floor(u/6)/5,i=u%6/5}const s=Math.max(t,n,i)*2;if(s===0)return 30;let o=30+(Math.round(i)<<2|Math.round(n)<<1|Math.round(t));return s===2&&(o+=60),o},enumerable:!1},rgbToAnsi:{value:(e,t,n)=>c.ansi256ToAnsi(c.rgbToAnsi256(e,t,n)),enumerable:!1},hexToAnsi:{value:e=>c.ansi256ToAnsi(c.hexToAnsi256(e)),enumerable:!1}}),c}const f=de(),_=(()=>{if(!("navigator"in globalThis))return 0;if(globalThis.navigator.userAgentData){const r=navigator.userAgentData.brands.find(({brand:e})=>e==="Chromium");if(r&&r.version>93)return 3}return/\b(Chrome|Chromium)\//.test(globalThis.navigator.userAgent)?1:0})(),G=_!==0&&{level:_},ce={stdout:G,stderr:G};function he(r,e,t){let n=r.indexOf(e);if(n===-1)return r;const i=e.length;let s=0,o="";do o+=r.slice(s,n)+e+t,s=n+i,n=r.indexOf(e,s);while(n!==-1);return o+=r.slice(s),o}function pe(r,e,t,n){let i=0,s="";do{const o=r[n-1]==="\r";s+=r.slice(i,o?n-1:n)+e+(o?`\r
2
- `:`
3
- `)+t,i=n+1,n=r.indexOf(`
4
- `,i)}while(n!==-1);return s+=r.slice(i),s}const{stdout:U,stderr:Y}=ce,P=Symbol("GENERATOR"),v=Symbol("STYLER"),A=Symbol("IS_EMPTY"),z=["ansi","ansi","ansi256","ansi16m"],C=Object.create(null),ge=(r,e={})=>{if(e.level&&!(Number.isInteger(e.level)&&e.level>=0&&e.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");const t=U?U.level:0;r.level=e.level===void 0?t:e.level},fe=r=>{const e=(...t)=>t.join(" ");return ge(e,r),Object.setPrototypeOf(e,x.prototype),e};function x(r){return fe(r)}Object.setPrototypeOf(x.prototype,Function.prototype);for(const[r,e]of Object.entries(f))C[r]={get(){const t=S(this,B(e.open,e.close,this[v]),this[A]);return Object.defineProperty(this,r,{value:t}),t}};C.visible={get(){const r=S(this,this[v],!0);return Object.defineProperty(this,"visible",{value:r}),r}};const T=(r,e,t,...n)=>r==="rgb"?e==="ansi16m"?f[t].ansi16m(...n):e==="ansi256"?f[t].ansi256(f.rgbToAnsi256(...n)):f[t].ansi(f.rgbToAnsi(...n)):r==="hex"?T("rgb",e,t,...f.hexToRgb(...n)):f[t][r](...n),ye=["rgb","hex","ansi256"];for(const r of ye){C[r]={get(){const{level:t}=this;return function(...n){const i=B(T(r,z[t],"color",...n),f.color.close,this[v]);return S(this,i,this[A])}}};const e="bg"+r[0].toUpperCase()+r.slice(1);C[e]={get(){const{level:t}=this;return function(...n){const i=B(T(r,z[t],"bgColor",...n),f.bgColor.close,this[v]);return S(this,i,this[A])}}}}const be=Object.defineProperties(()=>{},{...C,level:{enumerable:!0,get(){return this[P].level},set(r){this[P].level=r}}}),B=(r,e,t)=>{let n,i;return t===void 0?(n=r,i=e):(n=t.openAll+r,i=e+t.closeAll),{open:r,close:e,openAll:n,closeAll:i,parent:t}},S=(r,e,t)=>{const n=(...i)=>we(n,i.length===1?""+i[0]:i.join(" "));return Object.setPrototypeOf(n,be),n[P]=r,n[v]=e,n[A]=t,n},we=(r,e)=>{if(r.level<=0||!e)return r[A]?"":e;let t=r[v];if(t===void 0)return e;const{openAll:n,closeAll:i}=t;if(e.includes("\x1B"))for(;t!==void 0;)e=he(e,t.close,t.open),t=t.parent;const s=e.indexOf(`
5
- `);return s!==-1&&(e=pe(e,i,n,s)),n+e+i};Object.defineProperties(x.prototype,C);const a=x();x({level:Y?Y.level:0});class b extends Error{}function J(r){if(r==="string"||r==="number")return null;if(r==="boolean")return!1;if(Array.isArray(r)&&r.length===1){if(r[0]==="string")return[];if(r[0]==="number")return[]}throw new Error("Invalid option type: "+r)}function K(r){return typeof r=="string"||Array.isArray(r)?J(r):r.default!==void 0?r.default:J(r.type)}function y(r){return typeof r=="string"||Array.isArray(r)?{alias:[],default:K(r),description:"",required:!1,secret:!1,type:r,variadic:!1}:{alias:r.alias?Array.isArray(r.alias)?r.alias:[r.alias]:[],default:r.default??K(r.type),description:r.description??"",required:r.required??!1,secret:r.secret??!1,type:r.type,variadic:r.variadic??!1}}class E extends b{constructor(e,t={}){super(`Invalid option ${e} in not recognized`),this.option=e,this.optionsSchema=t}pretty(e){const t=Object.entries(this.optionsSchema);if(t.length>0){e.log(`
6
- ${a.yellow("Available options")}:`);for(const[n,i]of t){const s=y(i),o=typeof s.alias=="string"?[s.alias]:s.alias,u=Array.isArray(s.type)?`[${s.type[0]}]`:s.type,m=`--${n}${o.length>0?o.map(l=>`, -${l}`).join(""):""}`,h=" ".repeat(30-m.length);e.log(` ${a.green(m)} ${h} ${s.description||"\b"} ${a.white(`(${u})`)}`)}e.log("")}e.log(`${a.white.bgRed(" ERROR ")} Option ${a.bold.yellow(this.option)} is not recognized.`)}}class N extends b{constructor(e){super(`Argument "${e}" is required.`),this.argument=e}pretty(e){e.log(`${a.white.bgRed(" ERROR ")} Argument ${a.bold.yellow(this.argument)} is required.`)}}class X extends b{constructor(e){super(`Argument "${e}" is required.`),this.option=e}pretty(e){e.log(`${a.white.bgRed(" ERROR ")} Option ${a.bold.yellow(this.option)} is required.`)}}class ve extends b{constructor(e){let t=`Argument "${e.param}" value is invalid.`;e.reason?t+=` Reason: ${e.reason}`:t+=` Value: "${e.value}"`,super(t),this.param=e}pretty(e){e.log(` ${a.white.bgRed(" ERROR ")} Argument ${a.bold.yellow(this.param.param)} value is invalid. `),(this.param.value||this.param.reason)&&e.log(""),this.param.value&&e.log(` ${a.blue("Value")}: ${this.param.value}`),this.param.reason&&e.log(` ${a.yellow("Reason")}: ${this.param.reason}`)}}class F extends b{constructor(e){let t=`Option "${e.option}" value is invalid.`;e.reason?t+=` Reason: ${e.reason}`:t+=` Value: "${e.value}"`,super(t),this.param=e}pretty(e){e.log(` ${a.white.bgRed(" ERROR ")} Option ${a.bold.yellow(this.param.option)} value is invalid. `),(this.param.value||this.param.reason)&&e.log(""),this.param.value&&e.log(` ${a.blue("Value")}: ${this.param.value}`),this.param.reason&&e.log(` ${a.yellow("Reason")}: ${this.param.reason}`)}}class Z extends b{constructor(e){super(`Command "${e}" not found.`),this.command=e}pretty(e){e.log(`${a.bgRed(" ERROR ")} Command ${a.yellow(this.command)} not found.`)}}function O(r,e,t,n){if(r==null)return n??null;if(e==="string")return String(r);if(e==="number"){const i=Number(r);if(isNaN(i))throw new F({option:t,reason:`Expected a number, got "${r}"`});return i}if(e==="boolean")return typeof r=="boolean"?r:r==="true"||r==="1"?!0:r==="false"||r==="0"?!1:!!r;if(Array.isArray(e)){const i=e[0],s=Array.isArray(r)?r:[r];if(i==="string")return s.map(o=>String(o));if(i==="number")return s.map(o=>{const u=Number(o);if(isNaN(u))throw new F({option:t,reason:`Expected array of numbers, got "${o}" in array`});return u})}return r}class M{options;parsedOptions=null;arguments;parsedArguments=null;io;shouldPromptForMissingOptions=!0;constructor(e){this.options=e.options,this.arguments=e.arguments,this.io=e.io}init(e){const{_:t,...n}=ie(e);return this.validateUnknownOptions(n),this.parsedOptions=this.handleOptions(n),this.parsedArguments=this.handleArguments(t),{options:this.parsedOptions,arguments:this.parsedArguments}}async validate(){for(const e in this.options)if(y(this.options[e]).required&&(this.parsedOptions?.[e]===void 0||this.parsedOptions?.[e]===null))throw new X(e);for(const e in this.arguments){const t=y(this.arguments[e]),n=this.parsedArguments?.[e];if(t.required&&n==null){if(this.shouldPromptForMissingOptions){const i=await this.promptForArgument(e,t);if(i&&this.parsedArguments){this.parsedArguments[e]=O(i,t.type,e);continue}}throw new N(e)}if(t.required&&t.variadic&&Array.isArray(n)&&n.length===0){if(this.shouldPromptForMissingOptions){const i=await this.promptForArgument(e,t);if(i&&this.parsedArguments){this.parsedArguments[e]=O(i,t.type,e);continue}}throw new N(e)}}}option(e,t){if(!this.parsedOptions)throw new Error("Options have not been parsed yet. Call init() first.");return this.isEmptyValue(this.parsedOptions[e])&&t!==void 0?t:this.parsedOptions[e]}setOption(e,t){if(!this.parsedOptions)throw new Error("Options have not been parsed yet. Call init() first.");if(!(e in this.options))throw new E(e,this.options);this.parsedOptions[e]=t}argument(e,t){if(!this.parsedArguments)throw new Error("Arguments have not been parsed yet. Call init() first.");return this.isEmptyValue(this.parsedArguments[e])&&t!==void 0?t:this.parsedArguments[e]}setArgument(e,t){if(!this.parsedArguments)throw new Error("Arguments have not been parsed yet. Call init() first.");if(!(e in this.arguments))throw new E(e,this.arguments);this.parsedArguments[e]=t}isEmptyValue(e){return e==null||Array.isArray(e)&&e.length===0}validateUnknownOptions(e){const t=new Set;for(const n in this.options){t.add(n);const i=y(this.options[n]);for(const s of i.alias)t.add(s)}for(const n in e)if(!t.has(n))throw new E(n,this.options)}handleOptions(e){const t={};for(const n in this.options){const i=y(this.options[n]);t[n]=this.resolveOptionValue(n,i,e)}return t}handleArguments(e){const t={},n=[...e];for(const i in this.arguments){const s=y(this.arguments[i]);if(s.variadic){t[i]=this.handleVariadicArgument(i,s,n);continue}t[i]=this.resolveArgumentValue(i,s,n.shift())}return t}handleVariadicArgument(e,t,n){return n.length?O(n,t.type,e,t.default):t.default}resolveArgumentValue(e,t,n){return n===void 0?t.default:O(n,t.type,e,t.default)}resolveOptionValue(e,t,n){let i;const s=[e,...t.alias];for(const o of s)if(o in n){i=n[o];break}if(i===void 0){if(t.required)throw new F({option:e,reason:"Required option is missing"});return t.default}return O(i,t.type,e,t.default)}optionDefinitions(){const e={};for(const t in this.options)e[t]=y(this.options[t]);return e}argumentDefinitions(){const e={};for(const t in this.arguments)e[t]=y(this.arguments[t]);return e}availableOptions(){return Object.keys(this.options)}availableArguments(){return Object.keys(this.arguments)}disablePrompting(){return this.shouldPromptForMissingOptions=!1,this}async promptForArgument(e,t){if(!Array.isArray(t.type)&&!["string","number","secret"].includes(t.type))return null;let n=`${a.yellow.bold(e)} is required`;return t.description&&(n+=`: ${a.gray(`(${t.description})`)}`),n+=` ${a.green(`(${t.type}${t.variadic==!0?"[]":""})`)}
7
- `,Array.isArray(t.type)?(n+=`Please provide one or more values, separated by commas:
8
- `,await this.io.askForList(n,void 0,{separator:",",validate:i=>{if(!i.length)return"Please enter at least one value";if(t.type[0]==="number"){for(const s of i.split(","))if(isNaN(Number(s)))return"Please enter only valid numbers"}return!0}})):await this.io.askForInput(n,void 0,{type:t.type==="number"?"number":t.secret?"password":"text",validate:i=>{if(i==null||typeof i=="string"&&!i.length)return"This value is required";if(t.type==="number"){const s=Number(i);if(isNaN(s))return"Please enter a valid number"}else if(t.type==="string"&&(typeof i!="string"||!i.length))return"Please enter a valid text";return!0}})}}function j(r){return new Array(r+5).join(" ")}class ee{type="boolean";option="help";alias=["h"];default=!1;description=`Display help for the given command. When no command is given display help for the ${a.green("list")} command`;async handler(){const e=this.parser.argumentDefinitions(),t=this.parser.optionDefinitions(),n=Object.entries(e),i=Object.entries(t),s=i.map(([l,d])=>{const p=Array.isArray(d.alias)?d.alias:d.alias?[d.alias]:[];return{name:l,...d,optionWithAlias:`--${l}${p.map(g=>`, -${g}`).join("")}`}}),o=n.filter(([,l])=>l.required);this.io.log(a.yellow("Description:")),this.io.log(` ${this.description}
9
- `),this.io.log(a.yellow("Usage:")),this.io.log(` ${this.command} ${o.length>0?o.map(([l])=>`<${l}>`).join(" "):"\b"} [options]`);const u=Math.max(...s.map(l=>l.optionWithAlias.length),0),m=Math.max(...n.map(([l])=>l.length),0),h=m>u?m:u;if(n.length>0){this.io.log(`
10
- ${a.yellow("Arguments")}:`);for(const[l,d]of n){const p=j(h-l.length);let g=` ${a.green(l)} ${p} ${d.description??"\b"}`;if(d.default!==void 0&&!d.required){const re=(Array.isArray(d.type)?`[${d.type[0]}]`:d.type)==="array"||Array.isArray(d.type)?JSON.stringify(d.default):d.default;g+=` ${a.yellow(`[default: ${re}]`)}`}d.variadic&&(g+=` ${a.white("(variadic)")}`),this.io.log(g)}}if(i.length>0){this.io.log(`
11
- ${a.yellow("Options")}:`);for(const l of s){const d=j(h-l.optionWithAlias.length);let p=`${a.green(l.optionWithAlias)} ${d} ${l.description??"\b"}`;if(l.type){const g=Array.isArray(l.type)?`[${l.type[0]}]`:l.type;p+=` ${a.white(`(${g})`)}`}if(l.default!==void 0&&!l.required){const L=(Array.isArray(l.type)?`[${l.type[0]}]`:l.type)==="array"||Array.isArray(l.type)?JSON.stringify(l.default):l.default;p+=` ${a.yellow(`[default: ${L}]`)}`}this.io.log(p)}}if(this.commandsExamples.length>0){this.io.log(`
12
- ${a.yellow("Examples")}:`);let l=process.argv[0].split("/").pop();l==="node"&&(l+=" "+process.argv[1].split("/").pop());for(const[d,p]of this.commandsExamples.entries())d>0&&this.io.log(""),this.io.log(` ${p.description}
13
- `),this.io.log(` ${a.green(`${l} ${p.command}`)}`)}return-1}}class ${_command;description;group;commandsExamples=[];get command(){return this._command}ctx;io;logger;parser;disablePromptingFlag=!1;_preHandler;_handler;tmp;defaultOptions(){return[new ee]}newCommandParser(e){return new M({io:e.io,options:e.options,arguments:e.arguments})}newCommandIO(e){return new I(e.logger)}constructor(e,t){this._command=e,this.description=t?.description??"",this.group=t?.group,this.tmp={options:t?.options??{},arguments:t?.arguments??{}};const n=this.defaultOptions();if(n.length>0)for(const i of n)this.tmp.options[i.option]=i}disablePrompting(){return this.disablePromptingFlag=!0,this}preHandler(e){return this._preHandler=e,this}handler(e){return this._handler=e,this}options(e){return this.tmp={options:{...this.tmp?.options??{},...e},arguments:this.tmp?.arguments??{}},this}arguments(e){return this.tmp={options:this.tmp?.options??{},arguments:{...this.tmp?.arguments??{},...e}},this}async run(e){if(!this._handler&&!this.handle)throw new Error(`No handler defined for command ${this.command||"(unknown)"}`);let t;if(this.ctx=e.ctx,this.logger=e.logger,this.io=this.newCommandIO({logger:e.logger}),e&&"args"in e){const s=this.tmp?.options??{};for(const o of this.defaultOptions())o.option in s||(s[o.option]=o);this.parser=this.newCommandParser({io:this.io,options:s,arguments:this.tmp?.arguments??{}}),t=this.parser.init(e.args);for(const o of this.defaultOptions())if(t.options[o.option]===!0){const u=await o.handler.call(this);if(u&&u!==0)return u}this.disablePromptingFlag&&this.parser.disablePrompting(),await this.parser.validate()}else t={options:e.options,arguments:e.arguments};const n=this.preHandle?await this.preHandle():null;if(n&&n!==0)return n;if(!this._handler&&this.handle)this._handler=this.handle.bind(this);else if(!this._handler)throw new Error(`No handler defined for command ${this.command||"(unknown)"}`);return await this._handler(e.ctx,t)??0}}class R extends M{command;constructor(e){const t=R.parseSignature(e.signature,e.helperDefinitions,e.defaultOptions);super({io:e.io,options:t.options,arguments:t.arguments}),this.command=t.command}static parseSignature(e,t,n){const[i,...s]=e.split(/\{(.*?)\}/g).map(m=>m.trim()).filter(Boolean),o={},u={};for(const m of s){const{name:h,isOption:l,definition:d}=R.parseParamSignature(m,t);l?o[h]=d:u[h]=d}for(const m of n)o[m.option]={type:m.type,required:m.required,alias:m.alias,variadic:m.variadic??!1,description:m.description,default:m.default??null};return{command:i,options:o,arguments:u}}static parseParamSignature(e,t){let n=e,i=!1;const s={required:!0,type:"string",description:void 0,default:null,variadic:!1};if(n.includes(":")){const[o,u]=n.split(":");n=o.trim(),s.description=u.trim()}if(n.includes("=")){const[o,u]=n.split("=");n=o.trim(),s.default=u.trim(),s.required=!1,typeof s.default=="string"&&!s.default.length?s.default=null:s.default==="true"?(s.default=!0,s.type="boolean"):s.default==="false"&&(s.default=!1,s.type="boolean")}else n.startsWith("--")&&(s.required=!1,s.default=!1,s.type="boolean");if(n.includes("|")){const[o,...u]=n.split("|");n=o.trim(),s.alias=u.map(m=>m.trim())}return n.startsWith("--")&&(i=!0,n=n.slice(2)),s.default==="*"&&(s.default=[],s.type=["string"]),n.endsWith("?")&&(s.required=!1,n=n.slice(0,-1)),n.endsWith("*")&&(s.type=["string"],s.variadic=!0,s.default=[],n=n.slice(0,-1)),s.description=s.description??t[n]??t[`--${n}`],{name:n,isOption:i,definition:s}}}class Ce extends ${helperDefinitions={};get command(){return this.parser?this.parser.command:this.signature.split(" ")[0]}newCommandParser(e){return new R({io:e.io,signature:this.signature,helperDefinitions:this.helperDefinitions,defaultOptions:this.defaultOptions()})}constructor(){super("")}option(e,t=null){return this.parser.option(e,t)}argument(e,t=null){return this.parser.argument(e,t)}async askForConfirmation(...e){return this.io.askForConfirmation(...e)}async askForInput(...e){return this.io.askForInput(...e)}async askForSelect(...e){return this.io.askForSelect(...e)}newLoader(...e){return this.io.newLoader(...e)}}class q{level;constructor(e={}){this.level=e.level??"info"}shouldLog(e){const t=["debug","info","warn","error"],n=t.indexOf(this.level);return t.indexOf(e)>=n}setLevel(e){this.level=e}getLevel(){return this.level}log(...e){console.log(...e)}info(...e){this.shouldLog("info")&&console.log(...e)}warn(...e){this.shouldLog("warn")&&console.warn(...e)}error(...e){this.shouldLog("error")&&console.error(...e)}debug(...e){this.shouldLog("debug")&&console.log(...e)}}class te{commands={};io;logger;get CommandIOClass(){return I}constructor(e){this.logger=e??new q,this.io=new this.CommandIOClass(this.logger)}getAvailableCommands(){return Object.keys(this.commands)}getCommands(){return Object.values(this.commands)}importFile=async e=>(await import(e)).default;commandResolver=async e=>{let t=await this.importFile(e);if(!t)throw new Error(`The command at path ${e} does not have a default export.`);return t&&typeof t=="object"&&"default"in t&&(t=t.default),typeof t=="function"?new t:t instanceof $?t:null};withCommandResolver(e){return this.commandResolver=e,this}withFileImporter(e){return this.importFile=e,this}registerCommand(e,t=!1){const n=e.command;if(!n)throw new Error("Command signature is invalid, it must have a command name.");if(!t&&this.commands[n])throw new Error(`Command ${n} already registered.`);this.commands[n]=e}async loadCommandsPath(e){for await(const t of this.listCommandsFiles(e))try{const n=await this.commandResolver(t);n instanceof $&&this.registerCommand(n)}catch(n){throw new Error(`Command ${t} failed to load. ${n}`,{cause:n})}}async runCommand(e,t,...n){const i=typeof t=="string"?this.commands[t]:t,s=typeof t=="string"?t:i.command;if(!i){const o=await this.suggestCommand(s);return o?await this.runCommand(e,o,...n):1}return await i.run({ctx:e,logger:this.logger,args:n})??0}async suggestCommand(e){const t=this.getAvailableCommands(),{bestMatch:n,bestMatchIndex:i,ratings:s}=le.findBestMatch(e,t),o=s.filter(u=>u.rating>.3).map(u=>u.target);if(n.rating>0&&o.length<=1||n.rating>.7&&o.length>1){const u=t[i];return await this.askRunSimilarCommand(e,u)?u:null}if(o.length){this.io.error(`${a.bgRed(" ERROR ")} Command ${a.yellow(e)} not found.
14
- `);const u=await this.io.askForSelect(a.green("Did you mean to run one of these commands instead?"),o);if(u)return u}throw new Z(e)}async askRunSimilarCommand(e,t){return this.io.error(`${a.bgRed(" ERROR ")} Command ${a.yellow(e)} not found.
15
- `),this.io.askForConfirmation(`${a.green(`Do you want to run ${a.yellow(t)} instead?`)} `)}async*listCommandsFiles(e){const t=ae.readdirSync(e,{withFileTypes:!0});for(const n of t){const i=V.resolve(e,n.name);if(n.isDirectory())yield*this.listCommandsFiles(V.resolve(e,n.name));else{if(!i.endsWith(".ts")&&!i.endsWith(".js")&&!i.endsWith(".mjs")&&!i.endsWith(".cjs"))continue;yield i}}}}class ne{logger;constructor(e){this.logger=e}handle(e){if(e instanceof b)return e.pretty(this.logger),-1;throw e}}class Oe extends ${constructor(e){super("help",{description:a.bold("Show help information about the CLI and its commands")}),this.opts=e}async handle(){const e=this.opts.commandRegistry.getCommands(),t=this.opts.cliName??"Bob CLI",n=this.opts.cliVersion??"0.0.0",i=(await Promise.resolve().then(()=>require("./package-6GoPiEev.cjs")))?.default?.version??"0.0.0";this.io.log(`${t} ${a.green(n)} (core: ${a.yellow(i)})
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("prompts"),a=require("chalk"),H=require("minimist"),M=require("node:fs"),F=require("path");function T(s){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const e in s)if(e!=="default"){const i=Object.getOwnPropertyDescriptor(s,e);Object.defineProperty(t,e,i.get?i:{enumerable:!0,get:()=>s[e]})}}return t.default=s,Object.freeze(t)}const W=T(M);class R{logger;constructor(t){this.logger=t.logger}log(...t){this.logger.log(...t)}info(...t){this.logger.info(...t)}warn(...t){this.logger.warn(...t)}error(...t){this.logger.error(...t)}debug(...t){this.logger.debug(...t)}async askForConfirmation(t="Do you want to continue?",e){return(await y({type:"confirm",name:"value",message:t,initial:e??!1})).value}async askForInput(t,e,i){return(await y({type:"text",name:"value",message:t,initial:e,...i}))?.value??null}async askForDate(t,e,i){return(await y({type:"date",name:"value",message:t,initial:e,...i}))?.value??null}async askForList(t,e,i){return(await y({type:"list",name:"value",message:t,initial:e,...i}))?.value??null}async askForToggle(t,e,i){return(await y({type:"toggle",name:"value",message:t,initial:e,...i}))?.value??null}async askForSelect(t,e,i){if(e.length===0)throw new Error("No options provided");const n=[];for(const o of e)typeof o=="string"?n.push({title:o,value:o}):n.push(o);return(await y({type:"select",name:"value",message:t,choices:n,...i}))?.value??null}newLoader(t="",e=["⠙","⠘","⠰","⠴","⠤","⠦","⠆","⠃","⠋","⠉"],i=100){let n=t,r=null,o=0;const m=setInterval(function(){r&&(process.stdout.write(new TextEncoder().encode("\r"+" ".repeat(r.length+5)+"\r")),r=null),process.stdout.write(new TextEncoder().encode("\r"+e[o++]+" "+n)),o=o%e.length},i),u=()=>{clearInterval(m),process.stdout.write(new TextEncoder().encode("\r"+" ".repeat(n.length+5)+"\r"))};return{[Symbol.dispose]:u,[Symbol.asyncDispose]:u,updateText:c=>{r=n,n=c},stop:u}}}class f extends Error{}function k(s){if(s==="string"||s==="number")return null;if(s==="boolean")return!1;if(Array.isArray(s)&&s.length===1){if(s[0]==="string")return[];if(s[0]==="number")return[]}throw new Error("Invalid option type: "+s)}function q(s){return typeof s=="string"||Array.isArray(s)?k(s):s.default!==void 0?s.default:k(s.type)}function g(s){return typeof s=="string"||Array.isArray(s)?{alias:[],default:q(s),description:"",required:!1,secret:!1,type:s,variadic:!1}:{alias:s.alias?Array.isArray(s.alias)?s.alias:[s.alias]:[],default:s.default??q(s.type),description:s.description??"",required:s.required??!1,secret:s.secret??!1,type:s.type,variadic:s.variadic??!1}}class $ extends f{constructor(t,e={}){super(`Invalid option ${t} in not recognized`),this.option=t,this.optionsSchema=e}pretty(t){const e=Object.entries(this.optionsSchema);if(e.length>0){t.log(`
2
+ ${a.yellow("Available options")}:`);for(const[i,n]of e){const r=g(n),o=typeof r.alias=="string"?[r.alias]:r.alias,m=Array.isArray(r.type)?`[${r.type[0]}]`:r.type,u=`--${i}${o.length>0?o.map(l=>`, -${l}`).join(""):""}`,c=" ".repeat(30-u.length);t.log(` ${a.green(u)} ${c} ${r.description||"\b"} ${a.white(`(${m})`)}`)}t.log("")}t.log(`${a.white.bgRed(" ERROR ")} Option ${a.bold.yellow(this.option)} is not recognized.`)}}class O extends f{constructor(t){super(`Argument "${t}" is required.`),this.argument=t}pretty(t){t.log(`${a.white.bgRed(" ERROR ")} Argument ${a.bold.yellow(this.argument)} is required.`)}}class N extends f{constructor(t){super(`Argument "${t}" is required.`),this.option=t}pretty(t){t.log(`${a.white.bgRed(" ERROR ")} Option ${a.bold.yellow(this.option)} is required.`)}}class B extends f{constructor(t){let e=`Argument "${t.param}" value is invalid.`;t.reason?e+=` Reason: ${t.reason}`:e+=` Value: "${t.value}"`,super(e),this.param=t}pretty(t){t.log(` ${a.white.bgRed(" ERROR ")} Argument ${a.bold.yellow(this.param.param)} value is invalid. `),(this.param.value||this.param.reason)&&t.log(""),this.param.value&&t.log(` ${a.blue("Value")}: ${this.param.value}`),this.param.reason&&t.log(` ${a.yellow("Reason")}: ${this.param.reason}`)}}class C extends f{constructor(t){let e=`Option "${t.option}" value is invalid.`;t.reason?e+=` Reason: ${t.reason}`:e+=` Value: "${t.value}"`,super(e),this.param=t}pretty(t){t.log(` ${a.white.bgRed(" ERROR ")} Option ${a.bold.yellow(this.param.option)} value is invalid. `),(this.param.value||this.param.reason)&&t.log(""),this.param.value&&t.log(` ${a.blue("Value")}: ${this.param.value}`),this.param.reason&&t.log(` ${a.yellow("Reason")}: ${this.param.reason}`)}}class P extends f{constructor(t){super(`Command "${t}" not found.`),this.command=t}pretty(t){t.log(`${a.bgRed(" ERROR ")} Command ${a.yellow(this.command)} not found.`)}}function w(s,t,e,i){if(s==null)return i??null;if(t==="string")return String(s);if(t==="number"){const n=Number(s);if(isNaN(n))throw new C({option:e,reason:`Expected a number, got "${s}"`});return n}if(t==="boolean")return typeof s=="boolean"?s:s==="true"||s==="1"?!0:s==="false"||s==="0"?!1:!!s;if(Array.isArray(t)){const n=t[0],r=Array.isArray(s)?s:[s];if(n==="string")return r.map(o=>String(o));if(n==="number")return r.map(o=>{const m=Number(o);if(isNaN(m))throw new C({option:e,reason:`Expected array of numbers, got "${o}" in array`});return m})}return s}class x{options;parsedOptions=null;arguments;parsedArguments=null;io;shouldPromptForMissingOptions=!0;constructor(t){this.options=t.options,this.arguments=t.arguments,this.io=t.io}init(t){const{_:e,...i}=H(t);return this.validateUnknownOptions(i),this.parsedOptions=this.handleOptions(i),this.parsedArguments=this.handleArguments(e),{options:this.parsedOptions,arguments:this.parsedArguments}}async validate(){for(const t in this.options)if(g(this.options[t]).required&&(this.parsedOptions?.[t]===void 0||this.parsedOptions?.[t]===null))throw new N(t);for(const t in this.arguments){const e=g(this.arguments[t]),i=this.parsedArguments?.[t];if(e.required&&i==null){if(this.shouldPromptForMissingOptions){const n=await this.promptForArgument(t,e);if(n&&this.parsedArguments){this.parsedArguments[t]=w(n,e.type,t);continue}}throw new O(t)}if(e.required&&e.variadic&&Array.isArray(i)&&i.length===0){if(this.shouldPromptForMissingOptions){const n=await this.promptForArgument(t,e);if(n&&this.parsedArguments){this.parsedArguments[t]=w(n,e.type,t);continue}}throw new O(t)}}}option(t,e){if(!this.parsedOptions)throw new Error("Options have not been parsed yet. Call init() first.");return this.isEmptyValue(this.parsedOptions[t])&&e!==void 0?e:this.parsedOptions[t]}setOption(t,e){if(!this.parsedOptions)throw new Error("Options have not been parsed yet. Call init() first.");if(!(t in this.options))throw new $(t,this.options);this.parsedOptions[t]=e}argument(t,e){if(!this.parsedArguments)throw new Error("Arguments have not been parsed yet. Call init() first.");return this.isEmptyValue(this.parsedArguments[t])&&e!==void 0?e:this.parsedArguments[t]}setArgument(t,e){if(!this.parsedArguments)throw new Error("Arguments have not been parsed yet. Call init() first.");if(!(t in this.arguments))throw new $(t,this.arguments);this.parsedArguments[t]=e}isEmptyValue(t){return t==null||Array.isArray(t)&&t.length===0}validateUnknownOptions(t){const e=new Set;for(const i in this.options){e.add(i);const n=g(this.options[i]);for(const r of n.alias)e.add(r)}for(const i in t)if(!e.has(i))throw new $(i,this.options)}handleOptions(t){const e={};for(const i in this.options){const n=g(this.options[i]);e[i]=this.resolveOptionValue(i,n,t)}return e}handleArguments(t){const e={},i=[...t];for(const n in this.arguments){const r=g(this.arguments[n]);if(r.variadic){e[n]=this.handleVariadicArgument(n,r,i);continue}e[n]=this.resolveArgumentValue(n,r,i.shift())}return e}handleVariadicArgument(t,e,i){return i.length?w(i,e.type,t,e.default):e.default}resolveArgumentValue(t,e,i){return i===void 0?e.default:w(i,e.type,t,e.default)}resolveOptionValue(t,e,i){let n;const r=[t,...e.alias];for(const o of r)if(o in i){n=i[o];break}if(n===void 0){if(e.required)throw new C({option:t,reason:"Required option is missing"});return e.default}return w(n,e.type,t,e.default)}optionDefinitions(){const t={};for(const e in this.options)t[e]=g(this.options[e]);return t}argumentDefinitions(){const t={};for(const e in this.arguments)t[e]=g(this.arguments[e]);return t}availableOptions(){return Object.keys(this.options)}availableArguments(){return Object.keys(this.arguments)}disablePrompting(){return this.shouldPromptForMissingOptions=!1,this}async promptForArgument(t,e){if(!Array.isArray(e.type)&&!["string","number","secret"].includes(e.type))return null;let i=`${a.yellow.bold(t)} is required`;return e.description&&(i+=`: ${a.gray(`(${e.description})`)}`),i+=` ${a.green(`(${e.type}${e.variadic==!0?"[]":""})`)}
3
+ `,Array.isArray(e.type)?(i+=`Please provide one or more values, separated by commas:
4
+ `,await this.io.askForList(i,void 0,{separator:",",validate:n=>{if(!n.length)return"Please enter at least one value";if(e.type[0]==="number"){for(const r of n.split(","))if(isNaN(Number(r)))return"Please enter only valid numbers"}return!0}})):await this.io.askForInput(i,void 0,{type:e.type==="number"?"number":e.secret?"password":"text",validate:n=>{if(n==null||typeof n=="string"&&!n.length)return"This value is required";if(e.type==="number"){const r=Number(n);if(isNaN(r))return"Please enter a valid number"}else if(e.type==="string"&&(typeof n!="string"||!n.length))return"Please enter a valid text";return!0}})}}function A(s){return new Array(s+5).join(" ")}class L{type="boolean";option="help";alias=["h"];default=!1;description=`Display help for the given command. When no command is given display help for the ${a.green("list")} command`;async handler(){const t=this.parser.argumentDefinitions(),e=this.parser.optionDefinitions(),i=Object.entries(t),n=Object.entries(e),r=n.map(([l,d])=>{const h=Array.isArray(d.alias)?d.alias:d.alias?[d.alias]:[];return{name:l,...d,optionWithAlias:`--${l}${h.map(p=>`, -${p}`).join("")}`}}),o=i.filter(([,l])=>l.required);this.io.log(a.yellow("Description:")),this.io.log(` ${this.description}
5
+ `),this.io.log(a.yellow("Usage:")),this.io.log(` ${this.command} ${o.length>0?o.map(([l])=>`<${l}>`).join(" "):"\b"} [options]`);const m=Math.max(...r.map(l=>l.optionWithAlias.length),0),u=Math.max(...i.map(([l])=>l.length),0),c=u>m?u:m;if(i.length>0){this.io.log(`
6
+ ${a.yellow("Arguments")}:`);for(const[l,d]of i){const h=A(c-l.length);let p=` ${a.green(l)} ${h} ${d.description??"\b"}`;if(d.default!==void 0&&!d.required){const j=(Array.isArray(d.type)?`[${d.type[0]}]`:d.type)==="array"||Array.isArray(d.type)?JSON.stringify(d.default):d.default;p+=` ${a.yellow(`[default: ${j}]`)}`}d.variadic&&(p+=` ${a.white("(variadic)")}`),this.io.log(p)}}if(n.length>0){this.io.log(`
7
+ ${a.yellow("Options")}:`);for(const l of r){const d=A(c-l.optionWithAlias.length);let h=`${a.green(l.optionWithAlias)} ${d} ${l.description??"\b"}`;if(l.type){const p=Array.isArray(l.type)?`[${l.type[0]}]`:l.type;h+=` ${a.white(`(${p})`)}`}if(l.default!==void 0&&!l.required){const E=(Array.isArray(l.type)?`[${l.type[0]}]`:l.type)==="array"||Array.isArray(l.type)?JSON.stringify(l.default):l.default;h+=` ${a.yellow(`[default: ${E}]`)}`}this.io.log(h)}}if(this.commandsExamples.length>0){this.io.log(`
8
+ ${a.yellow("Examples")}:`);let l=process.argv[0].split("/").pop();l==="node"&&(l+=" "+process.argv[1].split("/").pop());for(const[d,h]of this.commandsExamples.entries())d>0&&this.io.log(""),this.io.log(` ${h.description}
9
+ `),this.io.log(` ${a.green(`${l} ${h.command}`)}`)}return-1}}class v{_command;description;group;commandsExamples=[];get command(){return this._command}ctx;io;logger;parser;disablePromptingFlag=!1;_preHandler;_handler;tmp;defaultOptions(){return[new L]}newCommandParser(t){return new x({io:t.io,options:t.options,arguments:t.arguments})}newCommandIO(t){return new R(t)}constructor(t,e){this._command=t,this.description=e?.description??"",this.group=e?.group,this.tmp={options:e?.options??{},arguments:e?.arguments??{}};const i=this.defaultOptions();if(i.length>0)for(const n of i)this.tmp.options[n.option]=n}disablePrompting(){return this.disablePromptingFlag=!0,this}preHandler(t){return this._preHandler=t,this}handler(t){return this._handler=t,this}options(t){return this.tmp={options:{...this.tmp?.options??{},...t},arguments:this.tmp?.arguments??{}},this}arguments(t){return this.tmp={options:this.tmp?.options??{},arguments:{...this.tmp?.arguments??{},...t}},this}async run(t){if(!this._handler&&!this.handle)throw new Error(`No handler defined for command ${this.command||"(unknown)"}`);let e;if(this.ctx=t.ctx,this.logger=t.logger,this.io=this.newCommandIO({logger:t.logger}),t&&"args"in t){const r=this.tmp?.options??{};for(const o of this.defaultOptions())o.option in r||(r[o.option]=o);this.parser=this.newCommandParser({io:this.io,options:r,arguments:this.tmp?.arguments??{}}),e=this.parser.init(t.args);for(const o of this.defaultOptions())if(e.options[o.option]===!0){const m=await o.handler.call(this);if(m&&m!==0)return m}this.disablePromptingFlag&&this.parser.disablePrompting(),await this.parser.validate()}else e={options:t.options,arguments:t.arguments};const i=this.preHandle?await this.preHandle():null;if(i&&i!==0)return i;if(!this._handler&&this.handle)this._handler=this.handle.bind(this);else if(!this._handler)throw new Error(`No handler defined for command ${this.command||"(unknown)"}`);return await this._handler(t.ctx,e)??0}}class b extends x{command;constructor(t){const e=b.parseSignature(t.signature,t.helperDefinitions,t.defaultOptions);super({io:t.io,options:e.options,arguments:e.arguments}),this.command=e.command}static parseSignature(t,e,i){const[n,...r]=t.split(/\{(.*?)\}/g).map(u=>u.trim()).filter(Boolean),o={},m={};for(const u of r){const{name:c,isOption:l,definition:d}=b.parseParamSignature(u,e);l?o[c]=d:m[c]=d}for(const u of i)o[u.option]={type:u.type,required:u.required,alias:u.alias,variadic:u.variadic??!1,description:u.description,default:u.default??null};return{command:n,options:o,arguments:m}}static parseParamSignature(t,e){let i=t,n=!1;const r={required:!0,type:"string",description:void 0,default:null,variadic:!1};if(i.includes(":")){const[o,m]=i.split(":");i=o.trim(),r.description=m.trim()}if(i.includes("=")){const[o,m]=i.split("=");i=o.trim(),r.default=m.trim(),r.required=!1,typeof r.default=="string"&&!r.default.length?r.default=null:r.default==="true"?(r.default=!0,r.type="boolean"):r.default==="false"&&(r.default=!1,r.type="boolean")}else i.startsWith("--")&&(r.required=!1,r.default=!1,r.type="boolean");if(i.includes("|")){const[o,...m]=i.split("|");i=o.trim(),r.alias=m.map(u=>u.trim())}return i.startsWith("--")&&(n=!0,i=i.slice(2)),r.default==="*"&&(r.default=[],r.type=["string"]),i.endsWith("?")&&(r.required=!1,i=i.slice(0,-1)),i.endsWith("*")&&(r.type=["string"],r.variadic=!0,r.default=[],i=i.slice(0,-1)),r.description=r.description??e[i]??e[`--${i}`],{name:i,isOption:n,definition:r}}}class _ extends v{helperDefinitions={};get command(){return this.parser?this.parser.command:this.signature.split(" ")[0]}newCommandParser(t){return new b({io:t.io,signature:this.signature,helperDefinitions:this.helperDefinitions,defaultOptions:this.defaultOptions()})}constructor(){super("")}option(t,e=null){return this.parser.option(t,e)}argument(t,e=null){return this.parser.argument(t,e)}async askForConfirmation(...t){return this.io.askForConfirmation(...t)}async askForInput(...t){return this.io.askForInput(...t)}async askForSelect(...t){return this.io.askForSelect(...t)}newLoader(...t){return this.io.newLoader(...t)}}class S{level;constructor(t={}){this.level=t.level??"info"}shouldLog(t){const e=["debug","info","warn","error"],i=e.indexOf(this.level);return e.indexOf(t)>=i}setLevel(t){this.level=t}getLevel(){return this.level}log(...t){console.log(...t)}info(...t){this.shouldLog("info")&&console.log(...t)}warn(...t){this.shouldLog("warn")&&console.warn(...t)}error(...t){this.shouldLog("error")&&console.error(...t)}debug(...t){this.shouldLog("debug")&&console.log(...t)}}class I{getBigrams(t){const e=[],i=t.toLowerCase();for(let n=0;n<i.length-1;n++)e.push(i.slice(n,n+2));return e}calculateSimilarity(t,e){if(t===e)return 1;if(t.length<2||e.length<2)return 0;const i=this.getBigrams(t),n=this.getBigrams(e),r=new Set(n);let o=0;for(const m of i)r.has(m)&&(o++,r.delete(m));return 2*o/(i.length+n.length)}findBestMatch(t,e){const i=e.map(o=>({target:o,rating:this.calculateSimilarity(t,o)}));let n=0,r=i[0]?.rating??0;for(let o=1;o<i.length;o++)i[o].rating>r&&(r=i[o].rating,n=o);return{ratings:i,bestMatch:i[n],bestMatchIndex:n}}}class V{commands={};io;logger;stringSimilarity;newCommandIO(t){return new R(t)}constructor(t){this.logger=t?.logger??new S,this.io=this.newCommandIO({logger:this.logger}),this.stringSimilarity=t?.stringSimilarity??new I}getAvailableCommands(){return Object.keys(this.commands)}getCommands(){return Object.values(this.commands)}importFile=async t=>(await import(t)).default;commandResolver=async t=>{let e=await this.importFile(t);if(!e)throw new Error(`The command at path ${t} does not have a default export.`);return e&&typeof e=="object"&&"default"in e&&(e=e.default),typeof e=="function"?new e:e instanceof v?e:null};withCommandResolver(t){return this.commandResolver=t,this}withFileImporter(t){return this.importFile=t,this}registerCommand(t,e=!1){const i=t.command;if(!i)throw new Error("Command signature is invalid, it must have a command name.");if(!e&&this.commands[i])throw new Error(`Command ${i} already registered.`);this.commands[i]=t}async loadCommandsPath(t){for await(const e of this.listCommandsFiles(t))try{const i=await this.commandResolver(e);i instanceof v&&this.registerCommand(i)}catch(i){throw new Error(`Command ${e} failed to load. ${i}`,{cause:i})}}async runCommand(t,e,...i){const n=typeof e=="string"?this.commands[e]:e,r=typeof e=="string"?e:n.command;if(!n){const o=await this.suggestCommand(r);return o?await this.runCommand(t,o,...i):1}return await n.run({ctx:t,logger:this.logger,args:i})??0}async suggestCommand(t){const e=this.getAvailableCommands(),{bestMatch:i,bestMatchIndex:n,ratings:r}=this.stringSimilarity.findBestMatch(t,e),o=r.filter(m=>m.rating>.3).map(m=>m.target);if(i.rating>0&&o.length<=1||i.rating>.7&&o.length>1){const m=e[n];return await this.askRunSimilarCommand(t,m)?m:null}if(o.length){this.io.error(`${a.bgRed(" ERROR ")} Command ${a.yellow(t)} not found.
10
+ `);const m=await this.io.askForSelect(a.green("Did you mean to run one of these commands instead?"),o);if(m)return m}throw new P(t)}async askRunSimilarCommand(t,e){return this.io.error(`${a.bgRed(" ERROR ")} Command ${a.yellow(t)} not found.
11
+ `),this.io.askForConfirmation(`${a.green(`Do you want to run ${a.yellow(e)} instead?`)} `)}async*listCommandsFiles(t){const e=W.readdirSync(t,{withFileTypes:!0});for(const i of e){const n=F.resolve(t,i.name);if(i.isDirectory())yield*this.listCommandsFiles(F.resolve(t,i.name));else{if(!n.endsWith(".ts")&&!n.endsWith(".js")&&!n.endsWith(".mjs")&&!n.endsWith(".cjs"))continue;yield n}}}}class D{logger;constructor(t){this.logger=t}handle(t){if(t instanceof f)return t.pretty(this.logger),-1;throw t}}class G extends v{constructor(t){super("help",{description:a.bold("Show help information about the CLI and its commands")}),this.opts=t}async handle(){const t=this.opts.commandRegistry.getCommands(),e=this.opts.cliName??"Bob CLI",i=this.opts.cliVersion??"0.0.0",n=(await Promise.resolve().then(()=>require("./package-o2EGFSAP.cjs")))?.default?.version??"0.0.0";this.io.log(`${e} ${a.green(i)} (core: ${a.yellow(n)})
16
12
 
17
13
  ${a.yellow("Usage")}:
18
14
  command [options] [arguments]
19
15
 
20
16
  ${a.yellow("Available commands")}:
21
- `);const s=Math.max(...e.map(m=>m.command.length))??0,o={};for(const m of e){const h=m.group??m.command.split(":")[0];o[h]||(o[h]=[]),o[h].push(m)}const u=Object.entries(o).sort(([m],[h])=>m.toLowerCase().localeCompare(h.toLowerCase())).sort(([,m],[,h])=>m.length-h.length);for(const[m,h]of u){const l=h.length>1;l&&this.io.log(a.yellow(`${m}:`));const d=h.sort((p,g)=>p.command.toLowerCase().localeCompare(g.command.toLowerCase()));for(const p of d){let g=j(s-p.command.length);l&&(g=g.slice(2)),this.io.log(`${l?" ":""}${a.green(p.command)} ${g} ${p.description}`)}}}}class Ae{ctx;logger;commandRegistry;exceptionHandler;helpCommand;newCommandRegistry(e){return new te(e.logger)}newHelpCommand(e){return new Oe(e)}newExceptionHandler(e){return new ne(e.logger)}constructor(e={}){this.ctx=e.ctx,this.logger=e.logger??new q,this.commandRegistry=this.newCommandRegistry({logger:this.logger}),this.exceptionHandler=this.newExceptionHandler({logger:this.logger}),this.helpCommand=this.newHelpCommand({cliName:e.name,cliVersion:e.version,commandRegistry:this.commandRegistry})}withCommandResolver(e){return this.commandRegistry.withCommandResolver(e),this}withFileImporter(e){return this.commandRegistry.withFileImporter(e),this}async withCommands(...e){for(const t of e)typeof t=="string"?await this.commandRegistry.loadCommandsPath(t):typeof t=="function"?this.registerCommand(new t):this.registerCommand(t)}async runCommand(e,...t){return e?await this.commandRegistry.runCommand(this.ctx??{},e,...t).catch(this.exceptionHandler.handle.bind(this.exceptionHandler)):await this.runHelpCommand()}async runHelpCommand(){return await this.runCommand(this.helpCommand)}registerCommand(e){this.commandRegistry.registerCommand(e)}}exports.BadCommandOption=F;exports.BadCommandParameter=ve;exports.BobError=b;exports.Cli=Ae;exports.Command=$;exports.CommandIO=I;exports.CommandNotFoundError=Z;exports.CommandParser=M;exports.CommandRegistry=te;exports.CommandSignatureParser=R;exports.CommandWithSignature=Ce;exports.ExceptionHandler=ne;exports.HelpOption=ee;exports.InvalidOption=E;exports.Logger=q;exports.MissingRequiredArgumentValue=N;exports.MissingRequiredOptionValue=X;
17
+ `);const r=Math.max(...t.map(u=>u.command.length))??0,o={};for(const u of t){const c=u.group??u.command.split(":")[0];o[c]||(o[c]=[]),o[c].push(u)}const m=Object.entries(o).sort(([u],[c])=>u.toLowerCase().localeCompare(c.toLowerCase())).sort(([,u],[,c])=>u.length-c.length);for(const[u,c]of m){const l=c.length>1;l&&this.io.log(a.yellow(`${u}:`));const d=c.sort((h,p)=>h.command.toLowerCase().localeCompare(p.command.toLowerCase()));for(const h of d){let p=A(r-h.command.length);l&&(p=p.slice(2)),this.io.log(`${l?" ":""}${a.green(h.command)} ${p} ${h.description}`)}}}}class z{ctx;logger;commandRegistry;exceptionHandler;helpCommand;newCommandRegistry(t){return new V(t)}newHelpCommand(t){return new G(t)}newExceptionHandler(t){return new D(t.logger)}constructor(t={}){this.ctx=t.ctx,this.logger=t.logger??new S,this.commandRegistry=this.newCommandRegistry({logger:this.logger}),this.exceptionHandler=this.newExceptionHandler({logger:this.logger}),this.helpCommand=this.newHelpCommand({cliName:t.name,cliVersion:t.version,commandRegistry:this.commandRegistry})}withCommandResolver(t){return this.commandRegistry.withCommandResolver(t),this}withFileImporter(t){return this.commandRegistry.withFileImporter(t),this}async withCommands(...t){for(const e of t)typeof e=="string"?await this.commandRegistry.loadCommandsPath(e):typeof e=="function"?this.registerCommand(new e):this.registerCommand(e)}async runCommand(t,...e){return t?await this.commandRegistry.runCommand(this.ctx??{},t,...e).catch(this.exceptionHandler.handle.bind(this.exceptionHandler)):await this.runHelpCommand()}async runHelpCommand(){return await this.runCommand(this.helpCommand)}registerCommand(t){this.commandRegistry.registerCommand(t)}}exports.BadCommandOption=C;exports.BadCommandParameter=B;exports.BobError=f;exports.Cli=z;exports.Command=v;exports.CommandIO=R;exports.CommandNotFoundError=P;exports.CommandParser=x;exports.CommandRegistry=V;exports.CommandSignatureParser=b;exports.CommandWithSignature=_;exports.ExceptionHandler=D;exports.HelpOption=L;exports.InvalidOption=$;exports.Logger=S;exports.MissingRequiredArgumentValue=O;exports.MissingRequiredOptionValue=N;exports.StringSimilarity=I;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e="bob-core",t="2.0.0-beta.13",s="BOB Core",i="module",n=!1,r=["dist/**"],o={".":{import:"./dist/esm/index.js",require:"./dist/cjs/index.js"}},c={"*":{"*":["./dist/cjs/*.d.ts"]}},p={start:"node -r @swc-node/register debug/main.ts",build:"rimraf ./dist && vite build",typecheck:"tsc --noEmit",prepack:"npm run build",test:"vitest run",lint:"eslint .","lint:fix":"eslint . --fix"},d="Léo Hubert",l="ISC",a={"@eslint/js":"^9.37.0","@faker-js/faker":"^10.0.0","@swc-node/register":"^1.11.1","@trivago/prettier-plugin-sort-imports":"^5.2.2","@types/minimist":"^1.2.5","@types/node":"^20.14.5","@types/prompts":"^2.4.9","@types/string-similarity":"^4.0.2","@vitest/coverage-v8":"^3.2.4",eslint:"^9.37.0","eslint-config-prettier":"^10.1.8","eslint-plugin-prettier":"^5.5.4",prettier:"^3.6.2",rimraf:"^6.0.1",tsx:"^4.20.6",typescript:"^5.7.3","typescript-eslint":"^8.46.0",vite:"^7.1.6","vite-plugin-dts":"^4.5.4",vitest:"^3.2.4"},m={chalk:"^5.6.2",minimist:"^1.2.8",prompts:"^2.4.2","string-similarity":"^4.0.4"},u={name:e,version:t,description:s,type:i,sideEffects:n,files:r,exports:o,typesVersions:c,scripts:p,author:d,license:l,devDependencies:a,dependencies:m};exports.author=d;exports.default=u;exports.dependencies=m;exports.description=s;exports.devDependencies=a;exports.exports=o;exports.files=r;exports.license=l;exports.name=e;exports.scripts=p;exports.sideEffects=n;exports.type=i;exports.typesVersions=c;exports.version=t;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e="bob-core",t="2.0.0-beta.15",s="BOB Core",i="module",n=!1,r=["dist/**"],o={".":{import:"./dist/esm/index.js",require:"./dist/cjs/index.js"}},c={"*":{"*":["./dist/cjs/*.d.ts"]}},p={start:"node -r @swc-node/register debug/main.ts",build:"rimraf ./dist && vite build",typecheck:"tsc --noEmit",prepack:"npm run build",test:"vitest run",lint:"eslint .","lint:fix":"eslint . --fix"},d="Léo Hubert",l="ISC",a={"@eslint/js":"^9.37.0","@faker-js/faker":"^10.0.0","@swc-node/register":"^1.11.1","@trivago/prettier-plugin-sort-imports":"^5.2.2","@types/minimist":"^1.2.5","@types/node":"^20.14.5","@types/prompts":"^2.4.9","@types/string-similarity":"^4.0.2","@vitest/coverage-v8":"^3.2.4",eslint:"^9.37.0","eslint-config-prettier":"^10.1.8","eslint-plugin-prettier":"^5.5.4",prettier:"^3.6.2",rimraf:"^6.0.1",tsx:"^4.20.6",typescript:"^5.7.3","typescript-eslint":"^8.46.0",vite:"^7.1.6","vite-plugin-dts":"^4.5.4",vitest:"^3.2.4"},m={chalk:"^5.6.2",minimist:"^1.2.8",prompts:"^2.4.2"},u={name:e,version:t,description:s,type:i,sideEffects:n,files:r,exports:o,typesVersions:c,scripts:p,author:d,license:l,devDependencies:a,dependencies:m};exports.author=d;exports.default=u;exports.dependencies=m;exports.description=s;exports.devDependencies=a;exports.exports=o;exports.files=r;exports.license=l;exports.name=e;exports.scripts=p;exports.sideEffects=n;exports.type=i;exports.typesVersions=c;exports.version=t;
@@ -1,5 +1,5 @@
1
1
  import { Command } from './Command.js';
2
- import { CommandRegistry, CommandResolver, FileImporter } from './CommandRegistry.js';
2
+ import { CommandRegistry, CommandRegistryOptions, CommandResolver, FileImporter } from './CommandRegistry.js';
3
3
  import { ExceptionHandler } from './ExceptionHandler.js';
4
4
  import { Logger } from './Logger.js';
5
5
  import { default as HelpCommand, HelpCommandOptions } from './commands/HelpCommand.js';
@@ -16,9 +16,7 @@ export declare class Cli<C extends ContextDefinition = ContextDefinition> {
16
16
  readonly commandRegistry: CommandRegistry;
17
17
  private readonly exceptionHandler;
18
18
  private readonly helpCommand;
19
- protected newCommandRegistry(opts: {
20
- logger: Logger;
21
- }): CommandRegistry;
19
+ protected newCommandRegistry(opts: CommandRegistryOptions): CommandRegistry;
22
20
  protected newHelpCommand(opts: HelpCommandOptions): HelpCommand;
23
21
  protected newExceptionHandler(opts: {
24
22
  logger: Logger;
@@ -1,4 +1,4 @@
1
- import { CommandIO } from './CommandIO.js';
1
+ import { CommandIO, CommandIOOptions } from './CommandIO.js';
2
2
  import { CommandParser } from './CommandParser.js';
3
3
  import { Logger } from './Logger.js';
4
4
  import { CommandOption } from './contracts/index.js';
@@ -43,9 +43,7 @@ export declare class Command<C extends ContextDefinition = ContextDefinition, Op
43
43
  options: Options;
44
44
  arguments: Arguments;
45
45
  }): CommandParser<Options, Arguments>;
46
- protected newCommandIO(opts: {
47
- logger: Logger;
48
- }): CommandIO;
46
+ protected newCommandIO(opts: CommandIOOptions): CommandIO;
49
47
  constructor(command: string, opts?: {
50
48
  description?: string;
51
49
  group?: string;
@@ -6,9 +6,12 @@ export type SelectOption = {
6
6
  selected?: boolean | undefined;
7
7
  description?: string | undefined;
8
8
  };
9
+ export type CommandIOOptions = {
10
+ logger: Logger;
11
+ };
9
12
  export declare class CommandIO {
10
13
  private logger;
11
- constructor(logger: Logger);
14
+ constructor(opts: CommandIOOptions);
12
15
  /**
13
16
  * Logger methods
14
17
  */
@@ -1,15 +1,21 @@
1
1
  import { Command } from './Command.js';
2
- import { CommandIO } from './CommandIO.js';
2
+ import { CommandIO, CommandIOOptions } from './CommandIO.js';
3
3
  import { Logger } from './Logger.js';
4
+ import { StringSimilarity } from './StringSimilarity.js';
4
5
  import { ArgumentsSchema, ContextDefinition, OptionsSchema } from './lib/types.js';
5
6
  export type CommandResolver = (path: string) => Promise<Command | null>;
6
7
  export type FileImporter = (filePath: string) => Promise<unknown>;
8
+ export type CommandRegistryOptions = {
9
+ logger?: Logger;
10
+ stringSimilarity?: StringSimilarity;
11
+ };
7
12
  export declare class CommandRegistry {
8
13
  private readonly commands;
9
14
  protected readonly io: CommandIO;
10
15
  protected readonly logger: Logger;
11
- protected get CommandIOClass(): typeof CommandIO;
12
- constructor(logger?: Logger);
16
+ private readonly stringSimilarity;
17
+ protected newCommandIO(opts: CommandIOOptions): CommandIO;
18
+ constructor(opts?: CommandRegistryOptions);
13
19
  getAvailableCommands(): string[];
14
20
  getCommands(): Array<Command>;
15
21
  private importFile;
@@ -0,0 +1,26 @@
1
+ export interface SimilarityResult {
2
+ rating: number;
3
+ target: string;
4
+ }
5
+ export interface BestMatchResult {
6
+ bestMatch: SimilarityResult;
7
+ bestMatchIndex: number;
8
+ ratings: SimilarityResult[];
9
+ }
10
+ /**
11
+ * String similarity calculator using Dice's Coefficient algorithm
12
+ */
13
+ export declare class StringSimilarity {
14
+ /**
15
+ * Generate bigrams (character pairs) from a string
16
+ */
17
+ private getBigrams;
18
+ /**
19
+ * Calculate Dice's Coefficient similarity between two strings (0-1 scale)
20
+ */
21
+ calculateSimilarity(str1: string, str2: string): number;
22
+ /**
23
+ * Find best matching string and ratings for all candidates
24
+ */
25
+ findBestMatch(target: string, candidates: string[]): BestMatchResult;
26
+ }
@@ -7,6 +7,7 @@ export * from './CommandRegistry.js';
7
7
  export * from './Cli.js';
8
8
  export * from './Logger.js';
9
9
  export * from './ExceptionHandler.js';
10
+ export * from './StringSimilarity.js';
10
11
  export * from './lib/types.js';
11
12
  export * from './errors/index.js';
12
13
  export * from './options/index.js';