bob-core 2.0.0-beta.16 → 2.0.0-beta.18
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/{package-FOHQ7LSp.cjs → package-DjialezZ.cjs} +1 -1
- package/dist/cjs/src/Command.d.ts +0 -1
- package/dist/cjs/src/index.js +8 -8
- package/dist/esm/{package-DOsqYTRO.js → package-BBcsXm_8.js} +1 -1
- package/dist/esm/src/Command.d.ts +0 -1
- package/dist/esm/src/index.js +86 -85
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e="bob-core",t="2.0.0-beta.
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e="bob-core",t="2.0.0-beta.18",s="BOB Core",i="module",n="./dist/cjs/src/index.js",r="./dist/esm/src/index.js",c="./dist/esm/src/index.d.ts",o=["dist"],d={".":{import:{types:"./dist/esm/src/index.d.ts",default:"./dist/esm/src/index.js"},require:{types:"./dist/cjs/src/index.d.ts",default:"./dist/cjs/src/index.js"}}},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"},l="Léo Hubert",m="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.9.3","typescript-eslint":"^8.46.0",vite:"^7.2.7","vite-plugin-dts":"^4.5.4",vitest:"^3.2.4"},u={chalk:"^5.6.2",minimist:"^1.2.8",prompts:"^2.4.2"},y={name:e,version:t,description:s,type:i,main:n,module:r,types:c,files:o,exports:d,scripts:p,author:l,license:m,devDependencies:a,dependencies:u};exports.author=l;exports.default=y;exports.dependencies=u;exports.description=s;exports.devDependencies=a;exports.exports=d;exports.files=o;exports.license=m;exports.main=n;exports.module=r;exports.name=e;exports.scripts=p;exports.type=i;exports.types=c;exports.version=t;
|
|
@@ -29,7 +29,6 @@ export declare class Command<C extends ContextDefinition = ContextDefinition, Op
|
|
|
29
29
|
get command(): string;
|
|
30
30
|
protected ctx: C;
|
|
31
31
|
protected io: CommandIO;
|
|
32
|
-
protected logger: Logger;
|
|
33
32
|
protected parser: CommandParser<Options, Arguments>;
|
|
34
33
|
protected disablePromptingFlag: boolean;
|
|
35
34
|
protected preHandle?(): Promise<void | number>;
|
package/dist/cjs/src/index.js
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("prompts"),a=require("chalk"),
|
|
2
|
-
${a.yellow("Available options")}:`);for(const[i,n]of e){const r=g(n),o=typeof r.alias=="string"?[r.alias]:r.alias,
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("prompts"),a=require("chalk"),j=require("minimist"),M=require("node:fs"),F=require("path");function _(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 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 u=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),m=()=>{clearInterval(u),process.stdout.write(new TextEncoder().encode("\r"+" ".repeat(n.length+5)+"\r"))};return{[Symbol.dispose]:m,[Symbol.asyncDispose]:m,updateText:c=>{r=n,n=c},stop:m}}}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=r.alias?typeof r.alias=="string"?[r.alias]:r.alias:[],u=Array.isArray(r.type)?`[${r.type[0]}]`:r.type,m=`--${i}${o.length>0?o.map(l=>`, -${l}`).join(""):""}`,c=" ".repeat(30-m.length);t.log(` ${a.green(m)} ${c} ${r.description||"\b"} ${a.white(`(${u})`)}`)}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 W 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 u=Number(o);if(isNaN(u))throw new C({option:e,reason:`Expected array of numbers, got "${o}" in array`});return u})}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}=j(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
3
|
`,Array.isArray(e.type)?(i+=`Please provide one or more values, separated by commas:
|
|
4
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
|
|
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
|
|
5
|
+
`),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(...r.map(l=>l.optionWithAlias.length),0),m=Math.max(...i.map(([l])=>l.length),0),c=m>u?m:u;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 D=(Array.isArray(d.type)?`[${d.type[0]}]`:d.type)==="array"||Array.isArray(d.type)?JSON.stringify(d.default):d.default;p+=` ${a.yellow(`[default: ${D}]`)}`}d.variadic&&(p+=` ${a.white("(variadic)")}`),this.io.log(p)}}if(n.length>0){this.io.log(`
|
|
7
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
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;
|
|
10
|
-
`);const
|
|
11
|
-
`),this.io.askForConfirmation(`${a.green(`Do you want to run ${a.yellow(e)} instead?`)} `)}async*listCommandsFiles(t){const e=
|
|
9
|
+
`),this.io.log(` ${a.green(`${l} ${h.command}`)}`)}return-1}}class v{_command;description;group;commandsExamples=[];get command(){return this._command}ctx;io;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.io=this.newCommandIO({logger:t.logger}),t&&"args"in t){const n=this.tmp?.options??{};for(const r of this.defaultOptions())r.option in n||(n[r.option]=r);this.parser=this.newCommandParser({io:this.io,options:n,arguments:this.tmp?.arguments??{}}),e=this.parser.init(t.args);for(const r of this.defaultOptions())if(e.options[r.option]===!0){const o=await r.handler.call(this);if(o&&o!==0)return o}this.disablePromptingFlag&&this.parser.disablePrompting(),await this.parser.validate()}else e={options:t.options,arguments:t.arguments};if(!this._preHandler&&this.preHandle&&(this._preHandler=this.preHandle.bind(this)),this._preHandler){const n=await this._preHandler(t.ctx,e);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(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(m=>m.trim()).filter(Boolean),o={},u={};for(const m of r){const{name:c,isOption:l,definition:d}=b.parseParamSignature(m,e);l?o[c]=d:u[c]=d}for(const m of i)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:n,options:o,arguments:u}}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,u]=i.split(":");i=o.trim(),r.description=u.trim()}if(i.includes("=")){const[o,u]=i.split("=");i=o.trim(),r.default=u.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,...u]=i.split("|");i=o.trim(),r.alias=u.map(m=>m.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 B 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 u of i)r.has(u)&&(o++,r.delete(u));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(u=>u.rating>.3).map(u=>u.target);if(i.rating>0&&o.length<=1||i.rating>.7&&o.length>1){const u=e[n];return await this.askRunSimilarCommand(t,u)?u:null}if(o.length){this.io.error(`${a.bgRed(" ERROR ")} Command ${a.yellow(t)} not found.
|
|
10
|
+
`);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 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=T.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 H{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-DjialezZ.cjs")))?.default?.version??"0.0.0";this.io.log(`${e} ${a.green(i)} (core: ${a.yellow(n)})
|
|
12
12
|
|
|
13
13
|
${a.yellow("Usage")}:
|
|
14
14
|
command [options] [arguments]
|
|
15
15
|
|
|
16
16
|
${a.yellow("Available commands")}:
|
|
17
|
-
`);const r=Math.max(...t.map(
|
|
17
|
+
`);const r=Math.max(...t.map(m=>m.command.length))??0,o={};for(const m of t){const c=m.group??m.command.split(":")[0];o[c]||(o[c]=[]),o[c].push(m)}const u=Object.entries(o).sort(([m],[c])=>m.toLowerCase().localeCompare(c.toLowerCase())).sort(([,m],[,c])=>m.length-c.length);for(const[m,c]of u){const l=c.length>1;l&&this.io.log(a.yellow(`${m}:`));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 H(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=W;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=B;exports.ExceptionHandler=H;exports.HelpOption=L;exports.InvalidOption=$;exports.Logger=S;exports.MissingRequiredArgumentValue=O;exports.MissingRequiredOptionValue=N;exports.StringSimilarity=I;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const t = "bob-core", s = "2.0.0-beta.
|
|
1
|
+
const t = "bob-core", s = "2.0.0-beta.18", e = "BOB Core", i = "module", n = "./dist/cjs/src/index.js", r = "./dist/esm/src/index.js", c = "./dist/esm/src/index.d.ts", o = ["dist"], d = { ".": { import: { types: "./dist/esm/src/index.d.ts", default: "./dist/esm/src/index.js" }, require: { types: "./dist/cjs/src/index.d.ts", default: "./dist/cjs/src/index.js" } } }, 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" }, l = "Léo Hubert", m = "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.9.3", "typescript-eslint": "^8.46.0", vite: "^7.2.7", "vite-plugin-dts": "^4.5.4", vitest: "^3.2.4" }, u = { chalk: "^5.6.2", minimist: "^1.2.8", prompts: "^2.4.2" }, x = {
|
|
2
2
|
name: t,
|
|
3
3
|
version: s,
|
|
4
4
|
description: e,
|
|
@@ -29,7 +29,6 @@ export declare class Command<C extends ContextDefinition = ContextDefinition, Op
|
|
|
29
29
|
get command(): string;
|
|
30
30
|
protected ctx: C;
|
|
31
31
|
protected io: CommandIO;
|
|
32
|
-
protected logger: Logger;
|
|
33
32
|
protected parser: CommandParser<Options, Arguments>;
|
|
34
33
|
protected disablePromptingFlag: boolean;
|
|
35
34
|
protected preHandle?(): Promise<void | number>;
|
package/dist/esm/src/index.js
CHANGED
|
@@ -89,18 +89,18 @@ class S {
|
|
|
89
89
|
}
|
|
90
90
|
newLoader(t = "", e = ["⠙", "⠘", "⠰", "⠴", "⠤", "⠦", "⠆", "⠃", "⠋", "⠉"], i = 100) {
|
|
91
91
|
let n = t, s = null, o = 0;
|
|
92
|
-
const
|
|
92
|
+
const u = setInterval(function() {
|
|
93
93
|
s && (process.stdout.write(new TextEncoder().encode("\r" + " ".repeat(s.length + 5) + "\r")), s = null), process.stdout.write(new TextEncoder().encode("\r" + e[o++] + " " + n)), o = o % e.length;
|
|
94
|
-
}, i),
|
|
95
|
-
clearInterval(
|
|
94
|
+
}, i), m = () => {
|
|
95
|
+
clearInterval(u), process.stdout.write(new TextEncoder().encode("\r" + " ".repeat(n.length + 5) + "\r"));
|
|
96
96
|
};
|
|
97
97
|
return {
|
|
98
|
-
[Symbol.dispose]:
|
|
99
|
-
[Symbol.asyncDispose]:
|
|
98
|
+
[Symbol.dispose]: m,
|
|
99
|
+
[Symbol.asyncDispose]: m,
|
|
100
100
|
updateText: (h) => {
|
|
101
101
|
s = n, n = h;
|
|
102
102
|
},
|
|
103
|
-
stop:
|
|
103
|
+
stop: m
|
|
104
104
|
};
|
|
105
105
|
}
|
|
106
106
|
}
|
|
@@ -147,8 +147,8 @@ class b extends f {
|
|
|
147
147
|
t.log(`
|
|
148
148
|
${a.yellow("Available options")}:`);
|
|
149
149
|
for (const [i, n] of e) {
|
|
150
|
-
const s = g(n), o = typeof s.alias == "string" ? [s.alias] : s.alias,
|
|
151
|
-
t.log(` ${a.green(
|
|
150
|
+
const s = g(n), o = s.alias ? typeof s.alias == "string" ? [s.alias] : s.alias : [], u = Array.isArray(s.type) ? `[${s.type[0]}]` : s.type, m = `--${i}${o.length > 0 ? o.map((l) => `, -${l}`).join("") : ""}`, h = " ".repeat(30 - m.length);
|
|
151
|
+
t.log(` ${a.green(m)} ${h} ${s.description || "\b"} ${a.white(`(${u})`)}`);
|
|
152
152
|
}
|
|
153
153
|
t.log("");
|
|
154
154
|
}
|
|
@@ -219,13 +219,13 @@ function w(r, t, e, i) {
|
|
|
219
219
|
return s.map((o) => String(o));
|
|
220
220
|
if (n === "number")
|
|
221
221
|
return s.map((o) => {
|
|
222
|
-
const
|
|
223
|
-
if (isNaN(
|
|
222
|
+
const u = Number(o);
|
|
223
|
+
if (isNaN(u))
|
|
224
224
|
throw new C({
|
|
225
225
|
option: e,
|
|
226
226
|
reason: `Expected array of numbers, got "${o}" in array`
|
|
227
227
|
});
|
|
228
|
-
return
|
|
228
|
+
return u;
|
|
229
229
|
});
|
|
230
230
|
}
|
|
231
231
|
return r;
|
|
@@ -480,7 +480,7 @@ class k {
|
|
|
480
480
|
function A(r) {
|
|
481
481
|
return new Array(r + 5).join(" ");
|
|
482
482
|
}
|
|
483
|
-
class
|
|
483
|
+
class H {
|
|
484
484
|
type = "boolean";
|
|
485
485
|
option = "help";
|
|
486
486
|
alias = ["h"];
|
|
@@ -488,27 +488,27 @@ class D {
|
|
|
488
488
|
description = `Display help for the given command. When no command is given display help for the ${a.green("list")} command`;
|
|
489
489
|
async handler() {
|
|
490
490
|
const t = this.parser.argumentDefinitions(), e = this.parser.optionDefinitions(), i = Object.entries(t), n = Object.entries(e), s = n.map(([l, d]) => {
|
|
491
|
-
const
|
|
491
|
+
const p = Array.isArray(d.alias) ? d.alias : d.alias ? [d.alias] : [];
|
|
492
492
|
return {
|
|
493
493
|
name: l,
|
|
494
494
|
...d,
|
|
495
|
-
optionWithAlias: `--${l}${
|
|
495
|
+
optionWithAlias: `--${l}${p.map((c) => `, -${c}`).join("")}`
|
|
496
496
|
};
|
|
497
497
|
}), o = i.filter(([, l]) => l.required);
|
|
498
498
|
this.io.log(a.yellow("Description:")), this.io.log(` ${this.description}
|
|
499
499
|
`), this.io.log(a.yellow("Usage:")), this.io.log(` ${this.command} ${o.length > 0 ? o.map(([l]) => `<${l}>`).join(" ") : "\b"} [options]`);
|
|
500
|
-
const
|
|
500
|
+
const u = Math.max(...s.map((l) => l.optionWithAlias.length), 0), m = Math.max(...i.map(([l]) => l.length), 0), h = m > u ? m : u;
|
|
501
501
|
if (i.length > 0) {
|
|
502
502
|
this.io.log(`
|
|
503
503
|
${a.yellow("Arguments")}:`);
|
|
504
504
|
for (const [l, d] of i) {
|
|
505
|
-
const
|
|
506
|
-
let
|
|
505
|
+
const p = A(h - l.length);
|
|
506
|
+
let c = ` ${a.green(l)} ${p} ${d.description ?? "\b"}`;
|
|
507
507
|
if (d.default !== void 0 && !d.required) {
|
|
508
508
|
const L = (Array.isArray(d.type) ? `[${d.type[0]}]` : d.type) === "array" || Array.isArray(d.type) ? JSON.stringify(d.default) : d.default;
|
|
509
|
-
|
|
509
|
+
c += ` ${a.yellow(`[default: ${L}]`)}`;
|
|
510
510
|
}
|
|
511
|
-
d.variadic && (
|
|
511
|
+
d.variadic && (c += ` ${a.white("(variadic)")}`), this.io.log(c);
|
|
512
512
|
}
|
|
513
513
|
}
|
|
514
514
|
if (n.length > 0) {
|
|
@@ -516,16 +516,16 @@ ${a.yellow("Arguments")}:`);
|
|
|
516
516
|
${a.yellow("Options")}:`);
|
|
517
517
|
for (const l of s) {
|
|
518
518
|
const d = A(h - l.optionWithAlias.length);
|
|
519
|
-
let
|
|
519
|
+
let p = `${a.green(l.optionWithAlias)} ${d} ${l.description ?? "\b"}`;
|
|
520
520
|
if (l.type) {
|
|
521
|
-
const
|
|
522
|
-
|
|
521
|
+
const c = Array.isArray(l.type) ? `[${l.type[0]}]` : l.type;
|
|
522
|
+
p += ` ${a.white(`(${c})`)}`;
|
|
523
523
|
}
|
|
524
524
|
if (l.default !== void 0 && !l.required) {
|
|
525
525
|
const O = (Array.isArray(l.type) ? `[${l.type[0]}]` : l.type) === "array" || Array.isArray(l.type) ? JSON.stringify(l.default) : l.default;
|
|
526
|
-
|
|
526
|
+
p += ` ${a.yellow(`[default: ${O}]`)}`;
|
|
527
527
|
}
|
|
528
|
-
this.io.log(
|
|
528
|
+
this.io.log(p);
|
|
529
529
|
}
|
|
530
530
|
}
|
|
531
531
|
if (this.commandsExamples.length > 0) {
|
|
@@ -533,9 +533,9 @@ ${a.yellow("Options")}:`);
|
|
|
533
533
|
${a.yellow("Examples")}:`);
|
|
534
534
|
let l = process.argv[0].split("/").pop();
|
|
535
535
|
l === "node" && (l += " " + process.argv[1].split("/").pop());
|
|
536
|
-
for (const [d,
|
|
537
|
-
d > 0 && this.io.log(""), this.io.log(` ${
|
|
538
|
-
`), this.io.log(` ${a.green(`${l} ${
|
|
536
|
+
for (const [d, p] of this.commandsExamples.entries())
|
|
537
|
+
d > 0 && this.io.log(""), this.io.log(` ${p.description}
|
|
538
|
+
`), this.io.log(` ${a.green(`${l} ${p.command}`)}`);
|
|
539
539
|
}
|
|
540
540
|
return -1;
|
|
541
541
|
}
|
|
@@ -550,14 +550,13 @@ class v {
|
|
|
550
550
|
}
|
|
551
551
|
ctx;
|
|
552
552
|
io;
|
|
553
|
-
logger;
|
|
554
553
|
parser;
|
|
555
554
|
disablePromptingFlag = !1;
|
|
556
555
|
_preHandler;
|
|
557
556
|
_handler;
|
|
558
557
|
tmp;
|
|
559
558
|
defaultOptions() {
|
|
560
|
-
return [new
|
|
559
|
+
return [new H()];
|
|
561
560
|
}
|
|
562
561
|
newCommandParser(t) {
|
|
563
562
|
return new k({
|
|
@@ -610,22 +609,22 @@ class v {
|
|
|
610
609
|
if (!this._handler && !this.handle)
|
|
611
610
|
throw new Error(`No handler defined for command ${this.command || "(unknown)"}`);
|
|
612
611
|
let e;
|
|
613
|
-
if (this.ctx = t.ctx, this.
|
|
612
|
+
if (this.ctx = t.ctx, this.io = this.newCommandIO({
|
|
614
613
|
logger: t.logger
|
|
615
614
|
}), t && "args" in t) {
|
|
616
|
-
const
|
|
617
|
-
for (const
|
|
618
|
-
|
|
615
|
+
const n = this.tmp?.options ?? {};
|
|
616
|
+
for (const s of this.defaultOptions())
|
|
617
|
+
s.option in n || (n[s.option] = s);
|
|
619
618
|
this.parser = this.newCommandParser({
|
|
620
619
|
io: this.io,
|
|
621
|
-
options:
|
|
620
|
+
options: n,
|
|
622
621
|
arguments: this.tmp?.arguments ?? {}
|
|
623
622
|
}), e = this.parser.init(t.args);
|
|
624
|
-
for (const
|
|
625
|
-
if (e.options[
|
|
626
|
-
const
|
|
627
|
-
if (
|
|
628
|
-
return
|
|
623
|
+
for (const s of this.defaultOptions())
|
|
624
|
+
if (e.options[s.option] === !0) {
|
|
625
|
+
const o = await s.handler.call(this);
|
|
626
|
+
if (o && o !== 0)
|
|
627
|
+
return o;
|
|
629
628
|
}
|
|
630
629
|
this.disablePromptingFlag && this.parser.disablePrompting(), await this.parser.validate();
|
|
631
630
|
} else
|
|
@@ -633,9 +632,11 @@ class v {
|
|
|
633
632
|
options: t.options,
|
|
634
633
|
arguments: t.arguments
|
|
635
634
|
};
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
635
|
+
if (!this._preHandler && this.preHandle && (this._preHandler = this.preHandle.bind(this)), this._preHandler) {
|
|
636
|
+
const n = await this._preHandler(t.ctx, e);
|
|
637
|
+
if (n && n !== 0)
|
|
638
|
+
return n;
|
|
639
|
+
}
|
|
639
640
|
if (!this._handler && this.handle)
|
|
640
641
|
this._handler = this.handle.bind(this);
|
|
641
642
|
else if (!this._handler)
|
|
@@ -658,24 +659,24 @@ class $ extends k {
|
|
|
658
659
|
* Example: "migrate {name} {--force}" -> { command: "migrate", arguments: {name: ...}, options: {force: ...} }
|
|
659
660
|
*/
|
|
660
661
|
static parseSignature(t, e, i) {
|
|
661
|
-
const [n, ...s] = t.split(/\{(.*?)\}/g).map((
|
|
662
|
-
for (const
|
|
663
|
-
const { name: h, isOption: l, definition: d } = $.parseParamSignature(
|
|
664
|
-
l ? o[h] = d :
|
|
662
|
+
const [n, ...s] = t.split(/\{(.*?)\}/g).map((m) => m.trim()).filter(Boolean), o = {}, u = {};
|
|
663
|
+
for (const m of s) {
|
|
664
|
+
const { name: h, isOption: l, definition: d } = $.parseParamSignature(m, e);
|
|
665
|
+
l ? o[h] = d : u[h] = d;
|
|
665
666
|
}
|
|
666
|
-
for (const
|
|
667
|
-
o[
|
|
668
|
-
type:
|
|
669
|
-
required:
|
|
670
|
-
alias:
|
|
671
|
-
variadic:
|
|
672
|
-
description:
|
|
673
|
-
default:
|
|
667
|
+
for (const m of i)
|
|
668
|
+
o[m.option] = {
|
|
669
|
+
type: m.type,
|
|
670
|
+
required: m.required,
|
|
671
|
+
alias: m.alias,
|
|
672
|
+
variadic: m.variadic ?? !1,
|
|
673
|
+
description: m.description,
|
|
674
|
+
default: m.default ?? null
|
|
674
675
|
};
|
|
675
676
|
return {
|
|
676
677
|
command: n,
|
|
677
678
|
options: o,
|
|
678
|
-
arguments:
|
|
679
|
+
arguments: u
|
|
679
680
|
};
|
|
680
681
|
}
|
|
681
682
|
/**
|
|
@@ -702,16 +703,16 @@ class $ extends k {
|
|
|
702
703
|
variadic: !1
|
|
703
704
|
};
|
|
704
705
|
if (i.includes(":")) {
|
|
705
|
-
const [o,
|
|
706
|
-
i = o.trim(), s.description =
|
|
706
|
+
const [o, u] = i.split(":");
|
|
707
|
+
i = o.trim(), s.description = u.trim();
|
|
707
708
|
}
|
|
708
709
|
if (i.includes("=")) {
|
|
709
|
-
const [o,
|
|
710
|
-
i = o.trim(), s.default =
|
|
710
|
+
const [o, u] = i.split("=");
|
|
711
|
+
i = 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");
|
|
711
712
|
} else i.startsWith("--") && (s.required = !1, s.default = !1, s.type = "boolean");
|
|
712
713
|
if (i.includes("|")) {
|
|
713
|
-
const [o, ...
|
|
714
|
-
i = o.trim(), s.alias =
|
|
714
|
+
const [o, ...u] = i.split("|");
|
|
715
|
+
i = o.trim(), s.alias = u.map((m) => m.trim());
|
|
715
716
|
}
|
|
716
717
|
return i.startsWith("--") && (n = !0, i = i.slice(2)), s.default === "*" && (s.default = [], s.type = ["string"]), i.endsWith("?") && (s.required = !1, i = i.slice(0, -1)), i.endsWith("*") && (s.type = ["string"], s.variadic = !0, s.default = [], i = i.slice(0, -1)), s.description = s.description ?? e[i] ?? e[`--${i}`], { name: i, isOption: n, definition: s };
|
|
717
718
|
}
|
|
@@ -783,7 +784,7 @@ class N {
|
|
|
783
784
|
this.shouldLog("debug") && console.log(...t);
|
|
784
785
|
}
|
|
785
786
|
}
|
|
786
|
-
class
|
|
787
|
+
class D {
|
|
787
788
|
/**
|
|
788
789
|
* Generate bigrams (character pairs) from a string
|
|
789
790
|
*/
|
|
@@ -801,8 +802,8 @@ class H {
|
|
|
801
802
|
if (t.length < 2 || e.length < 2) return 0;
|
|
802
803
|
const i = this.getBigrams(t), n = this.getBigrams(e), s = new Set(n);
|
|
803
804
|
let o = 0;
|
|
804
|
-
for (const
|
|
805
|
-
s.has(
|
|
805
|
+
for (const u of i)
|
|
806
|
+
s.has(u) && (o++, s.delete(u));
|
|
806
807
|
return 2 * o / (i.length + n.length);
|
|
807
808
|
}
|
|
808
809
|
/**
|
|
@@ -834,7 +835,7 @@ class j {
|
|
|
834
835
|
constructor(t) {
|
|
835
836
|
this.logger = t?.logger ?? new N(), this.io = this.newCommandIO({
|
|
836
837
|
logger: this.logger
|
|
837
|
-
}), this.stringSimilarity = t?.stringSimilarity ?? new
|
|
838
|
+
}), this.stringSimilarity = t?.stringSimilarity ?? new D();
|
|
838
839
|
}
|
|
839
840
|
getAvailableCommands() {
|
|
840
841
|
return Object.keys(this.commands);
|
|
@@ -887,17 +888,17 @@ class j {
|
|
|
887
888
|
}) ?? 0;
|
|
888
889
|
}
|
|
889
890
|
async suggestCommand(t) {
|
|
890
|
-
const e = this.getAvailableCommands(), { bestMatch: i, bestMatchIndex: n, ratings: s } = this.stringSimilarity.findBestMatch(t, e), o = s.filter((
|
|
891
|
+
const e = this.getAvailableCommands(), { bestMatch: i, bestMatchIndex: n, ratings: s } = this.stringSimilarity.findBestMatch(t, e), o = s.filter((u) => u.rating > 0.3).map((u) => u.target);
|
|
891
892
|
if (i.rating > 0 && o.length <= 1 || i.rating > 0.7 && o.length > 1) {
|
|
892
|
-
const
|
|
893
|
-
return await this.askRunSimilarCommand(t,
|
|
893
|
+
const u = e[n];
|
|
894
|
+
return await this.askRunSimilarCommand(t, u) ? u : null;
|
|
894
895
|
}
|
|
895
896
|
if (o.length) {
|
|
896
897
|
this.io.error(`${a.bgRed(" ERROR ")} Command ${a.yellow(t)} not found.
|
|
897
898
|
`);
|
|
898
|
-
const
|
|
899
|
-
if (
|
|
900
|
-
return
|
|
899
|
+
const u = await this.io.askForSelect(a.green("Did you mean to run one of these commands instead?"), o);
|
|
900
|
+
if (u)
|
|
901
|
+
return u;
|
|
901
902
|
}
|
|
902
903
|
throw new P(t);
|
|
903
904
|
}
|
|
@@ -937,7 +938,7 @@ class M extends v {
|
|
|
937
938
|
}), this.opts = t;
|
|
938
939
|
}
|
|
939
940
|
async handle() {
|
|
940
|
-
const t = this.opts.commandRegistry.getCommands(), e = this.opts.cliName ?? "Bob CLI", i = this.opts.cliVersion ?? "0.0.0", n = (await import("../package-
|
|
941
|
+
const t = this.opts.commandRegistry.getCommands(), e = this.opts.cliName ?? "Bob CLI", i = this.opts.cliVersion ?? "0.0.0", n = (await import("../package-BBcsXm_8.js"))?.default?.version ?? "0.0.0";
|
|
941
942
|
this.io.log(`${e} ${a.green(i)} (core: ${a.yellow(n)})
|
|
942
943
|
|
|
943
944
|
${a.yellow("Usage")}:
|
|
@@ -945,19 +946,19 @@ ${a.yellow("Usage")}:
|
|
|
945
946
|
|
|
946
947
|
${a.yellow("Available commands")}:
|
|
947
948
|
`);
|
|
948
|
-
const s = Math.max(...t.map((
|
|
949
|
-
for (const
|
|
950
|
-
const h =
|
|
951
|
-
o[h] || (o[h] = []), o[h].push(
|
|
949
|
+
const s = Math.max(...t.map((m) => m.command.length)) ?? 0, o = {};
|
|
950
|
+
for (const m of t) {
|
|
951
|
+
const h = m.group ?? m.command.split(":")[0];
|
|
952
|
+
o[h] || (o[h] = []), o[h].push(m);
|
|
952
953
|
}
|
|
953
|
-
const
|
|
954
|
-
for (const [
|
|
954
|
+
const u = Object.entries(o).sort(([m], [h]) => m.toLowerCase().localeCompare(h.toLowerCase())).sort(([, m], [, h]) => m.length - h.length);
|
|
955
|
+
for (const [m, h] of u) {
|
|
955
956
|
const l = h.length > 1;
|
|
956
|
-
l && this.io.log(a.yellow(`${
|
|
957
|
-
const d = h.sort((
|
|
958
|
-
for (const
|
|
959
|
-
let
|
|
960
|
-
l && (
|
|
957
|
+
l && this.io.log(a.yellow(`${m}:`));
|
|
958
|
+
const d = h.sort((p, c) => p.command.toLowerCase().localeCompare(c.command.toLowerCase()));
|
|
959
|
+
for (const p of d) {
|
|
960
|
+
let c = A(s - p.command.length);
|
|
961
|
+
l && (c = c.slice(2)), this.io.log(`${l ? " " : ""}${a.green(p.command)} ${c} ${p.description}`);
|
|
961
962
|
}
|
|
962
963
|
}
|
|
963
964
|
}
|
|
@@ -1021,10 +1022,10 @@ export {
|
|
|
1021
1022
|
$ as CommandSignatureParser,
|
|
1022
1023
|
z as CommandWithSignature,
|
|
1023
1024
|
W as ExceptionHandler,
|
|
1024
|
-
|
|
1025
|
+
H as HelpOption,
|
|
1025
1026
|
b as InvalidOption,
|
|
1026
1027
|
N as Logger,
|
|
1027
1028
|
F as MissingRequiredArgumentValue,
|
|
1028
1029
|
V as MissingRequiredOptionValue,
|
|
1029
|
-
|
|
1030
|
+
D as StringSimilarity
|
|
1030
1031
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "bob-core",
|
|
3
|
-
"version": "2.0.0-beta.
|
|
3
|
+
"version": "2.0.0-beta.18",
|
|
4
4
|
"description": "BOB Core",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/cjs/src/index.js",
|
|
@@ -48,7 +48,7 @@
|
|
|
48
48
|
"tsx": "^4.20.6",
|
|
49
49
|
"typescript": "^5.9.3",
|
|
50
50
|
"typescript-eslint": "^8.46.0",
|
|
51
|
-
"vite": "^7.
|
|
51
|
+
"vite": "^7.2.7",
|
|
52
52
|
"vite-plugin-dts": "^4.5.4",
|
|
53
53
|
"vitest": "^3.2.4"
|
|
54
54
|
},
|