legal-markdown-js
v3.5.0
Published
Node.js implementation of LegalMarkdown for processing legal documents with markdown and YAML - Complete feature parity with Ruby version
Maintainers
Readme
Legal Markdown JS
A Node.js and TypeScript implementation of the original Ruby LegalMarkdown project. Legal Markdown JS processes legal markdown documents with advanced features and PDF/HTML exports.
Process markdown with YAML front matter, conditional clauses
[text]{condition}, cross-references |reference|, mixins {{variable}},
imports @import, and generate professional PDFs ready to be shared.

Table of Contents
Installation
npm install legal-markdown-jsAfter installation, you'll have access to these commands:
legal-md- Standard command-line interface with options and flagslegal-md-ui- Interactive CLI with guided prompts and smart defaultslegal-md-setup- Configuration setup script for easy environment setuplegal-md-playground- Local playground server for testing and exploration
🚀 Try it Online
Live Playground - Try Legal Markdown JS directly in your browser with live examples and real-time processing.
Local Playground
You can also run the playground locally for offline use or testing:
# Start local playground server (when installed globally)
legal-md-playground
# Or with custom port
legal-md-playground --port=3000
# Or if installed locally in a project
npm run web:serveThe playground provides the same interactive experience as the online version, including real-time processing, syntax highlighting, and example templates.
Quick Start
Initial Setup (Optional)
For the best experience, especially if you're new to Legal Markdown JS, run the setup script to configure your environment:
# Configure paths and directories (when installed globally)
legal-md-setup
# Or if installed locally in a project
npm run setup-configThis creates a personalized configuration file that the tool will automatically find and use.
Command Line Usage
Standard CLI
# Basic document processing
legal-md input.md output.md
# Generate PDF with highlighting
legal-md document.md --pdf --highlight
# Process with custom CSS and archive source
legal-md document.md --html --css styles.css --archive-source
# Archive to custom directory
legal-md document.md --archive-source ./processedInteractive CLI
For a guided, user-friendly experience, use the interactive CLI:
# Launch interactive mode
legal-md-uiThe interactive CLI provides:
- 📁 Smart file discovery: Automatically scans your input directory for
supported files (
.md,.markdown,.rst,.tex,.latex,.txt) - 🎯 Multiple output formats: Select any combination of PDF, HTML, Markdown, and metadata export
- ⚙️ Conditional options: Processing options adapt based on your selected formats
- 🎨 CSS selection: Choose from available stylesheets or proceed without custom styling
- 📦 Source archiving: Configure automatic archiving of source files after successful processing
- 📋 Configuration summary: Review all settings before processing
- ✅ Clear results: See exactly which files were generated
Programmatic Usage
import {
processLegalMarkdown,
processLegalMarkdownAsync,
} from 'legal-markdown-js';
// Synchronous processing
const result = processLegalMarkdown(content, {
basePath: './documents',
exportMetadata: true,
exportFormat: 'json',
});
// Asynchronous processing with remark pipeline (recommended)
const asyncResult = await processLegalMarkdownAsync(content, {
basePath: './documents',
exportMetadata: true,
exportFormat: 'json',
enableFieldTracking: true,
});
console.log(asyncResult.content);
console.log(asyncResult.metadata);
console.log(asyncResult.fieldReport); // Enhanced field trackingKey Features
Core Compatibility
All original Legal Markdown features are fully implemented:
- File Formats: Markdown, ASCII, reStructuredText, LaTeX
- YAML Front Matter: Complete parsing with all standard fields
- Headers & Numbering: Full hierarchical numbering system (
l.,ll.,lll.) - Optional Clauses: Boolean, equality, and logical operations
(
[text]{condition}) - Cross-References: Internal section references using (
|reference|) syntax - Partial Imports: File inclusion with path resolution (
@import) - Metadata Export: YAML and JSON export with custom paths
Node.js Enhancements
Additional features available only in the Node.js version:
- Interactive CLI: User-friendly guided interface with smart file discovery and configuration management
- Mixins System: Template substitution and helpers with
{{variable}}syntax - AST-Based Processing: Modern AST-based mixin processing to prevent text contamination (v2.4.0+)
- Pipeline Architecture: Configurable step-based processing pipeline with dependency management and performance monitoring (v2.4.0+)
- PDF Generation: Professional PDF output with styling and field highlighting
- HTML Generation: Custom HTML output with CSS support
- Template Loops: Array iteration with
{{#items}}...{{/items}}syntax - Helper Functions: Date, number, and string formatting helpers
- Force Commands: Document-driven configuration with embedded CLI options
- Batch Processing: Multi-file processing with concurrency control
- Field Tracking: Enhanced field tracking with proper categorization for document review
- Source File Archiving: Automatic archiving of source files after successful processing with conflict resolution
Architecture & Performance
Modern Pipeline System (v2.4.0+)
Legal Markdown JS features a completely rewritten processing pipeline that provides:
- Step-Based Architecture: Configurable processing steps with dependency management
- AST-Based Processing: Modern AST parsing for mixin processing to prevent text contamination
- Performance Monitoring: Built-in step profiling and performance metrics
- Error Recovery: Graceful error handling and comprehensive logging
- Field Tracking: Enhanced field tracking with proper status categorization
Processing Order
The new pipeline ensures correct processing order to prevent conflicts:
- YAML Front Matter - Parse document metadata
- Import Processing - Handle file imports and inclusions
- Optional Clauses - Process conditional text blocks
- Cross-References - Resolve internal document references
- Template Loops - Expand array iterations first
- AST Mixin Processing - Process variables and helpers (avoids loop conflicts)
- Header Processing - Apply numbering and formatting
- Field Tracking - Apply highlighting and generate reports
API Usage
// Use the remark-based async API for best performance
const result = await processLegalMarkdownAsync(content, options);
// Comprehensive error handling and validation
// Full remark-based processing for all documentsDocumentation
User Documentation
- Getting Started - Installation and setup guide
- CLI Reference - Complete command-line interface documentation
- Features Guide - All features, helpers, and advanced usage
- Handlebars Helpers - Complete reference of all available Handlebars helpers (30+ helpers)
- Handlebars Migration Guide - ⚠️ Migrating from legacy syntax to Handlebars (legacy syntax deprecated)
- Headers & Numbering - Hierarchical numbering system guide
- CSS Classes Reference - CSS classes for styling and document review
- Features Overview - Complete feature implementation status and testing coverage
Developer Documentation
- Architecture - Complete system architecture and design patterns
- Contributing Guide - Development workflow, standards, and contribution guidelines
- Helper Functions - Complete reference for template helpers and functions
- Development Guide - Complete developer setup and workflow
- Release Process - Versioning and release procedures
- Scripts Reference - Available npm scripts and commands
- API Documentation - Auto-generated TypeScript API docs
Testing
# Run all tests
npm test
# Run specific test types
npm run test:unit
npm run test:integration
npm run test:e2e
# Run with coverage
npm run test:coverage- Unit Tests: Test individual components in isolation
- Integration Tests: Test complete workflows and feature combinations
- E2E Tests: Test CLI interface and full application behavior
- Path Validation Tests: Test environment configuration and error handling
Configuration
Legal Markdown JS supports environment-based configuration for customizing file paths and directories.
Quick Setup (Recommended)
For easy configuration setup, especially for non-technical users:
# Run the setup script (when installed globally)
legal-md-setup
# Or if installed locally in a project
npm run setup-configThis script will:
- Create a configuration directory at
~/.config/legal-markdown-js/ - Copy the configuration template with helpful comments
- Provide clear instructions on how to customize your paths
- Show you exactly where to edit your settings
Manual Configuration
If you prefer manual setup, create a .env file in one of these locations (in
order of precedence):
- Current working directory:
./.env - Your home directory:
~/.env - Config directory:
~/.config/legal-markdown-js/.env
# Copy the example configuration
cp .env.example .env
# Edit the configuration
nano .envPath Configuration Examples
# Custom asset organization
IMAGES_DIR=assets/media
STYLES_DIR=assets/css
# Separate project structure
DEFAULT_INPUT_DIR=documents/source
DEFAULT_OUTPUT_DIR=documents/generated
ARCHIVE_DIR=documents/archive
# Absolute paths (useful for CI/CD)
IMAGES_DIR=/var/lib/legal-markdown/images
DEFAULT_OUTPUT_DIR=/var/lib/legal-markdown/output
ARCHIVE_DIR=/var/lib/legal-markdown/archiveUsing Custom Paths in Code
import { PATHS, RESOLVED_PATHS } from 'legal-markdown-js';
// Access configured paths
console.log(PATHS.STYLES_DIR); // Relative path from .env
console.log(RESOLVED_PATHS.STYLES_DIR); // Absolute resolved pathContributing
We welcome contributions! Please see our Contributing Guide for:
- Development setup and workflow
- Coding standards and best practices
- Testing requirements
- Pull request process
Quick Start for Contributors
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Follow the development guidelines
- Run the test suite (
npm test) - Submit a Pull Request
License
MIT License - see LICENSE file for details.
Acknowledgments
- Original LegalMarkdown project by Casey Kuhlman
- The legal tech community for inspiration and feedback
