ij
Idea Junction - Connect vague ideas and evolve them to fully functional systems.
A bidirectional diagramming system that enables seamless movement between natural language, visual diagrams, and code.
- class ij.D2Parser[source]
Parse D2 syntax to DiagramIR.
Supports basic D2 syntax including: - Node definitions with shapes and labels - Edge connections with labels - Direction metadata
- parse(d2_text: str) DiagramIR[source]
Parse D2 syntax to DiagramIR.
- Parameters:
d2_text – D2 diagram source
- Returns:
DiagramIR representation
Example
>>> parser = D2Parser() >>> d2_code = ''' ... n1: "Start" { ... shape: oval ... } ... n2: "Process" { ... shape: rectangle ... } ... n1 -> n2 ... ''' >>> diagram = parser.parse(d2_code)
- class ij.D2Renderer(layout: str = 'dagre')[source]
Renders DiagramIR to D2 syntax.
D2 is a modern diagram language with clean syntax, multiple layout engines, and PowerPoint export capabilities.
- class ij.DiagramDiff[source]
Compare and diff diagrams.
- compare(diagram1: DiagramIR, diagram2: DiagramIR) DiagramChanges[source]
Compare two diagrams.
- Parameters:
diagram1 – Original diagram
diagram2 – Modified diagram
- Returns:
DiagramChanges describing differences
Example
>>> differ = DiagramDiff() >>> changes = differ.compare(old_diagram, new_diagram) >>> print(f"Added: {len(changes.added_nodes)} nodes")
- compare_files(file1: str, file2: str) DiagramChanges[source]
Compare two diagram files.
- Parameters:
file1 – Path to first diagram
file2 – Path to second diagram
- Returns:
DiagramChanges describing differences
- generate_diff_report(changes: DiagramChanges) str[source]
Generate human-readable diff report.
- Parameters:
changes – DiagramChanges to report
- Returns:
Formatted diff report string
- merge(base: DiagramIR, branch1: DiagramIR, branch2: DiagramIR, strategy: str = 'union') DiagramIR[source]
Merge two diagram versions with a common base.
- Parameters:
base – Common ancestor diagram
branch1 – First modified version
branch2 – Second modified version
strategy – Merge strategy (‘union’, ‘intersection’, ‘ours’, ‘theirs’)
- Returns:
Merged DiagramIR
Example
>>> differ = DiagramDiff() >>> merged = differ.merge(base, branch1, branch2, strategy='union')
- class ij.DiagramHistory[source]
Track diagram history and changes over time.
- add_version(name: str, diagram: DiagramIR)[source]
Add a version to history.
- Parameters:
name – Version name/identifier
diagram – DiagramIR snapshot
- compare_versions(name1: str, name2: str) DiagramChanges[source]
Compare two versions.
- Parameters:
name1 – First version name
name2 – Second version name
- Returns:
DiagramChanges between versions
- get_changelog() str[source]
Generate changelog across all versions.
- Returns:
Formatted changelog string
- class ij.DiagramIR(nodes: List[Node] = <factory>, edges: List[Edge] = <factory>, metadata: Dict[str, ~typing.Any]=<factory>)[source]
Intermediate Representation for diagrams.
This serves as the central data structure that can be: - Generated from natural language - Converted to various diagram formats (Mermaid, PlantUML, D2) - Manipulated programmatically - Parsed back from diagram syntax
- nodes
List of nodes in the diagram
- Type:
List[ij.core.Node]
- edges
List of edges connecting nodes
- Type:
List[ij.core.Edge]
- metadata
Diagram-level properties (title, description, etc.)
- Type:
Dict[str, Any]
- class ij.DiagramLinter[source]
Lint diagrams for style and best practices.
- lint(diagram: DiagramIR) List[ValidationIssue][source]
Lint diagram for style issues.
- Parameters:
diagram – DiagramIR to lint
- Returns:
List of linting issues
Example
>>> linter = DiagramLinter() >>> issues = linter.lint(diagram) >>> for issue in issues: ... print(f"{issue.severity.value.upper()}: {issue.message}")
- class ij.DiagramTransforms[source]
Transform and optimize diagram structures.
- static apply_node_filter(diagram: DiagramIR, predicate: Callable[[Node], bool]) DiagramIR[source]
Filter nodes using a custom predicate function.
- Parameters:
diagram – DiagramIR to filter
predicate – Function that returns True for nodes to keep
- Returns:
Filtered DiagramIR
Example
>>> # Keep only nodes with labels containing "error" >>> filtered = DiagramTransforms.apply_node_filter( ... diagram, lambda n: "error" in n.label.lower() ... )
- static extract_subgraph(diagram: DiagramIR, root_node_id: str, max_depth: int | None = None) DiagramIR[source]
Extract subgraph starting from a root node.
- Parameters:
diagram – Source DiagramIR
root_node_id – ID of root node
max_depth – Maximum depth to traverse (None = unlimited)
- Returns:
DiagramIR containing subgraph
Example
>>> # Extract subgraph from node 'start' with depth 2 >>> subgraph = DiagramTransforms.extract_subgraph(diagram, "start", max_depth=2)
- static filter_by_node_type(diagram: DiagramIR, node_types: List[NodeType], keep: bool = True) DiagramIR[source]
Filter diagram by node types.
- Parameters:
diagram – DiagramIR to filter
node_types – List of NodeTypes to filter
keep – If True, keep only these types; if False, remove these types
- Returns:
Filtered DiagramIR
Example
>>> # Keep only PROCESS nodes >>> filtered = DiagramTransforms.filter_by_node_type( ... diagram, [NodeType.PROCESS], keep=True ... )
- static find_cycles(diagram: DiagramIR) List[List[str]][source]
Find all cycles in the diagram.
- Parameters:
diagram – DiagramIR to analyze
- Returns:
List of cycles, where each cycle is a list of node IDs
Example
>>> cycles = DiagramTransforms.find_cycles(diagram) >>> if cycles: ... print(f"Found {len(cycles)} cycles")
- static get_statistics(diagram: DiagramIR) dict[source]
Get statistics about the diagram.
- Parameters:
diagram – DiagramIR to analyze
- Returns:
Dictionary containing diagram statistics
Example
>>> stats = DiagramTransforms.get_statistics(diagram) >>> print(f"Nodes: {stats['node_count']}, Edges: {stats['edge_count']}")
- static merge_diagrams(diagrams: List[DiagramIR], title: str | None = None) DiagramIR[source]
Merge multiple diagrams into one.
- Parameters:
diagrams – List of DiagramIR to merge
title – Optional title for merged diagram
- Returns:
Merged DiagramIR
Example
>>> diagram1 = DiagramIR() >>> diagram2 = DiagramIR() >>> merged = DiagramTransforms.merge_diagrams([diagram1, diagram2])
- static merge_sequential_nodes(diagram: DiagramIR, separator: str = ' → ') DiagramIR[source]
Merge sequential nodes into single nodes.
Combines nodes that form a linear sequence with no branching.
- Parameters:
diagram – DiagramIR to transform
separator – String to join labels
- Returns:
DiagramIR with merged nodes
- static reverse_edges(diagram: DiagramIR) DiagramIR[source]
Reverse all edge directions in the diagram.
- Parameters:
diagram – DiagramIR to reverse
- Returns:
DiagramIR with reversed edges
Example
>>> reversed_diagram = DiagramTransforms.reverse_edges(diagram)
- static simplify(diagram: DiagramIR, remove_isolated: bool = True) DiagramIR[source]
Simplify diagram by removing redundant nodes and edges.
- Parameters:
diagram – DiagramIR to simplify
remove_isolated – Remove nodes with no connections
- Returns:
Simplified DiagramIR
Example
>>> from ij import DiagramIR, Node, Edge >>> diagram = DiagramIR() >>> diagram.add_node(Node(id="a", label="A")) >>> diagram.add_node(Node(id="isolated", label="Isolated")) >>> diagram.add_edge(Edge(source="a", target="b")) >>> simplified = DiagramTransforms.simplify(diagram) >>> len(simplified.nodes) # isolated node removed 2
- class ij.DiagramValidator[source]
Validate diagrams against various rules.
- validate(diagram: DiagramIR, rules: List[str] | None = None) ValidationResult[source]
Validate diagram against rules.
- Parameters:
diagram – DiagramIR to validate
rules – List of rule names to check (None = all rules)
- Returns:
ValidationResult with issues found
Example
>>> validator = DiagramValidator() >>> result = validator.validate(diagram, rules=['no-cycles', 'no-orphaned-nodes']) >>> if not result.is_valid: ... for issue in result.errors: ... print(f"ERROR: {issue.message}")
- class ij.ERDiagram(title: str | None = None)[source]
Entity-Relationship Diagram.
- add_relationship(from_entity: str, to_entity: str, cardinality: Cardinality, label: str | None = None)[source]
Add a relationship between entities.
- class ij.Edge(source: str, target: str, label: str | None = None, edge_type: EdgeType = EdgeType.DIRECT, metadata: Dict[str, ~typing.Any]=<factory>)[source]
Represents an edge in the diagram IR.
- source
Source node ID
- Type:
str
- target
Target node ID
- Type:
str
- label
Optional edge label
- Type:
str | None
- edge_type
Type of edge
- Type:
- metadata
Additional properties for extensibility
- Type:
Dict[str, Any]
- class ij.EnhancedTextConverter[source]
Enhanced text-to-diagram converter with NLP capabilities.
Supports: - Conditional branches (if/else) - Parallel flows (parallel keyword) - Loops (while, repeat) - Better keyword detection - Multiple sentence formats
- convert(text: str, title: str | None = None) DiagramIR[source]
Convert enhanced text to DiagramIR.
- Parameters:
text – Input text describing a process/flow
title – Optional diagram title
- Returns:
DiagramIR representation
Examples
>>> converter = EnhancedTextConverter() >>> # Conditional >>> diagram = converter.convert("Start -> Check user. If authenticated: Show dashboard, else: Show login") >>> # Parallel >>> diagram = converter.convert("Start -> [parallel: Process A, Process B] -> End")
- class ij.Entity(name: str, fields: List[Field] = <factory>, metadata: Dict = <factory>)[source]
An entity in an ERD.
- class ij.Field(name: str, type: str, primary_key: bool = False, foreign_key: str | None = None, nullable: bool = True, unique: bool = False)[source]
A field in an entity.
- class ij.ForceDirectedLayout(iterations: int = 100, optimal_distance: float = 100, repulsion_strength: float = 5000, attraction_strength: float = 0.1, cooling_factor: float = 0.95)[source]
Force-directed layout using Fruchterman-Reingold algorithm.
- class ij.GraphOperations[source]
Graph manipulation and analysis using NetworkX.
- static find_critical_nodes(diagram: DiagramIR) Set[str][source]
Find nodes whose removal would disconnect the graph.
- Parameters:
diagram – DiagramIR to analyze
- Returns:
Set of critical node IDs
- static find_cycles(diagram: DiagramIR) List[List[str]][source]
Find all cycles in the diagram.
- Parameters:
diagram – DiagramIR to analyze
- Returns:
List of cycles (each cycle is a list of node IDs)
- static find_paths(diagram: DiagramIR, source: str, target: str) List[List[str]][source]
Find all paths between two nodes.
- Parameters:
diagram – DiagramIR to analyze
source – Source node ID
target – Target node ID
- Returns:
List of paths (each path is a list of node IDs)
- static from_networkx(G: DiGraph) DiagramIR[source]
Convert NetworkX graph to DiagramIR.
- Parameters:
G – NetworkX directed graph
- Returns:
DiagramIR representation
- static simplify_diagram(diagram: DiagramIR, remove_redundant: bool = True) DiagramIR[source]
Simplify diagram by removing redundant edges and nodes.
- Parameters:
diagram – DiagramIR to simplify
remove_redundant – If True, remove transitive edges
- Returns:
Simplified DiagramIR
- class ij.GraphvizRenderer(layout: str = 'dot', graph_type: str = 'digraph')[source]
Renders DiagramIR to Graphviz DOT syntax.
Graphviz is the 30-year-old foundation that underpins PlantUML, Structurizr, and many other tools.
- render(diagram: DiagramIR) str[source]
Render a DiagramIR to DOT syntax.
- Parameters:
diagram – The diagram to render
- Returns:
DOT syntax as a string
- class ij.HierarchicalLayout(direction: str = 'TB', layer_spacing: float = 100, node_spacing: float = 150)[source]
Hierarchical layout using Sugiyama algorithm.
- class ij.ImageExporter(format: Literal['svg', 'png', 'pdf'] = 'svg', engine: Literal['mermaid-cli', 'playwright', 'graphviz'] = 'mermaid-cli')[source]
Export diagrams to image formats.
- check_dependencies() dict[source]
Check which rendering engines are available.
- Returns:
Dictionary of engine availability
Example
>>> exporter = ImageExporter() >>> available = exporter.check_dependencies() >>> if available['graphviz']: ... print("Graphviz is installed")
- render(diagram: DiagramIR, output_path: str, width: int | None = None, height: int | None = None, background: str = 'white', theme: str = 'default') bool[source]
Render diagram to image file.
- Parameters:
diagram – DiagramIR to render
output_path – Output file path
width – Image width in pixels (optional)
height – Image height in pixels (optional)
background – Background color
theme – Diagram theme (‘default’, ‘dark’, ‘forest’, ‘neutral’)
- Returns:
True if successful, False otherwise
Example
>>> exporter = ImageExporter(format='png', engine='mermaid-cli') >>> success = exporter.render(diagram, 'output.png', width=800)
- class ij.InteractionAnalyzer[source]
Analyze code or text to identify interaction patterns for sequence diagrams.
- analyze_function_calls(caller: str, code: str) DiagramIR[source]
Analyze function calls to create a sequence diagram.
- Parameters:
caller – The calling function/component name
code – Python code to analyze
- Returns:
DiagramIR representing the call sequence
Example
>>> analyzer = InteractionAnalyzer() >>> code = ''' ... api.authenticate(user) ... db.query(user_id) ... cache.store(result) ... ''' >>> diagram = analyzer.analyze_function_calls("client", code)
- from_text_description(text: str) DiagramIR[source]
Create sequence diagram from text description.
- Parameters:
text – Natural language description of interactions
- Returns:
DiagramIR representing the interaction sequence
Example
>>> analyzer = InteractionAnalyzer() >>> text = "User sends request to API. API queries Database. Database returns data to API. API responds to User." >>> diagram = analyzer.from_text_description(text)
- class ij.LLMConverter(api_key: str | None = None, model: str = 'gpt-4o-mini', temperature: float = 0.3)[source]
AI-powered text to diagram converter using LLMs.
Uses OpenAI API with carefully crafted prompts to generate diagrams from natural language descriptions. Supports iterative refinement.
- convert(text: str, title: str | None = None, direction: str = 'TD') DiagramIR[source]
Convert natural language to DiagramIR using LLM.
- Parameters:
text – Natural language description
title – Optional diagram title
direction – Diagram direction (TD, LR, etc.)
- Returns:
DiagramIR representation
Example
>>> converter = LLMConverter() >>> diagram = converter.convert( ... "A user logs into the system. If authentication succeeds, " ... "they see the dashboard. Otherwise, they see an error message." ... )
- convert_with_examples(text: str, examples: List[Dict[str, str]], title: str | None = None) DiagramIR[source]
Convert with few-shot examples for better quality.
- Parameters:
text – Natural language description
examples – List of {“description”: “…”, “mermaid”: “…”} examples
title – Optional diagram title
- Returns:
DiagramIR representation
- refine(diagram: DiagramIR, feedback: str, current_mermaid: str) DiagramIR[source]
Refine an existing diagram based on feedback.
- Parameters:
diagram – Current diagram
feedback – User feedback/instructions
current_mermaid – Current Mermaid representation
- Returns:
Refined DiagramIR
Example
>>> diagram = converter.convert("User login process") >>> from ij.renderers import MermaidRenderer >>> mermaid = MermaidRenderer().render(diagram) >>> refined = converter.refine( ... diagram, ... "Add a step for password reset if login fails", ... mermaid ... )
- class ij.LayoutEngine(algorithm: Literal['force-directed', 'hierarchical', 'circular', 'grid'] = 'hierarchical', **kwargs)[source]
Apply layout algorithms to diagrams.
- apply(diagram: DiagramIR) Dict[str, Tuple[float, float]][source]
Apply layout algorithm to diagram.
- Parameters:
diagram – DiagramIR to layout
- Returns:
Dictionary mapping node IDs to (x, y) positions
Example
>>> engine = LayoutEngine(algorithm='force-directed') >>> positions = engine.apply(diagram) >>> print(positions['node1']) # (x, y) (150.0, 200.0)
- exception ij.MermaidParseWarning[source]
Warns that a Mermaid line could not be interpreted and was skipped.
- class ij.MermaidParser(*, strict: bool = False)[source]
Parses Mermaid flowchart syntax to DiagramIR.
Supports basic flowchart syntax including: - Node definitions with various shapes, standalone or inline on an edge line - Edge connections with labels, including chained edges - Title metadata
A line matching none of the above is reported instead of being dropped: see
unparsed_linesand thestrictargument.- strict
Whether an unparseable line raises instead of warning
- nodes
Nodes found by the last parse, keyed by node id
- edges
Edges found by the last parse
- metadata
Diagram-level metadata (title, direction) from the last parse
- unparsed_lines
Lines the last parse could not interpret
- parse(mermaid_text: str) DiagramIR[source]
Parse Mermaid syntax to DiagramIR.
- Parameters:
mermaid_text – Mermaid flowchart syntax
- Returns:
DiagramIR representation
- Raises:
ValueError – If
strictis set and a line cannot be parsed
Example
>>> parser = MermaidParser() >>> diagram = parser.parse('''flowchart TD ... start([Start]) --> check{Ok?} ... check --|Yes|--> done([Done])''') >>> [(node.id, node.node_type.value) for node in diagram.nodes] [('start', 'start'), ('check', 'decision'), ('done', 'end')] >>> [(edge.source, edge.target, edge.label) for edge in diagram.edges] [('start', 'check', None), ('check', 'done', 'Yes')]
- class ij.MermaidRenderer(direction: str = 'TD')[source]
Renders DiagramIR to Mermaid syntax.
Supports flowchart diagrams with various node shapes and edge types.
- class ij.Node(id: str, label: str, node_type: NodeType = NodeType.PROCESS, metadata: Dict[str, ~typing.Any]=<factory>)[source]
Represents a node in the diagram IR.
- id
Unique identifier for the node
- Type:
str
- label
Display label/text
- Type:
str
- node_type
Type of node (process, decision, etc.)
- Type:
- metadata
Additional properties for extensibility
- Type:
Dict[str, Any]
- class ij.PlantUMLRenderer(use_skinparam: bool = True)[source]
Renders DiagramIR to PlantUML activity diagram syntax.
PlantUML is the enterprise standard for comprehensive UML diagrams with support for 25+ diagram types.
- class ij.PluginManager[source]
Manage and execute plugins.
- apply_transform(transform_name: str, diagram: DiagramIR, **kwargs) DiagramIR[source]
Apply a registered transform.
- Parameters:
transform_name – Name of transform
diagram – DiagramIR to transform
**kwargs – Transform arguments
- Returns:
Transformed DiagramIR
- execute_plugin(plugin_name: str, diagram: DiagramIR, **kwargs) DiagramIR[source]
Execute a plugin on a diagram.
- Parameters:
plugin_name – Name of plugin to execute
diagram – DiagramIR to process
**kwargs – Plugin-specific arguments
- Returns:
Transformed DiagramIR
- list_plugins() List[Dict[str, str]][source]
List all registered plugins.
- Returns:
List of plugin information dictionaries
- load_plugin_file(file_path: str)[source]
Load plugin from a Python file.
- Parameters:
file_path – Path to plugin file
Example
>>> manager.load_plugin_file('plugins/my_plugin.py')
- load_plugins_directory(directory: str)[source]
Load all plugins from a directory.
- Parameters:
directory – Directory containing plugin files
Example
>>> manager.load_plugins_directory('~/.ij/plugins')
- register_hook(event: str, func: Callable)[source]
Register a hook for an event.
- Parameters:
event – Event name (‘pre_render’, ‘post_parse’, etc.)
func – Hook function
Example
>>> def on_render(diagram): ... print(f"Rendering {len(diagram.nodes)} nodes") >>> manager.register_hook('pre_render', on_render)
- register_plugin(plugin: Plugin)[source]
Register a plugin.
- Parameters:
plugin – Plugin instance to register
Example
>>> class MyPlugin(Plugin): ... name = "my_plugin" ... def process(self, diagram, **kwargs): ... # Transform diagram ... return diagram >>> manager = PluginManager() >>> manager.register_plugin(MyPlugin())
- register_transform(name: str, func: Callable)[source]
Register a transform function.
- Parameters:
name – Transform name
func – Transform function (diagram, **kwargs) -> diagram
Example
>>> def highlight_critical(diagram, start, end): ... # Highlight path from start to end ... return diagram >>> manager.register_transform('highlight-critical', highlight_critical)
- class ij.PythonCodeAnalyzer[source]
Analyze Python code to generate diagrams.
Supports: - Function call graphs - Control flow diagrams - Class relationship diagrams
- analyze_class(code: str, class_name: str | None = None) DiagramIR[source]
Analyze a Python class to create a class diagram.
- Parameters:
code – Python source code
class_name – Specific class to analyze (None = first class)
- Returns:
DiagramIR representation of the class structure
- analyze_function(code: str, function_name: str | None = None) DiagramIR[source]
Analyze a Python function to create a flowchart.
- Parameters:
code – Python source code
function_name – Specific function to analyze (None = first function)
- Returns:
DiagramIR representation of the function’s control flow
Example
>>> code = ''' ... def process_order(order): ... if order.is_valid(): ... save_to_database(order) ... send_confirmation(order) ... else: ... send_error_notification(order) ... ''' >>> analyzer = PythonCodeAnalyzer() >>> diagram = analyzer.analyze_function(code)
- class ij.SequenceDiagramRenderer[source]
Render DiagramIR as Mermaid sequence diagram.
Maps DiagramIR concepts to sequence diagrams: - Nodes -> Participants - Edges -> Messages between participants - Edge labels -> Message content - EdgeType.DIRECT -> Solid arrows (synchronous) - EdgeType.CONDITIONAL -> Dashed arrows (asynchronous/return) - EdgeType.BIDIRECTIONAL -> Bidirectional arrows
- render(diagram: DiagramIR) str[source]
Render DiagramIR as Mermaid sequence diagram.
- Parameters:
diagram – DiagramIR to render
- Returns:
Mermaid sequence diagram syntax
Example
>>> from ij import DiagramIR, Node, Edge >>> diagram = DiagramIR() >>> diagram.add_node(Node(id="user", label="User")) >>> diagram.add_node(Node(id="api", label="API")) >>> diagram.add_edge(Edge(source="user", target="api", label="Request")) >>> renderer = SequenceDiagramRenderer() >>> print(renderer.render(diagram)) sequenceDiagram participant user as User participant api as API user->>api: Request
- render_with_activations(diagram: DiagramIR, activations: List[tuple]) str[source]
Render sequence diagram with participant activations.
- Parameters:
diagram – DiagramIR to render
activations – List of (participant_id, “activate”/”deactivate”) tuples
- Returns:
Mermaid sequence diagram with activations
Example
>>> activations = [("api", "activate"), ("api", "deactivate")] >>> renderer.render_with_activations(diagram, activations)
- render_with_notes(diagram: DiagramIR, notes: Dict[str, List[str]]) str[source]
Render sequence diagram with notes.
- Parameters:
diagram – DiagramIR to render
notes – Dict mapping participant IDs to list of notes
- Returns:
Mermaid sequence diagram with notes
Example
>>> notes = {"user": ["Note about user"], "api": ["API note"]} >>> renderer.render_with_notes(diagram, notes)
- class ij.SimpleTextConverter[source]
Simple rule-based text to diagram converter.
Parses structured text like: - “Start -> Process A -> Decision B” - “If condition: Process C, else: Process D”
- class ij.State(name: str, state_type: StateType = StateType.NORMAL, on_enter: str | None = None, on_exit: str | None = None, metadata: Dict = <factory>)[source]
A state in a state machine.
- class ij.StateMachine(name: str = 'StateMachine', initial_state: str | None = None)[source]
Finite State Machine diagram.
- add_state(name: str, state_type: StateType = StateType.NORMAL, on_enter: str | None = None, on_exit: str | None = None)[source]
Add a state to the machine.
- Parameters:
name – State name
state_type – Type of state (NORMAL, INITIAL, FINAL)
on_enter – Action to perform on entering state
on_exit – Action to perform on exiting state
- add_transition(from_state: str, trigger: str, to_state: str, condition: str | None = None, action: str | None = None)[source]
Add a transition between states.
- Parameters:
from_state – Source state name
trigger – Event that triggers the transition
to_state – Target state name
condition – Optional condition guard
action – Optional action to perform during transition
- get_triggers_from_state(state_name: str) List[str][source]
Get all possible triggers from a given state.
- Parameters:
state_name – State name
- Returns:
List of trigger names
- simulate(initial_state: str, events: List[str]) List[str][source]
Simulate state machine execution.
- Parameters:
initial_state – Starting state
events – List of trigger events
- Returns:
List of states visited (including initial)
- class ij.TypeScriptAnalyzer[source]
Analyze TypeScript/JavaScript code to create diagrams.
- analyze_async_flow(code: str) DiagramIR[source]
Analyze async/await flow in TypeScript/JavaScript.
- Parameters:
code – Code with async operations
- Returns:
DiagramIR showing async flow
Example
>>> code = ''' ... async function fetchData() { ... const response = await fetch('/api'); ... const data = await response.json(); ... return data; ... } ... ''' >>> diagram = analyzer.analyze_async_flow(code)
- analyze_function(code: str, function_name: str | None = None) DiagramIR[source]
Analyze TypeScript/JavaScript function to create flowchart.
- Parameters:
code – TypeScript/JavaScript code
function_name – Specific function to analyze (or first if None)
- Returns:
DiagramIR representing function flow
Example
>>> analyzer = TypeScriptAnalyzer() >>> code = ''' ... function processData(input) { ... if (input > 0) { ... return input * 2; ... } ... return 0; ... } ... ''' >>> diagram = analyzer.analyze_function(code)
- analyze_module_imports(code: str) DiagramIR[source]
Analyze TypeScript module imports/exports.
- Parameters:
code – TypeScript/JavaScript code
- Returns:
DiagramIR showing module dependencies
Example
>>> code = ''' ... import { Component } from './components'; ... import axios from 'axios'; ... export default App; ... ''' >>> diagram = analyzer.analyze_module_imports(code)
- analyze_react_component(code: str, component_name: str) DiagramIR[source]
Analyze React component to show component hierarchy.
- Parameters:
code – React component code
component_name – Name of the component
- Returns:
DiagramIR showing component structure
Example
>>> code = ''' ... function App() { ... return ( ... <div> ... <Header /> ... <Content /> ... <Footer /> ... </div> ... ); ... } ... ''' >>> diagram = analyzer.analyze_react_component(code, 'App')
- class ij.ValidationResult(is_valid: bool, issues: List[ValidationIssue])[source]
Result of diagram validation.
- property errors: List[ValidationIssue]
Get only error-level issues.
- property warnings: List[ValidationIssue]
Get only warning-level issues.
- class ij.ViewerServer(port: int = 8080, theme: str = 'default')[source]
Interactive web server for diagram viewing.
- start(diagram: DiagramIR, open_browser: bool = True)[source]
Start the viewer server.
- Parameters:
diagram – DiagramIR to display
open_browser – Whether to open browser automatically
Example
>>> server = ViewerServer(port=8080) >>> server.start(diagram) Server running at http://localhost:8080 Press Ctrl+C to stop
- ij.analyze_package_json(file_path: str) DiagramIR[source]
Analyze package.json to show dependency graph.
- Parameters:
file_path – Path to package.json
- Returns:
DiagramIR showing dependencies
Example
>>> diagram = analyze_package_json('package.json')
- ij.quick_export(diagram: DiagramIR, output_path: str, format: str = 'svg', engine: str | None = None) bool[source]
Quick export diagram to image.
- Parameters:
diagram – DiagramIR to export
output_path – Output file path
format – Image format (‘svg’, ‘png’, ‘pdf’)
engine – Rendering engine (auto-detected if None)
- Returns:
True if successful
Example
>>> from ij import DiagramIR, Node, Edge >>> diagram = DiagramIR() >>> # ... build diagram ... >>> quick_export(diagram, 'diagram.png', format='png')
- ij.register_transform(name: str)[source]
Decorator to register a transform function.
Example
>>> @register_transform('my-transform') ... def my_transform(diagram, **kwargs): ... return diagram
- ij.serve_diagram(diagram: DiagramIR, port: int = 8080, theme: str = 'default', open_browser: bool = True)[source]
Quickly serve a diagram in browser.
- Parameters:
diagram – DiagramIR to display
port – Port number
theme – Mermaid theme
open_browser – Whether to open browser
Example
>>> from ij import DiagramIR, Node, Edge >>> diagram = DiagramIR() >>> # ... build diagram ... >>> serve_diagram(diagram)
- ij.text_to_mermaid(text: str, title: str = None, direction: str = 'TD') str[source]
Convert text description to Mermaid diagram (convenience function).
- Parameters:
text – Text description of the process/flow
title – Optional diagram title
direction – Flow direction (TD, LR, etc.)
- Returns:
Mermaid syntax string
Example
>>> mermaid = text_to_mermaid("Start -> Process data -> End") >>> print(mermaid) flowchart TD n0([Start]) n1[Process data] n2([End]) n0 --> n1 n1 --> n2