/** * Static checks of an embed fragment against the embed contract * (backend/embed-kit/contract.md), shared by the Embed Studio and the MCP * embed tools. Errors mean the fragment cannot work in the article; warnings * are contract rules a renderer cannot verify cheaply. The browser checker * (src/embed-check) covers what only rendering shows. */ export const MAX_EMBED_SIZE = 512_000; export const EMBED_NAME_RE = /^[a-z0-9][a-z0-9-]{0,59}\.html$/; export interface ContractReport { errors: string[]; warnings: string[]; /** Root class found on the first element, if any. */ rootClass: string | null; } /** * Slugify an arbitrary filename hint into a safe kebab-case slug. * Keeps ASCII letters/digits/dashes, collapses whitespace, lowercases. */ export function slugify(raw: string): string { const base = raw .toLowerCase() .replace(/\.html?$/i, "") .normalize("NFKD") .replace(/[\u0300-\u036f]/g, "") .replace(/[^a-z0-9]+/g, "-") .replace(/^-+|-+$/g, "") .slice(0, 55); return base || "chart"; } /** * Given a slug, find a unique .html filename. If the desired name is free, * return it; otherwise append `-2`, `-3`, ... */ export function ensureUniqueFilename( slug: string, taken: (name: string) => boolean, currentSrc: string, ): string { const base = `${slug}.html`; if (base === currentSrc) return base; if (!taken(base)) return base; let i = 2; while (taken(`${slug}-${i}.html`)) i++; return `${slug}-${i}.html`; } const CONFIG_BLOCK_RE = /]*\bdata-embed-config\b[^>]*>([\s\S]*?)<\/script>/i; const HARDCODED_COLOR = /(?:fill|stroke|color|background)["']?\s*[:=,]\s*["']?#[0-9a-f]{3,8}\b/i; export function validateEmbedHtml(html: string, opts: { banner?: boolean } = {}): ContractReport { const errors: string[] = []; const warnings: string[] = []; const trimmed = html.trim(); if (!trimmed) return { errors: ["html is empty"], warnings, rootClass: null }; if (trimmed.length > MAX_EMBED_SIZE) { errors.push(`html is ${trimmed.length} characters, the limit is ${MAX_EMBED_SIZE}: aggregate or downsample the data`); } if (/<\s*(html|head|body)\b/i.test(trimmed) || / +