All files / src/lib/dev-tools markdown-parser.ts

97.44% Statements 229/235
93.02% Branches 40/43
100% Functions 12/12
97.44% Lines 229/235

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 2361x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 783x 783x 783x 783x 783x 1x 1x 1x 1x 779x 779x 779x 779x 779x 779x         1x 1x 1x 1x 779x 779x 779x 779x 779x 779x 27222x 27222x 27222x 27222x 27222x 27222x 27222x 27222x 27222x 779x 779x 779x 1x 1x 1x 1x 716x 716x 716x 716x 1x 1x 1x 1x 716x 716x 716x 716x 1x 1x 1x 1x 1x 783x 783x 1x 1x 782x 782x 782x 779x 779x 779x 779x 779x 779x 779x 779x 779x 783x 3x 3x 783x 1x 1x 1x 1x 10x 10x 10x 10x 10x 10x 10x     10x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 124x 124x 124x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 124x 4x 4x 4x 4x 600x 600x 600x 600x 600x 600x 600x 600x 600x 600x 600x 600x 600x 600x 600x 4x 4x 4x 2812x 2812x 2812x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 2x 2x 2x 1x 1x 1x 1x 1x 2x 2x 2x 2x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x  
/**
 * Markdown Parser Utility
 * Read and parse markdown files for plans and guides viewer
 */
 
import fs from 'fs/promises';
import path from 'path';
import type { MarkdownDocument, MarkdownHeading, PlanSummary, GuideSummary } from './types';
 
// Base paths for documentation
const DOCS_BASE = path.join(process.cwd(), 'docs');
const PLANS_DIR = path.join(DOCS_BASE, 'plans');
const PLANS_ARCHIVE_DIR = path.join(PLANS_DIR, 'archive');
const GUIDES_DIR = path.join(DOCS_BASE, 'guides');
 
/**
 * Validate that a path is within allowed directory
 */
function isPathAllowed(filePath: string, allowedBase: string): boolean {
  const resolved = path.resolve(filePath);
  const normalizedBase = path.normalize(allowedBase);
  return resolved.startsWith(normalizedBase);
}
 
/**
 * Extract title from markdown content
 */
function extractTitle(content: string, filename: string): string {
  // Look for first H1 heading
  const h1Match = content.match(/^#\s+(.+)$/m);
  if (h1Match) {
    return h1Match[1].trim();
  }

  // Fallback to filename
  return filename.replace(/\.md$/i, '').replace(/[-_]/g, ' ');
}
 
/**
 * Extract headings from markdown content
 */
function extractHeadings(content: string): MarkdownHeading[] {
  const headings: MarkdownHeading[] = [];
  const headingRegex = /^(#{1,6})\s+(.+)$/gm;
 
  let match;
  while ((match = headingRegex.exec(content)) !== null) {
    const level = match[1].length;
    const text = match[2].trim();
    const id = text
      .toLowerCase()
      .replace(/[^\w\s-]/g, '')
      .replace(/\s+/g, '-');
 
    headings.push({ level, text, id });
  }
 
  return headings;
}
 
/**
 * Extract priority from plan content
 */
function extractPriority(content: string): string | undefined {
  const match = content.match(/\*\*Priority\*\*:\s*(\w+)/i);
  return match ? match[1] : undefined;
}
 
/**
 * Extract complexity from plan content
 */
function extractComplexity(content: string): string | undefined {
  const match = content.match(/\*\*Complexity\*\*:\s*(\w+(?:-\w+)?)/i);
  return match ? match[1] : undefined;
}
 
/**
 * Parse a markdown file
 */
export async function parseMarkdownFile(filePath: string): Promise<MarkdownDocument | null> {
  // Validate path is within docs directory
  if (!isPathAllowed(filePath, DOCS_BASE)) {
    return null;
  }
 
  try {
    const content = await fs.readFile(filePath, 'utf-8');
    const stats = await fs.stat(filePath);
    const filename = path.basename(filePath);
 
    return {
      title: extractTitle(content, filename),
      filename,
      content,
      headings: extractHeadings(content),
      modifiedAt: stats.mtime.toISOString()};
  } catch {
    return null;
  }
}
 
/**
 * List markdown files in a directory
 */
async function listMarkdownFiles(directory: string): Promise<string[]> {
  try {
    const files = await fs.readdir(directory);
    return files
      .filter(file => file.endsWith('.md'))
      .map(file => path.join(directory, file));
  } catch {
    return [];
  }
}
 
/**
 * Get all plans (active and archived)
 */
export async function getPlans(): Promise<{ active: PlanSummary[]; archived: PlanSummary[] }> {
  const active: PlanSummary[] = [];
  const archived: PlanSummary[] = [];
 
  // Get active plans
  const activePlanFiles = await listMarkdownFiles(PLANS_DIR);
  for (const filePath of activePlanFiles) {
    const filename = path.basename(filePath);
    // Skip non-plan files
    if (!filename.startsWith('PLAN_')) continue;
 
    const doc = await parseMarkdownFile(filePath);
    if (doc) {
      active.push({
        slug: filename.replace(/\.md$/i, ''),
        title: doc.title,
        filename,
        status: 'active',
        priority: extractPriority(doc.content),
        complexity: extractComplexity(doc.content),
        modifiedAt: doc.modifiedAt});
    }
  }
 
  // Get archived plans
  const archivedPlanFiles = await listMarkdownFiles(PLANS_ARCHIVE_DIR);
  for (const filePath of archivedPlanFiles) {
    const filename = path.basename(filePath);
    if (!filename.startsWith('PLAN_')) continue;
 
    const doc = await parseMarkdownFile(filePath);
    if (doc) {
      archived.push({
        slug: filename.replace(/\.md$/i, ''),
        title: doc.title,
        filename,
        status: 'archived',
        priority: extractPriority(doc.content),
        complexity: extractComplexity(doc.content),
        modifiedAt: doc.modifiedAt});
    }
  }
 
  // Sort by plan number
  const sortByPlanNumber = (a: PlanSummary, b: PlanSummary) => {
    const numA = parseInt(a.slug.match(/PLAN_(\d+)/)?.[1] || '0', 10);
    const numB = parseInt(b.slug.match(/PLAN_(\d+)/)?.[1] || '0', 10);
    return numA - numB;
  };
 
  active.sort(sortByPlanNumber);
  archived.sort(sortByPlanNumber);
 
  return { active, archived };
}
 
/**
 * Get a single plan by slug
 */
export async function getPlanBySlug(slug: string): Promise<MarkdownDocument | null> {
  // Sanitize slug to prevent path traversal
  const sanitizedSlug = slug.replace(/[^a-zA-Z0-9_-]/g, '');
 
  // Try active plans first
  let filePath = path.join(PLANS_DIR, `${sanitizedSlug}.md`);
  let doc = await parseMarkdownFile(filePath);
 
  if (!doc) {
    // Try archived plans
    filePath = path.join(PLANS_ARCHIVE_DIR, `${sanitizedSlug}.md`);
    doc = await parseMarkdownFile(filePath);
  }
 
  return doc;
}
 
/**
 * Get all guides
 */
export async function getGuides(): Promise<GuideSummary[]> {
  const guides: GuideSummary[] = [];
 
  const guideFiles = await listMarkdownFiles(GUIDES_DIR);
  for (const filePath of guideFiles) {
    const filename = path.basename(filePath);
    const doc = await parseMarkdownFile(filePath);
 
    if (doc) {
      // Extract description from first paragraph after title
      const descMatch = doc.content.match(/^#.+\n+([^#\n].+)/);
      const description = descMatch ? descMatch[1].trim() : undefined;
 
      guides.push({
        slug: filename.replace(/\.md$/i, ''),
        title: doc.title,
        filename,
        description,
        modifiedAt: doc.modifiedAt});
    }
  }
 
  // Sort alphabetically by title
  guides.sort((a, b) => a.title.localeCompare(b.title));
 
  return guides;
}
 
/**
 * Get a single guide by slug
 */
export async function getGuideBySlug(slug: string): Promise<MarkdownDocument | null> {
  // Sanitize slug to prevent path traversal
  const sanitizedSlug = slug.replace(/[^a-zA-Z0-9_-]/g, '');
  const filePath = path.join(GUIDES_DIR, `${sanitizedSlug}.md`);
 
  return parseMarkdownFile(filePath);
}