lezer-template-json
v0.1.4
Published
A Lezer grammar for parsing template JSON
Maintainers
Readme
lezer-template-json
A Lezer grammar for parsing template JSON (JSON with {{variable}} holes) with incremental parsing support and TypeScript definitions.
Install
npm i lezer-template-jsonFeatures
- Supports parsing template JSON with
{{variable}}syntax
Usage
Basic
import { parser } from "lezer-template-json";
const tree = parser.parse(`{
"name": {{name}},
"age": {{age}},
"nested": {
"value": {{value}}
}
}`);
console.log(tree.toString());With CodeMirror
import { parser, templateJsonHighlighting } from "lezer-template-json";
import { LRLanguage } from "@codemirror/language";
import { HighlightStyle, syntaxHighlighting } from "@codemirror/language";
const templateJsonLanguage = LRLanguage.define({
parser,
languageData: { name: "template-json" },
});
const highlightStyle = HighlightStyle.define([templateJsonHighlighting]);
const extensions = [templateJsonLanguage, syntaxHighlighting(highlightStyle)];Tree Navigation
import { parser } from "lezer-template-json";
import * as terms from "lezer-template-json";
const tree = parser.parse(`{
"name": {{name}},
"age": {{age}}
}`);
const cursor = tree.cursor();
while (cursor.next()) {
if (cursor.type.id === terms.Variable) {
console.log(`Found variable: ${cursor.node.name}`);
}
}Error Handling
import { parser } from "lezer-template-json";
function parseWithErrors(pattern: string) {
const tree = parser.parse(pattern);
const errors: any[] = [];
tree.cursor().iterate((node) => {
if (node.type.isError) {
errors.push({
from: node.from,
to: node.to,
message: `Syntax error at ${node.from}-${node.to}`,
});
}
});
return { tree, errors };
}API
Exports
parser- Lezer parser instancetemplateJsonHighlighting- CodeMirror syntax highlighting- Grammar terms - Node type constants for tree navigation
Types
parser.parse(input: string, fragments?: TreeFragment[], ranges?: {from: number, to: number}[]): TreeDevelopment
git clone https://github.com/Sec-ant/lezer-template-json
cd lezer-template-json
pnpm install
pnpm build
pnpm testCommands:
pnpm test:run- Run all testspnpm test:ui- Interactive test UI
Contributing
- Fork the repository
- Create a feature branch
- Add tests in
tests/fixtures/ - Ensure tests pass
- Submit a pull request
License
MIT
