@jango-blockchained/hoox-cli 0.4.1 → 0.5.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.
@@ -1,5 +1,7 @@
1
1
  /**
2
2
  * Types for the `hoox init` interactive setup wizard.
3
+ *
4
+ * Re-exports shared integration configs from @jango-blockchained/hoox-shared.
3
5
  */
4
6
 
5
7
  /** CLI flags for non-interactive mode. */
@@ -14,172 +16,8 @@ export interface InitOptions {
14
16
  prefix?: string;
15
17
  /** --accept-risk: Skip the risk acknowledgment confirmation */
16
18
  acceptRisk?: boolean;
19
+ /** --resume: Resume from saved wizard state */
20
+ resume?: boolean;
21
+ /** --preset: Use a preset worker template (non-interactive) */
22
+ preset?: string;
17
23
  }
18
-
19
- /** Definition of an integration that can be enabled during setup. */
20
- export interface IntegrationConfig {
21
- /** Unique key used for the multiselect value. */
22
- key: string;
23
- /** Display label shown in the multiselect prompt. */
24
- label: string;
25
- /** Which worker this integration maps to in wrangler.jsonc. */
26
- workerName: string;
27
- /** Secrets that must be collected for this integration (name → prompt label). */
28
- secrets: Record<string, string>;
29
- /** Extra non-secret environment variables for the worker. */
30
- vars?: Record<string, string>;
31
- }
32
-
33
- /** Shape of a single worker entry in wrangler.jsonc. */
34
- export interface WorkerConfig {
35
- enabled: boolean;
36
- path: string;
37
- vars: Record<string, string>;
38
- secrets: string[];
39
- }
40
-
41
- /** Shape of the wrangler.jsonc file. */
42
- export interface WorkersJsonConfig {
43
- global: {
44
- cloudflare_api_token: string;
45
- cloudflare_account_id: string;
46
- cloudflare_secret_store_id: string;
47
- subdomain_prefix: string;
48
- };
49
- workers: Record<string, WorkerConfig>;
50
- }
51
-
52
- /**
53
- * All supported integrations.
54
- * Exchanges (Binance, MEXC, Bybit) map to trade-worker.
55
- * Wallet maps to web3-wallet-worker, email to email-worker,
56
- * telegram to telegram-worker.
57
- */
58
- export const INTEGRATIONS: IntegrationConfig[] = [
59
- {
60
- key: "binance",
61
- label: "Binance Exchange",
62
- workerName: "trade-worker",
63
- secrets: {
64
- BINANCE_API_KEY: "Binance API Key",
65
- BINANCE_API_SECRET: "Binance API Secret",
66
- },
67
- },
68
- {
69
- key: "mexc",
70
- label: "MEXC Exchange",
71
- workerName: "trade-worker",
72
- secrets: {
73
- MEXC_API_KEY: "MEXC API Key",
74
- MEXC_API_SECRET: "MEXC API Secret",
75
- },
76
- },
77
- {
78
- key: "bybit",
79
- label: "Bybit Exchange",
80
- workerName: "trade-worker",
81
- secrets: {
82
- BYBIT_API_KEY: "Bybit API Key",
83
- BYBIT_API_SECRET: "Bybit API Secret",
84
- },
85
- },
86
- {
87
- key: "wallet",
88
- label: "Web3 Wallet (on-chain execution)",
89
- workerName: "web3-wallet-worker",
90
- secrets: {
91
- WALLET_MNEMONIC_SECRET: "Wallet Mnemonic Phrase",
92
- WALLET_PK_SECRET: "Wallet Private Key",
93
- },
94
- },
95
- {
96
- key: "email",
97
- label: "Email Signal Parsing",
98
- workerName: "email-worker",
99
- secrets: {
100
- EMAIL_HOST: "Email Host (IMAP server)",
101
- EMAIL_USER: "Email Username",
102
- EMAIL_PASS: "Email Password",
103
- INTERNAL_KEY: "Internal Auth Key",
104
- },
105
- vars: {
106
- USE_IMAP: "false",
107
- },
108
- },
109
- {
110
- key: "telegram",
111
- label: "Telegram Notifications",
112
- workerName: "telegram-worker",
113
- secrets: {
114
- TELEGRAM_BOT_TOKEN: "Telegram Bot Token",
115
- },
116
- },
117
- {
118
- key: "openai",
119
- label: "OpenAI (AI Agent)",
120
- workerName: "agent-worker",
121
- secrets: {
122
- AGENT_OPENAI_KEY: "OpenAI API Key",
123
- },
124
- },
125
- {
126
- key: "anthropic",
127
- label: "Anthropic (AI Agent)",
128
- workerName: "agent-worker",
129
- secrets: {
130
- AGENT_ANTHROPIC_KEY: "Anthropic API Key",
131
- },
132
- },
133
- {
134
- key: "google-ai",
135
- label: "Google AI (AI Agent)",
136
- workerName: "agent-worker",
137
- secrets: {
138
- AGENT_GOOGLE_KEY: "Google AI API Key",
139
- },
140
- },
141
- {
142
- key: "home-assistant",
143
- label: "Home Assistant (Smart Home)",
144
- workerName: "hoox",
145
- secrets: {
146
- HA_TOKEN_BINDING: "Home Assistant Token",
147
- },
148
- },
149
- ];
150
-
151
- /**
152
- * Base workers that are always enabled regardless of integration selection.
153
- */
154
- export const BASE_WORKERS: Record<string, Omit<WorkerConfig, "secrets">> = {
155
- "d1-worker": {
156
- enabled: true,
157
- path: "workers/d1-worker",
158
- vars: { database_name: "my-database" },
159
- },
160
- hoox: {
161
- enabled: true,
162
- path: "workers/hoox",
163
- vars: {},
164
- },
165
- "agent-worker": {
166
- enabled: true,
167
- path: "workers/agent-worker",
168
- vars: {},
169
- },
170
- "analytics-worker": {
171
- enabled: true,
172
- path: "workers/analytics-worker",
173
- vars: {},
174
- },
175
- };
176
-
177
- /**
178
- * Base secrets for base workers (not integration-driven).
179
- */
180
- export const BASE_SECRETS: Record<string, string[]> = {
181
- hoox: ["WEBHOOK_API_KEY_BINDING"],
182
- "agent-worker": ["AGENT_INTERNAL_KEY"],
183
- "analytics-worker": ["CLOUDFLARE_API_TOKEN"],
184
- "trade-worker": ["API_SERVICE_KEY"],
185
- };
@@ -0,0 +1 @@
1
+ export { registerLogsCommand } from "./logs-command.js";
@@ -0,0 +1,294 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Unit tests for the logs command.
4
+ *
5
+ * Mocks Bun.spawn (for wrangler tail), ConfigService, and stream readers
6
+ * to verify command logic in isolation. Uses the actual registerLogsCommand
7
+ * function but intercepts the action handlers by stubbing dependencies.
8
+ *
9
+ * IMPORTANT: Saves and restores all prototype modifications in afterEach
10
+ * to prevent cross-test pollution (no mock.module usage).
11
+ */
12
+
13
+ import { afterEach, beforeEach, describe, expect, it, mock } from "bun:test";
14
+ import { Command } from "commander";
15
+ import { ConfigService } from "../../services/config/config-service.js";
16
+ import { registerLogsCommand } from "./logs-command.js";
17
+ import { ExitCode } from "../../utils/errors.js";
18
+
19
+ // ---------------------------------------------------------------------------
20
+ // Mock setup — stub Bun.spawn and ConfigService
21
+ // ---------------------------------------------------------------------------
22
+
23
+ // Preserve originals for restoration in afterEach
24
+ const origLoad = ConfigService.prototype.load;
25
+ const origListEnabled = ConfigService.prototype.listEnabledWorkers;
26
+ const origBunSpawn = Bun.spawn;
27
+
28
+ /**
29
+ * Creates a mock ReadableStream that emits the given chunks and then closes.
30
+ * This simulates the stdout of a wrangler tail process.
31
+ */
32
+ function createMockReader(
33
+ chunks: string[],
34
+ delayMs = 0
35
+ ): ReadableStreamDefaultReader<Uint8Array> {
36
+ const encoder = new TextEncoder();
37
+ let chunkIndex = 0;
38
+
39
+ const stream = new ReadableStream<Uint8Array>({
40
+ async start(controller) {
41
+ for (const chunk of chunks) {
42
+ if (delayMs > 0) {
43
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
44
+ }
45
+ controller.enqueue(encoder.encode(chunk));
46
+ chunkIndex++;
47
+ }
48
+ controller.close();
49
+ },
50
+ });
51
+
52
+ return stream.getReader();
53
+ }
54
+
55
+ /**
56
+ * Creates a mock Bun.spawn return value that simulates a clean exit.
57
+ */
58
+ function createMockSpawn(chunks: string[], exitCode = 0) {
59
+ const reader = createMockReader(chunks);
60
+ return {
61
+ stdout: {
62
+ getReader: () => reader,
63
+ },
64
+ stderr: {
65
+ getReader: () => createMockReader([]),
66
+ },
67
+ exited: Promise.resolve(exitCode),
68
+ killed: false,
69
+ kill: mock(() => {}),
70
+ };
71
+ }
72
+
73
+ let spawnMock: ReturnType<typeof mock>;
74
+ let loadMock: ReturnType<typeof mock>;
75
+ let listEnabledWorkersMock: ReturnType<typeof mock>;
76
+
77
+ beforeEach(() => {
78
+ mock.restore();
79
+
80
+ // Restore ConfigService prototypes to originals first
81
+ ConfigService.prototype.load = origLoad;
82
+ ConfigService.prototype.listEnabledWorkers = origListEnabled;
83
+
84
+ // Restore Bun.spawn
85
+ (Bun as unknown as Record<string, unknown>).spawn = origBunSpawn;
86
+
87
+ // Mock Bun.spawn
88
+ spawnMock = mock((_args: string[], _options?: unknown) => {
89
+ return createMockSpawn(["Test log line\n"]);
90
+ });
91
+ (Bun as unknown as Record<string, unknown>).spawn = spawnMock;
92
+
93
+ // Stub ConfigService prototype methods
94
+ loadMock = mock(async () => ({}));
95
+ listEnabledWorkersMock = mock(() => ["d1-worker", "hoox", "trade-worker"]);
96
+
97
+ ConfigService.prototype.load = loadMock;
98
+ ConfigService.prototype.listEnabledWorkers = listEnabledWorkersMock;
99
+ });
100
+
101
+ afterEach(() => {
102
+ mock.restore();
103
+
104
+ // Restore ConfigService prototypes
105
+ ConfigService.prototype.load = origLoad;
106
+ ConfigService.prototype.listEnabledWorkers = origListEnabled;
107
+
108
+ // Restore Bun.spawn (individual property assignment — NOT globalThis.Bun)
109
+ (Bun as unknown as Record<string, unknown>).spawn = origBunSpawn;
110
+ });
111
+
112
+ // ---------------------------------------------------------------------------
113
+ // Helpers
114
+ // ---------------------------------------------------------------------------
115
+
116
+ /**
117
+ * Create a fresh Commander program with the logs command registered.
118
+ * Uses a custom name and exitOverride to prevent process exits during tests.
119
+ */
120
+ function createProgram(): Command {
121
+ const program = new Command().name("hoox-test").exitOverride(() => {
122
+ // Suppress Commander's own exit during tests
123
+ });
124
+ registerLogsCommand(program);
125
+ return program;
126
+ }
127
+
128
+ // ---------------------------------------------------------------------------
129
+ // Tests
130
+ // ---------------------------------------------------------------------------
131
+
132
+ describe("registerLogsCommand", () => {
133
+ // -- Command registration -------------------------------------------------
134
+
135
+ it("registers 'logs' as a command on the program", () => {
136
+ const program = createProgram();
137
+ const logsCmd = program.commands.find((c) => c.name() === "logs");
138
+ expect(logsCmd).toBeDefined();
139
+ });
140
+
141
+ it("registers 'logs worker <name>' subcommand", () => {
142
+ const program = createProgram();
143
+ const logsCmd = program.commands.find((c) => c.name() === "logs");
144
+ expect(logsCmd).toBeDefined();
145
+ const workerCmd = logsCmd!.commands.find((c) => c.name() === "worker");
146
+ expect(workerCmd).toBeDefined();
147
+ expect(workerCmd!.description()).toContain("Tail logs for a specific");
148
+ // The argument should be <name>
149
+ const args = workerCmd!.registeredArguments;
150
+ expect(args.some((a) => a.name() === "name")).toBe(true);
151
+ });
152
+
153
+ it("registers 'logs all' subcommand", () => {
154
+ const program = createProgram();
155
+ const logsCmd = program.commands.find((c) => c.name() === "logs");
156
+ expect(logsCmd).toBeDefined();
157
+ const allCmd = logsCmd!.commands.find((c) => c.name() === "all");
158
+ expect(allCmd).toBeDefined();
159
+ expect(allCmd!.description()).toContain("all enabled workers");
160
+ });
161
+
162
+ it("'logs worker' has --level, --follow, --json options", () => {
163
+ const program = createProgram();
164
+ const logsCmd = program.commands.find((c) => c.name() === "logs");
165
+ const workerCmd = logsCmd!.commands.find((c) => c.name() === "worker");
166
+ expect(workerCmd).toBeDefined();
167
+
168
+ const optionNames = workerCmd!.options.map((o) => o.long);
169
+ expect(optionNames).toContain("--level");
170
+ expect(optionNames).toContain("--follow");
171
+ expect(optionNames).toContain("--json");
172
+ });
173
+
174
+ it("'logs all' has --level, --follow, --json options", () => {
175
+ const program = createProgram();
176
+ const logsCmd = program.commands.find((c) => c.name() === "logs");
177
+ const allCmd = logsCmd!.commands.find((c) => c.name() === "all");
178
+ expect(allCmd).toBeDefined();
179
+
180
+ const optionNames = allCmd!.options.map((o) => o.long);
181
+ expect(optionNames).toContain("--level");
182
+ expect(optionNames).toContain("--follow");
183
+ expect(optionNames).toContain("--json");
184
+ });
185
+
186
+ // -- logs worker <name> ---------------------------------------------------
187
+
188
+ describe("logs worker <name>", () => {
189
+ it("spawns wrangler tail for the specified worker", async () => {
190
+ const program = createProgram();
191
+ await program.parseAsync(["logs", "worker", "hoox"], { from: "user" });
192
+
193
+ // Verify wrangler tail was called with the worker name
194
+ expect(spawnMock).toHaveBeenCalled();
195
+ const callArgs = (
196
+ spawnMock as unknown as { mock: { calls: Array<unknown[]> } }
197
+ ).mock.calls[0];
198
+ const spawnArgs = callArgs[0] as string[];
199
+ expect(spawnArgs).toContain("wrangler");
200
+ expect(spawnArgs).toContain("tail");
201
+ expect(spawnArgs).toContain("hoox");
202
+ });
203
+
204
+ it("passes --format json to wrangler when --json flag is set", async () => {
205
+ const program = createProgram();
206
+ await program.parseAsync(["logs", "worker", "hoox", "--json"], {
207
+ from: "user",
208
+ });
209
+
210
+ const callArgs = (
211
+ spawnMock as unknown as { mock: { calls: Array<unknown[]> } }
212
+ ).mock.calls[0];
213
+ const spawnArgs = callArgs[0] as string[];
214
+ expect(spawnArgs).toContain("--format");
215
+ expect(spawnArgs).toContain("json");
216
+ });
217
+
218
+ it("passes --format json to wrangler when --level is set to non-all", async () => {
219
+ const program = createProgram();
220
+ await program.parseAsync(["logs", "worker", "hoox", "--level", "error"], {
221
+ from: "user",
222
+ });
223
+
224
+ const callArgs = (
225
+ spawnMock as unknown as { mock: { calls: Array<unknown[]> } }
226
+ ).mock.calls[0];
227
+ const spawnArgs = callArgs[0] as string[];
228
+ expect(spawnArgs).toContain("--format");
229
+ expect(spawnArgs).toContain("json");
230
+ });
231
+
232
+ it("does NOT pass --format json when --level is all and --json not set", async () => {
233
+ const program = createProgram();
234
+ await program.parseAsync(["logs", "worker", "hoox"], { from: "user" });
235
+
236
+ const callArgs = (
237
+ spawnMock as unknown as { mock: { calls: Array<unknown[]> } }
238
+ ).mock.calls[0];
239
+ const spawnArgs = callArgs[0] as string[];
240
+ expect(spawnArgs).not.toContain("--format");
241
+ });
242
+
243
+ it("handles spawn failure gracefully", async () => {
244
+ spawnMock = mock(() => {
245
+ throw new Error("wrangler not found");
246
+ });
247
+ (Bun as unknown as Record<string, unknown>).spawn = spawnMock;
248
+
249
+ const program = createProgram();
250
+ await program.parseAsync(["logs", "worker", "hoox"], { from: "user" });
251
+
252
+ expect(process.exitCode).toBe(ExitCode.ERROR);
253
+ });
254
+ });
255
+
256
+ // -- logs all -------------------------------------------------------------
257
+
258
+ describe("logs all", () => {
259
+ it("calls ConfigService.listEnabledWorkers and spawns tail for each", async () => {
260
+ listEnabledWorkersMock = mock(() => ["hoox", "trade-worker"]);
261
+ ConfigService.prototype.listEnabledWorkers = listEnabledWorkersMock;
262
+
263
+ const program = createProgram();
264
+ await program.parseAsync(["logs", "all"], { from: "user" });
265
+
266
+ expect(listEnabledWorkersMock).toHaveBeenCalled();
267
+ // Should spawn two processes (one for each worker)
268
+ expect(spawnMock).toHaveBeenCalledTimes(2);
269
+ });
270
+
271
+ it("handles no enabled workers gracefully", async () => {
272
+ listEnabledWorkersMock = mock(() => []);
273
+ ConfigService.prototype.listEnabledWorkers = listEnabledWorkersMock;
274
+
275
+ const program = createProgram();
276
+ await program.parseAsync(["logs", "all"], { from: "user" });
277
+
278
+ // Should NOT spawn any processes
279
+ expect(spawnMock).toHaveBeenCalledTimes(0);
280
+ });
281
+
282
+ it("handles config load failure gracefully", async () => {
283
+ loadMock = mock(async () => {
284
+ throw new Error("Config file not found");
285
+ });
286
+ ConfigService.prototype.load = loadMock;
287
+
288
+ const program = createProgram();
289
+ await program.parseAsync(["logs", "all"], { from: "user" });
290
+
291
+ expect(process.exitCode).toBe(ExitCode.ERROR);
292
+ });
293
+ });
294
+ });