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