solforge 0.2.0 → 0.2.2

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 (56) hide show
  1. package/LICENSE +21 -0
  2. package/docs/API.md +379 -0
  3. package/docs/CONFIGURATION.md +407 -0
  4. package/package.json +67 -45
  5. package/src/api-server-entry.ts +109 -0
  6. package/src/commands/add-program.ts +337 -0
  7. package/src/commands/init.ts +122 -0
  8. package/src/commands/list.ts +136 -0
  9. package/src/commands/mint.ts +288 -0
  10. package/src/commands/start.ts +877 -0
  11. package/src/commands/status.ts +99 -0
  12. package/src/commands/stop.ts +406 -0
  13. package/src/config/manager.ts +157 -0
  14. package/src/gui/public/build/main.css +1 -0
  15. package/src/gui/public/build/main.js +303 -0
  16. package/src/gui/public/build/main.js.txt +231 -0
  17. package/src/index.ts +188 -0
  18. package/src/services/api-server.ts +485 -0
  19. package/src/services/port-manager.ts +177 -0
  20. package/src/services/process-registry.ts +154 -0
  21. package/src/services/program-cloner.ts +317 -0
  22. package/src/services/token-cloner.ts +809 -0
  23. package/src/services/validator.ts +295 -0
  24. package/src/types/config.ts +110 -0
  25. package/src/utils/shell.ts +110 -0
  26. package/src/utils/token-loader.ts +115 -0
  27. package/.agi/agi.sqlite +0 -0
  28. package/.claude/settings.local.json +0 -9
  29. package/.github/workflows/release-binaries.yml +0 -133
  30. package/.tmp/.787ebcdbf7b8fde8-00000000.hm +0 -0
  31. package/.tmp/.bffe6efebdf8aedc-00000000.hm +0 -0
  32. package/AGENTS.md +0 -271
  33. package/CLAUDE.md +0 -106
  34. package/PROJECT_STRUCTURE.md +0 -124
  35. package/SOLANA_KIT_GUIDE.md +0 -251
  36. package/SOLFORGE.md +0 -119
  37. package/biome.json +0 -34
  38. package/bun.lock +0 -743
  39. package/drizzle/0000_friendly_millenium_guard.sql +0 -53
  40. package/drizzle/0001_stale_sentinels.sql +0 -2
  41. package/drizzle/meta/0000_snapshot.json +0 -329
  42. package/drizzle/meta/0001_snapshot.json +0 -345
  43. package/drizzle/meta/_journal.json +0 -20
  44. package/drizzle.config.ts +0 -12
  45. package/index.ts +0 -21
  46. package/mint.sh +0 -47
  47. package/postcss.config.js +0 -6
  48. package/rpc-server.ts.backup +0 -519
  49. package/sf.config.json +0 -38
  50. package/tailwind.config.js +0 -27
  51. package/test-client.ts +0 -120
  52. package/tmp/inspect-html.ts +0 -4
  53. package/tmp/response-test.ts +0 -5
  54. package/tmp/test-html.ts +0 -5
  55. package/tmp/test-server.ts +0 -13
  56. package/tsconfig.json +0 -29
package/src/index.ts ADDED
@@ -0,0 +1,188 @@
1
+ #!/usr/bin/env bun
2
+
3
+ // Suppress bigint-buffer warning
4
+ const originalStderrWrite = process.stderr.write.bind(process.stderr);
5
+ process.stderr.write = function(chunk: any, encoding?: any, callback?: any) {
6
+ if (typeof chunk === 'string' && chunk.includes('bigint: Failed to load bindings')) {
7
+ return true; // Suppress this specific warning
8
+ }
9
+ return originalStderrWrite(chunk, encoding, callback);
10
+ };
11
+
12
+ import { Command } from "commander";
13
+ import chalk from "chalk";
14
+ import { existsSync } from "fs";
15
+ import { resolve } from "path";
16
+ import { initCommand } from "./commands/init.js";
17
+ import { statusCommand } from "./commands/status.js";
18
+ import { startCommand } from "./commands/start.js";
19
+ import { mintCommand } from "./commands/mint.js";
20
+ import { listCommand } from "./commands/list.js";
21
+ import { stopCommand, killCommand } from "./commands/stop.js";
22
+ import { addProgramCommand } from "./commands/add-program.js";
23
+ import packageJson from "../package.json" with { type: "json" };
24
+
25
+ const program = new Command();
26
+
27
+ program
28
+ .name("solforge")
29
+ .description("Solana localnet orchestration tool")
30
+ .version(packageJson.version);
31
+
32
+ // Check for sf.config.json in current directory
33
+ function findConfig(): string | null {
34
+ const configPath = resolve(process.cwd(), "sf.config.json");
35
+ return existsSync(configPath) ? configPath : null;
36
+ }
37
+
38
+ program
39
+ .command("init")
40
+ .description("Initialize a new sf.config.json in current directory")
41
+ .action(async () => {
42
+ console.log(chalk.blue("🚀 Initializing SolForge configuration..."));
43
+ await initCommand();
44
+ });
45
+
46
+ program
47
+ .command("start")
48
+ .description("Start localnet with current sf.config.json")
49
+ .option("--debug", "Enable debug logging to see commands and detailed output")
50
+ .option("--network", "Make API server accessible over network (binds to 0.0.0.0 instead of 127.0.0.1)")
51
+ .action(async (options) => {
52
+ const configPath = findConfig();
53
+ if (!configPath) {
54
+ console.error(
55
+ chalk.red("❌ No sf.config.json found in current directory")
56
+ );
57
+ console.log(chalk.yellow("💡 Run `solforge init` to create one"));
58
+ process.exit(1);
59
+ }
60
+
61
+ await startCommand(options.debug || false, options.network || false);
62
+ });
63
+
64
+ program
65
+ .command("list")
66
+ .description("List all running validators")
67
+ .action(async () => {
68
+ await listCommand();
69
+ });
70
+
71
+ program
72
+ .command("stop")
73
+ .description("Stop running validator(s)")
74
+ .argument("[validator-id]", "ID of validator to stop")
75
+ .option("--all", "Stop all running validators")
76
+ .option("--kill", "Force kill the validator (SIGKILL instead of SIGTERM)")
77
+ .action(async (validatorId, options) => {
78
+ await stopCommand(validatorId, options);
79
+ });
80
+
81
+ program
82
+ .command("kill")
83
+ .description("Force kill running validator(s)")
84
+ .argument("[validator-id]", "ID of validator to kill")
85
+ .option("--all", "Kill all running validators")
86
+ .action(async (validatorId, options) => {
87
+ await killCommand(validatorId, options);
88
+ });
89
+
90
+ program
91
+ .command("api-server")
92
+ .description("Start API server standalone")
93
+ .option("-p, --port <port>", "Port for API server", "3000")
94
+ .option("--host <host>", "Host to bind to (default: 127.0.0.1, use 0.0.0.0 for network access)")
95
+ .option("--rpc-url <url>", "Validator RPC URL", "http://127.0.0.1:8899")
96
+ .option("--faucet-url <url>", "Validator faucet URL", "http://127.0.0.1:9900")
97
+ .option("--work-dir <dir>", "Work directory", "./.solforge")
98
+ .action(async (options) => {
99
+ const configPath = findConfig();
100
+ if (!configPath) {
101
+ console.error(
102
+ chalk.red("❌ No sf.config.json found in current directory")
103
+ );
104
+ console.log(chalk.yellow("💡 Run `solforge init` to create one"));
105
+ process.exit(1);
106
+ }
107
+
108
+ // Import API server components
109
+ const { APIServer } = await import("./services/api-server.js");
110
+ const { configManager } = await import("./config/manager.js");
111
+
112
+ try {
113
+ await configManager.load(configPath);
114
+ const config = configManager.getConfig();
115
+
116
+ const apiServer = new APIServer({
117
+ port: parseInt(options.port),
118
+ host: options.host,
119
+ validatorRpcUrl: options.rpcUrl,
120
+ validatorFaucetUrl: options.faucetUrl,
121
+ config,
122
+ workDir: options.workDir,
123
+ });
124
+
125
+ const result = await apiServer.start();
126
+ if (result.success) {
127
+ console.log(chalk.green("✅ API Server started successfully!"));
128
+
129
+ // Keep the process alive
130
+ process.on("SIGTERM", async () => {
131
+ console.log(chalk.yellow("📡 API Server received SIGTERM, shutting down..."));
132
+ await apiServer.stop();
133
+ process.exit(0);
134
+ });
135
+
136
+ process.on("SIGINT", async () => {
137
+ console.log(chalk.yellow("📡 API Server received SIGINT, shutting down..."));
138
+ await apiServer.stop();
139
+ process.exit(0);
140
+ });
141
+
142
+ // Keep process alive
143
+ setInterval(() => {}, 1000);
144
+ } else {
145
+ console.error(chalk.red(`❌ Failed to start API server: ${result.error}`));
146
+ process.exit(1);
147
+ }
148
+ } catch (error) {
149
+ console.error(
150
+ chalk.red(
151
+ `❌ API Server error: ${
152
+ error instanceof Error ? error.message : String(error)
153
+ }`
154
+ )
155
+ );
156
+ process.exit(1);
157
+ }
158
+ });
159
+
160
+ program
161
+ .command("add-program")
162
+ .description("Add a program to sf.config.json")
163
+
164
+ .option("--program-id <address>", "Mainnet program ID to clone and deploy")
165
+ .option("--name <name>", "Friendly name for the program")
166
+ .option("--no-interactive", "Run in non-interactive mode")
167
+ .action(async (options) => {
168
+ await addProgramCommand(options);
169
+ });
170
+
171
+ program
172
+ .command("status")
173
+ .description("Show localnet status")
174
+ .action(async () => {
175
+ await statusCommand();
176
+ });
177
+
178
+ program.addCommand(mintCommand);
179
+
180
+ program
181
+ .command("reset")
182
+ .description("Reset localnet ledger")
183
+ .action(async () => {
184
+ console.log(chalk.blue("🔄 Resetting localnet..."));
185
+ // TODO: Implement reset
186
+ });
187
+
188
+ program.parse();
@@ -0,0 +1,485 @@
1
+ import express from "express";
2
+ import cors from "cors";
3
+ import { Server } from "http";
4
+ import { spawn, ChildProcess } from "child_process";
5
+ import { existsSync, readFileSync } from "fs";
6
+ import { join } from "path";
7
+ import chalk from "chalk";
8
+ import { Connection, PublicKey, Keypair } from "@solana/web3.js";
9
+ import { TOKEN_PROGRAM_ID } from "@solana/spl-token";
10
+ import { runCommand } from "../utils/shell.js";
11
+ import { TokenCloner } from "./token-cloner.js";
12
+ import { ProgramCloner } from "./program-cloner.js";
13
+ import { mintTokenToWallet as mintTokenToWalletShared } from "../commands/mint.js";
14
+ import {
15
+ loadClonedTokens,
16
+ findTokenByMint,
17
+ type ClonedToken,
18
+ } from "../utils/token-loader.js";
19
+ import type { Config } from "../types/config.js";
20
+
21
+ export interface APIServerConfig {
22
+ port: number;
23
+ host?: string;
24
+ validatorRpcUrl: string;
25
+ validatorFaucetUrl: string;
26
+ config: Config;
27
+ workDir: string;
28
+ }
29
+
30
+ export class APIServer {
31
+ private app: express.Application;
32
+ private server: Server | null = null;
33
+ private config: APIServerConfig;
34
+ private tokenCloner: TokenCloner;
35
+ private programCloner: ProgramCloner;
36
+ private connection: Connection;
37
+
38
+ constructor(config: APIServerConfig) {
39
+ this.config = config;
40
+ this.tokenCloner = new TokenCloner(config.workDir);
41
+ this.programCloner = new ProgramCloner(config.workDir);
42
+ this.connection = new Connection(config.validatorRpcUrl, "confirmed");
43
+
44
+ this.app = express();
45
+ this.setupMiddleware();
46
+ this.setupRoutes();
47
+ }
48
+
49
+ private setupMiddleware(): void {
50
+ this.app.use(cors());
51
+ this.app.use(express.json());
52
+
53
+ // Request logging
54
+ this.app.use((req, res, next) => {
55
+ console.log(chalk.gray(`🌐 API: ${req.method} ${req.path}`));
56
+ next();
57
+ });
58
+ }
59
+
60
+ private setupRoutes(): void {
61
+ const router = express.Router();
62
+
63
+ // Health check
64
+ router.get("/health", (req, res) => {
65
+ res.json({ status: "ok", timestamp: new Date().toISOString() });
66
+ });
67
+
68
+ // Get validator info
69
+ router.get("/validator/info", async (req, res) => {
70
+ try {
71
+ const version = await this.connection.getVersion();
72
+ const blockHeight = await this.connection.getBlockHeight();
73
+ const slotLeader = await this.connection.getSlotLeader();
74
+
75
+ res.json({
76
+ version,
77
+ blockHeight,
78
+ slotLeader: slotLeader.toString(),
79
+ rpcUrl: this.config.validatorRpcUrl,
80
+ faucetUrl: this.config.validatorFaucetUrl,
81
+ });
82
+ } catch (error) {
83
+ res.status(500).json({
84
+ error: "Failed to fetch validator info",
85
+ details: error instanceof Error ? error.message : String(error),
86
+ });
87
+ }
88
+ });
89
+
90
+ // Get all cloned tokens
91
+ router.get("/tokens", async (req, res) => {
92
+ try {
93
+ const clonedTokens = await this.getClonedTokens();
94
+ res.json({
95
+ tokens: clonedTokens.map((token) => ({
96
+ symbol: token.config.symbol,
97
+ mainnetMint: token.config.mainnetMint,
98
+ mintAuthority: token.mintAuthority.publicKey,
99
+ recipients: token.config.recipients,
100
+ cloneMetadata: token.config.cloneMetadata,
101
+ })),
102
+ count: clonedTokens.length,
103
+ });
104
+ } catch (error) {
105
+ res.status(500).json({
106
+ error: "Failed to fetch cloned tokens",
107
+ details: error instanceof Error ? error.message : String(error),
108
+ });
109
+ }
110
+ });
111
+
112
+ // Get all cloned programs
113
+ router.get("/programs", async (req, res) => {
114
+ try {
115
+ const clonedPrograms = await this.getClonedPrograms();
116
+ res.json({
117
+ programs: clonedPrograms,
118
+ count: clonedPrograms.length,
119
+ });
120
+ } catch (error) {
121
+ res.status(500).json({
122
+ error: "Failed to fetch cloned programs",
123
+ details: error instanceof Error ? error.message : String(error),
124
+ });
125
+ }
126
+ });
127
+
128
+ // Mint tokens to a wallet
129
+ router.post("/tokens/:mintAddress/mint", async (req, res) => {
130
+ try {
131
+ const { mintAddress } = req.params;
132
+ const { walletAddress, amount } = req.body;
133
+
134
+ if (!walletAddress || !amount) {
135
+ return res.status(400).json({
136
+ error: "Missing required fields: walletAddress and amount",
137
+ });
138
+ }
139
+
140
+ // Validate mint address
141
+ try {
142
+ new PublicKey(mintAddress);
143
+ } catch {
144
+ return res.status(400).json({
145
+ error: "Invalid mint address",
146
+ });
147
+ }
148
+
149
+ // Validate wallet address
150
+ try {
151
+ new PublicKey(walletAddress);
152
+ } catch {
153
+ return res.status(400).json({
154
+ error: "Invalid wallet address",
155
+ });
156
+ }
157
+
158
+ // Validate amount
159
+ if (!Number.isInteger(amount) || amount <= 0) {
160
+ return res.status(400).json({
161
+ error: "Amount must be a positive integer",
162
+ });
163
+ }
164
+
165
+ const result = await this.mintTokenToWallet(
166
+ mintAddress,
167
+ walletAddress,
168
+ amount
169
+ );
170
+ res.json(result);
171
+ } catch (error) {
172
+ res.status(500).json({
173
+ error: "Failed to mint tokens",
174
+ details: error instanceof Error ? error.message : String(error),
175
+ });
176
+ }
177
+ });
178
+
179
+ // Get account balances for a wallet
180
+ router.get("/wallet/:address/balances", async (req, res) => {
181
+ try {
182
+ const { address } = req.params;
183
+
184
+ // Validate wallet address
185
+ try {
186
+ new PublicKey(address);
187
+ } catch {
188
+ return res.status(400).json({
189
+ error: "Invalid wallet address",
190
+ });
191
+ }
192
+
193
+ const balances = await this.getWalletBalances(address);
194
+ res.json(balances);
195
+ } catch (error) {
196
+ res.status(500).json({
197
+ error: "Failed to fetch wallet balances",
198
+ details: error instanceof Error ? error.message : String(error),
199
+ });
200
+ }
201
+ });
202
+
203
+ // Airdrop SOL to a wallet
204
+ router.post("/airdrop", async (req, res) => {
205
+ try {
206
+ const { walletAddress, amount } = req.body;
207
+
208
+ if (!walletAddress || !amount) {
209
+ return res.status(400).json({
210
+ error: "Missing required fields: walletAddress and amount",
211
+ });
212
+ }
213
+
214
+ // Validate wallet address
215
+ try {
216
+ new PublicKey(walletAddress);
217
+ } catch {
218
+ return res.status(400).json({
219
+ error: "Invalid wallet address",
220
+ });
221
+ }
222
+
223
+ const result = await this.airdropSol(walletAddress, amount);
224
+ res.json(result);
225
+ } catch (error) {
226
+ res.status(500).json({
227
+ error: "Failed to airdrop SOL",
228
+ details: error instanceof Error ? error.message : String(error),
229
+ });
230
+ }
231
+ });
232
+
233
+ // Get recent transactions
234
+ router.get("/transactions/recent", async (req, res) => {
235
+ try {
236
+ const limit = Math.min(parseInt(req.query.limit as string) || 10, 100);
237
+ const signatures = await this.connection.getSignaturesForAddress(
238
+ new PublicKey("11111111111111111111111111111111"), // System program
239
+ { limit }
240
+ );
241
+
242
+ res.json({
243
+ transactions: signatures,
244
+ count: signatures.length,
245
+ });
246
+ } catch (error) {
247
+ res.status(500).json({
248
+ error: "Failed to fetch recent transactions",
249
+ details: error instanceof Error ? error.message : String(error),
250
+ });
251
+ }
252
+ });
253
+
254
+ this.app.use("/api", router);
255
+
256
+ // 404 handler
257
+ this.app.use("*", (req, res) => {
258
+ res.status(404).json({ error: "Endpoint not found" });
259
+ });
260
+ }
261
+
262
+ private async getClonedTokens(): Promise<ClonedToken[]> {
263
+ return await loadClonedTokens(
264
+ this.config.config.tokens,
265
+ this.config.workDir
266
+ );
267
+ }
268
+
269
+ private async getClonedPrograms(): Promise<
270
+ Array<{ name?: string; programId: string; filePath?: string }>
271
+ > {
272
+ const clonedPrograms: Array<{
273
+ name?: string;
274
+ programId: string;
275
+ filePath?: string;
276
+ }> = [];
277
+
278
+ for (const programConfig of this.config.config.programs) {
279
+ const programsDir = join(this.config.workDir, "programs");
280
+ const fileName = programConfig.name
281
+ ? `${programConfig.name.toLowerCase().replace(/\s+/g, "-")}.so`
282
+ : `${programConfig.mainnetProgramId}.so`;
283
+ const filePath = join(programsDir, fileName);
284
+
285
+ clonedPrograms.push({
286
+ name: programConfig.name,
287
+ programId: programConfig.mainnetProgramId,
288
+ filePath: existsSync(filePath) ? filePath : undefined,
289
+ });
290
+ }
291
+
292
+ return clonedPrograms;
293
+ }
294
+
295
+ private async mintTokenToWallet(
296
+ mintAddress: string,
297
+ walletAddress: string,
298
+ amount: number
299
+ ): Promise<any> {
300
+ const clonedTokens = await this.getClonedTokens();
301
+ const token = findTokenByMint(clonedTokens, mintAddress);
302
+
303
+ if (!token) {
304
+ throw new Error(`Token ${mintAddress} not found in cloned tokens`);
305
+ }
306
+
307
+ // Use the shared minting function from the mint command
308
+ await mintTokenToWalletShared(
309
+ token,
310
+ walletAddress,
311
+ amount,
312
+ this.config.validatorRpcUrl
313
+ );
314
+
315
+ return {
316
+ success: true,
317
+ symbol: token.config.symbol,
318
+ amount,
319
+ walletAddress,
320
+ mintAddress: token.config.mainnetMint,
321
+ };
322
+ }
323
+
324
+ private async getWalletBalances(walletAddress: string): Promise<any> {
325
+ try {
326
+ const publicKey = new PublicKey(walletAddress);
327
+
328
+ // Get SOL balance
329
+ const solBalance = await this.connection.getBalance(publicKey);
330
+
331
+ // Get token accounts
332
+ const tokenAccounts = await this.connection.getTokenAccountsByOwner(
333
+ publicKey,
334
+ {
335
+ programId: TOKEN_PROGRAM_ID,
336
+ }
337
+ );
338
+
339
+ const tokenBalances = [];
340
+ const clonedTokens = await this.getClonedTokens();
341
+
342
+ for (const tokenAccount of tokenAccounts.value) {
343
+ try {
344
+ const accountInfo = await this.connection.getAccountInfo(
345
+ tokenAccount.pubkey
346
+ );
347
+ if (accountInfo) {
348
+ // Parse token account data (simplified)
349
+ const data = accountInfo.data;
350
+ if (data.length >= 32) {
351
+ const mintBytes = data.slice(0, 32);
352
+ const mintAddress = new PublicKey(mintBytes).toBase58();
353
+
354
+ // Find matching cloned token
355
+ const clonedToken = clonedTokens.find(
356
+ (t) => t.config.mainnetMint === mintAddress
357
+ );
358
+
359
+ if (clonedToken) {
360
+ // Get token balance
361
+ const balance = await this.connection.getTokenAccountBalance(
362
+ tokenAccount.pubkey
363
+ );
364
+ tokenBalances.push({
365
+ mint: mintAddress,
366
+ symbol: clonedToken.config.symbol,
367
+ balance: balance.value.amount,
368
+ decimals: balance.value.decimals,
369
+ uiAmount: balance.value.uiAmount,
370
+ });
371
+ }
372
+ }
373
+ }
374
+ } catch (error) {
375
+ // Skip failed token accounts
376
+ continue;
377
+ }
378
+ }
379
+
380
+ return {
381
+ walletAddress,
382
+ solBalance: {
383
+ lamports: solBalance,
384
+ sol: solBalance / 1e9,
385
+ },
386
+ tokenBalances,
387
+ timestamp: new Date().toISOString(),
388
+ };
389
+ } catch (error) {
390
+ throw new Error(
391
+ `Failed to get wallet balances: ${
392
+ error instanceof Error ? error.message : String(error)
393
+ }`
394
+ );
395
+ }
396
+ }
397
+
398
+ private async airdropSol(
399
+ walletAddress: string,
400
+ amount: number
401
+ ): Promise<any> {
402
+ const result = await runCommand(
403
+ "solana",
404
+ [
405
+ "airdrop",
406
+ amount.toString(),
407
+ walletAddress,
408
+ "--url",
409
+ this.config.validatorRpcUrl,
410
+ ],
411
+ { silent: false, debug: false }
412
+ );
413
+
414
+ if (!result.success) {
415
+ throw new Error(`Failed to airdrop SOL: ${result.stderr}`);
416
+ }
417
+
418
+ return {
419
+ success: true,
420
+ amount,
421
+ walletAddress,
422
+ signature:
423
+ result.stdout.match(/Signature: ([A-Za-z0-9]+)/)?.[1] || "unknown",
424
+ };
425
+ }
426
+
427
+ async start(): Promise<{ success: boolean; error?: string }> {
428
+ return new Promise((resolve) => {
429
+ try {
430
+ const host = this.config.host || "127.0.0.1";
431
+ this.server = this.app.listen(this.config.port, host, () => {
432
+ console.log(
433
+ chalk.green(
434
+ `🚀 API Server started on http://${host}:${this.config.port}`
435
+ )
436
+ );
437
+ console.log(
438
+ chalk.gray(
439
+ ` 📋 Endpoints available at http://${host}:${this.config.port}/api`
440
+ )
441
+ );
442
+ resolve({ success: true });
443
+ });
444
+
445
+ this.server.on("error", (error) => {
446
+ console.error(
447
+ chalk.red(`❌ API Server failed to start: ${error.message}`)
448
+ );
449
+ resolve({ success: false, error: error.message });
450
+ });
451
+ } catch (error) {
452
+ resolve({
453
+ success: false,
454
+ error: error instanceof Error ? error.message : String(error),
455
+ });
456
+ }
457
+ });
458
+ }
459
+
460
+ async stop(): Promise<{ success: boolean; error?: string }> {
461
+ return new Promise((resolve) => {
462
+ if (!this.server) {
463
+ resolve({ success: true });
464
+ return;
465
+ }
466
+
467
+ this.server.close((error) => {
468
+ if (error) {
469
+ resolve({
470
+ success: false,
471
+ error: error instanceof Error ? error.message : String(error),
472
+ });
473
+ } else {
474
+ console.log(chalk.yellow("🛑 API Server stopped"));
475
+ resolve({ success: true });
476
+ }
477
+ this.server = null;
478
+ });
479
+ });
480
+ }
481
+
482
+ isRunning(): boolean {
483
+ return this.server !== null && this.server.listening;
484
+ }
485
+ }