Add Docstrings

This commit is contained in:
AlexKucera committed 2025-11-05 08:03:52 +01:00
1 parent 7ac9e1f489
commit 281c02210a
17 files changed
+5380 -177

No files matched your search

+445 -9
View File
@@ -1,6 +1,35 @@
/**
* MarkdownPreprocessor - Converts Obsidian-specific markdown syntax to standard markdown
* compatible with Pandoc for Typst PDF export
* Markdown preprocessing pipeline for Obsidian-to-Pandoc conversion.
*
* This module provides the central preprocessing system that transforms Obsidian's
* proprietary markdown syntax into standard markdown compatible with Pandoc and Typst.
* It coordinates multiple specialized processors to handle:
* - YAML frontmatter extraction and formatting
* - Wikilink conversion to standard markdown links
* - Obsidian embed syntax (![[...]]) to standard images/includes
* - Callout blocks (>[!note]) to custom Typst environments
* - Email block formatting for email exports
* - Remote image detection and download queue management
* - Metadata extraction (tags, title, frontmatter)
*
* The preprocessor runs in a specific order to avoid conflicts:
* 1. Horizontal rule normalization (prevent YAML delimiter confusion)
* 2. Frontmatter extraction and processing
* 3. Email block formatting
* 4. Unnecessary link filtering (Open: links, Mail.app links)
* 5. Embed processing (![[image]], ![[pdf]])
* 6. Remote image detection (![](https://...))
* 7. Wikilink conversion ([[link]] → [link](link.md))
* 8. Callout block conversion
* 9. Title extraction
*
* Key features:
* - Stateless processing (each call is independent)
* - Comprehensive metadata extraction for export pipeline
* - Configurable wikilink and frontmatter handling
* - Remote resource tracking for download coordination
* - Error and warning reporting for user feedback
* - Modular processor architecture for maintainability
*/
import { FrontmatterProcessor, FrontmatterProcessorConfig } from './preprocessors/FrontmatterProcessor';
@@ -11,6 +40,13 @@ import { MetadataExtractor } from './preprocessors/MetadataExtractor';
import { HorizontalRuleProcessor } from './preprocessors/HorizontalRuleProcessor';
import * as path from 'path';
/**
* Configuration options for markdown preprocessing behavior.
*
* @property preserveFrontmatter - Keep YAML frontmatter in output (true) or strip it (false)
* @property baseUrl - Base URL for relative link resolution (optional)
* @property printFrontmatter - Display frontmatter as formatted text at document start (optional)
*/
export interface PreprocessorOptions {
/** Preserve existing frontmatter */
preserveFrontmatter: boolean;
@@ -20,7 +56,24 @@ export interface PreprocessorOptions {
printFrontmatter?: boolean;
}
/**
* Result of markdown preprocessing operation.
*
* Contains the processed content, extracted metadata, and any errors or warnings
* encountered during processing. The metadata includes information needed by
* downstream export components like embedded resources and frontmatter data.
*
* @property content - Processed markdown content ready for Pandoc
* @property metadata - Extracted metadata and resource tracking
* @property metadata.tags - Extracted tags from frontmatter and content
* @property metadata.frontmatter - Parsed YAML frontmatter object
* @property metadata.title - Document title (from frontmatter or H1)
* @property metadata.pdfEmbeds - PDF files embedded via ![[file.pdf]]
* @property metadata.imageEmbeds - Images embedded via ![[image.png]] or ![](url)
* @property metadata.fileEmbeds - Other files embedded via ![[file.ext]]
* @property errors - Critical processing errors
* @property warnings - Non-critical processing warnings
*/
export interface PreprocessingResult {
/** Processed markdown content */
content: string;
@@ -61,6 +114,36 @@ export interface PreprocessingResult {
warnings: string[];
}
/**
* Configuration for MarkdownPreprocessor initialization.
*
* Provides all settings needed to initialize the preprocessor and its
* constituent processors. This configuration is typically built from plugin
* settings and file context.
*
* @property vaultPath - Absolute path to vault root for file resolution
* @property options - Preprocessing behavior configuration
* @property wikilinkConfig - Wikilink conversion settings
* @property noteTitle - Optional title to prepend as H1 heading
*
* @example
* ```typescript
* const config: MarkdownPreprocessorConfig = {
* vaultPath: '/Users/name/vault',
* options: {
* preserveFrontmatter: true,
* printFrontmatter: false,
* baseUrl: ''
* },
* wikilinkConfig: {
* format: 'md',
* extension: '.md'
* },
* noteTitle: 'My Document'
* };
* const preprocessor = new MarkdownPreprocessor(config);
* ```
*/
export interface MarkdownPreprocessorConfig {
/** Vault path for file resolution */
vaultPath: string;
@@ -72,6 +155,72 @@ export interface MarkdownPreprocessorConfig {
noteTitle?: string;
}
/**
* Central markdown preprocessing coordinator for Obsidian-to-Pandoc conversion.
*
* This class orchestrates multiple specialized processors to transform Obsidian's
* proprietary markdown into standard markdown that Pandoc can process. It ensures
* processors run in the correct order to avoid syntax conflicts and maintains
* comprehensive metadata about the conversion.
*
* The preprocessor is stateless - each process() call is independent and doesn't
* affect previous or future calls. Configuration can be updated between calls via
* updateConfig().
*
* Architecture:
* - Delegates to specialized processors for specific syntax
* - Maintains processing order to prevent conflicts
* - Aggregates metadata from all processors
* - Provides error and warning reporting
*
* Processing Pipeline:
* 1. Horizontal rules (prevent YAML confusion)
* 2. Frontmatter (extract metadata, optionally format)
* 3. Email blocks (custom email formatting)
* 4. Link filtering (remove unnecessary links)
* 5. Embeds (convert ![[...]] syntax)
* 6. Remote images (detect and queue for download)
* 7. Wikilinks (convert [[...]] to standard links)
* 8. Callouts (convert >[!type] blocks)
* 9. Title extraction (from H1 or frontmatter)
*
* @example
* ```typescript
* // Initialize preprocessor
* const preprocessor = new MarkdownPreprocessor({
* vaultPath: '/path/to/vault',
* options: {
* preserveFrontmatter: true,
* printFrontmatter: false
* },
* wikilinkConfig: {
* format: 'md',
* extension: '.md'
* },
* noteTitle: 'My Note'
* });
*
* // Process markdown
* const obsidianMarkdown = '# My Note\n\n[[internal-link]]\n\n![[image.png]]';
* const result = await preprocessor.process(obsidianMarkdown);
*
* console.log(result.content); // Standard markdown
* console.log(result.metadata.imageEmbeds); // Image processing info
* console.log(result.errors); // Any errors encountered
* ```
*
* @example
* ```typescript
* // Update configuration for different export
* preprocessor.updateConfig({
* options: { preserveFrontmatter: false },
* noteTitle: 'Different Title'
* });
*
* // Process with new configuration
* const newResult = await preprocessor.process(markdown);
* ```
*/
export class MarkdownPreprocessor {
private vaultPath: string;
private options: PreprocessorOptions;
@@ -113,7 +262,72 @@ export class MarkdownPreprocessor {
}
/**
* Main processing method that converts Obsidian markdown to standard markdown
* Processes Obsidian markdown and converts it to standard Pandoc-compatible markdown.
*
* This is the main entry point for preprocessing. It runs all configured processors
* in the correct order, aggregates metadata from each stage, and returns a complete
* result with processed content and comprehensive metadata.
*
* The method is async to support future extensions (though current processors are sync).
* Processing is stateless - each call operates independently on the provided content.
*
* Processing Order (critical for avoiding conflicts):
* 1. Horizontal rules → Prevent YAML delimiter confusion
* 2. Frontmatter → Extract metadata, optionally format
* 3. Email blocks → Custom formatting for email exports
* 4. Link filtering → Remove Open: and Mail.app links
* 5. Embeds → Convert ![[...]] syntax first (before wikilinks add .md)
* 6. Remote images → Detect and queue ![](https://...) for download
* 7. Wikilinks → Convert [[...]] after embeds processed
* 8. Callouts → Convert >[!type] blocks to Typst environments
* 9. Title extraction → From H1 or frontmatter
*
* @param content - Raw Obsidian markdown content to process
* @returns Preprocessing result with converted content, metadata, and diagnostics
*
* @example
* ```typescript
* // Process note with various Obsidian syntax
* const markdown = `---
* title: My Note
* tags: [export, pdf]
* ---
*
* # My Note
*
* Internal link: [[other-note]]
* Image: ![[screenshot.png]]
* Callout: > [!note] This is important
* `;
*
* const result = await preprocessor.process(markdown);
*
* // Check for errors
* if (result.errors.length > 0) {
* console.error('Processing errors:', result.errors);
* }
*
* // Access processed content
* console.log(result.content); // Standard markdown
*
* // Access extracted metadata
* console.log(result.metadata.title); // "My Note"
* console.log(result.metadata.tags); // ["export", "pdf"]
* console.log(result.metadata.imageEmbeds); // [{originalPath, ...}]
* ```
*
* @example
* ```typescript
* // Handle remote images
* const markdown = '![Remote](https://example.com/image.png)';
* const result = await preprocessor.process(markdown);
*
* // Remote images are queued for download
* result.metadata.imageEmbeds.forEach(embed => {
* console.log(`Download: ${embed.originalPath}`);
* // Export pipeline will download and embed these
* });
* ```
*/
public async process(content: string): Promise<PreprocessingResult> {
const result: PreprocessingResult = {
@@ -167,8 +381,51 @@ export class MarkdownPreprocessor {
}
/**
* Process standard markdown images and track remote URLs for download
* Remote images are marked for later download and embedding
* Processes standard markdown images and queues remote URLs for download.
*
* This method scans the content for standard markdown image syntax `![alt](url)`
* and detects remote images (http:// or https://). Remote images are:
* - Replaced with marker placeholders in the content
* - Added to the imageEmbeds metadata for download by the export pipeline
* - Tracked with a warning message for user visibility
*
* Local images (file paths without http/https) are left unchanged for normal
* processing. This allows the export pipeline to handle them separately from
* remote resources that need downloading.
*
* The marker format is: `IMAGE_EMBED_MARKER:{url}:{baseName}:{alt}`
* This allows the export pipeline to:
* - Download the remote image
* - Replace the marker with the local path
* - Preserve the alt text for accessibility
*
* @param content - Markdown content to process
* @param result - Processing result to update with remote image metadata
* @returns Content with remote images replaced by markers
* @private
*
* @example
* ```typescript
* // Remote image detected and queued
* const markdown = '![Photo](https://example.com/image.png)';
* const result = { metadata: {}, warnings: [], errors: [] };
* const processed = this.processStandardMarkdownImages(markdown, result);
*
* // Content has marker: 'IMAGE_EMBED_MARKER:https://...:image:Photo'
* // result.metadata.imageEmbeds has entry for download
* // result.warnings includes "Remote URL image queued for download"
* ```
*
* @example
* ```typescript
* // Local image left unchanged
* const markdown = '![Local](local-image.png)';
* const result = { metadata: {}, warnings: [], errors: [] };
* const processed = this.processStandardMarkdownImages(markdown, result);
*
* // Content unchanged: '![Local](local-image.png)'
* // No entries added to metadata or warnings
* ```
*/
private processStandardMarkdownImages(content: string, result: PreprocessingResult): string {
// Pattern to match standard markdown images: ![alt](url)
@@ -219,7 +476,66 @@ export class MarkdownPreprocessor {
}
/**
* Update configuration
* Updates the preprocessor configuration dynamically.
*
* This method allows modifying preprocessor settings after initialization without
* creating a new instance. It supports partial updates - only the provided fields
* are changed, leaving others intact. The method also propagates relevant changes
* to dependent processors (WikilinkProcessor, EmbedProcessor) to maintain consistency.
*
* When updating wikilink configuration or base URL, the changes cascade to:
* 1. WikilinkProcessor - Updated with new wikilink settings and base URL
* 2. EmbedProcessor - Receives updated WikilinkProcessor reference
*
* This cascading update ensures that all processors use consistent configuration
* throughout the preprocessing pipeline.
*
* Configuration updates are useful for:
* - Changing export settings between different notes
* - Applying user preference changes without reinitialization
* - Switching between different export contexts (web vs. local)
* - Testing different configuration combinations
*
* @param config - Partial configuration update (only specified fields are changed)
*
* @example
* ```typescript
* // Update base URL for web export
* preprocessor.updateConfig({
* options: { baseUrl: 'https://example.com/notes' }
* });
*
* // Process note with web-friendly links
* const result = await preprocessor.process(markdown);
* // Links will use the new base URL
* ```
*
* @example
* ```typescript
* // Change wikilink format for different export
* preprocessor.updateConfig({
* wikilinkConfig: {
* format: 'html',
* extension: '.html'
* }
* });
*
* // Process with HTML-style links
* const result = await preprocessor.process(markdown);
* // [[note]] becomes [note](note.html)
* ```
*
* @example
* ```typescript
* // Update multiple settings at once
* preprocessor.updateConfig({
* vaultPath: '/new/vault/path',
* options: {
* preserveFrontmatter: false,
* printFrontmatter: true
* }
* });
* ```
*/
public updateConfig(config: Partial<MarkdownPreprocessorConfig>): void {
if (config.vaultPath) {
@@ -247,7 +563,48 @@ export class MarkdownPreprocessor {
}
/**
* Get current configuration
* Retrieves the current preprocessor configuration.
*
* This method returns a snapshot of the preprocessor's current settings,
* including vault path, processing options, and wikilink configuration.
* The returned object is a plain data object that can be:
* - Inspected for debugging
* - Serialized for logging or caching
* - Modified and passed to updateConfig() for changes
* - Used to create a new preprocessor with the same settings
*
* Note: The returned configuration does not include the noteTitle field,
* as this is typically set per-export rather than persisted in the
* preprocessor configuration.
*
* @returns Current preprocessor configuration object
*
* @example
* ```typescript
* // Inspect current settings
* const config = preprocessor.getConfig();
* console.log('Vault path:', config.vaultPath);
* console.log('Preserve frontmatter:', config.options.preserveFrontmatter);
* console.log('Wikilink format:', config.wikilinkConfig.format);
* ```
*
* @example
* ```typescript
* // Clone preprocessor with same configuration
* const currentConfig = preprocessor.getConfig();
* const clonedPreprocessor = new MarkdownPreprocessor({
* ...currentConfig,
* noteTitle: 'Different Title'
* });
* ```
*
* @example
* ```typescript
* // Modify and reapply configuration
* const config = preprocessor.getConfig();
* config.options.baseUrl = 'https://new-url.com';
* preprocessor.updateConfig(config);
* ```
*/
public getConfig(): MarkdownPreprocessorConfig {
return {
@@ -258,12 +615,91 @@ export class MarkdownPreprocessor {
}
}
// Default configurations
/**
* Default preprocessor options for standard Markdown processing.
*
* These defaults are designed to work well for most Obsidian-to-Pandoc conversions:
* - **preserveFrontmatter: true** - Keeps YAML frontmatter in the output, allowing
* Pandoc and Typst to access metadata (title, author, date, custom variables).
* Set to false if you want to strip frontmatter entirely.
* - **baseUrl: ''** - Empty base URL means links remain relative to the vault.
* Set this when exporting to web to make links absolute (e.g., 'https://example.com/notes').
*
* These values are used when creating a new MarkdownPreprocessor without explicit
* options. They can be overridden via the MarkdownPreprocessorConfig constructor
* parameter or modified later via updateConfig().
*
* @example
* ```typescript
* // Use defaults implicitly
* const preprocessor = new MarkdownPreprocessor({
* vaultPath: '/vault',
* options: DEFAULT_PREPROCESSOR_OPTIONS, // Explicit use of defaults
* wikilinkConfig: DEFAULT_WIKILINK_CONFIG
* });
* ```
*
* @example
* ```typescript
* // Override defaults for web export
* const webOptions = {
* ...DEFAULT_PREPROCESSOR_OPTIONS,
* baseUrl: 'https://blog.example.com/notes'
* };
* ```
*/
export const DEFAULT_PREPROCESSOR_OPTIONS: PreprocessorOptions = {
preserveFrontmatter: true,
baseUrl: ''
};
/**
* Default wikilink conversion configuration for Markdown output.
*
* These defaults convert Obsidian wikilinks to standard Markdown links:
* - **format: 'md'** - Convert to Markdown format `[text](link.md)`
* Other possible values: 'html' for `[text](link.html)`, 'wiki' to preserve `[[link]]`
* - **extension: '.md'** - Add .md extension to converted links
* Ensures [[note]] becomes [note](note.md) for proper cross-reference handling
*
* This configuration is passed to WikilinkProcessor during preprocessing and
* ensures consistent link handling throughout the conversion pipeline.
*
* These values work well for Pandoc conversion, as Pandoc expects standard
* Markdown links with file extensions. For web publishing, you might want to
* use format: 'html' and extension: '.html' instead.
*
* @example
* ```typescript
* // Use defaults for standard Markdown output
* const preprocessor = new MarkdownPreprocessor({
* vaultPath: '/vault',
* options: DEFAULT_PREPROCESSOR_OPTIONS,
* wikilinkConfig: DEFAULT_WIKILINK_CONFIG // [[note]] → [note](note.md)
* });
* ```
*
* @example
* ```typescript
* // Override for HTML export
* const htmlWikilinkConfig = {
* ...DEFAULT_WIKILINK_CONFIG,
* format: 'html',
* extension: '.html'
* };
* // [[note]] → [note](note.html)
* ```
*
* @example
* ```typescript
* // Preserve wikilinks (no conversion)
* const preserveWikilinks = {
* format: 'wiki',
* extension: ''
* };
* // [[note]] → [[note]] (unchanged)
* ```
*/
export const DEFAULT_WIKILINK_CONFIG: WikilinkConfig = {
format: 'md',
extension: '.md'
+214 -18
View File
@@ -1,6 +1,17 @@
/**
* Pandoc to Typst PDF Converter
* Handles the conversion of Markdown to PDF using Pandoc with Typst engine
* Pandoc to Typst PDF Converter.
*
* This module provides the main conversion engine for transforming Markdown files
* to PDF documents using the Pandoc → Typst → PDF pipeline. It coordinates all
* aspects of the conversion process including:
* - Temporary file and directory management
* - Command building and execution
* - Progress reporting
* - Resource cleanup
* - Error handling
*
* The converter supports both file-based and content-based conversions, automatically
* managing temporary directories and cleanup on process termination.
*/
import { PandocOptions, TypstSettings, ConversionResult, ProgressCallback } from './converterTypes';
@@ -11,6 +22,52 @@ import { PathUtils } from '../core/PathUtils';
import { PandocCommandBuilder } from './pandoc/PandocCommandBuilder';
import { PandocExecutor } from './pandoc/PandocExecutor';
/**
* Main converter class for Markdown → Typst → PDF conversion.
*
* This class orchestrates the PDF export process by delegating to specialized
* components (PandocCommandBuilder, PandocExecutor) while managing temporary
* resources and providing progress feedback.
*
* Key features:
* - File and content-based conversion support
* - Automatic temporary directory management
* - Process cleanup on termination (exit, SIGINT, SIGTERM, exceptions)
* - Progress callback support for UI updates
* - Configurable Pandoc and Typst settings
*
* Lifecycle:
* 1. Constructor initializes command builder and executor
* 2. Conversion methods create temp directories and build commands
* 3. Executor runs Pandoc with Typst engine
* 4. Cleanup automatically removes temporary files
* 5. dispose() for manual cleanup when done
*
* @example
* ```typescript
* const converter = new PandocTypstConverter(
* plugin,
* { template: 'modern', variables: { ... } },
* { ppi: 144 }
* );
*
* try {
* const result = await converter.convertToPDF(
* 'input.md',
* 'output.pdf',
* (message, progress) => console.log(`${progress}%: ${message}`)
* );
*
* if (result.success) {
* console.log('PDF created:', result.outputPath);
* } else {
* console.error('Conversion failed:', result.error);
* }
* } finally {
* await converter.dispose();
* }
* ```
*/
export class PandocTypstConverter {
private tempDir: string | null = null;
private cleanupHandlers: (() => void)[] = [];
@@ -19,10 +76,34 @@ export class PandocTypstConverter {
private pandocExecutor: PandocExecutor;
/**
* Create a new PandocTypstConverter instance
* @param plugin The main plugin instance for accessing settings
* @param pandocOptions Configuration options for Pandoc
* @param typstSettings Settings specific to Typst engine
* Creates a new PandocTypstConverter instance with configuration.
*
* Initializes the converter with the plugin instance and configuration options
* for both Pandoc and Typst. Sets up cleanup handlers to ensure temporary
* files are removed on process termination.
*
* @param plugin - The main plugin instance for accessing app and settings
* @param pandocOptions - Configuration options for Pandoc conversion (template, variables, etc.)
* @param typstSettings - Settings specific to Typst rendering engine (ppi, font-paths, etc.)
*
* @example
* ```typescript
* const converter = new PandocTypstConverter(
* this.plugin,
* {
* template: 'modern',
* variables: {
* pageSize: 'a4',
* bodyFont: 'Georgia'
* },
* metadata: { title: 'My Document' }
* },
* {
* ppi: 144,
* fontPaths: ['/usr/share/fonts']
* }
* );
* ```
*/
constructor(
plugin: obsidianTypstPDFExport,
@@ -37,15 +118,46 @@ export class PandocTypstConverter {
}
/**
* Convert a markdown file to PDF using Pandoc with Typst engine
* @param inputPath Path to the input markdown file
* @param outputPath Path where the PDF should be saved
* @param progressCallback Optional callback for progress updates
* @returns Promise resolving to conversion result
* Converts a Markdown file to PDF using the Pandoc → Typst → PDF pipeline.
*
* This is the primary conversion method that handles the complete export process:
* 1. Creates temporary directory for intermediate files
* 2. Builds Pandoc command with configured options
* 3. Executes Pandoc with Typst engine
* 4. Reports progress via optional callback
* 5. Returns result with success status and output path
*
* The method automatically manages temporary files and provides progress updates
* at key stages. If conversion fails, returns error information in the result
* object rather than throwing.
*
* @param inputPath - Absolute path to the input Markdown file
* @param outputPath - Absolute path where the PDF should be saved
* @param progressCallback - Optional callback for progress updates (message, percentage)
* @returns Promise resolving to conversion result with success flag and optional error
*
* @example
* ```typescript
* const result = await converter.convertToPDF(
* '/path/to/note.md',
* '/path/to/output.pdf',
* (message, progress) => {
* console.log(`${progress}%: ${message}`);
* // Update UI progress bar
* }
* );
*
* if (result.success) {
* console.log('PDF created at:', result.outputPath);
* } else {
* console.error('Conversion failed:', result.error);
* console.log('Pandoc output:', result.stdout);
* }
* ```
*/
async convertToPDF(
inputPath: string,
outputPath: string,
inputPath: string,
outputPath: string,
progressCallback?: ProgressCallback
): Promise<ConversionResult> {
try {
@@ -89,7 +201,43 @@ export class PandocTypstConverter {
}
/**
* Convert markdown content to PDF
* Converts Markdown content (string) to PDF without requiring a file.
*
* This is a convenience method for converting Markdown content directly from
* memory without needing an existing file. It creates a temporary file,
* delegates to convertToPDF, then cleans up the temporary file.
*
* Useful for:
* - Converting dynamically generated content
* - Processing in-memory Markdown transformations
* - Testing conversion without file system operations
*
* Note: This method merges the provided options with existing pandocOptions.
*
* @param content - Markdown content to convert
* @param outputPath - Absolute path where the PDF should be saved
* @param options - Additional Pandoc options to merge with existing settings
* @param progressCallback - Optional callback for progress updates (message, percentage)
* @returns Promise resolving to conversion result with success flag and optional error
*
* @example
* ```typescript
* const markdown = `
* # My Document
* This is **dynamically generated** content.
* `;
*
* const result = await converter.convertMarkdownToPDF(
* markdown,
* '/path/to/output.pdf',
* { variables: { title: 'Generated Doc' } },
* (msg, pct) => updateProgress(pct)
* );
*
* if (result.success) {
* console.log('Created PDF from content');
* }
* ```
*/
async convertMarkdownToPDF(
content: string,
@@ -131,7 +279,17 @@ export class PandocTypstConverter {
}
/**
* Set up cleanup handlers for temporary files
* Sets up automatic cleanup handlers for process termination events.
*
* Registers the cleanup method to run on various process termination events
* to ensure temporary files are removed even if the process exits unexpectedly.
* Handlers are registered for:
* - Normal exit
* - SIGINT (Ctrl+C)
* - SIGTERM (kill command)
* - Uncaught exceptions
*
* @private
*/
private setupCleanup(): void {
const cleanup = () => {
@@ -146,7 +304,16 @@ export class PandocTypstConverter {
/**
* Clean up temporary files and directories
* Cleans up temporary files and directories.
*
* This method executes all registered cleanup handlers and removes the temporary
* directory created by the converter. Cleanup failures are logged but don't throw
* to avoid interfering with normal operation or other cleanup operations.
*
* Called automatically on process termination or manually via dispose().
*
* @private
* @returns Promise that resolves when cleanup is complete
*/
private async cleanup(): Promise<void> {
try {
@@ -171,7 +338,19 @@ export class PandocTypstConverter {
}
/**
* Ensure temporary directory exists
* Ensures a temporary directory exists for intermediate conversion files.
*
* Creates a temporary directory on first call and reuses it for subsequent calls.
* The directory is created inside the plugin folder if vaultBasePath is available,
* otherwise falls back to vault-level temp directories.
*
* The temporary directory is used for:
* - Temporary Markdown files
* - Intermediate Typst files (if debug mode enabled)
* - Processed resource files
*
* @private
* @returns Promise resolving to the temporary directory path
*/
private async ensureTempDirectory(): Promise<string> {
if (!this.tempDir) {
@@ -194,7 +373,24 @@ export class PandocTypstConverter {
/**
* Dispose of the converter and clean up resources
* Disposes of the converter and cleans up all resources.
*
* This method should be called when done with the converter to ensure temporary
* files are removed. While cleanup happens automatically on process termination,
* calling dispose explicitly allows for immediate cleanup and is recommended
* when the converter is no longer needed.
*
* @returns Promise that resolves when cleanup is complete
*
* @example
* ```typescript
* const converter = new PandocTypstConverter(plugin, options);
* try {
* await converter.convertToPDF(input, output);
* } finally {
* await converter.dispose(); // Cleanup even if conversion fails
* }
* ```
*/
async dispose(): Promise<void> {
await this.cleanup();
+439 -8
View File
@@ -1,6 +1,39 @@
/**
* PDF to Image Converter using pdf-to-img
* Converts PDF files to PNG images for preview in Typst exports
* PDF to Image conversion for embedded PDF files in Obsidian notes.
*
* This module provides a robust conversion system for transforming PDF files into
* images suitable for embedding in Typst-generated PDFs. Since Typst has limited
* native PDF embedding capabilities, this converter extracts the first page of
* embedded PDFs and converts them to high-quality PNG or JPEG images.
*
* Key features:
* - Singleton pattern for resource efficiency and state management
* - First-page-only conversion for preview purposes
* - Configurable image quality and dimensions
* - Multi-strategy PDF processing (pdf-to-img library with ImageMagick fallback)
* - Automatic format conversion and optimization
* - File discovery for handling various filename patterns
* - Comprehensive error handling and validation
*
* Conversion Pipeline:
* 1. PDF validation (file exists, valid format, readable)
* 2. Output directory preparation
* 3. CLI execution via pdf-to-img or ImageMagick
* 4. Generated file discovery (handles naming variations)
* 5. Image optimization (format conversion, dimension detection)
* 6. Result packaging with metadata
*
* The converter delegates to specialized utilities:
* - PdfProcessor: PDF validation and metadata extraction
* - PdfCliExecutor: Command-line tool execution
* - FileDiscovery: Generated file location
* - ImageOptimizer: Format conversion and dimension detection
*
* Architecture Notes:
* - Singleton pattern ensures consistent state across exports
* - Plugin reference enables vault file operations
* - Modular design allows easy extension for multi-page conversion
* - Error results preserve context for debugging
*/
import * as path from 'path';
@@ -11,6 +44,51 @@ import { FileDiscovery } from './pdf/FileDiscovery';
import type { obsidianTypstPDFExport } from '../../main';
import { PathUtils } from '../core/PathUtils';
/**
* Configuration options for PDF to image conversion.
*
* These options control the quality, dimensions, and format of generated images.
* All options are optional with sensible defaults optimized for embedding in PDFs.
*
* @property scale - Rendering scale factor for image quality (default: 2.0)
* Higher values produce sharper images but larger file sizes. 2.0 is optimal
* for HiDPI displays and print-quality PDFs. Use 1.0 for web-optimized exports.
* @property maxWidth - Maximum output image width in pixels (default: 800)
* Images wider than this are scaled down proportionally. Prevents excessive
* file sizes while maintaining readability in typical PDF layouts.
* @property maxHeight - Maximum output image height in pixels (default: 600)
* Images taller than this are scaled down proportionally. Balances quality
* with file size for typical document heights.
* @property format - Output image format (default: 'png')
* - 'png': Lossless compression, best for diagrams and text
* - 'jpeg': Lossy compression, smaller files for photos
* @property quality - JPEG compression quality 1-100 (default: 90)
* Only applies when format is 'jpeg'. Higher values preserve more detail
* but increase file size. 90 provides excellent quality with good compression.
*
* @example
* ```typescript
* // High-quality conversion for print
* const printOptions: PdfConversionOptions = {
* scale: 3.0,
* maxWidth: 1200,
* maxHeight: 900,
* format: 'png'
* };
* ```
*
* @example
* ```typescript
* // Web-optimized conversion
* const webOptions: PdfConversionOptions = {
* scale: 1.0,
* maxWidth: 600,
* maxHeight: 450,
* format: 'jpeg',
* quality: 85
* };
* ```
*/
export interface PdfConversionOptions {
/** Quality/scale factor for the rendered image (default: 2.0 for HiDPI) */
scale?: number;
@@ -24,6 +102,58 @@ export interface PdfConversionOptions {
quality?: number;
}
/**
* Result of PDF to image conversion operation.
*
* This interface provides comprehensive information about the conversion outcome,
* including file paths, dimensions, and success status. The result always includes
* a success flag - when false, the error field provides diagnostic information.
*
* @property imagePath - Absolute path to the generated image file
* Empty string if conversion failed. Use this path to embed the image in Typst.
* @property originalDimensions - Original PDF page dimensions in pixels
* Width and height of the PDF page before conversion. Set to {0, 0} on failure.
* Note: Currently estimates based on converted image due to library limitations.
* @property imageDimensions - Generated image dimensions in pixels
* Actual width and height of the output image file. May differ from original
* due to scaling, format conversion, or optimization. Set to {0, 0} on failure.
* @property success - Conversion success flag
* True if image was generated successfully, false if any error occurred.
* Always check this before using imagePath or dimension data.
* @property error - Error message if conversion failed
* Present only when success is false. Contains diagnostic information about
* what went wrong (file not found, invalid PDF, conversion failure, etc.).
*
* @example
* ```typescript
* const result = await converter.convertFirstPageToImage(pdfPath, outputDir);
*
* if (result.success) {
* console.log('Image created:', result.imagePath);
* console.log('Dimensions:', result.imageDimensions);
* // Use result.imagePath in Typst template
* } else {
* console.error('Conversion failed:', result.error);
* // Fallback to placeholder or skip embed
* }
* ```
*
* @example
* ```typescript
* // Handle dimension information
* const result = await converter.convertFirstPageToImage(pdfPath, outputDir);
*
* if (result.success) {
* const aspectRatio = result.imageDimensions.width / result.imageDimensions.height;
* console.log('Aspect ratio:', aspectRatio.toFixed(2));
*
* // Adjust Typst layout based on dimensions
* if (aspectRatio > 1.5) {
* // Wide image - use landscape layout
* }
* }
* ```
*/
export interface PdfConversionResult {
/** Path to the generated image file */
imagePath: string;
@@ -43,15 +173,124 @@ export interface PdfConversionResult {
error?: string;
}
/**
* Singleton converter for transforming PDF files into embeddable images.
*
* This class provides the primary interface for PDF to image conversion in the
* export pipeline. It implements the singleton pattern to ensure consistent state
* and resource management across multiple conversion operations.
*
* Key Responsibilities:
* - First-page extraction from PDF files
* - High-quality image generation with configurable options
* - PDF validation and metadata extraction
* - Integration with Obsidian vault file system
* - Error handling and result reporting
*
* Architecture:
* The converter delegates to specialized utility classes:
* - **PdfProcessor**: PDF file validation and metadata
* - **PdfCliExecutor**: Command-line tool execution (pdf-to-img, ImageMagick)
* - **FileDiscovery**: Generated file location and verification
* - **ImageOptimizer**: Format conversion and dimension detection
* - **PathUtils**: Obsidian vault file operations
*
* Singleton Pattern:
* Use `getInstance()` to obtain the converter instance. The singleton ensures:
* - Single plugin reference across all conversions
* - Consistent configuration and state
* - Efficient resource usage
* - Simplified dependency injection
*
* Usage Flow:
* 1. Get instance with plugin reference: `PdfToImageConverter.getInstance(plugin)`
* 2. Convert PDF: `await converter.convertFirstPageToImage(path, outDir, options)`
* 3. Check result.success and use result.imagePath in Typst template
* 4. Handle errors via result.error message
*
* @example
* ```typescript
* // Initialize converter with plugin reference
* const converter = PdfToImageConverter.getInstance(this.plugin);
*
* // Convert PDF with default options
* const result = await converter.convertFirstPageToImage(
* '/vault/attachments/document.pdf',
* '/vault/.obsidian/plugins/typst-pdf-export/temp-images'
* );
*
* if (result.success) {
* console.log('Converted to:', result.imagePath);
* // Embed result.imagePath in Typst template
* } else {
* console.error('Conversion failed:', result.error);
* }
* ```
*
* @example
* ```typescript
* // High-quality conversion with custom options
* const converter = PdfToImageConverter.getInstance(this.plugin);
*
* const result = await converter.convertFirstPageToImage(
* pdfPath,
* outputDir,
* {
* scale: 3.0, // 3x rendering for print quality
* maxWidth: 1200, // Larger dimensions
* format: 'png' // Lossless format
* }
* );
* ```
*/
export class PdfToImageConverter {
private static instance: PdfToImageConverter;
private plugin: obsidianTypstPDFExport | undefined;
/**
* Private constructor for singleton pattern.
*
* Use getInstance() to obtain the converter instance instead of constructing directly.
*
* @param plugin - Optional plugin reference for vault operations
* @private
*/
private constructor(plugin?: obsidianTypstPDFExport) {
this.plugin = plugin;
}
/**
* Gets or creates the singleton PdfToImageConverter instance.
*
* This method ensures only one converter instance exists throughout the application
* lifecycle. If a plugin reference is provided on subsequent calls, it updates the
* stored reference to ensure vault operations work correctly.
*
* Thread Safety:
* This implementation is safe for single-threaded JavaScript execution.
* The singleton is created on first access and reused thereafter.
*
* @param plugin - Optional plugin reference (updates stored reference if provided)
* @returns The singleton PdfToImageConverter instance
*
* @example
* ```typescript
* // First call creates instance
* const converter1 = PdfToImageConverter.getInstance(this.plugin);
*
* // Subsequent calls return same instance
* const converter2 = PdfToImageConverter.getInstance();
* console.log(converter1 === converter2); // true
* ```
*
* @example
* ```typescript
* // Update plugin reference after initialization
* const converter = PdfToImageConverter.getInstance(); // No plugin initially
* // ... later ...
* PdfToImageConverter.getInstance(this.plugin); // Updates plugin reference
* ```
*/
public static getInstance(plugin?: obsidianTypstPDFExport): PdfToImageConverter {
if (!PdfToImageConverter.instance) {
PdfToImageConverter.instance = new PdfToImageConverter(plugin);
@@ -63,11 +302,93 @@ export class PdfToImageConverter {
}
/**
* Convert the first page of a PDF to an image
* Converts the first page of a PDF file to a high-quality image.
*
* This is the primary conversion method that orchestrates the complete PDF-to-image
* pipeline. It handles validation, conversion, optimization, and error reporting in
* a single operation suitable for embedding in Typst exports.
*
* Conversion Pipeline:
* 1. **Validation**: Verify PDF file exists and is valid
* 2. **Directory Setup**: Ensure output directory exists (via vault adapter)
* 3. **CLI Execution**: Run pdf-to-img or ImageMagick to convert first page
* 4. **File Discovery**: Locate generated image (handles various naming patterns)
* 5. **Optimization**: Convert format and detect dimensions
* 6. **Result Packaging**: Return success with image path and metadata
*
* Error Handling:
* Each stage reports specific errors via PdfConversionResult. Common failures:
* - File not found or inaccessible
* - Invalid or corrupted PDF format
* - CLI tool execution failure
* - Output file not found after conversion
* - Image optimization failure
*
* All errors are captured and returned in result.error, never thrown as exceptions.
*
* Performance:
* - First-page-only conversion is fast (~1-2 seconds typical)
* - Uses CLI tools for native-quality rendering
* - Temporary files cleaned up automatically by caller
* - Suitable for batch processing multiple PDFs
*
* @param pdfPath - Absolute path to PDF file to convert
* @param outputDir - Absolute path to output directory for generated image
* @param options - Optional conversion configuration (defaults to HiDPI quality)
* @returns Promise resolving to conversion result with success status and metadata
*
* @example
* ```typescript
* // Basic conversion with defaults
* const converter = PdfToImageConverter.getInstance(this.plugin);
* const result = await converter.convertFirstPageToImage(
* '/vault/attachments/report.pdf',
* '/vault/.obsidian/plugins/typst-pdf-export/temp-images'
* );
*
* if (result.success) {
* console.log('Image:', result.imagePath);
* console.log('Size:', result.imageDimensions.width, 'x', result.imageDimensions.height);
* // Use result.imagePath in Typst: #image("path")
* } else {
* new Notice(`PDF conversion failed: ${result.error}`);
* }
* ```
*
* @example
* ```typescript
* // High-quality conversion for print
* const result = await converter.convertFirstPageToImage(
* pdfPath,
* outputDir,
* {
* scale: 3.0,
* maxWidth: 1600,
* maxHeight: 1200,
* format: 'png'
* }
* );
* ```
*
* @example
* ```typescript
* // Batch convert multiple PDFs
* const converter = PdfToImageConverter.getInstance(this.plugin);
* const pdfPaths = ['/vault/doc1.pdf', '/vault/doc2.pdf', '/vault/doc3.pdf'];
*
* for (const pdfPath of pdfPaths) {
* const result = await converter.convertFirstPageToImage(pdfPath, outputDir);
* if (result.success) {
* console.log(`✓ ${path.basename(pdfPath)}`);
* } else {
* console.error(`✗ ${path.basename(pdfPath)}: ${result.error}`);
* }
* }
* ```
*/
public async convertFirstPageToImage(
pdfPath: string,
outputDir: string,
pdfPath: string,
outputDir: string,
options: PdfConversionOptions = {}
): Promise<PdfConversionResult> {
try {
@@ -180,14 +501,124 @@ export class PdfToImageConverter {
}
/**
* Check if a file is a valid PDF
* Validates whether a file is a readable PDF document.
*
* This utility method provides quick PDF validation before attempting conversion.
* It checks both file existence and PDF format validity by delegating to PdfProcessor.
*
* Validation includes:
* - File exists and is accessible
* - File has PDF magic bytes (header signature)
* - File is not corrupted or truncated
*
* Use this for pre-flight checks before expensive conversion operations or to
* filter PDF files from mixed file lists.
*
* @param filePath - Absolute path to file to validate
* @returns Promise resolving to true if file is valid PDF, false otherwise
*
* @example
* ```typescript
* const converter = PdfToImageConverter.getInstance(this.plugin);
*
* // Validate before conversion
* if (await converter.isValidPdf(pdfPath)) {
* const result = await converter.convertFirstPageToImage(pdfPath, outputDir);
* // Process result...
* } else {
* new Notice('Not a valid PDF file');
* }
* ```
*
* @example
* ```typescript
* // Filter PDF files from attachments
* const attachments = app.vault.getFiles();
* const converter = PdfToImageConverter.getInstance(this.plugin);
*
* const validPdfs = [];
* for (const file of attachments) {
* if (file.extension === 'pdf' && await converter.isValidPdf(file.path)) {
* validPdfs.push(file);
* }
* }
* console.log(`Found ${validPdfs.length} valid PDFs`);
* ```
*/
public async isValidPdf(filePath: string): Promise<boolean> {
return await PdfProcessor.isValidPdf(filePath);
}
/**
* Get PDF metadata (page count, dimensions, etc.)
* Retrieves metadata about a PDF file without converting it.
*
* This method extracts essential PDF information including page count and page
* dimensions. It's useful for:
* - Determining if multi-page conversion is needed
* - Checking PDF dimensions before conversion
* - Pre-flight validation with detailed error messages
* - UI display of PDF properties
*
* The method delegates to PdfProcessor for actual metadata extraction. On success,
* returns page count and first page dimensions. On failure, returns error details.
*
* Note: Dimensions are for the first page only. Multi-page PDFs may have varying
* page sizes, but this implementation focuses on first-page conversion.
*
* @param filePath - Absolute path to PDF file
* @returns Promise resolving to metadata object with page count, dimensions, and success status
*
* @example
* ```typescript
* const converter = PdfToImageConverter.getInstance(this.plugin);
* const info = await converter.getPdfInfo(pdfPath);
*
* if (info.success) {
* console.log(`Pages: ${info.pageCount}`);
* console.log(`Size: ${info.dimensions.width}x${info.dimensions.height}px`);
*
* if (info.pageCount > 1) {
* new Notice(`PDF has ${info.pageCount} pages - only first will be converted`);
* }
* } else {
* console.error('Failed to read PDF info:', info.error);
* }
* ```
*
* @example
* ```typescript
* // Adjust conversion options based on PDF dimensions
* const info = await converter.getPdfInfo(pdfPath);
*
* if (info.success) {
* const isLandscape = info.dimensions.width > info.dimensions.height;
*
* const options: PdfConversionOptions = {
* maxWidth: isLandscape ? 1200 : 800,
* maxHeight: isLandscape ? 800 : 1200
* };
*
* const result = await converter.convertFirstPageToImage(pdfPath, outputDir, options);
* }
* ```
*
* @example
* ```typescript
* // Check PDF before showing conversion dialog
* const info = await converter.getPdfInfo(pdfPath);
*
* if (!info.success) {
* new Notice(`Cannot process PDF: ${info.error}`);
* return;
* }
*
* // Show dialog with PDF details
* new PDFConversionModal(
* this.app,
* pdfPath,
* `${info.pageCount} pages, ${info.dimensions.width}x${info.dimensions.height}px`
* ).open();
* ```
*/
public async getPdfInfo(filePath: string): Promise<{
pageCount: number;
+244 -9
View File
@@ -1,6 +1,50 @@
/**
* Pandoc Command Builder
* Handles construction of Pandoc command-line arguments for Typst PDF conversion
* Command-line argument builder for Pandoc-to-Typst PDF conversion.
*
* This module constructs complete Pandoc command-line arguments for converting
* preprocessed Markdown to Typst format, which is then compiled to PDF by the
* Typst engine. It orchestrates several key aspects of the conversion:
* - Input/output path specification
* - Typst PDF engine configuration
* - Template loading and variable passing
* - Resource path resolution for embedded media
* - Diagnostic and error reporting options
*
* Key Features:
* - Modular argument construction via specialized methods
* - Template system with universal wrapper for dynamic template selection
* - Comprehensive variable mapping from export config to Typst variables
* - Smart resource path resolution for Obsidian attachments
* - Enhanced diagnostics for debugging conversion failures
* - Safe path handling with automatic quoting via spawn
*
* Architecture:
* The builder delegates to specialized components:
* - **TypstVariableMapper**: Maps export config to Typst variables
* - **ResourcePathResolver**: Finds attachment directories in vault
* - **PathResolver**: Resolves executable paths with fallback logic
* - **PathUtils**: Obsidian vault file system operations
*
* Command Structure:
* ```bash
* pandoc input.md \
* -o output.pdf \
* --from markdown-smart \
* --pdf-engine=typst \
* --standalone \
* --no-citeproc \
* --embed-resources \
* --resource-path /vault/attachments \
* --template universal-wrapper.typ \
* -V template_path=default.typ \
* -V page_width=210mm \
* ... (more variables)
* --pdf-engine-opt --diagnostic-format=short
* ```
*
* The universal wrapper template receives the actual template path as a variable,
* allowing dynamic template selection without requiring separate wrapper files
* for each template.
*/
import * as path from 'path';
@@ -11,12 +55,58 @@ import { PathResolver } from '../../plugin/PathResolver';
import type { obsidianTypstPDFExport } from '../../../main';
import { PathUtils } from '../../core/PathUtils';
/**
* Builder for Pandoc command-line arguments in the Markdown → Typst → PDF pipeline.
*
* This class encapsulates the complex logic for constructing Pandoc command arguments
* that correctly configure Typst PDF generation. It manages several interdependent
* concerns including template loading, variable mapping, resource path resolution,
* and diagnostic configuration.
*
* Design Philosophy:
* - Single responsibility: Only builds command arguments, doesn't execute
* - Modular construction: Each argument category handled by dedicated method
* - Dependency injection: Receives plugin reference for configuration access
* - Async-safe: Handles file system checks without blocking
*
* The builder pattern allows testing argument construction independently from
* command execution, and makes it easy to modify argument logic without touching
* the execution layer.
*
* @example
* ```typescript
* const builder = new PandocCommandBuilder(this.plugin);
*
* const args = await builder.buildPandocArgs(
* '/vault/note.md',
* '/vault/exports/note.pdf',
* {
* template: 'default',
* vaultBasePath: '/vault',
* pluginDir: '/vault/.obsidian/plugins/typst-pdf-export',
* typstPath: 'typst',
* exportConfig: { pageSize: 'a4', orientation: 'portrait' }
* }
* );
*
* // Execute with spawn
* spawn('pandoc', args);
* ```
*/
export class PandocCommandBuilder {
private plugin: obsidianTypstPDFExport;
private variableMapper: TypstVariableMapper;
private resourcePathResolver: ResourcePathResolver;
private pathResolver: PathResolver;
/**
* Creates a new PandocCommandBuilder.
*
* Initializes all dependent components (variable mapper, resource path resolver,
* path resolver) that the builder needs to construct complete command arguments.
*
* @param plugin - Plugin instance for accessing configuration and vault operations
*/
constructor(plugin: obsidianTypstPDFExport) {
this.plugin = plugin;
this.variableMapper = new TypstVariableMapper(plugin);
@@ -25,7 +115,72 @@ export class PandocCommandBuilder {
}
/**
* Build pandoc command-line arguments
* Builds complete Pandoc command-line arguments for Typst PDF generation.
*
* This is the primary interface method that orchestrates all argument construction.
* It delegates to specialized private methods for each category of arguments,
* ensuring proper ordering and completeness.
*
* Argument Order (important for Pandoc):
* 1. Input file path
* 2. Output file specification (-o)
* 3. Input format (--from markdown-smart)
* 4. PDF engine configuration (--pdf-engine=typst)
* 5. Standalone mode (--standalone)
* 6. Citation processing (--no-citeproc)
* 7. Resource embedding (--embed-resources)
* 8. Resource paths (--resource-path, multiple)
* 9. Template configuration (--template, -V template_path)
* 10. Typst variables (-V key=value, multiple)
* 11. Engine options (--pdf-engine-opt, multiple)
* 12. Diagnostics (--pdf-engine-opt --diagnostic-format=short)
*
* Side Effects:
* - Changes process.cwd() if vaultBasePath is provided
* - Reads file system to verify template existence
* - May throw Error if universal wrapper template not found
*
* @param inputPath - Absolute path to preprocessed Markdown input file
* @param outputPath - Absolute path for generated PDF output file
* @param pandocOptions - Configuration for Pandoc execution and Typst variables
* @returns Promise resolving to array of command-line arguments for Pandoc
*
* @throws {Error} If universal wrapper template not found
*
* @example
* ```typescript
* // Basic usage
* const builder = new PandocCommandBuilder(this.plugin);
* const args = await builder.buildPandocArgs(
* '/vault/preprocessed.md',
* '/vault/output.pdf',
* {
* template: 'modern',
* vaultBasePath: '/vault',
* typstPath: '/usr/local/bin/typst',
* exportConfig: {
* pageSize: 'letter',
* margins: { top: '1in', bottom: '1in' }
* }
* }
* );
* console.log('Pandoc args:', args.join(' '));
* ```
*
* @example
* ```typescript
* // With custom engine options
* const args = await builder.buildPandocArgs(
* inputPath,
* outputPath,
* {
* template: 'article',
* typstSettings: {
* engineOptions: ['--root', '/custom/root', '--font-path', '/fonts']
* }
* }
* );
* ```
*/
async buildPandocArgs(inputPath: string, outputPath: string, pandocOptions: PandocOptions): Promise<string[]> {
const args: string[] = [];
@@ -78,7 +233,20 @@ export class PandocCommandBuilder {
}
/**
* Add resource paths for attachment resolution
* Adds resource paths to command arguments for Obsidian attachment resolution.
*
* This method enables Pandoc to find embedded images, PDFs, and other attachments
* referenced in the markdown content. It uses ResourcePathResolver to discover all
* attachment directories in the vault and adds them via --resource-path flags.
*
* Multiple --resource-path arguments can be provided, and Pandoc searches them in
* order when resolving relative paths in the markdown. This allows attachments to
* be stored in various locations (root-level, nested folders, etc.) and still be
* found during conversion.
*
* @param args - Command arguments array to append to
* @param pandocOptions - Options including vaultBasePath for resource discovery
* @private
*/
private async addResourcePaths(args: string[], pandocOptions: PandocOptions): Promise<void> {
if (!pandocOptions.vaultBasePath) {
@@ -96,7 +264,29 @@ export class PandocCommandBuilder {
/**
* Add template configuration to pandoc arguments
* Adds template configuration using the universal wrapper pattern.
*
* This method implements the plugin's template system using a universal wrapper
* template that dynamically loads the actual template via a Typst import. This
* approach allows template selection at runtime without maintaining separate
* wrapper files for each template.
*
* Template Resolution:
* 1. Locate universal-wrapper.pandoc.typ in plugin templates directory
* 2. Verify wrapper exists (throws if missing)
* 3. Add wrapper as Pandoc --template
* 4. Add templates directory to resource paths (enables Typst imports)
* 5. Pass actual template path as template_path variable
*
* Path Handling:
* - Absolute template paths are made relative to vault root for Typst imports
* - Relative paths are passed through unchanged
* - spawn automatically handles path quoting for spaces
*
* @param args - Command arguments array to append to
* @param pandocOptions - Options including template path and plugin directory
* @throws {Error} If universal wrapper template not found
* @private
*/
private async addTemplateConfiguration(args: string[], pandocOptions: PandocOptions): Promise<void> {
// Use universal wrapper with --template and pass actual template as template_path variable
@@ -130,19 +320,52 @@ export class PandocCommandBuilder {
}
/**
* Add all Typst variables using the variable mapper
* Adds all Typst template variables mapped from export configuration.
*
* This method delegates to TypstVariableMapper to transform the export configuration
* into Typst template variables. These variables control typography, layout, margins,
* and other formatting aspects of the final PDF.
*
* Variable Mapping:
* - ExportConfig fields → Typst variable names (e.g., pageSize → page_size)
* - Plugin settings provide fallback values for missing config fields
* - Values converted to Typst-compatible formats (e.g., "2.5cm" for margins)
* - Variables passed via -V key=value arguments to Pandoc
*
* Example Variables:
* - page_width, page_height: Page dimensions
* - margin_top, margin_bottom, margin_left, margin_right: Margins
* - body_font, heading_font, monospace_font: Typography
* - font_size: Base font size
*
* @param args - Command arguments array to append to
* @param pandocOptions - Options including exportConfig and plugin settings
* @private
*/
private addTypstVariables(args: string[], pandocOptions: PandocOptions): void {
// Map all variables (ExportConfig + plugin settings fallbacks) using the variable mapper
const typstVariables = this.variableMapper.mapAllVariablesToTypst(pandocOptions);
// Convert to pandoc arguments and add to args
const variableArgs = this.variableMapper.convertVariablesToPandocArgs(typstVariables);
args.push(...variableArgs);
}
/**
* Add Typst engine options to pandoc arguments
* Adds custom Typst engine options for advanced configuration.
*
* This method passes additional command-line options directly to the Typst engine
* via Pandoc's --pdf-engine-opt flag. These options can override Typst's default
* behavior for specific use cases.
*
* Common Engine Options:
* - --root /path: Set Typst root directory for imports
* - --font-path /fonts: Add custom font directories
* - --input key=value: Pass additional variables to Typst
*
* @param args - Command arguments array to append to
* @param pandocOptions - Options including typstSettings.engineOptions
* @private
*/
private addTypstEngineOptions(args: string[], pandocOptions: PandocOptions): void {
if (pandocOptions.typstSettings?.engineOptions) {
@@ -153,7 +376,19 @@ export class PandocCommandBuilder {
}
/**
* Add enhanced Typst diagnostics for better error reporting
* Adds Typst diagnostic configuration for enhanced error reporting.
*
* This method enables short-format diagnostics in Typst, which provide cleaner
* and more readable error messages when compilation fails. The short format is
* easier to parse and present to users compared to the verbose default format.
*
* Diagnostic Format:
* - Short: Concise error messages with file:line:column locations
* - Default (verbose): Detailed multi-line error reports with context
*
* @param args - Command arguments array to append to
* @param pandocOptions - Pandoc options (currently unused but kept for consistency)
* @private
*/
private addTypstDiagnostics(args: string[], pandocOptions: PandocOptions): void {
// Add Typst diagnostic options for better error reporting
+258 -17
View File
@@ -4,26 +4,148 @@ import { PathResolver } from '../../plugin/PathResolver';
import type { obsidianTypstPDFExport } from '../../../main';
/**
* Handles pandoc process execution, monitoring, and error parsing.
* Manages the spawning and lifecycle of pandoc processes for document conversion.
* Process executor for Pandoc command-line conversions with progress monitoring.
*
* This class manages the complete lifecycle of Pandoc subprocess execution including:
* - Process spawning with augmented PATH and working directory configuration
* - Real-time stdout/stderr streaming and parsing
* - Progress monitoring and user feedback via callbacks
* - Timeout enforcement to prevent hanging conversions
* - Error extraction and formatting for user-friendly messages
* - Graceful process termination and cleanup
*
* Key Features:
* - **Augmented PATH**: Ensures Pandoc and Typst are found in common locations
* - **Working Directory**: Sets vault root as CWD for proper attachment resolution
* - **Progress Callbacks**: Updates UI during conversion stages
* - **Timeout Protection**: Kills hung processes after configurable duration
* - **Error Parsing**: Extracts meaningful error messages from raw output
* - **Promise-based API**: Clean async interface for callers
*
* Process Lifecycle:
* 1. Resolve Pandoc executable path with PathResolver
* 2. Determine working directory (vault root preferred)
* 3. Augment PATH environment with common binary locations
* 4. Spawn Pandoc process with stdio piping
* 5. Set up timeout handler for hanging processes
* 6. Stream and parse stdout/stderr for progress
* 7. Handle process completion or error
* 8. Clean up timeout handler and resolve promise
*
* The executor is designed to work reliably across different environments (macOS,
* Linux, Windows) by handling path resolution and environment variables carefully.
*
* @example
* ```typescript
* const executor = new PandocExecutor(this.plugin);
*
* const result = await executor.executePandoc(
* ['input.md', '-o', 'output.pdf', '--pdf-engine=typst'],
* {
* pandocPath: 'pandoc',
* vaultBasePath: '/vault',
* timeout: 120000
* },
* (message, progress) => {
* console.log(`${progress}%: ${message}`);
* }
* );
*
* if (result.success) {
* console.log('Conversion succeeded');
* } else {
* console.error('Error:', result.error);
* }
* ```
*/
export class PandocExecutor {
private pathResolver: PathResolver;
/**
* Creates a new PandocExecutor.
*
* @param plugin - Plugin instance for accessing PathResolver configuration
*/
constructor(plugin: obsidianTypstPDFExport) {
this.pathResolver = new PathResolver(plugin);
}
/**
* Execute pandoc process with the given arguments
* @param args Command line arguments for pandoc
* @param pandocOptions Configuration options including paths and timeout
* @param progressCallback Optional callback for progress updates
* @returns Promise resolving to conversion result
* Executes Pandoc process with comprehensive monitoring and error handling.
*
* This is the primary execution method that spawns a Pandoc subprocess, monitors
* its progress, enforces timeouts, and returns a detailed result. The method is
* fully asynchronous and promise-based for clean integration with async workflows.
*
* Process Configuration:
* - **Executable Resolution**: Uses PathResolver to find Pandoc (handles custom paths)
* - **Working Directory**: Sets vault root for relative path resolution
* - **PATH Augmentation**: Adds common binary locations to ensure tool discovery
* - **Stdio Piping**: Captures stdout/stderr for progress parsing and error reporting
*
* Progress Monitoring:
* The progressCallback receives updates at various stages:
* - 45%: Reading input (parsing phase)
* - 60%: Processing document (conversion phase)
* - 75%: Generating output (template application)
* - 85%: Running Typst engine (PDF generation)
* - 90%: Complete
*
* Timeout Handling:
* - Default: 60 seconds (configurable via pandocOptions.timeout)
* - Process killed with SIGTERM on timeout
* - Returns error result with timeout message
* - Prevents hung processes from blocking export queue
*
* Error Handling:
* - Non-zero exit code → Parses stderr for meaningful error
* - Process spawn failure → Returns startup error
* - Timeout → Returns timeout error
* - All errors include diagnostic context for debugging
*
* @param args - Complete command-line arguments for Pandoc (from PandocCommandBuilder)
* @param pandocOptions - Configuration including paths, timeout, and working directory
* @param progressCallback - Optional callback for real-time progress updates
* @returns Promise resolving to ConversionResult with success status and output
*
* @example
* ```typescript
* // Basic execution
* const executor = new PandocExecutor(this.plugin);
* const result = await executor.executePandoc(args, options);
*
* if (!result.success) {
* new Notice(`Conversion failed: ${result.error}`);
* }
* ```
*
* @example
* ```typescript
* // With progress callback for UI updates
* const result = await executor.executePandoc(
* args,
* options,
* (message, progress) => {
* progressModal.update(message, progress);
* }
* );
* ```
*
* @example
* ```typescript
* // With custom timeout for large documents
* const result = await executor.executePandoc(
* args,
* {
* ...options,
* timeout: 300000 // 5 minutes for large PDF
* }
* );
* ```
*/
async executePandoc(
args: string[],
pandocOptions: PandocOptions,
args: string[],
pandocOptions: PandocOptions,
progressCallback?: ProgressCallback
): Promise<ConversionResult> {
return new Promise((resolve) => {
@@ -122,9 +244,59 @@ export class PandocExecutor {
}
/**
* Parse progress information from pandoc output and update progress callback
* @param output Raw output from pandoc stderr
* @param progressCallback Optional callback to update progress
* Parses Pandoc's stderr output to detect conversion progress and update the UI.
*
* This method implements heuristic progress detection by scanning stderr output for
* specific keywords that indicate which phase of the conversion pipeline is active.
* While Pandoc doesn't provide structured progress events, certain log patterns
* reliably appear during specific phases.
*
* Detection Heuristics:
* - **"parsing" or "reading"** → 45% (Input parsing phase)
* - Pandoc is reading and parsing the markdown input
* - AST construction is underway
* - **"writing" or "generating"** → 75% (Output generation phase)
* - Pandoc is generating Typst markup from the AST
* - Template application is occurring
* - **"typst"** → 85% (PDF generation phase)
* - Typst engine is compiling to PDF
* - Final rendering in progress
*
* Progress updates are only sent if a progressCallback was provided. Multiple
* matches to the same pattern won't duplicate callbacks - only one update per
* phase is typical.
*
* Enhancement Opportunities:
* - Parse Typst's own progress output for more granular PDF generation updates
* - Detect specific error keywords to provide early warning
* - Track file processing count for multi-file conversions
*
* @param output - Raw text from Pandoc's stderr stream
* @param progressCallback - Optional callback to invoke with progress updates
* @private
*
* @example
* ```typescript
* // Typical stderr patterns that trigger updates:
* parseProgressFromOutput('[INFO] Parsing markdown...', callback);
* // → Triggers: callback('Reading input...', 45)
*
* parseProgressFromOutput('[INFO] Writing typst output...', callback);
* // → Triggers: callback('Generating output...', 75)
*
* parseProgressFromOutput('Running typst compile...', callback);
* // → Triggers: callback('Running Typst engine...', 85)
* ```
*
* @example
* ```typescript
* // Used in stderr stream handler:
* pandocProcess.stderr?.on('data', (data: Buffer) => {
* const output = data.toString();
* stderr += output;
* this.parseProgressFromOutput(output, progressCallback);
* });
* ```
*/
private parseProgressFromOutput(output: string, progressCallback?: ProgressCallback): void {
// Basic progress parsing - could be enhanced based on pandoc output patterns
@@ -138,10 +310,79 @@ export class PandocExecutor {
}
/**
* Extract meaningful error messages from pandoc output
* @param stderr Standard error output from pandoc
* @param stdout Standard output from pandoc
* @returns Formatted error message
* Extracts meaningful, user-friendly error messages from Pandoc's raw output.
*
* This method implements a multi-tier fallback strategy to find the most relevant
* error information from Pandoc's stderr and stdout streams. Pandoc and Typst can
* produce verbose diagnostic output, so this method filters to find the most
* actionable error message for users.
*
* Extraction Strategy (in priority order):
* 1. **Pattern Matching**: Scan all output for common error indicators
* - Case-insensitive "error:" matches most Pandoc/Typst errors
* - Case-sensitive "Error:" catches Python and other tool errors
* - "failed" indicates operation failures
* - "Fatal" indicates critical termination errors
* - "pandoc:" catches Pandoc-specific diagnostic messages
*
* 2. **First Stderr Line**: If no pattern matches, use first non-empty stderr line
* - Assumes most important error appears early in stderr
* - Filters out empty lines for cleaner messages
*
* 3. **Generic Fallback**: If no stderr content, return generic error
* - Indicates process failure with no diagnostic output
* - Should be rare in practice
*
* Error Pattern Examples:
* - `Error: Could not find template: custom.typ` (Pandoc template error)
* - `pandoc: Cannot find file input.md` (File not found)
* - `error: font not found: "NonexistentFont"` (Typst font error)
* - `Fatal error: out of memory` (Resource exhaustion)
* - `failed to compile: syntax error at line 42` (Typst compilation error)
*
* The extracted message is displayed directly to users in error notices, so it
* should be concise and actionable without requiring interpretation.
*
* @param stderr - Complete stderr output captured from Pandoc process
* @param stdout - Complete stdout output captured from Pandoc process
* @returns User-friendly error message suitable for display in Notice
* @private
*
* @example
* ```typescript
* // Template not found error
* const stderr = "Error: Could not find template: custom.typ\nUsage: pandoc...";
* const error = this.extractErrorMessage(stderr, '');
* // Returns: "Error: Could not find template: custom.typ"
* ```
*
* @example
* ```typescript
* // Typst compilation error
* const stderr = "typst compile failed\nerror: undefined function `foo`\n at line 15";
* const error = this.extractErrorMessage(stderr, '');
* // Returns: "error: undefined function `foo`"
* ```
*
* @example
* ```typescript
* // Generic failure with no specific error
* const stderr = "";
* const stdout = "Some non-error output";
* const error = this.extractErrorMessage(stderr, stdout);
* // Returns: "Unknown error occurred during conversion"
* ```
*
* @example
* ```typescript
* // Used in process close handler:
* pandocProcess.on('close', (code: number | null) => {
* if (!success) {
* result.error = this.extractErrorMessage(stderr, stdout);
* new Notice(`Export failed: ${result.error}`);
* }
* });
* ```
*/
private extractErrorMessage(stderr: string, stdout: string): string {
// Look for common error patterns
@@ -154,7 +395,7 @@ export class PandocExecutor {
];
const allOutput = (stderr + '\n' + stdout).split('\n');
for (const line of allOutput) {
for (const pattern of errorPatterns) {
if (pattern.test(line)) {