Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
// Regenerates the Lezer parsers of the Mermaid language, src/languages/mermaid/parsers/<diagram>/
// parser.ts and parser.terms.ts, from the <diagram>.grammar next to them. Run it after editing a
// grammar:
// pnpm --filter @triliumnext/codemirror build:mermaid-grammars
// `mermaid.spec.ts` fails while a committed parser differs from what its grammar generates.
import { readdirSync, readFileSync, writeFileSync } from "node:fs";
import { basename, dirname, join } from "node:path";
import { buildParserFile } from "@lezer/generator";
export const PARSERS_DIR = join(import.meta.dirname, "../src/languages/mermaid/parsers");
const HEADER =
"// AUTO-GENERATED by scripts/build_mermaid_grammars.mts from the grammar in this directory.\n";
/** Lists the `.grammar` files, one per diagram directory. */
export function listGrammars(): string[] {
return readdirSync(PARSERS_DIR, { withFileTypes: true })
.filter((entry) => entry.isDirectory())
.map((entry) => join(PARSERS_DIR, entry.name, `${entry.name}.grammar`));
}
/** Generates the parser and terms files of a grammar, keyed by the path each belongs at. */
export function buildGrammar(grammarPath: string): Record<string, string> {
const { parser, terms } = buildParserFile(readFileSync(grammarPath, "utf8"), {
fileName: basename(grammarPath),
typeScript: true
});
const dir = dirname(grammarPath);
return {
[join(dir, "parser.ts")]: HEADER + parser,
[join(dir, "parser.terms.ts")]: HEADER + terms
};
}
if (process.argv[1] === import.meta.filename) {
for (const grammarPath of listGrammars()) {
for (const [ path, content ] of Object.entries(buildGrammar(grammarPath))) {
writeFileSync(path, content);
}
console.log(`Generated ${basename(dirname(grammarPath))}`);
}
}