### Install Bevel TypeScript Client Source: https://github.com/bevel-software/bevel-ts-client/blob/main/README.md This command installs the Bevel TypeScript client library using npm. Ensure you have Node.js and npm installed on your system. ```bash npm install @bevel-software/bevel-ts-client ``` -------------------------------- ### Bash: Build Bevel TS Client from Source Source: https://github.com/bevel-software/bevel-ts-client/blob/main/README.md Instructions for cloning the Bevel TS Client repository, installing dependencies, and building the library from source using npm commands. ```bash git clone https://github.com/your-org/bevel-ts-client.git cd bevel-ts-client npm install npm run build ``` -------------------------------- ### Analyze Project and Get Codebase Stats (TypeScript) Source: https://github.com/bevel-software/bevel-ts-client/blob/main/README.md Shows how to analyze a project using the Bevel client, including checking if it's already analyzed, performing the analysis (optionally with an LLM type), and retrieving codebase statistics. This requires a valid project path. ```typescript import { BevelClient, LLMType } from '@bevel-software/bevel-ts-client'; // Initialize with your Bevel server URL const client = new BevelClient('http://localhost:1645'); // Example: Analyze a project and get its structure async function analyzeAndExploreProject(projectPath: string) { // Check if project is already analyzed const isAnalyzed = await client.project.isProjectAnalyzed(projectPath); if (!isAnalyzed) { console.log('Analyzing project...'); await client.project.analyzeProject(projectPath, LLMType.OPENAI); console.log('Analysis complete'); } // Get project stats const stats = await client.project.getCodebaseStats(projectPath); console.log(`Project stats: ${stats.files.total} files, ${stats.linesOfCode.total} lines of code`); // Get the full graph structure const graph = await client.graph.getGraph(projectPath); return graph; } ``` -------------------------------- ### ChatApi: Stream AI Code Explanations with TypeScript Source: https://context7.com/bevel-software/bevel-ts-client/llms.txt Interact with Bevel's AI chat API to get explanations for code. Supports streaming responses via async generators for real-time processing and non-streaming requests to collect all chunks at once. Handles multi-turn conversations. ```typescript import { ChatMessageRequestDto, ChatCompletionUserMessageParamDto, ChatCompletionSystemMessageParamDto, ChatCompletionChunk } from '@bevel-software/bevel-ts-client'; // Prepare chat messages const chatRequest: ChatMessageRequestDto = { messages: [ { role: 'system', content: 'You are a helpful assistant that explains code.' } as ChatCompletionSystemMessageParamDto, { role: 'user', content: 'Explain what the PaymentProcessor.processPayment function does and how it handles errors.' } as ChatCompletionUserMessageParamDto ] }; // Stream chat responses with async generator console.log('AI Response (streaming):'); for await (const chunk of client.chat.streamChatMessage(projectPath, chatRequest)) { // Process each chunk as it arrives if (chunk.choices && chunk.choices[0]?.delta?.content) { process.stdout.write(chunk.choices[0].delta.content); } // Check token usage (only in final chunk) if (chunk.usage) { console.log(` Tokens used: ${chunk.usage.total_tokens} (${chunk.usage.prompt_tokens} prompt + ${chunk.usage.completion_tokens} completion)`); } } // Or collect all chunks at once (non-streaming) const allChunks = await client.chat.processChatMessage(projectPath, chatRequest); const fullResponse = allChunks .map(chunk => chunk.choices[0]?.delta?.content || '') .join(''); console.log('Full AI Response:', fullResponse); // Multi-turn conversation const conversationRequest: ChatMessageRequestDto = { messages: [ { role: 'system', content: 'You are a code review assistant.' } as ChatCompletionSystemMessageParamDto, { role: 'user', content: 'What are the security concerns in the authentication flow?' } as ChatCompletionUserMessageParamDto, { role: 'assistant', content: 'The main security concerns include...' } as any, { role: 'user', content: 'How can we improve the JWT token validation?' } as ChatCompletionUserMessageParamDto ] }; const conversationChunks = await client.chat.processChatMessage(projectPath, conversationRequest); console.log('Conversation response:', conversationChunks); ``` -------------------------------- ### NodeApi: Get, Find, Count, and Save Code Entities in TypeScript Source: https://context7.com/bevel-software/bevel-ts-client/llms.txt This snippet demonstrates how to interact with code entities using the NodeApi in TypeScript. It covers retrieving all nodes, finding specific nodes by name, getting nodes by ID, counting nodes of specific types, checking for node existence, retrieving nodes with business context, and creating/saving custom nodes. It utilizes the '@bevel-software/bevel-ts-client' library. ```typescript import { NodeType, Node } from '@bevel-software/bevel-ts-client'; // Get all nodes in the project const allNodes = await client.nodes.getNodes(projectPath); console.log(`Total nodes: ${allNodes.length}`); // Find a specific function by name const authFunction = await client.nodes.findNodeByName( projectPath, 'AuthService.authenticate', '/home/user/my-project/src/services/AuthService.ts', 42 // optional line number ); console.log(`Found: ${authFunction.simpleName} at ${authFunction.filePath}:${authFunction.codeLocation.start.line}`); // Get node by ID const node = await client.nodes.getNode(projectPath, authFunction.id); console.log(`Code signature: ${node.nodeSignature}`); console.log(`Description: ${node.description}`); // Count specific node types const functionCount = await client.nodes.countFunctions(projectPath); console.log(`Functions in project: ${functionCount}`); // Check if node exists const exists = await client.nodes.contains(projectPath, 'PaymentProcessor.processPayment'); console.log(`Payment processor exists: ${exists}`); // Get all nodes with business context descriptions const nodesWithContext = await client.nodes.getNodesWithBusinessContext(projectPath); nodesWithContext.forEach(node => { console.log(`${node.displayName} (${node.filePath}:${node.startLine})`); console.log(` ${node.description}`); }); // Create and save a custom node const customNode: Node = { id: 'custom.node.id', simpleName: 'CustomUtility', nodeType: NodeType.Function, description: 'Custom utility function', inboundConnectionVersion: '1', outboundConnectionVersion: '1', definingNodeName: 'CustomUtility', filePath: '/home/user/my-project/src/utils/custom.ts', codeLocation: { start: { line: 10, column: 0 }, end: { line: 20, column: 1 } }, nameLocation: { start: { line: 10, column: 9 }, end: { line: 10, column: 22 } }, codeHash: 'abc123', nodeSignature: 'function CustomUtility()' }; await client.nodes.saveNode(projectPath, customNode); ``` -------------------------------- ### Get All Nodes in a Project (TypeScript) Source: https://github.com/bevel-software/bevel-ts-client/blob/main/README.md Retrieves all nodes (code entities like classes, functions, variables) within a specified project path. This is useful for understanding the components of a codebase. ```typescript // Get all nodes in a project const nodes = await client.nodes.getNodes('/path/to/project'); ``` -------------------------------- ### ConnectionsApi: Navigate Code Relationships in TypeScript Source: https://context7.com/bevel-software/bevel-ts-client/llms.txt This snippet illustrates how to use the ConnectionsApi in TypeScript to navigate relationships between code entities. It covers finding incoming and outgoing connections for a node, retrieving connections of a specific type (e.g., USES, INHERITS_FROM), finding connections between two specific nodes, and getting all connections involving a particular node. It relies on the '@bevel-software/bevel-ts-client' library. ```typescript import { ConnectionType } from '@bevel-software/bevel-ts-client'; // Find all connections to a specific node (who calls this function?) const incomingConnections = await client.connections.findConnectionsTo( projectPath, 'PaymentService.processPayment' ); console.log(`Functions calling processPayment: ${incomingConnections.length}`); incomingConnections.forEach(conn => { console.log(` ${conn.sourceNodeName} -> ${conn.targetNodeName} (${conn.connectionType})`); console.log(` at ${conn.filePath}:${conn.location.start.line}`); }); // Find all connections from a node (what does this function call?) const outgoingConnections = await client.connections.findConnectionsFrom( projectPath, 'OrderController.createOrder' ); console.log(`Dependencies: ${outgoingConnections.length}`); // Get all USES relationships const usesConnections = await client.connections.getAllConnectionsOfType( projectPath, ConnectionType.USES ); console.log(`Total USES relationships: ${usesConnections.length}`); // Find inheritance relationships const inheritanceConnections = await client.connections.findConnectionsFromOfType( projectPath, 'BaseController', ConnectionType.INHERITS_FROM ); console.log(`Classes inheriting from BaseController: ${inheritanceConnections.length}`); // Find specific connection between two nodes const connections = await client.connections.findConnections( projectPath, 'UserService.getUser', 'DatabaseAdapter.query' ); if (connections.length > 0) { console.log(`UserService.getUser calls DatabaseAdapter.query at:`); connections.forEach(c => console.log(` ${c.filePath}:${c.location.start.line}`)); } // Get all connections involving a node (both incoming and outgoing) const allRelated = await client.connections.getAllConnectionsContaining( projectPath, 'AuthMiddleware.verifyToken' ); console.log(`Total relationships involving AuthMiddleware: ${allRelated.length}`); ``` -------------------------------- ### Get Business Context for a Function (TypeScript) Source: https://github.com/bevel-software/bevel-ts-client/blob/main/README.md Retrieves AI-generated business context for a specific function within a project. Requires specifying the project path, function name, and an LLM type for generation. ```typescript // Generate business context for a specific function const businessContext = await client.businessContext.getBusinessContext( '/path/to/project', 'PaymentProcessor.processPayment', LLMType.OPENAI ); ``` -------------------------------- ### Initialize and Check Bevel Server Status (TypeScript) Source: https://github.com/bevel-software/bevel-ts-client/blob/main/README.md Demonstrates how to initialize the BevelClient and check if the Bevel server is online. This requires the Bevel server to be running and accessible via the provided URL. ```typescript import { BevelClient, LLMType } from '@bevel-software/bevel-ts-client'; // Initialize with your Bevel server URL const client = new BevelClient('http://localhost:1645'); // Example: Check if the server is alive async function checkServerStatus() { try { const isAlive = await client.server.isAlive(); console.log(`Bevel server is ${isAlive ? 'online' : 'offline'}`); return isAlive; } catch (error) { console.error('Error checking Bevel server status:', error); return false; } } ``` -------------------------------- ### TypeScript: Analyze and Manage Bevel Projects Source: https://github.com/bevel-software/bevel-ts-client/blob/main/README.md Perform project analysis, check analysis status, and retrieve codebase statistics using the Bevel TS Client. Requires the client to be initialized. ```typescript const isAnalyzed = await client.project.isProjectAnalyzed('/path/to/project'); await client.project.analyzeProject( '/path/to/project', LLMType.OPENAI, null, // optional file to add null, // optional file to delete '/src/models/User.ts' // optional file to update ); const stats = await client.project.getCodebaseStats('/path/to/project'); ``` -------------------------------- ### Initialize Bevel Client Source: https://context7.com/bevel-software/bevel-ts-client/llms.txt Initializes the Bevel client to connect to a Bevel server, supporting local and authenticated connections with custom configurations like timeouts and headers. It also includes a check for server status. ```typescript import { BevelClient, LLMType } from '@bevel-software/bevel-ts-client'; // Connect to local Bevel server (default port 1645) const client = new BevelClient('http://localhost:1645'); // Connect to custom server with authentication const authenticatedClient = new BevelClient('http://bevel.company.com:8080', { timeout: 30000, headers: { 'X-Custom-Header': 'value' } }); authenticatedClient.setAuthToken('your-auth-token', 'Bearer'); // Check server status try { const isAlive = await client.server.isAlive(); console.log(`Server status: ${isAlive ? 'online' : 'offline'}`); } catch (error) { console.error('Failed to connect to Bevel server:', error); process.exit(1); } ``` -------------------------------- ### Manage Projects with ProjectApi Source: https://context7.com/bevel-software/bevel-ts-client/llms.txt Analyzes projects, retrieves codebase statistics, and updates analysis when files change. It checks if a project is already analyzed, initiates new analysis, and provides detailed statistics including file counts, lines of code, and generated descriptions. The project model can also be downloaded as a stream. ```typescript const projectPath = '/home/user/my-project'; // Check if project has been analyzed const isAnalyzed = await client.project.isProjectAnalyzed(projectPath); console.log(`Project analyzed: ${isAnalyzed}`); // Analyze project for the first time if (!isAnalyzed) { console.log('Starting project analysis...'); await client.project.analyzeProject(projectPath); console.log('Analysis complete'); } // Update analysis when a file changes await client.project.analyzeProject( projectPath, null, // fileToAdd null, // fileToDelete '/home/user/my-project/src/services/PaymentService.ts' // fileToUpdate ); // Get comprehensive codebase statistics const stats = await client.project.getCodebaseStats(projectPath); console.log(`Project Statistics: Files: ${stats.files.total} Lines of Code: ${stats.linesOfCode.total} Main Language: ${stats.linesOfCode.mainLanguage} Functions: ${stats.functions.total} Business Context Generated: ${stats.descriptionsGenerated.current} (${stats.descriptionsGenerated.percentage}%)`); // Download project model as stream const modelStream = await client.project.downloadModel(projectPath); // Process stream as needed ``` -------------------------------- ### TypeScript: Configure Bevel Client Connection Source: https://github.com/bevel-software/bevel-ts-client/blob/main/README.md Initialize the BevelClient to connect to a custom Bevel server URL, optionally setting an authentication token and advanced Axios options like timeout and custom headers. ```typescript const client = new BevelClient('http://your-bevel-server:8080'); ``` ```typescript const client = new BevelClient('http://localhost:1645'); client.setAuthToken('your-auth-token'); ``` ```typescript const client = new BevelClient('http://localhost:1645', { timeout: 30000, headers: { 'X-Custom-Header': 'value' } }); ``` -------------------------------- ### ServerApi: Health Checks for Bevel Server Availability with TypeScript Source: https://context7.com/bevel-software/bevel-ts-client/llms.txt Verify the availability and responsiveness of the Bevel server before initiating API calls. Provides a simple `isAlive` check and a robust `waitForServer` function with retry logic for safe application startup. ```typescript // Simple health check const serverAlive = await client.server.isAlive(); if (!serverAlive) { throw new Error('Bevel server is not responding'); } // Health check with retry logic async function waitForServer(maxRetries = 5, delayMs = 2000): Promise { for (let i = 0; i < maxRetries; i++) { try { const alive = await client.server.isAlive(); if (alive) { console.log('Bevel server is ready'); return true; } } catch (error) { console.log(`Attempt ${i + 1}/${maxRetries} failed, retrying...`); } await new Promise(resolve => setTimeout(resolve, delayMs)); } console.error('Bevel server did not respond after maximum retries'); return false; } // Use in application startup if (await waitForServer()) { console.log('Starting application...'); // Proceed with application logic } else { console.error('Cannot start application: Bevel server unavailable'); process.exit(1); } ``` -------------------------------- ### Generate Sequence Diagram (TypeScript) Source: https://github.com/bevel-software/bevel-ts-client/blob/main/README.md Generates a sequence diagram for a given function within a project. The output includes mermaid.js content for rendering and detailed function information. ```typescript // Generate a sequence diagram starting from a specific function const sequenceDiagram = await client.diagrams.generateSequenceDiagram( '/path/to/project', 'AuthService.authenticate' ); // The returned data contains both mermaid.js content and detailed function information console.log(sequenceDiagram.mmdContent); // Use with mermaid.js to render the diagram ``` -------------------------------- ### CodeLensApi: Retrieve File-Level Code Intelligence with TypeScript Source: https://context7.com/bevel-software/bevel-ts-client/llms.txt Fetch CodeLens information for a given file, providing inline code metrics and business context. The retrieved data includes function details, descriptions, and associated functional requirements, which can be used to generate IDE annotations. ```typescript // Get CodeLens data for a specific file const codeLensInfo = await client.codeLens.getCodeLensInfo( projectPath, '/home/user/my-project/src/controllers/OrderController.ts' ); console.log(`CodeLens data for OrderController (${codeLensInfo.infos.length} functions):`); codeLensInfo.infos.forEach(info => { console.log(` Function at line ${info.line}: `); console.log(` Name: ${info.node.displayName}`); console.log(` Type: ${info.node.nodeType}`); console.log(` Description: ${info.node.description || 'None'}`); if (info.functionalRequirements.length > 0) { console.log(` Functional Requirements (${info.functionalRequirements.length}):`); info.functionalRequirements.forEach(req => { console.log(` - [${req.type}] ${req.requirement}`); console.log(` ${req.description}`); console.log(` Source: ${req.sourceNode}`); console.log(` Last modified: ${new Date(req.modificationInfo.lastModified).toLocaleString()}`); }); } else { console.log(' No functional requirements'); } }); // Use CodeLens data to generate IDE annotations codeLensInfo.infos.forEach(info => { const annotation = `💡 ${info.node.description || 'No description'} | ${info.functionalRequirements.length} requirements`; console.log(`Line ${info.line}: ${annotation}`); }); ``` -------------------------------- ### Generate Sequence Diagram with Bevel TS Client Source: https://context7.com/bevel-software/bevel-ts-client/llms.txt Generates sequence diagrams to visualize code execution flow. It can include manual connections to define custom relationships between functions. The output includes Mermaid.js content for rendering, detailed function information, display names mapping, and toggle functions for expandable elements. ```typescript import { ManualConnection } from '@bevel-software/bevel-ts-client'; // Generate sequence diagram starting from a function const diagram = await client.diagrams.generateSequenceDiagram( projectPath, 'OrderService.createOrder' ); // Access Mermaid.js content for rendering console.log('Mermaid Diagram:'); console.log(diagram.mmdContent); // Access detailed function information for (const [funcName, funcInfo] of Object.entries(diagram.functionInfos)) { console.log(`Function: ${funcInfo.name}`); console.log(` Location: ${funcInfo.filePath}:${funcInfo.line}:${funcInfo.column}`); console.log(` Code:\n${funcInfo.code}`); } // Get display names mapping console.log('Display Names:', diagram.displayNames); // Check toggle functions (functions that can be expanded) for (const [funcName, toggleFuncs] of Object.entries(diagram.toggleFunctions)) { console.log(`${funcName} can expand to ${toggleFuncs.length} additional functions`); toggleFuncs.forEach(tf => { console.log(` - ${tf.displayName} at ${tf.filePath}:${tf.location.start.line}`); }); } // Generate diagram with manual connections to show custom relationships const manualConnections: ManualConnection[] = [ { sourceNodeName: 'OrderService.createOrder', targetNodeName: 'PaymentService.charge' }, { sourceNodeName: 'PaymentService.charge', targetNodeName: 'EmailService.sendReceipt' } ]; const customDiagram = await client.diagrams.generateSequenceDiagram( projectPath, 'OrderService.createOrder', manualConnections ); console.log(customDiagram.mmdContent); ``` -------------------------------- ### Extract and Manage Business Context with Bevel TS Client Source: https://context7.com/bevel-software/bevel-ts-client/llms.txt Extracts and manages AI-powered business context descriptions for code entities. It allows fetching existing context, generating context for the entire codebase, and saving custom descriptions. This feature helps in understanding the business logic behind code functions. ```typescript import { DescriptionDto } from '@bevel-software/bevel-ts-client'; // Get existing business context for a function const context = await client.businessContext.getBusinessContext( projectPath, 'PaymentProcessor.processPayment' ); console.log(`Business Context:\n${context}`); // Get business context without using graph (faster for simple cases) const contextNoGraph = await client.businessContext.getBusinessContextWithoutGraph( projectPath, 'PaymentProcessor.processPayment' ); console.log(`Simple Context:\n${contextNoGraph}`); // Generate business context for all functions in the project console.log('Generating business context for entire codebase...'); await client.businessContext.generateAllBusinessContext(projectPath); console.log('Generation complete'); // Save custom business context const customDescription: DescriptionDto = { description: 'Processes credit card and PayPal payments with fraud detection. Integrates with Stripe and PayPal APIs. Handles payment retry logic for failed transactions. Logs all payment attempts to audit trail. Sends email notifications on success or failure.' }; await client.businessContext.saveBusinessContext( projectPath, 'PaymentProcessor.processPayment', customDescription ); // Verify the saved context const updatedContext = await client.businessContext.getBusinessContext( projectPath, 'PaymentProcessor.processPayment' ); console.log(`Updated Context:\n${updatedContext}`); ``` -------------------------------- ### Access Code Knowledge Graph with GraphApi Source: https://context7.com/bevel-software/bevel-ts-client/llms.txt Retrieves the complete code knowledge graph for a project, including all nodes and connections. It allows access to individual nodes by ID, filtering connections by type (e.g., 'USES'), and extracting functional requirements. A lightweight graph structure can also be obtained. ```typescript // Get the complete graph for a project const graph = await client.graph.getGraph(projectPath); console.log(`Graph contains ${Object.keys(graph.nodes).length} nodes`); console.log(`Graph contains ${graph.connections.length} connections`); console.log(`App version: ${graph.appVersion}`); // Access individual nodes by ID for (const [nodeId, node] of Object.entries(graph.nodes)) { console.log(`${node.displayName} (${node.nodeType}): ${node.description || 'No description'}`); } // Analyze connections const usesConnections = graph.connections.filter(c => c.connectionType === 'USES'); console.log(`Found ${usesConnections.length} USES relationships`); // Get functional requirements extracted from the code console.log(`Functional Requirements (${graph.functionalRequirements.length}):`); graph.functionalRequirements.forEach((req, idx) => { console.log(` ${idx + 1}. ${req}`); }); // Get lightweight graph structure (nodes and connections without full details) const structure = await client.graph.getGraphStructure(projectPath); structure.nodes.forEach(node => { console.log(`${node.name} (${node.nodeType}) -> ${node.connections.length} connections`); }); ``` -------------------------------- ### Save Custom Business Context for a Node (TypeScript) Source: https://github.com/bevel-software/bevel-ts-client/blob/main/README.md Saves custom business context information for a specific code entity node. This allows developers to annotate code with their own descriptions or domain knowledge. ```typescript // Save custom business context for a node await client.businessContext.saveBusinessContext( '/path/to/project', 'PaymentProcessor.processPayment', { description: 'Handles payment processing with multiple gateways including credit cards and PayPal' } ); ``` -------------------------------- ### Find Connections to a Specific Node (TypeScript) Source: https://github.com/bevel-software/bevel-ts-client/blob/main/README.md Finds all connections (relationships) pointing to a specific code entity node identified by its ID. This helps in understanding dependencies and call flows. ```typescript // Find all connections to a specific node const connections = await client.connections.findConnectionsTo('/path/to/project', node.id); ``` -------------------------------- ### Find a Specific Node by Name (TypeScript) Source: https://github.com/bevel-software/bevel-ts-client/blob/main/README.md Searches for a specific code entity node within a project by its name and file path. This helps in locating particular functions or classes. ```typescript // Find a specific node by name const node = await client.nodes.findNodeByName( '/path/to/project', 'UserController.login', '/src/controllers/UserController.ts' ); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.