npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@darioh/ai-data-visualization

v1.0.5

Published

Framework-agnostic AI-powered data visualization library

Readme

AI Data Visualization

Let users create their own charts. No more, could you please add this to the diagram bla.

A library that let's a user generate data visualization based on the specified endpoints in your backend. AI will generate the code and it will be sandboxed in an iframe. The data is getting fetched from your specified API endpoints.

Installation

npm install @darioh/ai-data-visualization

Quick Start

Basic Usage

import { create } from '@darioh/ai-data-visualization';

const viz = create({
  container: '#visualization-container',
  apiDescription: JSON.stringify(yourApiSchema),
  chatCompletion: async (message, apiDescription) => {
    // Your AI service integration (OpenAI, Claude, etc.)
    const response = await fetch('/api/ai/chat', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ message, apiDescription })
    });
    return response.text();
  },
  apiRequest: async (url) => {
    // Your API request handler
    const response = await fetch(url, {
      headers: { 'Authorization': 'Bearer ' + yourApiKey }
    });
    return response.json();
  },
  onError: (error) => console.error('Visualization error:', error)
});

Configuration Options

interface AIDataVisualizationConfig {
  // Required
  container: string | HTMLElement;          // CSS selector or DOM element
  apiDescription: string;                   // API schema as JSON string
  chatCompletion: (message: string, apiDescription: string) => Promise<string>;
  apiRequest: (url: string) => Promise<any>;

  // Optional
  onError?: (error: Error) => void;         // Error callback
  theme?: 'light' | 'dark' | 'auto';        // UI theme
  className?: string;                       // Custom CSS class
  iframeHeight?: number;                    // Iframe height in pixels (default: 600)
}

API Description Format

We will send your API endpoints to your AI-model so it can automatically generate the code for the diagrams and knows where and what to fetch.

If you want it to work then the API endpoints need to be self explanatory with good naming conventions and you will need to specify the return type for the apis! something like the following works great:

Example Endpoint description

const apiDescription =  const apiSchema = JSON.stringify({
            "openapi": "3.0.0",
            "info": {
                "title": "Weather API",
                "version": "1.0.0",
                "description": "Simple weather data API for visualizations"
            },
            "servers": [
                {
                    "url": "http://localhost:3001",
                    "description": "Local development server"
                }
            ],
            "paths": {
                "/api/cities": {
                    "get": {
                        "summary": "Get all available cities",
                        "responses": {
                            "200": {
                                "description": "List of cities with coordinates",
                                "content": {
                                    "application/json": {
                                        "schema": {
                                            "type": "object",
                                            "properties": {
                                                "success": {"type": "boolean"},
                                                "data": {
                                                    "type": "array",
                                                    "items": {
                                                        "type": "object",
                                                        "properties": {
                                                            "id": {"type": "integer"},
                                                            "name": {"type": "string"},
                                                            "country": {"type": "string"},
                                                            "lat": {"type": "number"},
                                                            "lon": {"type": "number"}
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }}}});

if you are using the format above then we will parse your endpoints end show them to the user. what you need is 1: json 2: paths 3: summary

AI Integration Examples

OpenAI

async function chatCompletion(message, apiDescription) {
  const response = await fetch('https://api.openai.com/v1/chat/completions', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${OPENAI_API_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      model: 'gpt-4',
      messages: [
        {
          role: 'system',
          content: `You are a data visualization generator. Generate HTML/CSS/JavaScript code using Chart.js for the user's request. API Description: ${apiDescription}`
        },
        {
          role: 'user',
          content: message
        }
      ]
    })
  });

  const data = await response.json();
  return data.choices[0].message.content;
}

API Methods

Instance Methods

const viz = create(config);

// Generate visualization from user input
await viz.generateVisualization();

// Clear current visualization
viz.clearVisualization();

// Change theme
viz.setTheme('dark');

// Get current state
const state = viz.getState(); // 'idle' | 'generating' | 'displaying' | 'error'

// Clean up
viz.destroy();

Styling and Customization

Custom CSS Classes

const viz = create({
  // ... other config
  className: 'my-custom-viz',
  theme: 'light'
});

"Security"

The library uses sandboxed iframes for generated visualizations with restricted permissions:

  • allow-scripts: Enables Chart.js and visualization code

Generated HTML is executed in isolation and cannot access:

  • Parent page DOM
  • Cookies or localStorage
  • Cross-origin resources (except CDN)

Example User Requests

Users can ask for visualizations in natural language:

  • "Create a bar chart showing sales by region"
  • "Generate a pie chart of user demographics"
  • "Show me a line graph of monthly revenue trends"
  • "Display employee data in a table with charts"
  • "Create an interactive dashboard for project metrics"

Error Handling

const viz = create({
  // ... config
  onError: (error) => {
    console.error('Visualization error:', error);
    
    switch (error.type) {
      case 'container-not-found':
        // Handle container issues
        break;
      case 'chat-completion-failed':
        // Handle AI service errors
        break;
      case 'api-request-failed':
        // Handle API errors
        break;
      default:
        // Handle other errors
        break;
    }
  }
});

Check out the example like so

# Clone repository
git clone https://github.com/DarioHefti/ai-data-visualization.git
cd ai-data-visualization

# Install dependencies
npm install

# Build package
npm run build

# Run development server
npm run dev

# Watch mode
npm run watch