From 94dfa0da957679e1f7f522e5f476066b2730c342 Mon Sep 17 00:00:00 2001 From: Jarvis Date: Tue, 9 Sep 2025 10:06:03 +0200 Subject: [PATCH] refactor: extract EmbedProcessor from main.ts (step 1.8) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Extract all embed processing functionality into dedicated EmbedProcessor module: - Move processPdfEmbeds(), processImageEmbeds(), processFileEmbeds() methods - Move helper methods: resolvePdfPath(), copyImageToVaultTemp(), generatePdfEmbedContent(), generateFileEmbedContent(), getMimeTypeFromExtension(), getFileTypeIcon(), resolveFilePath() - Replace with delegation pattern in main.ts - Fix TypeScript type issues with proper type guards for path filtering - Reduce main.ts from 805 → 351 lines (454 lines extracted) Creates focused 474-line EmbedProcessor module handling: - PDF embed processing with preview image generation - Image embed processing with path resolution - File embed processing with MIME type detection - Multi-strategy path resolution for vault attachments - Proper error handling and fallback mechanisms Build passes successfully ✅ 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- AGENTS.md | 251 ++++++++++++++++++ main.ts | 476 +---------------------------------- plan.md | 334 ++++++++++++++++++++++++ src/plugin/EmbedProcessor.ts | 464 ++++++++++++++++++++++++++++++++++ 4 files changed, 1060 insertions(+), 465 deletions(-) create mode 100644 AGENTS.md create mode 100644 plan.md create mode 100644 src/plugin/EmbedProcessor.ts diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..3f4274a --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,251 @@ +# Obsidian community plugin + +## Project overview + +- Target: Obsidian Community Plugin (TypeScript → bundled JavaScript). +- Entry point: `main.ts` compiled to `main.js` and loaded by Obsidian. +- Required release artifacts: `main.js`, `manifest.json`, and optional `styles.css`. + +## Environment & tooling + +- Node.js: use current LTS (Node 18+ recommended). +- **Package manager: npm** (required for this sample - `package.json` defines npm scripts and dependencies). +- **Bundler: esbuild** (required for this sample - `esbuild.config.mjs` and build scripts depend on it). Alternative bundlers like Rollup or webpack are acceptable for other projects if they bundle all external dependencies into `main.js`. +- Types: `obsidian` type definitions. + +**Note**: This sample project has specific technical dependencies on npm and esbuild. If you're creating a plugin from scratch, you can choose different tools, but you'll need to replace the build configuration accordingly. + +### Install + +```bash +npm install +``` + +### Dev (watch) + +```bash +npm run dev +``` + +### Production build + +```bash +npm run build +``` + +## Linting + +- To use eslint install eslint from terminal: `npm install -g eslint` +- To use eslint to analyze this project use this command: `eslint main.ts` +- eslint will then create a report with suggestions for code improvement by file and line number. +- If your source code is in a folder, such as `src`, you can use eslint with this command to analyze all files in that folder: `eslint ./src/` + +## File & folder conventions + +- **Organize code into multiple files**: Split functionality across separate modules rather than putting everything in `main.ts`. +- Source lives in `src/`. Keep `main.ts` small and focused on plugin lifecycle (loading, unloading, registering commands). +- **Example file structure**: + ``` + src/ + main.ts # Plugin entry point, lifecycle management + settings.ts # Settings interface and defaults + commands/ # Command implementations + command1.ts + command2.ts + ui/ # UI components, modals, views + modal.ts + view.ts + utils/ # Utility functions, helpers + helpers.ts + constants.ts + types.ts # TypeScript interfaces and types + ``` +- **Do not commit build artifacts**: Never commit `node_modules/`, `main.js`, or other generated files to version control. +- Keep the plugin small. Avoid large dependencies. Prefer browser-compatible packages. +- Generated output should be placed at the plugin root or `dist/` depending on your build setup. Release artifacts must end up at the top level of the plugin folder in the vault (`main.js`, `manifest.json`, `styles.css`). + +## Manifest rules (`manifest.json`) + +- Must include (non-exhaustive): + - `id` (plugin ID; for local dev it should match the folder name) + - `name` + - `version` (Semantic Versioning `x.y.z`) + - `minAppVersion` + - `description` + - `isDesktopOnly` (boolean) + - Optional: `author`, `authorUrl`, `fundingUrl` (string or map) +- Never change `id` after release. Treat it as stable API. +- Keep `minAppVersion` accurate when using newer APIs. +- Canonical requirements are coded here: https://github.com/obsidianmd/obsidian-releases/blob/master/.github/workflows/validate-plugin-entry.yml + +## Testing + +- Manual install for testing: copy `main.js`, `manifest.json`, `styles.css` (if any) to: + ``` + /.obsidian/plugins// + ``` +- Reload Obsidian and enable the plugin in **Settings → Community plugins**. + +## Commands & settings + +- Any user-facing commands should be added via `this.addCommand(...)`. +- If the plugin has configuration, provide a settings tab and sensible defaults. +- Persist settings using `this.loadData()` / `this.saveData()`. +- Use stable command IDs; avoid renaming once released. + +## Versioning & releases + +- Bump `version` in `manifest.json` (SemVer) and update `versions.json` to map plugin version → minimum app version. +- Create a GitHub release whose tag exactly matches `manifest.json`'s `version`. Do not use a leading `v`. +- Attach `manifest.json`, `main.js`, and `styles.css` (if present) to the release as individual assets. +- After the initial release, follow the process to add/update your plugin in the community catalog as required. + +## Security, privacy, and compliance + +Follow Obsidian's **Developer Policies** and **Plugin Guidelines**. In particular: + +- Default to local/offline operation. Only make network requests when essential to the feature. +- No hidden telemetry. If you collect optional analytics or call third-party services, require explicit opt-in and document clearly in `README.md` and in settings. +- Never execute remote code, fetch and eval scripts, or auto-update plugin code outside of normal releases. +- Minimize scope: read/write only what's necessary inside the vault. Do not access files outside the vault. +- Clearly disclose any external services used, data sent, and risks. +- Respect user privacy. Do not collect vault contents, filenames, or personal information unless absolutely necessary and explicitly consented. +- Avoid deceptive patterns, ads, or spammy notifications. +- Register and clean up all DOM, app, and interval listeners using the provided `register*` helpers so the plugin unloads safely. + +## UX & copy guidelines (for UI text, commands, settings) + +- Prefer sentence case for headings, buttons, and titles. +- Use clear, action-oriented imperatives in step-by-step copy. +- Use **bold** to indicate literal UI labels. Prefer "select" for interactions. +- Use arrow notation for navigation: **Settings → Community plugins**. +- Keep in-app strings short, consistent, and free of jargon. + +## Performance + +- Keep startup light. Defer heavy work until needed. +- Avoid long-running tasks during `onload`; use lazy initialization. +- Batch disk access and avoid excessive vault scans. +- Debounce/throttle expensive operations in response to file system events. + +## Coding conventions + +- TypeScript with `"strict": true` preferred. +- **Keep `main.ts` minimal**: Focus only on plugin lifecycle (onload, onunload, addCommand calls). Delegate all feature logic to separate modules. +- **Split large files**: If any file exceeds ~200-300 lines, consider breaking it into smaller, focused modules. +- **Use clear module boundaries**: Each file should have a single, well-defined responsibility. +- Bundle everything into `main.js` (no unbundled runtime deps). +- Avoid Node/Electron APIs if you want mobile compatibility; set `isDesktopOnly` accordingly. +- Prefer `async/await` over promise chains; handle errors gracefully. + +## Mobile + +- Where feasible, test on iOS and Android. +- Don't assume desktop-only behavior unless `isDesktopOnly` is `true`. +- Avoid large in-memory structures; be mindful of memory and storage constraints. + +## Agent do/don't + +**Do** +- Add commands with stable IDs (don't rename once released). +- Provide defaults and validation in settings. +- Write idempotent code paths so reload/unload doesn't leak listeners or intervals. +- Use `this.register*` helpers for everything that needs cleanup. + +**Don't** +- Introduce network calls without an obvious user-facing reason and documentation. +- Ship features that require cloud services without clear disclosure and explicit opt-in. +- Store or transmit vault contents unless essential and consented. + +## Common tasks + +### Organize code across multiple files + +**main.ts** (minimal, lifecycle only): +```ts +import { Plugin } from "obsidian"; +import { MySettings, DEFAULT_SETTINGS } from "./settings"; +import { registerCommands } from "./commands"; + +export default class MyPlugin extends Plugin { + settings: MySettings; + + async onload() { + this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData()); + registerCommands(this); + } +} +``` + +**settings.ts**: +```ts +export interface MySettings { + enabled: boolean; + apiKey: string; +} + +export const DEFAULT_SETTINGS: MySettings = { + enabled: true, + apiKey: "", +}; +``` + +**commands/index.ts**: +```ts +import { Plugin } from "obsidian"; +import { doSomething } from "./my-command"; + +export function registerCommands(plugin: Plugin) { + plugin.addCommand({ + id: "do-something", + name: "Do something", + callback: () => doSomething(plugin), + }); +} +``` + +### Add a command + +```ts +this.addCommand({ + id: "your-command-id", + name: "Do the thing", + callback: () => this.doTheThing(), +}); +``` + +### Persist settings + +```ts +interface MySettings { enabled: boolean } +const DEFAULT_SETTINGS: MySettings = { enabled: true }; + +async onload() { + this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData()); + await this.saveData(this.settings); +} +``` + +### Register listeners safely + +```ts +this.registerEvent(this.app.workspace.on("file-open", f => { /* ... */ })); +this.registerDomEvent(window, "resize", () => { /* ... */ }); +this.registerInterval(window.setInterval(() => { /* ... */ }, 1000)); +``` + +## Troubleshooting + +- Plugin doesn't load after build: ensure `main.js` and `manifest.json` are at the top level of the plugin folder under `/.obsidian/plugins//`. +- Build issues: if `main.js` is missing, run `npm run build` or `npm run dev` to compile your TypeScript source code. +- Commands not appearing: verify `addCommand` runs after `onload` and IDs are unique. +- Settings not persisting: ensure `loadData`/`saveData` are awaited and you re-render the UI after changes. +- Mobile-only issues: confirm you're not using desktop-only APIs; check `isDesktopOnly` and adjust. + +## References + +- Obsidian sample plugin: https://github.com/obsidianmd/obsidian-sample-plugin +- API documentation: https://docs.obsidian.md +- Developer policies: https://docs.obsidian.md/Developer+policies +- Plugin guidelines: https://docs.obsidian.md/Plugins/Releasing/Plugin+guidelines +- Style guide: https://help.obsidian.md/style-guide diff --git a/main.ts b/main.ts index 2c7120e..a5bde06 100644 --- a/main.ts +++ b/main.ts @@ -42,6 +42,7 @@ import { ExportOrchestrator } from './src/plugin/ExportOrchestrator'; import { FontManager } from './src/plugin/FontManager'; import { PathResolver } from './src/plugin/PathResolver'; import { ObsidianTypstPDFExportSettingTab } from './src/plugin/SettingsTab'; +import { EmbedProcessor } from './src/plugin/EmbedProcessor'; import * as path from 'path'; import * as fs from 'fs'; @@ -57,6 +58,7 @@ export class obsidianTypstPDFExport extends Plugin { private exportOrchestrator: ExportOrchestrator; fontManager: FontManager; pathResolver: PathResolver; + embedProcessor: EmbedProcessor; // Type predicate to filter for markdown TFiles isMarkdownFile(file: TAbstractFile): file is TFile { @@ -85,6 +87,9 @@ export class obsidianTypstPDFExport extends Plugin { // Initialize export orchestrator this.exportOrchestrator = new ExportOrchestrator(this); + // Initialize embed processor + this.embedProcessor = new EmbedProcessor(this); + // Register custom icon addIcon('typst-pdf-export', ` @@ -285,483 +290,24 @@ ${dependencyResult.allAvailable } /** - * Process PDF embeds - convert PDF pages to images for inclusion + * Process PDF embeds (delegated to EmbedProcessor) */ - /** - * Resolve PDF path using multiple strategies - * @param sanitizedPath The sanitized path from the embed - * @param vaultBasePath Base path of the vault - * @param currentFile Current file being processed (optional) - * @returns Full path to PDF file if found, null otherwise - */ - private async resolvePdfPath(sanitizedPath: string, vaultBasePath: string, currentFile?: TFile): Promise { - const pathModule = require('path'); - const fs = require('fs'); - - // Decode the URL-encoded sanitized path back to normal characters - const decodedPath = decodeURIComponent(sanitizedPath); - - // Try multiple path resolution strategies - const possiblePaths = [ - // Strategy 1: Relative to vault root (standard Obsidian behavior) - pathModule.resolve(vaultBasePath, decodedPath), - // Strategy 2: Relative to current file's directory (for local attachments) - currentFile ? pathModule.resolve(vaultBasePath, pathModule.dirname(currentFile.path), decodedPath) : null - ].filter(p => p !== null); - - // Try each possible path until we find one that exists - for (const possiblePath of possiblePaths) { - try { - await fs.promises.access(possiblePath); - return possiblePath; - } catch { - // File doesn't exist, continue to next path - } - } - - return null; - } - - /** - * Generate Typst PDF embed syntax with optional preview image - * @param relativePdfPath Relative path to PDF from vault base - * @param baseName Base name of the PDF file - * @param relativeImagePath Optional relative path to preview image - * @param errorSuffix Optional error suffix for description - * @returns Formatted content for PDF embed - */ - /** - * Copy converted PDF image to vault temp directory and get relative paths - * @param imagePath Path to the converted image - * @param pdfPath Path to the original PDF - * @param baseName Base name of the PDF - * @param vaultBasePath Base path of the vault - * @returns Object with relative paths for image and PDF - */ - private async copyImageToVaultTemp( - imagePath: string, - pdfPath: string, - baseName: string, - vaultBasePath: string -): Promise<{ relativeImagePath: string; relativePdfPath: string }> { - const pathModule = require('path'); - const fs = require('fs'); - - // Copy image to vault temp directory for access - const vaultTempImagesDir = pathModule.join(vaultBasePath, this.manifest.dir!, 'temp-images'); - await fs.promises.mkdir(vaultTempImagesDir, { recursive: true }); - - // Sanitize the basename for use in filename - replace problematic characters - const sanitizedBaseName = baseName - .replace(/[^a-zA-Z0-9\-_]/g, '_') // Replace non-alphanumeric chars with underscore - .replace(/_{2,}/g, '_') // Collapse multiple underscores - .replace(/^_+|_+$/g, ''); // Remove leading/trailing underscores - - const imageFileName = `${sanitizedBaseName}_preview.png`; - const vaultImagePath = pathModule.join(vaultTempImagesDir, imageFileName); - await fs.promises.copyFile(imagePath, vaultImagePath); - - // Get relative paths from vault base - const relativeImagePath = pathModule.relative(vaultBasePath, vaultImagePath); - const relativePdfPath = pathModule.relative(vaultBasePath, pdfPath); - - return { relativeImagePath, relativePdfPath }; -} - - private generatePdfEmbedContent( - relativePdfPath: string, - baseName: string, - relativeImagePath?: string, - errorSuffix?: string, - embedPdfFiles: boolean = true - ): string { - const description = `${baseName}${errorSuffix ? ` ${errorSuffix}` : ''}`; - - const content = []; - - // Always include image preview if available - if (relativeImagePath) { - content.push(`![${baseName} - Page 1](${relativeImagePath})`); - content.push(''); - } - - // Only include PDF embedding and attachment note if embedPdfFiles is true - if (embedPdfFiles) { - content.push('```{=typst}'); - content.push(`#pdf.embed("${relativePdfPath}", description: "${description}", mime-type: "application/pdf")`); - content.push('```'); - content.push(''); - content.push(`*PDF attached: ${description} - check your PDF reader's attachment panel*`); - } - - return content.filter(line => line !== null).join('\n'); - } - - /** - * Generate file embed content with proper Typst pdf.embed syntax - */ - private generateFileEmbedContent( - relativeFilePath: string, - baseName: string, - fileExtension: string, - errorSuffix?: string - ): string { - const description = `${baseName}${errorSuffix ? ` ${errorSuffix}` : ''}`; - const mimeType = this.getMimeTypeFromExtension(fileExtension); - const fileIcon = this.getFileTypeIcon(fileExtension); - - const content = []; - - // Add file embed using Typst's pdf.embed - content.push('```{=typst}'); - content.push(`#pdf.embed("${relativeFilePath}", description: "${description}", mime-type: "${mimeType}")`); - content.push('```'); - content.push(''); - content.push(`*File attached: ${fileIcon} ${description} - check your PDF reader's attachment panel*`); - - return content.filter(line => line !== null).join('\n'); - } - - /** - * Get MIME type from file extension - */ - private getMimeTypeFromExtension(extension: string): string { - const mimeTypes: Record = { - // Office documents - '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - '.xls': 'application/vnd.ms-excel', - '.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation', - '.ppt': 'application/vnd.ms-powerpoint', - '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', - '.doc': 'application/msword', - // Open Document Format - '.odt': 'application/vnd.oasis.opendocument.text', - '.ods': 'application/vnd.oasis.opendocument.spreadsheet', - '.odp': 'application/vnd.oasis.opendocument.presentation', - // Archives - '.zip': 'application/zip', - '.rar': 'application/vnd.rar', - '.7z': 'application/x-7z-compressed', - '.tar': 'application/x-tar', - '.gz': 'application/gzip', - '.bz2': 'application/x-bzip2', - // Text/data formats - '.json': 'application/json', - '.xml': 'application/xml', - '.csv': 'text/csv', - '.yaml': 'text/yaml', - '.yml': 'text/yaml', - '.toml': 'text/plain', - '.txt': 'text/plain', - '.md': 'text/markdown', - '.rtf': 'application/rtf', - // Code files - '.js': 'text/javascript', - '.ts': 'text/typescript', - '.py': 'text/x-python', - '.java': 'text/x-java-source', - '.cpp': 'text/x-c++src', - '.c': 'text/x-csrc', - '.h': 'text/x-chdr', - '.css': 'text/css', - '.html': 'text/html', - '.php': 'text/x-php', - // Database files - '.db': 'application/x-sqlite3', - '.sqlite': 'application/x-sqlite3', - '.sql': 'application/sql', - // E-books - '.epub': 'application/epub+zip', - '.mobi': 'application/x-mobipocket-ebook', - // Other formats - '.ics': 'text/calendar', - '.vcf': 'text/vcard', - '.log': 'text/plain' - }; - - return mimeTypes[extension.toLowerCase()] || 'application/octet-stream'; - } - - /** - * Get appropriate icon for file type - */ - private getFileTypeIcon(extension: string): string { - const iconMap: Record = { - // Office documents - '.xlsx': '📊', '.xls': '📊', - '.pptx': '📽️', '.ppt': '📽️', - '.docx': '📄', '.doc': '📄', - // Open Document - '.odt': '📄', '.ods': '📊', '.odp': '📽️', - // Archives - '.zip': '📦', '.rar': '📦', '.7z': '📦', '.tar': '📦', '.gz': '📦', '.bz2': '📦', - // Text/data - '.json': '🗃️', '.xml': '🗃️', '.csv': '📊', '.yaml': '⚙️', '.yml': '⚙️', - '.toml': '⚙️', '.txt': '📄', '.md': '📝', '.rtf': '📄', - // Code files - '.js': '💻', '.ts': '💻', '.py': '🐍', '.java': '☕', '.cpp': '💻', '.c': '💻', - '.h': '💻', '.css': '🎨', '.html': '🌐', '.php': '💻', - // Database - '.db': '🗄️', '.sqlite': '🗄️', '.sql': '🗄️', - // E-books - '.epub': '📖', '.mobi': '📖', - // Other - '.ics': '📅', '.vcf': '👤', '.log': '📋' - }; - - return iconMap[extension.toLowerCase()] || '📎'; - } - - /** - * Resolve file path (similar to resolvePdfPath but for generic files) - */ - private async resolveFilePath(sanitizedPath: string, vaultBasePath: string, currentFile?: TFile): Promise { - const pathModule = require('path'); - const fs = require('fs'); - - // Decode the URL-encoded sanitized path back to normal characters - const decodedPath = decodeURIComponent(sanitizedPath); - - // Try multiple path resolution strategies - const possiblePaths = [ - // Strategy 1: Relative to vault root (standard Obsidian behavior) - pathModule.resolve(vaultBasePath, decodedPath), - // Strategy 2: Relative to current file's directory (for local attachments) - currentFile ? pathModule.resolve(vaultBasePath, pathModule.dirname(currentFile.path), decodedPath) : null, - // Strategy 3: Check in attachments folder (common pattern) - pathModule.resolve(vaultBasePath, 'attachments', pathModule.basename(decodedPath)) - ].filter(p => p !== null); - - // Try each possible path until we find one that exists - for (const possiblePath of possiblePaths) { - try { - await fs.promises.access(possiblePath); - return possiblePath; - } catch { - // File doesn't exist, continue to next path - } - } - - return null; - } - async processPdfEmbeds(processedResult: any, vaultBasePath: string, tempDir: string, currentFile?: TFile, embedPdfFiles: boolean = true): Promise { - const { PdfToImageConverter } = await import('./src/converters/PdfToImageConverter'); - const converter = PdfToImageConverter.getInstance(this); - const pathModule = require('path'); - const fs = require('fs'); - - - let updatedContent = processedResult.content; - - for (const pdfEmbed of processedResult.metadata.pdfEmbeds) { - try { - - // Resolve PDF path using helper method - const fullPdfPath = await this.resolvePdfPath(pdfEmbed.sanitizedPath, vaultBasePath, currentFile); - - if (!fullPdfPath) { - console.warn(`Export: PDF file not found: ${decodeURIComponent(pdfEmbed.sanitizedPath)}`); - // Replace marker with fallback message - const fallbackOutput = `*⚠️ PDF not found: ${pdfEmbed.baseName}*`; - updatedContent = updatedContent.replace(pdfEmbed.marker, fallbackOutput); - continue; - } - - // Convert PDF first page to image - pass options object as third parameter - const result = await converter.convertFirstPageToImage( - fullPdfPath, - tempDir, - { - scale: 1.5, - maxWidth: 800, - maxHeight: 600, - format: 'png' - } - ); - - if (result.success && result.imagePath) { - // Copy image to vault temp directory and get relative paths - const { relativeImagePath, relativePdfPath } = await this.copyImageToVaultTemp( - result.imagePath, - fullPdfPath, - pdfEmbed.baseName, - vaultBasePath - ); - - // Create combined output with image and optionally Typst pdf.embed using helper - const combinedOutput = this.generatePdfEmbedContent( - relativePdfPath, - pdfEmbed.baseName, - relativeImagePath, - undefined, - embedPdfFiles - ); - - // Replace the placeholder with the combined output - updatedContent = updatedContent.replace(pdfEmbed.marker, combinedOutput); - - } else { - console.warn(`Export: Failed to convert PDF to image: ${result.error}`); - const relativePdfPath = pathModule.relative(vaultBasePath, fullPdfPath); - // Even without preview image, still embed the PDF if requested - const fallbackOutput = this.generatePdfEmbedContent( - relativePdfPath, - pdfEmbed.baseName, - undefined, - '(preview not available)', - embedPdfFiles - ); - updatedContent = updatedContent.replace(pdfEmbed.marker, fallbackOutput); - } - } catch (error) { - ExportErrorHandler.handleProcessingError('PDF embed', pdfEmbed.originalPath, error); - // Still try to embed the PDF even if there's a processing error - const relativePdfPath = pathModule.relative(vaultBasePath, pdfEmbed.originalPath); - const fallbackOutput = this.generatePdfEmbedContent( - relativePdfPath, - pdfEmbed.baseName, - undefined, - '(error occurred)', - embedPdfFiles - ); - updatedContent = updatedContent.replace(pdfEmbed.marker, fallbackOutput); - } - } - - // Update the processed result with the new content - processedResult.content = updatedContent; + return this.embedProcessor.processPdfEmbeds(processedResult, vaultBasePath, tempDir, currentFile, embedPdfFiles); } /** - * Process image embeds - ensure images are accessible for Typst + * Process image embeds (delegated to EmbedProcessor) */ async processImageEmbeds(processedResult: any, vaultBasePath: string, tempDir: string, currentFile?: TFile): Promise { - const pathModule = require('path'); - const fs = require('fs'); - - - let updatedContent = processedResult.content; - - for (const imageEmbed of processedResult.metadata.imageEmbeds) { - try { - - // Decode the URL-encoded sanitized path back to normal characters - const decodedPath = decodeURIComponent(imageEmbed.sanitizedPath); - - // Try multiple path resolution strategies - const possiblePaths = [ - // Strategy 1: Relative to vault root (standard Obsidian behavior) - pathModule.resolve(vaultBasePath, decodedPath), - // Strategy 2: Relative to current file's directory (for local attachments) - currentFile ? pathModule.resolve(vaultBasePath, pathModule.dirname(currentFile.path), decodedPath) : null, - // Strategy 3: Check in attachments folder (common pattern) - pathModule.resolve(vaultBasePath, 'attachments', pathModule.basename(decodedPath)) - ].filter(p => p !== null); - - let fullImagePath = null; - - // Try each possible path until we find one that exists - for (const possiblePath of possiblePaths) { - try { - await fs.promises.access(possiblePath); - fullImagePath = possiblePath; - break; - } catch { - // File doesn't exist, continue to next path - } - } - - if (!fullImagePath) { - console.warn(`Export: Image file not found: ${decodedPath}`); - // Keep the original marker or replace with placeholder - const fallbackOutput = `[⚠️ **Image not found:** ${imageEmbed.alt || imageEmbed.originalPath}]`; - updatedContent = updatedContent.replace(imageEmbed.marker, fallbackOutput); - continue; - } - - // Get relative path from vault base for the image - const relativeImagePath = pathModule.relative(vaultBasePath, fullImagePath); - - // Replace the marker with Markdown image syntax (Pandoc will convert to Typst) - const markdownImage = imageEmbed.alt ? - `![${imageEmbed.alt}](${relativeImagePath})` : - `![](${relativeImagePath})`; - - updatedContent = updatedContent.replace(imageEmbed.marker, markdownImage); - - } catch (error) { - const { fallback } = ExportErrorHandler.handleProcessingError( - 'image embed', - imageEmbed.originalPath, - error, - `[⚠️ **Image processing error:** ${imageEmbed.alt || imageEmbed.originalPath}]` - ); - updatedContent = updatedContent.replace(imageEmbed.marker, fallback); - } - } - - // Update the processed result with the new content - processedResult.content = updatedContent; + return this.embedProcessor.processImageEmbeds(processedResult, vaultBasePath, tempDir, currentFile); } /** - * Process file embeds - Convert to attachments using Typst's pdf.embed + * Process file embeds (delegated to EmbedProcessor) */ async processFileEmbeds(processedResult: any, vaultBasePath: string, tempDir: string, currentFile?: TFile, embedAllFiles: boolean = true): Promise { - const pathModule = require('path'); - const fs = require('fs'); - - let updatedContent = processedResult.content; - - for (const fileEmbed of processedResult.metadata.fileEmbeds) { - try { - - // Resolve file path using helper method (similar to PDF processing) - const fullFilePath = await this.resolveFilePath(fileEmbed.sanitizedPath, vaultBasePath, currentFile); - - if (!fullFilePath) { - console.warn(`Export: File not found: ${decodeURIComponent(fileEmbed.sanitizedPath)}`); - // Replace marker with fallback message - const fallbackOutput = `*⚠️ File not found: ${fileEmbed.baseName}*`; - updatedContent = updatedContent.replace(fileEmbed.marker, fallbackOutput); - continue; - } - - if (embedAllFiles) { - // Get relative path from vault base - const relativeFilePath = pathModule.relative(vaultBasePath, fullFilePath); - - // Create file embed content using helper method - const combinedOutput = this.generateFileEmbedContent( - relativeFilePath, - fileEmbed.baseName, - fileEmbed.fileType, - undefined - ); - - // Replace the placeholder with the combined output - updatedContent = updatedContent.replace(fileEmbed.marker, combinedOutput); - } else { - // Just show as a link if embedding is disabled - const relativeFilePath = pathModule.relative(vaultBasePath, fullFilePath); - const fileIcon = this.getFileTypeIcon(fileEmbed.fileType); - const linkOutput = `[${fileIcon} ${fileEmbed.fileName}](${relativeFilePath})`; - updatedContent = updatedContent.replace(fileEmbed.marker, linkOutput); - } - - } catch (error) { - ExportErrorHandler.handleProcessingError('File embed', fileEmbed.originalPath, error); - // Still try to show as a link even if there's a processing error - const relativeFilePath = pathModule.relative(vaultBasePath, fileEmbed.originalPath); - const fileIcon = this.getFileTypeIcon(fileEmbed.fileType); - const fallbackOutput = `[${fileIcon} ${fileEmbed.fileName} (error occurred)](${relativeFilePath})`; - updatedContent = updatedContent.replace(fileEmbed.marker, fallbackOutput); - } - } - - // Update the processed result with the new content - processedResult.content = updatedContent; + return this.embedProcessor.processFileEmbeds(processedResult, vaultBasePath, tempDir, currentFile, embedAllFiles); } diff --git a/plan.md b/plan.md new file mode 100644 index 0000000..b0a9dda --- /dev/null +++ b/plan.md @@ -0,0 +1,334 @@ +# 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) + +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 - IN PROGRESS +**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 +**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** + +## PHASE 2: Refactor MarkdownPreprocessor.ts + +### Step 2.1: Create FrontmatterProcessor.ts +**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 +**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 +**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 +**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 +**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 +**Final size:** ~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 + +### Step 3.1: Create PandocCommandBuilder.ts +**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 +**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 +**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 +**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 + +### Step 4.1: Create ModalRenderer.ts +**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 +**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 +**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 + +### Step 5.1: Create PdfProcessor.ts +**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 +**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/plugin/EmbedProcessor.ts b/src/plugin/EmbedProcessor.ts new file mode 100644 index 0000000..86e13f6 --- /dev/null +++ b/src/plugin/EmbedProcessor.ts @@ -0,0 +1,464 @@ +/** + * Embed Processing + * Handles processing of PDF, image, and file embeds for PDF export + */ + +import { TFile } from 'obsidian'; +import type { obsidianTypstPDFExport } from '../../main'; +import { ExportErrorHandler } from '../core/ExportErrorHandler'; +import * as path from 'path'; +import * as fs from 'fs'; + +export class EmbedProcessor { + constructor(private plugin: obsidianTypstPDFExport) {} + + /** + * Process PDF embeds - convert PDF pages to images for inclusion + */ + async processPdfEmbeds(processedResult: any, vaultBasePath: string, tempDir: string, currentFile?: TFile, embedPdfFiles: boolean = true): Promise { + const { PdfToImageConverter } = await import('../converters/PdfToImageConverter'); + const converter = PdfToImageConverter.getInstance(this.plugin); + + let updatedContent = processedResult.content; + + for (const pdfEmbed of processedResult.metadata.pdfEmbeds) { + try { + // Resolve PDF path using helper method + const fullPdfPath = await this.resolvePdfPath(pdfEmbed.sanitizedPath, vaultBasePath, currentFile); + + if (!fullPdfPath) { + console.warn(`Export: PDF file not found: ${decodeURIComponent(pdfEmbed.sanitizedPath)}`); + // Replace marker with fallback message + const fallbackOutput = `*⚠️ PDF not found: ${pdfEmbed.baseName}*`; + updatedContent = updatedContent.replace(pdfEmbed.marker, fallbackOutput); + continue; + } + + // Convert PDF first page to image - pass options object as third parameter + const result = await converter.convertFirstPageToImage( + fullPdfPath, + tempDir, + { + scale: 1.5, + maxWidth: 800, + maxHeight: 600, + format: 'png' + } + ); + + if (result.success && result.imagePath) { + // Copy image to vault temp directory and get relative paths + const { relativeImagePath, relativePdfPath } = await this.copyImageToVaultTemp( + result.imagePath, + fullPdfPath, + pdfEmbed.baseName, + vaultBasePath + ); + + // Create combined output with image and optionally Typst pdf.embed using helper + const combinedOutput = this.generatePdfEmbedContent( + relativePdfPath, + pdfEmbed.baseName, + relativeImagePath, + undefined, + embedPdfFiles + ); + + // Replace the placeholder with the combined output + updatedContent = updatedContent.replace(pdfEmbed.marker, combinedOutput); + + } else { + console.warn(`Export: Failed to convert PDF to image: ${result.error}`); + const relativePdfPath = path.relative(vaultBasePath, fullPdfPath); + // Even without preview image, still embed the PDF if requested + const fallbackOutput = this.generatePdfEmbedContent( + relativePdfPath, + pdfEmbed.baseName, + undefined, + '(preview not available)', + embedPdfFiles + ); + updatedContent = updatedContent.replace(pdfEmbed.marker, fallbackOutput); + } + } catch (error) { + ExportErrorHandler.handleProcessingError('PDF embed', pdfEmbed.originalPath, error); + // Still try to embed the PDF even if there's a processing error + const relativePdfPath = path.relative(vaultBasePath, pdfEmbed.originalPath); + const fallbackOutput = this.generatePdfEmbedContent( + relativePdfPath, + pdfEmbed.baseName, + undefined, + '(error occurred)', + embedPdfFiles + ); + updatedContent = updatedContent.replace(pdfEmbed.marker, fallbackOutput); + } + } + + // Update the processed result with the new content + processedResult.content = updatedContent; + } + + /** + * Process image embeds - ensure images are accessible for Typst + */ + async processImageEmbeds(processedResult: any, vaultBasePath: string, tempDir: string, currentFile?: TFile): Promise { + let updatedContent = processedResult.content; + + for (const imageEmbed of processedResult.metadata.imageEmbeds) { + try { + // Decode the URL-encoded sanitized path back to normal characters + const decodedPath = decodeURIComponent(imageEmbed.sanitizedPath); + + // Try multiple path resolution strategies + const possiblePaths = [ + // Strategy 1: Relative to vault root (standard Obsidian behavior) + path.resolve(vaultBasePath, decodedPath), + // Strategy 2: Relative to current file's directory (for local attachments) + currentFile ? path.resolve(vaultBasePath, path.dirname(currentFile.path), decodedPath) : null, + // Strategy 3: Check in attachments folder (common pattern) + path.resolve(vaultBasePath, 'attachments', path.basename(decodedPath)) + ].filter((p): p is string => p !== null); + + let fullImagePath = null; + + // Try each possible path until we find one that exists + for (const possiblePath of possiblePaths) { + try { + await fs.promises.access(possiblePath); + fullImagePath = possiblePath; + break; + } catch { + // File doesn't exist, continue to next path + } + } + + if (!fullImagePath) { + console.warn(`Export: Image file not found: ${decodedPath}`); + // Keep the original marker or replace with placeholder + const fallbackOutput = `[⚠️ **Image not found:** ${imageEmbed.alt || imageEmbed.originalPath}]`; + updatedContent = updatedContent.replace(imageEmbed.marker, fallbackOutput); + continue; + } + + // Get relative path from vault base for the image + const relativeImagePath = path.relative(vaultBasePath, fullImagePath); + + // Replace the marker with Markdown image syntax (Pandoc will convert to Typst) + const markdownImage = imageEmbed.alt ? + `![${imageEmbed.alt}](${relativeImagePath})` : + `![](${relativeImagePath})`; + + updatedContent = updatedContent.replace(imageEmbed.marker, markdownImage); + + } catch (error) { + const { fallback } = ExportErrorHandler.handleProcessingError( + 'image embed', + imageEmbed.originalPath, + error, + `[⚠️ **Image processing error:** ${imageEmbed.alt || imageEmbed.originalPath}]` + ); + updatedContent = updatedContent.replace(imageEmbed.marker, fallback); + } + } + + // Update the processed result with the new content + processedResult.content = updatedContent; + } + + /** + * 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 { + let updatedContent = processedResult.content; + + for (const fileEmbed of processedResult.metadata.fileEmbeds) { + try { + // Resolve file path using helper method (similar to PDF processing) + const fullFilePath = await this.resolveFilePath(fileEmbed.sanitizedPath, vaultBasePath, currentFile); + + if (!fullFilePath) { + console.warn(`Export: File not found: ${decodeURIComponent(fileEmbed.sanitizedPath)}`); + // Replace marker with fallback message + const fallbackOutput = `*⚠️ File not found: ${fileEmbed.baseName}*`; + updatedContent = updatedContent.replace(fileEmbed.marker, fallbackOutput); + continue; + } + + if (embedAllFiles) { + // Get relative path from vault base + const relativeFilePath = path.relative(vaultBasePath, fullFilePath); + + // Create file embed content using helper method + const combinedOutput = this.generateFileEmbedContent( + relativeFilePath, + fileEmbed.baseName, + fileEmbed.fileType, + undefined + ); + + // Replace the placeholder with the combined output + updatedContent = updatedContent.replace(fileEmbed.marker, combinedOutput); + } else { + // Just show as a link if embedding is disabled + const relativeFilePath = path.relative(vaultBasePath, fullFilePath); + const fileIcon = this.getFileTypeIcon(fileEmbed.fileType); + const linkOutput = `[${fileIcon} ${fileEmbed.fileName}](${relativeFilePath})`; + updatedContent = updatedContent.replace(fileEmbed.marker, linkOutput); + } + + } catch (error) { + ExportErrorHandler.handleProcessingError('File embed', fileEmbed.originalPath, error); + // Still try to show as a link even if there's a processing error + const relativeFilePath = path.relative(vaultBasePath, fileEmbed.originalPath); + const fileIcon = this.getFileTypeIcon(fileEmbed.fileType); + const fallbackOutput = `[${fileIcon} ${fileEmbed.fileName} (error occurred)](${relativeFilePath})`; + updatedContent = updatedContent.replace(fileEmbed.marker, fallbackOutput); + } + } + + // Update the processed result with the new content + processedResult.content = updatedContent; + } + + /** + * Resolve PDF path using multiple strategies + * @param sanitizedPath The sanitized path from the embed + * @param vaultBasePath Base path of the vault + * @param currentFile Current file being processed (optional) + * @returns Full path to PDF file if found, null otherwise + */ + private async resolvePdfPath(sanitizedPath: string, vaultBasePath: string, currentFile?: TFile): Promise { + // Decode the URL-encoded sanitized path back to normal characters + const decodedPath = decodeURIComponent(sanitizedPath); + + // Try multiple path resolution strategies + const possiblePaths = [ + // Strategy 1: Relative to vault root (standard Obsidian behavior) + path.resolve(vaultBasePath, decodedPath), + // Strategy 2: Relative to current file's directory (for local attachments) + currentFile ? path.resolve(vaultBasePath, path.dirname(currentFile.path), decodedPath) : null + ].filter((p): p is string => p !== null); + + // Try each possible path until we find one that exists + for (const possiblePath of possiblePaths) { + try { + await fs.promises.access(possiblePath); + return possiblePath; + } catch { + // File doesn't exist, continue to next path + } + } + + return null; + } + + /** + * Resolve file path (similar to resolvePdfPath but for generic files) + */ + private async resolveFilePath(sanitizedPath: string, vaultBasePath: string, currentFile?: TFile): Promise { + // Decode the URL-encoded sanitized path back to normal characters + const decodedPath = decodeURIComponent(sanitizedPath); + + // Try multiple path resolution strategies + const possiblePaths = [ + // Strategy 1: Relative to vault root (standard Obsidian behavior) + path.resolve(vaultBasePath, decodedPath), + // Strategy 2: Relative to current file's directory (for local attachments) + currentFile ? path.resolve(vaultBasePath, path.dirname(currentFile.path), decodedPath) : null, + // Strategy 3: Check in attachments folder (common pattern) + path.resolve(vaultBasePath, 'attachments', path.basename(decodedPath)) + ].filter((p): p is string => p !== null); + + // Try each possible path until we find one that exists + for (const possiblePath of possiblePaths) { + try { + await fs.promises.access(possiblePath); + return possiblePath; + } catch { + // File doesn't exist, continue to next path + } + } + + return null; + } + + /** + * Copy converted PDF image to vault temp directory and get relative paths + * @param imagePath Path to the converted image + * @param pdfPath Path to the original PDF + * @param baseName Base name of the PDF + * @param vaultBasePath Base path of the vault + * @returns Object with relative paths for image and PDF + */ + private async copyImageToVaultTemp( + imagePath: string, + pdfPath: string, + baseName: string, + vaultBasePath: string + ): Promise<{ relativeImagePath: string; relativePdfPath: string }> { + // Copy image to vault temp directory for access + const vaultTempImagesDir = path.join(vaultBasePath, this.plugin.manifest.dir!, 'temp-images'); + await fs.promises.mkdir(vaultTempImagesDir, { recursive: true }); + + // Sanitize the basename for use in filename - replace problematic characters + const sanitizedBaseName = baseName + .replace(/[^a-zA-Z0-9\-_]/g, '_') // Replace non-alphanumeric chars with underscore + .replace(/_{2,}/g, '_') // Collapse multiple underscores + .replace(/^_+|_+$/g, ''); // Remove leading/trailing underscores + + const imageFileName = `${sanitizedBaseName}_preview.png`; + const vaultImagePath = path.join(vaultTempImagesDir, imageFileName); + await fs.promises.copyFile(imagePath, vaultImagePath); + + // Get relative paths from vault base + const relativeImagePath = path.relative(vaultBasePath, vaultImagePath); + const relativePdfPath = path.relative(vaultBasePath, pdfPath); + + return { relativeImagePath, relativePdfPath }; + } + + private generatePdfEmbedContent( + relativePdfPath: string, + baseName: string, + relativeImagePath?: string, + errorSuffix?: string, + embedPdfFiles: boolean = true + ): string { + const description = `${baseName}${errorSuffix ? ` ${errorSuffix}` : ''}`; + + const content = []; + + // Always include image preview if available + if (relativeImagePath) { + content.push(`![${baseName} - Page 1](${relativeImagePath})`); + content.push(''); + } + + // Only include PDF embedding and attachment note if embedPdfFiles is true + if (embedPdfFiles) { + content.push('```{=typst}'); + content.push(`#pdf.embed("${relativePdfPath}", description: "${description}", mime-type: "application/pdf")`); + content.push('```'); + content.push(''); + content.push(`*PDF attached: ${description} - check your PDF reader's attachment panel*`); + } + + return content.filter(line => line !== null).join('\n'); + } + + /** + * Generate file embed content with proper Typst pdf.embed syntax + */ + private generateFileEmbedContent( + relativeFilePath: string, + baseName: string, + fileExtension: string, + errorSuffix?: string + ): string { + const description = `${baseName}${errorSuffix ? ` ${errorSuffix}` : ''}`; + const mimeType = this.getMimeTypeFromExtension(fileExtension); + const fileIcon = this.getFileTypeIcon(fileExtension); + + const content = []; + + // Add file embed using Typst's pdf.embed + content.push('```{=typst}'); + content.push(`#pdf.embed("${relativeFilePath}", description: "${description}", mime-type: "${mimeType}")`); + content.push('```'); + content.push(''); + content.push(`*File attached: ${fileIcon} ${description} - check your PDF reader's attachment panel*`); + + return content.filter(line => line !== null).join('\n'); + } + + /** + * Get MIME type from file extension + */ + private getMimeTypeFromExtension(extension: string): string { + const mimeTypes: Record = { + // Office documents + '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + '.xls': 'application/vnd.ms-excel', + '.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation', + '.ppt': 'application/vnd.ms-powerpoint', + '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + '.doc': 'application/msword', + // Open Document Format + '.odt': 'application/vnd.oasis.opendocument.text', + '.ods': 'application/vnd.oasis.opendocument.spreadsheet', + '.odp': 'application/vnd.oasis.opendocument.presentation', + // Archives + '.zip': 'application/zip', + '.rar': 'application/vnd.rar', + '.7z': 'application/x-7z-compressed', + '.tar': 'application/x-tar', + '.gz': 'application/gzip', + '.bz2': 'application/x-bzip2', + // Text/data formats + '.json': 'application/json', + '.xml': 'application/xml', + '.csv': 'text/csv', + '.yaml': 'text/yaml', + '.yml': 'text/yaml', + '.toml': 'text/plain', + '.txt': 'text/plain', + '.md': 'text/markdown', + '.rtf': 'application/rtf', + // Code files + '.js': 'text/javascript', + '.ts': 'text/typescript', + '.py': 'text/x-python', + '.java': 'text/x-java-source', + '.cpp': 'text/x-c++src', + '.c': 'text/x-csrc', + '.h': 'text/x-chdr', + '.css': 'text/css', + '.html': 'text/html', + '.php': 'text/x-php', + // Database files + '.db': 'application/x-sqlite3', + '.sqlite': 'application/x-sqlite3', + '.sql': 'application/sql', + // E-books + '.epub': 'application/epub+zip', + '.mobi': 'application/x-mobipocket-ebook', + // Other formats + '.ics': 'text/calendar', + '.vcf': 'text/vcard', + '.log': 'text/plain' + }; + + return mimeTypes[extension.toLowerCase()] || 'application/octet-stream'; + } + + /** + * Get appropriate icon for file type + */ + private getFileTypeIcon(extension: string): string { + const iconMap: Record = { + // Office documents + '.xlsx': '📊', '.xls': '📊', + '.pptx': '📽️', '.ppt': '📽️', + '.docx': '📄', '.doc': '📄', + // Open Document + '.odt': '📄', '.ods': '📊', '.odp': '📽️', + // Archives + '.zip': '📦', '.rar': '📦', '.7z': '📦', '.tar': '📦', '.gz': '📦', '.bz2': '📦', + // Text/data + '.json': '🗃️', '.xml': '🗃️', '.csv': '📊', '.yaml': '⚙️', '.yml': '⚙️', + '.toml': '⚙️', '.txt': '📄', '.md': '📝', '.rtf': '📄', + // Code files + '.js': '💻', '.ts': '💻', '.py': '🐍', '.java': '☕', '.cpp': '💻', '.c': '💻', + '.h': '💻', '.css': '🎨', '.html': '🌐', '.php': '💻', + // Database + '.db': '🗄️', '.sqlite': '🗄️', '.sql': '🗄️', + // E-books + '.epub': '📖', '.mobi': '📖', + // Other + '.ics': '📅', '.vcf': '👤', '.log': '📋' + }; + + return iconMap[extension.toLowerCase()] || '📎'; + } +} \ No newline at end of file