| .. | ||
| coverage | ||
| dist | ||
| src | ||
| test | ||
| history.json | ||
| openai.md | ||
| package.json | ||
| pnpm-lock.yaml | ||
| query.json | ||
| README.md | ||
| readme.md.json | ||
| stats.json | ||
| tools-output.json | ||
| tools.json | ||
| tsconfig.json | ||
| vitest.config.ts | ||
Markdown Tree Parser
A TypeScript utility for parsing markdown files into a hierarchical tree structure based on headings.
Features
- Parses markdown content into a tree structure
- Maintains heading hierarchy
- Preserves content between headings
- Type-safe implementation using mdast types
- Schema validation using Zod
- Structured logging with tslog
- Provides comprehensive typing support
- Command-line interface (CLI)
- Comprehensive test suite using Vitest
Installation
npm install
Build
To build the project:
npm run build
This will create the compiled files in the dist directory.
Testing
The project uses Vitest for testing. The following commands are available:
# Run tests once
npm test
# Run tests in watch mode
npm run test:watch
# Run tests with coverage
npm run test:coverage
Usage
CLI Usage
After installing the package, you can use the CLI tool:
# Parse a markdown file and output as JSON
mdtree parse example.md
# Get help
mdtree --help
CLI Options:
--json, -j: Output as JSON (default: true)
Programmatic Usage
import { parseMarkdownToTree } from 'markdown-tree-parser';
const markdown = `
# Heading 1
Some content
## Heading 1.1
More content
# Heading 2
Final content
`;
const tree = parseMarkdownToTree(markdown);
console.log(JSON.stringify(tree, null, 2));
Key Components
Zod Schema Validation
We use Zod for runtime type validation of our data structures. The main schemas are:
const HeadingNodeSchema = z.lazy(() => z.object({
title: z.string(),
depth: z.number().min(0).max(6),
content: z.string().optional(),
children: z.array(HeadingNodeSchema)
}));
type HeadingNode = z.infer<typeof HeadingNodeSchema>;
API
parseMarkdownToTree(markdown: string): HeadingNode
Converts a markdown string into a tree structure based on headings. Uses mdast under the hood for reliable markdown parsing. All nodes are validated using Zod schemas.
Dependencies
- mdast-util-from-markdown: For parsing markdown into AST
- mdast-util-to-string: For converting AST nodes to strings
- @types/mdast: For TypeScript type definitions
- tslog: For structured logging
- zod: For runtime type validation
- yargs: For CLI functionality
- vitest: For testing
Development
To contribute to the project:
- Install dependencies:
npm install - Make your changes
- Run tests:
npm test - Build the project:
npm run build
License
MIT