Détail du package

@ts-graphviz/common

ts-graphviz2.1mMIT3.0.0

Graphviz Types and Utilities

graphviz, dot

readme

Main CodeQL License: MIT All Contributors OpenSSF Best Practices OpenSSF Scorecard Tidelift npm version node version deno version npm # ts-graphviz Graphviz library for TypeScript. 🔗 GitHub npm Reference Ask DeepWiki Sponsor OpenCollective format: Biome test: Vitest build: Vite

What is ts-graphviz? 🎯

ts-graphviz is a comprehensive TypeScript library that provides tools for creating, manipulating, and rendering Graphviz graph descriptions. It offers a type-safe, object-oriented approach to working with the DOT language, which is used by Graphviz for defining graph visualizations.

Key Features ✨

ts-graphviz offers several distinctive features that make it valuable for TypeScript/JavaScript developers working with graph visualizations:

  • TypeScript-friendly API
    • Provides fully typed models for the DOT language with type definitions for graph attributes.
  • Flexible Programming Paradigms
    • Supports both object-oriented and declarative approaches.
  • Multi-level API
    • Offers high-level model APIs and low-level AST manipulation.
  • Modular Design
    • Structured as separate packages for specific functionalities.
  • Cross-platform Support
    • Works in Node.js and Deno environments
  • Extensible
    • Allows extending the type system for custom graph visualization solutions.

Why ts-graphviz? 🤔

ts-graphviz is designed to make it easier for TypeScript and JavaScript developers to work with Graphviz by providing a type-safe, object-oriented API that abstracts away the complexities of the DOT language. It allows developers to create and manipulate graphs programmatically, making it suitable for both small-scale projects and large applications. It is particularly useful for applications that require dynamic graph generation, such as data visualization tools, network analysis, and more.

Getting Started 🚀

Installation 💽

Node.js

This package can then be installed using a package manager.

# npm
$ npm install -S ts-graphviz
# or yarn
$ yarn add ts-graphviz
# or pnpm
$ pnpm add ts-graphviz

Note Want to try before installing? Check out Runkit to see how it works.

Deno 🦕

Deno v1.28 and above supports npm.

You can install and use the package by specifying the following:

import { toDot } from 'npm:ts-graphviz';

Basic Usage 📖

ts-graphviz provides two main approaches to create graph visualizations:

Object-Oriented API

Create graphs using object-oriented programming with classes:

import { attribute as _, Digraph, Subgraph, Node, Edge, toDot } from 'ts-graphviz';

// Create a directed graph
const graph = new Digraph();

// Create nodes
const node1 = new Node('node1', { color: 'red' });
const node2 = new Node('node2', { color: 'blue' });

// Create an edge between the nodes
const edge = new Edge([node1, node2], { label: 'Edge Label' });

// Add elements to the graph
graph.addNode(node1);
graph.addNode(node2);
graph.addEdge(edge);

// Convert to DOT language
const dot = toDot(graph);

// Convert to DOT language
const dot = toDot(G);
// digraph {
//   "node1" [
//     color = "red",
//   ];
//   "node2" [
//     color = "blue",
//   ];
//   "node1" -> "node2" [
//     label = "Edge Label",
//   ];
// }

Declarative API (Factory Function)

Create graphs using a declarative approach with a factory function:


```ts
import { attribute as _, digraph, toDot } from 'ts-graphviz';

// Create a directed graph using the factory function
const graph = digraph('G', (g) => {
  // Create nodes within the graph context
  const a = g.node('a');
  const b = g.node('b');

  // Create an edge between nodes
  g.edge([a, b], { label: 'connects to' });

  // Create a subgraph with its own nodes and edges
  g.subgraph('A', (sg) => {
    const c = sg.node('c');
    const d = sg.node('d');
    sg.edge([c, d]);
  });
});

// Convert to DOT language
const dot = toDot(graph);
// digraph G {
//   "a";
//   "b";
//   "a" -> "b" [
//     label = "connects to",
//   ];
//   subgraph "A" {
//     "c";
//     "d";
//     "c" -> "d";
//   }
// }

Declarative API (React Component)

The @ts-graphviz/react package provides React components for creating Graphviz graphs declaratively with JSX:

import { Digraph, Node, Edge, renderToDot } from '@ts-graphviz/react';

// Define reusable components
const UserCard = ({ id, name, role }) => (
  <Node
    id={id}
    shape="record"
    label={
      <dot:table border="0" cellborder="1" cellspacing="0">
        <dot:tr>
          <dot:td bgcolor="lightblue">
            <dot:b>{name}</dot:b>
          </dot:td>
        </dot:tr>
        <dot:tr>
          <dot:td>{role}</dot:td>
        </dot:tr>
      </dot:table>
    }
  />
);

const StatusBadge = ({ status }) => (
  <dot:font color={status === 'active' ? 'green' : 'red'}>
    <dot:b>{status.toUpperCase()}</dot:b>
  </dot:font>
);

// Compose the graph
const TeamStructure = () => (
  <Digraph rankdir="TB">
    <UserCard id="alice" name="Alice Smith" role="Team Lead" />
    <UserCard id="bob" name="Bob Johnson" role="Developer" />
    <UserCard id="carol" name="Carol Davis" role="Designer" />

    <Node
      id="project"
      label={
        <>
          <dot:b>Project Alpha</dot:b><dot:br/>
          Status: <StatusBadge status="active" />
        </>
      }
      shape="box"
      style="rounded,filled"
      fillcolor="lightyellow"
    />

    <Edge targets={["alice", "bob"]} label="manages" />
    <Edge targets={["alice", "carol"]} label="manages" />
    <Edge targets={["project", "alice"]} label="assigned to" style="dashed" />
  </Digraph>
);

// Render to DOT
const dot = await renderToDot(<TeamStructure />);

[!TIP] See the @ts-graphviz/react documentation for comprehensive examples and API reference.

Useful Links 🔗

Documentation 📖

More detailed documentation and examples can be found in the following resources:

  • API Reference
    • See the API Reference for detailed documentation on how to use the library.
  • DeepWiki
    • See the AI generated documentation for more information.
    • And ask questions about the library.
  • Website
    • The official website for ts-graphviz.

Architecture 🏛

See ARCHITECTURE.md for more details.

Security 🛡️

See SECURITY.md for more details.

Package Structure 📦

The ts-graphviz repository is structured as a monorepo containing several packages, each with a specific responsibility:

Package Purpose
ts-graphviz Main entry point providing a high-level API for most users
@ts-graphviz/core Core object models for graph manipulation
@ts-graphviz/ast Parser and AST (Abstract Syntax Tree) handling for DOT language
@ts-graphviz/adapter Platform-specific implementations for rendering graphs
@ts-graphviz/common Shared types and utilities used across packages
@ts-graphviz/react React components for creating and rendering Graphviz graphs

[!TIP] Dependency graph Packages' Dependency graph

Data Flow and Processing Pipeline 🔄

The following diagram illustrates how data flows through the ts-graphviz system, from graph creation to final rendering:

Data flow

  1. Creation Phase: Users create graph models through object-oriented API, React components, or parsing DOT strings
  2. Processing Phase: Models are converted to AST and then to DOT language strings
  3. Rendering Phase: Platform-specific adapters convert DOT strings to visual output formats
    1. The adapters handle platform-specific operations, such as executing the Graphviz dot command in Node.js/Deno, while maintaining a consistent API across environments.

[!TIP] Rendering in the browser is not directly supported by this library, but you can use other libraries like @hpcc-js/wasm-graphviz to achieve rendering in the browser.

Key Data Transformations:

  • Model -> AST: Converts object model to abstract syntax tree
  • AST -> DOT: Generates DOT language string from AST
  • DOT -> AST: Parses DOT language into AST
  • AST -> Model: Converts AST back to object model
  • DOT -> Output: Uses adapters to render visual outputs

The toDot() function from the ts-graphviz package is a composite of fromModel() and stringify(), while the fromDot() function is a composite of parse() and toModel().

Who's using ts-graphviz 📜

[!NOTE] Let us know that you're using ts-graphviz on GitHub Discussions 🙏

Related Projects 💫

Related projects can be found at ts-graphviz GitHub Organization.

The TypeScript/JavaScript ecosystem provides a variety of OSS with the goal of making Graphviz more connected and easier to use.

Contributors 👥

Thanks goes to these wonderful people (emoji key):

Yuki Yamazaki
Yuki Yamazaki

💻 ⚠️ 📖 🤔
LaySent
LaySent

🐛 ⚠️
elasticdotventures
elasticdotventures

📖
Christian Murphy
Christian Murphy

💻 🤔 📖
Artem
Artem

🐛
fredericohpandolfo
fredericohpandolfo

🐛
diegoquinteiro
diegoquinteiro

🐛
robross0606
robross0606

🤔
Blake Regalia
Blake Regalia

🐛
bigbug
bigbug

💬
mrwk
mrwk

💬
svdvonde
svdvonde

💬
Adam
Adam

💬
Trevor Scheer
Trevor Scheer

️️️️♿️
Prem Pillai
Prem Pillai

🐛
nagasawaryoya
nagasawaryoya

💻 ⚠️
YukiSasaki
YukiSasaki

💻 ⚠️
Madd0g
Madd0g

🐛
j4k0xb
j4k0xb

🐛
HKrogstie
HKrogstie

🐛
Nils K
Nils K

🐛
hao2013
hao2013

🚧 👀
Walter Rafelsberger
Walter Rafelsberger

💬
grsjst
grsjst

🐛
Steve
Steve

🐛

This project follows the all-contributors specification. Contributions of any kind welcome!

How to Contribute 💪

The easiest way to contribute is to use the library and star repository.

Questions 💭

Feel free to ask questions on GitHub Discussions.

Report bugs / request additional features 💡

Please register at GitHub Issues.

Development / Bug Fixes 🧑‍💻

See CONTRIBUTING.md.

Financial Support 💸

Support this project by becoming a sponsor. Your logo will show up here with a link to your website. Become a sponsor

OpenCollective Sponsors

Thank you to all our backers! 🙏 Become a backer

OpenCollective Backers

Please support ts-graphviz on Open Collective or GitHub Sponsors.

Note Even just a dollar is enough motivation to develop 😊

ts-graphviz for Enterprise 🏢

Available as part of the Tidelift Subscription.

The maintainers of ts-graphviz and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open-source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use.

Learn more.

License ⚖️

This software is released under the MIT License, see LICENSE.

changelog

@ts-graphviz/common

3.0.0

Major Changes

  • #1363 9328563 Thanks @kamiazya! - 🚨 Breaking Changes: Drop Node.js 18 support

    Minimum required version is now Node.js 20+

    ESM-Only Distribution

    • Remove CommonJS builds: All packages now distribute only ESM (ECMAScript Modules)
    • Package exports: Removed require fields from package.json exports
    • Module type: All packages are now "type": "module"

    🔄 Migration Guide

    For ESM Projects (Recommended)

    {
      "type": "module"
    }
    
    // Import syntax remains unchanged
    import { Digraph, Node, Edge, toDot } from "ts-graphviz";
    import { toFile } from "ts-graphviz/adapter";
    import { parse } from "ts-graphviz/ast";
    

    For CommonJS Projects

    If you are using CommonJS (CJS) and need to migrate to ESM, you will need to update your project to support dynamic imports. This is necessary because the packages no longer provide CommonJS builds.

    Before (CJS)

    // JavaScript (CommonJS)
    function createGraph() {
      // Dynamic import is required because the packages no longer provide CommonJS builds.
      const { Digraph, Node, Edge, toDot } = require("ts-graphviz");
      const graph = new Digraph();
      return toDot(graph);
    }
    

    After (ESM)

    async function createGraph() {
      const { Digraph, Node, Edge, toDot } = await import("ts-graphviz");
    
      const graph = new Digraph();
      // Create your graph...
      return toDot(graph);
    }
    
    // TypeScript (CommonJS)
    // Update tsconfig.json
    {
      "compilerOptions": {
        "module": "Node16",
        "moduleResolution": "Node16"
      }
    }
    
    // Use dynamic imports
    async function createGraph() {
      const tsGraphviz = await import('ts-graphviz');
      const { Digraph, Node, Edge, toDot } = tsGraphviz;
    
      const graph = new Digraph();
      // Create your graph...
      return toDot(graph);
    }
    

    🎯 Benefits

    • Modern JavaScript: Leveraging native ES modules for better performance
    • Smaller bundle sizes: ESM enables better tree-shaking
    • Future-proof: Aligning with the JavaScript ecosystem direction
    • Better TypeScript support: Enhanced module resolution

Minor Changes

  • #1363 9328563 Thanks @kamiazya! - Define Supported environment and Support levels

    To provide clarity on the environments in which ts-graphviz operates, we have categorized support levels:

    Support Levels

    Tier 1: Full Support

    • Definition: Environments that are fully supported, with comprehensive automated testing and maintenance.
    • Environments:
      • Node.js LTS versions: All active Long-Term Support (LTS) versions.
        • If a Node.js LTS version is released, we will ensure compatibility with it.
        • If a Node.js LTS version is deprecated, we will drop support for it in the next major release.
    • Details:
      • We run automated tests on all LTS versions of Node.js.
      • Full compatibility and performance are ensured.
      • Critical issues are prioritized for fixes.

    Tier 2: Active Support

    • Definition: Environments that receive active support with limited automated testing.
    • Environments:
      • Deno Latest LTS version: The latest Long-Term Support (LTS) version of Deno.
        • If a new Deno LTS version is released, we will ensure compatibility with it.
        • If a Deno LTS version is deprecated, we will drop support for it in the next minor release.
      • Node.js Current Release: The latest Node.js release outside the LTS schedule.
        • If a new Node.js current release is available, we will ensure compatibility with it.
        • If a Node.js current release is deprecated, we will drop support for it in the next minor release.
    • Details:
      • Compatibility is maintained, and issues are addressed.

    Tier 3: Community Support

    • Definition: Environments that are not officially tested but are supported on a best-effort basis.
    • Environments:
      • Modern Browsers: Latest versions of major browsers, including:
        • Google Chrome
        • Mozilla Firefox
        • Microsoft Edge
        • Apple Safari
      • Deno Current Release: The latest Deno release outside the LTS schedule.
    • Details:
      • Installation methods are provided.
      • No automated testing is performed.
      • Issues reported by users will be addressed.
      • Targeting the latest versions ensures compatibility with modern web standards.
      • We will not actively test or maintain compatibility with older versions of browsers.
  • #1363 9328563 Thanks @kamiazya! - Export type guard and node reference utility APIs

    New Public APIs

    Type Guard Functions

    • isNodeModel(object: unknown): object is NodeModel - Type guard for NodeModel objects
    • isEdgeModel(object: unknown): object is EdgeModel - Type guard for EdgeModel objects
    • isSubgraphModel(object: unknown): object is SubgraphModel - Type guard for SubgraphModel objects
    • isRootGraphModel(object: unknown): object is RootGraphModel - Type guard for RootGraphModel objects
    • isAttributeListModel(object: unknown): object is AttributeListModel - Type guard for AttributeListModel objects

    Node Reference Utilities

    • isForwardRefNode(object: unknown): object is ForwardRefNode - Type guard for ForwardRefNode objects
    • isNodeRef(node: unknown): node is NodeRef - Type guard for NodeRef objects (NodeModel or ForwardRefNode)
    • isNodeRefLike(node: unknown): node is NodeRefLike - Type guard for NodeRefLike objects (string or NodeRef)
    • isNodeRefGroupLike(target: NodeRefLike | NodeRefGroupLike): target is NodeRefGroupLike - Type guard for arrays of NodeRefLike
    • isCompass(c: string): c is Compass - Type guard for valid compass directions ('n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw', 'c')

    Conversion Utilities

    • toNodeRef(target: NodeRefLike): NodeRef - Converts NodeRefLike to structured NodeRef object
    • toNodeRefGroup(targets: NodeRefGroupLike): NodeRefGroup - Converts array of NodeRefLike to array of NodeRef objects

    New Types

    • FilterableModel - Union type of all model types that can be filtered using type guards

    Features

    • Enhanced Type Safety: All functions provide strict runtime type checking with TypeScript type narrowing
    • Comprehensive Documentation: Full JSDoc comments with usage examples for all public APIs
    • Node Reference Parsing: Parse complex node reference strings like "node1:port:n" into structured objects
    • Compass Direction Validation: Validate and work with Graphviz compass directions

Patch Changes

  • #1363 9328563 Thanks @kamiazya! - Update Develop Environment

    • Drop turbo
    • Upgrade biome to 2.0
    • Upgrade TypeScript to 5.8
    • Upgrade Vite to 7.0
    • Upgrade Vitest to 3.2
    • Upgrade Peggy to 5.0 and drop ts-pegjs
    • Implement new E2E test workflow
  • #1363 9328563 Thanks @kamiazya! - New GitHub Action main workflow and tests

2.1.5

Patch Changes

2.1.4

Patch Changes

2.1.3

Patch Changes

2.1.2

Patch Changes

2.1.1

Patch Changes

2.1.0

Minor Changes

Patch Changes

2.0.0

It is part of the ts-graphviz library, which is split into modular packages to improve maintainability, flexibility, and ease of use.

This package contains type information, constants, and utility functions related to the DOT language attributes, attribute values, and models for ts-graphviz.

Features

  • Type definitions for DOT language elements, such as attributes and attribute values
  • Constants representing common attribute names and values
  • Utility functions for working with DOT language elements

Usage

Import the necessary types, constants, or utility functions from the @ts-graphviz/common package:

import {
  NodeAttributesObject,
  EdgeAttributesObject,
} from "@ts-graphviz/common";

Use the imported items in your project to work with the DOT language elements:

const nodeAttr: NodeAttributesObject = {
  label: "Node label",
  shape: "ellipse",
};

const edgeAttr: EdgeAttributesObject = {
  label: "Edge label",
  color: "red",
};