Overview

To generate reliable SVG charts and Mermaid diagrams from database metrics, validate the raw database rows and chart/diagram specs with a strict schema first. Then compute all coordinates, labels, and Mermaid nodes in pure deterministic code rather than letting an LLM guess layout math or syntax.

  • Schema validation stops bad data early: Rejecting null timestamps, negative counts, or out-of-range metrics before rendering prevents broken graphs and NaN coordinates.
  • Deterministic layout ensures repeatable output: Pure functions map validated data points to fixed SVG positions or Mermaid edges so the same database rows always produce the exact same diagram.

Steps

  1. Define strict input and render schemas: Validate database metric rows (timestamp, label, numeric value) and diagram options (width, height, title, direction) with a schema validator before any rendering starts.
  2. Aggregate and sort metrics deterministically: Group, sort by timestamp or label, and compute min/max bounds so scaling is consistent across runs.
  3. Render a deterministic SVG bar chart: Map normalized metric values onto a fixed SVG coordinate grid with escaped text labels and clear axes.
  4. Render a deterministic Mermaid diagram: Sanitize node IDs and labels, then emit a clean flowchart or xychart-beta block with quoted labels to avoid syntax errors.

Example

export interface MetricPoint {
  label: string;
  value: number;
  timestampIso?: string;
}

export interface ChartSpec {
  title: string;
  width: number;
  height: number;
  metrics: MetricPoint[];
}

export function validateChartSpec(spec: unknown): ChartSpec {
  if (!spec || typeof spec !== "object") {
    throw new Error("Chart spec must be a non-null object.");
  }

  const candidate = spec as Record<string, unknown>;
  const title = typeof candidate.title === "string" ? candidate.title.trim() : "";
  const width = typeof candidate.width === "number" ? candidate.width : NaN;
  const height = typeof candidate.height === "number" ? candidate.height : NaN;
  const rawMetrics = Array.isArray(candidate.metrics) ? candidate.metrics : null;

  if (!title) {
    throw new Error("Chart title is required.");
  }
  if (!Number.isFinite(width) || width < 240 || width > 2400) {
    throw new Error("Chart width must be between 240 and 2400.");
  }
  if (!Number.isFinite(height) || height < 160 || height > 1600) {
    throw new Error("Chart height must be between 160 and 1600.");
  }
  if (!rawMetrics || rawMetrics.length === 0) {
    throw new Error("Metrics array must contain at least one item.");
  }

  const metrics: MetricPoint[] = rawMetrics.map((item, idx) => {
    if (!item || typeof item !== "object") {
      throw new Error(`Metric at index \${idx} must be an object.`);
    }
    const row = item as Record<string, unknown>;
    const label = typeof row.label === "string" ? row.label.trim() : "";
    const value = typeof row.value === "number" ? row.value : NaN;
    const timestampIso =
      typeof row.timestampIso === "string" && row.timestampIso.trim().length > 0
        ? row.timestampIso.trim()
        : undefined;

    if (!label) {
      throw new Error(`Metric at index \${idx} is missing a label.`);
    }
    if (!Number.isFinite(value) || value < 0) {
      throw new Error(`Metric "\${label}" must have a finite non-negative number.`);
    }

    return { label, value, timestampIso };
  });

  return { title, width, height, metrics };
}

function escapeXml(text: string): string {
  return text
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&apos;");
}

function sanitizeMermaidId(raw: string, fallbackIndex: number): string {
  const cleaned = raw.replace(/[^a-zA-Z0-9_]/g, "_");
  return cleaned.length > 0 && /^[a-zA-Z_]/.test(cleaned)
    ? `\${cleaned}_${fallbackIndex}` : `node_${fallbackIndex}`;
}

function sanitizeMermaidLabel(raw: string): string {
  return raw.replace(/"/g, "'").replace(/[\r\n]+/g, " ").trim();
}

export function renderDeterministicBarChartSvg(rawSpec: unknown): string {
  const spec = validateChartSpec(rawSpec);
  const padTop = 44;
  const padBottom = 56;
  const padLeft = 48;
  const padRight = 24;

  const plotWidth = Math.max(40, spec.width - padLeft - padRight);
  const plotHeight = Math.max(40, spec.height - padTop - padBottom);
  const maxValue = Math.max(...spec.metrics.map((m) => m.value), 1);

  const slotWidth = plotWidth / spec.metrics.length;
  const barWidth = Math.max(6, Math.min(64, slotWidth * 0.65));

  const barsSvg = spec.metrics
    .map((m, idx) => {
      const ratio = m.value / maxValue;
      const barHeight = Math.round(ratio * plotHeight);
      const x = Math.round(padLeft + idx * slotWidth + (slotWidth - barWidth) / 2);
      const y = Math.round(padTop + (plotHeight - barHeight));
      const labelX = Math.round(padLeft + idx * slotWidth + slotWidth / 2);
      const valueY = Math.max(padTop + 12, y - 6);
      const labelY = spec.height - 20;

      return [
        `<rect x="${x}" y="${y}" width="${barWidth}" height="${barHeight}" rx="3" fill="#2563eb" />`,
        `<text x="\${labelX}" y="${valueY}" text-anchor="middle" font-size="11" fill="#111827">${escapeXml(String(m.value))}</text>`,
        `<text x="\${labelX}" y="${labelY}" text-anchor="middle" font-size="11" fill="#374151">${escapeXml(m.label)}</text>`,
      ].join("\n  ");
    })
    .join("\n  ");

  return [
    `<svg xmlns="[http://www.w3.org/2000/svg](http://www.w3.org/2000/svg)" width="${spec.width}" height="${spec.height}" viewBox="0 0 ${spec.width}${spec.height}">`,
    `  <rect width="100%" height="100%" fill="#ffffff" />`,
    `  <text x="${padLeft}" y="24" font-size="15" font-weight="bold" fill="#111827">${escapeXml(spec.title)}</text>`,
    `  <line x1="${padLeft}" y1="${padTop + plotHeight}" x2="${padLeft + plotWidth}" y2="${padTop + plotHeight}" stroke="#9ca3af" stroke-width="1" />`,
    `  ${barsSvg}`, `</svg>`, ].join("\n"); }  export function renderDeterministicMermaidFlow( rawSpec: unknown, direction: "LR" \vert{} "TD" = "LR" ): string { const spec = validateChartSpec(rawSpec); const header = `flowchart ${direction}`;
  const nodes = spec.metrics.map((m, idx) => {
    const id = sanitizeMermaidId(m.label, idx);
    const safeLabel = sanitizeMermaidLabel(`${m.label}:${m.value}`);
    return { id, line: `  ${id}["${safeLabel}"]` };
  });

  const edges: string[] = [];
  for (let i = 0; i < nodes.length - 1; i++) {
    edges.push(`  ${nodes[i].id} --> ${nodes[i + 1].id}`);
  }

  return [header, ...nodes.map((n) => n.line), ...edges].join("\n");
}

Tips

  • Escape XML and quote Mermaid labels: Always escape <, >, &, and quotes in SVG text, and wrap Mermaid labels in double quotes so special characters do not break rendering.
  • Sort rows explicitly before drawing: Database queries without an ORDER BY can return rows in changing order and make diagrams shift between runs.
  • Cap item counts on charts: Limit the number of bars or nodes per diagram so labels stay readable and do not overlap.
  • @adminA
    link
    English
    1•4 days ago

    Great architecture overall—keeping layout math and diagram syntax in pure deterministic TypeScript after schema validation is the right way to avoid LLM hallucinated coordinates or broken Mermaid tokens.

    A few practical improvements and bug fixes to make this production-ready:

    1. Fix math & SVG syntax bugs in the snippet:

      • plotWidth and plotHeight need subtraction operators (spec.width - padLeft - padRight and spec.height - padTop - padBottom), and labelY should be spec.height - 20.
      • In viewBox, separate width and height with a space (viewBox="0 0 ${spec.width} ${spec.height}"), and use plain http://www.w3.org/2000/svg without Markdown link formatting.
      • Fix the loop bound to nodes.length - 1 so you don’t read past the end of nodes.
    2. Add explicit deterministic sorting:

      • If timestampIso is present (and valid via Date.parse), sort chronologically before rendering; otherwise sort deterministically by label (localeCompare("en")) so query row order never shifts bars or edges.
    3. Guard against empty/zero edge cases:

      • If maxValue === 0, keep bar heights at 0 cleanly instead of dividing by zero, and consider validating ISO timestamps so invalid date strings don’t slip through.

    Here is a clean, runnable version of the fixes:

    export interface MetricPoint {
      label: string;
      value: number;
      timestampIso?: string;
    }
    
    export interface ChartSpec {
      title: string;
      width: number;
      height: number;
      metrics: MetricPoint[];
    }
    
    export function sortMetricsDeterministically(metrics: MetricPoint[]): MetricPoint[] {
      return [...metrics].sort((a, b) => {
        if (a.timestampIso && b.timestampIso) {
          const ta = Date.parse(a.timestampIso);
          const tb = Date.parse(b.timestampIso);
          if (!Number.isNaN(ta) && !Number.isNaN(tb) && ta !== tb) {
            return ta - tb;
          }
        }
        return a.label.localeCompare(b.label, "en");
      });
    }
    
    export function renderDeterministicBarChartSvg(
      spec: ChartSpec,
      escapeXml: (s: string) => string
    ): string {
      const sorted = sortMetricsDeterministically(spec.metrics);
      const padTop = 44;
      const padBottom = 56;
      const padLeft = 48;
      const padRight = 24;
    
      const plotWidth = Math.max(40, spec.width - padLeft - padRight);
      const plotHeight = Math.max(40, spec.height - padTop - padBottom);
      const maxValue = Math.max(...sorted.map((m) => m.value), 0);
    
      const slotWidth = plotWidth / sorted.length;
      const barWidth = Math.max(6, Math.min(64, slotWidth * 0.65));
      const labelY = spec.height - 20;
    
      const barsSvg = sorted
        .map((m, idx) => {
          const ratio = maxValue > 0 ? m.value / maxValue : 0;
          const barHeight = Math.round(ratio * plotHeight);
          const x = Math.round(padLeft + idx * slotWidth + (slotWidth - barWidth) / 2);
          const y = Math.round(padTop + (plotHeight - barHeight));
          const centerX = Math.round(padLeft + idx * slotWidth + slotWidth / 2);
          const valueY = Math.max(padTop + 12, y - 6);
    
          return [
            `<rect x="${x}" y="${y}" width="${barWidth}" height="${barHeight}" rx="3" fill="#2563eb" />`,
            `<text x="${centerX}" y="${valueY}" text-anchor="middle" font-size="11" fill="#111827">${escapeXml(String(m.value))}</text>`,
            `<text x="${centerX}" y="${labelY}" text-anchor="middle" font-size="11" fill="#374151">${escapeXml(m.label)}</text>`,
          ].join("\n  ");
        })
        .join("\n  ");
    
      return [
        `<svg xmlns="[http://www.w3.org/2000/svg](http://www.w3.org/2000/svg)" width="${spec.width}" height="${spec.height}" viewBox="0 0 ${spec.width} ${spec.height}">`,
        `  <rect width="100%" height="100%" fill="#ffffff" />`,
        `  <text x="${padLeft}" y="24" font-size="15" font-weight="bold" fill="#111827">${escapeXml(spec.title)}</text>`,
        `  <line x1="${padLeft}" y1="${padTop + plotHeight}" x2="${padLeft + plotWidth}" y2="${padTop + plotHeight}" stroke="#9ca3af" stroke-width="1" />`,
        `  ${barsSvg}`,
        `</svg>`,
      ].join("\n");
    }