@kjanat/dreamcli 2.2.1 → 2.4.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.
Files changed (38) hide show
  1. package/CHANGELOG.md +42 -1
  2. package/README.md +94 -34
  3. package/dist/core/cli/dispatch.d.mts +30 -2
  4. package/dist/core/cli/dispatch.mjs +1 -1
  5. package/dist/core/cli/index.mjs +1 -1
  6. package/dist/core/cli/planner.mjs +1 -1
  7. package/dist/core/config/package-json.mjs +1 -1
  8. package/dist/core/execution/index.mjs +1 -1
  9. package/dist/core/json-schema/meta-descriptions.generated.d.mts +59 -59
  10. package/dist/core/output/activity.mjs +1 -1
  11. package/dist/core/output/index.d.mts +6 -1
  12. package/dist/core/output/index.mjs +2 -2
  13. package/dist/core/parse/index.d.mts +31 -1
  14. package/dist/core/parse/index.mjs +1 -1
  15. package/dist/core/schema/activity.d.mts +1 -1
  16. package/dist/core/schema/command.d.mts +8 -0
  17. package/dist/core/schema/run.d.mts +8 -5
  18. package/dist/core/schema-dsl/runtime.mjs +1 -1
  19. package/dist/core/testkit/index.mjs +1 -1
  20. package/dist/index.mjs +1 -1
  21. package/dist/runtime/paths.mjs +1 -1
  22. package/dist/strings.d.mts +27 -0
  23. package/dist/strings.mjs +1 -0
  24. package/dist/testkit.mjs +1 -1
  25. package/dist/version.mjs +1 -1
  26. package/package.json +37 -25
  27. package/src/core/cli/dispatch.ts +70 -7
  28. package/src/core/cli/index.ts +13 -4
  29. package/src/core/cli/planner.ts +80 -6
  30. package/src/core/config/package-json.ts +3 -2
  31. package/src/core/execution/index.ts +8 -10
  32. package/src/core/help/index.ts +2 -2
  33. package/src/core/output/index.ts +29 -0
  34. package/src/core/parse/index.ts +23 -3
  35. package/src/core/schema/command.ts +8 -0
  36. package/src/core/schema/run.ts +8 -5
  37. package/src/runtime/paths.ts +4 -2
  38. package/src/strings.ts +34 -0
package/CHANGELOG.md CHANGED
@@ -7,6 +7,45 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [2.4.0] - 2026-06-23
11
+
12
+ ### Added
13
+
14
+ - **`out.setExitCode(code)` for normal-output status exits** — command handlers can now request a
15
+ process exit code without throwing or emitting error-shaped output, covering status/check CLIs that
16
+ should print their normal report while still signalling degraded state to scripts
17
+ (https://github.com/kjanat/dreamcli/issues/27).
18
+
19
+ ### Fixed
20
+
21
+ - **Unknown root commands under no-arg defaults now report `UNKNOWN_COMMAND`** — when a CLI has a
22
+ `.default()` command with no positional args, an unknown root token no longer falls through to the
23
+ default parser as an unexpected positional. Defaults that declare positional args still receive
24
+ those root tokens as before (https://github.com/kjanat/dreamcli/issues/26).
25
+
26
+ ### Security
27
+
28
+ - **Hardened trailing-separator trimming against polynomial ReDoS** — the home/config path
29
+ resolution, `package.json` repository-URL normalization, and runtime-binary `basename` helpers
30
+ previously stripped trailing slashes with backtracking regexes (`/[\\/]+$/`, `/\/+$/`) that CodeQL
31
+ flagged as polynomial regular expressions (`js/polynomial-redos`). They now route through a shared
32
+ linear-time `stripTrailing` scan, so adversarial slash-heavy input can no longer trigger quadratic
33
+ matching. No behavior change for valid inputs.
34
+
35
+ ## [2.3.0] - 2026-06-20
36
+
37
+ ### Fixed
38
+
39
+ - **Command dispatch now respects flag value-arity** — a space-separated value-flag value (e.g.
40
+ `--source anthropic`) is no longer mistaken for a command name when it collides with a registered
41
+ command, so the default-command fallback runs as intended
42
+ (https://github.com/kjanat/dreamcli/issues/25). The command-name scan now skips the token a
43
+ space-separated value-flag consumes (mirroring the parser's own value-consumption rules); the
44
+ inline `--source=anthropic` form already worked, and both forms are now consistent.
45
+ - **Root `--version`/`--json` interception now respects the `--` end-of-options separator**
46
+ (https://github.com/kjanat/dreamcli/issues/28). A `--version` or `--json` token after `--` is
47
+ treated as a literal positional instead of triggering version output or JSON mode.
48
+
10
49
  ## [2.2.1] - 2026-06-10
11
50
 
12
51
  ### Added
@@ -790,7 +829,9 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
790
829
  - MIT License.
791
830
  - Markdownlint configuration.
792
831
 
793
- [Unreleased]: https://github.com/kjanat/dreamcli/compare/v2.2.1...HEAD
832
+ [Unreleased]: https://github.com/kjanat/dreamcli/compare/v2.4.0...HEAD
833
+ [2.4.0]: https://github.com/kjanat/dreamcli/compare/v2.3.0...v2.4.0
834
+ [2.3.0]: https://github.com/kjanat/dreamcli/compare/v2.2.1...v2.3.0
794
835
  [2.2.1]: https://github.com/kjanat/dreamcli/compare/v2.2.0...v2.2.1
795
836
  [2.2.0]: https://github.com/kjanat/dreamcli/compare/v2.1.0...v2.2.0
796
837
  [2.1.0]: https://github.com/kjanat/dreamcli/compare/v2.0.1...v2.1.0
package/README.md CHANGED
@@ -8,14 +8,7 @@ Schema-first, fully typed TypeScript CLI framework. Zero runtime dependencies.
8
8
  One flag declaration configures the entire resolution pipeline:
9
9
 
10
10
  ```ts
11
- import {
12
- cli,
13
- command,
14
- flag,
15
- arg,
16
- middleware,
17
- CLIError,
18
- } from '@kjanat/dreamcli';
11
+ import { cli, command, flag, arg } from '@kjanat/dreamcli';
19
12
 
20
13
  const deploy = command('deploy')
21
14
  .description('Deploy to an environment')
@@ -34,6 +27,8 @@ const deploy = command('deploy')
34
27
  .action(({ args, flags, out }) => {
35
28
  out.log(`Deploying ${args.target} to ${flags.region}`);
36
29
  });
30
+
31
+ cli('deploy').default(deploy).run();
37
32
  ```
38
33
 
39
34
  By the time `action` runs, `flags.region` is `"us" | "eu" | "ap"` — not `string | undefined`.
@@ -64,7 +59,7 @@ deno add jsr:@kjanat/dreamcli # or npm:@kjanat/dreamcli
64
59
  ### Single command
65
60
 
66
61
  ```ts
67
- import { command, flag, arg } from '@kjanat/dreamcli';
62
+ import { cli, command, flag, arg } from '@kjanat/dreamcli';
68
63
 
69
64
  const greet = command('greet')
70
65
  .description('Greet someone')
@@ -87,11 +82,17 @@ const greet = command('greet')
87
82
  }
88
83
  });
89
84
 
90
- greet.run();
85
+ cli('greet').default(greet).run();
91
86
  ```
92
87
 
93
88
  ### Multi-command CLI
94
89
 
90
+ <picture>
91
+ <source media="(prefers-color-scheme: dark)" width="700" height="400" alt="dreamcli-migrate-dark" srcset="https://github.com/user-attachments/assets/1ef7f20c-9ffb-4cb6-a6bc-fb562895aa6f">
92
+ <source media="(prefers-color-scheme: light)" width="700" height="400" alt="dreamcli-migrate-light" srcset="https://github.com/user-attachments/assets/1ee5f38d-cad8-47ec-94b2-c826eabab76b">
93
+ <img alt="DreamCLI migration progress demo" width="700" height="400" src="https://github.com/user-attachments/assets/1ee5f38d-cad8-47ec-94b2-c826eabab76b">
94
+ </picture>
95
+
95
96
  ```ts
96
97
  import {
97
98
  cli,
@@ -130,8 +131,31 @@ const login = command('login')
130
131
  const migrate = command('migrate')
131
132
  .description('Run migrations')
132
133
  .flag('steps', flag.number())
133
- .action(({ flags, out }) => {
134
- out.log(`migrating ${flags.steps ?? 'all'} steps`);
134
+ .action(async ({ flags, meta, out }) => {
135
+ const steps = flags.steps ?? 3;
136
+
137
+ out.log(`${meta.name} ${meta.version ?? ''}`.trim());
138
+ out.log(`Command: ${meta.command}`);
139
+
140
+ const spinner = out.spinner('Preparing migrations');
141
+ await new Promise((resolve) =>
142
+ setTimeout(resolve, 1000),
143
+ );
144
+ spinner.succeed(`Ready to run ${steps} steps`);
145
+
146
+ const progress = out.progress({
147
+ label: 'Migrating',
148
+ total: steps,
149
+ });
150
+
151
+ for (let step = 1; step <= steps; step++) {
152
+ await new Promise((resolve) =>
153
+ setTimeout(resolve, 700),
154
+ );
155
+ progress.update(step);
156
+ }
157
+
158
+ progress.done(`Migrated ${steps} steps`);
135
159
  });
136
160
 
137
161
  const seed = command('seed')
@@ -190,6 +214,8 @@ the insight was wiring them so types flow end-to-end.
190
214
  ### Flag types
191
215
 
192
216
  ```ts
217
+ import { flag } from '@kjanat/dreamcli';
218
+
193
219
  flag.string(); // string | undefined
194
220
  flag.number(); // number | undefined
195
221
  flag.boolean(); // boolean (defaults to false)
@@ -217,6 +243,8 @@ non-interactive contexts (CI, piped stdin), prompts are automatically skipped.
217
243
  Four prompt types, declared per-flag or per-command:
218
244
 
219
245
  ```ts
246
+ import { command, flag } from '@kjanat/dreamcli';
247
+
220
248
  // Per-flag
221
249
  flag.string().prompt({ kind: 'input', message: 'Name?' });
222
250
  flag
@@ -245,7 +273,7 @@ command('deploy')
245
273
  ### Derive typed context from resolved input
246
274
 
247
275
  ```ts
248
- import { CLIError } from '@kjanat/dreamcli';
276
+ import { CLIError, command, flag } from '@kjanat/dreamcli';
249
277
 
250
278
  command('deploy')
251
279
  .flag('token', flag.string().env('AUTH_TOKEN'))
@@ -268,7 +296,7 @@ the action handler runs.
268
296
  ### Middleware with typed context
269
297
 
270
298
  ```ts
271
- import { middleware } from '@kjanat/dreamcli';
299
+ import { command, middleware } from '@kjanat/dreamcli';
272
300
 
273
301
  const timing = middleware<{ startTime: number }>(
274
302
  async ({ next }) => {
@@ -301,26 +329,33 @@ Use middleware when you need wrapper behavior with `next()`.
301
329
  Handlers receive `out` instead of `console`. Adapts to context automatically:
302
330
 
303
331
  ```ts
304
- cli('mycli')
305
- // ... omitted for brevity
306
- .action(({ out }) => {
307
- out.log('Human-readable message');
308
- out.json({ status: 'ok', count: 42 });
309
- out.table(rows, [
310
- { key: 'name', header: 'Name' },
311
- { key: 'status', header: 'Status' },
312
- ]);
313
-
314
- const spinner = out.spinner('Deploying...');
315
- spinner.succeed('Done');
332
+ import { cli, command } from '@kjanat/dreamcli';
333
+
334
+ const rows = [
335
+ { name: 'api', status: 'ok' },
336
+ { name: 'worker', status: 'deploying' },
337
+ ];
338
+
339
+ const status = command('status').action(({ out }) => {
340
+ out.log('Human-readable message');
341
+ out.json({ status: 'ok', count: 42 });
342
+ out.table(rows, [
343
+ { key: 'name', header: 'Name' },
344
+ { key: 'status', header: 'Status' },
345
+ ]);
346
+
347
+ const spinner = out.spinner('Deploying...');
348
+ spinner.succeed('Done');
316
349
 
317
- const progress = out.progress({
318
- label: 'Uploading',
319
- total: 100,
320
- });
321
- progress.update(50);
322
- progress.done('Upload complete');
350
+ const progress = out.progress({
351
+ label: 'Uploading',
352
+ total: 100,
323
353
  });
354
+ progress.update(50);
355
+ progress.done('Upload complete');
356
+ });
357
+
358
+ cli('mycli').default(status).run();
324
359
  ```
325
360
 
326
361
  - TTY → pretty formatting, spinners animate
@@ -332,7 +367,24 @@ cli('mycli')
332
367
  Generated from the command schema — always in sync:
333
368
 
334
369
  ```ts
335
- import { generateCompletion } from '@kjanat/dreamcli';
370
+ import { cli, command } from '@kjanat/dreamcli';
371
+
372
+ cli('mycli').command(command('deploy')).completions().run();
373
+
374
+ // mycli completions bash
375
+ // mycli completion zsh
376
+ ```
377
+
378
+ For programmatic integrations, call the generator directly:
379
+
380
+ ```ts
381
+ import {
382
+ cli,
383
+ command,
384
+ generateCompletion,
385
+ } from '@kjanat/dreamcli';
386
+
387
+ const myCli = cli('mycli').command(command('deploy'));
336
388
 
337
389
  generateCompletion(myCli.schema, 'bash');
338
390
  generateCompletion(myCli.schema, 'zsh');
@@ -341,6 +393,8 @@ generateCompletion(myCli.schema, 'zsh');
341
393
  ### Config file discovery
342
394
 
343
395
  ```ts
396
+ import { command, flag } from '@kjanat/dreamcli';
397
+
344
398
  command('deploy').flag(
345
399
  'region',
346
400
  flag.enum(['us', 'eu']).config('deploy.region'),
@@ -350,7 +404,7 @@ command('deploy').flag(
350
404
  Searches XDG-standard paths automatically. JSON built-in, plugin hook for YAML/TOML:
351
405
 
352
406
  ```ts
353
- import { configFormat } from '@kjanat/dreamcli';
407
+ import { cli, configFormat } from '@kjanat/dreamcli';
354
408
  import { parse as parseYAML } from 'yaml';
355
409
 
356
410
  cli('mycli')
@@ -361,6 +415,11 @@ cli('mycli')
361
415
  ### Structured errors
362
416
 
363
417
  ```ts
418
+ import { CLIError } from '@kjanat/dreamcli';
419
+
420
+ const target = 'production';
421
+ const region = 'us';
422
+
364
423
  throw new CLIError('Deployment failed', {
365
424
  code: 'DEPLOY_FAILED',
366
425
  exitCode: 1,
@@ -378,6 +437,7 @@ In `--json` mode, errors serialize to machine-readable JSON.
378
437
  subprocesses, no `process.argv` mutation, no mocking.
379
438
 
380
439
  ```ts
440
+ import { expect } from 'vitest';
381
441
  import { arg, command, flag } from '@kjanat/dreamcli';
382
442
  import {
383
443
  runCommand,
@@ -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 e(t,n,i=[]){let a=-1;for(let e=0;e<t.length;e++){let n=t[e];if(n===`--`){e+1<t.length&&(a=e+1);break}if(n!==void 0&&!n.startsWith(`-`)){a=e;break}}if(a===-1)return{kind:`unknown`,input:``,candidates:r(n),parentPath:i};let o=t[a];if(o===void 0)return{kind:`unknown`,input:``,candidates:r(n),parentPath:i};let s=n.get(o);if(s===void 0)return{kind:`unknown`,input:o,candidates:r(n),parentPath:i};let c=[...t.slice(0,a),...t.slice(a+1)],l=[...i,s.schema];if(s.subcommands.size>0){let t=e(c,s.subcommands,l);switch(t.kind){case`match`:return t;case`unknown`:return t.input===``?s.schema.hasAction?{kind:`match`,command:s,commandPath:l,remainingArgv:c}:{kind:`needs-subcommand`,command:s,commandPath:l}:s.schema.hasAction?{kind:`match`,command:s,commandPath:l,remainingArgv:c}:t;case`needs-subcommand`:return t;default:return t}}return{kind:`match`,command:s,commandPath:l,remainingArgv:c}}function t(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 n(e,n){let r,i=4;for(let a of n){let n=t(e,a.schema.name);n<i&&(i=n,r=a.schema.name);for(let n of a.schema.aliases){let o=t(e,n);o<i&&(i=o,r=a.schema.name)}}return i<=3?r:void 0}function r(e){let t=new Set,n=[];for(let r of e.values())t.has(r)||(t.add(r),n.push(r));return n}export{e as dispatch,n as findClosestCommand};
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};
@@ -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 i,executeCommand as a}from"../execution/index.mjs";import{createCaptureOutput as o,createOutput as s}from"../output/index.mjs";import{arg as c}from"../schema/arg.mjs";import{command as l}from"../schema/command.mjs";import{runCommand as u}from"../testkit/index.mjs";import{createAdapter as d}from"../../runtime/auto.mjs";import{deriveHelpLinks as f}from"./help-links.mjs";import{planInvocation as p}from"./planner.mjs";import"./plugin.mjs";import{formatRootHelp as m}from"./root-help.mjs";import{prepareRuntimePreflight as h}from"./runtime-preflight.mjs";function g(e){return[e.name,...e.aliases]}function _(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 v(t,n){let r=new Map;for(let e of t)for(let t of g(e.schema))_(`root`,r,t,e.schema.name);for(let t of g(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 y(e){let t=new Map,n=new Map;for(let r of e._subcommands){let i=g(r.schema);for(let t of i)_(e.schema.name,n,t,r.schema.name);let a=y(r);for(let e of i)t.set(e,a)}return{schema:e.schema,subcommands:t,_command:e,_execute(t,n){return u(e,t,n)}}}function b(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 x=class u{schema;constructor(e){this.schema=e}version(e){return new u({...this.schema,version:e})}description(e){return new u({...this.schema,description:e})}links(e){return new u({...this.schema,helpLinks:{name:E(e?.name),version:E(e?.version)}})}config(e,t){return new u({...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 u({...this.schema,configSettings:{...this.schema.configSettings,loaders:[...n,t]}})}packageJson(e){return k(e)?new u({...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 u({...this.schema,packageJsonSettings:{inferName:e?.inferName??!1,from:O(e?.from),data:void 0}})}command(e){return v(this.schema.commands,e.schema),new u({...this.schema,commands:[...this.schema.commands,y(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`});v(this.schema.commands,t.schema);let n=y(t);return new u({...this.schema,commands:[...this.schema.commands,n],defaultCommand:n})}plugin(e){return new u({...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=l(`completions`).alias(`completion`).description(`Generate shell completion script`).arg(`shell`,c.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 u({...this.command(s).schema,hasBuiltInCompletions:!0})}async execute(e,t){let n=e.includes(`--json`)||t?.jsonMode===!0,s={...t?.verbosity===void 0?{}:{verbosity:t.verbosity},...n?{jsonMode:n}:{},...t?.isTTY===void 0?{}:{isTTY:t.isTTY}},c,l;t?.out===void 0?[c,l]=o(Object.keys(s).length>0?s:void 0):(c=t.out,l=t.captured??{stdout:[],stderr:[],activity:[]});let u={...t?.help,binName:t?.help?.binName??this.schema.name,hyperlinks:t?.help?.hyperlinks??c.isTTY},d={...t,plugins:this.schema.plugins,...n?{jsonMode:n}:{}},f={jsonMode:n,isTTY:c.isTTY,verbosity:t?.verbosity??`normal`},h=p({schema:this.schema,argv:e,help:u,output:f});switch(h.kind){case`root-version`:return c.log(h.version),i({exitCode:0,error:void 0},l);case`root-help`:{let e=m(D(this.schema),h.help);return c.log(e),i({exitCode:0,error:void 0},l)}case`dispatch-error`:return n?c.json({error:h.error.toJSON()}):(c.error(h.error.message),h.error.suggest!==void 0&&h.error.code!==`NO_ACTION`&&c.error(`Suggestion: ${h.error.suggest}`)),i({exitCode:h.error.exitCode,error:h.error},l);case`needs-subcommand`:{let e=r(h.command.schema,h.help);return c.log(e),i({exitCode:0,error:void 0},l)}case`match`:{let e=b(d,h.plan.help??u,h.plan.meta);return h.plan.command._command===void 0?h.plan.command._execute(h.plan.argv,{...e,mergedSchema:h.plan.mergedSchema}):i(await a({command:h.plan.command._command,argv:h.plan.argv,out:c,schema:h.plan.mergedSchema,meta:h.plan.meta,options:e}),l)}}}async run(e){let t=e?.adapter??d(),n=this.schema.inheritName?T(t.argv):void 0,r=await h({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 u(r.schema),a={...e,...r.inputs,out:s({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 S=new Set([`bun`,`deno`,`node`,`tsx`]);function C(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 w(e){let t=e.toLowerCase().replace(/\.exe$/i,``);return S.has(t)}function T(e){let t=e[0],n=e[1],r=t===void 0?void 0:C(t);if(r!==void 0&&w(r)){if(r===`bun`&&n===`run`){let t=e[2];return t===void 0||t.startsWith(`-`)?void 0:C(t)}return r===`deno`&&n===`run`||n===void 0||n.startsWith(`-`)?void 0:C(n)}return t===void 0?void 0:C(t)}function E(e){if(e!==void 0)return e instanceof URL?e.href:e}function D(e){return e.helpLinks===void 0?e:{...e,helpLinks:f(e.helpLinks,e.packageJsonSettings?.data,e.version)}}function O(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 k(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 A(e){return new x({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{x as CLIBuilder,A as cli};
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{clearRequestedExitCode as i,createCaptureOutput as a,createOutput as o}from"../output/index.mjs";import{includesBeforeSeparator as s}from"../parse/index.mjs";import{buildRunResult as c,executeCommand as l}from"../execution/index.mjs";import{arg as u}from"../schema/arg.mjs";import{command as d}from"../schema/command.mjs";import{runCommand as f}from"../testkit/index.mjs";import{stripTrailing as p}from"../../strings.mjs";import{createAdapter as m}from"../../runtime/auto.mjs";import{deriveHelpLinks as h}from"./help-links.mjs";import{planInvocation as g}from"./planner.mjs";import"./plugin.mjs";import{formatRootHelp as _}from"./root-help.mjs";import{prepareRuntimePreflight as v}from"./runtime-preflight.mjs";function y(e){return[e.name,...e.aliases]}function b(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 x(t,n){let r=new Map;for(let e of t)for(let t of y(e.schema))b(`root`,r,t,e.schema.name);for(let t of y(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 S(e){let t=new Map,n=new Map;for(let r of e._subcommands){let i=y(r.schema);for(let t of i)b(e.schema.name,n,t,r.schema.name);let a=S(r);for(let e of i)t.set(e,a)}return{schema:e.schema,subcommands:t,_command:e,_execute(t,n){return f(e,t,n)}}}function C(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 w=class f{schema;constructor(e){this.schema=e}version(e){return new f({...this.schema,version:e})}description(e){return new f({...this.schema,description:e})}links(e){return new f({...this.schema,helpLinks:{name:k(e?.name),version:k(e?.version)}})}config(e,t){return new f({...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 f({...this.schema,configSettings:{...this.schema.configSettings,loaders:[...n,t]}})}packageJson(e){return M(e)?new f({...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 f({...this.schema,packageJsonSettings:{inferName:e?.inferName??!1,from:j(e?.from),data:void 0}})}command(e){return x(this.schema.commands,e.schema),new f({...this.schema,commands:[...this.schema.commands,S(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`});x(this.schema.commands,t.schema);let n=S(t);return new f({...this.schema,commands:[...this.schema.commands,n],defaultCommand:n})}plugin(e){return new f({...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=d(`completions`).alias(`completion`).description(`Generate shell completion script`).arg(`shell`,u.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 f({...this.command(s).schema,hasBuiltInCompletions:!0})}async execute(e,t){let n=s(e,`--json`)||t?.jsonMode===!0,o={...t?.verbosity===void 0?{}:{verbosity:t.verbosity},...n?{jsonMode:n}:{},...t?.isTTY===void 0?{}:{isTTY:t.isTTY}},u,d;t?.out===void 0?[u,d]=a(Object.keys(o).length>0?o:void 0):(u=t.out,d=t.captured??{stdout:[],stderr:[],activity:[]}),i(u);let f={...t?.help,binName:t?.help?.binName??this.schema.name,hyperlinks:t?.help?.hyperlinks??u.isTTY},p={...t,plugins:this.schema.plugins,...n?{jsonMode:n}:{}},m={jsonMode:n,isTTY:u.isTTY,verbosity:t?.verbosity??`normal`},h=g({schema:this.schema,argv:e,help:f,output:m});switch(h.kind){case`root-version`:return u.log(h.version),c({exitCode:0,error:void 0},d);case`root-help`:{let e=_(A(this.schema),h.help);return u.log(e),c({exitCode:0,error:void 0},d)}case`dispatch-error`:return n?u.json({error:h.error.toJSON()}):(u.error(h.error.message),h.error.suggest!==void 0&&h.error.code!==`NO_ACTION`&&u.error(`Suggestion: ${h.error.suggest}`)),c({exitCode:h.error.exitCode,error:h.error},d);case`needs-subcommand`:{let e=r(h.command.schema,h.help);return u.log(e),c({exitCode:0,error:void 0},d)}case`match`:{let e=C(p,h.plan.help??f,h.plan.meta);return h.plan.command._command===void 0?h.plan.command._execute(h.plan.argv,{...e,mergedSchema:h.plan.mergedSchema}):c(await l({command:h.plan.command._command,argv:h.plan.argv,out:u,schema:h.plan.mergedSchema,meta:h.plan.meta,options:e}),d)}}}async run(e){let t=e?.adapter??m(),n=this.schema.inheritName?O(t.argv):void 0,r=await v({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 f(r.schema),a={...e,...r.inputs,out:o({stdout:t.stdout,stderr:t.stderr,jsonMode:r.inputs.jsonMode,isTTY:r.inputs.isTTY,...r.inputs.verbosity===`normal`?{}:{verbosity:r.inputs.verbosity}})},s=await i.execute(r.filteredArgv,a);for(let e of s.stdout)t.stdout(e);for(let e of s.stderr)t.stderr(e);return t.exit(s.exitCode)}};const T=new Set([`bun`,`deno`,`node`,`tsx`]);function E(e){let t=p(e,[47,92]);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 D(e){let t=e.toLowerCase().replace(/\.exe$/i,``);return T.has(t)}function O(e){let t=e[0],n=e[1],r=t===void 0?void 0:E(t);if(r!==void 0&&D(r)){if(r===`bun`&&n===`run`){let t=e[2];return t===void 0||t.startsWith(`-`)?void 0:E(t)}return r===`deno`&&n===`run`||n===void 0||n.startsWith(`-`)?void 0:E(n)}return t===void 0?void 0:E(t)}function k(e){if(e!==void 0)return e instanceof URL?e.href:e}function A(e){return e.helpLinks===void 0?e:{...e,helpLinks:h(e.helpLinks,e.packageJsonSettings?.data,e.version)}}function j(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 M(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 N(e){return new w({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{w as CLIBuilder,N as cli};
@@ -1 +1 @@
1
- import{collectPropagatedFlags as e}from"./propagate.mjs";import{CLIError as t,ParseError as n}from"../errors/index.mjs";import{dispatch as r,findClosestCommand as i}from"./dispatch.mjs";function a(e,t,n){return{name:e.name,bin:t.binName??e.name,version:e.version,command:n}}function o(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 s(t,n){let r=e(n);return Object.keys(r).length===0?t.schema:{...t.schema,flags:{...r,...t.schema.flags}}}function c(e){return{command:e.command,mergedSchema:s(e.command,e.commandPath),argv:e.argv,meta:e.meta,plugins:e.plugins,output:e.output,help:e.help}}function l(e,t,n,r,i,o){return{kind:`match`,plan:c({command:t,commandPath:n,argv:r,meta:a(e,i,t.schema.name),plugins:e.plugins,output:o,help:i})}}function u(e){let a=e.argv.includes(`--json`)?e.argv.filter(e=>e!==`--json`):e.argv;if(e.schema.version!==void 0&&(a.includes(`--version`)||a.includes(`-V`)))return{kind:`root-version`,version:e.schema.version};let s=a[0];if(s===`--help`||s===`-h`)return{kind:`root-help`,help:e.help};if(s===`help`&&!e.schema.commands.some(e=>e.schema.name===`help`||e.schema.aliases.includes(`help`))){let t=a.slice(1);return t.length===0?{kind:`root-help`,help:e.help}:u({...e,argv:[...t,`--help`]})}if(s===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 c=r(a,o(e.schema.commands)),d=e.schema.defaultCommand;switch(c.kind){case`unknown`:{if(d!==void 0&&c.parentPath.length===0&&(c.input===``?void 0:i(c.input,c.candidates))===void 0)return l(e.schema,d,[d.schema],a,e.help,e.output);if(c.input===``){let t=a.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=i(c.input,c.candidates),r=c.parentPath.length>0?`${e.schema.name} ${c.parentPath.map(e=>e.name).join(` `)}`:e.schema.name;return{kind:`dispatch-error`,error:new n(`Unknown command: ${c.input}`,{code:`UNKNOWN_COMMAND`,suggest:t===void 0?`Run '${r} --help' for available commands`:`Did you mean '${t}'?`})}}case`needs-subcommand`:{let t=c.commandPath.slice(0,-1).map(e=>e.name);return{kind:`needs-subcommand`,command:c.command,commandPath:c.commandPath,help:{...e.help,binName:[e.schema.name,...t].join(` `)}}}case`match`:return l(e.schema,c.command,c.commandPath,c.remainingArgv,e.help,e.output)}}export{u as planInvocation};
1
+ import{collectPropagatedFlags as e}from"./propagate.mjs";import{CLIError as t,ParseError as n}from"../errors/index.mjs";import{buildFlagLookup as r,flagExpectsValue as i,includesBeforeSeparator as a}from"../parse/index.mjs";import{dispatch as o,findClosestCommand as s}from"./dispatch.mjs";function c(e,t,n){return{name:e.name,bin:t.binName??e.name,version:e.version,command:n}}function l(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 u(t,n){let r=e(n);return Object.keys(r).length===0?t.schema:{...t.schema,flags:{...r,...t.schema.flags}}}function d(e){return{command:e.command,mergedSchema:u(e.command,e.commandPath),argv:e.argv,meta:e.meta,plugins:e.plugins,output:e.output,help:e.help}}function f(e,t,n,r,i,a){return{kind:`match`,plan:d({command:t,commandPath:n,argv:r,meta:c(e,i,t.schema.name),plugins:e.plugins,output:a,help:i})}}function p(e,t){return t===``||e.schema.args.length>0}function m(e,t){let n=r(t);for(let t=0;t<e.length;t++){let r=e[t];if(r===void 0||r===`--`||r===`-`||!r.startsWith(`-`))return;if(r.startsWith(`--`)){let e=r.indexOf(`=`),a=r.slice(2,e===-1?void 0:e),o=n.get(a);if(o===void 0)return e===-1?r:`--${a}`;e===-1&&i(o[1])&&t++;continue}let a=r.slice(1);for(let e=0;e<a.length;e++){let r=a.charAt(e),o=n.get(r);if(o===void 0)return`-${r}`;if(i(o[1])){e===a.length-1&&t++;break}}}}function h(e){let i=e.argv.indexOf(`--`),c=i===-1?e.argv:e.argv.slice(0,i),u=i===-1?[]:e.argv.slice(i),d=c.includes(`--json`)?c.filter(e=>e!==`--json`):c,g=i===-1?d:[...d,...u];if(e.schema.version!==void 0&&(a(e.argv,`--version`)||a(e.argv,`-V`)))return{kind:`root-version`,version:e.schema.version};let _=g[0];if(_===`--help`||_===`-h`)return{kind:`root-help`,help:e.help};if(_===`help`&&!e.schema.commands.some(e=>e.schema.name===`help`||e.schema.aliases.includes(`help`))){let t=g.slice(1);return t.length===0?{kind:`root-help`,help:e.help}:h({...e,argv:[...t,`--help`]})}if(_===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 v=e.schema.defaultCommand,y=v===void 0?void 0:r(v.schema.flags),b=o(g,l(e.schema.commands),[],y);switch(b.kind){case`unknown`:{if(v!==void 0&&b.parentPath.length===0){if((b.input===``?void 0:s(b.input,b.candidates))===void 0&&p(v,b.input))return f(e.schema,v,[v.schema],g,e.help,e.output);let t=m(g,v.schema.flags);if(t!==void 0)return{kind:`dispatch-error`,error:new n(`Unknown flag ${t}`,{code:`UNKNOWN_FLAG`,suggest:`Run '${e.schema.name} --help' for available commands`})}}if(b.input===``){let t=g.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=s(b.input,b.candidates),r=b.parentPath.length>0?`${e.schema.name} ${b.parentPath.map(e=>e.name).join(` `)}`:e.schema.name;return{kind:`dispatch-error`,error:new n(`Unknown command: ${b.input}`,{code:`UNKNOWN_COMMAND`,suggest:t===void 0?`Run '${r} --help' for available commands`:`Did you mean '${t}'?`})}}case`needs-subcommand`:{let t=b.commandPath.slice(0,-1).map(e=>e.name);return{kind:`needs-subcommand`,command:b.command,commandPath:b.commandPath,help:{...e.help,binName:[e.schema.name,...t].join(` `)}}}case`match`:return f(e.schema,b.command,b.commandPath,b.remainingArgv,e.help,e.output)}}export{h as planInvocation};
@@ -1 +1 @@
1
- function e(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function t(e){let t=e.lastIndexOf(`/`),n=e.lastIndexOf(`\\`),r=Math.max(t,n),i=n>t?`\\`:`/`;if(r<0)return;if(r===0)return e.length>1?i:void 0;let a=e.slice(0,r);if(a.length===2&&a[1]===`:`){let t=`${a}${i}`;return t===e?void 0:t}return a}function n(e,t){let n=e.includes(`\\`)?`\\`:`/`;return e.endsWith(n)?`${e}${t}`:`${e}${n}${t}`}async function r(e,r){let a=r??e.cwd;for(;a!==void 0;){let r=null;try{r=await e.readFile(n(a,`package.json`))}catch{}if(r!==null){let e=i(r);if(e!==null)return e}a=t(a)}return null}function i(t){try{let n=JSON.parse(t);if(!e(n))return null;let r=typeof n.name==`string`?n.name:void 0,i=typeof n.version==`string`?n.version:void 0,s=typeof n.description==`string`?n.description:void 0,c=a(n.bin),l=typeof n.homepage==`string`?n.homepage:void 0,u=o(n.repository);return{...r===void 0?{}:{name:r},...i===void 0?{}:{version:i},...s===void 0?{}:{description:s},...c===void 0?{}:{bin:c},...l===void 0?{}:{homepage:l},...u===void 0?{}:{repository:u}}}catch{return null}}function a(t){if(typeof t==`string`)return t;if(!e(t))return;let n={};for(let[e,r]of Object.entries(t)){if(typeof r!=`string`)return;n[e]=r}return n}function o(t){if(typeof t==`string`)return t;if(!e(t))return;let n=typeof t.type==`string`?t.type:void 0,r=typeof t.url==`string`?t.url:void 0,i=typeof t.directory==`string`?t.directory:void 0;if(!(n===void 0&&r===void 0&&i===void 0))return{...n===void 0?{}:{type:n},...r===void 0?{}:{url:r},...i===void 0?{}:{directory:i}}}const s={github:`https://github.com`,gitlab:`https://gitlab.com`,bitbucket:`https://bitbucket.org`};function c(e){return e.endsWith(`.git`)?e.slice(0,-4):e}function l(e){let t=typeof e.repository==`string`?e.repository:e.repository?.url;if(t===void 0)return;let n=t.trim();if(n.length===0)return;let r=/^(github|gitlab|bitbucket):([^/]+\/[^/]+)$/.exec(n);if(r!==null&&r[1]!==void 0&&r[2]!==void 0){let e=s[r[1]];if(e!==void 0)return`${e}/${c(r[2])}`}if(/^[\w.-]+\/[\w.-]+$/.test(n))return`https://github.com/${c(n)}`;n.startsWith(`git+`)&&(n=n.slice(4));let i=/^git@([^:/]+):(.+)$/.exec(n);if(i!==null&&i[1]!==void 0&&i[2]!==void 0)return`https://${i[1]}/${c(i[2].replace(/\/+$/,``))}`;if(/^(?:https?|git|ssh):\/\//.test(n))try{let e=new URL(n),t=c(e.pathname.replace(/\/+$/,``));return`https://${e.hostname}${t}`}catch{return}}function u(e){if(typeof e.bin==`object`){let t=Object.keys(e.bin);if(t.length>0&&t[0]!==void 0)return t[0]}if(e.name!==void 0){let t=e.name.indexOf(`/`);return t>=0?e.name.slice(t+1):e.name}}export{r as discoverPackageJson,u as inferCliName,l as packageRepositoryUrl};
1
+ import{stripTrailing as e}from"../../strings.mjs";function t(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function n(e){let t=e.lastIndexOf(`/`),n=e.lastIndexOf(`\\`),r=Math.max(t,n),i=n>t?`\\`:`/`;if(r<0)return;if(r===0)return e.length>1?i:void 0;let a=e.slice(0,r);if(a.length===2&&a[1]===`:`){let t=`${a}${i}`;return t===e?void 0:t}return a}function r(e,t){let n=e.includes(`\\`)?`\\`:`/`;return e.endsWith(n)?`${e}${t}`:`${e}${n}${t}`}async function i(e,t){let i=t??e.cwd;for(;i!==void 0;){let t=null;try{t=await e.readFile(r(i,`package.json`))}catch{}if(t!==null){let e=a(t);if(e!==null)return e}i=n(i)}return null}function a(e){try{let n=JSON.parse(e);if(!t(n))return null;let r=typeof n.name==`string`?n.name:void 0,i=typeof n.version==`string`?n.version:void 0,a=typeof n.description==`string`?n.description:void 0,c=o(n.bin),l=typeof n.homepage==`string`?n.homepage:void 0,u=s(n.repository);return{...r===void 0?{}:{name:r},...i===void 0?{}:{version:i},...a===void 0?{}:{description:a},...c===void 0?{}:{bin:c},...l===void 0?{}:{homepage:l},...u===void 0?{}:{repository:u}}}catch{return null}}function o(e){if(typeof e==`string`)return e;if(!t(e))return;let n={};for(let[t,r]of Object.entries(e)){if(typeof r!=`string`)return;n[t]=r}return n}function s(e){if(typeof e==`string`)return e;if(!t(e))return;let n=typeof e.type==`string`?e.type:void 0,r=typeof e.url==`string`?e.url:void 0,i=typeof e.directory==`string`?e.directory:void 0;if(!(n===void 0&&r===void 0&&i===void 0))return{...n===void 0?{}:{type:n},...r===void 0?{}:{url:r},...i===void 0?{}:{directory:i}}}const c={github:`https://github.com`,gitlab:`https://gitlab.com`,bitbucket:`https://bitbucket.org`};function l(e){return e.endsWith(`.git`)?e.slice(0,-4):e}function u(t){let n=typeof t.repository==`string`?t.repository:t.repository?.url;if(n===void 0)return;let r=n.trim();if(r.length===0)return;let i=/^(github|gitlab|bitbucket):([^/]+\/[^/]+)$/.exec(r);if(i!==null&&i[1]!==void 0&&i[2]!==void 0){let e=c[i[1]];if(e!==void 0)return`${e}/${l(i[2])}`}if(/^[\w.-]+\/[\w.-]+$/.test(r))return`https://github.com/${l(r)}`;r.startsWith(`git+`)&&(r=r.slice(4));let a=/^git@([^:/]+):(.+)$/.exec(r);if(a!==null&&a[1]!==void 0&&a[2]!==void 0)return`https://${a[1]}/${l(e(a[2],[47]))}`;if(/^(?:https?|git|ssh):\/\//.test(r))try{let t=new URL(r),n=l(e(t.pathname,[47]));return`https://${t.hostname}${n}`}catch{return}}function d(e){if(typeof e.bin==`object`){let t=Object.keys(e.bin);if(t.length>0&&t[0]!==void 0)return t[0]}if(e.name!==void 0){let t=e.name.indexOf(`/`);return t>=0?e.name.slice(t+1):e.name}}export{i as discoverPackageJson,d as inferCliName,u as packageRepositoryUrl};
@@ -1 +1 @@
1
- import{CLIError as e}from"../errors/index.mjs";import{formatHelp as t}from"../help/index.mjs";import{parse as n}from"../parse/index.mjs";import{createTestPrompter as r}from"../prompt/index.mjs";import{resolve as i}from"../resolve/index.mjs";async function a(a){let{argv:l,command:f,meta:p,options:m,out:h,schema:g}=a;try{if(d(l,`--help`)||d(l,`-h`)){let e=t(g,m?.help);return h.log(e),{exitCode:0,error:void 0}}let a=f.handler;if(a===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 o(m?.plugins,{argv:l,command:g,meta:p,out:h});let _=n(g,l),v=m?.prompter??(m?.answers===void 0?void 0:r(m.answers)),y=await i(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 s(m?.plugins,`afterResolve`,b);for(let e of y.deprecations)h.warn(u(e));return await s(m?.plugins,`beforeAction`,b),await c(f,a,y.flags,y.args,h,p),await s(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 o(e,t){if(e!==void 0)for(let n of e){let e=n.hooks.beforeParse;e!==void 0&&await e(t)}}async function s(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 c(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 l(e,t){return{exitCode:e.exitCode,stdout:t.stdout,stderr:t.stderr,activity:t.activity,error:e.error}}function u(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`}function d(e,t){for(let n of e){if(n===`--`)return!1;if(n===t)return!0}return!1}export{l as buildRunResult,a as executeCommand};
1
+ import{CLIError as e}from"../errors/index.mjs";import{formatHelp as t}from"../help/index.mjs";import{clearRequestedExitCode as n,getRequestedExitCode as r}from"../output/index.mjs";import{includesBeforeSeparator as i,parse as a}from"../parse/index.mjs";import{createTestPrompter as o}from"../prompt/index.mjs";import{resolve as s}from"../resolve/index.mjs";async function c(c){let{argv:f,command:m,meta:h,options:g,out:_,schema:v}=c;n(_);try{if(i(f,`--help`)||i(f,`-h`)){let e=t(v,g?.help);return _.log(e),{exitCode:0,error:void 0}}let n=m.handler;if(n===void 0){let t=new e(`Command '${m.schema.name}' has no action handler`,{code:`NO_ACTION`,suggest:`Add an .action() handler to the '${m.schema.name}' command`});return _.error(t.message),{exitCode:1,error:t}}await l(g?.plugins,{argv:f,command:v,meta:h,out:_});let c=a(v,f),y=g?.prompter??(g?.answers===void 0?void 0:o(g.answers)),b=await s(v,c,{...g?.stdinData===void 0?{}:{stdinData:g.stdinData},...g?.env===void 0?{}:{env:g.env},...g?.config===void 0?{}:{config:g.config},...y===void 0?{}:{prompter:y}}),x={args:b.args,flags:b.flags,deprecations:b.deprecations,command:v,meta:h,out:_};await u(g?.plugins,`afterResolve`,x);for(let e of b.deprecations)_.warn(p(e));return await u(g?.plugins,`beforeAction`,x),await d(m,n,b.flags,b.args,_,h),await u(g?.plugins,`afterAction`,x),{exitCode:r(_)??0,error:void 0}}catch(t){if(t instanceof e)return g?.jsonMode===!0?_.json({error:t.toJSON()}):(_.error(t.message),t.suggest!==void 0&&_.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 g?.jsonMode===!0?_.json({error:n.toJSON()}):_.error(n.message),{exitCode:1,error:n}}finally{_.stopActive(),n(_)}}async function l(e,t){if(e!==void 0)for(let n of e){let e=n.hooks.beforeParse;e!==void 0&&await e(t)}}async function u(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 d(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 f(e,t){return{exitCode:e.exitCode,stdout:t.stdout,stderr:t.stderr,activity:t.activity,error:e.error}}function p(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{f as buildRunResult,c as executeCommand};