@hop-top/kit 0.4.0-alpha.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.
Files changed (174) hide show
  1. package/CHANGELOG.md +86 -0
  2. package/LICENSE +25 -0
  3. package/README.md +189 -0
  4. package/dist/aim.d.ts +116 -0
  5. package/dist/aim.js +417 -0
  6. package/dist/alias.d.ts +73 -0
  7. package/dist/alias.js +207 -0
  8. package/dist/api.d.ts +62 -0
  9. package/dist/api.js +165 -0
  10. package/dist/auth.d.ts +26 -0
  11. package/dist/auth.js +41 -0
  12. package/dist/cli.d.ts +309 -0
  13. package/dist/cli.js +885 -0
  14. package/dist/config.d.ts +97 -0
  15. package/dist/config.js +79 -0
  16. package/dist/errcorrect.d.ts +37 -0
  17. package/dist/errcorrect.js +69 -0
  18. package/dist/llm.d.ts +188 -0
  19. package/dist/llm.js +356 -0
  20. package/dist/output.d.ts +213 -0
  21. package/dist/output.js +447 -0
  22. package/dist/progress.d.ts +30 -0
  23. package/dist/progress.js +56 -0
  24. package/dist/provenance.d.ts +24 -0
  25. package/dist/provenance.js +32 -0
  26. package/dist/routellm.d.ts +64 -0
  27. package/dist/routellm.js +258 -0
  28. package/dist/rpc.d.ts +25 -0
  29. package/dist/rpc.js +101 -0
  30. package/dist/safety.d.ts +24 -0
  31. package/dist/safety.js +44 -0
  32. package/dist/scope.d.ts +121 -0
  33. package/dist/scope.js +380 -0
  34. package/dist/sqlstore.d.ts +84 -0
  35. package/dist/sqlstore.js +85 -0
  36. package/dist/stream.d.ts +35 -0
  37. package/dist/stream.js +52 -0
  38. package/dist/tui/index.d.ts +300 -0
  39. package/dist/tui/index.js +332 -0
  40. package/dist/upgrade.d.ts +95 -0
  41. package/dist/upgrade.js +115 -0
  42. package/dist/xdg.d.ts +169 -0
  43. package/dist/xdg.js +129 -0
  44. package/eslint.config.mjs +17 -0
  45. package/package.json +133 -0
  46. package/src/README.md +3 -0
  47. package/src/aim.test.ts +331 -0
  48. package/src/aim.ts +388 -0
  49. package/src/alias.test.ts +423 -0
  50. package/src/alias.ts +256 -0
  51. package/src/api.test.ts +190 -0
  52. package/src/api.ts +214 -0
  53. package/src/auth.test.ts +24 -0
  54. package/src/auth.ts +37 -0
  55. package/src/bus.test.ts +178 -0
  56. package/src/bus.ts +114 -0
  57. package/src/cli.test.ts +690 -0
  58. package/src/cli.ts +741 -0
  59. package/src/completion-values.test.ts +202 -0
  60. package/src/completion-values.ts +173 -0
  61. package/src/completion.test.ts +212 -0
  62. package/src/completion.ts +158 -0
  63. package/src/compliance.test.ts +134 -0
  64. package/src/compliance.ts +669 -0
  65. package/src/config.test.ts +110 -0
  66. package/src/config.ts +164 -0
  67. package/src/errcorrect.test.ts +134 -0
  68. package/src/errcorrect.ts +84 -0
  69. package/src/flagregister.test.ts +103 -0
  70. package/src/flagregister.ts +78 -0
  71. package/src/gen/crud_connect.ts +76 -0
  72. package/src/gen/crud_pb.ts +269 -0
  73. package/src/hint.test.ts +315 -0
  74. package/src/hint.ts +178 -0
  75. package/src/llm.test.ts +612 -0
  76. package/src/llm.ts +577 -0
  77. package/src/log.test.ts +145 -0
  78. package/src/log.ts +155 -0
  79. package/src/output/builtins.ts +34 -0
  80. package/src/output/dispatch.ts +195 -0
  81. package/src/output/flags.ts +151 -0
  82. package/src/output/format_help.ts +80 -0
  83. package/src/output/formatter.ts +167 -0
  84. package/src/output/formatters/csv.ts +72 -0
  85. package/src/output/formatters/json.ts +44 -0
  86. package/src/output/formatters/table.ts +44 -0
  87. package/src/output/formatters/text.ts +109 -0
  88. package/src/output/formatters/yaml.ts +47 -0
  89. package/src/output/projection.ts +126 -0
  90. package/src/output/registry.ts +88 -0
  91. package/src/output/template.ts +63 -0
  92. package/src/output.test.ts +117 -0
  93. package/src/output.ts +90 -0
  94. package/src/progress.test.ts +93 -0
  95. package/src/progress.ts +58 -0
  96. package/src/provenance.test.ts +59 -0
  97. package/src/provenance.ts +26 -0
  98. package/src/routellm.test.ts +179 -0
  99. package/src/routellm.ts +365 -0
  100. package/src/router/bert.test.ts +180 -0
  101. package/src/router/bert.ts +145 -0
  102. package/src/router/controller.test.ts +183 -0
  103. package/src/router/controller.ts +165 -0
  104. package/src/router/integration.test.ts +309 -0
  105. package/src/router/intent.test.ts +187 -0
  106. package/src/router/intent.ts +208 -0
  107. package/src/router/mf.test.ts +66 -0
  108. package/src/router/mf.ts +52 -0
  109. package/src/router/random.test.ts +23 -0
  110. package/src/router/random.ts +13 -0
  111. package/src/router/router.test.ts +31 -0
  112. package/src/router/router.ts +62 -0
  113. package/src/router/server.test.ts +193 -0
  114. package/src/router/server.ts +134 -0
  115. package/src/router/sw.test.ts +199 -0
  116. package/src/router/sw.ts +232 -0
  117. package/src/rpc.test.ts +47 -0
  118. package/src/rpc.ts +91 -0
  119. package/src/safety.test.ts +53 -0
  120. package/src/safety.ts +42 -0
  121. package/src/scope-defaults.json +72 -0
  122. package/src/scope.test.ts +177 -0
  123. package/src/scope.ts +382 -0
  124. package/src/setflag.test.ts +110 -0
  125. package/src/setflag.ts +102 -0
  126. package/src/sqlstore.test.ts +110 -0
  127. package/src/sqlstore.ts +144 -0
  128. package/src/stream.test.ts +69 -0
  129. package/src/stream.ts +47 -0
  130. package/src/textflag.test.ts +105 -0
  131. package/src/textflag.ts +68 -0
  132. package/src/toolspec.test.ts +187 -0
  133. package/src/toolspec.ts +279 -0
  134. package/src/triton/client.test.ts +205 -0
  135. package/src/triton/client.ts +261 -0
  136. package/src/tui/anim.test.ts +146 -0
  137. package/src/tui/anim.ts +134 -0
  138. package/src/tui/badge.test.ts +41 -0
  139. package/src/tui/badge.ts +55 -0
  140. package/src/tui/confirm.test.ts +68 -0
  141. package/src/tui/confirm.ts +49 -0
  142. package/src/tui/index.ts +29 -0
  143. package/src/tui/list.test.ts +84 -0
  144. package/src/tui/list.ts +72 -0
  145. package/src/tui/parity.ts +41 -0
  146. package/src/tui/pills.test.ts +40 -0
  147. package/src/tui/pills.ts +43 -0
  148. package/src/tui/progress.test.ts +164 -0
  149. package/src/tui/progress.ts +120 -0
  150. package/src/tui/spinner.test.ts +111 -0
  151. package/src/tui/spinner.ts +96 -0
  152. package/src/tui/status.test.ts +68 -0
  153. package/src/tui/status.ts +66 -0
  154. package/src/upgrade.test.ts +298 -0
  155. package/src/upgrade.ts +205 -0
  156. package/src/uri.ts +199 -0
  157. package/src/wizard.test.ts +441 -0
  158. package/src/wizard.ts +662 -0
  159. package/src/xdg.test.ts +202 -0
  160. package/src/xdg.ts +280 -0
  161. package/test/output/cols.test.ts +148 -0
  162. package/test/output/csv.test.ts +129 -0
  163. package/test/output/dispatch.test.ts +194 -0
  164. package/test/output/format_help.test.ts +131 -0
  165. package/test/output/formatter.test.ts +137 -0
  166. package/test/output/output_flag.test.ts +124 -0
  167. package/test/output/registry.test.ts +127 -0
  168. package/test/output/smoke-capture.ts +83 -0
  169. package/test/output/smoke.test.ts +142 -0
  170. package/test/output/template.test.ts +95 -0
  171. package/test/output/text.test.ts +75 -0
  172. package/test/testdata/api-fixture.json +115 -0
  173. package/test/testdata/query-vectors.json +187 -0
  174. package/tsconfig.json +12 -0
package/src/log.ts ADDED
@@ -0,0 +1,155 @@
1
+ /**
2
+ * Structured logger wrapping pino — applies kit's charmtone theme
3
+ * colors to stderr output.
4
+ *
5
+ * API: `logger.info('msg', 'key', val, 'key2', val2)` (variadic key-value)
6
+ * This matches Go's charm/log API, not pino's native object API.
7
+ * Pino handles transports, serialization, and performance under the hood.
8
+ */
9
+
10
+ import pino from 'pino';
11
+
12
+ // ---------------------------------------------------------------------------
13
+ // Types
14
+ // ---------------------------------------------------------------------------
15
+
16
+ export interface Logger {
17
+ info(msg: string, ...keyvals: any[]): void;
18
+ warn(msg: string, ...keyvals: any[]): void;
19
+ error(msg: string, ...keyvals: any[]): void;
20
+ debug(msg: string, ...keyvals: any[]): void;
21
+ trace(msg: string, ...keyvals: any[]): void;
22
+ }
23
+
24
+ export interface LoggerOptions {
25
+ quiet?: boolean;
26
+ noColor?: boolean;
27
+ }
28
+
29
+ // ---------------------------------------------------------------------------
30
+ // Theme — charmtone palette (matches Go kit/log)
31
+ // ---------------------------------------------------------------------------
32
+
33
+ const CHERRY = [0xed, 0x4a, 0x5e] as const;
34
+ const YAM = [0xe5, 0xa1, 0x4e] as const;
35
+ const SQUID = [0x85, 0x81, 0x83] as const;
36
+ const SMOKE = [0xbf, 0xbc, 0xc8] as const;
37
+
38
+ type RGB = readonly [number, number, number];
39
+
40
+ function fg(rgb: RGB, text: string): string {
41
+ return `\x1b[38;2;${rgb[0]};${rgb[1]};${rgb[2]}m${text}\x1b[0m`;
42
+ }
43
+
44
+ function bold(text: string): string {
45
+ return `\x1b[1m${text}\x1b[22m`;
46
+ }
47
+
48
+ // ---------------------------------------------------------------------------
49
+ // Kit-themed pino transport
50
+ // ---------------------------------------------------------------------------
51
+
52
+ const LEVEL_STYLES: Record<number, { label: string; color: RGB; bold: boolean }> = {
53
+ 10: { label: 'TRAC', color: SMOKE, bold: false },
54
+ 20: { label: 'DEBU', color: SMOKE, bold: false },
55
+ 30: { label: 'INFO', color: SQUID, bold: false },
56
+ 40: { label: 'WARN', color: YAM, bold: true },
57
+ 50: { label: 'ERRO', color: CHERRY, bold: true },
58
+ 60: { label: 'ERRO', color: CHERRY, bold: true },
59
+ };
60
+
61
+ function kitTransport(noColor: boolean): pino.DestinationStream {
62
+ return {
63
+ write(chunk: string): void {
64
+ try {
65
+ const obj = JSON.parse(chunk);
66
+ const style = LEVEL_STYLES[obj.level] ?? LEVEL_STYLES[30];
67
+ let prefix = noColor ? style.label : fg(style.color, style.label);
68
+ if (style.bold && !noColor) prefix = bold(prefix);
69
+
70
+ const msg = obj.msg ?? '';
71
+ const kvParts: string[] = [];
72
+ for (const [k, v] of Object.entries(obj)) {
73
+ if (['level', 'time', 'pid', 'hostname', 'msg', 'v'].includes(k)) continue;
74
+ const sv = String(v);
75
+ kvParts.push(sv.includes(' ') ? `${k}="${sv}"` : `${k}=${sv}`);
76
+ }
77
+ const kv = kvParts.length ? ' ' + kvParts.join(' ') : '';
78
+ process.stderr.write(`${prefix} ${msg}${kv}\n`);
79
+ } catch {
80
+ process.stderr.write(chunk);
81
+ }
82
+ },
83
+ };
84
+ }
85
+
86
+ // ---------------------------------------------------------------------------
87
+ // Variadic key-value → pino object adapter
88
+ // ---------------------------------------------------------------------------
89
+
90
+ function kvToObj(keyvals: any[]): Record<string, any> {
91
+ const obj: Record<string, any> = {};
92
+ for (let i = 0; i < keyvals.length; i += 2) {
93
+ const key = String(keyvals[i]);
94
+ obj[key] = i + 1 < keyvals.length ? keyvals[i + 1] : '';
95
+ }
96
+ return obj;
97
+ }
98
+
99
+ // ---------------------------------------------------------------------------
100
+ // Factory
101
+ // ---------------------------------------------------------------------------
102
+
103
+ export function createLogger(opts?: LoggerOptions): Logger {
104
+ const quiet = opts?.quiet ?? false;
105
+ const noColor = opts?.noColor ?? false;
106
+
107
+ const p = pino({
108
+ level: quiet ? 'warn' : 'debug',
109
+ }, kitTransport(noColor));
110
+
111
+ return {
112
+ info: (msg, ...kv) => p.info(kvToObj(kv), msg),
113
+ warn: (msg, ...kv) => p.warn(kvToObj(kv), msg),
114
+ error: (msg, ...kv) => p.error(kvToObj(kv), msg),
115
+ debug: (msg, ...kv) => p.debug(kvToObj(kv), msg),
116
+ trace: (msg, ...kv) => p.trace(kvToObj(kv), msg),
117
+ };
118
+ }
119
+
120
+ // ---------------------------------------------------------------------------
121
+ // Verbose-aware factory
122
+ // ---------------------------------------------------------------------------
123
+
124
+ /**
125
+ * Map verbose count to pino level: 0=info, 1=debug, 2+=trace.
126
+ * Quiet overrides to warn regardless of verbose count.
127
+ */
128
+ export function withVerbose(
129
+ opts: LoggerOptions & { verbose?: number },
130
+ ): Logger {
131
+ const quiet = opts.quiet ?? false;
132
+ const noColor = opts.noColor ?? false;
133
+ const v = opts.verbose ?? 0;
134
+
135
+ let level: string;
136
+ if (quiet) {
137
+ level = 'warn';
138
+ } else if (v >= 2) {
139
+ level = 'trace';
140
+ } else if (v >= 1) {
141
+ level = 'debug';
142
+ } else {
143
+ level = 'info';
144
+ }
145
+
146
+ const p = pino({ level }, kitTransport(noColor));
147
+
148
+ return {
149
+ info: (msg, ...kv) => p.info(kvToObj(kv), msg),
150
+ warn: (msg, ...kv) => p.warn(kvToObj(kv), msg),
151
+ error: (msg, ...kv) => p.error(kvToObj(kv), msg),
152
+ debug: (msg, ...kv) => p.debug(kvToObj(kv), msg),
153
+ trace: (msg, ...kv) => p.trace(kvToObj(kv), msg),
154
+ };
155
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * @module output/builtins
3
+ *
4
+ * Registers built-in formatters against defaultRegistry at module-load.
5
+ * Importing this module triggers registration as a side effect — same
6
+ * init-time guarantee Go achieves via init() functions.
7
+ */
8
+
9
+ import { defaultRegistry } from './registry';
10
+ import { jsonFormatter } from './formatters/json';
11
+ import { yamlFormatter } from './formatters/yaml';
12
+ import { tableFormatter } from './formatters/table';
13
+ import { csvFormatter } from './formatters/csv';
14
+ import { textFormatter } from './formatters/text';
15
+
16
+ let registered = false;
17
+
18
+ /**
19
+ * Register the built-in formatters (json, yaml, table, csv, text) against
20
+ * defaultRegistry. Idempotent — safe to call from multiple entry points.
21
+ */
22
+ export function registerBuiltins(): void {
23
+ if (registered) return;
24
+ defaultRegistry.register(jsonFormatter);
25
+ defaultRegistry.register(yamlFormatter);
26
+ defaultRegistry.register(tableFormatter);
27
+ defaultRegistry.register(csvFormatter);
28
+ defaultRegistry.register(textFormatter);
29
+ registered = true;
30
+ }
31
+
32
+ // Side-effect: register on import so adopters that pull anything from
33
+ // @hop-top/kit/output get the built-ins ready.
34
+ registerBuiltins();
@@ -0,0 +1,195 @@
1
+ /**
2
+ * @module output/dispatch
3
+ *
4
+ * Resolves the active output flags from a Commander Command and renders
5
+ * data, honoring --format, --format-opt, --cols/--columns, --template,
6
+ * --format-help, and --output|-o per the rules wired by registerOutputFlags.
7
+ *
8
+ * Mirrors Go's output.Dispatch.
9
+ */
10
+
11
+ import type { Command } from 'commander';
12
+ import { createWriteStream } from 'node:fs';
13
+ import { extname } from 'node:path';
14
+ import type { ColumnSpec, Formatter } from './formatter';
15
+ import { parseOptions } from './formatter';
16
+ import { registryFor, resolveCols } from './flags';
17
+ import { renderFormatHelp } from './format_help';
18
+ import { validateCols } from './projection';
19
+ import { renderTemplate } from './template';
20
+
21
+ /** Sentinel value of --output meaning "write to stdout". */
22
+ const STDOUT_SENTINEL = '-';
23
+
24
+ /** Optional inputs to dispatch. */
25
+ export interface DispatchOptions<T = unknown> {
26
+ /** ColumnSpec list for projection + --cols validation. */
27
+ columns?: readonly ColumnSpec[];
28
+ /** Override registry (default: registry stashed on cmd, else defaultRegistry). */
29
+ registry?: import('./registry').Registry;
30
+ /** Default format when --format isn't explicit (default: "table"). */
31
+ defaultFormat?: string;
32
+ // Phantom T for caller type inference.
33
+ _phantom?: T;
34
+ }
35
+
36
+ /**
37
+ * Renders `data` through the active formatter resolved from cmd's flags.
38
+ *
39
+ * Resolution order:
40
+ * 1. Resolve writer: empty/'-' → cmd.stdout (process.stdout), else file.
41
+ * 2. --format-help short-circuit: list registry or show one formatter.
42
+ * 3. Resolve format: explicit --format wins; else infer from --output ext.
43
+ * 4. Mismatch detection: explicit --format + ext mapping to different
44
+ * formatter is a hard error.
45
+ * 5. --template: build {items, cols} input, run eta, return.
46
+ * 6. Else: parseOptions, validateCols, formatter.render.
47
+ */
48
+ export async function dispatch<T>(
49
+ cmd: Command,
50
+ data: T | readonly T[],
51
+ options: DispatchOptions<T> = {},
52
+ ): Promise<void> {
53
+ const opts = cmd.optsWithGlobals
54
+ ? cmd.optsWithGlobals()
55
+ : (cmd as { opts(): Record<string, unknown> }).opts();
56
+ const registry = options.registry ?? registryFor(cmd);
57
+ const defaultFormat = options.defaultFormat ?? 'table';
58
+
59
+ // 1. Writer.
60
+ const path =
61
+ typeof opts['output'] === 'string' ? (opts['output'] as string) : '';
62
+ const { writer, close } = await resolveWriter(path);
63
+
64
+ try {
65
+ // 2. --format-help short-circuit.
66
+ const fhVal = opts['formatHelp'];
67
+ if (fhVal !== undefined && fhVal !== false) {
68
+ // commander stores [fmt] as: `true` when bare, string when value supplied.
69
+ const explicitKey = typeof fhVal === 'string' ? fhVal : '';
70
+ const formatChanged = isFormatExplicit(cmd);
71
+ const key = explicitKey || (formatChanged ? String(opts['format'] ?? '') : '');
72
+ renderFormatHelp(writer, registry, key);
73
+ return;
74
+ }
75
+
76
+ // 3 + 4. Format resolution.
77
+ const format = resolveFormat(cmd, opts, registry, path, defaultFormat);
78
+
79
+ // 5. Template escape hatch.
80
+ const tmplSrc =
81
+ typeof opts['template'] === 'string' ? (opts['template'] as string) : '';
82
+ const cols = resolveCols(opts);
83
+ if (tmplSrc) {
84
+ if (cols.length > 0) {
85
+ throw new Error('--template and --cols are mutually exclusive');
86
+ }
87
+ await renderTemplate(writer, tmplSrc, data, options.columns);
88
+ return;
89
+ }
90
+
91
+ // 6. Formatter render.
92
+ const formatter = registry.lookup(format);
93
+ if (!formatter) {
94
+ throw new Error(
95
+ `unknown output format "${format}" (valid: ${registry.keys().join(', ')})`,
96
+ );
97
+ }
98
+ const formatOpt = (opts['formatOpt'] as string[]) ?? [];
99
+ const parsedOpts = parseOptions(formatOpt, formatter.options);
100
+ if (cols.length > 0) {
101
+ const rows = Array.isArray(data) ? (data as readonly unknown[]) : [data];
102
+ validateCols(rows, options.columns, cols);
103
+ }
104
+ await Promise.resolve(
105
+ (formatter as Formatter).render(writer, data as never, parsedOpts, cols),
106
+ );
107
+ } finally {
108
+ if (close) await close();
109
+ }
110
+ }
111
+
112
+ interface ResolvedWriter {
113
+ writer: NodeJS.WritableStream;
114
+ close: (() => Promise<void>) | null;
115
+ }
116
+
117
+ async function resolveWriter(path: string): Promise<ResolvedWriter> {
118
+ if (!path || path === STDOUT_SENTINEL) {
119
+ return { writer: process.stdout, close: null };
120
+ }
121
+ const stream = createWriteStream(path, { flags: 'w', mode: 0o644 });
122
+ // Catch open errors (ENOENT for missing dir, EACCES, etc).
123
+ await new Promise<void>((resolve, reject) => {
124
+ const onErr = (err: Error) => {
125
+ stream.removeListener('open', onOpen);
126
+ reject(new Error(`open output "${path}": ${err.message}`));
127
+ };
128
+ const onOpen = () => {
129
+ stream.removeListener('error', onErr);
130
+ resolve();
131
+ };
132
+ stream.once('error', onErr);
133
+ stream.once('open', onOpen);
134
+ });
135
+ return {
136
+ writer: stream,
137
+ close: () =>
138
+ new Promise<void>((resolve, reject) => {
139
+ stream.end((err?: Error | null) => (err ? reject(err) : resolve()));
140
+ }),
141
+ };
142
+ }
143
+
144
+ /** Returns true if --format was explicitly set on the command line. */
145
+ function isFormatExplicit(cmd: Command): boolean {
146
+ // Commander's `getOptionValueSourceWithGlobals` reports the source.
147
+ type WithSource = {
148
+ getOptionValueSourceWithGlobals?(name: string): string | undefined;
149
+ getOptionValueSource?(name: string): string | undefined;
150
+ };
151
+ const c = cmd as unknown as WithSource;
152
+ const src =
153
+ c.getOptionValueSourceWithGlobals?.('format') ??
154
+ c.getOptionValueSource?.('format');
155
+ return src === 'cli';
156
+ }
157
+
158
+ /** Resolves the active format key honoring explicit > extension > default. */
159
+ function resolveFormat(
160
+ cmd: Command,
161
+ opts: Record<string, unknown>,
162
+ registry: import('./registry').Registry,
163
+ path: string,
164
+ defaultFormat: string,
165
+ ): string {
166
+ const format = (opts['format'] as string | undefined) || defaultFormat;
167
+ const explicit = isFormatExplicit(cmd);
168
+
169
+ if (!path || path === STDOUT_SENTINEL) return format;
170
+
171
+ const ext = extname(path).toLowerCase();
172
+ if (!ext) return format;
173
+
174
+ const mapped = registry.extensionMap().get(ext);
175
+ if (!mapped) return format;
176
+
177
+ if (!explicit) return mapped;
178
+ if (mapped !== format) {
179
+ const primary = primaryExt(registry, format);
180
+ throw new Error(
181
+ `format "${format}" does not match output extension "${ext}" ` +
182
+ `(use -o file${primary} or --format ${mapped})`,
183
+ );
184
+ }
185
+ return format;
186
+ }
187
+
188
+ function primaryExt(
189
+ registry: import('./registry').Registry,
190
+ key: string,
191
+ ): string {
192
+ const f = registry.lookup(key);
193
+ if (!f) return `.${key}`;
194
+ return f.extensions[0] ?? `.${key}`;
195
+ }
@@ -0,0 +1,151 @@
1
+ /**
2
+ * @module output/flags
3
+ *
4
+ * Commander integration: registerOutputFlags adds the standard output
5
+ * flag suite (--format, --format-opt, --format-help, --cols, --template,
6
+ * --output|-o) to a Commander program. Mirrors Go's RegisterFlagsWith.
7
+ */
8
+
9
+ import type { Command } from 'commander';
10
+ import { Registry, defaultRegistry } from './registry';
11
+
12
+ /** Internal stash mapping a Commander program → Registry. */
13
+ const registryStash = new WeakMap<Command, Registry>();
14
+
15
+ /** Returns the Registry attached to cmd (walks parents) or defaultRegistry. */
16
+ export function registryFor(cmd: Command): Registry {
17
+ for (let c: Command | null = cmd; c; c = (c as { parent?: Command | null }).parent ?? null) {
18
+ const r = registryStash.get(c);
19
+ if (r) return r;
20
+ }
21
+ return defaultRegistry;
22
+ }
23
+
24
+ /** Options for registerOutputFlags. */
25
+ export interface RegisterOutputFlagsOptions {
26
+ /** Custom registry (default: defaultRegistry). */
27
+ registry?: Registry;
28
+ /** Per-flag opt-out. */
29
+ disable?: {
30
+ format?: boolean;
31
+ formatOpt?: boolean;
32
+ formatHelp?: boolean;
33
+ cols?: boolean;
34
+ template?: boolean;
35
+ output?: boolean;
36
+ };
37
+ }
38
+
39
+ /**
40
+ * Adds the output flag suite to a Commander program. Each flag is opt-out
41
+ * via `opts.disable.<flag>`. The active registry can be swapped via
42
+ * `opts.registry`; tests + multi-CLI binaries use this for isolated sets.
43
+ */
44
+ export function registerOutputFlags(
45
+ program: Command,
46
+ opts: RegisterOutputFlagsOptions = {},
47
+ ): void {
48
+ const registry = opts.registry ?? defaultRegistry;
49
+ const d = opts.disable ?? {};
50
+
51
+ if (registry !== defaultRegistry) {
52
+ registryStash.set(program, registry);
53
+ }
54
+
55
+ if (!d.format) {
56
+ program.option(
57
+ '--format <fmt>',
58
+ `Output format (${registry.keys().join(', ')})`,
59
+ 'table',
60
+ );
61
+ }
62
+ // --format is the only output flag in the cross-language parity FLAGS
63
+ // contract; everything below is kit plumbing hidden from default --help.
64
+ // Adopters opting in via --help-all still see them (Commander's
65
+ // showHidden flag is wired by applyHelpTheme).
66
+ if (!d.formatOpt) {
67
+ const opt = program
68
+ .createOption(
69
+ '--format-opt <kv...>',
70
+ 'Per-format option as key=value (repeatable; bool keys may omit =value)',
71
+ )
72
+ .default([] as string[])
73
+ .argParser(collectKv);
74
+ opt.hidden = true;
75
+ program.addOption(opt);
76
+ }
77
+ if (!d.formatHelp) {
78
+ const opt = program.createOption(
79
+ '--format-help [fmt]',
80
+ 'Show available formats and their options (use --format-help <key> for one)',
81
+ );
82
+ opt.hidden = true;
83
+ program.addOption(opt);
84
+ }
85
+ if (!d.cols) {
86
+ const colsOpt = program
87
+ .createOption('--cols <cols...>', 'Restrict columns to this comma-separated list (repeatable)')
88
+ .default([] as string[])
89
+ .argParser(collectCols);
90
+ colsOpt.hidden = true;
91
+ program.addOption(colsOpt);
92
+ const columnsOpt = program
93
+ .createOption('--columns <cols...>', 'Alias for --cols')
94
+ .default([] as string[])
95
+ .argParser(collectCols);
96
+ columnsOpt.hidden = true;
97
+ program.addOption(columnsOpt);
98
+ }
99
+ if (!d.template) {
100
+ const opt = program.createOption(
101
+ '--template <tpl>',
102
+ 'eta template applied to results (mutually exclusive with --cols)',
103
+ );
104
+ opt.hidden = true;
105
+ program.addOption(opt);
106
+ }
107
+ if (!d.output) {
108
+ const opt = program
109
+ .createOption('-o, --output <path>', 'Write output to path (use - or empty for stdout)')
110
+ .default('');
111
+ opt.hidden = true;
112
+ program.addOption(opt);
113
+ }
114
+ }
115
+
116
+ /** Variadic collector for --format-opt. Each invocation appends one value. */
117
+ function collectKv(value: string, prev: readonly string[]): string[] {
118
+ return [...prev, value];
119
+ }
120
+
121
+ /**
122
+ * Variadic collector for --cols / --columns. Splits each invocation on
123
+ * commas so callers can pass either repeated flags or a single
124
+ * comma-separated string. Dedupe happens later in dispatch.
125
+ */
126
+ function collectCols(value: string, prev: readonly string[]): string[] {
127
+ return [...prev, ...value.split(',')];
128
+ }
129
+
130
+ /**
131
+ * Merges --cols + --columns from a Commander opts object into a single
132
+ * ordered, deduped string[]. Trims whitespace, drops empty entries.
133
+ */
134
+ export function resolveCols(opts: Record<string, unknown>): string[] {
135
+ const raw: string[] = [];
136
+ for (const k of ['cols', 'columns']) {
137
+ const v = opts[k];
138
+ if (Array.isArray(v)) raw.push(...(v as string[]));
139
+ }
140
+ const seen = new Set<string>();
141
+ const out: string[] = [];
142
+ for (const item of raw) {
143
+ for (const part of item.split(',')) {
144
+ const p = part.trim();
145
+ if (p === '' || seen.has(p)) continue;
146
+ seen.add(p);
147
+ out.push(p);
148
+ }
149
+ }
150
+ return out;
151
+ }
@@ -0,0 +1,80 @@
1
+ /**
2
+ * @module output/format_help
3
+ *
4
+ * --format-help rendering. Lists registered formatters or shows one
5
+ * formatter's options. Reuses the table formatter for the help table itself.
6
+ */
7
+
8
+ import type { OptionSpec } from './formatter';
9
+ import { Registry } from './registry';
10
+
11
+ /** Per-format row in the catalog table. */
12
+ export interface FormatSummary {
13
+ format: string;
14
+ extensions: string;
15
+ options: string;
16
+ }
17
+
18
+ /** Per-option row in the format-help options table. */
19
+ export interface OptionRow {
20
+ name: string;
21
+ type: string;
22
+ default: string;
23
+ enum: string;
24
+ usage: string;
25
+ }
26
+
27
+ /** Returns one FormatSummary per registered formatter, sorted by key. */
28
+ export function listFormats(registry: Registry): FormatSummary[] {
29
+ return registry.formatters().map(f => ({
30
+ format: f.key,
31
+ extensions: f.extensions.join(', '),
32
+ options: [...f.options.map(o => o.name)].sort().join(', '),
33
+ }));
34
+ }
35
+
36
+ /** Returns one OptionRow per OptionSpec on the formatter under key. */
37
+ export function formatOptions(registry: Registry, key: string): OptionRow[] {
38
+ const f = registry.lookup(key);
39
+ if (!f) {
40
+ throw new Error(
41
+ `unknown format "${key}" (valid: ${registry.keys().join(', ')})`,
42
+ );
43
+ }
44
+ return f.options.map(o => optionRow(o));
45
+ }
46
+
47
+ function optionRow(o: OptionSpec): OptionRow {
48
+ return {
49
+ name: o.name,
50
+ type: o.type,
51
+ default: o.default !== undefined ? String(o.default) : '',
52
+ enum: o.enum ? o.enum.join(', ') : '',
53
+ usage: o.usage,
54
+ };
55
+ }
56
+
57
+ /**
58
+ * Writes --format-help output. Empty `format` lists all formatters; a
59
+ * specific key prints that formatter's options.
60
+ */
61
+ export function renderFormatHelp(
62
+ out: NodeJS.WritableStream,
63
+ registry: Registry,
64
+ format: string,
65
+ ): void {
66
+ const tableFormatter = registry.lookup('table');
67
+ if (!tableFormatter) {
68
+ throw new Error('output: table formatter required for --format-help');
69
+ }
70
+ if (!format) {
71
+ tableFormatter.render(out, listFormats(registry), {}, []);
72
+ return;
73
+ }
74
+ const rows = formatOptions(registry, format);
75
+ if (rows.length === 0) {
76
+ out.write(`format "${format}" has no options\n`);
77
+ return;
78
+ }
79
+ tableFormatter.render(out, rows, {}, []);
80
+ }