fix(web): make mermaid sanitizer quote-aware and detect parens in bracket labels (#763)
* fix(web): make mermaid sanitizer quote-aware and detect parens in bracket labels
Two diagrams failed to render because sanitizeMermaidCode injected nested
quotes into already-quoted labels and missed parens-as-stadium-opener inside
bracket labels. Skip ranges already inside `"..."` (recomputed between
passes) and add `(`/`)` to the bracket-pass trigger set.
* refactor(web): drop dead text.startsWith('"') guards in mermaid sanitizer
The regex character classes [^\]"], [^|"], [^)"] already exclude `"`,
so the guards were unreachable.
* fix(web): stop unterminated quote bleeding across lines in mermaid sanitizer
findQuotedRanges now stops scanning at newline; an unterminated `"` is
discarded rather than paired with a `"` on a later line where it would
silently suppress sanitization of unrelated content. Add tests for the
cross-line guard and for a bracket-with-parens adjacent to a real
stadium node on the same line.
This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { sanitizeMermaidCode } from "./mermaid-utils";
|
||||
|
||||
describe("sanitizeMermaidCode", () => {
|
||||
it("leaves a pre-quoted bracket label with parens inside untouched", () => {
|
||||
const input = `D --> E["router.push('/github')"]`;
|
||||
expect(sanitizeMermaidCode(input)).toBe(input);
|
||||
});
|
||||
|
||||
it("quotes a bracket label containing slashes alongside a pre-quoted neighbour", () => {
|
||||
const input = `A[plain] --> B[Types 'github' / 'pr' / 'dashboard']\nD --> E["router.push('/github')"]`;
|
||||
const out = sanitizeMermaidCode(input);
|
||||
expect(out).toContain(`B["Types 'github' / 'pr' / 'dashboard'"]`);
|
||||
expect(out).toContain(`E["router.push('/github')"]`);
|
||||
});
|
||||
|
||||
it("leaves an init directive with single quotes untouched", () => {
|
||||
const input = `%%{init: {'theme': 'neutral'}}%%`;
|
||||
expect(sanitizeMermaidCode(input)).toBe(input);
|
||||
});
|
||||
|
||||
it("quotes a bracket label containing parens", () => {
|
||||
const input = `Action[reorderSidebarViews(activeId, overId)]`;
|
||||
expect(sanitizeMermaidCode(input)).toBe(`Action["reorderSidebarViews(activeId, overId)"]`);
|
||||
});
|
||||
|
||||
it("quotes a bracket label containing arrow `->`", () => {
|
||||
const input = `SSR[fetchUserSettings -> mapUserSettingsResponse]`;
|
||||
expect(sanitizeMermaidCode(input)).toBe(`SSR["fetchUserSettings -> mapUserSettingsResponse"]`);
|
||||
});
|
||||
|
||||
it("quotes a standalone stadium node containing `/`", () => {
|
||||
const input = `X(/api/v1)`;
|
||||
expect(sanitizeMermaidCode(input)).toBe(`X("/api/v1")`);
|
||||
});
|
||||
|
||||
it("quotes an edge label containing `/`", () => {
|
||||
const input = `A -->|/path/to/x| B`;
|
||||
expect(sanitizeMermaidCode(input)).toBe(`A -->|"/path/to/x"| B`);
|
||||
});
|
||||
|
||||
it("leaves a plain stadium node alone", () => {
|
||||
const input = `Y(plain text)`;
|
||||
expect(sanitizeMermaidCode(input)).toBe(input);
|
||||
});
|
||||
|
||||
it("does not corrupt parens inside a bracket label after the bracket pass quotes it", () => {
|
||||
// Pass 1 wraps `[fetch(/api/x)]` -> `["fetch(/api/x)"]`. Pass 3 must skip the
|
||||
// newly-quoted region rather than re-wrapping `(/api/x)` and producing nested quotes.
|
||||
const input = `Z[fetch(/api/x)]`;
|
||||
expect(sanitizeMermaidCode(input)).toBe(`Z["fetch(/api/x)"]`);
|
||||
});
|
||||
|
||||
it("renders the full reported case 1 diagram without nested quotes", () => {
|
||||
const input = [
|
||||
`%%{init: {'theme': 'neutral'}}%%`,
|
||||
`flowchart TD`,
|
||||
` A[User opens Cmd+K panel] --> B[Types 'github' / 'pr' / 'dashboard']`,
|
||||
` D --> E["router.push('/github')"]`,
|
||||
].join("\n");
|
||||
const out = sanitizeMermaidCode(input);
|
||||
expect(out).not.toContain(`("'`);
|
||||
expect(out).toContain(`E["router.push('/github')"]`);
|
||||
expect(out).toContain(`B["Types 'github' / 'pr' / 'dashboard'"]`);
|
||||
});
|
||||
|
||||
it("quotes a stadium node next to a bracket-with-parens on the same line", () => {
|
||||
// Pass 1 quotes `[fn(x)]` (parens inside bracket). Pass 3 must still quote
|
||||
// the adjacent stadium `(/api/v1)` — the new quoted range from pass 1 must
|
||||
// not leak past its actual close and suppress the unrelated stadium node.
|
||||
const input = `A[fn(x)] --> B(/api/v1)`;
|
||||
expect(sanitizeMermaidCode(input)).toBe(`A["fn(x)"] --> B("/api/v1")`);
|
||||
});
|
||||
|
||||
it("does not let an unterminated quote leak across lines", () => {
|
||||
// Line 1 has a stray `"` with no closing pair on the same line. The newline
|
||||
// guard in findQuotedRanges discards that opener instead of pairing it with
|
||||
// a `"` on a later line, so the bracket label on line 2 still gets quoted.
|
||||
const input = `%% stray " comment\nB[/api/x]`;
|
||||
const out = sanitizeMermaidCode(input);
|
||||
expect(out).toContain(`B["/api/x"]`);
|
||||
});
|
||||
});
|
||||
@@ -39,40 +39,79 @@ export function getSvgDimensions(container: HTMLElement): { w: number; h: number
|
||||
*/
|
||||
const SPECIAL_CHARS_RE = /[$#&/\\<>{}]/;
|
||||
|
||||
/**
|
||||
* Bracket-pass trigger: parens are mermaid grammar metachars (stadium-shape
|
||||
* opener) and break parsing when they appear inside `[...]` labels, so they
|
||||
* force quoting in bracket labels even though they're legal in standalone
|
||||
* `(...)` stadium nodes.
|
||||
*/
|
||||
const BRACKET_TRIGGER_RE = /[$#&/\\<>{}()]/;
|
||||
|
||||
/**
|
||||
* Index ranges of every top-level `"..."` span (start = opening `"`, end = closing `"`).
|
||||
* Scan stops at newline so an unterminated `"` on one line cannot pair with a
|
||||
* `"` on a later line and silently suppress sanitization of unrelated content.
|
||||
*/
|
||||
function findQuotedRanges(s: string): Array<[number, number]> {
|
||||
const out: Array<[number, number]> = [];
|
||||
let i = 0;
|
||||
while (i < s.length) {
|
||||
if (s[i] === '"' && s[i - 1] !== "\\") {
|
||||
const start = i;
|
||||
i++;
|
||||
while (i < s.length && s[i] !== "\n" && !(s[i] === '"' && s[i - 1] !== "\\")) i++;
|
||||
if (i < s.length && s[i] === '"') out.push([start, i]);
|
||||
}
|
||||
i++;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const inAnyRange = (offset: number, ranges: Array<[number, number]>): boolean =>
|
||||
ranges.some(([a, b]) => offset >= a && offset <= b);
|
||||
|
||||
/**
|
||||
* Preprocesses mermaid code to quote text containing special characters.
|
||||
* Mermaid requires quotes around text with special chars like $, /, etc.
|
||||
*
|
||||
* Handles:
|
||||
* - Node labels: A[text] -> A["text"] if text contains special chars
|
||||
* - Node labels: A[text] -> A["text"] if text contains special chars or parens
|
||||
* - Edge labels: -->|text| -> -->|"text"| if text contains special chars
|
||||
* - Subgraph titles: subgraph text -> subgraph "text" if text contains special chars
|
||||
* - Stadium nodes: (text) -> ("text") if text contains special chars
|
||||
*
|
||||
* Skips any region already inside a user-supplied `"..."` label so we never
|
||||
* inject nested quotes into pre-quoted content.
|
||||
*/
|
||||
export function sanitizeMermaidCode(code: string): string {
|
||||
// Quote node labels: [text] or (text) or {text} or ([text]) or [[text]] etc.
|
||||
// Match brackets that aren't already quoted
|
||||
let result = code.replace(/(\[+)([^\]"]+?)(\]+)/g, (match, open, text, close) => {
|
||||
if (SPECIAL_CHARS_RE.test(text) && !text.startsWith('"')) {
|
||||
// Quote node labels: [text] or [[text]] etc. Match brackets that aren't already quoted.
|
||||
let quoted = findQuotedRanges(code);
|
||||
let result = code.replace(/(\[+)([^\]"]+?)(\]+)/g, (match, open, text, close, offset) => {
|
||||
if (inAnyRange(offset, quoted)) return match;
|
||||
if (BRACKET_TRIGGER_RE.test(text)) {
|
||||
return `${open}"${text}"${close}`;
|
||||
}
|
||||
return match;
|
||||
});
|
||||
|
||||
// Quote edge labels: |text|
|
||||
result = result.replace(/\|([^|"]+?)\|/g, (match, text) => {
|
||||
if (SPECIAL_CHARS_RE.test(text) && !text.startsWith('"')) {
|
||||
quoted = findQuotedRanges(result);
|
||||
result = result.replace(/\|([^|"]+?)\|/g, (match, text, offset) => {
|
||||
if (inAnyRange(offset, quoted)) return match;
|
||||
if (SPECIAL_CHARS_RE.test(text)) {
|
||||
return `|"${text}"|`;
|
||||
}
|
||||
return match;
|
||||
});
|
||||
|
||||
// Quote parentheses labels: (text) for stadium/circle nodes
|
||||
result = result.replace(/(\(+)([^)"]+?)(\)+)/g, (match, open, text, close) => {
|
||||
quoted = findQuotedRanges(result);
|
||||
result = result.replace(/(\(+)([^)"]+?)(\)+)/g, (match, open, text, close, offset) => {
|
||||
if (inAnyRange(offset, quoted)) return match;
|
||||
// Skip if it looks like a subgraph or keyword
|
||||
if (/^(subgraph|end|graph|flowchart|sequenceDiagram)\b/.test(text.trim())) {
|
||||
return match;
|
||||
}
|
||||
if (SPECIAL_CHARS_RE.test(text) && !text.startsWith('"')) {
|
||||
if (SPECIAL_CHARS_RE.test(text)) {
|
||||
return `${open}"${text}"${close}`;
|
||||
}
|
||||
return match;
|
||||
|
||||
Reference in New Issue
Block a user