chore: improve errors for bad YAML frontmatter

Adds a custom error message for any mermaid diagram that starts with
a `---`. Normally, these are expected to be part of a YAML front-matter
block, but indentation issues or a missing closing `---` may cause
these to be not parsed correctly.
This commit is contained in:
Alois Klink
2022-12-01 22:43:03 +00:00
parent f884b745dc
commit accba3f408
3 changed files with 42 additions and 2 deletions

View File

@@ -125,6 +125,33 @@ export const addDiagrams = () => {
},
(text) => text.toLowerCase().trim() === 'error'
);
registerDiagram(
'---',
// --- diagram type may appear if YAML front-matter is not parsed correctly
{
db: {
clear: () => {
// Quite ok, clear needs to be there for --- to work as a regular diagram
},
},
styles: errorStyles, // should never be used
renderer: errorRenderer, // should never be used
parser: {
parser: { yy: {} },
parse: () => {
throw new Error(
'Diagrams beginning with --- are not valid. ' +
'If you were trying to use a YAML front-matter, please ensure that ' +
"you've correctly opened and closed the YAML front-matter with unindented `---` blocks"
);
},
},
init: () => null, // no op
},
(text) => {
return text.toLowerCase().trimStart().startsWith('---');
}
);
registerDiagram(
'c4',

View File

@@ -629,6 +629,19 @@ describe('mermaidAPI', function () {
expect(mermaid.parseError).toEqual(undefined);
expect(() => mermaidAPI.parse('this is not a mermaid diagram definition')).toThrow();
});
it('throws for a nicer error for a invalid definition starting with `---`', function () {
expect(mermaid.parseError).toEqual(undefined);
expect(() =>
mermaidAPI.parse(`
---
title: a malformed YAML front-matter
`)
).toThrow(
'Diagrams beginning with --- are not valid. ' +
'If you were trying to use a YAML front-matter, please ensure that ' +
"you've correctly opened and closed the YAML front-matter with unindented `---` blocks"
);
});
it('does not throw for a valid definition', function () {
expect(() => mermaidAPI.parse('graph TD;A--x|text including URL space|B;')).not.toThrow();
});

View File

@@ -238,9 +238,9 @@ Alice->Bob: hi`;
const type = detectType(str);
expect(type).toBe('gitGraph');
});
it('should not allow frontmatter with leading spaces', function () {
it('should handle malformed frontmatter (with leading spaces) with `---` error graphtype', function () {
const str = ' ---\ntitle: foo\n---\n gitGraph TB:\nbfs1:queue';
expect(() => detectType(str)).toThrow('No diagram type detected for text');
expect(detectType(str)).toBe('---');
});
});
describe('when finding substring in array ', function () {