@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
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Tests for layered config loader (config.ts).
3
+ * Covers: merge order, missing-file skip, bad YAML error, envOverride, empty opts.
4
+ */
5
+
6
+ import * as fs from "fs";
7
+ import * as os from "os";
8
+ import * as path from "path";
9
+ import { describe, it, expect } from "vitest";
10
+ import { load } from "./config";
11
+
12
+ // ---------------------------------------------------------------------------
13
+ // Helpers
14
+ // ---------------------------------------------------------------------------
15
+
16
+ function tmpYaml(content: string): string {
17
+ const p = path.join(os.tmpdir(), `config-test-${Math.random().toString(36).slice(2)}.yaml`);
18
+ fs.writeFileSync(p, content, "utf8");
19
+ return p;
20
+ }
21
+
22
+ function cleanup(...paths: string[]): void {
23
+ for (const p of paths) {
24
+ try { fs.unlinkSync(p); } catch { /* ignore */ }
25
+ }
26
+ }
27
+
28
+ // ---------------------------------------------------------------------------
29
+ // Tests
30
+ // ---------------------------------------------------------------------------
31
+
32
+ describe("load", () => {
33
+ it("returns dst unchanged when opts is empty", () => {
34
+ const dst = { host: "localhost", port: 3000 };
35
+ const result = load(dst);
36
+ expect(result).toBe(dst);
37
+ expect(result).toEqual({ host: "localhost", port: 3000 });
38
+ });
39
+
40
+ it("merges system → user → project in order (later wins)", () => {
41
+ const sys = tmpYaml("host: sys\nport: 1\ndebug: false\n");
42
+ const usr = tmpYaml("host: user\nport: 2\n");
43
+ const proj = tmpYaml("host: project\n");
44
+
45
+ const dst = { host: "", port: 0, debug: false };
46
+ try {
47
+ load(dst, { systemConfigPath: sys, userConfigPath: usr, projectConfigPath: proj });
48
+ // project wins for host; user wins for port; system sets debug
49
+ expect(dst.host).toBe("project");
50
+ expect(dst.port).toBe(2);
51
+ expect(dst.debug).toBe(false);
52
+ } finally {
53
+ cleanup(sys, usr, proj);
54
+ }
55
+ });
56
+
57
+ it("silently skips missing files", () => {
58
+ const missing = "/tmp/does-not-exist-config-loader-test.yaml";
59
+ const dst = { host: "default" };
60
+ expect(() => load(dst, { systemConfigPath: missing })).not.toThrow();
61
+ expect(dst.host).toBe("default");
62
+ });
63
+
64
+ it("throws on bad YAML", () => {
65
+ const bad = tmpYaml("key: [unclosed");
66
+ try {
67
+ const dst = {};
68
+ expect(() => load(dst, { systemConfigPath: bad })).toThrow();
69
+ } finally {
70
+ cleanup(bad);
71
+ }
72
+ });
73
+
74
+ it("applies envOverride last, after all file layers", () => {
75
+ const sys = tmpYaml("host: from-file\nport: 80\n");
76
+ const dst = { host: "", port: 0, token: "" };
77
+ try {
78
+ load(dst, {
79
+ systemConfigPath: sys,
80
+ envOverride(cfg) {
81
+ cfg.host = "from-env";
82
+ cfg.token = "secret";
83
+ },
84
+ });
85
+ expect(dst.host).toBe("from-env"); // env wins over file
86
+ expect(dst.port).toBe(80); // file value preserved
87
+ expect(dst.token).toBe("secret"); // env-only value set
88
+ } finally {
89
+ cleanup(sys);
90
+ }
91
+ });
92
+
93
+ it("partial opts: only systemConfigPath provided", () => {
94
+ const sys = tmpYaml("port: 9090\n");
95
+ const dst = { port: 0, host: "default" };
96
+ try {
97
+ load(dst, { systemConfigPath: sys });
98
+ expect(dst.port).toBe(9090);
99
+ expect(dst.host).toBe("default"); // not in yaml — unchanged
100
+ } finally {
101
+ cleanup(sys);
102
+ }
103
+ });
104
+
105
+ it("returns dst (same reference)", () => {
106
+ const dst = { x: 1 };
107
+ const result = load(dst, {});
108
+ expect(result).toBe(dst);
109
+ });
110
+ });
package/src/config.ts ADDED
@@ -0,0 +1,164 @@
1
+ /**
2
+ * @packageDocumentation
3
+ *
4
+ * Layered YAML configuration loader — TypeScript port of hop.top/kit/config.
5
+ *
6
+ * Merges configuration from up to three file layers in priority order:
7
+ * system → user → project → envOverride
8
+ *
9
+ * Each later layer's values overwrite earlier ones via {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign | Object.assign}.
10
+ * Missing files are silently skipped. A file that exists but contains invalid
11
+ * YAML causes {@link load} to throw.
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * import { load } from "@hop-top/kit/config";
16
+ *
17
+ * interface AppConfig {
18
+ * host: string;
19
+ * port: number;
20
+ * debug: boolean;
21
+ * token: string;
22
+ * }
23
+ *
24
+ * const cfg: AppConfig = { host: "localhost", port: 3000, debug: false, token: "" };
25
+ *
26
+ * load(cfg, {
27
+ * systemConfigPath: "/etc/mytool/config.yaml",
28
+ * userConfigPath: `${process.env.HOME}/.config/mytool/config.yaml`,
29
+ * projectConfigPath: ".mytool.yaml",
30
+ * envOverride(c) {
31
+ * if (process.env.HOST) c.host = process.env.HOST;
32
+ * if (process.env.PORT) c.port = Number(process.env.PORT);
33
+ * if (process.env.TOKEN) c.token = process.env.TOKEN;
34
+ * },
35
+ * });
36
+ * ```
37
+ */
38
+
39
+ import * as fs from "fs";
40
+ import * as yaml from "js-yaml";
41
+
42
+ // ---------------------------------------------------------------------------
43
+ // Public API
44
+ // ---------------------------------------------------------------------------
45
+
46
+ /**
47
+ * Configuration sources for {@link load}.
48
+ *
49
+ * All path fields are optional; an empty or omitted path is silently skipped.
50
+ * {@link Options.envOverride} is called last, after all file layers, so it can
51
+ * apply environment-variable overrides on top of file values.
52
+ */
53
+ export interface Options<T extends object = object> {
54
+ /**
55
+ * Path to the system-wide config file, e.g. `/etc/mytool/config.yaml`.
56
+ * Applied first (lowest priority).
57
+ */
58
+ systemConfigPath?: string;
59
+
60
+ /**
61
+ * Path to the per-user config file, e.g. `~/.config/mytool/config.yaml`.
62
+ * Applied second; overwrites system values for shared keys.
63
+ */
64
+ userConfigPath?: string;
65
+
66
+ /**
67
+ * Path to the project-level config file, e.g. `.mytool.yaml`.
68
+ * Applied third; overwrites system and user values for shared keys.
69
+ */
70
+ projectConfigPath?: string;
71
+
72
+ /**
73
+ * Optional callback invoked after all file layers have been merged.
74
+ * Receives the fully-merged `dst` object so the caller can apply
75
+ * environment-variable overrides last (highest priority).
76
+ *
77
+ * @param cfg - The merged config object (same reference as `dst`).
78
+ */
79
+ envOverride?: (cfg: T) => void;
80
+ }
81
+
82
+ /**
83
+ * Merges layered YAML configuration into `dst` and returns it.
84
+ *
85
+ * Merge order: `systemConfigPath` → `userConfigPath` → `projectConfigPath` →
86
+ * `envOverride`.
87
+ *
88
+ * - Missing files (ENOENT) are silently skipped.
89
+ * - A file that exists but is not valid YAML causes this function to throw
90
+ * a descriptive error wrapping the parse failure.
91
+ * - `envOverride`, when provided, is called last with the merged `dst`.
92
+ * - Returns `dst` (the same object reference passed in).
93
+ *
94
+ * @param dst - Destination object to merge config into. Must be a non-null
95
+ * object; mutated in place.
96
+ * @param opts - Config sources. All fields are optional.
97
+ * @returns The mutated `dst` object.
98
+ * @throws {Error} When a file exists but cannot be parsed as YAML.
99
+ *
100
+ * @example
101
+ * ```ts
102
+ * const cfg = { host: "localhost", port: 8080 };
103
+ * load(cfg, { projectConfigPath: ".tool.yaml" });
104
+ * console.log(cfg.host); // value from .tool.yaml, or "localhost" if file missing
105
+ * ```
106
+ */
107
+ export function load<T extends object>(dst: T, opts: Options<T> = {}): T {
108
+ const paths = [
109
+ opts.systemConfigPath,
110
+ opts.userConfigPath,
111
+ opts.projectConfigPath,
112
+ ] as const;
113
+
114
+ for (const p of paths) {
115
+ if (!p) continue;
116
+ mergeFile(dst, p);
117
+ }
118
+
119
+ if (opts.envOverride) {
120
+ opts.envOverride(dst);
121
+ }
122
+
123
+ return dst;
124
+ }
125
+
126
+ // ---------------------------------------------------------------------------
127
+ // Internal helpers
128
+ // ---------------------------------------------------------------------------
129
+
130
+ /**
131
+ * Read `path`, parse as YAML, and shallow-merge into `dst`.
132
+ * ENOENT is silently ignored; other errors propagate.
133
+ */
134
+ function mergeFile<T extends object>(dst: T, filePath: string): void {
135
+ let raw: string;
136
+ try {
137
+ raw = fs.readFileSync(filePath, "utf8");
138
+ } catch (err: unknown) {
139
+ if (isEnoent(err)) return;
140
+ throw err;
141
+ }
142
+
143
+ let parsed: unknown;
144
+ try {
145
+ parsed = yaml.load(raw);
146
+ } catch (err: unknown) {
147
+ throw new Error(
148
+ `config: failed to parse ${filePath}: ${err instanceof Error ? err.message : String(err)}`,
149
+ );
150
+ }
151
+
152
+ if (parsed !== null && parsed !== undefined && typeof parsed === "object") {
153
+ Object.assign(dst, parsed);
154
+ }
155
+ }
156
+
157
+ function isEnoent(err: unknown): boolean {
158
+ return (
159
+ typeof err === "object" &&
160
+ err !== null &&
161
+ "code" in err &&
162
+ (err as NodeJS.ErrnoException).code === "ENOENT"
163
+ );
164
+ }
@@ -0,0 +1,134 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import {
3
+ createCorrectedError,
4
+ formatError,
5
+ type CorrectedError,
6
+ } from './errcorrect';
7
+
8
+ describe('createCorrectedError', () => {
9
+ it('returns an Error with CorrectedError fields', () => {
10
+ const err = createCorrectedError({
11
+ code: 'NOT_FOUND',
12
+ message: 'mission not found',
13
+ cause: 'no mission matches "bogux"',
14
+ fix: 'spaced mission list',
15
+ alternatives: ['spaced mission search bogux'],
16
+ retryable: false,
17
+ });
18
+
19
+ expect(err).toBeInstanceOf(Error);
20
+ expect(err.message).toBe('mission not found');
21
+ expect(err.code).toBe('NOT_FOUND');
22
+ expect(err.cause).toBe('no mission matches "bogux"');
23
+ expect(err.fix).toBe('spaced mission list');
24
+ expect(err.alternatives).toEqual(['spaced mission search bogux']);
25
+ expect(err.retryable).toBe(false);
26
+ });
27
+
28
+ it('works with minimal fields', () => {
29
+ const err = createCorrectedError({
30
+ code: 'INVALID',
31
+ message: 'bad input',
32
+ });
33
+
34
+ expect(err).toBeInstanceOf(Error);
35
+ expect(err.code).toBe('INVALID');
36
+ expect(err.message).toBe('bad input');
37
+ expect(err.cause).toBeUndefined();
38
+ expect(err.fix).toBeUndefined();
39
+ expect(err.alternatives).toBeUndefined();
40
+ expect(err.retryable).toBeUndefined();
41
+ });
42
+
43
+ it('has a stack trace', () => {
44
+ const err = createCorrectedError({
45
+ code: 'TIMEOUT',
46
+ message: 'timed out',
47
+ });
48
+ expect(err.stack).toBeDefined();
49
+ });
50
+ });
51
+
52
+ describe('JSON serialization', () => {
53
+ it('includes all CorrectedError fields', () => {
54
+ const err = createCorrectedError({
55
+ code: 'NOT_FOUND',
56
+ message: 'mission not found',
57
+ cause: 'no mission matches "bogux"',
58
+ fix: 'spaced mission list',
59
+ alternatives: ['spaced mission search bogux'],
60
+ retryable: false,
61
+ });
62
+
63
+ const json = JSON.parse(JSON.stringify(err));
64
+ expect(json.code).toBe('NOT_FOUND');
65
+ expect(json.message).toBe('mission not found');
66
+ expect(json.cause).toBe('no mission matches "bogux"');
67
+ expect(json.fix).toBe('spaced mission list');
68
+ expect(json.alternatives).toEqual(['spaced mission search bogux']);
69
+ expect(json.retryable).toBe(false);
70
+ });
71
+
72
+ it('omits undefined optional fields', () => {
73
+ const err = createCorrectedError({
74
+ code: 'INVALID',
75
+ message: 'bad',
76
+ });
77
+
78
+ const json = JSON.parse(JSON.stringify(err));
79
+ expect(json.code).toBe('INVALID');
80
+ expect(json.message).toBe('bad');
81
+ expect(json).not.toHaveProperty('cause');
82
+ expect(json).not.toHaveProperty('fix');
83
+ expect(json).not.toHaveProperty('alternatives');
84
+ expect(json).not.toHaveProperty('retryable');
85
+ });
86
+ });
87
+
88
+ describe('formatError', () => {
89
+ it('renders terminal format with all fields', () => {
90
+ const err: CorrectedError = {
91
+ code: 'NOT_FOUND',
92
+ message: 'mission not found',
93
+ cause: 'no mission matches "bogux"',
94
+ fix: 'spaced mission list',
95
+ alternatives: ['spaced mission search bogux'],
96
+ };
97
+
98
+ const out = formatError(err, { noColor: true });
99
+ expect(out).toContain('ERROR');
100
+ expect(out).toContain('mission not found');
101
+ expect(out).toContain('Cause:');
102
+ expect(out).toContain('no mission matches "bogux"');
103
+ expect(out).toContain('Fix:');
104
+ expect(out).toContain('spaced mission list');
105
+ expect(out).toContain('Try:');
106
+ expect(out).toContain('spaced mission search bogux');
107
+ });
108
+
109
+ it('omits missing optional sections', () => {
110
+ const err: CorrectedError = {
111
+ code: 'INVALID',
112
+ message: 'bad input',
113
+ };
114
+
115
+ const out = formatError(err, { noColor: true });
116
+ expect(out).toContain('ERROR');
117
+ expect(out).toContain('bad input');
118
+ expect(out).not.toContain('Cause:');
119
+ expect(out).not.toContain('Fix:');
120
+ expect(out).not.toContain('Try:');
121
+ });
122
+
123
+ it('renders multiple alternatives', () => {
124
+ const err: CorrectedError = {
125
+ code: 'AMBIGUOUS',
126
+ message: 'ambiguous',
127
+ alternatives: ['cmd a', 'cmd b'],
128
+ };
129
+
130
+ const out = formatError(err, { noColor: true });
131
+ expect(out).toContain('cmd a');
132
+ expect(out).toContain('cmd b');
133
+ });
134
+ });
@@ -0,0 +1,84 @@
1
+ /**
2
+ * @module errcorrect
3
+ * @package @hop-top/kit
4
+ *
5
+ * Factor 4 — Corrective Error Model.
6
+ *
7
+ * Structured errors with machine-readable code, human-readable message,
8
+ * likely cause, suggested fix, and alternative commands.
9
+ */
10
+
11
+ export interface CorrectedError {
12
+ code: string;
13
+ message: string;
14
+ cause?: string;
15
+ fix?: string;
16
+ alternatives?: string[];
17
+ retryable?: boolean;
18
+ }
19
+
20
+ /**
21
+ * Creates an Error instance augmented with CorrectedError fields.
22
+ * Serializes cleanly to JSON (only defined fields).
23
+ */
24
+ export function createCorrectedError(
25
+ opts: CorrectedError,
26
+ ): Error & CorrectedError {
27
+ const err = new Error(opts.message) as Error & CorrectedError & {
28
+ toJSON(): Record<string, unknown>;
29
+ };
30
+ err.code = opts.code;
31
+ if (opts.cause !== undefined) err.cause = opts.cause;
32
+ if (opts.fix !== undefined) err.fix = opts.fix;
33
+ if (opts.alternatives !== undefined) err.alternatives = opts.alternatives;
34
+ if (opts.retryable !== undefined) err.retryable = opts.retryable;
35
+
36
+ err.toJSON = () => {
37
+ const o: Record<string, unknown> = {
38
+ code: err.code,
39
+ message: err.message,
40
+ };
41
+ if (err.cause !== undefined) o.cause = err.cause;
42
+ if (err.fix !== undefined) o.fix = err.fix;
43
+ if (err.alternatives !== undefined) o.alternatives = err.alternatives;
44
+ if (err.retryable !== undefined) o.retryable = err.retryable;
45
+ return o;
46
+ };
47
+
48
+ return err;
49
+ }
50
+
51
+ /**
52
+ * Formats a CorrectedError for terminal display.
53
+ *
54
+ * ```
55
+ * ERROR mission not found
56
+ * Cause: no mission matches "bogux"
57
+ * Fix: spaced mission list
58
+ * Try: spaced mission search bogux
59
+ * ```
60
+ */
61
+ export function formatError(
62
+ err: CorrectedError,
63
+ opts?: { noColor?: boolean },
64
+ ): string {
65
+ const red = opts?.noColor ? (s: string) => s : (s: string) => `\x1b[31m${s}\x1b[0m`;
66
+ const bold = opts?.noColor ? (s: string) => s : (s: string) => `\x1b[1m${s}\x1b[0m`;
67
+
68
+ const lines: string[] = [];
69
+ lines.push(` ${red(bold('ERROR'))} ${err.message}`);
70
+
71
+ if (err.cause) {
72
+ lines.push(` Cause: ${err.cause}`);
73
+ }
74
+ if (err.fix) {
75
+ lines.push(` Fix: ${err.fix}`);
76
+ }
77
+ if (err.alternatives && err.alternatives.length > 0) {
78
+ for (const alt of err.alternatives) {
79
+ lines.push(` Try: ${alt}`);
80
+ }
81
+ }
82
+
83
+ return lines.join('\n');
84
+ }
@@ -0,0 +1,103 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { Command } from 'commander';
3
+ import { registerSetFlag, registerTextFlag, FlagDisplay } from './flagregister';
4
+
5
+ describe('registerSetFlag', () => {
6
+ it('prefix only — --tag works, no --add-tag', () => {
7
+ const cmd = new Command();
8
+ const sf = registerSetFlag(cmd, 'tag', 'tags', FlagDisplay.Prefix);
9
+ cmd.parse(['node', 'test', '--tag', 'feat', '--tag', '+docs']);
10
+ expect(sf.values()).toEqual(['feat', 'docs']);
11
+ expect(cmd.options.find(o => o.long === '--add-tag')).toBeUndefined();
12
+ });
13
+
14
+ it('verbose only — --add-tag/--remove-tag work, no --tag', () => {
15
+ const cmd = new Command();
16
+ const sf = registerSetFlag(cmd, 'tag', 'tags', FlagDisplay.Verbose);
17
+ cmd.parse(['node', 'test', '--add-tag', 'feat', '--add-tag', 'bug', '--remove-tag', 'bug']);
18
+ expect(sf.values()).toEqual(['feat']);
19
+ expect(cmd.options.find(o => o.long === '--tag')).toBeUndefined();
20
+ });
21
+
22
+ it('both — all forms work together', () => {
23
+ const cmd = new Command();
24
+ const sf = registerSetFlag(cmd, 'tag', 'tags', FlagDisplay.Both);
25
+ cmd.parse(['node', 'test', '--tag', 'a', '--add-tag', 'b', '--tag', '-a']);
26
+ expect(sf.values()).toEqual(['b']);
27
+ });
28
+
29
+ it('verbose --clear-tag clears all', () => {
30
+ const cmd = new Command();
31
+ const sf = registerSetFlag(cmd, 'tag', 'tags', FlagDisplay.Verbose);
32
+ sf.set('existing');
33
+ cmd.parse(['node', 'test', '--clear-tag']);
34
+ expect(sf.values()).toEqual([]);
35
+ });
36
+
37
+ it('verbose --add-tag with + in value adds literally', () => {
38
+ const cmd = new Command();
39
+ const sf = registerSetFlag(cmd, 'tag', 'tags', FlagDisplay.Verbose);
40
+ cmd.parse(['node', 'test', '--add-tag', '+ppl']);
41
+ expect(sf.values()).toEqual(['+ppl']);
42
+ });
43
+
44
+ it('verbose --remove-tag with + in value removes literally', () => {
45
+ const cmd = new Command();
46
+ const sf = registerSetFlag(cmd, 'tag', 'tags', FlagDisplay.Verbose);
47
+ sf.add('+ppl');
48
+ cmd.parse(['node', 'test', '--remove-tag', '+ppl']);
49
+ expect(sf.values()).toEqual([]);
50
+ });
51
+
52
+ it('default is prefix', () => {
53
+ const cmd = new Command();
54
+ registerSetFlag(cmd, 'tag', 'tags');
55
+ expect(cmd.options.find(o => o.long === '--tag')).toBeDefined();
56
+ expect(cmd.options.find(o => o.long === '--add-tag')).toBeUndefined();
57
+ });
58
+ });
59
+
60
+ describe('registerTextFlag', () => {
61
+ it('prefix only — --desc with + prefix', () => {
62
+ const cmd = new Command();
63
+ const tf = registerTextFlag(cmd, 'desc', 'description', FlagDisplay.Prefix);
64
+ cmd.parse(['node', 'test', '--desc', 'base', '--desc', '+line2']);
65
+ expect(tf.value()).toBe('base\nline2');
66
+ expect(cmd.options.find(o => o.long === '--desc-append')).toBeUndefined();
67
+ });
68
+
69
+ it('verbose — --desc-append works', () => {
70
+ const cmd = new Command();
71
+ const tf = registerTextFlag(cmd, 'desc', 'description', FlagDisplay.Verbose);
72
+ cmd.parse(['node', 'test', '--desc', 'base', '--desc-append', 'added']);
73
+ expect(tf.value()).toBe('base\nadded');
74
+ });
75
+
76
+ it('verbose — --desc-append-inline works', () => {
77
+ const cmd = new Command();
78
+ const tf = registerTextFlag(cmd, 'desc', 'description', FlagDisplay.Verbose);
79
+ cmd.parse(['node', 'test', '--desc', 'hello', '--desc-append-inline', ' world']);
80
+ expect(tf.value()).toBe('hello world');
81
+ });
82
+
83
+ it('verbose --desc-append with + in value appends literally', () => {
84
+ const cmd = new Command();
85
+ const tf = registerTextFlag(cmd, 'desc', 'description', FlagDisplay.Verbose);
86
+ cmd.parse(['node', 'test', '--desc', 'base', '--desc-append', '+1 improvement']);
87
+ expect(tf.value()).toBe('base\n+1 improvement');
88
+ });
89
+
90
+ it('verbose --desc-prepend with ^ in value prepends literally', () => {
91
+ const cmd = new Command();
92
+ const tf = registerTextFlag(cmd, 'desc', 'description', FlagDisplay.Verbose);
93
+ cmd.parse(['node', 'test', '--desc', 'base', '--desc-prepend', '^caret']);
94
+ expect(tf.value()).toBe('^caret\nbase');
95
+ });
96
+
97
+ it('verbose — --desc-prepend works', () => {
98
+ const cmd = new Command();
99
+ const tf = registerTextFlag(cmd, 'desc', 'description', FlagDisplay.Verbose);
100
+ cmd.parse(['node', 'test', '--desc', 'second', '--desc-prepend', 'first']);
101
+ expect(tf.value()).toBe('first\nsecond');
102
+ });
103
+ });
@@ -0,0 +1,78 @@
1
+ /**
2
+ * @module flagregister
3
+ * @package @hop-top/kit
4
+ *
5
+ * Registers SetFlag/TextFlag on a Commander program with configurable
6
+ * display style (prefix-only, verbose-only, or both).
7
+ */
8
+
9
+ import { Command } from 'commander';
10
+ import { SetFlag } from './setflag';
11
+ import { TextFlag } from './textflag';
12
+
13
+ export enum FlagDisplay {
14
+ Prefix = 'prefix',
15
+ Verbose = 'verbose',
16
+ Both = 'both',
17
+ }
18
+
19
+ /**
20
+ * Register a set-valued flag with +/-/= prefix support.
21
+ * Returns the shared SetFlag instance.
22
+ */
23
+ export function registerSetFlag(
24
+ cmd: Command, name: string, usage: string,
25
+ display: FlagDisplay = FlagDisplay.Prefix,
26
+ ): SetFlag {
27
+ const sf = new SetFlag();
28
+
29
+ const showPrefix = display === FlagDisplay.Prefix || display === FlagDisplay.Both;
30
+ const showVerbose = display === FlagDisplay.Verbose || display === FlagDisplay.Both;
31
+
32
+ if (showPrefix) {
33
+ cmd.option(`--${name} <val>`, usage + ' (+add, -remove, =replace)',
34
+ (v: string) => { sf.set(v); return sf.values(); });
35
+ }
36
+
37
+ if (showVerbose) {
38
+ cmd.option(`--add-${name} <val>`, `Add to ${usage}`,
39
+ (v: string) => { sf.add(v); return sf.values(); });
40
+ cmd.option(`--remove-${name} <val>`, `Remove from ${usage}`,
41
+ (v: string) => { sf.remove(v); return sf.values(); });
42
+ cmd.option(`--clear-${name}`, `Clear all ${usage}`,
43
+ () => { sf.clear(); return sf.values(); });
44
+ }
45
+
46
+ return sf;
47
+ }
48
+
49
+ /**
50
+ * Register a text-valued flag with +/^/= prefix support.
51
+ * Returns the shared TextFlag instance.
52
+ */
53
+ export function registerTextFlag(
54
+ cmd: Command, name: string, usage: string,
55
+ display: FlagDisplay = FlagDisplay.Prefix,
56
+ ): TextFlag {
57
+ const tf = new TextFlag();
58
+
59
+ cmd.option(`--${name} <val>`, usage,
60
+ (v: string, prev: string) => tf.parseArg(v, prev));
61
+
62
+ const showVerbose = display === FlagDisplay.Verbose || display === FlagDisplay.Both;
63
+
64
+ if (showVerbose) {
65
+ cmd.option(`--${name}-append <val>`, `Append to ${usage} (new line)`,
66
+ (v: string) => { tf.append(v); return tf.value(); });
67
+ cmd.option(`--${name}-append-inline <val>`, `Append to ${usage} (inline)`,
68
+ (v: string) => { tf.appendInline(v); return tf.value(); });
69
+ cmd.option(`--${name}-prepend <val>`, `Prepend to ${usage} (new line)`,
70
+ (v: string) => { tf.prepend(v); return tf.value(); });
71
+ cmd.option(`--${name}-prepend-inline <val>`, `Prepend to ${usage} (inline)`,
72
+ (v: string) => { tf.prependInline(v); return tf.value(); });
73
+ }
74
+
75
+ return tf;
76
+ }
77
+
78
+ export { SetFlag, TextFlag };