@kjanat/dreamcli 3.0.0-rc.7 → 3.0.0-rc.9

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 (47) hide show
  1. package/CHANGELOG.md +71 -1
  2. package/dist/core/cli/dispatch.d.mts +6 -4
  3. package/dist/core/cli/dispatch.mjs +6 -4
  4. package/dist/core/cli/index.d.mts +27 -1
  5. package/dist/core/cli/index.mjs +32 -15
  6. package/dist/core/cli/planner.d.mts +3 -0
  7. package/dist/core/cli/planner.mjs +9 -9
  8. package/dist/core/cli/propagate.d.mts +1 -1
  9. package/dist/core/cli/root-help.mjs +32 -20
  10. package/dist/core/cli/runtime-preflight.d.mts +7 -1
  11. package/dist/core/cli/runtime-preflight.mjs +3 -3
  12. package/dist/core/completion/shells/bash.mjs +5 -2
  13. package/dist/core/completion/shells/fish.mjs +3 -1
  14. package/dist/core/completion/shells/powershell.mjs +8 -4
  15. package/dist/core/completion/shells/shared.d.mts +13 -2
  16. package/dist/core/completion/shells/shared.mjs +19 -2
  17. package/dist/core/completion/shells/zsh.mjs +8 -2
  18. package/dist/core/config/index.d.mts +2 -2
  19. package/dist/core/config/package-json.d.mts +27 -3
  20. package/dist/core/config/package-json.mjs +20 -19
  21. package/dist/core/errors/index.d.mts +1 -1
  22. package/dist/core/execution/index.mjs +13 -2
  23. package/dist/core/help/index.d.mts +22 -3
  24. package/dist/core/help/index.mjs +55 -49
  25. package/dist/core/help/theme.d.mts +68 -0
  26. package/dist/core/help/theme.mjs +46 -0
  27. package/dist/core/json-schema/index.d.mts +15 -2
  28. package/dist/core/json-schema/index.mjs +32 -4
  29. package/dist/core/json-schema/meta-descriptions.generated.d.mts +22 -5
  30. package/dist/core/json-schema/meta-descriptions.generated.mjs +14 -5
  31. package/dist/core/parse/index.d.mts +40 -7
  32. package/dist/core/parse/index.mjs +137 -34
  33. package/dist/core/resolve/args.d.mts +1 -1
  34. package/dist/core/resolve/coerce.d.mts +1 -1
  35. package/dist/core/resolve/contracts.d.mts +2 -2
  36. package/dist/core/resolve/index.d.mts +2 -2
  37. package/dist/core/schema/command.d.mts +2 -2
  38. package/dist/core/schema/command.mjs +23 -11
  39. package/dist/core/schema/flag.d.mts +148 -9
  40. package/dist/core/schema/flag.mjs +71 -1
  41. package/dist/core/schema/index.d.mts +2 -2
  42. package/dist/core/schema/run.d.mts +11 -0
  43. package/dist/index.d.mts +7 -6
  44. package/dist/index.mjs +3 -3
  45. package/dist/version.mjs +2 -2
  46. package/dreamcli.schema.json +33 -6
  47. package/package.json +1 -1
@@ -1,6 +1,6 @@
1
1
  import { getFlagAliasNames } from "../../schema/flag.mjs";
2
2
  import { flagExpectsValue } from "../../parse/index.mjs";
3
- import { quoteShellArg, resolveRootCompletionSurface, sanitizeShellIdentifier, versionTag, walkCommandTree } from "./shared.mjs";
3
+ import { getVisibleNegatedName, quoteShellArg, resolveRootCompletionSurface, sanitizeShellIdentifier, versionTag, walkCommandTree } from "./shared.mjs";
4
4
  //#region src/core/completion/shells/bash.ts
5
5
  /**
6
6
  * Generate a bash completion script for the CLI.
@@ -242,7 +242,8 @@ function escapeBashDollarQuote(value) {
242
242
  return value.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/\n/g, "\\n");
243
243
  }
244
244
  /**
245
- * Collect all `--flag` words (long + short aliases) for a flag record.
245
+ * Collect all `--flag` words (long + short aliases + visible negated
246
+ * spellings) for a flag record.
246
247
  *
247
248
  * @internal
248
249
  */
@@ -251,6 +252,8 @@ function collectFlagWords(flags) {
251
252
  for (const [name, schema] of Object.entries(flags)) {
252
253
  words.push(`--${name}`);
253
254
  for (const alias of getFlagAliasNames(schema)) words.push(alias.length === 1 ? `-${alias}` : `--${alias}`);
255
+ const negated = getVisibleNegatedName(name, schema);
256
+ if (negated !== void 0) words.push(`--${negated}`);
254
257
  }
255
258
  return words.join(" ");
256
259
  }
@@ -1,6 +1,6 @@
1
1
  import { getFlagAliasNames } from "../../schema/flag.mjs";
2
2
  import { flagExpectsValue } from "../../parse/index.mjs";
3
- import { quoteShellArg, resolveRootCompletionSurface, sanitizeShellIdentifier, versionTag, walkCommandTree } from "./shared.mjs";
3
+ import { getVisibleNegatedName, quoteShellArg, resolveRootCompletionSurface, sanitizeShellIdentifier, versionTag, walkCommandTree } from "./shared.mjs";
4
4
  //#region src/core/completion/shells/fish.ts
5
5
  /**
6
6
  * Generate a fish completion script for the CLI.
@@ -111,6 +111,8 @@ function appendFishFlagCompletions(lines, commandName, pathIsFuncName, path, fla
111
111
  for (const alias of getFlagAliasNames(schema, { kind: "short" })) parts.push(`-s ${quoteShellArg(alias)}`);
112
112
  parts.push(`-l ${quoteShellArg(name)}`);
113
113
  for (const alias of getFlagAliasNames(schema, { kind: "long" })) parts.push(`-l ${quoteShellArg(alias)}`);
114
+ const negated = getVisibleNegatedName(name, schema);
115
+ if (negated !== void 0) parts.push(`-l ${quoteShellArg(negated)}`);
114
116
  parts.push(`-d ${quoteShellArg(schema.description ?? name)}`);
115
117
  if (flagExpectsValue(schema)) parts.push("-r", "-f");
116
118
  if (schema.kind === "enum" && schema.enumValues !== void 0) {
@@ -1,6 +1,6 @@
1
- import { getFlagAliasNames } from "../../schema/flag.mjs";
1
+ import { getFlagAliasNames, getFlagNegatedName } from "../../schema/flag.mjs";
2
2
  import { flagExpectsValue } from "../../parse/index.mjs";
3
- import { resolveRootCompletionSurface, sanitizeShellIdentifier, versionTag, walkCommandTree } from "./shared.mjs";
3
+ import { getVisibleNegatedName, resolveRootCompletionSurface, sanitizeShellIdentifier, versionTag, walkCommandTree } from "./shared.mjs";
4
4
  //#region src/core/completion/shells/powershell.ts
5
5
  /**
6
6
  * Generate a PowerShell completion script for the CLI.
@@ -90,10 +90,13 @@ function appendPowerShellPathEntry(lines, path, commands, flags) {
90
90
  lines.push(" )");
91
91
  lines.push(" Flags = @(");
92
92
  for (const [name, schema] of Object.entries(flags)) {
93
+ const visibleNegated = getVisibleNegatedName(name, schema);
94
+ const parseNegated = getFlagNegatedName(name, schema);
93
95
  const forms = dedupeValues([
94
96
  `--${name}`,
95
97
  ...getFlagAliasNames(schema, { kind: "short" }).map((alias) => `-${alias}`),
96
- ...getFlagAliasNames(schema, { kind: "long" }).map((alias) => `--${alias}`)
98
+ ...getFlagAliasNames(schema, { kind: "long" }).map((alias) => `--${alias}`),
99
+ ...visibleNegated !== void 0 ? [`--${visibleNegated}`] : []
97
100
  ]);
98
101
  const parseForms = dedupeValues([
99
102
  `--${name}`,
@@ -104,7 +107,8 @@ function appendPowerShellPathEntry(lines, path, commands, flags) {
104
107
  ...getFlagAliasNames(schema, {
105
108
  kind: "long",
106
109
  includeHidden: true
107
- }).map((alias) => `--${alias}`)
110
+ }).map((alias) => `--${alias}`),
111
+ ...parseNegated !== void 0 ? [`--${parseNegated}`] : []
108
112
  ]);
109
113
  lines.push(" @{");
110
114
  lines.push(`\t\t\t\tCanonicalName = ${quotePowerShellString(name)}`);
@@ -1,6 +1,6 @@
1
1
  import { FlagSchema } from "../../schema/flag.mjs";
2
- import "../../schema/index.mjs";
3
2
  import { CommandSchema } from "../../schema/command.mjs";
3
+ import "../../schema/index.mjs";
4
4
  //#region src/core/completion/shells/shared.d.ts
5
5
  /**
6
6
  * Format a version tag for generated completion script headers.
@@ -120,6 +120,17 @@ interface CommandNode {
120
120
  * @internal
121
121
  */
122
122
  declare function walkCommandTree(topLevel: readonly CommandSchema[], ancestorSchemas?: readonly CommandSchema[]): readonly CommandNode[];
123
+ /**
124
+ * Effective negated long-form spelling for user-facing suggestion lists.
125
+ *
126
+ * Returns the negated spelling without the `--` prefix (e.g. `no-verbose`)
127
+ * when the flag is negatable and the negation is not hidden; `undefined`
128
+ * otherwise. Negated spellings are long-only and take no value, so they only
129
+ * belong in suggestion lists — never in value-flag (operand-skip) patterns.
130
+ *
131
+ * @internal
132
+ */
133
+ declare function getVisibleNegatedName(name: string, schema: FlagSchema): string | undefined;
123
134
  /**
124
135
  * Sanitize a string for use as a shell function identifier.
125
136
  * Replaces non-alphanumeric/underscore characters with underscores.
@@ -146,4 +157,4 @@ declare function sanitizeShellIdentifier(name: string): string;
146
157
  */
147
158
  declare function quoteShellArg(value: string): string;
148
159
  //#endregion
149
- export { type CommandNode, type CompletionOptions, type RootCompletionSurface, quoteShellArg, resolveRootCompletionSurface, sanitizeShellIdentifier, versionTag, walkCommandTree };
160
+ export { type CommandNode, type CompletionOptions, type RootCompletionSurface, getVisibleNegatedName, quoteShellArg, resolveRootCompletionSurface, sanitizeShellIdentifier, versionTag, walkCommandTree };
@@ -1,3 +1,4 @@
1
+ import { getFlagNegatedName } from "../../schema/flag.mjs";
1
2
  import { collectPropagatedFlags } from "../../cli/propagate.mjs";
2
3
  import { resolveRootSurface } from "../../cli/root-surface.mjs";
3
4
  import { DREAMCLI_REVISION, DREAMCLI_VERSION } from "../../../version.mjs";
@@ -83,7 +84,9 @@ function createSyntheticRootFlag(description) {
83
84
  prompt: void 0,
84
85
  parseFn: void 0,
85
86
  deprecated: void 0,
86
- propagate: false
87
+ propagate: false,
88
+ negation: void 0,
89
+ duplicates: "last"
87
90
  };
88
91
  }
89
92
  /**
@@ -119,6 +122,20 @@ function walkCommandTree(topLevel, ancestorSchemas = []) {
119
122
  return nodes;
120
123
  }
121
124
  /**
125
+ * Effective negated long-form spelling for user-facing suggestion lists.
126
+ *
127
+ * Returns the negated spelling without the `--` prefix (e.g. `no-verbose`)
128
+ * when the flag is negatable and the negation is not hidden; `undefined`
129
+ * otherwise. Negated spellings are long-only and take no value, so they only
130
+ * belong in suggestion lists — never in value-flag (operand-skip) patterns.
131
+ *
132
+ * @internal
133
+ */
134
+ function getVisibleNegatedName(name, schema) {
135
+ if (schema.negation === void 0 || schema.negation.hidden) return void 0;
136
+ return getFlagNegatedName(name, schema);
137
+ }
138
+ /**
122
139
  * Sanitize a string for use as a shell function identifier.
123
140
  * Replaces non-alphanumeric/underscore characters with underscores.
124
141
  * When sanitization changes the name, appends a short stable hash suffix so
@@ -156,4 +173,4 @@ function quoteShellArg(value) {
156
173
  return `'${value.replace(/'/g, "'\\''")}'`;
157
174
  }
158
175
  //#endregion
159
- export { quoteShellArg, resolveRootCompletionSurface, sanitizeShellIdentifier, versionTag, walkCommandTree };
176
+ export { getVisibleNegatedName, quoteShellArg, resolveRootCompletionSurface, sanitizeShellIdentifier, versionTag, walkCommandTree };
@@ -1,7 +1,7 @@
1
1
  import { CLIError } from "../../errors/index.mjs";
2
2
  import { getFlagAliasNames } from "../../schema/flag.mjs";
3
3
  import { flagExpectsValue } from "../../parse/index.mjs";
4
- import { quoteShellArg, resolveRootCompletionSurface, sanitizeShellIdentifier, versionTag, walkCommandTree } from "./shared.mjs";
4
+ import { getVisibleNegatedName, quoteShellArg, resolveRootCompletionSurface, sanitizeShellIdentifier, versionTag, walkCommandTree } from "./shared.mjs";
5
5
  //#region src/core/completion/shells/zsh.ts
6
6
  /**
7
7
  * Generate a zsh completion script for the CLI.
@@ -203,6 +203,9 @@ function escapeZshDescription(value) {
203
203
  * - `'(-s --name --alias)'{-s,--name,--alias}'[description]'` for flags with
204
204
  * visible aliases
205
205
  *
206
+ * A visible negated spelling (`--no-name`) joins the flag's form group — the
207
+ * two spellings are one logical flag, so completing one excludes the other.
208
+ *
206
209
  * @internal
207
210
  */
208
211
  function buildZshFlagSpecsFromFlags(flags) {
@@ -212,10 +215,13 @@ function buildZshFlagSpecsFromFlags(flags) {
212
215
  const longFlag = `--${name}`;
213
216
  const shortFlags = getFlagAliasNames(schema, { kind: "short" }).map((alias) => `-${alias}`);
214
217
  const longAliases = getFlagAliasNames(schema, { kind: "long" }).map((alias) => `--${alias}`);
218
+ const negated = getVisibleNegatedName(name, schema);
219
+ const negatedForms = negated !== void 0 ? [`--${negated}`] : [];
215
220
  const allForms = [
216
221
  ...shortFlags,
217
222
  longFlag,
218
- ...longAliases
223
+ ...longAliases,
224
+ ...negatedForms
219
225
  ];
220
226
  let valuePart = "";
221
227
  if (!flagExpectsValue(schema)) {} else if (schema.kind === "enum" && schema.enumValues !== void 0) valuePart = `:value:(${schema.enumValues.map(escapeZshEnumValue).join(" ")})`;
@@ -1,5 +1,5 @@
1
1
  import { RuntimeAdapter } from "../../runtime/adapter.mjs";
2
- import { ManifestDiscoveryOptions, PackageJsonAdapter, PackageJsonData, PackageRepository, discoverManifest, discoverPackageJson, inferCliName, packageRepositoryUrl } from "./package-json.mjs";
2
+ import { ManifestDiscoveryOptions, PackageJsonAdapter, PackageJsonData, PackageRepository, PackageRepositoryUrlOptions, discoverManifest, discoverPackageJson, inferCliName, packageRepositoryUrl } from "./package-json.mjs";
3
3
  //#region src/core/config/index.d.ts
4
4
  /**
5
5
  * Format loader — parses file content into a config object.
@@ -157,4 +157,4 @@ declare function discoverConfig(appName: string, adapter: ConfigAdapter, options
157
157
  */
158
158
  declare function configFormat(extensions: readonly string[], parse: (content: string) => unknown): FormatLoader;
159
159
  //#endregion
160
- export { type ConfigAdapter, type ConfigDiscoveryOptions, type ConfigDiscoveryResult, type ConfigFound, type ConfigNotFound, type FormatLoader, type ManifestDiscoveryOptions, type PackageJsonAdapter, type PackageJsonData, type PackageRepository, buildConfigSearchPaths, configFormat, discoverConfig, discoverManifest, discoverPackageJson, inferCliName, packageRepositoryUrl };
160
+ export { type ConfigAdapter, type ConfigDiscoveryOptions, type ConfigDiscoveryResult, type ConfigFound, type ConfigNotFound, type FormatLoader, type ManifestDiscoveryOptions, type PackageJsonAdapter, type PackageJsonData, type PackageRepository, type PackageRepositoryUrlOptions, buildConfigSearchPaths, configFormat, discoverConfig, discoverManifest, discoverPackageJson, inferCliName, packageRepositoryUrl };
@@ -132,6 +132,20 @@ declare function discoverManifest(adapter: PackageJsonAdapter, options?: Manifes
132
132
  * ```
133
133
  */
134
134
  declare function discoverPackageJson(adapter: PackageJsonAdapter, startDir?: string): Promise<PackageJsonData | null>;
135
+ /** Options for {@link packageRepositoryUrl}. */
136
+ interface PackageRepositoryUrlOptions {
137
+ /**
138
+ * Throw a `CLIError` (code `INVALID_REPOSITORY`) instead of returning
139
+ * `undefined` when the `repository` field is absent or not a recognisable
140
+ * locator. With `require: true` the return type narrows to `string`, so
141
+ * callers that know their manifest carries a valid repository need no
142
+ * assertion — and a bad manifest fails fast with a real message instead
143
+ * of propagating `undefined`.
144
+ *
145
+ * @defaultValue `false`
146
+ */
147
+ readonly require?: boolean;
148
+ }
135
149
  /**
136
150
  * Resolve a package's `repository` field to a browsable `https://` URL.
137
151
  *
@@ -142,15 +156,25 @@ declare function discoverPackageJson(adapter: PackageJsonAdapter, startDir?: str
142
156
  * - shorthands: `github:u/r`, `gitlab:u/r`, `bitbucket:u/r`, and bare `u/r`
143
157
  * (GitHub, per npm convention)
144
158
  *
145
- * Returns `undefined` when the field is absent or unrecognised.
159
+ * Returns `undefined` when the field is absent or unrecognised — or, with
160
+ * `{ require: true }`, throws instead and the return type is `string`.
161
+ * (The narrowing cannot key off the input type alone: a present `repository`
162
+ * may still be an empty string, a url-less object, or an unparseable
163
+ * locator, so the `string` promise is backed by the runtime check.)
146
164
  *
147
165
  * @example
148
166
  * ```ts
149
167
  * packageRepositoryUrl({ repository: 'git+https://github.com/u/r.git' });
150
168
  * // 'https://github.com/u/r'
169
+ *
170
+ * const url: string = packageRepositoryUrl(pkg, { require: true });
171
+ * // throws CLIError when pkg.repository is missing or unrecognised
151
172
  * ```
152
173
  */
153
- declare function packageRepositoryUrl(pkg: PackageJsonData): string | undefined;
174
+ declare function packageRepositoryUrl(pkg: PackageJsonData, options: PackageRepositoryUrlOptions & {
175
+ readonly require: true;
176
+ }): string;
177
+ declare function packageRepositoryUrl(pkg: PackageJsonData, options?: PackageRepositoryUrlOptions): string | undefined;
154
178
  /**
155
179
  * Infer the CLI binary name from manifest data.
156
180
  *
@@ -182,4 +206,4 @@ declare function inferCliName(pkg: PackageJsonData, options?: {
182
206
  readonly stripScope?: boolean;
183
207
  }): string | undefined;
184
208
  //#endregion
185
- export { type ManifestDiscoveryOptions, type PackageJsonAdapter, type PackageJsonData, type PackageRepository, discoverManifest, discoverPackageJson, inferCliName, packageRepositoryUrl };
209
+ export { type ManifestDiscoveryOptions, type PackageJsonAdapter, type PackageJsonData, type PackageRepository, type PackageRepositoryUrlOptions, discoverManifest, discoverPackageJson, inferCliName, packageRepositoryUrl };
@@ -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 & {}`). */
@@ -1,6 +1,7 @@
1
1
  import { CLIError } from "../errors/index.mjs";
2
2
  import { includesBeforeSeparator, parse } from "../parse/index.mjs";
3
3
  import { formatHelp } from "../help/index.mjs";
4
+ import { generateCommandSchema } from "../json-schema/index.mjs";
4
5
  import { clearRequestedExitCode, getRequestedExitCode } from "../output/index.mjs";
5
6
  import { createTestPrompter } from "../prompt/index.mjs";
6
7
  import { resolve } from "../resolve/index.mjs";
@@ -17,7 +18,17 @@ async function executeCommand(request) {
17
18
  clearRequestedExitCode(out);
18
19
  try {
19
20
  if (includesBeforeSeparator(argv, "--help") || includesBeforeSeparator(argv, "-h")) {
20
- const helpText = formatHelp(schema, options?.help);
21
+ if (out.jsonMode || options?.jsonMode === true) {
22
+ out.json(generateCommandSchema(schema));
23
+ return {
24
+ exitCode: 0,
25
+ error: void 0
26
+ };
27
+ }
28
+ const helpText = formatHelp(schema, options?.help?.colors !== void 0 ? options.help : {
29
+ ...options?.help,
30
+ colors: out.color
31
+ });
21
32
  out.log(helpText);
22
33
  return {
23
34
  exitCode: 0,
@@ -42,7 +53,7 @@ async function executeCommand(request) {
42
53
  meta,
43
54
  out
44
55
  });
45
- const parsed = parse(schema, argv);
56
+ const parsed = parse(schema, argv, options?.flags);
46
57
  const effectivePrompter = options?.prompter ?? (options?.answers !== void 0 ? createTestPrompter(options.answers) : void 0);
47
58
  const resolved = await resolve(schema, parsed, {
48
59
  ...options?.stdinData !== void 0 ? { stdinData: options.stdinData } : {},
@@ -1,6 +1,8 @@
1
- import "../schema/index.mjs";
1
+ import { HelpTheme, HelpThemeFactory } from "./theme.mjs";
2
2
  import { osc8, visibleWidth } from "./ansi.mjs";
3
3
  import { CommandSchema } from "../schema/command.mjs";
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
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,18 +38,22 @@ 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" && schema.kind !== "count") 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>`.
@@ -84,26 +81,28 @@ function formatValueHint(schema) {
84
81
  * Build description with env/config/prompt/default/required/deprecated annotations.
85
82
  *
86
83
  * @param schema - The {@link FlagSchema} to describe.
84
+ * @param theme - Theme applied to the metadata annotations (description stays plain).
87
85
  * @returns Concatenated description string with metadata annotations.
88
86
  */
89
- function formatFlagDescription(schema) {
87
+ function formatFlagDescription(schema, theme) {
90
88
  const parts = [];
91
89
  if (schema.description !== void 0) parts.push(schema.description);
92
- if (schema.deprecated !== void 0) parts.push(formatDeprecated(schema.deprecated));
93
- if (schema.envVar !== void 0) parts.push(`[env: ${schema.envVar}]`);
94
- if (schema.configPath !== void 0) parts.push(`[config: ${schema.configPath}]`);
95
- if (schema.prompt !== void 0) parts.push("[prompt]");
96
- if (schema.presence === "required") parts.push("[required]");
97
- else if (schema.presence === "defaulted" && schema.kind !== "boolean" && schema.kind !== "count") 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)})`));
98
96
  return parts.join(" ");
99
97
  }
100
98
  /**
101
99
  * Build the flag entries sorted: short-aliased first, then alphabetical.
102
100
  *
103
101
  * @param flags - Map of flag names to {@link FlagSchema} definitions.
102
+ * @param theme - Theme threaded into the per-flag formatters.
104
103
  * @returns Sorted array of {@link FlagEntry} objects for the flags table.
105
104
  */
106
- function buildFlagEntries(flags) {
105
+ function buildFlagEntries(flags, theme) {
107
106
  const names = Object.keys(flags);
108
107
  if (names.length === 0) return [];
109
108
  const sorted = [...names].sort((a, b) => {
@@ -121,8 +120,8 @@ function buildFlagEntries(flags) {
121
120
  const schema = flags[name];
122
121
  if (schema === void 0) continue;
123
122
  entries.push({
124
- left: formatFlagLeft(name, schema),
125
- description: formatFlagDescription(schema)
123
+ left: formatFlagLeft(name, schema, theme),
124
+ description: formatFlagDescription(schema, theme)
126
125
  });
127
126
  }
128
127
  return entries;
@@ -144,14 +143,15 @@ function formatArgUsage(entry) {
144
143
  * Format arg description with annotations.
145
144
  *
146
145
  * @param schema - The {@link ArgSchema} to describe.
146
+ * @param theme - Theme applied to the metadata annotations (description stays plain).
147
147
  * @returns Concatenated description string with metadata annotations.
148
148
  */
149
- function formatArgDescription(schema) {
149
+ function formatArgDescription(schema, theme) {
150
150
  const parts = [];
151
151
  if (schema.description !== void 0) parts.push(schema.description);
152
- if (schema.deprecated !== void 0) parts.push(formatDeprecated(schema.deprecated));
153
- if (schema.envVar !== void 0) parts.push(`[env: ${schema.envVar}]`);
154
- 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)})`));
155
155
  return parts.join(" ");
156
156
  }
157
157
  /**
@@ -171,7 +171,7 @@ function formatHelpSections(schema, options) {
171
171
  if (visibleCommands.length > 0) sections.push(formatCommandsSection(visibleCommands, opts));
172
172
  if (schema.args.length > 0) sections.push(formatArgsSection(schema.args, opts));
173
173
  if (Object.keys(schema.flags).length > 0) sections.push(formatFlagsSection(schema.flags, opts));
174
- if (schema.examples.length > 0) sections.push(formatExamplesSection(schema.examples));
174
+ if (schema.examples.length > 0) sections.push(formatExamplesSection(schema.examples, opts.theme));
175
175
  return sections;
176
176
  }
177
177
  /**
@@ -210,12 +210,13 @@ function formatHelp(schema, options) {
210
210
  * @returns Single-line usage string, e.g. `Usage: mycli deploy [flags] <env>`.
211
211
  */
212
212
  function formatUsageLine(schema, opts) {
213
- const parts = ["Usage:"];
213
+ const { theme } = opts;
214
+ const parts = [theme.sectionTitle("Usage:")];
214
215
  const cmdName = opts.binName === void 0 ? schema.name : opts.isDefaultHelp ? opts.binName : `${opts.binName} ${schema.name}`;
215
- parts.push(cmdName);
216
- if (schema.commands.length > 0) parts.push("<command>");
217
- if (Object.keys(schema.flags).length > 0) parts.push("[flags]");
218
- 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)));
219
220
  return parts.join(" ");
220
221
  }
221
222
  /**
@@ -226,18 +227,20 @@ function formatUsageLine(schema, opts) {
226
227
  * @returns Multi-line arguments section string.
227
228
  */
228
229
  function formatArgsSection(args, opts) {
229
- const lines = ["Arguments:"];
230
+ const { theme } = opts;
231
+ const lines = [theme.sectionTitle("Arguments:")];
230
232
  const GAP = 2;
231
233
  let maxLeft = 0;
232
234
  const entries = [];
233
235
  for (const entry of args) {
234
- const left = ` ${formatArgUsage(entry)}`;
235
- const desc = formatArgDescription(entry.schema);
236
+ const left = ` ${theme.arg(formatArgUsage(entry))}`;
237
+ const desc = formatArgDescription(entry.schema, theme);
236
238
  entries.push({
237
239
  left,
238
240
  desc
239
241
  });
240
- if (left.length > maxLeft) maxLeft = left.length;
242
+ const leftWidth = visibleWidth(left);
243
+ if (leftWidth > maxLeft) maxLeft = leftWidth;
241
244
  }
242
245
  const descCol = maxLeft + GAP;
243
246
  for (const { left, desc } of entries) if (desc.length === 0) lines.push(left);
@@ -256,7 +259,7 @@ function formatArgsSection(args, opts) {
256
259
  * @returns Multi-line flags section string.
257
260
  */
258
261
  function formatFlagsSection(flags, opts) {
259
- return formatFlagEntriesBlock("Flags:", buildFlagEntries(flags), opts.width);
262
+ return formatFlagEntriesBlock(opts.theme.sectionTitle("Flags:"), buildFlagEntries(flags, opts.theme), opts.width);
260
263
  }
261
264
  /**
262
265
  * Render a titled two-column flag block from pre-built {@link FlagEntry} rows.
@@ -265,7 +268,7 @@ function formatFlagsSection(flags, opts) {
265
268
  * block (built-in flags), so column alignment and description wrapping stay
266
269
  * identical across both. Returns `''` when there are no entries.
267
270
  *
268
- * @param title - Section heading (e.g. `'Flags:'`, `'Global options:'`).
271
+ * @param title - Section heading (e.g. `'Flags:'`, `'Global options:'`), pre-styled by the caller.
269
272
  * @param entries - Formatted left/description rows.
270
273
  * @param width - Terminal width for description wrapping.
271
274
  * @returns Multi-line block string, or `''` when `entries` is empty.
@@ -277,8 +280,8 @@ function formatFlagEntriesBlock(title, entries, width) {
277
280
  const GAP = 2;
278
281
  let maxLeft = 0;
279
282
  for (const entry of entries) {
280
- const indented = ` ${entry.left}`;
281
- if (indented.length > maxLeft) maxLeft = indented.length;
283
+ const indentedWidth = visibleWidth(entry.left) + 2;
284
+ if (indentedWidth > maxLeft) maxLeft = indentedWidth;
282
285
  }
283
286
  const descCol = maxLeft + GAP;
284
287
  for (const entry of entries) {
@@ -300,13 +303,14 @@ function formatFlagEntriesBlock(title, entries, width) {
300
303
  * @returns Multi-line commands section string.
301
304
  */
302
305
  function formatCommandsSection(commands, opts) {
303
- const lines = ["Commands:"];
306
+ const { theme } = opts;
307
+ const lines = [theme.sectionTitle("Commands:")];
304
308
  const GAP = 2;
305
309
  let maxNameLen = 0;
306
310
  for (const cmd of commands) if (cmd.name.length > maxNameLen) maxNameLen = cmd.name.length;
307
311
  const descCol = 2 + maxNameLen + GAP;
308
312
  for (const cmd of commands) {
309
- const left = ` ${cmd.name}`;
313
+ const left = ` ${theme.command(cmd.name)}`;
310
314
  const desc = cmd.description ?? "";
311
315
  if (desc.length === 0) lines.push(left);
312
316
  else {
@@ -321,14 +325,16 @@ function formatCommandsSection(commands, opts) {
321
325
  * Render the `Examples:` help section.
322
326
  *
323
327
  * @param examples - Array of {@link CommandExample} entries.
328
+ * @param theme - Theme applied to the section title and `$` prompt marker.
324
329
  * @returns Multi-line examples section string.
325
330
  */
326
- function formatExamplesSection(examples) {
327
- const lines = ["Examples:"];
331
+ function formatExamplesSection(examples, theme) {
332
+ const lines = [theme.sectionTitle("Examples:")];
333
+ const prompt = theme.examplePrompt("$");
328
334
  for (const example of examples) if (example.description !== void 0) {
329
335
  lines.push(` ${example.description}:`);
330
- lines.push(` $ ${example.command}`);
331
- } else lines.push(` $ ${example.command}`);
336
+ lines.push(` ${prompt} ${example.command}`);
337
+ } else lines.push(` ${prompt} ${example.command}`);
332
338
  return lines.join("\n");
333
339
  }
334
340
  //#endregion