circuit-bricks
Version:
A modular, Lego-style SVG circuit component system for React (ALPHA - Not for production use)
999 lines (976 loc) • 37.2 kB
JavaScript
import { circuitStateSchema, componentInstanceSchema, componentSchema, getAllComponents, getComponentSchema, pointSchema, portSchema, portTypeSchema, propertySchema, sizeSchema, validateCircuitState, validationIssueSchema, wireSchema } from "./registry-BiEqWRGy.mjs";
import { getAllServerComponents, getServerCategories, getServerComponentSchema, getServerComponentsByCategory } from "./server-Cvg4Ggu4.mjs";
//#region rolldown:runtime
var __defProp = Object.defineProperty;
var __export = (target, all) => {
for (var name in all) __defProp(target, name, {
get: all[name],
enumerable: true
});
};
//#endregion
//#region src/utils/circuitValidation.ts
/**
* Validate a circuit for common issues
*
* @param circuit - The circuit state to validate
* @returns Array of validation issues
*/
function validateCircuit(circuit) {
const validationResult = validateCircuitState(circuit);
if (!validationResult.success) return [{
type: "error",
message: `Invalid circuit structure: ${validationResult.error}`
}];
const issues = [];
issues.push(...validateWireConnections(circuit));
issues.push(...validateFloatingPorts(circuit));
issues.push(...validateShortCircuits(circuit));
return issues;
}
/**
* Validate wire connections to ensure they reference valid components
*/
function validateWireConnections(circuit) {
const issues = [];
const componentIds = new Set(circuit.components.map((c) => c.id));
for (const wire of circuit.wires) {
if (!componentIds.has(wire.from.componentId)) issues.push({
type: "error",
message: `Wire connected to non-existent component ID: ${wire.from.componentId}`,
wireId: wire.id
});
if (!componentIds.has(wire.to.componentId)) issues.push({
type: "error",
message: `Wire connected to non-existent component ID: ${wire.to.componentId}`,
wireId: wire.id
});
const sourceComponent = circuit.components.find((c) => c.id === wire.from.componentId);
const destComponent = circuit.components.find((c) => c.id === wire.to.componentId);
if (sourceComponent) {
const schema = getComponentSchema(sourceComponent.type);
if (schema && !schema.ports.some((p) => p.id === wire.from.portId)) issues.push({
type: "error",
message: `Wire connected to non-existent port: ${wire.from.portId} on component ${sourceComponent.type}`,
wireId: wire.id
});
}
if (destComponent) {
const schema = getComponentSchema(destComponent.type);
if (schema && !schema.ports.some((p) => p.id === wire.to.portId)) issues.push({
type: "error",
message: `Wire connected to non-existent port: ${wire.to.portId} on component ${destComponent.type}`,
wireId: wire.id
});
}
}
return issues;
}
/**
* Check for floating input/output ports that should be connected
*/
function validateFloatingPorts(circuit) {
const issues = [];
const connectedPorts = new Map();
for (const wire of circuit.wires) {
if (!connectedPorts.has(wire.from.componentId)) connectedPorts.set(wire.from.componentId, new Set());
if (!connectedPorts.has(wire.to.componentId)) connectedPorts.set(wire.to.componentId, new Set());
connectedPorts.get(wire.from.componentId).add(wire.from.portId);
connectedPorts.get(wire.to.componentId).add(wire.to.portId);
}
for (const component of circuit.components) {
const schema = getComponentSchema(component.type);
if (!schema) continue;
const componentConnectedPorts = connectedPorts.get(component.id) || new Set();
for (const port of schema.ports) {
if (port.type === "input" && !componentConnectedPorts.has(port.id)) issues.push({
type: "warning",
message: `Floating input port: ${port.id} on ${schema.name} (${component.id})`,
componentId: component.id
});
if (port.type === "output" && !componentConnectedPorts.has(port.id)) issues.push({
type: "warning",
message: `Floating output port: ${port.id} on ${schema.name} (${component.id})`,
componentId: component.id
});
}
}
return issues;
}
/**
* Check for short circuits (multiple outputs connected together)
*/
function validateShortCircuits(circuit) {
const issues = [];
const connectionGraph = new Map();
for (const wire of circuit.wires) {
const fromKey = `${wire.from.componentId}-${wire.from.portId}`;
const toKey = `${wire.to.componentId}-${wire.to.portId}`;
if (!connectionGraph.has(fromKey)) connectionGraph.set(fromKey, new Set());
if (!connectionGraph.has(toKey)) connectionGraph.set(toKey, new Set());
connectionGraph.get(fromKey).add(toKey);
connectionGraph.get(toKey).add(fromKey);
}
const portTypes = new Map();
for (const component of circuit.components) {
const schema = getComponentSchema(component.type);
if (!schema) continue;
for (const port of schema.ports) portTypes.set(`${component.id}-${port.id}`, port.type);
}
const visited = new Set();
const connectedComponents = [];
for (const [port, connections] of connectionGraph.entries()) {
if (visited.has(port)) continue;
const connectedPorts = new Set();
const queue = [port];
visited.add(port);
while (queue.length > 0) {
const currentPort = queue.shift();
connectedPorts.add(currentPort);
for (const connectedPort of connectionGraph.get(currentPort) || []) if (!visited.has(connectedPort)) {
queue.push(connectedPort);
visited.add(connectedPort);
}
}
const outputPorts = [...connectedPorts].filter((p) => portTypes.get(p) === "output");
if (outputPorts.length > 1) issues.push({
type: "error",
message: `Short circuit detected: ${outputPorts.length} output ports connected together`
});
}
return issues;
}
//#endregion
//#region src/llm/componentDiscovery.ts
/**
* Convert a ComponentSchema to simplified ComponentInfo for LLM consumption
*/
function schemaToComponentInfo(schema) {
return {
id: schema.id,
name: schema.name,
category: schema.category,
description: schema.description,
ports: schema.ports.map((port) => ({
id: port.id,
type: port.type,
label: port.label
})),
properties: schema.properties.map((prop) => ({
key: prop.key,
label: prop.label,
type: prop.type,
default: prop.default,
unit: prop.unit,
options: prop.options?.map((option) => ({
value: option.value,
label: option.label
}))
}))
};
}
/**
* List all available components in a format optimized for LLM consumption
*
* @returns Array of simplified component information
*/
function listAvailableComponents() {
const allComponents = getAllServerComponents();
return allComponents.map(schemaToComponentInfo);
}
/**
* Get detailed information about a specific component
*
* @param componentId - The ID of the component to get details for
* @returns Detailed component information or null if not found
*/
function getComponentDetails(componentId) {
const schema = getServerComponentSchema(componentId);
if (!schema) return null;
return schemaToComponentInfo(schema);
}
/**
* Search components by name, description, or category
*
* @param query - Search query string
* @returns Array of search results with relevance scores
*/
function searchComponents(query) {
const allComponents = getAllServerComponents();
const searchTerm = query.toLowerCase();
const results = [];
for (const schema of allComponents) {
const matchedFields = [];
let relevanceScore = 0;
if (schema.name.toLowerCase().includes(searchTerm)) {
matchedFields.push("name");
relevanceScore += 10;
}
if (schema.id.toLowerCase().includes(searchTerm)) {
matchedFields.push("id");
relevanceScore += 8;
}
if (schema.category.toLowerCase().includes(searchTerm)) {
matchedFields.push("category");
relevanceScore += 5;
}
if (schema.description.toLowerCase().includes(searchTerm)) {
matchedFields.push("description");
relevanceScore += 3;
}
for (const prop of schema.properties) if (prop.label.toLowerCase().includes(searchTerm) || prop.key.toLowerCase().includes(searchTerm)) {
matchedFields.push("properties");
relevanceScore += 1;
break;
}
if (relevanceScore > 0) results.push({
component: schemaToComponentInfo(schema),
relevanceScore,
matchedFields
});
}
return results.sort((a, b) => b.relevanceScore - a.relevanceScore);
}
/**
* Get all unique categories available in the registry
*
* @returns Array of category names
*/
function getAllCategories() {
return getServerCategories();
}
/**
* List components in a specific category
*
* @param category - The category to filter by
* @returns Array of components in the specified category
*/
function listComponentsByCategory(category) {
const componentsInCategory = getServerComponentsByCategory(category);
return componentsInCategory.map(schemaToComponentInfo);
}
//#endregion
//#region src/llm/registryMetadata.ts
/**
* Get comprehensive metadata about the component registry
*
* @returns Registry metadata including counts, categories, and organization
*/
function getRegistryMetadata() {
const allComponents = getAllComponents();
const categorySet = new Set(allComponents.map((schema) => schema.category));
const categories = Array.from(categorySet).sort();
const componentsByCategory = {};
for (const category of categories) componentsByCategory[category] = allComponents.filter((schema) => schema.category === category).length;
return {
totalComponents: allComponents.length,
categories,
componentsByCategory,
lastUpdated: new Date().toISOString()
};
}
/**
* Generate a human-readable summary of the component registry
*
* @returns A comprehensive text summary of the registry
*/
function getRegistrySummary() {
const metadata = getRegistryMetadata();
const allComponents = getAllComponents();
let summary = `# Circuit-Bricks Component Registry Summary
## Overview
The Circuit-Bricks component registry contains ${metadata.totalComponents} components organized into ${metadata.categories.length} categories.
## Categories and Components:
`;
for (const category of metadata.categories) {
const categoryComponents = allComponents.filter((schema) => schema.category === category);
summary += `\n### ${category.charAt(0).toUpperCase() + category.slice(1)} (${categoryComponents.length} components)
`;
for (const component of categoryComponents) summary += `- **${component.name}** (${component.id}): ${component.description}
`;
}
summary += `
## Component Capabilities
Total ports across all components: ${allComponents.reduce((total, comp) => total + comp.ports.length, 0)}
Total configurable properties: ${allComponents.reduce((total, comp) => total + comp.properties.length, 0)}
## Popular Components
Based on common circuit patterns, the most frequently used components are:
- Resistor: Essential for current limiting and voltage division
- Battery/Voltage Source: Power supply components
- Ground: Reference point for circuits
- LED: Visual output indicator
- Switch: User input control
Last updated: ${metadata.lastUpdated}
`;
return summary;
}
/**
* Get a detailed summary for a specific component
*
* @param componentId - The ID of the component to summarize
* @returns Detailed component summary or null if not found
*/
function getComponentDetailedSummary(componentId) {
const allComponents = getAllComponents();
const component = allComponents.find((schema) => schema.id === componentId);
if (!component) return null;
let summary = `# ${component.name} (${component.id})
## Description
${component.description}
## Category
${component.category.charAt(0).toUpperCase() + component.category.slice(1)}
## Physical Properties
- Default Width: ${component.defaultWidth}px
- Default Height: ${component.defaultHeight}px
## Ports (${component.ports.length} total)
`;
for (const port of component.ports) summary += `- **${port.id}** (${port.type}): Located at (${port.x}, ${port.y})${port.label ? ` - ${port.label}` : ""}
`;
if (component.properties.length > 0) {
summary += `
## Configurable Properties (${component.properties.length} total)
`;
for (const prop of component.properties) {
let propLine = `- **${prop.label}** (${prop.key}): ${prop.type}`;
if (prop.default !== void 0) propLine += `, default: ${prop.default}`;
if (prop.unit) propLine += ` ${prop.unit}`;
if (prop.min !== void 0 || prop.max !== void 0) propLine += ` (range: ${prop.min ?? "unlimited"} to ${prop.max ?? "unlimited"})`;
summary += propLine + "\n";
}
} else summary += `
## Configurable Properties
This component has no configurable properties.
`;
summary += `
## Usage Notes
This component can be connected to other components through its ${component.ports.length} port${component.ports.length !== 1 ? "s" : ""}. `;
if (component.ports.some((p) => p.type === "input")) summary += "It has input ports that can receive signals from other components. ";
if (component.ports.some((p) => p.type === "output")) summary += "It has output ports that can send signals to other components. ";
if (component.ports.some((p) => p.type === "inout")) summary += "It has bidirectional ports that can both send and receive signals. ";
return summary;
}
//#endregion
//#region src/llm/circuitGeneration.ts
/**
* Generate a circuit template from a natural language description
*
* @param description - Natural language description of the desired circuit
* @returns A basic circuit template
*/
function generateCircuitTemplate(description) {
const desc = description.toLowerCase();
const components = [];
const wires = [];
const allSchemas = getAllComponents();
let componentId = 1;
let wireId = 1;
if (allSchemas.find((s) => s.id === "ground")) components.push({
id: `ground_${componentId++}`,
type: "ground",
position: {
x: 100,
y: 200
},
props: {}
});
if (desc.includes("led") || desc.includes("light")) {
if (allSchemas.find((s) => s.id === "led")) components.push({
id: `led_${componentId++}`,
type: "led",
position: {
x: 200,
y: 100
},
props: { color: "#ff0000" }
});
if (allSchemas.find((s) => s.id === "resistor")) components.push({
id: `resistor_${componentId++}`,
type: "resistor",
position: {
x: 100,
y: 100
},
props: { resistance: 330 }
});
if (allSchemas.find((s) => s.id === "battery")) components.push({
id: `battery_${componentId++}`,
type: "battery",
position: {
x: 50,
y: 150
},
props: { voltage: 9 }
});
if (components.length >= 3) {
wires.push({
id: `wire_${wireId++}`,
from: {
componentId: components[2].id,
portId: "positive"
},
to: {
componentId: components[1].id,
portId: "terminal_1"
}
});
wires.push({
id: `wire_${wireId++}`,
from: {
componentId: components[1].id,
portId: "terminal_2"
},
to: {
componentId: components[0].id,
portId: "anode"
}
});
wires.push({
id: `wire_${wireId++}`,
from: {
componentId: components[0].id,
portId: "cathode"
},
to: {
componentId: components[2].id,
portId: "negative"
}
});
}
} else if (desc.includes("resistor") && !desc.includes("led")) {
if (allSchemas.find((s) => s.id === "resistor")) components.push({
id: `resistor_${componentId++}`,
type: "resistor",
position: {
x: 150,
y: 100
},
props: { resistance: 1e3 }
});
if (allSchemas.find((s) => s.id === "battery")) components.push({
id: `battery_${componentId++}`,
type: "battery",
position: {
x: 50,
y: 150
},
props: { voltage: 9 }
});
} else if (desc.includes("capacitor") || desc.includes("filter")) {
if (allSchemas.find((s) => s.id === "capacitor")) components.push({
id: `capacitor_${componentId++}`,
type: "capacitor",
position: {
x: 150,
y: 100
},
props: { capacitance: 100 }
});
if (allSchemas.find((s) => s.id === "battery")) components.push({
id: `battery_${componentId++}`,
type: "battery",
position: {
x: 50,
y: 150
},
props: { voltage: 9 }
});
}
if (components.length === 1) {
const basicComponents = ["resistor", "battery"];
for (const compType of basicComponents) if (allSchemas.find((s) => s.id === compType)) components.push({
id: `${compType}_${componentId++}`,
type: compType,
position: {
x: 100 + components.length * 50,
y: 100
},
props: compType === "battery" ? { voltage: 9 } : { resistance: 1e3 }
});
}
return {
id: `circuit_${Date.now()}`,
name: `Generated Circuit: ${description}`,
description: `Auto-generated circuit based on: "${description}"`,
components,
wires
};
}
/**
* Generate a human-readable description of a circuit
*
* @param circuit - The circuit to describe
* @returns Detailed circuit description
*/
function describeCircuit(circuit) {
const components = circuit.components;
const wires = circuit.wires;
const allSchemas = getAllComponents();
const componentDescriptions = [];
const connectionDescriptions = [];
for (const comp of components) {
const schema = allSchemas.find((s) => s.id === comp.type);
if (schema) {
let desc = `${schema.name} (${comp.id})`;
if (Object.keys(comp.props).length > 0) {
const propStrs = Object.entries(comp.props).map(([key, value]) => `${key}: ${value}`);
desc += ` with properties: ${propStrs.join(", ")}`;
}
componentDescriptions.push(desc);
}
}
for (const wire of wires) {
const fromComp = components.find((c) => c.id === wire.from.componentId);
const toComp = components.find((c) => c.id === wire.to.componentId);
if (fromComp && toComp) connectionDescriptions.push(`${fromComp.type}(${fromComp.id}).${wire.from.portId} → ${toComp.type}(${toComp.id}).${wire.to.portId}`);
}
let analysis = `This circuit contains ${components.length} component${components.length !== 1 ? "s" : ""} and ${wires.length} connection${wires.length !== 1 ? "s" : ""}. `;
const componentTypes = [...new Set(components.map((c) => c.type))];
if (componentTypes.includes("battery") || componentTypes.includes("voltage-source")) analysis += "It includes a power source. ";
if (componentTypes.includes("ground")) analysis += "It has a ground reference. ";
if (componentTypes.includes("resistor")) analysis += "It uses resistors for current control. ";
if (componentTypes.includes("led")) analysis += "It includes LED indicators. ";
if (componentTypes.includes("capacitor")) analysis += "It uses capacitors for filtering or energy storage. ";
return {
summary: `Circuit with ${components.length} components including: ${componentTypes.join(", ")}`,
components: componentDescriptions,
connections: connectionDescriptions,
analysis
};
}
/**
* Suggest connections between components in a circuit
*
* @param components - Array of components to analyze for connections
* @returns Array of connection suggestions
*/
function suggestConnections(components) {
const suggestions = [];
const allSchemas = getAllComponents();
for (let i = 0; i < components.length; i++) for (let j = i + 1; j < components.length; j++) {
const comp1 = components[i];
const comp2 = components[j];
const schema1 = allSchemas.find((s) => s.id === comp1.type);
const schema2 = allSchemas.find((s) => s.id === comp2.type);
if (!schema1 || !schema2) continue;
if (comp1.type === "battery" && comp2.type !== "ground") {
if (schema1.ports.find((p) => p.id === "positive") && schema2.ports.find((p) => p.type === "input" || p.type === "inout")) suggestions.push({
from: {
componentId: comp1.id,
portId: "positive"
},
to: {
componentId: comp2.id,
portId: schema2.ports.find((p) => p.type === "input" || p.type === "inout").id
},
reason: "Connect power source positive terminal to component input",
confidence: .8
});
}
if (comp2.type === "ground") {
const outputPort = schema1.ports.find((p) => p.type === "output" || p.type === "inout");
if (outputPort) suggestions.push({
from: {
componentId: comp1.id,
portId: outputPort.id
},
to: {
componentId: comp2.id,
portId: "terminal"
},
reason: "Connect component output to ground reference",
confidence: .7
});
}
if (comp1.type === "resistor" && comp2.type === "led") suggestions.push({
from: {
componentId: comp1.id,
portId: "terminal_2"
},
to: {
componentId: comp2.id,
portId: "anode"
},
reason: "Connect resistor output to LED anode for current limiting",
confidence: .9
});
}
return suggestions.sort((a, b) => b.confidence - a.confidence);
}
//#endregion
//#region src/llm/getAllSchemas.ts
/**
* Get all component schema information
*
* Returns all the Zod schemas and their structure from componentSchema.ts
*
* @returns Object containing all schema definitions
*/
function getAllComponentSchemas() {
return {
portTypeSchema,
pointSchema,
sizeSchema,
portSchema,
propertySchema,
componentSchema,
componentInstanceSchema,
wireSchema,
circuitStateSchema,
validationIssueSchema,
descriptions: {
portTypeSchema: "Enum of all available port types: input, output, inout, positive, negative, anode, cathode, collector, base, emitter, drain, gate, source, vcc, vdd, vss, gnd, clock, reset, enable",
pointSchema: "2D point with x and y coordinates (numbers)",
sizeSchema: "Size dimensions with width and height (numbers)",
portSchema: "Component port with id (string), x (number), y (number), type (portType), optional label (string)",
propertySchema: "Component property with key (string), label (string), type (number|boolean|select|text|color), optional unit (string), optional options array, default value, optional min/max (numbers)",
componentSchema: "Complete component definition with id (string), name (string), category (string), description (string), defaultWidth (number), defaultHeight (number), ports array, properties array, svgPath (string)",
componentInstanceSchema: "Component instance with id (string), type (string), position (point), optional size, props (record), optional rotation (number)",
wireSchema: "Wire connection with id (string), from (componentId, portId), to (componentId, portId), optional style (color, strokeWidth, dashArray)",
circuitStateSchema: "Complete circuit with components array, wires array, selectedComponentIds array, selectedWireIds array",
validationIssueSchema: "Validation issue with type (error|warning), message (string), optional componentId, optional wireId"
}
};
}
//#endregion
//#region src/llm/utilities.ts
/**
* Get quick start information for LLMs new to Circuit-Bricks
*
* @returns Quick start guide and essential information
*/
function getQuickStart() {
const metadata = getRegistryMetadata();
const allComponents = getAllComponents();
const essentialComponents = [
"resistor",
"battery",
"ground",
"led",
"switch"
];
const popularComponents = allComponents.filter((comp) => essentialComponents.includes(comp.id)).map((comp) => ({
id: comp.id,
name: comp.name,
description: comp.description,
category: comp.category
}));
return {
totalComponents: metadata.totalComponents,
categories: metadata.categories,
popularComponents,
exampleUsage: `// Quick Start Example
import { LLM } from 'circuit-bricks';
// 1. Discover available components
const components = LLM.listAvailableComponents();
console.log(\`Found \${components.length} components\`);
// 2. Search for specific components
const resistors = LLM.searchComponents('resistor');
// 3. Generate a simple circuit
const circuit = LLM.generateCircuitTemplate('LED circuit with current limiting resistor');
// 4. Validate the circuit
const validation = LLM.validateCircuitDesign(circuit);
if (!validation.isValid) {
console.log('Issues found:', validation.errors);
}
// 5. Get a description of the circuit
const description = LLM.describeCircuit(circuit);
console.log(description.summary);`
};
}
/**
* Get comprehensive API help for LLMs
*
* @returns Detailed API documentation and guidance
*/
function getAPIHelp() {
return {
overview: `Circuit-Bricks LLM Integration API provides a comprehensive set of functions for discovering components, generating circuits, and validating designs. The API is designed to be intuitive for LLMs with clear, structured responses and helpful error messages.`,
commonTasks: [
{
task: "Discover available components",
function: "listAvailableComponents()",
description: "Get all components with their basic information",
example: "const components = LLM.listAvailableComponents();"
},
{
task: "Search for specific components",
function: "searchComponents(query)",
description: "Find components by name, description, or category",
example: "const results = LLM.searchComponents(\"resistor\");"
},
{
task: "Get component details",
function: "getComponentDetails(id)",
description: "Get detailed information about a specific component",
example: "const details = LLM.getComponentDetails(\"resistor\");"
},
{
task: "Generate a circuit",
function: "generateCircuitTemplate(description)",
description: "Create a circuit from natural language description",
example: "const circuit = LLM.generateCircuitTemplate(\"LED circuit\");"
},
{
task: "Validate a circuit",
function: "validateCircuitDesign(circuit)",
description: "Check circuit for errors and get suggestions",
example: "const validation = LLM.validateCircuitDesign(myCircuit);"
},
{
task: "Describe a circuit",
function: "describeCircuit(circuit)",
description: "Get human-readable description of a circuit",
example: "const description = LLM.describeCircuit(myCircuit);"
}
],
bestPractices: [
"Always validate circuits after generation or modification",
"Use getComponentDetails() to understand component capabilities before using them",
"Check validation.errors and validation.warnings for circuit issues",
"Use searchComponents() to find alternatives if needed components don't exist",
"Include ground references in circuits for proper voltage reference",
"Use descriptive IDs for components to make circuits easier to understand",
"Consider electrical compatibility when connecting components",
"Start with simple circuits and gradually add complexity"
]
};
}
/**
* Get current API status and system information
*
* @returns Current status of the LLM API
*/
function getAPIStatus() {
const metadata = getRegistryMetadata();
return {
isReady: true,
version: "0.1.2",
componentsLoaded: metadata.totalComponents,
categoriesAvailable: metadata.categories.length,
lastUpdated: metadata.lastUpdated,
capabilities: [
"Component discovery and search",
"Circuit generation from descriptions",
"Circuit validation with detailed feedback",
"Connection suggestions",
"Registry metadata access",
"Human-readable circuit descriptions"
],
limitations: [
"Circuit generation is pattern-based, not AI-powered",
"Validation is structural, not electrical simulation",
"Limited to registered component types",
"Connection suggestions are heuristic-based"
]
};
}
//#endregion
//#region src/llm/validation.ts
/**
* Validate a circuit design with LLM-friendly output
*
* @param circuit - The circuit state to validate
* @returns Validation result with clear messages
*/
function validateCircuitDesign(circuit) {
const errors = [];
const warnings = [];
const suggestions = [];
for (const component of circuit.components) {
const schema = getComponentSchema(component.type);
if (!schema) {
errors.push(`Component type "${component.type}" (ID: ${component.id}) is not registered in the component registry.`);
continue;
}
for (const prop of schema.properties) {
const value = component.props[prop.key];
if (value === void 0 && prop.default === void 0) warnings.push(`Component "${component.id}" is missing required property "${prop.label}" (${prop.key}).`);
if (value !== void 0) switch (prop.type) {
case "number":
if (typeof value !== "number") errors.push(`Property "${prop.label}" of component "${component.id}" must be a number, got ${typeof value}.`);
else {
if (prop.min !== void 0 && value < prop.min) errors.push(`Property "${prop.label}" of component "${component.id}" must be at least ${prop.min}, got ${value}.`);
if (prop.max !== void 0 && value > prop.max) errors.push(`Property "${prop.label}" of component "${component.id}" must be at most ${prop.max}, got ${value}.`);
}
break;
case "boolean":
if (typeof value !== "boolean") errors.push(`Property "${prop.label}" of component "${component.id}" must be a boolean, got ${typeof value}.`);
break;
case "select":
if (prop.options && !prop.options.some((opt) => opt.value === value)) {
const validOptions = prop.options.map((opt) => opt.value).join(", ");
errors.push(`Property "${prop.label}" of component "${component.id}" must be one of: ${validOptions}, got ${value}.`);
}
break;
}
}
}
for (const wire of circuit.wires) {
const fromComponent = circuit.components.find((c) => c.id === wire.from.componentId);
const toComponent = circuit.components.find((c) => c.id === wire.to.componentId);
if (!fromComponent) {
errors.push(`Wire "${wire.id}" references non-existent source component "${wire.from.componentId}".`);
continue;
}
if (!toComponent) {
errors.push(`Wire "${wire.id}" references non-existent destination component "${wire.to.componentId}".`);
continue;
}
const fromSchema = getComponentSchema(fromComponent.type);
const toSchema = getComponentSchema(toComponent.type);
if (!fromSchema || !toSchema) continue;
const fromPort = fromSchema.ports.find((p) => p.id === wire.from.portId);
const toPort = toSchema.ports.find((p) => p.id === wire.to.portId);
if (!fromPort) errors.push(`Wire "${wire.id}" references non-existent port "${wire.from.portId}" on component "${fromComponent.id}" (${fromSchema.name}).`);
if (!toPort) errors.push(`Wire "${wire.id}" references non-existent port "${wire.to.portId}" on component "${toComponent.id}" (${toSchema.name}).`);
if (fromPort && toPort) {
if (fromPort.type === "input" && toPort.type === "input") warnings.push(`Wire "${wire.id}" connects two input ports, which may not be electrically valid.`);
if (fromPort.type === "output" && toPort.type === "output") warnings.push(`Wire "${wire.id}" connects two output ports, which may cause conflicts.`);
}
}
const powerSources = circuit.components.filter((comp) => {
const schema = getComponentSchema(comp.type);
return schema?.category === "power" || schema?.id === "battery" || schema?.id === "voltage-source";
});
const grounds = circuit.components.filter((comp) => {
const schema = getComponentSchema(comp.type);
return schema?.id === "ground";
});
if (powerSources.length === 0) warnings.push("Circuit has no power sources. Consider adding a battery or voltage source.");
if (grounds.length === 0) warnings.push("Circuit has no ground connection. This may cause issues in real circuits.");
if (powerSources.length > 1) warnings.push(`Circuit has ${powerSources.length} power sources. Ensure they are properly isolated or connected.`);
const connectedComponents = new Set();
for (const wire of circuit.wires) {
connectedComponents.add(wire.from.componentId);
connectedComponents.add(wire.to.componentId);
}
for (const component of circuit.components) if (!connectedComponents.has(component.id)) warnings.push(`Component "${component.id}" is not connected to any other components.`);
if (powerSources.length > 0 && grounds.length === 0) suggestions.push("Add a ground component to complete the circuit.");
if (circuit.components.length > 0 && circuit.wires.length === 0) suggestions.push("Add wire connections between components to create a functional circuit.");
const componentsByCategory = circuit.components.reduce((acc, comp) => {
const schema = getComponentSchema(comp.type);
if (schema) {
if (!acc[schema.category]) acc[schema.category] = [];
acc[schema.category].push(comp);
}
return acc;
}, {});
const outputComponents = componentsByCategory["output"] || [];
const passiveComponents = componentsByCategory["passive"] || [];
const hasLEDLikeComponent = outputComponents.some((comp) => {
const schema = getComponentSchema(comp.type);
return schema?.name.toLowerCase().includes("led") || schema?.description.toLowerCase().includes("light") || schema?.description.toLowerCase().includes("diode");
});
const hasCurrentLimitingComponent = passiveComponents.some((comp) => {
const schema = getComponentSchema(comp.type);
return schema?.name.toLowerCase().includes("resistor") || schema?.description.toLowerCase().includes("resistance") || schema?.description.toLowerCase().includes("current limiting");
});
if (hasLEDLikeComponent && !hasCurrentLimitingComponent && powerSources.length > 0) suggestions.push("Consider adding a current-limiting component (like a resistor) in series with light-emitting components to prevent damage.");
try {
const existingValidation = validateCircuit(circuit);
for (const issue of existingValidation) if (issue.type === "error") errors.push(issue.message);
else if (issue.type === "warning") warnings.push(issue.message);
} catch (error) {
errors.push(`Circuit validation failed: ${error instanceof Error ? error.message : "Unknown error"}`);
}
return {
isValid: errors.length === 0,
errors,
warnings,
suggestions
};
}
/**
* Validate a single component instance
*
* @param component - The component instance to validate
* @returns Validation result
*/
function validateComponentInstance(component) {
const errors = [];
const warnings = [];
const suggestions = [];
const schema = getComponentSchema(component.type);
if (!schema) {
errors.push(`Component type "${component.type}" is not registered.`);
return {
isValid: false,
errors,
warnings,
suggestions
};
}
for (const prop of schema.properties) {
const value = component.props[prop.key];
if (value === void 0 && prop.default === void 0) warnings.push(`Missing property "${prop.label}" (${prop.key}).`);
}
if (typeof component.position.x !== "number" || typeof component.position.y !== "number") errors.push("Component position must have numeric x and y coordinates.");
if (!component.id || typeof component.id !== "string") errors.push("Component must have a valid string ID.");
return {
isValid: errors.length === 0,
errors,
warnings,
suggestions
};
}
/**
* Validate a wire connection
*
* @param wire - The wire to validate
* @param components - Array of components in the circuit
* @returns Validation result
*/
function validateWireConnection(wire, components) {
const errors = [];
const warnings = [];
const suggestions = [];
const fromComponent = components.find((c) => c.id === wire.from.componentId);
const toComponent = components.find((c) => c.id === wire.to.componentId);
if (!fromComponent) errors.push(`Source component "${wire.from.componentId}" not found.`);
if (!toComponent) errors.push(`Destination component "${wire.to.componentId}" not found.`);
if (fromComponent && toComponent) {
const fromSchema = getComponentSchema(fromComponent.type);
const toSchema = getComponentSchema(toComponent.type);
if (fromSchema && toSchema) {
const fromPort = fromSchema.ports.find((p) => p.id === wire.from.portId);
const toPort = toSchema.ports.find((p) => p.id === wire.to.portId);
if (!fromPort) errors.push(`Port "${wire.from.portId}" not found on ${fromSchema.name}.`);
if (!toPort) errors.push(`Port "${wire.to.portId}" not found on ${toSchema.name}.`);
if (fromPort && toPort) {
if (fromPort.type === "input" && toPort.type === "input") warnings.push("Connecting two input ports may not be electrically valid.");
}
}
}
return {
isValid: errors.length === 0,
errors,
warnings,
suggestions
};
}
//#endregion
//#region src/llm/index.ts
var llm_exports = {};
__export(llm_exports, {
describeCircuit: () => describeCircuit,
generateCircuitTemplate: () => generateCircuitTemplate,
getAPIHelp: () => getAPIHelp,
getAPIStatus: () => getAPIStatus,
getAllCategories: () => getAllCategories,
getAllComponentSchemas: () => getAllComponentSchemas,
getComponentDetailedSummary: () => getComponentDetailedSummary,
getComponentDetails: () => getComponentDetails,
getQuickStart: () => getQuickStart,
getRegistryMetadata: () => getRegistryMetadata,
getRegistrySummary: () => getRegistrySummary,
listAvailableComponents: () => listAvailableComponents,
listComponentsByCategory: () => listComponentsByCategory,
searchComponents: () => searchComponents,
suggestConnections: () => suggestConnections,
validateCircuitDesign: () => validateCircuitDesign,
validateComponentInstance: () => validateComponentInstance,
validateWireConnection: () => validateWireConnection
});
//#endregion
export { describeCircuit, generateCircuitTemplate, getAPIHelp, getAPIStatus, getAllCategories, getAllComponentSchemas, getComponentDetailedSummary, getComponentDetails, getQuickStart, getRegistryMetadata, getRegistrySummary, listAvailableComponents, listComponentsByCategory, llm_exports, searchComponents, suggestConnections, validateCircuit, validateCircuitDesign, validateComponentInstance, validateWireConnection };
//# sourceMappingURL=llm-CUALlGle.mjs.map