Skip to content

AI Agent Skill to generate and render beautiful Mermaid diagrams as SVG or terminal ASCII — 15 themes, 6 diagram types, batch CLI, no browser.

Refactor: Migrate Mermaid rendering, batch processing, and theme listing scripts from Python to Node.js, updating documentation and dependencies.

sunmozong6fc38c7962b0
diff --git a/README.md b/README.md
index 81a9114..8a44646 100644
--- a/README.md
+++ b/README.md
@@ -1,49 +1,68 @@
-# Beautiful-Mermaid Skill for Claude
+# Beautiful-Mermaid Skills
## 简介
为 Claude AI 提供的 Mermaid 图表渲染 Skill,支持 SVG 和 ASCII 双格式输出。
## 功能特性
-- 📊 SVG 和 ASCII 渲染
-- 🎨 14 个精美主题(tokyo-night, dracula, github-dark...)
-- 📈 5 种图表类型(Flowchart, Sequence, State, Class, ER)
-- ⚡ 批量并行渲染
+- 📊 支持 SVG 和 ASCII 渲染导出
+- 🎨 15 种主题选择(zinc-light
+
+zinc-dark
+
+tokyo-night
+
+tokyo-night-storm
+
+tokyo-night-light
+
+cappuccin-mocha
+
+cappuccin-latte
+
+nord
+
+nord-light
+
+dracula
+
+github-light
+
+github-dark
+
+solarized-light
+
+solarized-dark
+
+one-dark)
+- 📈 支持 5 种图表类型(Flowchart, Sequence, State, Class, ER)
+- ⚡ 支持批量并行渲染
- 📚 完整的模板和文档
## 安装步骤
-### 1. 安装到 Claude Skills 目录
+### 1. 安装到 Skills 目录
```bash
-cd ~/.claude/skills
-git clone https://github.com/[用户名]/beautiful-mermaid.git
+npx skills add https://github.com/intellectronica/agent-skills --skill Pretty-mermaid
```
-### 2. 安装依赖
-```bash
-# 安装 Node.js(如果未安装)
-# macOS: brew install node
-# Ubuntu: sudo apt install nodejs npm
-
-# 安装 beautiful-mermaid
-npm install -g beautiful-mermaid
-```
-
-### 3. 验证安装
+### 2. 验证安装
```bash
cd beautiful-mermaid
-python3 scripts/list_themes.py
+node scripts/themes.mjs
```
+> **首次运行时会自动安装依赖,只需 Node.js 环境。**
+
## 快速开始
### 列出可用主题
```bash
-python3 scripts/list_themes.py
+node scripts/themes.mjs
```
### 渲染单个图表
```bash
-python3 scripts/render_mermaid.py \
+node scripts/render.mjs \
--input diagram.mmd \
--output output.svg \
--theme tokyo-night
@@ -51,7 +70,7 @@ python3 scripts/render_mermaid.py \
### 批量渲染
```bash
-python3 scripts/batch_render.py \
+node scripts/batch.mjs \
--input-dir ./diagrams \
--output-dir ./output \
--theme dracula
@@ -72,9 +91,7 @@ python3 scripts/batch_render.py \
## 系统要求
-- Python 3.7+
- Node.js 14+
-- npm 或 yarn
## 许可证
diff --git a/SKILL.md b/SKILL.md
index 17a7b4a..3a7cd48 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -23,7 +23,7 @@ Render stunning, professionally-styled Mermaid diagrams with one command. Suppor
**From a file:**
```bash
-python scripts/render_mermaid.py \
+node scripts/render.mjs \
--input diagram.mmd \
--output diagram.svg \
--format svg \
@@ -37,7 +37,7 @@ python scripts/render_mermaid.py \
### Batch Render Multiple Diagrams
```bash
-python scripts/batch_render.py \
+node scripts/batch.mjs \
--input-dir ./diagrams \
--output-dir ./output \
--format svg \
@@ -48,7 +48,7 @@ python scripts/batch_render.py \
### ASCII Output (Terminal-Friendly)
```bash
-python scripts/render_mermaid.py \
+node scripts/render.mjs \
--input diagram.mmd \
--format ascii \
--use-ascii
@@ -72,7 +72,7 @@ python scripts/render_mermaid.py \
- **Dark mode docs** → `tokyo-night` (recommended)
- **Light mode docs** → `github-light`
- **Vibrant colors** → `dracula`
-- **See all themes** → Run `python scripts/list_themes.py`
+- **See all themes** → Run `node scripts/themes.mjs`
---
@@ -92,7 +92,7 @@ When user provides a `.mmd` file or Mermaid code block:
2. **Render with theme**:
```bash
- python scripts/render_mermaid.py \
+ node scripts/render.mjs \
--input diagram.mmd \
--output diagram.svg \
--theme tokyo-night
@@ -122,7 +122,7 @@ When user provides a `.mmd` file or Mermaid code block:
**Custom Colors** (overrides theme):
```bash
-python scripts/render_mermaid.py \
+node scripts/render.mjs \
--input diagram.mmd \
--bg "#1a1b26" \
--fg "#a9b1d6" \
@@ -132,7 +132,7 @@ python scripts/render_mermaid.py \
**Transparent Background**:
```bash
-python scripts/render_mermaid.py \
+node scripts/render.mjs \
--input diagram.mmd \
--transparent \
--output transparent.svg
@@ -140,7 +140,7 @@ python scripts/render_mermaid.py \
**Custom Font**:
```bash
-python scripts/render_mermaid.py \
+node scripts/render.mjs \
--input diagram.mmd \
--font "JetBrains Mono" \
--output custom-font.svg
@@ -166,7 +166,7 @@ cp assets/example_diagrams/flowchart.mmd my-workflow.mmd
**Step 3: Render**
```bash
-python scripts/render_mermaid.py \
+node scripts/render.mjs \
--input my-workflow.mmd \
--output my-workflow.svg \
--theme github-dark
@@ -233,7 +233,7 @@ EOF
**Step 3: Render and iterate**
```bash
-python scripts/render_mermaid.py \
+node scripts/render.mjs \
--input user-diagram.mmd \
--output preview.svg \
--theme tokyo-night
@@ -248,7 +248,7 @@ python scripts/render_mermaid.py \
### List Available Themes
```bash
-python scripts/list_themes.py
+node scripts/themes.mjs
```
**Output:**
@@ -292,7 +292,7 @@ Total: 15 themes
### Apply Theme to Diagram
```bash
-python scripts/render_mermaid.py \
+node scripts/render.mjs \
--input diagram.mmd \
--output themed.svg \
--theme tokyo-night
@@ -303,7 +303,7 @@ python scripts/render_mermaid.py \
Render the same diagram with multiple themes:
```bash
for theme in tokyo-night dracula github-dark; do
- python scripts/render_mermaid.py \
+ node scripts/render.mjs \
--input diagram.mmd \
--output "diagram-${theme}.svg" \
--theme "$theme"
@@ -326,7 +326,7 @@ diagrams/
**Step 2: Batch render**
```bash
-python scripts/batch_render.py \
+node scripts/batch.mjs \
--input-dir ./diagrams \
--output-dir ./rendered \
--format svg \
@@ -349,14 +349,14 @@ Found 3 diagram(s) to render...
Render both SVG and ASCII:
```bash
# SVG for docs
-python scripts/batch_render.py \
+node scripts/batch.mjs \
--input-dir ./diagrams \
--output-dir ./svg \
--format svg \
--theme github-dark
# ASCII for README
-python scripts/batch_render.py \
+node scripts/batch.mjs \
--input-dir ./diagrams \
--output-dir ./ascii \
--format ascii \
@@ -379,7 +379,7 @@ python scripts/batch_render.py \
# → Create flowchart.mmd
# → Render with professional theme
-python scripts/render_mermaid.py \
+node scripts/render.mjs \
--input architecture.mmd \
--output docs/architecture.svg \
--theme github-dark \
@@ -393,7 +393,7 @@ python scripts/render_mermaid.py \
# → Create sequence.mmd
# → Render with clear theme
-python scripts/render_mermaid.py \
+node scripts/render.mjs \
--input api-flow.mmd \
--output api-sequence.svg \
--theme tokyo-night
@@ -406,7 +406,7 @@ python scripts/render_mermaid.py \
# → Create er.mmd
# → Render for database docs
-python scripts/render_mermaid.py \
+node scripts/render.mjs \
--input schema.mmd \
--output database-schema.svg \
--theme dracula
@@ -416,7 +416,7 @@ python scripts/render_mermaid.py \
```bash
# For README or terminal display
-python scripts/render_mermaid.py \
+node scripts/render.mjs \
--input workflow.mmd \
--format ascii \
--use-ascii > workflow.txt
@@ -426,7 +426,7 @@ python scripts/render_mermaid.py \
```bash
# High-contrast for projectors
-python scripts/render_mermaid.py \
+node scripts/render.mjs \
--input slides-diagram.mmd \
--output presentation.svg \
--theme zinc-light
@@ -436,19 +436,13 @@ python scripts/render_mermaid.py \
## Troubleshooting
-### Node.js Not Found
-```
-Error: Node.js not found. Please install Node.js to use this tool.
-```
-**Solution:** Install Node.js from https://nodejs.org/
-
### beautiful-mermaid Not Installed
```
Error: Cannot find module 'beautiful-mermaid'
```
-**Solution:**
+**Note:** This should auto-install on first run. If it fails:
```bash
-npm install -g beautiful-mermaid
+cd /path/to/beautiful-mermaid-skill && npm install
```
### Invalid Mermaid Syntax
@@ -474,11 +468,10 @@ Error: Input file not found: diagram.mmd
## Resources
### scripts/
-Executable Python and Node.js scripts for rendering operations:
-- `render_mermaid.py` - Main rendering script
-- `batch_render.py` - Batch processing script
-- `list_themes.py` - Theme listing utility
-- `render_helper.mjs` - Node.js bridge to beautiful-mermaid
+Executable Node.js scripts for rendering operations:
+- `render.mjs` - Main rendering script
+- `batch.mjs` - Batch processing script
+- `themes.mjs` - Theme listing utility
### references/
Documentation to inform diagram creation:
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..4316752
--- /dev/null
+++ b/package.json
@@ -0,0 +1,14 @@
+{
+ "name": "beautiful-mermaid-skill",
+ "version": "1.0.0",
+ "private": true,
+ "type": "module",
+ "bin": {
+ "render-mermaid": "./scripts/render.mjs",
+ "batch-mermaid": "./scripts/batch.mjs",
+ "list-mermaid-themes": "./scripts/themes.mjs"
+ },
+ "dependencies": {
+ "beautiful-mermaid": "^0.1.3"
+ }
+}
diff --git a/requirements.txt b/requirements.txt
deleted file mode 100644
index f9ec85c..0000000
--- a/requirements.txt
+++ /dev/null
@@ -1,13 +0,0 @@
-# Beautiful-Mermaid Skill - Python Dependencies
-# This skill requires no additional Python packages (uses only standard library)
-
-# System Dependencies:
-# - Node.js >= 14.0.0
-# - npm or yarn
-
-# Installation:
-# 1. npm install -g beautiful-mermaid@^0.1.3
-# 2. Ensure Node.js and npm are installed on your system
-
-# No Python packages are required for this skill to function.
-# All rendering is handled by the Node.js beautiful-mermaid library via subprocess calls.
diff --git a/scripts/batch.mjs b/scripts/batch.mjs
new file mode 100644
index 0000000..7e4d154
--- /dev/null
+++ b/scripts/batch.mjs
@@ -0,0 +1,175 @@
+#!/usr/bin/env node
+
+import { execSync } from 'child_process';
+import { dirname, join, resolve } from 'path';
+import { fileURLToPath } from 'url';
+import { readFileSync, writeFileSync, existsSync, mkdirSync, readdirSync } from 'fs';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const skillRoot = join(__dirname, '..');
+
+async function loadBeautifulMermaid() {
+ try {
+ return await import('beautiful-mermaid');
+ } catch {}
+
+ console.error('[beautiful-mermaid] Dependency not found. Installing automatically...');
+ try {
+ execSync('npm install --no-fund --no-audit', {
+ cwd: skillRoot,
+ stdio: ['pipe', 'pipe', 'inherit'],
+ timeout: 120000,
+ });
+ console.error('[beautiful-mermaid] Installed successfully.\n');
+ } catch (e) {
+ console.error(`[beautiful-mermaid] Auto-install failed: ${e.message}`);
+ console.error(`Manual fix: cd ${skillRoot} && npm install`);
+ process.exit(1);
+ }
+
+ try {
+ const pkgPath = join(skillRoot, 'node_modules', 'beautiful-mermaid', 'dist', 'index.js');
+ return await import(pkgPath);
+ } catch (e) {
+ console.error(`[beautiful-mermaid] Failed to load after install: ${e.message}`);
+ process.exit(1);
+ }
+}
+
+function parseArgs() {
+ const args = process.argv.slice(2);
+ const opts = {
+ inputDir: null,
+ outputDir: null,
+ format: 'svg',
+ theme: null,
+ bg: null,
+ fg: null,
+ transparent: false,
+ useAscii: false,
+ workers: 4,
+ };
+
+ for (let i = 0; i < args.length; i++) {
+ const key = args[i];
+ const val = args[i + 1];
+
+ switch (key) {
+ case '--input-dir': case '-i': opts.inputDir = val; i++; break;
+ case '--output-dir': case '-o': opts.outputDir = val; i++; break;
+ case '--format': case '-f': opts.format = val; i++; break;
+ case '--theme': case '-t': opts.theme = val; i++; break;
+ case '--bg': opts.bg = val; i++; break;
+ case '--fg': opts.fg = val; i++; break;
+ case '--transparent': opts.transparent = true; break;
+ case '--use-ascii': opts.useAscii = true; break;
+ case '--workers': case '-w': opts.workers = parseInt(val); i++; break;
+ case '--help': case '-h':
+ console.log(`Usage: node batch.mjs --input-dir <dir> --output-dir <dir> [options]
+
+Options:
+ -i, --input-dir <dir> Input directory containing .mmd files [required]
+ -o, --output-dir <dir> Output directory for rendered files [required]
+ -f, --format <fmt> Output format: svg | ascii (default: svg)
+ -t, --theme <name> Theme name (e.g. tokyo-night, dracula)
+ --bg <hex> Background color
+ --fg <hex> Foreground color
+ --transparent Transparent background (SVG only)
+ --use-ascii Pure ASCII instead of Unicode (ASCII only)
+ -w, --workers <n> Parallel workers (default: 4)`);
+ process.exit(0);
+ }
+ }
+
+ if (!opts.inputDir) {
+ console.error('Error: --input-dir is required. Use --help for usage.');
+ process.exit(1);
+ }
+ if (!opts.outputDir) {
+ console.error('Error: --output-dir is required. Use --help for usage.');
+ process.exit(1);
+ }
+ if (!existsSync(opts.inputDir)) {
+ console.error(`Error: Input directory not found: ${opts.inputDir}`);
+ process.exit(1);
+ }
+
+ return opts;
+}
+
+async function renderFile(file, inputDir, outputDir, opts, lib) {
+ const { renderMermaid, renderMermaidAscii, THEMES } = lib;
+ const inputPath = join(inputDir, file);
+ const ext = opts.format === 'svg' ? '.svg' : '.txt';
+ const outputPath = join(outputDir, file.replace(/\.mmd$/, ext));
+ const input = readFileSync(inputPath, 'utf8');
+
+ if (opts.format === 'ascii') {
+ const ascii = renderMermaidAscii(input, { useAscii: opts.useAscii });
+ writeFileSync(outputPath, ascii);
+ } else {
+ const theme = opts.theme ? THEMES[opts.theme] : undefined;
+ const colors = theme || {
+ ...(opts.bg && { bg: opts.bg }),
+ ...(opts.fg && { fg: opts.fg }),
+ };
+
+ const svg = await renderMermaid(input, {
+ ...colors,
+ transparent: opts.transparent,
+ });
+ writeFileSync(outputPath, svg);
+ }
+}
+
+async function main() {
+ const opts = parseArgs();
+ const lib = await loadBeautifulMermaid();
+
+ mkdirSync(opts.outputDir, { recursive: true });
+
+ const files = readdirSync(opts.inputDir).filter(f => f.endsWith('.mmd'));
+ if (files.length === 0) {
+ console.error(`No .mmd files found in ${opts.inputDir}`);
+ process.exit(1);
+ }
+
+ console.log(`Found ${files.length} diagram(s) to render...`);
+
+ let success = 0;
+ const failed = [];
+
+ // Process in batches of `workers` size
+ for (let i = 0; i < files.length; i += opts.workers) {
+ const batch = files.slice(i, i + opts.workers);
+ const results = await Promise.allSettled(
+ batch.map(file => renderFile(file, opts.inputDir, opts.outputDir, opts, lib))
+ );
+
+ results.forEach((result, idx) => {
+ const file = batch[idx];
+ if (result.status === 'fulfilled') {
+ console.log(`\u2713 ${file}`);
+ success++;
+ } else {
+ console.error(`\u2717 ${file}: ${result.reason?.message || result.reason}`);
+ failed.push([file, result.reason?.message || String(result.reason)]);
+ }
+ });
+ }
+
+ console.log(`\n${success}/${files.length} diagrams rendered successfully`);
+
+ if (failed.length > 0) {
+ console.error(`\n${failed.length} failed:`);
+ for (const [file, error] of failed) {
+ console.error(` - ${file}: ${error}`);
+ }
+ process.exit(1);
+ }
+}
+
+main().catch(e => {
+ console.error('Error:', e.message);
+ process.exit(1);
+});
diff --git a/scripts/batch_render.py b/scripts/batch_render.py
deleted file mode 100644
index 4883188..0000000
--- a/scripts/batch_render.py
+++ /dev/null
@@ -1,170 +0,0 @@
-#!/usr/bin/env python3
-"""
-Batch render multiple Mermaid diagrams.
-
-Usage:
- python batch_render.py --input-dir ./diagrams --output-dir ./output --format svg --theme tokyo-night
-"""
-
-import argparse
-import shutil
-import subprocess
-import sys
-from pathlib import Path
-from concurrent.futures import ThreadPoolExecutor, as_completed
-
-
-def render_file(input_file, output_dir, args):
- """Render a single Mermaid file."""
- output_ext = '.svg' if args.format == 'svg' else '.txt'
- output_file = output_dir / (input_file.stem + output_ext)
-
- # Build command
- helper_script = Path(__file__).parent / 'render_helper.mjs'
- cmd = [
- 'node', str(helper_script), 'render',
- '--input', str(input_file),
- '--output', str(output_file),
- '--format', args.format
- ]
-
- if args.theme:
- cmd.extend(['--theme', args.theme])
-
- if args.bg:
- cmd.extend(['--bg', args.bg])
-
- if args.fg:
- cmd.extend(['--fg', args.fg])
-
- if args.transparent:
- cmd.extend(['--transparent', 'true'])
-
- if args.use_ascii:
- cmd.extend(['--use-ascii', 'true'])
-
- try:
- result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
- if result.returncode == 0:
- return (input_file.name, True, None)
- else:
- return (input_file.name, False, result.stderr)
- except Exception as e:
- return (input_file.name, False, str(e))
-
-
-def main():
- parser = argparse.ArgumentParser(
- description='Batch render Mermaid diagrams'
- )
-
- parser.add_argument(
- '--input-dir', '-i',
- required=True,
- help='Input directory containing .mmd files'
- )
-
- parser.add_argument(
- '--output-dir', '-o',
- required=True,
- help='Output directory for rendered files'
- )
-
- parser.add_argument(
- '--format', '-f',
- choices=['svg', 'ascii'],
- default='svg',
- help='Output format (default: svg)'
- )
-
- parser.add_argument(
- '--theme', '-t',
- help='Built-in theme name'
- )
-
- parser.add_argument(
- '--bg',
- help='Background color (hex)'
- )
-
- parser.add_argument(
- '--fg',
- help='Foreground color (hex)'
- )
-
- parser.add_argument(
- '--transparent',
- action='store_true',
- help='Render with transparent background (SVG only)'
- )
-
- parser.add_argument(
- '--use-ascii',
- action='store_true',
- help='Use pure ASCII instead of Unicode (ASCII format only)'
- )
-
- parser.add_argument(
- '--workers', '-w',
- type=int,
- default=4,
- help='Number of parallel workers (default: 4)'
- )
-
- args = parser.parse_args()
-
- # Validate input directory
- input_dir = Path(args.input_dir)
- if not input_dir.exists():
- print(f"Error: Input directory not found: {args.input_dir}", file=sys.stderr)
- sys.exit(1)
-
- # Check for Node.js dependency
- if not shutil.which('node'):
- print("Error: Node.js is required but not found in PATH.", file=sys.stderr)
- sys.exit(1)
-
- # Create output directory
- output_dir = Path(args.output_dir)
- output_dir.mkdir(parents=True, exist_ok=True)
-
- # Find all .mmd files
- mmd_files = list(input_dir.glob('*.mmd'))
-
- if not mmd_files:
- print(f"No .mmd files found in {args.input_dir}", file=sys.stderr)
- sys.exit(1)
-
- print(f"Found {len(mmd_files)} diagram(s) to render...")
-
- # Render in parallel
- success_count = 0
- failed = []
-
- with ThreadPoolExecutor(max_workers=args.workers) as executor:
- futures = {
- executor.submit(render_file, mmd_file, output_dir, args): mmd_file
- for mmd_file in mmd_files
- }
-
- for future in as_completed(futures):
- filename, success, error = future.result()
- if success:
- print(f"✓ {filename}")
- success_count += 1
- else:
- print(f"✗ {filename}: {error}", file=sys.stderr)
- failed.append((filename, error))
-
- # Summary
- print(f"\n{success_count}/{len(mmd_files)} diagrams rendered successfully")
-
- if failed:
- print(f"\n{len(failed)} failed:")
- for filename, error in failed:
- print(f" - {filename}: {error}")
- sys.exit(1)
-
-
-if __name__ == '__main__':
- main()
diff --git a/scripts/list_themes.py b/scripts/list_themes.py
deleted file mode 100644
index 6f98232..0000000
--- a/scripts/list_themes.py
+++ /dev/null
@@ -1,48 +0,0 @@
-#!/usr/bin/env python3
-"""
-List all available beautiful-mermaid themes.
-
-Usage:
- python list_themes.py
-"""
-
-import subprocess
-import json
-import sys
-from pathlib import Path
-
-
-def main():
- helper_script = Path(__file__).parent / 'render_helper.mjs'
- cmd = ['node', str(helper_script), 'list-themes']
-
- try:
- result = subprocess.run(cmd, capture_output=True, text=True)
-
- if result.returncode != 0:
- print(f"Error: {result.stderr}", file=sys.stderr)
- sys.exit(1)
-
- themes = json.loads(result.stdout)
-
- print("Available Beautiful-Mermaid Themes:\n")
- for i, theme in enumerate(themes, 1):
- print(f"{i:2d}. {theme}")
-
- print(f"\nTotal: {len(themes)} themes")
- print("\nUsage:")
- print(" python render_mermaid.py --input diagram.mmd --theme <theme-name> --output output.svg")
-
- except FileNotFoundError:
- print("Error: Node.js not found. Please install Node.js to use this tool.", file=sys.stderr)
- sys.exit(1)
- except json.JSONDecodeError:
- print("Error: Could not parse theme list", file=sys.stderr)
- sys.exit(1)
- except Exception as e:
- print(f"Error: {e}", file=sys.stderr)
- sys.exit(1)
-
-
-if __name__ == '__main__':
- main()
diff --git a/scripts/render.mjs b/scripts/render.mjs
new file mode 100644
index 0000000..3082c44
--- /dev/null
+++ b/scripts/render.mjs
@@ -0,0 +1,164 @@
+#!/usr/bin/env node
+
+import { execSync } from 'child_process';
+import { dirname, join, resolve } from 'path';
+import { fileURLToPath } from 'url';
+import { readFileSync, writeFileSync, existsSync } from 'fs';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const skillRoot = join(__dirname, '..');
+
+async function loadBeautifulMermaid() {
+ try {
+ return await import('beautiful-mermaid');
+ } catch {}
+
+ console.error('[beautiful-mermaid] Dependency not found. Installing automatically...');
+ try {
+ execSync('npm install --no-fund --no-audit', {
+ cwd: skillRoot,
+ stdio: ['pipe', 'pipe', 'inherit'],
+ timeout: 120000,
+ });
+ console.error('[beautiful-mermaid] Installed successfully.\n');
+ } catch (e) {
+ console.error(`[beautiful-mermaid] Auto-install failed: ${e.message}`);
+ console.error(`Manual fix: cd ${skillRoot} && npm install`);
+ process.exit(1);
+ }
+
+ try {
+ const pkgPath = join(skillRoot, 'node_modules', 'beautiful-mermaid', 'dist', 'index.js');
+ return await import(pkgPath);
+ } catch (e) {
+ console.error(`[beautiful-mermaid] Failed to load after install: ${e.message}`);
+ process.exit(1);
+ }
+}
+
+function parseArgs() {
+ const args = process.argv.slice(2);
+ const opts = {
+ input: null,
+ output: null,
+ format: 'svg',
+ theme: null,
+ bg: '#FFFFFF',
+ fg: '#27272A',
+ font: 'Inter',
+ transparent: false,
+ useAscii: false,
+ paddingX: 5,
+ paddingY: 5,
+ boxBorderPadding: 1,
+ };
+
+ for (let i = 0; i < args.length; i++) {
+ const key = args[i];
+ const val = args[i + 1];
+
+ switch (key) {
+ case '--input': case '-i': opts.input = val; i++; break;
+ case '--output': case '-o': opts.output = val; i++; break;
+ case '--format': case '-f': opts.format = val; i++; break;
+ case '--theme': case '-t': opts.theme = val; i++; break;
+ case '--bg': opts.bg = val; i++; break;
+ case '--fg': opts.fg = val; i++; break;
+ case '--line': opts.line = val; i++; break;
+ case '--accent': opts.accent = val; i++; break;
+ case '--muted': opts.muted = val; i++; break;
+ case '--surface': opts.surface = val; i++; break;
+ case '--border': opts.border = val; i++; break;
+ case '--font': opts.font = val; i++; break;
+ case '--transparent': opts.transparent = true; break;
+ case '--use-ascii': opts.useAscii = true; break;
+ case '--padding-x': opts.paddingX = parseInt(val); i++; break;
+ case '--padding-y': opts.paddingY = parseInt(val); i++; break;
+ case '--box-border-padding': opts.boxBorderPadding = parseInt(val); i++; break;
+ case '--help': case '-h':
+ console.log(`Usage: node render.mjs --input <file> [options]
+
+Options:
+ -i, --input <file> Input Mermaid file (.mmd) [required]
+ -o, --output <file> Output file (default: stdout)
+ -f, --format <fmt> Output format: svg | ascii (default: svg)
+ -t, --theme <name> Theme name (e.g. tokyo-night, dracula)
+ --bg <hex> Background color
+ --fg <hex> Foreground color
+ --line <hex> Edge/connector color
+ --accent <hex> Arrow heads and highlights color
+ --muted <hex> Secondary text color
+ --surface <hex> Node fill tint color
+ --border <hex> Node stroke color
+ --font <name> Font family (default: Inter)
+ --transparent Transparent background (SVG only)
+ --use-ascii Pure ASCII instead of Unicode (ASCII only)
+ --padding-x <n> Horizontal spacing (ASCII only, default: 5)
+ --padding-y <n> Vertical spacing (ASCII only, default: 5)
+ --box-border-padding <n> Padding inside node boxes (ASCII only, default: 1)`);
+ process.exit(0);
+ }
+ }
+
+ if (!opts.input) {
+ console.error('Error: --input is required. Use --help for usage.');
+ process.exit(1);
+ }
+
+ if (!existsSync(opts.input)) {
+ console.error(`Error: Input file not found: ${opts.input}`);
+ process.exit(1);
+ }
+
+ return opts;
+}
+
+async function main() {
+ const opts = parseArgs();
+ const { renderMermaid, renderMermaidAscii, THEMES } = await loadBeautifulMermaid();
+ const input = readFileSync(opts.input, 'utf8');
+
+ if (opts.format === 'ascii') {
+ const ascii = renderMermaidAscii(input, {
+ useAscii: opts.useAscii,
+ paddingX: opts.paddingX,
+ paddingY: opts.paddingY,
+ boxBorderPadding: opts.boxBorderPadding,
+ });
+ if (opts.output) {
+ writeFileSync(opts.output, ascii);
+ console.log(`ASCII diagram saved to ${opts.output}`);
+ } else {
+ console.log(ascii);
+ }
+ } else {
+ const theme = opts.theme ? THEMES[opts.theme] : undefined;
+ const colors = theme || {
+ bg: opts.bg,
+ fg: opts.fg,
+ ...(opts.line && { line: opts.line }),
+ ...(opts.accent && { accent: opts.accent }),
+ ...(opts.muted && { muted: opts.muted }),
+ ...(opts.surface && { surface: opts.surface }),
+ ...(opts.border && { border: opts.border }),
+ };
+
+ const svg = await renderMermaid(input, {
+ ...colors,
+ font: opts.font,
+ transparent: opts.transparent,
+ });
+
+ if (opts.output) {
+ writeFileSync(opts.output, svg);
+ console.log(`SVG diagram saved to ${opts.output}`);
+ } else {
+ console.log(svg);
+ }
+ }
+}
+
+main().catch(e => {
+ console.error('Error:', e.message);
+ process.exit(1);
+});
diff --git a/scripts/render_helper.mjs b/scripts/render_helper.mjs
deleted file mode 100644
index 66eb500..0000000
--- a/scripts/render_helper.mjs
+++ /dev/null
@@ -1,165 +0,0 @@
-#!/usr/bin/env node
-
-/**
- * Node.js helper for beautiful-mermaid rendering
- * Called by Python wrapper scripts
- */
-
-import { renderMermaid, renderMermaidAscii, THEMES } from 'beautiful-mermaid';
-import { readFileSync, writeFileSync } from 'fs';
-
-const args = process.argv.slice(2);
-const command = args[0];
-
-async function main() {
- try {
- switch (command) {
- case 'render':
- await handleRender();
- break;
- case 'list-themes':
- handleListThemes();
- break;
- default:
- console.error(`Unknown command: ${command}`);
- process.exit(1);
- }
- } catch (error) {
- console.error('Error:', error.message);
- process.exit(1);
- }
-}
-
-async function handleRender() {
- const options = parseRenderArgs();
- const input = readFileSync(options.input, 'utf8');
-
- if (options.format === 'ascii') {
- const ascii = renderMermaidAscii(input, {
- useAscii: options.useAscii,
- paddingX: options.paddingX,
- paddingY: options.paddingY,
- boxBorderPadding: options.boxBorderPadding,
- });
-
- if (options.output) {
- writeFileSync(options.output, ascii);
- console.log(`ASCII diagram saved to ${options.output}`);
- } else {
- console.log(ascii);
- }
- } else {
- // SVG rendering
- const theme = options.theme ? THEMES[options.theme] : undefined;
- const colors = theme || {
- bg: options.bg,
- fg: options.fg,
- ...(options.line && { line: options.line }),
- ...(options.accent && { accent: options.accent }),
- ...(options.muted && { muted: options.muted }),
- ...(options.surface && { surface: options.surface }),
- ...(options.border && { border: options.border }),
- };
-
- const svg = await renderMermaid(input, {
- ...colors,
- font: options.font,
- transparent: options.transparent,
- });
-
- if (options.output) {
- writeFileSync(options.output, svg);
- console.log(`SVG diagram saved to ${options.output}`);
- } else {
- console.log(svg);
- }
- }
-}
-
-function handleListThemes() {
- console.log(JSON.stringify(Object.keys(THEMES), null, 2));
-}
-
-function parseRenderArgs() {
- const options = {
- input: null,
- output: null,
- format: 'svg',
- theme: null,
- bg: '#FFFFFF',
- fg: '#27272A',
- font: 'Inter',
- transparent: false,
- useAscii: false,
- paddingX: 5,
- paddingY: 5,
- boxBorderPadding: 1,
- };
-
- for (let i = 1; i < args.length; i += 2) {
- const key = args[i];
- const value = args[i + 1];
-
- switch (key) {
- case '--input':
- options.input = value;
- break;
- case '--output':
- options.output = value;
- break;
- case '--format':
- options.format = value;
- break;
- case '--theme':
- options.theme = value;
- break;
- case '--bg':
- options.bg = value;
- break;
- case '--fg':
- options.fg = value;
- break;
- case '--line':
- options.line = value;
- break;
- case '--accent':
- options.accent = value;
- break;
- case '--muted':
- options.muted = value;
- break;
- case '--surface':
- options.surface = value;
- break;
- case '--border':
- options.border = value;
- break;
- case '--font':
- options.font = value;
- break;
- case '--transparent':
- options.transparent = value === 'true';
- break;
- case '--use-ascii':
- options.useAscii = value === 'true';
- break;
- case '--padding-x':
- options.paddingX = parseInt(value);
- break;
- case '--padding-y':
- options.paddingY = parseInt(value);
- break;
- case '--box-border-padding':
- options.boxBorderPadding = parseInt(value);
- break;
- }
- }
-
- if (!options.input) {
- throw new Error('--input is required');
- }
-
- return options;
-}
-
-main();
diff --git a/scripts/render_mermaid.py b/scripts/render_mermaid.py
deleted file mode 100644
index d307b7a..0000000
--- a/scripts/render_mermaid.py
+++ /dev/null
@@ -1,191 +0,0 @@
-#!/usr/bin/env python3
-"""
-Render a Mermaid diagram as SVG or ASCII using beautiful-mermaid.
-
-Usage:
- python render_mermaid.py --input diagram.mmd --output diagram.svg --format svg --theme tokyo-night
- python render_mermaid.py --input diagram.mmd --format ascii
-"""
-
-import argparse
-import subprocess
-import sys
-from pathlib import Path
-
-
-def main():
- parser = argparse.ArgumentParser(
- description='Render Mermaid diagrams as beautiful SVGs or ASCII art'
- )
-
- parser.add_argument(
- '--input', '-i',
- required=True,
- help='Input Mermaid file (.mmd)'
- )
-
- parser.add_argument(
- '--output', '-o',
- help='Output file (SVG or text). If omitted, prints to stdout'
- )
-
- parser.add_argument(
- '--format', '-f',
- choices=['svg', 'ascii'],
- default='svg',
- help='Output format (default: svg)'
- )
-
- parser.add_argument(
- '--theme', '-t',
- help='Built-in theme name (e.g., tokyo-night, dracula, github-dark)'
- )
-
- parser.add_argument(
- '--bg',
- help='Background color (hex)'
- )
-
- parser.add_argument(
- '--fg',
- help='Foreground color (hex)'
- )
-
- parser.add_argument(
- '--line',
- help='Edge/connector color (hex)'
- )
-
- parser.add_argument(
- '--accent',
- help='Arrow heads and highlights color (hex)'
- )
-
- parser.add_argument(
- '--muted',
- help='Secondary text and labels color (hex)'
- )
-
- parser.add_argument(
- '--surface',
- help='Node fill tint color (hex)'
- )
-
- parser.add_argument(
- '--border',
- help='Node stroke color (hex)'
- )
-
- parser.add_argument(
- '--font',
- default='Inter',
- help='Font family (default: Inter)'
- )
-
- parser.add_argument(
- '--transparent',
- action='store_true',
- help='Render with transparent background (SVG only)'
- )
-
- parser.add_argument(
- '--use-ascii',
- action='store_true',
- help='Use pure ASCII instead of Unicode (ASCII format only)'
- )
-
- parser.add_argument(
- '--padding-x',
- type=int,
- default=5,
- help='Horizontal spacing between nodes (ASCII only, default: 5)'
- )
-
- parser.add_argument(
- '--padding-y',
- type=int,
- default=5,
- help='Vertical spacing between nodes (ASCII only, default: 5)'
- )
-
- parser.add_argument(
- '--box-border-padding',
- type=int,
- default=1,
- help='Padding inside node boxes (ASCII only, default: 1)'
- )
-
- args = parser.parse_args()
-
- # Validate input file
- input_path = Path(args.input)
- if not input_path.exists():
- print(f"Error: Input file not found: {args.input}", file=sys.stderr)
- sys.exit(1)
-
- # Build command
- helper_script = Path(__file__).parent / 'render_helper.mjs'
- cmd = ['node', str(helper_script), 'render', '--input', args.input]
-
- if args.output:
- cmd.extend(['--output', args.output])
-
- cmd.extend(['--format', args.format])
-
- if args.theme:
- cmd.extend(['--theme', args.theme])
-
- if args.bg:
- cmd.extend(['--bg', args.bg])
-
- if args.fg:
- cmd.extend(['--fg', args.fg])
-
- if args.line:
- cmd.extend(['--line', args.line])
-
- if args.accent:
- cmd.extend(['--accent', args.accent])
-
- if args.muted:
- cmd.extend(['--muted', args.muted])
-
- if args.surface:
- cmd.extend(['--surface', args.surface])
-
- if args.border:
- cmd.extend(['--border', args.border])
-
- if args.font:
- cmd.extend(['--font', args.font])
-
- if args.transparent:
- cmd.extend(['--transparent', 'true'])
-
- if args.use_ascii:
- cmd.extend(['--use-ascii', 'true'])
-
- cmd.extend(['--padding-x', str(args.padding_x)])
- cmd.extend(['--padding-y', str(args.padding_y)])
- cmd.extend(['--box-border-padding', str(args.box_border_padding)])
-
- # Execute
- try:
- result = subprocess.run(cmd, capture_output=True, text=True)
-
- if result.returncode != 0:
- print(f"Error: {result.stderr}", file=sys.stderr)
- sys.exit(result.returncode)
-
- print(result.stdout)
-
- except FileNotFoundError:
- print("Error: Node.js not found. Please install Node.js to use this tool.", file=sys.stderr)
- sys.exit(1)
- except Exception as e:
- print(f"Error: {e}", file=sys.stderr)
- sys.exit(1)
-
-
-if __name__ == '__main__':
- main()
diff --git a/scripts/themes.mjs b/scripts/themes.mjs
new file mode 100644
index 0000000..259eb37
--- /dev/null
+++ b/scripts/themes.mjs
@@ -0,0 +1,55 @@
+#!/usr/bin/env node
+
+import { execSync } from 'child_process';
+import { dirname, join } from 'path';
+import { fileURLToPath } from 'url';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const skillRoot = join(__dirname, '..');
+
+async function loadBeautifulMermaid() {
+ try {
+ return await import('beautiful-mermaid');
+ } catch {}
+
+ console.error('[beautiful-mermaid] Dependency not found. Installing automatically...');
+ try {
+ execSync('npm install --no-fund --no-audit', {
+ cwd: skillRoot,
+ stdio: ['pipe', 'pipe', 'inherit'],
+ timeout: 120000,
+ });
+ console.error('[beautiful-mermaid] Installed successfully.\n');
+ } catch (e) {
+ console.error(`[beautiful-mermaid] Auto-install failed: ${e.message}`);
+ console.error(`Manual fix: cd ${skillRoot} && npm install`);
+ process.exit(1);
+ }
+
+ try {
+ const pkgPath = join(skillRoot, 'node_modules', 'beautiful-mermaid', 'dist', 'index.js');
+ return await import(pkgPath);
+ } catch (e) {
+ console.error(`[beautiful-mermaid] Failed to load after install: ${e.message}`);
+ process.exit(1);
+ }
+}
+
+async function main() {
+ const { THEMES } = await loadBeautifulMermaid();
+ const themes = Object.keys(THEMES);
+
+ console.log('Available Beautiful-Mermaid Themes:\n');
+ themes.forEach((theme, i) => {
+ console.log(`${String(i + 1).padStart(2)}. ${theme}`);
+ });
+
+ console.log(`\nTotal: ${themes.length} themes`);
+ console.log('\nUsage:');
+ console.log(' node scripts/render.mjs --input diagram.mmd --theme <theme-name> --output output.svg');
+}
+
+main().catch(e => {
+ console.error('Error:', e.message);
+ process.exit(1);
+});