Merge branch 'hotfix/dependency_fix'

This commit is contained in:
AlexKucera committed 2025-09-08 10:56:27 +02:00
commit c0b45979eb
7 files changed
+286 -42

No files matched your search

+2
View File
@@ -68,3 +68,5 @@ temp-pandoc/*
typst2pdf-icon.afdesign typst2pdf-icon.afdesign
CLAUDE.md CLAUDE.md
repomix-output.xml repomix-output.xml
guidance.md
+51 -9
View File
@@ -70,8 +70,11 @@ export class obsidianTypstPDFExport extends Plugin {
new Notice(`Error extracting templates: ${error.message}`); new Notice(`Error extracting templates: ${error.message}`);
} }
// Initialize components // Initialize components with executable paths from settings
this.converter = new PandocTypstConverter(this); this.converter = new PandocTypstConverter(this, {
pandocPath: this.settings.pandocPath,
typstPath: this.settings.typstPath
});
this.templateManager = new TemplateManager(this); this.templateManager = new TemplateManager(this);
// Register custom icon // Register custom icon
@@ -104,6 +107,42 @@ export class obsidianTypstPDFExport extends Plugin {
this.cacheAvailableFonts(); this.cacheAvailableFonts();
} }
/**
* Resolve an executable path, handling empty settings by falling back to system search
*/
private resolveExecutablePath(userPath: string | undefined, defaultName: string): string {
// If user provided a path and it's not empty, use it
if (userPath && userPath.trim() !== '') {
return userPath;
}
// Try to find the executable using which command
const { spawnSync } = require('child_process');
try {
const augmentedEnv = {
...process.env,
PATH: `/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:${process.env.PATH || ''}`
};
const result = spawnSync('which', [defaultName], {
encoding: 'utf8',
env: augmentedEnv
});
if (result.status === 0 && result.stdout) {
const foundPath = result.stdout.trim();
if (foundPath) {
return foundPath;
}
}
} catch {
// Ignore errors from which command
}
// Fall back to the default name (will be found via PATH if available)
return defaultName;
}
/** /**
* Cache available fonts from typst to a file for quick access * Cache available fonts from typst to a file for quick access
*/ */
@@ -111,7 +150,7 @@ export class obsidianTypstPDFExport extends Plugin {
try { try {
const { spawn } = require('child_process'); const { spawn } = require('child_process');
const typstPath = this.settings.typstPath || 'typst'; const typstPath = this.resolveExecutablePath(this.settings.typstPath, 'typst');
// Use spawn instead of exec for security - arguments passed separately // Use spawn instead of exec for security - arguments passed separately
const stdout = await new Promise<string>((resolve, reject) => { const stdout = await new Promise<string>((resolve, reject) => {
@@ -201,7 +240,8 @@ export class obsidianTypstPDFExport extends Plugin {
// Check if cache is older than 24 hours or typst path changed // Check if cache is older than 24 hours or typst path changed
const isStale = Date.now() - cacheData.timestamp > 24 * 60 * 60 * 1000; const isStale = Date.now() - cacheData.timestamp > 24 * 60 * 60 * 1000;
const pathChanged = cacheData.typstPath !== (this.settings.typstPath || 'typst'); const resolvedTypstPath = this.resolveExecutablePath(this.settings.typstPath, 'typst');
const pathChanged = cacheData.typstPath !== resolvedTypstPath;
if (isStale || pathChanged) { if (isStale || pathChanged) {
// Refresh cache in background // Refresh cache in background
@@ -683,7 +723,8 @@ export class obsidianTypstPDFExport extends Plugin {
const dependencyResult = await DependencyChecker.checkAllDependencies( const dependencyResult = await DependencyChecker.checkAllDependencies(
this.settings.pandocPath, this.settings.pandocPath,
this.settings.typstPath, this.settings.typstPath,
this.settings.executablePaths?.imagemagickPath this.settings.executablePaths?.imagemagickPath,
this.settings.executablePaths?.additionalPaths || []
); );
const formatVersion = (dep: any) => dep.isAvailable ? (dep.version || 'Available') : 'Not found'; const formatVersion = (dep: any) => dep.isAvailable ? (dep.version || 'Available') : 'Not found';
@@ -706,7 +747,8 @@ ${dependencyResult.allAvailable
const missingDeps = DependencyChecker.checkDependenciesSync( const missingDeps = DependencyChecker.checkDependenciesSync(
this.settings.pandocPath, this.settings.pandocPath,
this.settings.typstPath, this.settings.typstPath,
this.settings.executablePaths?.imagemagickPath this.settings.executablePaths?.imagemagickPath,
this.settings.executablePaths?.additionalPaths || []
); );
// Only show notice if dependencies are missing // Only show notice if dependencies are missing
@@ -1395,10 +1437,10 @@ class ObsidianTypstPDFExportSettingTab extends PluginSettingTab {
})); }));
new Setting(containerEl) new Setting(containerEl)
.setName('ImageMagick convert path') .setName('ImageMagick path')
.setDesc('Path to ImageMagick convert executable (leave empty to use system PATH)') .setDesc('Path to ImageMagick executable (leave empty to use system PATH)')
.addText(text => text .addText(text => text
.setPlaceholder('convert') .setPlaceholder('magick')
.setValue(this.plugin.settings.executablePaths.imagemagickPath) .setValue(this.plugin.settings.executablePaths.imagemagickPath)
.onChange(async (value) => { .onChange(async (value) => {
if (!SecurityUtils.validateExecutablePath(value)) { if (!SecurityUtils.validateExecutablePath(value)) {
+39 -6
View File
@@ -277,11 +277,8 @@ export class PandocTypstConverter {
args.push('--from', 'markdown-smart'); args.push('--from', 'markdown-smart');
// Set PDF engine to Typst (use configured path if available) // Set PDF engine to Typst (use configured path if available)
if (this.pandocOptions.typstPath) { const typstPath = this.resolveExecutablePath(this.pandocOptions.typstPath, 'typst');
args.push(`--pdf-engine=${this.pandocOptions.typstPath}`); args.push(`--pdf-engine=${typstPath}`);
} else {
args.push('--pdf-engine=typst');
}
// Enable standalone mode (required for PDF output) // Enable standalone mode (required for PDF output)
args.push('--standalone'); args.push('--standalone');
@@ -549,12 +546,48 @@ export class PandocTypstConverter {
return args; return args;
} }
/**
* Resolve an executable path, handling empty settings by falling back to system search
*/
private resolveExecutablePath(userPath: string | undefined, defaultName: string): string {
// If user provided a path and it's not empty, use it
if (userPath && userPath.trim() !== '') {
return userPath;
}
// Try to find the executable using which command
const { spawnSync } = require('child_process');
try {
const augmentedEnv = {
...process.env,
PATH: `/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:${process.env.PATH || ''}`
};
const result = spawnSync('which', [defaultName], {
encoding: 'utf8',
env: augmentedEnv
});
if (result.status === 0 && result.stdout) {
const foundPath = result.stdout.trim();
if (foundPath) {
return foundPath;
}
}
} catch {
// Ignore errors from which command
}
// Fall back to the default name (will be found via PATH if available)
return defaultName;
}
/** /**
* Execute pandoc process with the given arguments * Execute pandoc process with the given arguments
*/ */
private async executePandoc(args: string[], progressCallback?: ProgressCallback): Promise<ConversionResult> { private async executePandoc(args: string[], progressCallback?: ProgressCallback): Promise<ConversionResult> {
return new Promise((resolve) => { return new Promise((resolve) => {
const pandocPath = this.pandocOptions.pandocPath || 'pandoc'; const pandocPath = this.resolveExecutablePath(this.pandocOptions.pandocPath, 'pandoc');
const timeout = this.pandocOptions.timeout || 60000; const timeout = this.pandocOptions.timeout || 60000;
// Log the exact command being executed for debugging // Log the exact command being executed for debugging
+13 -4
View File
@@ -180,11 +180,21 @@ export class PdfToImageConverter {
const additionalPaths = this.plugin?.settings?.executablePaths?.additionalPaths || const additionalPaths = this.plugin?.settings?.executablePaths?.additionalPaths ||
['/opt/homebrew/bin', '/usr/local/bin', '/usr/bin']; ['/opt/homebrew/bin', '/usr/local/bin', '/usr/bin'];
// Ensure Node.js paths are included for pdf2img execution
const nodePaths = [
'/usr/local/bin', // Common Node.js installation
'/opt/homebrew/bin', // Homebrew on macOS
'/usr/bin', // System Node.js
'/usr/local/node/bin' // Alternative Node.js location
];
const env = { const env = {
...process.env, ...process.env,
PATH: process.env.PATH + (additionalPaths.length > 0 PATH: [
? ':' + additionalPaths.join(':') process.env.PATH,
: '') ...nodePaths,
...additionalPaths
].filter(Boolean).join(':')
}; };
const result = await execAsync(cliCommand, { const result = await execAsync(cliCommand, {
@@ -263,7 +273,6 @@ export class PdfToImageConverter {
// Use ImageMagick to convert PNG to JPEG // Use ImageMagick to convert PNG to JPEG
const convertProcess = spawn('magick', [ const convertProcess = spawn('magick', [
'convert',
actualOutputPath, actualOutputPath,
'-quality', opts.quality.toString(), '-quality', opts.quality.toString(),
finalOutputPath finalOutputPath
+156 -14
View File
@@ -21,24 +21,112 @@ export interface DependencyCheckResult {
export class DependencyChecker { export class DependencyChecker {
/** /**
* Get augmented PATH with common binary locations * Get augmented PATH with common binary locations and additional paths
*/ */
private static getAugmentedPath(): string { private static getAugmentedPath(additionalPaths: string[] = []): string {
const homeDir = process.env.HOME || process.env.USERPROFILE || ''; const homeDir = process.env.HOME || process.env.USERPROFILE || '';
const commonPaths = DEPENDENCY_CONSTANTS.COMMON_PATHS.map(p => homeDir + p);
return `${process.env.PATH}:${commonPaths.join(':')}`; // Build default system paths - always included regardless of user settings
const homeRelativePaths = DEPENDENCY_CONSTANTS.COMMON_PATHS.HOME_RELATIVE.map(p => homeDir + p);
const absolutePaths = DEPENDENCY_CONSTANTS.COMMON_PATHS.ABSOLUTE;
const defaultSystemPaths = [...homeRelativePaths, ...absolutePaths];
// Combine default system paths with user-provided additional paths
const allAdditionalPaths = [...defaultSystemPaths, ...additionalPaths];
return `${process.env.PATH}:${allAdditionalPaths.join(':')}`;
} }
/** /**
* Get augmented environment with extended PATH * Get augmented environment with extended PATH
*/ */
private static getAugmentedEnv(): NodeJS.ProcessEnv { private static getAugmentedEnv(additionalPaths: string[] = []): NodeJS.ProcessEnv {
return { return {
...process.env, ...process.env,
PATH: this.getAugmentedPath() PATH: this.getAugmentedPath(additionalPaths)
}; };
} }
/**
* Try to find an executable using which command
*/
private static async findExecutableWithWhich(executableName: string, additionalPaths: string[] = []): Promise<string | null> {
console.log(`[DependencyChecker] findExecutableWithWhich: searching for "${executableName}"`);
const { spawn } = require('child_process');
try {
const stdout = await new Promise<string>((resolve, reject) => {
const env = this.getAugmentedEnv(additionalPaths);
console.log(`[DependencyChecker] findExecutableWithWhich: using PATH="${env.PATH}"`);
const whichProcess = spawn('which', [executableName], {
stdio: ['pipe', 'pipe', 'pipe'],
env: env
});
let output = '';
let error = '';
whichProcess.stdout?.on('data', (data: Buffer) => {
output += data.toString();
});
whichProcess.stderr?.on('data', (data: Buffer) => {
error += data.toString();
});
whichProcess.on('close', (code: number | null) => {
console.log(`[DependencyChecker] which ${executableName} exited with code ${code}, stdout: "${output.trim()}", stderr: "${error.trim()}"`);
if (code === 0) {
resolve(output);
} else {
reject(new Error(`which command failed with code ${code}: ${error}`));
}
});
whichProcess.on('error', (err: Error) => {
console.log(`[DependencyChecker] which ${executableName} spawn error:`, err.message);
reject(new Error(`Failed to spawn which process: ${err.message}`));
});
});
const foundPath = stdout.trim();
console.log(`[DependencyChecker] findExecutableWithWhich result: "${foundPath}"`);
return foundPath || null;
} catch (error) {
console.log(`[DependencyChecker] findExecutableWithWhich caught error:`, error.message);
return null;
}
}
/**
* Resolve the actual executable path, handling empty/undefined settings
*/
private static async resolveExecutablePath(userPath: string | undefined, defaultName: string, additionalPaths: string[] = []): Promise<string> {
console.log(`[DependencyChecker] 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(`[DependencyChecker] 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(`[DependencyChecker] ASYNC Searching for: ${searchName}`);
// Try to find the executable using which command
const foundPath = await this.findExecutableWithWhich(searchName, additionalPaths);
if (foundPath) {
console.log(`[DependencyChecker] ASYNC Found via which: ${foundPath}`);
return foundPath;
}
// Fall back to the search name (will be found via PATH if available)
console.log(`[DependencyChecker] ASYNC Falling back to search name: ${searchName}`);
return searchName;
}
/** /**
* Check if a dependency is available and get its version * Check if a dependency is available and get its version
*/ */
@@ -101,6 +189,46 @@ export class DependencyChecker {
} }
} }
/**
* Synchronous version of resolving executable path
*/
private static resolveExecutablePathSync(userPath: string | undefined, defaultName: string, additionalPaths: string[] = []): string {
console.log(`[DependencyChecker] 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(`[DependencyChecker] 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(`[DependencyChecker] SYNC Searching for: ${searchName}`);
// Try to find the executable using which command synchronously
const { spawnSync } = require('child_process');
try {
const result = spawnSync('which', [searchName], {
encoding: 'utf8',
env: this.getAugmentedEnv(additionalPaths)
});
if (result.status === 0 && result.stdout) {
const foundPath = result.stdout.trim();
if (foundPath) {
console.log(`[DependencyChecker] SYNC Found via which: ${foundPath}`);
return foundPath;
}
}
} catch {
// Ignore errors from which command
}
// Fall back to the search name (will be found via PATH if available)
console.log(`[DependencyChecker] SYNC Falling back to search name: ${searchName}`);
return searchName;
}
/** /**
* Check if a dependency is available (synchronous version for startup) * Check if a dependency is available (synchronous version for startup)
*/ */
@@ -124,11 +252,19 @@ export class DependencyChecker {
public static async checkAllDependencies( public static async checkAllDependencies(
pandocPath?: string, pandocPath?: string,
typstPath?: string, typstPath?: string,
imagemagickPath?: string imagemagickPath?: string,
additionalPaths: string[] = []
): Promise<DependencyCheckResult> { ): Promise<DependencyCheckResult> {
const pandocExec = pandocPath || DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.pandoc; console.log(`[DependencyChecker] checkAllDependencies called with:`, { pandocPath, typstPath, imagemagickPath, additionalPaths });
const typstExec = typstPath || DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.typst;
const imagemagickExec = imagemagickPath || DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.imagemagick; // Resolve actual executable paths, handling empty settings
const [pandocExec, typstExec, imagemagickExec] = await Promise.all([
this.resolveExecutablePath(pandocPath, DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.pandoc, additionalPaths),
this.resolveExecutablePath(typstPath, DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.typst, additionalPaths),
this.resolveExecutablePath(imagemagickPath, DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.imagemagick, additionalPaths)
]);
console.log(`[DependencyChecker] Resolved paths:`, { pandocExec, typstExec, imagemagickExec });
const [pandocInfo, typstInfo, imagemagickInfo] = await Promise.all([ const [pandocInfo, typstInfo, imagemagickInfo] = await Promise.all([
this.checkDependency('Pandoc', pandocExec, '--version', /pandoc\s+([\d.]+)/), this.checkDependency('Pandoc', pandocExec, '--version', /pandoc\s+([\d.]+)/),
@@ -155,11 +291,17 @@ export class DependencyChecker {
public static checkDependenciesSync( public static checkDependenciesSync(
pandocPath?: string, pandocPath?: string,
typstPath?: string, typstPath?: string,
imagemagickPath?: string imagemagickPath?: string,
additionalPaths: string[] = []
): string[] { ): string[] {
const pandocExec = pandocPath || DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.pandoc; console.log(`[DependencyChecker] checkDependenciesSync called with:`, { pandocPath, typstPath, imagemagickPath, additionalPaths });
const typstExec = typstPath || DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.typst;
const imagemagickExec = imagemagickPath || DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.imagemagick; // Resolve actual executable paths, handling empty settings
const pandocExec = this.resolveExecutablePathSync(pandocPath, DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.pandoc, additionalPaths);
const typstExec = this.resolveExecutablePathSync(typstPath, DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.typst, additionalPaths);
const imagemagickExec = this.resolveExecutablePathSync(imagemagickPath, DEPENDENCY_CONSTANTS.DEFAULT_EXECUTABLES.imagemagick, additionalPaths);
console.log(`[DependencyChecker] Resolved paths SYNC:`, { pandocExec, typstExec, imagemagickExec });
const missingDeps: string[] = []; const missingDeps: string[] = [];
+24 -8
View File
@@ -49,16 +49,32 @@ export const DEPENDENCY_CONSTANTS = {
DEFAULT_EXECUTABLES: { DEFAULT_EXECUTABLES: {
pandoc: 'pandoc', pandoc: 'pandoc',
typst: 'typst', typst: 'typst',
imagemagick: 'convert' imagemagick: 'magick'
}, },
/** /**
* Common paths to augment PATH with * Common paths to augment PATH with - these are always checked regardless of user settings
*/ */
COMMON_PATHS: [ COMMON_PATHS: {
'/.local/bin', /**
'/.cargo/bin', * Paths relative to home directory (will have HOME prepended)
'/usr/local/bin', */
'/opt/homebrew/bin' HOME_RELATIVE: [
] '/.local/bin',
'/.cargo/bin',
'/go/bin',
'/.npm-global/bin'
],
/**
* System-wide absolute paths (used as-is)
*/
ABSOLUTE: [
'/usr/local/bin',
'/opt/homebrew/bin',
'/usr/bin',
'/bin',
'/opt/local/bin',
'/snap/bin'
]
}
} as const; } as const;
+1 -1
View File
@@ -19,7 +19,7 @@ export interface obsidianTypstPDFExportSettings {
/** Executable paths configuration */ /** Executable paths configuration */
executablePaths: { executablePaths: {
/** Path to ImageMagick convert command (optional, uses PATH if not specified) */ /** Path to ImageMagick command (optional, uses PATH if not specified) */
imagemagickPath: string; imagemagickPath: string;
/** Additional paths to append to PATH environment variable */ /** Additional paths to append to PATH environment variable */
additionalPaths: string[]; additionalPaths: string[];