From a6b35d336a00445d705f8a96cf29aa9d0baf08c5 Mon Sep 17 00:00:00 2001 From: Jarvis Date: Tue, 9 Sep 2025 22:31:12 +0200 Subject: [PATCH] refactor: extract MetadataExtractor from MarkdownPreprocessor MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Create MetadataExtractor.ts with static utility methods - Extract extractTags(), calculateWordCount(), and extractTitle() methods - Maintain complete implementation logic and regex patterns - Update MarkdownPreprocessor to use MetadataExtractor - Remove 65 lines from MarkdownPreprocessor (280→215 lines) - Build verification passes without errors 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- plan.md | 8 +- src/converters/MarkdownPreprocessor.ts | 71 +-------------- .../preprocessors/MetadataExtractor.ts | 86 +++++++++++++++++++ 3 files changed, 94 insertions(+), 71 deletions(-) create mode 100644 src/converters/preprocessors/MetadataExtractor.ts diff --git a/plan.md b/plan.md index d2f014f..8903fb5 100644 --- a/plan.md +++ b/plan.md @@ -122,7 +122,7 @@ The main.ts file is the plugin entry point and most critical to get right. **STOP** → Verify build → Test wikilink conversion works -### Step 2.3: Create EmbedProcessor.ts - IN PROGRESS +### Step 2.3: Create EmbedProcessor.ts - DONE **Location:** `src/converters/preprocessors/EmbedProcessor.ts` (~250 lines) **Extract:** - `parseEmbeds()` method @@ -134,7 +134,7 @@ The main.ts file is the plugin entry point and most critical to get right. **STOP** → Verify build → Test all embed types work -### Step 2.4: Create CalloutProcessor.ts +### Step 2.4: Create CalloutProcessor.ts - DONE **Location:** `src/converters/preprocessors/CalloutProcessor.ts` (~200 lines) **Extract:** - `parseCallouts()` method @@ -144,7 +144,7 @@ The main.ts file is the plugin entry point and most critical to get right. **STOP** → Verify build → Test callouts and email blocks work -### Step 2.5: Create MetadataExtractor.ts +### Step 2.5: Create MetadataExtractor.ts - DONE **Location:** `src/converters/preprocessors/MetadataExtractor.ts` (~150 lines) **Extract:** - `extractTags()` method @@ -154,7 +154,7 @@ The main.ts file is the plugin entry point and most critical to get right. **STOP** → Verify build → Test metadata extraction works -### Step 2.6: Update MarkdownPreprocessor.ts +### Step 2.6: Update MarkdownPreprocessor.ts - IN PROGRESS **Final size:** ~200 lines **Keep:** - Main `preprocess()` method diff --git a/src/converters/MarkdownPreprocessor.ts b/src/converters/MarkdownPreprocessor.ts index 3c25583..9290b35 100644 --- a/src/converters/MarkdownPreprocessor.ts +++ b/src/converters/MarkdownPreprocessor.ts @@ -7,6 +7,7 @@ import { FrontmatterProcessor, FrontmatterProcessorConfig } from './preprocessor import { WikilinkProcessor, WikilinkConfig, WikilinkProcessorConfig } from './preprocessors/WikilinkProcessor'; import { EmbedProcessor, EmbedProcessorConfig } from './preprocessors/EmbedProcessor'; import { CalloutProcessor } from './preprocessors/CalloutProcessor'; +import { MetadataExtractor } from './preprocessors/MetadataExtractor'; export interface PreprocessorOptions { /** Include metadata extraction in processing */ @@ -135,7 +136,7 @@ export class MarkdownPreprocessor { // Step 2: Extract additional tags from content (combine with frontmatter tags) if (this.options.includeMetadata) { - const contentTags = this.extractTags(result.content); + const contentTags = MetadataExtractor.extractTags(result.content); // Merge content tags with frontmatter tags, avoiding duplicates for (const tag of contentTags) { @@ -161,11 +162,11 @@ export class MarkdownPreprocessor { result.content = this.calloutProcessor.processCallouts(result.content, result); // Step 8: Calculate final metadata - result.metadata.wordCount = this.calculateWordCount(result.content); + result.metadata.wordCount = MetadataExtractor.calculateWordCount(result.content); // Use title from frontmatter if available, otherwise extract from content if (!result.metadata.title) { - result.metadata.title = this.extractTitle(result.content); + result.metadata.title = MetadataExtractor.extractTitle(result.content); } } catch (error) { @@ -175,72 +176,8 @@ export class MarkdownPreprocessor { return result; } - /** - * Extract tags from content - */ - private extractTags(content: string): string[] { - const tags: string[] = []; - - // Use more sophisticated regex to avoid false positives - // This pattern matches hashtags that are: - // 1. At the start of a line (with optional whitespace) - // 2. After whitespace - // 3. Not part of headings (# ## ### etc.) - // 4. Not inside code blocks or inline code - const enhancedTagPattern = /(?:^|\s)#([a-zA-Z][a-zA-Z0-9_/-]*[a-zA-Z0-9_]|[a-zA-Z][a-zA-Z0-9_]*)/gm; - - // Remove code blocks to avoid extracting tags from them - const contentWithoutCodeBlocks = content - .replace(/```[\s\S]*?```/g, '') // Remove fenced code blocks - .replace(/`[^`\n]*`/g, ''); // Remove inline code - - let match; - while ((match = enhancedTagPattern.exec(contentWithoutCodeBlocks)) !== null) { - const tag = match[1]; // Get the tag without the # prefix - - // Additional validation to ensure it's a proper tag - if (tag && tag.length > 0 && !tags.includes(tag)) { - // Skip if it looks like a heading (check if preceded by multiple #) - const fullMatch = match[0]; - const beforeTag = contentWithoutCodeBlocks.substring(Math.max(0, match.index - 5), match.index); - - // Skip if this appears to be part of a markdown heading - if (!beforeTag.includes('#')) { - tags.push(tag); - } - } - } - - enhancedTagPattern.lastIndex = 0; // Reset regex state - return tags; - } - /** - * Calculate word count from processed content - */ - private calculateWordCount(content: string): number { - // Remove markdown syntax and count words - const plainText = content - .replace(/[#*_`~\[\]()]/g, '') // Remove markdown formatting - .replace(/\s+/g, ' ') // Normalize whitespace - .trim(); - - return plainText ? plainText.split(/\s+/).length : 0; - } - /** - * Extract title from content (first heading or inferred from filename) - */ - private extractTitle(content: string): string | undefined { - // Look for first heading - const headingMatch = content.match(/^#+\s+(.+)$/m); - if (headingMatch) { - return headingMatch[1].trim(); - } - - // Could be enhanced to use filename or frontmatter title - return undefined; - } /** * Update configuration diff --git a/src/converters/preprocessors/MetadataExtractor.ts b/src/converters/preprocessors/MetadataExtractor.ts new file mode 100644 index 0000000..3da612b --- /dev/null +++ b/src/converters/preprocessors/MetadataExtractor.ts @@ -0,0 +1,86 @@ +/** + * MetadataExtractor.ts + * + * Handles extraction of metadata from markdown content including tags, titles, and word counts. + * This module provides pure utility functions for processing markdown content to extract + * various metadata elements used in the PDF export process. + */ + +export class MetadataExtractor { + /** + * Extracts hashtags from markdown content while avoiding false positives + * from code blocks and markdown headings. + * + * @param content - The markdown content to extract tags from + * @returns Array of unique tags found in the content (without # prefix) + */ + public static extractTags(content: string): string[] { + const tags: string[] = []; + + // Use more sophisticated regex to avoid false positives + // This pattern matches hashtags that are: + // 1. At the start of a line (with optional whitespace) + // 2. After whitespace + // 3. Not part of headings (# ## ### etc.) + // 4. Not inside code blocks or inline code + const enhancedTagPattern = /(?:^|\s)#([a-zA-Z][a-zA-Z0-9_/-]*[a-zA-Z0-9_]|[a-zA-Z][a-zA-Z0-9_]*)/gm; + + // Remove code blocks to avoid extracting tags from them + const contentWithoutCodeBlocks = content + .replace(/```[\s\S]*?```/g, '') // Remove fenced code blocks + .replace(/`[^`\n]*`/g, ''); // Remove inline code + + let match; + while ((match = enhancedTagPattern.exec(contentWithoutCodeBlocks)) !== null) { + const tag = match[1]; // Get the tag without the # prefix + + // Additional validation to ensure it's a proper tag + if (tag && tag.length > 0 && !tags.includes(tag)) { + // Skip if it looks like a heading (check if preceded by multiple #) + const fullMatch = match[0]; + const beforeTag = contentWithoutCodeBlocks.substring(Math.max(0, match.index - 5), match.index); + + // Skip if this appears to be part of a markdown heading + if (!beforeTag.includes('#')) { + tags.push(tag); + } + } + } + + enhancedTagPattern.lastIndex = 0; // Reset regex state + return tags; + } + + /** + * Calculates word count for markdown content by removing formatting and counting words. + * + * @param content - The markdown content to count words in + * @returns Number of words in the content + */ + public static calculateWordCount(content: string): number { + // Remove markdown syntax and count words + const plainText = content + .replace(/[#*_`~\[\]()]/g, '') // Remove markdown formatting + .replace(/\s+/g, ' ') // Normalize whitespace + .trim(); + + return plainText ? plainText.split(/\s+/).length : 0; + } + + /** + * Extracts title from markdown content by looking for the first heading. + * + * @param content - The markdown content to extract title from + * @returns The title text if found, undefined otherwise + */ + public static extractTitle(content: string): string | undefined { + // Look for first heading + const headingMatch = content.match(/^#+\s+(.+)$/m); + if (headingMatch) { + return headingMatch[1].trim(); + } + + // Could be enhanced to use filename or frontmatter title + return undefined; + } +} \ No newline at end of file