Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 | /**
* JavaScript Parser Test
*
* This file contains a simple test to demonstrate how to use the JavaScript parser
* with Tree-sitter to extract code entities and relationships from JavaScript/TypeScript code.
* It can be run with: node src/services/parsing/javascriptParser.test.js
*/
import { TreeSitterManager } from "./treeSitterManager.js";
import { parseJavaScript, nodeToObject } from "./javascript.parser.js";
import logger from "../../utils/logger.js";
/**
* Run tests for the JavaScript parser
*/
async function testJavaScriptParser() {
try {
// Initialize the TreeSitterManager
const manager = new TreeSitterManager();
// Load grammar for JavaScript and TypeScript
await manager.initializeGrammars(["javascript", "typescript"]);
// Check what languages were loaded
const loadedLanguages = manager.getLoadedLanguages();
logger.info(`Loaded languages: ${loadedLanguages.join(", ")}`);
// Create a sample JavaScript file with relationships
const javaScriptCode = `
/**
* This is a sample JavaScript file with different code constructs that demonstrate relationships
*/
// Import statements (import relationships)
import React from 'react';
import { useState, useEffect } from 'react';
// Parent class (inheritance relationship)
class Parent {
constructor() {
this.name = 'Parent';
}
parentMethod() {
return this.name;
}
}
// Child class (extends relationship)
class Child extends Parent {
constructor() {
super();
this.name = 'Child';
}
// Override method (parent-child relationship)
parentMethod() {
// Call to super (function call relationship)
return super.parentMethod() + ' -> Child';
}
// Child method (no relationship to parent)
childMethod() {
// Variable reference relationship
console.log(this.name);
return 'Child only';
}
}
// Function declaration (parent entity)
function processData(data) {
// Nested function (parent-child relationship)
function validate(input) {
return input && typeof input === 'object';
}
// Function call relationship
if (validate(data)) {
// Variable reference relationship
return data.value;
}
return null;
}
// Variable declarations
const config = {
enabled: true,
timeout: 1000
};
// Function that references variables (variable reference relationship)
function getConfig() {
// Reference to the config variable
return config.enabled ? config.timeout : 0;
}
// Export statement (export relationship)
export { Parent, Child, processData, getConfig };
`;
// Parse the JavaScript code using Tree-sitter
if (manager.hasLanguage("javascript")) {
const parser = manager.getParserForLanguage("javascript");
const tree = parser.parse(javaScriptCode);
logger.info("JavaScript AST root node type:", tree.rootNode.type);
// Extract code entities and relationships from the AST
const { entities, relationships } = parseJavaScript(
tree.rootNode,
javaScriptCode
);
// Print the extracted entities
logger.info(`Extracted ${entities.length} code entities:`);
entities.forEach((entity, index) => {
logger.info(`Entity ${index + 1}:`);
logger.info(` Type: ${entity.entity_type}`);
logger.info(` ID: ${entity.id}`);
logger.info(` Name: ${entity.name}`);
logger.info(` Lines: ${entity.start_line}-${entity.end_line}`);
logger.info(` Language: ${entity.language}`);
// Print custom metadata if available
if (Object.keys(entity.custom_metadata).length > 0) {
logger.info(" Custom Metadata:", entity.custom_metadata);
}
// Print a condensed version of the raw content (first 40 chars)
const contentPreview = entity.raw_content
.substring(0, 40)
.replace(/\n/g, "\\n");
logger.info(
` Content: ${contentPreview}${
entity.raw_content.length > 40 ? "..." : ""
}`
);
logger.info("---");
});
// Print the extracted relationships
logger.info(`\nExtracted ${relationships.length} code relationships:`);
relationships.forEach((rel, index) => {
logger.info(`Relationship ${index + 1}:`);
logger.info(` Type: ${rel.relationship_type}`);
logger.info(` Source Entity ID: ${rel.source_entity_id}`);
logger.info(
` Target Entity ID: ${rel.target_entity_id || "None (external)"}`
);
logger.info(` Target Symbol Name: ${rel.target_symbol_name}`);
// Print custom metadata if available
if (Object.keys(rel.custom_metadata).length > 0) {
logger.info(" Custom Metadata:", rel.custom_metadata);
}
logger.info("---");
});
// Analyze specific relationship types
const relationshipsByType = relationships.reduce((acc, rel) => {
acc[rel.relationship_type] = (acc[rel.relationship_type] || 0) + 1;
return acc;
}, {});
logger.info("\nRelationship Types Summary:");
for (const [type, count] of Object.entries(relationshipsByType)) {
logger.info(` ${type}: ${count}`);
}
}
// TypeScript example with interfaces and implementation
const typeScriptCode = `
/**
* This is a sample TypeScript file demonstrating interfaces and implementations
*/
// Interface declaration
interface Vehicle {
start(): void;
stop(): void;
}
// Extended interface (interface extension relationship)
interface Car extends Vehicle {
drive(distance: number): void;
}
// Class implementing interfaces (implements relationship)
class Sedan implements Car {
constructor(private model: string) {}
// Implementing interface methods
start() {
console.log(\`Starting \${this.model}\`);
}
stop() {
console.log(\`Stopping \${this.model}\`);
}
drive(distance: number) {
console.log(\`Driving \${this.model} for \${distance} miles\`);
}
}
// Function using the class (function call relationships)
function testDrive(car: Car) {
car.start();
car.drive(100);
car.stop();
}
// Create an instance and test it
const myCar = new Sedan("Toyota");
testDrive(myCar);
export { Vehicle, Car, Sedan, testDrive };
`;
// If TypeScript is available, parse TypeScript code
if (manager.hasLanguage("typescript")) {
const tsParser = manager.getParserForLanguage("typescript");
const tsTree = tsParser.parse(typeScriptCode);
logger.info("\n\nTypeScript AST root node type:", tsTree.rootNode.type);
// Extract code entities and relationships from the AST
const { entities: tsEntities, relationships: tsRelationships } =
parseJavaScript(tsTree.rootNode, typeScriptCode);
// Print the extracted TypeScript entities
logger.info(`\nExtracted ${tsEntities.length} TypeScript code entities:`);
tsEntities.forEach((entity, index) => {
logger.info(`Entity ${index + 1}:`);
logger.info(` Type: ${entity.entity_type}`);
logger.info(` ID: ${entity.id}`);
logger.info(` Name: ${entity.name}`);
logger.info(` Lines: ${entity.start_line}-${entity.end_line}`);
logger.info(` Language: ${entity.language}`);
// Print a condensed version of the raw content (first 40 chars)
const contentPreview = entity.raw_content
.substring(0, 40)
.replace(/\n/g, "\\n");
logger.info(
` Content: ${contentPreview}${
entity.raw_content.length > 40 ? "..." : ""
}`
);
logger.info("---");
});
// Print the extracted TypeScript relationships
logger.info(
`\nExtracted ${tsRelationships.length} TypeScript code relationships:`
);
tsRelationships.forEach((rel, index) => {
logger.info(`Relationship ${index + 1}:`);
logger.info(` Type: ${rel.relationship_type}`);
logger.info(` Source Entity ID: ${rel.source_entity_id}`);
logger.info(
` Target Entity ID: ${rel.target_entity_id || "None (external)"}`
);
logger.info(` Target Symbol Name: ${rel.target_symbol_name}`);
// Print custom metadata if available
if (Object.keys(rel.custom_metadata).length > 0) {
logger.info(" Custom Metadata:", rel.custom_metadata);
}
logger.info("---");
});
// Analyze TypeScript specific relationship types
const tsRelationshipsByType = tsRelationships.reduce((acc, rel) => {
acc[rel.relationship_type] = (acc[rel.relationship_type] || 0) + 1;
return acc;
}, {});
logger.info("\nTypeScript Relationship Types Summary:");
for (const [type, count] of Object.entries(tsRelationshipsByType)) {
logger.info(` ${type}: ${count}`);
}
// Show TypeScript-specific relationships
logger.info("\nTypeScript Interface and Implementation Relationships:");
tsRelationships
.filter(
(rel) =>
rel.relationship_type === "EXTENDS_INTERFACE" ||
rel.relationship_type === "IMPLEMENTS_INTERFACE"
)
.forEach((rel, index) => {
logger.info(` ${rel.relationship_type}: ${rel.target_symbol_name}`);
});
} else {
logger.info(
"TypeScript parser not available. Skipping TypeScript example."
);
}
logger.info("JavaScript parser tests completed successfully");
} catch (error) {
logger.error(`JavaScript parser test failed: ${error.message}`, {
error: error.stack,
});
}
}
// Run the tests
testJavaScriptParser().catch((err) => {
logger.error("Unhandled error in JavaScript parser test", {
error: err.stack,
});
process.exit(1);
});
|