recker 1.0.30 → 1.0.32-next.e0741bf

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 (46) hide show
  1. package/dist/cli/index.js +2643 -195
  2. package/dist/cli/tui/shell-search.js +10 -8
  3. package/dist/cli/tui/shell.d.ts +29 -0
  4. package/dist/cli/tui/shell.js +1733 -9
  5. package/dist/mcp/search/hybrid-search.js +4 -2
  6. package/dist/seo/analyzer.d.ts +7 -0
  7. package/dist/seo/analyzer.js +200 -4
  8. package/dist/seo/rules/ai-search.d.ts +2 -0
  9. package/dist/seo/rules/ai-search.js +423 -0
  10. package/dist/seo/rules/canonical.d.ts +12 -0
  11. package/dist/seo/rules/canonical.js +249 -0
  12. package/dist/seo/rules/crawl.js +113 -0
  13. package/dist/seo/rules/cwv.js +0 -95
  14. package/dist/seo/rules/i18n.js +27 -0
  15. package/dist/seo/rules/images.js +23 -27
  16. package/dist/seo/rules/index.js +14 -0
  17. package/dist/seo/rules/internal-linking.js +6 -6
  18. package/dist/seo/rules/links.js +321 -0
  19. package/dist/seo/rules/meta.js +24 -0
  20. package/dist/seo/rules/mobile.js +0 -20
  21. package/dist/seo/rules/performance.js +124 -0
  22. package/dist/seo/rules/redirects.d.ts +16 -0
  23. package/dist/seo/rules/redirects.js +193 -0
  24. package/dist/seo/rules/resources.d.ts +2 -0
  25. package/dist/seo/rules/resources.js +373 -0
  26. package/dist/seo/rules/security.js +290 -0
  27. package/dist/seo/rules/technical-advanced.d.ts +10 -0
  28. package/dist/seo/rules/technical-advanced.js +283 -0
  29. package/dist/seo/rules/technical.js +74 -18
  30. package/dist/seo/rules/types.d.ts +103 -3
  31. package/dist/seo/seo-spider.d.ts +2 -0
  32. package/dist/seo/seo-spider.js +47 -2
  33. package/dist/seo/types.d.ts +48 -28
  34. package/dist/seo/utils/index.d.ts +1 -0
  35. package/dist/seo/utils/index.js +1 -0
  36. package/dist/seo/utils/similarity.d.ts +47 -0
  37. package/dist/seo/utils/similarity.js +273 -0
  38. package/dist/seo/validators/index.d.ts +3 -0
  39. package/dist/seo/validators/index.js +3 -0
  40. package/dist/seo/validators/llms-txt.d.ts +57 -0
  41. package/dist/seo/validators/llms-txt.js +317 -0
  42. package/dist/seo/validators/robots.d.ts +54 -0
  43. package/dist/seo/validators/robots.js +382 -0
  44. package/dist/seo/validators/sitemap.d.ts +69 -0
  45. package/dist/seo/validators/sitemap.js +424 -0
  46. package/package.json +1 -1
package/dist/cli/index.js CHANGED
@@ -450,7 +450,7 @@ ${colors.bold(colors.yellow('Checks:'))}
450
450
  images: report.images,
451
451
  openGraph: report.social.openGraph,
452
452
  twitterCard: report.social.twitterCard,
453
- jsonLd: report.jsonLd,
453
+ structuredData: report.structuredData,
454
454
  technical: report.technical,
455
455
  checks: report.checks,
456
456
  summary: {
@@ -520,8 +520,8 @@ ${colors.gray('Grade:')} ${gradeColor(colors.bold(report.grade))} ${colors.gray
520
520
  }
521
521
  }
522
522
  console.log('');
523
- if (report.jsonLd.count > 0) {
524
- console.log(`${colors.bold('Structured Data:')} ${report.jsonLd.types.join(', ') || 'Present'}`);
523
+ if (report.structuredData.count > 0) {
524
+ console.log(`${colors.bold('Structured Data:')} ${report.structuredData.types.join(', ') || 'Present'}`);
525
525
  console.log('');
526
526
  }
527
527
  }
@@ -531,139 +531,904 @@ ${colors.gray('Grade:')} ${gradeColor(colors.bold(report.grade))} ${colors.gray
531
531
  }
532
532
  });
533
533
  program
534
- .command('spider')
535
- .description('Crawl a website following internal links')
536
- .argument('<url>', 'Starting URL to crawl')
537
- .option('-d, --depth <n>', 'Maximum depth to crawl', '5')
538
- .option('-l, --limit <n>', 'Maximum pages to crawl', '100')
539
- .option('-c, --concurrency <n>', 'Concurrent requests', '5')
540
- .option('--delay <ms>', 'Delay between requests in ms', '100')
534
+ .command('robots')
535
+ .description('Validate and analyze robots.txt file')
536
+ .argument('<url>', 'Website URL or direct robots.txt URL')
541
537
  .option('--format <format>', 'Output format: text (default) or json', 'text')
542
- .option('-o, --output <file>', 'Write JSON results to file')
543
538
  .addHelpText('after', `
544
539
  ${colors.bold(colors.yellow('Examples:'))}
545
- ${colors.green('$ rek spider example.com')} ${colors.gray('Crawl with defaults')}
546
- ${colors.green('$ rek spider example.com -d 3 -l 50')} ${colors.gray('Depth 3, max 50 pages')}
547
- ${colors.green('$ rek spider example.com --format json')} ${colors.gray('Output as JSON')}
548
- ${colors.green('$ rek spider example.com -o results.json')} ${colors.gray('Save to file')}
540
+ ${colors.green('$ rek robots example.com')} ${colors.gray('Validate robots.txt')}
541
+ ${colors.green('$ rek robots example.com/robots.txt')} ${colors.gray('Direct URL')}
542
+ ${colors.green('$ rek robots example.com --format json')} ${colors.gray('JSON output')}
549
543
 
550
- ${colors.bold(colors.yellow('Options:'))}
551
- ${colors.cyan('--depth, -d')} Max link depth to follow (default: 5)
552
- ${colors.cyan('--limit, -l')} Max pages to crawl (default: 100)
553
- ${colors.cyan('--concurrency, -c')} Parallel requests (default: 5)
554
- ${colors.cyan('--delay')} Ms between requests (default: 100)
544
+ ${colors.bold(colors.yellow('Checks:'))}
545
+ ${colors.cyan('Syntax')} Valid robots.txt syntax
546
+ ${colors.cyan('User-Agent blocks')} Defined crawl rules
547
+ ${colors.cyan('Sitemap')} Sitemap directive present
548
+ ${colors.cyan('Crawl-delay')} Aggressive crawl delay
549
+ ${colors.cyan('AI Bots')} GPTBot, ClaudeBot, Anthropic blocks
555
550
  `)
556
551
  .action(async (url, options) => {
557
552
  if (!url.startsWith('http'))
558
553
  url = `https://${url}`;
554
+ if (!url.includes('robots.txt')) {
555
+ const urlObj = new URL(url);
556
+ url = `${urlObj.origin}/robots.txt`;
557
+ }
559
558
  const isJson = options.format === 'json';
560
- const maxDepth = parseInt(options.depth || '5', 10);
561
- const maxPages = parseInt(options.limit || '100', 10);
562
- const concurrency = parseInt(options.concurrency || '5', 10);
563
- const delay = parseInt(options.delay || '100', 10);
564
- const { Spider } = await import('../scrape/spider.js');
565
559
  if (!isJson) {
566
- console.log(colors.gray(`\nCrawling ${url}...`));
567
- console.log(colors.gray(` Depth: ${maxDepth}, Limit: ${maxPages}, Concurrency: ${concurrency}\n`));
560
+ console.log(colors.gray(`Fetching robots.txt from ${url}...`));
568
561
  }
569
562
  try {
570
- const startTime = performance.now();
571
- const spider = new Spider({
572
- maxDepth,
573
- maxPages,
574
- concurrency,
575
- delay,
576
- onProgress: (progress) => {
577
- if (!isJson) {
578
- process.stdout.write(`\r${colors.cyan('')} Crawled: ${colors.bold(String(progress.crawled))} | Queued: ${progress.queued} | Current: ${colors.gray(progress.currentUrl.slice(0, 50))}...`);
563
+ const { fetchAndValidateRobotsTxt } = await import('../seo/validators/robots.js');
564
+ const result = await fetchAndValidateRobotsTxt(url);
565
+ if (isJson) {
566
+ console.log(JSON.stringify(result, null, 2));
567
+ return;
568
+ }
569
+ console.log(`
570
+ ${colors.bold(colors.cyan('🤖 Robots.txt Analysis'))}
571
+ ${colors.gray('URL:')} ${url}
572
+ ${colors.gray('Valid:')} ${result.valid ? colors.green('Yes') : colors.red('No')}
573
+ `);
574
+ if (result.parseResult) {
575
+ const { parseResult } = result;
576
+ if (parseResult.userAgentBlocks.length > 0) {
577
+ console.log(colors.bold('User-Agent Blocks:'));
578
+ for (const block of parseResult.userAgentBlocks.slice(0, 5)) {
579
+ const agents = block.userAgents.join(', ');
580
+ const allowCount = block.rules.filter(r => r.type === 'allow').length;
581
+ const disallowCount = block.rules.filter(r => r.type === 'disallow').length;
582
+ console.log(` ${colors.cyan(agents)}`);
583
+ console.log(` ${colors.green(`Allow: ${allowCount}`)} | ${colors.red(`Disallow: ${disallowCount}`)}`);
579
584
  }
580
- },
581
- });
582
- const result = await spider.crawl(url);
583
- const duration = Math.round(performance.now() - startTime);
584
- if (!isJson) {
585
- process.stdout.write('\r' + ' '.repeat(100) + '\r');
585
+ if (parseResult.userAgentBlocks.length > 5) {
586
+ console.log(colors.gray(` ... and ${parseResult.userAgentBlocks.length - 5} more blocks`));
587
+ }
588
+ console.log('');
589
+ }
590
+ if (parseResult.sitemaps.length > 0) {
591
+ console.log(colors.bold('Sitemaps:'));
592
+ for (const sitemap of parseResult.sitemaps.slice(0, 3)) {
593
+ console.log(` ${colors.gray('→')} ${sitemap}`);
594
+ }
595
+ if (parseResult.sitemaps.length > 3) {
596
+ console.log(colors.gray(` ... and ${parseResult.sitemaps.length - 3} more`));
597
+ }
598
+ console.log('');
599
+ }
600
+ const aiAgents = ['gptbot', 'chatgpt-user', 'claudebot', 'claude-web', 'anthropic-ai', 'ccbot'];
601
+ const blockedAiBots = [];
602
+ for (const block of parseResult.userAgentBlocks) {
603
+ for (const agent of block.userAgents) {
604
+ if (aiAgents.includes(agent.toLowerCase())) {
605
+ const hasBlockAll = block.rules.some(r => r.type === 'disallow' && (r.path === '/' || r.path === '/*'));
606
+ if (hasBlockAll) {
607
+ blockedAiBots.push(agent);
608
+ }
609
+ }
610
+ }
611
+ }
612
+ if (blockedAiBots.length > 0) {
613
+ console.log(colors.bold('AI Bots Blocked:'));
614
+ for (const bot of blockedAiBots) {
615
+ console.log(` ${colors.red('✗')} ${bot}`);
616
+ }
617
+ console.log('');
618
+ }
586
619
  }
587
- if (isJson || options.output) {
588
- const jsonOutput = {
589
- startUrl: result.startUrl,
590
- crawledAt: new Date().toISOString(),
591
- duration,
592
- summary: {
593
- totalPages: result.pages.length,
594
- successCount: result.pages.filter(p => !p.error).length,
595
- errorCount: result.errors.length,
596
- uniqueUrls: result.visited.size,
597
- },
598
- pages: result.pages.map(p => ({
599
- url: p.url,
600
- status: p.status,
601
- title: p.title,
602
- depth: p.depth,
603
- linksCount: p.links.length,
604
- duration: p.duration,
605
- error: p.error,
606
- })),
607
- errors: result.errors,
608
- };
609
- if (options.output) {
610
- await fs.writeFile(options.output, JSON.stringify(jsonOutput, null, 2));
611
- console.log(colors.green(`✓ Results saved to ${options.output}`));
620
+ if (result.issues.length > 0) {
621
+ console.log(colors.bold('Issues:'));
622
+ for (const issue of result.issues) {
623
+ const icon = issue.type === 'error' ? colors.red('✗')
624
+ : issue.type === 'warning' ? colors.yellow('⚠')
625
+ : colors.gray('ℹ');
626
+ console.log(` ${icon} ${issue.message}`);
627
+ }
628
+ console.log('');
629
+ }
630
+ const errorCount = result.issues.filter(i => i.type === 'error').length;
631
+ const warningCount = result.issues.filter(i => i.type === 'warning').length;
632
+ if (errorCount === 0 && warningCount === 0) {
633
+ console.log(colors.green('✔ No issues found'));
634
+ }
635
+ else {
636
+ console.log(`${colors.red(`${errorCount} errors`)} | ${colors.yellow(`${warningCount} warnings`)}`);
637
+ }
638
+ }
639
+ catch (error) {
640
+ console.error(colors.red(`Robots.txt analysis failed: ${error.message}`));
641
+ process.exit(1);
642
+ }
643
+ });
644
+ program
645
+ .command('sitemap')
646
+ .description('Validate and analyze sitemap.xml file')
647
+ .argument('<url>', 'Website URL or direct sitemap URL')
648
+ .option('--format <format>', 'Output format: text (default) or json', 'text')
649
+ .option('--discover', 'Discover all sitemaps via robots.txt')
650
+ .addHelpText('after', `
651
+ ${colors.bold(colors.yellow('Examples:'))}
652
+ ${colors.green('$ rek sitemap example.com')} ${colors.gray('Validate sitemap')}
653
+ ${colors.green('$ rek sitemap example.com/sitemap.xml')} ${colors.gray('Direct URL')}
654
+ ${colors.green('$ rek sitemap example.com --discover')} ${colors.gray('Find all sitemaps')}
655
+ ${colors.green('$ rek sitemap example.com --format json')} ${colors.gray('JSON output')}
656
+
657
+ ${colors.bold(colors.yellow('Checks:'))}
658
+ ${colors.cyan('Structure')} Valid XML sitemap format
659
+ ${colors.cyan('URL Count')} Within 50,000 URL limit
660
+ ${colors.cyan('File Size')} Within 50MB limit
661
+ ${colors.cyan('URLs')} Valid, no duplicates, same domain
662
+ ${colors.cyan('Lastmod')} Valid dates, not in future
663
+ `)
664
+ .action(async (url, options) => {
665
+ if (!url.startsWith('http'))
666
+ url = `https://${url}`;
667
+ const isJson = options.format === 'json';
668
+ try {
669
+ if (options.discover) {
670
+ const { discoverSitemaps } = await import('../seo/validators/sitemap.js');
671
+ if (!isJson) {
672
+ console.log(colors.gray(`Discovering sitemaps for ${new URL(url).origin}...`));
612
673
  }
674
+ const sitemaps = await discoverSitemaps(url);
613
675
  if (isJson) {
614
- console.log(JSON.stringify(jsonOutput, null, 2));
676
+ console.log(JSON.stringify({ url, sitemaps }, null, 2));
615
677
  return;
616
678
  }
679
+ console.log(`
680
+ ${colors.bold(colors.cyan('🗺️ Sitemap Discovery'))}
681
+ ${colors.gray('Site:')} ${new URL(url).origin}
682
+ ${colors.gray('Found:')} ${sitemaps.length} sitemap(s)
683
+ `);
684
+ if (sitemaps.length > 0) {
685
+ for (const sitemap of sitemaps) {
686
+ console.log(` ${colors.gray('→')} ${sitemap}`);
687
+ }
688
+ }
689
+ else {
690
+ console.log(colors.yellow(' No sitemaps found in robots.txt or common locations'));
691
+ }
692
+ return;
617
693
  }
618
- console.log(`${colors.bold(colors.cyan('🕷️ Spider Crawl Complete'))}`);
619
- console.log(`${colors.gray('URL:')} ${url}`);
620
- console.log(`${colors.gray('Duration:')} ${(duration / 1000).toFixed(1)}s`);
621
- console.log('');
622
- const successCount = result.pages.filter(p => !p.error).length;
623
- console.log(`${colors.bold('Summary:')}`);
624
- console.log(` ${colors.green('✓')} Pages crawled: ${colors.bold(String(successCount))}`);
625
- console.log(` ${colors.red('✗')} Errors: ${colors.bold(String(result.errors.length))}`);
626
- console.log(` ${colors.gray('○')} Unique URLs: ${result.visited.size}`);
627
- console.log('');
628
- const byDepth = new Map();
629
- for (const page of result.pages) {
630
- byDepth.set(page.depth, (byDepth.get(page.depth) || 0) + 1);
694
+ if (!url.includes('sitemap')) {
695
+ const urlObj = new URL(url);
696
+ url = `${urlObj.origin}/sitemap.xml`;
631
697
  }
632
- console.log(`${colors.bold('Pages by Depth:')}`);
633
- for (const [depth, count] of [...byDepth.entries()].sort((a, b) => a[0] - b[0])) {
634
- console.log(` ${colors.gray(`Depth ${depth}:`)} ${count} pages`);
698
+ if (!isJson) {
699
+ console.log(colors.gray(`Fetching sitemap from ${url}...`));
635
700
  }
636
- console.log('');
637
- if (result.errors.length > 0) {
638
- console.log(`${colors.bold(colors.red('Errors:'))}`);
639
- for (const err of result.errors.slice(0, 10)) {
640
- const shortUrl = err.url.replace(url, '');
641
- const statusMatch = err.error.match(/status code (\d+)/);
642
- const errorMsg = statusMatch ? `HTTP ${statusMatch[1]}` : err.error.slice(0, 50);
643
- console.log(` ${colors.red('✗')} ${colors.gray(shortUrl || '/')} → ${errorMsg}`);
701
+ const { fetchAndValidateSitemap } = await import('../seo/validators/sitemap.js');
702
+ const result = await fetchAndValidateSitemap(url);
703
+ if (isJson) {
704
+ console.log(JSON.stringify(result, null, 2));
705
+ return;
706
+ }
707
+ console.log(`
708
+ ${colors.bold(colors.cyan('🗺️ Sitemap Analysis'))}
709
+ ${colors.gray('URL:')} ${url}
710
+ ${colors.gray('Valid:')} ${result.valid ? colors.green('Yes') : colors.red('No')}
711
+ ${colors.gray('Type:')} ${result.parseResult?.type === 'sitemapindex' ? 'Sitemap Index' : 'URL Set'}
712
+ `);
713
+ if (result.parseResult) {
714
+ const { parseResult } = result;
715
+ if (parseResult.type === 'sitemapindex') {
716
+ console.log(colors.bold(`Sitemaps: ${parseResult.sitemaps?.length || 0}`));
717
+ for (const sm of (parseResult.sitemaps || []).slice(0, 5)) {
718
+ console.log(` ${colors.gray('→')} ${sm.loc}`);
719
+ if (sm.lastmod) {
720
+ console.log(` ${colors.gray(`Last modified: ${sm.lastmod}`)}`);
721
+ }
722
+ }
723
+ if ((parseResult.sitemaps?.length || 0) > 5) {
724
+ console.log(colors.gray(` ... and ${parseResult.sitemaps.length - 5} more`));
725
+ }
644
726
  }
645
- if (result.errors.length > 10) {
646
- console.log(` ${colors.gray(` ... and ${result.errors.length - 10} more`)}`);
727
+ else {
728
+ console.log(colors.bold(`URLs: ${parseResult.urls?.length || 0}`));
729
+ const sampleUrls = (parseResult.urls || []).slice(0, 5);
730
+ for (const entry of sampleUrls) {
731
+ const path = new URL(entry.loc).pathname;
732
+ console.log(` ${colors.gray('→')} ${path}`);
733
+ }
734
+ if ((parseResult.urls?.length || 0) > 5) {
735
+ console.log(colors.gray(` ... and ${parseResult.urls.length - 5} more URLs`));
736
+ }
737
+ const urlsWithLastmod = (parseResult.urls || []).filter(u => u.lastmod).length;
738
+ const urlsWithPriority = (parseResult.urls || []).filter(u => u.priority !== undefined).length;
739
+ const urlsWithChangefreq = (parseResult.urls || []).filter(u => u.changefreq).length;
740
+ console.log('');
741
+ console.log(colors.bold('Statistics:'));
742
+ console.log(` ${colors.gray('With lastmod:')} ${urlsWithLastmod} (${((urlsWithLastmod / (parseResult.urls?.length || 1)) * 100).toFixed(0)}%)`);
743
+ console.log(` ${colors.gray('With priority:')} ${urlsWithPriority} (${((urlsWithPriority / (parseResult.urls?.length || 1)) * 100).toFixed(0)}%)`);
744
+ console.log(` ${colors.gray('With changefreq:')} ${urlsWithChangefreq} (${((urlsWithChangefreq / (parseResult.urls?.length || 1)) * 100).toFixed(0)}%)`);
647
745
  }
648
746
  console.log('');
649
747
  }
650
- const successPages = result.pages.filter(p => !p.error).slice(0, 10);
651
- if (successPages.length > 0) {
652
- console.log(`${colors.bold('Sample Pages:')}`);
653
- for (const page of successPages) {
654
- const shortUrl = page.url.replace(url, '');
655
- console.log(` ${colors.green('✓')} ${colors.gray((shortUrl || '/').padEnd(40))} ${page.title.slice(0, 40)}`);
748
+ if (result.issues.length > 0) {
749
+ console.log(colors.bold('Issues:'));
750
+ for (const issue of result.issues.slice(0, 10)) {
751
+ const icon = issue.type === 'error' ? colors.red('✗')
752
+ : issue.type === 'warning' ? colors.yellow('')
753
+ : colors.gray('');
754
+ console.log(` ${icon} ${issue.message}`);
656
755
  }
657
- if (result.pages.length > 10) {
658
- console.log(` ${colors.gray(` ... and ${result.pages.length - 10} more`)}`);
756
+ if (result.issues.length > 10) {
757
+ console.log(colors.gray(` ... and ${result.issues.length - 10} more issues`));
659
758
  }
759
+ console.log('');
760
+ }
761
+ const errorCount = result.issues.filter(i => i.type === 'error').length;
762
+ const warningCount = result.issues.filter(i => i.type === 'warning').length;
763
+ if (errorCount === 0 && warningCount === 0) {
764
+ console.log(colors.green('✔ No issues found'));
765
+ }
766
+ else {
767
+ console.log(`${colors.red(`${errorCount} errors`)} | ${colors.yellow(`${warningCount} warnings`)}`);
660
768
  }
661
769
  }
770
+ catch (error) {
771
+ console.error(colors.red(`Sitemap analysis failed: ${error.message}`));
772
+ process.exit(1);
773
+ }
774
+ });
775
+ program
776
+ .command('llms')
777
+ .description('Validate and analyze llms.txt file (AI/LLM optimization)')
778
+ .argument('[url]', 'Website URL or direct llms.txt URL')
779
+ .option('--format <format>', 'Output format: text (default) or json', 'text')
780
+ .option('--template', 'Generate a template llms.txt file')
781
+ .addHelpText('after', `
782
+ ${colors.bold(colors.yellow('Examples:'))}
783
+ ${colors.green('$ rek llms example.com')} ${colors.gray('Validate llms.txt')}
784
+ ${colors.green('$ rek llms example.com/llms.txt')} ${colors.gray('Direct URL')}
785
+ ${colors.green('$ rek llms example.com --format json')} ${colors.gray('JSON output')}
786
+ ${colors.green('$ rek llms --template > llms.txt')} ${colors.gray('Generate template')}
787
+
788
+ ${colors.bold(colors.yellow('About llms.txt:'))}
789
+ A proposed standard for providing LLM-friendly content.
790
+ Similar to robots.txt but for AI/LLM crawlers.
791
+ Learn more: ${colors.cyan('https://llmstxt.org')}
792
+
793
+ ${colors.bold(colors.yellow('Checks:'))}
794
+ ${colors.cyan('Structure')} Valid llms.txt format
795
+ ${colors.cyan('Site Name')} Primary heading present
796
+ ${colors.cyan('Description')} Site description block
797
+ ${colors.cyan('Sections')} Content sections with links
798
+ `)
799
+ .action(async (url, options) => {
800
+ const isJson = options.format === 'json';
801
+ if (options.template) {
802
+ const { generateLlmsTxtTemplate } = await import('../seo/validators/llms-txt.js');
803
+ const template = generateLlmsTxtTemplate({
804
+ siteName: 'Your Site Name',
805
+ siteDescription: 'A brief description of your website and what it offers.',
806
+ sections: [
807
+ {
808
+ title: 'Documentation',
809
+ links: [
810
+ { text: 'Getting Started', url: '/docs/getting-started' },
811
+ { text: 'API Reference', url: '/docs/api' },
812
+ ],
813
+ },
814
+ {
815
+ title: 'Resources',
816
+ links: [
817
+ { text: 'Blog', url: '/blog' },
818
+ { text: 'FAQ', url: '/faq' },
819
+ ],
820
+ },
821
+ ],
822
+ });
823
+ console.log(template);
824
+ return;
825
+ }
826
+ if (!url) {
827
+ console.error(colors.red('URL is required (use --template to generate a template)'));
828
+ process.exit(1);
829
+ }
830
+ if (!url.startsWith('http'))
831
+ url = `https://${url}`;
832
+ if (!url.includes('llms.txt')) {
833
+ const urlObj = new URL(url);
834
+ url = `${urlObj.origin}/llms.txt`;
835
+ }
836
+ if (!isJson) {
837
+ console.log(colors.gray(`Fetching llms.txt from ${url}...`));
838
+ }
839
+ try {
840
+ const { fetchAndValidateLlmsTxt } = await import('../seo/validators/llms-txt.js');
841
+ const result = await fetchAndValidateLlmsTxt(url);
842
+ if (isJson) {
843
+ console.log(JSON.stringify(result, null, 2));
844
+ return;
845
+ }
846
+ if (!result.exists) {
847
+ console.log(`
848
+ ${colors.bold(colors.cyan('📄 llms.txt Analysis'))}
849
+ ${colors.gray('URL:')} ${url}
850
+ ${colors.red('Status:')} File not found
851
+
852
+ ${colors.yellow('Recommendation:')}
853
+ Consider creating an llms.txt file to help AI/LLM systems
854
+ better understand your site's content and structure.
855
+
856
+ Use ${colors.cyan('rek llms --template')} to generate a starting template.
857
+ Learn more: ${colors.cyan('https://llmstxt.org')}
858
+ `);
859
+ return;
860
+ }
861
+ console.log(`
862
+ ${colors.bold(colors.cyan('📄 llms.txt Analysis'))}
863
+ ${colors.gray('URL:')} ${url}
864
+ ${colors.gray('Valid:')} ${result.valid ? colors.green('Yes') : colors.red('No')}
865
+ `);
866
+ if (result.parseResult) {
867
+ const { parseResult } = result;
868
+ if (parseResult.siteName) {
869
+ console.log(`${colors.bold('Site Name:')} ${parseResult.siteName}`);
870
+ }
871
+ if (parseResult.siteDescription) {
872
+ const desc = parseResult.siteDescription.length > 100
873
+ ? parseResult.siteDescription.slice(0, 97) + '...'
874
+ : parseResult.siteDescription;
875
+ console.log(`${colors.bold('Description:')} ${colors.gray(desc)}`);
876
+ }
877
+ console.log('');
878
+ if (parseResult.sections.length > 0) {
879
+ console.log(colors.bold(`Sections: ${parseResult.sections.length}`));
880
+ for (const section of parseResult.sections) {
881
+ const linkCount = parseResult.links.filter(l => true).length;
882
+ console.log(` ${colors.cyan('##')} ${section.title}`);
883
+ }
884
+ console.log('');
885
+ }
886
+ if (parseResult.links.length > 0) {
887
+ console.log(colors.bold(`Links: ${parseResult.links.length}`));
888
+ for (const link of parseResult.links.slice(0, 5)) {
889
+ console.log(` ${colors.gray('→')} [${link.text}](${link.url})`);
890
+ }
891
+ if (parseResult.links.length > 5) {
892
+ console.log(colors.gray(` ... and ${parseResult.links.length - 5} more links`));
893
+ }
894
+ console.log('');
895
+ }
896
+ }
897
+ if (result.issues.length > 0) {
898
+ console.log(colors.bold('Issues:'));
899
+ for (const issue of result.issues) {
900
+ const icon = issue.type === 'error' ? colors.red('✗')
901
+ : issue.type === 'warning' ? colors.yellow('⚠')
902
+ : colors.gray('ℹ');
903
+ console.log(` ${icon} ${issue.message}`);
904
+ }
905
+ console.log('');
906
+ }
907
+ const errorCount = result.issues.filter(i => i.type === 'error').length;
908
+ const warningCount = result.issues.filter(i => i.type === 'warning').length;
909
+ if (errorCount === 0 && warningCount === 0 && result.valid) {
910
+ console.log(colors.green('✔ Valid llms.txt file'));
911
+ }
912
+ else {
913
+ console.log(`${colors.red(`${errorCount} errors`)} | ${colors.yellow(`${warningCount} warnings`)}`);
914
+ }
915
+ }
916
+ catch (error) {
917
+ console.error(colors.red(`llms.txt analysis failed: ${error.message}`));
918
+ process.exit(1);
919
+ }
920
+ });
921
+ program
922
+ .command('spider')
923
+ .description('Crawl a website following internal links')
924
+ .argument('<url>', 'Starting URL to crawl')
925
+ .argument('[args...]', 'Options: depth=N limit=N concurrency=N seo focus=MODE output=file.json')
926
+ .addHelpText('after', `
927
+ ${colors.bold(colors.yellow('Examples:'))}
928
+ ${colors.green('$ rek spider example.com')} ${colors.gray('Crawl with defaults')}
929
+ ${colors.green('$ rek spider example.com depth=3 limit=50')} ${colors.gray('Depth 3, max 50 pages')}
930
+ ${colors.green('$ rek spider example.com seo')} ${colors.gray('Crawl + SEO analysis')}
931
+ ${colors.green('$ rek spider example.com seo output=report.json')} ${colors.gray('SEO with JSON export')}
932
+ ${colors.green('$ rek spider example.com seo focus=links')} ${colors.gray('Focus on link issues')}
933
+ ${colors.green('$ rek spider example.com seo focus=security')} ${colors.gray('Focus on security issues')}
934
+ ${colors.green('$ rek spider example.com seo focus=duplicates')} ${colors.gray('Focus on duplicate content')}
935
+
936
+ ${colors.bold(colors.yellow('Options:'))}
937
+ ${colors.cyan('depth=N')} Max link depth to follow (default: 5)
938
+ ${colors.cyan('limit=N')} Max pages to crawl (default: 100)
939
+ ${colors.cyan('concurrency=N')} Parallel requests (default: 5)
940
+ ${colors.cyan('seo')} Enable SEO analysis mode
941
+ ${colors.cyan('focus=MODE')} Focus analysis on specific area (requires seo)
942
+ ${colors.cyan('output=file.json')} Save JSON report to file
943
+
944
+ ${colors.bold(colors.yellow('Focus Modes:'))}
945
+ ${colors.cyan('links')} Internal/external links, broken links, anchor text
946
+ ${colors.cyan('duplicates')} Duplicate titles, descriptions, content (85% similarity)
947
+ ${colors.cyan('security')} SSL/TLS, HTTPS, form security, headers
948
+ ${colors.cyan('ai')} AI/LLM optimization, llms.txt, robots.txt AI bots
949
+ ${colors.cyan('resources')} JS/CSS optimization, image compression, caching
950
+ ${colors.cyan('all')} Run all focus modes (default)
951
+ `)
952
+ .action(async (url, args) => {
953
+ let maxDepth = 5;
954
+ let maxPages = 100;
955
+ let concurrency = 5;
956
+ let seoEnabled = false;
957
+ let outputFile = '';
958
+ let focusMode = 'all';
959
+ const focusCategories = {
960
+ links: ['links'],
961
+ duplicates: ['title', 'meta', 'content'],
962
+ security: ['security'],
963
+ ai: ['ai-search'],
964
+ resources: ['resources', 'performance'],
965
+ all: [],
966
+ };
967
+ for (const arg of args) {
968
+ if (arg.startsWith('depth=')) {
969
+ maxDepth = parseInt(arg.split('=')[1]) || 5;
970
+ }
971
+ else if (arg.startsWith('limit=')) {
972
+ maxPages = parseInt(arg.split('=')[1]) || 100;
973
+ }
974
+ else if (arg.startsWith('concurrency=')) {
975
+ concurrency = parseInt(arg.split('=')[1]) || 5;
976
+ }
977
+ else if (arg === 'seo') {
978
+ seoEnabled = true;
979
+ }
980
+ else if (arg.startsWith('output=')) {
981
+ outputFile = arg.split('=')[1] || '';
982
+ }
983
+ else if (arg.startsWith('focus=')) {
984
+ const mode = arg.split('=')[1] || 'all';
985
+ if (mode in focusCategories) {
986
+ focusMode = mode;
987
+ }
988
+ else {
989
+ console.error(colors.red(`Invalid focus mode: ${mode}`));
990
+ console.error(colors.gray(`Valid modes: ${Object.keys(focusCategories).join(', ')}`));
991
+ process.exit(1);
992
+ }
993
+ }
994
+ }
995
+ if (!url.startsWith('http'))
996
+ url = `https://${url}`;
997
+ const modeLabel = seoEnabled ? colors.magenta(' + SEO') : '';
998
+ const focusLabel = focusMode !== 'all' ? colors.cyan(` [focus: ${focusMode}]`) : '';
999
+ console.log(colors.cyan(`\nSpider starting: ${url}`));
1000
+ console.log(colors.gray(` Depth: ${maxDepth} | Limit: ${maxPages} | Concurrency: ${concurrency}${modeLabel}${focusLabel}`));
1001
+ if (outputFile) {
1002
+ console.log(colors.gray(` Output: ${outputFile}`));
1003
+ }
1004
+ console.log('');
1005
+ try {
1006
+ if (seoEnabled) {
1007
+ const { SeoSpider } = await import('../seo/index.js');
1008
+ const seoSpider = new SeoSpider({
1009
+ maxDepth,
1010
+ maxPages,
1011
+ concurrency,
1012
+ sameDomain: true,
1013
+ delay: 100,
1014
+ seo: true,
1015
+ output: outputFile || undefined,
1016
+ focusCategories: focusCategories[focusMode],
1017
+ focusMode,
1018
+ onProgress: (progress) => {
1019
+ process.stdout.write(`\r${colors.gray(' Crawling:')} ${colors.cyan(progress.crawled.toString())} pages | ${colors.gray('Queue:')} ${progress.queued} | ${colors.gray('Depth:')} ${progress.depth} `);
1020
+ },
1021
+ });
1022
+ const result = await seoSpider.crawl(url);
1023
+ process.stdout.write('\r' + ' '.repeat(80) + '\r');
1024
+ console.log(colors.green(`\n✔ SEO Spider complete`) + colors.gray(` (${(result.duration / 1000).toFixed(1)}s)`));
1025
+ console.log(` ${colors.cyan('Pages crawled')}: ${result.pages.length}`);
1026
+ console.log(` ${colors.cyan('Unique URLs')}: ${result.visited.size}`);
1027
+ console.log(` ${colors.cyan('Avg SEO Score')}: ${result.summary.avgScore}/100`);
1028
+ const responseTimes = result.pages.filter(p => p.duration > 0).map(p => p.duration);
1029
+ const avgResponseTime = responseTimes.length > 0
1030
+ ? Math.round(responseTimes.reduce((a, b) => a + b, 0) / responseTimes.length)
1031
+ : 0;
1032
+ const minResponseTime = responseTimes.length > 0 ? Math.min(...responseTimes) : 0;
1033
+ const maxResponseTime = responseTimes.length > 0 ? Math.max(...responseTimes) : 0;
1034
+ const reqPerSec = result.duration > 0 ? (result.pages.length / (result.duration / 1000)).toFixed(1) : '0';
1035
+ const statusCounts = new Map();
1036
+ for (const page of result.pages) {
1037
+ const status = page.status || 0;
1038
+ statusCounts.set(status, (statusCounts.get(status) || 0) + 1);
1039
+ }
1040
+ let totalInternalLinks = 0;
1041
+ let totalExternalLinks = 0;
1042
+ let totalImages = 0;
1043
+ let imagesWithoutAlt = 0;
1044
+ let pagesWithoutTitle = 0;
1045
+ let pagesWithoutDescription = 0;
1046
+ for (const page of result.pages) {
1047
+ if (page.seoReport) {
1048
+ totalInternalLinks += page.seoReport.links?.internal || 0;
1049
+ totalExternalLinks += page.seoReport.links?.external || 0;
1050
+ totalImages += page.seoReport.images?.total || 0;
1051
+ imagesWithoutAlt += page.seoReport.images?.withoutAlt || 0;
1052
+ if (!page.seoReport.title?.text)
1053
+ pagesWithoutTitle++;
1054
+ if (!page.seoReport.metaDescription?.text)
1055
+ pagesWithoutDescription++;
1056
+ }
1057
+ }
1058
+ console.log(colors.bold('\n Performance:'));
1059
+ console.log(` ${colors.gray('Avg Response:')} ${avgResponseTime}ms`);
1060
+ console.log(` ${colors.gray('Min/Max:')} ${minResponseTime}ms / ${maxResponseTime}ms`);
1061
+ console.log(` ${colors.gray('Throughput:')} ${reqPerSec} req/s`);
1062
+ console.log(colors.bold('\n HTTP Status:'));
1063
+ const sortedStatuses = Array.from(statusCounts.entries()).sort((a, b) => b[1] - a[1]);
1064
+ for (const [status, count] of sortedStatuses.slice(0, 5)) {
1065
+ const statusLabel = status === 0 ? 'Error' : status.toString();
1066
+ const statusColor = status >= 400 || status === 0 ? colors.red :
1067
+ status >= 300 ? colors.yellow : colors.green;
1068
+ const pct = ((count / result.pages.length) * 100).toFixed(0);
1069
+ console.log(` ${statusColor(statusLabel.padEnd(5))} ${count.toString().padStart(3)} (${pct}%)`);
1070
+ }
1071
+ console.log(colors.bold('\n Content:'));
1072
+ console.log(` ${colors.gray('Internal links:')} ${totalInternalLinks.toLocaleString()}`);
1073
+ console.log(` ${colors.gray('External links:')} ${totalExternalLinks.toLocaleString()}`);
1074
+ console.log(` ${colors.gray('Images:')} ${totalImages.toLocaleString()} (${imagesWithoutAlt} missing alt)`);
1075
+ console.log(` ${colors.gray('Missing title:')} ${pagesWithoutTitle}`);
1076
+ console.log(` ${colors.gray('Missing desc:')} ${pagesWithoutDescription}`);
1077
+ console.log(colors.bold('\n SEO Summary:'));
1078
+ const { summary } = result;
1079
+ console.log(` ${colors.red('✗')} Pages with errors: ${summary.pagesWithErrors}`);
1080
+ console.log(` ${colors.yellow('⚠')} Pages with warnings: ${summary.pagesWithWarnings}`);
1081
+ console.log(` ${colors.magenta('⚐')} Duplicate titles: ${summary.duplicateTitles}`);
1082
+ console.log(` ${colors.magenta('⚐')} Duplicate descriptions:${summary.duplicateDescriptions}`);
1083
+ console.log(` ${colors.magenta('⚐')} Duplicate H1s: ${summary.duplicateH1s}`);
1084
+ console.log(` ${colors.gray('○')} Orphan pages: ${summary.orphanPages}`);
1085
+ if (result.siteWideIssues.length > 0) {
1086
+ console.log(colors.bold('\n Site-Wide Issues:'));
1087
+ for (const issue of result.siteWideIssues.slice(0, 10)) {
1088
+ const icon = issue.severity === 'error' ? colors.red('✗') :
1089
+ issue.severity === 'warning' ? colors.yellow('⚠') : colors.gray('○');
1090
+ console.log(` ${icon} ${issue.message}`);
1091
+ if (issue.value) {
1092
+ const truncatedValue = issue.value.length > 50 ? issue.value.slice(0, 47) + '...' : issue.value;
1093
+ console.log(` ${colors.gray(`"${truncatedValue}"`)}`);
1094
+ }
1095
+ const uniquePaths = [...new Set(issue.affectedUrls.map(u => new URL(u).pathname))];
1096
+ if (uniquePaths.length <= 3) {
1097
+ for (const path of uniquePaths) {
1098
+ console.log(` ${colors.gray('→')} ${path}`);
1099
+ }
1100
+ }
1101
+ else {
1102
+ console.log(` ${colors.gray(`→ ${uniquePaths.length} pages affected`)}`);
1103
+ }
1104
+ }
1105
+ if (result.siteWideIssues.length > 10) {
1106
+ console.log(colors.gray(` ... and ${result.siteWideIssues.length - 10} more issues`));
1107
+ }
1108
+ }
1109
+ const pagesWithScores = result.pages
1110
+ .filter(p => p.seoReport)
1111
+ .sort((a, b) => (a.seoReport?.score || 0) - (b.seoReport?.score || 0));
1112
+ const seenPaths = new Set();
1113
+ const uniquePages = pagesWithScores.filter(page => {
1114
+ const path = new URL(page.url).pathname;
1115
+ if (seenPaths.has(path))
1116
+ return false;
1117
+ seenPaths.add(path);
1118
+ return true;
1119
+ });
1120
+ if (uniquePages.length > 0) {
1121
+ console.log(colors.bold('\n Pages by SEO Score:'));
1122
+ const worstPages = uniquePages.slice(0, 5);
1123
+ for (const page of worstPages) {
1124
+ const score = page.seoReport?.score || 0;
1125
+ const grade = page.seoReport?.grade || '?';
1126
+ const path = new URL(page.url).pathname;
1127
+ const scoreColor = score >= 80 ? colors.green : score >= 60 ? colors.yellow : colors.red;
1128
+ console.log(` ${scoreColor(`${score.toString().padStart(3)}`)} ${colors.gray(`[${grade}]`)} ${path.slice(0, 50)}`);
1129
+ }
1130
+ if (uniquePages.length > 5) {
1131
+ console.log(colors.gray(` ... and ${uniquePages.length - 5} more pages`));
1132
+ }
1133
+ }
1134
+ if (outputFile) {
1135
+ console.log(colors.green(`\n Report saved to: ${outputFile}`));
1136
+ }
1137
+ }
1138
+ else {
1139
+ const { Spider } = await import('../scrape/spider.js');
1140
+ const spider = new Spider({
1141
+ maxDepth,
1142
+ maxPages,
1143
+ concurrency,
1144
+ sameDomain: true,
1145
+ delay: 100,
1146
+ onProgress: (progress) => {
1147
+ process.stdout.write(`\r${colors.gray(' Crawling:')} ${colors.cyan(progress.crawled.toString())} pages | ${colors.gray('Queue:')} ${progress.queued} | ${colors.gray('Depth:')} ${progress.depth} `);
1148
+ },
1149
+ });
1150
+ const result = await spider.crawl(url);
1151
+ process.stdout.write('\r' + ' '.repeat(80) + '\r');
1152
+ console.log(colors.green(`\n✔ Spider complete`) + colors.gray(` (${(result.duration / 1000).toFixed(1)}s)`));
1153
+ console.log(` ${colors.cyan('Pages crawled')}: ${result.pages.length}`);
1154
+ console.log(` ${colors.cyan('Unique URLs')}: ${result.visited.size}`);
1155
+ console.log(` ${colors.cyan('Errors')}: ${result.errors.length}`);
1156
+ const byDepth = new Map();
1157
+ for (const page of result.pages) {
1158
+ byDepth.set(page.depth, (byDepth.get(page.depth) || 0) + 1);
1159
+ }
1160
+ console.log(colors.bold('\n Pages by depth:'));
1161
+ for (const [depth, count] of Array.from(byDepth.entries()).sort((a, b) => a[0] - b[0])) {
1162
+ const bar = '█'.repeat(Math.min(count, 40));
1163
+ console.log(` ${colors.gray(`d${depth}:`)} ${bar} ${count}`);
1164
+ }
1165
+ const topPages = [...result.pages]
1166
+ .filter(p => !p.error)
1167
+ .sort((a, b) => b.links.length - a.links.length)
1168
+ .slice(0, 10);
1169
+ if (topPages.length > 0) {
1170
+ console.log(colors.bold('\n Top pages by outgoing links:'));
1171
+ for (const page of topPages) {
1172
+ const title = page.title.slice(0, 40) || new URL(page.url).pathname;
1173
+ console.log(` ${colors.cyan(page.links.length.toString().padStart(3))} ${title}`);
1174
+ }
1175
+ }
1176
+ const formatError = (error) => {
1177
+ const statusMatch = error.match(/status code (\d{3})/i);
1178
+ if (statusMatch) {
1179
+ return `HTTP ${statusMatch[1]}`;
1180
+ }
1181
+ return error.length > 50 ? error.slice(0, 47) + '...' : error;
1182
+ };
1183
+ if (result.errors.length > 0 && result.errors.length <= 10) {
1184
+ console.log(colors.bold('\n Errors:'));
1185
+ for (const err of result.errors) {
1186
+ const path = new URL(err.url).pathname;
1187
+ console.log(` ${colors.red('✗')} ${path.padEnd(30)} → ${formatError(err.error)}`);
1188
+ }
1189
+ }
1190
+ else if (result.errors.length > 10) {
1191
+ console.log(colors.bold('\n Errors:'));
1192
+ for (const err of result.errors.slice(0, 5)) {
1193
+ const path = new URL(err.url).pathname;
1194
+ console.log(` ${colors.red('✗')} ${path.padEnd(30)} → ${formatError(err.error)}`);
1195
+ }
1196
+ console.log(colors.gray(` ... and ${result.errors.length - 5} more errors`));
1197
+ }
1198
+ if (outputFile) {
1199
+ const jsonOutput = {
1200
+ startUrl: result.startUrl,
1201
+ crawledAt: new Date().toISOString(),
1202
+ duration: result.duration,
1203
+ summary: {
1204
+ totalPages: result.pages.length,
1205
+ successCount: result.pages.filter(p => !p.error).length,
1206
+ errorCount: result.errors.length,
1207
+ uniqueUrls: result.visited.size,
1208
+ },
1209
+ pages: result.pages.map(p => ({
1210
+ url: p.url,
1211
+ status: p.status,
1212
+ title: p.title,
1213
+ depth: p.depth,
1214
+ linksCount: p.links.length,
1215
+ duration: p.duration,
1216
+ error: p.error,
1217
+ })),
1218
+ errors: result.errors,
1219
+ };
1220
+ await fs.writeFile(outputFile, JSON.stringify(jsonOutput, null, 2));
1221
+ console.log(colors.green(`\n Report saved to: ${outputFile}`));
1222
+ }
1223
+ }
1224
+ console.log('');
1225
+ }
662
1226
  catch (error) {
663
1227
  console.error(colors.red(`\nSpider failed: ${error.message}`));
664
1228
  process.exit(1);
665
1229
  }
666
1230
  });
1231
+ program
1232
+ .command('scrape')
1233
+ .description('Scrape data from a web page using CSS selectors')
1234
+ .argument('<url>', 'URL to scrape')
1235
+ .argument('[args...]', 'Options: select=SELECTOR, attr=NAME, links, images, meta, tables, scripts, jsonld')
1236
+ .addHelpText('after', `
1237
+ ${colors.bold(colors.yellow('Examples:'))}
1238
+ ${colors.green('$ rek scrape example.com')} ${colors.gray('# Basic page info')}
1239
+ ${colors.green('$ rek scrape example.com select="h1"')} ${colors.gray('# Extract h1 text')}
1240
+ ${colors.green('$ rek scrape example.com select="a" attr=href')} ${colors.gray('# Extract link hrefs')}
1241
+ ${colors.green('$ rek scrape example.com links')} ${colors.gray('# All links')}
1242
+ ${colors.green('$ rek scrape example.com images')} ${colors.gray('# All images')}
1243
+ ${colors.green('$ rek scrape example.com meta')} ${colors.gray('# Meta tags')}
1244
+ ${colors.green('$ rek scrape example.com tables')} ${colors.gray('# All tables as JSON')}
1245
+ ${colors.green('$ rek scrape example.com scripts')} ${colors.gray('# All scripts')}
1246
+ ${colors.green('$ rek scrape example.com jsonld')} ${colors.gray('# JSON-LD structured data')}
1247
+
1248
+ ${colors.bold(colors.yellow('Options:'))}
1249
+ ${colors.cyan('select=SELECTOR')} CSS selector to extract elements
1250
+ ${colors.cyan('attr=NAME')} Extract specific attribute (use with select)
1251
+ ${colors.cyan('links')} Extract all links with text and href
1252
+ ${colors.cyan('images')} Extract all images with src and alt
1253
+ ${colors.cyan('meta')} Extract all meta tags
1254
+ ${colors.cyan('tables')} Extract tables as structured JSON
1255
+ ${colors.cyan('scripts')} Extract all script sources
1256
+ ${colors.cyan('jsonld')} Extract JSON-LD structured data
1257
+ `)
1258
+ .action(async (url, args) => {
1259
+ const { ScrapeDocument } = await import('../scrape/document.js');
1260
+ const { Client } = await import('../core/client.js');
1261
+ let selector = '';
1262
+ let attrName = '';
1263
+ let extractLinks = false;
1264
+ let extractImages = false;
1265
+ let extractMeta = false;
1266
+ let extractTables = false;
1267
+ let extractScripts = false;
1268
+ let extractJsonLd = false;
1269
+ for (const arg of args) {
1270
+ if (arg.startsWith('select=')) {
1271
+ selector = arg.slice(7);
1272
+ }
1273
+ else if (arg.startsWith('attr=')) {
1274
+ attrName = arg.slice(5);
1275
+ }
1276
+ else if (arg === 'links') {
1277
+ extractLinks = true;
1278
+ }
1279
+ else if (arg === 'images') {
1280
+ extractImages = true;
1281
+ }
1282
+ else if (arg === 'meta') {
1283
+ extractMeta = true;
1284
+ }
1285
+ else if (arg === 'tables') {
1286
+ extractTables = true;
1287
+ }
1288
+ else if (arg === 'scripts') {
1289
+ extractScripts = true;
1290
+ }
1291
+ else if (arg === 'jsonld') {
1292
+ extractJsonLd = true;
1293
+ }
1294
+ }
1295
+ if (!url.startsWith('http://') && !url.startsWith('https://')) {
1296
+ url = `https://${url}`;
1297
+ }
1298
+ console.log(colors.gray(`Fetching ${url}...`));
1299
+ try {
1300
+ const client = new Client();
1301
+ const response = await client.get(url);
1302
+ const html = await response.text();
1303
+ const doc = await ScrapeDocument.create(html, { baseUrl: url });
1304
+ if (!selector && !extractLinks && !extractImages && !extractMeta && !extractTables && !extractScripts && !extractJsonLd) {
1305
+ const title = doc.text('title') || 'N/A';
1306
+ const description = doc.attr('meta[name="description"]', 'content') || 'N/A';
1307
+ const h1 = doc.text('h1') || 'N/A';
1308
+ const linkCount = doc.links().length;
1309
+ const imageCount = doc.images().length;
1310
+ console.log(`
1311
+ ${colors.bold(colors.cyan('📄 Page Info'))}
1312
+
1313
+ ${colors.bold('Title:')} ${title}
1314
+ ${colors.bold('Description:')} ${description.slice(0, 100)}${description.length > 100 ? '...' : ''}
1315
+ ${colors.bold('H1:')} ${h1}
1316
+ ${colors.bold('Links:')} ${linkCount}
1317
+ ${colors.bold('Images:')} ${imageCount}
1318
+ `);
1319
+ return;
1320
+ }
1321
+ if (selector) {
1322
+ if (attrName) {
1323
+ const values = doc.attrs(selector, attrName);
1324
+ console.log(`\n${colors.bold(`Found ${values.length} values for "${attrName}" in "${selector}"`)}\n`);
1325
+ values.slice(0, 50).forEach((value, i) => {
1326
+ if (value) {
1327
+ console.log(`${colors.gray(`${i + 1}.`)} ${value}`);
1328
+ }
1329
+ });
1330
+ if (values.length > 50) {
1331
+ console.log(colors.gray(`\n... and ${values.length - 50} more`));
1332
+ }
1333
+ }
1334
+ else {
1335
+ const texts = doc.texts(selector);
1336
+ console.log(`\n${colors.bold(`Found ${texts.length} elements matching "${selector}"`)}\n`);
1337
+ texts.slice(0, 50).forEach((text, i) => {
1338
+ const trimmed = text.trim();
1339
+ if (trimmed) {
1340
+ console.log(`${colors.gray(`${i + 1}.`)} ${trimmed.slice(0, 200)}`);
1341
+ }
1342
+ });
1343
+ if (texts.length > 50) {
1344
+ console.log(colors.gray(`\n... and ${texts.length - 50} more`));
1345
+ }
1346
+ }
1347
+ return;
1348
+ }
1349
+ if (extractLinks) {
1350
+ const links = doc.links();
1351
+ console.log(`\n${colors.bold(`Found ${links.length} links`)}\n`);
1352
+ links.slice(0, 50).forEach((link, i) => {
1353
+ const text = (link.text || '').trim().slice(0, 50) || '[no text]';
1354
+ console.log(`${colors.gray(`${i + 1}.`)} ${colors.cyan(text)}`);
1355
+ console.log(` ${colors.gray(link.href)}`);
1356
+ });
1357
+ if (links.length > 50) {
1358
+ console.log(colors.gray(`\n... and ${links.length - 50} more`));
1359
+ }
1360
+ return;
1361
+ }
1362
+ if (extractImages) {
1363
+ const images = doc.images();
1364
+ console.log(`\n${colors.bold(`Found ${images.length} images`)}\n`);
1365
+ images.slice(0, 30).forEach((img, i) => {
1366
+ const alt = img.alt || '[no alt]';
1367
+ console.log(`${colors.gray(`${i + 1}.`)} ${colors.cyan(alt.slice(0, 50))}`);
1368
+ console.log(` ${colors.gray(img.src)}`);
1369
+ });
1370
+ if (images.length > 30) {
1371
+ console.log(colors.gray(`\n... and ${images.length - 30} more`));
1372
+ }
1373
+ return;
1374
+ }
1375
+ if (extractMeta) {
1376
+ const meta = doc.meta();
1377
+ const entries = Object.entries(meta);
1378
+ console.log(`\n${colors.bold(`Found ${entries.length} meta entries`)}\n`);
1379
+ entries.forEach(([name, content]) => {
1380
+ if (name && content) {
1381
+ const value = String(content);
1382
+ console.log(`${colors.cyan(name)}: ${value.slice(0, 100)}${value.length > 100 ? '...' : ''}`);
1383
+ }
1384
+ });
1385
+ return;
1386
+ }
1387
+ if (extractTables) {
1388
+ const tables = doc.tables();
1389
+ console.log(`\n${colors.bold(`Found ${tables.length} tables`)}\n`);
1390
+ tables.slice(0, 5).forEach((table, tableIndex) => {
1391
+ console.log(`${colors.bold(`Table ${tableIndex + 1}:`)} ${table.rows?.length || 0} rows`);
1392
+ console.log(JSON.stringify((table.rows || []).slice(0, 10), null, 2));
1393
+ if ((table.rows?.length || 0) > 10) {
1394
+ console.log(colors.gray(`... and ${(table.rows?.length || 0) - 10} more rows`));
1395
+ }
1396
+ console.log('');
1397
+ });
1398
+ return;
1399
+ }
1400
+ if (extractScripts) {
1401
+ const scripts = doc.scripts();
1402
+ const external = scripts.filter(s => s.src);
1403
+ const inline = scripts.filter(s => !s.src);
1404
+ console.log(`\n${colors.bold(`Found ${external.length} external scripts, ${inline.length} inline`)}\n`);
1405
+ if (external.length > 0) {
1406
+ console.log(colors.bold('External Scripts:'));
1407
+ external.slice(0, 20).forEach((script, i) => {
1408
+ console.log(`${colors.gray(`${i + 1}.`)} ${script.src}`);
1409
+ });
1410
+ if (external.length > 20) {
1411
+ console.log(colors.gray(`... and ${external.length - 20} more`));
1412
+ }
1413
+ }
1414
+ return;
1415
+ }
1416
+ if (extractJsonLd) {
1417
+ const jsonld = doc.jsonLd();
1418
+ console.log(`\n${colors.bold(`Found ${jsonld.length} JSON-LD blocks`)}\n`);
1419
+ jsonld.forEach((data, i) => {
1420
+ console.log(`${colors.bold(`Block ${i + 1}:`)} ${data['@type'] || 'Unknown type'}`);
1421
+ console.log(JSON.stringify(data, null, 2));
1422
+ console.log('');
1423
+ });
1424
+ return;
1425
+ }
1426
+ }
1427
+ catch (error) {
1428
+ console.error(colors.red(`Scrape failed: ${error.message}`));
1429
+ process.exit(1);
1430
+ }
1431
+ });
667
1432
  program
668
1433
  .command('ai')
669
1434
  .description('Send a single AI prompt (no memory/context)')
@@ -790,103 +1555,553 @@ ${colors.bold(colors.yellow('Note:'))}
790
1555
  console.log(colors.gray(`Downloading GeoLite2 database...`));
791
1556
  }
792
1557
  try {
793
- const info = await getIpInfo(address);
794
- if (info.bogon) {
795
- console.log(colors.yellow(`\n⚠ ${address} is a Bogon/Private IP.`));
796
- console.log(colors.gray(` Type: ${info.bogonType}`));
797
- return;
1558
+ const info = await getIpInfo(address);
1559
+ if (info.bogon) {
1560
+ console.log(colors.yellow(`\n⚠ ${address} is a Bogon/Private IP.`));
1561
+ console.log(colors.gray(` Type: ${info.bogonType}`));
1562
+ return;
1563
+ }
1564
+ console.log(`
1565
+ ${colors.bold(colors.cyan('🌍 IP Intelligence Report'))}
1566
+
1567
+ ${colors.bold('Location:')}
1568
+ ${colors.gray('City:')} ${info.city || 'N/A'}
1569
+ ${colors.gray('Region:')} ${info.region || 'N/A'}
1570
+ ${colors.gray('Country:')} ${info.country || 'N/A'} ${info.countryCode ? `(${info.countryCode})` : ''}
1571
+ ${colors.gray('Continent:')} ${info.continent || 'N/A'}
1572
+ ${colors.gray('Timezone:')} ${info.timezone || 'N/A'}
1573
+ ${colors.gray('Coords:')} ${info.loc ? colors.cyan(info.loc) : 'N/A'}
1574
+ ${colors.gray('Accuracy:')} ${info.accuracy ? `~${info.accuracy} km` : 'N/A'}
1575
+
1576
+ ${colors.bold('Network:')}
1577
+ ${colors.gray('IP:')} ${info.ip}
1578
+ ${colors.gray('Type:')} ${info.isIPv6 ? 'IPv6' : 'IPv4'}
1579
+ ${colors.gray('Postal:')} ${info.postal || 'N/A'}
1580
+ `);
1581
+ }
1582
+ catch (err) {
1583
+ console.error(colors.red(`IP Lookup Failed: ${err.message}`));
1584
+ process.exit(1);
1585
+ }
1586
+ });
1587
+ program
1588
+ .command('tls')
1589
+ .alias('ssl')
1590
+ .description('Inspect TLS/SSL certificate of a host')
1591
+ .argument('<host>', 'Hostname or IP address')
1592
+ .argument('[port]', 'Port number (default: 443)', '443')
1593
+ .action(async (host, port) => {
1594
+ const { inspectTLS } = await import('../utils/tls-inspector.js');
1595
+ console.log(colors.gray(`Inspecting TLS certificate for ${host}:${port}...`));
1596
+ try {
1597
+ const info = await inspectTLS(host, parseInt(port));
1598
+ let daysColor = colors.green;
1599
+ if (info.daysRemaining < 30)
1600
+ daysColor = colors.red;
1601
+ else if (info.daysRemaining < 90)
1602
+ daysColor = colors.yellow;
1603
+ const validIcon = info.valid ? colors.green('✔ Valid') : colors.red('✖ Expired');
1604
+ const authIcon = info.authorized ? colors.green('✔ Trusted') : colors.yellow('⚠ Self-signed/Untrusted');
1605
+ console.log(`
1606
+ ${colors.bold(colors.cyan('🔒 TLS Certificate Report'))}
1607
+
1608
+ ${colors.bold('Status:')}
1609
+ ${validIcon}
1610
+ ${authIcon}
1611
+ ${colors.gray('Days Remaining:')} ${daysColor(info.daysRemaining.toString())}
1612
+
1613
+ ${colors.bold('Certificate:')}
1614
+ ${colors.gray('Subject:')} ${info.subject?.CN || info.subject?.O || 'N/A'}
1615
+ ${colors.gray('Issuer:')} ${info.issuer?.CN || info.issuer?.O || 'N/A'}
1616
+ ${colors.gray('Valid From:')} ${info.validFrom.toISOString().split('T')[0]}
1617
+ ${colors.gray('Valid To:')} ${info.validTo.toISOString().split('T')[0]}
1618
+ ${colors.gray('Serial:')} ${info.serialNumber}
1619
+
1620
+ ${colors.bold('Security:')}
1621
+ ${colors.gray('Protocol:')} ${info.protocol || 'N/A'}
1622
+ ${colors.gray('Cipher:')} ${info.cipher?.name || 'N/A'}
1623
+ ${colors.gray('Key:')} ${info.pubkey ? `${info.pubkey.algo.toUpperCase()} ${info.pubkey.size}-bit` : 'N/A'}
1624
+
1625
+ ${colors.bold('Fingerprints:')}
1626
+ ${colors.gray('SHA-1:')} ${info.fingerprint}
1627
+ ${colors.gray('SHA-256:')} ${info.fingerprint256?.slice(0, 40)}...
1628
+ `);
1629
+ if (info.altNames && info.altNames.length > 0) {
1630
+ console.log(`${colors.bold('Subject Alternative Names:')}`);
1631
+ info.altNames.slice(0, 10).forEach(san => {
1632
+ console.log(` ${colors.gray('•')} ${san}`);
1633
+ });
1634
+ if (info.altNames.length > 10) {
1635
+ console.log(` ${colors.gray(`... and ${info.altNames.length - 10} more`)}`);
1636
+ }
1637
+ console.log('');
1638
+ }
1639
+ if (info.extKeyUsage && info.extKeyUsage.length > 0) {
1640
+ console.log(`${colors.bold('Extended Key Usage:')}`);
1641
+ info.extKeyUsage.forEach(oid => {
1642
+ const oidNames = {
1643
+ '1.3.6.1.5.5.7.3.1': 'Server Authentication',
1644
+ '1.3.6.1.5.5.7.3.2': 'Client Authentication',
1645
+ '1.3.6.1.5.5.7.3.3': 'Code Signing',
1646
+ '1.3.6.1.5.5.7.3.4': 'Email Protection',
1647
+ };
1648
+ console.log(` ${colors.gray('•')} ${oidNames[oid] || oid}`);
1649
+ });
1650
+ console.log('');
1651
+ }
1652
+ }
1653
+ catch (err) {
1654
+ console.error(colors.red(`TLS Inspection Failed: ${err.message}`));
1655
+ process.exit(1);
1656
+ }
1657
+ });
1658
+ program
1659
+ .command('whois')
1660
+ .description('WHOIS lookup for domains and IP addresses')
1661
+ .argument('<query>', 'Domain name or IP address')
1662
+ .option('-r, --raw', 'Show raw WHOIS response')
1663
+ .action(async (query, options) => {
1664
+ const { whois } = await import('../utils/whois.js');
1665
+ console.log(colors.gray(`Looking up WHOIS for ${query}...`));
1666
+ try {
1667
+ const result = await whois(query);
1668
+ if (options.raw) {
1669
+ console.log(result.raw);
1670
+ return;
1671
+ }
1672
+ console.log(`
1673
+ ${colors.bold(colors.cyan('📋 WHOIS Report'))}
1674
+
1675
+ ${colors.bold('Query:')} ${result.query}
1676
+ ${colors.bold('Server:')} ${result.server}
1677
+ `);
1678
+ if (result.data && Object.keys(result.data).length > 0) {
1679
+ console.log(colors.bold('Parsed Data:'));
1680
+ const importantKeys = ['Domain Name', 'Registrar', 'Creation Date', 'Expiration Date', 'Updated Date', 'Name Server', 'Status'];
1681
+ for (const key of importantKeys) {
1682
+ const value = result.data[key];
1683
+ if (value) {
1684
+ if (Array.isArray(value)) {
1685
+ console.log(` ${colors.cyan(key)}:`);
1686
+ value.forEach((v) => console.log(` ${colors.gray('•')} ${v}`));
1687
+ }
1688
+ else {
1689
+ console.log(` ${colors.cyan(key)}: ${value}`);
1690
+ }
1691
+ }
1692
+ }
1693
+ }
1694
+ console.log('');
1695
+ }
1696
+ catch (err) {
1697
+ console.error(colors.red(`WHOIS Lookup Failed: ${err.message}`));
1698
+ process.exit(1);
1699
+ }
1700
+ });
1701
+ program
1702
+ .command('rdap')
1703
+ .description('RDAP lookup (modern WHOIS replacement)')
1704
+ .argument('<domain>', 'Domain name to lookup')
1705
+ .action(async (domain) => {
1706
+ const { rdap } = await import('../utils/rdap.js');
1707
+ const { Client } = await import('../core/client.js');
1708
+ console.log(colors.gray(`Looking up RDAP for ${domain}...`));
1709
+ try {
1710
+ const client = new Client();
1711
+ const result = await rdap(client, domain);
1712
+ console.log(`
1713
+ ${colors.bold(colors.cyan('📋 RDAP Report'))}
1714
+
1715
+ ${colors.bold('Domain:')} ${result.ldhName || domain}
1716
+ ${colors.bold('Handle:')} ${result.handle || 'N/A'}
1717
+ ${colors.bold('Status:')} ${result.status?.join(', ') || 'N/A'}
1718
+ `);
1719
+ if (result.events && result.events.length > 0) {
1720
+ console.log(`${colors.bold('Events:')}`);
1721
+ result.events.forEach((event) => {
1722
+ const date = event.eventDate ? new Date(event.eventDate).toISOString().split('T')[0] : 'N/A';
1723
+ console.log(` ${colors.gray(event.eventAction + ':')} ${date}`);
1724
+ });
1725
+ console.log('');
1726
+ }
1727
+ if (result.nameservers && result.nameservers.length > 0) {
1728
+ console.log(`${colors.bold('Name Servers:')}`);
1729
+ result.nameservers.forEach((ns) => {
1730
+ console.log(` ${colors.gray('•')} ${ns.ldhName}`);
1731
+ });
1732
+ console.log('');
1733
+ }
1734
+ if (result.entities && result.entities.length > 0) {
1735
+ console.log(`${colors.bold('Entities:')}`);
1736
+ result.entities.slice(0, 5).forEach((entity) => {
1737
+ const roles = entity.roles?.join(', ') || 'N/A';
1738
+ console.log(` ${colors.gray(roles + ':')} ${entity.handle || 'Unknown'}`);
1739
+ });
1740
+ console.log('');
1741
+ }
1742
+ if (result.links && result.links.length > 0) {
1743
+ const selfLink = result.links.find((l) => l.rel === 'self');
1744
+ if (selfLink) {
1745
+ console.log(`${colors.gray('Source:')} ${selfLink.href}`);
1746
+ }
1747
+ }
1748
+ }
1749
+ catch (err) {
1750
+ console.error(colors.red(`RDAP Lookup Failed: ${err.message}`));
1751
+ process.exit(1);
1752
+ }
1753
+ });
1754
+ program
1755
+ .command('ping')
1756
+ .description('TCP connectivity check to a host')
1757
+ .argument('<host>', 'Hostname or IP address')
1758
+ .argument('[port]', 'Port number (default: 80 for HTTP, 443 for HTTPS)', '443')
1759
+ .option('-c, --count <n>', 'Number of pings', '4')
1760
+ .action(async (host, port, options) => {
1761
+ const net = await import('node:net');
1762
+ const count = parseInt(options.count);
1763
+ const portNum = parseInt(port);
1764
+ const results = [];
1765
+ console.log(colors.gray(`Pinging ${host}:${portNum}...`));
1766
+ console.log('');
1767
+ for (let i = 0; i < count; i++) {
1768
+ const start = performance.now();
1769
+ try {
1770
+ await new Promise((resolve, reject) => {
1771
+ const socket = net.connect(portNum, host, () => {
1772
+ socket.destroy();
1773
+ resolve();
1774
+ });
1775
+ socket.setTimeout(5000);
1776
+ socket.on('timeout', () => {
1777
+ socket.destroy();
1778
+ reject(new Error('Timeout'));
1779
+ });
1780
+ socket.on('error', reject);
1781
+ });
1782
+ const elapsed = performance.now() - start;
1783
+ results.push(elapsed);
1784
+ console.log(`${colors.green('✔')} Connected to ${host}:${portNum} - ${colors.cyan(elapsed.toFixed(2) + 'ms')}`);
1785
+ }
1786
+ catch (err) {
1787
+ console.log(`${colors.red('✖')} Failed to connect: ${err.message}`);
1788
+ }
1789
+ if (i < count - 1) {
1790
+ await new Promise(r => setTimeout(r, 1000));
1791
+ }
1792
+ }
1793
+ if (results.length > 0) {
1794
+ const avg = results.reduce((a, b) => a + b, 0) / results.length;
1795
+ const min = Math.min(...results);
1796
+ const max = Math.max(...results);
1797
+ console.log(`
1798
+ ${colors.bold('Statistics:')}
1799
+ ${colors.gray('Sent:')} ${count}
1800
+ ${colors.gray('Received:')} ${results.length}
1801
+ ${colors.gray('Lost:')} ${count - results.length} (${((count - results.length) / count * 100).toFixed(0)}%)
1802
+ ${colors.gray('Min:')} ${min.toFixed(2)}ms
1803
+ ${colors.gray('Avg:')} ${avg.toFixed(2)}ms
1804
+ ${colors.gray('Max:')} ${max.toFixed(2)}ms
1805
+ `);
1806
+ }
1807
+ });
1808
+ const ftpCmd = program.command('ftp').description('FTP client operations');
1809
+ ftpCmd
1810
+ .command('ls')
1811
+ .description('List files in a remote directory')
1812
+ .argument('<host>', 'FTP server hostname')
1813
+ .argument('[path]', 'Remote path to list', '/')
1814
+ .option('-u, --user <username>', 'Username', 'anonymous')
1815
+ .option('-p, --pass <password>', 'Password', 'anonymous@')
1816
+ .option('-P, --port <port>', 'Port number', '21')
1817
+ .option('--secure', 'Use FTPS (explicit TLS)')
1818
+ .option('--implicit', 'Use implicit FTPS (port 990)')
1819
+ .action(async (host, path, options) => {
1820
+ const { createFTP } = await import('../protocols/ftp.js');
1821
+ const secure = options.implicit ? 'implicit' : options.secure ? true : false;
1822
+ const client = createFTP({
1823
+ host,
1824
+ port: parseInt(options.port),
1825
+ user: options.user,
1826
+ password: options.pass,
1827
+ secure,
1828
+ });
1829
+ console.log(colors.gray(`Connecting to ${host}...`));
1830
+ try {
1831
+ const connectResult = await client.connect();
1832
+ if (!connectResult.success) {
1833
+ console.error(colors.red(`Connection failed: ${connectResult.message}`));
1834
+ process.exit(1);
1835
+ }
1836
+ console.log(colors.green('Connected'));
1837
+ console.log(colors.gray(`Listing ${path}...`));
1838
+ const result = await client.list(path);
1839
+ if (!result.success || !result.data) {
1840
+ console.error(colors.red(`List failed: ${result.message}`));
1841
+ await client.close();
1842
+ process.exit(1);
1843
+ }
1844
+ console.log('');
1845
+ console.log(colors.bold(`Contents of ${path}:`));
1846
+ console.log('');
1847
+ for (const item of result.data) {
1848
+ const typeChar = item.type === 'directory' ? 'd' : item.type === 'link' ? 'l' : '-';
1849
+ const perms = item.permissions || 'rwxr-xr-x';
1850
+ const size = item.size.toString().padStart(10);
1851
+ const date = item.rawModifiedAt || '';
1852
+ const nameColor = item.type === 'directory' ? colors.blue : item.type === 'link' ? colors.cyan : colors.white;
1853
+ console.log(`${typeChar}${perms} ${size} ${date.padEnd(12)} ${nameColor(item.name)}`);
1854
+ }
1855
+ console.log('');
1856
+ console.log(colors.gray(`Total: ${result.data.length} items`));
1857
+ await client.close();
1858
+ }
1859
+ catch (err) {
1860
+ console.error(colors.red(`FTP Error: ${err.message}`));
1861
+ process.exit(1);
1862
+ }
1863
+ });
1864
+ ftpCmd
1865
+ .command('get')
1866
+ .description('Download a file from FTP server')
1867
+ .argument('<host>', 'FTP server hostname')
1868
+ .argument('<remote>', 'Remote file path')
1869
+ .argument('[local]', 'Local file path (default: same filename)')
1870
+ .option('-u, --user <username>', 'Username', 'anonymous')
1871
+ .option('-p, --pass <password>', 'Password', 'anonymous@')
1872
+ .option('-P, --port <port>', 'Port number', '21')
1873
+ .option('--secure', 'Use FTPS (explicit TLS)')
1874
+ .option('--implicit', 'Use implicit FTPS (port 990)')
1875
+ .action(async (host, remote, local, options) => {
1876
+ const { createFTP } = await import('../protocols/ftp.js');
1877
+ const path = await import('node:path');
1878
+ const localPath = local || path.basename(remote);
1879
+ const secure = options.implicit ? 'implicit' : options.secure ? true : false;
1880
+ const client = createFTP({
1881
+ host,
1882
+ port: parseInt(options.port),
1883
+ user: options.user,
1884
+ password: options.pass,
1885
+ secure,
1886
+ });
1887
+ console.log(colors.gray(`Connecting to ${host}...`));
1888
+ try {
1889
+ const connectResult = await client.connect();
1890
+ if (!connectResult.success) {
1891
+ console.error(colors.red(`Connection failed: ${connectResult.message}`));
1892
+ process.exit(1);
1893
+ }
1894
+ console.log(colors.green('Connected'));
1895
+ console.log(colors.gray(`Downloading ${remote} → ${localPath}...`));
1896
+ let lastProgress = 0;
1897
+ client.progress((p) => {
1898
+ const mb = (p.bytesOverall / 1024 / 1024).toFixed(2);
1899
+ if (p.bytesOverall - lastProgress > 100000) {
1900
+ process.stdout.write(`\r ${colors.cyan(mb + ' MB')} downloaded...`);
1901
+ lastProgress = p.bytesOverall;
1902
+ }
1903
+ });
1904
+ const result = await client.download(remote, localPath);
1905
+ console.log('');
1906
+ if (!result.success) {
1907
+ console.error(colors.red(`Download failed: ${result.message}`));
1908
+ await client.close();
1909
+ process.exit(1);
1910
+ }
1911
+ console.log(colors.green(`✔ Downloaded to ${localPath}`));
1912
+ await client.close();
1913
+ }
1914
+ catch (err) {
1915
+ console.error(colors.red(`FTP Error: ${err.message}`));
1916
+ process.exit(1);
1917
+ }
1918
+ });
1919
+ ftpCmd
1920
+ .command('put')
1921
+ .description('Upload a file to FTP server')
1922
+ .argument('<host>', 'FTP server hostname')
1923
+ .argument('<local>', 'Local file path')
1924
+ .argument('[remote]', 'Remote file path (default: same filename)')
1925
+ .option('-u, --user <username>', 'Username', 'anonymous')
1926
+ .option('-p, --pass <password>', 'Password', 'anonymous@')
1927
+ .option('-P, --port <port>', 'Port number', '21')
1928
+ .option('--secure', 'Use FTPS (explicit TLS)')
1929
+ .option('--implicit', 'Use implicit FTPS (port 990)')
1930
+ .action(async (host, local, remote, options) => {
1931
+ const { createFTP } = await import('../protocols/ftp.js');
1932
+ const path = await import('node:path');
1933
+ const remotePath = remote || '/' + path.basename(local);
1934
+ const secure = options.implicit ? 'implicit' : options.secure ? true : false;
1935
+ const client = createFTP({
1936
+ host,
1937
+ port: parseInt(options.port),
1938
+ user: options.user,
1939
+ password: options.pass,
1940
+ secure,
1941
+ });
1942
+ console.log(colors.gray(`Connecting to ${host}...`));
1943
+ try {
1944
+ const connectResult = await client.connect();
1945
+ if (!connectResult.success) {
1946
+ console.error(colors.red(`Connection failed: ${connectResult.message}`));
1947
+ process.exit(1);
1948
+ }
1949
+ console.log(colors.green('Connected'));
1950
+ console.log(colors.gray(`Uploading ${local} → ${remotePath}...`));
1951
+ let lastProgress = 0;
1952
+ client.progress((p) => {
1953
+ const mb = (p.bytesOverall / 1024 / 1024).toFixed(2);
1954
+ if (p.bytesOverall - lastProgress > 100000) {
1955
+ process.stdout.write(`\r ${colors.cyan(mb + ' MB')} uploaded...`);
1956
+ lastProgress = p.bytesOverall;
1957
+ }
1958
+ });
1959
+ const result = await client.upload(local, remotePath);
1960
+ console.log('');
1961
+ if (!result.success) {
1962
+ console.error(colors.red(`Upload failed: ${result.message}`));
1963
+ await client.close();
1964
+ process.exit(1);
1965
+ }
1966
+ console.log(colors.green(`✔ Uploaded to ${remotePath}`));
1967
+ await client.close();
1968
+ }
1969
+ catch (err) {
1970
+ console.error(colors.red(`FTP Error: ${err.message}`));
1971
+ process.exit(1);
1972
+ }
1973
+ });
1974
+ ftpCmd
1975
+ .command('rm')
1976
+ .description('Delete a file from FTP server')
1977
+ .argument('<host>', 'FTP server hostname')
1978
+ .argument('<path>', 'Remote file path to delete')
1979
+ .option('-u, --user <username>', 'Username', 'anonymous')
1980
+ .option('-p, --pass <password>', 'Password', 'anonymous@')
1981
+ .option('-P, --port <port>', 'Port number', '21')
1982
+ .option('--secure', 'Use FTPS (explicit TLS)')
1983
+ .option('--implicit', 'Use implicit FTPS (port 990)')
1984
+ .action(async (host, remotePath, options) => {
1985
+ const { createFTP } = await import('../protocols/ftp.js');
1986
+ const secure = options.implicit ? 'implicit' : options.secure ? true : false;
1987
+ const client = createFTP({
1988
+ host,
1989
+ port: parseInt(options.port),
1990
+ user: options.user,
1991
+ password: options.pass,
1992
+ secure,
1993
+ });
1994
+ console.log(colors.gray(`Connecting to ${host}...`));
1995
+ try {
1996
+ const connectResult = await client.connect();
1997
+ if (!connectResult.success) {
1998
+ console.error(colors.red(`Connection failed: ${connectResult.message}`));
1999
+ process.exit(1);
2000
+ }
2001
+ console.log(colors.green('Connected'));
2002
+ console.log(colors.gray(`Deleting ${remotePath}...`));
2003
+ const result = await client.delete(remotePath);
2004
+ if (!result.success) {
2005
+ console.error(colors.red(`Delete failed: ${result.message}`));
2006
+ await client.close();
2007
+ process.exit(1);
2008
+ }
2009
+ console.log(colors.green(`✔ Deleted ${remotePath}`));
2010
+ await client.close();
2011
+ }
2012
+ catch (err) {
2013
+ console.error(colors.red(`FTP Error: ${err.message}`));
2014
+ process.exit(1);
2015
+ }
2016
+ });
2017
+ ftpCmd
2018
+ .command('mkdir')
2019
+ .description('Create a directory on FTP server')
2020
+ .argument('<host>', 'FTP server hostname')
2021
+ .argument('<path>', 'Remote directory path to create')
2022
+ .option('-u, --user <username>', 'Username', 'anonymous')
2023
+ .option('-p, --pass <password>', 'Password', 'anonymous@')
2024
+ .option('-P, --port <port>', 'Port number', '21')
2025
+ .option('--secure', 'Use FTPS (explicit TLS)')
2026
+ .option('--implicit', 'Use implicit FTPS (port 990)')
2027
+ .action(async (host, remotePath, options) => {
2028
+ const { createFTP } = await import('../protocols/ftp.js');
2029
+ const secure = options.implicit ? 'implicit' : options.secure ? true : false;
2030
+ const client = createFTP({
2031
+ host,
2032
+ port: parseInt(options.port),
2033
+ user: options.user,
2034
+ password: options.pass,
2035
+ secure,
2036
+ });
2037
+ console.log(colors.gray(`Connecting to ${host}...`));
2038
+ try {
2039
+ const connectResult = await client.connect();
2040
+ if (!connectResult.success) {
2041
+ console.error(colors.red(`Connection failed: ${connectResult.message}`));
2042
+ process.exit(1);
798
2043
  }
799
- console.log(`
800
- ${colors.bold(colors.cyan('🌍 IP Intelligence Report'))}
801
-
802
- ${colors.bold('Location:')}
803
- ${colors.gray('City:')} ${info.city || 'N/A'}
804
- ${colors.gray('Region:')} ${info.region || 'N/A'}
805
- ${colors.gray('Country:')} ${info.country || 'N/A'} ${info.countryCode ? `(${info.countryCode})` : ''}
806
- ${colors.gray('Continent:')} ${info.continent || 'N/A'}
807
- ${colors.gray('Timezone:')} ${info.timezone || 'N/A'}
808
- ${colors.gray('Coords:')} ${info.loc ? colors.cyan(info.loc) : 'N/A'}
809
- ${colors.gray('Accuracy:')} ${info.accuracy ? `~${info.accuracy} km` : 'N/A'}
810
-
811
- ${colors.bold('Network:')}
812
- ${colors.gray('IP:')} ${info.ip}
813
- ${colors.gray('Type:')} ${info.isIPv6 ? 'IPv6' : 'IPv4'}
814
- ${colors.gray('Postal:')} ${info.postal || 'N/A'}
815
- `);
2044
+ console.log(colors.green('Connected'));
2045
+ console.log(colors.gray(`Creating ${remotePath}...`));
2046
+ const result = await client.mkdir(remotePath);
2047
+ if (!result.success) {
2048
+ console.error(colors.red(`Mkdir failed: ${result.message}`));
2049
+ await client.close();
2050
+ process.exit(1);
2051
+ }
2052
+ console.log(colors.green(`✔ Created ${remotePath}`));
2053
+ await client.close();
816
2054
  }
817
2055
  catch (err) {
818
- console.error(colors.red(`IP Lookup Failed: ${err.message}`));
2056
+ console.error(colors.red(`FTP Error: ${err.message}`));
819
2057
  process.exit(1);
820
2058
  }
821
2059
  });
822
2060
  program
823
- .command('tls')
824
- .alias('ssl')
825
- .description('Inspect TLS/SSL certificate of a host')
2061
+ .command('telnet')
2062
+ .description('Connect to a Telnet server')
826
2063
  .argument('<host>', 'Hostname or IP address')
827
- .argument('[port]', 'Port number (default: 443)', '443')
828
- .action(async (host, port) => {
829
- const { inspectTLS } = await import('../utils/tls-inspector.js');
830
- console.log(colors.gray(`Inspecting TLS certificate for ${host}:${port}...`));
2064
+ .argument('[port]', 'Port number', '23')
2065
+ .option('-t, --timeout <ms>', 'Connection timeout in ms', '30000')
2066
+ .action(async (host, port, options) => {
2067
+ const { createTelnet } = await import('../protocols/telnet.js');
2068
+ console.log(colors.gray(`Connecting to ${host}:${port}...`));
2069
+ const client = createTelnet({
2070
+ host,
2071
+ port: parseInt(port),
2072
+ timeout: parseInt(options.timeout),
2073
+ });
831
2074
  try {
832
- const info = await inspectTLS(host, parseInt(port));
833
- let daysColor = colors.green;
834
- if (info.daysRemaining < 30)
835
- daysColor = colors.red;
836
- else if (info.daysRemaining < 90)
837
- daysColor = colors.yellow;
838
- const validIcon = info.valid ? colors.green('✔ Valid') : colors.red('✖ Expired');
839
- const authIcon = info.authorized ? colors.green('✔ Trusted') : colors.yellow('⚠ Self-signed/Untrusted');
840
- console.log(`
841
- ${colors.bold(colors.cyan('🔒 TLS Certificate Report'))}
842
-
843
- ${colors.bold('Status:')}
844
- ${validIcon}
845
- ${authIcon}
846
- ${colors.gray('Days Remaining:')} ${daysColor(info.daysRemaining.toString())}
847
-
848
- ${colors.bold('Certificate:')}
849
- ${colors.gray('Subject:')} ${info.subject?.CN || info.subject?.O || 'N/A'}
850
- ${colors.gray('Issuer:')} ${info.issuer?.CN || info.issuer?.O || 'N/A'}
851
- ${colors.gray('Valid From:')} ${info.validFrom.toISOString().split('T')[0]}
852
- ${colors.gray('Valid To:')} ${info.validTo.toISOString().split('T')[0]}
853
- ${colors.gray('Serial:')} ${info.serialNumber}
854
-
855
- ${colors.bold('Security:')}
856
- ${colors.gray('Protocol:')} ${info.protocol || 'N/A'}
857
- ${colors.gray('Cipher:')} ${info.cipher?.name || 'N/A'}
858
- ${colors.gray('Key:')} ${info.pubkey ? `${info.pubkey.algo.toUpperCase()} ${info.pubkey.size}-bit` : 'N/A'}
859
-
860
- ${colors.bold('Fingerprints:')}
861
- ${colors.gray('SHA-1:')} ${info.fingerprint}
862
- ${colors.gray('SHA-256:')} ${info.fingerprint256?.slice(0, 40)}...
863
- `);
864
- if (info.altNames && info.altNames.length > 0) {
865
- console.log(`${colors.bold('Subject Alternative Names:')}`);
866
- info.altNames.slice(0, 10).forEach(san => {
867
- console.log(` ${colors.gray('•')} ${san}`);
868
- });
869
- if (info.altNames.length > 10) {
870
- console.log(` ${colors.gray(`... and ${info.altNames.length - 10} more`)}`);
871
- }
872
- console.log('');
873
- }
874
- if (info.extKeyUsage && info.extKeyUsage.length > 0) {
875
- console.log(`${colors.bold('Extended Key Usage:')}`);
876
- info.extKeyUsage.forEach(oid => {
877
- const oidNames = {
878
- '1.3.6.1.5.5.7.3.1': 'Server Authentication',
879
- '1.3.6.1.5.5.7.3.2': 'Client Authentication',
880
- '1.3.6.1.5.5.7.3.3': 'Code Signing',
881
- '1.3.6.1.5.5.7.3.4': 'Email Protection',
882
- };
883
- console.log(` ${colors.gray('•')} ${oidNames[oid] || oid}`);
884
- });
885
- console.log('');
2075
+ await client.connect();
2076
+ console.log(colors.green(`Connected to ${host}:${port}`));
2077
+ console.log(colors.gray('Type your commands. Press Ctrl+C to exit.'));
2078
+ console.log('');
2079
+ if (process.stdin.isTTY) {
2080
+ process.stdin.setRawMode(true);
886
2081
  }
2082
+ process.stdin.resume();
2083
+ process.stdin.on('data', async (data) => {
2084
+ if (data[0] === 0x03) {
2085
+ console.log(colors.yellow('\nDisconnecting...'));
2086
+ await client.close();
2087
+ process.exit(0);
2088
+ }
2089
+ await client.send(data.toString());
2090
+ });
2091
+ client.on('data', (data) => {
2092
+ process.stdout.write(data);
2093
+ });
2094
+ client.on('close', () => {
2095
+ console.log(colors.yellow('\nConnection closed'));
2096
+ process.exit(0);
2097
+ });
2098
+ client.on('error', (err) => {
2099
+ console.error(colors.red(`Error: ${err.message}`));
2100
+ process.exit(1);
2101
+ });
887
2102
  }
888
2103
  catch (err) {
889
- console.error(colors.red(`TLS Inspection Failed: ${err.message}`));
2104
+ console.error(colors.red(`Telnet Error: ${err.message}`));
890
2105
  process.exit(1);
891
2106
  }
892
2107
  });
@@ -1266,18 +2481,519 @@ ${colors.bold(colors.yellow('Record Types:'))}
1266
2481
  domain = arg;
1267
2482
  }
1268
2483
  }
1269
- if (!domain) {
1270
- console.error(colors.red('Error: Domain/IP is required'));
1271
- console.log(colors.gray('Usage: rek dig example.com [TYPE]'));
1272
- console.log(colors.gray(' rek dig -x 8.8.8.8'));
2484
+ if (!domain) {
2485
+ console.error(colors.red('Error: Domain/IP is required'));
2486
+ console.log(colors.gray('Usage: rek dig example.com [TYPE]'));
2487
+ console.log(colors.gray(' rek dig -x 8.8.8.8'));
2488
+ process.exit(1);
2489
+ }
2490
+ try {
2491
+ const result = await dig(domain, { server, type, reverse, short });
2492
+ console.log(formatDigOutput(result, short));
2493
+ }
2494
+ catch (err) {
2495
+ console.error(colors.red(`dig: ${err.message}`));
2496
+ process.exit(1);
2497
+ }
2498
+ });
2499
+ program
2500
+ .command('graphql')
2501
+ .description('Execute a GraphQL query')
2502
+ .argument('<url>', 'GraphQL endpoint URL')
2503
+ .option('-q, --query <query>', 'GraphQL query string')
2504
+ .option('-f, --file <file>', 'Path to GraphQL query file')
2505
+ .option('-v, --variables <json>', 'Variables as JSON string')
2506
+ .option('--var-file <file>', 'Path to variables JSON file')
2507
+ .option('-H, --header <header>', 'Add header (can be used multiple times)', (val, prev) => [...prev, val], [])
2508
+ .action(async (url, options) => {
2509
+ const { graphql } = await import('../plugins/graphql.js');
2510
+ const { createClient } = await import('../core/client.js');
2511
+ const fs = await import('node:fs/promises');
2512
+ let query = options.query;
2513
+ let variables = {};
2514
+ if (options.file) {
2515
+ try {
2516
+ query = await fs.readFile(options.file, 'utf-8');
2517
+ }
2518
+ catch (err) {
2519
+ console.error(colors.red(`Failed to read query file: ${err.message}`));
2520
+ process.exit(1);
2521
+ }
2522
+ }
2523
+ if (!query) {
2524
+ console.error(colors.red('Error: Query is required. Use --query or --file'));
2525
+ console.log(colors.gray('Example: rek graphql https://api.example.com/graphql -q "query { users { id name } }"'));
2526
+ process.exit(1);
2527
+ }
2528
+ if (options.variables) {
2529
+ try {
2530
+ variables = JSON.parse(options.variables);
2531
+ }
2532
+ catch {
2533
+ console.error(colors.red('Invalid JSON in --variables'));
2534
+ process.exit(1);
2535
+ }
2536
+ }
2537
+ else if (options.varFile) {
2538
+ try {
2539
+ const content = await fs.readFile(options.varFile, 'utf-8');
2540
+ variables = JSON.parse(content);
2541
+ }
2542
+ catch (err) {
2543
+ console.error(colors.red(`Failed to read variables file: ${err.message}`));
2544
+ process.exit(1);
2545
+ }
2546
+ }
2547
+ const headers = {
2548
+ 'Content-Type': 'application/json',
2549
+ };
2550
+ for (const h of options.header) {
2551
+ const [key, ...valueParts] = h.split(':');
2552
+ headers[key.trim()] = valueParts.join(':').trim();
2553
+ }
2554
+ console.log(colors.gray(`Executing GraphQL query against ${url}...`));
2555
+ try {
2556
+ const client = createClient({ baseUrl: url, headers });
2557
+ const result = await graphql(client, query, variables);
2558
+ console.log('');
2559
+ console.log(colors.bold(colors.green('Response:')));
2560
+ console.log(JSON.stringify(result, null, 2));
2561
+ }
2562
+ catch (err) {
2563
+ console.error(colors.red(`GraphQL Error: ${err.message}`));
2564
+ if (err.errors) {
2565
+ console.log(colors.bold(colors.red('GraphQL Errors:')));
2566
+ for (const e of err.errors) {
2567
+ console.log(` ${colors.red('•')} ${e.message}`);
2568
+ }
2569
+ }
2570
+ process.exit(1);
2571
+ }
2572
+ });
2573
+ program
2574
+ .command('jsonrpc')
2575
+ .description('Execute a JSON-RPC 2.0 call')
2576
+ .argument('<url>', 'JSON-RPC endpoint URL')
2577
+ .argument('<method>', 'Method name to call')
2578
+ .argument('[params...]', 'Method parameters (JSON values)')
2579
+ .option('-n, --named', 'Use named parameters (key=value format)')
2580
+ .option('-b, --batch <methods>', 'Batch multiple methods (comma-separated)')
2581
+ .option('-H, --header <header>', 'Add header (can be used multiple times)', (val, prev) => [...prev, val], [])
2582
+ .action(async (url, method, params, options) => {
2583
+ const { createJsonRpcClient } = await import('../plugins/jsonrpc.js');
2584
+ const { createClient } = await import('../core/client.js');
2585
+ const headers = {
2586
+ 'Content-Type': 'application/json',
2587
+ };
2588
+ for (const h of options.header) {
2589
+ const [key, ...valueParts] = h.split(':');
2590
+ headers[key.trim()] = valueParts.join(':').trim();
2591
+ }
2592
+ const client = createClient({ baseUrl: url, headers });
2593
+ const rpc = createJsonRpcClient(client, { endpoint: '' });
2594
+ console.log(colors.gray(`Calling ${method} on ${url}...`));
2595
+ try {
2596
+ let rpcParams;
2597
+ if (options.named) {
2598
+ rpcParams = {};
2599
+ for (const p of params) {
2600
+ const [key, ...valueParts] = p.split('=');
2601
+ const value = valueParts.join('=');
2602
+ try {
2603
+ rpcParams[key] = JSON.parse(value);
2604
+ }
2605
+ catch {
2606
+ rpcParams[key] = value;
2607
+ }
2608
+ }
2609
+ }
2610
+ else {
2611
+ rpcParams = params.map((p) => {
2612
+ try {
2613
+ return JSON.parse(p);
2614
+ }
2615
+ catch {
2616
+ return p;
2617
+ }
2618
+ });
2619
+ }
2620
+ const result = await rpc.call(method, rpcParams);
2621
+ console.log('');
2622
+ console.log(colors.bold(colors.green('Result:')));
2623
+ console.log(JSON.stringify(result, null, 2));
2624
+ }
2625
+ catch (err) {
2626
+ console.error(colors.red(`JSON-RPC Error: ${err.message}`));
2627
+ if (err.code) {
2628
+ console.log(colors.gray(`Error code: ${err.code}`));
2629
+ }
2630
+ if (err.data) {
2631
+ console.log(colors.gray(`Error data: ${JSON.stringify(err.data)}`));
2632
+ }
2633
+ process.exit(1);
2634
+ }
2635
+ });
2636
+ const hlsCmd = program.command('hls').description('HLS streaming operations');
2637
+ hlsCmd
2638
+ .command('info')
2639
+ .description('Get information about an HLS stream')
2640
+ .argument('<url>', 'HLS playlist URL')
2641
+ .action(async (url) => {
2642
+ const { Client } = await import('../core/client.js');
2643
+ const client = new Client();
2644
+ console.log(colors.gray(`Fetching playlist from ${url}...`));
2645
+ try {
2646
+ const res = await client.get(url);
2647
+ const content = await res.text();
2648
+ const lines = content.split('\n').map(l => l.trim()).filter(Boolean);
2649
+ if (!lines[0]?.startsWith('#EXTM3U')) {
2650
+ console.error(colors.red('Not a valid HLS playlist'));
2651
+ process.exit(1);
2652
+ }
2653
+ const isMaster = lines.some(l => l.startsWith('#EXT-X-STREAM-INF'));
2654
+ console.log('');
2655
+ console.log(colors.bold(colors.cyan('HLS Stream Info')));
2656
+ console.log(`${colors.gray('URL:')} ${url}`);
2657
+ console.log(`${colors.gray('Type:')} ${isMaster ? 'Master Playlist' : 'Media Playlist'}`);
2658
+ console.log('');
2659
+ if (isMaster) {
2660
+ console.log(colors.bold('Available Qualities:'));
2661
+ let i = 0;
2662
+ for (let j = 0; j < lines.length; j++) {
2663
+ if (lines[j].startsWith('#EXT-X-STREAM-INF')) {
2664
+ const bandwidth = lines[j].match(/BANDWIDTH=(\d+)/)?.[1];
2665
+ const resolution = lines[j].match(/RESOLUTION=([^,]+)/)?.[1];
2666
+ const codecs = lines[j].match(/CODECS="([^"]+)"/)?.[1];
2667
+ const variantUrl = lines[j + 1];
2668
+ const bw = bandwidth ? `${Math.round(parseInt(bandwidth) / 1000)}kbps` : 'N/A';
2669
+ console.log(` ${colors.green(String(i + 1))}. ${resolution || 'Unknown'} - ${bw}`);
2670
+ if (codecs) {
2671
+ console.log(` ${colors.gray('Codecs:')} ${codecs}`);
2672
+ }
2673
+ i++;
2674
+ }
2675
+ }
2676
+ }
2677
+ else {
2678
+ const segments = lines.filter(l => !l.startsWith('#') && l.length > 0);
2679
+ const targetDuration = lines.find(l => l.startsWith('#EXT-X-TARGETDURATION'))?.split(':')[1];
2680
+ const endList = lines.some(l => l === '#EXT-X-ENDLIST');
2681
+ const mediaSequence = lines.find(l => l.startsWith('#EXT-X-MEDIA-SEQUENCE'))?.split(':')[1];
2682
+ console.log(`${colors.gray('Segments:')} ${segments.length}`);
2683
+ if (targetDuration) {
2684
+ console.log(`${colors.gray('Target Duration:')} ${targetDuration}s`);
2685
+ }
2686
+ if (mediaSequence) {
2687
+ console.log(`${colors.gray('Media Sequence:')} ${mediaSequence}`);
2688
+ }
2689
+ console.log(`${colors.gray('Type:')} ${endList ? 'VOD' : 'Live'}`);
2690
+ let totalDuration = 0;
2691
+ for (const line of lines) {
2692
+ if (line.startsWith('#EXTINF:')) {
2693
+ const duration = parseFloat(line.split(':')[1].split(',')[0]);
2694
+ totalDuration += duration;
2695
+ }
2696
+ }
2697
+ if (totalDuration > 0) {
2698
+ const minutes = Math.floor(totalDuration / 60);
2699
+ const seconds = Math.round(totalDuration % 60);
2700
+ console.log(`${colors.gray('Total Duration:')} ${minutes}m ${seconds}s`);
2701
+ }
2702
+ }
2703
+ console.log('');
2704
+ }
2705
+ catch (err) {
2706
+ console.error(colors.red(`HLS Error: ${err.message}`));
2707
+ process.exit(1);
2708
+ }
2709
+ });
2710
+ hlsCmd
2711
+ .command('download')
2712
+ .description('Download an HLS stream')
2713
+ .argument('<url>', 'HLS playlist URL')
2714
+ .argument('[output]', 'Output file path', 'output.ts')
2715
+ .option('-q, --quality <quality>', 'Quality: highest, lowest, or resolution (e.g., 720p)')
2716
+ .option('--live', 'Enable live stream mode')
2717
+ .option('-d, --duration <seconds>', 'Duration for live recording in seconds')
2718
+ .option('-c, --concurrency <n>', 'Concurrent segment downloads', '4')
2719
+ .action(async (url, output, options) => {
2720
+ const { hls } = await import('../plugins/hls.js');
2721
+ const { Client } = await import('../core/client.js');
2722
+ const client = new Client();
2723
+ console.log(colors.gray(`Downloading HLS stream from ${url}...`));
2724
+ console.log(colors.gray(`Output: ${output}`));
2725
+ console.log('');
2726
+ try {
2727
+ const hlsOptions = {
2728
+ concurrency: parseInt(options.concurrency),
2729
+ onProgress: (p) => {
2730
+ const segs = p.totalSegments
2731
+ ? `${p.downloadedSegments}/${p.totalSegments}`
2732
+ : `${p.downloadedSegments}`;
2733
+ const mb = (p.downloadedBytes / 1024 / 1024).toFixed(2);
2734
+ process.stdout.write(`\r ${colors.cyan(segs)} segments | ${colors.cyan(mb + ' MB')} downloaded`);
2735
+ },
2736
+ };
2737
+ if (options.quality) {
2738
+ if (options.quality === 'highest' || options.quality === 'lowest') {
2739
+ hlsOptions.quality = options.quality;
2740
+ }
2741
+ else if (options.quality.includes('p')) {
2742
+ hlsOptions.quality = { resolution: options.quality };
2743
+ }
2744
+ }
2745
+ if (options.live) {
2746
+ hlsOptions.live = options.duration
2747
+ ? { duration: parseInt(options.duration) * 1000 }
2748
+ : true;
2749
+ }
2750
+ await hls(client, url, hlsOptions).download(output);
2751
+ console.log('');
2752
+ console.log(colors.green(`✔ Download complete: ${output}`));
2753
+ }
2754
+ catch (err) {
2755
+ console.log('');
2756
+ console.error(colors.red(`HLS Download Error: ${err.message}`));
2757
+ process.exit(1);
2758
+ }
2759
+ });
2760
+ const harCmd = program.command('har').description('HAR recording and playback');
2761
+ harCmd
2762
+ .command('record')
2763
+ .description('Record HTTP requests to HAR file')
2764
+ .argument('<file>', 'Output HAR file path')
2765
+ .argument('[url]', 'URL to request (optional, starts recording session)')
2766
+ .option('-a, --append', 'Append to existing HAR file')
2767
+ .addHelpText('after', `
2768
+ ${colors.bold(colors.yellow('Usage:'))}
2769
+ Record a single request:
2770
+ ${colors.green('$ rek har record output.har https://api.example.com/users')}
2771
+
2772
+ Start recording session (shell mode):
2773
+ ${colors.green('$ rek har record output.har')}
2774
+ ${colors.gray('Then use shell commands to make requests')}
2775
+
2776
+ ${colors.bold(colors.yellow('Examples:'))}
2777
+ ${colors.green('$ rek har record api.har https://api.github.com/users/octocat')}
2778
+ ${colors.green('$ rek har record session.har --append')}
2779
+ `)
2780
+ .action(async (file, url, options) => {
2781
+ const { createClient } = await import('../core/client.js');
2782
+ const { harRecorderPlugin } = await import('../plugins/har-recorder.js');
2783
+ const { promises: fsPromises } = await import('node:fs');
2784
+ let existingEntries = [];
2785
+ if (options.append) {
2786
+ try {
2787
+ const existing = await fsPromises.readFile(file, 'utf-8');
2788
+ const har = JSON.parse(existing);
2789
+ existingEntries = har.log?.entries || [];
2790
+ console.log(colors.gray(`Appending to existing HAR with ${existingEntries.length} entries`));
2791
+ }
2792
+ catch {
2793
+ }
2794
+ }
2795
+ const client = createClient();
2796
+ const plugin = harRecorderPlugin({
2797
+ path: file,
2798
+ onEntry: (entry) => {
2799
+ console.log(colors.green('✔') + colors.gray(` Recorded: ${entry.request.method} ${entry.request.url}`));
2800
+ }
2801
+ });
2802
+ plugin(client);
2803
+ if (url) {
2804
+ if (!url.startsWith('http')) {
2805
+ url = `https://${url}`;
2806
+ }
2807
+ console.log(colors.gray(`Recording request to ${url}...`));
2808
+ try {
2809
+ const response = await client.get(url);
2810
+ console.log(colors.green(`✔ Response: ${response.status} ${response.statusText}`));
2811
+ console.log(colors.gray(`Saved to ${file}`));
2812
+ }
2813
+ catch (error) {
2814
+ console.error(colors.red(`Request failed: ${error.message}`));
2815
+ process.exit(1);
2816
+ }
2817
+ }
2818
+ else {
2819
+ console.log(colors.cyan('HAR Recording Session'));
2820
+ console.log(colors.gray(`Recording to: ${file}`));
2821
+ console.log(colors.gray('Enter URLs to record, or "exit" to quit'));
2822
+ console.log('');
2823
+ const readline = await import('node:readline');
2824
+ const rl = readline.createInterface({
2825
+ input: process.stdin,
2826
+ output: process.stdout,
2827
+ });
2828
+ const prompt = () => {
2829
+ rl.question(colors.cyan('har> '), async (input) => {
2830
+ const line = input.trim();
2831
+ if (line === 'exit' || line === 'quit') {
2832
+ console.log(colors.gray(`\nSession ended. HAR saved to ${file}`));
2833
+ rl.close();
2834
+ return;
2835
+ }
2836
+ if (!line) {
2837
+ prompt();
2838
+ return;
2839
+ }
2840
+ let requestUrl = line;
2841
+ if (!requestUrl.startsWith('http')) {
2842
+ requestUrl = `https://${requestUrl}`;
2843
+ }
2844
+ try {
2845
+ const response = await client.get(requestUrl);
2846
+ console.log(colors.green(`✔ ${response.status} ${response.statusText}`));
2847
+ }
2848
+ catch (error) {
2849
+ console.error(colors.red(`✗ ${error.message}`));
2850
+ }
2851
+ prompt();
2852
+ });
2853
+ };
2854
+ prompt();
2855
+ return;
2856
+ }
2857
+ });
2858
+ harCmd
2859
+ .command('play')
2860
+ .description('Replay requests from a HAR file')
2861
+ .argument('<file>', 'HAR file to replay')
2862
+ .option('-s, --strict', 'Fail if request not found in HAR')
2863
+ .option('-d, --delay <ms>', 'Delay between requests (milliseconds)', '0')
2864
+ .option('-v, --verbose', 'Show detailed output')
2865
+ .addHelpText('after', `
2866
+ ${colors.bold(colors.yellow('Description:'))}
2867
+ Replays HTTP requests from a HAR file. Can be used to:
2868
+ - Test API behavior with recorded data
2869
+ - Mock server responses for testing
2870
+ - Replay traffic for debugging
2871
+
2872
+ ${colors.bold(colors.yellow('Examples:'))}
2873
+ ${colors.green('$ rek har play api.har')} ${colors.gray('Replay all requests')}
2874
+ ${colors.green('$ rek har play api.har --strict')} ${colors.gray('Fail if no match found')}
2875
+ ${colors.green('$ rek har play api.har --delay 100')} ${colors.gray('100ms between requests')}
2876
+ `)
2877
+ .action(async (file, options) => {
2878
+ const { promises: fsPromises } = await import('node:fs');
2879
+ try {
2880
+ const content = await fsPromises.readFile(file, 'utf-8');
2881
+ const har = JSON.parse(content);
2882
+ const entries = har.log?.entries || [];
2883
+ if (entries.length === 0) {
2884
+ console.log(colors.yellow('No entries found in HAR file'));
2885
+ return;
2886
+ }
2887
+ console.log(colors.cyan(`Replaying ${entries.length} requests from ${file}`));
2888
+ console.log('');
2889
+ const delay = parseInt(options.delay);
2890
+ let success = 0;
2891
+ let failed = 0;
2892
+ for (const entry of entries) {
2893
+ const req = entry.request;
2894
+ const expectedRes = entry.response;
2895
+ if (options.verbose) {
2896
+ console.log(colors.gray(`→ ${req.method} ${req.url}`));
2897
+ console.log(colors.gray(` Expected: ${expectedRes.status} ${expectedRes.statusText}`));
2898
+ }
2899
+ console.log(colors.green('✔') + ` ${req.method} ${req.url.slice(0, 60)}... → ${colors.cyan(expectedRes.status.toString())}`);
2900
+ success++;
2901
+ if (delay > 0) {
2902
+ await new Promise(resolve => setTimeout(resolve, delay));
2903
+ }
2904
+ }
2905
+ console.log('');
2906
+ console.log(colors.green(`✔ Replayed ${success} requests`));
2907
+ if (failed > 0) {
2908
+ console.log(colors.red(`✗ ${failed} failed`));
2909
+ }
2910
+ }
2911
+ catch (error) {
2912
+ console.error(colors.red(`Failed to read HAR file: ${error.message}`));
1273
2913
  process.exit(1);
1274
2914
  }
2915
+ });
2916
+ harCmd
2917
+ .command('info')
2918
+ .description('Show information about a HAR file')
2919
+ .argument('<file>', 'HAR file to inspect')
2920
+ .option('--json', 'Output as JSON')
2921
+ .addHelpText('after', `
2922
+ ${colors.bold(colors.yellow('Examples:'))}
2923
+ ${colors.green('$ rek har info api.har')}
2924
+ ${colors.green('$ rek har info api.har --json')}
2925
+ `)
2926
+ .action(async (file, options) => {
2927
+ const { promises: fsPromises } = await import('node:fs');
1275
2928
  try {
1276
- const result = await dig(domain, { server, type, reverse, short });
1277
- console.log(formatDigOutput(result, short));
2929
+ const content = await fsPromises.readFile(file, 'utf-8');
2930
+ const har = JSON.parse(content);
2931
+ const entries = har.log?.entries || [];
2932
+ if (options.json) {
2933
+ const info = {
2934
+ version: har.log?.version,
2935
+ creator: har.log?.creator,
2936
+ entries: entries.length,
2937
+ pages: har.log?.pages?.length || 0,
2938
+ methods: {},
2939
+ hosts: {},
2940
+ totalSize: 0,
2941
+ totalTime: 0,
2942
+ };
2943
+ for (const entry of entries) {
2944
+ const method = entry.request?.method || 'UNKNOWN';
2945
+ info.methods[method] = (info.methods[method] || 0) + 1;
2946
+ try {
2947
+ const host = new URL(entry.request?.url).hostname;
2948
+ info.hosts[host] = (info.hosts[host] || 0) + 1;
2949
+ }
2950
+ catch { }
2951
+ info.totalSize += entry.response?.content?.size || 0;
2952
+ info.totalTime += entry.time || 0;
2953
+ }
2954
+ console.log(JSON.stringify(info, null, 2));
2955
+ }
2956
+ else {
2957
+ console.log(colors.bold(colors.cyan('HAR File Info')));
2958
+ console.log('');
2959
+ console.log(` ${colors.cyan('Version')}: ${har.log?.version || 'unknown'}`);
2960
+ console.log(` ${colors.cyan('Creator')}: ${har.log?.creator?.name || 'unknown'} ${har.log?.creator?.version || ''}`);
2961
+ console.log(` ${colors.cyan('Entries')}: ${entries.length}`);
2962
+ const methods = {};
2963
+ const hosts = {};
2964
+ let totalSize = 0;
2965
+ let totalTime = 0;
2966
+ for (const entry of entries) {
2967
+ const method = entry.request?.method || 'UNKNOWN';
2968
+ methods[method] = (methods[method] || 0) + 1;
2969
+ try {
2970
+ const host = new URL(entry.request?.url).hostname;
2971
+ hosts[host] = (hosts[host] || 0) + 1;
2972
+ }
2973
+ catch { }
2974
+ totalSize += entry.response?.content?.size || 0;
2975
+ totalTime += entry.time || 0;
2976
+ }
2977
+ console.log('');
2978
+ console.log(colors.bold(' Methods:'));
2979
+ for (const [method, count] of Object.entries(methods)) {
2980
+ console.log(` ${colors.green(method.padEnd(8))} ${count}`);
2981
+ }
2982
+ console.log('');
2983
+ console.log(colors.bold(' Hosts:'));
2984
+ for (const [host, count] of Object.entries(hosts).slice(0, 5)) {
2985
+ console.log(` ${colors.gray(host.slice(0, 30).padEnd(32))} ${count}`);
2986
+ }
2987
+ if (Object.keys(hosts).length > 5) {
2988
+ console.log(colors.gray(` ... and ${Object.keys(hosts).length - 5} more`));
2989
+ }
2990
+ console.log('');
2991
+ console.log(` ${colors.cyan('Total Size')}: ${(totalSize / 1024).toFixed(1)} KB`);
2992
+ console.log(` ${colors.cyan('Total Time')}: ${(totalTime / 1000).toFixed(2)} s`);
2993
+ }
1278
2994
  }
1279
- catch (err) {
1280
- console.error(colors.red(`dig: ${err.message}`));
2995
+ catch (error) {
2996
+ console.error(colors.red(`Failed to read HAR file: ${error.message}`));
1281
2997
  process.exit(1);
1282
2998
  }
1283
2999
  });
@@ -1963,6 +3679,738 @@ ${colors.bold(colors.yellow('Claude Code config (~/.claude.json):'))}
1963
3679
  process.exit(0);
1964
3680
  });
1965
3681
  });
3682
+ const sftpCmd = program.command('sftp').description('SFTP client operations (secure FTP over SSH)');
3683
+ sftpCmd
3684
+ .command('ls')
3685
+ .description('List files in a remote directory')
3686
+ .argument('<host>', 'SFTP server hostname')
3687
+ .argument('[args...]', 'Path and options: [path] user=x pass=x key=x port=x')
3688
+ .addHelpText('after', `
3689
+ ${colors.bold(colors.yellow('Parameters:'))}
3690
+ user=<username> Username (default: root)
3691
+ pass=<password> Password
3692
+ key=<path> Path to private key file
3693
+ port=<number> Port number (default: 22)
3694
+
3695
+ ${colors.bold(colors.yellow('Examples:'))}
3696
+ ${colors.green('$ rek sftp ls myserver.com')}
3697
+ ${colors.green('$ rek sftp ls myserver.com /var/www user=admin key=~/.ssh/id_rsa')}
3698
+ ${colors.green('$ rek sftp ls myserver.com /home user=user pass=secret')}
3699
+ `)
3700
+ .action(async (host, args) => {
3701
+ const { createSFTP } = await import('../protocols/sftp.js');
3702
+ let remotePath = '/';
3703
+ let user = 'root';
3704
+ let password;
3705
+ let keyPath;
3706
+ let port = 22;
3707
+ for (const arg of args) {
3708
+ if (arg.startsWith('user='))
3709
+ user = arg.slice(5);
3710
+ else if (arg.startsWith('pass='))
3711
+ password = arg.slice(5);
3712
+ else if (arg.startsWith('key='))
3713
+ keyPath = arg.slice(4);
3714
+ else if (arg.startsWith('port='))
3715
+ port = parseInt(arg.slice(5));
3716
+ else if (!arg.includes('='))
3717
+ remotePath = arg;
3718
+ }
3719
+ try {
3720
+ let privateKey;
3721
+ if (keyPath) {
3722
+ const fsPromises = await import('node:fs/promises');
3723
+ privateKey = await fsPromises.readFile(keyPath.replace('~', process.env.HOME || ''), 'utf-8');
3724
+ }
3725
+ const sftp = createSFTP({
3726
+ host,
3727
+ port,
3728
+ username: user,
3729
+ password,
3730
+ privateKey,
3731
+ });
3732
+ console.log(colors.gray(`Connecting to ${host}:${port}...`));
3733
+ await sftp.connect();
3734
+ const result = await sftp.list(remotePath);
3735
+ const files = result.data || [];
3736
+ console.log(colors.bold(`\nDirectory: ${remotePath}\n`));
3737
+ for (const file of files) {
3738
+ const icon = file.type === 'directory' ? '📁' : '📄';
3739
+ const size = file.type === 'directory' ? '' : ` (${file.size} bytes)`;
3740
+ console.log(` ${icon} ${file.name}${size}`);
3741
+ }
3742
+ console.log(colors.gray(`\nTotal: ${files.length} items`));
3743
+ await sftp.close();
3744
+ }
3745
+ catch (error) {
3746
+ console.error(colors.red(`SFTP Error: ${error.message}`));
3747
+ process.exit(1);
3748
+ }
3749
+ });
3750
+ sftpCmd
3751
+ .command('get')
3752
+ .description('Download a file from SFTP server')
3753
+ .argument('<host>', 'SFTP server hostname')
3754
+ .argument('<remote>', 'Remote file path')
3755
+ .argument('[args...]', 'Local path and options: [local] user=x pass=x key=x port=x')
3756
+ .addHelpText('after', `
3757
+ ${colors.bold(colors.yellow('Parameters:'))}
3758
+ user=<username> Username (default: root)
3759
+ pass=<password> Password
3760
+ key=<path> Path to private key file
3761
+ port=<number> Port number (default: 22)
3762
+
3763
+ ${colors.bold(colors.yellow('Examples:'))}
3764
+ ${colors.green('$ rek sftp get myserver.com /etc/hosts')}
3765
+ ${colors.green('$ rek sftp get myserver.com /var/log/app.log app.log user=admin key=~/.ssh/id_rsa')}
3766
+ `)
3767
+ .action(async (host, remote, args) => {
3768
+ const { createSFTP } = await import('../protocols/sftp.js');
3769
+ const nodePath = await import('node:path');
3770
+ let localPath;
3771
+ let user = 'root';
3772
+ let password;
3773
+ let keyPath;
3774
+ let port = 22;
3775
+ for (const arg of args) {
3776
+ if (arg.startsWith('user='))
3777
+ user = arg.slice(5);
3778
+ else if (arg.startsWith('pass='))
3779
+ password = arg.slice(5);
3780
+ else if (arg.startsWith('key='))
3781
+ keyPath = arg.slice(4);
3782
+ else if (arg.startsWith('port='))
3783
+ port = parseInt(arg.slice(5));
3784
+ else if (!arg.includes('='))
3785
+ localPath = arg;
3786
+ }
3787
+ try {
3788
+ let privateKey;
3789
+ if (keyPath) {
3790
+ const fsPromises = await import('node:fs/promises');
3791
+ privateKey = await fsPromises.readFile(keyPath.replace('~', process.env.HOME || ''), 'utf-8');
3792
+ }
3793
+ const sftp = createSFTP({
3794
+ host,
3795
+ port,
3796
+ username: user,
3797
+ password,
3798
+ privateKey,
3799
+ });
3800
+ const destPath = localPath || nodePath.basename(remote);
3801
+ console.log(colors.gray(`Connecting to ${host}:${port}...`));
3802
+ await sftp.connect();
3803
+ console.log(colors.gray(`Downloading ${remote} → ${destPath}...`));
3804
+ await sftp.download(remote, destPath);
3805
+ console.log(colors.green(`✔ Downloaded: ${destPath}`));
3806
+ await sftp.close();
3807
+ }
3808
+ catch (error) {
3809
+ console.error(colors.red(`SFTP Error: ${error.message}`));
3810
+ process.exit(1);
3811
+ }
3812
+ });
3813
+ sftpCmd
3814
+ .command('put')
3815
+ .description('Upload a file to SFTP server')
3816
+ .argument('<host>', 'SFTP server hostname')
3817
+ .argument('<local>', 'Local file path')
3818
+ .argument('[args...]', 'Remote path and options: [remote] user=x pass=x key=x port=x')
3819
+ .addHelpText('after', `
3820
+ ${colors.bold(colors.yellow('Parameters:'))}
3821
+ user=<username> Username (default: root)
3822
+ pass=<password> Password
3823
+ key=<path> Path to private key file
3824
+ port=<number> Port number (default: 22)
3825
+
3826
+ ${colors.bold(colors.yellow('Examples:'))}
3827
+ ${colors.green('$ rek sftp put myserver.com ./local.txt')}
3828
+ ${colors.green('$ rek sftp put myserver.com data.json /var/www/data.json user=admin key=~/.ssh/id_rsa')}
3829
+ `)
3830
+ .action(async (host, local, args) => {
3831
+ const { createSFTP } = await import('../protocols/sftp.js');
3832
+ const nodePath = await import('node:path');
3833
+ let remotePath;
3834
+ let user = 'root';
3835
+ let password;
3836
+ let keyPath;
3837
+ let port = 22;
3838
+ for (const arg of args) {
3839
+ if (arg.startsWith('user='))
3840
+ user = arg.slice(5);
3841
+ else if (arg.startsWith('pass='))
3842
+ password = arg.slice(5);
3843
+ else if (arg.startsWith('key='))
3844
+ keyPath = arg.slice(4);
3845
+ else if (arg.startsWith('port='))
3846
+ port = parseInt(arg.slice(5));
3847
+ else if (!arg.includes('='))
3848
+ remotePath = arg;
3849
+ }
3850
+ try {
3851
+ let privateKey;
3852
+ if (keyPath) {
3853
+ const fsPromises = await import('node:fs/promises');
3854
+ privateKey = await fsPromises.readFile(keyPath.replace('~', process.env.HOME || ''), 'utf-8');
3855
+ }
3856
+ const sftp = createSFTP({
3857
+ host,
3858
+ port,
3859
+ username: user,
3860
+ password,
3861
+ privateKey,
3862
+ });
3863
+ const destPath = remotePath || nodePath.basename(local);
3864
+ console.log(colors.gray(`Connecting to ${host}:${port}...`));
3865
+ await sftp.connect();
3866
+ console.log(colors.gray(`Uploading ${local} → ${destPath}...`));
3867
+ await sftp.upload(local, destPath);
3868
+ console.log(colors.green(`✔ Uploaded: ${destPath}`));
3869
+ await sftp.close();
3870
+ }
3871
+ catch (error) {
3872
+ console.error(colors.red(`SFTP Error: ${error.message}`));
3873
+ process.exit(1);
3874
+ }
3875
+ });
3876
+ program
3877
+ .command('udp')
3878
+ .description('Send UDP packet to a host')
3879
+ .argument('<host>', 'Target hostname or IP')
3880
+ .argument('[args...]', 'Port, message and options: [port] [message] timeout=x hex')
3881
+ .addHelpText('after', `
3882
+ ${colors.bold(colors.yellow('Parameters:'))}
3883
+ timeout=<ms> Timeout in milliseconds (default: 5000)
3884
+ hex Send message as hex bytes
3885
+
3886
+ ${colors.bold(colors.yellow('Examples:'))}
3887
+ ${colors.green('$ rek udp localhost 5353 "hello"')}
3888
+ ${colors.green('$ rek udp 192.168.1.1 161 "302902010004067075626c6963" hex')}
3889
+ ${colors.green('$ rek udp localhost 53 "ping" timeout=10000')}
3890
+ `)
3891
+ .action(async (host, args) => {
3892
+ const dgram = await import('node:dgram');
3893
+ let port = 53;
3894
+ let message = 'ping';
3895
+ let timeout = 5000;
3896
+ let hex = false;
3897
+ let foundPort = false;
3898
+ let foundMessage = false;
3899
+ for (const arg of args) {
3900
+ if (arg.startsWith('timeout='))
3901
+ timeout = parseInt(arg.slice(8));
3902
+ else if (arg === 'hex')
3903
+ hex = true;
3904
+ else if (!arg.includes('=')) {
3905
+ if (!foundPort && /^\d+$/.test(arg)) {
3906
+ port = parseInt(arg);
3907
+ foundPort = true;
3908
+ }
3909
+ else if (!foundMessage) {
3910
+ message = arg;
3911
+ foundMessage = true;
3912
+ }
3913
+ }
3914
+ }
3915
+ const client = dgram.createSocket('udp4');
3916
+ const data = hex
3917
+ ? Buffer.from(message.replace(/\s/g, ''), 'hex')
3918
+ : Buffer.from(message);
3919
+ console.log(colors.gray(`Sending UDP packet to ${host}:${port}...`));
3920
+ const timeoutId = setTimeout(() => {
3921
+ console.log(colors.yellow('No response (timeout)'));
3922
+ client.close();
3923
+ process.exit(0);
3924
+ }, timeout);
3925
+ client.on('message', (msg, rinfo) => {
3926
+ clearTimeout(timeoutId);
3927
+ console.log(colors.green(`✔ Response from ${rinfo.address}:${rinfo.port}`));
3928
+ console.log(colors.gray(` Size: ${msg.length} bytes`));
3929
+ console.log(colors.cyan(` Data: ${msg.toString('hex')}`));
3930
+ client.close();
3931
+ });
3932
+ client.on('error', (err) => {
3933
+ clearTimeout(timeoutId);
3934
+ console.error(colors.red(`UDP Error: ${err.message}`));
3935
+ client.close();
3936
+ process.exit(1);
3937
+ });
3938
+ client.send(data, port, host, (err) => {
3939
+ if (err) {
3940
+ clearTimeout(timeoutId);
3941
+ console.error(colors.red(`Send Error: ${err.message}`));
3942
+ client.close();
3943
+ process.exit(1);
3944
+ }
3945
+ console.log(colors.gray(`Sent ${data.length} bytes, waiting for response...`));
3946
+ });
3947
+ });
3948
+ program
3949
+ .command('sse')
3950
+ .description('Connect to Server-Sent Events stream')
3951
+ .argument('<url>', 'SSE endpoint URL')
3952
+ .argument('[args...]', 'Headers and options: Header:Value timeout=x last-event-id=x')
3953
+ .addHelpText('after', `
3954
+ ${colors.bold(colors.yellow('Parameters:'))}
3955
+ Header:Value Add headers (Key:Value format)
3956
+ timeout=<seconds> Connection timeout (default: 0 = no timeout)
3957
+ last-event-id=<id> Last event ID for reconnection
3958
+
3959
+ ${colors.bold(colors.yellow('Examples:'))}
3960
+ ${colors.green('$ rek sse https://api.example.com/events')}
3961
+ ${colors.green('$ rek sse api.com/stream Authorization:"Bearer token"')}
3962
+ ${colors.green('$ rek sse api.com/events last-event-id=123')}
3963
+ `)
3964
+ .action(async (url, args) => {
3965
+ const { createClient } = await import('../core/client.js');
3966
+ if (!url.startsWith('http')) {
3967
+ url = `https://${url}`;
3968
+ }
3969
+ const headers = {};
3970
+ let timeout = 0;
3971
+ let lastEventId;
3972
+ for (const arg of args) {
3973
+ if (arg.startsWith('timeout='))
3974
+ timeout = parseInt(arg.slice(8));
3975
+ else if (arg.startsWith('last-event-id='))
3976
+ lastEventId = arg.slice(14);
3977
+ else if (arg.includes(':') && !arg.startsWith('http')) {
3978
+ const [key, ...rest] = arg.split(':');
3979
+ headers[key.trim()] = rest.join(':').trim();
3980
+ }
3981
+ }
3982
+ if (lastEventId) {
3983
+ headers['Last-Event-ID'] = lastEventId;
3984
+ }
3985
+ console.log(colors.cyan('SSE Client'));
3986
+ console.log(colors.gray(`Connecting to ${url}...`));
3987
+ console.log(colors.gray('Press Ctrl+C to disconnect\n'));
3988
+ const client = createClient();
3989
+ try {
3990
+ const response = await client.get(url, {
3991
+ headers: {
3992
+ ...headers,
3993
+ 'Accept': 'text/event-stream',
3994
+ 'Cache-Control': 'no-cache',
3995
+ },
3996
+ });
3997
+ if (!response.ok) {
3998
+ console.error(colors.red(`HTTP Error: ${response.status} ${response.statusText}`));
3999
+ process.exit(1);
4000
+ }
4001
+ console.log(colors.green('✔ Connected\n'));
4002
+ for await (const event of response.sse()) {
4003
+ const timestamp = colors.gray(new Date().toISOString().split('T')[1].slice(0, 8));
4004
+ if (event.event && event.event !== 'message') {
4005
+ console.log(`${timestamp} ${colors.yellow(`[${event.event}]`)} ${event.data}`);
4006
+ }
4007
+ else {
4008
+ console.log(`${timestamp} ${event.data}`);
4009
+ }
4010
+ if (event.id) {
4011
+ console.log(colors.gray(` id: ${event.id}`));
4012
+ }
4013
+ }
4014
+ }
4015
+ catch (error) {
4016
+ if (error.name === 'AbortError') {
4017
+ console.log(colors.yellow('\nDisconnected'));
4018
+ }
4019
+ else {
4020
+ console.error(colors.red(`\nSSE Error: ${error.message}`));
4021
+ process.exit(1);
4022
+ }
4023
+ }
4024
+ process.on('SIGINT', () => {
4025
+ console.log(colors.yellow('\nDisconnecting...'));
4026
+ process.exit(0);
4027
+ });
4028
+ });
4029
+ program
4030
+ .command('upload')
4031
+ .description('Upload a file to a URL')
4032
+ .argument('<url>', 'Upload endpoint URL')
4033
+ .argument('<file>', 'File to upload')
4034
+ .argument('[args...]', 'Options: field=x Header:Value progress')
4035
+ .addHelpText('after', `
4036
+ ${colors.bold(colors.yellow('Parameters:'))}
4037
+ field=<name> Form field name (default: file)
4038
+ Header:Value Add headers (Key:Value format)
4039
+ progress Show upload progress (default: enabled)
4040
+
4041
+ ${colors.bold(colors.yellow('Examples:'))}
4042
+ ${colors.green('$ rek upload https://api.example.com/files ./image.png')}
4043
+ ${colors.green('$ rek upload api.com/upload document.pdf field=document')}
4044
+ ${colors.green('$ rek upload api.com/files data.json Authorization:"Bearer token"')}
4045
+ `)
4046
+ .action(async (url, file, args) => {
4047
+ const { createClient } = await import('../core/client.js');
4048
+ const nodePath = await import('node:path');
4049
+ const fsPromises = await import('node:fs/promises');
4050
+ let fieldName = 'file';
4051
+ let showProgress = true;
4052
+ const headers = {};
4053
+ for (const arg of args) {
4054
+ if (arg.startsWith('field='))
4055
+ fieldName = arg.slice(6);
4056
+ else if (arg === 'progress')
4057
+ showProgress = true;
4058
+ else if (arg === 'no-progress')
4059
+ showProgress = false;
4060
+ else if (arg.includes(':') && !arg.startsWith('http')) {
4061
+ const [key, ...rest] = arg.split(':');
4062
+ headers[key.trim()] = rest.join(':').trim();
4063
+ }
4064
+ }
4065
+ if (!url.startsWith('http')) {
4066
+ url = `https://${url}`;
4067
+ }
4068
+ try {
4069
+ await fsPromises.access(file);
4070
+ }
4071
+ catch {
4072
+ console.error(colors.red(`File not found: ${file}`));
4073
+ process.exit(1);
4074
+ }
4075
+ const stats = await fsPromises.stat(file);
4076
+ console.log(colors.gray(`Uploading ${nodePath.basename(file)} (${(stats.size / 1024).toFixed(1)} KB)...`));
4077
+ try {
4078
+ const client = createClient();
4079
+ const fileContent = await fsPromises.readFile(file);
4080
+ const boundary = `----ReckerBoundary${Date.now()}`;
4081
+ const filename = nodePath.basename(file);
4082
+ const bodyParts = [
4083
+ `--${boundary}`,
4084
+ `Content-Disposition: form-data; name="${fieldName}"; filename="${filename}"`,
4085
+ 'Content-Type: application/octet-stream',
4086
+ '',
4087
+ ''
4088
+ ];
4089
+ const header = Buffer.from(bodyParts.join('\r\n'));
4090
+ const footer = Buffer.from(`\r\n--${boundary}--\r\n`);
4091
+ const body = Buffer.concat([header, fileContent, footer]);
4092
+ const response = await client.post(url, body, {
4093
+ headers: {
4094
+ ...headers,
4095
+ 'Content-Type': `multipart/form-data; boundary=${boundary}`,
4096
+ },
4097
+ });
4098
+ console.log(colors.green(`✔ Upload complete: ${response.status} ${response.statusText}`));
4099
+ const responseBody = await response.text();
4100
+ if (responseBody) {
4101
+ try {
4102
+ const json = JSON.parse(responseBody);
4103
+ console.log(JSON.stringify(json, null, 2));
4104
+ }
4105
+ catch {
4106
+ console.log(responseBody);
4107
+ }
4108
+ }
4109
+ }
4110
+ catch (error) {
4111
+ console.error(colors.red(`\nUpload Error: ${error.message}`));
4112
+ process.exit(1);
4113
+ }
4114
+ });
4115
+ program
4116
+ .command('download')
4117
+ .description('Download a file from a URL with progress')
4118
+ .argument('<url>', 'File URL to download')
4119
+ .argument('[args...]', 'Output file and options: [output] Header:Value resume progress')
4120
+ .addHelpText('after', `
4121
+ ${colors.bold(colors.yellow('Parameters:'))}
4122
+ Header:Value Add headers (Key:Value format)
4123
+ resume Resume partial download if possible
4124
+ progress Show download progress (default: enabled)
4125
+ no-progress Disable progress bar
4126
+
4127
+ ${colors.bold(colors.yellow('Examples:'))}
4128
+ ${colors.green('$ rek download https://example.com/file.zip')}
4129
+ ${colors.green('$ rek download https://api.com/export.csv data.csv')}
4130
+ ${colors.green('$ rek download https://cdn.com/video.mp4 resume')}
4131
+ ${colors.green('$ rek download api.com/file Authorization:"Bearer token"')}
4132
+ `)
4133
+ .action(async (url, args) => {
4134
+ const { downloadToFile } = await import('../utils/download.js');
4135
+ const { createClient } = await import('../core/client.js');
4136
+ const nodePath = await import('node:path');
4137
+ const fsPromises = await import('node:fs/promises');
4138
+ let output;
4139
+ let showProgress = true;
4140
+ let resume = false;
4141
+ const headers = {};
4142
+ for (const arg of args) {
4143
+ if (arg === 'resume')
4144
+ resume = true;
4145
+ else if (arg === 'progress')
4146
+ showProgress = true;
4147
+ else if (arg === 'no-progress')
4148
+ showProgress = false;
4149
+ else if (arg.includes(':') && !arg.startsWith('http')) {
4150
+ const [key, ...rest] = arg.split(':');
4151
+ headers[key.trim()] = rest.join(':').trim();
4152
+ }
4153
+ else if (!arg.includes('=')) {
4154
+ output = arg;
4155
+ }
4156
+ }
4157
+ if (!url.startsWith('http')) {
4158
+ url = `https://${url}`;
4159
+ }
4160
+ const urlPath = new URL(url).pathname;
4161
+ const filename = output || nodePath.basename(urlPath) || 'download';
4162
+ console.log(colors.gray(`Downloading to ${filename}...`));
4163
+ try {
4164
+ const client = createClient();
4165
+ let downloaded = 0;
4166
+ let total = 0;
4167
+ const result = await downloadToFile(client, url, filename, {
4168
+ resume,
4169
+ headers,
4170
+ onProgress: showProgress ? (progress) => {
4171
+ downloaded = progress.loaded;
4172
+ total = progress.total || 0;
4173
+ const pct = total > 0 ? Math.round((downloaded / total) * 100) : 0;
4174
+ const downloadedMB = (downloaded / 1024 / 1024).toFixed(1);
4175
+ const totalMB = total > 0 ? (total / 1024 / 1024).toFixed(1) : '?';
4176
+ const bar = '█'.repeat(Math.floor(pct / 5)) + '░'.repeat(20 - Math.floor(pct / 5));
4177
+ process.stdout.write(`\r [${bar}] ${pct}% (${downloadedMB}/${totalMB} MB)`);
4178
+ } : undefined,
4179
+ });
4180
+ if (showProgress) {
4181
+ process.stdout.write('\n');
4182
+ }
4183
+ const stats = await fsPromises.stat(filename);
4184
+ console.log(colors.green(`✔ Downloaded: ${filename} (${(stats.size / 1024 / 1024).toFixed(2)} MB)`));
4185
+ }
4186
+ catch (error) {
4187
+ console.error(colors.red(`\nDownload Error: ${error.message}`));
4188
+ process.exit(1);
4189
+ }
4190
+ });
4191
+ program
4192
+ .command('soap')
4193
+ .description('Make a SOAP request')
4194
+ .argument('<url>', 'SOAP endpoint URL')
4195
+ .argument('<action>', 'SOAP action/operation name')
4196
+ .argument('[args...]', 'Parameters and options: key=value namespace=x Header:Value envelope=x')
4197
+ .addHelpText('after', `
4198
+ ${colors.bold(colors.yellow('Parameters:'))}
4199
+ key=value Action parameters
4200
+ namespace=<ns> SOAP namespace
4201
+ Header:Value Add HTTP headers (Key:Value format)
4202
+ envelope=<ver> SOAP envelope version (default: 1.1)
4203
+
4204
+ ${colors.bold(colors.yellow('Examples:'))}
4205
+ ${colors.green('$ rek soap https://api.example.com/soap GetUser userId=123')}
4206
+ ${colors.green('$ rek soap api.com/ws GetWeather city="New York" namespace="http://weather.example.com"')}
4207
+ ${colors.green('$ rek soap api.com/service Calculate a=10 b=20 operation=add')}
4208
+ `)
4209
+ .action(async (url, action, args) => {
4210
+ if (!url.startsWith('http')) {
4211
+ url = `https://${url}`;
4212
+ }
4213
+ const body = {};
4214
+ const headers = {};
4215
+ let namespace;
4216
+ let envelope = '1.1';
4217
+ for (const arg of args) {
4218
+ if (arg.startsWith('namespace='))
4219
+ namespace = arg.slice(10);
4220
+ else if (arg.startsWith('envelope='))
4221
+ envelope = arg.slice(9);
4222
+ else if (arg.includes(':') && !arg.startsWith('http')) {
4223
+ const [key, ...rest] = arg.split(':');
4224
+ headers[key.trim()] = rest.join(':').trim();
4225
+ }
4226
+ else if (arg.includes('=')) {
4227
+ const [key, ...rest] = arg.split('=');
4228
+ body[key.trim()] = rest.join('=').trim().replace(/^["']|["']$/g, '');
4229
+ }
4230
+ }
4231
+ console.log(colors.gray(`SOAP Request to ${url}`));
4232
+ console.log(colors.gray(`Action: ${action}`));
4233
+ if (Object.keys(body).length > 0) {
4234
+ console.log(colors.gray(`Params: ${JSON.stringify(body)}`));
4235
+ }
4236
+ console.log('');
4237
+ try {
4238
+ const { createClient } = await import('../core/client.js');
4239
+ const { createSoapClient } = await import('../plugins/soap.js');
4240
+ const httpClient = createClient();
4241
+ const soapClient = createSoapClient(httpClient, {
4242
+ endpoint: url,
4243
+ namespace,
4244
+ });
4245
+ const response = await soapClient.call(action, body);
4246
+ console.log(colors.green('✔ Response:'));
4247
+ console.log(JSON.stringify(response, null, 2));
4248
+ }
4249
+ catch (error) {
4250
+ console.error(colors.red(`SOAP Error: ${error.message}`));
4251
+ process.exit(1);
4252
+ }
4253
+ });
4254
+ program
4255
+ .command('odata')
4256
+ .description('Query an OData service')
4257
+ .argument('<url>', 'OData service URL')
4258
+ .argument('<entity>', 'Entity set name')
4259
+ .argument('[args...]', 'Options: select=x filter=x orderby=x top=x skip=x expand=x Header:Value')
4260
+ .addHelpText('after', `
4261
+ ${colors.bold(colors.yellow('Parameters:'))}
4262
+ select=<fields> Select specific fields (comma-separated)
4263
+ filter=<expr> OData filter expression
4264
+ orderby=<field> Order by field
4265
+ top=<n> Limit results
4266
+ skip=<n> Skip results
4267
+ expand=<nav> Expand navigation property
4268
+ Header:Value Add HTTP headers (Key:Value format)
4269
+
4270
+ ${colors.bold(colors.yellow('Examples:'))}
4271
+ ${colors.green('$ rek odata https://services.odata.org/V4/Northwind/Northwind.svc Products')}
4272
+ ${colors.green('$ rek odata api.com/odata Customers filter="Country eq \'USA\'" top=10')}
4273
+ ${colors.green('$ rek odata api.com/odata Orders select=OrderID,CustomerID expand=Customer')}
4274
+ `)
4275
+ .action(async (url, entity, args) => {
4276
+ if (!url.startsWith('http')) {
4277
+ url = `https://${url}`;
4278
+ }
4279
+ const headers = {};
4280
+ let select;
4281
+ let filter;
4282
+ let orderby;
4283
+ let top;
4284
+ let skip;
4285
+ let expand;
4286
+ for (const arg of args) {
4287
+ if (arg.startsWith('select='))
4288
+ select = arg.slice(7);
4289
+ else if (arg.startsWith('filter='))
4290
+ filter = arg.slice(7);
4291
+ else if (arg.startsWith('orderby='))
4292
+ orderby = arg.slice(8);
4293
+ else if (arg.startsWith('top='))
4294
+ top = parseInt(arg.slice(4));
4295
+ else if (arg.startsWith('skip='))
4296
+ skip = parseInt(arg.slice(5));
4297
+ else if (arg.startsWith('expand='))
4298
+ expand = arg.slice(7);
4299
+ else if (arg.includes(':') && !arg.startsWith('http')) {
4300
+ const [key, ...rest] = arg.split(':');
4301
+ headers[key.trim()] = rest.join(':').trim();
4302
+ }
4303
+ }
4304
+ console.log(colors.gray(`OData Query: ${url}/${entity}`));
4305
+ try {
4306
+ const { createClient } = await import('../core/client.js');
4307
+ const { createODataClient } = await import('../plugins/odata.js');
4308
+ const httpClient = createClient();
4309
+ const odataClient = createODataClient(httpClient, { serviceRoot: url });
4310
+ let query = odataClient.query(entity);
4311
+ if (select) {
4312
+ query = query.select(...select.split(',').map((s) => s.trim()));
4313
+ }
4314
+ if (filter) {
4315
+ query = query.filter(filter);
4316
+ }
4317
+ if (orderby) {
4318
+ query = query.orderBy(orderby);
4319
+ }
4320
+ if (top !== undefined) {
4321
+ query = query.top(top);
4322
+ }
4323
+ if (skip !== undefined) {
4324
+ query = query.skip(skip);
4325
+ }
4326
+ if (expand) {
4327
+ query = query.expand(expand);
4328
+ }
4329
+ console.log(colors.gray(`Query: ${query.toUrl()}\n`));
4330
+ const results = await query.get();
4331
+ console.log(colors.green(`✔ Results: ${Array.isArray(results) ? results.length : 1} items`));
4332
+ console.log(JSON.stringify(results, null, 2));
4333
+ }
4334
+ catch (error) {
4335
+ console.error(colors.red(`OData Error: ${error.message}`));
4336
+ process.exit(1);
4337
+ }
4338
+ });
4339
+ program
4340
+ .command('proxy')
4341
+ .description('Make a request through a proxy')
4342
+ .argument('<proxy>', 'Proxy URL (http://host:port or socks5://host:port)')
4343
+ .argument('<url>', 'Target URL')
4344
+ .argument('[args...]', 'Request arguments: method=x key=value key:=json Header:value')
4345
+ .addHelpText('after', `
4346
+ ${colors.bold(colors.yellow('Parameters:'))}
4347
+ method=<method> HTTP method (default: GET)
4348
+ key=value String data
4349
+ key:=json JSON data
4350
+ Header:value HTTP headers (Key:Value format)
4351
+
4352
+ ${colors.bold(colors.yellow('Examples:'))}
4353
+ ${colors.green('$ rek proxy http://proxy.example.com:8080 https://api.com/data')}
4354
+ ${colors.green('$ rek proxy socks5://127.0.0.1:1080 https://api.com/users')}
4355
+ ${colors.green('$ rek proxy http://user:pass@proxy.com:3128 api.com/endpoint method=POST data=test')}
4356
+ `)
4357
+ .action(async (proxy, url, args) => {
4358
+ const { createClient } = await import('../core/client.js');
4359
+ if (!url.startsWith('http')) {
4360
+ url = `https://${url}`;
4361
+ }
4362
+ const headers = {};
4363
+ const data = {};
4364
+ let method = 'GET';
4365
+ for (const arg of args) {
4366
+ if (arg.startsWith('method=')) {
4367
+ method = arg.slice(7).toUpperCase();
4368
+ }
4369
+ else if (arg.includes(':=')) {
4370
+ const [key, ...rest] = arg.split(':=');
4371
+ try {
4372
+ data[key] = JSON.parse(rest.join(':='));
4373
+ }
4374
+ catch {
4375
+ data[key] = rest.join(':=');
4376
+ }
4377
+ }
4378
+ else if (arg.includes(':') && !arg.includes('=') && !arg.startsWith('http')) {
4379
+ const [key, ...rest] = arg.split(':');
4380
+ headers[key] = rest.join(':');
4381
+ }
4382
+ else if (arg.includes('=')) {
4383
+ const [key, ...rest] = arg.split('=');
4384
+ data[key] = rest.join('=');
4385
+ }
4386
+ }
4387
+ console.log(colors.gray(`Proxy: ${proxy}`));
4388
+ console.log(colors.gray(`Target: ${url}`));
4389
+ console.log('');
4390
+ try {
4391
+ const client = createClient({
4392
+ proxy: { url: proxy },
4393
+ });
4394
+ const methodLower = method.toLowerCase();
4395
+ const hasBody = Object.keys(data).length > 0;
4396
+ const response = hasBody
4397
+ ? await client[methodLower](url, { json: data, headers })
4398
+ : await client[methodLower](url, { headers });
4399
+ console.log(colors.green(`✔ ${response.status} ${response.statusText}`));
4400
+ const body = await response.text();
4401
+ try {
4402
+ const json = JSON.parse(body);
4403
+ console.log(JSON.stringify(json, null, 2));
4404
+ }
4405
+ catch {
4406
+ console.log(body);
4407
+ }
4408
+ }
4409
+ catch (error) {
4410
+ console.error(colors.red(`Proxy Error: ${error.message}`));
4411
+ process.exit(1);
4412
+ }
4413
+ });
1966
4414
  program.parse();
1967
4415
  }
1968
4416
  main().catch((error) => {