UNPKG

@nomyx/assistant

Version:

A powerful assistant library and cli for your AI projects. works with Vertex AI (Claude and Gemini)

115 lines (114 loc) 3.45 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CodeNode = void 0; exports.findNodeById = findNodeById; exports.countNodes = countNodes; exports.getLeafNodes = getLeafNodes; exports.getNodeDepth = getNodeDepth; exports.cloneCodeNode = cloneCodeNode; const crypto_1 = require("crypto"); class CodeNode { constructor(type, value, children = [], metadata = {}) { this.type = type; this.value = value; this.children = children; this.metadata = metadata; this.id = (0, crypto_1.randomUUID)(); } toJSON() { return { id: this.id, type: this.type, value: this.value, children: this.children.map(child => child.toJSON()), metadata: this.metadata, codeQualityMetrics: this.codeQualityMetrics, securityIssues: this.securityIssues, generatedCode: this.generatedCode }; } static fromJSON(json) { if (!json || typeof json !== 'object') { throw new Error('Invalid JSON structure for CodeNode'); } const node = new CodeNode(json.type || 'Unknown', json.value || '', Array.isArray(json.children) ? json.children.map((child) => CodeNode.fromJSON(child)) : [], json.metadata || {}); node.id = json.id || (0, crypto_1.randomUUID)(); node.codeQualityMetrics = json.codeQualityMetrics; node.securityIssues = json.securityIssues; node.generatedCode = json.generatedCode; return node; } toString(indent = '') { let result = `${indent}${this.type}: ${this.value}\n`; for (const child of this.children) { result += child.toString(indent + ' '); } return result; } // Tree traversal methods traverse(callback) { callback(this); for (const child of this.children) { child.traverse(callback); } } find(predicate) { if (predicate(this)) { return this; } for (const child of this.children) { const found = child.find(predicate); if (found) { return found; } } return null; } // Serialization and deserialization serialize() { return JSON.stringify(this.toJSON()); } static deserialize(serialized) { return CodeNode.fromJSON(JSON.parse(serialized)); } } exports.CodeNode = CodeNode; // Utility functions for working with CodeNode structures function findNodeById(root, id) { return root.find(node => node.id === id); } function countNodes(root) { let count = 1; root.traverse(() => count++); return count; } function getLeafNodes(root) { const leafNodes = []; root.traverse(node => { if (node.children.length === 0) { leafNodes.push(node); } }); return leafNodes; } function getNodeDepth(root, targetNode) { let depth = -1; let found = false; function traverse(node, currentDepth) { if (found) return; if (node === targetNode) { depth = currentDepth; found = true; return; } for (const child of node.children) { traverse(child, currentDepth + 1); } } traverse(root, 0); return depth; } function cloneCodeNode(node) { return CodeNode.fromJSON(node.toJSON()); }