@hop-top/kit 0.5.0-alpha.0 → 0.5.0-alpha.10

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 (284) hide show
  1. package/CHANGELOG.md +262 -0
  2. package/LICENSE +1 -1
  3. package/LICENSE-cobra.txt +174 -0
  4. package/NOTICE +15 -0
  5. package/README.md +55 -259
  6. package/dist/aim-DZHwwiIc.d.ts +139 -0
  7. package/dist/aim.d.ts +1 -116
  8. package/dist/aim.js +13 -414
  9. package/dist/alias-D9_qFlyP.d.ts +174 -0
  10. package/dist/alias.d.ts +2 -73
  11. package/dist/alias.js +27 -207
  12. package/dist/api-DAexsu2H.d.ts +77 -0
  13. package/dist/api.d.ts +1 -62
  14. package/dist/api.js +10 -164
  15. package/dist/auth-2-jfgiHn.d.ts +34 -0
  16. package/dist/auth.d.ts +1 -26
  17. package/dist/auth.js +6 -40
  18. package/dist/chunk-2JV3A7OP.js +1894 -0
  19. package/dist/chunk-3FIKGFKI.js +54 -0
  20. package/dist/chunk-4UE5TCMQ.js +104 -0
  21. package/dist/chunk-6HFAEZ52.js +29 -0
  22. package/dist/chunk-6SVOHNIC.js +17 -0
  23. package/dist/chunk-72XZWQX7.js +504 -0
  24. package/dist/chunk-ABQSE7AI.js +513 -0
  25. package/dist/chunk-BDNNPRX6.js +41 -0
  26. package/dist/chunk-BLS2OBIQ.js +263 -0
  27. package/dist/chunk-BRNEKPWX.js +37 -0
  28. package/dist/chunk-CSJWB6D3.js +151 -0
  29. package/dist/chunk-GGWJRWWA.js +309 -0
  30. package/dist/chunk-GHPJJV5L.js +613 -0
  31. package/dist/chunk-IXVQ62NZ.js +334 -0
  32. package/dist/chunk-JKMQSAJP.js +174 -0
  33. package/dist/chunk-JZ22ZUFA.js +1131 -0
  34. package/dist/chunk-K7VCKJ27.js +814 -0
  35. package/dist/chunk-KVG7YCTS.js +115 -0
  36. package/dist/chunk-L23O2FFE.js +51 -0
  37. package/dist/chunk-MQXYDYRD.js +968 -0
  38. package/dist/chunk-MUIQVU6E.js +251 -0
  39. package/dist/chunk-NLMS7HGP.js +178 -0
  40. package/dist/chunk-POR5L2DG.js +247 -0
  41. package/dist/chunk-PSFYJGDG.js +1445 -0
  42. package/dist/chunk-QJVSKKRQ.js +369 -0
  43. package/dist/chunk-QPUCXQXT.js +67 -0
  44. package/dist/chunk-QQQYCWSC.js +240 -0
  45. package/dist/chunk-R5U7XKVJ.js +16 -0
  46. package/dist/chunk-SNVGDYX7.js +187 -0
  47. package/dist/chunk-T46YPHKN.js +669 -0
  48. package/dist/chunk-UKZIAQA7.js +26 -0
  49. package/dist/chunk-WBVO43HU.js +355 -0
  50. package/dist/chunk-WUOAQVOA.js +86 -0
  51. package/dist/chunk-WWUKGJB5.js +90 -0
  52. package/dist/chunk-XJTRY453.js +868 -0
  53. package/dist/chunk-YGYQUFGY.js +219 -0
  54. package/dist/chunk-YOBAUCVN.js +583 -0
  55. package/dist/cli-C5B5tnpA.d.ts +400 -0
  56. package/dist/cli.d.ts +7 -309
  57. package/dist/cli.js +70 -885
  58. package/dist/completion-csVun6SP.d.ts +112 -0
  59. package/dist/completion-values-By-mnjNt.d.ts +142 -0
  60. package/dist/completion-values.d.ts +1 -0
  61. package/dist/completion-values.js +29 -0
  62. package/dist/completion.d.ts +3 -0
  63. package/dist/completion.js +34 -0
  64. package/dist/compliance-AxFf-uMy.d.ts +60 -0
  65. package/dist/compliance.d.ts +1 -0
  66. package/dist/compliance.js +17 -0
  67. package/dist/config-CaK60ByQ.d.ts +241 -0
  68. package/dist/config.d.ts +1 -97
  69. package/dist/config.js +8 -78
  70. package/dist/errcorrect-BcX1Ft0K.d.ts +44 -0
  71. package/dist/errcorrect.d.ts +1 -37
  72. package/dist/errcorrect.js +8 -68
  73. package/dist/error-Do8Qji43.d.ts +231 -0
  74. package/dist/id/index.d.ts +2 -83
  75. package/dist/id/index.js +14 -65
  76. package/dist/index-BKJZClJx.d.ts +1486 -0
  77. package/dist/index-C3Zw4wDJ.d.ts +359 -0
  78. package/dist/index-DCe1boBz.d.ts +328 -0
  79. package/dist/index-VLDcI5NF.d.ts +95 -0
  80. package/dist/index.d.ts +37 -0
  81. package/dist/index.js +132 -0
  82. package/dist/llm-DYuR7_uX.d.ts +1069 -0
  83. package/dist/llm-anthropic-Cd_I2xXB.d.ts +67 -0
  84. package/dist/llm-anthropic.d.ts +2 -0
  85. package/dist/llm-anthropic.js +13 -0
  86. package/dist/llm-openai-DyFrucmV.d.ts +87 -0
  87. package/dist/llm-openai.d.ts +2 -0
  88. package/dist/llm-openai.js +19 -0
  89. package/dist/llm.d.ts +1 -188
  90. package/dist/llm.js +101 -356
  91. package/dist/log-CkaxMX3U.d.ts +115 -0
  92. package/dist/log.d.ts +2 -0
  93. package/dist/log.js +14 -0
  94. package/dist/mcp/index.d.ts +4 -0
  95. package/dist/mcp/index.js +184 -0
  96. package/dist/netpolicy-Brx5XZUB.d.ts +151 -0
  97. package/dist/netpolicy.d.ts +1 -0
  98. package/dist/netpolicy.js +25 -0
  99. package/dist/output-CjZWmL8s.d.ts +420 -0
  100. package/dist/output.d.ts +3 -213
  101. package/dist/output.js +137 -447
  102. package/dist/parity-CvMuYcVI.d.ts +61 -0
  103. package/dist/progress-CAzyxeWl.d.ts +38 -0
  104. package/dist/progress.d.ts +1 -30
  105. package/dist/progress.js +6 -55
  106. package/dist/provenance-SMFHm5gx.d.ts +30 -0
  107. package/dist/provenance.d.ts +1 -24
  108. package/dist/provenance.js +6 -31
  109. package/dist/routellm-B0nv59mH.d.ts +111 -0
  110. package/dist/routellm.d.ts +2 -64
  111. package/dist/routellm.js +13 -255
  112. package/dist/rpc-D31Lg0Kc.d.ts +32 -0
  113. package/dist/rpc.d.ts +2 -25
  114. package/dist/rpc.js +4 -98
  115. package/dist/safety-CUaYEjZc.d.ts +30 -0
  116. package/dist/safety.d.ts +1 -24
  117. package/dist/safety.js +6 -43
  118. package/dist/scope-BrhYB4ij.d.ts +141 -0
  119. package/dist/scope.d.ts +1 -121
  120. package/dist/scope.js +20 -377
  121. package/dist/serve-D8yWMrTc.d.ts +646 -0
  122. package/dist/serve.d.ts +3 -0
  123. package/dist/serve.js +75 -0
  124. package/dist/sqlstore.js +6 -39
  125. package/dist/stream-CrjeCp0M.d.ts +44 -0
  126. package/dist/stream.d.ts +1 -35
  127. package/dist/stream.js +8 -51
  128. package/dist/telemetry/index.d.ts +1 -315
  129. package/dist/telemetry/index.js +26 -599
  130. package/dist/toolspec-DcPwwoAZ.d.ts +368 -0
  131. package/dist/toolspec.d.ts +2 -0
  132. package/dist/toolspec.js +37 -0
  133. package/dist/tui/index.d.ts +6 -298
  134. package/dist/tui/index.js +18 -322
  135. package/dist/upgrade-p_zh3pvV.d.ts +102 -0
  136. package/dist/upgrade.d.ts +1 -95
  137. package/dist/upgrade.js +6 -114
  138. package/dist/xdg-DB7Shoib.d.ts +179 -0
  139. package/dist/xdg.d.ts +1 -169
  140. package/dist/xdg.js +14 -128
  141. package/package.json +236 -46
  142. package/src/README.md +15 -0
  143. package/src/alias.conformance.test.ts +250 -0
  144. package/src/alias.test.ts +206 -2
  145. package/src/alias.ts +196 -21
  146. package/src/cli.help-command.test.ts +105 -0
  147. package/src/cli.offline.test.ts +93 -0
  148. package/src/cli.parity.test.ts +192 -0
  149. package/src/cli.test.ts +95 -1
  150. package/src/cli.ts +195 -25
  151. package/src/completion-scripts.ts +16 -0
  152. package/src/completion-values.test.ts +76 -16
  153. package/src/completion-values.ts +170 -66
  154. package/src/completion.conformance.test.ts +297 -0
  155. package/src/completion.test.ts +256 -145
  156. package/src/completion.ts +767 -121
  157. package/src/compliance.test.ts +196 -2
  158. package/src/compliance.ts +440 -20
  159. package/src/config-merge.test.ts +425 -0
  160. package/src/config.test.ts +228 -1
  161. package/src/config.ts +429 -16
  162. package/src/gen/crud_pb.ts +7 -7
  163. package/src/id/README.md +38 -0
  164. package/src/id/contract.test.ts +1 -1
  165. package/src/id/index.test.ts +1 -1
  166. package/src/id/index.ts +3 -2
  167. package/src/index.test.ts +71 -0
  168. package/src/index.ts +46 -0
  169. package/src/llm-anthropic.conformance.test.ts +1135 -0
  170. package/src/llm-anthropic.test.ts +152 -0
  171. package/src/llm-anthropic.ts +940 -0
  172. package/src/llm-choice-hermetic.test.ts +335 -0
  173. package/src/llm-config.test.ts +232 -0
  174. package/src/llm-config.ts +106 -0
  175. package/src/llm-endpoint.ts +254 -0
  176. package/src/llm-error.ts +17 -0
  177. package/src/llm-errors.ts +152 -0
  178. package/src/llm-file.ts +126 -0
  179. package/src/llm-http.ts +317 -0
  180. package/src/llm-keys.ts +167 -0
  181. package/src/llm-media.conformance.test.ts +87 -0
  182. package/src/llm-media.test.ts +279 -0
  183. package/src/llm-media.ts +322 -0
  184. package/src/llm-openai.conformance.test.ts +407 -0
  185. package/src/llm-openai.test.ts +510 -0
  186. package/src/llm-openai.ts +708 -0
  187. package/src/llm-payload.ts +155 -0
  188. package/src/llm-quote.ts +46 -0
  189. package/src/llm-routellm.conformance.test.ts +44 -0
  190. package/src/llm-toolnames.conformance.test.ts +112 -0
  191. package/src/llm-toolnames.test.ts +132 -0
  192. package/src/llm-toolnames.ts +298 -0
  193. package/src/llm-uri.ts +99 -0
  194. package/src/llm.test.ts +43 -15
  195. package/src/llm.toolcall.test.ts +175 -0
  196. package/src/llm.ts +602 -190
  197. package/src/log.parity.test.ts +105 -0
  198. package/src/log.test.ts +270 -1
  199. package/src/log.ts +228 -49
  200. package/src/mcp/README.md +63 -0
  201. package/src/mcp/args-separator.test.ts +164 -0
  202. package/src/mcp/args.test.ts +223 -0
  203. package/src/mcp/args.ts +160 -0
  204. package/src/mcp/audit.test.ts +520 -0
  205. package/src/mcp/audit.ts +70 -0
  206. package/src/mcp/bridge.test.ts +222 -0
  207. package/src/mcp/bridge.ts +291 -0
  208. package/src/mcp/conformance.test.ts +357 -0
  209. package/src/mcp/dispatch.ts +359 -0
  210. package/src/mcp/identity.test.ts +166 -0
  211. package/src/mcp/identity.ts +72 -0
  212. package/src/mcp/index.ts +176 -0
  213. package/src/mcp/legacy-notify.test.ts +59 -0
  214. package/src/mcp/legacy.ts +367 -0
  215. package/src/mcp/mcp.test.ts +707 -0
  216. package/src/mcp/modern-confirm.test.ts +520 -0
  217. package/src/mcp/modern-confirm.ts +484 -0
  218. package/src/mcp/modern.ts +788 -0
  219. package/src/mcp/stdio.test.ts +313 -0
  220. package/src/mcp/stdio.ts +254 -0
  221. package/src/mcp/tasks.ts +82 -0
  222. package/src/mcp/testtree.ts +250 -0
  223. package/src/mcp/toolname.test.ts +147 -0
  224. package/src/mcp/types.ts +689 -0
  225. package/src/netpolicy.test.ts +280 -0
  226. package/src/netpolicy.ts +256 -0
  227. package/src/output/README.md +46 -0
  228. package/src/output/builtins.ts +5 -5
  229. package/src/output/dispatch.ts +10 -2
  230. package/src/output/error.ts +459 -0
  231. package/src/output/formatter.ts +29 -5
  232. package/src/output/formatters/README.md +50 -0
  233. package/src/output/formatters/csv.ts +48 -12
  234. package/src/output/formatters/json.ts +4 -25
  235. package/src/output/formatters/project.ts +34 -0
  236. package/src/output/formatters/table.ts +8 -6
  237. package/src/output/formatters/text.ts +7 -3
  238. package/src/output/formatters/yaml.ts +5 -22
  239. package/src/output/projection.test.ts +298 -0
  240. package/src/output/projection.ts +33 -59
  241. package/src/output/template.ts +11 -21
  242. package/src/output.surface.test.ts +41 -0
  243. package/src/output.ts +64 -3
  244. package/src/published-types.test.ts +133 -0
  245. package/src/routellm.test.ts +209 -28
  246. package/src/routellm.toolcall.test.ts +521 -0
  247. package/src/routellm.ts +213 -177
  248. package/src/router/README.md +44 -0
  249. package/src/router/server.test.ts +41 -0
  250. package/src/router/server.ts +11 -0
  251. package/src/safety.test.ts +19 -9
  252. package/src/scope-defaults.json +29 -29
  253. package/src/serve.test.ts +1257 -0
  254. package/src/serve.ts +1665 -0
  255. package/src/telemetry/README.md +48 -0
  256. package/src/telemetry/client.test.ts +31 -0
  257. package/src/telemetry/client.ts +12 -6
  258. package/src/telemetry/offline.test.ts +64 -0
  259. package/src/toolspec-internal.ts +279 -0
  260. package/src/toolspec-manifest.test.ts +167 -0
  261. package/src/toolspec-manifest.ts +410 -0
  262. package/src/toolspec-spec-schemas.ts +12 -0
  263. package/src/toolspec-spec.test.ts +273 -0
  264. package/src/toolspec-spec.ts +458 -0
  265. package/src/toolspec.from-command.test.ts +350 -0
  266. package/src/toolspec.test.ts +2 -2
  267. package/src/toolspec.ts +222 -0
  268. package/src/triton/README.md +34 -0
  269. package/src/tui/README.md +42 -0
  270. package/src/tui/parity.test.ts +142 -0
  271. package/src/tui/parity.ts +59 -13
  272. package/src/wizard.test.ts +7 -7
  273. package/test/llm/conformance-helpers.ts +100 -0
  274. package/test/output/csv.test.ts +164 -0
  275. package/test/output/dispatch.test.ts +1 -2
  276. package/test/output/error.test.ts +277 -0
  277. package/test/output/smoke-capture.ts +2 -2
  278. package/test/output/smoke.test.ts +2 -2
  279. package/test/output/taxonomy-contract.test.ts +148 -0
  280. package/test/setup-env.ts +16 -0
  281. package/test/toolspec/fixture.ts +79 -0
  282. package/tsconfig.json +3 -1
  283. package/tsconfig.test.json +10 -0
  284. package/vitest.config.ts +9 -0
@@ -0,0 +1,34 @@
1
+ /**
2
+ * @module output/formatters/project
3
+ *
4
+ * Shared projection shim for the encoding formatters (json, yaml). Unlike
5
+ * table/csv/text, these two must preserve the payload's outer shape — a
6
+ * single object stays an object, an array stays an array — and must leave
7
+ * non-object payloads (scalars, arrays of scalars) untouched.
8
+ */
9
+
10
+ import { projectRows } from '../projection';
11
+
12
+ /**
13
+ * Projects `data` for encoding, keeping its outer shape.
14
+ *
15
+ * `cols` arrives pre-resolved from dispatch and fixes the emitted key order;
16
+ * empty means pass `data` through as-is.
17
+ */
18
+ export function projectForEncoding(
19
+ data: unknown,
20
+ cols: readonly string[],
21
+ ): unknown {
22
+ if (cols.length === 0) return data;
23
+
24
+ if (Array.isArray(data)) {
25
+ const rows = data as readonly unknown[];
26
+ // Non-object entries have no columns to project; pass the payload through
27
+ // rather than flattening every element to an empty object.
28
+ if (rows.some(r => r === null || typeof r !== 'object')) return data;
29
+ return projectRows(rows, cols);
30
+ }
31
+
32
+ if (data === null || typeof data !== 'object') return data;
33
+ return projectRows([data], cols)[0];
34
+ }
@@ -2,11 +2,12 @@
2
2
  * @module output/formatters/table
3
3
  *
4
4
  * Built-in table formatter. Hand-rolled aligner (matches the original
5
- * output.ts behaviour). Honors `cols` to filter columns; preserves first-
6
- * row key order otherwise.
5
+ * output.ts behaviour). Column order comes from the ColumnSpec list, or the
6
+ * first row's key order when none was supplied; `cols` narrows and reorders.
7
7
  */
8
8
 
9
9
  import type { Formatter, Options } from '../formatter';
10
+ import { deriveHeaders } from '../projection';
10
11
 
11
12
  export const tableFormatter: Formatter = {
12
13
  key: 'table',
@@ -14,11 +15,12 @@ export const tableFormatter: Formatter = {
14
15
  options: [],
15
16
  render(out, data, _opts: Options, cols) {
16
17
  const rows = normalise(data);
18
+ // Emptiness is a ROW-count decision: no rows means no output at all,
19
+ // not a bare header line.
17
20
  if (rows.length === 0) return;
18
21
 
19
- const allHeaders = Object.keys(rows[0] ?? {});
20
- const headers =
21
- cols.length > 0 ? cols.filter(c => allHeaders.includes(c)) : allHeaders;
22
+ // `cols` arrives pre-resolved from dispatch; empty means payload keys.
23
+ const headers = cols.length > 0 ? cols : deriveHeaders(rows);
22
24
  if (headers.length === 0) return;
23
25
 
24
26
  const cells = rows.map(row =>
@@ -28,7 +30,7 @@ export const tableFormatter: Formatter = {
28
30
  Math.max(h.length, ...cells.map(r => r[ci].length)),
29
31
  );
30
32
  const pad = (s: string, w: number) => s + ' '.repeat(w - s.length);
31
- const line = (parts: string[]) =>
33
+ const line = (parts: readonly string[]) =>
32
34
  parts.map((c, i) => pad(c, widths[i])).join(' ');
33
35
 
34
36
  out.write(line(headers) + '\n');
@@ -7,10 +7,14 @@
7
7
  * - lines: tab-separated, no header, one row per line
8
8
  * - paragraph: "Record N:" header line then " field: value" lines
9
9
  *
10
+ * Column order comes from the ColumnSpec list, or the first row's key order
11
+ * when none was supplied; `cols` narrows and reorders.
12
+ *
10
13
  * Zero deps. Mirrors Go text formatter byte-for-byte.
11
14
  */
12
15
 
13
16
  import type { Formatter, Options } from '../formatter';
17
+ import { deriveHeaders } from '../projection';
14
18
 
15
19
  const STYLE_KV = 'kv';
16
20
  const STYLE_LINES = 'lines';
@@ -36,11 +40,11 @@ export const textFormatter: Formatter = {
36
40
  ],
37
41
  render(out, data, opts: Options, cols) {
38
42
  const rows = normalise(data);
43
+ // Emptiness is a ROW-count decision: no rows means no output at all.
39
44
  if (rows.length === 0) return;
40
45
 
41
- const allHeaders = Object.keys(rows[0] ?? {});
42
- const headers =
43
- cols.length > 0 ? cols.filter(c => allHeaders.includes(c)) : allHeaders;
46
+ // `cols` arrives pre-resolved from dispatch; empty means payload keys.
47
+ const headers = cols.length > 0 ? cols : deriveHeaders(rows);
44
48
  if (headers.length === 0) return;
45
49
 
46
50
  const style = ((opts['style'] as string) || STYLE_KV) as
@@ -2,12 +2,14 @@
2
2
  * @module output/formatters/yaml
3
3
  *
4
4
  * Built-in YAML formatter. Honors `flow-level` option (default -1, mapping
5
- * to js-yaml's default block style). When `cols` is non-empty, projects
6
- * rows to header-keyed objects.
5
+ * to js-yaml's default block style). Emitted key order follows the ColumnSpec
6
+ * list, narrowed and reordered by `cols`; without either, the payload passes
7
+ * through untouched.
7
8
  */
8
9
 
9
10
  import * as yaml from 'js-yaml';
10
11
  import type { Formatter, Options } from '../formatter';
12
+ import { projectForEncoding } from './project';
11
13
 
12
14
  export const yamlFormatter: Formatter = {
13
15
  key: 'yaml',
@@ -22,26 +24,7 @@ export const yamlFormatter: Formatter = {
22
24
  ],
23
25
  render(out, data, opts: Options, cols) {
24
26
  const flowLevel = (opts['flow-level'] as number) ?? -1;
25
- const value = projectForYaml(data, cols);
27
+ const value = projectForEncoding(data, cols);
26
28
  out.write(yaml.dump(value, { flowLevel }));
27
29
  },
28
30
  };
29
-
30
- function projectForYaml(
31
- data: unknown,
32
- cols: readonly string[],
33
- ): unknown {
34
- if (cols.length === 0) return data;
35
- if (Array.isArray(data)) {
36
- return data.map(row => projectRow(row, cols));
37
- }
38
- return projectRow(data, cols);
39
- }
40
-
41
- function projectRow(row: unknown, cols: readonly string[]): unknown {
42
- if (row === null || typeof row !== 'object') return row;
43
- const r = row as Record<string, unknown>;
44
- const out: Record<string, unknown> = {};
45
- for (const c of cols) out[c] = r[c];
46
- return out;
47
- }
@@ -0,0 +1,298 @@
1
+ /**
2
+ * Ordering + header/key contract tests for the projection helpers and, more
3
+ * importantly, for the dispatch path that actually reaches them.
4
+ *
5
+ * Rules pinned here:
6
+ * 1. ColumnSpec list drives default column order + headers; payload key
7
+ * order is the fallback only when no ColumnSpec is supplied.
8
+ * 2. --cols reorders as well as selects — user order wins.
9
+ * 3. header == key universally.
10
+ * 4. Zero rows emits nothing, decided by ROW count not header count.
11
+ * 5. priority is accepted, stored, ignored.
12
+ */
13
+
14
+ import { describe, it, expect, vi } from 'vitest';
15
+ import { Command } from 'commander';
16
+ import { dispatch } from './dispatch';
17
+ import { registerOutputFlags } from './flags';
18
+ import { newRegistry } from './registry';
19
+ import { deriveHeaders, projectRows, resolveEffectiveCols } from './projection';
20
+ import { columnName, type ColumnSpec } from './formatter';
21
+ import './builtins';
22
+
23
+ function makeProgram(argv: readonly string[]) {
24
+ const program = new Command()
25
+ .name('test')
26
+ .exitOverride()
27
+ .configureOutput({ writeOut: () => {}, writeErr: () => {} });
28
+ registerOutputFlags(program);
29
+ program.action(() => {});
30
+ program.parse(['node', 'test', ...argv], { from: 'node' });
31
+ return program;
32
+ }
33
+
34
+ function captureStdout(): { restore: () => void; out: () => string } {
35
+ const chunks: Buffer[] = [];
36
+ const spy = vi.spyOn(process.stdout, 'write').mockImplementation(
37
+ ((c: string | Buffer) => {
38
+ chunks.push(Buffer.isBuffer(c) ? c : Buffer.from(c));
39
+ return true;
40
+ }) as typeof process.stdout.write,
41
+ );
42
+ return {
43
+ restore: () => spy.mockRestore(),
44
+ out: () => Buffer.concat(chunks).toString(),
45
+ };
46
+ }
47
+
48
+ async function run(
49
+ argv: readonly string[],
50
+ data: unknown,
51
+ columns?: readonly ColumnSpec[],
52
+ ): Promise<string> {
53
+ const program = makeProgram(argv);
54
+ const cap = captureStdout();
55
+ try {
56
+ await dispatch(program, data, columns ? { columns } : {});
57
+ } finally {
58
+ cap.restore();
59
+ }
60
+ return cap.out();
61
+ }
62
+
63
+ /**
64
+ * Rows whose own key order (notes, name, id) deliberately disagrees with the
65
+ * ColumnSpec order (id, name, notes) so the two rules are distinguishable.
66
+ */
67
+ const rows = [
68
+ { notes: 'a', name: 'Alice', id: '1' },
69
+ { notes: 'b', name: 'Bob', id: '2' },
70
+ ];
71
+
72
+ const cols: readonly ColumnSpec[] = [
73
+ { header: 'id', key: 'id', priority: 9 },
74
+ { header: 'name', key: 'name', priority: 8 },
75
+ { header: 'notes', key: 'notes', priority: 2 },
76
+ ];
77
+
78
+ // ---------------------------------------------------------------------------
79
+ // Rule 1 — ColumnSpec list drives default order, through dispatch.
80
+ // ---------------------------------------------------------------------------
81
+
82
+ describe('rule 1 — ColumnSpec drives default column order', () => {
83
+ it('table uses ColumnSpec order, not payload key order', async () => {
84
+ const out = await run([], rows, cols);
85
+ expect(out.split('\n')[0]).toBe('id name notes');
86
+ });
87
+
88
+ it('csv uses ColumnSpec order, not payload key order', async () => {
89
+ const out = await run(['--format', 'csv'], rows, cols);
90
+ expect(out).toBe('id,name,notes\n1,Alice,a\n2,Bob,b\n');
91
+ });
92
+
93
+ it('json emits keys in ColumnSpec order', async () => {
94
+ const out = await run(['--format', 'json'], rows, cols);
95
+ const parsed = JSON.parse(out) as Array<Record<string, unknown>>;
96
+ expect(Object.keys(parsed[0])).toEqual(['id', 'name', 'notes']);
97
+ });
98
+
99
+ it('yaml emits keys in ColumnSpec order', async () => {
100
+ const out = await run(['--format', 'yaml'], rows, cols);
101
+ expect(out.split('\n').slice(0, 4)).toEqual([
102
+ '- id: \'1\'',
103
+ ' name: Alice',
104
+ ' notes: a',
105
+ '- id: \'2\'',
106
+ ]);
107
+ });
108
+
109
+ it('text/lines uses ColumnSpec order', async () => {
110
+ const out = await run(
111
+ ['--format', 'text', '--format-opt', 'style=lines'],
112
+ rows,
113
+ cols,
114
+ );
115
+ expect(out).toBe('1\tAlice\ta\n2\tBob\tb\n');
116
+ });
117
+
118
+ it('falls back to payload key order when no ColumnSpec supplied', async () => {
119
+ const out = await run(['--format', 'csv'], rows);
120
+ expect(out).toBe('notes,name,id\na,Alice,1\nb,Bob,2\n');
121
+ });
122
+ });
123
+
124
+ // ---------------------------------------------------------------------------
125
+ // Rule 2 — --cols reorders as well as selects; user order wins.
126
+ // ---------------------------------------------------------------------------
127
+
128
+ describe('rule 2 — --cols reorders, user order wins', () => {
129
+ it('table honors user order against ColumnSpec order', async () => {
130
+ const out = await run(['--cols', 'notes,id'], rows, cols);
131
+ expect(out.split('\n')[0]).toBe('notes id');
132
+ });
133
+
134
+ it('csv honors user order against ColumnSpec order', async () => {
135
+ const out = await run(['--format', 'csv', '--cols', 'notes,id'], rows, cols);
136
+ expect(out).toBe('notes,id\na,1\nb,2\n');
137
+ });
138
+
139
+ it('json honors user order against ColumnSpec order', async () => {
140
+ const out = await run(
141
+ ['--format', 'json', '--cols', 'name,id'],
142
+ rows,
143
+ cols,
144
+ );
145
+ const parsed = JSON.parse(out) as Array<Record<string, unknown>>;
146
+ expect(Object.keys(parsed[0])).toEqual(['name', 'id']);
147
+ });
148
+
149
+ it('honors user order on the no-ColumnSpec fallback path too', async () => {
150
+ const out = await run(['--format', 'csv', '--cols', 'id,notes'], rows);
151
+ expect(out).toBe('id,notes\n1,a\n2,b\n');
152
+ });
153
+
154
+ it('rejects an unknown --cols name against the ColumnSpec list', async () => {
155
+ await expect(run(['--cols', 'bogus'], rows, cols)).rejects.toThrow(
156
+ /unknown column "bogus" \(valid: id, name, notes\)/,
157
+ );
158
+ });
159
+
160
+ it('resolveEffectiveCols returns user cols verbatim, ignoring schema order', () => {
161
+ expect(resolveEffectiveCols(['notes', 'id'], cols)).toEqual([
162
+ 'notes',
163
+ 'id',
164
+ ]);
165
+ });
166
+
167
+ it('resolveEffectiveCols falls back to ColumnSpec order when no --cols', () => {
168
+ expect(resolveEffectiveCols([], cols)).toEqual(['id', 'name', 'notes']);
169
+ });
170
+
171
+ it('resolveEffectiveCols yields empty for payload-key fallback', () => {
172
+ expect(resolveEffectiveCols([], undefined)).toEqual([]);
173
+ expect(resolveEffectiveCols([], [])).toEqual([]);
174
+ });
175
+ });
176
+
177
+ // ---------------------------------------------------------------------------
178
+ // Rule 3 — header == key.
179
+ // ---------------------------------------------------------------------------
180
+
181
+ describe('rule 3 — header == key', () => {
182
+ it('deriveHeaders reads the ColumnSpec list in order', () => {
183
+ expect(deriveHeaders(rows, cols)).toEqual(['id', 'name', 'notes']);
184
+ });
185
+
186
+ it('deriveHeaders falls back to first-row key order', () => {
187
+ expect(deriveHeaders(rows)).toEqual(['notes', 'name', 'id']);
188
+ });
189
+
190
+ it('projectRows keys output by the column name itself', () => {
191
+ const got = projectRows(rows, resolveEffectiveCols([], cols));
192
+ expect(Object.keys(got[0])).toEqual(['id', 'name', 'notes']);
193
+ expect(got[0]).toEqual({ id: '1', name: 'Alice', notes: 'a' });
194
+ });
195
+
196
+ it('projectRows emits keys in the exact order given', () => {
197
+ const got = projectRows(rows, ['notes', 'id']);
198
+ expect(Object.keys(got[0])).toEqual(['notes', 'id']);
199
+ });
200
+
201
+ it('columnName returns the single effective name', () => {
202
+ expect(columnName({ header: 'id', key: 'id' })).toBe('id');
203
+ });
204
+
205
+ it('columnName rejects a header/key split so drift stays impossible', () => {
206
+ expect(() => columnName({ header: 'Name', key: 'name' })).toThrow(
207
+ /column "Name": header and key must match \(got key "name"\)/,
208
+ );
209
+ });
210
+ });
211
+
212
+ // ---------------------------------------------------------------------------
213
+ // Rule 4 — zero rows emits nothing, decided by row count.
214
+ // ---------------------------------------------------------------------------
215
+
216
+ describe('rule 4 — zero rows emits nothing', () => {
217
+ it('table emits nothing for an empty payload even with a ColumnSpec', async () => {
218
+ expect(await run([], [], cols)).toBe('');
219
+ });
220
+
221
+ it('csv emits nothing for an empty payload even with a ColumnSpec', async () => {
222
+ expect(await run(['--format', 'csv'], [], cols)).toBe('');
223
+ });
224
+
225
+ it('text emits nothing for an empty payload even with a ColumnSpec', async () => {
226
+ expect(await run(['--format', 'text'], [], cols)).toBe('');
227
+ });
228
+ });
229
+
230
+ // ---------------------------------------------------------------------------
231
+ // Public API stability — ordering reaches formatters through `cols` alone.
232
+ // ---------------------------------------------------------------------------
233
+
234
+ describe('third-party formatters get ordering without signature changes', () => {
235
+ it('a 4-param formatter receives ColumnSpec order via cols', async () => {
236
+ const seen: string[][] = [];
237
+ const registry = newRegistry();
238
+ // Deliberately written against the documented 4-arg signature, with no
239
+ // knowledge of ColumnSpec — the case the interface must not break.
240
+ registry.register({
241
+ key: 'probe',
242
+ extensions: [],
243
+ options: [],
244
+ render(out, _data, _opts, cols) {
245
+ seen.push([...cols]);
246
+ out.write('ok');
247
+ },
248
+ });
249
+
250
+ const program = makeProgram(['--format', 'probe']);
251
+ const cap = captureStdout();
252
+ try {
253
+ await dispatch(program, rows, { columns: cols, registry });
254
+ } finally {
255
+ cap.restore();
256
+ }
257
+ expect(seen).toEqual([['id', 'name', 'notes']]);
258
+ });
259
+
260
+ it('a 4-param formatter sees user --cols order verbatim', async () => {
261
+ const seen: string[][] = [];
262
+ const registry = newRegistry();
263
+ registry.register({
264
+ key: 'probe',
265
+ extensions: [],
266
+ options: [],
267
+ render(out, _data, _opts, cols) {
268
+ seen.push([...cols]);
269
+ out.write('ok');
270
+ },
271
+ });
272
+
273
+ const program = makeProgram(['--format', 'probe', '--cols', 'notes,id']);
274
+ const cap = captureStdout();
275
+ try {
276
+ await dispatch(program, rows, { columns: cols, registry });
277
+ } finally {
278
+ cap.restore();
279
+ }
280
+ expect(seen).toEqual([['notes', 'id']]);
281
+ });
282
+ });
283
+
284
+ // ---------------------------------------------------------------------------
285
+ // Rule 5 — priority accepted, stored, ignored.
286
+ // ---------------------------------------------------------------------------
287
+
288
+ describe('rule 5 — priority is accepted and ignored', () => {
289
+ it('does not reorder or drop columns by priority', async () => {
290
+ const noisy: readonly ColumnSpec[] = [
291
+ { header: 'id', key: 'id', priority: 1 },
292
+ { header: 'name', key: 'name', priority: 99 },
293
+ { header: 'notes', key: 'notes', priority: 50 },
294
+ ];
295
+ const out = await run(['--format', 'csv'], rows, noisy);
296
+ expect(out).toBe('id,name,notes\n1,Alice,a\n2,Bob,b\n');
297
+ });
298
+ });
@@ -2,14 +2,19 @@
2
2
  * @module output/projection
3
3
  *
4
4
  * Helpers for projecting structured data through ColumnSpec lists. Mirrors
5
- * Go's projection.go (filterColumns / projectToMaps / TableHeaders).
5
+ * Go's projection.go (projectToMaps / TableHeaders).
6
6
  *
7
7
  * Unlike Go (which uses `table:""` struct tags), TS callers pass an explicit
8
8
  * ColumnSpec[] list. When no columns are provided, callers fall back to
9
9
  * deriving headers from the first row's own enumerable keys.
10
+ *
11
+ * A ColumnSpec's `header` and `key` are the same name: validation and value
12
+ * lookup are one operation, matching what Go's `table:""` tag can express.
13
+ * `--cols` reorders as well as selects, so the user's order wins over the
14
+ * ColumnSpec list's.
10
15
  */
11
16
 
12
- import type { ColumnSpec } from './formatter';
17
+ import { columnName, type ColumnSpec } from './formatter';
13
18
 
14
19
  /** Normalises data into a readonly array of plain objects (rows). */
15
20
  export function normaliseRows<T>(data: T | readonly T[]): readonly T[] {
@@ -31,74 +36,43 @@ export function deriveHeaders(
31
36
  }
32
37
 
33
38
  /**
34
- * Filters a ColumnSpec list to those whose `header` appears in `selected`.
35
- * Order is preserved from `columns` (caller's intended order). Unknown
36
- * names in `selected` throw with the available header list.
37
- */
38
- export function filterColumns(
39
- columns: readonly ColumnSpec[],
40
- selected: readonly string[],
41
- ): readonly ColumnSpec[] {
42
- const have = new Set(columns.map(c => c.header));
43
- for (const name of selected) {
44
- if (!have.has(name)) {
45
- const valid = columns.map(c => c.header).join(', ');
46
- throw new Error(`unknown column "${name}" (valid: ${valid})`);
47
- }
48
- }
49
- const want = new Set(selected);
50
- return columns.filter(c => want.has(c.header));
51
- }
52
-
53
- /**
54
- * Builds a header→key lookup. Used to project rows for json/yaml/csv/text.
55
- * When no ColumnSpec list is provided, headers map to themselves (the row
56
- * already keys by the same names).
39
+ * Resolves the effective column list a formatter should render.
40
+ *
41
+ * Precedence, per the settled ordering contract:
42
+ * - `cols` non-empty → the user's `--cols`, verbatim and in user order
43
+ * (rule 2: --cols reorders as well as selects).
44
+ * - else a ColumnSpec list → its headers, in list order (rule 1).
45
+ * - else → empty, meaning "fall back to payload key order".
46
+ *
47
+ * Because header == key (rule 3), an ordered array of names carries
48
+ * everything a formatter needs: the labels and the row lookup keys are the
49
+ * same strings. Resolving here keeps precedence in one place and leaves the
50
+ * public Formatter signature untouched.
57
51
  */
58
- export function buildHeaderToKey(
59
- columns?: readonly ColumnSpec[],
60
- ): Map<string, string> {
61
- const out = new Map<string, string>();
62
- if (!columns) return out;
63
- for (const c of columns) {
64
- out.set(c.header, c.key);
65
- }
66
- return out;
52
+ export function resolveEffectiveCols(
53
+ cols: readonly string[],
54
+ columns: readonly ColumnSpec[] | undefined,
55
+ ): readonly string[] {
56
+ if (cols.length > 0) return cols;
57
+ if (columns && columns.length > 0) return columns.map(columnName);
58
+ return [];
67
59
  }
68
60
 
69
61
  /**
70
- * Projects rows to plain objects keyed by header, optionally filtered by
71
- * `cols`. When `columns` is undefined, rows are returned as-is for JSON/
72
- * YAML pass-through. When `cols` is empty AND `columns` is defined,
73
- * every column is included.
62
+ * Projects rows to plain objects keyed by column name, in `cols` order.
63
+ * An empty `cols` passes rows through untouched, so JSON/YAML keep whatever
64
+ * shape the caller handed in.
74
65
  */
75
66
  export function projectRows(
76
67
  rows: readonly unknown[],
77
- columns: readonly ColumnSpec[] | undefined,
78
68
  cols: readonly string[],
79
69
  ): readonly Record<string, unknown>[] {
80
- const active = columns
81
- ? cols.length > 0
82
- ? filterColumns(columns, cols)
83
- : columns
84
- : undefined;
85
-
86
70
  return rows.map(row => {
87
71
  const r = (row ?? {}) as Record<string, unknown>;
88
- if (active) {
89
- const out: Record<string, unknown> = {};
90
- for (const c of active) {
91
- out[c.header] = r[c.key];
92
- }
93
- return out;
94
- }
95
- if (cols.length > 0) {
96
- // No ColumnSpec provided — treat cols as direct keys on the row.
97
- const out: Record<string, unknown> = {};
98
- for (const k of cols) out[k] = r[k];
99
- return out;
100
- }
101
- return r;
72
+ if (cols.length === 0) return r;
73
+ const out: Record<string, unknown> = {};
74
+ for (const name of cols) out[name] = r[name];
75
+ return out;
102
76
  });
103
77
  }
104
78
 
@@ -11,6 +11,7 @@
11
11
 
12
12
  import { Eta } from 'eta';
13
13
  import type { ColumnSpec } from './formatter';
14
+ import { deriveHeaders, projectRows, resolveEffectiveCols } from './projection';
14
15
 
15
16
  const eta = new Eta({ autoEscape: false });
16
17
 
@@ -29,12 +30,16 @@ export async function renderTemplate(
29
30
  columns?: readonly ColumnSpec[],
30
31
  ): Promise<void> {
31
32
  const rows = Array.isArray(data) ? (data as readonly unknown[]) : [data];
32
- const items = projectItems(rows, columns);
33
- const cols = columns
34
- ? columns.map(c => c.header)
35
- : items.length > 0 && typeof items[0] === 'object' && items[0] !== null
36
- ? Object.keys(items[0] as Record<string, unknown>)
37
- : [];
33
+ // Projection applies only when a ColumnSpec list fixes the order; the
34
+ // template's own `cols` binding always resolves to concrete names so
35
+ // `it.cols` stays usable on the payload-key fallback path too.
36
+ const projected = resolveEffectiveCols([], columns);
37
+ const cols = projected.length > 0 ? projected : deriveHeaders(rows);
38
+ // Templates always index items by field, so non-object rows become {}.
39
+ const items = projectRows(
40
+ rows.map(r => (r === null || typeof r !== 'object' ? {} : r)),
41
+ projected,
42
+ );
38
43
  const input = { items, cols, data };
39
44
 
40
45
  let rendered: string;
@@ -46,18 +51,3 @@ export async function renderTemplate(
46
51
  }
47
52
  out.write(rendered);
48
53
  }
49
-
50
- function projectItems(
51
- rows: readonly unknown[],
52
- columns?: readonly ColumnSpec[],
53
- ): readonly Record<string, unknown>[] {
54
- if (!columns) {
55
- return rows.map(r => (r === null || typeof r !== 'object' ? {} : (r as Record<string, unknown>)));
56
- }
57
- return rows.map(row => {
58
- const r = (row ?? {}) as Record<string, unknown>;
59
- const out: Record<string, unknown> = {};
60
- for (const c of columns) out[c.header] = r[c.key];
61
- return out;
62
- });
63
- }
@@ -0,0 +1,41 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import * as output from './output';
3
+
4
+ /**
5
+ * Guards the public symbol surface of the `./output` subpath export.
6
+ *
7
+ * The exports-map contract test in `index.test.ts` only asserts that each
8
+ * declared subpath has a source file and a build entry — it says nothing
9
+ * about which symbols a subpath exposes. `registerOutputFlags` and
10
+ * `dispatch` were defined under `output/` but never re-exported here, so
11
+ * the README's Commander wiring and the generated cli-ts template both
12
+ * threw `TypeError: registerOutputFlags is not a function` against the
13
+ * published package. `output/` is not itself a published subpath, so
14
+ * consumers had no alternate import path.
15
+ *
16
+ * These names are load-bearing for documented adopter code. Removing one
17
+ * is a breaking change and must fail here first.
18
+ */
19
+ describe('output — documented symbol surface', () => {
20
+ // README "Wiring into a Commander CLI" + templates/cli-ts/src/cli.ts.tmpl.
21
+ it.each(['registerOutputFlags', 'dispatch'])(
22
+ 'exports %s as a function',
23
+ (name) => {
24
+ expect(typeof (output as Record<string, unknown>)[name]).toBe('function');
25
+ },
26
+ );
27
+
28
+ it('exports the rest of the flag-wiring surface', () => {
29
+ expect(typeof output.registryFor).toBe('function');
30
+ expect(typeof output.resolveCols).toBe('function');
31
+ });
32
+
33
+ it('keeps the render shim and format constants', () => {
34
+ expect(typeof output.render).toBe('function');
35
+ expect(output.JSON_FORMAT).toBe('json');
36
+ expect(output.YAML_FORMAT).toBe('yaml');
37
+ expect(output.TABLE_FORMAT).toBe('table');
38
+ expect(output.CSV_FORMAT).toBe('csv');
39
+ expect(output.TEXT_FORMAT).toBe('text');
40
+ });
41
+ });