@kjanat/dreamcli 2.2.1 → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -1
- package/dist/core/cli/dispatch.d.mts +30 -2
- package/dist/core/cli/dispatch.mjs +1 -1
- package/dist/core/cli/index.mjs +1 -1
- package/dist/core/cli/planner.mjs +1 -1
- package/dist/core/execution/index.mjs +1 -1
- package/dist/core/parse/index.d.mts +31 -1
- package/dist/core/parse/index.mjs +1 -1
- package/dist/version.mjs +1 -1
- package/package.json +5 -2
- package/src/core/cli/dispatch.ts +70 -7
- package/src/core/cli/index.ts +4 -1
- package/src/core/cli/planner.ts +23 -5
- package/src/core/execution/index.ts +1 -9
- package/src/core/parse/index.ts +21 -1
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,20 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [2.3.0] - 2026-06-20
|
|
11
|
+
|
|
12
|
+
### Fixed
|
|
13
|
+
|
|
14
|
+
- **Command dispatch now respects flag value-arity** — a space-separated value-flag value (e.g.
|
|
15
|
+
`--source anthropic`) is no longer mistaken for a command name when it collides with a registered
|
|
16
|
+
command, so the default-command fallback runs as intended
|
|
17
|
+
(https://github.com/kjanat/dreamcli/issues/25). The command-name scan now skips the token a
|
|
18
|
+
space-separated value-flag consumes (mirroring the parser's own value-consumption rules); the
|
|
19
|
+
inline `--source=anthropic` form already worked, and both forms are now consistent.
|
|
20
|
+
- **Root `--version`/`--json` interception now respects the `--` end-of-options separator**
|
|
21
|
+
(https://github.com/kjanat/dreamcli/issues/28). A `--version` or `--json` token after `--` is
|
|
22
|
+
treated as a literal positional instead of triggering version output or JSON mode.
|
|
23
|
+
|
|
10
24
|
## [2.2.1] - 2026-06-10
|
|
11
25
|
|
|
12
26
|
### Added
|
|
@@ -790,7 +804,8 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
|
790
804
|
- MIT License.
|
|
791
805
|
- Markdownlint configuration.
|
|
792
806
|
|
|
793
|
-
[Unreleased]: https://github.com/kjanat/dreamcli/compare/v2.
|
|
807
|
+
[Unreleased]: https://github.com/kjanat/dreamcli/compare/v2.3.0...HEAD
|
|
808
|
+
[2.3.0]: https://github.com/kjanat/dreamcli/compare/v2.2.1...v2.3.0
|
|
794
809
|
[2.2.1]: https://github.com/kjanat/dreamcli/compare/v2.2.0...v2.2.1
|
|
795
810
|
[2.2.0]: https://github.com/kjanat/dreamcli/compare/v2.1.0...v2.2.0
|
|
796
811
|
[2.1.0]: https://github.com/kjanat/dreamcli/compare/v2.0.1...v2.1.0
|
|
@@ -1,6 +1,15 @@
|
|
|
1
|
+
import { FlagSchema } from "../schema/flag.mjs";
|
|
1
2
|
import { CommandSchema, ErasedCommand } from "../schema/command.mjs";
|
|
2
3
|
|
|
3
4
|
//#region src/core/cli/dispatch.d.ts
|
|
5
|
+
/**
|
|
6
|
+
* Flag lookup (name/alias → `[canonicalName, schema]`) used to make the
|
|
7
|
+
* command-name scan aware of value-flag arity. Built from the flags valid at
|
|
8
|
+
* the current dispatch level via {@link buildFlagLookup}.
|
|
9
|
+
*
|
|
10
|
+
* @internal
|
|
11
|
+
*/
|
|
12
|
+
type ValueFlagLookup = ReadonlyMap<string, readonly [name: string, schema: FlagSchema]>;
|
|
4
13
|
/** Successful dispatch — target command found with argv path. */
|
|
5
14
|
interface DispatchMatch {
|
|
6
15
|
/** Discriminant — a command name in argv matched a registered command. */
|
|
@@ -53,11 +62,30 @@ type DispatchResult = DispatchMatch | DispatchNeedsSubcommand | DispatchUnknown;
|
|
|
53
62
|
* @param argv - Remaining argv tokens (command names + flags + args).
|
|
54
63
|
* @param commands - Command map at the current tree level.
|
|
55
64
|
* @param ancestorPath - Schema path from root to current level (exclusive).
|
|
65
|
+
* @param valueFlags - Lookup of flags valid at this level, used so a
|
|
66
|
+
* space-separated value-flag's value (`--region eu`) is not mistaken for a
|
|
67
|
+
* command name. Empty by default (arity-unaware, legacy behaviour).
|
|
56
68
|
* @returns Discriminated dispatch result.
|
|
57
69
|
*
|
|
58
70
|
* @internal
|
|
59
71
|
*/
|
|
60
|
-
declare function dispatch(argv: readonly string[], commands: ReadonlyMap<string, ErasedCommand>, ancestorPath?: readonly CommandSchema[]): DispatchResult;
|
|
72
|
+
declare function dispatch(argv: readonly string[], commands: ReadonlyMap<string, ErasedCommand>, ancestorPath?: readonly CommandSchema[], valueFlags?: ValueFlagLookup): DispatchResult;
|
|
73
|
+
/**
|
|
74
|
+
* Whether a flag token consumes the following argv token as its value.
|
|
75
|
+
*
|
|
76
|
+
* Mirrors the parser's value-consumption rules (`parseLongFlag` /
|
|
77
|
+
* `parseShortFlags`) so the command-name scan skips exactly the tokens the
|
|
78
|
+
* parser would treat as flag values:
|
|
79
|
+
* - `--flag value` → consumes when `--flag` is a known value-flag.
|
|
80
|
+
* - `--flag=value` → self-contained, consumes nothing.
|
|
81
|
+
* - `-abc value` → consumes only when the trailing short flag is a value-flag;
|
|
82
|
+
* an earlier value-flag char takes the rest of the group as an inline value.
|
|
83
|
+
*
|
|
84
|
+
* Unknown flags conservatively consume nothing (the parser reports them later).
|
|
85
|
+
*
|
|
86
|
+
* @internal
|
|
87
|
+
*/
|
|
88
|
+
declare function consumesFollowingToken(token: string, valueFlags: ValueFlagLookup): boolean;
|
|
61
89
|
/**
|
|
62
90
|
* Levenshtein distance between two strings.
|
|
63
91
|
* @internal
|
|
@@ -82,4 +110,4 @@ declare function findClosestCommand(input: string, commands: readonly ErasedComm
|
|
|
82
110
|
*/
|
|
83
111
|
declare function uniqueCommands(commands: ReadonlyMap<string, ErasedCommand>): readonly ErasedCommand[];
|
|
84
112
|
//#endregion
|
|
85
|
-
export { type DispatchMatch, type DispatchNeedsSubcommand, type DispatchResult, type DispatchUnknown, dispatch, findClosestCommand, levenshtein, uniqueCommands };
|
|
113
|
+
export { type DispatchMatch, type DispatchNeedsSubcommand, type DispatchResult, type DispatchUnknown, type ValueFlagLookup, consumesFollowingToken, dispatch, findClosestCommand, levenshtein, uniqueCommands };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function
|
|
1
|
+
import{buildFlagLookup as e,flagExpectsValue as t}from"../parse/index.mjs";function n(t,i,a=[],s=new Map){let c=-1;for(let e=0;e<t.length;e++){let n=t[e];if(n!==void 0){if(n===`--`){e+1<t.length&&(c=e+1);break}if(n.startsWith(`-`)){r(n,s)&&e++;continue}c=e;break}}if(c===-1)return{kind:`unknown`,input:``,candidates:o(i),parentPath:a};let l=t[c];if(l===void 0)return{kind:`unknown`,input:``,candidates:o(i),parentPath:a};let u=i.get(l);if(u===void 0)return{kind:`unknown`,input:l,candidates:o(i),parentPath:a};let d=[...t.slice(0,c),...t.slice(c+1)],f=[...a,u.schema];if(u.subcommands.size>0){let t=n(d,u.subcommands,f,e(u.schema.flags));switch(t.kind){case`match`:return t;case`unknown`:return t.input===``?u.schema.hasAction?{kind:`match`,command:u,commandPath:f,remainingArgv:d}:{kind:`needs-subcommand`,command:u,commandPath:f}:u.schema.hasAction?{kind:`match`,command:u,commandPath:f,remainingArgv:d}:t;case`needs-subcommand`:return t;default:return t}}return{kind:`match`,command:u,commandPath:f,remainingArgv:d}}function r(e,n){if(e.startsWith(`--`)){if(e.includes(`=`))return!1;let r=n.get(e.slice(2));return r!==void 0&&t(r[1])}let r=e.slice(1);for(let e=0;e<r.length;e++){let i=n.get(r.charAt(e));if(i===void 0)return!1;if(t(i[1]))return e===r.length-1}return!1}function i(e,t){let n=e.length,r=t.length,i=r+1,a=new Uint16Array(i),o=new Uint16Array(i);for(let e=0;e<=r;e++)a[e]=e;for(let i=1;i<=n;i++){o[0]=i;for(let n=1;n<=r;n++){let r=e.charAt(i-1)===t.charAt(n-1)?0:1,s=a[n]??0,c=o[n-1]??0,l=a[n-1]??0;o[n]=Math.min(s+1,c+1,l+r)}[a,o]=[o,a]}return a[r]??Math.max(n,r)}function a(e,t){let n,r=4;for(let a of t){let t=i(e,a.schema.name);t<r&&(r=t,n=a.schema.name);for(let t of a.schema.aliases){let o=i(e,t);o<r&&(r=o,n=a.schema.name)}}return r<=3?n:void 0}function o(e){let t=new Set,n=[];for(let r of e.values())t.has(r)||(t.add(r),n.push(r));return n}export{n as dispatch,a as findClosestCommand};
|
package/dist/core/cli/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{CLIError as e}from"../errors/index.mjs";import{SHELLS as t,generateCompletion as n}from"../completion/index.mjs";import{formatHelp as r}from"../help/index.mjs";import{buildRunResult as
|
|
1
|
+
import{CLIError as e}from"../errors/index.mjs";import{SHELLS as t,generateCompletion as n}from"../completion/index.mjs";import{formatHelp as r}from"../help/index.mjs";import{includesBeforeSeparator as i}from"../parse/index.mjs";import{buildRunResult as a,executeCommand as o}from"../execution/index.mjs";import{createCaptureOutput as s,createOutput as c}from"../output/index.mjs";import{arg as l}from"../schema/arg.mjs";import{command as u}from"../schema/command.mjs";import{runCommand as d}from"../testkit/index.mjs";import{createAdapter as f}from"../../runtime/auto.mjs";import{deriveHelpLinks as p}from"./help-links.mjs";import{planInvocation as m}from"./planner.mjs";import"./plugin.mjs";import{formatRootHelp as h}from"./root-help.mjs";import{prepareRuntimePreflight as g}from"./runtime-preflight.mjs";function _(e){return[e.name,...e.aliases]}function v(t,n,r,i){let a=n.get(r);if(a!==void 0)throw new e(`Duplicate command route '${r}' under '${t}' (${a} and ${i})`,{code:`DUPLICATE_COMMAND`,suggest:`Ensure sibling command names and aliases are unique`});n.set(r,i)}function y(t,n){let r=new Map;for(let e of t)for(let t of _(e.schema))v(`root`,r,t,e.schema.name);for(let t of _(n)){let i=r.get(t);if(i!==void 0)throw new e(`Command route '${t}' is already registered by '${i}'`,{code:`DUPLICATE_COMMAND`,suggest:i===n.name?`Ensure command '${n.name}' does not reuse route '${t}'`:`Rename '${n.name}' or remove route '${t}' from '${i}'`});r.set(t,n.name)}}function b(e){let t=new Map,n=new Map;for(let r of e._subcommands){let i=_(r.schema);for(let t of i)v(e.schema.name,n,t,r.schema.name);let a=b(r);for(let e of i)t.set(e,a)}return{schema:e.schema,subcommands:t,_command:e,_execute(t,n){return d(e,t,n)}}}function x(e,t,n){return{help:t,...n===void 0?{}:{meta:n},...e?.plugins===void 0?{}:{plugins:e.plugins},...e?.env===void 0?{}:{env:e.env},...e?.config===void 0?{}:{config:e.config},...e?.stdinData===void 0?{}:{stdinData:e.stdinData},...e?.prompter===void 0?{}:{prompter:e.prompter},...e?.answers===void 0?{}:{answers:e.answers},...e?.verbosity===void 0?{}:{verbosity:e.verbosity},...e?.jsonMode===void 0?{}:{jsonMode:e.jsonMode},...e?.isTTY===void 0?{}:{isTTY:e.isTTY},...e?.out===void 0?{}:{out:e.out},...e?.captured===void 0?{}:{captured:e.captured}}}var S=class d{schema;constructor(e){this.schema=e}version(e){return new d({...this.schema,version:e})}description(e){return new d({...this.schema,description:e})}links(e){return new d({...this.schema,helpLinks:{name:D(e?.name),version:D(e?.version)}})}config(e,t){return new d({...this.schema,configSettings:{appName:e,loaders:t}})}configLoader(t){if(this.schema.configSettings===void 0)throw new e(`.configLoader() requires .config() to be called first`,{code:`INVALID_BUILDER_STATE`,suggest:`Call .config(appName) before .configLoader()`});let n=this.schema.configSettings.loaders??[];return new d({...this.schema,configSettings:{...this.schema.configSettings,loaders:[...n,t]}})}packageJson(e){return A(e)?new d({...this.schema,...this.schema.version===void 0&&e.version!==void 0?{version:e.version}:{},...this.schema.description===void 0&&e.description!==void 0?{description:e.description}:{},packageJsonSettings:{inferName:!1,from:void 0,data:e}}):new d({...this.schema,packageJsonSettings:{inferName:e?.inferName??!1,from:k(e?.from),data:void 0}})}command(e){return y(this.schema.commands,e.schema),new d({...this.schema,commands:[...this.schema.commands,b(e)]})}default(t){if(this.schema.defaultCommand!==void 0)throw new e(`Only one default command is allowed`,{code:`DUPLICATE_DEFAULT`,suggest:`Call .default() only once when building the CLI`});y(this.schema.commands,t.schema);let n=b(t);return new d({...this.schema,commands:[...this.schema.commands,n],defaultCommand:n})}plugin(e){return new d({...this.schema,plugins:[...this.schema.plugins,e]})}completions(r){if(this.schema.hasBuiltInCompletions)throw new e(`.completions() has already been called`,{code:`DUPLICATE_COMMAND`,suggest:`Call .completions() only once when building the CLI`});let i=this.schema,a=r,o=new Map;for(let e of t)o.set(e,e);o.set(`pwsh`,`powershell`);let s=u(`completions`).alias(`completion`).description(`Generate shell completion script`).arg(`shell`,l.custom(e=>{let n=e.split(/[\\/]/),r=(n[n.length-1]??e).replace(/\.(?:exe|cmd|bat)$/i,``),i=o.get(r);if(i===void 0)throw Error(`Unknown shell '${r}'. Valid shells: ${t.join(`, `)}`);return i}).env(`SHELL`).describe(`Target shell (${t.join(`, `)})`)).action(({args:e,meta:t,out:r})=>{let o=n(t.bin===i.name?i:{...i,name:t.bin},e.shell,a);r.jsonMode?r.json({shell:e.shell,script:o}):r.log(o)});return new d({...this.command(s).schema,hasBuiltInCompletions:!0})}async execute(e,t){let n=i(e,`--json`)||t?.jsonMode===!0,c={...t?.verbosity===void 0?{}:{verbosity:t.verbosity},...n?{jsonMode:n}:{},...t?.isTTY===void 0?{}:{isTTY:t.isTTY}},l,u;t?.out===void 0?[l,u]=s(Object.keys(c).length>0?c:void 0):(l=t.out,u=t.captured??{stdout:[],stderr:[],activity:[]});let d={...t?.help,binName:t?.help?.binName??this.schema.name,hyperlinks:t?.help?.hyperlinks??l.isTTY},f={...t,plugins:this.schema.plugins,...n?{jsonMode:n}:{}},p={jsonMode:n,isTTY:l.isTTY,verbosity:t?.verbosity??`normal`},g=m({schema:this.schema,argv:e,help:d,output:p});switch(g.kind){case`root-version`:return l.log(g.version),a({exitCode:0,error:void 0},u);case`root-help`:{let e=h(O(this.schema),g.help);return l.log(e),a({exitCode:0,error:void 0},u)}case`dispatch-error`:return n?l.json({error:g.error.toJSON()}):(l.error(g.error.message),g.error.suggest!==void 0&&g.error.code!==`NO_ACTION`&&l.error(`Suggestion: ${g.error.suggest}`)),a({exitCode:g.error.exitCode,error:g.error},u);case`needs-subcommand`:{let e=r(g.command.schema,g.help);return l.log(e),a({exitCode:0,error:void 0},u)}case`match`:{let e=x(f,g.plan.help??d,g.plan.meta);return g.plan.command._command===void 0?g.plan.command._execute(g.plan.argv,{...e,mergedSchema:g.plan.mergedSchema}):a(await o({command:g.plan.command._command,argv:g.plan.argv,out:l,schema:g.plan.mergedSchema,meta:g.plan.meta,options:e}),u)}}}async run(e){let t=e?.adapter??f(),n=this.schema.inheritName?E(t.argv):void 0,r=await g({schema:this.schema,adapter:t,options:e,inheritedName:n});if(r.kind===`config-error`)return r.jsonMode?t.stdout(`${JSON.stringify({error:r.error.toJSON()})}\n`):(t.stderr(`Error: ${r.error.message}\n`),r.error.suggest!==void 0&&t.stderr(`Suggestion: ${r.error.suggest}\n`)),t.exit(r.error.exitCode);let i=r.schema===this.schema?this:new d(r.schema),a={...e,...r.inputs,out:c({stdout:t.stdout,stderr:t.stderr,jsonMode:r.inputs.jsonMode,isTTY:r.inputs.isTTY,...r.inputs.verbosity===`normal`?{}:{verbosity:r.inputs.verbosity}})},o=await i.execute(r.filteredArgv,a);for(let e of o.stdout)t.stdout(e);for(let e of o.stderr)t.stderr(e);return t.exit(o.exitCode)}};const C=new Set([`bun`,`deno`,`node`,`tsx`]);function w(e){let t=e.replace(/[\\/]+$/g,``);if(t.length===0)return;let n=Math.max(t.lastIndexOf(`/`),t.lastIndexOf(`\\`)),r=n>=0?t.slice(n+1):t;return r.length>0?r:void 0}function T(e){let t=e.toLowerCase().replace(/\.exe$/i,``);return C.has(t)}function E(e){let t=e[0],n=e[1],r=t===void 0?void 0:w(t);if(r!==void 0&&T(r)){if(r===`bun`&&n===`run`){let t=e[2];return t===void 0||t.startsWith(`-`)?void 0:w(t)}return r===`deno`&&n===`run`||n===void 0||n.startsWith(`-`)?void 0:w(n)}return t===void 0?void 0:w(t)}function D(e){if(e!==void 0)return e instanceof URL?e.href:e}function O(e){return e.helpLinks===void 0?e:{...e,helpLinks:p(e.helpLinks,e.packageJsonSettings?.data,e.version)}}function k(e){if(e===void 0)return;if(e instanceof URL){if(e.protocol!==`file:`)return e.href}else if(!e.startsWith(`file:`))return e;let t=decodeURIComponent(new URL(e).pathname);return/^\/[A-Za-z]:/.test(t)?t.slice(1).replace(/\//g,`\\`):t}function A(e){return typeof e!=`object`||!e||Array.isArray(e)?!1:`name`in e||`version`in e||`description`in e||`bin`in e||`homepage`in e||`repository`in e}function j(e){return new S({name:typeof e==`string`?e:e.name??`cli`,inheritName:typeof e==`string`?!1:e.inherit??!1,version:void 0,description:void 0,commands:[],defaultCommand:void 0,configSettings:void 0,packageJsonSettings:void 0,helpLinks:void 0,hasBuiltInCompletions:!1,plugins:[]})}export{S as CLIBuilder,j as cli};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{collectPropagatedFlags as e}from"./propagate.mjs";import{CLIError as t,ParseError as n}from"../errors/index.mjs";import{
|
|
1
|
+
import{collectPropagatedFlags as e}from"./propagate.mjs";import{CLIError as t,ParseError as n}from"../errors/index.mjs";import{buildFlagLookup as r,includesBeforeSeparator as i}from"../parse/index.mjs";import{dispatch as a,findClosestCommand as o}from"./dispatch.mjs";function s(e,t,n){return{name:e.name,bin:t.binName??e.name,version:e.version,command:n}}function c(e){let n=new Map,r=(e,r)=>{let i=n.get(e);if(i!==void 0)throw new t(`Duplicate root command route '${e}' (${i.schema.name} and ${r.schema.name})`,{code:`DUPLICATE_COMMAND`,suggest:`Ensure root command names and aliases are unique`});n.set(e,r)};for(let t of e){r(t.schema.name,t);for(let e of t.schema.aliases)r(e,t)}return n}function l(t,n){let r=e(n);return Object.keys(r).length===0?t.schema:{...t.schema,flags:{...r,...t.schema.flags}}}function u(e){return{command:e.command,mergedSchema:l(e.command,e.commandPath),argv:e.argv,meta:e.meta,plugins:e.plugins,output:e.output,help:e.help}}function d(e,t,n,r,i,a){return{kind:`match`,plan:u({command:t,commandPath:n,argv:r,meta:s(e,i,t.schema.name),plugins:e.plugins,output:a,help:i})}}function f(e){let s=e.argv.indexOf(`--`),l=s===-1?e.argv:e.argv.slice(0,s),u=s===-1?[]:e.argv.slice(s),p=l.includes(`--json`)?l.filter(e=>e!==`--json`):l,m=s===-1?p:[...p,...u];if(e.schema.version!==void 0&&(i(e.argv,`--version`)||i(e.argv,`-V`)))return{kind:`root-version`,version:e.schema.version};let h=m[0];if(h===`--help`||h===`-h`)return{kind:`root-help`,help:e.help};if(h===`help`&&!e.schema.commands.some(e=>e.schema.name===`help`||e.schema.aliases.includes(`help`))){let t=m.slice(1);return t.length===0?{kind:`root-help`,help:e.help}:f({...e,argv:[...t,`--help`]})}if(h===void 0&&e.schema.defaultCommand===void 0)return{kind:`root-help`,help:e.help};if(e.schema.commands.length===0)return{kind:`dispatch-error`,error:new t(`No commands registered`,{code:`NO_ACTION`,suggest:`Add commands via .command() before calling .run()`})};let g=e.schema.defaultCommand,_=g===void 0?void 0:r(g.schema.flags),v=a(m,c(e.schema.commands),[],_);switch(v.kind){case`unknown`:{if(g!==void 0&&v.parentPath.length===0&&(v.input===``?void 0:o(v.input,v.candidates))===void 0)return d(e.schema,g,[g.schema],m,e.help,e.output);if(v.input===``){let t=m.find(e=>e.startsWith(`-`));return t===void 0?{kind:`root-help`,help:e.help}:{kind:`dispatch-error`,error:new n(`Unknown flag ${t}`,{code:`UNKNOWN_FLAG`,suggest:`Run '${e.schema.name} --help' for available commands`})}}let t=o(v.input,v.candidates),r=v.parentPath.length>0?`${e.schema.name} ${v.parentPath.map(e=>e.name).join(` `)}`:e.schema.name;return{kind:`dispatch-error`,error:new n(`Unknown command: ${v.input}`,{code:`UNKNOWN_COMMAND`,suggest:t===void 0?`Run '${r} --help' for available commands`:`Did you mean '${t}'?`})}}case`needs-subcommand`:{let t=v.commandPath.slice(0,-1).map(e=>e.name);return{kind:`needs-subcommand`,command:v.command,commandPath:v.commandPath,help:{...e.help,binName:[e.schema.name,...t].join(` `)}}}case`match`:return d(e.schema,v.command,v.commandPath,v.remainingArgv,e.help,e.output)}}export{f as planInvocation};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{CLIError as e}from"../errors/index.mjs";import{formatHelp as t}from"../help/index.mjs";import{parse as
|
|
1
|
+
import{CLIError as e}from"../errors/index.mjs";import{formatHelp as t}from"../help/index.mjs";import{includesBeforeSeparator as n,parse as r}from"../parse/index.mjs";import{createTestPrompter as i}from"../prompt/index.mjs";import{resolve as a}from"../resolve/index.mjs";async function o(o){let{argv:u,command:f,meta:p,options:m,out:h,schema:g}=o;try{if(n(u,`--help`)||n(u,`-h`)){let e=t(g,m?.help);return h.log(e),{exitCode:0,error:void 0}}let o=f.handler;if(o===void 0){let t=new e(`Command '${f.schema.name}' has no action handler`,{code:`NO_ACTION`,suggest:`Add an .action() handler to the '${f.schema.name}' command`});return h.error(t.message),{exitCode:1,error:t}}await s(m?.plugins,{argv:u,command:g,meta:p,out:h});let _=r(g,u),v=m?.prompter??(m?.answers===void 0?void 0:i(m.answers)),y=await a(g,_,{...m?.stdinData===void 0?{}:{stdinData:m.stdinData},...m?.env===void 0?{}:{env:m.env},...m?.config===void 0?{}:{config:m.config},...v===void 0?{}:{prompter:v}}),b={args:y.args,flags:y.flags,deprecations:y.deprecations,command:g,meta:p,out:h};await c(m?.plugins,`afterResolve`,b);for(let e of y.deprecations)h.warn(d(e));return await c(m?.plugins,`beforeAction`,b),await l(f,o,y.flags,y.args,h,p),await c(m?.plugins,`afterAction`,b),{exitCode:0,error:void 0}}catch(t){if(t instanceof e)return m?.jsonMode===!0?h.json({error:t.toJSON()}):(h.error(t.message),t.suggest!==void 0&&h.error(`Suggestion: ${t.suggest}`)),{exitCode:t.exitCode,error:t};let n=new e(`Unexpected error: ${t instanceof Error?t.message:String(t)}`,{code:`UNEXPECTED_ERROR`,cause:t});return m?.jsonMode===!0?h.json({error:n.toJSON()}):h.error(n.message),{exitCode:1,error:n}}finally{h.stopActive()}}async function s(e,t){if(e!==void 0)for(let n of e){let e=n.hooks.beforeParse;e!==void 0&&await e(t)}}async function c(e,t,n){if(e!==void 0)for(let r of e){let e=r.hooks[t];e!==void 0&&await e(n)}}async function l(t,n,r,i,a,o){let s=t._executionSteps,c=async e=>{await n({flags:r,args:i,ctx:e,out:a,meta:o})};for(let t=s.length-1;t>=0;t--){let n=s[t];if(n===void 0)continue;let l=c;switch(n.kind){case`derive`:c=async t=>{let s=await n.handler({args:i,flags:r,ctx:t,out:a,meta:o});if(s===void 0){await l(t);return}if(typeof s!=`object`||!s||Array.isArray(s))throw new e(`derive() must return an object or undefined`,{code:`INVALID_BUILDER_STATE`,suggest:`Return an object to add context, or return nothing for validation-only derive handlers`});await l({...t,...s})};break;case`middleware`:c=async e=>{await n.handler({args:i,flags:r,ctx:e,out:a,meta:o,next:async t=>{await l({...e,...t})}})};break}}await c({})}function u(e,t){return{exitCode:e.exitCode,stdout:t.stdout,stderr:t.stderr,activity:t.activity,error:e.error}}function d(e){let t=e.kind===`flag`?`flag --${e.name}`:`argument <${e.name}>`;return typeof e.message==`string`?`Warning: ${t} is deprecated: ${e.message}`:`Warning: ${t} is deprecated`}export{u as buildRunResult,o as executeCommand};
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { FlagSchema } from "../schema/flag.mjs";
|
|
1
2
|
import { CommandSchema } from "../schema/command.mjs";
|
|
2
3
|
|
|
3
4
|
//#region src/core/parse/index.d.ts
|
|
@@ -44,6 +45,19 @@ type Token = {
|
|
|
44
45
|
* ```
|
|
45
46
|
*/
|
|
46
47
|
declare function tokenize(argv: readonly string[]): readonly Token[];
|
|
48
|
+
/**
|
|
49
|
+
* Whether `token` appears in argv before the `--` end-of-options separator.
|
|
50
|
+
*
|
|
51
|
+
* Everything at or after the first `--` is a literal positional, so root-level
|
|
52
|
+
* flag interception (`--help` / `--version` / `--json`) must use this instead of
|
|
53
|
+
* a naive `Array.includes()` — otherwise a post-separator literal (`-- --json`)
|
|
54
|
+
* is wrongly treated as the flag.
|
|
55
|
+
*
|
|
56
|
+
* @param argv - Raw argument strings.
|
|
57
|
+
* @param token - Exact flag token to look for (e.g. `--version`).
|
|
58
|
+
* @returns `true` if `token` occurs before any `--` separator.
|
|
59
|
+
*/
|
|
60
|
+
declare function includesBeforeSeparator(argv: readonly string[], token: string): boolean;
|
|
47
61
|
/**
|
|
48
62
|
* Raw parsed values before resolution (defaults, env, config, etc.).
|
|
49
63
|
*
|
|
@@ -56,6 +70,22 @@ interface ParseResult {
|
|
|
56
70
|
/** Positional arg values keyed by arg name. */
|
|
57
71
|
readonly args: Readonly<Record<string, unknown>>;
|
|
58
72
|
}
|
|
73
|
+
/**
|
|
74
|
+
* Build a map from flag name/alias → [canonicalName, {@link FlagSchema}].
|
|
75
|
+
*
|
|
76
|
+
* Supports both long names and single-char aliases for short flag expansion.
|
|
77
|
+
*
|
|
78
|
+
* @param flags - Flag schemas keyed by canonical name
|
|
79
|
+
* @returns Lookup map covering all names and aliases
|
|
80
|
+
*/
|
|
81
|
+
declare function buildFlagLookup(flags: Readonly<Record<string, FlagSchema>>): ReadonlyMap<string, readonly [name: string, schema: FlagSchema]>;
|
|
82
|
+
/**
|
|
83
|
+
* Whether a flag kind expects a value argument (vs. being a bare boolean).
|
|
84
|
+
*
|
|
85
|
+
* @param schema - Flag schema to check
|
|
86
|
+
* @returns `true` if the flag expects a value token after it
|
|
87
|
+
*/
|
|
88
|
+
declare function flagExpectsValue(schema: FlagSchema): boolean;
|
|
59
89
|
/**
|
|
60
90
|
* Parse tokenized argv against a command schema.
|
|
61
91
|
*
|
|
@@ -76,4 +106,4 @@ interface ParseResult {
|
|
|
76
106
|
*/
|
|
77
107
|
declare function parse(schema: CommandSchema, argv: readonly string[]): ParseResult;
|
|
78
108
|
//#endregion
|
|
79
|
-
export { type ParseResult, type Token, parse, tokenize };
|
|
109
|
+
export { type ParseResult, type Token, buildFlagLookup, flagExpectsValue, includesBeforeSeparator, parse, tokenize };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getFlagAliasNames as e}from"../schema/flag.mjs";import{ParseError as t}from"../errors/index.mjs";function n(e){let t=[],n=!1;for(let r of e){if(n){t.push({kind:`positional`,value:r});continue}if(r===`--`){t.push({kind:`separator`}),n=!0;continue}if(r.startsWith(`--`)){let e=r.indexOf(`=`);e===-1?t.push({kind:`long-flag`,name:r.slice(2),value:void 0}):t.push({kind:`long-flag`,name:r.slice(2,e),value:r.slice(e+1)});continue}if(r.startsWith(`-`)&&r.length>1){t.push({kind:`short-flags`,chars:r.slice(1)});continue}t.push({kind:`positional`,value:r})}return t}function r(t){let n=new Map;for(let[r,i]of Object.entries(t)){n.set(r,[r,i]);for(let t of e(i,{includeHidden:!0}))n.set(t,[r,i])}return n}function
|
|
1
|
+
import{getFlagAliasNames as e}from"../schema/flag.mjs";import{ParseError as t}from"../errors/index.mjs";function n(e){let t=[],n=!1;for(let r of e){if(n){t.push({kind:`positional`,value:r});continue}if(r===`--`){t.push({kind:`separator`}),n=!0;continue}if(r.startsWith(`--`)){let e=r.indexOf(`=`);e===-1?t.push({kind:`long-flag`,name:r.slice(2),value:void 0}):t.push({kind:`long-flag`,name:r.slice(2,e),value:r.slice(e+1)});continue}if(r.startsWith(`-`)&&r.length>1){t.push({kind:`short-flags`,chars:r.slice(1)});continue}t.push({kind:`positional`,value:r})}return t}function r(e,t){for(let n of e){if(n===`--`)return!1;if(n===t)return!0}return!1}function i(t){let n=new Map;for(let[r,i]of Object.entries(t)){n.set(r,[r,i]);for(let t of e(i,{includeHidden:!0}))n.set(t,[r,i])}return n}function a(e){return e.kind!==`boolean`}function o(e,n,r,i=`--${e}`){switch(r.kind){case`string`:return n;case`number`:{let r=Number(n);if(Number.isNaN(r))throw new t(`Invalid number value '${n}' for flag ${i}`,{code:`INVALID_VALUE`,details:{flag:e,input:i,value:n,expected:`number`}});return r}case`boolean`:if(n===`true`||n===`1`)return!0;if(n===`false`||n===`0`)return!1;throw new t(`Invalid boolean value '${n}' for flag ${i}. Use true/false or 1/0`,{code:`INVALID_VALUE`,details:{flag:e,input:i,value:n,expected:`boolean`}});case`enum`:{let a=r.enumValues;if(a===void 0)throw new t(`Enum flag --${e} is misconfigured: no allowed values declared`,{code:`INVALID_SCHEMA`,details:{flag:e,kind:`enum`,missing:`enumValues`}});if(!a.includes(n))throw new t(`Invalid value '${n}' for flag ${i}. Allowed: ${a.join(`, `)}`,{code:`INVALID_VALUE`,details:{flag:e,input:i,value:n,allowed:a}});return n}case`array`:return r.elementSchema?o(e,n,r.elementSchema):n;case`custom`:if(!r.parseFn)return n;try{return r.parseFn(n)}catch(r){throw r instanceof t?r:new t(`Failed to parse flag ${i}: ${r instanceof Error?r.message:String(r)}`,{code:`INVALID_VALUE`,details:{flag:e,input:i,value:n},cause:r})}}}function s(e,n,r){switch(r.kind){case`string`:return n;case`number`:{let r=Number(n);if(Number.isNaN(r))throw new t(`Invalid number value '${n}' for argument <${e}>`,{code:`INVALID_VALUE`,details:{arg:e,value:n,expected:`number`}});return r}case`enum`:{let i=r.enumValues;if(i===void 0)throw new t(`Enum argument <${e}> is misconfigured: no allowed values declared`,{code:`INVALID_SCHEMA`,details:{arg:e,kind:`enum`,missing:`enumValues`}});if(!i.includes(n))throw new t(`Invalid value '${n}' for argument <${e}>. Allowed: ${i.join(`, `)}`,{code:`INVALID_VALUE`,details:{arg:e,value:n,allowed:i}});return n}case`custom`:if(!r.parseFn)return n;try{return r.parseFn(n)}catch(r){throw r instanceof t?r:new t(`Failed to parse argument <${e}>: ${r instanceof Error?r.message:String(r)}`,{code:`INVALID_VALUE`,details:{arg:e,value:n},cause:r})}}}function c(e,t){let r=n(t),a=i(e.flags),o={},s=[],c=0;for(;c<r.length;){let e=r[c];if(e===void 0)break;if(e.kind===`separator`){c++;continue}if(e.kind===`positional`){s.push(e.value),c++;continue}if(e.kind===`long-flag`){c=l(e,r,c,a,o);continue}c=u(e,r,c,a,o)}return{flags:o,args:f(e.args,s)}}function l(e,n,r,i,s){let c=i.get(e.name);if(!c){let n=p(e.name,i);throw new t(`Unknown flag --${e.name}${n?`. Did you mean --${n}?`:``}`,{code:`UNKNOWN_FLAG`,details:{flag:e.name,...n?{suggestion:n}:{}},...n?{suggest:`--${n}`}:{}})}let[l,u]=c;if(!a(u))return e.value===void 0?s[l]=!0:s[l]=o(l,e.value,u,`--${e.name}`),r+1;if(e.value!==void 0)return d(s,l,u,e.value),r+1;let f=n[r+1];if(!f||f.kind!==`positional`)throw new t(`Flag --${e.name} requires a value`,{code:`MISSING_VALUE`,details:{flag:l,input:e.name,kind:u.kind}});return d(s,l,u,f.value,`--${e.name}`),r+2}function u(e,n,r,i,o){let{chars:s}=e,c=r+1;for(let e=0;e<s.length;e++){let r=s.charAt(e),l=i.get(r);if(!l)throw new t(`Unknown flag -${r}`,{code:`UNKNOWN_FLAG`,details:{flag:r}});let[u,f]=l;if(!a(f)){o[u]=!0;continue}if(e<s.length-1){d(o,u,f,s.slice(e+1),`-${r}`);break}let p=n[c];if(!p||p.kind!==`positional`)throw new t(`Flag -${r} requires a value`,{code:`MISSING_VALUE`,details:{flag:u,input:r,kind:f.kind}});d(o,u,f,p.value,`-${r}`),c++}return c}function d(e,t,n,r,i=`--${t}`){let a=o(t,r,n,i);if(n.kind===`array`){let n=e[t];Array.isArray(n)?n.push(a):e[t]=[a]}else e[t]=a}function f(e,n){let r={},i=0;for(let t of e){if(t.schema.variadic){let e=n.slice(i);r[t.name]=e.map(e=>s(t.name,e,t.schema)),i=n.length;break}let e=n[i];e!==void 0&&(r[t.name]=s(t.name,e,t.schema),i++)}if(i<n.length){let r=n.slice(i);throw new t(`Unexpected positional argument${r.length>1?`s`:``}: ${r.join(`, `)}`,{code:`UNEXPECTED_POSITIONAL`,details:{excess:r,expected:e.length}})}return r}function p(e,t){let n,r=1/0,i=Math.max(2,Math.floor(e.length/2));for(let a of t.keys()){let o=t.get(a);if(o===void 0)continue;let[s,c]=o,l=c.aliases.find(e=>e.name===a);if(a.length<2||a!==s&&l?.hidden)continue;let u=m(e,a);u<r&&u<=i&&(r=u,n=a)}return n}function m(e,t){if(e===t)return 0;if(e.length===0)return t.length;if(t.length===0)return e.length;let n=e.length<=t.length?e:t,r=e.length<=t.length?t:e,i=n.length,a=r.length,o=Array.from({length:i+1},(e,t)=>t);for(let e=1;e<=a;e++){let t=o[0]??0;o[0]=e;for(let a=1;a<=i;a++){let i=n.charAt(a-1)===r.charAt(e-1)?0:1,s=Math.min((o[a]??0)+1,(o[a-1]??0)+1,t+i);t=o[a]??0,o[a]=s}}return o[i]??0}export{i as buildFlagLookup,a as flagExpectsValue,r as includesBeforeSeparator,c as parse,n as tokenize};
|
package/dist/version.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const e=`2.
|
|
1
|
+
const e=`2.3.0`,t=`23cad0f`;export{t as DREAMCLI_REVISION,e as DREAMCLI_VERSION};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kjanat/dreamcli",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.3.0",
|
|
4
4
|
"description": "Schema-first, fully typed TypeScript CLI framework",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cli",
|
|
@@ -82,6 +82,8 @@
|
|
|
82
82
|
"docs:dev": "bunx --bun vitepress@next dev docs",
|
|
83
83
|
"docs:preview": "bunx --bun vitepress@next preview docs",
|
|
84
84
|
"fmt": "dprint fmt",
|
|
85
|
+
"fmt:autofix": "dprint fmt --allow-no-files --excludes .github",
|
|
86
|
+
"fmt:update": "dprint config update --yes --recursive",
|
|
85
87
|
"format": "dprint fmt",
|
|
86
88
|
"format:check": "dprint check",
|
|
87
89
|
"gh-project": "bun scripts/gh-project.ts",
|
|
@@ -92,6 +94,7 @@
|
|
|
92
94
|
"gh-project:sync": "bun gh-project sync",
|
|
93
95
|
"knip": "knip",
|
|
94
96
|
"lint": "biome lint",
|
|
97
|
+
"lint:autofix": "biome check --skip-parse-errors --no-errors-on-unmatched --changed --write",
|
|
95
98
|
"lint:fix": "biome lint --fix",
|
|
96
99
|
"meta-descriptions": "bun --bun scripts/build-meta-descriptions.ts",
|
|
97
100
|
"meta-descriptions:check": "bun --bun scripts/build-meta-descriptions.ts --check",
|
|
@@ -130,7 +133,7 @@
|
|
|
130
133
|
"wrangler": "^4.80.0",
|
|
131
134
|
"yaml": "^2.8.3"
|
|
132
135
|
},
|
|
133
|
-
"packageManager": "bun@1.3.
|
|
136
|
+
"packageManager": "bun@1.3.14",
|
|
134
137
|
"engines": {
|
|
135
138
|
"bun": ">=1.3",
|
|
136
139
|
"deno": ">=2.6.0",
|
package/src/core/cli/dispatch.ts
CHANGED
|
@@ -10,7 +10,18 @@
|
|
|
10
10
|
* @internal
|
|
11
11
|
*/
|
|
12
12
|
|
|
13
|
+
import { buildFlagLookup, flagExpectsValue } from '#internals/core/parse/index.ts';
|
|
13
14
|
import type { CommandSchema, ErasedCommand } from '#internals/core/schema/command.ts';
|
|
15
|
+
import type { FlagSchema } from '#internals/core/schema/flag.ts';
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Flag lookup (name/alias → `[canonicalName, schema]`) used to make the
|
|
19
|
+
* command-name scan aware of value-flag arity. Built from the flags valid at
|
|
20
|
+
* the current dispatch level via {@link buildFlagLookup}.
|
|
21
|
+
*
|
|
22
|
+
* @internal
|
|
23
|
+
*/
|
|
24
|
+
type ValueFlagLookup = ReadonlyMap<string, readonly [name: string, schema: FlagSchema]>;
|
|
14
25
|
|
|
15
26
|
// --- Dispatch result types (discriminated union)
|
|
16
27
|
|
|
@@ -72,6 +83,9 @@ type DispatchResult = DispatchMatch | DispatchNeedsSubcommand | DispatchUnknown;
|
|
|
72
83
|
* @param argv - Remaining argv tokens (command names + flags + args).
|
|
73
84
|
* @param commands - Command map at the current tree level.
|
|
74
85
|
* @param ancestorPath - Schema path from root to current level (exclusive).
|
|
86
|
+
* @param valueFlags - Lookup of flags valid at this level, used so a
|
|
87
|
+
* space-separated value-flag's value (`--region eu`) is not mistaken for a
|
|
88
|
+
* command name. Empty by default (arity-unaware, legacy behaviour).
|
|
75
89
|
* @returns Discriminated dispatch result.
|
|
76
90
|
*
|
|
77
91
|
* @internal
|
|
@@ -80,22 +94,29 @@ function dispatch(
|
|
|
80
94
|
argv: readonly string[],
|
|
81
95
|
commands: ReadonlyMap<string, ErasedCommand>,
|
|
82
96
|
ancestorPath: readonly CommandSchema[] = [],
|
|
97
|
+
valueFlags: ValueFlagLookup = new Map(),
|
|
83
98
|
): DispatchResult {
|
|
84
99
|
// Find first non-flag token (potential command name).
|
|
85
100
|
// Flags may appear before the command name (e.g. `--verbose db migrate`).
|
|
86
101
|
// `--` terminates flag scanning — the next token is treated as a command name.
|
|
102
|
+
// Value-flags in space-separated form (`--region eu`, `-r eu`) consume the
|
|
103
|
+
// following token as their value, so it must be skipped rather than matched
|
|
104
|
+
// as a command name (see #25).
|
|
87
105
|
let cmdIdx = -1;
|
|
88
106
|
for (let i = 0; i < argv.length; i++) {
|
|
89
107
|
const token = argv[i];
|
|
108
|
+
if (token === undefined) continue;
|
|
90
109
|
if (token === '--') {
|
|
91
110
|
// End-of-flags marker: next token (if any) is the command name.
|
|
92
111
|
if (i + 1 < argv.length) cmdIdx = i + 1;
|
|
93
112
|
break;
|
|
94
113
|
}
|
|
95
|
-
if (token
|
|
96
|
-
|
|
97
|
-
|
|
114
|
+
if (token.startsWith('-')) {
|
|
115
|
+
if (consumesFollowingToken(token, valueFlags)) i++; // skip the flag's value
|
|
116
|
+
continue;
|
|
98
117
|
}
|
|
118
|
+
cmdIdx = i;
|
|
119
|
+
break;
|
|
99
120
|
}
|
|
100
121
|
|
|
101
122
|
if (cmdIdx === -1) {
|
|
@@ -132,9 +153,15 @@ function dispatch(
|
|
|
132
153
|
const remaining = [...argv.slice(0, cmdIdx), ...argv.slice(cmdIdx + 1)];
|
|
133
154
|
const currentPath = [...ancestorPath, matched.schema];
|
|
134
155
|
|
|
135
|
-
// If command has subcommands, try to descend.
|
|
156
|
+
// If command has subcommands, try to descend. The matched command's own
|
|
157
|
+
// flags govern arity at the child level (e.g. `db --config x migrate`).
|
|
136
158
|
if (matched.subcommands.size > 0) {
|
|
137
|
-
const subResult = dispatch(
|
|
159
|
+
const subResult = dispatch(
|
|
160
|
+
remaining,
|
|
161
|
+
matched.subcommands,
|
|
162
|
+
currentPath,
|
|
163
|
+
buildFlagLookup(matched.schema.flags),
|
|
164
|
+
);
|
|
138
165
|
|
|
139
166
|
switch (subResult.kind) {
|
|
140
167
|
case 'match':
|
|
@@ -188,6 +215,42 @@ function dispatch(
|
|
|
188
215
|
};
|
|
189
216
|
}
|
|
190
217
|
|
|
218
|
+
// --- Flag-arity awareness
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Whether a flag token consumes the following argv token as its value.
|
|
222
|
+
*
|
|
223
|
+
* Mirrors the parser's value-consumption rules (`parseLongFlag` /
|
|
224
|
+
* `parseShortFlags`) so the command-name scan skips exactly the tokens the
|
|
225
|
+
* parser would treat as flag values:
|
|
226
|
+
* - `--flag value` → consumes when `--flag` is a known value-flag.
|
|
227
|
+
* - `--flag=value` → self-contained, consumes nothing.
|
|
228
|
+
* - `-abc value` → consumes only when the trailing short flag is a value-flag;
|
|
229
|
+
* an earlier value-flag char takes the rest of the group as an inline value.
|
|
230
|
+
*
|
|
231
|
+
* Unknown flags conservatively consume nothing (the parser reports them later).
|
|
232
|
+
*
|
|
233
|
+
* @internal
|
|
234
|
+
*/
|
|
235
|
+
function consumesFollowingToken(token: string, valueFlags: ValueFlagLookup): boolean {
|
|
236
|
+
if (token.startsWith('--')) {
|
|
237
|
+
if (token.includes('=')) return false;
|
|
238
|
+
const entry = valueFlags.get(token.slice(2));
|
|
239
|
+
return entry !== undefined && flagExpectsValue(entry[1]);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// Short flag group (`-abc`). A value attaches to the trailing flag only; an
|
|
243
|
+
// earlier value-flag char swallows the remaining chars as an inline value.
|
|
244
|
+
const chars = token.slice(1);
|
|
245
|
+
for (let i = 0; i < chars.length; i++) {
|
|
246
|
+
const entry = valueFlags.get(chars.charAt(i));
|
|
247
|
+
if (entry === undefined) return false;
|
|
248
|
+
if (!flagExpectsValue(entry[1])) continue;
|
|
249
|
+
return i === chars.length - 1;
|
|
250
|
+
}
|
|
251
|
+
return false;
|
|
252
|
+
}
|
|
253
|
+
|
|
191
254
|
// --- "Did you mean?" suggestion
|
|
192
255
|
|
|
193
256
|
/**
|
|
@@ -282,5 +345,5 @@ function uniqueCommands(commands: ReadonlyMap<string, ErasedCommand>): readonly
|
|
|
282
345
|
|
|
283
346
|
// --- Exports
|
|
284
347
|
|
|
285
|
-
export type { DispatchMatch, DispatchNeedsSubcommand, DispatchResult, DispatchUnknown };
|
|
286
|
-
export { dispatch, findClosestCommand, levenshtein, uniqueCommands };
|
|
348
|
+
export type { DispatchMatch, DispatchNeedsSubcommand, DispatchResult, DispatchUnknown, ValueFlagLookup };
|
|
349
|
+
export { consumesFollowingToken, dispatch, findClosestCommand, levenshtein, uniqueCommands };
|
package/src/core/cli/index.ts
CHANGED
|
@@ -19,6 +19,7 @@ import type { HelpOptions } from '#internals/core/help/index.ts';
|
|
|
19
19
|
import { formatHelp } from '#internals/core/help/index.ts';
|
|
20
20
|
import type { CapturedOutput } from '#internals/core/output/index.ts';
|
|
21
21
|
import { createCaptureOutput, createOutput } from '#internals/core/output/index.ts';
|
|
22
|
+
import { includesBeforeSeparator } from '#internals/core/parse/index.ts';
|
|
22
23
|
import type { ArgBuilder, ArgConfig } from '#internals/core/schema/arg.ts';
|
|
23
24
|
import { arg } from '#internals/core/schema/arg.ts';
|
|
24
25
|
import type {
|
|
@@ -805,7 +806,9 @@ class CLIBuilder {
|
|
|
805
806
|
*/
|
|
806
807
|
async execute(argv: readonly string[], options?: CLIRunOptions): Promise<RunResult> {
|
|
807
808
|
// -- Detect global --json mode before building output ---------------------
|
|
808
|
-
|
|
809
|
+
// Only a `--json` before the `--` separator toggles JSON mode; a literal
|
|
810
|
+
// `--json` positional (after `--`) must reach the command unchanged (#28).
|
|
811
|
+
const hasJsonFlag = includesBeforeSeparator(argv, '--json');
|
|
809
812
|
const jsonMode = hasJsonFlag || options?.jsonMode === true;
|
|
810
813
|
|
|
811
814
|
const captureOptions = {
|
package/src/core/cli/planner.ts
CHANGED
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
|
|
13
13
|
import { CLIError, ParseError } from '#internals/core/errors/index.ts';
|
|
14
14
|
import type { HelpOptions } from '#internals/core/help/index.ts';
|
|
15
|
+
import { buildFlagLookup, includesBeforeSeparator } from '#internals/core/parse/index.ts';
|
|
15
16
|
import type { OutputPolicy } from '#internals/core/output/contracts.ts';
|
|
16
17
|
import type { CommandMeta, CommandSchema, ErasedCommand } from '#internals/core/schema/command.ts';
|
|
17
18
|
import { dispatch, findClosestCommand } from './dispatch.ts';
|
|
@@ -257,13 +258,20 @@ function buildPlannerMatchOutcome(
|
|
|
257
258
|
* @internal
|
|
258
259
|
*/
|
|
259
260
|
function planInvocation(options: PlanInvocationOptions): InvocationPlan {
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
261
|
+
// `--json` is a root-level flag, not part of any command schema, so it is
|
|
262
|
+
// stripped before dispatch/parse — but only before the `--` separator, so a
|
|
263
|
+
// literal `--json` positional (after `--`) survives and reaches the command
|
|
264
|
+
// (#28). The `--json` *output mode* is detected separately in `.execute()`.
|
|
265
|
+
const separatorIndex = options.argv.indexOf('--');
|
|
266
|
+
const head = separatorIndex === -1 ? options.argv : options.argv.slice(0, separatorIndex);
|
|
267
|
+
const tail = separatorIndex === -1 ? [] : options.argv.slice(separatorIndex);
|
|
268
|
+
const filteredHead = head.includes('--json') ? head.filter((arg) => arg !== '--json') : head;
|
|
269
|
+
const filteredArgv = separatorIndex === -1 ? filteredHead : [...filteredHead, ...tail];
|
|
263
270
|
|
|
264
271
|
if (
|
|
265
272
|
options.schema.version !== undefined &&
|
|
266
|
-
(
|
|
273
|
+
(includesBeforeSeparator(options.argv, '--version') ||
|
|
274
|
+
includesBeforeSeparator(options.argv, '-V'))
|
|
267
275
|
) {
|
|
268
276
|
return {
|
|
269
277
|
kind: 'root-version',
|
|
@@ -316,8 +324,18 @@ function planInvocation(options: PlanInvocationOptions): InvocationPlan {
|
|
|
316
324
|
};
|
|
317
325
|
}
|
|
318
326
|
|
|
319
|
-
const result = dispatch(filteredArgv, buildRootCommandMap(options.schema.commands));
|
|
320
327
|
const defaultCommand = options.schema.defaultCommand;
|
|
328
|
+
// At the root, a default command's flags govern value-flag arity so a
|
|
329
|
+
// space-separated value (`mycli --region eu`) is not misread as a command
|
|
330
|
+
// name and stolen from the default-command fallback (see #25).
|
|
331
|
+
const rootValueFlags =
|
|
332
|
+
defaultCommand !== undefined ? buildFlagLookup(defaultCommand.schema.flags) : undefined;
|
|
333
|
+
const result = dispatch(
|
|
334
|
+
filteredArgv,
|
|
335
|
+
buildRootCommandMap(options.schema.commands),
|
|
336
|
+
[],
|
|
337
|
+
rootValueFlags,
|
|
338
|
+
);
|
|
321
339
|
|
|
322
340
|
switch (result.kind) {
|
|
323
341
|
case 'unknown': {
|
|
@@ -16,7 +16,7 @@ import type {
|
|
|
16
16
|
import { CLIError } from '#internals/core/errors/index.ts';
|
|
17
17
|
import { formatHelp } from '#internals/core/help/index.ts';
|
|
18
18
|
import type { CapturedOutput } from '#internals/core/output/index.ts';
|
|
19
|
-
import { parse } from '#internals/core/parse/index.ts';
|
|
19
|
+
import { includesBeforeSeparator, parse } from '#internals/core/parse/index.ts';
|
|
20
20
|
import { createTestPrompter } from '#internals/core/prompt/index.ts';
|
|
21
21
|
import type { DeprecationWarning, ResolveOptions } from '#internals/core/resolve/index.ts';
|
|
22
22
|
import { resolve } from '#internals/core/resolve/index.ts';
|
|
@@ -258,13 +258,5 @@ function formatDeprecation(deprecation: DeprecationWarning): string {
|
|
|
258
258
|
: `Warning: ${entity} is deprecated`;
|
|
259
259
|
}
|
|
260
260
|
|
|
261
|
-
function includesBeforeSeparator(argv: readonly string[], token: string): boolean {
|
|
262
|
-
for (const arg of argv) {
|
|
263
|
-
if (arg === '--') return false;
|
|
264
|
-
if (arg === token) return true;
|
|
265
|
-
}
|
|
266
|
-
return false;
|
|
267
|
-
}
|
|
268
|
-
|
|
269
261
|
export type { CommandExecutionRequest, CommandExecutionResult };
|
|
270
262
|
export { buildRunResult, executeCommand };
|
package/src/core/parse/index.ts
CHANGED
|
@@ -101,6 +101,26 @@ function tokenize(argv: readonly string[]): readonly Token[] {
|
|
|
101
101
|
return tokens;
|
|
102
102
|
}
|
|
103
103
|
|
|
104
|
+
/**
|
|
105
|
+
* Whether `token` appears in argv before the `--` end-of-options separator.
|
|
106
|
+
*
|
|
107
|
+
* Everything at or after the first `--` is a literal positional, so root-level
|
|
108
|
+
* flag interception (`--help` / `--version` / `--json`) must use this instead of
|
|
109
|
+
* a naive `Array.includes()` — otherwise a post-separator literal (`-- --json`)
|
|
110
|
+
* is wrongly treated as the flag.
|
|
111
|
+
*
|
|
112
|
+
* @param argv - Raw argument strings.
|
|
113
|
+
* @param token - Exact flag token to look for (e.g. `--version`).
|
|
114
|
+
* @returns `true` if `token` occurs before any `--` separator.
|
|
115
|
+
*/
|
|
116
|
+
function includesBeforeSeparator(argv: readonly string[], token: string): boolean {
|
|
117
|
+
for (const arg of argv) {
|
|
118
|
+
if (arg === '--') return false;
|
|
119
|
+
if (arg === token) return true;
|
|
120
|
+
}
|
|
121
|
+
return false;
|
|
122
|
+
}
|
|
123
|
+
|
|
104
124
|
// --- Parse result
|
|
105
125
|
|
|
106
126
|
/**
|
|
@@ -658,4 +678,4 @@ function levenshtein(a: string, b: string): number {
|
|
|
658
678
|
// --- Exports
|
|
659
679
|
|
|
660
680
|
export type { ParseResult, Token };
|
|
661
|
-
export { parse, tokenize };
|
|
681
|
+
export { buildFlagLookup, flagExpectsValue, includesBeforeSeparator, parse, tokenize };
|