repositories / dotfiles
dotfiles
bugabingas dorkfiles
owned by bugabinga
opencode/tools/d2.ts
Rawimport { tool } from "@opencode-ai/plugin";
import { spawn } from "node:child_process";
import path from "node:path";
import {
existsSync,
mkdirSync,
readFileSync,
statSync,
unlinkSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
// ============================================================================
// Security Constants
// ============================================================================
const MAX_CODE_SIZE = 1024 * 1024; // 1MB max D2 code size
const MAX_FILE_SIZE = 50 * 1024 * 1024; // 50MB max output file size
const SUPPORTED_FORMATS = ["svg", "png", "pdf"] as const;
const SUPPORTED_THEMES = [
"default",
"dark",
"terminal",
"earth",
"cool",
"grape",
"asteroid",
"flagship",
] as const;
const SUPPORTED_LAYOUTS = ["dagre", "elk", "tala"] as const;
type OutputFormat = (typeof SUPPORTED_FORMATS)[number];
type Theme = (typeof SUPPORTED_THEMES)[number];
type Layout = (typeof SUPPORTED_LAYOUTS)[number];
// ============================================================================
// Helper Functions
// ============================================================================
/**
* Create a JSON response string
*/
export function jsonResponse(data: Record<string, unknown>): string {
return JSON.stringify(data, null, 2);
}
/**
* Assert that a target path stays within the specified directory
* Prevents path traversal attacks
*/
export function assertWithinDirectory(
targetPath: string,
directory: string,
operation: string,
): void {
const resolvedTarget = path.resolve(targetPath);
const resolvedDir = path.resolve(directory);
const dirWithSep = resolvedDir.endsWith(path.sep)
? resolvedDir
: resolvedDir + path.sep;
if (
resolvedTarget !== resolvedDir &&
!resolvedTarget.startsWith(dirWithSep)
) {
throw new Error(
`Path security error: ${operation}: path escapes working directory: ${targetPath}`,
);
}
}
/**
* Check if a path attempts path traversal
*/
export function isPathTraversalAttempt(
inputPath: string,
directory: string,
): boolean {
try {
const fullPath = path.resolve(directory, inputPath);
const resolvedDir = path.resolve(directory);
const dirWithSep = resolvedDir.endsWith(path.sep)
? resolvedDir
: resolvedDir + path.sep;
return (
fullPath !== resolvedDir && !fullPath.startsWith(dirWithSep)
);
} catch {
return true;
}
}
/**
* Determine output path for rendered diagram
*/
function determineOutputPath(
inputPath: string | null,
suffix: string,
format: string,
directory: string,
): string {
const outputDir = path.join(directory, ".output");
// Ensure output directory exists
if (!existsSync(outputDir)) {
mkdirSync(outputDir, { recursive: true });
}
if (inputPath) {
const baseName = path.basename(inputPath, path.extname(inputPath));
return path.join(outputDir, `${baseName}${suffix}.${format}`);
}
const timestamp = Date.now();
return path.join(outputDir, `diagram${suffix}-${timestamp}.${format}`);
}
/**
* Format file size for human readability
*/
export function formatFileSize(bytes: number): string {
const units = ["B", "KB", "MB", "GB"];
let size = bytes;
let unitIndex = 0;
while (size >= 1024 && unitIndex < units.length - 1) {
size /= 1024;
unitIndex++;
}
return `${size.toFixed(2)} ${units[unitIndex]}`;
}
/**
* Extract error message from unknown error
*/
export function getErrorMessage(err: unknown): string {
if (err instanceof Error) {
return err.message;
}
return String(err);
}
/**
* Parse D2 syntax error from stderr output
* Attempts to extract line number and helpful context
*/
export function parseD2Error(stderr: string): {
message: string;
line?: number;
column?: number;
hint?: string;
} {
// Common D2 error patterns:
// 1. "error: <message>" format
// 2. "d2: <message>" format
// 3. Line/column info like "at line 5, column 10"
const lineMatch = stderr.match(/line\s*(\d+)/i);
const columnMatch = stderr.match(/column\s*(\d+)/i);
const line = lineMatch ? parseInt(lineMatch[1]!, 10) : undefined;
const column = columnMatch ? parseInt(columnMatch[1]!, 10) : undefined;
// Extract the main error message
let message = stderr.trim();
// Try to extract just the error message without the full path/context
const errorMatch = stderr.match(/(?:error|d2):\s*(.+?)(?:\n|$)/i);
if (errorMatch) {
message = errorMatch[1]!.trim();
} else {
// Remove file paths and temp file references for cleaner messages
message = message
.replace(/\/tmp\/[^\s:]+/g, "<temp-file>")
.replace(/in file [^\s:]+/gi, "")
.trim();
}
// Generate hints based on common errors
let hint: string | undefined;
const lowerMessage = message.toLowerCase();
if (lowerMessage.includes("unexpected") && lowerMessage.includes("token")) {
hint =
"Check for syntax errors like missing colons, brackets, or quotes in your D2 code.";
} else if (
lowerMessage.includes("undefined") || lowerMessage.includes("not found")
) {
hint =
"Make sure all referenced shapes and connections are defined before use.";
} else if (
lowerMessage.includes("invalid") || lowerMessage.includes("invalid key")
) {
hint = "Check that you're using valid D2 keywords and proper syntax.";
} else if (lowerMessage.includes("connection")) {
hint =
"Connection syntax should be: 'shape1 -> shape2: label' or 'shape1 -- shape2: label'";
} else if (lowerMessage.includes("style") || lowerMessage.includes("fill")) {
hint =
"Style properties should use valid CSS colors (e.g., '#ff0000', 'red', 'blue').";
}
return { message, line, column, hint };
}
/**
* Validate D2 code for common issues before processing
*/
export function validateD2Code(
code: string,
): { valid: boolean; error?: string; hint?: string } {
// Check for empty code (code was provided but is empty string)
if (code.length === 0) {
return {
valid: false,
error: "D2 code is empty. Please provide valid D2 diagram code.",
hint:
"D2 code should define shapes and connections. Example: 'x -> y: my arrow'",
};
}
// Check for whitespace-only code
if (!/\S/.test(code)) {
return {
valid: false,
error:
"D2 code contains only whitespace. Please provide valid D2 diagram code.",
hint:
"D2 code should contain at least one shape or connection definition. Example: 'x -> y: my arrow'",
};
}
return { valid: true };
}
/**
* Check if d2 CLI is available
*/
function checkD2Available(): Promise<
{ available: boolean; version?: string; error?: string; hint?: string }
> {
return new Promise((resolve) => {
const proc = spawn("d2", ["--version"], { shell: false });
let stdout = "";
let stderr = "";
proc.stdout.on("data", (data) => {
stdout += data.toString();
});
proc.stderr.on("data", (data) => {
stderr += data.toString();
});
proc.on("error", (err) => {
let hint: string;
if ((err as NodeJS.ErrnoException).code === "ENOENT") {
hint =
"D2 CLI is not installed. Install it with: curl -fsSL https://d2lang.com/install.sh | sh -s --";
} else {
hint =
"There was an issue running the D2 CLI. Check your installation.";
}
resolve({
available: false,
error: `D2 CLI not found: ${err.message}`,
hint,
});
});
proc.on("close", (code) => {
if (code === 0) {
const version = stdout.trim() || "unknown";
resolve({ available: true, version });
} else {
resolve({
available: false,
error: `D2 CLI returned exit code ${code}: ${
stderr || "Unknown error"
}`,
hint: "D2 CLI may be corrupted or misconfigured. Try reinstalling.",
});
}
});
});
}
/**
* Resolve a file path relative to the context directory
*/
export function resolveFilePath(inputPath: string, directory: string): string {
const trimmed = inputPath.trim();
const fullPath = path.resolve(directory, trimmed);
assertWithinDirectory(fullPath, directory, "resolveFilePath");
return fullPath;
}
/**
* Execute d2 CLI command
*/
function executeD2(
inputPath: string,
outputPath: string,
options: {
format: OutputFormat;
theme?: Theme;
layout?: Layout;
pad?: number;
},
): Promise<
{ success: boolean; error?: string; hint?: string; stderr?: string }
> {
return new Promise((resolve) => {
const args: string[] = [];
// Add layout option
if (options.layout) {
args.push("--layout", options.layout);
}
// Add theme option
if (options.theme && options.theme !== "default") {
args.push("--theme", options.theme);
}
// Add pad option
if (options.pad !== undefined) {
args.push("--pad", String(options.pad));
}
// Add input and output paths
args.push(inputPath, outputPath);
const proc = spawn("d2", args, { shell: false });
let stderr = "";
let stdout = "";
proc.stdout.on("data", (data) => {
stdout += data.toString();
});
proc.stderr.on("data", (data) => {
stderr += data.toString();
});
proc.on("error", (err) => {
resolve({
success: false,
error: `Failed to execute d2: ${err.message}`,
hint:
"Ensure D2 CLI is properly installed and accessible in your PATH.",
});
});
proc.on("close", (code) => {
if (code === 0) {
resolve({ success: true });
} else {
const parsed = parseD2Error(stderr);
resolve({
success: false,
error: parsed.message,
hint: parsed.hint,
stderr,
});
}
});
});
}
/**
* Get MIME type for output format
*/
export function getMimeType(format: OutputFormat): string {
switch (format) {
case "svg":
return "image/svg+xml";
case "png":
return "image/png";
case "pdf":
return "application/pdf";
default:
return "application/octet-stream";
}
}
/**
* Try to extract dimensions from SVG content
*/
export function tryExtractSvgDimensions(
content: string,
): { width?: number; height?: number } | null {
try {
// Look for width/height in SVG tag
const widthMatch = content.match(/<svg[^>]+width=["'](\d+(?:\.\d+)?)/i);
const heightMatch = content.match(/<svg[^>]+height=["'](\d+(?:\.\d+)?)/i);
const viewBoxMatch = content.match(/<svg[^>]+viewBox=["']([\d\s.]+)["']/i);
if (widthMatch && heightMatch) {
return {
width: parseFloat(widthMatch[1]!),
height: parseFloat(heightMatch[1]!),
};
}
if (viewBoxMatch) {
const parts = viewBoxMatch[1]!.trim().split(/\s+/);
if (parts.length >= 4) {
return {
width: parseFloat(parts[2]!),
height: parseFloat(parts[3]!),
};
}
}
} catch {
// Ignore parsing errors
}
return null;
}
// ============================================================================
// Tool: d2_render
// ============================================================================
export const render = tool({
description: `Render a D2 diagram to an image file.
D2 is a declarative diagramming language that turns text into diagrams.
This tool compiles D2 code into SVG, PNG, or PDF format.
Parameters:
- code: The D2 diagram code (required if file not specified)
- file: Path to a .d2 file (required if code not specified)
- format: Output format - svg (default), png, or pdf
- theme: Visual theme - default, dark, terminal, earth, cool, grape, asteroid, flagship
- layout: Layout engine - dagre, elk, or tala (default uses d2's default)
- pad: Padding around the diagram in pixels
- returnBase64: Return base64 encoded output instead of file path
Examples:
- Render inline code: render({ code: "a -> b: hello", format: "svg" })
- From file: render({ file: "diagram.d2", format: "png" })
- With theme: render({ code: "...", theme: "dark" })
- Return base64: render({ code: "...", returnBase64: true })
D2 Code Example:
\`\`\`d2
direction: right
User -> Server: Request
Server -> Database: Query
Database -> Server: Result
Server -> User: Response
\`\`\``,
args: {
code: tool.schema
.string()
.optional()
.describe("D2 diagram code. Required if 'file' is not specified."),
file: tool.schema
.string()
.optional()
.describe("Path to a .d2 file. Required if 'code' is not specified."),
format: tool.schema
.enum(SUPPORTED_FORMATS)
.default("svg")
.describe("Output format: svg (default), png, or pdf"),
theme: tool.schema
.enum(SUPPORTED_THEMES)
.optional()
.describe(
"Visual theme: default, dark, terminal, earth, cool, grape, asteroid, flagship",
),
layout: tool.schema
.enum(SUPPORTED_LAYOUTS)
.optional()
.describe(
"Layout engine: dagre, elk, or tala. Uses d2's default if not specified.",
),
pad: tool.schema
.number()
.min(0)
.max(500)
.optional()
.describe("Padding around the diagram in pixels (0-500)"),
returnBase64: tool.schema
.boolean()
.default(false)
.describe("Return base64 encoded output instead of saving to file"),
},
async execute(args, context) {
try {
// Check if code is explicitly provided (even if empty) vs not provided
const hasCode = args.code !== undefined;
const hasFile = args.file !== undefined;
// Validate that either code or file is provided
if (!hasCode && !hasFile) {
return jsonResponse({
success: false,
error: "Either 'code' or 'file' parameter must be provided.",
hint:
"Provide D2 code via the 'code' parameter, or specify a .d2 file path via the 'file' parameter.",
example:
'render({ code: "a -> b: hello" }) or render({ file: "diagram.d2" })',
});
}
if (hasCode && hasFile) {
return jsonResponse({
success: false,
error: "Provide either 'code' or 'file', not both.",
hint: "Choose one input method: inline code or file path.",
});
}
// Validate code content if provided
if (hasCode) {
const validation = validateD2Code(args.code!);
if (!validation.valid) {
return jsonResponse({
success: false,
error: validation.error,
hint: validation.hint,
});
}
// Validate code size
if (args.code!.length > MAX_CODE_SIZE) {
return jsonResponse({
success: false,
error: `D2 code exceeds maximum size of ${
MAX_CODE_SIZE / 1024 / 1024
}MB (${formatFileSize(args.code!.length)} provided).`,
hint:
"Reduce the complexity of your diagram or split it into multiple diagrams.",
});
}
}
// Handle file input - check security FIRST before extension check
if (hasFile) {
// Check for path traversal attempts BEFORE extension check
if (isPathTraversalAttempt(args.file!, context.directory)) {
return jsonResponse({
success: false,
error:
`Path security error: path escapes working directory: ${args.file}`,
hint:
"File paths must stay within the project directory. Avoid using '..' or absolute paths.",
});
}
// Check for .d2 extension hint
if (!args.file!.toLowerCase().endsWith(".d2")) {
return jsonResponse({
success: false,
error: `File "${args.file}" does not have a .d2 extension.`,
hint:
"D2 files should have the .d2 extension. Rename your file or verify it's a valid D2 file.",
});
}
const fullPath = resolveFilePath(args.file!, context.directory);
if (!existsSync(fullPath)) {
return jsonResponse({
success: false,
error: `D2 file not found: ${args.file}`,
hint:
"Verify the file path is correct and the file exists in your project directory.",
searched_path: fullPath,
});
}
const stats = statSync(fullPath);
if (stats.size > MAX_CODE_SIZE) {
return jsonResponse({
success: false,
error: `D2 file exceeds maximum size of ${
MAX_CODE_SIZE / 1024 / 1024
}MB (${formatFileSize(stats.size)} found).`,
hint: "Reduce the file size by simplifying your diagram.",
});
}
}
// Check if d2 is available
const d2Check = await checkD2Available();
if (!d2Check.available) {
return jsonResponse({
success: false,
error: d2Check.error,
hint: d2Check.hint,
install_command:
"curl -fsSL https://d2lang.com/install.sh | sh -s --",
docs_url: "https://d2lang.com/tour/install",
});
}
const format = args.format || "svg";
let inputPath: string;
let tempFile: string | null = null;
let sourceType: "code" | "file" = "code";
let sourceName: string | null = null;
// Handle input source
if (hasFile) {
const fullPath = resolveFilePath(args.file!, context.directory);
inputPath = fullPath;
sourceType = "file";
sourceName = args.file!;
} else {
// Create temporary file for inline code
tempFile = path.join(tmpdir(), `d2-input-${Date.now()}.d2`);
writeFileSync(tempFile, args.code!, "utf-8");
inputPath = tempFile;
sourceType = "code";
}
// Determine output path
const outputPath = determineOutputPath(
sourceName,
"",
format,
context.directory,
);
// Execute d2
const result = await executeD2(inputPath, outputPath, {
format,
theme: args.theme,
layout: args.layout,
pad: args.pad,
});
// Clean up temp file
if (tempFile) {
try {
unlinkSync(tempFile);
} catch {
// Ignore cleanup errors
}
}
if (!result.success) {
const response: Record<string, unknown> = {
success: false,
error: result.error,
d2_version: d2Check.version,
};
if (result.hint) {
response.hint = result.hint;
}
// Include raw stderr for debugging if available
if (result.stderr) {
response.raw_error = result.stderr;
}
return jsonResponse(response);
}
// Check output file
if (!existsSync(outputPath)) {
return jsonResponse({
success: false,
error: "D2 completed but output file was not created.",
hint:
"This may indicate a problem with the D2 installation or disk space issues.",
});
}
const outputStats = statSync(outputPath);
if (outputStats.size > MAX_FILE_SIZE) {
// Clean up oversized file
try {
unlinkSync(outputPath);
} catch {
// Ignore cleanup errors
}
return jsonResponse({
success: false,
error: `Output file exceeds maximum size of ${
MAX_FILE_SIZE / 1024 / 1024
}MB (${formatFileSize(outputStats.size)} generated).`,
hint:
"The diagram may be too complex. Try simplifying it or reducing the number of elements.",
});
}
// Handle base64 return
if (args.returnBase64) {
const buffer = readFileSync(outputPath);
const base64 = buffer.toString("base64");
const mimeType = getMimeType(format);
// Try to extract dimensions from SVG
let dimensions: { width?: number; height?: number } | undefined;
if (format === "svg") {
const content = buffer.toString("utf-8");
dimensions = tryExtractSvgDimensions(content) || undefined;
}
// Clean up file when returning base64
try {
unlinkSync(outputPath);
} catch {
// Ignore cleanup errors
}
const response: Record<string, unknown> = {
success: true,
operation: "render",
data: `data:${mimeType};base64,${base64}`,
format,
theme: args.theme || "default",
layout: args.layout || "default",
size_bytes: outputStats.size,
size_human: formatFileSize(outputStats.size),
d2_version: d2Check.version,
input_source: sourceType === "file" ? args.file : "inline code",
};
if (dimensions) {
response.dimensions = dimensions;
}
return jsonResponse(response);
}
// Try to extract dimensions from SVG file
let dimensions: { width?: number; height?: number } | undefined;
if (format === "svg") {
try {
const content = readFileSync(outputPath, "utf-8");
dimensions = tryExtractSvgDimensions(content) || undefined;
} catch {
// Ignore errors reading dimensions
}
}
// Return file path
const response: Record<string, unknown> = {
success: true,
operation: "render",
input: sourceType === "file" ? args.file : "(inline code)",
output: path.relative(context.directory, outputPath),
output_path: outputPath,
format,
theme: args.theme || "default",
layout: args.layout || "default",
size_bytes: outputStats.size,
size_human: formatFileSize(outputStats.size),
d2_version: d2Check.version,
message:
`Successfully rendered D2 diagram to ${format.toUpperCase()} format.`,
};
if (dimensions) {
response.dimensions = dimensions;
}
return jsonResponse(response);
} catch (err) {
return jsonResponse({
success: false,
error: getErrorMessage(err),
hint:
"An unexpected error occurred. Check the error message for details.",
});
}
},
});
// ============================================================================
// Tool: d2_check
// ============================================================================
export const check = tool({
description: `Check if the D2 CLI is available and get version information.
Use this tool to verify D2 installation before attempting to render diagrams.
Example:
- Check availability: check()`,
args: {},
async execute() {
try {
const result = await checkD2Available();
if (result.available) {
return jsonResponse({
success: true,
available: true,
version: result.version,
message: `D2 CLI v${result.version} is available and ready to use.`,
supported_formats: SUPPORTED_FORMATS,
supported_themes: SUPPORTED_THEMES,
supported_layouts: SUPPORTED_LAYOUTS,
quick_start: {
example: 'render({ code: "x -> y: my arrow" })',
docs: "https://d2lang.com/tour/intro",
},
});
}
return jsonResponse({
success: false,
available: false,
error: result.error,
hint: result.hint,
install_command: "curl -fsSL https://d2lang.com/install.sh | sh -s --",
docs_url: "https://d2lang.com/tour/install",
alternative_install: {
macos: "brew install d2",
windows: "scoop install d2",
linux: "curl -fsSL https://d2lang.com/install.sh | sh -s --",
},
});
} catch (err) {
return jsonResponse({
success: false,
error: getErrorMessage(err),
hint: "An unexpected error occurred while checking D2 availability.",
});
}
},
});
// ============================================================================
// Tool: d2_themes
// ============================================================================
export const themes = tool({
description: `List available D2 themes.
D2 supports multiple visual themes for diagram styling.
Example:
- List themes: themes()`,
args: {},
async execute() {
const themeDescriptions: Record<string, string> = {
default:
"Light theme with clean, professional styling. Best for documentation.",
dark:
"Dark theme with inverted colors. Ideal for presentations or dark-mode interfaces.",
terminal:
"Terminal-style green-on-black theme. Great for technical diagrams.",
earth: "Earth-toned color palette. Warm and natural feel.",
cool: "Cool blue tones. Professional and calming.",
grape: "Purple and violet palette. Creative and distinctive.",
asteroid: "Space-inspired dark theme with cosmic colors.",
flagship: "Modern dark theme with accent colors. Premium feel.",
};
return jsonResponse({
success: true,
themes: SUPPORTED_THEMES.map((theme) => ({
id: theme,
name: theme.charAt(0).toUpperCase() + theme.slice(1),
description: themeDescriptions[theme] || `${theme} theme`,
})),
usage: "Use the 'theme' parameter in render() to apply a theme",
example: 'render({ code: "a -> b: hello", theme: "dark" })',
tip:
"The 'default' theme works best for light-mode documentation. Use 'dark' or 'flagship' for presentations.",
});
},
});
// ============================================================================
// Tool: d2_layouts
// ============================================================================
export const layouts = tool({
description: `List available D2 layout engines.
Layout engines control how diagrams are arranged:
- dagre: General purpose, hierarchical layouts
- elk: Complex graphs, better edge routing
- tala: Software architecture, nested containers
Example:
- List layouts: layouts()`,
args: {},
async execute() {
return jsonResponse({
success: true,
layouts: [
{
id: "dagre",
name: "Dagre",
description:
"General purpose, hierarchical layouts. Good default choice for simple diagrams.",
best_for: "Simple flowcharts, org charts, simple hierarchies",
pros: ["Fast", "Predictable", "Good for small graphs"],
cons: [
"Less optimal edge routing",
"May struggle with complex graphs",
],
},
{
id: "elk",
name: "ELK (Eclipse Layout Kernel)",
description:
"Complex graphs with better edge routing. Good for large, dense diagrams.",
best_for: "Large diagrams, complex networks, dense graphs",
pros: [
"Excellent edge routing",
"Handles large graphs well",
"Layer-based",
],
cons: ["Slower than dagre", "May over-optimize simple diagrams"],
},
{
id: "tala",
name: "TALA",
description:
"Software architecture diagrams with nested containers. D2's recommended default.",
best_for: "Architecture diagrams, system diagrams, nested structures",
pros: [
"Handles nested containers",
"Designed for software architecture",
"Clean layouts",
],
cons: ["May not be optimal for non-hierarchical diagrams"],
},
],
usage: "Use the 'layout' parameter in render() to specify engine",
example: 'render({ code: "a -> b: hello", layout: "elk" })',
tip:
"TALA is D2's recommended default. Try ELK for complex graphs with many connections.",
});
},
});