refactor: complete TypeScript type safety improvements

- Replace all 'any' types with proper TypeScript types throughout codebase
- Fix processedResult parameters to use PreprocessingResult interface
- Update UI modal types: app parameter (App), pluginDefaults (obsidianTypstPDFExportSettings)
- Fix dropdown components to use DropdownComponent from Obsidian API
- Replace plugin 'any' types with obsidianTypstPDFExport throughout converters
- Fix margins parameter to use proper interface structure
- Update fs parameter to use proper Node.js fs module type
- Improve error handling with proper unknown type and type guards
- Remove unused PdfEmbedProcessor and clean up imports

Achieves complete type safety with zero remaining 'any' types across src/ directory.
Provides better IDE support, compile-time error detection, and maintainability.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Jarvis committed 2025-09-10 16:45:27 +02:00
1 parent bc689a6768
commit 2bd384fbd1
31 files changed
+204 -580

No files matched your search

+4 -6
View File
@@ -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<void> {
async processPdfEmbeds(processedResult: PreprocessingResult, vaultBasePath: string, tempDir: string, currentFile?: TFile, embedPdfFiles: boolean = true): Promise<void> {
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<void> {
async processImageEmbeds(processedResult: PreprocessingResult, vaultBasePath: string, tempDir: string, currentFile?: TFile): Promise<void> {
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<void> {
async processFileEmbeds(processedResult: PreprocessingResult, vaultBasePath: string, tempDir: string, currentFile?: TFile, embedAllFiles: boolean = true): Promise<void> {
let updatedContent = processedResult.content;
for (const fileEmbed of processedResult.metadata.fileEmbeds) {
+3 -2
View File
@@ -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;
}
+5 -5
View File
@@ -63,7 +63,7 @@ export class ExportOrchestrator {
async showExportModal(view: MarkdownView): Promise<void> {
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<void> {
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<void>
): Promise<void> {
if (files.length === 0) {
new Notice('No files to export');
ExportErrorHandler.showNoFilesWarning();
return;
}
+2 -7
View File
@@ -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;
+3 -3
View File
@@ -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
+5 -5
View File
@@ -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;