File size: 6,629 Bytes
da2e594
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
#!/usr/bin/env npx tsx
/**
 * Test script for enhanced node type suggestions
 * Tests the NodeSimilarityService to ensure it provides helpful suggestions
 * for unknown or incorrectly typed nodes in workflows.
 */

import { createDatabaseAdapter } from '../database/database-adapter';
import { NodeRepository } from '../database/node-repository';
import { NodeSimilarityService } from '../services/node-similarity-service';
import { WorkflowValidator } from '../services/workflow-validator';
import { EnhancedConfigValidator } from '../services/enhanced-config-validator';
import { WorkflowAutoFixer } from '../services/workflow-auto-fixer';
import { Logger } from '../utils/logger';
import path from 'path';

const logger = new Logger({ prefix: '[NodeSuggestions Test]' });
const console = {
  log: (msg: string) => logger.info(msg),
  error: (msg: string, err?: any) => logger.error(msg, err)
};

async function testNodeSimilarity() {
  console.log('🔍 Testing Enhanced Node Type Suggestions\n');

  // Initialize database and services
  const dbPath = path.join(process.cwd(), 'data/nodes.db');
  const db = await createDatabaseAdapter(dbPath);
  const repository = new NodeRepository(db);
  const similarityService = new NodeSimilarityService(repository);
  const validator = new WorkflowValidator(repository, EnhancedConfigValidator);

  // Test cases with various invalid node types
  const testCases = [
    // Case variations
    { invalid: 'HttpRequest', expected: 'nodes-base.httpRequest' },
    { invalid: 'HTTPRequest', expected: 'nodes-base.httpRequest' },
    { invalid: 'Webhook', expected: 'nodes-base.webhook' },
    { invalid: 'WebHook', expected: 'nodes-base.webhook' },

    // Missing package prefix
    { invalid: 'slack', expected: 'nodes-base.slack' },
    { invalid: 'googleSheets', expected: 'nodes-base.googleSheets' },
    { invalid: 'telegram', expected: 'nodes-base.telegram' },

    // Common typos
    { invalid: 'htpRequest', expected: 'nodes-base.httpRequest' },
    { invalid: 'webook', expected: 'nodes-base.webhook' },
    { invalid: 'slak', expected: 'nodes-base.slack' },

    // Partial names
    { invalid: 'http', expected: 'nodes-base.httpRequest' },
    { invalid: 'sheet', expected: 'nodes-base.googleSheets' },

    // Wrong package prefix
    { invalid: 'nodes-base.openai', expected: 'nodes-langchain.openAi' },
    { invalid: 'n8n-nodes-base.httpRequest', expected: 'nodes-base.httpRequest' },

    // Complete unknowns
    { invalid: 'foobar', expected: null },
    { invalid: 'xyz123', expected: null },
  ];

  console.log('Testing individual node type suggestions:');
  console.log('=' .repeat(60));

  for (const testCase of testCases) {
    const suggestions = await similarityService.findSimilarNodes(testCase.invalid, 3);

    console.log(`\n❌ Invalid type: "${testCase.invalid}"`);

    if (suggestions.length > 0) {
      console.log('✨ Suggestions:');
      for (const suggestion of suggestions) {
        const confidence = Math.round(suggestion.confidence * 100);
        const marker = suggestion.nodeType === testCase.expected ? '✅' : '  ';
        console.log(
          `${marker} ${suggestion.nodeType} (${confidence}% match) - ${suggestion.reason}`
        );

        if (suggestion.confidence >= 0.9) {
          console.log('   💡 Can be auto-fixed!');
        }
      }

      // Check if expected match was found
      if (testCase.expected) {
        const found = suggestions.some(s => s.nodeType === testCase.expected);
        if (!found) {
          console.log(`   ⚠️  Expected "${testCase.expected}" was not suggested!`);
        }
      }
    } else {
      console.log('   No suggestions found');
      if (testCase.expected) {
        console.log(`   ⚠️  Expected "${testCase.expected}" was not suggested!`);
      }
    }
  }

  console.log('\n' + '='.repeat(60));
  console.log('\n📋 Testing workflow validation with unknown nodes:');
  console.log('='.repeat(60));

  // Test with a sample workflow
  const testWorkflow = {
    id: 'test-workflow',
    name: 'Test Workflow',
    nodes: [
      {
        id: '1',
        name: 'Start',
        type: 'nodes-base.manualTrigger',
        position: [100, 100] as [number, number],
        parameters: {},
        typeVersion: 1
      },
      {
        id: '2',
        name: 'HTTP Request',
        type: 'HTTPRequest', // Wrong capitalization
        position: [300, 100] as [number, number],
        parameters: {},
        typeVersion: 1
      },
      {
        id: '3',
        name: 'Slack',
        type: 'slack', // Missing prefix
        position: [500, 100] as [number, number],
        parameters: {},
        typeVersion: 1
      },
      {
        id: '4',
        name: 'Unknown',
        type: 'foobar', // Completely unknown
        position: [700, 100] as [number, number],
        parameters: {},
        typeVersion: 1
      }
    ],
    connections: {
      'Start': {
        main: [[{ node: 'HTTP Request', type: 'main', index: 0 }]]
      },
      'HTTP Request': {
        main: [[{ node: 'Slack', type: 'main', index: 0 }]]
      },
      'Slack': {
        main: [[{ node: 'Unknown', type: 'main', index: 0 }]]
      }
    },
    settings: {}
  };

  const validationResult = await validator.validateWorkflow(testWorkflow as any, {
    validateNodes: true,
    validateConnections: false,
    validateExpressions: false,
    profile: 'runtime'
  });

  console.log('\nValidation Results:');
  for (const error of validationResult.errors) {
    if (error.message?.includes('Unknown node type:')) {
      console.log(`\n🔴 ${error.nodeName}: ${error.message}`);
    }
  }

  console.log('\n' + '='.repeat(60));
  console.log('\n🔧 Testing AutoFixer with node type corrections:');
  console.log('='.repeat(60));

  const autoFixer = new WorkflowAutoFixer(repository);
  const fixResult = await autoFixer.generateFixes(
    testWorkflow as any,
    validationResult,
    [],
    {
      applyFixes: false,
      fixTypes: ['node-type-correction'],
      confidenceThreshold: 'high'
    }
  );

  if (fixResult.fixes.length > 0) {
    console.log('\n✅ Auto-fixable issues found:');
    for (const fix of fixResult.fixes) {
      console.log(`   • ${fix.description}`);
    }
    console.log(`\nSummary: ${fixResult.summary}`);
  } else {
    console.log('\n❌ No auto-fixable node type issues found (only high-confidence fixes are applied)');
  }

  console.log('\n' + '='.repeat(60));
  console.log('\n✨ Test complete!');
}

// Run the test
testNodeSimilarity().catch(error => {
  console.error('Test failed:', error);
  process.exit(1);
});