refactor: extract EmbedProcessor and fix WebP conversion
- Extract embed processing logic from MarkdownPreprocessor to new EmbedProcessor module - Fix WebP image conversion that was broken during refactoring: - Update ImageMagick command from deprecated 'convert' to modern 'magick' - Fix field name mismatch: use 'sizeOrAlt' instead of 'alt' in plugin/EmbedProcessor - Use PathResolver for proper ImageMagick executable path resolution - Restore comprehensive embed processing including images, PDFs, and files - Add proper error handling and fallback for WebP conversion failures - Maintain size parameter parsing (e.g., "400x300") vs alt text differentiation Resolves WebP conversion issues and completes Step 2.3 of refactoring plan. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
3 files changed
+329
-173
No files matched your search
@@ -5,6 +5,7 @@
|
|||||||
|
|
||||||
import { FrontmatterProcessor, FrontmatterProcessorConfig } from './preprocessors/FrontmatterProcessor';
|
import { FrontmatterProcessor, FrontmatterProcessorConfig } from './preprocessors/FrontmatterProcessor';
|
||||||
import { WikilinkProcessor, WikilinkConfig, WikilinkProcessorConfig } from './preprocessors/WikilinkProcessor';
|
import { WikilinkProcessor, WikilinkConfig, WikilinkProcessorConfig } from './preprocessors/WikilinkProcessor';
|
||||||
|
import { EmbedProcessor, EmbedProcessorConfig } from './preprocessors/EmbedProcessor';
|
||||||
|
|
||||||
export interface PreprocessorOptions {
|
export interface PreprocessorOptions {
|
||||||
/** Include metadata extraction in processing */
|
/** Include metadata extraction in processing */
|
||||||
@@ -77,11 +78,10 @@ export class MarkdownPreprocessor {
|
|||||||
private noteTitle?: string;
|
private noteTitle?: string;
|
||||||
private frontmatterProcessor: FrontmatterProcessor;
|
private frontmatterProcessor: FrontmatterProcessor;
|
||||||
private wikilinkProcessor: WikilinkProcessor;
|
private wikilinkProcessor: WikilinkProcessor;
|
||||||
|
private embedProcessor: EmbedProcessor;
|
||||||
|
|
||||||
// Regex patterns for Obsidian syntax
|
// Regex patterns for Obsidian syntax
|
||||||
private readonly WIKILINK_PATTERN = /\[\[([^\|\]]+)(?:\|([^\]]+))?\]\]/g;
|
private readonly WIKILINK_PATTERN = /\[\[([^\|\]]+)(?:\|([^\]]+))?\]\]/g;
|
||||||
private readonly EMBED_PATTERN = /!\[\[([^\|\]]+)(?:\|([^\]]+))?\]\]/g;
|
|
||||||
private readonly EMBED_SIZE_PATTERN = /(\d+)(?:x(\d+))?/;
|
|
||||||
private readonly CALLOUT_PATTERN = /^>\s*\[!([\w-]+)\]([+-]?)\s*(.*)$/gm;
|
private readonly CALLOUT_PATTERN = /^>\s*\[!([\w-]+)\]([+-]?)\s*(.*)$/gm;
|
||||||
private readonly MULTI_LINE_CALLOUT_PATTERN = /^(>\s*\[!([\w-]+)\]([+-]?)\s*(.*(?:\n(?:>.*|$))*?))/gm;
|
private readonly MULTI_LINE_CALLOUT_PATTERN = /^(>\s*\[!([\w-]+)\]([+-]?)\s*(.*(?:\n(?:>.*|$))*?))/gm;
|
||||||
private readonly TAG_PATTERN = /#(?:[^\s#]+)/g;
|
private readonly TAG_PATTERN = /#(?:[^\s#]+)/g;
|
||||||
@@ -105,6 +105,11 @@ export class MarkdownPreprocessor {
|
|||||||
baseUrl: this.options.baseUrl
|
baseUrl: this.options.baseUrl
|
||||||
};
|
};
|
||||||
this.wikilinkProcessor = new WikilinkProcessor(wikilinkProcessorConfig);
|
this.wikilinkProcessor = new WikilinkProcessor(wikilinkProcessorConfig);
|
||||||
|
|
||||||
|
const embedProcessorConfig: EmbedProcessorConfig = {
|
||||||
|
wikilinkProcessor: this.wikilinkProcessor
|
||||||
|
};
|
||||||
|
this.embedProcessor = new EmbedProcessor(embedProcessorConfig);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -146,7 +151,7 @@ export class MarkdownPreprocessor {
|
|||||||
result.content = this.filterUnnecessaryLinks(result.content, result);
|
result.content = this.filterUnnecessaryLinks(result.content, result);
|
||||||
|
|
||||||
// Step 5: Convert embeds FIRST (before wikilinks to avoid .md extension being added)
|
// Step 5: Convert embeds FIRST (before wikilinks to avoid .md extension being added)
|
||||||
result.content = this.parseEmbeds(result.content, result);
|
result.content = this.embedProcessor.processEmbeds(result.content, result);
|
||||||
|
|
||||||
// Step 6: Convert wikilinks (after embeds are processed)
|
// Step 6: Convert wikilinks (after embeds are processed)
|
||||||
result.content = this.wikilinkProcessor.processWikilinks(result.content, result);
|
result.content = this.wikilinkProcessor.processWikilinks(result.content, result);
|
||||||
@@ -211,167 +216,6 @@ export class MarkdownPreprocessor {
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Convert embed syntax to standard markdown references
|
|
||||||
*/
|
|
||||||
private parseEmbeds(content: string, result: PreprocessingResult): string {
|
|
||||||
return content.replace(this.EMBED_PATTERN, (match, embedPath, sizeOrAlt) => {
|
|
||||||
try {
|
|
||||||
const cleanPath = embedPath.trim();
|
|
||||||
|
|
||||||
if (!cleanPath) {
|
|
||||||
result.warnings.push(`Empty embed path found: ${match}`);
|
|
||||||
return match;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Parse file extension and path
|
|
||||||
const fileExtension = this.getFileExtension(cleanPath);
|
|
||||||
const fileType = this.determineFileType(fileExtension);
|
|
||||||
|
|
||||||
// Handle different file types
|
|
||||||
switch (fileType) {
|
|
||||||
case 'image':
|
|
||||||
return this.processImageEmbed(cleanPath, sizeOrAlt, result);
|
|
||||||
|
|
||||||
case 'pdf':
|
|
||||||
return this.processPdfEmbed(cleanPath, sizeOrAlt, result);
|
|
||||||
|
|
||||||
case 'file':
|
|
||||||
return this.processFileEmbed(cleanPath, sizeOrAlt, result);
|
|
||||||
|
|
||||||
default:
|
|
||||||
// This should never happen with the simplified type system
|
|
||||||
result.warnings.push(`Unexpected file type for embed: ${cleanPath}`);
|
|
||||||
return this.processFileEmbed(cleanPath, sizeOrAlt, result);
|
|
||||||
}
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
result.warnings.push(`Failed to process embed: ${match} - ${error.message}`);
|
|
||||||
return match; // Return original on error
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get file extension from path
|
|
||||||
*/
|
|
||||||
private getFileExtension(filePath: string): string {
|
|
||||||
const lastDot = filePath.lastIndexOf('.');
|
|
||||||
return lastDot > 0 ? filePath.substring(lastDot).toLowerCase() : '';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Determine file type based on extension
|
|
||||||
* Simplified to 3 types: image (displayed), pdf (embedded with preview), file (embedded)
|
|
||||||
*/
|
|
||||||
private determineFileType(extension: string): 'image' | 'pdf' | 'file' {
|
|
||||||
const imageExtensions = ['.png', '.jpg', '.jpeg', '.gif', '.svg', '.webp', '.bmp', '.ico', '.tiff'];
|
|
||||||
|
|
||||||
if (imageExtensions.includes(extension)) return 'image';
|
|
||||||
if (extension === '.pdf') return 'pdf';
|
|
||||||
|
|
||||||
// All other file types (including DOCX, videos, audio, etc.) are treated as files to be embedded
|
|
||||||
return 'file';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Process image embeds with size parameters
|
|
||||||
*/
|
|
||||||
private processImageEmbed(imagePath: string, sizeOrAlt: string | undefined, result: PreprocessingResult): string {
|
|
||||||
const sanitizedPath = this.wikilinkProcessor.sanitizeFilePath(imagePath);
|
|
||||||
|
|
||||||
// For now, we'll mark this for async processing and return a placeholder
|
|
||||||
// The actual copying will be handled in the main export process
|
|
||||||
const fileName = imagePath.substring(imagePath.lastIndexOf('/') + 1);
|
|
||||||
const baseName = fileName.replace(/\.[^/.]+$/, ""); // Remove extension
|
|
||||||
|
|
||||||
// Create a marker that the export process can detect and replace
|
|
||||||
const marker = `IMAGE_EMBED_MARKER:${imagePath}:${baseName}:${sizeOrAlt || ''}`;
|
|
||||||
|
|
||||||
// Add to processing queue for later copying
|
|
||||||
if (!result.metadata.imageEmbeds) {
|
|
||||||
result.metadata.imageEmbeds = [];
|
|
||||||
}
|
|
||||||
result.metadata.imageEmbeds.push({
|
|
||||||
originalPath: imagePath,
|
|
||||||
sanitizedPath: sanitizedPath,
|
|
||||||
fileName: fileName,
|
|
||||||
baseName: baseName,
|
|
||||||
sizeOrAlt: sizeOrAlt,
|
|
||||||
marker: marker
|
|
||||||
});
|
|
||||||
|
|
||||||
result.warnings.push(`Image embed queued for processing: ${imagePath}`);
|
|
||||||
|
|
||||||
return marker;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Process PDF embeds - Convert to image preview with PDF attachment using Typst's pdf.embed
|
|
||||||
*/
|
|
||||||
private processPdfEmbed(pdfPath: string, options: string | undefined, result: PreprocessingResult): string {
|
|
||||||
const sanitizedPath = this.wikilinkProcessor.sanitizeFilePath(pdfPath);
|
|
||||||
|
|
||||||
// For now, we'll mark this for async processing and return a placeholder
|
|
||||||
// The actual conversion will be handled in the main export process
|
|
||||||
const fileName = pdfPath.substring(pdfPath.lastIndexOf('/') + 1);
|
|
||||||
const baseName = fileName.replace(/\.[^/.]+$/, ""); // Remove extension
|
|
||||||
|
|
||||||
// Create a marker that the export process can detect and replace with Typst code
|
|
||||||
const marker = `TYPST_PDF_EMBED_MARKER:${pdfPath}:${baseName}:${options || ''}`;
|
|
||||||
|
|
||||||
// Add to processing queue for later conversion
|
|
||||||
if (!result.metadata.pdfEmbeds) {
|
|
||||||
result.metadata.pdfEmbeds = [];
|
|
||||||
}
|
|
||||||
result.metadata.pdfEmbeds.push({
|
|
||||||
originalPath: pdfPath,
|
|
||||||
sanitizedPath: sanitizedPath,
|
|
||||||
fileName: fileName,
|
|
||||||
baseName: baseName,
|
|
||||||
options: options,
|
|
||||||
marker: marker
|
|
||||||
});
|
|
||||||
|
|
||||||
result.warnings.push(`PDF embed queued for processing with Typst pdf.embed: ${pdfPath}`);
|
|
||||||
|
|
||||||
return marker;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Process generic file embeds - Convert to attachment using Typst's pdf.embed
|
|
||||||
*/
|
|
||||||
private processFileEmbed(filePath: string, options: string | undefined, result: PreprocessingResult): string {
|
|
||||||
const sanitizedPath = this.wikilinkProcessor.sanitizeFilePath(filePath);
|
|
||||||
|
|
||||||
// For now, we'll mark this for async processing and return a placeholder
|
|
||||||
// The actual embedding will be handled in the main export process
|
|
||||||
const fileName = filePath.substring(filePath.lastIndexOf('/') + 1);
|
|
||||||
const baseName = fileName.replace(/\.[^/.]+$/, ""); // Remove extension
|
|
||||||
const fileExtension = this.getFileExtension(fileName);
|
|
||||||
|
|
||||||
// Create a marker that the export process can detect and replace with Typst code
|
|
||||||
const marker = `FILE_EMBED_MARKER:${filePath}:${baseName}:${options || ''}`;
|
|
||||||
|
|
||||||
// Add to processing queue for later conversion
|
|
||||||
if (!result.metadata.fileEmbeds) {
|
|
||||||
result.metadata.fileEmbeds = [];
|
|
||||||
}
|
|
||||||
result.metadata.fileEmbeds.push({
|
|
||||||
originalPath: filePath,
|
|
||||||
sanitizedPath: sanitizedPath,
|
|
||||||
fileName: fileName,
|
|
||||||
baseName: baseName,
|
|
||||||
fileType: fileExtension,
|
|
||||||
options: options,
|
|
||||||
marker: marker
|
|
||||||
});
|
|
||||||
|
|
||||||
result.warnings.push(`File embed queued for processing with Typst pdf.embed: ${filePath}`);
|
|
||||||
|
|
||||||
return marker;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Convert Obsidian callouts to standard blockquotes with styling markers
|
* Convert Obsidian callouts to standard blockquotes with styling markers
|
||||||
@@ -789,6 +633,11 @@ export class MarkdownPreprocessor {
|
|||||||
wikilinkConfig: this.wikilinkConfig,
|
wikilinkConfig: this.wikilinkConfig,
|
||||||
baseUrl: this.options.baseUrl
|
baseUrl: this.options.baseUrl
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Update EmbedProcessor since it depends on WikilinkProcessor
|
||||||
|
this.embedProcessor.updateConfig({
|
||||||
|
wikilinkProcessor: this.wikilinkProcessor
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,245 @@
|
|||||||
|
/**
|
||||||
|
* EmbedProcessor - Handles conversion of Obsidian embed syntax to markdown references
|
||||||
|
* Processes images, PDFs, and generic file embeds with appropriate markers for later processing
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { WikilinkProcessor } from './WikilinkProcessor';
|
||||||
|
|
||||||
|
export interface EmbedProcessorConfig {
|
||||||
|
/** WikilinkProcessor instance for path sanitization */
|
||||||
|
wikilinkProcessor: WikilinkProcessor;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Note: PreprocessingResult is imported from the parent MarkdownPreprocessor module
|
||||||
|
export interface PreprocessingResult {
|
||||||
|
/** Processed markdown content */
|
||||||
|
content: string;
|
||||||
|
/** Extracted metadata including tags and frontmatter */
|
||||||
|
metadata: {
|
||||||
|
tags: string[];
|
||||||
|
frontmatter?: Record<string, any>;
|
||||||
|
title?: string;
|
||||||
|
wordCount: number;
|
||||||
|
pdfEmbeds?: Array<{
|
||||||
|
originalPath: string;
|
||||||
|
sanitizedPath: string;
|
||||||
|
fileName: string;
|
||||||
|
baseName: string;
|
||||||
|
options?: string;
|
||||||
|
marker: string;
|
||||||
|
}>;
|
||||||
|
imageEmbeds?: Array<{
|
||||||
|
originalPath: string;
|
||||||
|
sanitizedPath: string;
|
||||||
|
fileName: string;
|
||||||
|
baseName: string;
|
||||||
|
sizeOrAlt?: string;
|
||||||
|
marker: string;
|
||||||
|
}>;
|
||||||
|
fileEmbeds?: Array<{
|
||||||
|
originalPath: string;
|
||||||
|
sanitizedPath: string;
|
||||||
|
fileName: string;
|
||||||
|
baseName: string;
|
||||||
|
fileType: string;
|
||||||
|
options?: string;
|
||||||
|
marker: string;
|
||||||
|
}>;
|
||||||
|
};
|
||||||
|
/** Processing errors and warnings */
|
||||||
|
errors: string[];
|
||||||
|
/** Processing warnings */
|
||||||
|
warnings: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export class EmbedProcessor {
|
||||||
|
private wikilinkProcessor: WikilinkProcessor;
|
||||||
|
|
||||||
|
// Regex patterns for embed matching
|
||||||
|
private readonly EMBED_PATTERN = /!\[\[([^\|\]]+)(?:\|([^\]]+))?\]\]/g;
|
||||||
|
private readonly EMBED_SIZE_PATTERN = /(\d+)(?:x(\d+))?/;
|
||||||
|
|
||||||
|
constructor(config: EmbedProcessorConfig) {
|
||||||
|
this.wikilinkProcessor = config.wikilinkProcessor;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert embed syntax to standard markdown references
|
||||||
|
*/
|
||||||
|
public processEmbeds(content: string, result: PreprocessingResult): string {
|
||||||
|
return content.replace(this.EMBED_PATTERN, (match, embedPath, sizeOrAlt) => {
|
||||||
|
try {
|
||||||
|
const cleanPath = embedPath.trim();
|
||||||
|
|
||||||
|
if (!cleanPath) {
|
||||||
|
result.warnings.push(`Empty embed path found: ${match}`);
|
||||||
|
return match;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse file extension and path
|
||||||
|
const fileExtension = this.getFileExtension(cleanPath);
|
||||||
|
const fileType = this.determineFileType(fileExtension);
|
||||||
|
|
||||||
|
// Handle different file types
|
||||||
|
switch (fileType) {
|
||||||
|
case 'image':
|
||||||
|
return this.processImageEmbed(cleanPath, sizeOrAlt, result);
|
||||||
|
|
||||||
|
case 'pdf':
|
||||||
|
return this.processPdfEmbed(cleanPath, sizeOrAlt, result);
|
||||||
|
|
||||||
|
case 'file':
|
||||||
|
return this.processFileEmbed(cleanPath, sizeOrAlt, result);
|
||||||
|
|
||||||
|
default:
|
||||||
|
// This should never happen with the simplified type system
|
||||||
|
result.warnings.push(`Unexpected file type for embed: ${cleanPath}`);
|
||||||
|
return this.processFileEmbed(cleanPath, sizeOrAlt, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
result.warnings.push(`Failed to process embed: ${match} - ${error.message}`);
|
||||||
|
return match; // Return original on error
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get file extension from path
|
||||||
|
*/
|
||||||
|
private getFileExtension(filePath: string): string {
|
||||||
|
const lastDot = filePath.lastIndexOf('.');
|
||||||
|
return lastDot > 0 ? filePath.substring(lastDot).toLowerCase() : '';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Determine file type based on extension
|
||||||
|
* Simplified to 3 types: image (displayed), pdf (embedded with preview), file (embedded)
|
||||||
|
*/
|
||||||
|
private determineFileType(extension: string): 'image' | 'pdf' | 'file' {
|
||||||
|
const imageExtensions = ['.png', '.jpg', '.jpeg', '.gif', '.svg', '.webp', '.bmp', '.ico', '.tiff'];
|
||||||
|
|
||||||
|
if (imageExtensions.includes(extension)) return 'image';
|
||||||
|
if (extension === '.pdf') return 'pdf';
|
||||||
|
|
||||||
|
// All other file types (including DOCX, videos, audio, etc.) are treated as files to be embedded
|
||||||
|
return 'file';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Process image embeds with size parameters
|
||||||
|
*/
|
||||||
|
private processImageEmbed(imagePath: string, sizeOrAlt: string | undefined, result: PreprocessingResult): string {
|
||||||
|
const sanitizedPath = this.wikilinkProcessor.sanitizeFilePath(imagePath);
|
||||||
|
|
||||||
|
// For now, we'll mark this for async processing and return a placeholder
|
||||||
|
// The actual copying will be handled in the main export process
|
||||||
|
const fileName = imagePath.substring(imagePath.lastIndexOf('/') + 1);
|
||||||
|
const baseName = fileName.replace(/\.[^/.]+$/, ""); // Remove extension
|
||||||
|
|
||||||
|
// Create a marker that the export process can detect and replace
|
||||||
|
const marker = `IMAGE_EMBED_MARKER:${imagePath}:${baseName}:${sizeOrAlt || ''}`;
|
||||||
|
|
||||||
|
// Add to processing queue for later copying
|
||||||
|
if (!result.metadata.imageEmbeds) {
|
||||||
|
result.metadata.imageEmbeds = [];
|
||||||
|
}
|
||||||
|
result.metadata.imageEmbeds.push({
|
||||||
|
originalPath: imagePath,
|
||||||
|
sanitizedPath: sanitizedPath,
|
||||||
|
fileName: fileName,
|
||||||
|
baseName: baseName,
|
||||||
|
sizeOrAlt: sizeOrAlt,
|
||||||
|
marker: marker
|
||||||
|
});
|
||||||
|
|
||||||
|
result.warnings.push(`Image embed queued for processing: ${imagePath}`);
|
||||||
|
|
||||||
|
return marker;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Process PDF embeds - Convert to image preview with PDF attachment using Typst's pdf.embed
|
||||||
|
*/
|
||||||
|
private processPdfEmbed(pdfPath: string, options: string | undefined, result: PreprocessingResult): string {
|
||||||
|
const sanitizedPath = this.wikilinkProcessor.sanitizeFilePath(pdfPath);
|
||||||
|
|
||||||
|
// For now, we'll mark this for async processing and return a placeholder
|
||||||
|
// The actual conversion will be handled in the main export process
|
||||||
|
const fileName = pdfPath.substring(pdfPath.lastIndexOf('/') + 1);
|
||||||
|
const baseName = fileName.replace(/\.[^/.]+$/, ""); // Remove extension
|
||||||
|
|
||||||
|
// Create a marker that the export process can detect and replace with Typst code
|
||||||
|
const marker = `TYPST_PDF_EMBED_MARKER:${pdfPath}:${baseName}:${options || ''}`;
|
||||||
|
|
||||||
|
// Add to processing queue for later conversion
|
||||||
|
if (!result.metadata.pdfEmbeds) {
|
||||||
|
result.metadata.pdfEmbeds = [];
|
||||||
|
}
|
||||||
|
result.metadata.pdfEmbeds.push({
|
||||||
|
originalPath: pdfPath,
|
||||||
|
sanitizedPath: sanitizedPath,
|
||||||
|
fileName: fileName,
|
||||||
|
baseName: baseName,
|
||||||
|
options: options,
|
||||||
|
marker: marker
|
||||||
|
});
|
||||||
|
|
||||||
|
result.warnings.push(`PDF embed queued for processing with Typst pdf.embed: ${pdfPath}`);
|
||||||
|
|
||||||
|
return marker;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Process generic file embeds - Convert to attachment using Typst's pdf.embed
|
||||||
|
* Note: This handles all non-image, non-PDF files including videos, audio, documents, etc.
|
||||||
|
*/
|
||||||
|
private processFileEmbed(filePath: string, options: string | undefined, result: PreprocessingResult): string {
|
||||||
|
const sanitizedPath = this.wikilinkProcessor.sanitizeFilePath(filePath);
|
||||||
|
|
||||||
|
// For now, we'll mark this for async processing and return a placeholder
|
||||||
|
// The actual embedding will be handled in the main export process
|
||||||
|
const fileName = filePath.substring(filePath.lastIndexOf('/') + 1);
|
||||||
|
const baseName = fileName.replace(/\.[^/.]+$/, ""); // Remove extension
|
||||||
|
const fileExtension = this.getFileExtension(fileName);
|
||||||
|
|
||||||
|
// Create a marker that the export process can detect and replace with Typst code
|
||||||
|
const marker = `FILE_EMBED_MARKER:${filePath}:${baseName}:${options || ''}`;
|
||||||
|
|
||||||
|
// Add to processing queue for later conversion
|
||||||
|
if (!result.metadata.fileEmbeds) {
|
||||||
|
result.metadata.fileEmbeds = [];
|
||||||
|
}
|
||||||
|
result.metadata.fileEmbeds.push({
|
||||||
|
originalPath: filePath,
|
||||||
|
sanitizedPath: sanitizedPath,
|
||||||
|
fileName: fileName,
|
||||||
|
baseName: baseName,
|
||||||
|
fileType: fileExtension,
|
||||||
|
options: options,
|
||||||
|
marker: marker
|
||||||
|
});
|
||||||
|
|
||||||
|
result.warnings.push(`File embed queued for processing with Typst pdf.embed: ${filePath}`);
|
||||||
|
|
||||||
|
return marker;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update configuration
|
||||||
|
*/
|
||||||
|
public updateConfig(config: Partial<EmbedProcessorConfig>): void {
|
||||||
|
if (config.wikilinkProcessor) {
|
||||||
|
this.wikilinkProcessor = config.wikilinkProcessor;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get current configuration
|
||||||
|
*/
|
||||||
|
public getConfig(): EmbedProcessorConfig {
|
||||||
|
return {
|
||||||
|
wikilinkProcessor: this.wikilinkProcessor
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -136,27 +136,89 @@ export class EmbedProcessor {
|
|||||||
if (!fullImagePath) {
|
if (!fullImagePath) {
|
||||||
console.warn(`Export: Image file not found: ${decodedPath}`);
|
console.warn(`Export: Image file not found: ${decodedPath}`);
|
||||||
// Keep the original marker or replace with placeholder
|
// Keep the original marker or replace with placeholder
|
||||||
const fallbackOutput = `[⚠️ **Image not found:** ${imageEmbed.alt || imageEmbed.originalPath}]`;
|
const fallbackOutput = `[⚠️ **Image not found:** ${imageEmbed.sizeOrAlt || imageEmbed.originalPath}]`;
|
||||||
updatedContent = updatedContent.replace(imageEmbed.marker, fallbackOutput);
|
updatedContent = updatedContent.replace(imageEmbed.marker, fallbackOutput);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get relative path from vault base for the image
|
// Handle WebP conversion if needed
|
||||||
const relativeImagePath = path.relative(vaultBasePath, fullImagePath);
|
let finalImagePath = fullImagePath;
|
||||||
|
const fileExtension = path.extname(fullImagePath).toLowerCase();
|
||||||
|
|
||||||
// Replace the marker with Markdown image syntax (Pandoc will convert to Typst)
|
if (fileExtension === '.webp') {
|
||||||
const markdownImage = imageEmbed.alt ?
|
// Convert WebP to PNG using ImageMagick
|
||||||
`` :
|
const originalImageName = path.basename(fullImagePath);
|
||||||
``;
|
const pngFileName = originalImageName.replace(/\.webp$/i, '.png');
|
||||||
|
const vaultTempImagesDir = path.join(vaultBasePath, this.plugin.manifest.dir!, 'temp-images');
|
||||||
|
await fs.promises.mkdir(vaultTempImagesDir, { recursive: true });
|
||||||
|
|
||||||
updatedContent = updatedContent.replace(imageEmbed.marker, markdownImage);
|
const convertedImagePath = path.join(vaultTempImagesDir, pngFileName);
|
||||||
|
|
||||||
|
console.log(`Export: Converting WebP to PNG: ${originalImageName} -> ${pngFileName}`);
|
||||||
|
|
||||||
|
const { exec } = require('child_process');
|
||||||
|
const util = require('util');
|
||||||
|
const execAsync = util.promisify(exec);
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Use PathResolver to get the correct ImageMagick path
|
||||||
|
const { PathResolver } = await import('./PathResolver');
|
||||||
|
const pathResolver = new PathResolver(this.plugin);
|
||||||
|
const imagemagickPath = pathResolver.resolveExecutablePath(
|
||||||
|
this.plugin.settings.executablePaths.imagemagickPath,
|
||||||
|
'magick'
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!imagemagickPath) {
|
||||||
|
throw new Error('ImageMagick not found - please install ImageMagick or configure the path in settings');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use resolved ImageMagick path to convert WebP to PNG
|
||||||
|
await execAsync(`"${imagemagickPath}" "${fullImagePath}" "${convertedImagePath}"`);
|
||||||
|
console.log(`Export: Successfully converted WebP to PNG: ${pngFileName}`);
|
||||||
|
finalImagePath = convertedImagePath;
|
||||||
|
} catch (convertError) {
|
||||||
|
console.error(`Export: Failed to convert WebP image: ${convertError.message}`);
|
||||||
|
// Fall back to original path and let Typst/Pandoc handle the error
|
||||||
|
console.warn(`Export: Proceeding with original WebP file: ${fullImagePath}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get relative path from vault base for the final image
|
||||||
|
const relativeImagePath = path.relative(vaultBasePath, finalImagePath);
|
||||||
|
|
||||||
|
// Create the appropriate markdown output based on size/alt text
|
||||||
|
let imageOutput;
|
||||||
|
if (imageEmbed.sizeOrAlt) {
|
||||||
|
// Check if it's size information (width x height pattern)
|
||||||
|
const sizeMatch = imageEmbed.sizeOrAlt.match(/^(\d+)(?:x(\d+))?$/);
|
||||||
|
if (sizeMatch) {
|
||||||
|
const width = sizeMatch[1];
|
||||||
|
const height = sizeMatch[2];
|
||||||
|
|
||||||
|
// Create image with size attributes (optimized for Pandoc → Typst conversion)
|
||||||
|
if (height) {
|
||||||
|
imageOutput = `<img src="${relativeImagePath}" width="${width}" height="${height}" alt="${imageEmbed.baseName}" />`;
|
||||||
|
} else {
|
||||||
|
imageOutput = `<img src="${relativeImagePath}" width="${width}" alt="${imageEmbed.baseName}" />`;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Treat as alt text
|
||||||
|
imageOutput = ``;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Standard image reference
|
||||||
|
imageOutput = ``;
|
||||||
|
}
|
||||||
|
|
||||||
|
updatedContent = updatedContent.replace(imageEmbed.marker, imageOutput);
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const { fallback } = ExportErrorHandler.handleProcessingError(
|
const { fallback } = ExportErrorHandler.handleProcessingError(
|
||||||
'image embed',
|
'image embed',
|
||||||
imageEmbed.originalPath,
|
imageEmbed.originalPath,
|
||||||
error,
|
error,
|
||||||
`[⚠️ **Image processing error:** ${imageEmbed.alt || imageEmbed.originalPath}]`
|
`[⚠️ **Image processing error:** ${imageEmbed.sizeOrAlt || imageEmbed.originalPath}]`
|
||||||
);
|
);
|
||||||
updatedContent = updatedContent.replace(imageEmbed.marker, fallback);
|
updatedContent = updatedContent.replace(imageEmbed.marker, fallback);
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in new issue
Block a user