@kjanat/dreamcli 2.1.0 → 2.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,50 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [2.2.1] - 2026-06-10
11
+
12
+ ### Added
13
+
14
+ - **`.links()` — OSC 8 hyperlinks in the root-help header** — the program name and version on the
15
+ first line of root `--help` output can now carry
16
+ [OSC 8 hyperlinks](https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda) in
17
+ supporting terminals ([#20](https://github.com/kjanat/dreamcli/issues/20)). Pass explicit URLs
18
+ (`.links({ name, version })`) or call `.links()` with no arguments to derive them from
19
+ `package.json` metadata when `.packageJson()` is active: the name links to the normalized
20
+ `repository` URL (falling back to `homepage`), and the version links to the forge release tag
21
+ (`{repo}/releases/tag/v{version}` on GitHub, `{repo}/-/releases/v{version}` on GitLab). Escapes
22
+ are emitted only when stdout is a TTY (overridable via the new `help.hyperlinks` option) and only
23
+ on the header line — usage lines, the `--help` hint, the commands table, `--version` output, and
24
+ completion scripts stay plain.
25
+ - **ANSI/OSC-aware help width helpers** — help padding and wrapping now measure _visible_ width:
26
+ the shared `padEnd()`/`wrapText()` helpers strip ANSI CSI (colors) and OSC (hyperlink) escape
27
+ sequences before counting columns, so escape-bearing text no longer mangles `--help` alignment.
28
+ New public exports `osc8(url, text)` (wrap text in an OSC 8 hyperlink) and `visibleWidth(text)`
29
+ (escape-aware width measurement) support custom help rendering.
30
+ - **`packageRepositoryUrl(pkg)`** — new public helper that normalizes a package's `repository`
31
+ field to a browsable `https://` URL, handling the locator formats npm accepts (`{ type, url }`
32
+ object form, `git+`/`.git` affixes, scp-style `git@host:u/r.git`, and the
33
+ `github:`/`gitlab:`/`bitbucket:`/bare `u/r` shorthands). `PackageJsonData` now also parses the
34
+ `homepage` and `repository` fields.
35
+
36
+ ## [2.2.0] - 2026-06-09
37
+
38
+ ### Added
39
+
40
+ - **`.packageJson(data)` — pre-loaded metadata** — `CLIBuilder.packageJson()` now accepts an
41
+ already-imported `package.json` object (e.g. `import pkg from './package.json' with { type: 'json' }`),
42
+ skipping filesystem discovery entirely. The data is detected via field shape (`name`/`version`/
43
+ `description`/`bin`), and its `version`/`description` are merged into the CLI schema at builder time
44
+ so the data form works in **both** `.run()` and `.execute()` (the filesystem-free path that
45
+ previously couldn't consume `.packageJson()` at all). Explicit `.version()`/`.description()` still
46
+ win; an empty `{}` or a settings-shaped object falls through to the settings overload, so this is a
47
+ non-breaking addition.
48
+ - **`.packageJson({ from })` — anchored discovery** — discovery can now be anchored to an explicit
49
+ location instead of the runtime cwd. Pass `{ from: import.meta.url }` (also accepts path strings,
50
+ `file:` URL strings, or `URL` instances) so installable CLIs (`npm i -g`, `bunx`, `npx`) report
51
+ their OWN version from any working directory. `discoverPackageJson(adapter, startDir?)` gained a
52
+ matching optional anchor parameter.
53
+
10
54
  ## [2.1.0] - 2026-04-16
11
55
 
12
56
  ### Added
@@ -746,7 +790,9 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
746
790
  - MIT License.
747
791
  - Markdownlint configuration.
748
792
 
749
- [Unreleased]: https://github.com/kjanat/dreamcli/compare/v2.1.0...HEAD
793
+ [Unreleased]: https://github.com/kjanat/dreamcli/compare/v2.2.1...HEAD
794
+ [2.2.1]: https://github.com/kjanat/dreamcli/compare/v2.2.0...v2.2.1
795
+ [2.2.0]: https://github.com/kjanat/dreamcli/compare/v2.1.0...v2.2.0
750
796
  [2.1.0]: https://github.com/kjanat/dreamcli/compare/v2.0.1...v2.1.0
751
797
  [2.0.1]: https://github.com/kjanat/dreamcli/compare/v2.0.0...v2.0.1
752
798
  [2.0.0]: https://github.com/kjanat/dreamcli/compare/v1.0.0...v2.0.0
@@ -0,0 +1,28 @@
1
+ import { PackageJsonData } from "../config/package-json.mjs";
2
+
3
+ //#region src/core/cli/help-links.d.ts
4
+ /**
5
+ * OSC 8 hyperlink targets for the root-help header.
6
+ *
7
+ * Set via `CLIBuilder.links()`; fields left `undefined` are derived from
8
+ * package.json metadata when `.packageJson()` is active.
9
+ */
10
+ interface HelpLinks {
11
+ /** URL the program name links to (e.g. the repository or homepage). */
12
+ readonly name: string | undefined;
13
+ /** URL the version links to (e.g. the release tag). */
14
+ readonly version: string | undefined;
15
+ }
16
+ /**
17
+ * Fill `undefined` link fields from package.json metadata.
18
+ *
19
+ * Explicit URLs always win. The name falls back to the normalized
20
+ * `repository` URL, then `homepage`; the version falls back to the forge
21
+ * release-tag URL when both a repository and a version are known.
22
+ * Idempotent — already-resolved fields pass through unchanged.
23
+ *
24
+ * @internal
25
+ */
26
+ declare function deriveHelpLinks(links: HelpLinks | undefined, pkg: PackageJsonData | undefined, version: string | undefined): HelpLinks | undefined;
27
+ //#endregion
28
+ export { type HelpLinks, deriveHelpLinks };
@@ -0,0 +1 @@
1
+ import{packageRepositoryUrl as e}from"../config/package-json.mjs";function t(e,t){let n;try{n=new URL(e).hostname}catch{return}if(n===`github.com`)return`${e}/releases/tag/v${t}`;if(n===`gitlab.com`)return`${e}/-/releases/v${t}`}function n(n,r,i){if(n===void 0)return;if(r===void 0||n.name!==void 0&&n.version!==void 0)return n;let a=e(r);return{name:n.name??a??r.homepage,version:n.version??(a!==void 0&&i!==void 0?t(a,i):void 0)}}export{n as deriveHelpLinks};
@@ -3,8 +3,10 @@ import { FlagBuilder, FlagConfig } from "../schema/flag.mjs";
3
3
  import { BeforeParseParams, CLIPlugin, CLIPluginHooks, PluginCommandContext, ResolvedCommandParams, plugin } from "./plugin.mjs";
4
4
  import { RunOptions, RunResult } from "../schema/run.mjs";
5
5
  import { CommandBuilder, ErasedCommand } from "../schema/command.mjs";
6
- import { CompletionOptions } from "../completion/shells/shared.mjs";
7
6
  import { RuntimeAdapter } from "../../runtime/adapter.mjs";
7
+ import { PackageJsonData } from "../config/package-json.mjs";
8
+ import { HelpLinks } from "./help-links.mjs";
9
+ import { CompletionOptions } from "../completion/shells/shared.mjs";
8
10
  import { FormatLoader } from "../config/index.mjs";
9
11
  import { formatRootHelp } from "./root-help.mjs";
10
12
 
@@ -55,6 +57,14 @@ interface CLISchema {
55
57
  * Set via the {@linkcode CLIBuilder.packageJson | .packageJson()} builder method.
56
58
  */
57
59
  readonly packageJsonSettings: PackageJsonSettings | undefined;
60
+ /**
61
+ * OSC 8 hyperlink targets for the root-help header (name/version).
62
+ *
63
+ * Set via the {@linkcode CLIBuilder.links | .links()} builder method.
64
+ * Fields left `undefined` are derived from package.json metadata
65
+ * (`repository` / `homepage`) when `.packageJson()` is active.
66
+ */
67
+ readonly helpLinks: HelpLinks | undefined;
58
68
  /** Whether built-in `.completions()` command registration is active. */
59
69
  readonly hasBuiltInCompletions: boolean;
60
70
  /** Registered CLI plugins. */
@@ -96,6 +106,26 @@ interface PackageJsonSettings {
96
106
  * @defaultValue `false`
97
107
  */
98
108
  readonly inferName: boolean;
109
+ /**
110
+ * Explicit filesystem anchor for discovery; overrides `adapter.cwd`.
111
+ *
112
+ * Resolved to a string path before storage. When set, `discoverPackageJson`
113
+ * walks up from here instead of the runtime cwd. Required for installable
114
+ * CLIs whose version should reflect THEIR OWN package, not the consumer's
115
+ * working directory.
116
+ */
117
+ readonly from: string | undefined;
118
+ /**
119
+ * Pre-loaded data; skips filesystem discovery, uses values verbatim.
120
+ *
121
+ * @example
122
+ * ```ts
123
+ * import pkg from './package.json' with { type: 'json' };
124
+ *
125
+ * cli('mycli').packageJson(pkg);
126
+ * ```
127
+ */
128
+ readonly data: PackageJsonData | undefined;
99
129
  }
100
130
  /**
101
131
  * Options for {@linkcode CLIBuilder.execute | .execute()} and {@linkcode CLIBuilder.run | .run()}.
@@ -158,6 +188,48 @@ declare class CLIBuilder {
158
188
  * @returns The builder (for chaining).
159
189
  */
160
190
  description(text: string): CLIBuilder;
191
+ /**
192
+ * Make the root-help header clickable with OSC 8 hyperlinks.
193
+ *
194
+ * Links the program name and version on the first line of root `--help`
195
+ * output in terminals that support
196
+ * [OSC 8 hyperlinks](https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda).
197
+ * The escapes are only emitted when stdout is a TTY (overridable via
198
+ * `options.help.hyperlinks`), and only in the header — usage lines, the
199
+ * `--help` hint, the commands table, and completion scripts stay plain.
200
+ *
201
+ * URLs not provided here are derived from package.json metadata when
202
+ * `.packageJson()` is active (works with both filesystem discovery and
203
+ * pre-loaded data):
204
+ * - **name** → normalized `repository` URL, falling back to `homepage`
205
+ * - **version** → forge release tag (`{repo}/releases/tag/v{version}` on
206
+ * GitHub, `{repo}/-/releases/v{version}` on GitLab)
207
+ *
208
+ * @param links - Explicit URLs; omit to derive everything from package.json.
209
+ * @returns The builder (for chaining).
210
+ *
211
+ * @example
212
+ * ```ts
213
+ * // Derive both links from package.json repository/homepage:
214
+ * cli('mycli')
215
+ * .packageJson()
216
+ * .links()
217
+ * .run();
218
+ *
219
+ * // Explicit URLs (no package.json required):
220
+ * cli('mycli')
221
+ * .version('1.0.0')
222
+ * .links({
223
+ * name: 'https://github.com/me/mycli',
224
+ * version: 'https://github.com/me/mycli/releases/tag/v1.0.0',
225
+ * })
226
+ * .run();
227
+ * ```
228
+ */
229
+ links(links?: {
230
+ readonly name?: string | URL;
231
+ readonly version?: string | URL;
232
+ }): CLIBuilder;
161
233
  /**
162
234
  * Enable automatic config file discovery.
163
235
  *
@@ -219,6 +291,35 @@ declare class CLIBuilder {
219
291
  * ```
220
292
  */
221
293
  configLoader(loader: FormatLoader): CLIBuilder;
294
+ /**
295
+ * Enable package.json metadata from pre-loaded data.
296
+ *
297
+ * Pass an already-imported `package.json` to skip filesystem discovery
298
+ * entirely — useful for bundled or installable CLIs where the version
299
+ * should be locked at build time. The data's `version`/`description` are
300
+ * merged into the CLI schema immediately, so this form works in **both**
301
+ * `.run()` and `.execute()` (the filesystem-free path). Explicit
302
+ * `.version()`/`.description()` calls still take precedence, and the data
303
+ * form does not infer the CLI name.
304
+ *
305
+ * Detected by field shape: an object carrying at least one of
306
+ * `name`/`version`/`description`/`bin`. An empty `{}` or a settings-shaped
307
+ * object falls through to the settings overload.
308
+ *
309
+ * @param data - Pre-loaded `package.json` metadata.
310
+ *
311
+ * @example
312
+ * ```ts
313
+ * import pkg from './package.json' with { type: 'json' };
314
+ *
315
+ * // No filesystem; works in .run() AND .execute():
316
+ * cli('mycli')
317
+ * .packageJson(pkg)
318
+ * .command(deploy)
319
+ * .run();
320
+ * ```
321
+ */
322
+ packageJson(data: PackageJsonData): CLIBuilder;
222
323
  /**
223
324
  * Enable automatic package.json metadata discovery.
224
325
  *
@@ -227,10 +328,15 @@ declare class CLIBuilder {
227
328
  * into the CLI schema. Explicit `.version()` and `.description()`
228
329
  * calls always take precedence over discovered values.
229
330
  *
230
- * Has no effect in `.execute()` (which is filesystem-free by design).
331
+ * Has no effect in `.execute()` (which is filesystem-free by design) —
332
+ * use the {@link CLIBuilder.packageJson | data overload} for that.
231
333
  *
232
- * @param settings - Optional settings. Pass `{ inferName: true }` to
233
- * also infer the CLI name from `bin` keys or the package `name` field.
334
+ * @param settings - Optional settings:
335
+ * - `inferName`: also infer the CLI name from `bin` keys or `name` field.
336
+ * - `from`: anchor discovery to a specific file/URL/path instead of `cwd`.
337
+ * Pass `import.meta.url` for installable CLIs that need to report
338
+ * THEIR OWN version (not the consumer's project version). Accepts
339
+ * string paths, `file:` URL strings, or `URL` instances.
234
340
  *
235
341
  * @example
236
342
  * ```ts
@@ -246,6 +352,12 @@ declare class CLIBuilder {
246
352
  * .command(deploy)
247
353
  * .run();
248
354
  *
355
+ * // Installable CLI; discover OUR package.json, not the consumer's:
356
+ * cli('mycli')
357
+ * .packageJson({ from: import.meta.url })
358
+ * .command(deploy)
359
+ * .run();
360
+ *
249
361
  * // Explicit values always win:
250
362
  * cli('mycli')
251
363
  * .packageJson()
@@ -255,6 +367,7 @@ declare class CLIBuilder {
255
367
  */
256
368
  packageJson(settings?: {
257
369
  readonly inferName?: boolean;
370
+ readonly from?: string | URL;
258
371
  }): CLIBuilder;
259
372
  /**
260
373
  * Register a command with the CLI program.
@@ -415,4 +528,4 @@ declare function cli(name: string): CLIBuilder;
415
528
  /** Create a new CLI program builder from an options object. */
416
529
  declare function cli(options: CLIOptions): CLIBuilder;
417
530
  //#endregion
418
- export { type BeforeParseParams, CLIBuilder, type CLIOptions, type CLIPlugin, type CLIPluginHooks, type CLIRunOptions, type CLISchema, type ConfigSettings, type PackageJsonSettings, type PluginCommandContext, type ResolvedCommandParams, cli, formatRootHelp, plugin };
531
+ export { type BeforeParseParams, CLIBuilder, type CLIOptions, type CLIPlugin, type CLIPluginHooks, type CLIRunOptions, type CLISchema, type ConfigSettings, type HelpLinks, type PackageJsonSettings, type PluginCommandContext, type ResolvedCommandParams, cli, formatRootHelp, plugin };
@@ -1 +1 @@
1
- import{CLIError as e}from"../errors/index.mjs";import{SHELLS as t,generateCompletion as n}from"../completion/index.mjs";import{formatHelp as r}from"../help/index.mjs";import{buildRunResult as i,executeCommand as a}from"../execution/index.mjs";import{createCaptureOutput as o,createOutput as s}from"../output/index.mjs";import{arg as c}from"../schema/arg.mjs";import{command as l}from"../schema/command.mjs";import{runCommand as u}from"../testkit/index.mjs";import{createAdapter as d}from"../../runtime/auto.mjs";import{planInvocation as f}from"./planner.mjs";import"./plugin.mjs";import{formatRootHelp as p}from"./root-help.mjs";import{prepareRuntimePreflight as m}from"./runtime-preflight.mjs";function h(e){return[e.name,...e.aliases]}function g(t,n,r,i){let a=n.get(r);if(a!==void 0)throw new e(`Duplicate command route '${r}' under '${t}' (${a} and ${i})`,{code:`DUPLICATE_COMMAND`,suggest:`Ensure sibling command names and aliases are unique`});n.set(r,i)}function _(t,n){let r=new Map;for(let e of t)for(let t of h(e.schema))g(`root`,r,t,e.schema.name);for(let t of h(n)){let i=r.get(t);if(i!==void 0)throw new e(`Command route '${t}' is already registered by '${i}'`,{code:`DUPLICATE_COMMAND`,suggest:i===n.name?`Ensure command '${n.name}' does not reuse route '${t}'`:`Rename '${n.name}' or remove route '${t}' from '${i}'`});r.set(t,n.name)}}function v(e){let t=new Map,n=new Map;for(let r of e._subcommands){let i=h(r.schema);for(let t of i)g(e.schema.name,n,t,r.schema.name);let a=v(r);for(let e of i)t.set(e,a)}return{schema:e.schema,subcommands:t,_command:e,_execute(t,n){return u(e,t,n)}}}function y(e,t,n){return{help:t,...n===void 0?{}:{meta:n},...e?.plugins===void 0?{}:{plugins:e.plugins},...e?.env===void 0?{}:{env:e.env},...e?.config===void 0?{}:{config:e.config},...e?.stdinData===void 0?{}:{stdinData:e.stdinData},...e?.prompter===void 0?{}:{prompter:e.prompter},...e?.answers===void 0?{}:{answers:e.answers},...e?.verbosity===void 0?{}:{verbosity:e.verbosity},...e?.jsonMode===void 0?{}:{jsonMode:e.jsonMode},...e?.isTTY===void 0?{}:{isTTY:e.isTTY},...e?.out===void 0?{}:{out:e.out},...e?.captured===void 0?{}:{captured:e.captured}}}var b=class u{schema;constructor(e){this.schema=e}version(e){return new u({...this.schema,version:e})}description(e){return new u({...this.schema,description:e})}config(e,t){return new u({...this.schema,configSettings:{appName:e,loaders:t}})}configLoader(t){if(this.schema.configSettings===void 0)throw new e(`.configLoader() requires .config() to be called first`,{code:`INVALID_BUILDER_STATE`,suggest:`Call .config(appName) before .configLoader()`});let n=this.schema.configSettings.loaders??[];return new u({...this.schema,configSettings:{...this.schema.configSettings,loaders:[...n,t]}})}packageJson(e){return new u({...this.schema,packageJsonSettings:{inferName:e?.inferName??!1}})}command(e){return _(this.schema.commands,e.schema),new u({...this.schema,commands:[...this.schema.commands,v(e)]})}default(t){if(this.schema.defaultCommand!==void 0)throw new e(`Only one default command is allowed`,{code:`DUPLICATE_DEFAULT`,suggest:`Call .default() only once when building the CLI`});_(this.schema.commands,t.schema);let n=v(t);return new u({...this.schema,commands:[...this.schema.commands,n],defaultCommand:n})}plugin(e){return new u({...this.schema,plugins:[...this.schema.plugins,e]})}completions(r){if(this.schema.hasBuiltInCompletions)throw new e(`.completions() has already been called`,{code:`DUPLICATE_COMMAND`,suggest:`Call .completions() only once when building the CLI`});let i=this.schema,a=r,o=new Map;for(let e of t)o.set(e,e);o.set(`pwsh`,`powershell`);let s=l(`completions`).alias(`completion`).description(`Generate shell completion script`).arg(`shell`,c.custom(e=>{let n=e.split(/[\\/]/),r=(n[n.length-1]??e).replace(/\.(?:exe|cmd|bat)$/i,``),i=o.get(r);if(i===void 0)throw Error(`Unknown shell '${r}'. Valid shells: ${t.join(`, `)}`);return i}).env(`SHELL`).describe(`Target shell (${t.join(`, `)})`)).action(({args:e,meta:t,out:r})=>{let o=n(t.bin===i.name?i:{...i,name:t.bin},e.shell,a);r.jsonMode?r.json({shell:e.shell,script:o}):r.log(o)});return new u({...this.command(s).schema,hasBuiltInCompletions:!0})}async execute(e,t){let n=e.includes(`--json`)||t?.jsonMode===!0,s={...t?.verbosity===void 0?{}:{verbosity:t.verbosity},...n?{jsonMode:n}:{},...t?.isTTY===void 0?{}:{isTTY:t.isTTY}},c,l;t?.out===void 0?[c,l]=o(Object.keys(s).length>0?s:void 0):(c=t.out,l=t.captured??{stdout:[],stderr:[],activity:[]});let u={...t?.help,binName:t?.help?.binName??this.schema.name},d={...t,plugins:this.schema.plugins,...n?{jsonMode:n}:{}},m={jsonMode:n,isTTY:c.isTTY,verbosity:t?.verbosity??`normal`},h=f({schema:this.schema,argv:e,help:u,output:m});switch(h.kind){case`root-version`:return c.log(h.version),i({exitCode:0,error:void 0},l);case`root-help`:{let e=p(this.schema,h.help);return c.log(e),i({exitCode:0,error:void 0},l)}case`dispatch-error`:return n?c.json({error:h.error.toJSON()}):(c.error(h.error.message),h.error.suggest!==void 0&&h.error.code!==`NO_ACTION`&&c.error(`Suggestion: ${h.error.suggest}`)),i({exitCode:h.error.exitCode,error:h.error},l);case`needs-subcommand`:{let e=r(h.command.schema,h.help);return c.log(e),i({exitCode:0,error:void 0},l)}case`match`:{let e=y(d,h.plan.help??u,h.plan.meta);return h.plan.command._command===void 0?h.plan.command._execute(h.plan.argv,{...e,mergedSchema:h.plan.mergedSchema}):i(await a({command:h.plan.command._command,argv:h.plan.argv,out:c,schema:h.plan.mergedSchema,meta:h.plan.meta,options:e}),l)}}}async run(e){let t=e?.adapter??d(),n=this.schema.inheritName?w(t.argv):void 0,r=await m({schema:this.schema,adapter:t,options:e,inheritedName:n});if(r.kind===`config-error`)return r.jsonMode?t.stdout(`${JSON.stringify({error:r.error.toJSON()})}\n`):(t.stderr(`Error: ${r.error.message}\n`),r.error.suggest!==void 0&&t.stderr(`Suggestion: ${r.error.suggest}\n`)),t.exit(r.error.exitCode);let i=r.schema===this.schema?this:new u(r.schema),a={...e,...r.inputs,out:s({stdout:t.stdout,stderr:t.stderr,jsonMode:r.inputs.jsonMode,isTTY:r.inputs.isTTY,...r.inputs.verbosity===`normal`?{}:{verbosity:r.inputs.verbosity}})},o=await i.execute(r.filteredArgv,a);for(let e of o.stdout)t.stdout(e);for(let e of o.stderr)t.stderr(e);return t.exit(o.exitCode)}};const x=new Set([`bun`,`deno`,`node`,`tsx`]);function S(e){let t=e.replace(/[\\/]+$/g,``);if(t.length===0)return;let n=Math.max(t.lastIndexOf(`/`),t.lastIndexOf(`\\`)),r=n>=0?t.slice(n+1):t;return r.length>0?r:void 0}function C(e){let t=e.toLowerCase().replace(/\.exe$/i,``);return x.has(t)}function w(e){let t=e[0],n=e[1],r=t===void 0?void 0:S(t);if(r!==void 0&&C(r)){if(r===`bun`&&n===`run`){let t=e[2];return t===void 0||t.startsWith(`-`)?void 0:S(t)}return r===`deno`&&n===`run`||n===void 0||n.startsWith(`-`)?void 0:S(n)}return t===void 0?void 0:S(t)}function T(e){return new b({name:typeof e==`string`?e:e.name??`cli`,inheritName:typeof e==`string`?!1:e.inherit??!1,version:void 0,description:void 0,commands:[],defaultCommand:void 0,configSettings:void 0,packageJsonSettings:void 0,hasBuiltInCompletions:!1,plugins:[]})}export{b as CLIBuilder,T as cli};
1
+ import{CLIError as e}from"../errors/index.mjs";import{SHELLS as t,generateCompletion as n}from"../completion/index.mjs";import{formatHelp as r}from"../help/index.mjs";import{buildRunResult as i,executeCommand as a}from"../execution/index.mjs";import{createCaptureOutput as o,createOutput as s}from"../output/index.mjs";import{arg as c}from"../schema/arg.mjs";import{command as l}from"../schema/command.mjs";import{runCommand as u}from"../testkit/index.mjs";import{createAdapter as d}from"../../runtime/auto.mjs";import{deriveHelpLinks as f}from"./help-links.mjs";import{planInvocation as p}from"./planner.mjs";import"./plugin.mjs";import{formatRootHelp as m}from"./root-help.mjs";import{prepareRuntimePreflight as h}from"./runtime-preflight.mjs";function g(e){return[e.name,...e.aliases]}function _(t,n,r,i){let a=n.get(r);if(a!==void 0)throw new e(`Duplicate command route '${r}' under '${t}' (${a} and ${i})`,{code:`DUPLICATE_COMMAND`,suggest:`Ensure sibling command names and aliases are unique`});n.set(r,i)}function v(t,n){let r=new Map;for(let e of t)for(let t of g(e.schema))_(`root`,r,t,e.schema.name);for(let t of g(n)){let i=r.get(t);if(i!==void 0)throw new e(`Command route '${t}' is already registered by '${i}'`,{code:`DUPLICATE_COMMAND`,suggest:i===n.name?`Ensure command '${n.name}' does not reuse route '${t}'`:`Rename '${n.name}' or remove route '${t}' from '${i}'`});r.set(t,n.name)}}function y(e){let t=new Map,n=new Map;for(let r of e._subcommands){let i=g(r.schema);for(let t of i)_(e.schema.name,n,t,r.schema.name);let a=y(r);for(let e of i)t.set(e,a)}return{schema:e.schema,subcommands:t,_command:e,_execute(t,n){return u(e,t,n)}}}function b(e,t,n){return{help:t,...n===void 0?{}:{meta:n},...e?.plugins===void 0?{}:{plugins:e.plugins},...e?.env===void 0?{}:{env:e.env},...e?.config===void 0?{}:{config:e.config},...e?.stdinData===void 0?{}:{stdinData:e.stdinData},...e?.prompter===void 0?{}:{prompter:e.prompter},...e?.answers===void 0?{}:{answers:e.answers},...e?.verbosity===void 0?{}:{verbosity:e.verbosity},...e?.jsonMode===void 0?{}:{jsonMode:e.jsonMode},...e?.isTTY===void 0?{}:{isTTY:e.isTTY},...e?.out===void 0?{}:{out:e.out},...e?.captured===void 0?{}:{captured:e.captured}}}var x=class u{schema;constructor(e){this.schema=e}version(e){return new u({...this.schema,version:e})}description(e){return new u({...this.schema,description:e})}links(e){return new u({...this.schema,helpLinks:{name:E(e?.name),version:E(e?.version)}})}config(e,t){return new u({...this.schema,configSettings:{appName:e,loaders:t}})}configLoader(t){if(this.schema.configSettings===void 0)throw new e(`.configLoader() requires .config() to be called first`,{code:`INVALID_BUILDER_STATE`,suggest:`Call .config(appName) before .configLoader()`});let n=this.schema.configSettings.loaders??[];return new u({...this.schema,configSettings:{...this.schema.configSettings,loaders:[...n,t]}})}packageJson(e){return k(e)?new u({...this.schema,...this.schema.version===void 0&&e.version!==void 0?{version:e.version}:{},...this.schema.description===void 0&&e.description!==void 0?{description:e.description}:{},packageJsonSettings:{inferName:!1,from:void 0,data:e}}):new u({...this.schema,packageJsonSettings:{inferName:e?.inferName??!1,from:O(e?.from),data:void 0}})}command(e){return v(this.schema.commands,e.schema),new u({...this.schema,commands:[...this.schema.commands,y(e)]})}default(t){if(this.schema.defaultCommand!==void 0)throw new e(`Only one default command is allowed`,{code:`DUPLICATE_DEFAULT`,suggest:`Call .default() only once when building the CLI`});v(this.schema.commands,t.schema);let n=y(t);return new u({...this.schema,commands:[...this.schema.commands,n],defaultCommand:n})}plugin(e){return new u({...this.schema,plugins:[...this.schema.plugins,e]})}completions(r){if(this.schema.hasBuiltInCompletions)throw new e(`.completions() has already been called`,{code:`DUPLICATE_COMMAND`,suggest:`Call .completions() only once when building the CLI`});let i=this.schema,a=r,o=new Map;for(let e of t)o.set(e,e);o.set(`pwsh`,`powershell`);let s=l(`completions`).alias(`completion`).description(`Generate shell completion script`).arg(`shell`,c.custom(e=>{let n=e.split(/[\\/]/),r=(n[n.length-1]??e).replace(/\.(?:exe|cmd|bat)$/i,``),i=o.get(r);if(i===void 0)throw Error(`Unknown shell '${r}'. Valid shells: ${t.join(`, `)}`);return i}).env(`SHELL`).describe(`Target shell (${t.join(`, `)})`)).action(({args:e,meta:t,out:r})=>{let o=n(t.bin===i.name?i:{...i,name:t.bin},e.shell,a);r.jsonMode?r.json({shell:e.shell,script:o}):r.log(o)});return new u({...this.command(s).schema,hasBuiltInCompletions:!0})}async execute(e,t){let n=e.includes(`--json`)||t?.jsonMode===!0,s={...t?.verbosity===void 0?{}:{verbosity:t.verbosity},...n?{jsonMode:n}:{},...t?.isTTY===void 0?{}:{isTTY:t.isTTY}},c,l;t?.out===void 0?[c,l]=o(Object.keys(s).length>0?s:void 0):(c=t.out,l=t.captured??{stdout:[],stderr:[],activity:[]});let u={...t?.help,binName:t?.help?.binName??this.schema.name,hyperlinks:t?.help?.hyperlinks??c.isTTY},d={...t,plugins:this.schema.plugins,...n?{jsonMode:n}:{}},f={jsonMode:n,isTTY:c.isTTY,verbosity:t?.verbosity??`normal`},h=p({schema:this.schema,argv:e,help:u,output:f});switch(h.kind){case`root-version`:return c.log(h.version),i({exitCode:0,error:void 0},l);case`root-help`:{let e=m(D(this.schema),h.help);return c.log(e),i({exitCode:0,error:void 0},l)}case`dispatch-error`:return n?c.json({error:h.error.toJSON()}):(c.error(h.error.message),h.error.suggest!==void 0&&h.error.code!==`NO_ACTION`&&c.error(`Suggestion: ${h.error.suggest}`)),i({exitCode:h.error.exitCode,error:h.error},l);case`needs-subcommand`:{let e=r(h.command.schema,h.help);return c.log(e),i({exitCode:0,error:void 0},l)}case`match`:{let e=b(d,h.plan.help??u,h.plan.meta);return h.plan.command._command===void 0?h.plan.command._execute(h.plan.argv,{...e,mergedSchema:h.plan.mergedSchema}):i(await a({command:h.plan.command._command,argv:h.plan.argv,out:c,schema:h.plan.mergedSchema,meta:h.plan.meta,options:e}),l)}}}async run(e){let t=e?.adapter??d(),n=this.schema.inheritName?T(t.argv):void 0,r=await h({schema:this.schema,adapter:t,options:e,inheritedName:n});if(r.kind===`config-error`)return r.jsonMode?t.stdout(`${JSON.stringify({error:r.error.toJSON()})}\n`):(t.stderr(`Error: ${r.error.message}\n`),r.error.suggest!==void 0&&t.stderr(`Suggestion: ${r.error.suggest}\n`)),t.exit(r.error.exitCode);let i=r.schema===this.schema?this:new u(r.schema),a={...e,...r.inputs,out:s({stdout:t.stdout,stderr:t.stderr,jsonMode:r.inputs.jsonMode,isTTY:r.inputs.isTTY,...r.inputs.verbosity===`normal`?{}:{verbosity:r.inputs.verbosity}})},o=await i.execute(r.filteredArgv,a);for(let e of o.stdout)t.stdout(e);for(let e of o.stderr)t.stderr(e);return t.exit(o.exitCode)}};const S=new Set([`bun`,`deno`,`node`,`tsx`]);function C(e){let t=e.replace(/[\\/]+$/g,``);if(t.length===0)return;let n=Math.max(t.lastIndexOf(`/`),t.lastIndexOf(`\\`)),r=n>=0?t.slice(n+1):t;return r.length>0?r:void 0}function w(e){let t=e.toLowerCase().replace(/\.exe$/i,``);return S.has(t)}function T(e){let t=e[0],n=e[1],r=t===void 0?void 0:C(t);if(r!==void 0&&w(r)){if(r===`bun`&&n===`run`){let t=e[2];return t===void 0||t.startsWith(`-`)?void 0:C(t)}return r===`deno`&&n===`run`||n===void 0||n.startsWith(`-`)?void 0:C(n)}return t===void 0?void 0:C(t)}function E(e){if(e!==void 0)return e instanceof URL?e.href:e}function D(e){return e.helpLinks===void 0?e:{...e,helpLinks:f(e.helpLinks,e.packageJsonSettings?.data,e.version)}}function O(e){if(e===void 0)return;if(e instanceof URL){if(e.protocol!==`file:`)return e.href}else if(!e.startsWith(`file:`))return e;let t=decodeURIComponent(new URL(e).pathname);return/^\/[A-Za-z]:/.test(t)?t.slice(1).replace(/\//g,`\\`):t}function k(e){return typeof e!=`object`||!e||Array.isArray(e)?!1:`name`in e||`version`in e||`description`in e||`bin`in e||`homepage`in e||`repository`in e}function A(e){return new x({name:typeof e==`string`?e:e.name??`cli`,inheritName:typeof e==`string`?!1:e.inherit??!1,version:void 0,description:void 0,commands:[],defaultCommand:void 0,configSettings:void 0,packageJsonSettings:void 0,helpLinks:void 0,hasBuiltInCompletions:!1,plugins:[]})}export{x as CLIBuilder,A as cli};
@@ -13,6 +13,10 @@ interface CLISchemaLike {
13
13
  readonly defaultCommand: {
14
14
  readonly schema: CommandSchema;
15
15
  } | undefined;
16
+ readonly helpLinks?: {
17
+ readonly name: string | undefined;
18
+ readonly version: string | undefined;
19
+ } | undefined;
16
20
  }
17
21
  /**
18
22
  * Generate root-level help text for the CLI program.
@@ -1,7 +1,6 @@
1
- import{resolveRootSurface as e}from"./root-surface.mjs";import{formatHelpSections as t}from"../help/index.mjs";function n(n,a){let s=a?.width??80,c=e(n);if(c.hasSingleVisibleDefault){let e=c.visibleDefaultCommand;if(e!==void 0){let i=r(n,c.visibleCommands,c.visibleDefaultCommand,s),l=i.findIndex(e=>e.startsWith(`Usage: `)),u=[...t(e,{...a,binName:n.name,isDefaultHelp:!0})],d=u.shift();return l!==-1&&d!==void 0&&(i[l]=o(i[l]??``,d)),e.description!==void 0&&n.description!==void 0&&e.description===n.description&&u.shift(),i.push(...u),`${i.join(`
1
+ import{resolveRootSurface as e}from"./root-surface.mjs";import{osc8 as t,padEnd as n,wrapText as r}from"../help/ansi.mjs";import{formatHelpSections as i}from"../help/index.mjs";function a(t,n){let r=n?.width??80,a=n?.hyperlinks===!0,s=e(t);if(s.hasSingleVisibleDefault){let e=s.visibleDefaultCommand;if(e!==void 0){let c=o(t,s.visibleCommands,s.visibleDefaultCommand,r,a),l=c.findIndex(e=>e.startsWith(`Usage: `)),d=[...i(e,{...n,binName:t.name,isDefaultHelp:!0})],f=d.shift();return l!==-1&&f!==void 0&&(c[l]=u(c[l]??``,f)),e.description!==void 0&&t.description!==void 0&&e.description===t.description&&d.shift(),c.push(...d),`${c.join(`
2
2
 
3
- `)}\n`}}let l=r(n,c.visibleCommands,c.visibleDefaultCommand,s),u=i(c.visibleCommands,c.visibleDefaultCommand);return l.push(u.length>0?`Run '${n.name} ${u} --help' for more information.`:`Run '${n.name} --help' for more information.`),`${l.join(`
3
+ `)}\n`}}let l=o(t,s.visibleCommands,s.visibleDefaultCommand,r,a),d=c(s.visibleCommands,s.visibleDefaultCommand);return l.push(d.length>0?`Run '${t.name} ${d} --help' for more information.`:`Run '${t.name} --help' for more information.`),`${l.join(`
4
4
 
5
- `)}\n`}function r(e,t,n,r){let o=[],s=e.version===void 0?e.name:`${e.name} v${e.version}`;o.push(s),e.description!==void 0&&o.push(e.description);let c=i(t,n);return o.push(c.length>0?`Usage: ${e.name} ${c} [options]`:`Usage: ${e.name} [options]`),t.length>0&&o.push(a(t,n?.name,r)),o}function i(e,t){return e.length===0&&t===void 0?``:t===void 0?`<command>`:`[command]`}function a(e,t,n){let r=[`Commands:`],i=0;for(let n of e){let e=n.name===t?10:0,r=n.name.length+e;r>i&&(i=r)}let a=2+i+2;for(let i of e){let e=s(` ${i.name===t?`${i.name} (default)`:i.name}`,a),o=i.description??``;o.length===0?r.push(e.trimEnd()):r.push(`${e}${c(o,n,a)}`)}return r.join(`
6
- `)}function o(e,t){let n=t.startsWith(`Usage: `)?t.slice(7):t;return`${e}\n${` `.repeat(7)}${n}`}function s(e,t){return e.length>=t?e:e+` `.repeat(t-e.length)}function c(e,t,n){if(e.length+n<=t)return e;let r=t-n;if(r<=0)return e;let i=e.split(` `),a=[],o=``;for(let e of i)o.length===0?o=e:o.length+1+e.length<=r?o+=` ${e}`:(a.push(o),o=e);o.length>0&&a.push(o);let s=` `.repeat(n);return a.map((e,t)=>t===0?e:`${s}${e}`).join(`
7
- `)}export{n as formatRootHelp};
5
+ `)}\n`}function o(e,t,n,r,i){let a=[];a.push(s(e,i)),e.description!==void 0&&a.push(e.description);let o=c(t,n);return a.push(o.length>0?`Usage: ${e.name} ${o} [options]`:`Usage: ${e.name} [options]`),t.length>0&&a.push(l(t,n?.name,r)),a}function s(e,n){let r=n?e.helpLinks:void 0,i=r?.name===void 0?e.name:t(r.name,e.name);if(e.version===void 0)return i;let a=`v${e.version}`;return`${i} ${r?.version===void 0?a:t(r.version,a)}`}function c(e,t){return e.length===0&&t===void 0?``:t===void 0?`<command>`:`[command]`}function l(e,t,i){let a=[`Commands:`],o=0;for(let n of e){let e=n.name===t?10:0,r=n.name.length+e;r>o&&(o=r)}let s=2+o+2;for(let o of e){let e=n(` ${o.name===t?`${o.name} (default)`:o.name}`,s),c=o.description??``;c.length===0?a.push(e.trimEnd()):a.push(`${e}${r(c,i,s)}`)}return a.join(`
6
+ `)}function u(e,t){let n=t.startsWith(`Usage: `)?t.slice(7):t;return`${e}\n${` `.repeat(7)}${n}`}export{a as formatRootHelp};
@@ -4,6 +4,8 @@ import { CLIPlugin } from "./plugin.mjs";
4
4
  import { CLIError } from "../errors/index.mjs";
5
5
  import { CommandSchema, ErasedCommand } from "../schema/command.mjs";
6
6
  import { RuntimeAdapter } from "../../runtime/adapter.mjs";
7
+ import { PackageJsonData } from "../config/package-json.mjs";
8
+ import { HelpLinks } from "./help-links.mjs";
7
9
  import { FormatLoader } from "../config/index.mjs";
8
10
 
9
11
  //#region src/core/cli/runtime-preflight.d.ts
@@ -18,6 +20,10 @@ interface RuntimeConfigSettings {
18
20
  interface RuntimePackageJsonSettings {
19
21
  /** Whether to infer the CLI binary name from `package.json` `bin` field. */
20
22
  readonly inferName: boolean;
23
+ /** Explicit anchor (resolved path) for discovery; `undefined` falls back to `adapter.cwd`. */
24
+ readonly from: string | undefined;
25
+ /** Pre-loaded data; when set, discovery is skipped entirely. */
26
+ readonly data: PackageJsonData | undefined;
21
27
  }
22
28
  /**
23
29
  * Structural subset of CLISchema used by runtime preflight.
@@ -43,6 +49,8 @@ interface RuntimePreflightSchemaLike {
43
49
  readonly configSettings: RuntimeConfigSettings | undefined;
44
50
  /** Package.json discovery settings; `undefined` disables package.json inference. */
45
51
  readonly packageJsonSettings: RuntimePackageJsonSettings | undefined;
52
+ /** Root-help header link targets; `undefined` fields may be derived from package.json. */
53
+ readonly helpLinks: HelpLinks | undefined;
46
54
  /** Whether `.completions()` registered the built-in completions command. */
47
55
  readonly hasBuiltInCompletions: boolean;
48
56
  /** Plugins forwarded into the execution pipeline. */
@@ -1 +1 @@
1
- import{CLIError as e,ParseError as t}from"../errors/index.mjs";import{parse as n}from"../parse/index.mjs";import{createTerminalPrompter as r}from"../prompt/index.mjs";import{planInvocation as i}from"./planner.mjs";import{discoverPackageJson as a,inferCliName as o}from"../config/package-json.mjs";import{discoverConfig as s}from"../config/index.mjs";const c={jsonMode:!1,isTTY:!1,verbosity:`normal`};function l(e){let t=[],n;for(let r=0;r<e.length;r+=1){let i=e[r];if(i!==void 0){if(i===`--`){t.push(...e.slice(r));break}if(n===void 0&&i.startsWith(`--config=`)){let e=i.slice(9);if(e.length>0){n=e;continue}t.push(i);continue}if(n===void 0&&i===`--config`){let a=e[r+1];if(a!==void 0&&!a.startsWith(`-`)&&a!==`--`){n=a,r+=1;continue}t.push(i);continue}t.push(i)}}return{configPath:n,filteredArgv:t}}function u(e,r){if(r.includes(`--help`)||r.includes(`-h`))return!1;try{let t=n(e,r);return e.args.some(({name:e,schema:n})=>{let r=t.args[e];return n.stdinMode&&(r===void 0||r===`-`)})}catch(e){if(e instanceof t)return!1;throw e}}function d(e,t){let n=i({schema:e,argv:t,help:{binName:e.name},output:c});switch(n.kind){case`match`:return u(n.plan.mergedSchema,n.plan.argv);case`dispatch-error`:case`needs-subcommand`:case`root-help`:case`root-version`:return!1}}function f(e,t){if(!e.hasBuiltInCompletions)return!1;let n=i({schema:e,argv:t,help:{binName:e.name},output:c});return n.kind===`match`&&n.plan.command.schema.name===`completions`}async function p(e,t,n,r){let i=e.packageJsonSettings,s=i!==void 0&&!r?await(async()=>{let n=await a(t);if(n===null)return e;let r=i.inferName?o(n):void 0;return{...e,...e.version===void 0&&n.version!==void 0?{version:n.version}:{},...e.description===void 0&&n.description!==void 0?{description:n.description}:{},...r===void 0?{}:{name:r}}})():e;return n===void 0?s:{...s,name:n}}async function m(t,n,r,i,a){if(t.configSettings===void 0||i||a!==void 0)return a;try{let e=await s(t.configSettings.appName,n,{...r===void 0?{}:{configPath:r},...t.configSettings.loaders===void 0?{}:{loaders:t.configSettings.loaders}});return e.found?e.data:void 0}catch(t){if(t instanceof e)return t;throw t}}async function h(t){let n=t.adapter.argv.slice(2),{configPath:i,filteredArgv:a}=t.schema.configSettings===void 0?{configPath:void 0,filteredArgv:n}:l(n),o=a.includes(`--json`)||t.options?.jsonMode===!0,s=f(t.schema,a),c=await p(t.schema,t.adapter,t.inheritedName,s),u=await m(c,t.adapter,i,s,t.options?.config);if(u instanceof e)return{kind:`config-error`,error:u,jsonMode:o};let h=t.options?.prompter===void 0&&t.adapter.stdinIsTTY?r(t.adapter.stdin,t.adapter.stderr):void 0,g=t.options?.stdinData===void 0&&d(c,a)?await t.adapter.readStdin():t.options?.stdinData;return{kind:`ready`,schema:c,filteredArgv:a,inputs:{env:t.options?.env??t.adapter.env,isTTY:t.options?.isTTY??t.adapter.isTTY,jsonMode:o,verbosity:t.options?.verbosity??`normal`,...g===void 0?{}:{stdinData:g},...t.options?.prompter===void 0?h===void 0?{}:{prompter:h}:{prompter:t.options.prompter},...u===void 0?{}:{config:u}}}}export{h as prepareRuntimePreflight};
1
+ import{CLIError as e,ParseError as t}from"../errors/index.mjs";import{parse as n}from"../parse/index.mjs";import{createTerminalPrompter as r}from"../prompt/index.mjs";import{discoverPackageJson as i,inferCliName as a}from"../config/package-json.mjs";import{deriveHelpLinks as o}from"./help-links.mjs";import{planInvocation as s}from"./planner.mjs";import{discoverConfig as c}from"../config/index.mjs";const l={jsonMode:!1,isTTY:!1,verbosity:`normal`};function u(e){let t=[],n;for(let r=0;r<e.length;r+=1){let i=e[r];if(i!==void 0){if(i===`--`){t.push(...e.slice(r));break}if(n===void 0&&i.startsWith(`--config=`)){let e=i.slice(9);if(e.length>0){n=e;continue}t.push(i);continue}if(n===void 0&&i===`--config`){let a=e[r+1];if(a!==void 0&&!a.startsWith(`-`)&&a!==`--`){n=a,r+=1;continue}t.push(i);continue}t.push(i)}}return{configPath:n,filteredArgv:t}}function d(e,r){if(r.includes(`--help`)||r.includes(`-h`))return!1;try{let t=n(e,r);return e.args.some(({name:e,schema:n})=>{let r=t.args[e];return n.stdinMode&&(r===void 0||r===`-`)})}catch(e){if(e instanceof t)return!1;throw e}}function f(e,t){let n=s({schema:e,argv:t,help:{binName:e.name},output:l});switch(n.kind){case`match`:return d(n.plan.mergedSchema,n.plan.argv);case`dispatch-error`:case`needs-subcommand`:case`root-help`:case`root-version`:return!1}}function p(e,t){if(!e.hasBuiltInCompletions)return!1;let n=s({schema:e,argv:t,help:{binName:e.name},output:l});return n.kind===`match`&&n.plan.command.schema.name===`completions`}async function m(e,t,n,r){let s=e.packageJsonSettings,c=s!==void 0&&!r?await(async()=>{let n=s.data??await i(t,s.from);if(n===null)return e;let r=s.inferName?a(n):void 0;return{...e,...e.version===void 0&&n.version!==void 0?{version:n.version}:{},...e.description===void 0&&n.description!==void 0?{description:n.description}:{},...r===void 0?{}:{name:r},helpLinks:o(e.helpLinks,n,e.version??n.version)}})():e;return n===void 0?c:{...c,name:n}}async function h(t,n,r,i,a){if(t.configSettings===void 0||i||a!==void 0)return a;try{let e=await c(t.configSettings.appName,n,{...r===void 0?{}:{configPath:r},...t.configSettings.loaders===void 0?{}:{loaders:t.configSettings.loaders}});return e.found?e.data:void 0}catch(t){if(t instanceof e)return t;throw t}}async function g(t){let n=t.adapter.argv.slice(2),{configPath:i,filteredArgv:a}=t.schema.configSettings===void 0?{configPath:void 0,filteredArgv:n}:u(n),o=a.includes(`--json`)||t.options?.jsonMode===!0,s=p(t.schema,a),c=await m(t.schema,t.adapter,t.inheritedName,s),l=await h(c,t.adapter,i,s,t.options?.config);if(l instanceof e)return{kind:`config-error`,error:l,jsonMode:o};let d=t.options?.prompter===void 0&&t.adapter.stdinIsTTY?r(t.adapter.stdin,t.adapter.stderr):void 0,g=t.options?.stdinData===void 0&&f(c,a)?await t.adapter.readStdin():t.options?.stdinData;return{kind:`ready`,schema:c,filteredArgv:a,inputs:{env:t.options?.env??t.adapter.env,isTTY:t.options?.isTTY??t.adapter.isTTY,jsonMode:o,verbosity:t.options?.verbosity??`normal`,...g===void 0?{}:{stdinData:g},...t.options?.prompter===void 0?d===void 0?{}:{prompter:d}:{prompter:t.options.prompter},...l===void 0?{}:{config:l}}}}export{g as prepareRuntimePreflight};
@@ -1,5 +1,5 @@
1
1
  import { RuntimeAdapter } from "../../runtime/adapter.mjs";
2
- import { PackageJsonAdapter, PackageJsonData, discoverPackageJson, inferCliName } from "./package-json.mjs";
2
+ import { PackageJsonAdapter, PackageJsonData, PackageRepository, discoverPackageJson, inferCliName, packageRepositoryUrl } from "./package-json.mjs";
3
3
 
4
4
  //#region src/core/config/index.d.ts
5
5
  /**
@@ -158,4 +158,4 @@ declare function discoverConfig(appName: string, adapter: ConfigAdapter, options
158
158
  */
159
159
  declare function configFormat(extensions: readonly string[], parse: (content: string) => unknown): FormatLoader;
160
160
  //#endregion
161
- export { type ConfigAdapter, type ConfigDiscoveryOptions, type ConfigDiscoveryResult, type ConfigFound, type ConfigNotFound, type FormatLoader, type PackageJsonAdapter, type PackageJsonData, buildConfigSearchPaths, configFormat, discoverConfig, discoverPackageJson, inferCliName };
161
+ export { type ConfigAdapter, type ConfigDiscoveryOptions, type ConfigDiscoveryResult, type ConfigFound, type ConfigNotFound, type FormatLoader, type PackageJsonAdapter, type PackageJsonData, type PackageRepository, buildConfigSearchPaths, configFormat, discoverConfig, discoverPackageJson, inferCliName, packageRepositoryUrl };
@@ -1,6 +1,18 @@
1
1
  import { RuntimeAdapter } from "../../runtime/adapter.mjs";
2
2
 
3
3
  //#region src/core/config/package-json.d.ts
4
+ /**
5
+ * Object form of the package.json `repository` field
6
+ * (e.g. `{"type":"git","url":"git+https://github.com/u/r.git"}`).
7
+ */
8
+ interface PackageRepository {
9
+ /** Version control system type (usually `'git'`). */
10
+ readonly type?: string;
11
+ /** Repository URL or locator. */
12
+ readonly url?: string;
13
+ /** Subdirectory within a monorepo where the package lives. */
14
+ readonly directory?: string;
15
+ }
4
16
  /**
5
17
  * Subset of package.json fields relevant to CLI metadata.
6
18
  *
@@ -15,6 +27,10 @@ interface PackageJsonData {
15
27
  readonly description?: string;
16
28
  /** Binary entry point(s) — string for single-bin, object for multi-bin. */
17
29
  readonly bin?: string | Readonly<Record<string, string>>;
30
+ /** Project homepage URL. */
31
+ readonly homepage?: string;
32
+ /** Repository locator — URL/shorthand string or `{type, url, directory}` object. */
33
+ readonly repository?: string | PackageRepository;
18
34
  }
19
35
  /**
20
36
  * The subset of {@link RuntimeAdapter} needed for package.json discovery.
@@ -24,7 +40,8 @@ interface PackageJsonData {
24
40
  */
25
41
  type PackageJsonAdapter = Pick<RuntimeAdapter, 'readFile' | 'cwd'>;
26
42
  /**
27
- * Discover the nearest `package.json` by walking up from `adapter.cwd`.
43
+ * Discover the nearest `package.json` by walking up from `startDir` (or
44
+ * `adapter.cwd` when omitted).
28
45
  *
29
46
  * Convenience helper behind `CLIBuilder.packageJson()`. Most apps should let
30
47
  * the CLI runtime discover package metadata automatically; call this directly
@@ -34,6 +51,15 @@ type PackageJsonAdapter = Pick<RuntimeAdapter, 'readFile' | 'cwd'>;
34
51
  * is found (not an error). Malformed JSON and non-object roots also
35
52
  * return `null` — the feature is a convenience, not a hard requirement.
36
53
  *
54
+ * @param adapter - Adapter providing `readFile` + `cwd`.
55
+ * @param startDir - Optional explicit directory or file path to walk up from.
56
+ * Pass an absolute path inside your own package (e.g.
57
+ * `fileURLToPath(import.meta.url)`) when authoring an installable CLI whose
58
+ * version should reflect the CLI's own package, not the consumer's working
59
+ * directory. Defaults to `adapter.cwd` when `undefined`. A file path is
60
+ * probed as a directory first (yielding nothing) before the walk-up reaches
61
+ * its real parent directory, so passing `import.meta.url` resolves correctly.
62
+ *
37
63
  * @example
38
64
  * ```ts
39
65
  * import { discoverPackageJson } from '@kjanat/dreamcli';
@@ -44,7 +70,26 @@ type PackageJsonAdapter = Pick<RuntimeAdapter, 'readFile' | 'cwd'>;
44
70
  * }
45
71
  * ```
46
72
  */
47
- declare function discoverPackageJson(adapter: PackageJsonAdapter): Promise<PackageJsonData | null>;
73
+ declare function discoverPackageJson(adapter: PackageJsonAdapter, startDir?: string): Promise<PackageJsonData | null>;
74
+ /**
75
+ * Resolve a package's `repository` field to a browsable `https://` URL.
76
+ *
77
+ * Handles the locator formats npm accepts:
78
+ * - object form: `{ "type": "git", "url": "git+https://github.com/u/r.git" }`
79
+ * - `https`/`git`/`ssh` URLs (`git+` prefix and `.git` suffix stripped)
80
+ * - scp-style locators: `git@github.com:u/r.git`
81
+ * - shorthands: `github:u/r`, `gitlab:u/r`, `bitbucket:u/r`, and bare `u/r`
82
+ * (GitHub, per npm convention)
83
+ *
84
+ * Returns `undefined` when the field is absent or unrecognised.
85
+ *
86
+ * @example
87
+ * ```ts
88
+ * packageRepositoryUrl({ repository: 'git+https://github.com/u/r.git' });
89
+ * // 'https://github.com/u/r'
90
+ * ```
91
+ */
92
+ declare function packageRepositoryUrl(pkg: PackageJsonData): string | undefined;
48
93
  /**
49
94
  * Infer the CLI binary name from package.json data.
50
95
  *
@@ -65,4 +110,4 @@ declare function discoverPackageJson(adapter: PackageJsonAdapter): Promise<Packa
65
110
  */
66
111
  declare function inferCliName(pkg: PackageJsonData): string | undefined;
67
112
  //#endregion
68
- export { type PackageJsonAdapter, type PackageJsonData, discoverPackageJson, inferCliName };
113
+ export { type PackageJsonAdapter, type PackageJsonData, type PackageRepository, discoverPackageJson, inferCliName, packageRepositoryUrl };
@@ -1 +1 @@
1
- function e(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function t(e){let t=e.lastIndexOf(`/`),n=e.lastIndexOf(`\\`),r=Math.max(t,n),i=n>t?`\\`:`/`;if(r<0)return;if(r===0)return e.length>1?i:void 0;let a=e.slice(0,r);if(a.length===2&&a[1]===`:`){let t=`${a}${i}`;return t===e?void 0:t}return a}function n(e,t){let n=e.includes(`\\`)?`\\`:`/`;return e.endsWith(n)?`${e}${t}`:`${e}${n}${t}`}async function r(e){let r=e.cwd;for(;r!==void 0;){let a=null;try{a=await e.readFile(n(r,`package.json`))}catch{}if(a!==null){let e=i(a);if(e!==null)return e}r=t(r)}return null}function i(t){try{let n=JSON.parse(t);if(!e(n))return null;let r=typeof n.name==`string`?n.name:void 0,i=typeof n.version==`string`?n.version:void 0,o=typeof n.description==`string`?n.description:void 0,s=a(n.bin);return{...r===void 0?{}:{name:r},...i===void 0?{}:{version:i},...o===void 0?{}:{description:o},...s===void 0?{}:{bin:s}}}catch{return null}}function a(t){if(typeof t==`string`)return t;if(!e(t))return;let n={};for(let[e,r]of Object.entries(t)){if(typeof r!=`string`)return;n[e]=r}return n}function o(e){if(typeof e.bin==`object`){let t=Object.keys(e.bin);if(t.length>0&&t[0]!==void 0)return t[0]}if(e.name!==void 0){let t=e.name.indexOf(`/`);return t>=0?e.name.slice(t+1):e.name}}export{r as discoverPackageJson,o as inferCliName};
1
+ function e(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function t(e){let t=e.lastIndexOf(`/`),n=e.lastIndexOf(`\\`),r=Math.max(t,n),i=n>t?`\\`:`/`;if(r<0)return;if(r===0)return e.length>1?i:void 0;let a=e.slice(0,r);if(a.length===2&&a[1]===`:`){let t=`${a}${i}`;return t===e?void 0:t}return a}function n(e,t){let n=e.includes(`\\`)?`\\`:`/`;return e.endsWith(n)?`${e}${t}`:`${e}${n}${t}`}async function r(e,r){let a=r??e.cwd;for(;a!==void 0;){let r=null;try{r=await e.readFile(n(a,`package.json`))}catch{}if(r!==null){let e=i(r);if(e!==null)return e}a=t(a)}return null}function i(t){try{let n=JSON.parse(t);if(!e(n))return null;let r=typeof n.name==`string`?n.name:void 0,i=typeof n.version==`string`?n.version:void 0,s=typeof n.description==`string`?n.description:void 0,c=a(n.bin),l=typeof n.homepage==`string`?n.homepage:void 0,u=o(n.repository);return{...r===void 0?{}:{name:r},...i===void 0?{}:{version:i},...s===void 0?{}:{description:s},...c===void 0?{}:{bin:c},...l===void 0?{}:{homepage:l},...u===void 0?{}:{repository:u}}}catch{return null}}function a(t){if(typeof t==`string`)return t;if(!e(t))return;let n={};for(let[e,r]of Object.entries(t)){if(typeof r!=`string`)return;n[e]=r}return n}function o(t){if(typeof t==`string`)return t;if(!e(t))return;let n=typeof t.type==`string`?t.type:void 0,r=typeof t.url==`string`?t.url:void 0,i=typeof t.directory==`string`?t.directory:void 0;if(!(n===void 0&&r===void 0&&i===void 0))return{...n===void 0?{}:{type:n},...r===void 0?{}:{url:r},...i===void 0?{}:{directory:i}}}const s={github:`https://github.com`,gitlab:`https://gitlab.com`,bitbucket:`https://bitbucket.org`};function c(e){return e.endsWith(`.git`)?e.slice(0,-4):e}function l(e){let t=typeof e.repository==`string`?e.repository:e.repository?.url;if(t===void 0)return;let n=t.trim();if(n.length===0)return;let r=/^(github|gitlab|bitbucket):([^/]+\/[^/]+)$/.exec(n);if(r!==null&&r[1]!==void 0&&r[2]!==void 0){let e=s[r[1]];if(e!==void 0)return`${e}/${c(r[2])}`}if(/^[\w.-]+\/[\w.-]+$/.test(n))return`https://github.com/${c(n)}`;n.startsWith(`git+`)&&(n=n.slice(4));let i=/^git@([^:/]+):(.+)$/.exec(n);if(i!==null&&i[1]!==void 0&&i[2]!==void 0)return`https://${i[1]}/${c(i[2].replace(/\/+$/,``))}`;if(/^(?:https?|git|ssh):\/\//.test(n))try{let e=new URL(n),t=c(e.pathname.replace(/\/+$/,``));return`https://${e.hostname}${t}`}catch{return}}function u(e){if(typeof e.bin==`object`){let t=Object.keys(e.bin);if(t.length>0&&t[0]!==void 0)return t[0]}if(e.name!==void 0){let t=e.name.indexOf(`/`);return t>=0?e.name.slice(t+1):e.name}}export{r as discoverPackageJson,u as inferCliName,l as packageRepositoryUrl};
@@ -0,0 +1,78 @@
1
+ //#region src/core/help/ansi.d.ts
2
+ /**
3
+ * ANSI/OSC-aware text helpers for help formatting.
4
+ *
5
+ * Terminal escape sequences (SGR colors, OSC 8 hyperlinks) occupy zero
6
+ * columns when rendered, so width math must measure the *visible* text.
7
+ * {@linkcode visibleWidth} strips escapes before counting, and the shared
8
+ * {@linkcode padEnd}/{@linkcode wrapText} helpers build on it so aligned
9
+ * tables and wrapped lines stay intact when escapes are present.
10
+ *
11
+ * @module dreamcli/core/help/ansi
12
+ */
13
+ /**
14
+ * Remove ANSI CSI and OSC escape sequences from `text`.
15
+ *
16
+ * @param text - Text possibly containing terminal escapes.
17
+ * @returns The text with all escape sequences removed.
18
+ */
19
+ declare function stripAnsi(text: string): string;
20
+ /**
21
+ * Measure the visible column width of `text`, ignoring ANSI/OSC escapes.
22
+ *
23
+ * Escape sequences (SGR colors, OSC 8 hyperlinks) occupy zero columns when
24
+ * rendered, so `.length` overcounts whenever they are present. Help
25
+ * formatting uses this for padding and wrapping; exported for custom help
26
+ * renderers that mix colors or links into aligned output.
27
+ *
28
+ * @param text - Text possibly containing terminal escapes.
29
+ * @returns Number of visible characters.
30
+ *
31
+ * @example
32
+ * ```ts
33
+ * visibleWidth('plain'); // 5
34
+ * visibleWidth(osc8('https://x.dev', 'x')); // 1
35
+ * ```
36
+ */
37
+ declare function visibleWidth(text: string): number;
38
+ /**
39
+ * Wrap `text` in an [OSC 8 hyperlink](https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda)
40
+ * pointing at `url`.
41
+ *
42
+ * Supporting terminals render `text` as a clickable link; non-supporting
43
+ * terminals ignore the escape sequence and show plain text. Combine with
44
+ * {@linkcode visibleWidth}-aware formatting when embedding links in aligned
45
+ * output.
46
+ *
47
+ * @param url - Link target (string or `URL` instance).
48
+ * @param text - Visible link text.
49
+ * @returns The OSC 8 escape sequence wrapping `text`.
50
+ *
51
+ * @example
52
+ * ```ts
53
+ * cli('mycli').version(osc8('https://github.com/me/mycli/releases/tag/v1.0.0', '1.0.0'));
54
+ * ```
55
+ */
56
+ declare function osc8(url: string | URL, text: string): string;
57
+ /**
58
+ * Pad `text` to `length` visible columns with trailing spaces.
59
+ *
60
+ * @param text - The string to pad (may contain ANSI/OSC escapes).
61
+ * @param length - Target visible width in columns.
62
+ * @returns The padded string, unchanged if already at or beyond `length`.
63
+ */
64
+ declare function padEnd(text: string, length: number): string;
65
+ /**
66
+ * Wrap text to `width`, preserving leading indent on continuation lines.
67
+ *
68
+ * Line lengths are measured with {@linkcode visibleWidth}, so embedded
69
+ * ANSI/OSC escapes do not trigger premature wrapping.
70
+ *
71
+ * @param text - The text to wrap.
72
+ * @param width - Maximum line width in columns.
73
+ * @param indent - Number of leading spaces for continuation lines.
74
+ * @returns The wrapped string with newlines inserted as needed.
75
+ */
76
+ declare function wrapText(text: string, width: number, indent: number): string;
77
+ //#endregion
78
+ export { osc8, padEnd, stripAnsi, visibleWidth, wrapText };
@@ -0,0 +1,2 @@
1
+ const e=/\u001B(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001B]*(?:\u0007|\u001B\\))/g;function t(t){return t.replace(e,``)}function n(e){return t(e).length}function r(e,t){return`]8;;${e instanceof URL?e.href:e}${t}]8;;`}function i(e,t){let r=n(e);return r>=t?e:e+` `.repeat(t-r)}function a(e,t,r){if(n(e)+r<=t)return e;let i=t-r;if(i<=0)return e;let a=e.split(` `),o=[],s=``,c=0;for(let e of a){let t=n(e);s.length===0?(s=e,c=t):c+1+t<=i?(s+=` ${e}`,c+=1+t):(o.push(s),s=e,c=t)}s.length>0&&o.push(s);let l=` `.repeat(r);return o.map((e,t)=>t===0?e:`${l}${e}`).join(`
2
+ `)}export{r as osc8,i as padEnd,n as visibleWidth,a as wrapText};
@@ -1,3 +1,4 @@
1
+ import { osc8, visibleWidth } from "./ansi.mjs";
1
2
  import { CommandSchema } from "../schema/command.mjs";
2
3
 
3
4
  //#region src/core/help/index.d.ts
@@ -7,6 +8,13 @@ interface HelpOptions {
7
8
  readonly width?: number;
8
9
  /** Binary/program name shown in the usage line. Defaults to command name. */
9
10
  readonly binName?: string;
11
+ /**
12
+ * Emit OSC 8 hyperlinks where link metadata is available (currently the
13
+ * root-help header name/version configured via `CLIBuilder.links()`).
14
+ * Defaults to `false`; `CLIBuilder.execute()`/`.run()` enable it
15
+ * automatically when stdout is a TTY.
16
+ */
17
+ readonly hyperlinks?: boolean;
10
18
  /** @internal Whether this usage line is being rendered as merged root/default help. */
11
19
  readonly isDefaultHelp?: boolean;
12
20
  }
@@ -46,4 +54,4 @@ declare function formatHelpSections(schema: CommandSchema, options?: HelpOptions
46
54
  */
47
55
  declare function formatHelp(schema: CommandSchema, options?: HelpOptions): string;
48
56
  //#endregion
49
- export { type HelpOptions, formatHelp, formatHelpSections };
57
+ export { type HelpOptions, formatHelp, formatHelpSections, osc8, visibleWidth };