@kjanat/dreamcli 3.0.0-rc.6 → 3.0.0-rc.8

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 (94) hide show
  1. package/CHANGELOG.md +94 -1
  2. package/dist/core/cli/dispatch.d.mts +6 -5
  3. package/dist/core/cli/dispatch.mjs +7 -5
  4. package/dist/core/cli/help-links.d.mts +0 -1
  5. package/dist/core/cli/index.d.mts +27 -2
  6. package/dist/core/cli/index.mjs +28 -14
  7. package/dist/core/cli/planner.d.mts +3 -1
  8. package/dist/core/cli/planner.mjs +12 -12
  9. package/dist/core/cli/plugin.d.mts +1 -1
  10. package/dist/core/cli/propagate.d.mts +1 -1
  11. package/dist/core/cli/root-help.d.mts +0 -1
  12. package/dist/core/cli/root-help.mjs +38 -21
  13. package/dist/core/cli/root-surface.d.mts +0 -1
  14. package/dist/core/cli/runtime-preflight.d.mts +12 -2
  15. package/dist/core/cli/runtime-preflight.mjs +5 -4
  16. package/dist/core/completion/index.d.mts +0 -1
  17. package/dist/core/completion/index.mjs +1 -1
  18. package/dist/core/completion/shells/bash.d.mts +0 -1
  19. package/dist/core/completion/shells/bash.mjs +8 -4
  20. package/dist/core/completion/shells/fish.d.mts +0 -1
  21. package/dist/core/completion/shells/fish.mjs +6 -3
  22. package/dist/core/completion/shells/powershell.d.mts +0 -1
  23. package/dist/core/completion/shells/powershell.mjs +10 -5
  24. package/dist/core/completion/shells/shared.d.mts +13 -2
  25. package/dist/core/completion/shells/shared.mjs +24 -2
  26. package/dist/core/completion/shells/zsh.d.mts +0 -1
  27. package/dist/core/completion/shells/zsh.mjs +11 -4
  28. package/dist/core/config/index.d.mts +2 -3
  29. package/dist/core/config/index.mjs +2 -2
  30. package/dist/core/config/package-json.d.mts +27 -4
  31. package/dist/core/config/package-json.mjs +20 -19
  32. package/dist/core/errors/index.d.mts +1 -1
  33. package/dist/core/execution/index.d.mts +0 -1
  34. package/dist/core/execution/index.mjs +8 -4
  35. package/dist/core/help/ansi.mjs +3 -2
  36. package/dist/core/help/index.d.mts +22 -3
  37. package/dist/core/help/index.mjs +65 -53
  38. package/dist/core/help/theme.d.mts +68 -0
  39. package/dist/core/help/theme.mjs +46 -0
  40. package/dist/core/json-schema/index.d.mts +1 -1
  41. package/dist/core/json-schema/index.mjs +39 -8
  42. package/dist/core/json-schema/meta-descriptions.generated.d.mts +22 -5
  43. package/dist/core/json-schema/meta-descriptions.generated.mjs +14 -5
  44. package/dist/core/output/activity.d.mts +0 -1
  45. package/dist/core/output/contracts.d.mts +0 -1
  46. package/dist/core/output/contracts.mjs +1 -1
  47. package/dist/core/output/index.d.mts +0 -1
  48. package/dist/core/output/index.mjs +1 -1
  49. package/dist/core/output/renderers.d.mts +0 -1
  50. package/dist/core/parse/index.d.mts +40 -7
  51. package/dist/core/parse/index.mjs +209 -40
  52. package/dist/core/prompt/index.d.mts +1 -0
  53. package/dist/core/resolve/args.d.mts +1 -1
  54. package/dist/core/resolve/coerce.d.mts +1 -1
  55. package/dist/core/resolve/coerce.mjs +71 -14
  56. package/dist/core/resolve/contracts.d.mts +7 -2
  57. package/dist/core/resolve/errors.d.mts +0 -1
  58. package/dist/core/resolve/flags.d.mts +7 -2
  59. package/dist/core/resolve/flags.mjs +61 -6
  60. package/dist/core/resolve/index.d.mts +2 -2
  61. package/dist/core/resolve/index.mjs +1 -1
  62. package/dist/core/resolve/property.d.mts +3 -0
  63. package/dist/core/resolve/property.mjs +11 -3
  64. package/dist/core/schema/activity.d.mts +31 -11
  65. package/dist/core/schema/arg.d.mts +1 -2
  66. package/dist/core/schema/command.d.mts +8 -6
  67. package/dist/core/schema/command.mjs +26 -12
  68. package/dist/core/schema/flag.d.mts +439 -10
  69. package/dist/core/schema/flag.mjs +255 -3
  70. package/dist/core/schema/index.d.mts +4 -2
  71. package/dist/core/schema/middleware.d.mts +4 -3
  72. package/dist/core/schema/prompt.d.mts +5 -2
  73. package/dist/core/schema/run.d.mts +20 -1
  74. package/dist/core/schema/string-constraints.d.mts +97 -0
  75. package/dist/core/schema/string-constraints.mjs +69 -0
  76. package/dist/core/schema/value-parsers.d.mts +78 -0
  77. package/dist/core/schema/value-parsers.mjs +142 -0
  78. package/dist/core/schema-dsl/to-json-schema.d.mts +0 -1
  79. package/dist/core/testkit/index.d.mts +0 -31
  80. package/dist/core/testkit/index.mjs +1 -1
  81. package/dist/index.d.mts +8 -4
  82. package/dist/index.mjs +7 -7
  83. package/dist/runtime/adapter.d.mts +22 -1
  84. package/dist/runtime/adapter.mjs +3 -0
  85. package/dist/runtime/auto.d.mts +0 -1
  86. package/dist/runtime/deno.d.mts +15 -5
  87. package/dist/runtime/deno.mjs +9 -0
  88. package/dist/runtime/node.d.mts +2 -2
  89. package/dist/runtime/node.mjs +10 -0
  90. package/dist/runtime.d.mts +1 -0
  91. package/dist/testkit.d.mts +1 -0
  92. package/dist/version.mjs +2 -2
  93. package/dreamcli.schema.json +35 -6
  94. package/package.json +12 -13
@@ -1,5 +1,15 @@
1
+ import { CLIError } from "../errors/index.mjs";
1
2
  import { stripTrailing } from "../../strings.mjs";
2
3
  //#region src/core/config/package-json.ts
4
+ /**
5
+ * Package.json auto-discovery via directory walk-up.
6
+ *
7
+ * Walks up from `adapter.cwd` to find the nearest `package.json`, parses
8
+ * it, and extracts metadata (name, version, description, bin). All I/O
9
+ * flows through the adapter — fully testable with virtual filesystems.
10
+ *
11
+ * @module dreamcli/core/config/package-json
12
+ */
3
13
  /** Type guard: narrows `unknown` to a plain (non-array) object. */
4
14
  function isPlainObject(value) {
5
15
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -302,25 +312,16 @@ const SHORTHAND_HOSTS = {
302
312
  function stripGitSuffix(path) {
303
313
  return path.endsWith(".git") ? path.slice(0, -4) : path;
304
314
  }
305
- /**
306
- * Resolve a package's `repository` field to a browsable `https://` URL.
307
- *
308
- * Handles the locator formats npm accepts:
309
- * - object form: `{ "type": "git", "url": "git+https://github.com/u/r.git" }`
310
- * - `https`/`git`/`ssh` URLs (`git+` prefix and `.git` suffix stripped)
311
- * - scp-style locators: `git@github.com:u/r.git`
312
- * - shorthands: `github:u/r`, `gitlab:u/r`, `bitbucket:u/r`, and bare `u/r`
313
- * (GitHub, per npm convention)
314
- *
315
- * Returns `undefined` when the field is absent or unrecognised.
316
- *
317
- * @example
318
- * ```ts
319
- * packageRepositoryUrl({ repository: 'git+https://github.com/u/r.git' });
320
- * // 'https://github.com/u/r'
321
- * ```
322
- */
323
- function packageRepositoryUrl(pkg) {
315
+ function packageRepositoryUrl(pkg, options) {
316
+ const url = resolveRepositoryUrl(pkg);
317
+ if (url === void 0 && options?.require === true) throw new CLIError(pkg.repository === void 0 ? "package.json has no 'repository' field" : `package.json 'repository' is not a recognisable locator: ${JSON.stringify(pkg.repository)}`, {
318
+ code: "INVALID_REPOSITORY",
319
+ suggest: "Set 'repository' to a supported locator (e.g. 'github:user/repo' or 'git+https://github.com/user/repo.git'), or drop { require: true } and handle undefined"
320
+ });
321
+ return url;
322
+ }
323
+ /** Locator normalization behind {@link packageRepositoryUrl}. @internal */
324
+ function resolveRepositoryUrl(pkg) {
324
325
  const raw = typeof pkg.repository === "string" ? pkg.repository : pkg.repository?.url;
325
326
  if (raw === void 0) return void 0;
326
327
  let locator = raw.trim();
@@ -9,7 +9,7 @@
9
9
  * @module dreamcli/core/errors
10
10
  */
11
11
  /** Codes emitted during argv parsing. */
12
- type ParseErrorCode = 'UNKNOWN_FLAG' | 'UNKNOWN_COMMAND' | 'MISSING_VALUE' | 'INVALID_VALUE' | 'INVALID_SCHEMA' | 'UNEXPECTED_POSITIONAL';
12
+ type ParseErrorCode = 'UNKNOWN_FLAG' | 'UNKNOWN_COMMAND' | 'MISSING_VALUE' | 'INVALID_VALUE' | 'INVALID_SCHEMA' | 'DUPLICATE_FLAG' | 'UNEXPECTED_POSITIONAL';
13
13
  /** Codes emitted during post-parse validation / resolution. */
14
14
  type ValidationErrorCode = 'REQUIRED_FLAG' | 'REQUIRED_ARG' | 'INVALID_ENUM' | 'TYPE_MISMATCH' | 'CONSTRAINT_VIOLATED';
15
15
  /** Any framework error code (extensible via `string & {}`). */
@@ -2,7 +2,6 @@ import { CapturedOutput } from "../output/index.mjs";
2
2
  import { CLIError } from "../errors/index.mjs";
3
3
  import { RunOptions, RunResult } from "../schema/run.mjs";
4
4
  import { CommandMeta, CommandSchema, Out, RunnableCommand } from "../schema/command.mjs";
5
-
6
5
  //#region src/core/execution/index.d.ts
7
6
  /**
8
7
  * Explicit executor input for a single command invocation.
@@ -1,7 +1,7 @@
1
1
  import { CLIError } from "../errors/index.mjs";
2
+ import { includesBeforeSeparator, parse } from "../parse/index.mjs";
2
3
  import { formatHelp } from "../help/index.mjs";
3
4
  import { clearRequestedExitCode, getRequestedExitCode } from "../output/index.mjs";
4
- import { includesBeforeSeparator, parse } from "../parse/index.mjs";
5
5
  import { createTestPrompter } from "../prompt/index.mjs";
6
6
  import { resolve } from "../resolve/index.mjs";
7
7
  //#region src/core/execution/index.ts
@@ -17,7 +17,10 @@ async function executeCommand(request) {
17
17
  clearRequestedExitCode(out);
18
18
  try {
19
19
  if (includesBeforeSeparator(argv, "--help") || includesBeforeSeparator(argv, "-h")) {
20
- const helpText = formatHelp(schema, options?.help);
20
+ const helpText = formatHelp(schema, options?.help?.colors !== void 0 ? options.help : {
21
+ ...options?.help,
22
+ colors: out.color
23
+ });
21
24
  out.log(helpText);
22
25
  return {
23
26
  exitCode: 0,
@@ -42,13 +45,14 @@ async function executeCommand(request) {
42
45
  meta,
43
46
  out
44
47
  });
45
- const parsed = parse(schema, argv);
48
+ const parsed = parse(schema, argv, options?.flags);
46
49
  const effectivePrompter = options?.prompter ?? (options?.answers !== void 0 ? createTestPrompter(options.answers) : void 0);
47
50
  const resolved = await resolve(schema, parsed, {
48
51
  ...options?.stdinData !== void 0 ? { stdinData: options.stdinData } : {},
49
52
  ...options?.env !== void 0 ? { env: options.env } : {},
50
53
  ...options?.config !== void 0 ? { config: options.config } : {},
51
- ...effectivePrompter !== void 0 ? { prompter: effectivePrompter } : {}
54
+ ...effectivePrompter !== void 0 ? { prompter: effectivePrompter } : {},
55
+ ...options?.stat !== void 0 ? { stat: options.stat } : {}
52
56
  });
53
57
  const resolvedParams = {
54
58
  args: resolved.args,
@@ -67,7 +67,8 @@ const BEL = "\x07";
67
67
  * ```
68
68
  */
69
69
  function osc8(url, text) {
70
- return `${OSC}8;;${url instanceof URL ? url.href : url}${BEL}${text}${OSC}8;;${BEL}`;
70
+ const href = url instanceof URL ? url.href : url;
71
+ return `${OSC}8;;${href}${BEL}${text}${OSC}8;;${BEL}`;
71
72
  }
72
73
  /**
73
74
  * Pad `text` to `length` visible columns with trailing spaces.
@@ -119,4 +120,4 @@ function wrapText(text, width, indent) {
119
120
  return lines.map((line, i) => i === 0 ? line : `${pad}${line}`).join("\n");
120
121
  }
121
122
  //#endregion
122
- export { osc8, padEnd, visibleWidth, wrapText };
123
+ export { osc8, padEnd, stripAnsi, visibleWidth, wrapText };
@@ -1,6 +1,8 @@
1
+ import { HelpTheme, HelpThemeFactory } from "./theme.mjs";
1
2
  import { osc8, visibleWidth } from "./ansi.mjs";
2
3
  import { CommandSchema } from "../schema/command.mjs";
3
-
4
+ import "../schema/index.mjs";
5
+ import { Colors } from "ansispeck";
4
6
  //#region src/core/help/index.d.ts
5
7
  /** Options for customising help output. */
6
8
  interface HelpOptions {
@@ -42,6 +44,23 @@ interface HelpOptions {
42
44
  readonly footer?: boolean;
43
45
  /** @internal Whether this usage line is being rendered as merged root/default help. */
44
46
  readonly isDefaultHelp?: boolean;
47
+ /**
48
+ * Gated ANSI palette used to style help output. Identity formatters mean
49
+ * plain text. `CLIBuilder.execute()`/`.run()` thread the output channel's
50
+ * `out.color` here automatically, so styling follows the same policy as
51
+ * handler output (TTY + color support, no `--json`, `NO_COLOR` honored).
52
+ *
53
+ * @defaultValue `undefined` (plain text)
54
+ */
55
+ readonly colors?: Colors;
56
+ /**
57
+ * Theme overrides merged over the built-in help theme. Receives the gated
58
+ * palette; never invoked when color is off, so overrides cannot leak
59
+ * escapes into piped output.
60
+ *
61
+ * @defaultValue `undefined` (built-in theme)
62
+ */
63
+ readonly theme?: HelpThemeFactory;
45
64
  }
46
65
  /** Formatted flag entry for the flags table. @internal */
47
66
  interface FlagEntry {
@@ -90,7 +109,7 @@ declare function formatHelp(schema: CommandSchema, options?: HelpOptions): strin
90
109
  * block (built-in flags), so column alignment and description wrapping stay
91
110
  * identical across both. Returns `''` when there are no entries.
92
111
  *
93
- * @param title - Section heading (e.g. `'Flags:'`, `'Global options:'`).
112
+ * @param title - Section heading (e.g. `'Flags:'`, `'Global options:'`), pre-styled by the caller.
94
113
  * @param entries - Formatted left/description rows.
95
114
  * @param width - Terminal width for description wrapping.
96
115
  * @returns Multi-line block string, or `''` when `entries` is empty.
@@ -98,4 +117,4 @@ declare function formatHelp(schema: CommandSchema, options?: HelpOptions): strin
98
117
  */
99
118
  declare function formatFlagEntriesBlock(title: string, entries: readonly FlagEntry[], width: number): string;
100
119
  //#endregion
101
- export { type FlagEntry, type HelpOptions, formatFlagEntriesBlock, formatHelp, formatHelpSections, osc8, visibleWidth };
120
+ export { type FlagEntry, type HelpOptions, type HelpTheme, type HelpThemeFactory, formatFlagEntriesBlock, formatHelp, formatHelpSections, osc8, visibleWidth };
@@ -1,16 +1,8 @@
1
1
  import { getFlagAliasNames } from "../schema/flag.mjs";
2
2
  import { formatDisplayValue } from "../output/display-value.mjs";
3
- import { padEnd, wrapText } from "./ansi.mjs";
3
+ import { osc8, padEnd, visibleWidth, wrapText } from "./ansi.mjs";
4
+ import { resolveHelpTheme } from "./theme.mjs";
4
5
  //#region src/core/help/index.ts
5
- /**
6
- * Auto-generated help text from command schemas.
7
- *
8
- * Renders usage line, description, positional args, flags table, and
9
- * examples from a {@linkcode CommandSchema}. Designed for TTY output with
10
- * configurable width.
11
- *
12
- * @module dreamcli/core/help
13
- */
14
6
  const DEFAULT_WIDTH = 80;
15
7
  /**
16
8
  * Apply defaults to optional {@link HelpOptions}.
@@ -22,7 +14,8 @@ function resolveOptions(options) {
22
14
  return {
23
15
  width: options?.width ?? DEFAULT_WIDTH,
24
16
  binName: options?.binName,
25
- isDefaultHelp: options?.isDefaultHelp ?? false
17
+ isDefaultHelp: options?.isDefaultHelp ?? false,
18
+ theme: resolveHelpTheme(options?.colors, options?.theme)
26
19
  };
27
20
  }
28
21
  /**
@@ -45,59 +38,71 @@ function formatHelpDefaultValue(value) {
45
38
  *
46
39
  * @param name - Long flag name (without `--` prefix).
47
40
  * @param schema - The {@link FlagSchema} describing the flag.
41
+ * @param theme - Theme applied to the flag forms and value hint.
48
42
  * @returns Formatted left-column string for the flags table.
49
43
  */
50
- function formatFlagLeft(name, schema) {
44
+ function formatFlagLeft(name, schema, theme) {
51
45
  const visibleShortAliases = getFlagAliasNames(schema, { kind: "short" });
52
46
  const visibleLongAliases = getFlagAliasNames(schema, { kind: "long" });
47
+ const negation = schema.negation !== void 0 && !schema.negation.hidden ? schema.negation : void 0;
48
+ const canonicalForm = negation !== void 0 && negation.alias === void 0 ? `--[no-]${name}` : `--${name}`;
53
49
  const forms = [
54
50
  ...visibleShortAliases.map((alias) => `-${alias}`),
55
- `--${name}`,
56
- ...visibleLongAliases.map((alias) => `--${alias}`)
51
+ canonicalForm,
52
+ ...visibleLongAliases.map((alias) => `--${alias}`),
53
+ ...negation?.alias !== void 0 ? [`--${negation.alias}`] : []
57
54
  ];
58
- if (schema.kind !== "boolean") return `${forms.join(", ")} ${formatValueHint(schema)}`;
59
- return forms.join(", ");
55
+ if (schema.kind !== "boolean" && schema.kind !== "count") return `${theme.flag(forms.join(", "))} ${theme.placeholder(formatValueHint(schema))}`;
56
+ return theme.flag(forms.join(", "));
60
57
  }
61
58
  /**
62
59
  * Produce a type hint like `<string>`, `<number>`, `<us|eu|ap>`.
63
60
  *
61
+ * A schema-level `valueHint` (set by sugar factories like `flag.url()`)
62
+ * overrides the kind-derived hint.
63
+ *
64
64
  * @param schema - The {@link FlagSchema} whose value type determines the hint.
65
- * @returns Angle-bracketed hint string, or empty string for booleans.
65
+ * @returns Angle-bracketed hint string, or empty string for no-value kinds.
66
66
  */
67
67
  function formatValueHint(schema) {
68
+ if (schema.valueHint !== void 0) return `<${schema.valueHint}>`;
68
69
  switch (schema.kind) {
69
70
  case "string": return "<string>";
70
71
  case "number": return "<number>";
71
72
  case "enum": return `<${(schema.enumValues ?? []).join("|")}>`;
72
73
  case "array": return `<${schema.elementSchema !== void 0 ? formatValueHint(schema.elementSchema).slice(1, -1) : "value"}>...`;
73
- case "boolean": return "";
74
+ case "boolean":
75
+ case "count": return "";
74
76
  case "custom": return "<value>";
77
+ case "keyValue": return "<key=value>";
75
78
  }
76
79
  }
77
80
  /**
78
81
  * Build description with env/config/prompt/default/required/deprecated annotations.
79
82
  *
80
83
  * @param schema - The {@link FlagSchema} to describe.
84
+ * @param theme - Theme applied to the metadata annotations (description stays plain).
81
85
  * @returns Concatenated description string with metadata annotations.
82
86
  */
83
- function formatFlagDescription(schema) {
87
+ function formatFlagDescription(schema, theme) {
84
88
  const parts = [];
85
89
  if (schema.description !== void 0) parts.push(schema.description);
86
- if (schema.deprecated !== void 0) parts.push(formatDeprecated(schema.deprecated));
87
- if (schema.envVar !== void 0) parts.push(`[env: ${schema.envVar}]`);
88
- if (schema.configPath !== void 0) parts.push(`[config: ${schema.configPath}]`);
89
- if (schema.prompt !== void 0) parts.push("[prompt]");
90
- if (schema.presence === "required") parts.push("[required]");
91
- else if (schema.presence === "defaulted" && schema.kind !== "boolean") parts.push(`(default: ${formatHelpDefaultValue(schema.defaultValue)})`);
90
+ if (schema.deprecated !== void 0) parts.push(theme.deprecated(formatDeprecated(schema.deprecated)));
91
+ if (schema.envVar !== void 0) parts.push(theme.annotation(`[env: ${schema.envVar}]`));
92
+ if (schema.configPath !== void 0) parts.push(theme.annotation(`[config: ${schema.configPath}]`));
93
+ if (schema.prompt !== void 0) parts.push(theme.annotation("[prompt]"));
94
+ if (schema.presence === "required") parts.push(theme.annotation("[required]"));
95
+ else if (schema.presence === "defaulted" && schema.kind !== "boolean" && schema.kind !== "count") parts.push(theme.defaultValue(`(default: ${formatHelpDefaultValue(schema.defaultValue)})`));
92
96
  return parts.join(" ");
93
97
  }
94
98
  /**
95
99
  * Build the flag entries sorted: short-aliased first, then alphabetical.
96
100
  *
97
101
  * @param flags - Map of flag names to {@link FlagSchema} definitions.
102
+ * @param theme - Theme threaded into the per-flag formatters.
98
103
  * @returns Sorted array of {@link FlagEntry} objects for the flags table.
99
104
  */
100
- function buildFlagEntries(flags) {
105
+ function buildFlagEntries(flags, theme) {
101
106
  const names = Object.keys(flags);
102
107
  if (names.length === 0) return [];
103
108
  const sorted = [...names].sort((a, b) => {
@@ -115,8 +120,8 @@ function buildFlagEntries(flags) {
115
120
  const schema = flags[name];
116
121
  if (schema === void 0) continue;
117
122
  entries.push({
118
- left: formatFlagLeft(name, schema),
119
- description: formatFlagDescription(schema)
123
+ left: formatFlagLeft(name, schema, theme),
124
+ description: formatFlagDescription(schema, theme)
120
125
  });
121
126
  }
122
127
  return entries;
@@ -138,14 +143,15 @@ function formatArgUsage(entry) {
138
143
  * Format arg description with annotations.
139
144
  *
140
145
  * @param schema - The {@link ArgSchema} to describe.
146
+ * @param theme - Theme applied to the metadata annotations (description stays plain).
141
147
  * @returns Concatenated description string with metadata annotations.
142
148
  */
143
- function formatArgDescription(schema) {
149
+ function formatArgDescription(schema, theme) {
144
150
  const parts = [];
145
151
  if (schema.description !== void 0) parts.push(schema.description);
146
- if (schema.deprecated !== void 0) parts.push(formatDeprecated(schema.deprecated));
147
- if (schema.envVar !== void 0) parts.push(`[env: ${schema.envVar}]`);
148
- if (schema.presence === "defaulted") parts.push(`(default: ${formatHelpDefaultValue(schema.defaultValue)})`);
152
+ if (schema.deprecated !== void 0) parts.push(theme.deprecated(formatDeprecated(schema.deprecated)));
153
+ if (schema.envVar !== void 0) parts.push(theme.annotation(`[env: ${schema.envVar}]`));
154
+ if (schema.presence === "defaulted") parts.push(theme.defaultValue(`(default: ${formatHelpDefaultValue(schema.defaultValue)})`));
149
155
  return parts.join(" ");
150
156
  }
151
157
  /**
@@ -165,7 +171,7 @@ function formatHelpSections(schema, options) {
165
171
  if (visibleCommands.length > 0) sections.push(formatCommandsSection(visibleCommands, opts));
166
172
  if (schema.args.length > 0) sections.push(formatArgsSection(schema.args, opts));
167
173
  if (Object.keys(schema.flags).length > 0) sections.push(formatFlagsSection(schema.flags, opts));
168
- if (schema.examples.length > 0) sections.push(formatExamplesSection(schema.examples));
174
+ if (schema.examples.length > 0) sections.push(formatExamplesSection(schema.examples, opts.theme));
169
175
  return sections;
170
176
  }
171
177
  /**
@@ -204,12 +210,13 @@ function formatHelp(schema, options) {
204
210
  * @returns Single-line usage string, e.g. `Usage: mycli deploy [flags] <env>`.
205
211
  */
206
212
  function formatUsageLine(schema, opts) {
207
- const parts = ["Usage:"];
213
+ const { theme } = opts;
214
+ const parts = [theme.sectionTitle("Usage:")];
208
215
  const cmdName = opts.binName === void 0 ? schema.name : opts.isDefaultHelp ? opts.binName : `${opts.binName} ${schema.name}`;
209
- parts.push(cmdName);
210
- if (schema.commands.length > 0) parts.push("<command>");
211
- if (Object.keys(schema.flags).length > 0) parts.push("[flags]");
212
- for (const entry of schema.args) parts.push(formatArgUsage(entry));
216
+ parts.push(theme.usageBin(cmdName));
217
+ if (schema.commands.length > 0) parts.push(theme.placeholder("<command>"));
218
+ if (Object.keys(schema.flags).length > 0) parts.push(theme.placeholder("[flags]"));
219
+ for (const entry of schema.args) parts.push(theme.arg(formatArgUsage(entry)));
213
220
  return parts.join(" ");
214
221
  }
215
222
  /**
@@ -220,18 +227,20 @@ function formatUsageLine(schema, opts) {
220
227
  * @returns Multi-line arguments section string.
221
228
  */
222
229
  function formatArgsSection(args, opts) {
223
- const lines = ["Arguments:"];
230
+ const { theme } = opts;
231
+ const lines = [theme.sectionTitle("Arguments:")];
224
232
  const GAP = 2;
225
233
  let maxLeft = 0;
226
234
  const entries = [];
227
235
  for (const entry of args) {
228
- const left = ` ${formatArgUsage(entry)}`;
229
- const desc = formatArgDescription(entry.schema);
236
+ const left = ` ${theme.arg(formatArgUsage(entry))}`;
237
+ const desc = formatArgDescription(entry.schema, theme);
230
238
  entries.push({
231
239
  left,
232
240
  desc
233
241
  });
234
- if (left.length > maxLeft) maxLeft = left.length;
242
+ const leftWidth = visibleWidth(left);
243
+ if (leftWidth > maxLeft) maxLeft = leftWidth;
235
244
  }
236
245
  const descCol = maxLeft + GAP;
237
246
  for (const { left, desc } of entries) if (desc.length === 0) lines.push(left);
@@ -250,7 +259,7 @@ function formatArgsSection(args, opts) {
250
259
  * @returns Multi-line flags section string.
251
260
  */
252
261
  function formatFlagsSection(flags, opts) {
253
- return formatFlagEntriesBlock("Flags:", buildFlagEntries(flags), opts.width);
262
+ return formatFlagEntriesBlock(opts.theme.sectionTitle("Flags:"), buildFlagEntries(flags, opts.theme), opts.width);
254
263
  }
255
264
  /**
256
265
  * Render a titled two-column flag block from pre-built {@link FlagEntry} rows.
@@ -259,7 +268,7 @@ function formatFlagsSection(flags, opts) {
259
268
  * block (built-in flags), so column alignment and description wrapping stay
260
269
  * identical across both. Returns `''` when there are no entries.
261
270
  *
262
- * @param title - Section heading (e.g. `'Flags:'`, `'Global options:'`).
271
+ * @param title - Section heading (e.g. `'Flags:'`, `'Global options:'`), pre-styled by the caller.
263
272
  * @param entries - Formatted left/description rows.
264
273
  * @param width - Terminal width for description wrapping.
265
274
  * @returns Multi-line block string, or `''` when `entries` is empty.
@@ -271,8 +280,8 @@ function formatFlagEntriesBlock(title, entries, width) {
271
280
  const GAP = 2;
272
281
  let maxLeft = 0;
273
282
  for (const entry of entries) {
274
- const indented = ` ${entry.left}`;
275
- if (indented.length > maxLeft) maxLeft = indented.length;
283
+ const indentedWidth = visibleWidth(entry.left) + 2;
284
+ if (indentedWidth > maxLeft) maxLeft = indentedWidth;
276
285
  }
277
286
  const descCol = maxLeft + GAP;
278
287
  for (const entry of entries) {
@@ -294,13 +303,14 @@ function formatFlagEntriesBlock(title, entries, width) {
294
303
  * @returns Multi-line commands section string.
295
304
  */
296
305
  function formatCommandsSection(commands, opts) {
297
- const lines = ["Commands:"];
306
+ const { theme } = opts;
307
+ const lines = [theme.sectionTitle("Commands:")];
298
308
  const GAP = 2;
299
309
  let maxNameLen = 0;
300
310
  for (const cmd of commands) if (cmd.name.length > maxNameLen) maxNameLen = cmd.name.length;
301
311
  const descCol = 2 + maxNameLen + GAP;
302
312
  for (const cmd of commands) {
303
- const left = ` ${cmd.name}`;
313
+ const left = ` ${theme.command(cmd.name)}`;
304
314
  const desc = cmd.description ?? "";
305
315
  if (desc.length === 0) lines.push(left);
306
316
  else {
@@ -315,15 +325,17 @@ function formatCommandsSection(commands, opts) {
315
325
  * Render the `Examples:` help section.
316
326
  *
317
327
  * @param examples - Array of {@link CommandExample} entries.
328
+ * @param theme - Theme applied to the section title and `$` prompt marker.
318
329
  * @returns Multi-line examples section string.
319
330
  */
320
- function formatExamplesSection(examples) {
321
- const lines = ["Examples:"];
331
+ function formatExamplesSection(examples, theme) {
332
+ const lines = [theme.sectionTitle("Examples:")];
333
+ const prompt = theme.examplePrompt("$");
322
334
  for (const example of examples) if (example.description !== void 0) {
323
335
  lines.push(` ${example.description}:`);
324
- lines.push(` $ ${example.command}`);
325
- } else lines.push(` $ ${example.command}`);
336
+ lines.push(` ${prompt} ${example.command}`);
337
+ } else lines.push(` ${prompt} ${example.command}`);
326
338
  return lines.join("\n");
327
339
  }
328
340
  //#endregion
329
- export { formatFlagEntriesBlock, formatHelp, formatHelpSections };
341
+ export { formatFlagEntriesBlock, formatHelp, formatHelpSections, osc8, visibleWidth };
@@ -0,0 +1,68 @@
1
+ import { Colors, Formatter } from "ansispeck";
2
+ //#region src/core/help/theme.d.ts
3
+ /**
4
+ * Semantic styling roles for help output.
5
+ *
6
+ * Roles that appear inside wrap-eligible description text (`defaultValue`,
7
+ * `annotation`, `deprecated`) should stick to foreground colors and `dim` —
8
+ * a styled span may cross a soft-wrap boundary, and while color/dim carry
9
+ * invisibly across the continuation indent, `underline`/`inverse`/background
10
+ * styles would visibly paint it.
11
+ */
12
+ interface HelpTheme {
13
+ /** Section headings: `Usage:`, `Arguments:`, `Flags:`, `Commands:`, `Examples:`, `Global options:`. */
14
+ readonly sectionTitle: Formatter;
15
+ /** Binary / command path in the usage line. */
16
+ readonly usageBin: Formatter;
17
+ /** Flag forms in the flags table: `-f, --force`. */
18
+ readonly flag: Formatter;
19
+ /** Grammar tokens: `<string>`, `<command>`, `[flags]`, value hints. */
20
+ readonly placeholder: Formatter;
21
+ /** Command names in `Commands:` tables. */
22
+ readonly command: Formatter;
23
+ /** Positional arg tokens: `<file>`, `[out]...`. */
24
+ readonly arg: Formatter;
25
+ /** Default-value annotations: `(default: 8080)`. */
26
+ readonly defaultValue: Formatter;
27
+ /** Metadata annotations: `[env: X]`, `[config: a.b]`, `[prompt]`, `[required]`, ` (default)`. */
28
+ readonly annotation: Formatter;
29
+ /** Deprecation labels: `[deprecated]`, `[deprecated: use --x]`. */
30
+ readonly deprecated: Formatter;
31
+ /** Program name in the root-help header. */
32
+ readonly headerName: Formatter;
33
+ /** Version (`vX.Y.Z`) in the root-help header. */
34
+ readonly headerVersion: Formatter;
35
+ /** The `$` prompt marker in `Examples:`. */
36
+ readonly examplePrompt: Formatter;
37
+ }
38
+ /**
39
+ * User theme customization: receives the gated palette and returns role
40
+ * overrides merged over the default theme.
41
+ *
42
+ * The palette formatters are identity functions when color is disabled, and
43
+ * the factory itself is only invoked when color is enabled — style
44
+ * unconditionally, gating is the framework's job.
45
+ */
46
+ type HelpThemeFactory = (colors: Colors) => Partial<HelpTheme>;
47
+ /**
48
+ * The built-in help theme (clap/cargo conventions).
49
+ *
50
+ * @param c - Palette to build formatters from (typically the gated `out.color`).
51
+ * @internal
52
+ */
53
+ declare function defaultHelpTheme(c: Colors): HelpTheme;
54
+ /**
55
+ * Resolve the effective help theme from a palette and optional user factory.
56
+ *
57
+ * When the palette renders no styling (color disabled — its formatters are
58
+ * identity functions), the user factory is **never invoked**: even a factory
59
+ * that emits raw escapes cannot leak them into color-off output. When color
60
+ * is enabled, factory overrides merge over {@linkcode defaultHelpTheme}.
61
+ *
62
+ * @param colors - Gated palette, or `undefined` for a color-off theme.
63
+ * @param theme - Optional user overrides factory.
64
+ * @internal
65
+ */
66
+ declare function resolveHelpTheme(colors: Colors | undefined, theme: HelpThemeFactory | undefined): HelpTheme;
67
+ //#endregion
68
+ export { type HelpTheme, type HelpThemeFactory, defaultHelpTheme, resolveHelpTheme };
@@ -0,0 +1,46 @@
1
+ import { createColors } from "ansispeck";
2
+ //#region src/core/help/theme.ts
3
+ /**
4
+ * The built-in help theme (clap/cargo conventions).
5
+ *
6
+ * @param c - Palette to build formatters from (typically the gated `out.color`).
7
+ * @internal
8
+ */
9
+ function defaultHelpTheme(c) {
10
+ return {
11
+ sectionTitle: (input) => c.bold(c.underline(input)),
12
+ usageBin: c.bold,
13
+ flag: c.cyan,
14
+ placeholder: c.dim,
15
+ command: c.cyan,
16
+ arg: c.cyan,
17
+ defaultValue: c.dim,
18
+ annotation: c.dim,
19
+ deprecated: c.yellow,
20
+ headerName: c.bold,
21
+ headerVersion: c.dim,
22
+ examplePrompt: c.dim
23
+ };
24
+ }
25
+ /**
26
+ * Resolve the effective help theme from a palette and optional user factory.
27
+ *
28
+ * When the palette renders no styling (color disabled — its formatters are
29
+ * identity functions), the user factory is **never invoked**: even a factory
30
+ * that emits raw escapes cannot leak them into color-off output. When color
31
+ * is enabled, factory overrides merge over {@linkcode defaultHelpTheme}.
32
+ *
33
+ * @param colors - Gated palette, or `undefined` for a color-off theme.
34
+ * @param theme - Optional user overrides factory.
35
+ * @internal
36
+ */
37
+ function resolveHelpTheme(colors, theme) {
38
+ const palette = colors ?? createColors(false);
39
+ if (!(palette.bold("x") !== "x") || theme === void 0) return defaultHelpTheme(palette);
40
+ return {
41
+ ...defaultHelpTheme(palette),
42
+ ...theme(palette)
43
+ };
44
+ }
45
+ //#endregion
46
+ export { defaultHelpTheme, resolveHelpTheme };
@@ -1,6 +1,6 @@
1
1
  import { CommandSchema } from "../schema/command.mjs";
2
+ import "../schema/index.mjs";
2
3
  import { CLISchema } from "../cli/index.mjs";
3
-
4
4
  //#region src/core/json-schema/index.d.ts
5
5
  /**
6
6
  * Options for JSON Schema generation.
@@ -102,6 +102,13 @@ function serializeFlag(schema, opts) {
102
102
  if (opts.includePrompts && schema.prompt !== void 0) result.prompt = serializePrompt(schema.prompt);
103
103
  if (schema.deprecated !== void 0) result.deprecated = schema.deprecated;
104
104
  if (schema.propagate) result.propagate = true;
105
+ if (schema.negation !== void 0) {
106
+ const negation = {};
107
+ if (schema.negation.alias !== void 0) negation.alias = schema.negation.alias;
108
+ if (schema.negation.hidden) negation.hidden = true;
109
+ result.negation = negation;
110
+ }
111
+ if (schema.duplicates !== "last") result.duplicates = schema.duplicates;
105
112
  return result;
106
113
  }
107
114
  /**
@@ -215,15 +222,19 @@ function generateInputSchema(schema, options) {
215
222
  if (!opts.includeHidden && cmd.schema.hidden) continue;
216
223
  collectInputBranches(cmd.schema, "", branches, opts);
217
224
  }
218
- if (branches.length === 1) return {
219
- $schema: JSON_SCHEMA_DRAFT,
220
- ...stripCommandDiscriminator(branches[0] ?? {})
221
- };
225
+ if (branches.length === 1) {
226
+ const branch = stripCommandDiscriminator(branches[0] ?? {});
227
+ return {
228
+ $schema: JSON_SCHEMA_DRAFT,
229
+ ...branch
230
+ };
231
+ }
222
232
  if (branches.length > 0) {
223
233
  const defaultBranchName = schema.defaultCommand !== void 0 && (opts.includeHidden || !schema.defaultCommand.schema.hidden) ? schema.defaultCommand.schema.name : void 0;
234
+ const normalizedBranches = defaultBranchName !== void 0 ? branches.map((branch) => getBranchCommandDiscriminator(branch) === defaultBranchName ? stripCommandDiscriminator(branch) : branch) : branches;
224
235
  return {
225
236
  $schema: JSON_SCHEMA_DRAFT,
226
- oneOf: defaultBranchName !== void 0 ? branches.map((branch) => getBranchCommandDiscriminator(branch) === defaultBranchName ? stripCommandDiscriminator(branch) : branch) : branches
237
+ oneOf: normalizedBranches
227
238
  };
228
239
  }
229
240
  return {
@@ -302,9 +313,15 @@ function getBranchCommandDiscriminator(branch) {
302
313
  function flagToJsonSchemaType(schema) {
303
314
  const result = {};
304
315
  switch (schema.kind) {
305
- case "string":
316
+ case "string": {
306
317
  result.type = "string";
318
+ const constraints = schema.stringConstraints;
319
+ const minLength = constraints?.nonEmpty === true ? Math.max(constraints.minLength ?? 1, 1) : constraints?.minLength;
320
+ if (minLength !== void 0) result.minLength = minLength;
321
+ if (constraints?.maxLength !== void 0) result.maxLength = constraints.maxLength;
322
+ if (constraints?.pattern !== void 0) result.pattern = constraints.pattern.source;
307
323
  break;
324
+ }
308
325
  case "number": {
309
326
  const constraints = schema.numberConstraints;
310
327
  result.type = constraints?.int === true ? "integer" : "number";
@@ -324,6 +341,14 @@ function flagToJsonSchemaType(schema) {
324
341
  if (schema.elementSchema !== void 0) result.items = flagToJsonSchemaType(schema.elementSchema);
325
342
  break;
326
343
  case "custom": break;
344
+ case "count":
345
+ result.type = "integer";
346
+ result.minimum = 0;
347
+ break;
348
+ case "keyValue":
349
+ result.type = "object";
350
+ result.additionalProperties = { type: "string" };
351
+ break;
327
352
  }
328
353
  if (schema.description !== void 0) result.description = schema.description;
329
354
  if (schema.presence === "defaulted" && isJsonSerializable(schema.defaultValue)) result.default = schema.defaultValue;
@@ -485,7 +510,7 @@ const definitionMetaSchema = withDefinitionMetaSchemaDescriptions({
485
510
  commands: @command[]
486
511
  }`),
487
512
  flag: def(`{
488
- kind: 'string' | 'number' | 'boolean' | 'enum' | 'array' | 'custom';
513
+ kind: 'string' | 'number' | 'boolean' | 'enum' | 'array' | 'custom' | 'count' | 'keyValue';
489
514
  presence: 'optional' | 'required' | 'defaulted';
490
515
  defaultValue?: unknown;
491
516
  aliases?: string[];
@@ -496,7 +521,13 @@ const definitionMetaSchema = withDefinitionMetaSchemaDescriptions({
496
521
  elementSchema?: @flag;
497
522
  prompt?: @prompt;
498
523
  deprecated?: string | true;
499
- propagate?: true
524
+ propagate?: true;
525
+ negation?: @negation;
526
+ duplicates?: 'last' | 'first' | 'error'
527
+ }`),
528
+ negation: def(`{
529
+ alias?: string;
530
+ hidden?: true
500
531
  }`),
501
532
  arg: def(`{
502
533
  name: string;