apiforge-analyzer 1.2.1 → 1.3.0

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.
package/dist/esm/cli.js CHANGED
@@ -1,9 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
  import { group, intro, outro, text, select, password, confirm, tasks, note, log, isCancel, cancel, spinner, } from '@clack/prompts';
3
- import { readFileSync, existsSync, writeFileSync, unlinkSync } from 'fs';
3
+ import { readFileSync, existsSync, writeFileSync, unlinkSync, readdirSync } from 'fs';
4
4
  import { join } from 'path';
5
5
  import { spawn } from 'child_process';
6
6
  import axios from 'axios';
7
+ import { detectArchitectureType } from './arch-detect.js';
8
+ import { uploadRoutes } from './uploader.js';
7
9
  // ─── ANSI colour helpers ──────────────────────────────────────────────────────
8
10
  const r = '\x1b[0m';
9
11
  const b = '\x1b[1m';
@@ -20,7 +22,7 @@ const green = (s) => `${gn}${s}${r}`;
20
22
  const yellow = (s) => `${yl}${s}${r}`;
21
23
  const red = (s) => `${rd}${s}${r}`;
22
24
  const white = (s) => `${wh}${s}${r}`;
23
- const VERSION = '1.2.0';
25
+ const VERSION = '1.3.0';
24
26
  // Built-in URLs — users never need to configure these
25
27
  const BACKEND_PROD = 'https://apiforgeapi.brainfogagency.com';
26
28
  const DASHBOARD_PROD = 'https://apiforge.brainfogagency.com/dashboard';
@@ -80,25 +82,6 @@ async function main() {
80
82
  if (isCancel(answers))
81
83
  process.exit(0);
82
84
  const { projectName, apiKey, baseUrl } = answers;
83
- // ── Select run command ────────────────────────────────────────────────────
84
- const scripts = detectScripts();
85
- const scriptOptions = scripts.map(s => ({
86
- value: s.command,
87
- label: `${bold(s.name)} ${dim('→')} ${dim(s.command)}`,
88
- }));
89
- if (scriptOptions.length === 0) {
90
- log.warn('No scripts found in package.json — please ensure you have a start/dev script.');
91
- cancel('No run script available.');
92
- process.exit(1);
93
- }
94
- const runCommand = await select({
95
- message: 'Which command starts your server?',
96
- options: scriptOptions,
97
- });
98
- if (isCancel(runCommand)) {
99
- cancel('Cancelled.');
100
- process.exit(0);
101
- }
102
85
  // ── Select backend ────────────────────────────────────────────────────────
103
86
  const backendChoice = await select({
104
87
  message: 'Send routes to',
@@ -122,13 +105,72 @@ async function main() {
122
105
  const isLocal = backendChoice === 'local';
123
106
  const backendUrl = isLocal ? BACKEND_LOCAL : BACKEND_PROD;
124
107
  const dashboardUrl = isLocal ? DASHBOARD_LOCAL : DASHBOARD_PROD;
108
+ // ── Detect architecture type ─────────────────────────────────────────────
109
+ const archResult = detectArchitectureType(process.cwd());
110
+ const archLabel = {
111
+ 'monolithic': cyan('Monolithic'),
112
+ 'modular-monolithic': cyan('Modular Monolithic'),
113
+ 'microservices': cyan('Microservices'),
114
+ };
115
+ // ── Full multi-service mode when apiforge.config.json exists ─────────────
116
+ if (archResult.type === 'microservices') {
117
+ let microConfig = loadMicroConfig();
118
+ // Auto-create apiforge.config.json if not present
119
+ if (!microConfig) {
120
+ microConfig = await buildAndSaveConfig(projectName);
121
+ }
122
+ if (microConfig && microConfig.services.length > 0) {
123
+ log.info(dim('─────────────────────────────────────────────────'));
124
+ log.info(`${dim('Project:')} ${bold(projectName)}`);
125
+ log.info(`${dim('Backend:')} ${cyan(backendUrl)}`);
126
+ log.info(`${dim('Architecture:')} ${archLabel['microservices']}`);
127
+ log.info(`${dim('Services:')} ${bold(String(microConfig.services.length))} ${dim('(from apiforge.config.json)')}`);
128
+ log.info(dim('─────────────────────────────────────────────────'));
129
+ await microservicesFlow(microConfig, { projectName, apiKey, baseUrl, backendUrl, dashboardUrl });
130
+ return;
131
+ }
132
+ }
133
+ // ── Single-service: ask for run command ───────────────────────────────────
134
+ const scripts = detectScripts();
135
+ const scriptOptions = scripts.map(s => ({
136
+ value: s.command,
137
+ label: `${bold(s.name)} ${dim('→')} ${dim(s.command)}`,
138
+ }));
139
+ if (scriptOptions.length === 0) {
140
+ log.warn('No scripts found in package.json — please ensure you have a start/dev script.');
141
+ cancel('No run script available.');
142
+ process.exit(1);
143
+ }
144
+ const runCommand = await select({
145
+ message: 'Which command starts your server?',
146
+ options: scriptOptions,
147
+ });
148
+ if (isCancel(runCommand)) {
149
+ cancel('Cancelled.');
150
+ process.exit(0);
151
+ }
152
+ if (archResult.type === 'microservices') {
153
+ note([
154
+ `${yellow('Microservices architecture detected.')}`,
155
+ '',
156
+ `${dim('Add an')} ${bold('apiforge.config.json')} ${dim('to document all services automatically:')}`,
157
+ '',
158
+ ` ${cyan('{ "services": [{ "name": "auth", "dir": "./services/auth" }] }')}`,
159
+ '',
160
+ `${dim('For now, analyzing the single service started by the selected command.')}`,
161
+ ].join('\n'), 'Multi-service tip');
162
+ }
125
163
  log.info(dim('─────────────────────────────────────────────────'));
126
- log.info(`${dim('Project:')} ${bold(projectName)}`);
127
- log.info(`${dim('Command:')} ${bold(runCommand)}`);
128
- log.info(`${dim('Backend:')} ${cyan(backendUrl)}`);
164
+ log.info(`${dim('Project:')} ${bold(projectName)}`);
165
+ log.info(`${dim('Command:')} ${bold(runCommand)}`);
166
+ log.info(`${dim('Backend:')} ${cyan(backendUrl)}`);
167
+ log.info(`${dim('Architecture:')} ${archLabel[archResult.type]}`);
129
168
  log.info(dim('─────────────────────────────────────────────────'));
169
+ if (archResult.moduleNames.length > 0) {
170
+ log.info(`${dim('Modules found:')} ${archResult.moduleNames.map(m => bold(m)).join(', ')}`);
171
+ }
130
172
  // ── Detect & patch entry file ─────────────────────────────────────────────
131
- const entryFile = detectEntryFile() ?? await askEntryFile();
173
+ const entryFile = detectEntryFile(archResult.type) ?? await askEntryFile(archResult.type);
132
174
  let injected = false;
133
175
  let linesAdded = 0;
134
176
  await tasks([
@@ -151,7 +193,7 @@ async function main() {
151
193
  tryUnlink(join(process.cwd(), LOCK_FILE));
152
194
  // Store API key in .env.local — never embed it in source code
153
195
  persistApiKeyToEnv(apiKey);
154
- const result = injectCode(entryFile, projectName, apiKey, baseUrl, backendUrl);
196
+ const result = injectCode(entryFile, projectName, apiKey, baseUrl, backendUrl, archResult.type);
155
197
  injected = !result.alreadyInjected;
156
198
  linesAdded = result.linesAdded ?? 0;
157
199
  if (result.alreadyInjected) {
@@ -248,6 +290,246 @@ async function main() {
248
290
  }[approval.status];
249
291
  outro(outroMsg);
250
292
  }
293
+ /**
294
+ * Scan the project for services and interactively write apiforge.config.json.
295
+ * Called when microservices arch is detected but no config file exists yet.
296
+ */
297
+ async function buildAndSaveConfig(projectName) {
298
+ const cwd = process.cwd();
299
+ // Collect services from filesystem scan (same logic as findServiceEntries but raw)
300
+ const discovered = [];
301
+ for (const parentDir of ['services', 'apps', 'packages', 'microservices', 'src/services']) {
302
+ const parentPath = join(cwd, parentDir);
303
+ if (!existsSync(parentPath))
304
+ continue;
305
+ try {
306
+ const subdirs = readdirSync(parentPath, { withFileTypes: true }).filter(d => d.isDirectory());
307
+ for (const subdir of subdirs) {
308
+ const entry = findEntryInDir(join(parentPath, subdir.name));
309
+ if (entry) {
310
+ discovered.push({ name: subdir.name, dir: `./${parentDir}/${subdir.name}` });
311
+ }
312
+ }
313
+ }
314
+ catch { }
315
+ if (discovered.length > 0)
316
+ break;
317
+ }
318
+ if (discovered.length === 0)
319
+ return null;
320
+ note([
321
+ bold(`Found ${discovered.length} service${discovered.length > 1 ? 's' : ''}:`),
322
+ '',
323
+ ...discovered.map(s => ` ${dim('·')} ${bold(s.name)} ${dim('→')} ${dim(s.dir)}`),
324
+ '',
325
+ `${dim('apiforge.config.json will be created so you never have to set this up again.')}`,
326
+ ].join('\n'), 'Auto-detected services');
327
+ const shouldCreate = await confirm({
328
+ message: `Create apiforge.config.json with these ${discovered.length} services?`,
329
+ initialValue: true,
330
+ });
331
+ if (isCancel(shouldCreate) || !shouldCreate)
332
+ return null;
333
+ const config = {
334
+ projectName,
335
+ architectureType: 'microservices',
336
+ services: discovered.map(s => ({ name: s.name, dir: s.dir })),
337
+ };
338
+ writeFileSync(join(cwd, 'apiforge.config.json'), JSON.stringify(config, null, 2) + '\n', 'utf-8');
339
+ log.success(green(`✓ Created apiforge.config.json (${discovered.length} services)`));
340
+ log.info(dim(' Commit this file so teammates can run apiforge without re-setup.'));
341
+ return { services: discovered };
342
+ }
343
+ function loadMicroConfig() {
344
+ for (const cfgName of ['apiforge.config.json', '.apiforge.json']) {
345
+ try {
346
+ const cfg = JSON.parse(readFileSync(join(process.cwd(), cfgName), 'utf-8'));
347
+ if (Array.isArray(cfg.services) && cfg.services.length > 0) {
348
+ return { projectName: cfg.projectName, services: cfg.services };
349
+ }
350
+ }
351
+ catch { }
352
+ }
353
+ return null;
354
+ }
355
+ function serviceNodeCommand(entryRelPath) {
356
+ if (entryRelPath.endsWith('.ts')) {
357
+ const hasTsx = existsSync(join(process.cwd(), 'node_modules/.bin/tsx'));
358
+ const hasTsNode = existsSync(join(process.cwd(), 'node_modules/.bin/ts-node'));
359
+ if (hasTsx)
360
+ return `node_modules/.bin/tsx ${entryRelPath}`;
361
+ if (hasTsNode)
362
+ return `node_modules/.bin/ts-node ${entryRelPath}`;
363
+ return `npx --yes tsx ${entryRelPath}`;
364
+ }
365
+ return `node ${entryRelPath}`;
366
+ }
367
+ function waitForServiceStatusFile(statusFile, timeoutMs) {
368
+ return new Promise(resolve => {
369
+ const fullPath = join(process.cwd(), statusFile);
370
+ const poller = setInterval(() => {
371
+ try {
372
+ if (!existsSync(fullPath))
373
+ return;
374
+ const data = JSON.parse(readFileSync(fullPath, 'utf-8'));
375
+ if (data.status === 'collected' && Array.isArray(data.routes)) {
376
+ clearInterval(poller);
377
+ clearTimeout(timer);
378
+ resolve(data.routes);
379
+ }
380
+ }
381
+ catch { }
382
+ }, 500);
383
+ const timer = setTimeout(() => {
384
+ clearInterval(poller);
385
+ resolve(null);
386
+ }, timeoutMs);
387
+ });
388
+ }
389
+ async function microservicesFlow(config, opts) {
390
+ const cwd = process.cwd();
391
+ const allRoutes = [];
392
+ const serviceMeta = [];
393
+ const injectedFiles = [];
394
+ // Clear any stale per-service status files
395
+ for (const svc of config.services) {
396
+ tryUnlink(join(cwd, `.apiforge-status-${svc.name}.json`));
397
+ }
398
+ tryUnlink(join(cwd, STATUS_FILE));
399
+ tryUnlink(join(cwd, LOCK_FILE));
400
+ persistApiKeyToEnv(opts.apiKey);
401
+ note([
402
+ bold(`Analyzing ${config.services.length} service${config.services.length > 1 ? 's' : ''}…`),
403
+ '',
404
+ ...config.services.map(s => ` ${dim('·')} ${bold(s.name)} ${dim('→')} ${dim(s.dir)}`),
405
+ '',
406
+ dim('Each service is started individually and its routes are collected.'),
407
+ ].join('\n'), 'Multi-service analysis');
408
+ for (const svc of config.services) {
409
+ const svcSpin = spinner();
410
+ svcSpin.start(`${bold(svc.name)} — starting…`);
411
+ const svcDir = svc.dir.replace(/^\.\//, '');
412
+ // Resolve entry file
413
+ const relEntry = svc.entryFile ?? findEntryInDir(join(cwd, svcDir));
414
+ if (!relEntry) {
415
+ svcSpin.stop(yellow(`◌ ${svc.name} — no entry file found, skipping`));
416
+ continue;
417
+ }
418
+ const fullEntry = join(svcDir, relEntry);
419
+ const statusFile = `.apiforge-status-${svc.name}.json`;
420
+ // Inject collection snippet (upload: false, writes to per-service status file)
421
+ injectCode(fullEntry, opts.projectName, opts.apiKey, opts.baseUrl, opts.backendUrl, 'microservices', {
422
+ serviceName: svc.name,
423
+ statusFile,
424
+ });
425
+ injectedFiles.push(fullEntry);
426
+ // Start service with plain node (or tsx for .ts files)
427
+ const startCmd = svc.startCommand ?? serviceNodeCommand(fullEntry);
428
+ const child = spawn(startCmd, {
429
+ cwd,
430
+ stdio: 'ignore',
431
+ shell: true,
432
+ env: { ...process.env },
433
+ detached: false,
434
+ });
435
+ // Wait up to 30 s for the status file to appear
436
+ const routes = await waitForServiceStatusFile(statusFile, 30000);
437
+ // Kill service process
438
+ try {
439
+ child.kill('SIGTERM');
440
+ }
441
+ catch { }
442
+ tryUnlink(join(cwd, statusFile));
443
+ if (routes && routes.length > 0) {
444
+ const annotated = routes.map((r) => ({ ...r, service: svc.name }));
445
+ allRoutes.push(...annotated);
446
+ serviceMeta.push({ name: svc.name, baseUrl: svc.baseUrl });
447
+ svcSpin.stop(green(`✓ ${svc.name} — ${routes.length} routes collected`));
448
+ }
449
+ else {
450
+ svcSpin.stop(yellow(`◌ ${svc.name} — no routes collected (timeout or error)`));
451
+ }
452
+ // Remove injected code
453
+ removeInjectedCode(fullEntry);
454
+ injectedFiles.splice(injectedFiles.indexOf(fullEntry), 1);
455
+ }
456
+ // Safety: clean up any remaining injections (e.g. if process was interrupted)
457
+ for (const f of injectedFiles)
458
+ removeInjectedCode(f);
459
+ if (allRoutes.length === 0) {
460
+ log.error(red('No routes were collected from any service.'));
461
+ outro(red('Analysis failed.'));
462
+ process.exit(1);
463
+ }
464
+ // Upload aggregated routes
465
+ const uploadSpin = spinner();
466
+ uploadSpin.start(`Uploading ${allRoutes.length} routes from ${serviceMeta.length} service${serviceMeta.length > 1 ? 's' : ''}…`);
467
+ const uploadResult = await uploadRoutes(allRoutes, {
468
+ projectName: opts.projectName,
469
+ apiKey: opts.apiKey,
470
+ baseUrl: opts.baseUrl,
471
+ apiForgeUrl: opts.backendUrl,
472
+ architectureType: 'microservices',
473
+ services: serviceMeta,
474
+ });
475
+ if (!uploadResult) {
476
+ uploadSpin.stop(red('✗ Upload failed'));
477
+ outro(red('Analysis failed.'));
478
+ process.exit(1);
479
+ }
480
+ uploadSpin.stop(green(`✓ ${uploadResult.routeCount} routes submitted across ${serviceMeta.length} service${serviceMeta.length > 1 ? 's' : ''}`));
481
+ // ── Poll for dashboard approval ───────────────────────────────────────────
482
+ note([
483
+ bold('Open your dashboard to review:'),
484
+ '',
485
+ ` ${cyan(opts.dashboardUrl)}`,
486
+ '',
487
+ dim('In "Import JSON" → "Pending CLI Imports"'),
488
+ dim('Accept to start AI processing · Deny to discard.'),
489
+ ].join('\n'), 'Action required');
490
+ const poll = spinner();
491
+ poll.start('Waiting for your decision in the dashboard… (5 min timeout)');
492
+ const approval = await pollForApproval(uploadResult.pendingImportId, opts.apiKey, opts.backendUrl, 5 * 60000);
493
+ const statusMsg = {
494
+ approved: green('✓ Accepted — AI processing started!'),
495
+ denied: red('✗ Import denied by dashboard.'),
496
+ timeout: yellow('◌ Timed out — no decision made within 5 minutes.'),
497
+ }[approval.status];
498
+ poll.stop(statusMsg);
499
+ if (approval.status === 'approved') {
500
+ note([
501
+ bold('Your API is being documented.'),
502
+ '',
503
+ ` ${dim('Track progress:')} ${cyan(opts.dashboardUrl)}`,
504
+ ` ${dim('Import ID:')} ${dim(uploadResult.pendingImportId)}`,
505
+ ].join('\n'), 'Processing');
506
+ }
507
+ else if (approval.status === 'denied') {
508
+ note([
509
+ ` ${bold('You denied this import from the dashboard.')}`,
510
+ '',
511
+ ` ${dim('No documentation was generated.')}`,
512
+ ` ${dim('Run')} ${cyan('npx apiforge')} ${dim('again whenever you\'re ready.')}`,
513
+ ].join('\n'), 'Denied');
514
+ }
515
+ else {
516
+ note([
517
+ ` ${dim('Your import is still pending:')}`,
518
+ ` ${cyan(opts.dashboardUrl)}`,
519
+ '',
520
+ ` ${dim('Import ID:')} ${cyan(uploadResult.pendingImportId)}`,
521
+ ` ${dim('You can still accept or deny it from the dashboard.')}`,
522
+ ].join('\n'), 'Pending');
523
+ }
524
+ tryUnlink(join(cwd, STATUS_FILE));
525
+ tryUnlink(join(cwd, LOCK_FILE));
526
+ const outroMsg = {
527
+ approved: `${green('✓')} Done! View your AI docs at ${cyan(opts.dashboardUrl)}`,
528
+ denied: `${red('✗')} Import denied. No changes were made.`,
529
+ timeout: `${yellow('◌')} Timed out. Your import is still pending at ${cyan(opts.dashboardUrl)}`,
530
+ }[approval.status];
531
+ outro(outroMsg);
532
+ }
251
533
  function startAndWaitForAnalysis(command, timeoutMs) {
252
534
  return new Promise(resolve => {
253
535
  const statusPath = join(process.cwd(), STATUS_FILE);
@@ -379,9 +661,124 @@ function removeInjectedCode(filePath) {
379
661
  return false;
380
662
  }
381
663
  }
382
- // ─── Entry file detection ─────────────────────────────────────────────────────
383
- function detectEntryFile() {
664
+ /** Look for a server entry inside a single directory (checks src/ then root). */
665
+ function findEntryInDir(absDir) {
666
+ const names = ['index', 'server', 'app', 'main'];
667
+ const exts = ['ts', 'js', 'mjs', 'cjs'];
668
+ for (const depth of ['src', '']) {
669
+ for (const name of names) {
670
+ for (const ext of exts) {
671
+ const rel = depth ? join(depth, `${name}.${ext}`) : `${name}.${ext}`;
672
+ if (existsSync(join(absDir, rel)))
673
+ return rel;
674
+ }
675
+ }
676
+ }
677
+ return null;
678
+ }
679
+ /**
680
+ * Detect the project's root/main entry point — package.json main,
681
+ * common gateway directories, then flat root candidates.
682
+ * Returns a relative path or null.
683
+ */
684
+ function detectMainEntry(cwd) {
685
+ // 1. package.json main / start / dev script
686
+ try {
687
+ const pkg = JSON.parse(readFileSync(join(cwd, 'package.json'), 'utf-8'));
688
+ if (pkg.main && existsSync(join(cwd, pkg.main)))
689
+ return pkg.main;
690
+ for (const s of ['start', 'dev', 'serve']) {
691
+ const cmd = pkg.scripts?.[s] ?? '';
692
+ const m = cmd.match(/(?:node|tsx|ts-node|nodemon)\s+([^\s&|;]+\.(js|ts|mjs|cjs))/);
693
+ if (m && existsSync(join(cwd, m[1])))
694
+ return m[1];
695
+ }
696
+ }
697
+ catch { }
698
+ // 2. Common gateway/proxy directory (e.g. api-gateway/)
699
+ for (const gatewayDir of ['api-gateway', 'gateway', 'proxy', 'api-proxy']) {
700
+ const entry = findEntryInDir(join(cwd, gatewayDir));
701
+ if (entry)
702
+ return join(gatewayDir, entry);
703
+ }
704
+ // 3. Flat root candidates
705
+ for (const c of [
706
+ 'index.ts', 'server.ts', 'app.ts', 'main.ts',
707
+ 'index.js', 'server.js', 'app.js', 'main.js',
708
+ 'src/index.ts', 'src/server.ts', 'src/app.ts', 'src/main.ts',
709
+ 'src/index.js', 'src/server.js', 'src/app.js', 'src/main.js',
710
+ ]) {
711
+ if (existsSync(join(cwd, c)))
712
+ return c;
713
+ }
714
+ return null;
715
+ }
716
+ /**
717
+ * Scan the project for per-service entry files.
718
+ * Prepends the root main entry (if any) so it appears first in the select list.
719
+ * Reads apiforge.config.json first; falls back to common service parent dirs.
720
+ */
721
+ function findServiceEntries() {
722
+ const cwd = process.cwd();
723
+ const results = [];
724
+ // 0. Root / main entry — shown first so the user always sees it
725
+ const mainEntry = detectMainEntry(cwd);
726
+ if (mainEntry) {
727
+ results.push({ label: `[ Main entry ] → ${mainEntry}`, path: mainEntry });
728
+ }
729
+ // 1. Authoritative list from apiforge.config.json / .apiforge.json
730
+ for (const cfgName of ['apiforge.config.json', '.apiforge.json']) {
731
+ try {
732
+ const cfg = JSON.parse(readFileSync(join(cwd, cfgName), 'utf-8'));
733
+ if (!Array.isArray(cfg.services) || cfg.services.length === 0)
734
+ continue;
735
+ for (const svc of cfg.services) {
736
+ const dir = svc.dir.replace(/^\.\//, '');
737
+ const entry = findEntryInDir(join(cwd, dir));
738
+ if (!entry)
739
+ continue;
740
+ const relPath = join(dir, entry);
741
+ // Skip if same path as the main entry already added
742
+ if (relPath !== mainEntry) {
743
+ results.push({ label: `${svc.name} → ${relPath}`, path: relPath });
744
+ }
745
+ }
746
+ if (results.length > 0)
747
+ return results;
748
+ }
749
+ catch { }
750
+ }
751
+ // 2. Filesystem scan of common service parent dirs
752
+ for (const parentDir of ['services', 'apps', 'packages', 'src/services', 'microservices']) {
753
+ const parentPath = join(cwd, parentDir);
754
+ if (!existsSync(parentPath))
755
+ continue;
756
+ try {
757
+ const subdirs = readdirSync(parentPath, { withFileTypes: true }).filter(d => d.isDirectory());
758
+ for (const subdir of subdirs) {
759
+ const entry = findEntryInDir(join(parentPath, subdir.name));
760
+ if (!entry)
761
+ continue;
762
+ const relPath = join(parentDir, subdir.name, entry);
763
+ if (relPath !== mainEntry) {
764
+ results.push({ label: `${subdir.name} → ${relPath}`, path: relPath });
765
+ }
766
+ }
767
+ }
768
+ catch { }
769
+ if (results.length > 1)
770
+ return results; // >1 because main entry is already at index 0
771
+ }
772
+ return results;
773
+ }
774
+ function detectEntryFile(archType) {
384
775
  const cwd = process.cwd();
776
+ // For microservices: auto-pick only when exactly one service entry is found
777
+ if (archType === 'microservices') {
778
+ const entries = findServiceEntries();
779
+ return entries.length === 1 ? entries[0].path : null;
780
+ }
781
+ // Package.json hints
385
782
  try {
386
783
  const pkg = JSON.parse(readFileSync(join(cwd, 'package.json'), 'utf-8'));
387
784
  if (pkg.main && existsSync(join(cwd, pkg.main)))
@@ -394,16 +791,47 @@ function detectEntryFile() {
394
791
  }
395
792
  }
396
793
  catch { }
794
+ // Flat file candidates — root → src/ → compiled output → misc
397
795
  const candidates = [
398
- 'index.ts', 'server.ts', 'app.ts',
399
- 'index.js', 'server.js', 'app.js',
400
- 'src/index.ts', 'src/server.ts', 'src/app.ts',
401
- 'src/index.js', 'src/server.js', 'src/app.js',
796
+ 'index.ts', 'server.ts', 'app.ts', 'main.ts',
797
+ 'index.js', 'server.js', 'app.js', 'main.js',
798
+ 'src/index.ts', 'src/server.ts', 'src/app.ts', 'src/main.ts',
799
+ 'src/index.js', 'src/server.js', 'src/app.js', 'src/main.js',
800
+ 'dist/index.js', 'dist/server.js', 'dist/main.js',
801
+ 'build/index.js', 'build/server.js', 'build/main.js',
802
+ 'lib/index.js', 'lib/server.js',
803
+ 'server/index.ts', 'server/index.js',
804
+ 'api/index.ts', 'api/index.js',
805
+ 'src/server/index.ts', 'src/server/index.js',
806
+ 'lambda.ts', 'lambda.js', 'handler.ts', 'handler.js',
402
807
  ];
403
808
  return candidates.find(c => existsSync(join(cwd, c))) ?? null;
404
809
  }
405
- async function askEntryFile() {
406
- log.warn('Could not auto-detect your server entry file.');
810
+ async function askEntryFile(archType) {
811
+ if (archType === 'microservices') {
812
+ const entries = findServiceEntries();
813
+ if (entries.length > 0) {
814
+ const choice = await select({
815
+ message: 'Which service entry file do you want to analyze?',
816
+ options: [
817
+ ...entries.map(e => ({ value: e.path, label: e.label })),
818
+ { value: '__manual', label: 'Enter path manually…' },
819
+ ],
820
+ });
821
+ if (isCancel(choice)) {
822
+ cancel('Cancelled.');
823
+ process.exit(0);
824
+ }
825
+ if (choice !== '__manual')
826
+ return choice;
827
+ }
828
+ else {
829
+ log.warn('Could not find service entry files in services/, apps/, or packages/.');
830
+ }
831
+ }
832
+ else {
833
+ log.warn('Could not auto-detect your server entry file.');
834
+ }
407
835
  const custom = await text({
408
836
  message: 'Path to your server entry file',
409
837
  placeholder: 'src/index.ts',
@@ -431,7 +859,7 @@ function detectScripts() {
431
859
  if (scripts[name])
432
860
  result.push({ name, command: `npm run ${name}` });
433
861
  }
434
- // Then any remaining scripts that look like server starters
862
+ // Scripts that directly invoke a node runtime
435
863
  for (const [name, cmd] of Object.entries(scripts)) {
436
864
  if (preferred.includes(name))
437
865
  continue;
@@ -439,13 +867,22 @@ function detectScripts() {
439
867
  result.push({ name, command: `npm run ${name}` });
440
868
  }
441
869
  }
870
+ // Workspace per-service scripts: start:*, dev:*, serve:* patterns
871
+ // (e.g. "dev:auth", "start:wallet" common in npm/pnpm monorepos)
872
+ for (const [name] of Object.entries(scripts)) {
873
+ if (preferred.includes(name))
874
+ continue;
875
+ if (/^(?:start|dev|serve|run):[a-z0-9_-]+$/i.test(name) && !result.some(r => r.name === name)) {
876
+ result.push({ name, command: `npm run ${name}` });
877
+ }
878
+ }
442
879
  return result;
443
880
  }
444
881
  catch {
445
882
  return [];
446
883
  }
447
884
  }
448
- function injectCode(filePath, projectName, apiKey, baseUrl, backendUrl) {
885
+ function injectCode(filePath, projectName, apiKey, baseUrl, backendUrl, architectureType, collectionOpts) {
449
886
  const fullPath = join(process.cwd(), filePath);
450
887
  const content = readFileSync(fullPath, 'utf-8');
451
888
  if (content.includes('apiforge-analyzer')) {
@@ -453,7 +890,7 @@ function injectCode(filePath, projectName, apiKey, baseUrl, backendUrl) {
453
890
  }
454
891
  const isESM = detectESM(filePath, content);
455
892
  const appVar = detectAppVariable(content) ?? 'app';
456
- const snippet = buildSnippet(projectName, apiKey, baseUrl, backendUrl, appVar, isESM);
893
+ const snippet = buildSnippet(projectName, apiKey, baseUrl, backendUrl, appVar, isESM, architectureType, collectionOpts);
457
894
  const listenRe = /\b(?:app|server|httpServer|http)\s*\.listen\s*\(/;
458
895
  const listenMatch = listenRe.exec(content);
459
896
  let newContent;
@@ -504,19 +941,34 @@ function addToGitignore(pattern) {
504
941
  }
505
942
  catch { }
506
943
  }
507
- function buildSnippet(projectName, apiKey, baseUrl, backendUrl, appVar, isESM) {
944
+ function buildSnippet(projectName, apiKey, baseUrl, backendUrl, appVar, isESM, architectureType, collectionOpts) {
508
945
  // The API key is embedded directly — this snippet is TEMPORARY (auto-removed after analysis).
509
946
  // Hardcoding guarantees the same key is used for both submit and CLI status polling,
510
947
  // eliminating the mismatch that causes 401s when .env.local already has a different key.
511
948
  const isProd = backendUrl === BACKEND_PROD;
512
- const opts = [
513
- ` apiKey: '${apiKey}',`,
514
- ` projectName: '${projectName}',`,
515
- ` baseUrl: '${baseUrl}',`,
516
- ...(isProd ? [] : [` apiForgeUrl: '${backendUrl}',`]),
517
- ` upload: true,`,
518
- ` runOnce: true,`,
519
- ].join('\n');
949
+ // Collection mode (multi-service): upload: false, write to per-service status file
950
+ const opts = collectionOpts
951
+ ? [
952
+ ` apiKey: '${apiKey}',`,
953
+ ` projectName: '${projectName}',`,
954
+ ` baseUrl: '${baseUrl}',`,
955
+ ` service: '${collectionOpts.serviceName}',`,
956
+ ` statusFile: '${collectionOpts.statusFile}',`,
957
+ ` architectureType: 'microservices',`,
958
+ ` upload: false,`,
959
+ ` runOnce: true,`,
960
+ ].join('\n')
961
+ : [
962
+ ` apiKey: '${apiKey}',`,
963
+ ` projectName: '${projectName}',`,
964
+ ` baseUrl: '${baseUrl}',`,
965
+ ...(isProd ? [] : [` apiForgeUrl: '${backendUrl}',`]),
966
+ ...(architectureType && architectureType !== 'monolithic'
967
+ ? [` architectureType: '${architectureType}',`]
968
+ : []),
969
+ ` upload: true,`,
970
+ ` runOnce: true,`,
971
+ ].join('\n');
520
972
  if (isESM) {
521
973
  return [
522
974
  `// APIForge — https://apiforge.brainfogagency.com`,
@@ -54,6 +54,8 @@ export function enrichRoute(route, index) {
54
54
  routeKey,
55
55
  tag,
56
56
  tags: route.tags?.length ? route.tags : [tag],
57
+ module: route.module,
58
+ service: route.service,
57
59
  summary: route.summary || generateSummary(route.method, route.path),
58
60
  description: route.description || generateDescription(route.method, route.path, tag),
59
61
  authRequired,