@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/setflag.ts ADDED
@@ -0,0 +1,102 @@
1
+ /**
2
+ * @module setflag
3
+ * @package @hop-top/kit
4
+ *
5
+ * SetFlag provides +append/-remove/=replace semantics for list-valued
6
+ * CLI options. Use with Commander's custom parseArg to eliminate
7
+ * --add-X/--remove-X/--clear-X flag proliferation.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * import { SetFlag } from '@hop-top/kit/setflag';
12
+ *
13
+ * const tags = new SetFlag();
14
+ * program.option('--tag <val>', 'Manage tags', (v, prev) => tags.parseArg(v, prev));
15
+ * // --tag feat --tag +docs --tag -bug --tag =a,b --tag =
16
+ * ```
17
+ */
18
+
19
+ /**
20
+ * SetFlag manages a list of string values with +/-/= prefix operations.
21
+ *
22
+ * val append (default)
23
+ * +val append (explicit)
24
+ * -val remove
25
+ * =a,b replace all
26
+ * = clear all
27
+ *
28
+ * Comma-separated values are split. Duplicates suppressed.
29
+ */
30
+ export class SetFlag {
31
+ private items: string[];
32
+
33
+ constructor(initial?: string[]) {
34
+ this.items = initial ? [...initial] : [];
35
+ }
36
+
37
+ /** Apply a single +/-/= operation. */
38
+ set(val: string): void {
39
+ if (!val) return;
40
+
41
+ switch (val[0]) {
42
+ case '=': {
43
+ const raw = val.slice(1);
44
+ this.items = raw === '' ? [] : splitAndTrim(raw);
45
+ return;
46
+ }
47
+ case '-': {
48
+ const target = val.slice(1);
49
+ this.items = this.items.filter(s => s !== target);
50
+ return;
51
+ }
52
+ case '+':
53
+ val = val.slice(1);
54
+ break;
55
+ }
56
+
57
+ for (const v of splitAndTrim(val)) {
58
+ if (!this.items.includes(v)) {
59
+ this.items.push(v);
60
+ }
61
+ }
62
+ }
63
+
64
+ /** Add val literally (no prefix interpretation). */
65
+ add(val: string): void {
66
+ if (!this.items.includes(val)) this.items.push(val);
67
+ }
68
+
69
+ /** Remove val literally (no prefix interpretation). */
70
+ remove(val: string): void {
71
+ this.items = this.items.filter(s => s !== val);
72
+ }
73
+
74
+ /** Clear all items. */
75
+ clear(): void {
76
+ this.items = [];
77
+ }
78
+
79
+ /** Return a copy of current items. */
80
+ values(): string[] {
81
+ return [...this.items];
82
+ }
83
+
84
+ /** Comma-joined string representation. */
85
+ toString(): string {
86
+ return this.items.join(',');
87
+ }
88
+
89
+ /**
90
+ * Commander-compatible parseArg callback.
91
+ * Use as: `program.option('--tag <v>', 'desc', (v, prev) => sf.parseArg(v, prev))`
92
+ */
93
+ parseArg(value: string, previous: string[]): string[] {
94
+ this.items = previous ? [...previous] : [];
95
+ this.set(value);
96
+ return this.values();
97
+ }
98
+ }
99
+
100
+ function splitAndTrim(s: string): string[] {
101
+ return s.split(',').map(p => p.trim()).filter(p => p !== '');
102
+ }
@@ -0,0 +1,110 @@
1
+ import { describe, it, expect, vi, afterEach } from 'vitest'
2
+ import { open } from './sqlstore'
3
+
4
+ describe('sqlstore', () => {
5
+ afterEach(() => {
6
+ vi.restoreAllMocks()
7
+ })
8
+
9
+ describe('put/get roundtrip', () => {
10
+ it('stores and retrieves a string value', () => {
11
+ const store = open(':memory:')
12
+ store.put('hello', 'world')
13
+ expect(store.get<string>('hello')).toBe('world')
14
+ store.close()
15
+ })
16
+
17
+ it('stores and retrieves an object value', () => {
18
+ const store = open(':memory:')
19
+ store.put('obj', { foo: 1, bar: true })
20
+ expect(store.get<{ foo: number; bar: boolean }>('obj')).toEqual({ foo: 1, bar: true })
21
+ store.close()
22
+ })
23
+
24
+ it('stores and retrieves a number value', () => {
25
+ const store = open(':memory:')
26
+ store.put('num', 42)
27
+ expect(store.get<number>('num')).toBe(42)
28
+ store.close()
29
+ })
30
+
31
+ it('overwrites an existing key', () => {
32
+ const store = open(':memory:')
33
+ store.put('k', 'first')
34
+ store.put('k', 'second')
35
+ expect(store.get<string>('k')).toBe('second')
36
+ store.close()
37
+ })
38
+ })
39
+
40
+ describe('missing key', () => {
41
+ it('returns null for a key that does not exist', () => {
42
+ const store = open(':memory:')
43
+ expect(store.get('missing')).toBeNull()
44
+ store.close()
45
+ })
46
+ })
47
+
48
+ describe('TTL expiry', () => {
49
+ it('returns value when not yet expired', () => {
50
+ const now = 1_000_000
51
+ vi.spyOn(Date, 'now').mockReturnValue(now)
52
+ const store = open(':memory:', { ttl: 5000 })
53
+ store.put('ttl-key', 'alive')
54
+ // still within TTL
55
+ vi.spyOn(Date, 'now').mockReturnValue(now + 4999)
56
+ expect(store.get<string>('ttl-key')).toBe('alive')
57
+ store.close()
58
+ })
59
+
60
+ it('returns null after TTL has elapsed', () => {
61
+ const now = 1_000_000
62
+ vi.spyOn(Date, 'now').mockReturnValue(now)
63
+ const store = open(':memory:', { ttl: 5000 })
64
+ store.put('ttl-key', 'doomed')
65
+ // advance past TTL
66
+ vi.spyOn(Date, 'now').mockReturnValue(now + 5001)
67
+ expect(store.get('ttl-key')).toBeNull()
68
+ store.close()
69
+ })
70
+
71
+ it('returns value when TTL is not set', () => {
72
+ const store = open(':memory:')
73
+ store.put('no-ttl', 'persists')
74
+ expect(store.get<string>('no-ttl')).toBe('persists')
75
+ store.close()
76
+ })
77
+ })
78
+
79
+ describe('migrateSql', () => {
80
+ it('runs migrateSql on open and makes table available', () => {
81
+ const store = open(':memory:', {
82
+ migrateSql: 'CREATE TABLE IF NOT EXISTS meta (id INTEGER PRIMARY KEY, name TEXT)',
83
+ })
84
+ const db = store.db()
85
+ // If table exists, this insert should succeed without throwing
86
+ expect(() => db.prepare('INSERT INTO meta (name) VALUES (?)').run('test')).not.toThrow()
87
+ store.close()
88
+ })
89
+ })
90
+
91
+ describe('close', () => {
92
+ it('close() makes subsequent operations throw', () => {
93
+ const store = open(':memory:')
94
+ store.put('x', 1)
95
+ store.close()
96
+ expect(() => store.get('x')).toThrow()
97
+ })
98
+ })
99
+
100
+ describe('db()', () => {
101
+ it('returns a Database instance', () => {
102
+ const store = open(':memory:')
103
+ const db = store.db()
104
+ expect(db).toBeDefined()
105
+ // Database has a prepare method
106
+ expect(typeof db.prepare).toBe('function')
107
+ store.close()
108
+ })
109
+ })
110
+ })
@@ -0,0 +1,144 @@
1
+ /**
2
+ * @module sqlstore
3
+ *
4
+ * SQLite-backed key-value store with optional TTL and custom migration support.
5
+ *
6
+ * ## Schema
7
+ * ```sql
8
+ * CREATE TABLE IF NOT EXISTS kv (
9
+ * key TEXT PRIMARY KEY,
10
+ * value TEXT NOT NULL,
11
+ * expires_at INTEGER -- NULL means no expiry; epoch-ms when set
12
+ * )
13
+ * ```
14
+ *
15
+ * ## TTL semantics
16
+ * - `opts.ttl` is in **milliseconds**.
17
+ * - On `put`, `expires_at` is set to `Date.now() + ttl` when `ttl > 0`.
18
+ * - On `get`, if `expires_at !== null && expires_at <= Date.now()`, `null` is returned.
19
+ * Expired rows are NOT automatically deleted; prune them with:
20
+ * ```sql
21
+ * DELETE FROM kv WHERE expires_at IS NOT NULL AND expires_at <= <now>
22
+ * ```
23
+ *
24
+ * ## migrateSql
25
+ * If `opts.migrateSql` is provided it is executed once inside `open()`, after
26
+ * the `kv` table is created. Use it to add application-specific tables,
27
+ * indexes, or seed data. Multiple statements must be separated by semicolons.
28
+ *
29
+ * ## Example
30
+ * ```ts
31
+ * import { open } from '@hop-top/kit/sqlstore'
32
+ *
33
+ * const store = open('/tmp/myapp.db', { ttl: 60_000 })
34
+ * store.put('session:abc', { userId: 1 })
35
+ * const session = store.get<{ userId: number }>('session:abc')
36
+ * store.close()
37
+ * ```
38
+ */
39
+
40
+ import Database from 'better-sqlite3'
41
+
42
+ /** Options accepted by {@link open}. */
43
+ export interface Options {
44
+ /**
45
+ * Time-to-live in **milliseconds**. When positive, values older than this
46
+ * are treated as absent on `get`. Zero or omitted disables expiry.
47
+ */
48
+ ttl?: number
49
+
50
+ /**
51
+ * SQL executed once during `open()` after the `kv` table is created.
52
+ * Useful for adding custom tables, indexes, or initial data.
53
+ * Multiple statements must be semicolon-separated.
54
+ */
55
+ migrateSql?: string
56
+ }
57
+
58
+ /** A SQLite-backed key-value store. */
59
+ export interface Store {
60
+ /**
61
+ * Serialises `value` as JSON and upserts it under `key`.
62
+ * If `key` already exists its value (and expiry) are overwritten.
63
+ */
64
+ put(key: string, value: unknown): void
65
+
66
+ /**
67
+ * Returns the JSON-deserialised value for `key`, or `null` if the key
68
+ * does not exist or has expired.
69
+ */
70
+ get<T>(key: string): T | null
71
+
72
+ /** Returns the underlying `better-sqlite3` Database instance. */
73
+ db(): Database.Database
74
+
75
+ /** Closes the underlying database connection. */
76
+ close(): void
77
+ }
78
+
79
+ const CREATE_KV = `
80
+ CREATE TABLE IF NOT EXISTS kv (
81
+ key TEXT PRIMARY KEY,
82
+ value TEXT NOT NULL,
83
+ expires_at INTEGER
84
+ )
85
+ `
86
+
87
+ /**
88
+ * Opens (or creates) a SQLite database at `path`, ensures the `kv` table
89
+ * exists, and runs `opts.migrateSql` if supplied.
90
+ *
91
+ * Pass `':memory:'` as `path` for an in-memory database (useful in tests).
92
+ *
93
+ * @param path Filesystem path or `':memory:'`.
94
+ * @param opts Optional TTL and migration SQL.
95
+ */
96
+ export function open(path: string, opts: Options = {}): Store {
97
+ const database = new Database(path)
98
+
99
+ // Create kv table
100
+ database.exec(CREATE_KV)
101
+
102
+ // Run caller-supplied migration
103
+ if (opts.migrateSql) {
104
+ database.exec(opts.migrateSql)
105
+ }
106
+
107
+ const stmtPutNoExpiry = database.prepare(
108
+ `INSERT INTO kv (key, value, expires_at) VALUES (?, ?, NULL)
109
+ ON CONFLICT(key) DO UPDATE SET value = excluded.value, expires_at = NULL`,
110
+ )
111
+
112
+ const stmtPutWithExpiry = database.prepare(
113
+ `INSERT INTO kv (key, value, expires_at) VALUES (?, ?, ?)
114
+ ON CONFLICT(key) DO UPDATE SET value = excluded.value, expires_at = excluded.expires_at`,
115
+ )
116
+
117
+ const stmtGet = database.prepare(`SELECT value, expires_at FROM kv WHERE key = ?`)
118
+
119
+ return {
120
+ put(key: string, value: unknown): void {
121
+ const json = JSON.stringify(value)
122
+ if (opts.ttl && opts.ttl > 0) {
123
+ stmtPutWithExpiry.run(key, json, Date.now() + opts.ttl)
124
+ } else {
125
+ stmtPutNoExpiry.run(key, json)
126
+ }
127
+ },
128
+
129
+ get<T>(key: string): T | null {
130
+ const row = stmtGet.get(key) as { value: string; expires_at: number | null } | undefined
131
+ if (row == null) return null
132
+ if (row.expires_at !== null && row.expires_at <= Date.now()) return null
133
+ return JSON.parse(row.value) as T
134
+ },
135
+
136
+ db(): Database.Database {
137
+ return database
138
+ },
139
+
140
+ close(): void {
141
+ database.close()
142
+ },
143
+ }
144
+ }
@@ -0,0 +1,69 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { PassThrough } from 'node:stream';
3
+ import { ExitCode, createStreamWriter } from './stream';
4
+
5
+ describe('ExitCode', () => {
6
+ it('maps OK to 0', () => {
7
+ expect(ExitCode.OK).toBe(0);
8
+ });
9
+
10
+ it('maps Error to 1', () => {
11
+ expect(ExitCode.Error).toBe(1);
12
+ });
13
+
14
+ it('maps Usage to 2', () => {
15
+ expect(ExitCode.Usage).toBe(2);
16
+ });
17
+
18
+ it('maps NotFound to 3', () => {
19
+ expect(ExitCode.NotFound).toBe(3);
20
+ });
21
+
22
+ it('maps Conflict to 4', () => {
23
+ expect(ExitCode.Conflict).toBe(4);
24
+ });
25
+
26
+ it('maps Auth to 5', () => {
27
+ expect(ExitCode.Auth).toBe(5);
28
+ });
29
+
30
+ it('maps Permission to 6', () => {
31
+ expect(ExitCode.Permission).toBe(6);
32
+ });
33
+
34
+ it('maps Timeout to 7', () => {
35
+ expect(ExitCode.Timeout).toBe(7);
36
+ });
37
+
38
+ it('maps Cancelled to 8', () => {
39
+ expect(ExitCode.Cancelled).toBe(8);
40
+ });
41
+ });
42
+
43
+ describe('createStreamWriter', () => {
44
+ it('returns a StreamWriter with data, human, and isTTY', () => {
45
+ const sw = createStreamWriter();
46
+ expect(sw).toHaveProperty('data');
47
+ expect(sw).toHaveProperty('human');
48
+ expect(sw).toHaveProperty('isTTY');
49
+ expect(typeof sw.isTTY).toBe('boolean');
50
+ });
51
+
52
+ it('defaults data to stdout', () => {
53
+ const sw = createStreamWriter();
54
+ expect(sw.data).toBe(process.stdout);
55
+ });
56
+
57
+ it('defaults human to stderr', () => {
58
+ const sw = createStreamWriter();
59
+ expect(sw.human).toBe(process.stderr);
60
+ });
61
+
62
+ it('accepts custom streams', () => {
63
+ const data = new PassThrough();
64
+ const human = new PassThrough();
65
+ const sw = createStreamWriter({ data, human });
66
+ expect(sw.data).toBe(data);
67
+ expect(sw.human).toBe(human);
68
+ });
69
+ });
package/src/stream.ts ADDED
@@ -0,0 +1,47 @@
1
+ /**
2
+ * @module stream
3
+ * @package @hop-top/kit
4
+ *
5
+ * Factor 3 — Stream and Exit Discipline.
6
+ *
7
+ * Structured data goes to stdout; human-oriented messages
8
+ * (logs, progress, prompts) go to stderr. Exit codes are
9
+ * semantic, not just 0/1.
10
+ */
11
+
12
+ export enum ExitCode {
13
+ OK = 0,
14
+ Error = 1,
15
+ Usage = 2,
16
+ NotFound = 3,
17
+ Conflict = 4,
18
+ Auth = 5,
19
+ Permission = 6,
20
+ Timeout = 7,
21
+ Cancelled = 8,
22
+ }
23
+
24
+ export interface StreamWriter {
25
+ /** stdout — structured/parseable output */
26
+ data: NodeJS.WritableStream;
27
+ /** stderr — logs, progress, human messages */
28
+ human: NodeJS.WritableStream;
29
+ isTTY: boolean;
30
+ }
31
+
32
+ export interface StreamWriterOptions {
33
+ data?: NodeJS.WritableStream;
34
+ human?: NodeJS.WritableStream;
35
+ }
36
+
37
+ export function createStreamWriter(
38
+ opts?: StreamWriterOptions,
39
+ ): StreamWriter {
40
+ const data = opts?.data ?? process.stdout;
41
+ const human = opts?.human ?? process.stderr;
42
+ return {
43
+ data,
44
+ human,
45
+ isTTY: !!(process.stdout as any).isTTY,
46
+ };
47
+ }
@@ -0,0 +1,105 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { TextFlag } from './textflag';
3
+
4
+ describe('TextFlag', () => {
5
+ it('replace by default', () => {
6
+ const tf = new TextFlag();
7
+ tf.set('hello');
8
+ expect(tf.value()).toBe('hello');
9
+ tf.set('world');
10
+ expect(tf.value()).toBe('world');
11
+ });
12
+
13
+ it('replace explicit with =', () => {
14
+ const tf = new TextFlag('old');
15
+ tf.set('=new');
16
+ expect(tf.value()).toBe('new');
17
+ });
18
+
19
+ it('append on new line with +', () => {
20
+ const tf = new TextFlag('first');
21
+ tf.set('+second');
22
+ expect(tf.value()).toBe('first\nsecond');
23
+ });
24
+
25
+ it('append multiple lines', () => {
26
+ const tf = new TextFlag('line1');
27
+ tf.set('+line2');
28
+ tf.set('+line3');
29
+ expect(tf.value()).toBe('line1\nline2\nline3');
30
+ });
31
+
32
+ it('append inline with +=', () => {
33
+ const tf = new TextFlag('hello');
34
+ tf.set('+= world');
35
+ expect(tf.value()).toBe('hello world');
36
+ });
37
+
38
+ it('prepend on new line with ^', () => {
39
+ const tf = new TextFlag('second');
40
+ tf.set('^first');
41
+ expect(tf.value()).toBe('first\nsecond');
42
+ });
43
+
44
+ it('prepend inline with ^=', () => {
45
+ const tf = new TextFlag('world');
46
+ tf.set('^=hello ');
47
+ expect(tf.value()).toBe('hello world');
48
+ });
49
+
50
+ it('clear with bare =', () => {
51
+ const tf = new TextFlag('something');
52
+ tf.set('=');
53
+ expect(tf.value()).toBe('');
54
+ });
55
+
56
+ it('append to empty skips newline', () => {
57
+ const tf = new TextFlag();
58
+ tf.set('+line');
59
+ expect(tf.value()).toBe('line');
60
+ });
61
+
62
+ it('prepend to empty skips newline', () => {
63
+ const tf = new TextFlag();
64
+ tf.set('^line');
65
+ expect(tf.value()).toBe('line');
66
+ });
67
+
68
+ it('toString returns value', () => {
69
+ const tf = new TextFlag('hello');
70
+ expect(tf.toString()).toBe('hello');
71
+ });
72
+
73
+ it('= escapes literal + prefix', () => {
74
+ const tf = new TextFlag();
75
+ tf.set('=+ppl');
76
+ expect(tf.value()).toBe('+ppl');
77
+ });
78
+
79
+ it('= escapes literal ^ prefix', () => {
80
+ const tf = new TextFlag();
81
+ tf.set('=^weird');
82
+ expect(tf.value()).toBe('^weird');
83
+ });
84
+
85
+ it('= escapes literal = prefix', () => {
86
+ const tf = new TextFlag();
87
+ tf.set('==equals');
88
+ expect(tf.value()).toBe('=equals');
89
+ });
90
+
91
+ it('mixed operations', () => {
92
+ const tf = new TextFlag();
93
+ tf.set('base');
94
+ tf.set('+appended');
95
+ tf.set('^prepended');
96
+ expect(tf.value()).toBe('prepended\nbase\nappended');
97
+ });
98
+
99
+ it('parseArg works as Commander option parser', () => {
100
+ const tf = new TextFlag();
101
+ let result = tf.parseArg('base', '');
102
+ result = tf.parseArg('+added', result);
103
+ expect(result).toBe('base\nadded');
104
+ });
105
+ });
@@ -0,0 +1,68 @@
1
+ /**
2
+ * @module textflag
3
+ * @package @hop-top/kit
4
+ *
5
+ * TextFlag provides +append/^prepend/=replace semantics for text-valued
6
+ * CLI options.
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * import { TextFlag } from '@hop-top/kit/textflag';
11
+ *
12
+ * const desc = new TextFlag();
13
+ * program.option('--desc <val>', 'Description', (v, prev) => desc.parseArg(v, prev));
14
+ * ```
15
+ */
16
+
17
+ export class TextFlag {
18
+ private text: string;
19
+
20
+ constructor(initial?: string) {
21
+ this.text = initial ?? '';
22
+ }
23
+
24
+ set(val: string): void {
25
+ if (!val) return;
26
+
27
+ if (val.startsWith('+=')) {
28
+ this.text += val.slice(2);
29
+ } else if (val[0] === '+') {
30
+ const body = val.slice(1);
31
+ this.text = this.text === '' ? body : this.text + '\n' + body;
32
+ } else if (val.startsWith('^=')) {
33
+ this.text = val.slice(2) + this.text;
34
+ } else if (val[0] === '^') {
35
+ const body = val.slice(1);
36
+ this.text = this.text === '' ? body : body + '\n' + this.text;
37
+ } else if (val[0] === '=') {
38
+ this.text = val.slice(1);
39
+ } else {
40
+ this.text = val;
41
+ }
42
+ }
43
+
44
+ /** Append val on new line (no prefix interpretation). */
45
+ append(val: string): void {
46
+ this.text = this.text === '' ? val : this.text + '\n' + val;
47
+ }
48
+
49
+ /** Append val inline (no prefix interpretation). */
50
+ appendInline(val: string): void { this.text += val; }
51
+
52
+ /** Prepend val on new line (no prefix interpretation). */
53
+ prepend(val: string): void {
54
+ this.text = this.text === '' ? val : val + '\n' + this.text;
55
+ }
56
+
57
+ /** Prepend val inline (no prefix interpretation). */
58
+ prependInline(val: string): void { this.text = val + this.text; }
59
+
60
+ value(): string { return this.text; }
61
+ toString(): string { return this.text; }
62
+
63
+ parseArg(value: string, previous: string): string {
64
+ this.text = previous ?? '';
65
+ this.set(value);
66
+ return this.value();
67
+ }
68
+ }