@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/package.json CHANGED
@@ -1,8 +1,9 @@
1
1
  {
2
2
  "name": "@kjanat/dreamcli",
3
- "version": "2.2.1",
3
+ "version": "2.4.0",
4
4
  "description": "Schema-first, fully typed TypeScript CLI framework",
5
5
  "keywords": [
6
+ "dreamcli",
6
7
  "cli",
7
8
  "typescript",
8
9
  "framework",
@@ -75,13 +76,15 @@
75
76
  "bd": "bunx --bun tsdown",
76
77
  "build": "bunx --bun tsdown",
77
78
  "build:watch": "bunx --bun tsdown --watch",
78
- "ci": "bun typecheck && bun lint && bun run format:check && bun run meta-descriptions:check && bun run test && bun run docs:build && bun bd",
79
+ "ci": "run -pk typecheck lint format:check meta-descriptions:check test docs:build bd",
79
80
  "coverage": "vitest run --coverage",
80
81
  "dev": "bunx --bun tsdown --logLevel silent --watch & bunx --bun vitepress@next dev docs --host --port ${PORT:-5173} & wait",
81
82
  "docs:build": "bunx --bun vitepress@next build docs",
82
83
  "docs:dev": "bunx --bun vitepress@next dev docs",
83
84
  "docs:preview": "bunx --bun vitepress@next preview docs",
84
85
  "fmt": "dprint fmt",
86
+ "fmt:autofix": "dprint fmt --allow-no-files --excludes .github",
87
+ "fmt:update": "dprint config update --yes --recursive",
85
88
  "format": "dprint fmt",
86
89
  "format:check": "dprint check",
87
90
  "gh-project": "bun scripts/gh-project.ts",
@@ -92,45 +95,54 @@
92
95
  "gh-project:sync": "bun gh-project sync",
93
96
  "knip": "knip",
94
97
  "lint": "biome lint",
98
+ "lint:autofix": "biome check --skip-parse-errors --no-errors-on-unmatched --changed --write",
95
99
  "lint:fix": "biome lint --fix",
96
100
  "meta-descriptions": "bun --bun scripts/build-meta-descriptions.ts",
97
101
  "meta-descriptions:check": "bun --bun scripts/build-meta-descriptions.ts --check",
98
102
  "prepack": "bunx --bun tsdown --logLevel silent",
103
+ "publish:preview": "bunx pkg-pr-new publish --bun --comment=update --packageManager=bun,npm",
104
+ "schema:emit": "bun scripts/emit-definition-schema.ts",
99
105
  "test": "vitest run",
106
+ "test:bun": "bunx --bun vitest run",
107
+ "test:gh": "run --dir examples/gh test",
108
+ "test:node": "npx -y vitest run",
100
109
  "test:watch": "vitest",
101
110
  "typecheck": "tsgo --noEmit",
111
+ "typecheck:gh": "run --dir examples/gh typecheck",
102
112
  "typecheck:tsc": "tsc --noEmit",
103
- "upgrade": "bun update --latest && bun add -D vitepress@next"
113
+ "upgrade": "bun update --latest && bun add -D vitepress@next",
114
+ "version:check": "bun scripts/check-version-sync.ts"
104
115
  },
105
116
  "overrides": {
106
117
  "vitepress": "next"
107
118
  },
108
119
  "devDependencies": {
109
- "@arethetypeswrong/core": "^0.18.2",
110
- "@biomejs/biome": "^2.4.10",
120
+ "@arethetypeswrong/core": "^0.18.4",
121
+ "@biomejs/biome": "^2.5.1",
111
122
  "@iarna/toml": "^2.2.5",
112
- "@shikijs/transformers": "^4.0.2",
113
- "@shikijs/vitepress-twoslash": "^4.0.2",
114
- "@types/bun": "^1.3.12",
115
- "@types/deno": "^2.5.0",
123
+ "@shikijs/transformers": "^4.2.0",
124
+ "@shikijs/vitepress-twoslash": "^4.2.0",
125
+ "@types/bun": "^1.3.14",
126
+ "@types/deno": "^2.7.0",
116
127
  "@types/node": ">=22.0.0, <23.0.0",
117
- "@typescript/native-preview": "^7.0.0-dev.20260406.1",
118
- "@vitest/coverage-v8": "^4.1.2",
119
- "dprint": "^0.53.2",
128
+ "@typescript/native-preview": "^7.0.0-dev",
129
+ "@vitest/coverage-v8": "^4.1.9",
130
+ "dprint": "^0.54.0",
120
131
  "floating-vue": "^5.2.2",
121
- "knip": "^6.3.0",
122
- "mermaid": "^11.14.0",
123
- "publint": "^0.3.18",
124
- "tsdown": "^0.21.7",
125
- "typedoc": "^0.28.18",
126
- "typescript": "^6.0.2",
127
- "vite": "^8",
132
+ "knip": "^6.18.0",
133
+ "mermaid": "^11.15.0",
134
+ "publint": "^0.3.21",
135
+ "runner-run": "0.14.0",
136
+ "tsdown": "^0.22.3",
137
+ "typedoc": "^0.28.19",
138
+ "typescript": "^6.0.3",
139
+ "vite": "^8.1.0",
128
140
  "vitepress": "^2.0.0-alpha.17",
129
- "vitest": "^4.1.2",
130
- "wrangler": "^4.80.0",
131
- "yaml": "^2.8.3"
141
+ "vitest": "^4.1.9",
142
+ "wrangler": "^4.104.0",
143
+ "yaml": "^2.9.0"
132
144
  },
133
- "packageManager": "bun@1.3.12",
145
+ "packageManager": "bun@1.3.14",
134
146
  "engines": {
135
147
  "bun": ">=1.3",
136
148
  "deno": ">=2.6.0",
@@ -155,8 +167,8 @@
155
167
  "provenance": true
156
168
  },
157
169
  "catalog": {
158
- "@types/bun": "^1.3.12",
170
+ "@types/bun": "^1.3.14",
159
171
  "@types/node": ">=22.0.0, <23.0.0",
160
- "typescript": "^6.0.2"
172
+ "typescript": "^6.0.3"
161
173
  }
162
174
  }
@@ -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 !== undefined && !token.startsWith('-')) {
96
- cmdIdx = i;
97
- break;
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(remaining, matched.subcommands, currentPath);
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 };
@@ -18,7 +18,12 @@ import { buildRunResult, executeCommand } from '#internals/core/execution/index.
18
18
  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
- import { createCaptureOutput, createOutput } from '#internals/core/output/index.ts';
21
+ import {
22
+ clearRequestedExitCode,
23
+ createCaptureOutput,
24
+ createOutput,
25
+ } from '#internals/core/output/index.ts';
26
+ import { includesBeforeSeparator } from '#internals/core/parse/index.ts';
22
27
  import type { ArgBuilder, ArgConfig } from '#internals/core/schema/arg.ts';
23
28
  import { arg } from '#internals/core/schema/arg.ts';
24
29
  import type {
@@ -35,6 +40,7 @@ import type { RunOptions, RunResult } from '#internals/core/schema/run.ts';
35
40
  import { runCommand } from '#internals/core/testkit/index.ts';
36
41
  import type { RuntimeAdapter } from '#internals/runtime/adapter.ts';
37
42
  import { createAdapter } from '#internals/runtime/auto.ts';
43
+ import { BACKSLASH, SLASH, stripTrailing } from '#internals/strings.ts';
38
44
  import type { HelpLinks } from './help-links.ts';
39
45
  import { deriveHelpLinks } from './help-links.ts';
40
46
  import type { OutputPolicy } from './planner.ts';
@@ -805,7 +811,9 @@ class CLIBuilder {
805
811
  */
806
812
  async execute(argv: readonly string[], options?: CLIRunOptions): Promise<RunResult> {
807
813
  // -- Detect global --json mode before building output ---------------------
808
- const hasJsonFlag = argv.includes('--json');
814
+ // Only a `--json` before the `--` separator toggles JSON mode; a literal
815
+ // `--json` positional (after `--`) must reach the command unchanged (#28).
816
+ const hasJsonFlag = includesBeforeSeparator(argv, '--json');
809
817
  const jsonMode = hasJsonFlag || options?.jsonMode === true;
810
818
 
811
819
  const captureOptions = {
@@ -823,6 +831,7 @@ class CLIBuilder {
823
831
  Object.keys(captureOptions).length > 0 ? captureOptions : undefined,
824
832
  );
825
833
  }
834
+ clearRequestedExitCode(out);
826
835
 
827
836
  // Resolve help options — default binName to CLI program name,
828
837
  // hyperlinks to TTY detection (escapes never leak into piped output)
@@ -982,7 +991,7 @@ const RUNTIME_BINARIES = new Set(['bun', 'deno', 'node', 'tsx']);
982
991
  * @internal
983
992
  */
984
993
  function basename(input: string): string | undefined {
985
- const trimmed = input.replace(/[\\/]+$/g, '');
994
+ const trimmed = stripTrailing(input, [SLASH, BACKSLASH]);
986
995
  if (trimmed.length === 0) return undefined;
987
996
  const slashIdx = Math.max(trimmed.lastIndexOf('/'), trimmed.lastIndexOf('\\'));
988
997
  const name = slashIdx >= 0 ? trimmed.slice(slashIdx + 1) : trimmed;
@@ -1194,6 +1203,7 @@ function cli(nameOrOptions: string | CLIOptions): CLIBuilder {
1194
1203
 
1195
1204
  // --- Exports
1196
1205
 
1206
+ export type { HelpLinks } from './help-links.ts';
1197
1207
  export type {
1198
1208
  BeforeParseParams,
1199
1209
  CLIPlugin,
@@ -1201,6 +1211,5 @@ export type {
1201
1211
  PluginCommandContext,
1202
1212
  ResolvedCommandParams,
1203
1213
  } from './plugin.ts';
1204
- export type { HelpLinks } from './help-links.ts';
1205
1214
  export type { CLIOptions, CLIRunOptions, CLISchema, ConfigSettings, PackageJsonSettings };
1206
1215
  export { CLIBuilder, cli, formatRootHelp, plugin };
@@ -13,6 +13,11 @@
13
13
  import { CLIError, ParseError } from '#internals/core/errors/index.ts';
14
14
  import type { HelpOptions } from '#internals/core/help/index.ts';
15
15
  import type { OutputPolicy } from '#internals/core/output/contracts.ts';
16
+ import {
17
+ buildFlagLookup,
18
+ flagExpectsValue,
19
+ includesBeforeSeparator,
20
+ } from '#internals/core/parse/index.ts';
16
21
  import type { CommandMeta, CommandSchema, ErasedCommand } from '#internals/core/schema/command.ts';
17
22
  import { dispatch, findClosestCommand } from './dispatch.ts';
18
23
  import type { CLIPlugin } from './plugin.ts';
@@ -248,6 +253,44 @@ function buildPlannerMatchOutcome(
248
253
  };
249
254
  }
250
255
 
256
+ function canDelegateUnknownRootToDefault(command: ErasedCommand, input: string): boolean {
257
+ return input === '' || command.schema.args.length > 0;
258
+ }
259
+
260
+ function findUnknownFlagBeforePositional(
261
+ argv: readonly string[],
262
+ flags: CommandSchema['flags'],
263
+ ): string | undefined {
264
+ const lookup = buildFlagLookup(flags);
265
+
266
+ for (let index = 0; index < argv.length; index++) {
267
+ const token = argv[index];
268
+ if (token === undefined || token === '--') return undefined;
269
+ if (token === '-' || !token.startsWith('-')) return undefined;
270
+
271
+ if (token.startsWith('--')) {
272
+ const equalsIndex = token.indexOf('=');
273
+ const name = token.slice(2, equalsIndex === -1 ? undefined : equalsIndex);
274
+ const entry = lookup.get(name);
275
+ if (entry === undefined) return equalsIndex === -1 ? token : `--${name}`;
276
+ if (equalsIndex === -1 && flagExpectsValue(entry[1])) index++;
277
+ continue;
278
+ }
279
+
280
+ const chars = token.slice(1);
281
+ for (let charIndex = 0; charIndex < chars.length; charIndex++) {
282
+ const char = chars.charAt(charIndex);
283
+ const entry = lookup.get(char);
284
+ if (entry === undefined) return `-${char}`;
285
+ if (!flagExpectsValue(entry[1])) continue;
286
+ if (charIndex === chars.length - 1) index++;
287
+ break;
288
+ }
289
+ }
290
+
291
+ return undefined;
292
+ }
293
+
251
294
  /**
252
295
  * Decide what to do with an argv invocation before any command executes.
253
296
  *
@@ -257,13 +300,20 @@ function buildPlannerMatchOutcome(
257
300
  * @internal
258
301
  */
259
302
  function planInvocation(options: PlanInvocationOptions): InvocationPlan {
260
- const filteredArgv = options.argv.includes('--json')
261
- ? options.argv.filter((arg) => arg !== '--json')
262
- : options.argv;
303
+ // `--json` is a root-level flag, not part of any command schema, so it is
304
+ // stripped before dispatch/parse — but only before the `--` separator, so a
305
+ // literal `--json` positional (after `--`) survives and reaches the command
306
+ // (#28). The `--json` *output mode* is detected separately in `.execute()`.
307
+ const separatorIndex = options.argv.indexOf('--');
308
+ const head = separatorIndex === -1 ? options.argv : options.argv.slice(0, separatorIndex);
309
+ const tail = separatorIndex === -1 ? [] : options.argv.slice(separatorIndex);
310
+ const filteredHead = head.includes('--json') ? head.filter((arg) => arg !== '--json') : head;
311
+ const filteredArgv = separatorIndex === -1 ? filteredHead : [...filteredHead, ...tail];
263
312
 
264
313
  if (
265
314
  options.schema.version !== undefined &&
266
- (filteredArgv.includes('--version') || filteredArgv.includes('-V'))
315
+ (includesBeforeSeparator(options.argv, '--version') ||
316
+ includesBeforeSeparator(options.argv, '-V'))
267
317
  ) {
268
318
  return {
269
319
  kind: 'root-version',
@@ -316,15 +366,25 @@ function planInvocation(options: PlanInvocationOptions): InvocationPlan {
316
366
  };
317
367
  }
318
368
 
319
- const result = dispatch(filteredArgv, buildRootCommandMap(options.schema.commands));
320
369
  const defaultCommand = options.schema.defaultCommand;
370
+ // At the root, a default command's flags govern value-flag arity so a
371
+ // space-separated value (`mycli --region eu`) is not misread as a command
372
+ // name and stolen from the default-command fallback (see #25).
373
+ const rootValueFlags =
374
+ defaultCommand !== undefined ? buildFlagLookup(defaultCommand.schema.flags) : undefined;
375
+ const result = dispatch(
376
+ filteredArgv,
377
+ buildRootCommandMap(options.schema.commands),
378
+ [],
379
+ rootValueFlags,
380
+ );
321
381
 
322
382
  switch (result.kind) {
323
383
  case 'unknown': {
324
384
  if (defaultCommand !== undefined && result.parentPath.length === 0) {
325
385
  const suggestion =
326
386
  result.input !== '' ? findClosestCommand(result.input, result.candidates) : undefined;
327
- if (suggestion === undefined) {
387
+ if (suggestion === undefined && canDelegateUnknownRootToDefault(defaultCommand, result.input)) {
328
388
  return buildPlannerMatchOutcome(
329
389
  options.schema,
330
390
  defaultCommand,
@@ -334,6 +394,20 @@ function planInvocation(options: PlanInvocationOptions): InvocationPlan {
334
394
  options.output,
335
395
  );
336
396
  }
397
+
398
+ const unknownFlag = findUnknownFlagBeforePositional(
399
+ filteredArgv,
400
+ defaultCommand.schema.flags,
401
+ );
402
+ if (unknownFlag !== undefined) {
403
+ return {
404
+ kind: 'dispatch-error',
405
+ error: new ParseError(`Unknown flag ${unknownFlag}`, {
406
+ code: 'UNKNOWN_FLAG',
407
+ suggest: `Run '${options.schema.name} --help' for available commands`,
408
+ }),
409
+ };
410
+ }
337
411
  }
338
412
 
339
413
  if (result.input === '') {
@@ -9,6 +9,7 @@
9
9
  */
10
10
 
11
11
  import type { RuntimeAdapter } from '#internals/runtime/adapter.ts';
12
+ import { SLASH, stripTrailing } from '#internals/strings.ts';
12
13
 
13
14
  // --- Narrowing helpers
14
15
 
@@ -297,13 +298,13 @@ function packageRepositoryUrl(pkg: PackageJsonData): string | undefined {
297
298
  // scp-style locator: `git@github.com:u/r.git`
298
299
  const scp = /^git@([^:/]+):(.+)$/.exec(locator);
299
300
  if (scp !== null && scp[1] !== undefined && scp[2] !== undefined) {
300
- return `https://${scp[1]}/${stripGitSuffix(scp[2].replace(/\/+$/, ''))}`;
301
+ return `https://${scp[1]}/${stripGitSuffix(stripTrailing(scp[2], [SLASH]))}`;
301
302
  }
302
303
 
303
304
  if (!/^(?:https?|git|ssh):\/\//.test(locator)) return undefined;
304
305
  try {
305
306
  const url = new URL(locator);
306
- const path = stripGitSuffix(url.pathname.replace(/\/+$/, ''));
307
+ const path = stripGitSuffix(stripTrailing(url.pathname, [SLASH]));
307
308
  return `https://${url.hostname}${path}`;
308
309
  } catch {
309
310
  return undefined;
@@ -16,7 +16,11 @@ 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 {
20
+ clearRequestedExitCode,
21
+ getRequestedExitCode,
22
+ } from '#internals/core/output/index.ts';
23
+ import { includesBeforeSeparator, parse } from '#internals/core/parse/index.ts';
20
24
  import { createTestPrompter } from '#internals/core/prompt/index.ts';
21
25
  import type { DeprecationWarning, ResolveOptions } from '#internals/core/resolve/index.ts';
22
26
  import { resolve } from '#internals/core/resolve/index.ts';
@@ -67,6 +71,7 @@ interface CommandExecutionResult {
67
71
  */
68
72
  async function executeCommand(request: CommandExecutionRequest): Promise<CommandExecutionResult> {
69
73
  const { argv, command, meta, options, out, schema } = request;
74
+ clearRequestedExitCode(out);
70
75
 
71
76
  try {
72
77
  if (includesBeforeSeparator(argv, '--help') || includesBeforeSeparator(argv, '-h')) {
@@ -123,7 +128,7 @@ async function executeCommand(request: CommandExecutionRequest): Promise<Command
123
128
  await executeWithExecutionSteps(command, handler, resolved.flags, resolved.args, out, meta);
124
129
  await runResolvedHooks(options?.plugins, 'afterAction', resolvedParams);
125
130
 
126
- return { exitCode: 0, error: undefined };
131
+ return { exitCode: getRequestedExitCode(out) ?? 0, error: undefined };
127
132
  } catch (error: unknown) {
128
133
  if (error instanceof CLIError) {
129
134
  if (options?.jsonMode === true) {
@@ -150,6 +155,7 @@ async function executeCommand(request: CommandExecutionRequest): Promise<Command
150
155
  return { exitCode: 1, error: wrapped };
151
156
  } finally {
152
157
  out.stopActive();
158
+ clearRequestedExitCode(out);
153
159
  }
154
160
  }
155
161
 
@@ -258,13 +264,5 @@ function formatDeprecation(deprecation: DeprecationWarning): string {
258
264
  : `Warning: ${entity} is deprecated`;
259
265
  }
260
266
 
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
267
  export type { CommandExecutionRequest, CommandExecutionResult };
270
268
  export { buildRunResult, executeCommand };
@@ -10,7 +10,6 @@
10
10
 
11
11
  import { formatDisplayValue } from '#internals/core/output/display-value.ts';
12
12
  import { getFlagAliasNames } from '#internals/core/schema/flag.ts';
13
- import { padEnd, wrapText } from './ansi.ts';
14
13
  import type {
15
14
  ArgSchema,
16
15
  CommandArgEntry,
@@ -18,6 +17,7 @@ import type {
18
17
  CommandSchema,
19
18
  FlagSchema,
20
19
  } from '#internals/core/schema/index.ts';
20
+ import { padEnd, wrapText } from './ansi.ts';
21
21
 
22
22
  // --- Configuration
23
23
 
@@ -511,6 +511,6 @@ function formatExamplesSection(examples: readonly CommandExample[]): string {
511
511
 
512
512
  // --- Exports
513
513
 
514
- export type { HelpOptions };
515
514
  export { osc8, visibleWidth } from './ansi.ts';
515
+ export type { HelpOptions };
516
516
  export { formatHelp, formatHelpSections };
@@ -115,6 +115,27 @@ interface ResolvedOutputOptions {
115
115
  */
116
116
  const noopWrite: WriteFn = () => {};
117
117
 
118
+ const requestedExitCodes = new WeakMap<Out, number>();
119
+
120
+ function validateExitCode(code: number): number {
121
+ if (!Number.isInteger(code) || code < 0 || code > 255) {
122
+ throw new RangeError('Exit code must be an integer from 0 to 255');
123
+ }
124
+ return code;
125
+ }
126
+
127
+ function setRequestedExitCode(out: Out, code: number): void {
128
+ requestedExitCodes.set(out, validateExitCode(code));
129
+ }
130
+
131
+ function getRequestedExitCode(out: Out): number | undefined {
132
+ return requestedExitCodes.get(out);
133
+ }
134
+
135
+ function clearRequestedExitCode(out: Out): void {
136
+ requestedExitCodes.delete(out);
137
+ }
138
+
118
139
  /** Merge user-supplied options with defaults. */
119
140
  function resolveOptions(options?: OutputOptions): ResolvedOutputOptions {
120
141
  return {
@@ -199,6 +220,11 @@ class OutputChannel implements Out {
199
220
  writeLine(this.options.stderr, message);
200
221
  }
201
222
 
223
+ /** Request a successful-process exit code without writing error output. */
224
+ setExitCode(code: number): void {
225
+ setRequestedExitCode(this, code);
226
+ }
227
+
202
228
  /**
203
229
  * Emit a structured JSON value to stdout.
204
230
  *
@@ -656,13 +682,16 @@ export {
656
682
  CaptureOutputChannel,
657
683
  CaptureProgressHandle,
658
684
  CaptureSpinnerHandle,
685
+ clearRequestedExitCode,
659
686
  createCaptureOutput,
660
687
  createOutput,
688
+ getRequestedExitCode,
661
689
  noopProgressHandle,
662
690
  noopSpinnerHandle,
663
691
  OutputChannel,
664
692
  StaticProgressHandle,
665
693
  StaticSpinnerHandle,
694
+ setRequestedExitCode,
666
695
  TTYProgressHandle,
667
696
  TTYSpinnerHandle,
668
697
  writeLine,
@@ -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
  /**
@@ -425,7 +445,7 @@ function parseLongFlag(
425
445
 
426
446
  // --flag value (next token is the value)
427
447
  const nextToken = tokens[startIdx + 1];
428
- if (!nextToken || nextToken.kind !== 'positional') {
448
+ if (nextToken?.kind !== 'positional') {
429
449
  throw new ParseError(`Flag --${token.name} requires a value`, {
430
450
  code: 'MISSING_VALUE',
431
451
  details: { flag: canonicalName, input: token.name, kind: flagSchema.kind },
@@ -485,7 +505,7 @@ function parseShortFlags(
485
505
 
486
506
  // Last char in the group — consume next token as value
487
507
  const nextToken = tokens[nextIdx];
488
- if (!nextToken || nextToken.kind !== 'positional') {
508
+ if (nextToken?.kind !== 'positional') {
489
509
  throw new ParseError(`Flag -${ch} requires a value`, {
490
510
  code: 'MISSING_VALUE',
491
511
  details: { flag: canonicalName, input: ch, kind: flagSchema.kind },
@@ -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 };
@@ -152,6 +152,14 @@ interface Out {
152
152
  warn(message: string): void;
153
153
  /** Error to stderr. */
154
154
  error(message: string): void;
155
+ /**
156
+ * Request a process exit code without emitting error-shaped output.
157
+ *
158
+ * Use this for check/status commands that should print normal output but
159
+ * still signal a non-zero status to scripts. This does not stop execution;
160
+ * later calls overwrite earlier calls, and thrown errors still win.
161
+ */
162
+ setExitCode(code: number): void;
155
163
  /**
156
164
  * Emit a structured JSON value to stdout.
157
165
  *