@stricli/core 1.2.4 → 1.2.5

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/index.cjs CHANGED
@@ -1,23 +1,2286 @@
1
- "use strict";var ie=Object.defineProperty;var Ge=Object.getOwnPropertyDescriptor;var je=Object.getOwnPropertyNames;var Ue=Object.prototype.hasOwnProperty;var qe=(e,t)=>{for(var n in t)ie(e,n,{get:t[n],enumerable:!0})},Ve=(e,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of je(t))!Ue.call(e,r)&&r!==n&&ie(e,r,{get:()=>t[r],enumerable:!(a=Ge(t,r))||a.enumerable});return e};var We=e=>Ve(ie({},"__esModule",{value:!0}),e);var yn={};qe(yn,{AliasNotFoundError:()=>k,ArgumentParseError:()=>I,ArgumentScannerError:()=>A,EnumValidationError:()=>U,ExitCode:()=>h,FlagNotFoundError:()=>$,InvalidNegatedFlagSyntaxError:()=>K,UnexpectedFlagError:()=>z,UnexpectedPositionalError:()=>q,UnsatisfiedFlagError:()=>O,UnsatisfiedPositionalError:()=>V,booleanParser:()=>pe,buildApplication:()=>be,buildChoiceParser:()=>Be,buildCommand:()=>Ie,buildRouteMap:()=>De,formatMessageForArgumentScannerError:()=>ee,generateHelpTextForAllCommands:()=>Se,looseBooleanParser:()=>Q,numberParser:()=>Z,proposeCompletions:()=>ve,run:()=>Cn,text_en:()=>me});module.exports=We(yn);function J(e,t){let n=e.env?.[t];return typeof n=="string"&&n!=="0"}var h={UnknownCommand:-5,InvalidArgument:-4,ContextLoadError:-3,CommandLoadError:-2,InternalError:-1,Success:0,CommandRunError:1};function D(e){return e.replace(/-./g,t=>t[1].toUpperCase())}function F(e){return Array.from(e).map((t,n)=>{let a=t.toUpperCase(),r=t.toLowerCase();return n===0||a!==t||a===r?t:`-${r}`}).join("")}function He(e){let t=new Map;return{get:(...n)=>t.get(n.join(","))??e,set:(n,...a)=>{t.set(a.join(","),n)}}}function _e(e,t,n){let{threshold:a,weights:r}=n;if(e===t)return 0;let i=Math.abs(e.length-t.length);if(typeof a=="number"&&i>a)return 1/0;let o=He(1/0);o.set(0,-1,-1);for(let s=0;s<t.length;++s)o.set((s+1)*r.insertion,-1,s);for(let s=0;s<e.length;++s)o.set((s+1)*r.deletion,s,-1);let d=-1/0;for(let s=0;s<e.length;++s){let u=1/0;for(let l=0;l<=t.length-1;++l){let p=e[s]===t[l]?0:1,c=[o.get(s-1,l)+r.deletion,o.get(s,l-1)+r.insertion,o.get(s-1,l-1)+p*r.substitution];e[s]===t[l-1]&&e[s-1]===t[l]&&c.push(o.get(s-2,l-2)+p*r.transposition);let f=Math.min(...c);o.set(f,s,l),f<u&&(u=f)}if(u>a){if(d>a)return 1/0;d=u}else d=-1/0}let m=o.get(e.length-1,t.length-1);return m>a?1/0:m}function Ke(e,t,n){let a=e[1]-t[1];if(a!==0)return a;let r=e[0].startsWith(n),i=t[0].startsWith(n);return r&&!i?-1:!r&&i?1:e[0].localeCompare(t[0])}function G(e,t,n){let a=t.map(i=>[i,_e(e,i,n)]).filter(([,i])=>i<=n.threshold),r=Math.min(...a.map(([,i])=>i));return a.filter(([,i])=>i===r).sort((i,o)=>Ke(i,o,e)).map(([i])=>i)}var C=class extends Error{};function H(e){return e instanceof Error?e.stack??String(e):String(e)}function ze(e,t){let n=[],a=Math.max(e.length,t.length);for(let r=0;r<a;++r)n[r]=Math.max(e[r],t[r]);return n}function L(e,t){if(e.length===0)return[];let n=Array(Math.max(...e.map(r=>r.length))).fill(0,0),a=e.reduce((r,i)=>{let o=i.map(d=>d.length);return ze(r,o)},n);return e.map(r=>{let i=(r[0]??"").padEnd(a[0]);return r.slice(1).reduce((o,d,m,s)=>{let u=s.length===m+1?d:d.padEnd(a[m+1]);return[...o,t?.[m]??" ",u]},[i]).join("").trimEnd()})}function _(e,t){if(e.length<=1)return e[0]??"";if(e.length===2)return e.join(` ${t.conjunction} `);let n=e.slice(0,e.length-1).join(", ");return t.serialComma&&(n+=","),[n,t.conjunction,e[e.length-1]].join(" ")}function Je(e,t){return e.reduce((n,a)=>{let r=t(a),i=n[r]??[];return i.push(a),n[r]=i,n},{})}function ue(e,t){return Je(e,n=>n[t])}async function Y(e){let t=await Promise.allSettled(e),n=ue(t,"status");return n.rejected&&n.rejected.length>0?{status:"rejected",reasons:n.rejected.map(a=>a.reason)}:{status:"fulfilled",value:n.fulfilled?.map(a=>a.value)??[]}}var pe=e=>{switch(e.toLowerCase()){case"true":return!0;case"false":return!1}throw new SyntaxError(`Cannot convert ${e} to a boolean`)},Ye=new Set(["true","t","yes","y","on","1"]),Qe=new Set(["false","f","no","n","off","0"]),Q=e=>{let t=e.toLowerCase();if(Ye.has(t))return!0;if(Qe.has(t))return!1;throw new SyntaxError(`Cannot convert ${e} to a boolean`)};var Z=e=>{let t=Number(e);if(Number.isNaN(t))throw new SyntaxError(`Cannot convert ${e} to a number`);return t};var A=class extends C{_brand};function ee(e,t){let n=e.constructor.name,a=t[n];return a?a(e):e.message}function Ze(e,t,n){return Object.fromEntries(Object.entries(t).map(([a,r])=>{let i=r,o=e[i];if(!o){let d=w(i,n);throw new $(d,[],a)}return[a,[i,o]]}))}var $=class extends A{input;corrections;aliasName;constructor(t,n,a){let r=`No flag registered for --${t}`;if(a)r+=` (aliased from -${a})`;else if(n.length>0){let i=_(n.map(o=>`--${o}`),{kind:"conjunctive",conjunction:"or",serialComma:!0});r+=`, did you mean ${i}?`}super(r),this.input=t,this.corrections=n,this.aliasName=a}},k=class extends A{input;constructor(t){super(`No alias registered for -${t}`),this.input=t}};function se(e,t){return e.placeholder?e.placeholder:typeof t=="number"?`arg${t}`:"args"}function w(e,t){return t==="allow-kebab-for-camel"?F(e):e}var I=class extends A{externalFlagNameOrPlaceholder;input;exception;constructor(t,n,a){super(`Failed to parse "${n}" for ${t}: ${a instanceof Error?a.message:String(a)}`),this.externalFlagNameOrPlaceholder=t,this.input=n,this.exception=a}};function j(e,t,n,a){try{return t.parse.call(a,n)}catch(r){throw new I(e,n,r)}}var U=class extends A{externalFlagName;input;values;constructor(t,n,a,r){let i=`Expected "${n}" to be one of (${a.join("|")})`;if(r.length>0){let o=_(r.map(d=>`"${d}"`),{kind:"conjunctive",conjunction:"or",serialComma:!0});i+=`, did you mean ${o}?`}super(i),this.externalFlagName=t,this.input=n,this.values=a}},O=class extends A{externalFlagName;nextFlagName;constructor(t,n){let a=`Expected input for flag --${t}`;n&&(a+=` but encountered --${n} instead`),super(a),this.externalFlagName=t,this.nextFlagName=n}},q=class extends A{expectedCount;input;constructor(t,n){super(`Too many arguments, expected ${t} but encountered "${n}"`),this.expectedCount=t,this.input=n}},V=class extends A{placeholder;limit;constructor(t,n){let a;n?(a=`Expected at least ${n[0]} argument(s) for ${t}`,n[1]===0?a+=" but found none":a+=` but only found ${n[1]}`):a=`Expected argument for ${t}`,super(a),this.placeholder=t,this.limit=n}};function ce(e){if(e.startsWith("no")&&e.length>2){if(e[2]==="-")return e.slice(4);let t=e[2],n=t.toUpperCase();return t!==n?void 0:t.toLowerCase()+e.slice(3)}}function ge(e,t,n){let a=e,r=t[a];if(!r){let o=ce(a);if(o&&(r=t[o],r&&r.kind=="boolean"))return{namedFlag:[o,r],negated:!0}}let i=D(e);if(n.caseStyle==="allow-kebab-for-camel"&&!r){if(r=t[i],r)return{namedFlag:[i,r]};let o=ce(i);if(o&&(r=t[o],r&&r.kind=="boolean"))return{namedFlag:[o,r],negated:!0}}if(!r){if(i in t)throw new $(e,[i]);let o=F(e);if(o in t)throw new $(e,[o]);let d=G(a,Object.keys(t),n.distanceOptions);throw new $(e,d)}return{namedFlag:[a,r]}}function fe(e){return e.namedFlag[1].kind==="boolean"||e.namedFlag[1].kind==="counter"}var Ce=/^-([a-z]+)$/i,en=/^--([a-z][a-z-.\d_]+)$/i;function nn(e,t,n,a){let r=Ce.exec(e);if(r){let o=r[1];return Array.from(o).map(d=>{let m=d,s=n[m];if(!s)throw new k(m);return{namedFlag:s}})}let i=en.exec(e);if(i){let o=i[1];return[ge(o,t,a)]}return[]}var tn=/^--([a-z][a-z-.\d_]+)=(.+)$/i,rn=/^-([a-z])=(.+)$/i,K=class extends A{externalFlagName;valueText;constructor(t,n){super(`Cannot negate flag --${t} and pass "${n}" as value`),this.externalFlagName=t,this.valueText=n}};function on(e,t,n,a){let r=tn.exec(e);if(r){let o=r[1],{namedFlag:d,negated:m}=ge(o,t,a),s=r[2];if(m)throw new K(o,s);return[d,s]}let i=rn.exec(e);if(i){let o=i[1],d=n[o];if(!d)throw new k(o);let m=i[2];return[d,m]}}async function an(e,t,n,a,r){if(!n){if("default"in t&&typeof t.default<"u")return t.kind==="boolean"||t.kind==="enum"?t.default:j(e,t,t.default,r);if(t.optional)return;if(t.kind==="boolean")return!1;if(t.kind==="counter")return 0;throw new O(e)}if(t.kind==="counter")return n.reduce((o,d)=>{try{return o+Z.call(r,d)}catch(m){throw new I(e,d,m)}},0);if("variadic"in t&&t.variadic){if(t.kind==="enum"){for(let o of n)if(!t.values.includes(o)){let d=G(o,t.values,a.distanceOptions);throw new U(e,o,t.values,d)}return n}return Promise.all(n.map(o=>j(e,t,o,r)))}let i=n[0];if(t.kind==="boolean")try{return Q.call(r,i)}catch(o){throw new I(e,i,o)}if(t.kind==="enum"){if(!t.values.includes(i)){let o=G(i,t.values,a.distanceOptions);throw new U(e,i,t.values,o)}return i}return j(e,t,i,r)}var z=class extends A{externalFlagName;previousInput;input;constructor(t,n,a){super(`Too many arguments for --${t}, encountered "${a}" after "${n}"`),this.externalFlagName=t,this.previousInput=n,this.input=a}};function ye(e){return e.kind==="counter"?!0:"variadic"in e?!!e.variadic:!1}function B(e,t,[n,a],r){let i=e.get(n)??[];if(i.length>0&&!ye(a)){let o=w(n,t);throw new z(o,i[0],r)}if("variadic"in a&&typeof a.variadic=="string"){let o=r.split(a.variadic);e.set(n,[...i,...o])}else e.set(n,[...i,r])}function le(e,t,n){if(t.get(n)){let r=e[n];return!ye(r)}return!1}function ne(e,t){let{flags:n={},aliases:a={},positional:r={kind:"tuple",parameters:[]}}=e,i=Ze(n,a,t.caseStyle),o=[],d=new Map,m=0,s,u=!1;return{next:l=>{if(!u&&t.allowArgumentEscapeSequence&&l==="--"){if(s)if(s[1].kind==="parsed"&&s[1].inferEmpty)B(d,t.caseStyle,s,""),s=void 0;else{let p=w(s[0],t.caseStyle);throw new O(p)}u=!0;return}if(!u){let p=on(l,n,i,t);if(p){if(s)if(s[1].kind==="parsed"&&s[1].inferEmpty)B(d,t.caseStyle,s,""),s=void 0;else{let f=w(s[0],t.caseStyle),T=w(p[0][0],t.caseStyle);throw new O(f,T)}B(d,t.caseStyle,...p);return}let c=nn(l,n,i,t);if(c.length>0){if(s)if(s[1].kind==="parsed"&&s[1].inferEmpty)B(d,t.caseStyle,s,""),s=void 0;else{let f=w(s[0],t.caseStyle),T=w(c[0].namedFlag[0],t.caseStyle);throw new O(f,T)}if(c.every(fe))for(let f of c)f.namedFlag[1].kind==="boolean"?B(d,t.caseStyle,f.namedFlag,f.negated?"false":"true"):B(d,t.caseStyle,f.namedFlag,"1");else if(c.length>1){let f=c.find(E=>!fe(E)),T=w(f.namedFlag[0],t.caseStyle);throw new O(T)}else s=c[0].namedFlag;return}}if(s)B(d,t.caseStyle,s,l),s=void 0;else{if(r.kind==="tuple"){if(m>=r.parameters.length)throw new q(r.parameters.length,l)}else if(typeof r.maximum=="number"&&m>=r.maximum)throw new q(r.maximum,l);o[m]=l,++m}},parseArguments:async l=>{let p=[],c;r.kind==="array"?(typeof r.minimum=="number"&&m<r.minimum&&p.push(new V(se(r.parameter),[r.minimum,m])),c=Y(o.map(async(g,x)=>{let y=se(r.parameter,x+1);return j(y,r.parameter,g,l)}))):c=Y(r.parameters.map(async(g,x)=>{let y=se(g,x+1),N=o[x];if(typeof N!="string"){if(typeof g.default=="string")return j(y,g,g.default,l);if(g.optional)return;throw new V(y)}return j(y,g,N,l)})),s&&s[1].kind==="parsed"&&s[1].inferEmpty&&(B(d,t.caseStyle,s,""),s=void 0);let f=Y(Object.entries(n).map(async g=>{let[x,y]=g,N=w(x,t.caseStyle);if(s&&s[0]===x)throw new O(N);let b=d.get(x),X=await an(N,y,b,t,l);return[x,X]})),[T,E]=await Promise.all([c,f]);if(T.status==="rejected")for(let g of T.reasons)p.push(g);if(E.status==="rejected")for(let g of E.reasons)p.push(g);if(p.length>0)return{success:!1,errors:p};if(T.status==="rejected")throw new C("Unknown failure while scanning positional arguments");if(E.status==="rejected")throw new C("Unknown failure while scanning flag arguments");return{success:!0,arguments:[Object.fromEntries(E.value),...T.value]}},proposeCompletions:async({partial:l,completionConfig:p,text:c,context:f,includeVersionFlag:T})=>{if(s)return xe(s[1],f,l);let E=[];if(!u){let S=Ce.exec(l);if(p.includeAliases){if(l===""||l==="-"){let g=Object.entries(a).filter(x=>!le(n,d,x[1]));for(let[x]of g){let y=i[x];y&&E.push({kind:"argument:flag",completion:`-${x}`,brief:y[1].brief})}}else if(S){let g=Array.from(S[1]);if(g.includes("h"))return[];if(T&&g.includes("v"))return[];let x=new Map(d);for(let b of g){let X=i[b];if(!X)throw new k(b);B(x,t.caseStyle,X,X[1].kind==="boolean"?"true":"1")}let y=g[g.length-1];if(y){let b=i[y];b&&E.push({kind:"argument:flag",completion:l,brief:b[1].brief})}let N=Object.entries(a).filter(b=>!le(n,x,b[1]));for(let[b]of N){let X=i[b];X&&E.push({kind:"argument:flag",completion:`${l}${b}`,brief:X[1].brief})}}}if(l===""||l==="-"||l.startsWith("--")){t.allowArgumentEscapeSequence&&E.push({kind:"argument:flag",completion:"--",brief:c.briefs.argumentEscapeSequence});let g=Object.entries(n).filter(([y])=>!le(n,d,y));t.caseStyle==="allow-kebab-for-camel"&&(g=g.map(([y,N])=>[F(y),N]));let x=g.map(([y,N])=>[`--${y}`,N]).filter(([y])=>y.startsWith(l));E.push(...x.map(([y,N])=>({kind:"argument:flag",completion:y,brief:N.brief})))}}if(r.kind==="array"){if(r.parameter.proposeCompletions&&(typeof r.maximum!="number"||m<r.maximum)){let S=await r.parameter.proposeCompletions.call(f,l);E.push(...S.map(g=>({kind:"argument:value",completion:g,brief:r.parameter.brief})))}}else{let S=r.parameters[m];if(S?.proposeCompletions){let g=await S.proposeCompletions.call(f,l);E.push(...g.map(x=>({kind:"argument:value",completion:x,brief:S.brief})))}}return E.filter(({completion:S})=>S.startsWith(l))}}}async function xe(e,t,n){if(typeof e.variadic=="string"&&n.endsWith(e.variadic))return xe(e,t,"");let a;return e.kind==="enum"?a=e.values:e.proposeCompletions?a=await e.proposeCompletions.call(t,n):a=[],a.map(r=>({kind:"argument:value",completion:r,brief:e.brief})).filter(({completion:r})=>r.startsWith(n))}function Te(e,t,n){let a=t==="allow-kebab-for-camel"?"convert-camel-to-kebab":t,r=e.getAllEntries();return n.includeHiddenRoutes||(r=r.filter(i=>!i.hidden)),r.flatMap(i=>{let o=i.name[a];return n.includeAliases?[o,...i.aliases]:[o]})}var me={headers:{usage:"USAGE",aliases:"ALIASES",commands:"COMMANDS",flags:"FLAGS",arguments:"ARGUMENTS"},keywords:{default:"default =",separator:"separator ="},briefs:{help:"Print help information and exit",helpAll:"Print help information (including hidden commands/flags) and exit",version:"Print version information and exit",argumentEscapeSequence:"All subsequent inputs should be interpreted as arguments"},noCommandRegisteredForInput:({input:e,corrections:t})=>{let n=`No command registered for \`${e}\``;if(t.length>0){let a=_(t,{kind:"conjunctive",conjunction:"or",serialComma:!0});return`${n}, did you mean ${a}?`}else return n},noTextAvailableForLocale:({requestedLocale:e,defaultLocale:t})=>`Application does not support "${e}" locale, defaulting to "${t}"`,exceptionWhileParsingArguments:e=>e instanceof A?ee(e,{}):`Unable to parse arguments, ${H(e)}`,exceptionWhileLoadingCommandFunction:e=>`Unable to load command function, ${H(e)}`,exceptionWhileLoadingCommandContext:e=>`Unable to load command context, ${H(e)}`,exceptionWhileRunningCommand:e=>`Command failed, ${H(e)}`,commandErrorResult:e=>e.message,currentVersionIsNotLatest:({currentVersion:e,latestVersion:t,upgradeCommand:n})=>n?`Latest available version is ${t} (currently running ${e}), upgrade with "${n}"`:`Latest available version is ${t} (currently running ${e})`};function Fe(e){if(e.startsWith("en"))return me}function P(e,t,n){return!n.disableAnsiColor&&!J(e,"STRICLI_NO_COLOR")&&(t.getColorDepth?.(e.env)??1)>=4}async function Ee({loader:e,parameters:t},{context:n,inputs:a,scannerConfig:r,errorFormatting:i,documentationConfig:o,determineExitCode:d}){let m=e(),s;try{let l=ne(t,r);for(let c of a)l.next(c);let p=await l.parseArguments(n);if(p.success)s=p.arguments;else{let c=P(n.process,n.process.stderr,o);for(let f of p.errors){let T=i.exceptionWhileParsingArguments(f,c);n.process.stderr.write(c?`\x1B[1m\x1B[31m${T}\x1B[39m\x1B[22m
2
- `:`${T}
3
- `)}return h.InvalidArgument}}catch(l){let p=P(n.process,n.process.stderr,o),c=i.exceptionWhileParsingArguments(l,p);return n.process.stderr.write(p?`\x1B[1m\x1B[31m${c}\x1B[39m\x1B[22m
4
- `:`${c}
5
- `),h.InvalidArgument}let u;try{let l=await m;typeof l=="function"?u=l:u=l.default}catch(l){let p=P(n.process,n.process.stderr,o),c=i.exceptionWhileLoadingCommandFunction(l,p);return n.process.stderr.write(p?`\x1B[1m\x1B[31m${c}\x1B[39m\x1B[22m
6
- `:`${c}
7
- `),h.CommandLoadError}try{let l=await u.call(n,...s);if(l instanceof Error){let p=P(n.process,n.process.stderr,o),c=i.commandErrorResult(l,p);return n.process.stderr.write(p?`\x1B[1m\x1B[31m${c}\x1B[39m\x1B[22m
8
- `:`${c}
9
- `),d?d(l):h.CommandRunError}}catch(l){let p=P(n.process,n.process.stderr,o),c=i.exceptionWhileRunningCommand(l,p);return n.process.stderr.write(p?`\x1B[1m\x1B[31m${c}\x1B[39m\x1B[22m
10
- `:`${c}
11
- `),d?d(l):h.CommandRunError}return h.Success}var R=Symbol("RouteMap");var v=Symbol("Command");function te(e,t,n){let a=[...n],r=[],i,o=e,d,m=!0,s=!1;return{next:u=>{if(u==="--help"||u==="-h"){s=!0,d||(d=o);return}else if(u==="--helpAll"||u==="--help-all"||u==="-H"){s="all",d||(d=o);return}if(d){r.push(u);return}if(o.kind===v){d=o,r.push(u);return}let l=D(u),p=u,c=o.getRoutingTargetForInput(p);if(t.caseStyle==="allow-kebab-for-camel"&&!c&&(c=o.getRoutingTargetForInput(l),c&&(p=l)),!c){let f=o.getDefaultCommand();if(f){m=!1,i=[o,""],r.push(u),o=f;return}return{input:u,routeMap:o}}m=!1,i=[o,u],o=c,a.push(u)},finish:()=>{if(d=d??o,d.kind===R&&!s){let l=d.getDefaultCommand();l&&(i=[d,""],d=l,m=!1)}let u=i?i[0].getOtherAliasesForInput(i[1],t.caseStyle):{original:[],"convert-camel-to-kebab":[]};return{target:d,unprocessedInputs:r,helpRequested:s,prefix:a,rootLevel:m,aliases:u}}}}async function Ae({root:e,defaultText:t,config:n},a,r){let i=t;if(r.locale){let l=n.localization.loadText(r.locale);if(l)i=l;else{let p=P(r.process,r.process.stderr,n.documentation),c=i.noTextAvailableForLocale({requestedLocale:r.locale,defaultLocale:n.localization.defaultLocale,ansiColor:p});r.process.stderr.write(p?`\x1B[1m\x1B[33m${c}\x1B[39m\x1B[22m
12
- `:`${c}
13
- `)}}if(n.versionInfo?.getLatestVersion&&!J(r.process,"STRICLI_SKIP_VERSION_CHECK")){let l;"currentVersion"in n.versionInfo?l=n.versionInfo.currentVersion:l=await n.versionInfo.getCurrentVersion.call(r);let p=await n.versionInfo.getLatestVersion.call(r,l);if(p&&l!==p){let c=P(r.process,r.process.stderr,n.documentation),f=i.currentVersionIsNotLatest({currentVersion:l,latestVersion:p,upgradeCommand:n.versionInfo.upgradeCommand,ansiColor:c});r.process.stderr.write(c?`\x1B[1m\x1B[33m${f}\x1B[39m\x1B[22m
14
- `:`${f}
15
- `)}}let o=a.slice();if(n.versionInfo&&(o[0]==="--version"||o[0]==="-v")){let l;return"currentVersion"in n.versionInfo?l=n.versionInfo.currentVersion:l=await n.versionInfo.getCurrentVersion.call(r),r.process.stdout.write(l+`
16
- `),h.Success}let d=te(e,n.scanner,[n.name]),m;for(;o.length>0&&!m;){let l=o.shift();m=d.next(l)}if(m){let l=Te(m.routeMap,n.scanner.caseStyle,n.completion),p=G(m.input,l,n.scanner.distanceOptions).map(T=>`\`${T}\``),c=P(r.process,r.process.stderr,n.documentation),f=i.noCommandRegisteredForInput({input:m.input,corrections:p,ansiColor:c});return r.process.stderr.write(c?`\x1B[1m\x1B[31m${f}\x1B[39m\x1B[22m
17
- `:`${f}
18
- `),h.UnknownCommand}let s=d.finish();if(s.helpRequested||s.target.kind===R){let l=P(r.process,r.process.stdout,n.documentation);return r.process.stdout.write(s.target.formatHelp({prefix:s.prefix,includeVersionFlag:!!n.versionInfo&&s.rootLevel,includeArgumentEscapeSequenceFlag:n.scanner.allowArgumentEscapeSequence,includeHelpAllFlag:s.helpRequested==="all"||n.documentation.alwaysShowHelpAllFlag,includeHidden:s.helpRequested==="all",config:n.documentation,aliases:s.aliases[n.documentation.caseStyle],text:i,ansiColor:l})),h.Success}let u;if("forCommand"in r)try{u=await r.forCommand({prefix:s.prefix})}catch(l){let p=P(r.process,r.process.stderr,n.documentation),c=i.exceptionWhileLoadingCommandContext(l,p);return r.process.stderr.write(p?`\x1B[1m\x1B[31m${c}\x1B[39m\x1B[22m`:c),h.ContextLoadError}else u=r;return Ee(s.target,{context:u,inputs:s.unprocessedInputs,scannerConfig:n.scanner,documentationConfig:n.documentation,errorFormatting:i,determineExitCode:n.determineExitCode})}function W(e,t){return t==="convert-camel-to-kebab"?F(e):e}function he(e,t){return t==="convert-camel-to-kebab"?`no-${F(e)}`:`no${e[0].toUpperCase()}${e.slice(1)}`}function Ne(e){let t=e.scanner?.caseStyle??"original",n;if(e.documentation?.caseStyle){if(t==="original"&&e.documentation.caseStyle==="convert-camel-to-kebab")throw new C("Cannot convert route and flag names on display but scan as original");n=e.documentation.caseStyle}else t==="allow-kebab-for-camel"?n="convert-camel-to-kebab":n=t;let a={caseStyle:t,allowArgumentEscapeSequence:e.scanner?.allowArgumentEscapeSequence??!1,distanceOptions:e.scanner?.distanceOptions??{threshold:7,weights:{insertion:1,deletion:3,substitution:2,transposition:0}}},r={alwaysShowHelpAllFlag:e.documentation?.alwaysShowHelpAllFlag??!1,useAliasInUsageLine:e.documentation?.useAliasInUsageLine??!1,onlyRequiredInUsageLine:e.documentation?.onlyRequiredInUsageLine??!1,caseStyle:n,disableAnsiColor:e.documentation?.disableAnsiColor??!1},i={includeAliases:e.completion?.includeAliases??r.useAliasInUsageLine,includeHiddenRoutes:e.completion?.includeHiddenRoutes??!1,...e.completion};return{...e,scanner:a,completion:i,documentation:r,localization:{defaultLocale:"en",loadText:Fe,...e.localization}}}function be(e,t){let n=Ne(t);if(e.kind===v&&n.versionInfo){if(e.usesFlag("version"))throw new C("Unable to use command with flag --version as root when version info is supplied");if(e.usesFlag("v"))throw new C("Unable to use command with alias -v as root when version info is supplied")}let a=n.localization.loadText(n.localization.defaultLocale);if(!a)throw new C(`No text available for the default locale "${n.localization.defaultLocale}"`);return{root:e,config:n,defaultText:a}}function*Pe(e,t,n){for(let a of e.getAllEntries()){if(a.hidden)continue;let r=a.name[n],i=[...t,r];a.target.kind===R?yield*Pe(a.target,i,n):yield[i,a.target,a.aliases]}}function Se({root:e,defaultText:t,config:n},a){let r=t;if(a){let o=n.localization.loadText(a);if(o)r=o;else throw new C(`Application does not support "${a}" locale`)}let i=[];return e.kind===v?i.push([[n.name],e,[]]):i.push(...Pe(e,[n.name],n.documentation.caseStyle)),i.map(([o,d,m])=>[o.join(" "),d.formatHelp({prefix:o,config:n.documentation,includeVersionFlag:!!n.versionInfo&&o.length===1,includeArgumentEscapeSequenceFlag:n.scanner.allowArgumentEscapeSequence,includeHelpAllFlag:n.documentation.alwaysShowHelpAllFlag,includeHidden:!1,aliases:m,text:r,ansiColor:!1})])}async function Re({parameters:e},t){try{let n=ne(e,t.scannerConfig);for(let a of t.inputs)n.next(a);return await n.proposeCompletions(t)}catch{return[]}}async function Oe(e,{partial:t,scannerConfig:n,completionConfig:a}){let r=e.getAllEntries();a.includeHiddenRoutes||(r=r.filter(o=>!o.hidden));let i=n.caseStyle==="allow-kebab-for-camel"?"convert-camel-to-kebab":n.caseStyle;return r.flatMap(o=>{let d=o.target.kind===v?"routing-target:command":"routing-target:route-map",m=o.target.brief,s={kind:d,completion:o.name[i],brief:m};return a.includeAliases?[s,...o.aliases.map(u=>({kind:d,completion:u,brief:m}))]:[s]}).filter(({completion:o})=>o.startsWith(t))}async function ve({root:e,config:t,defaultText:n},a,r){if(a.length===0)return[];let i=te(e,t.scanner,[]),o=a.slice(0,-1),d;for(;o.length>0&&!d;){let l=o.shift();d=i.next(l)}if(d)return[];let m=i.finish();if(m.helpRequested)return[];let s;if("forCommand"in r)try{s=await r.forCommand({prefix:m.prefix})}catch{return[]}else s=r;let u=a[a.length-1];return m.target.kind===R?Oe(m.target,{context:s,partial:u,scannerConfig:t.scanner,completionConfig:t.completion}):Re(m.target,{context:s,inputs:m.unprocessedInputs,partial:u,scannerConfig:t.scanner,completionConfig:t.completion,text:n,includeVersionFlag:!!t.versionInfo&&m.rootLevel})}function sn(e,t){return e.includes(t)}function Be(e){return t=>{if(!sn(e,t))throw new SyntaxError(`${t} is not one of (${e.join("|")})`);return t}}function de(e){return"default"in e&&typeof e.default<"u"}function M(e){return e.optional??de(e)}function we(e){return`(${e})`}function Xe(e){return`[${e}]`}function $e(e){return`${e}...`}function ln(e){return`<${e}>`}function mn(e){return`[<${e}>]`}function dn(e){return`<${e}>...`}function re(e,t){let n=Object.entries(e.flags??{}).filter(([,i])=>!(i.hidden||t.config.onlyRequiredInUsageLine&&M(i))).map(([i,o])=>{let d=t.config.caseStyle==="convert-camel-to-kebab"?`--${F(i)}`:`--${i}`;if(e.aliases&&t.config.useAliasInUsageLine){let s=Object.entries(e.aliases).filter(u=>u[1]===i);s.length===1&&s[0]&&(d=`-${s[0][0]}`)}if(o.kind==="boolean")return[o,d];if(o.kind==="enum"&&typeof o.placeholder!="string")return[o,`${d} ${o.values.join("|")}`];let m=o.placeholder??"value";return[o,`${d} ${m}`]}).map(([i,o])=>i.kind==="parsed"&&i.variadic?M(i)?$e(Xe(o)):$e(we(o)):M(i)?Xe(o):we(o)),a=[],r=e.positional;if(r)if(r.kind==="array")a=[dn(r.parameter.placeholder??"args")];else{let i=r.parameters;t.config.onlyRequiredInUsageLine&&(i=i.filter(o=>!o.optional&&typeof o.default>"u")),a=i.map((o,d)=>{let m=o.placeholder??`arg${d+1}`;return o.optional||typeof o.default<"u"?mn(m):ln(m)})}return[...t.prefix,...n,...a].join(" ")}function oe(e,t,n){let{keywords:a,briefs:r}=n.text,i=Object.entries(e).filter(([,m])=>!(m.hidden&&!n.includeHidden)),o=i.some(([,m])=>M(m)),d=i.map(([m,s])=>{let u=Object.entries(t).filter(f=>f[1]===m).map(([f])=>`-${f}`),l="--"+W(m,n.config.caseStyle);if(s.kind==="boolean"&&s.default!==!1){let f=he(m,n.config.caseStyle);l=`${l}/--${f}`}M(s)?l=`[${l}]`:o&&(l=` ${l}`),s.kind==="parsed"&&s.variadic&&(l=`${l}...`);let p=[];if(s.kind==="enum"){let f=s.values.join("|");p.push(f)}if(de(s)){let f=n.ansiColor?`\x1B[90m${a.default}\x1B[39m`:a.default;p.push(`${f} ${s.default===""?'""':String(s.default)}`)}if("variadic"in s&&typeof s.variadic=="string"){let f=n.ansiColor?`\x1B[90m${a.separator}\x1B[39m`:a.separator;p.push(`${f} ${s.variadic}`)}let c=p.length>0?`[${p.join(", ")}]`:void 0;return{aliases:u.join(" "),flagName:l,brief:s.brief,suffix:c,hidden:s.hidden}});if(d.push({aliases:"-h",flagName:o?" --help":"--help",brief:r.help}),n.includeHelpAllFlag){let m=W("helpAll",n.config.caseStyle);d.push({aliases:"-H",flagName:o?` --${m}`:`--${m}`,brief:r.helpAll,hidden:!n.config.alwaysShowHelpAllFlag})}return n.includeVersionFlag&&d.push({aliases:"-v",flagName:o?" --version":"--version",brief:r.version}),n.includeArgumentEscapeSequenceFlag&&d.push({aliases:"",flagName:o?" --":"--",brief:r.argumentEscapeSequence}),L(d.map(m=>n.ansiColor?[m.hidden?`\x1B[90m${m.aliases}\x1B[39m`:`\x1B[97m${m.aliases}\x1B[39m`,m.hidden?`\x1B[90m${m.flagName}\x1B[39m`:`\x1B[97m${m.flagName}\x1B[39m`,m.hidden?`\x1B[90m${m.brief}\x1B[39m`:`\x1B[03m${m.brief}\x1B[23m`,m.suffix??""]:[m.aliases,m.flagName,m.brief,m.suffix??""]),[" "," "," "])}function*ae(e){if(yield e.config.useAliasInUsageLine?"-h":"--help",e.includeHelpAllFlag){let t=W("helpAll",e.config.caseStyle);yield e.config.useAliasInUsageLine?"-H":`--${t}`}e.includeVersionFlag&&(yield e.config.useAliasInUsageLine?"-v":"--version")}function Le(e,t){if(e.kind==="array"){let r=e.parameter.placeholder??"args",i=t.ansiColor?`\x1B[97m${r}...\x1B[39m`:`${r}...`,o=t.ansiColor?`\x1B[3m${e.parameter.brief}\x1B[23m`:e.parameter.brief;return L([[i,o]],[" "])}let{keywords:n}=t.text,a=e.parameters.some(r=>r.optional);return L(e.parameters.map((r,i)=>{let o=r.placeholder??`arg${i+1}`,d;return r.optional?o=`[${o}]`:a&&(o=` ${o}`),r.default&&(d=`[${t.ansiColor?`\x1B[90m${n.default}\x1B[39m`:n.default} ${r.default}]`),[t.ansiColor?`\x1B[97m${o}\x1B[39m`:o,t.ansiColor?`\x1B[3m${r.brief}\x1B[23m`:r.brief,d??""]}),[" "," "])}function*ke(e,t,n){let{brief:a,fullDescription:r,customUsage:i}=t,{headers:o}=n.text,d=n.prefix.join(" ");if(yield n.ansiColor?`\x1B[1m${o.usage}\x1B[22m`:o.usage,i)for(let s of i)if(typeof s=="string")yield` ${d} ${s}`;else{let u=n.ansiColor?`\x1B[3m${s.brief}\x1B[23m`:s.brief;yield` ${d} ${s.input}
19
- ${u}`}else yield` ${re(e,n)}`;for(let s of ae(n))yield` ${d} ${s}`;if(yield"",yield r??a,n.aliases&&n.aliases.length>0){let s=n.prefix.slice(0,-1).join(" ");yield"",yield n.ansiColor?`\x1B[1m${o.aliases}\x1B[22m`:o.aliases;for(let u of n.aliases)yield` ${s} ${u}`}yield"",yield n.ansiColor?`\x1B[1m${o.flags}\x1B[22m`:o.flags;for(let s of oe(e.flags??{},e.aliases??{},n))yield` ${s}`;let m=e.positional??{kind:"tuple",parameters:[]};if(m.kind==="array"||m.parameters.length>0){yield"",yield n.ansiColor?`\x1B[1m${o.arguments}\x1B[22m`:o.arguments;for(let s of Le(m,n))yield` ${s}`}}function un(e,t){for(let n of t)if(n in e)throw new C(`Unable to use reserved flag --${n}`)}function pn(e,t){for(let n of t)if(n in e)throw new C(`Unable to use reserved alias -${n}`)}function*cn(e){yield`no-${F(e)}`,yield`no${e[0].toUpperCase()}${e.slice(1)}`}function fn(e){let t=Object.entries(e).filter(([,n])=>n.kind==="boolean"&&!n.optional);for(let[n]of t)for(let a of cn(n))if(a in e)throw new C(`Unable to allow negation for --${n} as it conflicts with --${a}`)}function gn(e){for(let[t,n]of Object.entries(e))if("variadic"in n&&typeof n.variadic=="string"){if(n.variadic.length<1)throw new C(`Unable to use "" as variadic separator for --${t} as it is empty`);if(/\s/.test(n.variadic))throw new C(`Unable to use "${n.variadic}" as variadic separator for --${t} as it contains whitespace`)}}function Ie(e){let{flags:t={},aliases:n={}}=e.parameters;un(t,["help","helpAll","help-all"]),pn(n,["h","H"]),fn(t),gn(t);let a;return"func"in e?a=async()=>e.func:a=e.loader,{kind:v,loader:a,parameters:e.parameters,get brief(){return e.docs.brief},formatUsageLine:r=>re(e.parameters,r),formatHelp:r=>[...ke(e.parameters,e.docs,r)].join(`
20
- `)+`
21
- `,usesFlag:r=>r in t||r in n}}function*Me(e,t,n){let{brief:a,fullDescription:r,hideRoute:i}=t,{headers:o}=n.text;yield n.ansiColor?`\x1B[1m${o.usage}\x1B[22m`:o.usage;for(let[l,p]of Object.entries(e))if(!i||!i[l]||n.includeHidden){let c=n.config.caseStyle==="convert-camel-to-kebab"?F(l):l;yield` ${p.formatUsageLine({...n,prefix:[...n.prefix,c]})}`}let d=n.prefix.join(" ");for(let l of ae(n))yield` ${d} ${l}`;if(yield"",yield r??a,n.aliases&&n.aliases.length>0){let l=n.prefix.slice(0,-1).join(" ");yield"",yield n.ansiColor?`\x1B[1m${o.aliases}\x1B[22m`:o.aliases;for(let p of n.aliases)yield` ${l} ${p}`}yield"",yield n.ansiColor?`\x1B[1m${o.flags}\x1B[22m`:o.flags;for(let l of oe({},{},n))yield` ${l}`;yield"",yield n.ansiColor?`\x1B[1m${o.commands}\x1B[22m`:o.commands;let s=Object.entries(e).filter(([l])=>!i||!i[l]||n.includeHidden).map(([l,p])=>({routeName:W(l,n.config.caseStyle),brief:p.brief,hidden:i&&i[l]})),u=L(s.map(l=>n.ansiColor?[l.hidden?`\x1B[90m${l.routeName}\x1B[39m`:`\x1B[97m${l.routeName}\x1B[39m`,l.hidden?`\x1B[90m${l.brief}\x1B[39m`:`\x1B[03m${l.brief}\x1B[23m`]:[l.routeName,l.brief]),[" "]);for(let l of u)yield` ${l}`}function De({routes:e,defaultCommand:t,docs:n,aliases:a}){if(Object.entries(e).length===0)throw new C("Route map must contain at least one route");let r=a??{},i=new Map;for(let[m,s]of Object.entries(r)){if(m in e)throw new C(`Cannot use "${m}" as an alias when a route with that name already exists`);let u=i.get(s)??[];i.set(s,[...u,m])}let o=t?e[t]:void 0;if(o&&o.kind===R)throw new C(`Cannot use "${t}" as the default command because it is not a Command`);let d=m=>{if(m in r)return r[m];if(m in e)return m};return{kind:R,get brief(){return n.brief},formatUsageLine(m){let s=this.getAllEntries().filter(u=>!u.hidden).map(u=>u.name[m.config.caseStyle]);return`${m.prefix.join(" ")} ${s.join("|")} ...`},formatHelp:m=>[...Me(e,n,m)].join(`
22
- `)+`
23
- `,getDefaultCommand:()=>o,getOtherAliasesForInput:(m,s)=>{if(t){if(m===t)return{original:[""],"convert-camel-to-kebab":[""]};if(m==="")return{original:[t],"convert-camel-to-kebab":[t]}}let u=D(m),l=d(m);if(!l&&s==="allow-kebab-for-camel"&&(l=d(u)),!l)return{original:[],"convert-camel-to-kebab":[]};let p=[l,...i.get(l)??[]].filter(c=>c!==m&&c!==u);return{original:p,"convert-camel-to-kebab":p.map(F)}},getRoutingTargetForInput:m=>{let s=m in r?r[m]:m;return e[s]},getAllEntries(){let m=n.hideRoute;return Object.entries(e).map(([s,u])=>({name:{original:s,"convert-camel-to-kebab":F(s)},target:u,aliases:i.get(s)??[],hidden:m?.[s]??!1}))}}}async function Cn(e,t,n){let a=await Ae(e,t,n);n.process.exitCode=a}0&&(module.exports={AliasNotFoundError,ArgumentParseError,ArgumentScannerError,EnumValidationError,ExitCode,FlagNotFoundError,InvalidNegatedFlagSyntaxError,UnexpectedFlagError,UnexpectedPositionalError,UnsatisfiedFlagError,UnsatisfiedPositionalError,booleanParser,buildApplication,buildChoiceParser,buildCommand,buildRouteMap,formatMessageForArgumentScannerError,generateHelpTextForAllCommands,looseBooleanParser,numberParser,proposeCompletions,run,text_en});
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ AliasNotFoundError: () => AliasNotFoundError,
24
+ ArgumentParseError: () => ArgumentParseError,
25
+ ArgumentScannerError: () => ArgumentScannerError,
26
+ EnumValidationError: () => EnumValidationError,
27
+ ExitCode: () => ExitCode,
28
+ FlagNotFoundError: () => FlagNotFoundError,
29
+ InvalidNegatedFlagSyntaxError: () => InvalidNegatedFlagSyntaxError,
30
+ UnexpectedFlagError: () => UnexpectedFlagError,
31
+ UnexpectedPositionalError: () => UnexpectedPositionalError,
32
+ UnsatisfiedFlagError: () => UnsatisfiedFlagError,
33
+ UnsatisfiedPositionalError: () => UnsatisfiedPositionalError,
34
+ booleanParser: () => booleanParser,
35
+ buildApplication: () => buildApplication,
36
+ buildChoiceParser: () => buildChoiceParser,
37
+ buildCommand: () => buildCommand,
38
+ buildRouteMap: () => buildRouteMap,
39
+ formatMessageForArgumentScannerError: () => formatMessageForArgumentScannerError,
40
+ generateHelpTextForAllCommands: () => generateHelpTextForAllCommands,
41
+ looseBooleanParser: () => looseBooleanParser,
42
+ numberParser: () => numberParser,
43
+ proposeCompletions: () => proposeCompletionsForApplication,
44
+ run: () => run,
45
+ text_en: () => text_en
46
+ });
47
+ module.exports = __toCommonJS(src_exports);
48
+
49
+ // src/context.ts
50
+ function checkEnvironmentVariable(process, varName) {
51
+ const value = process.env?.[varName];
52
+ return typeof value === "string" && value !== "0";
53
+ }
54
+
55
+ // src/exit-code.ts
56
+ var ExitCode = {
57
+ /**
58
+ * Unable to find a command in the application with the given command line arguments.
59
+ */
60
+ UnknownCommand: -5,
61
+ /**
62
+ * Unable to parse the specified arguments.
63
+ */
64
+ InvalidArgument: -4,
65
+ /**
66
+ * An error was thrown while loading the context for a command run.
67
+ */
68
+ ContextLoadError: -3,
69
+ /**
70
+ * Failed to load command module.
71
+ */
72
+ CommandLoadError: -2,
73
+ /**
74
+ * An unexpected error was thrown by or not caught by this library.
75
+ */
76
+ InternalError: -1,
77
+ /**
78
+ * Command executed successfully.
79
+ */
80
+ Success: 0,
81
+ /**
82
+ * Command module unexpectedly threw an error.
83
+ */
84
+ CommandRunError: 1
85
+ };
86
+
87
+ // src/util/case-style.ts
88
+ function convertKebabCaseToCamelCase(str) {
89
+ return str.replace(/-./g, (match) => match[1].toUpperCase());
90
+ }
91
+ function convertCamelCaseToKebabCase(name) {
92
+ return Array.from(name).map((char, i) => {
93
+ const upper = char.toUpperCase();
94
+ const lower = char.toLowerCase();
95
+ if (i === 0 || upper !== char || upper === lower) {
96
+ return char;
97
+ }
98
+ return `-${lower}`;
99
+ }).join("");
100
+ }
101
+
102
+ // src/util/distance.ts
103
+ function newSparseMatrix(defaultValue) {
104
+ const values = /* @__PURE__ */ new Map();
105
+ return {
106
+ get: (...args) => {
107
+ return values.get(args.join(",")) ?? defaultValue;
108
+ },
109
+ set: (value, ...args) => {
110
+ values.set(args.join(","), value);
111
+ }
112
+ // toString([iMin, iMax], [jMin, jMax]) {
113
+ // const rows: string[] = [];
114
+ // for (let i = iMin; i <= iMax; ++i) {
115
+ // const row: string[] = [];
116
+ // for (let j = jMin; j <= jMax; ++j) {
117
+ // row.push(this.get(i, j).toString());
118
+ // }
119
+ // rows.push(row.join(", "));
120
+ // }
121
+ // return rows.join("\n");
122
+ // },
123
+ };
124
+ }
125
+ function damerauLevenshtein(a, b, options) {
126
+ const { threshold, weights } = options;
127
+ if (a === b) {
128
+ return 0;
129
+ }
130
+ const lengthDiff = Math.abs(a.length - b.length);
131
+ if (typeof threshold === "number" && lengthDiff > threshold) {
132
+ return Infinity;
133
+ }
134
+ const matrix = newSparseMatrix(Infinity);
135
+ matrix.set(0, -1, -1);
136
+ for (let j = 0; j < b.length; ++j) {
137
+ matrix.set((j + 1) * weights.insertion, -1, j);
138
+ }
139
+ for (let i = 0; i < a.length; ++i) {
140
+ matrix.set((i + 1) * weights.deletion, i, -1);
141
+ }
142
+ let prevRowMinDistance = -Infinity;
143
+ for (let i = 0; i < a.length; ++i) {
144
+ let rowMinDistance = Infinity;
145
+ for (let j = 0; j <= b.length - 1; ++j) {
146
+ const cost = a[i] === b[j] ? 0 : 1;
147
+ const distances = [
148
+ // deletion
149
+ matrix.get(i - 1, j) + weights.deletion,
150
+ // insertion
151
+ matrix.get(i, j - 1) + weights.insertion,
152
+ // substitution
153
+ matrix.get(i - 1, j - 1) + cost * weights.substitution
154
+ ];
155
+ if (a[i] === b[j - 1] && a[i - 1] === b[j]) {
156
+ distances.push(matrix.get(i - 2, j - 2) + cost * weights.transposition);
157
+ }
158
+ const minDistance = Math.min(...distances);
159
+ matrix.set(minDistance, i, j);
160
+ if (minDistance < rowMinDistance) {
161
+ rowMinDistance = minDistance;
162
+ }
163
+ }
164
+ if (rowMinDistance > threshold) {
165
+ if (prevRowMinDistance > threshold) {
166
+ return Infinity;
167
+ }
168
+ prevRowMinDistance = rowMinDistance;
169
+ } else {
170
+ prevRowMinDistance = -Infinity;
171
+ }
172
+ }
173
+ const distance = matrix.get(a.length - 1, b.length - 1);
174
+ if (distance > threshold) {
175
+ return Infinity;
176
+ }
177
+ return distance;
178
+ }
179
+ function compareAlternatives(a, b, target) {
180
+ const cmp = a[1] - b[1];
181
+ if (cmp !== 0) {
182
+ return cmp;
183
+ }
184
+ const aStartsWith = a[0].startsWith(target);
185
+ const bStartsWith = b[0].startsWith(target);
186
+ if (aStartsWith && !bStartsWith) {
187
+ return -1;
188
+ } else if (!aStartsWith && bStartsWith) {
189
+ return 1;
190
+ }
191
+ return a[0].localeCompare(b[0]);
192
+ }
193
+ function filterClosestAlternatives(target, alternatives, options) {
194
+ const validAlternatives = alternatives.map((alt) => [alt, damerauLevenshtein(target, alt, options)]).filter(([, dist]) => dist <= options.threshold);
195
+ const minDistance = Math.min(...validAlternatives.map(([, dist]) => dist));
196
+ return validAlternatives.filter(([, dist]) => dist === minDistance).sort((a, b) => compareAlternatives(a, b, target)).map(([alt]) => alt);
197
+ }
198
+
199
+ // src/util/error.ts
200
+ var InternalError = class extends Error {
201
+ };
202
+ function formatException(exc) {
203
+ if (exc instanceof Error) {
204
+ return exc.stack ?? String(exc);
205
+ }
206
+ return String(exc);
207
+ }
208
+
209
+ // src/util/formatting.ts
210
+ function maximum(arr1, arr2) {
211
+ const maxValues = [];
212
+ const maxLength = Math.max(arr1.length, arr2.length);
213
+ for (let i = 0; i < maxLength; ++i) {
214
+ maxValues[i] = Math.max(arr1[i], arr2[i]);
215
+ }
216
+ return maxValues;
217
+ }
218
+ function formatRowsWithColumns(cells, separators) {
219
+ if (cells.length === 0) {
220
+ return [];
221
+ }
222
+ const startingLengths = Array(Math.max(...cells.map((cellRow) => cellRow.length))).fill(0, 0);
223
+ const maxLengths = cells.reduce((acc, cellRow) => {
224
+ const lengths = cellRow.map((cell) => cell.length);
225
+ return maximum(acc, lengths);
226
+ }, startingLengths);
227
+ return cells.map((cellRow) => {
228
+ const firstCell = (cellRow[0] ?? "").padEnd(maxLengths[0]);
229
+ return cellRow.slice(1).reduce(
230
+ (parts, str, i, arr) => {
231
+ const paddedStr = arr.length === i + 1 ? str : str.padEnd(maxLengths[i + 1]);
232
+ return [...parts, separators?.[i] ?? " ", paddedStr];
233
+ },
234
+ [firstCell]
235
+ ).join("").trimEnd();
236
+ });
237
+ }
238
+ function joinWithGrammar(parts, grammar) {
239
+ if (parts.length <= 1) {
240
+ return parts[0] ?? "";
241
+ }
242
+ if (parts.length === 2) {
243
+ return parts.join(` ${grammar.conjunction} `);
244
+ }
245
+ let allButLast = parts.slice(0, parts.length - 1).join(", ");
246
+ if (grammar.serialComma) {
247
+ allButLast += ",";
248
+ }
249
+ return [allButLast, grammar.conjunction, parts[parts.length - 1]].join(" ");
250
+ }
251
+
252
+ // src/util/array.ts
253
+ function group(array, callback) {
254
+ return array.reduce((groupings, item) => {
255
+ const key = callback(item);
256
+ const groupItems = groupings[key] ?? [];
257
+ groupItems.push(item);
258
+ groupings[key] = groupItems;
259
+ return groupings;
260
+ }, {});
261
+ }
262
+ function groupBy(array, selector) {
263
+ return group(array, (item) => item[selector]);
264
+ }
265
+
266
+ // src/util/promise.ts
267
+ async function allSettledOrElse(values) {
268
+ const results = await Promise.allSettled(values);
269
+ const grouped = groupBy(results, "status");
270
+ if (grouped.rejected && grouped.rejected.length > 0) {
271
+ return { status: "rejected", reasons: grouped.rejected.map((result) => result.reason) };
272
+ }
273
+ return { status: "fulfilled", value: grouped.fulfilled?.map((result) => result.value) ?? [] };
274
+ }
275
+
276
+ // src/parameter/parser/boolean.ts
277
+ var booleanParser = (input) => {
278
+ switch (input.toLowerCase()) {
279
+ case "true":
280
+ return true;
281
+ case "false":
282
+ return false;
283
+ }
284
+ throw new SyntaxError(`Cannot convert ${input} to a boolean`);
285
+ };
286
+ var TRUTHY_VALUES = /* @__PURE__ */ new Set(["true", "t", "yes", "y", "on", "1"]);
287
+ var FALSY_VALUES = /* @__PURE__ */ new Set(["false", "f", "no", "n", "off", "0"]);
288
+ var looseBooleanParser = (input) => {
289
+ const value = input.toLowerCase();
290
+ if (TRUTHY_VALUES.has(value)) {
291
+ return true;
292
+ }
293
+ if (FALSY_VALUES.has(value)) {
294
+ return false;
295
+ }
296
+ throw new SyntaxError(`Cannot convert ${input} to a boolean`);
297
+ };
298
+
299
+ // src/parameter/parser/number.ts
300
+ var numberParser = (input) => {
301
+ const value = Number(input);
302
+ if (Number.isNaN(value)) {
303
+ throw new SyntaxError(`Cannot convert ${input} to a number`);
304
+ }
305
+ return value;
306
+ };
307
+
308
+ // src/parameter/scanner.ts
309
+ var ArgumentScannerError = class extends InternalError {
310
+ _brand;
311
+ };
312
+ function formatMessageForArgumentScannerError(error, formatter) {
313
+ const errorType = error.constructor.name;
314
+ const formatError = formatter[errorType];
315
+ if (formatError) {
316
+ return formatError(error);
317
+ }
318
+ return error.message;
319
+ }
320
+ function resolveAliases(flags, aliases, scannerCaseStyle) {
321
+ return Object.fromEntries(
322
+ Object.entries(aliases).map(([alias, internalFlagName_]) => {
323
+ const internalFlagName = internalFlagName_;
324
+ const flag = flags[internalFlagName];
325
+ if (!flag) {
326
+ const externalFlagName = asExternal(internalFlagName, scannerCaseStyle);
327
+ throw new FlagNotFoundError(externalFlagName, [], alias);
328
+ }
329
+ return [alias, [internalFlagName, flag]];
330
+ })
331
+ );
332
+ }
333
+ var FlagNotFoundError = class extends ArgumentScannerError {
334
+ /**
335
+ * Command line input that triggered this error.
336
+ */
337
+ input;
338
+ /**
339
+ * Set of proposed suggestions that are similar to the input.
340
+ */
341
+ corrections;
342
+ /**
343
+ * Set if error was caused indirectly by an alias.
344
+ * This indicates that something is wrong with the command configuration itself.
345
+ */
346
+ aliasName;
347
+ constructor(input, corrections, aliasName) {
348
+ let message = `No flag registered for --${input}`;
349
+ if (aliasName) {
350
+ message += ` (aliased from -${aliasName})`;
351
+ } else if (corrections.length > 0) {
352
+ const formattedCorrections = joinWithGrammar(
353
+ corrections.map((correction) => `--${correction}`),
354
+ {
355
+ kind: "conjunctive",
356
+ conjunction: "or",
357
+ serialComma: true
358
+ }
359
+ );
360
+ message += `, did you mean ${formattedCorrections}?`;
361
+ }
362
+ super(message);
363
+ this.input = input;
364
+ this.corrections = corrections;
365
+ this.aliasName = aliasName;
366
+ }
367
+ };
368
+ var AliasNotFoundError = class extends ArgumentScannerError {
369
+ /**
370
+ * Command line input that triggered this error.
371
+ */
372
+ input;
373
+ constructor(input) {
374
+ super(`No alias registered for -${input}`);
375
+ this.input = input;
376
+ }
377
+ };
378
+ function getPlaceholder(param, index) {
379
+ if (param.placeholder) {
380
+ return param.placeholder;
381
+ }
382
+ return typeof index === "number" ? `arg${index}` : "args";
383
+ }
384
+ function asExternal(internal, scannerCaseStyle) {
385
+ return scannerCaseStyle === "allow-kebab-for-camel" ? convertCamelCaseToKebabCase(internal) : internal;
386
+ }
387
+ var ArgumentParseError = class extends ArgumentScannerError {
388
+ /**
389
+ * External name of flag or placeholder for positional argument that was parsing this input.
390
+ */
391
+ externalFlagNameOrPlaceholder;
392
+ /**
393
+ * Command line input that triggered this error.
394
+ */
395
+ input;
396
+ /**
397
+ * Raw exception thrown from parse function.
398
+ */
399
+ exception;
400
+ constructor(externalFlagNameOrPlaceholder, input, exception) {
401
+ super(
402
+ `Failed to parse "${input}" for ${externalFlagNameOrPlaceholder}: ${exception instanceof Error ? exception.message : String(exception)}`
403
+ );
404
+ this.externalFlagNameOrPlaceholder = externalFlagNameOrPlaceholder;
405
+ this.input = input;
406
+ this.exception = exception;
407
+ }
408
+ };
409
+ function parseInput(externalFlagNameOrPlaceholder, parameter, input, context) {
410
+ try {
411
+ return parameter.parse.call(context, input);
412
+ } catch (exc) {
413
+ throw new ArgumentParseError(externalFlagNameOrPlaceholder, input, exc);
414
+ }
415
+ }
416
+ var EnumValidationError = class extends ArgumentScannerError {
417
+ /**
418
+ * External name of flag that was parsing this input.
419
+ */
420
+ externalFlagName;
421
+ /**
422
+ * Command line input that triggered this error.
423
+ */
424
+ input;
425
+ /**
426
+ * All possible enum values.
427
+ */
428
+ values;
429
+ constructor(externalFlagName, input, values, corrections) {
430
+ let message = `Expected "${input}" to be one of (${values.join("|")})`;
431
+ if (corrections.length > 0) {
432
+ const formattedCorrections = joinWithGrammar(
433
+ corrections.map((str) => `"${str}"`),
434
+ {
435
+ kind: "conjunctive",
436
+ conjunction: "or",
437
+ serialComma: true
438
+ }
439
+ );
440
+ message += `, did you mean ${formattedCorrections}?`;
441
+ }
442
+ super(message);
443
+ this.externalFlagName = externalFlagName;
444
+ this.input = input;
445
+ this.values = values;
446
+ }
447
+ };
448
+ var UnsatisfiedFlagError = class extends ArgumentScannerError {
449
+ /**
450
+ * External name of flag that was active when this error was thrown.
451
+ */
452
+ externalFlagName;
453
+ /**
454
+ * External name of flag that interrupted the original flag.
455
+ */
456
+ nextFlagName;
457
+ constructor(externalFlagName, nextFlagName) {
458
+ let message = `Expected input for flag --${externalFlagName}`;
459
+ if (nextFlagName) {
460
+ message += ` but encountered --${nextFlagName} instead`;
461
+ }
462
+ super(message);
463
+ this.externalFlagName = externalFlagName;
464
+ this.nextFlagName = nextFlagName;
465
+ }
466
+ };
467
+ var UnexpectedPositionalError = class extends ArgumentScannerError {
468
+ /**
469
+ * Expected (maximum) count of positional arguments.
470
+ */
471
+ expectedCount;
472
+ /**
473
+ * Command line input that triggered this error.
474
+ */
475
+ input;
476
+ constructor(expectedCount, input) {
477
+ super(`Too many arguments, expected ${expectedCount} but encountered "${input}"`);
478
+ this.expectedCount = expectedCount;
479
+ this.input = input;
480
+ }
481
+ };
482
+ var UnsatisfiedPositionalError = class extends ArgumentScannerError {
483
+ /**
484
+ * Placeholder for positional argument that was active when this error was thrown.
485
+ */
486
+ placeholder;
487
+ /**
488
+ * If specified, indicates the minimum number of arguments that are expected and the last argument count.
489
+ */
490
+ limit;
491
+ constructor(placeholder, limit) {
492
+ let message;
493
+ if (limit) {
494
+ message = `Expected at least ${limit[0]} argument(s) for ${placeholder}`;
495
+ if (limit[1] === 0) {
496
+ message += " but found none";
497
+ } else {
498
+ message += ` but only found ${limit[1]}`;
499
+ }
500
+ } else {
501
+ message = `Expected argument for ${placeholder}`;
502
+ }
503
+ super(message);
504
+ this.placeholder = placeholder;
505
+ this.limit = limit;
506
+ }
507
+ };
508
+ function undoNegation(flagName) {
509
+ if (flagName.startsWith("no") && flagName.length > 2) {
510
+ if (flagName[2] === "-") {
511
+ return flagName.slice(4);
512
+ }
513
+ const firstChar = flagName[2];
514
+ const firstUpper = firstChar.toUpperCase();
515
+ if (firstChar !== firstUpper) {
516
+ return;
517
+ }
518
+ const firstLower = firstChar.toLowerCase();
519
+ return firstLower + flagName.slice(3);
520
+ }
521
+ }
522
+ function findInternalFlagMatch(externalFlagName, flags, config) {
523
+ const internalFlagName = externalFlagName;
524
+ let flag = flags[internalFlagName];
525
+ let foundFlagWithNegatedFalse;
526
+ let foundFlagWithNegatedFalseFromKebabConversion = false;
527
+ if (!flag) {
528
+ const internalWithoutNegation = undoNegation(internalFlagName);
529
+ if (internalWithoutNegation) {
530
+ flag = flags[internalWithoutNegation];
531
+ if (flag && flag.kind == "boolean") {
532
+ if (flag.withNegated !== false) {
533
+ return { namedFlag: [internalWithoutNegation, flag], negated: true };
534
+ } else {
535
+ foundFlagWithNegatedFalse = internalWithoutNegation;
536
+ flag = void 0;
537
+ }
538
+ }
539
+ }
540
+ }
541
+ const camelCaseFlagName = convertKebabCaseToCamelCase(externalFlagName);
542
+ if (config.caseStyle === "allow-kebab-for-camel" && !flag) {
543
+ flag = flags[camelCaseFlagName];
544
+ if (flag) {
545
+ return { namedFlag: [camelCaseFlagName, flag] };
546
+ }
547
+ const camelCaseWithoutNegation = undoNegation(camelCaseFlagName);
548
+ if (camelCaseWithoutNegation) {
549
+ flag = flags[camelCaseWithoutNegation];
550
+ if (flag && flag.kind == "boolean") {
551
+ if (flag.withNegated !== false) {
552
+ return { namedFlag: [camelCaseWithoutNegation, flag], negated: true };
553
+ } else {
554
+ foundFlagWithNegatedFalse = camelCaseWithoutNegation;
555
+ foundFlagWithNegatedFalseFromKebabConversion = true;
556
+ flag = void 0;
557
+ }
558
+ }
559
+ }
560
+ }
561
+ if (!flag) {
562
+ if (foundFlagWithNegatedFalse) {
563
+ let correction = foundFlagWithNegatedFalse;
564
+ if (foundFlagWithNegatedFalseFromKebabConversion && externalFlagName.includes("-")) {
565
+ correction = convertCamelCaseToKebabCase(foundFlagWithNegatedFalse);
566
+ }
567
+ throw new FlagNotFoundError(externalFlagName, [correction]);
568
+ }
569
+ if (camelCaseFlagName in flags) {
570
+ throw new FlagNotFoundError(externalFlagName, [camelCaseFlagName]);
571
+ }
572
+ const kebabCaseFlagName = convertCamelCaseToKebabCase(externalFlagName);
573
+ if (kebabCaseFlagName in flags) {
574
+ throw new FlagNotFoundError(externalFlagName, [kebabCaseFlagName]);
575
+ }
576
+ const corrections = filterClosestAlternatives(internalFlagName, Object.keys(flags), config.distanceOptions);
577
+ throw new FlagNotFoundError(externalFlagName, corrections);
578
+ }
579
+ return { namedFlag: [internalFlagName, flag] };
580
+ }
581
+ function isNiladic(namedFlagWithNegation) {
582
+ if (namedFlagWithNegation.namedFlag[1].kind === "boolean" || namedFlagWithNegation.namedFlag[1].kind === "counter") {
583
+ return true;
584
+ }
585
+ return false;
586
+ }
587
+ var FLAG_SHORTHAND_PATTERN = /^-([a-z]+)$/i;
588
+ var FLAG_NAME_PATTERN = /^--([a-z][a-z-.\d_]+)$/i;
589
+ function findFlagsByArgument(arg, flags, resolvedAliases, config) {
590
+ const shorthandMatch = FLAG_SHORTHAND_PATTERN.exec(arg);
591
+ if (shorthandMatch) {
592
+ const batch = shorthandMatch[1];
593
+ return Array.from(batch).map((alias) => {
594
+ const aliasName = alias;
595
+ const namedFlag = resolvedAliases[aliasName];
596
+ if (!namedFlag) {
597
+ throw new AliasNotFoundError(aliasName);
598
+ }
599
+ return { namedFlag };
600
+ });
601
+ }
602
+ const flagNameMatch = FLAG_NAME_PATTERN.exec(arg);
603
+ if (flagNameMatch) {
604
+ const externalFlagName = flagNameMatch[1];
605
+ return [findInternalFlagMatch(externalFlagName, flags, config)];
606
+ }
607
+ return [];
608
+ }
609
+ var FLAG_NAME_VALUE_PATTERN = /^--([a-z][a-z-.\d_]+)=(.+)$/i;
610
+ var ALIAS_VALUE_PATTERN = /^-([a-z])=(.+)$/i;
611
+ var InvalidNegatedFlagSyntaxError = class extends ArgumentScannerError {
612
+ /**
613
+ * External name of flag that was active when this error was thrown.
614
+ */
615
+ externalFlagName;
616
+ /**
617
+ * Input text equivalent to right hand side of input
618
+ */
619
+ valueText;
620
+ constructor(externalFlagName, valueText) {
621
+ super(`Cannot negate flag --${externalFlagName} and pass "${valueText}" as value`);
622
+ this.externalFlagName = externalFlagName;
623
+ this.valueText = valueText;
624
+ }
625
+ };
626
+ function findFlagByArgumentWithInput(arg, flags, resolvedAliases, config) {
627
+ const flagsNameMatch = FLAG_NAME_VALUE_PATTERN.exec(arg);
628
+ if (flagsNameMatch) {
629
+ const externalFlagName = flagsNameMatch[1];
630
+ const { namedFlag: flagMatch, negated } = findInternalFlagMatch(externalFlagName, flags, config);
631
+ const valueText = flagsNameMatch[2];
632
+ if (negated) {
633
+ throw new InvalidNegatedFlagSyntaxError(externalFlagName, valueText);
634
+ }
635
+ return [flagMatch, valueText];
636
+ }
637
+ const aliasValueMatch = ALIAS_VALUE_PATTERN.exec(arg);
638
+ if (aliasValueMatch) {
639
+ const aliasName = aliasValueMatch[1];
640
+ const namedFlag = resolvedAliases[aliasName];
641
+ if (!namedFlag) {
642
+ throw new AliasNotFoundError(aliasName);
643
+ }
644
+ const valueText = aliasValueMatch[2];
645
+ return [namedFlag, valueText];
646
+ }
647
+ }
648
+ async function parseInputsForFlag(externalFlagName, flag, inputs, config, context) {
649
+ if (!inputs) {
650
+ if ("default" in flag && typeof flag.default !== "undefined") {
651
+ if (flag.kind === "boolean") {
652
+ return flag.default;
653
+ }
654
+ if (flag.kind === "enum") {
655
+ if ("variadic" in flag && flag.variadic && Array.isArray(flag.default)) {
656
+ const defaultArray = flag.default;
657
+ for (const value of defaultArray) {
658
+ if (!flag.values.includes(value)) {
659
+ const corrections = filterClosestAlternatives(value, flag.values, config.distanceOptions);
660
+ throw new EnumValidationError(externalFlagName, value, flag.values, corrections);
661
+ }
662
+ }
663
+ return flag.default;
664
+ }
665
+ return flag.default;
666
+ }
667
+ if ("variadic" in flag && flag.variadic && Array.isArray(flag.default)) {
668
+ const defaultArray = flag.default;
669
+ return Promise.all(defaultArray.map((input2) => parseInput(externalFlagName, flag, input2, context)));
670
+ }
671
+ return parseInput(externalFlagName, flag, flag.default, context);
672
+ }
673
+ if (flag.optional) {
674
+ return;
675
+ }
676
+ if (flag.kind === "boolean") {
677
+ return false;
678
+ } else if (flag.kind === "counter") {
679
+ return 0;
680
+ }
681
+ throw new UnsatisfiedFlagError(externalFlagName);
682
+ }
683
+ if (flag.kind === "counter") {
684
+ return inputs.reduce((total, input2) => {
685
+ try {
686
+ return total + numberParser.call(context, input2);
687
+ } catch (exc) {
688
+ throw new ArgumentParseError(externalFlagName, input2, exc);
689
+ }
690
+ }, 0);
691
+ }
692
+ if ("variadic" in flag && flag.variadic) {
693
+ if (flag.kind === "enum") {
694
+ for (const input2 of inputs) {
695
+ if (!flag.values.includes(input2)) {
696
+ const corrections = filterClosestAlternatives(input2, flag.values, config.distanceOptions);
697
+ throw new EnumValidationError(externalFlagName, input2, flag.values, corrections);
698
+ }
699
+ }
700
+ return inputs;
701
+ }
702
+ return Promise.all(inputs.map((input2) => parseInput(externalFlagName, flag, input2, context)));
703
+ }
704
+ const input = inputs[0];
705
+ if (flag.kind === "boolean") {
706
+ try {
707
+ return looseBooleanParser.call(context, input);
708
+ } catch (exc) {
709
+ throw new ArgumentParseError(externalFlagName, input, exc);
710
+ }
711
+ }
712
+ if (flag.kind === "enum") {
713
+ if (!flag.values.includes(input)) {
714
+ const corrections = filterClosestAlternatives(input, flag.values, config.distanceOptions);
715
+ throw new EnumValidationError(externalFlagName, input, flag.values, corrections);
716
+ }
717
+ return input;
718
+ }
719
+ return parseInput(externalFlagName, flag, input, context);
720
+ }
721
+ var UnexpectedFlagError = class extends ArgumentScannerError {
722
+ /**
723
+ * External name of flag that was parsing this input.
724
+ */
725
+ externalFlagName;
726
+ /**
727
+ * Command line input that was previously encountered by this flag.
728
+ */
729
+ previousInput;
730
+ /**
731
+ * Command line input that triggered this error.
732
+ */
733
+ input;
734
+ constructor(externalFlagName, previousInput, input) {
735
+ super(`Too many arguments for --${externalFlagName}, encountered "${input}" after "${previousInput}"`);
736
+ this.externalFlagName = externalFlagName;
737
+ this.previousInput = previousInput;
738
+ this.input = input;
739
+ }
740
+ };
741
+ function isVariadicFlag(flag) {
742
+ if (flag.kind === "counter") {
743
+ return true;
744
+ }
745
+ if ("variadic" in flag) {
746
+ return Boolean(flag.variadic);
747
+ }
748
+ return false;
749
+ }
750
+ function storeInput(flagInputs, scannerCaseStyle, [internalFlagName, flag], input) {
751
+ const inputs = flagInputs.get(internalFlagName) ?? [];
752
+ if (inputs.length > 0 && !isVariadicFlag(flag)) {
753
+ const externalFlagName = asExternal(internalFlagName, scannerCaseStyle);
754
+ throw new UnexpectedFlagError(externalFlagName, inputs[0], input);
755
+ }
756
+ if ("variadic" in flag && typeof flag.variadic === "string") {
757
+ const multipleInputs = input.split(flag.variadic);
758
+ flagInputs.set(internalFlagName, [...inputs, ...multipleInputs]);
759
+ } else {
760
+ flagInputs.set(internalFlagName, [...inputs, input]);
761
+ }
762
+ }
763
+ function isFlagSatisfiedByInputs(flags, flagInputs, key) {
764
+ const inputs = flagInputs.get(key);
765
+ if (inputs) {
766
+ const flag = flags[key];
767
+ if (isVariadicFlag(flag)) {
768
+ return false;
769
+ }
770
+ return true;
771
+ }
772
+ return false;
773
+ }
774
+ function buildArgumentScanner(parameters, config) {
775
+ const { flags = {}, aliases = {}, positional = { kind: "tuple", parameters: [] } } = parameters;
776
+ const resolvedAliases = resolveAliases(flags, aliases, config.caseStyle);
777
+ const positionalInputs = [];
778
+ const flagInputs = /* @__PURE__ */ new Map();
779
+ let positionalIndex = 0;
780
+ let activeFlag;
781
+ let treatInputsAsArguments = false;
782
+ return {
783
+ next: (input) => {
784
+ if (!treatInputsAsArguments && config.allowArgumentEscapeSequence && input === "--") {
785
+ if (activeFlag) {
786
+ if (activeFlag[1].kind === "parsed" && activeFlag[1].inferEmpty) {
787
+ storeInput(flagInputs, config.caseStyle, activeFlag, "");
788
+ activeFlag = void 0;
789
+ } else {
790
+ const externalFlagName = asExternal(activeFlag[0], config.caseStyle);
791
+ throw new UnsatisfiedFlagError(externalFlagName);
792
+ }
793
+ }
794
+ treatInputsAsArguments = true;
795
+ return;
796
+ }
797
+ if (!treatInputsAsArguments) {
798
+ const flagInput = findFlagByArgumentWithInput(input, flags, resolvedAliases, config);
799
+ if (flagInput) {
800
+ if (activeFlag) {
801
+ if (activeFlag[1].kind === "parsed" && activeFlag[1].inferEmpty) {
802
+ storeInput(flagInputs, config.caseStyle, activeFlag, "");
803
+ activeFlag = void 0;
804
+ } else {
805
+ const externalFlagName = asExternal(activeFlag[0], config.caseStyle);
806
+ const nextExternalFlagName = asExternal(flagInput[0][0], config.caseStyle);
807
+ throw new UnsatisfiedFlagError(externalFlagName, nextExternalFlagName);
808
+ }
809
+ }
810
+ storeInput(flagInputs, config.caseStyle, ...flagInput);
811
+ return;
812
+ }
813
+ const nextFlags = findFlagsByArgument(input, flags, resolvedAliases, config);
814
+ if (nextFlags.length > 0) {
815
+ if (activeFlag) {
816
+ if (activeFlag[1].kind === "parsed" && activeFlag[1].inferEmpty) {
817
+ storeInput(flagInputs, config.caseStyle, activeFlag, "");
818
+ activeFlag = void 0;
819
+ } else {
820
+ const externalFlagName = asExternal(activeFlag[0], config.caseStyle);
821
+ const nextFlagName = asExternal(nextFlags[0].namedFlag[0], config.caseStyle);
822
+ throw new UnsatisfiedFlagError(externalFlagName, nextFlagName);
823
+ }
824
+ }
825
+ if (nextFlags.every(isNiladic)) {
826
+ for (const nextFlag of nextFlags) {
827
+ if (nextFlag.namedFlag[1].kind === "boolean") {
828
+ storeInput(
829
+ flagInputs,
830
+ config.caseStyle,
831
+ nextFlag.namedFlag,
832
+ nextFlag.negated ? "false" : "true"
833
+ );
834
+ } else {
835
+ storeInput(flagInputs, config.caseStyle, nextFlag.namedFlag, "1");
836
+ }
837
+ }
838
+ } else if (nextFlags.length > 1) {
839
+ const nextFlagExpectingArg = nextFlags.find((nextFlag) => !isNiladic(nextFlag));
840
+ const externalFlagName = asExternal(nextFlagExpectingArg.namedFlag[0], config.caseStyle);
841
+ throw new UnsatisfiedFlagError(externalFlagName);
842
+ } else {
843
+ activeFlag = nextFlags[0].namedFlag;
844
+ }
845
+ return;
846
+ }
847
+ }
848
+ if (activeFlag) {
849
+ storeInput(flagInputs, config.caseStyle, activeFlag, input);
850
+ activeFlag = void 0;
851
+ } else {
852
+ if (positional.kind === "tuple") {
853
+ if (positionalIndex >= positional.parameters.length) {
854
+ throw new UnexpectedPositionalError(positional.parameters.length, input);
855
+ }
856
+ } else {
857
+ if (typeof positional.maximum === "number" && positionalIndex >= positional.maximum) {
858
+ throw new UnexpectedPositionalError(positional.maximum, input);
859
+ }
860
+ }
861
+ positionalInputs[positionalIndex] = input;
862
+ ++positionalIndex;
863
+ }
864
+ },
865
+ parseArguments: async (context) => {
866
+ const errors = [];
867
+ let positionalValues_p;
868
+ if (positional.kind === "array") {
869
+ if (typeof positional.minimum === "number" && positionalIndex < positional.minimum) {
870
+ errors.push(
871
+ new UnsatisfiedPositionalError(getPlaceholder(positional.parameter), [
872
+ positional.minimum,
873
+ positionalIndex
874
+ ])
875
+ );
876
+ }
877
+ positionalValues_p = allSettledOrElse(
878
+ positionalInputs.map(async (input, i) => {
879
+ const placeholder = getPlaceholder(positional.parameter, i + 1);
880
+ return parseInput(placeholder, positional.parameter, input, context);
881
+ })
882
+ );
883
+ } else {
884
+ positionalValues_p = allSettledOrElse(
885
+ positional.parameters.map(async (param, i) => {
886
+ const placeholder = getPlaceholder(param, i + 1);
887
+ const input = positionalInputs[i];
888
+ if (typeof input !== "string") {
889
+ if (typeof param.default === "string") {
890
+ return parseInput(placeholder, param, param.default, context);
891
+ }
892
+ if (param.optional) {
893
+ return;
894
+ }
895
+ throw new UnsatisfiedPositionalError(placeholder);
896
+ }
897
+ return parseInput(placeholder, param, input, context);
898
+ })
899
+ );
900
+ }
901
+ if (activeFlag && activeFlag[1].kind === "parsed" && activeFlag[1].inferEmpty) {
902
+ storeInput(flagInputs, config.caseStyle, activeFlag, "");
903
+ activeFlag = void 0;
904
+ }
905
+ const flagEntries_p = allSettledOrElse(
906
+ Object.entries(flags).map(async (entry) => {
907
+ const [internalFlagName, flag] = entry;
908
+ const externalFlagName = asExternal(internalFlagName, config.caseStyle);
909
+ if (activeFlag && activeFlag[0] === internalFlagName) {
910
+ throw new UnsatisfiedFlagError(externalFlagName);
911
+ }
912
+ const inputs = flagInputs.get(internalFlagName);
913
+ const value = await parseInputsForFlag(externalFlagName, flag, inputs, config, context);
914
+ return [internalFlagName, value];
915
+ })
916
+ );
917
+ const [positionalValuesResult, flagEntriesResult] = await Promise.all([positionalValues_p, flagEntries_p]);
918
+ if (positionalValuesResult.status === "rejected") {
919
+ for (const reason of positionalValuesResult.reasons) {
920
+ errors.push(reason);
921
+ }
922
+ }
923
+ if (flagEntriesResult.status === "rejected") {
924
+ for (const reason of flagEntriesResult.reasons) {
925
+ errors.push(reason);
926
+ }
927
+ }
928
+ if (errors.length > 0) {
929
+ return { success: false, errors };
930
+ }
931
+ if (positionalValuesResult.status === "rejected") {
932
+ throw new InternalError("Unknown failure while scanning positional arguments");
933
+ }
934
+ if (flagEntriesResult.status === "rejected") {
935
+ throw new InternalError("Unknown failure while scanning flag arguments");
936
+ }
937
+ const parsedFlags = Object.fromEntries(flagEntriesResult.value);
938
+ return { success: true, arguments: [parsedFlags, ...positionalValuesResult.value] };
939
+ },
940
+ proposeCompletions: async ({ partial, completionConfig, text, context, includeVersionFlag }) => {
941
+ if (activeFlag) {
942
+ return proposeFlagCompletionsForPartialInput(activeFlag[1], context, partial);
943
+ }
944
+ const completions = [];
945
+ if (!treatInputsAsArguments) {
946
+ const shorthandMatch = FLAG_SHORTHAND_PATTERN.exec(partial);
947
+ if (completionConfig.includeAliases) {
948
+ if (partial === "" || partial === "-") {
949
+ const incompleteAliases = Object.entries(aliases).filter(
950
+ (entry) => !isFlagSatisfiedByInputs(flags, flagInputs, entry[1])
951
+ );
952
+ for (const [alias] of incompleteAliases) {
953
+ const flag = resolvedAliases[alias];
954
+ if (flag) {
955
+ completions.push({
956
+ kind: "argument:flag",
957
+ completion: `-${alias}`,
958
+ brief: flag[1].brief
959
+ });
960
+ }
961
+ }
962
+ } else if (shorthandMatch) {
963
+ const partialAliases = Array.from(shorthandMatch[1]);
964
+ if (partialAliases.includes("h")) {
965
+ return [];
966
+ }
967
+ if (includeVersionFlag && partialAliases.includes("v")) {
968
+ return [];
969
+ }
970
+ const flagInputsIncludingPartial = new Map(flagInputs);
971
+ for (const alias of partialAliases) {
972
+ const namedFlag = resolvedAliases[alias];
973
+ if (!namedFlag) {
974
+ throw new AliasNotFoundError(alias);
975
+ }
976
+ storeInput(
977
+ flagInputsIncludingPartial,
978
+ config.caseStyle,
979
+ namedFlag,
980
+ namedFlag[1].kind === "boolean" ? "true" : "1"
981
+ );
982
+ }
983
+ const lastAlias = partialAliases[partialAliases.length - 1];
984
+ if (lastAlias) {
985
+ const namedFlag = resolvedAliases[lastAlias];
986
+ if (namedFlag) {
987
+ completions.push({
988
+ kind: "argument:flag",
989
+ completion: partial,
990
+ brief: namedFlag[1].brief
991
+ });
992
+ }
993
+ }
994
+ const incompleteAliases = Object.entries(aliases).filter(
995
+ (entry) => !isFlagSatisfiedByInputs(
996
+ flags,
997
+ flagInputsIncludingPartial,
998
+ entry[1]
999
+ )
1000
+ );
1001
+ for (const [alias] of incompleteAliases) {
1002
+ const flag = resolvedAliases[alias];
1003
+ if (flag) {
1004
+ completions.push({
1005
+ kind: "argument:flag",
1006
+ completion: `${partial}${alias}`,
1007
+ brief: flag[1].brief
1008
+ });
1009
+ }
1010
+ }
1011
+ }
1012
+ }
1013
+ if (partial === "" || partial === "-" || partial.startsWith("--")) {
1014
+ if (config.allowArgumentEscapeSequence) {
1015
+ completions.push({
1016
+ kind: "argument:flag",
1017
+ completion: "--",
1018
+ brief: text.briefs.argumentEscapeSequence
1019
+ });
1020
+ }
1021
+ let incompleteFlags = Object.entries(flags).filter(
1022
+ ([flagName]) => !isFlagSatisfiedByInputs(flags, flagInputs, flagName)
1023
+ );
1024
+ if (config.caseStyle === "allow-kebab-for-camel") {
1025
+ incompleteFlags = incompleteFlags.map(([flagName, param]) => {
1026
+ return [convertCamelCaseToKebabCase(flagName), param];
1027
+ });
1028
+ }
1029
+ const possibleFlags = incompleteFlags.map(([flagName, param]) => [`--${flagName}`, param]).filter(([flagName]) => flagName.startsWith(partial));
1030
+ completions.push(
1031
+ ...possibleFlags.map(([name, param]) => {
1032
+ return {
1033
+ kind: "argument:flag",
1034
+ completion: name,
1035
+ brief: param.brief
1036
+ };
1037
+ })
1038
+ );
1039
+ }
1040
+ }
1041
+ if (positional.kind === "array") {
1042
+ if (positional.parameter.proposeCompletions) {
1043
+ if (typeof positional.maximum !== "number" || positionalIndex < positional.maximum) {
1044
+ const positionalCompletions = await positional.parameter.proposeCompletions.call(
1045
+ context,
1046
+ partial
1047
+ );
1048
+ completions.push(
1049
+ ...positionalCompletions.map((value) => {
1050
+ return {
1051
+ kind: "argument:value",
1052
+ completion: value,
1053
+ brief: positional.parameter.brief
1054
+ };
1055
+ })
1056
+ );
1057
+ }
1058
+ }
1059
+ } else {
1060
+ const nextPositional = positional.parameters[positionalIndex];
1061
+ if (nextPositional?.proposeCompletions) {
1062
+ const positionalCompletions = await nextPositional.proposeCompletions.call(context, partial);
1063
+ completions.push(
1064
+ ...positionalCompletions.map((value) => {
1065
+ return {
1066
+ kind: "argument:value",
1067
+ completion: value,
1068
+ brief: nextPositional.brief
1069
+ };
1070
+ })
1071
+ );
1072
+ }
1073
+ }
1074
+ return completions.filter(({ completion }) => completion.startsWith(partial));
1075
+ }
1076
+ };
1077
+ }
1078
+ async function proposeFlagCompletionsForPartialInput(flag, context, partial) {
1079
+ if (typeof flag.variadic === "string") {
1080
+ if (partial.endsWith(flag.variadic)) {
1081
+ return proposeFlagCompletionsForPartialInput(flag, context, "");
1082
+ }
1083
+ }
1084
+ let values;
1085
+ if (flag.kind === "enum") {
1086
+ values = flag.values;
1087
+ } else if (flag.proposeCompletions) {
1088
+ values = await flag.proposeCompletions.call(context, partial);
1089
+ } else {
1090
+ values = [];
1091
+ }
1092
+ return values.map((value) => {
1093
+ return {
1094
+ kind: "argument:value",
1095
+ completion: value,
1096
+ brief: flag.brief
1097
+ };
1098
+ }).filter(({ completion }) => completion.startsWith(partial));
1099
+ }
1100
+ function listAllRouteNamesAndAliasesForScan(routeMap, scannerCaseStyle, config) {
1101
+ const displayCaseStyle = scannerCaseStyle === "allow-kebab-for-camel" ? "convert-camel-to-kebab" : scannerCaseStyle;
1102
+ let entries = routeMap.getAllEntries();
1103
+ if (!config.includeHiddenRoutes) {
1104
+ entries = entries.filter((entry) => !entry.hidden);
1105
+ }
1106
+ return entries.flatMap((entry) => {
1107
+ const routeName = entry.name[displayCaseStyle];
1108
+ if (config.includeAliases) {
1109
+ return [routeName, ...entry.aliases];
1110
+ }
1111
+ return [routeName];
1112
+ });
1113
+ }
1114
+
1115
+ // src/text.ts
1116
+ var text_en = {
1117
+ headers: {
1118
+ usage: "USAGE",
1119
+ aliases: "ALIASES",
1120
+ commands: "COMMANDS",
1121
+ flags: "FLAGS",
1122
+ arguments: "ARGUMENTS"
1123
+ },
1124
+ keywords: {
1125
+ default: "default =",
1126
+ separator: "separator ="
1127
+ },
1128
+ briefs: {
1129
+ help: "Print help information and exit",
1130
+ helpAll: "Print help information (including hidden commands/flags) and exit",
1131
+ version: "Print version information and exit",
1132
+ argumentEscapeSequence: "All subsequent inputs should be interpreted as arguments"
1133
+ },
1134
+ noCommandRegisteredForInput: ({ input, corrections }) => {
1135
+ const errorMessage = `No command registered for \`${input}\``;
1136
+ if (corrections.length > 0) {
1137
+ const formattedCorrections = joinWithGrammar(corrections, {
1138
+ kind: "conjunctive",
1139
+ conjunction: "or",
1140
+ serialComma: true
1141
+ });
1142
+ return `${errorMessage}, did you mean ${formattedCorrections}?`;
1143
+ } else {
1144
+ return errorMessage;
1145
+ }
1146
+ },
1147
+ noTextAvailableForLocale: ({ requestedLocale, defaultLocale }) => {
1148
+ return `Application does not support "${requestedLocale}" locale, defaulting to "${defaultLocale}"`;
1149
+ },
1150
+ exceptionWhileParsingArguments: (exc) => {
1151
+ if (exc instanceof ArgumentScannerError) {
1152
+ return formatMessageForArgumentScannerError(exc, {});
1153
+ }
1154
+ return `Unable to parse arguments, ${formatException(exc)}`;
1155
+ },
1156
+ exceptionWhileLoadingCommandFunction: (exc) => {
1157
+ return `Unable to load command function, ${formatException(exc)}`;
1158
+ },
1159
+ exceptionWhileLoadingCommandContext: (exc) => {
1160
+ return `Unable to load command context, ${formatException(exc)}`;
1161
+ },
1162
+ exceptionWhileRunningCommand: (exc) => {
1163
+ return `Command failed, ${formatException(exc)}`;
1164
+ },
1165
+ commandErrorResult: (err) => {
1166
+ return err.message;
1167
+ },
1168
+ currentVersionIsNotLatest: ({ currentVersion, latestVersion, upgradeCommand }) => {
1169
+ if (upgradeCommand) {
1170
+ return `Latest available version is ${latestVersion} (currently running ${currentVersion}), upgrade with "${upgradeCommand}"`;
1171
+ }
1172
+ return `Latest available version is ${latestVersion} (currently running ${currentVersion})`;
1173
+ }
1174
+ };
1175
+ function defaultTextLoader(locale) {
1176
+ if (locale.startsWith("en")) {
1177
+ return text_en;
1178
+ }
1179
+ }
1180
+ function shouldUseAnsiColor(process, stream, config) {
1181
+ return !config.disableAnsiColor && !checkEnvironmentVariable(process, "STRICLI_NO_COLOR") && (stream.getColorDepth?.(process.env) ?? 1) >= 4;
1182
+ }
1183
+
1184
+ // src/routing/command/run.ts
1185
+ async function runCommand({ loader, parameters }, {
1186
+ context,
1187
+ inputs,
1188
+ scannerConfig,
1189
+ errorFormatting,
1190
+ documentationConfig,
1191
+ determineExitCode
1192
+ }) {
1193
+ let parsedArguments;
1194
+ try {
1195
+ const scanner = buildArgumentScanner(parameters, scannerConfig);
1196
+ for (const input of inputs) {
1197
+ scanner.next(input);
1198
+ }
1199
+ const result = await scanner.parseArguments(context);
1200
+ if (result.success) {
1201
+ parsedArguments = result.arguments;
1202
+ } else {
1203
+ const ansiColor = shouldUseAnsiColor(context.process, context.process.stderr, documentationConfig);
1204
+ for (const error of result.errors) {
1205
+ const errorMessage = errorFormatting.exceptionWhileParsingArguments(error, ansiColor);
1206
+ context.process.stderr.write(
1207
+ ansiColor ? `\x1B[1m\x1B[31m${errorMessage}\x1B[39m\x1B[22m
1208
+ ` : `${errorMessage}
1209
+ `
1210
+ );
1211
+ }
1212
+ return ExitCode.InvalidArgument;
1213
+ }
1214
+ } catch (exc) {
1215
+ const ansiColor = shouldUseAnsiColor(context.process, context.process.stderr, documentationConfig);
1216
+ const errorMessage = errorFormatting.exceptionWhileParsingArguments(exc, ansiColor);
1217
+ context.process.stderr.write(
1218
+ ansiColor ? `\x1B[1m\x1B[31m${errorMessage}\x1B[39m\x1B[22m
1219
+ ` : `${errorMessage}
1220
+ `
1221
+ );
1222
+ return ExitCode.InvalidArgument;
1223
+ }
1224
+ let commandFunction;
1225
+ try {
1226
+ const loaded = await loader();
1227
+ if (typeof loaded === "function") {
1228
+ commandFunction = loaded;
1229
+ } else {
1230
+ commandFunction = loaded.default;
1231
+ }
1232
+ } catch (exc) {
1233
+ const ansiColor = shouldUseAnsiColor(context.process, context.process.stderr, documentationConfig);
1234
+ const errorMessage = errorFormatting.exceptionWhileLoadingCommandFunction(exc, ansiColor);
1235
+ context.process.stderr.write(
1236
+ ansiColor ? `\x1B[1m\x1B[31m${errorMessage}\x1B[39m\x1B[22m
1237
+ ` : `${errorMessage}
1238
+ `
1239
+ );
1240
+ return ExitCode.CommandLoadError;
1241
+ }
1242
+ try {
1243
+ const result = await commandFunction.call(context, ...parsedArguments);
1244
+ if (result instanceof Error) {
1245
+ const ansiColor = shouldUseAnsiColor(context.process, context.process.stderr, documentationConfig);
1246
+ const errorMessage = errorFormatting.commandErrorResult(result, ansiColor);
1247
+ context.process.stderr.write(
1248
+ ansiColor ? `\x1B[1m\x1B[31m${errorMessage}\x1B[39m\x1B[22m
1249
+ ` : `${errorMessage}
1250
+ `
1251
+ );
1252
+ if (determineExitCode) {
1253
+ return determineExitCode(result);
1254
+ }
1255
+ return ExitCode.CommandRunError;
1256
+ }
1257
+ } catch (exc) {
1258
+ const ansiColor = shouldUseAnsiColor(context.process, context.process.stderr, documentationConfig);
1259
+ const errorMessage = errorFormatting.exceptionWhileRunningCommand(exc, ansiColor);
1260
+ context.process.stderr.write(
1261
+ ansiColor ? `\x1B[1m\x1B[31m${errorMessage}\x1B[39m\x1B[22m
1262
+ ` : `${errorMessage}
1263
+ `
1264
+ );
1265
+ if (determineExitCode) {
1266
+ return determineExitCode(exc);
1267
+ }
1268
+ return ExitCode.CommandRunError;
1269
+ }
1270
+ return ExitCode.Success;
1271
+ }
1272
+
1273
+ // src/routing/route-map/types.ts
1274
+ var RouteMapSymbol = Symbol("RouteMap");
1275
+
1276
+ // src/routing/command/types.ts
1277
+ var CommandSymbol = Symbol("Command");
1278
+
1279
+ // src/routing/scanner.ts
1280
+ function buildRouteScanner(root, config, startingPrefix) {
1281
+ const prefix = [...startingPrefix];
1282
+ const unprocessedInputs = [];
1283
+ let parent;
1284
+ let current = root;
1285
+ let target;
1286
+ let rootLevel = true;
1287
+ let helpRequested = false;
1288
+ return {
1289
+ next: (input) => {
1290
+ if (input === "--help" || input === "-h") {
1291
+ helpRequested = true;
1292
+ if (!target) {
1293
+ target = current;
1294
+ }
1295
+ return;
1296
+ } else if (input === "--helpAll" || input === "--help-all" || input === "-H") {
1297
+ helpRequested = "all";
1298
+ if (!target) {
1299
+ target = current;
1300
+ }
1301
+ return;
1302
+ }
1303
+ if (target) {
1304
+ unprocessedInputs.push(input);
1305
+ return;
1306
+ }
1307
+ if (current.kind === CommandSymbol) {
1308
+ target = current;
1309
+ unprocessedInputs.push(input);
1310
+ return;
1311
+ }
1312
+ const camelCaseRouteName = convertKebabCaseToCamelCase(input);
1313
+ let internalRouteName = input;
1314
+ let next = current.getRoutingTargetForInput(internalRouteName);
1315
+ if (config.caseStyle === "allow-kebab-for-camel" && !next) {
1316
+ next = current.getRoutingTargetForInput(camelCaseRouteName);
1317
+ if (next) {
1318
+ internalRouteName = camelCaseRouteName;
1319
+ }
1320
+ }
1321
+ if (!next) {
1322
+ const defaultCommand = current.getDefaultCommand();
1323
+ if (defaultCommand) {
1324
+ rootLevel = false;
1325
+ parent = [current, ""];
1326
+ unprocessedInputs.push(input);
1327
+ current = defaultCommand;
1328
+ return;
1329
+ }
1330
+ return { input, routeMap: current };
1331
+ }
1332
+ rootLevel = false;
1333
+ parent = [current, input];
1334
+ current = next;
1335
+ prefix.push(input);
1336
+ },
1337
+ finish: () => {
1338
+ target = target ?? current;
1339
+ if (target.kind === RouteMapSymbol && !helpRequested) {
1340
+ const defaultCommand = target.getDefaultCommand();
1341
+ if (defaultCommand) {
1342
+ parent = [target, ""];
1343
+ target = defaultCommand;
1344
+ rootLevel = false;
1345
+ }
1346
+ }
1347
+ const aliases = parent ? parent[0].getOtherAliasesForInput(parent[1], config.caseStyle) : { original: [], "convert-camel-to-kebab": [] };
1348
+ return {
1349
+ target,
1350
+ unprocessedInputs,
1351
+ helpRequested,
1352
+ prefix,
1353
+ rootLevel,
1354
+ aliases
1355
+ };
1356
+ }
1357
+ };
1358
+ }
1359
+
1360
+ // src/application/run.ts
1361
+ async function runApplication({ root, defaultText, config }, rawInputs, context) {
1362
+ let text = defaultText;
1363
+ if (context.locale) {
1364
+ const localeText = config.localization.loadText(context.locale);
1365
+ if (localeText) {
1366
+ text = localeText;
1367
+ } else {
1368
+ const ansiColor = shouldUseAnsiColor(context.process, context.process.stderr, config.documentation);
1369
+ const warningMessage = text.noTextAvailableForLocale({
1370
+ requestedLocale: context.locale,
1371
+ defaultLocale: config.localization.defaultLocale,
1372
+ ansiColor
1373
+ });
1374
+ context.process.stderr.write(
1375
+ ansiColor ? `\x1B[1m\x1B[33m${warningMessage}\x1B[39m\x1B[22m
1376
+ ` : `${warningMessage}
1377
+ `
1378
+ );
1379
+ }
1380
+ }
1381
+ if (config.versionInfo?.getLatestVersion && !checkEnvironmentVariable(context.process, "STRICLI_SKIP_VERSION_CHECK")) {
1382
+ let currentVersion;
1383
+ if ("currentVersion" in config.versionInfo) {
1384
+ currentVersion = config.versionInfo.currentVersion;
1385
+ } else {
1386
+ currentVersion = await config.versionInfo.getCurrentVersion.call(context);
1387
+ }
1388
+ const latestVersion = await config.versionInfo.getLatestVersion.call(context, currentVersion);
1389
+ if (latestVersion && currentVersion !== latestVersion) {
1390
+ const ansiColor = shouldUseAnsiColor(context.process, context.process.stderr, config.documentation);
1391
+ const warningMessage = text.currentVersionIsNotLatest({
1392
+ currentVersion,
1393
+ latestVersion,
1394
+ upgradeCommand: config.versionInfo.upgradeCommand,
1395
+ ansiColor
1396
+ });
1397
+ context.process.stderr.write(
1398
+ ansiColor ? `\x1B[1m\x1B[33m${warningMessage}\x1B[39m\x1B[22m
1399
+ ` : `${warningMessage}
1400
+ `
1401
+ );
1402
+ }
1403
+ }
1404
+ const inputs = rawInputs.slice();
1405
+ if (config.versionInfo && (inputs[0] === "--version" || inputs[0] === "-v")) {
1406
+ let currentVersion;
1407
+ if ("currentVersion" in config.versionInfo) {
1408
+ currentVersion = config.versionInfo.currentVersion;
1409
+ } else {
1410
+ currentVersion = await config.versionInfo.getCurrentVersion.call(context);
1411
+ }
1412
+ context.process.stdout.write(currentVersion + "\n");
1413
+ return ExitCode.Success;
1414
+ }
1415
+ const scanner = buildRouteScanner(root, config.scanner, [config.name]);
1416
+ let error;
1417
+ while (inputs.length > 0 && !error) {
1418
+ const arg = inputs.shift();
1419
+ error = scanner.next(arg);
1420
+ }
1421
+ if (error) {
1422
+ const routeNames = listAllRouteNamesAndAliasesForScan(
1423
+ error.routeMap,
1424
+ config.scanner.caseStyle,
1425
+ config.completion
1426
+ );
1427
+ const corrections = filterClosestAlternatives(error.input, routeNames, config.scanner.distanceOptions).map(
1428
+ (str) => `\`${str}\``
1429
+ );
1430
+ const ansiColor = shouldUseAnsiColor(context.process, context.process.stderr, config.documentation);
1431
+ const errorMessage = text.noCommandRegisteredForInput({ input: error.input, corrections, ansiColor });
1432
+ context.process.stderr.write(
1433
+ ansiColor ? `\x1B[1m\x1B[31m${errorMessage}\x1B[39m\x1B[22m
1434
+ ` : `${errorMessage}
1435
+ `
1436
+ );
1437
+ return ExitCode.UnknownCommand;
1438
+ }
1439
+ const result = scanner.finish();
1440
+ if (result.helpRequested || result.target.kind === RouteMapSymbol) {
1441
+ const ansiColor = shouldUseAnsiColor(context.process, context.process.stdout, config.documentation);
1442
+ context.process.stdout.write(
1443
+ result.target.formatHelp({
1444
+ prefix: result.prefix,
1445
+ includeVersionFlag: Boolean(config.versionInfo) && result.rootLevel,
1446
+ includeArgumentEscapeSequenceFlag: config.scanner.allowArgumentEscapeSequence,
1447
+ includeHelpAllFlag: result.helpRequested === "all" || config.documentation.alwaysShowHelpAllFlag,
1448
+ includeHidden: result.helpRequested === "all",
1449
+ config: config.documentation,
1450
+ aliases: result.aliases[config.documentation.caseStyle],
1451
+ text,
1452
+ ansiColor
1453
+ })
1454
+ );
1455
+ return ExitCode.Success;
1456
+ }
1457
+ let commandContext;
1458
+ if ("forCommand" in context) {
1459
+ try {
1460
+ commandContext = await context.forCommand({ prefix: result.prefix });
1461
+ } catch (exc) {
1462
+ const ansiColor = shouldUseAnsiColor(context.process, context.process.stderr, config.documentation);
1463
+ const errorMessage = text.exceptionWhileLoadingCommandContext(exc, ansiColor);
1464
+ context.process.stderr.write(ansiColor ? `\x1B[1m\x1B[31m${errorMessage}\x1B[39m\x1B[22m` : errorMessage);
1465
+ return ExitCode.ContextLoadError;
1466
+ }
1467
+ } else {
1468
+ commandContext = context;
1469
+ }
1470
+ return runCommand(result.target, {
1471
+ context: commandContext,
1472
+ inputs: result.unprocessedInputs,
1473
+ scannerConfig: config.scanner,
1474
+ documentationConfig: config.documentation,
1475
+ errorFormatting: text,
1476
+ determineExitCode: config.determineExitCode
1477
+ });
1478
+ }
1479
+
1480
+ // src/config.ts
1481
+ function formatForDisplay(flagName, displayCaseStyle) {
1482
+ if (displayCaseStyle === "convert-camel-to-kebab") {
1483
+ return convertCamelCaseToKebabCase(flagName);
1484
+ }
1485
+ return flagName;
1486
+ }
1487
+ function formatAsNegated(flagName, displayCaseStyle) {
1488
+ if (displayCaseStyle === "convert-camel-to-kebab") {
1489
+ return `no-${convertCamelCaseToKebabCase(flagName)}`;
1490
+ }
1491
+ return `no${flagName[0].toUpperCase()}${flagName.slice(1)}`;
1492
+ }
1493
+ function withDefaults(config) {
1494
+ const scannerCaseStyle = config.scanner?.caseStyle ?? "original";
1495
+ let displayCaseStyle;
1496
+ if (config.documentation?.caseStyle) {
1497
+ if (scannerCaseStyle === "original" && config.documentation.caseStyle === "convert-camel-to-kebab") {
1498
+ throw new InternalError("Cannot convert route and flag names on display but scan as original");
1499
+ }
1500
+ displayCaseStyle = config.documentation.caseStyle;
1501
+ } else if (scannerCaseStyle === "allow-kebab-for-camel") {
1502
+ displayCaseStyle = "convert-camel-to-kebab";
1503
+ } else {
1504
+ displayCaseStyle = scannerCaseStyle;
1505
+ }
1506
+ const scannerConfig = {
1507
+ caseStyle: scannerCaseStyle,
1508
+ allowArgumentEscapeSequence: config.scanner?.allowArgumentEscapeSequence ?? false,
1509
+ distanceOptions: config.scanner?.distanceOptions ?? {
1510
+ threshold: 7,
1511
+ weights: {
1512
+ insertion: 1,
1513
+ deletion: 3,
1514
+ substitution: 2,
1515
+ transposition: 0
1516
+ }
1517
+ }
1518
+ };
1519
+ const documentationConfig = {
1520
+ alwaysShowHelpAllFlag: config.documentation?.alwaysShowHelpAllFlag ?? false,
1521
+ useAliasInUsageLine: config.documentation?.useAliasInUsageLine ?? false,
1522
+ onlyRequiredInUsageLine: config.documentation?.onlyRequiredInUsageLine ?? false,
1523
+ caseStyle: displayCaseStyle,
1524
+ disableAnsiColor: config.documentation?.disableAnsiColor ?? false
1525
+ };
1526
+ const completionConfig = {
1527
+ includeAliases: config.completion?.includeAliases ?? documentationConfig.useAliasInUsageLine,
1528
+ includeHiddenRoutes: config.completion?.includeHiddenRoutes ?? false,
1529
+ ...config.completion
1530
+ };
1531
+ return {
1532
+ ...config,
1533
+ scanner: scannerConfig,
1534
+ completion: completionConfig,
1535
+ documentation: documentationConfig,
1536
+ localization: {
1537
+ defaultLocale: "en",
1538
+ loadText: defaultTextLoader,
1539
+ ...config.localization
1540
+ }
1541
+ };
1542
+ }
1543
+
1544
+ // src/application/builder.ts
1545
+ function buildApplication(root, appConfig) {
1546
+ const config = withDefaults(appConfig);
1547
+ if (root.kind === CommandSymbol && config.versionInfo) {
1548
+ if (root.usesFlag("version")) {
1549
+ throw new InternalError("Unable to use command with flag --version as root when version info is supplied");
1550
+ }
1551
+ if (root.usesFlag("v")) {
1552
+ throw new InternalError("Unable to use command with alias -v as root when version info is supplied");
1553
+ }
1554
+ }
1555
+ const defaultText = config.localization.loadText(config.localization.defaultLocale);
1556
+ if (!defaultText) {
1557
+ throw new InternalError(`No text available for the default locale "${config.localization.defaultLocale}"`);
1558
+ }
1559
+ return {
1560
+ root,
1561
+ config,
1562
+ defaultText
1563
+ };
1564
+ }
1565
+
1566
+ // src/application/documentation.ts
1567
+ function* iterateAllCommands(routeMap, prefix, caseStyle) {
1568
+ for (const entry of routeMap.getAllEntries()) {
1569
+ if (entry.hidden) {
1570
+ continue;
1571
+ }
1572
+ const routeName = entry.name[caseStyle];
1573
+ const route = [...prefix, routeName];
1574
+ if (entry.target.kind === RouteMapSymbol) {
1575
+ yield* iterateAllCommands(entry.target, route, caseStyle);
1576
+ } else {
1577
+ yield [route, entry.target, entry.aliases];
1578
+ }
1579
+ }
1580
+ }
1581
+ function generateHelpTextForAllCommands({ root, defaultText, config }, locale) {
1582
+ let text = defaultText;
1583
+ if (locale) {
1584
+ const localeText = config.localization.loadText(locale);
1585
+ if (localeText) {
1586
+ text = localeText;
1587
+ } else {
1588
+ throw new InternalError(`Application does not support "${locale}" locale`);
1589
+ }
1590
+ }
1591
+ const commands = [];
1592
+ if (root.kind === CommandSymbol) {
1593
+ commands.push([[config.name], root, []]);
1594
+ } else {
1595
+ commands.push(...iterateAllCommands(root, [config.name], config.documentation.caseStyle));
1596
+ }
1597
+ return commands.map(([route, command, aliases]) => {
1598
+ return [
1599
+ route.join(" "),
1600
+ command.formatHelp({
1601
+ prefix: route,
1602
+ config: config.documentation,
1603
+ includeVersionFlag: Boolean(config.versionInfo) && route.length === 1,
1604
+ includeArgumentEscapeSequenceFlag: config.scanner.allowArgumentEscapeSequence,
1605
+ includeHelpAllFlag: config.documentation.alwaysShowHelpAllFlag,
1606
+ includeHidden: false,
1607
+ aliases,
1608
+ text,
1609
+ ansiColor: false
1610
+ })
1611
+ ];
1612
+ });
1613
+ }
1614
+
1615
+ // src/routing/command/propose-completions.ts
1616
+ async function proposeCompletionsForCommand({ parameters }, args) {
1617
+ try {
1618
+ const scanner = buildArgumentScanner(parameters, args.scannerConfig);
1619
+ for (const input of args.inputs) {
1620
+ scanner.next(input);
1621
+ }
1622
+ return await scanner.proposeCompletions(args);
1623
+ } catch {
1624
+ return [];
1625
+ }
1626
+ }
1627
+
1628
+ // src/routing/route-map/propose-completions.ts
1629
+ async function proposeCompletionsForRouteMap(routeMap, { partial, scannerConfig, completionConfig }) {
1630
+ let entries = routeMap.getAllEntries();
1631
+ if (!completionConfig.includeHiddenRoutes) {
1632
+ entries = entries.filter((entry) => !entry.hidden);
1633
+ }
1634
+ const displayCaseStyle = scannerConfig.caseStyle === "allow-kebab-for-camel" ? "convert-camel-to-kebab" : scannerConfig.caseStyle;
1635
+ return entries.flatMap((entry) => {
1636
+ const kind = entry.target.kind === CommandSymbol ? "routing-target:command" : "routing-target:route-map";
1637
+ const brief = entry.target.brief;
1638
+ const targetCompletion = {
1639
+ kind,
1640
+ completion: entry.name[displayCaseStyle],
1641
+ brief
1642
+ };
1643
+ if (completionConfig.includeAliases) {
1644
+ return [
1645
+ targetCompletion,
1646
+ ...entry.aliases.map((alias) => {
1647
+ return {
1648
+ kind,
1649
+ completion: alias,
1650
+ brief
1651
+ };
1652
+ })
1653
+ ];
1654
+ }
1655
+ return [targetCompletion];
1656
+ }).filter(({ completion }) => completion.startsWith(partial));
1657
+ }
1658
+
1659
+ // src/application/propose-completions.ts
1660
+ async function proposeCompletionsForApplication({ root, config, defaultText }, rawInputs, context) {
1661
+ if (rawInputs.length === 0) {
1662
+ return [];
1663
+ }
1664
+ const scanner = buildRouteScanner(root, config.scanner, []);
1665
+ const leadingInputs = rawInputs.slice(0, -1);
1666
+ let error;
1667
+ while (leadingInputs.length > 0 && !error) {
1668
+ const input = leadingInputs.shift();
1669
+ error = scanner.next(input);
1670
+ }
1671
+ if (error) {
1672
+ return [];
1673
+ }
1674
+ const result = scanner.finish();
1675
+ if (result.helpRequested) {
1676
+ return [];
1677
+ }
1678
+ let commandContext;
1679
+ if ("forCommand" in context) {
1680
+ try {
1681
+ commandContext = await context.forCommand({ prefix: result.prefix });
1682
+ } catch {
1683
+ return [];
1684
+ }
1685
+ } else {
1686
+ commandContext = context;
1687
+ }
1688
+ const partial = rawInputs[rawInputs.length - 1];
1689
+ if (result.target.kind === RouteMapSymbol) {
1690
+ return proposeCompletionsForRouteMap(result.target, {
1691
+ context: commandContext,
1692
+ partial,
1693
+ scannerConfig: config.scanner,
1694
+ completionConfig: config.completion
1695
+ });
1696
+ }
1697
+ return proposeCompletionsForCommand(result.target, {
1698
+ context: commandContext,
1699
+ inputs: result.unprocessedInputs,
1700
+ partial,
1701
+ scannerConfig: config.scanner,
1702
+ completionConfig: config.completion,
1703
+ text: defaultText,
1704
+ includeVersionFlag: Boolean(config.versionInfo) && result.rootLevel
1705
+ });
1706
+ }
1707
+
1708
+ // src/parameter/parser/choice.ts
1709
+ function narrowString(choices, value) {
1710
+ return choices.includes(value);
1711
+ }
1712
+ function buildChoiceParser(choices) {
1713
+ return (input) => {
1714
+ if (!narrowString(choices, input)) {
1715
+ throw new SyntaxError(`${input} is not one of (${choices.join("|")})`);
1716
+ }
1717
+ return input;
1718
+ };
1719
+ }
1720
+
1721
+ // src/parameter/flag/types.ts
1722
+ function hasDefault(flag) {
1723
+ return "default" in flag && typeof flag.default !== "undefined";
1724
+ }
1725
+ function isOptionalAtRuntime(flag) {
1726
+ return flag.optional ?? hasDefault(flag);
1727
+ }
1728
+
1729
+ // src/parameter/formatting.ts
1730
+ function wrapRequiredFlag(text) {
1731
+ return `(${text})`;
1732
+ }
1733
+ function wrapOptionalFlag(text) {
1734
+ return `[${text}]`;
1735
+ }
1736
+ function wrapVariadicFlag(text) {
1737
+ return `${text}...`;
1738
+ }
1739
+ function wrapRequiredParameter(text) {
1740
+ return `<${text}>`;
1741
+ }
1742
+ function wrapOptionalParameter(text) {
1743
+ return `[<${text}>]`;
1744
+ }
1745
+ function wrapVariadicParameter(text) {
1746
+ return `<${text}>...`;
1747
+ }
1748
+ function formatUsageLineForParameters(parameters, args) {
1749
+ const flagsUsage = Object.entries(parameters.flags ?? {}).filter(([, flag]) => {
1750
+ if (flag.hidden) {
1751
+ return false;
1752
+ }
1753
+ if (args.config.onlyRequiredInUsageLine && isOptionalAtRuntime(flag)) {
1754
+ return false;
1755
+ }
1756
+ return true;
1757
+ }).map(([name, flag]) => {
1758
+ let displayName = args.config.caseStyle === "convert-camel-to-kebab" ? `--${convertCamelCaseToKebabCase(name)}` : `--${name}`;
1759
+ if (parameters.aliases && args.config.useAliasInUsageLine) {
1760
+ const aliases = Object.entries(parameters.aliases).filter((entry) => entry[1] === name);
1761
+ if (aliases.length === 1 && aliases[0]) {
1762
+ displayName = `-${aliases[0][0]}`;
1763
+ }
1764
+ }
1765
+ if (flag.kind === "boolean") {
1766
+ return [flag, displayName];
1767
+ }
1768
+ if (flag.kind === "enum" && typeof flag.placeholder !== "string") {
1769
+ return [flag, `${displayName} ${flag.values.join("|")}`];
1770
+ }
1771
+ const placeholder = flag.placeholder ?? "value";
1772
+ return [flag, `${displayName} ${placeholder}`];
1773
+ }).map(([flag, usage]) => {
1774
+ if (flag.kind === "parsed" && flag.variadic) {
1775
+ if (isOptionalAtRuntime(flag)) {
1776
+ return wrapVariadicFlag(wrapOptionalFlag(usage));
1777
+ }
1778
+ return wrapVariadicFlag(wrapRequiredFlag(usage));
1779
+ }
1780
+ if (isOptionalAtRuntime(flag)) {
1781
+ return wrapOptionalFlag(usage);
1782
+ }
1783
+ return wrapRequiredFlag(usage);
1784
+ });
1785
+ let positionalUsage = [];
1786
+ const positional = parameters.positional;
1787
+ if (positional) {
1788
+ if (positional.kind === "array") {
1789
+ positionalUsage = [wrapVariadicParameter(positional.parameter.placeholder ?? "args")];
1790
+ } else {
1791
+ let parameters2 = positional.parameters;
1792
+ if (args.config.onlyRequiredInUsageLine) {
1793
+ parameters2 = parameters2.filter((param) => !param.optional && typeof param.default === "undefined");
1794
+ }
1795
+ positionalUsage = parameters2.map((param, i) => {
1796
+ const argName = param.placeholder ?? `arg${i + 1}`;
1797
+ return param.optional || typeof param.default !== "undefined" ? wrapOptionalParameter(argName) : wrapRequiredParameter(argName);
1798
+ });
1799
+ }
1800
+ }
1801
+ return [...args.prefix, ...flagsUsage, ...positionalUsage].join(" ");
1802
+ }
1803
+
1804
+ // src/parameter/flag/formatting.ts
1805
+ function formatDocumentationForFlagParameters(flags, aliases, args) {
1806
+ const { keywords, briefs } = args.text;
1807
+ const visibleFlags = Object.entries(flags).filter(([, flag]) => {
1808
+ if (flag.hidden && !args.includeHidden) {
1809
+ return false;
1810
+ }
1811
+ return true;
1812
+ });
1813
+ const atLeastOneOptional = visibleFlags.some(([, flag]) => isOptionalAtRuntime(flag));
1814
+ const rows = visibleFlags.map(([name, flag]) => {
1815
+ const aliasStrings = Object.entries(aliases).filter((entry) => entry[1] === name).map(([alias]) => `-${alias}`);
1816
+ let flagName = "--" + formatForDisplay(name, args.config.caseStyle);
1817
+ if (flag.kind === "boolean" && flag.default !== false && flag.withNegated !== false) {
1818
+ const negatedFlagName = formatAsNegated(name, args.config.caseStyle);
1819
+ flagName = `${flagName}/--${negatedFlagName}`;
1820
+ }
1821
+ if (isOptionalAtRuntime(flag)) {
1822
+ flagName = `[${flagName}]`;
1823
+ } else if (atLeastOneOptional) {
1824
+ flagName = ` ${flagName}`;
1825
+ }
1826
+ if (flag.kind === "parsed" && flag.variadic) {
1827
+ flagName = `${flagName}...`;
1828
+ }
1829
+ const suffixParts = [];
1830
+ if (flag.kind === "enum") {
1831
+ const choices = flag.values.join("|");
1832
+ suffixParts.push(choices);
1833
+ }
1834
+ if (hasDefault(flag)) {
1835
+ const defaultKeyword = args.ansiColor ? `\x1B[90m${keywords.default}\x1B[39m` : keywords.default;
1836
+ let defaultValue;
1837
+ if (Array.isArray(flag.default)) {
1838
+ if (flag.default.length === 0) {
1839
+ defaultValue = "[]";
1840
+ } else {
1841
+ const separator = "variadic" in flag && typeof flag.variadic === "string" ? flag.variadic : " ";
1842
+ defaultValue = flag.default.join(separator);
1843
+ }
1844
+ } else {
1845
+ defaultValue = flag.default === "" ? `""` : String(flag.default);
1846
+ }
1847
+ suffixParts.push(`${defaultKeyword} ${defaultValue}`);
1848
+ }
1849
+ if ("variadic" in flag && typeof flag.variadic === "string") {
1850
+ const separatorKeyword = args.ansiColor ? `\x1B[90m${keywords.separator}\x1B[39m` : keywords.separator;
1851
+ suffixParts.push(`${separatorKeyword} ${flag.variadic}`);
1852
+ }
1853
+ const suffix = suffixParts.length > 0 ? `[${suffixParts.join(", ")}]` : void 0;
1854
+ return {
1855
+ aliases: aliasStrings.join(" "),
1856
+ flagName,
1857
+ brief: flag.brief,
1858
+ suffix,
1859
+ hidden: flag.hidden
1860
+ };
1861
+ });
1862
+ rows.push({
1863
+ aliases: "-h",
1864
+ flagName: atLeastOneOptional ? " --help" : "--help",
1865
+ brief: briefs.help
1866
+ });
1867
+ if (args.includeHelpAllFlag) {
1868
+ const helpAllFlagName = formatForDisplay("helpAll", args.config.caseStyle);
1869
+ rows.push({
1870
+ aliases: "-H",
1871
+ flagName: atLeastOneOptional ? ` --${helpAllFlagName}` : `--${helpAllFlagName}`,
1872
+ brief: briefs.helpAll,
1873
+ hidden: !args.config.alwaysShowHelpAllFlag
1874
+ });
1875
+ }
1876
+ if (args.includeVersionFlag) {
1877
+ rows.push({
1878
+ aliases: "-v",
1879
+ flagName: atLeastOneOptional ? " --version" : "--version",
1880
+ brief: briefs.version
1881
+ });
1882
+ }
1883
+ if (args.includeArgumentEscapeSequenceFlag) {
1884
+ rows.push({
1885
+ aliases: "",
1886
+ flagName: atLeastOneOptional ? " --" : "--",
1887
+ brief: briefs.argumentEscapeSequence
1888
+ });
1889
+ }
1890
+ return formatRowsWithColumns(
1891
+ rows.map((row) => {
1892
+ if (!args.ansiColor) {
1893
+ return [row.aliases, row.flagName, row.brief, row.suffix ?? ""];
1894
+ }
1895
+ return [
1896
+ row.hidden ? `\x1B[90m${row.aliases}\x1B[39m` : `\x1B[97m${row.aliases}\x1B[39m`,
1897
+ row.hidden ? `\x1B[90m${row.flagName}\x1B[39m` : `\x1B[97m${row.flagName}\x1B[39m`,
1898
+ row.hidden ? `\x1B[90m${row.brief}\x1B[39m` : `\x1B[03m${row.brief}\x1B[23m`,
1899
+ row.suffix ?? ""
1900
+ ];
1901
+ }),
1902
+ [" ", " ", " "]
1903
+ );
1904
+ }
1905
+ function* generateBuiltInFlagUsageLines(args) {
1906
+ yield args.config.useAliasInUsageLine ? "-h" : "--help";
1907
+ if (args.includeHelpAllFlag) {
1908
+ const helpAllFlagName = formatForDisplay("helpAll", args.config.caseStyle);
1909
+ yield args.config.useAliasInUsageLine ? "-H" : `--${helpAllFlagName}`;
1910
+ }
1911
+ if (args.includeVersionFlag) {
1912
+ yield args.config.useAliasInUsageLine ? "-v" : "--version";
1913
+ }
1914
+ }
1915
+
1916
+ // src/parameter/positional/formatting.ts
1917
+ function formatDocumentationForPositionalParameters(positional, args) {
1918
+ if (positional.kind === "array") {
1919
+ const name = positional.parameter.placeholder ?? "args";
1920
+ const argName = args.ansiColor ? `\x1B[97m${name}...\x1B[39m` : `${name}...`;
1921
+ const brief = args.ansiColor ? `\x1B[3m${positional.parameter.brief}\x1B[23m` : positional.parameter.brief;
1922
+ return formatRowsWithColumns([[argName, brief]], [" "]);
1923
+ }
1924
+ const { keywords } = args.text;
1925
+ const atLeastOneOptional = positional.parameters.some((def) => def.optional);
1926
+ return formatRowsWithColumns(
1927
+ positional.parameters.map((def, i) => {
1928
+ let name = def.placeholder ?? `arg${i + 1}`;
1929
+ let suffix;
1930
+ if (def.optional) {
1931
+ name = `[${name}]`;
1932
+ } else if (atLeastOneOptional) {
1933
+ name = ` ${name}`;
1934
+ }
1935
+ if (def.default) {
1936
+ const defaultKeyword = args.ansiColor ? `\x1B[90m${keywords.default}\x1B[39m` : keywords.default;
1937
+ suffix = `[${defaultKeyword} ${def.default}]`;
1938
+ }
1939
+ return [
1940
+ args.ansiColor ? `\x1B[97m${name}\x1B[39m` : name,
1941
+ args.ansiColor ? `\x1B[3m${def.brief}\x1B[23m` : def.brief,
1942
+ suffix ?? ""
1943
+ ];
1944
+ }),
1945
+ [" ", " "]
1946
+ );
1947
+ }
1948
+
1949
+ // src/routing/command/documentation.ts
1950
+ function* generateCommandHelpLines(parameters, docs, args) {
1951
+ const { brief, fullDescription, customUsage } = docs;
1952
+ const { headers } = args.text;
1953
+ const prefix = args.prefix.join(" ");
1954
+ yield args.ansiColor ? `\x1B[1m${headers.usage}\x1B[22m` : headers.usage;
1955
+ if (customUsage) {
1956
+ for (const usage of customUsage) {
1957
+ if (typeof usage === "string") {
1958
+ yield ` ${prefix} ${usage}`;
1959
+ } else {
1960
+ const brief2 = args.ansiColor ? `\x1B[3m${usage.brief}\x1B[23m` : usage.brief;
1961
+ yield ` ${prefix} ${usage.input}
1962
+ ${brief2}`;
1963
+ }
1964
+ }
1965
+ } else {
1966
+ yield ` ${formatUsageLineForParameters(parameters, args)}`;
1967
+ }
1968
+ for (const line of generateBuiltInFlagUsageLines(args)) {
1969
+ yield ` ${prefix} ${line}`;
1970
+ }
1971
+ yield "";
1972
+ yield fullDescription ?? brief;
1973
+ if (args.aliases && args.aliases.length > 0) {
1974
+ const aliasPrefix = args.prefix.slice(0, -1).join(" ");
1975
+ yield "";
1976
+ yield args.ansiColor ? `\x1B[1m${headers.aliases}\x1B[22m` : headers.aliases;
1977
+ for (const alias of args.aliases) {
1978
+ yield ` ${aliasPrefix} ${alias}`;
1979
+ }
1980
+ }
1981
+ yield "";
1982
+ yield args.ansiColor ? `\x1B[1m${headers.flags}\x1B[22m` : headers.flags;
1983
+ for (const line of formatDocumentationForFlagParameters(parameters.flags ?? {}, parameters.aliases ?? {}, args)) {
1984
+ yield ` ${line}`;
1985
+ }
1986
+ const positional = parameters.positional ?? { kind: "tuple", parameters: [] };
1987
+ if (positional.kind === "array" || positional.parameters.length > 0) {
1988
+ yield "";
1989
+ yield args.ansiColor ? `\x1B[1m${headers.arguments}\x1B[22m` : headers.arguments;
1990
+ for (const line of formatDocumentationForPositionalParameters(positional, args)) {
1991
+ yield ` ${line}`;
1992
+ }
1993
+ }
1994
+ }
1995
+
1996
+ // src/routing/command/builder.ts
1997
+ function checkForReservedFlags(flags, reserved) {
1998
+ for (const flag of reserved) {
1999
+ if (flag in flags) {
2000
+ throw new InternalError(`Unable to use reserved flag --${flag}`);
2001
+ }
2002
+ }
2003
+ }
2004
+ function checkForReservedAliases(aliases, reserved) {
2005
+ for (const alias of reserved) {
2006
+ if (alias in aliases) {
2007
+ throw new InternalError(`Unable to use reserved alias -${alias}`);
2008
+ }
2009
+ }
2010
+ }
2011
+ function* asNegationFlagNames(flagName) {
2012
+ yield `no-${convertCamelCaseToKebabCase(flagName)}`;
2013
+ yield `no${flagName[0].toUpperCase()}${flagName.slice(1)}`;
2014
+ }
2015
+ function checkForNegationCollisions(flags) {
2016
+ const flagsAllowingNegation = Object.entries(flags).filter(([, flag]) => flag.kind === "boolean" && !flag.optional);
2017
+ for (const [internalFlagName] of flagsAllowingNegation) {
2018
+ for (const negatedFlagName of asNegationFlagNames(internalFlagName)) {
2019
+ if (negatedFlagName in flags) {
2020
+ throw new InternalError(
2021
+ `Unable to allow negation for --${internalFlagName} as it conflicts with --${negatedFlagName}`
2022
+ );
2023
+ }
2024
+ }
2025
+ }
2026
+ }
2027
+ function checkForInvalidVariadicSeparators(flags) {
2028
+ for (const [internalFlagName, flag] of Object.entries(flags)) {
2029
+ if ("variadic" in flag && typeof flag.variadic === "string") {
2030
+ if (flag.variadic.length < 1) {
2031
+ throw new InternalError(
2032
+ `Unable to use "" as variadic separator for --${internalFlagName} as it is empty`
2033
+ );
2034
+ }
2035
+ if (/\s/.test(flag.variadic)) {
2036
+ throw new InternalError(
2037
+ `Unable to use "${flag.variadic}" as variadic separator for --${internalFlagName} as it contains whitespace`
2038
+ );
2039
+ }
2040
+ }
2041
+ }
2042
+ }
2043
+ function buildCommand(builderArgs) {
2044
+ const { flags = {}, aliases = {} } = builderArgs.parameters;
2045
+ checkForReservedFlags(flags, ["help", "helpAll", "help-all"]);
2046
+ checkForReservedAliases(aliases, ["h", "H"]);
2047
+ checkForNegationCollisions(flags);
2048
+ checkForInvalidVariadicSeparators(flags);
2049
+ let loader;
2050
+ if ("func" in builderArgs) {
2051
+ loader = async () => builderArgs.func;
2052
+ } else {
2053
+ loader = builderArgs.loader;
2054
+ }
2055
+ return {
2056
+ kind: CommandSymbol,
2057
+ loader,
2058
+ parameters: builderArgs.parameters,
2059
+ get brief() {
2060
+ return builderArgs.docs.brief;
2061
+ },
2062
+ /* v8 ignore next -- @preserve */
2063
+ get fullDescription() {
2064
+ return builderArgs.docs.fullDescription;
2065
+ },
2066
+ formatUsageLine: (args) => {
2067
+ return formatUsageLineForParameters(builderArgs.parameters, args);
2068
+ },
2069
+ formatHelp: (args) => {
2070
+ const lines = [
2071
+ ...generateCommandHelpLines(builderArgs.parameters, builderArgs.docs, args)
2072
+ ];
2073
+ const text = lines.join("\n");
2074
+ return text + "\n";
2075
+ },
2076
+ usesFlag: (flagName) => {
2077
+ return Boolean(flagName in flags || flagName in aliases);
2078
+ }
2079
+ };
2080
+ }
2081
+
2082
+ // src/routing/route-map/documentation.ts
2083
+ function* generateRouteMapHelpLines(routes, docs, args) {
2084
+ const { brief, fullDescription, hideRoute } = docs;
2085
+ const { headers } = args.text;
2086
+ yield args.ansiColor ? `\x1B[1m${headers.usage}\x1B[22m` : headers.usage;
2087
+ for (const [name, route] of Object.entries(routes)) {
2088
+ if (!hideRoute || !hideRoute[name] || args.includeHidden) {
2089
+ const externalRouteName = args.config.caseStyle === "convert-camel-to-kebab" ? convertCamelCaseToKebabCase(name) : name;
2090
+ yield ` ${route.formatUsageLine({
2091
+ ...args,
2092
+ prefix: [...args.prefix, externalRouteName]
2093
+ })}`;
2094
+ }
2095
+ }
2096
+ const prefix = args.prefix.join(" ");
2097
+ for (const line of generateBuiltInFlagUsageLines(args)) {
2098
+ yield ` ${prefix} ${line}`;
2099
+ }
2100
+ yield "";
2101
+ yield fullDescription ?? brief;
2102
+ if (args.aliases && args.aliases.length > 0) {
2103
+ const aliasPrefix = args.prefix.slice(0, -1).join(" ");
2104
+ yield "";
2105
+ yield args.ansiColor ? `\x1B[1m${headers.aliases}\x1B[22m` : headers.aliases;
2106
+ for (const alias of args.aliases) {
2107
+ yield ` ${aliasPrefix} ${alias}`;
2108
+ }
2109
+ }
2110
+ yield "";
2111
+ yield args.ansiColor ? `\x1B[1m${headers.flags}\x1B[22m` : headers.flags;
2112
+ for (const line of formatDocumentationForFlagParameters({}, {}, args)) {
2113
+ yield ` ${line}`;
2114
+ }
2115
+ yield "";
2116
+ yield args.ansiColor ? `\x1B[1m${headers.commands}\x1B[22m` : headers.commands;
2117
+ const visibleRoutes = Object.entries(routes).filter(
2118
+ ([name]) => !hideRoute || !hideRoute[name] || args.includeHidden
2119
+ );
2120
+ const rows = visibleRoutes.map(([internalRouteName, route]) => {
2121
+ const externalRouteName = formatForDisplay(internalRouteName, args.config.caseStyle);
2122
+ return {
2123
+ routeName: externalRouteName,
2124
+ brief: route.brief,
2125
+ hidden: hideRoute && hideRoute[internalRouteName]
2126
+ };
2127
+ });
2128
+ const formattedRows = formatRowsWithColumns(
2129
+ rows.map((row) => {
2130
+ if (!args.ansiColor) {
2131
+ return [row.routeName, row.brief];
2132
+ }
2133
+ return [
2134
+ row.hidden ? `\x1B[90m${row.routeName}\x1B[39m` : `\x1B[97m${row.routeName}\x1B[39m`,
2135
+ row.hidden ? `\x1B[90m${row.brief}\x1B[39m` : `\x1B[03m${row.brief}\x1B[23m`
2136
+ ];
2137
+ }),
2138
+ [" "]
2139
+ );
2140
+ for (const line of formattedRows) {
2141
+ yield ` ${line}`;
2142
+ }
2143
+ }
2144
+
2145
+ // src/routing/route-map/builder.ts
2146
+ function buildRouteMap({
2147
+ routes,
2148
+ defaultCommand: defaultCommandRoute,
2149
+ docs,
2150
+ aliases
2151
+ }) {
2152
+ if (Object.entries(routes).length === 0) {
2153
+ throw new InternalError("Route map must contain at least one route");
2154
+ }
2155
+ const activeAliases = aliases ?? {};
2156
+ const aliasesByRoute = /* @__PURE__ */ new Map();
2157
+ for (const [alias, routeName] of Object.entries(activeAliases)) {
2158
+ if (alias in routes) {
2159
+ throw new InternalError(`Cannot use "${alias}" as an alias when a route with that name already exists`);
2160
+ }
2161
+ const routeAliases = aliasesByRoute.get(routeName) ?? [];
2162
+ aliasesByRoute.set(routeName, [...routeAliases, alias]);
2163
+ }
2164
+ const defaultCommand = defaultCommandRoute ? routes[defaultCommandRoute] : void 0;
2165
+ if (defaultCommand && defaultCommand.kind === RouteMapSymbol) {
2166
+ throw new InternalError(
2167
+ `Cannot use "${defaultCommandRoute}" as the default command because it is not a Command`
2168
+ );
2169
+ }
2170
+ const resolveRouteName = (input) => {
2171
+ if (input in activeAliases) {
2172
+ return activeAliases[input];
2173
+ } else if (input in routes) {
2174
+ return input;
2175
+ }
2176
+ };
2177
+ return {
2178
+ kind: RouteMapSymbol,
2179
+ get brief() {
2180
+ return docs.brief;
2181
+ },
2182
+ /* v8 ignore next -- @preserve */
2183
+ get fullDescription() {
2184
+ return docs.fullDescription;
2185
+ },
2186
+ formatUsageLine(args) {
2187
+ const routeNames = this.getAllEntries().filter((entry) => !entry.hidden).map((entry) => entry.name[args.config.caseStyle]);
2188
+ return `${args.prefix.join(" ")} ${routeNames.join("|")} ...`;
2189
+ },
2190
+ formatHelp: (config) => {
2191
+ const lines = [...generateRouteMapHelpLines(routes, docs, config)];
2192
+ const text = lines.join("\n");
2193
+ return text + "\n";
2194
+ },
2195
+ getDefaultCommand: () => {
2196
+ return defaultCommand;
2197
+ },
2198
+ getOtherAliasesForInput: (input, caseStyle) => {
2199
+ if (defaultCommandRoute) {
2200
+ if (input === defaultCommandRoute) {
2201
+ return {
2202
+ original: [""],
2203
+ "convert-camel-to-kebab": [""]
2204
+ };
2205
+ }
2206
+ if (input === "") {
2207
+ return {
2208
+ original: [defaultCommandRoute],
2209
+ "convert-camel-to-kebab": [defaultCommandRoute]
2210
+ };
2211
+ }
2212
+ }
2213
+ const camelInput = convertKebabCaseToCamelCase(input);
2214
+ let routeName = resolveRouteName(input);
2215
+ if (!routeName && caseStyle === "allow-kebab-for-camel") {
2216
+ routeName = resolveRouteName(camelInput);
2217
+ }
2218
+ if (!routeName) {
2219
+ return {
2220
+ original: [],
2221
+ "convert-camel-to-kebab": []
2222
+ };
2223
+ }
2224
+ const otherAliases = [routeName, ...aliasesByRoute.get(routeName) ?? []].filter(
2225
+ (alias) => alias !== input && alias !== camelInput
2226
+ );
2227
+ return {
2228
+ original: otherAliases,
2229
+ "convert-camel-to-kebab": otherAliases.map(convertCamelCaseToKebabCase)
2230
+ };
2231
+ },
2232
+ getRoutingTargetForInput: (input) => {
2233
+ const routeName = input in activeAliases ? activeAliases[input] : input;
2234
+ return routes[routeName];
2235
+ },
2236
+ getAllEntries() {
2237
+ const hiddenRoutes = docs.hideRoute;
2238
+ return Object.entries(routes).map(([originalRouteName, target]) => {
2239
+ return {
2240
+ name: {
2241
+ original: originalRouteName,
2242
+ "convert-camel-to-kebab": convertCamelCaseToKebabCase(originalRouteName)
2243
+ },
2244
+ target,
2245
+ aliases: aliasesByRoute.get(originalRouteName) ?? [],
2246
+ hidden: hiddenRoutes?.[originalRouteName] ?? false
2247
+ };
2248
+ });
2249
+ }
2250
+ };
2251
+ }
2252
+
2253
+ // src/index.ts
2254
+ async function run(app, inputs, context) {
2255
+ const exitCode = await runApplication(app, inputs, context);
2256
+ context.process.exitCode = exitCode;
2257
+ }
2258
+ // Annotate the CommonJS export names for ESM import in node:
2259
+ 0 && (module.exports = {
2260
+ AliasNotFoundError,
2261
+ ArgumentParseError,
2262
+ ArgumentScannerError,
2263
+ EnumValidationError,
2264
+ ExitCode,
2265
+ FlagNotFoundError,
2266
+ InvalidNegatedFlagSyntaxError,
2267
+ UnexpectedFlagError,
2268
+ UnexpectedPositionalError,
2269
+ UnsatisfiedFlagError,
2270
+ UnsatisfiedPositionalError,
2271
+ booleanParser,
2272
+ buildApplication,
2273
+ buildChoiceParser,
2274
+ buildCommand,
2275
+ buildRouteMap,
2276
+ formatMessageForArgumentScannerError,
2277
+ generateHelpTextForAllCommands,
2278
+ looseBooleanParser,
2279
+ numberParser,
2280
+ proposeCompletions,
2281
+ run,
2282
+ text_en
2283
+ });
2284
+ /* v8 ignore next -- @preserve */
2285
+ /* v8 ignore if -- @preserve */
2286
+ /* v8 ignore else -- @preserve */