diff --git a/main.ts b/main.ts index 2f814f6..8bee73e 100644 --- a/main.ts +++ b/main.ts @@ -17,6 +17,7 @@ import { import { obsidianTypstPDFExportSettings, DEFAULT_SETTINGS } from './src/core/settings'; import { DependencyChecker } from './src/core/DependencyChecker'; +import type { PreprocessingResult } from './src/converters/MarkdownPreprocessor'; import { ExportErrorHandler } from './src/core/ExportErrorHandler'; import { PandocTypstConverter } from './src/converters/PandocTypstConverter'; import { TemplateManager } from './src/templates/TemplateManager'; @@ -194,21 +195,21 @@ export class obsidianTypstPDFExport extends Plugin { /** * Process PDF embeds (delegated to EmbedProcessor) */ - async processPdfEmbeds(processedResult: any, vaultBasePath: string, tempDir: string, currentFile?: TFile, embedPdfFiles: boolean = true): Promise { + async processPdfEmbeds(processedResult: PreprocessingResult, vaultBasePath: string, tempDir: string, currentFile?: TFile, embedPdfFiles: boolean = true): Promise { return this.embedProcessor.processPdfEmbeds(processedResult, vaultBasePath, tempDir, currentFile, embedPdfFiles); } /** * Process image embeds (delegated to EmbedProcessor) */ - async processImageEmbeds(processedResult: any, vaultBasePath: string, tempDir: string, currentFile?: TFile): Promise { + async processImageEmbeds(processedResult: PreprocessingResult, vaultBasePath: string, tempDir: string, currentFile?: TFile): Promise { return this.embedProcessor.processImageEmbeds(processedResult, vaultBasePath, tempDir, currentFile); } /** * Process file embeds (delegated to EmbedProcessor) */ - async processFileEmbeds(processedResult: any, vaultBasePath: string, tempDir: string, currentFile?: TFile, embedAllFiles: boolean = true): Promise { + async processFileEmbeds(processedResult: PreprocessingResult, vaultBasePath: string, tempDir: string, currentFile?: TFile, embedAllFiles: boolean = true): Promise { return this.embedProcessor.processFileEmbeds(processedResult, vaultBasePath, tempDir, currentFile, embedAllFiles); } diff --git a/plan.md b/plan.md deleted file mode 100644 index dce6c77..0000000 --- a/plan.md +++ /dev/null @@ -1,334 +0,0 @@ -# Typst PDF Export Plugin Refactoring Plan - -## CRITICAL SAFETY REQUIREMENTS ⚠️ -**Previous refactor broke workflows** - We must be EXTREMELY careful -- **STOP after EVERY file creation** for verification -- **STOP after EVERY file modification** for verification -- **NO jumping ahead** - wait for explicit confirmation -- **Use Context7** for Obsidian and TypeScript API documentation -- **Test build after EVERY change** - -## Overview -Refactoring 6 large files (200-1800 lines) into smaller, focused modules to improve maintainability and reduce complexity. - -### Files Requiring Refactoring -1. **main.ts** - 1792 lines → ~200 lines + 6 modules -2. **MarkdownPreprocessor.ts** - 1235 lines → ~200 lines + 5 modules -3. **PandocTypstConverter.ts** - 741 lines → ~200 lines + 4 modules -4. **ExportConfigModal.ts** - 492 lines → ~200 lines + 3 modules -5. **PdfToImageConverter.ts** - 444 lines → ~150 lines + 3 modules -6. **DependencyChecker.ts** - 319 lines → ~170 lines + 2 modules - -## PHASE 1: Refactor main.ts (MOST CRITICAL)- DONE - -The main.ts file is the plugin entry point and most critical to get right. - -### Step 1.1: Create PluginLifecycle.ts - DONE -**Location:** `src/plugin/PluginLifecycle.ts` (~150 lines) -**Extract:** -- `onload()` method -- `onunload()` method -- Template initialization logic -- Settings loading/saving -- Cleanup on startup - -**STOP** → Verify: `npm run build` passes -**STOP** → Test: Plugin loads in Obsidian without errors - -### Step 1.2: Create CommandRegistry.ts - DONE -**Location:** `src/plugin/CommandRegistry.ts` (~150 lines) -**Extract:** -- `registerCommands()` method -- All command handler methods -- Command definitions and callbacks - -**STOP** → Verify: `npm run build` passes -**STOP** → Test: Commands appear and work in command palette - -### Step 1.3: Create EventHandlers.ts - DONE -**Location:** `src/plugin/EventHandlers.ts` (~150 lines) -**Extract:** -- `registerEventHandlers()` method -- `handleRibbonClick()` method -- File menu integration -- Context menu handlers - -**STOP** → Verify: `npm run build` passes -**STOP** → Test: Context menus and ribbon icon work - -### Step 1.4: Create ExportOrchestrator.ts -**Location:** `src/plugin/ExportOrchestrator.ts` (~400 lines) -**Extract:** -- `exportFile()` method -- `exportFiles()` method -- `exportFileWithConfig()` method -- `handleFolderExport()` method -- Export workflow coordination - -**STOP** → Verify: `npm run build` passes -**STOP** → Test: Basic single note export works - -### Step 1.5: Create FontManager.ts - DONE -**Location:** `src/plugin/FontManager.ts` (~150 lines) -**Extract:** -- `cacheAvailableFonts()` method -- `getCachedFonts()` method -- Font discovery and caching logic - -**STOP** → Verify: `npm run build` passes -**STOP** → Test: Font detection works in settings - -### Step 1.6: Create PathResolver.ts - DONE -**Location:** `src/plugin/PathResolver.ts` (~200 lines) -**Extract:** -- `resolveExecutablePath()` method -- `prepareOutputPath()` method -- Path validation utilities -- Executable finding logic - -**STOP** → Verify: `npm run build` passes -**STOP** → Test: Pandoc/Typst detection works - -### Step 1.7: Update main.ts - DONE -**Final size:** ~200 lines -**Keep:** -- Plugin class declaration -- Settings property -- Core Obsidian plugin methods -- Delegation to modules - -**STOP** → Full integration test of all functionality - -**CHECKPOINT: Complete test of all Phase 1 functionality** - DONE - -## PHASE 2: Refactor MarkdownPreprocessor.ts - DONE - -### Step 2.1: Create FrontmatterProcessor.ts - DONE -**Location:** `src/converters/preprocessors/FrontmatterProcessor.ts` (~200 lines) -**Extract:** -- `processFrontmatter()` method -- `formatFrontmatterForDisplay()` method -- Frontmatter parsing logic - -**STOP** → Verify build → Test frontmatter parsing works - -### Step 2.2: Create WikilinkProcessor.ts - DONE -**Location:** `src/converters/preprocessors/WikilinkProcessor.ts` (~150 lines) -**Extract:** -- `parseWikilinks()` method -- `sanitizeFilePath()` method -- `sanitizeHeadingForLink()` method -- `resolveRelativePath()` method - -**STOP** → Verify build → Test wikilink conversion works - -### Step 2.3: Create EmbedProcessor.ts - DONE -**Location:** `src/converters/preprocessors/EmbedProcessor.ts` (~250 lines) -**Extract:** -- `parseEmbeds()` method -- `processImageEmbed()` method -- `processVideoEmbed()` method -- `processAudioEmbed()` method -- `processPdfEmbed()` method -- `processFileEmbed()` method - -**STOP** → Verify build → Test all embed types work - -### Step 2.4: Create CalloutProcessor.ts - DONE -**Location:** `src/converters/preprocessors/CalloutProcessor.ts` (~200 lines) -**Extract:** -- `parseCallouts()` method -- `parseEmailBlocks()` method -- `processMultiLineCallouts()` method -- `processEmailBlock()` method - -**STOP** → Verify build → Test callouts and email blocks work - -### Step 2.5: Create MetadataExtractor.ts - DONE -**Location:** `src/converters/preprocessors/MetadataExtractor.ts` (~150 lines) -**Extract:** -- `extractTags()` method -- `extractTitle()` method -- `calculateWordCount()` method -- Metadata processing utilities - -**STOP** → Verify build → Test metadata extraction works - -### Step 2.6: Update MarkdownPreprocessor.ts - DONE -**Final size:** 204 lines (target ~200 lines) -**Keep:** -- Main `preprocess()` method -- Orchestration logic -- Result compilation - -**STOP** → Full preprocessing test with various note types - -**CHECKPOINT: Test various note types with different content** - -## PHASE 3: Refactor PandocTypstConverter.ts - IN PROGRESS - -### Step 3.1: Create PandocCommandBuilder.ts - DONE -**Location:** `src/converters/pandoc/PandocCommandBuilder.ts` (~200 lines) -**Extract:** -- Command building logic -- Argument construction -- Template handling - -**STOP** → Verify build → Test Pandoc command generation - -### Step 3.2: Create TypstVariableMapper.ts - DONE -**Location:** `src/converters/pandoc/TypstVariableMapper.ts` (~200 lines) -**Extract:** -- Variable mapping logic -- Settings to Typst conversion -- Font and layout variable handling - -**STOP** → Verify build → Test variable application in templates - -### Step 3.3: Create ResourcePathResolver.ts - DONE -**Location:** `src/converters/pandoc/ResourcePathResolver.ts` (~150 lines) -**Extract:** -- `resolveResourcePaths()` method -- Path caching logic -- Resource discovery - -**STOP** → Verify build → Test resource resolution works - -### Step 3.4: Update PandocTypstConverter.ts - DONE -**Final size:** ~200 lines -**Keep:** -- Main conversion method -- Result processing -- Error handling - -**STOP** → Full conversion test with various settings - -**CHECKPOINT: Test PDF generation with various settings** - -## PHASE 4: Refactor ExportConfigModal.ts - DONE - -### Step 4.1: Create ModalRenderer.ts - DONE -**Location:** `src/ui/modal/ModalRenderer.ts` (~150 lines) -**Extract:** -- `createHeader()` method -- `renderSections()` method -- `createProgressContainer()` method -- `createActionButtons()` method - -**STOP** → Verify build → Test modal displays correctly - -### Step 4.2: Create ModalValidator.ts - DONE -**Location:** `src/ui/modal/ModalValidator.ts` (~100 lines) -**Extract:** -- `validateAllSections()` method -- `showValidationErrors()` method -- `showValidationWarnings()` method -- Validation logic - -**STOP** → Verify build → Test validation works - -### Step 4.3: Update ExportConfigModal.ts - DONE -**Final size:** ~200 lines -**Keep:** -- Modal lifecycle methods -- Event handlers -- State management - -**STOP** → Full modal functionality test - -**CHECKPOINT: Test all modal interactions** - -## PHASE 5: Refactor PdfToImageConverter.ts - IN PROGRESS - -### Step 5.1: Create PdfProcessor.ts - DONE -**Location:** `src/converters/pdf/PdfProcessor.ts` (~150 lines) -**Extract:** -- Core PDF processing logic -- PDF parsing and page extraction - -**STOP** → Verify build → Test PDF processing - -### Step 5.2: Create ImageOptimizer.ts - IN PROGRESS -**Location:** `src/converters/pdf/ImageOptimizer.ts` (~150 lines) -**Extract:** -- Image optimization logic -- Resizing and compression -- Quality management - -**STOP** → Verify build → Test image optimization - -### Step 5.3: Update PdfToImageConverter.ts -**Final size:** ~150 lines -**Keep:** -- Main conversion method -- Error handling -- Result processing - -**STOP** → Test PDF to image conversion works - -**CHECKPOINT: Test embedded PDF conversion** - -## PHASE 6: Refactor DependencyChecker.ts - -### Step 6.1: Create ExecutableChecker.ts -**Location:** `src/core/dependencies/ExecutableChecker.ts` (~150 lines) -**Extract:** -- Executable checking utilities -- Version detection -- Path validation - -**STOP** → Verify build → Test executable detection - -### Step 6.2: Update DependencyChecker.ts -**Final size:** ~170 lines -**Keep:** -- Main dependency checking logic -- Status reporting -- Error handling - -**STOP** → Test all dependency checking functionality - -**CHECKPOINT: Test all external tool detection** - -## Final Verification - -After ALL phases complete: -1. Full plugin functionality test -2. Export various note types (simple, complex, with embeds) -3. Test all settings combinations -4. Verify no regressions from original functionality -5. Performance check - ensure no significant slowdown - -## Execution Process (CRITICAL) - -For EACH file modification: -1. **Use Context7** to check Obsidian/TypeScript API documentation -2. Create new file with minimal extraction -3. Update imports in original file -4. Run `npm run build` -5. **STOP and wait for user verification of build** -6. Test specific functionality in Obsidian -7. **STOP and wait for user confirmation functionality works** -8. Only then proceed to next step - -## Success Criteria - -- All 6 large files reduced to manageable size (150-200 lines each) -- No loss of functionality -- No performance degradation -- Clean module boundaries -- Maintainable code structure -- All tests pass (build + manual verification) - -## Rollback Plan - -If any phase fails: -1. Revert changes using git -2. Analyze what went wrong -3. Adjust approach before retrying -4. Consider smaller extraction steps - ---- - -*Plan created: 2025-01-08* -*Status: Ready to execute Phase 1* \ No newline at end of file diff --git a/src/converters/PandocTypstConverter.ts b/src/converters/PandocTypstConverter.ts index 6816aee..009da21 100644 --- a/src/converters/PandocTypstConverter.ts +++ b/src/converters/PandocTypstConverter.ts @@ -10,19 +10,18 @@ import * as os from 'os'; import { mapToTypstPaperSize } from '../utils/paperSizeMapper'; import { PandocOptions, TypstSettings, ConversionResult, ProgressCallback } from './converterTypes'; import type { obsidianTypstPDFExportSettings } from '../core/settings'; +import type { obsidianTypstPDFExport } from '../../main'; import { TempDirectoryManager } from '../core/TempDirectoryManager'; import { PandocCommandBuilder } from './pandoc/PandocCommandBuilder'; import { PandocExecutor } from './pandoc/PandocExecutor'; -import { PdfEmbedProcessor } from './pdf/PdfEmbedProcessor'; export class PandocTypstConverter { private tempDir: string | null = null; private cleanupHandlers: (() => void)[] = []; - private plugin: any; // Will be properly typed when we refactor the main plugin class + private plugin: obsidianTypstPDFExport; private commandBuilder: PandocCommandBuilder; private pandocExecutor: PandocExecutor; - private pdfEmbedProcessor: PdfEmbedProcessor; /** * Create a new PandocTypstConverter instance @@ -31,14 +30,13 @@ export class PandocTypstConverter { * @param typstSettings Settings specific to Typst engine */ constructor( - plugin: any, + plugin: obsidianTypstPDFExport, private pandocOptions: PandocOptions = {}, private typstSettings: TypstSettings = {} ) { this.plugin = plugin; this.commandBuilder = new PandocCommandBuilder(plugin); this.pandocExecutor = new PandocExecutor(plugin); - this.pdfEmbedProcessor = new PdfEmbedProcessor(plugin); // Set up cleanup handlers for process termination this.setupCleanup(); } diff --git a/src/converters/PdfToImageConverter.ts b/src/converters/PdfToImageConverter.ts index 9f234cc..93c974a 100644 --- a/src/converters/PdfToImageConverter.ts +++ b/src/converters/PdfToImageConverter.ts @@ -9,6 +9,7 @@ import { PdfProcessor } from './pdf/PdfProcessor'; import { ImageOptimizer } from './pdf/ImageOptimizer'; import { PdfCliExecutor } from './pdf/PdfCliExecutor'; import { FileDiscovery } from './pdf/FileDiscovery'; +import type { obsidianTypstPDFExport } from '../../main'; export interface PdfConversionOptions { /** Quality/scale factor for the rendered image (default: 2.0 for HiDPI) */ @@ -44,14 +45,14 @@ export interface PdfConversionResult { export class PdfToImageConverter { private static instance: PdfToImageConverter; - private plugin: any; // Plugin instance for accessing settings + private plugin: obsidianTypstPDFExport | undefined; - private constructor(plugin?: any) { + private constructor(plugin?: obsidianTypstPDFExport) { this.plugin = plugin; } - public static getInstance(plugin?: any): PdfToImageConverter { + public static getInstance(plugin?: obsidianTypstPDFExport): PdfToImageConverter { if (!PdfToImageConverter.instance) { PdfToImageConverter.instance = new PdfToImageConverter(plugin); } else if (plugin && !PdfToImageConverter.instance.plugin) { @@ -162,13 +163,14 @@ export class PdfToImageConverter { success: true }; - } catch (error: any) { + } catch (error: unknown) { + const errorMessage = error instanceof Error ? error.message : String(error); return { imagePath: '', originalDimensions: { width: 0, height: 0 }, imageDimensions: { width: 0, height: 0 }, success: false, - error: `PDF conversion failed: ${error.message}` + error: `PDF conversion failed: ${errorMessage}` }; } } diff --git a/src/converters/pandoc/PandocCommandBuilder.ts b/src/converters/pandoc/PandocCommandBuilder.ts index 99f51b5..b404fd4 100644 --- a/src/converters/pandoc/PandocCommandBuilder.ts +++ b/src/converters/pandoc/PandocCommandBuilder.ts @@ -8,14 +8,15 @@ import { PandocOptions } from '../converterTypes'; import { TypstVariableMapper } from './TypstVariableMapper'; import { ResourcePathResolver } from './ResourcePathResolver'; import { PathResolver } from '../../plugin/PathResolver'; +import type { obsidianTypstPDFExport } from '../../../main'; export class PandocCommandBuilder { - private plugin: any; + private plugin: obsidianTypstPDFExport; private variableMapper: TypstVariableMapper; private resourcePathResolver: ResourcePathResolver; private pathResolver: PathResolver; - constructor(plugin: any) { + constructor(plugin: obsidianTypstPDFExport) { this.plugin = plugin; this.variableMapper = new TypstVariableMapper(plugin); this.resourcePathResolver = new ResourcePathResolver(); diff --git a/src/converters/pandoc/PandocExecutor.ts b/src/converters/pandoc/PandocExecutor.ts index 8a699e2..c31ec0b 100644 --- a/src/converters/pandoc/PandocExecutor.ts +++ b/src/converters/pandoc/PandocExecutor.ts @@ -1,6 +1,7 @@ import { spawn, ChildProcess } from 'child_process'; import { ConversionResult, ProgressCallback, PandocOptions } from '../converterTypes'; import { PathResolver } from '../../plugin/PathResolver'; +import type { obsidianTypstPDFExport } from '../../../main'; /** * Handles pandoc process execution, monitoring, and error parsing. @@ -9,7 +10,7 @@ import { PathResolver } from '../../plugin/PathResolver'; export class PandocExecutor { private pathResolver: PathResolver; - constructor(plugin: any) { + constructor(plugin: obsidianTypstPDFExport) { this.pathResolver = new PathResolver(plugin); } diff --git a/src/converters/pandoc/ResourcePathResolver.ts b/src/converters/pandoc/ResourcePathResolver.ts index d2126a8..b5c1898 100644 --- a/src/converters/pandoc/ResourcePathResolver.ts +++ b/src/converters/pandoc/ResourcePathResolver.ts @@ -83,7 +83,7 @@ export class ResourcePathResolver { * @param now Current timestamp * @returns Array of resource paths found during scan */ - private async scanForResourcePaths(vaultBasePath: string, fs: any, now: number): Promise { + private async scanForResourcePaths(vaultBasePath: string, fs: typeof import('fs'), now: number): Promise { const foundResourcePaths: string[] = []; try { diff --git a/src/converters/pandoc/TypstVariableMapper.ts b/src/converters/pandoc/TypstVariableMapper.ts index 453b834..12f995c 100644 --- a/src/converters/pandoc/TypstVariableMapper.ts +++ b/src/converters/pandoc/TypstVariableMapper.ts @@ -6,6 +6,7 @@ import { mapToTypstPaperSize } from '../../utils/paperSizeMapper'; import { PandocOptions } from '../converterTypes'; import type { obsidianTypstPDFExportSettings } from '../../core/settings'; +import type { obsidianTypstPDFExport } from '../../../main'; export interface TypstVariable { name: string; @@ -13,9 +14,9 @@ export interface TypstVariable { } export class TypstVariableMapper { - private plugin: any; + private plugin: obsidianTypstPDFExport; - constructor(plugin: any) { + constructor(plugin: obsidianTypstPDFExport) { this.plugin = plugin; } @@ -225,7 +226,7 @@ export class TypstVariableMapper { /** * Map margin settings to Typst variables */ - private mapMarginVariables(margins: any, existingVars: Record): TypstVariable[] { + private mapMarginVariables(margins: {top: number; right: number; bottom: number; left: number;}, existingVars: Record): TypstVariable[] { const variables: TypstVariable[] = []; if (!existingVars.marginTop && !existingVars.margin_top && margins.top !== undefined) { diff --git a/src/converters/pdf/BinaryLocator.ts b/src/converters/pdf/BinaryLocator.ts index 78caec3..261b93e 100644 --- a/src/converters/pdf/BinaryLocator.ts +++ b/src/converters/pdf/BinaryLocator.ts @@ -4,6 +4,7 @@ */ import * as path from 'path'; +import type { obsidianTypstPDFExport } from '../../../main'; export interface BinaryLocation { /** Full path to the binary */ @@ -21,7 +22,7 @@ export class BinaryLocator { * @param plugin The plugin instance for accessing manifest and settings * @returns Binary location info */ - public static async findPdf2ImgBinary(plugin?: any): Promise { + public static async findPdf2ImgBinary(plugin?: obsidianTypstPDFExport): Promise { try { // Get the plugin directory - need to handle Obsidian's environment // In Obsidian, __dirname points to electron.asar, so we need to find the actual plugin path @@ -60,11 +61,12 @@ export class BinaryLocator { exists: true }; - } catch (error: any) { + } catch (error: unknown) { + const errorMessage = error instanceof Error ? error.message : String(error); return { binaryPath: '', exists: false, - error: `Failed to locate pdf2img binary: ${error.message}` + error: `Failed to locate pdf2img binary: ${errorMessage}` }; } } @@ -76,7 +78,7 @@ export class BinaryLocator { * @param configDir Obsidian config directory (.obsidian) * @returns Array of possible plugin directory paths */ - private static getPossiblePluginDirs(plugin: any, pluginDirName: string, configDir: string): string[] { + private static getPossiblePluginDirs(plugin: obsidianTypstPDFExport | undefined, pluginDirName: string, configDir: string): string[] { return [ // Strategy 1: From process.cwd() if it's in the vault path.join(process.cwd(), configDir, 'plugins', pluginDirName), diff --git a/src/converters/pdf/EnvironmentUtils.ts b/src/converters/pdf/EnvironmentUtils.ts index d5e8bba..84147bc 100644 --- a/src/converters/pdf/EnvironmentUtils.ts +++ b/src/converters/pdf/EnvironmentUtils.ts @@ -3,6 +3,8 @@ * Handles PATH augmentation and environment variable setup for external tools. */ +import type { obsidianTypstPDFExportSettings } from '../../core/settings'; + export interface EnvironmentSetupOptions { /** Additional paths to include in PATH */ additionalPaths?: string[]; @@ -19,28 +21,45 @@ export class EnvironmentUtils { * @returns Augmented environment with extended PATH */ public static getAugmentedEnvironment( - settings?: any, + settings?: obsidianTypstPDFExportSettings, options: EnvironmentSetupOptions = {} ): NodeJS.ProcessEnv { - // Set environment variables to ensure node can be found - // Use configured additional paths or fall back to defaults - const additionalPaths = options.additionalPaths || - settings?.executablePaths?.additionalPaths || - ['/opt/homebrew/bin', '/usr/local/bin', '/usr/bin']; + // Common tool paths where CLI tools might be installed + const commonToolPaths = [ + '/opt/homebrew/bin', // Homebrew on Apple Silicon + '/usr/local/bin', // Homebrew on Intel Mac, standard Unix tools + '/usr/bin', // System binaries + '/bin', // Core system binaries + '/usr/local/texlive/bin', // TeX Live installation + '/Library/TeX/texbin', // MacTeX installation + ...(options.additionalPaths || []) + ]; + + // Get base environment + const baseEnv = options.baseEnvironment || process.env; - // Ensure Node.js paths are included for pdf2img execution - const nodePaths = this.getNodePaths(); - - const env = { - ...(options.baseEnvironment || process.env), - PATH: this.mergePathVariables([ - process.env.PATH, - ...nodePaths, - ...additionalPaths - ]) + // Build augmented PATH + const existingPath = baseEnv.PATH || ''; + const augmentedPath = [ + ...commonToolPaths, + existingPath + ].filter(Boolean).join(':'); + + // Create augmented environment + const augmentedEnv = { + ...baseEnv, + PATH: augmentedPath, + // Ensure locale is set for proper tool operation + LC_ALL: baseEnv.LC_ALL || 'en_US.UTF-8', + LANG: baseEnv.LANG || 'en_US.UTF-8' }; - return env; + // Add any custom environment variables from settings if available + if (settings?.customEnvironmentVariables) { + Object.assign(augmentedEnv, settings.customEnvironmentVariables); + } + + return augmentedEnv; } /** @@ -73,13 +92,14 @@ export class EnvironmentUtils { * @param timeout Command timeout in milliseconds * @returns Environment configuration object */ - public static createCliEnvironment(settings?: any, timeout?: number) { + public static createCliEnvironment(settings?: obsidianTypstPDFExportSettings, timeout?: number) { const env = this.getAugmentedEnvironment(settings); return { env, - timeout: timeout || 30000, // 30 second default timeout - stdio: ['pipe', 'pipe', 'pipe'] as const + timeout: timeout || 60000, // Default 60 second timeout + stdio: ['pipe', 'pipe', 'pipe'] as const, + shell: false // Use direct process spawning for better control }; } } \ No newline at end of file diff --git a/src/converters/pdf/FileDiscovery.ts b/src/converters/pdf/FileDiscovery.ts index 36a055e..c8a070a 100644 --- a/src/converters/pdf/FileDiscovery.ts +++ b/src/converters/pdf/FileDiscovery.ts @@ -97,12 +97,13 @@ export class FileDiscovery { }; } - } catch (listError: any) { + } catch (listError: unknown) { console.error(`Failed to list output directory:`, listError); + const errorMessage = listError instanceof Error ? listError.message : String(listError); return { filePath: '', found: false, - error: `Failed to search output directory: ${listError.message}` + error: `Failed to search output directory: ${errorMessage}` }; } } diff --git a/src/converters/pdf/ImageOptimizer.ts b/src/converters/pdf/ImageOptimizer.ts index 237923c..9d68f48 100644 --- a/src/converters/pdf/ImageOptimizer.ts +++ b/src/converters/pdf/ImageOptimizer.ts @@ -89,10 +89,11 @@ export class ImageOptimizer { }); return { success: true }; - } catch (error: any) { + } catch (error: unknown) { + const errorMessage = error instanceof Error ? error.message : String(error); return { success: false, - error: `JPEG conversion failed: ${error.message}` + error: `JPEG conversion failed: ${errorMessage}` }; } } @@ -163,12 +164,13 @@ export class ImageOptimizer { error: 'Could not parse dimensions from ImageMagick output' }; } - } catch (error: any) { + } catch (error: unknown) { + const errorMessage = error instanceof Error ? error.message : String(error); console.warn('ImageMagick not available for image metadata, using fallback dimensions'); return { dimensions: fallbackDimensions, success: false, - error: `Failed to get image dimensions: ${error.message}` + error: `Failed to get image dimensions: ${errorMessage}` }; } } @@ -234,12 +236,13 @@ export class ImageOptimizer { success: true }; - } catch (error: any) { + } catch (error: unknown) { + const errorMessage = error instanceof Error ? error.message : String(error); return { imagePath: '', dimensions: { width: 0, height: 0 }, success: false, - error: `Image optimization failed: ${error.message}` + error: `Image optimization failed: ${errorMessage}` }; } } diff --git a/src/converters/pdf/PdfCliExecutor.ts b/src/converters/pdf/PdfCliExecutor.ts index b442ec0..92ac242 100644 --- a/src/converters/pdf/PdfCliExecutor.ts +++ b/src/converters/pdf/PdfCliExecutor.ts @@ -6,6 +6,7 @@ import * as path from 'path'; import { BinaryLocator } from './BinaryLocator'; import { EnvironmentUtils } from './EnvironmentUtils'; +import type { obsidianTypstPDFExport } from '../../../main'; export interface PdfCliOptions { /** Scale factor for the rendered image */ @@ -38,7 +39,7 @@ export class PdfCliExecutor { public static async executePdf2Img( pdfPath: string, options: PdfCliOptions, - plugin?: any + plugin?: obsidianTypstPDFExport ): Promise { try { // Find the pdf2img binary @@ -66,10 +67,11 @@ export class PdfCliExecutor { // Execute the command return await this.executeCommand(cliCommand, plugin); - } catch (error: any) { + } catch (error: unknown) { + const errorMessage = error instanceof Error ? error.message : String(error); return { success: false, - error: `PDF CLI execution failed: ${error.message}` + error: `PDF CLI execution failed: ${errorMessage}` }; } } @@ -106,7 +108,7 @@ export class PdfCliExecutor { */ private static async executeCommand( command: string, - plugin?: any + plugin?: obsidianTypstPDFExport ): Promise { try { const { exec } = require('child_process'); @@ -129,12 +131,13 @@ export class PdfCliExecutor { stderr: result.stderr }; - } catch (cliError: any) { - console.error(`PDF conversion error: ${cliError.message}`); + } catch (cliError: unknown) { + const errorMessage = cliError instanceof Error ? cliError.message : String(cliError); + console.error(`PDF conversion error: ${errorMessage}`); return { success: false, - error: `PDF CLI conversion failed: ${cliError.message}`, - stderr: cliError.stderr + error: `PDF CLI conversion failed: ${errorMessage}`, + stderr: (cliError as any)?.stderr || '' }; } } @@ -144,7 +147,7 @@ export class PdfCliExecutor { * @param plugin Plugin instance for accessing settings * @returns Validation result */ - public static async validatePdf2ImgAvailable(plugin?: any): Promise<{ + public static async validatePdf2ImgAvailable(plugin?: obsidianTypstPDFExport): Promise<{ available: boolean; error?: string; }> { @@ -154,10 +157,11 @@ export class PdfCliExecutor { available: binaryLocation.exists, error: binaryLocation.error }; - } catch (error: any) { + } catch (error: unknown) { + const errorMessage = error instanceof Error ? error.message : String(error); return { available: false, - error: `Failed to validate pdf2img: ${error.message}` + error: `Failed to validate pdf2img: ${errorMessage}` }; } } diff --git a/src/converters/pdf/PdfEmbedProcessor.ts b/src/converters/pdf/PdfEmbedProcessor.ts deleted file mode 100644 index e9442e8..0000000 --- a/src/converters/pdf/PdfEmbedProcessor.ts +++ /dev/null @@ -1,102 +0,0 @@ -import * as path from 'path'; - -/** - * Processes PDF embeds during document conversion. - * Converts PDF files to images for display in the final PDF output. - */ -export class PdfEmbedProcessor { - private plugin: any; - - constructor(plugin: any) { - this.plugin = plugin; - } - - /** - * Process PDF embeds by converting them to images and creating combined output - * @param processedResult The processed markdown content with metadata - * @param vaultBasePath Base path of the vault for resolving relative paths - * @param tempDir Temporary directory for conversion files - * @param embedPdfFiles Whether to include PDF download links alongside images - */ - async processPdfEmbeds( - processedResult: any, - vaultBasePath: string, - tempDir: string, - embedPdfFiles: boolean = true - ): Promise { - const { PdfToImageConverter } = require('../PdfToImageConverter'); - const converter = PdfToImageConverter.getInstance(this.plugin); - - for (const pdfEmbed of processedResult.metadata.pdfEmbeds) { - try { - - // Resolve full path to the PDF - const fullPdfPath = path.resolve(vaultBasePath, pdfEmbed.sanitizedPath); - - // Check if PDF file exists - const fs = require('fs'); - if (!fs.existsSync(fullPdfPath)) { - console.warn(`Export: PDF file not found: ${fullPdfPath}`); - // Replace marker with error message - processedResult.content = processedResult.content.replace( - pdfEmbed.marker, - `[⚠️ PDF not found: ${pdfEmbed.fileName}](${pdfEmbed.sanitizedPath})` - ); - continue; - } - - // Convert PDF to image (always happens regardless of embedPdfFiles setting) - const conversionResult = await converter.convertFirstPageToImage( - fullPdfPath, - tempDir, - { - scale: 1.5, - maxWidth: 600, - maxHeight: 400, - format: 'png' - } - ); - - if (conversionResult.success) { - // Get relative path for the generated image - const relativeImagePath = path.relative(vaultBasePath, conversionResult.imagePath); - - // Create output based on embedPdfFiles setting - let combinedOutput: string; - if (embedPdfFiles) { - // Include both image preview and PDF attachment note - combinedOutput = [ - `![${pdfEmbed.fileName} - Page 1](${relativeImagePath})`, - `[📎 **Download PDF:** ${pdfEmbed.fileName}](${pdfEmbed.sanitizedPath})` - ].join('\n\n'); - } else { - // Only show image preview - combinedOutput = `![${pdfEmbed.fileName} - Page 1](${relativeImagePath})`; - } - - // Replace marker with output - processedResult.content = processedResult.content.replace(pdfEmbed.marker, combinedOutput); - - - } else { - console.error(`Export: PDF conversion failed: ${conversionResult.error}`); - - // Replace marker with fallback link - processedResult.content = processedResult.content.replace( - pdfEmbed.marker, - `[📖 ${pdfEmbed.fileName}](${pdfEmbed.sanitizedPath})\n\n*Note: PDF preview could not be generated*` - ); - } - - } catch (error: any) { - console.error(`Export: Error processing PDF embed: ${error.message}`); - - // Replace marker with error fallback - processedResult.content = processedResult.content.replace( - pdfEmbed.marker, - `[⚠️ ${pdfEmbed.fileName}](${pdfEmbed.sanitizedPath})\n\n*Error: Could not process PDF embed*` - ); - } - } - } -} \ No newline at end of file diff --git a/src/converters/pdf/PdfProcessor.ts b/src/converters/pdf/PdfProcessor.ts index d74ba18..1444896 100644 --- a/src/converters/pdf/PdfProcessor.ts +++ b/src/converters/pdf/PdfProcessor.ts @@ -60,12 +60,13 @@ export class PdfProcessor { dimensions: { width: 612, height: 792 }, // Standard letter size estimate success: true }; - } catch (error: any) { + } catch (error: unknown) { + const errorMessage = error instanceof Error ? error.message : String(error); return { pageCount: 0, dimensions: { width: 0, height: 0 }, success: false, - error: error.message + error: errorMessage }; } } @@ -82,7 +83,7 @@ export class PdfProcessor { try { await fs.access(filePath); return { success: true }; - } catch (error: any) { + } catch (error: unknown) { return { success: false, error: `PDF file not found: ${filePath}` diff --git a/src/converters/preprocessors/FrontmatterProcessor.ts b/src/converters/preprocessors/FrontmatterProcessor.ts index 3157fa8..212e6c7 100644 --- a/src/converters/preprocessors/FrontmatterProcessor.ts +++ b/src/converters/preprocessors/FrontmatterProcessor.ts @@ -49,7 +49,7 @@ export class FrontmatterProcessor { if (Array.isArray(parsed.data.tags)) { // Handle array of tags frontmatterTags = parsed.data.tags - .map((tag: any) => typeof tag === 'string' ? tag : String(tag)) + .map((tag: unknown) => typeof tag === 'string' ? tag : String(tag)) .filter((tag: string) => tag.trim() !== ''); } else if (typeof parsed.data.tags === 'string') { // Handle comma-separated string or single tag @@ -129,8 +129,9 @@ export class FrontmatterProcessor { return content; } } - } catch (error: any) { - result.warnings.push(`Failed to parse frontmatter with gray-matter: ${error.message}`); + } catch (error: unknown) { + const errorMessage = error instanceof Error ? error.message : String(error); + result.warnings.push(`Failed to parse frontmatter with gray-matter: ${errorMessage}`); // Fallback to simple regex-based parsing const frontmatterMatch = content.match(this.FRONTMATTER_PATTERN); @@ -138,7 +139,7 @@ export class FrontmatterProcessor { if (frontmatterMatch) { try { const yamlContent = frontmatterMatch[1]; - const frontmatter: Record = {}; + const frontmatter: Record = {}; const lines = yamlContent.split('\n'); for (const line of lines) { @@ -199,8 +200,9 @@ export class FrontmatterProcessor { return content.replace(this.FRONTMATTER_PATTERN, ''); } } - } catch (fallbackError: any) { - result.warnings.push(`Fallback frontmatter parsing also failed: ${fallbackError.message}`); + } catch (fallbackError: unknown) { + const fallbackErrorMessage = fallbackError instanceof Error ? fallbackError.message : String(fallbackError); + result.warnings.push(`Fallback frontmatter parsing also failed: ${fallbackErrorMessage}`); } } diff --git a/src/core/DependencyChecker.ts b/src/core/DependencyChecker.ts index a52803b..2279432 100644 --- a/src/core/DependencyChecker.ts +++ b/src/core/DependencyChecker.ts @@ -2,7 +2,6 @@ * Dependency checking utilities for Obsidian Typst PDF Export plugin */ -import { Notice } from 'obsidian'; import { DEPENDENCY_CONSTANTS } from './constants'; import { ExportErrorHandler } from './ExportErrorHandler'; import { ExecutableChecker, DependencyInfo } from './ExecutableChecker'; @@ -32,16 +31,12 @@ export class DependencyChecker { imagemagickPath?: string, additionalPaths: string[] = [] ): Promise { - console.log(`[DependencyChecker] checkAllDependencies called with:`, { pandocPath, typstPath, imagemagickPath, additionalPaths }); - // Resolve actual executable paths, handling empty settings const [pandocExec, typstExec, imagemagickExec] = await Promise.all([ ExecutableChecker.resolveExecutablePath(pandocPath, DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.pandoc, additionalPaths), ExecutableChecker.resolveExecutablePath(typstPath, DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.typst, additionalPaths), ExecutableChecker.resolveExecutablePath(imagemagickPath, DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.imagemagick, additionalPaths) ]); - - console.log(`[DependencyChecker] Resolved paths:`, { pandocExec, typstExec, imagemagickExec }); const [pandocInfo, typstInfo, imagemagickInfo] = await Promise.all([ ExecutableChecker.checkDependency('Pandoc', pandocExec, '--version', /pandoc\s+([\d.]+)/), @@ -71,14 +66,10 @@ export class DependencyChecker { imagemagickPath?: string, additionalPaths: string[] = [] ): string[] { - console.log(`[DependencyChecker] checkDependenciesSync called with:`, { pandocPath, typstPath, imagemagickPath, additionalPaths }); - // Resolve actual executable paths, handling empty settings const pandocExec = ExecutableChecker.resolveExecutablePathSync(pandocPath, DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.pandoc, additionalPaths); const typstExec = ExecutableChecker.resolveExecutablePathSync(typstPath, DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.typst, additionalPaths); const imagemagickExec = ExecutableChecker.resolveExecutablePathSync(imagemagickPath, DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.imagemagick, additionalPaths); - - console.log(`[DependencyChecker] Resolved paths SYNC:`, { pandocExec, typstExec, imagemagickExec }); const missingDeps: string[] = []; @@ -122,7 +113,7 @@ ${dependencyResult.allAvailable ? 'All dependencies found!' : `Missing dependencies: ${dependencyResult.missingDependencies.join(', ')}. Please install them and check the paths in settings.`}`; - new Notice(message, 12000); // Show for 12 seconds (longer due to more content) + ExportErrorHandler.showProgressNotice(message, 12000); // Show for 12 seconds (longer due to more content) } /** @@ -145,7 +136,7 @@ ${dependencyResult.allAvailable // Only show notice if dependencies are missing if (missingDeps.length > 0) { - new Notice( + ExportErrorHandler.showProgressNotice( `Typst PDF Export: Missing dependencies: ${missingDeps.join(', ')}. ` + `Run "Check Dependencies" command for details.`, 8000 diff --git a/src/core/ExecutableChecker.ts b/src/core/ExecutableChecker.ts index 5545ac1..658f9af 100644 --- a/src/core/ExecutableChecker.ts +++ b/src/core/ExecutableChecker.ts @@ -48,13 +48,11 @@ export class ExecutableChecker { * Try to find an executable using which command */ private static async findExecutableWithWhich(executableName: string, additionalPaths: string[] = []): Promise { - console.log(`[ExecutableChecker] findExecutableWithWhich: searching for "${executableName}"`); const { spawn } = require('child_process'); try { const stdout = await new Promise((resolve, reject) => { const env = this.getAugmentedEnv(additionalPaths); - console.log(`[ExecutableChecker] findExecutableWithWhich: using PATH="${env.PATH}"`); const whichProcess = spawn('which', [executableName], { stdio: ['pipe', 'pipe', 'pipe'], @@ -73,7 +71,6 @@ export class ExecutableChecker { }); whichProcess.on('close', (code: number | null) => { - console.log(`[ExecutableChecker] which ${executableName} exited with code ${code}, stdout: "${output.trim()}", stderr: "${error.trim()}"`); if (code === 0) { resolve(output); } else { @@ -82,16 +79,13 @@ export class ExecutableChecker { }); whichProcess.on('error', (err: Error) => { - console.log(`[ExecutableChecker] which ${executableName} spawn error:`, err.message); reject(new Error(`Failed to spawn which process: ${err.message}`)); }); }); const foundPath = stdout.trim(); - console.log(`[ExecutableChecker] findExecutableWithWhich result: "${foundPath}"`); return foundPath || null; } catch (error) { - console.log(`[ExecutableChecker] findExecutableWithWhich caught error:`, error.message); return null; } } @@ -100,27 +94,21 @@ export class ExecutableChecker { * Resolve executable path - async version */ public static async resolveExecutablePath(userPath: string | undefined, defaultName: string, additionalPaths: string[] = []): Promise { - console.log(`[ExecutableChecker] ASYNC Resolving path for ${defaultName}: userPath="${userPath}"`); - // If user provided a full path (contains /), use it as-is if (userPath && userPath.trim() !== '' && userPath.includes('/')) { - console.log(`[ExecutableChecker] ASYNC Using user-provided full path: ${userPath}`); return userPath; } // If user provided just an executable name or empty path, resolve it const searchName = (userPath && userPath.trim() !== '') ? userPath.trim() : defaultName; - console.log(`[ExecutableChecker] ASYNC Searching for: ${searchName}`); // Try to find the executable using which command const foundPath = await this.findExecutableWithWhich(searchName, additionalPaths); if (foundPath) { - console.log(`[ExecutableChecker] ASYNC Found via which: ${foundPath}`); return foundPath; } // Fall back to the search name (will be found via PATH if available) - console.log(`[ExecutableChecker] ASYNC Falling back to search name: ${searchName}`); return searchName; } @@ -128,17 +116,13 @@ export class ExecutableChecker { * Resolve executable path - sync version */ public static resolveExecutablePathSync(userPath: string | undefined, defaultName: string, additionalPaths: string[] = []): string { - console.log(`[ExecutableChecker] SYNC Resolving path for ${defaultName}: userPath="${userPath}"`); - // If user provided a full path (contains /), use it as-is if (userPath && userPath.trim() !== '' && userPath.includes('/')) { - console.log(`[ExecutableChecker] SYNC Using user-provided full path: ${userPath}`); return userPath; } // If user provided just an executable name or empty path, resolve it const searchName = (userPath && userPath.trim() !== '') ? userPath.trim() : defaultName; - console.log(`[ExecutableChecker] SYNC Searching for: ${searchName}`); // Try to find the executable using which command synchronously const { spawnSync } = require('child_process'); @@ -151,7 +135,6 @@ export class ExecutableChecker { if (result.status === 0 && result.stdout) { const foundPath = result.stdout.trim(); if (foundPath) { - console.log(`[ExecutableChecker] SYNC Found via which: ${foundPath}`); return foundPath; } } @@ -160,7 +143,6 @@ export class ExecutableChecker { } // Fall back to the search name (will be found via PATH if available) - console.log(`[ExecutableChecker] SYNC Falling back to search name: ${searchName}`); return searchName; } diff --git a/src/core/ExportErrorHandler.ts b/src/core/ExportErrorHandler.ts index 9dd08f5..7e2357c 100644 --- a/src/core/ExportErrorHandler.ts +++ b/src/core/ExportErrorHandler.ts @@ -168,4 +168,59 @@ export class ExportErrorHandler { public static showCancellationNotice(): void { new Notice('Export cancelled'); } + + /** + * Show settings validation error + */ + public static showValidationError(field: string, validationMessage: string): void { + new Notice(`Invalid ${field}: ${validationMessage}`); + } + + /** + * Show template loading error + */ + public static showTemplateError(error: Error | string): void { + const errorMessage = error instanceof Error ? error.message : String(error); + new Notice(`Failed to load available templates: ${errorMessage}`); + } + + /** + * Show font caching error + */ + public static showFontError(error: Error | string, showFallback: boolean = true): void { + const errorMessage = error instanceof Error ? error.message : String(error); + new Notice(`Font caching failed: ${errorMessage}. Using fallback fonts.`, 5000); + + if (showFallback) { + new Notice('Font list may be incomplete. Check debug mode for details.', 3000); + } + } + + /** + * Show export success notice + */ + public static showExportSuccess(outputPath: string): void { + new Notice(`PDF exported successfully to ${outputPath}`); + } + + /** + * Show file not found warning + */ + public static showFileNotFoundWarning(context: string): void { + new Notice(`Please open a ${context} file to export`); + } + + /** + * Show no files warning + */ + public static showNoFilesWarning(context: string = 'files'): void { + new Notice(`No ${context} to export`); + } + + /** + * Show settings reset confirmation + */ + public static showSettingsReset(): void { + new Notice('Settings reset to defaults'); + } } \ No newline at end of file diff --git a/src/plugin/EmbedProcessor.ts b/src/plugin/EmbedProcessor.ts index cbb779a..00cc13b 100644 --- a/src/plugin/EmbedProcessor.ts +++ b/src/plugin/EmbedProcessor.ts @@ -5,6 +5,7 @@ import { TFile } from 'obsidian'; import type { obsidianTypstPDFExport } from '../../main'; +import type { PreprocessingResult } from '../converters/MarkdownPreprocessor'; import { ExportErrorHandler } from '../core/ExportErrorHandler'; import * as path from 'path'; import * as fs from 'fs'; @@ -15,7 +16,7 @@ export class EmbedProcessor { /** * Process PDF embeds - convert PDF pages to images for inclusion */ - async processPdfEmbeds(processedResult: any, vaultBasePath: string, tempDir: string, currentFile?: TFile, embedPdfFiles: boolean = true): Promise { + async processPdfEmbeds(processedResult: PreprocessingResult, vaultBasePath: string, tempDir: string, currentFile?: TFile, embedPdfFiles: boolean = true): Promise { const { PdfToImageConverter } = await import('../converters/PdfToImageConverter'); const converter = PdfToImageConverter.getInstance(this.plugin); @@ -102,7 +103,7 @@ export class EmbedProcessor { /** * Process image embeds - ensure images are accessible for Typst */ - async processImageEmbeds(processedResult: any, vaultBasePath: string, tempDir: string, currentFile?: TFile): Promise { + async processImageEmbeds(processedResult: PreprocessingResult, vaultBasePath: string, tempDir: string, currentFile?: TFile): Promise { let updatedContent = processedResult.content; for (const imageEmbed of processedResult.metadata.imageEmbeds) { @@ -154,8 +155,6 @@ export class EmbedProcessor { 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); @@ -175,7 +174,6 @@ export class EmbedProcessor { // 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}`); @@ -231,7 +229,7 @@ export class EmbedProcessor { /** * Process file embeds - Convert to attachments using Typst's pdf.embed */ - async processFileEmbeds(processedResult: any, vaultBasePath: string, tempDir: string, currentFile?: TFile, embedAllFiles: boolean = true): Promise { + async processFileEmbeds(processedResult: PreprocessingResult, vaultBasePath: string, tempDir: string, currentFile?: TFile, embedAllFiles: boolean = true): Promise { let updatedContent = processedResult.content; for (const fileEmbed of processedResult.metadata.fileEmbeds) { diff --git a/src/plugin/EventHandlers.ts b/src/plugin/EventHandlers.ts index 2caf772..ea54ec3 100644 --- a/src/plugin/EventHandlers.ts +++ b/src/plugin/EventHandlers.ts @@ -3,8 +3,9 @@ * Handles registration of all plugin event handlers and menu items */ -import { Menu, Editor, MarkdownView, TFile, TAbstractFile, Notice } from 'obsidian'; +import { Menu, Editor, MarkdownView, TFile, TAbstractFile } from 'obsidian'; import type { obsidianTypstPDFExport } from '../../main'; +import { ExportErrorHandler } from '../core/ExportErrorHandler'; export class EventHandlers { constructor(private plugin: obsidianTypstPDFExport) {} @@ -79,7 +80,7 @@ export class EventHandlers { const activeView = this.plugin.app.workspace.getActiveViewOfType(MarkdownView); if (!activeView || !activeView.file) { - new Notice('Please open a markdown file to export'); + ExportErrorHandler.showFileNotFoundWarning('markdown'); return; } diff --git a/src/plugin/ExportOrchestrator.ts b/src/plugin/ExportOrchestrator.ts index 109851e..200c76f 100644 --- a/src/plugin/ExportOrchestrator.ts +++ b/src/plugin/ExportOrchestrator.ts @@ -63,7 +63,7 @@ export class ExportOrchestrator { async showExportModal(view: MarkdownView): Promise { const file = view.file; if (!file) { - new Notice('No active file to export'); + ExportErrorHandler.showFileNotFoundWarning('markdown'); return; } @@ -98,7 +98,7 @@ export class ExportOrchestrator { */ async showExportModalForFiles(files: TFile[]): Promise { if (files.length === 0) { - new Notice('No files to export'); + ExportErrorHandler.showNoFilesWarning(); return; } @@ -229,14 +229,14 @@ export class ExportOrchestrator { progressNotice.hide(); if (result.success) { - new Notice(`PDF exported successfully to ${result.outputPath}`); + ExportErrorHandler.showExportSuccess(result.outputPath!); // Open PDF if configured if (this.plugin.settings.behavior.openAfterExport) { this.plugin.openPDF(result.outputPath!); } } else { - new Notice(`Export failed: ${result.error}`); + ExportErrorHandler.handleSingleExportError(result.error!); } } catch (error) { ExportErrorHandler.handleSingleExportError(error); @@ -273,7 +273,7 @@ export class ExportOrchestrator { exportFunction: (file: TFile) => Promise ): Promise { if (files.length === 0) { - new Notice('No files to export'); + ExportErrorHandler.showNoFilesWarning(); return; } diff --git a/src/plugin/FontManager.ts b/src/plugin/FontManager.ts index a710658..0038f67 100644 --- a/src/plugin/FontManager.ts +++ b/src/plugin/FontManager.ts @@ -3,8 +3,8 @@ * Handles font discovery, caching, and retrieval for the plugin */ -import { Notice } from 'obsidian'; import type { obsidianTypstPDFExport } from '../../main'; +import { ExportErrorHandler } from '../core/ExportErrorHandler'; import { FALLBACK_FONTS } from '../core/constants'; import * as path from 'path'; @@ -74,12 +74,7 @@ export class FontManager { console.error('Failed to cache fonts from typst:', error); // Notify user of font caching failure (only if debug mode is enabled or if it's a critical error) - if (this.plugin.settings.behavior.debugMode) { - new Notice(`Font caching failed: ${error.message}. Using fallback fonts.`, 5000); - } else { - // For non-debug mode, show a more gentle notice - new Notice('Font list may be incomplete. Check debug mode for details.', 3000); - } + ExportErrorHandler.showFontError(error, !this.plugin.settings.behavior.debugMode); // Create fallback cache file const fallbackFonts = FALLBACK_FONTS; diff --git a/src/plugin/PluginLifecycle.ts b/src/plugin/PluginLifecycle.ts index 18e9327..c23da61 100644 --- a/src/plugin/PluginLifecycle.ts +++ b/src/plugin/PluginLifecycle.ts @@ -3,8 +3,8 @@ * Handles plugin loading, unloading, initialization, and cleanup */ -import { Notice } from 'obsidian'; import type { obsidianTypstPDFExport } from '../../main'; +import { ExportErrorHandler } from '../core/ExportErrorHandler'; import { PandocTypstConverter } from '../converters/PandocTypstConverter'; import { TemplateManager } from '../templates/TemplateManager'; import { EmbeddedTemplateManager } from '../templates/embeddedTemplates'; @@ -31,11 +31,11 @@ export class PluginLifecycle { const extractionResult = this.plugin.embeddedTemplateManager.extractAllMissingTemplates(); if (extractionResult.failed.length > 0) { console.warn(`Failed to extract ${extractionResult.failed.length} templates:`, extractionResult.failed); - new Notice(`Warning: Failed to extract some templates. Plugin may not work correctly.`); + ExportErrorHandler.showTemplateError(`Failed to extract some templates. Plugin may not work correctly.`); } } catch (error) { console.error('Error during template extraction:', error); - new Notice(`Error extracting templates: ${error.message}`); + ExportErrorHandler.showTemplateError(error); } // Initialize components with executable paths from settings diff --git a/src/plugin/SettingsTab.ts b/src/plugin/SettingsTab.ts index 9d678e1..9208cdd 100644 --- a/src/plugin/SettingsTab.ts +++ b/src/plugin/SettingsTab.ts @@ -68,7 +68,7 @@ export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab { .setValue(this.plugin.settings.pandocPath) .onChange(async (value) => { if (!SecurityUtils.validateExecutablePath(value)) { - new Notice(`Invalid Pandoc path: ${SecurityUtils.getExecutablePathValidationError(value)}`); + ExportErrorHandler.showValidationError('Pandoc path', SecurityUtils.getExecutablePathValidationError(value)); return; } this.plugin.settings.pandocPath = value; @@ -83,7 +83,7 @@ export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab { .setValue(this.plugin.settings.typstPath) .onChange(async (value) => { if (!SecurityUtils.validateExecutablePath(value)) { - new Notice(`Invalid Typst path: ${SecurityUtils.getExecutablePathValidationError(value)}`); + ExportErrorHandler.showValidationError('Typst path', SecurityUtils.getExecutablePathValidationError(value)); return; } this.plugin.settings.typstPath = value; @@ -98,7 +98,7 @@ export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab { .setValue(this.plugin.settings.executablePaths.imagemagickPath) .onChange(async (value) => { if (!SecurityUtils.validateExecutablePath(value)) { - new Notice(`Invalid ImageMagick path: ${SecurityUtils.getExecutablePathValidationError(value)}`); + ExportErrorHandler.showValidationError('ImageMagick path', SecurityUtils.getExecutablePathValidationError(value)); return; } this.plugin.settings.executablePaths.imagemagickPath = value; @@ -120,7 +120,7 @@ export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab { // Validate each path for (const pathItem of paths) { if (!SecurityUtils.validateExecutablePath(pathItem)) { - new Notice(`Invalid system path: ${SecurityUtils.getExecutablePathValidationError(pathItem)}`); + ExportErrorHandler.showValidationError('system path', SecurityUtils.getExecutablePathValidationError(pathItem)); return; } } @@ -184,7 +184,7 @@ export class ObsidianTypstPDFExportSettingTab extends PluginSettingTab { .onChange(async (value) => { const normalizedValue = normalizePath(value); if (!SecurityUtils.validateOutputPath(normalizedValue)) { - new Notice(`Invalid output folder: ${SecurityUtils.getPathValidationError(normalizedValue)}`); + ExportErrorHandler.showValidationError('output folder', SecurityUtils.getPathValidationError(normalizedValue)); return; } this.plugin.settings.outputFolder = normalizedValue; diff --git a/src/templates/templateTypes.ts b/src/templates/templateTypes.ts index 0369df8..8fbb6de 100644 --- a/src/templates/templateTypes.ts +++ b/src/templates/templateTypes.ts @@ -3,7 +3,7 @@ */ export interface TemplateVariable { type: 'string' | 'number' | 'boolean'; - defaultValue: any; + defaultValue: string | number | boolean; description?: string; required: boolean; } diff --git a/src/ui/modal/ExportConfigModal.ts b/src/ui/modal/ExportConfigModal.ts index 7fffaa7..827cb2f 100644 --- a/src/ui/modal/ExportConfigModal.ts +++ b/src/ui/modal/ExportConfigModal.ts @@ -3,7 +3,8 @@ * Refactored modular version that uses section components */ -import { Modal, App, Notice } from 'obsidian'; +import { Modal, App } from 'obsidian'; +import { ExportErrorHandler } from '../../core/ExportErrorHandler'; import { obsidianTypstPDFExport } from '../../../main'; import { ExportConfig, ExportConfigModalSettings, ModalSection } from './modalTypes'; import { ModalState } from './state/ModalState'; @@ -101,7 +102,7 @@ export class ExportConfigModal extends Modal { } } catch (error) { console.error('Failed to load templates:', error); - new Notice(`Failed to load available templates: ${error.message}`); + ExportErrorHandler.showTemplateError(error); } } @@ -139,7 +140,7 @@ export class ExportConfigModal extends Modal { // Reload templates to update the dropdown this.loadAvailableTemplates(); - new Notice('Settings reset to defaults'); + ExportErrorHandler.showSettingsReset(); } private async handleSubmit(): Promise { diff --git a/src/ui/modal/modalTypes.ts b/src/ui/modal/modalTypes.ts index 91b8cdb..ca91578 100644 --- a/src/ui/modal/modalTypes.ts +++ b/src/ui/modal/modalTypes.ts @@ -2,8 +2,8 @@ * Type definitions for the Export Configuration Modal */ -import { TFile } from 'obsidian'; -import { ExportFormat } from '../../core/settings'; +import { TFile, App } from 'obsidian'; +import { ExportFormat, obsidianTypstPDFExportSettings } from '../../core/settings'; export interface ExportConfig { /** Override default template */ @@ -46,7 +46,7 @@ export interface ExportConfigModalSettings extends ExportConfig { } export interface ModalSection { - render(containerEl: HTMLElement, state: ModalState, app?: any): void; + render(containerEl: HTMLElement, state: ModalState, app?: App): void; validate?(): ValidationResult; getId(): string; } @@ -65,6 +65,6 @@ export interface ModalState { buildExportConfig(): ExportConfig; notifyChange(): void; setProgress(percent: number, operation: string): void; - reset(pluginDefaults: any): void; + reset(pluginDefaults: obsidianTypstPDFExportSettings): void; onChange(listener: () => void): void; } \ No newline at end of file diff --git a/src/ui/modal/sections/GeneralSection.ts b/src/ui/modal/sections/GeneralSection.ts index 3a0c63e..c252962 100644 --- a/src/ui/modal/sections/GeneralSection.ts +++ b/src/ui/modal/sections/GeneralSection.ts @@ -3,7 +3,7 @@ * Handles template selection, format options, and output settings */ -import { Setting, App, normalizePath } from 'obsidian'; +import { Setting, App, normalizePath, DropdownComponent } from 'obsidian'; import { ModalSection, ModalState, ValidationResult } from '../modalTypes'; import { ExportFormat } from '../../../core/settings'; import { FolderSuggest } from '../../components/FolderSuggest'; @@ -11,7 +11,7 @@ import { SecurityUtils } from '../../../core/SecurityUtils'; export class GeneralSection implements ModalSection { private container: HTMLElement | null = null; - private templateDropdown: any = null; + private templateDropdown: DropdownComponent | null = null; private outputFolderInput: HTMLInputElement | null = null; private app: App; diff --git a/src/ui/modal/sections/TypographySection.ts b/src/ui/modal/sections/TypographySection.ts index 6c6c287..8351d54 100644 --- a/src/ui/modal/sections/TypographySection.ts +++ b/src/ui/modal/sections/TypographySection.ts @@ -3,7 +3,7 @@ * Handles font selection and size configuration */ -import { Setting, App } from 'obsidian'; +import { Setting, App, DropdownComponent } from 'obsidian'; import { ModalSection, ModalState, ValidationResult } from '../modalTypes'; export class TypographySection implements ModalSection { @@ -161,7 +161,7 @@ export class TypographySection implements ModalSection { } } - private addFallbackBodyFonts(dropdown: any, state: ModalState, fontType: 'body' | 'heading'): void { + private addFallbackBodyFonts(dropdown: DropdownComponent, state: ModalState, fontType: 'body' | 'heading'): void { dropdown .addOption('Concourse OT', 'Concourse OT') .addOption('Times New Roman', 'Times New Roman') @@ -189,7 +189,7 @@ export class TypographySection implements ModalSection { }); } - private addFallbackMonospaceFonts(dropdown: any, state: ModalState): void { + private addFallbackMonospaceFonts(dropdown: DropdownComponent, state: ModalState): void { dropdown .addOption('Source Code Pro', 'Source Code Pro') .addOption('Courier New', 'Courier New') diff --git a/src/ui/modal/state/ModalState.ts b/src/ui/modal/state/ModalState.ts index 1f831dd..e25f267 100644 --- a/src/ui/modal/state/ModalState.ts +++ b/src/ui/modal/state/ModalState.ts @@ -4,7 +4,7 @@ */ import { ExportConfigModalSettings, ExportConfig, ModalState as IModalState } from '../modalTypes'; -import { ExportFormat } from '../../../core/settings'; +import { ExportFormat, obsidianTypstPDFExportSettings } from '../../../core/settings'; export class ModalState implements IModalState { settings: ExportConfigModalSettings; @@ -138,7 +138,7 @@ export class ModalState implements IModalState { /** * Reset state to defaults */ - reset(pluginDefaults: any): void { + reset(pluginDefaults: obsidianTypstPDFExportSettings): void { // Reset to plugin defaults, not hardcoded defaults this.settings = { ...this.settings,