@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,111 @@
1
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2
+ import { buildTheme } from '../cli.js';
3
+ import { spinner } from './spinner.js';
4
+
5
+ // Capture stderr writes.
6
+ function captureStderr(): { output: string[]; restore: () => void } {
7
+ const output: string[] = [];
8
+ vi.spyOn(process.stderr, 'write').mockImplementation((chunk: unknown) => {
9
+ output.push(String(chunk));
10
+ return true;
11
+ });
12
+ return { output, restore: () => vi.restoreAllMocks() };
13
+ }
14
+
15
+ describe('spinner()', () => {
16
+ const theme = buildTheme();
17
+
18
+ beforeEach(() => {
19
+ vi.useFakeTimers();
20
+ });
21
+
22
+ afterEach(() => {
23
+ vi.useRealTimers();
24
+ vi.restoreAllMocks();
25
+ });
26
+
27
+ it('start() writes initial frame to stderr', () => {
28
+ const { output, restore } = captureStderr();
29
+ const s = spinner(theme);
30
+ s.start('loading');
31
+ expect(output.length).toBeGreaterThan(0);
32
+ expect(output[0]).toContain('loading');
33
+ restore();
34
+ });
35
+
36
+ it('start() includes theme.accent ANSI color', () => {
37
+ const { output, restore } = captureStderr();
38
+ const s = spinner(theme);
39
+ s.start('x');
40
+ // accent #7ED957 → 38;2;126;217;87
41
+ expect(output[0]).toContain('38;2;126;217;87');
42
+ restore();
43
+ });
44
+
45
+ it('advances frames on interval tick', () => {
46
+ const { output, restore } = captureStderr();
47
+ const s = spinner(theme);
48
+ s.start('tick');
49
+ const countBefore = output.length;
50
+ vi.advanceTimersByTime(80 * 3);
51
+ expect(output.length).toBeGreaterThan(countBefore);
52
+ s.stop();
53
+ restore();
54
+ });
55
+
56
+ it('stop() clears line', () => {
57
+ const { output, restore } = captureStderr();
58
+ const s = spinner(theme);
59
+ s.start();
60
+ output.length = 0; // reset
61
+ s.stop();
62
+ const joined = output.join('');
63
+ expect(joined).toContain('\r');
64
+ restore();
65
+ });
66
+
67
+ it('stop() prints final message', () => {
68
+ const { output, restore } = captureStderr();
69
+ const s = spinner(theme);
70
+ s.start();
71
+ output.length = 0;
72
+ s.stop('done!');
73
+ const joined = output.join('');
74
+ expect(joined).toContain('done!');
75
+ restore();
76
+ });
77
+
78
+ it('stop() without message does not print extra newline content', () => {
79
+ const { output, restore } = captureStderr();
80
+ const s = spinner(theme);
81
+ s.start();
82
+ output.length = 0;
83
+ s.stop();
84
+ // Should only clear line, no message string
85
+ expect(output.join('')).not.toContain('done');
86
+ restore();
87
+ });
88
+
89
+ it('message() updates displayed text on next tick', () => {
90
+ const { output, restore } = captureStderr();
91
+ const s = spinner(theme);
92
+ s.start('first');
93
+ s.message('updated');
94
+ vi.advanceTimersByTime(80);
95
+ const joined = output.join('');
96
+ expect(joined).toContain('updated');
97
+ s.stop();
98
+ restore();
99
+ });
100
+
101
+ it('stop() stops interval — no further renders after stop', () => {
102
+ const { output, restore } = captureStderr();
103
+ const s = spinner(theme);
104
+ s.start();
105
+ s.stop();
106
+ const countAfterStop = output.length;
107
+ vi.advanceTimersByTime(500);
108
+ expect(output.length).toBe(countAfterStop);
109
+ restore();
110
+ });
111
+ });
@@ -0,0 +1,96 @@
1
+ /**
2
+ * @module tui/spinner
3
+ * @package @hop-top/kit
4
+ *
5
+ * Terminal spinner component.
6
+ * Mirrors Go's NewSpinner from hop.top/kit/tui — pure ANSI, no bubbletea dep.
7
+ */
8
+
9
+ import type { Theme } from '../cli.js';
10
+ import { parity } from './parity.js';
11
+
12
+ const FRAMES = parity.spinner.frames;
13
+ const INTERVAL_MS = parity.spinner.interval_ms;
14
+
15
+ export interface Spinner {
16
+ /** Start spinning with optional message. */
17
+ start(msg?: string): void;
18
+ /** Stop spinner, print optional final message. */
19
+ stop(msg?: string): void;
20
+ /** Update the spinner message while running. */
21
+ message(msg: string): void;
22
+ }
23
+
24
+ /**
25
+ * Creates a terminal spinner styled with theme.accent.
26
+ *
27
+ * Renders to stderr; uses \r to overwrite the current line each frame.
28
+ *
29
+ * @param theme - Active CLI theme.
30
+ * @returns Spinner control object.
31
+ *
32
+ * @example
33
+ * ```ts
34
+ * import { buildTheme } from '@hop-top/kit/cli';
35
+ * import { spinner } from '@hop-top/kit/tui';
36
+ * const s = spinner(buildTheme());
37
+ * s.start('Loading…');
38
+ * // await work
39
+ * s.stop('Done');
40
+ * ```
41
+ */
42
+ export function spinner(theme: Theme): Spinner {
43
+ const [r, g, b] = hexToRgb(theme.accent);
44
+ const accentOpen = `\x1b[38;2;${r};${g};${b}m`;
45
+ const reset = `\x1b[0m`;
46
+
47
+ let timer: ReturnType<typeof setInterval> | null = null;
48
+ let frameIdx = 0;
49
+ let currentMsg = '';
50
+
51
+ function render(): void {
52
+ const frame = FRAMES[frameIdx % FRAMES.length];
53
+ const line = `\r${accentOpen}${frame}${reset} ${currentMsg}`;
54
+ process.stderr.write(line);
55
+ frameIdx++;
56
+ }
57
+
58
+ return {
59
+ start(msg = ''): void {
60
+ if (timer !== null) return;
61
+ currentMsg = msg;
62
+ frameIdx = 0;
63
+ render();
64
+ timer = setInterval(render, INTERVAL_MS);
65
+ },
66
+
67
+ stop(msg?: string): void {
68
+ if (timer !== null) {
69
+ clearInterval(timer);
70
+ timer = null;
71
+ }
72
+ // Clear spinner line.
73
+ process.stderr.write('\r\x1b[K');
74
+ if (msg !== undefined) {
75
+ process.stderr.write(`${msg}\n`);
76
+ }
77
+ },
78
+
79
+ message(msg: string): void {
80
+ currentMsg = msg;
81
+ },
82
+ };
83
+ }
84
+
85
+ // ---------------------------------------------------------------------------
86
+ // Helpers
87
+ // ---------------------------------------------------------------------------
88
+
89
+ function hexToRgb(hex: string): [number, number, number] {
90
+ const h = hex.replace('#', '');
91
+ return [
92
+ parseInt(h.slice(0, 2), 16),
93
+ parseInt(h.slice(2, 4), 16),
94
+ parseInt(h.slice(4, 6), 16),
95
+ ];
96
+ }
@@ -0,0 +1,68 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { buildTheme } from '../cli.js';
3
+ import { status } from './status.js';
4
+
5
+ const stripAnsi = (s: string) => s.replace(/\x1b\[[0-9;]*m/g, '');
6
+
7
+ describe('status()', () => {
8
+ const theme = buildTheme();
9
+
10
+ it('defaults to info kind', () => {
11
+ const out = stripAnsi(status(theme, 'hello'));
12
+ expect(out).toBe('ℹ hello');
13
+ });
14
+
15
+ it('info kind uses ℹ symbol', () => {
16
+ const out = stripAnsi(status(theme, 'msg', 'info'));
17
+ expect(out).toMatch(/^ℹ /);
18
+ });
19
+
20
+ it('success kind uses ✓ symbol', () => {
21
+ const out = stripAnsi(status(theme, 'ok', 'success'));
22
+ expect(out).toMatch(/^✓ /);
23
+ });
24
+
25
+ it('error kind uses ● symbol', () => {
26
+ const out = stripAnsi(status(theme, 'fail', 'error'));
27
+ expect(out).toMatch(/^● /);
28
+ });
29
+
30
+ it('warn kind uses ▲ symbol', () => {
31
+ const out = stripAnsi(status(theme, 'careful', 'warn'));
32
+ expect(out).toMatch(/^▲ /);
33
+ });
34
+
35
+ it('includes message text', () => {
36
+ const out = stripAnsi(status(theme, 'operation complete', 'success'));
37
+ expect(out).toContain('operation complete');
38
+ });
39
+
40
+ it('returns ANSI-colored output', () => {
41
+ const out = status(theme, 'test', 'info');
42
+ expect(out).toContain('\x1b[');
43
+ });
44
+
45
+ it('info uses theme.accent color', () => {
46
+ // accent = #7ED957 → rgb(126,217,87)
47
+ const out = status(theme, 'test', 'info');
48
+ expect(out).toContain('38;2;126;217;87');
49
+ });
50
+
51
+ it('error uses theme.error color', () => {
52
+ // error = #ED4A5E → rgb(237,74,94)
53
+ const out = status(theme, 'test', 'error');
54
+ expect(out).toContain('38;2;237;74;94');
55
+ });
56
+
57
+ it('success uses theme.success color', () => {
58
+ // success = #52CF84 → rgb(82,207,132)
59
+ const out = status(theme, 'test', 'success');
60
+ expect(out).toContain('38;2;82;207;132');
61
+ });
62
+
63
+ it('warn uses theme.secondary color', () => {
64
+ // secondary = #FF00FF → rgb(255,0,255)
65
+ const out = status(theme, 'test', 'warn');
66
+ expect(out).toContain('38;2;255;0;255');
67
+ });
68
+ });
@@ -0,0 +1,66 @@
1
+ /**
2
+ * @module tui/status
3
+ * @package @hop-top/kit
4
+ *
5
+ * Renders a prefixed status line with kind-derived symbol + color.
6
+ * Mirrors Go's InfoType/Status concept from hop.top/kit/tui.
7
+ */
8
+
9
+ import type { Theme } from '../cli.js';
10
+ import { parity } from './parity.js';
11
+
12
+ const _symbols = parity.status.symbols;
13
+
14
+ /** Classification of a status message — maps to indicator symbol and color. */
15
+ export type StatusKind = 'info' | 'success' | 'error' | 'warn';
16
+
17
+ /**
18
+ * Renders a prefixed status line.
19
+ *
20
+ * Indicator symbols and colors mirror Go's InfoType constants:
21
+ * - info → ℹ accent
22
+ * - success → ✓ success
23
+ * - error → ● error
24
+ * - warn → ▲ secondary
25
+ *
26
+ * @param theme - Active CLI theme.
27
+ * @param text - Status message text.
28
+ * @param kind - Message classification (default: `'info'`).
29
+ * @returns ANSI-styled status string with indicator prefix.
30
+ *
31
+ * @example
32
+ * ```ts
33
+ * import { buildTheme } from '@hop-top/kit/cli';
34
+ * import { status } from '@hop-top/kit/tui';
35
+ * console.log(status(buildTheme(), 'Operation complete', 'success'));
36
+ * ```
37
+ */
38
+ export function status(theme: Theme, text: string, kind: StatusKind = 'info'): string {
39
+ const { symbol, color } = resolveKind(theme, kind);
40
+ const indicator = colorize(color, symbol);
41
+ const message = colorize(color, text);
42
+ return `${indicator} ${message}`;
43
+ }
44
+
45
+ // ---------------------------------------------------------------------------
46
+ // Helpers
47
+ // ---------------------------------------------------------------------------
48
+
49
+ interface KindSpec { symbol: string; color: string }
50
+
51
+ function resolveKind(theme: Theme, kind: StatusKind): KindSpec {
52
+ switch (kind) {
53
+ case 'success': return { symbol: _symbols.success, color: theme.success };
54
+ case 'error': return { symbol: _symbols.error, color: theme.error };
55
+ case 'warn': return { symbol: _symbols.warn, color: theme.secondary };
56
+ default: return { symbol: _symbols.info, color: theme.accent };
57
+ }
58
+ }
59
+
60
+ function colorize(hex: string, text: string): string {
61
+ const h = hex.replace('#', '');
62
+ const r = parseInt(h.slice(0, 2), 16);
63
+ const g = parseInt(h.slice(2, 4), 16);
64
+ const b = parseInt(h.slice(4, 6), 16);
65
+ return `\x1b[38;2;${r};${g};${b}m${text}\x1b[0m`;
66
+ }
@@ -0,0 +1,298 @@
1
+ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
2
+ import * as os from 'os';
3
+ import * as fs from 'fs';
4
+ import * as path from 'path';
5
+ import { createChecker } from './upgrade';
6
+
7
+ // ─── helpers ─────────────────────────────────────────────────────────────────
8
+
9
+ /** Writable stream that accumulates output into a string. */
10
+ class StringStream {
11
+ private buf = '';
12
+
13
+ write(chunk: string | Buffer): boolean {
14
+ this.buf += typeof chunk === 'string' ? chunk : chunk.toString();
15
+ return true;
16
+ }
17
+
18
+ value(): string {
19
+ return this.buf;
20
+ }
21
+ }
22
+
23
+ /** Build a minimal fetch Response with JSON body. */
24
+ function jsonResponse(body: unknown, status = 200): Response {
25
+ return new Response(JSON.stringify(body), {
26
+ status,
27
+ headers: { 'Content-Type': 'application/json' },
28
+ });
29
+ }
30
+
31
+ // ─── suite ───────────────────────────────────────────────────────────────────
32
+
33
+ describe('createChecker', () => {
34
+ let tmpDir: string;
35
+
36
+ beforeEach(() => {
37
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'upgrade-test-'));
38
+ vi.restoreAllMocks();
39
+ });
40
+
41
+ afterEach(() => {
42
+ fs.rmSync(tmpDir, { recursive: true, force: true });
43
+ vi.restoreAllMocks();
44
+ });
45
+
46
+ // ── newer version available ─────────────────────────────────────────────
47
+
48
+ it('writes notice when newer version is available', async () => {
49
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(
50
+ jsonResponse({ tag_name: 'v2.0.0' }),
51
+ );
52
+
53
+ const checker = createChecker({
54
+ name: 'my-tool',
55
+ currentVersion: '1.0.0',
56
+ owner: 'acme',
57
+ repo: 'my-tool',
58
+ stateDir: tmpDir,
59
+ });
60
+
61
+ const out = new StringStream();
62
+ await checker.notifyIfAvailable(out as unknown as NodeJS.WritableStream);
63
+
64
+ expect(out.value()).toBe(
65
+ '\nA new release of my-tool is available: v1.0.0 → v2.0.0\n' +
66
+ 'https://github.com/acme/my-tool/releases/latest\n',
67
+ );
68
+ });
69
+
70
+ // ── same version → no output ────────────────────────────────────────────
71
+
72
+ it('writes nothing when latest version equals current', async () => {
73
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(
74
+ jsonResponse({ tag_name: 'v1.0.0' }),
75
+ );
76
+
77
+ const checker = createChecker({
78
+ name: 'my-tool',
79
+ currentVersion: '1.0.0',
80
+ owner: 'acme',
81
+ repo: 'my-tool',
82
+ stateDir: tmpDir,
83
+ });
84
+
85
+ const out = new StringStream();
86
+ await checker.notifyIfAvailable(out as unknown as NodeJS.WritableStream);
87
+
88
+ expect(out.value()).toBe('');
89
+ });
90
+
91
+ // ── older remote version → no output ────────────────────────────────────
92
+
93
+ it('writes nothing when latest version is older than current', async () => {
94
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(
95
+ jsonResponse({ tag_name: 'v0.9.0' }),
96
+ );
97
+
98
+ const checker = createChecker({
99
+ name: 'my-tool',
100
+ currentVersion: '1.0.0',
101
+ owner: 'acme',
102
+ repo: 'my-tool',
103
+ stateDir: tmpDir,
104
+ });
105
+
106
+ const out = new StringStream();
107
+ await checker.notifyIfAvailable(out as unknown as NodeJS.WritableStream);
108
+
109
+ expect(out.value()).toBe('');
110
+ });
111
+
112
+ // ── cache hit within TTL → fetch not called again ────────────────────────
113
+
114
+ it('does not call fetch again when cache is fresh (within TTL)', async () => {
115
+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
116
+ jsonResponse({ tag_name: 'v2.0.0' }),
117
+ );
118
+
119
+ const opts = {
120
+ name: 'my-tool',
121
+ currentVersion: '1.0.0',
122
+ owner: 'acme',
123
+ repo: 'my-tool',
124
+ stateDir: tmpDir,
125
+ cacheTTL: 60_000, // 1 minute
126
+ };
127
+
128
+ const checker = createChecker(opts);
129
+ const out = new StringStream();
130
+ // First call — populates cache.
131
+ await checker.notifyIfAvailable(out as unknown as NodeJS.WritableStream);
132
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
133
+
134
+ // Second call — should hit cache, not fetch.
135
+ const out2 = new StringStream();
136
+ await checker.notifyIfAvailable(out2 as unknown as NodeJS.WritableStream);
137
+ expect(fetchSpy).toHaveBeenCalledTimes(1); // still 1
138
+ });
139
+
140
+ // ── cache miss (expired) → fetch called again ────────────────────────────
141
+
142
+ it('calls fetch again when cache has expired', async () => {
143
+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
144
+ jsonResponse({ tag_name: 'v2.0.0' }),
145
+ );
146
+
147
+ const opts = {
148
+ name: 'my-tool',
149
+ currentVersion: '1.0.0',
150
+ owner: 'acme',
151
+ repo: 'my-tool',
152
+ stateDir: tmpDir,
153
+ cacheTTL: 1, // 1 ms — expires almost immediately
154
+ };
155
+
156
+ const checker = createChecker(opts);
157
+ const out = new StringStream();
158
+ // First call — populates cache.
159
+ await checker.notifyIfAvailable(out as unknown as NodeJS.WritableStream);
160
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
161
+
162
+ // Wait for TTL to expire.
163
+ await new Promise((r) => setTimeout(r, 5));
164
+
165
+ // Second call — cache expired, should fetch again.
166
+ const out2 = new StringStream();
167
+ await checker.notifyIfAvailable(out2 as unknown as NodeJS.WritableStream);
168
+ expect(fetchSpy).toHaveBeenCalledTimes(2);
169
+ });
170
+
171
+ // ── fetch throws → silently skipped ─────────────────────────────────────
172
+
173
+ it('silently skips and writes nothing when fetch throws', async () => {
174
+ vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('network error'));
175
+
176
+ const checker = createChecker({
177
+ name: 'my-tool',
178
+ currentVersion: '1.0.0',
179
+ owner: 'acme',
180
+ repo: 'my-tool',
181
+ stateDir: tmpDir,
182
+ });
183
+
184
+ const out = new StringStream();
185
+ // Must not throw.
186
+ await expect(
187
+ checker.notifyIfAvailable(out as unknown as NodeJS.WritableStream),
188
+ ).resolves.toBeUndefined();
189
+
190
+ expect(out.value()).toBe('');
191
+ });
192
+
193
+ // ── notice format ────────────────────────────────────────────────────────
194
+
195
+ it('formats the notice with correct owner/repo URL and versions', async () => {
196
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(
197
+ jsonResponse({ tag_name: 'v3.1.4' }),
198
+ );
199
+
200
+ const checker = createChecker({
201
+ name: 'awesome-cli',
202
+ currentVersion: '2.0.0',
203
+ owner: 'myorg',
204
+ repo: 'awesome-cli',
205
+ stateDir: tmpDir,
206
+ });
207
+
208
+ const out = new StringStream();
209
+ await checker.notifyIfAvailable(out as unknown as NodeJS.WritableStream);
210
+
211
+ const notice = out.value();
212
+ expect(notice).toContain('awesome-cli');
213
+ expect(notice).toContain('v2.0.0');
214
+ expect(notice).toContain('v3.1.4');
215
+ expect(notice).toContain('https://github.com/myorg/awesome-cli/releases/latest');
216
+ // Exact format check.
217
+ expect(notice).toBe(
218
+ '\nA new release of awesome-cli is available: v2.0.0 → v3.1.4\n' +
219
+ 'https://github.com/myorg/awesome-cli/releases/latest\n',
220
+ );
221
+ });
222
+
223
+ // ── tag_name without 'v' prefix ──────────────────────────────────────────
224
+
225
+ it('handles tag_name without v prefix', async () => {
226
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(
227
+ jsonResponse({ tag_name: '2.0.0' }),
228
+ );
229
+
230
+ const checker = createChecker({
231
+ name: 'my-tool',
232
+ currentVersion: '1.0.0',
233
+ owner: 'acme',
234
+ repo: 'my-tool',
235
+ stateDir: tmpDir,
236
+ });
237
+
238
+ const out = new StringStream();
239
+ await checker.notifyIfAvailable(out as unknown as NodeJS.WritableStream);
240
+
241
+ expect(out.value()).toContain('v2.0.0');
242
+ });
243
+
244
+ // ── non-200 HTTP response → silently skipped ─────────────────────────────
245
+
246
+ it('silently skips on non-200 HTTP response', async () => {
247
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(
248
+ jsonResponse({ message: 'Not Found' }, 404),
249
+ );
250
+
251
+ const checker = createChecker({
252
+ name: 'my-tool',
253
+ currentVersion: '1.0.0',
254
+ owner: 'acme',
255
+ repo: 'my-tool',
256
+ stateDir: tmpDir,
257
+ });
258
+
259
+ const out = new StringStream();
260
+ await expect(
261
+ checker.notifyIfAvailable(out as unknown as NodeJS.WritableStream),
262
+ ).resolves.toBeUndefined();
263
+
264
+ expect(out.value()).toBe('');
265
+ });
266
+
267
+ // ── pre-written stale cache on disk ─────────────────────────────────────
268
+
269
+ it('reads cache from disk and skips fetch when fresh', async () => {
270
+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
271
+ jsonResponse({ tag_name: 'v9.9.9' }),
272
+ );
273
+
274
+ // Write a fresh cache file manually.
275
+ const cacheFile = path.join(tmpDir, '.upgrade-my-tool-cache.json');
276
+ fs.writeFileSync(
277
+ cacheFile,
278
+ JSON.stringify({ version: '2.0.0', checkedAt: Date.now() }),
279
+ );
280
+
281
+ const checker = createChecker({
282
+ name: 'my-tool',
283
+ currentVersion: '1.0.0',
284
+ owner: 'acme',
285
+ repo: 'my-tool',
286
+ stateDir: tmpDir,
287
+ cacheTTL: 60_000,
288
+ });
289
+
290
+ const out = new StringStream();
291
+ await checker.notifyIfAvailable(out as unknown as NodeJS.WritableStream);
292
+
293
+ // Should use cached version 2.0.0, not fetch.
294
+ expect(fetchSpy).not.toHaveBeenCalled();
295
+ // 2.0.0 > 1.0.0 so notice is shown.
296
+ expect(out.value()).toContain('v2.0.0');
297
+ });
298
+ });